{"text": "```\nimport numpy as np\nimport scipy as sp\nimport scipy.signal\nimport matplotlib\nimport matplotlib.pyplot as plt\n%matplotlib inline\n```\n\nShannon's sampling theorem tells us the signal $x(t)$ can be exactly and uniquely reconstructed for all time from its samples $x(nT_S)$ by bandlimited interpolation:\n\n\\begin{equation}\n\\hat x(t) = \\sum_{n=-\\infty}^{+\\infty} x(nT_S)h_S(t-nT_S) = (x \\ast h_S)(t) \\equiv x(t)\n\\end{equation}\n\nwhere\n$$\nh_S(t) = \\text{sinc}(tf_S)\n$$\n\n\n```\nTs = 1\nFs = 1/Ts\n\nres = 10 # resolution parameter to fake continuous time\nsc_zc = 10 # number of uni-directional zero crossing taken into account\n\nt = np.arange(-sc_zc*Ts,+sc_zc*Ts,Ts/res)\nh_S = np.sinc(t*Fs)\n\nfig, ax = plt.subplots(1, 1, figsize=(13,4))\nax.plot(t, h_S)\n\nax.spines['top'].set_visible(False)\nax.spines['right'].set_visible(False)\nax.spines['left'].set_position('zero')\nax.spines['bottom'].set_position('zero')\n\nn = np.arange(-10,10,1)\nax.set_xticks(Ts * n)\nlabels = [\"$%d T_S$\" % y for y in n[0:]]\nlabels[10] = \"0\"\nax.set_xticklabels(labels, fontsize=12)\nax.grid()\nax.set_xlim([-7, 7]);\n\n```\n\nThis function is the impulse response of the ideal LPF with cut off frequency set at $F_S/2$. The convolution can be interpreted as a superpositon of shifted and scaled $\\text{sinc}$ functions.\n\n\n```\nTs = 1\nFs = 1/Ts\nres = 10 # resolution parameter to fake continuous time\nsc_zc = 10 # number of uni-directional zero crossing taken into account\n\nt = np.arange(-sc_zc*Ts,+sc_zc*Ts,Ts/res)\nh_S = np.sinc(t*Fs)\n\n# my discrete signal\nx = np.array([0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0]) \n# x = np.sin(np.arange(10)*2*np.pi/10)\n# x = np.array([0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0]) \n\n# interpolation\nsampled_t = np.arange(0,len(x)*Ts,Ts)\ncontinuous_t = np.arange(0,(len(x)-1)*Ts + Ts/res,Ts/res)\nx_interp = np.zeros((len(continuous_t),))\nx_interp[0::res] = x\n\n#convolve\nx_hat = np.convolve(x_interp, h_S)\nx_hat = x_hat[(len(h_S)/2):-len(h_S)/2+1]\n\n# plot\nfig, axes = plt.subplots(1, 2, figsize=(16,6))\naxes[0].stem(sampled_t, x)\naxes[1].plot(continuous_t, x_hat)\n\nfor ax in axes:\n ax.spines['top'].set_visible(False)\n ax.spines['right'].set_visible(False)\n ax.spines['left'].set_position('zero')\n ax.spines['bottom'].set_position('zero')\n\n n = np.arange(0,len(x),1)\n ax.set_xticks(Ts * n)\n labels = [\"$%d T_S$\" % y for y in n[0:]]\n labels[0] = \"0\"\n ax.set_xticklabels(labels, fontsize=12)\n ax.grid()\n ax.set_xlim([0, continuous_t[-1]+Ts]);\n ax.set_ylim([np.min((0,np.min((np.min(x),np.min(x_hat)))))-0.1,np.max((np.max(x),np.max(x_hat)))+0.1])\n```\n", "meta": {"hexsha": "155df34082123a3e48c9efb9c5cd3a783d3b8df9", "size": 61296, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "audio/BandlimitedInterpolation.ipynb", "max_stars_repo_name": "brunodigiorgi/ipn-notes", "max_stars_repo_head_hexsha": "c8840a45989f25442c1d800ef8acdf8c630cdafc", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-03-07T13:46:17.000Z", "max_stars_repo_stars_event_max_datetime": "2018-03-07T13:46:17.000Z", "max_issues_repo_path": "audio/BandlimitedInterpolation.ipynb", "max_issues_repo_name": "brunodigiorgi/ipn-notes", "max_issues_repo_head_hexsha": "c8840a45989f25442c1d800ef8acdf8c630cdafc", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "audio/BandlimitedInterpolation.ipynb", "max_forks_repo_name": "brunodigiorgi/ipn-notes", "max_forks_repo_head_hexsha": "c8840a45989f25442c1d800ef8acdf8c630cdafc", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 387.9493670886, "max_line_length": 31157, "alphanum_fraction": 0.9168787523, "converted": true, "num_tokens": 891, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9724147169737826, "lm_q2_score": 0.9252299550303293, "lm_q1q2_score": 0.8997072248564832}} {"text": "## Linear Algebra\n\nLinear algebra refers to the study of linear relationships. In this class, we will cover some basic concepts of linear algebra that are needed to understand some more advanced and *practical* concepts and definitions. If you are interested in the concepts related to linear algebra and application, there is an excellent online series that covers these topics in detail \n\nhttps://github.com/fastai/numerical-linear-algebra\n\n\nLinear algebra is a fundamental component of machine learning, so if you are interested in using machine learning in the future go and check that class. \n\n\n### Vectors\n\nA vector is a collection of numbers. Vectors can be **row vectors** or **column vectors** depending on their orientation. In general, you can assume that a vector is a **column vector** unless otherwise stated. \n\n\n\n```python\nimport numpy as np\nvector_row = np.array([[1, -5, 3, 2, 4]])\nvector_column = np.array([[1], \n [2], \n [3], \n [4]])\nprint(vector_row.shape)\nprint(vector_column.shape)\n```\n\n (1, 5)\n (4, 1)\n\n\nThe transpose ($T$) of a vector is an operation that transform a column vector into a row vector and a row vector into a column vector. If $v$ is a vector, then $v^{T}$ is the transpose.\n\n\n```python\nvector_row, vector_row.T\n```\n\n\n\n\n (array([[ 1, -5, 3, 2, 4]]),\n array([[ 1],\n [-5],\n [ 3],\n [ 2],\n [ 4]]))\n\n\n\nThe norm of a vector is a measure of its lenght. There are many ways to measure lenght and you can use different definitions depending on the application. The most common norm is the $L_2$ norm, if $v$ is a vector, then the $L_2$ norm ($\\Vert v \\Vert_{2}$) is \n\n$$\n\\Vert v \\Vert_{2} = \\sqrt{\\sum_i v_i^2}\n$$\n\nThis is also known as the Euclidian norm. \n\nOthers well known norms are the $L_1$ norm (or Manhattan Distance), and the $L_\\infty$ norm (or infinity norm) equal to the maximum absolut value of the vector \n\n\n```python\nfrom numpy.linalg import norm\nnew_vector = vector_row.T\nnorm_1 = norm(new_vector, 1)\nnorm_2 = norm(new_vector, 2)\nnorm_inf = norm(new_vector, np.inf)\nprint('L_1 is: %.1f'%norm_1)\nprint('L_2 is: %.1f'%norm_2)\nprint('L_inf is: %.1f'%norm_inf)\n```\n\n L_1 is: 15.0\n L_2 is: 7.4\n L_inf is: 5.0\n\n\nThe **dot product** of two vectors is the sum of the product of the respective elements in each vector and is denoted by $\\cdot$. If $v$ and $w$ are vectors, then the dot product is defined as \n$$\nd = v \\cdot w= \\sum_{i = 1}^{n} v_iw_i\n$$\n\nalternatively, the dot product can be computed as \n\n$$\nv \\cdot w = \\Vert v \\Vert_{2} \\Vert w \\Vert_{2} \\cos{\\theta}\n$$\n\nwhere $\\theta$ is the angle between the vectors. In the same way, the angle between two vector can be computed as \n\n$$\n\\theta = cos^{-1}\\left[\\frac{v \\cdot w }{\\Vert v \\Vert_{2} \\Vert w \\Vert_{2}}\\right]\n$$\n\n\n```python\n#lets take two vectors that are on the same direction but have different lenghts \nfrom numpy import arccos, dot\nv = np.array([[1,2]])\nw = np.array([[5,10]])\ntheta = arccos(v.dot(w.T)/(norm(v)*norm(w)))\ntheta*(180/pi) #arcos return gradients, we are convering to degrees\n```\n\n\n\n\n array([[8.53773646e-07]])\n\n\n\n\n```python\n#lets take two vectors that are on opposite directions \nfrom numpy import arccos, dot, pi\nv = np.array([[1,2]])\nw = np.array([[-1,-2]])\ntheta = arccos(v.dot(w.T)/(norm(v)*norm(w)))\ntheta*(180/pi) #arcos return gradients, we are convering to degrees \n```\n\n\n\n\n array([[179.99999879]])\n\n\n\n\n```python\n#lets take two vectors that are on orthogonal to eachother \nfrom numpy import arccos, dot, pi\nv = np.array([[1,1]])\nw = np.array([[-1,1]])\ntheta = arccos(v.dot(w.T)/(norm(v)*norm(w)))\ntheta*(180/pi) #arcos return gradients, we are convering to degrees \n```\n\n\n\n\n array([[90.]])\n\n\n\nThe **cross product** between two vectors, $v$ and $w$, is written $v\\times w$. It is defined by \n\n$$\nv \\times w = \\Vert v \\Vert_{2}\\Vert w \\Vert_{2}\\sin{(\\theta)} \n$$\n\nwhere $θ$ is the angle between the $v$ and $w$.\n\nThe geometric interpretation of the cross product is a vector perpendicular to both $v$ and $w$ with length (as measured by $L_2$) equal to the area enclosed by the parallelogram created by the two vectors.\n\n\n\n\n```python\nv = np.array([[0, 2, 0]])\nw = np.array([[3, 0, 0]])\ncross = np.cross(v, w)\nprint(cross)\n```\n\n [[ 0 0 -6]]\n\n\n\n```python\narccos(v.dot(cross.T)/(norm(v)*norm(cross)))*(180/pi)\n```\n\n\n\n\n array([[90.]])\n\n\n\n\n```python\narccos(w.dot(cross.T)/(norm(w)*norm(cross)))*(180/pi)\n```\n\n\n\n\n array([[90.]])\n\n\n\n### Matrices \n\nAn $n \\times m $ matrix is a rectangular table of numbers consisting of $m$ rows and $n$ columns.\n\nThe norm of a matrix can be consider as a kind of vector norm by alingming the $n * m$ elements of the matrix into a single vector\n$$\n\\Vert M \\Vert_{p} = \\sqrt[p]{(\\sum_i^m \\sum_j^n |a_{ij}|^p)}\n$$\n\nwhere $p$ defines the norm order ($p=0, 1, 2,...$)\n\n\n**Matrix multiplication** between two matrices, $P$ and $Q$, is defined when $P$ is an $m \\timed p$ matrix and $Q$ is a $p \\times n$ matrix. The result of $M=PQ$ is a matrix $M$ that is $m \\times n$. The dimension with size $p$ is called the inner matrix dimension, and the inner matrix dimensions must match (i.e., the number of columns in $P$ and the number of rows in $Q$ must be the same) for matrix multiplication. The dimensions $m$ and $n$ are called the outer matrix dimensions. Formally, $M=PQ$ is defined as\n$$\nM_{ij} = \\sum_{k=1}^p P_{ik}Q_{kj}\n$$\n\n\n\n```python\nP = np.array([[1, 7], [2, 3], [5, 0]])\nQ = np.array([[2, 6, 3, 1], [1, 2, 3, 4]])\nprint(P)\nprint(f'The dimensions of P are: {P.shape}')\nprint(Q, Q.shape)\nprint(f'The dimensions of Q are: {Q.shape}')\nprint(np.dot(P, Q))\nprint(f'The dimensions of PxQ are: {np.dot(P, Q).shape}')\n```\n\n [[1 7]\n [2 3]\n [5 0]]\n The dimensions of P are: (3, 2)\n [[2 6 3 1]\n [1 2 3 4]] (2, 4)\n The dimensions of Q are: (2, 4)\n [[ 9 20 24 29]\n [ 7 18 15 14]\n [10 30 15 5]]\n The dimensions of PxQ are: (3, 4)\n\n\n\n```python\n#what will happend here? \nnp.dot(P, Q)\n```\n\nThe **determinant** is an important property of square matrices (same number of rows and columns). The determinant is denoted by $\\det(M)$ or $|M|$.\n\nIn the case of $2 \\times 2$ matrices, the determinant is \n$$\n\\begin{split}\n|M| = \\begin{bmatrix}\na & b \\\\\nc & d\\\\\n\\end{bmatrix} = ad - bc\\end{split}\n$$\n\n\nIn the case of $3 \\times 3$ matrices, the determinant is \n$$\n\\begin{split}\n\\begin{eqnarray*}\n|M| = \\begin{bmatrix}\na & b & c \\\\\nd & e & f \\\\\ng & h & i \\\\\n\\end{bmatrix} & = & a\\begin{bmatrix}\n\\Box &\\Box &\\Box \\\\\n\\Box & e & f \\\\\n\\Box & h & i \\\\\n\\end{bmatrix} - b\\begin{bmatrix}\n\\Box &\\Box &\\Box \\\\\nd & \\Box & f \\\\\ng & \\Box & i \\\\\n\\end{bmatrix}+c\\begin{bmatrix}\n\\Box &\\Box &\\Box \\\\\nd & e & \\Box \\\\\ng & h & \\Box \\\\\n\\end{bmatrix} \\\\\n&&\\\\\n& = & a\\begin{bmatrix}\ne & f \\\\\nh & i \\\\\n\\end{bmatrix} - b\\begin{bmatrix}\nd & f \\\\\ng & i \\\\\n\\end{bmatrix}+c\\begin{bmatrix}\nd & e \\\\\ng & h \\\\\n\\end{bmatrix} \\\\ \n&&\\\\\n& = & aei + bfg + cdh - ceg - bdi - afh\n\\end{eqnarray*}\\end{split}\n$$\n\n\nComputing the determinant or larger matrices is cumbersome. However, the process can be easily automated and always reduced to computing the determinant of $2 \\time 2$ matrices. Numpy includes an efficient method to compute the determinant of a matrix\n\n\n```python\nfrom numpy.linalg import det\n\nM = np.array([[0,2,1,3], \n [3,2,8,1], \n [1,0,0,3],\n [0,3,2,1]])\nprint(f'M: {M}')\n\nprint(f'Determinant: {det(M):0.2f}') #note that the :0.2f limits the number of decimals printed!\n\n```\n\n M: [[0 2 1 3]\n [3 2 8 1]\n [1 0 0 3]\n [0 3 2 1]]\n Determinant: -38.00\n\n\nThe inverse of a square matrix $M$ is a matrix of the same size, $N$, such that $M \\bullet N=I$, Where $I$ is a matrix with only ones in its diagonal (unity matrix). The inverse of a matrix $M$ is denoted as $M^{-1}$. For a $2 \\times 2$ matrix, the inverse is defined as \n\n$$\n\\begin{split}\nM^{-1} = \\begin{bmatrix}\na & b \\\\\nc & d\\\\\n\\end{bmatrix}^{-1} = \\frac{1}{|M|}\\begin{bmatrix}\nd & -b \\\\\n-c & a\\\\\n\\end{bmatrix}\\end{split}\n$$\n\ncalculating the inverse of a matrix is a complex process; however, it is an important step in many calculations and several *easier* approaches have been developed.\n\nif the determinant of a matrix is zero, then the matrix doesn't have an inverse. \n\n\n```python\nfrom numpy.linalg import inv\n\nM = np.array([[0,2,1,3], \n [3,2,8,1], \n [1,0,0,3],\n [0,3,2,1]])\nprint(f'M: {M}')\n\nprint(f'Inverse: {inv(M)}') #note that the :0.2f limits the number of decimals printed!\n\nprint(f'M x inv(M) = {np.dot(M,inv(M))}')\n\n```\n\n M: [[0 2 1 3]\n [3 2 8 1]\n [1 0 0 3]\n [0 3 2 1]]\n Inverse: [[-1.57894737 -0.07894737 1.23684211 1.10526316]\n [-0.63157895 -0.13157895 0.39473684 0.84210526]\n [ 0.68421053 0.18421053 -0.55263158 -0.57894737]\n [ 0.52631579 0.02631579 -0.07894737 -0.36842105]]\n M x inv(M) = [[ 1.00000000e+00 -3.46944695e-18 5.55111512e-17 1.11022302e-16]\n [ 0.00000000e+00 1.00000000e+00 4.99600361e-16 -1.11022302e-16]\n [ 2.22044605e-16 5.20417043e-17 1.00000000e+00 -3.33066907e-16]\n [ 0.00000000e+00 1.73472348e-17 5.55111512e-17 1.00000000e+00]]\n\n\nA matrix that is close to being singular (i.e., the determinant is close to 0) is called **ill-conditioned**. Although ill-conditioned matrices have inverses, they are problematic numerically in the same way that dividing a number by a very, very small number is problematic. \nThe **condition number** is a measure of how ill-conditioned a matrix is, and it can be computed using Numpy’s function cond from linalg. The higher the condition number, the closer the matrix is to being singular.\n\nThe **rank** of an $m \\times n$ matrix $A$ is the number of linearly independent columns or rows of $A$ (that is, you cannot write a row or column as a linear combination of other rows or columns), and is denoted by **rank(A)**. It can be shown that the number of linearly independent rows is always equal to the number of linearly independent columns for any matrix. A matrix is called full rank. if **rank (A)=min(m,n)**. The matrix, $A$, is also full rank if all of its columns are linearly independent.\n\n\n\n```python\nfrom numpy.linalg import cond, matrix_rank\n\nA = np.array([[1,1,0],\n [0,1,0],\n [1,0,1]])\n\nprint(f'Condition number: {cond(A)}')\nprint(f'Rank: {matrix_rank(A)}')\n```\n\n Condition number: 4.048917339522305\n Rank: 3\n\n\nif you append a new columns (or row) to a matrix, the rank will increase if the new columns add new information (that is, the new column cannot be explained by a linear combinantion of existing columns)\n\n\n```python\ny = np.array([[1], [2], [1]])\nA_y = np.concatenate((A, y), axis = 1)\nprint(f'Augmented matrix: \\n {A_y}')\nprint(f'Rank of augmented matrix: {matrix_rank(A_y)} ')\n```\n\n Augmented matrix: \n [[1 1 0 1]\n [0 1 0 2]\n [1 0 1 1]]\n Rank of augmented matrix: 3 \n\n\n### Linear Transformations \n\nYou can transform a vector by applying linear operations to it, for examples \n\n- Sum with a scalar \n- Multiplication with a scalar\n- Sum with another vector\n- Multiplication with another vector \n- Multiplication with a matrix \n\nThe last operation is one of the most important operation in linear algebra and has many applications. \n\nExample, **Vector Rotation**\n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\nV = np.array([[3],[1]])\norigin = np.array([[0], [0]]) # origin point\n\nplt.quiver(0,0,*V, color=['r'], scale=21)\nplt.plot([-1,1],[0,0], lw=0.5, color = 'k')\nplt.plot([0,0],[-1,1], lw=0.5, color = 'k')\nplt.show()\n```\n\nTo rotate a vector by an angle $\\theta$, you have to multiply it by a rotation matrix given by \n$$\nR = \\begin{bmatrix}\n\\cos(\\theta) & -\\sin(\\theta) \\\\\n\\sin(\\theta) & \\cos(\\theta)\n\\end{bmatrix}\n$$\n\n\n```python\n#Rotate the vector by 45 degress\ntheta = 45 * (np.pi/180)\nRot_Matrix = np.array([[np.cos(theta), -np.sin(theta)],[np.sin(theta), np.cos(theta)]])\n\nrot_V = Rot_Matrix @ V\n\n#(2x2) @ (2x1) -> (2x1)\nplt.quiver(0,0,*V, color=['r'], scale=21)\nplt.quiver(0,0,*rot_V, color=['tab:green'], scale=21)\nplt.plot([-1,1],[0,0], lw=0.5, color = 'k')\nplt.plot([0,0],[-1,1], lw=0.5, color = 'k')\nplt.show()\n```\n\n## Exercise \nTry it yourself, rotate the vector\n$$\nR = \\begin{bmatrix}\n5 \\\\\n3\n\\end{bmatrix}\n$$\n\nby 50 degrees. Verify the result of the operation\n\n\n```python\nimport numpy as np\n\ndef rot_matrix(theta):\n \n return np.array([[np.cos(theta), -np.sin(theta)],[np.sin(theta), np.cos(theta)]])\n\na = np.array([[5,3]]).T\nangle = 50 * (np.pi/180)\nR = rot_matrix(angle)\n\na_rot = R.dot(a)\n\nprint(np.arccos(((a.T).dot(a_rot))/(np.linalg.norm(a)*np.linalg.norm(a_rot)))*(180/np.pi))\n```\n\n [[50.]]\n\n\nLinear transformation are **inversible**, you can recover the original vector by multiplying by the inverse of the rotation matrix\n\n\n\n```python\nV = np.array([[3],[1]])\n\ntheta = 45 * (np.pi/180)\nRot_Matrix = np.array([[np.cos(theta), -np.sin(theta)],[np.sin(theta), np.cos(theta)]])\n\nrot_V = Rot_Matrix @ V\n\nrec_V = np.linalg.inv(Rot_Matrix)@rot_V\n\nprint(f'The original Vector is: \\n {V}')\nprint(f'The recovered Vector is : \\n {rec_V}')\n```\n\n The original Vector is: \n [[3]\n [1]]\n The recovered Vector is : \n [[3.]\n [1.]]\n\n\n### System of linear equations\n\nA system of linear equations is a set of linear equations that share the same variables. Consider the following system of linear equations:\n\n$$\n\\begin{eqnarray*}\n\\begin{array}{rcrcccccrcc}\na_{1,1} x_1 &+& a_{1,2} x_2 &+& {\\ldots}& +& a_{1,n-1} x_{n-1} &+&a_{1,n} x_n &=& y_1,\\\\\na_{2,1} x_1 &+& a_{2,2} x_2 &+&{\\ldots}& +& a_{2,n-1} x_{n-1} &+& a_{2,n} x_n &=& y_2, \\\\\n&&&&{\\ldots} &&{\\ldots}&&&& \\\\\na_{m-1,1}x_1 &+& a_{m-1,2}x_2&+ &{\\ldots}& +& a_{m-1,n-1} x_{n-1} &+& a_{m-1,n} x_n &=& y_{m-1},\\\\\na_{m,1} x_1 &+& a_{m,2}x_2 &+ &{\\ldots}& +& a_{m,n-1} x_{n-1} &+& a_{m,n} x_n &=& y_{m}.\n\\end{array}\n\\end{eqnarray*}$$\n\n\nThe matrix form of a system of linear equations is $\\textbf{A}x = y$ where $\\textbf{A}$ is a m×n matrix, $y$ is a vector, and $x$ is an unknown vector:\n$$\n\\begin{split}\\begin{bmatrix}\na_{1,1} & a_{1,2} & ... & a_{1,n}\\\\\na_{2,1} & a_{2,2} & ... & a_{2,n}\\\\\n... & ... & ... & ... \\\\\na_{m,1} & a_{m,2} & ... & a_{m,n}\n\\end{bmatrix}\\left[\\begin{array}{c} x_1 \\\\x_2 \\\\ ... \\\\x_n \\end{array}\\right] =\n\\left[\\begin{array}{c} y_1 \\\\y_2 \\\\ ... \\\\y_m \\end{array}\\right]\\end{split}\n$$\n\n\nFor example, the system of linear equations \n\n$$\n\\begin{eqnarray*}\n4x + 3y - 5z &=& 2 \\\\\n-2x - 4y + 5z &=& 5 \\\\\n7x + 8y &=& -3 \\\\\nx + 2z &=& 1 \\\\\n9 + y - 6z &=& 6 \\\\\n\\end{eqnarray*}\n$$\n\ncan be written as \n$$\n\\begin{split}\\begin{bmatrix}\n4 & 3 & -5\\\\\n-2 & -4 & 5\\\\\n7 & 8 & 0\\\\\n1 & 0 & 2\\\\\n9 & 1 & -6\n\\end{bmatrix}\\left[\\begin{array}{c} x \\\\y \\\\z \\end{array}\\right] =\n\\left[\\begin{array}{c} 2 \\\\5 \\\\-3 \\\\1 \\\\6 \\end{array}\\right]\\end{split}\n$$\n\n#### Solutions to Systems of Linear Equations\n\nThe objective is to find a set of scalars ($x$, $y$, and $z$) that allow us to write the vector $y$ as a linear combination of the columns of $\\textbf{A}$. \n\nIf the rank of the augmented matriz $[\\textbf{A},y]$ is equal to the rank of $[\\textbf{A}]$, this solution exist. Otherwise, the solution doesn't exists.\n\nMoreover, if $\\textbf{A}$ is not full rank (i.e, the $rank(\\textbf{A})$ is smaller than the number of columns), then not all the columns of $\\textbf{A}$ are independent and the system will have infinite number of solutions. \n\nThere are many methods that can be used to solve a system of linear equations. Most methods were designed to simplify manual calculations, however, we are mostly interested in computer based methods\n1) Direct matrix inversion \nIn this method, we multiply by the inverse of the matrix $\\textbf{A}$ in both sides of the equation \n$$\n\\begin{align}\n\\textbf{A} x &= y \\\\\n\\textbf{A}^{-1}\\textbf{A}x &= \\textbf{A}^{-1} y \\\\\nx &= \\textbf{A}^{-1}y\n\\end{align}\n$$\n\n\n```python\nA = np.array([[8, 8, 0], \n [-2, -4, 5], \n [4, 3, -5] ])\ny = np.array([2, 5, -3])\n\nx = np.linalg.inv(A)@y\nprint(x)\n```\n\n [ 0.75 -0.5 0.9 ]\n\n\n\n```python\n#Verify the results\nprint(f'Ax = {A@x}')\n```\n\n Ax = [ 2. 5. -3.]\n\n\nThat methods works fine unless the matrix $\\textbf{A}$ is close to be singular. In that case, we can use other methods that avoid finding the inverse of the matrix. The most common method is called $LU$ decomposition, , where a matrix $\\textbf{A}$ is expressed as \n$$\n\\textbf{A} = \\textbf{L}\\textbf{U}\n$$\n\nwith $\\textbf{L}$ a lower diagonal matrix and $\\textbf{U}$ a upper diagonal matrix\n\n$$\n\\begin{split}Ax = y \\rightarrow LUx=y\\rightarrow\n\\begin{bmatrix}\nl_{1,1} & 0 & 0 & 0\\\\\nl_{2,1} & l_{2,2} & 0 & 0\\\\\nl_{3,1} & l_{3,2} & l_{3,3} & 0 \\\\\nl_{4,1} & l_{4,2} & l_{4,3} & l_{4,4}\n\\end{bmatrix}\n\\begin{bmatrix}\nu_{1,1} & u_{1,2} & u_{1,3} & u_{1,4}\\\\\n0 & u_{2,2} & u_{2,3} & u_{2,4}\\\\\n0 & 0 & u_{3,3} & u_{3,4} \\\\\n0 & 0 & 0 & u_{4,4}\n\\end{bmatrix}\\left[\\begin{array}{c} x_1 \\\\x_2 \\\\ x_3 \\\\x_4 \\end{array}\\right] =\n\\left[\\begin{array}{c} y_1 \\\\y_2 \\\\ y_3 \\\\y_4 \\end{array}\\right]\\end{split}\n$$\n\nwe can now split this problem into two simpler problems\n$$\n\\begin{split}\n\\begin{bmatrix}\nu_{1,1} & u_{1,2} & u_{1,3} & u_{1,4}\\\\\n0 & u_{2,2} & u_{2,3} & u_{2,4}\\\\\n0 & 0 & u_{3,3} & u_{3,4} \\\\\n0 & 0 & 0 & u_{4,4}\n\\end{bmatrix}\\left[\\begin{array}{c} x_1 \\\\x_2 \\\\ x_3 \\\\x_4 \\end{array}\\right] =\n\\left[\\begin{array}{c} m_1 \\\\m_2 \\\\ m_3 \\\\m_4 \\end{array}\\right]\\end{split}\n$$\n\nand\n\n$$\n\\begin{split}\n\\begin{bmatrix}\nl_{1,1} & 0 & 0 & 0\\\\\nl_{2,1} & l_{2,2} & 0 & 0\\\\\nl_{3,1} & l_{3,2} & l_{3,3} & 0 \\\\\nl_{4,1} & l_{4,2} & l_{4,3} & l_{4,4}\n\\end{bmatrix}\n\\left[\\begin{array}{c} m_1 \\\\m_2 \\\\ m_3 \\\\m_4 \\end{array}\\right] =\n\\left[\\begin{array}{c} y_1 \\\\y_2 \\\\ y_3 \\\\y_4 \\end{array}\\right]\\end{split}\n$$\n\nNote that if $\\textbf{A}$ is full rank, then the matrices $\\textbf{L}$ and $\\textbf{U}$ exist, and its inverse is easy to find and the determinant is equal to the mutiplication of the elements in the diagonal \n\n\n```python\nfrom scipy.linalg import lu #note that we are not using numpy\nA = np.array([[8, 8, 0], \n [-2, -4, 5], \n [4, 3, -5] ])\ny = np.array([2, 5, -3])\n\nP,L,U = lu(A)\nprint(L)\nprint(U)\n```\n\n [[ 1. 0. 0. ]\n [-0.25 1. 0. ]\n [ 0.5 0.5 1. ]]\n [[ 8. 8. 0. ]\n [ 0. -2. 5. ]\n [ 0. 0. -7.5]]\n\n\n\n```python\n#compute m using L and y \nm = np.linalg.inv(L)@y\n```\n\n\n```python\n#compute x using U and m\nx = np.linalg.inv(U)@m\nprint(x)\n```\n\n [ 0.75 -0.5 0.9 ]\n\n\n\n```python\n#Verify the results\nprint(f'Ax = {A@x}')\n```\n\n Ax = [ 2. 5. -3.]\n\n\n\n```python\n#numpy does the same in its own function to solve linear system \nfrom numpy.linalg import solve\n\nx = solve(A,y)\nprint(x)\n```\n\n [ 0.75 -0.5 0.9 ]\n\n", "meta": {"hexsha": "b70211afe93fde3e5139a2354ad681413b21e932", "size": 74860, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Linear_Algebra.ipynb", "max_stars_repo_name": "dguari1/BME3240_2021", "max_stars_repo_head_hexsha": "b069d6e6336f44dcb8d3ef79bbcf5410cde68dcc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-08-28T03:42:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-04T17:14:29.000Z", "max_issues_repo_path": "Linear_Algebra.ipynb", "max_issues_repo_name": "dguari1/BME3240_2021", "max_issues_repo_head_hexsha": "b069d6e6336f44dcb8d3ef79bbcf5410cde68dcc", "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": "Linear_Algebra.ipynb", "max_forks_repo_name": "dguari1/BME3240_2021", "max_forks_repo_head_hexsha": "b069d6e6336f44dcb8d3ef79bbcf5410cde68dcc", "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": 70.6226415094, "max_line_length": 18056, "alphanum_fraction": 0.7688752338, "converted": true, "num_tokens": 6571, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768541530197, "lm_q2_score": 0.9525741217735478, "lm_q1q2_score": 0.8993984376437238}} {"text": "## Calculus\n### limits\n\nNote: for interactive work it is useful to run `init_session()`, which defines some basic symbols\n\n\n```python\nfrom sympy import *\ninit_session()\n%matplotlib inline\n```\n\n IPython console for SymPy 1.3 (Python 3.6.6-64-bit) (ground types: python)\n \n These commands were executed:\n >>> from __future__ import division\n >>> from sympy import *\n >>> x, y, z, t = symbols('x y z t')\n >>> k, m, n = symbols('k m n', integer=True)\n >>> f, g, h = symbols('f g h', cls=Function)\n >>> init_printing()\n \n Documentation can be found at http://docs.sympy.org/1.3/\n \n\n\n\n```python\nlimit(sin(x)/x, x, 0)\n```\n\n\n```python\nlimit(1/x, x, 0)\n```\n\nLimits are from the right by default. It can be changed with `dir` argument:\n\n\n```python\nlimit(1/x, x, 0, dir=\"-\")\n```\n\n\n```python\nlimit(1/x, x, 0, dir=\"+-\")\n```\n\nWe may also create an expression with the limit without evaluating it\n\n\n```python\nLimit(1/x, x, 0, dir=\"+\")\n```\n\nand evaluate later if needed\n\n\n```python\n_.doit()\n```\n\n#### Differentiation\n\n\n```python\ndiff(sin(x)/x, x)\n```\n\nMultiple and multivariate derivatives are possible\n\n\n```python\ndiff(sin(x)/x, x, x)\n```\n\n\n```python\ndiff(sin(x)/x, x, 2)\n```\n\n\n```python\ndiff(sin(x)/y, x, 2, y, 2)\n```\n\nUnevaluated derivatives are useful for expressing differential equations\n\n\n```python\nDerivative(sin(x)/y, x, 2, y, 2)\n```\n\n#### Series expansion\n\n\n```python\nexp(x).series()\n```\n\n\n```python\nexpr = exp(sin(x**2+pi))\nexpr.series(x)\n```\n\n\n```python\nexpr.series(x, 1)\n```\n\nLets compare the original function with its series expansion visually\n\n### Plotting side-note $\\to$\n\n\n```python\np1 = plot(expr, expr.series(x, 1, 7).removeO(), (x, -4, 7),\n ylim = (-1,3),\n show = False,\n legend = True\n)\np1[1].line_color=\"r\"\np1[1].label=\"series(6)\"\np1.show()\n```\n\n### ODE solving\n\n\n```python\nf, g = symbols('f, g', cls=Function)\n```\n\n\n```python\neqn = Eq(f(x).diff(x, x) - 2*f(x).diff(x) + f(x), sin(x))\neqn\n```\n\n\n```python\nsol = dsolve(eqn, f(x))\nsol\n```\n\nWe can test that the solution is valid\n\n\n```python\neqn.subs(f(x), sol.args[1]).doit()\n```\n\nSystems of equations are also supported\n\n\n```python\nalpha = symbols(\"alpha\", positive=True)\neqn = Eq(f(x).diff(x), alpha*g(x)), Eq(g(x).diff(x), -alpha*g(x))\neqn\n```\n\n\n```python\ndsolve(eqn, (f(x), g(x)))\n```\n", "meta": {"hexsha": "6b596d7d34963223f1b01b881b176c69213806d2", "size": 106115, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/02 Calculus.ipynb", "max_stars_repo_name": "rouckas/sympy-slides", "max_stars_repo_head_hexsha": "c2777f0eddedd19c4bf094d40489f49c1ef8ad28", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2018-10-22T19:52:48.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-01T16:59:45.000Z", "max_issues_repo_path": "notebooks/02 Calculus.ipynb", "max_issues_repo_name": "rouckas/sympy-slides", "max_issues_repo_head_hexsha": "c2777f0eddedd19c4bf094d40489f49c1ef8ad28", "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": "notebooks/02 Calculus.ipynb", "max_forks_repo_name": "rouckas/sympy-slides", "max_forks_repo_head_hexsha": "c2777f0eddedd19c4bf094d40489f49c1ef8ad28", "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": 144.9658469945, "max_line_length": 34460, "alphanum_fraction": 0.8456862837, "converted": true, "num_tokens": 733, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9603611597645271, "lm_q2_score": 0.9362850075259039, "lm_q1q2_score": 0.899171755697716}} {"text": "# Transformations, Eigenvectors, and Eigenvalues\n\nMatrices and vectors are used together to manipulate spatial dimensions. This has a lot of applications, including the mathematical generation of 3D computer graphics, geometric modeling, and the training and optimization of machine learning algorithms. We're not going to cover the subject exhaustively here; but we'll focus on a few key concepts that are useful to know when you plan to work with machine learning.\n\n## Linear Transformations\nYou can manipulate a vector by multiplying it with a matrix. The matrix acts a function that operates on an input vector to produce a vector output. Specifically, matrix multiplications of vectors are *linear transformations* that transform the input vector into the output vector.\n\nFor example, consider this matrix ***A*** and vector ***v***:\n\n$$ A = \\begin{bmatrix}2 & 3\\\\5 & 2\\end{bmatrix} \\;\\;\\;\\; \\vec{v} = \\begin{bmatrix}1\\\\2\\end{bmatrix}$$\n\nWe can define a transformation ***T*** like this:\n\n$$ T(\\vec{v}) = A\\vec{v} $$\n\nTo perform this transformation, we simply calculate the dot product by applying the *RC* rule; multiplying each row of the matrix by the single column of the vector:\n\n$$\\begin{bmatrix}2 & 3\\\\5 & 2\\end{bmatrix} \\cdot \\begin{bmatrix}1\\\\2\\end{bmatrix} = \\begin{bmatrix}8\\\\9\\end{bmatrix}$$\n\nHere's the calculation in Python:\n\n\n```python\nimport numpy as np\n\nv = np.array([1,2])\nA = np.array([[2,3],\n [5,2]])\n\nt = A@v\nprint (t)\n```\n\n [8 9]\n\n\nIn this case, both the input vector and the output vector have 2 components - in other words, the transformation takes a 2-dimensional vector and produces a new 2-dimensional vector; which we can indicate like this:\n\n$$ T: \\rm I\\!R^{2} \\to \\rm I\\!R^{2} $$\n\nNote that the output vector may have a different number of dimensions from the input vector; so the matrix function might transform the vector from one space to another - or in notation, ${\\rm I\\!R}$n -> ${\\rm I\\!R}$m.\n\nFor example, let's redefine matrix ***A***, while retaining our original definition of vector ***v***:\n\n$$ A = \\begin{bmatrix}2 & 3\\\\5 & 2\\\\1 & 1\\end{bmatrix} \\;\\;\\;\\; \\vec{v} = \\begin{bmatrix}1\\\\2\\end{bmatrix}$$\n\nNow if we once again define ***T*** like this:\n\n$$ T(\\vec{v}) = A\\vec{v} $$\n\nWe apply the transformation like this:\n\n$$\\begin{bmatrix}2 & 3\\\\5 & 2\\\\1 & 1\\end{bmatrix} \\cdot \\begin{bmatrix}1\\\\2\\end{bmatrix} = \\begin{bmatrix}8\\\\9\\\\3\\end{bmatrix}$$\n\nSo now, our transformation transforms the vector from 2-dimensional space to 3-dimensional space:\n\n$$ T: \\rm I\\!R^{2} \\to \\rm I\\!R^{3} $$\n\nHere it is in Python:\n\n\n```python\nimport numpy as np\nv = np.array([1,2])\nA = np.array([[2,3],\n [5,2],\n [1,1]])\n\nt = A@v\nprint (t)\n```\n\n [8 9 3]\n\n\n\n```python\nimport numpy as np\nv = np.array([1,2])\nA = np.array([[1,2],\n [2,1]])\n\nt = A@v\nprint (t)\n```\n\n [5 4]\n\n\n## Transformations of Magnitude and Amplitude\n\nWhen you multiply a vector by a matrix, you transform it in at least one of the following two ways:\n* Scale the length (*magnitude*) of the matrix to make it longer or shorter\n* Change the direction (*amplitude*) of the matrix\n\nFor example consider the following matrix and vector:\n\n$$ A = \\begin{bmatrix}2 & 0\\\\0 & 2\\end{bmatrix} \\;\\;\\;\\; \\vec{v} = \\begin{bmatrix}1\\\\0\\end{bmatrix}$$\n\nAs before, we transform the vector ***v*** by multiplying it with the matrix ***A***:\n\n\\begin{equation}\\begin{bmatrix}2 & 0\\\\0 & 2\\end{bmatrix} \\cdot \\begin{bmatrix}1\\\\0\\end{bmatrix} = \\begin{bmatrix}2\\\\0\\end{bmatrix}\\end{equation}\n\nIn this case, the resulting vector has changed in length (*magnitude*), but has not changed its direction (*amplitude*).\n\nLet's visualize that in Python:\n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\nv = np.array([1,0])\nA = np.array([[2,0],\n [0,2]])\n\nt = A@v\nprint (t)\n\n# Plot v and t\nvecs = np.array([t,v])\norigin = [0], [0]\nplt.axis('equal')\nplt.grid()\nplt.ticklabel_format(style='sci', axis='both', scilimits=(0,0))\nplt.quiver(*origin, vecs[:,0], vecs[:,1], color=['blue', 'orange'], scale=10)\nplt.show()\n```\n\nThe original vector ***v*** is shown in orange, and the transformed vector ***t*** is shown in blue - note that ***t*** has the same direction (*amplitude*) as ***v*** but a greater length (*magnitude*).\n\nNow let's use a different matrix to transform the vector ***v***:\n\\begin{equation}\\begin{bmatrix}0 & -1\\\\1 & 0\\end{bmatrix} \\cdot \\begin{bmatrix}1\\\\0\\end{bmatrix} = \\begin{bmatrix}0\\\\1\\end{bmatrix}\\end{equation}\n\nThis time, the resulting vector has been changed to a different amplitude, but has the same magnitude.\n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\nv = np.array([1,0])\nA = np.array([[0,-1],\n [1,0]])\n\nt = A@v\nprint (t)\n\n# Plot v and t\nvecs = np.array([v,t])\norigin = [0], [0]\nplt.axis('equal')\nplt.grid()\nplt.ticklabel_format(style='sci', axis='both', scilimits=(0,0))\nplt.quiver(*origin, vecs[:,0], vecs[:,1], color=['orange', 'blue'], scale=10)\nplt.show()\n```\n\nNow let's see change the matrix one more time:\n\\begin{equation}\\begin{bmatrix}2 & 1\\\\1 & 2\\end{bmatrix} \\cdot \\begin{bmatrix}1\\\\0\\end{bmatrix} = \\begin{bmatrix}2\\\\1\\end{bmatrix}\\end{equation}\n\nNow our resulting vector has been transformed to a new amplitude *and* magnitude - the transformation has affected both direction and scale.\n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\nv = np.array([1,0])\nA = np.array([[2,1],\n [1,2]])\n\nt = A@v\nprint (t)\n\n# Plot v and t\nvecs = np.array([v,t])\norigin = [0], [0]\nplt.axis('equal')\nplt.grid()\nplt.ticklabel_format(style='sci', axis='both', scilimits=(0,0))\nplt.quiver(*origin, vecs[:,0], vecs[:,1], color=['orange', 'blue'], scale=10)\nplt.show()\n```\n\n### Afine Transformations\nAn Afine transformation multiplies a vector by a matrix and adds an offset vector, sometimes referred to as *bias*; like this:\n\n$$T(\\vec{v}) = A\\vec{v} + \\vec{b}$$\n\nFor example:\n\n\\begin{equation}\\begin{bmatrix}5 & 2\\\\3 & 1\\end{bmatrix} \\cdot \\begin{bmatrix}1\\\\1\\end{bmatrix} + \\begin{bmatrix}-2\\\\-6\\end{bmatrix} = \\begin{bmatrix}5\\\\-2\\end{bmatrix}\\end{equation}\n\nThis kind of transformation is actually the basis of linear regression, which is a core foundation for machine learning. The matrix defines the *features*, the first vector is the *coefficients*, and the bias vector is the *intercept*.\n\nhere's an example of an Afine transformation in Python:\n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\nv = np.array([1,1])\nA = np.array([[5,2],\n [3,1]])\nb = np.array([-2,-6])\n\nt = A@v + b\nprint (t)\n\n# Plot v and t\nvecs = np.array([v,t])\norigin = [0], [0]\nplt.axis('equal')\nplt.grid()\nplt.ticklabel_format(style='sci', axis='both', scilimits=(0,0))\nplt.quiver(*origin, vecs[:,0], vecs[:,1], color=['orange', 'blue'], scale=15)\nplt.show()\n```\n\n## Eigenvectors and Eigenvalues\nSo we can see that when you transform a vector using a matrix, we change its direction, length, or both. When the transformation only affects scale (in other words, the output vector has a different magnitude but the same amplitude as the input vector), the matrix multiplication for the transformation is the equivalent operation as some scalar multiplication of the vector.\n\nFor example, earlier we examined the following transformation that dot-mulitplies a vector by a matrix:\n\n$$\\begin{bmatrix}2 & 0\\\\0 & 2\\end{bmatrix} \\cdot \\begin{bmatrix}1\\\\0\\end{bmatrix} = \\begin{bmatrix}2\\\\0\\end{bmatrix}$$\n\nYou can achieve the same result by mulitplying the vector by the scalar value ***2***:\n\n$$2 \\times \\begin{bmatrix}1\\\\0\\end{bmatrix} = \\begin{bmatrix}2\\\\0\\end{bmatrix}$$\n\nThe following python performs both of these calculation and shows the results, which are identical.\n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\nv = np.array([1,0])\nA = np.array([[2,0],\n [0,2]])\n\nt1 = A@v\nprint (t1)\nt2 = 2*v\nprint (t2)\n\nfig = plt.figure()\na=fig.add_subplot(1,1,1)\n# Plot v and t1\nvecs = np.array([t1,v])\norigin = [0], [0]\nplt.axis('equal')\nplt.grid()\nplt.ticklabel_format(style='sci', axis='both', scilimits=(0,0))\nplt.quiver(*origin, vecs[:,0], vecs[:,1], color=['blue', 'orange'], scale=10)\nplt.show()\na=fig.add_subplot(1,2,1)\n# Plot v and t2\nvecs = np.array([t2,v])\norigin = [0], [0]\nplt.axis('equal')\nplt.grid()\nplt.ticklabel_format(style='sci', axis='both', scilimits=(0,0))\nplt.quiver(*origin, vecs[:,0], vecs[:,1], color=['blue', 'orange'], scale=10)\nplt.show()\n```\n\nIn cases like these, where a matrix transformation is the equivelent of a scalar-vector multiplication, the scalar-vector pairs that correspond to the matrix are known respectively as eigenvalues and eigenvectors. We generally indicate eigenvalues using the Greek letter lambda (λ), and the formula that defines eigenvalues and eigenvectors with respect to a transformation is:\n\n$$ T(\\vec{v}) = \\lambda\\vec{v}$$\n\nWhere the vector ***v*** is an eigenvector and the value ***λ*** is an eigenvalue for transformation ***T***.\n\nWhen the transformation ***T*** is represented as a matrix multiplication, as in this case where the transformation is represented by matrix ***A***:\n\n$$ T(\\vec{v}) = A\\vec{v} = \\lambda\\vec{v}$$\n\nThen ***v*** is an eigenvector and ***λ*** is an eigenvalue of ***A***.\n\nA matrix can have multiple eigenvector-eigenvalue pairs, and you can calculate them manually. However, it's generally easier to use a tool or programming language. For example, in Python you can use the ***linalg.eig*** function, which returns an array of eigenvalues and a matrix of the corresponding eigenvectors for the specified matrix.\n\nHere's an example that returns the eigenvalue and eigenvector pairs for the following matrix:\n\n$$A=\\begin{bmatrix}2 & 0\\\\0 & 3\\end{bmatrix}$$\n\n\n```python\nimport numpy as np\nA = np.array([[2,0],\n [0,3]])\neVals, eVecs = np.linalg.eig(A)\nprint(eVals)\nprint(eVecs)\n```\n\n [2. 3.]\n [[1. 0.]\n [0. 1.]]\n\n\nSo there are two eigenvalue-eigenvector pairs for this matrix, as shown here:\n\n$$ \\lambda_{1} = 2, \\vec{v_{1}} = \\begin{bmatrix}1 \\\\ 0\\end{bmatrix} \\;\\;\\;\\;\\;\\; \\lambda_{2} = 3, \\vec{v_{2}} = \\begin{bmatrix}0 \\\\ 1\\end{bmatrix} $$\n\nLet's verify that multiplying each eigenvalue-eigenvector pair corresponds to the dot-product of the eigenvector and the matrix. Here's the first pair:\n\n$$ 2 \\times \\begin{bmatrix}1 \\\\ 0\\end{bmatrix} = \\begin{bmatrix}2 \\\\ 0\\end{bmatrix} \\;\\;\\;and\\;\\;\\; \\begin{bmatrix}2 & 0\\\\0 & 3\\end{bmatrix} \\cdot \\begin{bmatrix}1 \\\\ 0\\end{bmatrix} = \\begin{bmatrix}2 \\\\ 0\\end{bmatrix} $$\n\nSo far so good. Now let's check the second pair:\n\n$$ 3 \\times \\begin{bmatrix}0 \\\\ 1\\end{bmatrix} = \\begin{bmatrix}0 \\\\ 3\\end{bmatrix} \\;\\;\\;and\\;\\;\\; \\begin{bmatrix}2 & 0\\\\0 & 3\\end{bmatrix} \\cdot \\begin{bmatrix}0 \\\\ 1\\end{bmatrix} = \\begin{bmatrix}0 \\\\ 3\\end{bmatrix} $$\n\nSo our eigenvalue-eigenvector scalar multiplications do indeed correspond to our matrix-eigenvector dot-product transformations.\n\nHere's the equivalent code in Python, using the ***eVals*** and ***eVecs*** variables you generated in the previous code cell:\n\n\n```python\nvec1 = eVecs[:,0]\nlam1 = eVals[0]\n\nprint('Matrix A:')\nprint(A)\nprint('-------')\n\nprint('lam1: ' + str(lam1))\nprint ('v1: ' + str(vec1))\nprint ('Av1: ' + str(A@vec1))\nprint ('lam1 x v1: ' + str(lam1*vec1))\n\nprint('-------')\n\nvec2 = eVecs[:,1]\nlam2 = eVals[1]\n\nprint('lam2: ' + str(lam2))\nprint ('v2: ' + str(vec2))\nprint ('Av2: ' + str(A@vec2))\nprint ('lam2 x v2: ' + str(lam2*vec2))\n```\n\n Matrix A:\n [[2 0]\n [0 3]]\n -------\n lam1: 2.0\n v1: [1. 0.]\n Av1: [2. 0.]\n lam1 x v1: [2. 0.]\n -------\n lam2: 3.0\n v2: [0. 1.]\n Av2: [0. 3.]\n lam2 x v2: [0. 3.]\n\n\nYou can use the following code to visualize these transformations:\n\n\n```python\nt1 = lam1*vec1\nprint (t1)\nt2 = lam2*vec2\nprint (t2)\n\nfig = plt.figure()\na=fig.add_subplot(1,1,1)\n# Plot v and t1\nvecs = np.array([t1,vec1])\norigin = [0], [0]\nplt.axis('equal')\nplt.grid()\nplt.ticklabel_format(style='sci', axis='both', scilimits=(0,0))\nplt.quiver(*origin, vecs[:,0], vecs[:,1], color=['blue', 'orange'], scale=10)\nplt.show()\na=fig.add_subplot(1,2,1)\n# Plot v and t2\nvecs = np.array([t2,vec2])\norigin = [0], [0]\nplt.axis('equal')\nplt.grid()\nplt.ticklabel_format(style='sci', axis='both', scilimits=(0,0))\nplt.quiver(*origin, vecs[:,0], vecs[:,1], color=['blue', 'orange'], scale=10)\nplt.show()\n```\n\nSimilarly, earlier we examined the following matrix transformation:\n\n$$\\begin{bmatrix}2 & 0\\\\0 & 2\\end{bmatrix} \\cdot \\begin{bmatrix}1\\\\0\\end{bmatrix} = \\begin{bmatrix}2\\\\0\\end{bmatrix}$$\n\nAnd we saw that you can achieve the same result by mulitplying the vector by the scalar value ***2***:\n\n$$2 \\times \\begin{bmatrix}1\\\\0\\end{bmatrix} = \\begin{bmatrix}2\\\\0\\end{bmatrix}$$\n\nThis works because the scalar value 2 and the vector (1,0) are an eigenvalue-eigenvector pair for this matrix.\n\nLet's use Python to determine the eigenvalue-eigenvector pairs for this matrix:\n\n\n```python\nimport numpy as np\nA = np.array([[2,0],\n [0,2]])\neVals, eVecs = np.linalg.eig(A)\nprint(eVals)\nprint(eVecs)\n```\n\nSo once again, there are two eigenvalue-eigenvector pairs for this matrix, as shown here:\n\n$$ \\lambda_{1} = 2, \\vec{v_{1}} = \\begin{bmatrix}1 \\\\ 0\\end{bmatrix} \\;\\;\\;\\;\\;\\; \\lambda_{2} = 2, \\vec{v_{2}} = \\begin{bmatrix}0 \\\\ 1\\end{bmatrix} $$\n\nLet's verify that multiplying each eigenvalue-eigenvector pair corresponds to the dot-product of the eigenvector and the matrix. Here's the first pair:\n\n$$ 2 \\times \\begin{bmatrix}1 \\\\ 0\\end{bmatrix} = \\begin{bmatrix}2 \\\\ 0\\end{bmatrix} \\;\\;\\;and\\;\\;\\; \\begin{bmatrix}2 & 0\\\\0 & 2\\end{bmatrix} \\cdot \\begin{bmatrix}1 \\\\ 0\\end{bmatrix} = \\begin{bmatrix}2 \\\\ 0\\end{bmatrix} $$\n\nWell, we already knew that. Now let's check the second pair:\n\n$$ 2 \\times \\begin{bmatrix}0 \\\\ 1\\end{bmatrix} = \\begin{bmatrix}0 \\\\ 2\\end{bmatrix} \\;\\;\\;and\\;\\;\\; \\begin{bmatrix}2 & 0\\\\0 & 2\\end{bmatrix} \\cdot \\begin{bmatrix}0 \\\\ 1\\end{bmatrix} = \\begin{bmatrix}0 \\\\ 2\\end{bmatrix} $$\n\nNow let's use Pythonto verify and plot these transformations:\n\n\n```python\nvec1 = eVecs[:,0]\nlam1 = eVals[0]\n\nprint('Matrix A:')\nprint(A)\nprint('-------')\n\nprint('lam1: ' + str(lam1))\nprint ('v1: ' + str(vec1))\nprint ('Av1: ' + str(A@vec1))\nprint ('lam1 x v1: ' + str(lam1*vec1))\n\nprint('-------')\n\nvec2 = eVecs[:,1]\nlam2 = eVals[1]\n\nprint('lam2: ' + str(lam2))\nprint ('v2: ' + str(vec2))\nprint ('Av2: ' + str(A@vec2))\nprint ('lam2 x v2: ' + str(lam2*vec2))\n\n\n# Plot the resulting vectors\nt1 = lam1*vec1\nt2 = lam2*vec2\n\nfig = plt.figure()\na=fig.add_subplot(1,1,1)\n# Plot v and t1\nvecs = np.array([t1,vec1])\norigin = [0], [0]\nplt.axis('equal')\nplt.grid()\nplt.ticklabel_format(style='sci', axis='both', scilimits=(0,0))\nplt.quiver(*origin, vecs[:,0], vecs[:,1], color=['blue', 'orange'], scale=10)\nplt.show()\na=fig.add_subplot(1,2,1)\n# Plot v and t2\nvecs = np.array([t2,vec2])\norigin = [0], [0]\nplt.axis('equal')\nplt.grid()\nplt.ticklabel_format(style='sci', axis='both', scilimits=(0,0))\nplt.quiver(*origin, vecs[:,0], vecs[:,1], color=['blue', 'orange'], scale=10)\nplt.show()\n```\n\nLet's take a look at one more, slightly more complex example. Here's our matrix:\n\n$$\\begin{bmatrix}2 & 1\\\\1 & 2\\end{bmatrix}$$\n\nLet's get the eigenvalue and eigenvector pairs:\n\n\n```python\nimport numpy as np\n\nA = np.array([[2,1],\n [1,2]])\n\neVals, eVecs = np.linalg.eig(A)\nprint(eVals)\nprint(eVecs)\n```\n\n [3. 1.]\n [[ 0.70710678 -0.70710678]\n [ 0.70710678 0.70710678]]\n\n\nThis time the eigenvalue-eigenvector pairs are:\n\n$$ \\lambda_{1} = 3, \\vec{v_{1}} = \\begin{bmatrix}0.70710678 \\\\ 0.70710678\\end{bmatrix} \\;\\;\\;\\;\\;\\; \\lambda_{2} = 1, \\vec{v_{2}} = \\begin{bmatrix}-0.70710678 \\\\ 0.70710678\\end{bmatrix} $$\n\nSo let's check the first pair:\n\n$$ 3 \\times \\begin{bmatrix}0.70710678 \\\\ 0.70710678\\end{bmatrix} = \\begin{bmatrix}2.12132034 \\\\ 2.12132034\\end{bmatrix} \\;\\;\\;and\\;\\;\\; \\begin{bmatrix}2 & 1\\\\0 & 2\\end{bmatrix} \\cdot \\begin{bmatrix}0.70710678 \\\\ 0.70710678\\end{bmatrix} = \\begin{bmatrix}2.12132034 \\\\ 2.12132034\\end{bmatrix} $$\n\nNow let's check the second pair:\n\n$$ 1 \\times \\begin{bmatrix}-0.70710678 \\\\ 0.70710678\\end{bmatrix} = \\begin{bmatrix}-0.70710678\\\\0.70710678\\end{bmatrix} \\;\\;\\;and\\;\\;\\; \\begin{bmatrix}2 & 1\\\\1 & 2\\end{bmatrix} \\cdot \\begin{bmatrix}-0.70710678 \\\\ 0.70710678\\end{bmatrix} = \\begin{bmatrix}-0.70710678\\\\0.70710678\\end{bmatrix} $$\n\nWith more complex examples like this, it's generally easier to do it with Python:\n\n\n```python\nvec1 = eVecs[:,0]\nlam1 = eVals[0]\n\nprint('Matrix A:')\nprint(A)\nprint('-------')\n\nprint('lam1: ' + str(lam1))\nprint ('v1: ' + str(vec1))\nprint ('Av1: ' + str(A@vec1))\nprint ('lam1 x v1: ' + str(lam1*vec1))\n\nprint('-------')\n\nvec2 = eVecs[:,1]\nlam2 = eVals[1]\n\nprint('lam2: ' + str(lam2))\nprint ('v2: ' + str(vec2))\nprint ('Av2: ' + str(A@vec2))\nprint ('lam2 x v2: ' + str(lam2*vec2))\n\n\n# Plot the results\nt1 = lam1*vec1\nt2 = lam2*vec2\n\nfig = plt.figure()\na=fig.add_subplot(1,1,1)\n# Plot v and t1\nvecs = np.array([t1,vec1])\norigin = [0], [0]\nplt.axis('equal')\nplt.grid()\nplt.ticklabel_format(style='sci', axis='both', scilimits=(0,0))\nplt.quiver(*origin, vecs[:,0], vecs[:,1], color=['blue', 'orange'], scale=10)\nplt.show()\na=fig.add_subplot(1,2,1)\n# Plot v and t2\nvecs = np.array([t2,vec2])\norigin = [0], [0]\nplt.axis('equal')\nplt.grid()\nplt.ticklabel_format(style='sci', axis='both', scilimits=(0,0))\nplt.quiver(*origin, vecs[:,0], vecs[:,1], color=['blue', 'orange'], scale=10)\nplt.show()\n```\n\n## Eigendecomposition\nSo we've learned a little about eigenvalues and eigenvectors; but you may be wondering what use they are. Well, one use for them is to help decompose transformation matrices.\n\nRecall that previously we found that a matrix transformation of a vector changes its magnitude, amplitude, or both. Without getting too technical about it, we need to remember that vectors can exist in any spatial orientation, or *basis*; and the same transformation can be applied in different *bases*.\n\nWe can decompose a matrix using the following formula:\n\n$$A = Q \\Lambda Q^{-1}$$\n\nWhere ***A*** is a trasformation that can be applied to a vector in its current base, ***Q*** is a matrix of eigenvectors that defines a change of basis, and ***Λ*** is a matrix with eigenvalues on the diagonal that defines the same linear transformation as ***A*** in the base defined by ***Q***.\n\nLet's look at these in some more detail. Consider this matrix:\n\n$$A=\\begin{bmatrix}3 & 2\\\\1 & 0\\end{bmatrix}$$\n\n***Q*** is a matrix in which each column is an eigenvector of ***A***; which as we've seen previously, we can calculate using Python:\n\n\n```python\nimport numpy as np\n\nA = np.array([[3,2],\n [1,0]])\n\nl, Q = np.linalg.eig(A)\nprint(Q)\n```\n\nSo for matrix ***A***, ***Q*** is the following matrix:\n\n$$Q=\\begin{bmatrix}0.96276969 & -0.48963374\\\\0.27032301 & 0.87192821\\end{bmatrix}$$\n\n***Λ*** is a matrix that contains the eigenvalues for ***A*** on the diagonal, with zeros in all other elements; so for a 2x2 matrix, Λ will look like this:\n\n$$\\Lambda=\\begin{bmatrix}\\lambda_{1} & 0\\\\0 & \\lambda_{2}\\end{bmatrix}$$\n\nIn our Python code, we've already used the ***linalg.eig*** function to return the array of eigenvalues for ***A*** into the variable ***l***, so now we just need to format that as a matrix:\n\n\n```python\nL = np.diag(l)\nprint (L)\n```\n\nSo ***Λ*** is the following matrix:\n\n$$\\Lambda=\\begin{bmatrix}3.56155281 & 0\\\\0 & -0.56155281\\end{bmatrix}$$\n\nNow we just need to find ***Q-1***, which is the inverse of ***Q***:\n\n\n```python\nQinv = np.linalg.inv(Q)\nprint(Qinv)\n```\n\nThe inverse of ***Q*** then, is:\n\n$$Q^{-1}=\\begin{bmatrix}0.89720673 & 0.50382896\\\\-0.27816009 & 0.99068183\\end{bmatrix}$$\n\nSo what does that mean? Well, it means that we can decompose the transformation of *any* vector multiplied by matrix ***A*** into the separate operations ***QΛQ-1***:\n\n$$A\\vec{v} = Q \\Lambda Q^{-1}\\vec{v}$$\n\nTo prove this, let's take vector ***v***:\n\n$$\\vec{v} = \\begin{bmatrix}1\\\\3\\end{bmatrix} $$\n\nOur matrix transformation using ***A*** is:\n\n$$\\begin{bmatrix}3 & 2\\\\1 & 0\\end{bmatrix} \\cdot \\begin{bmatrix}1\\\\3\\end{bmatrix} $$\n\nSo let's show the results of that using Python:\n\n\n```python\nv = np.array([1,3])\nt = A@v\n\nprint(t)\n\n# Plot v and t\nvecs = np.array([v,t])\norigin = [0], [0]\nplt.axis('equal')\nplt.grid()\nplt.ticklabel_format(style='sci', axis='both', scilimits=(0,0))\nplt.quiver(*origin, vecs[:,0], vecs[:,1], color=['orange', 'b'], scale=20)\nplt.show()\n```\n\nAnd now, let's do the same thing using the ***QΛQ-1*** sequence of operations:\n\n\n```python\nimport math\nimport numpy as np\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\nt = (Q@(L@(Qinv)))@v\n\n# Plot v and t\nvecs = np.array([v,t])\norigin = [0], [0]\nplt.axis('equal')\nplt.grid()\nplt.ticklabel_format(style='sci', axis='both', scilimits=(0,0))\nplt.quiver(*origin, vecs[:,0], vecs[:,1], color=['orange', 'b'], scale=20)\nplt.show()\n```\n\nSo ***A*** and ***QΛQ-1*** are equivalent.\n\nIf we view the intermediary stages of the decomposed transformation, you can see the transformation using ***A*** in the original base for ***v*** (orange to blue) and the transformation using ***Λ*** in the change of basis decribed by ***Q*** (red to magenta):\n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\nt1 = Qinv@v\nt2 = L@t1\nt3 = Q@t2\n\n# Plot the transformations\nvecs = np.array([v,t1, t2, t3])\norigin = [0], [0]\nplt.axis('equal')\nplt.grid()\nplt.ticklabel_format(style='sci', axis='both', scilimits=(0,0))\nplt.quiver(*origin, vecs[:,0], vecs[:,1], color=['orange', 'red', 'magenta', 'blue'], scale=20)\nplt.show()\n```\n\nSo from this visualization, it should be apparent that the transformation ***Av*** can be performed by changing the basis for ***v*** using ***Q*** (from orange to red in the above plot) applying the equivalent linear transformation in that base using ***Λ*** (red to magenta), and switching back to the original base using ***Q-1*** (magenta to blue).\n\n## Rank of a Matrix\n\nThe **rank** of a square matrix is the number of non-zero eigenvalues of the matrix. A **full rank** matrix has the same number of non-zero eigenvalues as the dimension of the matrix. A **rank-deficient** matrix has fewer non-zero eigenvalues as dimensions. The inverse of a rank deficient matrix is singular and so does not exist (this is why in a previous notebook we noted that some matrices have no inverse).\n\nConsider the following matrix ***A***:\n\n$$A=\\begin{bmatrix}1 & 2\\\\4 & 3\\end{bmatrix}$$\n\nLet's find its eigenvalues (***Λ***):\n\n\n```python\nimport numpy as np\nA = np.array([[1,2],\n [4,3]])\nl, Q = np.linalg.eig(A)\nL = np.diag(l)\nprint(L)\n```\n\n [[-1. 0.]\n [ 0. 5.]]\n\n\n$$\\Lambda=\\begin{bmatrix}-1 & 0\\\\0 & 5\\end{bmatrix}$$\n\nThis matrix has full rank. The dimensions of the matrix is 2. There are two non-zero eigenvalues. \n\nNow consider this matrix:\n\n$$B=\\begin{bmatrix}3 & -3 & 6\\\\2 & -2 & 4\\\\1 & -1 & 2\\end{bmatrix}$$\n\nNote that the second and third columns are just scalar multiples of the first column.\n\nLet's examine it's eigenvalues:\n\n\n```python\nB = np.array([[3,-3,6],\n [2,-2,4],\n [1,-1,2]])\nlb, Qb = np.linalg.eig(B)\nLb = np.diag(lb)\nprint(Lb)\n```\n\n [[3.00000000e+00 0.00000000e+00 0.00000000e+00]\n [0.00000000e+00 5.23364153e-16 0.00000000e+00]\n [0.00000000e+00 0.00000000e+00 0.00000000e+00]]\n\n\n$$\\Lambda=\\begin{bmatrix}3 & 0& 0\\\\0 & -6\\times10^{-17} & 0\\\\0 & 0 & 3.6\\times10^{-16}\\end{bmatrix}$$\n\nNote that matrix has only 1 non-zero eigenvalue. The other two eigenvalues are so extremely small as to be effectively zero. This is an example of a rank-deficient matrix; and as such, it has no inverse.\n\n## Inverse of a Square Full Rank Matrix\nYou can calculate the inverse of a square full rank matrix by using the following formula:\n\n$$A^{-1} = Q \\Lambda^{-1} Q^{-1}$$\n\nLet's apply this to matrix ***A***:\n\n$$A=\\begin{bmatrix}1 & 2\\\\4 & 3\\end{bmatrix}$$\n\nLet's find the matrices for ***Q***, ***Λ-1***, and ***Q-1***:\n\n\n```python\nimport numpy as np\nA = np.array([[1,2],\n [4,3]])\n\nl, Q = np.linalg.eig(A)\nL = np.diag(l)\nprint(Q)\nLinv = np.linalg.inv(L)\nQinv = np.linalg.inv(Q)\nprint(Linv)\nprint(Qinv)\n```\n\nSo:\n\n$$A^{-1}=\\begin{bmatrix}-0.70710678 & -0.4472136\\\\0.70710678 & -0.89442719\\end{bmatrix}\\cdot\\begin{bmatrix}-1 & -0\\\\0 & 0.2\\end{bmatrix}\\cdot\\begin{bmatrix}-0.94280904 & 0.47140452\\\\-0.74535599 & -0.74535599\\end{bmatrix}$$\n\nLet's calculate that in Python:\n\n\n```python\nAinv = (Q@(Linv@(Qinv)))\nprint(Ainv)\n```\n\nThat gives us the result:\n\n$$A^{-1}=\\begin{bmatrix}-0.6 & 0.4\\\\0.8 & -0.2\\end{bmatrix}$$\n\nWe can apply the ***np.linalg.inv*** function directly to ***A*** to verify this:\n\n\n```python\nprint(np.linalg.inv(A))\n```\n", "meta": {"hexsha": "05b7e7eb98b85db7c03377ecf3895d73bae28922", "size": 98702, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "MathsToML/Module03-Vectors and Matrices/03-05-Transformations Eigenvectors and Eigenvalues.ipynb", "max_stars_repo_name": "hpaucar/data-mining-repo", "max_stars_repo_head_hexsha": "d0e48520bc6c01d7cb72e882154cde08020e1d33", "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": "MathsToML/Module03-Vectors and Matrices/03-05-Transformations Eigenvectors and Eigenvalues.ipynb", "max_issues_repo_name": "hpaucar/data-mining-repo", "max_issues_repo_head_hexsha": "d0e48520bc6c01d7cb72e882154cde08020e1d33", "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": "MathsToML/Module03-Vectors and Matrices/03-05-Transformations Eigenvectors and Eigenvalues.ipynb", "max_forks_repo_name": "hpaucar/data-mining-repo", "max_forks_repo_head_hexsha": "d0e48520bc6c01d7cb72e882154cde08020e1d33", "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": 160.2305194805, "max_line_length": 6522, "alphanum_fraction": 0.8200644364, "converted": true, "num_tokens": 8132, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9777138157595305, "lm_q2_score": 0.9196425350319858, "lm_q1q2_score": 0.8991472120608905}} {"text": "# Logistic Regression Model\n\n## 1. Cost function\n\nWe assume that we have a training set $\\{(\\boldsymbol{x}^{(1)}, y^{(1)}), (\\boldsymbol{x}^{(2)}, y^{(2)}), \\dots, (\\boldsymbol{x}^{(m)}, y^{(m)})\\}$ with $m$ examples, where \n\n$$x=\\left[\n\\begin{array}{c}\nx_0 \\\\\nx_1 \\\\\n\\vdots \\\\\nx_n\n\\end{array}\n\\right]\n$$\n\nwith $x_0 = 1$ and $y\\in\\{0, 1\\}.$\n\nThe hypothesis function is:\n\n$$\nh_{\\theta}(\\boldsymbol{x}) = \\frac{1}{1 + e^{-\\boldsymbol{\\theta}^T\\boldsymbol{x}}} = \\frac{1}{1 + e^{-\\boldsymbol{x}^T\\boldsymbol{\\theta}}}\n$$\n\nHow can we choose the parameters $\\theta$? Does the linear regression cost works?\n\nRecall that the linear regression cost could be expressed as:\n\n$$\nJ(\\boldsymbol{\\theta}) = \\frac{1}{2m}\\sum_{i=1}^{m}(h_{\\theta}(\\boldsymbol{x}^{(i)}) - y^{(i)})^2.\n$$\n\nIt turns out that for this hypothesis, this cost function is not convex.\n\nNow, let's consider the **logistic regression cost function**:\n\n$$\nJ(\\boldsymbol{\\theta}) = \\frac{1}{m}\\sum_{i=1}^{m} \\mathrm{cost}(h_{\\theta}(\\boldsymbol{x}^{(i)}), y^{(i)}),\n$$\n\nwhere\n\n$$\n\\mathrm{cost}(h_{\\theta}(\\boldsymbol{x}), y) = \\left\\lbrace\n\\begin{array}{ccc}\n-\\log(h_{\\theta}(\\boldsymbol{x})) & \\mathrm{if} & y=1 \\\\\n-\\log(1-h_{\\theta}(\\boldsymbol{x})) & \\mathrm{if} & y=0.\n\\end{array}\n\\right.\n$$\n\nNote that $\\mathrm{cost}(h_{\\theta}(\\boldsymbol{x}), y) = 0$:\n- If $y=1$ and $h_{\\theta}(\\boldsymbol{x})=1$, or\n- If $y=0$ and $h_{\\theta}(\\boldsymbol{x})=0$.\n\nOtherwise, if for example $h_{\\theta}(\\boldsymbol{x})\\to 0$ and $y=1$, then $\\mathrm{cost}(h_{\\theta}(\\boldsymbol{x}), y)\\to \\infty$.\n\nThen, this cost function captures the desired behavior.\n\n## 2. Simplified Cost Function and Gradient Descent\n\nNote that the term $\\mathrm{cost}(h_{\\theta}(\\boldsymbol{x}), y)$ can be written in only one expression as:\n\n$$\n\\mathrm{cost}(h_{\\theta}(\\boldsymbol{x}), y) = \\left\\lbrace\n\\begin{array}{ccc}\n-\\log(h_{\\theta}(\\boldsymbol{x})) & \\mathrm{if} & y=1 \\\\\n-\\log(1-h_{\\theta}(\\boldsymbol{x})) & \\mathrm{if} & y=0.\n\\end{array}\n\\right. = -y\\log(h_{\\theta}(\\boldsymbol{x})) - (1-y)\\log(1-h_{\\theta}(\\boldsymbol{x})).\n$$\n\nThus, the logistic regression cost function can be rewritten as:\n\n$$\nJ(\\boldsymbol{\\theta}) = -\\frac{1}{m}\\sum_{i=1}^{m} \\left[y^{(i)}\\log(h_{\\theta}(\\boldsymbol{x}^{(i)})) + (1-y^{(i)})\\log(1-h_{\\theta}(\\boldsymbol{x}^{(i)}))\\right],\n$$\n\nNow, recalling that \n\n$$\nh_{\\theta}(\\boldsymbol{x}) = \\frac{1}{1 + e^{-\\boldsymbol{\\theta}^T\\boldsymbol{x}}} = \\frac{1}{1 + e^{-\\boldsymbol{x}^T\\boldsymbol{\\theta}}},\n$$\n\nwe can write this cost function in a vectorized form as:\n\n$$\nJ(\\boldsymbol{\\theta}) = -\\frac{1}{m} \\left[y^T \\log\\left(\\frac{1}{1 + e^{-\\boldsymbol{X}\\boldsymbol{\\theta}}}\\right) + (1- y)^T \\log\\left(\\frac{e^{-\\boldsymbol{X}\\boldsymbol{\\theta}}}{1 + e^{-\\boldsymbol{X}\\boldsymbol{\\theta}}}\\right)\\right],\n$$\n\nwhere\n\n$$\n\\boldsymbol{X} = \\left[\n\\begin{array}{c}\n\\boldsymbol{x}^{(1)} \\ ^T \\\\\n\\boldsymbol{x}^{(2)} \\ ^T \\\\\n\\vdots \\\\\n\\boldsymbol{x}^{(n)} \\ ^T\n\\end{array}\n\\right] = \\left[\n\\begin{array}{ccccc}\nx_0^{(1)} & x_1^{(1)} & x_2^{(1)} & \\dots & x_n^{(1)} \\\\\nx_0^{(2)} & x_1^{(2)} & x_2^{(2)} & \\dots & x_n^{(2)} \\\\\n\\vdots & \\vdots & \\vdots & \\ddots & \\vdots \\\\\nx_0^{(m)} & x_1^{(m)} & x_2^{(m)} & \\dots & x_n^{(m)}\n\\end{array}\n\\right] = \\left[\n\\begin{array}{ccccc}\n1 & x_1^{(1)} & x_2^{(1)} & \\dots & x_n^{(1)} \\\\\n1 & x_1^{(2)} & x_2^{(2)} & \\dots & x_n^{(2)} \\\\\n\\vdots & \\vdots & \\vdots & \\ddots & \\vdots \\\\\n1 & x_1^{(m)} & x_2^{(m)} & \\dots & x_n^{(m)}\n\\end{array}\n\\right] \\in \\mathbb{R}^{m \\times (n+1)}\n$$\n\nis the matrix of all the training examples, and the functions $e^{(\\cdot)}$ and $\\log{(\\cdot)}$ are understood as the componentwise application of the exponential and logarithm functions.\n\nWith the above vectorization, the gradient of the cost function is:\n\n\\begin{align}\n\\frac{\\partial}{\\partial \\boldsymbol{\\theta}} J(\\boldsymbol{\\theta}) ^T &= - \\frac{1}{m} \\left[y^T \\left(1 + e^{-\\boldsymbol{X}\\boldsymbol{\\theta}}\\right) - (1- y)^T \\left(\\frac{1 + e^{-\\boldsymbol{X}\\boldsymbol{\\theta}}}{e^{-\\boldsymbol{X}\\boldsymbol{\\theta}}}\\right)\\right] \\frac{\\partial}{\\partial \\boldsymbol{\\theta}}\\left(\\frac{1}{1 + e^{-\\boldsymbol{X}\\boldsymbol{\\theta}}}\\right)^T \\\\\n&= - \\frac{1}{m} \\left[y^T \\left(1 + e^{-\\boldsymbol{X}\\boldsymbol{\\theta}}\\right) - (1- y)^T \\left(\\frac{1 + e^{-\\boldsymbol{X}\\boldsymbol{\\theta}}}{e^{-\\boldsymbol{X}\\boldsymbol{\\theta}}}\\right)\\right] \\left(\\frac{e^{-\\boldsymbol{X}\\boldsymbol{\\theta}}}{\\left(1 + e^{-\\boldsymbol{X}\\boldsymbol{\\theta}}\\right)^2}\\right)^T \\boldsymbol{X}\\\\\n&= - \\frac{1}{m} \\left[y^T \\left(1 - \\frac{1}{1 + e^{-\\boldsymbol{X}\\boldsymbol{\\theta}}}\\right) - (1- y)^T \\left(\\frac{1}{1 + e^{-\\boldsymbol{X}\\boldsymbol{\\theta}}}\\right)\\right] \\boldsymbol{X}\\\\\n&= \\frac{1}{m} \\left[\\left(\\frac{1}{1 + e^{-\\boldsymbol{X}\\boldsymbol{\\theta}}}\\right)^T - y^T\\right] \\boldsymbol{X}\n\\end{align}\n\nThis is:\n\n$$\n\\frac{\\partial}{\\partial \\boldsymbol{\\theta}} J(\\boldsymbol{\\theta}) = \\frac{1}{m} \\boldsymbol{X}^T \\left[\\left(\\frac{1}{1 + e^{-\\boldsymbol{X}\\boldsymbol{\\theta}}}\\right) - y\\right].\n$$\n\nHaving defined the gradient, we can apply some numerical optimization method to minimize $J(\\boldsymbol{\\theta})$ and find the parameters.\n\n\n\n\n", "meta": {"hexsha": "71d963e2f15c2f9808740e9c2e0e38d4c344a350", "size": 8496, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Week3/2LogisticRegressionModel.ipynb", "max_stars_repo_name": "esjimenezro/ml_course", "max_stars_repo_head_hexsha": "5967489aeda57451228014df13c30ca356c79b84", "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": "Week3/2LogisticRegressionModel.ipynb", "max_issues_repo_name": "esjimenezro/ml_course", "max_issues_repo_head_hexsha": "5967489aeda57451228014df13c30ca356c79b84", "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": "Week3/2LogisticRegressionModel.ipynb", "max_forks_repo_name": "esjimenezro/ml_course", "max_forks_repo_head_hexsha": "5967489aeda57451228014df13c30ca356c79b84", "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.7792207792, "max_line_length": 437, "alphanum_fraction": 0.4891713748, "converted": true, "num_tokens": 2045, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9591542840900507, "lm_q2_score": 0.9372107870185259, "lm_q1q2_score": 0.8989297414642271}} {"text": "# Introducción\n\nEn esta sección se aprenderá a hacer lo siguiente:\n\n* Importar *Sympy* y configurar la impresión \"bonita\"\n* Usar operaciones matemáticas como `sqrt` y `sin`\n* Crear símbolos *Sympy*\n* Hacer derivadas de expresiones\n\n## Preámbulo\n\nAl igual que NumPy y Pandas reemplazan funciones como `sin`,` cos`, `exp` y `log` con implementaciones numéricas potentes, SymPy reemplaza `sin`, `cos`, `exp` y `log` con potentes implementaciones matemáticas.\n\n\n```python\nfrom sympy import *\ninit_printing() # configura impresión elegante\n```\n\n\n```python\nimport math\nmath.sqrt(2)\n```\n\n\n```python\nsqrt(2) # Este `sqrt` proviene de SymPy\n```\n\n### Ejercicio\n\nUsa la función `acos` en `-1` para encontrar cuando el coseno es igual a `-1`. Prueba esta misma función con la biblioteca *math*. ¿Obtienes el mismo resultado?\n\n\n\n\n```python\n# Usa a acos en -1 para encontrar en qué parte del círculo la coordenada x es igual a -1\n\n\n```\n\n\n```python\n# Usa a `math.acos` en -1 para encontrar el mismo resultado usando el módulo math.\n# ¿Es el mismo resultado?\n# ¿Que te da la función `numpy.arccos`?\n\n\n```\n\n## Symbols\n\nAl igual que `ndarray` de NumPy o `DataFrame` de Pandas, SymPy tiene `Symbol`, que representa una variable matemática.\n\nCreamos símbolos usando la función `symbols`. Las operaciones en estos símbolos no hacen un trabajo numérico como con NumPy o Pandas, sino que construyen expresiones matemáticas.\n\n\n```python\nx, y, z = symbols('x,y,z')\nalpha, beta, gamma = symbols('alpha,beta,gamma')\n```\n\n\n```python\nx + 1\n```\n\n\n```python\nlog(alpha**beta) + gamma\n```\n\n\n```python\nsin(x)**2 + cos(x)**2\n```\n\n### Ejercicio\n\nUsa `symbols` para crear dos variables, `mu` y `sigma`.\n\n\n```python\n?, ? = symbols('?')\n```\n\n### Ejercicio\n\nUsa `exp`, `sqrt` y operadores aritméticos de Python como `+, -, *, **` para crear la curva de campana estándar con objetos SymPy\n\n$$ e^{-\\frac{(x - \\mu)^2}{ \\sigma^2}} $$\n\n\n\n```python\nexp(?)\n```\n\n## Derivadas\n\nUna de las operaciones más solicitadas en SymPy es la derivada. Para tomar la derivada de una expresión, usa el método `diff`\n\n\n```python\n(x**2).diff(x)\n```\n\n\n```python\nsin(x).diff(x)\n```\n\n\n```python\n(x**2 + x*y + y**2).diff(x)\n```\n\n\n```python\ndiff(x**2 + x*y + y**2, y) # diff también está disponible como una función\n```\n\n### Ejercicio\n\nEn la última sección hiciste una distribución normal\n\n\n```python\nmu, sigma = symbols('mu,sigma')\n```\n\n\n```python\nbell = exp(-(x - mu)**2 / sigma**2)\nbell\n```\n\nToma la derivada de esta expresión con respecto a $x$\n\n\n```python\n?.diff(?)\n```\n\n### Ejercicio\n\nHay tres símbolos en esa expresión. Normalmente estamos interesados en la derivada con respecto a `x`, pero podríamos pedir la derivada con respecto a `sigma`. Prueba esto ahora\n\n\n```python\n# Derivada de la curva de campana con respecto a sigma\n\n```\n\n### Ejercicio\n\nLa segunda derivada de una expresión es solo la derivada de la derivada. Encadena llamadas `.diff( )` para encontrar la segunda y tercera derivada de tu expresión\n\n\n```python\n# Encuentra la segunda y tercera derivada de `bell`\n\n```\n\n## Funciones\n\n*SymPy* tiene varias rutinas para manipular expresiones. La función más utilizada es `simplify`.\n\n\n```python\nexpr = sin(x)**2 + cos(x)**2\nexpr\n```\n\n\n```python\nsimplify(expr)\n```\n\n### Ejercicio\n\nEn el ejercicio anterior, encontraste la tercera derivada de la curva de campana\n\n\n```python\nbell.diff(x).diff(x).diff(x)\n```\n\nPuedes notar que esta expresión tiene mucha estructura compartida. Podemos factorizar algunos términos para simplificar esta expresión.\n\nLlama a `simplify` en esta expresión y observa el resultado.\n\n\n```python\n# Llama simplify en la tercera derivada de la curva de campana\n\n```\n\n## Sympify\n\nLa función `sympify` transforma objetos Python (ints, floats, strings) en objetos Sympy (Integers, Reals, Symbols).\n*nota la diferencia entre `sympify` y `simplify`. Estas no son las mismas funciones.*\n\n\n```python\nsympify('r * cos(theta)^2')\n```\n\nEs útil cuando interactúas con el mundo real, o para copiar y pegar rápidamente una expresión de una fuente externa.\n", "meta": {"hexsha": "0364ddc60bf8e937404f20bdd30e5f9c44b8af54", "size": 9276, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "tutorial_exercises/01-Symbols-Derivatives-Functions.ipynb", "max_stars_repo_name": "t3rodrig/sympy-tutorial-es", "max_stars_repo_head_hexsha": "5cd5497f799e889d758a26539781cdc72b1e6a74", "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": "tutorial_exercises/01-Symbols-Derivatives-Functions.ipynb", "max_issues_repo_name": "t3rodrig/sympy-tutorial-es", "max_issues_repo_head_hexsha": "5cd5497f799e889d758a26539781cdc72b1e6a74", "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": "tutorial_exercises/01-Symbols-Derivatives-Functions.ipynb", "max_forks_repo_name": "t3rodrig/sympy-tutorial-es", "max_forks_repo_head_hexsha": "5cd5497f799e889d758a26539781cdc72b1e6a74", "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": 21.6223776224, "max_line_length": 215, "alphanum_fraction": 0.5376239759, "converted": true, "num_tokens": 1190, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897475985937, "lm_q2_score": 0.9553191249569861, "lm_q1q2_score": 0.8987544384443924}} {"text": "The Pebble Game\n\nLet's imagine right now, that rather than being on this zoom call we were all transported to the beaches of Monte Carlo. You can see it now, can't you? The beautiful clear blue sky and crystal clear water, and maybe even a cold brew. All of a sudden someone in the group has an idea... All excited, he/she grabs a stick and quickly draws a large square in the sand, and this person have a keen eye for measurements makes each side 2 meters.... The person says 'lets play a game...' OKay so we're going to play a game, a geeky game, but a game nonetheless. The game that's proposed, let's call it the 'pebble game', asks if we estimate the value of \\pi by randomly throwing pebbles into the circle inscribed square in the sand? The rules of the game are - Pebbles are randomly thrown into the enclosed area (let's blindfold the gineu pig). The ratio of stones in the circle and the total number of thrown stones is a simple or direct sampling statistical estimate for the area of the pond.\n\n\nLet there be a circle with radius 1 and centre (0,0).\n\nSurrounding the circle is a square with sides of length 2.\n
\n\n\\begin{align}\nA_{circle} = \\pi r^2 \\\\\n\\pi = \\frac{A_{circle}}{r^2} \\tag{1}\\\\\nA_{square} = (2r)^2 = 4r^2\\\\\nr=\\sqrt{\\frac{A_{square}}{4}} \\tag{2}\\\\\n\\text{substitute eq. 4 into eq. 2:}\\\\\n\\boxed{\\pi = 4\\left(\\frac{A_{circle}}{A_{square}}\\right)} \\tag{3}\\\\\n\\end{align}\n\n\nWe can estimate the ratio $\\frac{A_{circle}}{A_{square}}$ by generating random points\non the plane between (-1, 1). We count the number of points that land\nwithin the circle and the number of points outside the circle.\nThen, $\\frac{A_{circle}}{A_{square}} \\approx \\frac{Trials_{\\text{hits}}}{Trials_{total}}$.\n\nSo, $\\pi \\approx 4 \\cdot \\frac{Trials_{\\text{hits}}}{Trials_{total}}$\n\n\n```python\n\nimport random\nimport numpy as np \nimport matplotlib.pyplot as plt\nfrom matplotlib.animation import FuncAnimation\nimport matplotlib.animation as animation\nfrom IPython.display import Video\nfrom random import choice\nimport pandas as pd\nimport math\n%matplotlib inline\n\ndef MonteCarloSim(num_trials, decimalplaces = 5):\n '''returns dataframe with all the results of num_trials = trials of the Monte Carlo algo'''\n df = pd.DataFrame(columns=['x', 'y', 'r', 'Location', 'piEstimate','Error','Color'])\n df['x'] = 2*(np.random.rand(num_trials)-0.5)\n df['y'] = 2*(np.random.rand(num_trials)-0.5)\n df['r'] = np.sqrt(df['x']**2 + df['y']**2)\n df.loc[df['r'] <= 1, 'Location'] = 'Inside'\n df.loc[df['r'] > 1, 'Location'] = 'Outside'\n df.loc[df['r'] <= 1, 'Color'] = 'green'\n df.loc[df['r'] > 1, 'Color'] = 'red'\n df['piEstimate'] = 4*(df['Location'] == 'Inside').cumsum()/(df.index-1) \n df['Error'] = 4*(df['Location'] == 'Inside').cumsum()/(df.index-1) - math.pi\n return df\n```\n\n\n```python\n\ndef MonteCarloAnimation(Ntrials):\n data=MonteCarloSim(Ntrials)\n\n plt.rcParams['axes.facecolor'] = plt.rcParamsDefault['axes.facecolor']\n plt.rcParams['axes.edgecolor'] = plt.rcParamsDefault['axes.edgecolor']\n plt.rcParams['axes.grid'] = plt.rcParamsDefault['axes.grid']\n plt.rcParams['grid.alpha'] = plt.rcParamsDefault['grid.alpha']\n plt.rcParams['grid.color'] = plt.rcParamsDefault['grid.color']\n\n circle = plt.Circle((0, 0), 1.0, color='g', linewidth=1, fill=False) ##define circle with built in circle object\n\n plotfunc = plt.figure(figsize=(10,10))\n plotfunc.subplots_adjust(top=0.8, wspace=0.025)\n plotfunc.tight_layout()\n\n ax1 = plt.subplot(111, xlim=(-1.0, 1), ylim=(-1.0, 1.0))\n ax1.add_patch(circle)\n\n scat = ax1.scatter(x=0, y=0, s=70, marker='o')\n\n # Animation update function\n def animationUpdate(k):\n x=list(data['x'])[:k]\n y = list(data['y'])[:k]\n scat.set_offsets(np.c_[x,y])\n scat.set_color(data['Color'][:k])\n return scat,\n\n # function for creating animation\n anim = FuncAnimation(plotfunc, animationUpdate, frames=Ntrials, interval=400, blit=True)\n\n # Set up formatting for the movie files\n Writer = animation.writers['ffmpeg']\n writer = Writer(fps=1, bitrate=10000)\n anim.save('animatedMonteCarlo.mp4', writer=writer)\n\n Video('animatedMonteCarlo.mp4')\n```\n\n\n```python\nMonteCarloAnimation(30)\n```\n\n\n```python\n!pwd\n```\n\n /Users/okara/Desktop/pythonMC_visual/Onur-MonteCarlo\r\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "61f1bd9555b49d2c469946159e24716da43997ed", "size": 48369, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Python/6. Simulations and Modeling/Monte-Carlo-Visualizations/MonteCarlo_develop.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/6. Simulations and Modeling/Monte-Carlo-Visualizations/MonteCarlo_develop.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/6. Simulations and Modeling/Monte-Carlo-Visualizations/MonteCarlo_develop.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": 48369.0, "max_line_length": 48369, "alphanum_fraction": 0.9261096984, "converted": true, "num_tokens": 1251, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.970687766704745, "lm_q2_score": 0.925229959153748, "lm_q1q2_score": 0.898109402739274}} {"text": "Probability is associated with at least one event. E.g.: rolling a die or pulling a coloured ball out of a bag\n\nOutcome of the event is random (can’t be sure of the outcome of the die will). \n\nHence the variable that represents the outcome of these events is called a random variable\n\n# A. 3 Types of Probability\n\n## Marginal Probability\n\nMarginal Probability is the probability of event A occurring, P(A). Rigorously written as P(X=A).\n\nExample: A pack of playing cards, the probability that a card drawn from a pack is red: P(X=red) = 0.5\n\n## Joint Probability\n\nJoint Probability is the probability ofntersection of two or more events. Written as $ P(A \\cap B) , P(A,B), P(A\\ and\\ B)$\n\nExample: Probability that a card drawn from a pack is red and 4 is P(red and 4) = 2/52 = 1/26\n\nNOTE: Joint probability is symmetrical P(A,B) = P(B,A)\n\n## Conditional Probability\n\nConditional probability is the probability of an event(s) occuring given that we know other events have already occurred. If A and B are two events then the conditional probability of A occurring given that B has occurred is written as P(A|B)\n\nExample: Probability that a card is a four given that we have drawn a red card is P(4|red) = 2/26 = 1/13\n\n# B. Linking the 3 types of Probability\n\nThis is the equation linking the 3 probabilities\n\\begin{equation}\n\\begin{aligned}\nP(A | B) = \\dfrac{P(A \\cap B)}{P(B)}\n\\end{aligned}\n\\tag{Equation B.1}\n\\end{equation}\n\n### Intutition\n\nWe start with. This is logical.\n\\begin{equation}\n\\begin{aligned}\nP(A \\cap B) = P(B)\\,P(A \\mid B)\n\\end{aligned}\n\\tag{Equation B.2}\n\\end{equation}\n\nRearranging eq B.2, we get the following\n\n\\begin{equation}\n\\begin{aligned}\nP(A \\cap B) = P(A \\mid B)\\,P(B)\n\\end{aligned}\n\\tag{Equation B.3}\n\\end{equation}\n\\begin{align}\n\\end{align}\n\nRearranging further we get the first equation B.1\n\n# C. Special Case of Joint Probabilities for Independent Events\n\nWhen two events A and B are independent, P(A | B) = P(A)\nUsing this in equation B.3 we get\n\n\\begin{equation}\n\\begin{aligned}\nP(A \\cap B) = P(A)\\,P(B)\n\\end{aligned}\n\\tag{Equation C.1}\n\\end{equation}\n\\begin{align}\n\\end{align}\n\n# D. Additive rule of Probability\n\nAddition is used in OR scenario we have to add the individual probabilities and subtract the intersection\n\n\\begin{equation}\n\\begin{aligned}\nP(A \\cup B) = P(A) + P(B) - P(A \\cap B)\n\\end{aligned}\n\\tag{Equation D.1}\n\\end{equation}\n\\begin{align}\n\\end{align}\n\nIf you visualize Venn Diagram, then adding P(A) and P(B) accounts for adding the intersection twice. One of this has to be removed. Hence the equation\n\n## D.1 Special case of Mutually exclusive events\nIn case of mutually exclusive events $ P(A \\cap B) = 0 $ and the above equation simplifies as \n\n\\begin{equation}\n\\begin{aligned}\nP(A \\cup B) = P(A) + P(B)\n\\end{aligned}\n\\tag{Equation D.2}\n\\end{equation}\n\\begin{align}\n\\end{align}\n\n\n# E. Bayes Theorem\n\nBayes theorem provides a mechanism to utilize prior knowledge to improve probability estimation\n\nE.g: \n\\begin{align*}\n\\text{Initially: P(Person has Cancer) = Percent of population with cancer}\n\\end{align*}\n\n\\begin{align*}\n\\text{Prior evidence: Person is smoker}\n\\end{align*}\n\n\\begin{align*}\n\\text{Modification: } P(\\text{Person has Cancer}\\, \\mid \\text{Person is smoker})\\, > \\, P(\\text{Person has Cancer)}\n\\end{align*}\n\n\n\\begin{equation}\n\\begin{aligned}\nP(A \\mid B) = \\dfrac{P(B \\mid A)\\,P(A)}{P(B)}\n\\end{aligned}\n\\tag{Equation E.1}\n\\end{equation}\n\nIt is also used when calculating one conditional propbability say P(A|B) is hard, but the converse conditional probability P(B|A) is easily found\n\nE.g.:\n1. Suppose there are 2 bowls - M and N. \n2. Bowl M has 5 Oranges and 8 Apples. \n3. Bowl N has 12 Oranges and 4 Apples\n\nWhat is probability of having picked from M, given than the picking was Apple ?\n\\begin{align*}\n\\text{Modification: } P(M \\mid Apple)\\, = \\, \\dfrac{P(Apple \\mid N)\\,P(M)}{P(Apple)}\n\\end{align*}\n\nHere, the P(LHS) is hard by itself. But all P() on RHS can be easily calculated. Hence its utlity\n\n## E.1 Derivation\n\nP(A,B) is equal to P(B,A). Combining b.2 and B.3 \n\\begin{equation}\nP(B)\\,P(A \\mid B) = P(A \\mid B)\\,P(B)\n\\end{equation}\n\nRe arranging, we get Bayes Theorem forumla shown in E.1\n\n## E.2 Bayesian Terminology\n\n1. P(A|B) is called the posterior; this is what we are trying to estimate. In the above example, this would be the “probability of having cancer given that the person is a smoker”.\n2. P(B|A) is called the likelihood; this is the probability of observing the new evidence, given our initial hypothesis. In the above example, this would be the “probability of being a smoker given that the person has cancer”.\n3. P(A) is called the prior; this is the probability of our hypothesis without any additional prior information. In the above example, this would be the “probability of having cancer”.\n4. P(B) is called the marginal likelihood; this is the total probability of observing the evidence. In the above example, this would be the “probability of being a smoker”. In many applications of Bayes Rule, this is ignored, as it mainly serves as normalization.\n\n\\begin{align*}\nP(A \\mid B)\\, \\propto \\,P(B \\mid A)\\,P(A)\n\\end{align*}\n\n# Acknowledgements\n1. Probability Basics Explanation https://towardsdatascience.com/probability-concepts-explained-introduction-a7c0316de465\n2. https://machinelearningmastery.com/joint-marginal-and-conditional-probability-for-machine-learning/\n3. https://towardsdatascience.com/what-is-bayes-rule-bb6598d8a2fd\n4. https://machinelearningmastery.com/bayes-theorem-for-machine-learning/\n5. https://towardsdatascience.com/maximum-likelihood-vs-bayesian-estimation-dd2eb4dfda8a\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "49ff1b642b8b68e1042b890672b0defc3b813e09", "size": 8396, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Bayesian/01-Probability_Intro.ipynb", "max_stars_repo_name": "datavector-io/datascience", "max_stars_repo_head_hexsha": "b1de0cd1c563b3c90d3f4382f0130c77e18308f9", "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": "Bayesian/01-Probability_Intro.ipynb", "max_issues_repo_name": "datavector-io/datascience", "max_issues_repo_head_hexsha": "b1de0cd1c563b3c90d3f4382f0130c77e18308f9", "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": "Bayesian/01-Probability_Intro.ipynb", "max_forks_repo_name": "datavector-io/datascience", "max_forks_repo_head_hexsha": "b1de0cd1c563b3c90d3f4382f0130c77e18308f9", "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.4098360656, "max_line_length": 272, "alphanum_fraction": 0.5782515484, "converted": true, "num_tokens": 1662, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422227627598, "lm_q2_score": 0.9441768549384141, "lm_q1q2_score": 0.898046472487275}} {"text": "# Optimization Exercise 1\n\n## Imports\n\n\n```python\n%matplotlib inline\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport scipy.optimize as opt\n```\n\n## Hat potential\n\nThe following potential is often used in Physics and other fields to describe symmetry breaking and is often known as the \"hat potential\":\n\n$$ V(x) = -a x^2 + b x^4 $$\n\nWrite a function `hat(x,a,b)` that returns the value of this function:\n\n\n```python\ndef hat(x,a,b):\n return -1*a*(x**2) + b*(x**4)\n```\n\n\n```python\nassert hat(0.0, 1.0, 1.0)==0.0\nassert hat(0.0, 1.0, 1.0)==0.0\nassert hat(1.0, 10.0, 1.0)==-9.0\n```\n\nPlot this function over the range $x\\in\\left[-3,3\\right]$ with $b=1.0$ and $a=5.0$:\n\n\n```python\na = 5.0\nb = 1.0\n```\n\n\n```python\nx = np.linspace(-3,3,100)\nv = hat(x,a,b)\ngraph = plt.plot(x,v)\n\n```\n\n\n```python\nassert True # leave this to grade the plot\n```\n\nWrite code that finds the two local minima of this function for $b=1.0$ and $a=5.0$.\n\n* Use `scipy.optimize.minimize` to find the minima. You will have to think carefully about how to get this function to find both minima.\n* Print the x values of the minima.\n* Plot the function as a blue line.\n* On the same axes, show the minima as red circles.\n* Customize your visualization to make it beatiful and effective.\n\n\n```python\nf = lambda g: hat(g,a,b)\nx1 = float(opt.minimize(f,-2 ).x)\nx2 = float(opt.minimize(f,2 ).x)\nprint(x1)\nprint(x2)\ngraph = plt.plot(x,v)\nplt.plot([x1,x2],[f(x1),f(x2)],'ro')\n```\n\n\n```python\nassert True # leave this for grading the plot\n```\n\nTo check your numerical results, find the locations of the minima analytically. Show and describe the steps in your derivation using LaTeX equations. Evaluate the location of the minima using the above parameters.\n\n\\begin{align}\nV(x) = -a x^2 + b x^4 \\\\\nx(4bx^2-2a) = 0 \\\\\n4bx^2=2a \\\\\nx = \\pm \\sqrt{\\frac{a}{2b}} \\\\\nx = \\pm \\sqrt{\\frac{5}{2(1)}} \\approx \\pm 1.5811388\n\\end{align}\n\n", "meta": {"hexsha": "5b6244707faf255771727f22e8b628c14aeefd3f", "size": 28816, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "assignments/assignment11/OptimizationEx01.ipynb", "max_stars_repo_name": "joshnsolomon/Josh-Solomon-PHYS-202-work", "max_stars_repo_head_hexsha": "919bb26416af0e81ca9724d5991e041dbd79d164", "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/assignment11/OptimizationEx01.ipynb", "max_issues_repo_name": "joshnsolomon/Josh-Solomon-PHYS-202-work", "max_issues_repo_head_hexsha": "919bb26416af0e81ca9724d5991e041dbd79d164", "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/assignment11/OptimizationEx01.ipynb", "max_forks_repo_name": "joshnsolomon/Josh-Solomon-PHYS-202-work", "max_forks_repo_head_hexsha": "919bb26416af0e81ca9724d5991e041dbd79d164", "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": 95.417218543, "max_line_length": 11342, "alphanum_fraction": 0.8515408107, "converted": true, "num_tokens": 621, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.945801274759925, "lm_q2_score": 0.9489172590702516, "lm_q1q2_score": 0.897487153270338}} {"text": "# Solving Multiple Equations/Multiple Unknowns in SymPy\n\nJoseph C. Slater, Oct. 2018\n\n\n```python\n# import symbolic capability to Python\nfrom sympy import *\n\n# print things all pretty. Not as important in this notebook. \nfrom sympy.abc import *\ninit_printing()\n```\n\n\n```python\n# Need to define the variables as symbolic for sympy to use them. \nx, y = symbols(\"x, y\", real = True)\n```\n\nAll of this is based on using the [general symbolic solvers](https://docs.sympy.org/latest/modules/solvers/solvers.html). They are not as robust as putting things in matrix form. A function to do that wouldn't be too hard, but would take a couple hours to make.\n\nLet's do a simple test case.\n\n$$ x^4 = 4$$\n\nNote that we have to solve it to be equal to zero, so we use the form\n\n$$x^4-4=0$$\n\n\n```python\nequation = x**2 - 4\nsolve(equation, x)\n```\n\nThat worked. Let's make some equation. I'm going to store them in variable to make this easier to keep track of. \n\nHere we have\n\n$$3x + 4y - 5 = 0$$\n\n\n```python\nequation1 = 3*x + 4*y - 5\nequation1\n```\n\nNow we have\n\n$$\n6x+7y-8=0\n$$\n\n\n```python\nequation2 = 6*x + 7*y - 8\nequation2\n```\n\n``solve`` would like to be told which variables to solve for, but it can usually make a reasonable guess. \n\nThe (seemingly) extra parentheses are because there is only a single argument being sent in, the list of equations: ``(equation1, equation2)``. \n\n\n```python\nsolve((equation1, equation2))\n```\n\nBelow I'm more explicit in sending it two arguments (two lists), the first is a list of equations, the second is a list of variables to solve for. \n\n\n```python\nsolve((equation1, equation2), (x, y))\n```\n\n\n```python\nchecksol(equation1, {x: -1, y: 2})\n```\n\n\n\n\n True\n\n\n\nIf the second equation had been nonlinear, such as\n\n$$6x+7y^2-8=0$$\n\n\n```python\nequation2 = 6*x + 7*y**2 - 8\nequation2\n```\n\nWe now get multiple solutions:\n\n\n```python\nans = solve((equation1, equation2))\nans\n```\n\nEngineers like decimals in most cases, so, if any number given were a float, we wouldn't get the square roots and all. \n\n\n```python\nequation2 = 6*x + 7*y**2 - 8.0\nequation2\n```\n\n\n```python\nsolve((equation1, equation2))\n```\n\nWe can create an equation with two sides by using the ``Eq`` command as below. \n\n\n```python\nequation2 = Eq(6*x + 7*y**2 , 8.0)\nequation2\n```\n\n\n```python\nsolve((equation1, equation2))\n```\n", "meta": {"hexsha": "99ae3c7d951014ad75e899b91ee55c8cc8fadb6d", "size": 29255, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Solving_Multiple_Symbolic_Algebraic_Equations.ipynb", "max_stars_repo_name": "josephcslater/JupyterExamples", "max_stars_repo_head_hexsha": "4f2af75b9fda80dcab6cac0b9210713eeb703839", "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": "Solving_Multiple_Symbolic_Algebraic_Equations.ipynb", "max_issues_repo_name": "josephcslater/JupyterExamples", "max_issues_repo_head_hexsha": "4f2af75b9fda80dcab6cac0b9210713eeb703839", "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": "Solving_Multiple_Symbolic_Algebraic_Equations.ipynb", "max_forks_repo_name": "josephcslater/JupyterExamples", "max_forks_repo_head_hexsha": "4f2af75b9fda80dcab6cac0b9210713eeb703839", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-02-07T20:28:39.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-07T20:28:39.000Z", "avg_line_length": 58.51, "max_line_length": 4088, "alphanum_fraction": 0.787113314, "converted": true, "num_tokens": 704, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.949669363129097, "lm_q2_score": 0.9449947120938248, "lm_q1q2_score": 0.897432526394507}} {"text": "# Generating Fractals\n\nHere we will be generating fractals and learning about a few things as well\n\n1. Complex numbers (very breifly) \n2. Root finding (this is a good primer for gradient decent for those of you with ML on the mind) \n3. Thinking iteratively ( very important nor numerical mathematics) \n\n## Complex Numbers\n\nBefore we start talking about fractals, we should probably introduce the idea of a complex number before hand, as the fractas we will be generating rely heavily on them. I'll note that this may get kind of deep into some mathematics, and if you want to skip this section you totally can. There are som quirks to complex numbers, but luckily Python will handle them for you, and realistically they will behave like any other number in Python (for our purposes).\n\nFirst and foremost, let us introduce the complex number $i$\n$$\n\\begin{equation}\ni = \\sqrt{-1} \\implies i^2 = -1\n\\end{equation}\n$$\n\nwhere $i$ is known as the imaginary number, or a number that when multiplied by itself, returns a negative number, an impossible situation in the real numbers (the set of numbers including integers, natural numbers, rational and irrational numbers). At first this might be concerning, but we must remember that when it comes to math, there is no concensus on whether math is discovered or invented. People thought [mathematicians who suggested working with complex numbers were crazy](https://medium.com/i-math/imaginary-numbers-explained-e5aa63bdb7ae), only for time to reveal that complex number were applicable in many areas, including [electrical engineering](https://www.electronics-tutorials.ws/accircuits/complex-numbers.html).\\\nMore often than not, we will write a complex number as $z$, which is written as the sum of an imaginary numers real and complex parts, \n\n$$\nz = a + ib\n$$\nwhere $a$ is the real part of the complex number $z$, and $b$ is another real number, multiplied by the imaginary unit $i$ representing the imaginary part of the number. \n\nIf you're curious, you can get more details about complex numbers using the drop down below. For our purposes however, all that you really need to know is the following:\n\n1. A complex number $a + ib$ can be thought of as the classical $x,y$ ordered pair we're used to. In this case our $x$ axis is the real part of the number, and our $y$ axis is the imaginary part of the number\n\n2. These $(a, b)$ ordered pairs can be used to define the \"complex plane\", which we will use to plot our fractals\n\n
\n

More details on complex numbers (not required)

\n\n
\nThere are a lot of very useful properties that come from imaginary numbers, and they're used all the time in fiels such as pure mathematics, signal processing, physics, chemistry, fluid dynamics... in principle we could go on forever. The largest reason for this is due to something known as [eulers formula](https://en.wikipedia.org/wiki/Euler%27s_formula), where we instead think of complex numbers on the \"complex plane\", with the real part of the function $a$ representing our $x$ axis, and the imaginary part of our function $b$ on the $y$ axis. Euler's formula states that we can write the exponential of a complex number as follows\n\n$$\ne^{ix} = r (\\cos \\theta + i\\sin \\theta)\n$$\nwhere $r$ is the radius of tihs circle on the complex plane (more on this later).\nFor those of you mathematically inclined and want to prove this, the easiest way is to write out the Taylor series for each $e^{ix}, i\\sin \\theta$ and $\\cos \\theta$, and you may be surprised what you see. \n\nLong story short, using Euler's formula, we can essentially write any complex number in terms of sine and cosine, this is useful for a whole lot of reasons, but for fractals specificially, this implies periodic boundary conditions -- we expect to see repeating patterns. Indeed, as cosine and sine have $N$ roots repeating every $\\pi$, we expect that our complex functions may also have (up to) that many roots!\n\n\n\n\n### Finding Roots Of Complex Polynomials\n\nWe all remember polynomial equations of real numbers, for example the quadratic function\n\n$$\nx^2 - C = 0\n$$\nwhere we can all read quite readily that the solution to this equation is $x = \\pm \\sqrt{C}$. But what about if we have some complex polynomial like\n\n$$\nz^2 + C = 0,\n$$\n\nTo be honest, I pulled a fast one on you. It' just as easy! In this case, we have two roots which are $\\pm i \\sqrt{C} $, where we just bring our friend the imaginary unit along for the ride. In principle what we do is we once again factor this into the real and imaginary part of the solution, but often it's easier to think of this (in a way that will make mathmaticians cry) we simply get rid of the part we don't like, and call it $i$. For quadratic complex polynomial equations, we can simply use the quadratic formula and sprinkle in the imaginary unit where ever we need it. This is a bit of an over simplification, but for our purposes it should be fine. \n\nWhere this can get a little spicier is when the roots aren't obvious enough to be read off. For example, the equation\n\n$$\nz^3 = 1,\n$$\n\nis cubic, which means we have three distinct roots which satisfy this equation. In this case, it is easier to look at our friend Euler's formula to find these roots. So let's rewrite our complex equation above using euler's formula. First, the left hand side\n\n$$\nz = r e^{ix} \\implies z^3 = r^3 e^{3ix}\n$$\n\nand the right hand side:\n\n$$\n1 = re^{ix} = r (\\cos \\theta + i\\sin \\theta)\n$$\n\nWhere, as one has no complex component, we know that this must be one. Therefore, $r$ is equal to one in this equation, angles are those where cosine is one and sine is zero, or $\\theta = 2\\pi k$ where $k$ is an integer. Therefore, we have \n\n$$\ne^{3ix} = e^{2\\pi k}\n$$\n\nor by taking the natural logarithm of each side,\n\n$$\nix = \\frac{2 \\pi k}{3} \n$$\n\nAnd going back to our original equation:\n\n$$\nz = e^{ix} = e^{\\frac{2 \\pi k}{3}}\n$$\n\nWhere we can take our first three roots as $k = -1, 0, 1$ and obtain\n\n$$\nz = 1, e^{2\\pi i/3}, e^{-2\\pi i/3}\n$$\n\nWe also note we have periodic roots at integer values of $k$, but we won't worry about those. Knowing these roots are useful in terms of understanding the behaviour of our fractals. We may expect that different roots may cause different basins of convergence, or result in rotations of our fractal. This is also important with respect to establishing the domains in which our fractals may exist.\n
\n\n# Root Finding With Complex Numbers\n\nIf you were crazy enough to read the drop down menu, you may have noticed that finding roots to complex equations were more work that the quadratic formula. And if you take anything away from these notebooks it should be that we Data Scientists (and regular scientists) are _super_ lazy. Wouldn't it be nice if we could use our computer to solve these for us? Luckily, the answer is a resounding yes! And even more better is that our Newton Raphson formula from before generalizes to the complex domain without us having to do anything. Convenient! \n\nOne thing to be aware of however in Python is we will need to define complex numbers. It's quite simple. For a complex number $ a + ib$, we can define that in python like\n\n```python3\na = b = 1\ncomplex_number = complex(a, b)\n```\n\nand we can then throw that number at our root finding routines as we did before and find ourselves solutions.\n\n## My First Fractal: Mandelbrot\n\nBefore we go into root finding for fractals, let's start with a relatively simple one to generate the Mandelbrot. Rather than have me drone on for a year, here's a YouTube video that does a better job than I could explaining that set. \n\n\n```python\nfrom IPython.display import YouTubeVideo\nYouTubeVideo('NGMRB4O922I')\n```\n\n# Your Task\n\nWrite two functions, the first function will be to calculate the Mandelbrot set as follows\n\n### Mandelbrot Function\n1. Initialize $z$ and the number of iterations $n$ as zero,\n - Also intialize the maximum iterations as 80\n2. while `abs(z) <= 2 and n < max_iter` do the following\n * $z = z^2 + c$\n * n += 1\n3. On exit, return the number of iterations $n$\n\n\n```python\n# note the **kwargs is not strictly necessary, and won'tdo anything here, but will be useful\n# if you want to use some of the provided functions later. \n\ndef mandelbrot(c, max_iter = 80, **kwargs):\n '''\n here c is any complex number, and max_iter is the maximum numberof iterations through your loop\n you want to go\n '''\n z = # YOUR CODE HERE\n n = # YOUR CODE HERE\n while CONDITION: # YOUR CODE HERE\n z = SOMETHING #YOUR CODE HERE\n n += 1\n \n return n\n \n```\n\n### Iteration Function\n\nYou will also need a function which iterates across the complex plane to see what pixel you should generate there. This function itself will require three functions\n\n1. A scale function to convert pixel location into complex coordinates\n2. A scale function to convert the number of itereations in your `mandelbrot` function into an RGB color scale\n3. A function which iterates over pixels with a given height and width for your image. \n\nIn principle we will have the following pseudocode for point 3 which will encompass the other functions\n\n---\n```python\ndef CreateImage(mandelbrot, height, width, domain):\n\n ImageMap = np.zeros([width, height])\n \n for x in range(0, width):\n for y in range(0, height):\n \n c = scale_function_coordinate(x, y, width, height, real_max, real_min, complex_max, complex_min)\n \n m = mandelbrot(c)\n \n color = color_function(m)\n \n X[x,y] = color\n \n return ImageMap\n \n```\n---\nWhere let's outline those functions explicitly \n\n##### Pixel Scale Function\n\nGiven a pixel coordinate $x$ and $y$, we need to convert this location into a complex number within our domain. the formula for this is as follows\n\n$$\nR = R_{min} + \\frac{x}{\\text{Image Width}} \\times (R_{max} - R_{min})\n$$\n\nWhere $R$ is your value in the real coordinate, $R_{min}$ is the smallest value in the real domain, and $R_{max}$ is the largest value in the real domain, $x$ is the current pixel, and Image Width is the width of the image in pixels you want to create. A similar formula for the complex domain is as follows \n\n$$\nC = C_{min} + \\frac{x}{\\text{Image Height}} \\times (C_{max} - C_{min})\n$$\n\nWhere $C$ is your value in the complex coordinate, $C_{min}$ is the smallest value in the complex domain, $C_{max}$ is the largest value in the complex domain, $x$ is the current pixel, and Image Height is the height of the image in pixels you want to create. \n\nIn this case, if we have a known image size in advance, and we know the domain in which our fractal will exist, we can calculate the complex value $c$ at this place in our image. Please fill in the function below\n\n\n```python\nimport numpy as np\ndef scale_function_coordinate(x, y, width, height, r_max, r_min, c_max, c_min):\n '''\n x --> x coordnate of pixel\n y --> y coordinate of pixel\n \n width --> width of image\n height --> height of image\n \n r_max, r_min --> maximum and minimum numbers on thereal axis\n c_max, c_min --> maximum and minimum numbers on the complex axis\n '''\n \n R = None # YOUR CODE HERE\n C = None # YOUR CODE HERE\n \n return complex(R, C) # complex is a built in function for complex numbers\n \n \n```\n\n##### Color Function\n\nNow we need to be able to convert the number of iterations to an RGB coordinate. RGB colors can take values between 0 and 255, so we need to find a way to scale our number of iterations to become some pretty colors so we can observe the changes. Rather than boring you with this, I'll just provide the function \n\n\n```python\ndef color(number_of_iterations):\n return 255 - int(m * 255/max_iter)\n\n```\n\n## Putting it All Together\n\nIf that worked out well for you, you should be able to fill in the following to create your image functions!\n\n\n\n```python\n# Boundaries for the mandelbrot function \nbounds = [-2, 1, -1, 1]\n\ndef CreateImage(function, width, height, bounds): \n r_max, r_min, c_max, c_min = bounds\n\n if width > 1000:\n print(f'width of {width} is too large. Your computer only has so many pixels.')\n print(\"try zooming in with a smaller boundary to observe more detail\")\n return\n \n if height > 1000:\n print(f'height of {height} is too large. Your computer only has so many pixels.')\n print(\"try zooming in with a smaller boundary to observe more detail\")\n return\n \n X = np.zeros(width, height)\n \n for x in range(0, width):\n for y in range(0, height):\n c = scale_function_coordinate(x, y, width, height, r_max, r_min, c_max, c_min)\n \n # Note here for changes later for root finding \n m = function(c)\n color = color(m)\n X[width, height] = color\n \n return X\n\n# When you're ready uncomment this line to see if it worked\n\n# plt.imshow(X)\n```\n\nIf all that worked out, running the above cell should produce what you see below!\n\n\n```python\nimport sys\nsys.path.append('scripts/')\nimport fractalfuncs as FF\nimport matplotlib.pyplot as plt\n\nbounds = [-2, 1, -1, 1]\nX = FF.CreateImageMap(function = FF.mandelbrot, function_args = {}, bounds = bounds) \nplt.imshow(X, extent=bounds)\nplt.xlabel(\"Real Axis\", size = 12)\nplt.ylabel(\"Imaginary Axis\", size = 12)\nplt.show()\n```\n\n# Using Rootfinding\n\nNow, rather than using the mandelbrot set, let's try and use our root finding techniques to find roots instead! If we're in a stable region,it should be pretty easy! If not, it will get spicy and diverge. We will use that divergence to create our fractals instead. Here the fractal properties not only come from the mathematical formulation of our complex set, but also the convergence properties of our root finder: different root finding techniques will result in different fractals.\n\n## Your Task\n\nCopy and paste your NewtonRaphson root finder from the Root Finding portion of this, and use it in this assignment. **NOTE** instead of returning the root, you will have to modify your NewtonRaphson function to return the number of iterations it took.\n\nTo use root finding, we will do exactly what we did for the mandelbrot set above, however, we will now modify your image generation function to use $c$ as an initial guess at your solution, and see if your NewtonRaphson root finder can find a solution or not. You will need to modify the cell below for use with your own function. Remember that you will also need to pass the derivative and the function you are evaluating (Hint: `**kwargs` can be handy here) \n\n\n\n```python\ndef CreateImageRootFinding(YOUR ARGUMENTS HERE, width, height, bounds): \n r_max, r_min, c_max, c_min = bounds\n\n if width > 1000:\n print(f'width of {width} is too large. Your computer only has so many pixels.')\n print(\"try zooming in with a smaller boundary to observe more detail\")\n return\n \n if height > 1000:\n print(f'height of {height} is too large. Your computer only has so many pixels.')\n print(\"try zooming in with a smaller boundary to observe more detail\")\n return\n \n X = np.zeros(width, height)\n \n for x in range(0, width):\n for y in range(0, height):\n INITIAL_GUESS = scale_function_coordinate(x, y, width, height, r_max, r_min, c_max, c_min)\n \n # Note you may need to wrap this in try/except to prevent accidental zero division/other nastiness\n m = MY_ROOT_FINDER(INITIAL_GUESS)\n color = color(m)\n X[width, height] = color\n \n```\n\n## First Fractal With Root Finding\n\nThe mandelbrot set works well for what it is, but alas, if you try to use thet function in root finding, you will find that your fractal is dreadfully boring. A more interesting function is\n\n$$\nf(z) = z^3 - 1\n$$\n\nWhose derivative is\n\n$$ \nf^\\prime(z) = 3z^2\n$$\n\n### Sanity Check\n\nSee if you can reproduce the image below with your own function\n\n\n```python\nimport importlib\nimportlib.reload(FF)\ndef function(z):\n # All this extra stuff on top is if you want \n # to use this with numerical derivatives as shown below\n rlist = False\n if isinstance(z, list):\n rlist = True\n z= z[0]\n if rlist:\n return [z**3 - 1]\n # If you're using analytical derivatives, you just need this line at the bottom.\n return z**3 - 1\n\ndef derivative(z):\n ans = FF.nderiv(function, [z])\n\n return ans#3 * z ** 2 \n\nbounds = [-1,1, -1, 1]\n\nnewton_args = dict(fprime = derivative, f = function, max_iter = 50, prec = 1e-5)\nX = FF.CreateImageMap(FF.NewtonRaphsonFact, newton_args, bounds, height=200, width=200)\n\nplt.imshow(X, extent=bounds)\nplt.xlabel(\"Real Axis\", size = 12)\nplt.ylabel(\"Imaginary Axis\", size = 12)\nplt.show()\n```\n\nUsing the function above, try playing around with the following: \n\n1. Different powers of $z$ \n2. Change the constant (-1) term. Larger/Smaller positive/negative. What if this term is complex?\n\nWhat do you observe about the fractal at higher powers and different values of the constant\n\n# Other Functions To Try\n\nOnce you've got that working, you should try these functions as well and see what fractals you observe!\n\n$$\n\\begin{aligned}\nf(z) &= \\sin(z), x \\in \\left[-\\frac{\\pi}{2} - \\frac{1}{2}, -\\frac{\\pi}{2} + \\frac{1}{2}\\right], y\\in \\left[-0.3, 0.3\\right] \\\\\nf(z) &= \\cosh(z) - 1, x \\in \\left[-0.2, 0.2\\right], y \\in \\left[-\\pi, -\\pi -\\frac{\\pi}{8}\\right]\\\\\nf(z) &= z^3 - 3^z, x\\in [-10, 10], y\\in[-10, 10]\n\\end{aligned}\n$$\n\nNote that if you don't know how to calculate a derivative, that's okay, you can use wolfrapmalpha, or alternatively, you can take them numerically with a function i've provided. It can be used as follows\n\n```python\n# Only if you haven't imported it already\nimport sys\nsys.path.append('scripts/')\nimport fractalfuncs as FF\ndef myfunction(z):\n return z**2 # for example\n\ndef myderivative(z):\n return FF.nderiv(myfunction, z)\n```\nI note that numerical derivatives are always worse than analytic ones, but that's okay for now. If anyone is interested I can talk about how that works later as well. \n\n## Bored of that? \n\nIf you're bored, you can also try other root finding techniques instead of your newton solver! Here are some suggestions\n\n1. [Secant Method](https://en.wikipedia.org/wiki/Secant_method#:~:text=In%20numerical%20analysis%2C%20the%20secant,difference%20approximation%20of%20Newton's%20method.)\n2. [Halley's Method](https://en.wikipedia.org/wiki/Halley%27s_method#:~:text=In%20numerical%20analysis%2C%20Halley's%20method,Householder's%20methods%2C%20after%20Newton's%20method.)\n3. [Schroder's Method](https://mathworld.wolfram.com/SchroedersMethod.html)\n\nNote that these fractals are getting created with based on convergence properties of the above solvers. For example, the cells below outline the same function we used originially, just with their different methods of solving!\n\n\n```python\ndef function(z):\n return z**3 - 1\n\ndef derivative(z):\n return 3 * z ** 2\n\ndef secondder(z):\n return 6 * z\n\nbounds = [-1,1,-1,1]\nsecant_args = dict(function = function, mult = 0.5)\nX = FF.CreateImageMap(FF.secantfact, secant_args, bounds, height=100, width=100)\nplt.imshow(X, extent=bounds)\nplt.xlabel(\"Real Axis\", size = 12)\nplt.ylabel(\"Imaginary Axis\", size = 12)\nplt.show()\n```\n\n\n```python\nbounds = [-1,1,-1,1]\nschroder_args = dict(derivative = derivative, function = function,\n secondder=secondder, prec = 1e-6, max_iter = 50)\nX = FF.CreateImageMap(FF.schroderfact, schroder_args, bounds, height=100, width=100)\nplt.imshow(X, extent=bounds)\nplt.xlabel(\"Real Axis\", size = 12)\nplt.ylabel(\"Imaginary Axis\", size = 12)\nplt.show()\n```\n\n\n```python\nbounds = [-1,1,-1,1]\nhalley_args = dict(derivative = derivative, function = function,\n seconder=secondder, prec = 1e-6, max_iter = 50)\nX = FF.CreateImageMap(FF.halleyfact, halley_args, bounds, height=100, width=100)\nplt.imshow(X, extent=bounds)\nplt.xlabel(\"Real Axis\", size = 12)\nplt.ylabel(\"Imaginary Axis\", size = 12)\nplt.show()\n```\n\nWhere you'll notice each root finding technique has different convergence criteria, so the fractals generated are all slightly different. If you try the other fractals listed, you'll notice tht their fractal patterns will show even more variation \n", "meta": {"hexsha": "fa1bb64b71daddf7439c34f64a27c0082132de7c", "size": 26759, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/fractals/Fractals.ipynb", "max_stars_repo_name": "cybera/mathscovery", "max_stars_repo_head_hexsha": "cd397264958fb50eb113abf015f503109586a8c3", "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": "notebooks/fractals/Fractals.ipynb", "max_issues_repo_name": "cybera/mathscovery", "max_issues_repo_head_hexsha": "cd397264958fb50eb113abf015f503109586a8c3", "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": "notebooks/fractals/Fractals.ipynb", "max_forks_repo_name": "cybera/mathscovery", "max_forks_repo_head_hexsha": "cd397264958fb50eb113abf015f503109586a8c3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-03-12T00:49:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-12T00:49:57.000Z", "avg_line_length": 43.5814332248, "max_line_length": 745, "alphanum_fraction": 0.6027504765, "converted": true, "num_tokens": 5221, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.958537730841905, "lm_q2_score": 0.9353465107426521, "lm_q1q2_score": 0.8965649219581552}} {"text": "# Potential flow\n\n\n## Potencial functions\n\n**Uniform flow**:\n\n$w = U\\exp{(-i\\alpha)}z$\n\n**Line source**:\n\n$w = \\dfrac{\\dot{Q}}{2\\pi}\\ln z$\n\n## Velocity fields\n\n$\\dfrac{dw}{dz} = u + iv$\n\n**Uniform flow:**\n\n$\\dfrac{dw}{dz} = U\\left(\\cos{\\alpha}-i\\sin{\\alpha}\\right)$ \n\n**Line source:**\n\n$\\dfrac{dw}{dz} = \\dfrac{\\dot{Q}}{2\\pi}\\dfrac{1}{z}$\n\n## Combine potentials \n\nConsider a potential flow with a sink at $(0,0)$ and a source at $(r,0)$, under the influence of a horizontal uniform flow going from left to right ($\\alpha = \\pi$). The potential that describes that system is given by:\n\n$w = w_{\\rm uniform} + w_{\\rm source} + w_{\\rm sink}$\n\nHence, \n\n$w = U\\exp{(-i\\alpha)}z + \\dfrac{\\dot{Q_{\\rm in}}}{2\\pi}\\ln (z-r) - \\dfrac{\\dot{Q_{\\rm out}}}{2\\pi}\\ln z$\n\n$w = -Uz + \\dfrac{\\dot{Q_{\\rm in}}}{2\\pi}\\ln (z-r) - \\dfrac{\\dot{Q_{\\rm out}}}{2\\pi}\\ln z$\n\nThe uniform flow component will represent the regional flow, which can be described using Darcy's law as $U=-K\\dot{I}$, where $K$ is the hydraulic conductivity (m/s) and $\\dot{I}$ is the water table gradient (m/m). The source and sink wells represent injection and extraction points, characterized by flow rates per unit depth $\\dot{Q_{\\rm in}}$ and $\\dot{Q_{\\rm out}}$ (m²/s). For an aquifer of depth $H$, the volumetric flow rate $Q$ is $\\dot{Q}=Q/H$. Now, the extraction rate can be expressed as a proportion to the injection rate as $Q_{\\rm out} = fQ_{\\rm in}$. With all this replacements, the potential function can be rewritten as:\n\n$w = K\\dot{I}z + \\dfrac{Q_{\\rm in}}{2\\pi H} \\left( \\ln(z-r) - f \\ln z \\right)$\n\nNotice that in our case, the gradient $\\dot{I}$ must be negative so the regional flow goes indeed from right to left. To avoid confusion, let's rewrite it in terms of the abs value of the gradient $I$:\n\n$w = -KIz + \\dfrac{Q_{\\rm in}}{2\\pi H} \\left( \\ln(z-r) - f \\ln z \\right)$\n\n## Velocity field \n\n$\\dfrac{dw}{dz} = \\dfrac{d}{dz}\\left(-KIz + \\dfrac{Q_{\\rm in}}{2\\pi H} \\left( \\ln(z-r) - f \\ln z \\right)\\right)$\n\n$\\dfrac{dw}{dz} = -KI + \\dfrac{Q_{\\rm in}}{2\\pi H} \\dfrac{d}{dz}\\left( \\ln(z-r) - f \\ln z \\right)$\n\n$\\dfrac{dw}{dz} = -KI + \\dfrac{Q_{\\rm in}}{2\\pi H} \\left(\\dfrac{1}{z-r} - \\dfrac{f}{z} \\right)$\n\n## Velocity at the midpoint\n\nWe'll pick the velocity in the midpoint between the extraction and injection points as the characteristic velocity of the system. This means that we want to evaluate the velocity field at $z = r/2 + 0i$\n\n\\begin{equation}\n\\begin{array}{rl}\n \\dfrac{dw}{dz}\\bigg\\rvert_{z=r/2+0i} =& -KI + \\dfrac{Q_{\\rm in}}{2\\pi H} \\left(\\dfrac{1}{r/2-r} - \\dfrac{f}{r/2} \\right)\\\\\n =& -KI - \\dfrac{Q_{\\rm in}}{\\pi H} \\left(\\dfrac{1+f}{r}\\right)\n\\end{array}\n\\end{equation}\n\nNotice that this velocity can be split into the contribution of the regional flow and the contribution from the wells:\n\n\\begin{equation}\n\\begin{array}{rl}\n w'_{\\rm regional} =& -KI \\\\\n w'_{\\rm wells} =& -\\dfrac{1}{\\pi}\\dfrac{Q_{\\rm in} (1+f)}{r H}\n\\end{array}\n\\end{equation}\n\n\n### Non-dimensional flow number ($\\mathcal{F}_L$)\n\nA comparison between the component in the velocity due regional flow and the component due the wells as a ratio between them two. \n\n\\begin{equation}\n\\begin{array}{rl}\n\\mathcal{F}_L =& \\dfrac{\\text{Velocity due regional flow}}{\\text{Velocity due well couple}} \\\\\n=& \\dfrac{w'_{\\rm regional}}{w'_{\\rm wells}} \\\\\n=& \\dfrac{-KI}{-\\dfrac{Q_{\\rm in}}{2\\pi H} \\left(\\dfrac{1+f}{r}\\right)} \\\\\n=& \\dfrac{\\pi K I H r}{Q_{in}(1+f)}\n\\end{array}\n\\end{equation}\n\nIf $\\mathcal{F}_L \\to 0$, the flow induced by the wells rule the system, whereas if $\\mathcal{F}_L \\to \\infty$, the regional flow rule the system.\n\n## Minimum velocity along a streamline\n\nThe minimum velocity is found at:\n\n\\begin{equation}\n\\begin{array}{rl}\n \\dfrac{d}{dx}\\dfrac{dw}{dz}\\bigg\\rvert_{z=x+0i} =& 0 \\\\\n \\dfrac{d}{dx}\\left(-KI + \\dfrac{Q_{\\rm in}}{2\\pi H} \\left(\\dfrac{1}{x-r} - \\dfrac{f}{x} \\right)\\right) =& 0\\\\\n \\dfrac{Q_{\\rm in}}{2 \\pi H} \\dfrac{d}{dx}\\left(\\dfrac{1}{x-r} - \\dfrac{f}{x} \\right) =& 0\\\\\n \\dfrac{Q_{\\rm in}}{2 \\pi H} \\left(\\dfrac{f}{x^2} - \\dfrac{1}{\\left(x-r\\right)^2}\\right) =& 0\\\\\n \\\\\n \\dfrac{f}{x^2} =& \\dfrac{1}{\\left(x-r\\right)^2}\\\\\n x^2 =& f \\left( x-r \\right) ^2\\\\\n x =& \\dfrac{\\sqrt{f}}{\\sqrt{f}\\pm1}r\n \\\\\n x < r \\Rightarrow x =& \\dfrac{\\sqrt{f}}{\\sqrt{f}+1}r\n\\end{array}\n\\end{equation}\n\nDefining $m = \\dfrac{\\sqrt{f}}{\\sqrt{f}+1}$, evaluating at $z = mr + 0i$ gives the minimum velocity.\n\n\n\\begin{equation}\n\\begin{array}{rl}\n \\dfrac{dw}{dz}\\bigg\\rvert_{z=mr+0i} =& -KI + \\dfrac{Q_{\\rm in}}{2\\pi H} \\left(\\dfrac{1}{mr-r} - \\dfrac{f}{mr} \\right)\\\\\n =& -KI + \\dfrac{Q_{\\rm in}}{2 \\pi H} \\left(\\dfrac{m-fm+f}{m(m-1)}\\right)\\\\\n =& -KI - \\dfrac{Q_{\\rm in}}{2 \\pi H} \\left(\\dfrac{\\left(\\sqrt{f}+f\\right)\\left(\\sqrt{f}+1\\right)}{\\sqrt{f}}\\right)\\\\\n =& -KI - \\dfrac{Q_{\\rm in}}{2 \\pi H} \\left( \\left( 1+ \\sqrt{f}\\right)\\left( 1 + \\dfrac{\\sqrt{f}}{f} \\right) \\right)\\\\\n =& -KI - \\dfrac{ Q_{\\rm in}\\left( 1 + \\tfrac{\\sqrt{f}}{f} \\right) } {\\pi H r}\n\\end{array}\\\\\n\\end{equation}\n\nThis velocity can also be split into the contribution of the regional flow and the contribution from the wells:\n\n\\begin{equation}\n\\begin{array}{rl}\n w'_{\\rm regional} =& -KI \\\\\n w'_{\\rm wells} =& -\\dfrac{Q_{\\rm in} }{\\pi r H}\\left(1+\\tfrac{\\sqrt{f}}{f}\\right)\n\\end{array}\n\\end{equation}\n\n## Mean velocity along a streamline\n\nConsider the streamline that connects the sink and source points. It cannot be measured at those points because those are poles in the system, hence, some separation $\\delta$ from those points has to be considered: the well radius should be the straighforward election so we'll adopt it and assume that both injection and extraction wells have the same diameter.\n\nNow, with $z = x+iy$, the streamline exists at $y=0$ and $\\delta\",\n connectionstyle=\"angle,angleA=90,angleB=10,rad=5\")\n\nannotation = \\\n r\"$\\bf{-\\log(C/C_0)} = $\" + \"{:.1f}\".format(-np.log10(worstC)) + \\\n \"\\n@\" + r\" $\\bf{I} = $\" + \"{:.1E}\".format(worstI)\n\ninformation = \\\n r\"$\\bf{K}$\" + \" = {:.1E} m/s\".format(K) + \"\\n\"\\\n r\"$\\bf{H}$\" + \" = {:.1f} m\".format(H) + \"\\n\"\\\n r\"$\\bf{r}$\" + \" = {:.1f} m\".format(r) + \"\\n\"\\\n r\"$\\bf{Q_{in}}$\" + \" = {:.2f} m³/d\".format(Qin*86400) + \"\\n\"\\\n r\"$\\bf{f}$\" + \" = {:.1f}\".format(f) + \"\\n\"\\\n r\"$\\bf{\\lambda}$\" + \" = {:.2E} 1/s\".format(decayRate)\n\n# Ax1 - Relative concentration\nax = axs[1,0]\nax.plot(I,c1,label=\"Due decay\",lw=3,ls=\"dashed\",alpha=0.8)\nax.plot(I,c2,label=\"Due dilution\",lw=3,ls=\"dashed\",alpha=0.8)\n#ax.plot(I,np.minimum(c1,c2),label=\"Overall effect\",lw=3,c='k',alpha=0.9)\nax.plot(I,c3,label=\"Overall effect\",lw=3,c='k',alpha=0.9)\n\nax.set_xscale(\"log\")\nax.set_yscale(\"log\")\n\nax.set_ylim(1.0E-10,1)\nax.set_xlim(1.0E-4,1.0E-1)\n\nax.set_xlabel(\"Water table gradient\\n$I$ [m/m]\")\nax.set_ylabel(\"Relative Concentration\\n$C/C_0$ [-]\")\nax.legend(loc=\"lower left\",shadow=True)\n\nax.annotate(annotation,(worstI,worstC),\n xytext=(0.05,0.85), textcoords='axes fraction',\n bbox=bbox, arrowprops=arrowprops)\n\nax.text(0.65,0.05,information,bbox=bbox,transform=ax.transAxes)\nax.axvline(x=I[i], lw = 1, ls = \"dashed\", c = \"red\")\n\n####################################\n# Ax2 - log-removals\nax = axs[1,1]\nax.plot(I,-np.log10(c1),label=\"Due decay\",lw=3,ls=\"dashed\",alpha=0.8)\nax.plot(I,-np.log10(c2),label=\"Due dilution\",lw=3,ls=\"dashed\",alpha=0.8)\n#ax.plot(I,-np.log10(np.minimum(c1,c2)),label=\"Overall effect\",lw=3,c='k',alpha=0.9)\nax.plot(I,-np.log10(c3),label=\"Overall effect\",lw=3,c='k',alpha=0.9)\n\nax.set_xscale(\"log\")\nax.set_ylim(0,10)\nax.set_xlim(1.0E-4,1.0E-1)\nax.set_xlabel(\"Water table gradient\\n$I$ [m/m]\")\nax.set_ylabel(\"log-reductions\\n$-\\log(C/C_0)$ [-]\")\nax.legend(loc=\"lower right\",shadow=True)\n\nax.annotate(annotation,(worstI,-np.log10(worstC)),\n xytext=(0.05,0.10), textcoords='axes fraction',\n bbox=bbox, arrowprops=arrowprops)\n\nax.text(0.65,0.70,information,bbox=bbox,transform=ax.transAxes)\nax.axvline(x=I[i], lw = 1, ls = \"dashed\", c = \"red\")\n\n####################################\n#Ax3 - Flow number\nax = axs[0,1]\nax.plot(I,flowNumber(),label=\"flowNumber\",lw=3,c=\"gray\")\nax.axhline(y=1.0)\nax.set_xscale(\"log\")\nax.set_yscale(\"log\")\nax.xaxis.set_tick_params(which=\"both\",labeltop='on',top=True,bottom=False)\n\nax.set_ylabel(\"Nondim. flow number\\n$\\mathcal{F}_L$ [-]\")\nax.axvline(x=I[i], lw = 1, ls = \"dashed\", c = \"red\")\n\n#Ax4 - Flow number\nax = axs[0,0]\nax.plot(I,flowNumber(),label=\"flowNumber\",lw=3,c=\"gray\")\nax.axhline(y=1.0)\nax.set_xscale(\"log\")\nax.set_yscale(\"log\")\nax.xaxis.set_tick_params(which=\"both\",labeltop='on',top=True,bottom=False)\n\nax.set_ylabel(\"Nondim. flow number\\n$\\mathcal{F}_L$ [-]\")\nax.axvline(x=I[i], lw = 1, ls = \"dashed\", c = \"red\")\n\nplt.show()\n```\n\n____\n# Find the worst case \n## >> Geometric parameters $H$ and $r$\n\n\n```python\nfrom drawStuff import *\n```\n\n\n```python\nK = 10**-2\nQin = 0.24/86400\nf = 10\nC0 = 1.0\ndecayRate = 3.5353E-06\n\nHarray = np.array([2.,5.,10.,20.,50.])\nrarray = np.array([5.,10.,40.,100.])\nIarray = 10**np.linspace(-5,0,num=100)\n\nCi = np.zeros([len(rarray),len(Harray)])\nIi = np.zeros([len(rarray),len(Harray)])\nFLi = np.zeros([len(rarray),len(Harray)])\n\nfor hi,H in enumerate(Harray):\n for ri,r in enumerate(rarray):\n i = findSweet()\n\n worstC = -np.log10(cBoth()[i])\n worstGradient = Iarray[i]\n worstFlowNumber = flowNumber()[i]\n \n Ci[ri,hi] = worstC\n Ii[ri,hi] = worstGradient\n FLi[ri,hi] = worstFlowNumber\n```\n\n\n```python\nmyLabels={\"Title\": { 0: r\"$\\bf{-\\log (C_{\\tau}/C_0)}$\",\n 1: r\"$\\bf{I}$ (%)\",\n 2: r\"$\\log(\\mathcal{F}_L)$\"},\n \"Y\": \"Aquifer thickness\\n$\\\\bf{H}$ (m)\",\n \"X\": \"Setback distance\\n$\\\\bf{r}$ (m)\"}\n\nthreeHeatplots(data={\"I\":Ii.T,\"C\":Ci.T,\"FL\":FLi.T},\\\n xlabel=Harray,ylabel=rarray,myLabels=myLabels)\n```\n\n## >>Well parameters\n\n\n```python\nK = 10**-2\nH = 20\nr = 40\nC0 = 1.0\ndecayRate = 3.5353E-06\n\nQin_array = np.array([0.24,1.0,10.0,100.])/86400.\nf_array = np.array([1,10.,100.,1000.,10000.])\nIarray = 10**np.linspace(-5,0,num=100)\n\nCi = np.zeros([len(Qin_array),len(f_array)])\nIi = np.zeros([len(Qin_array),len(f_array)])\nFLi = np.zeros([len(Qin_array),len(f_array)])\n\nfor fi,f in enumerate(f_array):\n for qi,Qin in enumerate(Qin_array):\n i = findSweet()\n worstC = -np.log10(cBoth()[i])\n worstGradient = Iarray[i]\n worstFlowNumber = flowNumber()[i]\n \n Ci[qi,fi] = worstC\n Ii[qi,fi] = worstGradient\n FLi[qi,fi] = worstFlowNumber\n```\n\n\n```python\nmyLabels={\"Title\": { 0: r\"$\\bf{-\\log (C_{\\tau}/C_0)}$\",\n 1: r\"$\\bf{I}$ (%)\",\n 2: r\"$\\log(\\mathcal{F}_L)$\"},\n \"Y\": \"Extraction to injection ratio\\n$\\\\bf{f}$ (-)\",\n \"X\": \"Injection flow rate\\n$\\\\bf{Q_{in}}$ (m³/d)\"}\n\nthreeHeatplots(data={\"I\":Ii.T,\"C\":Ci.T,\"FL\":FLi.T},\\\n xlabel=f_array,ylabel=np.round(Qin_array*86400,decimals=2),myLabels=myLabels)\n```\n\n## Hydraulic conductivity\n\n\n```python\nQin = 0.24/86400\nf = 10\nC0 = 1.0\ndecayRate = 3.5353E-06\n\nKarray = 10.**np.array([-1.,-2.,-3.,-4.,-5.])\nrarray = np.array([5.,10.,40.,100.])\nIarray = 10**np.linspace(-5,0,num=100)\n\nCi = np.zeros([len(rarray),len(Karray)])\nIi = np.zeros([len(rarray),len(Karray)])\nFLi = np.zeros([len(rarray),len(Karray)])\n\nfor ki,K in enumerate(Karray):\n for ri,r in enumerate(rarray):\n i = findSweet()\n\n worstC = -np.log10(cBoth()[i])\n worstGradient = Iarray[i]\n worstFlowNumber = flowNumber()[i]\n \n Ci[ri,ki] = worstC\n Ii[ri,ki] = worstGradient\n FLi[ri,ki] = worstFlowNumber\n```\n\n\n```python\nmyLabels={\"Title\": { 0: r\"$\\bf{-\\log (C_{\\tau}/C_0)}$\",\n 1: r\"$\\bf{I}$ (%)\",\n 2: r\"$\\log(\\mathcal{F}_L)$\"},\n \"Y\": \"Hydraulic conductivity\\n$\\\\bf{K}$ (m/s)\",\n \"X\": \"Setback distance\\n$\\\\bf{r}$ (m)\"}\n\nthreeHeatplots(data={\"I\":Ii.T,\"C\":Ci.T,\"FL\":FLi.T},\\\n xlabel=Karray,ylabel=rarray,myLabels=myLabels)\n```\n\n>> EXPERIMENTAL\n\n\n```python\n\n```\n\n## r and Qin\n\n\n```python\nK = 10**-2\nH = 20\nf = 10\nC0 = 1.0\ndecayRate = 3.5353E-06\n\nQin_array = np.array([0.24,1.0,10.0,100.])/86400.\nrarray = np.array([5.,10.,40.,100.])\nIarray = 10**np.linspace(-5,0,num=100)\n\nCi = np.zeros([len(rarray),len(Qin_array)])\nIi = np.zeros([len(rarray),len(Qin_array)])\nFLi = np.zeros([len(rarray),len(Qin_array)])\n\nfor qi,Qin in enumerate(Qin_array):\n for ri,r in enumerate(rarray):\n i = findSweet()\n\n worstC = -np.log10(cBoth()[i])\n worstGradient = Iarray[i]\n worstFlowNumber = flowNumber()[i]\n \n Ci[ri,qi] = worstC\n Ii[ri,qi] = worstGradient\n FLi[ri,qi] = worstFlowNumber\n```\n\n\n```python\nmyLabels={\"Title\": { 0: r\"$\\bf{-\\log (C_{\\tau}/C_0)}$\",\n 1: r\"$\\bf{I}$ (%)\",\n 2: r\"$\\log(\\mathcal{F}_L)$\"},\n \"Y\": \"Injection flow rate\\n$\\\\bf{Q_{in}}$ (m³/d)\",\n \"X\": \"Setback distance\\n$\\\\bf{r}$ (m)\"}\n\nthreeHeatplots(data={\"I\":Ii.T,\"C\":Ci.T,\"FL\":FLi.T},\\\n ylabel=rarray,xlabel=np.round(Qin_array*86400,decimals=2),myLabels=myLabels)\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "96ebd40a8e71779a84c6b1d7037137930aadfd03", "size": 860736, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/Concepts/.ipynb_checkpoints/Potential flow-checkpoint.ipynb", "max_stars_repo_name": "edsaac/bioparticle", "max_stars_repo_head_hexsha": "67e191329ef191fc539b290069524b42fbaf7e21", "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/Concepts/.ipynb_checkpoints/Potential flow-checkpoint.ipynb", "max_issues_repo_name": "edsaac/bioparticle", "max_issues_repo_head_hexsha": "67e191329ef191fc539b290069524b42fbaf7e21", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-09-25T23:31:21.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-25T23:31:21.000Z", "max_forks_repo_path": "notebooks/Concepts/.ipynb_checkpoints/Potential flow-checkpoint.ipynb", "max_forks_repo_name": "edsaac/VirusTransport_RxSandbox", "max_forks_repo_head_hexsha": "67e191329ef191fc539b290069524b42fbaf7e21", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-09-30T05:00:58.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-30T05:00:58.000Z", "avg_line_length": 586.3324250681, "max_line_length": 128672, "alphanum_fraction": 0.9375139416, "converted": true, "num_tokens": 11716, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9736446502128796, "lm_q2_score": 0.9207896818685504, "lm_q1q2_score": 0.8965219477225335}} {"text": "## Regression\n\n$J=\\displaystyle \\sum_{i=1}^n(\\vec{p}\\cdot{\\vec{\\tilde{x_i}}}-y_i)^2$\n\n$\\displaystyle \\vec{p}^* = arg \\min_{\\vec{p}} J(\\vec{p})$\n\n$ \\displaystyle \\forall i :\\frac{\\partial J}{\\partial p_j}=0 \\;\\;\\quad \\frac{\\partial J}{\\partial p_j} =\\sum_{i=1}^n 2(\\vec{p}\\cdot{\\vec{\\tilde{x_i}}}-y_i)\\vec{\\tilde{x_i}}$\n\nsolution is $\\displaystyle \\quad \\vec{p}^*= (X^TX)^{-1}X^T\\vec{y}$\n\n\n\n**Over-determined**:\n\n$\\displaystyle \\quad arg \\min_{\\vec{p}}(||A\\vec{p}-\\vec{b}||_2 +\\lambda g(p)) $\n\n**Under-determined**:\n\n$\\displaystyle \\quad arg \\min_{\\vec{p}} g(p) \\quad$ subject to $||A\\vec{p}-\\vec{b}||_2\\le \\epsilon$\n\n## Loss\n\n$\\displaystyle L(\\hat{y},y)=\\frac{1}{N} \\sum_i (\\hat{y}_i -y_i)^2 \\quad$ MSE\n\n$\\displaystyle L(\\hat{y},y)=-(y \\,\\text{log}\\hat{y} +(1-y)\\,\\text{log}(1-\\hat{y})) \\quad $ Cross Entropy\n\n$\\displaystyle L(\\hat{y},y)=-\\sum_c(y_{o,c})\\,\\text{log}p_{o,c} \\quad $ Cross Entropy Multi class\n\n## Cost \n\n$\\displaystyle J(W,b) = \\frac{1}{M}\\sum_{i=1}^m L(\\hat{y}^{(i)},y^{(i)})$\n\n## Logistic Regression\n\nWe'll start with single neuron logistic regression using activation function **sigmoid**\n\n* Loss Cross Entropy\n* Maximum Likelihood\n* Convex Optimization\n\n### Computation Graph\n\n$\\hat{y} = \\sigma(\\vec{w}^T\\vec{x} + b) \\rightarrow $ cross entropy $\\rightarrow L(\\hat{y},y)$\n\n\n## Multiple Examples Training set\n\n* **Forward Propagation**: Computing the loss through forward pass for a single training example\n* **Backward Propagation**: Computing gradients of parameters through backward pass for a single training example $\\\\$\n\n* **Batch**: Traning set could be divided into smaller sets called batches\n* **Iteration**: When an entire batch is passed both forward and backward\n* **Epoch**: When an entire dataset is passed both forward and backward through the NN once\n\n## Multiple Outputs \nSigmoid -> softmax with one hot encoding\n\n$softmax (\\hat{y})_i= \\frac{e^{y_i}}{\\sum_ie^{y_i}}$\n\n## Other Loss/Activations\n* Changing **activation** will change the gradients\n\n* Changing **loss** will change the gradients and could make the composition unseparable\n\n* Most activations we discussed have analytic gradients. It is possible that there is no analytic expression. \n\n* Gradients could be evaluated numerically\n - When **analytic** expression is not available\n - When it is **faster** to evaluate them numerically\n \n* Use central difference formula \n* Check against analytic gradient for several examples\n\n\n\n\n## Curriculum Learning \n* Training machine learning models with particular order. Starting with easier subtasks and gradually increase the difficulty level of the tasks (For example, NLP problem learn words and then learn sentences)\n\n* Both traning set and cost functions are updated accordingly\n\n## Stochastic Gradient Descent\n\n**Almost surely convergence**\n\n* Performs an update for each training example $x^{(i)}$ and label $y^{(i)}$\n\n* The values of the loss and parameters will fluctuate\n - (+) will discover better minimums\n - (-) convergence to chosen minimum will keep overshooting\n\n* Learning rate plays a very important role\n\n## Mini-batch GD\n\n$$w_{k+1} =w_k -\\alpha \\cdot \\nabla_wJ(w;x^{(i:i+n)};y^{(i:i+n)})$$\n\n* Mini-batch GD is a hybrid method between GD and SGD. \n* Performs an update for every mini-batch of n traning examples.\n\n - (+) reduces the variance of the parameter updates\n - (+) efficient in computing the gradient w.r.t a mini-batch\n* mini-batch sizes range between 50-256\n\n**Challenges**\n* Chossing a proper learning rate can be difficult\n\n* Learning rate smart schedule\n - Annealing\n - Change of J below threshold\n* Variable learning for different parameters\n* Suboptimal local (saddle points)\n\n\n**Parameters**\n* Model Parameters: W, b, activation, output, cost\n\n* Hyper-parameters: Batch/minibatch size, learning parameters, external parameters\n\n## Methods for choosing learning rate\n**1. Learning rate decay**\n\n* $\\displaystyle \\alpha = \\frac{\\alpha_0}{1+\\text{decr}\\cdot\\text{epnum}}$\n\n* $\\displaystyle \\alpha = d^{\\text{epnum}}\\cdot \\alpha_0$\n\n* $\\displaystyle \\alpha = \\frac{d\\cdot\\alpha_0}{\\sqrt{\\text{epnum}}}$\n\n**2. Momentum Method**\n\n$$ v_{k+1} =\\gamma v_k+\\alpha\\cdot\\nabla_wJ(w_k)$$\n$$w_{k+1} =w_k -v_{k+1}$$\n\n
\n \n
\n\n**3. Nesterov Accelerated Gradient**\n\n$$v_{k+1}=\\gamma v_k +\\alpha \\cdot\\nabla_wJ(w_k-\\gamma v_k)$$\n$$w_{k+1}=w_k-v_{k+1}$$\n\n\n**4. Adagrad**\n$$w_{k+1,j} =w_{k,j} -\\frac{\\alpha}{\\sqrt{G_{k,jj}+\\epsilon}}\\cdot g_{k,j}$$\n\ng is our gradient\n\n* Adagrad uses a different learning rate for every parameter $w_j$ at every step $k$. $G$ is diagonal matrix of sum squared gradient values.\n\n* Performs smaller update (i.e. low learning rates) for parameters associated with frequntly occurring features, and larger updates (i.e. high learning rates) for parameters associated with infrequent features.\n\n**5. RMSProp**\n\n$$E[g^2]_k =\\gamma E[g^2]_{k-1} + (1-\\gamma)g_k^2$$\n$$w_{k+1} =w_k -\\frac{\\eta}{\\sqrt{E[g^2]_k+ \\epsilon}}g_k$$\n\n* Prevents accumulation by adding regularizing term in the running average (exponentially decaying)\n\n* Beneficial for RNNs\n\n**6. Adadelta**\n\n\\begin{align}\nE[\\Delta w^2]_k = \\gamma E[\\Delta &w^2]_{k-1} +(1-\\gamma) \\Delta w_k^2\\\\\n\\text{RMS}[\\Delta w]_k &=\\sqrt{E[\\Delta w^2]_k +\\epsilon}\\\\\n \\Delta w_k &=-\\frac{\\text{RMS}[\\Delta w]_{k-1}}{\\text{RMS}[g]_k}g_k\\\\\n w_{k+1}&=w_k+\\Delta w_k\n\\end{align}\n\n* Generalizes RMSProp /Adagard for considering RMS instead of accumulation of grad\n\n* No learning rate parameter\n\n**7. AdaM - Adaptive Moment Estimation**\n\n\\begin{align}\nm_k &=\\beta_1m_{k-1} + (1-\\beta_1)g_k\\\\\nv_k &=\\beta_2v_{k-1} +(1-\\beta_2)g_k^2\\\\\nw_{k+1}&=w_k -\\frac{\\eta}{\\sqrt{\\hat{v}_k}+\\epsilon}\\hat{m}_k\n\\end{align}\n\n* Keeps track of 2 moments: mean and variance\n* Normalizes them to prevent biases\n - $\\displaystyle \\hat{m}_k =\\frac{m_k}{1-\\beta_1^k}$\n - $\\displaystyle \\hat{v}_k =\\frac{v_k}{1-\\beta_2^k}$\n\n**Additional**\n- AdaMax: Generalization of AdaM to L-infinity norm\n- Nadam: Nesterov AdaM\n- AMSgrad: Max normalization instead of exponential in AdaM\n\n**Notes on Choosing Opimizers**\n\n* RSMProp & AdaDelta adaptive\n* AdaM adaptive + momentum -> robust\n* SGD as a first pass\n\n\n\n", "meta": {"hexsha": "2be594ea288e9da1427f238b4e7daf3836da51e2", "size": 9776, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Week 2_Optimization and Training.ipynb", "max_stars_repo_name": "raph651/amath-563", "max_stars_repo_head_hexsha": "3e17ad492ff425bd3ab6319b8ab4af9e1a428927", "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 2_Optimization and Training.ipynb", "max_issues_repo_name": "raph651/amath-563", "max_issues_repo_head_hexsha": "3e17ad492ff425bd3ab6319b8ab4af9e1a428927", "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 2_Optimization and Training.ipynb", "max_forks_repo_name": "raph651/amath-563", "max_forks_repo_head_hexsha": "3e17ad492ff425bd3ab6319b8ab4af9e1a428927", "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.5945017182, "max_line_length": 219, "alphanum_fraction": 0.5426554828, "converted": true, "num_tokens": 1938, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9643214511730026, "lm_q2_score": 0.9294404028354748, "lm_q1q2_score": 0.8962793180411252}} {"text": "```python\nfrom IPython.display import display, Latex\nfrom sympy import *\ninit_printing(use_latex='mathjax')\n\nx, y = symbols('x y')\ndisplay(x,y)\n\nint_x = Integral(cos(x)*exp(x), x)\nresult =\"$${} = {}$$\".format(latex(int_x), latex(int_x.doit()))\ndisplay(Latex(result))\n\nderv_x = Derivative(cos(x)*exp(x), x)\nresult =\"$${} = {}$$\".format(latex(derv_x), latex(derv_x.doit()))\ndisplay(Latex(result))\n```\n\n\n$\\displaystyle x$\n\n\n\n$\\displaystyle y$\n\n\n\n$$\\int e^{x} \\cos{\\left(x \\right)}\\, dx = \\frac{e^{x} \\sin{\\left(x \\right)}}{2} + \\frac{e^{x} \\cos{\\left(x \\right)}}{2}$$\n\n\n\n$$\\frac{d}{d x} e^{x} \\cos{\\left(x \\right)} = - e^{x} \\sin{\\left(x \\right)} + e^{x} \\cos{\\left(x \\right)}$$\n\n\n\n```python\nfrom IPython.display import display\n\ndef show(a, fmt='png'):\n import PIL.Image\n from io import BytesIO\n import IPython.display\n import numpy as np\n f = BytesIO()\n PIL.Image.fromarray(np.uint8(a)).save(f, fmt)\n IPython.display.display(IPython.display.Image(data=f.getvalue()))\n \nfrom sympy import *\ninit_printing()\n3+4j, Rational(1,3), sqrt(8), sqrt(-1), pi, E**2, oo, -oo\nimport IPython.display\ndisplay(3+4j, Rational(1,3), sqrt(8), sqrt(-1), pi, E**2, oo, -oo)\n# x = symbols('x')\n# a = Integral(cos(x)*exp(x), x)\n# Eq(a, a.doit())\n```\n\n\n```python\nalpha, beta, nu = symbols('alpha beta nu')\ndisplay(alpha, beta, nu)\n```\n\n\n```python\nalpha, beta\n```\n\n\n```python\n3+4j, Rational(1,3), sqrt(8), sqrt(-1), pi, E**2, oo, -oo\n```\n\n\n\n\n ((3+4j), 1/3, 2*sqrt(2), I, pi, exp(2), oo, -oo)\n\n\n\n\n```python\ndiff(sin(x)*exp(x),x)\n```\n\n\n```python\nintegrate(exp(x)*sin(x)+exp(x)*cos(x),x)\n```\n\n\n```python\nintegrate(sin(x**2),(x,-oo,oo))\n```\n\n\n```python\nimport sympy\nfrom sympy import init_printing, Integral, Symbol\n\nx = Symbol('x')\nexpr1 = 2*x**2 + 3*x + 2\n\ninit_printing(use_latex='mathjax')\nprint(\"Here is an integral \")\nIntegral(expr1, x), sympy.integrate(expr1)\n```\n\n Here is an integral \n\n\n\n\n\n$\\displaystyle \\left( \\int \\left(2 x^{2} + 3 x + 2\\right)\\, dx, \\ \\frac{2 x^{3}}{3} + \\frac{3 x^{2}}{2} + 2 x\\right)$\n\n\n\n\n```python\nimport sympy\nfrom sympy import init_printing, Integral, Symbol\n\nx = Symbol('x')\nexpr1 = 2*x**2 + 3*x + 2\n\ninit_printing(use_latex='mathjax')\nprint(\"Here is list\")\nexpr = Limit(sin(x)/x,x,0)\n[expr,expr.doit()]\n```\n\n Here is list\n\n\n\n\n\n$\\displaystyle \\left[ \\lim_{x \\to 0^+}\\left(\\frac{\\sin{\\left(x \\right)}}{x}\\right), \\ 1\\right]$\n\n\n\n\n```python\nimport sympy\nfrom sympy import init_printing, Integral, Symbol\n\nx = Symbol('x')\nexpr1 = 2*x**2 + 3*x + 2\n\ninit_printing(use_latex='mathjax')\nprint(\"Here is list\")\nexpr = Limit(sin(x)/x,x,0)\nexpr,expr.doit()\n```\n\n Here is list\n\n\n\n\n\n$\\displaystyle \\left( \\lim_{x \\to 0^+}\\left(\\frac{\\sin{\\left(x \\right)}}{x}\\right), \\ 1\\right)$\n\n\n\n\n```python\nsolve(x**2+1, x)\n```\n\n\n\n\n$\\displaystyle \\left[ - i, \\ i\\right]$\n\n\n\n\n```python\nsolve(x**2 - 2, x)\n```\n\n\n\n\n$\\displaystyle \\left[ - \\sqrt{2}, \\ \\sqrt{2}\\right]$\n\n\n\n\n```python\ny = Function('y')\nt = symbols('t')\nexpr = Eq(y(t).diff(t,t) - y(t), exp(t))\nexpr,y(t)\n```\n\n\n\n\n$\\displaystyle \\left( - y{\\left(t \\right)} + \\frac{d^{2}}{d t^{2}} y{\\left(t \\right)} = e^{t}, \\ y{\\left(t \\right)}\\right)$\n\n\n\n\n```python\ndsolve(expr,y(t))\n```\n\n\n\n\n$\\displaystyle y{\\left(t \\right)} = C_{2} e^{- t} + \\left(C_{1} + \\frac{t}{2}\\right) e^{t}$\n\n\n\n\n```python\nlatex(expr)\n```\n\n\n\n\n '- y{\\\\left(t \\\\right)} + \\\\frac{d^{2}}{d t^{2}} y{\\\\left(t \\\\right)} = e^{t}'\n\n\n\n\n```python\nfrom sympy.plotting import plot\nx = symbols('x')\np = plot(2*x+3, 3*x+1, legend=True, show=False)\np.show()\n```\n\n\n```python\ni = tensor.Idx('i',3)\nj = tensor.Idx('j',3)\nk = tensor.Idx('k',3)\nl = tensor.Idx('l',3)\n\nF = MatrixSymbol('F', 3, 3)\ni,j,k,l,F\n```\n\n\n\n\n$\\displaystyle \\left( Idx\\left(i, \\left( 0, \\ 2\\right)\\right), \\ Idx\\left(j, \\left( 0, \\ 2\\right)\\right), \\ Idx\\left(k, \\left( 0, \\ 2\\right)\\right), \\ Idx\\left(l, \\left( 0, \\ 2\\right)\\right), \\ F\\right)$\n\n\n\n\n```python\nfrom sympy.tensor.array import *\nvar(\"a,b,c,d,e,f\")\nX = Array([[a, b, c], [d, e, f]])\nX\nvar(\"w1,w2,w3\")\nW = Array([w1, w2, w3])\nW\ntp = tensorproduct(X, W)\ntp\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}\\left[\\begin{matrix}a w_{1} & a w_{2} & a w_{3}\\\\b w_{1} & b w_{2} & b w_{3}\\\\c w_{1} & c w_{2} & c w_{3}\\end{matrix}\\right] & \\left[\\begin{matrix}d w_{1} & d w_{2} & d w_{3}\\\\e w_{1} & e w_{2} & e w_{3}\\\\f w_{1} & f w_{2} & f w_{3}\\end{matrix}\\right]\\end{matrix}\\right]$\n\n\n\n\n```python\nstc = sum(tensorcontraction(tp, (1, 2)))\nstc\n```\n\n\n\n\n$\\displaystyle a w_{1} + b w_{2} + c w_{3} + d w_{1} + e w_{2} + f w_{3}$\n\n\n\n\n```python\nderive_by_array(stc, W)\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}a + d & b + e & c + f\\end{matrix}\\right]$\n\n\n\n\n```python\nX = IndexedBase(\"X\")\nW = IndexedBase(\"W\")\nvar(\"i,j,M,K\", integer=True)\ns = Sum(X[i, j]*W[j], (i, 1, M), (j, 1, K))\ns\n```\n\n\n\n\n$\\displaystyle \\sum_{\\substack{1 \\leq i \\leq M\\\\1 \\leq j \\leq K}} {W}_{j} {X}_{i,j}$\n\n\n\n\n```python\ns.diff(W[j])\n```\n\n\n\n\n$\\displaystyle \\sum_{\\substack{1 \\leq i \\leq M\\\\1 \\leq j \\leq K}} {X}_{i,j}$\n\n\n\n\n```python\ns.diff(W[k])\n```\n\n\n\n\n$\\displaystyle \\sum_{\\substack{1 \\leq i \\leq M\\\\1 \\leq j \\leq K}} \\delta_{j Idx\\left(k, \\left( 0, \\ 2\\right)\\right)} {X}_{i,j}$\n\n\n\n\n```python\n# https://docs.sympy.org/latest/modules/tensor/array.html\n\nArray([[[1,2,3],[2,3,4],[3,4,5]],[[1,2,3],[2,3,4],[3,4,5]]])\n)\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}\\left[\\begin{matrix}1 & 2 & 3\\\\2 & 3 & 4\\\\3 & 4 & 5\\end{matrix}\\right] & \\left[\\begin{matrix}1 & 2 & 3\\\\2 & 3 & 4\\\\3 & 4 & 5\\end{matrix}\\right]\\end{matrix}\\right]$\n\n\n\n\n```python\nfrom sympy.physics.mechanics import *\na = Array([1,2,3,4])\nb = Array([2,3,4,5])\nc=tensorproduct(a,b)\nd=tensorproduct(b,a)\n#dot(a,b)\n```\n\n\n```python\nexpr = sin(x**2)\nexpr, integrate(expr,(x,-oo,oo))\n```\n\n\n\n\n$\\displaystyle \\left( \\sin{\\left(x^{2} \\right)}, \\ \\frac{\\sqrt{2} \\sqrt{\\pi}}{2}\\right)$\n\n\n\n\n```python\nsolve(x**2+1,x)\n```\n\n\n\n\n$\\displaystyle \\left[ - i, \\ i\\right]$\n\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "e6f8051a1868ce87bafacb614b5ae5142cae06ae", "size": 55779, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "knowledge/tmp.ipynb", "max_stars_repo_name": "partnernetsoftware/openlab", "max_stars_repo_head_hexsha": "faa4e58486a7bc4140ad3d56545bfb736cb86696", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-09-26T05:27:30.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-26T05:27:30.000Z", "max_issues_repo_path": "knowledge/tmp.ipynb", "max_issues_repo_name": "partnernetsoftware/openlab", "max_issues_repo_head_hexsha": "faa4e58486a7bc4140ad3d56545bfb736cb86696", "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": "knowledge/tmp.ipynb", "max_forks_repo_name": "partnernetsoftware/openlab", "max_forks_repo_head_hexsha": "faa4e58486a7bc4140ad3d56545bfb736cb86696", "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.5041237113, "max_line_length": 23092, "alphanum_fraction": 0.7509994801, "converted": true, "num_tokens": 2281, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012732322216, "lm_q2_score": 0.947381044980928, "lm_q1q2_score": 0.8960341985790343}} {"text": "# Verlet Algorithm\n\nIn molecular dynamics, the most commonly used time integration algorithm is probably the so-called Verlet algorithm [L. Verlet, Computer experiments on classical fluids. I. Thermodynamical properties of Lennard-Jones molecules, Physical Review 159, 98 (1967)]. The basic idea is to write two third-order Taylor expansions for the positions ${\\bf r} (t)$, one forward and one backward in time. Calling $\\bf v$ the velocities, $\\bf a$ the accelerations, and $\\bf b$ the third derivatives of ${\\bf r}$ with respect to $t$, one has:\n$$\\begin{equation}\n{\\bf r} (t+\\Delta t) = {\\bf r} (t) + {\\bf v} (t) \\Delta t + \\frac{1}{2} {\\bf a}(t) \\Delta t^2 + (1/6) {\\bf b} (t) \\Delta t^3\n + O(\\Delta t^4) \\end{equation}\n$$\n$$\n\\begin{equation}\n{\\bf r} (t-\\Delta t) = {\\bf r} (t) - {\\bf v} (t) \\Delta t + \\frac{1}{2} {\\bf a}(t) \\Delta t^2 - (1/6) {\\bf b} (t) \\Delta t^3\n + O(\\Delta t^4) \\end{equation}\n$$\nAdding the two expressions gives\n$$\\begin{equation}\n{\\bf r} (t+\\Delta t) = 2{\\bf r} (t) - {\\bf r} (t-\\Delta t)\n + {\\bf a} (t) \\Delta t^2 + O(\\Delta t^4) \\end{equation}\t\n$$\nThis is the basic form of the Verlet algorithm. Since we are integrating Newton's equations, ${\\bf a} (t)$ is just the force divided by the mass, and the force is in turn a function of the positions ${\\bf r} (t)$:\n$$\\begin{equation}\n{\\bf a} (t) = - \\frac{1}{m} {\\bf\\nabla} V\\left( {\\bf r}(t) \\right) \\end{equation}\t\n$$\nAs one can immediately see, the truncation error of the algorithm when evolving the system by $\\Delta t$ is of the order of $\\Delta t^4$, even if third derivatives do not appear explicitly. This algorithm is at the same time simple to implement, accurate and stable, explaining its large popularity among molecular dynamics simulators.\n\nWhile the velocities are not needed for the time evolution, their knowledge is sometimes necessary. Moreover, they are required to compute the kinetic energy $K$, whose evaluation is necessary to test the conservation of the total energy $E=K+V$. This is one of the most important tests to verify that a MD simulation is proceeding correctly. One could compute the velocities from the positions by subtracting the previous expression to obtain:\n\n$$\\begin{equation}\n{\\bf v} (t) = \\frac { {\\bf r}(t+\\Delta t) - {\\bf r}(t-\\Delta t) }\n { 2 \\Delta t } . \\end{equation}\n$$\nHowever, the error associated to this expression is of order $\\Delta t^2$ rather than $\\Delta t^4$.\n\nThe main problem with the Verlet algorithm is that it is not self starting, and the first step needs to be computed by different means. An additional problem is that the new velocity is found by computing the difference between two quantities of the same order of magnitude. When using computers which always operate with finite numerical precision, such an operation results in a loss of numerical precision and may give rise to substantial roundoff error.\n\nAn even better implementation of the same basic algorithm is the so-called \"**velocity Verlet scheme**\", where positions, velocities and accelerations at time $t+\\Delta t$ are obtained from the same quantities at time $t$ in the following way:\n\n$$\\begin{eqnarray}\n{\\bf r} (t + \\Delta t) &=& {\\bf r} (t) + {\\bf v} (t) \\Delta t + (1/2) {\\bf a} (t) \\Delta t^2 \\\\\n{\\bf v} (t + \\Delta t/2) &=& {\\bf v} (t) + (1/2) {\\bf a} (t) \\Delta t \\\\\n{\\bf a} (t + \\Delta t) &=& - (1/m) {\\bf\\nabla} V \\left( {\\bf r}(t+\\Delta t) \\right) \\\\ \n{\\bf v} (t + \\Delta t) &=& {\\bf v} (t + \\Delta t/2) + (1/2) {\\bf a} (t + \\Delta t) \\Delta t \n\\end{eqnarray}$$\n\nNote how we need $9N$ memory locations to save the $3N$ positions, velocities and accelerations, but we never need to have simultaneously stored the values at two different times for any one of these quantities.\n\nHere, we modify the code for particle2 implementing velocity Verlet:\n\n\n```python\nclass particle2(object):\n \n def __init__(self, mass=1., x=0., y=0., vx=0., vy=0.):\n self.mass = mass\n self.x = x\n self.y = y\n self.vx = vx\n self.vy = vy\n \n def euler(self, fx, fy, dt):\n self.vx = self.vx + fx*dt\n self.vy = self.vy + fy*dt\n self.x = self.x + self.vx*dt\n self.y = self.y + self.vy*dt\n \n def get_force(self): # returns force per unit of mass (acceleration)\n GM=4*math.pi*math.pi # We use astronomical units\n r = math.sqrt(self.x*self.x+self.y*self.y)\n r3 = r * r * r\n fx = -GM*self.x/r3\n fy = -GM*self.y/r3\n return (fx,fy)\n \n def verlet(self, dt):\n (fx,fy) = self.get_force() # before I move to the new position\n self.x += self.vx*dt + 0.5*fx*dt*dt\n self.y += self.vy*dt + 0.5*fy*dt*dt\n self.vx += 0.5*fx*dt\n self.vy += 0.5*fy*dt\n (fx,fy) = self.get_force() # after I move to the new position\n self.vx += 0.5*fx*dt\n self.vy += 0.5*fy*dt\n\n\n```\n\n### Challenge 2.3:\n\nUse velocity verlet to simulate the mini-solar system from Challenge 2.2.\nCan you come up with a different way to write the algorithm such that you call get_force only once per move?\n\n\n```python\n\n```\n", "meta": {"hexsha": "6a2c38bc7b597c42891f8036c9b363e23a49575e", "size": 6740, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "02_02_Verlet.ipynb", "max_stars_repo_name": "herybala/comp-phys", "max_stars_repo_head_hexsha": "73dd6429b87e20849fa384952155b6d8d6786f05", "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_02_Verlet.ipynb", "max_issues_repo_name": "herybala/comp-phys", "max_issues_repo_head_hexsha": "73dd6429b87e20849fa384952155b6d8d6786f05", "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_02_Verlet.ipynb", "max_forks_repo_name": "herybala/comp-phys", "max_forks_repo_head_hexsha": "73dd6429b87e20849fa384952155b6d8d6786f05", "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": 48.4892086331, "max_line_length": 542, "alphanum_fraction": 0.5661721068, "converted": true, "num_tokens": 1510, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.962673111584966, "lm_q2_score": 0.9304582526016021, "lm_q1q2_score": 0.8957271412318946}} {"text": "# Symbolically Understanding Christoffel Symbol and Riemann Curvature Tensor using EinsteinPy\n\n\n```python\nimport sympy\nfrom einsteinpy.symbolic import MetricTensor, ChristoffelSymbols, RiemannCurvatureTensor\n\nsympy.init_printing() # enables the best printing available in an environment\n```\n\n### Defining the metric tensor for 3d spherical coordinates\n\n\n```python\nsyms = sympy.symbols('r theta phi')\n# define the metric for 3d spherical coordinates\nmetric = [[0 for i in range(3)] for i in range(3)]\nmetric[0][0] = 1\nmetric[1][1] = syms[0]**2\nmetric[2][2] = (syms[0]**2)*(sympy.sin(syms[1])**2)\n# creating metric object\nm_obj = MetricTensor(metric, syms)\nm_obj.tensor()\n```\n\n### Calculating the christoffel symbols\n\n\n```python\nch = ChristoffelSymbols.from_metric(m_obj)\nch.tensor()\n```\n\n\n```python\nch.tensor()[1,1,0]\n```\n\n### Calculating the Riemann Curvature tensor\n\n\n```python\n# Calculating Riemann Tensor from Christoffel Symbols\nrm1 = RiemannCurvatureTensor.from_christoffels(ch)\nrm1.tensor()\n```\n\n\n```python\n# Calculating Riemann Tensor from Metric Tensor\nrm2 = RiemannCurvatureTensor.from_metric(m_obj)\nrm2.tensor()\n```\n\n### Calculating the christoffel symbols for Schwarzschild Spacetime Metric\n - The expressions are unsimplified\n\n\n```python\nsyms = sympy.symbols(\"t r theta phi\")\nG, M, c, a = sympy.symbols(\"G M c a\")\n# using metric values of schwarschild space-time\n# a is schwarzschild radius\nlist2d = [[0 for i in range(4)] for i in range(4)]\nlist2d[0][0] = 1 - (a / syms[1])\nlist2d[1][1] = -1 / ((1 - (a / syms[1])) * (c ** 2))\nlist2d[2][2] = -1 * (syms[1] ** 2) / (c ** 2)\nlist2d[3][3] = -1 * (syms[1] ** 2) * (sympy.sin(syms[2]) ** 2) / (c ** 2)\nsch = MetricTensor(list2d, syms)\nsch.tensor()\n```\n\n\n```python\n# single substitution\nsubs1 = sch.subs(a,0)\nsubs1.tensor()\n```\n\n\n```python\n# multiple substitution\nsubs2 = sch.subs([(a,0), (c,1)])\nsubs2.tensor()\n```\n\n\n```python\nsch_ch = ChristoffelSymbols.from_metric(sch)\nsch_ch.tensor()\n```\n\n### Calculating the simplified expressions\n\n\n```python\nsimplified = sch_ch.simplify()\nsimplified\n```\n", "meta": {"hexsha": "28fa136534a04efcb0ffe2c0bff971d3bf9f156e", "size": 74416, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "docs/source/examples/Symbolically Understanding Christoffel Symbol and Riemann Curvature Tensor using EinsteinPy.ipynb", "max_stars_repo_name": "r0cketr1kky/einsteinpy", "max_stars_repo_head_hexsha": "d86f412736a42e2cf688a1e21d7b553868a14bc4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-04-07T04:01:57.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-11T11:59:55.000Z", "max_issues_repo_path": "docs/source/examples/Symbolically Understanding Christoffel Symbol and Riemann Curvature Tensor using EinsteinPy.ipynb", "max_issues_repo_name": "r0cketr1kky/einsteinpy", "max_issues_repo_head_hexsha": "d86f412736a42e2cf688a1e21d7b553868a14bc4", "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/source/examples/Symbolically Understanding Christoffel Symbol and Riemann Curvature Tensor using EinsteinPy.ipynb", "max_forks_repo_name": "r0cketr1kky/einsteinpy", "max_forks_repo_head_hexsha": "d86f412736a42e2cf688a1e21d7b553868a14bc4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-03-19T18:46:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-19T18:46:13.000Z", "avg_line_length": 138.8358208955, "max_line_length": 14080, "alphanum_fraction": 0.7544345302, "converted": true, "num_tokens": 654, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338101862455, "lm_q2_score": 0.9314625131514056, "lm_q1q2_score": 0.8956326993161269}} {"text": "# Normal Equations\n\nReal numbers only this time.\n\n## Linear Systems of Equations\n\nLinear equations are of the form $Ax = b$ where $A$ is a matrix and $x$ and $b$ are vectors. The rows of $A$ and $b$ form a system of equations that must be simultaneously satisfied by the entries of $x$. If $x,b\\in\\mathbb{R}^n$, then the solutions to the equation of a single row corresponds to an $n-1$-dimensional hyperplane. If the rows of $A$ are linearly independent, then solutions that that simultaneously satisfy the equations in $k$-rows correspond to the $n-k$-dimensional intersection of $k$ $n$-dimensional hyperplanes. The solution of $x$ that satisfies all $n$ equations is a $n-n = 0$-dimensional point, and so $x$ is uniquely determined. If any two rows of $A$ are not linearly independent, then the hyperplanes that correspond to values of $x$ that satisfy them overlap exactly, and their intersection is $n$ dimensional, rather than $n-1$ dimensional. In this case, the value of $x$ that satisfies all rows of $A$ is not narrowed down to a single point. The system of equations is said to be *underdetermined*:. This is equivalently the case when $A$ has $mn$ rows, then there need not be any point $x\\in\\mathbb{R}^n$ in which the $m$ hyperplanes all intersect. In that case, the system does not have a solution $x\\in\\mathbb{R}^n$, and the system is considered *overdetermined*. (The intersection of $m$ distinct hyperplanes in $n$ dimensional space would have negative dimension $(n-m)<0$ if $m>n$, which my feeble brain can't make sense of.)\n\n\n## The Normal Equations\nIn the overdetermined case $A^{mxn}$ with $m>n$, the columns of $A$ do not span $\\mathbb{R}^m$ and therefore $b\\in\\mathbb{R}^m$ may have some component $\\epsilon$ that lies outside of the column space of $A$. In that case, no linear combination $x$ of the columns of $A$ can express $b$ perfectly, but we might look for approximate solutions $\\hat{x}$ so that:\n\n\\begin{equation}\nA\\hat{x} + \\epsilon = b\n\\end{equation}\n\nA natural approach for picking an approximate solution $\\hat{x}$ is to look for the projection of $b$ in the column space of $A$, which can be thought of as looking for the shadow of an $m$-dimensional vector in $n$ dimensional space. \n\nThe projection maximizes the dot product $(A\\hat{x})\\cdot b$, and hence minimizes the length of the difference vector $\\epsilon$. In turn, the length of the difference vector $\\epsilon$ is $\\sqrt{\\epsilon\\cdot\\epsilon}$, which is monotonic to $\\epsilon\\cdot\\epsilon = \\sum^m_i \\epsilon_i^2$. That means that finding the projection of $b$ in the column space of $A$ minimizes the $L_2$ norm of $\\epsilon$ or *least squares error*.\n\nThere are two ways to go about finding $\\hat{x}$.\n\n### The Quick Way to $\\hat{x}$\n\nBy construction, the vector $\\epsilon$ is orthogonal to the column space of $A$. Which means:\n\n\\begin{equation}\n\\begin{array}{rl}\nA^T\\epsilon &= 0\\\\\nA^T\\left(A\\hat{x}-b\\right) &= 0\\\\\nA^TA\\hat{x} &= A^Tb\\\\\n\\hat{x} &= \\left(A^TA\\right)^{-1}A^Tb\n\\end{array}\n\\end{equation}\n\nMaking use of the fact that $A^TA$ is square and therefore hopefully invertible.\n\n### The Long Way to $\\hat{x}$\n\nLoss functions play a central role in computational statistics (for example when regularization is introduced), and therefore it is of interest to approach finding $\\hat{x}$ by instead minimizing the least square error. This requires:\n\n\\begin{equation}\n\\frac{d}{d\\hat{x}}L_2(\\epsilon) = 0\n\\end{equation}\n\nwhere\n\n\\begin{equation}\n\\begin{array}{rl}\nL_2(\\epsilon) &= \\left(A\\hat{x}-b\\right)^T\\left(A\\hat{x}-b\\right)\\\\\n&= \\hat{x}^TA^TA\\hat{x} - \\hat{x}^TA^Tb - b^TA\\hat{x} + b^Tb \n\\end{array}\n\\end{equation}\n\nUseful factoids about taking derivatives with respect to vectors include:\n\n\\begin{equation}\n\\begin{array}{l}\n\\frac{d}{dx} \\left(u^Tx\\right) = \\left[\\frac{d}{dx_1}\\left(\\sum_i u_i x_i\\right),...,\\frac{d}{dx_n}\\left(\\sum_i u_i x_i\\right)\\right] = u^T\\\\\n\\\\\n\\frac{d}{dx} \\left(x^Tu\\right) = \\left[\\frac{d}{dx_1}\\left(\\sum_i u_i x_i\\right),...,\\frac{d}{dx_n}\\left(\\sum_i u_i x_i\\right)\\right] = u^T\\\\\n\\\\\n\\frac{d}{dx} \\left(x^Tx\\right) = \\left[\\frac{d}{dx_1}\\left(\\sum_i x_i^2\\right),...,\\frac{d}{dx_n}\\left(\\sum_i x_i^2\\right)\\right] = 2x^T\\\\\n\\\\\n\\frac{d}{dx} \\left(Ax\\right) = \\left[\n\\begin{array}{ccc} \n\\underbrace{\\frac{d}{dx_1}\\left(\\sum_i A_1i x_i\\right)}_{A_{11}} &...& \\underbrace{\\frac{d}{dx_n}\\left(\\sum_i A_1i x_i\\right)}_{A_1n}\\\\\n\\vdots&\\vdots&\\vdots\\\\\n\\underbrace{\\frac{d}{dx_1}\\left(\\sum_i A_ni x_i\\right)}_{A_{n1}} &...& \\underbrace{\\frac{d}{dx_n}\\left(\\sum_i A_ni x_i\\right)}_{A_{nn}}\\\\\n\\end{array}\\right] = A\\\\\n\\end{array}\n\\end{equation}\n\nIt follows:\n\n\\begin{equation}\n\\begin{array}{l}\n\\frac{d}{d\\hat{x}}\\left(x^TA^T\\underbrace{A\\hat{x}}_{u(\\hat{x})}\\right) = \\frac{d}{du}\\left(u^Tu\\right)\\frac{d}{d\\hat{x}}u = 2u^T\\frac{d}{d\\hat{x}}u = 2\\hat{x}^TA^TA\\\\\n\\\\\n\\frac{d}{d\\hat{x}}\\hat{x}^TA^Tb = b^TA\\\\\n\\\\\n\\frac{d}{d\\hat{x}}b^TA\\hat{x} = b^TA\\\\\n\\\\\n\\frac{d}{d\\hat{x}}b^Tb = 0\n\\end{array}\n\\end{equation}\n\nSo that \n\n\\begin{equation}\n\\begin{array}{rl}\n\\frac{d}{dx}L_2(\\epsilon) = 0 &= 2\\hat{x}^TA^TA - 2b^TA\\\\\n\\hat{x}^TA^TA &= b^TA\\\\\nA^TA\\hat{x} &= A^Tb\\\\\n\\hat{x} &= \\left(A^TA\\right)^{-1}A^Tb\n\\end{array}\n\\end{equation}\n\n\n### Projection Matrix\n\nIf $\\hat{b}=A\\hat{x}$ is the projection of $b$ in the column space of $A$, then, based on the result for $\\hat{x}$, the projection matrix is $P = A\\left(A^TA\\right)^{-1}A^T$. In a fully determined system, $P=I$. Projection matrices have eigenvalues that are either 1 or 0, corresponding to dimensions that are kept or discarded during the projection operation.\n\n### Underdetermined Case\n\nFor an underdetermined system with $m This is a counterexample to a conjecture by Euler ... that at least $n$ $n$th powers are required to sum to an $n$th power, $n > 2$.\n\n## Exercise 1\n\nUsing python, check the equation above is true.\n\n#### Solution\n\n\n```python\nlhs = 27**5 + 84**5 + 110**5 + 133**5\nrhs = 144**5\n\nprint(\"Does the LHS {} equal the RHS {}? {}\".format(lhs, rhs, lhs==rhs))\n```\n\n Does the LHS 61917364224 equal the RHS 61917364224? True\n\n\n## Exercise 2\n\nThe more interesting statement in the paper is that\n\n\\begin{equation}\n 27^5 + 84^5 + 110^5 + 133^5 = 144^5.\n\\end{equation}\n\n> [is] the smallest instance in which four fifth powers sum to a fifth power.\n\nInterpreting \"the smallest instance\" to mean the solution where the right hand side term (the largest integer) is the smallest, we want to use python to check this statement.\n\nYou may find the `combinations` function from the `itertools` package useful.\n\n\n```python\nimport numpy\nimport itertools\n```\n\nThe `combinations` function returns all the combinations (ignoring order) of `r` elements from a given list. For example, take a list of length 6, `[1, 2, 3, 4, 5, 6]` and compute all the combinations of length 4:\n\n\n```python\ninput_list = numpy.arange(1, 7)\ncombinations = list(itertools.combinations(input_list, 4))\nprint(combinations)\n```\n\n [(1, 2, 3, 4), (1, 2, 3, 5), (1, 2, 3, 6), (1, 2, 4, 5), (1, 2, 4, 6), (1, 2, 5, 6), (1, 3, 4, 5), (1, 3, 4, 6), (1, 3, 5, 6), (1, 4, 5, 6), (2, 3, 4, 5), (2, 3, 4, 6), (2, 3, 5, 6), (2, 4, 5, 6), (3, 4, 5, 6)]\n\n\nWe can already see that the number of terms to consider is large.\n\nNote that we have used the `list` function to explicitly get a list of the combinations. The `combinations` function returns a *generator*, which can be used in a loop as if it were a list, without storing all elements of the list.\n\nHow fast does the number of combinations grow? The standard formula says that for a list of length $n$ there are\n\n\\begin{equation}\n \\begin{pmatrix} n \\\\ k \\end{pmatrix} = \\frac{n!}{k! (n-k)!}\n\\end{equation}\n\ncombinations of length $k$. For $k=4$ as needed here we will have $n (n-1) (n-2) (n-3) / 24$ combinations. For $n=144$ we therefore have\n\n\n```python\nn_combinations = 144*143*142*141/24\nprint(\"Number of combinations of 4 objects from 144 is {}\".format(n_combinations))\n```\n\n Number of combinations of 4 objects from 144 is 17178876.0\n\n\n### Exercise 2a\n\nShow, by getting python to compute the number of combinations $N = \\begin{pmatrix} n \\\\ 4 \\end{pmatrix}$ that $N$ grows roughly as $n^4$. To do this, plot the number of combinations and $n^4$ on a log-log scale. Restrict to $n \\le 50$.\n\n#### Solution\n\n\n```python\nfrom matplotlib import pyplot\n%matplotlib inline\n```\n\n\n```python\nn = numpy.arange(5, 51)\nN = numpy.zeros_like(n)\nfor i, n_c in enumerate(n):\n combinations = list(itertools.combinations(numpy.arange(1,n_c+1), 4))\n N[i] = len(combinations)\n```\n\n\n```python\npyplot.figure(figsize=(12,6))\npyplot.loglog(n, N, linestyle='None', marker='x', color='k', label='Combinations')\npyplot.loglog(n, n**4, color='b', label=r'$n^4$')\npyplot.xlabel(r'$n$')\npyplot.ylabel(r'$N$')\npyplot.legend(loc='upper left')\npyplot.show()\n```\n\nWith 17 million combinations to work with, we'll need to be a little careful how we compute.\n\nOne thing we could try is to loop through each possible \"smallest instance\" (the term on the right hand side) in increasing order. We then check all possible combinations of left hand sides.\n\nThis is computationally *very expensive* as we repeat a lot of calculations. We repeatedly recalculate combinations (a bad idea). We repeatedly recalculate the powers of the same number.\n\nInstead, let us try creating the list of all combinations of powers once.\n\n### Exercise 2b\n\n1. Construct a `numpy` array containing all integers in $1, \\dots, 144$ to the fifth power. \n2. Construct a list of all combinations of four elements from this array.\n3. Construct a list of sums of all these combinations.\n4. Loop over one list and check if the entry appears in the other list (ie, use the `in` keyword).\n\n#### Solution\n\n\n```python\nnmax=145\nrange_to_power = numpy.arange(1, nmax)**5.0\nlhs_combinations = list(itertools.combinations(range_to_power, 4))\n```\n\nThen calculate the sums:\n\n\n```python\nlhs_sums = []\nfor lhs_terms in lhs_combinations:\n lhs_sums.append(numpy.sum(numpy.array(lhs_terms)))\n```\n\nFinally, loop through the sums and check to see if it matches any possible term on the RHS:\n\n\n```python\nfor i, lhs in enumerate(lhs_sums):\n if lhs in range_to_power:\n rhs_primitive = int(lhs**(0.2))\n lhs_primitive = (numpy.array(lhs_combinations[i])**(0.2)).astype(int)\n print(\"The LHS terms are {}.\".format(lhs_primitive))\n print(\"The RHS term is {}.\".format(rhs_primitive))\n```\n\n The LHS terms are [ 27 84 110 133].\n The RHS term is 144.\n\n\n# Lorenz attractor\n\nThe Lorenz system is a set of ordinary differential equations which can be written\n\n\\begin{equation}\n \\frac{\\text{d} \\vec{v}}{\\text{d} \\vec{t}} = \\vec{f}(\\vec{v})\n\\end{equation}\n\nwhere the variables in the state vector $\\vec{v}$ are\n\n\\begin{equation}\n \\vec{v} = \\begin{pmatrix} x(t) \\\\ y(t) \\\\ z(t) \\end{pmatrix}\n\\end{equation}\n\nand the function defining the ODE is\n\n\\begin{equation}\n \\vec{f} = \\begin{pmatrix} \\sigma \\left( y(t) - x(t) \\right) \\\\ x(t) \\left( \\rho - z(t) \\right) - y(t) \\\\ x(t) y(t) - \\beta z(t) \\end{pmatrix}.\n\\end{equation}\n\nThe parameters $\\sigma, \\rho, \\beta$ are all real numbers.\n\n## Exercise 1\n\nWrite a function `dvdt(v, t, params)` that returns $\\vec{f}$ given $\\vec{v}, t$ and the parameters $\\sigma, \\rho, \\beta$.\n\n#### Solution\n\n\n```python\ndef dvdt(v, t, sigma, rho, beta):\n \"\"\"\n Define the Lorenz system.\n \n Parameters\n ----------\n \n v : list\n State vector\n t : float\n Time\n sigma : float\n Parameter\n rho : float\n Parameter\n beta : float\n Parameter\n \n Returns\n -------\n \n dvdt : list\n RHS defining the Lorenz system\n \"\"\"\n \n x, y, z = v\n \n return [sigma*(y-x), x*(rho-z)-y, x*y-beta*z]\n```\n\n## Exercise 2\n\nFix $\\sigma=10, \\beta=8/3$. Set initial data to be $\\vec{v}(0) = \\vec{1}$. Using `scipy`, specifically the `odeint` function of `scipy.integrate`, solve the Lorenz system up to $t=100$ for $\\rho=13, 14, 15$ and $28$.\n\nPlot your results in 3d, plotting $x, y, z$.\n\n#### Solution\n\n\n```python\nimport numpy\nfrom scipy.integrate import odeint\n```\n\n\n```python\nv0 = [1.0, 1.0, 1.0]\nsigma = 10.0\nbeta = 8.0/3.0\nt_values = numpy.linspace(0.0, 100.0, 5000)\nrho_values = [13.0, 14.0, 15.0, 28.0]\nv_values = []\nfor rho in rho_values:\n params = (sigma, rho, beta)\n v = odeint(dvdt, v0, t_values, args=params)\n v_values.append(v)\n```\n\n\n```python\n%matplotlib inline\nfrom matplotlib import pyplot\nfrom mpl_toolkits.mplot3d.axes3d import Axes3D\n```\n\n\n```python\nfig = pyplot.figure(figsize=(12,6))\nfor i, v in enumerate(v_values):\n ax = fig.add_subplot(2,2,i+1,projection='3d')\n ax.plot(v[:,0], v[:,1], v[:,2])\n ax.set_xlabel(r'$x$')\n ax.set_ylabel(r'$y$')\n ax.set_zlabel(r'$z$')\n ax.set_title(r\"$\\rho={}$\".format(rho_values[i]))\npyplot.show()\n```\n\n## Exercise 3\n\nFix $\\rho = 28$. Solve the Lorenz system twice, up to $t=40$, using the two different initial conditions $\\vec{v}(0) = \\vec{1}$ and $\\vec{v}(0) = \\vec{1} + \\vec{10^{-5}}$.\n\nShow four plots. Each plot should show the two solutions on the same axes, plotting $x, y$ and $z$. Each plot should show $10$ units of time, ie the first shows $t \\in [0, 10]$, the second shows $t \\in [10, 20]$, and so on.\n\n#### Solution\n\n\n```python\nt_values = numpy.linspace(0.0, 40.0, 4000)\nrho = 28.0\nparams = (sigma, rho, beta)\nv_values = []\nv0_values = [[1.0,1.0,1.0],\n [1.0+1e-5,1.0+1e-5,1.0+1e-5]]\nfor v0 in v0_values:\n v = odeint(dvdt, v0, t_values, args=params)\n v_values.append(v)\n```\n\n\n```python\nfig = pyplot.figure(figsize=(12,6))\nline_colours = 'by'\nfor tstart in range(4):\n ax = fig.add_subplot(2,2,tstart+1,projection='3d')\n for i, v in enumerate(v_values):\n ax.plot(v[tstart*1000:(tstart+1)*1000,0], \n v[tstart*1000:(tstart+1)*1000,1], \n v[tstart*1000:(tstart+1)*1000,2], \n color=line_colours[i])\n ax.set_xlabel(r'$x$')\n ax.set_ylabel(r'$y$')\n ax.set_zlabel(r'$z$')\n ax.set_title(r\"$t \\in [{},{}]$\".format(tstart*10, (tstart+1)*10))\npyplot.show()\n```\n\nThis shows the *sensitive dependence on initial conditions* that is characteristic of chaotic behaviour.\n\n# Systematic ODE solving with sympy\n\nWe are interested in the solution of\n\n\\begin{equation}\n \\frac{\\text{d} y}{\\text{d} t} = e^{-t} - y^n, \\qquad y(0) = 1,\n\\end{equation}\n\nwhere $n > 1$ is an integer. The \"minor\" change from the above examples mean that `sympy` can only give the solution as a power series.\n\n## Exercise 1\n\nCompute the general solution as a power series for $n = 2$.\n\n#### Solution\n\n\n```python\nimport sympy\nsympy.init_printing()\n```\n\n\n```python\ny, t = sympy.symbols('y, t')\n```\n\n\n```python\nsympy.dsolve(sympy.diff(y(t), t) + y(t)**2 - sympy.exp(-t), y(t))\n```\n\n## Exercise 2\n\nInvestigate the help for the `dsolve` function to straightforwardly impose the initial condition $y(0) = 1$ using the `ics` argument. Using this, compute the specific solutions that satisfy the ODE for $n = 2, \\dots, 10$.\n\n#### Solution\n\n\n```python\nfor n in range(2, 11):\n ode_solution = sympy.dsolve(sympy.diff(y(t), t) + y(t)**n - sympy.exp(-t), y(t), \n ics = {y(0) : 1})\n print(ode_solution)\n```\n\n y(t) == 1 - t**2/2 + t**3/2 - 7*t**4/24 + 3*t**5/40 + O(t**6)\n y(t) == 1 - t**2/2 + 2*t**3/3 - 13*t**4/24 + 11*t**5/60 + O(t**6)\n y(t) == 1 - t**2/2 + 5*t**3/6 - 7*t**4/8 + 49*t**5/120 + O(t**6)\n y(t) == 1 - t**2/2 + t**3 - 31*t**4/24 + 4*t**5/5 + O(t**6)\n y(t) == 1 - t**2/2 + 7*t**3/6 - 43*t**4/24 + 169*t**5/120 + O(t**6)\n y(t) == 1 - t**2/2 + 4*t**3/3 - 19*t**4/8 + 137*t**5/60 + O(t**6)\n y(t) == 1 - t**2/2 + 3*t**3/2 - 73*t**4/24 + 139*t**5/40 + O(t**6)\n y(t) == 1 - t**2/2 + 5*t**3/3 - 91*t**4/24 + 151*t**5/30 + O(t**6)\n y(t) == 1 - t**2/2 + 11*t**3/6 - 37*t**4/8 + 841*t**5/120 + O(t**6)\n\n\n## Exercise 3\n\nUsing the `removeO` command, plot each of these solutions for $t \\in [0, 1]$.\n\n\n```python\n%matplotlib inline\n\nfor n in range(2, 11):\n ode_solution = sympy.dsolve(sympy.diff(y(t), t) + y(t)**n - sympy.exp(-t), y(t), \n ics = {y(0) : 1})\n sympy.plot(ode_solution.rhs.removeO(), (t, 0, 1));\n```\n\n# Twin primes\n\nA *twin prime* is a pair $(p_1, p_2)$ such that both $p_1$ and $p_2$ are prime and $p_2 = p_1 + 2$.\n\n## Exercise 1\n\nWrite a generator that returns twin primes. You can use the generators above, and may want to look at the [itertools](https://docs.python.org/3/library/itertools.html) module together with [its recipes](https://docs.python.org/3/library/itertools.html#itertools-recipes), particularly the `pairwise` recipe.\n\n#### Solution\n\nNote: we need to first pull in the generators introduced in that notebook\n\n\n```python\ndef all_primes(N):\n \"\"\"\n Return all primes less than or equal to N.\n \n Parameters\n ----------\n \n N : int\n Maximum number\n \n Returns\n -------\n \n prime : generator\n Prime numbers\n \"\"\"\n \n primes = []\n for n in range(2, N+1):\n is_n_prime = True\n for p in primes:\n if n%p == 0:\n is_n_prime = False\n break\n if is_n_prime:\n primes.append(n)\n yield n\n```\n\nNow we can generate pairs using the pairwise recipe:\n\n\n```python\nfrom itertools import tee\n\ndef pair_primes(N):\n \"Generate consecutive prime pairs, using the itertools recipe\"\n a, b = tee(all_primes(N))\n next(b, None)\n return zip(a, b)\n```\n\nWe could examine the results of the two primes directly. But an efficient solution is to use python's [filter function](https://docs.python.org/3/library/functions.html#filter). To do this, first define a function checking if the pair are *twin* primes:\n\n\n```python\ndef check_twin(pair):\n \"\"\"\n Take in a pair of integers, check if they differ by 2.\n \"\"\"\n p1, p2 = pair\n return p2-p1 == 2\n```\n\nThen use the `filter` function to define another generator:\n\n\n```python\ndef twin_primes(N):\n \"\"\"\n Return all twin primes\n \"\"\"\n return filter(check_twin, pair_primes(N))\n```\n\nNow check by finding the twin primes with $N<20$:\n\n\n```python\nfor tp in twin_primes(20):\n print(tp)\n```\n\n (3, 5)\n (5, 7)\n (11, 13)\n (17, 19)\n\n\n## Exercise 2\n\nFind how many twin primes there are with $p_2 < 1000$.\n\n#### Solution\n\nAgain there are many solutions, but the itertools recipes has the `quantify` pattern. Looking ahead to exercise 3 we'll define:\n\n\n```python\ndef pi_N(N):\n \"\"\"\n Use the quantify pattern from itertools to count the number of twin primes.\n \"\"\"\n return sum(map(check_twin, pair_primes(N)))\n```\n\n\n```python\npi_N(1000)\n```\n\n## Exercise 3\n\nLet $\\pi_N$ be the number of twin primes such that $p_2 < N$. Plot how $\\pi_N / N$ varies with $N$ for $N=2^k$ and $k = 4, 5, \\dots 16$. (You should use a logarithmic scale where appropriate!)\n\n#### Solution\n\nWe've now done all the hard work and can use the solutions above.\n\n\n```python\nimport numpy\nfrom matplotlib import pyplot\n%matplotlib inline\n```\n\n\n```python\nN = numpy.array([2**k for k in range(4, 17)])\ntwin_prime_fraction = numpy.array(list(map(pi_N, N))) / N\n```\n\n\n```python\npyplot.semilogx(N, twin_prime_fraction)\npyplot.xlabel(r\"$N$\")\npyplot.ylabel(r\"$\\pi_N / N$\")\npyplot.show()\n```\n\nFor those that have checked Wikipedia, you'll see [Brun's theorem](https://en.wikipedia.org/wiki/Twin_prime#Brun.27s_theorem) which suggests a specific scaling, that $\\pi_N$ is bounded by $C N / \\log(N)^2$. Checking this numerically on this data:\n\n\n```python\npyplot.semilogx(N, twin_prime_fraction * numpy.log(N)**2)\npyplot.xlabel(r\"$N$\")\npyplot.ylabel(r\"$\\pi_N \\times \\log(N)^2 / N$\")\npyplot.show()\n```\n\n# A basis for the polynomials\n\nIn the section on classes we defined a `Monomial` class to represent a polynomial with leading coefficient $1$. As the $N+1$ monomials $1, x, x^2, \\dots, x^N$ form a basis for the vector space of polynomials of order $N$, $\\mathbb{P}^N$, we can use the `Monomial` class to return this basis.\n\n## Exercise 1\n\nDefine a generator that will iterate through this basis of $\\mathbb{P}^N$ and test it on $\\mathbb{P}^3$.\n\n#### Solution\n\nAgain we first take the definition of the crucial class from the notes.\n\n\n```python\nclass Polynomial(object):\n \"\"\"Representing a polynomial.\"\"\"\n explanation = \"I am a polynomial\"\n \n def __init__(self, roots, leading_term):\n self.roots = roots\n self.leading_term = leading_term\n self.order = len(roots)\n \n def __repr__(self):\n string = str(self.leading_term)\n for root in self.roots:\n if root == 0:\n string = string + \"x\"\n elif root > 0:\n string = string + \"(x - {})\".format(root)\n else:\n string = string + \"(x + {})\".format(-root)\n return string\n \n def __mul__(self, other):\n roots = self.roots + other.roots\n leading_term = self.leading_term * other.leading_term\n return Polynomial(roots, leading_term)\n \n def explain_to(self, caller):\n print(\"Hello, {}. {}.\".format(caller,self.explanation))\n print(\"My roots are {}.\".format(self.roots))\n return None\n```\n\n\n```python\nclass Monomial(Polynomial):\n \"\"\"Representing a monomial, which is a polynomial with leading term 1.\"\"\"\n explanation = \"I am a monomial\"\n \n def __init__(self, roots):\n Polynomial.__init__(self, roots, 1)\n \n def __repr__(self):\n string = \"\"\n for root in self.roots:\n if root == 0:\n string = string + \"x\"\n elif root > 0:\n string = string + \"(x - {})\".format(root)\n else:\n string = string + \"(x + {})\".format(-root)\n return string\n```\n\nNow we can define the first basis:\n\n\n```python\ndef basis_pN(N):\n \"\"\"\n A generator for the simplest basis of P^N.\n \"\"\"\n \n for n in range(N+1):\n yield Monomial(n*[0])\n```\n\nThen test it on $\\mathbb{P}^N$:\n\n\n```python\nfor poly in basis_pN(3):\n print(poly)\n```\n\n \n x\n xx\n xxx\n\n\nThis looks horrible, but is correct. To really make this look good, we need to improve the output. If we use\n\n\n```python\nclass Monomial(Polynomial):\n \"\"\"Representing a monomial, which is a polynomial with leading term 1.\"\"\"\n explanation = \"I am a monomial\"\n \n def __init__(self, roots):\n Polynomial.__init__(self, roots, 1)\n \n def __repr__(self):\n if len(self.roots):\n string = \"\"\n n_zero_roots = len(self.roots) - numpy.count_nonzero(self.roots)\n if n_zero_roots == 1:\n string = \"x\"\n elif n_zero_roots > 1:\n string = \"x^{}\".format(n_zero_roots)\n else: # Monomial degree 0.\n string = \"1\"\n for root in self.roots:\n if root > 0:\n string = string + \"(x - {})\".format(root)\n elif root < 0:\n string = string + \"(x + {})\".format(-root)\n return string\n```\n\nthen we can deal with the uglier cases, and re-running the test we get\n\n\n```python\nfor poly in basis_pN(3):\n print(poly)\n```\n\n 1\n x\n x^2\n x^3\n\n\nAn even better solution would be to use the `numpy.unique` function as in [this stackoverflow answer](http://stackoverflow.com/questions/10741346/numpy-most-efficient-frequency-counts-for-unique-values-in-an-array) (the second one!) to get the frequency of all the roots.\n\n## Exercise 2\n\nAn alternative basis is given by the monomials\n\n\\begin{align}\n p_0(x) &= 1, \\\\ p_1(x) &= 1-x, \\\\ p_2(x) &= (1-x)(2-x), \\\\ \\dots & \\quad \\dots, \\\\ p_N(x) &= \\prod_{n=1}^N (n-x).\n\\end{align}\n\nDefine a generator that will iterate through this basis of $\\mathbb{P}^N$ and test it on $\\mathbb{P}^4$.\n\n#### Solution\n\n\n```python\ndef basis_pN_variant(N):\n \"\"\"\n A generator for the 'sum' basis of P^N.\n \"\"\"\n \n for n in range(N+1):\n yield Monomial(range(n+1))\n```\n\n\n```python\nfor poly in basis_pN_variant(4):\n print(poly)\n```\n\n x\n x(x - 1)\n x(x - 1)(x - 2)\n x(x - 1)(x - 2)(x - 3)\n x(x - 1)(x - 2)(x - 3)(x - 4)\n\n\nI am too lazy to work back through the definitions and flip all the signs; it should be clear how to do this!\n\n## Exercise 3\n\nUse these generators to write another generator that produces a basis of $\\mathbb{P^3} \\times \\mathbb{P^4}$.\n\n#### Solution\n\nHopefully by now you'll be aware of how useful `itertools` is!\n\n\n```python\nfrom itertools import product\n```\n\n\n```python\ndef basis_product():\n \"\"\"\n Basis of the product space\n \"\"\"\n yield from product(basis_pN(3), basis_pN_variant(4))\n```\n\n\n```python\nfor p1, p2 in basis_product():\n print(\"Basis element is ({}) X ({}).\".format(p1, p2))\n```\n\n Basis element is (1) X (x).\n Basis element is (1) X (x(x - 1)).\n Basis element is (1) X (x(x - 1)(x - 2)).\n Basis element is (1) X (x(x - 1)(x - 2)(x - 3)).\n Basis element is (1) X (x(x - 1)(x - 2)(x - 3)(x - 4)).\n Basis element is (x) X (x).\n Basis element is (x) X (x(x - 1)).\n Basis element is (x) X (x(x - 1)(x - 2)).\n Basis element is (x) X (x(x - 1)(x - 2)(x - 3)).\n Basis element is (x) X (x(x - 1)(x - 2)(x - 3)(x - 4)).\n Basis element is (x^2) X (x).\n Basis element is (x^2) X (x(x - 1)).\n Basis element is (x^2) X (x(x - 1)(x - 2)).\n Basis element is (x^2) X (x(x - 1)(x - 2)(x - 3)).\n Basis element is (x^2) X (x(x - 1)(x - 2)(x - 3)(x - 4)).\n Basis element is (x^3) X (x).\n Basis element is (x^3) X (x(x - 1)).\n Basis element is (x^3) X (x(x - 1)(x - 2)).\n Basis element is (x^3) X (x(x - 1)(x - 2)(x - 3)).\n Basis element is (x^3) X (x(x - 1)(x - 2)(x - 3)(x - 4)).\n\n\nI've cheated here as I haven't introduced the `yield from` syntax (which returns an iterator from a generator). We could write this out instead as\n\n\n```python\ndef basis_product_long_form():\n \"\"\"\n Basis of the product space (without using yield_from)\n \"\"\"\n prod = product(basis_pN(3), basis_pN_variant(4))\n yield next(prod)\n```\n\n\n```python\nfor p1, p2 in basis_product():\n print(\"Basis element is ({}) X ({}).\".format(p1, p2))\n```\n\n Basis element is (1) X (x).\n Basis element is (1) X (x(x - 1)).\n Basis element is (1) X (x(x - 1)(x - 2)).\n Basis element is (1) X (x(x - 1)(x - 2)(x - 3)).\n Basis element is (1) X (x(x - 1)(x - 2)(x - 3)(x - 4)).\n Basis element is (x) X (x).\n Basis element is (x) X (x(x - 1)).\n Basis element is (x) X (x(x - 1)(x - 2)).\n Basis element is (x) X (x(x - 1)(x - 2)(x - 3)).\n Basis element is (x) X (x(x - 1)(x - 2)(x - 3)(x - 4)).\n Basis element is (x^2) X (x).\n Basis element is (x^2) X (x(x - 1)).\n Basis element is (x^2) X (x(x - 1)(x - 2)).\n Basis element is (x^2) X (x(x - 1)(x - 2)(x - 3)).\n Basis element is (x^2) X (x(x - 1)(x - 2)(x - 3)(x - 4)).\n Basis element is (x^3) X (x).\n Basis element is (x^3) X (x(x - 1)).\n Basis element is (x^3) X (x(x - 1)(x - 2)).\n Basis element is (x^3) X (x(x - 1)(x - 2)(x - 3)).\n Basis element is (x^3) X (x(x - 1)(x - 2)(x - 3)(x - 4)).\n\n\n# Anscombe's quartet\n\nFour separate datasets are given:\n\n| x | y | x | y | x | y | x | y |\n|------|-------|------|------|------|-------|------|-------|\n| 10.0 | 8.04 | 10.0 | 9.14 | 10.0 | 7.46 | 8.0 | 6.58 |\n| 8.0 | 6.95 | 8.0 | 8.14 | 8.0 | 6.77 | 8.0 | 5.76 |\n| 13.0 | 7.58 | 13.0 | 8.74 | 13.0 | 12.74 | 8.0 | 7.71 |\n| 9.0 | 8.81 | 9.0 | 8.77 | 9.0 | 7.11 | 8.0 | 8.84 |\n| 11.0 | 8.33 | 11.0 | 9.26 | 11.0 | 7.81 | 8.0 | 8.47 |\n| 14.0 | 9.96 | 14.0 | 8.10 | 14.0 | 8.84 | 8.0 | 7.04 |\n| 6.0 | 7.24 | 6.0 | 6.13 | 6.0 | 6.08 | 8.0 | 5.25 |\n| 4.0 | 4.26 | 4.0 | 3.10 | 4.0 | 5.39 | 19.0 | 12.50 |\n| 12.0 | 10.84 | 12.0 | 9.13 | 12.0 | 8.15 | 8.0 | 5.56 |\n| 7.0 | 4.82 | 7.0 | 7.26 | 7.0 | 6.42 | 8.0 | 7.91 |\n| 5.0 | 5.68 | 5.0 | 4.74 | 5.0 | 5.73 | 8.0 | 6.89 |\n\n## Exercise 1\n\nUsing standard `numpy` operations, show that each dataset has the same mean and standard deviation, to two decimal places.\n\n#### Solution\n\n\n```python\nimport numpy\n```\n\n\n```python\nset1_x = numpy.array([10.0, 8.0, 13.0, 9.0, 11.0, 14.0, 6.0, 4.0, 12.0, 7.0, 5.0])\nset1_y = numpy.array([8.04, 6.95, 7.58, 8.81, 8.33, 9.96, 7.24, 4.26, 10.84, 4.82, 5.68])\nset2_x = numpy.array([10.0, 8.0, 13.0, 9.0, 11.0, 14.0, 6.0, 4.0, 12.0, 7.0, 5.0])\nset2_y = numpy.array([9.14, 8.14, 8.74, 8.77, 9.26, 8.10, 6.13, 3.10, 9.13, 7.26, 4.74])\nset3_x = numpy.array([10.0, 8.0, 13.0, 9.0, 11.0, 14.0, 6.0, 4.0, 12.0, 7.0, 5.0])\nset3_y = numpy.array([7.46, 6.77, 12.74, 7.11, 7.81, 8.84, 6.08, 5.39, 8.15, 6.42, 5.73])\nset4_x = numpy.array([8.0, 8.0, 8.0, 8.0, 8.0, 8.0, 8.0, 19.0, 8.0, 8.0, 8.0])\nset4_y = numpy.array([6.58, 5.76, 7.71, 8.84, 8.47, 7.04, 5.25, 12.50, 5.56, 7.91, 6.89])\n\ndata_x = set1_x, set2_x, set3_x, set4_x\ndata_y = set1_y, set2_y, set3_y, set4_y\n```\n\n\n```python\nprint(\"Results for x:\")\nfor x in data_x:\n print(\"Mean: {:.2f}. Variance {:.2f}. Standard deviation {:.2f}.\".format(numpy.mean(x),\n numpy.var(x),\n numpy.std(x)))\nprint(\"Results for y:\")\nfor data in data_y:\n print(\"Mean: {:.2f}. Variance {:.2f}. Standard deviation {:.2f}.\".format(numpy.mean(data),\n numpy.var(data),\n numpy.std(data)))\n```\n\n Results for x:\n Mean: 9.00. Variance 10.00. Standard deviation 3.16.\n Mean: 9.00. Variance 10.00. Standard deviation 3.16.\n Mean: 9.00. Variance 10.00. Standard deviation 3.16.\n Mean: 9.00. Variance 10.00. Standard deviation 3.16.\n Results for y:\n Mean: 7.50. Variance 3.75. Standard deviation 1.94.\n Mean: 7.50. Variance 3.75. Standard deviation 1.94.\n Mean: 7.50. Variance 3.75. Standard deviation 1.94.\n Mean: 7.50. Variance 3.75. Standard deviation 1.94.\n\n\n## Exercise 2\n\nUsing the standard `scipy` function, compute the linear regression of each data set and show that the slope and correlation coefficient match to two decimal places.\n\n\n```python\nfrom scipy import stats\n\nfor x, y in zip(data_x, data_y):\n slope, intercept, r_value, p_value, std_err = stats.linregress(x, y)\n print(\"Slope: {:.2f}. Correlation: {:.2f}.\".format(slope, r_value))\n```\n\n Slope: 0.500. Correlation: 0.816.\n Slope: 0.500. Correlation: 0.816.\n Slope: 0.500. Correlation: 0.816.\n Slope: 0.500. Correlation: 0.817.\n\n\n## Exercise 3\n\nPlot each dataset. Add the best fit line. Then look at the description of [Anscombe's quartet](https://en.wikipedia.org/wiki/Anscombe%27s_quartet), and consider in what order the operations in this exercise *should* have been done.\n\n\n```python\n%matplotlib inline\nfrom matplotlib import pyplot\n\nfit_x = numpy.linspace(2.0, 20.0)\nfig = pyplot.figure(figsize=(12,6))\nfor i in range(4):\n slope, intercept, r_value, p_value, std_err = stats.linregress(data_x[i], data_y[i])\n ax = fig.add_subplot(2,2,i+1)\n ax.scatter(data_x[i], data_y[i])\n ax.plot(fit_x, intercept + slope*fit_x)\n ax.set_xlim(2.0, 20.0)\n ax.set_xlabel(r'$x$')\n ax.set_ylabel(r'$y$')\npyplot.show()\n```\n", "meta": {"hexsha": "91a50f43044da4fdf4f45b5938cda33430cb556d", "size": 712747, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "ExercisesSolutions.ipynb", "max_stars_repo_name": "IanHawke/maths-with-python", "max_stars_repo_head_hexsha": "9ca8054462e84045353a1a8f7158a87760a93cc8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 70, "max_stars_repo_stars_event_min_datetime": "2015-06-26T21:14:03.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-20T02:36:02.000Z", "max_issues_repo_path": "ExercisesSolutions.ipynb", "max_issues_repo_name": "QuantumNovice/maths-with-python", "max_issues_repo_head_hexsha": "9ca8054462e84045353a1a8f7158a87760a93cc8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 19, "max_issues_repo_issues_event_min_datetime": "2015-08-19T06:39:42.000Z", "max_issues_repo_issues_event_max_datetime": "2017-03-04T12:36:13.000Z", "max_forks_repo_path": "content/notebooks/ExercisesSolutions.ipynb", "max_forks_repo_name": "IanHawke/maths-with-python-book", "max_forks_repo_head_hexsha": "552be64d07ff218988885f272194786b4cd30716", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 49, "max_forks_repo_forks_event_min_datetime": "2015-08-21T02:42:12.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-03T14:20:08.000Z", "avg_line_length": 146.2645187769, "max_line_length": 176742, "alphanum_fraction": 0.8707619955, "converted": true, "num_tokens": 22666, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404057671714, "lm_q2_score": 0.9632305330008187, "lm_q1q2_score": 0.8952653774396097}} {"text": "# On my way to linear regression\n\nIn this notebook, I show my path to linear regression. Before using a whole bunch of predefined functions from python libraries which will do a linear regression for me, I want to figure out what's under the hood and how it's working. So, first, I will start with a linear function and see how this can be plot in python.\n\n\n\n\n## Linear function, part 1\n\nAs we all should know from school, the general formula for a linear function is \n\n\\begin{equation} \nf(x) = m \\cdot x + b\n\\end{equation}\n\nwhere m is the slope and b the y-intercept. The following lines of code show how to program a linear function in python using the numpy library. You may experiment with the code but be aware this code is just a concept, not a complete program, so I decided to renounce error checking.\n\n\n```python\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n# 10 linearly spaced numbers in th einterval of [-10,10]\nx=np.linspace(-10,10,10)\n\n# y intercept\nb = 3\n# slope\nm = 2\n# declaration of function f(x) which is y=mx+b here\ny = m*x + b\n\nfig = plt.figure()\nax = fig.add_subplot(1,1,1)\n\nax.spines['left'].set_position('center')\nax.spines['right'].set_color('none')\nax.spines['top'].set_color('none')\nax.spines['bottom'].set_position('zero')\n\nax.xaxis.set_ticks_position('bottom')\nax.yaxis.set_ticks_position('left')\n\nplt.plot(x,y,'red')\nplt.show\n```\n\n## Linear function, part 2\n\nIn the first example, we set the slope and y-intercept by manipulating values in the code. But, what is to do if we do not have a slope or the y-intercept so far but only 2 coordinates (x1, y1) and (x2, y2)? We must calculate the missing values ourself. To calculate a slope, you simply divide y by x. Since we have two values to take into consideration, we have to calculate the delta between the y and x values:\n\n\\begin{equation}\nslope = m = \\frac{\\Delta y}{\\Delta x} = \\frac{y_2 - y_1}{x_2 - x_1} \n\\end{equation}\n\nExample: Let P1 = (-3,-2) and P2 = (5,4). Put in the equation above we get\n\n\\begin{equation}\nslope = m = \\frac{\\Delta y}{\\Delta x} = \\frac{y_2 - y_1}{x_2 - x_1} = \\frac{4 - (-2)}{5 - (-3)} = \\frac{6}{8} = \\frac{3}{4}\n\\end{equation}\n\nFinding the y-intercept, given the slope and one point is no problem anymore\n\n\\begin{equation}\ny = m \\cdot x + b \\Leftrightarrow \ny - m \\cdot x = b\n\\end{equation}\n\nPutting P2 = (5,4) in the equation above we get\n\n\\begin{equation}\n4 - \\frac{3}{4} \\cdot 5 = b \\leftrightarrow\n4 - \\frac{15}{4} = 4 - 3\\frac{3}{4} = \\frac{1}{4} = b\n\\end{equation}\n\nSo the y-intercept is 1/4. Put the values for b and m in the source code. A scatter plot has been added as overlay above the line plot. As you can see, both points are on the line.\n\n\n```python\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n# 10 linearly spaced numbers in th einterval of [-10,10]\nx=np.linspace(-10,10,10)\n\n# y intercept\nb = 0.25\n# slope\nm = 0.75\n# declaration of function f(x) which is y=mx+b here\ny = m*x + b\n\nfig = plt.figure()\nax = fig.add_subplot(1,1,1)\n\nax.spines['left'].set_position('center')\nax.spines['right'].set_color('none')\nax.spines['top'].set_color('none')\nax.spines['bottom'].set_position('zero')\n\nax.xaxis.set_ticks_position('bottom')\nax.yaxis.set_ticks_position('left')\n\n#\n# begin\n# this is the part for drawing the two points as scatter polot\n#\n\n# put p1 and p2 in a list\n# put the x values\nscatter_x = [-3, 5]\n# put the y values\nscatter_y = [-2, 4]\nplt.scatter(scatter_x,scatter_y)\n\n#\n# end\n# this is the part for drawing the two points as scatter polot\n#\n\nplt.plot(x,y,'red')\nplt.show\n\n```\n\n## Linear function, part 3\n\nIf only two points are given, it is always possible to draw a straight line by these two points.If there are more than two points, it is no longer possible to assume that all points are on the calculated straight line. In this case, it is necessary to make a compensation calculation to determine the best straight line for the point cloud. A typical and also easy-to-understand method of balancing calculation is the method of the smallest squares.\n\n Here, the unknowns (parameters) of the model are determined in such a way that the square sum of the measurement deviations of all observations is minimized and thus the measurement curve and theory curve correspond best.\nThis is an optimization process. The calculation steps of a balancing process are simplified if the observations are considered to be normally distributed, equal and uncorrelated. The stochastic properties of the observations in the regression analysis are examined.\n\nLet's repeat the equation for linear equations\n\n\\begin{equation} \nf(x) = y = m \\cdot x + b\n\\end{equation}\n\nand find a more general formula:\n\n\\begin{equation} \ny = \\beta_0 + \\beta_1 \\cdot x\n\\end{equation}\n\nwhere m and b are redefined by \n\n\\begin{equation} \nb = \\beta_0 \n\\end{equation}\n\\begin{equation} \nm = \\beta_1\n\\end{equation}\n\nThe formula for the slope's calculation via the smallest squares is\n\n\\begin{equation} \n\\beta_1 = \\frac{\\sum_{i=1}^{n} (x_i - \\bar{x}) \\cdot (y_i - \\bar{y})}{\\sum_{i=1}^n (x_i - \\bar{x})^2}\n\\end{equation}\n\nwhere $\\bar{x}$ is the mean of the x-values and $\\bar{y}$ is the mean of the y-values. $\\beta_0$ can be calculated as\n\n\\begin{equation}\n\\beta_0 = \\bar{y} - \\beta_1\\cdot \\bar{x}\n\\end{equation}\n\nTime to get our hands dirty...\n\n\n\n## One ring to rule them all\n\nWe want to give our girlfriend a ring for Christmas, but we don't know her ring size. Now it would be doofy to ask her about the ring size, so the whole surprise would be gone. Therefore we would like to appreciate the ring size (y) of our girlfriend. But we only know their height (x). To estimate the ring size, we collect 10 data points from friends and acquaintances, and record their height and ring size:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
Person \\(i\\)12345678910
Height \\(x\\)156.3158.9160.8179.6156.6165.1165.9156.7167.8160.8
Ring size \\(y\\)47.146.849.353.247.749.050.647.151.747.8
\n\nWe call y the target size here, because their prediction is our goal. The height x is commonly called influence size. However, there are countless other names for the two types of variables. In other sources, y is also often called target variable, regressing edge, outcome, explained variable, or dependent variable (because it depends on x). Other names for x are covariable, input, regressor, explanatory variable, or independent variable.\n\nWait... regressing edge? Regressor? Hmmm....\nSounds like we are building a linear regression model\n\n\n```python\nimport matplotlib.pyplot as plt \nimport numpy as np\n\n# enter the body height (x)\n# enter the ring size (y)\nx = [156.3, 158.9, 160.8, 179.6, 156.6, 165.1, 165.9, 156.7, 167.8, 160.8] \ny = [47.1, 46.8, 49.3, 53.2, 47.7, 49.0, 50.6, 47.1, 51.7, 47.8]\n\n# calculate the arithmetic mean\n# for both x and y\nx_mean = sum(x)/len(x)\ny_mean = sum(y)/len(y)\n\n# let's call the values (xi - x) x_opt\n# let's call the values (yi - y) y_opt\nx_opt = []\ny_opt = []\n\n# calculate a list with (xi -x)\nfor x_item in x:\n x_opt.append(x_item-x_mean)\n\n# calculate a list with (yi -y)\nfor y_item in y:\n y_opt.append(y_item-y_mean)\n\n# multiply each element from two lists \ndenominator = sum(x * y for x, y in zip(x_opt, x_opt)) \nnumerator = sum(x * y for x, y in zip(x_opt, y_opt))\n\n# calculate the slope\nm = numerator / denominator\n# calculate the y-intercept\nb = y_mean - m*x_mean\n\n# draw a scatter plot with the tupels \nfigure = plt.figure()\nax = figure.add_subplot(1,1,1)\nax.set_ylabel('ring size')\nax.set_xlabel('height')\nax.set_ylim(45,55)\nplt.scatter(x, y) \n\n# draw the regression line\nx_line = [min(x), max(x)]\ny_line = [b + m*min(x), b + m*max(x)]\nplt.plot(x_line,y_line,'red')\n\n# show the plot\nplt.show()\n```\n\n## Prediction in simple linear regression\n\nSo far, we have learned how to calculate the two coefficients a and b. Now we want to use the parameters to predict for new data x what value we expect for y.\n\nThe goal we want to achieve with regression is this: Suppose a new person comes, of which we only know the height x=170. What then is the expected value of the ring size y? So we are looking for E(y|x), the conditional expected value of y, given one knows x.\n\nIn simple linear regression, there is only one influence x. The regression line is therefore\n\n\\begin{equation}\ny = \\beta_0 + \\beta_1 \\cdot x\n\\end{equation}\n\nSo to get a prediction for target size y, we simply need to insert the corresponding value for x into the equation. We have already calculated the values for $\\beta_0$ and $\\beta_1$ beforehand.\n\nFor example, in the shown code, we determined the values $\\beta_1=2.8457$ and $\\beta_0=0.2836$. What ring size can be expected of your girlfriend if she has a height of x=170cm? For this we calculate:\n\n\\begin{equation}\ny = \\beta_0 + \\beta_1 \\cdot x = 2.8457 + 0.2836 \\cdot 170 = 51.0577\n\\end{equation}\n\nA ring with a size 51 should therefore fit well with her.\n\nIt is still important to mention here that we only predict the expected value of y. So the ring size will not be exactly 51.06, but there is always a small error, which is called in the linear model ε (read: Epsilon). In reality, the regression equation is\n\n\\begin{equation}\ny = \\beta_0 + \\beta_1 \\cdot x + \\epsilon\n\\end{equation}\n\n\n```python\n\n```\n", "meta": {"hexsha": "6243b7dcb69748b3a1e975f6386232a2f735c216", "size": 49610, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "linear_regression.ipynb", "max_stars_repo_name": "jegali/DataScience", "max_stars_repo_head_hexsha": "1331be6133f5d725b983821000df501e6ceb028c", "max_stars_repo_licenses": ["CNRI-Python"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-12-28T04:18:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-28T12:55:08.000Z", "max_issues_repo_path": "linear_regression.ipynb", "max_issues_repo_name": "Emoghena/DataScience", "max_issues_repo_head_hexsha": "1331be6133f5d725b983821000df501e6ceb028c", "max_issues_repo_licenses": ["CNRI-Python"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "linear_regression.ipynb", "max_forks_repo_name": "Emoghena/DataScience", "max_forks_repo_head_hexsha": "1331be6133f5d725b983821000df501e6ceb028c", "max_forks_repo_licenses": ["CNRI-Python"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-01-12T04:38:45.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-24T18:44:29.000Z", "avg_line_length": 115.9112149533, "max_line_length": 12212, "alphanum_fraction": 0.8467446079, "converted": true, "num_tokens": 2854, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248225478306, "lm_q2_score": 0.9532750398805294, "lm_q1q2_score": 0.8951489251630903}} {"text": "# Numerical Integration\n\nNumerical integration can be expressed as the following approximate sum:\n\n$$I = \\int_a^b f(x) dx \\approx \\sum_{i=1}^{n} A_i f(x_i)$$\n\nwhere $A_i$ are the weights associated with the function evaluated at $x_i$. Typically, $n+1$ data points $x_i, i = 0,1,2, \\ldots , n$ are selected starting from $a$ upto $b$, and the function is evaluated at each of these ordinates. The weighted sum above is an approximation to the integral we are attemptying to evaluate.\n\nThere are two main approaches to carrying out numerical integration. The first approach based on Newton-Cotes formulae divides the interval $a$ to $b$ into a certain number of panels, usually of equal width. If $n$ is the number of panels, then $n+1$ is the number of ordinates, and the function is evaluated at each of these ordinates. For such methods, accuracy usually increases with the number of panels. The second approach is based on Gauss Quadrature. These methods evaluate the function at only a few specified ordinates. Gauss quadrature usually gives accurate results even with only a few function evaluations and can be used even when the limits tend to infinity.\n\n## Newton-Cotes Formulas\nNewton-Cotes formulas are based on approximating the given function by a polynomial and computing the integral of the polynomial.\n\n$$I = \\int_a^b f(x) dx \\approx \\int_a^b f_n(x) dx$$\n\nwhere $f_n(x)$ is a polynomial of the form $f_n(x) = a_0 + a_1 c + a_2 x^2 + \\cdots + a_{n-1} x^{n-1} + a_n x^n$.\n\nTrapezoidal Rule is Newton-Cotes formula with $n=1$, which is the equation of a straigt line. Simpson's 1/3 Rule is Newton-Cotes formula with $n=2$, which is a parabola. Trapezoidal rule requires us to determine two unknowns, $a_0$ and $a_1$, thereby requiring two points whereas Simpson's 1/3 rule requires three unknowns $a_0$, $a_1$ and $a_2$, thereby requiring three points. It is easier to obtain the coefficients $a_i$ if the panels are of equal width. The formula for Trapezoidal rule is as follows:\n\n$$I \\approx \\frac{h}{2} \\left[ f(a) + f(a+h) \\right]$$\n\nSimpson's 1/3 rule is as follows:\n\n$$I \\approx \\frac{h}{3} \\left[ f(a) + 4 f(a+h) + f(a+2h) \\right]$$\n\n## Example\nLet us consider the function $f(x) = e^{-x^2}$ and integrate it between the limits $a=0$ to $b=1$, $I = \\int_{0}^{1} e^{-x^2} dx$. Let us first use SymPy to calculate the exact answer. In SymPy we must define the symbols that we will use for variables, in this case $x$. We will then define the equation that we wish to integrate, the symbol for the variable and the lower and upper limits of integration. Method **`doit()`** evaluates the integral and the function **`N()`** calculates the numerical value of the integral.\n\n\n```python\nfrom sympy import *\nx = symbols('x')\ninit_printing()\n\nc = Integral(exp(-x**2), (x, 0, 1))\nEq(c, c.doit())\n```\n\n\n```python\nd = N(c.doit())\nprint d\n```\n\n 0.746824132812427\n\n\nWe now have the value of the integral stored in the object $d$, which we can use later.\n\n## Trapezoidal Rule\n\n\nConsidering one panel, $(x_i, y_i)$ and $(x_{i+1}, y_{i+1})$, and assuming the function to be varying linearly, we get:\n$$ I = \\frac{y_i + y_{i+1}}{2} \\, h$$\nwhere $h = x_{i+1} - x_i$.\n\n### Composite Trapezoidal Rule\nLet the range $a$ to $b$ be divided into $n$ equal panels, each of width $h = \\frac{b - a}{n}$. Thus the number of data points is $n+1$ and the ordinate of the points is $x_i = a + (i \\cdot h), i = 0, 1, \\ldots , n$.\n\nTrapezoidal rule assumes the function to vary linearly between successive data points, and the resulting approximation to the integral is given as:\n\n$$I = \\int_a^b f(x) dx \\approx \\frac{h}{2} \\left( y_0 + 2 \\sum_{i=1}^{n-2} y_i + y_{n-1} \\right)$$\n\nwhere $y_i = f(x_i)$ is the value of the function evaluated at each ordindate.\n\n\n```python\nfrom __future__ import division\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n%matplotlib inline\n\ndef trapezoidal(y, h):\n n = len(y)\n if n < 2:\n return None\n elif n == 2:\n s = (y[0] + y[1]) * h / 2.0\n else:\n s = (y[0] + y[-1] + 2* np.sum(y[1:-1])) * h / 2.0\n return s\n\nx = np.linspace(0, np.pi/2, 21)\ny = np.sin(x)\nh = x[1] - x[0]\ns1 = trapezoidal(y, h)\nprint 'Trapezoidal rule with %d points: %f' % (len(x), s1)\nplt.plot(x, y)\nplt.grid()\nplt.title('sin(x) with %d points' % (len(x)))\nplt.xlabel('x')\nplt.ylabel('sin(x)')\nplt.show()\n\nn = [6, 11, 21, 51, 101, 501, 1001]\nfor nn in n:\n x = np.linspace(0, np.pi/2, nn)\n y = np.sin(x)\n h = x[1] - x[0]\n s = trapezoidal(y, h)\n print 'Trapezoidal rule with %4d points: %f' % (len(x), s)\n```\n\n## Simpson's 1/3 Rule\n\n\nConsidering two consecutine panels $(x_i, y_i), (x_{i+1}, y_{i+1}), (x_{i+2}, y_{i+2})$, where $h = x_{i+1} - x_i = x_{i+2} - x_{i+1}$\n$$ I = \\left( y_i + 4 \\, y_{i+1} + y_{i+2} \\right) \\frac{h}{3} $$\n\n### Composite Simpson's 1/3 Rule\nIf the interval from $a$ to $b$ is divided into $n$ equal panels each of width $h = \\frac{b - a}{n}$ and $n+1$ is the number of ordinates, for Simpson's 1/3 rule, $n$ must be an even number (and $n+1$, obviously must be an odd number).\n\nSimpson's 1/3 rule fits a parabola (polynomial of order two) between three successive points and approximates the integral for the two consecutive panels. To be able to do so, the number of data points must be atleast 3 and the number of panels must be an even number. The composite Simpson's 1/3 rule for $n$ data points, and $n-1$ panels (where $n-1$ must be even) is given below:\n\n$$I = \\int_a^b f(x) dx \\approx \\frac{h}{3} \\left( y_0 + 4 \\sum_{i=1, 3, 5,\\ldots}^{n-2} y_i + 2 \\sum_{j=2,4,6,\\ldots}^{n-3} y_j \\right)$$\n\n\n```python\ndef simpson(y, h):\n n = len(y)\n if n < 3:\n return None\n elif n == 3:\n s = y[0] + 4 * y[1] + y[2]\n return s * h / 3.0\n elif n % 2 == 1:\n s = (y[0] + y[-1] + 4 * np.sum(y[1:-1:2]) + 2 * np.sum(y[2:-2:2])) * h / 3.0\n else:\n s = (y[0] + y[-2] + 4 * np.sum(y[1:-2:2]) + 2 * np.sum(y[2:-3:2])) * h / 3.0\n s += (y[-2] + y[-1]) * h / 2.0\n return s\n\nx = np.linspace(0, np.pi/2, 21)\ny = np.sin(x)\nh = x[1] - x[0]\ns2 = simpson(y, h)\nprint \"Simpson's 1/3 rule with %d points: %f\" % (len(x), s2)\n\nx = np.linspace(0, np.pi/2, 101)\ny = np.sin(x)\nh = x[1] - x[0]\ns3 = trapezoidal(y, h)\nprint 'Trapezoidal rule with %d points: %f' % (len(x), s3)\ns4 = simpson(y, h)\nprint \"Simpson's 1/3 rule with %d points: %f\" % (len(x), s4)\n\nplt.plot(x, y)\nplt.grid()\nplt.title(\"sin(x) with %d points\" % (len(x)))\nplt.xlabel('x')\nplt.ylabel('sin(x)')\nplt.show()\n\nn = [7, 11, 21, 51, 101, 501, 1001]\nfor nn in n:\n x = np.linspace(0, np.pi/2, nn)\n y = np.sin(x)\n h = x[1] - x[0]\n s = simpson(y, h)\n print \"Simpson's rule with %4d points: %f\" % (len(x), s)\n```\n\nIt is possible to evaluate an integral exactly using symbolic computing. SymPy is a Python module for symbolic computing and we can find the exact integral as follows:\n\n\n```python\nimport sympy\nfrom sympy import init_printing\n\ninit_printing()\n\nxx, yy = sympy.symbols('x y')\nyy = sympy.sin(xx)\nyy\nA = sympy.integrate(yy, (xx, 0, pi/2))\nprint A\n```\n\n 1\n\n\n## Stress Distribution in Concrete as per IS456:2000\n\nAs per IS 456:2000, it is assumed that the strain varies linearly across the depth of a cross section. IS 456:2000 also specifies the stress strain relationship for concrete and steel. We can use this information to determine the stress distribution across the depth of a concrete beam, find the stress resultant and its point of action using numerical integration.\n$$\n\\begin{align*}\n\\frac{\\epsilon_c}{x} & = \\frac{\\epsilon_{cu}}{x_u} \\\\\n\\epsilon_c & = \\frac{\\epsilon_{cu}}{x_u} \\, x \\\\\nf_c & = \\begin{cases}\n0.446 \\, f_{ck} \\left[ 2 \\, \\left( \\frac{\\epsilon_c}{\\epsilon_{cy}} \\right) - \\left( \\frac{\\epsilon_c}{\\epsilon_{cy}} \\right)^2 \\right] & 0 \\leq \\epsilon_c \\leq \\epsilon_{cy} \\\\\n0.446 \\, f_{ck} & \\epsilon_{cy} < \\epsilon_{c} \\leq \\epsilon_{cu}\n\\end{cases} \\\\\nC & = b \\, \\int_{0}^{x_u} f_c \\, dx \\\\\n & = b \\, \\int_{0}^{x_u} f_c \\, dx \\\\\n M & = \\int_{0}^{x_u} f_c \\, b \\, x \\, dx \\\\\n & = b \\, \\int_{0}^{x_u} f_c \\, x \\, dx \\\\\n \\bar{x} & = \\frac{M}{C}\n\\end{align*}\n$$\n\nAt collapse, strain in concrete is $\\epsilon_{cu} = 0.0035$. If we know the depth of neutral axis, we can determine the strain and stress at different locations across the depth. Magnitude of the stress resultant is given by the area of the stress distribution, which is obtained by integrating stress across the depth. Moment of the stress resultant about the neutral axis is obtained by integrating \n\n\n```python\ndef conc_stress(ec, fck, ecy=0.002):\n if ec < ecy:\n ee = ec / ecy\n fc = 2 * ee - ee**2\n else:\n fc = 1.0\n return 4.0 / 9.0 * fck * fc\n\necu = 0.0035\nxu = 125.0\nfck = 25.0\nxx = np.linspace(0, xu, 101)\nx = xx * ecu / xu\ny = np.array([conc_stress(e, fck) for e in x])\n\nplt.plot(xx, y)\nplt.grid()\nplt.show()\n\nh = xx[1] - xx[0]\nC = simpson(y, h)\nprint C, 68/189*fck*xu\n```\n\n\n```python\nyy = y * xx\nM = simpson(yy, h)\nxbar = M/C\nprint xu - xbar, 99/238*xu, (0.416*xu - (xu - xbar)) / (99/238*xu) * 100\n```\n\n 51.9957981734 51.9957983193 0.00808108882941\n\n\nThe actual area of stress diagram is given by\n$$A = \\frac{68}{189} \\, f_{ck} \\, b \\, x_u$$\nAssuming $f_{ck}=25, b=1 \\text{ and } x_u = 125$, we get $A = \\frac{68}{189} \\times 25 \\times 1 \\times 125 = 1124.3386$. \n\n## Improvements\nAccuracy of the integral depends on the step size (that is, number of intervals). More the number of intervals, more accurate is the integral. Theoretically, a numerical method can never give the accurate answer. Trapezoidal rule is simple but not as accurate as Simpson's rule for the same number of data points.\n\nThere is a recursive form of trapezoidal rule where we can begin with only one interval and successively keep on doubling the number of intervals. Each time we double the number of intervals, the value of the integral will improve. We can keep checking the change in the integral in subsequent iterations and stop when the change is too small.\n\n## References\n1. Chapra, S.C., _Applied Numerical Methods with MATLAB for Engineers and Scientists_, 3ed., McGraw Hill, 2008.\n2. Kiusalaas, J., _Numerical Methods in Engineering with Python_, Cambridge University Press, 2005.\n3. IS456:2000, Plain and Reinforced Concrete - Code of Practice (Fourth Revision), Bureau of Indian Standards, New Delhi, 2000\n\n## Gauss Quadrature\n### Gauss-Legendre Quadrature\n\n\n```python\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\nt = np.arange(0.0, 1.01, 0.01)\ns = np.sin(2*2*np.pi*t)\n\nplt.fill(t, s*np.exp(-5*t), 'r')\nplt.grid(True)\nplt.show()\n```\n\n\n```python\ndef f(x):\n return 120.0*(x+0.5)*(x+0.25)*x*(x-1.0/3.0)*(x-0.2)*(x-1.0)\n\nx = np.linspace(-0.5, 0.5, 101)\ny = f(x)\nplt.plot(x, y)\nplt.grid()\nplt.show()\n```\n\n\n```python\ndef horner(a, x):\n n = len(a)\n p = a[-1]\n for k in range(n-2, -1, -1):\n p = a[k] + p * x\n return p\n\na = np.array([5.0, -1.0, 3.0], dtype=float)\nx = np.array([-2, -1, 0, 1, 2], dtype=float)\nprint a\nprint horner(a, 1.0)\nprint horner(a, 2.0)\nprint horner(a, x)\n```\n\n [ 5. -1. 3.]\n 7.0\n 15.0\n [ 19. 9. 5. 7. 15.]\n\n\n\n```python\ndef f(x):\n return 0.2+25*x-200*x**2+675*x**3-900*x**4+400.0*x**5\n\nx = np.linspace(0, 0.8, 201)\ny = f(x)\nplt.plot(x, y)\nplt.grid()\nxx = np.linspace(0, 0.8, 5)\nyy = f(xx)\nplt.plot(xx, yy, 'b')\nplt.fill(xx, yy, 'c')\nplt.stem(xx, yy, 'b')\nplt.show()\n```\n\n\n```python\ndef trap1(x, y):\n assert (len(x) == len(y)), 'x and y must have same length'\n m = len(x)\n h = x[1] - x[0]\n return h * (y[0] + 2*sum(y[1:-1]) + y[-1]) / 2.0\n\nfor n in [10, 50, 100]:\n x = np.linspace(0, 1, n+1)\n y = f(x)\n s = trap1(x, y)\n print \"%5d %20.16f %20.16f\" % (n, s, (s-d)/s*100)\n\ndef simp1(x, y):\n assert (len(x) == len(y)), 'x and y must have same length'\n m = len(x)\n h = x[1] - x[0]\n return h / 3 * (y[0] + 4*sum(y[1:-1:2])+2*sum(y[2:-2:2])+y[-1])\n\na = 0.0; b = 1.0; n = 10\nfor n in [10, 50, 100]:\n x = np.linspace(a, b, n+1)\n y = f(x)\n s = simp1(x, y)\n print \"%5d %20.16f %20.16f\" % (n, s, (s-d)/s*100)\n\ndef f(x):\n return np.exp(-x**2)\n\nx = np.linspace(0, 1, 11)\ny = f(x)\nplt.plot(x, y)\nplt.grid()\nplt.show()\nprint trap1(x, y)\nprint simp1(x, y)\n```\n\n\n```python\ndef gauss_legendre(f, a, b, n=2, debug=False):\n if n == 1:\n t = np.array([0.0])\n A = np.array([2.0])\n elif n == 2:\n t1 = np.sqrt(1.0/3.0)\n t = np.array([-t1, t1])\n A = np.array([1.0, 1.0])\n elif n == 3:\n t1 = np.sqrt(3.0/5.0)\n A1 = 5.0 / 9.0\n A2 = 8.0 / 9.0\n t = np.array([-t1, 0.0, t1])\n A = np.array([A1, A2, A1])\n elif n == 4:\n t1 = np.sqrt(3.0/7 - 2.0/7*np.sqrt(6.0/5))\n t2 = np.sqrt(3.0/7 + 2.0/7*np.sqrt(6.0/5))\n A1 = (18.0 + np.sqrt(30.0)) / 36.0\n A2 = (18.0 - np.sqrt(30.0)) / 36.0\n t = np.array([-t2, -t1, t1, t2])\n A = np.array([A2, A1, A1, A2])\n else:\n t1 = (np.sqrt(5.0 - 2.0 * np.sqrt(10.0/7))) / 3.0\n t2 = (np.sqrt(5.0 + 2.0 * np.sqrt(10.0/7))) / 3.0\n A1 = (322.0 + 13 * np.sqrt(70.0)) / 900.0\n A2 = (322.0 - 13 * np.sqrt(70.0)) / 900.0\n A3 = 128.0 / 225.0\n t = np.array([-t2, -t1, 0.0, t1, t2])\n A = np.array([A2, A1, A3, A1, A2])\n\n c1 = (b - a) / 2.0\n c2 = (b + a) / 2.0\n x = c1 * t + c2\n y = f(x)\n\n if debug:\n for tt, xx, yy, AA in zip(t, x, y, A):\n print \"%12.6f %12.6f %12.6f %12.6f %12.6f\" % (tt, xx, yy, AA, AA*yy)\n\n return c1 * sum(y*A)\n\nfrom scipy.special import erf\n\nprint 'Correct answer =', np.sqrt(np.pi) * erf(1.0) / 2.0\n\nfor n in [1, 2, 3, 4, 5]:\n I = gauss_legendre(f, 0, 1, n)\n print 'n =', n, 'I =', I\n```\n\n Correct answer = 0.746824132812\n n = 1 I = 0.778800783071\n n = 2 I = 0.746594688283\n n = 3 I = 0.746814584191\n n = 4 I = 0.746824468131\n n = 5 I = 0.746824126766\n\n\n\n```python\ndef trap4(f, a, b, Iold, k):\n '''Recursive Trapezoidal Rule'''\n n = int(2**(k-2))\n h = float(b - a) / n\n x = a + h / 2.0\n s = 0.0\n for i in range(n):\n s += f(x)\n x += h\n Inew = (Iold + h*s) / 2.0\n return Inew\n\nIold = float(b - a) * (f(a) + f(b)) / 2.0\nfor k in range(2, 11):\n Inew = trap4(f, 0.0, 1.0, Iold, k)\n print \"%5d %21.16f\" % (k, Inew)\n Iold = Inew\n```\n\n 2 0.7313702518285630\n 3 0.7429840978003812\n 4 0.7458656148456952\n 5 0.7465845967882216\n 6 0.7467642546522943\n 7 0.7468091636378279\n 8 0.7468203905416179\n 9 0.7468231972461524\n 10 0.7468238989209475\n\n\n\n```python\ndef f(x):\n return (np.sin(x) / x)**2\n\nprint 'Exact I =', 1.41815\nfor n in [2, 3, 4, 5]:\n print 'n =', n, 'I =', gauss_legendre(f, 0, np.pi, n)\n```\n\n Exact I = 1.41815\n n = 2 I = 1.45031180528\n n = 3 I = 1.41618742467\n n = 4 I = 1.4182150179\n n = 5 I = 1.4181502678\n\n\n\n```python\ndef f(x):\n return np.log(x) / (x**2 - 2.0*x + 2.0)\n\nfor n in [2, 3, 4, 5]:\n print 'n =', n, 'I =', gauss_legendre(f, 1, np.pi, n)\n```\n\n n = 2 I = 0.606725022862\n n = 3 I = 0.581686953277\n n = 4 I = 0.584768036213\n n = 5 I = 0.58500930387\n\n\n\n```python\ndef f(x):\n return np.sin(x) * np.log(x)\n\nfor n in [2, 3, 4, 5]:\n print 'n =', n, 'I =', gauss_legendre(f, 0, np.pi, n)\n```\n\n n = 2 I = 0.481728993916\n n = 3 I = 0.626557170805\n n = 4 I = 0.634859692783\n n = 5 I = 0.638388665011\n\n", "meta": {"hexsha": "689adc97eedfb33062d1b5a9647dcc5792d9c248", "size": 132665, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Engg_Comp/07_Numerical_integration.ipynb", "max_stars_repo_name": "satish-annigeri/Notebooks", "max_stars_repo_head_hexsha": "92a7dc1d4cf4aebf73bba159d735a2e912fc88bb", "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": "Engg_Comp/07_Numerical_integration.ipynb", "max_issues_repo_name": "satish-annigeri/Notebooks", "max_issues_repo_head_hexsha": "92a7dc1d4cf4aebf73bba159d735a2e912fc88bb", "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": "Engg_Comp/07_Numerical_integration.ipynb", "max_forks_repo_name": "satish-annigeri/Notebooks", "max_forks_repo_head_hexsha": "92a7dc1d4cf4aebf73bba159d735a2e912fc88bb", "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": 150.0735294118, "max_line_length": 23340, "alphanum_fraction": 0.8595635624, "converted": true, "num_tokens": 5817, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067211996142, "lm_q2_score": 0.9496693647316318, "lm_q1q2_score": 0.8950697591769308}} {"text": "---\nauthor: Nathan Carter (ncarter@bentley.edu)\n---\n\nThis answer assumes you have imported SymPy as follows.\n\n\n```python\nfrom sympy import * # load all math functions\ninit_printing( use_latex='mathjax' ) # use pretty math output\n```\n\nLet's choose an example formula whose antiderivative we will compute.\n\n\n```python\nvar( 'x' )\nformula = 3*sqrt(x)\nformula\n```\n\n\n\n\n$\\displaystyle 3 \\sqrt{x}$\n\n\n\nUse the `Integral` function to build a definite integral without evaluating it.\nThe second parameter is the variable with respect to which you're integrating.\n\n\n```python\nIntegral( formula, x )\n```\n\n\n\n\n$\\displaystyle \\int 3 \\sqrt{x}\\, dx$\n\n\n\nUse the `integrate` function to perform the integration, showing the answer.\n\n\n```python\nintegrate( formula, x )\n```\n\n\n\n\n$\\displaystyle 2 x^{\\frac{3}{2}}$\n\n\n\n\n```python\nintegrate( formula, x ) + var('C') # same, but with a constant of integration\n```\n\n\n\n\n$\\displaystyle C + 2 x^{\\frac{3}{2}}$\n\n\n", "meta": {"hexsha": "abbb2df6fb646077cfefb833dee09a5ad3561d37", "size": 3263, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "database/tasks/How to write and evaluate indefinite integrals/Python, using SymPy.ipynb", "max_stars_repo_name": "nathancarter/how2data", "max_stars_repo_head_hexsha": "7d4f2838661f7ce98deb1b8081470cec5671b03a", "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": "database/tasks/How to write and evaluate indefinite integrals/Python, using SymPy.ipynb", "max_issues_repo_name": "nathancarter/how2data", "max_issues_repo_head_hexsha": "7d4f2838661f7ce98deb1b8081470cec5671b03a", "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": "database/tasks/How to write and evaluate indefinite integrals/Python, using SymPy.ipynb", "max_forks_repo_name": "nathancarter/how2data", "max_forks_repo_head_hexsha": "7d4f2838661f7ce98deb1b8081470cec5671b03a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-07-18T19:01:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T06:47:11.000Z", "avg_line_length": 20.6518987342, "max_line_length": 99, "alphanum_fraction": 0.4980079681, "converted": true, "num_tokens": 252, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9648551535992068, "lm_q2_score": 0.9273632961485915, "lm_q1q2_score": 0.894771255547716}} {"text": "---\nauthor: Nathan Carter (ncarter@bentley.edu)\n---\n\nThis answer assumes you have imported SymPy as follows.\n\n\n```python\nfrom sympy import * # load all math functions\ninit_printing( use_latex='mathjax' ) # use pretty math output\n```\n\nLet's re-use here the code from how to write an ordinary differential equation,\nto write $\\frac{dy}{dx}=y$.\n\n\n\n```python\nvar( 'x' )\ny = Function('y')(x)\ndydx = Derivative( y, x )\node = dydx - y\node\n```\n\n\n\n\n$\\displaystyle - y{\\left(x \\right)} + \\frac{d}{d x} y{\\left(x \\right)}$\n\n\n\nYou can solve an ODE by using the `dsolve` command.\n\n\n```python\nsolution = dsolve( ode )\nsolution\n```\n\n\n\n\n$\\displaystyle y{\\left(x \\right)} = C_{1} e^{x}$\n\n\n\nIf there are initial conditions that need to be substituted in for $x$ and $y$,\nit is crucial to substitute for $y$ first and then $x$. Let's assume we have the\ninitial condition $(3,5)$. We might proceed as follows.\n\n\n```python\nwith_inits = solution.subs( y, 5 ).subs( x, 3 )\nwith_inits\n```\n\n\n\n\n$\\displaystyle 5 = C_{1} e^{3}$\n\n\n\n\n```python\nsolve( with_inits )\n```\n\n\n\n\n$\\displaystyle \\left[ \\frac{5}{e^{3}}\\right]$\n\n\n\nTo substitute $C_1=\\frac{5}{e^3}$ into the solution, note that $C_1$ is written as `var('C1')`.\n\n\n```python\nsolution.subs( var('C1'), 5/E**3 )\n```\n\n\n\n\n$\\displaystyle y{\\left(x \\right)} = \\frac{5 e^{x}}{e^{3}}$\n\n\n", "meta": {"hexsha": "02bfcd6a9d0d6a72068afd06cccc660586859658", "size": 4178, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "database/tasks/How to solve an ordinary differential equation/Python, using SymPy.ipynb", "max_stars_repo_name": "nathancarter/how2data", "max_stars_repo_head_hexsha": "7d4f2838661f7ce98deb1b8081470cec5671b03a", "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": "database/tasks/How to solve an ordinary differential equation/Python, using SymPy.ipynb", "max_issues_repo_name": "nathancarter/how2data", "max_issues_repo_head_hexsha": "7d4f2838661f7ce98deb1b8081470cec5671b03a", "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": "database/tasks/How to solve an ordinary differential equation/Python, using SymPy.ipynb", "max_forks_repo_name": "nathancarter/how2data", "max_forks_repo_head_hexsha": "7d4f2838661f7ce98deb1b8081470cec5671b03a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-07-18T19:01:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T06:47:11.000Z", "avg_line_length": 21.5360824742, "max_line_length": 102, "alphanum_fraction": 0.4784585926, "converted": true, "num_tokens": 421, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9688561730622296, "lm_q2_score": 0.9230391669503405, "lm_q1q2_score": 0.8942921948780553}} {"text": "# Problem set 1\n\n##Strassen Algorithm\n\nLet $C = AB$, where $A$ and $B$ are squared matrices of the same size.\nDirect computation of $C$ requires $\\mathcal{O}(n^3)$ arithmetic operations.\nFortunately, this complexity can be reduced even for arbitrary matrices $A$ and $B$.\nThe following approach which has $\\mathcal{O}(n^{\\log_2 7})$ is called Strassen algorithm.\nIts idea is based on the fact that elements of $2\\times 2$ matrix\n$$\n\\begin{bmatrix} c_{11} & c_{12} \\\\ c_{21} & c_{22} \\end{bmatrix} =\n\\begin{bmatrix} a_{11} & a_{12} \\\\ a_{21} & a_{22} \\end{bmatrix}\n\\begin{bmatrix} b_{11} & b_{12} \\\\ b_{21} & b_{22} \\end{bmatrix}\n$$\ncan be computed using only 7 multiplications:\n\\begin{equation}\\begin{split}\nc_{11} &= f_1 + f_4 - f_5 + f_7, \\\\\nc_{12} &= f_3 + f_5, \\\\\nc_{21} &= f_2 + f_4, \\\\\nc_{22} &= f_1 - f_2 + f_3 + f_6,\n\\end{split}\\end{equation}\nwhere\n\\begin{equation}\\begin{split}\nf_1 &= (a_{11} + a_{22}) (b_{11} + b_{22}),\\\\\nf_2 &= (a_{21} + a_{22}) b_{11},\\\\\nf_3 &= a_{11} (b_{12} - b_{22}),\\\\\nf_4 &= a_{22} (b_{21} - b_{11}),\\\\\nf_5 &= (a_{11} + a_{12}) b_{22},\\\\\nf_6 &= (a_{21} - a_{11}) (b_{11} + b_{12}),\\\\\nf_7 &= (a_{12} - a_{22}) (b_{21} + b_{22}).\n\\end{split}\\end{equation}\n\nFormulas above hold for the case when $a_{ij}, b_{ij}, c_{ij}$ ($i$ and $j=1,2$) are blocks.\nTherefore, spliting matrices $A$ and $B$ of abitrary sizes into 4 blocks and applying described procedure recursively for blocks one will get $\\mathcal{O}(n^{\\log_2 7})$ complexity.\n\n**Tasks**\n\n- (4 pts) Prove that Strassen alogorithm has $\\mathcal{O}(n^{\\log_2 7})$ complexity\n- (4 pts) Implement Strassen algorithm in Python. **Note**: for simplicity consider that $n$ is a power of 2 \n- (3 pts) Compare the result with direct matrix-by-matrix multiplication and $\\verb|numpy.dot|$ procedure by ploting timings as a function of $n$. **Note**: use logarithmic scale\n\n\n```\n\n```\n\n##Fast Fourier Transform\n\nLet $y = Ax$ (matvec operation), where $A \\in \\mathbb{C}^{m\\times n}$ and $x \\in \\mathbb{C}^{n\\times 1}$. \nDirect computation of $y$ requires $\\mathcal{O}(n^2)$. \nSince $A$ contains $n^2$ elements, this complexity can not be reduced for an arbitrary matrix $A$.\nThere are certain classes of matrices for which matvec requires less operations.\nFor instance, sparse, Toeplitz, lowrank, etc.\nAnother important example of structured matrix which arises in a huge amount of applications (signal and image processing, fast PDE solvers) is Fourier matrix\n$$\nF_n = \\{ \\omega^{kl} \\}_{k,l=0}^{n-1}, \\quad \\text{where} \\quad \\omega = e^{-\\frac{2\\pi i}{n}}.\n$$\nMatvec operation with Fourier matrix is called discrete Fourier transform (DFT) and has $\\mathcal{O}(n \\log n)$ complexity.\nThe simplest way to get this complexity is to spilt odd and even rows in Fourier matrix:\n\\begin{equation}\nP_n F_n = \\begin{bmatrix} F_{n/2} & F_{n/2} \\\\ F_{n/2} W_{n/2} & -F_{n/2} W_{n/2} \\end{bmatrix}, \\quad (1)\n\\end{equation}\nwhere $P_n$ is a permutaion matrix which permutes odd and even rows, and $W_{n/2}=\\text{diag}(1,\\omega,\\omega^2,\\dots,\\omega^{n/2-1})$.\nThus, multiplication by $F_n$ is reduced to several multiplications by $F_{n/2}$ and linear operations such as multiplication by the diagonal matrix $W_{n/2}$.\nContinuing this procedure recursively for $F_{n/2}$ we will get $\\mathcal{O}(n \\log n)$ operations.\n\n**Tasks**\n\n- (4 pts) Prove expression (1)\n- (4 pts) Implement the described fft algorithm in Python. **Note**: for simplicity consider that $n$ is a power of 2 \n- (3 pts) Compare the result with $\\verb|numpy.dot|$ and $\\verb|numpy.fft.fft|$ procedures by ploting timings as a function of $n$. **Note**: use logarithmic scale\n\n\n```\n\n```\n", "meta": {"hexsha": "c905fe9e642461c9cfd2d5932a61ca7dad82b058", "size": 5184, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "problems/Pset1.ipynb", "max_stars_repo_name": "oseledets/NLA", "max_stars_repo_head_hexsha": "d16d47bc8e20df478d98b724a591d33d734ec74b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2015-01-20T13:24:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-03T05:54:09.000Z", "max_issues_repo_path": "problems/Pset1.ipynb", "max_issues_repo_name": "oseledets/NLA", "max_issues_repo_head_hexsha": "d16d47bc8e20df478d98b724a591d33d734ec74b", "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": "problems/Pset1.ipynb", "max_forks_repo_name": "oseledets/NLA", "max_forks_repo_head_hexsha": "d16d47bc8e20df478d98b724a591d33d734ec74b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2015-09-10T09:14:10.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-09T04:36:07.000Z", "avg_line_length": 45.0782608696, "max_line_length": 194, "alphanum_fraction": 0.5530478395, "converted": true, "num_tokens": 1240, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9643214532237353, "lm_q2_score": 0.9273632931373373, "lm_q1q2_score": 0.894276318504546}} {"text": "---\nauthor: Nathan Carter (ncarter@bentley.edu)\n---\n\nThis answer assumes you have imported SymPy as follows.\n\n\n```python\nfrom sympy import * # load all math functions\ninit_printing( use_latex='mathjax' ) # use pretty math output\n```\n\nLet's say we want to write the equation $x^2+y^2=2$.\nWe must first define $x$ and $y$ as mathematical variables,\nthen use SymPy's `Eq` function to build an equation.\nThis helps SymPy distinguish a mathematical equation\nfrom a Python assignment statement.\n\n\n```python\nvar( 'x y' )\nEq( x**2 + y**2, 2 ) # Two parameters: left and right sides of equation\n```\n\n\n\n\n$\\displaystyle x^{2} + y^{2} = 2$\n\n\n\nYou can make a system of equations just by placing several equations in a Python list.\n\n\n```python\nsystem = [\n Eq( x + 2*y, 1 ),\n Eq( x - 9*y, 5 )\n]\nsystem\n```\n\n\n\n\n$\\displaystyle \\left[ x + 2 y = 1, \\ x - 9 y = 5\\right]$\n\n\n", "meta": {"hexsha": "fc7acd4c5d5c528b22927dff0293227d936585ca", "size": 2572, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "database/tasks/How to write symbolic equations/Python, using SymPy.ipynb", "max_stars_repo_name": "nathancarter/how2data", "max_stars_repo_head_hexsha": "7d4f2838661f7ce98deb1b8081470cec5671b03a", "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": "database/tasks/How to write symbolic equations/Python, using SymPy.ipynb", "max_issues_repo_name": "nathancarter/how2data", "max_issues_repo_head_hexsha": "7d4f2838661f7ce98deb1b8081470cec5671b03a", "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": "database/tasks/How to write symbolic equations/Python, using SymPy.ipynb", "max_forks_repo_name": "nathancarter/how2data", "max_forks_repo_head_hexsha": "7d4f2838661f7ce98deb1b8081470cec5671b03a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-07-18T19:01:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T06:47:11.000Z", "avg_line_length": 22.1724137931, "max_line_length": 99, "alphanum_fraction": 0.5050544323, "converted": true, "num_tokens": 261, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122672782974, "lm_q2_score": 0.93343081565912, "lm_q1q2_score": 0.8941448289754581}} {"text": "# Exponentials, Radicals, and Logs\nUp to this point, all of our equations have included standard arithmetic operations, such as division, multiplication, addition, and subtraction. Many real-world calculations involve exponential values in which numbers are raised by a specific power.\n\n## Exponentials\nA simple case of of using an exponential is squaring a number; in other words, multipying a number by itself. For example, 2 squared is 2 times 2, which is 4. This is written like this:\n\n\\begin{equation}2^{2} = 2 \\cdot 2 = 4\\end{equation}\n\nSimilarly, 2 cubed is 2 times 2 times 2 (which is of course 8):\n\n\\begin{equation}2^{3} = 2 \\cdot 2 \\cdot 2 = 8\\end{equation}\n\nIn R, you use the ****** operator, like this example in which **x** is assigned the value of 5 raised to the power of 3 (in other words, 5 x 5 x 5, or 5-cubed):\n\n\n```R\nx = 5**3\nprint(x)\n```\n\n [1] 125\n\n\nMultiplying a number by itself twice or three times to calculate the square or cube of a number is a common operation, but you can raise a number by any exponential power. For example, the following notation shows 4 to the power of 7 (or 4 x 4 x 4 x 4 x 4 x 4 x 4), which has the value:\n\n\\begin{equation}4^{7} = 16384 \\end{equation}\n\nIn mathematical terminology, **4** is the *base*, and **7** is the *power* or *exponent* in this expression.\n\n## Radicals (Roots)\nWhile it's common to need to calculate the solution for a given base and exponential, sometimes you'll need to calculate one or other of the elements themselves. For example, consider the following expression:\n\n\\begin{equation}?^{2} = 9 \\end{equation}\n\nThis expression is asking, given a number (9) and an exponent (2), what's the base? In other words, which number multipled by itself results in 9? This type of operation is referred to as calculating the *root*, and in this particular case it's the *square root* (the base for a specified number given the exponential **2**). In this case, the answer is 3, because 3 x 3 = 9. We show this with a **√** symbol, like this:\n\n\\begin{equation}\\sqrt{9} = 3 \\end{equation}\n\nOther common roots include the *cube root* (the base for a specified number given the exponential **3**). For example, the cube root of 64 is 4 (because 4 x 4 x 4 = 64). To show that this is the cube root, we include the exponent **3** in the **√** symbol, like this:\n\n\\begin{equation}\\sqrt[3]{64} = 4 \\end{equation}\n\nWe can calculate any root of any non-negative number, indicating the exponent in the **√** symbol.\n\nThe R **sqrt** function calculates the square root of a number. To calculate other roots, you need to reverse the exponential calculation by raising the given number to the power of 1 divided by the given exponent:\n\n\n```R\n## calculate and display the square root of 25\nx = sqrt(25)\nprint(x)\n\n## calculate and display the cube root of 64\ncr = 64**(1/3)\nprint(cr)\n```\n\n [1] 5\n [1] 4\n\n\nThe code used in R to calculate roots other than the square root reveals something about the relationship between roots and exponentials. The exponential root of a number is the same as that number raised to the power of 1 divided by the exponential. For example, consider the following statement:\n\n\\begin{equation} 8^{\\frac{1}{3}} = \\sqrt[3]{8} = 2 \\end{equation}\n\nNote that a number to the power of 1/3 is the same as the cube root of that number.\n\nBased on the same arithmetic, a number to the power of 1/2 is the same as the square root of the number:\n\n\\begin{equation} 9^{\\frac{1}{2}} = \\sqrt{9} = 3 \\end{equation}\n\nYou can see this for yourself with the following R code:\n\n\n```R\nprint(9**0.5)\nprint(sqrt(9))\n```\n\n [1] 3\n [1] 3\n\n\n## Logarithms\nAnother consideration for exponential values is the requirement occassionally to determine the exponent for a given number and base. In other words, how many times do I need to multiply a base number by itself to get the given result. This kind of calculation is known as the *logarithm*.\n\nFor example, consider the following expression:\n\n\\begin{equation}4^{?} = 16 \\end{equation}\n\nIn other words, to what power must you raise 4 to produce the result 16?\n\nThe answer to this is 2, because 4 x 4 (or 4 to the power of 2) = 16. The notation looks like this:\n\n\\begin{equation}log_{4}(16) = 2 \\end{equation}\n\nIn R, you can calculate the logarithm of a number of a specified base using the **logb** function, indicating the number and the base:\n\n\n```R\nx = logb(16, 4)\nprint(x)\n```\n\n [1] 2\n\n\nThe final thing you need to know about exponentials and logarithms is that there are some special logarithms:\n\nThe *common* logarithm of a number is its exponential for the base **10**. You'll occassionally see this written using the usual *log* notation with the base omitted:\n\n\\begin{equation}log(1000) = 3 \\end{equation}\n\nAnother special logarithm is something called the *natural log*, which is a exponential of a number for base ***e***, where ***e*** is a constant with the approximate value 2.718. This number occurs naturally in a lot of scenarios, and you'll see it often as you work with data in many analytical contexts. For the time being, just be aware that the natural log is sometimes written as ***ln***:\n\n\\begin{equation}log_{e}(64) = ln(64) = 4.1589 \\end{equation}\n\nThe **log** function in R returns the natural log (base ***e***) when no base is specified. To return the base 10 or common log in R, use the **log10** function:\n\n\n```R\n## Natural log of 29\nlog(29)\n\n## Base 10 log of 100\nlog10(100)\n```\n\n\n3.36729582998647\n\n\n\n2\n\n\n## Solving Equations with Exponentials\nOK, so now that you have a basic understanding of exponentials, roots, and logarithms; let's take a look at some equations that involve exponential calculations.\n\nLet's start with what might at first glance look like a complicated example, but don't worry - we'll solve it step-by-step and learn a few tricks along the way:\n\n\\begin{equation}2y = 2x^{4} ( \\frac{x^{2} + 2x^{2}}{x^{3}} ) \\end{equation}\n\nFirst, let's deal with the fraction on the right side. The numerator of this fraction is x2 + 2x2 - so we're adding two exponential terms. When the terms you're adding (or subtracting) have the same exponential, you can simply add (or subtract) the coefficients. In this case, x2 is the same as 1x2, which when added to 2x2 gives us the result 3x2, so our equation now looks like this: \n\n\\begin{equation}2y = 2x^{4} ( \\frac{3x^{2}}{x^{3}} ) \\end{equation}\n\nNow that we've condolidated the numerator, let's simplify the entire fraction by dividing the numerator by the denominator. When you divide exponential terms with the same variable, you simply divide the coefficients as you usually would and subtract the exponential of the denominator from the exponential of the numerator. In this case, we're dividing 3x2 by 1x3: The coefficient 3 divided by 1 is 3, and the exponential 2 minus 3 is -1, so the result is 3x-1, making our equation:\n\n\\begin{equation}2y = 2x^{4} ( 3x^{-1} ) \\end{equation}\n\nSo now we've got rid of the fraction on the right side, let's deal with the remaining multiplication. We need to multiply 3x-1 by 2x4. Multiplication, is the opposite of division, so this time we'll multipy the coefficients and add the exponentials: 3 multiplied by 2 is 6, and -1 + 4 is 3, so the result is 6x3:\n\n\\begin{equation}2y = 6x^{3} \\end{equation}\n\nWe're in the home stretch now, we just need to isolate y on the left side, and we can do that by dividing both sides by 2. Note that we're not dividing by an exponential, we simply need to divide the whole 6x3 term by two; and half of 6 times x3 is just 3 times x3:\n\n\\begin{equation}y = 3x^{3} \\end{equation}\n\nNow we have a solution that defines y in terms of x. We can use R to plot the line created by this equation for a set of arbitrary *x* and *y* values:\n\n\n```R\n# Create a dataframe with an x column containing values from -10 to 10\ndf = data.frame(x = seq(-10, 10))\n\n# Add a y column by applying the slope-intercept equation to x\ndf$y = 3*df$x**3\n\n#Display the dataframe\nprint(df)\n\n# Plot the line\nlibrary(ggplot2)\nlibrary(repr)\noptions(repr.plot.width=4, repr.plot.height=4)\nggplot(df, aes(x,y)) + \n geom_line(color = 'magenta', size = 1) +\n geom_hline(yintercept=0) + geom_vline(xintercept=0)\n```\n\nNote that the line is curved. This is symptomatic of an exponential equation: as values on one axis increase or decrease, the values on the other axis scale *exponentially* rather than *linearly*.\n\nLet's look at an example in which x is the exponential, not the base:\n\n\\begin{equation}y = 2^{x} \\end{equation}\n\nWe can still plot this as a line:\n\n\n```R\n# Create a dataframe with an x column containing values from -10 to 10\ndf = data.frame(x = seq(-10, 10))\n\n# Add a y column by applying the slope-intercept equation to x\ndf$y = 2.0**df$x\n\n## Plot the line\nggplot(df, aes(x,y)) + \n geom_line(color = 'magenta', size = 1) +\n geom_hline(yintercept=0) + geom_vline(xintercept=0)\n```\n\nNote that when the exponential is a negative number, R reports the result as 0. Actually, it's a very small fractional number, but because the base is positive the exponential number will always positive. Also, note the rate at which y increases as x increases - exponential growth can be be pretty dramatic.\n\nSo what's the practical application of this?\n\nWell, let's suppose you deposit $100 in a bank account that earns 5% interest per year. What would the balance of the account be in twenty years, assuming you don't deposit or withdraw any additional funds?\n\nTo work this out, you could calculate the balance for each year:\n\nAfter the first year, the balance will be the initial deposit ($100) plus 5% of that amount:\n\n\\begin{equation}y1 = 100 + (100 \\cdot 0.05) \\end{equation}\n\nAnother way of saying this is:\n\n\\begin{equation}y1 = 100 \\cdot 1.05 \\end{equation}\n\nAt the end of year two, the balance will be the year one balance plus 5%:\n\n\\begin{equation}y2 = 100 \\cdot 1.05 \\cdot 1.05 \\end{equation}\n\nNote that the interest for year two, is the interest for year one multiplied by itself - in other words, squared. So another way of saying this is:\n\n\\begin{equation}y2 = 100 \\cdot 1.05^{2} \\end{equation}\n\nIt turns out, if we just use the year as the exponent, we can easily calculate the growth after twenty years like this:\n\n\\begin{equation}y20 = 100 \\cdot 1.05^{20} \\end{equation}\n\nLet's apply this logic in R to see how the account balance would grow over twenty years:\n\n\n```R\n# Create a dataframe with an x column containing values from -10 to 10\ndf = data.frame(Year = seq(1, 20))\n\n# Calculate the balance for each year based on the exponential growth from interest\ndf$Balance = 100 * (1.05**df$Year)\n\n## Plot the line\nggplot(df, aes(Year, Balance)) + \n geom_line(color = 'green', size = 1) +\n geom_hline(yintercept=0) + geom_vline(xintercept=0)\n```\n", "meta": {"hexsha": "fc98e68d8f83b6d97c43647ef252ef0bd0a9facb", "size": 30710, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "R/Module01/01-04-Exponentials Radicals and Logarithms.ipynb", "max_stars_repo_name": "joelgenter/Essential-Math", "max_stars_repo_head_hexsha": "2e76546a82fb0ad2b8698c7dc0f48f0aad0762bb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 33, "max_stars_repo_stars_event_min_datetime": "2018-01-11T20:44:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T16:10:41.000Z", "max_issues_repo_path": "R/Module01/01-04-Exponentials Radicals and Logarithms.ipynb", "max_issues_repo_name": "joelgenter/Essential-Math", "max_issues_repo_head_hexsha": "2e76546a82fb0ad2b8698c7dc0f48f0aad0762bb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2018-11-19T23:54:27.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-20T00:15:39.000Z", "max_forks_repo_path": "R/Module01/01-04-Exponentials Radicals and Logarithms.ipynb", "max_forks_repo_name": "joelgenter/Essential-Math", "max_forks_repo_head_hexsha": "2e76546a82fb0ad2b8698c7dc0f48f0aad0762bb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 35, "max_forks_repo_forks_event_min_datetime": "2018-03-08T15:42:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-03T06:11:43.000Z", "avg_line_length": 65.9012875536, "max_line_length": 4988, "alphanum_fraction": 0.7513187887, "converted": true, "num_tokens": 3120, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9609517078329177, "lm_q2_score": 0.9304582526016021, "lm_q1q2_score": 0.8941254469047419}} {"text": "The Cholesky Decomposition exists when a matrix is hermitian and positive-definite. It expresses the matrix $\\mathbf{A}$ as:\n\n\\begin{equation}\n\\mathbf{A} = \\mathbf{L}\\mathbf{L^\\dagger}\n\\end{equation}\n\nWhere $\\mathbf{L}$ is a lower-triangular matrix with positive, real diagonal entries. When $\\mathbf{A}$ is real, then so is $\\mathbf{L}$. The Cholesky decomposition enables fast solution of a linear system, but it can also be used to create correlated random variables in Monte Carlo simulations. \n\n### Creating Correlated Random Variables\nLet $\\mathbf{u}_t$ be a vector of uncorrelated samples with unit standard deviation. If the covariance matrix of the system to be simulated is $\\mathbf{\\Sigma}$ with Cholesky decomposition $\\mathbf{\\Sigma} = \\mathbf{LL}^\\dagger$, then the vector $\\mathbf{v}_t = \\mathbf{Lu}_t$ has the desired covariance.\n\n\n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nnp.random.seed = 42\n\nT = 10000\nn = 5\n\nM = np.random.randn(*(n,n))\nCovar = np.matmul(M.T,M) # random symmetric matrix\n\nL = np.linalg.cholesky(Covar)\n\nprint('covar:\\n',Covar)\nprint('L:\\n',L)\nprint('L*L^T:\\n',np.matmul(L,L.T))\nprint('covar - L*L^T = 0',np.allclose(np.matmul(L,L.T)-Covar,0))\n```\n\n covar:\n [[ 5.83329982 -2.7988554 -1.221951 0.1995683 2.31184273]\n [-2.7988554 12.06818258 1.35675522 -0.99876349 -4.46688883]\n [-1.221951 1.35675522 2.52907446 -2.10538897 1.58002341]\n [ 0.1995683 -0.99876349 -2.10538897 3.50034403 -2.21280123]\n [ 2.31184273 -4.46688883 1.58002341 -2.21280123 5.34210571]]\n L:\n [[ 2.41522252 0. 0. 0. 0. ]\n [-1.15883956 3.27494633 0. 0. 0. ]\n [-0.50593723 0.23525733 1.4892132 0. 0. ]\n [ 0.08262936 -0.27573255 -1.34212858 1.27129023 0. ]\n [ 0.95719658 -1.02525392 1.54813515 -0.39077877 0.90846262]]\n L*L^T:\n [[ 5.83329982 -2.7988554 -1.221951 0.1995683 2.31184273]\n [-2.7988554 12.06818258 1.35675522 -0.99876349 -4.46688883]\n [-1.221951 1.35675522 2.52907446 -2.10538897 1.58002341]\n [ 0.1995683 -0.99876349 -2.10538897 3.50034403 -2.21280123]\n [ 2.31184273 -4.46688883 1.58002341 -2.21280123 5.34210571]]\n covar - L*L^T = 0 True\n\n\n\n```python\nu = np.random.randn(*(n,T))\nv = np.matmul(L,u)\n```\n\n\n```python\nfig, ax = plt.subplots(2,1,figsize=(12,8)) \nfor i in range(n):\n ax[0].plot(np.cumsum(u[i],axis=0))\n ax[1].plot(np.cumsum(v[i],axis=0))\n \nax[0].set_title('Uncorrelated Gaussian Random Walk (mu=0,std=1)')\nax[1].set_title('Correlated')\n\nplt.savefig('img/cholesky1.png')\n```\n\n\n```python\nfig, ax = plt.subplots(2,2,figsize=(8,8))\n\n\nax[0][0].imshow(Covar,vmin=np.min(Covar),vmax=np.max(Covar))\nax[0][0].set_title('Covariance: Target')\nax[0][1].imshow(np.cov(u))\nax[0][1].set_title('Covariance: Uncorrelated u')\nax[1][0].imshow(np.cov(v),vmin=np.min(Covar),vmax=np.max(Covar))\nax[1][0].set_title('Covariance: Cholesky Constructed v=Lu')\nax[1][1].imshow(np.log10(np.abs(Covar-np.cov(v))),vmin=np.min(Covar),vmax=np.max(Covar))\nax[1][1].set_title('Error (log10)')\n\nplt.savefig('img/cholesky2.png')\n```\n", "meta": {"hexsha": "52f93b118c6a446755056723961a23e49f09bf70", "size": 182772, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Simulation - Cholesky Decomposition, Correlated Random Variables.ipynb", "max_stars_repo_name": "jpbm/probabilism", "max_stars_repo_head_hexsha": "a2f5c1595aed616236b2b889195604f365175899", "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": "Simulation - Cholesky Decomposition, Correlated Random Variables.ipynb", "max_issues_repo_name": "jpbm/probabilism", "max_issues_repo_head_hexsha": "a2f5c1595aed616236b2b889195604f365175899", "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": "Simulation - Cholesky Decomposition, Correlated Random Variables.ipynb", "max_forks_repo_name": "jpbm/probabilism", "max_forks_repo_head_hexsha": "a2f5c1595aed616236b2b889195604f365175899", "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": 1062.6279069767, "max_line_length": 161932, "alphanum_fraction": 0.9532149345, "converted": true, "num_tokens": 1218, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545274901876, "lm_q2_score": 0.9425067240257282, "lm_q1q2_score": 0.893642017574939}} {"text": "# 2D heat conduction\n\nThe equation of heat conduction in 2D is:\n\n$$\n\\begin{equation}\n\\rho c_p \\frac{\\partial T}{\\partial t} = \\frac{\\partial}{\\partial x} \\left( \\kappa_x \\frac{\\partial T}{\\partial x} \\right) + \\frac{\\partial}{\\partial y} \\left(\\kappa_y \\frac{\\partial T}{\\partial y} \\right)\n\\end{equation}\n$$\n\nwhere $\\rho$ is the density, $c_p$ is the heat capacity and $\\kappa$ is the thermal conductivity.\n\nIf the thermal conductivity $\\kappa$ is constant, then we can take it outside of the spatial derivative and the equation simplifies to:\n\n$$\n\\begin{equation}\n\\frac{\\partial T}{\\partial t} = \\alpha \\left(\\frac{\\partial^2 T}{\\partial x^2} + \\frac{\\partial^2 T}{\\partial y^2} \\right)\n\\end{equation}\n$$\n\nwhere $\\alpha = \\frac{\\kappa}{\\rho c_p}$ is the thermal diffusivity. The thermal diffusivity describes the ability of a material to conduct heat vs. storing it.\n\n\n\nLet's write this out discretized using forward difference in time, and central difference in space, using an explicit scheme. You should be able write this out yourself, without looking—if you need to look, it means you still need to write more difference equations by your own hand!\n\n$$\n\\begin{equation}\n\\frac{T^{n+1}_{i,j} - T^n_{i,j}}{\\Delta t} = \\alpha \\left( \\frac{T^n_{i+1, j} - 2T^n_{i,j} + T^n_{i-1,j}}{\\Delta x^2} + \\frac{T^n_{i, j+1} - 2T^n_{i,j} + T^n_{i,j-1}}{\\Delta y^2}\\right)\n\\end{equation}\n$$\nsuppose we have \n$$\n\\begin{equation}\n{\\Delta x^2}={\\Delta y^2}\n\\end{equation}\n$$\nNow our discrtized equation will simpler \n\n\n\n$$\n\\begin{equation}\n\\frac{T^{n+1}_{i,j} - T^n_{i,j}}{\\Delta t} = \\alpha( \\frac{T^n_{i+1, j} - 4T^n_{i,j} + T^n_{i-1,j} + T^n_{i, j+1} + T^n_{i,j-1}} {\\Delta x^2})\n\\end{equation}\n$$\nRearranging the equation to solve for the value at the next time step, $T^{n+1}_{i,j}$, yields\n\n$$\n\\begin{equation}\nT^{n+1}_{i,j}= T^n_{i,j} + \\alpha \\left( \\frac{\\Delta t}{\\Delta x^2} (T^n_{i+1, j} - 2T^n_{i,j} + T^n_{i-1,j}) + \\\\\\frac{\\Delta t}{\\Delta y^2} (T^n_{i, j+1} - 2T^n_{i,j} + T^n_{i,j-1})\\right) = T^n_{i,j} + \\frac{\\Delta t}{\\Delta x^2}\\alpha (T^n_{i+1, j} - 4T^n_{i,j} + T^n_{i-1,j} + T^n_{i, j+1} + T^n_{i,j-1})\n\\end{equation}\n$$\n\n### Stability analysis\n\nBefore doing any coding, let's revisit stability constraints. We saw in the 1D explicit discretization of the diffusion equation was stable as long as $\\alpha \\frac{\\Delta t}{(\\Delta x)^2} \\leq \\frac{1}{2}$. In 2D, this constraint is even tighter, as we need to add them in both directions:\n\n$$\n\\begin{equation}\n\\alpha \\frac{\\Delta t}{(\\Delta x)^2} + \\alpha \\frac{\\Delta t}{(\\Delta y)^2} < \\frac{1}{2}.\n\\end{equation}\n$$\n\nSay that the mesh has the same spacing in $x$ and $y$, $\\Delta x = \\Delta y = \\delta$. In that case, the stability condition is:\n\n$$\n\\begin{equation}\n\\alpha \\frac{\\Delta t}{\\delta^2} < \\frac{1}{4}\n\\end{equation}\n$$\n\n### Problem statement\n\nWe understand how heat is conducted through water . we consider 2D water body of size $1{\\rm m}\\times 1{\\rm m}$, with a thermal diffusivity $\\alpha \\approx 0.146.10^{-6}{\\rm m}^2{/\\rm s}$. \nWe're going to set up a somewhat artificial problem, just to demonstrate an interesting numerical solution. water is in contact at left side with a heat source which has a constant temperature of $T=100°C $, and for the rest of the edges it is in contact with insulating material, Initially, the water temperature is at $(25{\\rm C})$. *How long does it take for the water tempreture to be fully warmed by the heat source ?*\n\n### Boundary Conditions\n\nWhenever we reach a point that interacts with the boundary, we apply the boundary condition,if the boundary has Dirichlet conditions, we simply impose the prescribed temperature $T=100°C $ at $y=0$ at the left side. If the boundary has Neumann conditions, we approximate them with a finite-difference scheme.\n\nRemember, Neumann boundary conditions prescribe the derivative in the normal direction. For example, in the problem described above, we have $\\frac{\\partial T}{\\partial y} = q_y$ in the top boundary and $\\frac{\\partial T}{\\partial x} = q_x$ in the right boundary, with $q_y = q_x = 0$ (insulation).\n\nThus, at every time step, we need to enforce\n\n$$\n\\begin{equation}\nT_{i,end} = q_y\\cdot\\Delta y + T_{i,end-1}\n\\end{equation}\n$$\n\nand\n\n$$\n\\begin{equation}\nT_{end,j} = q_x\\cdot\\Delta x + T_{end-1,j}\n\\end{equation}\n$$\n\n\n```python\nfrom mpl_toolkits import mplot3d\nimport numpy as np\nfrom matplotlib import animation\nimport matplotlib.pyplot as plt \nfrom IPython.display import HTML\n%matplotlib inline\n```\n\n\n```python\n# Set the font family and size to use for Matplotlib figures.\nplt.rcParams['font.family'] = 'serif'\nplt.rcParams['font.size'] = 16\n```\n\n\n```python\nLx = 1 # length of the plate in the x direction\nLy = 1 # height of the plate in the y direction\nnx = 41 # number of points in the x direction\nny = 41 # number of points in the y direction\ndx = Lx / (nx - 1) # grid spacing in the x direction\ndy = Ly / (ny - 1) # grid spacing in the y direction\nalpha = 0.146e-6 # thermal diffusivity of the water\n\n# Define the locations along a gridline.\nx = np.linspace(0.0, Lx, num=nx)\ny = np.linspace(0.0, Ly, num=ny)\n\n# Compute the initial temperature distribution.\nTb = 100.0 # temperature at the left boundaries\nT0 = 25.0 * np.ones((ny, nx))\n#apply Dirichlet boundary conditions\nT0[:, 0] = Tb #here T[j,i] because in python j represnts the rows which corresponds to y axis and i represnts the colums which corresponds to x axis\n\n```\n\n\n```python\nsigma = 0.24\ndt = (sigma * dx**2 )/ alpha # time-step size\nnt = 100\nc=(dt*alpha)/dx**2\n```\n\n\n```python\nT=T0.copy()\nfor i in range (nt):\n Tn=T.copy()\n T[1:-1, 1:-1] = (Tn[1:-1, 1:-1] +\n c * (Tn[1:-1, 2:] - 4.0 * Tn[1:-1, 1:-1] + Tn[1:-1, :-2] \n + Tn[2:, 1:-1] + Tn[:-2, 1:-1]))\n#apply Neumann boundary conditions \n T[-1,:]=T[-2,:] \n T[:, -1] = T[:, -2] \n T[0,:] = T[1,:] \n```\n\n\n```python\n# Plot the filled 2d contour of the temperature.\nplt.figure(figsize=(8.0, 5.0))\nplt.xlabel('x [m]')\nplt.ylabel('y [m]')\nlevels= np.linspace(25.0, 100.0, num=40)\ncontf = plt.contourf(x, y, T, levels=levels)\ncbar = plt.colorbar(contf)\ncbar.set_label('Temperature [C]')\n```\n\n\n```python\n# Plot the filled 3d contour of the temperature.\nplt.figure(figsize=(8.0, 5.0))\naxis=plt.gca(projection= \"3d\")\nplt.xlabel('x [m]')\nplt.ylabel('y [m]')\nlevels= np.linspace(25.0, 100.0, num=40)\ncontf = plt.contourf(x, y, T, levels=levels)\ncbar = plt.colorbar(contf)\ncbar.set_label('Temperature [C]')\n\n```\n\n\n```python\ndef ftcs(T0,nt, c):\n T=T0.copy() \n for i in range (nt):\n Tn=T.copy()\n T[1:-1, 1:-1] = (Tn[1:-1, 1:-1] +\n c * (Tn[1:-1, 2:] - 4.0 * Tn[1:-1, 1:-1] + Tn[1:-1, :-2] \n + Tn[2:, 1:-1] + Tn[:-2, 1:-1]))\n#apply Neumann boundary conditions \n T[-1,:]=T[-2,:] \n T[:, -1] = T[:, -2] \n T[0,:] = T[1,:] \n return T\n```\n\n\n```python\nnt = 1000\nc=(dt*alpha)/dx**2\nT1=ftcs(T0, nt,c)\n```\n\n\n```python\n# Plot the filled 2d contour of the temperature.\nfig=plt.figure(figsize=(8.0, 5.0))\nplt.xlabel('x [m]')\nplt.ylabel('y [m]')\nlevels= np.linspace(25.0, 100.0, num=40)\ncontf = plt.contourf(x, y, T1, levels=levels)\ncbar = plt.colorbar(contf)\ncbar.set_label('Temperature [C]')\n```\n\n\n```python\n#def animate(n):\n #fig.suptitle('Time step {:0>2}'.format(n))\n \n```\n\n\n```python\n#anim = animation.FuncAnimation(fig, animate,frames=nt , interval=100)\n```\n\n__3D heat conduction__\n\nNow we are going to expand our problem into 3D , adding a z dimension with the same height , thus we are going to have $1{\\rm m}\\times 1{\\rm m}\\times 1{\\rm m}$ water with the same initial conditions as before\nour new equation will be if \n$$\n\\begin{equation}\n{\\Delta x^2}={\\Delta y^2}={\\Delta z^2}\n\\end{equation}\n$$\n$$\n\\begin{equation}\n\\frac{T^{n+1}_{i,j,k} - T^n_{i,j,k}}{\\Delta t} = \\alpha( \\frac{T^n_{i+1, j,k} - 6T^n_{i,j,k} + T^n_{i-1,j,k} + T^n_{i, j+1,k} + T^n_{i,j-1,k}+ T^n_{i, j,k+1} +T^n_{i, j,k-1}}{\\Delta x^2})\n\\end{equation}\n$$\nRearranging the equation to solve for the value at the next time step, $T^{n+1}_{i,j}$, yields\n\n$$\n\\begin{equation}\nT^{n+1}_{i,j,k} = T^n_{i,j,k} + \\frac{\\Delta t}{\\Delta x^2}\\alpha (T^n_{i+1, j,k} - 6T^n_{i,j,k} + T^n_{i-1,j,k} + T^n_{i, j+1,k} + T^n_{i,j-1,k}+ T^n_{i, j,k+1} +T^n_{i, j,k-1})\n\\end{equation}\n$$\n\n__Stability analysis__\n\nNow let's examine the stability constraint of 3D dimensions\n\n$$\n\\begin{equation}\n\\alpha \\frac{\\Delta t}{(\\Delta x)^2} + \\alpha \\frac{\\Delta t}{(\\Delta y)^2} + \\alpha \\frac{\\Delta t}{(\\Delta z)^2} < \\frac{1}{2}.\n\\end{equation}\n$$\n\nSay that the mesh has the same spacing in $x$,$y$,$z$ $\\Delta x = \\Delta y = \\Delta z = \\delta $. In that case, the stability condition is:\n\n$$\n\\begin{equation}\n\\alpha \\frac{\\Delta t}{\\delta^2} < \\frac{1}{6}\n\\end{equation}\n$$\n\n\n```python\nLx = 1 # length of the plate in the x direction\nLy = 1 # height of the plate in the y direction\nLz = 1 # height of the plate in the z direction\nnx = 41 # number of points in the x direction\nny = 41 # number of points in the y direction\nnz= 41 # number of points in the z direction\ndx = Lx / (nx - 1) # grid spacing in the x direction\ndy = Ly / (ny - 1) # grid spacing in the y direction\ndz = Lz / (nz - 1) # grid spacing in the z direction\nalpha = 0.146e-6 # thermal diffusivity of the water\n\n# Define the locations along a gridline.\nx = np.linspace(0.0, Lx, num=nx)\ny = np.linspace(0.0, Ly, num=ny)\nz = np.linspace(0.0, Lz, num=nz)\n\n#initial conditions\nT0=25.0*np.ones((nx,ny,nz))\nTb=100.0\nT0[:,0,:]= Tb\n \n```\n\n\n```python\nsigma = 0.16\ndt = (sigma * dx**2 )/ alpha # time-step size\nnt = 500\nc=(dt*alpha)/dx**2\n```\n\n\n```python\n%%time\nT=T0.copy()\nfor i in range (nt):\n Tn=T.copy()\n T[1:-1, 1:-1,1:-1] = (Tn[1:-1, 1:-1,1:-1] + c * (Tn[1:-1, 2:,1:-1] - 6.0 * Tn[1:-1, 1:-1,1:-1] \n + Tn[1:-1, :-2,1:-1] + + Tn[2:, 1:-1,1:-1] + Tn[:-2, 1:-1,1:-1]+ Tn[1:-1,1:-1,2:] \n + Tn[ 1:-1,1:-1,:-2] ))\n \n \n #apply Neumann boundary conditions \n T[-1,:,:]=T[-2,:,:] #delta t/ delta y = 0 at y=ly \n T[:, -1,:] = T[:, -2,:] #delta t/ delta x = 0 at x=lx \n T[0,:,:] = T[1,:,:] #delta t/ delta y = 0 at y=0 \n T[:,:,-1] = T[:,:,-2] #delta t/ delta z = 0 at z=Lz \n T[:,:,0] = T[:,:,1] #delta t/ delta z = 0 at z=0 \n```\n\n Wall time: 1.1 s\n\n\n\n```python\nfrom mayavi import mlab\nmlab.init_notebook()\n```\n\n Notebook initialized with ipy backend.\n\n\n\n```python\nX,Y,Z=np.mgrid[0:1:41j,0:1:41j,0:1:41j]\n```\n\n\n```python\nmlab.clf()\ns=mlab.volume_slice(T,plane_orientation='z_axes')\nmlab.title('time step is {}' .format(nt))\nmlab.colorbar(object=None, title='Temperature',orientation='horizontal')\ns \n```\n\n\n Image(value=b'\\x89PNG\\r\\n\\x1a\\n\\x00\\x00\\x00\\rIHDR\\x00\\x00\\x01\\x90\\x00\\x00\\x01^\\x08\\x02\\x00\\x00\\x00$?\\xde_\\x00\\…\n\n\n\n```python\n\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "048e6016471c2a14e6500aa4632d8e044c0e3129", "size": 119294, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "heat_transfer_in_water.ipynb", "max_stars_repo_name": "Arbi-ben-aoun/Numerical-modeling-with-python", "max_stars_repo_head_hexsha": "7b0c02e7d3c94a668e719b7d32893e61fa88f3b6", "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": "heat_transfer_in_water.ipynb", "max_issues_repo_name": "Arbi-ben-aoun/Numerical-modeling-with-python", "max_issues_repo_head_hexsha": "7b0c02e7d3c94a668e719b7d32893e61fa88f3b6", "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": "heat_transfer_in_water.ipynb", "max_forks_repo_name": "Arbi-ben-aoun/Numerical-modeling-with-python", "max_forks_repo_head_hexsha": "7b0c02e7d3c94a668e719b7d32893e61fa88f3b6", "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": 201.1703204047, "max_line_length": 65208, "alphanum_fraction": 0.8951749459, "converted": true, "num_tokens": 3858, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566341975270266, "lm_q2_score": 0.9334308082517252, "lm_q1q2_score": 0.892951832198893}} {"text": "# Multiples in Number Range\n\nRepo: https://github.com/Andrewnetwork/MathematicalProgrammingProblems\n\n## 0.) Definitions \nA *range* of natural numbers, positive integers, can be defined by the notation $[x,y]$ where $x$ is the starting number and $y$ is the ending number. Example: $[0,10] = [0,1,2,3,4,5,6,7,8,9,10]$. \n\nIn the range $[x,y]$ there are $y-x = \\lvert[x,y]\\lvert$ numbers. Example: $\\lvert[2,5]\\lvert= 5 - 2 = 3.$ There are three numbers in the range $[2,5]$: $[2,3,4]$\n\nA number $m$ is a *multiple* of some natural number $n$ if there is some integer $i$ such that $n = im$.\n\n## 1.) How Many Multiples in a Range\n\nLet $x,y,z \\in \\mathbb{N}.$ \n\n\nIn the number range $[x,y]$ given $x\n\n\n\n\n\n\n\n```python\ny_interp = sym.simplify(sum(f_data[k]*basis[k] for k in range(3)))\ny_interp\n```\n\nNow we plot the complete approximating polynomial, the actual function and the points where the function was known.\n\n\n```python\ny_interp = sum(f_data[k]*basis_num(x_eval)[k] for k in range(3))\ny_original = fun(x_eval)\n\nplt.figure(figsize=(6, 4))\nplt.plot(x_eval, y_original)\nplt.plot(x_eval, y_interp)\nplt.plot([-1, 1, 0], f_data, 'ko')\nplt.show()\n```\n\n\n \n\n\n\n\n\n\nThe next cell change the format of the Notebook.\n\n\n```python\nfrom IPython.core.display import HTML\ndef css_styling():\n styles = open('../styles/custom_barba.css', 'r').read()\n return HTML(styles)\ncss_styling()\n```\n", "meta": {"hexsha": "58a534a611940b799937c611a4ccef212bf5295a", "size": 151725, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/.ipynb_checkpoints/LAGRANGE1D-checkpoint.ipynb", "max_stars_repo_name": "jomorlier/FEM-Notes", "max_stars_repo_head_hexsha": "3b81053aee79dc59965c3622bc0d0eb6cfc7e8ae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-04-15T01:53:14.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-15T01:53:14.000Z", "max_issues_repo_path": "notebooks/.ipynb_checkpoints/LAGRANGE1D-checkpoint.ipynb", "max_issues_repo_name": "jomorlier/FEM-Notes", "max_issues_repo_head_hexsha": "3b81053aee79dc59965c3622bc0d0eb6cfc7e8ae", "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/.ipynb_checkpoints/LAGRANGE1D-checkpoint.ipynb", "max_forks_repo_name": "jomorlier/FEM-Notes", "max_forks_repo_head_hexsha": "3b81053aee79dc59965c3622bc0d0eb6cfc7e8ae", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-05-25T17:19:53.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-25T17:19:53.000Z", "avg_line_length": 81.9692058347, "max_line_length": 42435, "alphanum_fraction": 0.7188531883, "converted": true, "num_tokens": 967, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122744874229, "lm_q2_score": 0.9314625112488223, "lm_q1q2_score": 0.8922593727501261}} {"text": "# Item I\n\nWhat is a...\n\n### a) Singular matrix\n\nA square matrix ($n\\times n$) $A$ is singular if there doesn't exist a square matrix ($n \\times n$) $B$ such that:\n$$\nBA = I_n \\, \\wedge \\, AB = I_n\n$$\nwhere $I_n$ is the $n \\times n$ identity matrix. $B$ is denoted as $A^{-1}$.\n\nThe following conditions for $A$ are equivalent:\n* $A$ is singular.\n* Its determinant is 0.\n* At least one of its eigenvalues is 0.\n* $\\text{rank}(A) < n $.\n* The equation $A\\vec{x} = \\vec{0}$ has infinite solutions.\n\nProperties:\n* The equation $A\\vec{x} = \\vec{b}$, with $\\vec{b}\\neq \\vec{0}$, can have zero or infinite solutions.\n* $(A^{-1})^{-1} = A$.\n* $(kA)^{-1} = k^{-1} A^{-1}$, if $k \\neq 0$.\n* $(A^T)^{-1} = (A^{-1})^T$\n* $\\text{det}(A^{-1}) = \\text{det}(A)^{-1}$\n* $A^{-1} = Q \\Lambda^{-1} Q^{-1}$, where $Q$ and $\\Lambda$ are matrices obtained from the [eigendecomposition](https://en.wikipedia.org/wiki/Eigendecomposition_of_a_matrix) of the matrix: $A = Q \\Lambda Q^{-1}$.\n\n### b) Vandermonde matrix\n\nIs a $m \\times n$ matrix with the following structure:\n$$\nV = \\begin{bmatrix}1&\\alpha _{1}&\\alpha _{1}^{2}&\\dots &\\alpha _{1}^{n-1}\\\\1&\\alpha _{2}&\\alpha _{2}^{2}&\\dots &\\alpha _{2}^{n-1}\\\\1&\\alpha _{3}&\\alpha _{3}^{2}&\\dots &\\alpha _{3}^{n-1}\\\\\\vdots &\\vdots &\\vdots &\\ddots &\\vdots \\\\1&\\alpha _{m}&\\alpha _{m}^{2}&\\dots &\\alpha _{m}^{n-1}\\end{bmatrix}\n$$\n\n* It evaluates a polynomial at a set of points. It maps the coefficients of a polynomial to the value it acquires at the $\\alpha_i$'s.\n* $\\det(V) = \\prod_{1\\leq i < j \\leq n} (\\alpha_j-\\alpha_i)$.\n* A $m \\times n$ rectangular Vandermonde matrix such that $m \\leq n$ has maximum rank $m$ iff all $x_i$ are distinct.\n* A $m \\times n$ rectangular Vandermonde matrix such that $n \\leq m$ has maximum rank $n$ iff there are $n$ of the $\\alpha_i$ that are distinct.\n* A $n \\times n$ Vandermonde matrix is invertible iff the $\\alpha_i$ are distinct. [A direct formula to compute it is known](https://ntrs.nasa.gov/archive/nasa/casi.ntrs.nasa.gov/19660023042.pdf).\n* The discrete Fourier transform is defined by the [DFT matrix](https://en.wikipedia.org/wiki/DFT_matrix), which is a specific Vandermonde matrix where the numbers $\\alpha_i$ are chosen to be roots of unity.\n\n### c) Symmetric matrix\n\nA square matrix $A$ so that $A = A^T$.\n\n* Every square diagonal matrix is symmetric.\n* With $A,B$ symmetric, $A+B$ is symmetric.\n* With $A,B$ symmetric, iff $AB=BA$, then $AB$ is symmetric.\n* Given $n$ integer, $A^n$ is symmetric.\n* If $A^{-1}$ exists, it is symmetric.\n* If $A \\in \\mathbb{R}^{n\\times n}$, then $\\langle A\\vec{x}, \\vec{y} \\rangle = \\langle \\vec{x}, A\\vec{y} \\rangle \\quad \\forall \\vec{x},\\vec{y}, \\in \\mathbb{R}^n$\n* If $A$ is congruent with $R$, i.e. there exists an invertible matrix $P$ so that $P^T AP = B$, then $B$ is also symmetric.\n* Every squared real matrix can be docmposed into two real symmetric matrices.\n* If $A \\in \\mathbb{R}$, it is also hermitian (and has their properties!).\n\n### d) Hermitian matrix\n\nA square matrix $A$ so that $A = A^*$, where $A^* = \\overline{A^T}$.\n* $a_{ij} = \\overline{a_{ji}}$\n* All the eigenvalues $A$ are real.\n* $A$ is normal, i.e. $A^*A = AA^*$.\n* $\\langle \\vec{v}, A\\vec{v} \\rangle \\in \\mathbb{R}$\n* If $A$ is also positive-definite (i.e. $\\vec{z}^* A \\vec{z} > 0, \\forall z \\neq \\vec{0}$), then $A=LL^*$ where $L$ is a lower-triangular matrix.\n * This is the [Cholesky decomposition](https://en.wikipedia.org/wiki/Cholesky_decomposition), more efficient than $LU$ decomposition for solving systems of linear equations.\n* $\\langle \\vec{v}, A \\vec{w} \\rangle = \\langle A\\vec{v}, \\vec{w} \\rangle$\n* With $A,B$ hermitian, $A+B$ is hermitian.\n* With $A,B$ hermitian, if $AB=BA$, then $AB$ is hermitian.\n* Given $n$ integer, $A^n$ is hermitian.\n* $A$ can be diagonalized: $A= Q\\Lambda Q^T$, where $Q$ is a unitary matrix.\n * $Q$ is composed of orthonormal eigenvectors of $A$ and $\\Lambda$ is diagonal, having the eigenvalues of $A$.\n * It holds that $$\n A = \\sum_j \\lambda_j u_j u_j^* \\,,\n $$ where the $u_j$'s are the orthonormal eigenvectors and the $\\lambda_j$'s are the eigenvalues.\n * This is the [eigendecomposition](https://en.wikipedia.org/wiki/Eigendecomposition_of_a_matrix) of $A$.\n* $B + B^*$ is Hermitian, for a square matrix $B$.\n\n### e) Skew-hermitian matrix\n\nA square matrix $A$ so that $A^* = -A$, where $A^* = \\overline{A^T}$.\n\nThe following conditions are equivalent:\n* The real part $\\mathfrak{R}(A)$ is skew-symmetric and the imaginary part $\\mathfrak{I}(A)$ is symmetric.\n* $iA$ is Hermitian.\n* $-iA$ is Hermitian.\n* $x^*Ay=-y^*Ax$ for all vectors $x,y$.\n\nProperties:\n* $a_{ij} = -\\overline{a_{ji}}$\n* All the eigenvalues of a $A$ are purely imaginary (possibly zero).\n* It is normal (i.e. $A^*A = AA^*$).\n * $\\Rightarrow$ it is diagonalizable ($A = VDV^*$ with $V$ unitary and $D$ diagonal).\n * Its eigenvectors for distinct eigenvalues are orthogonal.\n* All $a_{ii}$ (values in the diagonal) have to be purely imaginary (possibly zero).\n* With $A,B$ skew-Hermitian, $A+B$ is skew-hermitian.\n* $A^k$ is Hermitian if $k$ is even and skew-Hermitian if $k$ is odd.\n* $B - B^*$ is skew-Hermitian, for a square matrix $B$.\n* An arbitrary square matrix $X$ can be writeen as the sum of a Hermitian matrix $H$ and a skew-Hermitian matrix $S$:\n$$\nX = H + S \\quad \\text{with} \\quad H = \\tfrac{1}{2}(X+X^*) \\quad \\text{and} \\quad S = \\tfrac{1}{2}(X-X^*)\n$$\n\n### f) Unitary matrix\n\nA square matrix $U$ is unitary if $U^*$ is also its inverse $U^{-1}$:\n$$\nU^* U = U U^* = I\n$$\n\nThe following conditions for $U$ are equivalent:\n* $U^*$ is unitary.\n* $U^{-1} = U^*$\n* $U$ is normal and their eigenvalues are in the unit circle.\n* The columns of $U$ form an orthonormal basis of $\\mathbb{C}^n$.\n* The rows of $U$ form an orthonormal basis of $\\mathbb{C}^n$.\n\nProperties:\n* By definition, it is normal (i.e. $U^*U = UU^*$).\n * $\\Rightarrow$ it is diagonalizable ($A = VDV^*$ with $V$ unitary and $D$ diagonal).\n * Its eigenvectors for distinct eigenvalues are orthogonal (orthonormal in this case).\n* $|\\text{det}(U)| = 1$\n* Vector norms are preserved on multiplication.\n\n### g) Jacobian matrix\n\nA matrix $J$ that contains all the first-order partial derivates of a vector-valued function $\\mathbf{f}:\\mathbb{R}^n \\rightarrow \\mathbb{R}^m$ :\n\n$$\nJ(x_1,\\dots,x_n) = \\left[\n\\begin{matrix}\n\\frac{\\partial \\mathbf{f}}{\\partial x_1}\n& \\cdots\n& \\frac{\\partial \\mathbf{f}}{\\partial x_n}\n\\end{matrix} \\right]\n= \\left[\n\\begin{matrix}\n\\frac{\\partial f_1}{\\partial x_1} & \\cdots & \\frac{\\partial f_1}{\\partial x_n}\n\\\\ \\vdots & \\ddots & \\vdots\n\\\\ \\frac{\\partial f_m}{\\partial x_1} & \\cdots & \\frac{\\partial f_m}{\\partial x_n}\n\\end{matrix} \\right]\n$$\n\n* The best linear approximation of $\\mathbf{f}$ near a point $\\mathbf{p}$ is:\n$$\n\\mathbf{f}(\\mathbf{x})-\\mathbf{f}(\\mathbf{p}) = J(\\mathbf{p})(\\mathbf{x}-\\mathbf{p})\n$$\n* If $J(\\mathbf{x})$ is non-singular, $\\mathbf{f}$ is locally invertible near $\\mathbf{x}$.\n* The inverse of the Jacobian matrix $J$ of $\\mathbf{f}$ is the Jacobian matrix of $\\mathbf{f}^{-1}$.\n* It satiesfies the chain rule:\n$$\nJ_{\\mathbf{g} \\circ \\mathbf{f}}(\\mathbf{x}) = J_{\\mathbf{g}}(\\mathbf{f}(\\mathbf{x})) J_{\\mathbf{f}}(\\mathbf{x}) \n$$\n\n### h) Projection matrix\n\nA matrix $P$ such that $P^2 = P$ (idempotent), that defines a transformation between the vector space $W$ to itself.\n\n* Its eigenvalues are $0$ or $1$.\n* Being $U = \\text{Rank}(P)$ and $V = \\text{Kern}(P)$:\n * $\\forall x \\in U : Px = x$, i.e. $P$ is equivalent to the identity on the subspace $U$.\n * Every vector $x \\in W$ may be decomposed uniquely as $x = u + v$, with $u = Px$ and $v = x - Px = (I-P) x$, where $u \\in U, v \\in V$.\n* If two projections commute, their product is a projection.\n* If $P$ projects onto a line with unit vector $u$, then $P=uu^T$.\n* If $P$ projects onto a subspace $U$ with $u_1,\\dots,u_k$ an arthonormal basis, then\n $P = AA^T$, where $A$ is the $n \\times k$ matrix whose columns are $u_1,\\dots,u_k$.\n\n### i) Companion matrix\n\nA square matrix defined for the polinomial:\n$$\np(t) = c_0 + c_1 t + \\cdots + c_{n-1} t^{n-1} + t^n\n$$\nas\n$$\nC(p) = \\left[\n\\begin{matrix}\n0 & 0 & \\cdots & 0 & -c_0 \\\\\n1 & 0 & \\cdots & 0 & -c_1 \\\\\n0 & 1 & \\cdots & 0 & -c_2 \\\\\n\\vdots & \\vdots & \\ddots & \\vdots & \\vdots \\\\\n0 & 0 & \\cdots & 1 & -c_{n-1}\n\\end{matrix}\n\\right]\n$$\n\n* A matrix $A$ is similar to the companion matrix $C$ of its characteristic polynomial (i.e. $\\exists P: C=P^{-1}AP$).\n * Similar matrices share several properties, in that sense, analyzing $C$ could be more easy that analyzing $B$.\n * Rank\n * Characteristic polynomial\n * Determinant\n * Trace\n * Eigenvalues\n\n### j) Jacobi matrix\n\nA square tridiagonal matrix:\n$$\nA = \\left[\\begin{matrix}\na_1 & b_1 & 0 & \\cdots & 0 & 0 \\\\\nc_1 & a_2 & b_2 & \\cdots & 0 & 0 \\\\\n0 & c_2 & a_3 & \\cdots & 0 & 0 \\\\\n\\vdots & \\vdots & \\vdots & \\ddots & \\vdots & \\vdots \\\\\n0 & 0 & 0 & \\cdots & a_{n-1} & b_{n-1} \\\\\n0 & 0 & 0 & \\cdots & c_{n-1} & a_{n} \n\\end{matrix}\\right]\n$$\nso that $a_i \\neq 0 , \\forall i$.\n\n* The determinant can be computed from a three-term recurrence relation:\n \\begin{align}\n f_m &= a_m f_{m-1} - c_{m-1}b_{m-1}f_{m-2} \\\\\n f_{-1} &= 0 \\\\\n f_{0} &= 1\n \\end{align}\n where each $f_m$ is the determinant of the top-left $m\\times m$ submatrix and, thus, $\\text{det}(A) = f_n$.\n* The inverse can be obtained by a [known recurrence](https://en.wikipedia.org/w/index.php?title=Tridiagonal_matrix&oldid=905913546#Inversion).\n* If it is also Toeplitz (i.e. all values in the same diagonal are equal), which means $a_i =a \\, \\forall i$ ; $b_i =b \\, \\forall i$ ; $c_i =c \\, \\forall i$; the eigenvalues are:\n$$\n\\lambda_k = a+2\\sqrt{bc} \\cos\\left(\\frac{k\\pi}{n+1}\\right), \\quad k=1,\\dots,n\n$$\n* If $A$ is real and symmetric, then its eigenvalues are real. If all offdiagonal elements are nonzero, then they also are distinct.\n* [Numerous methods](https://www.sciencedirect.com/science/article/pii/S1063520312001042?via%3Dihub) exist for the numerical computation of the eigenvalues of a real symmetric tridiagonal matrix.\n* With [Lanczos algorithm](https://en.wikipedia.org/wiki/Lanczos_algorithm) it is possible to transform a Hermitian matrix to tridiagonal (and compute its eigenvalues).\n\n### k) Defective matrix\n\nA $n \\times n$ matrix $A$ that doesn't have $n$ linearly independent eigenvectors.\n\n* $A$ has fewer than $n$ distinct eigenvalues. Repeated eigenvalues are called *defective*.\n* $A$ cannot be diagonalized.\n* Normal matrices are never defective.\n\n### l) Toeplitz matrix\n\nA matrix $A$ of size $n \\times n$ in which each descending diagonal from left to right is constant.\n$$\nA = \\left[ \\begin{matrix}\na_0 & a_{-1} & a_{-2} & \\cdots & a_{-(n-1)} \\\\\na_{1} & a_0 & a_{-1} & \\ddots & \\vdots \\\\\na_{2} & a_{1} & a_0 & \\ddots & a_{-2} \\\\\n\\vdots & \\ddots & \\ddots & \\ddots & a_{-1} \\\\\na_{n-1} & \\cdots & a_2 & a_1 & a_0\n\\end{matrix}\\right]\n$$\ni.e. it is determined by the constants $c_{-(n{-}1)},\\dots,c_{n-1}$, so that\n$$\na_{i,j} = c_{i-j}\n$$\n\n* The system $Ax = b$ (called Toeplitz system) can be solved using the [Levinson algorithm](https://en.wikipedia.org/wiki/Levinson_recursion) on $\\Theta(n^2)$ time.\n* $A$ can be decomposed ($LU$) in $O(n^2)$ time.\n* If $A$ is symmetric, it can be decomposed as:\n$$\n\\tfrac{1}{a_0} A = G G^T - (G-I) (G-I)^T\n$$\nwhere $G$ is the lower triangular part of $\\tfrac{1}{a_0}A$.\n* If $A$ is nonsingular and symmetric, we have that:\n$$\nA^{-1} = \\tfrac{1}{a_0}(B B^T - C C^T)\n$$\nwhere $B$ and $C$ are lower triangular Toeplitz matrices and $C$ is strictly lower.\n* It can be used to express a [discrete convolution](https://en.wikipedia.org/wiki/Toeplitz_matrix#Discrete_convolution) as matrix multiplication.\n\nNote: The definition sometimes is extended to include $n \\times m$ matrices but most properties don't apply.\n\n### m) Circulant matrix\n\nA Toeplitz matrix with the aditional condition that $a_i = a_{i+m}$.\n\n$$\nA = \\left[ \\begin{matrix}\na_0 & a_{n-1} & a_{n-2} & \\cdots & a_{1} \\\\\na_1 & a_0 & a_{n-1} & \\ddots & \\vdots \\\\\na_2 & a_{1} & a_0 & \\ddots & a_{n-2} \\\\\n\\vdots & \\ddots & \\ddots & \\ddots & a_{n-1} \\\\\na_{n-1} & \\cdots & a_2 & a_1 & a_0\n\\end{matrix}\\right]\n$$\n\nThe polynomial $f(x) = a_0 + a_1 x + a_2 x^2 + \\dots + a_{n-1}x^{n-1}$ is called the *asociated polynomial* of $A$.\n\n* It is fully specified by a vector $\\mathbf{a} = a_0,\\dots,a_{n-1}$.\n* They are diagonalized by a discrete Fourier transform.\n * Equations that contain them may be quickly solved useing a FFT.\n * The following matrix $U_n$ is composed of the eigenvectors of $A$:\n $$\n U_n^* = \\tfrac{1}{\\sqrt{n}}F_n \\quad \\text{and} \\quad U_n = \\sqrt{n}F_n^{-1} \\,,\n $$\n where $F_n = [f_{jk}]$ with $f_{jk} = e^{-2jk\\pi i/n},\\quad 0\\leq j,k < n$.\n * $A = U_n \\text{diag}(F_n \\mathbf{a}) U_n^* = F_n^{-1} \\text{diag}(F_n \\mathbf{a})F_n.$\n The eigenvalues of $A$ are given by $F_n \\mathbf{a}$ which can be calculated using a FFT.\n* The normalized eigenvectors are given by:\n$$\nv_j = \\tfrac{1}{\\sqrt{n}}(1,\\omega_j,\\omega_j^2,\\dots,\\omega_j^{n-1}), \\qquad \\forall j \\in [0,n{-}1] \\,,\n$$\nwhere $\\omega_j = \\text{exp}\\left( i \\tfrac{2 \\pi j}{n} \\right)$ (the $n$-th roots of unity).\n* The eigenvalues are given by:\n$$\n\\lambda_j = f(w_j), \\qquad \\forall j \\in [0,n{-}1] \\,.\n$$\n* $\\text{Rank}(A) = n-d$, where $d$ is the degree of the $\\text{gcd}(f(x),x^n-1)$.\n* If $A$ and $B$ are circulant, $A+B$ is circulant, $AB=BA$ is also circulant.\n* Given an equation $A\\mathbf{x} = \\mathbf{b}$, it can be written as a circular convolution:\n $$\n \\mathbf{a} \\star \\mathbf{x} = \\mathbf{b}\n $$\n Then $F_n(\\mathbf{a} \\star \\mathbf{x}) = F_n(\\mathbf{a})F_n(\\mathbf{x}) = F_n(\\mathbf{b})$ and then\n $$\n \\mathbf{x} = F_n^{-1}\\left[ \\left(\\frac{(F_n(\\mathbf{b}))_v}{(F_n(\\mathbf{a}))_v} \\right)_{v \\in Z} \\right]^T\n $$\n\n### n) Hankel matrix\n\nA matrix $A$ of size $n \\times n$ in which each **ascending** diagonal from left to right is constant.\n$$\nA = \\left[ \\begin{matrix}\na_0 & a_1 & a_2 & \\cdots & a_{n-1} \\\\\na_1 & a_2 & a_3 & \\cdots & a_n \\\\\na_2 & a_3 & a_4 & \\cdots & a_{n+1} \\\\\n\\vdots & \\vdots & \\vdots & \\ddots & \\vdots \\\\\na_{n-1} & a_{n} & a_{n+1} & \\cdots & a_{2n-2}\n\\end{matrix}\\right]\n$$\nin other words\n$$\nA = [A_{ij} = a_{i+j-2}]\n$$\n\n* It is symmetric.\n* The determinant of the particular Hankel matrix:\n$$\nH_n = \\left[h_{ij} = \\begin{cases}\n0 & \\text{ if } i+j-1 > n \\\\\ni+j-1 & \\text{otherwise}\n\\end{cases}\\right] = \\left[\n\\begin{matrix}\n1 & 2 & 3 & \\cdots & n{-}2 & n{-}1 & n \\\\\n2 & 3 & 4 & \\cdots & n{-}1 & n & 0 \\\\\n3 & 4 & 5 & \\cdots & n & 0 & 0 \\\\\n\\vdots & \\vdots & \\vdots & \\ddots & \\vdots & \\vdots & \\vdots \\\\\nn{-}2 & n{-}1 & n & \\cdots & 0 & 0 & 0\\\\\nn{-}1 & n & 0 & \\cdots & 0 & 0 & 0 \\\\\nn & 0 & 0 & \\cdots & 0 & 0 & 0 \\\\\n\\end{matrix}\n\\right]\n$$\nis given by $\\text{det}(H_n) = (-1)^{\\lfloor n/2 \\rfloor} n^n$.\n\n### o) Hilbert matrix\n\nThe Hilbert matrix is an specific $n \\times n$ matrix with the following form:\n$$\nH = \\left[h_{ij} = \\frac{1}{i+j-1}\\right] = \\left[\\begin{matrix}\n1 & \\tfrac{1}{2} & \\tfrac{1}{3} & \\cdots & \\tfrac{1}{n} \\\\\n\\tfrac{1}{2} & \\tfrac{1}{3} & \\tfrac{1}{4} & \\cdots & \\tfrac{1}{n{+}1} \\\\\n\\tfrac{1}{3} & \\tfrac{1}{4} & \\tfrac{1}{5} & \\cdots & \\tfrac{1}{n{+}2} \\\\\n\\vdots & \\vdots & \\vdots & \\ddots & \\vdots \\\\\n\\tfrac{1}{n} & \\tfrac{1}{n{+}1} & \\tfrac{1}{n{+}2} & \\cdots & \\tfrac{1}{2n{-}1}\n\\end{matrix}\\right]\n$$\n\n* They are canonical examples of ill-conditioned matrices.\n* It is a Hankel matrix.\n * It is symmetric.\n* The determinant is:\n$$\n\\text{det}(H) = \\frac{c_n^4}{c_{2n}} \\,,\n$$\nwhere\n$$\nc_n = \\prod_{i=1}^{n-1} i^{n-i} = \\prod_{i=1}^{n-1} i! \\, . \n$$\n* The inverse is given by:\n$$\nH^{-1} = \\left[h'_{ij} = (-1)^{i+j}(i+j-1)\\binom{n+i-1}{n-j} \\binom{n+j-1}{n-i} \\binom{i+j-2}{i-1}^2 \\right]\n$$\n * All entries are integers.\n * The signs form a checkerboard matrix, with the principal diagonal positive.\n* The condition number grows as $O\\left((1+\\sqrt{2})^{4n}\\middle/\\sqrt{n}\\right)$.\n\n### p) Markov matrix\n\nA matrix that describes the transitions of a Markov chain, where each entry represents a probability (non-negative), there are 3 kinds:\n* **right stochastic matrix**: each rows sums 1.\n* **left stochastic matrix**: each column sums 1.\n* **doubly stochastic matrix**: the whole matrix sums 1.\n\nFor the first one we have that\n$$\nP = [p_{ij}] \\, ,\n$$\nwith the condition that $\\sum_{j=1}^{n} p_{ij} = 1$, which is equivalent to:\n$$\nP \\mathbf{1} = \\mathbf{1}\n$$\n\n* The entry $p_{ij}$ represents the probability of transitioning from state $i$ to state $j$, where there are $n$ possible states. State probabilities should be multiplied by the left in order to advance the system.\n* The product of two right stochastic matrices is also stochastic: $P' P'' \\mathbf{1} = \\mathbf{1}$.\n* A probability vector $\\mathbf{\\pi}$ that's also a row eigenvector asociated to the eigenvalue $1$ represents a stationary distribution (that doesn't change under the application of the transition matrix):\n$$\n\\mathbf{\\pi} P = \\mathbf{\\pi} \\,.\n$$\n * The system evolves over time to a static state:\n $$\n \\lim_{k \\rightarrow \\infty} P^k = \\Pi,\n $$\n where al $\\Pi$ rows are equal, and coincide with the vector $\\mathbf{\\pi}$. \n* The vector $\\mathbf{1}$ is a column eigenvector of $P$.\n* The spectral radius is at most $1$, moreover:\n$$\n|\\lambda - \\omega| \\leq 1-\\omega, \\quad \\text{where } \\omega = \\min_{1\\leq i \\leq n} p_{ii}.\n$$\n\n### q) Differentiation matrices\n\nIts a matrix that when multiplied with a discrete approximation for a function $y(x)$, at some fixed points $x_j, j \\in 0,\\dots,n$ retrieves a numerical discrete approximation a derivate of $y$.\n\nThese matrices are equivalent to fiting a function $p$ to the data, differentiating this approximation and evaluating this differentiation.\n\nFor instance:\n$$\nD = \\frac{1}{h^2}\\left[\\begin{matrix}\n1 & -1 \\\\\n-1 & 2 & -1 \\\\\n& -1 & 2 & -1 \\\\\n& & \\ddots & \\ddots & \\ddots \\\\\n& & & -1 & 2 & -1 \\\\\n& & & & -1 & 2 & -1 \\\\\n& & & & & -1 & 1 \\\\\n\\end{matrix}\\right]\n$$\nperforms an approximation of $y''(x)$ using second-order central difference.\n\nThe approximation is performed:\n$$\nD \\mathbf{y} = \\mathbf{y''}\n$$\nwhere $\\mathbf{y} = [y(x_j)]$ and $\\mathbf{y''}$ is the approximation of $[y''(x_j)]$.\n\n* Spectral methods use basis functions that are nonzero over the whole domain (they are **global**), for instance, $p(x)$ being a polynomial of degree $n$. Differentiation matrices are dense.\n* Finite element methods use basis functions that are nonzero only on small subdomains (they are **local**), for instance, using $p(x)$ as splines. Differentiation matrices are sparse.\n* The spectral element method chooses high degree piecewise polynomials as basis functions, also achieving a very high order of accuracy. Such polynomials are usually orthogonal Chebyshev polynomials or very high order Legendre polynomials over non-uniformly spaced nodes.\n\nThese matrices are used to represent the differentiation operator in order to solve differential equations.\n\nPowers $D^n$ can be used to represent the $(n)$ derivate of a function discretization.\n\n### r) Spectral differentiation matrices\n\nDifferentiation matrices that get better global approximations for derivates. These approximations have \"*spectral accuracy*\", i.e. error diminises exponentially with $n$.\n\nOn multiplication, retrieves a vector of points $p'(x_j)$ (or a higher order derivate) where $p$ is a single function so that $p(x_j)=y_j$ and this function $p$ is (generally) nonzero over the domain.\n\n* For periodic grids: Fourier methods can be used, $p$ is chosen to be a sum of trigonometric functions.\n* For non periodic grids: Chebyshev methods can be used, $p$ is chosen to be a polynomial.\n\n### s) Chebyshev differentiation matrices\n\nA $(n{+}1) \\times (n{+}1)$ spectral differentiation matrix that evaluates the function at the Chebyshev points:\n$$\nx_j = \\cos(j\\pi/N),\\quad j = 0,\\dots,N\n$$\n\nOn multiplication, retrieves a vector of the points $p'(x_j)$ where $p(x)$ is the unique polynomial of degree $N$ that interpolates the input points.\n\nFor instance, for $n=2$:\n$$\nD = \\left[\n\\begin{matrix}\n\\tfrac{3}{2} & -2 & \\tfrac{1}{2} \\\\\n\\tfrac{1}{2} & 0 & -\\tfrac{1}{2} \\\\\n-\\tfrac{1}{2} & 2 & -\\tfrac{3}{2}\n\\end{matrix}\n\\right]\n$$\n\n\n```python\n\n```\n", "meta": {"hexsha": "9fae6ef4a3d0e9c2bd42c8c25873c2323a7f2220", "size": 26792, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "t1_questions/item_01.ipynb", "max_stars_repo_name": "autopawn/cc5-works", "max_stars_repo_head_hexsha": "63775574c82da85ed0e750a4d6978a071096f6e7", "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": "t1_questions/item_01.ipynb", "max_issues_repo_name": "autopawn/cc5-works", "max_issues_repo_head_hexsha": "63775574c82da85ed0e750a4d6978a071096f6e7", "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": "t1_questions/item_01.ipynb", "max_forks_repo_name": "autopawn/cc5-works", "max_forks_repo_head_hexsha": "63775574c82da85ed0e750a4d6978a071096f6e7", "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.0657894737, "max_line_length": 335, "alphanum_fraction": 0.5340773365, "converted": true, "num_tokens": 7202, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122696813392, "lm_q2_score": 0.9314625055410722, "lm_q1q2_score": 0.8922593628059156}} {"text": "# Chapter 9\n\n*Modeling and Simulation in Python*\n\nCopyright 2021 Allen Downey\n\nLicense: [Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International](https://creativecommons.org/licenses/by-nc-sa/4.0/)\n\n\n```python\n# check if the libraries we need are installed\n\ntry:\n import pint\nexcept ImportError:\n !pip install pint\n import pint\n \ntry:\n from modsim import *\nexcept ImportError:\n !pip install modsimpy\n from modsim import *\n```\n\nThe following displays SymPy expressions and provides the option of showing results in LaTeX format.\n\n\n```python\nfrom sympy.printing import latex\n\ndef show(expr, show_latex=False):\n \"\"\"Display a SymPy expression.\n \n expr: SymPy expression\n show_latex: boolean\n \"\"\"\n if show_latex:\n print(latex(expr))\n return expr\n```\n\n### Analysis with SymPy\n\nCreate a symbol for time.\n\n\n```python\nimport sympy as sp\n\nt = sp.symbols('t')\nt\n```\n\n\n\n\n$\\displaystyle t$\n\n\n\nIf you combine symbols and numbers, you get symbolic expressions.\n\n\n```python\nexpr = t + 1\nexpr\n```\n\n\n\n\n$\\displaystyle t + 1$\n\n\n\nThe result is an `Add` object, which just represents the sum without trying to compute it.\n\n\n```python\ntype(expr)\n```\n\n\n\n\n sympy.core.add.Add\n\n\n\n`subs` can be used to replace a symbol with a number, which allows the addition to proceed.\n\n\n```python\nexpr.subs(t, 2)\n```\n\n\n\n\n$\\displaystyle 3$\n\n\n\n`f` is a special class of symbol that represents a function.\n\n\n```python\nf = sp.Function('f')\nf\n```\n\n\n\n\n f\n\n\n\nThe type of `f` is `UndefinedFunction`\n\n\n```python\ntype(f)\n```\n\n\n\n\n sympy.core.function.UndefinedFunction\n\n\n\nSymPy understands that `f(t)` means `f` evaluated at `t`, but it doesn't try to evaluate it yet.\n\n\n```python\nf(t)\n```\n\n\n\n\n$\\displaystyle f{\\left(t \\right)}$\n\n\n\n`diff` returns a `Derivative` object that represents the time derivative of `f`\n\n\n```python\ndfdt = sp.diff(f(t), t)\ndfdt\n```\n\n\n\n\n$\\displaystyle \\frac{d}{d t} f{\\left(t \\right)}$\n\n\n\n\n```python\ntype(dfdt)\n```\n\n\n\n\n sympy.core.function.Derivative\n\n\n\nWe need a symbol for `alpha`\n\n\n```python\nalpha = sp.symbols('alpha')\nalpha\n```\n\n\n\n\n$\\displaystyle \\alpha$\n\n\n\nNow we can write the differential equation for proportional growth.\n\n\n```python\neq1 = sp.Eq(dfdt, alpha*f(t))\neq1\n```\n\n\n\n\n$\\displaystyle \\frac{d}{d t} f{\\left(t \\right)} = \\alpha f{\\left(t \\right)}$\n\n\n\nAnd use `dsolve` to solve it. The result is the general solution.\n\n\n```python\nsolution_eq = sp.dsolve(eq1)\nsolution_eq\n```\n\n\n\n\n$\\displaystyle f{\\left(t \\right)} = C_{1} e^{\\alpha t}$\n\n\n\nWe can tell it's a general solution because it contains an unspecified constant, `C1`.\n\nIn this example, finding the particular solution is easy: we just replace `C1` with `p_0`\n\n\n```python\nC1, p_0 = sp.symbols('C1 p_0')\n```\n\n\n```python\nparticular = solution_eq.subs(C1, p_0)\nparticular\n```\n\n\n\n\n$\\displaystyle f{\\left(t \\right)} = p_{0} e^{\\alpha t}$\n\n\n\nIn the next example, we have to work a little harder to find the particular solution.\n\n### Solving the quadratic growth equation \n\nWe'll use the (r, K) parameterization, so we'll need two more symbols:\n\n\n```python\nr, K = sp.symbols('r K')\n```\n\nNow we can write the differential equation.\n\n\n```python\neq2 = sp.Eq(sp.diff(f(t), t), r * f(t) * (1 - f(t)/K))\neq2\n```\n\n\n\n\n$\\displaystyle \\frac{d}{d t} f{\\left(t \\right)} = r \\left(1 - \\frac{f{\\left(t \\right)}}{K}\\right) f{\\left(t \\right)}$\n\n\n\nAnd solve it.\n\n\n```python\nsolution_eq = sp.dsolve(eq2)\nsolution_eq\n```\n\n\n\n\n$\\displaystyle f{\\left(t \\right)} = \\frac{K e^{C_{1} K + r t}}{e^{C_{1} K + r t} - 1}$\n\n\n\nThe result, `solution_eq`, contains `rhs`, which is the right-hand side of the solution.\n\n\n```python\ngeneral = solution_eq.rhs\ngeneral\n```\n\n\n\n\n$\\displaystyle \\frac{K e^{C_{1} K + r t}}{e^{C_{1} K + r t} - 1}$\n\n\n\nWe can evaluate the right-hand side at $t=0$\n\n\n```python\nat_0 = general.subs(t, 0)\nat_0\n```\n\n\n\n\n$\\displaystyle \\frac{K e^{C_{1} K}}{e^{C_{1} K} - 1}$\n\n\n\nNow we want to find the value of `C1` that makes `f(0) = p_0`.\n\nSo we'll create the equation `at_0 = p_0` and solve for `C1`. Because this is just an algebraic identity, not a differential equation, we use `solve`, not `dsolve`.\n\nThe result from `solve` is a list of solutions. In this case, [we have reason to expect only one solution](https://en.wikipedia.org/wiki/Picard%E2%80%93Lindel%C3%B6f_theorem), but we still get a list, so we have to use the bracket operator, `[0]`, to select the first one.\n\n\n```python\nsolutions = sp.solve(sp.Eq(at_0, p_0), C1)\ntype(solutions), len(solutions)\n```\n\n\n\n\n (list, 1)\n\n\n\n\n```python\nvalue_of_C1 = solutions[0]\nvalue_of_C1\n```\n\n\n\n\n$\\displaystyle \\frac{\\log{\\left(- \\frac{p_{0}}{K - p_{0}} \\right)}}{K}$\n\n\n\nNow in the general solution, we want to replace `C1` with the value of `C1` we just figured out.\n\n\n```python\nparticular = general.subs(C1, value_of_C1)\nparticular\n```\n\n\n\n\n$\\displaystyle - \\frac{K p_{0} e^{r t}}{\\left(K - p_{0}\\right) \\left(- \\frac{p_{0} e^{r t}}{K - p_{0}} - 1\\right)}$\n\n\n\nThe result is complicated, but SymPy provides a method that tries to simplify it.\n\n\n```python\nparticular = sp.simplify(particular)\nparticular\n```\n\n\n\n\n$\\displaystyle \\frac{K p_{0} e^{r t}}{K + p_{0} e^{r t} - p_{0}}$\n\n\n\nOften simplicity is in the eye of the beholder, but that's about as simple as this expression gets.\n\nJust to double-check, we can evaluate it at `t=0` and confirm that we get `p_0`\n\n\n```python\nparticular.subs(t, 0)\n```\n\n\n\n\n$\\displaystyle p_{0}$\n\n\n\nThis solution is called the [logistic function](https://en.wikipedia.org/wiki/Population_growth#Logistic_equation).\n\nIn some places you'll see it written in a different form:\n\n$f(t) = \\frac{K}{1 + A e^{-rt}}$\n\nwhere $A = (K - p_0) / p_0$.\n\nWe can use SymPy to confirm that these two forms are equivalent. First we represent the alternative version of the logistic function:\n\n\n```python\nA = (K - p_0) / p_0\nA\n```\n\n\n\n\n$\\displaystyle \\frac{K - p_{0}}{p_{0}}$\n\n\n\n\n```python\nlogistic = K / (1 + A * sp.exp(-r*t))\nlogistic\n```\n\n\n\n\n$\\displaystyle \\frac{K}{1 + \\frac{\\left(K - p_{0}\\right) e^{- r t}}{p_{0}}}$\n\n\n\nTo see whether two expressions are equivalent, we can check whether their difference simplifies to 0.\n\n\n```python\nsp.simplify(particular - logistic)\n```\n\n\n\n\n$\\displaystyle 0$\n\n\n\nThis test only works one way: if SymPy says the difference reduces to 0, the expressions are definitely equivalent (and not just numerically close).\n\nBut if SymPy can't find a way to simplify the result to 0, that doesn't necessarily mean there isn't one. Testing whether two expressions are equivalent is a surprisingly hard problem; in fact, there is no algorithm that can solve it in general.\n\n### Exercises\n\n**Exercise:** Solve the quadratic growth equation using the alternative parameterization\n\n$\\frac{df(t)}{dt} = \\alpha f(t) + \\beta f^2(t) $\n\n\n```python\nbeta = sp.symbols('beta')\nbeta\n```\n\n\n\n\n$\\displaystyle \\beta$\n\n\n\n\n```python\neq3 = sp.Eq(sp.diff(f(t), t), alpha * f(t) + beta * f(t)**2)\neq3\n```\n\n\n\n\n$\\displaystyle \\frac{d}{d t} f{\\left(t \\right)} = \\alpha f{\\left(t \\right)} + \\beta f^{2}{\\left(t \\right)}$\n\n\n\n\n```python\nsolution_eq3 = sp.dsolve(eq3)\nsolution_eq3\n```\n\n\n\n\n$\\displaystyle f{\\left(t \\right)} = \\frac{\\alpha e^{\\alpha \\left(C_{1} + t\\right)}}{\\beta \\left(1 - e^{\\alpha \\left(C_{1} + t\\right)}\\right)}$\n\n\n\n\n```python\ngeneral3 = solution_eq3.rhs\ngeneral3\n```\n\n\n\n\n$\\displaystyle \\frac{\\alpha e^{\\alpha \\left(C_{1} + t\\right)}}{\\beta \\left(1 - e^{\\alpha \\left(C_{1} + t\\right)}\\right)}$\n\n\n\n\n```python\nat_03 = general3.subs(t, 0)\nat_03\n```\n\n\n\n\n$\\displaystyle \\frac{\\alpha e^{C_{1} \\alpha}}{\\beta \\left(1 - e^{C_{1} \\alpha}\\right)}$\n\n\n\n\n```python\nsolutions3 = sp.solve(sp.Eq(at_03, p_0), C1)\nsolutions3[0]\n```\n\n\n\n\n$\\displaystyle \\frac{\\log{\\left(\\frac{\\beta p_{0}}{\\alpha + \\beta p_{0}} \\right)}}{\\alpha}$\n\n\n\n\n```python\nparticular3 = sp.simplify(general3.subs(C1, solutions3[0]))\nparticular3\n```\n\n\n\n\n$\\displaystyle \\frac{\\alpha p_{0} e^{\\alpha t}}{\\alpha - \\beta p_{0} e^{\\alpha t} + \\beta p_{0}}$\n\n\n\n**Exercise:** Use [WolframAlpha](https://www.wolframalpha.com/) to solve the quadratic growth model, using either or both forms of parameterization:\n\n df(t) / dt = alpha f(t) + beta f(t)^2\n\nor\n\n df(t) / dt = r f(t) (1 - f(t)/K)\n\nFind the general solution and also the particular solution where `f(0) = p_0`.\n\n\n```python\nPlease see the solution above\n```\n", "meta": {"hexsha": "4a83b9f6182251234e0e64421bbd5dd9a42583ab", "size": 35113, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "colab/chap09.ipynb", "max_stars_repo_name": "ferrysany/ModSimPy", "max_stars_repo_head_hexsha": "4b68634ee847102ad3b0f1816ac0b1c3125018d3", "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": "colab/chap09.ipynb", "max_issues_repo_name": "ferrysany/ModSimPy", "max_issues_repo_head_hexsha": "4b68634ee847102ad3b0f1816ac0b1c3125018d3", "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": "colab/chap09.ipynb", "max_forks_repo_name": "ferrysany/ModSimPy", "max_forks_repo_head_hexsha": "4b68634ee847102ad3b0f1816ac0b1c3125018d3", "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": 25.0628122769, "max_line_length": 283, "alphanum_fraction": 0.4169111155, "converted": true, "num_tokens": 2530, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012709406661, "lm_q2_score": 0.9433475806647386, "lm_q1q2_score": 0.8922193407315123}} {"text": "# Gradient Descent Optimizations\n\nMini-batch and stochastic gradient descent is widely used in deep learning, where the large number of parameters and limited memory make the use of more sophisticated optimization methods impractical. Many methods have been proposed to accelerate gradient descent in this context, and here we sketch the ideas behind some of the most popular algorithms.\n\n\n```python\n%matplotlib inline\n```\n\n\n```python\nimport matplotlib.pyplot as plt\nimport numpy as np\n```\n\n## Smoothing with exponentially weighted averages\n\n\n```python\nn = 50\nx = np.arange(n) * np.pi\ny = np.cos(x) * np.exp(x/100) - 10*np.exp(-0.01*x)\n```\n\n### Exponentially weighted average\n\nThe exponentially weighted average adds a fraction $\\beta$ of the current value to a leaky running sum of past values. Effectively, the contribution from the $t-n$th value is scaled by\n\n$$\n\\beta^n(1 - \\beta)\n$$\n\nFor example, here are the contributions to the current value after 5 iterations (iteration 5 is the current iteration)\n\n| iteration | contribution |\n| --- | --- |\n| 1 | $\\beta^4(1 - \\beta)$ |\n| 2 | $\\beta^3(1 - \\beta)$ |\n| 3 | $\\beta^2(1 - \\beta)$ |\n| 4 | $\\beta^1(1 - \\beta)$ |\n| 5 | $(1 - \\beta)$ |\n\nSince $\\beta \\lt 1$, the contribution decreases exponentially with the passage of time. Effectively, this acts as a smoother for a function.\n\n\n```python\ndef ewa(y, beta):\n \"\"\"Exponentially weighted average.\"\"\"\n \n n = len(y)\n zs = np.zeros(n)\n z = 0\n for i in range(n):\n z = beta*z + (1 - beta)*y[i]\n zs[i] = z\n return zs\n```\n\n### Exponentially weighted average with bias correction\n\nSince the EWA starts from 0, there is an initial bias. This can be corrected by scaling with \n\n$$\n\\frac{1}{1 - \\beta^t}\n$$\n\nwhere $t$ is the iteration number.\n\n\n```python\ndef ewabc(y, beta):\n \"\"\"Exponentially weighted average with hias correction.\"\"\"\n \n n = len(y)\n zs = np.zeros(n)\n z = 0\n for i in range(n):\n z = beta*z + (1 - beta)*y[i]\n zc = z/(1 - beta**(i+1))\n zs[i] = zc\n return zs\n```\n\n\n```python\nbeta = 0.9\n\nplt.plot(x, y, 'o-')\nplt.plot(x, ewa(y, beta), c='red', label='EWA')\nplt.plot(x, ewabc(y, beta), c='orange', label='EWA with bias correction')\nplt.legend()\npass\n```\n\n## Momentum in 1D\n\nMomentum comes from physics, where the contribution of the gradient is to the velocity, not the position. Hence we create an accessory variable $v$ and increment it with the gradient. The position is then updated with the velocity in place of the gradient. The analogy is that we can think of the parameter $x$ as a particle in an energy well with potential energy $U = mgh$ where $h$ is given by our objective function $f$. The force generated is a function of the rat of change of potential energy $F \\propto \\nabla U \\propto \\nabla f$, and we use $F = ma$ to get that the acceleration $a \\propto \\nabla f$. Finally, we integrate $a$ over time to get the velocity $v$ and integrate $v$ to get the displacement $x$. Note that we need to damp the velocity otherwise the particle would just oscillate forever.\n\nWe use a version of the update that simply treats the velocity as an exponentially weighted average popularized by Andrew Ng in his Coursera course. This is the same as the momentum scheme motivated by physics with some rescaling of constants.\n\n\n```python\ndef f(x):\n return x**2\n```\n\n\n```python\ndef grad(x):\n return 2*x\n```\n\n\n```python\ndef gd(x, grad, alpha, max_iter=10):\n xs = np.zeros(1 + max_iter)\n xs[0] = x\n for i in range(max_iter):\n x = x - alpha * grad(x)\n xs[i+1] = x\n return xs\n```\n\n\n```python\ndef gd_momentum(x, grad, alpha, beta=0.9, max_iter=10):\n xs = np.zeros(1 + max_iter)\n xs[0] = x\n v = 0\n for i in range(max_iter):\n v = beta*v + (1-beta)*grad(x)\n vc = v/(1+beta**(i+1))\n x = x - alpha * vc\n xs[i+1] = x\n return xs\n```\n\n### Gradient descent with moderate step size\n\n\n```python\nalpha = 0.1\nx0 = 1\nxs = gd(x0, grad, alpha)\nxp = np.linspace(-1.2, 1.2, 100)\nplt.plot(xp, f(xp))\nplt.plot(xs, f(xs), 'o-', c='red')\nfor i, (x, y) in enumerate(zip(xs, f(xs)), 1):\n plt.text(x, y+0.2, i, \n bbox=dict(facecolor='yellow', alpha=0.5), fontsize=14)\npass\n```\n\n### Gradient descent with large step size\n\nWhen the step size is too large, gradient descent can oscillate and even diverge.\n\n\n```python\nalpha = 0.95\nxs = gd(1, grad, alpha)\nxp = np.linspace(-1.2, 1.2, 100)\nplt.plot(xp, f(xp))\nplt.plot(xs, f(xs), 'o-', c='red')\nfor i, (x, y) in enumerate(zip(xs, f(xs)), 1):\n plt.text(x*1.2, y, i,\n bbox=dict(facecolor='yellow', alpha=0.5), fontsize=14)\npass\n```\n\n### Gradient descent with momentum\n\nMomentum results in cancellation of gradient changes in opposite directions, and hence damps out oscillations while amplifying consistent changes in the same direction. This is perhaps clearer in the 2D example below.\n\n\n```python\nalpha = 0.95\nxs = gd_momentum(1, grad, alpha, beta=0.9)\nxp = np.linspace(-1.2, 1.2, 100)\nplt.plot(xp, f(xp))\nplt.plot(xs, f(xs), 'o-', c='red')\nfor i, (x, y) in enumerate(zip(xs, f(xs)), 1):\n plt.text(x, y+0.2, i, \n bbox=dict(facecolor='yellow', alpha=0.5), fontsize=14)\npass\n```\n\n## Momentum and RMSprop in 2D\n\n\n```python\ndef f2(x):\n return x[0]**2 + 100*x[1]**2\n```\n\n\n```python\ndef grad2(x):\n return np.array([2*x[0], 200*x[1]])\n```\n\n\n```python\nx = np.linspace(-1.2, 1.2, 100)\ny = np.linspace(-1.2, 1.2, 100)\nX, Y = np.meshgrid(x, y)\nlevels = [0.1,1,2,4,9, 16, 25, 36, 49, 64, 81, 100]\nZ = x**2 + 100*Y**2\nc = plt.contour(X, Y, Z, levels)\npass\n```\n\n\n```python\ndef gd2(x, grad, alpha, max_iter=10):\n xs = np.zeros((1 + max_iter, x.shape[0]))\n xs[0,:] = x\n for i in range(max_iter):\n x = x - alpha * grad(x)\n xs[i+1,:] = x\n return xs\n```\n\n\n```python\ndef gd2_momentum(x, grad, alpha, beta=0.9, max_iter=10):\n xs = np.zeros((1 + max_iter, x.shape[0]))\n xs[0, :] = x\n v = 0\n for i in range(max_iter):\n v = beta*v + (1-beta)*grad(x)\n vc = v/(1+beta**(i+1))\n x = x - alpha * vc\n xs[i+1, :] = x\n return xs\n```\n\n### Gradient descent with large step size\n\nWe get severe oscillations.\n\n\n```python\nalpha = 0.01\nx0 = np.array([-1,-1])\nxs = gd2(x0, grad2, alpha, max_iter=75)\n```\n\n\n```python\nx = np.linspace(-1.2, 1.2, 100)\ny = np.linspace(-1.2, 1.2, 100)\nX, Y = np.meshgrid(x, y)\nlevels = [0.1,1,2,4,9, 16, 25, 36, 49, 64, 81, 100]\nZ = x**2 + 100*Y**2\nc = plt.contour(X, Y, Z, levels)\nplt.plot(xs[:, 0], xs[:, 1], 'o-', c='red')\nplt.title('Vanilla gradient descent')\npass\n```\n\n### Gradient descent with momentum\n\nThe damping effect is clear.\n\n\n```python\nalpha = 0.01\nx0 = np.array([-1,-1])\nxs = gd2_momentum(x0, grad2, alpha, beta=0.9, max_iter=75)\n```\n\n\n```python\nx = np.linspace(-1.2, 1.2, 100)\ny = np.linspace(-1.2, 1.2, 100)\nX, Y = np.meshgrid(x, y)\nlevels = [0.1,1,2,4,9, 16, 25, 36, 49, 64, 81, 100]\nZ = x**2 + 100*Y**2\nc = plt.contour(X, Y, Z, levels)\nplt.plot(xs[:, 0], xs[:, 1], 'o-', c='red')\nplt.title('Gradieent descent with momentum')\npass\n```\n\n### Gradient descent with RMSprop\n\nRMSprop scales the learning rate in each direction by the square root of the exponentially weighted sum of squared gradients. Near a saddle or any plateau, there are directions where the gradient is very small - RMSporp encourages larger steps in those directions, allowing faster escape.\n\n\n```python\ndef gd2_rmsprop(x, grad, alpha, beta=0.9, eps=1e-8, max_iter=10):\n xs = np.zeros((1 + max_iter, x.shape[0]))\n xs[0, :] = x\n v = 0\n for i in range(max_iter):\n v = beta*v + (1-beta)*grad(x)**2\n x = x - alpha * grad(x) / (eps + np.sqrt(v))\n xs[i+1, :] = x\n return xs\n```\n\n\n```python\nalpha = 0.1\nx0 = np.array([-1,-1])\nxs = gd2_rmsprop(x0, grad2, alpha, beta=0.9, max_iter=10)\n```\n\n\n```python\nx = np.linspace(-1.2, 1.2, 100)\ny = np.linspace(-1.2, 1.2, 100)\nX, Y = np.meshgrid(x, y)\nlevels = [0.1,1,2,4,9, 16, 25, 36, 49, 64, 81, 100]\nZ = x**2 + 100*Y**2\nc = plt.contour(X, Y, Z, levels)\nplt.plot(xs[:, 0], xs[:, 1], 'o-', c='red')\nplt.title('Gradient descent with RMSprop')\npass\n```\n\n### ADAM\n\nADAM (Adaptive Moment Estimation) combines the ideas of momentum, RMSprop and bias correction. It is probably the most popular gradient descent method in current deep learning practice.\n\n\n```python\ndef gd2_adam(x, grad, alpha, beta1=0.9, beta2=0.999, eps=1e-8, max_iter=10):\n xs = np.zeros((1 + max_iter, x.shape[0]))\n xs[0, :] = x\n m = 0\n v = 0\n for i in range(max_iter):\n m = beta1*m + (1-beta1)*grad(x)\n v = beta2*v + (1-beta2)*grad(x)**2\n mc = m/(1+beta1**(i+1))\n vc = v/(1+beta2**(i+1))\n x = x - alpha * m / (eps + np.sqrt(vc))\n xs[i+1, :] = x\n return xs\n```\n\n\n```python\nalpha = 0.1\nx0 = np.array([-1,-1])\nxs = gd2_adam(x0, grad2, alpha, beta1=0.9, beta2=0.9, max_iter=10)\n```\n\n\n```python\nx = np.linspace(-1.2, 1.2, 100)\ny = np.linspace(-1.2, 1.2, 100)\nX, Y = np.meshgrid(x, y)\nlevels = [0.1,1,2,4,9, 16, 25, 36, 49, 64, 81, 100]\nZ = x**2 + 100*Y**2\nc = plt.contour(X, Y, Z, levels)\nplt.plot(xs[:, 0], xs[:, 1], 'o-', c='red')\nplt.title('Gradient descent with RMSprop')\npass\n```\n\n## Implementing a custom optimization routine for `scipy.optimize`\n\nGradient descent is not one of the methods available in `scipy.optimize`. However we can implement our own version by following the API of the `minimize` function.\n\n\n```python\nimport scipy.optimize as opt\nimport scipy.linalg as la\n```\n\n\n```python\ndef custmin(fun, x0, args=(), maxfev=None, alpha=0.0002,\n maxiter=100000, tol=1e-10, callback=None, **options):\n \"\"\"Implements simple gradient descent for the Rosen function.\"\"\"\n bestx = x0\n bestf = fun(x0)\n funcalls = 1\n niter = 0\n improved = True\n stop = False\n\n while improved and not stop and niter < maxiter:\n niter += 1\n # the next 2 lines are gradient descent\n step = alpha * rosen_der(bestx)\n bestx = bestx - step\n\n bestf = fun(bestx)\n funcalls += 1\n \n if la.norm(step) < tol:\n improved = False\n if callback is not None:\n callback(bestx)\n if maxfev is not None and funcalls >= maxfev:\n stop = True\n break\n\n return opt.OptimizeResult(fun=bestf, x=bestx, nit=niter,\n nfev=funcalls, success=(niter > 1))\n```\n\n\n```python\ndef reporter(p):\n \"\"\"Reporter function to capture intermediate states of optimization.\"\"\"\n global ps\n ps.append(p)\n```\n\n### Test on Rosenbrock banana function\n\nWe will use the [Rosenbrock \"banana\" function](http://en.wikipedia.org/wiki/Rosenbrock_function) to illustrate unconstrained multivariate optimization. In 2D, this is\n$$\nf(x, y) = b(y - x^2)^2 + (a - x)^2\n$$\n\nThe function has a global minimum at (1,1) and the standard expression takes $a = 1$ and $b = 100$. \n\n#### Conditioning of optimization problem\n\nWith these values for $a$ and $b$, the problem is ill-conditioned. As we shall see, one of the factors affecting the ease of optimization is the condition number of the curvature (Hessian). When the condition number is high, the gradient may not point in the direction of the minimum, and simple gradient descent methods may be inefficient since they may be forced to take many sharp turns.\n\nFor the 2D version, we have\n\n$$\nf(x) = 100(y - x^2)^2 + (1 - x)^2\n$$\n\nand can calculate the Hessian to be \n\n$$\n\\begin{bmatrix}\n802 & -400 \\\\\n-400 & 200\n\\end{bmatrix}\n$$\n\n\n```python\nH = np.array([\n [802, -400],\n [-400, 200]\n])\n```\n\n\n```python\nnp.linalg.cond(H)\n```\n\n\n\n\n 2508.009601277298\n\n\n\n\n```python\nU, s, Vt = np.linalg.svd(H)\ns[0]/s[1]\n```\n\n\n\n\n 2508.0096012772983\n\n\n\n#### Function to minimize\n\n\n```python\ndef rosen(x):\n \"\"\"Generalized n-dimensional version of the Rosenbrock function\"\"\"\n return sum(100*(x[1:]-x[:-1]**2.0)**2.0 +(1-x[:-1])**2.0)\n```\n\n\n```python\ndef rosen_der(x):\n \"\"\"Derivative of generalized Rosen function.\"\"\"\n xm = x[1:-1]\n xm_m1 = x[:-2]\n xm_p1 = x[2:]\n der = np.zeros_like(x)\n der[1:-1] = 200*(xm-xm_m1**2) - 400*(xm_p1 - xm**2)*xm - 2*(1-xm)\n der[0] = -400*x[0]*(x[1]-x[0]**2) - 2*(1-x[0])\n der[-1] = 200*(x[-1]-x[-2]**2)\n return der\n```\n\n#### Why is the condition number so large?\n\n\n```python\nx = np.linspace(-5, 5, 100)\ny = np.linspace(-5, 5, 100)\nX, Y = np.meshgrid(x, y)\nZ = rosen(np.vstack([X.ravel(), Y.ravel()])).reshape((100,100))\n```\n\n\n```python\n# Note: the global minimum is at (1,1) in a tiny contour island\nplt.contour(X, Y, Z, np.arange(10)**5, cmap='jet')\nplt.text(1, 1, 'x', va='center', ha='center', color='red', fontsize=20)\npass\n```\n\n#### Zooming in to the global minimum at (1,1)\n\n\n```python\nx = np.linspace(0, 2, 100)\ny = np.linspace(0, 2, 100)\nX, Y = np.meshgrid(x, y)\nZ = rosen(np.vstack([X.ravel(), Y.ravel()])).reshape((100,100))\n```\n\n\n```python\nplt.contour(X, Y, Z, [rosen(np.array([k, k])) for k in np.linspace(1, 1.5, 10)], cmap='jet')\nplt.text(1, 1, 'x', va='center', ha='center', color='red', fontsize=20)\npass\n```\n\n#### We will use our custom gradient descent to minimize the banana function\n\n#### Helpful Hint \n\nOne of the most common causes of failure of optimization is because the gradient or Hessian function is specified incorrectly. You can check for this using `check_grad` which compares the analytical gradient with one calculated using finite differences.\n\n\n```python\nfrom scipy.optimize import check_grad\n\nfor x in np.random.uniform(-2,2,(10,2)):\n print(x, check_grad(rosen, rosen_der, x))\n```\n\n [ 1.48907302 -1.42171331] 3.04092560512107e-05\n [-0.48887404 1.21108406] 1.0685858595103707e-06\n [-1.1971752 1.28731448] 9.014975946452588e-06\n [-0.74543228 0.77030133] 3.1276750146010007e-06\n [ 0.24111646 -1.65737227] 7.678560202206516e-06\n [-1.37253259 -1.06738594] 2.2075707844094206e-05\n [-0.16354856 0.61330733] 2.526511024327562e-06\n [-1.20574923 0.20626545] 1.3748984984515249e-05\n [ 1.73282778 -1.84865849] 3.4902945985726736e-05\n [ 0.4104856 -1.81645528] 4.023697388337955e-06\n\n\n\n```python\n# Initial starting position\nx0 = np.array([4,-4.1])\nps = [x0]\nopt.minimize(rosen, x0, method=custmin, callback=reporter)\n```\n\n\n\n\n fun: 1.060466347344834e-08\n nfev: 100001\n nit: 100000\n success: True\n x: array([0.9998971 , 0.99979381])\n\n\n\n\n```python\nx = np.linspace(-5, 5, 100)\ny = np.linspace(-5, 5, 100)\nX, Y = np.meshgrid(x, y)\nZ = rosen(np.vstack([X.ravel(), Y.ravel()])).reshape((100,100))\n```\n\n\n```python\nps = np.array(ps)\nplt.figure(figsize=(12,4))\nplt.subplot(121)\nplt.contour(X, Y, Z, np.arange(10)**5, cmap='jet')\nplt.plot(ps[:, 0], ps[:, 1], '-ro')\nplt.subplot(122)\nplt.semilogy(range(len(ps)), rosen(ps.T))\npass\n```\n\n### Comparison with standard algorithms\n\nNote that all these methods take far fewer function iterations and function evaluations to find the minimum compared with vanilla gradient descent.\n\nMany of these are based on estimating the Newton direction. Recall Newton's method for finding roots of a univariate function\n\n$$\nx_{K+1} = x_k - \\frac{f(x_k)}{f'(x_k)}\n$$\n\nWhen we are looking for a minimum, we are looking for the roots of the *derivative* $f'(x)$, so\n\n$$\nx_{K+1} = x_k - \\frac{f'(x_k}{f''(x_k)}\n$$\n\nNewton's method can also be seen as a Taylor series approximation\n\n$$\nf(x+h) = f(x) + h f'(x) + \\frac{h^2}{2}f''(x)\n$$\n\nAt the function minimum, the derivative is 0, so\n\\begin{align}\n\\frac{f(x+h) - f(x)}{h} &= f'(x) + \\frac{h}{2}f''(x) \\\\\n0 &= f'(x) + \\frac{h}{2}f''(x) \n\\end{align}\n\nand letting $\\Delta x = \\frac{h}{2}$, we get that the Newton step is\n\n$$\n\\Delta x = - \\frac{f'(x)}{f''(x)}\n$$\n\nThe multivariate analog replaces $f'$ with the Jacobian and $f''$ with the Hessian, so the Newton step is\n\n$$\n\\Delta x = -H^{-1}(x) \\nabla f(x)\n$$\n\nSlightly more rigorously, we can optimize the quadratic multivariate Taylor expansion \n\n$$\nf(x + p) = f(x) + p^T\\nabla f(x) + \\frac{1}{2}p^TH(x)p\n$$\n\nDifferentiating with respect to the direction vector $p$ and setting to zero, we get\n\n$$\nH(x)p = -\\nabla f(x)\n$$\n\ngiving\n\n$$\np = -H(x)^{-1}\\nabla f(x)\n$$\n\n\n```python\nfrom scipy.optimize import rosen, rosen_der, rosen_hess\n```\n\n#### Nelder-Mead\n\nThere are some optimization algorithms not based on the Newton method, but on other heuristic search strategies that do not require any derivatives, only function evaluations. One well-known example is the Nelder-Mead simplex algorithm.\n\n\n```python\nps = [x0]\nopt.minimize(rosen, x0, method='nelder-mead', callback=reporter)\n```\n\n\n\n\n final_simplex: (array([[0.99998846, 0.99997494],\n [0.99994401, 0.99989075],\n [1.0000023 , 1.0000149 ]]), array([5.26275688e-10, 3.87529507e-09, 1.06085894e-08]))\n fun: 5.262756878429089e-10\n message: 'Optimization terminated successfully.'\n nfev: 162\n nit: 85\n status: 0\n success: True\n x: array([0.99998846, 0.99997494])\n\n\n\n\n```python\nps = np.array(ps)\nplt.figure(figsize=(12,4))\nplt.subplot(121)\nplt.contour(X, Y, Z, np.arange(10)**5, cmap='jet')\nplt.plot(ps[:, 0], ps[:, 1], '-ro')\nplt.subplot(122)\nplt.semilogy(range(len(ps)), rosen(ps.T));\n```\n\n#### BFGS\n\nAs calculating the Hessian is computationally expensive, sometimes first order methods that only use the first derivatives are preferred. Quasi-Newton methods use functions of the first derivatives to approximate the inverse Hessian. A well know example of the Quasi-Newoton class of algorithjms is BFGS, named after the initials of the creators. As usual, the first derivatives can either be provided via the `jac=` argument or approximated by finite difference methods.\n\n\n```python\nps = [x0]\nopt.minimize(rosen, x0, method='Newton-CG', jac=rosen_der, hess=rosen_hess, callback=reporter)\n```\n\n\n\n\n fun: 1.3642782750354208e-13\n jac: array([ 1.21204353e-04, -6.08502470e-05])\n message: 'Optimization terminated successfully.'\n nfev: 38\n nhev: 26\n nit: 26\n njev: 63\n status: 0\n success: True\n x: array([0.99999963, 0.99999926])\n\n\n\n\n```python\nps = np.array(ps)\nplt.figure(figsize=(12,4))\nplt.subplot(121)\nplt.contour(X, Y, Z, np.arange(10)**5, cmap='jet')\nplt.plot(ps[:, 0], ps[:, 1], '-ro')\nplt.subplot(122)\nplt.semilogy(range(len(ps)), rosen(ps.T))\npass\n```\n\n#### Newton-CG\n\nSecond order methods solve for $H^{-1}$ and so require calculation of the Hessian (either provided or approximated using finite differences). For efficiency reasons, the Hessian is not directly inverted, but solved for using a variety of methods such as conjugate gradient. An example of a second order method in the `optimize` package is `Newton-GC`.\n\n\n```python\nps = [x0]\nopt.minimize(rosen, x0, method='Newton-CG', jac=rosen_der, hess=rosen_hess, callback=reporter)\n```\n\n\n\n\n fun: 1.3642782750354208e-13\n jac: array([ 1.21204353e-04, -6.08502470e-05])\n message: 'Optimization terminated successfully.'\n nfev: 38\n nhev: 26\n nit: 26\n njev: 63\n status: 0\n success: True\n x: array([0.99999963, 0.99999926])\n\n\n\n\n```python\nps = np.array(ps)\nplt.figure(figsize=(12,4))\nplt.subplot(121)\nplt.contour(X, Y, Z, np.arange(10)**5, cmap='jet')\nplt.plot(ps[:, 0], ps[:, 1], '-ro')\nplt.subplot(122)\nplt.semilogy(range(len(ps)), rosen(ps.T))\npass\n```\n", "meta": {"hexsha": "882e175f1ac7698b277da0c9647fa2784c4d2388", "size": 728569, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebook/S09G_Gradient_Descent_Optimization.ipynb", "max_stars_repo_name": "ashnair1/sta-663-2019", "max_stars_repo_head_hexsha": "17eb85b644c52978c2ef3a53a80b7fb031360e3d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 68, "max_stars_repo_stars_event_min_datetime": "2019-01-09T21:53:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-16T17:14:22.000Z", "max_issues_repo_path": "notebook/S09G_Gradient_Descent_Optimization.ipynb", "max_issues_repo_name": "ashnair1/sta-663-2019", "max_issues_repo_head_hexsha": "17eb85b644c52978c2ef3a53a80b7fb031360e3d", "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": "notebook/S09G_Gradient_Descent_Optimization.ipynb", "max_forks_repo_name": "ashnair1/sta-663-2019", "max_forks_repo_head_hexsha": "17eb85b644c52978c2ef3a53a80b7fb031360e3d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 62, "max_forks_repo_forks_event_min_datetime": "2019-01-09T21:43:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-15T04:26:25.000Z", "avg_line_length": 533.7501831502, "max_line_length": 71516, "alphanum_fraction": 0.9432929482, "converted": true, "num_tokens": 6326, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632288833653, "lm_q2_score": 0.93721079754114, "lm_q1q2_score": 0.8920964958918635}} {"text": "# Mandatory exercises\n\nConsider the system $Ax = b$ where\n\\begin{equation}\n A=\\begin{bmatrix}\n 2 & 1 & 2\\\\\n 1 & 0 & 3\\\\\n 4 & -3 & -1\n \\end{bmatrix}\n \\text{ and }\n b=\\begin{bmatrix}\n -3\\\\\n 1\\\\\n -6\n \\end{bmatrix}\n\\end{equation}\n\n1. Perform the $LU$-factorization of the matrix $A$ by using Gaussian elimination with partial pivoting. Conclude by specifying $L$, $U$, and the permutation matrix $P$ . How is $A$ related to the matrices $L, U$ and $P$?\n\n\n```python\nimport scipy.linalg\nimport scipy\nimport numpy as np\n\nA = np.array([[2, 1, 2],\n [1, 0, 3],\n [4, -3, -1]])\nP, L, U = scipy.linalg.lu(A)\n\nprint('A='+str(A))\nprint('P='+str(P))\nprint('L='+str(L))\nprint('U='+str(U))\n\nprint(scipy.dot(P.T,A))\nprint(scipy.dot(L,U))\n```\n\n A=[[ 2 1 2]\n [ 1 0 3]\n [ 4 -3 -1]]\n P=[[0. 1. 0.]\n [0. 0. 1.]\n [1. 0. 0.]]\n L=[[1. 0. 0. ]\n [0.5 1. 0. ]\n [0.25 0.3 1. ]]\n U=[[ 4. -3. -1. ]\n [ 0. 2.5 2.5]\n [ 0. 0. 2.5]]\n [[ 4. -3. -1.]\n [ 2. 1. 2.]\n [ 1. 0. 3.]]\n [[ 4.00000000e+00 -3.00000000e+00 -1.00000000e+00]\n [ 2.00000000e+00 1.00000000e+00 2.00000000e+00]\n [ 1.00000000e+00 1.11022302e-16 3.00000000e+00]]\n\n\n2. Use $L$, $U$, and $P$ to solve the system $Ax = b$.\n\n3. Suppose that you have represented the system of equations $Ax = b$ by storing variables $A$ and $b$.\n 1. Write the Matlab/Python command that solves the system using Matlab’s 'backslash' operator/ Python function scipy.linalg.solve(), and stores the result in the variable $x$.\n 2. Write the Matlab/Python command that LU-factorizes the matrix. Then, write the commands that use the result of the LU-factorization to solve $Ax = b$.\n\n## If you have time\n\n4. Perform the LU-factorization as in Exercise 1 above. However, instead of the permutation matrix $P$ , you should use a vector `piv` to keep track of the pivoting information. Write a script that uses `L`, `U` and `piv` to solve $Ax = b$. \n\n5. It is important that computational algorithms are efficient with regard to both (1) floating point operations and (2) memory requirements, and that they (3) are stable. For each of these aspects, mention some feature(s) of the algorithm used in Exercise 1 relating to that aspect.\n\n6. True or false? (Give arguments to support your claim):\n 1. You can improve the conditioning of a coefficient matrix by increasing the precision in the floating point number representation.\n 2. Pivoting improves the condition number of the coefficient matrix.\n 3. Pivoting improves the accuracy of the solution obtained.\n\n# Non-mandatory exercises\n\n7. Suppose that you are going to compute the forces in a truss structure. This leads to a system of linear equations, where the right-hand side contains the external forces acting on the truss. We consider a case where the coefficient matrix has condition number cond$_1(A)\\approx10^3$ and the right-hand side is as follows (only two external forces acting on the truss):\n\\begin{equation}\n b=\\begin{bmatrix}\n 0\\\\\n \\vdots\\\\\n 0\\\\\n 5000\\\\\n 0\\\\\n 6000\\\\\n 0\\\\\n \\vdots\\\\\n 0\n \\end{bmatrix}\n\\end{equation}\n 1. The forces are measured in Newton (N), with an accuracy of $\\pm$ 0.005N. What is the upper bound of the relative error in the right-hand side, in the 1-norm?\n 2. Suppose that you want the solution to be computed with a relative error no larger than 1%, using the 1-norm. Can that be guaranteed in this case?\n 3. What would be the upper bound of the relative error in the solution if the condition number was ca. $10^6$?\n\n8. In what situations will you get a shorter execution time by using LU-factorization? Express the time gain as a formula in terms of suitable parameters.\n\n9. The lab session for this course module contains an example concerning a diving board. In that application, the mathematical model after discretization is a system of linear equations where the coefficient matrix has a band structure. In addition, the matrix has further properties that make pivoting unnecessary. This is a very common situation in computer simulations. In such cases,the system of equations can be solved much faster if the band structure is taken advantage of. You should now investigate this in detail for the special case of a tridiagonal matrix A, assuming that pivoting is not required. An efficient implementation of Gaussian elimination for this case should make use of the fact that most of the elements in the lower triangle of A are already zero. Sketch a psuedo code for how to LU-factorize A when the tri-diagonal structure is taken into account. You can follow the lecture note or look up for the Thomas algorithm.\n\n10. Show that by using the algorithm from the previous exercise, you will only need ca. $3n$ floating point operations to LU-factorize the tri-diagonal matrix $A$.\n\n11. We now consider the general case, where $A$ is a full $n\\times n$ matrix. Make your own, efficient implementation of LU-factorization with partial pivoting, in such a way that no explicit swapping of rows takes place. Use the integer vector piv to keep track of the ordering of the rows. Sketch your algorithm in pseudo code.\n", "meta": {"hexsha": "ce258a6e56199bf95d33b8ad08bf503efbd06683", "size": 9393, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Workouts/Workout1.ipynb", "max_stars_repo_name": "enigne/ScientificComputingBridging", "max_stars_repo_head_hexsha": "920f3c9688ae0e7d17cffce5763289864b9cac80", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-05-04T01:15:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-08T15:08:27.000Z", "max_issues_repo_path": "Workouts/Workout1.ipynb", "max_issues_repo_name": "enigne/ScientificComputingBridging", "max_issues_repo_head_hexsha": "920f3c9688ae0e7d17cffce5763289864b9cac80", "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": "Workouts/Workout1.ipynb", "max_forks_repo_name": "enigne/ScientificComputingBridging", "max_forks_repo_head_hexsha": "920f3c9688ae0e7d17cffce5763289864b9cac80", "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.8426573427, "max_line_length": 953, "alphanum_fraction": 0.5809645481, "converted": true, "num_tokens": 1501, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.952574129515172, "lm_q2_score": 0.9362850101927077, "lm_q1q2_score": 0.8918808785624225}} {"text": "# Homework 17\n## Symbolic math\n\n### Problem 1\n#### Part a\n\nImport the library needed for using symbolic math in python. Also setup the notebook for printing.\n\n\n```python\n\n```\n\n#### Part b\nSet variables x, y, z, and function f, and g.\n\n\n```python\n\n```\n\n#### Part c\n\nSet an expression for the following: $$x^2+2x-5.$$\n\n\n\n```python\n\n```\n\n #### Part d\n \nEvaluate the expression for $x=1.5$. Also, make a variable substitution: $z$ for $x$. Do a variable substitution $y^2$ for x. \n\n\n```python\n\n```\n\n### Problem 2\n#### Part a\n\nSimplify the following expression:\n$$\\frac{x^2 - x - 6}{x^2-3x}.$$\n\n\n```python\n\n```\n\n#### Part b\n\nExpand the following expression symbolically: $$(x+1)^3(x-2)^2.$$\n\n\n```python\n\n```\n\n#### Part c\nFactor the following expression: $$3x^4 - 36x^3+99x^2-6x-144.$$\n\n\n```python\n\n```\n\n### Problem 3\n#### Part a\nCompute the symbolic derivative: $$\\frac{d}{dx}\\sin^2(x)e^{2x}.$$\nThen evaluate the resulting expression for $x=3.3.$\n\n\n```python\n\n```\n\n#### Part b\nCreate a sympy expression representing the following integral:\n$$\\int_0^5x^2\\sin(x^2)dx.$$\n\nThen evaluate the integral symbolically.\n\n\n```python\n\n```\n\n### Problem 4\n#### Part a\nSolve for the roots of the following equation: $$x^3+15x^2=3x-10.$$\nUse the ```Eq``` and ```solve``` functions and save as an expression. Show the expression (it will be a list). Then find the numerical value of each root using the evalf function. You can use evalf on some expression using ```my_expression.evalf()```.\n\n\n```python\n\n```\n\n#### Part b\nSolve the system of three equations in three unknowns symbolically:\n\\begin{align}\nx+y+z&=0 \\\\\n2x-y-z&=10 \\\\\ny+2z&=5\n\\end{align}\nCompare the result to the answer computed with fsolve from scipy.optimize.\n\n\n```python\n\n```\n\n#### Part c\nSolve the following differential equation symbolically using the ```dsolve``` function:\n$$\\frac{df(x)}{dx} = x\\cos(x).$$\n\n\n```python\n\n```\n\n### Problem 5\n#### Part a\nFor the system $Ax=b$ with\n$$ A = \\left[\\begin{matrix}\n1 & 2 & 5 \\\\\n3 & 4 & 6 \\\\\n-1 & 0 & 3\n\\end{matrix}\\right],$$\n$$b = \\left[\\begin{matrix}\n1 \\\\\n0 \\\\\n-2\n\\end{matrix}\\right].$$\nSetup the matrices $A$ and $b$\n\n\n\n```python\n\n```\n\n#### Part b\nFor the system in Part a, solve for matrix $x$ by matrix algebra.\n\n\n```python\n\n```\n\n#### Part c\n\nFor matrix A above, return the middle row, and the middle column.\n\n\n```python\n\n```\n\n#### Part d\nCreate a matrix $M$ using the ```zeros``` function that has 2 rows and 2 columns. Fill in some values using array notation (like M[i,j]=value).\n\n\n```python\n\n```\n", "meta": {"hexsha": "9c185111b730eddd655eab478908aa9914b093d6", "size": 6688, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "python/HW17.ipynb", "max_stars_repo_name": "uw-cheme375/uw-cheme375.github.io", "max_stars_repo_head_hexsha": "5b20393705c4640a9e6af89708730eb08cb15ded", "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": "python/HW17.ipynb", "max_issues_repo_name": "uw-cheme375/uw-cheme375.github.io", "max_issues_repo_head_hexsha": "5b20393705c4640a9e6af89708730eb08cb15ded", "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": "python/HW17.ipynb", "max_forks_repo_name": "uw-cheme375/uw-cheme375.github.io", "max_forks_repo_head_hexsha": "5b20393705c4640a9e6af89708730eb08cb15ded", "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": 20.0239520958, "max_line_length": 257, "alphanum_fraction": 0.4959629187, "converted": true, "num_tokens": 755, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9390248140158417, "lm_q2_score": 0.9496693723881865, "lm_q1q2_score": 0.8917631057833579}} {"text": "# Linear least square fitting\n\nIn the lectures we looked at linear least square approximat to a linear fit. In this notebook we extend that general polynomial fits and then to general linear fits. This will involve simultaneous linear equations which we solve via matrix methods.\n\nA model a linear if the parameters are independent of each other, i.e., \n\n$$f(x, \\vec{\\beta}) = \\beta_0 x + \\beta_1 \\sin(x) $$\n\nis a linear model whereas\n\n$$f(x, \\vec{\\beta}) = \\beta_0[x + \\beta_1\\sin(x)] $$\n\nis a non-linear model due to the product $\\beta_0 \\beta_1$. In this notebook we will only look at fitting data linear with models.\n\n## Setup and overview\n\nFor all the following algorithms let $(x_i,y_i)$ with $i=1\\dots n$ be the data we want to fit to. Let the *residual* at each data point be given by \n\n$$ r_i = f(x_i,\\vec{\\beta}) - y_i $$\n\n\nThe goal is to vary $\\vec{\\beta}$ in order to minimize the sum of the squares of the residuals, i.e., we want to minimize, $S$, where\n\n$$ S(\\vec{\\beta}) = \\sum_{i=1}^n r_i^2 $$\n\nAs usual to find the minimize a function we find where the tangent(s) of the function are equal to zero.\n\n## A quadratic example\n\nLet's extend the linear model given in the notes to a quadratic model. Let our model be given by\n\n$$ f(x, \\vec{\\beta}) = \\beta_1 x + \\beta_2 x^2$$\n\nIn this case\n\n$$\n\\begin{align}\n\\frac{\\partial S}{\\partial \\beta_1} &= \\sum_{i=1}^n 2(\\beta_1 x_i +\\beta_2 x_i^2 - y_i) x_i = 0 \\\\\n\\frac{\\partial S}{\\partial \\beta_2} &= \\sum_{i=1}^n 2(\\beta_1 x_i +\\beta_2 x_i^2 - y_i) x_i^2 =0\n\\end{align}\n$$\n\nWe can re-write this as matrix equation:\n\n$$\n\\begin{bmatrix}\\sum_{i=1}^n x_i^2 & \\sum_{i=1}^n x_i^3 \\\\ \\sum_{i=1}^n x_i^3 & \\sum_{i=1}^n x_i^4\\end{bmatrix}\\begin{bmatrix}\\beta_1 \\\\ \\beta_2 \\end{bmatrix} = \\begin{bmatrix} \\sum_{i=1}^n y_i x_i \\\\ \\sum_{i=1}^n y_i x_i^2 \\end{bmatrix}\n$$\n\nWriting this as a matrix equation in the form $X \\vec{\\beta} = \\vec{\\alpha}$ we can find the best fit parameters via $\\vec{\\beta} = X^{-1}\\vec{\\alpha}$.\n\nLet's see this in action in the code\n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom numpy import linalg as la\n```\n\n\n```python\n# The below two lines set the default size and font size for matplotlib\nplt.rcParams['figure.figsize'] = (16.0, 10.0)\nplt.rcParams.update({'font.size': 22})\n```\n\nFirst let's prepare some data to test the algorithm on\n\n\n```python\nx = np.linspace(-4,4,100)\n\na = 3;\nb = -2\n\ny = a*x**2 + b*x\n```\n\nNext prepare the matrix $X$ and vector, $\\vec{\\alpha}$\n\n\n```python\nX = np.sum(np.array([[x**4, x**3],[x**3, x**2]]),2)\nalpha = np.sum(np.array([y*x**2, y*x]),1)\n```\n\nNow solve for $\\vec{\\beta}$\n\n\n```python\nla.inv(X)@alpha\n```\n\n\n\n\n array([ 3., -2.])\n\n\n\nThe algorithm worked! We recoved the coefficients $a$ and $b$.\n\n## Fitting to a polynomial\n\nNow let's generalize to fitting data using an $n^{th}$-order polynomial. By making the natural extension of above we have\n\n$$ f(x,\\vec{\\beta}) = \\beta_0 + \\beta_1 x + \\beta_2 x^2 +\\dots + \\beta_n x^n$$\n\nThe $(n+1)\\times(n+1)$ system ofequations we have to solve is now given by\n\n$$\\begin{bmatrix}\nX_0 & X_1 & \\cdots & X_n \\\\\nX_1 & X_2 & \\cdots & X_{n+1} \\\\\n\\vdots & & & \\vdots \\\\\nX_n & X_{n+1} & \\cdots & X_{2n}\n\\end{bmatrix}\n\\begin{bmatrix} \\beta_0 \\\\ \\beta_1 \\\\ \\cdots \\\\ \\beta_n \\end{bmatrix} = \n\\begin{bmatrix} \\alpha_0 \\\\ \\alpha_1 \\\\ \\cdots \\\\ \\alpha_n \\end{bmatrix}\n$$\n\nwhere $$\n\\begin{align}\nX_n &= \\sum_{i=1}^n x_i^n \\\\\n\\alpha_n &= \\sum_{i=1}^n y_i x_i^n\n\\end{align}\n$$\n\nLet's now write a function that implements this algorithm\n\n\n```python\ndef PolynomialFit(xi, yi, n):\n X = np.zeros((n+1, n+1))\n alpha = np.zeros(n+1)\n\n for i in range(0,n+1):\n alpha[i] = np.sum(yi*xi**i)\n for j in range(0,n+1):\n X[i,j] = np.sum(xi**(i+j))\n\n return la.inv(X)@alpha\n```\n\nLet's make some data to test the function on\n\n\n```python\nxi = np.linspace(-4,4,100)\nyi = 9 - 9*xi -xi**2 + x**3\n```\n\n\n```python\nPolynomialFit(xi,yi, 3)\n```\n\n\n\n\n array([ 9., -9., -1., 1.])\n\n\n\nFor this smooth data we recover precisely the coefficients of the cubic. Let's look at fitting some noisy data and plotting the result. First let's generate some noisy data and the fit to it.\n\n\n```python\nyiNoisy = yi + 10*np.random.random(xi.size)\n\ncubicFitCoeffs = PolynomialFit(xi, yiNoisy, 3)\n\ncubicFit = cubicFitCoeffs[0] + cubicFitCoeffs[1]*xi + cubicFitCoeffs[2]*xi**2 + cubicFitCoeffs[3]*xi**3\n```\n\n\n```python\nplt.grid(True)\nplt.scatter(xi,yiNoisy);\nplt.plot(xi, cubicFit, 'r');\n```\n\n## Fitting to a general linear model\n\nIf we have a general linear model we can still perform fits. We wont derive the algorithm below but it is a generalization of the above methods. Instead we will just state it and show it in action.\n\n$$ f(x, \\vec{\\beta}) = \\beta_0 \\phi_0(x) + \\beta_1 \\phi_1(x) + \\dots + \\beta_n \\phi_n(x) $$\n\nThen we can define the elements of a matrix $X$ via\n\n$$ X_{ij} = \\phi_j(x_i) $$\n\nThen the coefficients in the fit can be calculated via\n\n$$ \\vec{\\beta} = (X^T X)^{-1} X^T \\vec{y} $$\n\nwhere $\\vec{y}$ is the $y$-values of the data.\n\n### Example\n\nLet's look at the example where the data is given by\n\n$$ y_i = 5\\sin(x_i) - x + 4$$\n\nIn this case $\\phi_0 = \\sin(x)$, $\\phi_1 = x$ and $\\phi_2 = 4$. Let's now define the matrix $X$ and the vector $\\vec{y}$.\n\n\n```python\nxi = np.linspace(-4,4,100)\nyi = 5*np.sin(xi) - xi + 4\n\nX = np.array([np.sin(xi), xi, 4*np.ones(xi.size)]).T\n\n```\n\nApplying the formula abovr we recover the coefficients:\n\n\n```python\nla.inv(X.T@X)@X.T@yi\n```\n\n\n\n\n array([ 5., -1., 1.])\n\n\n\nLet's look at a noise data version\n\n\n```python\nyiNoisy = 5*np.sin(xi) - xi + 5*np.random.rand(xi.size)\n\nfitCoeffs = la.inv(X.T@X)@X.T@yiNoisy\n\nfit = fitCoeffs[0]*np.sin(xi) + fitCoeffs[1]*xi + fitCoeffs[2]*4\n\nprint(fitCoeffs)\n```\n\n [ 5.1905638 -0.950227 0.64035906]\n\n\n\n```python\nplt.scatter(xi, yiNoisy)\nplt.grid(True)\nplt.plot(xi, fit, 'r');\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "9daf04e45087331ed27ab9c734965dfff4981a28", "size": 96978, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "InterestingExamples/LinearLeastSquares.ipynb", "max_stars_repo_name": "gerryb123/nielsexamples", "max_stars_repo_head_hexsha": "ca1247475d94a0fcdf07ee4b37b58b70c69ca207", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13, "max_stars_repo_stars_event_min_datetime": "2020-02-15T21:30:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-21T12:03:13.000Z", "max_issues_repo_path": "InterestingExamples/LinearLeastSquares.ipynb", "max_issues_repo_name": "gerryb123/nielsexamples", "max_issues_repo_head_hexsha": "ca1247475d94a0fcdf07ee4b37b58b70c69ca207", "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": "InterestingExamples/LinearLeastSquares.ipynb", "max_forks_repo_name": "gerryb123/nielsexamples", "max_forks_repo_head_hexsha": "ca1247475d94a0fcdf07ee4b37b58b70c69ca207", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 24, "max_forks_repo_forks_event_min_datetime": "2020-02-13T14:27:47.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-05T14:17:10.000Z", "avg_line_length": 221.9176201373, "max_line_length": 44280, "alphanum_fraction": 0.914073295, "converted": true, "num_tokens": 2017, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.953966096291997, "lm_q2_score": 0.93439516117075, "lm_q1q2_score": 0.8913813042961918}} {"text": "# Solving Linear Equations\n\n\n```python\nimport numpy as np\nimport scipy.linalg as la\n```\n\n## Linear Equations\n\nConsider a set of $m$ linear equations in $n$ unknowns:\n\n\\begin{align*}\na_{11} x_1 + &a_{12} x_2& +& ... + &a_{1n} x_n &=& b_1\\\\\n\\vdots && &&\\vdots &= &\\vdots\\\\\na_{m1} x_1 + &a_{m2} x_2& +& ... + &a_{mn} x_n &=&b_m \n\\end{align*}\n\nWe can let\n\n\\begin{align*}\n A=\\left[\\begin{matrix}a_{11}&\\cdots&a_{1n}\\\\\n \\vdots & &\\vdots\\\\\n a_{m1}&\\cdots&a_{mn}\\end{matrix}\\right]\n\\end{align*}\n\n\\begin{align*}\nx = \\left[\\begin{matrix}x_1\\\\\n \\vdots\\\\\n x_n\\end{matrix}\\right] & \\;\\;\\;\\;\\textrm{ and } &\nb = \\left[\\begin{matrix}b_1\\\\\n \\vdots\\\\\n b_m\\end{matrix}\\right]\n\\end{align*}\n\nand re-write the system\n \n$$ Ax = b$$\n\n### Linear independence and existence of solutions\n\n* If $A$ is an $m\\times n$ matrix and $m>n$, if all $m$ rows are linearly independent, then the system is *overdetermined* and *inconsistent*. The system cannot be solved exactly. This is the usual case in data analysis, and why least squares is so important. For example, we may be finding the parameters of a linear model, where there are $m$ data points and $n$ parameters.\n \n* If $A$ is an $m\\times n$ matrix and $m n$, $m = n$ and $m < n$ and provide some intuition as to the existence of a no, unique or infinite solutions.\n\n## LU Decomposition\n\nLU stands for 'Lower Upper', and so an LU decomposition of a matrix $A$ is a decomposition so that \n$$A= LU$$\nwhere $L$ is lower triangular and $U$ is upper triangular.\n\nNow, LU decomposition is essentially gaussian elimination, but we work only with the matrix $A$ (as opposed to the augmented matrix). \n\nGaussian elimination is all fine when we are solving a system one time, for one outcome $b$. Many applications involve solutions to multiple problems, where the left-hand-side of our matrix equation does not change, but there are many outcome vectors $b$. In this case, it is more efficient to *decompose* $A$.\n\nFirst, we start just as in ge, but we 'keep track' of the various multiples required to eliminate entries. For example, consider the matrix\n\n$$A = \\left(\\begin{matrix} 1 & 3 & 4 \\\\\n 2 & 1 & 3\\\\\n 4 & 7 & 2\n \\end{matrix}\\right)$$\n\nWe need to multiply row $1$ by $2$ and subtract from row $2$ to eliminate the first entry in row $2$, and then multiply row $1$ by $4$ and subtract from row $3$. Instead of entering zeroes into the first entries of rows $2$ and $3$, we record the multiples required for their elimination, as so:\n\n$$\\left(\\begin{matrix} 1 & 3 & 4 \\\\\n (2)& -5 & -5\\\\\n (4)&-5 &-14\n \\end{matrix}\\right)$$\n \n\nAnd then we eliminate the second entry in the third row:\n\n\n$$\\left(\\begin{matrix} 1 & 3 & 4 \\\\\n (2)& -5 & -5\\\\\n (4)& (1)&-9\n \\end{matrix}\\right)$$\n \nAnd now we have the decomposition:\n$$L= \\left(\\begin{matrix} 1 & 0 & 0 \\\\\n 2& 1 & 0\\\\\n 4& 1 &1\n \\end{matrix}\\right) \\,\n U = \\left(\\begin{matrix} 1 & 3 & 4 \\\\\n 0& -5 & -5\\\\\n 0&0&-9\n \\end{matrix}\\right)$$\n\n### Elementary matrices\n\nWhy does the algorithm for LU work? Gaussian elimination consists of 3 elementary operations\n\n- Op1: swapping two rows\n- Op2: replace a row by the sum of that row and a multiple of another\n- Op3: multiplying a row by a non-zero scalar\n\nThese can be recast as matrix operations - in particular, pre-multiplication with corresponding elementary matrices.\n\n- Op1: swapping two rows uses a permutation matrix\n\n$$\n\\begin{bmatrix}\n0 & 1 \\\\\n1 & 0 \n\\end{bmatrix}\\begin{bmatrix}\n3 & 4 \\\\\n1 & 2 \n\\end{bmatrix} = \\begin{bmatrix}\n1 & 2 \\\\\n3 & 4 \n\\end{bmatrix}\n$$\n\n- Op2: replace a row by the sum of that row and a multiple of another uses an lower triangular matrix\n\n$$\n\\begin{bmatrix}\n1 & 0 \\\\\n-3 & 1 \n\\end{bmatrix}\\begin{bmatrix}\n1 & 2 \\\\\n3 & 4 \n\\end{bmatrix} = \\begin{bmatrix}\n1 & 2 \\\\\n0 & -2 \n\\end{bmatrix}\n$$\n\nNote: The inverse operation just substitutes the negative of the multiple, and is also lower triangular.\n\n- Op3: multiplying a row by a non-zero scalar uses an lower triangular matrix\n\n$$\n\\begin{bmatrix}\n1 & 0 \\\\\n0 & -0.5 \n\\end{bmatrix}\\begin{bmatrix}\n1 & 2 \\\\\n0 & -2 \n\\end{bmatrix} = \\begin{bmatrix}\n1 & 2 \\\\\n0 & 1 \n\\end{bmatrix}\n$$\n\nNote: The inverse operation just substitutes the inverse of the scalar, and is also lower triangular.\n\nMultiplying an upper triangular matrix by another lower triangular matrix gives an lower triangular matrix. Hence if we put the permutations aside (i.e. keep a separate permutation matrix), Gaussian elimination can be expressed as a product of lower triangular matrices, which is just another lower triangular matrix $L$, with the original matrix $A$ to give an upper triangular matrix $U$. The lower triangular matrix $L$ is then the product of the inverse operations.\n\n\n```python\nA = np.array([\n [1,3,4],\n [2,1,3],\n [4,7,2]\n])\n```\n\n\n```python\nA\n```\n\n\n\n\n array([[1, 3, 4],\n [2, 1, 3],\n [4, 7, 2]])\n\n\n\n#### Construct U\n\n\n```python\nb1 = np.array([\n [1, 0, 0],\n [-2, 1, 0],\n [0, 0, 1]\n])\n```\n\n\n```python\nb2 = np.array([\n [1, 0, 0],\n [0, 1, 0],\n [-4, 0, 1]\n])\n```\n\n\n```python\nb3 = np.array([\n [1, 0, 0],\n [0, 1, 0],\n [0, -1, 1]\n])\n```\n\n\n```python\nb1 @ A\n```\n\n\n\n\n array([[ 1, 3, 4],\n [ 0, -5, -5],\n [ 4, 7, 2]])\n\n\n\n\n```python\nb2 @ b1 @ A\n```\n\n\n\n\n array([[ 1, 3, 4],\n [ 0, -5, -5],\n [ 0, -5, -14]])\n\n\n\n\n```python\nb3 @ b2 @ b1 @ A\n```\n\n\n\n\n array([[ 1, 3, 4],\n [ 0, -5, -5],\n [ 0, 0, -9]])\n\n\n\n\n```python\nU = b3 @ b2 @ b1 @ A\nU\n```\n\n\n\n\n array([[ 1, 3, 4],\n [ 0, -5, -5],\n [ 0, 0, -9]])\n\n\n\n#### Construct L\n\n\n```python\nib1 = np.array([\n [1, 0, 0],\n [2, 1, 0],\n [0, 0, 1]\n])\n```\n\n\n```python\nib2 = np.array([\n [1, 0, 0],\n [0, 1, 0],\n [4, 0, 1]\n])\n```\n\n\n```python\nib3 = np.array([\n [1, 0, 0],\n [0, 1, 0],\n [0, 1, 1]\n])\n```\n\n\n```python\nL = ib1 @ ib2 @ ib3\nL\n```\n\n\n\n\n array([[1, 0, 0],\n [2, 1, 0],\n [4, 1, 1]])\n\n\n\n#### A is factorized into LU\n\n\n```python\nL @ U\n```\n\n\n\n\n array([[1, 3, 4],\n [2, 1, 3],\n [4, 7, 2]])\n\n\n\n\n```python\nA\n```\n\n\n\n\n array([[1, 3, 4],\n [2, 1, 3],\n [4, 7, 2]])\n\n\n\nWe can now use the LU decomposition to solve for *any* $b$ without having to perform Gaussian elimination again. \n\n- First solve $Ly = b$\n- Then solve $Ux = y$\n\nSince $L$ and $U$ are triangular, they can be cheaply solved by substitution.\n\n\n```python\nb\n```\n\n\n\n\n array([[1],\n [2],\n [3]])\n\n\n\n\n```python\ny = la.solve_triangular(L, b, lower=True)\ny\n```\n\n\n\n\n array([[ 1.],\n [ 0.],\n [-1.]])\n\n\n\n\n```python\nx = la.solve_triangular(U, y)\nx\n```\n\n\n\n\n array([[ 0.88888889],\n [-0.11111111],\n [ 0.11111111]])\n\n\n\n### LDU Decomposition\n\nNote that $L$ is a unit triangular matrix while $U$ is not. It is sometimes instructive to factorize $A = LDU$ where both $L$ and $U$ are unit triangular, and $D$ is a diagonal matrix.\n\n\n```python\nU\n```\n\n\n\n\n array([[ 1, 3, 4],\n [ 0, -5, -5],\n [ 0, 0, -9]])\n\n\n\n\n```python\nD = np.diag(np.diag(U))\nD\n```\n\n\n\n\n array([[ 1, 0, 0],\n [ 0, -5, 0],\n [ 0, 0, -9]])\n\n\n\nThe next step is just element-wise division.\n\n\n```python\nU1 = U/np.diag(U)[:, None]\nU1\n```\n\n\n\n\n array([[ 1., 3., 4.],\n [-0., 1., 1.],\n [-0., -0., 1.]])\n\n\n\n\n```python\nD @ U1\n```\n\n\n\n\n array([[ 1., 3., 4.],\n [ 0., -5., -5.],\n [ 0., 0., -9.]])\n\n\n\n\n```python\nnp.allclose(A, L @ D @ U1)\n```\n\n\n\n\n True\n\n\n\n### LU Decomposition in practice\n\n\n```python\nP, L, U = la.lu(A)\n```\n\n\n```python\nL\n```\n\n\n\n\n array([[ 1. , 0. , 0. ],\n [ 0.5 , 1. , 0. ],\n [ 0.25, -0.5 , 1. ]])\n\n\n\n\n```python\nU\n```\n\n\n\n\n array([[ 4. , 7. , 2. ],\n [ 0. , -2.5, 2. ],\n [ 0. , 0. , 4.5]])\n\n\n\nP is a permutation matrix.\n\n\n```python\nP\n```\n\n\n\n\n array([[0., 0., 1.],\n [0., 1., 0.],\n [1., 0., 0.]])\n\n\n\nIn practice, we can store both L and U in a single matrix LU.\n\n\n```python\nLU, P = la.lu_factor(A)\n```\n\n\n```python\nLU\n```\n\n\n```python\nla.lu_solve((LU, P), b)\n```\n\n## Cholesky Decomposition\n\nRecall that a square matrix $A$ is positive definite if\n\n$$u^TA u > 0$$\n\nfor any non-zero n-dimensional vector $u$,\n\nand a symmetric, positive-definite matrix $A$ is a positive-definite matrix such that\n\n$$A = A^T$$\n\nFor a positive definite square matrix, all the pivots (diagonal elements of $U$) are positive. If the matrix is also symmetric, then we must have an $LDU$ decomposition of the form $LDL^T$, where all the diagonal elements of $D$ are positive. Given this, $D^{1/2}$ is well-defined, and we have\n\n$$\nA = LDL^T = LD^{1/2}D^{1/2}L^T = LD^{1/2}(LD^{1/2})^T = CC^{T}\n$$\n\nwhere $C$ is lower-triangular with positive diagonal elements and $C^T$ is its transpose. This decomposition is known as the Cholesky decomposition, and $C$ may be interpreted as the 'square root' of the matrix $A$. \n\n### Algorithm\n\nLet $A$ be an $n\\times n$ matrix. We find the matrix $L$ using the following iterative procedure:\n\n\n$$A = \\left(\\begin{matrix}a_{11}&A_{12}\\\\A_{12}&A_{22}\\end{matrix}\\right) =\n\\left(\\begin{matrix}\\ell_{11}&0\\\\\nL_{12}&L_{22}\\end{matrix}\\right)\n\\left(\\begin{matrix}\\ell_{11}&L_{12}\\\\0&L_{22}\\end{matrix}\\right)\n$$\n\n1.) Let $\\ell_{11} = \\sqrt{a_{11}}$\n\n2.) $L_{12} = \\frac{1}{\\ell_{11}}A_{12}$\n\n3.) Solve $A_{22} - L_{12}L_{12}^T = L_{22}L_{22}^T$ for $L_{22}$\n\n### Example\n\n$$A = \\left(\\begin{matrix}1&3&5\\\\3&13&23\\\\5&23&42\\end{matrix}\\right)$$\n\n$$\\ell_{11} = \\sqrt{a_{11}} = 1$$\n\n$$L_{12} = \\frac{1}{\\ell_{11}} A_{12} = A_{12}$$\n\n$\\begin{eqnarray*}\nA_{22} - L_{12}L_{12}^T &=& \\left(\\begin{matrix}13&23\\\\23&42\\end{matrix}\\right) - \\left(\\begin{matrix}9&15\\\\15&25\\end{matrix}\\right)\\\\\n&=& \\left(\\begin{matrix}4&8\\\\8&17\\end{matrix}\\right)\n\\end{eqnarray*}$\n\nThis is also symmetric and positive definite, and can be solved by another iteration\n\n$\\begin{eqnarray*}\n&=& \\left(\\begin{matrix}2&0\\\\4&\\ell_{33}\\end{matrix}\\right) \\left(\\begin{matrix}2&4\\\\0&\\ell_{33}\\end{matrix}\\right)\\\\\n&=& \\left(\\begin{matrix}4&8\\\\8&16+\\ell_{33}^2\\end{matrix}\\right)\n\\end{eqnarray*}$\n\nAnd so we conclude that $\\ell_{33}=1$.\n\n\nThis yields the decomposition:\n\n\n$$\\left(\\begin{matrix}1&3&5\\\\3&13&23\\\\5&23&42\\end{matrix}\\right) = \n\\left(\\begin{matrix}1&0&0\\\\3&2&0\\\\5&4&1\\end{matrix}\\right)\\left(\\begin{matrix}1&3&5\\\\0&2&4\\\\0&0&1\\end{matrix}\\right)$$\n\n\n\n\n```python\nA = np.array([\n [1,3,5],\n [3,13,23],\n [5,23,42]\n])\n```\n\n\n```python\nC = la.cholesky(A)\nC\n```\n\n\n\n\n array([[1., 3., 5.],\n [0., 2., 4.],\n [0., 0., 1.]])\n\n\n\n\n```python\nC1 = la.cho_factor(A)\nC1\n```\n\n\n\n\n (array([[ 1., 3., 5.],\n [ 3., 2., 4.],\n [ 5., 23., 1.]]), False)\n\n\n\n\n```python\nC1 = la.cho_factor(A)\nla.cho_solve(C1, b)\n```\n", "meta": {"hexsha": "ce09ac0bf8a0eed31311482ebe89f91f313c46d2", "size": 32264, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/copies/lectures/T028B_Sovling_Linear_Equations.ipynb", "max_stars_repo_name": "robkravec/sta-663-2021", "max_stars_repo_head_hexsha": "4dc8018f7b172eaf81da9edc33174768ff157939", "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/copies/lectures/T028B_Sovling_Linear_Equations.ipynb", "max_issues_repo_name": "robkravec/sta-663-2021", "max_issues_repo_head_hexsha": "4dc8018f7b172eaf81da9edc33174768ff157939", "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/copies/lectures/T028B_Sovling_Linear_Equations.ipynb", "max_forks_repo_name": "robkravec/sta-663-2021", "max_forks_repo_head_hexsha": "4dc8018f7b172eaf81da9edc33174768ff157939", "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.4239212718, "max_line_length": 475, "alphanum_fraction": 0.4601723283, "converted": true, "num_tokens": 5706, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632234212403, "lm_q2_score": 0.9362850066369693, "lm_q1q2_score": 0.891215264458443}} {"text": "### Algebraic definition\n\nA set G equipped with operation $\\bullet$\n\n> Closure: $\\forall a,b \\in G, a \\bullet b \\in G$ \n>Associativity: $(a \\bullet b) \\bullet c = a \\bullet (b \\bullet c)$ \n>Identity element: $\\exists e \\in G, such \\ that \\ \\forall a \\in G \\ a \\bullet e = a$ \n>Inverse element: $\\forall a \\in G, \\exists a^{-1}, such \\ that \\ a \\bullet a^{-1} = e$\n\nCan be shown, that $e \\bullet a = a$ and $a^{-1} \\bullet a = e$ and inverse and e are unique\n\n**Abelian group**: $\\forall a,b \\in G, a \\bullet b = b \\bullet a$\n\nIf a group is abelian, usually group operation is denoted by + and the identity element by 0\n\nAs usual in algebra are difined Homomorphism, Isomorphism, Endomorphism, Automorphism. In Algebra isomorph groups are deemed the same.\n\ngroup homomorphism $f:G \\to H$ such that $f(g_1 \\bullet g_2) = f(g_1) * f(g_2)$\n\n**kernel** of a homomorphism is defined as the set of elements that get mapped to the identity element in the image.\n\nGroup operation may be viewed as bijection from G to G.\n\n**Subgroup**: if H subset of G, which is closed under group operation and inverse operation. $H \\leq G$, proper subgroup: $H \\lt G$\n\n \n\nFinite groups can be described by **Cayley table**:\n\n$\n\\begin{bmatrix}\n& Elmnts & e & a & b & c \\\\\n& e & e & a & b & c \\\\\n& a & a & a \\bullet a & a \\bullet b & a \\bullet c \\\\\n& b & b & b \\bullet a & b \\bullet b & b \\bullet c \\\\\n& c & c & c \\bullet a & c \\bullet b & c \\bullet c \\\\\n\\end{bmatrix}\n$\n\nGroup can be described by **Presentation of a group**: \n\n$\\langle S \\vert R \\rangle$ where S is set of generators and R is a set of rules\n\nfree group $F_S$ over a given set $S$ consists of all expressions (a.k.a. words, or terms) that can be built from members of S: $\\langle S \\vert \\emptyset \\rangle$\n\n\n\n### Normal Subgroup\n\n**Coset left** (right): if $H \\lt G$, set defined by an element $gH = \\{g \\bullet h : h \\in H\\}$ ($Hg = \\{h \\bullet g : h \\in H\\}$)\n\ncosets form a partitioning of group, any element of a coset is a represantative of the coset. the number of distinct cosets is called index of subgroup. \n\nif $H \\lt G$ then $ index= \\frac {\\vert G \\vert} {\\vert H \\vert} $ . A finite groups of prime size can not have subgroups.\n\nif $\\forall g \\in G : gH = Hg$, then $H$ is said to be a normal subgroup. Subgroups of abelian group are normal.\n\n**Conjugacy class**: $Cl(a)=\\{ b \\in G : \\exists g \\in G \\text{ such that } b = gag^-1\\}$\n\nConjugacy class is an equivalence relation and thus partitions the group. For abelian group $Cl(a) = \\{a\\}$\n\ngroup of **Inner automorphisms**; $Inn(G)$\n>$\\varphi_g: G \\rightarrow G$ such that $\\varphi_g(x)=gxg^-1$ \n> $Inn(AbelianGroup) \\simeq \\{e\\}$ \n>Normal subgoup is preserved by inner automorphisms. \n>kernel of a homomorphism is equal to a normal subgroup\n\n**Quotient group (factor group)**: we can define a group operation on cosets as the following $g_1H*g_2H=(g_1 \\bullet g_2)H$. \n\nIf $H \\vartriangleleft G$ then $G/H$ is a group. ( $G/\\{e\\}=G$ , $G/G=\\{e\\}$ )\n\n \n\n**Direct product**: $G \\times H$ is the ordered pairs $(g,h)$ where $g \\in G$ and $h \\in H$ such that $(g_1,h_1) \\bullet (g_2,h_2) == (g_1 * g_2, h_1*'h_2)$\n\nLet a group $P$ has 2 subgroups $G,H$. \n\n$\nP=G \\times H \n\\Leftrightarrow \n\\begin{cases}\n & G \\cap H == \\{e\\} \\\\ \n & \\text{ every element can be expressed in } g \\bullet h \\\\ \n & G \\text{ comutes with } H \\text{( or stronger:} G \\text{ and } H \\text{ are normal subgroups} \\\\\n\\end{cases}\n$\n\n\n\n\n### Geometric definition\n\n**Transformation group (Group action)** : $\\varphi$ is a function of G on set X\n\n$\\varphi : G \\times X \\rightarrow X:(g,x) \\mapsto \\varphi(g,x) $ where $\\varphi(e,x)=x$, and $\\varphi$ is bijective map.\n\n**symmetric group**: defined over any set is the group whose elements are all the bijections from the set to itself. For finite set of size n, it is $S_n$: all permutations of finite set of size n.\n\n**Cayley's theorem**: every group can be realized as a subgroup of a symmetric group over some set\n\n**Orbit**: Suppose $G$ is a group acting on a set $S$. ${G_{.s}}$ the orbit of $s \\in S$ is defined as $\\{t \\in S \\vert \\exists g \\in G, g.t=s \\}$\n\nThe set of orbits of (points x in) X under the action of G form a partition of X.\n\nA group action is termed **transitive** if it has exactly one orbit: $\\forall x,y \\in S, \\exists g \\in G , g.x = y$\n\n**Stabilizer (isotropy group)**: denoted $Stab_G(s)$, is defined as: $\\{ h \\in G \\mid \\ h.s = s \\} $. \n\nActions of groups on vector spaces are called **representations** of the group \n\nAlternativly a **representation** of a group G on a vector space V is a group homomorphism $\\varphi: G \\rightarrow GL(V,F)$\n\n**General linear group** : $GL(V,F)$ are all matrices over a field $F$, with 0 determinant (invertible).\n> $SL(n, F)$: determinant is 1. In $R^n$ volume and orientation preserving linear transformations \n> $O(n)$: orthogonal matrcies $O^TO=I$. Preserves the dot product of vectors. \n>$SU(n)$: n×n unitary matrices with determinant 1 on $\\mathbb{C}$\n\n\nA **faithful representation** is one in which the homomorphism G → GL(V) is injective; in other words, one whose kernel is the trivial subgroup {e} consisting only of the group's identity element.\n\n\n\n\n\n\n\n\n### examples\n\nsmall groups of order n:\n> n=1, the only group {e} == **trivial group**\n\n> n=2, only one group $Z_2 \\simeq S_2$ \n>> $\n\\begin{bmatrix}\n& & e & a \\\\\n& e & e & a \\\\\n& a & a & e \\\\\n\\end{bmatrix}\n$\n\n> n=3, only one group $Z_3$\n>>$\\begin{bmatrix}\n& & e & a & b \\\\\n& e & e & a & b \\\\\n& a & a & b & e\\\\\n& b & b & e & a\\\\\n\\end{bmatrix}$ \n>> that is $b = a \\bullet a == a^2$\n\n> n=4, two non isomorphic groups\n>> $Z_4$ \n>>>$\\begin{bmatrix}\n& & e & g & g^2 & g^3 \\\\\n& e & e & g & g^2 & g^3 \\\\\n& g & g & g^2 & g^3 & e\\\\\n& g^2 & g^2 & g^3 & e & g\\\\\n& g^3 & g^3 & e & g & g^2\\\\\n\\end{bmatrix}$ \n>> this can be viewed as a group of multiplications of $\\{1, i, -1, -i\\}$ \n>> one proper subgroup $Z_2 \\lt Z_4 : \\{ e, g^2 \\}$ \n>> this subgroup partitions the group to the following cosets: $\\{e, g^2\\}$, $\\{g, g^3\\}$\n\n>> Klein four-group $K_4$: \n>>>$\n\\begin{bmatrix}\n& & e & a & b & c \\\\\n& e & e & a & b & c \\\\\n& a & a & e & c & b \\\\\n& b & b & c & e & a \\\\\n& c & c & b & a & e \\\\\n\\end{bmatrix}\n$\n>> 3 proper subgroups : $\\{ e, a \\},\\{ e, b \\},\\{ e, c \\}$ \n>> $K_4 = Z_2 \\times Z_2 $ and can be presented as $ \\langle a, b \\vert a^2,b^2, ab=ba \\rangle$\n\n\n**symmetric group**: $S_3$\n\n> order of the group is $3!=6$ \n> cycle examples:\n>>$(1,2) == \\begin{pmatrix}\n1 & 2 & 3\\\\ \n2 & 1 & 3\n\\end{pmatrix}$ \n>>$(1,2,3) == \\begin{pmatrix}\n1 & 2 & 3\\\\ \n2 & 3 & 1\n\\end{pmatrix}$ \n> elements (in cycles): { e, (1,2), (1,3), (2,3), (1,2,3), (1,3,2) } \n> first non abelian group: (1,2)(2,3) = (1,2,3) and (2,3)(1,2)=(1,3,2) \n>presentations: $\\langle a, b, c \\vert a^2,b^2, c^3, abc \\rangle$ or $\\langle s_1, s_2 \\vert s_1^2,s_2^2, (s_1s_2)^3 \\rangle$ or $\\langle s, t \\vert s^3,t^2, (st)=ts^2 \\rangle$\n\n> proper subgroups: \n>>$Z_2$: {e,(1,2)}, {e,(1,3)}, {e,(2,3)} \n>> $Z_3$: {e,(1,2,3), (1,3,2)} \n> conjugacy class partitioning\n>> {e} \n>>{ (1,2), (1,3), (2,3) } \n>>{ (1,2,3), (1,3,2) } this is the only normal subgroup\n\n>$Inn(S_3) \\simeq S_3$\n\n**Cyclic group** of order n: $Z_n$ : $\\langle a \\vert a^n \\rangle$, that is one generator and $a^n = e$\n> $Z_n$ is abelian group\n\n> it may be looked as \n>> modulo n arithmetics \n>> rotations by $2\\pi \\frac {m} {n}$\n\n**Free group** of order 1: $F_1: \\langle a \\vert \\emptyset \\rangle$\n> consists of all possible strings of $a$ and $a^{-1}$ reducted by the group identity $a \\bullet a^{-1} = e$ \n> for example $\"aaaaaa\"$ or $\"a^{-1}a^{-1}a^{-1}\"$ \n> $F_1 \\simeq Z$ where $Z$ with + is treated as Cyclic goup\n\n\n## example Dihedral transformation group \n$D_n$ is the group of symmetries of a regular polygon (includes rotations and reflections).\n\nOrbit of a point in $R^2$ is the set of vertexes of a polygon.\n\n$D_n = \\langle r,s \\vert r^n, s^2, (sr)^2 \\rangle$, order of the group = 2n, $D_3 \\simeq S_3$\n\n$(sr)^2=e \\Leftrightarrow srs=r^{-1}$\n\n$r_i==r^i; s_i==r_is \\Rightarrow r_ir_j=r_{i+j}, r_is_j=s_{i+j},s_jr_i=s_{i-j},s_is_j=r_{i-j}$ \n\nnatural represantation in $R^2$: \n$\nr_i=\\begin{pmatrix}\ncos \\frac{2 \\pi i}{n} & -sin \\frac{2 \\pi i}{n}\\\\ \nsin \\frac{2 \\pi i}{n} & cos \\frac{2 \\pi i}{n}\n\\end{pmatrix}\n,\ns_i=\\begin{pmatrix}\ncos \\frac{2 \\pi i}{n} & sin \\frac{2 \\pi i}{n}\\\\ \nsin \\frac{2 \\pi i}{n} & -cos \\frac{2 \\pi i}{n}\n\\end{pmatrix}\n$\n\n$D_4 \\lt O(2)$, $D_4 \\lt SO(3)$\n\n$D_4$: group of symmetries of a square\n\n \n\n> conjucacy classes:\n>> $\\{e\\}$ \n>> $\\{r^2\\}$ rotation by $\\pi$ \n>> $\\{s,s_2\\}$ reflections horisontal and vertical \n>> $\\{s_1,s_3\\}$ diagonal reflections \n>> $\\{r,r^3\\}$ rotations by $\\pi/2$ and $3\\pi/2$\n\n> proper subgroups:\n>> $\\{e,r^2\\}$ Normal subgroup \n>> $\\{e,s\\}$,$\\{e,s_1\\}$,$\\{e,s_2\\}$,$\\{e,s_3\\}$ \n>> $\\{e,s,r^2,r^2s\\}$, $\\{e,rs,r^2,r^3s\\}$ \n>> $\\{e,r,r^2,r^3\\}$ Normal subgroup\n\n> $Inn(D_4) \\simeq K_4$\n\n\n```python\n# some sympy Permutation examples\n\n# this is needed for google.colab\n#from IPython.display import HTML\n#display(HTML(\"\"))\n\nfrom sympy import init_printing\ninit_printing(use_latex='mathjax')\n\nimport sympy.combinatorics.permutations as P\n\np1 = P.Permutation(4)\ndisplay(p1.array_form)\ndisplay(p1) #p1.cyclic_form\nprint('='*50)\n\np1 = P.Permutation(3,1)(0,2,4)\ndisplay(p1.array_form)\ndisplay(p1)\nprint('='*50)\n\np2=p1*p1\ndisplay(p2.array_form)\ndisplay(p2)\nprint('='*50)\n\n```\n\n\n$$\\left [ 0, \\quad 1, \\quad 2, \\quad 3, \\quad 4\\right ]$$\n\n\n\n$$\\left( 4\\right)$$\n\n\n ==================================================\n\n\n\n$$\\left [ 2, \\quad 3, \\quad 4, \\quad 1, \\quad 0\\right ]$$\n\n\n\n$$\\left( 0\\; 2\\; 4\\right)\\left( 1\\; 3\\right)$$\n\n\n ==================================================\n\n\n\n$$\\left [ 4, \\quad 1, \\quad 0, \\quad 3, \\quad 2\\right ]$$\n\n\n\n$$\\left( 0\\; 4\\; 2\\right)$$\n\n\n ==================================================\n\n\n\n```python\np1('abcde')\n```\n\n\n\n\n ['c', 'd', 'e', 'b', 'a']\n\n\n\n\n```python\nimport sympy.combinatorics.generators as G\nd = G.dihedral(4)\nlist(d)\n```\n\n\n\n\n$$\\left [ \\left( 3\\right), \\quad \\left( 0\\; 3\\right)\\left( 1\\; 2\\right), \\quad \\left( 0\\; 1\\; 2\\; 3\\right), \\quad \\left( 1\\; 3\\right), \\quad \\left( 0\\; 2\\right)\\left( 1\\; 3\\right), \\quad \\left( 0\\; 1\\right)\\left( 2\\; 3\\right), \\quad \\left( 0\\; 3\\; 2\\; 1\\right), \\quad \\left( 0\\; 2\\right)\\left( 3\\right)\\right ]$$\n\n\n\n\n```python\n#S3\nfrom sympy.combinatorics.free_groups import free_group, FreeGroup\nimport sympy.combinatorics.fp_groups\nF, a, b = free_group(\"a, b\")\nG = FpGroup(F, [a**2, b**3, (a*b)**4])\nprint(\"Order is:\",G.order())\n#l = sympy.combinatorics.fp_groups.low_index_subgroups(G,2)\n#for t in l:\n# print(t.table)\n```\n\n Order is: 24\n\n\n## Links\n\n[The Group Properties Wiki](https://groupprops.subwiki.org/wiki/Main_Page) \n\n[Magma Computational Algebra System](http://magma.maths.usyd.edu.au/magma/)\n\n[GAP - Groups, Algorithms, Programming -a System for Computational Discrete Algebra](https://www.gap-system.org/)\n\nhttp://www.sagemath.org/\n\n[Handbook of Computational Group Theory. Derek F. Holt, Bettina Eick, Eamonn A. O'Brien](https://books.google.am/books?id=rnTLBQAAQBAJ&source=gbs_book_other_versions)\n\nhttps://docs.sympy.org/latest/modules/combinatorics/perm_groups.html\n\nhttps://people.maths.bris.ac.uk/~matyd/GroupNames/index.html\n\n\n```python\n\n```\n", "meta": {"hexsha": "14163f558b14909503e6c3d2a3149d33b04abbdb", "size": 20153, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Math/IntroToGroups1.ipynb", "max_stars_repo_name": "gate42qc/seminars", "max_stars_repo_head_hexsha": "35ff77b902d9c2ede619fd6e2d9c3e80d20d78de", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2018-12-07T10:02:06.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-24T19:30:03.000Z", "max_issues_repo_path": "Math/IntroToGroups1.ipynb", "max_issues_repo_name": "gate42qc/seminars", "max_issues_repo_head_hexsha": "35ff77b902d9c2ede619fd6e2d9c3e80d20d78de", "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/IntroToGroups1.ipynb", "max_forks_repo_name": "gate42qc/seminars", "max_forks_repo_head_hexsha": "35ff77b902d9c2ede619fd6e2d9c3e80d20d78de", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-08-22T12:07:40.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-22T12:07:40.000Z", "avg_line_length": 32.039745628, "max_line_length": 368, "alphanum_fraction": 0.4874212276, "converted": true, "num_tokens": 4107, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.959762055074521, "lm_q2_score": 0.9284088064979619, "lm_q1q2_score": 0.8910515440737672}} {"text": "# Modeling and Simulation in Python\n\nChapter 9\n\nCopyright 2017 Allen Downey\n\nLicense: [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0)\n\n\n\n```python\n# Configure Jupyter to display the assigned value after an assignment\n%config InteractiveShell.ast_node_interactivity='last_expr_or_assign'\n\n# import everything from SymPy.\nfrom sympy import *\n\n# Set up Jupyter notebook to display math.\ninit_printing() \n```\n\nThe following displays SymPy expressions and provides the option of showing results in LaTeX format.\n\n\n```python\nfrom sympy.printing import latex\n\ndef show(expr, show_latex=False):\n \"\"\"Display a SymPy expression.\n \n expr: SymPy expression\n show_latex: boolean\n \"\"\"\n if show_latex:\n print(latex(expr))\n return expr\n```\n\n### Analysis with SymPy\n\nCreate a symbol for time.\n\n\n```python\nt = symbols('t')\n```\n\nIf you combine symbols and numbers, you get symbolic expressions.\n\n\n```python\nexpr = t + 1\n```\n\nThe result is an `Add` object, which just represents the sum without trying to compute it.\n\n\n```python\ntype(expr)\n```\n\n\n\n\n sympy.core.add.Add\n\n\n\n`subs` can be used to replace a symbol with a number, which allows the addition to proceed.\n\n\n```python\nexpr.subs(t, 2)\n```\n\n`f` is a special class of symbol that represents a function.\n\n\n```python\nf = Function('f')\n```\n\n\n\n\n f\n\n\n\nThe type of `f` is `UndefinedFunction`\n\n\n```python\ntype(f)\n```\n\n\n\n\n sympy.core.function.UndefinedFunction\n\n\n\nSymPy understands that `f(t)` means `f` evaluated at `t`, but it doesn't try to evaluate it yet.\n\n\n```python\nf(t)\n```\n\n`diff` returns a `Derivative` object that represents the time derivative of `f`\n\n\n```python\ndfdt = diff(f(t), t)\n```\n\n\n```python\ntype(dfdt)\n```\n\n\n\n\n sympy.core.function.Derivative\n\n\n\nWe need a symbol for `alpha`\n\n\n```python\nalpha = symbols('alpha')\n```\n\nNow we can write the differential equation for proportional growth.\n\n\n```python\neq1 = Eq(dfdt, alpha*f(t))\n```\n\nAnd use `dsolve` to solve it. The result is the general solution.\n\n\n```python\nsolution_eq = dsolve(eq1)\n```\n\nWe can tell it's a general solution because it contains an unspecified constant, `C1`.\n\nIn this example, finding the particular solution is easy: we just replace `C1` with `p_0`\n\n\n```python\nC1, p_0 = symbols('C1 p_0')\n```\n\n\n```python\nparticular = solution_eq.subs(C1, p_0)\n```\n\nIn the next example, we have to work a little harder to find the particular solution.\n\n### Solving the quadratic growth equation \n\nWe'll use the (r, K) parameterization, so we'll need two more symbols:\n\n\n```python\nr, K = symbols('r K')\n```\n\nNow we can write the differential equation.\n\n\n```python\neq2 = Eq(diff(f(t), t), r * f(t) * (1 - f(t)/K))\n```\n\nAnd solve it.\n\n\n```python\nsolution_eq = dsolve(eq2)\n```\n\nThe result, `solution_eq`, contains `rhs`, which is the right-hand side of the solution.\n\n\n```python\ngeneral = solution_eq.rhs\n```\n\nWe can evaluate the right-hand side at $t=0$\n\n\n```python\nat_0 = general.subs(t, 0)\n```\n\nNow we want to find the value of `C1` that makes `f(0) = p_0`.\n\nSo we'll create the equation `at_0 = p_0` and solve for `C1`. Because this is just an algebraic identity, not a differential equation, we use `solve`, not `dsolve`.\n\nThe result from `solve` is a list of solutions. In this case, [we have reason to expect only one solution](https://en.wikipedia.org/wiki/Picard%E2%80%93Lindel%C3%B6f_theorem), but we still get a list, so we have to use the bracket operator, `[0]`, to select the first one.\n\n\n```python\nsolutions = solve(Eq(at_0, p_0), C1)\ntype(solutions), len(solutions)\n```\n\n\n\n\n (list, 1)\n\n\n\n\n```python\nvalue_of_C1 = solutions[0]\n```\n\nNow in the general solution, we want to replace `C1` with the value of `C1` we just figured out.\n\n\n```python\nparticular = general.subs(C1, value_of_C1)\n```\n\nThe result is complicated, but SymPy provides a method that tries to simplify it.\n\n\n```python\nparticular = simplify(particular)\n```\n\nOften simplicity is in the eye of the beholder, but that's about as simple as this expression gets.\n\nJust to double-check, we can evaluate it at `t=0` and confirm that we get `p_0`\n\n\n```python\nparticular.subs(t, 0)\n```\n\nThis solution is called the [logistic function](https://en.wikipedia.org/wiki/Population_growth#Logistic_equation).\n\nIn some places you'll see it written in a different form:\n\n$f(t) = \\frac{K}{1 + A e^{-rt}}$\n\nwhere $A = (K - p_0) / p_0$.\n\nWe can use SymPy to confirm that these two forms are equivalent. First we represent the alternative version of the logistic function:\n\n\n```python\nA = (K - p_0) / p_0\n```\n\n\n```python\nlogistic = K / (1 + A * exp(-r*t))\n```\n\nTo see whether two expressions are equivalent, we can check whether their difference simplifies to 0.\n\n\n```python\nsimplify(particular - logistic)\n```\n\nThis test only works one way: if SymPy says the difference reduces to 0, the expressions are definitely equivalent (and not just numerically close).\n\nBut if SymPy can't find a way to simplify the result to 0, that doesn't necessarily mean there isn't one. Testing whether two expressions are equivalent is a surprisingly hard problem; in fact, there is no algorithm that can solve it in general.\n\n### Exercises\n\n**Exercise:** Solve the quadratic growth equation using the alternative parameterization\n\n$\\frac{df(t)}{dt} = \\alpha f(t) + \\beta f^2(t) $\n\n\n```python\nalpha, beta = symbols('alpha beta')\n```\n\n\n```python\neq3 = Eq(diff(f(t), t), alpha*f(t) + beta*f(t)**2)\n```\n\n\n```python\nsolution_eq = dsolve(eq3)\n```\n\n\n```python\ngeneral = solution_eq.rhs\n```\n\n\n```python\nat_0 = general.subs(t, 0)\n```\n\n\n```python\nsolutions = solve(Eq(at_0, p_0), C1)\nvalue_of_C1 = solutions[0]\n```\n\n\n```python\nparticular = general.subs(C1, value_of_C1)\nparticular.simplify()\n```\n\n**Exercise:** Use [WolframAlpha](https://www.wolframalpha.com/) to solve the quadratic growth model, using either or both forms of parameterization:\n\n df(t) / dt = alpha f(t) + beta f(t)^2\n\nor\n\n df(t) / dt = r f(t) (1 - f(t)/K)\n\nFind the general solution and also the particular solution where `f(0) = p_0`.\n\n\n```python\n\n```\n", "meta": {"hexsha": "37b2b2cc6b314afbac34e2cb9f3b63b760abcb16", "size": 51418, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/chap09.ipynb", "max_stars_repo_name": "pmalo46/ModSimPy", "max_stars_repo_head_hexsha": "dc5ef44757b59b38215aead6fc4c0d486526c1e5", "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/chap09.ipynb", "max_issues_repo_name": "pmalo46/ModSimPy", "max_issues_repo_head_hexsha": "dc5ef44757b59b38215aead6fc4c0d486526c1e5", "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/chap09.ipynb", "max_forks_repo_name": "pmalo46/ModSimPy", "max_forks_repo_head_hexsha": "dc5ef44757b59b38215aead6fc4c0d486526c1e5", "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.3022026432, "max_line_length": 2224, "alphanum_fraction": 0.7223151426, "converted": true, "num_tokens": 1655, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9664104972521579, "lm_q2_score": 0.9219218337824342, "lm_q1q2_score": 0.8909549378133035}} {"text": "```python\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom scipy.interpolate import interp1d\nfrom typing import List, Tuple\n```\n\n\n```python\ndata = np.array([0.5, -0.32, -0.55, -0.76, -0.07, 0.44, -0.48])\ntheta = np.linspace(-10, 10, 10000)\n```\n\n(a) Let $x_1,...,x_n \\sim DExp(\\theta)$. The contribution of $x_i$ to the likelihood is:\n$$L_i(\\theta) = \\frac{1}{2} e^{|x_i - \\theta|} $$\n\nand the total log-likelihood is:\n\\begin{align}\n\\log L(\\theta) & = \\sum_{i=1}^n \\log L_i(\\theta) \\\\\n& = -n \\log 2 + \\sum_{i=1}^n |x_i - \\theta|\n\\end{align}\n\n\n```python\ndef log_likelihood_double_exp(theta: List[float], data: List[float]) -> List[float]:\n log_like = []\n for th in theta:\n ll = 0\n for dt in data:\n ll += np.abs(dt - th)\n ll *= -np.log(2)\n log_like.append(ll)\n return log_like\n```\n\n\n```python\ndef plot_log_likelihood(theta: List[float], data: List[float]):\n log_like = log_likelihood_double_exp(theta, data)\n plt.plot(theta, log_like)\n plt.title('Double exponential likelihood')\n plt.xlabel(r'$\\theta$')\n plt.ylabel('Log likelihood');\n```\n\n\n```python\nplot_log_likelihood(theta, data)\n```\n\n(b) Then $\\hat{\\theta}$ the MLE of $\\theta$ is given by the solution to the score equation:\n\n\\begin{align}\nS(\\theta) = 0 & = \\frac{\\partial}{\\partial \\theta} \\log L(\\theta) \\\\\n& = \\sum_{i=1}^n sgn |x_i - \\theta| \\\\\n& = median(x)\n\\end{align}\n\nwhere the last statement is due to the following argument: https://math.stackexchange.com/questions/1678740/mle-of-double-exponential.\n\n\n```python\nprint(f\"MLE = {np.median(data)}\")\n```\n\nor alternatively we can use the log-likelihood directly:\n\n\n```python\nlog_like = log_like = log_likelihood_double_exp(theta, data)\nprint(f\"MLE = {np.round(theta[np.argmax(log_like)], 2)}\") \n```\n\nThe likelihood based interval:\n\n\n```python\ndef likelihood_interval(theta: List[float],\n likelihood: List[float],\n cutoff: float) -> Tuple[float, float]:\n # intersection points occur below and above the maximum likelihood estimate\n mle_index = np.argmax(likelihood)\n interp_below_max = interp1d(likelihood[:mle_index], theta[:mle_index])\n interp_above_max = interp1d(likelihood[mle_index:], theta[mle_index :])\n lower_int = np.round(interp_below_max(cutoff).flatten()[0], 2)\n upper_int = np.round(interp_above_max(cutoff).flatten()[0], 2)\n return (lower_int, upper_int)\n```\n\nat a cut-off of:\n\n\n```python\nc = 0.15 # 95% confidence interval\nprint(f'Likelihood interval for c = {c} is {likelihood_interval(theta, np.exp(log_like), c)}') \n```\n\n(c) If the largest value in the data is now 2.5 instead of 0.5:\n\n\n```python\ndata[0] = 2.5\ndata\n```\n\nthen the log-loikelihood function is now:\n\n\n```python\nplot_log_likelihood(theta, data)\n```\n\nDespite the change in the largest value, the inference of the MLE $\\hat{\\theta}$ does not change. This is expected as it is the median of the data which remains unchanged. The median is known to be robust to outliers.\n\n\n```python\nprint(f\"MLE = {np.median(data)}\")\n```\n", "meta": {"hexsha": "7986fb8c679b29d88c2cbf81e551561296881c5f", "size": 5871, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "python/chapter-2/exercises/EX2-13.ipynb", "max_stars_repo_name": "covuworie/in-all-likelihood", "max_stars_repo_head_hexsha": "6638bec8bb4dde7271adb5941d1c66e7fbe12526", "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/chapter-2/exercises/EX2-13.ipynb", "max_issues_repo_name": "covuworie/in-all-likelihood", "max_issues_repo_head_hexsha": "6638bec8bb4dde7271adb5941d1c66e7fbe12526", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-03-24T17:53:04.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-23T20:16:17.000Z", "max_forks_repo_path": "python/chapter-2/exercises/EX2-13.ipynb", "max_forks_repo_name": "covuworie/in-all-likelihood", "max_forks_repo_head_hexsha": "6638bec8bb4dde7271adb5941d1c66e7fbe12526", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-11-21T10:24:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-21T10:24:59.000Z", "avg_line_length": 25.0897435897, "max_line_length": 225, "alphanum_fraction": 0.5295520354, "converted": true, "num_tokens": 868, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750413739076, "lm_q2_score": 0.9343951556900273, "lm_q1q2_score": 0.8907355806999896}} {"text": "# Linear Regression\n\nThis notebook implements linear regression in numpy using the least squares method. Some fitness metrics are also discussed.\n\nSome imports:\n\n\n```python\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport sys\n\nfrom mpl_toolkits.mplot3d import Axes3D\n\nsys.path.append(\"..\")\nfrom models.linear_regression import LinearRegression\n```\n\n\n```python\n%matplotlib inline\n```\n\n## Simple linear regression: One variable\n\nLinear regression is a method that allows to predict the value of a quantitative respone Y on the basis of some predictor variables $\\{X_1, X_2, ..., X_n\\}$. This approach assumes a linear relationship between the response and the predictors. This takes the form:\n\n$$\n\\begin{equation}\nY = \\beta_0 + \\beta_1X_1 + \\beta_2X_2 + ... + \\beta_nX_n,\n\\end{equation}\n$$\n\nwhere $\\beta_0, \\beta_1, ..., \\beta_n$ are unknown parameters. First, we implement a simple version where there is only one variable $X$. This leave us with 2 paremeters, the intercept($\\beta_0$) and the coefficient($\\beta_1$) of the function:\n$$\n\\begin{equation}\nY = \\beta_0 + \\beta_1X\n\\end{equation}\n$$\n\nBased on a training set we produce the estimates $\\hat{\\beta_0}$ and $\\hat{\\beta_1}$ that fit the training data, we can later use them to predict future values of the response $Y$ for new values of $X$ as:\n$$\n\\begin{equation}\n\\hat{y} = \\hat{\\beta_0} + \\hat{\\beta_1}x_i\n\\end{equation}\n$$\n\nIn this notation $\\hat{y}$ is the predicted value of $Y$ for $X = x_i$\n\n### Generate the data\n\nWe are gonna try to interpolate the function $y = 5x + 2$\n\nWe take randomly 20 points in the interval $[0, 5)$, this correspond to our set of training samples $X = \\{x_1, x_2, ..., x_{20}\\}$\n\n\n```python\nsample_size = 20\n\n# Parameters to estimate\nb0 = 2\nb1 = 5\n\n# Standard deviation of the simulated irreducible error\ne = 2\n\n\nx = np.random.random_sample(sample_size)*5\n```\n\nWe compute the dependent variable, $y_i$, mapping with the function and adding some random noise to the data.\n\nWe are using zero mean and two standar deviation normal distributed noise.\n\n\n```python\ny = (b1*x + b0) + e*np.random.randn(sample_size)\n```\n\nLet's check the data we are going to fit\n\n\n```python\nplt.plot(x, y, 'o')\nplt.show()\n```\n\n## Least squares method\n\nNow fit the data using the least squares technique, we are going to estimate parameters $\\hat{\\beta_0}$ and $\\hat{\\beta_1}$ corresponing to the parameters of the line $y = \\beta_0 + \\beta_1x$ that generated the data. The least square method computes the parameters that minimize the residual sum of squares (RSS) defined as:\n$$\n\\text{RSS} = \\sum_{i=1}^n (y_i - \\hat{y}_i)^2\n$$\n\nThe analytic solution of the values of $\\hat{\\beta_0}$ and $\\hat{\\beta_1}$ that minimize the RSS is:\n$$\n\\hat{\\beta_1} = \\frac{\\sum_{i=1}^n (x_i - \\overline{x})(y_i - \\overline{y})}{\\sum_{i=1}^n (x_i - \\overline{x})^2}, \\\\\n\\hat{\\beta_0} = \\overline{y} - \\hat{\\beta_1}\\overline{x}\n$$\n\n\n```python\nsimple_model = LinearRegression()\nb_hat = simple_model.fit(x.reshape(-1, 1), y)\n\nprint(\"Estimated parameters of the linear regression model:\\n\"\n + \"Intercept = \"+str(b_hat[0])+\" \\nCoefficient = \" + str(b_hat[1]))\n```\n\n Estimated parameters of the linear regression model:\n Intercept = 3.390914159450319 \n Coefficient = 4.504515480115419\n\n\n\n```python\n# Plottin rergession line over data\nx_axis = np.linspace(0, 5, 100)\nplt.plot(x, y, 'o')\nplt.plot(x_axis, b1*x_axis + b0, label='True line', color='green')\nplt.plot(x_axis, b_hat[1]*x_axis + b_hat[0], label='Regressed line')\nplt.legend()\nplt.show()\n```\n\nUsing the LinearRegression class:\n\n### Making new predictions\n\nWe can now predict the response for a new value $x_i$ as:\n$$\n\\hat{y_i} = \\hat{\\beta_0} + \\hat{\\beta_1}x_i\n$$\n\n\n```python\nx_test = 2\n\npred_test = b_hat[0] + x_test*b_hat[1]\n\nresult = \"For a test value of x = %.2f, the predicted response is y_hat = %.2f, and the true value is y = %.2f\" % (x_test, pred_test, (b1*x_test + b0))\nprint(result)\n```\n\n For a test value of x = 2.00, the predicted response is y_hat = 12.40, and the true value is y = 12.00\n\n\nWe may also use the predict method:\n\n\n```python\npred_test = simple_model.predict(x_test)\nprint(\"Predicted value: %.2f\" % pred_test)\n```\n\n Predicted value: 12.40\n\n\n## Fitness metrics\n\n### Residual Standard Error of the estimation\n\nThe residual standard error (RSE) is an estimate of the standard deviation of the random error term $\\epsilon$. Typically we dont know $\\epsilon$ and it is considered the irreducible error. However in this case we have generated the data and simulated noise, so $\\epsilon$ can be identified with the added noise. This measure gives an estimation of how much the prediction deviates from the true line in average measured in the units of the respond. The metric is defined as follows \n$$\n\\text{RSE} = \\sqrt{\\frac{1}{n-2}\\sum_{i=1}^n(y_i - \\hat{y}_i)^2},\n$$\nwhere $n$ is the number of samples.\n\n\n```python\nprint(\"Estimated standard error of the model: %.2f\" % simple_model.std_err)\n```\n\n Estimated standard error of the model: 1.52\n\n\nNotice that the output is in units of $y$, so the number on its own does not give much information, it should be considered along with the magnitud of $y$. It is not the same to deviate $2$ units from the true value when this is $y_i = 10000$ than when it is $y_i = 1$. For this reason the RSE has to be interpreted along with the scale of $Y$. To overcome this limitation we can use the $R^2$ Statistic.\n\n### $R^2$ Statistic\n\n\nThe R squared is used to verify how well the model describes the data. This metric is the proportion of variability explained, because it's a proportion it takes values in the range $[0, 1]$ and avoids the problem of being subject to the scale of $Y$. But how can we measure the explained variability? To do this we can exploit a couple concepts. \n\nThe total variance of the response $Y$ can be measured using the total sum of squares (TSS) defined as\n$$\n\\text{TSS} = \\sum_{i=1}^n(y_i - \\overline{y})^2\n$$\n\nBesides, the residual sum of squares (RSS) represents the amount of variability that is left after performing the regression. The R squared statistic is defined as:\n$$\nR^2 = \\frac{\\text{TSS} - \\text{RSS}}{\\text{TSS}} = 1 - \\frac{\\text{RSS}}{\\text{TSS}} = \\frac{\\sum_{i=1}^n (y_i - \\hat{y_i})^2}{\\sum_{i=1}^n(y_i - \\overline{y})^2}\n$$\n\nLooking into our particular case:\n\n\n```python\nprint(\"R squared score of the model: %.5f\" % simple_model.r2)\n```\n\n R squared score of the model: 0.94928\n\n\nIt is actually very good, it might be because we have small noise.\nFor noisier data it should perform worse.\n\n\n```python\n# Use a bigger standard deviation for the simulated error, this is more noise\nnoisier_e = 5\n\ny_noisy = (b1*x + b0) + noisier_e*np.random.randn(sample_size)\n\n# Estimate parameters\n[b0_hat, b1_hat] = simple_model.fit(x.reshape(-1, 1), y_noisy)\n\n# Fitness metrics\nprint(\"Estimated standard error: %.2f\" % simple_model.std_err)\nprint(\"R squared score: %.2f\" % simple_model.r2)\n```\n\n Estimated standard error: 4.40\n R squared score: 0.78\n\n\nWe can see that the estimate of the standard error has grown (keeping track of the real error) and the r2 score is worse too.\n\n## Comparison to the sklearn implementation\n\nTo the aim of validating our results let's compare them against the linear regression implementation of sklearn. \n\n\n```python\nfrom sklearn import linear_model\n```\n\n\n```python\nlinear = linear_model.LinearRegression()\nlinear.fit(x.reshape(-1, 1), y.reshape(-1, 1))\n\nprint(\"Sklearn beta0: %.5f\" % np.squeeze(linear.intercept_))\nprint(\"Sklearn beta1: %.5f\" % np.squeeze(linear.coef_))\nprint(\"Sklearn R squared: %.5f\" % linear.score(x.reshape(-1, 1), y.reshape(-1, 1)))\n```\n\n Sklearn beta0: 3.39091\n Sklearn beta1: 4.50452\n Sklearn R squared: 0.94928\n\n\nThe same! Not surprise really.. This is beacuase the algorithm is deterministic. In more complex algorithms such as in a MLP we could different results due to, for example, random initialization.\n\n## General linear regression: multiple independant variables\n\nThe model can be generalized as:\n$$\nY = X\\beta\n$$\nwhere $\\beta$ is the vector $[\\beta_0, \\beta_1, ..., \\beta_n]$ and X is the collection of examples(one per row). The first entry in each training example is $1$ as it is the coefficient of the intercept. Typically the linear model can be written as:\n$$\nY = \\beta_0 + X\\beta_{1:n},\n$$\nbut adding a first column on $1$s to $X$ we can rewritte the equation as the more compact one of the begining.\n\nIn this case instead of fitting a line we fit an n-dimensional hyperplane. Let's see this in 2D\n\n\n```python\nsample_size = 100\n\n# Parameters to estimate\nbeta = np.array([1, 2, -2])\n\n# Standard deviation of the simulated irreducible error\ne = 2\n\n# Generate random points\nx = np.random.rand(sample_size, 2)*5\n\n\n# Simulate data with noise\ny = (np.matmul(x, beta[1:]) + beta[0]) + e*np.random.randn(sample_size)\n```\n\n### Visualize the data\n\n\n```python\nfig = plt.figure()\n\nax = plt.axes(projection='3d')\nax.scatter3D(x[:, 0], x[:, 1], y);\nplt.show()\n```\n\n### Estimator for $\\beta$\n\nUsing the least squares method the resulting estimator is:\n$$\n\\hat{\\beta} = (X^TX)^{-1}X^TY\n$$\nThis assumes $X$ has full column rank. If $M^+$ is the Moore-Penrose pseudoinverse of any matrix $M$, then $\\beta$ can be estimated as:\n\n$$\n\\hat{\\beta} = X^+Y,\n$$\n\nwhich can be expressed as:\n$$\n\\hat{\\beta} = (X^TX)^+X^TY,\n$$\n\nobtaining a correct estimator for $\\beta$ even when $X$ has less than full rank.\n\n\n```python\nlinear_model = LinearRegression()\n\n# The model expects the data without the column of ones and with shape (n_samples, n_features)\nbeta_hat = linear_model.fit(x, y)\nprint(\"Estimated parameters:\\n B0={}\\n B1={}\\n B2={}\".format(beta_hat[0], beta_hat[1], beta_hat[2]))\n```\n\n Estimated parameters:\n B0=2.364948307515827\n B1=1.6136037083970096\n B2=-2.1559887289541617\n\n\n\n```python\nxx, yy = np.meshgrid(np.linspace(0, 5, 100), np.linspace(0, 5, 100))\nz = beta[0] + beta[1]*xx + beta[2]*yy\nz_hat = beta_hat[0] + beta_hat[1]*xx + beta_hat[2]*yy\n\nfig = plt.figure()\n\nax = plt.axes(projection='3d')\nax.scatter3D(x[:, 0], x[:, 1], y);\nax.plot_surface(xx, yy, z, alpha=0.5, color='green', label='True plane')\nax.plot_surface(xx, yy, z_hat, alpha=0.5, color='orange', label='Regressed plane')\nplt.show()\n```\n\n### Fitness metrics\n\n\n```python\nprint(\"Estimated standard error: %.2f\" % linear_model.std_err)\nprint(\"R squared score: %.2f\" % linear_model.r2)\n```\n\n Estimated standard error: 2.00\n R squared score: 0.80\n\n\n## Bibliography\n\n* [Wikipedia: Linear Regression](https://en.wikipedia.org/wiki/Linear_regression)\n* [Proofs involving ordinary least squares](https://en.wikipedia.org/wiki/Proofs_involving_ordinary_least_squares#Least_squares_estimator_for_.CE.B2)\n* [Regression via pseudoinverse](https://spartanideas.msu.edu/2015/10/21/regression-via-pseudoinverse/)\n", "meta": {"hexsha": "aaf130e86b3354dc6ccb72139dbcd32daf52c719", "size": 130345, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/linear-regression.ipynb", "max_stars_repo_name": "SergioAlvarezB/ml-numpy", "max_stars_repo_head_hexsha": "bf450b0d48b52c56fd3d124a5b41f2b99594ea3b", "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/linear-regression.ipynb", "max_issues_repo_name": "SergioAlvarezB/ml-numpy", "max_issues_repo_head_hexsha": "bf450b0d48b52c56fd3d124a5b41f2b99594ea3b", "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/linear-regression.ipynb", "max_forks_repo_name": "SergioAlvarezB/ml-numpy", "max_forks_repo_head_hexsha": "bf450b0d48b52c56fd3d124a5b41f2b99594ea3b", "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": 196.8957703927, "max_line_length": 43456, "alphanum_fraction": 0.9082281637, "converted": true, "num_tokens": 3155, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.963779946215714, "lm_q2_score": 0.9241418168448761, "lm_q1q2_score": 0.8906693505344468}} {"text": "# RSA Cryptography Algorithm\n\n## About RSA Algorithm\nRSA (Rivest–Shamir–Adleman) is one of the first public-key cryptosystems and is widely used for secure data transmission. In such a cryptosystem, the encryption key is public and distinct from the decryption key which is kept secret (private).\n\n## Algorithm\n\n1. Select 2 Prime Numbers - **p & q**\n2. Calculate **n = p x q**\n3. Calculate Euler's Totient Function of n, **φ(n) = (p-1) x (q-1)**\n4. Select PUBLIC KEY, **e** such that **e & φ(n) are Co-primes** i.e, **gcd(e , φ(n))=1**\n5. Calculate PRIVATE KEY, **d** such that **(d x e) mod φ(n) = 1**\n\n## Public and Private Keys\n\n1. The Public key is { e , n }, which is known to all in the network.\n2. The Private key is { d , n }, which is known ONLY to the User to whom message is to be sent.\n\n## Encryption & Decryption\n\n#### Encryption Algorithm\n\nThe Cipher Text, C is generated from the plaintext, M using the public key, e as:\n\n**C = Me mod n**\n\n#### Decryption Algorithm\n\nThe Plain Text, M is generated from the ciphertext, C using the private key, d as:\n\n**M = Cd mod n**\n\n\n\n## Implementation of RSA using Python\n\n\n```python\nfrom sympy import *\nimport math \n\n#Generate p and q\np = randprime(1, 10)\nq = randprime(11, 20)\n\n#Generate n and l(n)\nn = p*q\nl = (p-1)*(q-1)\n\n#Function to test Co-Primality for generation of list of Public Keys\ndef isCoPrime(x):\n if math.gcd(l,x)==1:\n return True\n else:\n return False\n\n#Function to find mod Inverese of e withl(n) to generate d \ndef modInverse(e, l) :\n e = e % l;\n for x in range(1, l) :\n if ((e * x) % l == 1) :\n return x\n return 1\n\n#List for Co-Primes\nlistOfCP = []\nfor i in range(1, l):\n if isCoPrime(i) == True:\n listOfCP.append(i)\n\n#Print values of P, Q, N, L \nprint(\"Value of P = \", p)\nprint(\"Value of Q = \", q)\nprint(\"Value of N = \", n)\nprint(\"Value of L = \", l)\n\nprint(\" \")\n\n#Print List of Co-Primes for e\nprint(\"List of Available Public Keys\")\nprint(listOfCP)\n\nprint(\" \")\n\n#select a Public Key from list of Co-Primes\ne = int(input(\"Select Public Key from the Above List ONLY: \"))\n\n#Value of d\nd = modInverse(e, l)\n\nprint(\" \")\n\n#Print Public and Private Keys\nprint(\"PUBLIC KEY : { e , n } = {\", e ,\",\", n , \"}\")\nprint(\"PRIVATE KEY : { d , n } = {\", d ,\",\", n , \"}\")\n\nprint(\" \")\n\n#Encryption Algorithm\ndef encrypt(plainText):\n return (plainText**e)%n\n\n#Decryption Algorithm\ndef decrypt(cipherText):\n pvtKey = int(input(\"Enter your Private Key: \"))\n return (cipherText**pvtKey)%n\n\n#Driver Code\n\n#Message Input\npt = int(input('Enter the Plain Text: '))\nprint(\"CipherText: \", encrypt(pt))\n\nprint(\" \")\n\n#CipherText Input\nct = int(input('Enter the Cipher Text: '))\nprint(\"PlainText: \", decrypt(ct))\n```\n\n Value of P = 7\n Value of Q = 19\n Value of N = 133\n Value of L = 108\n \n List of Available Public Keys\n [1, 5, 7, 11, 13, 17, 19, 23, 25, 29, 31, 35, 37, 41, 43, 47, 49, 53, 55, 59, 61, 65, 67, 71, 73, 77, 79, 83, 85, 89, 91, 95, 97, 101, 103, 107]\n \n Select Public Key from the Above List ONLY: 47\n \n PUBLIC KEY : { e , n } = { 47 , 133 }\n PRIVATE KEY : { d , n } = { 23 , 133 }\n \n Enter the Plain Text: 51\n CipherText: 116\n \n Enter the Cipher Text: 116\n Enter your Private Key: 23\n PlainText: 51\n\n\n## Encryption & Decryption Mechanism\n\nThe Encryption and Decryption mechanishm block diagram is shown below\n\n\n\n## Explanation\n\nThe explanation for the above example is shown below\n\n\n\n#### Tanmoy Sen Gupta\n[tanmoysg.com](http://tanmoysg.com) | +91 9864809029 | tanmoysps@gmail.com\n", "meta": {"hexsha": "333d04b378dc8aef86d11805e6a7ea19dfcf43ef", "size": 199167, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "RSA-Algorithm/RSA-Example.ipynb", "max_stars_repo_name": "TanmoySG/RSA-Algorithm", "max_stars_repo_head_hexsha": "cba1b4ba8e96c6eb1bd67097e47ed7763185fb63", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-05-05T11:07:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-03T13:19:05.000Z", "max_issues_repo_path": "RSA-Algorithm/RSA-Example.ipynb", "max_issues_repo_name": "TanmoySG/RSA-Algorithm", "max_issues_repo_head_hexsha": "cba1b4ba8e96c6eb1bd67097e47ed7763185fb63", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-03-12T18:13:12.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-12T18:13:12.000Z", "max_forks_repo_path": "RSA-Algorithm/RSA-Example.ipynb", "max_forks_repo_name": "TanmoySG/RSA-Algorithm", "max_forks_repo_head_hexsha": "cba1b4ba8e96c6eb1bd67097e47ed7763185fb63", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-10-01T01:19:39.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-01T01:19:39.000Z", "avg_line_length": 796.668, "max_line_length": 127448, "alphanum_fraction": 0.9527833426, "converted": true, "num_tokens": 1143, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422199928904, "lm_q2_score": 0.936285006192502, "lm_q1q2_score": 0.8905401993359935}} {"text": "## Plotting\n\n\n```python\nfrom sympy import init_session\ninit_session(quiet=True)\n```\n\n \n\n\n\n```python\nexpr = exp(sin(x**2+pi))\nexpr.series(x)\n```\n\n\n```python\nexpr.series(x, 1, n=7)\n```\n\nLets compare the original function with its series expansion visually\n\nSymPy includes plotting functions, which are (by default) based on matplotlib (and also a legacy pyglet-based plotting...)\n\n\n```python\n%matplotlib inline\n```\n\n\n```python\nplot(expr);\n```\n\n\n```python\np1 = plot(expr, expr.series(x, 1, 7).removeO(), (x, -4, 7),\n ylim = (-3,3),\n show = False,\n legend = True\n)\np1[1].line_color=\"r\"\np1[1].label=\"series(6)\"\np1.show()\n```\n\n\n```python\np0 = plot(expr, (x, -2.5, 5),\n ylim = (-0,3),\n show = False,\n legend = True\n)\nfor n in range(1, 6):\n p1 = plot(expr.series(x, 1, n=n).removeO(), (x, -2.5, 5), show = False)\n p1[0].line_color = \"C%d\"%n\n p1[0].label = \"n=%d\"%(n,)\n p0.append(p1[0])\np0.show()\n```\n\nFor more complicated plots I personally prefer to use matplotlib\n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\n```\n\n\n```python\nnumexpr = lambdify(x, expr)\nxpts = np.linspace(-4, 4, 500)\nplt.plot(xpts, numexpr(xpts), label=\"$%s$\"%latex(expr), lw=2)\nfor n in range(1, 5):\n plt.plot(xpts, lambdify(x, expr.series(x, 1, n=n).removeO())(xpts)*np.ones_like(xpts),\n c=\"C%d\"%n, label=\"$n=%d$\"%n, lw=1)\nplt.ylim(0.0, 3)\nplt.xlim(-4, 4)\nplt.legend(loc=\"lower left\", fontsize=12);\n```\n\nWe have used the lambdify function, which turns a sympy expression into a numerical function (using numpy by default)\n\n\n```python\nfun = lambdify(x, expr)\n```\n\nIt is a numpy function...\n\n\n```python\nimport inspect\ninspect.getsource(fun)\n```\n\n\n\n\n 'def _lambdifygenerated(x):\\n return (exp(-sin(x**2)))\\n'\n\n\n\n3D plots are also supported\n\n\n```python\nfrom sympy.plotting import plot3d, plot3d_parametric_surface\nplot3d(sin(x)*cos(y), (x, -5, 5), (y, -5, 5));\n```\n\n\n```python\nu, v = symbols('u v')\nplot3d_parametric_surface(cos(u + v), sin(u - v), u - v, (u, -5, 5), (v, -5, 5));\n```\n", "meta": {"hexsha": "5e73c91445694014a96a373c203d344f79a03e6b", "size": 355745, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/03a Plotting.ipynb", "max_stars_repo_name": "rouckas/sympy-slides", "max_stars_repo_head_hexsha": "c2777f0eddedd19c4bf094d40489f49c1ef8ad28", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2018-10-22T19:52:48.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-01T16:59:45.000Z", "max_issues_repo_path": "notebooks/03a Plotting.ipynb", "max_issues_repo_name": "rouckas/sympy-slides", "max_issues_repo_head_hexsha": "c2777f0eddedd19c4bf094d40489f49c1ef8ad28", "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": "notebooks/03a Plotting.ipynb", "max_forks_repo_name": "rouckas/sympy-slides", "max_forks_repo_head_hexsha": "c2777f0eddedd19c4bf094d40489f49c1ef8ad28", "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": 876.2192118227, "max_line_length": 75236, "alphanum_fraction": 0.9389787629, "converted": true, "num_tokens": 682, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240177362486, "lm_q2_score": 0.9489172614177538, "lm_q1q2_score": 0.8902020737805013}} {"text": "# Series (Lecture 6)\n\n\n```python\n# This cell just imports relevant modules\n\nimport numpy\nfrom sympy import sin, cos, exp, ln, Function, Symbol, diff, integrate, limit, oo, series, factorial\nfrom math import pi\nimport mpmath\nimport matplotlib.pyplot as plt\n```\n\n## Sequences\n\n**Slide 10**\n\n\n```python\n# Store elements of the sequence in a list\nfinite_sequence = [2*k for k in range(1, 5)]\n\nprint(finite_sequence)\n```\n\n [2, 4, 6, 8]\n\n\nRemember: `range(A,B)` generates integers from `A` up to `B-1`, so we need to use `B=5` here.\n\n### Convergence of sequences\n\n**Slides 11, 13, 14**\n\n\n```python\nk = Symbol('k')\nprint(\"As k->infinity, the sequence {k} tends to:\", limit(k, k, oo)) \n# The 'oo' here is SymPy's notation for infinity\n\nprint(\"As k->infinity, the sequence {1/k} tends to:\", limit(1.0/k, k, oo)) \n\nprint(\"As k->infinity, the sequence {exp(1/k)} tends to:\", limit(exp(1.0/k), k, oo)) \n\nprint(\"As k->infinity, the sequence {(k**3 + 2*k - 4)/(k**3 + 1)} tends to:\", \n limit((k**3 + 2*k - 4)/(k**3 + 1), k, oo)) \n```\n\n As k->infinity, the sequence {k} tends to: oo\n As k->infinity, the sequence {1/k} tends to: 0\n As k->infinity, the sequence {exp(1/k)} tends to: 1\n As k->infinity, the sequence {(k**3 + 2*k - 4)/(k**3 + 1)} tends to: 1\n\n\n## Series\n\n**Slide 15**\n\n\n```python\n# Using list comprehension:\nprint(\"The sum of 3*k + 1 (from k=0 to k=4) is:\", sum([3*k + 1 for k in range(0,5)])) \n# Note: we could also use the nsum function (part of the module mpmath): \n# print(mpmath.nsum(lambda k: 3*k + 1, [0, 4]))\n```\n\n The sum of 3*k + 1 (from k=0 to k=4) is: 35\n\n\n\n```python\nx = 1\nprint(f\"The sum of (x**k)/(k!) from k=0 to k=4, with x = {x}, is:\", \n sum([x**k/factorial(k) for k in range(1,5)])) \n```\n\n The sum of (x**k)/(k!) from k=0 to k=4, with x = 1, is: 41/24\n\n\n### Arithmetic progression\n\n**Slide 18**\n\n\n```python\nprint(\"The sum of 5 + 4*k up to the 11th term (i.e. up to k=10) is:\", \n sum([5 + 4*k for k in range(0,11)])) \n```\n\n The sum of 5 + 4*k up to the 11th term (i.e. up to k=10) is: 275\n\n\n### Geometric progression\n\n**Slide 21**\n\n\n```python\nprint(\"The sum of 3**k up to the 7th term (i.e. up to k=6) is:\", \n sum([3**k for k in range(0,7)])) \n```\n\n The sum of 3**k up to the 7th term (i.e. up to k=6) is: 1093\n\n\n### Infinite series\n\n**Slides 23, 24, 25**\n\n\n```python\nprint(\"The sum of the infinite series sum(1/(2**k)) is:\", \n mpmath.nsum(lambda k: 1/(2**k), [1, mpmath.inf])) \nprint(\"The sum of the infinite alternating series sum(((-1)**(k+1))/k) is:\", \n mpmath.nsum(lambda k: ((-1)**(k+1))/k, [1, mpmath.inf])) \n```\n\n The sum of the infinite series sum(1/(2**k)) is: 1.0\n The sum of the infinite alternating series sum(((-1)**(k+1))/k) is: 0.693147180559945\n\n\n### Ratio test\n\n**Slide 27**\n\nA diverging example:\n\n\n```python\nk = Symbol('k')\nf = (2**k)/(3*k)\nf1 = (2**(k+1))/(3*(k+1))\nratio = f1/f\n\nlim = limit(ratio, k, oo) \nprint(\"As k -> infinity, the ratio tends to:\", lim) \nif(lim < 1.0):\n print(\"The series converges\") \nelif(lim > 1.0):\n print(\"The series diverges\") \nelse:\n print(\"The series either converges or diverges\") \n```\n\n As k -> infinity, the ratio tends to: 2\n The series diverges\n\n\nA converging example:\n\n\n```python\nf = (2**k)/(5**k)\nf1 = (2**(k+1))/(5**(k+1))\nratio = f1/f\n\nlim = limit(ratio, k, oo) \nprint(\"As k -> infinity, the ratio tends to:\", lim) \nif(lim < 1.0):\n print(\"The series converges\") \nelif(lim > 1.0):\n print(\"The series diverges\") \nelse:\n print(\"The series either converges or diverges\") \n```\n\n As k -> infinity, the ratio tends to: 2/5\n The series converges\n\n\n### Power series\n\n**Slide 30**\n\n\n```python\nk = Symbol('k')\nx = Symbol('x')\n\na = 1/k\nf = a*(x**k)\n\na1 = 1/(k+1)\nf1 = a1*(x**(k+1))\n\nratio = abs(a/a1)\nR = limit(ratio, k, oo)\nprint(\"The radius of convergence (denoted R) is:\", R) \n\nx = 0.5\nif(abs(x) < 1):\n print(f\"The series converges for |x| = {abs(x)} (< R)\") \nelif(abs(x) > 1):\n print(f\"The series diverges for |x| = {abs(x)} (> R)\") \nelse:\n print(f\"The series either converges or diverges for |x| = {abs(x)} (== R)\\n\") \n```\n\n The radius of convergence (denoted R) is: 1\n The series converges for |x| = 0.5 (< R)\n\n\n## Useful series\n\n**Slide 34**\n\n\n```python\nx = Symbol('x')\nr = Symbol('r')\n\n# Note: the optional argument 'n' allows us to truncate the series\n# after a certain order of x has been reached.\nprint(\"1/(1+x) = \", series(1.0/(1.0+x), x, n=4)) \nprint(\"1/(1-x) = \", series(1.0/(1.0-x), x, n=4)) \nprint(\"ln(1+x) = \", series(ln(1.0+x), x, n=4)) \nprint(\"exp(x) = \", series(exp(x), x, n=4)) \nprint(\"cos(x) = \", series(cos(x), x, n=7)) \nprint(\"sin(x) = \", series(sin(x), x, n=8)) \n```\n\n 1/(1+x) = 1.0 - 1.0*x + 1.0*x**2 - 1.0*x**3 + O(x**4)\n 1/(1-x) = 1.0 + 1.0*x + 1.0*x**2 + 1.0*x**3 + O(x**4)\n ln(1+x) = 1.0*x - 0.5*x**2 + 0.333333333333333*x**3 + O(x**4)\n exp(x) = 1 + x + x**2/2 + x**3/6 + O(x**4)\n cos(x) = 1 - x**2/2 + x**4/24 - x**6/720 + O(x**7)\n sin(x) = x - x**3/6 + x**5/120 - x**7/5040 + O(x**8)\n\n\n### Taylor series\n\nThe more terms there are in the series the more accurate it is as it better approximates the function. The error of the Taylor series decreases as \\\\(x\\\\) approaches \\\\(0\\\\).\n\n#### \\\\( \\ln(1+x) \\\\) with different number of terms \\\\(n\\\\):\n\n\n```python\ndef ln_taylor(x, n):\n y = numpy.zeros(x.shape)\n for i in range(1, n):\n y = y + (-1)**(i+1) * (x**i)/(factorial(i)) # taylor series of ln(1+x)\n return y \n\n\nx = numpy.linspace(-0.9, 0.9, 181) # [-0.9, -0.89, ..., 0.88, 0.89, 0.9]\n\nln = numpy.log(1+x) # actual function\n\nn = [i for i in range(1, 6)] # list [1, 2, 3, 4, 5]\ncolour = ['y', 'b', 'c', 'g', 'r'] \n\nfig, ax = plt.subplots(1, 2, figsize=(15, 10))\n\nfor i in range(len(n)):\n y_ln = ln_taylor(x, n[i]) # values from taylor series\n ln_error = abs(y_ln - ln) # difference between taylor series and function\n \n ax[0].plot(x, y_ln, colour[i], label=f'n={n[i]}')\n ax[1].plot(x, ln_error, colour[i], label=f'n={n[i]}')\n\nax[0].plot(x, ln, 'k', label='y=ln(1+x)')\n\nax[0].set_ylabel('y')\nax[0].set_title('ln(1+x) vs taylor series', fontsize=14)\nax[1].set_ylabel('error')\nax[1].set_title('Error plot of taylor series for ln(1+x)', fontsize=14) \nfor i in range(len(ax)):\n ax[i].set_xlabel('x')\n ax[i].legend(loc='best', fontsize=14)\n ax[i].grid(True)\n\nfig.tight_layout()\nplt.show()\n```\n\n#### \\\\( \\exp(x) \\\\) with different number of terms \\\\(n\\\\)\n\n\n```python\ndef exp_taylor(x, n):\n y = numpy.zeros(x.shape)\n for i in range(n):\n y = y + x**i / factorial(i) # taylor series for exp(x)\n return y\n\n\nx = numpy.linspace(0, 5, 501) # x between 0 and 5\n\nexpx = numpy.exp(x) # actual function\n\nn = [1, 2, 3, 4, 5] # number of terms between 1 and 5\ncolour = ['y', 'b', 'c', 'g', 'r'] \n\nfig, ax = plt.subplots(1, 2, figsize=(15, 10))\n\nfor i in range(len(n)):\n y_exp = exp_taylor(x, n[i]) # values from taylor series\n exp_error = abs(y_exp - expx) # difference between taylor series and function\n \n ax[0].plot(x, y_exp, colour[i], label=f'n={n[i]}')\n ax[1].plot(x, exp_error, colour[i], label=f'n={n[i]}')\n\nax[0].plot(x, expx, 'k', label='y=exp(x)')\n\nax[0].set_ylabel('y')\nax[0].set_title('exp(x) vs taylor series', fontsize=14)\nax[1].set_ylabel('error')\nax[1].set_title('Error plot of taylor series for exp(x)', fontsize=14) \nfor i in range(len(ax)):\n ax[i].set_xlabel('x')\n ax[i].legend(loc='best', fontsize=14)\n ax[i].grid(True)\n\nfig.tight_layout()\nplt.show()\n```\n\n#### \\\\( \\sin(x) \\\\) with different number of terms \\\\(n\\\\)\n\n\n```python\ndef sin_taylor(x, n):\n y = numpy.zeros(x.shape)\n for i in range(n):\n y = y + (-1)**(i)*(x**(2*i+1) / factorial(2*i+1)) # taylor series for sin(x)\n return y\n\nx = numpy.linspace(-5, 5, 1001) # x between -5 and 5\n\nsinx = numpy.sin(x) # actual function\n\nn = [1, 2, 3, 4, 5] # number of terms between 1 and 5\ncolour = ['y', 'b', 'c', 'g', 'r'] \n\nfig, ax = plt.subplots(2, 1, figsize=(10, 15))\n\nfor i in range(len(n)):\n y_sin = sin_taylor(x, n[i]) # values from taylor series\n sin_error = abs(y_sin - sinx) # difference between taylor series and function\n \n ax[0].plot(x, y_sin, colour[i], label=f'n={n[i]}')\n ax[1].plot(x, sin_error, colour[i], label=f'n={n[i]}')\n\nax[0].plot(x, sinx, 'k', label='y=sin(x)')\n\nax[0].set_ylabel('y')\nax[0].set_title('sin(x) vs taylor series', fontsize=14)\nax[1].set_ylabel('error')\nax[1].set_title('Error plot of taylor series for sin(x)', fontsize=14) \nfor i in range(len(ax)):\n ax[i].set_xlabel('x')\n ax[i].legend(loc='best', fontsize=14)\n ax[i].grid(True)\n\nfig.tight_layout()\nplt.show()\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "34899f2e9f91f216bc1f98a6463a8c32c4ce491f", "size": 328779, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/a_modules/math_methods_1/7_Series.ipynb", "max_stars_repo_name": "primer-computational-mathematics/book", "max_stars_repo_head_hexsha": "305941b4f1fc4f15d472fd11f2c6e90741fb8b64", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-08-02T07:32:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-16T16:40:43.000Z", "max_issues_repo_path": "notebooks/a_modules/math_methods_1/7_Series.ipynb", "max_issues_repo_name": "primer-computational-mathematics/book", "max_issues_repo_head_hexsha": "305941b4f1fc4f15d472fd11f2c6e90741fb8b64", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2020-07-27T10:45:26.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-12T15:09:14.000Z", "max_forks_repo_path": "notebooks/a_modules/math_methods_1/7_Series.ipynb", "max_forks_repo_name": "primer-computational-mathematics/book", "max_forks_repo_head_hexsha": "305941b4f1fc4f15d472fd11f2c6e90741fb8b64", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2020-08-05T13:57:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-02T19:03:57.000Z", "avg_line_length": 516.136577708, "max_line_length": 112772, "alphanum_fraction": 0.9415047798, "converted": true, "num_tokens": 3207, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377225508371, "lm_q2_score": 0.9284087956033519, "lm_q1q2_score": 0.8899148525338025}} {"text": "# Hamiltonian Monte Carlo (HMC)\n\n\n```python\n%matplotlib inline\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport seaborn as sns\nfrom functools import partial\n```\n\n## Hamiltonian Monte Carlo (HMC)\n\nHMC uses an auxiliary variable corresponding to the momentum of particles in a potential energy well to generate proposal distributions that can make use of gradient information in the posterior distribution. For reversibility to be maintained, the total energy of the particle has to be conserved - hence we are interested in Hamiltonian systems. The main attraction of HMC is that it works much better than other methods when variables of interest are highly correlated. Because we have to solve problems involving momentum, we need to understand how to numerically solve differential equations in a way that is both accurate (i.e. second order) and preserves total energy (necessary for a Hamiltonian system).\n\nExample adapted from [MCMC: Hamiltonian Monte Carlo (a.k.a. Hybrid Monte Carlo)](https://theclevermachine.wordpress.com/2012/11/18/mcmc-hamiltonian-monte-carlo-a-k-a-hybrid-monte-carlo/)\n\n### Hamiltonian systems\n\nIn a Hamiltonian system, we consider particles with position $x$ and momentum (or velocity if we assume unit mass) $v$. The total energy of the system $H(x, v) = K(v) + U(x)$, where $K$ is the kinetic energy and $U$ is the potential energy, is conserved. Such a system satisfies the following Hamiltonian equations\n\n$$\n\\begin{align}\n\\frac{dx}{dt} &= & \\frac{\\delta H}{dv} \\\\\n\\frac{dv}{dt} &= & -\\frac{\\delta H}{dx} \n\\end{align}\n$$\n\nSince $K$ depends only on $v$ and $U$ depends only on $x$, we have\n$$\n\\begin{align}\n\\frac{dx}{dt} &= & \\frac{\\delta K}{dv} \\\\\n\\frac{dv}{dt} &= & -\\frac{\\delta U}{dx}\n\\end{align}\n$$\n\n#### Harmonic oscillator\n\nWe will consider solving a classical Hamiltonian system - that of a undamped spring governed by the second order differential equation\n\n$$\nx'' + x = 0\n$$\n\nWe convert this to two first order ODEs by using a dummy variable $x' = v$ to get\n\n$$\n\\begin{align}\nx' &= v \\\\\nv' &= -x\n\\end{align}\n$$\n\nFrom the Hamiltonian equations above, this is equivalent to a system with kinetic energy $K(v) = \\frac{1}{2}v^2$ and potential energy $U(x) = \\frac{1}{2}x^2$.\n\nWriting in matrix form,\n\n$$\nA = \\pmatrix{ x' \\\\ v' } = \\pmatrix{0 & 1 \\\\ -1 & 0} \\pmatrix{x \\\\ v}\n$$\n\nand in general, for the state vector $x$,\n\n$$\nx' = Ax\n$$\n\nWe note that $A$ is anti- or skew-symmetric ($A^T = -A$), and hence has purely imaginary eigenvalues. Solving $|A - \\lambda I = 0$, we see that the eigenvalues and eigenvectors are $i, \\pmatrix{1\\\\i}$ and $-i, \\pmatrix{1\\\\-i}$. Since the eigenvalues are pure imaginary, we see that the solution for the initial conditions $(x,v) = (1, 0)$ is $x(t) = e^{it}$ and the orbit just goes around a circle with a period of $2\\pi$, neither growing nor decaying. Another weay of seeing this is that the Hamiltonian $H(u, v)$ or sum of potential ($U(x)) = \\frac{1}{2}x^2$) and kinetic energy ($K(v) = \\frac{1}{2}v^2$) is constant, i.e. in vector form, $(x^T x) = \\text{constant}$.\n\n### Finite difference methods\n\nWe want to find a finite difference approximation to $u' = Au$ that is **accurate** and **preserves total energy**. If total energy is not preserved, the orbit will either spiral in towards zero or outwards away from the unit circle. If the accuracy is poor, the orbit will not be close to its starting value after $t = 2\\pi$. This gives us an easy way to visualize how good our numerical scheme is. We can also compare the numerical scheme to the Taylor series to evaluate its accuracy.\n\n#### Forward Euler\n\nThe simplest finite difference scheme for integrating ODEs is the forward Euler\n\n$$\n\\frac{u_{n+1} - u_n}{\\Delta t} = A u_n\n$$\n\nRearranging terms, we get\n\n$$\nu_{n+1} = u_n + \\Delta t A u_n = \\left( I + \\Delta t A \\right) u_n\n$$\n\nSince the eigenvalues of $A$ are $\\pm i$, we see that the eigenvalues of the forward Euler matrix are $1 \\pm i$. Since the absolute value of the eigenvalues is greater than 1, we expect **growing** solutions - i.e. the solution will spiral away from the unit circle.\n\n\n```python\nimport scipy.linalg as la\n```\n\n\n```python\ndef f_euler(A, u, N):\n orbit = np.zeros((N,2))\n\n dt = 2*np.pi/N\n for i in range(N):\n u = u + dt * A @ u\n orbit[i] = u\n return orbit\n```\n\n\n```python\nA = np.array([[0,1],[-1,0]])\nu = np.array([1.0,0.0])\nN = 64\norbit = f_euler(A, u, N)\n```\n\n##### Accuracy\n\n\n```python\nla.norm(np.array([1.0,0.0]) - orbit[-1])\n```\n\n\n\n\n 0.3600318484671192\n\n\n\n##### Conservation of energy\n\n\n```python\nplt.plot([p @ p for p in orbit])\npass\n```\n\n\n```python\nax = plt.subplot(111)\nplt.plot(orbit[:, 0], orbit[:,1], 'o')\nax.axis('square')\nplt.axis([-1.5, 1.5, -1.5, 1.5])\npass\n```\n\n##### Accuracy and conservation of energy\n\nWe can see that forward Euler is not very accurate and also does not preserve energy since the orbit spirals away from the unit circle.\n\n#### The trapezoidal method\n\nThe trapezoidal method uses the following scheme\n\n$$\n\\frac{u_{n+1} - u_n}{\\Delta t} = \\frac{1}{2} ( A u_{n+1} + A u_{n})\n$$\n\nThis is an implicit scheme (because $u_{n+1}$ appears on the RHS) whose solution is\n\n$$\nu_{n+1} = \\left(I - \\frac{\\Delta t}{2} A \\right)^{-1} \\left(I + \\frac{\\Delta t}{2} A \\right) u_{n} = B u_n\n$$\n\nBy inspection, we see that the eigenvalues are the complex conjugates of\n\n$$\n\\frac{1 + \\frac{\\Delta t}{2} i}{1 - \\frac{\\Delta t}{2} i}\n$$\n\nwhose absolute value is 1 - hence, energy is conserved. If we expand the matrix $B$ using the geometric series and compare with the Taylor expansion, we see that the trapezoidal method has local truncation error $O(h^3)$ and hence accuracy $O(h^2)$, where $h$ is the time step.\n\n\n```python\ndef trapezoidal(A, u, N):\n p = len(u)\n orbit = np.zeros((N,p))\n\n dt = 2*np.pi/N\n for i in range(N):\n u = la.inv(np.eye(p) - dt/2 * A) @ (np.eye(p) + dt/2 * A) @ u\n orbit[i] = u\n return orbit\n```\n\n\n```python\nA = np.array([[0,1],[-1,0]])\nu = np.array([1.0,0.0])\nN = 64\norbit = trapezoidal(A, u, N)\n```\n\n##### Accuracy\n\n\n```python\nla.norm(np.array([1.0,0.0]) - orbit[-1])\n```\n\n\n\n\n 0.005039305635733781\n\n\n\n##### Conservation of energy\n\n\n```python\nplt.plot([p @ p for p in orbit])\npass\n```\n\n\n```python\nax = plt.subplot(111)\nplt.plot(orbit[:, 0], orbit[:,1], 'o')\nax.axis('square')\nplt.axis([-1.5, 1.5, -1.5, 1.5])\npass\n```\n\n#### The leapfrog method\n\nThe leapfrog method uses a second order difference to update $u_n$. The algorithm simplifies to the following explicit scheme:\n\n- First take one half-step for v\n- Then take a full step for u\n- Then take one final half step for v\n\nIt performs almost as well as the trapezoidal method, with the advantage of being an explicit scheme and cheaper to calculate, so the leapfrog method is used in HMC.\n\n\n```python\ndef leapfrog(A, u, N):\n orbit = np.zeros((N,2))\n\n dt = 2*np.pi/N\n for i in range(N):\n u[1] = u[1] + dt/2 * A[1] @ u\n u[0] = u[0] + dt * A[0] @ u\n u[1] = u[1] + dt/2 * A[1] @ u\n orbit[i] = u\n return orbit\n```\n\n##### If we don't care about the intermediate steps, it is more efficient to just take 1/2 steps at the beginning and end\n\n\n```python\ndef leapfrog2(A, u, N):\n dt = 2*np.pi/N\n\n u[1] = u[1] + dt/2 * A[1] @ u\n for i in range(N-1):\n u[0] = u[0] + dt * A[0] @ u\n u[1] = u[1] + dt * A[1] @ u\n\n u[0] = u[0] + dt * A[0] @ u\n u[1] = u[1] + dt/2 * A[1] @ u \n return u\n```\n\n\n```python\nA = np.array([[0,1],[-1,0]])\nu = np.array([1.0,0.0])\nN = 64\n```\n\n\n```python\norbit = leapfrog(A, u, N)\n```\n\n##### Accuracy\n\n\n```python\nla.norm(np.array([1.0,0.0]) - orbit[-1])\n```\n\n\n\n\n 0.0025229913808033464\n\n\n\n##### Conservation of energy\n\nNote that unlike the trapezoidal scheme, energy is not perfectly conserved.\n\n\n```python\nplt.plot([p @ p for p in orbit])\npass\n```\n\n\n```python\nax = plt.subplot(111)\nplt.plot(orbit[:, 0], orbit[:,1], 'o')\nax.axis('square')\nplt.axis([-1.5, 1.5, -1.5, 1.5])\npass\n```\n\n### From Hamiltonians to probability distributions\n\nThe physical analogy considers the negative log likelihood of the target distribution $p(x)$ to correspond to a potential energy well, with a collection of particles moving on the surface of the well. The state of each particle is given only by its position and momentum (or velocity if we assume unit mass for each particle). In a Hamiltonian system, the total energy $H(x, v) = U(x) + K(v)$ is conserved. From statistical mechanics, the probability of each state is related to the total energy of the system\n\n$$\n\\begin{align}\np(x, v) & \\propto e^{-H(x, v)} \\\\\n&= e^{-U(x) - K(v)} \\\\\n&= e^{-P(x)}e^{-K(v)} \\\\\n& \\propto p(x) \\, p(v)\n\\end{align}\n$$\n\nSince the joint distribution factorizes $p(x, v) = p(x)\\, p(v)$, we can select an initial random $v$ for a particle, numerically integrate using a finite difference method such as the leapfrog and then use the updated $x^*$ as the new proposal. The acceptance ratio for the new $x^*$ is\n\n$$\n\\frac{ e^{ -U(x^*)-K(v^*) }} { e^{-U(x)-K(v)} } = e^{U(x)-U(x^*)+K(x)-K(x^*)}\n$$\n\nIf our finite difference scheme was exact, the acceptance ration would be 1 since energy is conserved with Hamiltonian dynamics. However, as we have seen, the leapfrog method does not conserve energy perfectly and an accept/reject step is still needed.\n\n#### Example of HMC\n\nWe will explore how HMC works when the target distribution is bivariate normal centered at zero\n\n$$\nx \\sim N(0, \\Sigma)\n$$\n\nIn practice of course, the target distribution will be the posterior distribution and depend on both data and distributional parameters.\n\nThe potential energy or negative log likelihood is proportional to\n$$\nU(x) = \\frac{x^T\\Sigma^{-1} x}{2}\n$$\n\nThe kinetic energy is given by\n$$\nK(v) = \\frac{v^T v}{2}\n$$ \n\nwhere the initial $v_0$ is chosen at random from the unit normal at each step.\n\nTo find the time updates, we use the Hamiltonian equations and find the first derivatives of total energy with respect to $x$ and $v$\n\n$$\n\\begin{align}\nx' &= \\frac{\\delta K}{\\delta v} &= v \\\\\nv' &= -\\frac{\\delta U}{\\delta x} &= -\\Sigma^{-1} x \\\\\n\\end{align}\n$$\n\ngiving us the block matrix\n\n$$\nA = \\pmatrix{0 & 1 \\\\ -\\Sigma^{-1} & 0}\n$$\n\nBy using the first derivatives, we are making use of the gradient information on the log posterior to guide the proposal distribution.\n\n##### This is what the target distribution should look like\n\n\n```python\nsigma = np.array([[1,0.8],[0.8,1]])\nmu = np.zeros(2)\nys = np.random.multivariate_normal(mu, sigma, 1000)\nsns.kdeplot(ys[:,0], ys[:,1])\nplt.axis([-3.5,3.5,-3.5,3.5])\npass\n```\n\n##### This is the HMC posterior\n\n\n```python\ndef E(A, u0, v0, u, v):\n \"\"\"Total energy.\"\"\"\n return (u0 @ tau @ u0 + v0 @ v0) - (u @ tau@u + v @ v)\n```\n\n\n```python\ndef leapfrog(A, u, v, h, N):\n \"\"\"Leapfrog finite difference scheme.\"\"\"\n v = v - h/2 * A @ u\n for i in range(N-1):\n u = u + h * v\n v = v - h * A @ u\n\n u = u + h * v\n v = v - h/2 * A @ u\n\n return u, v\n```\n\n\n```python\nniter = 100\nh = 0.01\nN = 100\n\ntau = la.inv(sigma)\n\norbit = np.zeros((niter+1, 2))\nu = np.array([-3,3])\norbit[0] = u\nfor k in range(niter):\n v0 = np.random.normal(0,1,2)\n u, v = leapfrog(tau, u, v0, h, N)\n\n # accept-reject\n u0 = orbit[k]\n a = np.exp(E(A, u0, v0, u, v))\n r = np.random.rand()\n\n if r < a:\n orbit[k+1] = u\n else:\n orbit[k+1] = u0\n```\n\n\n```python\nsns.kdeplot(orbit[:, 0], orbit[:, 1])\nplt.plot(orbit[:,0], orbit[:,1], alpha=0.2)\nplt.scatter(orbit[:1,0], orbit[:1,1], c='red', s=30)\nplt.scatter(orbit[1:,0], orbit[1:,1], c=np.arange(niter)[::-1], cmap='Reds')\nplt.axis([-3.5,3.5,-3.5,3.5])\npass\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "81761d2e93099d77ba2a9e2887c0b0684dbf8e7f", "size": 203061, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/copies/lectures/T08F_HMC.ipynb", "max_stars_repo_name": "robkravec/sta-663-2021", "max_stars_repo_head_hexsha": "4dc8018f7b172eaf81da9edc33174768ff157939", "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/copies/lectures/T08F_HMC.ipynb", "max_issues_repo_name": "robkravec/sta-663-2021", "max_issues_repo_head_hexsha": "4dc8018f7b172eaf81da9edc33174768ff157939", "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/copies/lectures/T08F_HMC.ipynb", "max_forks_repo_name": "robkravec/sta-663-2021", "max_forks_repo_head_hexsha": "4dc8018f7b172eaf81da9edc33174768ff157939", "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.0585175553, "max_line_length": 77800, "alphanum_fraction": 0.9202801129, "converted": true, "num_tokens": 3658, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9688561685659693, "lm_q2_score": 0.9184802523931341, "lm_q1q2_score": 0.8898752582371164}} {"text": "# Modeling and Simulation in Python\n\nChapter 9\n\nCopyright 2017 Allen Downey\n\nLicense: [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0)\n\n\n\n```python\n# Configure Jupyter to display the assigned value after an assignment\n%config InteractiveShell.ast_node_interactivity='last_expr_or_assign'\n\n# import everything from SymPy.\nfrom sympy import *\n\n# Set up Jupyter notebook to display math.\ninit_printing() \n```\n\nThe following displays SymPy expressions and provides the option of showing results in LaTeX format.\n\n\n```python\nfrom sympy.printing import latex\n\ndef show(expr, show_latex=False):\n \"\"\"Display a SymPy expression.\n \n expr: SymPy expression\n show_latex: boolean\n \"\"\"\n if show_latex:\n print(latex(expr))\n return expr\n```\n\n### Analysis with SymPy\n\nCreate a symbol for time.\n\n\n```python\nt = symbols('t')\n```\n\nIf you combine symbols and numbers, you get symbolic expressions.\n\n\n```python\nexpr = t + 1\n```\n\nThe result is an `Add` object, which just represents the sum without trying to compute it.\n\n\n```python\ntype(expr)\n```\n\n\n\n\n sympy.core.add.Add\n\n\n\n`subs` can be used to replace a symbol with a number, which allows the addition to proceed.\n\n\n```python\nexpr.subs(t, 2)\n```\n\n`f` is a special class of symbol that represents a function.\n\n\n```python\nf = Function('f')\n```\n\n\n\n\n f\n\n\n\nThe type of `f` is `UndefinedFunction`\n\n\n```python\ntype(f)\n```\n\n\n\n\n sympy.core.function.UndefinedFunction\n\n\n\nSymPy understands that `f(t)` means `f` evaluated at `t`, but it doesn't try to evaluate it yet.\n\n\n```python\nf(t)\n```\n\n`diff` returns a `Derivative` object that represents the time derivative of `f`\n\n\n```python\ndfdt = diff(f(t), t)\n```\n\n\n```python\ntype(dfdt)\n```\n\n\n\n\n sympy.core.function.Derivative\n\n\n\nWe need a symbol for `alpha`\n\n\n```python\nalpha = symbols('alpha')\n```\n\nNow we can write the differential equation for proportional growth.\n\n\n```python\neq1 = Eq(dfdt, alpha*f(t))\n```\n\nAnd use `dsolve` to solve it. The result is the general solution.\n\n\n```python\nsolution_eq = dsolve(eq1)\n```\n\nWe can tell it's a general solution because it contains an unspecified constant, `C1`.\n\nIn this example, finding the particular solution is easy: we just replace `C1` with `p_0`\n\n\n```python\nC1, p_0 = symbols('C1 p_0')\n```\n\n\n```python\nparticular = solution_eq.subs(C1, p_0)\n```\n\nIn the next example, we have to work a little harder to find the particular solution.\n\n### Solving the quadratic growth equation \n\nWe'll use the (r, K) parameterization, so we'll need two more symbols:\n\n\n```python\nr, K = symbols('r K')\n```\n\nNow we can write the differential equation.\n\n\n```python\neq2 = Eq(diff(f(t), t), r * f(t) * (1 - f(t)/K))\n```\n\nAnd solve it.\n\n\n```python\nsolution_eq = dsolve(eq2)\n```\n\nThe result, `solution_eq`, contains `rhs`, which is the right-hand side of the solution.\n\n\n```python\ngeneral = solution_eq.rhs\n```\n\nWe can evaluate the right-hand side at $t=0$\n\n\n```python\nat_0 = general.subs(t, 0)\n```\n\nNow we want to find the value of `C1` that makes `f(0) = p_0`.\n\nSo we'll create the equation `at_0 = p_0` and solve for `C1`. Because this is just an algebraic identity, not a differential equation, we use `solve`, not `dsolve`.\n\nThe result from `solve` is a list of solutions. In this case, [we have reason to expect only one solution](https://en.wikipedia.org/wiki/Picard%E2%80%93Lindel%C3%B6f_theorem), but we still get a list, so we have to use the bracket operator, `[0]`, to select the first one.\n\n\n```python\nsolutions = solve(Eq(at_0, p_0), C1)\ntype(solutions), len(solutions)\n```\n\n\n\n\n (list, 1)\n\n\n\n\n```python\nvalue_of_C1 = solutions[0]\n```\n\nNow in the general solution, we want to replace `C1` with the value of `C1` we just figured out.\n\n\n```python\nparticular = general.subs(C1, value_of_C1)\n```\n\nThe result is complicated, but SymPy provides a method that tries to simplify it.\n\n\n```python\nparticular = simplify(particular)\n```\n\nOften simplicity is in the eye of the beholder, but that's about as simple as this expression gets.\n\nJust to double-check, we can evaluate it at `t=0` and confirm that we get `p_0`\n\n\n```python\nparticular.subs(t, 0)\n```\n\nThis solution is called the [logistic function](https://en.wikipedia.org/wiki/Population_growth#Logistic_equation).\n\nIn some places you'll see it written in a different form:\n\n$f(t) = \\frac{K}{1 + A e^{-rt}}$\n\nwhere $A = (K - p_0) / p_0$.\n\nWe can use SymPy to confirm that these two forms are equivalent. First we represent the alternative version of the logistic function:\n\n\n```python\nA = (K - p_0) / p_0\n```\n\n\n```python\nlogistic = K / (1 + A * exp(-r*t))\n```\n\nTo see whether two expressions are equivalent, we can check whether their difference simplifies to 0.\n\n\n```python\nsimplify(particular - logistic)\n```\n\nThis test only works one way: if SymPy says the difference reduces to 0, the expressions are definitely equivalent (and not just numerically close).\n\nBut if SymPy can't find a way to simplify the result to 0, that doesn't necessarily mean there isn't one. Testing whether two expressions are equivalent is a surprisingly hard problem; in fact, there is no algorithm that can solve it in general.\n\n### Exercises\n\n**Exercise:** Solve the quadratic growth equation using the alternative parameterization\n\n$\\frac{df(t)}{dt} = \\alpha f(t) + \\beta f^2(t) $\n\n\n```python\ndfdt = diff(f(t),t)\n```\n\n\n```python\nalpha,beta = symbols('alpha beta')\n\neq1 = Eq(dfdt,(alpha * f(t)) + (beta * f(t)**2))\n```\n\n\n```python\nsolution_eqn = dsolve(eq1)\n```\n\n\n```python\ngeneral = solution_eqn.rhs\n```\n\n\n```python\nat_0 = general.subs(t, 0)\n```\n\n\n```python\nsolutions = solve(Eq(at_0, p_0), C1)\nvalue_of_C1 = solutions[0]\n```\n\n\n```python\nparticular = general.subs(C1, value_of_C1)\n```\n\n\n```python\nparticular = simplify(particular)\n```\n\n**Exercise:** Use [WolframAlpha](https://www.wolframalpha.com/) to solve the quadratic growth model, using either or both forms of parameterization:\n\n df(t) / dt = alpha f(t) + beta f(t)^2\n\nor\n\n df(t) / dt = r f(t) (1 - f(t)/K)\n\nFind the general solution and also the particular solution where `f(0) = p_0`.\n\n\n```python\ngeneral = solution_eqn.rhs\n```\n\n\n```python\nparticular.subs(t,0)\n```\n", "meta": {"hexsha": "b1091480117f4b07ac34702cff371e45ef01c1f8", "size": 101958, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/chap09.ipynb", "max_stars_repo_name": "devinteran/ModSimPy", "max_stars_repo_head_hexsha": "d003ef7013e2952d0c446c7d1cbb83f0c5df0913", "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/chap09.ipynb", "max_issues_repo_name": "devinteran/ModSimPy", "max_issues_repo_head_hexsha": "d003ef7013e2952d0c446c7d1cbb83f0c5df0913", "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/chap09.ipynb", "max_forks_repo_name": "devinteran/ModSimPy", "max_forks_repo_head_hexsha": "d003ef7013e2952d0c446c7d1cbb83f0c5df0913", "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": 82.623987034, "max_line_length": 10220, "alphanum_fraction": 0.8280762667, "converted": true, "num_tokens": 1695, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.966410492898765, "lm_q2_score": 0.9207896699134004, "lm_q1q2_score": 0.8898607987571004}} {"text": "# Advanced topic: Solving the two-layer grey gas model analytically with sympy\n\n____________\n\n## 1. Introducing symbolic computation with sympy\n____________\n\nThese notes elaborate on material in the [lecture on elementary greenhouse models](elementary-greenhouse.ipynb), demonstrating use of a computer algebra system to make precise calculations.\n\n### Symbolic math with the sympy package\n\nThe two-layer grey gas model is simple enough that we can work out all the details algebraically. There are three temperatures to keep track of $(T_s, T_0, T_1)$, so we will have 3x3 matrix equations.\n\nWe all know how to work these things out with pencil and paper. But it can be tedious and error-prone. \n\nSymbolic math software lets us use the computer to automate a lot of tedious algebra.\n\nThe [sympy](http://www.sympy.org/en/index.html) package is a powerful open-source symbolic math library that is well-integrated into the scientific Python ecosystem. \n\n### Getting started with sympy\n\n\n```python\nimport sympy\n# Allow sympy to produce nice looking equations as output\nsympy.init_printing()\n# Define some symbols for mathematical quantities\n# Assume all quantities are positive (which will help simplify some expressions)\nepsilon, T_e, T_s, T_0, T_1, sigma = \\\n sympy.symbols('epsilon, T_e, T_s, T_0, T_1, sigma', positive=True)\n# So far we have just defined some symbols, e.g.\nT_s\n```\n\n\n```python\n# We have hard-coded the assumption that the temperature is positive\nsympy.ask(T_s>0)\n```\n\n\n\n\n True\n\n\n\n____________\n\n## 2. Coding up the 2-layer grey gas model in sympy\n____________\n\n### Longwave emissions\n\nLet's denote the emissions from each layer as\n\\begin{align}\nE_s &= \\sigma T_s^4 \\\\\nE_0 &= \\epsilon \\sigma T_0^4 \\\\\nE_1 &= \\epsilon \\sigma T_1^4 \n\\end{align}\n\nrecognizing that $E_0$ and $E_1$ contribute to **both** the upwelling and downwelling beams.\n\n\n```python\n# Define these operations as sympy symbols \n# And display as a column vector:\nE_s = sigma*T_s**4\nE_0 = epsilon*sigma*T_0**4\nE_1 = epsilon*sigma*T_1**4\nE = sympy.Matrix([E_s, E_0, E_1])\nE\n```\n\n### Shortwave radiation\n\nSince we have assumed the atmosphere is transparent to shortwave, the incident beam $Q$ passes unchanged from the top to the surface, where a fraction $\\alpha$ is reflected upward out to space.\n\n\n```python\n# Define some new symbols for shortwave radiation\nQ, alpha = sympy.symbols('Q, alpha', positive=True)\n# Create a dictionary to hold our numerical values\ntuned = {}\ntuned[Q] = 341.3 # global mean insolation in W/m2\ntuned[alpha] = 101.9/Q.subs(tuned) # observed planetary albedo\ntuned[sigma] = 5.67E-8 # Stefan-Boltzmann constant in W/m2/K4\ntuned\n# Numerical value for emission temperature\n#T_e.subs(tuned)\n```\n\n### Tracing the upwelling beam of longwave radiation\n\nLet $U$ be the upwelling flux of longwave radiation. \n\nThe upward flux **from the surface to layer 0** is\n\n$$ U_0 = E_s $$\n\n(just the emission from the suface).\n\n\n```python\nU_0 = E_s\nU_0\n```\n\nFollowing this beam upward, we can write the upward flux from layer 0 to layer 1 as the sum of the transmitted component that originated below layer 0 and the new emissions from layer 0:\n\n$$ U_1 = (1-\\epsilon) U_0 + E_0 $$\n\n\n```python\nU_1 = (1-epsilon)*U_0 + E_0\nU_1\n```\n\nContinuing to follow the same beam, the upwelling flux above layer 1 is\n$$ U_2 = (1-\\epsilon) U_1 + E_1 $$\n\n\n```python\nU_2 = (1-epsilon) * U_1 + E_1\n```\n\nSince there is no more atmosphere above layer 1, this upwelling flux is our Outgoing Longwave Radiation for this model:\n\n$$ OLR = U_2 $$\n\n\n```python\nU_2\n```\n\nThe three terms in the above expression represent the **contributions to the total OLR that originate from each of the three levels**. \n\nLet's code this up explicitly for future reference:\n\n\n```python\n# Define the contributions to OLR originating from each level\nOLR_s = (1-epsilon)**2 *sigma*T_s**4\nOLR_0 = epsilon*(1-epsilon)*sigma*T_0**4\nOLR_1 = epsilon*sigma*T_1**4\n\nOLR = OLR_s + OLR_0 + OLR_1\n\nprint( 'The expression for OLR is')\nOLR\n```\n\n### Downwelling beam\n\nLet $D$ be the downwelling longwave beam. Since there is no longwave radiation coming in from space, we begin with \n\n\n```python\nfromspace = 0\nD_2 = fromspace\n```\n\nBetween layer 1 and layer 0 the beam contains emissions from layer 1:\n\n$$ D_1 = (1-\\epsilon)D_2 + E_1 = E_1 $$\n\n\n```python\nD_1 = (1-epsilon)*D_2 + E_1\nD_1\n```\n\nFinally between layer 0 and the surface the beam contains a transmitted component and the emissions from layer 0:\n\n$$ D_0 = (1-\\epsilon) D_1 + E_0 = \\epsilon(1-\\epsilon) \\sigma T_1^4 + \\epsilon \\sigma T_0^4$$\n\n\n```python\nD_0 = (1-epsilon)*D_1 + E_0\nD_0\n```\n\nThis $D_0$ is what we call the **back radiation**, i.e. the longwave radiation from the atmosphere to the surface.\n\n____________\n\n\n## 3. Tuning the grey gas model to observations\n____________\n\nIn building our new model we have introduced exactly one parameter, the absorptivity $\\epsilon$. We need to choose a value for $\\epsilon$.\n\nWe will tune our model so that it **reproduces the observed global mean OLR** given **observed global mean temperatures**.\n\nTo get appropriate temperatures for $T_s, T_0, T_1$, revisit the global, annual mean lapse rate plot from NCEP Reanalysis data we first encountered in the [Radiation notes](https://brian-rose.github.io/ClimateLaboratoryBook/courseware/radiation.html).\n\n### Temperatures\n\nFirst, we set \n$$T_s = 288 \\text{ K} $$\n\nFrom the lapse rate plot, an average temperature for the layer between 1000 and 500 hPa is \n\n$$ T_0 = 275 \\text{ K}$$\n\nDefining an average temperature for the layer between 500 and 0 hPa is more ambiguous because of the lapse rate reversal at the tropopause. We will choose\n\n$$ T_1 = 230 \\text{ K}$$\n\nFrom the graph, this is approximately the observed global mean temperature at 275 hPa or about 10 km.\n\n\n```python\n# add to our dictionary of values:\ntuned[T_s] = 288.\ntuned[T_0] = 275.\ntuned[T_1] = 230.\ntuned\n```\n\n### OLR\n\nFrom the [observed global energy budget](https://brian-rose.github.io/ClimateLaboratoryBook/courseware/models-budgets-fun.html#2.-The-observed-global-energy-budget) we set \n\n$$ OLR = 238.5 \\text{ W m}^{-2} $$\n\n### Solving for $\\epsilon$\n\nWe wrote down the expression for OLR as a function of temperatures and absorptivity in our model above. \n\nWe just need to equate this to the observed value and solve a **quadratic equation** for $\\epsilon$.\n\nThis is where the real power of the symbolic math toolkit comes in. \n\nSubsitute in the numerical values we are interested in:\n\n\n```python\n# the .subs() method for a sympy symbol means\n# substitute values in the expression using the supplied dictionary\n# Here we use observed values of Ts, T0, T1 \nOLR2 = OLR.subs(tuned)\nOLR2\n```\n\nWe have a quadratic equation for $\\epsilon$.\n\nNow use the `sympy.solve` function to solve the quadratic:\n\n\n```python\n# The sympy.solve method takes an expression equal to zero\n# So in this case we subtract the tuned value of OLR from our expression\neps_solution = sympy.solve(OLR2 - 238.5, epsilon)\neps_solution\n```\n\nThere are two roots, but the second one is unphysical since we must have $0 < \\epsilon < 1$.\n\nJust for fun, here is a simple of example of *filtering a list* using powerful Python *list comprehension* syntax:\n\n\n```python\n# Give me only the roots that are between zero and 1!\nlist_result = [eps for eps in eps_solution if 0\n\n## 4. Level of emission\n____________\n\nEven in this very simple greenhouse model, there is **no single level** at which the OLR is generated.\n\nThe three terms in our formula for OLR tell us the contributions from each level.\n\n\n```python\nOLRterms = sympy.Matrix([OLR_s, OLR_0, OLR_1])\nOLRterms\n```\n\nNow evaluate these expressions for our tuned temperature and absorptivity:\n\n\n```python\nOLRtuned = OLRterms.subs(tuned)\nOLRtuned\n```\n\nSo we are getting about 67 W m$^{-2}$ from the surface, 79 W m$^{-2}$ from layer 0, and 93 W m$^{-2}$ from the top layer.\n\nIn terms of fractional contributions to the total OLR, we have (limiting the output to two decimal places):\n\n\n```python\nsympy.N(OLRtuned / 238.5, 2)\n```\n\nNotice that the largest single contribution is coming from the top layer. This is in spite of the fact that the emissions from this layer are weak, because it is so cold.\n\nComparing to observations, the actual contribution to OLR from the surface is about 22 W m$^{-2}$ (or about 9% of the total), not 67 W m$^{-2}$. So we certainly don't have all the details worked out yet!\n\nAs we will see later, to really understand what sets that observed 22 W m$^{-2}$, we will need to start thinking about the spectral dependence of the longwave absorptivity.\n\n____________\n\n\n## 5. Radiative forcing in the 2-layer grey gas model\n____________\n\nAdding some extra greenhouse absorbers will mean that a greater fraction of incident longwave radiation is absorbed in each layer.\n\nThus **$\\epsilon$ must increase** as we add greenhouse gases.\n\nSuppose we have $\\epsilon$ initially, and the absorptivity increases to $\\epsilon_2 = \\epsilon + \\delta_\\epsilon$.\n\nSuppose further that this increase happens **abruptly** so that there is no time for the temperatures to respond to this change. **We hold the temperatures fixed** in the column and ask how the radiative fluxes change.\n\n**Do you expect the OLR to increase or decrease?**\n\nLet's use our two-layer leaky greenhouse model to investigate the answer.\n\nThe components of the OLR before the perturbation are\n\n\n```python\nOLRterms\n```\n\nAfter the perturbation we have\n\n\n```python\ndelta_epsilon = sympy.symbols('delta_epsilon')\nOLRterms_pert = OLRterms.subs(epsilon, epsilon+delta_epsilon)\nOLRterms_pert\n```\n\nLet's take the difference\n\n\n```python\ndeltaOLR = OLRterms_pert - OLRterms\ndeltaOLR\n```\n\nTo make things simpler, we will neglect the terms in $\\delta_\\epsilon^2$. This is perfectly reasonably because we are dealing with **small perturbations** where $\\delta_\\epsilon << \\epsilon$.\n\nTelling `sympy` to set the quadratic terms to zero gives us\n\n\n```python\ndeltaOLR_linear = sympy.expand(deltaOLR).subs(delta_epsilon**2, 0)\ndeltaOLR_linear\n```\n\nRecall that the three terms are the contributions to the OLR from the three different levels. In this case, the **changes** in those contributions after adding more absorbers.\n\nNow let's divide through by $\\delta_\\epsilon$ to get the normalized change in OLR per unit change in absorptivity:\n\n\n```python\ndeltaOLR_per_deltaepsilon = \\\n sympy.simplify(deltaOLR_linear / delta_epsilon)\ndeltaOLR_per_deltaepsilon\n```\n\nNow look at the **sign** of each term. Recall that $0 < \\epsilon < 1$. **Which terms in the OLR go up and which go down?**\n\n**THIS IS VERY IMPORTANT, SO STOP AND THINK ABOUT IT.**\n\nThe contribution from the **surface** must **decrease**, while the contribution from the **top layer** must **increase**.\n\n**When we add absorbers, the average level of emission goes up!**\n\n### \"Radiative forcing\" is the change in radiative flux at TOA after adding absorbers\n\nIn this model, only the longwave flux can change, so we define the radiative forcing as\n\n$$ R = - \\delta OLR $$\n\n(with the minus sign so that $R$ is positive when the climate system is gaining extra energy).\n\nWe just worked out that whenever we add some extra absorbers, the emissions to space (on average) will originate from higher levels in the atmosphere. \n\nWhat does this mean for OLR? Will it increase or decrease?\n\nTo get the answer, we just have to sum up the three contributions we wrote above:\n\n\n```python\nR_per_deltaepsilon = -sum(deltaOLR_per_deltaepsilon)\nR_per_deltaepsilon\n```\n\nIs this a positive or negative number? The key point is this:\n\n**It depends on the temperatures, i.e. on the lapse rate.**\n\n### Greenhouse effect for an isothermal atmosphere\n\nStop and think about this question:\n\nIf the **surface and atmosphere are all at the same temperature**, does the OLR go up or down when $\\epsilon$ increases (i.e. we add more absorbers)?\n\nUnderstanding this question is key to understanding how the greenhouse effect works.\n\n#### Let's solve the isothermal case\n\nWe will just set $T_s = T_0 = T_1$ in the above expression for the radiative forcing.\n\n\n```python\nR_per_deltaepsilon.subs([(T_0, T_s), (T_1, T_s)])\n```\n\nwhich then simplifies to\n\n\n```python\nsympy.simplify(R_per_deltaepsilon.subs([(T_0, T_s), (T_1, T_s)]))\n```\n\n#### The answer is zero\n\nFor an isothermal atmosphere, there is **no change** in OLR when we add extra greenhouse absorbers. Hence, no radiative forcing and no greenhouse effect.\n\nWhy?\n\nThe level of emission still must go up. But since the temperature at the upper level is the **same** as everywhere else, the emissions are exactly the same.\n\n### The radiative forcing (change in OLR) depends on the lapse rate!\n\nFor a more realistic example of radiative forcing due to an increase in greenhouse absorbers, we can substitute in our tuned values for temperature and $\\epsilon$. \n\nWe'll express the answer in W m$^{-2}$ for a 2% increase in $\\epsilon$.\n\n\n```python\ndelta_epsilon = 0.02 * epsilon\ndelta_epsilon\n```\n\nThe three components of the OLR change are\n\n\n```python\n(deltaOLR_per_deltaepsilon * delta_epsilon).subs(tuned)\n```\n\nAnd the net radiative forcing is\n\n\n```python\n(R_per_deltaepsilon*delta_epsilon).subs(tuned)\n```\n\nSo in our example, **the OLR decreases by 2.6 W m$^{-2}$**, or equivalently, the radiative forcing is +2.6 W m$^{-2}$.\n\nWhat we have just calculated is this:\n\n*Given the observed lapse rates, a small increase in absorbers will cause a small decrease in OLR.*\n\nThe greenhouse effect thus gets stronger, and energy will begin to accumulate in the system -- which will eventually cause temperatures to increase as the system adjusts to a new equilibrium.\n\n____________\n\n\n## 6. Radiative equilibrium in the 2-layer grey gas model\n____________\n\nIn the previous section we:\n\n- made no assumptions about the processes that actually set the temperatures. \n- used the model to calculate radiative fluxes, **given observed temperatures**. \n- stressed the importance of knowing the lapse rates in order to know how an increase in emission level would affect the OLR, and thus determine the radiative forcing.\n\nA key question in climate dynamics is therefore this:\n\n**What sets the lapse rate?**\n\nIt turns out that lots of different physical processes contribute to setting the lapse rate. \n\nUnderstanding how these processes acts together and how they change as the climate changes is one of the key reasons for which we need more complex climate models.\n\nFor now, we will use our prototype greenhouse model to do the most basic lapse rate calculation: the **radiative equilibrium temperature**.\n\nWe assume that\n\n- the only exchange of energy between layers is longwave radiation\n- equilibrium is achieved when the **net radiative flux convergence** in each layer is zero.\n\n### Compute the radiative flux convergence\n\nFirst, the **net upwelling flux** is just the difference between flux up and flux down:\n\n\n```python\n# Upwelling and downwelling beams as matrices\nU = sympy.Matrix([U_0, U_1, U_2])\nD = sympy.Matrix([D_0, D_1, D_2])\n# Net flux, positive up\nF = U-D\nF\n```\n\n#### Net absorption is the flux convergence in each layer\n\n(difference between what's coming in the bottom and what's going out the top of each layer)\n\n\n```python\n# define a vector of absorbed radiation -- same size as emissions\nA = E.copy()\n\n# absorbed radiation at surface\nA[0] = F[0]\n# Compute the convergence\nfor n in range(2):\n A[n+1] = -(F[n+1]-F[n])\n\nA\n```\n\n#### Radiative equilibrium means net absorption is ZERO in the atmosphere\n\nThe only other heat source is the **shortwave heating** at the **surface**.\n\nIn matrix form, here is the system of equations to be solved:\n\n\n```python\nradeq = sympy.Equality(A, sympy.Matrix([(1-alpha)*Q, 0, 0]))\nradeq\n```\n\nJust as we did for the 1-layer model, it is helpful to rewrite this system using the definition of the **emission temperture** $T_e$\n\n$$ (1-\\alpha) Q = \\sigma T_e^4 $$\n\n\n```python\nradeq2 = radeq.subs([((1-alpha)*Q, sigma*T_e**4)])\nradeq2\n```\n\nIn this form we can see that we actually have a **linear system** of equations for a set of variables $T_s^4, T_0^4, T_1^4$.\n\nWe can solve this matrix problem to get these as functions of $T_e^4$.\n\n\n```python\n# Solve for radiative equilibrium \nfourthpower = sympy.solve(radeq2, [T_s**4, T_1**4, T_0**4])\nfourthpower\n```\n\nThis produces a dictionary of solutions for the fourth power of the temperatures!\n\nA little manipulation gets us the solutions for temperatures that we want:\n\n\n```python\n# need the symbolic fourth root operation\nfrom sympy.simplify.simplify import nthroot\n\nfourthpower_list = [fourthpower[key] for key in [T_s**4, T_0**4, T_1**4]]\nsolution = sympy.Matrix([nthroot(item,4) for item in fourthpower_list])\n# Display result as matrix equation!\nT = sympy.Matrix([T_s, T_0, T_1])\nsympy.Equality(T, solution)\n```\n\nIn more familiar notation, the radiative equilibrium solution is thus\n\n\\begin{align} \nT_s &= T_e \\left( \\frac{2+\\epsilon}{2-\\epsilon} \\right)^{1/4} \\\\\nT_0 &= T_e \\left( \\frac{1+\\epsilon}{2-\\epsilon} \\right)^{1/4} \\\\\nT_1 &= T_e \\left( \\frac{ 1}{2 - \\epsilon} \\right)^{1/4}\n\\end{align}\n\nPlugging in the tuned value $\\epsilon = 0.586$ gives\n\n\n```python\nTsolution = solution.subs(tuned)\n# Display result as matrix equation!\nsympy.Equality(T, Tsolution)\n```\n\nNow we just need to know the Earth's emission temperature $T_e$!\n\n(Which we already know is about 255 K)\n\n\n```python\n# Here's how to calculate T_e from the observed values\nsympy.solve(((1-alpha)*Q - sigma*T_e**4).subs(tuned), T_e)\n```\n\n\n```python\n# Need to unpack the list\nTe_value = sympy.solve(((1-alpha)*Q - sigma*T_e**4).subs(tuned), T_e)[0]\nTe_value\n```\n\n#### Now we finally get our solution for radiative equilibrium\n\n\n```python\n# Output 4 significant digits\nTrad = sympy.N(Tsolution.subs([(T_e, Te_value)]), 4)\nsympy.Equality(T, Trad)\n```\n\nCompare these to the values we derived from the **observed lapse rates**:\n\n\n```python\nsympy.Equality(T, T.subs(tuned))\n```\n\nThe **radiative equilibrium** solution is substantially **warmer at the surface** and **colder in the lower troposphere** than reality.\n\nThis is a very general feature of radiative equilibrium, and we will see it again very soon in this course.\n\n____________\n\n\n## 7. Summary\n____________\n\n## Key physical lessons\n\n- Putting a **layer of longwave absorbers** above the surface keeps the **surface substantially warmer**, because of the **backradiation** from the atmosphere (greenhouse effect).\n- The **grey gas** model assumes that each layer absorbs and emits a fraction $\\epsilon$ of its blackbody value, independent of wavelength.\n\n- With **incomplete absorption** ($\\epsilon < 1$), there are contributions to the OLR from every level and the surface (there is no single **level of emission**)\n- Adding more absorbers means that **contributions to the OLR** from **upper levels** go **up**, while contributions from the surface go **down**.\n- This upward shift in the weighting of different levels is what we mean when we say the **level of emission goes up**.\n\n- The **radiative forcing** caused by an increase in absorbers **depends on the lapse rate**.\n- For an **isothermal atmosphere** the radiative forcing is zero and there is **no greenhouse effect**\n- The radiative forcing is positive for our atmosphere **because tropospheric temperatures tends to decrease with height**.\n- Pure **radiative equilibrium** produces a **warm surface** and **cold lower troposphere**.\n- This is unrealistic, and suggests that crucial heat transfer mechanisms are missing from our model.\n\n### And on the Python side...\n\nDid we need `sympy` to work all this out? No, of course not. We could have solved the 3x3 matrix problems by hand. But computer algebra can be very useful and save you a lot of time and error, so it's good to invest some effort into learning how to use it. \n\nHopefully these notes provide a useful starting point.\n\n____________\n\n## Credits\n\nThis notebook is part of [The Climate Laboratory](https://brian-rose.github.io/ClimateLaboratoryBook), an open-source textbook developed and maintained by [Brian E. J. Rose](http://www.atmos.albany.edu/facstaff/brose/index.html), University at Albany. It has been modified by [Nicole Feldl](http://nicolefeldl.com), UC Santa Cruz.\n\nIt is licensed for free and open consumption under the\n[Creative Commons Attribution 4.0 International (CC BY 4.0)](https://creativecommons.org/licenses/by/4.0/) license.\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": "a69fdedff315cf7176a895546e1716d484366c93", "size": 152786, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "content/courseware/sympy-greenhouse.ipynb", "max_stars_repo_name": "nfeldl/ClimateLaboratoryBook", "max_stars_repo_head_hexsha": "05eb0395c0e07d3724e6569e160fbefc9829a990", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-08-25T13:02:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-25T13:02:15.000Z", "max_issues_repo_path": "content/courseware/sympy-greenhouse.ipynb", "max_issues_repo_name": "nfeldl/ClimateLaboratoryBook", "max_issues_repo_head_hexsha": "05eb0395c0e07d3724e6569e160fbefc9829a990", "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": "content/courseware/sympy-greenhouse.ipynb", "max_forks_repo_name": "nfeldl/ClimateLaboratoryBook", "max_forks_repo_head_hexsha": "05eb0395c0e07d3724e6569e160fbefc9829a990", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-07-21T20:43:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-25T13:02:16.000Z", "avg_line_length": 66.9820254274, "max_line_length": 5948, "alphanum_fraction": 0.7671841661, "converted": true, "num_tokens": 5615, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541544761565, "lm_q2_score": 0.9449947126747433, "lm_q1q2_score": 0.8898581971481739}} {"text": "# Part 1: Linear Regression\n\n\n```\n# Execute this code block to install dependencies when running on colab\ntry:\n import torch\nexcept:\n from os.path import exists\n from wheel.pep425tags import get_abbr_impl, get_impl_ver, get_abi_tag\n platform = '{}{}-{}'.format(get_abbr_impl(), get_impl_ver(), get_abi_tag())\n cuda_output = !ldconfig -p|grep cudart.so|sed -e 's/.*\\.\\([0-9]*\\)\\.\\([0-9]*\\)$/cu\\1\\2/'\n accelerator = cuda_output[0] if exists('/dev/nvidia0') else 'cpu'\n\n !pip install -q http://download.pytorch.org/whl/{accelerator}/torch-1.0.0-{platform}-linux_x86_64.whl torchvision\n```\n\n## Getting started \n\nAt its heart, PyTorch is just a library for manipulating tensors. We're going to start learning how to use \nPyTorch by looking at how we can implement simple linear regression. \n\nCode speaks better than words, so lets start by looking at a bit of pytorch code to generate some 2d data to regress:\n\n\n```\nimport torch\n\n# Generate some data points on a straight line perturbed with Gaussian noise\nN = 1000 # number of points\ntheta_true = torch.Tensor([[1.5], [2.0]]) # true parameters of the line\n\nX = torch.rand(N, 2) #Returns a tensor filled with random numbers from a uniform distribution on the interval [0, 1)\nX[:, 1] = 1.0 #the second column\nprint(X)\ny = X @ theta_true + 0.1 * torch.randn(N, 1) # Note that just like in numpy '@' represents matrix multiplication and A@B is equivalent to torch.mm(A, B) \n```\n\n tensor([[0.7577, 1.0000],\n [0.5942, 1.0000],\n [0.2248, 1.0000],\n ...,\n [0.2073, 1.0000],\n [0.8536, 1.0000],\n [0.6797, 1.0000]])\n\n\nThe above code generates $(x,y)$ data according to $y = 1.5x + 2$, with the $x$'s chosen from a uniform distribution. The $y$'s are additionally purturbed by adding an amount $0.1z$, where $z\\sim \\mathcal{N}(0,1)$ is a sample from a standard normal distribution. \n\nNote that we represent our $x$'s as a two-dimensional (row) vector with a 1 in the second element so that the offset can be rolled into the matrix multiplication for efficiency:\n\n\\begin{align}\n y &= \\mathbf{X}\\begin{bmatrix}\n 1.5 \\\\\n 2\n \\end{bmatrix}\n \\end{align}\n\nLet's use `matplotlib` to draw a scatter so we can be sure of what our data looks like:\n\n\n```\n%matplotlib inline\nimport matplotlib.pyplot as plt\n\nplt.scatter(X[:,0].numpy(), y.numpy())\nplt.show()\n```\n\n__Make sure you understand how the code above is generating data; feel free to change the parameters to see what effect they have.__\n\nNow, lets consider the situation where we have been given the tensors $X$ and $y$ and wish to compute the regression parameters. Our model looks like $\\mathbf{y} = \\mathbf{X\\theta}$, and we wish to recover the parameters $\\theta$. \n\nAs the problem is both overcomplete (only two data pairs are required to find $\\theta$), and the data is noisy, we can use the Moore-Penrose Pseudoinverse to find the least-squares solution to $\\theta$: $\\theta = \\mathbf{X^+y}$. PyTorch has a built-in pseudoinverse method (`pinverse`) that can do all the work for us:\n\n\n```\n# direct solution using moore-penrose pseudo inverse\nX_inv = torch.pinverse(X)\ntheta_pinv = torch.mm(X_inv, y)\nprint(theta_pinv)\n```\n\n tensor([[1.5169],\n [1.9939]])\n\n\nRunning the above code should give you a solution vector for $\\theta$ that is very similar to the true parameter vector (`theta_true`). \n\n## Exercise: computing the pseudoinverse from the Singular Value Decomposition.\n\nThe standard way of computing the pseudoinverse is by using the Singular Value Decomposition (SVD). The SVD is defined as: $\\mathbf{X} = \\mathbf{U}\\Sigma\\mathbf{V}^\\top$. The pseudoinverse is thus $\\mathbf{X}^+ = \\mathbf{V}\\Sigma^{-1}\\mathbf{U}^\\top$ where $\\Sigma^{-1}$ is a diagonal matrix in which the reciprocal of the corresponding non-zero elements in $\\Sigma$ has been taken.\n\n__Use the code block below to compute the parameter vector using the SVD directly rather than the through the `pinverse` method.__ You need to store your manually computed pseudoinverse in `X_inv_svd`. Useful methods will be `torch.svd()` to compute the SVD, `[Tensor].t()` to transpose a matrix and `torch.diag()` to form a diagonal matrix from a vector.\n\n\n```\n# YOUR CODE HERE\nu,s,v=torch.svd(X)\nprint('U=',u)\nprint('S=',s)\nprint('V=',v)\ns1=torch.diag(s)\nprint(\"S1=\",s1)\nX_inv_svd=v@torch.inverse(s1)@u.t()\nprint(\"X_inv_svd=\",X_inv_svd)\n# raise NotImplementedError()\n\ntheta_pinv_svd = torch.mm(X_inv_svd, y)\nprint(\"theta_pinv_svd=\",theta_pinv_svd)\n```\n\n U= tensor([[-0.0348, 0.0240],\n [-0.0326, 0.0063],\n [-0.0277, -0.0337],\n ...,\n [-0.0275, -0.0356],\n [-0.0361, 0.0343],\n [-0.0338, 0.0155]])\n S= tensor([35.6136, 8.1517])\n V= tensor([[-0.4725, 0.8813],\n [-0.8813, -0.4725]])\n S1= tensor([[35.6136, 0.0000],\n [ 0.0000, 8.1517]])\n X_inv_svd= tensor([[ 3.0518e-03, 1.1121e-03, -3.2711e-03, ..., -3.4793e-03,\n 4.1895e-03, 2.1268e-03],\n [-5.2742e-04, 4.4339e-04, 2.6372e-03, ..., 2.7414e-03,\n -1.0968e-03, -6.4459e-05]])\n theta_pinv_svd= tensor([[1.5169],\n [1.9939]])\n\n\n\n```\nprint(torch.abs(torch.add(theta_pinv, -theta_pinv_svd)))\nassert(torch.all(torch.lt(torch.abs(torch.add(theta_pinv, -theta_pinv_svd)), 1e-6)))\n```\n\n tensor([[1.1921e-07],\n [2.3842e-07]])\n\n\n## Gradient based Linear Regression\n\nFundamentally, with linear regression we are trying to find a solution vector, $theta$ that minimises $f(\\theta) = 0.5\\|\\mathbf{X}\\theta - \\mathbf{y}\\|_2^2$. \n\nWe've already seen how this can be minimised directly using the pseudoinverse, but it could also be minimised by using gradient descent: $\\theta \\gets \\theta - \\alpha f'(\\theta)$. (_Interesting aside_: SVD (and thus the pseudoinverse) can also be solved using gradient methods - in fact this becomes the only practical way for really large matrices.).\n\n__Use the following block to derive and write down the gradient, $f'(\\theta)$, of $f(\\theta)$__. Note that you can insert latex code by wrapping expressions in dollar symbols.\n\n- **Answer**: \n\n**The deriviate of $f(\\theta) = 0.5\\|\\mathbf{X}\\theta - \\mathbf{y}\\|_2^2$ is $0.5* 2*\\mathbf{X}^T(\\mathbf{X}\\theta-\\mathbf{y})$** \n\n__Now complete the following code block to implement your gradient as pytorch code:__\n\n\n```\ndef linear_regression_loss_grad(theta, X, y):\n # theta, X and y have the same shape as used previously\n # YOUR CODE HERE\n# raise NotImplementedError()\n \n n, p = X.shape # n rows, p columns actually n row 2 column \n# print(n,p)\n# grad1=0.5*(-2/n)*X.t()@((y-torch.mm(X,theta))) ### \n grad=0.5*(-2)*X.t()@((y-torch.mm(X,theta))) \n return grad\n```\n\n\n```\nassert(linear_regression_loss_grad(torch.zeros(2,1), X, y).shape == (2,1))\n\n```\n\nNow we can plug that gradient function into a basic gradient descent solver and check that the solution is close to what we get with the pseudoinverse:\n\n\n```\nalpha = 0.001\ntheta = torch.Tensor([[0], [0]])\nfor e in range(0, 300):\n gr = linear_regression_loss_grad(theta, X, y)\n theta -= alpha * gr\n\nprint(theta)\n```\n\n tensor([[1.5169],\n [1.9939]])\n\n\n## Real data\n\nDoing linear regression on synthetic data is a great way to understand how PyTorch works, but it isn't quite as satisfying as working with a real dataset. Let's now apply or understanding of computing linear regression parameters to a dataset of house prices in Boston.\n\nWe'll load the dataset using scikit-learn and perform some manipulations in the following code block:\n\n\n```\nfrom sklearn.datasets import load_boston\n\nX, y = tuple(torch.Tensor(z) for z in load_boston(True)) #convert to pytorch Tensors\nX = X[:, [2,5]] # We're just going to use features 2 and 5, rather than using all of of them #from the 3th column to 5th column\nX = torch.cat((X, torch.ones((X.shape[0], 1))), 1) # append a column of 1's to the X's\n\ny = y.reshape(-1, 1) # reshape y into a column vector\nprint(X)\n# print(X[:,2])\nprint('X:', X.shape) #506*3\nprint('y:', y.shape) #506*1\n\n# We're also going to break the data into a training set for computing the regression parameters\n# and a test set to evaluate the predictive ability of those parameters\nperm = torch.randperm(y.shape[0]) #Returns a random permutation of integers from 0 to n - 1.\nX_train = X[perm[0:253], :] #254*3\ny_train = y[perm[0:253]] #254*1\nX_test = X[perm[253:], :]\ny_test = y[perm[253:]]\n```\n\n tensor([[ 2.3100, 6.5750, 1.0000],\n [ 7.0700, 6.4210, 1.0000],\n [ 7.0700, 7.1850, 1.0000],\n ...,\n [11.9300, 6.9760, 1.0000],\n [11.9300, 6.7940, 1.0000],\n [11.9300, 6.0300, 1.0000]])\n X: torch.Size([506, 3])\n y: torch.Size([506, 1])\n\n\n__Use the following code block to compute the regression parameters using the training data in the variable `theta` by solving using the pseudoinverse directly:__\n\n\n```\n# compute the regression parameters in variable theta\n# YOUR CODE HERE\n# raise NotImplementedError()\nX_inv = torch.pinverse(X_train)\ntheta= torch.mm(X_inv, y_train)\nprint(theta)\n```\n\n tensor([[ -0.3223],\n [ 7.4680],\n [-20.5415]])\n\n\n\n```\nassert(theta.shape == (3,1))\n\nprint(\"Theta: \", theta.t())\nprint(\"MSE of test data: \", torch.nn.functional.mse_loss(X_test @ theta, y_test))\n```\n\n Theta: tensor([[ -0.3223, 7.4680, -20.5415]])\n MSE of test data: tensor(39.9052)\n\n\nNow let's try using gradient descent:\n\n\n```\nalpha = 0.00001 #0.00001\ntheta_gd = torch.rand((X_train.shape[1], 1)) #initialize\nfor e in range(0, 10000): \n gr = linear_regression_loss_grad(theta_gd, X_train, y_train)\n theta_gd -= alpha * gr\n\nprint(\"Gradient Descent Theta: \", theta_gd.t())\nprint(\"MSE of test data: \", torch.nn.functional.mse_loss(X_test @ theta_gd, y_test))\n```\n\n Gradient Descent Theta: tensor([[-0.4533, 4.9514, -3.1055]])\n MSE of test data: tensor(44.1014)\n\n\n__Use the following block to note down any observations you can make about the choice of learning rate and number of iterations in the above code. What factors do you think influence the choice?__\n\n\n```\nalpha = 0.0001 \ntheta_gd = torch.rand((X_train.shape[1], 1)) #initialize\nfor e in range(0, 10000): \n gr = linear_regression_loss_grad(theta_gd, X_train, y_train)\n theta_gd -= alpha * gr\n\nprint(\"Gradient Descent Theta: \", theta_gd.t())\nprint(\"MSE of test data: \", torch.nn.functional.mse_loss(X_test @ theta_gd, y_test))\n```\n\n Gradient Descent Theta: tensor([[nan, nan, nan]])\n MSE of test data: tensor(nan)\n\n\n\n```\nimport numpy as np\nalphas = [10**(-7),0.000001,0.00001]\nnumiter_array=np.array([10**4,6*10**4,8*10**4,12*10**4])\nfor i,r in enumerate(alphas):\n for numiter in numiter_array:\n theta_gd = torch.rand((X_train.shape[1], 1)) #initialize\n for e in range(0, numiter): #80000\n gr = linear_regression_loss_grad(theta_gd, X_train, y_train)\n theta_gd -= r * gr\n print(\"alpha is: \",r,\"numiter is: \",numiter,\"Gradient Descent Theta: \", theta_gd.t())\n print(\"MSE of test data: \", torch.nn.functional.mse_loss(X_test @ theta_gd, y_test))\n\n```\n\n alpha is: 1e-07 numiter is: 10000 Gradient Descent Theta: tensor([[-0.3959, 4.1427, 1.0744]])\n MSE of test data: tensor(46.8674)\n alpha is: 1e-07 numiter is: 60000 Gradient Descent Theta: tensor([[-0.4850, 4.3420, 1.1158]])\n MSE of test data: tensor(45.9251)\n alpha is: 1e-07 numiter is: 80000 Gradient Descent Theta: tensor([[-0.4786, 4.4641, 0.2695]])\n MSE of test data: tensor(45.5343)\n alpha is: 1e-07 numiter is: 120000 Gradient Descent Theta: tensor([[-0.4775, 4.4851, 0.1238]])\n MSE of test data: tensor(45.4683)\n alpha is: 1e-06 numiter is: 10000 Gradient Descent Theta: tensor([[-0.4836, 4.3690, 0.9293]])\n MSE of test data: tensor(45.8378)\n alpha is: 1e-06 numiter is: 60000 Gradient Descent Theta: tensor([[-0.4616, 4.7923, -2.0035]])\n MSE of test data: tensor(44.5471)\n alpha is: 1e-06 numiter is: 80000 Gradient Descent Theta: tensor([[-0.4597, 4.8288, -2.2563]])\n MSE of test data: tensor(44.4430)\n alpha is: 1e-06 numiter is: 120000 Gradient Descent Theta: tensor([[-0.4488, 5.0382, -3.7073]])\n MSE of test data: tensor(43.8671)\n alpha is: 1e-05 numiter is: 10000 Gradient Descent Theta: tensor([[-0.4502, 5.0118, -3.5239]])\n MSE of test data: tensor(43.9378)\n alpha is: 1e-05 numiter is: 60000 Gradient Descent Theta: tensor([[ -0.3659, 6.6300, -14.7352]])\n MSE of test data: tensor(40.7059)\n alpha is: 1e-05 numiter is: 80000 Gradient Descent Theta: tensor([[ -0.3500, 6.9359, -16.8546]])\n MSE of test data: tensor(40.3446)\n alpha is: 1e-05 numiter is: 120000 Gradient Descent Theta: tensor([[ -0.3335, 7.2530, -19.0517]])\n MSE of test data: tensor(40.0538)\n\n\n\n```\n# YOUR CODE HERE\nimport numpy as np\n# raise NotImplementedError()\ndef gradient_descent(X,y,theta_gd,alpha,numiter):\n theta_history = []\n mse_loss_history = [] \n for i in range(numiter):\n mse_loss=torch.nn.functional.mse_loss(X@ theta_gd, y)\n theta_history.append(theta_gd)\n mse_loss_history.append(mse_loss)\n gr = linear_regression_loss_grad(theta_gd, X, y)\n theta_gd -= alpha * gr\n return theta_gd,theta_history,mse_loss_history\n \nalphas = [10**(-7),0.000001,0.00001]\ntheta_gd_init = torch.rand((X_train.shape[1], 1)) #initialize\nnumiter_array=np.array([10**4,6*10**4,8*10**4])\nfor numiter in numiter_array:\n for i,r in enumerate(alphas): \n theta_gd,theta_history,mse_loss_history=gradient_descent(X_train,y_train,theta_gd_init,r,numiter)\n plt.plot(mse_loss_history,label=r)\n plt.legend()\n plt.show()\n \nprint(\"Gradient Descent Theta: \", theta_gd.t())\nprint(\"MSE of test data: \", torch.nn.functional.mse_loss(X_test @ theta_gd, y_test))\n\n```\n\n- Answer:\n\n**From the above, it indicates that the smaller the learning rate, the slower it converges. On the other hand, the larger the learning rate, it is harder to converge. In terms of number of iterations, the more of number of iterations, the less of the loss. **\n\n**Finally, we choose learning rate = $0.00001$, number of iterations=$180000$**\n\n\n```\nalpha = 0.00001\ntheta_gd = torch.rand((X_train.shape[1], 1)) #initialize\nfor e in range(0, 18*10**4): \n gr = linear_regression_loss_grad(theta_gd, X_train, y_train)\n theta_gd -= alpha * gr\n\nprint(\"Gradient Descent Theta: \", theta_gd.t())\nprint(\"MSE of test data: \", torch.nn.functional.mse_loss(X_test @ theta_gd, y_test))\n```\n\n Gradient Descent Theta: tensor([[ -0.3252, 7.4126, -20.1577]])\n MSE of test data: tensor(39.9397)\n\n\nFinally, just so we can visualise what our model has learned, we can plot the predicted house prices (from both the direct solution and from gradient descent) along with the true value for each of the houses in the test set (ordered by increasing true value):\n\n\n```\nperm = torch.argsort(y_test, dim=0)\nplt.plot(y_test[perm[:,0]].numpy(), '.', label='True Prices')\nplt.plot((X_test[perm[:,0]] @ theta).numpy(), '.', label='Predicted (pinv)')\nplt.plot((X_test[perm[:,0]] @ theta_gd).numpy(), '.', label='Predicted (G.D.)')\nplt.xlabel('House Number')\nplt.ylabel('House Price ($,000s)')\nplt.legend()\nplt.show()\n```\n\n\n```\n\n```\n", "meta": {"hexsha": "3bae05b511fb3fcb1dc0ec5a6c97241ac9a753b2", "size": 133282, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "1_1_linear_regression_submit_29299675.ipynb", "max_stars_repo_name": "mjjackey/DL_Lab_Soton", "max_stars_repo_head_hexsha": "5df0dc3124e6fae6c27bfb99d70c457dd77935c5", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-11-09T09:49:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-09T09:49:16.000Z", "max_issues_repo_path": "1_1_linear_regression_submit_29299675.ipynb", "max_issues_repo_name": "mjjackey/DL_Lab_Soton", "max_issues_repo_head_hexsha": "5df0dc3124e6fae6c27bfb99d70c457dd77935c5", "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": "1_1_linear_regression_submit_29299675.ipynb", "max_forks_repo_name": "mjjackey/DL_Lab_Soton", "max_forks_repo_head_hexsha": "5df0dc3124e6fae6c27bfb99d70c457dd77935c5", "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": 133282.0, "max_line_length": 133282, "alphanum_fraction": 0.8918833751, "converted": true, "num_tokens": 4817, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109713976399, "lm_q2_score": 0.9362850088593058, "lm_q1q2_score": 0.8898555447750206}} {"text": "```python\n\n```\n\nSupport the display of mathematical expressions typeset in LaTeX, which is rendered in the browser thanks to the `MathJax library`.\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\n\n\n\n\\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\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\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\n\n```python\n\n```\n\nTo insert a mathematical formula we use the dollar symbol $, as follows:\nEuler's identity: $ e^{i \\pi} + 1 = 0 $\nTo isolate and center the formulas and enter in math display mode, we use 2 dollars symbol:\n$$\n...\n$$\nEuler's identity: $$ e^{i \\pi} + 1 = 0 $$\n\n\n```python\n\n```\n", "meta": {"hexsha": "ee672dac9bbb29611e9aa190e801536f899d5bce", "size": 5106, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "02_Latex_Format.ipynb", "max_stars_repo_name": "erkundanec/Jupyter-Notebook-Formatting", "max_stars_repo_head_hexsha": "38b04f5c7bd05ebced0409d014dcdb3192a76ceb", "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_Latex_Format.ipynb", "max_issues_repo_name": "erkundanec/Jupyter-Notebook-Formatting", "max_issues_repo_head_hexsha": "38b04f5c7bd05ebced0409d014dcdb3192a76ceb", "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_Latex_Format.ipynb", "max_forks_repo_name": "erkundanec/Jupyter-Notebook-Formatting", "max_forks_repo_head_hexsha": "38b04f5c7bd05ebced0409d014dcdb3192a76ceb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.0549450549, "max_line_length": 156, "alphanum_fraction": 0.4841363102, "converted": true, "num_tokens": 910, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109770159683, "lm_q2_score": 0.9362850026367633, "lm_q1q2_score": 0.8898555441214047}} {"text": "## Visualizing Attractors\n\nAn [attractor](https://en.wikipedia.org/wiki/Attractor#Strange_attractor) is a set of values to which a numerical system tends to evolve. An attractor is called a [strange attractor](https://en.wikipedia.org/wiki/Attractor#Strange_attractor) if the resulting pattern has a fractal structure. This notebook shows how to calculate and plot two-dimensional attractors of a variety of types, using code and parameters primarily from [Lázaro Alonso](https://lazarusa.github.io/Webpage/codepython2.html), [François Pacull](https://aetperf.github.io/2018/08/29/Plotting-Hopalong-attractor-with-Datashader-and-Numba.html), [Jason Rampe](https://softologyblog.wordpress.com/2017/03/04/2d-strange-attractors), [Paul Bourke](http://paulbourke.net/fractals/), and [James A. Bednar](http://github.io/jbednar).\n\n\n## Clifford Attractors\n\nFor example, a [Clifford Attractor](http://paulbourke.net/fractals/clifford) is a strange attractor defined by two iterative equations that determine the _x,y_ locations of discrete steps in the path of a particle across a 2D space, given a starting point _(x0,y0)_ and the values of four parameters _(a,b,c,d)_:\n\n\\begin{equation}\nx_{n +1} = \\sin(a y_{n}) + c \\cos(a x_{n})\\\\\ny_{n +1} = \\sin(b x_{n}) + d \\cos(b y_{n})\n\\end{equation}\n\nAt each time step, the equations define the location for the following time step, and the accumulated locations show the areas of the 2D plane most commonly visited by the imaginary particle. \n\nIt's easy to calculate these values in Python using [Numba](http://numba.pydata.org). First, we define the iterative attractor equation:\n\n\n```python\nimport numpy as np, pandas as pd, datashader as ds\nfrom datashader import transfer_functions as tf\nfrom datashader.colors import inferno, viridis\nfrom numba import jit\nfrom math import sin, cos, sqrt, fabs\n\n@jit\ndef Clifford(x, y, a, b, c, d, *o):\n return sin(a * y) + c * cos(a * x), \\\n sin(b * x) + d * cos(b * y)\n```\n\nWe then evaluate this equation 10 million times, creating a set of _x,y_ coordinates visited. The `@jit` here and above is optional, but it makes the code 50x faster.\n\n\n```python\nn=10000000\n\n@jit\ndef trajectory(fn, x0, y0, a, b=0, c=0, d=0, e=0, f=0, n=n):\n x, y = np.zeros(n), np.zeros(n)\n x[0], y[0] = x0, y0\n for i in np.arange(n-1):\n x[i+1], y[i+1] = fn(x[i], y[i], a, b, c, d, e, f)\n return pd.DataFrame(dict(x=x,y=y))\n```\n\n\n```python\n%%time\ndf = trajectory(Clifford, 0, 0, -1.3, -1.3, -1.8, -1.9)\n```\n\n\n```python\ndf.tail()\n```\n\nWe can now aggregate these 10,000,000 continuous coordinates into a discrete 2D rectangular grid with [Datashader](http://datashader.org), counting each time a point fell into that grid cell:\n\n\n```python\n%%time\n\ncvs = ds.Canvas(plot_width = 700, plot_height = 700)\nagg = cvs.points(df, 'x', 'y')\nprint(agg.values[190:195,190:195],\"\\n\")\n```\n\nA small portion of that grid is shown above, but it's difficult to see the grid's structure from the numerical values. To see the entire array at once, we can turn each grid cell into a pixel, using a greyscale value from white to black:\n\n\n```python\nds.transfer_functions.Image.border=0\n\ntf.shade(agg, cmap = [\"white\", \"black\"])\n```\n\nAs you can see, the most-visited areas of the plane have an interesting structure for this set of parameters. To explore further, let's wrap up the above aggregation and shading commands into a function so we can apply them more easily:\n\n\n```python\ndef dsplot(fn, vals, n=n, cmap=viridis, label=True):\n \"\"\"Return a Datashader image by collecting `n` trajectory points for the given attractor `fn`\"\"\"\n lab = (\"{}, \"*(len(vals)-1)+\" {}\").format(*vals) if label else None\n df = trajectory(fn, *vals, n=n)\n cvs = ds.Canvas(plot_width = 300, plot_height = 300)\n agg = cvs.points(df, 'x', 'y')\n img = tf.shade(agg, cmap=cmap, name=lab)\n return img\n```\n\nAnd let's load some colormaps that we can use for subsequent plots:\n\n\n```python\nfrom colorcet import palette\npalette[\"viridis\"]=viridis\npalette[\"inferno\"]=inferno\n```\n\nWe can now use these colormaps with a pre-selected set of Clifford attractor parameter values (stored in a separate [YAML-format text file](https://raw.githubusercontent.com/pyviz/datashader/master/examples/topics/attractors.yml)) to show a wide variety of trajectories that these equations can form:\n\n\n```python\nimport yaml\nvals = yaml.load(open(\"attractors.yml\",\"r\"))\n\ndef args(name):\n \"\"\"Return a list of available argument lists for the given type of attractor\"\"\"\n return [v[1:] for v in vals if v[0]==name] \n\ndef plot(fn, vals=None, **kw):\n \"\"\"Plot the given attractor `fn` once per provided set of arguments.\"\"\"\n vargs=args(fn.__name__) if vals is None else vals\n return tf.Images(*[dsplot(fn, v[1:], cmap=palette[v[0]][::-1], **kw) for v in vargs]).cols(4)\n```\n\n\n```python\nplot(Clifford)\n```\n\nHere the values shown are the arguments for the first call to `Clifford(x, y, a, b, c, d)`, with each subsequent call using the _x,y_ location of the previous call. \n\nRandomly sampling the parameter space typically yields much less dramatic patterns, such as all trajectory locations being on a small number of points:\n\n\n```python\nimport numpy.random\nnumpy.random.seed(21)\nnum = 4\n\nrvals=np.c_[np.zeros((num,2)), numpy.random.random((num,4))*4-2]\nplot(Clifford, vals=[[\"kbc\"]+list(rvals[i]) for i in range(len(rvals))], label=True)\n```\n\nIf you wish, Datashader could easily be used to filter out such uninteresting examples, by applying a criterion to the aggregate array before shading and showing only those that remain (e.g. rejecting those where 80% of the pixel bins are empty).\n\n\n## De Jong attractors\n\nA variety of other sets of attractor equations have been proposed, such as these from [Peter de Jong](http://paulbourke.net/fractals/peterdejong):\n\n\n```python\n@jit\ndef De_Jong(x, y, a, b, c, d, *o):\n return sin(a * y) - cos(b * x), \\\n sin(c * x) - cos(d * y)\n\nplot(De_Jong)\n```\n\n## Svensson attractors\n\nFrom [Johnny Svensson](http://paulbourke.net/fractals/peterdejong/):\n\n\n```python\n@jit\ndef Svensson(x, y, a, b, c, d, *o):\n return d * sin(a * x) - sin(b * y), \\\n c * cos(a * x) + cos(b * y)\n\nplot(Svensson)\n```\n\n## Bedhead Attractor\n\nFrom [Ivan Emrich](https://www.deviantart.com/jaguarfacedman) and [Jason Rampe](https://softologyblog.wordpress.com/2017/03/04/2d-strange-attractors):\n\n\n```python\n@jit\ndef Bedhead(x, y, a, b, *o):\n return sin(x*y/b)*y + cos(a*x-y), \\\n x + sin(y)/b\n\nplot(Bedhead)\n```\n\n## Fractal Dream Attractor\n\nFrom Clifford A. Pickover's book “Chaos In Wonderland”, with parameters from [Jason Rampe](https://softologyblog.wordpress.com/2017/03/04/2d-strange-attractors):\n\n\n```python\n@jit\ndef Fractal_Dream(x, y, a, b, c, d, *o):\n return sin(y*b)+c*sin(x*b), \\\n sin(x*a)+d*sin(y*a)\n\nplot(Fractal_Dream)\n```\n\n## Hopalong attractors\n\nFrom Barry Martin, here with code for two variants from [François Pacull](https://aetperf.github.io/2018/08/29/Plotting-Hopalong-attractor-with-Datashader-and-Numba.html):\n\n\n```python\n@jit\ndef Hopalong1(x, y, a, b, c, *o):\n return y - sqrt(fabs(b * x - c)) * np.sign(x), \\\n a - x\n@jit\ndef Hopalong2(x, y, a, b, c, *o):\n return y - 1.0 - sqrt(fabs(b * x - 1.0 - c)) * np.sign(x - 1.0), \\\n a - x - 1.0\n\nplot(Hopalong1)\n```\n\n\n```python\nplot(Hopalong2)\n```\n\n## Gumowski-Mira Attractor\n\nFrom [I. Gumowski and C. Mira](http://kgdawiec.bplaced.net/badania/pdf/cacs_2010.pdf), with code and parameters from [Jason Rampe](https://softologyblog.wordpress.com/2017/03/04/2d-strange-attractors) and [Lázaro Alonso](https://lazarusa.github.io/Webpage/codepython2.html):\n\n\n```python\n@jit\ndef G(x, mu):\n return mu * x + 2 * (1 - mu) * x**2 / (1.0 + x**2)\n\n@jit\ndef Gumowski_Mira(x, y, a, b, mu, *o):\n xn = y + a*(1 - b*y**2)*y + G(x, mu)\n yn = -x + G(xn, mu)\n return xn, yn\n\nplot(Gumowski_Mira)\n```\n\n## Symmetric Icon Attractor\n\nThe Hopalong and Gumowski-Mira equations often result in symmetric patterns, but a different approach is to *force* the patterns to be symmetric, which is often pleasing. Examples from “Symmetry in Chaos” by Michael Field and Martin Golubitsky, with code and parameters from [Jason Rampe](https://softologyblog.wordpress.com/2017/03/04/2d-strange-attractors):\n\n\n```python\n@jit\ndef Symmetric_Icon(x, y, a, b, g, om, l, d, *o):\n zzbar = x*x + y*y\n p = a*zzbar + l\n zreal, zimag = x, y\n \n for i in range(1, d-1):\n za, zb = zreal * x - zimag * y, zimag * x + zreal * y\n zreal, zimag = za, zb\n \n zn = x*zreal - y*zimag\n p += b*zn\n \n return p*x + g*zreal - om*y, \\\n p*y - g*zimag + om*x\n\nplot(Symmetric_Icon)\n```\n\n## Interactive plotting\n\nIf you are running a live Python process, you can use Datashader with HoloViews and Bokeh to zoom in and see the individual steps in any of these calculations:\n\n\n```python\nimport holoviews as hv\nfrom holoviews.operation.datashader import datashade, dynspread\nhv.extension('bokeh')\n\ndynspread(datashade(hv.Points(trajectory(Clifford, *(args(\"Clifford\")[5][1:]))), \n cmap=viridis[::-1]).opts(width=400,height=400))\n```\n\nEach time you zoom in in a live process, the data will be reaggregated, which should take a small fraction of a second for 10 million points. Eventually, once you zoom in enough you should see individual data points, as we are not connecting the points into a trajectory here. \n\nYou can also try \"connecting the dots\", which will reveal how the particle jumps discretely from one region of the space to another:\n\n\n```python\ndynspread(datashade(hv.Path([trajectory(Clifford, *(args(\"Clifford\")[5][1:]))]), \n cmap=viridis[::-1]).opts(width=400,height=400))\n```\n\nAgain, if you zoom in on a live server, the plot will update so that you can see the individual traces involved. \n\nOn the live server, you can also explore to find your own parameter values that generate interesting patterns:\n\n\n```python\ndef hv_clif(a,b,c,d,x0=0,y0=0,n=n):\n return datashade(hv.Points(trajectory(Clifford, x0, y0, a, b, c, d, n)), \n cmap=inferno[::-1], dynamic=False)\n\nx0,y0,a,b,c,d = args(\"Clifford\")[6][1:]\n\ndm = hv.DynamicMap(hv_clif, kdims=['a', 'b', 'c', 'd'])\ndm = dm.redim.range(a=(-2.0, 2.0), b=(-2.0,2.0), c=(-2.0,2.0), d=(-2.0,2.0))\ndm = dm.redim.default(a=a, b=b, c=c, d=d).opts(width=500,height=500)\ndm\n```\n\nAlthough many of the regions of this four-dimensional parameter space generate uninteresting trajectories such as single points, you can find interesting regions by starting with one of the _a,b,c,d_ tuples of values in previous plots, then click on one slider and use the left and right arrow keys to see how the plot changes as that parameter changes.\n", "meta": {"hexsha": "a197035bf3727f08c905831b619b0d5e0e2657e5", "size": 16312, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "examples/topics/strange_attractors.ipynb", "max_stars_repo_name": "av-fti/datashade_av", "max_stars_repo_head_hexsha": "53bbffb85bcb33dbb9e6c15c73599eb146105967", "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": "examples/topics/strange_attractors.ipynb", "max_issues_repo_name": "av-fti/datashade_av", "max_issues_repo_head_hexsha": "53bbffb85bcb33dbb9e6c15c73599eb146105967", "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": "examples/topics/strange_attractors.ipynb", "max_forks_repo_name": "av-fti/datashade_av", "max_forks_repo_head_hexsha": "53bbffb85bcb33dbb9e6c15c73599eb146105967", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-07-24T09:01:16.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-24T09:01:16.000Z", "avg_line_length": 32.4294234592, "max_line_length": 812, "alphanum_fraction": 0.5674350172, "converted": true, "num_tokens": 3193, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966732132748, "lm_q2_score": 0.9399133523506772, "lm_q1q2_score": 0.8897188524438876}} {"text": "# Tutorial\n\nWe will solve the following problem using a computer to using a programming\ntechnique called **recursion**.\n\n```{admonition} Problem\n\nA sequence $a_1, a_2, a_3, …$ is defined by:\n\n$$\n \\left\\{\n \\begin{array}{l}\n a_1 = k,\\\\\n a_{n + 1} = 2a_n – 7, n \\geq 1,\n \\end{array}\n \\right.\n$$\n\nwhere $k$ is a constant.\n\n\n1. Write down an expression for $a_2$ in terms of $k$.\n2. Show that $a_3 = 4k -21$\n3. Given that $\\sum_{r=1}^4 a_r = 43$ find the value of $k$.\n```\n\nWe will use a Python to define a function that reproduces the mathematical\ndefinition of $a_k$:\n\n\n```python\ndef generate_a(k_value, n):\n \"\"\"\n Uses recursion to return a_n for a given value of k:\n\n a_1 = k\n a_n = 2a_n - 7\n \"\"\"\n if n == 1:\n return k_value\n return 2 * generate_a(k_value, n - 1) - 7\n```\n\n```{attention}\nThis is similar to the mathematical definition the Python definition of\nthe function refers to itself.\n```\n\n\nWe can use this to compute $a_3$ for $k=4$:\n\n\n```python\ngenerate_a(k_value=4, n=3)\n```\n\n\n\n\n -5\n\n\n\nWe can use this to compute $a_5$ for $k=1$:\n\n\n```python\ngenerate_a(k_value=1, n=5)\n```\n\n\n\n\n -89\n\n\n\nFinally it is also possible to pass a symbolic value to `k_value`. This allows\nus to answer the first question:\n\n\n```python\nimport sympy as sym\n\nk = sym.Symbol(\"k\")\ngenerate_a(k_value=k, n=2)\n```\n\n\n\n\n$\\displaystyle 2 k - 7$\n\n\n\nLikewise for $a_3$:\n\n\n```python\ngenerate_a(k_value=k, n=3)\n```\n\n\n\n\n$\\displaystyle 4 k - 21$\n\n\n\nFor the last question we start by computing the sum:\n\n$$\n \\sum_{r=1}^4 a_r = 43\n$$\n\n\n```python\nsum_of_first_four_terms = sum(generate_a(k_value=k, n=r) for r in range(1, 5))\nsum_of_first_four_terms\n```\n\n\n\n\n$\\displaystyle 15 k - 77$\n\n\n\nThis allows us to create the given equation and solve it:\n\n\n```python\nequation = sym.Eq(sum_of_first_four_terms, 43)\nsym.solveset(equation, k)\n```\n\n\n\n\n$\\displaystyle \\left\\{8\\right\\}$\n\n\n\n```{important}\nIn this tutorial we have\n\n- Defined a function using recursion.\n- Called this function using both numeric and symbolic values.\n```\n", "meta": {"hexsha": "266a214709445fd83de9ff82fe111269adf7c82c", "size": 5594, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "book/tools-for-mathematics/07-sequences/tutorial/.main.md.bcp.ipynb", "max_stars_repo_name": "daffidwilde/pfm", "max_stars_repo_head_hexsha": "dcf38faccee3c212c8394c36f4c093a2916d283e", "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": "book/tools-for-mathematics/07-sequences/tutorial/.main.md.bcp.ipynb", "max_issues_repo_name": "daffidwilde/pfm", "max_issues_repo_head_hexsha": "dcf38faccee3c212c8394c36f4c093a2916d283e", "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": "book/tools-for-mathematics/07-sequences/tutorial/.main.md.bcp.ipynb", "max_forks_repo_name": "daffidwilde/pfm", "max_forks_repo_head_hexsha": "dcf38faccee3c212c8394c36f4c093a2916d283e", "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": 19.7667844523, "max_line_length": 87, "alphanum_fraction": 0.4692527708, "converted": true, "num_tokens": 652, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9637799472560582, "lm_q2_score": 0.923039171184527, "lm_q1q2_score": 0.8896066437194992}} {"text": "# 15.7. Analyzing a nonlinear differential system — Lotka-Volterra (predator-prey) equations\n\n\n```python\nfrom sympy import *\ninit_printing(pretty_print=True)\n\nvar('x y')\nvar('a b c d', positive=True)\n```\n\n\n```python\nf = x * (a - b * y)\ng = -y * (c - d * x)\n```\n\n\n```python\nsolve([f, g], (x, y))\n```\n\n\n```python\n(x0, y0), (x1, y1) = _\n```\n\n\n```python\nM = Matrix((f, g))\nM\n```\n\n\n```python\nJ = M.jacobian((x, y))\nJ\n```\n\n\n```python\nM0 = J.subs(x, x0).subs(y, y0)\nM0\n```\n\n\n```python\nM0.eigenvals()\n```\n\n\n```python\nM1 = J.subs(x, x1).subs(y, y1)\nM1\n```\n\n\n```python\nM1.eigenvals()\n```\n", "meta": {"hexsha": "d573361a0f669882d49d3c9d610bd18a4f406754", "size": 2712, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "001-Jupyter/001-Tutorials/002-IPython-Cookbook/chapter15_symbolic/07_lotka.ipynb", "max_stars_repo_name": "jhgoebbert/jupyter-jsc-notebooks", "max_stars_repo_head_hexsha": "bcd08ced04db00e7a66473b146f8f31f2e657539", "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": "001-Jupyter/001-Tutorials/002-IPython-Cookbook/chapter15_symbolic/07_lotka.ipynb", "max_issues_repo_name": "jhgoebbert/jupyter-jsc-notebooks", "max_issues_repo_head_hexsha": "bcd08ced04db00e7a66473b146f8f31f2e657539", "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": "001-Jupyter/001-Tutorials/002-IPython-Cookbook/chapter15_symbolic/07_lotka.ipynb", "max_forks_repo_name": "jhgoebbert/jupyter-jsc-notebooks", "max_forks_repo_head_hexsha": "bcd08ced04db00e7a66473b146f8f31f2e657539", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-13T18:49:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-13T18:49:12.000Z", "avg_line_length": 16.5365853659, "max_line_length": 98, "alphanum_fraction": 0.4568584071, "converted": true, "num_tokens": 227, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9736446471538802, "lm_q2_score": 0.91367652458901, "lm_q1q2_score": 0.8895962573962503}} {"text": "# Solving Non Linear Systems using Newton's Method\n\nWe'll be finding the roots of the following system of equations: \n\n$f(\\bar{v},\\theta)$ = 0.5$\\bar{v}^{2}$ + $\\sin(\\theta)$ = 0\n\n$g(\\bar{v},\\theta)$ = 0.5$\\bar{v}^{2}$ - $\\cos(\\theta)$ = 0\n\n\n```python\nfrom numpy.linalg import inv\nimport numpy as np\nimport math\n```\n\n\n```python\ndef f(v_bar, theta):\n return 0.5*(v_bar**2) + math.sin(theta)\n\ndef g(v_bar, theta):\n return 0.5*(v_bar**2) - math.cos(theta)\n```\n\nThe Jacobian Matrix is calculated as follows: \n\\begin{equation}\nJ = \n\\begin{bmatrix}\n\\frac{df(\\bar{v},\\theta)}{d\\bar{v}} & \\frac{df(\\bar{v},\\theta)}{d\\theta} \newline \\\\\n \\frac{dg(\\bar{v},\\theta)}{d\\bar{v}} & \\frac{dg(\\bar{v},\\theta)}{d\\theta} \\ \\\\\n \\end{bmatrix}\n\\end{equation}\n\n\n```python\ndef jacobian(v_bar,theta):\n array = np.array([[v_bar, math.cos(theta)],[v_bar, math.sin(theta)]])\n return array\n```\n\nAssuming the initial point as \n\\begin{equation}\nx_{0} = \n\\begin{bmatrix}\n0 \\\\\n0 \\\\\n\\end{bmatrix}\n\\end{equation}\n\nAnd the reiterating solution as\n\\begin{equation}\nx_{n} = \n\\begin{bmatrix}\n\\bar{v}_{n} \\\\\n\\theta_{n} \\\\\n\\end{bmatrix}\n\\end{equation}\n\nThe next point is \\begin{equation}\nx_{n+1} = \nx_{n} - J(\\bar{v}_{n},\\theta_{n})^{-1}F(\\bar{v}_{n},\\theta_{n})\n\\end{equation}\n\nwhere \\begin{equation}\nF(\\bar{v}_{n},\\theta_{n}) = \n\\begin{bmatrix}\nf(\\bar{v}_{n},\\theta_{n}) \\\\\ng(\\bar{v}_{n},\\theta_{n}) \\\\\n\\end{bmatrix}\n\\end{equation}\n\n\n```python\ndef next_x(old_x):\n \n inverse_jacobian = inv(jacobian(old_x[0][0],old_x[1][0]))\n F = np.array([[f(old_x[0][0],old_x[1][0])],[g(old_x[0][0],old_x[1][0])]])\n \n next_x = old_x - np.matmul(inverse_jacobian,F)\n return next_x\n```\n\nRunning 10 iterations of the algorithm\n\n\n```python\nall_x = []\n\nx = np.array([[1],[0]])\nall_x.append(x)\n\nfor _ in range(10):\n x = next_x(x)\n all_x.append(x)\n```\n\n\n```python\nfinal_x = np.array(all_x).reshape(11,2)\n```\n\n\n```python\nprint('Final Solution:',all_x[10][0][0],',',all_x[10][1][0])\n```\n\n Final Solution: 1.189207115002721 , -0.7853981633974483\n\n\n# Visualizing the convergence of the solution to the true solution\n\n\n```python\nimport matplotlib.pyplot as plt\n\nplt.figure(figsize=(12,6))\nplt.plot(range(11),final_x[:,0])\nplt.title('Convergence of the Value of v bar')\nplt.axhline(1.18920712, color='red')\nplt.show()\n```\n\n\n```python\nimport matplotlib.pyplot as plt\n\nplt.figure(figsize=(12,6))\nplt.plot(range(11),final_x[:,1])\nplt.title('Convergence of the Value of theta')\nplt.axhline(-0.78539816, color='red')\nplt.show()\n```\n", "meta": {"hexsha": "1f102dd252c3b9629f3553da866ada9ca6eb978e", "size": 39067, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Newton-Method-of-solving-non-linear-systems.ipynb", "max_stars_repo_name": "sohitmiglani/Practical-Simulations-and-Social-Networks", "max_stars_repo_head_hexsha": "5b6741794004d8347ecfe90f21ea5828b174a71c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-01-16T13:36:05.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-23T19:25:37.000Z", "max_issues_repo_path": "Newton-Method-of-solving-non-linear-systems.ipynb", "max_issues_repo_name": "sohitmiglani/Practical-Simulations-and-Social-Networks", "max_issues_repo_head_hexsha": "5b6741794004d8347ecfe90f21ea5828b174a71c", "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": "Newton-Method-of-solving-non-linear-systems.ipynb", "max_forks_repo_name": "sohitmiglani/Practical-Simulations-and-Social-Networks", "max_forks_repo_head_hexsha": "5b6741794004d8347ecfe90f21ea5828b174a71c", "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.8684210526, "max_line_length": 17688, "alphanum_fraction": 0.8968694806, "converted": true, "num_tokens": 892, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9697854146791214, "lm_q2_score": 0.9173026488471135, "lm_q1q2_score": 0.8895867296984544}} {"text": "# Least square estimation of sinusoid parameters\n\nThe signal paramters for a function\n$$x = o + g t + \\hat{x} \\sin \\left( \\omega t + \\phi \\right)$$\nfor a known frequency $\\omega$ at discrete from a given series of data points $x_i$ sampled at discrete time intervals $t_i$ will be estimated.\n\nThe sunusoidal function can be expressed as\n$$ \\hat{x} \\sin \\left( \\omega t + \\phi \\right) = a \\sin \\left( \\omega t \\right) + b \\cos \\left( \\omega t \\right) $$\nwith\n$$ \\phi = \\text{arctan2} \\left( b, a \\right) \\quad \\text{and} \\quad \\hat{x} = \\sqrt{a^2 + b^2} \\text{.}$$\n\nTherefore the problem can be rewritten as\n$$x = c_0 + c_1 t + c_2 \\sin \\left( \\omega t \\right) + c_3 \\cos \\left( \\omega t \\right) \\text{.}$$\nOnly the parameters $c_i$ have to be estimate, which means the problem can be solved using a linear least square.\n\n## Linear least square\n\nFor a sinusoidal signal described above sampled at discreet time intervals the error term is\n$$e_i = c_0 + c_1 t_i + c_2 \\sin \\left( \\omega t_i \\right) + c_3 \\cos \\left( \\omega t_i \\right) - x_i \\text{.}$$\n\nFor the set of measured values the error term can be expressed in matrix notation\n$$\\mathbf{e} = \\mathbf{V} \\mathbf{c} - \\mathbf{x}$$\nwith\n$$\\mathbf{e} = \\begin{bmatrix}\n e_1 \\\\\n e_2 \\\\\n \\vdots \\\\\n e_n \\\\\n\\end{bmatrix} \\text{,} \\quad\n\\mathbf{V} = \\begin{bmatrix}\n 1 & t_1 & \\sin \\left( \\omega t_1 \\right) & \\cos \\left( \\omega t_1 \\right) \\\\\n 1 & t_2 & \\sin \\left( \\omega t_2 \\right) & \\cos \\left( \\omega t_2 \\right) \\\\\n \\vdots & \\vdots & \\vdots & \\vdots \\\\\n 1 & t_n & \\sin \\left( \\omega t_n \\right) & \\cos \\left( \\omega t_n \\right) \\\\\n\\end{bmatrix} \\text{,} \\quad\n\\mathbf{c} = \\begin{bmatrix}\n c_1 \\\\\n c_2 \\\\\n c_3 \\\\\n c_4 \\\\\n\\end{bmatrix} \\text{,} \\quad\n\\mathbf{x} = \\begin{bmatrix}\n x_1 \\\\\n x_2 \\\\\n \\vdots \\\\\n x_n \\\\\n\\end{bmatrix} \\text{.}$$\n\nThe cost function of the least square algorithm is the squared error term (${e_i}^2$). In matrix notation the error term\n\\begin{equation}\n\\begin{split}\nJ = \\mathbf{e}^\\text{T} \\mathbf{e} & = \\left( \\mathbf{c}^\\text{T} \\mathbf{V}^\\text{T} - \\mathbf{x}^\\text{T} \\right) \\left( \\mathbf{V} \\mathbf{c} - \\mathbf{x} \\right) \\\\\n& = \\mathbf{c}^\\text{T} \\mathbf{V}^\\text{T} \\mathbf{V} \\mathbf{c} - \\mathbf{c}^\\text{T} \\mathbf{V}^\\text{T} \\mathbf{x} - \\mathbf{x}^\\text{T} \\mathbf{V} \\mathbf{c} \\\\\n\\end{split}\n\\end{equation}\nhas to be minimized. To find the minimum of $J \\left( \\mathbf{c} \\right)$\n$$ \\frac{\\text{d} J}{\\text{d} \\mathbf{c}} \\stackrel{!}{=} 0 $$\nis solved for $\\mathbf{c}$.\n\nThe following equation has to be solved for $\\mathbf{c}$:\n$$\\begin{split}\n& \\frac{\\text{d} J}{\\text{d} \\mathbf{c}} = 0 \\\\\n\\Leftrightarrow \\ &\n \\underbrace{\\frac{\\text{d} \\left( \\mathbf{c}^\\text{T} \\mathbf{V}^\\text{T} \\mathbf{V} \\mathbf{c} \\right)}{\\text{d} \\mathbf{c}}}_{= \\mathbf{V}^\\text{T} \\mathbf{V} \\mathbf{c} + \\mathbf{c}^\\text{T} \\mathbf{V}^\\text{T} \\mathbf{V}} -\n \\underbrace{\\frac{\\mathbf{c}^\\text{T} \\mathbf{V}^\\text{T} \\mathbf{x}}{\\text{d} \\mathbf{c}}}_{= \\mathbf{V}^\\text{T} \\mathbf{x}} - \n \\underbrace{\\frac{\\mathbf{x}^\\text{T} \\mathbf{V} \\mathbf{c}}{\\text{d} \\mathbf{c}}}_{= \\mathbf{x}^\\text{T} \\mathbf{V}}\n = 0 \\\\\n\\Leftrightarrow \\ & \\mathbf{V}^\\text{T} \\mathbf{V} \\mathbf{c} + \\mathbf{c}^\\text{T} \\mathbf{V}^\\text{T} \\mathbf{V} - \\mathbf{V}^\\text{T} \\mathbf{x} - \\mathbf{x}^\\text{T} \\mathbf{V} = 0 \\\\\n\\Leftrightarrow \\ & 2 \\mathbf{V}^\\text{T} \\mathbf{V} \\mathbf{c} - 2 \\mathbf{V}^\\text{T} \\mathbf{x} = 0 \\\\\n\\Leftrightarrow \\ & \\mathbf{V}^\\text{T} \\mathbf{V} \\mathbf{c} = \\mathbf{V}^\\text{T} \\mathbf{x} \\\\\n\\Leftrightarrow \\ & \\mathbf{c} = \\left( \\mathbf{V}^\\text{T} \\mathbf{V} \\right)^{-1} \\mathbf{V}^\\text{T} \\mathbf{x} \\\\\n\\end{split}$$\n\n## Python implementation of sine parameter estimator\n\nThe following python function implements a sine parameter estimator.\n\nThe frequency ($\\omega$), the signal data ($x$) and the time vector ($t$) are passed to the function and the signal parameters offset ($o$), gradiant ($g$), amplitud ($\\hat{x}$) and phase ($\\phi$) are returned.\n\n\n```python\nimport numpy as np\n\ndef estimate_sine(omega, data, t):\n func_mtrx_transp = np.array([\n len(data) * [1.],\n t,\n np.sin(omega * t),\n np.cos(omega * t),\n ])\n res = np.linalg.solve(np.dot(func_mtrx_transp, func_mtrx_transp.T),\n np.dot(func_mtrx_transp, np.array([data]).T))\n amp = np.sqrt(res[2][0]**2. + res[3][0]**2.)\n phase = np.arctan2(res[3][0], res[2][0])\n return res[0][0], res[1][0], amp, phase\n```\n\nTo test the function 'estimate_sine' a test signal is created and the paramters are estimated.\n\n\n```python\nimport matplotlib.pyplot as plt\n\n# Signal parameters\noffset = 7.5\ngradient = 2.25\nomega = 2. * np.pi * 2.\nsine_amp = 12.25\nsine_phase = np.pi * 0.2\nnoise_amp = 1.5\n\n# Create test signal\nt = np.arange(0., 2.0, 0.004)\nx = offset + gradient * t + sine_amp * np.sin(omega * t + sine_phase) \\\n + noise_amp * 2 * (np.random.random(len(t)) - 0.5)\n\n# Estimate signal parameters\nest_offset, est_grad, est_amp, est_phase = estimate_sine(omega, x, t)\nx_est = est_offset + est_grad * t + est_amp * np.sin(omega * t + est_phase)\n\n# Print results\nprint(\" Original Estimated Error\")\nprint(\"Offset: {orig_offs:>9f} {est_offs:>9f} {error:>9f}\".format(\n orig_offs=offset, est_offs=est_offset, error=offset-est_offset))\nprint(\"Gradient: {orig_grad:>9f} {est_grad:>9f} {error:>9f}\".format(\n orig_grad=gradient, est_grad=est_grad, error=gradient-est_grad))\nprint(\"Amplitude: {orig_amp:>9f} {est_amp:>9f} {error:>9f}\".format(\n orig_amp=sine_amp, est_amp=est_amp, error=sine_amp-est_amp))\nprint(\"Phase: {orig_phase:>9f} {est_phase:>9f} {error:>9f}\".format(\n orig_phase=sine_phase, est_phase=est_phase, error=sine_phase-est_phase))\n\n# Plot results\nplt.plot(t, x, 'b', linewidth=0.5, label=\"Signal\")\nplt.plot(t, x_est, 'r', linewidth=1.0, label=\"Estimated Sine\")\nplt.xlabel(\"time / s\")\nplt.ylabel(\"signal\")\nplt.legend(bbox_to_anchor=(1.4, 1.0))\nplt.grid(True)\nplt.show()\n```\n", "meta": {"hexsha": "7e52763a45164d1473576f2f0890993879734ff6", "size": 66743, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "sine_estimator.ipynb", "max_stars_repo_name": "SvenMayer/notebooks", "max_stars_repo_head_hexsha": "5de618c3497d1a88ad8bb3fbd1ae54e0f56fa2da", "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": "sine_estimator.ipynb", "max_issues_repo_name": "SvenMayer/notebooks", "max_issues_repo_head_hexsha": "5de618c3497d1a88ad8bb3fbd1ae54e0f56fa2da", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-01-14T20:10:54.000Z", "max_issues_repo_issues_event_max_datetime": "2018-01-14T20:10:54.000Z", "max_forks_repo_path": "sine_estimator.ipynb", "max_forks_repo_name": "SvenMayer/notebooks", "max_forks_repo_head_hexsha": "5de618c3497d1a88ad8bb3fbd1ae54e0f56fa2da", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-01-14T19:43:05.000Z", "max_forks_repo_forks_event_max_datetime": "2018-01-14T19:43:05.000Z", "avg_line_length": 279.2594142259, "max_line_length": 57456, "alphanum_fraction": 0.8911795994, "converted": true, "num_tokens": 2237, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9787126513110865, "lm_q2_score": 0.9086178932210351, "lm_q1q2_score": 0.889275827303053}} {"text": "# Horner's Method\n\nWhat is the best way to evaluate \n\n\\\\[ f(x) = x^3 + 4x^2 - 10 \\\\]\n\nat $ x = \\dfrac{1}{2} $? The traditional and direct approach is\n\n\\\\[ f(\\dfrac{1}{2}) = \\dfrac{1}{2} * \\dfrac{1}{2} * \\dfrac{1}{2} + 4 * \\dfrac{1}{2} * \\dfrac{1}{2} - 10 \\\\]\n\nThis procedure takes 4 multiplications and 2 additions where a subtraction can be interpreted as adding a negative number. All together it takes 6 operations to evaluate the function. Is there a way to reduce the number of operations? Rewrite the polynomial in such a way the variable $x$ is factored out:\n \n\\begin{align}\nf(x) & = -10 + 4x^2 + x^3 \\\\\n & = -10 + x * (0 + 4x + x^2 ) \\\\\n & = -10 + x * (0 + x * (4 + x))\n\\end{align}\n\nAs you can see, it takes a total of 5 operations to evaluate the function; 3 additions and 2 multiplications. This method is called **Horner's Method**.\nThe point of this notebook is to check the absolute error and relative error and to test the efficiency of using Horner's Method for numerical computations. In this case, we explore its application to find the root of the equation using Bisection Method.\n\n### Absolute and Relative Error\nTo calculate the error between the two functions we need to find the absolute and the relative error where $x^*$ is the approximate function and $x$ is the true function.\n\n**Absolute Error** $= |x^* - x| $\n\n**Relative Error** $= \\dfrac{|x^* - x|}{|x|} $\n\n\n```python\ndef error_analysis(true_fx, approx_fx):\n absolute_error = abs(approx_fx - true_fx)\n relative_error = absolute_error / abs(true_fx)\n return absolute_error, relative_error\n```\n\n#### True Function - Naive Method\n\n\n```python\ndef f(x):\n return (x ** 3) + (4 * (x ** 2)) - 10\n```\n\n#### Approximate Function - Horner's Method\n\n\n```python\ndef f_a(x):\n return -10 + 𝑥 * (0 + 𝑥 * (4 + 𝑥))\n```\n\n### Bisection Method\nBisection method is a root-finding algorithm based from the intermediate-value theorem from calculus.\nYou need to verify if a root exist by making sure the two endpoints of the interval $ [a,b] $ or $\\{f(a),f(b)\\}$ have different signs. If function $ f $ is continuous, then there will be a root $r$ between $a$ and $b$ such that $f(r) = 0$ and $a < r < b$.\n\n\n```python\nimport numpy as np\n```\n\n\n```python\ndef bisection_method(a,b):\n if f(a) * f(b) < 0: \n roots = []\n while (b - a) / 2 > 1e-7:\n c = (a + b) / 2 \n if f(a) * f(c) < 0:\n b = c\n else:\n a = c\n roots.append(c)\n return np.array(roots)\n```\n\n\n```python\n%%timeit\nroots = bisection_method(1,2)\n```\n\n 24.7 µs ± 1.49 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)\n\n\n\n```python\nroots = bisection_method(1,2)\n```\n\n\n```python\ndef bisection_method_hm(a,b):\n if f_a(a) * f_a(b) < 0: \n roots = []\n while (b - a) / 2 > 1e-7:\n c = (a + b) / 2 \n if f_a(a) * f_a(c) < 0:\n b = c\n else:\n a = c\n roots.append(c)\n return np.array(roots)\n```\n\n\n```python\n%%timeit\nroots_a = bisection_method_hm(1,2)\n```\n\n 20 µs ± 4.59 µs per loop (mean ± std. dev. of 7 runs, 100000 loops each)\n\n\n\n```python\nroots_a = bisection_method(1,2)\n```\n\nAccording to the benchmark an implementation of the Horner's Method perform faster than the naive method. Now let us look at the error analysis to find out whether results are different on a precision level.\n\n\n```python\nabsolute_error, relative_error = error_analysis(roots, roots_a)\n```\n\n\n```python\nabsolute_error\n```\n\n\n\n\n array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,\n 0., 0., 0., 0., 0., 0.])\n\n\n\n\n```python\nrelative_error\n```\n\n\n\n\n array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,\n 0., 0., 0., 0., 0., 0.])\n\n\n\nLuckily errors were not found in this example, however polynomials should always be expressed in the nested form before performing an evaluation, because this form minimizes the number of arithmetic calculations, as a result, the errors are reduced. The example \\begin{align}\nf(x) & = -10 + 4x^2 + x^3 \\\\\n & = -10 + x * (0 + 4x + x^2 ) \\\\\n & = -10 + x * (0 + x * (4 + x))\n\\end{align}\n\nhas already placed the coefficients and the variables in the rightful place. Notice we placed an additional coefficient $0$ to fill-in the missing degree.\n\n### Evaluation using Horner's Method\n\nAs an engineer we can write an algorithm to evaluate `x` given only the `degree` (or the number of terms in a polynomial) and its `coefficients`. This way we don't have to rewrite a function everytime a new polynomial is introduced.\n\nConsider the following polynomial $ P(x) = a_{k}x^{k} + a_{k-1}x^{k-1} + a_{k-2}x^{k-2} + ... + a_{1}x + a_{0} $ we can evaluate `x` using this algorithm below.\n\n\n```python\ndef evaluate(x, k, c, b=None):\n '''\n Evaluate `x` from a polynomial using Horner's Method.\n\n Parameters\n ----------\n x : int or float\n The value of x\n k : int\n degrees or the number of terms\n c : int or float\n coefficients\n b : int or float\n base points\n\n Returns\n -------\n y : int or float\n The output of the polynomial\n '''\n y = c[0]\n if b is None:\n for i in range(1, k):\n y = c[i] + (x * y)\n else:\n for i in range(1, k):\n y = (y * (x - b[i])) + c[i]\n return y\n```\n\n\n```python\n%%timeit\nevaluate(2, 4, [1, 4, 0, -10])\n```\n\n 684 ns ± 9.99 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)\n\n\n\n```python\n%%timeit\nf_a(2)\n```\n\n 160 ns ± 2.02 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)\n\n\n\n```python\n%%timeit\nf(2)\n```\n\n 581 ns ± 9.06 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)\n\n\nAlthough Horner's method is slower in comparison with functions whose polynomials are laid out, this method still is efficient as it saves time to rewrite equations and evaluate. We shall look more into the applications of Horner's Method once we get into Interpolation.\n\n### Reference\n\n- R.L. Burden and J.D. Faires. *Numerical Analysis*. Brooks/Cole, Cengage Learning, Boston, 9th edition, 2010.\n- Timothy Sauer. 2018. *Numerical Analysis (3rd. ed.)*. Pearson, UK.\n- Justin Solomon. 2015. *Numerical Algorithms: Methods for Computer Vision, Machine Learning, and Graphics*. A. K. Peters, Ltd., USA.\n\n\n```python\n\n```\n", "meta": {"hexsha": "b74ef0313df3d0fb2ccc823fae18838409234c54", "size": 11293, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "fundamentals/horners_method.ipynb", "max_stars_repo_name": "jrpespinas/numerical-analysis", "max_stars_repo_head_hexsha": "00fea39c4879893dd60e4a2b7b4dbcb5114234ea", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-01-08T04:17:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-24T16:03:28.000Z", "max_issues_repo_path": "fundamentals/horners_method.ipynb", "max_issues_repo_name": "jrpespinas/numerical-computing", "max_issues_repo_head_hexsha": "00fea39c4879893dd60e4a2b7b4dbcb5114234ea", "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": "fundamentals/horners_method.ipynb", "max_forks_repo_name": "jrpespinas/numerical-computing", "max_forks_repo_head_hexsha": "00fea39c4879893dd60e4a2b7b4dbcb5114234ea", "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.9522673031, "max_line_length": 314, "alphanum_fraction": 0.5033206411, "converted": true, "num_tokens": 1967, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067179697695, "lm_q2_score": 0.9433475727011219, "lm_q1q2_score": 0.8891114246512829}} {"text": "```python\nimport numpy as np\n```\n\n### Matrices\n\n\n```python\nmatrix_01 = np.matrix(\"1, 2, 3; 4, 5, 6\"); matrix_01\n```\n\n\n\n\n matrix([[1, 2, 3],\n [4, 5, 6]])\n\n\n\n\n```python\nmatrix_02 = np.matrix([[1, 2, 3], [4, 5, 6]]); matrix_02\n```\n\n\n\n\n matrix([[1, 2, 3],\n [4, 5, 6]])\n\n\n\n### Math Operations with Arrays and Matrices\n\n\n```python\narray_01 = np.array([[1, 2], [3, 4]]); array_01\n```\n\n\n\n\n array([[1, 2],\n [3, 4]])\n\n\n\n\n```python\ntype(array_01)\n```\n\n\n\n\n numpy.ndarray\n\n\n\n\n```python\narray_01 * array_01\n```\n\n\n\n\n array([[ 1, 4],\n [ 9, 16]])\n\n\n\n\n```python\nmatrix_01 = np.mat(array_01); matrix_01\n```\n\n\n\n\n matrix([[1, 2],\n [3, 4]])\n\n\n\n\n```python\ntype(matrix_01)\n```\n\n\n\n\n numpy.matrix\n\n\n\n\n```python\nmatrix_01 * matrix_01\n```\n\n\n\n\n matrix([[ 7, 10],\n [15, 22]])\n\n\n\n### The multiplications results between arrays and matrices are different. The math is the following:\n\n## $$ \\boxed{ \\begin{align} \\begin{pmatrix} 1 & 2 \\\\ 3 & 4 \\end{pmatrix} & \\begin{pmatrix} 1 & 2 \\\\ 3 & 4 \\end{pmatrix} = \\begin{pmatrix} 7 & 10 \\\\ 15 & 22 \\end{pmatrix} \\end{align} }$$\n\n### A matrix apply the multiplication from lines to columns, resulting in the following operations:\n\n\n```python\nfrom IPython.display import Image\nImage('aux/images/matrix-multiplication.png')\n```\n\n### To do the same operation with an array object:\n\n\n```python\narray_01 = np.array([[1, 2], [3, 4]]); array_01\n```\n\n\n\n\n array([[1, 2],\n [3, 4]])\n\n\n\n\n```python\nnp.dot(array_01, array_01)\n```\n\n\n\n\n array([[ 7, 10],\n [15, 22]])\n\n\n\n### Conversions\n\n\n```python\narray_01 = np.array([[1, 2], [3, 4]]); array_01\n```\n\n\n\n\n array([[1, 2],\n [3, 4]])\n\n\n\n\n```python\n# Array to Matrix\nmatrix_01 = np.asmatrix(array_01); matrix_01\n```\n\n\n\n\n matrix([[1, 2],\n [3, 4]])\n\n\n\n\n```python\n# Matrix to Array\narray_02 = np.asarray(matrix_01); array_02\n```\n\n\n\n\n array([[1, 2],\n [3, 4]])\n\n\n", "meta": {"hexsha": "b801552fa4e6a7665d76c23257067f5306883fc5", "size": 26029, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "modules/02-data-organization-and-visualization/06-numpy-array-matrix-math-operations.ipynb", "max_stars_repo_name": "cfascina/rtaps", "max_stars_repo_head_hexsha": "d54c83a2100ac3a300041e2d589c86e5ca0c4a8e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-07-27T14:25:23.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-02T22:12:03.000Z", "max_issues_repo_path": "modules/02-data-organization-and-visualization/06-numpy-array-matrix-math-operations.ipynb", "max_issues_repo_name": "cfascina/rtaps", "max_issues_repo_head_hexsha": "d54c83a2100ac3a300041e2d589c86e5ca0c4a8e", "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": "modules/02-data-organization-and-visualization/06-numpy-array-matrix-math-operations.ipynb", "max_forks_repo_name": "cfascina/rtaps", "max_forks_repo_head_hexsha": "d54c83a2100ac3a300041e2d589c86e5ca0c4a8e", "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": 68.6781002639, "max_line_length": 19140, "alphanum_fraction": 0.8267317223, "converted": true, "num_tokens": 677, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541610257063, "lm_q2_score": 0.9441768604361741, "lm_q1q2_score": 0.8890880693739109}} {"text": "# Functions as Real-valued Circuits\n\n## Base Case: Single Gate in the Circuit\n\n### Single Multiply Gate\n\nThe first thing we are going to compute is a simple function of two variables $F = f(X,Y)=X*Y$.\n\n\n\nThe circuit takes two real-valued inputs $X$ and $Y$, computes the product $X*Y$ defined by the function $f$ and stores it in the variable $F$.\n\n\n```python\ndef f(X,Y):\n return X*Y\n```\n\n\n```python\nF = f(-2,3)\nprint (f'The output F is: {F}')\n```\n\n The output F is: -6\n\n\n### *How should one tweak the inputs $(X,Y)$ slightly to increase the output of the function __f__?* \n\n### Strategy #1 - Numerical Gradient\n\nThe partial derivative of the function $f$ with respect to $X$ can be computed as:\n\n\\begin{align}\n\\frac{\\partial f (X,Y)}{\\partial X} = \\lim_{h\\to 0} \\frac{f(X+h,Y)-f(X,Y)}{h} \\\\\n\\end{align}\n\nThis can be simulated in code by choosing $h$ to be a very small number:\n\n\n```python\nh = 0.0001\n```\n\n#### Computing a partial derivative with respect to $X$\n\n\n```python\nX = -2; Y = 3\n```\n\n\n```python\nX_derivative = (f(X+h, Y)-f(X, Y))/h\nprint (f'the derivative in respect to X is: {X_derivative}')\n```\n\n the derivative in respect to X is: 3.00000000000189\n\n\nPositive derivative value indicates that $X$ should be increased in order to increase $f$, let's try that:\n\n\n```python\nprint (f'the original output is: {f(-2,3)}')\n# increase X for a small value, for example 0.2\nprint (f'the new output is: {f(-1.8,3)}')\n```\n\n the original output is: -6\n the new output is: -5.4\n\n\n$-5.4$ is larger than $-6$, it works!\n\n#### compute a partial derivative with respect to $Y$\n\n\n```python\nY_derivative = (f(X, Y+h)-f(X, Y))/h\nprint (f'the derivative in respect to Y is: {Y_derivative}')\n```\n\n the derivative in respect to Y is: -2.0000000000042206\n\n\nNegative derivative value indicates that $Y$ should be decreased in order to increase $f$, let's try that:\n\n\n```python\nprint (f'the original output is: {f(-2,3)}')\n# decrease Y for a small value, for example 0.1\nprint (f'the new output is: {f(-2,2.9)}')\n```\n\n the original output is: -6\n the new output is: -5.8\n\n\n$-5.8$ is larger than $-6$, it works!\n\nThe __gradient__ of a function is made up of all the partial derivatives of this function concatenated in a vector\n\n\\begin{align}\n\\nabla f(X,Y)=\\left[\\frac{\\partial f (X,Y)}{\\partial X},\\frac{\\partial f (X,Y)}{\\partial Y}\\right]\n\\end{align}\n\n#### Gradually minimizing a function by using derivatives\n\nIn order to gradually maximize the function $f$ (step-by-step) towards our desired result, we need to update our parameters. This is done by adding to the parameter's value the value of its partial derivative. To achieve this gradually in small steps, we multiply the value of the partial derivative by a a small number (step).\n\n\n```python\nstep_size = 0.01\nF = f(X,Y)\nprint (f'The original output F is: {F}')\n```\n\n The original output F is: -6\n\n\n\n```python\nX = X + step_size * X_derivative\nY = Y + step_size * Y_derivative\nprint (f'X is: {X}, Y is: {Y}')\n```\n\n X is: -1.969999999999981, Y is: 2.979999999999958\n\n\n\n```python\nF_new = f(X,Y)\nprint (f'old output: {F}\\nnew output: {F_new}')\n```\n\n old output: -6\n new output: -5.87059999999986\n\n\nThe new output is larger than the old, thanks to partial derivatives.\n\nThis approach, however, is still expensive because we need to compute the circuit’s output as we tweak every input value independently a small amount. \n\n### Strategy #2 - Analytic Gradient\n\nWe can use calculus to compute partial derivatives of the function $f(X,Y)$.\n\n\\begin{align}\n\\frac{\\partial F}{\\partial X}=\\frac{\\partial f (X,Y)}{\\partial X} = \\lim_{h\\to 0} \\frac{f(X+h,Y)-f(X,Y)}{h} \\\\\n\\end{align}\n\nA partial derivative of $F=f(X,Y)$ in respect to $X$ is:\n\n\\begin{align*}\n\\frac{\\partial F}{\\partial X}=\\frac{\\partial f (X,Y)}{\\partial X} &= \\lim_{h\\to 0} \\frac{f(X+h,Y)-f(X,Y)}{h} \\\\\\\\\n&=\\lim_{h\\to 0}\\frac{(X+h)Y -XY}{h} \\\\\n&=\\lim_{h\\to 0}\\frac{XY+Yh-XY}{h} \\\\\n&=\\lim_{h\\to 0}\\frac{Yh}{h} \\\\\n\\frac{\\partial F}{\\partial X}=\\frac{\\partial f (X,Y)}{\\partial X}&=Y\n\\end{align*}\n\nA partial derivative of $F=f(X,Y)$ in respect to $Y$ is:\n\n\\begin{align*}\n\\frac{\\partial F}{\\partial Y}=\\frac{\\partial f (X,Y)}{\\partial Y} &= \\lim_{h\\to 0} \\frac{f(X,Y+h)-f(X,Y)}{h} \\\\\\\\\n&=\\lim_{h\\to 0}\\frac{X(Y+h) -XY}{h} \\\\\n&=\\lim_{h\\to 0}\\frac{XY+Xh-XY}{h} \\\\\n&=\\lim_{h\\to 0}\\frac{Xh}{h} \\\\\n\\frac{\\partial F}{\\partial Y}=\\frac{\\partial f (X,Y)}{\\partial Y} &=X\n\\end{align*}\n\nHere are both partial derivatives:\n\n\\begin{align*}\n\\frac{\\partial F}{\\partial X}=Y ; \\frac{\\partial F}{\\partial Y}=X \\\\\n\\end{align*}\n\nWe can represent this as a gradient:\n\n\\begin{align}\n\\nabla f(X,Y)=\\left[Y,X\\right]\n\\end{align}\n\nWe can now use this information to increase the output of the function __f__:\n\n\n```python\nX = -2; Y = 3\nF = f(X,Y)\nprint (f'the output F is: {F}')\n```\n\n the output F is: -6\n\n\n\n\n\n```python\nX_gradient = Y\nY_gradient = X\nprint (f'X-gradient: {X_gradient} \\nY-gradient: {Y_gradient}')\n```\n\n X-gradient: 3 \n Y-gradient: -2\n\n\n\n\n\n```python\nstep_size = 0.001\nX = X + step_size * X_gradient\nY = Y + step_size * Y_gradient\nprint (f'X is now: {X}, \\nY is now: {Y}')\n```\n\n X is now: -1.997, \n Y is now: 2.998\n\n\n\n```python\nF_new = f(X,Y)\nprint (f'old output: {F}\\nnew output: {F_new}')\n```\n\n old output: -6\n new output: -5.987006000000001\n\n\nThe new output $-5.8706$ is larger than the old: $-6$.\n\n***\n\n### Single Add Gate\n\nThe second function we're going to compute is $G=g(X,Y)=X+Y.$\n\n\n\nThe circuit takes two real-valued inputs $X$ and $Y$ and computes the sum $X+Y$.\n\n\n```python\ndef g(X,Y):\n return X+Y\n```\n\n\n```python\nX = -2; Y = 3\nG = g(X,Y)\nprint (f'The output is: {G}')\n```\n\n The output is: 1\n\n\n\n\nAs we did before, we can use calculus to compute partial derivatives for the function $G=g(X,Y)$:\n\n\\begin{align}\n\\frac{\\partial G}{\\partial X}=\\frac{\\partial g (X,Y)}{\\partial X} = \\lim_{h\\to 0} \\frac{g(X+h,Y)-g(X,Y)}{h} \\\\\n\\end{align}\n\nA partial derivative of $G=g(X,Y)$ in respect to $X$ is:\n\n\\begin{align*}\n\\frac{\\partial G}{\\partial X}=\\frac{\\partial g (X,Y)}{\\partial X} &= \\lim_{h\\to 0} \\frac{g(X+h,Y)-g(X,Y)}{h} \\\\\\\\\n&=\\lim_{h\\to 0}\\frac{X+h+Y -X-Y}{h} \\\\\n\\frac{\\partial G}{\\partial X}=\\frac{\\partial g (X,Y)}{\\partial X}&=\\lim_{h\\to 0}\\frac{h}{h} =1 \\\\\n\\end{align*}\n\nA partial derivative of $G=g(X,Y)$ in respect to $Y$ is:\n\n\\begin{align*}\n\\frac{\\partial G}{\\partial Y}=\\frac{\\partial g (X,Y)}{\\partial Y} &= \\lim_{h\\to 0} \\frac{g(X,Y+h)-g(X,Y)}{h} \\\\\\\\\n&=\\lim_{h\\to 0}\\frac{X+Y+h -X-Y}{h} \\\\\n\\frac{\\partial G}{\\partial Y}=\\frac{\\partial g (X,Y)}{\\partial Y}&=\\lim_{h\\to 0}\\frac{h}{h} =1 \\\\\n\\end{align*}\n\nBoth partial derivatives $\\frac{\\partial G}{\\partial X}$ and $\\frac{\\partial G}{\\partial Y}$ in this case are equal to $1$.\n\nWe can use this information to maximize the function __g__:\n\n\n```python\nX_gradient = 1\nY_gradient = 1\nprint (f'X-gradient: {X_gradient} \\nY-gradient: {Y_gradient}')\n```\n\n X-gradient: 1 \n Y-gradient: 1\n\n\n\n\n\n```python\nstep_size = 0.01\nX = X + step_size * X_gradient\nY = Y + step_size * Y_gradient\nprint (f'X is: {X} \\nY is: {Y}')\n```\n\n X is: -1.99 \n Y is: 3.01\n\n\n\n```python\nF_new = g(X,Y)\nprint (f'old output: {F}\\nnew output: {F_new}')\n```\n\n old output: -6\n new output: 1.0199999999999998\n\n\n## Recursive Case: Circuits with Multiple Gates\n\nThe expression we are computing now is $M = m(X,Y,Z)=(X+Y)*Z$.\n\n\n\n\n```python\ndef m(X,Y,Z):\n return (X+Y)*Z\n```\n\n\n```python\nX = -2; Y = 5; Z = -4\n```\n\nthis is equal to $M=m(-2,5,-4)=(-2+5)-4=3*-4=-12$\n\n\n```python\nM = m(X,Y,Z)\nprint (f'the output M is: {M}')\n```\n\n the output M is: -12\n\n\n\n\nAs we did before, we can use calculus to derive partial derivatives for the function $M=m(X,Y,Z)$.\n\n\\begin{align}\n\\frac{\\partial M}{\\partial X}=\\frac{\\partial m (X,Y,Z)}{\\partial X} = \\lim_{h\\to 0} \\frac{m(X+h,Y,Z)-m(X,Y,Z)}{h} \\\\\n\\end{align}\n\nA partial derivative of $M=m(X,Y,Z)$ in respect to $X$ is:\n\n\\begin{align*}\n\\frac{\\partial M}{\\partial X}=\\frac{\\partial m(X,Y,Z)}{\\partial X} &= \\lim_{h\\to 0} \\frac{f(X+h,Y,Z)-f(X,Y,Z)}{h} \\\\\\\\\n&=\\lim_{h\\to 0}\\frac{(X+h+Y)*Z -(X+Y)*Z}{h} \\\\\n&=\\lim_{h\\to 0}\\frac{ZX+Zh+ZY-ZX-ZY}{h} \\\\\n\\frac{\\partial M}{\\partial X}=\\frac{\\partial m(X,Y,Z)}{\\partial X}&=\\lim_{h\\to 0}\\frac{Zh}{h} =Z \\\\\n\\end{align*}\n\n \n\nSimilarly, partial derivative of $M=m(X,Y,Z)$ in respect to $Y$ is:\n\n\\begin{align*}\n\\frac{\\partial M}{\\partial Y}=\\frac{\\partial m(X,Y,Z)}{\\partial Y} &= \\lim_{h\\to 0} \\frac{f(X,Y+h,Z)-f(X,Y,Z)}{h} \\\\\\\\\n&=\\lim_{h\\to 0}\\frac{(X+Y+h)*Z -(X+Y)*Z}{h} \\\\\n&=\\lim_{h\\to 0}\\frac{ZX+ZY+Zh-ZX-ZY}{h} \\\\\n\\frac{\\partial M}{\\partial Y}=\\frac{\\partial m(X,Y,Z)}{\\partial Y}&=\\lim_{h\\to 0}\\frac{Zh}{h} =Z \\\\\n\\end{align*}\n\n \n\nA partial derivative of $M=m(X,Y,Z)$ in respect to $Z$ is:\n\n\\begin{align*}\n\\frac{\\partial M}{\\partial Z}=\\frac{\\partial m(X,Y,Z)}{\\partial Z} &= \\lim_{h\\to 0} \\frac{f(X,Y,Z+h)-f(X,Y,Z)}{h} \\\\\\\\\n&=\\lim_{h\\to 0}\\frac{(X+Y)*(Z+h) -(X+Y)*Z}{h} \\\\\n&=\\lim_{h\\to 0}\\frac{XZ+Xh+YZ+Yh-XZ-YZ}{h} \\\\\n&=\\lim_{h\\to 0}\\frac{Xh+Yh}{h} \\\\\n&=\\lim_{h\\to 0}\\frac{h(X+Y)}{h}\\\\\n\\frac{\\partial M}{\\partial Z}=\\frac{\\partial m(X,Y,Z)}{\\partial Z}&=X+Y \\\\\n\\end{align*}\n\nHere are all three partial derivatives:\n\n\\begin{align*}\n\\frac{\\partial M}{\\partial X}=Z ; \\frac{\\partial M}{\\partial Y}=Z ;\\frac{\\partial M}{\\partial Z}=X+Y \\\\\n\\end{align*}\n\nWe can represent this as a gradient:\n\n\\begin{align}\n\\nabla m(X,Y,Z)=\\left[Z,Z,X+Y\\right]\n\\end{align}\n\nWe can now use this information to maximize the output of the function __m__:\n\n\n```python\nX_gradient = Z\nY_gradient = Z\nZ_gradient = X+Y\nprint (f'X-gradient: {X_gradient} \\nY-gradient: {Y_gradient} \\nZ-gradient: {Z_gradient}')\n```\n\n X-gradient: -4 \n Y-gradient: -4 \n Z-gradient: 3\n\n\n\n\n\n```python\nstep_size = 0.01\nX = X + step_size * X_gradient\nY = Y + step_size * Y_gradient\nZ = Z + step_size * Z_gradient\nprint (f'X is: {X} \\nY is: {Y} \\nZ is: {Z}')\n```\n\n X is: -2.04 \n Y is: 4.96 \n Z is: -3.97\n\n\n\n```python\nM_new = m(X,Y,Z)\nprint (f'old output: {M}\\nnew output: {M_new}')\n```\n\n old output: -12\n new output: -11.5924\n\n\n***\n\n### Backpropagation\n\nInstead of working with the function $m(X,Y,Z)=(X+Y)*Z$, we can simplify the computation by composing two new simpler functions:
$G=g(X,Y)=X+Y$, and
$F=f(G,Z)=G*Z$, into:
$F=f(g(X,Y),Z)$\n\n\n\nHere, we can apply the chain rule for derivation, because $F$ is a function of $G$ and $G$ is a function of $X$ and $Y$.
\nSo instead of computing $\\frac{\\partial M}{\\partial X}$, $\\frac{\\partial M}{\\partial Y}$ and $\\frac{\\partial M}{\\partial Z}$ which gets more complicated to compute with more complex expressions, we compute instead $\\frac{\\partial F}{\\partial X}$, $\\frac{\\partial F}{\\partial Y}$ and $\\frac{\\partial F}{\\partial Z}$, which can be decomposed:\n\n\\begin{align*}\n\\frac{\\partial F}{\\partial X}=\\frac{\\partial F}{\\partial G}\\frac{\\partial G}{\\partial X}\n\\end{align*}\n\nHere $\\frac{\\partial F}{\\partial G}$ is a simple multiplication gate, whose derivate we have already computed:$\\frac{\\partial F}{\\partial G}$ =$\\frac{\\partial f(G,Z)}{\\partial G}=Z$\n\nAlso $\\frac{\\partial G}{\\partial X}$ is a simple addition gate, whose derivate we have already computed: $\\frac{\\partial G}{\\partial X}$ =$\\frac{\\partial g(X,Y)}{\\partial X}=1$, thus:\n\n\\begin{align*}\n\\frac{\\partial F}{\\partial X}=\\frac{\\partial F}{\\partial G}\\frac{\\partial G}{\\partial X} = Z*1 = Z\n\\end{align*}\n\n***\n\nThe same applies when computing the partial $\\frac{\\partial F}{\\partial Y}$:\n\n\\begin{align*}\n\\frac{\\partial F}{\\partial Y}=\\frac{\\partial F}{\\partial G}\\frac{\\partial G}{\\partial Y}\n\\end{align*}\n\n\\begin{align*}\n\\frac{\\partial F}{\\partial Y}=\\frac{\\partial F}{\\partial G}\\frac{\\partial G}{\\partial Y} = Z*1 = Z\n\\end{align*}\n\n***\n\nThe partial derivative $\\frac{\\partial F}{\\partial Z}$ does not need to be decomposed:\n\n\\begin{align*}\n\\frac{\\partial F}{\\partial Z}=G=X+Y\n\\end{align*}\n\nWe can now use this information to maximize the output of the function __m_decomposed__:\n\n\n```python\ndef m_decomposed(X,Y,Z):\n G = g(X,Y)\n F = f(G,Z)\n return F\n```\n\n\n```python\nX = -2; Y = 5; Z = -4\n```\n\n\n```python\nF = m_decomposed(X,Y,Z)\nprint (f'the output is: {F}')\n```\n\n the output is: -12\n\n\n\n\n\n```python\nX_gradient = Z\nY_gradient = Z\nZ_gradient = X+Y\nprint (f'X-gradient: {X_gradient}, \\nY-gradient: {Y_gradient}, \\nZ-gradient: {Z_gradient}.')\n```\n\n X-gradient: -4, \n Y-gradient: -4, \n Z-gradient: 3.\n\n\n\n\nHere, we can observe, that in the backward pass, the multiplication gate switches the values of outputs: what used to be (3,-4) in the forward pass, it becomes (-4,3) in the backward pass. The addition gate, on the other hand just passes its input value to the ouput without changing it.\n\n\n```python\nstep_size = 0.01\nX = X + step_size * X_gradient\nY = Y + step_size * Y_gradient\nZ = Z + step_size * Z_gradient\nprint (f'X is: {X}\\nY is: {Y}\\nZ is: {Z}')\n```\n\n X is: -2.04\n Y is: 4.96\n Z is: -3.97\n\n\n\n```python\nF_new = m(X,Y,Z)\nprint (f'old output: {F}\\nnew output: {F_new}')\n```\n\n old output: -12\n new output: -11.5924\n\n\n***\n\n### Example: More complex functions\n\nHere is a seemingly complicated function:\n\n\\begin{align}\nl(A,B,C,X,Y)&= \\frac{1}{1+e^{-(AX+BY+C)}}\\\\\n&or \\\\\nl(A,B,C,X,Y)&= \\sigma (AX+BY+C)\\\\\n\\end{align}\n\n\nThe function $\\sigma$ is called a *sigmoid function*:\n\n\\begin{align}\n\\sigma&= \\frac{1}{1+e^{-x}}\\\\\n\\end{align}\n\nand it was used a lot in machine learning before.\n\nThe derivative of the sigmoid function is:\n\n\\begin{align}\n\\frac{d\\sigma(x)}{dx}= \\sigma(x) * (1-\\sigma(x))\n\\end{align}\n\n\n\nwhich means that once we compute the final activation $F=\\sigma(AX+BY+C)$, we can simply calculate the derivative as $F*(1-F)$.\n\nWe can compute the forward pass of this function without a problem, however, directly computing the partial derivatives $\\frac{\\partial L}{\\partial A}$, $\\frac{\\partial L}{\\partial B}$, $\\frac{\\partial L}{\\partial C}$, ... could be tricky. It is much better to use the chain rule and compose multiple functions togeher.\n\nWe can create 4 simple functions:\n\n\\begin{align*}\nG=g(A,X)&=A*X \\\\\nH=h(B,Y)&=B*Y \\\\\nK=k(G,H,C)&=G+H+C \\\\\nF=f(K)&= \\frac{1}{1+e^{-x}}\\\\\n\\end{align*}\n\nand compose them as:\n\n\\begin{align*}\nF=f(k(g(A,X),h(B,Y),C))\n\\end{align*}\n\nThis looks much simpler on a diagram:\n\n\n\nLet's compute all the partial derivatives by using the chain rule:\n\n\\begin{align*}\n\\frac{\\partial F}{\\partial A}&=\\frac{\\partial F}{\\partial K}*\\frac{\\partial K}{\\partial G}*\\frac{\\partial G}{\\partial A} \\\\\n\\frac{\\partial F}{\\partial A}&= F(1-F)*1*X \\\\\n\\frac{\\partial F}{\\partial A}&= XF(1-F)\n\\end{align*}\n\n\\begin{align*}\n\\frac{\\partial F}{\\partial X}&=\\frac{\\partial F}{\\partial K}*\\frac{\\partial K}{\\partial G}*\\frac{\\partial G}{\\partial X} \\\\\n\\frac{\\partial F}{\\partial X}&= F(1-F)*1*A \\\\\n\\frac{\\partial F}{\\partial X}&= AF(1-F)\n\\end{align*}\n\nBy following the exact same procedure for $B$, $Y$, and $C$ we get:\n\n\\begin{align*}\n\\frac{\\partial F}{\\partial B}&=YF(1-F)\\\\\n\\end{align*}\n\n\\begin{align*}\n\\frac{\\partial F}{\\partial Y}&=BF(1-F)\\\\\n\\end{align*}\n\n\\begin{align*}\n\\frac{\\partial F}{\\partial C}&=F(1-F)\\\\\n\\end{align*}\n\nWe can represent this as a gradient:\n\n\\begin{align}\n\\nabla l(A,B,C,X,Y)=\\left[XF(1-F),YF(1-F),F(1-F),AF(1-F),BF(1-F) \\right]\n\\end{align}\n\nWe can now use this information to maximize the output of the function __l__:\n\n\n```python\nimport numpy as np\ndef sigmoid(x):\n return 1 / (1 + np.exp(-x))\n```\n\n\n```python\ndef l(A,B,C,X,Y):\n G = f(A,X)\n H = f(B,Y)\n K = G + H + C\n F = sigmoid(K)\n return F\n```\n\n\n```python\nA = 1.0; B = 2.0; C = -3.0; X = -1.0; Y = 3.0\n```\n\n\n```python\nF = l(A,B,C,X,Y)\nprint (f'the output F is: {F}')\n```\n\n the output F is: 0.8807970779778823\n\n\n\n\nSince every partial derivative involves $F(1-F)$, we will compute it first as `F_K`\n\n\n```python\ngradient_end = 1\nF_K = (F * (1 - F)) * gradient_end\nprint (f'F_K = {F_K}')\n```\n\n F_K = 0.10499358540350662\n\n\n\n```python\nA_gradient = X*F_K\nB_gradient = Y*F_K\nC_gradient = F_K\nX_gradient = A*F_K\nY_gradient = B*F_K\n\nprint (f'A-gradient: {A_gradient} \\nX-gradient: {X_gradient} \\nB-gradient: {B_gradient} \\nY-gradient: {Y_gradient}\\nC-gradient: {C_gradient}')\n```\n\n A-gradient: -0.10499358540350662 \n X-gradient: 0.10499358540350662 \n B-gradient: 0.31498075621051985 \n Y-gradient: 0.20998717080701323\n C-gradient: 0.10499358540350662\n\n\n\n\n\n```python\nstep_size = 0.01\nA = A + step_size * A_gradient\nB = B + step_size * B_gradient\nC = C + step_size * C_gradient\nX = X + step_size * X_gradient\nY = Y + step_size * Y_gradient\nprint (f'A is: {A}, \\nB is: {B}, \\nC is: {C}, \\nX is: {X}, \\nY is: {Y}')\n```\n\n A is: 0.998950064145965, \n B is: 2.0031498075621053, \n C is: -2.9989500641459648, \n X is: -0.998950064145965, \n Y is: 3.00209987170807\n\n\n\n```python\nF_new = l(A,B,C,X,Y)\nprint (f'old output: {F}\\nnew output: {F_new}')\n```\n\n old output: 0.8807970779778823\n new output: 0.8825501816218984\n\n\nThe new output is higher than the old one!\n", "meta": {"hexsha": "21539df46e81ddcbd9698251dc885159f10bf975", "size": 37930, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "04. Functions as Real Valued Circuits.ipynb", "max_stars_repo_name": "Mistrymm7/machineintelligence", "max_stars_repo_head_hexsha": "7629d61d46dafa8e5f3013082b1403813d165375", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 82, "max_stars_repo_stars_event_min_datetime": "2019-09-23T11:25:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T22:56:10.000Z", "max_issues_repo_path": "04. Functions as Real Valued Circuits.ipynb", "max_issues_repo_name": "Iason-Giraud/machineintelligence", "max_issues_repo_head_hexsha": "b34a070208c7ac7d7b8a1e1ad02813b39274921c", "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": "04. Functions as Real Valued Circuits.ipynb", "max_forks_repo_name": "Iason-Giraud/machineintelligence", "max_forks_repo_head_hexsha": "b34a070208c7ac7d7b8a1e1ad02813b39274921c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 31, "max_forks_repo_forks_event_min_datetime": "2019-09-30T16:08:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-19T10:29:07.000Z", "avg_line_length": 22.2332942556, "max_line_length": 365, "alphanum_fraction": 0.4857368837, "converted": true, "num_tokens": 5908, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.964321452198369, "lm_q2_score": 0.9219218305645894, "lm_q1q2_score": 0.8890289984634235}} {"text": "```python\nfrom sympy import symbols, diff\n# initialize x and y to be symbols to use in a function\nx, y = symbols('x y', real=True)\nf = (x**2)/y\n# Find the partial derivatives of x and y\nfx = diff(f, x, evaluate=True)\nfy = diff(f, y, evaluate=True)\nprint(fx)\nprint(fy)\n# print(f.evalf(subs={x: 2, y: 1}))\nprint(fx.evalf(subs={x: 2, y: 1}))\nprint(fy.evalf(subs={x: 2, y: 1}))\n```\n\n\n```python\n\ndef f(x, y):\n return x**2/y\n\n\neps = 1e-6\nx = 2\ny = 1\nprint((f(x + eps, y) - f(x, y)) / eps)\nprint((f(x, y + eps) - f(x, y)) / eps)\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "236a82a80f89b19593c4917e2e72150a89f5f04c", "size": 1482, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Notebooks/Calculus/.ipynb_checkpoints/Untitled-checkpoint.ipynb", "max_stars_repo_name": "alannanoguchi/QL-1.1", "max_stars_repo_head_hexsha": "33e5074f56a8007e103ccee7065ed61dd3f337dd", "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/Calculus/.ipynb_checkpoints/Untitled-checkpoint.ipynb", "max_issues_repo_name": "alannanoguchi/QL-1.1", "max_issues_repo_head_hexsha": "33e5074f56a8007e103ccee7065ed61dd3f337dd", "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/Calculus/.ipynb_checkpoints/Untitled-checkpoint.ipynb", "max_forks_repo_name": "alannanoguchi/QL-1.1", "max_forks_repo_head_hexsha": "33e5074f56a8007e103ccee7065ed61dd3f337dd", "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": 20.8732394366, "max_line_length": 64, "alphanum_fraction": 0.4811066127, "converted": true, "num_tokens": 217, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9811668734137682, "lm_q2_score": 0.9059898260946732, "lm_q1q2_score": 0.888927205013994}} {"text": "# First Steps\n\n- [DifferentialEquations.jl docs](https://diffeq.sciml.ai/dev/index.html)\n\n## Building an ODE model\n\nHow to define your model, state variables, initial (and/or boundary) conditions, and parameters.\n\nAs a simple example, the concentration of a decaying nuclear isotope could be described as an exponential decay:\n\n$$\n\\frac{d}{dt}C(t) = - \\lambda C(t)\n$$\n\n**State variable(s)**\n- $C(t)$: The concentration of a decaying nuclear isotope.\n\n**Parameter(s)**\n- $\\lambda$: The rate constant of decay. The half-life $t_{\\frac{1}{2}} = \\frac{ln2}{\\lambda}$\n\nFor our ODE model to be compatible to the `DifferentialEquations.jl` ecosystem, the function for the right hand side should follow one of the following two formats:\n\n- Out-of-place form: `f(u, p, t)` where `u` is the state variable(s), `p` is the parameter(s), and `t` is the independent variable (usually time). The output is the right hand side (RHS) of the differential equation system.\n- In-place form: `f!(du, u, p, t)`, where the output is saved to `du`. The rest is the same as the out of place form. The in-place form has potential performance benefits since it allocates less arrays than the out-of-place form.\n\n\n```julia\nusing DifferentialEquations\n\n# The Exponential decay ODE model\nexpdecay(u, p, t) = p * u\n\n\np = -1.0 # Parameter\nu0 = 1.0 # Initial condition\ntspan = (0.0, 2.0) # Simulation start and end time points\nprob = ODEProblem(expdecay, u0, tspan, p) # Define the problem\nsol = solve(prob) # Solve the problem\n```\n\nWe can then use `Plots.jl` to visualized the solution. `DifferentialEquations.jl` has defined a plot recipe so that one can call `plot(sol)` directly.\n\n\n```julia\nusing Plots\nplot(sol) # Visualize the solution\n```\n\n## The SIR model\n\nA more complicated example is the [SIR model](https://www.maa.org/press/periodicals/loci/joma/the-sir-model-for-spread-of-disease-the-differential-equation-model) describing infectious disease spreading. There are more state variables and parameters.\n\n$$\n\\begin{align}\n\\frac{d}{dt}S(t) &= - \\beta S(t)I(t) \\\\\n\\frac{d}{dt}I(t) &= \\beta S(t)I(t) - \\gamma I(t) \\\\\n\\frac{d}{dt}R(t) &= \\gamma I(t)\n\\end{align}\n$$\n\n**State variable(s)**\n\n- $S(t)$ : the fraction of susceptible people\n- $I(t)$ : the fraction of infectious people\n- $R(t)$ : the fraction of recovered (or removed) people\n\n**Parameter(s)**\n\n- $\\beta$ : the rate of infection when susceptible and infectious people meet\n- $\\gamma$ : the rate of recovery of infectious people\n\n\n```julia\nusing DifferentialEquations\nusing Plots\n\n# SIR model\n# In-place form\nfunction sir!(du, u, p ,t)\n\ts, i, r = u\n\tβ, γ = p\n\tv1 = β * s * i\n\tv2 = γ * i\n du[1] = -v1\n du[2] = v1 - v2\n du[3] = v2\n\treturn nothing\nend\n\n# Parameters of the SIR model\np = (β = 1.0, γ = 0.3)\nu0 = [0.99, 0.01, 0.00] # s, i, r\ntspan = (0.0, 20.0)\n\n# Define a problem\nprob = ODEProblem(sir!, u0, tspan, p)\n\n# Solve the problem\nsol = solve(prob)\n\n# Visualize the solution\nplot(sol, label=[\"S\" \"I\" \"R\"], legend=:right)\n```\n", "meta": {"hexsha": "0895721d5ad2a2985a0c94f5dde51cb0ab779a81", "size": 4657, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "docs/intro/01-first-steps.ipynb", "max_stars_repo_name": "sosiristseng/juliabook-diffeq", "max_stars_repo_head_hexsha": "eedb41e2506f953bc3d37c095dd2c69a26a0799a", "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/intro/01-first-steps.ipynb", "max_issues_repo_name": "sosiristseng/juliabook-diffeq", "max_issues_repo_head_hexsha": "eedb41e2506f953bc3d37c095dd2c69a26a0799a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2022-03-15T11:26:37.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-27T02:39:34.000Z", "max_forks_repo_path": "docs/intro/01-first-steps.ipynb", "max_forks_repo_name": "sosiristseng/juliabook-diffeq", "max_forks_repo_head_hexsha": "eedb41e2506f953bc3d37c095dd2c69a26a0799a", "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.6381578947, "max_line_length": 259, "alphanum_fraction": 0.5462744256, "converted": true, "num_tokens": 922, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.960361162033533, "lm_q2_score": 0.9252299493606284, "lm_q1q2_score": 0.8885549093162}} {"text": "## Computing Sums\n\nSuppose we want to compute the sum of a sequence of numbers $x_0$, $x_1$, $x_2$, $x_3$, $\\dots$, $x_n$. There are at least two approaches:\n\n1. Compute the entire sequence, store it as a list $[x_0,x_1,x_2,\\dots,x_n]$ and then use the built-in function `sum`.\n2. Initialize a variable with value 0 (and name it `result` for example), create and add each element in the sequence to `result` one at a time.\n\nThe advantage of the second approach is that we don't need to store all the values at once. For example, here are two ways to write a function which computes the sum of squares.\n\nFor the first approach, use a list comprehension:\n\n\n```python\ndef sum_of_squares_1(N):\n \"Compute the sum of squares 1**2 + 2**2 + ... + N**2.\"\n return sum([n**2 for n in range(1,N + 1)])\n```\n\n\n```python\nsum_of_squares_1(4)\n```\n\n\n\n\n 30\n\n\n\nFor the second approach, use a `for` loop with the initialize-and-update construction:\n\n\n```python\ndef sum_of_squares_2(N):\n \"Compute the sum of squares 1**2 + 2**2 + ... + N**2.\"\n # Initialize the output value to 0\n result = 0\n for n in range(1,N + 1):\n # Update the result by adding the next term\n result = result + n**2\n return result\n```\n\n\n```python\nsum_of_squares_2(4)\n```\n\n\n\n\n 30\n\n\n\nAgain, both methods yield the same result however the second uses less memory!\n\n## Computing Products\n\nThere is no built-in function to compute products of sequences therefore we'll use an initialize-and-update construction similar to the example above for computing sums.\n\nWrite a function called `factorial` which takes a positive integer $N$ and return the factorial $N!$.\n\n\n```python\ndef factorial(N):\n \"Compute N! = N(N-1) ... (2)(1) for N >= 1.\"\n # Initialize the output variable to 1\n product = 1\n for n in range(2,N + 1):\n # Update the output variable\n product = product * n\n return product\n```\n\nLet's test our function for input values for which we know the result:\n\n\n```python\nfactorial(2)\n```\n\n\n\n\n 2\n\n\n\n\n```python\nfactorial(5)\n```\n\n\n\n\n 120\n\n\n\nWe can use our function to approximate $e$ using the Taylor series for $e^x$:\n\n$$\ne^x = \\sum_{k=0}^{\\infty} \\frac{x^k}{k!}\n$$\n\nFor example, let's compute the 100th partial sum of the series with $x=1$:\n\n\n```python\nsum([1/factorial(k) for k in range(0,101)])\n```\n\n\n\n\n 2.7182818284590455\n\n\n\n## Searching for Solutions\n\nWe can use `for` loops to search for integer solutions of equations. For example, suppose we would like to find all representations of a positive integer $N$ as a [sum of two squares](https://en.wikipedia.org/wiki/Sum_of_two_squares_theorem). In other words, we want to find all integer solutions $(x,y)$ of the equation:\n\n$$\nx^2 + y^2 = N\n$$\n\nWrite a function called `reps_sum_squares` which takes an integer $N$ and finds all representations of $N$ as a sum of squares $x^2 + y^2 = N$ for $0 \\leq x \\leq y$. The function returns the representations as a list of tuples. For example, if $N = 50$ then $1^2 + 7^2 = 50$ and $5^2 + 5^2 = 50$ and the function returns the list `[(1, 7),(5, 5)]`.\n\nLet's outline our approach before we write any code:\n\n1. Given $x \\leq y$, the largest possible value for $x$ is $\\sqrt{\\frac{N}{2}}$\n2. For $x \\leq \\sqrt{\\frac{N}{2}}$, the pair $(x,y)$ is a solution if $N - x^2$ is a square\n3. Define a helper function called `is_square` to test if an integer is square\n\n\n```python\ndef is_square(n):\n \"Determine if the integer n is a square.\"\n if round(n**0.5)**2 == n:\n return True\n else:\n return False\n\ndef reps_sum_squares(N):\n '''Find all representations of N as a sum of squares x**2 + y**2 = N.\n\n Parameters\n ----------\n N : integer\n\n Returns\n -------\n reps : list of tuples of integers\n List of tuples (x,y) of positive integers such that x**2 + y**2 = N.\n\n Examples\n --------\n >>> reps_sum_squares(1105)\n [(4, 33), (9, 32), (12, 31), (23, 24)]\n '''\n reps = []\n if is_square(N/2):\n # If N/2 is a square, search up to x = (N/2)**0.5\n max_x = round((N/2)**0.5)\n else:\n # If N/2 is not a square, search up to x = floor((N/2)**0.5)\n max_x = int((N/2)**0.5)\n for x in range(0,max_x + 1):\n y_squared = N - x**2\n if is_square(y_squared):\n y = round(y_squared**0.5)\n # Append solution (x,y) to list of solutions\n reps.append((x,y))\n return reps\n```\n\n\n```python\nreps_sum_squares(1105)\n```\n\n\n\n\n [(4, 33), (9, 32), (12, 31), (23, 24)]\n\n\n\nWhat is the smallest integer which can be expressed as the sum of squares in 5 different ways?\n\n\n```python\nN = 1105\nnum_reps = 4\nwhile num_reps < 5:\n N = N + 1\n reps = reps_sum_squares(N)\n num_reps = len(reps)\nprint(N,':',reps_sum_squares(N))\n```\n\n 4225 : [(0, 65), (16, 63), (25, 60), (33, 56), (39, 52)]\n\n\n## Examples\n\n### Prime Numbers\n\nA positive integer is [prime](https://en.wikipedia.org/wiki/Prime_number) if it is divisible only by 1 and itself. Write a function called `is_prime` which takes an input parameter `n` and returns `True` or `False` depending on whether `n` is prime or not.\n\nLet's outline our approach before we write any code:\n\n1. An integer $d$ divides $n$ if there is no remainder of $n$ divided by $d$.\n2. Use the modulus operator `%` to compute the remainder.\n3. If $d$ divides $n$ then $n = d q$ for some integer $q$ and either $d \\leq \\sqrt{n}$ or $q \\leq \\sqrt{n}$ (and not both), therefore we need only test if $d$ divides $n$ for integers $d \\leq \\sqrt{n}$\n\n\n```python\ndef is_prime(n):\n \"Determine whether or not n is a prime number.\"\n if n <= 1:\n return False\n # Test if d divides n for d <= n**0.5\n for d in range(2,round(n**0.5) + 1):\n if n % d == 0:\n # n is divisible by d and so n is not prime\n return False\n # If we exit the for loop, then n is not divisible by any d\n # and therefore n is prime\n return True\n```\n\nLet's test our function on the first 30 numbers:\n\n\n```python\nfor n in range(0,31):\n if is_prime(n):\n print(n,'is prime!')\n```\n\n 2 is prime!\n 3 is prime!\n 5 is prime!\n 7 is prime!\n 11 is prime!\n 13 is prime!\n 17 is prime!\n 19 is prime!\n 23 is prime!\n 29 is prime!\n\n\nOur function works! Let's find all the primes between 20,000 and 20,100.\n\n\n```python\nfor n in range(20000,20100):\n if is_prime(n):\n print(n,'is prime!')\n```\n\n 20011 is prime!\n 20021 is prime!\n 20023 is prime!\n 20029 is prime!\n 20047 is prime!\n 20051 is prime!\n 20063 is prime!\n 20071 is prime!\n 20089 is prime!\n\n\n### Divisors\n\nLet's write a function called `divisors` which takes a positive integer $N$ and returns the list of positive integers which divide $N$.\n\n\n```python\ndef divisors(N):\n \"Return the list of divisors of N.\"\n # Initialize the list of divisors (which always includes 1)\n divisor_list = [1]\n # Check division by d for d <= N/2\n for d in range(2,N // 2 + 1):\n if N % d == 0:\n divisor_list.append(d)\n # N divides itself and so we append N to the list of divisors\n divisor_list.append(N)\n return divisor_list\n```\n\nLet's test our function:\n\n\n```python\ndivisors(10)\n```\n\n\n\n\n [1, 2, 5, 10]\n\n\n\n\n```python\ndivisors(100)\n```\n\n\n\n\n [1, 2, 4, 5, 10, 20, 25, 50, 100]\n\n\n\n\n```python\ndivisors(59)\n```\n\n\n\n\n [1, 59]\n\n\n\n### Collatz Conjecture\n\nLet $a$ be a positive integer and consider the recursive sequence where $x_0 = a$ and\n\n$$\nx_{n+1} = \\left\\\\{ \\begin{array}{cl} x_n/2 & \\text{if } x_n \\text{ is even} \\\\\\\\ 3x_n+1 & \\text{if } x_n \\text{ is odd} \\end{array} \\\\right.\n$$\n\nThe [Collatz conjecture](https://en.wikipedia.org/wiki/Collatz_conjecture) states that this sequence will *always* reach 1. For example, if $a = 10$ then $x_0 = 10$, $x_1 = 5$, $x_2 = 16$, $x_3 = 8$, $x_4 = 4$, $x_5 = 2$ and $x_6 = 1$.\n\nWrite a function called `collatz` which takes one input parameter `a` and returns the sequence of integers defined above and ending with the first occurrence $x_n=1$.\n\n\n```python\ndef collatz(a):\n \"Compute the Collatz sequence starting at a and ending at 1.\"\n # Initialize list with first value a\n sequence = [a]\n # Compute values until we reach 1\n while sequence[-1] > 1:\n # Check if the last element in the list is even\n if sequence[-1] % 2 == 0:\n # Compute and append the new value\n sequence.append(sequence[-1] // 2)\n else:\n # Compute and append the new value\n sequence.append(3*sequence[-1] + 1)\n return sequence\n```\n\nLet's test our function:\n\n\n```python\nprint(collatz(10))\n```\n\n [10, 5, 16, 8, 4, 2, 1]\n\n\n\n```python\ncollatz(22)\n```\n\n\n\n\n [22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1]\n\n\n\nThe Collatz conjecture is quite amazing. No matter where we start, the sequence always terminates at 1!\n\n\n```python\na = 123456789\nseq = collatz(a)\nprint(\"Collatz sequence for a =\",a)\nprint(\"begins with\",seq[:5])\nprint(\"ends with\",seq[-5:])\nprint(\"and has\",len(seq),\"terms.\")\n```\n\n Collatz sequence for a = 123456789\n begins with [123456789, 370370368, 185185184, 92592592, 46296296]\n ends with [16, 8, 4, 2, 1]\n and has 178 terms.\n\n\nWhich $a < 1000$ produces the longest sequence?\n\n\n```python\nmax_length = 1\na_max = 1\nfor a in range(1,1001):\n seq_length = len(collatz(a))\n if seq_length > max_length:\n max_length = seq_length\n a_max = a\nprint('Longest sequence begins with a =',a_max,'and has length',max_length)\n```\n\n Longest sequence begins with a = 871 and has length 179\n\n\n## Exercises\n\n1. [Fermat's theorem on the sum of two squares](https://en.wikipedia.org/wiki/Fermat%27s_theorem_on_sums_of_two_squares) states that every prime number $p$ of the form $4k+1$ can be expressed as the sum of two squares. For example, $5 = 2^2 + 1^2$ and $13 = 3^2 + 2^2$. Find the smallest prime greater than $2019$ of the form $4k+1$ and write it as a sum of squares. (Hint: Use the functions `is_prime` and `reps_sum_squares` from this section.)\n\n2. What is the smallest prime number which can be represented as a sum of squares in 2 different ways?\n\n3. What is the smallest integer which can be represented as a sum of squares in 3 different ways?\n\n4. Write a function called `primes_between` which takes two integer inputs $a$ and $b$ and returns the list of primes in the closed interval $[a,b]$.\n\n5. Write a function called `primes_d_mod_N` which takes four integer inputs $a$, $b$, $d$ and $N$ and returns the list of primes in the closed interval $[a,b]$ which are congruent to $d$ mod $N$ (this means that the prime has remainder $d$ after division by $N$). This kind of list is called [primes in an arithmetic progression](https://en.wikipedia.org/wiki/Dirichlet%27s_theorem_on_arithmetic_progressions).\n\n6. Write a function called `reciprocal_recursion` which takes three positive integers $x_0$, $x_1$ and $N$ and returns the sequence $[x_0,x_1,x_2,\\dots,x_N]$ where\n\n $$\n x_n = \\frac{1}{x_{n-1}} + \\frac{1}{x_{n-2}}\n $$\n\n7. Write a function called `root_sequence` which takes input parameters $a$ and $N$, both positive integers, and returns the $N$th term $x_N$ in the sequence:\n\n $$\n \\begin{align}\n x_0 &= a \\\\\\\n x_n &= 1 + \\sqrt{x_{n-1}}\n \\end{align}\n $$\n\n Does the sequence converge to different values for different starting values $a$?\n\n8. Write a function called `fib_less_than` which takes one input $N$ and returns the list of Fibonacci numbers less than $N$.\n\n9. Write a function called `fibonacci_primes` which takes an input parameter $N$ and returns the list of Fibonacci numbers less than $N$ which are also prime numbers.\n\n10. Let $w(N)$ be the number of ways $N$ can be expressed as a sum of two squares $x^2 + y^2 = N$ with $1 \\leq x \\leq y$. Then\n\n $$\n \\lim_{N \\to \\infty} \\frac{1}{N} \\sum_{n=1}^{N} w(n) = \\frac{\\pi}{8}\n $$\n\n Compute the left side of the formula for $N=100$ and compare the result to $\\pi / 8$.\n\n11. A list of positive integers $[a,b,c]$ (with $1 \\leq a < b$) are a [Pythagorean triple](https://en.wikipedia.org/wiki/Pythagorean_triple) if $a^2 + b^2 = c^2$. Write a function called `py_triples` which takes an input parameter $N$ and returns the list of Pythagorean triples `[a,b,c]` with $c \\leq N$.\n", "meta": {"hexsha": "a0a2c22932ad51d3467ba4d3ba92feea9eca94fa", "size": 18777, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Python/1. Python Basics/Notebooks/1. The Basics.- Startups/1.0 Fundamentals Continued/1.4b Using Functions to Solve Math Problems.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/1. Python Basics/Notebooks/1. The Basics.- Startups/1.0 Fundamentals Continued/1.4b Using Functions to Solve Math Problems.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/1. Python Basics/Notebooks/1. The Basics.- Startups/1.0 Fundamentals Continued/1.4b Using Functions to Solve Math Problems.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": 18777.0, "max_line_length": 18777, "alphanum_fraction": 0.6444586462, "converted": true, "num_tokens": 3778, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9674102552339747, "lm_q2_score": 0.9184802429095672, "lm_q1q2_score": 0.8885472062205075}} {"text": "# Finding Roots of Equations\n\n## Calculus review\n\n\n```python\n%matplotlib inline\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport scipy as scipy\nfrom scipy.interpolate import interp1d\n```\n\nLet's review the theory of optimization for multivariate functions. Recall that in the single-variable case, extreme values (local extrema) occur at points where the first derivative is zero, however, the vanishing of the first derivative is not a sufficient condition for a local max or min. Generally, we apply the second derivative test to determine whether a candidate point is a max or min (sometimes it fails - if the second derivative either does not exist or is zero). In the multivariate case, the first and second derivatives are *matrices*. In the case of a scalar-valued function on $\\mathbb{R}^n$, the first derivative is an $n\\times 1$ vector called the *gradient* (denoted $\\nabla f$). The second derivative is an $n\\times n$ matrix called the *Hessian* (denoted $H$)\n\nJust to remind you, the gradient and Hessian are given by:\n\n$$\\nabla f(x) = \\left(\\begin{matrix}\\frac{\\partial f}{\\partial x_1}\\\\ \\vdots \\\\\\frac{\\partial f}{\\partial x_n}\\end{matrix}\\right)$$\n\n\n$$H = \\left(\\begin{matrix}\n \\dfrac{\\partial^2 f}{\\partial x_1^2} & \\dfrac{\\partial^2 f}{\\partial x_1\\,\\partial x_2} & \\cdots & \\dfrac{\\partial^2 f}{\\partial x_1\\,\\partial x_n} \\\\[2.2ex]\n \\dfrac{\\partial^2 f}{\\partial x_2\\,\\partial x_1} & \\dfrac{\\partial^2 f}{\\partial x_2^2} & \\cdots & \\dfrac{\\partial^2 f}{\\partial x_2\\,\\partial x_n} \\\\[2.2ex]\n \\vdots & \\vdots & \\ddots & \\vdots \\\\[2.2ex]\n \\dfrac{\\partial^2 f}{\\partial x_n\\,\\partial x_1} & \\dfrac{\\partial^2 f}{\\partial x_n\\,\\partial x_2} & \\cdots & \\dfrac{\\partial^2 f}{\\partial x_n^2}\n\\end{matrix}\\right)$$\n\nOne of the first things to note about the Hessian - it's symmetric. This structure leads to some useful properties in terms of interpreting critical points.\n\nThe multivariate analog of the test for a local max or min turns out to be a statement about the gradient and the Hessian matrix. Specifically, a function $f:\\mathbb{R}^n\\rightarrow \\mathbb{R}$ has a critical point at $x$ if $\\nabla f(x) = 0$ (where zero is the zero vector!). Furthermore, the second derivative test at a critical point is as follows:\n\n* If $H(x)$ is positive-definite ($\\iff$ it has all positive eigenvalues), $f$ has a local minimum at $x$\n* If $H(x)$ is negative-definite ($\\iff$ it has all negative eigenvalues), $f$ has a local maximum at $x$\n* If $H(x)$ has both positive and negative eigenvalues, $f$ has a saddle point at $x$.\n\nIf you have $m$ equations with $n$ variables, then the $m \\times n$ matrix of first partial derivatives is known as the Jacobian $J(x)$. For example, for two equations $f(x, y)$ and $g(x, y)$, we have\n\n$$\nJ(x) = \\begin{bmatrix}\n\\frac{\\delta f}{\\delta x} & \\frac{\\delta f}{\\delta y} \\\\\n\\frac{\\delta g}{\\delta x} & \\frac{\\delta g}{\\delta y} \n\\end{bmatrix}\n$$\n\nWe can now express the multivariate form of Taylor polynomials in a familiar format.\n\n$$\nf(x + \\delta x) = f(x) + \\delta x \\cdot J(x) + \\frac{1}{2} \\delta x^T H(x) \\delta x + \\mathcal{O}(\\delta x^3)\n$$\n\n## Main Issues in Root Finding in One Dimension\n\n* Separating close roots\n* Numerical Stability\n* Rate of Convergence\n* Continuity and Differentiability\n\n## Bisection Method\n\nThe bisection method is one of the simplest methods for finding zeros of a non-linear function. It is guaranteed to find a root - but it can be slow. The main idea comes from the intermediate value theorem: If $f(a)$ and $f(b)$ have different signs and $f$ is continuous, then $f$ must have a zero between $a$ and $b$. We evaluate the function at the midpoint, $c = \\frac12(a+b)$. $f(c)$ is either zero, has the same sign as $f(a)$ or the same sign as $f(b)$. Suppose $f(c)$ has the same sign as $f(a)$ (as pictured below). We then repeat the process on the interval $[c,b]$. \n\n\n```python\ndef f(x):\n return x**3 + 4*x**2 -3\n\nx = np.linspace(-3.1, 0, 100)\nplt.plot(x, x**3 + 4*x**2 -3)\n\na = -3.0\nb = -0.5\nc = 0.5*(a+b)\n\nplt.text(a,-1,\"a\")\nplt.text(b,-1,\"b\")\nplt.text(c,-1,\"c\")\n\nplt.scatter([a,b,c], [f(a), f(b),f(c)], s=50, facecolors='none')\nplt.scatter([a,b,c], [0,0,0], s=50, c='red')\n\nxaxis = plt.axhline(0)\npass\n```\n\n\n```python\nx = np.linspace(-3.1, 0, 100)\nplt.plot(x, x**3 + 4*x**2 -3)\n\nd = 0.5*(b+c)\n\nplt.text(d,-1,\"d\")\nplt.text(b,-1,\"b\")\nplt.text(c,-1,\"c\")\n\nplt.scatter([d,b,c], [f(d), f(b),f(c)], s=50, facecolors='none')\nplt.scatter([d,b,c], [0,0,0], s=50, c='red')\n\nxaxis = plt.axhline(0)\npass\n```\n\nWe can terminate the process whenever the function evaluated at the new midpoint is 'close enough' to zero. This method is an example of what are known as 'bracketed methods'. This means the root is 'bracketed' by the end-points (it is somewhere in between). Another class of methods are 'open methods' - the root need not be somewhere in between the end-points (but it usually needs to be close!)\n\n## Secant Method\n\nThe secant method also begins with two initial points, but without the constraint that the function values are of opposite signs. We use the secant line to extrapolate the next candidate point.\n\n\n```python\ndef f(x):\n return (x**3-2*x+7)/(x**4+2)\n\nx = np.arange(-3,5, 0.1);\ny = f(x)\n\np1=plt.plot(x, y)\nplt.xlim(-3, 4)\nplt.ylim(-.5, 4)\nplt.xlabel('x')\nplt.axhline(0)\nt = np.arange(-10, 5., 0.1)\n\nx0=-1.2\nx1=-0.5\nxvals = []\nxvals.append(x0)\nxvals.append(x1)\nnotconverge = 1\ncount = 0\ncols=['r--','b--','g--','y--']\nwhile (notconverge==1 and count < 3):\n slope=(f(xvals[count+1])-f(xvals[count]))/(xvals[count+1]-xvals[count])\n intercept=-slope*xvals[count+1]+f(xvals[count+1])\n plt.plot(t, slope*t + intercept, cols[count])\n nextval = -intercept/slope\n if abs(f(nextval)) < 0.001:\n notconverge=0\n else:\n xvals.append(nextval)\n count = count+1\n\nplt.show()\n```\n\nThe secant method has the advantage of fast convergence. While the bisection method has a linear convergence rate (i.e. error goes to zero at the rate that $h(x) = x$ goes to zero, the secant method has a convergence rate that is faster than linear, but not quite quadratic (i.e. $\\sim x^\\alpha$, where $\\alpha = \\frac{1+\\sqrt{5}}2 \\approx 1.6$) however, the trade-off is that the secant method is not guaranteed to find a root in the brackets.\n\nA variant of the secant method is known as the **method of false positions**. Conceptually it is identical to the secant method, except that instead of always using the last two values of $x$ for linear interpolation, it chooses the two most recent values that maintain the bracket property (i.e $f(a) f(b) < 0$). It is slower than the secant, but like the bisection, is safe.\n\n## Newton-Raphson Method\n\nWe want to find the value $\\theta$ so that some (differentiable) function $g(\\theta)=0$. \nIdea: start with a guess, $\\theta_0$. Let $\\tilde{\\theta}$ denote the value of $\\theta$ for which $g(\\theta) = 0$ and define $h = \\tilde{\\theta} - \\theta_0$. Then:\n\n$$\n\\begin{eqnarray*}\ng(\\tilde{\\theta}) &=& 0 \\\\\\\\\n&=&g(\\theta_0 + h) \\\\\\\\\n&\\approx& g(\\theta_0) + hg'(\\theta_0)\n\\end{eqnarray*}\n$$\n\nThis implies that \n\n$$ h\\approx \\frac{g(\\theta_0)}{g'(\\theta_0)}$$\n\nSo that\n\n$$\\tilde{\\theta}\\approx \\theta_0 - \\frac{g(\\theta_0)}{g'(\\theta_0)}$$\n\nThus, we set our next approximation:\n\n$$\\theta_1 = \\theta_0 - \\frac{g(\\theta_0)}{g'(\\theta_0)}$$\n\nand we have developed an iterative procedure with:\n\n$$\\theta_n = \\theta_{n-1} - \\frac{g(\\theta_{n-1})}{g'(\\theta_{n-1})}$$\n\n#### Example\n\nLet $$g(x) = \\frac{x^3-2x+7}{x^4+2}$$\n\n\n```python\nx = np.arange(-5,5, 0.1);\ny = (x**3-2*x+7)/(x**4+2)\n\np1=plt.plot(x, y)\nplt.xlim(-4, 4)\nplt.ylim(-.5, 4)\nplt.xlabel('x')\nplt.axhline(0)\nplt.title('Example Function')\nplt.show()\n```\n\n\n```python\nx = np.arange(-5,5, 0.1);\ny = (x**3-2*x+7)/(x**4+2)\n\np1=plt.plot(x, y)\nplt.xlim(-4, 4)\nplt.ylim(-.5, 4)\nplt.xlabel('x')\nplt.axhline(0)\nplt.title('Good Guess')\nt = np.arange(-5, 5., 0.1)\n\nx0=-1.5\nxvals = []\nxvals.append(x0)\nnotconverge = 1\ncount = 0\ncols=['r--','b--','g--','y--','c--','m--','k--','w--']\nwhile (notconverge==1 and count < 6):\n funval=(xvals[count]**3-2*xvals[count]+7)/(xvals[count]**4+2)\n slope=-((4*xvals[count]**3 *(7 - 2 *xvals[count] + xvals[count]**3))/(2 + xvals[count]**4)**2) + (-2 + 3 *xvals[count]**2)/(2 + xvals[count]**4)\n \n intercept=-slope*xvals[count]+(xvals[count]**3-2*xvals[count]+7)/(xvals[count]**4+2)\n\n plt.plot(t, slope*t + intercept, cols[count])\n nextval = -intercept/slope\n if abs(funval) < 0.01:\n notconverge=0\n else:\n xvals.append(nextval)\n count = count+1\n\n\n```\n\nFrom the graph, we see the zero is near -2. We make an initial guess of $$x=-1.5$$\n\nWe have made an excellent choice for our first guess, and we can see rapid convergence!\n\n\n```python\nfunval\n```\n\n\n\n\n 0.007591996330867034\n\n\n\nIn fact, the Newton-Raphson method converges quadratically. However, NR (and the secant method) have a fatal flaw:\n\n\n```python\nx = np.arange(-5,5, 0.1);\ny = (x**3-2*x+7)/(x**4+2)\n\np1=plt.plot(x, y)\nplt.xlim(-4, 4)\nplt.ylim(-.5, 4)\nplt.xlabel('x')\nplt.axhline(0)\nplt.title('Bad Guess')\nt = np.arange(-5, 5., 0.1)\n\nx0=-0.5\nxvals = []\nxvals.append(x0)\nnotconverge = 1\ncount = 0\ncols=['r--','b--','g--','y--','c--','m--','k--','w--']\nwhile (notconverge==1 and count < 6):\n funval=(xvals[count]**3-2*xvals[count]+7)/(xvals[count]**4+2)\n slope=-((4*xvals[count]**3 *(7 - 2 *xvals[count] + xvals[count]**3))/(2 + xvals[count]**4)**2) + (-2 + 3 *xvals[count]**2)/(2 + xvals[count]**4)\n \n intercept=-slope*xvals[count]+(xvals[count]**3-2*xvals[count]+7)/(xvals[count]**4+2)\n\n plt.plot(t, slope*t + intercept, cols[count])\n nextval = -intercept/slope\n if abs(funval) < 0.01:\n notconverge = 0\n else:\n xvals.append(nextval)\n count = count+1\n```\n\nWe have stumbled on the horizontal asymptote. The algorithm fails to converge. \n\n### Convergence Rate\n\nThe following is a derivation of the convergence rate of the NR method:\n\n\nSuppose $x_k \\; \\rightarrow \\; x^*$ and $g'(x^*) \\neq 0$. Then we may write:\n\n$$x_k = x^* + \\epsilon_k$$.\n\nNow expand $g$ at $x^*$:\n\n$$g(x_k) = g(x^*) + g'(x^*)\\epsilon_k + \\frac12 g''(x^*)\\epsilon_k^2 + ...$$\n$$g'(x_k)=g'(x^*) + g''(x^*)\\epsilon_k$$\n\nWe have that\n\n\n\\begin{eqnarray}\n\\epsilon_{k+1} &=& \\epsilon_k + \\left(x_{k-1}-x_k\\right)\\\\\n&=& \\epsilon_k -\\frac{g(x_k)}{g'(x_k)}\\\\\n&\\approx & \\frac{g'(x^*)\\epsilon_k + \\frac12g''(x^*)\\epsilon_k^2}{g'(x^*)+g''(x^*)\\epsilon_k}\\\\\n&\\approx & \\frac{g''(x^*)}{2g'(x^*)}\\epsilon_k^2\n\\end{eqnarray}\n\n## Gauss-Newton\n\nFor 1D, the Newton method is\n$$\nx_{n+1} = x_n - \\frac{f(x_n)}{f'(x_n)}\n$$\n\nWe can generalize to $k$ dimensions by \n$$\nx_{n+1} = x_n - J^{-1} f(x_n)\n$$\nwhere $x$ and $f(x)$ are now vectors, and $J^{-1}$ is the inverse Jacobian matrix. In general, the Jacobian is not a square matrix, and we use the generalized inverse $(J^TJ)^{-1}J^T$ instead, giving\n$$\nx_{n+1} = x_n - (J^TJ)^{-1}J^T f(x_n)\n$$\n\nIn multivariate nonlinear estimation problems, we can find the vector of parameters $\\beta$ by minimizing the residuals $r(\\beta)$, \n$$\n\\beta_{n+1} = \\beta_n - (J^TJ)^{-1}J^T r(\\beta_n)\n$$\nwhere the entries of the Jacobian matrix $J$ are\n$$\nJ_{ij} = \\frac{\\partial r_i(\\beta)}{\\partial \\beta_j}\n$$\n\n## Inverse Quadratic Interpolation\n\nInverse quadratic interpolation is a type of polynomial interpolation. Polynomial interpolation simply means we find the polynomial of least degree that fits a set of points. In quadratic interpolation, we use three points, and find the quadratic polynomial that passes through those three points. \n\n\n```python\n\ndef f(x):\n return (x - 2) * x * (x + 2)**2\n\n\nx = np.arange(-5,5, 0.1);\nplt.plot(x, f(x))\nplt.xlim(-3.5, 0.5)\nplt.ylim(-5, 16)\nplt.xlabel('x')\nplt.axhline(0)\nplt.title(\"Quadratic Interpolation\")\n\n#First Interpolation\nx0=np.array([-3,-2.5,-1.0])\ny0=f(x0)\nf2 = interp1d(x0, y0,kind='quadratic')\n\n#Plot parabola\nxs = np.linspace(-3, -1, num=10000, endpoint=True)\nplt.plot(xs, f2(xs))\n\n#Plot first triplet\nplt.plot(x0, f(x0),'ro');\nplt.scatter(x0, f(x0), s=50, c='yellow');\n\n#New x value\nxnew=xs[np.where(abs(f2(xs))==min(abs(f2(xs))))]\n\nplt.scatter(np.append(xnew,xnew), np.append(0,f(xnew)), c='black');\n\n#New triplet\nx1=np.append([-3,-2.5],xnew)\ny1=f(x1)\nf2 = interp1d(x1, y1,kind='quadratic')\n\n#New Parabola\nxs = np.linspace(min(x1), max(x1), num=100, endpoint=True)\nplt.plot(xs, f2(xs))\n\nxnew=xs[np.where(abs(f2(xs))==min(abs(f2(xs))))]\nplt.scatter(np.append(xnew,xnew), np.append(0,f(xnew)), c='green');\n\n\n```\n\nSo that's the idea behind quadratic interpolation. Use a quadratic approximation, find the zero of interest, use that as a new point for the next quadratic approximation.\n\n\nInverse quadratic interpolation means we do quadratic interpolation on the *inverse function*. So, if we are looking for a root of $f$, we approximate $f^{-1}(x)$ using quadratic interpolation. This just means fitting $x$ as a function of $y$, so that the quadratic is turned on its side and we are guaranteed that it cuts the x-axis somewhere. Note that the secant method can be viewed as a *linear* interpolation on the inverse of $f$. We can write:\n\n$$f^{-1}(y) = \\frac{(y-f(x_n))(y-f(x_{n-1}))}{(f(x_{n-2})-f(x_{n-1}))(f(x_{n-2})-f(x_{n}))}x_{n-2} + \\frac{(y-f(x_n))(y-f(x_{n-2}))}{(f(x_{n-1})-f(x_{n-2}))(f(x_{n-1})-f(x_{n}))}x_{n-1} + \\frac{(y-f(x_{n-2}))(y-f(x_{n-1}))}{(f(x_{n})-f(x_{n-2}))(f(x_{n})-f(x_{n-1}))}x_{n-1}$$\n\nWe use the above formula to find the next guess $x_{n+1}$ for a zero of $f$ (so $y=0$):\n\n$$x_{n+1} = \\frac{f(x_n)f(x_{n-1})}{(f(x_{n-2})-f(x_{n-1}))(f(x_{n-2})-f(x_{n}))}x_{n-2} + \\frac{f(x_n)f(x_{n-2})}{(f(x_{n-1})-f(x_{n-2}))(f(x_{n-1})-f(x_{n}))}x_{n-1} + \\frac{f(x_{n-2})f(x_{n-1})}{(f(x_{n})-f(x_{n-2}))(f(x_{n})-f(x_{n-1}))}x_{n}$$\n\nWe aren't so much interested in deriving this as we are understanding the procedure:\n\n\n\n\n\n```python\nx = np.arange(-5,5, 0.1);\nplt.plot(x, f(x))\nplt.xlim(-3.5, 0.5)\nplt.ylim(-5, 16)\nplt.xlabel('x')\nplt.axhline(0)\nplt.title(\"Inverse Quadratic Interpolation\")\n\n#First Interpolation\nx0=np.array([-3,-2.5,1])\ny0=f(x0)\nf2 = interp1d(y0, x0,kind='quadratic')\n\n#Plot parabola\nxs = np.linspace(min(f(x0)), max(f(x0)), num=10000, endpoint=True)\nplt.plot(f2(xs), xs)\n\n#Plot first triplet\nplt.plot(x0, f(x0),'ro');\nplt.scatter(x0, f(x0), s=50, c='yellow');\n```\n\nConvergence rate is approximately $1.8$. The advantage of the inverse method is that we will *always* have a real root (the parabola will always cross the x-axis). A serious disadvantage is that the initial points must be very close to the root or the method may not converge.\n\nThat is why it is usually used in conjunction with other methods.\n\n## Brentq Method\n\nBrent's method is a combination of bisection, secant and inverse quadratic interpolation. Like bisection, it is a 'bracketed' method (starts with points $(a,b)$ such that $f(a)f(b)<0$.\n\nRoughly speaking, the method begins by using the secant method to obtain a third point $c$, then uses inverse quadratic interpolation to generate the next possible root. Without going into too much detail, the algorithm attempts to assess when interpolation will go awry, and if so, performs a bisection step. Also, it has certain criteria to reject an iterate. If that happens, the next step will be linear interpolation (secant method). \n\nTo find zeros, use \n\n\n```python\nx = np.arange(-5,5, 0.1);\np1=plt.plot(x, f(x))\nplt.xlim(-4, 4)\nplt.ylim(-10, 20)\nplt.xlabel('x')\nplt.axhline(0)\npass\n```\n\n\n```python\nfrom scipy import optimize\n```\n\n\n```python\nscipy.optimize.brentq(f,-1,.5)\n```\n\n\n\n\n -7.864845203343107e-19\n\n\n\n\n```python\nscipy.optimize.brentq(f,.5,3)\n```\n\n\n\n\n 2.0\n\n\n\n## Roots of polynomials\n\nOne method for finding roots of polynomials converts the problem into an eigenvalue one by using the **companion matrix** of a polynomial. For a polynomial \n\n$$\np(x) = a_0 + a_1x + a_2 x^2 + \\ldots + a_m x^m\n$$\n\nthe companion matrix is\n\n$$\nA = \\begin{bmatrix}\n-a_{m-1}/a_m & -a_{m-2}/a_m & \\ldots & -a_0/a_m \\\\\n1 & 0 & \\ldots & 0 \\\\\n0 & 1 & \\ldots & 0 \\\\\n\\vdots & \\vdots & \\ldots & \\vdots \\\\\n0 & 0 & \\ldots & 0\n\\end{bmatrix}\n$$\n\nThe characteristic polynomial of the companion matrix is $\\lvert \\lambda I - A \\rvert$ which expands to \n\n$$\na_0 + a_1 \\lambda + a_2 \\lambda^2 + \\ldots + a_m \\lambda^m\n$$\n\nIn other words, the roots we are seeking are the eigenvalues of the companion matrix.\n\nFor example, to find the cube roots of unity, we solve $x^3 - 1 = 0$. The `roots` function uses the companion matrix method to find roots of polynomials.\n\n\n```python\n# Coefficients of $x^3, x^2, x^1, x^0$\n\npoly = np.array([1, 0, 0, -1])\n```\n\nManual construction\n\n\n```python\nA = np.array([\n [0,0,1],\n [1,0,0],\n [0,1,0]\n])\n```\n\n\n```python\nscipy.linalg.eigvals(A)\n```\n\n\n\n\n array([-0.5+0.8660254j, -0.5-0.8660254j, 1. +0.j ])\n\n\n\nUsing built-in function\n\n\n```python\nx = np.roots(poly)\nx\n```\n\n\n\n\n array([-0.5+0.8660254j, -0.5-0.8660254j, 1. +0.j ])\n\n\n\n\n```python\nplt.scatter([z.real for z in x], [z.imag for z in x])\ntheta = np.linspace(0, 2*np.pi, 100)\nu = np.cos(theta)\nv = np.sin(theta)\nplt.plot(u, v, ':')\nplt.axis('square')\npass\n```\n\n## Using `scipy.optimize`\n\n### Finding roots of univariate equations\n\n\n```python\ndef f(x):\n return x**3-3*x+1\n```\n\n\n```python\nx = np.linspace(-3,3,100)\nplt.axhline(0, c='red')\nplt.plot(x, f(x))\npass\n```\n\n\n```python\nfrom scipy.optimize import brentq, newton\n```\n\n#### `brentq` is the recommended method\n\n\n```python\nbrentq(f, -3, 0), brentq(f, 0, 1), brentq(f, 1,3)\n```\n\n\n\n\n (-1.8793852415718166, 0.3472963553337031, 1.532088886237956)\n\n\n\n#### Secant method\n\n\n```python\nnewton(f, -3), newton(f, 0), newton(f, 3)\n```\n\n\n\n\n (-1.8793852415718166, 0.34729635533385395, 1.5320888862379578)\n\n\n\n#### Newton-Raphson method\n\n\n```python\nfprime = lambda x: 3*x**2 - 3\nnewton(f, -3, fprime), newton(f, 0, fprime), newton(f, 3, fprime)\n```\n\n\n\n\n (-1.8793852415718166, 0.34729635533386066, 1.532088886237956)\n\n\n\n### Finding fixed points\n\nFinding the fixed points of a function $g(x) = x$ is the same as finding the roots of $g(x) - x$. However, specialized algorithms also exist - e.g. using `scipy.optimize.fixedpoint`.\n\n\n```python\nfrom scipy.optimize import fixed_point\n```\n\n\n```python\nx = np.linspace(-3,3,100)\nplt.plot(x, f(x), color='red')\nplt.plot(x, x)\npass\n```\n\n\n```python\nfixed_point(f, 0), fixed_point(f, -3), fixed_point(f, 3)\n```\n\n\n\n\n (array(0.25410169), array(-2.11490754), array(1.86080585))\n\n\n\n### Mutlivariate roots and fixed points\n\nUse `root` to solve polynomial equations. Use `fsolve` for non-polynomial equations.\n\n\n```python\nfrom scipy.optimize import root, fsolve\n```\n\nSuppose we want to solve a sysetm of $m$ equations with $n$ unknowns\n\n\\begin{align}\nf(x_0, x_1) &= x_1 - 3x_0(x_0+1)(x_0-1) \\\\\ng(x_0, x_1) &= 0.25 x_0^2 + x_1^2 - 1\n\\end{align}\n\nNote that the equations are non-linear and there can be multiple solutions. These can be interpreted as fixed points of a system of differential equations.\n\n\n```python\ndef f(x):\n return [x[1] - 3*x[0]*(x[0]+1)*(x[0]-1),\n .25*x[0]**2 + x[1]**2 - 1]\n```\n\n\n```python\nsol = root(f, (0.5, 0.5))\nsol.x\n```\n\n\n\n\n array([1.11694147, 0.82952422])\n\n\n\n\n```python\nfsolve(f, (0.5, 0.5))\n```\n\n\n\n\n array([1.11694147, 0.82952422])\n\n\n\n\n```python\nr0 = root(f,[1,1])\nr1 = root(f,[0,1])\nr2 = root(f,[-1,1.1])\nr3 = root(f,[-1,-1])\nr4 = root(f,[2,-0.5])\n\nroots = np.c_[r0.x, r1.x, r2.x, r3.x, r4.x]\n```\n\n\n```python\nY, X = np.mgrid[-3:3:100j, -3:3:100j]\nU = Y - 3*X*(X + 1)*(X-1)\nV = .25*X**2 + Y**2 - 1\n\nplt.streamplot(X, Y, U, V, color=U, linewidth=2, cmap=plt.cm.autumn)\nplt.scatter(roots[0], roots[1], s=50, c='none', edgecolors='k', linewidth=2)\npass\n```\n\n#### We can also give the Jacobian\n\n\n```python\ndef jac(x):\n return [[-6*x[0], 1], [0.5*x[0], 2*x[1]]]\n```\n\n\n```python\nsol = root(f, (0.5, 0.5), jac=jac)\nsol.x, sol.fun\n```\n\n\n\n\n (array([1.11694147, 0.82952422]), array([-4.23383550e-12, -3.31612515e-12]))\n\n\n\n#### Check that values found are really roots\n\n\n\n```python\nnp.allclose(f(sol.x), 0)\n```\n\n\n\n\n True\n\n\n\n#### Starting from other initial conditions, different roots may be found\n\n\n```python\nsol = root(f, (12,12))\nsol.x\n```\n\n\n\n\n array([ 0.77801314, -0.92123498])\n\n\n\n\n```python\nnp.allclose(f(sol.x), 0)\n```\n\n\n\n\n True\n\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "96be26caa6004abd1935923e7d7441130d31fff4", "size": 332723, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/S09A_Root_Finding.ipynb", "max_stars_repo_name": "cjuracek/sta-663-2020", "max_stars_repo_head_hexsha": "9f0e81e783000b1485951322561b3e47acef5072", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 47, "max_stars_repo_stars_event_min_datetime": "2020-01-08T21:45:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T09:25:59.000Z", "max_issues_repo_path": "notebooks/S09A_Root_Finding.ipynb", "max_issues_repo_name": "cjuracek/sta-663-2020", "max_issues_repo_head_hexsha": "9f0e81e783000b1485951322561b3e47acef5072", "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/S09A_Root_Finding.ipynb", "max_forks_repo_name": "cjuracek/sta-663-2020", "max_forks_repo_head_hexsha": "9f0e81e783000b1485951322561b3e47acef5072", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 54, "max_forks_repo_forks_event_min_datetime": "2020-01-08T21:46:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-15T05:04:00.000Z", "avg_line_length": 232.5108315863, "max_line_length": 75264, "alphanum_fraction": 0.9136038086, "converted": true, "num_tokens": 6998, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067228145365, "lm_q2_score": 0.9425067207958835, "lm_q1q2_score": 0.8883189206480036}} {"text": "## The usual imports\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\n# And a new import - scipy's basic ODE integration function\nfrom scipy.integrate import odeint\n```\n\n## Intro - The Euler Method\n\nA first-order ordinary differential equation can be written as \n$$\\frac{d y}{dt} = g(y, t)$$\nThe time derivative can depend on the value of $y(t)$ as well as on $t$. \n\nTo solve a differential equation on a computer, we use a discrete approximation to the derivative\n$$\\frac{d y}{dt} = \\frac{y_{i+1} - y_{i}}{t_{i+1} - t_{i}}$$\nwhere we're evaluating $y$ at discrete *time steps* $t_{i}$.\n\nWe'll work with equal time steps given by $t_{i+1} - t_{i} = \\tau$. The Euler method makes a simple approximation:\n$$y_{i+1} = y_{i} + g_{i} \\tau + O(\\tau^2)$$\nThe last term just means that we've ignored any terms of order $\\tau^2$ or higher. The bigger $\\tau$ is, the bigger the error will be.\n\nWe'll see how this works by solving the equation\n$$\\frac{d y}{dt} = - y ~,$$\nwhich has the solution $y(t) = A~e^{-t}$.\n\n\n```python\ntau = 1.\nyi = 1.\nresult1 = [(0., yi)]\nfor t in np.arange(tau, 6.+tau, tau):\n yi = yi + (-yi) * tau\n result1.append((t, yi))\nresult1 = np.array(result1)\n```\n\n\n```python\ntimes = np.linspace(0.,6.,1000)\nplt.plot(times, np.exp(-times))\nplt.scatter(result1[:,0], result1[:,1], c='g')\n```\n\n**Exercise 0.1**: Make the time step above $\\tau = 1.5$. What happens?\n\n**Exercise 0.2**: Now make two new sets of results with smaller values of $\\tau$ and add them to the plot. Does the solution get better?\n\n## Ex 1 - The Decaying Exponential\n\nNow let's start to use scipy's odeint to solve some differential equations with nice sophisticated integrators. We'll continue to solve\n$$\\frac{d y}{dt} = - y$$\nWe start by defining a function for the right-hand side.\n\n\n```python\n# Defining the function is simple.\ndef f1(y, t):\n return -y\n```\n\n\n```python\n# We'll solve from t = 0 to t = 4, at 100 equally-spaced points.\ntimes = np.linspace(0.,4.,100)\n```\n\n\n```python\ny_init1 = 1. # Starting value for y, at t = 0\nyarr1 = odeint(f1, y_init1, times)\n```\n\n\n```python\nplt.figure(figsize=(8,6))\nplt.plot(times, np.exp(-times), c='g', label='True solution')\nplt.scatter(times, yarr1, s=2, c='k', label='ODE solver')\nplt.legend()\n```\n\n**Exercise 1.1**: Can you make this decay twice as fast?\n\n\n```python\n\n```\n\n**Exercise 1.2**: Can you change the amplitude, i.e. make the solution $2 e^{-t}$ rather than $e^{-t}$?\n\n\n```python\n\n```\n\n## Ex 2 - The Sinusoid\n\nNow let's try to get a sinusoid. We can't do that with a single derivative -- we need a second-order equation. It looks like\n$$ \\frac{d^2 y}{d t^2} = - \\omega^2 y$$\nBut odeint doesn't say anything about second derivatives. How are we supposed to solve this?\n\nThe trick is, we're allowed to have many variables. So let's define a new variable\n$$v_y = \\frac{d y}{d t}$$\n\nIf we take another derivative, we get:\n$$\\frac{d v_y}{d t} = \\frac{d^2 y}{d t}$$\n\nNow we can re-write the above equation as two pieces:\n$$\\begin{align}\n\\frac{d v_y}{d t} &= -\\omega^2 y \\\\\n\\frac{d y}{d t} &= v_y\n\\end{align}$$\n\nWe've gone from one second-order equation to two first-order equations. Our new variable is the velocity.\n\n\n```python\n# The function now takes a vector as input.\nomega = np.pi\ndef f2(vec, t):\n y, vy = vec\n return (vy, -omega*omega*y)\n```\n\n\n```python\ny_init2 = (1., 0.) # Starting value for y, vy at t = 0\nyarr2 = odeint(f2, y_init2, times)\n```\n\n\n```python\nyarr2.shape\n```\n\n\n\n\n (100, 2)\n\n\n\nThe result now has two variables, each one is its own column. Each time is a row. We can use numpy's multi-dimensional slicing to access just the first variable by doing\n\nyarr2\\[:, 0\\]\n\nIn the first slot, we put the slice operator ':' all by itself. This just means take all the data in that dimension. Then we specify that we want column zero, which is the first variable since Python counts from zero.\n\n\n```python\nplt.figure(figsize=(8,6))\nplt.plot(times, np.cos(omega*times), 'g')\nplt.plot(times, yarr2[:,0], 'r:')\n```\n\n**Exercise 2.1**: How do you double the amplitude?\n\n\n```python\n\n```\n\n**Exercise 2.2**: Can you change the result in y from a cosine to a sine? Hint: A sine starts at zero, but it has some initial slope.\n\n\n```python\n\n```\n\n**Exercise 2.3**: Can you change the frequency in the same way? If not, how do you change it?\n\n\n```python\n\n```\n\n**Exercise 2.4**: Copying the example from above, can you modify the equation to add damping? The result should be a decaying sinusoid.\n\n\n```python\n\n```\n", "meta": {"hexsha": "8449831701644efe34fde96aa29ccc669ae344de", "size": 72252, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "IntroODEs/intro_to_ODEs1.ipynb", "max_stars_repo_name": "andrew-lundgren/ComputationalPhysics", "max_stars_repo_head_hexsha": "2dc20e0794b60d4d890ad9470b8d1f84871e1acd", "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": "IntroODEs/intro_to_ODEs1.ipynb", "max_issues_repo_name": "andrew-lundgren/ComputationalPhysics", "max_issues_repo_head_hexsha": "2dc20e0794b60d4d890ad9470b8d1f84871e1acd", "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": "IntroODEs/intro_to_ODEs1.ipynb", "max_forks_repo_name": "andrew-lundgren/ComputationalPhysics", "max_forks_repo_head_hexsha": "2dc20e0794b60d4d890ad9470b8d1f84871e1acd", "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": 171.6199524941, "max_line_length": 31632, "alphanum_fraction": 0.9050960527, "converted": true, "num_tokens": 1367, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248225478306, "lm_q2_score": 0.9458012644479256, "lm_q1q2_score": 0.8881308645137271}} {"text": "## What is symbolic computation?\n\n\"Symbolic computation deals with the computation of mathematical objects symbolically. This means that the mathematical objects are represented exactly, not approximately, and mathematical expressions with unevaluated variables are left in symbolic form.\"\n\n- [SymPy Documentation](https://docs.sympy.org/latest/tutorial/intro.html)\n\n### A More Interesting Example\n\n\n```python\nfrom sympy import *\ninit_printing()\n```\n\n\n```python\n#Definimos los símbolos (SymPy) 'x' e 'y' y los definimos en las \n#variables (Python) 'x' e 'y'\nx,y=symbols('x y')\n\nexpr=x+2*y\nexpr\n```\n\n\n```python\ntype(x)\n```\n\n\n\n\n sympy.core.symbol.Symbol\n\n\n\n\n```python\nexpr+1\n```\n\n\n```python\nexpr-x\n```\n\n\n```python\n#No expande automáticamente\nx*expr\n```\n\n\n```python\n#Podemos expandir una expresión o factorizarla de la siguiente forma+\nfrom sympy import expand, factor\nexpanded_expr=expand(x*expr)\nexpanded_expr\n```\n\n\n```python\nfactor_expr=factor(expanded_expr)\nfactor_expr\n```\n\n### The Power of Symbolic Computation\n\n\n```python\nx,t,z,nu=symbols('x t z nu')\n```\n\n\n```python\n#Tomamos la derivsada de cos(x**2)/x\ndiff(cos(x**2)/x,x)\n```\n\n\n```python\n#Podemos ver la versión simbólica de output anterior usando \n#la función print()\nprint(_)\n```\n\n -2*sin(x**2) - cos(x**2)/x**2\n\n\n\n```python\n#Calculemos la integral de exp(x)*sin(x)+exp(x)*cos(x)\nintegrate(exp(x)*sin(x)+exp(x)*cos(x),x)\n```\n\n\n```python\n#Calculemos la integral de exp(-x**2) desde -oo hatsta +oo\nintegrate(exp(-x**2),(x,-oo,+oo))\n```\n\n\n```python\n#Calcular el límite de (sin(x+t)-sin(x))/t cuando t va a 0\nlimit((sin(x+t)-sin(x))/t,t,0)\n```\n\n\n```python\n#De igual forma\nlimit((cos(x+t)-cos(x))/t,t,0)\n```\n\n\n```python\n#Por defecto el límite se toma por la derecha. \n#Por ejemplo, calculemos el límite cuando 'x' va a cero,\n#luego por la derecha e izquierda de la siguiente expresión\n\nabs(sin(x))/sin(x)\n```\n\n\n```python\nlimit(_,x,0)\n```\n\n\n```python\nlimit(abs(sin(x))/sin(x),x,0,'+')\n```\n\n\n```python\nlimit(abs(sin(x))/sin(x),x,0,'-')\n```\n\n\n```python\n#También podemos imprimir las expresiones que vamos a computar\nIntegral(cos(z)*sin(nu),z,nu)\n```\n\n\n```python\nr,phi,theta,R=symbols('r phi theta R')\n```\n\n\n```python\nIntegral(r**2*sin(theta),(theta,0,pi),(phi,0,2*pi),(r,0,R))\n```\n\n\n```python\nintegrate(r**2*sin(theta),(theta,0,pi),(phi,0,2*pi),(r,0,R))\n```\n\n\n```python\nLimit(exp(cos(t**2)),t,5,'+')\n```\n\n\n```python\n#Podemos resolver ecuaciones introduciendo en el código la expresión\n#que es igual a cero. Por ejemplo, resolvamos la siguiente expresión\n```\n\n$x^2-2=0\\quad\\quad\\quad\\quad(1)$\n\n\n```python\nsolve(x**2-2,x)\n```\n\n\n```python\n#Otra forma de igualar la parte izqueirda y derecha de la ecuación (1)\n#es mediante la instrucción 'Eq()'\n```\n\n\n```python\nEq(x**2-2,0)\n```\n\n\n```python\nsolve(_,x)\n```\n\n\n```python\n#Resolvamos la siguiente ecuación diferencial\n```\n\n$y''-y=e^t\\quad\\quad\\quad\\quad(2)$\n\n\n```python\n#Primero definimos 'y' como una función y a continuación establecemos\n#su argumento\ny=Function('y')\n\n#Ahora aplicamos la primera derivada\ny(t).diff(t)\n```\n\n\n```python\n#Ahora aplicamos la segunda derivada\ny(t).diff(t,t)\n```\n\n\n```python\n#Veamos el código simbólico\nprint(_)\n```\n\n Derivative(y(t), (t, 2))\n\n\n\n```python\n#Ahora sí, a resolver la ecuación diferencial usando 'Eq()'\ndsolve(Eq(y(t).diff(t,t)-y(t),exp(t)),y(t))\n```\n\n\n```python\nEq(4*t*y(t).diff(t,t)+y(t).diff(t)-y(t),0)\n```\n\n\n```python\ndsolve(_)\n```\n\n\n```python\nprint(latex(_))\n```\n\n y{\\left(t \\right)} = t^{\\frac{3}{8}} \\left(C_{1} J_{\\frac{3}{4}}\\left(i \\sqrt{t}\\right) + C_{2} Y_{\\frac{3}{4}}\\left(i \\sqrt{t}\\right)\\right)\n\n\n\n```python\n#Calculemos los autovalores de la siguiente matriz\n```\n\n$\\begin{pmatrix}\n0 & -i\\\\\ni & 0\n\\end{pmatrix}\n$\n\n\n```python\nMatrix([[0,-I],[I,0]]).eigenvals()\n#En el resultado tenemos un diccionario donde el 'key' es el autovalor\n#y el 'value' es la multiplicidad\n```\n\n\n```python\n#Por úñtimo podemos imprimir en código LaTeX para poder copiar\n#directamente a nuestro documento. Para ello usamos 'print()' y 'latex()'\nIntegral(cos(x)**2, (x, 0, pi))\n\n```\n\n\n```python\nprint(latex(_))\n```\n\n \\int\\limits_{0}^{\\pi} \\cos^{2}{\\left(x \\right)}\\, dx\n\n\n\n```python\nprint(Integral(cos(x)**2, (x, 0, pi)))\n```\n\n Integral(cos(x)**2, (x, 0, pi))\n\n", "meta": {"hexsha": "b9383235d504cea9fefb62088498f7dc6b33ed21", "size": 69006, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "IntroToSciPy/SymPy/SymPyTutorial/Introduction.ipynb", "max_stars_repo_name": "migueloayza/LearningPython", "max_stars_repo_head_hexsha": "00fe5e0072d16cb5caa10f546d2708b1beb8c30b", "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": "IntroToSciPy/SymPy/SymPyTutorial/Introduction.ipynb", "max_issues_repo_name": "migueloayza/LearningPython", "max_issues_repo_head_hexsha": "00fe5e0072d16cb5caa10f546d2708b1beb8c30b", "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": "IntroToSciPy/SymPy/SymPyTutorial/Introduction.ipynb", "max_forks_repo_name": "migueloayza/LearningPython", "max_forks_repo_head_hexsha": "00fe5e0072d16cb5caa10f546d2708b1beb8c30b", "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.8015488867, "max_line_length": 4444, "alphanum_fraction": 0.8059878851, "converted": true, "num_tokens": 1395, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.946596665680527, "lm_q2_score": 0.9381240177362488, "lm_q1q2_score": 0.8880250671839527}} {"text": "# Bond Pricing\n\n* maturity (T)\n - date\n* coupon\n - type\n - rate\n - frequency\n* bid/ask prices\n - clean vs. dirty\n - accrued interest\n* yield (r)\n\nbid/ask prices usually are quoted as percentage of par value at a clean price.\n\n\\begin{equation}\n\\text{Bond value}=\\sum_{t=1}^{T}\\frac{\\text{Coupon}}{(1+r)^t}+\\frac{\\text{Par Value}}{(1+r)^T}\n\\end{equation}\n\nIf the coupons and r are fixed:\n\n\\begin{equation}\n\\text{Bond value}=\\frac{\\text{Coupon}}{r}\\times(1-(1+r)^{-T})+\\text{Par Value}\\times(1+r)^{-T}\n\\end{equation}\n\n## Accrued Interest and Quoted Prices\n\nIf you buy a bond x days after its issuance you must pay the accrued interest to the seller as follow:\n\n$$\\text{Dirty Price}=\\text{Clean Price}+\\text{Accrued interest}$$\n\nwhere:\n\n$$\\text{Accrued Interest}=\\frac{\\text{Annual coupon payment}}{\\text{coupon pmt p.a.}}\\times\\frac{\\text{days since last pmt}}{\\text{days between pmts}}$$\n\nIf you don't know the clean price:\n\n1. $T = \\text{maturity date}-\\text{last coupon date}$;\n2. Calculate the FV from the last coupon date to the date you are interest in.\n\n*this price will be the dirty price*\n\n\n\n## Yield to Maturity (YtM)\nYtM is the IRR of the bond - the interest rate that makes the PV of a bond's payments equal to its price.\nIt's the average rate of return that would be earned on a bond held until maturity, if all coupons are reinvested at the same interest rate.\n\n**The relationship between Yield and Bond Price is negative as follows**\n\n\n$$\\uparrow\\text{YtM}\\Longleftrightarrow\\downarrow\\text{Bond price}$$\n\n\n\n```python\ndef quoted_bond_price(maturity, yield_, coupon):\n \"\"\"Prices a bond as percentage of par value.\"\"\"\n annuity_factor = (1/yield_)*(1-(1+yield_)**(-maturity))\n pv_factor = (1+yield_)**(-maturity)\n return coupon*annuity_factor + pv_factor\n```\n\n\n```python\ndef bond_prices_vs_yield(maturity, coupon, yield_i, yield_f):\n \"\"\"Plots the relationship between bond price and yields.\"\"\"\n import numpy as np\n import pandas as pd\n import seaborn as sns\n yields = np.arange(yield_i, yield_f, step=0.01)\n prices = [quoted_bond_price(maturity, x, coupon) for x in yields]\n bond_df = pd.DataFrame({'Yield': yields, 'Price': prices}) \n return sns.lineplot(x=bond_df.Yield, y=bond_df.Price)\n```\n\n\n```python\nbond_prices_vs_yield(30, 0.05, 0.01, 0.2)\n\n```\n\n**The yield-to-Bond price relationship derived above is sensitive to the maturity. Long-term bond's price vary more than short-term bond's price as follows**\n\n\n```python\nimport numpy as np\nfor i in np.arange(1, 30):\n bond_prices_vs_yield(i, 0.05, 0.01, 0.2)\n```\n\n# Interest Rate Sensivity\n* **Yield curve**: is a plot of YtM as function of maturities\n\n1. *Bond prices* and *yields* are *inversely related*: as yields increase, bond prices fall; as yields fall, bond prices rise\n2. An *increase in a bond’s yield to maturity* results in a *smaller price change* than a *decrease in yield* of equal magnitude\n3. *Prices of long-term bonds* tend to be *more sensitive* to *interest rate changes* than prices of short-term bonds\n4. The *sensitivity of bond prices to changes in yields increases at a decreasing rate as maturity increases*. In other words, interest rate risk is less than proportional to bond maturity.\n5. *Interest rate risk is inversely related to the bond’s coupon rate*. Prices of low-coupon bonds are more sensitive to changes in interest rates than prices of high-coupon bonds.\n6. The *sensitivity of a bond’s price to a change in its yield is inversely related to the yield to maturity at which the bond currently is selling*\n\n## Macaulay duration\nMeasures the \"real\" maturity of a bond. It serves as a guide to the sensitivity of a bond to interest rate.\n\n$$D=\\frac{\\sum_{t=1}^{T}t\\times\\frac{CF_t}{(1+YtM)^t}}{\\text{Bond Price}}$$\n\n### Modified duration\n\\begin{array}\n\\text{MD}&=\\frac{D}{(1+YtM)}\\\\\n\\frac{\\Delta P}{P}&=-MD\\times\\Delta YtM\\\\\n\\end{array}\n\n* The duration of a zero-coupon bond is equal its maturity\n* Duration is lower when the coupon is higher\n* Duration is higher when YtM is lower\n* Practitioners use BPV (or PV01): price change in \\% or \\$ for one base point.\n\n$$PV01=MD\\times Price\\times 0.01\\%$$\n\n## wrapping up\n- $\\uparrow\\text{YtM}\\Longleftrightarrow\\downarrow\\text{Bond price}$\n- $\\uparrow\\text{MD}\\Longleftrightarrow\\downarrow\\text{YtM}$\n- $\\uparrow\\text{MD}\\Longleftrightarrow\\downarrow\\text{coupon}$\n- $\\uparrow\\text{MD}\\Longleftrightarrow\\uparrow\\text{maturity}$\n- $\\downarrow\\Delta\\text{MD}\\Longleftrightarrow\\uparrow\\text{maturity}$\n\n\n```python\ndef bond_cash_flows(maturity, coupon_rate, coupons_per_year=1):\n \"\"\"Returns a series of cash flows generated by a bond.\"\"\"\n import numpy as np\n import pandas as pd\n n_coupons = round(maturity*coupons_per_year)\n coupon_pmt = (coupon_rate/coupons_per_year)\n coupon_index = np.arange(1, n_coupons + 1)\n cash_flows = pd.Series(data = coupon_pmt, index = coupon_index)\n cash_flows.iloc[-1] += 1\n return pd.Series(cash_flows)\n\ndef discount(t, r):\n \"\"\"Returns a discounted rates series.\"\"\"\n import pandas as pd\n discounts = pd.Series([(r+1)**-i for i in t])\n discounts.index = t\n return discounts\n\ndef pv(flows, r):\n \"\"\"Computes the pv of cash flows indexed by time.\"\"\"\n dates = flows.index\n discounts = discount(dates, r)\n return discounts.multiply(flows, axis='rows').sum()\n\ndef bond_price(maturity, coupon_rate, coupons_per_year, discount_rate):\n \"\"\"Prices a bond based on its cash flows.\"\"\"\n import pandas as pd\n if maturity <= 0:\n return (1 + coupon_rate/coupons_per_year)\n else:\n cash_flows = bond_cash_flows(maturity,\n coupon_rate, coupons_per_year)\n return pv(cash_flows, discount_rate/coupons_per_year)\n\ndef macauly_duration(cash_flows, discount_rate):\n \"\"\"Computes the Macauly duration of a bond.\"\"\"\n import numpy as np\n import pandas as pd\n discounted_flows = discount(cash_flows.index, discount_rate)*cash_flows\n weights = discounted_flows/discounted_flows.sum()\n return np.average(pd.Series(cash_flows.index), weights=weights)\n\ndef modified_duration(macauly_duration, ytm, maturity):\n \"\"\"Computes the modified duration of a bond.\"\"\"\n return macauly_duration/(1 + ytm/maturity)\n```\n\n\n```python\ndef md_vs_maturity(maturity_i, maturity_f, coupon_rate, ytm):\n import numpy as np\n import pandas as pd\n import seaborn as sns\n maturities = np.arange(maturity_i, maturity_f, step=1)\n mds = []\n for maturity in maturities:\n cf = bond_cash_flows(maturity, coupon_rate=coupon_rate, coupons_per_year=1)\n mds.append(modified_duration(macauly_duration(cf, ytm), ytm, maturity))\n bond_df = pd.DataFrame({'MD': mds, 'Maturity': maturities})\n return sns.lineplot(x=bond_df.Maturity, y=bond_df.MD)\n```\n\n**MD (sensibility) increases as Maturity increases** \n\n\n```python\nmd_vs_maturity(1, 30, 0.08, 0.05)\n```\n\n**MD (sensibility) increases as YtM decreases** \n\n\n```python\nimport numpy as np\nfor i in np.arange(0.01, 0.15, step=0.01):\n md_vs_maturity(1, 30, 0.08, i)\n```\n\n## Convexity\nAs the relationship between bond prices and yields are not linear, the duration rule is good approximation just for small changes in bond yield. Convexity allows improvement on duration aproximation for bond price changes.\n\\begin{array}\n\\text{Convexity}&=\\frac{1}{P\\times(1+YtM)^2}\\times\\sum_{t=1}^{T}\\big(\\frac{CF_t}{(1+YtM)^t}\\times(t^2+t)\\big)\\\\\n\\frac{\\Delta P}{P}&=-MD\\times\\Delta YtM+\\frac{\\text{Convexity}\\times\\Delta YtM^2}{2}\\\\\n\\end{array}\n\n\n```python\n# A bond with 10y maturity, sensitivity 8, yield 4% is priced at 98% what is the coupon?\n# if coupon = yield -> price = 1 -> deltaytm = delta p/MD -> coupon - ytm = delta p/md\nmd = 8\ndelta_p = 0.98 - 1\nytm = 0.04\ncoupon = ytm + delta_p/md\ncoupon\n```\n\n\n\n\n 0.0375\n\n\n\n\n```python\n# A bond is quoted at 110%, its md is 5. supposing the yield goes down by 10 basis points. What would be its price?\nmd = 5\np = 1.10\ndelta_y = -0.001\n-(delta_y*md - p)\n```\n\n\n\n\n 1.105\n\n\n\n\n```python\n# A 10y bond, coupon 2% and md equal to 8.978 and yield 1.95%\n# Price?\n# md = delta price/delta yield -> md*(0.02 - 0.0195)=(p - 1)\nmd = 8.978\ndelta_y = 0.02 - 0.0195\np = md*delta_y + 1\np\n```\n\n\n\n\n 1.004489\n\n\n\n\n```python\n# 210 days later the bond trades with a yield of 2.5%. What are the clean and dirty price?\ndp = quoted_bond_price(10, 0.025, 0.02)*(1+0.025)**(210/365)\nai = 0.02*(210/365)\ncp = dp - ai\nprint('clean Price: ', cp, '; dirty Price: ', dp)\n```\n\n clean Price: 0.9584148073395676 ; dirty Price: 0.9699216566546361\n\n\n\n```python\n# P&L (10M)\n(dp - p)*10\n```\n\n\n\n\n -0.3456734334536382\n\n\n\n# Hedging with duration\n$$\\text{Hedging ratio}=\\frac{P_1\\times MD_1}{P_2\\times MD_2}$$\nor:\n$$HR=-BPV_1/BPV_2$$\n\n1. 10M 3%10y, YtM 2,5% - quoted 104.376%, MD=8,6\n2. x? 2.5%7y, YtM 1.75% - quoted 104.901%, MD=6.41\n\nTo hedge 10M of 1 you need to sell 13.349M of the 2.\n\n\n```python\nhr = (1.04376*8.6)/(1.04901*6.41)\nhr*10\n```\n\n\n\n\n 13.349390669080591\n\n\n\n# Floating Rate Notes (FRN)\n- variable coupon\n- Discount Margin (cristalization)\n 1. last known reference\n 2. yield for a given price\n 3. Discount Margin = yield - Reference\n \n5y bond paying Euribor + 1% coupons\n - last euribor = 2%\n - price 102%\n - MD = 4.61\n \n cristalized coupon = 2% + 1% \n\n\n```python\n# delta p/p = -md * deltaY\ncoupon = 0.03\nmd = 4.61\np =1.02\ndelta_p = 1 - p\ndelta_y = -(delta_p/(p*md))\ny = 0.03 - delta_y\ny - 0.02\n```\n\n\n\n\n 0.005746671770660537\n\n\n", "meta": {"hexsha": "2193f8c71384c9077c52fb933005cf5230414673", "size": 141037, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Bonds.ipynb", "max_stars_repo_name": "caiomts/scripts-tsm-fit", "max_stars_repo_head_hexsha": "2dd6c43c8d999a2e67cb82e6423e416121d0c736", "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": "Bonds.ipynb", "max_issues_repo_name": "caiomts/scripts-tsm-fit", "max_issues_repo_head_hexsha": "2dd6c43c8d999a2e67cb82e6423e416121d0c736", "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": "Bonds.ipynb", "max_forks_repo_name": "caiomts/scripts-tsm-fit", "max_forks_repo_head_hexsha": "2dd6c43c8d999a2e67cb82e6423e416121d0c736", "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": 246.1378708551, "max_line_length": 56116, "alphanum_fraction": 0.9177875309, "converted": true, "num_tokens": 2948, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750427013549, "lm_q2_score": 0.9314625007846135, "lm_q1q2_score": 0.8879399552101632}} {"text": "# Part I - Linear Equations\n\n## 1. Views of linear equations\n\nIt can be reasonable to state that the the linear equations are the most simple equation system and the one that we know the best. Thus, it constitute the basic part of our toolkit and the study of linear algebra.\n\nFor the below linear equations system,\n\n$$\n\\begin{equation}\n2x - y = 0 \\\\\n-x + 2y = 3 \\\\\n\\end{equation}\n$$\n\nIt can be organized the system into a matrix representation as below.And that will lead to two kinds of views of the system.\n\n$$\n\\begin{equation}\n\\left[\n\\begin{matrix}\n 2 & -1 \\\\\n-1 & 2 \\\\\n\\end{matrix}\n\\right]\n\\left[\n\\begin{matrix}\nx \\\\\ny \\\\\n\\end{matrix}\n\\right]\n=\n\\left[\n\\begin{matrix}\n0 \\\\\n3 \\\\\n\\end{matrix}\n\\right]\n\\end{equation}\n$$\n\nAnd the representation can further be summarized in the general form:\n\n$$\\begin{equation}\n\\rm{A}\n\\textbf{x}\n=\n\\textbf{b}\n\\end{equation}$$\n\nwhere \n$\n\\begin{equation}\n\\rm{A}\n=\n\\left[\n\\begin{matrix}\n 2 & -1 \\\\\n-1 & 2 \\\\\n\\end{matrix}\n\\right]\n\\end{equation}\n$\nis called the $\\textit{coefficient matrix}$,\n$\n\\begin{equation}\n\\textbf{x}\n=\n\\left[\n\\begin{matrix}\nx \\\\\ny \\\\\n\\end{matrix}\n\\right]\n\\end{equation}\n$\nis the $\\textit{vector of unknowns}$,\nand \n$\n\\begin{equation}\n\\textbf{b}\n=\n\\left[\n\\begin{matrix}\n0 \\\\\n3 \\\\\n\\end{matrix}\n\\right]\n\\end{equation}\n$\nis the vector coming from the right hand side of the equations.\n\n### View of Row (View of Separate Equations)\n\nBy seeing the system as separate equations, we get the view of row.\n\n$$\n\\begin{equation}\n\\begin{cases}\n2x - y = 0, & Eq1\\\\\n-x + 2y = 3, & Eq2\\\\\n\\end{cases}\n\\end{equation}\n$$\n\nUnder the view of row, solutions are interpreted as the set of points that satisfy all of the equations. Therefore, in geometry, they are the **intersection points of all the geometric objects (lines/planes/hyperplanes)** these equation represent.\n\n### View of Column (View of Linear Combination)\n\nAn alternative view can be: Since all the equations share the same vector of unknowns (if some unknowns are missing, it can be represented as unknowns with 0 coefficient), we can **\"factor out\"** those unknowns and reshape the system like this.\n\n$$\n\\begin{equation}\nx\n\\left[\n\\begin{matrix}\n 2 \\\\\n-1 \\\\\n\\end{matrix}\n\\right]\n+\ny\n\\left[\n\\begin{matrix}\n-1 \\\\\n2 \\\\\n\\end{matrix}\n\\right]\n=\n\\left[\n\\begin{matrix}\n0 \\\\\n3 \\\\\n\\end{matrix}\n\\right]\n\\end{equation}\n$$\n\nIn this view, the different rows of the coefficient vectors are treated as the independent \"coordinates\". For example, the $2$ and $-1$ in\n$\n\\left[\n\\begin{matrix}\n 2 \\\\\n-1 \\\\\n\\end{matrix}\n\\right]\n$\nare treated as the x-coordinate and the y-coordinate.\nAnd the solution to the euqations are interpreted as the **correct multiples** of these coefficient vectors such that the sum of them equals the the right hand side $\\textbf{b}$.\n\nFollowing this view, since the coefficient vectors constitute the columns of the coefficient matrix, we call them the $\\textit{column vectors}$. And solving the linear equations is equivalent to finding the correct multiples of the column vectors. Or to say, finding the correct $\\textit{linear combination}$ of the column vectors.\n\nBy linear combination, we mean adding/subtracting and multipling vectors by **scalars (pure numbers)**.\n\n## 2. Gaussian Elimination\n\n### Prerequisite: Matrix Multiplication\n\nThe most elementary and mechanical view of matrix multiplication is the **element view**. This view focuses on every single element of the resulting matrix, and is more often used in simple calculations. In particular, for a $m\\times{n}$ matrix $\\rm{A}$ and a $n\\times{p}$ matrix $\\rm{B}$, the resulting matrix $\\rm{C}=\\rm{AB}$ is a $m\\times{p}$ matrix. And a general element in row $i$ and column $j$ of matrix $\\rm{C}$ is:\n\n$$\n\\begin{equation}\nc_{ij} = \\sum_{k=1}^{n} a_{ik}b_{kj}\n\\end{equation}\n$$\n\nFrom Section 1 we have seen that when a matrix is multiplied by a vector on the right, it is equivalent to taking the $\\textit{linear combination}$ of the columns of that matrix. And that helps to introduce the **vector view** of matrix multiplication.\n\nNotice that from the **element view** formula, all of the elements in column $j$ (denoted as $\\rm{C_{j}}$) of the resulting matrix $\\rm{C}$ are only influenced by the repective column $j$ (denoted as $\\rm{B_{j}}$) in matrix $\\rm{B}$, rather then the other columns from matrix $\\rm{B}$. And the elements of $\\rm{C_{j}}$ can be seen as the linear combination of the columns of $\\rm{A}$. In other words, $\\rm{A}B_{j}=C_{j}$.\n\nFor detailed demonstration, think about the case that a $3\\times{2}$ matrix $\\rm{A}$ multiplies a $2\\times{3}$ matrix $\\rm{B}$, where the resulting matrix is a $3\\times{3}$ matrix $\\rm{C}$. The first column of $\\rm{C}$ comes from the first columns of $\\rm{B}$ with elements computed as follows.\n\n$$\n\\begin{equation}\n\\begin{aligned}\nc_{11} &= a_{11}b_{11} + a_{12}b_{21} + a_{13}b_{31} \\\\\nc_{21} &= a_{21}b_{11} + a_{22}b_{21} + a_{23}b_{31} \\\\\nc_{31} &= a_{31}b_{11} + a_{32}b_{21} + a_{33}b_{31} \\\\\n\\end{aligned}\n\\end{equation}\n$$\n\nGoing through the trick we have seen in Section 1 we may have,\n\n$$\n\\begin{equation}\nC_{1}\n=\n\\left[\n\\begin{matrix}\nc_{11} \\\\\nc_{21} \\\\\nc_{31} \\\\\n\\end{matrix}\n\\right]\n=\nb_{11}\n\\left[\n\\begin{matrix}\na_{11} \\\\\na_{21} \\\\\na_{31} \\\\\n\\end{matrix}\n\\right]\n+\nb_{21}\n\\left[\n\\begin{matrix}\na_{12} \\\\\na_{22} \\\\\na_{32} \\\\\n\\end{matrix}\n\\right]\n+\nb_{31}\n\\left[\n\\begin{matrix}\na_{13} \\\\\na_{23} \\\\\na_{33} \\\\\n\\end{matrix}\n\\right]\n=\n\\left[\n\\begin{matrix}\na_{11} & a_{12} & a_{13}\\\\\na_{21} & a_{22} & a_{23}\\\\\na_{31} & a_{32} & a_{33}\\\\\n\\end{matrix}\n\\right]\n\\left[\n\\begin{matrix}\nb_{11} \\\\\nb_{21} \\\\\nb_{31} \\\\\n\\end{matrix}\n\\right]\n=\n\\rm{AB_{1}}\n\\end{equation}\n$$\n\nTherefore, in **verctor view**, we have the following important conclusions:\n\nFor the product of matrix multiplication $\\rm{C}=\\rm{AB}$,\n1. The column of $\\rm{C}$ is a linear combination of the columns of of $\\rm{A}$.\n2. The row of $\\rm{C}$ is a linear combination of the rows of of $\\rm{B}$.\n\nThe second conclusion can be proved like the way we do above. Since matrix multiplication is not commutative, the $\\rm{A}$ and $\\rm{B}$ cannot be interchanged under most circumstances.\n\n### Warm-up from High Schools\n\nIn high school, students learned how to solve simple linear equations through eliminating variables and simplifying the system. For general linear equation systems, since they can be represented by matrices, the idea of finding the solutions is alike but extended to the operation of matrices.\n\nFor example, concerning the linear equations below, we may cancel the $x$ variable in $Eq2$ through multiplying the $Eq1$ by 3 and subtract that from $Eq2$, which will result in a new equation $Eq2^{'}$ with no $x$ variable. And then further eliminating $y$ in $Eq3$ by subtracting 2 times of $Eq2^{'}$ from it. Then the equations can be easily solved by $\\textit{backsubstitution}$: solving z by $Eq3^{'}$, then using z to solve y by $Eq2^{'}$...\n\n$$\n\\begin{equation}\n\\begin{aligned}\nx + 2y + z &= 2 &Eq1\\\\\n3x + 8y + z &= 12 &Eq2\\\\\n 4y + z &= 2 &Eq3\\\\\n\\end{aligned}\n\\ \\rightarrow\\ \n\\begin{aligned}\nx + 2y + z &= 2 &Eq1\\\\\n 2y - 2z &= 6 &Eq2^{'}\\\\\n 4y + z &= 2 &Eq3\\\\\n\\end{aligned}\n\\ \\rightarrow\\ \n\\begin{aligned}\nx + 2y + z &= 2 &Eq1\\\\\n 2y - 2z &= 6 &Eq2^{'}\\\\\n 5z &= -10 &Eq3^{'}\\\\\n\\end{aligned}\n\\end{equation}\n$$\n\n### Matrix Representation of the Elimination Process\n\nSince the linear equations can be represented by matrices, the elimination process above can also be stated in the language of matrices. First of all, the original equations can be represented by the following $\\textit{augmented matrix}$. By $\\textit{augmented}$, we mean adding an extra column to the coefficient matrix $\\rm{A}$ to represent the right hand side vector $\\textbf{b}$. \n\nRemember that in order to have the same solution, when multiplying or subtracting the equations in the system should do the same manipulation to the both sides of the equations.\n\n$$\n\\begin{equation}\n\\left[\n\\begin {array}{c|c}\n\\rm{A}&\n\\textbf{b}\n\\end {array}\n\\right]\n=\n\\left[{\n\\begin {array}{c|c}\n\\begin{matrix}\n1 & 2 & 1 \\\\\n3 & 8 & 1 \\\\\n0 & 4 & 1 \\\\\n\\end{matrix}&\n\\begin{matrix}\n2 \\\\\n12 \\\\\n2\\\\\n\\end{matrix}\n\\end{array}}\n\\right]\n\\end{equation}\n$$\n\nGiven this the elimination above can be restated in matrix language, which again, can be solved in ease.\n\n$$\n\\begin{equation}\n\\left[\n{\\begin{array}{c|c}\n\\begin{matrix}\n1 & 2 & 1 \\\\\n3 & 8 & 1 \\\\\n0 & 4 & 1 \\\\\n\\end{matrix}&\n\\begin{matrix}\n2 \\\\\n12 \\\\\n2\\\\\n\\end{matrix}\n\\end{array}}\n\\right]\n\\ \\rightarrow \\ \n\\left[\n{\\begin{array}{c|c}\n\\begin{matrix}\n1 & 2 & 1 \\\\\n0 & 2 & -2 \\\\\n0 & 4 & 1 \\\\\n\\end{matrix}&\n\\begin{matrix}\n2 \\\\\n6 \\\\\n2\\\\\n\\end{matrix}\n\\end{array}}\n\\right]\n\\ \\rightarrow \\ \n\\left[\n{\\begin{array}{c|c}\n\\begin{matrix}\n1 & 2 & 1 \\\\\n0 & 2 & -2 \\\\\n0 & 0 & 5 \\\\\n\\end{matrix}&\n\\begin{matrix}\n2 \\\\\n6 \\\\\n-10\\\\\n\\end{matrix}\n\\end{array}}\n\\right]\n=\n\\left[\n\\begin {array}{c|c}\n\\rm{U}&\n\\textbf{c}\n\\end {array}\n\\right]\n\\end{equation}\n$$\n\n### Mathematical View of Matrix Operation\n\nThe next thing we are going to do is to express the operations in the elimination process through mathematical language. \n\nIn the elimination process, what we have done is taking multiples of the equations and performing addition or subtraction operations among them. \n\nIn matrix language, we are manipulating the rows of the coefficient matrix or the augmented matrix. Recall from matrix multiplication, this can be expressed by multiplying a matrix on the left side, since taking multiples of the rows and performing addition or subtraction operations among them are just taking the $\\textit{linear combinations}$.\n\nBasically, the procedures taken in the elimination process can be **decomposed** into fundamental ones represented by the so-called $\\textit{elimination matrices}$. In particular, the matrix representing the procedures needed to eliminate the entry $\\textit a_{ij}$ is denoted as the elimination matrix $\\textit E_{ij}$.\n\nFor example, for eliminating the 3 in row 2 and column 1 in the above matrix $\\rm{A}$, we need to multiply the first row by 3 and subtract it from the second row of $\\rm{A}$. In the language of matrix operation, \n$\n\\begin{equation}\n\\textit E_{21}\n=\n\\left[\n\\begin{matrix}\n1 & 0 & 0 \\\\\n-3 & 1 & 0 \\\\\n0 & 0 & 1 \\\\\n\\end{matrix}\n\\right]\n\\end{equation}\n$. \nAnd \n$\\begin{equation}\n\\textit E_{21}\\rm{A}\n=\n\\left[\n\\begin{matrix}\n1 & 2 & 1 \\\\\n0 & 2 & -2 \\\\\n0 & 4 & 1 \\\\\n\\end{matrix}\n\\right]\n\\end{equation}\n$ will eliminate the element $\\textit a_{21}=3$.\n\nThen the process can continue to eliminate $\\textit a_{32}$ by multiplying\n$\n\\begin{equation}\n\\textit E_{32}\n=\n\\left[\n\\begin{matrix}\n1 & 0 & 0 \\\\\n0 & 1 & 0 \\\\\n0 & -2 & 1 \\\\\n\\end{matrix}\n\\right]\n\\end{equation}\n$ \nand get the final result $\\rm{U}$.\nSince matrix multiplication is **associative**, all the elimination matrix can be grouped together and computed first, denoted as $\\textit{E}$.\n\n$$\n\\begin{equation}\n\\textit E_{32}\\ (E_{21}\\rm{A})\n=\n(\\textit E_{32}\\ \\textit E_{21})\\rm{A}\n=\n\\left[\n\\begin{matrix}\n1 & 2 & 1 \\\\\n0 & 2 & -2 \\\\\n0 & 0 & 5 \\\\\n\\end{matrix}\n\\right]\n=\n\\rm{U}\n\\end{equation}\n$$\n$$\n\\textit E = \\textit E_{32}\\ \\textit E_{21}\n$$\n\nAnd for the equations to have the same solutions as the original ones, the same multiplication should also be applied to the right hand side vector $\\textbf{b}$, such that $\\textit E\\textbf{b} = \\textbf{c}$. \n\nThus, the original linear equations system \n$\n\\begin{equation}\n\\rm{A}\n\\textbf{x}\n=\n\\textbf{b}\n\\end{equation}\n$\nhas been transformed into a new system\n$\n\\begin{equation}\n(\\textit E\\rm{A})\n\\textbf{x}\n=\n\\rm{U}\n\\textbf{x}\n=\n\\textbf{c}\n\\end{equation}\n$, which can be easily solved by the $\\textit{backsubstitution}$ procedure.\nAnd most importantly, the solutions stay the same.\n\n### Additional comments\n\nWhen conductiong the elimination process, the final elements we put on the diagonal are often called as $\\textit{pivot}$, including the elements $\\textit u_{11}=1$, $\\textit u_{22}=2$, $\\textit u_{33}=5$ in the resulting matrix $\\rm{U}$. Those are the elements we usually used to eliminate other elements below them. \n\nWhat worths noticing is that a $\\textit{pivot}$ cannot be zero. In case of seeing a zero in the diagonal position, we will try to do **row exchange** with a row below and make the pivot non-zero. This can be done by multiplying a group of matrices called the $\\textit{permutation matrices}$.\nHowever, if no non-zero element is available, then the matrix will have some problems or some additional properties. We called this kind of matrix $\\textit{not invertible}$.\n\nFor example, if \n$\\begin{equation}\n\\rm{A}\n=\n\\left[\n\\begin{matrix}\n1 & 2 & 1 \\\\\n3 & 6 & 1 \\\\\n0 & 4 & 1 \\\\\n\\end{matrix}\n\\right]\n\\end{equation}\n$,\nthen after eliminating the $a_{21}=3$,\n$\\textit E_{21}\\rm{A}\n=\n\\left[\n\\begin{matrix}\n1 & 2 & 1 \\\\\n0 & 0 & -2 \\\\\n0 & 4 & 1 \\\\\n\\end{matrix}\n\\right]\n$\nwould have $a_{22}=0$.\n\nAt the time, we need to multiply an additional permutation matrix which will perform a swap between row 2 and row 3 of \n$\\textit E_{21}\\rm{A}$. And the permutation matrix \n$\\begin{equation}\nP_{23}\n=\n\\left[\n\\begin{matrix}\n1 & 0 & 0 \\\\\n0 & 0 & 1 \\\\\n0 & 1 & 0 \\\\\n\\end{matrix}\n\\right]\n\\end{equation}\n$\nwould finish the job. (Using the **vector view** of matrix multiplication, multiplying a matrix from the left is taking linear combination of the rows. Therefore, the second row of the product is the third row of $\\textit E_{21}\\rm{A}$, and the third row is the second row of $\\textit E_{21}\\rm{A}$.Thus, \n$\\begin{equation}\nP_{23}\\textit E_{21}\\rm{A}\n=\n\\left[\n\\begin{matrix}\n1 & 2 & 1 \\\\\n0 & 4 & 1 \\\\\n0 & 0 & -2 \\\\\n\\end{matrix}\n\\right]\n\\end{equation}\n$.)\n\n## 3. Inverse\n\nFor square matrices, there is one special family of members that deserves further attention. Each of them, say $\\rm{A}$, is paired with another matrix called its $\\textit{inverse}$ $\\rm A^{-1}$ such that $\\rm AA^{-1} = A^{-1}A = I$.\n\nNot all of the square matrices have the corresponding inverse matrices. Those do have their corresponding inverse matrices are called $\\textit{invertible}$ or $\\textit{non-singular}$. And those cannot find the corresponding inverse matrices are called $\\textit{singluar matrices}$.\n\nThe most simple example of inverse matrices are those corresponding to the $\\textit{elimination matrices}$ or the $\\textit{permutation matrices}$, which just undo the elimination or permutation steps.\n\nFor example, if \n$\n\\begin{equation}\n\\textit E_{21}\n=\n\\left[\n\\begin{matrix}\n1 & 0 & 0 \\\\\n-3 & 1 & 0 \\\\\n0 & 0 & 1 \\\\\n\\end{matrix}\n\\right]\n\\end{equation}\n$,\nthen the corresponding inverse\n$\n\\begin{equation}\n\\textit E_{21}^{-1}\n=\n\\left[\n\\begin{matrix}\n1 & 0 & 0 \\\\\n3 & 1 & 0 \\\\\n0 & 0 & 1 \\\\\n\\end{matrix}\n\\right]\n\\end{equation}\n$.\n\nIn words, what $\\textit E_{21}^{-1}$ is doing is just adding 3 times of the row 1 to row 2 of matrix $\\rm{A}$, which is just the opposite of what $\\textit E_{21}$ is doing. Therefore, the result of the two operations is just the matrix $\\rm{A}$ itself, represented by $\\textit E_{21}^{-1}\\textit E_{21}=\\rm{I}$, ie multiplying an identity matrix.\n\n### Relation with linear equations\n\nThe idea of inverse matrices is closely related to the solution of linear equations. If the coefficient matrix $\\rm{A}$ has an inverse, then solution of the linear equation system\n$\n\\begin{equation}\n\\rm{A}\n\\textbf{x}\n=\n\\textbf{b}\n\\end{equation}\n$\ncan be easily found by multiplying the inverse $\\rm{A^{-1}}$ on both sides, such that\n\n$$\n\\begin{equation}\n\\rm{A^{-1}A}\n\\textbf{x}\n=\n\\rm{A^{-1}}\\textbf{b} \\\\\n\\textbf{x}\n=\n\\rm{A^{-1}}\\textbf{b}\n\\end{equation}\n$$.\n\nMoreover, if $\\rm{A}$ has an inverse, the corresponding **homogeneous equation system** $\\rm{A}𝐱 = 0$ has the unique solution $𝐱=0$, which means that the column vectors in $\\rm{A}$ are $\\textit{linear independent}$. The concept of linear independence is the key to finding overall properties of the solutions to a linear equation system \n$\n\\begin{equation}\n\\rm{A}\n\\textbf{x}\n=\n\\textbf{b}\n\\end{equation}\n$\nand will be introduced in later parts.\n\n### Gauss-Jordan Elimination\n\nThe next issue becomes, how to find an inverse of a square matrix, if it exists. In fact, finding the inverse can also be accomplished through **row operations**, given that $\\rm A^{-1}A = I$. \n\nAssume that we are doing a series of row operations and get the inverse of $\\rm{A}$, and the product of those row operation matrices is $E=\\rm A^{-1}$. Now suppose we perform these series of operations with two matrices $\\rm{A}$ and $\\rm{I}$ simutaneously, and record them through two blocks of a matrix. Then the inverse will automatically turn out in the second block.\n\n$$\n\\begin{equation}\nE\n\\begin{matrix}\n\\left[\n\\begin {array}{c|c}\n\\rm{A}&\n\\rm{I}\n\\end {array}\n\\right]\n\\end{matrix}\n=\n\\begin{matrix}\n\\left[\n\\begin {array}{c|c}\n\\rm{I}&\nE\n\\end {array}\n\\right]\n\\end{matrix}\n\\end{equation}\n$$\n\nTherefore, by **augmenting** an extra block of a identity matrix, we can keep track of the row operations which turn $\\rm{A}$ into $\\rm{I}$. Specifically, the row operations are done in the manner of Gaussian elimination, but continue to **eliminate the upper right entries** above the diagonal, and normalize the diagonal entries into 1.\n\nFor example, to find the inverse of the matrix \n$\n\\left[\n\\begin{matrix}\n1 & 3 \\\\\n2 & 7 \\\\\n\\end{matrix}\n\\right]\n$,\nwe augment an identity matrix to the right, and start to perform the elimination.\n\n$$\n\\left[\n\\begin{array}{c|c}\n\\begin{matrix}\n1 & 3 \\\\\n2 & 7 \\\\\n\\end{matrix}&\n\\begin{matrix}\n1 & 0 \\\\\n0 & 1 \\\\\n\\end{matrix}\n\\end{array}\n\\right]\n\\ \\rightarrow \\ \n\\left[\n\\begin{array}{c|c}\n\\begin{matrix}\n1 & 3 \\\\\n0 & 1 \\\\\n\\end{matrix}&\n\\begin{matrix}\n1 & 0 \\\\\n-2 & 1 \\\\\n\\end{matrix}\n\\end{array}\n\\right]\n\\ \\rightarrow \\ \n\\left[\n\\begin{array}{c|c}\n\\begin{matrix}\n1 & 0 \\\\\n0 & 1 \\\\\n\\end{matrix}&\n\\begin{matrix}\n7 & -3 \\\\\n-2 & 1 \\\\\n\\end{matrix}\n\\end{array}\n\\right]\n$$\n\n## 4. First Factorization: A=LU\n\nThe elimination process produces $\\textit E\\rm{A} = \\rm{U}$ and $\\rm{U}\\textbf{x} = \\text{c}$, where $\\textit {E}$ is the product of a series of elimination matrices. Assume that we do not need to perform any permutation, or to say multiply any permutation matrices during the elimination process.\n\nWe know that the $\\textit{elimination matrices}$ always have their corresponding inverses, since what they do is taking $\\textit{linear combinations}$ of the rows in $\\rm{A}$. For example,\n$\n\\begin{equation}\n\\textit E_{21}\n=\n\\left[\n\\begin{matrix}\n1 & 0 & 0 \\\\\n-3 & 1 & 0 \\\\\n0 & 0 & 1 \\\\\n\\end{matrix}\n\\right]\n\\end{equation}\n$\nabove is just taking 3 times of the first row and subtracting it from the second row of matrix $\\rm{A}$. Therefore, adding 3 times of the first row to the second row of the **product**, namely multiplying \n$\n\\begin{equation}\n\\textit E_{21}^{-1}\n=\n\\left[\n\\begin{matrix}\n1 & 0 & 0 \\\\\n3 & 1 & 0 \\\\\n0 & 0 & 1 \\\\\n\\end{matrix}\n\\right]\n\\end{equation}\n$\non the left will give the identity matrix $\\rm{I}$ back.\n\nBack to the product of elimination matrices $\\textit {E}$, $\\textit {E}$ must have an inverse. If we multiply the inverse $\\textit E^{-1}$ on both sides of $\\textit E\\rm{A} = \\rm{U}$. We will get,\n\n$$\n\\rm{A} = \\textit E^{-1}\\rm{U}\n$$\n\nNotice there are two important properties for the two matrices on the right,\n1. $\\textit {E}$ and $\\textit E^{-1}$ are both lower triangular matrices.\n2. $\\rm {U}$ is a upper triangular matrix.\n\nThe fact that $\\rm{U}$ is upper triangular is obvious, since we knock off all the entries below the diagonal in the elimination process. And every elimination matrix $\\textit E_{ij}$ is lower triangular, since we always subtract a multiple of one **upper** row from row $i$ that contains the element $a_{ij}$. Similarly, the inverse of $\\textit E_{ij}$, which **undo** the row operation in $\\textit E_{ij}$, is also a lower triangular matrix. Lastly, the **product** of two lower triangular matrices is once agin a lower triangular matrix, which will give us property 1.\n\nBecause of these two properties, we often denote the $\\textit E^{-1}$ on the right hand side as $\\rm{L}$ to signify its lower triangular nature. Thus, we arrived at the first **factorization** of a matrix.\n\n$$\n\\rm{A} = \\rm{L} \\rm{U}\n$$\n\nThis means the information contains in $\\rm{A}$ is now **decomposed** into two parts, storing in $\\rm{L}$ and $\\rm{U}$ respectively.\n\n### Additional comments\n\nIn order to decompose $\\rm{A}$ into two triangular matrices $\\rm{L}$ and $\\rm{U}$, we have assumed that no permutation will need to perform. That is surely not the case all the time. If we do need to perform any permutation, represented by a permutation matrix $\\textit{P}$, we will accomplish it **before** the elimination or decomposition process, such that the result of permutation $\\textit{P}\\rm{A}$, will become a matrix that does not require further permutations.\n\nThis additional procedure gives us back to the case discussed above, with a generalized form of\n\n$$\n\\textit{P} \\rm{A} = \\rm{L} \\rm{U}\n$$\n", "meta": {"hexsha": "75d941b0e3e681662ebca93571d0c2748a078fb9", "size": 33811, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Part I - Linear Equations.ipynb", "max_stars_repo_name": "Explorer-Ken/Quick-Linear-Algebra", "max_stars_repo_head_hexsha": "1bdc28ee9f9bb4cf49461c0a0aa08258413a8d12", "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": "Part I - Linear Equations.ipynb", "max_issues_repo_name": "Explorer-Ken/Quick-Linear-Algebra", "max_issues_repo_head_hexsha": "1bdc28ee9f9bb4cf49461c0a0aa08258413a8d12", "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": "Part I - Linear Equations.ipynb", "max_forks_repo_name": "Explorer-Ken/Quick-Linear-Algebra", "max_forks_repo_head_hexsha": "1bdc28ee9f9bb4cf49461c0a0aa08258413a8d12", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.5807269653, "max_line_length": 580, "alphanum_fraction": 0.5219603088, "converted": true, "num_tokens": 6320, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172659321807, "lm_q2_score": 0.9353465125449002, "lm_q1q2_score": 0.8875664553833069}} {"text": "# Homework - 1 \n\n#####Vectors and Matrices \n\nConsider the matrix X and the vectors y and z below:\n\n$$ \n\\mathbf{X} = \n\\begin{bmatrix} \n2&4 \\\\\n1&3\n\\end{bmatrix}\n$$\n\n$$\\mathbf{y} = \\begin{bmatrix} 1 \\\\ 3 \\end{bmatrix}$$\n\n$$\\mathbf{z} = \\begin{bmatrix} 2 \\\\ 3 \\end{bmatrix}$$\n\n\n\n\n**1. What is the inner product of the vectors y and z? (this is also sometimes called the dot product, and is sometimes written $y^Tz$)**\n\nInner Product of y and z ($y^T z$) = $(1 * 2) + ( 3 * 3) = 11$ \n\n\n```\n# Inner Product of two vectors using Numpy\nimport numpy as np\ny = np.array([[1], [3]])\nz = np.array([[2], [3]])\n\nprint np.vdot(y,z)\n```\n\n 11\n\n\n**2. What is the product Xy?**\n\nXy = $\\begin{bmatrix} (2 * 1) + ( 1 * 3) \\\\(4 * 1) + (3 * 3) \\end{bmatrix}$\n\nXy = $\\begin{bmatrix} 5 \\\\ 13 \\end{bmatrix}$\n\n\n```\n# Matrix Vector multiplication using Numpy\nX = np.array([[2,1],[4,3]])\ny = np.array([[1], [3]])\n\nprint X.dot(y)\n```\n\n [[ 5]\n [13]]\n\n\n**3. Is X invertible? If so, give the inverse, and if no, explain why not.**\n\nA n x n square matrix A is said to be invertible or nonsingular if there exists any n x n square matrix B such that $$ AB = BA = I_n $$ , where $I_n$ is a n x n Identity matrix.\n\nThe inverse matrix of $X$, denoted by $X^{-1}$ is $$\\mathbf{X^{-1}} = \\begin{bmatrix} 1.5&-0.5 \\\\ -2&1 \\end{bmatrix}$$\n\n\n```\n# Inverse of X in Numpy\nfrom numpy.linalg import inv\nX_inv = inv(X)\nprint 'Inverse of X is:'\nprint X_inv\n\nprint 'X * X_inv is an Identity Matrix'\nprint X.dot(X_inv)\n```\n\n Inverse of X is:\n [[ 1.5 -0.5]\n [-2. 1. ]]\n X * X_inv is an Identity Matrix\n [[ 1. 0.]\n [ 0. 1.]]\n\n\n**4. What is the rank of X?**\n\nThe rank of X is 2, since the column rank is 2.\n\n##### Calculus\n\n**1. If $y = x^3 + x − 5$ then what is the derivative of y with respect to x?**\n\nDerivative of y w.r.t x is: $ \\frac{dy}{dx} = 3x^2 + 1$\n\n**2. If $y = x\\:sin(z)\\:e^{−x}$ then what is the partial derivative of y with respect to x?**\n\nUsing Product Rule and the fact that derivative of $e^{-x} = -e^{-x}$, $x = 1$, we have \n\n$\\frac{\\partial y}{\\partial x} = sin(z)\\:e^{-x} - x\\:sin(z)\\:e^{-x}$\n\n##### Probability and Statistics\n\nConsider a sample of data S = {1, 1, 0, 1, 0} created by flipping a coin x five times, where 0 denotes that the coin turned up heads and 1 denotes that it turned up tails.\n\n**1. What is the sample mean for this data?**\n\nSample Mean is $\\frac{1 + 1 + 0 + 1 + 0}{5} = \\frac{3}{5}$\n\n**2. What is the sample variance for this data?**\n\nSample Variance is $\\frac{6}{25}$\n\n** 3. What is the probability of observing this data, assuming it was generated by flipping a coin with an equal probability of heads and tails (i.e. the probability distribution is p(x = 1) = 0.5, p(x = 0) = 0.5).**\n\nSince it is a sequence of five independent tosses with P(H) = P(T) = 0.5, \nP(S) = $(\\frac{1}{2})^5 = \\frac{1}{32}$\n\n\n** 4. Note that the probability of this data sample would be greater if the value of p(x = 1) was not 0.5, but instead some other value. What is the value that maximizes the probability of the sample S. Please justify your answer.**\n\nAnswer:\nLet p(x=1) = p. Therefore, we have p(x=0) = 1-p. If n is the number of tosses, we have the total probability as $\\prod\\limits_{i=1}^n p^{x_i} \\: (1-p)^{x_i} = p^{\\sum_{i=1}^n x_i} \\: (1-p)^{n - \\sum_{i=1}^n x_i}$\n\nLet y = $ {\\sum_{i=1}^n x_i} $. \n\nThe above equation can be now written as $ p^{y} \\: (1-p)^{n - y}$\n\nSince we need to find the value of p that maximizes the probability of sample S, we can take the log of the above equation, take its derivative w.r.t p, set it to zero and solve for p.\n\nTaking the log, we have $y\\>log(p) + (n-y)\\>log(1-p)$, since $log(a^p) = p\\>log(a)$ and $log(a * b) = log(a) + log(b)$.\n\nTaking the derivative w.r.t p and setting it to 0 and solving for p, we have:\n\n$$\\begin{equation}\n\\begin{split}\n\\frac{dl(p)}{dp} & = \\frac{y}{p} + \\frac{n-y}{(1-p)} = 0 \\\\\n \\implies 0 & = \\frac{(1-p)\\>y + p\\>(n - y)}{p\\>(1-p)} \\\\\n \\implies 0 & = \\frac{y - py + py - pn}{p\\>(1-p)} \\\\\n \\implies 0 & = \\frac{y - pn}{p\\>(1-p)} \\\\\n pn & = y \\\\\n p & = \\frac{1}{n} y \\\\\n p & = \\frac{1}{n} {\\sum_{i=1}^n x_i} \\\\\n\\end{split}\n\\end{equation}$$\n\nPlugging in the values for $x_i$ and n=5, we get $\\boxed{p = \\frac{3}{5}}$\n\n\n```\n# Custom Styling - Please ignore\n# Custom CSS Styling \nfrom IPython.core.display import HTML\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", "meta": {"hexsha": "e05c8b6d1cb8649cf037333ba6cfbc39747e7a4f", "size": 11770, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "coursework/CMU 10-601/Homework 1.ipynb", "max_stars_repo_name": "mathkann/ML", "max_stars_repo_head_hexsha": "65ace09c7327c2625ed176bc7d0e7ad46794218e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2015-08-15T11:16:14.000Z", "max_stars_repo_stars_event_max_datetime": "2015-08-15T11:16:14.000Z", "max_issues_repo_path": "coursework/CMU 10-601/Homework 1.ipynb", "max_issues_repo_name": "mathkann/ML", "max_issues_repo_head_hexsha": "65ace09c7327c2625ed176bc7d0e7ad46794218e", "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": "coursework/CMU 10-601/Homework 1.ipynb", "max_forks_repo_name": "mathkann/ML", "max_forks_repo_head_hexsha": "65ace09c7327c2625ed176bc7d0e7ad46794218e", "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": 31.8108108108, "max_line_length": 243, "alphanum_fraction": 0.4341546304, "converted": true, "num_tokens": 2142, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299653388752, "lm_q2_score": 0.9591542867170962, "lm_q1q2_score": 0.8874382874538925}} {"text": "# Diving into symbolic computing with SymPy\n\n\n```\nfrom sympy import *\ninit_printing()\n```\n\n\n```\nvar('x y')\n```\n\n\n```\nx, y = symbols('x y')\n```\n\n\n```\nexpr1 = (x + 1) ** 2\nexpr2 = x**2 + 2 * x + 1\n```\n\n\n```\nexpr1 == expr2\n```\n\n\n\n\n False\n\n\n\n\n```\nsimplify(expr1 - expr2)\n```\n\n\n```\nexpr1.subs(x, expr1)\n```\n\n\n```\nexpr1.subs(x, pi)\n```\n\n\n```\nexpr1.subs(x, S(1) / 2)\n```\n\n\n```\n_.evalf()\n```\n\n\n```\nf = lambdify(x, expr1)\n```\n\n\n```\nimport numpy as np\nf(np.linspace(-2., 2., 5))\n```\n\n\n\n\n array([ 1., 0., 1., 4., 9.])\n\n\n", "meta": {"hexsha": "b9e266fea6338a8a69665c576ee806e5376fadb2", "size": 16039, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Chapter15/01_sympy_intro.ipynb", "max_stars_repo_name": "PacktPublishing/IPython-Interactive-Computing-and-Visualization-Cookbook-Second-Edition", "max_stars_repo_head_hexsha": "7c41466113641abf7070f7bd14cc687c19c9c1ea", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16, "max_stars_repo_stars_event_min_datetime": "2018-03-06T19:38:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-25T06:54:38.000Z", "max_issues_repo_path": "Chapter15/01_sympy_intro.ipynb", "max_issues_repo_name": "PacktPublishing/IPython-Interactive-Computing-and-Visualization-Cookbook-Second-Edition", "max_issues_repo_head_hexsha": "7c41466113641abf7070f7bd14cc687c19c9c1ea", "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": "Chapter15/01_sympy_intro.ipynb", "max_forks_repo_name": "PacktPublishing/IPython-Interactive-Computing-and-Visualization-Cookbook-Second-Edition", "max_forks_repo_head_hexsha": "7c41466113641abf7070f7bd14cc687c19c9c1ea", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 17, "max_forks_repo_forks_event_min_datetime": "2018-02-19T16:11:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-25T06:54:40.000Z", "avg_line_length": 67.3907563025, "max_line_length": 4412, "alphanum_fraction": 0.8357752977, "converted": true, "num_tokens": 211, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.96741025335478, "lm_q2_score": 0.9173026590205305, "lm_q1q2_score": 0.8874079977660648}} {"text": "```python\nfrom scipy import optimize\nimport cvxopt\n\nimport matplotlib.pyplot as plt\n\nimport numpy as np\n\nimport sympy\nsympy.init_printing()\n```\n\n\n```python\n# Minimize the area of a cylinder with unit volume\nr, h = sympy.symbols(\"r, h\")\n\nArea = 2 * sympy.pi * r**2 + 2 * sympy.pi * r * h\n\nVolume = sympy.pi * r**2 * h\n\nh_r = sympy.solve(Volume - 1)[0]\n\nArea_r = Area.subs(h_r)\n\nrsol = sympy.solve(Area_r.diff(r))[0]\nrsol\n```\n\n\n```python\n_.evalf()\n```\n\n\n```python\nArea_r.diff(r, 2).subs(r, rsol)\n```\n\n\n```python\nArea_r.subs(r, rsol)\n```\n\n\n```python\n_.evalf()\n```\n\n\n```python\ndef f(r):\n return 2 * np.pi * r**2 + 2 / r\n\nr_min = optimize.brent(f, brack=(0.1, 4))\nr_min\n```\n\n\n```python\nf(r_min)\n```\n\n\n```python\noptimal = optimize.minimize_scalar(f, bracket=(0.1, 4))\n```\n\n\n```python\nr = np.linspace(0.065, 2, 1000)\n\nfig, ax = plt.subplots()\n\nax.plot(r, f(r), color=\"blue\", label=\"$f(r)=2{\\pi}r^2 + 2 / r$\")\nax.plot(optimal.x, optimal.fun, \"*\", color=\"red\", markersize=10)\nax.legend()\n```\n\n### Multivariable optimization example\n\n\n```python\nx1, x2 = sympy.symbols(\"x_1, x_2\")\n\nf_sym = (x1-1)**4 + 5 * (x2-1)**2 - 2*x1*x2\n\nfprime_sym = [f_sym.diff(x_) for x_ in (x1, x2)]\nfprime_sym\n\n```\n\n\n```python\nsympy.Matrix(fprime_sym)\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}- 2 x_{2} + 4 \\left(x_{1} - 1\\right)^{3}\\\\- 2 x_{1} + 10 x_{2} - 10\\end{matrix}\\right]$\n\n\n\n\n```python\nfhess_sym = [\n [f_sym.diff(x1_, x2_) for x1_ in (x1, x2)]\n for x2_ in (x1, x2)\n]\nfhess_sym\n```\n\n\n```python\nsympy.Matrix(fhess_sym)\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}12 \\left(x_{1} - 1\\right)^{2} & -2\\\\-2 & 10\\end{matrix}\\right]$\n\n\n\n\n```python\nf_lmbda = sympy.lambdify((x1, x2), f_sym, 'numpy')\nfprime_lmbda = sympy.lambdify((x1, x2), fprime_sym, 'numpy')\nfhess_lmbda = sympy.lambdify((x1, x2), fhess_sym, 'numpy')\n```\n\n\n```python\ndef func_XY_to_X_Y(f):\n \"\"\"\n Wrapper for f(X) -> f(X[0], X[1])\n \"\"\"\n return lambda X: np.array(f(X[0], X[1]))\n\nf = func_XY_to_X_Y(f_lmbda)\nfprime = func_XY_to_X_Y(fprime_lmbda)\nfhess = func_XY_to_X_Y(fhess_lmbda)\n```\n\n\n```python\nx_opt = optimize.fmin_ncg(f, (0, 0), fprime=fprime, fhess=fhess)\n```\n\n Optimization terminated successfully.\n Current function value: -3.867223\n Iterations: 8\n Function evaluations: 10\n Gradient evaluations: 10\n Hessian evaluations: 8\n\n\n\n```python\nx_opt\n```\n\n\n\n\n array([1.88292613, 1.37658523])\n\n\n\n### Contour plot example\n\n\n```python\nfig, ax = plt.subplots(figsize=(6, 4))\nx_ = y_ = np.linspace(-1, 4, 100)\n\nX, Y = np.meshgrid(x_, y_)\n\nc = ax.contour(X, Y, f_lmbda(X, Y), 50)\nax.plot(x_opt[0], x_opt[1], 'r*', markersize=15)\n\nax.set_xlabel(r\"$x_1$\", fontsize=18)\nax.set_ylabel(r\"$x_2$\", fontsize=18)\n\nplt.colorbar(c, ax=ax)\n```\n\n\n```python\n# Broyden-Fletcher-Goldfarb-Shanno (BFGS)\n\nx_opt = optimize.fmin_bfgs(f, (0, 0), fprime=fprime)\n```\n\n Optimization terminated successfully.\n Current function value: -3.867223\n Iterations: 9\n Function evaluations: 13\n Gradient evaluations: 13\n\n\n\n```python\nx_opt\n```\n\n\n\n\n array([1.88292645, 1.37658596])\n\n\n\n\n```python\n# conjugate gradient methods\n\nx_opt = optimize.fmin_cg(f, (0, 0), fprime=fprime)\n```\n\n Optimization terminated successfully.\n Current function value: -3.867223\n Iterations: 8\n Function evaluations: 18\n Gradient evaluations: 18\n\n\n\n```python\nx_opt\n```\n\n\n\n\n array([1.88292612, 1.37658523])\n\n\n\n\n```python\n# without providing a function for the gradient as well\n\nx_opt = optimize.fmin_bfgs(f, (0, 0))\n```\n\n Optimization terminated successfully.\n Current function value: -3.867223\n Iterations: 9\n Function evaluations: 39\n Gradient evaluations: 13\n\n\n\n```python\nx_opt\n```\n\n\n\n\n array([1.88292644, 1.37658595])\n\n\n\n\n```python\ndef f(X):\n x, y = X\n return (4 * np.sin(np.pi * x) + 6 * np.sin(np.pi * y)) + (x - 1)**2 + (y - 1)**2\n```\n\n\n```python\nx_start = optimize.brute(f, (slice(-3, 5, 0.5), slice(-3, 5, 0.5)), finish=None)\nx_start\n```\n\n\n\n\n array([1.5, 1.5])\n\n\n\n\n```python\nf(x_start)\n```\n\n\n```python\nx_opt = optimize.fmin_bfgs(f, x_start)\n```\n\n Optimization terminated successfully.\n Current function value: -9.520229\n Iterations: 4\n Function evaluations: 21\n Gradient evaluations: 7\n\n\n\n```python\nx_opt\n```\n\n\n\n\n array([1.47586906, 1.48365787])\n\n\n\n\n```python\nf(x_opt)\n```\n\n\n```python\ndef func_X_Y_to_XY(f, X, Y):\n \"\"\"\n Wrapper for f(X, Y) -> f([X, Y])\n \"\"\"\n s = np.shape(X)\n return f(np.vstack([X.ravel(), Y.ravel()])).reshape(*s)\n\nfig, ax = plt.subplots(figsize=(6, 4))\n \nx_ = y_ = np.linspace(-3, 5, 100)\nX, Y = np.meshgrid(x_, y_)\n\nc = ax.contour(X, Y, func_X_Y_to_XY(f, X, Y), 25)\n\nax.plot(x_opt[0], x_opt[1], 'r*', markersize=15)\n\nax.set_xlabel(r\"$x_1$\", fontsize=18)\nax.set_ylabel(r\"$x_2$\", fontsize=18)\n\nplt.colorbar(c, ax=ax)\n```\n\n\n```python\noptimize.minimize(f, x_start, method= 'BFGS')\n```\n\n\n\n\n fun: -9.520229273055016\n hess_inv: array([[2.41596001e-02, 4.61008275e-06],\n [4.61008275e-06, 1.63490348e-02]])\n jac: array([-7.15255737e-07, -7.15255737e-07])\n message: 'Optimization terminated successfully.'\n nfev: 21\n nit: 4\n njev: 7\n status: 0\n success: True\n x: array([1.47586906, 1.48365787])\n\n\n", "meta": {"hexsha": "cda1d4e24a2ef6204416eccde0c594c60ff10e22", "size": 806587, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "NumericalPython/5.Optimization.ipynb", "max_stars_repo_name": "nickovchinnikov/Computational-Science-and-Engineering", "max_stars_repo_head_hexsha": "45620e432c97fce68a24e2ade9210d30b341d2e4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2021-01-14T08:00:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-31T14:00:11.000Z", "max_issues_repo_path": "NumericalPython/5.Optimization.ipynb", "max_issues_repo_name": "nickovchinnikov/Computational-Science-and-Engineering", "max_issues_repo_head_hexsha": "45620e432c97fce68a24e2ade9210d30b341d2e4", "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": "NumericalPython/5.Optimization.ipynb", "max_forks_repo_name": "nickovchinnikov/Computational-Science-and-Engineering", "max_forks_repo_head_hexsha": "45620e432c97fce68a24e2ade9210d30b341d2e4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-25T15:21:40.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-25T15:21:40.000Z", "avg_line_length": 1005.7194513716, "max_line_length": 221474, "alphanum_fraction": 0.8364293002, "converted": true, "num_tokens": 1868, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474233166329, "lm_q2_score": 0.9294404018582427, "lm_q1q2_score": 0.8872878847603473}} {"text": "# Matrix\n\n## Create a matrix $$\\begin{bmatrix} 1 & 2 \\\\ -2 & 3 \\\\ 3 & 4 \\end{bmatrix}$$\n\n\n```python\n# Create a matrix\nfrom sympy import *\n\ninit_printing(use_unicode=True)\n\nMatrix([[1, 2], [-2, 3], [3, 4]])\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}1 & 2\\\\-2 & 3\\\\3 & 4\\end{matrix}\\right]$\n\n\n\n## Create some matrix\n$$M = \\begin{bmatrix} 1 & 2 \\\\ -2 & 1 \\end{bmatrix}$$\n$$N = \\begin{bmatrix} -1 \\\\ 1 \\end{bmatrix}$$\n\n\n```python\n# Manipulate the matrix\nM = Matrix([[1, 2], [-2, 1]])\nN = Matrix([-1, 1])\nN\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}-1\\\\1\\end{matrix}\\right]$\n\n\n\n## Manipulate the matrix\n$$M \\times N$$\n\n\n```python\nM*N\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}1\\\\3\\end{matrix}\\right]$\n\n\n\n\n```python\n# Basic Operations\n# Get the shape of the matrix M\nshape(M)\n```\n\n\n```python\n# Accessing rows\nM.row(0)\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}1 & 2\\end{matrix}\\right]$\n\n\n\n\n```python\n# Accessing columns\nM.col(-1)\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}2\\\\1\\end{matrix}\\right]$\n\n\n\n## Addition of M and N $$\\begin{bmatrix} 1 & 2 \\\\ -2 & 1 \\end{bmatrix} + \\begin{bmatrix} -1 & 1 \\\\ 1 & 2 \\end{bmatrix} = \\begin{bmatrix} 0 & 3 \\\\ -1 & 3 \\end{bmatrix}$$\n\n\n```python\n# Addition of matrices\nM = Matrix([[1, 2], [-2, 1]])\nN = Matrix([[-1, 1], [1, 2]])\nM + N\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}0 & 3\\\\-1 & 3\\end{matrix}\\right]$\n\n\n\n## Multiplication of M and N $$\\begin{bmatrix} 1 & 2 \\\\ -2 & 1 \\end{bmatrix} \\times \\begin{bmatrix} -1 & 1 \\\\ 1 & 2 \\end{bmatrix} = \\begin{bmatrix} 1 & 5 \\\\ 3 & 0 \\end{bmatrix}$$\n\n\n```python\n# Multiplication of matrices\nM*N\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}1 & 5\\\\3 & 0\\end{matrix}\\right]$\n\n\n\n## Power of matrix M $$\\begin{bmatrix} 1 & 2 \\\\ -2 & 1 \\end{bmatrix}^2 = \\begin{bmatrix} -3 & 4 \\\\ -4 & -3 \\end{bmatrix}$$\n\n\n```python\n# Power of a matrix\nM**2\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}-3 & 4\\\\-4 & -3\\end{matrix}\\right]$\n\n\n\n## Inverse of matrix M $$\\begin{bmatrix} 1 & 2 \\\\ -2 & 1 \\end{bmatrix}^{-1} = \\begin{bmatrix} \\frac{1}{5} & -\\frac{2}{5} \\\\ \\frac{2}{5} & \\frac{1}{5} \\end{bmatrix}$$\n\n\n```python\n# Inverse of a matrix\nM**-1\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}\\frac{1}{5} & - \\frac{2}{5}\\\\\\frac{2}{5} & \\frac{1}{5}\\end{matrix}\\right]$\n\n\n\n## Transpose of matrix M $$MT = \\begin{bmatrix} 1 & -2 \\\\ 2 & 1 \\end{bmatrix}$$\n\n\n```python\n# Transpose of a matrix\nM.T\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}1 & -2\\\\2 & 1\\end{matrix}\\right]$\n\n\n\n## Create a matrix identity $$\\begin{bmatrix} 1 & 0 & 0 \\\\ 0 & 1 & 1 \\\\ 0 & 0 & 1 \\end{bmatrix}$$\n\n\n```python\n# Matrix Constructor\n# Identity Matrix\neye(3)\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}1 & 0 & 0\\\\0 & 1 & 0\\\\0 & 0 & 1\\end{matrix}\\right]$\n\n\n\n## Create all zeros matrix $$\\begin{bmatrix} 0 & 0 \\\\ 0 & 0 \\end{bmatrix}$$\n\n\n```python\n# All zeros matrix\nzeros(2, 2)\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}0 & 0\\\\0 & 0\\end{matrix}\\right]$\n\n\n\n## Create all ones matrix $$\\begin{bmatrix} 1 & 1 \\\\ 1 & 1 \\end{bmatrix}$$\n\n\n```python\n# All ones matrix\nones(2, 2)\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}1 & 1\\\\1 & 1\\end{matrix}\\right]$\n\n\n\n## Create a diagonal matrix $$\\begin{bmatrix} 1 & 0 & 0 \\\\ 0 & 2 & 0 \\\\ 0 & 0 & 3 \\end{bmatrix}$$\n\n\n```python\n# Diagonal Matrix\ndiag(1, 2, 3)\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}1 & 0 & 0\\\\0 & 2 & 0\\\\0 & 0 & 3\\end{matrix}\\right]$\n\n\n\n## Determinant of matrix M $$a \\times d - b \\times c$$ $$=1 \\times 1 - 2 \\times (-2) = 5$$\n\n\n```python\n# Determinant of a matrix\nM.det()\n```\n", "meta": {"hexsha": "2332c1142f4905f60f732795fa91e508362be3bc", "size": 14662, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "matrices.ipynb", "max_stars_repo_name": "ricoen/learn-math", "max_stars_repo_head_hexsha": "fc84bc4d0dc353f8ccb3c52e36155069e9ca5af4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-11-30T10:05:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-30T13:39:08.000Z", "max_issues_repo_path": "matrices.ipynb", "max_issues_repo_name": "ricoen/learn-math", "max_issues_repo_head_hexsha": "fc84bc4d0dc353f8ccb3c52e36155069e9ca5af4", "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": "matrices.ipynb", "max_forks_repo_name": "ricoen/learn-math", "max_forks_repo_head_hexsha": "fc84bc4d0dc353f8ccb3c52e36155069e9ca5af4", "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": 21.6253687316, "max_line_length": 1170, "alphanum_fraction": 0.4849952258, "converted": true, "num_tokens": 1371, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9683812299938006, "lm_q2_score": 0.9161096112990283, "lm_q1q2_score": 0.8871433521988956}} {"text": "# Exercises 2 - Answers\n\n## Exercise 1\n\nThe profit that you make for each kwH is $2-0.01x^2-(1-0.01x)$. Thus, the amount of profit that you make is\n$$\n(1+0.01x-0.01x^2)x=x+0.01x^2-0.01x^3.\n$$\nThus, the optimization problem is\n$$\n\\begin{align}\n\\max \\qquad & x+0.01x^2-0.01x^3\\\\\n\\text{s.t.} \\qquad & 0\\leq x \\leq 50.\n\\end{align}\n$$\n\n## Exercise 2\n\n\n```python\ndef bisection_line_search(a,b,f,L,epsilon):\n x = a\n y = b\n while y-x>2*L:\n if f((x+y)/2+epsilon)>f((x+y)/2-epsilon):\n y=(x+y)/2+epsilon\n else:\n x = (x+y)/2-epsilon\n return (x+y)/2\n```\n\n\n```python\ndef f_ex2(x):\n return (1-x)**2+x\n```\n\n\n```python\nprint f_ex2(0.5), f_ex2(0), f_ex2(1)\n```\n\n 0.75 1 1\n\n\n\n```python\nbisection_line_search(0,2,f_ex2,0.0001,1e-6)\n```\n\n\n\n\n 0.49993946490478514\n\n\n\n## Exercise 3\n\n\n```python\nimport math\ndef golden_section_line_search(a,b,f,L):\n x = a\n y = b\n f_left = f(y-(math.sqrt(5.0)-1)/2.0*(y-x)) #funtion eval \n f_right = f(x+(math.sqrt(5.0)-1)/2.0*(y-x)) #function eval\n while y-x>2*L:\n if f_left > f_right:\n x = y-(math.sqrt(5.0)-1)/2.0*(y-x)\n f_left = f_right #no function eval\n f_right = f(x+(math.sqrt(5.0)-1)/2.0*(y-x)) #function eval\n else:\n y = x+(math.sqrt(5.0)-1)/2.0*(y-x)\n f_right = f_left #no function eval\n f_left = f(y-(math.sqrt(5.0)-1)/2.0*(y-x)) #function eval\n return (x+y)/2\n```\n\n\n```python\ngolden_section_line_search(0,2,f_ex2,0.0001)\n```\n\n\n\n\n 0.4999795718254958\n\n\n\n## Exercise 4\n\nNow, $f(x) = (1-x)^2+x$. Thus, \n$$\nf'(x)=2(1-x)(-1)+1= -1 +2x.\n$$\n\n\nIf $f'(x) = 0$, then $2x=1$ and $x=\\frac 12$.\nThis is a local minimum since,\n$$\nf''(x) = 2,\n$$\nwhich is greater than $0$.\n\nThis means that the algorithms work!\n", "meta": {"hexsha": "993c34c1396cc96d79ae87fc52a378260dff98c6", "size": 4777, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Exercise 2 answers.ipynb", "max_stars_repo_name": "maeehart/TIES483", "max_stars_repo_head_hexsha": "cce5c779aeb0ade5f959a2ed5cca982be5cf2316", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2019-04-26T12:46:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-23T03:38:59.000Z", "max_issues_repo_path": "Exercise 2 answers.ipynb", "max_issues_repo_name": "maeehart/TIES483", "max_issues_repo_head_hexsha": "cce5c779aeb0ade5f959a2ed5cca982be5cf2316", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Exercise 2 answers.ipynb", "max_forks_repo_name": "maeehart/TIES483", "max_forks_repo_head_hexsha": "cce5c779aeb0ade5f959a2ed5cca982be5cf2316", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2016-01-08T16:28:11.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-10T05:18:10.000Z", "avg_line_length": 19.658436214, "max_line_length": 116, "alphanum_fraction": 0.4502826041, "converted": true, "num_tokens": 714, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308110294983, "lm_q2_score": 0.9504109801762777, "lm_q1q2_score": 0.8871428920372834}} {"text": "sergazy.nurbavliyev@gmail.com © 2021\n\n## Detecting Unfair Coin\n\nQuestion: Assume we have a fair coin (one side heads and the other side tails) also we have an unfair coin (both sides heads). You pick randomly one coin, and flip it 5 times. You get 5 heads in a row. What is the probability that you are indeed flipping the unfair coin?\n\n\n### Intuition\n\nAssume you flip a fair coin 5 times, what is the probability of getting 5 heads in a row. That is $\\frac{1}{2^5}$. \nIf this is confusing, think this way, take 5 fair coin and flip once, and now the same question what is the probability of getting 5 heads? The same answer that is $\\frac{1}{2^5}$. Which is around 0.03125. If you dont have a calculator, then rougly you can guess $3/96\\approx 3/100=0.03$. That tells us probability of flipping an unfair coin is around 0.97. \n\nIf you are flipping an unfair coin well then probability of getting 5 head is 1. Now correct answer should be close to these numbers.\n\n\n```python\n1/32\n```\n\n\n\n\n 0.03125\n\n\n\n\n```python\n\n```\n\n### Theoritical result\n\nAs you can guess we will use Bayes theorem here. \nWe will denote with $U$ letter if we are flipping the unfair coin and $F$ letter if we are flipping a fair\nSince we are picking randomly one coin, $\\mathbb{P}(U)=\\mathbb{P}(F)=1/2$.\n\nLet 5H represent the case where we get 5 heads in a row. Then we want to find the probability that we are flipping the unfair coin, given that we saw 5 heads in a row.\ni.e. $\\mathbb{P}(U|5H)$. \nIf we are given an unfair coin and then the probability of getting 5 heads in a row would be 1. i.e. $\\mathbb{P}(5H|U)=1$. With the same logic if we have fair coin and then the probability of getting 5 heads in a row would be 1/32. i.e. $\\mathbb{P}(5H|F)=\\frac{1}{2^5}.$ We actually collected all the information we want. Now using Bayes rule we get\n\\begin{equation}\n\\mathbb{P}(U|5H)=\\dfrac{\\mathbb{P}(5H|U)\\mathbb{P}(U)}{\\mathbb{P}(5H|U)\\mathbb{P}(U)+\\mathbb{P}(5H|F)\\mathbb{P}(F)}=\\frac{\\frac{1}{2}*1}{\\frac{1}{2}*1+\\frac{1}{2}*\\frac{1}{2^5}}=\\frac{32}{33}= 0.9696969696969697\n\\end{equation}\n\n\n```python\n32/33\n```\n\n\n\n\n 0.9696969696969697\n\n\n\n## Python code for our intuition\n\n\n```python\nimport scipy.stats as stats\ndef fair(n_trials):\n return stats.bernoulli.rvs(0.5, size=n_trials) # this returns an array of 0s and 1s\ndef unfair(n_trials):\n return stats.bernoulli.rvs(1, size=n_trials) ## this returns an array of 1s\n```\n\n\n```python\nimport numpy as np\ncount_f=0\ncount_unf=0\nfor j in range(100):\n data = fair(5)\n if np.sum(data)==5:\n count_f+=1\nfor j in range(100):\n data = unfair(5)\n if np.sum(data)==5:\n count_unf+=1\n \n```\n\n\n```python\ncount_f/100,count_unf/10000\n```\n\n\n\n\n (0.06, 0.01)\n\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "3f5d267f6f776d9bf694882dab7722bd5ba5f7b3", "size": 6505, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Unfair Coin March 4 2021.ipynb", "max_stars_repo_name": "sernur/probability_stats_interveiw_questions", "max_stars_repo_head_hexsha": "3144dae00fa83c82ff4e1f7668828349270a1937", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2021-03-04T06:48:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-19T10:04:24.000Z", "max_issues_repo_path": "Unfair Coin March 4 2021.ipynb", "max_issues_repo_name": "sernur/probability_stats_interveiw_questions", "max_issues_repo_head_hexsha": "3144dae00fa83c82ff4e1f7668828349270a1937", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-03-05T22:00:43.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-05T22:00:43.000Z", "max_forks_repo_path": "Unfair Coin March 4 2021.ipynb", "max_forks_repo_name": "sernur/probability_stats_interveiw_questions", "max_forks_repo_head_hexsha": "3144dae00fa83c82ff4e1f7668828349270a1937", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-03-04T05:02:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-16T01:13:40.000Z", "avg_line_length": 25.9163346614, "max_line_length": 369, "alphanum_fraction": 0.5581860108, "converted": true, "num_tokens": 873, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9609517028006208, "lm_q2_score": 0.9230391722430736, "lm_q1q2_score": 0.8869960643186572}} {"text": "# Linear Algebra and Python Basics\n\nIn this chapter, I will be discussing some linear algebra basics that will provide sufficient linear algebra background for effective programming in Python for our purposes. We will be doing very basic linear algebra that by no means covers the full breadth of this topic. Why linear algebra? Linear algebra allows us to express relatively complex linear expressions in a very compact way.\n\nBeing comfortable with the rules for scalar and matrix addition, subtraction, multiplication, and division (known as inversion) is important for our class.\n\nBefore we can implement any of these ideas in code, we need to talk a bit about python and how data is stored.\n\n## Python Primer\n\nThere are numerous ways to run python code. I will show you two and both are easily accessible after installing Anaconda:\n\n1. The Spyder integrated development environment. The major advantages of Spyder is that it provides a graphical way for viewing matrices, vectors, and other objects you want to check as you work on a problem. It also has the most intuitive way of debugging code.\n\n Spyder looks like this:\n \n Code can be run by clicking the green arrow (runs the entire file) or by blocking a subset and running it.\n In Windows or Mac, you can launch the Spyder by looking for the icon in the newly installed Program Folder Anaconda. \n \n2. The Ipython Notebook (now called Jupyter). The major advantages of this approach is that you use your web browser for all of your python work and you can mix code, videos, notes, graphics from the web, and mathematical notation to tell the whole story of your python project. In fact, I am using the ipython notebook for writing these notes. \n The Ipython Notebook looks like this:\n \n In Windows or Mac, you can launch the Ipython Notebook by looking in the newly installed Program Folder Anaconda.\n\nIn my work flow, I usually only use the Ipython Notebook, but for some coding problems where I need access to the easy debugging capabilities of Spyder, I use it. We will be using the Ipython Notebook interface (web browser) mostly in this class.\n\n### Loading libraries\n\nThe python universe has a huge number of libraries that extend the capabilities of python. Nearly all of these are open source, unlike packages like stata or matlab where some key libraries are proprietary (and can cost lots of money). In lots of my code, you will see this at the top:\n\n\n```python\n%matplotlib inline\nimport sympy as sympy\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sbn\nfrom scipy import *\n```\n\nThis code sets up Ipython Notebook environments (lines beginning with `%`), and loads several libraries and functions. The core scientific stack in python consists of a number of free libraries. The ones I have loaded above include:\n\n1. sympy: provides for symbolic computation (solving algebra problems)\n2. numpy: provides for linear algebra computations\n3. matplotlib.pyplot: provides for the ability to graph functions and draw figures\n4. scipy: scientific python provides a plethora of capabilities\n5. seaborn: makes matplotlib figures even pretties (another library like this is called bokeh). This is entirely optional and is purely for eye candy.\n\n### Creating arrays, scalars, and matrices in Python\n\nScalars can be created easily like this:\n\n\n```python\nx = .5\nprint x\n```\n\n 0.5\n\n\n#### Vectors and Lists\n\nThe numpy library (we will reference it by np) is the workhorse library for linear algebra in python. To creat a vector simply surround a python list ($[1,2,3]$) with the np.array function:\n\n\n```python\nx_vector = np.array([1,2,3])\nprint x_vector\n```\n\n [1 2 3]\n\n\nWe could have done this by defining a python list and converting it to an array:\n\n\n```python\nc_list = [1,2]\nprint \"The list:\",c_list\nprint \"Has length:\", len(c_list)\n\nc_vector = np.array(c_list)\nprint \"The vector:\", c_vector\nprint \"Has shape:\",c_vector.shape\n```\n\n The list: [1, 2]\n Has length: 2\n The vector: [1 2]\n Has shape: (2,)\n\n\n\n```python\nz = [5,6]\nprint \"This is a list, not an array:\",z\nprint type(z)\n```\n\n This is a list, not an array: [5, 6]\n \n\n\n\n```python\nzarray = np.array(z)\nprint \"This is an array, not a list\",zarray\nprint type(zarray)\n```\n\n This is an array, not a list [5 6]\n \n\n\n#### Matrices\n\n\n```python\nb = zip(z,c_vector)\nprint b\nprint \"Note that the length of our zipped list is 2 not (2 by 2):\",len(b)\n```\n\n [(5, 1), (6, 2)]\n Note that the length of our zipped list is 2 not (2 by 2): 2\n\n\n\n```python\nprint \"But we can convert the list to a matrix like this:\"\nA = np.array(b)\nprint A\nprint type(A)\nprint \"A has shape:\",A.shape\n```\n\n But we can convert the list to a matrix like this:\n [[5 1]\n [6 2]]\n \n A has shape: (2, 2)\n\n\n## Matrix Addition and Subtraction\n\n###Adding or subtracting a scalar value to a matrix\n\nTo learn the basics, consider a small matrix of dimension $2 \\times 2$, where $2 \\times 2$ denotes the number of rows $\\times$ the number of columns. Let $A$=$\\bigl( \\begin{smallmatrix} a_{11} & a_{12} \\\\ a_{21} & a_{22} \\end{smallmatrix} \\bigr)$. Consider adding a scalar value (e.g. 3) to the A.\n$$\n\\begin{equation}\n\tA+3=\\begin{bmatrix}\n\t a_{11} & a_{12} \\\\\n\t a_{21} & a_{22} \t\n\t\\end{bmatrix}+3\n\t=\\begin{bmatrix}\n\t a_{11}+3 & a_{12}+3 \\\\\n\t a_{21}+3 & a_{22}+3 \t\n\t\\end{bmatrix}\n\\end{equation}\n$$\nThe same basic principle holds true for A-3:\n$$\n\\begin{equation}\n\tA-3=\\begin{bmatrix}\n\t a_{11} & a_{12} \\\\\n\t a_{21} & a_{22} \t\n\t\\end{bmatrix}-3\n\t=\\begin{bmatrix}\n\t a_{11}-3 & a_{12}-3 \\\\\n\t a_{21}-3 & a_{22}-3 \t\n\t\\end{bmatrix}\n\\end{equation}\n$$\nNotice that we add (or subtract) the scalar value to each element in the matrix A. A can be of any dimension.\n\nThis is trivial to implement, now that we have defined our matrix A:\n\n\n```python\nresult = A + 3\n#or\nresult = 3 + A\nprint result\n```\n\n [[8 4]\n [9 5]]\n\n\n###Adding or subtracting two matrices\nConsider two small $2 \\times 2$ matrices, where $2 \\times 2$ denotes the \\# of rows $\\times$ the \\# of columns. Let $A$=$\\bigl( \\begin{smallmatrix} a_{11} & a_{12} \\\\ a_{21} & a_{22} \\end{smallmatrix} \\bigr)$ and $B$=$\\bigl( \\begin{smallmatrix} b_{11} & b_{12} \\\\ b_{21} & b_{22} \\end{smallmatrix} \\bigr)$. To find the result of $A-B$, simply subtract each element of A with the corresponding element of B:\n\n$$\n\\begin{equation}\n\tA -B =\n\t\\begin{bmatrix}\n\t a_{11} & a_{12} \\\\\n\t a_{21} & a_{22} \t\n\t\\end{bmatrix} -\n\t\\begin{bmatrix} b_{11} & b_{12} \\\\\n\t b_{21} & b_{22}\n\t\\end{bmatrix}\n\t=\n\t\\begin{bmatrix}\n\t a_{11}-b_{11} & a_{12}-b_{12} \\\\\n\t a_{21}-b_{21} & a_{22}-b_{22} \t\n\t\\end{bmatrix}\n\\end{equation}\n$$\n\nAddition works exactly the same way:\n\n$$\n\\begin{equation}\n\tA + B =\n\t\\begin{bmatrix}\n\t a_{11} & a_{12} \\\\\n\t a_{21} & a_{22} \t\n\t\\end{bmatrix} +\n\t\\begin{bmatrix} b_{11} & b_{12} \\\\\n\t b_{21} & b_{22}\n\t\\end{bmatrix}\n\t=\n\t\\begin{bmatrix}\n\t a_{11}+b_{11} & a_{12}+b_{12} \\\\\n\t a_{21}+b_{21} & a_{22}+b_{22} \t\n\t\\end{bmatrix}\n\\end{equation}\n$$\n\nAn important point to know about matrix addition and subtraction is that it is only defined when $A$ and $B$ are of the same size. Here, both are $2 \\times 2$. Since operations are performed element by element, these two matrices must be conformable- and for addition and subtraction that means they must have the same numbers of rows and columns. I like to be explicit about the dimensions of matrices for checking conformability as I write the equations, so write\n\n$$\nA_{2 \\times 2} + B_{2 \\times 2}= \\begin{bmatrix}\n a_{11}+b_{11} & a_{12}+b_{12} \\\\\n a_{21}+b_{21} & a_{22}+b_{22} \t\n\\end{bmatrix}_{2 \\times 2}\n$$\n\nNotice that the result of a matrix addition or subtraction operation is always of the same dimension as the two operands.\n\nLet's define another matrix, B, that is also $2 \\times 2$ and add it to A:\n\n\n```python\nB = np.random.randn(2,2)\nprint B\n```\n\n [[ 0.65905256 1.8847017 ]\n [ 0.61068714 1.96506417]]\n\n\n\n```python\nresult = A + B\nresult\n```\n\n\n\n\n array([[ 5.65905256, 2.8847017 ],\n [ 6.61068714, 3.96506417]])\n\n\n\n##Matrix Multiplication\n\n###Multiplying a scalar value times a matrix\n\nAs before, let $A$=$\\bigl( \\begin{smallmatrix} a_{11} & a_{12} \\\\ a_{21} & a_{22} \\end{smallmatrix} \\bigr)$. Suppose we want to multiply A times a scalar value (e.g. $3 \\times A$)\n\n$$\n\\begin{equation}\n\t3 \\times A = 3 \\times \\begin{bmatrix}\n\t a_{11} & a_{12} \\\\\n\t a_{21} & a_{22} \t\n\t\\end{bmatrix}\n\t=\n\t\\begin{bmatrix}\n\t 3a_{11} & 3a_{12} \\\\\n\t 3a_{21} & 3a_{22} \t\n\t\\end{bmatrix}\n\\end{equation}\n$$\n\nis of dimension (2,2). Scalar multiplication is commutative, so that $3 \\times A$=$A \\times 3$. Notice that the product is defined for a matrix A of any dimension.\n\nSimilar to scalar addition and subtration, the code is simple:\n\n\n```python\nA * 3\n```\n\n\n\n\n array([[15, 3],\n [18, 6]])\n\n\n\n###Multiplying two matricies\n\nNow, consider the $2 \\times 1$ vector $C=\\bigl( \\begin{smallmatrix} c_{11} \\\\\n c_{21}\n\\end{smallmatrix} \\bigr)$ \n\nConsider multiplying matrix $A_{2 \\times 2}$ and the vector $C_{2 \\times 1}$. Unlike the addition and subtraction case, this product is defined. Here, conformability depends not on the row **and** column dimensions, but rather on the column dimensions of the first operand and the row dimensions of the second operand. We can write this operation as follows\n\n$$\n\\begin{equation}\n\tA_{2 \\times 2} \\times C_{2 \\times 1} = \n\t\\begin{bmatrix}\n\t a_{11} & a_{12} \\\\\n\t a_{21} & a_{22} \t\n\t\\end{bmatrix}_{2 \\times 2}\n \\times\n \\begin{bmatrix}\n\tc_{11} \\\\\n\tc_{21}\n\t\\end{bmatrix}_{2 \\times 1}\n\t=\n\t\\begin{bmatrix}\n\t a_{11}c_{11} + a_{12}c_{21} \\\\\n\t a_{21}c_{11} + a_{22}c_{21} \t\n\t\\end{bmatrix}_{2 \\times 1}\n\\end{equation}\n$$\n\nAlternatively, consider a matrix C of dimension $2 \\times 3$ and a matrix A of dimension $3 \\times 2$\n\n$$\n\\begin{equation}\n\tA_{3 \\times 2}=\\begin{bmatrix}\n\t a_{11} & a_{12} \\\\\n\t a_{21} & a_{22} \\\\\n\t a_{31} & a_{32} \t\n\t\\end{bmatrix}_{3 \\times 2}\n\t,\n\tC_{2 \\times 3} = \n\t\\begin{bmatrix}\n\t\t c_{11} & c_{12} & c_{13} \\\\\n\t\t c_{21} & c_{22} & c_{23} \\\\\n\t\\end{bmatrix}_{2 \\times 3}\n\t\\end{equation}\n$$\n\nHere, A $\\times$ C is\n\n$$\n\\begin{align}\n\tA_{3 \\times 2} \\times C_{2 \\times 3}=&\n\t\\begin{bmatrix}\n\t a_{11} & a_{12} \\\\\n\t a_{21} & a_{22} \\\\\n\t a_{31} & a_{32} \t\n\t\\end{bmatrix}_{3 \\times 2}\n\t\\times\n\t\\begin{bmatrix}\n\t c_{11} & c_{12} & c_{13} \\\\\n\t c_{21} & c_{22} & c_{23} \n\t\\end{bmatrix}_{2 \\times 3} \\\\\n\t=&\n\t\\begin{bmatrix}\n\t a_{11} c_{11}+a_{12} c_{21} & a_{11} c_{12}+a_{12} c_{22} & a_{11} c_{13}+a_{12} c_{23} \\\\\n\t a_{21} c_{11}+a_{22} c_{21} & a_{21} c_{12}+a_{22} c_{22} & a_{21} c_{13}+a_{22} c_{23} \\\\\n\t a_{31} c_{11}+a_{32} c_{21} & a_{31} c_{12}+a_{32} c_{22} & a_{31} c_{13}+a_{32} c_{23}\n\t\\end{bmatrix}_{3 \\times 3}\t\n\\end{align}\n$$\n\nSo in general, $X_{r_x \\times c_x} \\times Y_{r_y \\times c_y}$ we have two important things to remember: \n\n* For conformability in matrix multiplication, $c_x=r_y$, or the columns in the first operand must be equal to the rows of the second operand.\n* The result will be of dimension $r_x \\times c_y$, or of dimensions equal to the rows of the first operand and columns equal to columns of the second operand.\n\nGiven these facts, you should convince yourself that matrix multiplication is not generally commutative, that the relationship $X \\times Y = Y \\times X$ does **not** hold in all cases.\nFor this reason, we will always be very explicit about whether we are pre multiplying ($X \\times Y$) or post multiplying ($Y \\times X$) the vectors/matrices $X$ and $Y$.\n\nFor more information on this topic, see this\nhttp://en.wikipedia.org/wiki/Matrix_multiplication.\n\n\n```python\n# Let's redefine A and C to demonstrate matrix multiplication:\nA = np.arange(6).reshape((3,2))\nC = np.random.randn(2,2)\n\nprint A.shape\nprint C.shape\n```\n\n (3, 2)\n (2, 2)\n\n\nWe will use the numpy dot operator to perform the these multiplications. You can use it two ways to yield the same result:\n\n\n```python\nprint A.dot(C)\nprint np.dot(A,C)\n```\n\n [[-1.05731701 -0.93611763]\n [-3.11819033 -2.65506704]\n [-5.17906365 -4.37401644]]\n [[-1.05731701 -0.93611763]\n [-3.11819033 -2.65506704]\n [-5.17906365 -4.37401644]]\n\n\nSuppose instead of pre-multiplying C by A, we post-multiply. The product doesn't exist because we don't have conformability as described above:\n\n\n```python\nC.dot(A)\n```\n\n##Matrix Division\nThe term matrix division is actually a misnomer. To divide in a matrix algebra world we first need to invert the matrix. It is useful to consider the analog case in a scalar work. Suppose we want to divide the $f$ by $g$. We could do this in two different ways:\n$$\n\\begin{equation}\n\t\\frac{f}{g}=f \\times g^{-1}.\n\\end{equation}\n$$\nIn a scalar seeting, these are equivalent ways of solving the division problem. The second one requires two steps: first we invert g and then we multiply f times g. In a matrix world, we need to think about this second approach. First we have to invert the matrix g and then we will need to pre or post multiply depending on the exact situation we encounter (this is intended to be vague for now).\n\n###Inverting a Matrix\n\nAs before, consider the square $2 \\times 2$ matrix $A$=$\\bigl( \\begin{smallmatrix} a_{11} & a_{12} \\\\ a_{21} & a_{22}\\end{smallmatrix} \\bigr)$. Let the inverse of matrix A (denoted as $A^{-1}$) be \n\n$$\n\\begin{equation}\n\tA^{-1}=\\begin{bmatrix}\n a_{11} & a_{12} \\\\\n\t\t a_{21} & a_{22} \n \\end{bmatrix}^{-1}=\\frac{1}{a_{11}a_{22}-a_{12}a_{21}}\t\\begin{bmatrix}\n\t\t a_{22} & -a_{12} \\\\\n\t\t\t\t -a_{21} & a_{11} \n\t\t \\end{bmatrix}\n\\end{equation}\n$$\n\nThe inverted matrix $A^{-1}$ has a useful property:\n$$\n\\begin{equation}\n\tA \\times A^{-1}=A^{-1} \\times A=I\n\\end{equation}\n$$\nwhere I, the identity matrix (the matrix equivalent of the scalar value 1), is\n$$\n\\begin{equation}\n\tI_{2 \\times 2}=\\begin{bmatrix}\n 1 & 0 \\\\\n\t\t 0 & 1 \n \\end{bmatrix}\n\\end{equation}\n$$\nfurthermore, $A \\times I = A$ and $I \\times A = A$.\n\nAn important feature about matrix inversion is that it is undefined if (in the $2 \\times 2$ case), $a_{11}a_{22}-a_{12}a_{21}=0$. If this relationship is equal to zero the inverse of A does not exist. If this term is very close to zero, an inverse may exist but $A^{-1}$ may be poorly conditioned meaning it is prone to rounding error and is likely not well identified computationally. The term $a_{11}a_{22}-a_{12}a_{21}$ is the determinant of matrix A, and for square matrices of size greater than $2 \\times 2$, if equal to zero indicates that you have a problem with your data matrix (columns are linearly dependent on other columns). The inverse of matrix A exists if A is square and is of full rank (ie. the columns of A are not linear combinations of other columns of A).\n\nFor more information on this topic, see this\nhttp://en.wikipedia.org/wiki/Matrix_inversion, for example, on inverting matrices.\n\n\n```python\n# note, we need a square matrix (# rows = # cols), use C:\nC_inverse = np.linalg.inv(C)\nprint C_inverse\n```\n\n [[-16.7544699 -1.37174182]\n [ 18.92367512 0.48109974]]\n\n\nCheck that $C\\times C^{-1} = I$:\n\n\n```python\nprint C.dot(C_inverse)\nprint \"Is identical to:\"\nprint C_inverse.dot(C)\n```\n\n [[ 1. 0.]\n [ 0. 1.]]\n Is identical to:\n [[ 1. 0.]\n [ 0. 1.]]\n\n\n##Transposing a Matrix\n\nAt times it is useful to pivot a matrix for conformability- that is in order to matrix divide or multiply, we need to switch the rows and column dimensions of matrices. Consider the matrix\n$$\n\\begin{equation}\n\tA_{3 \\times 2}=\\begin{bmatrix}\n\t a_{11} & a_{12} \\\\\n\t a_{21} & a_{22} \\\\\n\t a_{31} & a_{32} \t\n\t\\end{bmatrix}_{3 \\times 2}\t\n\\end{equation}\n$$\nThe transpose of A (denoted as $A^{\\prime}$) is\n$$\n\\begin{equation}\n A^{\\prime}=\\begin{bmatrix}\n\t a_{11} & a_{21} & a_{31} \\\\\n\t a_{12} & a_{22} & a_{32} \\\\\n\t\\end{bmatrix}_{2 \\times 3}\n\\end{equation}\n$$\n\n\n```python\nA = np.arange(6).reshape((3,2))\nB = np.arange(8).reshape((2,4))\nprint \"A is\"\nprint A\n\nprint \"The Transpose of A is\"\nprint A.T\n```\n\n A is\n [[0 1]\n [2 3]\n [4 5]]\n The Transpose of A is\n [[0 2 4]\n [1 3 5]]\n\n\nOne important property of transposing a matrix is the transpose of a product of two matrices. Let matrix A be of dimension $N \\times M$ and let B of of dimension $M \\times P$. Then\n$$\n\\begin{equation}\n\t(AB)^{\\prime}=B^{\\prime}A^{\\prime}\n\\end{equation}\n$$\nFor more information, see this http://en.wikipedia.org/wiki/Matrix_transposition on matrix transposition. This is also easy to implement:\n\n\n```python\nprint B.T.dot(A.T)\nprint \"Is identical to:\"\nprint (A.dot(B)).T\n```\n\n [[ 4 12 20]\n [ 5 17 29]\n [ 6 22 38]\n [ 7 27 47]]\n Is identical to:\n [[ 4 12 20]\n [ 5 17 29]\n [ 6 22 38]\n [ 7 27 47]]\n\n\n## More python tools\n\n### Indexing\n\nPython begins indexing at 0 (not 1), therefore the first row and first column is referenced by 0,0 **not** 1,1.\n\n### Slicing \n\nAccessing elements of numpy matrices and arrays. This code grabs the first column of A:\n\n\n```python\nprint A\nA[:,0]\n```\n\n [[0 1]\n [2 3]\n [4 5]]\n\n\n\n\n\n array([0, 2, 4])\n\n\n\nor, we could grab a particular element (in this case, the second column, last row):\n\n\n```python\nA[2,1]\n```\n\n\n\n\n 5\n\n\n\n### Logical Checks to extract values from matrices/arrays:\n\n\n```python\nprint A\n```\n\n [[0 1]\n [2 3]\n [4 5]]\n\n\n\n```python\nprint A[:,1]>4\n\nA[A[:,1]>4]\n```\n\n [False False True]\n\n\n\n\n\n array([[4, 5]])\n\n\n\n### For loops\n\nCreate a $12 \\times 2$ matrix and print it out:\n\n\n```python\nA = np.arange(24).reshape((12,2))\nprint A\nprint A.shape\n```\n\n [[ 0 1]\n [ 2 3]\n [ 4 5]\n [ 6 7]\n [ 8 9]\n [10 11]\n [12 13]\n [14 15]\n [16 17]\n [18 19]\n [20 21]\n [22 23]]\n (12, 2)\n\n\nThe code below loops over the rows (12 of them) of our matrix A. For each row, it slices A and prints the row values across all columns. Notice the form of the for loop. The colon defines the statement we are looping over. For each iteration of the loop **idented** lines will be executed:\n\n\n```python\nfor rows in A:\n print rows\n```\n\n [0 1]\n [2 3]\n [4 5]\n [6 7]\n [8 9]\n [10 11]\n [12 13]\n [14 15]\n [16 17]\n [18 19]\n [20 21]\n [22 23]\n\n\n\n```python\nfor rows in A:\n print rows\n```\n\n [0 1]\n [2 3]\n [4 5]\n [6 7]\n [8 9]\n [10 11]\n [12 13]\n [14 15]\n [16 17]\n [18 19]\n [20 21]\n [22 23]\n\n\n\n```python\nfor cols in A.T:\n print cols\n```\n\n [ 0 2 4 6 8 10 12 14 16 18 20 22]\n [ 1 3 5 7 9 11 13 15 17 19 21 23]\n\n\n### If/then/else\n\nThe code below checks the value of x and categorizes it into one of three values. Like the for loop, each logical if check is ended with a colon, and any commands to be applied to that particular if check (if true) must be indented.\n\n\n```python\nx=.4\n\nif x<.5:\n print \"Heads\"\n print 100\nelif x>.5:\n print \"Tails\"\n print 0\nelse:\n print \"Tie\"\n print 50\n```\n\n Heads\n 100\n\n\n### While loops\n\nAgain, we have the same basic form for the statement (note the colons and indents). Here we use the shorthand notation `x+=1` for performing the calculation `x = x + 1`:\n\n\n```python\nx=0\nwhile x<10:\n x+=1 \n print x<10\n\nprint x\n```\n\n True\n True\n True\n True\n True\n True\n True\n True\n True\n False\n 10\n\n", "meta": {"hexsha": "acb8d70a193873cc8ff5e55203c7aaa356894d79", "size": 33853, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "other/linear-algebra-python-basics.ipynb", "max_stars_repo_name": "lnsongxf/Applied_Computational_Economics_and_Finance", "max_stars_repo_head_hexsha": "f14661bfbfa711d49539bda290d4be5a25087185", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 19, "max_stars_repo_stars_event_min_datetime": "2018-05-09T08:17:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-26T07:02:17.000Z", "max_issues_repo_path": "other/linear-algebra-python-basics.ipynb", "max_issues_repo_name": "lnsongxf/Applied_Computational_Economics_and_Finance", "max_issues_repo_head_hexsha": "f14661bfbfa711d49539bda290d4be5a25087185", "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": "other/linear-algebra-python-basics.ipynb", "max_forks_repo_name": "lnsongxf/Applied_Computational_Economics_and_Finance", "max_forks_repo_head_hexsha": "f14661bfbfa711d49539bda290d4be5a25087185", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11, "max_forks_repo_forks_event_min_datetime": "2017-12-15T13:39:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-15T15:06:02.000Z", "avg_line_length": 27.6125611746, "max_line_length": 792, "alphanum_fraction": 0.5165568783, "converted": true, "num_tokens": 6231, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896715436483, "lm_q2_score": 0.9632305318133553, "lm_q1q2_score": 0.8869327250092331}} {"text": "\n\nManipulate Taylor series using the **SymPy** package in Python, following the tutorial at [scipy-lectures.org/packages/sympy.html](https://scipy-lectures.org/packages/sympy.html). SymPy is used in [SageMath](https://www.sagemath.org/).\n\nYou can do this in Maple, which is a bit old-school, or Mathematica (which we have a license for at CU). Wolfram Alpha is another choice (by the company that makes Mathematica) though the free version does have some limitations.\n\nThe nice thing about Python is that it is free and community supported, so if you take the time to use it, it won't go away. If you learn Mathematica now, you may not be able to use it in your job, since it's an expensive license.\n\n\n```\n# Load the package\nimport sympy as sym\nfrom sympy import init_printing\ninit_printing() # This will make output look very nice!\n\nimport math # has things like math.pi (which is the numerical value of pi)\n```\n\n\n```\n# First, all symbolic variables must be declared. This is in contrast to Mathematica\nx = sym.Symbol('x')\n\n# Now, let's ask for a Taylor series expansion\nsym.series( sym.cos(x), x )\n```\n\n\n```\n# We can see the Docstring for the function to see all the options\n?sym.series\n```\n\nBefore going further, let's play with cos(pi/4)\n\n\n```\nprint( math.cos( math.pi/4 ) )\n# or, ask to print out 20 decimal places\nprint( '%.20f' % math.cos( math.pi/4 ) ) # this is old-school: see https://docs.python.org/3/tutorial/inputoutput.html#old-string-formatting\nprint( math.cos( sym.pi/4) )\nprint( sym.cos( math.pi/4) )\nprint( sym.cos( sym.pi/4) )\nsym.cos( sym.pi/4) # same as above, but use fancy formatting\n```\n\nNow let's explore the series. In particular, let's try to evaluate cos( .75 ), using only addition and multiplication, and a few \"memorized\" values of sine/cosine (let's assume that we memorize the fact that $\\cos( \\pi/4 ) = \\sqrt{2}/2$ and that $\\sin( \\pi/4 ) = \\sqrt{2}/2$.\n\nSince .75 is not that far from $\\pi/4 \\approx 0.785$, let's do a Taylor expansion of $\\cos$ around $\\pi/4$.\n\n\n```\nTaylor = sym.series( sym.cos(x), x, x0=sym.pi/4, n=5)\nTaylor\n```\n\n\n```\nTaylor.subs(x,.75) # Not what we want\n```\n\n\n```\nTaylor.evalf( subs={x: .75})\n```\n\n\n```\n# Numerically evaluating this was a problem, because of the O( x^5 ) term. Let's remove it.\n# See https://docs.sympy.org/latest/tutorial/calculus.html\nTaylor.removeO()\n```\n\n\n```\nguess = Taylor.removeO().subs(x,.75).evalf()\nprint(\"Our guess is: \\t%.15f\" % guess)\nprint(\"True value is: \\t%.15f\" % math.cos( .75) )\nprint(\"Discrepency is: \\t%.3e\" % abs( guess - math.cos(.75) ))\n```\n\n Our guess is: \t0.731688868548266\n True value is: \t0.731688868873821\n Discrepency is: \t3.256e-10\n\n\nOur *absolute* error is about $3\\times 10^{-10}$. Is this what we'd expect? Let's use math to be able to **guarantee** a small error (without having known the true answer first)\n\nLet's look at the remainder term in the Taylor series\n\n\n```\nx0=sym.Symbol('x0')\nsym.series( sym.cos(x), x, x0=x0, n=5)\n```\n\n\n```\nxi = sym.Symbol('xi')\nRemainder = -(x-x0)**5*sym.sin(xi)/120\nRemainder\n```\n\nBy Taylor's remainder theorem, we know $\\xi \\in [x,x_0]$ (or $\\xi \\in [x_0,x]$ if $x_0 < x$) such that the above remainder is the error in the Taylor series. We don't know exactly what $\\xi$ is, but that's OK, because for any $\\xi$, we can just bound $|\\sin(\\xi)| \\le 1$. So using this,...\n\n\n```\nRemainderBound = -(x-x0)**5/120\nRemainderBound\n```\n\n\n```\n# See https://docs.sympy.org/latest/tutorial/basic_operations.html\nRemainderBound.subs( [ (x,.75), (x0,math.pi/4) ])\n```\n\nTo summarize, our Taylor series approximation had error $3.25 \\times 10^{-10}$. We were able to use math to give an *a priori* bound that the error was no more than $4.63 \\times 10^{-10}$ (though in that bound, we disregarded potentially cancellation errors when summing the series)\n", "meta": {"hexsha": "2303a5ea0a5bb1415fda43644cd015ba551ea014", "size": 55915, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Demos/Ch1_SymbolicTaylorSeries.ipynb", "max_stars_repo_name": "skhadem/numerical-analysis-class", "max_stars_repo_head_hexsha": "a022fc2e73254800a1e193f94280446223ef01ae", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2020-08-25T19:11:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-12T21:49:44.000Z", "max_issues_repo_path": "Demos/Ch1_SymbolicTaylorSeries.ipynb", "max_issues_repo_name": "sabrinazhengliu/numerical-analysis-class", "max_issues_repo_head_hexsha": "1585b68d3f3c375259507bf18f03ba0332851edb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-09-01T21:44:12.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-01T21:44:12.000Z", "max_forks_repo_path": "Demos/Ch1_SymbolicTaylorSeries.ipynb", "max_forks_repo_name": "sabrinazhengliu/numerical-analysis-class", "max_forks_repo_head_hexsha": "1585b68d3f3c375259507bf18f03ba0332851edb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 13, "max_forks_repo_forks_event_min_datetime": "2020-08-25T21:25:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-03T04:14:26.000Z", "avg_line_length": 101.8488160291, "max_line_length": 10238, "alphanum_fraction": 0.7736206742, "converted": true, "num_tokens": 1194, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947163538936, "lm_q2_score": 0.9381240207636536, "lm_q1q2_score": 0.8865222429063231}} {"text": "# PuLP : getting started\n\nPuLP installation:\n\n```\npip install pulp\n```\n\n## Simple PuLP Model (bonds_simple-PuLP.py)\n\n$$\n\\begin{align}\n \\max_{x_1,x_2} & \\quad 4 x_1 + 3 x_2 \\\\\n \\text{s.t.} & \\quad x_1 + x_2 \\leq 100 \\\\\n & \\quad 2 x_1 + x_2 \\leq 150 \\\\\n & \\quad 3 x_1 + 4 x_2 \\leq 360 \\\\\n & \\quad x_1, x_2 \\geq 0\n\\end{align}\n$$\n\nExample taken from: https://www.ima.umn.edu/materials/2017-2018.2/W8.21-25.17/26306/PythonModeling.pdf\n\n\n```python\nfrom pulp import LpProblem, LpVariable, lpSum, LpMaximize, value\n```\n\n\n```python\nprob = LpProblem(\"Dedication Model\", LpMaximize)\n```\n\n\n```python\nX1 = LpVariable(\"X1\", 0, None)\nX2 = LpVariable(\"X2\", 0, None)\n```\n\n\n```python\n# Objective function\nprob += 4*X1 + 3*X2 # Objectives are nothing more than expressions without a right hand side\n\n# Constraints\nprob += X1 + X2 <= 100\nprob += 2*X1 + X2 <= 150\nprob += 3*X1 + 4*X2 <= 360\n```\n\n\n```python\nprob.solve()\n```\n\n\n```python\nprint(\"Optimal total cost is: \", value(prob.objective))\n```\n\n\n```python\nprint(\"X1 :\", X1.varValue)\nprint(\"X2 :\", X2.varValue)\n```\n", "meta": {"hexsha": "89a32863632e37d06c2fef804a7315c01d064c87", "size": 2949, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "nb_dev_python/python_pulp_getting_started.ipynb", "max_stars_repo_name": "jdhp-docs/python-notebooks", "max_stars_repo_head_hexsha": "91a97ea5cf374337efa7409e4992ea3f26b99179", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2017-05-03T12:23:36.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-26T17:30:56.000Z", "max_issues_repo_path": "nb_dev_python/python_pulp_getting_started.ipynb", "max_issues_repo_name": "jdhp-docs/python-notebooks", "max_issues_repo_head_hexsha": "91a97ea5cf374337efa7409e4992ea3f26b99179", "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": "nb_dev_python/python_pulp_getting_started.ipynb", "max_forks_repo_name": "jdhp-docs/python-notebooks", "max_forks_repo_head_hexsha": "91a97ea5cf374337efa7409e4992ea3f26b99179", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-10-26T17:30:57.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-26T17:30:57.000Z", "avg_line_length": 20.4791666667, "max_line_length": 114, "alphanum_fraction": 0.476432689, "converted": true, "num_tokens": 410, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9626731105140617, "lm_q2_score": 0.9207896769778074, "lm_q1q2_score": 0.886419462465464}} {"text": "# Section 1.2.6 Example: Testing for Primality\n\n\n```scheme\n(if (> 1 2)\n (print \"true\")\n (print \"false\"))\n```\n\n \"false\"\n\n\n\n```scheme\n(define (smallest-divisor n)\n (find-divisor n 2))\n\n(define (find-divisor n test-divisor)\n (cond ((> (square test-divisor) n) n)\n ((divides? test-divisor n) test-divisor)\n (else (find-divisor n (+ test-divisor 1)))))\n\n(define (divides? a b)\n (= (remainder b a) 0))\n\n(define (square n)\n (* n n))\n```\n\n\n```scheme\n(define (prime? n)\n (= n (smallest-divisor n)))\n\n(print (prime? 4))\n(print (prime? 5))\n(print (prime? 13))\n```\n\n #f\n #t\n #t\n\n\nThe order of this procedure is $\\Theta(\\sqrt{n})$\n\n## The Fermat test\n\nThe $\\Theta(\\log{n})$ primality test is based on a result from number theory known as ***Fermat's Little Theorem***.\n\n### Fermat's Little Theorem - フェルマーの小定理:\n\nIf $n$ is prime and $a$ is ***any positive interger*** less than $n$, the $a$ raised to the $n$-th power is congruent to $a$ modulo $n$.\n\nI.e., $a \\equiv a^n \\pmod{n}$\n\n- $a \\equiv a^n$ でなかった場合は、即それは素数でないと判断できる。\n- $a \\equiv a^n$ だった場合は、素数の可能性があるので、ことなる $a$ でまた探索をする\n\n\n```scheme\n;; base = a\n;; exp = 1,...,n\n;; m = n\n(define (expmod base exp m)\n (cond ((= exp 0) 1)\n ((even? exp)\n (remainder (square (expmod base (/ exp 2) m))\n m))\n (else\n (remainder (* base (expmod base (- exp 1) m))\n m))))\n```\n\n$\n\\begin{align}\na^n\\bmod{n} = \\left\\{\n\\begin{aligned}\n\\left[ (a^{n/2} \\bmod{n})^2 \\right] \\bmod{n} &\\quad \\textrm{if $n$ is even} \\\\\n\\left[ (a^{n-1} \\bmod{n}) \\cdot a \\right] \\bmod{n} &\\quad \\textrm{overwise}\n\\end{aligned}\n\\right.\n\\end{align}\n$\n\n\n```scheme\n(define (fermat-test n)\n (define (try-it a)\n (= (expmod a n n) a))\n (try-it (+ 1 (random (- n 1)))))\n```\n\n\n```scheme\n(define (fast-prime? n times)\n (cond \n ((= times 0) #t)\n ((fermat-test n) (fast-prime? n (- times 1)))\n (else #f)\n )\n )\n```\n\n\n```scheme\n(print (fast-prime? 2 10))\n(print (fast-prime? 11 10))\n(print (fast-prime? 443 10))\n(print (fast-prime? 93 10))\n```\n\n #t\n #t\n #t\n #f\n\n\n\n```scheme\n\n```\n", "meta": {"hexsha": "a8d01a61a7142fe8c02a25fe795d78060962bd29", "size": 4493, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "chapter01/sec1.2.6.ipynb", "max_stars_repo_name": "tyohei/sicp2e", "max_stars_repo_head_hexsha": "733f17f112fb43117b37c663ee1be33afc3794d8", "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": "chapter01/sec1.2.6.ipynb", "max_issues_repo_name": "tyohei/sicp2e", "max_issues_repo_head_hexsha": "733f17f112fb43117b37c663ee1be33afc3794d8", "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": "chapter01/sec1.2.6.ipynb", "max_forks_repo_name": "tyohei/sicp2e", "max_forks_repo_head_hexsha": "733f17f112fb43117b37c663ee1be33afc3794d8", "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": 21.3952380952, "max_line_length": 145, "alphanum_fraction": 0.4409080792, "converted": true, "num_tokens": 787, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109784205503, "lm_q2_score": 0.9324533097989077, "lm_q1q2_score": 0.8862138624974605}} {"text": "# Modeling and Simulation in Python\n\nChapter 9\n\nCopyright 2017 Allen Downey\n\nLicense: [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0)\n\n\n## Assignment 9\n### Completed by: Philip Tanofsky\n\n\n```python\n# Configure Jupyter to display the assigned value after an assignment\n%config InteractiveShell.ast_node_interactivity='last_expr_or_assign'\n\n# import everything from SymPy.\nfrom sympy import *\n\n# Set up Jupyter notebook to display math.\ninit_printing() \n```\n\nThe following displays SymPy expressions and provides the option of showing results in LaTeX format.\n\n\n```python\nfrom sympy.printing import latex\n\ndef show(expr, show_latex=False):\n \"\"\"Display a SymPy expression.\n \n expr: SymPy expression\n show_latex: boolean\n \"\"\"\n if show_latex:\n print(latex(expr))\n return expr\n```\n\n### Analysis with SymPy\n\nCreate a symbol for time.\n\n\n```python\nt = symbols('t')\n```\n\nIf you combine symbols and numbers, you get symbolic expressions.\n\n\n```python\nexpr = t + 1\n```\n\nThe result is an `Add` object, which just represents the sum without trying to compute it.\n\n\n```python\ntype(expr)\n```\n\n\n\n\n sympy.core.add.Add\n\n\n\n`subs` can be used to replace a symbol with a number, which allows the addition to proceed.\n\n\n```python\nexpr.subs(t, 2)\n```\n\n`f` is a special class of symbol that represents a function.\n\n\n```python\nf = Function('f')\n```\n\n\n\n\n f\n\n\n\nThe type of `f` is `UndefinedFunction`\n\n\n```python\ntype(f)\n```\n\n\n\n\n sympy.core.function.UndefinedFunction\n\n\n\nSymPy understands that `f(t)` means `f` evaluated at `t`, but it doesn't try to evaluate it yet.\n\n\n```python\nf(t)\n```\n\n`diff` returns a `Derivative` object that represents the time derivative of `f`\n\n\n```python\ndfdt = diff(f(t), t)\n```\n\n\n```python\ntype(dfdt)\n```\n\n\n\n\n sympy.core.function.Derivative\n\n\n\nWe need a symbol for `alpha`\n\n\n```python\nalpha = symbols('alpha')\n```\n\nNow we can write the differential equation for proportional growth.\n\n\n```python\neq1 = Eq(dfdt, alpha*f(t))\n```\n\nAnd use `dsolve` to solve it. The result is the general solution.\n\n\n```python\nsolution_eq = dsolve(eq1)\n```\n\nWe can tell it's a general solution because it contains an unspecified constant, `C1`.\n\nIn this example, finding the particular solution is easy: we just replace `C1` with `p_0`\n\n\n```python\nC1, p_0 = symbols('C1 p_0')\n```\n\n\n```python\nparticular = solution_eq.subs(C1, p_0)\n```\n\nIn the next example, we have to work a little harder to find the particular solution.\n\n### Solving the quadratic growth equation \n\nWe'll use the (r, K) parameterization, so we'll need two more symbols:\n\n\n```python\nr, K = symbols('r K')\n```\n\nNow we can write the differential equation.\n\n\n```python\neq2 = Eq(diff(f(t), t), r * f(t) * (1 - f(t)/K))\n```\n\nAnd solve it.\n\n\n```python\nsolution_eq = dsolve(eq2)\n```\n\nThe result, `solution_eq`, contains `rhs`, which is the right-hand side of the solution.\n\n\n```python\ngeneral = solution_eq.rhs\n```\n\nWe can evaluate the right-hand side at $t=0$\n\n\n```python\nat_0 = general.subs(t, 0)\n```\n\nNow we want to find the value of `C1` that makes `f(0) = p_0`.\n\nSo we'll create the equation `at_0 = p_0` and solve for `C1`. Because this is just an algebraic identity, not a differential equation, we use `solve`, not `dsolve`.\n\nThe result from `solve` is a list of solutions. In this case, [we have reason to expect only one solution](https://en.wikipedia.org/wiki/Picard%E2%80%93Lindel%C3%B6f_theorem), but we still get a list, so we have to use the bracket operator, `[0]`, to select the first one.\n\n\n```python\nsolutions = solve(Eq(at_0, p_0), C1)\ntype(solutions), len(solutions)\n```\n\n\n\n\n (list, 1)\n\n\n\n\n```python\nvalue_of_C1 = solutions[0]\n```\n\nNow in the general solution, we want to replace `C1` with the value of `C1` we just figured out.\n\n\n```python\nparticular = general.subs(C1, value_of_C1)\n```\n\nThe result is complicated, but SymPy provides a method that tries to simplify it.\n\n\n```python\nparticular = simplify(particular)\n```\n\nOften simplicity is in the eye of the beholder, but that's about as simple as this expression gets.\n\nJust to double-check, we can evaluate it at `t=0` and confirm that we get `p_0`\n\n\n```python\nparticular.subs(t, 0)\n```\n\nThis solution is called the [logistic function](https://en.wikipedia.org/wiki/Population_growth#Logistic_equation).\n\nIn some places you'll see it written in a different form:\n\n$f(t) = \\frac{K}{1 + A e^{-rt}}$\n\nwhere $A = (K - p_0) / p_0$.\n\nWe can use SymPy to confirm that these two forms are equivalent. First we represent the alternative version of the logistic function:\n\n\n```python\nA = (K - p_0) / p_0\n```\n\n\n```python\nlogistic = K / (1 + A * exp(-r*t))\n```\n\nTo see whether two expressions are equivalent, we can check whether their difference simplifies to 0.\n\n\n```python\nsimplify(particular - logistic)\n```\n\nThis test only works one way: if SymPy says the difference reduces to 0, the expressions are definitely equivalent (and not just numerically close).\n\nBut if SymPy can't find a way to simplify the result to 0, that doesn't necessarily mean there isn't one. Testing whether two expressions are equivalent is a surprisingly hard problem; in fact, there is no algorithm that can solve it in general.\n\n### Exercises\n\n**Exercise:** Solve the quadratic growth equation using the alternative parameterization\n\n$\\frac{df(t)}{dt} = \\alpha f(t) + \\beta f^2(t) $\n\n\n```python\n# Create symbol for beta\nbeta = symbols('beta')\n```\n\n\n```python\n# Now write the differential equation\neqX = Eq(diff(f(t), t), alpha*f(t) + beta*f(t)**2)\n```\n\n\n```python\n# Solve it\nsolution_X = dsolve(eqX)\n```\n\n\n```python\n# Extract the right hand side\ngeneral_X = solution_X.rhs\n```\n\n\n```python\n# Evaluate the right-hand side at t = 0\nat_0_X = general_X.subs(t, 0)\n```\n\n\n```python\n# Now find the value of C1 that makes f(0) = p_0\n# So create equation at_0_x = p_0 and solve for C1\n# Use solve and not dsolve\nsolutions_X = solve(Eq(at_0_X, p_0), C1)\ntype(solutions_X), len(solutions_X)\n```\n\n\n\n\n (list, 1)\n\n\n\n\n```python\n# Result of solve is a list of solutions\n# Use bracket operator [0] to select first and only one solution\nvalue_of_C1_X = solutions_X[0]\n```\n\n\n```python\n# Replace C1 with the value of C1 just determined\nparticular_X = general_X.subs(C1, value_of_C1_X)\n```\n\n\n```python\n# Simply above with SymPy\nparticular_X = simplify(particular_X)\n```\n\n\n```python\n# Double check result by evaluating t=0 to confirm p_0\nparticular_X.subs(t, 0)\n```\n\n\n```python\n# Above shows the equation solved\n```\n\n**Exercise:** Use [WolframAlpha](https://www.wolframalpha.com/) to solve the quadratic growth model, using either or both forms of parameterization:\n\n df(t) / dt = alpha f(t) + beta f(t)^2\n\nor\n\n df(t) / dt = r f(t) (1 - f(t)/K)\n\nFind the general solution and also the particular solution where `f(0) = p_0`.\n\n### General solution for \n\n df(t) / dt = alpha f(t) + beta f(t)^2\n\n\n\n### Particular solution for \n\n df(t) / dt = alpha f(t) + beta f(t)^2 where f(0) = p_0\n\n\n\n### General solution for \n\n df(t) / dt = r f(t) (1 - f(t)/K)\n\n\n\n### Particular solution for \n\n df(t) / dt = r f(t) (1 - f(t)/K) where f(0) = p_0\n\n\n", "meta": {"hexsha": "b6e702e83f003430230ae651347e32267ce4d5d8", "size": 76332, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/chap09.ipynb", "max_stars_repo_name": "ptanofsky/ModSimPy", "max_stars_repo_head_hexsha": "8bce9989eabb83dc36a4f65b3aa68b5cf20ccb90", "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/chap09.ipynb", "max_issues_repo_name": "ptanofsky/ModSimPy", "max_issues_repo_head_hexsha": "8bce9989eabb83dc36a4f65b3aa68b5cf20ccb90", "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/chap09.ipynb", "max_forks_repo_name": "ptanofsky/ModSimPy", "max_forks_repo_head_hexsha": "8bce9989eabb83dc36a4f65b3aa68b5cf20ccb90", "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": 58.0030395137, "max_line_length": 3340, "alphanum_fraction": 0.7735549966, "converted": true, "num_tokens": 1984, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9632305297023093, "lm_q2_score": 0.9196425372343816, "lm_q1q2_score": 0.8858277682770491}} {"text": "```python\nimport numpy as np\nfrom scipy import stats\n\nimport matplotlib.pyplot as plt\nplt.style.use('fivethirtyeight')\n```\n\n# Inverse Transform sampling\n\n\n## Rationale\n\n\n**Inverse transform sampling** allows to transform samples from uniform distribution $U$ to any other distribution $D$, given the $CDF$ of $D$.\n\nHow can we do it?\n\nLet's take\n\n$$\\large T(U) = X$$\n\nwhere:\n\n* $U$ is a uniform random variable\n* $T$ is some kind of a transformation\n* $X$ is the target random variable (let's use **exponential** distribution as an example)\n\n\nNow, we said that to perform **inverse transformation sampling**, we need a $CDF$.\n\nBy definition $CDF$ (we'll call it $F_X(x)$ here) is given by: \n\n$$\\large F_X(x) \\triangleq P(X \\leq x)$$\n\nWe said before that to get $X$, we'll apply certain transformation $T$ to a uniform random variable.\n\nWe can then say, that:\n\n$$\\large P(X \\leq x) = P(T(U) \\leq x)$$\n\nNow, let's apply an ibnverse of $T$ to the both sides of the inequality:\n\n$$\\large = P(U \\leq T^{-1}(x))$$\n\nUniform distribution has a nice property that it's $CDF$ at any given point $x$ is equal to the value of $x$.\n\nTherefore, we can say that:\n\n$$\\large = T^{-1}(x)$$\n\nand conclude that:\n\n$$\\large F_X(x) = T^{-1}(x)$$\n\n\n## Conclusion\n\nWe demonstrated how to sample from any density $D$ using a sample from a uniform distribution and an inverse of $CDF$ od $D$. \n\nNow, let's apply it in practice!\n\n## Code\n\nLet's see how to apply this in Python. \n\nWe'll use **exponential distribution** as an example.\n\n\n```python\n# Define params\nSAMPLE_SIZE = 100000\nN_BINS = np.sqrt(SAMPLE_SIZE).astype('int') // 2\nLAMBDA = 8 \n```\n\nLet's instantiate distributions.\n\nWe will instantiate an exponential distribution expicitly for comparison purposes.\n\n___________\n\nNote that **`scipy.stats`** has a slightly **different parametrization** of exponential than the populuar $\\lambda$ parametrization. \n\nIn the [documentation](https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.expon.html), we read:\n\n*A common parameterization for expon is in terms of the rate parameter lambda, such that pdf = lambda * exp(-lambda * x). This parameterization corresponds to using scale = 1 / lambda.*\n\n____________\n\nTherefore, we're going to use **`scale=1/LAMBDA`** to parametrize our test **exponential distribution**. \n\n\n```python\n# Instantiate U(0, 1)\nunif = stats.uniform(0, 1)\n\n# Instantiate Exp(8) for comparison purposes\nexp = stats.expon(loc=0, scale=1/LAMBDA)\n```\n\nNow, we need to define the inverse transformation $T^{-1}(x)$ that will allow us to translate between uniform and exponential samples.\n\nThe $CDF$ of exponential distribution is defined as:\n\n$$\\large\n\\begin{equation}\n F_X(x) \\triangleq\n \\begin{cases}\n 1 - e^{-\\lambda x} \\ \\text{ for }\\ x \\geq 0\\\\\n 0 \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\text{for }\\ x<0 \\\\\n \\end{cases} \n\\end{equation}\n$$\n\nLet's take the inverse of this function (solve for $x$):\n\n$$\\large y = 1 - e^{-\\lambda x}$$\n\n* subtract $1$ from both sides:\n\n$$\\large 1 - y = - e^{-\\lambda x}$$\n\n* take $ln$ of both sides:\n\n$$\\large ln(1 - y) = \\lambda x$$\n\n* divide both sides by $\\lambda$:\n\n$$\\large x = \\frac{ln(1 - y)}{\\lambda}$$\n\n
\n\n**Et voilà!** 🎉🎉🎉 \n\nWe've got it! 💪🏼\n\n
\n\nLet's translate it to Python code:\n\n\n```python\n# Define \ndef transform_to_exp(x, lmbd):\n \n \"\"\"Transoforms a uniform sample into an exponential sample\"\"\"\n \n return -np.log(1 - x) / lmbd\n```\n\nTake samples:\n\n\n```python\n# Sample from uniform\nsample_unif = unif.rvs(SAMPLE_SIZE)\n\n# Sample from the true exponential\nsample_exp = exp.rvs(SAMPLE_SIZE)\n\n# Transform U -> Exp\nsample_transform = transform_to_exp(sample_unif, LAMBDA)\n```\n\nA brief sanity check:\n\n\n```python\n# Sanity check -> U(0, 1)\nplt.hist(sample_unif, bins=N_BINS, density=True)\nplt.title('Histogarm of $U(0, 1)$')\nplt.ylabel('$p(x)$')\nplt.xlabel('$x$')\nplt.show()\n```\n\n..and let's compare the resutls:\n\n\n```python\nplt.hist(sample_exp, bins=N_BINS, density=True, alpha=.5, label='Exponential')\nplt.hist(sample_transform, bins=N_BINS, density=True, alpha=.5, label='$T(U)$')\nplt.legend()\nplt.title('Histogram of exponential and transformed distributions', fontsize=12)\nplt.ylabel('$p(x)$')\nplt.xlabel('$x$')\nplt.show()\n```\n\nBeautiful! It worked as expected 🎉🎉🎉\n", "meta": {"hexsha": "b65ade8e8fecae8e5ddd64b26f270f1180d8d923", "size": 42054, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "sampling/00 - Inverse transform sampling.ipynb", "max_stars_repo_name": "AlxndrMlk/statistics", "max_stars_repo_head_hexsha": "664f88d04be61fcee2a485cb29c01727332d0b73", "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": "sampling/00 - Inverse transform sampling.ipynb", "max_issues_repo_name": "AlxndrMlk/statistics", "max_issues_repo_head_hexsha": "664f88d04be61fcee2a485cb29c01727332d0b73", "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": "sampling/00 - Inverse transform sampling.ipynb", "max_forks_repo_name": "AlxndrMlk/statistics", "max_forks_repo_head_hexsha": "664f88d04be61fcee2a485cb29c01727332d0b73", "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": 129.7962962963, "max_line_length": 18188, "alphanum_fraction": 0.8781328768, "converted": true, "num_tokens": 1233, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.957277806109987, "lm_q2_score": 0.9252299622463116, "lm_q1q2_score": 0.8857021084063753}} {"text": "\n\n# Binomial Trees\n\n\n```python\nimport math\n```\n\n\n```python\ndef exp(x):\n return math.exp(x)\n```\n\n## Application of Binomial Trees\n\nBinomial trees are a popular technique for pricing options. This method relies on the assumption that stock prices follow a random walk and at each time step, it has a certain probability of moving up or down by a certain percentage. Furthermore, it requires the assumption that no arbitrage opportunities exist. The binomial tree represents the different paths a stock price can follow. In the limit, this model converges to the Black-Scholes-Merton model, which is described [here](european_plain_vanilla_option.ipynb).\n\n## Example - One-Step Binomial Tree\n\nConsider a stock which currently trades at 50. We are interested in pricing a European call option with a strike of 50 and maturity in six months from now. We know that at maturity, the stock will either move up to 55 or move down to 45. Hence, if the stock price moves up, the option will have a value of 5; if the stock price moves down, the option will have the value zero. \n\nAssuming a risk neutral world, we can set up a portfolio of the stock itself and the option so that we already know the value of the portfolio at maturity. Therefore, we need to calculate the delta of shares we need to hold to make the portfolio riskless. We can calculate delta as \n\n$$\\Delta=\\frac{c_u-c_d}{S_0u-S_0d},$$\n\n\nwhere $c_u$ and $c_d$ is the value of the option assuming the stock moves up respectively down and $S_0u$ and $S_0d$ is the value of the stock if it moves up respectively down. Hence, delta is given as \n\n$$\\Delta=\\frac{5-0}{55-45}=0.5.$$\n\n\nNow, we can create a riskless portfolio by holding a long position in $\\Delta$ shares and short one call option. If the stock price moves up to 55, the value of the portfolio is $55\\cdot0.5-5=22.5$; if the stock price moves down to 45, the value of the portfolio is $45\\cdot0.5-0=22.5$. Discounting the portfolio value at maturity assuming a risk-free interest rate $r$ of 0.05 gives as a present value of the portfolio of \n\n$$22.5e^{-0.05\\cdot6/12}=21.94.$$\n\nIn order to determine the option price today, we know that the portfolio value is the value of the long position in $\\Delta$ shares and the short position in one option and we further now that this value is $21.94$. Hence, it follows that \n\n$$50\\cdot0.5-c=21.94$$ or $$c = 3.06.$$\n\nThe following code shows how the option value can be calculated.\n\n\n```python\nS0 = 50\nK = 50\nS0_u = 55\nS0_d = 45\nr= 0.05\nT = 0.5\n\nc_u = max(S0_u-K,0)\nc_d = max(S0_d-K, 0)\n\ndelta = (c_u-c_d)/(S0_u-S0_d)\n\npf_value_u = (S0_u*delta-c_u)*exp(-r*T)\npf_value_d = (S0_d*delta-c_d)*exp(-r*T)\n\nc = -(pf_value_u-(S0*delta))\nprint(c)\n```\n\n## Generalization of the One-Step Binomial Tree\n\nThe following formula allows the pricing of an option using a one-step binomial tree. The value of an option $o$ is defined as\n\n$$ o = e^{-rT}[po_u+(1-p)o_d]$$\n\nwhere $o_u$ describes the value of the option in case of an upward-movement of the stock and $o_d$ in case of a downward-movement of the stock with the probability of an upward-movement $p$ defined as\n\n$$p=\\frac{e^{rT}-d}{u-d}$$\n\nwhere $u$ is the upward-moving factor and $d$ is the downward-moving factor, i.e. $u-1$ is the percentage increase in case of an upward-movement and $1-d$ is the percentage decrease in case of an downward-movement.\n\nFor a detailed description how the formulas are derived please refer to Hull, *Options, futures, and other derivatives, 8th Edition,* 2012, p. 265.\n\nWe now can take the example from before using these formulas.\n\n\n```python\nS0 = 50\nK = 50\nr = 0.05\nT = 0.5\nu = 1.1\nd = 0.9\nS0_u = S0*u\nS0_d = S0*d\n\n#Call\no_u = max(S0_u-K,0)\no_d = max(S0_d-K, 0)\n\n#Put - uncomment the following lines to calculate the value of a put option instead of a call option\n#o_u = max(K-S0_u,0)\n#o_d = max(K-S0_d, 0)\n\np = (exp(r*T)-d)/(u-d)\n\no = exp(-r*T)*(p*o_u+(1-p)*o_d)\nprint(o)\n```\n\n## Two-Step Binomial Tree\n\nThe analysis of the option value using the one-step binomial tree can be extended to a two-step binomial tree. Hence, let A denote the node at start $S_0$. In the first step, the stock price either moves up by $u$ or down by $d$ to $S_0u$ or $S_0d$ where $S_0u$ is node B and $S_0d$ is node C of the binomial tree. In the second step, the stock price again goes up by $u$ or down by $d$ from each node. Hence from node B, the stock price goes up to $S_0uu$ (node D), or down to $S_0ud$ (node E). From node C, the stock price either goes up to $S_0du$ which equals $S_0ud$ (node E) or down to $S_0dd$ node (F). Hence, we derive the following nodes from the two-step binomial model.\n\n\n$A = S_0$,\n$B = S_0u$,\n$C = S_0d$,\n$D = S_0uu$,\n$E = S_0ud/S_0du$,\n$F = S_0dd$.\n\nIn order to determine the option price today, we need to go backwards starting at the nodes at maturity to determine the option prices at the previous nodes. Therefore, we need the stock prices at each node A to F which are given as \n\n$A = 50.00$,\n$B = 55.00$,\n$C = 45.00$,\n$D = 60.50$,\n$E = 49.50$,\n$F = 40.50$.\n\nHence, at nodes D to F the option price is either $max(S_T-K, 0)$ in case of call option or $max(K-S_T, 0)$ in case of a put option. This leads to the following option values at the terminal nodes D to F in case of a call option:\n\n$o_D = 10.50$,\n$o_E = 0.00$,\n$o_F = 0.00$.\n\nHaving calculated the payoffs at maturity, we can determine the option values at nodes B and C. The values are calculated using the formula given in section 1.3 as \n\n$$o = e^{-rT}[po_u+(1-p)o_d].$$\n\nThe probability of an upward-movement $p$ is defined as shown in section 1.2 as \n\n$$p=\\frac{e^{rT}-d}{u-d}$$ which is approximately 0.63.\n\nUsing this probability of an upward movement, the option value at node B is $o_B=e^{-0.05\\cdot{0.5}}[0.63\\cdot{10.50}+(1-0.63)\\cdot{0}]=6.42$ and the option value at node C is $o_C=e^{-0.05\\cdot{0.5}}[0.63\\cdot{0}+(1-0.63)\\cdot{0}]=0$.\n\n$o_B = 6.42$,\n$o_C = 0.00$.\n\nThe same can be done for the last node A which is $o_A=e^{-0.05\\cdot{0.5}}[0.63\\cdot{6.42}+(1-0.63)\\cdot{0}]=3.92$.\n\nHence, the option value today at node A is 3.92.\n\nThe procedure for deriving the option value can be reproduced using the following code cell.\n\n\n```python\nS0 = 50\nK = 50\nr = 0.05\nT = 0.5\nu = 1.1\nd = 0.9\n\nS0_u = S0*u\nS0_d = S0*d\n\nS0_uu = S0*u**2\nS0_ud = S0*u*d #Equals S0_du == S0*d*u\nS0_dd = S0*d**2\n\np = (exp(r*T)-d)/(u-d)\n\n\no_F = max(S0_dd-K, 0) #In the case of a put option this needs to be max(K-S0_dd, 0)\no_E = max(S0_ud-K, 0)\no_D = max(S0_uu-K, 0)\n\no_C = exp(-r*T)*(o_E*p+o_F*(1-p))\no_B = exp(-r*T)*(o_D*p+o_E*(1-p))\n\no_A = exp(-r*T)*(o_B*p+o_C*(1-p))\n\nprint('Value of the call option = ',o_A)\n```\n\n## Generalization of the Two-Step Binomial Tree\n\nThe formula for the two-step binomial tree can be generalized as follows: Let $r$ denote the risk-free interest rate and $\\Delta{t}$ denote the length of a time step. The probability of an upward movement is $p$ and the option value is $o$ (e.g. the option value after an upward movement is $o_u$). The option value at each time step $\\Delta{t}$ is defined as\n\n$$o = e^{-r\\Delta{t}}[po_u+(1-p)o_d]$$\nwith\n$$p=\\frac{e^{r\\Delta{t}}-d}{u-d}$$\n\nRepeating this step for the relevant nodes gives\n\n\\begin{align}\no_u &= e^{-r\\Delta{t}}[po_uu+(1-p)o_ud] \\\\\n\\\\\no_d &= e^{-r\\Delta{t}}[po_ud+(1-p)o_dd] \\\\\n\\\\\no &= e^{-r\\Delta{t}}[po_u+(1-p)o_d] \\\\\n\\end{align}\n\nwhich can be summarized to \n\n$$o = e^{-2r\\Delta{t}}[p^2o_{uu}+2p(1-p)o_{ud}+(1-p^2)o_{dd}].$$\n\n## Application of Binomial Trees in Option Pricing\n\nThe most commonly application of binomial trees in option pricing is the case of American options. In contrast to European options, American options can be exercised at any time before expiry, and this give the holder of the option more rights than in the case of an European option. The valuation of American options using binomial trees is explained in the [American Plain Vanilla Option](american_plain_vanilla_option.ipynb) notebook.\n\n---\n", "meta": {"hexsha": "a95b6efbdcac4bacd51c9593785280b67c7bec12", "size": 12712, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "instruments/binomial_trees.ipynb", "max_stars_repo_name": "frontmark/jupyter-notebooks", "max_stars_repo_head_hexsha": "556a01bc4d3f2dc9b44af9c167aaabf35d23f5ba", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 24, "max_stars_repo_stars_event_min_datetime": "2020-01-16T17:05:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-17T00:59:00.000Z", "max_issues_repo_path": "instruments/binomial_trees.ipynb", "max_issues_repo_name": "frontmark/jupyter-notebooks", "max_issues_repo_head_hexsha": "556a01bc4d3f2dc9b44af9c167aaabf35d23f5ba", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 17, "max_issues_repo_issues_event_min_datetime": "2020-05-01T10:19:24.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-07T10:40:03.000Z", "max_forks_repo_path": "instruments/binomial_trees.ipynb", "max_forks_repo_name": "frontmark/jupyter-notebooks", "max_forks_repo_head_hexsha": "556a01bc4d3f2dc9b44af9c167aaabf35d23f5ba", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2020-01-31T18:52:56.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-27T12:06:01.000Z", "avg_line_length": 35.0192837466, "max_line_length": 689, "alphanum_fraction": 0.5805538074, "converted": true, "num_tokens": 2552, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966671870766, "lm_q2_score": 0.9353465156988344, "lm_q1q2_score": 0.8853958944255612}} {"text": "# Dynamic programming\n\nThis notebook is based on the tutorial on Dynamic programming on this webpage (in Russian): https://bestprogrammer.ru/izuchenie/uchebnik-po-dinamicheskomu-programmirovaniyu-sozdanie-effektivnyh-programm-na-python\n\n## Imports\n\n\n```python\nimport time\nimport matplotlib.pyplot as plt\n```\n\n## Recursive algorithm for Fibonacci numbers\n\n\n```python\n%%timeit\n\ndef fib(n):\n if n <= 0:\n return 0\n if n == 1:\n return 1\n else:\n return fib(n-1) + fib(n-2)\n \nfib(10)\n```\n\n 17.5 µs ± 228 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)\n\n\n## Recursive algorithm with memoization for Fibonacci numbers\n\n\n```python\n%%timeit\n\ncache = {}\n\ndef fib(n):\n if n <= 0:\n return 0\n if n == 1:\n return 1\n elif n in cache:\n return cache[n]\n else:\n cache[n] = fib(n-1) + fib(n-2)\n return cache[n]\n \nfib(10)\n```\n\n 2.95 µs ± 27.8 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)\n\n\nWe can see that with memoization, the runtime decreases from 18 to 3 microseconds, that is, we get a six-fold improvement.\n\n## Knapsack problem\n\nBased on the description from https://en.wikipedia.org/wiki/Knapsack_problem as the original statement is incomprehensible.\n\nWe consider the problem of choosing some items from the given $n$ items such that the total value of these items is maximized but the total weight of these items does not exceed a given maximum capacity. This is called **0-1 knapsack problem** because we either take an item (1) or do not (0); we are not allowed to take fractions of the items.\n\nLet's denote by $x_i$ if we take the $ith$ item or not: $x_i \\in \\{0, 1\\}$. The value and the weight of the $i$th item are $v_i$ and $w_i$, respectively. The maximum allowed capacity is $M$.\n\nThen, mathematically we solve the following problem:\n$$\n\\begin{align}\n\\text{maximize} & \\sum_{i=1}^n x_i v_i \\\\\n\\text{subject to} & \\sum_{i=1}^n x_i w_i \\leq M,\n\\end{align}\n$$\nwhere $x_i \\in \\{0, 1\\}$.\n\nThe following implementation and test problem follows https://en.wikipedia.org/wiki/Knapsack_problem\n\n\n```python\ndef solve_knapsack_problem(v, w, M):\n \"\"\"Solve knapsack problem with values `v`, weights `w`, and capacity `M`.\"\"\"\n n = len(v)\n assert len(v) == len(w)\n \n cache = {}\n \n for i in (range(0, n)):\n cache[i, 0] = 0\n for j in (range(0, M+1)):\n cache[0, j] = 0\n \n for i in range(1, n):\n for j in range(0, M+1):\n if w[i] > j:\n cache[i, j] = cache[i-1, j]\n else:\n cache[i, j] = max(\n cache[i-1, j],\n cache[i-1, j-w[i]] + v[i]\n )\n \n return cache[n-1, M]\n```\n\n\n```python\nv = [5, 4, 3, 2]\nw = [4, 3, 2, 1]\nM = 6\n\nsolve_knapsack_problem(v, w, M)\n```\n\n\n\n\n 9\n\n\n\n## Coin change problem\n\n\n```python\n\n```\n", "meta": {"hexsha": "05692ceb14e8ab0aae66d68346872b0900ebcf5d", "size": 6503, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "2021-12-18-dynamic-programming.ipynb", "max_stars_repo_name": "dmitry-kabanov/datascience", "max_stars_repo_head_hexsha": "487d7b8609320d7d207b030e5ba1b538d5bd1394", "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": "2021-12-18-dynamic-programming.ipynb", "max_issues_repo_name": "dmitry-kabanov/datascience", "max_issues_repo_head_hexsha": "487d7b8609320d7d207b030e5ba1b538d5bd1394", "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": "2021-12-18-dynamic-programming.ipynb", "max_forks_repo_name": "dmitry-kabanov/datascience", "max_forks_repo_head_hexsha": "487d7b8609320d7d207b030e5ba1b538d5bd1394", "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": 25.2054263566, "max_line_length": 353, "alphanum_fraction": 0.5085345225, "converted": true, "num_tokens": 870, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.952574122783325, "lm_q2_score": 0.9294404062557874, "lm_q1q2_score": 0.8853608796684839}} {"text": "# Factorial digits\n\nHow many digits does the factorial of $n$ have?\n\n\n```python\nimport matplotlib.pyplot as plt\n%matplotlib inline\nimport numpy as np\nimport sympy\n```\n\nCompute the factorial of numbers ranging over several orders of magnitude.\n\n\n```python\norder = 5\nx_values = np.logspace(0, order, 4*order + 1, dtype=np.int64)\nfac_values = [sympy.factorial(x) for x in x_values]\nnr_digits = list(map(lambda x: len(str(x)), fac_values))\n```\n\nPlot the result in a $\\log$-$\\log$ plot.\n\n\n```python\nfigure, axes = plt.subplots(nrows=1, ncols=2, figsize=(12, 6))\naxes[0].loglog(x_values, fac_values)\naxes[0].set_xlabel(r'$n$')\naxes[0].set_ylabel(r'$n!$')\naxes[1].loglog(x_values, nr_digits)\naxes[1].set_xlabel(r'$n$')\naxes[1].set_ylabel(r'nr. digits of $n!$')\nfigure.tight_layout()\n```\n\n\nThe number of digits grows approximately linear with $n$. This is easy to see since $n! = 10^{\\log_{10} n!}$, $n! = \\prod_{i=1}^{n} i$ and hence $\\log_{10} n! = \\sum_{i=1}^{n} \\log_{10} i$. Now we can bound this sum from above since $\\log i < 1$ for $i < 10$, $\\log i < 2$ for $i < 100$, and so on. So if $n = 10^p$, $\\log_{10} n! < 1 \\times 10 + 2 \\times 100 + 3 \\times 1000 + \\ldots + p \\times 10^p$. So $\\log_{10} 10^p! < (p + 1) \\times 10^p$. Since the number of digits of an integer $n$ is $\\lceil \\log_{10} n \\rceil$, this proves the point.\n", "meta": {"hexsha": "03792f737d7e2aa4afbce96853ebbc70d0111011", "size": 33546, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Python/Sympy/factorial_digits.ipynb", "max_stars_repo_name": "Gjacquenot/training-material", "max_stars_repo_head_hexsha": "16b29962bf5683f97a1072d961dd9f31e7468b8d", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 115, "max_stars_repo_stars_event_min_datetime": "2015-03-23T13:34:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T00:27:21.000Z", "max_issues_repo_path": "Python/Sympy/factorial_digits.ipynb", "max_issues_repo_name": "Gjacquenot/training-material", "max_issues_repo_head_hexsha": "16b29962bf5683f97a1072d961dd9f31e7468b8d", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 56, "max_issues_repo_issues_event_min_datetime": "2015-02-25T15:04:26.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-03T07:42:48.000Z", "max_forks_repo_path": "Python/Sympy/factorial_digits.ipynb", "max_forks_repo_name": "Gjacquenot/training-material", "max_forks_repo_head_hexsha": "16b29962bf5683f97a1072d961dd9f31e7468b8d", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 59, "max_forks_repo_forks_event_min_datetime": "2015-11-26T11:44:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-21T00:27:22.000Z", "avg_line_length": 262.078125, "max_line_length": 30348, "alphanum_fraction": 0.927800632, "converted": true, "num_tokens": 468, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741227833249, "lm_q2_score": 0.9294403979493139, "lm_q1q2_score": 0.885360871755952}} {"text": "\n\n# Homework 0\n\n## Exercise \n\nGet used to using python as a calculator. Try computing all of the following:\n\n(i) $10 \\sqrt{(2(11.4+12.6))}$\n\n\n```python\nimport numpy as np\na = 10*np.sqrt(2*(11.4+12.6))\na\n```\n\n\n\n\n 69.28203230275508\n\n\n\n(ii) $e^{0.5}$\n\n\n```python\nimport numpy as np\na = np.exp(0.5)\na\n```\n\n\n\n\n 1.6487212707001282\n\n\n\n(iii) the value of $y=(10+sin(x)+x^2+cosh(x^2+1))/(sinh(x)+x^3+3x^4+e^x)$ for $x=\\pi$ and $x=0.2$\n\n\n```python\nimport numpy as np\n\ndef value(xValue):\n x = xValue\n num = 10+np.sin(x)+x**2+np.cosh(x**2+1)\n dem = np.sinh(x) + x**3 + 3*x**4 +np.exp(x)\n y = num/dem\n return y\n\nprint(\"When x = pi, the value of y equals: \" , value(np.pi))\nprint(\"When x = 0.2, the value of y equals: \" , value(0.2))\n\n```\n\n When x = pi, the value of y equals: 73.47132985890015\n When x = 0.2, the value of y equals: 8.240812092855817\n\n\n## Exercise\n\nWrite a function that takes as arguement $r$ for the radius of a circle and returns the diameter $r$ of the circle, as well as the circle's circumference $c$ and the area $a$. Try the function for $r=6$.\n\n\n```python\nimport numpy as np\n\ndef triangleInfo(radius):\n r = radius\n d = 2*r\n c = 2*np.pi*r\n a = np.pi*r**2\n infoList = [d,c,a]\n return infoList\n\ninfo = triangleInfo(radius=6)\nprint(\"Given radius r=6, the circle's diameter d is\", info[0],\n \" circumference c is \", info[1], \", and area a is \", info[2])\n```\n\n Given radius r=6, the circle's diameter d is 12 circumference c is 37.69911184307752 , and area a is 113.09733552923255\n\n\n## Exercise\n\nWrite a for loop to sum up all natural numbers from $1$ to $1,000,000$.\n\n\n```python\n## Method 1\ndef sequenceSum(startVal,endVal, increment):\n sum = 0\n item = startVal\n while (item < endVal) | (item == endVal):\n sum += item\n item +=increment\n return sum\n\nsum1 = sequenceSum(1,1000000,1)\nprint(\"method 1\", sum1)\n\n\n## Method 2\na= range(1,1000001,1) # notice the exclusive or range at the right boundary\nsum2 = sum(a)\nprint(\"method 2\", sum2)\n```\n\n method 1 500000500000\n method 2 500000500000\n\n\n## Exercise\n\nCompute the sum $\\sum_{i=1}^{10}(i+1)$.\n\n\n```python\ndef sequenceSum(startVal,endVal,increment,bias):\n sum = 0\n item = startVal\n while (item < endVal) | (item == endVal):\n sum += item\n item +=increment\n return sum\n\nsum1 = sequenceSum(1,10,1,bias = 1)\nprint(\"The sum of sequence here is \", sum1)\n```\n\n The sum of sequence here is 55\n\n\n## Exercise\n\nThe curve $f(x)=x^2+3x+\\sqrt5$ intersects the curve $g(x)=-x^2-2x+1$ at two points. Find the coordinates of the intersections and the gradients of the tangents to each curve at those points.\n\n\n```python\n\"\"\"Method 1\"\"\"\nimport numpy as np\nimport sympy as sy\n\n\ndef find_intersections(x,line_1,line_2):\n intersection_set = set()\n # print(type(intersection_set))\n N = len(x)-1\n index = 0\n while index < N:\n current_x, current_y1, current_y2 = x[index], line_1[index], line_2[index]\n dif = np.abs(current_y2 - current_y1)\n if dif < 1e-3:\n # print(dif)\n intersection_set.add((round(current_x, 3), round(current_y1, 2)))\n index += 1\n intersection_list = list(intersection_set)\n return intersection_list\n\n\ndef fun1(x):\n y1 = np.square(x)+3*x+np.sqrt(5)\n return y1\n\n\ndef fun2(x):\n y2 = - np.square(x)-2*x+1\n return y2\n\n\ndef FindGradients(current_x,tag=\"fun1\"):\n import sympy as sy\n\n x = sy.symbols('x')\n y1 = x**2 + 3*x + sy.sqrt(5)\n y2 = - x**2 - 2*x + 1\n y1_dif = sy.diff(y1, x)\n y2_dif = sy.diff(y2, x)\n\n if tag == \"fun1\":\n difValue = y1_dif.subs(x,current_x)\n difValue = round(difValue.evalf(),2)\n print(\"The gradient of function1 at x = \", current_x, \" is \", difValue)\n if tag == \"fun2\":\n difValue = y2_dif.subs(x,current_x)\n difValue = round(difValue.evalf(),2)\n print(\"The gradient of function2 at x = \", current_x, \" is \", difValue)\n\n\nt = np.linspace(-10, 10, 200000)\ncurve_1 = fun1(t)\ncurve_2 = fun2(t)\n\n\nintersection_points = find_intersections(t, curve_1, curve_2)\nprint(\"The coordinates of intersection points are \", intersection_points)\n\nfor point in intersection_points:\n x, y = point\n FindGradients(x,\"fun1\")\n FindGradients(x,\"fun2\")\n```\n\n The coordinates of intersection points are [(-0.278, 1.48), (-2.222, 0.51)]\n The gradient of function1 at x = -0.278 is 2.44\n The gradient of function2 at x = -0.278 is -1.44\n The gradient of function1 at x = -2.222 is -1.44\n The gradient of function2 at x = -2.222 is 2.44\n\n\n## Exercise\n\nThe Taylor series for sinh(x) is given by,\n\n$$sinh(x)=x+\\frac{x^3}{3!} + \\frac{x^5}{5!} + \\frac{x^7}{7!}+ ...$$\n\nWrite a function that finds an approximate solution for $sinh(x)$. Try your function for $x=4$ and compute the error between your approximate answer and numpy's `sinh()` function. Report how many terms you need in order to achieve an error \n\n$$\\epsilon < 1e-4$$.\n\n\n```python\nimport numpy as np\nimport sympy as sy\n\nglobal x\nx = sy.symbols('x')\n\n\ndef approximate_sinh(term_Num = 3):\n global x\n # x = sy.symbols('x')\n exp = 0\n n=1\n while n< term_Num+1:\n exp += x**(2*n-1)/sy.factorial(2*n-1)\n n +=1\n\n # print(exp)\n return exp\n\n\nN = range(1, 10)\ni = 1\nwhile i < len(N):\n # print(i)\n sym_exp = approximate_sinh(term_Num = i)\n error = np.abs(np.sinh(4)-sym_exp.subs(x,4))\n if error < 1e-4:\n print(\"The required minimum number of terms to accurately approximating sinh() is \",i)\n print(\"And the current expression is \", sym_exp)\n break\n else:\n i += 1\n```\n\n The required minimum number of terms to accurately approximating sinh() is 8\n And the current expression is x**15/1307674368000 + x**13/6227020800 + x**11/39916800 + x**9/362880 + x**7/5040 + x**5/120 + x**3/6 + x\n\n\n## Exercise \n\nConsider the functions $f(x)=x^2$, $g(x)=sin(x)$, and $h(x)=sinh(x+1)-e^{2x}$. Write lambda functions that represents each of these functions. Then write another function that takes as its arguements two functions and the value of $x$ and returns the composition of the functions (e.g., $f(g(x))=f\\circ g(x)$). Use this to find:\n\n(i) $g\\circ f(5.0)$\n\n(ii) $f \\circ g(2)$\n\n(iii) $h \\circ(g\\circ f)(2\\pi)$\n\n\n```python\n\"\"\" Lambda functions, also referred to as 'Anonymous function'\nis same as a regular python function but can be defined without a name.\nref: https://www.machinelearningplus.com/python/lambda-function/#1.-What-is-Lambda-Function-in-Python?\"\"\"\n\nimport numpy as np\n\n# calculate squares using lambda\nf = lambda x: x*x\ng = lambda x: np.sin(x)\nh = lambda x: np.sinh(x+1)-np.exp(2*x)\n\n\ndef nesting_g_f(f, g, x_value):\n return g(f(x_value))\n\n\nprint(nesting_g_f(f, g, x_value=5))\n```\n\n -0.13235175009777303\n\n\n\n```python\n\"\"\" Lambda functions, also referred to as 'Anonymous function'\nis same as a regular python function but can be defined without a name.\nref: https://www.machinelearningplus.com/python/lambda-function/#1.-What-is-Lambda-Function-in-Python?\"\"\"\n\nimport numpy as np\n\n# calculate squares using lambda\nf = lambda x: x*x\ng = lambda x: np.sin(x)\nh = lambda x: np.sinh(x+1)-np.exp(2*x)\n\n\ndef nesting_f_g(f, g, x_value):\n return f(g(x_value))\n\n\nprint(nesting_f_g(f, g, x_value=2))\n```\n\n 0.826821810431806\n\n\n\n```python\n\"\"\" Lambda functions, also referred to as 'Anonymous function'\nis same as a regular python function but can be defined without a name.\nref: https://www.machinelearningplus.com/python/lambda-function/#1.-What-is-Lambda-Function-in-Python?\"\"\"\n\nimport numpy as np\n\n# calculate squares using lambda\nf = lambda x: x*x\ng = lambda x: np.sin(x)\nh = lambda x: np.sinh(x+1)-np.exp(2*x)\n\n\ndef nesting_h_g_f(f, g, h,x_value):\n return h(g(f(x_value)))\n\nprint(nesting_h_g_f(f, g, h, x_value=2*np.pi))\n```\n\n -3.5295864605536447\n\n\n\n## Exercise\n\nImplement the following matirx addition in Python using Numpy.\n\n\n$$\n \\mathbf{A} + \\mathbf{B} = \\begin{bmatrix} \n1 & 2 \\\\\n3 & 4 \\\\\n\\end{bmatrix}\n+\n\\begin{bmatrix} \n1 & 1 \\\\\n1 & 1 \\\\\n\\end{bmatrix}\n=\n\\begin{bmatrix} \n2 & 3 \\\\\n4 & 5 \\\\\n\\end{bmatrix}\n$$\n\n\n\n\n```python\n\"\"\" Implementing matrix operation with numpy only\nref: https://numpy.org/doc/stable/reference/generated/numpy.matrix.html\n\"\"\"\nimport numpy as np\n\nA = np.matrix('1 2; 3 4')\nB = np.matrix('1 1; 1 1')\nC = A+B\nprint(C)\n```\n\nWrite a double for-loop that iterates over the elements of the numpy arrays and adds the two matrices together.\n\n\n```python\n\"\"\" Implementing matrix operation with numpy only\nref: https://numpy.org/doc/stable/reference/generated/numpy.matrix.html\n\"\"\"\nimport numpy as np\n\nA = np.matrix('1 2; 3 4')\nB = np.matrix('1 1; 1 1')\nlist_C = []\nitem_B = 1 # as all the elements of B equal to ONE\nfor row_A in A:\n print(row_A)\n for item_A in row_A:\n item_C = item_A + item_B\n list_C.append(item_C)\n\nprint(list_C)\nprint(np.array(list_C))\n```\n\n [[1 2]]\n [[3 4]]\n [matrix([[2, 3]]), matrix([[4, 5]])]\n [[[2 3]]\n \n [[4 5]]]\n\n\n\n", "meta": {"hexsha": "2382423bcb03234fbaa762d68475d36155489a2e", "size": 21168, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "homework0.ipynb", "max_stars_repo_name": "ice-bear-git/Astar-with-smoothed-path", "max_stars_repo_head_hexsha": "28931020836284abf130c589c61d9add5fb7019e", "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": "homework0.ipynb", "max_issues_repo_name": "ice-bear-git/Astar-with-smoothed-path", "max_issues_repo_head_hexsha": "28931020836284abf130c589c61d9add5fb7019e", "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": "homework0.ipynb", "max_forks_repo_name": "ice-bear-git/Astar-with-smoothed-path", "max_forks_repo_head_hexsha": "28931020836284abf130c589c61d9add5fb7019e", "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": 28.8392370572, "max_line_length": 342, "alphanum_fraction": 0.4377834467, "converted": true, "num_tokens": 2941, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.931462514578343, "lm_q2_score": 0.9504109791228412, "lm_q1q2_score": 0.8852722004966267}} {"text": "# Introdução à Computação Simbólica com _sympy_\n\n## Motivação\n\n- O valor de $\\pi$ que você usa é finito...\n\n```python\nfrom math import pi\nprint(pi)\n3.141592653589793\n```\n- E se pudéssemos usá-lo com precisão infinita? \n\n- 3.141592653589793 é um valor razoavelmente aceitável\n\n- Exemplo: a equipe de engenharia da NASA explica que, usando este valor para calcular o perímetro de uma circunferência com diâmetro igual a 25 bilhões de milhas, o erro de cálculo é próximo de 1,5 polegada [[NASA]](https://www.jpl.nasa.gov/edu/news/2016/3/16/how-many-decimals-of-pi-do-we-really-need/).\n\n## O que é computação simbólica\n\n> *Computação Simbólica* (CS) é uma subárea de estudo da matemática e da ciência da computação que se preocupa em resolver problemas usando objetos simbólicos representáveis em um computador. \n\n## Para que serve CS? \n\n- Base de vários *sistemas de computação algébrica* (SCAs). \n\n- Álgebra computacional, projetos assistidos por computação (CAD)\n\n- Raciocínio automatizado, gestão do conhecimento, lógica computacional, sistemas formais de verificação etc. \n\n### Como a CS está integrada? \n\n\n
\n \n
\n\n\nFonte: [[RISC/JKU]](https://risc.jku.at/studying-symbolic-computation/)\n\n## Principais SCAs \n\n- Maple\n\n- Mathematica \n\n- MuPad\n\n- Sagemath \n\n- ...\n\n## Por que *sympy*? \n\n> O objetivo principal do *sympy* é ser uma biblioteca de manipulação simbólica para Python. \n\n- 2006 em diante (2019, v. 1.5.1)\n\nPrincipais características:\n\n- é gratuito;\n\n- é baseado inteiramente em Python;\n\n- é leve e independente.\n\n## Objetos numéricos x objetos simbólicos\n\nImportaremos os módulos `math` e `sympy` para ver diferenças\n\n\n```python\nimport math as mt\nimport sympy as sy\nsy.init_printing(pretty_print=True) # melhor impressão de símbolos\n```\n\n\n```python\nmt.pi # numérico\n```\n\n\n```python\nsy.pi # simbólico\n```\n\nVerifiquemos com `type`.\n\n\n```python\ntype(mt.pi)\n```\n\n\n\n\n float\n\n\n\n\n```python\ntype(sy.pi) # é um objeto simbólico\n```\n\n\n\n\n sympy.core.numbers.Pi\n\n\n\nVejamos mais um exemplo:\n\n\n```python\nmt.sqrt(2)\n```\n\n\n```python\nsy.sqrt(2)\n```\n\n\n```python\ntype(mt.sqrt(2))\n```\n\n\n\n\n float\n\n\n\n\n```python\ntype(sy.sqrt(2)) # é um objeto simbólico\n```\n\n\n\n\n sympy.core.power.Pow\n\n\n\n### Função x método \n\nA partir deste ponto, poderemos ver situações como as seguintes:\n\n- `f(x)`: a função `f` é aplicada ao parâmetro `x`; ex. `print('a')`; `type('a')`\n\n- `a.f()`: `f` é um método sem parâmetro do objeto `a`; ex. `z.conjugate()`\n\n- `a.f(x)`: `f` é um método com parâmetro `x` do objeto `a`; ex. `mt.sqrt(2)`\n\nA partir do último exemplo, podemos dizer que um método é, na verdade, uma função que pertence a um objeto.\n\n### Atribuições com símbolos\n\nPodemos atribuir símbolos a variáveis usando a função `symbols`.\n\n\n```python\nx = sy.symbols('x')\ny = sy.symbols('y')\n```\n\n`x` e `y` são símbolos sem valor definido.\n\n\n```python\nx\n```\n\n\n```python\ny\n```\n\nPodemos operar aritmeticamente com símbolos e obter uma expressão simbólica como resultado.\n\n\n```python\nz = sy.symbols('z')\nx*y + z**2/3 + sy.sqrt(x*y - z)\n```\n\n**Exemplo**: escreva o produto notável $(x - y)^2$ como uma expressão simbólica.\n\n\n```python\nx**2 - 2*x*y + y**2\n```\n\nNote que o nome da variável não tem a ver com o nome do símbolo. Poderíamos fazer o seguinte:\n\n\n```python\ny = sy.symbols('x') # y é variável; x é símbolo\ny\n```\n\n### Atribuição por desempacotamento \n\nTambém poderíamos realizar as atribuições anteriores da seguinte forma: \n\n\n```python\nx, y, z = sy.symbols('x y z')\n```\n\n### Alfabeto de símbolos \n\nO *sympy* dispõe de um submódulo chamado `abc` do qual podemos importar símbolos para letras latinas (maiúsculas e minúsculas) e gregas (minúsculas).\n\n\n```python\nfrom sympy.abc import a,b,c,alpha,beta,gamma\n(a + 2*b - 3*c)*(alpha/3 + beta/2 - gamma) # símbolico\n```\n\n\n```python\nfrom sympy.abc import D,G,psi,theta\nD**a * G**b * psi**c * theta**2 # símbolico\n```\n\n**Nota**: algumas letras já são usadas como símbolos especiais, tais como `O`, que indica \"ordem\" e `I`, que é o complexo $i$. Neste caso, cuidado deve ser tomado com nomes de variáveis\n\n\n```python\nsy.I # imaginário simbólico\n```\n\n\n```python\ntype(sy.I)\n```\n\n\n\n\n sympy.core.numbers.ImaginaryUnit\n\n\n\n### Símbolos com nomes genéricos\n\nPara criar símbolos genéricos, temos de usar `symbols` ou `Symbol`.\n\n\n```python\nsem_nocao = sy.symbols('nada')\nsem_nocao\n```\n\n\n```python\nmuito_louco = sy.Symbol('massa')\nmuito_louco\n```\n\n### Variáveis e símbolos\n\n\n```python\nsem_medo = sem_nocao + 2\nsem_medo \n```\n\n\n```python\nsoma = muito_louco + 2\nmuito_louco = 3 # 'muito_louco' aqui não é o simbólico\nsoma\n```\n\n## Substituição\n\nA operação de *substituição* permite que: \n\n1. substituamos variáveis por valores numéricos para avaliar uma expressão ou calcular valores de uma função em um dado ponto.\n2. substituamos uma subexpressão por outra.\n\nPara tanto, procedemos da seguinte forma: \n\n```python\nexpressao.subs(variavel,valor)\n```\n\n\n**Exemplo**: considere o polinômio $P(x) = 2x^3 - 4x -6$. Calcule o valor de $P(-1)$, $P(e/3)$, $P(\\sqrt{3.2})$.\n\n\n```python\nfrom sympy.abc import x \nP = 2*x**3 - 4*x - 6\nP1 = P.subs(x,-1)\nPe3 = P.subs(x,mt.e/3)\nP32 = P.subs(x,mt.sqrt(3.2))\nprint(P1, Pe3, P32)\n```\n\n -4 -8.13655822141297 -1.70674948320040\n\n\n**Exemplo:** sejam $f(x) = 4^x$ e $g(x) = 2x - 1$. Compute o valor da função composta $f(g(x))$ em $x = 3$. \n\n\n```python\nf = 4**x\nfg = f.subs(x,2*x - 1)\n```\n\n\n```python\nfg.subs(x,3)\n```\n\nPoderíamos também fazer isso com um estilo \"Pythônico\":\n\n\n```python\nfg = 4**x.subs(x,2*x - 1).subs(x,3)\nfg\n```\n\n**Exemplo:** se $a(x) = 2^x$, $b(x) = 6^x$ e $c(x) = \\cos(x)$, compute o valor de $a(x)b(c(x))$ em $x = 4$\n\n\n```python\na = 2**x\nb = 6**x\nc = sy.cos(x)\n(a * b.subs(x,c)).subs(x,4)\n```\n\nOu, de modo direto:\n\n\n```python\nvalor = ( 2**x * ( 6**x.subs(x,sy.cos(x))) ).subs(x,4)\nvalor\n```\n\n### Avaliação de expressão em ponto flutuante\n\nNote que a expressão anterior não foi computada em valor numérico. Para obter seu valor numérico, podemos usar o método `evalf`.\n\n\n```python\nvalor.evalf()\n```\n\n#### Precisão arbitrária \n\n`evalf` permite que escolhamos a precisão do cálculo impondo o número de dígitos de precisão. Por exemplo, a última expressão com 20 dígitos de precisão seria:\n\n\n```python\nvalor.evalf(20)\n```\n\nCom 55, seria:\n\n\n```python\nvalor.evalf(55)\n```\n\nE com 90 seria:\n\n\n```python\nvalor.evalf(90)\n```\n\n**Exemplo**: calcule o valor de $e$ com 200 dígitos de precisão.\n\n\n```python\nsy.exp(1).evalf(200)\n```\n\n## Funções predefinidas x funções regulares\n\nApresentaremos 3 grupos de funções que podem ser criadas em Python\n\n- **funções predefinidas** (*built-in functions*): funções já prontas que podemos usar (ex. `print()`, `type()` , `int()`, `float()`\n\n- ** funções regulares**, ou *normais*, *definidas pelo usuário* (do inglês *user-defined functions*, ou simplesmente *UDF*): aquelas que você cria!\n\nPodemos fazer isto de uma maneira usando uma \"palavra-chave\" (*keyword*) chamada `def` da seguinte forma:\n\n```python\ndef f(x):\n (...)\n return y\n```\n- uma UDF **pode ter zero ou mais argumentos**, tantos quantos se queira;\n- uma UDF **pode ou não ter valor de retorno**;\n\nVamos entender as UDFs com exemplos.\n\n**Exemplo:** Suponha que você é um(a) analista de dados do mercado imobiliário e está estudando o impacto do repasse de comissões pagas a corretores mediante vendas de imóveis. Você, então, começa a raciocinar e cria um modelo matemático bastante simples que, antes de tudo, precisa calcular o valor do repasse a partir do preço de venda. \n\nSe $c$ for o percentual de comissão, $V$ o valor da venda do imóvel e $r$ o valor a ser repassado para o corretor, então, a função a ser definida é \n\n$$r(V) = c\\, V,$$ \n\nassumindo que $c$ seja um valor fixo. \n\nDigamos que $c$ corresponda a 1.03% do valor da venda do imóvel. Neste caso podemos criar uma UDF para calcular $r$ para nós da seguinte forma:\n\n\n```python\ndef repasse(V): \n r = 0.0103*V \n return r\n```\n\nPara $V = \\, R\\$ \\, 332.130,00$:\n\n\n```python\nrepasse(332130)\n```\n\nO que é necessário observar:\n\n- `def` seguido pelo *nome* da função \n- argumentos enclausurados por parênteses\n- os dois-pontos (`:`) são obrigatórios\n- *escopo* da função, que deve ser escrito em uma ou mais linhas indentadas (pressione `TAB` para isso, ou use 4 espaços)\n- o valor de retorno, se houver, é posto na última linha do escopo.\n\nPodemos atribuir os valores do argumento e resultado a variáveis:\n\n\n```python\nV = 332130\nrep = repasse(V)\nrep\n```\n\nNomes iguais de variável e função são permissíveis.\n\n\n```python\nrepasse = repasse(V) # 'repasse' à esquerda é uma variável; à direita, função\nprint(repasse)\n```\n\n 3420.939\n\n\nTodavia, isto pode ser confuso e é bom evitar.\n\nO estilo \"Pythônico\" de escrever permite que o valor de retorno não seja explicitamente declarado. No escopo\n\n```python\n...\n r = 0.0103*V \n return r\n```\n a variável `r` não é necessária.\n \nPython é inteligente para permitir o seguinte:\n\n\n```python\ndef repasse(V): \n return 0.0103*V\n\n# note que aqui não indentamos a linha. \n# Logo esta instrução NÃO pertence ao escopo da função.\nrepasse(V)\n```\n\nPodemos criar uma função para diferentes valores de `c` e `V` usando *dois* argumentos:\n\n\n```python\ndef repasse_c(c,V): # esta função tem outro nome\n return c*V\n```\n\n\n```python\nc = 0.0234 # equivaleria a uma taxa de repasse de 2.34%\nV = 197432 # o valor do imóvel agora é R$ 197.432,00\nrepasse_c(c,V)\n```\n\nA ordem dos argumentos importa:\n\n\n```python\nV = 0.0234 # este deveria ser o valor de c\nc = 197432 # este deveria ser o valor de V\nrepasse_c(c,V)\n```\n\nPor que o valor resultante é o mesmo? Porque a operação no escopo da função é uma multiplicação, `c*V`, que é comutativa independentemente do valor das variáveis. Porém, digamos que um segundo modelo tenha uma forma de cálculo distinta para a comissão dada por\n\n$$r_2(V) = c^{3/5} \\, V$$\n\nNeste caso:\n\n\n```python\ndef repasse_2(c,V):\n return c**(3/5)*V\n\nV = 197432\nc = 0.0234\n\nrepasse_2(c,V)\n```\n\nPorém, se trocarmos o valor das variáveis, a função `repasse_2` calculará um valor distinto. Embora exista um produto também comutativo, o expoente `3/4` modifica apenas o valor de `c`.\n\n\n```python\n# variáveis com valores trocados\nc = 197432\nV = 0.0234\n\nrepasse_2(c,V)\n```\n\nA ordem com que escrevemos os argumentos tem importância relativa aos valores que passamos e ao que definimos: \n\n\n```python\n# variáveis com valores corretos\nV = 197432\nc = 0.0234\n\ndef repasse_2_trocada(V,c): # V vem antes de c\n return c**(3/5)*V\n \nrepasse_2_trocada(V,c)\n```\n\nMas,\n\n\n```python\n# os valores das variáveis estão corretos, \n# mas foram passados para a função na ordem errada\nrepasse_2_trocada(c,V) \n```\n\ne \n\n\n```python\n# a ordem dos argumentos está de acordo com a que foi definida\n# mas os valores das variáveis foram trocados\nV = 197432\nc = 0.0234\nrepasse_2_trocada(c,V) \n```\n\n## Modelos matemáticos simbólicos\n\nA partir do que aprendemos, podemos definir modelos matemáticos completamente simbólicos.\n\n\n```python\nfrom sympy.abc import c,V\n\ndef repasse_2_simbolica(c,V):\n return c**(3/5)*V\n```\n\nSe chamarmos esta função, ela será um objeto simbólico.\n\n\n```python\nrepasse_2_simbolica(c,V)\n```\n\nAtribuindo em variável:\n\n\n```python\nrep_simb = repasse_2_simbolica(c,V)\n```\n\n\n```python\ntype(rep_simb) # é um objeto simbólico\n```\n\n\n\n\n sympy.core.mul.Mul\n\n\n\n**Exemplo:** Suponha, agora, que seu modelo matemático de repasse deva considerar não apenas um percentual $c$ pré-estabelecido, mas também um valor de \"bônus\" adicional concedido como prêmio pela venda do imóvel. Considere, então, que o valor deste bônus seja $b$. Diante disso, nosso novo modelo teria uma fórmula como a seguinte: \n\n$$r_3(V) = c\\,V + b$$\n\nSimbolicamente:\n\n\n```python\n# importaremos apenas o símbolo b, \n# uma vez que c e V já foram importados \n# como símbolos anteriormente\nfrom sympy.abc import b \n\ndef r3(V):\n return c*V + b\n\nrep_3 = r3(V)\nrep_3\n```\n\n### Substituindo valores\n\nPodemos usar a função `subs` para atribuir quaisquer valores para o modelo.\n\n**Exemplo:** $c = 0.119$\n\n\n```python\nrep_3.subs(c,0.119) # substituindo para c\n```\n\n**Exemplo:** $c = 0.222$\n\n\n```python\nrep_3.subs(c,0.222) # substituindo para c\n```\n\n**Exemplo:** $c = 0.222$ e $b = 12.0$\n\n\n```python\nrep_3.subs(c,0.222).subs(b,12.0) # substituindo para c, depois para b\n```\n\n### Substituição múltipla\n\nO modo anterior de substituição não é \"Pythônico\". Para substituirmos mais de uma variável de uma vez, devemos usar *pares ordenados* separados por vírgula sequenciados entre colchetes como uma *lista*. Mais tarde, aprenderemos sobre pares ordenados e listas.\n\n**Exemplo:** Modifique o modelo $r_3$ para que $c = 0.043$ e $b = 54.0$\n\n\n```python\n# espaços foram adicionados para dar legibilidade\nrep_3.subs( [ (c,0.043), (b,54.0) ] )\n```\n\n#### Pares ordenados\n\n$$X \\times Y = \\{ (x,y) ; x \\in X \\text{ e } y \\in Y \\}$$\n\nonde $X$ e $Y$ são conjuntos quaisquer e $x$ e $y$ são as *coordenadas*. \n\n- ex. $X = Y = \\mathbb{R}$; $(3,2)$, $(-1,3)$, $(\\pi,2.18)$ etc. \n\n- Este é o caso de $\\mathbb{R} \\times \\mathbb{R} = \\mathbb{R}^2$, que é exatamente o *plano cartesiano*.\n\nA substituição múltipla com `subs` ocorre da seguinte forma; \n\n- a primeira coordenada é o *símbolo*;\n\n- a segunda coordenada é o *valor* que você quer dar para o símbolo.\n\n**Exemplo:** Calcule $r_3(V)$ considerando $c = 0.021$, $b = 34.0$ e $V = 432.000$.\n\n\n```python\n# armazenaremos o valor na variável 'valor'\nvalor = r3(V)\n\n# subsituição \nvalor.subs( [ (c,0.021), (b,54.0) ] )\n```\n\nCom o estilo \"Pythônico\":\n\n\n```python\nvalor = r3(V).subs( [ (c,0.021), (b,54.0) ] ) # \nvalor\n```\n\nPodemos seguir esta regra de pares para substituir todos os valores de um modelo simbólico genérico não necessariamente definido através de uma função. Veja o exemplo aplicado a seguir.\n\n## Exemplo de aplicação: o índice de caminhabilidade\n\nO *índice de caminhabilidade* $W$ para uma vizinhança de casas é uma medida matemática que assume valores no intervalo $[0,1]$. A fórmula é definida por: \n\n$$W(d) = e^{-5 \\left( \\dfrac{d}{M} \\right)^5},$$\n\nonde $d$ é a distância medida entre a vizinhança (0 metro) e um dado ponto de referência, e $M$ é a distância máxima de avaliação considerada a partir da qual a caminhabilidade é assumida como nula.\n\n\n
\n \n
\n\n\n### Interpretação\n\n- quando estamos na vizinhança, $d = 0$, $W = 1$ e a caminhabilidade é considerada ótima.\n\n- à medida que nos afastamos da vizinhança em direção ao local da amenidade, $d$ aumenta e o valor $W$ decai vertiginosamente até atingir o valor limite $M$ a partir do qual $W = 0$ e a caminhabilidade é considerada \"péssima\". \n\n- W é calculado com relação a um ponto de destino definido\n- A distância deve levar em consideração as vias de circulação (ruas, rodovias etc) e não a distância mais curta (raio do perímetro). \n- ex. Para $M = 500 \\, m$ , um bar a 100 metros da vizinhança teria um índice de caminhabilidade maior do que o de uma farmácia localizada a 300 m e muito maior do que o de um shopping localizado a 800 m, ainda que muito famoso. \n\nFonte: *De Nadai, M. and Lepri, B. [[The economic value of neighborhoods: Predicting real estate prices from the urban environment]](https://arxiv.org/pdf/1808.02547.pdf)*. \n\n### Modelo simbólico\n\nPodemos modelar $W$ simbolicamente e calcular seu valor para diferentes valores de $d$ e $M$ usando a substituição múltipla.\n\n\n```python\nfrom sympy.abc import d,M,W \n\nW = sy.exp(-5*(d/M)**5) # função exponencial simbólica\nW\n```\n\n**Exemplo:** A nossa corretora de imóveis gostaria de entender a relação de preços de imóveis para o Condomínio Pedras de Marfim. Considerando $M = 1 km$, calcule:\n \n- o índice de caminhabilidade $W_1$ em relação à farmácia Dose Certa, localizada a 222 m do condomínio.\n\n- o índice de caminhabilidade $W_2$ em relação ao restaurante Sabor da Arte, localizada a 628 m do condomínio.\n\n- o índice de caminhabilidade $W_3$ em relação ao Centro Esportivo Physicalidade, localizada a 998 m do condomínio.\n\n- o índice de caminhabilidade $W_4$ em relação à Padaria Dolce Panini, localizada a 1,5 km do condomínio.\n\n\n```python\n# note que 1 km = 1000 m\nW1 = W.subs([ (d,222), (M,1000) ]) \nW2 = W.subs([ (d,628), (M,1000) ]) \nW3 = W.subs([ (d,998), (M,1000) ]) \nW4 = W.subs([ (d,1500), (M,1000) ])\n```\n\nPerceba, entretanto, que os valores calculados ainda não são numéricos, como esperado.\n\n\n```python\nW1\n```\n\n\n```python\nW2\n```\n\n\n```python\nW3\n```\n\n\n```python\nW4\n```\n\nLembre-se que podemos usar `evalf` para calcular esses valores. Faremos isso considerando 3 casas decimais.\n\n\n```python\n# reatribuindo todos os valores\nW1n = W1.evalf(3)\nW2n = W2.evalf(3)\nW3n = W3.evalf(3)\nW4n = W4.evalf(3)\n\nprint('W1 =', W1n, '; ' \\\n 'W2 =', W2n, '; ' \\\n 'W3 =', W3n, '; ' \\\n 'W4 =', W4n) \n```\n\n W1 = 0.997 ; W2 = 0.614 ; W3 = 0.00708 ; W4 = 3.24e-17\n\n\nComo era de se esperar, os valores decaem de 0.997 a 3.24e-17, que é um valor considerado nulo em termos de aproximação numérica.\n\n#### Quebrando instruções com `\\`\n\nA contra-barra `\\` pode ser usada para quebrar instruções e continuá-las nas próximas linhas, porém não poderá haver nenhum caracter após ela, nem mesmo espaços. Caso contrário, um erro será lançado.\n\n\n```python\nprint('Continuando' \\\n 'na linha abaixo')\n```\n\n Continuandona linha abaixo\n\n\n\n```python\n# neste exemplo, há um caracter de espaço após \\\nprint('Continuando' \\ \n 'na linha abaixo')\n```\n\n### O tipo `bool`\n\nEm Python, temos mais um tipo de dado bastante útil, o `bool`, que é uma redução de \"booleano\". Objetos `bool`, que têm sua raiz na chamada Álgebra de Boole, são baseados nos conceitos *true* (verdadeiro) e *false*, ou *0* e *1* e são estudados em algumas disciplinas, tais como Circuitos Lógicos, Matemática Discreta, Lógica Aplicada, entre outras. \n\nAprenderemos sobre operadores lógicos mais à frente. Por enquanto, cabe mencionar as entidades fundamentais `True` e `False`. \n\n\n```python\nTrue\n```\n\n\n\n\n True\n\n\n\n\n```python\nFalse\n```\n\n\n\n\n False\n\n\n\n\n```python\ntype(True)\n```\n\n\n\n\n bool\n\n\n\n\n```python\ntype(False)\n```\n\n\n\n\n bool\n\n\n\nPodemos realizar testes lógicos para concluir verdades ou falsidades quando temos dúvidas sobre objetos e relações entre eles. Por exemplo, retomemos os seguintes valores:\n\n\n```python\nW1\n```\n\n\n```python\nW2\n```\n\nA princípio, é difícil determinar qual dos dois é o maior. Porém, podemos realizar \"perguntas\" lógicas para o interpretador Python com operadores lógicos. Mostraremos apenas dois exemplos com `>` e `<`.\n\n\n```python\nW1 > W2 # isto quer dizer: \"W1 é maior do que W2?\"\n```\n\nO valor `True` confirma que o valor de `W1` é maior do que `W2`. \n\n\n```python\nW4 < 0\n```\n\n> Note que, de acordo com nosso modelo de caminhabilidade, este valor deveria ser zero. Porém, numericamente, ele é uma aproximação para zero. Embora muito pequeno, não é exatamente zero! Por que isso ocorre? Porque o computador lida com uma matemática inexata e aproximada, mas com precisão satisfatória.\n", "meta": {"hexsha": "0e76251fb5dfe22f1b21dfa7154701db4aa3d6c6", "size": 164119, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "rise/02a-computacao-simbolica-rise.ipynb", "max_stars_repo_name": "gcpeixoto/FMECD", "max_stars_repo_head_hexsha": "9bca72574c6630d1594396fffef31cfb8d58dec2", "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": "rise/02a-computacao-simbolica-rise.ipynb", "max_issues_repo_name": "gcpeixoto/FMECD", "max_issues_repo_head_hexsha": "9bca72574c6630d1594396fffef31cfb8d58dec2", "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": "rise/02a-computacao-simbolica-rise.ipynb", "max_forks_repo_name": "gcpeixoto/FMECD", "max_forks_repo_head_hexsha": "9bca72574c6630d1594396fffef31cfb8d58dec2", "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": 52.0187004754, "max_line_length": 14536, "alphanum_fraction": 0.7781670617, "converted": true, "num_tokens": 6352, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951643678382, "lm_q2_score": 0.9473810475808185, "lm_q1q2_score": 0.8852282696732536}} {"text": "## Numeric vs symbolic computing\n\n\n```python\n1.01 - 1\n```\n\n\n\n\n 0.010000000000000009\n\n\n\nFloating point numbers have limited accuracy (53 bits for double precision IEEE 754)\n\n\n```python\nimport math\nmath.log10(2**53)\n```\n\n\n\n\n 15.954589770191003\n\n\n\nThat is, about 15 decimal places. Additionally, decimal numbers don't have exact representation in binary in general. In some cases, it may lead to accumulation of errors (numerically unstable algorithms)\n\n\n```python\nx = 1\nfor i in range(10):\n x = (1.01-x)*100\n print(x)\n```\n\n 1.0000000000000009\n 0.9999999999999121\n 1.0000000000087939\n 0.9999999991206154\n 1.0000000879384574\n 0.9999912061542604\n 1.0008793845739605\n 0.912061542603948\n 9.7938457396052\n -878.38457396052\n\n\n## SymPy as a calculator\n\nSymbolic computing uses exact mathematical rules. Numbers in sympy are represented by objects of type Integer, Rational, and Float and they have overloaded mathematical operators\n\n\n```python\nfrom sympy import *\n```\n\n\n```python\nRational(101, 100)-Integer(1)\n```\n\n\n\n\n 1/100\n\n\n\n\n```python\nsympify(\"101/100-1\")\n```\n\n\n\n\n 1/100\n\n\n\n\n```python\nnsimplify(\"1.01\") - 1\n```\n\n\n\n\n 1/100\n\n\n\n\n```python\nx = Integer(1)\nfor i in range(10):\n x = (Rational(101, 100)-x)*100\n print(x)\n```\n\n 1\n 1\n 1\n 1\n 1\n 1\n 1\n 1\n 1\n 1\n\n\nSympy has some predefined mathematical constants\n\n\n```python\nE*I - pi\n```\n\n\n\n\n -pi + E*I\n\n\n\nand many functions...\n\n\n```python\ncos(0)\n```\n\n\n\n\n 1\n\n\n\n\n```python\nsin(pi/3)\n```\n\n\n\n\n sqrt(3)/2\n\n\n\nand you can evaluate the expressions numerically with function N() or method .evalf() with arbirtary precision (based on mpmath)\n\n\n```python\nN(pi+E*I, 30)\n```\n\n\n\n\n 3.14159265358979323846264338328 + 2.71828182845904523536028747135*I\n\n\n\n\n```python\nsqrt(2).evalf(1000)\n```\n\n\n\n\n 1.414213562373095048801688724209698078569671875376948073176679737990732478462107038850387534327641572735013846230912297024924836055850737212644121497099935831413222665927505592755799950501152782060571470109559971605970274534596862014728517418640889198609552329230484308714321450839762603627995251407989687253396546331808829640620615258352395054745750287759961729835575220337531857011354374603408498847160386899970699004815030544027790316454247823068492936918621580578463111596668713013015618568987237235288509264861249497715421833420428568606014682472077143585487415565706967765372022648544701585880162075847492265722600208558446652145839889394437092659180031138824646815708263010059485870400318648034219489727829064104507263688131373985525611732204024509122770022694112757362728049573810896750401836986836845072579936472906076299694138047565482372899718032680247442062926912485905218100445984215059112024944134172853147810580360337107730918286931471017111168391658172688941975871658215212822951848847\n\n\n\n## Symbolic computing\nSymbols are python objects\n\n\n```python\nx, y, z = symbols(\"x, y, z\")\nalpha, beta, delta = symbols('alpha, beta, delta')\n```\n\nsymbolic expressions are created using standard python syntax\n\n\n```python\nexpr = x**y + sqrt(alpha)/2\nexpr\n```\n\n\n\n\n sqrt(alpha)/2 + x**y\n\n\n\nSymPy can print expressions in various forms, including $\\LaTeX$, unicode pretty printing, and others. The pretty printing is enabled with `init_printing()`\n\n\n```python\ninit_printing()\n```\n\n\n```python\nexpr\n```\n\nLists of symbols can be created with the following notation\n\n\n```python\nsymbols(\"x0:10\")\n```\n\n### Basic manipulation with the expressions\n#### Polynomials and rational functions\n\n\n```python\n(x+y)**10\n```\n\nPolynomials can be expanded\n\n\n```python\nexpand(_)\n```\n\nand, more importantly, factorized\n\n\n```python\nfactor(_)\n```\n\n\n```python\n_.subs(x+y, z)\n```\n\nWe can collect the terms with the same power of a given variable\n\n\n```python\ncollect(y*x**2 + 3*x**2 - x*y + x - 1, x)\n```\n\nCancel rational functions\n\n\n```python\ncancel((x**2 + 2*x + 1)/(x**2 - 1))\n```\n\nor decompose them into partial fractions\n\n\n```python\napart((x**3 + 4*x - 1)/(x**2 - 1))\n```\n\n#### Trigonometric functions\n\n\n```python\nsin(x+y)\n```\n\n\n```python\nexpand(_, trig=True)\n```\n\n\n```python\ntrigsimp(_)\n```\n\n\n```python\ntrigsimp(sin(x)**2 + cos(x)**2)\n```\n\n#### Exponentiation\n\n\n```python\nx**alpha * y**alpha\n```\n\n\n```python\npowsimp(_)\n```\n\nNote that symbols in SymPy are complex by default. However, $x^\\alpha y^\\alpha$ does not equal $(xy)^\\alpha$ in general. For example $\\sqrt{-1}\\sqrt{-1} \\neq \\sqrt{-1\\cdot-1}$.\n\nIt is valid for $x, y \\ge 0$ and $\\alpha\\in\\mathbb R$ and we have to define the symbols as such.\n\nSimilarly $(x^a)^b = x^{ab}$ holds only for $b\\in\\mathbb Z$\n\n\n```python\nx_pos, y_pos = symbols(\"x_pos, y_pos\", positive=True)\nalpha_R = symbols(\"alpha_R\", real=True)\nbeta_Z = symbols(\"beta_Z\", integer=True)\n```\n\n\n```python\npowsimp(x_pos**alpha_R * y_pos**alpha_R)\n```\n\n\n```python\n(expand_power_base(_))\n```\n\n\n```python\n(z**delta)**beta_Z\n```\n\n\n```python\nlog(x_pos**alpha_R * y_pos)\n```\n\n\n```python\nexpand_log(_)\n```\n\n\n```python\nlogcombine(_)\n```\n\nThe need for assumptions can be avoided using `force=True` (not recommended :)\n\n\n```python\nexpand_log(log(x**alpha * y))\n```\n\n\n```python\nexpand_log(log(x**alpha * y), force=True)\n```\n\n#### Rewriting functions\n\n\n```python\ntan(x).rewrite(sin)\n```\n\nNote that there are many special functions defined in SymPy...\n\n\n```python\nfactorial(x).rewrite(gamma)\n```\n\n\n```python\nk, m, n = symbols('k, m, n')\nbinomial(k, n).rewrite(factorial)\n```\n\n\n```python\nbinomial(k, k-2)\n```\n\n\n```python\ncombsimp(_)\n```\n\n#### Equation solving\nEquations are defined using `Eq`. Note that `=` is assignment and `==` tests for exact identity of two expressions\n\n\n```python\nEq(x**2, 1)\n```\n\n`solveset` attempts to find all solutions of the given equation. If it fails, you may try to use `solve`...\n\n\n```python\nsolveset(_, x)\n```\n\n\n```python\nsolveset(sin(x), x)\n```\n\n\n```python\nsolveset(x**2+1, x)\n```\n\n\n```python\nsolveset(x**2+1, x, domain=S.Reals)\n```\n\n\n```python\nsolveset(exp(x)-1, x)\n```\n\n\n```python\nsolveset(exp(x) > 1, x, domain=S.Reals)\n```\n\n\n```python\nlinsolve([x + y + z - 1, x + y + 2*z - 3 ], (x, y, z))\n```\n\n\n```python\nnonlinsolve([x**2 + 1, y**2 + 1], [x, y])\n```\n\n## Sympy internals\nExpressions are represented as trees. This can be seen by printing with srepr\n\n\n```python\nx*y\n```\n\n\n```python\nsrepr(x*y)\n```\n\n\n\n\n \"Mul(Symbol('x'), Symbol('y'))\"\n\n\n\n\n```python\nfrom IPython.display import Image\ndef show_tree(expr):\n with open(\"xy.dot\", \"w\") as f:\n f.write(dotprint(expr))\n !dot xy.dot -Tpng > xy.png\n return Image(filename='xy.png') \n```\n\n\n```python\nshow_tree(x*y)\n```\n\n\n```python\nexpr = sin(x)/y+1-x\nshow_tree(expr)\n```\n\n\n```python\nexpr.func\n```\n\n\n\n\n sympy.core.add.Add\n\n\n\n\n```python\nexpr.args\n```\n\n\n```python\nexpr.args[1].func\n```\n\n\n\n\n sympy.core.mul.Mul\n\n\n\n\n```python\nexpr.args[1].args\n```\n", "meta": {"hexsha": "34a7ed36f345365af0a7d0e96bdc1c2c4c2762b9", "size": 123797, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/01 Basics.ipynb", "max_stars_repo_name": "rouckas/sympy-slides", "max_stars_repo_head_hexsha": "c2777f0eddedd19c4bf094d40489f49c1ef8ad28", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2018-10-22T19:52:48.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-01T16:59:45.000Z", "max_issues_repo_path": "notebooks/01 Basics.ipynb", "max_issues_repo_name": "rouckas/sympy-slides", "max_issues_repo_head_hexsha": "c2777f0eddedd19c4bf094d40489f49c1ef8ad28", "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": "notebooks/01 Basics.ipynb", "max_forks_repo_name": "rouckas/sympy-slides", "max_forks_repo_head_hexsha": "c2777f0eddedd19c4bf094d40489f49c1ef8ad28", "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": 74.7566425121, "max_line_length": 23984, "alphanum_fraction": 0.8311348417, "converted": true, "num_tokens": 2135, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566341999997376, "lm_q2_score": 0.9252299612154571, "lm_q1q2_score": 0.8851066237631371}} {"text": "# Lecture Mathematical Foundations\nHoracio Gomez-Acevedo\n\nBMIG 6120\n\nUAMS\n\n\n# Basic Concepts of Linear Algebra\n\nMathematical quantities are normally associated with sets of numbers. For instance points on the plane have two coordinates $x$ and $y$, whereas on the space they will have three coordinates $x$,$y$ and $z$. We further extend this idea to say that $(x_1,\\ldots,x_n)$ is a point (or vector) in the $n$-dimensional space (normally denoted as $\\mathbb{R}^n)$. We will denote vectors by bold face symbols, for instance $\\pmb{x}=(x_1,\\ldots,x_n)$ \n\nSome basic operations on vectors are:\n\n\\begin{align*}\n\\pmb{x}+\\pmb{y}&=\n(x_1,x_2,\\ldots,x_n)+(y_1,y_2,\\ldots,y_n)=(x_1+y_1,x_2+y_2,\\ldots,x_n+y_n)\\\\\n\\pmb{x}-\\pmb{y}&=\n(x_1,x_2,\\ldots,x_n)-(y_1,y_2,\\ldots,y_n)=(x_1-y_1,x_2-y_2,\\ldots,x_n-y_n)\\\\\n\\end{align*}\nThe **dot product** of two vectors $\\pmb{x}$ and $\\pmb{y}$ is defined as\n\n\\begin{align*}\n\\pmb{x}\\cdot\\pmb{y}&=(x_1,x_2,\\ldots,x_n)\\cdot(y_1,y_2,\\ldots,y_n)=x_1\\cdot y_1+ x_2\\cdot y_2,\\ldots+x_n\\cdot y_n\\\\\n&=\\sum_{i=1}^n x_iy_i\\\\\n\\end{align*}\nThe length of an $n$-vector is given by\n\\begin{equation*}\n\\| \\pmb{x} \\| = \\sqrt{ \\pmb{x} \\cdot \\pmb{x}} = \\sqrt{x_1^2+x_2^2+\\ldots+x_n^2}= \\sqrt{\\sum_{i=1}^n x_i^2}\n\\end{equation*}\n\n\n\n## Matrices\n\nA matrix is a collection of numbers, arranged in a particular way, for instance\n\\begin{equation*}\n\\left( \n \\matrix{1 & 2& 3\\\\ 4&5&6}\n \\right)\n\\end{equation*}\n\nWe can think of a matrix as a square section of a table. \nA matrix of size $n\\times p$ is a table with $n$ rows and $p$ columns like\n\\begin{equation*}\n\\left( \n\\matrix{ x_{1,1} & x_{1,2} & \\ldots & x_{1,p} \\\\\nx_{2,1} & x_{2,2} & \\ldots & x_{2,p} \\\\\n\\vdots & \\vdots & \\ddots & \\vdots \\\\\nx_{n,1} & x_{n,2} & \\cdots & x_{n,p}\n}\n\\right)\n\\end{equation*}\n\nWe will denote matrices with capital bold variables such as $\\pmb{X}$. \n\nMatrices can be represented as either column or row vectors. \n\n\n## Matrices operations\n\nThe matrices have similar operations as vectors\n\n\\begin{equation*}\n\\pmb{X}+\\pmb{Y}= \\left( \n\\matrix{ x_{1,1} & x_{1,2} & \\ldots & x_{1,p} \\\\\nx_{2,1} & x_{2,2} & \\ldots & x_{2,p} \\\\\n\\vdots & \\vdots & \\ddots & \\vdots \\\\\nx_{n,1} & x_{n,2} & \\cdots & x_{n,p}\n}\n\\right) +\n\\left( \n\\matrix{ y_{1,1} & y_{1,2} & \\ldots & y_{1,p} \\\\\ny_{2,1} & y_{2,2} & \\ldots & y_{2,p} \\\\\n\\vdots & \\vdots & \\ddots & \\vdots \\\\\ny_{n,1} & y_{n,2} & \\cdots & y_{n,p}\n}\n\\right)= \n\\left( \n\\matrix{ x_{1,1}+y_{1,1} & x_{1,2}+ y_{1,2} & \\ldots & x_{1,p}+y_{1,p} \\\\\nx_{2,1}+y_{2,1} & x_{2,2}+y_{2,2} & \\ldots & x_{2,p} +y_{2,p}\\\\\n\\vdots & \\vdots & \\ddots & \\vdots \\\\\nx_{n,1}+y_{n,1} & x_{n,2}+y_{n,2} & \\cdots & x_{n,p}+y_{n,p}\n}\n\\right)\n\\end{equation*}\n\n\\begin{equation*}\n\\pmb{X}-\\pmb{Y}= \\left( \n\\matrix{ x_{1,1} & x_{1,2} & \\ldots & x_{1,p} \\\\\nx_{2,1} & x_{2,2} & \\ldots & x_{2,p} \\\\\n\\vdots & \\vdots & \\ddots & \\vdots \\\\\nx_{n,1} & x_{n,2} & \\cdots & x_{n,p}\n}\n\\right) -\n\\left( \n\\matrix{ y_{1,1} & y_{1,2} & \\ldots & y_{1,p} \\\\\ny_{2,1} & y_{2,2} & \\ldots & y_{2,p} \\\\\n\\vdots & \\vdots & \\ddots & \\vdots \\\\\ny_{n,1} & y_{n,2} & \\cdots & y_{n,p}\n}\n\\right)= \n\\left( \n\\matrix{ x_{1,1}-y_{1,1} & x_{1,2}- y_{1,2} & \\ldots & x_{1,p}-y_{1,p} \\\\\nx_{2,1}-y_{2,1} & x_{2,2}-y_{2,2} & \\ldots & x_{2,p} -y_{2,p}\\\\\n\\vdots & \\vdots & \\ddots & \\vdots \\\\\nx_{n,1}-y_{n,1} & x_{n,2}-y_{n,2} & \\cdots & x_{n,p}-y_{n,p}\n}\n\\right)\n\\end{equation*}\n\nFor any real number $\\alpha \\in \\mathbb{R}$\n\\begin{equation*}\n\\alpha \\pmb{X}= \\alpha\\left( \n\\matrix{ x_{1,1} & x_{1,2} & \\ldots & x_{1,p} \\\\\nx_{2,1} & x_{2,2} & \\ldots & x_{2,p} \\\\\n\\vdots & \\vdots & \\ddots & \\vdots \\\\\nx_{n,1} & x_{n,2} & \\cdots & x_{n,p}\n}\n\\right)=\n\\left( \n\\matrix{\\alpha x_{1,1} & \\alpha x_{1,2} & \\ldots & \\alpha x_{1,p} \\\\\n\\alpha x_{2,1} & \\alpha x_{2,2} & \\ldots & \\alpha x_{2,p} \\\\\n\\vdots & \\vdots & \\ddots & \\vdots \\\\\n\\alpha x_{n,1} & \\alpha x_{n,2} & \\cdots & \\alpha x_{n,p}\n}\n\\right)\n\\end{equation*}\n\n## Transpose of a Matrix\n\nThe transpose of a matrix is obtained by swapping rows and columns. \n\\begin{equation*}\n\\pmb{X}= \\left( \n\\matrix{ x_{1,1} & x_{1,2} & \\ldots & x_{1,p} \\\\\nx_{2,1} & x_{2,2} & \\ldots & x_{2,p} \\\\\n\\vdots & \\vdots & \\ddots & \\vdots \\\\\nx_{n,1} & x_{n,2} & \\cdots & x_{n,p}\n}\n\\right) \n\\Rightarrow\n\\;\\pmb{X}^t=\n \\left( \n\\matrix{ x_{1,1} & x_{2,1} & \\ldots & x_{n,1} \\\\\nx_{1,2} & x_{2,2} & \\ldots & x_{n,2} \\\\\n\\vdots & \\vdots & \\ddots & \\vdots \\\\\nx_{1,p} & x_{2,p} & \\cdots & x_{n,p}\n}\n\\right)\n\\end{equation*}\n\n## Matrix multiplication\n\nThis operation is a bit different than the other operations. \n\nLet $\\pmb{X}$ be an $n\\times p$ matrix represented as an arrange of row vectors, and $\\pmb{Y}$ be a $p \\times k$ matrix represented as an arrange of column vectors\n\n\\begin{equation*}\n\\pmb{X}= \n\\left( \n\\matrix{ x_{1,1} & x_{1,2} & \\ldots & x_{1,p} \\\\\nx_{2,1} & x_{2,2} & \\ldots & x_{2,p} \\\\\n\\vdots & \\vdots & \\ddots & \\vdots \\\\\nx_{n,1} & x_{n,2} & \\cdots & x_{n,p}\n}\n\\right)=\n\\left( \n\\matrix{ \\pmb{x}_1 \\\\\n\\pmb{x}_2 \\\\\n\\vdots \\\\\n\\pmb{x}_n\n}\n\\right) \\; \\textrm{and}\\;\n\\pmb{Y} = \n\\left( \n\\matrix{ y_{1,1} & y_{1,2} & \\ldots & y_{1,k} \\\\\ny_{2,1} & y_{2,2} & \\ldots & y_{2,k} \\\\\n\\vdots & \\vdots & \\ddots & \\vdots \\\\\ny_{p,1} & y_{n,2} & \\cdots & y_{n,k}\n}\n\\right)=\n\\left(\n\\matrix{\\pmb{y}_1 & \\pmb{y}_2 & \\ldots & \\pmb{y}_k \\\\}\n\\right)\n\\end{equation*}\n\nThe multiplication of $\\pmb{X}$ and $\\pmb{Y}$ \n\n\\begin{equation*}\n\\pmb{X}\\cdot\\pmb{Y}= \\left( \n\\matrix{ \\pmb{x}_1\\cdot\\pmb{y}_1 & \\pmb{x}_1\\cdot \\pmb{y}_2 & \\ldots & \\pmb{x}_1 \\cdot \\pmb{y}_k \\\\\n\\pmb{x}_2\\cdot\\pmb{y}_1 & \\pmb{x}_2\\cdot \\pmb{y}_2 & \\ldots & \\pmb{x}_2 \\cdot \\pmb{y}_k \\\\\n\\vdots & \\vdots & \\ddots & \\vdots \\\\\n\\pmb{x}_n\\cdot\\pmb{y}_1 & \\pmb{x}_n\\cdot \\pmb{y}_2 & \\ldots & \\pmb{x}_n \\cdot \\pmb{y}_k \\\\\n}\n\\right) \n\\end{equation*}\n\n\n> Check the size of the matrix under multiplication! Multiplying a matrix of size $n\\times k$ by a matrix of size $k \\times p$ gives you a matrix of size $n \\times p$ (middle number $k$ must coincide but cancells out)\n\n## Example\n\nConsider the following matrices\n\n\\begin{equation*}\n\\pmb{A}=\\left( \\matrix{2 & -5 \\\\ 1 & 2} \\right) \\; \\textrm{and } \\; \\pmb{B}= \\left( \\matrix{3 & 2 \\\\ -1 & 4} \\right) \n\\end{equation*}\n\n\\begin{equation*}\n\\pmb{A}\\cdot \\pmb{B}= \\left( \\matrix{ \n2*3 + (-5)*(-1) & 2*2+(-5)*4 \\\\\n1*3 + 2*(-1) & 1*2+2*4 }\n\\right)= \\left( \\matrix{11 & -16 \\\\ 1 & 10 } \\right)\n\\end{equation*}\n\n\n## Systems of Equations in Matrix Form\n\nSuppose you want to solve the following system of equations\n\n\\begin{align}\n2x -5y &= 3\\\\\nx + 2y &= 2\n\\end{align}\n\nAt this point we write these equations as\n\n\\begin{equation}\n\\left(\n\\matrix{2 & -5\\\\ 1 & 2}\n\\right) \\cdot \\left(\n\\matrix{x \\\\ y} \n\\right)\n= \\left(\n\\matrix{3 \\\\ 2}\n\\right)\n\\end{equation}\n\nIf we call $A=\\left(\n\\matrix{2 & -5\\\\ 1 & 2}\n\\right) $, $\\pmb{x}= \\left( \\matrix{x \\\\y} \\right) $ and $\\pmb{b}=\\left( \\matrix{3\\\\2}\\right)$, we can rewrite our system as\n\n\\begin{equation*}\n\\pmb{A}\\cdot \\pmb{x}=\\pmb{b}\n\\end{equation*}\n\nFollowing our basic algebra knowledge, we would like to solve this equation as\n\n\\begin{equation*}\n\\pmb{x}= \\pmb{A}^{-1} \\cdot \\pmb{b}\n\\end{equation*}\n\nBut, how do we find $\\pmb{A}^{-1}$?\n\n\n\n```python\nimport numpy as np\nfrom numpy.linalg import inv\na = np.array([[2., -5.], [1., 2.]])\nainv = inv(a)\nprint(ainv)\nx=np.dot(ainv,b=np.array([3,2]))\n```\n\n [[ 0.22222222 0.55555556]\n [-0.11111111 0.22222222]]\n\n\nThus,\n\\begin{equation*}\n\\pmb{x}= \\left(\n\\matrix{\n0.222 & 0.556 \\\\\n-0.111 & 0.222 } \\right)\n\\cdot \\left( \n\\matrix{ 3 \\\\ 2} \\right)= \n\\left(\\matrix{1.778\\\\ 0.111} \\right)\n\\end{equation*}\n\nAnd we can verify that $\\pmb{A}\\cdot \\pmb{x}= \\pmb{b}$\n\n\n```python\nprint(np.dot(a,x))\n```\n\n [3. 2.]\n\n\n> Note. Not all the systems of equations have a solution and some have infinite number of solutions.\n\nFor instance, \n\\begin{align*}\nx_1-x_2 +x_3 -x_4 &=1\\\\\nx_1-x_2-x_3+x_4 &=0\\\\\nx_1-x_2-2x_3+2x_4&= -\\frac{1}{2}\n\\end{align*}\nor in matrix form\n\\begin{equation*}\n\\left(\n\\begin{matrix}\n1 & -1 & 1 & -1 \\\\\n1 & -1 & -1 & 1 \\\\\n1 & -1 & -2 & 2 \n\\end{matrix} \\right)\n\\cdot \\pmb{x}= \\left( \n\\begin{matrix}\n1 \\\\\n0\\\\\n-\\frac{1}{2}\n\\end{matrix}\n\\right)\n\\end{equation*}\n\nIn this case any expression that satisfies $x_2=x_1 -1/2$ and $x_3=x_4+1/2$ for arbitrary values of $x_1$ and $x_4$ will satisfy the system.\nSo, what is the problem?\n\nFirst, there are more $x$'s than equations. But not only that, we have to make sure that the equations that we add make rows *linearly dependent*. This means that they cannot be additions(substractions) or constant multiplication of the previous rows. \n\nThere is a simple way to find out wheter the system has a solution and if so this one would be unique. We apply the **determinant** function. If it is different from zero, we are Ok.\n\nLet's check quickly the what is the definition of the **determinant** of a matrix $A$ of type $n\\times n$.\n\nCase $n=2$\n\n\\begin{equation*}\n\\mathrm{det}\\left[ \n\\begin{matrix}\na_{11} & a_{12} \\\\\na_{21} & a_{22} \n\\end{matrix}\n\\right]= (a_{11}* a_{22}) - (a_{21}* a_{12})\n\\end{equation*}\n\nCase n=3\n\n\\begin{equation*}\n\\mathrm{det}\n\\begin{pmatrix}\na_{11} & a_{12} & a_{13} \\\\\na_{21} & a_{22} & a_{23} \\\\\na_{31} & a_{32} & a_{33}\n\\end{pmatrix}\n= a_{11} \\cdot \\mathrm{det} \n\\begin{pmatrix}\na_{22} & a_{23} \\\\\na_{32} & a_{33}\n\\end{pmatrix} \n- a_{12}\\cdot \\mathrm{det}\n\\begin{pmatrix}\na_{21} & a_{13} \\\\\na_{31} & a_{33} \n\\end{pmatrix} \n+a_{13} \\cdot \\mathrm{det}\n\\begin{pmatrix}\na_{21} & a_{22} \\\\\na_{31} & a_{32} \n\\end{pmatrix}\n\\end{equation*}\n\nMatrices of type $n\\times n$ that have determinant different from zero are called **non-singular**. These matrices will have an **inverse matrix** that satisfies\n\n\\begin{equation*}\nA \\cdot A^{-1} = A^{-1} \\cdot A = I_n,\n\\end{equation*}\nwhere $I_n$ is the identity matrix (a matrix of type $n\\times n$ that has 1's in the diagonal and zeros elsewhere)\n\n\n### Example\n\nLet $A$ be the $3\\times3$ matrix\n\n\\begin{equation}\nA=\n\\begin{pmatrix}\n4 & 3 & 2 \\\\\n3& 5 & 2 \\\\\n2 & 2 &1 \\\\\n\\end{pmatrix}\n\\end{equation}\n\nWhat is the inverse matrix $A^{-1}$?\n\n\n\n```python\nimport numpy as np\nA=np.array([[4.,3.,2.],[3.,5.,2.],[2.,2.,1.]])\nfrom numpy.linalg import inv\n\ninv(A)\n```\n\n\n\n\n array([[-1.00000000e+00, -1.00000000e+00, 4.00000000e+00],\n [-1.00000000e+00, -3.22973971e-16, 2.00000000e+00],\n [ 4.00000000e+00, 2.00000000e+00, -1.10000000e+01]])\n\n\n\n## Matrices as transformations\n\nAmong the different functions say from $f \\colon \\mathbb{R}^2\\to \\mathbb{R}^2$, the so-called **linear transformation** play a very important role in mathematics. Such transformations can be represented by a matrix (defined by the transformation itself). Let's suppose we have a vector $\\pmb{x}=(x_1,x_2)^t$ (note that we write $\\pmb{x}$ as a column vector) and a matrix $\\pmb{A}$ (of type $2\\times2$ in this case), so we can define a linear transformation \n\\begin{equation}\nT_A(\\pmb{x}) = \\pmb{A} \\cdot \\pmb{x}\n\\end{equation}\nWhat does the transformation $T_A$ do to any vector $\\pmb{x}$?\n\nHere are some possibilitites\n\n+ It keeps the same vector (trivial transformation)\n\n\\begin{equation}\n\\pmb{I}_2 \\cdot \\pmb{x}= \\pmb{x}\n\\end{equation}\n\n+ Expands the vector in a given direction\n$\\pmb{x}=\\pmatrix{x_1\\\\x_2}$\n\\begin{equation}\n\\begin{pmatrix}\n2 & 0\\\\\n0 & 1\n\\end{pmatrix} \\cdot \\pmb{x} = (2x_1,x_2)^t= \\pmatrix{2x_1\\\\x_2}\n\\end{equation}\n\n+ Rotates the vector $180^\\circ$\n\n\\begin{equation}\n\\begin{pmatrix}\n-1 & 0\\\\\n0 & -1\n\\end{pmatrix} \\cdot \\pmb{x} =\\pmatrix{-x_1\\\\ -x_2}\n\\end{equation}\n\n+ Rotates the vector with a specific angle $\\theta$\n\n\\begin{equation}\n\\begin{pmatrix}\n\\cos(\\theta) & \\sin (\\theta)\\\\\n-\\sin (\\theta) & \\cos(\\theta)\n\\end{pmatrix} \\cdot \\pmb{x} =\\pmatrix{x_1 \\cos(\\theta) +x_2 \\sin(\\theta)\\\\ -x_1\\sin(\\theta)+ x_2 \\cos(\\theta)\n}\n\\end{equation}\n\n+ It can project the vector to each coordinate axis\n\n\\begin{equation}\n\\begin{pmatrix}\n0 &0 \\\\\n0 & 1 \\\\\n\\end{pmatrix} \\cdot \\pmb{x}= \\pmatrix{0 \\\\ x_2}\n\\end{equation}\n\n## Rigid transformations\n\nFrom basic algebra we know that the equation $y=mx +b$ represents a line in the plane with slope $m$ and $y$-intercept $b$. However, a similar expression such as\n\\begin{equation}\n\\pmb{A} \\cdot \\pmb{x} + \\pmb{b}\n\\end{equation}\ndoes not represent a linear transformation! This transformation is a translation of every vector by the vector $\\pmb{b}$\n\nFor instance, the rigid-transformation $T$ defined as\n\\begin{equation}\nT(\\pmb{x})= \\pmatrix{\n3 & 0 \\\\\n2 & 1 } \\cdot \\pmb{x}+ \\pmatrix{1\\\\1}\n\\end{equation}\n\nFor $e_1=(1,0)$ and $e_2=(0,1)$\n\n\n\n## Composition of transformations\n\nIn mathematics, a composition of functions refers to the operation of putting functions in tandem. That is, applying a function to a point (vector) and taking the output to put it as input of another function and so on. \n\nLet $T_A \\colon \\mathbb{R}^m\\to \\mathbb{R}^k$ and $T_B\\colon \\mathbb{R}^n \\to \\mathbb{R}^m$ two linear transformations, then the composition $T_A$ with $T_B$ is the (linear) transformation $T_{A B}\\colon \\mathbb{R}^n \\to \\mathbb{R}^k$ defined as\n\n\\begin{equation}\nT_{A B} ( \\pmb{x})= T_A\\circ T_B(\\pmb{x}))= T_A(T_B(\\pmb{x}))= \\pmb{A} \\cdot \\pmb{B} \\cdot \\pmb{x}\n\\end{equation}\n\n\n\n# Geometric properties\n\nThe **dot** product on arrays (or vectors) have a nice geometric interpretation\n\n\\begin{equation*}\n\\pmb{x} \\cdot \\pmb{y} = \\| \\pmb{x}\\| \\| \\pmb{y} \\| \\cos( \\theta)\n\\end{equation*}\nwhere $\\theta$ is the angle between the two vectors. This property is very handy when we want to find **perpendicular vectors**, in which case $\\theta =90^\\circ$ and the dot product will be zero!)\n\n\nThere is another operation between vectors in higher dimensions, the so-called **cross-product**. Whereas the previous product results in a number, the cross-product represents another vector.\n\n\\begin{equation*}\n\\pmb{x} \\times \\pmb{y}= \\textrm{det } \n\\pmatrix{ \\pmb{i} & \\pmb{j} & \\pmb{k} \\\\\nx_1 & x_2 & x_3\\\\\ny_1 & y_2 & y_3 }\n= \\pmb{i}(x_2y_3 - y_2 x_3)+ \\pmb{j}(x_3y_1-x_1 y_3)+ \\pmb{k}(x_1 y_2 -x_2y_1)\n\\end{equation*}\nwhere $\\pmb{i}= (1,0,0)$, $\\pmb{j}=(0,1,0)$ and $\\pmb{k}=(0,0,1)$.\n\n\n```python\nimport numpy as np\n\nx = [1, 2, 0]\ny = [4, 5, 6]\nnp.cross(x, y)\n```\n\n\n\n\n array([12, -6, -3])\n\n\n\n# Derivatives and Gradients\n\n\n## Case $n=1$\nWe will begin with elementary calculus. Let $f\\colon \\mathbb{R} \\to \\mathbb{R}$ be a smooth (differentiable) function at the point $x_0$. \n\nWhat does the derivative of $f$ at $x_0$ represents? In theory, it represents the slope of the tangent line of $f(x)$ at $x_0$ (for points *close* to $x_0$). \n\n\\begin{equation}\nf'(x_0) \\approx \\frac{f(x)-f(x_0)}{x-x_0} \n\\end{equation}\n\n\n\nWe can isolate $f(x)$ from the previous expressin and conclude that the derivate provide a linear approximation of a function a the given point for points *close* to $x_0$. More specifically \n\n\\begin{equation}\nf(x) \\approx f(x_0) + f'(x_0) (x-x_0)\n\\end{equation}\nfor points close to $x_0$. \n\n\n\n## Case $n\\ge2$\n\nLet us first recall the concept of **level surfaces** of a function. If $f\\colon \\mathbb{R}^2 \\to \\mathbb{R}$, we can represent the graph of $f$ in a 3-d plot as a surface. If the function reaches a level $c$ (i.e., there is $\\pmb{x}_0$ such that $f(\\pmb{x}_0)=c$), then the set of all points in the plane that have the same value $c$ are called the level surface at level $c$.\n\n\n\nAnother example is the temperature map\n\n\n\nLet's suppose now that $f\\colon \\mathbb{R}^n \\to \\mathbb{R}$ a smooth (differentiable) function at the point (vector) $\\pmb{x}_0=(x_1^0,x_2^0,\\ldots,x_n^0)$. The **gradient** of the function $f$ (in cartesian coordinates) is defined as\n\n\\begin{equation}\n\\textrm{grad }f(\\pmb{x}_0)= \\nabla f(\\pmb{x}_0)= \\left( \\frac{\\partial f (\\pmb{x_0})}{\\partial x_1},\\frac{\\partial f (\\pmb{x_0})}{\\partial x_2},\\ldots,\\frac{\\partial f (\\pmb{x_0})}{\\partial x_n} \\right)\n\\end{equation}\n\nRecall that the partial derivatives represent derivatives of the function $f$ with respect to a given variable while considering the rest of them constant. \n\nHow can we interpret the gradient?\n\n+ It is a vector whose direction is always perpendicular to the direction of the level surface passing through the point.\n\n+ The gradient vector always points to the direction in which the function $f$ is increasing.\n\n\n### Example.\n\nConsider $f(x_1,x_2)= 20 \\cos(36*(x_1^2+x_2^2))+30$. The surface levels are depicted in the following animation.\n\n\n\nLet's suppose we have a value $c=40$. The level-surface $L_c$ is defined as\n\n\\begin{equation}\nL_c= \\{ (x_1,x_2): f(x_1,x_2)=40\\}= \\{(x_1,x_2): x_1^2+x_2^2= \\frac\\pi{108} \\}\n\\end{equation}\nThus, $L_c$ represents a circle of radius $\\sqrt{\\pi/108}$ centered at the origin. The gradient would be\n\\begin{equation}\n\\nabla f(x_1,x_2)= \\left( \n-1440 \\sin(36*(x_1^2+x_2^2))x_1 , -1440 \\sin(36*(x_1^2+x_2^2))x_2\n\\right)\n\\end{equation}\nFor a point $(x_1^0,x_2^0) \\in L_c$, \n\\begin{equation}\n\\nabla f(x_1^0,x_2^0)= -720\\sqrt{3} (x_1^0,x_2^0)\n\\end{equation}\nThus, the gradient points towards the origin for every point in the level surface $L_c$.\n\n\n\n# Random Numbers\n\nCan a deterministic machine produce random numbers? \nIn principle, any program in a deterministic machine will produce an output that is entirely predictable, thus not random. \n\nOur computers produce *pseudo*-random numbers. At the minimum, we expect that a random number generator produces different sequences which are statistically uncorrelated to each other. \n\nWhen we invoke a random number generator, we have access to a large sequence of numbers. The term **seed** refers to the initialization point of such sequence. Consecutive calls to the generator will give us the desired sequence or \"random\" numbers. \n\nThe basic module *random* generates uniform random numbers, but it is possible to use *numpy*.\n\n\n\n\n```python\nimport random\nrandom.seed(2021)\nprint(\"Uniformly Distributed Random numbers between (0,1) \")\nprint(\"%.4f\"%random.uniform(0,1))\nprint(\"%.4f\"%random.uniform(0,1))\n```\n\n Uniformly Distributed Random numbers between (0,1) \n 0.8363\n 0.8583\n\n\n\n```python\nimport numpy as np\nnp.random.seed(2021)\nprint(\"Uniformly Distributed Random numbers between (0,1) \")\nprint(\"%.4f\"%np.random.uniform(0,1))\nprint(\"%.4f\"%np.random.uniform(0,1))\n```\n\n Uniformly Distributed Random numbers between (0,1) \n 0.6060\n 0.7334\n\n\nLet's verify emprically, how accurate are our random number generators\n\n\n```python\nimport math\nmy_mean=0; my_stdev=1.0; n=5000\nu=np.random.normal(my_mean,my_stdev,n)\nm=sum(u)/n; s =math.sqrt(sum((u-my_mean)**2)/(n-1))\nprint(\"Mean = %.5f and Emprical mean= %.5f\"%(my_mean,m))\nprint(\"Standard Deviation = %.5f and Empirical Stdev = %.5f\"%(my_stdev,s))\n\n```\n\n Mean = 0.00000 and Emprical mean= -0.00063\n Standard Deviation = 1.00000 and Empirical Stdev = 0.99494\n\n\n# Numerical Python\n\nAs we saw in our previous discussion, one of the most often used package for mathematical computations in Python is called *Numerical Python* abbreviates **NumPy**\n\nIn **Numpy** arrays with one index are called vectors. \n\n\n```python\nimport numpy as np\na=np.zeros(10)\nprint(a)\ntype(a)\n```\n\n [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]\n\n\n\n\n\n numpy.ndarray\n\n\n\nIn the previous example $\\verb+a+$ is not a list per se, it has been converted into a *numpy* array.\n\nIf we want to find in an interval, say $[1,3]$, 10 uniformly distributed values. \n\n\n```python\nb=np.linspace(1,3,10)\nprint(b)\n```\n\n [1. 1.22222222 1.44444444 1.66666667 1.88888889 2.11111111\n 2.33333333 2.55555556 2.77777778 3. ]\n\n", "meta": {"hexsha": "f0aabd00331df37d29858f92e0eca96126e7a0b7", "size": 31035, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Lectures/Lecture_LAlgebra/Lecture_Linear_Algebra.ipynb", "max_stars_repo_name": "horaciogacevedo/Bmig6201", "max_stars_repo_head_hexsha": "41946bcfcf8782867365bd31d8bff8ed26ddf4fd", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-01-22T13:49:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-24T02:41:00.000Z", "max_issues_repo_path": "Lectures/Lecture_LAlgebra/Lecture_Linear_Algebra.ipynb", "max_issues_repo_name": "horaciogacevedo/Bmig6201", "max_issues_repo_head_hexsha": "41946bcfcf8782867365bd31d8bff8ed26ddf4fd", "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": "Lectures/Lecture_LAlgebra/Lecture_Linear_Algebra.ipynb", "max_forks_repo_name": "horaciogacevedo/Bmig6201", "max_forks_repo_head_hexsha": "41946bcfcf8782867365bd31d8bff8ed26ddf4fd", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-01-30T03:47:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-24T02:41:08.000Z", "avg_line_length": 31.7331288344, "max_line_length": 474, "alphanum_fraction": 0.5052038022, "converted": true, "num_tokens": 7387, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9674102589923637, "lm_q2_score": 0.914900959053549, "lm_q1q2_score": 0.8850845737503557}} {"text": "# Introduction to Neural Networks \n\n\n\n## The Perceptron\n\n\nTo get an intuitive idea about Neural Networks, we will code an elementary perceptron. In this example we will illustrate some of the concepts you have just seen, build a small perceptron and make a link between Perceptron and linear classifier.\n\n### Generating some data\n\nBefore working with the MNIST dataset, you'll first test your perceptron implementation on a \"toy\" dataset with just a few data points. This allows you to test your implementations with data you can easily inspect and visualise without getting lost in the complexities of the dataset itself.\n\n\nStart by loading two basic libraries: `matplotlib` and numpy\n\n\n\n\n```python\n# Load the libraries ...\nimport matplotlib.pyplot as plt\nimport numpy as np\n%matplotlib inline\n\n```\n\nThen let us generate some points in a 2D space that will form our dataset (you can add points later if you'd like)\n\n\n```python\ncrosses = np.array([[0.5, 1.0], [1.0, 1.5], [1.5, 1.5], [2.0, 1.2], [3.0, 1.7], [1.5, 1.1],[2.1, 1.7]])\ncircles = np.array([[3.0, 0.5], [4.0, 1.0], [5.0, 0.7], [4.0, 0.2], [5.1, 0.3], [4.2, 0.7]])\n```\n\n### Visualising the data\n\nUsing `matploblib`, you can display the crosses as crosses (use `marker='x'`) and the circles as circles (use `marker='o'`). You will need to specify that you don't want a line using `linestyle='none'`. You can observe that the points are very easily separable. \n\n\n```python\nplt.plot(crosses[:,0], crosses[:,1], marker='x', linestyle='none')\nplt.plot(circles[:,0], circles[:,1], marker='o', linestyle='none')\nplt.ylim((0, 2))\nplt.xlim((0, 6))\n\n```\n\n### Computing the output of a Perceptron\n\n\nLet us consider the problem of building a classifier that for a given **new** point will return whether it belongs to the crosses (class 1) or circles (class 0). So for example it would take `(2, 1.5)` and return `1`. \n\nDefine a function `outPerceptron` which takes a 2d vector `x`, a 2d weight vector `w` and a bias `b` and returns the output following the step rule:\n\n$$\n\\text{output} = \\left\\{\\begin{align} 1\\,\\, &\\text{if}\\,\\, \\langle x, w\\rangle -b \\, >\\,0 \\\\ 0\\,\\, &\\text{otherwise}\\end{align}\\right.\n$$\n\n\n```python\ndef outPerceptron(x, w, b):\n innerProd = np.dot(x, w)\n output = 0\n if innerProd > b:\n output = 1\n return output\n\n```\n\nYou can then enrich the function so that it can take a **sequence of inputs** (in the form of a matrix where each line of the matrix is one input vector) and return the corresponding **sequence of outputs**. \n\nOne way of doing this is to loop over the rows of `X` and for each of them, use the function `outPerceptron` that you just wrote. Store the results in an array `outputs` and return that. Call that function `multiOutPerceptron`/\n\nOnce you have that, you can try optimising the function by using a matrix-vector product; call the resulting function `multiOutPerceptron2` (and make sure it leads to the same results!)\n\n\n```python\ndef multiOutPerceptron(X,w,b):\n nInstances = X.shape[0]\n outputs = np.zeros(nInstances)\n for i in range(0,nInstances):\n outputs[i] = outPerceptron(X[i,:],w,b)\n return outputs\n\ndef multiOutPerceptron2(X,w,b):\n return (np.dot(X,w)>b).astype(float)\n\n```\n\n## = checkpoint 1 =\n\nhere, you should copy-paste the following code. If it returns `True` you're good to go on.\n\n```python\nnp.random.seed(1234)\nX = np.random.randn(10, 5)\nw = np.random.randn(5)\nb = np.random.randn()\nnp.all(multiOutPerceptron2(X, w, b) == np.array([ 1., 1., 0., 0., 0., 1., 0., 0., 1., 0.]))\n```\n\n\n### Trying different weights and biases\n\nYou now have a method that can compute the outputs predicted by an **untrained** perceptron. Can you try picking different weights and biases and see how well you can classify the crosses and circles? \n\n**Note**: to join the crosses and circles into one `instances` matrix, you can use `np.concatenate((crosses, circles), axis=0)`.\n\nYou can maybe start with `w=[1, 1]` and `b=1` and output the result of `multiOutPerceptron`. What is your analysis?\n\n\n```python\ntest_w1 = [1., 1.]\ntest_b1 = 1.\ninstances = np.concatenate((crosses, circles), axis=0)\nprint(multiOutPerceptron(instances, test_w1, test_b1))\n\n```\n\nWith the suggested weights and biases (`([1, 1],1)`), you should see something like \n\n> `[ 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]` \n\nwhich is clearly not great! Now try with `w=[-0.5, 1]` and `b=-0.2`, what do you observe? \n\n\n```python\ntest_w2 = [-0.5, 1.]\ntest_b2 = -0.2\nprint (multiOutPerceptron(instances, test_w2, test_b2))\n\n```\n\n### How did we get there?\n\nThis is much better (100% correct on the training data). \nTo obtain these values, we found a **separating hyperplane** (here a line) between the points. \nThe equation of the line is \n\n$ y = 0.5x-0.2 $\n\n\n**Quiz**\n- **Can you explain why this line corresponds to the weights and bias we used?**\n- **Is this separating line unique? does it matter?**\n\n### Illustrating the output of the Perceptron and the separating line\n\nCopy-paste your code to visualise the crosses and circles above and overlay the separating line in red. \n\nCan you modify the parameters of the line a little bit and still find a separating line that \"works\"? \n\n\n```python\nxx = np.linspace(0, 6)\nyy1 = 0.5 * xx - 0.2\nyy2 = 0.4 * xx - 0.3\n\nplt.plot(xx, yy1, color='red')\nplt.plot(xx, yy2, color='orange')\nplt.plot(crosses[:, 0], crosses[:, 1], marker='x', linestyle='none', label='sp1')\nplt.plot(circles[:, 0], circles[:, 1], marker='o', linestyle='none', label='sp2')\nplt.ylim((0, 2))\nplt.xlim((0, 6))\nplt.legend()\n\n```\n\n### Testing a few new points\n\nCan you add the following `testPoints` on the plot and discuss what happens to them? \n\n\n```python\ntestPoints = np.array([[1, 0.5],[5, 1.5],[3, 1.1]])\n```\n\n\n```python\nplt.plot(xx, yy1, color='red')\nplt.plot(xx, yy2, color='orange')\nplt.plot(crosses[:, 0], crosses[:, 1], marker='x', linestyle='none')\nplt.plot(circles[:, 0], circles[:, 1], marker='o', linestyle='none')\nplt.ylim((0, 2))\nplt.xlim((0, 6))\n\n# the points\nplt.plot(1, 0.5, marker='s', color='blue', markersize=10) \nplt.plot(5, 1.5, marker='s', color='green', markersize=10)\nplt.plot(3, 1.1, marker='^', color='black', markersize=10)\n\n```\n\n## = checkpoint 2 =\n\n\n# Gradient Descent (remember?)\n\n## Coding a simple gradient descent\n\n### Considering some function\n\nLet's consider the following arbitrary function and its gradient\n\n$f(x) = \\exp(-\\sin(x))x^2$\n\n$f'(x) = -x \\exp(-\\sin(x)) (x\\cos(x)-2)$\n\nIt is convenient to define python functions which return the value of the function and its gradient at an arbitrary point $x$. Can you define a function `function` and a function `gradient`? \n\n* use `np.exp`, `np.sin`, `np.cos` and remember that `x**2` is the squared of `x`\n\n\n```python\ndef function(x):\n return np.exp(-np.sin(x))*(x**2)\n\ndef gradient(x):\n return -x*np.exp(-np.sin(x))*(x*np.cos(x)-2)\n\n```\n\n### Visualising the function\n\nCan you write a simple code that shows what the function looks like over the interval `[-10,10]`? use at least `100` points in order to have a high enough definition of the line.\n\n\n```python\nx = np.linspace(-10, 10, 500)\nplt.plot(x, function(x))\n\n```\n\n### Implementing a simple GD\n\nNow let us implement a simple Gradient Descent that uses constant stepsizes. Define two functions:\n\n1. simplest version which doesn't store the intermediate steps that are taken. \n2. a version which does store the steps (useful to visualize what is going on and explain some of the typical behaviour of GD).\n\nLet's call them `simpleGD` and `simpleGD2`. The parameters of both functions will be the initial point `x0`, the stepsize, and the number of steps to be taken.\n\n\n```python\ndef simpleGD(x0, stepsize, nsteps):\n x = x0\n for k in range(0,nsteps):\n x -= stepsize*gradient(x)\n return x\n\ndef simpleGD2(x0, stepsize, nsteps):\n x = np.zeros(nsteps+1)\n x[0] = x0\n for k in range(0,nsteps):\n x[k+1] = x[k]-stepsize*gradient(x[k])\n return x\n\n```\n\n### Testing different situations\n\nTry your algorithm `simpleGD` in the following cases:\n\n* $x_0=1, \\delta=0.1, n=100$\n* $x_0=6, \\delta=0.1, n=100$\n* $x_0=8, \\delta=0.01, n=100$\n\nCan you discuss the results you obtained by having a look at the plot of the function? \n\n### Visualising the cases\n\nWe suggest below a function `viz` which shows the path taken by the gradient descent when computed using `simpleGD2`. \n\nUse it in the different cases above in order to see what the Gradient Descent does. Try to interpret the different cases.\n\n\n```python\ndef viz(x, a=-10, b=10):\n xx = np.linspace(a, b, 100)\n yy = function(xx)\n ygd = function(x)\n plt.plot(xx, yy)\n plt.plot(x, ygd, color='red')\n plt.plot(x[0], ygd[0], marker='o', color='green', markersize=10)\n plt.plot(x[len(x)-1], ygd[len(x)-1], marker='o', color='red', markersize=10)\n plt.show()\n\n```\n\n\n```python\nx1 = simpleGD2(3, 0.1, 100)\nx2 = simpleGD2(6, 0.1, 100)\nx3 = simpleGD2(8, 0.01, 100)\nx4 = simpleGD2(3, 0.5, 100)\n\nviz(x1)\nviz(x2)\nviz(x3)\nviz(x4)\n\n```\n", "meta": {"hexsha": "2a65f6fe8f77de38e02f2ae96a91d95bf5c36439", "size": 15671, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "ads8-neuralnets_content_students/d1-introNN-part1_solution.ipynb", "max_stars_repo_name": "JamesOwers/camsparknn", "max_stars_repo_head_hexsha": "c94b6c8307ff85c819f8efc1f57ab58242bdd7cd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-06-04T14:26:30.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-04T14:26:30.000Z", "max_issues_repo_path": "ads8-neuralnets_content_tutors/d1-introNN-part1_solution.ipynb", "max_issues_repo_name": "JamesOwers/camsparknn", "max_issues_repo_head_hexsha": "c94b6c8307ff85c819f8efc1f57ab58242bdd7cd", "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": "ads8-neuralnets_content_tutors/d1-introNN-part1_solution.ipynb", "max_forks_repo_name": "JamesOwers/camsparknn", "max_forks_repo_head_hexsha": "c94b6c8307ff85c819f8efc1f57ab58242bdd7cd", "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.7010752688, "max_line_length": 306, "alphanum_fraction": 0.4951183715, "converted": true, "num_tokens": 2744, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088025362857, "lm_q2_score": 0.9532750460199726, "lm_q1q2_score": 0.8850289439631254}} {"text": "# Final project\n## Author: Eros Fabrici\nThe Allen–Cahn equation (after John W. Cahn and Sam Allen) is a reaction–diffusion equation of mathematical physics which describes the process of phase separation in multi-component alloy systems, including order-disorder transitions.\n\nThe equation describes the time evolution of a scalar-valued state variable $\\eta$ on a domain $\\Omega=[0,1]$ during a time interval $[0,T]$, and is given (in one dimension) by:\n\n$$\n\\frac{\\partial \\eta}{\\partial t} - \\varepsilon^2 \\eta'' + f'(\\eta) = 0, \\qquad \\eta'(0, t) = \\eta'(1, t) = 0,\\qquad\\eta(x,0) = \\eta_0(x)\n$$\n\nwhere $f$ is a double-well potential, $\\eta_0$ is the initial condition, and $\\varepsilon$ is the characteristic width of the phase transition.\n\nThis equation is the L2 gradient flow of the Ginzburg–Landau free energy functional, and it is closely related to the Cahn–Hilliard equation.\n\nA typical example of double well potential is given by the following function\n\n$$\nf(\\eta) = \\eta^2(\\eta-1)^2\n$$\n\nwhich has two minima in $0$ and $1$ (the two wells, where its value is zero), one local maximum in $0.5$, and it is always greater or equal than zero.\n\nThe two minima above behave like \"attractors\" for the phase $\\eta$. Think of a solid-liquid phase transition (say water+ice) occupying the region $[0,1]$. When $\\eta = 0$, then the material is liquid, while when $\\eta = 1$ the material is solid (or viceversa).\n\nAny other value for $\\eta$ is *unstable*, and the equation will pull that region towards either $0$ or $1$.\n\nDiscretisation of this problem can be done by finite difference in time. For example, a fully explicity discretisation in time would lead to the following algorithm.\n\nWe split the interval $[0,T]$ in `n_steps` intervals, of dimension `dt = T/n_steps`. Given the solution at time `t[k] = k*dt`, it i possible to compute the next solution at time `t[k+1]` as\n\n$$\n\\eta_{k+1} = \\eta_{k} + \\Delta t \\varepsilon^2 \\eta_k'' - \\Delta t f'(\\eta_k)\n$$\n\nSuch a solution will not be stable. A possible remedy that improves the stability of the problem, is to treat the linear term $\\Delta t \\varepsilon^2 \\eta_k''$ implicitly, and keep the term $-f'(\\eta_k)$ explicit, that is:\n\n$$\n\\eta_{k+1} - \\Delta t \\varepsilon^2 \\eta_k'' = \\eta_{k} - \\Delta t f'(\\eta_k)\n$$\n\nGrouping together the terms on the right hand side, this problem is identical to the one we solved in the python notebook number 9, with the exception of the constant $\\Delta t \\varepsilon^2$ in front the stiffness matrix.\n\nIn particular, given a set of basis functions $v_i$, representing $\\eta = \\eta^j v_j$ (sum is implied), we can solve the problem using finite elements by computing\n\n$$\n\\big((v_i, v_j) + \\Delta t \\varepsilon^2 (v_i', v_j')\\big) \\eta^j_{k+1} = \\big((v_i, v_j) \\eta^j_{k} - \\Delta t (v_i, f'(\\eta_k)\\big)\n$$\nwhere a sum is implied over $j$ on both the left hand side and the right hand side. Let us remark that while writing this last version of the equation we moved from a forward Euler scheme to a backward Euler scheme for the second spatial derivative term: that is, we used $\\eta^j_{k+1}$ instead of $\\eta^j_{k}$. \n\nThis results in a linear system\n\n$$\nA x = b\n$$\n\nwhere \n\n$$\nA_{ij} = M_{ij}+ \\Delta t \\varepsilon^2 K_{ij} = \\big((v_i, v_j) + \\Delta t \\varepsilon^2 (v_i', v_j')\\big) \n$$\n\nand \n\n$$\nb_i = M_{ij} \\big(\\eta_k^j - \\Delta t f'(\\eta_k^j)\\big)\n$$\n\nwhere we simplified the integration on the right hand side, by computing the integral of the interpolation of $f'(\\eta)$.\n\n## Step 1\n\nWrite a finite element solver, to solve one step of the problem above, given the solution at the previous time step, using the same techniques used in notebook number 9.\n\nIn particular:\n\n1. Write a function that takes in input a vector representing $\\eta$, an returns a vector containing $f'(\\eta)$. Call this function `F`.\n\n2. Write a function that takes in input a vector of support points of dimension `ndofs` and the degree `degree` of the polynomial basis, and returns a list of basis functions (piecewise polynomial objects of type `PPoly`) of dimension `ndofs`, representing the interpolatory spline basis of degree `degree`\n\n3. Write a function that, given a piecewise polynomial object of type `PPoly` and a number `n_gauss_quadrature_points`, computes the vector of global_quadrature_points and global_quadrature_weights, that contains replicas of a Gauss quadrature formula with `n_gauss_quadrature_points` on each of the intervals defined by `unique(PPoly.x)`\n\n4. Write a function that, given the basis and the quadrature points and weights, returns the two matrices $M$ and $K$ \n\n## Step 2\n\nSolve the Allen-Cahan equation on the interval $[0,1]$, from time $t=0$ and time $t=1$, given a time step `dt`, a number of degrees of freedom `ndofs`, and a polynomial degree `k`.\n\n1. Write a function that takes the initial value of $\\eta_0$ as a function, eps, dt, ndofs, and degree, and returns a matrix of dimension `(int(T/dt), ndofs)` containing all the coefficients $\\eta_k^i$ representing the solution, and the set of basis functions used to compute the solution\n\n2. Write a function that takes all the solutions `eta`, the basis functions, a stride number `s`, and a resolution `res`, and plots on a single plot the solutions $\\eta_0$, $\\eta_s$, $\\eta_{2s}$, computed on `res` equispaced points between zero and one\n\n## Step 3\n\nSolve the problem for all combinations of\n\n1. eps = [01, .001]\n\n2. ndofs = [16, 32, 64, 128]\n\n3. degree = [1, 2, 3]\n\n3. dt = [.25, .125, .0625, .03125, .015625]\n\nwith $\\eta_0 = \\sin(2 \\pi x)+1$.\n\nPlot the final solution at $t=1$ in all cases. What do you observe? What happens when you increase ndofs and keep dt constant? \n\n## Step 4 (Optional)\n\nInstead of solving the problem explicitly, solve it implicitly, by using backward euler method also for the non linear term. This requires the solution of a Nonlinear problem at every step. Use scipy and numpy methods to solve the non linear iteration.\n\n\n```python\n%pylab inline\nimport sympy as sym\nimport scipy\nfrom scipy.interpolate import *\nfrom scipy.integrate import *\n```\n\n Populating the interactive namespace from numpy and matplotlib\n\n\n\n```python\n# Step 1.1\n\ndef F(eta):\n \"\"\"\n Derivative of f(eta)\n \"\"\"\n return 2*eta*(eta-1)*(2*eta-1)\n```\n\n\n```python\n# Step 1.2\n\ndef compute_basis_functions(support_points, degree):\n basis_functions = []\n for i in range(len(support_points)):\n temp = support_points*0\n temp[i] = 1\n bi = PPoly.from_spline(splrep(support_points, temp, k=degree))\n basis_functions.append(bi)\n return basis_functions\n```\n\n\n```python\n# Step 1.3\n\ndef compute_global_quadrature(basis, n_gauss_quadrature_points):\n quad_points, weights = numpy.polynomial.legendre.leggauss(n_gauss_quadrature_points+1) \n quad_points = (quad_points+1)/2\n weights /= 2\n # extract intervals\n intervals = unique(basis[0].x)\n # compute the first order difference points\n discr_difference = diff(intervals)\n discr_diff_length = len(discr_difference)\n \n gloabl_quadrature = array([intervals[i] + discr_difference[i] * quad_points\n for i in range(discr_diff_length)]).reshape((-1,))\n global_weights = array([weights * discr_difference[i]\n for i in range(discr_diff_length)]).reshape((-1,))\n return gloabl_quadrature, global_weights\n```\n\n\n```python\n# Step 1.4\n\ndef compute_system_matrices(basis, gloabl_quadrature, global_weights):\n n_basis_funct = len(basis)\n derivative_basis = []\n for i in range(n_basis_funct):\n derivative_basis.append(basis[i].derivative(1))\n basis_quad = array([basis[i](gloabl_quadrature)\n for i in range(n_basis_funct)]).T\n derivative_basis_quad = array([derivative_basis[i](gloabl_quadrature)\n for i in range(n_basis_funct)]).T\n M = einsum('qi, q, qj', basis_quad, global_weights, basis_quad)\n K = einsum('qi, q, qj', derivative_basis_quad, global_weights, derivative_basis_quad)\n return M, K\n```\n\n\n```python\n# Step 2.1\n\ndef solve_allen_cahan(eta_0_function, eps, dt, ndofs, degree):\n '''\n Forward Euler solution.\n '''\n points = linspace(0, 1, ndofs)\n basis = compute_basis_functions(points, degree)\n Q, W = compute_global_quadrature(basis, degree+1)\n M, K = compute_system_matrices(basis, Q, W)\n A = M + (dt*eps**2)*K\n steps = int(1/dt) + 1\n t_interval = [step*dt for step in range(steps)]\n # matrix where the results will be stored\n eta = zeros((len(t_interval), ndofs))\n # setting the initial function \n eta[0, :] = eta_k = eta_0_function(points)\n for t in range(1, len(t_interval)):\n b = M.dot((eta_k - dt*F(eta_k)))\n eta_k = linalg.solve(A, b)\n eta[t, :] = eta_k\n\n return eta, basis\n```\n\n\n```python\n# Step 2.2 \n\ndef plot_solution(eta, basis, stride, resolution):\n x = linspace(0, 1, resolution)\n B = zeros((resolution, len(basis)))\n for i in range(len(basis)):\n B[:,i] = basis[i](x)\n \n n_t = shape(eta)[0]\n t = ['t ='+str(round((i/(n_t-1)), 2)) for i in range(n_t)]\n for eta, label_t in zip(eta[::-stride], t[::-stride]):\n plot(x, eta.dot(B.T), label=label_t)\n\n _ = legend(fontsize='x-large')\n _ = title('Allen–Cahn equation $\\eta(x,t)$')\n _ = xlabel('$x$')\n _ = ylabel('$\\eta$')\n```\n\n\n```python\n#initial function choosen\ndef eta_0(x):\n return sin(2*pi*x)+1\n\n\nfigure(figsize=(20,6))\neta, basis = solve_allen_cahan(eta_0, eps=0.01, dt=0.1, ndofs=64, degree=1)\n_= plot_solution(eta, basis, stride=3, resolution=1025)\n```\n\n## Step 3\n\n\n```python\ndef plot_increasing_eps(dt, degree, ndofs, eps):\n #eps = [.1, .01, .001]\n fig = figure(figsize=(20, 7))\n for i in range(len(eps)):\n eta, basis = solve_allen_cahan(eta_0, eps[i], dt, ndofs, degree)\n subplot(1,3,i+1)\n plot_solution(eta, basis, int(1/dt+1), 1024)\n xlabel('x')\n ylabel('$\\eta$') \n title('eps = '+ str(eps[i]))\n \n\ndef plot_increasing_ndofs(eps, degree, dt, ndofs):\n #ndofs = [16, 32, 64, 128]\n fig = figure(figsize=(22, 11))\n for i in range(len(ndofs)):\n eta, basis = solve_allen_cahan(eta_0, eps, dt, ndofs[i], degree)\n subplot(2, 2, i+1)\n plot_solution(eta, basis, int(1/dt+1), 1024)\n xlabel('x')\n ylabel('$\\eta$')\n title('ndofs = '+ str(ndofs[i]))\n \n \n \ndef plot_increasing_degree(eps, degree, ndofs, dt):\n #dt = [.25, .125, .0625, .03125, .015625]\n fig = figure(figsize=(18,28))\n for i in range(len(degree)):\n eta, basis = solve_allen_cahan(eta_0, eps, dt, ndofs, degree[i])\n subplot(5,3,i+1)\n plot_solution(eta, basis, int(1/dt+1), 1024)\n xlabel('x')\n ylabel('$\\eta$') \n title('degree = '+str(degree[i]))\n\n \ndef plot_increasing_dt(eps, degree, ndofs, dt):\n #dt = [.25, .125, .0625, .03125, .015625]\n fig = figure(figsize=(18,28))\n for i in range(len(dt)):\n eta, basis = solve_allen_cahan(eta_0, eps, dt[i], ndofs, degree)\n subplot(5,3,i+1)\n plot_solution(eta, basis, int(1/dt[i]+1), 1024)\n xlabel('x')\n ylabel('$\\eta$') \n title('dt = '+ str(dt[i]))\n\n```\n\n\n```python\nresolution = 1024\neps = [.01, .001]\nndofs = [16, 32, 64, 128]\ndegree = [1, 2, 3]\ndt = [.25, .125, .0625, .03125, .015625]\n\nplot_increasing_eps(eps = eps, degree = 1, dt = 0.1, ndofs = 128)\n```\n\n\n```python\nplot_increasing_ndofs(eps = 0.01, degree = 1, dt = 0.1, ndofs=ndofs)\n```\n\nThe more we increase the `ndofos`, the smoother the line becomes. This is due to the fact that we are increasing the support points for computing the basis functions.\n\n\n```python\nplot_increasing_degree(eps=0.01, degree=degree, ndofs=128, dt=0.1)\n```\n\n\n```python\nplot_increasing_dt(eps=0.01, degree=1, ndofs=128, dt=dt)\n```\n\nIt is possible to observe an abnormal behaviour when $dt>0.1$. This is due to the fact that the Forward Euler method is conditionally stable. More precisely, it is stable when the time step is smaller than a specific value, which depends on the problem you are solving.\n\n## Step 4\nAs stated in the exercise description, if we use a backward Euler method we have:\n$$\n\\big((v_i, v_j) + \\Delta t \\varepsilon^2 (v_i', v_j')\\big) \\eta^j_{k+1} = \\big((v_i, v_j) \\eta^j_{k} - \\Delta t (v_i, f'(\\eta_k)\\big)\n$$\nPutting everything on the left-end side and rewriting with the matrix notation we obtain\n$$\nA_{i,j}\\eta^j_{k+1} - M_{i,j}\\eta^j_k + \\Delta tM_{i,j}f'(\\eta_{k+1}) = 0\n$$\nThus we need to find $\\eta^j_{k+1}$ such that the equation above is satisfied, namely we have to find the roots of a non-linear equation.\nThe solution in terms of code is pretty straight forward, as we just need to change the code inside the for-loop.\nFor solving the non-linear problem I will use scipy.optimize.fsolve that takes a function and an initial estimate of the root.\n\n\n```python\ndef solve_allen_cahan_Backward(eta_0_function, eps, dt, ndofs, degree):\n points = linspace(0, 1, ndofs)\n basis = compute_basis_functions(points, degree)\n Q, W = compute_global_quadrature(basis, degree+1)\n M, K = compute_system_matrices(basis, Q, W)\n A = M + (dt*eps**2)*K\n steps = int(1/dt) + 1\n t_interval = [step*dt for step in range(steps)]\n # matrix where the results will be stored\n eta = zeros((len(t_interval), ndofs))\n # setting the initial function \n eta[0, :] = eta_k = eta_0_function(points)\n for t in range(1, len(t_interval)):\n eta_k = scipy.optimize.fsolve(\n lambda x: A.dot(x) - M.dot(eta_k) + dt*M.dot(F(x)),\n eta_k # starting estimate of the root\n )\n eta[t, :] = eta_k\n\n return eta, basis\n```\n\nNow we confront the results of the two methods with $\\Delta t=0.25$\n\n\n```python\nfigure(figsize=(20,6))\n\nplt.subplot(1, 2, 1)\neta, basis = solve_allen_cahan_Backward(eta_0, eps=0.01, dt=0.25, ndofs=64, degree=1)\n_ = plot_solution(eta, basis, stride=2, resolution=1025)\n_ = title(\"Backward Euler Solution\")\n\nplt.subplot(1, 2, 2)\neta, basis = solve_allen_cahan(eta_0, eps=0.01, dt=0.25, ndofs=64, degree=1)\n_ = plot_solution(eta, basis, stride=2, resolution=1025)\n_ = title(\"Forward Euler Solution\")\n```\n\nAs stated by theory, Backward Euler method is unconditionally stable.\n", "meta": {"hexsha": "fca6ac610023cef4e2d164b22bf173cabea09948", "size": 405762, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "final_project/Fabrici_Eros_final_project_2019-2020.ipynb", "max_stars_repo_name": "eferos93/numerical-analysis-repo", "max_stars_repo_head_hexsha": "67d6200bde0a64e50bf5c4b5124381181dd2cb4f", "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": "final_project/Fabrici_Eros_final_project_2019-2020.ipynb", "max_issues_repo_name": "eferos93/numerical-analysis-repo", "max_issues_repo_head_hexsha": "67d6200bde0a64e50bf5c4b5124381181dd2cb4f", "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": "final_project/Fabrici_Eros_final_project_2019-2020.ipynb", "max_forks_repo_name": "eferos93/numerical-analysis-repo", "max_forks_repo_head_hexsha": "67d6200bde0a64e50bf5c4b5124381181dd2cb4f", "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": 687.7322033898, "max_line_length": 87524, "alphanum_fraction": 0.9466608504, "converted": true, "num_tokens": 4221, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422213778251, "lm_q2_score": 0.9304582559762669, "lm_q1q2_score": 0.8849981324886035}} {"text": "# Modeling and Simulation in Python\n\nChapter 9\n\nCopyright 2017 Allen Downey\n\nLicense: [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0)\n\n\n\n```python\n# Configure Jupyter to display the assigned value after an assignment\n%config InteractiveShell.ast_node_interactivity='last_expr_or_assign'\n\n# import everything from SymPy.\nfrom sympy import *\n\n# Set up Jupyter notebook to display math.\ninit_printing() \n```\n\nThe following displays SymPy expressions and provides the option of showing results in LaTeX format.\n\n\n```python\nfrom sympy.printing import latex\n\ndef show(expr, show_latex=False):\n \"\"\"Display a SymPy expression.\n \n expr: SymPy expression\n show_latex: boolean\n \"\"\"\n if show_latex:\n print(latex(expr))\n return expr\n```\n\n### Analysis with SymPy\n\nCreate a symbol for time.\n\n\n```python\nt = symbols('t')\n```\n\nIf you combine symbols and numbers, you get symbolic expressions.\n\n\n```python\nexpr = t + 1\n```\n\nThe result is an `Add` object, which just represents the sum without trying to compute it.\n\n\n```python\ntype(expr)\n```\n\n\n\n\n sympy.core.add.Add\n\n\n\n`subs` can be used to replace a symbol with a number, which allows the addition to proceed.\n\n\n```python\nexpr.subs(t, 2)\n```\n\n`f` is a special class of symbol that represents a function.\n\n\n```python\nf = Function('f')\n```\n\n\n\n\n f\n\n\n\nThe type of `f` is `UndefinedFunction`\n\n\n```python\ntype(f)\n```\n\n\n\n\n sympy.core.function.UndefinedFunction\n\n\n\nSymPy understands that `f(t)` means `f` evaluated at `t`, but it doesn't try to evaluate it yet.\n\n\n```python\nf(t)\n```\n\n`diff` returns a `Derivative` object that represents the time derivative of `f`\n\n\n```python\ndfdt = diff(f(t), t)\n```\n\n\n```python\ntype(dfdt)\n```\n\n\n\n\n sympy.core.function.Derivative\n\n\n\nWe need a symbol for `alpha`\n\n\n```python\nalpha = symbols('alpha')\n```\n\nNow we can write the differential equation for proportional growth.\n\n\n```python\neq1 = Eq(dfdt, alpha*f(t))\n```\n\nAnd use `dsolve` to solve it. The result is the general solution.\n\n\n```python\nsolution_eq = dsolve(eq1)\n```\n\nWe can tell it's a general solution because it contains an unspecified constant, `C1`.\n\nIn this example, finding the particular solution is easy: we just replace `C1` with `p_0`\n\n\n```python\nC1, p_0 = symbols('C1 p_0')\n```\n\n\n```python\nparticular = solution_eq.subs(C1, p_0)\n```\n\nIn the next example, we have to work a little harder to find the particular solution.\n\n### Solving the quadratic growth equation \n\nWe'll use the (r, K) parameterization, so we'll need two more symbols:\n\n\n```python\nr, K = symbols('r K')\n```\n\nNow we can write the differential equation.\n\n\n```python\neq2 = Eq(diff(f(t), t), r * f(t) * (1 - f(t)/K))\n```\n\nAnd solve it.\n\n\n```python\nsolution_eq = dsolve(eq2)\n```\n\nThe result, `solution_eq`, contains `rhs`, which is the right-hand side of the solution.\n\n\n```python\ngeneral = solution_eq.rhs\n```\n\nWe can evaluate the right-hand side at $t=0$\n\n\n```python\nat_0 = general.subs(t, 0)\n```\n\nNow we want to find the value of `C1` that makes `f(0) = p_0`.\n\nSo we'll create the equation `at_0 = p_0` and solve for `C1`. Because this is just an algebraic identity, not a differential equation, we use `solve`, not `dsolve`.\n\nThe result from `solve` is a list of solutions. In this case, [we have reason to expect only one solution](https://en.wikipedia.org/wiki/Picard%E2%80%93Lindel%C3%B6f_theorem), but we still get a list, so we have to use the bracket operator, `[0]`, to select the first one.\n\n\n```python\nsolutions = solve(Eq(at_0, p_0), C1)\ntype(solutions), len(solutions)\n```\n\n\n\n\n (list, 1)\n\n\n\n\n```python\nvalue_of_C1 = solutions[0]\n```\n\nNow in the general solution, we want to replace `C1` with the value of `C1` we just figured out.\n\n\n```python\nparticular = general.subs(C1, value_of_C1)\n```\n\nThe result is complicated, but SymPy provides a method that tries to simplify it.\n\n\n```python\nparticular = simplify(particular)\n```\n\nOften simplicity is in the eye of the beholder, but that's about as simple as this expression gets.\n\nJust to double-check, we can evaluate it at `t=0` and confirm that we get `p_0`\n\n\n```python\nparticular.subs(t, 0)\n```\n\nThis solution is called the [logistic function](https://en.wikipedia.org/wiki/Population_growth#Logistic_equation).\n\nIn some places you'll see it written in a different form:\n\n$f(t) = \\frac{K}{1 + A e^{-rt}}$\n\nwhere $A = (K - p_0) / p_0$.\n\nWe can use SymPy to confirm that these two forms are equivalent. First we represent the alternative version of the logistic function:\n\n\n```python\nA = (K - p_0) / p_0\n```\n\n\n```python\nlogistic = K / (1 + A * exp(-r*t))\n```\n\nTo see whether two expressions are equivalent, we can check whether their difference simplifies to 0.\n\n\n```python\nsimplify(particular - logistic)\n```\n\nThis test only works one way: if SymPy says the difference reduces to 0, the expressions are definitely equivalent (and not just numerically close).\n\nBut if SymPy can't find a way to simplify the result to 0, that doesn't necessarily mean there isn't one. Testing whether two expressions are equivalent is a surprisingly hard problem; in fact, there is no algorithm that can solve it in general.\n\n### Exercises\n\n**Exercise:** Solve the quadratic growth equation using the alternative parameterization\n\n$\\frac{df(t)}{dt} = \\alpha f(t) + \\beta f^2(t) $\n\n\n```python\n# Solution\n\nalpha, beta = symbols('alpha beta')\n```\n\n\n```python\n# Solution\n\neq3 = Eq(diff(f(t), t), alpha*f(t) + beta*f(t)**2)\n```\n\n\n```python\n# Solution\n\nsolution_eq = dsolve(eq3)\n```\n\n\n```python\n# Solution\n\ngeneral = solution_eq.rhs\n```\n\n\n```python\n# Solution\n\nat_0 = general.subs(t, 0)\n```\n\n\n```python\n# Solution\n\nsolutions = solve(Eq(at_0, p_0), C1)\nvalue_of_C1 = solutions[0]\n```\n\n\n```python\n# Solution\n\nparticular = general.subs(C1, value_of_C1)\nparticular.simplify()\n```\n\n**Exercise:** Use [WolframAlpha](https://www.wolframalpha.com/) to solve the quadratic growth model, using either or both forms of parameterization:\n\n df(t) / dt = alpha f(t) + beta f(t)^2\n\nor\n\n df(t) / dt = r f(t) (1 - f(t)/K)\n\nFind the general solution and also the particular solution where `f(0) = p_0`.\n\n\n```python\n\n```\n", "meta": {"hexsha": "4fbd6fcb83f54c8f9a243247386767aaebe15b5f", "size": 53367, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "code/soln/chap09soln.ipynb", "max_stars_repo_name": "rsmxingu/ModSimPy", "max_stars_repo_head_hexsha": "3eeb081d534a9e3943583c8d40944625ee562e43", "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": "code/soln/chap09soln.ipynb", "max_issues_repo_name": "rsmxingu/ModSimPy", "max_issues_repo_head_hexsha": "3eeb081d534a9e3943583c8d40944625ee562e43", "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": "code/soln/chap09soln.ipynb", "max_forks_repo_name": "rsmxingu/ModSimPy", "max_forks_repo_head_hexsha": "3eeb081d534a9e3943583c8d40944625ee562e43", "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": 46.1253241141, "max_line_length": 2232, "alphanum_fraction": 0.7294582795, "converted": true, "num_tokens": 1676, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9697854159890078, "lm_q2_score": 0.9124361569052932, "lm_q1q2_score": 0.8848672779878114}} {"text": "## Introduction to Sympy\n\nWhat if you would like to perform some calculus alongside your other computations? For that. you would need a computer algebra system (CAS). Luckily, the sympy package can provide you with the tools to perform symbolic computations and then can help you numerically evaluate those results.\n\nLet's get started...\n\n\n```python\n# Typical import for numpy\n# We will use a utility function or two for now...\nimport numpy as np\n```\n\n\n```python\n#Typical import for Matplotlib\nimport matplotlib.pyplot as plt\n%matplotlib inline\n```\n\n\n```python\n# Import sympy tools\nfrom sympy import *\ninit_printing(use_latex=True)\n```\n\nNote that I imported sympy, but then also initialized the sympy printing facilities to utilize \\LaTeX. The reason for this will be obvious soon, if you haven't already figured it out.\n\nRather than have x be a vector, I need it to be a symbol. In particular, I need it to be a symbol that one would like to manipulate similar to how one uses symbols in mathematical expressions. Unlike variables which point to specific data structures, a symbol is more like how a variable is used in mathematics, and can take on values at a later time.\n\n\n```python\n# Make x a symbol\nx = symbols('x')\n```\n\n\n```python\n# Let's write an expression\ny = cos(x)\n```\n\n\n```python\n# Just provide the expression by itself,\n# and it will be printed with LaTeX!\ny\n```\n\nSo, you can define mathematical expressions in sympy, and they will be rendered using \\LaTeX.\n\nAdditionally, we can perform symbolic math on that expression. For example, let's take the derivative with respect to x using the `diff()` function.\n\n\n```python\ndydx = y.diff(x)\n```\n\n\n```python\ndydx\n```\n\nNow we have the derivative of the function with respect to x, and have solved it symbolically using sympy! Sympy has it's own matplotlib functions for plotting expressions as well...\n\n\n```python\nplot(dydx)\n```\n\nHowever, we may want more control over the sampling and plot itself. This can sometimes be better done by evaluating the function _numerically_ instead. Let's do that now...\n\n\n```python\nx_vals = np.linspace(-2*np.pi,2*np.pi,101)\ny_vals = np.array([dydx.evalf(subs=dict(x=x_val)) for x_val in x_vals])\nprint('The length of x is %d'%(len(x_vals)))\nprint('The length of y is %d'%(len(y_vals)))\n```\n\n The length of x is 101\n The length of y is 101\n\n\nHere we have used a python list comprehension to evaluate our derivative (dydx) at each of the 101 points in the $-2\\pi$ to $2\\pi$ range created by `linspace()`. The `evalf()` function allows us plug in values for our symbols. In particular, we pass the subs= argument a python dictionary object which contains a mapping from a symbol to a particular value we would like to associate with that symbol. Multiple symbols can be passed into the function using the dictionary object, so that functions with more than one symbol can be evaluated numerically.\n\n\n```python\nplt.plot(x_vals,y_vals)\nplt.title('$y=%s$'%(latex(dydx)))\nplt.xlabel('x')\nplt.ylabel('y')\nplt.show()\n```\n\nYou can also now see how the `latex()` function can be used to convert the expression we were storing in dydx into a string form recognized by \\LaTeX math mode, and therefore the `title()` function from matplotlib. It's usually much easier to control how you want your plots to look using numerical evaluation instead of using sympy's built-in plotting tools, so keep that in mind in the future.\n\n\n```python\n\n```\n", "meta": {"hexsha": "adf246d5fab6f49220e3c406542cc4e18eda9731", "size": 59135, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Introductions/Sympy Intro.ipynb", "max_stars_repo_name": "mtr3t/notebook-examples", "max_stars_repo_head_hexsha": "936f24e87e23160c73b8b4d01a37f1040e0ceb61", "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": "Introductions/Sympy Intro.ipynb", "max_issues_repo_name": "mtr3t/notebook-examples", "max_issues_repo_head_hexsha": "936f24e87e23160c73b8b4d01a37f1040e0ceb61", "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": "Introductions/Sympy Intro.ipynb", "max_forks_repo_name": "mtr3t/notebook-examples", "max_forks_repo_head_hexsha": "936f24e87e23160c73b8b4d01a37f1040e0ceb61", "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": 213.4837545126, "max_line_length": 27940, "alphanum_fraction": 0.9188128858, "converted": true, "num_tokens": 803, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9597620619801095, "lm_q2_score": 0.9219218294919745, "lm_q1q2_score": 0.8848255960576924}} {"text": "```\n#Developer : Vinay Venkatesh\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom sympy import *\n```\n\n\n```\ndef sigmoid():\n\n '''\n In the context of artificial neural networks, the Sigmoid Function is a type of activation function. The Sigmoid Function is often referred\n to as a squashing function because it limits its outputs to a range between 0 and 1. The Sigmoid Function has an \"S\" - shaped curve or sigmoid curve.\n\n This function was intended to be only for visualizing the graph of a sigmoid function.\n\n Learn More: https://deepai.org/machine-learning-glossary-and-terms/sigmoid-function\n '''\n\n x = np.linspace(-10, 10, 100) \n z = 1/(1 + np.exp(-x)) \n \n plt.plot(x, z) \n plt.xlabel(\"x\") \n plt.ylabel(\"Sigmoid(X)\") \n \n plt.show() \n```\n\n\n```\nsigmoid()\n```\n\n\n```\ndef relu():\n\n '''\n In the context of artificial neural networks, the ReLu Function is a type of activation function. The ReLu function directly outputs its input\n if it is positive. Otherwise, it outputs 0.\n\n This function was intended to be only for visualizing the graph of a ReLu function.\n\n Learn More: https://machinelearningmastery.com/rectified-linear-activation-function-for-deep-learning-neural-networks/#.\n '''\n\n x = np.linspace(-10, 10, 100) \n z = np.maximum(0, x) \n \n plt.plot(x, z) \n plt.xlabel(\"x\") \n plt.ylabel(\"ReLu(X)\") \n \n plt.show() \n```\n\n\n```\nrelu()\n```\n\n\n```\ndef constant(c):\n\n '''\n A constant function is a function whose value is the same for every input value.\n With a constant function, for any two points in the interval, a change in x results in a zero change in f(x).\n\n Learn More: https://www.varsitytutors.com/hotmath/hotmath_help/topics/constant-function\n '''\n\n fig = plt.figure()\n # Hold activation for multiple lines on same graph\n # Set x-axis range\n ax = fig.add_subplot(1, 1, 1)\n ax.spines['left'].set_position('center')\n ax.spines['bottom'].set_position('center')\n ax.spines['right'].set_color('none')\n ax.spines['top'].set_color('none')\n ax.xaxis.set_ticks_position('bottom')\n ax.yaxis.set_ticks_position('left')\n plt.xlim((-1 * (c + c), c + c))\n # Set y-axis range\n plt.ylim((-1 * (c + c), c + c))\n # Draw lines to split quadrants\n\n plt.axhline(y = c)\n\n plt.title('Constant Graph')\n\n plt.show()\n```\n\n\n```\nconstant(100)\n```\n\n\n```\ndef linear(m, b):\n\n '''\n A linear function is a function whose graph is a straight line.\n A linear function has one independent variable and one dependent variable. \n The independent variable is x and the dependent variable is y. \n The inputs, m and b stand for the slope and y intercept.\n\n The difference between `linear()` and `psflinear()` is the forms of the linear functions.\n `psflinear()` is meant to be in a y - y1 = m(x - x1) form and `linear()` is meant to be in a y = mx+b form.\n\n Learn More: https://www.mathsisfun.com/algebra/linear-equations.html\n '''\n\n #y = mx + b\n x = np.linspace(-5,5,100)\n y = m*x+b\n plt.plot(x, y, '-r', label=f'y={m}x+{b}')\n plt.title(f'Linear Graph')\n plt.xlabel('x', color='#1C2833')\n plt.ylabel('y', color='#1C2833')\n plt.legend(loc='upper left')\n plt.grid()\n plt.show()\n\n x, y = symbols('x y')\n\n equation = Eq(y, m*x+b)\n\n # Use sympy.subs() method\n result = solve(equation.subs(y, 0))\n\n for i in range(0, len(result)):\n result[i] = round(result[i].simplify().evalf(),3)\n\n print(f\"Slope: {m}\")\n print(f\"Y-Intercept: (0, {b})\")\n print(f\"X-Intercept: \")\n for i in range(0, len(result)):\n print(f\"({result[i]}, 0)\")\n```\n\n\n```\nlinear(5,2)\n```\n\n\n```\ndef psflinear(y1, m, x1):\n\n '''\n A linear function is a function whose graph is a straight line.\n A linear function has one independent variable and one dependent variable. \n The independent variable is x and the dependent variable is y. \n The inputs, y1 and m and x1 stand for a y coordinate, slope, and x coordinate.\n\n The difference between `psflinear()` and `linear()` is the forms of the linear functions.\n `psflinear()` is meant to be in a y - y1 = m(x - x1) form and `linear()` is meant to be in a y = mx+b form.\n\n Learn More: https://www.mathsisfun.com/algebra/linear-equations.html\n '''\n\n #y - y1 = m(x - x1)\n x = np.linspace(-5,5,100)\n y = m * (x - x1) + y1\n plt.plot(x, y, '-r', label=f'y-{y1}={m}(x-{x1})')\n plt.title(f'Linear Graph')\n plt.xlabel('x', color='#1C2833')\n plt.ylabel('y', color='#1C2833')\n plt.legend(loc='upper left')\n plt.grid()\n plt.show()\n\n x, y = symbols('x y')\n\n equation = Eq(y, m*(x-x1)+y1)\n\n # Use sympy.subs() method\n result = solve(equation.subs(y, 0))\n\n for i in range(0, len(result)):\n result[i] = round(result[i].simplify().evalf(),3)\n\n print(f\"Slope: {m}\")\n print(f\"Y-Intercept: (0, {y1})\")\n print(f\"X-Intercept: \")\n for i in range(0, len(result)):\n print(f\"({result[i]}, 0)\")\n```\n\n\n```\npsflinear(6, 0.5, 20)\n```\n\n\n```\ndef quadratic(a, b, c):\n\n '''\n In algebra, a quadratic function, a quadratic polynomial, a \n polynomial of degree 2, or simply a quadratic, is a polynomial \n function with one or more variables in which the highest-degree term is of the second degree. \n\n The difference between `quadratic()` and `vtquadratic()` is the forms of the quadratic functions.\n `quadratic()` is meant to be in a ax^2 + bx + c form and `vtquadratic()` is meant to be in a a(x - h)^2 + k form.\n\n Learn More: https://www.mathsisfun.com/algebra/quadratic-equation.html\n '''\n\n #Y = AX^2 + BX + C\n if a == 0:\n print(\"a cannot be 0\")\n x = np.linspace(-6,6,100)\n\n # the function, which is y = x^2 here\n y = a*x**2 + b*x + c\n vertex = (-1 * b) / (2 * a)\n vertex = a * vertex ** 2 + b * vertex + c\n\n # setting the axes at the centre\n fig = plt.figure()\n ax = fig.add_subplot(1, 1, 1)\n ax.spines['left'].set_position('center')\n ax.spines['bottom'].set_position('zero')\n ax.spines['right'].set_color('none')\n ax.spines['top'].set_color('none')\n ax.xaxis.set_ticks_position('bottom')\n ax.yaxis.set_ticks_position('left')\n if c < 0 and a < 0:\n plt.ylim((vertex + (2 * vertex), vertex * -1 + 1))\n if c < 0:\n plt.ylim((vertex -1, vertex * -1 + 1))\n elif c > 0 and c <= 999:\n plt.ylim((-5,c+c+5))\n elif c == 0:\n plt.ylim((-5,5))\n elif c >= 1000 and c <= 5000:\n plt.ylim((0,c*10))\n x = np.linspace(-20,20,100)\n elif c >= 5001 and c <= 20000:\n plt.ylim((0,c*10))\n x = np.linspace(-20,20,100)\n elif c >= 20001:\n plt.ylim((0,c*2))\n x = np.linspace(-20,20,100)\n # plot the function\n\n else:\n numList = []\n numList.append(a)\n numList.append(b)\n numList.append(c)\n for i in range(0, len(numList)):\n if numList[i] < 0:\n numList[i] = -1 * numList[i]\n\n plt.ylim((-1 * max(numList) * 5, max(numList) * 5))\n \n plt.plot(x,y, 'r', label=f'{a}x^2+{b}x+{c}')\n plt.title(f'Quadratic Graph')\n # show the plot\n \n plt.show()\n\n print(f\"Vertex: ({(-1 * b)/(2 * a)}, {vertex})\")\n print(f\"Y-Intercept: (0, {c})\")\n\n x, y = symbols('x y')\n\n equation = Eq(y, a*x**2 + b*x + c)\n\n # Use sympy.subs() method\n result = solve(equation.subs(y, 0))\n\n for i in range(0, len(result)):\n result[i] = round(result[i].simplify().evalf(),3)\n\n #print(result)\n if len(result) == 2:\n print(f\"X-Intercept: ({result[0]}, 0), ({result[1]}, 0)\")\n elif len(result) == 1:\n print(f\"X-Intercept: ({result[0]}, 0)\")\n```\n\n\n```\nquadratic(1, 5, 4)\n```\n\n\n```\ndef vtquadratic(a, h, k):\n\n '''\n In algebra, a quadratic function, a quadratic polynomial, a \n polynomial of degree 2, or simply a quadratic, is a polynomial \n function with one or more variables in which the highest-degree term is of the second degree. \n\n The difference between `quadratic()` and `vtquadratic()` is the forms of the quadratic functions.\n `quadratic()` is meant to be in a ax^2 + bx + c form and `vtquadratic()` is meant to be in a a(x - h)^2 + k form.\n\n Learn More: https://www.mathsisfun.com/algebra/quadratic-equation.html\n '''\n\n #y = a(x - h)^2 + k\n if a == 0:\n print(\"a cannot be 0\")\n\n if h < 0:\n x = np.linspace(h-5, (-1 * h) + 5,100)\n elif k < 0:\n x = np.linspace(k*2, -k*3,100)\n else:\n x = np.linspace(-6,6,100)\n y = a * (x - h)**2 + k\n vertexX = h\n vertexY = k\n fig = plt.figure()\n ax = fig.add_subplot(1, 1, 1)\n ax.spines['left'].set_position('center')\n ax.spines['bottom'].set_position('zero')\n ax.spines['right'].set_color('none')\n ax.spines['top'].set_color('none')\n ax.xaxis.set_ticks_position('bottom')\n ax.yaxis.set_ticks_position('left')\n\n if k < 0 and h < 0:\n plt.ylim((k + (2 * k), k * -1 + 1))\n elif a < 0 and k < 0:\n plt.ylim((k*3, 0))\n elif k < 0:\n plt.ylim((k * 1.5, -k * 1.5))\n elif k > 0 and k <= 999:\n plt.ylim((-k*3,k*3))\n #x = np.linspace(-20,20,100)\n elif k == 0:\n plt.ylim((-5,5))\n elif k >= 1000 and k <= 5000:\n plt.ylim((0,k*5))\n x = np.linspace(-100,100,100)\n elif k >= 5001 and k <= 20000:\n plt.ylim((0,k*3))\n x = np.linspace(-100,100,100)\n elif k >= 20001:\n plt.ylim((0,k*3))\n x = np.linspace(-100,100,100)\n\n else:\n numList = []\n numList.append(a)\n numList.append(h)\n numList.append(k)\n for i in range(0, len(numList)):\n if numList[i] < 0:\n numList[i] = -1 * numList[i]\n\n plt.ylim((-1 * max(numList) * 5, max(numList) * 5))\n\n # plot the function\n plt.plot(x,y, 'r', label=f'{a}(x-{h})^2+{k}')\n plt.title(f'Quadratic Graph')\n\n plt.show()\n\n print(f\"Vertex: ({round(h,3)}, {round(k,3)})\")\n print(f\"Y-Intercept: (0, {round(a*(0-h)**2+k,3)})\")\n\n x, y = symbols('x y')\n\n equation = Eq(y, a * (x - h)**2 + k)\n\n # Use sympy.subs() method\n result = solve(equation.subs(y, 0))\n #print(result)\n for i in range(0, len(result)):\n result[i] = result[i].simplify().evalf()\n try:\n result[i] = round(result[i], 3)\n except:\n pass\n\n if len(result) == 2:\n print(f\"X-Intercept: ({result[0]}, 0), ({result[1]}, 0)\")\n elif len(result) == 1:\n print(f\"X-Intercept: ({result[0]}, 0)\")\n```\n\n\n```\nvtquadratic(2, -6, 20)\n```\n\n\n```\ndef cubic(a, b, c, d):\n\n '''\n In mathematics, a cubic function is a function of the form f(x)=ax^3+bx^2+cx+d \n where the coefficients a, b, c, and d are real numbers, and the variable x takes real values, \n and a ≠ 0. In other words, it is both a polynomial function of degree three, and a real function.\n\n Learn More: https://www.varsitytutors.com/hotmath/hotmath_help/topics/cubic-functions\n '''\n\n #ax^3+bx^2+cx+d\n if a == 0:\n print(\"a cannot be 0\")\n\n x = np.linspace(-6,6,100)\n if d >= 1000:\n x = np.linspace(-100,100,100)\n\n # the function, which is y = x^2 here\n y = a * x**3 + b * x**2 + c * x + d\n\n # setting the axes at the centre\n fig = plt.figure()\n ax = fig.add_subplot(1, 1, 1)\n ax.spines['left'].set_position('center')\n ax.spines['bottom'].set_position('zero')\n ax.spines['right'].set_color('none')\n ax.spines['top'].set_color('none')\n ax.xaxis.set_ticks_position('bottom')\n ax.yaxis.set_ticks_position('left')\n\n if d == 0:\n plt.ylim((-5,5))\n elif b < 0 and c < 0 and d < 0:\n if -b > -c and -b > -d:\n plt.ylim((b*5,-b*5))\n elif -c > -b and -c > -d:\n plt.ylim((c*5,-c*5))\n elif -d > -c and -d > -b:\n plt.ylim((d*5,-d*5))\n elif d > 0 and c < 0:\n plt.ylim((-d*5,d*5))\n elif c > 0 and d < 0:\n if c > -d:\n plt.ylim((c*4,-c*4))\n else:\n plt.ylim((d*4,-d*4))\n elif d < 0:\n plt.ylim((d*4,-d*4))\n elif d > 0 and c > 0:\n if d > c or d == c:\n plt.ylim((-d*5,d*5))\n elif d > 0 and d <= 999:\n plt.ylim((-d*3.5,d*3.5))\n elif d >= 1000 and d <= 5000:\n plt.ylim((-d*5,d*5))\n #x = np.linspace(-100,100,100)\n elif d >= 5001 and d <= 20000:\n plt.ylim((0,d*3))\n #x = np.linspace(-100,100,100)\n elif d >= 20001:\n plt.ylim((0,d*3))\n #x = np.linspace(-100,100,100)\n\n else:\n numList = []\n numList.append(a)\n numList.append(b)\n numList.append(c)\n numList.append(d)\n for i in range(0, len(numList)):\n if numList[i] < 0:\n numList[i] = -1 * numList[i]\n\n plt.ylim((-1 * max(numList) * 5, max(numList) * 5)) \n\n # plot the function\n plt.plot(x,y, 'r', label=f'{a}x^3+{b}x^2+{c}x+{d}')\n plt.title(f'Cubic Graph')\n\n plt.show()\n\n '''vertX = (-b) / (2 * a)\n vertY = a * vertX**3 + b * vertX**2 + c*vertX + d\n print(f\"Vertex: ({vertX}, {vertY})\")'''\n print(f\"Y-Intercept: (0, {d})\")\n\n x, y = symbols('x y')\n\n equation = Eq(y, a * x**3 + b * x**2 + c * x + d)\n\n # Use sympy.subs() method\n result = solve(equation.subs(y, 0))\n for i in range(0, len(result)):\n result[i] = result[i].simplify().evalf()\n try:\n result[i] = round(result[i], 3)\n except:\n pass\n\n if len(result) == 1:\n print(f\"X-Intercept(s): ({result[0]}, 0)\")\n if len(result) == 2:\n print(f\"X-Intercept(s): ({result[0]}, 0), ({result[1]}, 0)\")\n if len(result) == 3:\n print(f\"X-Intercept(s): ({result[0]}, 0), ({result[1]}, 0), ({result[2]}, 0)\")\n```\n\n\n```\ncubic(2, -3, -3, -35)\n```\n\n\n```\ndef trigsin(z, b):\n\n '''\n In mathematics, the trigonometric functions are real functions which relate\n an angle of a right-angled triangle to ratios of two side lengths. \n\n Learn More: https://www.mathsisfun.com/sine-cosine-tangent.html\n '''\n\n x = np.linspace(-np.pi,np.pi,100)\n\n # the function, which is y = sin(x) here\n y = z * np.sin(b * x)\n yint = z * np.sin(b * 0)\n\n # setting the axes at the centre\n fig = plt.figure()\n ax = fig.add_subplot(1, 1, 1)\n ax.spines['left'].set_position('center')\n ax.spines['bottom'].set_position('center')\n ax.spines['right'].set_color('none')\n ax.spines['top'].set_color('none')\n ax.xaxis.set_ticks_position('bottom')\n ax.yaxis.set_ticks_position('left')\n if z < 0:\n plt.ylim((z*1.5,-z*1.5))\n else:\n plt.ylim((-z*1.5,z*1.5))\n # plot the functions\n plt.plot(x,y, 'b', label=f'y={z}sin({b}x)')\n plt.title('Sine Graph')\n plt.legend(loc='upper left')\n\n # show the plot\n plt.show()\n```\n\n\n```\ntrigsin(1, 0.5)\n```\n\n\n```\ndef trigcos(z, b):\n\n '''\n In mathematics, the trigonometric functions are real functions which relate\n an angle of a right-angled triangle to ratios of two side lengths. \n\n Learn More: https://www.mathsisfun.com/sine-cosine-tangent.html\n '''\n \n x = np.linspace(-np.pi,np.pi,100)\n\n # the function, which is y = sin(x) here\n y = z * np.cos(b * x)\n\n # setting the axes at the centre\n fig = plt.figure()\n ax = fig.add_subplot(1, 1, 1)\n ax.spines['left'].set_position('center')\n ax.spines['bottom'].set_position('center')\n ax.spines['right'].set_color('none')\n ax.spines['top'].set_color('none')\n ax.xaxis.set_ticks_position('bottom')\n ax.yaxis.set_ticks_position('left')\n if z < 0:\n plt.ylim((z*1.5,-z*1.5))\n else:\n plt.ylim((-z*1.5,z*1.5))\n # plot the functions\n plt.plot(x,y, 'b', label=f'y={z}cos({b}x)')\n plt.title('Cosine Graph')\n plt.legend(loc='upper left')\n\n # show the plot\n plt.show()\n```\n\n\n```\ntrigcos(2, 1)\n```\n\n\n```\ndef trigtan(z, b):\n\n '''\n In mathematics, the trigonometric functions are real functions which relate\n an angle of a right-angled triangle to ratios of two side lengths. \n\n Learn More: https://www.mathsisfun.com/sine-cosine-tangent.html\n '''\n\n x = np.linspace(-np.pi,np.pi,100)\n\n # the function, which is y = sin(x) here\n y = z * np.tan(b * x)\n\n # setting the axes at the centre\n fig = plt.figure()\n ax = fig.add_subplot(1, 1, 1)\n ax.spines['left'].set_position('center')\n ax.spines['bottom'].set_position('center')\n ax.spines['right'].set_color('none')\n ax.spines['top'].set_color('none')\n ax.xaxis.set_ticks_position('bottom')\n ax.yaxis.set_ticks_position('left')\n if z < 0:\n plt.ylim((z*1.5,-z*1.5))\n else:\n plt.ylim((-z*1.5,z*1.5))\n # plot the functions\n plt.plot(x,y, 'b', label=f'y={z}tan({b}x)')\n plt.title('Tangent Graph')\n plt.legend(loc='upper left')\n\n # show the plot\n plt.show()\n```\n\n\n```\ntrigtan(5, 2)\n```\n\n\n```\ndef quartic(a, b, c, d, e):\n\n '''\n In algebra, a quartic function is a function of the form f(x)=ax^{4}+bx^{3}+cx^{2}+dx+e, \n where a is nonzero, which is defined by a polynomial of degree four, called a quartic polynomial.\n\n Learn More: https://www.calculushowto.com/types-of-functions/quartic-function/\n '''\n\n if a == 0:\n print(\"a cannot be 0\")\n\n x = np.linspace(-6,6,100)\n if b <= -18 and b >= -29:\n x = np.linspace(b,-b,100)\n elif b <= -30:\n x = np.linspace(b/2, -b/2, 100)\n elif b >= 10 and b <= 29:\n x = np.linspace(b,-b,100)\n elif b >= 30:\n x = np.linspace(b/2, -b/2, 100)\n\n # the function, which is y = x^2 here\n y = a * x**4 + b * x**3 + c * x**2 + d*x + e\n\n # setting the axes at the centre\n fig = plt.figure()\n ax = fig.add_subplot(1, 1, 1)\n ax.spines['left'].set_position('center')\n ax.spines['bottom'].set_position('zero')\n ax.spines['right'].set_color('none')\n ax.spines['top'].set_color('none')\n ax.xaxis.set_ticks_position('bottom')\n ax.yaxis.set_ticks_position('left')\n \n #positive constraints\n if b >= -5 and b <= 0:\n plt.ylim((-6,6))\n elif b < -5 and b >= -9:\n plt.ylim((b*3,-b*3))\n elif b < -9 and b > -16:\n plt.ylim((b*-b,-b*-b))\n elif b <= -16 and b >= -27:\n plt.ylim((b*-b*3,-b*-b*3))\n elif b <= -28 and b >= -35:\n plt.ylim((b*-b*5,-b*-b*5))\n elif b <= -35 and b >= -120:\n plt.ylim((b*-b*-b/2,-b*-b*-b/2))\n elif b <= -121:\n plt.ylim((b*-b*-b,-b*-b*-b))\n\n\n #negative constraints\n elif b <= 5 and b >= 0:\n plt.ylim((-6,6))\n elif b > 5 and b <= 9:\n plt.ylim((-b*3,b*3))\n elif b > 9 and b < 16:\n plt.ylim((b*-b,-b*-b))\n elif b >= 16 and b <= 27:\n plt.ylim((b*-b*3,-b*-b*3))\n elif b >= 28 and b <= 35:\n plt.ylim((b*-b*5,-b*-b*5))\n elif b >= 35 and b <= 120:\n plt.ylim((b*b*-b/2,-b*b*-b/2))\n elif b >= 121:\n plt.ylim((b*-b*-b,-b*-b*-b))\n\n if e == 0:\n plt.ylim((-5,5))\n elif e > b:\n plt.ylim((-e*2,e*2))\n elif e * -1 > b * -1:\n plt.ylim((e*2,-e*2))\n \n else:\n numList = []\n numList.append(a)\n numList.append(b)\n numList.append(c)\n numList.append(d)\n numList.append(e)\n for i in range(0, len(numList)):\n if numList[i] < 0:\n numList[i] = -1 * numList[i]\n\n plt.ylim((-1 * max(numList) * 5, max(numList) * 5))\n\n #plt.ylim((-5,5))\n # plot the function\n plt.plot(x,y, 'r', label=f'{a}x^4+{b}x^3+{c}x^2+{d}x+{e}')\n plt.title('Quartic Graph')\n\n plt.show()\n\n print(f\"Y-Intercept: (0, {e})\")\n\n x, y = symbols('x y')\n\n equation = Eq(y, a * x**4 + b * x**3 + c * x**2 + d*x + e)\n\n # Use sympy.subs() method\n result = solve(equation.subs(y, 0))\n for i in range(0, len(result)):\n result[i] = result[i].simplify().evalf()\n try:\n result[i] = round(result[i], 3)\n except:\n pass\n\n print(f\"X-Intercept(s): \")\n for i in range(0, len(result)):\n print(f\"({result[i]}, 0)\")\n```\n\n\n```\nquartic(10, 10, 5, 5, -150)\n```\n\n\n```\ndef quintic(a, b, c, d, e, f):\n\n '''\n In algebra, a quintic function is a function of the form g(x)=ax^{5}+bx^{4}+cx^{3}+dx^{2}+ex+f,\n where a, b, c, d, e and f are members of a field, typically the rational numbers, the real numbers or the complex numbers, \n and a is nonzero. In other words, a quintic function is defined by a polynomial of degree five.\n\n Learn More: https://www.calculushowto.com/quintic-function-polynomial/\n '''\n\n if a == 0:\n print(\"a cannot be 0\")\n\n x = np.linspace(-6,6,100)\n if b <= -18 and b >= -29:\n x = np.linspace(b,-b,100)\n elif b <= -30:\n x = np.linspace(b/2, -b/2, 100)\n elif b >= 10 and b <= 29:\n x = np.linspace(b,-b,100)\n elif b >= 30:\n x = np.linspace(b/2, -b/2, 100)\n\n # the function, which is y = x^2 here\n y = a * x**5 + b * x**4 + c * x**3 + d*x**2 + e*x + f\n\n # setting the axes at the centre\n fig = plt.figure()\n ax = fig.add_subplot(1, 1, 1)\n ax.spines['left'].set_position('center')\n ax.spines['bottom'].set_position('zero')\n ax.spines['right'].set_color('none')\n ax.spines['top'].set_color('none')\n ax.xaxis.set_ticks_position('bottom')\n ax.yaxis.set_ticks_position('left')\n\n if b >= 10 and b <= 29:\n plt.ylim((-b*5,b*5))\n\n else:\n numList = []\n numList.append(a)\n numList.append(b)\n numList.append(c)\n numList.append(d)\n numList.append(e)\n numList.append(f)\n for i in range(0, len(numList)):\n if numList[i] < 0:\n numList[i] = -1 * numList[i]\n\n plt.ylim((-1 * max(numList) * 5, max(numList) * 5))\n\n plt.plot(x,y, 'r', label=f'{a}x^5+{b}x^4+{c}x^3+{d}x^2+{e}x+{f}')\n plt.title('Quintic Graph')\n\n plt.show()\n\n print(f\"Y-Intercept: (0, {f})\")\n\n x, y = symbols('x y')\n\n equation = Eq(y, a * x**5 + b * x**4 + c * x**3 + d*x**2 + e*x + f)\n\n # Use sympy.subs() method\n result = solve(equation.subs(y, 0))\n for i in range(0, len(result)):\n result[i] = result[i].simplify().evalf()\n try:\n result[i] = round(result[i], 3)\n except:\n pass\n\n print(f\"X-Intercept(s): \")\n for i in range(0, len(result)):\n print(f\"({result[i]}, 0)\")\n```\n\n\n```\nquintic(2, 4, 0, 2, 10, 4)\n```\n\n\n```\ndef sextic(a, b, c, d, e, f, g):\n\n '''\n A sextic function is a function defined by a sextic polynomial. Because they have an even degree,\n sextic functions appear similar to quartic functions when graphed, except they may possess an additional local\n maximum and local minimum each. The derivative of a sextic function is a quintic function.\n\n Learn More: https://www.calculushowto.com/sextic-function/\n '''\n\n if a == 0:\n print(\"a cannot be 0\")\n\n x = np.linspace(-6,6,100)\n if b <= -18 and b >= -29:\n x = np.linspace(b,-b,100)\n elif b <= -30:\n x = np.linspace(b/2, -b/2, 100)\n elif b >= 10 and b <= 29:\n x = np.linspace(b,-b,100)\n elif b >= 30:\n x = np.linspace(b/2, -b/2, 100)\n\n # the function, which is y = x^2 here\n y = a * x**6 + b * x**5 + c * x**4 + d*x**3 + e*x**2 + f*x + g\n\n # setting the axes at the centre\n fig = plt.figure()\n ax = fig.add_subplot(1, 1, 1)\n ax.spines['left'].set_position('center')\n ax.spines['bottom'].set_position('zero')\n ax.spines['right'].set_color('none')\n ax.spines['top'].set_color('none')\n ax.xaxis.set_ticks_position('bottom')\n ax.yaxis.set_ticks_position('left')\n\n numList = []\n numList.append(a)\n numList.append(b)\n numList.append(c)\n numList.append(d)\n numList.append(e)\n numList.append(f)\n numList.append(g)\n for i in range(0, len(numList)):\n if numList[i] < 0:\n numList[i] = -1 * numList[i]\n\n plt.ylim((-1 * max(numList) * 5, max(numList) * 5))\n\n plt.plot(x,y, 'r', label=f'{a}x^6+{b}x^5+{c}x^4+{d}x^3+{e}x^2+{f}x+{g}')\n plt.title('Sextic Graph')\n\n plt.show()\n\n print(f\"Y-Intercept: (0, {g})\")\n\n x, y = symbols('x y')\n\n equation = Eq(y, a * x**6 + b * x**5 + c * x**4 + d*x**3 + e*x**2 + f*x + g)\n\n # Use sympy.subs() method\n result = solve(equation.subs(y, 0))\n for i in range(0, len(result)):\n result[i] = result[i].simplify().evalf()\n try:\n result[i] = round(result[i], 3)\n except:\n pass\n\n print(f\"X-Intercept(s): \")\n for i in range(0, len(result)):\n print(f\"({result[i]}, 0)\")\n```\n\n\n```\nsextic(2, 4, 0, 2, 10, 4, 2)\n```\n\n\n```\ndef logFun(a, b, c, d):\n\n '''\n Logarithm (log) In mathematics, the logarithm is the inverse function to exponentiation.\n That means the logarithm of a given number x is the exponent to which another fixed number,\n the base b, must be raised, to produce that number x.\n\n Learn More: https://www.mathsisfun.com/sets/function-logarithmic.html\n '''\n\n if a == 0:\n print(\"a cannot be 0\")\n elif b == 0:\n print(\"b cannot be 0\")\n\n x = np.linspace(-6,6,100)\n\n # the function, which is y = x^2 here\n y = a * np.log(b * x ** c) + d\n\n fig = plt.figure()\n\n numList = []\n numList.append(a)\n numList.append(b)\n numList.append(c)\n numList.append(d)\n for i in range(0, len(numList)):\n if numList[i] < 0:\n numList[i] = -1 * numList[i]\n\n plt.ylim((-1 * max(numList) * 5, max(numList) * 5))\n\n plt.plot(x,y, 'r') #label=f'{a}x^6+{b}x^5+{c}x^4+{d}x^3+{e}x^2+{f}x+{g}')\n plt.title('Log Graph')\n\n plt.show()\n```\n\n\n```\nlogFun(4, 1, -2, 10)\n```\n\n\n```\ndef absVal(a, b, c):\n\n '''\n An absolute value function is a function that contains an algebraic expression within absolute value symbols. \n\n Learn More: https://www.varsitytutors.com/hotmath/hotmath_help/topics/absolute-value-functions\n '''\n\n if a == 0:\n print(\"a cannot be 0\")\n elif b == 0:\n print(\"b cannot be 0\")\n\n numList = []\n numList.append(a)\n numList.append(b)\n numList.append(c)\n for i in range(0, len(numList)):\n if numList[i] < 0:\n numList[i] = -1 * numList[i]\n\n fig = plt.figure()\n\n plt.ylim((-1 * max(numList) * 5, max(numList) * 5))\n x = np.linspace(-5 * max(numList),max(numList)*5,100)\n # the function, which is y = x^2 here\n y = a * abs(b + x) + c\n\n plt.plot(x,y, 'r') #label=f'{a}x^6+{b}x^5+{c}x^4+{d}x^3+{e}x^2+{f}x+{g}')\n plt.title('Absolute Value Graph')\n\n plt.show()\n\n```\n\n\n```\nabsVal(1, -5, 12)\n```\n", "meta": {"hexsha": "6fa70a0fbddb6461ebd2543ff80c30b5260b54c9", "size": 41952, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "examples/libmathsGraph.ipynb", "max_stars_repo_name": "alecgirman/libmaths", "max_stars_repo_head_hexsha": "d64772dfe7a5d520af792a227748d57333ba0da7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 75, "max_stars_repo_stars_event_min_datetime": "2021-02-24T03:12:19.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-31T21:46:05.000Z", "max_issues_repo_path": "examples/libmathsGraph.ipynb", "max_issues_repo_name": "alecgirman/libmaths", "max_issues_repo_head_hexsha": "d64772dfe7a5d520af792a227748d57333ba0da7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-02-24T18:37:33.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-25T17:09:12.000Z", "max_forks_repo_path": "examples/libmathsGraph.ipynb", "max_forks_repo_name": "alecgirman/libmaths", "max_forks_repo_head_hexsha": "d64772dfe7a5d520af792a227748d57333ba0da7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2021-02-24T11:03:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-18T05:56:52.000Z", "avg_line_length": 33.9692307692, "max_line_length": 166, "alphanum_fraction": 0.4208857742, "converted": true, "num_tokens": 8605, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9683812290812827, "lm_q2_score": 0.9136765251766503, "lm_q1q2_score": 0.8847871964332802}} {"text": "# The Process \nNot everytime is there a situation where $Ax = b$ has exact solutions , such is the case when we are trying to find a best fit line for a given set of datapoints , there is no direct solution for it , instead we are in search for the best possible solution.So instead of finding solutions for $Ax = b$ , we can project the $b$ vector onto the column space of $A$ so that we can get the best possible solution.The solution to the equation $A^TA\\hat{X} = A^Tb$ , gives us the best possible solution that we are looking for , which can be simplified to , $\\hat{X} = (A^TA)^{-1}A^Tb$ understanding all this with an example would give us a better idea.\n\nLet us find the best possible line passing/fitting through $(1,1),(2,2) ,(3,2)$ \ntaking the equation to be of the form $y = mx + c$ \n\n\\begin{equation}\n\\begin{pmatrix}\n1 & 1 \\\\\n2 & 2 \\\\\n3 & 2 \n\\end{pmatrix} \n\\begin{pmatrix}\nm \\\\\nc\n\\end{pmatrix}\n=\n\\begin{pmatrix}\n1 \\\\\n2 \\\\\n2\n\\end{pmatrix}\n\\end{equation}\nWhich has no solution,so our $\\hat{X}$ is given by\n\\begin{equation}\n\\begin{pmatrix}\n1 & 1 \\\\\n2 & 2 \\\\\n3 & 2 \n\\end{pmatrix}^{T} \n\\begin{pmatrix}\n1 & 1 \\\\\n2 & 2 \\\\\n3 & 2 \n\\end{pmatrix} \n\\hat{X}\n=\n\\begin{pmatrix}\n1 & 1 \\\\\n2 & 2 \\\\\n3 & 2 \n\\end{pmatrix}^{T} \n\\begin{pmatrix}\n1 \\\\\n2 \\\\\n2\n\\end{pmatrix}\n\\end{equation}\nwhich on solving gives\n\\begin{equation}\n\\begin{pmatrix}\n\\hat{m} \\\\\n\\hat{c}\n\\\n\\end{pmatrix}\n=\n\\begin{pmatrix}\n\\frac{1}{2} \\\\\n\\frac{2}{3}\n\\\n\\end{pmatrix}\n\\end{equation}\nThus the best fitting line is given by\n$ y = \\frac{1}{2}x+\\frac{2}{3} $\n\nThis exact process is done by the below given python fxn.\n\n\n```python\nimport numpy as np\nimport pandas as pd\nfrom matplotlib import pyplot as plt\n```\n\n\n```python\ndef LeastSquares(points):\n A = []\n b = []\n #Extracting the A,b matrix from the given set of points\n for p in points:\n A.append([1,p[0]])\n b.append([p[1]])\n A = np.array(A)\n b = np.array(b)\n points = np.array(points)\n #finding the parameters m and c\n x = np.matmul(np.matmul(np.linalg.inv(np.matmul(A.T,A)),A.T),b)\n #drawing the fitting line\n inp_space = np.linspace(points[:,0].min(),points[:,0].max(),1000)\n out = (inp_space)*x[1]+x[0]\n plt.plot(inp_space,out)\n for i in points:\n plt.scatter(i[0],i[1])\n plt.title(f\"Y = {x[1]}x+{x[0]}\")\n```\n\n\n```python\nA = LeastSquares([(0,0),(-1,1),(2,3),(3,4)]) # takes in list of points to fit line on.\n```\n\n# Learn more on\n[MIT OCW LECTURE](https://ocw.mit.edu/courses/mathematics/18-06-linear-algebra-spring-2010/video-lectures/lecture-16-projection-matrices-and-least-squares) \n\n[Least square Approximations](http://math.mit.edu/~gs/linearalgebra/ila0403.pdf)\n", "meta": {"hexsha": "5aefb101235bd1f06d103563648bdc0e8a72945d", "size": 18907, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Linearreg.ipynb", "max_stars_repo_name": "B20204/Professorpy", "max_stars_repo_head_hexsha": "572c735c360c19c55f7554245c65975505e5e237", "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": "Linearreg.ipynb", "max_issues_repo_name": "B20204/Professorpy", "max_issues_repo_head_hexsha": "572c735c360c19c55f7554245c65975505e5e237", "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": "Linearreg.ipynb", "max_forks_repo_name": "B20204/Professorpy", "max_forks_repo_head_hexsha": "572c735c360c19c55f7554245c65975505e5e237", "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": 112.5416666667, "max_line_length": 14268, "alphanum_fraction": 0.8531760724, "converted": true, "num_tokens": 873, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.951863227517834, "lm_q2_score": 0.9294404116305639, "lm_q1q2_score": 0.8847001500001728}} {"text": "```python\nimport numpy as np\nfrom numpy.linalg import det, inv, matrix_rank, eig\nfrom sympy import Matrix, symbols\n\na = np.array([[1, 2], [3, 4]])\na\n```\n\n\n\n\n array([[1, 2],\n [3, 4]])\n\n\n\n# Common matrix operations\n\n## Multiplication\n***With a number*** (aka scalar, because it scales the matrix).\n\n\n```python\n5 * a\n```\n\n\n\n\n array([[ 5, 10],\n [15, 20]])\n\n\n\n**With another matrix.**\n\nIt can be viewed as a linear transformation of a coordinate system. Example of 90 degree rotation transform:\n\n\n\n```python\ntransform = np.array([[0,-1],[1,0]])\ni = np.array([1,0])\nnp.matmul(transform,i)\n```\n\n\n\n\n array([0, 1])\n\n\n\nMultiplying two square matrices can be viewed as composing two transforms. The one on the right is applied first. Example of rotation then shear transforms:\n\n\n```python\ntransform = np.matmul(np.array([[1,1],[0,1]]), np.array([[0,-1],[1,0]]))\ntransform\n```\n\n\n\n\n array([[ 1, -1],\n [ 1, 0]])\n\n\n\n**Identity matrix** multiplication preserves the original matrix\n\n\n```python\nnp.matmul(a,np.eye(2))\n```\n\n\n\n\n array([[1., 2.],\n [3., 4.]])\n\n\n\n## Dot product\nDot product between two vectors (1d matrices or tensors) gives you an idea about their orientation:\n\n- if dot product is zero -> perpendicular, negative ->opposite directions (angle > 90 degrees)\n\nIt is also a way to map vectors into a different space (e.g. lower/higher dimensional). For example the projection of a 2d vector to a 1d line. Dot product is just a shorthand for multiply a and b transponse: $A \\bullet B = AB^T$\n\n\n```python\na * a\n```\n\n\n\n\n array([[ 1, 4],\n [ 9, 16]])\n\n\n\n## Transpose\nRows become columns and vice versa. If $A=A^T$ then A is **symmetric** (implies that A is square).\n\n\n```python\na.T\n```\n\n\n\n\n array([[1, 3],\n [2, 4]])\n\n\n\n## Determinant\nIf determinant is zero, the matrix is called **singular**. It means that the matrix vectors are linearly dependent and that dimensionality of space is reduced. Negative determinant means that the orientation of space is inverted (e.g. flipped). The absolute value of the determinant shows how a shape's size will change.\n\n\n```python\ndet(a) # a flips space and increases area twofold\n```\n\n## Inverse matrices\nNon-singular matrices (det != 0) are invertible: $A^{-1}A=I$, where $I$ is the identity matrix (np.eye)\n\n\n```python\ninv(a)\n```\n\n\n\n\n array([[-2. , 1. ],\n [ 1.5, -0.5]])\n\n\n\n\n```python\nnp.matmul(a,inv(a)) #shall give the identity matrix, but there is some quantization error\n```\n\n\n\n\n array([[1.0000000e+00, 0.0000000e+00],\n [8.8817842e-16, 1.0000000e+00]])\n\n\n\n## Rank\nThe max number of linearly independent rows or columns in the matrix\n\n\n```python\n#matrix_rank(a) #2\n#matrix_rank(np.array([[1,0],[1,0]])) #1\ndet(np.array([[15.000000000000001,1],[30,2]]))\n```\n\n## Echelon form\nNumerical algebra is not very suitable for finding exact solutions to the reduced row echelon form. Symbolic algebra with sympy might be a better fit here.\n\nhttp://numpy-discussion.10968.n7.nabble.com/Reduced-row-echelon-form-td16486.html\n\nhttp://docs.sympy.org/0.7.5/tutorial/matrices.html\n\n\n```python\nA = Matrix([[1, -1], [3, 4], [0, 2]])\nA.rref()\n```\n\n## Cross product\nIn 3D space, cross product of two vectors, v1 and v2, yields another vector that is perpendicular to the two. The resulting vector is computed by constructing the determinant with the identity vector $(\\hat{i}, \\hat{j}, \\hat{k})$ in the first column and v1 and v2 in the second and third respectively.\n\n$A \\times B$\n\n\n\n```python\nv1 = Matrix([1,2,4])\nv2 = Matrix([3,2,5])\n\ni,j,k = symbols('i j k')\nresult = Matrix([[i,v1[0],v2[0]],[j,v1[1],v2[1]],[k,v1[2],v2[2]]]).det()\nprint(result)\n[result.subs([(i,1),(j,0),(k,0)]), result.subs([(i,0),(j,1),(k,0)]), result.subs([(i,0),(j,0),(k,1)])]\n```\n\n## Eigenvalues & Eigenvectors\n\nGiven a transformation matrix $A$ if there exists a vector $\\vec{v}$ and a scalar $\\lambda$, such that: \n\n$A\\vec{v} = \\lambda\\vec{v} \\Rightarrow A\\vec{v} = \\lambda I\\vec{v} \\Rightarrow (A - \\lambda I)\\vec{v} = 0 \\Rightarrow $\n\n$$det(A - \\lambda I) = 0$$\n\nThen all possible values of $\\lambda$ that satisfy the equation are called eigenvalues. Each of these values corresponds to one or more eigenvectors $\\vec{v}$, which won't change their span after the transformation with matrix $A$.\n\n**Eigenbasis** with respect to the transformation A is the set of new basis vectors (e.g. at least two in 2d) that are also eigenvectors. Transforming the original transformation matrix $A$ to $A'$ in the new basis guarantees that $A'$ will be diagonal.\n\n\n```python\n#eig(np.array([[3,1],[0,2]]))\nm = Matrix([[3,1],[0,2]])\nprint(m.eigenvals()) # value:algebraic multiplicity\nm.eigenvects() # eigenvalue, algebraic multiplicity, eigenvector\n```\n\n## Null space\nIn non-full rank matrices, this is the set of vectors that will get reduced to a line or a point. In other words, this is the space of all possible solutions of the system of equations (no single solution exists because det=0 & rank< full rank)\n\n## Frobenius normal form\n## Matrix equivalence\n## Matrix congruence\n## Singular value decomposition\n\nhttps://www.youtube.com/watch?v=P5mlg91as1c\n\n## PCA\n## SVD\n## Jacobian matrix\nJacobian is the matrix of partial derivatives of a $ R^n \\longrightarrow R^m $ function. It has $m$ columns - one for each output (dependent) variable and $n$ rows - one for each input (independent) variable. Thus each column is the gradient of the respective dependent variable. \n\nhttps://www.value-at-risk.net/functions/\n\n\n```python\n\n```\n\n## Conjugate transponse\nConjugate transponse (Hermitian transponse) of a matrix with complex entries is obtained by first taking the transponse of the matrix and then taking the complex conjugate of each entry:\n\n$ A^* = \\overline{A^T}$, where complex conjugate is the element-wise operation: $a + ib \\Rightarrow a - ib$.\n\n\n# Some interesting matrix properties\n\n## Similar\nTwo **square** matrices $A$ and $B$ are similar if $B=P^{-1}AP$ and $P$ is invertible.\n\n## Diagonalizable\n\n## Normal\nA complex square matrix is normal if: $A^*A=AA^*$. For real matrices this reduces to: $A^TA=AA^T$\n\n\n\n\n\n\n# Unitary matrices\nA **complex square** matrix is unitary if its inverse is equal to its conjugate transponse: $А^{*} = A^{-1} \\implies A^*A=AA^*=I$\n\nFor real valued matrices, the unitary is called orthogonal: $A^{T}=A^{-1} \\implies A^TA=AA^T=I$\n\nUnitary matrices preserve the euclidian norm (length) of a vector x during multiplication: $\\lVert x \\rVert = \\lVert Ax \\rVert$\n\n\n\n```python\nnp.conj(a).T\n```\n\n\n\n\n array([[1, 3],\n [2, 4]], dtype=int32)\n\n\n\n\n```python\na = np.array([[2,-1],[0.5,-0.5]])\nnp.matmul(a,a.T)\n```\n\n\n\n\n array([[5. , 1.5],\n [1.5, 0.5]])\n\n\n\n\n```python\nx = np.array([[1,2],[3,4],[5,6]])\nnp.matmul(x,x.T) # symmetrize\n```\n\n\n\n\n array([[ 5, 11, 17],\n [11, 25, 39],\n [17, 39, 61]])\n\n\n\n\n```python\n# \n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "355f5e77f6b5cb74118c6701446c86a6d05887be", "size": 21881, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "ml/Matrix cheatsheet.ipynb", "max_stars_repo_name": "pgenevski/notebooks", "max_stars_repo_head_hexsha": "186b0e41d1424cb33bb1dea8905c4aec3a7b4cc5", "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": "ml/Matrix cheatsheet.ipynb", "max_issues_repo_name": "pgenevski/notebooks", "max_issues_repo_head_hexsha": "186b0e41d1424cb33bb1dea8905c4aec3a7b4cc5", "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/Matrix cheatsheet.ipynb", "max_forks_repo_name": "pgenevski/notebooks", "max_forks_repo_head_hexsha": "186b0e41d1424cb33bb1dea8905c4aec3a7b4cc5", "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.7149460709, "max_line_length": 2528, "alphanum_fraction": 0.6323294182, "converted": true, "num_tokens": 2042, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9539660936744719, "lm_q2_score": 0.9273632991598454, "lm_q1q2_score": 0.8846731439165884}} {"text": "### Computing for Mathematics - Mock individual coursework\n\nThis jupyter notebook contains questions that will resemble the questions in your individual coursework.\n\n**Important** Do not delete the cells containing: \n\n```\n### BEGIN SOLUTION\n\n### END SOLUTION\n```\n\nwrite your solution attempts in those cells.\n\n**If you would like to** submit this notebook:\n\n- Change the name of the notebook from `main` to: ``. For example, if your student number is `c1234567` then change the name of the notebook to `c1234567`.\n- Write all your solution attempts in the correct locations;\n- Save the notebook (`File>Save As`);\n- Follow the instructions given in class/email to submit.\n\n#### Question 1\n\nOutput the evaluation of the following expressions exactly.\n\na. \\\\(\\frac{(9a^2bc^4) ^ {\\frac{1}{2}}}{6ab^{\\frac{3}{2}}c}\\\\)\n\n\n```python\n### BEGIN SOLUTION\nimport sympy as sym\na, b, c = sym.Symbol(\"a\"), sym.Symbol(\"b\"), sym.Symbol(\"c\")\n\nsym.expand((9 * a ** 2 * b * c ** 4) ** (sym.S(1) / 2) / (6 * a * b ** (sym.S(3) / 2) * c))\n### END SOLUTION\n```\n\n\n\n\n$\\displaystyle \\frac{\\sqrt{a^{2} b c^{4}}}{2 a b^{\\frac{3}{2}} c}$\n\n\n\nb. \\\\((2 ^ {\\frac{1}{2}} + 2) ^ 2 - 2 ^ {\\frac{5}{2}}\\\\)\n\n\n```python\n### BEGIN SOLUTION\nsym.expand((sym.S(2) ** (sym.S(1) / 2) + 2) ** 2 - 2 ** (sym.S(5) / 2))\n### END SOLUTION\n```\n\n\n\n\n$\\displaystyle 6$\n\n\n\n3. \\\\((\\frac{1}{8}) ^ {\\frac{4}{3}}\\\\)\n\n\n```python\n### BEGIN SOLUTION\n(sym.S(1) / 8) ** (sym.S(4) / 3)\n### END SOLUTION\n```\n\n\n\n\n$\\displaystyle \\frac{1}{16}$\n\n\n\n### Question 2\n\nWrite a function `expand` that takes a given mathematical expression and returns the expanded expression.\n\n\n```python\ndef expand(expression):\n ### BEGIN SOLUTION\n \"\"\"\n Take a symbolic expression and expands it.\n \"\"\"\n return sym.expand(expression)\n ### END SOLUTION\n```\n\n### Question 3\n\nThe matrix \\\\(D\\\\) is given by \\\\(D = \\begin{pmatrix} 1& 2 & a\\\\ 3 & 1 & 0\\\\ 1 & 1 & 1\\end{pmatrix}\\\\) where \\\\(a\\ne 2\\\\).\n\na. Create a variable `D` which has value the matrix \\\\(D\\\\).\n\n\n```python\n### BEGIN SOLUTION\na = sym.Symbol(\"a\")\nD = sym.Matrix([[1, 2, a], [3, 1, 0], [1, 1, 1]])\n### END SOLUTION\n```\n\nb. Create a variable `D_inv` with value the inverse of \\\\(D\\\\).\n\n\n```python\n### BEGIN SOLUTION\nD_inv = D.inv()\n### END SOLUTION\n```\n\nc. Using `D_inv` **output** the solution of the following system of equations:\n\n\\\\[\n\\begin{array}{r}\n x + 2y + 4z = 3\\\\\n 3x + y = 4\\\\\n x + y + z = 1\\\\\n\\end{array}\n\\\\]\n\n\n```python\n### BEGIN SOLUTION\nb = sym.Matrix([[3], [4], [1]])\nsym.simplify(D.inv() @ b).subs({a: 4})\n### END SOLUTION\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}\\frac{7}{3}\\\\-3\\\\\\frac{5}{3}\\end{matrix}\\right]$\n\n\n\n### Question 4\n\nDuring a game of frisbee between a handler and their dog the handler chooses to randomly select if they throw using a backhand or a forehand: 25% of the time they will throw a backhand.\n\nBecause of the way their dog chooses to approach a flying frisbee they catch it with the following probabilities:\n\n- 80% of the time when it is thrown using a backhand\n- 90% of the time when it is thrown using a forehand\n\na. Write a function `sample_experiment()` that simulates a given throw and returns the throw type (as a string with value `\"backhand\"` or `\"forehand\"`) and whether it was caught (as a boolean: either `True` or `False`).\n\n\n```python\nimport random\n\n\ndef sample_experiment():\n \"\"\"\n Returns the throw type and whether it was caught\n \"\"\"\n ### BEGIN SOLUTION\n if random.random() < .25:\n throw = \"backhand\"\n probability_of_catch = .8\n else:\n throw = \"forehand\"\n probability_of_catch = .9\n \n caught = random.random() < probability_of_catch\n ### END SOLUTION\n return throw, caught\n```\n\nb. Using 1,000,000 samples create a variable `probability_of_catch` which has value an estimate for the probability of the frisbee being caught.\n\n\n```python\n### BEGIN SOLUTION\nnumber_of_repetitions = 1_000_000\nrandom.seed(0)\nsamples = [sample_experiment() for repetition in range(number_of_repetitions)]\nprobability_of_catch = sum(catch is True for throw, catch in samples) / number_of_repetitions\n### END SOLUTION\n```\n\nc. Using the above, create a variable `probability_of_forehand_given_drop` which has value an estimate for the probability of the frisbee being thrown with a forehand given that it was not caught.\n\n\n```python\n### BEGIN SOLUTION\nsamples_with_drop = [(throw, catch) for throw, catch in samples if catch is False]\nnumber_of_drops = len(samples_with_drop)\nprobability_of_forehand_given_drop = sum(throw == \"forehand\" for throw, catch in samples_with_drop) / number_of_drops\n### END SOLUTION\n```\n", "meta": {"hexsha": "e239d74c0078686106f65438c41d87d72132f2ca", "size": 7309, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "assets/assessment/mock/solution.ipynb", "max_stars_repo_name": "drvinceknight/cfm", "max_stars_repo_head_hexsha": "06977f5c1ba37590b17a8d2a22f57e3575875b3b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2016-08-25T01:05:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-04T16:17:06.000Z", "max_issues_repo_path": "assets/assessment/mock/solution.ipynb", "max_issues_repo_name": "drvinceknight/cfm", "max_issues_repo_head_hexsha": "06977f5c1ba37590b17a8d2a22f57e3575875b3b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 88, "max_issues_repo_issues_event_min_datetime": "2016-08-24T20:08:15.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-19T23:26:14.000Z", "max_forks_repo_path": "assets/assessment/mock/solution.ipynb", "max_forks_repo_name": "drvinceknight/cfm", "max_forks_repo_head_hexsha": "06977f5c1ba37590b17a8d2a22f57e3575875b3b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2016-09-22T12:36:03.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-13T13:21:30.000Z", "avg_line_length": 7309.0, "max_line_length": 7309, "alphanum_fraction": 0.6323710494, "converted": true, "num_tokens": 1333, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.953966093674472, "lm_q2_score": 0.9273632881185803, "lm_q1q2_score": 0.884673133383596}} {"text": "# Exercise 2\nWrite a function to compute the roots of a mathematical equation of the form\n\\begin{align}\n ax^{2} + bx + c = 0.\n\\end{align}\nYour function should be sensitive enough to adapt to situations in which a user might accidentally set $a=0$, or $b=0$, or even $a=b=0$. For example, if $a=0, b\\neq 0$, your function should print a warning and compute the roots of the resulting linear function. It is up to you on how to handle the function header: feel free to use default keyword arguments, variable positional arguments, variable keyword arguments, or something else as you see fit. Try to make it user friendly.\n\nYour function should return a tuple containing the roots of the provided equation.\n\n**Hint:** Quadratic equations can have complex roots of the form $r = a + ib$ where $i=\\sqrt{-1}$ (Python uses the notation $j=\\sqrt{-1}$). To deal with complex roots, you should import the `cmath` library and use `cmath.sqrt` when computing square roots. `cmath` will return a complex number for you. You could handle complex roots yourself if you want, but you might as well use available libraries to save some work.\n\n\n```python\nimport numpy as np\nimport cmath\n```\n\n\n```python\ndef find_roots(a, b, c):\n if 0 == a:\n if 0 == b:\n print('Warning: wrong input! a and b cannot be zero simultaneously!')\n if 0 == c:\n print('All x')\n return None\n else:\n print('Warning: a = 0; it is a linear function!')\n return [-c/b]\n else:\n return [(-b+cmath.sqrt(b*b-4*a*c))/(2*a), (-b-cmath.sqrt(b*b-4*a*c))/(2*a)] \n```\n\n\n```python\n# Test 1\nroots = find_roots(1, 1, 1)\nif roots:\n print('The root(s) is (are) %s.' %', '.join([str(root) for root in roots]))\n```\n\n The root(s) is (are) (-0.5+0.8660254037844386j), (-0.5-0.8660254037844386j).\n\n\n\n```python\n# Test 2\nroots = find_roots(1, 2, 1)\nif roots:\n print('The root(s) is (are) %s.' %', '.join([str(root) for root in roots]))\n```\n\n The root(s) is (are) (-1+0j), (-1+0j).\n\n\n\n```python\n# Test 3\nroots = find_roots(1, 2, 1)\nif roots:\n print('The root(s) is (are) %s.' %', '.join([str(root) for root in roots]))\n```\n\n The root(s) is (are) (-1+0j), (-1+0j).\n\n\n\n```python\n# Test 4\nroots = find_roots(0, 0, 0)\nif roots:\n print('The root(s) is (are) %s.' %', '.join([str(root) for root in roots]))\n```\n\n Warning: wrong input! a and b cannot be zero simultaneously!\n All x\n\n\n\n```python\n# Test 5\nroots = find_roots(0, 1, 1)\nif roots:\n print('The root(s) is (are) %s.' %', '.join([str(root) for root in roots]))\n```\n\n Warning: a = 0; it is a linear function!\n The root(s) is (are) -1.0.\n\n\n\n```python\n# Test 6\nroots = find_roots(0, 0, 1)\nif roots:\n print('The root(s) is (are) %s.' %', '.join([str(root) for root in roots]))\n```\n\n Warning: wrong input! a and b cannot be zero simultaneously!\n\n", "meta": {"hexsha": "004b3c8d194546251484a46c6dd684f30c859ca3", "size": 5236, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "lectures/L5/Exercise_2-final.ipynb", "max_stars_repo_name": "xuwd11/cs207_Weidong_Xu", "max_stars_repo_head_hexsha": "00442657239c7a4040501bf7fa0f6697c731fe94", "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": "lectures/L5/Exercise_2-final.ipynb", "max_issues_repo_name": "xuwd11/cs207_Weidong_Xu", "max_issues_repo_head_hexsha": "00442657239c7a4040501bf7fa0f6697c731fe94", "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/L5/Exercise_2-final.ipynb", "max_forks_repo_name": "xuwd11/cs207_Weidong_Xu", "max_forks_repo_head_hexsha": "00442657239c7a4040501bf7fa0f6697c731fe94", "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.4444444444, "max_line_length": 495, "alphanum_fraction": 0.5120320856, "converted": true, "num_tokens": 878, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9693241991754918, "lm_q2_score": 0.9124361682155118, "lm_q1q2_score": 0.8844464580542553}} {"text": "# K-Means Clustering algorithm \n\n* *What is clustering?*\n\n\n* The K-means algorithm is summarized as: \n * Set number of clusters, M\n * Initialize cluster centers\n * Do until Change in cluster centers is small:\n * FOR i = 1 to N\n * Determine the closest representative, $\\Theta_j$, for $\\mathbf{x}_i$\n * Set label for data point $i$ to $j$\n * FOR j = 1 to M\n * Update cluster representative $\\Theta_j$ to the mean of the points with cluster label $j$\n\n\n\n* The objective function for the K-means clustering algorithm is\n\\begin{equation}\nJ(\\Theta, U) = \\sum_{i=1}^N \\sum_{j=1}^m u_{ij}\\left\\| \\mathbf{x}_i - \\theta_j \\right\\|^2\n\\end{equation}\nwhere $u_{ij} \\in \\{0,1\\}$ and is '1' for the $j$ index corresponding to the class label assigned to data point $\\mathbf{x}_i$ and zero otherwise. The $\\theta_j$ vector is the $j^{th}$ cluster representative.\n* *How would you optimize this objective function?*\n\n\n\n* Does the K-means algorithm find the *globally optimal* solution (i.e., the cluster centers and assignments that globally minimize the objective function)? \n* Does the K-means algorithm make any assumptions on cluster shape? \n* Given a data set with an unknown number of clusters, come up with a strategy for determining the ``right'' number of clusters.\n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn import datasets \nfrom scipy import spatial\n%matplotlib inline\n\ndef KMeans(X, C):\n MaxIter = 10000;\n StopThresh = 1e-5;\n\n #Initialize Cluster Centers by drawing randomly from input data (can use other\n # methods for initialization...)\n N = X.shape[0] #number of data points\n d = X.shape[1] #dimensionality\n rp = np.random.permutation(N); #random permutation of numbers 1:N\n centers = X[rp[0:C],:]; #select first M data points sorted according to rp\n\n diff = 1e100;\n iter = 0;\n while((diff > StopThresh) & (iter < MaxIter)):\n #Assign data to closest cluster representative (using Euclidean distance)\n D = spatial.distance.cdist(X, centers)\n L = np.argmin(D, axis=1)\n \n #Update cluster centers\n centersPrev = centers.copy()\n for i in range(C):\n centers[i,:] = np.mean(X[L == i,:], axis=0)\n\n #Update diff & iteration count for stopping criteria\n diff = np.linalg.norm(centersPrev - centers)\n iter = iter+1\n return centers, L\n\n```\n\n\n```python\nn_samples = 1500\nn_clusters = 3\n\n# Make Blob Data\nX, y_blobs = datasets.make_blobs(n_samples=n_samples)\n\n#Cluster\ncenters, L = KMeans(X,n_clusters)\n\n#Plot Results\nplt.figure(figsize=(12, 12))\nplt.subplot(221)\nplt.scatter(X[:, 0], X[:, 1], c=y_blobs)\nplt.title(\"Blobs with True Labels\")\nplt.subplot(222)\nplt.scatter(X[:, 0], X[:, 1], c=L)\nplt.title(\"Clustered Blobs\")\n\n\n```\n\n\n```python\n# Anisotropicly distributed data\n#some examples from: http://scikit-learn.org/stable/auto_examples/cluster/plot_kmeans_assumptions.html\n\nn_samples = 1500\nn_clusters = 3\n\n#generate data\ntransformation = [[ 0.60834549, -0.63667341], [-0.40887718, 0.85253229]]\nX, y = datasets.make_blobs(n_samples=n_samples)\nX = np.dot(X, transformation)\n\n#cluster data\ncenters, L = KMeans(X,n_clusters)\n\n#plot data\nplt.figure(figsize=(12, 12))\nplt.subplot(221)\nplt.scatter(X[:, 0], X[:, 1], c=y)\nplt.title(\"Data with True Labels\")\nplt.subplot(222)\nplt.scatter(X[:, 0], X[:, 1], c=L)\nplt.title(\"Clustered Results\")\n\n```\n\n\n```python\n# Data with different variances\n\nn_samples = 1500\nn_clusters = 3\n\n#generate data\nX, y = datasets.make_blobs(n_samples=n_samples,cluster_std=[1.0, 2.5, 0.5])\n\n#cluster data\ncenters, L = KMeans(X,n_clusters)\n\n#plot data\nplt.figure(figsize=(12, 12))\nplt.subplot(221)\nplt.scatter(X[:, 0], X[:, 1], c=y)\nplt.title(\"Data with True Labels\")\nplt.subplot(222)\nplt.scatter(X[:, 0], X[:, 1], c=L)\nplt.title(\"Clustered Results\")\n \n```\n\n\n```python\n# Uneven sized blobs\n\nn_samples = 1500\nn_clusters = 3\n\n#generate data\nX, y = datasets.make_blobs(n_samples=n_samples)\nX = np.vstack((X[y == 0][:500], X[y == 1][:100], X[y == 2][:10]))\ny = np.hstack((np.ones(500), 2*np.ones(100), 3*np.ones(10)))\n \n#cluster data\ncenters, L = KMeans(X,n_clusters)\n\n#plot data\nplt.figure(figsize=(12, 12))\nplt.subplot(221)\nplt.scatter(X[:, 0], X[:, 1], c=y)\nplt.title(\"Data with True Labels\")\nplt.subplot(222)\nplt.scatter(X[:, 0], X[:, 1], c=L)\nplt.title(\"Clustered Results\")\n \n```\n\n\n```python\n# Moons\n\nn_samples = 1500\nn_clusters = 3\n\n#generate data\nX, y = datasets.make_moons(n_samples=n_samples, noise=.05)\n\n#cluster data\ncenters, L = KMeans(X,n_clusters)\n\n#plot data\nplt.figure(figsize=(12, 12))\nplt.subplot(221)\nplt.scatter(X[:, 0], X[:, 1], c=y)\nplt.title(\"Data with True Labels\")\nplt.subplot(222)\nplt.scatter(X[:, 0], X[:, 1], c=L)\nplt.title(\"Clustered Results\")\n \n```\n\n\n```python\n# Circles\n\nn_samples = 1500\nn_clusters = 3\n\n#generate data\nX, y = datasets.make_circles(n_samples=n_samples, factor=.5, noise=.05)\n\n#cluster data\ncenters, L = KMeans(X,n_clusters)\n\n#plot data\nplt.figure(figsize=(12, 12))\nplt.subplot(221)\nplt.scatter(X[:, 0], X[:, 1], c=y)\nplt.title(\"Data with True Labels\")\nplt.subplot(222)\nplt.scatter(X[:, 0], X[:, 1], c=L)\nplt.title(\"Clustered Results\")\n \n```\n\n# Cluster Validity\n\n* *How would you evaluate clustering results?* As discussed and illustrated in our first lecture, clustering results can be subjective and/or the desired result can be application dependent. One approach is the use of *cluster validity indices*\n\n* There are many cluster validity indices in the literature. \n\n* Cluster validity measures are used for a number of different goals. For example, cluster validity metrics can be used to compare clustering results, try to determine the *correct* number of clusters, try to select the *correct* parameter settings, try to evaluate the appropriateness of the clustering result based on the data only (and not using another result or \"ground truth\" data). \n\n\n* *External index* is used to measure how well a clustering result matches a set of supplied class labels. This can be used to compare to \"ground truth\" as well as to compare different clustering results to see how similar they are (and how stable a particular clustering is on a data set across parameter settings and/or algorithms). An example of an external index is the Rand index: \n\nGiven a set of $n$ data points, $\\mathbf{X} = \\{x_1, \\ldots, x_n\\}$ and two partitions (i.e., clustering results) of $\\mathbf{X}$ to compare, $C = \\{C_1, \\ldots, C_r\\}$, a partition of $\\mathbf{X}$ into $r$ partitions, and $D = \\{D_1, \\ldots, D_s\\}$, a partition of $\\mathbf{X}$ into $s$ partitions, define the following:\n* $a$, the number of pairs of elements in $X$ that are in the same subset in $C$ and in the same subset in $D$\n* $b$, the number of pairs of elements in $X$ that are in different subsets in $C$ and in different subsets in $D$\n* $c$, the number of pairs of elements in $X$ that are in the same subset in $C$ and in different subsets in $D$\n* $d$, the number of pairs of elements in $X$ that are in different subsets in $C$ and in the same subset in $D$\n\nThe Rand index, $R$, is:\n$R = \\frac{a+b}{a+b+c+d}$\nIntuitively, $a + b$ can be considered as the number of agreements between $C$ and $D$ and $c + d$ as the number of disagreements between $C$ and $D$. The numerator is the number of agreements and the denominator is the total number of pairs (agreements and disagreements)\n\n* There are many other external cluster validity indices, the Rand index is just one example!\n\n\n\n\n* An *Internal index* is used to measure how well a clustering result is without using any external labels or other results. \n\n* Many internal indices are based on measuring within-cluster vs. between-cluster variation with the idea being within cluster variation should be small and between cluster variation should be large. \n\n* One example of an internal index is the Dunn's index: \n\n\nLet $C_i$ be a cluster of vectors. Let $x$ and $y$ be any two $n$ dimensional feature vectors assigned to the same cluster $C_i$.\n\n$\\Delta_i = \\text{max}_{x,y \\in C_i} d(x,y)$ calculates the maximum distance in a cluster.\n\n\n Let $\\delta(C_i,C_j)$ be the intercluster distance metric, between clusters $C_i$ and $C_j$. This intercluster distance can be computed in a number of ways. For example, the minumum distance between any two points in the cluster or, alternatively, the distance between the cluster means.\n\nWith the above notation, if there are $m$ clusters, then the Dunn Index for the set is defined as:\n\n$\\mathit{D}_m = \\frac{ \\underset{ 1 \\leqslant i < j \\leqslant m}{\\text{min}} \\left.\\delta(C_i,C_j)\\right.}{ \\underset{ 1 \\leqslant k \\leqslant m}{\\text{max}} \\left.\\Delta_k\\right.}$\n\nLike the intercluster distance, alternative measures for the internal cluster distance can be used. Some examples are: \n\n$\\Delta_i = \\dfrac{1}{|C_i| (|C_i| - 1)} {\\sum}_{x , y \\in C_i, x \\neq y} d(x,y)$ calculates the mean distance between all pairs in a cluster. \n\n$\\Delta_i = \\dfrac{\\underset{x \\in C_i}{\\sum} d(x,\\mu)}{|C_i|} , \\mu = \\dfrac{\\underset{x \\in C_i}{\\sum} x}{|C_i|}$ calculates the distance of all the points from the mean.\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "ede8da0e6a4001bb698676e4004da340899e1350", "size": 13243, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Lecture08_KMeans/K-Means Clustering.ipynb", "max_stars_repo_name": "Michael-Monaldi/LectureNotes", "max_stars_repo_head_hexsha": "3afc1b4473aa91297ac4cf515a77a578547cca5f", "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": "Lecture08_KMeans/K-Means Clustering.ipynb", "max_issues_repo_name": "Michael-Monaldi/LectureNotes", "max_issues_repo_head_hexsha": "3afc1b4473aa91297ac4cf515a77a578547cca5f", "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": "Lecture08_KMeans/K-Means Clustering.ipynb", "max_forks_repo_name": "Michael-Monaldi/LectureNotes", "max_forks_repo_head_hexsha": "3afc1b4473aa91297ac4cf515a77a578547cca5f", "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.1830601093, "max_line_length": 401, "alphanum_fraction": 0.5678471645, "converted": true, "num_tokens": 2594, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9719924777713886, "lm_q2_score": 0.90990700787036, "lm_q1q2_score": 0.8844227671214617}} {"text": "# The Iterative Relaxation Method\n> Written by Ryan Soklaski\n\n## Understanding Fixed-Points\nIn mathematics, a function $f(x)$ is said to have a \"fixed-point\" solution if there exists a value $x_{*}$ such that $f(x_{*}) = x_{*}$. That is, $f$ maps $x_{*}$ to itself. As a simple example, given $f(x) = x^{2}$, check that $f$ has a fixed-points at $x = 0$ and $x = 1$.\n\nFor a less trivial example, let's see if the function $f(x) = x^{2} - 1$ has any fixed points. That is, we want to find all solutions to $f(x) = x$:\n\n\\begin{equation}\nx^{2} - 1 = x \\\\\\\nx^{2} - x - 1 = 0 \\\\\\\nx = -0.61803...,\\; x = 1.61803...\n\\end{equation}\n\nWe made use of the [quadratic formula](https://en.wikipedia.org/wiki/Quadratic_formula) to find the two fixed-points for $f(x) = x^{2} - 1$. \n\nConsider that solving the fixed-point equation $f(x) = x$ is tantamount to finding where the values of $x$ where $f(x)$ intersects the line $y = x$:\n\n\nThere are many functions such that one cannot simply solve for $x$. For example, neither of the following equations are amenable to any algebraic manipulation that would reveal their solutions :\n\\begin{equation}\n\\sin{x} = x \\\\\\\ne^{x} - 1 = x\n\\end{equation}\n\nSuch equations are thus known as *transcendental* equations. How, then, can we find the fixed-point solutions (if they exist) for such functions? There is a simple numerical method, known as the relaxation method, that can be used towards this end.\n\n## The Relaxation Method\nSuppose for now that $f(x)$ has one fixed-point solution, $x_{*}$. The relaxation method allows us to \"guess\" a fixed-point solution, and then iteratively improve upon this guess until you have arrived at a value that is sufficiently close to the true fixed-point, $x_{*}$. \n\nSpecifically, given your initial guess of $f$'s fixed-point, $x_{0}$, you can generate a better guess by simply feeding $x_{0}$ to $f$, and using the output as your updated guess, $x_{1}$: \n\\begin{equation}\nx_{1} = f(x_{0})\n\\end{equation}\n\nYou can then improve this guess by feeding $x_{1}$ to $f$ and using the output as the next guess. Repeating this process $n$ times will produce $n$ consecutively-improved guesses at the true fixed-point, $x_{*}$:\n\\begin{equation}\nx_{1} = f(x_{0}) \\\\\\\nx_{2} = f(x_{1}) \\\\\\\nx_{3} = f(x_{2}) \\\\\\\n... \\\\\\\nx_{n} = f(x_{n-1}) \\\\\\\n\\\\\\\nx_{n} \\approx x_{*}\n\\end{equation}\n\nFor example, let's find a fixed point for $f(x) = \\tanh{5x}$ taking an initial guess of $0.5$.\n\\begin{equation}\n-0.9866143 = f(0.5) \\\\\\\n-0.9998962 = f(-0.9866143) \\\\\\\n-0.99990912 = f(-0.99990911) \\\\\\\n-0.99990912 = f(-0.99990912) \\\\\\\n\\end{equation}\n\nWe arrived at a fixed-point (within 7 decimal-places of precision) after four iterations!\n\n### Caveats to the relaxation method \nFor all its simplicity, the relaxation method is not a completely robust solution for finding fixed points, in which case this method can only potentially find one, for a given initial guess. It will fail if your function does not have fixed points. It is also very much possible for a function to have multiple fixed points. Additionally, this iterative process can \"blow up\" and lead you to ever-growing numbers if you use a \"bad\" starting guess. It is possible for the relaxation method to get stuck in a loop. If you try to find the fixed points for $x^2 - 1$ using an initial guess of $x_{o} = 0.5$, you will find that you eventually repeatedly guess 0, -1, 0, -1, 0, .... Be aware of these pitfalls when you are testing your code - they are a fundamental issue of the relaxation method, and not a symptom of bad code. \n\nYou need not worry about accounting for these issues in your code. You will never be given pathological functions/guesses that would cause these issues, in this homework.\n\n\n\n\n### Problem #1\nWrite a relaxation-method function that accepts three arguments:\n- a python function, which accepts a number as an input, and returns a float as an output\n- an initial guess for the fixed-point, $x_{0}$, a floating-point number\n- the number of iterations, $n$, to perform the relaxation method on the provided function\n\nYour function should return a list of the $n+1$ numbers: the initial guess and the $n$ guesses that you generate using the relaxation method. \n\nSo, in the context of the preceding relaxation example, I could define the function:\n```python\nfrom math import tanh\ndef f(x):\n return tanh(5*x)\n```\nand then calling your relaxation function, passing it this function, an initial guess of $x_{o}=0.5$, and instructing it to perform 5 iterations, should produce the following list:\n```python\n>>> relaxation_method(f, xo=-.5, num_it=5)\n[-0.5,\n -0.98661429815143031,\n -0.99989620032332682,\n -0.99990910997226823,\n -0.99990912170456125,\n -0.99990912171522284]\n```\nThat is, your `relaxation_method` function should call `f(xo)` to obtain the updated-guess for the fixed point, as the first iteration, and so on. Use the parameters provided in this example to test your code. \n\n\n```python\ndef relaxation_method1(func, xo, num_it):\n \"\"\" Performs the relaxation method to find a fixed-point for `func`,\n given the initial guess `xo`. The relaxation process is carried out for\n `num_it` steps.\n \n Parameters\n ----------\n func : Callable[[float], float]\n The function whose fixed point is being found.\n xo : float\n The initial \"guess\" value.\n num_it : int\n The number of relaxation-iterations to perform.\n \n Returns\n -------\n List[float]\n A list of the initial guess, and all of the subsequent guesses generated\n by the relaxation method. \"\"\"\n output = []\n output.append(xo)\n curr = xo\n i = 0\n while i != num_it:\n curr = func(curr)\n output.append(curr)\n i += 1\n return output\n \n```\n\n\n```python\n# run this cell to grade your work\nfrom bwsi_grader.python.relaxation_method import grader1 \ngrader1(relaxation_method1)\n```\n\n Finding fixed-points for the function: f(x) = x**2\n Finding fixed-points for the function: f(x) = tanh(4*x)\n \n ============================== ALL TESTS PASSED! ===============================\n Your submission code: bwb8e4b8ae3afecb32279a3941952049fff73d1181e93d77b45f39506c\n ================================================================================\n \n\n\n## Problem #2\nOur current implementation of the relaxation method is quite crude in that we must specify the number of iterations that it performs, and then simply look at the output to see if we have converged to a fix-point. It would instead be better if we could have our algorithm check its own numbers to see if they are converging to a single value, and then terminate itself if it has converged.\n\nWe can measure how close our most recent guess is to a fixed-point by looking at our most-recent three guesses $x_{n-2}, x_{n-1}, x_{n}$ , and seeing if $x_{n-1}$ and $x_{n}$ are closer to one another than are $x_{n-1}$ and $x_{n-2}$. Skipping a formal derivation, the following formula gives an upper-bound estimate on how close $x_{n}$ is to a true fixed-point:\n\n\\begin{equation}\n\\epsilon_{n} = \\lvert\\frac{(x_n - x_{n-1})^2}{2x_{n-1} - x_{n-2} - x_{n}}\\rvert\n\\end{equation}\n\nThat is, if your previous three guesses were $1.0$, then $1.63$, and then $1.80$, plugging these into the preceding formula produces an error bound of $\\epsilon = 0.06$. This means that the guess $1.80$ is within $0.06$ of the true fixed-point. To prevent division-by-zero errors, if your denominator is equal to 0.0, replace it with the value `1e-14`.\n\nArmed with this formula, we can now write a much better algorithm, which can operate based on a tolerance rather than a strict number of iterations.\n\nWrite a second version of the relaxation-method. This function should accept four arguments:\n- a python function, which accepts a number as an input, and returns a float as an output\n- an initial guess for the fixed-point, $x_{0}$, a floating-point number\n- a tolerance value, a positive-valued floating-point number\n- a max number of iterations that your algorithm is permitted to run\n\nYour algorithm should produce guesses until $\\epsilon_{n}$ is smaller than the specified tolerance value, or until the number of guesses produced (including the initial guess) matches/exceeds the max number of iterations. Like the last function, it should return a list of all the guesses. You will need to have three guesses before you can assess the tolerance.\n\n\n```python\ndef relaxation_method2(func, xo, tol, max_it):\n \"\"\" Performs the relaxation method to find a fixed-point for `func`,\n given the initial guess `xo`. The relaxation process is carried out for\n `num_it` steps.\n \n Parameters\n ----------\n func : Callable[[float], float]\n The function whose fixed point is being found.\n xo : float\n The initial \"guess\" value.\n tol : float\n A positive value that sets the maximum permissable error\n in the final fixed-point estimate.\n max_it : int\n The maximum number relaxation-guesses (i.e. the length of the\n list you are creating) allotted before the \n algorithm will end. The length of the list you return should\n never exceed this number.\n \n Returns\n -------\n List[float]\n A list of the initial guess, and all of the subsequent guesses generated\n by the relaxation method. \"\"\"\n output = []\n output.append(xo)\n curr = xo\n i = 0\n tolerance = 0\n while i < max_it - 1:\n if i < 2:\n curr = func(curr)\n output.append(curr)\n i += 1\n else:\n denominator = (2*(output[len(output)-2]))-(output[len(output)-3])-(output[len(output)-1])\n if denominator == 0.0:\n denominator = 1e-14\n tolerance = abs((((output[len(output)-1])-(output[len(output)-2]))**2)/denominator)\n if tolerance <= tol:\n return output\n else:\n curr = func(curr)\n output.append(curr)\n i += 1\n return output\n```\n\n\n```python\n# run this cell to grade your work\nfrom bwsi_grader.python.relaxation_method import grader2\ngrader2(relaxation_method2)\n```\n\n Finding fixed-points for the function: f(x) = 2 - exp(-x)\n \n ============================== ALL TESTS PASSED! ===============================\n Your submission code: bw7ab135590053bf38cdb655fff9447e2553dfc315e04ed295c498190c\n ================================================================================\n \n\n\n## A fun application of the relaxation method\nThe relaxation method is not just a parlor trick, nor are fixed-point equations a relic of pure-mathematics. The following will put the relaxation-function that you wrote to use, in order to solve a very real physics problem. You don't need to do any work here, just follow along and enjoy!\n\nYou have likely held a bar-magnet before - a special kind of metal that can use its magnetic field to push or pull on other magnets. Such a material is known as a ferromagnet, and it's magnetic properties are created by coordinated behavior among the electrons belonging to its atoms. The electrons in a ferromagnet naturally coordinate in such a way to create an overall magnetic field throughout and around the material. However, heating up a ferromagnet will jostle its atoms and electrons around, disturbing the coordination of the electrons and thus weakening the net magnetic field of the material. If you set out to describe the statistical behavior of a ferromagnetic material's electrons, you will eventually find that the strength of its magnetization, $M$, depends on temperature, $T$, according to the following equation:\n\n\\begin{equation}\nM = \\mu\\tanh{\\frac{JM}{k_{B}T}}\n\\end{equation}\n\nwhere $\\mu$ and $J$ are physical constants particular to the specific ferromagnetic material we are interested in, and $k_B$ is a fundamental constant from statistical mechanics. If $M = 0$, then the material is completely non-magnetic. For simplicity's sake, we'll set these constants to 1, without changing the essence of the problem at hand. Thus our equation for the magnetization of our material becomes: \n\n\\begin{equation}\nM = \\tanh{\\frac{M}{T}}\n\\end{equation}\n\nThis is a fixed-point equation! We can pick a value of $T$, and then use the relaxation method to solve for $M$. By varying $T$, we can measure the magnetization for each value of $T$, and thus understand how the material's magnetization depends on temperature.\n\nIn the following code, we will pick a value of $T$, and then solve for $M$ (within a given tolerance). Then we pick our next value of $T$ and repeat the process. Ultimately, we will have a collection of temperature values and corresponding magnetization values. We will plot $M$ vs $T$ to understand the temperature dependence for a ferromagnetic material.\n\n\n```python\n# just run this cell - you don't need to change any of this code\n\nimport numpy as np\n# `temps` is 1000 evenly-spaced values within [0, 1.5]\ntemps = np.linspace(0, 1.5, 1000)\n\nmags = []\nfor T in temps:\n \n # define the magnetization function, given\n # the current temperature value\n def mag_func(m, temp=T): \n return np.tanh(m / temp) if temp > 0. else 1.\n \n # Use the relaxation value to compute M within an error\n # of 1e-6.\n mag = relaxation_method2(mag_func, 1., 1e-6, 1000)[-1]\n mags.append(mag)\n\nprint(\"number of magnetization-values computed: {}\".format(len(mags)))\n```\n\n number of magnetization-values computed: 1000\n\n\n\n```python\n# just run this cell - you don't need to change any of this code\n\n# Plotting M vs T\nimport matplotlib.pyplot as plt\n%matplotlib notebook\nfig, ax = plt.subplots()\nax.plot(temps, mags)\nax.grid(True)\nax.set_ylabel(\"Magnetization\")\nax.set_xlabel(r\"$T$\")\nax.set_title(\"Magnetization vs Temperature\");\n```\n\n\n \n\n\n\n\n\n\nSee that $M = 0$ for high temperatures, meaning that the material is non-magnetic when it is at a temperature greater than 1 (no actual units, since we set all those constants to be $1$). However, once the material is cooled to $T \\leq 1$, the material suddenly magnetizes, and its magnetization strengthens as you cool it further.\n\nThis sudden magnetization at $T = 1$ is a *phase transition*. This is very similar to water freezing: water's atoms molecules will rapidly begin to form a crystal once they are cooled to 0-celsius or below. Similarly, we see that a ferromagnetic material's electrons will suddenly be able to coordinate and produce a net magnetic field throughout the material, once they are cooled to $T=1$ and below.\n\nThis is a no-joke physics problem that we were able to solve thanks to the relaxation method! If you look up the constants, $\\mu$ and $J$, for a specific material, you can repeat this computation to produce its actual magnetic phase diagram. This rules!\n", "meta": {"hexsha": "b4bbfffafa26e96a9e64e9c2745d83a48cb2b110", "size": 85566, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "PythonHW-1.2.4/relaxation_method/HW_relaxation_method.ipynb", "max_stars_repo_name": "abhatia25/Beaverworks-Racecar", "max_stars_repo_head_hexsha": "7c579e27de3688d58f280ff260897f77efa5fb4a", "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": "PythonHW-1.2.4/relaxation_method/HW_relaxation_method.ipynb", "max_issues_repo_name": "abhatia25/Beaverworks-Racecar", "max_issues_repo_head_hexsha": "7c579e27de3688d58f280ff260897f77efa5fb4a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-03-06T21:24:28.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-06T21:24:28.000Z", "max_forks_repo_path": "PythonHW-1.2.4/relaxation_method/HW_relaxation_method.ipynb", "max_forks_repo_name": "abhatia25/Beaverworks-Racecar", "max_forks_repo_head_hexsha": "7c579e27de3688d58f280ff260897f77efa5fb4a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-03-06T21:04:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-06T21:04:55.000Z", "avg_line_length": 72.3908629442, "max_line_length": 31491, "alphanum_fraction": 0.6923076923, "converted": true, "num_tokens": 3771, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088084787998, "lm_q2_score": 0.9525741291785796, "lm_q1q2_score": 0.8843782122584155}} {"text": "```python\n# symbols and expressions\nfrom sympy import *\ninit_printing(use_unicode=True)\n```\n\n\n```python\nx = Symbol('x')\ny,z = symbols('y,z')\n```\n\n\n```python\nf = Function('f')\n```\n\n\n```python\nf = x**2 + y**2 + z**2\n```\n\n\n```python\nprint(f)\n```\n\n x**2 + y**2 + z**2\n\n\n\n```python\npprint(f)\n```\n\n 2 2 2\n x + y + z \n\n\n\n```python\nf = x**2 - 3*x + 2\n```\n\n\n```python\npprint(f)\n```\n\n 2 \n x - 3⋅x + 2\n\n\n\n```python\n# evaluate f for a particular value of x, say x=1.0\npprint(f.subs(x,1.0))\n```\n\n 0\n\n\n\n```python\npprint(f.subs(x,3.0))\n```\n\n 2.00000000000000\n\n\n\n```python\nf = (x**2 - 3*x + 2)/(x**2-x)\n```\n\n\n```python\npprint(f)\n```\n\n 2 \n x - 3⋅x + 2\n ────────────\n 2 \n x - x \n\n\n\n```python\n# simplify expressions\nsimplify(f)\n```\n\n\n```python\n# expand an expression\nf = (x+2)**3*(x-3)**2\n```\n\n\n```python\npprint(f)\n```\n\n 2 3\n (x - 3) ⋅(x + 2) \n\n\n\n```python\nexpand(f)\n```\n\n\n```python\n# finding roots\nf = x**2 - 3*x + 2\n```\n\n\n```python\nsolve(f,x)\n```\n\n\n```python\ng = (x+2)**3*(x-3)**2\n```\n\n\n```python\nsolve(g,x)\n```\n\n\n```python\nf = x**2 + x + 1\n```\n\n\n```python\ny=solve(f,x)\n```\n\n\n```python\npprint(y)\n```\n\n ⎡ 1 √3⋅ⅈ 1 √3⋅ⅈ⎤\n ⎢- ─ - ────, - ─ + ────⎥\n ⎣ 2 2 2 2 ⎦\n\n\n\n```python\n# show the values are numerals\ny[0].evalf()\n```\n\n\n```python\ny[1].evalf()\n```\n\n\n```python\nfor z in y:\n pprint(z.evalf())\n```\n\n -0.5 - 0.866025403784439⋅ⅈ\n -0.5 + 0.866025403784439⋅ⅈ\n\n\n\n```python\n# solution of a set of equations\nx,y,z = symbols('x y z')\n```\n\n\n```python\neq1 = Eq(x+y+z,0)\n```\n\n\n```python\nprint(eq1)\n```\n\n Eq(x + y + z, 0)\n\n\n\n```python\neq2 = Eq(2*x-y-z,10)\neq3 = Eq(y+2*z,5)\n```\n\n\n```python\nsolve([eq1, eq2, eq3],[x,y,z])\n```\n", "meta": {"hexsha": "27af484066d84d3bb61cb0c26682022490a9671a", "size": 16519, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "3-polynomials.ipynb", "max_stars_repo_name": "chennachaos/SA2CTechChatSymPy", "max_stars_repo_head_hexsha": "9f1dbb48655ff5f8bdd6b4ced48b58aed0ba5bf4", "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": "3-polynomials.ipynb", "max_issues_repo_name": "chennachaos/SA2CTechChatSymPy", "max_issues_repo_head_hexsha": "9f1dbb48655ff5f8bdd6b4ced48b58aed0ba5bf4", "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": "3-polynomials.ipynb", "max_forks_repo_name": "chennachaos/SA2CTechChatSymPy", "max_forks_repo_head_hexsha": "9f1dbb48655ff5f8bdd6b4ced48b58aed0ba5bf4", "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.1381322957, "max_line_length": 1728, "alphanum_fraction": 0.671771899, "converted": true, "num_tokens": 744, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810511092411, "lm_q2_score": 0.9334308040850653, "lm_q1q2_score": 0.8843146563118532}} {"text": "# Lecture 2\n\nWe now look at solving second-order ordinary differential equations using a computer algebra system.\n\n### Initialising SymPy\n\nTo use Sympy, we first need to import it and call `init_printing()` to get nicely typeset equations:\n\n\n```\nfrom sympy import *\n\n# This initialises pretty printing\ninit_printing()\nfrom IPython.display import display\n\n# This command makes plots appear inside the browser window\n%matplotlib inline\n```\n\n## Mass-spring-damper system\n\nThe differential equation that governs an unforced, single degree-of-freedom mass-spring-damper system is\n\n$$\nm \\frac{d^{2}y}{dx^{2}} + \\lambda \\frac{dy}{dx} + ky = 0\n$$\n\nTo solve this problem using SymPy, we first define the symbols $t$ (time), $m$ (mass), $\\lambda$ (damper coefficient) and $k$ (spring stiffness), and the function $y$ (displacement): \n\n\n```\nt, m, lmbda, k = symbols(\"t m lambda k\")\ny = Function(\"y\")\n```\n\nNote that we mis-spell $\\lambda$ as `lmbda` because `lambda` is a protected keyword in Python.\n\nNext, we define the differential equation, and print it to the screen:\n\n\n```\neqn = Eq(m*Derivative(y(t), t, t) + lmbda*Derivative(y(t), t) + k*y(t), 0)\ndisplay(eqn)\n```\n\nChecking the order of the ODE:\n\n\n```\nprint(\"This order of the ODE is: {}\".format(ode_order(eqn, y(t))))\n```\n\n This order of the ODE is: 2\n\n\nand now classifying the ODE:\n\n\n```\nprint(\"Properties of the ODE are: {}\".format(classify_ode(eqn)))\n```\n\n Properties of the ODE are: ('nth_linear_constant_coeff_homogeneous', '2nd_power_series_ordinary')\n\n\nwe see as expected that the equation is linear, constant coefficient, homogeneous and second order.\n\nThe `dsolve` function solves the differential equation:\n\n\n```\ny = dsolve(eqn, y(t))\ndisplay(y)\n```\n\nThe solution looks very complicated because we have not specified values for the constants $m$, $\\lambda$ and $k$. The nature of the solution depends heavily on the relative values of the coefficients, as we will see later. We have four constants because the most general case the solution is complex, with two complex constants having four real coefficients.\n\nNote that the solution is make up of expoential functions and sinusoidal functions. This is typical of second-order ODEs.\n\n## Second order, constant coefficient equation\n\nWe'll now solve \n\n$$\n\\frac{d^{2}y}{dx^{2}} + 2 \\frac{dy}{dx} - 3 y = 0\n$$\n\nThe solution for this problem will appear simpler because we have concrete values for the coefficients.\n\nEntering the differential equation:\n\n\n```\ny = Function(\"y\")\nx = symbols(\"x\")\neqn = Eq(Derivative(y(x), x, x) + 2*Derivative(y(x), x) - 3*y(x), 0)\ndisplay(eqn)\n```\n\nSolving this equation,\n\n\n```\ny1 = dsolve(eqn)\ndisplay(y1)\n```\n\nwhich is the general solution. As expected for a second-order equation, there are two constants.\n\nNote that the general solution is of the form\n\n$$\ny = C_{1} e^{\\lambda_{1} x} + C_{2} e^{\\lambda_{2} x}\n$$\n\nThe constants $\\lambda_{1}$ and $\\lambda_{2}$ are roots of the \\emph{characteristic} equation\n\n$$\n\\lambda^{2} + 2\\lambda - 3 = 0\n$$\n\nThis quadratic equation is trivial to solve, but for completeness we'll look at how to solve it using SymPy. We first define the quadratic equation:\n\n\n```\neqn = Eq(lmbda**2 + 2*lmbda -3, 0)\ndisplay(eqn)\n```\n\nand then compute the roots:\n\n\n```\nsolve(eqn)\n```\n\nwhich as expected are the two exponents in the solution to the differential equattion.\n", "meta": {"hexsha": "d1a609c09f2cde2c93fe3f8584621d6860c868a8", "size": 20079, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/Lecture2.ipynb", "max_stars_repo_name": "quang-ha/IA-maths-Ipython", "max_stars_repo_head_hexsha": "8ff8533d64a3d8db8e4813a7b6dfee39339fd846", "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": "notebooks/Lecture2.ipynb", "max_issues_repo_name": "quang-ha/IA-maths-Ipython", "max_issues_repo_head_hexsha": "8ff8533d64a3d8db8e4813a7b6dfee39339fd846", "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": "notebooks/Lecture2.ipynb", "max_forks_repo_name": "quang-ha/IA-maths-Ipython", "max_forks_repo_head_hexsha": "8ff8533d64a3d8db8e4813a7b6dfee39339fd846", "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": 51.8837209302, "max_line_length": 2211, "alphanum_fraction": 0.6894765676, "converted": true, "num_tokens": 910, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9702399069145609, "lm_q2_score": 0.9111797027760039, "lm_q1q2_score": 0.8840629100038273}} {"text": "# Linear Equations\nThe equations in the previous lab included one variable, for which you solved the equation to find its value. Now let's look at equations with multiple variables. For reasons that will become apparent, equations with two variables are known as linear equations.\n\n## Solving a Linear Equation\nConsider the following equation:\n\n\\begin{equation}2y + 3 = 3x - 1 \\end{equation}\n\nThis equation includes two different variables, **x** and **y**. These variables depend on one another; the value of x is determined in part by the value of y and vice-versa; so we can't solve the equation and find absolute values for both x and y. However, we *can* solve the equation for one of the variables and obtain a result that describes a relative relationship between the variables.\n\nFor example, let's solve this equation for y. First, we'll get rid of the constant on the right by adding 1 to both sides:\n\n\\begin{equation}2y + 4 = 3x \\end{equation}\n\nThen we'll use the same technique to move the constant on the left to the right to isolate the y term by subtracting 4 from both sides:\n\n\\begin{equation}2y = 3x - 4 \\end{equation}\n\nNow we can deal with the coefficient for y by dividing both sides by 2:\n\n\\begin{equation}y = \\frac{3x - 4}{2} \\end{equation}\n\nOur equation is now solved. We've isolated **y** and defined it as 3x-4/2\n\nWhile we can't express **y** as a particular value, we can calculate it for any value of **x**. For example, if **x** has a value of 6, then **y** can be calculated as:\n\n\\begin{equation}y = \\frac{3\\cdot6 - 4}{2} \\end{equation}\n\nThis gives the result 14/2 which can be simplified to 7.\n\nYou can view the values of **y** for a range of **x** values by applying the equation to them using the following Python code:\n\n\n```python\nimport pandas as pd\n\n# Create a dataframe with an x column containing values from -10 to 10\ndf = pd.DataFrame ({'x': range(-10, 11)})\n\n# Add a y column by applying the solved equation to x\ndf['y'] = (3*df['x'] - 4) / 2\n\n#Display the dataframe\ndf\n```\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
xy
0-10-17.0
1-9-15.5
2-8-14.0
3-7-12.5
4-6-11.0
5-5-9.5
6-4-8.0
7-3-6.5
8-2-5.0
9-1-3.5
100-2.0
111-0.5
1221.0
1332.5
1444.0
1555.5
1667.0
1778.5
18810.0
19911.5
201013.0
\n
\n\n\n\nWe can also plot these values to visualize the relationship between x and y as a line. For this reason, equations that describe a relative relationship between two variables are known as *linear equations*:\n\n\n```python\n%matplotlib inline\nfrom matplotlib import pyplot as plt\n\nplt.plot(df.x, df.y, color=\"grey\", marker = \"o\")\nplt.xlabel('x')\nplt.ylabel('y')\nplt.grid()\nplt.show()\n```\n\nIn a linear equation, a valid solution is described by an ordered pair of x and y values. For example, valid solutions to the linear equation above include:\n- (-10, -17)\n- (0, -2)\n- (9, 11.5)\n\nThe cool thing about linear equations is that we can plot the points for some specific ordered pair solutions to create the line, and then interpolate the x value for any y value (or vice-versa) along the line.\n\n## Intercepts\nWhen we use a linear equation to plot a line, we can easily see where the line intersects the X and Y axes of the plot. These points are known as *intercepts*. The *x-intercept* is where the line intersects the X (horizontal) axis, and the *y-intercept* is where the line intersects the Y (horizontal) axis.\n\nLet's take a look at the line from our linear equation with the X and Y axis shown through the origin (0,0).\n\n\n```python\nplt.plot(df.x, df.y, color=\"grey\")\nplt.xlabel('x')\nplt.ylabel('y')\nplt.grid()\n\n## add axis lines for 0,0\nplt.axhline()\nplt.axvline()\nplt.show()\n```\n\nThe x-intercept is the point where the line crosses the X axis, and at this point, the **y** value is always 0. Similarly, the y-intercept is where the line crosses the Y axis, at which point the **x** value is 0. So to find the intercepts, we need to solve the equation for **x** when **y** is 0.\n\nFor the x-intercept, our equation looks like this:\n\n\\begin{equation}0 = \\frac{3x - 4}{2} \\end{equation}\n\nWhich can be reversed to make it look more familar with the x expression on the left:\n\n\\begin{equation}\\frac{3x - 4}{2} = 0 \\end{equation}\n\nWe can multiply both sides by 2 to get rid of the fraction:\n\n\\begin{equation}3x - 4 = 0 \\end{equation}\n\nThen we can add 4 to both sides to get rid of the constant on the left:\n\n\\begin{equation}3x = 4 \\end{equation}\n\nAnd finally we can divide both sides by 3 to get the value for x:\n\n\\begin{equation}x = \\frac{4}{3} \\end{equation}\n\nWhich simplifies to:\n\n\\begin{equation}x = 1\\frac{1}{3} \\end{equation}\n\nSo the x-intercept is 11/3 (approximately 1.333).\n\nTo get the y-intercept, we solve the equation for y when x is 0:\n\n\\begin{equation}y = \\frac{3\\cdot0 - 4}{2} \\end{equation}\n\nSince 3 x 0 is 0, this can be simplified to:\n\n\\begin{equation}y = \\frac{-4}{2} \\end{equation}\n\n-4 divided by 2 is -2, so:\n\n\\begin{equation}y = -2 \\end{equation}\n\nThis gives us our y-intercept, so we can plot both intercepts on the graph:\n\n\n```python\nplt.plot(df.x, df.y, color=\"grey\")\nplt.xlabel('x')\nplt.ylabel('y')\nplt.grid()\n\n## add axis lines for 0,0\nplt.axhline()\nplt.axvline()\nplt.annotate('x-intercept',(1.333, 0))\nplt.annotate('y-intercept',(0,-2))\nplt.show()\n```\n\nThe ability to calculate the intercepts for a linear equation is useful, because you can calculate only these two points and then draw a straight line through them to create the entire line for the equation.\n\n## Slope\nIt's clear from the graph that the line from our linear equation describes a slope in which values increase as we travel up and to the right along the line. It can be useful to quantify the slope in terms of how much **x** increases (or decreases) for a given change in **y**. In the notation for this, we use the greek letter Δ (*delta*) to represent change:\n\n\\begin{equation}slope = \\frac{\\Delta{y}}{\\Delta{x}} \\end{equation}\n\nSometimes slope is represented by the variable ***m***, and the equation is written as:\n\n\\begin{equation}m = \\frac{y_{2} - y_{1}}{x_{2} - x_{1}} \\end{equation}\n\nAlthough this form of the equation is a little more verbose, it gives us a clue as to how we calculate slope. What we need is any two ordered pairs of x,y values for the line - for example, we know that our line passes through the following two points:\n- (0,-2)\n- (6,7)\n\nWe can take the x and y values from the first pair, and label them x1 and y1; and then take the x and y values from the second point and label them x2 and y2. Then we can plug those into our slope equation:\n\n\\begin{equation}m = \\frac{7 - -2}{6 - 0} \\end{equation}\n\nThis is the same as:\n\n\\begin{equation}m = \\frac{7 + 2}{6 - 0} \\end{equation}\n\nThat gives us the result 9/6 which is 11/2 or 1.5 .\n\nSo what does that actually mean? Well, it tells us that for every change of **1** in x, **y** changes by 11/2 or 1.5. So if we start from any point on the line and move one unit to the right (along the X axis), we'll need to move 1.5 units up (along the Y axis) to get back to the line.\n\nYou can plot the slope onto the original line with the following Python code to verify it fits:\n\n\n```python\nplt.plot(df.x, df.y, color=\"grey\")\nplt.xlabel('x')\nplt.ylabel('y')\nplt.grid()\nplt.axhline()\nplt.axvline()\n\n# set the slope\nm = 1.5\n\n# get the y-intercept\nyInt = -2\n\n# plot the slope from the y-intercept for 1x\nmx = [0, 1]\nmy = [yInt, yInt + m]\nplt.plot(mx,my, color='red', lw=5)\n\nplt.show()\n```\n\n### Slope-Intercept Form\nOne of the great things about algebraic expressions is that you can write the same equation in multiple ways, or *forms*. The *slope-intercept form* is a specific way of writing a 2-variable linear equation so that the equation definition includes the slope and y-intercept. The generalised slope-intercept form looks like this:\n\n\\begin{equation}y = mx + b \\end{equation}\n\nIn this notation, ***m*** is the slope and ***b*** is the y-intercept.\n\nFor example, let's look at the solved linear equation we've been working with so far in this section:\n\n\\begin{equation}y = \\frac{3x - 4}{2} \\end{equation}\n\nNow that we know the slope and y-intercept for the line that this equation defines, we can rewrite the equation as:\n\n\\begin{equation}y = 1\\frac{1}{2}x + -2 \\end{equation}\n\nYou can see intuitively that this is true. In our original form of the equation, to find y we multiply x by three, subtract 4, and divide by two - in other words, x is half of 3x - 4; which is 1.5x - 2. So these equations are equivalent, but the slope-intercept form has the advantages of being simpler, and including two key pieces of information we need to plot the line represented by the equation. We know the y-intecept that the line passes through (0, -2), and we know the slope of the line (for every x, we add 1.5 to y.\n\nLet's recreate our set of test x and y values using the slope-intercept form of the equation, and plot them to prove that this describes the same line:\n\n\n```python\n%matplotlib inline\n\nimport pandas as pd\nfrom matplotlib import pyplot as plt\n\n# Create a dataframe with an x column containing values from -10 to 10\ndf = pd.DataFrame ({'x': range(-10, 11)})\n\n# Define slope and y-intercept\nm = 1.5\nyInt = -2\n\n# Add a y column by applying the slope-intercept equation to x\ndf['y'] = m*df['x'] + yInt\n\n# Plot the line\nfrom matplotlib import pyplot as plt\n\nplt.plot(df.x, df.y, color=\"grey\")\nplt.xlabel('x')\nplt.ylabel('y')\nplt.grid()\nplt.axhline()\nplt.axvline()\n\n# label the y-intercept\nplt.annotate('y-intercept',(0,yInt))\n\n# plot the slope from the y-intercept for 1x\nmx = [0, 1]\nmy = [yInt, yInt + m]\nplt.plot(mx,my, color='red', lw=5)\n\nplt.show()\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "de1782c469ba03d96cfece7723ef5e9c4fe7b542", "size": 86349, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Basics Of Algebra by Hiren/01-02-Linear Equations.ipynb", "max_stars_repo_name": "serkin/Basic-Mathematics-for-Machine-Learning", "max_stars_repo_head_hexsha": "ac0ae9fad82a9f0429c93e3da744af6e6d63e5ab", "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": "Basics Of Algebra by Hiren/01-02-Linear Equations.ipynb", "max_issues_repo_name": "serkin/Basic-Mathematics-for-Machine-Learning", "max_issues_repo_head_hexsha": "ac0ae9fad82a9f0429c93e3da744af6e6d63e5ab", "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": "Basics Of Algebra by Hiren/01-02-Linear Equations.ipynb", "max_forks_repo_name": "serkin/Basic-Mathematics-for-Machine-Learning", "max_forks_repo_head_hexsha": "ac0ae9fad82a9f0429c93e3da744af6e6d63e5ab", "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": 147.6051282051, "max_line_length": 15244, "alphanum_fraction": 0.8654298255, "converted": true, "num_tokens": 3578, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750427013548, "lm_q2_score": 0.9273632916317103, "lm_q1q2_score": 0.8840322814298875}} {"text": "# Quadratic Equations\n\nConsider the following equation:\n\n\\begin{equation}y = 2(x - 1)(x + 2)\\end{equation}\n\nIf you multiply out the factored ***x*** expressions, this equates to:\n\n\\begin{equation}y = 2x^{2} + 2x - 4\\end{equation}\n\nNote that the highest ordered term includes a squared variable (x2).\n\nLet's graph this equation for a range of ***x*** values:\n\n\n```R\n# Create a dataframe with an x column containing values to plot\ndf = data.frame(x = seq(-9, 8))\n\n# Add a y column by applying the quadratic equation to x\ndf$y = 2*df$x**2 + 2 *df$x - 4\n\n## Plot the parabola\nlibrary(ggplot2)\nlibrary(repr)\noptions(repr.plot.width=4, repr.plot.height=4)\nggplot(df, aes(x,y)) + \n geom_line(color = 'blue', size = 1) +\n geom_hline(yintercept=0) + geom_vline(xintercept=0)\n```\n\nNote that the graph shows a *parabola*, which is an arc-shaped line that reflects the x and y values calculated for the equation.\n\nNow let's look at another equation that includes an ***x2*** term:\n\n\\begin{equation}y = -2x^{2} + 6x + 7\\end{equation}\n\nWhat does that look like as a graph?:\n\n\n```R\n# Create a dataframe with an x column containing values to plot\ndf = data.frame(x = seq(-8,11))\n\n# Add a y column by applying the quadratic equation to x\ndf$y = -2*df$x**2 + 6*df$x + 7\n\n## Plot the parabola\nlibrary(ggplot2)\nlibrary(repr)\noptions(repr.plot.width=4, repr.plot.height=4)\nggplot(df, aes(x,y)) + \n geom_line(color = 'blue', size = 1) +\n geom_hline(yintercept=0) + geom_vline(xintercept=0)\n```\n\nAgain, the graph shows a parabola, but this time instead of being open at the top, the parabola is open at the bottom.\n\nEquations that assign a value to ***y*** based on an expression that includes a squared value for ***x*** create parabolas. If the relationship between ***y*** and ***x*** is such that ***y*** is a *positive* multiple of the ***x2*** term, the parabola will be open at the top; when ***y*** is a *negative* multiple of the ***x2*** term, then the parabola will be open at the bottom.\n\nThese kinds of equations are known as *quadratic* equations, and they have some interesting characteristics. There are several ways quadratic equations can be written, but the *standard form* for quadratic equation is:\n\n\\begin{equation}y = ax^{2} + bx + c\\end{equation}\n\nWhere ***a***, ***b***, and ***c*** are numeric coefficients or constants.\n\nLet's start by examining the parabolas generated by quadratic equations in more detail.\n\n## Parabola Vertex and Line of Symmetry\nParabolas are symmetrical, with x and y values converging exponentially towards the highest point (in the case of a downward opening parabola) or lowest point (in the case of an upward opening parabola). The point where the parabola meets the line of symmetry is known as the *vertex*.\n\nRun the following cell to see the line of symmetry and vertex for the two parabolas described previously (don't worry about the calculations used to find the line of symmetry and vertex - we'll explore that later):\n\n\n```R\nplot_parabola = function(a, b, c){\n # get the x value for the line of symmetry\n vx = (-1*b)/(2*a)\n \n # get the y value when x is at the line of symmetry\n vy = a*vx**2 + b*vx + c\n\n # Create a dataframe with an x column containing values from x-10 to x+10\n minx = as.integer(vx - 10)\n maxx = as.integer(vx + 10)\n df = data.frame(x = seq(minx, maxx))\n \n # Add a y column by applying the quadratic equation to x\n df$y = a*df$x**2 + b*df$x + c\n\n # get min and max y values\n miny = min(df$y)\n maxy = max(df$y)\n \n ## data frame for line of symmetry\n symmetry = data.frame(sx = c(vx,vx), sy = c(miny,maxy))\n \n ## Plot the parabola\n ggplot(df, aes(x,y)) + \n geom_line(color = 'blue', size = 1) +\n geom_line(data = symmetry, aes(sx,sy), color = 'magenta', size = 1) + \n geom_point(data = symmetry, aes(sx,sy), color = 'magenta', size = 2) +\n annotate(\"text\", x = vx, y = -10, label = \"Vertex\") +\n geom_hline(yintercept=0) + geom_vline(xintercept=0)\n }\n\nplot_parabola(2, 2, -4) \n\nplot_parabola(-2, 3, 5) \n```\n\n## Parabola Intercepts\nRecall that linear equations create lines that intersect the **x** and **y** axis of a graph, and we call the points where these intersections occur *intercepts*. Now look at the graphs of the parabolas we've worked with so far. Note that these parabolas both have a y-intercept; a point where the line intersects the y axis of the graph (in other words, when x is 0). However, note that the parabolas have *two* x-intercepts; in other words there are two points at which the line crosses the x axis (and y is 0). Additionally, imagine a downward opening parabola with its vertex at -1, -1. This is perfectly possible, and the line would never have an x value greater than -1, so it would have *no* x-intercepts.\n\nRegardless of whether the parabola crosses the x axis or not, other than the vertex, for every ***y*** point in the parabola, there are *two* ***x*** points; one on the right (or positive) side of the axis of symmetry, and one of the left (or negative) side. The implications of this are what make quadratic equations so interesting. When we solve the equation for ***x***, there are *two* correct answers.\n\nLet's take a look at an example to demonstrate this. Let's return to the first of our quadratic equations, and we'll look at it in its *factored* form:\n\n\\begin{equation}y = 2(x - 1)(x + 2)\\end{equation}\n\nNow, let's solve this equation for a ***y*** value of 0. We can restate the equation like this:\n\n\\begin{equation}2(x - 1)(x + 2) = 0\\end{equation}\n\nThe equation is the product of two expressions **2(x - 1)** and **(x + 2)**. In this case, we know that the product of these expressions is 0, so logically *one or both of the expressions must return 0*.\n\nLet's try the first one:\n\n\\begin{equation}2(x - 1) = 0\\end{equation}\n\nIf we distrbute this, we get:\n\n\\begin{equation}2x - 2 = 0\\end{equation}\n\nThis simplifies to:\n\n\\begin{equation}2x = 2\\end{equation}\n\nWhich gives us a value for *x* of **1**.\n\nNow let's try the other expression:\n\n\\begin{equation}x + 2 = 0\\end{equation}\n\nThis gives us a value for *x* of **-2**.\n\nSo, when *y* is **0**, *x* is **-2** or **1**. Let's plot these points on our parabola:\n\n\n```R\nplot_parabola_limits = function(a, b, c){\n # get the x value for the line of symmetry\n vx = (-1*b)/(2*a)\n \n # get the y value when x is at the line of symmetry\n vy = a*vx**2 + b*vx + c\n\n # Create a dataframe with an x column containing values from x-10 to x+10\n minx = as.integer(vx - 10)\n maxx = as.integer(vx + 10)\n df = data.frame(x = seq(minx, maxx))\n \n # Add a y column by applying the quadratic equation to x\n df$y = a*df$x**2 + b*df$x + c\n\n # get min and max y values\n miny = min(df$y)\n maxy = max(df$y)\n \n ## data frame for line of symmetry\n symmetry = data.frame(sx = c(vx,vx), sy = c(miny,maxy))\n \n ## data frame for xlimits\n xlims = data.frame(x = c(-2,1), y = c(0,0))\n \n ## Plot the parabola\n ggplot(df, aes(x,y)) + \n geom_line(color = 'blue', size = 1) +\n geom_line(data = symmetry, aes(sx,sy), color = 'magenta', size = 1) + \n geom_point(data = symmetry, aes(sx,sy), color = 'magenta', size = 2) +\n geom_point(data = xlims, aes(x,y), color = 'red', size = 2) +\n geom_text(data = xlims, aes(label=c('x1','x2')),hjust=-0.5, vjust=0) +\n annotate(\"text\", x = vx, y = -10, label = \"Vertex\") +\n geom_hline(yintercept=0) + geom_vline(xintercept=0)\n }\n\nplot_parabola_limits(2, 2, -4) \n```\n\nSo from the plot, we can see that both of the values we calculated for ***x*** align with the parabola when ***y*** is 0. Additionally, because the parabola is symmetrical, we know that every pair of ***x*** values for each ***y*** value will be equidistant from the line of symmetry, so we can calculate the ***x*** value for the line of symmetry as the average of the ***x*** values for any value of ***y***. This in turn means that we know the ***x*** coordinate for the vertex (it's on the line of symmetry), and we can use the quadratic equation to calculate ***y*** for this point.\n\n## Solving Quadratics Using the Square Root Method\nThe technique we just looked at makes it easy to calculate the two possible values for ***x*** when ***y*** is 0 if the equation is presented as the product two expressions. If the equation is in standard form, and it can be factored, you could do the necessary manipulation to restate it as the product of two expressions. Otherwise, you can calculate the possible values for x by applying a different method that takes advantage of the relationship between squared values and the square root.\n\nLet's consider this equation:\n\n\\begin{equation}y = 3x^{2} - 12\\end{equation}\n\nNote that this is in the standard quadratic form, but there is no *b* term; in other words, there's no term that contains a coeffecient for ***x*** to the first power. This type of equation can be easily solved using the square root method. Let's restate it so we're solving for ***x*** when ***y*** is 0:\n\n\\begin{equation}3x^{2} - 12 = 0\\end{equation}\n\nThe first thing we need to do is to isolate the ***x2*** term, so we'll remove the constant on the left by adding 12 to both sides:\n\n\\begin{equation}3x^{2} = 12\\end{equation}\n\nThen we'll divide both sides by 3 to isolate x2:\n\n\\begin{equation}x^{2} = 4\\end{equation}\n\nNo we can isolate ***x*** by taking the square root of both sides. However, there's an additional consideration because this is a quadratic equation. The ***x*** variable can have two possibe values, so we must calculate the *principle* and *negative* square roots of the expression on the right:\n\n\\begin{equation}x = \\pm\\sqrt{4}\\end{equation}\n\nThe principle square root of 4 is 2 (because 22 is 4), and the corresponding negative root is -2 (because -22 is also 4); so *x* is **2** or **-2**.\n\nLet's see this in R, and use the results to calculate and plot the parabola with its line of symmetry and vertex:\n\n\n```R\ny = 0\nx1 = as.integer(-sqrt(y + 12 / 3))\nx2 = as.integer(sqrt(y + 12 / 3))\n\n# Create a dataframe with an x column containing some values to plot\ndf = data.frame(x = seq(x1-10, x2+10))\n\n# Add a y column by applying the quadratic equation to x\ndf$y = 3*df$x**2 - 12\n\n# Get x at the line of symmetry (halfway between x1 and x2)\nvx = (x1 + x2) / 2\n\n# Get y when x is at the line of symmetry\nvy = 3*vx**2 - 12\n\n# get min and max y values\nminy = min(df$y)\nmaxy = max(df$y)\n \n## data frame for line of symmetry\nsymmetry = data.frame(sx = c(vx,vx), sy = c(miny,maxy))\n \n## data frame for xlimits\nxlims = data.frame(x = c(x1,x2), y = c(0,0))\n \n## Plot the parabola\nggplot(df, aes(x,y)) + \n geom_line(color = 'blue', size = 1) +\n geom_line(data = symmetry, aes(sx,sy), color = 'magenta', size = 1) + \n geom_point(data = symmetry, aes(sx,sy), color = 'magenta', size = 2) +\n geom_point(data = xlims, aes(x,y), color = 'red', size = 2) +\n geom_text(data = xlims, aes(label=c('x1','x2')),hjust=-0.5, vjust=0) +\n annotate(\"text\", x = vx, y = -20, label = \"Vertex\") +\n geom_hline(yintercept=0) + geom_vline(xintercept=0)\n\n```\n\n## Solving Quadratics Using the Completing the Square Method\nIn quadratic equations where there is a *b* term; that is, a term containing **x** to the first power, it is impossible to directly calculate the square root. However, with some algebraic manipulation, you can take advantage of the ability to factor a polynomial expression in the form *a2 + 2ab + b2* as a binomial *perfect square* expression in the form *(a + b)2*.\n\nAt first this might seem like some sort of mathematical sleight of hand, but follow through the steps carefull and you'll see that there's nothing up my sleeve!\n\nThe underlying basis of this approach is that a trinomial expression like this:\n\n\\begin{equation}x^{2} + 24x + 12^{2}\\end{equation}\n\nCan be factored to this:\n\n\\begin{equation}(x + 12)^{2}\\end{equation}\n\nOK, so how does this help us solve a quadratic equation? Well, let's look at an example:\n\n\\begin{equation}y = x^{2} + 6x - 7\\end{equation}\n\nLet's start as we've always done so far by restating the equation to solve ***x*** for a ***y*** value of 0:\n\n\\begin{equation}x^{2} + 6x - 7 = 0\\end{equation}\n\nNow we can move the constant term to the right by adding 7 to both sides:\n\n\\begin{equation}x^{2} + 6x = 7\\end{equation}\n\nOK, now let's look at the expression on the left: *x2 + 6x*. We can't take the square root of this, but we can turn it into a trinomial that will factor into a perfect square by adding a squared constant. The question is, what should that constant be? Well, we know that we're looking for an expression like *x2 + 2**c**x + **c**2*, so our constant **c** is half of the coefficient we currently have for ***x***. This is **6**, making our constant **3**, which when squared is **9** So we can create a trinomial expression that will easily factor to a perfect square by adding 9; giving us the expression *x2 + 6x + 9*.\n\nHowever, we can't just add something to one side without also adding it to the other, so our equation becomes:\n\n\\begin{equation}x^{2} + 6x + 9 = 16\\end{equation}\n\nSo, how does that help? Well, we can now factor the trinomial expression as a perfect square binomial expression:\n\n\\begin{equation}(x + 3)^{2} = 16\\end{equation}\n\nAnd now, we can use the square root method to find x + 3:\n\n\\begin{equation}x + 3 =\\pm\\sqrt{16}\\end{equation}\n\nSo, x + 3 is **-4** or **4**. We isolate ***x*** by subtracting 3 from both sides, so ***x*** is **-7** or **1**:\n\n\\begin{equation}x = -7, 1\\end{equation}\n\nLet's see what the parabola for this equation looks like in R:\n\n\n```R\nx1 = as.integer(-sqrt(16) - 3)\nx2 = as.integer(sqrt(16) - 3)\n\n# Create a dataframe with an x column containing some values to plot\ndf = data.frame(x = seq(x1-10, x2+10))\n\n# Add a y column by applying the quadratic equation to x\ndf$y = ((df$x + 3)**2) - 16\n\n# Get x at the line of symmetry (halfway between x1 and x2)\nvx = (x1 + x2) / 2\n\n# Get y when x is at the line of symmetry\nvy = ((vx + 3)**2) - 16\n\n# get min and max y values\nminy = min(df$y)\nmaxy = max(df$y)\n \n## data frame for line of symmetry\nsymmetry = data.frame(sx = c(vx,vx), sy = c(miny,maxy))\n \n## data frame for xlimits\nxlims = data.frame(x = c(x1,x2), y = c(0,0))\n \n## Plot the parabola\nggplot(df, aes(x,y)) + \n geom_line(color = 'blue', size = 1) +\n geom_line(data = symmetry, aes(sx,sy), color = 'magenta', size = 1) + \n geom_point(data = symmetry, aes(sx,sy), color = 'magenta', size = 2) +\n geom_point(data = xlims, aes(x,y), color = 'red', size = 2) +\n geom_text(data = xlims, aes(label=c('x1','x2')),hjust=-0.5, vjust=0) +\n annotate(\"text\", x = vx, y = -20, label = \"Vertex\") +\n geom_hline(yintercept=0) + geom_vline(xintercept=0)\n\n```\n\n## Vertex Form\nLet's look at another example of a quadratic equation in standard form:\n\n\\begin{equation}y = 2x^{2} - 16x + 2\\end{equation}\n\nWe can start to solve this by subtracting 2 from both sides to move the constant term from the right to the left:\n\n\\begin{equation}y - 2 = 2x^{2} - 16x\\end{equation}\n\nNow we can factor out the coefficient for x2, which is **2**. 2x2 is 2 • x2, and -16x is 2 • 8x:\n\n\\begin{equation}y - 2 = 2(x^{2} - 8x)\\end{equation}\n\nNow we're ready to complete the square, so we add the square of half of the -8x coefficient on the right side to the parenthesis. Half of -8 is -4, and -42 is 16, so the right side of the equation becomes *2(x2 - 8x + 16)*. Of course, we can't add something to one side of the equation without also adding it to the other side, and we've just added 2 • 16 (which is 32) to the right, so we must also add that to the left.\n\n\\begin{equation}y - 2 + 32 = 2(x^{2} - 8x + 16)\\end{equation}\n\nNow we can simplify the left and factor out a perfect square binomial expression on the right:\n\n\\begin{equation}y + 30 = 2(x - 4)^{2}\\end{equation}\n\nWe now have a squared term for ***x***, so we could use the square root method to solve the equation. However, we can also isolate ***y*** by subtracting 30 from both sides. So we end up restating the original equation as:\n\n\\begin{equation}y = 2(x - 4)^{2} - 30\\end{equation}\n\nLet's just quickly check our math with Python:\n\n\n```R\nx = sample.int(100, 1)\n\n2*x**2 - 16*x + 2 == 2*(x - 4)**2 - 30\n```\n\n\nTRUE\n\n\nSo we've managed to take the expression ***2x2 - 16x + 2*** and change it to ***2(x - 4)2 - 30***. How does that help?\n\nWell, when a quadratic equation is stated this way, it's in *vertex form*, which is generically described as:\n\n\\begin{equation}y = a(x - h)^{2} + k\\end{equation}\n\nThe neat thing about this form of the equation is that it tells us the coordinates of the vertex - it's at ***h,k***.\n\nSo in this case, we know that the vertex of our equation is 4, -30. Moreover, we know that the line of symmetry is at ***x = 4***.\n\nWe can then just use the equation to calculate two more points, and the three points will be enough for us to determine the shape of the parabola. We can simply choose any ***x*** value we like and substitute it into the equation to calculate the corresponding ***y*** value. For example, let's calculate ***y*** when x is **0**:\n\n\\begin{equation}y = 2(0 - 4)^{2} - 30\\end{equation}\n\nWhen we work through the equation, it gives us the answer **2**, so we know that the point 0, 2 is in our parabola.\n\nSo, we know that the line of symmetry is at ***x = h*** (which is 4), and we now know that the ***y*** value when ***x*** is 0 (***h*** - ***h***) is 2. The ***y*** value at the same distance from the line of symmetry in the negative direction will be the same as the value in the positive direction, so when ***x*** is ***h*** + ***h***, the ***y*** value will also be 2.\n\nThe following Python code encapulates all of this in a function that draws and annotates a parabola using only the ***a***, ***h***, and ***k*** values from a quadratic equation in vertex form:\n\n\n```R\nplot_parabola_from_vertex_form = function(a, h, k){\n # Create a dataframe with an x column containing values from x=-10 to x=10)\n df = data.frame(x = seq(h-10, h+10))\n \n # Add a y column by applying the quadratic equation to x\n df$y = (a*(df$x - h)**2) + k\n\n # get min and max y values\n miny = min(df$y)\n maxy = max(df$y)\n \n # calculate y when x is 0 (h+-h)\n y = a*(0 - h)**2 + k\n \n ## data frame for line of symmetry\n symmetry = data.frame(sx = c(h,h), sy = c(miny,maxy))\n \n ## data frame for xlimits\n xlims = data.frame(x = c(h-h, h+h), y = c(y,y))\n \n ## Plot the parabola\n ggplot(df, aes(x,y)) + \n geom_line(color = 'blue', size = 1) +\n geom_line(data = symmetry, aes(sx,sy), color = 'magenta', size = 1) + \n geom_point(data = symmetry, aes(sx,sy), color = 'magenta', size = 2) +\n geom_point(data = xlims, aes(x,y), color = 'red', size = 2) +\n geom_text(data = xlims, aes(label=c(toString(h-h),toString(h+h))),hjust=-0.5, vjust=0) +\n annotate(\"text\", x = h, y = -40, label = paste('v = ',toString(h),',',toString(miny))) +\n geom_hline(yintercept=0) + geom_vline(xintercept=0)\n }\n\n# Call the function for the example discussed above\nplot_parabola_from_vertex_form(2, 4, -30) \n```\n\n\n```R\nplot_parabola_from_vertex_form(3, -1, -1)\n```\n\n## Shortcuts for Solving Quadratic Equations\nWe've spent some time in this notebook discussing how to solve quadratic equations to determine the vertex of a parabola and the ***x*** values in relation to ***y***. It's important to understand the techniques we've used, which incude:\n- Factoring\n- Calculating the Square Root\n- Completing the Square\n- Using the vertex form of the equation\n\nThe underlying algebra for all of these techniques is the same, and this consistent algebra results in some shortcuts that you can memorize to make it easier to solve quadratic equations without going through all of the steps:\n\n### Calculating the Vertex from Standard Form\nYou've already seen that converting a quadratic equation to the vertex form makes it easy to identify the vertex coordinates, as they're encoded as ***h*** and ***k*** in the equation itself - like this:\n\n\\begin{equation}y = a(x - \\textbf{h})^{2} + \\textbf{k}\\end{equation}\n\nHowever, what if you have an equation in standard form?:\n\n\\begin{equation}y = ax^{2} + bx + c\\end{equation}\n\nThere's a quick and easy technique you can apply to get the vertex coordinates. \n\n1. To find ***h*** (which is the x-coordinate of the vertex), apply the following formula:\n\\begin{equation}h = \\frac{-b}{2a}\\end{equation}\n2. After you've found ***h***, use it in the quadratic equation to solve for ***k***:\n\\begin{equation}\\textbf{k} = a\\textbf{h}^{2} + b\\textbf{h} + c\\end{equation}\n\nFor example, here's the quadratic equation in standard form that we previously converted to the vertex form:\n\n\\begin{equation}y = 2x^{2} - 16x + 2\\end{equation}\n\nTo find ***h***, we perform the following calculation:\n\n\\begin{equation}h = \\frac{-b}{2a}\\;\\;\\;\\;=\\;\\;\\;\\;\\frac{-1 \\cdot16}{2\\cdot2}\\;\\;\\;\\;=\\;\\;\\;\\;\\frac{16}{4}\\;\\;\\;\\;=\\;\\;\\;\\;4\\end{equation}\n\nThen we simply plug the value we've obtained for ***h*** into the quadratic equation in order to find ***k***:\n\n\\begin{equation}k = 2\\cdot(4^{2}) - 16\\cdot4 + 2\\;\\;\\;\\;=\\;\\;\\;\\;32 - 64 + 2\\;\\;\\;\\;=\\;\\;\\;\\;-30\\end{equation}\n\nNote that a vertex at 4,-30 is also what we previously calculated for the vertex form of the same equation:\n\n\\begin{equation}y = 2(x - 4)^{2} - 30\\end{equation}\n\n### The Quadratic Formula\nAnother useful formula to remember is the *quadratic formula*, which makes it easy to calculate values for ***x*** when ***y*** is **0**; or in other words:\n\n\\begin{equation}ax^{2} + bx + c = 0\\end{equation}\n\nHere's the formula:\n\n\\begin{equation}x = \\frac{-b \\pm \\sqrt{b^{2} - 4ac}}{2a}\\end{equation}\n\nLet's apply that formula to our equation, which you may remember looks like this:\n\n\\begin{equation}y = 2x^{2} - 16x + 2\\end{equation}\n\nOK, let's plug the ***a***, ***b***, and ***c*** variables from our equation into the quadratic formula:\n\n\\begin{equation}x = \\frac{--16 \\pm \\sqrt{-16^{2} - 4\\cdot2\\cdot2}}{2\\cdot2}\\end{equation}\n\nThis simplifes to:\n\n\\begin{equation}x = \\frac{16 \\pm \\sqrt{256 - 16}}{4}\\end{equation}\n\nThis in turn (with the help of a calculator) simplifies to:\n\n\\begin{equation}x = \\frac{16 \\pm 15.491933384829668}{4}\\end{equation}\n\nSo our positive value for ***x*** is:\n\n\\begin{equation}x = \\frac{16 + 15.491933384829668}{4}\\;\\;\\;\\;=7.872983346207417\\end{equation}\n\nAnd the negative value for ***x*** is:\n\n\\begin{equation}x = \\frac{16 - 15.491933384829668}{4}\\;\\;\\;\\;=0.12701665379258298\\end{equation}\n\n\n\nThe following Python code uses the vertex formula and the quadtratic formula to calculate the vertex and the -x and +x for y = 0, and then plots the resulting parabola:\n\n\n```R\nplot_parabola_from_formula = function(a, b, c){\n # Get vertex\n print('CALCULATING THE VERTEX')\n print('vx = -b / 2a')\n\n nb = -b\n a2 = 2*a\n print(paste('vx = ', toString(nb), ' / ', toString(a2)))\n\n vx = -b/(2*a)\n print(paste('vx = ', toString(vx)))\n\n cat('\\n')\n print('vy = ax^2 + bx + c')\n print(paste('vy =', toString(a), '(', toString(vx), '^2) + ', \n toString(b), '(', toString(vx), ') + ', toString(c)))\n\n avx2 = a*vx**2\n bvx = b*vx\n print(paste('vy =', toString(avx2), ' + ', toString(bvx), ' + ', toString(c)))\n\n vy = avx2 + bvx + c\n print(paste('vy = ', toString(vy)))\n\n cat('\\n') \n print (paste('v = ', toString(vx), ',', toString(vy)))\n\n # Get +x and -x (showing intermediate calculations)\n cat('\\n')\n print('CALCULATING -x AND +x FOR y=0')\n print('x = -b +- sqrt(b^2 - 4ac) / 2a')\n \n b2 = b**2\n ac4 = 4*a*c\n print(paste('x = ', toString(nb), '+-sqrt(', toString(b2), \n ' - ', toString(ac4), ')/', toString(a2)))\n\n sr = sqrt(b2 - ac4)\n print(paste('x = ', toString(nb), ' +- ', toString(sr), ' / ', toString(a2)))\n print(paste('-x = ', toString(nb), ' - ', toString(sr), ' / ', toString(a2)))\n print(paste('+x = ', toString(nb), ' + ', toString(sr), ' / ', toString(a2)))\n\n posx = (nb + sr) / a2\n negx = (nb - sr) / a2\n print(paste('-x = ', toString(negx)))\n print(paste('+x = ', toString(posx)))\n\n cat('\\n')\n print('PLOTTING THE PARABOLA')\n \n # Create a dataframe with an x column containing values from x=-10 to x=10)\n df = data.frame(x = seq(round(vx)-10, round(vx)+10))\n \n # Add a y column by applying the quadratic equation to x\n df$y = a*df$x**2 + b*df$x + c\n\n # get min and max y values\n miny = min(df$y)\n maxy = max(df$y)\n \n ## data frame for line of symmetry\n symmetry = data.frame(sx = c(vx,vx), sy = c(miny,maxy))\n \n ## data frame for xlimits\n xlims = data.frame(x = c(negx, posx), y = c(0,0))\n \n ## Plot the parabola\n ggplot(df, aes(x,y)) + \n geom_line(color = 'blue', size = 1) +\n geom_line(data = symmetry, aes(sx,sy), color = 'magenta', size = 1) + \n geom_point(data = symmetry, aes(sx,sy), color = 'magenta', size = 2) +\n geom_point(data = xlims, aes(x,y), color = 'red', size = 2) +\n geom_text(data = xlims, aes(label=c(toString(round(negx,4)),toString(round(posx,4)))),hjust=-0.2, vjust=0) +\n annotate(\"text\", x = 4, y = -40, label = paste('v = ',toString(vx),',',toString(vy))) +\n geom_hline(yintercept=0) + geom_vline(xintercept=0)\n }\n\nplot_parabola_from_formula (2, -16, 2)\n```\n", "meta": {"hexsha": "062b8fa48a8bd30354e970fde26e33b4ec8fa2e3", "size": 104301, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "R/Module01/01-07-Quadratic Equations.ipynb", "max_stars_repo_name": "joelgenter/Essential-Math", "max_stars_repo_head_hexsha": "2e76546a82fb0ad2b8698c7dc0f48f0aad0762bb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 33, "max_stars_repo_stars_event_min_datetime": "2018-01-11T20:44:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T16:10:41.000Z", "max_issues_repo_path": "R/Module01/01-07-Quadratic Equations.ipynb", "max_issues_repo_name": "joelgenter/Essential-Math", "max_issues_repo_head_hexsha": "2e76546a82fb0ad2b8698c7dc0f48f0aad0762bb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2018-11-19T23:54:27.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-20T00:15:39.000Z", "max_forks_repo_path": "R/Module01/01-07-Quadratic Equations.ipynb", "max_forks_repo_name": "joelgenter/Essential-Math", "max_forks_repo_head_hexsha": "2e76546a82fb0ad2b8698c7dc0f48f0aad0762bb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 35, "max_forks_repo_forks_event_min_datetime": "2018-03-08T15:42:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-03T06:11:43.000Z", "avg_line_length": 113.6176470588, "max_line_length": 7252, "alphanum_fraction": 0.8079692429, "converted": true, "num_tokens": 7939, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172688214138, "lm_q2_score": 0.9314625102975306, "lm_q1q2_score": 0.8838808612810708}} {"text": "sergazy.nurbavliyev@gmail.com © 2021\n\n## Is the coin biased?\n\nQuestion: A coin is flipped 1000 times and 560 times heads show up. Do you think the coin is biased?\n\n\nhttps://stats.stackexchange.com/questions/282786/a-job-interview-question-on-flipping-a-coin\n\n## Answer\n\nIt is already answered pretty nice in the stackexchange website where I give the link above. I would definitely try exactly the same way. \n\nSince the 1000 sample size is large enough, we can apply the Central Limit Theorem. Assume probability of head is $p$ and probability of tails as $q$. Note $p+q=1$. We want to know if $p=1/2$ or not. \n\nAssuming each trial are independent of each other, if $p=1/2$ then we should have expected to see 500 heads.\nand the variance is given by:\n\\begin{equation}\n\\sigma^2= np(1-p)=1000\\frac{1}{2}\\frac{1}{2}=250 \n\\end{equation}\nthen the standard deviation would be $\\sqrt{250}=15.81$. Remembering the 68-95-99.7 rule for a Normal Distribution\nwe can calculate the z-score for 560 heads:\n\\begin{equation}\nz = \\frac{560-500}{15.81}=3.79\n\\end{equation}\nRemember that 99.7% of the data lies within 3 standard deviation (15.81) of the mean 500. However, we see that here z lies outside of the 99.7%. In other words, if our coin was fair, then probibility of seeing 560 heads is less than 0.03. This means that, most probably our coin is biased coin.\n\n\n```python\n60/250**(1/2)\n```\n\n\n\n\n 3.794733192202055\n\n\n\n\n```python\n60\n```\n\n## Python code for simulation\n\n\n```python\nimport random\ntrial_list= [sum([random.randint(0,1) for i in range(1000)]) for j in range(1000)]\n```\n\n\n```python\nfrom matplotlib import pyplot as plt\nplt.plot(trial_list)\nplt.axhline(y=560, color='r', linestyle='-')\nplt.show()\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "0eb84fcb48116c6cb0fa8752f7cea2a25901e0aa", "size": 31785, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Is the coin biased March 10 2021.ipynb", "max_stars_repo_name": "sernur/probability_stats_interveiw_questions", "max_stars_repo_head_hexsha": "3144dae00fa83c82ff4e1f7668828349270a1937", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2021-03-04T06:48:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-19T10:04:24.000Z", "max_issues_repo_path": "Is the coin biased March 10 2021.ipynb", "max_issues_repo_name": "sernur/probability_stats_interveiw_questions", "max_issues_repo_head_hexsha": "3144dae00fa83c82ff4e1f7668828349270a1937", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-03-05T22:00:43.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-05T22:00:43.000Z", "max_forks_repo_path": "Is the coin biased March 10 2021.ipynb", "max_forks_repo_name": "sernur/probability_stats_interveiw_questions", "max_forks_repo_head_hexsha": "3144dae00fa83c82ff4e1f7668828349270a1937", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-03-04T05:02:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-16T01:13:40.000Z", "avg_line_length": 156.5763546798, "max_line_length": 26956, "alphanum_fraction": 0.9053012427, "converted": true, "num_tokens": 508, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572778000158576, "lm_q2_score": 0.9230391669503405, "lm_q1q2_score": 0.8836049030666918}} {"text": "## Shanon Information Content\n\nFirst, let's consider storing an integer that isn't random. Let's say we have an integer that is from $0,1,\\dots ,63$. Then the number of bits needed to store this integer is $\\log _{2}(64)=6$ bits: you tell me $6$ bits and I can tell you exactly what the integer is.\n\nA different way to think about this result is that we don't a priori know which of the $64$ outcomes is going to be stored, and so each outcome is equally likely with probability $\\frac{1}{64}$. Then the number of bits needed to store an event $\\mathcal{A}$ is given by what's called the “Shannon information content\" (also called self-information):\n\n$$\\log _{2}\\frac{1}{\\mathbb {P}(\\mathcal{A})}.$$\n \nIn particular, for an integer $x\\in \\{ 0,1,\\dots ,63\\}$, the Shannon information content of observing $x$ is\n\n$$\\log _{2}\\frac{1}{\\mathbb {P}(\\text {integer is }x)}=\\log _{2}\\frac{1}{1/64}=\\log _{2}64=6\\text { bits}.$$\n \nIf instead, the integer was deterministically $0$ and never equal to any of the other values $1,2,\\dots ,63,$ then the Shannon information content of observing integer $0$ is\n\n$$\\log _{2}\\frac{1}{\\mathbb {P}(\\text {integer is }0)}=\\log _{2}\\frac{1}{1}=0\\text { bits}.$$\n \nThis is not surprising in that a outcome that we deterministically always observe tells us no new information. Meanwhile, for each integer $x\\in \\{ 1,2,\\dots ,63\\},$\n\n$$\\log _{2}\\frac{1}{\\mathbb {P}(\\text {integer is }x)}=\\log _{2}\\frac{1}{0}=\\infty \\text { bits}.$$\n \nHow could observing one of the integers $\\{ 1,2,\\dots ,63\\}$ tell us infinite bits of information?! Well, this isn't an issue since the event that we observe any of these integers has probability $0$ and is thus impossible. An interpration of Shannon information content is how surprised we would be to observe an event. In this sense, observing an impossible event would be infinitely surprising.\n\nIt is possible to have the Shannon information content of an event be some fractional number of bits (e.g., $0.7$ bits). The interpretation is that from many repeats of the underlying experiment, the average number of bits needed to store the event is given by the Shannon information content, which can be fractional.\n\n### Exercise: Shannon Information Content\n\nI have an integer in mind, uniformly distributed between $0$ and $127$. You can keep guessing what my number is until you get it right (and each time you guess, I tell you whether you got it right). Each time you guess a number wrong, you discard that number so as to not guess it again.\n\nFor example, if you guess wrong the first time, then the Shannon information content of guessing wrong is\n\n$$\\log _2\\frac{1}{\\frac{127}{128}}=\\log _{2}\\frac{128}{127}=0.0113\\dots \\text { bits}.$$\n \nIf you guess wrong the second time, then the Shannon information content of the second guess is\n\n$$\\log _2\\frac{1}{\\frac{126}{127}}=\\log _{2}\\frac{127}{126}=0.0114\\dots \\text { bits}.$$\n \nIf you guess right on the third time, then the Shannon information content of the third guess is\n\n$$\\log _2\\frac{1}{\\frac{1}{126}}=\\log _{2}\\frac{126}{1}=6.9772\\dots \\text { bits}.$$\n \n**Question:** For the above example where the third guess is right, what is the sum of the Shannon information content of the three guesses? \n\n**Solution:**\n$$\\begin{eqnarray}\n&&\n\\log_2 \\frac1{\\frac{127}{128}}\n+\\log_2 \\frac1{\\frac{126}{127}}\n+\\log_2 \\frac1{\\frac{1}{126}} \\\\\n&&=\n\\log_2 \\frac{128}{127}\n+\\log_2 \\frac{127}{126}\n+\\log_2 126 \\\\\n&&=\n\\log_2 128 - \\log_2 127\n+ \\log_2 127 - \\log_2 126\n+ \\log_2 126 \\\\\n&&=\n\\log_2 128 \\\\\n&&=\n\\boxed{7\\text{ bits}}.\n\\end{eqnarray}$$\n\n**Question:** Suppose you guessed right only after 5 tries. What is the sum of the Shannon information content of these 5 guesses? \n\n**Solution:**\n\n$$\\begin{eqnarray}\n&&\\log_2 \\frac1{\\frac{127}{128}}\n+\\log_2 \\frac1{\\frac{126}{127}}\n+\\log_2 \\frac1{\\frac{125}{126}}\n+\\log_2 \\frac1{\\frac{124}{125}}\n+\\log_2 \\frac1{\\frac{1}{124}} \\\\\n&&=\n\\log_2 \\frac{128}{127}\n+\\log_2 \\frac{127}{126}\n+\\log_2 \\frac{126}{125}\n+\\log_2 \\frac{125}{124}\n+\\log_2 124 \\\\\n&&=\n\\log_2 128 - \\log_2 127\n+ \\log_2 127 - \\log_2 126\n+ \\log_2 126 \\\\\n&&\\quad\n- \\log_2 125\n+ \\log_2 125 - \\log_2 124\n+ \\log_2 124 \\\\\n&&=\n\\log_2 128 \\\\\n&&=\n\\boxed{7\\text{ bits}}.\n\\end{eqnarray}$$ \n\n**Question:** Suppose you guess right after $k$ tries $(k \\in \\{ 1, 2, \\dots , 128\\})$. If you sum up the Shannon information content for all the guesses up and including the one in which you guess right, does this total number of bits depend on $k$? (While we aren't asking for you to justify your answer, we encourage you to be able to do so! For example, if your answer is \"Yes\" then you should be able to come up with two specific cases for two different number of tries before guessing right that yield different number of total bits, and if your answer is \"No\" then you should be able to show why the total number of bits gained is always the same.)\n\n**Solution:** The answer is no. The previous two parts provide a clue: the sum we're computing is a telescoping sum where all the terms cancel out except for the first one: $\\log _2 128 = 7.$\n\nIn general, if we guess right after $k$ tries, then the total amount of information “learned\" is:\n\n$$\\begin{eqnarray}\n&&\n\\left[\n\\sum_{i=1}^{k-1}\n \\log_2 \\frac1{\\frac{128 - i}{128 - (i - 1)}}\n\\right]\n+ \\log_2 (128 - (k - 1)) \\\\\n&&=\n\\left[\n\\sum_{i=1}^{k-1}\n \\log_2 \\frac{128 - (i - 1)}{128 - i}\n\\right]\n+ \\log_2 (128 - (k - 1)) \\\\\n&&=\n\\left[\n\\sum_{i=1}^{k-1}\n \\log_2 (128 - (i - 1)) - \\log_2(128 - i)\n\\right]\n+ \\log_2 (128 - (k - 1)) \\\\\n&&= \\log_2 128 - \\log_2 127 + \\log_2 127 - \\cdots \\\\\n&&\\quad\n- \\log_2 (128 - (k - 1)) + \\log_2 (128 - (k - 1)) \\\\\n&&= \\log_2 128 \\\\\n&&= 7\\text{ bits}.\n\\end{eqnarray}$$\n\nPut another way, $7$ bits of information are needed before you know the number, and with wrong guesses, you learn very few bits of information (although as the number of possibilities shrinks, wrong guesses provide more and more bits of information).\n\n### Shanon Entropy\n\nTo go from the number of bits contained in an event to the number of bits contained in a random variable, we simply take the expectation of the Shannon information content across the possible outcomes. The resulting quantity is called the entropy of a random variable:\n\n$$H(X)=\\sum _{x}p_{X}(x)\\underbrace{\\log _{2}\\frac{1}{p_{X}(x)}}_{\\text {Shannon information content of event }X=x}.$$\n \nThe interpretation is that on average, the number of bits needed to encode each i.i.d. sample of a random variable X is $H(X)$. In fact, if we sample n times i.i.d. from $p_{X}$, then two fundamental results in information theory that are beyond the scope of this course state that: (a) there's an algorithm that is able to store these n samples in $nH(X)$ bits, and (b) we can't possibly store the sequence in fewer than $nH(X)$ bits!\n\n**Example:** If $X$ is a fair coin toss “heads\" or “tails\" each with probability $1/2$, then\n\n$$\\begin{eqnarray}\nH(X)\n&=& p_X(\\text{heads}) \\log_2 \\frac1{p_X(\\text{heads})}\n+ p_X(\\text{tails}) \\log_2 \\frac1{p_X(\\text{tails})} \\\\\n&=& \\frac12 \\cdot \\underbrace{\\log_2 \\frac1{\\frac{1}{2}}}_1\n+ \\frac12 \\cdot \\underbrace{\\log_2 \\frac1{\\frac{1}{2}}}_1 \\\\\n&=& 1 \\text{ bit}.\n\\end{eqnarray}$$\n\n**Example:** If $X$ is a biased coin toss where heads occurs with probability $1$ then\n\n$$\\begin{eqnarray}\nH(X)\n&=& p_X(\\text{heads}) \\log_2 \\frac1{p_X(\\text{heads})}\n+ p_X(\\text{tails}) \\log_2 \\frac1{p_X(\\text{tails})} \\\\\n&=& 1 \\cdot \\underbrace{\\log_2 \\frac11}_0\n+ 0 \\cdot \\cdot \\underbrace{\\log_2 \\frac10}_1 \\\\\n&=& 0 \\text{ bits},\n\\end{eqnarray}$$\n\nwhere $0 \\log _2 \\frac10 = 0 \\log _2 1 - 0 \\log _2 0 = 0$ using the convention that $0 \\log _2 0 \\triangleq 0$. (Note: You can use l'Hopital's rule from calculus to show that $\\lim _{x\\rightarrow 0} x \\log x = 0 and \\lim _{x\\rightarrow 0} x \\log \\frac1x = 0$.)\n\nNotation: Note that entropy $H(X) = \\sum _ x p_ X(x) \\log _2 \\frac{1}{p_ X(x)}$ is in the form of an expectation! So in fact, we can write an expectation:\n\n$$H(X) = \\mathbb {E}\\left[\\log _2 \\frac{1}{p_ X(X)}\\right].$$\n\n\n```python\ndef H(pX):\n \"\"\"\n Retrun Shanon entropy of given probability.\n >>> pX = {-1: 999999/1000000, 999 : 1/1000000}\n >>> H(pX)\n 2.137426288890686e-05\n \n >>> coin = {'H': 1/2, 'T': 1/2}\n >>> H(coin)\n 1.0\n \"\"\"\n from math import log\n return - sum([value * log(value,2) for key, value in pX.items()]) \n\nif __name__ == \"__main__\":\n import doctest\n doctest.testmod()\n```\n\n### Exercise: Shannon Entropy\n\nEntropy gives a very different measure for uncertainty than variance, which we saw previously. Whereas variance $\\text {var}(X) = \\mathbb {E}[(X-\\mathbb {E}[X])^2]$ measures how far a random variable is expected to deviate from its expected value $\\mathbb {E}[X]$, entropy measures how many bits are needed on average to store each i.i.d. sample of a random variable $X$.\n\nLet's return to the three lotteries from earlier. Here, random variables $L_1, L_2,$ and $L_3$ represent the amount won (accounting for having to pay \\$1):\n\n|$L_1$ | $p$ | $L_2$ | $p$ | $L_3$ | $p$ |\n|----------:|:------------------------:|-------------:|:------------------------:|--------:|:--------------:|\n| -1 | $\\frac{999999}{1000000}$ | -1 | $\\frac{999999}{1000000}$ | -1 | $\\frac{9}{10}$ |\n| -1+1000 | $\\frac{1}{1000000}$ | -1+1000000 | $\\frac{1}{1000000}$ | -1+10 | $\\frac{1}{10}$ |\n\nCompute the following entropies in bits. Please input just the number and do not include the text \"bits\" at the end. (Please be precise with at least $7$ decimal places, unless of course the answer doesn't need that many decimal places. You could also put a fraction.)\n\n- $H(L_1) =$ {{H_1}} \n- $H(L_2) =$ {{H_2}}\n- $H(L_3) =$ {{H_3}} \n\n\n```python\np_L1 = {-1: 999999/1000000, 999 : 1/1000000}\np_L2 = {-1: 999999/1000000, 999999: 1/1000000}\np_L3 = {-1: 9/10 , 9 : 1/10 }\n\nH_1 = '{0:0.7f}'.format(H(p_L1))\nH_2 = '{0:0.7f}'.format(H(p_L2))\nH_3 = '{0:0.7f}'.format(H(p_L3))\n```\n\nNow that you've computed some entropies, let's answer some general questions about entropy.\n\n**Question:** In computing the entropy of a random variable $X$, we look at the probabilities in the probability table of $X.$ Did we have to look at the labels in the probability table (note that the labels correspond to the alphabet of $X$)?\n\n[$\\times $] Yes
\n[$\\checkmark$] No\n\n**Solution:** The answer is no. You can see this in the Python code: we don't need to look at the alphabet $\\mathcal{X}$.\n\nSuppose for a random variable $X$, we take its probability table and shuffle the ordering of the probabilities (but otherwise keep the labels the same). For example, if $X$ is a biased coin flip with probability of heads $3/4$, suppose we took its table and instead have the probability of tails be $3/4$ and the probability of heads be $1/4$.\n\n**Question:** By shuffling the ordering of the probabilities, does the entropy of the random variable change?\n\n[$\\times $] Yes
\n[$\\checkmark$] No\n\n**Solution:** The answer is no. Since what the labels are does not actually matter (of course, we cannot have the same label appear twice in the table though), we can permute the labels (or the probabilities) and get the same entropy.\n\nFinally, let's think about how small and large entropy could be.\n\n**Question:** We've seen an example where the entropy is $0$ bits. Can entropy be negative? (While there is an intuitive answer for this, see if you can show it mathematically.)\n\n[$\\times $] Yes
\n[$\\checkmark$] No\n\n**Solution:** The answer is no. First, note that for any probability $p\\in [0,1]$, the Shannon information content corresponding to this probability is $\\log_2 (1/p)$, which has a value from $0$ to infinity, i.e., Shannon information content is always nonnegative. Shannon entropy is just a weighted average of Shannon information content, where the weights are nonnegative. A nonnegative weighted sum of a collection of nonnegative numbers remains nonnegative.\n\n**Question:** For a random variable $X$ that takes on one of two values, one with probability $p$ and the other with probability $1-p$, plot the entropy $H(p)$ as a function of $p$ in Python. For what value of $p$ is the entropy maximized (i.e., what value of $p$ yields the largest $H(X))$? Please provide an exact answer.\n\n\n```python\n%matplotlib inline\nimport numpy as np\n# Ignore divide by zero error\n# Ref: http://stackoverflow.com/questions/14861891/runtimewarning-invalid-value-encountered-in-divide\nnp.seterr(divide='ignore', invalid='ignore')\nimport matplotlib.pyplot as plt\n\nentropy = lambda p: np.sum(p * np.log2(1 / p))\n\np_list = np.linspace(0, 1, 50)\nplt.figure()\nplt.plot(p_list,\n [entropy(np.array([p, 1-p])) for p in p_list])\nplt.xlabel('p')\nplt.ylabel('H(Ber(p))')\nplt.show()\n```\n\n## Information divergence \n\nInformation divergence (also called “Kullback-Leibler divergence\" or “KL divergence\" for short, or also “relative entropy\") is a measure of how different two distributions $p$ and $q$ (over the same alphabet) are. To come up with information divergence, first, note that entropy of a random variable with distribution $p$ could be thought of as the expected number of bits needed to encode a sample from $p$ using the information content according to distribution $p$:\n\n$$\\underbrace{\\sum _{x}p(x)}_{\\begin{matrix}\\text {expectation } \\\\ \\text{using }p\\end{matrix} }\\underbrace{\\log _{2}\\frac{1}{p(x)}}_{\\begin{matrix}\\text { information content } \\\\ \\text{ according to }p \\end{matrix}}\\triangleq \\mathbb {E}_{X \\sim p}\\Big[\\log _{2}\\frac{1}{p(X)}\\Big].$$\n \nHere, we have introduced a new notation: $\\mathbb {E}_{X \\sim p}$ means that we are taking the expectation with respect to random variable $X$ drawn from the distribution $p$. If it's clear which random variable we are taking the expectation with respect to, we will often just abbreviate the notation and write $\\mathbb {E}_ p$ instead of $\\mathbb {E}_{X \\sim p}$.\n\nIf instead we look at the information content according to a different distribution $q$, we get\n\n$$\\underbrace{\\sum _{x}p(x)}_{\\begin{matrix}\\text {expectation } \\\\ \\text{using }p\\end{matrix} }\\underbrace{\\log _{2}\\frac{1}{p(x)}}_{\\begin{matrix}\\text { information content } \\\\ \\text{ according to }p \\end{matrix}}\\triangleq \\mathbb {E}_{X \\sim p}\\Big[\\log _{2}\\frac{1}{p(X)}\\Big].$$\n \nIt turns out that if we are actually sampling from p but encoding samples as if they were from a different distribution $q$, then we always need to use more bits! This isn't terribly surprising in light of the fundamental result we alluded to that entropy of a random variable with distribution $p$ is the minimum number of bits needed to encode samples from $p$.\n\nInformation divergence is the price you pay in bits for trying to encode a sample from $p$ using information content according to $q$ instead of according to $p$:\n\n$$D(p\\parallel q)=\\mathbb {E}_{X \\sim p}\\Big[\\log _{2}\\frac{1}{q(X)}\\Big]-\\mathbb {E}_{X \\sim p}\\Big[\\log _{2}\\frac{1}{p(X)}\\Big].$$\n \nInformation divergence is always at least $0$, and when it is equal to $0$, then this means that $p$ and $q$ are the same distribution (i.e., $p(x) = q(x)$ for all $x$). This property is called Gibbs' inequality.\n\nGibbs' inequality makes information divergence seem a bit like a distance. However, information divergence is not like a distance in that it is not symmetric: in general, $D(p \\parallel q) \\ne D(q \\parallel p).$\n\nOften times, the equation for information divergence is written more concisely as\n\n$$D(p\\parallel q) = \\sum _ x p(x) \\log \\frac{p(x)}{q(x)},$$\n \nwhich you can get as follows:\n\n$$\\begin{eqnarray}\nD(p\\parallel q)\n&=&\n \\mathbb{E}_{X \\sim p}\\Big[\\log_{2}\\frac{1}{q(X)}\\Big]\n- \\mathbb{E}_{X \\sim p}\\Big[\\log_{2}\\frac{1}{p(X)}\\Big] \\\\\n&=&\n \\sum_x p(x) \\log_2 \\frac{1}{q(x)}\n- \\sum_x p(x) \\log_2 \\frac{1}{p(x)} \\\\\n&=&\n \\sum_x p(x)\n \\Big[ \\log_2 \\frac{1}{q(x)} - \\log_2 \\frac{1}{p(x)} \\Big] \\\\\n&=&\n \\sum_x p(x)\n \\log_2 \\frac{p(x)}{q(x)}.\n\\end{eqnarray}$$\n\nExample: Suppose $p$ is the distribution for a fair coin flip:\n\n$$\\begin{eqnarray}\np(x)\n&=&\n\\begin{cases}\n\\frac12 & \\text{if }x=\\text{heads}, \\\\\n\\frac12 & \\text{if }x=\\text{tails}. \\\\\n\\end{cases}\n\\end{eqnarray}$$\n\nMeanwhile, suppose q is a distribution for a biased coin that always comes up heads (perhaps it's double-headed):\n\n$$\\begin{eqnarray}\nq(x)\n&=&\n\\begin{cases}\n1 & \\text{if }x=\\text{heads}, \\\\\n0 & \\text{if }x=\\text{tails}. \\\\\n\\end{cases}\n\\end{eqnarray}$$\n\nThen\n\n$$\\begin{eqnarray}\nD(p \\parallel q)\n&=&\n p(\\text{heads}) \\log_2 \\frac{p(\\text{heads})}{q(\\text{heads})}\n+ p(\\text{tails}) \\log_2 \\frac{p(\\text{tails})}{q(\\text{tails})} \\\\\n&=&\n \\frac12\\log_2 \\frac{\\frac12}1\n+ \\underbrace{\\frac12\\log_2 \\frac{\\frac12}0}_{\\infty} \\\\\n&=&\n \\infty\\text{ bits}.\n\\end{eqnarray}$$\n\nThis is not surprising: If we are sampling from $p$ (for which we could get tails) but trying to encode the sample using $q$ (which cannot possibly encode tails), then if we get tails, we are stuck: we can't store it! This incurs a penalty of infinity bits.\n\nMeanwhile,\n\n$$\\begin{eqnarray}\nD(q \\parallel p)\n&=&\n q(\\text{heads}) \\log_2 \\frac{q(\\text{heads})}{p(\\text{heads})}\n+ q(\\text{tails}) \\log_2 \\frac{q(\\text{tails})}{p(\\text{tails})} \\\\\n&=&\n 1 \\log_2 \\frac1{\\frac12}\n+ \\underbrace{0 \\log_2 \\frac0{\\frac12}}_0 \\\\\n&=&\n 1\\text{ bit}.\n\\end{eqnarray}$$\n\nWhen we sample from $q$, we always get heads. In fact, as we saw previously, the entropy of the distribution for an always-heads coin flip is $0$ bits since there's no randomness. But here we are sampling from $q$ and storing the sample using distribution $p$. For a fair coin flip, encoding using distribution $p$ would store each sample using on average $1$ bit. Thus, even though a sample from $q$ is deterministically heads, we store it using $1$ bit. This is the penalty we pay for storing a sample from $q$ using distribution $p$.\n\nNotice that in this example, $D(p \\parallel q) \\ne D(q \\parallel p)$. They aren't even close — one is infinity and the other is finite!\n\n### Exercise: Information Divergence\n\nWe now look at a different way to think of Shannon entropy for a random variable $X$ with alphabet $\\mathcal{X}.$\n\nLet random variable $U$ have what's called a uniform distribution over alphabet $\\mathcal{X}$, meaning that\n\n$$p_ U(x) = \\frac{1}{|\\mathcal{X}|} \\qquad \\text {for all }x\\in \\mathcal{X}.$$\n \nNotationally, we can write $U \\sim \\text {Uniform}(\\mathcal{X})$.\n\nIn the following problems, suppose the number of labels in $\\mathcal{X}$ is given by $k$, i.e., $k = |\\mathcal{X}|.$\n\n**Question:** What is $H(U)$ in terms of $k$?\n\n**Solution:**\n\n$$\\begin{eqnarray}\nH(U)\n&=& \\sum_{x\\in\\mathcal{X}} p_U(x) \\log_2 \\frac1{p_U(x)} \\\\\n&=& \\sum_{x\\in\\mathcal{X}} \\frac1k \\log_2 \\frac1{\\frac1k} \\\\\n&=& \\sum_{x\\in\\mathcal{X}} \\frac1k \\log_2 k \\\\\n&=& (\\log_2 k)\\Big(\\frac1k\\Big)\n \\underbrace{\\sum_{x\\in\\mathcal{X}} 1}_k \\\\\n&=& \\log_2 k.\n\\end{eqnarray}$$ \n\nSo using “log\" to mean log base 2, the answer is $log(k)$.\n\nNext, we examine the divergence between $p_X$ and the uniform distribution. Show that $D(p_ X \\parallel p_ U)$ can be written of the form\n\n$$D(p_ X \\parallel p_ U) = f(k) - H(X),$$\n \nfor a function $f$ that you will determine:\n\n**Question:** What is $f$? \n\n**Solution:**\n\n$$\\begin{eqnarray}\nD(p_X \\parallel p_U)\n&=& \\sum_{x\\in\\mathcal{X}} p_X(x) \\log_2 \\frac{p_X(x)}{p_U(x)} \\\\\n&=& \\sum_{x\\in\\mathcal{X}} p_X(x) \\log_2 \\frac{p_X(x)}{1/k} \\\\\n&=& \\sum_{x\\in\\mathcal{X}} p_X(x) \\log_2 (k p_X(x)) \\\\\n&=& \\sum_{x\\in\\mathcal{X}} p_X(x) \\log_2 k\n + \\sum_{x\\in\\mathcal{X}} p_X(x) \\log_2 p_X(x) \\\\\n&=& (\\log_2 k) \\underbrace{\\sum_{x\\in\\mathcal{X}} p_X(x)}_1\n + \\sum_{x\\in\\mathcal{X}} p_X(x) \\log_2 p_X(x) \\\\\n&=& \\log_2 k\n - \\sum_{x\\in\\mathcal{X}} p_X(x) \\log_2 \\frac{1}{p_X(x)} \\\\\n&=& \\underbrace{\\log_2 k}_{f(k)} - H(X).\n\\end{eqnarray}$$\n\nIn particular, $f$ is $\\log$ base $2$, which for this part you answer by just saying log to mean $\\log$ base $2$.\n\nYour answers to the previous two parts should tell you how the entropy of a uniform distribution (over an alphabet of size $k$) relates to the entropy of any distribution $p_X$ (over the same alphabet of size $k$).\n\n\nFill in the blanks:\n\n**Question:** Because of Gibbs' inequality, the entropy of random variable \\_\\_\\_\\_\\_\\_\\_ cannot be larger than the entropy of random variable \\_\\_\\_\\_\\_\\_\\_.\n\n**Solution:** Because of Gibbs' inequality, the entropy of random variable $\\underline{~X~}$ cannot be larger than the entropy of random variable $\\underline{~U~}$.\n\nIn particular, notice that from the answers to the previous parts,\n\n$$D(p_ X \\parallel p_ U) = H(U) - H(X).$$\n \nBy Gibbs' inequality, information divergence is always nonnegative, which means that we must have $H(U) - H(X) \\ge 0$, which means that $H(X) \\le H(U)$.\n\n## Proof of Gibbs' Inequality\n\nWe provide a proof for Gibbs' inequality here for those who are interested. For those of you up for the challenge, try to prove it yourself!\n\nThere are various ways to prove Gibbs' inequality. We'll be using a way that relies on the fact that $\\ln x\\le x-1$ for all $x>0$, with equality if and only if $x=1$, which we provide a proof for at the end of this page, but for which you can also readily see from the following plot:\n\n\n```python\nx = np.linspace(0,2,10000)\nplt.figure()\nplt.plot(x, np.log(x))\nplt.plot(x, x - 1)\nplt.xlabel('x')\nplt.legend(['ln(x)', 'x - 1'], loc=4)\nplt.show()\n```\n\n**Gibbs' inequality:** For any two distributions $p$ and $q$ defined over the same alphabet, we have $D(p\\parallel q)\\ge 0$, where equality holds if and only if $p$ and $q$ are the same distribution, i.e., $p(x)=q(x)$ for all $x$.\n\nProof: Recall that changing the base of a log just changes the log by a constant factor:\n\n$$\\log _{2}x=\\frac{\\ln x}{\\ln 2}.$$\n \nLet $\\mathcal{X}$ be the alphabet of distribution p restricted to where the probability is positive, i.e., $\\mathcal{X}=\\{ a\\text { such that }p(a)>0\\}.$ (There is no need to look at values a for which $p(a)=0.$)\n\nIf $q(a)=0$ for any $a\\in \\mathcal{X}$, then $D(p\\parallel q)=\\infty$, so trivially $D(p\\parallel q)>0.$\n\nWhat's left to consider is when $q(a)>0$ for every $a\\in \\mathcal{X}$. Then\n\n$$\\begin{align}D(p\\parallel q) &= \\sum _{a\\in \\mathcal{X}}p(a)\\log _{2}\\frac{p(a)}{q(a)}\\\\\t \t \n&= \\frac{1}{\\ln 2}\\sum _{a\\in \\mathcal{X}}p(a)\\ln \\frac{p(a)}{q(a)}\\\\\t \n&= -\\frac{1}{\\ln 2}\\sum _{a\\in \\mathcal{X}}p(a)\\ln \\frac{q(a)}{p(a)}.\n\\end{align}$$\n\nNext, using the fact that $\\ln x\\le x-1$ for all $x>0,$ and accounting for the minus sign outside the summation,\n\n$$\\begin{align}D(p\\parallel q) &= -\\frac{1}{\\ln 2}\\sum _{a\\in \\mathcal{X}}p(a)\\ln \\frac{q(a)}{p(a)}\t\\\\ \t \n&\\ge -\\frac{1}{\\ln 2}\\sum _{a\\in \\mathcal{X}}p(a)\\Big(\\frac{q(a)}{p(a)}-1\\Big)\t\\\\ \t \n&= -\\frac{1}{\\ln 2}\\sum _{a\\in \\mathcal{X}}\\big (q(a)-p(a)\\big )\\\\\t \t \n&= -\\frac{1}{\\ln 2}\\big (\\underbrace{\\sum _{a\\in \\mathcal{X}}q(a)}_{1}-\\underbrace{\\sum _{a\\in \\mathcal{X}}p(a)}_{1}\\big )\\\\\t \t \n&= 0. \\end{align}$$\n\nRecall that inequality $\\ln x\\le x-1$ becomes an equality if and only if $x=1.$ Thus, the inequality above becomes an equality if and only if, for all $a\\in \\mathcal{X}$, we have $\\ln \\frac{q(a)}{p(a)}=\\frac{q(a)}{p(a)}-1,$ which holds if and only if $\\frac{q(a)}{p(a)}=1.$ Thus $D(p\\parallel q)=0$ if and only if $p(a)=q(a)$ for all $a\\in \\mathcal{X}.$ This finishes the proof. $\\square$\n\nClaim: $\\ln x\\le x-1$ for all $x>0$ where equality holds if and only if $x=1.$\n\nProof: We show that the function $f$ given by $f(x)=x-1-\\ln x$ is always at least $0$ and achieves its minimum value at $x=1.$ First, note that $f$ is differentiable for all $x>0$ (which implies that $f$ is continuous on $(0,\\infty )$ and doesn't, for example, do some crazy jump midway through). In fact, the derivative of $f$ is given by\n\n$$\\frac{d}{dx}f(x)=\\frac{d}{dx}(x-1-\\ln x)=1-\\frac{1}{x}.$$\n \nOn the interval $x>0,$ the derivative is $0$ (and so there's a local extremum) precisely when $x=1.$ The question is whether this is a local minimum or a local maximum. We look at the second derivative of $f$ to do a second derivative test:\n\n$$\\frac{d^{2}}{dx^{2}}f(x)=\\frac{1}{x^{2}},$$\n \nwhich is strictly positive for all $x>0$. In other words, $x=1$ is a local minimum. The only possible other extrema could happen at the boundaries, but it's easy to check that\n\n$$\\lim _{x\\rightarrow 0}f(x) = \\lim _{x\\rightarrow 0} (x - 1 - \\ln x) = -1 - \\underbrace{\\lim _{x\\rightarrow 0} \\ln x}_{-\\infty } = \\infty ,$$\n \nand\n\n$$\\lim _{x\\rightarrow \\infty }f(x) = \\lim _{x\\rightarrow \\infty } (x - 1 - \\ln x) = \\infty ,$$\n \nsince $x$ grows faster than $\\ln x.$\n\nHence, $f$ attains its global minimum at $x=1,$ for which we have\n\n$$f(1)=1-1-\\ln 1=0.$$\n \nSince this is the global minimum, we know that $f(x)\\ge 0$ for all $x>0.$ Furthermore, since there is only one unique global minimum $x=1,$ we further conclude that $f(x)=0$ if and only if $x=1.$ $\\square$\n\n\n```python\n\n```\n", "meta": {"hexsha": "008b131f6c27b425d9315f4e383694c123924ce4", "size": 70120, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "week04/03 Measuring Randomness.ipynb", "max_stars_repo_name": "infimath/Computational-Probability-and-Inference", "max_stars_repo_head_hexsha": "e48cd52c45ffd9458383ba0f77468d31f781dc77", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-04-04T03:07:47.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-04T03:07:47.000Z", "max_issues_repo_path": "week04/03 Measuring Randomness.ipynb", "max_issues_repo_name": "infimath/Computational-Probability-and-Inference", "max_issues_repo_head_hexsha": "e48cd52c45ffd9458383ba0f77468d31f781dc77", "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": "week04/03 Measuring Randomness.ipynb", "max_forks_repo_name": "infimath/Computational-Probability-and-Inference", "max_forks_repo_head_hexsha": "e48cd52c45ffd9458383ba0f77468d31f781dc77", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-02-27T05:33:49.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-27T05:33:49.000Z", "avg_line_length": 110.4251968504, "max_line_length": 22856, "alphanum_fraction": 0.7768397034, "converted": true, "num_tokens": 8051, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.96323053709097, "lm_q2_score": 0.9173026612812898, "lm_q1q2_score": 0.8835739351009528}} {"text": "```python\nfrom sympy import *\nimport math\n```\n\n\n```python\nx,y,z = symbols(\"x,y,z,\")\n```\n\n\n```python\nfxyz = x**2*y*z\nfxyz\n```\n\n\n\n\n$\\displaystyle x^{2} y z$\n\n\n\n\n```python\nf_x =diff(fxyz,x)\nf_x\n```\n\n\n\n\n$\\displaystyle 2 x y z$\n\n\n\n\n```python\nf_y = diff(fxyz,y)\nf_y\n```\n\n\n\n\n$\\displaystyle x^{2} z$\n\n\n\n\n```python\nf_z = diff(fxyz,z)\nf_z\n```\n\n\n\n\n$\\displaystyle x^{2} y$\n\n\n\n\n```python\njacobian = Matrix([[f_x,f_y,f_z]])\njacobian\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}2 x y z & x^{2} z & x^{2} y\\end{matrix}\\right]$\n\n\n\n\n```python\njx_x = diff(f_x,x)\njx_x\n```\n\n\n\n\n$\\displaystyle 2 y z$\n\n\n\n\n```python\njx_y = diff(f_x,y)\njx_y\n```\n\n\n\n\n$\\displaystyle 2 x z$\n\n\n\n\n```python\njx_z = diff(f_x,z)\njx_z\n```\n\n\n\n\n$\\displaystyle 2 x y$\n\n\n\n\n```python\njy_x = diff(f_y,x)\njy_x\n```\n\n\n\n\n$\\displaystyle 2 x z$\n\n\n\n\n```python\njy_y = diff(f_y,y)\njy_y\n```\n\n\n\n\n$\\displaystyle 0$\n\n\n\n\n```python\njy_z = diff(f_y,z)\njy_z\n```\n\n\n\n\n$\\displaystyle x^{2}$\n\n\n\n\n```python\njz_x = diff(f_z,x)\njz_x\n```\n\n\n\n\n$\\displaystyle 2 x y$\n\n\n\n\n```python\njz_y = diff(f_z,y)\njz_y\n```\n\n\n\n\n$\\displaystyle x^{2}$\n\n\n\n\n```python\njz_z = diff(f_z,z)\njz_z\n```\n\n\n\n\n$\\displaystyle 0$\n\n\n\n\n```python\nhessian = Matrix([[jx_x,jx_y,jx_z],\n [jy_x,jy_y,jy_z],\n [jz_x,jz_y,jz_z]])\nhessian\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}2 y z & 2 x z & 2 x y\\\\2 x z & 0 & x^{2}\\\\2 x y & x^{2} & 0\\end{matrix}\\right]$\n\n\n\n\n```python\nfxy = x**3*y+x+2*y\nfxy\n```\n\n\n\n\n$\\displaystyle x^{3} y + x + 2 y$\n\n\n\n\n```python\nfxy_x = diff(fxy,x)\nfxy_x\n```\n\n\n\n\n$\\displaystyle 3 x^{2} y + 1$\n\n\n\n\n```python\nfxy_y = diff(fxy,y)\nfxy_y\n```\n\n\n\n\n$\\displaystyle x^{3} + 2$\n\n\n\n\n```python\njacobian = Matrix([[fxy_x,fxy_y]])\njacobian\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}3 x^{2} y + 1 & x^{3} + 2\\end{matrix}\\right]$\n\n\n\n\n```python\njx_x = diff(fxy_x,x)\njx_x\n```\n\n\n\n\n$\\displaystyle 6 x y$\n\n\n\n\n```python\njx_y = diff(fxy_x,y)\njx_y\n```\n\n\n\n\n$\\displaystyle 3 x^{2}$\n\n\n\n\n```python\njy_x = diff(fxy_y,x)\njy_x\n```\n\n\n\n\n$\\displaystyle 3 x^{2}$\n\n\n\n\n```python\njy_y = diff(fxy_y,y)\njy_y\n```\n\n\n\n\n$\\displaystyle 0$\n\n\n\n\n```python\nhessian = Matrix([[jx_x, jx_y],\n [jy_x,jy_y]])\nhessian\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}6 x y & 3 x^{2}\\\\3 x^{2} & 0\\end{matrix}\\right]$\n\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "5a13b0066ae0db46031766c900f8416ec5790d97", "size": 10945, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Groups/Group_ID_13/HessCCAimplementation.ipynb", "max_stars_repo_name": "aryapushpa/DataScience", "max_stars_repo_head_hexsha": "89ba01c18d3ed36942ffdf3e1f3c68fd08b05324", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2020-12-13T07:53:22.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-20T18:49:27.000Z", "max_issues_repo_path": "Groups/Group_ID_13/HessCCAimplementation.ipynb", "max_issues_repo_name": "Gulnaz-Tabassum/DataScience", "max_issues_repo_head_hexsha": "1fd771f873a9bc0800458fd7c05e228bb6c4e8a0", "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": "Groups/Group_ID_13/HessCCAimplementation.ipynb", "max_forks_repo_name": "Gulnaz-Tabassum/DataScience", "max_forks_repo_head_hexsha": "1fd771f873a9bc0800458fd7c05e228bb6c4e8a0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 24, "max_forks_repo_forks_event_min_datetime": "2020-12-12T11:23:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-04T13:09:38.000Z", "avg_line_length": 17.2091194969, "max_line_length": 132, "alphanum_fraction": 0.4131566926, "converted": true, "num_tokens": 864, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9724147145755, "lm_q2_score": 0.9086178876533446, "lm_q1q2_score": 0.8835534038806209}} {"text": "# Modeling and Simulation in Python\n\nChapter 9\n\nCopyright 2017 Allen Downey\n\nLicense: [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0)\n\n\n\n```python\n# Configure Jupyter to display the assigned value after an assignment\n%config InteractiveShell.ast_node_interactivity='last_expr_or_assign'\n\n# import everything from SymPy.\nfrom sympy import *\n\n# Set up Jupyter notebook to display math.\ninit_printing() \n```\n\nThe following displays SymPy expressions and provides the option of showing results in LaTeX format.\n\n\n```python\nfrom sympy.printing import latex\n\ndef show(expr, show_latex=False):\n \"\"\"Display a SymPy expression.\n \n expr: SymPy expression\n show_latex: boolean\n \"\"\"\n if show_latex:\n print(latex(expr))\n return expr\n```\n\n### Analysis with SymPy\n\nCreate a symbol for time.\n\n\n```python\nt = symbols('t')\n```\n\nIf you combine symbols and numbers, you get symbolic expressions.\n\n\n```python\nexpr = t + 1\n```\n\nThe result is an `Add` object, which just represents the sum without trying to compute it.\n\n\n```python\ntype(expr)\n```\n\n\n\n\n sympy.core.add.Add\n\n\n\n`subs` can be used to replace a symbol with a number, which allows the addition to proceed.\n\n\n```python\nexpr.subs(t, 2)\n```\n\n`f` is a special class of symbol that represents a function.\n\n\n```python\nf = Function('f')\n```\n\n\n\n\n f\n\n\n\nThe type of `f` is `UndefinedFunction`\n\n\n```python\ntype(f)\n```\n\n\n\n\n sympy.core.function.UndefinedFunction\n\n\n\nSymPy understands that `f(t)` means `f` evaluated at `t`, but it doesn't try to evaluate it yet.\n\n\n```python\nf(t)\n```\n\n`diff` returns a `Derivative` object that represents the time derivative of `f`\n\n\n```python\ndfdt = diff(f(t), t)\n```\n\n\n```python\ntype(dfdt)\n```\n\n\n\n\n sympy.core.function.Derivative\n\n\n\nWe need a symbol for `alpha`\n\n\n```python\nalpha = symbols('alpha')\n```\n\nNow we can write the differential equation for proportional growth.\n\n\n```python\neq1 = Eq(dfdt, alpha*f(t))\n```\n\nAnd use `dsolve` to solve it. The result is the general solution.\n\n\n```python\nsolution_eq = dsolve(eq1)\n```\n\nWe can tell it's a general solution because it contains an unspecified constant, `C1`.\n\nIn this example, finding the particular solution is easy: we just replace `C1` with `p_0`\n\n\n```python\nC1, p_0 = symbols('C1 p_0')\n```\n\n\n```python\nparticular = solution_eq.subs(C1, p_0)\n```\n\nIn the next example, we have to work a little harder to find the particular solution.\n\n### Solving the quadratic growth equation \n\nWe'll use the (r, K) parameterization, so we'll need two more symbols:\n\n\n```python\nr, K = symbols('r K')\n```\n\nNow we can write the differential equation.\n\n\n```python\neq2 = Eq(diff(f(t), t), r * f(t) * (1 - f(t)/K))\n```\n\nAnd solve it.\n\n\n```python\nsolution_eq = dsolve(eq2)\n```\n\nThe result, `solution_eq`, contains `rhs`, which is the right-hand side of the solution.\n\n\n```python\ngeneral = solution_eq.rhs\n```\n\nWe can evaluate the right-hand side at $t=0$\n\n\n```python\nat_0 = general.subs(t, 0)\n```\n\nNow we want to find the value of `C1` that makes `f(0) = p_0`.\n\nSo we'll create the equation `at_0 = p_0` and solve for `C1`. Because this is just an algebraic identity, not a differential equation, we use `solve`, not `dsolve`.\n\nThe result from `solve` is a list of solutions. In this case, [we have reason to expect only one solution](https://en.wikipedia.org/wiki/Picard%E2%80%93Lindel%C3%B6f_theorem), but we still get a list, so we have to use the bracket operator, `[0]`, to select the first one.\n\n\n```python\nsolutions = solve(Eq(at_0, p_0), C1)\ntype(solutions), len(solutions)\n```\n\n\n\n\n (list, 1)\n\n\n\n\n```python\nvalue_of_C1 = solutions[0]\n```\n\nNow in the general solution, we want to replace `C1` with the value of `C1` we just figured out.\n\n\n```python\nparticular = general.subs(C1, value_of_C1)\n```\n\nThe result is complicated, but SymPy provides a method that tries to simplify it.\n\n\n```python\nparticular = simplify(particular)\n```\n\nOften simplicity is in the eye of the beholder, but that's about as simple as this expression gets.\n\nJust to double-check, we can evaluate it at `t=0` and confirm that we get `p_0`\n\n\n```python\nparticular.subs(t, 0)\n```\n\nThis solution is called the [logistic function](https://en.wikipedia.org/wiki/Population_growth#Logistic_equation).\n\nIn some places you'll see it written in a different form:\n\n$f(t) = \\frac{K}{1 + A e^{-rt}}$\n\nwhere $A = (K - p_0) / p_0$.\n\nWe can use SymPy to confirm that these two forms are equivalent. First we represent the alternative version of the logistic function:\n\n\n```python\nA = (K - p_0) / p_0\n```\n\n\n```python\nlogistic = K / (1 + A * exp(-r*t))\n```\n\nTo see whether two expressions are equivalent, we can check whether their difference simplifies to 0.\n\n\n```python\nsimplify(particular - logistic)\n```\n\nThis test only works one way: if SymPy says the difference reduces to 0, the expressions are definitely equivalent (and not just numerically close).\n\nBut if SymPy can't find a way to simplify the result to 0, that doesn't necessarily mean there isn't one. Testing whether two expressions are equivalent is a surprisingly hard problem; in fact, there is no algorithm that can solve it in general.\n\n### Exercises\n\n**Exercise:** Solve the quadratic growth equation using the alternative parameterization\n\n$\\frac{df(t)}{dt} = \\alpha f(t) + \\beta f^2(t) $\n\n\n```python\n# Solution\n\nalpha, beta = symbols('alpha beta')\n```\n\n\n```python\n# Solution\n\neq3 = Eq(diff(f(t), t), alpha*f(t) + beta*f(t)**2)\n```\n\n\n```python\n# Solution\n\nsolution_eq = dsolve(eq3)\n```\n\n\n```python\n# Solution\n\ngeneral = solution_eq.rhs\n```\n\n\n```python\n# Solution\n\nat_0 = general.subs(t, 0)\n```\n\n\n```python\n# Solution\n\nsolutions = solve(Eq(at_0, p_0), C1)\nvalue_of_C1 = solutions[0]\n```\n\n\n```python\n# Solution\n\nparticular = general.subs(C1, value_of_C1)\nparticular.simplify()\n```\n\n**Exercise:** Use [WolframAlpha](https://www.wolframalpha.com/) to solve the quadratic growth model, using either or both forms of parameterization:\n\n df(t) / dt = alpha f(t) + beta f(t)^2\n\nor\n\n df(t) / dt = r f(t) (1 - f(t)/K)\n\nFind the general solution and also the particular solution where `f(0) = p_0`.\n\n\n```python\n\n```\n", "meta": {"hexsha": "9f67915831f75fb86c59552aed7a573a795a92cb", "size": 83474, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "soln/chap09soln.ipynb", "max_stars_repo_name": "akashloch/ModSimPy", "max_stars_repo_head_hexsha": "73d4ba3b8677115bc752fd758e6fdf54ae21eb1d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-12-18T23:18:24.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-18T23:18:24.000Z", "max_issues_repo_path": "soln/chap09soln.ipynb", "max_issues_repo_name": "akashloch/ModSimPy", "max_issues_repo_head_hexsha": "73d4ba3b8677115bc752fd758e6fdf54ae21eb1d", "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": "soln/chap09soln.ipynb", "max_forks_repo_name": "akashloch/ModSimPy", "max_forks_repo_head_hexsha": "73d4ba3b8677115bc752fd758e6fdf54ae21eb1d", "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.6492602263, "max_line_length": 5392, "alphanum_fraction": 0.8163140619, "converted": true, "num_tokens": 1676, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9669140206578809, "lm_q2_score": 0.9136765310530521, "lm_q1q2_score": 0.8834466482212519}} {"text": "# Systems of linear equations\nThe solution of a system of linear equations $Ax=b$ is obtained as\n\n\n```python\nimport numpy as np\n\nA = np.array([[1, 2], [3, -1]])\nb = np.array([-1, 4])\n```\n\n\n```python\nx = np.linalg.solve(A,b)\nprint(x)\n```\n\n [ 1. -1.]\n\n\nTo check that this really is a solution, you should always compute the residual, which should vanish (to machine precision):\n\n\n```python\nr = A.dot(x)-b\nprint(r)\n```\n\n [4.4408921e-16 0.0000000e+00]\n\n\nThe same solution is obtained using the command\n\n\n```python\nx = np.linalg.inv(A).dot(b)\nprint(x)\n```\n\n [ 1. -1.]\n\n\nThe difference is that this requires computing the inverse of $A$, which is time consuming, whereas `solve(A,b)` applies a fast algorithm for solving linear equations, which does not require the inverse explicitly. This becomes relevant for large systems:\n\n\n```python\nimport timeit\nprint(timeit.timeit(stmt='np.linalg.solve(A,b)',setup='import numpy as np; A = np.random.rand(1000,1000); b = np.random.rand(1000,1)',number=100))\nprint(timeit.timeit(stmt='np.linalg.inv(A).dot(b)',setup='import numpy as np; A = np.random.rand(1000,1000); b = np.random.rand(1000,1)',number=100))\n```\n\n 0.834245866\n 2.5875389249999996\n\n\nYou can either use `linalg.inv()` and `linalg.dot()` methods in chain to solve a system of linear equations, or you can simply use the `solve()` method. The `solve()` method is the preferred way.\n\n## Overdetermined systems\nA system of linear equations is considered overdetermined if there are more equations than unknowns. For example, we have the overdetermined system\n\n$$x_1 + x_2 =2 \\\\\nx_1 = 1\\\\\nx_2 = 0$$\n\nIn practice, we have a system $Ax=b$ where $A$ is a $m$ by $n$ matrix and $b$ is a $m$ dimensional vector, but $m$ is greater than $n$. In this case, the vector $b$ cannot be expressed as a linear combination of the columns of $A$. Hence, we can't find $x$ so that satisfies the problem $Ax=b$ (except in specific cases) but it is possible to determine $x$ so that $Ax$ is as close to $b$ as possible. So we wish to find $x$ which minimizes $\\begin{Vmatrix}Ax-b\\end{Vmatrix}$. Considering the [QR decomposition](https://en.wikipedia.org/wiki/QR_decomposition) of $A$, we have that $Ax=b$ becomes $QRx=b$. Multiplying by $Q^T$ we obtain $Q^TQRx=Q^Tb$, and since $Q^T$ is orthogonal (this means that Q^T*Q=I) we have $Rx=Q^Tb$.\n\nNow, this is a well defined system, $R$ is an upper triangular matrix and $Q^T*b$ is a vector. More precisely $b$ is the orthogonal projection of $b$ onto the range of $A$ and $\\begin{Vmatrix}Ax-b\\end{Vmatrix}=\\begin{Vmatrix}Rx-Q^Tb\\end{Vmatrix}$.\n\nThe function `linalg.lstsq()` provided by numpy returns the least-squares solution to a linear system equation and is able to solve overdetermined systems. Let's compare the solutions of `linalg.lstsq()` with the ones computed using the QR decomposition:\n\n\n```python\nA = np.array([[1, 1], [1, 0],[0, 1]])\nb = np.array([2, 1, 0])\nx = np.linalg.lstsq(A,b,rcond=None)[0]\nprint(x)\n```\n\n [1.33333333 0.33333333]\n\n\n\n```python\nQ,R = np.linalg.qr(A) # qr decomposition of A\nQb = np.dot(Q.T,b) # computing Q^T*b (project b onto the range of A)\nx = np.linalg.solve(R,Qb) # solving R*x = Q^T*b\nprint(x)\n```\n\n [1.33333333 0.33333333]\n\n\nAs we can see, the solutions are the same.\n\nThis is the vector for which the norm of the residual $\\begin{Vmatrix}r\\end{Vmatrix}$ becomes minimal:\n\n\n```python\nr = A.dot(x)-b\nprint(r)\nnp.linalg.norm(r)\n```\n\n [-0.33333333 0.33333333 0.33333333]\n\n\n\n\n\n 0.5773502691896257\n\n\n\nAn even simpler example $x=0$, $x=1$. Here the norm of the residual $\\begin{Vmatrix}Ax-b\\end{Vmatrix}$ is\n\n$$\\begin{Vmatrix}r\\end{Vmatrix}=\\sqrt{x^2+(x-1)^2}$$\n\nand minimising this function (by finding the zero of the derivative) yields $x=1/2$. This is indeed what numpy returns:\n\n\n```python\nA = np.array([[1], [1]]);\nb = np.array([0, 1]);\nx = np.linalg.lstsq(A,b,rcond=None)[0]\nprint(x)\n```\n\n [0.5]\n\n\n## Underdetermined systems\nAs an example consider\n$$x_1 + 2 x_2 + 3 x_3 + 4 x_4 = 1\\\\\n5 x_1 + 6 x_2 + 7 x_3 + 8 x_4 = 2$$\nThis has an infinite number of solutions. `lstsq` returns one solution:\n\n\n```python\nA = np.array([[1,2,3,4],[5,6,7,8]])\nb = np.array([1,2])\nx = np.linalg.lstsq(A,b,rcond=None)[0]\nprint(x)\n```\n\n [-0.05 0.025 0.1 0.175]\n\n\nUsing `scipy.optimize.nnls`, a non-negative least squares solver. Solve $argmin_x \\begin{Vmatrix}Ax - b\\end{Vmatrix}_2$ for $x\\ge0$, returns a solution with as many components as possible equal to zero. \n\n\n```python\nfrom scipy.optimize import nnls \nx, rnorm = nnls(A,b)\nprint(x)\nprint(rnorm)\n```\n\n [1.65502277e-16 0.00000000e+00 0.00000000e+00 2.50000000e-01]\n 0.0\n\n\nTo find all solutions, we need to determine the kernel of $A$. The nullspace or kernel of a matrix $A$ (denoted $\\ker A$) is the set of all vectors $x$, for which $Ax=0$. If $x$ and $y$ are in the nullspace, then $c_1x+c_2y$ is also in the nullspace as \n\n$$A(c_1x+c_2y)=c_1(Ax)+c_2(Ay)=0+0=0$$\n\nThe nullspace is a vector space. When $A$ is viewed as a linear transformation, the nullspace is the subspace of $\\mathcal{R}^n$ that is sent to 0 under the map $A$, hence the term \"fundamental subspace.\"\n\nAn orthonormal basis $N=(n_1,\\dots,n_k)$ of the kernel is returned by\n\n\n```python\nfrom scipy.linalg import null_space, orth\nN = null_space(A)\nprint(N)\n```\n\n [[-0.40008743 -0.37407225]\n [ 0.25463292 0.79697056]\n [ 0.69099646 -0.47172438]\n [-0.54554195 0.04882607]]\n\n\nThe nullspace consists of all vectors $x$ such that $Ax=0$. This defines a system of linear equations that can be solved to give the family of solutions\n\n$$$$\n\n\n```python\nn0=N[:,0]\nn1=N[:,1]\nassert (abs(A.dot(n0))<=1e-14).all(), \"Ax=0 for all x in nullspace {}\".format(A.dot(n1))\nassert (abs(A.dot(n1))<=1e-14).all(), \"Ax=0 for all x in nullspace {}\".format(A.dot(n1))\n```\n\nwhich defines a vector space with basis $\\{n_0,n_1\\}$. As there are two vectors in this basis, the dimension of the nullspace is 2.\n\n\n```python\n# example fundamental subspaces\nA = np.array([[1,2,3,3],[2,0,6,2],[3,4,9,7]])\n# column/row space (image)\nprint('column space: {}'.format(orth(A)))\nprint('row space: {}'.format(orth(A.T)))\n# nullspace/ left nullspace (kernel)\nprint('nullspace: {}'.format(null_space(A)))\nprint('left nullspace: {}'.format(null_space(A.T)))\nassert (abs(A.dot(null_space(A)))<=1e-14).all(), \"Ax=0 for all x in nullspace {}\".format(A.dot(null_space(A)))\n# Fundamental Theorem of Linear Algebra: rank-nullity theorem (relates the dimensions of the four fundamental subspaces)\nassert np.linalg.matrix_rank(A)==len(orth(A)[0])==len(orth(A.T)[0]), \"The column and row spaces of an m×n matrix A both have dimension r, the rank of the matrix.\"\nassert A.shape[1]-np.linalg.matrix_rank(A)==len(null_space(A)[1]), \"The nullspace has dimension n−r.\"\nassert A.shape[0]-np.linalg.matrix_rank(A.T)==len(null_space(A.T)[1]), \"The left nullspace has dimension m−r.\"\n# Fundamental Theorem of Linear Algebra: orthogonal spaces (the dot product v⋅w is 0)\nassert (abs(null_space(A).T.dot(orth(A.T)))<=1e-14).all(), \"The nullspace and row space are orthogonal.\"\nassert (abs(null_space(A.T).T.dot(orth(A)))<=1e-14).all(), \"The left nullspace and the column space are also orthogonal.\"\n# Fundamental Theorem of Linear Algebra: orthonormal basis (singular value decomposition)\n[U,s,V]=np.linalg.svd(A)\nS = np.zeros(A.shape, dtype=complex)\nS[:(A.shape[0]), :(A.shape[0])] = np.diag(s)\nassert np.allclose(A, np.dot(U, np.dot(S, V))), \"any matrix M can be written as dot product of an m x m unitary martix, an m x n matrix with nonnegative values in diagonal, and an b x n unitary matrix.\"\n```\n\n column space: [[-0.31994238 -0.36841839]\n [-0.41936816 0.88119879]\n [-0.84956884 -0.29623738]]\n row space: [[-0.25358142 0.17588223]\n [-0.27620609 -0.66896915]\n [-0.76074427 0.52764668]\n [-0.52978752 -0.49308692]]\n nullspace: [[-0.94415867 -0.11543961]\n [ 0.03383545 -0.68923555]\n [ 0.32599804 -0.19126531]\n [-0.03383545 0.68923555]]\n left nullspace: [[ 0.87287156]\n [ 0.21821789]\n [-0.43643578]]\n\n\nUsing sympy to solve the equation set symbolically\n\n\n```python\nfrom sympy import * \n\nx_1, x_2, x_3, x_4 = symbols('x_1 x_2 x_3 x_4')\n\nres = solve([Eq(1*x_1+2*x_2+3*x_3+4*x_4, 1),\n Eq(5*x_1+6*x_2+7*x_3+8*x_4, 2)],\n [x_1, x_2, x_3, x_4])\nprint(res)\n```\n\n {x_1: x_3 + 2*x_4 - 1/2, x_2: -2*x_3 - 3*x_4 + 3/4}\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "02613a47861c1d9d5f54ddb5f5fdb5e28588f925", "size": 14043, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/Systems of linear equations.ipynb", "max_stars_repo_name": "OleBo/MathSo", "max_stars_repo_head_hexsha": "1f9fa0492d467c0bb0479768c503eee7723ae777", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-08T23:52:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-08T23:52:57.000Z", "max_issues_repo_path": "notebooks/Systems of linear equations.ipynb", "max_issues_repo_name": "OleBo/MathSo", "max_issues_repo_head_hexsha": "1f9fa0492d467c0bb0479768c503eee7723ae777", "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/Systems of linear equations.ipynb", "max_forks_repo_name": "OleBo/MathSo", "max_forks_repo_head_hexsha": "1f9fa0492d467c0bb0479768c503eee7723ae777", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-02T21:14:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-02T21:14:30.000Z", "avg_line_length": 28.6591836735, "max_line_length": 737, "alphanum_fraction": 0.5461083814, "converted": true, "num_tokens": 2787, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248191350351, "lm_q2_score": 0.940789745108413, "lm_q1q2_score": 0.8834249202445232}} {"text": "# Introduction to Matrices\nIn general terms, a matrix is an array of numbers that are arranged into rows and columns.\n\n## Matrices and Matrix Notation\nA matrix arranges numbers into rows and columns, like this:\n\n\\begin{equation}A = \\begin{bmatrix}\n 1 & 2 & 3 \\\\\n 4 & 5 & 6\n \\end{bmatrix}\n\\end{equation}\n\nNote that matrices are generally named as a capital letter. We refer to the *elements* of the matrix using the lower case equivalent with a subscript row and column indicator, like this:\n\n\\begin{equation}A = \\begin{bmatrix}\n a_{1,1} & a_{1,2} & a_{1,3} \\\\\n a_{2,1} & a_{2,2} & a_{2,3}\n \\end{bmatrix}\n\\end{equation}\n\nIn Python, you can define a matrix as a 2-dimensional *numpy.**array***, like this:\n\n\n```python\nimport numpy as np\n\nA = np.array([[1,2,3],\n [4,5,6]])\nprint (A)\n```\n\nYou can also use the *numpy.**matrix*** type, which is a specialist subclass of ***array***:\n\n\n```python\nimport numpy as np\n\nM = np.matrix([[1,2,3],\n [4,5,6]])\nprint (M)\n```\n\nThere are some differences in behavior between ***array*** and ***matrix*** types - particularly with regards to multiplication (which we'll explore later). You can use either, but most experienced Python programmers who need to work with both vectors and matrices tend to prefer the ***array*** type for consistency.\n\n## Matrix Operations\nMatrices support common arithmetic operations.\n\n### Adding Matrices\nTo add two matrices of the same size together, just add the corresponding elements in each matrix:\n\n\\begin{equation}\\begin{bmatrix}1 & 2 & 3 \\\\4 & 5 & 6\\end{bmatrix}+ \\begin{bmatrix}6 & 5 & 4 \\\\3 & 2 & 1\\end{bmatrix} = \\begin{bmatrix}7 & 7 & 7 \\\\7 & 7 & 7\\end{bmatrix}\\end{equation}\n\nIn this example, we're adding two matrices (let's call them ***A*** and ***B***). Each matrix has two rows of three columns (so we describe them as 2x3 matrices). Adding these will create a new matrix of the same dimensions with the values a1,1 + b1,1, a1,2 + b1,2, a1,3 + b1,3,a2,1 + b2,1, a2,2 + b2,2, and a2,3 + b2,3. In this instance, each pair of corresponding elements(1 and 6, 2, and 5, 3 and 4, etc.) adds up to 7.\n\nLet's try that with Python:\n\n\n```python\nimport numpy as np\n\nA = np.array([[1,2,3],\n [4,5,6]])\nB = np.array([[6,5,4],\n [3,2,1]])\nprint(A + B)\n```\n\n### Subtracting Matrices\nMatrix subtraction works similarly to matrix addition:\n\n\\begin{equation}\\begin{bmatrix}1 & 2 & 3 \\\\4 & 5 & 6\\end{bmatrix}- \\begin{bmatrix}6 & 5 & 4 \\\\3 & 2 & 1\\end{bmatrix} = \\begin{bmatrix}-5 & -3 & -1 \\\\1 & 3 & 5\\end{bmatrix}\\end{equation}\n\nHere's the Python code to do this:\n\n\n```python\nimport numpy as np\n\nA = np.array([[1,2,3],\n [4,5,6]])\nB = np.array([[6,5,4],\n [3,2,1]])\nprint (A - B)\n```\n\n#### Conformability\nIn the previous examples, we were able to add and subtract the matrices, because the *operands* (the matrices we are operating on) are ***conformable*** for the specific operation (in this case, addition or subtraction). To be conformable for addition and subtraction, the operands must have the same number of rows and columns. There are different conformability requirements for other operations, such as multiplication; which we'll explore later.\n\n### Negative Matrices\nThe nagative of a matrix, is just a matrix with the sign of each element reversed:\n\n\\begin{equation}C = \\begin{bmatrix}-5 & -3 & -1 \\\\1 & 3 & 5\\end{bmatrix}\\end{equation}\n\n\\begin{equation}-C = \\begin{bmatrix}5 & 3 & 1 \\\\-1 & -3 & -5\\end{bmatrix}\\end{equation}\n\nLet's see that with Python:\n\n\n```python\nimport numpy as np\n\nC = np.array([[-5,-3,-1],\n [1,3,5]])\nprint (C)\nprint (-C)\n```\n\n### Matrix Transposition\nYou can *transpose* a matrix, that is switch the orientation of its rows and columns. You indicate this with a superscript **T**, like this:\n\n\\begin{equation}\\begin{bmatrix}1 & 2 & 3 \\\\4 & 5 & 6\\end{bmatrix}^{T} = \\begin{bmatrix}1 & 4\\\\2 & 5\\\\3 & 6 \\end{bmatrix}\\end{equation}\n\nIn Python, both *numpy.**array*** and *numpy.**matrix*** have a **T** function:\n\n\n```python\nimport numpy as np\n\nA = np.array([[1,2,3],\n [4,5,6]])\nprint(A.T)\n```\n", "meta": {"hexsha": "b8d4b93298e7b878481950659b33ab2ff582886d", "size": 6724, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Vector and Matrices by Hiren/03-03-Matrices.ipynb", "max_stars_repo_name": "awesome-archive/Basic-Mathematics-for-Machine-Learning", "max_stars_repo_head_hexsha": "b6699a9c29ec070a0b1615c46952cb0deeb73b54", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 401, "max_stars_repo_stars_event_min_datetime": "2018-08-29T04:55:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T11:03:39.000Z", "max_issues_repo_path": "Vector and Matrices by Hiren/03-03-Matrices.ipynb", "max_issues_repo_name": "aligeekk/Basic-Mathematics-for-Machine-Learning", "max_issues_repo_head_hexsha": "8662076d60e89f58a6e81e4ca1377569472760a2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-09-28T13:52:53.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-28T18:13:53.000Z", "max_forks_repo_path": "Vector and Matrices by Hiren/03-03-Matrices.ipynb", "max_forks_repo_name": "aligeekk/Basic-Mathematics-for-Machine-Learning", "max_forks_repo_head_hexsha": "8662076d60e89f58a6e81e4ca1377569472760a2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 135, "max_forks_repo_forks_event_min_datetime": "2018-08-29T05:04:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T07:04:25.000Z", "avg_line_length": 31.5680751174, "max_line_length": 563, "alphanum_fraction": 0.5388161808, "converted": true, "num_tokens": 1348, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109770159682, "lm_q2_score": 0.9294404082102516, "lm_q1q2_score": 0.8833503664452256}} {"text": "```python\n%matplotlib inline\n```\n\n\n```python\nimport sympy\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport math\n```\n\n## 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 f_vectorized = np.vectorize(f)\n x = np.linspace(min_x, max_x, num_points)\n y = f_vectorized(x)\n plt.plot(x, y)\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## 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 fs_vectorized = [np.vectorize(f) for f in functions]\n x = np.linspace(min_x, max_x, num_points)\n ys = [vectorized_f(x) for vectorized_f in fs_vectorized]\n \n for y in ys:\n plt.plot(x, y)\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", "meta": {"hexsha": "1d3bf920c55dc61339adc1f3c069dd622c1211fe", "size": 122521, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "math/linear-algebra/plotting-function.ipynb", "max_stars_repo_name": "VGGeorgiev/ml-playground", "max_stars_repo_head_hexsha": "65dc329d325ccdf40e021b0cb0c8fd1f4cfacc9e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-04-07T23:19:29.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-07T23:19:29.000Z", "max_issues_repo_path": "math/linear-algebra/plotting-function.ipynb", "max_issues_repo_name": "VladiGGeorgiev/ml-playground", "max_issues_repo_head_hexsha": "65dc329d325ccdf40e021b0cb0c8fd1f4cfacc9e", "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/linear-algebra/plotting-function.ipynb", "max_forks_repo_name": "VladiGGeorgiev/ml-playground", "max_forks_repo_head_hexsha": "65dc329d325ccdf40e021b0cb0c8fd1f4cfacc9e", "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": 474.8875968992, "max_line_length": 16972, "alphanum_fraction": 0.9425486243, "converted": true, "num_tokens": 990, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475715065793, "lm_q2_score": 0.9362850079703712, "lm_q1q2_score": 0.8832421885068679}} {"text": "```python\nimport matplotlib.pyplot as plt\nimport math\nimport functools\nimport numpy as np\n```\n\n__Exponential Growth Equation__\n\n$\n\\begin{align}\n\\frac{\\partial N}{\\partial t} = N(t) * r\n\\end{align}\n$\n\nLet r = 1.2 and N(0) = 10\n\n\n\n```python\nframes = 20\ntimeSerie = np.linspace(1, frames, frames, endpoint=True)\n```\n\n\n```python\npop_exp_120 = [10]\npop_exp_125 = [10]\npop_exp_130 = [10]\n\nfor i in range(frames):\n pop_exp_120.append((pop_exp_120[-1] * (1 + 0.20)))\n pop_exp_125.append((pop_exp_125[-1] * (1 + 0.25)))\n pop_exp_130.append((pop_exp_130[-1] * (1 + 0.30)))\n```\n\n\n```python\nfig = plt.figure('Exponential Plot', figsize=(14, 6))\nax = fig.add_subplot(111)\nplt.plot(timeSerie ,pop_exp_120[:-1], label='1.20')\nplt.plot(timeSerie ,pop_exp_125[:-1], label='1.25')\nplt.plot(timeSerie ,pop_exp_130[:-1], label='1.30')\nax.annotate(round(pop_exp_130[-2], 0) , xy=(timeSerie[-1], pop_exp_130[-2]), textcoords='data')\nax.annotate(round(pop_exp_125[-2], 0) , xy=(timeSerie[-1], pop_exp_125[-2]), textcoords='data')\nax.annotate(round(pop_exp_120[-2], 0) , xy=(timeSerie[-1], pop_exp_120[-2]), textcoords='data')\nplt.legend(loc='best')\nplt.show()\n```\n\n__Logistic Equation__\n\n$\n\\begin{align}\n\\frac{\\partial N}{\\partial t} = N(t) * r * [ (K - N(t)) / K ]\n\\end{align}\n$\n\nLet r = 1.2, N(0) = 10 and K = 450\n\n\n```python\npop_log = []\n\nK = 80\n\npop_log_120 = [10]\npop_log_125 = [10]\npop_log_130 = [10]\n\nfor i in range(frames):\n pop_log_120.append((pop_log_120[-1] * (1 + (0.20 * (K - pop_log_120[-1])/K)) ))\n pop_log_125.append((pop_log_125[-1] * (1 + (0.25 * (K - pop_log_125[-1])/K)) ))\n pop_log_130.append((pop_log_130[-1] * (1 + (0.30 * (K - pop_log_130[-1])/K)) ))\n```\n\n\n```python\nfig = plt.figure('Exponential Plot', figsize=(14, 6))\nax = fig.add_subplot(111)\nplt.plot(timeSerie ,pop_log_120[:-1], label='1.20')\nplt.plot(timeSerie ,pop_log_125[:-1], label='1.25')\nplt.plot(timeSerie ,pop_log_130[:-1], label='1.30')\nax.annotate(round(pop_log_130[-2], 0) , xy=(timeSerie[-1], pop_log_130[-2]), textcoords='data')\nax.annotate(round(pop_log_125[-2], 0) , xy=(timeSerie[-1], pop_log_125[-2]), textcoords='data')\nax.annotate(round(pop_log_120[-2], 0) , xy=(timeSerie[-1], pop_log_120[-2]), textcoords='data')\nplt.legend(loc='best')\nplt.show()\n```\n", "meta": {"hexsha": "3c7401fb91045e8012288522c66ba74eeebf399c", "size": 81093, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Population.ipynb", "max_stars_repo_name": "FeMaffezzolli/python_population_growth", "max_stars_repo_head_hexsha": "82ead4a2b9c6dd55b3b9968952260e3eb572d709", "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": "Population.ipynb", "max_issues_repo_name": "FeMaffezzolli/python_population_growth", "max_issues_repo_head_hexsha": "82ead4a2b9c6dd55b3b9968952260e3eb572d709", "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": "Population.ipynb", "max_forks_repo_name": "FeMaffezzolli/python_population_growth", "max_forks_repo_head_hexsha": "82ead4a2b9c6dd55b3b9968952260e3eb572d709", "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": 471.4709302326, "max_line_length": 43028, "alphanum_fraction": 0.9418322173, "converted": true, "num_tokens": 817, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9706877700966099, "lm_q2_score": 0.9099070060380481, "lm_q1q2_score": 0.8832356026863555}} {"text": "# SYMBOLIC PROGRAMMING\n\n**DONE BY:\n
Thejaswin.S\n
RA1911026010029\n
CSE-AIML K1**\n\n**1. Solve the following using symbolic paradigm:\n
i. Calculate sqrt (2) with 100 decimals.**\n\n\n\n```python\nfrom sympy import sqrt\nprint(sqrt(2).evalf(100))\n```\n\n 1.414213562373095048801688724209698078569671875376948073176679737990732478462107038850387534327641573\n\n\n**ii. Calculate (1/2+1/3) in rational arithmetic.**\n\n\n```python\nimport sympy as sym\na0029 = sym.Rational(1, 2)\nb0029 = sym.Rational(1, 3)\na0029+b0029\n```\n\n\n\n\n$\\displaystyle \\frac{5}{6}$\n\n\n\n**iii. Calculate the expanded form of (x+y) ^ 6.**\n\n\n```python\nimport sympy as sym\nx0029 = sym.Symbol('x')\ny0029 = sym.Symbol('y')\nsym.expand((x0029+y0029)**6)\n```\n\n\n\n\n$\\displaystyle x^{6} + 6 x^{5} y + 15 x^{4} y^{2} + 20 x^{3} y^{3} + 15 x^{2} y^{4} + 6 x y^{5} + y^{6}$\n\n\n\n**iv. Simplify the trigonometric expression sin (x) / cos (x)**\n\n\n```python\nimport sympy as sym\nx0029=sym.Symbol('x')\nsym.simplify(sym.sin(x0029)/sym.cos(x0029))\n```\n\n\n\n\n$\\displaystyle \\tan{\\left(x \\right)}$\n\n\n\n**v. Calculate sin x -xx^3n**\n\n\n```python\nimport sympy as sym\nx0029=sym.Symbol('x')\nn0029=sym.Symbol('n')\nsym.solveset(sym.sin(x0029)-x0029*x0029**3*n0029,x0029)\n```\n\n\n\n\n$\\displaystyle \\left\\{x \\mid x \\in \\mathbb{C} \\wedge - n x^{4} + \\sin{\\left(x \\right)} = 0 \\right\\}$\n\n\n\n\n```python\nimport sympy\nfrom sympy import *\nx0029,n0029=symbols('x n')\nexpr0029=sin(x0029)-x0029*x0029**3*n0029\nsmpl0029=trigsimp(expr0029)\nsmpl0029\n```\n\n\n\n\n$\\displaystyle - n x^{4} + \\sin{\\left(x \\right)}$\n\n\n\n**2. Develop a python code for to carryout the operations on the given algebraic manipulation for the given expression a2−ab+ab−b2=a2−b2 by using the symbolic programming paradigms principles.**\n\n\n```python\nfrom sympy import *\na,b=symbols('a b')\ng10029=simplify(a**2-ab+ab-b**2)\ng10029\n```\n\n\n\n\n$\\displaystyle a^{2} - b^{2}$\n\n\n\n**3. Give the Symbolic program for the expression given below:\n
a. ∬a2 da**\n\n\n```python\na0029=symbols('a')\ng0029=integrate('a**2',a)\nj0029=integrate(g0029,a0029) \nprint(\"first integration \"+str(g0029))\nprint(\"second integration \"+str(j0029))\n```\n\n first integration a**3/3\n second integration a**4/12\n\n\n**b. 2x+y2**\n\n\n```python\nx=Symbol('x')\ny=Symbol('y')\n2*x+y**2\n```\n\n\n\n\n$\\displaystyle 2 x + y^{2}$\n\n\n\n**c. 1/10 + 1/5**\n\n\n```python\na0029=Rational(1,10)\nb0029=Rational(1,5)\na0029+b0029\n```\n\n\n\n\n$\\displaystyle \\frac{3}{10}$\n\n\n\n**d. d/dx(sin(x))**\n\n\n```python\nx0029=symbols('x')\ng0029=sin(x0029)\nj0029=diff(g0029,x0029) \nprint(\"Before differentiation \"+str(g0029))\nprint(\"After differentiation \"+str(j0029)) \n```\n\n Before differentiation sin(x)\n After differentiation cos(x)\n\n\n# Functional Programming\n\n**1.\tCalculate the following using Lambda calculus:\n
a.\tT AND F**\n\n\n```python\ny0029=lambda s0029: s0029 and False\nprint(\"T AND F = \",y0029(True)) \n```\n\n T AND F = False\n\n\n**b. 3 * 4**\n\n\n```python\nx0029 = lambda a0029,b0029 : a0029*b0029\nprint(\"3*4 =\",x0029(3,4))\n```\n\n 3*4 = 12\n\n\n**2.\tLambda functions\n
a.\tWrite a lambda function to convert measurements from meters to feet.**\n\n\n```python\nx0029=lambda y0029: y0029*3.28084\nprint(\"feet : {:.6f}\".format(x0029(float(input(\"enter in metres: \")))))\n```\n\n enter in metres: 12.5\n feet : 41.010500\n\n\n**b. Write a lambda function in Python to implement the following lambda expression:\n
(𝜆𝑓. 𝜆𝑚. (𝑓 + 𝑚)𝑎)(𝜆𝑥. 𝑥2)(𝑏)\n
Note: You need to write a nested lambda function for implementing f+m where f takes the\n
square function (which takes argument x) passed as a parameter. The above expression\n
calculates a^2+b.**\n\n\n```python\nsquare0029=lambda x: x**2\ntotal0029=lambda f, b: lambda a: f(a)+b\na0029=int(input(\"Enter value for a: \"))\nb0029=int(input(\"Enter value for b: \"))\nprint(total0029(square0029,b0029)(a0029))\n```\n\n Enter value for a: 10\n Enter value for b: 12\n 112\n\n\n**3. Passing and returning a function as an argument\n
Define a function ‘square’ for squaring a number. Define a function named ‘twice’ that takes a\n
function f as an argument and returns f(f(x)). Using ‘twice’ and ‘square’ create a function ‘quad’ that\n
takes n as an argument and returns n 4 . ‘quad’ should not be defined explicitly. It should only be\n
created as a variable which is then assigned a function.**\n\n\n```python\ndef square0029(n0029):\n return n0029**2\n\ndef twice0029(f0029):\n return square0029(f0029)\n\nn0029 = int(input(\"Enter a number: \"))\nquad0029 = twice0029(square0029(n0029))\nprint(quad0029)\n```\n\n Enter a number: 10\n 10000\n\n\n**4. Closure\n
A Closure is a function object that remembers values in enclosing scopes even if they are not present\n
in memory. We have a closure in Python when a nested function references a value in its enclosing\n
scope.\n
a. Study the following program by executing it:**\n\n\n```python\ndef multiplier_of(n0029):\n def multiplier(number0029):\n return number0029*n0029\n return multiplier\n\nmultiplywith5 = multiplier_of(5)\nprint(multiplywith5(9))\n```\n\n 45\n\n\n**b. In a lottery system, random number is chosen by retrieving the number from a\n
random index from a list of random numbers. Write a program to choose a random\n
number in this way. You must use nested functions – the inner function chooses a\n
number from a random index and the outer function generates a random list of\n
numbers. The outer function takes n as a parameter where is the maximum number\n
that can be put in the random list. (Your code should be similar to the program in\n
5a)**\n\n\n```python\nimport random\ndef outer_func(n0029):\n list_0029 = random.sample(range(0,n0029+1), n0029)\n def inner_func():\n index = random.randrange(0, n0029)\n return list_0029[index]\n return inner_func\n\nn0029 = int(input(\"Enter a random number: \"))\nans0029 = outer_func(n0029)\nprint(\"Random number generated is: {}\".format(ans0029()))\n```\n\n Enter a random number: 10\n Random number generated is: 6\n\n\n**6. Map\n
A secret message needs to be sent. Use the map function to encrypt the message using Caesar cipher.**\n\n\n```python\ndef encrypt(letter_0029, s_0029):\n if (letter_0029.isupper()):\n return chr((ord(letter_0029) + s_0029 - 65) % 26 + 65)\n elif (letter_0029.islower()):\n return chr((ord(letter_0029) + s_0029 - 97) % 26 + 97)\n else:\n return letter_0029\n\ntext_0029 = input(\"Enter the word: \")\ns_0029 = int(input(\"Enter the shift: \"))\nshift_0029 = [s_0029] * len(text_0029)\nresult_0029 = list(map(encrypt, text_0029, shift_0029))\n#result_0029\nprint(\"Encrypted text: \", end=\"\")\nfor i in result_0029:\n print(i, end=\"\")\n```\n\n Enter the word: hello\n Enter the shift: 2\n Encrypted text: jgnnq\n\n**7. Reduce\n
Given runs scored by 2 players in a series of matches, write a Python program using reduce function\n
to find who is the better player of the two in terms of maintaining consistency. (You need to find\n
SD).**\n\n\n```python\nimport functools,operator\n\npl1_0029 = [51, 50, 58, 55, 53, 60]\npl2_0029 = [98, 42, 88, 74, 88, 12]\n\nmean1_0029 = (functools.reduce(operator.add, pl1_0029)) / len(pl1_0029)\nmean2_0029 = (functools.reduce(operator.add, pl2_0029)) / len(pl2_0029)\n\nm1_0029 = [mean1_0029] * len(pl1_0029)\nm2_0029 = [mean2_0029] * len(pl2_0029)\n\ndef variance_0029(p_0029, m_0029):\n var_0029 = p_0029 - m_0029\n return var_0029**2\n \nsqsum1_0029 = list(map(variance_0029, pl1_0029, m1_0029))\nsqsum2_0029 = list(map(variance_0029, pl2_0029, m2_0029))\n\nvar1_0029 = (functools.reduce(operator.add, sqsum1_0029)) / len(sqsum1_0029)\nvar2_0029 = (functools.reduce(operator.add, sqsum2_0029)) / len(sqsum2_0029)\n\nsd1_0029 = var1_0029**0.5\nsd2_0029 = var2_0029**0.5\n\nif sd1_0029==sd2_0029:\n print(\"Both players are consistent.\")\nelif sd1_0029>sd2_0029:\n print(\"Player 2 is more consistent.\")\nelse:\n print(\"Player 1 is more consistent.\")\n```\n\n Player 1 is more consistent.\n\n\n**8. Filter\n
The marks scored by a class of students in 5 different subjects are stored in a list of lists. Using the\n
filter function, write a program to find the students who failed in one or more subjects.**\n\n\n```python\na0029=lambda x0029:x0029<35\nmarks0029=[[10,90,80,75,32],[23,67,78,87,90],[90,90,90,90,90],[39, 1, 100, 56, 72]]\nl=len(marks0029)\nfor i in range(l):\n red=filter(a0029,marks0029[i])\n if len(list(red))>=1:\n print (\"student '\"+str(i+1)+\"' failed in atleast 1 subject\")\n```\n\n student '1' failed in atleast 1 subject\n student '2' failed in atleast 1 subject\n student '4' failed in atleast 1 subject\n\n\n**9. Map+reduce+filter\n
Given two trending topics and a bunch of tweets, write a Python program to count the number of\n
tweets that contain each topic. You need to do this by putting together map(), reduce() and filter()\n
functions.**\n\n\n```python\nimport functools,operator\ntweets0029 = [\"Is this the final ipl of msd #IPL #chennaisuperkings\",\n \"Most 10-wicket wins in IPL: 4 - RCB, 2 - MI, 2 - SRH, 2 - CSK #RCBvsRR #CSK #RR #CricTracker\",\n \"My @chennaisuperkings outfit has arrived! Now to be well enough towear it....Thanks @MSD & the #CSK management! All the best for the rest of the #IPL!\",\n \"Mental health of #Students deteriorating\",\n \"#Students suffering inside home and inside themselves\",\n \"#Students not able to cope up with studies during COVID\"]\n\ncsk_0029 = [\"#csk\"] * len(tweets0029)\nstudents_0029 = [\"students\"] * len(tweets0029)\n\ndef segregate_tweets(str0029, topic0029):\n if topic0029 in str0029.lower():\n return str0029\n return \"\"\n\nresult_csk = list(map(segregate_tweets, tweets0029, csk_0029))\nresult_stud = list(map(segregate_tweets, tweets0029, students_0029))\nprint(result_csk)\nprint(result_stud)\nprint()\ndef filter_list(str0029):\n return str0029!=\"\"\n\nrescsk_0029 = list(filter(filter_list, result_csk))\nresstud_0029 = list(filter(filter_list, result_stud))\n\nprint(\"No. of csk tweets: {}\".format(len(rescsk_0029)))\nprint(\"No. of students tweets: {}\".format(len(resstud_0029)))\n```\n\n ['', 'Most 10-wicket wins in IPL: 4 - RCB, 2 - MI, 2 - SRH, 2 - CSK #RCBvsRR #CSK #RR #CricTracker', 'My @chennaisuperkings outfit has arrived! Now to be well enough towear it....Thanks @MSD & the #CSK management! All the best for the rest of the #IPL!', '', '', '']\n ['', '', '', 'Mental health of #Students deteriorating', '#Students suffering inside home and inside themselves', '#Students not able to cope up with studies during COVID']\n \n No. of csk tweets: 2\n No. of students tweets: 3\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "969fcb4a45650f52b86ac416b42ae5dea7e11a9d", "size": 20145, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "WEEK-7.ipynb", "max_stars_repo_name": "thejaswin123/APP_lab", "max_stars_repo_head_hexsha": "051add9bf979d8c706ff5d64c12e19a08cbc6552", "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-7.ipynb", "max_issues_repo_name": "thejaswin123/APP_lab", "max_issues_repo_head_hexsha": "051add9bf979d8c706ff5d64c12e19a08cbc6552", "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-7.ipynb", "max_forks_repo_name": "thejaswin123/APP_lab", "max_forks_repo_head_hexsha": "051add9bf979d8c706ff5d64c12e19a08cbc6552", "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.9319306931, "max_line_length": 277, "alphanum_fraction": 0.5220650285, "converted": true, "num_tokens": 3414, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465062370312, "lm_q2_score": 0.9441768616142655, "lm_q1q2_score": 0.8831325287807481}} {"text": "# Modeling and Simulation in Python\n\nChapter 4: Predict\n\nCopyright 2017 Allen Downey\n\nLicense: [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0)\n\n\n### Analysis with SymPy\n\n\n```python\nfrom sympy import *\n```\n\nThe following line sets up Jupyter notebook to display math.\n\n\n```python\ninit_printing() \n```\n\nAnd this function provides the option of showing results in LaTeX format.\n\n\n```python\nfrom sympy.printing import latex\n\ndef show(expr, show_latex=False):\n if show_latex:\n print(latex(expr))\n return expr\n```\n\nCreate a symbol for time.\n\n\n```python\nt = symbols('t')\nshow(t)\n```\n\nIf you combine symbols and numbers, you get symbolic expressions.\n\n\n```python\nexpr = t + 1\nshow(expr)\n```\n\nThe result is an Add object, which just represents the sum without trying to compute it.\n\n\n```python\ntype(expr)\n```\n\n\n\n\n sympy.core.add.Add\n\n\n\n`subs` can be used to replace a symbol with a number, which allows the addition to proceed.\n\n\n```python\nexpr.subs(t, 2)\n```\n\n`f` is a special class of symbol that represents a function.\n\n\n```python\nf = Function('f')\nshow(f)\n```\n\n\n\n\n f\n\n\n\nThe type of `f` is `UndefinedFunction`\n\n\n```python\ntype(f)\n```\n\n\n\n\n sympy.core.function.UndefinedFunction\n\n\n\nNow SymPy understands that `f(t)` means `f` evaluated at `t`, but it doesn't try to evaluate it yet.\n\n\n```python\nf(t)\n```\n\n`diff` returns a `Derivative` object that represents the time derivative of `f`\n\n\n```python\ndfdt = diff(f(t), t)\nshow(dfdt)\n```\n\n\n```python\ntype(dfdt)\n```\n\n\n\n\n sympy.core.function.Derivative\n\n\n\nWe need a symbol for `alpha`\n\n\n```python\nalpha = symbols('alpha')\nshow(alpha)\n```\n\nNow we can write the differential equation for proportional growth.\n\n\n```python\neq1 = Eq(dfdt, alpha*f(t))\nshow(eq1)\n```\n\nAnd use `dsolve` to solve it. The result is the general solution.\n\n\n```python\nsolution_eq = dsolve(eq1)\nshow(solution_eq)\n```\n\nIn this case, finding the particular solution is easy: we just replace `C1` with `p0`\n\n\n```python\nC1, p0 = symbols('C1 p0')\n```\n\n\n```python\nparticular = solution_eq.subs(C1, p0)\nshow(particular)\n```\n\nIn the next example, we'll have to work a little harder to find the particular solution.\n\n### Solving the quadratic growth equation \n\nWe'll use the (r, K) parameterization, so we'll need two more symbols:\n\n\n```python\nr, K = symbols('r K')\n```\n\nNow we can write the differential equation.\n\n\n```python\neq2 = Eq(diff(f(t), t), r*f(t) * (1 - f(t)/K))\nshow(eq2)\n```\n\nAnd solve it.\n\n\n```python\nsolution_eq = dsolve(eq2)\nshow(solution_eq)\n```\n\n`rhs` selects the right-hand side of the solution.\n\n\n```python\ngeneral = solution_eq.rhs\nshow(general)\n```\n\nWe can evaluate the right-hand side at $t=0$\n\n\n```python\nat0 = general.subs(t, 0)\nshow(at0)\n```\n\nNow we want to find the value of `C1` that makes `f(0) = p0`.\n\nSo we'll create the equation `at0 = p0` and solve for `C1`. Because this is just an algebraic identity, not a differential equation, we use `solve`, not `dsolve`.\n\nThe result from `solve` is a sequence of solutions. In this case, [we have reason to expect only one solution](https://en.wikipedia.org/wiki/Picard%E2%80%93Lindel%C3%B6f_theorem), but we still get a sequence, so we have to use the bracket operator, `[0]`, to select the first one.\n\n\n```python\nsolutions = solve(Eq(at0, p0), C1)\ntype(solutions), len(solutions)\n```\n\n\n\n\n (list, 1)\n\n\n\n\n```python\nvalue_of_C1 = solutions[0]\nshow(value_of_C1)\n```\n\nNow in the general solution, we want to replace `C1` with the value of `C1` we just figured out.\n\n\n```python\nparticular = general.subs(C1, value_of_C1)\nparticular\n```\n\nThe result is complicated, but SymPy provides a method that tries to simplify it.\n\n\n```python\nparticular = simplify(particular)\nshow(particular)\n```\n\nOften simplicity is in the eye of the beholder, but that's about as simple as this expression gets.\n\nJust to double-check, we can evaluate it at `t=0` and confirm that we get `p0`\n\n\n```python\nparticular.subs(t, 0)\n```\n\n[In some places](https://en.wikipedia.org/wiki/Population_growth#Logistic_equation) you'll see this solution, which is called the \"logistic function\" written in a different form:\n\n$f(t) = \\frac{K}{1 + A e^{-rt}}$\n\nwhere $A = (K - p_0) / p_0$.\n\nWe can use SymPy to confirm that these two forms are equivalent. First we represent the alternative version of the logistic function:\n\n\n```python\nA = (K - p0) / p0\nshow(A)\n```\n\n\n```python\nlogistic = K / (1 + A * exp(-r*t))\nshow(logistic)\n```\n\nTo see whether two expressions are equivalent, we can check whether their difference simplifies to 0.\n\n\n```python\nsimplify(particular - logistic)\n```\n\nThis test only works one way: if SymPy says the difference reduces to 0, the expressions are definitely equivalent (and not just numerically close).\n\nBut if SymPy can't find a way to simplify the result to 0, that doesn't necessarily mean there isn't one. Testing whether two expressions is a surprisingly hard problem; in fact, there is no algorithm that can solve it in general.\n\n**Exercise:** Solve the quadratic growth equation using the alternative parameterization\n\n$\\frac{df(t)}{dt} = \\alpha f(t) + \\beta f^2(t) $\n\n\n```python\n# Solution\n\nalpha, beta = symbols('alpha beta')\n```\n\n\n```python\n# Solution\n\neq3 = Eq(diff(f(t), t), alpha*f(t) + beta*f(t)**2)\neq3\n```\n\n\n```python\n# Solution\n\nsolution_eq = dsolve(eq3)\nsolution_eq\n```\n\n\n```python\n# Solution\n\ngeneral = solution_eq.rhs\ngeneral\n```\n\n\n```python\n# Solution\n\nat0 = general.subs(t, 0)\nat0\n```\n\n\n```python\n# Solution\n\nsolutions = solve(Eq(at0, p0), C1)\nvalue_of_C1 = solutions[0]\nvalue_of_C1\n```\n\n\n```python\n# Solution\n\nparticular = general.subs(C1, value_of_C1)\nparticular.simplify()\n```\n\n**Exercise:** Use [WolframAlpha](https://www.wolframalpha.com/) to solve the quadratic growth model, using either or both forms of parameterization:\n\n df(t) / dt = alpha f(t) + beta f(t)^2\n\nor\n\n df(t) / dt = alpha f(t) (1 - f(t)/K)\n\nFind the general solution and also the particular solution where `f(0) = p0`.\n\n\n```python\n\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "cc595bdd7a82a5ec5b6e693fe3715e5f3afab3fd", "size": 54388, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "code/chap04sympy.ipynb", "max_stars_repo_name": "annagriffin/ModSimPy", "max_stars_repo_head_hexsha": "6f451aae0ce88289734b1153426bb6af933b8dd6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-04-13T01:09:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-13T01:09:39.000Z", "max_issues_repo_path": "code/chap04sympy.ipynb", "max_issues_repo_name": "annagriffin/ModSimPy", "max_issues_repo_head_hexsha": "6f451aae0ce88289734b1153426bb6af933b8dd6", "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": "code/chap04sympy.ipynb", "max_forks_repo_name": "annagriffin/ModSimPy", "max_forks_repo_head_hexsha": "6f451aae0ce88289734b1153426bb6af933b8dd6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-04-13T01:10:41.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-13T01:10:41.000Z", "avg_line_length": 45.6275167785, "max_line_length": 2290, "alphanum_fraction": 0.7238729131, "converted": true, "num_tokens": 1660, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122684798184, "lm_q2_score": 0.9219218289556671, "lm_q1q2_score": 0.8831202305359862}} {"text": "# Pearson Correlation Vs. Z-normalized Euclidean Distance\n\nIt is [well understood](https://arxiv.org/pdf/1601.02213.pdf) that the z-normalized Euclidean distance, $ED_{z-norm}$, and the Pearson correlation, $PC$, between any two subsequences with length $m$ share the following relationship:\n\n$ED_{z-norm} = \\sqrt {2 * m * (1 - PC)}$\n\nNaturally, when the two subsequences are perfectly correlated (i.e., $PC = 1$), then we get:\n\n\\begin{align}\n ED_{z-norm} ={}&\n \\sqrt {2 * m * (1 - PC)}\n \\\\\n ={}&\n \\sqrt {2 * m * (1 - 1)}\n \\\\\n ={}&\n \\sqrt {2 * m * 0}\n \\\\\n ={}&\n \\sqrt {0}\n \\\\\n ={}&\n 0\n \\\\\n\\end{align}\n\nSimilarly, when the two subsequences are completely uncorrelated (i.e., $PC = 0$), then we get:\n\n\\begin{align}\n ED_{z-norm} ={}&\n \\sqrt {2 * m * (1 - PC)}\n \\\\\n ={}&\n \\sqrt {2 * m * (1 - 0)}\n \\\\\n ={}&\n \\sqrt {2 * m * 1}\n \\\\\n ={}&\n \\sqrt {2 * m}\n \\\\\n\\end{align}\n\nIn other words, the largest possible z-normalized distance between any pair of subsequences with length $m$ is $\\sqrt{2 * m}$. The maximum distance can never be bigger!\n\nFinally, when two subsequences are anti-correlated (i.e., $PC = -1$), then we get:\n\n\\begin{align}\n ED_{z-norm} ={}&\n \\sqrt {2 * m * (1 - PC)}\n \\\\\n ={}&\n \\sqrt {2 * m * (1 - (-1))}\n \\\\\n ={}&\n \\sqrt {2 * m * 2}\n \\\\\n ={}&\n \\sqrt {4 * m}\n \\\\\n ={}&\n 2 * \\sqrt {m}\n \\\\\n\\end{align}\n\nNote that while $2 * \\sqrt {m}$ (i.e., anti-correlated) is obviously larger than $\\sqrt {2m}$ (i.e., uncorrelated), it is basically impossible for a matrix profile distance to be \"worse\" than uncorrelated (i.e., larger than $\\sqrt {2m}$) due to the fact that it is defined as the distance to its one-nearest-neighbor. For example, given a subsequence `T[i : i + m]`, the matrix profile is supposed to return the z-norm distance to its one-nearest-neighbor. So, even if there existed another z-norm subsequence, `T[j : j + m]`, along the time series that was perfectly anti-correlated with `T[i : i + m]`, then any subsequence that is even slightly shifted away from location `j` must have a smaller distance than $2 * \\sqrt {m}$. Therefore, a perfectly anti-correlated subsequence would/could (almost?) never be a one-nearest-neighbor to `T[i : i + m]` especially if `T` is long.\n\n\n```python\n\n```\n", "meta": {"hexsha": "0f4933beaabe19f40f8dcbb804267fb7bc4a49eb", "size": 3758, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "docs/Pearson.ipynb", "max_stars_repo_name": "alvii147/stumpy", "max_stars_repo_head_hexsha": "6dacfcf35ce03255951d70e5dd2f8b3f4e20a27f", "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": "docs/Pearson.ipynb", "max_issues_repo_name": "alvii147/stumpy", "max_issues_repo_head_hexsha": "6dacfcf35ce03255951d70e5dd2f8b3f4e20a27f", "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/Pearson.ipynb", "max_forks_repo_name": "alvii147/stumpy", "max_forks_repo_head_hexsha": "6dacfcf35ce03255951d70e5dd2f8b3f4e20a27f", "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": 35.1214953271, "max_line_length": 891, "alphanum_fraction": 0.4922831293, "converted": true, "num_tokens": 734, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566342049451596, "lm_q2_score": 0.9230391595405136, "lm_q1q2_score": 0.8830108325202876}} {"text": "# The NumPy random package \n\n## Overview\n1. Introduction to Numpy.Random\n2. Simple Random Data\n - Rand()\n - Randn()\n - Random_sample()\n - Choice()\n - Bytes()\n3. Permutations\n - shuffle()\n - permutation()\n4. Distributions\n - Uniform()\n - Normal()\n - Binomial()\n - Poisson()\n5. Random Generator\n6. References\n\n\n## Introduction to Numpy.random\n**Numpy[1]** is a package in the Python Language. It provides a high-performance multidimensional array object, and tools for working with these arrays. It contains useful linear algebra, Fourier transform, and random number capabilities.\nNumpy.random is a sub-package of the Numpy package, and it basically churns out (pseudo) random numbers, using various tools and functions. It takes advantage of the **Mersenne Twister[2]** , which is the most used pseudorandom number generator (PRNG), and is already embedded in Python's library. The functions in the numpy.random sub-package can be divided into 4 categories, which are Simple random data (getting random numbers), permutations, distributions and seeding.\n\n## Simple Random Data\n\n### Rand()\n\n**Numpy.random.rand()[3]** is a function when called (with no argument), will return a random number in the **half-open interval[4]** between 0 (inclusive) and 1 (exclusive). It will also create an array of a given shape and populates it with random samples if parameters are passed through. This function uses the uniform distribution (see numpy.random.uniform).\n\nParameters:\t\nd0, d1, …, dn : int, optional\n
The dimensions of the returned array, should all be positive. If no argument is given a single Python float is returned.\n\nReturns:\t\nout : ndarray, shape (d0, d1, ..., dn)\n
Random values.\n\n\n```python\nimport numpy as np\nnp.random.rand() #produces a random float number between 0 and 1\n```\n\n\n\n\n 0.0923385947687978\n\n\n\n\n```python\nnp.random.rand(2,2) #produces a 2d array with 2 rows and 2 columns\n```\n\n\n\n\n array([[0.18626021, 0.34556073],\n [0.39676747, 0.53881673]])\n\n\n\n\n```python\nnp.random.rand(3,2,2) #produces a 3d array with 2 rows and 2 columns, and a depth of 3\n```\n\n\n\n\n array([[[0.41919451, 0.6852195 ],\n [0.20445225, 0.87811744]],\n \n [[0.02738759, 0.67046751],\n [0.4173048 , 0.55868983]],\n \n [[0.14038694, 0.19810149],\n [0.80074457, 0.96826158]]])\n\n\n\nTo prove that this function uses the uniform distribution, we will generate an array with 10000 values and plot it on a histogram with **matplotlib.pyplot[5]**, a useful tool for plotting data in graph form. In the graph below, we can see that the values that an almost equal number of values are generated per column.\n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nx = np.random.rand(10000) #generate an array with 10000 values\nplt.hist(x,color='g') #plot out a histogram of the array\n```\n\n### Randn()\n\n**Numpy.random.randn()[6]** is a function that returns a sample (or samples) from the “standard normal” distribution. Returns a random number from using the univariate “normal” (Gaussian) distribution of mean 0 and variance 1.\n\nThe normal curve (also known as the bell curve) has its symmetry about the centre. Half of the values generated will be less than the mean, and the other 50% of the values will be greater than the mean.\n\nParameters:\t\nd0, d1, …, dn : int, optional\n
The dimensions of the returned array, should be all positive. If no argument is given a single Python float is returned.\n\nReturns:\t\nZ : ndarray or float\n
A (d0, d1, ..., dn)-shaped array of floating-point samples from the standard normal distribution, or a single such float if no parameters were supplied.\n\n\n```python\nnp.random.randn() #returns sample with one number\n```\n\n\n\n\n -0.2959569528837944\n\n\n\n\n```python\nnp.random.randn(2,2) #returns 2 by 2 array sample\n```\n\n\n\n\n array([[ 0.65228253, -0.16824741],\n [-1.3086617 , -0.82948031]])\n\n\n\nFor random samples from N(mu, sigma^2), use:\n\nsigma * np.random.randn(...) + mu\n\nTwo-by-two array of samples from N(2, 6.25):\n\n\n```python\n2.5 * np.random.randn(2, 2) + 2 #returns 2 by 2 array sample N(2, 6.25)\n```\n\n\n\n\n array([[ 6.33697059, 5.7842766 ],\n [ 1.69177013, -1.772594 ]])\n\n\n\nSample of 10000 values using this function will display a bell curve:\n\n\n```python\nx = np.random.randn(10000) #generate an array with 10000 values\nplt.hist(x,color='r')\nplt.show()\n```\n\nFurther explanation of the normal distribution explained under numpy.random.normal()\n\n### Randint()\n\n**numpy.random.randint()[7]** is a function that returns random integers from low (inclusive) to high (exclusive). It uses the discrete uniform distribution, similar to the numpy.random.rand function. \n\nParameters:\t\nlow : int\n
Lowest (signed) integer to be drawn from the distribution (unless high=None, in which case this parameter is one above the highest such integer).\n\nhigh : int, optional\n
If provided, one above the largest (signed) integer to be drawn from the distribution (see above for behavior if high=None).\n\nsize : int or tuple of ints, optional\n
Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are drawn. Default is None, in which case a single value is returned.\n\ndtype : dtype, optional\n
Desired dtype of the result. All dtypes are determined by their name, i.e., ‘int64’, ‘int’, etc, so byteorder is not available and a specific precision may have different C types depending on the platform. The default value is ‘np.int’.\n\nReturns:\t\nout : int or ndarray of ints\n
size-shaped array of random integers from the appropriate distribution, or a single such random int if size not provided.\n\nnote: random.random_integers, which is similar to this function, has been deprecated.\n\nExample: Coin flip example, possible integers are 0 (heads) or 1 (tails)\n\n\n```python\nnp.random.randint(2) #random number is either 0 or 1\n```\n\n\n\n\n 0\n\n\n\nExample: Generate a random byte\n\n\n```python\nnp.random.randint(2, size = 8)\n```\n\n\n\n\n array([0, 1, 1, 1, 1, 0, 0, 0])\n\n\n\nExample: Generate a sample with 10 numbers of which numbers are between 2(inclusive) and 5 (exclusive)\n\n\n```python\nnp.random.randint(2,5,size=10) \n```\n\n\n\n\n array([2, 2, 3, 4, 2, 2, 4, 4, 3, 2])\n\n\n\nExample: Generate a sample with 10 by 5 numbers that are between 2(inclusive) and 5(exclusive)\n\n\n```python\nnp.random.randint(2,5,size=(10,5))\n```\n\n\n\n\n array([[2, 3, 2, 4, 3],\n [2, 3, 3, 2, 4],\n [3, 3, 2, 4, 4],\n [2, 4, 4, 2, 3],\n [3, 2, 3, 4, 4],\n [3, 2, 4, 3, 4],\n [2, 3, 2, 4, 4],\n [4, 2, 2, 3, 4],\n [3, 4, 4, 4, 4],\n [2, 3, 4, 3, 2]])\n\n\n\n### Random_sample()\n\n**numpy.random.random_sample()[8]** is a function that returns random floats in the half-open interval. Similar to the randint() function, but instead of returning ints, it'll return floats. Calling a function without any parameters will output a float between 0.0(inlusive) and 1.0(exlusive). Results are based off the continuous uniform distribution.\n\nParameters:\t\nsize : int or tuple of ints, optional\n
Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are drawn. Default is None, in which case a single value is returned.\n\nReturns:\t\nout : float or ndarray of floats\n
Array of random floats of shape size (unless size=None, in which case a single float is returned).\n\n\n\nExample: Generate a random price for a good under one euro\n\n\n```python\nround(np.random.random_sample(),2) #gets a random float and round up to two decimal places\n```\n\n\n\n\n 0.1\n\n\n\nExample: Generate an array of 3 random floats\n\n\n```python\nnp.random.random_sample(3)\n```\n\n\n\n\n array([0.947187 , 0.47447803, 0.63588946])\n\n\n\nExample: Generate a random float between -5 and 15\nUse formula : (b - a) * random_sample() + a\n\n\n```python\n(15 - -5) * np.random.random_sample() + -5\n```\n\n\n\n\n -4.464749887084832\n\n\n\nExample: Return a 3 by 3 array of random floats between -5 and 15\n\n\n```python\n(15 - -5) * np.random.random_sample((3,3)) + -5\n```\n\n\n\n\n array([[ 6.34331272, 13.16863128, 8.17594392],\n [12.99294443, -0.53621199, 3.77536419],\n [11.48817683, 5.83157003, 1.45544615]])\n\n\n\n*random(),ranf(), and sample() functions are similar to random_sample and have been deprecated\n\n### Choice()\n\n**numpy.random.choice()[9]** function generates a random sample from a given 1-D array. It uses a uniform distribution when generating the sample, or a non-uniform sample if the user specifies the probability of each element in the array.\n\nParameters:\t\na : 1-D array-like or int\n
If an ndarray, a random sample is generated from its elements. If an int, the random sample is generated as if a were np.arange(a)\n\nsize : int or tuple of ints, optional\n
Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are drawn. Default is None, in which case a single value is returned.\n\nreplace : boolean, optional\n
Whether the sample is with or without replacement\n\np : 1-D array-like, optional\n
The probabilities associated with each entry in a. If not given the sample assumes a uniform distribution over all entries in a.\n\nReturns:\t\nsamples : single item or ndarray\n
The generated random samples\n\nRaises:\t\nValueError\n
If a is an int and less than zero, if a or p are not 1-dimensional, if a is an array-like of size 0, if p is not a vector of probabilities, if a and p have different lengths, or if replace=False and the sample size is greater than the population size\n\nExample: Generate a uniform random sample from an array of number [0,1,2,3,4] of size 4.\n\n\n```python\nnp.random.choice(5, 3)\n```\n\n\n\n\n array([2, 1, 4])\n\n\n\nExample: Generate a non-uniform random sample from an array of numbers [0,1,2,3,4] of size 4.\n\n\n```python\nnp.random.choice(5, 3, p=[0.1, 0.1, 0.1, 0.7, 0])\n```\n\n\n\n\n array([3, 3, 2], dtype=int64)\n\n\n\nExample: Generate a uniform random sample from np.arange(5) of size 3 without replacement:\n\n\n```python\nnp.random.choice(5, 3, replace=False)\n```\n\n\n\n\n array([1, 3, 2])\n\n\n\nExample: Prove that the non-uniform random sample generated uses the probability given to each element. Create a sample size of 1000 with fruit elements, with varying probabilities. The total number of times per fruit is generated should match up to the probabilities given to the respective fruit.\n\n\n```python\nx = np.random.choice([\"apple\",\"banana\",\"orange\",\"berry\"],(1000),p=[0.1,0.1,0.2,0.6])\nplt.hist(x,color='b')\n```\n\nAs we can see from the graph, berries was given a probability of 0.6, and hence roughly 600 berry objects were created out of a sample size of 1000.\n\n### Bytes()\n\nnumpy.random.bytes() is function that generates random bytes.\nParameters:\t\nlength : int\n
Number of random bytes.\n\nReturns:\t\nout : str\n
String of length length.\n\nExample: Generate a random bte with length 5 and convert to string.\n\n\n```python\nx = np.random.bytes(5)\n\"\".join(map(chr, x))\n```\n\n\n\n\n '[\\tv\\xa0×'\n\n\n\n## Permutations\n\n### Shuffle()\n\n**shuffle[11]** is a function that modifies a sequence by shuffling its contents. For multi dimentionally arrays, shuffle() will only change the order of the array along the first axis.\n\nParameters:\t\nx : array_like\n
The array or list to be shuffled.\n\nReturns:\t\n
None\n\nExample: Shuffle an array of integers:\n\n\n```python\narr = np.arange(10)\nnp.random.shuffle(arr)\narr\n```\n\n\n\n\n array([8, 4, 9, 5, 1, 3, 7, 6, 0, 2])\n\n\n\nExample: Shuffle the order of a 2d 3 by 3 array along the first axis.\n\n\n```python\narr = np.arange(9).reshape((3, 3))\nnp.random.shuffle(arr)\narr\n```\n\n\n\n\n array([[6, 7, 8],\n [0, 1, 2],\n [3, 4, 5]])\n\n\n\n### Permutation()\n\npermutation()[12] is a function that takes in an array and returns a permutated copy of that array. For multi dimentionally arrays, shuffle() will only change the order of the array along the first axis.\n\n\nParameters:\t\nx : int or array_like\n
If x is an integer, randomly permute np.arange(x). If x is an array, make a copy and shuffle the elements randomly.\n\nReturns:\t\nout : ndarray\n
Permuted sequence or array range.\n\nExample: Permutate an array of 10 integers from 0-9\n\n\n```python\nnp.random.permutation(10)\n```\n\n\n\n\n array([2, 7, 1, 9, 0, 5, 8, 6, 4, 3])\n\n\n\n\n```python\narr = np.arange(9).reshape((3, 3))\nprint(\"permutated array:\")\nprint(np.random.permutation(arr))\nprint(\"original array (not changed):\")\nprint(arr)\n```\n\n permutated array:\n [[0 1 2]\n [3 4 5]\n [6 7 8]]\n original array (not changed):\n [[0 1 2]\n [3 4 5]\n [6 7 8]]\n\n\n*The **difference[13]** between shuffle() and permutation() is that for permutation(), a copy of the array is shuffled, where as the array itself is shuffled for shuffle() \n\n## Distributions\n\n### Uniform()\n**Numpy.random.uniform()[14]** is a function that draws samples from a uniform distribution. Samples are uniformly distributed over the half-open interval [low, high) (includes low, but excludes high). It is the default distribution function used by rand(), randint() and random_sample()\n\nThe probability density function of the uniform distribution is\n$$p(x) = \\frac{1}{b - a}$$\nwhere a = low and b = high\n\nFor example: if a = -5 and b = 5\n$$p(x) = \\frac{1}{5 -(-5)} = \\frac{1}{10}$$\ntherefore, the probability of every object in that array is 0.1\n\nParameters:\t\nlow : float or array_like of floats, optional\n
Lower boundary of the output interval. All values generated will be greater than or equal to low. The default value is 0.\n\nhigh : float or array_like of floats\n
Upper boundary of the output interval. All values generated will be less than high. The default value is 1.0.\n\nsize : int or tuple of ints, optional\n
Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are drawn. If size is None (default), a single value is returned if low and high are both scalars. Otherwise, np.broadcast(low, high).size samples are drawn.\n\nReturns:\t\nout : ndarray or scalar\n
Drawn samples from the parameterized uniform distribution.\n\nExample: Generate a random sample that is uniformly distributed with 10000 values from 0 to 10\n\n\n```python\nimport matplotlib.pyplot as plt\ns = np.random.uniform(0,10,10000)\ncount, bins, ignored = plt.hist(s, 10, density=True, color='g')\nplt.axhline(y=np.average(count), color='r', linestyle='-')\nplt.show()\n\n\n```\n\nBased on that diagram, we can see that the graph shows a fairly uniform result. The red line shows the probability p(x) of this distribution, which is at 0.1. There is little fluctutation in between the columns. \n\n### Normal()\n\nThe **numpy.random.normal()[15]** function draws random samples from a normal distribution. It is also known as the bell curve because of its shape. \n\nParameters:\t\nloc : float or array_like of floats\n
Mean (“centre”) of the distribution.\n\nscale : float or array_like of floats\n
Standard deviation (spread or “width”) of the distribution.\n\nsize : int or tuple of ints, optional\n
Output shape.\n\nReturns:\t\nout : ndarray or scalar\n
Drawn samples from the parameterized normal distribution.\n\nData can be \"distributed\" in different ways, but in many cases, data tends to be around a central value with no bias left or right, and it gets close to a normal distribution like this[16]: \n\n50% of values less than the mean and 50% greater than the mean, and the symmetry is about the center. \n\nTo understand normal distributions, we need to understand what **standard deviations** are. Standard deviations is basically a measure of how spread out numbers are. When we calculate the standard deviation we find that generally:\n1. 68% of values are within 1 standard deviation of the mean\n2. 95% of values are within 2 standard deviations of the mean\n3. 99.7% of values are within 3 standard deviations of the mean\n\nExample of drawing a bellcurve of the height of students in a school, with mean 1.4, standard deviation of 0.15 and a sample size of 1000 students. [17]\n\n\n```python\ns = np.random.normal(1.4, 0.15, 1000)\ncount, bins, ignored = plt.hist(s, 30, density=True,alpha=0.5)\n\nimport matplotlib.mlab as mlab\ny = mlab.normpdf(bins, 1.4, 0.15) # add the best fit line\nplt.plot(bins, y, 'r--')\nplt.subplots_adjust(left=0.15)\nplt.axvline(x=1.4, color='y')\nplt.axvline(x=1.25, color='y')\nplt.axvline(x=1.1, color='y')\nplt.axvline(x=1.55, color='y')\nplt.axvline(x=1.7, color='y')\n```\n\n### Binomial()\n\nThe **numpy.random.binomial()[18]** function draws samples from a binomial distribution.\n\n\nParameters:\t\nn : int or array_like of ints\n
Parameter of the distribution, >= 0. Floats are also accepted, but they will be truncated to integers.\n\np : float or array_like of floats\n
Parameter of the distribution, >= 0 and <=1.\n\nsize : int or tuple of ints, optional\n
Output shape. \n\nReturns:\t\nout : ndarray or scalar\n
Drawn samples from the parameterized binomial distribution, where each sample is equal to the number of successes over the n trials.\n\nExample: Tossing a coin. The probability of the coin landing on heads is 0.5, and the probability of the coin landing on tails is also 0.5. If the coin is tossed 3 times, what are the probabilities of every outcome?\n\nThere are 8 possibilities:\n1. HHH\n2. HTT\n3. HHT\n4. HTH\n5. THT\n6. TTH\n7. THH\n8. TTT\n\nTherefore, we can see that the probability of getting 3 heads is 1/8 (HHH), the probability of getting 2 heads is 3/8 (HHT,HTH,THH), the probability of getting 1 head is 3/8 (THT,TTH,HTT), and the probability of getting no heads is 1/8 (TTT). \n\nLet's run this test 100 times using numpy:\n\n\n```python\nn, p = 3, 0.5\nx = np.random.binomial(n, p,100)\nplt.hist(x)\n```\n\nFrom the graph, we can see roughly 3/8 or 38 times there will be two heads or two tails, and 1/8 of the time, there will be no tails or no heads.\n\nExample: Dangerous Road. Unlike a coin flip with has an equal probability, the probability of an accident occuring on a dangerous road might not be equal as not having an accident. Say if the chances of having an accident on this road is 0.3 (0.7 probability of a safe journey), what is the probability that the next 5 out of 10 cars will be involved in an accident?\n\nLet's run this test 10000 times:\n\n\n```python\nn, p = 10, 0.3\n\nx = np.random.binomial(n, p,10000)\nplt.hist(x)\n```\n\nWe can see that roughly 1000 times out of 10000 times the next 5 cars will be in accidents, that means the probability of the next 5 cars being in an accident is 10%.\n\nExamples referenced from **mathisfun.com[19]**\n\n### poisson()\n\nThe **numpy.random.poisson()[20]** function draws samples from a poisson distribution.\n\nParameters:\t\nlam : float or array_like of floats\n
Expectation of interval, should be >= 0. A sequence of expectation intervals must be broadcastable over the requested size.\n\nsize : int or tuple of ints, optional\n
Output shape. \n\nReturns:\t\nout : ndarray or scalar\n
Drawn samples from the parameterized Poisson distribution.\n\n\n\nAbove shows an example of Poisson curves with carying lamdas, extracted from the **umass maths department website[20]**. The Poisson distribution shows that the smaller the lambda, the range of likely possibilities will lie closer to the zero line. For example, if the lambda is 1, the graph will be skewed to the left, compared to say lambda = 5 where the graph will be less skewed.\n\nThe values of a poisson curve can be calculated using the Poisson distribution formula, which is
\n$$P(k; \\lambda)=\\frac{\\lambda^k e^{-\\lambda}}{k!}$$\n\nExample: In the World Cup, an average of 2.5 goals are scored each game. Modeling this situation with a Poisson distribution, what is the probability that goals are scored in a game? (example from brilliant.org[21]\n\n\n\\begin{align}\nP(X=0)= \\frac{2.5^0e^{-2.5}}{0!} \\approx 0.082\\\\\\\\\nP(X=1) = \\frac{2.5^1e^{-2.5}}{1!} \\approx 0.205\\\\\\\\\nP(X=2) = \\frac{2.5^2e^{-2.5}}{2!} \\approx 0.257\\\\\\\\\nP(X=3) = \\frac{2.5^3e^{-2.5}}{3!} \\approx 0.213\\\\\\\\\nP(X=4) = \\frac{2.5^4e^{-2.5}}{4!} \\approx 0.133\\\\\\\\\n\\vdots\n\\end{align}\n\n\n\n```python\ns = np.random.poisson(2.5, 10000)\ncount, bins, ignored = plt.hist(s, 10, density=True, color=\"purple\")\nplt.show()\n\n\n```\n\n## Random generator\n\nAs mentioned above, numpy uses the Mersenne Twister for its PseudoRandom Number Generator (PRNG). The PRNG-generated sequence is not truly random, because it is completely determined by an initial value, called the PRNG's seed (which may include truly random values). \n\nThe functions included in numpys random generator are:\n1. **numpy.random.RandomState()[23]**, a container for the Mersenne Twister pseudo-random number generator.\n2. **numpy.random.seed()[24]**, which seeds the generator\n3. **numpy.random.get_state()[25]**, which returns a tuple representing the internal state of the generator.\n4. **numpy.random.set_state(state)[26]**, which sets the internal state of the generator from a tuple.\n\nAn example of seeding and containing random states, from this **stackoverflow explanation[27]**:\n\nWhen a user calls the function np.random.seed(1), the seed for the generator is set to the first number.\n\n\n\n\n```python\nnp.random.seed(1)\nprint(np.random.rand())\nprint(np.random.rand(2,2))\n```\n\n 0.417022004702574\n [[7.20324493e-01 1.14374817e-04]\n [3.02332573e-01 1.46755891e-01]]\n\n\nWhen the user runs the same two functions with the same seed, the results should be the exact same:\n\n\n```python\nnp.random.seed(1)\nprint(np.random.rand())\nprint(np.random.rand(2,2))\n```\n\n 0.417022004702574\n [[7.20324493e-01 1.14374817e-04]\n [3.02332573e-01 1.46755891e-01]]\n\n\nWe can use np.random.RandomState as a container for the PRNG:\n\n\n```python\nr = np.random.RandomState(1)\nprint(r.rand())\nprint(r.rand(2,2))\n```\n\n 0.417022004702574\n [[7.20324493e-01 1.14374817e-04]\n [3.02332573e-01 1.46755891e-01]]\n\n\nThe user can run get_state() which will return the entire PRNG:\n\n\n```python\nprint(r.get_state())\n```\n\n ('MT19937', array([2629073562, 2983301384, 681580311, 4033622241, 792772838,\n 3306961981, 92883131, 1785085746, 3364128315, 2402025379,\n 3224868746, 1145213362, 3784365245, 1948434636, 2667646161,\n 2598854474, 921967201, 1345782310, 4019597455, 2906395199,\n 1349669984, 2676817993, 4201769589, 2002781766, 3540177092,\n 4224925813, 3661313599, 1709930435, 1812273278, 2973452884,\n 1592291796, 3452239013, 3588672187, 3228651068, 3191454495,\n 3286135343, 2640545275, 3096953148, 3746505897, 2292163827,\n 2164382601, 1581410039, 2413832827, 2536571847, 179684232,\n 1638923698, 3155158821, 1454330362, 4050607484, 607322300,\n 2216566078, 597866774, 1036426282, 732815996, 3131865469,\n 2440339870, 2814550949, 1479383443, 2449469876, 3810238677,\n 2923086221, 437801529, 2891199990, 1886893516, 3898673786,\n 376204646, 1392372379, 4123661669, 1140754642, 3539167101,\n 2386309702, 3740957436, 4033654965, 1720449988, 3434980330,\n 4213508374, 3576835843, 2818865106, 1653162115, 2935588114,\n 3870616539, 102614847, 1476834675, 1220770796, 1233652508,\n 2385138085, 1300608482, 2753953039, 262993567, 4009374062,\n 2143978386, 1613109469, 3072671496, 1223816410, 4088822114,\n 3382188205, 2250056281, 1926821318, 3806317775, 2882166470,\n 94227745, 2877123406, 1030225246, 1555072155, 95009460,\n 1855512191, 2840453856, 2478087736, 836340051, 1566383306,\n 2625414289, 3519123538, 840509954, 2373484829, 676528503,\n 2783662465, 3557034492, 2566048980, 2347785709, 3566819907,\n 1311855742, 198269976, 2693520819, 2127070362, 961491174,\n 3932714317, 837664826, 4277891831, 3535515583, 2831416447,\n 3505045078, 3763313683, 367436315, 3614057572, 3780746374,\n 2693039652, 2297021184, 2224934154, 698822522, 2718629137,\n 1175446314, 2603507610, 2067589016, 2280810156, 2037033584,\n 3956938481, 1112874779, 3264939860, 2054107185, 2354026721,\n 1958640221, 2844284824, 3775753525, 2462549847, 3562644229,\n 3683686884, 3714884555, 2266356233, 2808583945, 980888698,\n 1137581788, 2771236582, 1975939317, 1605707990, 614167064,\n 767063856, 4227905160, 3590303986, 2932373212, 2230415839,\n 127157074, 2328724316, 3356372094, 3215726425, 282321962,\n 4226412442, 106823192, 3925701436, 610765913, 281952627,\n 1832011890, 2670621135, 1012800992, 1489632964, 1371755819,\n 2529629289, 607643288, 3941535311, 3202770816, 284461833,\n 3696778854, 325625733, 2671656400, 1391137252, 1240723705,\n 3132941411, 314202987, 1301784708, 2575857120, 313287791,\n 3569720512, 981744121, 2986286440, 1051168756, 3881027887,\n 1088809168, 3421075971, 2655923113, 2577977181, 3968201444,\n 1406585576, 4001025594, 1854233928, 3825832114, 954907921,\n 3109212504, 1706316388, 1550715292, 2934259476, 1892992132,\n 4050317728, 4110743408, 359920673, 3542060425, 597068400,\n 843058885, 3799566677, 2064802063, 860032883, 2732673041,\n 3457529378, 3660165513, 1125914118, 4212233956, 3757086488,\n 2632116865, 462233764, 161423763, 141910303, 2265109737,\n 1983126147, 2231395445, 2147383559, 611750005, 2194081082,\n 1699618892, 3841025952, 1294478167, 936120505, 4102008957,\n 4268194620, 1994019922, 1187332833, 3953675561, 1917283619,\n 896867387, 1634068959, 3950876764, 485558549, 45383166,\n 2795959904, 1717914918, 3449856475, 3796449494, 3318166191,\n 1007512487, 480498390, 1730605673, 3972660041, 2287008439,\n 539639323, 1569683418, 3795864463, 453065119, 2449404120,\n 265049099, 3514892628, 2665563904, 2534523080, 1969344934,\n 4294466702, 1478959417, 1858551310, 3029422620, 4121720519,\n 2933843154, 3209557296, 3111170404, 4264711934, 2448282623,\n 1388503581, 1999436060, 818418468, 3283991819, 2356924521,\n 2684567658, 1424193429, 1187340812, 3847120877, 1987859863,\n 1879502046, 3422594099, 1419478013, 4148487199, 2538837125,\n 3694851522, 636350498, 1097832595, 3779331880, 351970715,\n 2534774459, 3389311029, 3762283879, 3742425828, 3882821767,\n 2683353, 1981273229, 4068324016, 539226467, 2411256222,\n 1780609115, 2059099269, 2889497980, 1123848930, 540086248,\n 3467353606, 3362203896, 4058078927, 93044840, 426751932,\n 824266620, 3444590461, 2122918776, 3339845861, 4233923286,\n 3733051177, 2957657929, 3110908772, 2551930098, 1294126893,\n 2213336821, 2124571119, 49780221, 2901327722, 2493306969,\n 2545470627, 102527300, 3876142393, 4097726412, 3510695954,\n 660912408, 2033930425, 1601509561, 969180562, 635252598,\n 177954239, 3054207519, 4122051269, 2787463443, 1664731394,\n 2907371963, 1484884283, 1560546623, 2902374922, 2395942225,\n 451352804, 3346805556, 3459298550, 3482428591, 10753957,\n 4101820340, 3306178891, 1122941824, 355877597, 1683964498,\n 238724805, 3926649337, 3197046734, 4277634633, 2288745211,\n 4202067531, 526022968, 4017453944, 1499184106, 2677441952,\n 2227353703, 1995296581, 1690255681, 2920887680, 605849491,\n 3072795503, 746910746, 2709796449, 1225135658, 657841564,\n 4070363626, 144842260, 3718575695, 3159187032, 88291794,\n 3129049475, 410962657, 1728726693, 2397606939, 4126386549,\n 751549633, 4226219908, 1549973222, 3060733996, 3741110422,\n 2530947598, 2627897488, 2317706652, 1170828427, 2671701715,\n 1153351468, 3762293788, 4093330405, 1641962571, 699324101,\n 3173743570, 1798831929, 3467616712, 4198420524, 2448981354,\n 499920867, 968642107, 2140815539, 4193124145, 1639223168,\n 284638153, 396985542, 3543438633, 237854258, 3938010494,\n 24441053, 2947436871, 1273496002, 719279415, 3574242559,\n 1040109604, 3849196601, 3250223302, 3411729501, 3031943234,\n 2932285520, 2932420675, 2011314805, 2480850074, 3207806491,\n 462404995, 3279042455, 4270524229, 1064389665, 1894847490,\n 721365878, 357178131, 2827490451, 2604438657, 242514037,\n 678802395, 1322770750, 2747624534, 4246466163, 4188936761,\n 1207204018, 980275996, 841637218, 1468131552, 4102349079,\n 586888764, 3105466755, 1628818384, 2991889790, 2801191520,\n 2114916962, 1124291831, 3242113092, 1082871720, 3625937786,\n 2796251125, 1651820702, 3427511545, 2035120316, 1024058911,\n 4209506140, 2527167744, 213886228, 2514956543, 2450260579,\n 327684603, 3444379103, 3884997363, 2844468873, 2261078634,\n 3926825101, 439487268, 3789435080, 1212963762, 4259079565,\n 2772611204, 2534236055, 2430244594, 916922266, 903950702,\n 3381351589, 2268543712, 3616954837, 1273083041, 1682465785,\n 1342921678, 2593265787, 3033724173, 2988544460, 1824668777,\n 1214999983, 257453352, 4187931679, 3523379959, 1481153225,\n 4290295859, 220376185, 4136013972, 511679284, 3510589272,\n 1404047266, 3712771231, 2125374725, 32037606, 3601685135,\n 3433623522, 841138647, 1610171318, 3920699442, 1084892922,\n 3146108732, 3672652561, 1148331655, 2473777375, 3039860130,\n 1170979324, 575756423, 1389255297, 339011744, 2351938991,\n 4050094885, 2773634239, 3715040333, 3920910597, 562407139,\n 29887881, 1623822350, 358193390, 1822261341, 1243290919,\n 755541153, 153529770, 994467513, 1339524978, 3174283928,\n 2782204324, 182251010, 1833692038, 3477775846, 2820237500,\n 2165639585, 4089211432, 4010345846, 1238643345, 3710224584,\n 2251039304, 1196168985, 3165387311, 3920626153, 1796963839,\n 2112227260, 3358845388, 593715887, 3046897033, 2968478428,\n 3846781604, 3565923316, 2452128692, 68338106, 1427007580,\n 2192917968, 75235680, 2134869635, 1857807303, 3745016485,\n 2601327385, 35512535, 559792668, 2093376088, 939608650,\n 2259549051, 2605376692, 2058599240, 2980581379, 3160415220,\n 2739135905, 254886981, 1652380747, 371107437, 1123937393,\n 4185309254, 864314942, 2739416220, 2185572068, 1163546293,\n 3491702910, 996401156, 1198755052, 2898003956, 745796080,\n 4127642404, 4237523457, 1274635091, 3144139009, 1600421663,\n 4226154574, 538248802, 373236455, 116925273], dtype=uint32), 10, 0, 0.0)\n\n\n## References\n1. https://www.numpy.org/ - Welcome to NumPy - Introduction of NumPy\n2. https://www.maths.tcd.ie/~fionn/misc/mt.php - Details of the Mersenne Twister formula\n3. https://docs.scipy.org/doc/numpy-1.15.1/reference/generated/numpy.random.randint.html#numpy.random.randint - numpy.random.rand() explanation\n4. http://mathworld.wolfram.com/Half-ClosedInterval.html - explanation of the half-open interval\n5. https://matplotlib.org/api/pyplot_api.html - introduction to matplotlib.pyplot package\n6. https://docs.scipy.org/doc/numpy-1.15.1/reference/generated/numpy.random.randn.html#numpy.random.randn - numpy.random.randn() explanation\n7. https://docs.scipy.org/doc/numpy-1.15.1/reference/generated/numpy.random.random_integers.html#numpy.random.random_integers - numpy.random.randint() explanation\n8. https://docs.scipy.org/doc/numpy-1.15.1/reference/generated/numpy.random.random_sample.html#numpy.random.random_sample - numpy.random.random_sample explanation\n9. https://docs.scipy.org/doc/numpy-1.15.1/reference/generated/numpy.random.choice.html#numpy.random.choice - numpy.random.choice() explanation\n10. https://docs.scipy.org/doc/numpy-1.15.1/reference/generated/numpy.random.bytes.html#numpy.random.bytes - numpy.random.bytes explanation\n11. https://docs.scipy.org/doc/numpy-1.15.1/reference/generated/numpy.random.shuffle.html#numpy.random.shuffle - shuffle() explanation\n12. https://docs.scipy.org/doc/numpy-1.15.1/reference/generated/numpy.random.permutation.html - permutation() explanation\n13. https://stackoverflow.com/questions/15474159/shuffle-vs-permute-numpy - difference between shuffle() and permutation()\n14. https://docs.scipy.org/doc/numpy-1.15.1/reference/generated/numpy.random.uniform.html#numpy.random.uniform - official numpy reference for numpy.random.uniform()\n15. https://docs.scipy.org/doc/numpy-1.15.1/reference/generated/numpy.random.normal.html#numpy.random.normal - official numpy reference for numpy.random.normal()\n16. https://www.mathsisfun.com/data/standard-normal-distribution.html - good explanation of bell curves by math is fun.\n17. https://plot.ly/matplotlib/histograms/#basic-histogram-with-hist-function - code to draw bell curve\n18. https://docs.scipy.org/doc/numpy-1.15.1/reference/generated/numpy.random.binomial.html#numpy.random.binomial - official numpy reference for numpy.random.binomial()\n19. https://www.mathsisfun.com/data/binomial-distribution.html - good examples of binomial distribution\n20. https://docs.scipy.org/doc/numpy-1.15.1/reference/generated/numpy.random.poisson.html#numpy.random.poisson - official numpy reference for numpy.random.possion()\n21. https://www.umass.edu/wsp/resources/poisson/ - good explanation and graphs for poisson curve\n22. https://brilliant.org/wiki/poisson-distribution/ - good examples of poisson curve\n23. https://docs.scipy.org/doc/numpy-1.15.1/reference/generated/numpy.random.RandomState.html#numpy.random.RandomState - official numpy reference for numpy.random.RandomState()\n24. https://docs.scipy.org/doc/numpy-1.15.1/reference/generated/numpy.random.seed.html#numpy.random.seed\n25. https://docs.scipy.org/doc/numpy-1.15.1/reference/generated/numpy.random.get_state.html#numpy.random.get_state\n26. https://docs.scipy.org/doc/numpy-1.15.1/reference/generated/numpy.random.set_state.html#numpy.random.set_state\n27. https://stackoverflow.com/questions/22994423/difference-between-np-random-seed-and-np-random-randomstate?rq=1\n\n\n```python\n\n```\n", "meta": {"hexsha": "80abea75aa667289f1d25a3f84df33ca05d8b4d2", "size": 106931, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "numpy-random.ipynb", "max_stars_repo_name": "yonjeremy/emerging-technologies-assesment", "max_stars_repo_head_hexsha": "4afbad9af44e865a551e7e1c2e820721cb304fce", "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": "numpy-random.ipynb", "max_issues_repo_name": "yonjeremy/emerging-technologies-assesment", "max_issues_repo_head_hexsha": "4afbad9af44e865a551e7e1c2e820721cb304fce", "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": "numpy-random.ipynb", "max_forks_repo_name": "yonjeremy/emerging-technologies-assesment", "max_forks_repo_head_hexsha": "4afbad9af44e865a551e7e1c2e820721cb304fce", "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.831875, "max_line_length": 13032, "alphanum_fraction": 0.7728909297, "converted": true, "num_tokens": 10791, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425355825848, "lm_q2_score": 0.9597620553622539, "lm_q1q2_score": 0.8826380101492963}} {"text": "```python\n# This cell just imports the relevant modules\n\nimport numpy\nimport pylab\nfrom math import pi, exp\nfrom sympy import sin, cos, Function, Symbol, diff, integrate, dsolve, checkodesol, solve, ode_order, classify_ode, pprint\nimport mpmath\n```\n\n\n```python\n###### ORDER OF AN ODE ######\n###### Lecture 7, slide 9 ######\nt = Symbol('t') # Independent variable\neta = Symbol('eta') # Constant\nv = Function('v') # Dependent variable v(t)\node = diff(v(t),t) + eta*v(t) # The ODE we wish to solve. Make sure the RHS is equal to zero.\nprint(\"ODE #1:\") \npprint(ode)\nprint(\"The order of ODE #1 is %d\" % ode_order(ode, v(t))) \n\nx = Function('x') # Dependent variable x(t)\nm = Symbol('m') # Constant\nk = Symbol('k') # Constant\node = m*diff(x(t),t,2) + k*x(t)\nprint(\"ODE #2:\") \npprint(ode)\nprint(\"The order of ODE #2 is %d\" % ode_order(ode, x(t))) \n\ny = Function('y') # Dependent variable y(t)\node = diff(y(t),t,4) - diff(y(t),t,2)\nprint(\"ODE #3:\") \npprint(ode)\nprint(\"The order of ODE #3 is %d\" % ode_order(ode, y(t))) \n```\n\n\n```python\n###### ANALYTICAL SOLUTIONS ######\n###### Lecture 7, slide 14 ######\nx = Symbol('x') # Independent variable\ny = Function('y') # Dependent variable y(x)\n\n# The ODE we wish to solve. Make sure the RHS is equal to zero.\node = diff(y(x),x) - 2*x*(1-y(x))\nsolution = dsolve(ode, y(x)) # Solve the ode for function y(x).\nprint(\"ODE #4:\") \npprint(ode)\nprint(\"The solution to ODE #4 is: \", solution) \n\n# This function checks that the result of dsolve is indeed a solution\n# to the ode. Basically it substitutes in 'solution' into 'ode' and\n# checks that the RHS is zero. If it is, the function returns 'True'.\nprint(\"Checking solution using checkodesol...\") \ncheck = checkodesol(ode, solution)\nif(check[0] == True):\n print(\"y(x) is indeed a solution to ODE #4\") \nelse:\n print(\"y(x) is NOT a solution to ODE #4\") \n \n# The mpmath module can handle initial conditions (x0, y0) when solving an\n# initial value problem, using the odefun function. However, this will\n# not give you an analytical solution to the ODE, only a numerical\n# solution. The print statement below compares the numerical solution\n# with the values of the (already known) analytical solution between x=0 and x=10.\n\nf = mpmath.odefun(lambda x, y: 2*x*(1-y), x0=0, y0=2)\nfor x in numpy.linspace(0, 10, 100):\n print(f(x), 1.0 + exp(-x**2))\n```\n\n\n```python\n###### SEPARATION OF VARIABLES ######\n###### Lecture 7, slide 20 ######\nx = Symbol('x') # Independent variable\ny = Function('y') # Dependent variable y(x)\n# The ODE we wish to solve.\node = (1.0/y(x))*diff(y(x),x) - cos(x)\nprint(\"ODE #5:\") \npprint(ode)\n# Solve the ode for function y(x).using separation of variables.\n# Note that the optional 'hint' argument here has been used\n# to tell SymPy how to solve the ODE. However, it is usually\n# smart enough to work it out for itself.\nsolution = dsolve(ode, y(x), hint='separable')\nprint(\"The solution to ODE #5 is: \", solution) \n```\n\n\n```python\n###### INTEGRATION FACTOR ######\n###### Lecture 7, slide 23 ######\nx = Symbol('x') # Independent variable\ny = Function('y') # Dependent variable y(x)\n# The ODE we wish to solve.\node = diff(y(x),x) - 2*x + 2*x*y(x)\nprint(\"ODE #6:\") \npprint(ode)\n# Solve the ode for function y(x).using separation of variables\nsolution = dsolve(ode, y(x))\nprint(\"The solution to ODE #6 is: \", solution) \n```\n\n\n```python\n###### APPLICATION: RADIOACTIVE DECAY ######\n###### Lecture 7, slide 26 ######\nt = Symbol('t') # Independent variable\nN = Function('N') # Dependent variable N(t)\nl = Symbol('l') # Constant\n# The ODE we wish to solve.\node = diff(N(t),t) + l*N(t)\nprint(\"ODE #7:\") \npprint(ode)\nsolution = dsolve(ode, N(t))\nprint(\"The solution to ODE #7 is: \", solution) \n```\n\n\n```python\n###### APPLICATION: PARTICLE SETTLING ######\n###### Lecture 7, slide 31 ######\nt = Symbol('t') # Independent variable - time\nv = Function('v') # Dependent variable v(t) - the particle velocity\n# Physical constants\nrho_f = Symbol('rho_f') # Fluid density\nrho_p = Symbol('rho_p') # Particle density\neta = Symbol('eta') # Viscosity\ng = Symbol('g') # Gravitational acceleration\na = Symbol('a') # Particle radius\n# The ODE we wish to solve.\node = diff(v(t),t) - ((rho_p - rho_f)/rho_p)*g + (9*eta/(2*(a**2)*rho_p))*v(t)\nprint(\"ODE #8:\") \npprint(ode)\nsolution = dsolve(ode, v(t))\nprint(\"The solution to ODE #8 is: \", solution) \n```\n", "meta": {"hexsha": "4b23da8f8a3321ffd036a9a4b7587de663017c6e", "size": 6529, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "mathematics/mm1/Lecture_7_ODEs.ipynb", "max_stars_repo_name": "jrper/thebe-test", "max_stars_repo_head_hexsha": "554484b1422204a23fe47da41c6dc596a681340f", "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/mm1/Lecture_7_ODEs.ipynb", "max_issues_repo_name": "jrper/thebe-test", "max_issues_repo_head_hexsha": "554484b1422204a23fe47da41c6dc596a681340f", "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/mm1/Lecture_7_ODEs.ipynb", "max_forks_repo_name": "jrper/thebe-test", "max_forks_repo_head_hexsha": "554484b1422204a23fe47da41c6dc596a681340f", "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.4820512821, "max_line_length": 131, "alphanum_fraction": 0.5340787257, "converted": true, "num_tokens": 1340, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9609517106286379, "lm_q2_score": 0.9184802507195636, "lm_q1q2_score": 0.8826151681075849}} {"text": "# Linear programming with scipy\n\nSee https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.linprog.html\n\n\n```python\nimport scipy.optimize\n```\n\nProblem examples:\n- http://people.brunel.ac.uk/~mastjjb/jeb/or/morelp.html\n\n## Scipy's syntax\n\nExample for a problem of 2 dimensions:\n\n$$\n\\begin{align}\n \\min_{x_1,x_2} & \\quad \\color{\\red}{c_1} x_1 + \\color{\\red}{c_2} x_2 \\\\\n \\text{s.t.} & \\quad \\color{\\orange}{A_{1,1}} x_1 + \\color{\\orange}{A_{1,2}} x_2 \\leq \\color{\\green}{b_1} \\\\\n & \\quad \\color{\\orange}{A_{2,1}} x_1 + \\color{\\orange}{A_{2,2}} x_2 \\leq \\color{\\green}{b_2} \\\\\n & \\quad \\color{\\purple}{B_{1,1}} \\geq x_1 \\geq \\color{\\purple}{B_{1,2}} \\\\\n & \\quad \\color{\\purple}{B_{2,1}} \\geq x_2 \\geq \\color{\\purple}{B_{2,2}} \\\\\n\\end{align}\n$$\n\n \n\n$$\n\\color{\\red}{\n\\boldsymbol{c} = \\begin{pmatrix}\n c_1 \\\\\n c_2\n\\end{pmatrix}\n}\n\\quad\n\\color{\\orange}{\n\\boldsymbol{A} = \\begin{pmatrix}\n A_{1,1} & A_{1,2} \\\\\n A_{2,1} & A_{2,2}\n\\end{pmatrix}\n}\n\\quad\n\\color{\\green}{\n\\boldsymbol{b} = \\begin{pmatrix}\n b_1 \\\\\n b_2\n\\end{pmatrix}\n}\n\\quad\n\\color{\\purple}{\n\\boldsymbol{B} = \\begin{pmatrix}\n B_{1,1} & B_{1,2} \\\\\n B_{2,1} & B_{2,2}\n\\end{pmatrix}\n}\n$$\n\n \n\n$$\n\\text{scipy.optimize.linprog}(\\color{\\red}{\\boldsymbol{c}}, ~ \\color{\\orange}{\\boldsymbol{A}}, ~ \\color{\\green}{\\boldsymbol{b}}, ~ \\color{\\purple}{\\boldsymbol{B}})\n$$\n\n## Example 1\n\n$$\n\\begin{align}\n \\min_{x_0,x_1} & \\quad -x_0 + 4 x_1 \\\\\n \\text{s.t.} & \\quad -3 x_0 + x_1 \\leq 6 \\\\\n & \\quad -x_0 - 2 x_1 \\geq -4 \\\\\n & \\quad x_1 \\geq -3\n\\end{align}\n$$\n\n\n```python\n# Coefficients of the linear objective function to be minimized\nc = [-1, 4]\n\n# 2-D array which, when matrix-multiplied by x, gives the values of the upper-bound inequality constraints at x.\nA = [[-3, 1],\n [ 1, 2]]\n\n# 1-D array of values representing the upper-bound of each inequality constraint (row) in A.\nb = [6, 4]\n\n# Sequence of (min, max) pairs for each element in x, defining the bounds on that parameter.\n# Use None for one of min or max when there is no bound in that direction.\n# By default bounds are (0, None) (non-negative).\n# If a sequence containing a single tuple is provided, then min and max will be applied to all variables in the problem.\nx0_bounds = (None, None)\nx1_bounds = (-3, None)\nbounds = (x0_bounds,x1_bounds)\n\nscipy.optimize.linprog(c, A_ub=A, b_ub=b, bounds=bounds)\n```\n\n## The carpenter problem\n\n\n```python\n# Coefficients of the linear objective function to be minimized\nc = np.array([3, 5])\n\n# 2-D array which, when matrix-multiplied by x, gives the values of the upper-bound inequality constraints at x.\nA_ub = np.array([[3, 2],\n [1, 2],\n [5, 4]])\n\n# 1-D array of values representing the upper-bound of each inequality constraint (row) in A_ub.\nb_ub = np.array([700, 500, 1500])\n\n# Sequence of (min, max) pairs for each element in x, defining the bounds on that parameter.\n# Use None for one of min or max when there is no bound in that direction.\n# By default bounds are (0, None) (non-negative).\n# If a sequence containing a single tuple is provided, then min and max will be applied to all variables in the problem.\nbounds = ((0, None), (0, None))\n\nscipy.optimize.linprog(-c, A_ub=A_ub, b_ub=b_ub, bounds=bounds)\n```\n\nThe optimal solution is obtain for $x_1=100$ and $x_2=200$ with a gain of 1300.\n", "meta": {"hexsha": "e2b4ae6daf557b63ee3754f935363337dfe078c6", "size": 6101, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "nb_dev_python/python_scipy_linear_programming_en.ipynb", "max_stars_repo_name": "jdhp-docs/python-notebooks", "max_stars_repo_head_hexsha": "91a97ea5cf374337efa7409e4992ea3f26b99179", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2017-05-03T12:23:36.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-26T17:30:56.000Z", "max_issues_repo_path": "nb_dev_python/python_scipy_linear_programming_en.ipynb", "max_issues_repo_name": "jdhp-docs/python-notebooks", "max_issues_repo_head_hexsha": "91a97ea5cf374337efa7409e4992ea3f26b99179", "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": "nb_dev_python/python_scipy_linear_programming_en.ipynb", "max_forks_repo_name": "jdhp-docs/python-notebooks", "max_forks_repo_head_hexsha": "91a97ea5cf374337efa7409e4992ea3f26b99179", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-10-26T17:30:57.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-26T17:30:57.000Z", "avg_line_length": 26.8766519824, "max_line_length": 185, "alphanum_fraction": 0.4969677102, "converted": true, "num_tokens": 1143, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377249197138, "lm_q2_score": 0.9207896758909757, "lm_q1q2_score": 0.8826116410580965}} {"text": "# Symbolically Understanding Christoffel Symbol and Riemann Curvature Tensor using EinsteinPy\n\n\n```python\nimport sympy\nfrom einsteinpy.symbolic import MetricTensor, ChristoffelSymbols, RiemannCurvatureTensor\n\nsympy.init_printing() # enables the best printing available in an environment\n```\n\n### Defining the metric tensor for 3d spherical coordinates\n\n\n```python\nsyms = sympy.symbols('r theta phi')\n# define the metric for 3d spherical coordinates\nmetric = [[0 for i in range(3)] for i in range(3)]\nmetric[0][0] = 1\nmetric[1][1] = syms[0]**2\nmetric[2][2] = (syms[0]**2)*(sympy.sin(syms[1])**2)\n# creating metric object\nm_obj = MetricTensor(metric, syms)\nm_obj.tensor()\n```\n\n### Calculating the christoffel symbols\n\n\n```python\nch = ChristoffelSymbols.from_metric(m_obj)\nch.tensor()\n```\n\n\n```python\nch.tensor()[1,1,0]\n```\n\n### Calculating the Riemann Curvature tensor\n\n\n```python\n# Calculating Riemann Tensor from Christoffel Symbols\nrm1 = RiemannCurvatureTensor.from_christoffels(ch)\nrm1.tensor()\n```\n\n\n```python\n# Calculating Riemann Tensor from Metric Tensor\nrm2 = RiemannCurvatureTensor.from_metric(m_obj)\nrm2.tensor()\n```\n\n### Calculating the christoffel symbols for Schwarzschild Spacetime Metric\n - The expressions are unsimplified\n\n\n```python\nsyms = sympy.symbols(\"t r theta phi\")\nG, M, c, a = sympy.symbols(\"G M c a\")\n# using metric values of schwarschild space-time\n# a is schwarzschild radius\nlist2d = [[0 for i in range(4)] for i in range(4)]\nlist2d[0][0] = 1 - (a / syms[1])\nlist2d[1][1] = -1 / ((1 - (a / syms[1])) * (c ** 2))\nlist2d[2][2] = -1 * (syms[1] ** 2) / (c ** 2)\nlist2d[3][3] = -1 * (syms[1] ** 2) * (sympy.sin(syms[2]) ** 2) / (c ** 2)\nsch = MetricTensor(list2d, syms)\nsch.tensor()\n```\n\n\n```python\n# single substitution\nsubs1 = sch.subs(a,0)\nsubs1.tensor()\n```\n\n\n```python\n# multiple substitution\nsubs2 = sch.subs([(a,0), (c,1)])\nsubs2.tensor()\n```\n\n\n```python\nsch_ch = ChristoffelSymbols.from_metric(sch)\nsch_ch.tensor()\n```\n\n### Calculating the simplified expressions\n\n\n```python\nsimplified = sch_ch.simplify()\nsimplified\n```\n", "meta": {"hexsha": "20b1046045fe5117cf3c2be6df43d52c5a14dd0f", "size": 124618, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "docs/source/examples/Symbolically Understanding Christoffel Symbol and Riemann Curvature Tensor using EinsteinPy.ipynb", "max_stars_repo_name": "bibek22/einsteinpy", "max_stars_repo_head_hexsha": "78bf5d942cbb12393852f8e4d7a8426f1ffe6f23", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-06-01T18:37:53.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-01T18:37:53.000Z", "max_issues_repo_path": "docs/source/examples/Symbolically Understanding Christoffel Symbol and Riemann Curvature Tensor using EinsteinPy.ipynb", "max_issues_repo_name": "bibek22/einsteinpy", "max_issues_repo_head_hexsha": "78bf5d942cbb12393852f8e4d7a8426f1ffe6f23", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2019-04-08T17:39:50.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-11T03:10:09.000Z", "max_forks_repo_path": "docs/source/examples/Symbolically Understanding Christoffel Symbol and Riemann Curvature Tensor using EinsteinPy.ipynb", "max_forks_repo_name": "bibek22/einsteinpy", "max_forks_repo_head_hexsha": "78bf5d942cbb12393852f8e4d7a8426f1ffe6f23", "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": 232.4962686567, "max_line_length": 27632, "alphanum_fraction": 0.8384824022, "converted": true, "num_tokens": 654, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377237352755, "lm_q2_score": 0.9207896748041438, "lm_q1q2_score": 0.8826116389257085}} {"text": "# Solve equation systems with SymPy\nOnce an a while you need to solve simple equation systems, I have found that using SymPy for this is a much better option than using pen and paper, where I usually make mistakes. Here is some short examples...\n\n\n```python\n# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport sympy as sp\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n for filename in filenames:\n print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session\n```\n\n## Linear system\n\n\n```python\nx,y,z = sp.symbols('x y z')\n```\n\n\n```python\neq_1 = sp.Eq(lhs=y,\n rhs=2*x)\neq_1\n```\n\n\n```python\neq_2 = sp.Eq(lhs=z,\n rhs=3*y)\neq_2\n```\n\n\n```python\neq_2.subs(y,sp.solve(eq_1,y)[0])\n```\n\nWe try to use *solve* to get the expression for **z**:\n\n\n```python\neqs = (\n eq_1,\n eq_2,\n)\n\nsolution = sp.solve(eqs, [z])\nsolution\n```\n\n...so this is giving us **eq_2** which we kind of know already.\nSo we must add a list [y,z] to solve both equations.\n\n\n```python\neqs = (\n eq_1,\n eq_2,\n)\n\nsolution = sp.solve(eqs, [y,z])\nsolution\n```\n\n\n```python\nsolution[z]\n```\n\n## Quadratic\n\n\n```python\neq_3 = sp.Eq(lhs=z**2,\n rhs=2*y)\neq_3\n```\n\n\n```python\neq_3.subs(y,sp.solve(eq_1,y)[0])\n```\n\n\n```python\neqs = (\n eq_1,\n eq_3,\n)\n\nsolution = sp.solve(eqs, [y,z])\nsolution\n```\n\nSince there is now two solutions these are given in a list where each item contain the solution for **y** and **z**.\n\n\n```python\nsolution[0][-1]\n```\n\n\n```python\nsolution[1][-1]\n```\n\nBut in order to make this less confusing the *dict* flag can be set to True:\n\n\n```python\neqs = (\n eq_1,\n eq_3,\n)\n\nsolution = sp.solve(eqs, [y,z], dict=True)\nsolution\n```\n\n## Changing the order of symbols:\n\n\n```python\neqs = (\n eq_1,\n eq_3,\n)\n\nsolution = sp.solve(eqs, [z,y])\nsolution\n```\n\n... this is swapping the order of solutions\n\n## Changing the order of equations:\n\n\n```python\neqs = (\n eq_3,\n eq_1,\n)\n\nsolution = sp.solve(eqs, [y,z])\nsolution\n```\n\n...this has no effect.\n", "meta": {"hexsha": "d41450a8092d350f579b02e2d7ee253c28a6a459", "size": 5184, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "kernels/sympy-solve/sympy-solve.ipynb", "max_stars_repo_name": "martinlarsalbert/kaggle", "max_stars_repo_head_hexsha": "5f75b0b7bf6adf1f5c9c20c2c3d4e1f6670716ac", "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": "kernels/sympy-solve/sympy-solve.ipynb", "max_issues_repo_name": "martinlarsalbert/kaggle", "max_issues_repo_head_hexsha": "5f75b0b7bf6adf1f5c9c20c2c3d4e1f6670716ac", "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": "kernels/sympy-solve/sympy-solve.ipynb", "max_forks_repo_name": "martinlarsalbert/kaggle", "max_forks_repo_head_hexsha": "5f75b0b7bf6adf1f5c9c20c2c3d4e1f6670716ac", "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": 5184.0, "max_line_length": 5184, "alphanum_fraction": 0.6857638889, "converted": true, "num_tokens": 774, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541528387691, "lm_q2_score": 0.9372107892107373, "lm_q1q2_score": 0.882528431745591}} {"text": "# Transformations, Eigenvectors, and Eigenvalues\n\nMatrices and vectors are used together to manipulate spatial dimensions. This has a lot of applications, including the mathematical generation of 3D computer graphics, geometric modeling, and the training and optimization of machine learning algorithms. We're not going to cover the subject exhaustively here; but we'll focus on a few key concepts that are useful to know when you plan to work with machine learning.\n\n## Linear Transformations\nYou can manipulate a vector by multiplying it with a matrix. The matrix acts a function that operates on an input vector to produce a vector output. Specifically, matrix multiplications of vectors are *linear transformations* that transform the input vector into the output vector.\n\nFor example, consider this matrix ***A*** and vector ***v***:\n\n$$ A = \\begin{bmatrix}2 & 3\\\\5 & 2\\end{bmatrix} \\;\\;\\;\\; \\vec{v} = \\begin{bmatrix}1\\\\2\\end{bmatrix}$$\n\nWe can define a transformation ***T*** like this:\n\n$$ T(\\vec{v}) = A\\vec{v} $$\n\nTo perform this transformation, we simply calculate the dot product by applying the *RC* rule; multiplying each row of the matrix by the single column of the vector:\n\n$$\\begin{bmatrix}2 & 3\\\\5 & 2\\end{bmatrix} \\cdot \\begin{bmatrix}1\\\\2\\end{bmatrix} = \\begin{bmatrix}8\\\\9\\end{bmatrix}$$\n\nHere's the calculation in Python:\n\n\n```python\nimport numpy as np\n\nv = np.array([1,2])\nA = np.array([[2,3],\n [5,2]])\n\nt = A@v\nprint (t)\n```\n\n [8 9]\n\n\nIn this case, both the input vector and the output vector have 2 components - in other words, the transformation takes a 2-dimensional vector and produces a new 2-dimensional vector; which we can indicate like this:\n\n$$ T: \\rm I\\!R^{2} \\to \\rm I\\!R^{2} $$\n\nNote that the output vector may have a different number of dimensions from the input vector; so the matrix function might transform the vector from one space to another - or in notation, ${\\rm I\\!R}$n -> ${\\rm I\\!R}$m.\n\nFor example, let's redefine matrix ***A***, while retaining our original definition of vector ***v***:\n\n$$ A = \\begin{bmatrix}2 & 3\\\\5 & 2\\\\1 & 1\\end{bmatrix} \\;\\;\\;\\; \\vec{v} = \\begin{bmatrix}1\\\\2\\end{bmatrix}$$\n\nNow if we once again define ***T*** like this:\n\n$$ T(\\vec{v}) = A\\vec{v} $$\n\nWe apply the transformation like this:\n\n$$\\begin{bmatrix}2 & 3\\\\5 & 2\\\\1 & 1\\end{bmatrix} \\cdot \\begin{bmatrix}1\\\\2\\end{bmatrix} = \\begin{bmatrix}8\\\\9\\\\3\\end{bmatrix}$$\n\nSo now, our transformation transforms the vector from 2-dimensional space to 3-dimensional space:\n\n$$ T: \\rm I\\!R^{2} \\to \\rm I\\!R^{3} $$\n\nHere it is in Python:\n\n\n```python\nimport numpy as np\nv = np.array([1,2])\nA = np.array([[2,3],\n [5,2],\n [1,1]])\n\nt = A@v\nprint (t)\n```\n\n [8 9 3]\n\n\n\n```python\nimport numpy as np\nv = np.array([1,2])\nA = np.array([[1,2],\n [2,1]])\n\nt = A@v\nprint (t)\n```\n\n [5 4]\n\n\n## Transformations of Magnitude and Amplitude\n\nWhen you multiply a vector by a matrix, you transform it in at least one of the following two ways:\n* Scale the length (*magnitude*) of the matrix to make it longer or shorter\n* Change the direction (*amplitude*) of the matrix\n\nFor example consider the following matrix and vector:\n\n$$ A = \\begin{bmatrix}2 & 0\\\\0 & 2\\end{bmatrix} \\;\\;\\;\\; \\vec{v} = \\begin{bmatrix}1\\\\0\\end{bmatrix}$$\n\nAs before, we transform the vector ***v*** by multiplying it with the matrix ***A***:\n\n\\begin{equation}\\begin{bmatrix}2 & 0\\\\0 & 2\\end{bmatrix} \\cdot \\begin{bmatrix}1\\\\0\\end{bmatrix} = \\begin{bmatrix}2\\\\0\\end{bmatrix}\\end{equation}\n\nIn this case, the resulting vector has changed in length (*magnitude*), but has not changed its direction (*amplitude*).\n\nLet's visualize that in Python:\n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\nv = np.array([1,0])\nA = np.array([[2,0],\n [0,2]])\n\nt = A@v\nprint (t)\n\n# Plot v and t\nvecs = np.array([t,v])\norigin = [0], [0]\nplt.axis('equal')\nplt.grid()\nplt.ticklabel_format(style='sci', axis='both', scilimits=(0,0))\nplt.quiver(*origin, vecs[:,0], vecs[:,1], color=['blue', 'orange'], scale=10)\nplt.show()\n```\n\nThe original vector ***v*** is shown in orange, and the transformed vector ***t*** is shown in blue - note that ***t*** has the same direction (*amplitude*) as ***v*** but a greater length (*magnitude*).\n\nNow let's use a different matrix to transform the vector ***v***:\n\\begin{equation}\\begin{bmatrix}0 & -1\\\\1 & 0\\end{bmatrix} \\cdot \\begin{bmatrix}1\\\\0\\end{bmatrix} = \\begin{bmatrix}0\\\\1\\end{bmatrix}\\end{equation}\n\nThis time, the resulting vector has been changed to a different amplitude, but has the same magnitude.\n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\nv = np.array([1,0])\nA = np.array([[0,-1],\n [1,0]])\n\nt = A@v\nprint (t)\n\n# Plot v and t\nvecs = np.array([v,t])\norigin = [0], [0]\nplt.axis('equal')\nplt.grid()\nplt.ticklabel_format(style='sci', axis='both', scilimits=(0,0))\nplt.quiver(*origin, vecs[:,0], vecs[:,1], color=['orange', 'blue'], scale=10)\nplt.show()\n```\n\nNow let's see change the matrix one more time:\n\\begin{equation}\\begin{bmatrix}2 & 1\\\\1 & 2\\end{bmatrix} \\cdot \\begin{bmatrix}1\\\\0\\end{bmatrix} = \\begin{bmatrix}2\\\\1\\end{bmatrix}\\end{equation}\n\nNow our resulting vector has been transformed to a new amplitude *and* magnitude - the transformation has affected both direction and scale.\n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\nv = np.array([1,0])\nA = np.array([[2,1],\n [1,2]])\n\nt = A@v\nprint (t)\n\n# Plot v and t\nvecs = np.array([v,t])\norigin = [0], [0]\nplt.axis('equal')\nplt.grid()\nplt.ticklabel_format(style='sci', axis='both', scilimits=(0,0))\nplt.quiver(*origin, vecs[:,0], vecs[:,1], color=['orange', 'blue'], scale=10)\nplt.show()\n```\n\n### Afine Transformations\nAn Afine transformation multiplies a vector by a matrix and adds an offset vector, sometimes referred to as *bias*; like this:\n\n$$T(\\vec{v}) = A\\vec{v} + \\vec{b}$$\n\nFor example:\n\n\\begin{equation}\\begin{bmatrix}5 & 2\\\\3 & 1\\end{bmatrix} \\cdot \\begin{bmatrix}1\\\\1\\end{bmatrix} + \\begin{bmatrix}-2\\\\-6\\end{bmatrix} = \\begin{bmatrix}5\\\\-2\\end{bmatrix}\\end{equation}\n\nThis kind of transformation is actually the basis of linear regression, which is a core foundation for machine learning. The matrix defines the *features*, the first vector is the *coefficients*, and the bias vector is the *intercept*.\n\nhere's an example of an Afine transformation in Python:\n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\nv = np.array([1,1])\nA = np.array([[5,2],\n [3,1]])\nb = np.array([-2,-6])\n\nt = A@v + b\nprint (t)\n\n# Plot v and t\nvecs = np.array([v,t])\norigin = [0], [0]\nplt.axis('equal')\nplt.grid()\nplt.ticklabel_format(style='sci', axis='both', scilimits=(0,0))\nplt.quiver(*origin, vecs[:,0], vecs[:,1], color=['orange', 'blue'], scale=15)\nplt.show()\n```\n\n## Eigenvectors and Eigenvalues\nSo we can see that when you transform a vector using a matrix, we change its direction, length, or both. When the transformation only affects scale (in other words, the output vector has a different magnitude but the same amplitude as the input vector), the matrix multiplication for the transformation is the equivalent operation as some scalar multiplication of the vector.\n\nFor example, earlier we examined the following transformation that dot-mulitplies a vector by a matrix:\n\n$$\\begin{bmatrix}2 & 0\\\\0 & 2\\end{bmatrix} \\cdot \\begin{bmatrix}1\\\\0\\end{bmatrix} = \\begin{bmatrix}2\\\\0\\end{bmatrix}$$\n\nYou can achieve the same result by mulitplying the vector by the scalar value ***2***:\n\n$$2 \\times \\begin{bmatrix}1\\\\0\\end{bmatrix} = \\begin{bmatrix}2\\\\0\\end{bmatrix}$$\n\nThe following python performs both of these calculation and shows the results, which are identical.\n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\nv = np.array([1,0])\nA = np.array([[2,0],\n [0,2]])\n\nt1 = A@v\nprint (t1)\nt2 = 2*v\nprint (t2)\n\nfig = plt.figure()\na=fig.add_subplot(1,1,1)\n# Plot v and t1\nvecs = np.array([t1,v])\norigin = [0], [0]\nplt.axis('equal')\nplt.grid()\nplt.ticklabel_format(style='sci', axis='both', scilimits=(0,0))\nplt.quiver(*origin, vecs[:,0], vecs[:,1], color=['blue', 'orange'], scale=10)\nplt.show()\na=fig.add_subplot(1,2,1)\n# Plot v and t2\nvecs = np.array([t2,v])\norigin = [0], [0]\nplt.axis('equal')\nplt.grid()\nplt.ticklabel_format(style='sci', axis='both', scilimits=(0,0))\nplt.quiver(*origin, vecs[:,0], vecs[:,1], color=['blue', 'orange'], scale=10)\nplt.show()\n```\n\nIn cases like these, where a matrix transformation is the equivelent of a scalar-vector multiplication, the scalar-vector pairs that correspond to the matrix are known respectively as eigenvalues and eigenvectors. We generally indicate eigenvalues using the Greek letter lambda (λ), and the formula that defines eigenvalues and eigenvectors with respect to a transformation is:\n\n$$ T(\\vec{v}) = \\lambda\\vec{v}$$\n\nWhere the vector ***v*** is an eigenvector and the value ***λ*** is an eigenvalue for transformation ***T***.\n\nWhen the transformation ***T*** is represented as a matrix multiplication, as in this case where the transformation is represented by matrix ***A***:\n\n$$ T(\\vec{v}) = A\\vec{v} = \\lambda\\vec{v}$$\n\nThen ***v*** is an eigenvector and ***λ*** is an eigenvalue of ***A***.\n\nA matrix can have multiple eigenvector-eigenvalue pairs, and you can calculate them manually. However, it's generally easier to use a tool or programming language. For example, in Python you can use the ***linalg.eig*** function, which returns an array of eigenvalues and a matrix of the corresponding eigenvectors for the specified matrix.\n\nHere's an example that returns the eigenvalue and eigenvector pairs for the following matrix:\n\n$$A=\\begin{bmatrix}2 & 0\\\\0 & 3\\end{bmatrix}$$\n\n\n```python\nimport numpy as np\nA = np.array([[2,0],\n [0,3]])\neVals, eVecs = np.linalg.eig(A)\nprint(eVals)\nprint(eVecs)\n```\n\n [2. 3.]\n [[1. 0.]\n [0. 1.]]\n\n\nSo there are two eigenvalue-eigenvector pairs for this matrix, as shown here:\n\n$$ \\lambda_{1} = 2, \\vec{v_{1}} = \\begin{bmatrix}1 \\\\ 0\\end{bmatrix} \\;\\;\\;\\;\\;\\; \\lambda_{2} = 3, \\vec{v_{2}} = \\begin{bmatrix}0 \\\\ 1\\end{bmatrix} $$\n\nLet's verify that multiplying each eigenvalue-eigenvector pair corresponds to the dot-product of the eigenvector and the matrix. Here's the first pair:\n\n$$ 2 \\times \\begin{bmatrix}1 \\\\ 0\\end{bmatrix} = \\begin{bmatrix}2 \\\\ 0\\end{bmatrix} \\;\\;\\;and\\;\\;\\; \\begin{bmatrix}2 & 0\\\\0 & 3\\end{bmatrix} \\cdot \\begin{bmatrix}1 \\\\ 0\\end{bmatrix} = \\begin{bmatrix}2 \\\\ 0\\end{bmatrix} $$\n\nSo far so good. Now let's check the second pair:\n\n$$ 3 \\times \\begin{bmatrix}0 \\\\ 1\\end{bmatrix} = \\begin{bmatrix}0 \\\\ 3\\end{bmatrix} \\;\\;\\;and\\;\\;\\; \\begin{bmatrix}2 & 0\\\\0 & 3\\end{bmatrix} \\cdot \\begin{bmatrix}0 \\\\ 1\\end{bmatrix} = \\begin{bmatrix}0 \\\\ 3\\end{bmatrix} $$\n\nSo our eigenvalue-eigenvector scalar multiplications do indeed correspond to our matrix-eigenvector dot-product transformations.\n\nHere's the equivalent code in Python, using the ***eVals*** and ***eVecs*** variables you generated in the previous code cell:\n\n\n```python\nvec1 = eVecs[:,0]\nlam1 = eVals[0]\n\nprint('Matrix A:')\nprint(A)\nprint('-------')\n\nprint('lam1: ' + str(lam1))\nprint ('v1: ' + str(vec1))\nprint ('Av1: ' + str(A@vec1))\nprint ('lam1 x v1: ' + str(lam1*vec1))\n\nprint('-------')\n\nvec2 = eVecs[:,1]\nlam2 = eVals[1]\n\nprint('lam2: ' + str(lam2))\nprint ('v2: ' + str(vec2))\nprint ('Av2: ' + str(A@vec2))\nprint ('lam2 x v2: ' + str(lam2*vec2))\n```\n\n Matrix A:\n [[2 0]\n [0 3]]\n -------\n lam1: 2.0\n v1: [1. 0.]\n Av1: [2. 0.]\n lam1 x v1: [2. 0.]\n -------\n lam2: 3.0\n v2: [0. 1.]\n Av2: [0. 3.]\n lam2 x v2: [0. 3.]\n\n\nYou can use the following code to visualize these transformations:\n\n\n```python\nt1 = lam1*vec1\nprint (t1)\nt2 = lam2*vec2\nprint (t2)\n\nfig = plt.figure()\na=fig.add_subplot(1,1,1)\n# Plot v and t1\nvecs = np.array([t1,vec1])\norigin = [0], [0]\nplt.axis('equal')\nplt.grid()\nplt.ticklabel_format(style='sci', axis='both', scilimits=(0,0))\nplt.quiver(*origin, vecs[:,0], vecs[:,1], color=['blue', 'orange'], scale=10)\nplt.show()\na=fig.add_subplot(1,2,1)\n# Plot v and t2\nvecs = np.array([t2,vec2])\norigin = [0], [0]\nplt.axis('equal')\nplt.grid()\nplt.ticklabel_format(style='sci', axis='both', scilimits=(0,0))\nplt.quiver(*origin, vecs[:,0], vecs[:,1], color=['blue', 'orange'], scale=10)\nplt.show()\n```\n\nSimilarly, earlier we examined the following matrix transformation:\n\n$$\\begin{bmatrix}2 & 0\\\\0 & 2\\end{bmatrix} \\cdot \\begin{bmatrix}1\\\\0\\end{bmatrix} = \\begin{bmatrix}2\\\\0\\end{bmatrix}$$\n\nAnd we saw that you can achieve the same result by mulitplying the vector by the scalar value ***2***:\n\n$$2 \\times \\begin{bmatrix}1\\\\0\\end{bmatrix} = \\begin{bmatrix}2\\\\0\\end{bmatrix}$$\n\nThis works because the scalar value 2 and the vector (1,0) are an eigenvalue-eigenvector pair for this matrix.\n\nLet's use Python to determine the eigenvalue-eigenvector pairs for this matrix:\n\n\n```python\nimport numpy as np\nA = np.array([[2,0],\n [0,2]])\neVals, eVecs = np.linalg.eig(A)\nprint(eVals)\nprint(eVecs)\n```\n\n [2. 2.]\n [[1. 0.]\n [0. 1.]]\n\n\nSo once again, there are two eigenvalue-eigenvector pairs for this matrix, as shown here:\n\n$$ \\lambda_{1} = 2, \\vec{v_{1}} = \\begin{bmatrix}1 \\\\ 0\\end{bmatrix} \\;\\;\\;\\;\\;\\; \\lambda_{2} = 2, \\vec{v_{2}} = \\begin{bmatrix}0 \\\\ 1\\end{bmatrix} $$\n\nLet's verify that multiplying each eigenvalue-eigenvector pair corresponds to the dot-product of the eigenvector and the matrix. Here's the first pair:\n\n$$ 2 \\times \\begin{bmatrix}1 \\\\ 0\\end{bmatrix} = \\begin{bmatrix}2 \\\\ 0\\end{bmatrix} \\;\\;\\;and\\;\\;\\; \\begin{bmatrix}2 & 0\\\\0 & 2\\end{bmatrix} \\cdot \\begin{bmatrix}1 \\\\ 0\\end{bmatrix} = \\begin{bmatrix}2 \\\\ 0\\end{bmatrix} $$\n\nWell, we already knew that. Now let's check the second pair:\n\n$$ 2 \\times \\begin{bmatrix}0 \\\\ 1\\end{bmatrix} = \\begin{bmatrix}0 \\\\ 2\\end{bmatrix} \\;\\;\\;and\\;\\;\\; \\begin{bmatrix}2 & 0\\\\0 & 2\\end{bmatrix} \\cdot \\begin{bmatrix}0 \\\\ 1\\end{bmatrix} = \\begin{bmatrix}0 \\\\ 2\\end{bmatrix} $$\n\nNow let's use Pythonto verify and plot these transformations:\n\n\n```python\nvec1 = eVecs[:,0]\nlam1 = eVals[0]\n\nprint('Matrix A:')\nprint(A)\nprint('-------')\n\nprint('lam1: ' + str(lam1))\nprint ('v1: ' + str(vec1))\nprint ('Av1: ' + str(A@vec1))\nprint ('lam1 x v1: ' + str(lam1*vec1))\n\nprint('-------')\n\nvec2 = eVecs[:,1]\nlam2 = eVals[1]\n\nprint('lam2: ' + str(lam2))\nprint ('v2: ' + str(vec2))\nprint ('Av2: ' + str(A@vec2))\nprint ('lam2 x v2: ' + str(lam2*vec2))\n\n\n# Plot the resulting vectors\nt1 = lam1*vec1\nt2 = lam2*vec2\n\nfig = plt.figure()\na=fig.add_subplot(1,1,1)\n# Plot v and t1\nvecs = np.array([t1,vec1])\norigin = [0], [0]\nplt.axis('equal')\nplt.grid()\nplt.ticklabel_format(style='sci', axis='both', scilimits=(0,0))\nplt.quiver(*origin, vecs[:,0], vecs[:,1], color=['blue', 'orange'], scale=10)\nplt.show()\na=fig.add_subplot(1,2,1)\n# Plot v and t2\nvecs = np.array([t2,vec2])\norigin = [0], [0]\nplt.axis('equal')\nplt.grid()\nplt.ticklabel_format(style='sci', axis='both', scilimits=(0,0))\nplt.quiver(*origin, vecs[:,0], vecs[:,1], color=['blue', 'orange'], scale=10)\nplt.show()\n```\n\nLet's take a look at one more, slightly more complex example. Here's our matrix:\n\n$$\\begin{bmatrix}2 & 1\\\\1 & 2\\end{bmatrix}$$\n\nLet's get the eigenvalue and eigenvector pairs:\n\n\n```python\nimport numpy as np\n\nA = np.array([[2,1],\n [1,2]])\n\neVals, eVecs = np.linalg.eig(A)\nprint(eVals)\nprint(eVecs)\n```\n\n [3. 1.]\n [[ 0.70710678 -0.70710678]\n [ 0.70710678 0.70710678]]\n\n\nThis time the eigenvalue-eigenvector pairs are:\n\n$$ \\lambda_{1} = 3, \\vec{v_{1}} = \\begin{bmatrix}0.70710678 \\\\ 0.70710678\\end{bmatrix} \\;\\;\\;\\;\\;\\; \\lambda_{2} = 1, \\vec{v_{2}} = \\begin{bmatrix}-0.70710678 \\\\ 0.70710678\\end{bmatrix} $$\n\nSo let's check the first pair:\n\n$$ 3 \\times \\begin{bmatrix}0.70710678 \\\\ 0.70710678\\end{bmatrix} = \\begin{bmatrix}2.12132034 \\\\ 2.12132034\\end{bmatrix} \\;\\;\\;and\\;\\;\\; \\begin{bmatrix}2 & 1\\\\0 & 2\\end{bmatrix} \\cdot \\begin{bmatrix}0.70710678 \\\\ 0.70710678\\end{bmatrix} = \\begin{bmatrix}2.12132034 \\\\ 2.12132034\\end{bmatrix} $$\n\nNow let's check the second pair:\n\n$$ 1 \\times \\begin{bmatrix}-0.70710678 \\\\ 0.70710678\\end{bmatrix} = \\begin{bmatrix}-0.70710678\\\\0.70710678\\end{bmatrix} \\;\\;\\;and\\;\\;\\; \\begin{bmatrix}2 & 1\\\\1 & 2\\end{bmatrix} \\cdot \\begin{bmatrix}-0.70710678 \\\\ 0.70710678\\end{bmatrix} = \\begin{bmatrix}-0.70710678\\\\0.70710678\\end{bmatrix} $$\n\nWith more complex examples like this, it's generally easier to do it with Python:\n\n\n```python\nvec1 = eVecs[:,0]\nlam1 = eVals[0]\n\nprint('Matrix A:')\nprint(A)\nprint('-------')\n\nprint('lam1: ' + str(lam1))\nprint ('v1: ' + str(vec1))\nprint ('Av1: ' + str(A@vec1))\nprint ('lam1 x v1: ' + str(lam1*vec1))\n\nprint('-------')\n\nvec2 = eVecs[:,1]\nlam2 = eVals[1]\n\nprint('lam2: ' + str(lam2))\nprint ('v2: ' + str(vec2))\nprint ('Av2: ' + str(A@vec2))\nprint ('lam2 x v2: ' + str(lam2*vec2))\n\n\n# Plot the results\nt1 = lam1*vec1\nt2 = lam2*vec2\n\nfig = plt.figure()\na=fig.add_subplot(1,1,1)\n# Plot v and t1\nvecs = np.array([t1,vec1])\norigin = [0], [0]\nplt.axis('equal')\nplt.grid()\nplt.ticklabel_format(style='sci', axis='both', scilimits=(0,0))\nplt.quiver(*origin, vecs[:,0], vecs[:,1], color=['blue', 'orange'], scale=10)\nplt.show()\na=fig.add_subplot(1,2,1)\n# Plot v and t2\nvecs = np.array([t2,vec2])\norigin = [0], [0]\nplt.axis('equal')\nplt.grid()\nplt.ticklabel_format(style='sci', axis='both', scilimits=(0,0))\nplt.quiver(*origin, vecs[:,0], vecs[:,1], color=['blue', 'orange'], scale=10)\nplt.show()\n```\n\n## Eigendecomposition\nSo we've learned a little about eigenvalues and eigenvectors; but you may be wondering what use they are. Well, one use for them is to help decompose transformation matrices.\n\nRecall that previously we found that a matrix transformation of a vector changes its magnitude, amplitude, or both. Without getting too technical about it, we need to remember that vectors can exist in any spatial orientation, or *basis*; and the same transformation can be applied in different *bases*.\n\nWe can decompose a matrix using the following formula:\n\n$$A = Q \\Lambda Q^{-1}$$\n\nWhere ***A*** is a trasformation that can be applied to a vector in its current base, ***Q*** is a matrix of eigenvectors that defines a change of basis, and ***Λ*** is a matrix with eigenvalues on the diagonal that defines the same linear transformation as ***A*** in the base defined by ***Q***.\n\nLet's look at these in some more detail. Consider this matrix:\n\n$$A=\\begin{bmatrix}3 & 2\\\\1 & 0\\end{bmatrix}$$\n\n***Q*** is a matrix in which each column is an eigenvector of ***A***; which as we've seen previously, we can calculate using Python:\n\n\n```python\nimport numpy as np\n\nA = np.array([[3,2],\n [1,0]])\n\nl, Q = np.linalg.eig(A)\nprint(Q)\n```\n\n [[ 0.96276969 -0.48963374]\n [ 0.27032301 0.87192821]]\n\n\nSo for matrix ***A***, ***Q*** is the following matrix:\n\n$$Q=\\begin{bmatrix}0.96276969 & -0.48963374\\\\0.27032301 & 0.87192821\\end{bmatrix}$$\n\n***Λ*** is a matrix that contains the eigenvalues for ***A*** on the diagonal, with zeros in all other elements; so for a 2x2 matrix, Λ will look like this:\n\n$$\\Lambda=\\begin{bmatrix}\\lambda_{1} & 0\\\\0 & \\lambda_{2}\\end{bmatrix}$$\n\nIn our Python code, we've already used the ***linalg.eig*** function to return the array of eigenvalues for ***A*** into the variable ***l***, so now we just need to format that as a matrix:\n\n\n```python\nL = np.diag(l)\nprint (L)\n```\n\n [[ 3.56155281 0. ]\n [ 0. -0.56155281]]\n\n\nSo ***Λ*** is the following matrix:\n\n$$\\Lambda=\\begin{bmatrix}3.56155281 & 0\\\\0 & -0.56155281\\end{bmatrix}$$\n\nNow we just need to find ***Q-1***, which is the inverse of ***Q***:\n\n\n```python\nQinv = np.linalg.inv(Q)\nprint(Qinv)\n```\n\n [[ 0.89720673 0.50382896]\n [-0.27816009 0.99068183]]\n\n\nThe inverse of ***Q*** then, is:\n\n$$Q^{-1}=\\begin{bmatrix}0.89720673 & 0.50382896\\\\-0.27816009 & 0.99068183\\end{bmatrix}$$\n\nSo what does that mean? Well, it means that we can decompose the transformation of *any* vector multiplied by matrix ***A*** into the separate operations ***QΛQ-1***:\n\n$$A\\vec{v} = Q \\Lambda Q^{-1}\\vec{v}$$\n\nTo prove this, let's take vector ***v***:\n\n$$\\vec{v} = \\begin{bmatrix}1\\\\3\\end{bmatrix} $$\n\nOur matrix transformation using ***A*** is:\n\n$$\\begin{bmatrix}3 & 2\\\\1 & 0\\end{bmatrix} \\cdot \\begin{bmatrix}1\\\\3\\end{bmatrix} $$\n\nSo let's show the results of that using Python:\n\n\n```python\nv = np.array([1,3])\nt = A@v\n\nprint(t)\n\n# Plot v and t\nvecs = np.array([v,t])\norigin = [0], [0]\nplt.axis('equal')\nplt.grid()\nplt.ticklabel_format(style='sci', axis='both', scilimits=(0,0))\nplt.quiver(*origin, vecs[:,0], vecs[:,1], color=['orange', 'b'], scale=20)\nplt.show()\n```\n\nAnd now, let's do the same thing using the ***QΛQ-1*** sequence of operations:\n\n\n```python\nimport math\nimport numpy as np\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\nt = (Q@(L@(Qinv)))@v\n\n# Plot v and t\nvecs = np.array([v,t])\norigin = [0], [0]\nplt.axis('equal')\nplt.grid()\nplt.ticklabel_format(style='sci', axis='both', scilimits=(0,0))\nplt.quiver(*origin, vecs[:,0], vecs[:,1], color=['orange', 'b'], scale=20)\nplt.show()\n```\n\nSo ***A*** and ***QΛQ-1*** are equivalent.\n\nIf we view the intermediary stages of the decomposed transformation, you can see the transformation using ***A*** in the original base for ***v*** (orange to blue) and the transformation using ***Λ*** in the change of basis decribed by ***Q*** (red to magenta):\n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\nt1 = Qinv@v\nt2 = L@t1\nt3 = Q@t2\n\n# Plot the transformations\nvecs = np.array([v,t1, t2, t3])\norigin = [0], [0]\nplt.axis('equal')\nplt.grid()\nplt.ticklabel_format(style='sci', axis='both', scilimits=(0,0))\nplt.quiver(*origin, vecs[:,0], vecs[:,1], color=['orange', 'red', 'magenta', 'blue'], scale=20)\nplt.show()\n```\n\nSo from this visualization, it should be apparent that the transformation ***Av*** can be performed by changing the basis for ***v*** using ***Q*** (from orange to red in the above plot) applying the equivalent linear transformation in that base using ***Λ*** (red to magenta), and switching back to the original base using ***Q-1*** (magenta to blue).\n\n## Rank of a Matrix\n\nThe **rank** of a square matrix is the number of non-zero eigenvalues of the matrix. A **full rank** matrix has the same number of non-zero eigenvalues as the dimension of the matrix. A **rank-deficient** matrix has fewer non-zero eigenvalues as dimensions. The inverse of a rank deficient matrix is singular and so does not exist (this is why in a previous notebook we noted that some matrices have no inverse).\n\nConsider the following matrix ***A***:\n\n$$A=\\begin{bmatrix}1 & 2\\\\4 & 3\\end{bmatrix}$$\n\nLet's find its eigenvalues (***Λ***):\n\n\n```python\nimport numpy as np\nA = np.array([[1,2],\n [4,3]])\nl, Q = np.linalg.eig(A)\nL = np.diag(l)\nprint(L)\n```\n\n [[-1. 0.]\n [ 0. 5.]]\n\n\n$$\\Lambda=\\begin{bmatrix}-1 & 0\\\\0 & 5\\end{bmatrix}$$\n\nThis matrix has full rank. The dimensions of the matrix is 2. There are two non-zero eigenvalues. \n\nNow consider this matrix:\n\n$$B=\\begin{bmatrix}3 & -3 & 6\\\\2 & -2 & 4\\\\1 & -1 & 2\\end{bmatrix}$$\n\nNote that the second and third columns are just scalar multiples of the first column.\n\nLet's examine it's eigenvalues:\n\n\n```python\nB = np.array([[3,-3,6],\n [2,-2,4],\n [1,-1,2]])\nlb, Qb = np.linalg.eig(B)\nLb = np.diag(lb)\nprint(Lb)\n```\n\n [[3.00000000e+00 0.00000000e+00 0.00000000e+00]\n [0.00000000e+00 5.23364153e-16 0.00000000e+00]\n [0.00000000e+00 0.00000000e+00 0.00000000e+00]]\n\n\n$$\\Lambda=\\begin{bmatrix}3 & 0& 0\\\\0 & -6\\times10^{-17} & 0\\\\0 & 0 & 3.6\\times10^{-16}\\end{bmatrix}$$\n\nNote that matrix has only 1 non-zero eigenvalue. The other two eigenvalues are so extremely small as to be effectively zero. This is an example of a rank-deficient matrix; and as such, it has no inverse.\n\n## Inverse of a Square Full Rank Matrix\nYou can calculate the inverse of a square full rank matrix by using the following formula:\n\n$$A^{-1} = Q \\Lambda^{-1} Q^{-1}$$\n\nLet's apply this to matrix ***A***:\n\n$$A=\\begin{bmatrix}1 & 2\\\\4 & 3\\end{bmatrix}$$\n\nLet's find the matrices for ***Q***, ***Λ-1***, and ***Q-1***:\n\n\n```python\nimport numpy as np\nA = np.array([[1,2],\n [4,3]])\n\nl, Q = np.linalg.eig(A)\nL = np.diag(l)\nprint(Q)\nLinv = np.linalg.inv(L)\nQinv = np.linalg.inv(Q)\nprint(Linv)\nprint(Qinv)\n```\n\n [[-0.70710678 -0.4472136 ]\n [ 0.70710678 -0.89442719]]\n [[-1. -0. ]\n [ 0. 0.2]]\n [[-0.94280904 0.47140452]\n [-0.74535599 -0.74535599]]\n\n\nSo:\n\n$$A^{-1}=\\begin{bmatrix}-0.70710678 & -0.4472136\\\\0.70710678 & -0.89442719\\end{bmatrix}\\cdot\\begin{bmatrix}-1 & -0\\\\0 & 0.2\\end{bmatrix}\\cdot\\begin{bmatrix}-0.94280904 & 0.47140452\\\\-0.74535599 & -0.74535599\\end{bmatrix}$$\n\nLet's calculate that in Python:\n\n\n```python\nAinv = (Q@(Linv@(Qinv)))\nprint(Ainv)\n```\n\n [[-0.6 0.4]\n [ 0.8 -0.2]]\n\n\nThat gives us the result:\n\n$$A^{-1}=\\begin{bmatrix}-0.6 & 0.4\\\\0.8 & -0.2\\end{bmatrix}$$\n\nWe can apply the ***np.linalg.inv*** function directly to ***A*** to verify this:\n\n\n```python\nprint(np.linalg.inv(A))\n```\n\n [[-0.6 0.4]\n [ 0.8 -0.2]]\n\n", "meta": {"hexsha": "51d1e92a003aa9e19baeaf49a30c353be110ccf9", "size": 137783, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Essential_Math_for_Machine_Learning_Python_Edition/Module03/03-05-Transformations Eigenvectors and Eigenvalues.ipynb", "max_stars_repo_name": "chandlersong/pythonMath", "max_stars_repo_head_hexsha": "f267f14b954327bea61485fe37590fefc0d45e65", "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": "Essential_Math_for_Machine_Learning_Python_Edition/Module03/03-05-Transformations Eigenvectors and Eigenvalues.ipynb", "max_issues_repo_name": "chandlersong/pythonMath", "max_issues_repo_head_hexsha": "f267f14b954327bea61485fe37590fefc0d45e65", "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": "Essential_Math_for_Machine_Learning_Python_Edition/Module03/03-05-Transformations Eigenvectors and Eigenvalues.ipynb", "max_forks_repo_name": "chandlersong/pythonMath", "max_forks_repo_head_hexsha": "f267f14b954327bea61485fe37590fefc0d45e65", "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": 94.0498293515, "max_line_length": 8716, "alphanum_fraction": 0.8277000791, "converted": true, "num_tokens": 8378, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9697854138058637, "lm_q2_score": 0.9099070084811306, "lm_q1q2_score": 0.8824145447447288}} {"text": "Yule Process: \n\nIt's a pure-birth process which is a Poisson process for simulation of the population at time $t$, $X(t)$.\n\nIt's a continuous-time Markov chain with transition probabilities:\n\n\\begin{equation}\n\\begin{split}\n&P(X(t+\\Delta t)=n+1 | X(t)=n)= \\nu_n\\,\\Delta t\\\\\n&P(X(t+\\Delta t)=n | X(t)=n)= 1-\\nu_n\\,\\Delta t\n\\end{split}\n\\end{equation}\n\nWe call $\\nu_n$ as the rate of the change at state $n$. For a special case we have $\\nu_n= b\\,n^{d}$ for some parameter $b$. If $d=1$,\nthen we have the linear growth. It can be proved that if $\\Sigma\\, 1/\\nu_n < \\infty$, then the population size explodes in a finte time; in other words, we will have infintely many jumps in a finte time. Therefore for the special case where, $\\nu_n= b\\,n^{d}$, we have an explosive Markov chain if $d>1$.\n\nSimulation of Yule process can be done using two different techniques: Sampling of time increments and tau-leaping method. In the the first method, we use the fact that waiting time (sojurn time) until the next jump in the population, when the current population is $n$, is exponentially distributed with mean $1/\\nu_{n}$ and hence we can sample the time incerements from these exponential distributions. \n\nIn the following cells, I have simulated one special case of Yule process, where $\\nu_n= b\\,n^{d}$ with inital population $X_{0}=1$. I have simulated until a max population $N=2000$ and with 3 different degrees, $d$, for the rate of the change to show the explosive Markov chains for $d>1$.\n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.offsetbox import AnchoredText\nimport scipy.misc\nimport scipy.special\nfrom matplotlib.lines import Line2D \nimport seaborn as sns\nfrom cycler import cycler\n\nplt.style.use('ggplot')\n \ndef incremental_sampling(b, N, P0, d, num_sim):\n \n \"\"\"\n b -- birth_rate\n N -- max population \n P0 -- initial population \n num_sim -- number of simulations\n d -- degree of population growth. \n \"\"\" \n s = np.zeros((num_sim, N)) # Sojurn times\n X1 = np.zeros((num_sim, N)) # Population matrix\n inc = np.zeros((num_sim, N)) # Time increments\n X1[:,0] = P0\n\n for j in range(num_sim):\n for i in range(N-1):\n U = np.random.uniform(0,1)\n h = - np.log(U)/(b*X1[j,i]**d) # Time incerements\n inc[j,i] = h\n s[j,i+1] = s[j,i] + h\n X1[j,i+1] = X1[j,i] + 1 \n \n return [s, X1, inc]\n \n \ndef plots(b, N, P0, deg, num_sim):\n \n fig, ax = plt.subplots(2,3,figsize=(12,8))\n marker_style = dict(linestyle=':',marker='o', markersize=4) \n col = ['cornflowerblue', 'orchid', 'orange']\n \n for i, d in enumerate(deg):\n \n [s, X1, inc] = incremental_sampling(b, N, P0, d, num_sim)\n \n ax[0,i].plot(s[0,:], X1[0,:], color=col[i], **marker_style)\n sns.distplot(inc, ax=ax[1,i], bins=np.linspace(0,0.1,100), kde=False)\n ax[0,i].set_title(r'$\\nu_n \\propto n^{%1.1f}$'%d)\n ax[1,i].set_title(r'distribution of increments: $\\nu_n\\propto n^{%1.1f}$'%d, fontsize=10)\n ax[0,0].set_ylabel('population size', fontsize=12)\n ax[0,1].set_xlabel('time', fontsize=12)\n ax[1,i].set_xlim([0,0.03])\n plt.suptitle('One realization by incremental sampling with different rates:\\n'\\\n ' explosion occurs in a finite time when the power of n exceeds 1', y=1.05) \n plt.tight_layout(h_pad=8,w_pad=2)\n \nb = 0.5\nN = 2000\nP0 = 1\ndeg = [1, 1.5, 2]\nnum_sim = 1\n\nplots(b, N, P0, deg, num_sim)\n```\n\nIn the second method, tau-leaping method, we update the population size using\n$$ X(t+\\tau)-X(t)=Poisson(b\\,\\tau).$$\nObviousely in this case we have jumps and the plot $X(t)$ vs $t$ becomes piecewise linear. To make the plot smoother, we can sample on a large number and then take the average. In the next cell, I have simulated the process by using this method and have compared the result with the exat mean or deterministic method, which is the soluation of \n\n$$ \\frac{d}{dt}E[X(t)] = b\\,E[X(t)^{d}].$$\n\nfor the next simulation, I have used the linear growth, $d=1$ and hence the excat mean is\n\n$$ E[X(t)] = X(0)\\,e^{b\\,t}.$$\n\nI have chosen $\\tau = 0.01$ and have tried $1000$ steps, therefore the max-time is $10$. Moreove similar to the pervious cell, I have used $b=0.5$.\n\n\n```python\ndef tau_leaping(b, tau, P0, num_steps, num_sim):\n \n \"\"\"\n b -- birth_rate\n num_steps -- number of steps\n P0 -- initial population \n num_sim -- number of simulations\n d -- degree of population growth. \n \"\"\"\n X2 = np.zeros((num_sim, num_steps)) # Population matrix\n X2[:,0] = P0\n\n for j in range(num_sim):\n for i in range(num_steps-1):\n r = np.random.poisson(lam = b*X2[j,i]*tau)\n X2[j,i+1] = X2[j,i] + r\n \n X2_aver = np.mean(X2, axis=0)\n \n return [X2, X2_aver] \n\n\ndef exact_mean(b, P0, t):\n \n y = P0*np.exp(b*t)\n return y \n\n \ndef tau_leaping_plots(b, tau, P0, num_steps, num_sim):\n \n fig, ax = plt.subplots(1,figsize=(10,4))\n \n col = ['cornflowerblue','orchid']\n \n [X2, X2_aver] = tau_leaping(b, tau, P0, num_steps, num_sim)\n t = np.linspace(0, tau*num_steps, num_steps)\n y = exact_mean(b, P0, t)\n ax.plot(t, X2_aver, color=col[0], label='tau_leaping')\n ax.plot(t, y, color=col[1], label='exact mean')\n ax.set_title('Comparison between tau-leaping simulations'\\\n ' and deterministic method for the linear growth', y=1.03) \n ax.text(2,100, r\"$\\nu_n = 0.5\\,n$\", style = 'italic' , fontsize=12)\n ax.legend(['mean from tau-leaping',' mean from deterministic method'])\n ax.set_xlabel('time',fontsize=12)\n ax.set_ylabel('population mean', fontsize=12) \n plt.tight_layout()\n \nb = 0.5\ntau = 0.01\nP0 = 1 \nnum_steps = 1000\nnum_sim = 1000\n \ntau_leaping_plots(b, tau, P0, num_steps, num_sim) \n```\n\n In the next cell, I have plotted kernel density estimation for $1000$ simulations of population size at time $10$.\n\n\n```python\ndef tau_leaping_hist(b, tau, P0, num_steps, num_sim):\n \n fig, ax = plt.subplots()\n \n [X2, X2_aver] = tau_leaping(b, tau, P0, num_steps, num_sim)\n sns.distplot(X2[:,num_steps-1], label='tau_leaping', color='orchid')\n ax.legend(['population size: one realization'])\n ax.text(600,0.004, r\"$\\nu_n=0.5\\,n$\", style = 'italic' , size=12)\n ax.text(600,0.0035, r\"$\\tau=0.01,\\,t =10$\", style = 'italic' , size=12)\n ax.set_xlabel('population size', fontsize=12)\n ax.set_ylabel('KDE', fontsize=12)\n plt.title(r'Kernel density estimation for population size at time'\\\n r' $t=10$', va='center', ha='center', y=1.03) \n \n \nb = 0.5\ntau = 0.01\nP0 = 1 \nnum_steps = 1000\nnum_sim = 1000\n\n\ntau_leaping_hist(b, tau, P0, num_steps, num_sim)\n```\n\nAnd different trajectories ( realizations ) for population size where $\\nu_{n}=0.5\\,n$.\n\n\n```python\n\ndef trajectories(b, tau, P0, num_steps, num_sim):\n \n fig, ax = plt.subplots(figsize=(6,5))\n col = ['cornflowerblue','orchid','orange','green']\n [X2, X2_aver] = tau_leaping(b, tau, P0, num_steps, num_sim)\n t = np.linspace(0, tau*num_steps, num_steps)\n \n for i in range(num_sim):\n \n ax.plot(t,X2[i,:], color=col[i])\n at = AnchoredText(r'$\\nu_n=0.5\\,n,\\,\\tau=0.01$', loc='upper left', frameon=True)\n ax.add_artist(at)\n ax.set_xlabel('time', fontsize=12)\n ax.set_ylabel('population size', fontsize=12)\n plt.title(r'Different trajectories for population size', va='center', ha='center', y=1.03) \n\n \nb = 0.5\ntau = 0.01\nP0 = 1 \nnum_steps = 1000\nnum_sim = 4\n\ntrajectories(b, tau, P0, num_steps, num_sim)\n```\n", "meta": {"hexsha": "192c2bb7f00b0eef80f8529c5a4e2507c855317f", "size": 167233, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Yule-Process.ipynb", "max_stars_repo_name": "mdaneshv/Stochastic-Simulations", "max_stars_repo_head_hexsha": "2c96b37f96bb2547cdeb9d74b1d9a067db002560", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-11-30T02:13:54.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-30T08:32:49.000Z", "max_issues_repo_path": "Yule-Process.ipynb", "max_issues_repo_name": "mdaneshv/Stochastic-Simulations", "max_issues_repo_head_hexsha": "2c96b37f96bb2547cdeb9d74b1d9a067db002560", "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": "Yule-Process.ipynb", "max_forks_repo_name": "mdaneshv/Stochastic-Simulations", "max_forks_repo_head_hexsha": "2c96b37f96bb2547cdeb9d74b1d9a067db002560", "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": 516.1512345679, "max_line_length": 57824, "alphanum_fraction": 0.9352161356, "converted": true, "num_tokens": 2401, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475715065793, "lm_q2_score": 0.9353465120943382, "lm_q1q2_score": 0.8823568607013432}} {"text": "# Introdução à Computação Simbólica com _sympy_\n\n## Motivação\n\nNeste ponto do curso, você já aprendeu a realizar operações matemáticas elementares com Python. Por exemplo, se lhe for dado o valor do raio $R$, você consegue facilmente computar a área $\\pi R^2$ de um círculo. Todavia, o valor de $\\pi$ que você obtém é finito. As instruções abaixo verificam isto. \n\n```python\nfrom math import pi\nprint(pi)\n3.141592653589793\n```\n\nPense, no entanto, se você pudesse realizar o cálculo desta área de maneira \"exata\". Matematicamente falando, é impossível fazer isto pois $\\pi$ é um número irracional – o imbróglio desta constante é longo na história da Matemática. Porém, a computação simbólica permite que operemos com $\\pi$ como se fosse simplesmente um símbolo com precisão infinita. Embora 15 casas decimais, como o valor exemplificado acima, sejam suficientes para a maioria dos cálculos do mundo real, a computação simbólica permite que trabalhemos com modelos abstratos que servem a uma diversidade de propósitos. \n\nAliás, quando se diz que 3.141592653589793 é um valor razoavelmente aceitável, isto é verdade até mesmo para cálculos em escala astronômica. A equipe de engenharia da NASA explica que, usando este valor para calcular o perímetro de uma circunferência com diâmetro igual a 25 bilhões de milhas, o erro de cálculo é próximo de 1,5 polegada [[NASA]](https://www.jpl.nasa.gov/edu/news/2016/3/16/how-many-decimals-of-pi-do-we-really-need/). Até aí, nada mal para uma aproximação!\n\n## O que é Computação Simbólica e para que serve? \n\n*Computação Simbólica* (CS) é uma subárea de estudo da matemática e da ciência da computação que se preocupa em resolver problemas usando objetos simbólicos representáveis em um computador. Esses problemas surgem em muitas aplicações em ciências naturais, pesquisa básica, na indústria e principalmente no desenvolvimento de softwares para computação avançada denominados _sistemas de computação algébrica_ (SCAs). \n\nA CS existente em um SCA é aplicada em álgebra computacional, projetos assistidos por computação (CAD), raciocínio automatizado, gestão do conhecimento, lógica computacional e sistemas formais de verificação. O desenvolvimento da CS depende da integração de basicamente três campos: *softwares matemáticos*, *álgebra computacional* e *lógica computacional* [[RISC/JKU]](https://risc.jku.at/studying-symbolic-computation/). Em casos mais avançados, a CS é útil para solucionar equações da macroeconomia, manipular números para a finalidade de criptografia e criar modelos probabilísticos [[Kotzé]](https://kevinkotze.github.io/mm-tut1-symbolic/), [[Cohen]](https://www.ukma.edu.ua/~yubod/teach/compalgebra/%5BJoel_S._Cohen%5D_Computer_algebra_and_symbolic_comp(BookFi.org).pdf). \n\n## Principais SCAs \n\nAlguns SCAs são populares de longa data, tais como Maple, Mathematica e MuPad. Entretanto, são comerciais e costumam ter licenças custosas, embora ofereçam versões com desconto para estudantes. Algumas alternativas robustas de uso livre são Scilab, Sagemath, Octave e o próprio módulo *sympy*. Uma lista completa de SCAs está disponível na [[Wikipedia]](https://en.wikipedia.org/wiki/Computer_algebra_system).\n\n## Por que *sympy*? \n\nO objetivo principal do *sympy* é ser uma biblioteca de manipulação simbólica para Python. Ele começou a ser desenvolvido em 2006 e atualmente está na versão 1.5.1, lançada em dezembro de 2019 na página oficial [[sympy.org]](https://www.sympy.org/pt/index.html). As principais características do módulo são as seguintes: \n\n- é gratuito;\n\n- é baseado inteiramente em Python;\n\n- é leve e independente.\n\n## Objetos numéricos x objetos simbólicos\n\nImportaremos os módulos `math` e `sympy` para ver algumas diferenças entre objetos numéricos e simbólicos.\n\n\n```python\nimport math as mt\nimport sympy as sy\nsy.init_printing(pretty_print=True) # melhor impressão de símbolos\n```\n\n\n```python\nmt.pi # numérico\n```\n\n\n```python\nsy.pi # simbólico\n```\n\nVerifiquemos com `type`.\n\n\n```python\ntype(mt.pi)\n```\n\n\n\n\n float\n\n\n\n\n```python\ntype(sy.pi) # é um objeto simbólico\n```\n\n\n\n\n sympy.core.numbers.Pi\n\n\n\nVejamos mais um exemplo:\n\n\n```python\nmt.sqrt(2)\n```\n\n\n```python\nsy.sqrt(2)\n```\n\n\n```python\ntype(mt.sqrt(2))\n```\n\n\n\n\n float\n\n\n\n\n```python\ntype(sy.sqrt(2)) # é um objeto simbólico\n```\n\n\n\n\n sympy.core.power.Pow\n\n\n\n### Função x método \n\nNa aula anterior destacamos que `print` e `type` são \"funções\" similares àquelas do tipo $y = f(x)$ em Matemática. Em Python, essas \"funções\" recebem o nome de *função* mesmo.\n\nPorém, há módulos que possuem *métodos*, que para seu entendimento, podem ser vistos como \"funções\" também. Porém, *função* e *método* são conceitos levemenete distintos. \n\nPara aplicarmos funções usamos parênteses envolvendo um ou mais *parâmetros*. \n\nNo caso acima, `mt.sqrt(2)` mostra que `sqrt` age como uma função e o número 2 é seu único parâmetro. Note, além disso, que o sympy também possui a sua própria função `sqrt`, que é de uma natureza distinta. Ela é um objeto `sympy.core.power.Pow`. Não precisamos entender isso agora, mas basta saber que ela pertence a um submódulo do *sympy*.\n\nPor outro lado, também aprendemos que o conjugado de um número complexo `z` (tipo `complex`) pode ser obtido como `z.conjugate()`. Esta forma \"sem parâmetros\" indica que `conjugate` é um método do objeto `z`.\n\nA partir deste ponto, poderemos ver situações como as seguintes:\n\n- `f(x)`: a função `f` é aplicada ao parâmetro `x`\n\n- `a.f()`: `f` é um método sem parâmetro do objeto `a`\n\n- `a.f(x)`: `f` é um método com parâmetro `x` do objeto `a`\n\nA partir do último exemplo, podemos dizer que um método é, na verdade, uma função que pertence a um objeto.\n\n### Atribuições com símbolos\n\nPodemos atribuir símbolos a variáveis usando a função `symbols`.\n\n\n```python\nx = sy.symbols('x')\ny = sy.symbols('y')\n```\n\n`x` e `y` são símbolos sem valor definido.\n\n\n```python\nx\n```\n\n\n```python\ny\n```\n\nPodemos operar aritmeticamente com símbolos e obter uma expressão simbólica como resultado.\n\n\n```python\nz = sy.symbols('z')\nx*y + z**2/3 + sy.sqrt(x*y - z)\n```\n\n**Exemplo**: escreva o produto notável $(x - y)^2$ como uma expressão simbólica.\n\n\n```python\nx**2 - 2*x*y + y**2\n```\n\nNote que o nome da variável não tem a ver com o nome do símbolo. Poderíamos fazer o seguinte:\n\n\n```python\ny = sy.symbols('x') # y é variável; x é símbolo\ny\n```\n\n### Atribuição por desempacotamento \n\nTambém poderíamos realizar as atribuições anteriores da seguinte forma: \n\n\n```python\nx, y, z = sy.symbols('x y z')\n```\n\n### Alfabeto de símbolos \n\nO *sympy* dispõe de um submódulo chamado `abc` do qual podemos importar símbolos para letras latinas (maiúsculas e minúsculas) e gregas (minúsculas).\n\n\n```python\nfrom sympy.abc import a,b,c,alpha,beta,gamma\n(a + 2*b - 3*c)*(alpha/3 + beta/2 - gamma) # símbolico\n```\n\n\n```python\nfrom sympy.abc import D,G,psi,theta\nD**a * G**b * psi**c * theta**2 # símbolico\n```\n\n**Nota**: algumas letras já são usadas como símbolos especiais, tais como `O`, que indica \"ordem\" e `I`, que é o complexo $i$. Neste caso, cuidado deve ser tomado com nomes de variáveis\n\n\n```python\nsy.I # imaginário simbólico\n```\n\n\n```python\ntype(sy.I)\n```\n\n\n\n\n sympy.core.numbers.ImaginaryUnit\n\n\n\n### Símbolos com nomes genéricos\n\nPara criar símbolos genéricos, temos de usar `symbols` ou `Symbol`.\n\n\n```python\nsem_nocao = sy.symbols('nada')\nsem_nocao\n```\n\n\n```python\nmuito_louco = sy.Symbol('massa')\nmuito_louco\n```\n\n### Variáveis e símbolos\n\n\n```python\nsem_medo = sem_nocao + 2\nsem_medo \n```\n\n\n```python\nsoma = muito_louco + 2\nmuito_louco = 3 # 'muito_louco' aqui não é o simbólico\nsoma\n```\n\n## Substituição\n\nA operação de *substituição* permite que: \n\n1. substituamos variáveis por valores numéricos para avaliar uma expressão ou calcular valores de uma função em um dado ponto.\n2. substituamos uma subexpressão por outra.\n\nPara tanto, procedemos da seguinte forma: \n\n```python\nexpressao.subs(variavel,valor)\n```\n\n\n**Exemplo**: considere o polinômio $P(x) = 2x^3 - 4x -6$. Calcule o valor de $P(-1)$, $P(e/3)$, $P(\\sqrt{3.2})$.\n\n\n```python\nfrom sympy.abc import x \nP = 2*x**3 - 4*x - 6\nP1 = P.subs(x,-1)\nPe3 = P.subs(x,mt.e/3)\nP32 = P.subs(x,mt.sqrt(3.2))\nprint(P1, Pe3, P32)\n```\n\n -4 -8.13655822141297 -1.70674948320040\n\n\n**Exemplo:** sejam $f(x) = 4^x$ e $g(x) = 2x - 1$. Compute o valor da função composta $f(g(x))$ em $x = 3$. \n\n\n```python\nf = 4**x\nfg = f.subs(x,2*x - 1)\n```\n\n\n```python\nfg.subs(x,3)\n```\n\nPoderíamos também fazer isso com um estilo \"Pythônico\":\n\n\n```python\nfg = 4**x.subs(x,2*x - 1).subs(x,3)\nfg\n```\n\n**Exemplo:** se $a(x) = 2^x$, $b(x) = 6^x$ e $c(x) = \\cos(x)$, compute o valor de $a(x)b(c(x))$ em $x = 4$\n\n\n```python\na = 2**x\nb = 6**x\nc = sy.cos(x)\n(a * b.subs(x,c)).subs(x,4)\n```\n\nOu, de modo direto:\n\n\n```python\nvalor = ( 2**x * ( 6**x.subs(x,sy.cos(x))) ).subs(x,4)\nvalor\n```\n\n### Avaliação de expressão em ponto flutuante\n\nNote que a expressão anterior não foi computada em valor numérico. Para obter seu valor numérico, podemos usar o método `evalf`.\n\n\n```python\nvalor.evalf()\n```\n\n#### Precisão arbitrária \n\n`evalf` permite que escolhamos a precisão do cálculo impondo o número de dígitos de precisão. Por exemplo, a última expressão com 20 dígitos de precisão seria:\n\n\n```python\nvalor.evalf(20)\n```\n\nCom 55, seria:\n\n\n```python\nvalor.evalf(55)\n```\n\nE com 90 seria:\n\n\n```python\nvalor.evalf(90)\n```\n\n**Exemplo**: calcule o valor de $e$ com 200 dígitos de precisão.\n\n\n```python\nsy.exp(1).evalf(200)\n```\n\n## Funções predefinidas x funções regulares\n\nVamos apresentar aqui três grupos de funções que podem ser criadas em Python para nos auxiliar ao longo do curso sem, no entanto, nos aprofundaremos nos detalhes de cada um. \n\nComo dissemos em um momento anterior, a linguagem Python possui um *core* que contém um conjunto de funções já prontas que podemos usar, como é o caso de `print()`, `type()` e até mesmo `int()` e `float()` para operações de *casting*. Essas funções podem ser chamadas de **predefinidas** (*built-in functions*). Ou seja, são aquelas funções \"já existentes\". Exemplos adicionais seriam as funções do módulo `math`.\n\nSuponhamos, porém, que você vasculhe módulos e mais módulos atrás de uma função que faça exatamente o que você quer, mas não a encontra. O que você faz? Você a cria! Podemos fazer isto de uma maneira usando uma \"palavra-chave\" (*keyword*) chamada `def` da seguinte forma:\n\n```python\ndef f(x):\n (...)\n return y\n```\nA instrução acima permite que você crie uma *função* chamada `f` da qual `x` é um *argumento* e `y` é um *valor de retorno*, indicado por uma segunda \"palavra-chave\", *return*. Funções definidas por você dessa maneira são chamadas de **regulares**, *normais* – pelo fato de serem programadas de um modo regular, seguindo a \"normalidade\" da linguagem –, ou ainda *definidas pelo usuário* (do inglês *user-defined functions*, ou simplesmente *UDF*). Por conveniência, vamos nos referir a elas por este acrônimo elegante: UDF. \n\nUma UDF permite que você abstraia seu pensamento para criar basicamente o que quiser dentro dos limites da linguagem Python. Cabe, apesar disso, fazermos as seguintes ressalvas: \n\n- uma UDF **pode ter zero ou mais argumentos**, tantos quantos se queira;\n- uma UDF **pode ou não ter valor de retorno**;\n\nVamos entender as UDFs com exemplos.\n\n**Exemplo:** Suponha que você é um(a) analista de dados do mercado imobiliário e está estudando o impacto do repasse de comissões pagas a corretores mediante vendas de imóveis. Você, então, começa a raciocinar e cria um modelo matemático bastante simples que, antes de tudo, precisa calcular o valor do repasse a partir do preço de venda. \n\nSe $c$ for o percentual de comissão, $V$ o valor da venda do imóvel e $r$ o valor a ser repassado para o corretor, então, a função a ser definida é \n\n$$r(V) = c\\, V,$$ \n\nassumindo que $c$ seja um valor fixo. \n\nDigamos que $c$ corresponda a 1.03% do valor da venda do imóvel. Neste caso podemos criar uma UDF para calcular $r$ para nós da seguinte forma:\n\n\n```python\ndef repasse(V): \n r = 0.0103*V \n return r\n```\n\nPara $V = \\, R\\$ \\, 332.130,00$:\n\n\n```python\nrepasse(332130)\n```\n\nO que é necessário observar:\n\n- `def` vem seguido pelo *nome* da função (`repasse`) após um espaço;\n- o nome precede os argumentos, enclausurados por parênteses `(V)`. Neste caso, temos apenas um *argumento*, que é `V`;\n- após o nome, os dois-pontos (`:`) são obrigatórios e significam mais ou menos \"o que esta função faz será definido da seguinte maneira\"\n- a instrução `r = 0.0103*V` é o *escopo* da função, que deve ser escrito em uma ou mais linhas indentadas (pressione `TAB` para isso, ou use 4 espaços)\n- o valor de retorno, se houver, é posto na última linha do escopo.\n\nPodemos atribuir os valores do argumento e resultado a variáveis:\n\n\n```python\nV = 332130\nrep = repasse(V)\nrep\n```\n\nNomes iguais de variável e função são permissíveis.\n\n\n```python\nrepasse = repasse(V) # 'repasse' à esquerda é uma variável; à direita, função\nprint(repasse)\n```\n\n 3420.939\n\n\nTodavia, isto pode ser confuso e é bom evitar.\n\nO estilo \"Pythônico\" de escrever permite que o valor de retorno não seja explicitamente declarado. No escopo\n\n```python\n...\n r = 0.0103*V \n return r\n```\n a variável `r` não é necessária.\n \nPython é inteligente para permitir o seguinte:\n\n\n```python\ndef repasse(V): \n return 0.0103*V\n\n# note que aqui não indentamos a linha. \n# Logo esta instrução NÃO pertence ao escopo da função.\nrepasse(V)\n```\n\nPodemos criar uma função para diferentes valores de `c` e `V` usando *dois* argumentos:\n\n\n```python\ndef repasse_c(c,V): # esta função tem outro nome\n return c*V\n```\n\n\n```python\nc = 0.0234 # equivaleria a uma taxa de repasse de 2.34%\nV = 197432 # o valor do imóvel agora é R$ 197.432,00\nrepasse_c(c,V)\n```\n\nA ordem dos argumentos importa:\n\n\n```python\nV = 0.0234 # este deveria ser o valor de c\nc = 197432 # este deveria ser o valor de V\nrepasse_c(c,V)\n```\n\nPor que o valor resultante é o mesmo? Porque a operação no escopo da função é uma multiplicação, `c*V`, que é comutativa independentemente do valor das variáveis. Porém, digamos que um segundo modelo tenha uma forma de cálculo distinta para a comissão dada por\n\n$$r_2(V) = c^{3/5} \\, V$$\n\nNeste caso:\n\n\n```python\ndef repasse_2(c,V):\n return c**(3/5)*V\n\nV = 197432\nc = 0.0234\n\nrepasse_2(c,V)\n```\n\nPorém, se trocarmos o valor das variáveis, a função `repasse_2` calculará um valor distinto. Embora exista um produto também comutativo, o expoente `3/4` modifica apenas o valor de `c`.\n\n\n```python\n# variáveis com valores trocados\nc = 197432\nV = 0.0234\n\nrepasse_2(c,V)\n```\n\nA ordem com que escrevemos os argumentos tem importância relativa aos valores que passamos e ao que definimos: \n\n\n```python\n# variáveis com valores corretos\nV = 197432\nc = 0.0234\n\ndef repasse_2_trocada(V,c): # V vem antes de c\n return c**(3/5)*V\n \nrepasse_2_trocada(V,c)\n```\n\nMas,\n\n\n```python\n# os valores das variáveis estão corretos, \n# mas foram passados para a função na ordem errada\nrepasse_2_trocada(c,V) \n```\n\ne \n\n\n```python\n# a ordem dos argumentos está de acordo com a que foi definida\n# mas os valores das variáveis foram trocados\nV = 197432\nc = 0.0234\nrepasse_2_trocada(c,V) \n```\n\n## Modelos matemáticos simbólicos\n\nA partir do que aprendemos, podemos definir modelos matemáticos completamente simbólicos.\n\n\n```python\nfrom sympy.abc import c,V\n\ndef repasse_2_simbolica(c,V):\n return c**(3/5)*V\n```\n\nSe chamarmos esta função, ela será um objeto simbólico.\n\n\n```python\nrepasse_2_simbolica(c,V)\n```\n\nAtribuindo em variável:\n\n\n```python\nrep_simb = repasse_2_simbolica(c,V)\n```\n\n\n```python\ntype(rep_simb) # é um objeto simbólico\n```\n\n\n\n\n sympy.core.mul.Mul\n\n\n\n**Exemplo:** Suponha, agora, que seu modelo matemático de repasse deva considerar não apenas um percentual $c$ pré-estabelecido, mas também um valor de \"bônus\" adicional concedido como prêmio pela venda do imóvel. Considere, então, que o valor deste bônus seja $b$. Diante disso, nosso novo modelo teria uma fórmula como a seguinte: \n\n$$r_3(V) = c\\,V + b$$\n\nSimbolicamente:\n\n\n```python\n# importaremos apenas o símbolo b, \n# uma vez que c e V já foram importados \n# como símbolos anteriormente\nfrom sympy.abc import b \n\ndef r3(V):\n return c*V + b\n\nrep_3 = r3(V)\nrep_3\n```\n\n### Substituindo valores\n\nPodemos usar a função `subs` para atribuir quaisquer valores para o modelo.\n\n**Exemplo:** $c = 0.119$\n\n\n```python\nrep_3.subs(c,0.119) # substituindo para c\n```\n\n**Exemplo:** $c = 0.222$\n\n\n```python\nrep_3.subs(c,0.222) # substituindo para c\n```\n\n**Exemplo:** $c = 0.222$ e $b = 12.0$\n\n\n```python\nrep_3.subs(c,0.222).subs(b,12.0) # substituindo para c, depois para b\n```\n\n### Substituição múltipla\n\nO modo anterior de substituição não é \"Pythônico\". Para substituirmos mais de uma variável de uma vez, devemos usar *pares ordenados* separados por vírgula sequenciados entre colchetes como uma *lista*. Mais tarde, aprenderemos sobre pares ordenados e listas.\n\n**Exemplo:** Modifique o modelo $r_3$ para que $c = 0.043$ e $b = 54.0$\n\n\n```python\n# espaços foram adicionados para dar legibilidade\nrep_3.subs( [ (c,0.043), (b,54.0) ] )\n```\n\n#### Pares ordenados\n\nEm matemática, o conceito de par ordenado pode ser definido pelo conjunto: \n\n$$ X \\times Y = \\{ (x,y) ; x \\in X \\text{ e } y \\in Y \\},$$\n\nonde $X$ e $Y$ são conjuntos quaisquer e $x$ e $y$ são as *coordenadas*. Por exemplo, se $X = Y = \\mathbb{R}$, o conjunto acima contém elementos do tipo $(3,2)$, $(-1,3)$, $(\\pi,2.18)$ etc. Na verdade, eles formam o conjunto $\\mathbb{R} \\times \\mathbb{R} = \\mathbb{R}^2$, que é exatamente o *plano cartesiano*.\n\nLogo, a substituição múltipla com `subs` ocorre da seguinte forma; \n\n- a primeira coordenada é o *símbolo*;\n\n- a segunda coordenada é o *valor* que você quer dar para o símbolo.\n\n**Exemplo:** Calcule $r_3(V)$ considerando $c = 0.021$, $b = 34.0$ e $V = 432.000$.\n\n\n```python\n# armazenaremos o valor na variável 'valor'\nvalor = r3(V)\n\n# subsituição \nvalor.subs( [ (c,0.021), (b,54.0) ] )\n```\n\nCom o estilo \"Pythônico\":\n\n\n```python\nvalor = r3(V).subs( [ (c,0.021), (b,54.0) ] ) # \nvalor\n```\n\nPodemos seguir esta regra de pares para substituir todos os valores de um modelo simbólico genérico não necessariamente definido através de uma função. Veja o exemplo aplicado a seguir.\n\n## Exemplo de aplicação: o índice de caminhabilidade\n\nEstudos empíricos nos EUA mostraram que a *caminhabilidade* de uma vizinhança impacta substancialmente os preços das casas. A caminhabilidade está relacionada à distância da moradia a locais de amenidades, tais como restaurantes, bares, bibliotecas, mercearias etc.\n\nO *índice de caminhabilidade* $W$ para uma vizinhança de casas é uma medida matemática que assume valores no intervalo $[0,1]$. A fórmula é definida por: \n\n$$W(d) = e^{-5 \\left( \\dfrac{d}{M} \\right)^5},$$\n\nonde $d$ é a distância medida entre a vizinhança (0 metro) e um dado ponto de referência, e $M$ é a distância máxima de avaliação considerada a partir da qual a caminhabilidade é assumida como nula. Ou seja, \n\n- quando estamos na vizinhança, $d = 0$, $W = 1$ e a caminhabilidade é considerada ótima.\n\n- à medida que nos afastamos da vizinhança em direção ao local da amenidade, $d$ aumenta e o valor $W$ decai vertiginosamente até atingir o valor limite $M$ a partir do qual $W = 0$ e a caminhabilidade é considerada \"péssima\". \n\nO índice de caminhabilidade é, portanto, calculado com relação a um ponto de destino definido e a distância deve levar em consideração as vias de circulação (ruas, rodovias etc) e não a distância mais curta (raio do perímetro). Por exemplo, se a distância máxima a ser considerada para a caminhabilidade for $M = 500 \\, m$ , um bar localizado a 100 metros da vizinhança teria um índice de caminhabilidade maior do que o de uma farmácia localizada a 300 m e muito maior do que o de um shopping localizado a 800 m, ainda que muito famoso. Aliás, neste caso, o valor de $W$ para o shopping seria zero, já que 800 m está além do limite $M$ estabelecido.\n\nFonte: *De Nadai, M. and Lepri, B. [[The economic value of neighborhoods: Predicting real estate prices from the urban environment]](https://arxiv.org/pdf/1808.02547.pdf)*. \n\n### Modelo simbólico\n\nPodemos modelar $W$ simbolicamente e calcular seu valor para diferentes valores de $d$ e $M$ usando a substituição múltipla.\n\n\n```python\nfrom sympy.abc import d,M,W \n\nW = sy.exp(-5*(d/M)**5) # função exponencial simbólica\nW\n```\n\n**Exemplo:** A nossa corretora de imóveis gostaria de entender a relação de preços de imóveis para o Condomínio Pedras de Marfim. Considerando $M = 1 km$, calcule:\n \n- o índice de caminhabilidade $W_1$ em relação à farmácia Dose Certa, localizada a 222 m do condomínio.\n\n- o índice de caminhabilidade $W_2$ em relação ao restaurante Sabor da Arte, localizada a 628 m do condomínio.\n\n- o índice de caminhabilidade $W_3$ em relação ao Centro Esportivo Physicalidade, localizada a 998 m do condomínio.\n\n- o índice de caminhabilidade $W_4$ em relação à Padaria Dolce Panini, localizada a 1,5 km do condomínio.\n\n\n```python\n# note que 1 km = 1000 m\nW1 = W.subs([ (d,222), (M,1000) ]) \nW2 = W.subs([ (d,628), (M,1000) ]) \nW3 = W.subs([ (d,998), (M,1000) ]) \nW4 = W.subs([ (d,1500), (M,1000) ])\n```\n\nPerceba, entretanto, que os valores calculados ainda não são numéricos, como esperado.\n\n\n```python\nW1\n```\n\n\n```python\nW2\n```\n\n\n```python\nW3\n```\n\n\n```python\nW4\n```\n\nLembre-se que podemos usar `evalf` para calcular esses valores. Faremos isso considerando 3 casas decimais.\n\n\n```python\n# reatribuindo todos os valores\nW1n = W1.evalf(3)\nW2n = W2.evalf(3)\nW3n = W3.evalf(3)\nW4n = W4.evalf(3)\n\nprint('W1 =', W1n, '; ' \\\n 'W2 =', W2n, '; ' \\\n 'W3 =', W3n, '; ' \\\n 'W4 =', W4n) \n```\n\n W1 = 0.997 ; W2 = 0.614 ; W3 = 0.00708 ; W4 = 3.24e-17\n\n\nComo era de se esperar, os valores decaem de 0.997 a 3.24e-17, que é um valor considerado nulo em termos de aproximação numérica.\n\n#### Quebrando instruções com `\\`\n\nA contra-barra `\\` pode ser usada para quebrar instruções e continuá-las nas próximas linhas, porém não poderá haver nenhum caracter após ela, nem mesmo espaços. Caso contrário, um erro será lançado.\n\n\n```python\nprint('Continuando' \\\n 'na linha abaixo')\n```\n\n Continuandona linha abaixo\n\n\n\n```python\n# neste exemplo, há um caracter de espaço após \\\nprint('Continuando' \\ \n 'na linha abaixo')\n```\n\n### O tipo `bool`\n\nEm Python, temos mais um tipo de dado bastante útil, o `bool`, que é uma redução de \"booleano\". Objetos `bool`, que têm sua raiz na chamada Álgebra de Boole, são baseados nos conceitos *true* (verdadeiro) e *false*, ou *0* e *1* e são estudados em algumas disciplinas, tais como Circuitos Lógicos, Matemática Discreta, Lógica Aplicada, entre outras. \n\nAprenderemos sobre operadores lógicos mais à frente. Por enquanto, cabe mencionar as entidades fundamentais `True` e `False`. \n\n\n```python\nTrue\n```\n\n\n\n\n True\n\n\n\n\n```python\nFalse\n```\n\n\n\n\n False\n\n\n\n\n```python\ntype(True)\n```\n\n\n\n\n bool\n\n\n\n\n```python\ntype(False)\n```\n\n\n\n\n bool\n\n\n\nPodemos realizar testes lógicos para concluir verdades ou falsidades quando temos dúvidas sobre objetos e relações entre eles. Por exemplo, retomemos os seguintes valores:\n\n\n```python\nW1\n```\n\n\n```python\nW2\n```\n\nA princípio, é difícil determinar qual dos dois é o maior. Porém, podemos realizar \"perguntas\" lógicas para o interpretador Python com operadores lógicos. Mostraremos apenas dois exemplos com `>` e `<`.\n\n\n```python\nW1 > W2 # isto quer dizer: \"W1 é maior do que W2?\"\n```\n\nO valor `True` confirma que o valor de `W1` é maior do que `W2`. \n\n\n```python\nW4 < 0\n```\n\nNote que, de acordo com nosso modelo de caminhabilidade, este valor deveria ser zero. Porém, numericamente, ele é uma aproximação para zero. Embora muito pequeno, não é exatamente zero! Por que isso ocorre? Porque o computador lida com uma matemática inexata e aproximada, mas com precisão satisfatória.\n\n## Operadores lógicos\n\nVimos que `True` e `False` são os dois valores atribuíves a um objeto de tipo `bool`. Eles são úteis para testar condições, realizar verificações e comparar quantidades. Vamos estudar *operadores de comparação*, *operadores de pertencimento* e *operadores de identidade*.\n\n### Operadores de comparação\n\nA tabela abaixo resume os operadores de comparação utilizados em Python.\n\n| operador | significado | símbolo matemático | \n|---|---|---| \n| `<` | menor do que | $<$ |\n| `<=` | menor ou igual a | $\\leq$ |\n| `>` | maior do que | $>$ |\n| `>=` | maior ou igual a | $\\geq$ |\n| `==` | igual a | $=$ |\n| `!=` | diferente de | $\\neq$ |\n\nPodemos usá-los para comparar objetos. \n\n**Nota:** `==` está relacionado à igualdade, ao passo que `=` é uma atribuição. São conceitos operadores com finalidade distinta. \n\n\n```python\n2 < 3 # o resultado é um 'bool'\n```\n\n\n\n\n True\n\n\n\n\n```python\n5 < 2 # isto é falso\n```\n\n\n\n\n False\n\n\n\n\n```python\n2 <= 2 # isto é verdadeiro\n```\n\n\n\n\n True\n\n\n\n\n```python\n4 >= 3 # isto é verdadeiro\n```\n\n\n\n\n True\n\n\n\n\n```python\n6 != -2 \n```\n\n\n\n\n True\n\n\n\n\n```python\n4 == 4 # isto não é uma atribuição! \n```\n\n\n\n\n True\n\n\n\nPodemos realizar comparações aninhadas:\n\n\n```python\nx = 2\n1 < x < 3\n```\n\n\n\n\n True\n\n\n\n\n```python\n3 > x > 4\n```\n\n\n\n\n False\n\n\n\n\n```python\n2 == x > 3 \n```\n\n\n\n\n False\n\n\n\nAs comparações aninhadas acima são resolvidas da esquerda para a direita e em partes. Isso nos leva a introduzir os seguintes operadores.\n\n| operador | símbolo matemático | significado | uso relacionado a |\n|---|---|---|---|\n| `or` | $\\vee$ | \"ou\" booleano | união, disjunção |\n| `and` | $\\wedge$ | \"e\" booleano | interseção, conjunção |\n| `not` | $\\neg$ | \"não\" booleano | exclusão, negação |\n\n\n```python\n# parênteses não são necessários aqui\n(2 == x) and (x > 3) # 1a. comparação: 'True'; 2a.: 'False'. Portanto, ambas: 'False'\n```\n\n\n\n\n False\n\n\n\n\n```python\n# parênteses não são necessários aqui\n(x < 1) or (x < 2) # nenhuma das duas é True. Portanto, \n```\n\n\n\n\n False\n\n\n\n\n```python\nnot (x == 2) # nega o \"valor-verdade\" que é 'True'\n```\n\n\n\n\n False\n\n\n\n\n```python\nnot x + 1 > 3 # estude a precedência deste exemplo. Por que é 'True'?\n```\n\n\n\n\n True\n\n\n\n\n```python\nnot (x + 1 > 3) # estude a precedência deste exemplo. Por que também é 'True'?\n```\n\n\n\n\n True\n\n\n\n### Operadores de pertencimento\n\nA tabela abaixo resume os operadores de pertencimento. \n\n| operador | significado | símbolo matemático\n|---|---|---|\n| `in` | pertence a | $\\in$ |\n| `not in` | não pertence a | $\\notin$ |\n\nEles terão mais utilidade quando falarmos sobre sequências, listas. Neste momento, vejamos exemplos com objetos `str`.\n\n\n```python\n'2' in '2 4 6 8 10' # o caracter '2' pertence à string\n```\n\n\n\n\n True\n\n\n\n\n```python\nfrase_teste = 'maior do que' \n'maior' in frase_teste\n```\n\n\n\n\n True\n\n\n\n\n```python\n'menor' in frase_teste # a palavra 'menor' está na frase\n```\n\n\n\n\n False\n\n\n\n\n```python\n1 in 2 # 'in' e 'not in' não são aplicáveis aqui\n```\n\n### Operadores de identidade\n\nA tabela abaixo resume os operadores de identidade. \n\n| operador | significado \n|---|---|\n| `is` | \"aponta para o mesmo objeto\" \n| `is not` | \"não aponta para o mesmo objeto\" |\n\nEsses operadores são úteis para verificar se duas variáveis se referem ao mesmo objeto. Exemplo: \n\n```python\na is b\na is not b\n```\n\n- `is` é `True` se `a` e `b` se referem ao mesmo objeto; `False`, caso contrário.\n- `is not` é `False` se `a` e `b` se referem ao mesmo objeto; `True`, caso contrário.\n\n\n```python\na = 2\nb = 3\na is b # valores distintos\n```\n\n\n\n\n False\n\n\n\n\n```python\na = 2\nb = a\na is b # mesmos valores\n```\n\n\n\n\n True\n\n\n\n\n```python\na = 2\nb = 3\na is not b # de fato, valores não são distintos\n```\n\n\n\n\n True\n\n\n\n\n```python\na = 2\nb = a\na is not b # de fato, valores são distintos\n```\n\n\n\n\n False\n\n\n\n## Equações simbólicas\n\nEquações simbólicas podem ser formadas por meio de `Eq` e não com `=` ou `==`.\n\n\n```python\n# importação\nfrom sympy.abc import a,b\nimport sympy as sy \nsy.init_printing(pretty_print=True)\n```\n\n\n```python\nsy.Eq(a,b) # equação simbólica\n```\n\n\n```python\nsy.Eq(sy.cos(a), b**3) # os objetos da equação são simbólicos\n```\n\n### Resolução de equações algébricas simbólicas\n\nPodemos resolver equações algébricas da seguinte forma:\n\n```python\nsolveset(equação,variável,domínio)\n```\n\n**Exemplo:** resolva $x^2 = 1$ no conjunto $\\mathbb{R}$.\n\n\n```python\nfrom sympy.abc import x\nsy.solveset( sy.Eq( x**2, 1), x,domain=sy.Reals)\n```\n\nPodemos reescrever a equação como: $x^2 - 1 = 0$.\n\n\n```python\nsy.solveset( sy.Eq( x**2 - 1, 0), x,domain=sy.Reals)\n```\n\nCom `solveset`, não precisamos de `Eq`. Logo, a equação é passada diretamente.\n\n\n```python\nsy.solveset( x**2 - 1, x,domain=sy.Reals)\n```\n\n**Exemplo:** resolva $x^2 + 1 = 0$ no conjunto $\\mathbb{R}$.\n\n\n```python\nsy.solveset( x**2 + 1, x,domain=sy.Reals) # não possui solução real\n```\n\n**Exemplo:** resolva $x^2 + 1 = 0$ no conjunto $\\mathbb{C}$.\n\n\n```python\nsy.solveset( x**2 + 1, x,domain=sy.Complexes) # possui soluções complexas\n```\n\n**Exemplo:** resolva $\\textrm{sen}(2x) = 3 + x$ no conjunto $\\mathbb{R}$.\n\n\n```python\nsy.solveset( sy.sin(2*x) - x - 3,x,sy.Reals) # a palavra 'domain' também pode ser omitida.\n```\n\nO conjunto acima indica que nenhuma solução foi encontrada.\n\n**Exemplo:** resolva $\\textrm{sen}(2x) = 1$ no conjunto $\\mathbb{R}$.\n\n\n```python\nsy.solveset( sy.sin(2*x) - 1,x,sy.Reals)\n```\n\n## Expansão, simplificação e fatoração de polinômios\n\nVejamos exemplos de polinômios em uma variável. \n\n\n```python\na0, a1, a2, a3 = sy.symbols('a0 a1 a2 a3') # coeficientes\nP3x = a0 + a1*x + a2*x**2 + a3*x**3 # polinômio de 3o. grau em x\nP3x\n```\n\n\n```python\nb0, b1, b2, b3 = sy.symbols('b0 b1 b2 b3') # coeficientes\nQ3x = b0 + b1*x + b2*x**2 + b3*x**3 # polinômio de 3o. grau em x\nQ3x\n```\n\n\n```python\nR3x = P3x*Q3x # produto polinomial\nR3x\n```\n\n\n```python\nR3x_e = sy.expand(R3x) # expande o produto\nR3x_e\n```\n\n\n```python\nsy.simplify(R3x_e) # simplify às vezes não funciona como esperado\n```\n\n\n```python\nsy.factor(R3x_e) # 'factor' pode funcionar melhor\n```\n\n\n```python\n# simplify funciona para casos mais gerais \nident_trig = sy.sin(x)**2 + sy.cos(x)**2\nident_trig\n```\n\n\n```python\nsy.simplify(ident_trig)\n```\n\n## Identidades trigonométricas \n\nPodemos usar `expand_trig` para expandir funções trigonométricas. \n\n\n```python\nsy.expand_trig( sy.sin(a + b) ) # sin(a+b)\n```\n\n\n```python\nsy.expand_trig( sy.cos(a + b) ) # cos(a+b)\n```\n\n\n```python\nsy.expand_trig( sy.sec(a - b) ) # sec(a-b)\n```\n\n## Propriedades de logaritmo\n\n\nCom `expand_log`, podemos aplicar propriedades válidas de logaritmo.\n\n\n```python\nsy.expand_log( sy.log(a*b) )\n```\n\nA identidade não foi validada pois `a` e `b` são símbolos irrestritos.\n\n\n```python\na,b = sy.symbols('a b',positive=True) # impomos que a,b > 0\n```\n\n\n```python\nsy.expand_log( sy.log(a*b) ) # identidade validada\n```\n\n\n```python\nsy.expand_log( sy.log(a/b) )\n```\n\n\n```python\nm = sy.symbols('m', real = True) # impomos que m seja um no. real\nsy.expand_log( sy.log(a**m) )\n```\n\nCom `logcombine`, compactamos as propriedades.\n\n\n```python\nsy.logcombine( sy.log(a) + sy.log(b) ) # identidade recombinada\n```\n\n## Fatorial \n\nA função `factorial(n)` pode ser usada para calcular o fatorial de um número.\n\n\n```python\nsy.factorial(m)\n```\n\n\n```python\nsy.factorial(m).subs(m,10) # 10! \n```\n\n\n```python\nsy.factorial(10) # diretamente\n```\n\n**Exemplo:** Sejam $m,n,x$ inteiros positivos. Se $f(m) = 2m!$, $g(n) = \\frac{(n + 1)!}{n^2!}$ e $h(x) = f(x)g(x)$, qual é o valor de $h(2)$? \n\n\n```python\nfrom sympy.abc import m,n,x\n\nf = 2*sy.factorial(m)\ng = sy.factorial(n + 1)/sy.factorial(n**2)\n\nh = (f.subs(m,x)*g.subs(n,x)).subs(x,4)\nh\n```\n\n## Funções anônimas \n\nA terceira classe de funções que iremos aprender é a de *funções anônimas*. Uma **função anônima** em Python consiste em uma função cujo nome não é explicitamente definido e que pode ser criada em apenas uma linha de código para executar uma tarefa específica.\n\nFunções anônimas são baseadas na palavra-chave `lambda`. Este nome tem inspiração em uma área da ciência da computação chamada de cálculo-$\\lambda$.\n\nUma função anônima tem a seguinte forma: \n\n```python\nlambda lista_de_parâmetros: expressão\n```\n\nFunções anônimas podem são bastante úteis para tornar um código mais conciso. \n\nPor exemplo, na aula anterior, definimos a função\n\n```python\ndef repasse(V): \n return 0.0103*V\n```\n\npara calcular o repasse financeiro ao corretor imobiliário. \n\nCom uma função anônima, a mesma função seria escrita como:\n\n\n```python\nrepasse = lambda V: 0.0103*V\n```\n\nNão necessariamente temos que atribui-la a uma variável. Neste caso, teríamos:\n\n\n```python\nlambda V: 0.0103*V\n```\n\n\n\n\n (V)>\n\n\n\nPara usar a função, passamos um valor:\n\n\n```python\nrepasse(100000) # repasse sobre R$ 100.000,00\n```\n\nO modelo completo com \"bonificação\" seria escrito como:\n\n\n```python\nr3 = lambda c,V,b: c*V + b # aqui há 3 parâmetros necessários\n```\n\nRedefinamos objetos simbólicos:\n\n\n```python\nfrom sympy.abc import b,c,V\nr3(b,c,V)\n```\n\nO resultado anterior continua sendo um objeto simbólico, mas obtido de uma maneira mais direta. Podemos usar funções anônimas para tarefas de menor complexidade.\n\n## \"Lambdificação\" simbólica\n\nUsando `lambdify`, podemos converter uma expressão simbólica do *sympy* para uma expressão que pode ser numericamente avaliada em outra biblioteca. Essa função desempenha papel similar a uma função *lambda* (anônima).\n\n\n```python\nexpressao = sy.sin(x) + sy.sqrt(x) # expressão simbólica\nf = sy.lambdify(x,expressao,\"math\") # lambdificação para o módulo math\nf(0.2) # avalia\n```\n\nPara avaliações simples como a anterior, podemos usar `evalf` e `subs`. A lambdificação será útil quando quisermos avaliar uma função em vários pontos, por exemplo. Na próxima aula, introduziremos sequencias e listas. Para mostrar um exemplo de lambdificação melhor veja o seguinte exemplo.\n\n\n```python\nfrom numpy import arange # importação de função do módulo numpy\n\nX = arange(40) # gera 40 valores de 0 a 39\n```\n\n\n```python\nX\n```\n\n\n\n\n array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,\n 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33,\n 34, 35, 36, 37, 38, 39])\n\n\n\n\n```python\nf = sy.lambdify(x,expressao,\"numpy\")(X) # avalia 'expressao' em X\nf\n```\n\n\n\n\n array([0. , 1.84147098, 2.32351099, 1.87317082, 1.2431975 ,\n 1.2771437 , 2.17007424, 3.30273791, 3.81778537, 3.41211849,\n 2.61825655, 2.31663458, 2.9275287 , 4.02571831, 4.73226474,\n 4.52327119, 3.71209668, 3.16170813, 3.49165344, 4.50877615,\n 5.38508121, 5.41923133, 4.68156445, 3.94961112, 3.99340112,\n 4.86764825, 5.86157796, 6.15252835, 5.56240841, 4.72153092,\n 4.48919395, 5.16372672, 6.20828093, 6.74447451, 6.36003458,\n 5.48789711, 5.00822115, 5.4392244 , 6.46078258, 7.20879338])\n\n\n", "meta": {"hexsha": "6f63ba3c4348140a72e691517b2ef75821d533b3", "size": 281678, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "_build/jupyter_execute/ipynb/02a-computacao-simbolica.ipynb", "max_stars_repo_name": "gcpeixoto/FMECD", "max_stars_repo_head_hexsha": "9bca72574c6630d1594396fffef31cfb8d58dec2", "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": "_build/jupyter_execute/ipynb/02a-computacao-simbolica.ipynb", "max_issues_repo_name": "gcpeixoto/FMECD", "max_issues_repo_head_hexsha": "9bca72574c6630d1594396fffef31cfb8d58dec2", "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": "_build/jupyter_execute/ipynb/02a-computacao-simbolica.ipynb", "max_forks_repo_name": "gcpeixoto/FMECD", "max_forks_repo_head_hexsha": "9bca72574c6630d1594396fffef31cfb8d58dec2", "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": 62.7904592064, "max_line_length": 14152, "alphanum_fraction": 0.7906581274, "converted": true, "num_tokens": 11581, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582612793112, "lm_q2_score": 0.9481545280395656, "lm_q1q2_score": 0.8822182135838}} {"text": "#### Finding the axes of a hyper-ellipse\n\nLet us try finding the axes of the hyper ellipse described by the\n
equation $5x^2+6xy+5y^2=20$.\n
Note: The actual ellipse we use as example is 2D (to facilitate \n
visualization), but the code we develop will be general\n
and extensible to multi-dimensions.\n\nThe ellipse equation can be written using matrices and vectors as\n
$\\vec{x}^{T}A\\vec{x} = 1$ where\n$A=\n\\begin{bmatrix} \n 5 & 3 \\\\\n 3 & 5 \\\\\n\\end{bmatrix} \n\\space \\space \\space\n\\vec{x} = \n\\begin{bmatrix} \n x \\\\\n y \\\\\n\\end{bmatrix}$.\n\nTo find the axes of the hyper ellipse, we need to transform the\n
coordinate system so that the matrix in the middle becomes diagonal.\n
Here is how this can be done:\n
If we diagonalise $A$ into $S\\Sigma S^{-1}$, then the ellipse equation\n
becomes $\\vec{x}^{T}S \\Sigma S^{-1}\\vec{x} = 1$ where $\\Sigma$ is a\n
diagonal matrix.\n
Since $A$ is symmetric, its eigenvectors are orthogonal.\n
Hence, the matrix containing these eigenvectors as columns is orthogonal,\n
i.e., $S^{-1} = S^{T}$. In other words, $S$ is a rotation matrix.\n
\n
So the ellipse equation becomes $\\vec{x}^{T}S \\Sigma S^{T}\\vec{x} = 1$\n
or $\\left(\\vec{x}^{T}S\\right) \\Sigma \\left(S^{T}\\vec{x}\\right) = 1$\n
or $\\vec{y}^{T} \\Sigma \\vec{y} = 1$ where $\\vec{y} = S^{T}\\vec{x}$.\n
This is of the desired form since $\\Sigma$ is a diagonal matrix.\n
Remember, $S$ is a rotation matrix. Thus, rotating the coordinate system\n
by $S$ aligns the coordinate axes with the ellipse axes.\n\n\n\n```python\nimport numpy as np\nfrom sympy import Symbol\nimport sympy as sy\n\nx = Symbol('x')\ny = Symbol('y')\na = Symbol('a')\nb = Symbol('b')\nellipse_eq = sy.Eq(5*x**2 + 5*y**2 + 6*x*y, 20)\nellipse_eq\n```\n\n\n\n\n$\\displaystyle 5 x^{2} + 6 x y + 5 y^{2} = 20$\n\n\n\n\n```python\n# Let us plot this ellipse\n%matplotlib inline\nimport matplotlib.pyplot as plt\nimport sympy as sy\n\ndef sym_eq_plot(eq):\n plot = sy.plot_implicit(eq)\n return plot \nplot = sym_eq_plot(ellipse_eq)\n\nprint(\"Note that the ellipse major axis is forming an\\n\"\n \"angle of 45 degrees with X axis.\\n\"\n \"Rotating coordinate system by this angle\\n\"\n \"will align ellipse axes with coordinate axes.\")\n```\n\n\n```python\nA = np.array([[5, 3], [3, 5]])\n\n# Obtain eigen values and vectors of the ellipse\n# coeeficients matrix\nl, S = np.linalg.eig(np.array(A).astype(np.float64))\n\nprint(\"Eigen values are: {}\\n\".format(l))\nprint(\"Eigen vectors are columns of S matrix\\n{}\".format(S))\n\n# Assert that eigen vectors are orthogonal\nassert np.dot(S[:, 0], S[:, 1]) == 0.0\n\n# Find the angle between the principal axis and the X-axis.\nimport math\n\n# Vector corresponding to X-axis\nx_axis_vec = np.zeros((A.shape[0]))\nx_axis_vec[0] = 1\n\n# First principal eigen vector\nfirst_eigen_vec = S[:, 0]\n\n# Dot product between the two vectors (equals cosine\n# of the angle between the directions of the two vectors)\ndot_prod = np.dot(x_axis_vec, first_eigen_vec)\n\n# The angle between the two vectors is the cosine inverse\n# of the dot-product, in radians\ntheta = math.acos(dot_prod)\n\n# Convert to degrees from radian\ntheta = math.degrees(theta)\nprint(\"\\nRotation angle theta = {:.2f} degrees\".format(theta))\n```\n\n Eigen values are: [8. 2.]\n \n Eigen vectors are columns of S matrix\n [[ 0.70710678 -0.70710678]\n [ 0.70710678 0.70710678]]\n \n Rotation angle theta = 45.00 degrees\n\n\n\n```python\n# Plot the eigen vectors\nplt.quiver([0], [0], S[:,0], S[:,1],\n color=['r','b','g'], scale=5)\nplt.show()\n```\n\n\n```python\n# Let us plot the ellipse along with the axes.\n# From our calculations, we know that the angle \n# of rotation is 45 degrees, and that the eigen vectors\n# are the columns of S\n\nimport matplotlib\nfig = plt.figure(0)\nax = fig.add_subplot(111, aspect='equal')\n\ne = matplotlib.patches.Ellipse((0, 0), 1, 3,\n theta, fc='None',\n edgecolor='g')\n# The ellipse is centered at (0, 0)\n# We are using random width and height. \n# Note that the direction of the axes is independent of\n# width and height\nax.add_artist(e)\nax.set_xlim(-2, 2)\nax.set_ylim(-2, 2)\nax.quiver([0], [0], S[:,0], S[:,1], color=['r','b','g'],\n scale=5)\n\nplt.show()\n\n```\n", "meta": {"hexsha": "727f430711595958bb25926714d0a5f3a11e03ca", "size": 33790, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "python/ch2/2.17-hyper-ellipse-numpy.ipynb", "max_stars_repo_name": "krishnonwork/mathematical-methods-in-deep-learning", "max_stars_repo_head_hexsha": "12a7e7a9981f8639b4524b7977bd185f82c04e2d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-08-30T05:36:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-30T05:36:03.000Z", "max_issues_repo_path": "python/ch2/2.17-hyper-ellipse-numpy.ipynb", "max_issues_repo_name": "TranTony/mathematical-methods-in-deep-learning-ipython", "max_issues_repo_head_hexsha": "56b1f6d1386379afd4f83fd02bd39b9631b20089", "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/ch2/2.17-hyper-ellipse-numpy.ipynb", "max_forks_repo_name": "TranTony/mathematical-methods-in-deep-learning-ipython", "max_forks_repo_head_hexsha": "56b1f6d1386379afd4f83fd02bd39b9631b20089", "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.6863468635, "max_line_length": 11032, "alphanum_fraction": 0.8662326132, "converted": true, "num_tokens": 1273, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566342037088041, "lm_q2_score": 0.9219218428996602, "lm_q1q2_score": 0.8819419680640697}} {"text": "\n\n\n```python\nimport numpy as np\nimport sympy as sp\nimport math\nsp.init_printing(use_unicode=True)\n```\n\n# Compare sin30 and cos30 (numpy, sympy)\n\n\n```python\n# sin30 and cos30 using numpy: \nsin30 = np.sin(30*math.pi/180)\ncos30 = np.cos(30*math.pi/180)\nprint(sin30, cos30)\n```\n\n 0.49999999999999994 0.8660254037844387\n\n\n\n```python\n# sin30 and cos30 using sympy ... with 'regular' pi: \nsin30 = sp.sin(30*math.pi/180)\ncos30 = sp.cos(30*math.pi/180)\nprint(sin30, cos30)\n```\n\n 0.500000000000000 0.866025403784439\n\n\n\n```python\n# sin30 and cos30 using sympy with exact pi: \nsin30e = sp.sin(30*sp.pi/180)\ncos30e = sp.cos(30*sp.pi/180)\nprint(sin30e, cos30e)\n```\n\n 1/2 sqrt(3)/2\n\n\n\n```python\n# results for sympy calculations are shown in LaTeX if called outside of print():\nsin30e\n```\n\n\n```python\n# that's more obvious here: \ncos30e\n```\n\n# Setup rotation matrices and apply them to u=[3,2]\n\n\n```python\n# rot30 will be a sympy matrix with exact values. \nrot30 = sp.Matrix([[cos30e, -1*sin30e], [sin30e, cos30e]])\nrot30\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}\\frac{\\sqrt{3}}{2} & - \\frac{1}{2}\\\\\\frac{1}{2} & \\frac{\\sqrt{3}}{2}\\end{matrix}\\right]$\n\n\n\n\n```python\nu = sp.Matrix([3,2])\nu\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}3\\\\2\\end{matrix}\\right]$\n\n\n\n\n```python\n# Remember you can use * for matrix multiplication in sympy only\nR30u = rot30*u\nR30u\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}-1 + \\frac{3 \\sqrt{3}}{2}\\\\\\frac{3}{2} + \\sqrt{3}\\end{matrix}\\right]$\n\n\n\n\n```python\n# Let's repeat our results using numpy: \nrot30n = np.array([[cos30, -1*sin30], [sin30, cos30]])\nrot30n\n```\n\n\n\n\n array([[0.866025403784439, -0.500000000000000],\n [0.500000000000000, 0.866025403784439]], dtype=object)\n\n\n\n\n```python\n# Numpy does floating point calculations so all answers are in decimals. It's fast but less precise than sympy. \nR30un = np.dot(rot30n, u)\nR30un\n```\n\n\n\n\n array([[1.59807621135332],\n [3.23205080756888]], dtype=object)\n\n\n", "meta": {"hexsha": "9d4a30521520424dfa623258fc33038f46416c27", "size": 11191, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "7B_Rotation_Matrices_with_sympy_and_numpy.ipynb", "max_stars_repo_name": "tofighi/Linear-Algebra", "max_stars_repo_head_hexsha": "bea7d2a4a81e0c49b324f23c47cf03db72e376cf", "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": "7B_Rotation_Matrices_with_sympy_and_numpy.ipynb", "max_issues_repo_name": "tofighi/Linear-Algebra", "max_issues_repo_head_hexsha": "bea7d2a4a81e0c49b324f23c47cf03db72e376cf", "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": "7B_Rotation_Matrices_with_sympy_and_numpy.ipynb", "max_forks_repo_name": "tofighi/Linear-Algebra", "max_forks_repo_head_hexsha": "bea7d2a4a81e0c49b324f23c47cf03db72e376cf", "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": 30.0833333333, "max_line_length": 1010, "alphanum_fraction": 0.4969171656, "converted": true, "num_tokens": 710, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191246389618, "lm_q2_score": 0.9230391643039738, "lm_q1q2_score": 0.8817969664503511}} {"text": "# CSE 330 Numerical Analysis Lab \n\n### Lab 8: LU Decomposition\n\nLet a system of equations be,\n\\begin{equation}\n2\\boldsymbol{x}_1 - \\boldsymbol{x}_{2}+3\\boldsymbol{x}_3 = 4\n\\end{equation} \n\\begin{equation}\n4\\boldsymbol{x}_1 + 2\\boldsymbol{x}_{2}+\\boldsymbol{x}_3 = 1\n\\end{equation} \n\\begin{equation}\n-6\\boldsymbol{x}_1 - \\boldsymbol{x}_{2}+2\\boldsymbol{x}_3 = 2\n\\end{equation} \n\nWe can write the whole thing in matrix form,\n\n\\begin{equation}\n\\begin{pmatrix}\n2 & -1 & 3 \\\\\n4 & 2 & 1 \\\\\n-6 & -1 & 2 \\\\\n\\end{pmatrix}\n\\begin{pmatrix}\n\\boldsymbol{x}_1 \\\\\n\\boldsymbol{x}_2 \\\\\n\\boldsymbol{x}_3 \n\\end{pmatrix}\n=\n\\begin{pmatrix}\n4 \\\\\n1 \\\\\n2\n\\end{pmatrix}\n\\end{equation}\n\n\n\nIn the system of equations, there are 3 equations and 3 unknowns. Therefore, it can be solved for $\\boldsymbol{x}_1, \\boldsymbol{x}_2, \\boldsymbol{x}_3$ unless any 2 of the equations are parallel to each other. \n\nGaussian elimination is a commonly used tactics to solve a system of equation. In this method, we create an augmented matrix from a set of equations and then eliminate everything below the diagonal terms. First, let's create the augmented matrix. \n\n\\begin{equation}\n\\begin{pmatrix}\n2 & -1 & 3 & \\qquad 4 \\\\\n4 & 2 & 1 & \\qquad 1\\\\\n-6 & -1 & 2 & \\qquad 2 \\\\\n\\end{pmatrix}\n\\end{equation}\n\nNow, if we multiply row 1 with 2 and subtract it from row 2, we get,\n\n\\begin{equation}\n\\begin{pmatrix}\n2 & -1 & 3 & \\qquad 4 \\\\\n0 & 4 & -5 & \\qquad -7\\\\\n-6 & -1 & 2 & \\qquad 2 \\\\\n\\end{pmatrix}\n\\end{equation}\n\nAdditionally, multiply row 1 with -3 and subtract it from row 3,\n\n\\begin{equation}\n\\begin{pmatrix}\n2 & -1 & 3 & \\qquad 4 \\\\\n0 & 4 & -5 & \\qquad -7\\\\\n0 & -4 & 11 & \\qquad 14 \\\\\n\\end{pmatrix}\n\\end{equation}\n\nFinally, multiply row 2 with -1 and subtract it from row 3,\n\n\\begin{equation}\n\\begin{pmatrix}\n2 & -1 & 3 & \\qquad 4 \\\\\n0 & 4 & -5 & \\qquad -7\\\\\n0 & 0 & 6 & \\qquad 7 \\\\\n\\end{pmatrix}\n\\end{equation}\n\nNow, the simplified equations are very easy to solve,\n\n\\begin{equation}\n6\\boldsymbol{x}_3 = 7 \\quad or, \\quad \\boldsymbol{x}_3 = 7/6 \n\\end{equation}\n\n\\begin{equation}\n4\\boldsymbol{x}_2 - 5\\boldsymbol{x}_3 = -7 \\quad or, \\quad 4\\boldsymbol{x}_2 - 35/6 = -7 \\quad or, \\quad \\boldsymbol{x}_2 = -7/24\n\\end{equation}\n\n\\begin{equation}\n2\\boldsymbol{x}_1 - \\boldsymbol{x}_{2}+3\\boldsymbol{x}_3 = 4 \\quad or, \\quad 2\\boldsymbol{x}_1 + 7/24 + 21/6 = 4 \\quad or, \\quad \\boldsymbol{x}_1 = 5/48\n\\end{equation} \n\n\nWe are solving this for a system $Ax=B$, the complexity of this whole process is somewhere around $O(n^3)$. In many matrix problems you do not only have to solve $Ax=B$, but also have to solve $Ax=C$, $Ax=D$, $Ax=E$ etc., where repeating the same process again and again becomes expensive. \n\nTherefore, a clever approach is to just drop the right side of the equation at first and decompose the matrix into lower part $\\boldsymbol{L}$ and upper part $\\boldsymbol{U}$. Where, $\\boldsymbol{U}$ is the simplified matrix and $\\boldsymbol{L}$ has the multipliers. Then the LU matrices can be repeatedly used to solve multiple systems of equations which is much cheaper. The common structure for these matrices are,\n\n\\begin{equation}\nL =\n\\begin{pmatrix}\n1 & 0 & 0 \\\\\nL_{21} & 1 & 0 \\\\\nL_{31} & L_{32} & 1 \\\\\n\\end{pmatrix}\n,\nU =\n\\begin{pmatrix}\nU_{11} & U_{12} & U_{13} \\\\\n0 & U_{22} & U_{23} \\\\\n0 & 0 & U_{33} \\\\\n\\end{pmatrix}\n\\end{equation}\n\nNow, let's drop the right side of the original system of equations and isolate the left side,\n\\begin{pmatrix}\n2 & -1 & 3 \\\\\n4 & 2 & 1 \\\\\n-6 & -1 & 2 \\\\\n\\end{pmatrix}\nLet's calculate the LU decomposition for this.\n\n\n\n\n\n\n```\nfrom sympy import Matrix\nfrom sympy import init_printing\n\nA = Matrix([[2,-1,3],\n [4,2,1],\n [-6,-1,2]])\nL, U, _ = A.LUdecomposition()\n\ninit_printing(use_latex='matplotlib')\nL\n```\n\n\n\n\n ⎡1 0 0⎤\n ⎢ ⎥\n ⎢2 1 0⎥\n ⎢ ⎥\n ⎣-3 -1 1⎦\n\n\n\n\n```\nU\n```\n\n\n\n\n ⎡2 -1 3 ⎤\n ⎢ ⎥\n ⎢0 4 -5⎥\n ⎢ ⎥\n ⎣0 0 6 ⎦\n\n\n\nUsing the symbolic python library we can directly compute the LU decomposition for any matrix. Our task for today will be to manually calculate the LU decomposition matrices. LU decompoition has different variants which involve pivoting and partial pivoting in order to avoid 0 on the diagonal and to reduce rounding error. For now, we'll avoid those and calculate in the simplest way possible using gaussian elimination.\n\nAn important factor to note: LU decomposition is not a unique value. There might be multiple LU decomposition for the same matrix. Therefore, your manually calculated LU decomposition and the values returned by python libraries may not match.\n\n\n```\nimport numpy as np\n\ndef LUDecomposition(M):\n #Initializing the Upper matrix that has to be simplified\n U = M\n #Initializing the Lower matrix as an identity matrix (all diagonals are 1)\n L = np.identity(U.shape[0])\n ###Use Gaussian elimination to populate both L and U##### \n print(\"L and U of Given Matrix b: \\n\",L,\"\\n\\n\",U,\"\\n\\n\")\n\n pivot = 0\n for i in range(1, len(U)):\n print(f\"\\n#### Iteration = {i}\")\n print(\"#################################################\")\n for row in range(i, len(U)):\n print(f\"\\n## row = {row}\")\n print(f\"\\npivot = {pivot}, U[{pivot}][{pivot}] = {U[pivot][pivot]}\")\n multiplier = U[row][pivot] / U[pivot][pivot]\n L[row][pivot] = multiplier\n print(f\"\\nmultiplier = {multiplier}\\n\")\n for col in range(len(U)):\n print(f\"col = {col}, U[{row}][{col}] = {U[row][col]}, U[{row-1}][{col}] = {U[row-1][col]}\")\n print(f\"{U[pivot][col]} - {U[pivot][col]} * {multiplier} = {U[pivot][col] * multiplier}\\n\")\n U[row][col] -= U[pivot][col] * multiplier\n print(U)\n pivot += 1\n \n return L, U\n\nb = np.array([[2,-1,3],\n [4,2,1],\n [-6,-1,2]])\n\n\nL, U = LUDecomposition(b)\nprint(\"\\n\\nL and U of Matrix b: \\n\",L,\"\\n\\n\",U,\"\\n\\n\")\n\n```\n\n L and U of Given Matrix b: \n [[1. 0. 0.]\n [0. 1. 0.]\n [0. 0. 1.]] \n \n [[ 2 -1 3]\n [ 4 2 1]\n [-6 -1 2]] \n \n \n \n #### Iteration = 1\n #################################################\n \n ## row = 1\n \n pivot = 0, U[0][0] = 2\n \n multiplier = 2.0\n \n col = 0, U[1][0] = 4, U[0][0] = 2\n 2 - 2 * 2.0 = 4.0\n \n col = 1, U[1][1] = 2, U[0][1] = -1\n -1 - -1 * 2.0 = -2.0\n \n col = 2, U[1][2] = 1, U[0][2] = 3\n 3 - 3 * 2.0 = 6.0\n \n [[ 2 -1 3]\n [ 0 4 -5]\n [-6 -1 2]]\n \n ## row = 2\n \n pivot = 0, U[0][0] = 2\n \n multiplier = -3.0\n \n col = 0, U[2][0] = -6, U[1][0] = 0\n 2 - 2 * -3.0 = -6.0\n \n col = 1, U[2][1] = -1, U[1][1] = 4\n -1 - -1 * -3.0 = 3.0\n \n col = 2, U[2][2] = 2, U[1][2] = -5\n 3 - 3 * -3.0 = -9.0\n \n [[ 2 -1 3]\n [ 0 4 -5]\n [ 0 -4 11]]\n \n #### Iteration = 2\n #################################################\n \n ## row = 2\n \n pivot = 1, U[1][1] = 4\n \n multiplier = -1.0\n \n col = 0, U[2][0] = 0, U[1][0] = 0\n 0 - 0 * -1.0 = -0.0\n \n col = 1, U[2][1] = -4, U[1][1] = 4\n 4 - 4 * -1.0 = -4.0\n \n col = 2, U[2][2] = 11, U[1][2] = -5\n -5 - -5 * -1.0 = 5.0\n \n [[ 2 -1 3]\n [ 0 4 -5]\n [ 0 0 6]]\n \n \n L and U of Matrix b: \n [[ 1. 0. 0.]\n [ 2. 1. 0.]\n [-3. -1. 1.]] \n \n [[ 2 -1 3]\n [ 0 4 -5]\n [ 0 0 6]] \n \n \n\n\nLet's go back to the original matrix form,\n\\begin{equation}\n\\begin{pmatrix}\n2 & -1 & 3 \\\\\n4 & 2 & 1 \\\\\n-6 & -1 & 2 \\\\\n\\end{pmatrix}\n\\begin{pmatrix}\n\\boldsymbol{x}_1 \\\\\n\\boldsymbol{x}_2 \\\\\n\\boldsymbol{x}_3 \n\\end{pmatrix}\n=\n\\begin{pmatrix}\n4 \\\\\n1 \\\\\n2\n\\end{pmatrix}\n\\end{equation}\n\nIf it is in the form $Ax=B$ then, \n\\begin{equation}\nA=\n\\begin{pmatrix}\n2 & -1 & 3 \\\\\n4 & 2 & 1 \\\\\n-6 & -1 & 2 \\\\\n\\end{pmatrix}\n,B=\n\\begin{pmatrix}\n4 \\\\\n1 \\\\\n2\n\\end{pmatrix}\n\\end{equation}\n\nWe already know that the LU decompositon of A is,\n\\begin{equation}\nL=\n\\begin{pmatrix}\n1 & 0 & 0 \\\\\n2 & 1 & 0 \\\\\n-3 & -1 & 1 \\\\\n\\end{pmatrix}\n,\nU=\n\\begin{pmatrix}\n2 & -1 & 3 \\\\\n0 & 4 & -5 \\\\\n0 & 0 & 6 \\\\\n\\end{pmatrix}\n\\end{equation}\n\nNow, Use $L$, $U$ and $B$ to solve the original system of equations. \n\n\nWe have to solve y for $Ly=B$\nOr, in this case,\n\\begin{equation}\n\\begin{pmatrix}\n1 & 0 & 0 \\\\\n2 & 1 & 0 \\\\\n-3 & -1 & 1 \\\\\n\\end{pmatrix}\n\\begin{pmatrix}\ny_1 \\\\\ny_2 \\\\\ny_3 \\\\\n\\end{pmatrix}\n=\n\\begin{pmatrix}\n4 \\\\\n1 \\\\\n2\n\\end{pmatrix}\n\\end{equation}\nIt can be solved by forward substitution. It is an iterative process that can be implemented with a nested loop. \n\\begin{equation}\n\\boldsymbol{y}_1 = 4 \n\\end{equation}\n\n\\begin{equation}\n2\\boldsymbol{y}_1 + \\boldsymbol{y}_2 = 1 \\quad or, \\quad 8 + \\boldsymbol{y}_2 = 1 \\quad or, \\quad \\boldsymbol{y}_2 = -7\n\\end{equation}\n\n\\begin{equation}\n-3\\boldsymbol{y}_1 - \\boldsymbol{y}_{2}+\\boldsymbol{y}_3 = 2 \\quad or, \\quad -12 + 7 + \\boldsymbol{y}_3 = 2 \\quad or, \\quad \\boldsymbol{y}_3 = 7\n\\end{equation} \n\n\nAfter solving $y$, in order to calculate $x$ we need to solve, \n$Ux = y$ or,\n\\begin{equation}\n\\begin{pmatrix}\n2 & -1 & 3 \\\\\n0 & 4 & -5 \\\\\n0 & 0 & 6 \\\\\n\\end{pmatrix}\n\\begin{pmatrix}\nx_1 \\\\\nx_2 \\\\\nx_3 \\\\\n\\end{pmatrix}\n=\n\\begin{pmatrix}\ny_1 \\\\\ny_2 \\\\\ny_3 \\\\\n\\end{pmatrix}\n\t\t\\Longrightarrow\n \\begin{pmatrix}\n2 & -1 & 3 \\\\\n0 & 4 & -5 \\\\\n0 & 0 & 6 \\\\\n\\end{pmatrix}\n\\begin{pmatrix}\nx_1 \\\\\nx_2 \\\\\nx_3 \\\\\n\\end{pmatrix}\n=\n\\begin{pmatrix}\n4 \\\\\n-7 \\\\\n7 \\\\\n\\end{pmatrix}\n\\end{equation}\nWhich can be done through backward substitution.\n\nIf you find it hard to iterate backwards, you can just flip $U$, $x$ and $y$, then it results into,\n\\begin{equation}\n\\begin{pmatrix}\n6 & 0 & 0 \\\\\n-5 & 4 & 0 \\\\\n3 & -1 & 2 \\\\\n\\end{pmatrix}\n\\begin{pmatrix}\nx_3 \\\\\nx_2 \\\\\nx_1 \\\\\n\\end{pmatrix}\n=\n\\begin{pmatrix}\n7 \\\\\n-7 \\\\\n4 \\\\\n\\end{pmatrix}\n\\end{equation}\n\nSolving which would be the same as the forward substitution!\n\nThe forward substitution part is done for you. Complete the backward substitution part for correct output.\n\n\n```\nimport numpy as np\nL = np.array([[1,0,0],\n [2,1,0],\n [-3,-1,1]])\n\nU = np.array([[2,-1,3],\n [0,4,-5],\n [0,0,6]])\n\nB = np.array([4,1,2])\n\n\n#Forward Substitution process\nB_L = np.zeros(B.shape[0]) \n\nfor i in range(L.shape[0]):\n summation=0\n for j in range(L.shape[0]):\n if i == j:\n B_L[j] = B[j] - summation\n B_L[j] = B_L[j]/L[i,j]\n break\n else:\n summation = summation + L[i,j]*B_L[j]\n\n# Backward Substitution, your task is to complete this task\n#Flip the U and B_L matrices if necessary using np.flip(array, axis) method\nU = np.flip(U, 0)\nU = np.flip(U, 1)\nB_L = np.flip(B)\n\nB_LU = np.zeros(B.shape[0]) \n#Use U and B_L to populate B_LU, just like how L and B was used to populate B_L in forward substitution\n\n#Place your code here (You may need nested loop)\n\nfor i in range(L.shape[0]):\n summation=0\n for j in range(L.shape[0]):\n if i == j:\n B_LU[j] = B_L[j] - summation\n B_LU[j] = B_LU[j]/L[i,j]\n break\n else:\n summation = summation + U[i,j]*B_LU[j]\n\n################################################################\n\n\nfinal_result = np.flip(B_LU)\n\nprint(final_result)\n\n```\n\n [0. 0. 0.]\n\n\nBoth the forward and the backward substitution method can accomplish the task with $O(n^2)$ complexity!\n", "meta": {"hexsha": "b39046a7312bd7d1922200cda8c623c3d0bff989", "size": 13581, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "LU Decomposition.ipynb", "max_stars_repo_name": "sheikhmishar/Numerical-Analysis-Python", "max_stars_repo_head_hexsha": "03a737ba38b372fb52ad773f52cd029f7da2b307", "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": "LU Decomposition.ipynb", "max_issues_repo_name": "sheikhmishar/Numerical-Analysis-Python", "max_issues_repo_head_hexsha": "03a737ba38b372fb52ad773f52cd029f7da2b307", "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": "LU Decomposition.ipynb", "max_forks_repo_name": "sheikhmishar/Numerical-Analysis-Python", "max_forks_repo_head_hexsha": "03a737ba38b372fb52ad773f52cd029f7da2b307", "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": 13581.0, "max_line_length": 13581, "alphanum_fraction": 0.5939179736, "converted": true, "num_tokens": 4156, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248242542283, "lm_q2_score": 0.939024817002038, "lm_q1q2_score": 0.8817676137556976}} {"text": "# Exercise 2\nWrite a function to compute the roots of a mathematical equation of the form\n\\begin{align}\n ax^{2} + bx + c = 0.\n\\end{align}\nYour function should be sensitive enough to adapt to situations in which a user might accidentally set $a=0$, or $b=0$, or even $a=b=0$. For example, if $a=0, b\\neq 0$, your function should print a warning and compute the roots of the resulting linear function. It is up to you on how to handle the function header: feel free to use default keyword arguments, variable positional arguments, variable keyword arguments, or something else as you see fit. Try to make it user friendly.\n\nYour function should return a tuple containing the roots of the provided equation.\n\n**Hint:** Quadratic equations can have complex roots of the form $r = a + ib$ where $i=\\sqrt{-1}$ (Python uses the notation $j=\\sqrt{-1}$). To deal with complex roots, you should import the `cmath` library and use `cmath.sqrt` when computing square roots. `cmath` will return a complex number for you. You could handle complex roots yourself if you want, but you might as well use available libraries to save some work.\n\n\n```python\nimport cmath\nimport math\n\ndef find_roots(a,b,c):\n #check if quadratic quadratic function\n if (a == 0):\n if(b==0):\n print(\"Error: This is not a function!\")\n else:\n #linear function find root & give warning\n print(\"WARNING: This is the not a quadratic function!\")\n print(\"The root of this linear function is:\" )\n print(-c/b)\n else:\n # calculate the discriminant\n d = (b**2) - (4*a*c)\n\n # find roots of quadratic\n if (d<0):\n sqrt = cmath.sqrt(d)\n root1 = (-b - sqrt)/(2*a)\n root2 = (-b + sqrt)/(2*a)\n print(\"The roots of this function are complex:\" )\n elif (d>0):\n sqrt = math.sqrt(d)\n root1 = (-b -sqrt)/(2*a)\n root2 = (-b + sqrt)/(2*a)\n print(\"The roots of this function are real:\" )\n print(root1)\n print (root2)\n\nfind_roots(0,0.5,2)\nfind_roots(1,0,-1)\n```\n\n WARNING: This is the not a quadratic function!\n The root of this linear function is:\n -4.0\n The roots of this function are real:\n -1.0\n 1.0\n\n", "meta": {"hexsha": "f11de631966dd1cb1ac6d95acbfe537ec894ae1f", "size": 3420, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "lectures/L5/Exercise_2-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": "lectures/L5/Exercise_2-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": "lectures/L5/Exercise_2-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": 35.625, "max_line_length": 495, "alphanum_fraction": 0.5368421053, "converted": true, "num_tokens": 584, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693731004241, "lm_q2_score": 0.9284087960985614, "lm_q1q2_score": 0.8816813993718403}} {"text": "#
Polinomios
\n\nUna de las virtudes de Sympy es que puede realizar operaciones con expresiones algebraicas. Las más simples de estas expresiones algebraicas son los polinomios. Sin embargo Sympy no reconoce, por defecto, a las letras, como expresiones algebraicas (en principio para Python las letras son nombres de variables). Para informar a Sympy de que vamos a trabajar con una letra debemos utilizar la función **symbols**.\n\n\n```python\nfrom sympy import *\ninit_printing()\nx = symbols('x')\ny = symbols('y')\n```\n\nPara desarrollar polinomios utilizamos el comando **expand**. De esta forma podemos simplificar todos las operaciones combinadas donde aparezcan sumas, restas, productos y potencias. Aunque esta función tiene muchos argumentos optativos, en principio la usaremos del modo más sencillo.\n\n###
Realiza las siguientes operaciones con polinomios:
\n\n\n* $x^3+(3x^2+7)(4x-1)+(2x-3)^4$\n\n\n* $(4x^2+5)^2$\n\n\n* $(x+y)^3$\n\n\n```python\nexpand(x**3 +(3*x**2+7)*(4*x-1))\n```\n\n\n```python\nsimplify((x+y)**3)\n```\n\nPara realizar una división euclídea de polinomios utilizamos la función **div**. Esta nos devuelve dos resultados en forma de lista: el primero es el cociente y el segundo es el resto.\n\n###
Realiza la siguiente división de polinomios, comprobando el resultado:
\n\n\n* $(x^3+5x^2-3x+2):(4x-3)$\n\n\n```python\n\n```\n\n\n```python\n\n```\n\nPara factorizar polinomios en una variable, podemos utilizar el comando **factor**.\n\n###
Factoriza los siguientes polinomios y comprueba el resultado:
\n\n\n* $p= x^4-x^3-7x^2+13x-6 \\qquad q= x^3-5x^2+8x-4$\n\n\n```python\n\n```\n\n\n```python\nfactor(q)\n```\n\n###
Calcula el máximo común denominador y el mínimo común múltiplo de los polinomios anteriores.
\n\n\n```python\nlcm(p,q)\n```\n\nPara sustituir una letra por un número o por una expresión, se utiliza el método **subs**. A este le debemos facilitar dos argumentos: el primero es la letra que queremos sustituir, y el segundo debe ser el número o expresión por la que lo vamos a sustituir.\n\n###
Calcula el valor de $p(x)$ cuando $x$ es 5 y cuando $x$ es 1. Sustituye $x$ por $y^2-1$.
\n\n\n```python\n\n```\n\nAunque lo veremos en más profundidad en otro notebook, el comando para encontrar las raíces de un polinomios el **solve**.\n\n###
Resuelve la ecuación $p(x)=0$.
\n\n\n```python\n\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "b0be9b3f688ef116ee757743463462a962d08b51", "size": 13312, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/05.- Polinomios.ipynb", "max_stars_repo_name": "disoftw/python-for-maths", "max_stars_repo_head_hexsha": "39d80cc7fe2584a0b5de01151bda361260e0ab1a", "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/05.- Polinomios.ipynb", "max_issues_repo_name": "disoftw/python-for-maths", "max_issues_repo_head_hexsha": "39d80cc7fe2584a0b5de01151bda361260e0ab1a", "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/05.- Polinomios.ipynb", "max_forks_repo_name": "disoftw/python-for-maths", "max_forks_repo_head_hexsha": "39d80cc7fe2584a0b5de01151bda361260e0ab1a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-11-26T04:54:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-26T04:54:09.000Z", "avg_line_length": 46.5454545455, "max_line_length": 2466, "alphanum_fraction": 0.7352764423, "converted": true, "num_tokens": 746, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541610257063, "lm_q2_score": 0.9362850093037731, "lm_q1q2_score": 0.8816566749168901}} {"text": "## Number Theory with Sympy's Sieve\n\nAn infinite list of prime numbers, implemented as a dynamically growing sieve of Eratosthenes. When a lookup is requested involving an odd number that has not been sieved, the sieve is automatically extended up to that number.\n\n\n```python\nfrom sympy import sieve\n```\n\n\n```python\nsieve._reset()\n25 in sieve\n```\n\n\n\n\n False\n\n\n\n\n```python\nsieve._list\n```\n\n\n\n\n array('l', [2, 3, 5, 7, 11, 13, 17, 19, 23])\n\n\n\n\n```python\n# Grow the sieve to cover all primes <= n\nsieve._reset()\nsieve.extend(30)\nsieve[10] == 28\n```\n\n\n\n\n False\n\n\n\n\n```python\nsieve[10] == 29\n```\n\n\n\n\n True\n\n\n\n\n```python\nsieve[10] == 23\n```\n\n\n\n\n False\n\n\n\n\n```python\n# Extend to include the ith prime number\nsieve._reset()\nsieve.extend_to_no(9)\nsieve._list\n```\n\n\n\n\n array('l', [2, 3, 5, 7, 11, 13, 17, 19, 23])\n\n\n\n\n```python\n# $primerange(a,b)$\n\nprint([i for i in sieve.primerange(7, 23)])\n```\n\n [7, 11, 13, 17, 19]\n\n\n\n```python\n# Search = returns the indice i, j of the primes that bound n\n#if n is prime then i = j\n\nsieve.search(25)\n```\n\n\n\n\n (9, 10)\n\n\n\n\n```python\nsieve.search(23)\n```\n\n\n\n\n (9, 9)\n\n\n\n\n```python\n# Prime\n# Return the nth prime, with the primes indexed as prime(1) = 2, prime(2) = 3, etc…. \n# The nth prime is approximately n*log(n).\nfrom sympy import prime\nprime(10)\n```\n\n\n\n\n 29\n\n\n\n## Primes \n\n\n```python\nprime(1)\n```\n\n\n\n\n 2\n\n\n\n\n```python\n%time\nprime(1000000)\n```\n\n CPU times: user 3 µs, sys: 0 ns, total: 3 µs\n Wall time: 6.91 µs\n\n\n\n\n\n 15485863\n\n\n\n\n```python\n# primepi(n) - gives n number of primes\n\nfrom sympy import primepi\nprimepi(25)\n```\n\n\n\n\n 9\n\n\n\n\n```python\n%time\nprimepi(1000000)\n```\n\n CPU times: user 3 µs, sys: 0 ns, total: 3 µs\n Wall time: 6.91 µs\n\n\n\n\n\n 78498\n\n\n\n\n```python\nfrom sympy import nextprime\n[(i, nextprime(i)) for i in range(10, 15)]\n```\n\n\n\n\n [(10, 11), (11, 13), (12, 13), (13, 17), (14, 17)]\n\n\n\n\n```python\nfrom sympy import prevprime\n[(i, prevprime(i)) for i in range(10, 15)]\n```\n\n\n\n\n [(10, 7), (11, 7), (12, 11), (13, 11), (14, 13)]\n\n\n\n## Prime Ranges\n\nSome famous conjectures about the occurence of primes in a given range are [1]:\n\n**Twin primes**: though often not, the following will give 2 primes\nan infinite number of times:\nprimerange(6*n - 1, 6*n + 2)\n\n**Legendre’s**: the following always yields at least one prime\n`primerange(n**2, (n+1)**2+1)`\n\n**Bertrand’s (proven)**: there is always a prime in the range\n`primerange(n, 2*n)`\n\n**Brocard’s**: there are at least four primes in the range\n`primerange(prime(n)**2, prime(n+1)**2)`\n\nThe average gap between primes is log(n) [2]; the gap between primes can be arbitrarily large since sequences of composite numbers are arbitrarily large, e.g. the numbers in the sequence `n! + 2, n! + 3 … n! + n` are all composite.\n\n\n```python\nfrom sympy import primerange, sieve\nprint([i for i in primerange(1, 30)])\n```\n\n [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]\n\n\n\n```python\nlist(sieve.primerange(1, 30))\n```\n\n\n\n\n [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]\n\n\n\n\n```python\n# randprime\nfrom sympy import randprime, isprime\nrandprime(1, 30)\n```\n\n\n\n\n 19\n\n\n\n\n```python\nisprime(randprime(1, 30))\n```\n\n\n\n\n True\n\n\n\n\n```python\n# This returns the product of the first n primes or teh primes <= n (when nth=False)\nfrom sympy.ntheory.generate import primorial, randprime, primerange\nfrom sympy import factorint, Mul, primefactors, sqrt\nprimorial(5) # product of 2, 3, 5, 7, 11\n```\n\n\n\n\n 2310\n\n\n\n\n```python\n2*3*5*7*11\n```\n\n\n\n\n 2310\n\n\n\n\n```python\nprimorial(2)\n```\n\n\n\n\n 6\n\n\n\n\n```python\nprimorial(3, nth=False) # primes <= 3 are 2 and 3\n```\n\n\n\n\n 6\n\n\n\n\n```python\nprimorial(5, nth=False) # product of 2*3*5\n```\n\n\n\n\n 30\n\n\n\n\n```python\nprimorial(sqrt(100), nth=False)\n```\n\n\n\n\n 210\n\n\n\n\n```python\n# Adding or subtracting by 1 of a primorial product gives you a prime\nfactorint(primorial(5) - 1)\n```\n\n\n\n\n {2309: 1}\n\n\n\n\n```python\n# here we get two new primes that are factors\nfactorint(primorial(7) - 1)\n```\n\n\n\n\n {61: 1, 8369: 1}\n\n\n\n\n```python\n# Some primes smaller and larger than the primes multiplied together\np = list(primerange(10, 20))\nsorted(set(primefactors(Mul(*p) + 1)).difference(set(p)))\n```\n\n\n\n\n [2, 5, 31, 149]\n\n\n\n### cycle_length\n\n$cycle_length(f, x0, nmax=None, values=False)$\n\nFor a given iterated sequence, return a generator that gives the length of the iterated cycle (lambda) and the length of terms before the cycle begins (mu); if values is True then the terms of the sequence will be returned instead. The sequence is started with value x0.\n\nNote: more than the first lambda + mu terms may be returned and this is the cost of cycle detection with Brent’s method; there are, however, generally less terms calculated than would have been calculated if the proper ending point were determined, e.g. by using Floyd’s method.\n\n\n```python\nfrom sympy.ntheory.generate import cycle_length # will give succesive values of i <- func(i)\n\n```\n\n\n```python\ndef iter(func, i):\n while 1:\n ii = func(1)\n yield ii\n i = ii\n# give a seed of 4 and the mu and lambda terms\nfunc = lambda i: (i**2 + 1) % 51\n```\n\n\n```python\nnext(cycle_length(func, 4))\n```\n\n\n\n\n (6, 2)\n\n\n\n\n```python\nn = cycle_length(func, 4, values=True)\nlist(ni for ni in n)\n```\n\n\n\n\n [17, 35, 2, 5, 26, 14, 44, 50, 2, 5, 26, 14]\n\n\n\n### composite(nth)\n\nReturn the nth composite number, with the composite numbers indexed as composite(1) = 4, composite(2) = 6, etc…. \n\n\n```python\nfrom sympy import composite\ncomposite(24)\n```\n\n\n\n\n 36\n\n\n\n\n```python\ncomposite(1)\n```\n\n\n\n\n 4\n\n\n\n### compositepi\n\n\n```python\nfrom sympy import compositepi\ncompositepi(20)\n```\n\n\n\n\n 11\n\n\n\n### smoothness_p(n, m=-1, power=0, visual=None)\n\nReturn a list of $[m, (p, (M, sm(p + m), psm(p + m)))…]$ where:\n\n1. $p**M$ is the base-p divisor of n\n2. $sm(p + m)$ is the smoothness of $p + m (m = -1 by default)$\n3. $psm(p + m)$ is the power smoothness of $p + m$\n\nThe list is sorted according to smoothness (default) or by power smoothness if power=1.\n\nThe smoothness of the numbers to the left (m = -1) or right (m = 1) of a factor govern the results that are obtained from the p +/- 1 type factoring methods.\n\n\n```python\nfrom sympy.ntheory.factor_ import smoothness_p, factorint\nsmoothness_p(10345, m=1)\n```\n\n\n\n\n (1, [(5, (1, 3, 3)), (2069, (1, 23, 23))])\n\n\n\n\n```python\nsmoothness_p(10345)\n```\n\n\n\n\n (-1, [(5, (1, 2, 4)), (2069, (1, 47, 47))])\n\n\n\n\n```python\nsmoothness_p(10345, power=1)\n```\n\n\n\n\n (-1, [(5, (1, 2, 4)), (2069, (1, 47, 47))])\n\n\n\n\n```python\nprint(smoothness_p(344556576677878, visual=1))\n```\n\n p**i=2**1 has p-1 B=1, B-pow=1\n p**i=172278288338939**1 has p-1 B=18836462753, B-pow=18836462753\n\n\n\n```python\nfactorint(15*11)\n```\n\n\n\n\n {3: 1, 5: 1, 11: 1}\n\n\n\n\n```python\nsmoothness_p(_)\n```\n\n\n\n\n 'p**i=3**1 has p-1 B=2, B-pow=2\\np**i=5**1 has p-1 B=2, B-pow=4\\np**i=11**1 has p-1 B=5, B-pow=5'\n\n\n\n\n```python\nsmoothness_p(_)\n```\n\n\n\n\n {3: 1, 5: 1, 11: 1}\n\n\n\n### Table for output logic is like this\n\n#### Visual\n\n| Input | True | False | Other |\n|---------------|-------------|-------------|-------------|\n| ``str`` |``str`` |``tuple`` |``str`` |\n| ``str`` |``str`` |``tuple`` |``dict`` |\n| ``tuple`` |``str`` |``tuple`` |``str`` |\n| ``n`` |``str`` |``tuple`` |``tuple`` |\n| ``mul`` |``str`` |``tuple`` |``tuple`` |\n\n\n```python\n# training(n)\n# Count the number of trailing zero digits in the binary representation of n, \n# i.e. determine the largest power of 2 that divides n.\nfrom sympy import trailing\ntrailing(128)\n```\n\n\n\n\n 7\n\n\n\n\n```python\ntrailing(51)\n```\n\n\n\n\n 0\n\n\n\n\n```python\n# multiplicity\n# Find the greatest integer m such that p**m divides n.\nfrom sympy.ntheory import multiplicity\nfrom sympy.core.numbers import Rational as R\n[multiplicity(5, n) for n in [8, 5, 25, 125, 250]]\n```\n\n\n\n\n [0, 1, 2, 3, 3]\n\n\n\n\n```python\nmultiplicity(3, R(1, 9))\n```\n\n\n\n\n -2\n\n\n\n### sympy.ntheory.factor_.perfect_power\n\nsympy.ntheory.factor_.perfect_power(n, candidates=None, big=True, factor=True)\n\nReturn `(b, e)` such that `n == b**e` if n is a perfect power; otherwise return False.\n\nBy default, the base is recursively decomposed and the exponents collected so the largest possible e is sought. If big=False then the smallest possible e (thus prime) will be chosen.\n\nIf `candidates` for exponents are given, they are assumed to be sorted and the first one that is larger than the computed maximum will signal failure for the routine.\n\nIf `factor=True` then simultaneous factorization of n is attempted since finding a factor indicates the only possible root for n. This is True by default since only a few small factors will be tested in the course of searching for the perfect power.\n\n\n\n\n```python\nfrom sympy import perfect_power\nperfect_power(16)\n```\n\n\n\n\n (2, 4)\n\n\n\n\n```python\nperfect_power(25, big=False)\n```\n\n\n\n\n (5, 2)\n\n\n\n### Pollard_rho\n\nUse Pollard’s rho method to try to extract a nontrivial factor of n. The returned factor may be a composite number. If no factor is found, None is returned.\n\nThe algorithm generates pseudo-random values of x with a generator function, replacing x with F(x). If F is not supplied then the function x**2 + a is used. The first value supplied to F(x) is s. Upon failure (if retries is > 0) a new a and s will be supplied; the a will be ignored if F was supplied.\n\nThe sequence of numbers generated by such functions generally have a a lead-up to some number and then loop around back to that number and begin to repeat the sequence, e.g. 1, 2, 3, 4, 5, 3, 4, 5 – this leader and loop look a bit like the Greek letter rho, and thus the name, ‘rho’.\n\nFor a given function, very different leader-loop values can be obtained so it is a good idea to allow for retries:\n\n\n```python\nfrom sympy.ntheory.generate import cycle_length\nn = 14345656\nF = lambda x:(2048*pow(x, 2, n) + 32767) % n\nfor s in range(5):\n print('loop length = %4i; leader length = %3i' % next(cycle_length(F, s)))\n```\n\n loop length = 660; leader length = 19\n loop length = 660; leader length = 19\n loop length = 120; leader length = 26\n loop length = 660; leader length = 6\n loop length = 660; leader length = 17\n\n\n\n```python\n# An explicit example where there is a two element leadup to a seq of 3 numbers\nx = 2\nfor i in range(9):\n x = (x**2 + 12)%17\n print(x)\n```\n\n 16\n 13\n 11\n 14\n 4\n 11\n 14\n 4\n 11\n\n\n\n```python\nnext(cycle_length(lambda x:(x**2+12)%17, 2))\n```\n\n\n\n\n (3, 2)\n\n\n\n\n```python\nlist(cycle_length(lambda x: (x**2+12)%17, 2, values=True))\n```\n\n\n\n\n [16, 13, 11, 14, 4]\n\n\n\n### Note\n\nInstead of checking the differences of all generated values for a gcd with n, only the $kth$ and $2*kth$ numbers are checked, e.g. 1st and 2nd, 2nd and 4th, 3rd and 6th until it has been detected that the loop has been traversed. Loops may be many thousands of steps long before rho finds a factor or reports failure. If max_steps is specified, the iteration is cancelled with a failure after the specified number of steps.\n\n\n```python\nfrom sympy import pollard_rho\nn = 14345656\nF = lambda x:(2048*pow(x,2,n) + 32767) % n\npollard_rho(n, F=F)\n```\n\n\n\n\n 8\n\n\n\n\n```python\npollard_rho(n, a=n-2, retries=1)\n```\n\n\n\n\n 8\n\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "943b80ad53e4270fe76872e0e554f52cf135600f", "size": 28032, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "sympy/Number Theory.ipynb", "max_stars_repo_name": "DanielMabadeje/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials", "max_stars_repo_head_hexsha": "7adab3877fc1d3f1d5f57e6c1743dae8f76f72c5", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3266, "max_stars_repo_stars_event_min_datetime": "2017-08-06T16:51:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T07:34:24.000Z", "max_issues_repo_path": "sympy/Number Theory.ipynb", "max_issues_repo_name": "nuhaltinsoy/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials", "max_issues_repo_head_hexsha": "6017441f2d476f9c6c568dd886da43c6c0fd89bd", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 150, "max_issues_repo_issues_event_min_datetime": "2017-08-28T14:59:36.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-11T23:21:35.000Z", "max_forks_repo_path": "sympy/Number Theory.ipynb", "max_forks_repo_name": "nuhaltinsoy/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials", "max_forks_repo_head_hexsha": "6017441f2d476f9c6c568dd886da43c6c0fd89bd", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1449, "max_forks_repo_forks_event_min_datetime": "2017-08-06T17:40:59.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T12:03:24.000Z", "avg_line_length": 20.7952522255, "max_line_length": 429, "alphanum_fraction": 0.4852311644, "converted": true, "num_tokens": 3622, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418158002492, "lm_q2_score": 0.9539660989095221, "lm_q1q2_score": 0.8815999628581259}} {"text": "# Modeling and Simulation in Python\n\nChapter 9\n\nCopyright 2017 Allen Downey\n\nLicense: [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0)\n\n\n\n```python\n# Configure Jupyter to display the assigned value after an assignment\n%config InteractiveShell.ast_node_interactivity='last_expr_or_assign'\n\n# import everything from SymPy.\nfrom sympy import *\n\n# Set up Jupyter notebook to display math.\ninit_printing() \n```\n\nThe following displays SymPy expressions and provides the option of showing results in LaTeX format.\n\n\n```python\nfrom sympy.printing import latex\n\ndef show(expr, show_latex=False):\n \"\"\"Display a SymPy expression.\n \n expr: SymPy expression\n show_latex: boolean\n \"\"\"\n if show_latex:\n print(latex(expr))\n return expr\n```\n\n### Analysis with SymPy\n\nCreate a symbol for time.\n\n\n```python\nt = symbols('t')\n```\n\nIf you combine symbols and numbers, you get symbolic expressions.\n\n\n```python\nexpr = t + 1\n```\n\nThe result is an `Add` object, which just represents the sum without trying to compute it.\n\n\n```python\ntype(expr)\n```\n\n\n\n\n sympy.core.add.Add\n\n\n\n`subs` can be used to replace a symbol with a number, which allows the addition to proceed.\n\n\n```python\nexpr.subs(t, 2)\n```\n\n`f` is a special class of symbol that represents a function.\n\n\n```python\nf = Function('f')\n```\n\n\n\n\n f\n\n\n\nThe type of `f` is `UndefinedFunction`\n\n\n```python\ntype(f)\n```\n\n\n\n\n sympy.core.function.UndefinedFunction\n\n\n\nSymPy understands that `f(t)` means `f` evaluated at `t`, but it doesn't try to evaluate it yet.\n\n\n```python\nf(t)\n```\n\n`diff` returns a `Derivative` object that represents the time derivative of `f`\n\n\n```python\ndfdt = diff(f(t), t)\n```\n\n\n```python\ntype(dfdt)\n```\n\n\n\n\n sympy.core.function.Derivative\n\n\n\nWe need a symbol for `alpha`\n\n\n```python\nalpha = symbols('alpha')\n```\n\nNow we can write the differential equation for proportional growth.\n\n\n```python\neq1 = Eq(dfdt, alpha*f(t))\n```\n\nAnd use `dsolve` to solve it. The result is the general solution.\n\n\n```python\nsolution_eq = dsolve(eq1)\n```\n\nWe can tell it's a general solution because it contains an unspecified constant, `C1`.\n\nIn this example, finding the particular solution is easy: we just replace `C1` with `p_0`\n\n\n```python\nC1, p_0 = symbols('C1 p_0')\n```\n\n\n```python\nparticular = solution_eq.subs(C1, p_0)\n```\n\nIn the next example, we have to work a little harder to find the particular solution.\n\n### Solving the quadratic growth equation \n\nWe'll use the (r, K) parameterization, so we'll need two more symbols:\n\n\n```python\nr, K = symbols('r K')\n```\n\nNow we can write the differential equation.\n\n\n```python\neq2 = Eq(diff(f(t), t), r * f(t) * (1 - f(t)/K))\n```\n\nAnd solve it.\n\n\n```python\nsolution_eq = dsolve(eq2)\n```\n\nThe result, `solution_eq`, contains `rhs`, which is the right-hand side of the solution.\n\n\n```python\ngeneral = solution_eq.rhs\n```\n\nWe can evaluate the right-hand side at $t=0$\n\n\n```python\nat_0 = general.subs(t, 0)\n```\n\nNow we want to find the value of `C1` that makes `f(0) = p_0`.\n\nSo we'll create the equation `at_0 = p_0` and solve for `C1`. Because this is just an algebraic identity, not a differential equation, we use `solve`, not `dsolve`.\n\nThe result from `solve` is a list of solutions. In this case, [we have reason to expect only one solution](https://en.wikipedia.org/wiki/Picard%E2%80%93Lindel%C3%B6f_theorem), but we still get a list, so we have to use the bracket operator, `[0]`, to select the first one.\n\n\n```python\nsolutions = solve(Eq(at_0, p_0), C1)\ntype(solutions), len(solutions)\n```\n\n\n\n\n (list, 1)\n\n\n\n\n```python\nvalue_of_C1 = solutions[0]\n```\n\nNow in the general solution, we want to replace `C1` with the value of `C1` we just figured out.\n\n\n```python\nparticular = general.subs(C1, value_of_C1)\n```\n\nThe result is complicated, but SymPy provides a method that tries to simplify it.\n\n\n```python\nparticular = simplify(particular)\n```\n\nOften simplicity is in the eye of the beholder, but that's about as simple as this expression gets.\n\nJust to double-check, we can evaluate it at `t=0` and confirm that we get `p_0`\n\n\n```python\nparticular.subs(t, 0)\n```\n\nThis solution is called the [logistic function](https://en.wikipedia.org/wiki/Population_growth#Logistic_equation).\n\nIn some places you'll see it written in a different form:\n\n$f(t) = \\frac{K}{1 + A e^{-rt}}$\n\nwhere $A = (K - p_0) / p_0$.\n\nWe can use SymPy to confirm that these two forms are equivalent. First we represent the alternative version of the logistic function:\n\n\n```python\nA = (K - p_0) / p_0\n```\n\n\n```python\nlogistic = K / (1 + A * exp(-r*t))\n```\n\nTo see whether two expressions are equivalent, we can check whether their difference simplifies to 0.\n\n\n```python\nsimplify(particular - logistic)\n```\n\nThis test only works one way: if SymPy says the difference reduces to 0, the expressions are definitely equivalent (and not just numerically close).\n\nBut if SymPy can't find a way to simplify the result to 0, that doesn't necessarily mean there isn't one. Testing whether two expressions are equivalent is a surprisingly hard problem; in fact, there is no algorithm that can solve it in general.\n\n### Exercises\n\n**Exercise:** Solve the quadratic growth equation using the alternative parameterization\n\n$\\frac{df(t)}{dt} = \\alpha f(t) + \\beta f^2(t) $\n\n\n```python\nalpha = symbols('alpha')\nbeta = symbols('beta')\nf = Function('f')\nt = symbols('t')\n```\n\n\n```python\nquad_growth_expression = alpha*f(t) + beta*f(t)**2\n```\n\n\n```python\neq_quad = Eq(dfdt, quad_growth_expression)\n```\n\n\n```python\nsolution_eq_quad = dsolve(eq_quad)\n```\n\n\n```python\n# Solution goes here\n```\n\n\n```python\n# Solution goes here\n```\n\n\n```python\n# Solution goes here\n```\n\n**Exercise:** Use [WolframAlpha](https://www.wolframalpha.com/) to solve the quadratic growth model, using either or both forms of parameterization:\n\n df(t) / dt = alpha f(t) + beta f(t)^2\n\nor\n\n df(t) / dt = r f(t) (1 - f(t)/K)\n\nFind the general solution and also the particular solution where `f(0) = p_0`.\n\n\n```python\n\n```\n", "meta": {"hexsha": "d54b2e0a12710ed60e7aabd9f506aa0b70b859ab", "size": 45956, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "code/chap09mine.ipynb", "max_stars_repo_name": "Griffith-Stites/ModSimPy", "max_stars_repo_head_hexsha": "3cfc30639928d091b7082e9e34062a1e25371d09", "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": "code/chap09mine.ipynb", "max_issues_repo_name": "Griffith-Stites/ModSimPy", "max_issues_repo_head_hexsha": "3cfc30639928d091b7082e9e34062a1e25371d09", "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": "code/chap09mine.ipynb", "max_forks_repo_name": "Griffith-Stites/ModSimPy", "max_forks_repo_head_hexsha": "3cfc30639928d091b7082e9e34062a1e25371d09", "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.1228230981, "max_line_length": 2212, "alphanum_fraction": 0.7119636174, "converted": true, "num_tokens": 1628, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9688561726126036, "lm_q2_score": 0.9099070151996071, "lm_q1q2_score": 0.8815690281796495}} {"text": "$$\n\\huge \\text{Deriving the Quadratic Formula with SymPy}\\\\\n\\large \\text{Andrew Ribeiro}\\\\\n\\text{December 2017}\n$$\n\n\n```python\nimport sympy as sp\nfrom IPython.display import display\nsp.init_printing(order=\"lex\",use_latex='mathjax')\n```\n\nQuadratic equations are of the form: \n\n$$ ax^2 + bx^1 + cx^0 = ax^2 + bx + c = 0$$\n\nWhere $a,b,c$ are coeficients. The coeficients can be integers, real numbers, or imaginary numbers. We know from the quadratic formula that such equations can be solved for x by completing the square. In this exercise we will use SymPy to help us derive the quadratic formula. Let's first define some symbols we will use in our symbolic calculations. \n\n\n```python\na,b,c = sp.symbols(\"a b c\")\nz,k = sp.symbols(\"z k\")\nx = sp.symbols(\"x\")\n```\n\nNow we can easily represent the quadratic equation.\n\n\n```python\nlhs = a*x**2 + b*x + c\nrhs = 0 \nquadraticEqn = sp.Eq(lhs,rhs)\nquadraticEqn\n```\n\n\n\n\n$$a x^{2} + b x + c = 0$$\n\n\n\n## Completing the square \n\nBefore we start our derivation, let's talk about completing the square. Say we have binomial rased to a power. \n\n\n```python\nf =(a+b)**2\nf\n```\n\n\n\n\n$$\\left(a + b\\right)^{2}$$\n\n\n\nIf we expand this we get the form: \n\n\n```python\nfExp = f.expand()\nfExp\n```\n\n\n\n\n$$a^{2} + 2 a b + b^{2}$$\n\n\n\nGoing from this expanded form back to the binomial is called *factoring.*\n\n\n```python\nfExp.factor()\n```\n\n\n\n\n$$\\left(a + b\\right)^{2}$$\n\n\n\nWe use SymPy to define a function for completing the square of a symbolic polynomial. This will work for different types of polynomials, but in the case of a quadratic, this works by solving for $z$ and $k$: \n\n$$\nax^2 + bx + c = (x+z)^2 + k \\\\\nax^2 + bx + c - (x+z)^2 + k = 0\n$$\n\n\n```python\ndef completeSquare(poly):\n z,k = sp.symbols(\"z k\")\n completedSquareForm = (x+z)**2+k\n sol = sp.solve(poly-completedSquareForm,[z,k])\n squareRes = sp.Pow(x+sol[0][0],2,evaluate=False)\n constantRes = sol[0][1]\n return squareRes + constantRes\n\n```\n\nConsider the following polynomial, which is not a perfect square. \n\n\n```python\npoly1 = x**2 + 10*x + 28\npoly1\n```\n\n\n\n\n$$x^{2} + 10 x + 28$$\n\n\n\nIf we try to factor this with SymPy it will throw up its hands and do nothing because it cannot be factored. \n\n\n```python\npoly1.factor()\n```\n\n\n\n\n$$x^{2} + 10 x + 28$$\n\n\n\nWe still can, however, complete the square. \n\n\n```python\ncompletedSquareForm = (x+b)**2+c\npoly1Eqn = sp.Eq(poly1,completedSquareForm)\npoly1Eqn\n```\n\n\n\n\n$$x^{2} + 10 x + 28 = c + \\left(b + x\\right)^{2}$$\n\n\n\n\n```python\nsol = sp.solve(poly1 - completedSquareForm,[b,c])\nsp.Eq(poly1Eqn,completeSquare(poly1))\n```\n\n\n\n\n$$x^{2} + 10 x + 28 = c + \\left(b + x\\right)^{2} = \\left(x + 5\\right)^{2} + 3$$\n\n\n\nNow consider a polynomial which is a perfect square. \n\n\n```python\npoly2 = ((x+5)**2).expand()\npoly2\n```\n\n\n\n\n$$x^{2} + 10 x + 25$$\n\n\n\nFactoring now works, but we can also complete the square with $c=0$\n\n\n```python\npoly2.factor()\n```\n\n\n\n\n$$\\left(x + 5\\right)^{2}$$\n\n\n\n\n```python\ncompleteSquare(poly2)\n```\n\n\n\n\n$$\\left(x + 5\\right)^{2}$$\n\n\n\nWe will use this function below to help us derive the quadratic formula. \n\n## Using the completion of the square to derive the quadratic formula\n\n\n```python\nquadApart = (quadraticEqn/a).apart(a)\nquadApart\n```\n\n\n\n\n$$x^{2} + \\frac{1}{a} \\left(b x + c\\right)$$\n\n\n\n\n```python\nexpanded = quadApart.expand()\nlhs = expanded\nlhs\n```\n\n\n\n\n$$x^{2} + \\frac{b x}{a} + \\frac{c}{a}$$\n\n\n\nSubtract both sides by $\\large \\frac{c}{a}$\n\n\n```python\nlhs = lhs - c/a\nrhs = rhs - c/a\nsp.Eq(lhs,rhs)\n```\n\n\n\n\n$$x^{2} + \\frac{b x}{a} = - \\frac{c}{a}$$\n\n\n\nWe would now like to know what term we must add to both sides of the equation such that we can complete the square of the left hand side so we can isolate x. We know from previous results that it is:\n\n$$ \n\\begin{align}\n\\large \\left( \\frac{b}{2a} \\right)^2 = \\frac{b^2}{4a^2}\n\\end{align}\n$$\n\nBut let's derive this using sympy. To do this we will need to solve the following equation for $z$. We can also solve for $k$ to get the completed square, but we will derive this later. \n\n$$\n\\large x^2+\\frac{b}{a}x+z = \\left( x+k \\right)^2\n$$\n\nSubtracting the right hand side from both sides will put this in a form SymPy favors for solving:\n\n$$\n\\large x^2+\\frac{b}{a}x+z - \\left( x+k \\right)^2 = 0\n$$\n\n\n```python\nsolvingForZK = sp.solve(lhs+z -(x+k)**2,z,k)\nprint(\"Z:\")\n# Sympy automatically applies the square. \ndisplay(solvingForZK[0][0])\nprint(\"K:\")\ndisplay(solvingForZK[0][1])\n```\n\n Z:\n\n\n\n$$\\frac{b^{2}}{4 a^{2}}$$\n\n\n K:\n\n\n\n$$\\frac{b}{2 a}$$\n\n\nThus we see if we'd like to write the left hand side of our equation as a square, we need to add $ \\left( \\frac{b}{2a} \\right)^2$ to both sides of our equation.\n\n\n```python\ncompletingSquareTerm = sp.Pow((b/(2*a)),2,evaluate=False)\nnLhs = lhs + completingSquareTerm\nnRhs = rhs + completingSquareTerm\nsp.Eq(nLhs,nRhs)\n```\n\n\n\n\n$$x^{2} + \\left(\\frac{b}{2 a}\\right)^{2} + \\frac{b x}{a} = \\left(\\frac{b}{2 a}\\right)^{2} - \\frac{c}{a}$$\n\n\n\nWe can use the function we defined above to complete the square of the left hand side.\n\n\n```python\nnLhs = completeSquare(nLhs)\nnLhs\n```\n\n\n\n\n$$\\left(x + \\frac{b}{2 a}\\right)^{2}$$\n\n\n\nAs we see, $\\frac{b}{2a}$ is the $k$ we computed before. We now have: \n\n\n```python\nsp.Eq(nLhs,nRhs)\n```\n\n\n\n\n$$\\left(x + \\frac{b}{2 a}\\right)^{2} = \\left(\\frac{b}{2 a}\\right)^{2} - \\frac{c}{a}$$\n\n\n\nWe have finally found a form where we can isolate $x$! The remainder of the derivation is just a simple matter of rearanging terms. \n\nWe need to get the right hand side into a form easier for sympy to work with later. This requires a little wizardry with polynomial manipulation module. We could have done this operation on one line, but I will show the steps here. \n\nWe first factor. \n\n\n```python\nnRhs = nRhs.factor()\nnRhs\n```\n\n\n\n\n$$- \\frac{1}{4 a^{2}} \\left(4 a c - b^{2}\\right)$$\n\n\n\nAs you see this gives us a strange form. We can resolve this by expanding, then bringing the terms together again. \n\n\n```python\nnRhs = nRhs.expand()\nnRhs\n```\n\n\n\n\n$$- \\frac{c}{a} + \\frac{b^{2}}{4 a^{2}}$$\n\n\n\n\n```python\nnRhs = nRhs.together()\nnRhs\n```\n\n\n\n\n$$\\frac{1}{4 a^{2}} \\left(- 4 a c + b^{2}\\right)$$\n\n\n\nWe now square both sides. \n\nSince we did not define our symbol type, sympy will not apply the square root because it does not always hold for all types of numbers that $\\sqrt{x^2} = x^2$; however we can force it to make this assumption with a utility function called powdnest.\n\n\n```python\nnLhs = sp.powdenest(sp.sqrt(nLhs),force=True)\nnRhs = sp.powdenest(sp.sqrt(nRhs),force=True)\nsp.Eq(nLhs,nRhs)\n```\n\n\n\n\n$$x + \\frac{b}{2 a} = \\frac{1}{2 a} \\sqrt{- 4 a c + b^{2}}$$\n\n\n\nNow we subtract $\\frac{b}{2a}$ from both sides. \n\n\n```python\nnLhs = nLhs - b/(2*a)\nnRhs = nRhs - b/(2*a)\nsp.Eq(nLhs,nRhs)\n```\n\n\n\n\n$$x = - \\frac{b}{2 a} + \\frac{1}{2 a} \\sqrt{- 4 a c + b^{2}}$$\n\n\n\nWe simplify the right hand side and get our familiar quadratic equation. \n\n\n```python\nsp.Eq(x,nRhs.simplify())\n```\n\n\n\n\n$$x = \\frac{1}{2 a} \\left(- b + \\sqrt{- 4 a c + b^{2}}\\right)$$\n\n\n\nAs you can see, there is no $\\pm$ we are accustom to seeing. There is obviously no plus or minus operator inherent in mathematics. We would have introduced this when we took the square root of both sides because the square of $x$ could either be positive or negative. \n", "meta": {"hexsha": "2e40cac7d3ce6712fb632ff9f04de9f7f1adb76f", "size": 20539, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Notebooks/Exercise - Deriving the Quadratic Formula with SymPy.ipynb", "max_stars_repo_name": "Andrewnetwork/WorkshopScipy", "max_stars_repo_head_hexsha": "739d24b9078fffb84408e7877862618d88d947dc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 433, "max_stars_repo_stars_event_min_datetime": "2017-12-16T20:50:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-08T13:05:57.000Z", "max_issues_repo_path": "Notebooks/Exercise - Deriving the Quadratic Formula with SymPy.ipynb", "max_issues_repo_name": "Andrewnetwork/WorkshopScipy", "max_issues_repo_head_hexsha": "739d24b9078fffb84408e7877862618d88d947dc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2017-12-17T06:10:28.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-14T15:50:10.000Z", "max_forks_repo_path": "Notebooks/Exercise - Deriving the Quadratic Formula with SymPy.ipynb", "max_forks_repo_name": "Andrewnetwork/WorkshopScipy", "max_forks_repo_head_hexsha": "739d24b9078fffb84408e7877862618d88d947dc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 47, "max_forks_repo_forks_event_min_datetime": "2017-12-06T20:40:09.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-01T11:33:57.000Z", "avg_line_length": 21.7343915344, "max_line_length": 357, "alphanum_fraction": 0.4393105799, "converted": true, "num_tokens": 2353, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475723029411, "lm_q2_score": 0.9343951584303887, "lm_q1q2_score": 0.8814594042769291}} {"text": "# Modeling and Simulation in Python\n\nChapter 9\n\nCopyright 2017 Allen Downey\n\nLicense: [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0)\n\n\n\n```python\n# Configure Jupyter to display the assigned value after an assignment\n%config InteractiveShell.ast_node_interactivity='last_expr_or_assign'\n\n# import everything from SymPy.\nfrom sympy import *\n\n# Set up Jupyter notebook to display math.\ninit_printing() \n```\n\nThe following displays SymPy expressions and provides the option of showing results in LaTeX format.\n\n\n```python\nfrom sympy.printing import latex\n\ndef show(expr, show_latex=False):\n \"\"\"Display a SymPy expression.\n \n expr: SymPy expression\n show_latex: boolean\n \"\"\"\n if show_latex:\n print(latex(expr))\n return expr\n```\n\n### Analysis with SymPy\n\nCreate a symbol for time.\n\n\n```python\nt = symbols('t')\n```\n\nIf you combine symbols and numbers, you get symbolic expressions.\n\n\n```python\nexpr = t + 1\n```\n\nThe result is an `Add` object, which just represents the sum without trying to compute it.\n\n\n```python\ntype(expr)\n```\n\n\n\n\n sympy.core.add.Add\n\n\n\n`subs` can be used to replace a symbol with a number, which allows the addition to proceed.\n\n\n```python\nexpr.subs(t, 2)\n```\n\n`f` is a special class of symbol that represents a function.\n\n\n```python\nf = Function('f')\n```\n\n\n\n\n f\n\n\n\nThe type of `f` is `UndefinedFunction`\n\n\n```python\ntype(f)\n```\n\n\n\n\n sympy.core.function.UndefinedFunction\n\n\n\nSymPy understands that `f(t)` means `f` evaluated at `t`, but it doesn't try to evaluate it yet.\n\n\n```python\nf(t)\n```\n\n`diff` returns a `Derivative` object that represents the time derivative of `f`\n\n\n```python\ndfdt = diff(f(t), t)\n```\n\n\n```python\ntype(dfdt)\n```\n\n\n\n\n sympy.core.function.Derivative\n\n\n\nWe need a symbol for `alpha`\n\n\n```python\nalpha = symbols('alpha')\n```\n\nNow we can write the differential equation for proportional growth.\n\n\n```python\neq1 = Eq(dfdt, alpha*f(t))\n```\n\nAnd use `dsolve` to solve it. The result is the general solution.\n\n\n```python\nsolution_eq = dsolve(eq1)\n```\n\nWe can tell it's a general solution because it contains an unspecified constant, `C1`.\n\nIn this example, finding the particular solution is easy: we just replace `C1` with `p_0`\n\n\n```python\nC1, p_0 = symbols('C1 p_0')\n```\n\n\n```python\nparticular = solution_eq.subs(C1, p_0)\n```\n\nIn the next example, we have to work a little harder to find the particular solution.\n\n### Solving the quadratic growth equation \n\nWe'll use the (r, K) parameterization, so we'll need two more symbols:\n\n\n```python\nr, K = symbols('r K')\n```\n\nNow we can write the differential equation.\n\n\n```python\neq2 = Eq(diff(f(t), t), r * f(t) * (1 - f(t)/K))\n```\n\nAnd solve it.\n\n\n```python\nsolution_eq = dsolve(eq2)\n```\n\nThe result, `solution_eq`, contains `rhs`, which is the right-hand side of the solution.\n\n\n```python\ngeneral = solution_eq.rhs\n```\n\nWe can evaluate the right-hand side at $t=0$\n\n\n```python\nat_0 = general.subs(t, 0)\n```\n\nNow we want to find the value of `C1` that makes `f(0) = p_0`.\n\nSo we'll create the equation `at_0 = p_0` and solve for `C1`. Because this is just an algebraic identity, not a differential equation, we use `solve`, not `dsolve`.\n\nThe result from `solve` is a list of solutions. In this case, [we have reason to expect only one solution](https://en.wikipedia.org/wiki/Picard%E2%80%93Lindel%C3%B6f_theorem), but we still get a list, so we have to use the bracket operator, `[0]`, to select the first one.\n\n\n```python\nsolutions = solve(Eq(at_0, p_0), C1)\ntype(solutions), len(solutions)\n```\n\n\n\n\n (list, 1)\n\n\n\n\n```python\nvalue_of_C1 = solutions[0]\n```\n\nNow in the general solution, we want to replace `C1` with the value of `C1` we just figured out.\n\n\n```python\nparticular = general.subs(C1, value_of_C1)\n```\n\nThe result is complicated, but SymPy provides a method that tries to simplify it.\n\n\n```python\nparticular = simplify(particular)\n```\n\nOften simplicity is in the eye of the beholder, but that's about as simple as this expression gets.\n\nJust to double-check, we can evaluate it at `t=0` and confirm that we get `p_0`\n\n\n```python\nparticular.subs(t, 0)\n```\n\nThis solution is called the [logistic function](https://en.wikipedia.org/wiki/Population_growth#Logistic_equation).\n\nIn some places you'll see it written in a different form:\n\n$f(t) = \\frac{K}{1 + A e^{-rt}}$\n\nwhere $A = (K - p_0) / p_0$.\n\nWe can use SymPy to confirm that these two forms are equivalent. First we represent the alternative version of the logistic function:\n\n\n```python\nA = (K - p_0) / p_0\n```\n\n\n```python\nlogistic = K / (1 + A * exp(-r*t))\n```\n\nTo see whether two expressions are equivalent, we can check whether their difference simplifies to 0.\n\n\n```python\nsimplify(particular - logistic)\n```\n\nThis test only works one way: if SymPy says the difference reduces to 0, the expressions are definitely equivalent (and not just numerically close).\n\nBut if SymPy can't find a way to simplify the result to 0, that doesn't necessarily mean there isn't one. Testing whether two expressions are equivalent is a surprisingly hard problem; in fact, there is no algorithm that can solve it in general.\n\n### Exercises\n\n**Exercise:** Solve the quadratic growth equation using the alternative parameterization\n\n$\\frac{df(t)}{dt} = \\alpha f(t) + \\beta f^2(t) $\n\n\n```python\nbeta = symbols('beta')\n```\n\n\n```python\neq3 = Eq(diff(f(t), t), alpha*f(t) + beta*f(t)**2)\n```\n\n\n```python\nsolution_eq = dsolve(eq3)\n```\n\n\n```python\ngeneral = solution_eq.rhs\n```\n\n\n```python\nat_0 = general.subs(t, 0)\n```\n\n\n```python\nsolutions = solve(Eq(at_0, p_0), C1)\ntype(solutions), len(solutions)\n```\n\n\n\n\n (list, 1)\n\n\n\n\n```python\nvalue_of_C1 = solutions[0]\n```\n\n\n```python\nparticular = general.subs(C1, value_of_C1)\n```\n\n\n```python\nparticular = simplify(particular)\n```\n\n\n```python\nparticular.subs(t, 0)\n```\n\n**Exercise:** Use [WolframAlpha](https://www.wolframalpha.com/) to solve the quadratic growth model, using either or both forms of parameterization:\n\n df(t) / dt = alpha f(t) + beta f(t)^2\n\nor\n\n df(t) / dt = r f(t) (1 - f(t)/K)\n\nFind the general solution and also the particular solution where `f(0) = p_0`.\n\n\n```python\n\n```\n", "meta": {"hexsha": "9ba5136e5b3e7e5fb8babfacfe3ffa086bd42ee4", "size": 69501, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "code/chap09mine.ipynb", "max_stars_repo_name": "NWeil/ModSimPy", "max_stars_repo_head_hexsha": "4db4ac014da4d2e5893258d4bb21e48bab30db11", "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": "code/chap09mine.ipynb", "max_issues_repo_name": "NWeil/ModSimPy", "max_issues_repo_head_hexsha": "4db4ac014da4d2e5893258d4bb21e48bab30db11", "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": "code/chap09mine.ipynb", "max_forks_repo_name": "NWeil/ModSimPy", "max_forks_repo_head_hexsha": "4db4ac014da4d2e5893258d4bb21e48bab30db11", "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": 56.5508543531, "max_line_length": 3288, "alphanum_fraction": 0.7647947512, "converted": true, "num_tokens": 1693, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9683812341001314, "lm_q2_score": 0.9099070115349838, "lm_q1q2_score": 0.8811368747466101}} {"text": "# Part 1 - Scalars and Vectors\n\nFor the questions below it is not sufficient to simply provide answer to the questions, but you must solve the problems and show your work using python (the NumPy library will help a lot!) Translate the vectors and matrices into their appropriate python representations and use numpy or functions that you write yourself to demonstrate the result or property. \n\n\n```\nimport numpy as np\nimport pandas as pd\nimport math\nimport matplotlib.pyplot as plt\n```\n\n## 1.1 Create a two-dimensional vector and plot it on a graph\n\n\n```\n# vector samples\ngreen = [-.6, .7]\npurple = [.3, .2]\norange = [.4, -.4]\n```\n\n\n```\n# examine component\norange[0]\n```\n\n\n\n\n 0.4\n\n\n\n\n```\n# loop\nfor color in [green, purple, orange]:\n print(color[1])\n```\n\n 0.7\n 0.2\n 0.4\n\n\n\n```\n# plotting using matplotlib\nfig, ax = plt.subplots()\nax.grid()\nplt.xlim(-.8, .8)\nplt.ylim(-.8, .8)\nplt.arrow(0,0,\n green[0],\n green[1],\n head_width=.02,\n head_length=.02,\n linewidth=3,\n color='green')\nplt.arrow(0,0,\n purple[0],\n purple[1],\n head_width=.02,\n head_length=.02,\n linewidth=3,\n color='purple')\nplt.arrow(0,0,\n orange[0],\n orange[1],\n head_width=.02,\n head_length=.02,\n linewidth=3,\n color='orange');\n```\n\n\n```\nprint(green, purple, orange)\n```\n\n [-0.6, 0.7] [0.3, 0.2] [0.4, -0.4]\n\n\n## 1.2 Create a three-dimensional vecor and plot it on a graph\n\n\n```\n# create 3 dimensional vector\ngreen = [.5, .5, .5]\npurple = [.4, .3, .2]\norange = [.2, .1, .1]\nmyvector = np.array([[0,0,0, .5, .5, .5],\n [0,0,0, .4, .3, .2],\n [0,0,0, .2, .1, .1]])\nmyvector[0]\n```\n\n\n\n\n array([0. , 0. , 0. , 0.5, 0.5, 0.5])\n\n\n\n\n```\n# unzip vector\nX, Y, Z, U, V, W = zip(*myvector)\nfor letter in [X, Y, Z, U, V, W]:\n print(letter)\n```\n\n (0.0, 0.0, 0.0)\n (0.0, 0.0, 0.0)\n (0.0, 0.0, 0.0)\n (0.5, 0.4, 0.2)\n (0.5, 0.3, 0.1)\n (0.5, 0.2, 0.1)\n\n\n\n```\n# displaying in 3d\nfrom mpl_toolkits.mplot3d import Axes3D\n\nfig = plt.figure()\nax = fig.add_subplot(111, projection='3d')\nax.quiver(X[0], Y[0], Z[0], U[0], V[0], W[0], length=1, color='green')\nax.quiver(X[1], Y[1], Z[1], U[1], V[1], W[1], length=1, color='purple')\nax.quiver(X[2], Y[2], Z[2], U[2], V[2], W[2], length=1, color='orange')\n\nax.set_xlim([0, 1])\nax.set_ylim([0, 1])\nax.set_zlim([0, 1])\nax.set_xlabel('X')\nax.set_ylabel('Y')\nax.set_zlabel('Z')\nplt.show()\n```\n\n## 1.3 Scale the vectors you created in 1.1 by $5$, $\\pi$, and $-e$ and plot all four vectors (original + 3 scaled vectors) on a graph. What do you notice about these vectors? \n\n\n```\nfrom math import e, pi\nprint(e)\nprint(pi)\n```\n\n 2.718281828459045\n 3.141592653589793\n\n\n\n```\n# scale by 5\npink = np.multiply(5, green)\nyellow = np.multiply(5, purple)\nred = np.multiply (5, orange)\npink, yellow, red\n```\n\n\n\n\n (array([-3. , 3.5]), array([1.5, 1. ]), array([ 2., -2.]))\n\n\n\n\n```\n# scale by pi\nblue = np.multiply(pi, green)\ncyan = np.multiply(pi, purple)\nbrown = np.multiply(pi, orange)\nblue, cyan, brown\n```\n\n\n\n\n (array([-1.88495559, 2.19911486]),\n array([0.9424778 , 0.62831853]),\n array([ 1.25663706, -1.25663706]))\n\n\n\n\n```\n# scale by e\nmagenta = np.multiply(e, green)\nteal = np.multiply(e, purple)\nsienna = np.multiply(e, orange)\nmagenta, teal, sienna\n```\n\n\n\n\n (array([-1.6309691 , 1.90279728]),\n array([0.81548455, 0.54365637]),\n array([ 1.08731273, -1.08731273]))\n\n\n\n\n```\n# plot on graph\nax.grid()\nplt.xlim(-3, 3)\nplt.ylim(-3, 3)\nplt.arrow(0,0,\n green[0],\n green[1],\n head_width=.02,\n head_length=.02,\n linewidth=3,\n color='green')\nplt.arrow(0,0,\n purple[0],\n purple[1],\n head_width=.02,\n head_length=.02,\n linewidth=3,\n color='purple')\nplt.arrow(0,0,\n orange[0],\n orange[1],\n head_width=.02,\n head_length=.02,\n linewidth=3,\n color='orange')\nplt.arrow(0,0,\n pink[0],\n pink[1],\n head_width=.02,\n head_length=.02,\n linewidth=3,\n color='pink')\nplt.arrow(0,0,\n yellow[0],\n yellow[1],\n head_width=.02,\n head_length=.02,\n linewidth=3,\n color='yellow')\nplt.arrow(0,0,\n red[0],\n red[1],\n head_width=.02,\n head_length=.02,\n linewidth=3,\n color='red')\nplt.arrow(0,0,\n blue[0],\n blue[1],\n head_width=.02,\n head_length=.02,\n linewidth=3,\n color='blue')\nplt.arrow(0,0,\n cyan[0],\n cyan[1],\n head_width=.02,\n head_length=.02,\n linewidth=3,\n color='cyan')\nplt.arrow(0,0,\n brown[0],\n brown[1],\n head_width=.02,\n head_length=.02,\n linewidth=3,\n color='brown')\nplt.arrow(0,0,\n magenta[0],\n magenta[1],\n head_width=.02,\n head_length=.02,\n linewidth=3,\n color='magenta')\nplt.arrow(0,0,\n teal[0],\n teal[1],\n head_width=.02,\n head_length=.02,\n linewidth=3,\n color='teal')\nplt.arrow(0,0,\n sienna[0],\n sienna[1],\n head_width=.02,\n head_length=.02,\n linewidth=3,\n color='sienna');\n```\n\n\n```\n# the vectors follow the same direction of their multlipicand\n```\n\n\n```\n\n```\n\n## 1.4 Graph vectors $\\vec{a}$ and $\\vec{b}$ and plot them on a graph\n\n\\begin{align}\n\\vec{a} = \\begin{bmatrix} 5 \\\\ 7 \\end{bmatrix}\n\\qquad\n\\vec{b} = \\begin{bmatrix} 3 \\\\4 \\end{bmatrix}\n\\end{align}\n\n\n```\na = [5, 7]\nb = [3, 4]\n```\n\n\n```\nnp_a = np.array(a)\nnp_b = np.array(b)\nprint(np_a, np_b)\n```\n\n [5 7] [3 4]\n\n\n\n```\n# graph\nimport matplotlib.pyplot as plt\nfig, ax = plt.subplots()\nax.grid()\nplt.xlim(-0,8)\nplt.ylim(0,8)\n\nplt.arrow(0,0,\n a[0],\n a[1],\n head_width=.02,\n head_length=.02,\n linewidth=3,\n color='gold')\nplt.arrow(0,0,\n b[0],\n b[1],\n head_width=.02,\n head_length=.02,\n linewidth=3,\n color='grey');\n```\n\n## 1.5 find $\\vec{a} - \\vec{b}$ and plot the result on the same graph as $\\vec{a}$ and $\\vec{b}$. Is there a relationship between vectors $\\vec{a} \\thinspace, \\vec{b} \\thinspace \\text{and} \\thinspace \\vec{a-b}$\n\n\n```\nc = np_a - np_b\nc\n```\n\n\n\n\n array([2, 3])\n\n\n\n\n```\n# graph\nimport matplotlib.pyplot as plt\nfig, ax = plt.subplots()\nax.grid()\nplt.xlim(-0,8)\nplt.ylim(0,8)\n\nplt.arrow(0,0,\n a[0],\n a[1],\n head_width=.02,\n head_length=.02,\n linewidth=3,\n color='gold')\nplt.arrow(0,0,\n b[0],\n b[1],\n head_width=.02,\n head_length=.02,\n linewidth=3,\n color='grey')\nplt.arrow(0,0,\n c[0],\n c[1],\n head_width=.02,\n head_length=.02,\n linewidth=3,\n color='tan');\n```\n\n## 1.6 Find $c \\cdot d$\n\n\\begin{align}\n\\vec{c} = \\begin{bmatrix}7 & 22 & 4 & 16\\end{bmatrix}\n\\qquad\n\\vec{d} = \\begin{bmatrix}12 & 6 & 2 & 9\\end{bmatrix}\n\\end{align}\n\n\n\n```\n# define c and d\nc = np.array([7, 22, 4, 16])\nd = np.array([12, 6, 2 , 9])\nc, d\n```\n\n\n\n\n (array([ 7, 22, 4, 16]), array([12, 6, 2, 9]))\n\n\n\n\n```\n# dot-product method\nnp.dot(c,d)\n```\n\n\n\n\n 368\n\n\n\n## 1.7 Find $e \\times f$\n\n\\begin{align}\n\\vec{e} = \\begin{bmatrix} 5 \\\\ 7 \\\\ 2 \\end{bmatrix}\n\\qquad\n\\vec{f} = \\begin{bmatrix} 3 \\\\4 \\\\ 6 \\end{bmatrix}\n\\end{align}\n\n\n```\ne = np.array([5, 7, 2])\nf = np.array([3, 4, 6])\ne, f\n```\n\n\n\n\n (array([5, 7, 2]), array([3, 4, 6]))\n\n\n\n\n```\ne * f\n```\n\n\n\n\n array([15, 28, 12])\n\n\n\n## 1.8 Find $||g||$ and then find $||h||$. Which is longer?\n\n\\begin{align}\n\\vec{g} = \\begin{bmatrix} 1 \\\\ 1 \\\\ 1 \\\\ 8 \\end{bmatrix}\n\\qquad\n\\vec{h} = \\begin{bmatrix} 3 \\\\3 \\\\ 3 \\\\ 3 \\end{bmatrix}\n\\end{align}\n\n\n```\ng = ([1, 1, 8, 8])\nh = ([3, 3, 3, 3])\ng, h\n```\n\n\n\n\n ([1, 1, 8, 8], [3, 3, 3, 3])\n\n\n\n\n```\n# norm_g is longer\nnorm_g = np.linalg.norm(g)\nnorm_h = np.linalg.norm(h)\nnorm_g, norm_h\n```\n\n\n\n\n (11.40175425099138, 6.0)\n\n\n\n# Part 2 - Matrices\n\n## 2.1 What are the dimensions of the following matrices? Which of the following can be multiplied together? See if you can find all of the different legal combinations.\n\\begin{align}\nA = \\begin{bmatrix}\n1 & 2 \\\\\n3 & 4 \\\\\n5 & 6\n\\end{bmatrix}\n\\qquad\nB = \\begin{bmatrix}\n2 & 4 & 6 \\\\\n\\end{bmatrix}\n\\qquad\nC = \\begin{bmatrix}\n9 & 6 & 3 \\\\\n4 & 7 & 11\n\\end{bmatrix}\n\\qquad\nD = \\begin{bmatrix}\n1 & 0 & 0 \\\\\n0 & 1 & 0 \\\\\n0 & 0 & 1\n\\end{bmatrix}\n\\qquad\nE = \\begin{bmatrix}\n1 & 3 \\\\\n5 & 7\n\\end{bmatrix}\n\\end{align}\n\n\n```\n# A is 3 x 2\n# B is 1 x 3\n# C is 2 x 3\n# D is 3 x 3\n# E is 2 x 2\n```\n\n\n```\n# compatible matrices\n# A & B\n# A & C\n# A & D\n# E & A\n# D & B\n# D & C\n# C & E\n```\n\n## 2.2 Find the following products: CD, AE, and BA. What are the dimensions of the resulting matrices? How does that relate to the dimensions of their factor matrices?\n\n\n```\n# Define Matrices\nA = np.array([[1, 2],\n [3, 4],\n [5, 6]])\nB = np.array([[2, 4, 6]])\nC = np.array([[9, 6, 3],\n [4, 7, 11]])\nD = np.array([[1, 0, 0],\n [0, 1, 0],\n [0, 0, 1]])\nE = np.array([[1, 3],\n [5, 7]])\nA, B, C, D, E\n```\n\n\n\n\n (array([[1, 2],\n [3, 4],\n [5, 6]]), array([[2, 4, 6]]), array([[ 9, 6, 3],\n [ 4, 7, 11]]), array([[1, 0, 0],\n [0, 1, 0],\n [0, 0, 1]]), array([[1, 3],\n [5, 7]]))\n\n\n\n\n```\n# CD - 2x3\npd.DataFrame(np.matmul(C, D))\n```\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
012
0963
14711
\n
\n\n\n\n\n```\n# AE - 3x2\npd.DataFrame(np.matmul(A, E))\n```\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
01
01117
12337
23557
\n
\n\n\n\n\n```\n# BA - 1x2\npd.DataFrame(np.matmul(B, A))\n```\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
01
04456
\n
\n\n\n\n\n```\n# the resulting matrices usually takes on the shape of the smaller factor\n```\n\n## 2.3 Find $F^{T}$. How are the numbers along the main diagonal (top left to bottom right) of the original matrix and its transpose related? What are the dimensions of $F$? What are the dimensions of $F^{T}$?\n\n\\begin{align}\nF = \n\\begin{bmatrix}\n20 & 19 & 18 & 17 \\\\\n16 & 15 & 14 & 13 \\\\\n12 & 11 & 10 & 9 \\\\\n8 & 7 & 6 & 5 \\\\\n4 & 3 & 2 & 1\n\\end{bmatrix}\n\\end{align}\n\n\n```\nF = np.array([[20, 19, 19, 17],\n [16, 15, 14, 13],\n [12, 11, 10, 9],\n [8, 7, 6, 5],\n [4, 3, 2, 1]])\nF\n```\n\n\n\n\n array([[20, 19, 19, 17],\n [16, 15, 14, 13],\n [12, 11, 10, 9],\n [ 8, 7, 6, 5],\n [ 4, 3, 2, 1]])\n\n\n\n\n```\npd.DataFrame(F.T)\n# the dimension changed from 5x4 to 4x5, thus, the first 4 diagonal \n# numbers remained\n```\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
01234
020161284
119151173
219141062
31713951
\n
\n\n\n\n# Part 3 - Square Matrices\n\n## 3.1 Find $IG$ (be sure to show your work) 😃\n\nYou don't have to do anything crazy complicated here to show your work, just create the G matrix as specified below, and a corresponding 2x2 Identity matrix and then multiply them together to show the result. You don't need to write LaTeX or anything like that (unless you want to).\n\n\\begin{align}\nG= \n\\begin{bmatrix}\n13 & 14 \\\\\n21 & 12 \n\\end{bmatrix}\n\\end{align}\n\n\n```\n# G Matrix\nG = np.array([[13, 14],\n [21, 12]])\npd.DataFrame(G)\n```\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
01
01314
12112
\n
\n\n\n\n\n```\n# Identity matrix\nI = np.array ([[1, 0],\n [0, 1]])\npd.DataFrame(I)\n```\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
01
010
101
\n
\n\n\n\n\n```\n# multipy\npd.DataFrame(np.matmul(I, G))\n```\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
01
01314
12112
\n
\n\n\n\n## 3.2 Find $|H|$ and then find $|J|$.\n\n\\begin{align}\nH= \n\\begin{bmatrix}\n12 & 11 \\\\\n7 & 10 \n\\end{bmatrix}\n\\qquad\nJ= \n\\begin{bmatrix}\n0 & 1 & 2 \\\\\n7 & 10 & 4 \\\\\n3 & 2 & 0\n\\end{bmatrix}\n\\end{align}\n\n\n\n```\n# H & J\nH = np.array([[12, 11],\n [7,10]])\nJ = np.array([[0, 1, 2],\n [7, 10, 4],\n [3, 2, 0]])\n```\n\n\n```\npd.DataFrame(H)\n```\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
01
01211
1710
\n
\n\n\n\n\n```\npd.DataFrame(J)\n```\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
012
0012
17104
2320
\n
\n\n\n\n## 3.3 Find $H^{-1}$ and then find $J^{-1}$\n\n\n```\n# H inverse\npd.DataFrame(np.linalg.inv(H))\n```\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
01
00.232558-0.255814
1-0.1627910.279070
\n
\n\n\n\n\n```\n# J inverse\npd.DataFrame(np.linalg.inv(J))\n```\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
012
00.4-0.200.80
1-0.60.30-0.70
20.8-0.150.35
\n
\n\n\n\n## 3.4 Find $HH^{-1}$ and then find $J^{-1}J$. Is $HH^{-1} == J^{-1}J$? Why or Why not? \n\nPlease ignore Python rounding errors. If necessary, format your output so that it rounds to 5 significant digits (the fifth decimal place).\n\n\n```\nHH1 = np.matmul(H, np.linalg.inv(H))\npd.DataFrame(HH1)\n```\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
01
01.000000e+005.551115e-16
12.220446e-161.000000e+00
\n
\n\n\n\n\n```\nJJ1 = np.matmul(J, np.linalg.inv(J))\npd.DataFrame(JJ1)\n```\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
012
01.0-5.551115e-170.0
10.01.000000e+000.0
20.00.000000e+001.0
\n
\n\n\n\n\n```\nnp.round(HH1, decimals=5)\n```\n\n\n\n\n array([[1., 0.],\n [0., 1.]])\n\n\n\n\n```\nnp.round(JJ1, decimals=5)\n```\n\n\n\n\n array([[ 1., -0., 0.],\n [ 0., 1., 0.],\n [ 0., 0., 1.]])\n\n\n\n# Stretch Goals: \n\nA reminder that these challenges are optional. If you finish your work quickly we welcome you to work on them. If there are other activities that you feel like will help your understanding of the above topics more, feel free to work on that. Topics from the Stretch Goals sections will never end up on Sprint Challenges. You don't have to do these in order, you don't have to do all of them. \n\n- Write a function that can calculate the dot product of any two vectors of equal length that are passed to it.\n- Write a function that can calculate the norm of any vector\n- Prove to yourself again that the vectors in 1.9 are orthogonal by graphing them. \n- Research how to plot a 3d graph with animations so that you can make the graph rotate (this will be easier in a local notebook than in google colab)\n- Create and plot a matrix on a 2d graph.\n- Create and plot a matrix on a 3d graph.\n- Plot two vectors that are not collinear on a 2d graph. Calculate the determinant of the 2x2 matrix that these vectors form. How does this determinant relate to the graphical interpretation of the vectors?\n\n\n", "meta": {"hexsha": "02f4014e20882ed998d917b6032e1a275e8ca796", "size": 151161, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "01_Unit_1/Sprint3-Linear-Algebra/Module1/LS_DS_131_Vectors_and_Matrices_Assignment.ipynb", "max_stars_repo_name": "mark-morelos/my_DataScience_notes", "max_stars_repo_head_hexsha": "2e05a3d77949cb8ccd9aac7c04cf7758d7b73d1c", "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": "01_Unit_1/Sprint3-Linear-Algebra/Module1/LS_DS_131_Vectors_and_Matrices_Assignment.ipynb", "max_issues_repo_name": "mark-morelos/my_DataScience_notes", "max_issues_repo_head_hexsha": "2e05a3d77949cb8ccd9aac7c04cf7758d7b73d1c", "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": "01_Unit_1/Sprint3-Linear-Algebra/Module1/LS_DS_131_Vectors_and_Matrices_Assignment.ipynb", "max_forks_repo_name": "mark-morelos/my_DataScience_notes", "max_forks_repo_head_hexsha": "2e05a3d77949cb8ccd9aac7c04cf7758d7b73d1c", "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": 63.6199494949, "max_line_length": 38790, "alphanum_fraction": 0.6897281706, "converted": true, "num_tokens": 7650, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9591542887603537, "lm_q2_score": 0.9184802484881361, "lm_q1q2_score": 0.8809642694790711}} {"text": "# Linear Regression Derived\n\n#### Cost function\n\n$ C = \\sum_i (y_i - mx_i - c)^2 $\n\n#### Calculate the partial derivative with respect to $m$\n\n$\n\\begin{align}\n\\frac{\\partial C}{\\partial m} &= \\sum_i 2(y_i - m x_i -c)(-x_i) \\\\\n&= -2 \\sum_i x_i (y_i - m x_i -c) \\\\\n\\end{align}\n$\n\n#### Set derivative to zero\n\n$\n\\begin{align}\n& \\frac{\\partial C}{\\partial m} = 0 \\\\\n\\Rightarrow & -2 \\sum_i x_i (y_i - m x_i -c) = 0 \\\\\n\\Rightarrow & \\sum_i ( x_i y_i - m x_i x_i - x_i c ) = 0 \\\\\n\\Rightarrow & \\sum_i x_i y_i - \\sum_i m x_i x_i - \\sum_i x_i c = 0 \\\\\n\\Rightarrow & \\sum_i x_i y_i - c \\sum_i x_i = m \\sum_i x_i x_i \\\\\n\\Rightarrow & m = \\frac{\\sum_i x_i y_i - c \\sum_i x_i}{\\sum_i x_i x_i}\n\\end{align}\n$\n\n#### Calculate the partial derivative with respect to $c$\n\n$\n\\begin{align}\n\\frac{\\partial C}{\\partial c} &= \\sum_i 2(y_i - m x_i -c)(-1) \\\\\n&= -2 \\sum_i (y_i - m x_i -c) \\\\\n\\end{align}\n$\n\n#### Set the derivative to zero\n\n$\n\\begin{align}\n& \\frac{\\partial C}{\\partial c} = 0 \\\\\n\\Rightarrow & -2 \\sum_i (y_i - m x_i - c) = 0 \\\\\n\\Rightarrow & \\sum_i (y_i - m x_i - c) = 0 \\\\\n\\Rightarrow & \\sum_i y_i - \\sum_i m x_i - \\sum_i c = 0 \\\\\n\\Rightarrow & \\sum_i y_i - m \\sum_i x_i - c \\sum_i 1 = 0 \\\\\n\\Rightarrow & \\sum_i y_i - m \\sum_i x_i = c \\sum_i 1 \\\\\n\\Rightarrow & c = \\frac{\\sum_i y_i - m \\sum_i x_i}{\\sum_i 1} \\\\\n\\Rightarrow & c = \\frac{\\sum_i y_i}{\\sum_i 1} - m \\frac{\\sum_i x_i}{\\sum_i 1} \\\\\n\\Rightarrow & c = \\bar{y} - m \\bar{x} \\\\\n\\end{align}\n$\n\n#### Combine the estimates\n\n$\n\\begin{align}\n& m = \\frac{\\sum_i x_i y_i - c \\sum_i x_i}{\\sum_i x_i x_i} \\\\\n& c = \\bar{y} - m \\bar{x} \\\\\n& \\Rightarrow m = \\frac{\\sum_i x_i y_i - (\\bar{y} - m \\bar{x}) \\sum_i x_i}{\\sum_i x_i x_i} \\\\\n& \\Rightarrow m = \\frac{\\sum_i x_i y_i - \\bar{y} \\sum_i x_i + m \\bar{x} \\sum_i x_i}{\\sum_i x_i x_i} \\\\\n& \\Rightarrow m = \\frac{\\sum_i x_i y_i - \\bar{y} \\sum_i x_i}{\\sum_i x_i x_i} + m \\frac{\\bar{x} \\sum_i x_i}{\\sum_i x_i x_i} \\\\\n& \\Rightarrow m - m \\frac{\\bar{x} \\sum_i x_i}{\\sum_i x_i x_i} = \\frac{\\sum_i x_i y_i - \\bar{y} \\sum_i x_i}{\\sum_i x_i x_i} \\\\\n& \\Rightarrow m(1 - \\frac{\\bar{x} \\sum_i x_i}{\\sum_i x_i x_i}) = \\frac{\\sum_i x_i y_i - \\bar{y} \\sum_i x_i}{\\sum_i x_i x_i} \\\\\n& \\Rightarrow m(\\frac{\\sum_i x_i x_i - \\bar{x} \\sum_i x_i}{\\sum_i x_i x_i}) = \\frac{\\sum_i x_i y_i - \\bar{y} \\sum_i x_i}{\\sum_i x_i x_i} \\\\\n& \\Rightarrow m(\\sum_i x_i x_i - \\bar{x} \\sum_i x_i) = \\sum_i x_i y_i - \\bar{y} \\sum_i x_i \\\\\n& \\Rightarrow m = \\frac{\\sum_i x_i y_i - \\bar{y} \\sum_i x_i}{\\sum_i x_i x_i - \\bar{x} \\sum_i x_i} \\\\\n\\end{align}\n$\n\n#### End\n", "meta": {"hexsha": "744a3fb2ee56906abcfeef89b2dd4e4f7cfc5d2e", "size": 4706, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "linear-regression-derived.ipynb", "max_stars_repo_name": "ianmcloughlin/jupyter-teaching-notebooks", "max_stars_repo_head_hexsha": "46fed19115bf2f7e63c7bcb3d78bee92295c33b6", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2018-10-23T15:30:48.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-31T20:30:47.000Z", "max_issues_repo_path": "linear-regression-derived.ipynb", "max_issues_repo_name": "ianmcloughlin/jupyter-teaching-notebooks", "max_issues_repo_head_hexsha": "46fed19115bf2f7e63c7bcb3d78bee92295c33b6", "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": "linear-regression-derived.ipynb", "max_forks_repo_name": "ianmcloughlin/jupyter-teaching-notebooks", "max_forks_repo_head_hexsha": "46fed19115bf2f7e63c7bcb3d78bee92295c33b6", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 34, "max_forks_repo_forks_event_min_datetime": "2018-10-30T00:08:01.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-08T23:33:52.000Z", "avg_line_length": 28.0119047619, "max_line_length": 161, "alphanum_fraction": 0.4691882703, "converted": true, "num_tokens": 1043, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9626731083722525, "lm_q2_score": 0.9149009619539554, "lm_q1q2_score": 0.8807505528969782}} {"text": "# Assignment: Traffic Flow\n\n---\n\nConsider the flow of traffic on a one-lane highway.\nHow can we describe the general behavior of this system?\n\nWe can define the speed of traffic, $V$, in kilometers per hour.\nWe can also define a traffic density, the number of cars per unit length of highway, $\\rho$, in cars per kilometer.\nFinally, we can define a traffic flux, or the flow rate of cars, $F$,in cars per hour.\n\nNow make a few assumptions about how traffic moves.\n\nIf $\\rho$ approaches $0$, i.e. there are very few cars on the road, then cars will drive as fast as they can at some $V_\\text{max}$.\n\nConversely, if cars are bumper to bumper along the road, then $\\rho$ approaches a $\\rho_\\text{max}$ and $V$ approaches $0$.\n\nOne possible equation to describe this behavior is\n\n$$\n\\begin{equation}\n V = V_\\text{max} \\left( 1 - \\frac{\\rho}{\\rho_\\text{max}} \\right)\n\\end{equation}\n$$\n\nIf we describe the traffic flux, $F$ as $F = \\rho V$, then\n\n$$\n\\begin{equation}\n F = F \\left( \\rho \\right) = V \\left( \\rho \\right) \\rho = V_\\text{max} \\rho \\left( 1 - \\frac{\\rho}{\\rho_{max}} \\right)\n\\end{equation}\n$$\n\nUnsteady traffic flow can be modeled as the non-linear convection of car density, so we apply the non-linear convection equation with $V$, the wave speed, equal to $\\frac{\\partial F}{\\partial \\rho}$:\n\n$$\n\\begin{equation}\n \\frac{\\partial \\rho}{\\partial t} + \\frac{\\partial F}{\\partial \\rho} \\frac{\\partial \\rho}{\\partial x} = 0\n\\end{equation}\n$$\n\nApplying the chain rule of calculus, this becomes\n\n$$\n\\begin{equation}\n \\frac{\\partial \\rho}{\\partial t} + \\frac{\\partial F}{\\partial x} = 0\n\\end{equation}\n$$\n\nwhere $F$ is defined as above.\nThe PDE above is written in conservation form.\n(See section at the end of Notebook for more details about the conservation form.)\n\nYou will integrate the traffic flow equation (in conservation form) using the modified Euler's method (also called midpoint method or Runge-Kutta second-order method).\nYou will discretize the first-order spatial derivative with a backward-difference quotient:\n\n$$\n\\begin{equation}\n \\left. \\frac{\\partial F}{\\partial x} \\right|_i = \\frac{F_i - F_{i-1}}{\\Delta x} = \\frac{F(\\rho_i) - F(\\rho_{i-1})}{\\Delta x}\n\\end{equation}\n$$\n\nExamine a stretch of road using the following conditions:\n\n* $V_\\text{max} = 90 \\; \\text{km/h}$\n* $L = 25 \\; \\text{km}$\n* $\\rho_\\text{max} = 100 \\; \\text{cars/km}$\n* $nx = 101$ (number of points to discretize the road of length $L$)\n* $\\Delta t = 0.001 \\; \\text{hours}$\n\n## Implement your solution (40 points)\n\n---\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 = 101\nL = 25.0\ndx = L / (nx - 1)\ndt = 0.001\nVmax = 90.0\n𝜌max = 100\n```\n\n\n```python\n# Get the grid point coordinates.\nx = numpy.linspace(0.0, L, num=nx)\n```\n\n## Assessment (60 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\n#######################################\n# IMPORTANT\n#\n# Import mooc38 if you use Python 3.8\n# It will not work for other versions\n#\n#######################################\n\n# Import module to check your answers.\nimport mooc38 as mooc\n```\n\n### Part A\n\nUse the following initial condition\n\n$$\n\\begin{equation}\n \\rho_0 = \\rho \\left(x, t = 0 \\right) =\n \\begin{cases}\n 50 \\quad \\text{if} \\; 2 \\leq x \\leq 4.2 \\\\\n 10 \\quad \\text{otherwise}\n \\end{cases}\n ,\\quad \\forall x \\in \\left[ 0, L \\right]\n\\end{equation}\n$$\n\nand the following boundary condition\n\n$$\n\\begin{equation}\n \\rho \\left( x=0, t \\right) = \\rho \\left( x=L, t \\right) = 10, \\quad \\forall t\n\\end{equation}\n$$\n\nto answer questions Q1, Q2, Q3, and Q4.\n\n\n```python\n# YOUR CODE HERE\n# Set the initial conditions.𝜌\nu0 = numpy.ones(nx)\nfor i in range(len(u0)):\n if u0[i] == 1:\n u0[i] = 10 \nmask = numpy.where(numpy.logical_and(x >= 2.0, x <= 4.2))\nu0[mask] = 50.0\n```\n\n\n```python\n# Plot the initial conditions.\npyplot.figure(figsize=(4.0, 4.0))\npyplot.title('Initial conditions')\npyplot.xlabel('x')\npyplot.ylabel('u')\npyplot.grid()\npyplot.plot(x, u0, color='C0', linestyle='--', linewidth=2)\npyplot.xlim(0.0, L)\npyplot.ylim(0.0, 55);\n```\n\n\n```python\n# get the non-linear solution\nnt = int(1/15/dt)\nu = u0.copy()\nfor n in range(1, nt):\n un = u.copy()\n for i in range(1, nx):\n u[i] = un[i] - dt/dx * (un[i]*Vmax*(1-un[i]/𝜌max) - un[i-1]*Vmax*(1-un[i-1]/𝜌max))\n```\n\n\n```python\n# Plot the solution after nt time steps\n # along with the initial conditions.\npyplot.figure(figsize=(4.0, 4.0))\npyplot.xlabel('x')\npyplot.ylabel('u')\npyplot.grid()\npyplot.plot(x, u0, label='Initial',\n color='C0', linestyle='--', linewidth=2)\npyplot.plot(x, u, label='nt = {}'.format(nt),\n color='C1', linestyle='-', linewidth=2)\npyplot.legend()\npyplot.xlim(0.0, L)\npyplot.ylim(0.0, 55);\n```\n\n\n```python\n\n```\n\n* **Q1 (5 points):** What's the minimum initial velocity in meters per second?\n\nStore your result in the variable `v0_min`; you can check your answer by calling the function `mooc.check('hw2_answer1', v0_min)`.\n\n\n```python\n# YOUR CODE HERE\na = max(u0)\nv0_min = Vmax * (1 - a / 𝜌max) * 1000 / 3600\nprint(v0_min)\nmooc.check('hw2_answer1', v0_min)\n```\n\n 12.5\n [hw2_answer1] Good job!\n\n\n\n```python\n\n```\n\n* **Q2 (10 points):** What's the average velocity, in meters per second, along the road after $4$ minutes?\n\nStore your result in the variable `v4_mean`; you can check your answer with the function `mooc.check('hw2_answer2', v4_mean)`.\n\n\n```python\n# YOUR CODE HERE\nb = 0\nfor i in u:\n b = b + i \n𝜌4 = b / len(u)\nv4_mean = Vmax*(1-𝜌4/𝜌max)*1000/3600\nprint(v4_mean)\nmooc.check('hw2_answer2', v4_mean)\n```\n\n 21.60891089108911\n [hw2_answer2] Good job!\n\n\n\n```python\n\n```\n\n* **Q3 (10 points):** What's the minimum velocity, in meters per second, after $8$ minutes?\n\nStore your result in the variable `v8_min`; you can check your answer with the function `mooc.check('hw2_answer3', v8_min)`.\n\n\n```python\n# YOUR CODE HERE\nnx = 101\nL = 25.0\ndx = L / (nx - 1)\ndt = 0.001\nVmax = 90.0\n𝜌max = 100\nnt = int(8/60/dt)\n\nx = numpy.linspace(0.0, L, num=nx)\n\nu0 = numpy.ones(nx)\nfor i in range(len(u0)):\n if u0[i] == 1:\n u0[i] = 10 \nmask = numpy.where(numpy.logical_and(x >= 2.0, x <= 4.2))\nu0[mask] = 50.0\nu0[0] = 10\nu0[-1] = 10\n\nu = u0.copy()\nfor n in range(1, nt):\n un = u.copy()\n for i in range(1, nx):\n u[i] = un[i] - dt/dx * (un[i]*Vmax*(1-un[i]/𝜌max) - un[i-1]*Vmax*(1-un[i-1]/𝜌max))\n\n\nc = max(u)\nprint(c)\nv8_min = Vmax * (1 - c / 𝜌max) * 1000 / 3600\nprint(v8_min)\nmooc.check('hw2_answer3', v8_min)\n```\n\n 31.807381516040245\n 17.04815462098994\n [hw2_answer3] Try again!\n\n\n\n```python\n\n```\n\n* **Q4 (5 points):** What's the maximum car density, in cars per kilometer, along the road after 8 minutes?\n\nStore you result in the variable `rho8_max`; you can check your answer with `mooc.check('hw2_answer4', rho8_max)`.\n\n\n```python\n# YOUR CODE HERE\n\n```\n\n\n```python\n\n```\n\n### Part B\n\nNow, set $V_\\text{max} = 130 \\; \\text{km/hr}$ and redo the simulations using the following initial condition for the traffic density\n\n$$\n\\begin{equation}\n \\rho_0 = \\rho \\left(x, t = 0 \\right) =\n \\begin{cases}\n 50 \\quad \\text{if} \\; 2 \\leq x \\leq 4.2 \\\\\n 20 \\quad \\text{otherwise}\n \\end{cases}\n ,\\quad \\forall x \\in \\left[ 0, L \\right]\n\\end{equation}\n$$\n\nand the following boundary condition\n\n$$\n\\begin{equation}\n \\rho \\left( x=0, t \\right) = \\rho \\left( x=L, t \\right) = 20, \\quad \\forall t\n\\end{equation}\n$$\n\nRedo the simulations to answer questions Q5, Q6, Q7, and Q8.\n\n\n```python\n# YOUR CODE HERE\nnx = 101\nL = 25.0\ndx = L / (nx - 1)\ndt = 0.001\nVmax = 90.0\n𝜌max = 100\n\nx = numpy.linspace(0.0, L, num=nx)\n```\n\n* **Q5 (5 points):** What's the minimum initial velocity in meters per second?\n\nStore your result in the variable `v0_min2`; you can check your answer by calling the function `mooc.check('hw2_answer5', v0_min2)`.\n\n\n```python\n# YOUR CODE HERE\nraise NotImplementedError()\n```\n\n\n```python\n\n```\n\n* **Q6 (10 points):** What's the average velocity, in meters per second, along the road after $4$ minutes?\n\nStore your result in the variable `v4_mean2`; you can check your answer with the function `mooc.check('hw2_answer6', v4_mean2)`.\n\n\n```python\n# YOUR CODE HERE\nraise NotImplementedError()\n```\n\n\n```python\n\n```\n\n* **Q7 (10 points):** What's the minimum velocity, in meters per second, after $8$ minutes?\n\nStore your result in the variable `v8_min2`; you can check your answer with the function `mooc.check('hw2_answer7', v8_min2)`.\n\n\n```python\n# YOUR CODE HERE\nraise NotImplementedError()\n```\n\n\n```python\n\n```\n\n* **Q8 (5 points):** What's the average car density, in cars per kilometer, along the road after 8 minutes?\n\nStore your result in the variable `rho8_mean2`; you can check your answer with the function `mooc.check('hw2_answer8', rho8_mean2)`.\n\n\n```python\n# YOUR CODE HERE\nraise NotImplementedError()\n```\n\n\n```python\n\n```\n\n## Conservation and non-conservation forms\n\n---\n\nThe traffic flow is modeled by the following equation\n\n$$\n\\begin{equation}\n \\frac{\\partial \\rho}{\\partial t} + \\frac{\\partial F}{\\partial x} = 0\n\\end{equation}\n$$\n\nwhere $\\rho$ is the density and $F$ is the flux of density given by\n\n$$\n\\begin{equation*}\n F = F \\left( \\rho \\right) = \\rho V \\left( \\rho \\right) = \\rho V_\\text{max} \\left( 1 - \\frac{\\rho}{\\rho_\\text{max}} \\right)\n\\end{equation*}\n$$\n\nThe equation above is called the **conservation form** of the traffic-flow equation.\n\nAlternatively, we could also write another equation by deriving the flux with respect to $x$:\n\n$$\n\\begin{eqnarray*}\n \\frac{\\partial \\rho}{\\partial t} &=& -\\frac{\\partial F}{\\partial x} \\\\\n &=& -\\frac{\\partial F}{\\partial \\rho} \\frac{\\partial \\rho}{\\partial x} \\\\\n &=& - V_\\text{max} \\left( 1 - 2 \\frac{\\rho}{\\rho_\\text{max}} \\right) \\frac{\\partial \\rho}{\\partial x}\n\\end{eqnarray*}\n$$\n\ni.e.,\n\n$$\n\\begin{equation}\n \\frac{\\partial \\rho}{\\partial t} + V_\\text{max} \\left( 1 - 2 \\frac{\\rho}{\\rho_\\text{max}} \\right) \\frac{\\partial \\rho}{\\partial x} = 0\n\\end{equation}\n$$\n\nThe equation above is call the **non-conservation form** of the traffic-flow equation.\n\nAlthough the two equations are mathematically identical, their respective discrete version is different and will not lead to the same numerical solution.\n\nSuppose, we want to advance the solution in time using a first-order Euler's method while computing the space derivative using a backward-difference technique.\n\nThe discrete version of the equation in conservation form is\n\n$$\n\\begin{equation}\n \\frac{\\rho_i^{n + 1} - \\rho_i^n}{\\Delta t} + \\frac{F_i^n - F_{i-1}^n}{\\Delta x} = 0\n\\end{equation}\n$$\n\nwhich leads to\n\n$$\n\\begin{equation}\n \\frac{\\rho_i^{n + 1} - \\rho_i^n}{\\Delta t} + \\frac{\\rho_i^n V_\\text{max} \\left( 1 - \\frac{\\rho_i^n}{\\rho_\\text{max}} \\right) - \\rho_{i - 1}^n V_\\text{max} \\left( 1 - \\frac{\\rho_{i - 1}^n}{\\rho_\\text{max}} \\right)}{\\Delta x} = 0\n\\end{equation}\n$$\n\nThe discrete version of the equation in non-conservation form is\n\n$$\n\\begin{equation}\n \\frac{\\rho_i^{n + 1} - \\rho_i^n}{\\Delta t} + V_\\text{max} \\left( 1 - 2 \\frac{\\rho_i^n}{\\rho_\\text{max}} \\right) \\frac{\\rho_i^n - \\rho_{i - 1}^n}{\\Delta x} = 0\n\\end{equation}\n$$\n\nYou can see that the two discrete equations are different, and thus will not lead to the same numerical solution.\n\nFor the second assignment of this class, you should discretize the traffic-flow equation in its conservation form.\n", "meta": {"hexsha": "d668eff2fbb40a4e59e1cb6cf61069b8b83aacbd", "size": 59759, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "hw2/hw2/Traffic_Flow_Assignment.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": "hw2/hw2/Traffic_Flow_Assignment.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": "hw2/hw2/Traffic_Flow_Assignment.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": 51.9643478261, "max_line_length": 16636, "alphanum_fraction": 0.7424990378, "converted": true, "num_tokens": 3880, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.951863227517834, "lm_q2_score": 0.9252299498760559, "lm_q1q2_score": 0.8806923662851863}} {"text": "We are answering questions in (Lane, 2019)\n\nThe first question we answer is on how to find the smallest absolute difference for the set of numbers $S=\\left\\{2,3,4,9,16\\right\\}$\n\n\n```python\ns=[2,3,4,9,16]\nresult=[]\nfor i in range(10,1,-1):\n sum=0\n for j in s:\n sum += abs(j-i)\n result.append((i,sum))\nresult.sort(key=lambda x: x[1])\nprint(\"The number that gives the smallest absolute difference is %d. The sum of absolute differences is %d.\" \n % (result[0][0],result[0][1]))\n```\n\n The number that gives the smallest absolute difference is 4. The sum of absolute differences is 20.\n\n\nWe can generalize the logic in the cell above into a that operates on a list of numbers. Let us make the convention that we enumerate the elements $s_j \\in S$ starting with $0$, so if $S$ has three elements then $S=\\left\\{s_0,s_1,s_2\\right\\}.$ We know the number we should need to subtract from the elements of $s_j \\in S$ should be \n\\begin{equation}\n\\underset{i} {\\mathrm{argmin}} \\sum_{j=0}^{\\left|S\\right|-1} \\left|s_j-i\\right|.\n\\label{equ:argmin-1}\n\\end{equation}\n\nWe do not claim this range to search is optimal, but we show that we can choose a range that is guaranteed to find the value of $i$ that minimizes the expression above. Let $s_{\\text{max}}=\\text{max}\\left(S\\right)$ be the largest element in $S$, and let $s_{\\text{min}}=\\text{min}\\left(S\\right)$ be the smallest element in $S$. Then the value of $i$ that satisfies equation \\ref{equ:argmin-1} is in the closed interval $\\left[ s_{\\text{min}}, s_{\\text{max}} \\right].$ \n\nTo see why this is so, if we use any number $k$ less than the smallest element $s_{\\text{min}}$ or greater than the largest element $s_{\\text{max}}$ then we are adding at least $\\left|s_{\\text{min}}-k\\right|$ or $\\left|s_{\\text{max}}-k\\right|$ unnecessarily to every term in the sum.\n\n\n```python\ndef find_min_abs_diff_val(s):\n \"\"\"\n returns the integer that when subtracted from every element of s\n gives the smallest sum of the absolute values of all the differences.\n for clarification see the section titled, \"Smallest Absolute Deviation,\"\n in http://onlinestatbook.com/2/summarizing_distributions/what_is_ct.html\n \"\"\"\n s.sort()\n s_min=s[0]\n s_max=s[len(s)-1]\n result=[]\n for i in range(s_min, s_max, 1):\n sum=0\n for j in s:\n sum += abs(j-i)\n result.append((i,sum))\n result.sort(key=lambda x: x[1])\n return result[0][0]\n\nprint(find_min_abs_diff(s))\n```\n\n 4\n\n", "meta": {"hexsha": "078fd1a35bbc73b87465f579d1fd9f2d3a1d32e2", "size": 3997, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "ch-3/smallest-absolute-difference.ipynb", "max_stars_repo_name": "jhancock1975/online-status-book-exercises", "max_stars_repo_head_hexsha": "70059beffc7f8b2ce84a4bb5c6bcbaf8eda339fa", "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": "ch-3/smallest-absolute-difference.ipynb", "max_issues_repo_name": "jhancock1975/online-status-book-exercises", "max_issues_repo_head_hexsha": "70059beffc7f8b2ce84a4bb5c6bcbaf8eda339fa", "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": "ch-3/smallest-absolute-difference.ipynb", "max_forks_repo_name": "jhancock1975/online-status-book-exercises", "max_forks_repo_head_hexsha": "70059beffc7f8b2ce84a4bb5c6bcbaf8eda339fa", "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.1623931624, "max_line_length": 493, "alphanum_fraction": 0.5631723793, "converted": true, "num_tokens": 756, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067195846919, "lm_q2_score": 0.9343951579736619, "lm_q1q2_score": 0.8806737151375761}} {"text": "# Week 2: Day 2 AM // PDF & Sampling\n\nToday we will learn about\n\n\n1. PDF, PMF, and CDF\n2. Sampling and Sampling Distribution\n3. Central Limit Theorem\n\n\n\n\n```python\nimport numpy as np\nfrom matplotlib import pyplot as plt\nimport scipy\nimport scipy.stats\n\n%matplotlib inline\n```\n\n# CDF, PDF, and PMF\n\n## CDF\n\n$$ F_{X}(x)=P[X \\le x] $$\n\nIn probability theory and statistics, the cumulative distribution function (CDF) of a real-valued random variable ${X}$, or just distribution function of ${X}$, evaluated at ${x}$, is the probability that ${X}$ will take a value less than or equal to ${x}$\n\nIn the case of a scalar continuous distribution, it gives the area under the probability density function from minus infinity to ${x}$. Cumulative distribution functions are also used to specify the distribution of multivariate random variables.\n\nMax value of CDF is always one and min values is always 0\n\n\n```python\ndef my_dist(x,myu=0,sigma=1):\n pf=np.exp(-0.5*((x-myu)/sigma)**2)\n return pf/(sigma*((2*np.pi)**(1/2)))\n\nimport numpy as np\nfrom pylab import *\n\nx = np.arange(-3, 3,0.001)\np = my_dist(x)\n\n# Normalize the data to a proper PDF\nY = p\ndx = 0.001\nY /= (dx * Y).sum()\n\n# Compute the CDF\nCY = np.cumsum(Y * dx)\n\n# Plot both\nplot(x, Y)\nplot(x, CY, 'r--')\n\nshow()\n```\n\n## PDF\n\nIn probability theory, a probability density function (PDF), or density of a continuous random variable, is a function whose value at any given sample (or point) in the sample space (the set of possible values taken by the random variable) can be interpreted as providing a relative likelihood that the value of the random variable would equal that sample.\n\nProperties of PDF:\n1. Area under PDF is always accumulated to one\n2. Integrate the pdf to get the cdf. \n\n\n```python\nfig, ax = plt.subplots(1,2, figsize =(18,4))\n\ndef my_dist(x,myu=0,sigma=1):\n pf=np.exp(-0.5*((x-myu)/sigma)**2)\n return pf/(sigma*((2*np.pi)**(1/2)))\n\nx = np.arange(-3, 3,0.001)\np = my_dist(x)\nax[0].set_title('Handmade norm function')\nax[0].plot(x, p)\n\n\nrv_norm = scipy.stats.norm(0, 1)\np_scp = rv_norm.pdf(x)\nax[1].set_title('Norm function with SciPy')\nax[1].plot(x, p_scp)\nplt.show()\n```\n\n## PMF\n\nIn probability and statistics, a probability mass function is a function that gives the probability that a discrete random variable is exactly equal to some value. Sometimes it is also known as the discrete density function. It can be regarded as PDF in term of discrete variable.\n\n\n```python\nfrom scipy.stats import poisson\nfig, ax = plt.subplots(1, 1)\nmu = 3\nx = np.arange(poisson.ppf(0.00001, mu),poisson.ppf(0.99999, mu))\nax.plot(x, poisson.pmf(x, mu), 'bo', ms=8, label='poisson pmf')\nax.vlines(x, 0, poisson.pmf(x, mu), colors='b', lw=5, alpha=0.5)\n```\n\n## Application of PDF, CDF, PMF: Probability of Events\n\nSuppose we have a distribution of cat weights with mean of 3 and standard deviation of 0.5. For now, do not worry about the meaning mean and std, just keep in mind it is the parameter of a normal distribution. What is the chances for us founding a cat with weight above 3.8 Kg?\n\n\n```python\nfig, ax = plt.subplots(1,1, figsize =(10,4), sharey=True)\nx = np.arange(0, 6,0.001)\nrv_norm = scipy.stats.norm(3, 0.5)\np= rv_norm.pdf(x)\nax.plot(x, p)\nax.set_xlabel('Weight of cat (Kg)')\nthresh_r=3.8\nax.fill_betweenx(p,x1=x,x2=thresh_r, where = x > thresh_r,color='r')\nplt.show()\n```\n\nThe cumulative sum (area) highlighted by the read determine the probability of us finding cat with weight larger than 3.8. This logic of finding an event probability can be applied for many functions, such as anomaly detection.\n\nWe can use CDF to find the probability, as we know CDF is the integral of PDF. Combining it with the concept of complement, we can use the following calculation.\n\nRemember that CDF is defined by integral of PDF starting from the left side to certain point.\n\n\n```python\n1-rv_norm.cdf(3.8)\n```\n\n\n\n\n 0.054799291699557995\n\n\n\n# Common Distribution Functions\n\nOn every distribution functions, there are some key characteristics that we need to take note:\n1. PDF\n2. CDF\n3. Mean (Expected Value)\n4. Variance\n\n## Gaussian Distribution\n\nCommonly found on \"natural\" distribution\n\n$$ f(x) = \\frac{e^{-(x - \\mu)^{2}/(2\\sigma^{2}) }} {\\sigma\\sqrt{2\\pi}} $$\n\n\n```python\nfrom scipy.stats import norm\nfig, ax = plt.subplots(1, 1)\nx = np.linspace(norm.ppf(0.01),norm.ppf(0.99), 100)\nax.plot(x, norm.pdf(x),'r-', lw=5, alpha=0.6, label='norm pdf')\n```\n\n\n```python\n\n```\n\n## Uniform Distribution\n\n$$ f(x) = \\frac{1} {B - A} \\;\\;\\;\\;\\;\\;\\; \\mbox{for} \\ A \\le x \\le B $$\n\n\n```python\nimport random\nrandom.randint(1,5)\n```\n\n\n\n\n 1\n\n\n\n\n```python\nx\n```\n\n\n\n\n array([-2.32634787, -2.27935095, -2.23235402, -2.18535709, -2.13836017,\n -2.09136324, -2.04436631, -1.99736939, -1.95037246, -1.90337553,\n -1.85637861, -1.80938168, -1.76238475, -1.71538783, -1.6683909 ,\n -1.62139397, -1.57439705, -1.52740012, -1.48040319, -1.43340627,\n -1.38640934, -1.33941241, -1.29241549, -1.24541856, -1.19842163,\n -1.15142471, -1.10442778, -1.05743085, -1.01043393, -0.963437 ,\n -0.91644007, -0.86944314, -0.82244622, -0.77544929, -0.72845236,\n -0.68145544, -0.63445851, -0.58746158, -0.54046466, -0.49346773,\n -0.4464708 , -0.39947388, -0.35247695, -0.30548002, -0.2584831 ,\n -0.21148617, -0.16448924, -0.11749232, -0.07049539, -0.02349846,\n 0.02349846, 0.07049539, 0.11749232, 0.16448924, 0.21148617,\n 0.2584831 , 0.30548002, 0.35247695, 0.39947388, 0.4464708 ,\n 0.49346773, 0.54046466, 0.58746158, 0.63445851, 0.68145544,\n 0.72845236, 0.77544929, 0.82244622, 0.86944314, 0.91644007,\n 0.963437 , 1.01043393, 1.05743085, 1.10442778, 1.15142471,\n 1.19842163, 1.24541856, 1.29241549, 1.33941241, 1.38640934,\n 1.43340627, 1.48040319, 1.52740012, 1.57439705, 1.62139397,\n 1.6683909 , 1.71538783, 1.76238475, 1.80938168, 1.85637861,\n 1.90337553, 1.95037246, 1.99736939, 2.04436631, 2.09136324,\n 2.13836017, 2.18535709, 2.23235402, 2.27935095, 2.32634787])\n\n\n\n\n```python\nfrom scipy.stats import uniform\nfig, ax = plt.subplots(1, 1)\n#x = np.linspace(uniform.ppf(0.01,loc=1,scale=6),uniform.ppf(0.99,loc=1,scale=6), 100)\nx = np.linspace(0,7, 100)\nax.plot(x, uniform.pdf(x,loc=2,scale=3),'r-', lw=5, alpha=0.6, label='uniform pdf')\n```\n\n\n```python\nfrom scipy.stats import uniform\nfig, ax = plt.subplots(1, 1,figsize=(15,3))\ncolors = ['r','b','m']\nfor idx,scale in enumerate([0.5,1,2]):\n color = colors[idx]\n #x = np.arange(1,10,1)\n #x = np.linspace(uniform.ppf(0.01,scale=scale),uniform.ppf(0.99,scale=scale), 100)\n x = np.linspace(0,5, 100)\n ax.plot(x, uniform.pdf(x,loc=1,scale=scale),str(color)+'-', lw=5, alpha=0.6, label='Scale='+str(scale))\n ax.legend()\n```\n\n\n```python\n\n```\n\n## Exponential Distribution\n\nConsider a packet router that passes arriving packets to next destination routers. Measure the time \nbetween successive packets arrivals, referred to as the packet **inter-arrival time** (expected value).\n\n$$ f(x) = \\lambda e^{-\\lambda x} $$\n\n$ \\lambda $ = rate of distribution\n\n\n```python\nfrom scipy.stats import expon \nfig, ax = plt.subplots(1, 1)\n\nx = np.linspace(expon.ppf(0.01),expon.ppf(0.99), 100)\nax.plot(x, expon.pdf(x),'r-', lw=5, alpha=0.6, label='expon pdf')\n```\n\n\n```python\n\n```\n\n\n```python\nfrom scipy.stats import expon \nfig, ax = plt.subplots(1, 1)\n\ncolors = ['r','b','m']\nfor idx,lambda_ in enumerate([0.5,1,2]):\n color = colors[idx]\n x = np.linspace(0,5, 100)\n scale = 1/lambda_\n ax.plot(x, expon.pdf(x,scale=scale),str(color)+'-', lw=5, alpha=0.6, label='Lambda='+str(lambda_))\n ax.legend()\n```\n\nhttps://en.wikipedia.org/wiki/Exponential_distribution\n\n## Gamma Distribution\n\n$$ f(x) = \\frac{(\\frac{x-\\mu}{\\beta})^{\\gamma - 1}\\exp{(-\\frac{x-\\mu}\n{\\beta}})} {\\beta\\Gamma(\\gamma)} \\hspace{.2in} x \\ge \\mu; \\gamma,\n\\beta > 0 $$\n\n\n```python\nfrom scipy.stats import gamma\nfig, ax = plt.subplots(1, 1)\nbeta = 5\nx = np.linspace(gamma.ppf(0.000000001,beta),gamma.ppf(0.99,beta), 100)\nax.plot(x, gamma.pdf(x,beta),'r-', lw=5, alpha=0.6, label='norm pdf')\n```\n\n## Poisson Distribution\n\nThe number of arrivals has a Poisson distribution.\n\n$$ p(x;\\lambda) = \\frac{e^{-\\lambda}\\lambda^{x}} {x!} \\mbox{ for } \nx = 0, 1, 2, \\cdots $$\n\n\n```python\nfrom scipy.stats import poisson\nfig, ax = plt.subplots(1, 1)\nmu = 1\nx = np.arange(poisson.ppf(0.00001, mu),poisson.ppf(0.99999, mu))\nax.plot(x, poisson.pmf(x, mu), 'bo', ms=8, label='poisson pmf')\nax.vlines(x, 0, poisson.pmf(x, mu), colors='b', lw=5, alpha=0.5)\n```\n\n## Binomial Distribution\n\nToss a biased coin. The coin falls down heads with probability p.\n\n$$ P(x;p,n) = \\left( \\begin{array}{c} n \\\\ x \\end{array} \\right)\n (p)^{x}(1 - p)^{(n-x)} \\;\\;\\;\\;\\;\\; \\mbox{for $x = 0, 1, 2, \\cdots , n$} $$\n\n\n```python\nfrom scipy.stats import binom\nfig, ax = plt.subplots(1, 1)\n\nn, p = 10, 0.5\n\nx = np.arange(binom.ppf(0.01, n, p),\n binom.ppf(0.99, n, p))\nax.plot(x, binom.pmf(x, n, p), 'bo', ms=8, label='binom pmf')\nax.vlines(x, 0, binom.pmf(x, n, p), colors='b', lw=5, alpha=0.5)\n```\n\n## Geometric Distribution\n\nToss a biased coin. k is the number of times we toss the coin until we see the first head.\n\n$$ f(k)=(1-p)^{k-1}p \\;\\;\\;\\;\\;\\; \\mbox{for $k \\ge 1, 0

3/16 or 0.1875. This is our proportion (or **p**); but because we know that this is based on a sample, we call it **p̂** (or p-hat). The remaining proportion of passengers is 1-p; in this case 1 - 0.1875, which is 0.8125.\n\nThe data itself is *qualitative* (categorical) - we're indicating \"no search\" or \"search\"; but because we're using numeric values (0 and 1), we can treat these values as numeric and create a binomial distribution from them - it's the simplest form of a binomial distribution - a Bernoulli distribution with two values.\n\nBecause we're treating the results as a numberic distribution, we can also calculate statistics like *mean* and *standard deviation*:\n\nTo calculate these, you can use the following formulae:\n\n$$\n\\begin{equation}\\mu_{\\hat{p}} = \\hat{p}\\end{equation}\n$$\n\n$$\n\\begin{equation}\\sigma_{\\hat{p}} = \\sqrt{\\hat{p}(1-\\hat{p})}\\end{equation}\n$$\n\nThe mean is just the value of **p̂**, so in the case of the passenger search sample it is 0.1875.\n\nThe standard deviation is calculated as:\n\n$$\n\\begin{equation}\\sigma_{\\hat{p}} = \\sqrt{0.1875 \\times 0.8125} \\approx 0.39\\end{equation}\n$$\n\nWe can use Python to plot the sample distribution and calculate the mean and standard deviation of our sample like this:\n\n\n```python\n%matplotlib inline\nfrom matplotlib import pyplot as plt\nimport numpy as np\n\nsearches = np.array([0,1,0,0,1,0,0,0,0,0,0,0,1,0,0,0])\n\n# Set up the graph\nplt.xlabel('Search Results')\nplt.ylabel('Frequency')\nplt.hist(searches)\nplt.show()\nprint('Mean: ' + str(np.mean(searches)))\nprint('StDev: ' + str(np.std(searches)))\n```\n\nWhen talking about probability, the *mean* is also known as the *expected value*; so based on our single sample of 16 passengers, should we expect the proportion of searched passengers to be 0.1875 (18.75%)?\n\nWell, using a single sample like this can be misleading because the number of searches can vary with each sample. Another person observing 100 passengers may get a (very) different result from you. One way to address this problem is to take multiple samples and combine the resulting means to form a *sampling* distribution. This will help us ensure that the distribution and statistics of our sample data is closer to the true values; even if we can't measure the full population.\n\n### Creating a Sampling Distribution of a Sample Proportion\nSo, let's collect mulitple 16-passenger samples - here are the resulting sample proportions for 12 samples:\n\n| Sample | Result |\n|--------|--------|\n| p̂1| 0.1875 |\n| p̂2| 0.2500 |\n| p̂3| 0.3125 |\n| p̂4| 0.1875 |\n| p̂5| 0.1250 |\n| p̂6| 0.3750 |\n| p̂7| 0.2500 |\n| p̂8| 0.1875 |\n| p̂9| 0.3125 |\n| p̂10| 0.2500 |\n| p̂11| 0.2500 |\n| p̂12| 0.3125 |\n\nWe can plot these as a sampling distribution like this:\n\n\n```python\n%matplotlib inline\nfrom matplotlib import pyplot as plt\nimport numpy as np\n\nsearches = np.array([0.1875,0.25,0.3125,0.1875,0.125,0.375,0.25,0.1875,0.3125,0.25,0.25,0.3125])\n\n# Set up the graph\nplt.xlabel('Search Results')\nplt.ylabel('Frequency')\nplt.hist(searches)\nplt.show()\n```\n\n#### The Central Limit Theorem\nYou saw previously with the binomial probability distribution, with a large enough sample size (the *n* value indicating the number of binomial experiments), the distribution of values for a random variable started to form an approximately *normal* curve. This is the effect of the *central limit theorem*, and it applies to any distribution of sample data if the size of the sample is large enough. For our airport passenger data, if we collect a large enough number of samples, each based on a large enough number of passenger observations, the sampling distribution will be approximately normal. The larger the sample size, the closer to a perfect *normal* distribution the data will be, and the less variance around the mean there will be.\n\nRun the cell below to see a simulated distribution created by 10,000 random 100-passenger samples:\n\n\n```python\n%matplotlib inline\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nn, p, s = 100, 0.25, 10000\ndf = pd.DataFrame(np.random.binomial(n,p,s)/n, columns=['p-hat'])\n\n# Plot the distribution as a histogram\nmeans = df['p-hat']\nmeans.plot.hist(title='Simulated Sampling Distribution') \nplt.show()\nprint ('Mean: ' + str(means.mean()))\nprint ('Std: ' + str(means.std()))\n```\n\n\n```python\ndf\n```\n\n\n\n\n

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
p-hat
00.18
10.22
20.17
30.19
40.23
......
99950.19
99960.24
99970.22
99980.27
99990.27
\n

10000 rows × 1 columns

\n
\n\n\n\n### Mean and Standard Error of a Sampling Distribution of Proportion\nThe sampling distribution is created from the means of multiple samples, and its mean is therefore the mean of all the sample means. For a distribution of proportion means, this is considered to be the same as **p** (the population mean). In the case of our passenger search samples, this is 0.25.\n\nBecause the sampling distribution is based on means, and not totals, its standard deviation is referred to as its *standard error*, and its formula is:\n\n$$\n\\begin{equation}\\sigma_{\\hat{p}} = \\sqrt{\\frac{p(1-p)}{n}}\\end{equation}\n$$\n\nIn this formula, *n* is the size of each sample; and we divide by this to correct for the error introduced by the average values used in the sampling distribution. In this case, our samples were based on observing 16-passengers, so:\n\n$$\n\\begin{equation}\\sigma_{\\hat{p}} = \\sqrt{\\frac{0.25 \\times 0.75}{16}} \\approx 0.11\\end{equation}\n$$\n\nIn our simulation of 100-passenger samples, the mean remains 0.25. The standard error is:\n\n$$\n\\begin{equation}\\sigma_{\\hat{p}} = \\sqrt{\\frac{0.25 \\times 0.75}{100}} \\approx 0.043\\end{equation}\n$$\n\nNote that the effect of the central limit theorem is that as you increase the number and/or size of samples, the mean remains constant but the amount of variance around it is reduced.\n\nBeing able to calculate the mean (or *expected value*) and standard error is useful, because we can apply these to what we know about an approximately normal distribution to estimate probabilities for particular values. For example, we know that in a normal distribution, around 95.4% of the values are within two standard deviations of the mean. If we apply that to our sampling distribution of ten thousand 100-passenger samples, we can determine that the proportion of searched passengers in 95.4% of the samples was between 0.164 (16.4%) and 0.336 (36.6%).\n\nHow do we know this?\n\nWe know that the mean is ***0.25*** and the standard error (which is the same thing as the standard deviation for our sampling distribution) is ***0.043***. We also know that because this is a *normal* distribution, ***95.4%*** of the data lies within two standard deviations (so 2 x 0.043) of the mean, so the value for 95.4% of our samples is 0.25 ± (*plus or minus*) 0.086.\n\nThe *plus or minus* value is known as the *margin of error*, and the range of values within it is known as a *confidence interval* - we'll look at these in more detail later. For now, run the following cell to see a visualization of this interval:\n\n\n```python\n%matplotlib inline\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nn, p, s = 100, 0.25, 10000\ndf = pd.DataFrame(np.random.binomial(n,p,s)/n, columns=['p-hat'])\n\n# Plot the distribution as a histogram\nmeans = df['p-hat']\nm = means.mean()\nsd = means.std()\nmoe1 = m - (sd * 2)\nmoe2 = m + (sd * 2)\n\n\nmeans.plot.hist(title='Simulated Sampling Distribution') \n\nplt.axvline(m, color='red', linestyle='dashed', linewidth=2)\nplt.axvline(moe1, color='magenta', linestyle='dashed', linewidth=2)\nplt.axvline(moe2, color='magenta', linestyle='dashed', linewidth=2)\nplt.show()\n```\n\n### Creating a Sampling Distribution of Sample Means\nIn the previous example, we created a sampling distribution of proportions; which is a suitable way to handle discrete values, like the number of passengers searched or not searched. When you need to work with continuous data, you use slightly different formulae to work with the sampling distribution.\n\nFor example, suppose we want to examine the weight of the hand luggage carried by each passenger. It's impractical to weigh every bag that is carried through security, but we could weigh one or more samples, for say, 5 passengers at a time, on twelve occassions. We might end up with some data like this:\n\n| Sample | Weights |\n|--------|---------|\n| 1 | [4.020992,2.143457,2.260409,2.339641,4.699211] |\n| 2 | [3.38532,4.438345,3.170228,3.499913,4.489557] |\n| 3 | [3.338228,1.825221,3.53633,3.507952,2.698669] |\n| 4 | [2.992756,3.292431,3.38148,3.479455,3.051273] |\n| 5 | [2.969977,3.869029,4.149342,2.785682,3.03557] |\n| 6 | [3.138055,2.535442,3.530052,3.029846,2.881217] |\n| 7 | [1.596558,1.486385,3.122378,3.684084,3.501813] |\n| 8 | [2.997384,3.818661,3.118434,3.455269,3.026508] |\n| 9 | [4.078268,2.283018,3.606384,4.555053,3.344701] |\n| 10 | [2.532509,3.064274,3.32908,2.981303,3.915995] |\n| 11 | [4.078268,2.283018,3.606384,4.555053,3.344701] |\n| 12 | [2.532509,3.064274,3.32908,2.981303,3.915995] |\n\nJust as we did before, we could take the mean of each of these samples and combine them to form a sampling distribution of the sample means (which we'll call **X**, and which will contain a mean for each sample, which we'll label x̄n):\n\n| Sample | Mean Weight |\n|--------|---------|\n| x̄1 | 3.092742 |\n| x̄2 | 3.7966726 |\n| x̄3 | 2.98128 |\n| x̄4 | 3.239479 |\n| x̄5 | 3.36192 |\n| x̄6 | 3.0229224 |\n| x̄7 | 2.6782436 |\n| x̄8 | 3.2832512 |\n| x̄9 | 3.5734848 |\n| x̄10 | 3.1646322 |\n| x̄11 | 3.5734848 |\n| x̄12 | 3.1646322 |\n\nWe can plot the distribution for the sampling distribution like this:\n\n\n```python\n%matplotlib inline\nfrom matplotlib import pyplot as plt\nimport numpy as np\n\nmeanweights = np.array([3.092742,\n 3.7966726,\n 2.98128,\n 3.239479,\n 3.36192,\n 3.0229224,\n 2.6782436,\n 3.2832512,\n 3.5734848,\n 3.1646322,\n 3.5734848,\n 3.1646322])\n\n# Set up the graph\nplt.xlabel('Mean Weights')\nplt.ylabel('Frequency')\nplt.hist(meanweights, bins=6)\nplt.show()\n\nprint('Mean: ' + str(meanweights.mean()))\nprint('Std: ' + str(meanweights.std()))\n```\n\nJust as before, as we increase the sample size, the central limit theorem ensures that our sampling distribution starts to approximate a normal distribution. Our current distribution is based on the means generated from twelve samples, each containing 5 weight observations. Run the following code to see a distribution created from a simulation of 10,000 samples each containing weights for 500 passengers:\n\n>This may take a few minutes to run. The code is not the most efficient way to generate a sample distribution, but it reflects the principle that our sampling distribution is made up of the means from multiple samples. In reality, you could simulate the sampling by just creating a single sample from the ***random.normal*** function with a larger ***n*** value.\n\n\n```python\n\n```\n\n\n```python\n%matplotlib inline\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nmu, sigma, n = 3.2, 1.2, 500\nsamples = list(range(0, 10000))\n\n# data will hold all of the sample data\ndata = np.array([])\n\n# sampling will hold the means of the samples\nsampling = np.array([])\n\n# Perform 10,000 samples\nfor s in samples:\n # In each sample, get 500 data points from a normal distribution\n sample = np.random.normal(mu, sigma, n)\n data = np.append(data,sample)\n sampling = np.append(sampling,sample.mean())\n\n# Create a dataframe with the sampling of means\ndf = pd.DataFrame(sampling, columns=['mean'])\n\n# Plot the distribution as a histogram\nmeans = df['mean']\nmeans.plot.hist(title='Simulated Sampling Distribution', bins=100) \nplt.show()\n\n# Print the Mean and StdDev for the full sample and for the sampling distribution\nprint('Sample Mean: ' + str(data.mean()))\nprint('Sample StdDev: ' + str(data.std()))\nprint ('Sampling Mean: ' + str(means.mean()))\nprint ('Sampling StdErr: ' + str(means.std()))\n```\n\n### Mean and Variance of the Sampling Distribution\n\nThe following variables are printed beneath the histogram:\n\n- **Sample Mean**: This is the mean for the complete set of sample data - all 10,000 x 500 bag weights.\n- **Sample StdDev**: This is the standard deviation for the complete set of sample data - all 10,000 x 500 bag weights.\n- **Sampling Mean**: This is the mean for the sampling distribution - the means of the means!\n- **Sampling StdErr**: This is the standard deviation (or *standard error*) for the sampling distribution\n\nIf we assume that **X** is a random variable representing every possible bag weight, then its mean (indicated as **μx**) is the population mean (**μ**). The mean of the **X** sampling distribution (which is indicated as **μ**) is considered to have the same value. Or, as an equation:\n\n$$\n\\begin{equation}\\mu_{x} = \\mu_{\\bar{x}}\\end{equation}\n$$\n\nIn this case, the full population mean is unknown (unless we weigh every bag in the world!), but we do have the mean of the full set of sample observations we collected (**x̄**), and if we check the values generated by Python for the sample mean and the sampling mean, they're more or less the same: around 3.2.\n\nTo find the standard deviation of the sample mean, which is technically the *standard error*, we can use this formula:\n\n$$\n\\begin{equation}\\sigma_{\\bar{x}} = \\frac{\\sigma}{\\sqrt{n}}\\end{equation}\n$$\n\nIn this formula, ***σ*** is the population standard deviation and ***n*** is the size of each sample.\n\nSince our the population standard deviation is unknown, we can use the full sample standard deviation instead:\n\n$$\n\\begin{equation}SE_{\\bar{x}} \\approx \\frac{s}{\\sqrt{n}}\\end{equation}\n$$\n\nIn this case, the standard deviation of our set of sample data is around 1.2, and we have used 500 variables in each sample to calculate our sample means, so:\n\n$$\n\\begin{equation}SE_{\\bar{x}} \\approx \\frac{1.2}{\\sqrt{500}} = \\frac{1.2}{22.36} \\approx 0.053\\end{equation}\n$$\n\n## Confidence Intervals\nA confidence interval is a range of values around a sample statistic within which we are confident that the true parameter lies. For example, our bag weight sampling distribution is based on samples of the weights of bags carried by passengers through our airport security line. We know that the mean weight (the *expected value* for the weight of a bag) in our sampling distribution is 3.2, and we assume this is also the population mean for all bags; but how confident can we be that the true mean weight of all carry-on bags is close to the value?\n\nLet's start to put some precision onto these terms. We could state the question another way. What's the range of weights within which are confident that the mean weight of a carry-on bag will be 95% of the time? To calculate this, we need to determine the range of values within which the population mean weight is likely to be in 95% of samples. This is known as a *confidence interval*; and it's based on the Z-scores inherent in a normal distribution.\n\nConfidence intervals are expressed as a sample statistic ± (*plus or minus*) a margin of error. To calculate the margin of error, you need to determine the confidence level you want to find (for example, 95%), and determine the Z score that marks the threshold above or below which the values that are *not* within the chosen interval reside. For example, to calculate a 95% confidence interval, you need the critical Z scores that exclude 5% of the values under the curve; with 2.5% of them being lower than the values in the confidence interval range, and 2.5% being higher. In a normal distribution, 95% of the area under the curve is between a Z score of ± 1.96. The following table shows the critical Z values for some other popular confidence interval ranges:\n\n| Confidence | Z Score |\n|-------------|---------|\n| 90% | 1.645 |\n| 95% | 1.96 |\n| 99% | 2.576 |\n\n\nTo calculate a confidence interval around a sample statistic, we simply calculate the *standard error* for that statistic as described previously, and multiply this by the approriate Z score for the confidence interval we want.\n\nTo calculate the 95% confidence interval margin of error for our bag weights, we multiply our standard error of 0.053 by the Z score for a 95% confidence level, which is 1.96:\n\n$$\n\\begin{equation}MoE = 0.053 \\times 1.96 = 0.10388 \\end{equation}\n$$\n\nSo we can say that we're confident that the population mean weight is in the range of the sample mean ± 0.10388 with 95% confidence. Thanks to the central limit theorem, if we used an even bigger sample size, the confidence interval would become smaller as the amount of variance in the distribution is reduced. If the number of samples were infinite, the standard error would be 0 and the confidence interval would become a certain value that reflects the true mean weight for all carry-on bags:\n\n$$\n\\begin{equation}\\lim_{n \\to \\infty} \\frac{\\sigma}{\\sqrt{n}} = 0\\end{equation}\n$$\n\nIn Python, you can use the *scipy.stats.**norm.interval*** function to calculate a confidence interval for a normal distribution. Run the following code to recreate the sampling distribution for bag searches with the same parameters, and display the 95% confidence interval for the mean (again, this may take some time to run):\n\n\n```python\n%matplotlib inline\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom scipy import stats\n\nmu, sigma, n = 3.2, 1.2, 500\nsamples = list(range(0, 10000))\n\n# data will hold all of the sample data\ndata = np.array([])\n\n# sampling will hold the means of the samples\nsampling = np.array([])\n\n# Perform 10,000 samples\nfor s in samples:\n # In each sample, get 500 data points from a normal distribution\n sample = np.random.normal(mu, sigma, n)\n data = np.append(data,sample)\n sampling = np.append(sampling,sample.mean())\n\n# Create a dataframe with the sampling of means\ndf = pd.DataFrame(sampling, columns=['mean'])\n\n# Get the Mean, StdDev, and 95% CI of the means\nmeans = df['mean']\nm = means.mean()\nsd = means.std()\nci = stats.norm.interval(0.95, m, sd)\n\n# Plot the distribution, mean, and CI\nmeans.plot.hist(title='Simulated Sampling Distribution', bins=100) \nplt.axvline(m, color='red', linestyle='dashed', linewidth=2)\nplt.axvline(ci[0], color='magenta', linestyle='dashed', linewidth=2)\nplt.axvline(ci[1], color='magenta', linestyle='dashed', linewidth=2)\nplt.show()\n\n# Print the Mean, StdDev and 95% CI\nprint ('Sampling Mean: ' + str(m))\nprint ('Sampling StdErr: ' + str(sd))\nprint ('95% Confidence Interval: ' + str(ci))\n```\n\nIn Normal Distribution 95% confidence interval are located at $(\\mu - 1.645\\sigma,\\mu + 1.645\\sigma)$ \n", "meta": {"hexsha": "5a6ae369468b7acb6ad847694a8a1cff2a72864e", "size": 319222, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "learning_material/p0/w3/d2am.ipynb", "max_stars_repo_name": "madinHA8/H8_FTDS_001", "max_stars_repo_head_hexsha": "86de98d4f0edf35902d4b667f59555c82f79fe34", "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": "learning_material/p0/w3/d2am.ipynb", "max_issues_repo_name": "madinHA8/H8_FTDS_001", "max_issues_repo_head_hexsha": "86de98d4f0edf35902d4b667f59555c82f79fe34", "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": "learning_material/p0/w3/d2am.ipynb", "max_forks_repo_name": "madinHA8/H8_FTDS_001", "max_forks_repo_head_hexsha": "86de98d4f0edf35902d4b667f59555c82f79fe34", "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": 159.611, "max_line_length": 34568, "alphanum_fraction": 0.8863580831, "converted": true, "num_tokens": 9692, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810407096791, "lm_q2_score": 0.9294404018582427, "lm_q1q2_score": 0.8805342151900843}} {"text": "## Exercise 2.9 Conditional independence\n(Source: Koller.) Are the following properties true? Prove or disprove. Note that we are not restricting\nattention to distributions that can be represented by a graphical model. \n* a. True or false? $(X\\perp W|Z,Y)\\land(X\\perp Y|Z)\\Rightarrow(X\\perp Y,W|Z)$\n* b. True or false?$(X\\perp Y|Z)\\land(X\\perp Y|W)\\Rightarrow(X\\perp Y|Z,W)$\n\n### Solution\n#### (a)\nWe have two information about conditional independence: The first one is\n\n$$\nX\\perp W |Z, Y.\n$$\n\nBased on this, we can state:\n\\begin{equation}\np(x, w |z, y) = p(x |z, y) p(w|z, y) \n\\end{equation}\n\nThe second one is:\n\n$$\nX\\perp Y|Z\n$$\n\nBased on this, we can state that:\n\n\\begin{equation}\np(x, y|z) = p(x|z)p(y|z)\n\\end{equation}\n\nNow we have to see if $X\\perp Y, W|Z$ is true.\n\n\\begin{equation}\np(x, y, w|z) = p(w|y, x, z)p(y|x, z)p(x|z) = p(x|z)p(y|z)p(w|y, z) = p(x|z)p(y, w|z)\n\\end{equation}\n\n- The first passage is the chain rule of probability\n- The second makes use of the conditional independences given to us ($Y$ does not dependent on $X$ given $Z$ and $W$ does not depend on $X$ given $Z$ and $Y$)\n- The third puts the joint distribution back together. So the proposition is **True**.\n\n#### (b)\nProve this proposition is false with a counter example. Start by defining $X$, $Y$ and $Z$ to be iid random variables with the following distribution:\n\n\\begin{equation}\\left\\{\n\\begin{array}{l}\nP(X=1) = 0.5 \\\\ \nP(X=-1) = 0.5\n\\end{array}\\right.\n\\end{equation}\n\nAlso, define $W=XYZ$. First prove that the two conditional independences $X\\perp Y|Z$ and $X\\perp Y|W$ are true.\n", "meta": {"hexsha": "04800cb9967fe9f7dd7c22611a37ea11b7d34349", "size": 2711, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "murphy-book/chapter02/q09.ipynb", "max_stars_repo_name": "yusueliu/murphy-book", "max_stars_repo_head_hexsha": "71d62cc083a683fb861be1e5acb8eeb948b00c54", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-03-25T22:22:23.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-29T20:46:58.000Z", "max_issues_repo_path": "murphy-book/chapter02/q09.ipynb", "max_issues_repo_name": "yusueliu/murphy-book", "max_issues_repo_head_hexsha": "71d62cc083a683fb861be1e5acb8eeb948b00c54", "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": "murphy-book/chapter02/q09.ipynb", "max_forks_repo_name": "yusueliu/murphy-book", "max_forks_repo_head_hexsha": "71d62cc083a683fb861be1e5acb8eeb948b00c54", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-24T01:14:12.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-24T01:14:12.000Z", "avg_line_length": 28.8404255319, "max_line_length": 167, "alphanum_fraction": 0.5304315751, "converted": true, "num_tokens": 545, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.944176863577751, "lm_q2_score": 0.9324533158993963, "lm_q1q2_score": 0.8804008472385658}} {"text": "# Generating Fractals\n\nHere we will be generating fractals and learning about a few things as well\n\n1. Complex numbers (very breifly) \n2. Root finding (this is a good primer for gradient decent for those of you with ML on the mind) \n3. Thinking iteratively ( very important nor numerical mathematics) \n\n## Complex Numbers\n\nBefore we start talking about fractals, we should probably introduce the idea of a complex number before hand, as the fractas we will be generating rely heavily on them. I'll note that this may get kind of deep into some mathematics, and if you want to skip this section you totally can. There are som quirks to complex numbers, but luckily Python will handle them for you, and realistically they will behave like any other number in Python (for our purposes).\n\nFirst and foremost, let us introduce the complex number $i$\n$$\n\\begin{equation}\ni = \\sqrt{-1} \\implies i^2 = -1\n\\end{equation}\n$$\n\nwhere $i$ is known as the imaginary number, or some impossible number that when multiplied by itself, returns a negative number. At first this might be concerning, but we must remember that when it comes to math, we made it all up anyways, so why not make up another number for fun? However, that line of thinking might be more concerning, so let's move on.\n\nMore often than not, we will write a complex number as $z$, which is written as the sum of an imaginary numers real and complex parts, \n\n$$\nz = a + ib\n$$\nwhere $a$ is the real part of the complex number $z$, and $b$ is the complex or imaginary part. \n\nIf you're curious, you can get more details about complex numbers using the drop down below. For our purposes however, all that you really need to know is the following:\n\n1. A complex number $a + ib$ can be thought of as the classical $x,y$ ordered pair we're used to. In this case our $x$ axis is the real part of the number, and our $y$ axis is the imaginary part of the number\n\n2. These $(a, b)$ ordered pairs can be used to define the \"complex plane\", which we will use to plot our fractals\n\n
\n

More details on complex numbers (not required)

\n\n
\nThere are a lot of very useful properties that come from imaginary numbers, and they're used all the time in fiels such as pure mathematics, signal processing, physics, chemistry, fluid dynamics... in principle we could go on forever. The largest reason for this is due to something known as [eulers formula](https://en.wikipedia.org/wiki/Euler%27s_formula), where we instead think of complex numbers on the \"complex plane\", with the real part of the function $a$ representing our $x$ axis, and the imaginary part of our function $b$ on the $y$ axis. Euler's formula states that we can write the exponential of a complex number as follows\n\n$$\ne^{ix} = r (\\cos \\theta + i\\sin \\theta)\n$$\nwhere $r$ is the radius of tihs circle on the complex plane (more on this later).\nFor those of you mathematically inclined and want to prove this, the easiest way is to write out the Taylor series for each $e^{ix}, i\\sin \\theta$ and $\\cos \\theta$, and you may be surprised what you see. \n\nLong story short, using Euler's formula, we can essentially write any complex number in terms of sine and cosine, this is useful for a whole lot of reasons, but for fractals specificially, this implies periodic boundary conditions -- we expect to see repeating patterns. Indeed, as cosine and sine have $N$ roots repeating every $\\pi$, we expect that our complex functions may also have (up to) that many roots!\n\n\n\n\n### Finding Roots Of Complex Polynomials\n\nWe all remember polynomial equations of real numbers, for example the quadratic function\n\n$$\nx^2 - C = 0\n$$\nwhere we can all read quite readily that the solution to this equation is $x = \\pm \\sqrt{C}$. But what about if we have some complex polynomial like\n\n$$\nz^2 + C = 0,\n$$\n\nTo be honest, I pulled a fast one on you. It' just as easy! In this case, we have two roots which are $\\pm i \\sqrt{C} $, where we just bring our friend the imaginary unit along for the ride. In principle what we do is we once again factor this into the real and imaginary part of the solution, but often it's easier to think of this (in a way that will make mathmaticians cry) we simply get rid of the part we don't like, and call it $i$. For quadratic complex polynomial equations, we can simply use the quadratic formula and sprinkle in the imaginary unit where ever we need it. This is a bit of an over simplification, but for our purposes it should be fine. \n\nWhere this can get a little spicier is when the roots aren't obvious enough to be read off. For example, the equation\n\n$$\nz^3 = 1,\n$$\n\nis cubic, which means we have three distinct roots which satisfy this equation. In this case, it is easier to look at our friend Euler's formula to find these roots. So let's rewrite our complex equation above using euler's formula. First, the left hand side\n\n$$\nz = r e^{ix} \\implies z^3 = r^3 e^{3ix}\n$$\n\nand the right hand side:\n\n$$\n1 = re^{ix} = r (\\cos \\theta + i\\sin \\theta)\n$$\n\nWhere, as one has no complex component, we know that this must be one. Therefore, $r$ is equal to one in this equation, angles are those where cosine is one and sine is zero, or $\\theta = 2\\pi k$ where $k$ is an integer. Therefore, we have \n\n$$\ne^{3ix} = e^{2\\pi k}\n$$\n\nor by taking the natural logarithm of each side,\n\n$$\nix = \\frac{2 \\pi k}{3} \n$$\n\nAnd going back to our original equation:\n\n$$\nz = e^{ix} = e^{\\frac{2 \\pi k}{3}}\n$$\n\nWhere we can take our first three roots as $k = -1, 0, 1$ and obtain\n\n$$\nz = 1, e^{2\\pi i/3}, e^{-2\\pi i/3}\n$$\n\nWe also note we have periodic roots at integer values of $k$, but we won't worry about those. Knowing these roots are useful in terms of understanding the behaviour of our fractals. We may expect that different roots may cause different basins of convergence, or result in rotations of our fractal. This is also important with respect to establishing the domains in which our fractals may exist.\n
\n\n# Root Finding With Complex Numbers\n\nIf you were crazy enough to read the drop down menu, you may have noticed that finding roots to complex equations were more work that the quadratic formula. And if you take anything away from these notebooks it should be that we Data Scientists (and regular scientists) are _super_ lazy. Wouldn't it be nice if we could use our computer to solve these for us? Luckily, the answer is a resounding yes! And even more better is that our Newton Raphson formula from before generalizes to the complex domain without us having to do anything. Convenient! \n\nOne thing to be aware of however in Python is we will need to define complex numbers. It's quite simple. For a complex number $ a + ib$, we can define that in python like\n\n```python3\na = b = 1\ncomplex_number = complex(a, b)\n```\n\nand we can then throw that number at our root finding routines as we did before and find ourselves solutions.\n\n## My First Fractal: Mandelbrot\n\nBefore we go into root finding for fractals, let's start with a relatively simple one to generate the Mandelbrot. Rather than have me drone on for a year, here's a YouTube video that does a better job than I could explaining that set. \n\n\n```python\nfrom IPython.display import YouTubeVideo\nYouTubeVideo('NGMRB4O922I')\n```\n\n\n\n\n\n\n\n\n\n\n# Your Task\n\nWrite two functions, the first function will be to calculate the Mandelbrot set as follows\n\n### Mandelbrot Function\n1. Initialize $z$ and the number of iterations $n$ as zero,\n - Also intialize the maximum iterations as 80\n2. while `abs(z) <= 2 and n < max_iter` do the following\n * $z = z^2 + c$\n * n += 1\n3. On exit, return the number of iterations $n$\n\n\n```python\n# note the **kwargs is not strictly necessary, and won'tdo anything here, but will be useful\n# if you want to use some of the provided functions later. \n\ndef mandelbrot(c, max_iter = 80, **kwargs):\n '''\n here c is any complex number, and max_iter is the maximum numberof iterations through your loop\n you want to go\n '''\n z = # YOUR CODE HERE\n n = # YOUR CODE HERE\n while CONDITION: # YOUR CODE HERE\n z = SOMETHING #YOUR CODE HERE\n n += 1\n \n return n\n \n```\n\n### Iteration Function\n\nYou will also need a function which iterates across the complex plane to see what pixel you should generate there. This function itself will require three functions\n\n1. A scale function to convert pixel location into complex coordinates\n2. A scale function to convert the number of itereations in your `mandelbrot` function into an RGB color scale\n3. A function which iterates over pixels with a given height and width for your image. \n\nIn principle we will have the following pseudocode for point 3 which will encompass the other functions\n\n---\n```python\ndef CreateImage(mandelbrot, height, width, domain):\n\n ImageMap = np.zeros([width, height])\n \n for x in range(0, width):\n for y in range(0, height):\n \n c = scale_function_coordinate(x, y, width, height, real_max, real_min, complex_max, complex_min)\n \n m = mandelbrot(c)\n \n color = color_function(m)\n \n X[x,y] = color\n \n return ImageMap\n \n```\n---\nWhere let's outline those functions explicitly \n\n##### Pixel Scale Function\n\nGiven a pixel coordinate $x$ and $y$, we need to convert this location into a complex number within our domain. the formula for this is as follows\n\n$$\nR = R_{min} + \\frac{x}{\\text{Image Width}} \\times (R_{max} - R_{min})\n$$\n\nWhere $R$ is your value in the real coordinate, $R_{min}$ is the smallest value in the real domain, and $R_{max}$ is the largest value in the real domain, $x$ is the current pixel, and Image Width is the width of the image in pixels you want to create. A similar formula for the complex domain is as follows \n\n$$\nC = C_{min} + \\frac{x}{\\text{Image Height}} \\times (C_{max} - C_{min})\n$$\n\nWhere $C$ is your value in the complex coordinate, $C_{min}$ is the smallest value in the complex domain, $C_{max}$ is the largest value in the complex domain, $x$ is the current pixel, and Image Height is the height of the image in pixels you want to create. \n\nIn this case, if we have a known image size in advance, and we know the domain in which our fractal will exist, we can calculate the complex value $c$ at this place in our image. Please fill in the function below\n\n\n```python\nimport numpy as np\ndef scale_function_coordinate(x, y, width, height, r_max, r_min, c_max, c_min):\n '''\n x --> x coordnate of pixel\n y --> y coordinate of pixel\n \n width --> width of image\n height --> height of image\n \n r_max, r_min --> maximum and minimum numbers on thereal axis\n c_max, c_min --> maximum and minimum numbers on the complex axis\n '''\n \n R = None # YOUR CODE HERE\n C = None # YOUR CODE HERE\n \n return complex(R, C) # complex is a built in function for complex numbers\n \n \n```\n\n##### Color Function\n\nNow we need to be able to convert the number of iterations to an RGB coordinate. RGB colors can take values between 0 and 255, so we need to find a way to scale our number of iterations to become some pretty colors so we can observe the changes. Rather than boring you with this, I'll just provide the function \n\n\n```python\ndef color(number_of_iterations):\n return 255 - int(m * 255/max_iter)\n\n```\n\n## Putting it All Together\n\nIf that worked out well for you, you should be able to fill in the following to create your image functions!\n\n\n\n```python\n# Boundaries for the mandelbrot function \nbounds = [-2, 1, -1, 1]\n\ndef CreateImage(function, width, height, bounds): \n r_max, r_min, c_max, c_min = bounds\n\n if width > 1000:\n print(f'width of {width} is too large. Your computer only has so many pixels.')\n print(\"try zooming in with a smaller boundary to observe more detail\")\n return\n \n if height > 1000:\n print(f'height of {height} is too large. Your computer only has so many pixels.')\n print(\"try zooming in with a smaller boundary to observe more detail\")\n return\n \n X = np.zeros(width, height)\n \n for x in range(0, width):\n for y in range(0, height):\n c = scale_function_coordinate(x, y, width, height, r_max, r_min, c_max, c_min)\n \n # Note here for changes later for root finding \n m = function(c)\n color = color(m)\n X[width, height] = color\n \n return X\n\n# When you're ready uncomment this line to see if it worked\n\n# plt.imshow(X)\n```\n\nIf all that worked out, running the above cell should produce what you see below!\n\n\n```python\nimport sys\nsys.path.append('scripts/')\nimport fractalfuncs as FF\nimport matplotlib.pyplot as plt\n\nbounds = [-2, 1, -1, 1]\nX = FF.CreateImageMap(function = FF.mandelbrot, function_args = {}, bounds = bounds) \nplt.imshow(X, extent=bounds)\nplt.xlabel(\"Real Axis\", size = 12)\nplt.ylabel(\"Imaginary Axis\", size = 12)\nplt.show()\n```\n\n# Using Rootfinding\n\nNow, rather than using the mandelbrot set, let's try and use our root finding techniques to find roots instead! If we're in a stable region,it should be pretty easy! If not, it will get spicy and diverge. We will use that divergence to create our fractals instead. Here the fractal properties not only come from the mathematical formulation of our complex set, but also the convergence properties of our root finder: different root finding techniques will result in different fractals.\n\n## Your Task\n\nCopy and paste your NewtonRaphson root finder from the Root Finding portion of this, and use it in this assignment. **NOTE** instead of returning the root, you will have to modify your NewtonRaphson function to return the number of iterations it took.\n\nTo use root finding, we will do exactly what we did for the mandelbrot set above, however, we will now modify your image generation function to use $c$ as an initial guess at your solution, and see if your NewtonRaphson root finder can find a solution or not. You will need to modify the cell below for use with your own function. Remember that you will also need to pass the derivative and the function you are evaluating (Hint: `**kwargs` can be handy here) \n\n\n\n```python\ndef CreateImageRootFinding(YOUR ARGUMENTS HERE, width, height, bounds): \n r_max, r_min, c_max, c_min = bounds\n\n if width > 1000:\n print(f'width of {width} is too large. Your computer only has so many pixels.')\n print(\"try zooming in with a smaller boundary to observe more detail\")\n return\n \n if height > 1000:\n print(f'height of {height} is too large. Your computer only has so many pixels.')\n print(\"try zooming in with a smaller boundary to observe more detail\")\n return\n \n X = np.zeros(width, height)\n \n for x in range(0, width):\n for y in range(0, height):\n INITIAL_GUESS = scale_function_coordinate(x, y, width, height, r_max, r_min, c_max, c_min)\n \n # Note you may need to wrap this in try/except to prevent accidental zero division/other nastiness\n m = MY_ROOT_FINDER(INITIAL_GUESS)\n color = color(m)\n X[width, height] = color\n \n```\n\n## First Fractal With Root Finding\n\nThe mandelbrot set works well for what it is, but alas, if you try to use thet function in root finding, you will find that your fractal is dreadfully boring. A more interesting function is\n\n$$\nf(z) = z^3 - 1\n$$\n\nWhose derivative is\n\n$$ \nf^\\prime(z) = 3z^2\n$$\n\n### Sanity Check\n\nSee if you can reproduce the image below with your own function\n\n\n```python\ndef function(z):\n return z**3 - 1\n\ndef derivative(z):\n return 3 * z ** 2\n\nbounds = [-1,1,-1,1]\n\nnewton_args = dict(fprime = derivative, f = function, max_iter = 200, prec = 1e-6)\nX = FF.CreateImageMap(FF.NewtonRaphsonFact, newton_args, bounds, height=250, width=250)\n\nplt.imshow(X, extent=bounds)\nplt.xlabel(\"Real Axis\", size = 12)\nplt.ylabel(\"Imaginary Axis\", size = 12)\nplt.show()\n```\n\nUsing the function above, try playing around with the following: \n\n1. Different powers of $z$ \n2. Change the constant (-1) term. Larger/Smaller positive/negative. What if this term is complex?\n\nWhat do you observe about the fractal at higher powers and different values of the constant\n\n# Other Functions To Try\n\nOnce you've got that working, you should try these functions as well and see what fractals you observe!\n\n$$\n\\begin{aligned}\nf(z) &= \\sin(z), x \\in \\left[-\\frac{\\pi}{2} - \\frac{1}{2}, -\\frac{\\pi}{2} + \\frac{1}{2}\\right], y\\in \\left[-0.3, 0.3\\right] \\\\\nf(z) &= \\cosh(z) - 1, x \\in \\left[-0.2, 0.2\\right], y \\in \\left[-\\pi, -\\pi -\\frac{\\pi}{8}\\right]\\\\\nf(z) &= z^3 - 3^z, x\\in [-10, 10], y\\in[-10, 10]\n\\end{aligned}\n$$\n\nNote that if you don't know how to calculate a derivative, that's okay, you can use wolfrapmalpha, or alternatively, you can take them numerically with a function i've provided. It can be used as follows\n\n```python\n# Only if you haven't imported it already\nimport sys\nsys.path.append('scripts/')\nimport fractalfuncs as FF\ndef myfunction(z):\n return z**2 # for example\n\ndef myderivative(z):\n return FF.nderiv(myfunction, z)\n```\nI note that numerical derivatives are always worse than analytic ones, but that's okay for now. If anyone is interested I can talk about how that works later as well. \n\n## Bored of that? \n\nIf you're bored, you can also try other root finding techniques instead of your newton solver! Here are some suggestions\n\n1. [Secant Method](https://en.wikipedia.org/wiki/Secant_method#:~:text=In%20numerical%20analysis%2C%20the%20secant,difference%20approximation%20of%20Newton's%20method.)\n2. [Halley's Method](https://en.wikipedia.org/wiki/Halley%27s_method#:~:text=In%20numerical%20analysis%2C%20Halley's%20method,Householder's%20methods%2C%20after%20Newton's%20method.)\n3. [Schroder's Method](https://mathworld.wolfram.com/SchroedersMethod.html)\n\nNote that these fractals are getting created with based on convergence properties of the above solvers. For example, the cells below outline the same function we used originially, just with their different methods of solving!\n\n\n```python\ndef function(z):\n return z**3 - 1\n\ndef derivative(z):\n return 3 * z ** 2\n\ndef secondder(z):\n return 6 * z\n\nbounds = [-1,1,-1,1]\nsecant_args = dict(function = function, mult = 0.5)\nX = FF.CreateImageMap(FF.secantfact, secant_args, bounds, height=100, width=100)\nplt.imshow(X, extent=bounds)\nplt.xlabel(\"Real Axis\", size = 12)\nplt.ylabel(\"Imaginary Axis\", size = 12)\nplt.show()\n```\n\n\n```python\nbounds = [-1,1,-1,1]\nschroder_args = dict(derivative = derivative, function = function,\n secondder=secondder, prec = 1e-6, max_iter = 50)\nX = FF.CreateImageMap(FF.schroderfact, schroder_args, bounds, height=100, width=100)\nplt.imshow(X, extent=bounds)\nplt.xlabel(\"Real Axis\", size = 12)\nplt.ylabel(\"Imaginary Axis\", size = 12)\nplt.show()\n```\n\n\n```python\nbounds = [-1,1,-1,1]\nhalley_args = dict(derivative = derivative, function = function,\n seconder=secondder, prec = 1e-6, max_iter = 50)\nX = FF.CreateImageMap(FF.halleyfact, halley_args, bounds, height=100, width=100)\nplt.imshow(X, extent=bounds)\nplt.xlabel(\"Real Axis\", size = 12)\nplt.ylabel(\"Imaginary Axis\", size = 12)\nplt.show()\n```\n\nWhere you'll notice each root finding technique has different convergence criteria, so the fractals generated are all slightly different. If you try the other fractals listed, you'll notice tht their fractal patterns will show even more variation \n", "meta": {"hexsha": "2b0687856c8ad2573ee390594c4954583b37ded6", "size": 283759, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/fractals/Fractals.ipynb", "max_stars_repo_name": "lgfunderburk/mathscovery", "max_stars_repo_head_hexsha": "da9fcfd7f660835c663985c94645aec6dfd9f7bb", "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": "notebooks/fractals/Fractals.ipynb", "max_issues_repo_name": "lgfunderburk/mathscovery", "max_issues_repo_head_hexsha": "da9fcfd7f660835c663985c94645aec6dfd9f7bb", "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": "notebooks/fractals/Fractals.ipynb", "max_forks_repo_name": "lgfunderburk/mathscovery", "max_forks_repo_head_hexsha": "da9fcfd7f660835c663985c94645aec6dfd9f7bb", "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": 395.2075208914, "max_line_length": 52324, "alphanum_fraction": 0.9328091796, "converted": true, "num_tokens": 5019, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572778030629224, "lm_q2_score": 0.9196425267730008, "lm_q1q2_score": 0.8803533776324931}} {"text": "### **Claim**\n\nIn the limit, maximizing the likelihood of a parametric distribution whose family contains the true unknown distribution is equivalent to minimizing the forward Kullback-Leibler divergence between them.\n\n---\n\nLet $P(X)$ be an unknown distribution producing observations $x$ with a pdf $p(x)$. We wish to approximate the pdf $p(x)$ of with a parametric family $q_{\\theta}(x)$. We assume that the true distribution is within the family described by $q_{\\theta}(x)$. \n\n\nThe parameters $\\theta_{ML}$ of the approximating distribution $q_{\\theta_{ML}}$ are defined with the maximum likelihood estimator\n\n$$\\theta_{ML} = \\max_{\\theta} \\frac{1}{m}\\sum_{i=1}^m \\log q_{\\theta}(x_i)$$\n\nwhere $x_i \\sim P$ and $i \\in \\{1, \\dots, m\\}$. \n\n\nThe approximating distribution $q_{\\theta_{KL}}$ is defined by minimizing the KL divergence between $p(x)$ and $q_{\\theta}(x)$.\n\n$$\\theta_{KL} = \\min_{\\theta} KL(P||Q_{\\theta}) = \\min_{\\theta} \\int_x p(x) \\log \\frac{p(x)}{q_{\\theta}(x)} dx$$\n\nwhere here we use the forward KL divergence.\n\n\nIf we take the limit as $m \\rightarrow \\infty$ then $\\theta_{ML}$ found by maximizing the likelihood is the same as $\\theta_{KL}$ found by minimizing the forward KL divergence.\n\n\\begin{align}\n\\lim_{m \\rightarrow \\infty} \\theta_{ML} &= \\lim_{m \\rightarrow \\infty} \\max_{\\theta} \\frac{1}{m}\\sum_{i=1}^m \\log q_{\\theta}(x_i) \\\\\n&= \\max_{\\theta} \\int_x p(x) \\log q_{\\theta}(x) dx \\\\\n&= \\min_{\\theta} \\bigg [ -\\int_x p(x) \\log q_{\\theta}(x) dx \\bigg] \\\\\n&= \\min_{\\theta} \\bigg [ \\int_x p(x) \\log p(x) dx -\\int_x p(x) \\log q_{\\theta}(x) dx \\bigg] \\\\\n&= \\min_{\\theta} \\bigg [ \\int_x p(x) \\log \\frac{p(x)}{q_{\\theta}(x)} dx \\bigg] \\\\\n&= \\min_{\\theta} KL(P||Q_{\\theta}) \\\\\n&= \\theta_{KL}\n\\end{align}\n\n\n```python\n\n```\n", "meta": {"hexsha": "94a60cfebad933a71a107e7b11412e60fd218dad", "size": 2931, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Maximizing Liklihood and Minimizing KL Divergence.ipynb", "max_stars_repo_name": "mathnathan/notebooks", "max_stars_repo_head_hexsha": "63ae2f17fd8e1cd8d80fef8ee3b0d3d11d45cd28", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-12-04T11:04:45.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-04T11:04:45.000Z", "max_issues_repo_path": "Maximizing Liklihood and Minimizing KL Divergence.ipynb", "max_issues_repo_name": "mathnathan/notebooks", "max_issues_repo_head_hexsha": "63ae2f17fd8e1cd8d80fef8ee3b0d3d11d45cd28", "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": "Maximizing Liklihood and Minimizing KL Divergence.ipynb", "max_forks_repo_name": "mathnathan/notebooks", "max_forks_repo_head_hexsha": "63ae2f17fd8e1cd8d80fef8ee3b0d3d11d45cd28", "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.6896551724, "max_line_length": 266, "alphanum_fraction": 0.5428181508, "converted": true, "num_tokens": 584, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9702399069145609, "lm_q2_score": 0.9073122232403329, "lm_q1q2_score": 0.8803105270191438}} {"text": "# How\n\n## Calculate the derivative of an expression.\n\nWe can calculate the derivative of an expression using `sympy.diff` which takes,\nan expression, a variable and a degree.\n\n````{tip}\n```\nsympy.diff(expression, variable, degree=1)\n```\n````\n\nThe default value of `degree` is 1.\n\nFor example to compute $\\frac{d (4 x ^ 3 + 2 x + 1}{dx}$:\n\n\n```python\nimport sympy as sym\n\nx = sym.Symbol(\"x\")\nexpression = 4 * x ** 3 + 2 * x + 1\nsym.diff(expression, x)\n```\n\n\n\n\n$\\displaystyle 12 x^{2} + 2$\n\n\n\nTo compute the second derivative: $\\frac{d ^ 2 (4 x ^ 3 + 2 x + 1}{dx ^ 2}$\n\n\n```python\nsym.diff(expression, x, 2)\n```\n\n\n\n\n$\\displaystyle 24 x$\n\n\n\n## Calculate the indefinite integral of an expression.\n\nWe can calculate the indefinite integral of an expression using\n`sympy.integrate`. Which takes an expression and a variable.\n\n````{tip}\n```\nsympy.integrate(expression, variable)\n```\n````\n\nFor example to compute $\\int 4x^3 + 2x + 1 dx$:\n\n\n```python\nsym.integrate(expression, x)\n```\n\n\n\n\n$\\displaystyle x^{4} + x^{2} + x$\n\n\n\n## Calculate the definite integral of an expression.\n\nWe can calculate the definite integral of an expression using\n`sympy.integrate`. The first argument is an expression but instead of passing a\nvariable as the second argument we pass a tuple with the variable and the upper\nand lower bounds of integration.\n\n````{tip}\n```\nsympy.integrate(expression, (variable, lower_bound, upper_bound))\n```\n````\n\nFor example to compute $\\int_0^4 4x^3 + 2x + 1 dx$:\n\n\n```python\nsym.integrate(expression, (x, 0, 4))\n```\n\n\n\n\n$\\displaystyle 276$\n\n\n\n## Use $\\infty$\n\nIn `sympy` we can access $\\infty$ using `sym.oo`:\n\n````{tip}\n```\nsympy.oo\n```\n````\n\nFor example:\n\n\n```python\nsym.oo\n```\n\n\n\n\n$\\displaystyle \\infty$\n\n\n\n## Calculate limits\n\nWe can calculate limits using `sympy.limit`. The first argument is the\nexpression, then the variable and finally the expression the variable tends to.\n\n````{tip}\n```\nsympy.limit(expression, variable, value)\n```\n````\n\nFor example to compute $\\lim_{h \\to 0} \\frac{4 x ^ 3 + 2 x + 1 - 4(x - h)^3 - 2(x - h) - 1}{h}$:\n\n\n```python\nh = sym.Symbol(\"h\")\nexpression = (4 * x ** 3 + 2 * x + 1 - 4 * (x - h) ** 3 - 2 * (x - h) - 1) / h\nsym.limit(expression, h, 0)\n```\n\n\n\n\n$\\displaystyle 12 x^{2} + 2$\n\n\n", "meta": {"hexsha": "c99965c9bf93605def7e2898fd3c9765524a39f1", "size": 5685, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "book/tools-for-mathematics/03-calculus/how/.main.md.bcp.ipynb", "max_stars_repo_name": "11michalis11/pfm", "max_stars_repo_head_hexsha": "c91b1eda70d7cde3fbe065db4667f84853947850", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2020-09-24T21:02:41.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-14T08:37:21.000Z", "max_issues_repo_path": "book/tools-for-mathematics/03-calculus/how/.main.md.bcp.ipynb", "max_issues_repo_name": "11michalis11/pfm", "max_issues_repo_head_hexsha": "c91b1eda70d7cde3fbe065db4667f84853947850", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 87, "max_issues_repo_issues_event_min_datetime": "2020-09-21T15:54:23.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-19T23:26:15.000Z", "max_forks_repo_path": "book/tools-for-mathematics/03-calculus/how/.main.md.bcp.ipynb", "max_forks_repo_name": "11michalis11/pfm", "max_forks_repo_head_hexsha": "c91b1eda70d7cde3fbe065db4667f84853947850", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-10-02T09:21:27.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-08T14:46:27.000Z", "avg_line_length": 20.6727272727, "max_line_length": 105, "alphanum_fraction": 0.4673702726, "converted": true, "num_tokens": 705, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9702399094961359, "lm_q2_score": 0.9073122144683576, "lm_q1q2_score": 0.880310520850518}} {"text": "# Integer Programming\n\n* All decision variables are integers\n\n\\begin{align}\n\\text{maximize}\\ & \\mathbf{c}^T\\mathbf{x} \\\\\n\\text{subject to } & \\\\\n& A\\mathbf{x} &&\\leq \\mathbf{b} \\\\\n& \\mathbf{x} &&\\geq 0 \\\\\n& \\mathbf{x} \\in \\mathbb{Z}^n\n\\end{align}\n\n* Binary integer programming: Variables are restricted to be either 0 or 1\n\n# Binary Knapsack Problem\n* Combinatorial optimization problem\n* Problem of packing the most valuable or useful items without overloading the luggage. \n * A set of items ($N$ items), each with a weight($w$) and a value($v$)\n * Fixed capacity \n * Maximize the total value possible\n\n\n\n## Problem Formulation\n\\begin{align}\n\\text{maximize}\\ & \\sum_{i=0}^{N-1}v_{i}x_{i} \\\\\n\\text{subject to } & \\\\\n& \\sum_{i=0}^{N-1}w_{i}x_{i} & \\leq C \\\\\n& x_i \\in \\{0,1\\} & \\forall i=0,\\dots,N-1\n\\end{align}\n\n## Coding in Python\n\n## Creating the data (weights and values)\n\n\n```python\nw = [4,2,5,4,5,1,3,5]\nv = [10,5,18,12,15,1,2,8]\nC = 15\nN = len(w)\n```\n\n## Step 2: Importing gurobipy package\n\n\n```python\nfrom gurobipy import *\n```\n\n## Step 3: Create an optimization model\n\n\n```python\nknapsack_model = Model('knapsack')\n```\n\n## Step 4: Add multiple binary decision variables\n\nAdds multiple decision variables and stores them in the model.\n```python\naddVars(*indices, \n lb=0.0, \n ub=float('inf'), \n obj=0.0, \n vtype=GRB.CONTINUOUS, \n name=\"\" \n```\n\n\n```python\nx = knapsack_model.addVars(N, vtype = GRB.BINARY, name=\"x\")\n```\n\n## Step 5: Add the constraints\n\n$$\\sum_{i=1}^{N} w_{i}x_{i} \\leq C$$\n\n\n```python\n# \\sum_{i=1}^{N} w_{i}*x_{i} <= C\nknapsack_model.addConstr(sum(w[i]*x[i] for i in range(N)) <= C)\n```\n\n## Step 6: Define the objective function\n\n$$\\sum_{i=1}^{N} v_{i}x_{i}$$\n\n\n```python\n# \\sum_{i=1}^{N} v_{i}*x_{i}\nobj_fn = sum(v[i]*x[i] for i in range(N))\nknapsack_model.setObjective(obj_fn, GRB.MAXIMIZE)\n```\n\n## Step 7: Solve the model and output the solution\n\n\n```python\nknapsack_model.optimize()\nprint('Optimization is done. Objective Function Value: %.2f' % knapsack_model.objVal)\n# Get values of the decision variables\n\nfor v in knapsack_model.getVars():\n print('%s: %g' % (v.varName, v.x))\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "a0dc98e1b9804789fa22c187530f4111e8f53ec5", "size": 4749, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "mathematicalProgramming/Video04/Video04.ipynb", "max_stars_repo_name": "codingperspective/videoMaterials", "max_stars_repo_head_hexsha": "8c9665466d8912c6f0c701c25ad9eb4802fb73a3", "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": "mathematicalProgramming/Video04/Video04.ipynb", "max_issues_repo_name": "codingperspective/videoMaterials", "max_issues_repo_head_hexsha": "8c9665466d8912c6f0c701c25ad9eb4802fb73a3", "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": "mathematicalProgramming/Video04/Video04.ipynb", "max_forks_repo_name": "codingperspective/videoMaterials", "max_forks_repo_head_hexsha": "8c9665466d8912c6f0c701c25ad9eb4802fb73a3", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2021-11-21T05:02:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-17T04:44:57.000Z", "avg_line_length": 22.8317307692, "max_line_length": 97, "alphanum_fraction": 0.4946304485, "converted": true, "num_tokens": 760, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9715639636617014, "lm_q2_score": 0.9059898222871763, "lm_q1q2_score": 0.8802270627784894}} {"text": "# Modeling and Simulation in Python\n\nChapter 9\n\nCopyright 2017 Allen Downey\n\nLicense: [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0)\n\n\n\n```python\n# Configure Jupyter to display the assigned value after an assignment\n%config InteractiveShell.ast_node_interactivity='last_expr_or_assign'\n\n# import everything from SymPy.\nfrom sympy import *\n\n# Set up Jupyter notebook to display math.\ninit_printing() \n```\n\nThe following displays SymPy expressions and provides the option of showing results in LaTeX format.\n\n\n```python\nfrom sympy.printing import latex\n\ndef show(expr, show_latex=False):\n \"\"\"Display a SymPy expression.\n \n expr: SymPy expression\n show_latex: boolean\n \"\"\"\n if show_latex:\n print(latex(expr))\n return expr\n```\n\n### Analysis with SymPy\n\nCreate a symbol for time.\n\n\n```python\nt = symbols('t')\n```\n\nIf you combine symbols and numbers, you get symbolic expressions.\n\n\n```python\nexpr = t + 1\n```\n\nThe result is an `Add` object, which just represents the sum without trying to compute it.\n\n\n```python\ntype(expr)\n```\n\n\n\n\n sympy.core.add.Add\n\n\n\n`subs` can be used to replace a symbol with a number, which allows the addition to proceed.\n\n\n```python\nexpr.subs(t, 2)\n```\n\n`f` is a special class of symbol that represents a function.\n\n\n```python\nf = Function('f')\n```\n\n\n\n\n f\n\n\n\nThe type of `f` is `UndefinedFunction`\n\n\n```python\ntype(f)\n```\n\n\n\n\n sympy.core.function.UndefinedFunction\n\n\n\nSymPy understands that `f(t)` means `f` evaluated at `t`, but it doesn't try to evaluate it yet.\n\n\n```python\nf(t)\n```\n\n`diff` returns a `Derivative` object that represents the time derivative of `f`\n\n\n```python\ndfdt = diff(f(t), t)\n```\n\n\n```python\ntype(dfdt)\n```\n\n\n\n\n sympy.core.function.Derivative\n\n\n\nWe need a symbol for `alpha`\n\n\n```python\nalpha = symbols('alpha')\n```\n\nNow we can write the differential equation for proportional growth.\n\n\n```python\neq1 = Eq(dfdt, alpha*f(t))\n```\n\nAnd use `dsolve` to solve it. The result is the general solution.\n\n\n```python\nsolution_eq = dsolve(eq1)\n```\n\nWe can tell it's a general solution because it contains an unspecified constant, `C1`.\n\nIn this example, finding the particular solution is easy: we just replace `C1` with `p_0`\n\n\n```python\nC1, p_0 = symbols('C1 p_0')\n```\n\n\n```python\nparticular = solution_eq.subs(C1, p_0)\n```\n\nIn the next example, we have to work a little harder to find the particular solution.\n\n### Solving the quadratic growth equation \n\nWe'll use the (r, K) parameterization, so we'll need two more symbols:\n\n\n```python\nr, K = symbols('r K')\n```\n\nNow we can write the differential equation.\n\n\n```python\neq2 = Eq(diff(f(t), t), r * f(t) * (1 - f(t)/K))\n```\n\n\n```python\ndiff(f(t),t)\n```\n\nAnd solve it.\n\n\n```python\nsolution_eq = dsolve(eq2)\n```\n\nThe result, `solution_eq`, contains `rhs`, which is the right-hand side of the solution.\n\n\n```python\ngeneral = solution_eq.rhs\n```\n\nWe can evaluate the right-hand side at $t=0$\n\n\n```python\nat_0 = general.subs(t, 0)\n```\n\nNow we want to find the value of `C1` that makes `f(0) = p_0`.\n\nSo we'll create the equation `at_0 = p_0` and solve for `C1`. Because this is just an algebraic identity, not a differential equation, we use `solve`, not `dsolve`.\n\nThe result from `solve` is a list of solutions. In this case, [we have reason to expect only one solution](https://en.wikipedia.org/wiki/Picard%E2%80%93Lindel%C3%B6f_theorem), but we still get a list, so we have to use the bracket operator, `[0]`, to select the first one.\n\n\n```python\nsolutions = solve(Eq(at_0, p_0), C1)\ntype(solutions), len(solutions)\n```\n\n\n\n\n (list, 1)\n\n\n\n\n```python\nvalue_of_C1 = solutions[0]\n```\n\nNow in the general solution, we want to replace `C1` with the value of `C1` we just figured out.\n\n\n```python\nparticular = general.subs(C1, value_of_C1)\n```\n\nThe result is complicated, but SymPy provides a method that tries to simplify it.\n\n\n```python\nparticular = simplify(particular)\n```\n\nOften simplicity is in the eye of the beholder, but that's about as simple as this expression gets.\n\nJust to double-check, we can evaluate it at `t=0` and confirm that we get `p_0`\n\n\n```python\nparticular.subs(t, 0)\n```\n\nThis solution is called the [logistic function](https://en.wikipedia.org/wiki/Population_growth#Logistic_equation).\n\nIn some places you'll see it written in a different form:\n\n$f(t) = \\frac{K}{1 + A e^{-rt}}$\n\nwhere $A = (K - p_0) / p_0$.\n\nWe can use SymPy to confirm that these two forms are equivalent. First we represent the alternative version of the logistic function:\n\n\n```python\nA = (K - p_0) / p_0\n```\n\n\n```python\nlogistic = K / (1 + A * exp(-r*t))\n```\n\nTo see whether two expressions are equivalent, we can check whether their difference simplifies to 0.\n\n\n```python\nsimplify(particular - logistic)\n```\n\nThis test only works one way: if SymPy says the difference reduces to 0, the expressions are definitely equivalent (and not just numerically close).\n\nBut if SymPy can't find a way to simplify the result to 0, that doesn't necessarily mean there isn't one. Testing whether two expressions are equivalent is a surprisingly hard problem; in fact, there is no algorithm that can solve it in general.\n\n### Exercises\n\n**Exercise:** Solve the quadratic growth equation using the alternative parameterization\n\n$\\frac{df(t)}{dt} = \\alpha f(t) + \\beta f^2(t) $\n\n\n```python\n# Solution goes here\nbeta= symbols('Beta')\n```\n\n\n```python\n# Solution goes here\neq3 = Eq(diff(f(t), t), alpha * f(t) + beta *f(t)**2)\n```\n\n\n```python\n# Solution goes here\nsolution_2 = dsolve(eq3)\n```\n\n**Exercise:** Use [WolframAlpha](https://www.wolframalpha.com/) to solve the quadratic growth model, using either or both forms of parameterization:\n\n df(t) / dt = alpha f(t) + beta f(t)^2\n\nor\n\n df(t) / dt = r f(t) (1 - f(t)/K)\n\nFind the general solution and also the particular solution where `f(0) = p_0`.\n\nResults from the website\n\nalternate1: f'(t) = -(r f(t) (f(t) - K))/K \nalternate2: f'(t) = r (f(t) - f(t)^2/K)\n\nGeneral solution: f(t) = (ξ e^(c_1 ξ + r t))/(e^(c_1 ξ + r t) - 1)\n", "meta": {"hexsha": "47ff42c1c5e8b903e6fe6fb9e6593f722123b0a3", "size": 55260, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/chap09.ipynb", "max_stars_repo_name": "KevinJpotter/ModSimPy", "max_stars_repo_head_hexsha": "af6cb9aad9df5dc490d22116f8fb2146727d88d1", "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/chap09.ipynb", "max_issues_repo_name": "KevinJpotter/ModSimPy", "max_issues_repo_head_hexsha": "af6cb9aad9df5dc490d22116f8fb2146727d88d1", "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/chap09.ipynb", "max_forks_repo_name": "KevinJpotter/ModSimPy", "max_forks_repo_head_hexsha": "af6cb9aad9df5dc490d22116f8fb2146727d88d1", "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": 51.4525139665, "max_line_length": 2664, "alphanum_fraction": 0.7548678972, "converted": true, "num_tokens": 1677, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9728307664950512, "lm_q2_score": 0.9046505344582187, "lm_q1q2_score": 0.8800718728471466}} {"text": "(nm_linear_algebra_intro)=\n# Linear algebra introduction\n\n## Linear (matrix) systems\n\nWe can re-write a system of simultaneous (linear) equations in a matrix form. For example, let's consider:\n\n\\\\[\\begin{eqnarray*}\n 2x + 3y &=& 7 \\\\\\\\\\\\\n x - 4y &=& 3\n\\end{eqnarray*}\\\\]\n\nIt can be rewritten in a matrix form:\n\n\\\\[\n\\left(\n \\begin{array}{rr}\n 2 & 3 \\\\\\\\\\\\\n 1 & -4 \\\\\\\\\\\\\n \\end{array}\n\\right)\\left(\n \\begin{array}{c}\n x \\\\\\\\\\\\\n y \\\\\\\\\\\\\n \\end{array}\n\\right) = \\left(\n \\begin{array}{c}\n 7 \\\\\\\\\\\\\n 3 \\\\\\\\\\\\\n \\end{array}\n\\right)\n\\\\]\n\nWe understand that this system always has the form of \n\n\\\\[\n\\left(\n \\begin{array}{rr}\n a & b \\\\\\\\\\\\\n c & d \\\\\\\\\\\\\n \\end{array}\n\\right)\\left(\n \\begin{array}{c}\n x \\\\\\\\\\\\\n y \\\\\\\\\\\\\n \\end{array}\n\\right) = \\left(\n \\begin{array}{c}\n e \\\\\\\\\\\\\n f \\\\\\\\\\\\\n \\end{array}\n\\right),\n\\\\]\n\nwhere \\\\(a,b,c,d,e,f\\\\) are arbitrary constants.\n\nLet's call the matrix which stores the coefficients of our system of linear equations to be \\\\(A\\\\)\n\n\\\\[\nA=\n\\left(\n \\begin{array}{rr}\n a & b \\\\\\\\\\\\\n c & d \\\\\\\\\\\\\n \\end{array}\n\\right)\n\\\\]\n\nand the matrix that contains our variables to be \\\\(\\mathbf{x}\\\\)\n\n\\\\[\n\\mathbf{x}=\n\\left(\n \\begin{array}{c}\n x \\\\\\\\\\\\\n y \\\\\\\\\\\\\n \\end{array}\n\\right).\n\\\\]\n\nThe matrix that contains the results of our system of linear equation will be called \\\\(\\mathbf{b}\\\\)\n\n\\\\[\n\\mathbf{b}=\n\\left(\n \\begin{array}{c}\n e \\\\\\\\\\\\\n f \\\\\\\\\\\\\n \\end{array}\n\\right).\n\\\\]\n\nThis system of equations can be represented as the matrix equation\n\\\\[A\\pmb{x}=\\pmb{b}.\\\\]\n\nMore generally, consider an arbitrary system of \\\\(n\\\\) linear equations for \\\\(n\\\\) unknowns\n\n\\\\[\n\\begin{eqnarray*}\n A_{11}x_1 + A_{12}x_2 + \\dots + A_{1n}x_n &=& b_1 \\\\\\\\\\\\ \n A_{21}x_1 + A_{22}x_2 + \\dots + A_{2n}x_n &=& b_2 \\\\\\\\\\\\ \n \\vdots &=& \\vdots \\\\\\\\\\\\ \n A_{n1}x_1 + A_{n2}x_2 + \\dots + A_{nn}x_n &=& b_n\n\\end{eqnarray*}\n\\\\]\n\nwhere \\\\(A_{ij}\\\\) are the constant coefficients of the linear system, \\\\(x_j\\\\) are the unknown variables, and \\\\(b_i\\\\)\nare the terms on the right hand side (RHS). Here the index \\\\(i\\\\) is referring to the equation number\n(the row in the matrix below), with the index \\\\(j\\\\) referring to the component of the unknown\nvector \\\\(\\pmb{x}\\\\) (the column of the matrix).\n\nThis system of equations can be represented as the matrix equation \\\\(A\\pmb{x}=\\pmb{b}\\\\):\n\n\\\\[\n\\left(\n \\begin{array}{cccc}\n A_{11} & A_{12} & \\dots & A_{1n} \\\\\\\\\\\\\n A_{21} & A_{22} & \\dots & A_{2n} \\\\\\\\\\\\\n \\vdots & \\vdots & \\ddots & \\vdots \\\\\\\\\\\\\n A_{n1} & A_{n2} & \\dots & A_{nn} \\\\\\\\\\\\\n \\end{array}\n\\right)\\left(\n \\begin{array}{c}\n x_1 \\\\\\\\\\\\\n x_2 \\\\\\\\\\\\\n \\vdots \\\\\\\\\\\\\n x_n \\\\\\\\\\\\\n \\end{array}\n \\right) = \\left(\n \\begin{array}{c}\n b_1 \\\\\\\\\\\\\n b_2 \\\\\\\\\\\\\n \\vdots \\\\\\\\\\\\\n b_n \\\\\\\\\\\\\n \\end{array}\n \\right)\n\\\\]\n\n\nWe can easily solve the above \\\\(2 \\times 2\\\\) example of two equations and two unknowns using substitution (e.g. multiply the second equation by 2 and subtract the first equation from the resulting equation to eliminate \\\\(x\\\\) and hence allowing us to find \\\\(y\\\\), then we could compute \\\\(x\\\\) from the first equation). We find:\n\n\\\\[ x=\\frac{37}{11}, \\quad y=\\frac{1}{11}.\\\\]\n\n```{margin} Note\nCases where the matrix is non-square, i.e. of shape \\\\(m \\times n\\\\) where \\\\(m\\ne n\\\\) correspond to the over- or under-determined systems where you have more or less equations than unknowns. \n```\n\nExample systems of \\\\(3\\times 3\\\\) are a little more complicated but doable. In this notebook, we consider the case of \\\\(n\\times n\\\\), where \\\\(n\\\\) could be billions (e.g. in AI or machine learning).\n\n## Matrices in Python\n\nWe can use `numpy.arrays` to store matrices. The convention for one-dimensional vectors is to call them column vectors and have shape \\\\(n \\times 1\\\\). We can extend to higher dimensions through the introduction of matrices as two-dimensional arrays (more generally vectors and matrices are just two examples of {ref}`tensors `). \n\nWe use subscript indices to identify each component of the array or matrix, i.e. we can identify each component of the vector \\\\(\\pmb{v}\\\\) by \\\\(v_i\\\\), and each component of the matrix \\\\(A\\\\) by \\\\(A_{ij}\\\\). \n\nThe dimension or shape of a vector/matrix is the number of rows and columns it posesses, i.e. \\\\(n \\times 1\\\\) and \\\\(m \\times n\\\\) for the examples above. Here is an example of how we can extend our use of the `numpy.array` to two dimensions in order to define a matrix \\\\(A\\\\).\n\n\n```python\nimport numpy as np\n\nA = np.array([[10., 2., 1.],\n [6., 5., 4.],\n [1., 4., 7.]])\n\nprint(A)\n```\n\n [[10. 2. 1.]\n [ 6. 5. 4.]\n [ 1. 4. 7.]]\n\n\nCheck total size of the array storing matrix \\\\(A\\\\). It will be \\\\(3\\times3=9\\\\):\n\n\n```python\nprint(np.size(A))\n```\n\n 9\n\n\nCheck the number of dimensions of matrix \\\\(A\\\\):\n\n\n```python\nprint(np.ndim(A))\n```\n\n 2\n\n\nCheck the shape of the matrix \\\\(A\\\\):\n\n\n```python\nprint(np.shape(A))\n```\n\n (3, 3)\n\n\nTranspose matrix \\\\(A\\\\):\n\n\n```python\nprint(A.T)\n```\n\n [[10. 6. 1.]\n [ 2. 5. 4.]\n [ 1. 4. 7.]]\n\n\nGet the inverse of matrix \\\\(A\\\\):\n\n\n```python\nimport scipy.linalg as sl\n\nprint(sl.inv(A))\n```\n\n [[ 0.14285714 -0.07518797 0.02255639]\n [-0.28571429 0.51879699 -0.2556391 ]\n [ 0.14285714 -0.28571429 0.28571429]]\n\n\nGet the determinant of matrix \\\\(A\\\\):\n\n\n```python\nprint(sl.det(A))\n```\n\n 133.00000000000003\n\n\n````{margin}\nNormal `*` operator does operations element-wise, which we do not want!!!\n```python\n\nprint(A*sl.inv(A))\n```\n[[ 1.42857143 -0.15037594 0.02255639]\n [-1.71428571 2.59398496 -1.02255639]\n [ 0.14285714 -1.14285714 2. ]]\n\n````\n\nMultiply \\\\(A\\\\) with its inverse using the `@` matrix multiplication operator. Note that due to roundoff errors the off diagonal values are not exactly zero:\n\n\n```python\nprint(A @ sl.inv(A))\n```\n\n [[ 1.00000000e+00 -1.66533454e-16 0.00000000e+00]\n [ 1.11022302e-16 1.00000000e+00 2.22044605e-16]\n [-2.77555756e-17 -1.66533454e-16 1.00000000e+00]]\n\n\nAnother way of multiplying matrices is to use `np.dot` function:\n\n\n```python\nprint(np.dot(A, sl.inv(A)))\nprint(\"\\n\")\nprint(A.dot(sl.inv(A)))\n```\n\n [[ 1.00000000e+00 -1.66533454e-16 0.00000000e+00]\n [ 1.11022302e-16 1.00000000e+00 2.22044605e-16]\n [-2.77555756e-17 -1.66533454e-16 1.00000000e+00]]\n \n \n [[ 1.00000000e+00 -1.66533454e-16 0.00000000e+00]\n [ 1.11022302e-16 1.00000000e+00 2.22044605e-16]\n [-2.77555756e-17 -1.66533454e-16 1.00000000e+00]]\n\n\nInitialise vector and matrix of zeros:\n\n\n```python\nprint(np.zeros(3))\nprint(\"\\n\")\nprint(np.zeros((3,3)))\n```\n\n [0. 0. 0.]\n \n \n [[0. 0. 0.]\n [0. 0. 0.]\n [0. 0. 0.]]\n\n\nInitialise identity matrix:\n\n\n```python\nprint(np.eye(3))\n```\n\n [[1. 0. 0.]\n [0. 1. 0.]\n [0. 0. 1.]]\n\n\n### Matrix objects\n\nNote that NumPy has a matrix object. We can cast the above two-dimensional arrays into matrix objects and then the star operator does yield the expected matrix product:\n\n\n```python\nA = np.array([[10., 2., 1.],\n [6., 5., 4.],\n [1., 4., 7.]])\n\nprint(type(A))\nprint(type(np.mat(A)))\n```\n\n \n \n\n\n\n```python\nprint(np.mat(A)*np.mat(sl.inv(A)))\n```\n\n [[ 1.00000000e+00 -1.66533454e-16 0.00000000e+00]\n [ 1.11022302e-16 1.00000000e+00 2.22044605e-16]\n [-2.77555756e-17 -1.66533454e-16 1.00000000e+00]]\n\n\n### Slicing\nWe can use slicing to extract components of matrices:\n\n\n```python\n# Single entry, first row, second column\nprint(A[0,1])\n\n# First row\nprint(A[0,:])\n\n# last row\nprint(A[-1,:])\n\n# Second column\nprint(A[:,1])\n\n# Extract a 2x2 sub-matrix\nprint(A[1:3,1:3])\n```\n\n 2.0\n [10. 2. 1.]\n [1. 4. 7.]\n [2. 5. 4.]\n [[5. 4.]\n [4. 7.]]\n\n\n## Exercises\n\n### Solving a linear system\n\nLet's quickly consider the \\\\(2 \\times 2\\\\) case from the beginning of the notebook that we claimed the solution for to be\n\n\\\\[x=\\frac{37}{11} \\quad\\text{and}\\quad y=\\frac{1}{11}.\\\\]\n\nTo solve the matrix equation \n\n\\\\[ A\\pmb{x}=\\pmb{b}\\\\]\n\nwe can simply multiply both sides by the inverse of the matrix \\\\(A\\\\) (if \\\\(A\\\\) is [invertible](https://en.wikipedia.org/wiki/Invertible_matrix)):\n\n\\\\[\n\\begin{align}\nA\\pmb{x} & = \\pmb{b}\\\\\\\\\\\\\n\\implies A^{-1}A\\pmb{x} & = A^{-1}\\pmb{b}\\\\\\\\\\\\\n\\implies I\\pmb{x} & = A^{-1}\\pmb{b}\\\\\\\\\\\\\n\\implies \\pmb{x} & = A^{-1}\\pmb{b}\n\\end{align}\n\\\\]\n\nso we can find the solution \\\\(\\pmb{x}\\\\) by multiplying the inverse of \\\\(A\\\\) with the RHS vector \\\\(\\pmb{b}\\\\).\n\n\n```python\nA = np.array([[2., 3.],\n [1., -4.]])\n\n# Check first whether the determinant of A is non-zero\nprint(\"Det A = \", sl.det(A))\n\nb = np.array([7., 3.])\n\n# Compute A inverse and multiply by b\nprint(\"A^-1 @ b =\", sl.inv(A) @ b)\n```\n\n Det A = -11.0\n A^-1 @ b = [3.36363636 0.09090909]\n\n\nWe can solve the system using `scipy.linalg.solve`:\n\n\n```python\nprint(\"A^-1 @ b =\", sl.solve(A,b))\n```\n\n A^-1 @ b = [3.36363636 0.09090909]\n\n\nCheck if the solutions match:\n\n\n```python\nprint(np.allclose(np.array([37./11., 1./11.]), sl.solve(A,b)))\n```\n\n True\n\n\n### Matrix multiplication\n\n\nLet\n\\\\[\nA = \\left(\n \\begin{array}{ccc}\n 1 & 2 & 3 \\\\\\\\\\\\\n 4 & 5 & 6 \\\\\\\\\\\\\n 7 & 8 & 9 \\\\\\\\\\\\\n \\end{array}\n\\right)\n\\mathrm{\\quad\\quad and \\quad\\quad}\nb = \\left(\n \\begin{array}{c}\n 2 \\\\\\\\\\\\\n 4 \\\\\\\\\\\\\n 6 \\\\\\\\\\\\\n \\end{array}\n\\right)\n\\\\]\n\nWe will store \\\\(A\\\\) and \\\\(b\\\\) in NumPy arrays. We will create NumPy array \\\\(I\\\\) containing the identity matrix \\\\(I_3\\\\) and perform \\\\(A = A+I\\\\). Then we will substitute third column of \\\\(A\\\\) with \\\\(b\\\\). We will solve \\\\(Ax=b\\\\).\n\n\n```python\nA = np.array([[1, 2, 3],\n [4, 5, 6],\n [7, 8, 9]])\nb = np.array([2, 4, 6])\nprint(\"A =\", A)\nprint(\"b = \",b)\n\nprint(\"Size of A: \", A.size,\" and shape of A: \",A.shape)\nprint(\"Size of b: \", b.size,\" and shape of b: \",b.shape)\n\nI = np.eye(3)\nprint(\"I = \",I)\nA = A + I\nprint(\"A = \",A)\n\nA[:, 2] = b\nprint(\"A = \",A)\n\nx = sl.solve(A,b)\nprint(\"x = \", x)\n```\n\n A = [[1 2 3]\n [4 5 6]\n [7 8 9]]\n b = [2 4 6]\n Size of A: 9 and shape of A: (3, 3)\n Size of b: 3 and shape of b: (3,)\n I = [[1. 0. 0.]\n [0. 1. 0.]\n [0. 0. 1.]]\n A = [[ 2. 2. 3.]\n [ 4. 6. 6.]\n [ 7. 8. 10.]]\n A = [[2. 2. 2.]\n [4. 6. 4.]\n [7. 8. 6.]]\n x = [3.80647894e-17 7.77156117e-17 1.00000000e+00]\n\n\n## Matrix properties\n\nConsider \\\\(N\\\\) linear equations in \\\\(N\\\\) unknowns, \\\\(A\\pmb{x}=\\pmb{b}\\\\).\n\nthis system has a unique solution provided that the determinant of \\\\(A\\\\), \\\\(\\det(A)\\\\), is non-zero. In this case the matrix is said to be non-singular.\n\nIf \\\\(\\det(A)=0\\\\) (with \\\\(A\\\\) then termed a singular matrix), then the linear system does not have a unique solution, it may have either infinite or no solutions.\n\nFor example, consider\n\n\\\\[\n\\left(\n \\begin{array}{rr}\n 2 & 3 \\\\\\\\\\\\\n 4 & 6 \\\\\\\\\\\\\n \\end{array}\n\\right)\\left(\n \\begin{array}{c}\n x \\\\\\\\\\\\\n y \\\\\\\\\\\\\n \\end{array}\n\\right) = \\left(\n \\begin{array}{c}\n 4 \\\\\n 8 \\\\\n \\end{array}\n\\right).\n\\\\]\n\nThe second equation is simply twice the first, and hence a solution to the first equation is also automatically a solution to the second equation.\n\nWe only have one linearly-independent equation, and our problem is under-constrained - we effectively only have one eqution for two unknowns with infinitely many possibly solutions.\n\nIf we replaced the RHS vector with \\\\((4,7)^T\\\\), then the two equations would be contradictory - in this case we have no solutions.\n\nNote that a set of vectors where one can be written as a linear sum of the others are termed linearly-dependent. When this is not the case the vectors are termed linearly-independent.\n\n```{admonition} The following properties of a square \\\\(n\\times n\\\\) matrix are equivalent:\n\n* \\\\(\\det(A)\\ne 0\\implies\\\\) A is non-singular\n* the columns of \\\\(A\\\\) are linearly independent\n* the rows of \\\\(A\\\\) are linearly independent\n* the columns of \\\\(A\\\\) span \\\\(n\\\\)-dimensional space (we can reach any point in \\\\(\\mathbb{R}^N\\\\) through a linear combination of these vectors)\n* \\\\(A\\\\) is invertible, i.e. there exists a matrix \\\\(A^{-1}\\\\) such that \\\\(A^{-1}A = A A^{-1}=I\\\\)\n* the matrix system \\\\(A\\pmb{x}=\\pmb{b}\\\\) has a unique solution for every vector \\\\(b\\\\)\n\n```\n", "meta": {"hexsha": "81575c1a160085536600014f42c06bfe43f11b69", "size": 22054, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/c_mathematics/numerical_methods/11_linear_algebra_intro.ipynb", "max_stars_repo_name": "primer-computational-mathematics/book", "max_stars_repo_head_hexsha": "305941b4f1fc4f15d472fd11f2c6e90741fb8b64", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-08-02T07:32:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-16T16:40:43.000Z", "max_issues_repo_path": "notebooks/c_mathematics/numerical_methods/11_linear_algebra_intro.ipynb", "max_issues_repo_name": "primer-computational-mathematics/book", "max_issues_repo_head_hexsha": "305941b4f1fc4f15d472fd11f2c6e90741fb8b64", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2020-07-27T10:45:26.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-12T15:09:14.000Z", "max_forks_repo_path": "notebooks/c_mathematics/numerical_methods/11_linear_algebra_intro.ipynb", "max_forks_repo_name": "primer-computational-mathematics/book", "max_forks_repo_head_hexsha": "305941b4f1fc4f15d472fd11f2c6e90741fb8b64", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2020-08-05T13:57:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-02T19:03:57.000Z", "avg_line_length": 26.6352657005, "max_line_length": 359, "alphanum_fraction": 0.4431395665, "converted": true, "num_tokens": 4381, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133515091156, "lm_q2_score": 0.9362850124150441, "lm_q1q2_score": 0.880026783986778}} {"text": "## Definition\n\nGiven the parametric equation of a logarithmic spiral:\n\n$$\nx(t) = ae^{bt} \\cos(t)\n\\\\\ny(t) = ae^{bt} \\sin(t)\n$$\n\nThen the curvature $\\kappa$ of the spiral is given by:\n\n$$\n\\kappa (t) = \\frac{ e^{-bt} } {a\\sqrt{1 + b^2}}\n$$\n\nwhere $t$ is the tangential angle.\n\n## Objective\n\nGiven the general definition of the curvature of a parametric curve in the xy plane:\n\n$$\n\\kappa = \\left \\| \\frac{d\\mathbf{T}}{dt} \\right \\| = \\frac{| \\dot{x}\\ddot{y} - \\dot{y}\\ddot{x} |}{{(\\dot{x}^2 + \\dot{y}^2)} ^ { \\frac{3}{2} }}\n$$\n\nRecover the above curvature equation of a logarithmic spiral using sympy.\n\n\n```python\nfrom sympy import *\ninit_printing()\n\n# Define variables\nx, y, t = symbols('x y t')\na, b = symbols('a b')\n\n# Spiral equation\nx = a * exp(b*t) * cos(t)\ny = a * exp(b*t) * sin(t)\n\nx, y\n```\n\n\n```python\n# Get derivatives\nxd = diff(x, t)\nyd = diff(y, t)\nxdd = diff(xd, t)\nydd = diff(yd, t)\n\n# Define the true curvature equation\ntrue_curvature = exp(- b * t) / (a * sqrt(1 + b**2))\ntrue_curvature\n```\n\n\n```python\n# Compute curvature\ncurvature = Abs(xd * ydd - yd * xdd) / (xd**2 + yd**2)**(3/2)\ncurvature\n```\n\n\n```python\ncurvature = curvature.simplify()\ncurvature\n```\n\n\n```python\nargs = {'a': 14, 'b': 5, 't': 0.2}\ntrue_curvature.subs(args).evalf()\n```\n\n\n```python\ncurvature.subs(args).evalf()\n```\n\n\n```python\nexpand(true_curvature - curvature)\n```\n\nThe newly computed `curvature` expression give the same result as the `true_curvature` expression given in the textbooks.\n", "meta": {"hexsha": "25f572697fd831d1364431ed848001019af17beb", "size": 29513, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Analysis/Notebooks/Spiral Dataset/Spiral Curvature Calculus.ipynb", "max_stars_repo_name": "brouhardlab/kappa", "max_stars_repo_head_hexsha": "2e74530e54fc02e08e03e56a4a33ece6c7ce9941", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2017-11-29T15:09:50.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-04T11:08:17.000Z", "max_issues_repo_path": "Analysis/Notebooks/Spiral Dataset/Spiral Curvature Calculus.ipynb", "max_issues_repo_name": "brouhardlab/kappa", "max_issues_repo_head_hexsha": "2e74530e54fc02e08e03e56a4a33ece6c7ce9941", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 18, "max_issues_repo_issues_event_min_datetime": "2017-11-17T19:20:10.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-16T16:33:31.000Z", "max_forks_repo_path": "Analysis/Notebooks/Spiral Dataset/Spiral Curvature Calculus.ipynb", "max_forks_repo_name": "brouhardlab/kappa", "max_forks_repo_head_hexsha": "2e74530e54fc02e08e03e56a4a33ece6c7ce9941", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2017-10-13T02:24:17.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-16T01:14:59.000Z", "avg_line_length": 102.4756944444, "max_line_length": 7168, "alphanum_fraction": 0.7946328736, "converted": true, "num_tokens": 501, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422172230208, "lm_q2_score": 0.9252299565766113, "lm_q1q2_score": 0.8800252723394374}} {"text": "# 2/ Linearity\n\n\n```python\n# setup SymPy\nfrom sympy import *\ninit_printing()\nx, y, z, t = symbols('x y z t')\nalpha, beta = symbols('alpha beta')\n```\n\n## Simplest linear function\n\n\n```python\nb, m = symbols('b m')\n\ndef f(x):\n return m*x\n```\n\n\n```python\nf(1)\n```\n\n\n```python\nf(2)\n```\n\n\n```python\nf(1+2)\n```\n\n\n```python\nf(1) + f(2)\n```\n\n\n```python\nexpand(f(x+y)) == f(x) + f(y)\n```\n\n\n\n\n True\n\n\n\n## What about vector inputs?\n\n\n```python\nm_1, m_2 = symbols('m_1 m_2')\n\ndef T(vec):\n \"\"\"A function that takes a 2D vector and returns a number.\"\"\"\n return m_1*vec[0] + m_2*vec[1]\n```\n\n\n```python\nu_1, u_2 = symbols('u_1 u_2')\nu = Matrix([u_1,u_2])\nv_1, v_2 = symbols('v_1 v_2')\nv = Matrix([v_1,v_2])\n```\n\n\n```python\nT(u)\n```\n\n\n```python\nT(v)\n```\n\n\n```python\nT(u) + T(v)\n```\n\n\n```python\nexpand( T(u+v) )\n```\n\n\n```python\nsimplify( T(alpha*u + beta*v) - alpha*T(u) - beta*T(v) )\n```\n\n# Linear transformations\n\nA linear transformation is function that takes vectors as inputs, and produces vectors as outputs:\n\n$$\n T: \\mathbb{R}^n \\to \\mathbb{R}^m.\n$$\n\nSee [page 136](https://minireference.com/static/excerpts/noBSLA_v2_preview.pdf#page=43) in v2.2 of the book.\n\n\n```python\nm_11, m_12, m_21, m_22 = symbols('m_11 m_12 m_21 m_22')\n\ndef T(vec):\n \"\"\"A linear transformations R^2 --> R^2.\"\"\"\n out_1 = m_11*vec[0] + m_12*vec[1]\n out_2 = m_21*vec[0] + m_22*vec[1]\n return Matrix([out_1, out_2])\n```\n\n\n```python\nT(u)\n```\n\n\n```python\nT(v)\n```\n\n\n```python\nT(u+v)\n```\n\n## Linear transformations as matrix-vector products \n\nSee [page 133](https://minireference.com/static/excerpts/noBSLA_v2_preview.pdf#page=40) in v2.2 of the book.\n\n\n```python\ndef T_impl(vec):\n \"\"\"A linear transformations implemented as matrix-vector product.\"\"\"\n M_T = Matrix([[m_11, m_12], \n [m_21, m_22]])\n return M_T*vec\n```\n\n\n```python\nT_impl(u)\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "cec3569e3d16aeee1d87ffa7a69622405ed075be", "size": 30766, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "chapter02_linearity_intuition.ipynb", "max_stars_repo_name": "minireference/noBSLAnotebooks", "max_stars_repo_head_hexsha": "3d6acb134266a5e304cb2d51c5ac4dc3eb3949b4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 116, "max_stars_repo_stars_event_min_datetime": "2016-04-20T13:56:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T08:55:08.000Z", "max_issues_repo_path": "chapter02_linearity_intuition.ipynb", "max_issues_repo_name": "minireference/noBSLAnotebooks", "max_issues_repo_head_hexsha": "3d6acb134266a5e304cb2d51c5ac4dc3eb3949b4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-07-01T17:00:38.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-01T19:34:09.000Z", "max_forks_repo_path": "chapter02_linearity_intuition.ipynb", "max_forks_repo_name": "minireference/noBSLAnotebooks", "max_forks_repo_head_hexsha": "3d6acb134266a5e304cb2d51c5ac4dc3eb3949b4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 29, "max_forks_repo_forks_event_min_datetime": "2017-02-04T05:22:23.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-28T00:06:50.000Z", "avg_line_length": 60.8023715415, "max_line_length": 4484, "alphanum_fraction": 0.7985763505, "converted": true, "num_tokens": 668, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9697854164256365, "lm_q2_score": 0.9073122119620789, "lm_q1q2_score": 0.8798981513057101}} {"text": "# Mathematical Induction\n\nThe simple case of 'weak' induction.\n\n1. Prove the Base Case k=b\n2. Prove that, assuming it holds for some case $k$, it also holds for $k+1$\n\n\n\n- It holds for $k=b$. (step 1)\n- If it holds for $k=b$ then it should hold for $k=b+1$. (step 2)\n\n- Therefore, it holds for $k=b+1$. (step 1 + step 2)\n\n- If it holds for $b+1$ then it holds for $b+2$. (step 2)\n\n- If it holds for $b+2$ then it holds for $b+3$. (step 2)\n.\n.\n.\n\nAnd so on.\n\n\n### Example:\n\nThe proposition is that:\n\n\\begin{equation}\nP(n) = \\sum_{i=0}^{n-1} b^i = \\frac{1-b^n}{1-b}\n\\end{equation}\n\n#### Base Case: Prove that it Holds for n = 1\n\n\\begin{equation}\nP(1) = \\sum_{i=0}^{1-1} b^i = b^0 = \\frac{1-b^1}{1-b} = 1\n\\end{equation}\n\nThis proves the base case.\n\n#### Step Case: Prove that if it holds for n=k then it also holds for n=k+1\n\nAssume the following to be true:\n\\begin{equation}\nP(n) = \\frac{1-b^n}{1-b}\n\\end{equation}\n\n\\begin{equation}\nP(k+1) = P(k) + b^{k} = \\frac{1-b^k}{1-b} + \\frac{(1-b)b^{k}}{1-b} = \\frac{1-b^k+b^k+b^{k+1}}{1-b} = \\frac{1-b^{k+1}}{1-b}\n\\end{equation}\n\nThis proves the step case.\n\n\n\n", "meta": {"hexsha": "e0a591fc0067b51473f5b570f238e742c45d8164", "size": 2119, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Math - Mathematical Induction.ipynb", "max_stars_repo_name": "jpbm/probabilism", "max_stars_repo_head_hexsha": "a2f5c1595aed616236b2b889195604f365175899", "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": "Math - Mathematical Induction.ipynb", "max_issues_repo_name": "jpbm/probabilism", "max_issues_repo_head_hexsha": "a2f5c1595aed616236b2b889195604f365175899", "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 - Mathematical Induction.ipynb", "max_forks_repo_name": "jpbm/probabilism", "max_forks_repo_head_hexsha": "a2f5c1595aed616236b2b889195604f365175899", "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.6395348837, "max_line_length": 136, "alphanum_fraction": 0.4672015101, "converted": true, "num_tokens": 438, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122756889438, "lm_q2_score": 0.918480237330998, "lm_q1q2_score": 0.8798234943170575}} {"text": "The Relative Frequency of any random variable is the number of occurance in the total number of observation. \nThe Relative Frequency is calculated as:
\n\\begin{equation}\nRelative Frequency = \\frac{Frequency}{Total\\ number\\ of\\ observations}\n\\end{equation}
\nE.g. We have a samples are like { 5,7,11,19,23,5,18,7,18,23 }. If we calculate the relative frequency of each unique values then it will be as:
\n${R.F of (5)} = {\\frac {2}{10}}$
\n${R.F of (7)} = {\\frac {2}{10}}$
\n${R.F of (11)} = {\\frac {1}{10}}$
\n${R.F of (18)} = {\\frac {2}{10}}$
\n${R.F of (19)} = {\\frac {1}{10}}$
\n${R.F of (23)} = {\\frac {2}{10}}$
\n\nWhereas, Probability is actually the limiting case of the Relative Frequency when the sample approaches(limits) towards population. \n\nGoing to demonstrate that probability is actually the limiting case of relative frequency when the sample slowly approaches population.\n\nLets first take an example of binomial random variable where we are taking a sample of observations (responses) arrising due to repititive conduction of a binomial experiment. Which means that we are going to perform some experiment 'N' number of times where each each conduction of experiment (trial) will result in an obervation or response of a trial out of two possible responses. Lets say that our binomial trial is the toss of a coin where each toss is going to give us one of the two responses : Either Heads or Tails. \n\nAs we are in statistical domain, we will evaluate the relative frequencies of heads as well as tails as:\n\n\\begin{equation}\nr = \\frac{h}{N}\n\\end{equation}\n\nWhere, r = Relative Frequency.\n h = Number of Binomial Experiments in which heads was the outcome.\n N = Total number of times binomial experiment has been conducted. \n\n\n```python\n# Importing the Numpy library alias np and matplotlib library alias plt\nimport numpy as np\nimport matplotlib.pyplot as plt\n```\n\nGoing to conduct a binomial experiment (having two results either Head or Tail) for N=10 times and considering that the coin used in coin tossing is an unbiased coin, i.e. p=q=0.5\n\n\n```python\nN = 10\npsuccess = 0.5\nqfailure = 1-psuccess\nExperimentOutcomes = np.random.binomial(N,psuccess)\n```\n\n\n```python\nExperimentOutcomes\n```\n\n\n\n\n 4\n\n\n\nWe tossed an unbiased coin 10 times, we got only 4 heads. So, the relative frequency is given by:\n\n\\begin{equation}\nr = \\frac{h}{N} = \\frac{4}{10} = 0.4\n\\end{equation}\n\nLet's toss an unbiased coin 100 times and see what happens. \n\n\n```python\nN = 100\nExperimentOutcomes = np.random.binomial(N,psuccess)\n```\n\n\n```python\nExperimentOutcomes\n```\n\n\n\n\n 54\n\n\n\nWe tossed a coin 100 times, we got 54 heads. So, the relative frequency is given by:\n\n\\begin{equation}\nr = \\frac{h}{N} = \\frac{54}{100} = 0.54\n\\end{equation}\n\nLet's toss an unbiased coin 10000 times and see what happens.\n\n\n```python\nN = 10000\nExperimentOutcomes = np.random.binomial(N,psuccess)\n```\n\n\n```python\nExperimentOutcomes\n```\n\n\n\n\n 4972\n\n\n\nWe tossed a coin 10000 times, we got 4972 heads. So, the relative frequency is given by:\n\n\\begin{equation}\nr = \\frac{h}{N} = \\frac{4972}{10000} = 0.4972\n\\end{equation}\n\nLet's toss a coin 100000 times and see what happens.\n\n\n```python\nN = 100000\nExperimentOutcomes = np.random.binomial(N,psuccess)\n```\n\n\n```python\nExperimentOutcomes\n```\n\n\n\n\n 49991\n\n\n\nWe tossed a coin 100000 times, we got 49991 heads. So the relative frequency is given by:\n\n\\begin{equation}\nr = \\frac{h}{N} = \\frac{49991}{100000} = 0.49991\n\\end{equation}\n\nThe theoretical answer to the probability of getting heads in a single toss is 0.5 and we can observe that as we are increasing the number of tosses, we are approaching the theoretical value of probability in terms of relative frequency.\n\nThis phenomena can also be shown by plotting relative frequencies of heads with increasing sample sizes which are slowly approaching population. \n\n\n```python\n#we are trying to get the values from the lower limit=10, higher limit=500 \n#in the interval of 10.\nNs = np.arange(10,500,10)\n```\n\n\n```python\nNs\n```\n\n\n\n\n array([ 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130,\n 140, 150, 160, 170, 180, 190, 200, 210, 220, 230, 240, 250, 260,\n 270, 280, 290, 300, 310, 320, 330, 340, 350, 360, 370, 380, 390,\n 400, 410, 420, 430, 440, 450, 460, 470, 480, 490])\n\n\n\nWe have generated different sample sizes at the gap of 10 tosses. \n\n\n```python\nExperimentOutcomes = np.random.binomial(Ns,psuccess)\n```\n\nWe have tossed an unbiased coin at different values of total tosses(N) and recorded the number of heads(h) during several number of total tosses. \n\n\n```python\nRelativeFrequencies = ExperimentOutcomes/Ns\n```\n\nWe have now calculated relative frequencies by dividing the number of heads(h) which we observed during different values of N.\n\n\n```python\nplt.stem(Ns,RelativeFrequencies)\n```\n\nAs we can observe from above plot that as we are tossing a coin more number of times, the relative frequency of heads is approaching towards psuccess = 0.5. \n\nNow, let's change the psuccess to 0.65 and plot the similar graph once again. \n\n\n```python\npsuccess = 0.65\nExperimentOutcomes = np.random.binomial(Ns,psuccess)\n```\n\n\n```python\nRelativeFrequencies = ExperimentOutcomes/Ns\n```\n\n\n```python\nplt.stem(Ns,RelativeFrequencies)\n```\n\nAs we can observe from above plot that as we are tossing a coin more number of times, the relative frequency of heads is approaching towards psuccess = 0.65. \n\nNow, let's change the psuccess to 0.35 and plot the similar graph once again. \n\n\n```python\npsuccess = 0.35\nExperimentOutcomes = np.random.binomial(Ns,psuccess)\n```\n\n\n```python\nRelativeFrequencies = ExperimentOutcomes/Ns\n```\n\n\n```python\nplt.stem(Ns,RelativeFrequencies)\n```\n\nAs we can observe from above plot that as we are tossing a coin more number of times, the relative frequency of heads is approaching towards psuccess = 0.35. \n\n\n```python\n\n```\n", "meta": {"hexsha": "dc72aaae23f93222c2e9a24d0a9c582d48e3c5f5", "size": 34844, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "1. Relative Frequency and Probability and their relation.ipynb", "max_stars_repo_name": "rarpit1994/Probability-and-Statistics", "max_stars_repo_head_hexsha": "1ae8b7428ec9a3072fce3089d7951b9f7bd06c26", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-03-24T10:29:56.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-24T10:29:56.000Z", "max_issues_repo_path": "1. Relative Frequency and Probability and their relation.ipynb", "max_issues_repo_name": "rarpit1994/Probability-and-Statistics", "max_issues_repo_head_hexsha": "1ae8b7428ec9a3072fce3089d7951b9f7bd06c26", "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": "1. Relative Frequency and Probability and their relation.ipynb", "max_forks_repo_name": "rarpit1994/Probability-and-Statistics", "max_forks_repo_head_hexsha": "1ae8b7428ec9a3072fce3089d7951b9f7bd06c26", "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": 63.0090415913, "max_line_length": 7696, "alphanum_fraction": 0.8093789462, "converted": true, "num_tokens": 1675, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966732132748, "lm_q2_score": 0.9294404047899392, "lm_q1q2_score": 0.8798051951241559}} {"text": "```python\n%matplotlib inline\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib import cm\nfrom mpl_toolkits.mplot3d import Axes3D\nplt.rcParams['font.size'] = 13\nplt.rcParams['axes.spines.right'] = False\nplt.rcParams['ytick.right'] = False\nplt.rcParams['axes.spines.top'] = False\nplt.rcParams['xtick.top'] = False\n```\n\n### A linear mapping from input to output space\n\nLinear regression assumes that some recorded output values $y_i$ for $i=1,...,N_\\mathrm{samples}$ depend linearly on some input values $\\mathbf{x}_i$, and that any deviations are due to noise. Given $\\mathbf{x}$-$y$ data, your task is then to rediscover the form of this linear mapping, which in the simplest case corresponds to fitting a line to the data. The question is merely how to select the best line?\n\n\n```python\n# Generate example data\n# Initialize\nsigma = 0.5 # noise std\nnSamples = 21 # number of samples\nx = np.linspace(0, 5, nSamples) # input values\nlineFun = lambda w0, w1, x: w0 + w1*x # linear mapping\n\n# Generate y-data\nw0 = 1 # intercept\nw1 = 0.5 # slope\ny = lineFun(w0, w1, x)\ny += np.random.randn(nSamples)*sigma\n\n# Plot our generated data\nplt.figure(figsize=(7.5, 3))\nplt.plot(x, y, 'ko')\nplt.xlabel('x')\nplt.ylabel('y');\n```\n\n### Least squares approach\n\nOne approach for evaluating how good a line fits is by summing up the squared distances to each $y$-value from the line, and to compare this value for various lines. A lower value would indicate a better fit and a higher a worse fit. Usually, this sum is further divided by the number of samples, so as to get a mean squared error (MSE).\n\n\n```python\n# Calculate the MSE for a test line\nw0Test = 1.0\nw1Test = 0.5\nyHat = lineFun(w0Test, w1Test, x) # Model predictions, the predicted line\nmseFun = lambda y, yHat: np.mean((y-yHat)**2) # MSE function\nmseTest = mseFun(y, yHat) # MSE value for our test line\n\n# Plot the test line (blue), the distace to each y_i (red) and the y-values (black)\nplt.figure(figsize=(7.5, 3))\nfor xi, yi, yHati in zip(x, y, yHat): \n plt.stem([xi], [yi], 'r', bottom=yHati)\nplt.plot(x, yHat, 'b-') \nplt.plot(x, y, 'ko')\nplt.xlabel('x')\nplt.ylabel('y');\nplt.title('MSE: ' + '%1.3f' % mseTest);\n```\n\nFrom the example above we learn that each line (a unique combination of $w_0$ and $w_1$) obtains a slightly different MSE value. Our task is therefore to find the $w_0$ and $w_1$ combination with the lowest value. Naively, we can try to do this by simply testing various combinations and plotting the MSE value as a function of both $w_0$ and $w_1$.\n\n\n```python\n# Get w0 and w1 combinations over a grid\nnGrid = 21\nW0, W1 = np.meshgrid(np.linspace(w0-2, w0+2, nGrid), np.linspace(w1-1, w1+1, nGrid))\n\n# Get the MSE for each combination\nmseVals = np.zeros([nGrid, nGrid])\nfor i in range(nGrid):\n for j in range(nGrid):\n yHat = lineFun(W0[i, j], W1[i, j], x)\n mseVals[i, j] = mseFun(y, yHat)\n\n# Plot the surface\nfig = plt.figure(figsize=(15, 5))\nax = plt.subplot(1, 2, 1, projection='3d')\nax.plot_surface(W0, W1, mseVals, cmap=cm.coolwarm, linewidth=0, antialiased=False)\nax.set_xlabel('$w_0$')\nax.set_ylabel('$w_1$')\nax.set_zlabel('MSE')\nax = plt.subplot(1, 2, 2)\nax.contourf(W0, W1, mseVals, 50, cmap=cm.coolwarm)\nax.set_xlabel('$w_0$')\nax.set_ylabel('$w_1$');\n```\n\nThe take home message so far is thus that each line (unique combination of $w_0$ and $w_1$) corresponds to one point on a MSE surface, and that the best line in a MSE sense is at the bottom of the surface where the MSE minimum is located.\n\n\n```python\n# Test various w0 and w1 values to see how the corresponding line fits at various locations on MSE surface\nw0Test = 0.5\nw1Test = 1.0\n\n# Evaluate the MSE value for our current test line\nyHat = lineFun(w0Test, w1Test, x)\nmseFun = lambda y, yHat: np.mean((y-yHat)**2)\nmseTest = mseFun(y, yHat)\n\n# Plot\nfig = plt.figure(figsize=(15, 5))\nax = plt.subplot(1, 2, 1)\nfor xi, yi, yHati in zip(x, y, yHat): \n ax.stem([xi], [yi], 'r', bottom=yHati)\nax.plot(x, yHat, 'b-') \nax.plot(x, y, 'ko')\nax.set_xlabel('x')\nax.set_ylabel('y');\nax.set_title('MSE: ' + '%1.3f' % mseTest);\nax = plt.subplot(1, 2, 2)\nax.contourf(W0, W1, mseVals, 50, cmap=cm.coolwarm)\nax.set_xlabel('$w_0$')\nax.set_ylabel('$w_1$');\nax.plot(w0Test, w1Test, 'ko', ms=10);\n```\n\n### How to find the minimum in practice\n\nBefore moving on we need a more general description of our optimization problem, and we obtain it by describing the linear mapping using matrix notation. The line equation used above ($\\hat{y}_i = w_0+w_1 x_i$) can then be written as:\n\n\\begin{equation}\n \\hat{y}_i = \\mathbf{x}_i^T \\mathbf{w}, \\quad \\text{where}: \\mathbf{x}_i^T = [1, x_i] \\; \\text{and} \\; \\mathbf{w}^T = [w_0, w_1],\n\\end{equation}\n\nand subsequently, it is possible to write the predictions for all samples as $\\hat{\\mathbf{y}} = \\mathbf{X}\\mathbf{w}$, where $\\mathbf{x}_i^T$, ..., $\\mathbf{x}_{N_\\mathrm{samples}}^T$ make up the rows in $\\mathbf{X}$. Similarly, the MSE can also be expressed with matrix notation as:\n\n\\begin{equation}\n MSE = \\frac{1}{N_\\mathrm{samples}} (\\mathbf{y}-\\mathbf{X}\\mathbf{w})^T(\\mathbf{y}-\\mathbf{X}\\mathbf{w})\n\\end{equation}\n\nNow, lets assume that we start with an initial guess ($\\tilde{w}$) for both $w_0$ and $w_1$, and then we will try to iteratively improve it. This does, however, require a way of choosing how to iteratively change $\\tilde{w}$, but we can use the gradient for this. The gradient points in the direction that a function increases the fastest. So, by moving in the opposite direction we should effectively find new values for $w_0$ and $w_1$ that correspond to a lower MSE value. We this move on to find the gradient by differentiating the MSE function with respect to $\\mathbf{w}$:\n\n\\begin{equation}\n \\frac{MSE}{d\\mathbf{w}} = \\frac{-2}{N_\\mathrm{samples}} \\mathbf{X}^T(\\mathbf{y}-\\mathbf{X}\\mathbf{w})\n\\end{equation}\n\nThe idea of moving in the opposite direction to the gradient is fundamental to all gradient based optimization techniques, and the simplest idea of just taking small steps in the opposite direction is called gradient descent.\n\n\n```python\n# Plot the MSE surface first\nfig = plt.figure(figsize=(7.5, 5))\nplt.contourf(W0, W1, mseVals, 50, cmap=cm.coolwarm)\nplt.xlabel('$w_0$')\nplt.ylabel('$w_1$');\n\n# Gradient descent\neta = 0.5e-2 # step length\nwTilde = np.array([2.5, 1.25]) # initial guess\nX = np.vstack([np.ones(nSamples), x]).T # create the X matrix where each row is one sample\nplt.plot(wTilde[0], wTilde[1], 'o', ms=6, c=[1, 1, 1]) # Plot our initial location on the MSE surface\nfor i in range(10):\n gradient = -2./nSamples * np.dot(X.T, y-np.dot(X, wTilde)) # Calculate the gradient\n wTilde -= eta*gradient # Move in the opposite direction of the gradient\n plt.plot(wTilde[0], wTilde[1], 'o', ms=6, c=[1, 1, 1]) # Plot our new location on the MSE surface\n```\n\nGradient descent is a stupidly simple approach, but it often converges quite slowly (as seen above). Luckily, we don't actually have to use it to find our MSE optimal line. We can actually take a shortcut by remembering that the gradient is zero at a the minimum. Thus, we can solve for the optimal $w_0$ and $w_1$ values by setting the gradient to zero:\n\n\\begin{align}\n \\frac{-2}{N_\\mathrm{samples}} \\mathbf{X}^T(\\mathbf{y}-\\mathbf{X}\\mathbf{w}) &= 0 \\\\\n \\mathbf{X}^T \\mathbf{y} &= \\mathbf{X}^T \\mathbf{X}\\mathbf{w}\\\\\n (\\mathbf{X}^T \\mathbf{X})^{-1} \\mathbf{X}^T \\mathbf{y} &= \\mathbf{w}\n\\end{align}\n\nwhere the last line now corresponds to the classical expression for solving a linear regression problem.\n\n\n```python\n# Optimal solution\nwOpt = np.dot(np.dot(np.linalg.inv(np.dot(X.T, X)), X.T), y)\nyHat = lineFun(wOpt[0], wOpt[1], x)\nmseFun = lambda y, yHat: np.mean((y-yHat)**2)\nmseTest = mseFun(y, yHat)\n\nfig = plt.figure(figsize=(15, 5))\nax = plt.subplot(1, 2, 1)\nfor xi, yi, yHati in zip(x, y, yHat): \n ax.stem([xi], [yi], 'r', bottom=yHati)\nax.plot(x, yHat, 'b-') \nax.plot(x, y, 'ko')\nax.set_xlabel('x')\nax.set_ylabel('y');\nax.set_title('MSE: ' + '%1.3f' % mseTest);\nax = plt.subplot(1, 2, 2)\nax.contourf(W0, W1, mseVals, 50, cmap=cm.coolwarm)\nax.set_xlabel('$w_0$')\nax.set_ylabel('$w_1$');\nax.plot(wOpt[0], wOpt[1], 'o', ms=6, c=[1, 1, 1]);\n```\n\n### What if x is multi-dimensional?\n\nThe general solution derived above works even if $\\mathbf{x}_i$ is multi-dimensional. The only difference is that we now try to fit a plane or a hyper-plane to the data instead of just a line.\n\n\n```python\n# Initialize\nw0 = 0.5 # True parameter values for w0, w1, and w2\nw1 = 0.5\nw2 = 0.5\nsigma = 1. # noise std\nnGrid = 11 # x-grid resolution\nX1, X2 = np.meshgrid(np.linspace(-5, 5, nGrid), np.linspace(-5, 5, nGrid)) # x1 ans x2 values on a grid\nplaneFun = lambda w0, w1, w2, x1, x2: w0 + w1*x1 + w2*x2 # linear mapping\n\n# Generate noisy y-data\ny = planeFun(w0, w1, w2, X1, X2).ravel()\ny += np.random.randn(nGrid**2)*sigma\n\n# Find the least squares solution\nX = np.vstack([np.ones(nGrid**2), X1.ravel(), X2.ravel()]).T \nwOpt = np.dot(np.dot(np.linalg.inv(np.dot(X.T, X)), X.T), y)\nyHat = planeFun(wOpt[0], wOpt[1], wOpt[2], X1, X2)\n\n# Plot the found least squares plane and the data points\nfig = plt.figure(figsize=(7.5, 5))\nax = fig.add_subplot(111, projection='3d')\nax.plot(X1.ravel(), X2.ravel(), y, 'ko')\nax.plot_surface(X1, X2, yHat, cmap=cm.coolwarm, linewidth=0, antialiased=False, alpha=0.5)\nax.set_xlabel('x_1')\nax.set_ylabel('x_2')\nax.set_zlabel('y');\n```\n\n### Maximum likelihood, a second approach\n\nAnother approach of finding an optimal line would be to assume that each observed $y$-value consist of two parts, signal and noise, such that\n\n\\begin{equation}\n y_i = \\mathbf{x}_i^T \\mathbf{w} + \\epsilon_i\n\\end{equation}\n\nwhere $\\epsilon$ is a normally distributed random noise term with zero mean. If the noise is identical and all data points (samples) are independent, then we can score various mappings (unique $\\mathbf{w}$ vectors) by how likely it is that each particular mapping would have generated the observed data. That is, the probability to observe any one single data point for the mapping $\\mathbf{w}$ is\n\n\\begin{equation}\n P(y_i|\\mathbf{w}) = \\frac{1}{\\sqrt{2 \\pi \\sigma^2}} \\exp \\left( -\\frac{(y_i - \\mathbf{x}_i^T \\mathbf{w})^2}{2 \\sigma^2} \\right),\n\\end{equation}\n\nand subsequently, the likelihood for observing all independent data points are:\n\n\\begin{equation}\n l(\\mathbf{y}|\\mathbf{w}) = \\prod_i^{N_\\mathrm{samples}} \\frac{1}{\\sqrt{2 \\pi \\sigma^2}} \\exp \\left( -\\frac{(y_i - \\mathbf{x}_i^T \\mathbf{w})^2}{2 \\sigma^2} \\right).\n\\end{equation}\n\nIt is however a bit cumbersome to work with likelihoods, but luckily we can work with the simpler log-likelihood instead. Taking logs of the likelihood thus gives:\n\n\\begin{align}\n ll(\\mathbf{y}|\\mathbf{w}) &= \\sum_i^{N_\\mathrm{samples}} \\ -\\frac{(y_i - \\mathbf{x}_i^T \\mathbf{w})^2}{2 \\sigma^2} - N_\\mathrm{samples} \\log( \\sqrt{2 \\pi \\sigma^2} ) \\\\\n ll(\\mathbf{y}|\\mathbf{w}) &= \\frac{-1}{2 \\sigma^2} (\\mathbf{y}-\\mathbf{X}\\mathbf{w})^T(\\mathbf{y}-\\mathbf{X}\\mathbf{w}) - N_\\mathrm{samples} \\log( \\sqrt{2 \\pi \\sigma^2} ) \n\\end{align}\n\nThe log-likelihood represents a function which we would like to maximize, in contrast to the MSE, as we want to find the $\\mathbf{w}$ that is most likely to have generated the data. However, the gradient is zero at both a maximum and a minimum, and we can thus find the $\\mathbf{w}$ at the maximum by setting the gradient of the log-likelihood function to zero.\n\n\\begin{align}\n \\frac{ll(\\mathbf{y}|\\mathbf{w})}{d\\mathbf{w}} = \\frac{-1}{\\sigma^2} \\mathbf{X}^T(\\mathbf{y}-\\mathbf{X}\\mathbf{w}) = &0 \\\\\n \\frac{-1}{\\sigma^2} \\mathbf{X}^T(\\mathbf{y}-\\mathbf{X}\\mathbf{w}) &= 0 \\\\\n \\mathbf{X}^T \\mathbf{y} &= \\mathbf{X}^T \\mathbf{X}\\mathbf{w}\\\\\n (\\mathbf{X}^T \\mathbf{X})^{-1} \\mathbf{X}^T \\mathbf{y} &= \\mathbf{w}\n\\end{align}\n\nAmazingly, we can now see that the maximum likelihood solution is the same as the least squares solution.\n\n### Orthogonal projections, a third approach \n\nIf we go back and look at how we described our linear mapping in matrix form\n\n\\begin{equation}\n \\hat{\\mathbf{y}} = \\mathbf{X} \\mathbf{w}\n\\end{equation}\n\nwe notice that all possible prediction vectors ($\\hat{\\mathbf{y}}$) live in the column space of $\\mathbf{X}$, that is in the space spanned by the columns in $\\mathbf{X}$. The intuitive explanation for this is that all prediction vectors are constructed as a linear combination of the columns in $\\mathbf{X}$, and thus these must lie in the columns space of $\\mathbf{X}$. This also means that if $\\mathbf{y}$ is not in the column space of $\\mathbf{X}$, then we can not describe it perfectly as a linear combination of the columns in $\\mathbf{X}$. However, we can search for an orthogonal projection of $\\mathbf{y}$ onto the column space, and this will represent the $\\hat{\\mathbf{y}}$ that is closest (euclidean norm) to $\\mathbf{y}$, that is our best possible approximation. These ideas are illustrated below where the dashed black lines represent the columns of $\\mathbf{X}$, the gray plane the column space, the blue line $\\mathbf{y}$, the black line our orthogonal projection of $\\mathbf{y}$, and the red line the error $\\mathbf{y}-\\hat{\\mathbf{y}}$\n\n\n```python\n# Example X and y selected to get a descent figure\nX = np.array([[1, 1, 1],[3, 1, 0.5]]).T\ny = np.array([7, 14, 1])\nwOpt = np.dot(np.dot(np.linalg.inv(np.dot(X.T, X)), X.T), y)\nu = np.dot(X, wOpt)\n\n# The columns space\nnGrid = 11 \nX1 = np.zeros([nGrid, nGrid])\nX2 = np.zeros([nGrid, nGrid])\nX3 = np.zeros([nGrid, nGrid])\nW1, W2 = np.meshgrid(np.linspace(-5, 5, nGrid), np.linspace(-5, 5, nGrid))\nfor i in range(nGrid):\n for j in range(nGrid):\n X1[i, j] = W1[i, j]*X[0, 0] + W2[i, j]*X[0, 1]\n X2[i, j] = W1[i, j]*X[1, 0] + W2[i, j]*X[1, 1]\n X3[i, j] = W1[i, j]*X[2, 0] + W2[i, j]*X[2, 1]\n \n# Plot columns vectors, the column space, y, and the orthogonal projection of y onto the column space \nfig = plt.figure(figsize=(10, 7.5))\nax = fig.add_subplot(111, projection='3d')\nax.plot_surface(X1, X2, X3, color='gray', linewidth=0, antialiased=False, alpha=0.5)\nscaling = 5\nax.plot([0, scaling*X[0, 0]], [0, scaling*X[1, 0]], [0, scaling*X[2, 0]], 'k--', lw=2)\nax.plot([0, scaling*X[0, 1]], [0, scaling*X[1, 1]], [0, scaling*X[2, 1]], 'k--', lw=2)\nax.plot([0, y[0]], [0, y[1]], [0, y[2]], 'k-', lw=2)\nax.plot([0, u[0]], [0, u[1]], [0, u[2]], 'b-', lw=2)\nax.plot([y[0], u[0]], [y[1], u[1]], [y[2], u[2]], 'r-', lw=2)\nax.grid(False)\nax.set_xlabel('$x_1$')\nax.set_ylabel('$x_2$')\nax.set_zlabel('$x_3$');\n```\n\nThe question is now then how to find the orthogonal projection of $\\mathbf{y}$. We do, however, know that the inner product between two vectors is zero if they are orthogonal. The error $\\mathbf{y}-\\hat{\\mathbf{y}}$ should thus be orthogonal to all columns in $\\mathbf{X}$. If we now write this is mathematical terms, we get:\n\n\\begin{align}\n <\\mathbf{X}, (\\mathbf{y} - \\hat{\\mathbf{y}})> = <\\mathbf{X}, (\\mathbf{y} - \\mathbf{X} \\mathbf{w})> &= 0, \\\\\n \\mathbf{X}^T(\\mathbf{y}-\\mathbf{X}\\mathbf{w}) &= 0, \\\\\n \\mathbf{X}^T \\mathbf{y} &= \\mathbf{X}^T \\mathbf{X}\\mathbf{w}, \\\\\n (\\mathbf{X}^T \\mathbf{X})^{-1} \\mathbf{X}^T \\mathbf{y} &= \\mathbf{w},\n\\end{align}\n\nand amazingly see that this approach also yielded the exact same solution as the original least squares approach.\n", "meta": {"hexsha": "e133996738b02fa07a8cd7af740db7e89ec6268b", "size": 335291, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "MixedTopics/Linear Regression.ipynb", "max_stars_repo_name": "ala-laurila-lab/jupyter-notebooks", "max_stars_repo_head_hexsha": "c7fac1ee74af8e61832dad8536b223a205e79bf2", "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": "MixedTopics/Linear Regression.ipynb", "max_issues_repo_name": "ala-laurila-lab/jupyter-notebooks", "max_issues_repo_head_hexsha": "c7fac1ee74af8e61832dad8536b223a205e79bf2", "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": "MixedTopics/Linear Regression.ipynb", "max_forks_repo_name": "ala-laurila-lab/jupyter-notebooks", "max_forks_repo_head_hexsha": "c7fac1ee74af8e61832dad8536b223a205e79bf2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-02-21T17:03:39.000Z", "max_forks_repo_forks_event_max_datetime": "2019-02-21T17:03:39.000Z", "avg_line_length": 590.301056338, "max_line_length": 80992, "alphanum_fraction": 0.9362165999, "converted": true, "num_tokens": 5117, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475699138558, "lm_q2_score": 0.9324533135530545, "lm_q1q2_score": 0.8796275673983966}} {"text": "# Linear Equations\nThe equations in the previous lab included one variable, for which you solved the equation to find its value. Now let's look at equations with multiple variables. For reasons that will become apparent, equations with two variables are known as linear equations.\n\n## Solving a Linear Equation\nConsider the following equation:\n\n\\begin{equation}2y + 3 = 3x - 1 \\end{equation}\n\nThis equation includes two different variables, **x** and **y**. These variables depend on one another; the value of x is determined in part by the value of y and vice-versa; so we can't solve the equation and find absolute values for both x and y. However, we *can* solve the equation for one of the variables and obtain a result that describes a relative relationship between the variables.\n\nFor example, let's solve this equation for y. First, we'll get rid of the constant on the right by adding 1 to both sides:\n\n\\begin{equation}2y + 4 = 3x \\end{equation}\n\nThen we'll use the same technique to move the constant on the left to the right to isolate the y term by subtracting 4 from both sides:\n\n\\begin{equation}2y = 3x - 4 \\end{equation}\n\nNow we can deal with the coefficient for y by dividing both sides by 2:\n\n\\begin{equation}y = \\frac{3x - 4}{2} \\end{equation}\n\nOur equation is now solved. We've isolated **y** and defined it as 3x-4/2\n\nWhile we can't express **y** as a particular value, we can calculate it for any value of **x**. For example, if **x** has a value of 6, then **y** can be calculated as:\n\n\\begin{equation}y = \\frac{3\\cdot6 - 4}{2} \\end{equation}\n\nThis gives the result 14/2 which can be simplified to 7.\n\nYou can view the values of **y** for a range of **x** values by applying the equation to them using the following R code:\n\n\n```R\n# Create a dataframe with an x column containing values from -10 to 10\ndf = data.frame(x = seq(-10, 10))\n\n# Add a y column by applying the solved equation to x\ndf$y = (3*df$x - 4) / 2\n\n#Display the dataframe\ndf\n```\n\n\n\n\n\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\n
xy
-10 -17.0
-9 -15.5
-8 -14.0
-7 -12.5
-6 -11.0
-5 -9.5
-4 -8.0
-3 -6.5
-2 -5.0
-1 -3.5
0 -2.0
1 -0.5
2 1.0
3 2.5
4 4.0
5 5.5
6 7.0
7 8.5
8 10.0
9 11.5
10 13.0
\n\n\n\nWe can also plot these values to visualize the relationship between x and y as a line. For this reason, equations that describe a relative relationship between two variables are known as *linear equations*:\n\n\n```R\nlibrary(ggplot2)\nlibrary(repr)\noptions(repr.plot.width=4, repr.plot.height=4)\nggplot(df, aes(x,y)) + geom_point() + geom_line(color = 'blue')\n```\n\nIn a linear equation, a valid solution is described by an ordered pair of x and y values. For example, valid solutions to the linear equation above include:\n- (-10, -17)\n- (0, -2)\n- (9, 11.5)\n\nThe cool thing about linear equations is that we can plot the points for some specific ordered pair solutions to create the line, and then interpolate the x value for any y value (or vice-versa) along the line.\n\n## Intercepts\nWhen we use a linear equation to plot a line, we can easily see where the line intersects the X and Y axes of the plot. These points are known as *intercepts*. The *x-intercept* is where the line intersects the X (horizontal) axis, and the *y-intercept* is where the line intersects the Y (horizontal) axis.\n\nLet's take a look at the line from our linear equation with the X and Y axis shown through the origin (0,0).\n\n\n```R\nggplot(df, aes(x,y)) + geom_point() + geom_line(color = 'blue') +\n geom_hline(yintercept=0) + geom_vline(xintercept=0)\n```\n\nThe x-intercept is the point where the line crosses the X axis, and at this point, the **y** value is always 0. Similarly, the y-intercept is where the line crosses the Y axis, at which point the **x** value is 0. So to find the intercepts, we need to solve the equation for **x** when **y** is 0.\n\nFor the x-intercept, our equation looks like this:\n\n\\begin{equation}0 = \\frac{3x - 4}{2} \\end{equation}\n\nWhich can be reversed to make it look more familar with the x expression on the left:\n\n\\begin{equation}\\frac{3x - 4}{2} = 0 \\end{equation}\n\nWe can multiply both sides by 2 to get rid of the fraction:\n\n\\begin{equation}3x - 4 = 0 \\end{equation}\n\nThen we can add 4 to both sides to get rid of the constant on the left:\n\n\\begin{equation}3x = 4 \\end{equation}\n\nAnd finally we can divide both sides by 3 to get the value for x:\n\n\\begin{equation}x = \\frac{4}{3} \\end{equation}\n\nWhich simplifies to:\n\n\\begin{equation}x = 1\\frac{1}{3} \\end{equation}\n\nSo the x-intercept is 11/3 (approximately 1.333).\n\nTo get the y-intercept, we solve the equation for y when x is 0:\n\n\\begin{equation}y = \\frac{3\\cdot0 - 4}{2} \\end{equation}\n\nSince 3 x 0 is 0, this can be simplified to:\n\n\\begin{equation}y = \\frac{-4}{2} \\end{equation}\n\n-4 divided by 2 is -2, so:\n\n\\begin{equation}y = -2 \\end{equation}\n\nThis gives us our y-intercept, so we can plot both intercepts on the graph:\n\n\n```R\nggplot(df, aes(x,y)) + geom_line(color = 'blue') +\n geom_hline(yintercept=0) + geom_vline(xintercept=0) +\n annotate(\"text\", x = 3, y = -2, label = \"y-intercept\")+\n annotate(\"text\", x = 5, y = 1, label = \"x-intercept\")\n```\n\nThe ability to calculate the intercepts for a linear equation is useful, because you can calculate only these two points and then draw a straight line through them to create the entire line for the equation.\n\n## Slope\nIt's clear from the graph that the line from our linear equation describes a slope in which values increase as we travel up and to the right along the line. It can be useful to quantify the slope in terms of how much **x** increases (or decreases) for a given change in **y**. In the notation for this, we use the greek letter Δ (*delta*) to represent change:\n\n\\begin{equation}slope = \\frac{\\Delta{y}}{\\Delta{x}} \\end{equation}\n\nSometimes slope is represented by the variable ***m***, and the equation is written as:\n\n\\begin{equation}m = \\frac{y_{2} - y_{1}}{x_{2} - x_{1}} \\end{equation}\n\nAlthough this form of the equation is a little more verbose, it gives us a clue as to how we calculate slope. What we need is any two ordered pairs of x,y values for the line - for example, we know that our line passes through the following two points:\n- (0,-2)\n- (6,7)\n\nWe can take the x and y values from the first pair, and label them x1 and y1; and then take the x and y values from the second point and label them x2 and y2. Then we can plug those into our slope equation:\n\n\\begin{equation}m = \\frac{7 - -2}{6 - 0} \\end{equation}\n\nThis is the same as:\n\n\\begin{equation}m = \\frac{7 + 2}{6 - 0} \\end{equation}\n\nThat gives us the result 9/6 which is 11/2 or 1.5 .\n\nSo what does that actually mean? Well, it tells us that for every change of **1** in x, **y** changes by 11/2 or 1.5. So if we start from any point on the line and move one unit to the right (along the X axis), we'll need to move 1.5 units up (along the Y axis) to get back to the line.\n\nYou can plot the slope onto the original line with the following R code to verify it fits:\n\n\n```R\nline = data.frame(x = c(0,1.5), y = c(-2,0))\nggplot() + geom_line(data = df, aes(x,y),color = 'blue') +\n geom_hline(yintercept=0) + geom_vline(xintercept=0) +\n geom_line(data = line, aes(x,y), color = 'red', size = 3)\n```\n\n### Slope-Intercept Form\nOne of the great things about algebraic expressions is that you can write the same equation in multiple ways, or *forms*. The *slope-intercept form* is a specific way of writing a 2-variable linear equation so that the equation definition includes the slope and y-intercept. The generalised slope-intercept form looks like this:\n\n\\begin{equation}y = mx + b \\end{equation}\n\nIn this notation, ***m*** is the slope and ***b*** is the y-intercept.\n\nFor example, let's look at the solved linear equation we've been working with so far in this section:\n\n\\begin{equation}y = \\frac{3x - 4}{2} \\end{equation}\n\nNow that we know the slope and y-intercept for the line that this equation defines, we can rewrite the equation as:\n\n\\begin{equation}y = 1\\frac{1}{2}x + -2 \\end{equation}\n\nYou can see intuitively that this is true. In our original form of the equation, to find y we multiply x by three, subtract 4, and divide by two - in other words, x is half of 3x - 4; which is 1.5x - 2. So these equations are equivalent, but the slope-intercept form has the advantages of being simpler, and including two key pieces of information we need to plot the line represented by the equation. We know the y-intecept that the line passes through (0, -2), and we know the slope of the line (for every x, we add 1.5 to y.\n\nLet's recreate our set of test x and y values using the slope-intercept form of the equation, and plot them to prove that this describes the same line:\n\n\n```R\n## Make a data frame with the x values\ndf = data.frame(x = seq(-10,10))\n\n## Add the y values using the formula y = mx + b\nm = 1.5\nb = -2\ndf$y = m * df$x + b\n\n## Plot the result\nggplot() + geom_line(data = df, aes(x,y),color = 'blue') +\n geom_hline(yintercept=0) + geom_vline(xintercept=0) +\n geom_line(data = line, aes(x,y), color = 'red', size = 3) +\n annotate(\"text\", x = 3, y = -2, label = \"y-intercept\")\n```\n", "meta": {"hexsha": "1e92e80e4ce9dc4f248cc35be32327046b9d9cd6", "size": 44734, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "R/Module01/01-02-Linear Equations.ipynb", "max_stars_repo_name": "joelgenter/Essential-Math", "max_stars_repo_head_hexsha": "2e76546a82fb0ad2b8698c7dc0f48f0aad0762bb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 33, "max_stars_repo_stars_event_min_datetime": "2018-01-11T20:44:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T16:10:41.000Z", "max_issues_repo_path": "R/Module01/01-02-Linear Equations.ipynb", "max_issues_repo_name": "joelgenter/Essential-Math", "max_issues_repo_head_hexsha": "2e76546a82fb0ad2b8698c7dc0f48f0aad0762bb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2018-11-19T23:54:27.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-20T00:15:39.000Z", "max_forks_repo_path": "R/Module01/01-02-Linear Equations.ipynb", "max_forks_repo_name": "joelgenter/Essential-Math", "max_forks_repo_head_hexsha": "2e76546a82fb0ad2b8698c7dc0f48f0aad0762bb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 35, "max_forks_repo_forks_event_min_datetime": "2018-03-08T15:42:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-03T06:11:43.000Z", "avg_line_length": 94.1768421053, "max_line_length": 6036, "alphanum_fraction": 0.784705146, "converted": true, "num_tokens": 3134, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109798251322, "lm_q2_score": 0.9252299524531926, "lm_q1q2_score": 0.8793487056745993}} {"text": "```python\nimport numpy as np\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\n```\n\n# Using a known function\n\n
We will optimize the following equation:\n\\begin{equation} y = (x-5)^2 + 3 \\end{equation} \n\nWhich we know the minimum is:\n\n\\begin{equation} x = 5 \\end{equation} \n\\begin{equation} y = 3 \\end{equation} \n\n\n```python\nX = np.linspace(0,10, 100) # Get 100 datapoints equally spaced from 0 to 10\ny = 3 + np.power((X-5),2)\n```\n\nLet's plot our data to check the relation between X and y\n\n\n```python\nplt.plot(X,y,'red')\nplt.xlabel(\"$x$\", fontsize=18)\nplt.ylabel(\"$y$\", rotation=0, fontsize=18)\nplt.xlim((0,10))\n```\n\n# Gradient Descent\n\n## Cost Function & Gradients\n\n

Remember that in optimization methods we optimize a given cost. In our case it will be the quadratic equation below. Just in case calculating gradients is not your thing, I already precalculated the gradient in this case. \n\n\n\nCost\n\\begin{equation}\ny = (X-5)^2 + 3\n\\end{equation}\n\nGradient\n\n\\begin{equation}\n2*(X-5)\n\\end{equation}\n\n\n```python\ndef cost(X):\n return 3 + np.power((X-5), 2)\n```\n\n\n```python\ndef gradient(X):\n return 2*(X-5)\n```\n\n\n```python\ndef gradient_descent(X,learning_rate=0.01,iterations=100, print_all=True):\n costs = []\n for it in range(iterations):\n X = X -learning_rate*gradient(X)\n if it % 50 == 0 and print_all:\n print(\"The iteration is {} and the current value of X is {}\".format(it, X))\n costs.append(cost(X))\n return X, costs\n \n```\n\n

Let's start from a random number between 0 and 1, with 200 iterations and a learning rate of 0.01.\n\n\n```python\nlr =0.01\nn_iter = 200\nX = np.random.random()*10\nX, costs = gradient_descent(X,lr,n_iter)\nprint(\"Minimum is at (x,y) = ({}, {})\".format(X, cost(X)))\n```\n\n The iteration is 0 and the current value of X is 7.399074672684869\n The iteration is 50 and the current value of X is 5.873670256056753\n The iteration is 100 and the current value of X is 5.3181642176498185\n The iteration is 150 and the current value of X is 5.115865761356701\n Minimum is at (x,y) = (5.043055915557471, 3.001853811864492)\n\n\n

Let's plot the cost history over iterations\n\n\n```python\nfig,ax = plt.subplots(figsize=(12,8))\n\nax.set_ylabel('Cost')\nax.set_xlabel('Iterations')\n_=ax.plot(range(n_iter),costs,'b.')\n```\n\n

After around 120 iterations the cost is flat so the remaining iterations are not needed or will not result in any further optimization. And if the learning rate is bigger?\n\n\n```python\nnew_lr =0.1\nnew_n_iter = 50\nX_b = np.random.random()\nX_new, costs_new = gradient_descent(X_b,new_lr,new_n_iter)\nprint(\"Minimum is at (x,y) = ({}, {})\".format(X_new, cost(X_new)))\n\n\nfig,ax = plt.subplots(figsize=(12,8))\n\nax.set_ylabel('Cost')\nax.set_xlabel('Iterations')\n_=ax.plot(range(new_n_iter),costs_new,'b.')\n```\n\nClearly with a higher learning rate we got to the optimal point in 10 iterations. Let's see how this changes with different learning rates\n\n\n```python\nlearning_rates = [0.01,0.1,1,10]\niterations = 200\nX_0 = np.random.random()\nplt.figure(figsize=(20,5))\nall_costs = []\nfor lr in learning_rates:\n X, costs = gradient_descent(X_0,lr,iterations, print_all=True)\n print(\"Minimum is at (x,y) = ({}, {})\".format(X, cost(X)))\n all_costs.append(costs)\n\nax.set_ylabel('Cost')\nax.set_xlabel('Iterations')\nplt.xlim((0,200))\nplt.ylim((0,50))\nplt.scatter(range(iterations), all_costs[0], color='red')\nplt.scatter(range(iterations), all_costs[1], color='blue')\nplt.scatter(range(iterations), all_costs[2], color='green')\nplt.scatter(range(iterations), all_costs[3], color='black')\nplt.legend(['LR = 0.01', 'LR = 0.1', 'LR = 1', 'LR = 10'])\nplt.show()\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "1594ef62f2fcc2989de09969f8fe088f18019e6b", "size": 61449, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Module 3/demo_module3_gd_sgd.ipynb", "max_stars_repo_name": "axel-sirota/interpreting-data-with-advanced-models", "max_stars_repo_head_hexsha": "699dd8281c78d88b31b59f43bdf2f29a57f3f94c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-12-10T13:15:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-10T13:15:01.000Z", "max_issues_repo_path": "Module 3/demo_module3_gd_sgd.ipynb", "max_issues_repo_name": "axel-sirota/interpreting-data-with-advanced-models", "max_issues_repo_head_hexsha": "699dd8281c78d88b31b59f43bdf2f29a57f3f94c", "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": "Module 3/demo_module3_gd_sgd.ipynb", "max_forks_repo_name": "axel-sirota/interpreting-data-with-advanced-models", "max_forks_repo_head_hexsha": "699dd8281c78d88b31b59f43bdf2f29a57f3f94c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-04-13T06:07:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-10T13:15:09.000Z", "avg_line_length": 127.7525987526, "max_line_length": 15152, "alphanum_fraction": 0.8818857915, "converted": true, "num_tokens": 1103, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947117065459, "lm_q2_score": 0.9304582612793112, "lm_q1q2_score": 0.8792781363726166}} {"text": "```python\nfrom sympy import *\ninit_printing(use_latex='mathjax')\nx, y, z = symbols('x,y,z')\nr, theta = symbols('r,theta', positive=True)\n```\n\n## Matrices\n\nEl objeto `Matrix` de *Sympy* nos ayuda con pequeños problemas en álgebra lineal.\n\n\n```python\nrot = Matrix([[r*cos(theta), -r*sin(theta)],\n [r*sin(theta), r*cos(theta)]])\nrot\n```\n\n### Métodos estándar\n\n\n```python\nrot.det()\n```\n\n\n```python\nrot.inv()\n```\n\n\n```python\nrot.singular_values()\n```\n\n### Ejercicios\n\nEncuentre la inversa de la siguiente matriz:\n\n$$ \\left[\\begin{matrix}1 & x\\\\y & 1\\end{matrix}\\right] $$\n\n\n```python\n# Crea una matriz y usa el método `inv` para encontrar la inverso\n\n\n```\n\n### Operadores\n\nLos operadores estándar *SymPy* trabajan en matrices.\n\n\n```python\nrot * 2\n```\n\n\n```python\nrot**2\n```\n\n\n```python\nv = Matrix([[x], [y]])\nv\n```\n\n\n```python\nrot * v\n```\n\n### Ejercicio\n\nEn el último ejercicio encontraste la inversa de la siguiente matriz\n\n\n```python\nM = Matrix([[1, x], [y, 1]])\nM\n```\n\n\n```python\nM.inv()\n```\n\nAhora verifica que esta es la verdadera inversa multiplicando la matriz por su inversa. ¿Recuperas la matriz identidad?\n\n\n```python\n# Multiplica `M` por su inversa. ¿Recuperas la matriz identidad?\n```\n\n### Ejercicio\n\n¿Cuáles son los vectores y valores propios de `M`?\n\n\n```python\n# Encuentra los metodos para calcular vectores y valores propios. Usa estos metodos en `M`\n\n```\n\n### Acceso a elementos estilo NumPy\n\n\n```python\nrot[0, 0]\n```\n\n\n```python\nrot[:, 0]\n```\n\n\n```python\nrot[1, :]\n```\n\n### Mutación\n\nPodemos cambiar elementos en la matriz.\n\n\n```python\nrot[0, 0] += 1\nrot\n```\n\n\n```python\nsimplify(rot.det())\n```\n\n\n```python\nrot.singular_values()\n```\n\n### Ejercicio\n\nJuega con tu matriz `M`, manipulando elementos de forma similar a *NumPy*. Luego prueba los diversos métodos de los que hemos hablado (u otros). Averigua qué tipo de respuestas obtienes.\n\n\n```python\n# Juega con matrices\n\n\n```\n", "meta": {"hexsha": "67e8ef74b065710bdcbcf1eee3b5340d286d1064", "size": 5982, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "tutorial_exercises/04-Matrices.ipynb", "max_stars_repo_name": "t3rodrig/sympy-tutorial-es", "max_stars_repo_head_hexsha": "5cd5497f799e889d758a26539781cdc72b1e6a74", "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": "tutorial_exercises/04-Matrices.ipynb", "max_issues_repo_name": "t3rodrig/sympy-tutorial-es", "max_issues_repo_head_hexsha": "5cd5497f799e889d758a26539781cdc72b1e6a74", "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": "tutorial_exercises/04-Matrices.ipynb", "max_forks_repo_name": "t3rodrig/sympy-tutorial-es", "max_forks_repo_head_hexsha": "5cd5497f799e889d758a26539781cdc72b1e6a74", "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": 18.462962963, "max_line_length": 192, "alphanum_fraction": 0.4994984955, "converted": true, "num_tokens": 574, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947132556618, "lm_q2_score": 0.9304582501911272, "lm_q1q2_score": 0.879278127335729}} {"text": "# Implementing Discrete Fourier Transform(DFT) Using Python\n\n## Table of Contents\n* [Introduction](#Introduction)\n* [Python Implementation](#Implementation)\n* [Testing the Code](#Testing)\n* [Conclusion](#Conclusion)\n\n\n\n## Introduction\n\nDigital images are usually stored and displayed in **space domain**. That is, each point/pixel in the image contains an integer value that shows the color intensity value. For example, if we have 8x8 image, then there are 64 values that are stored in each pixel location.\n\nHowever, images can be transformed in to their corresponding **frequecy domain** representation. The advantage of the transformation is that several image processing tasks are well done in their transformed format. For example, they can be used for:\n\n* *Image Enhancement*\n* *Image Restoration*\n* *Image Coding*\n* *Image Compression*\n\nThen, after these processes are performed, the processed image can be returned back to its original space domain form by using inverse transform process. There are several types of transforms, such as:\n\n* *Discrete Fourier Transform (DFT)*\n* *Discrete Cosine Transform (DCT)*\n* *Walsh-Hadamard Transform*\n* *Haar Transform*\n\nIn this homework, we are only concerned with DFT. \n\nA 2-dimensional DFT (2D-DFT) decomposes an image into its sinusoidal components (sines and cosines). As explained above, the input is the image in its **spatial domain**. In contrast, the output will be the image's representation in its fourier or **frequency domain**. DFT is a complex number transform as it has both the real (cosine) and imaginary (sine) components as an output.\n\nLet the size of an input image be NxN. The general form is:\n\n$$\n\\begin{align}\nF(u,v) = \\frac{1}{N^2}\\sum_{x=0}^{N-1}\\sum_{y=0}^{N-1}f(x,y) e^{(-j2\\pi\\frac{ux+vy}{N})} \\; where \\; u,v=0,1,2,...N-1\n\\end{align}\n$$\n\nThe above formula is **forward DFT transformation**.\n\nSimilarly, for **inverse DFT transformation**:\n$$\n\\begin{align}\nf(u,v) = \\sum_{u=0}^{N-1}\\sum_{v=0}^{N-1}F(u,v) e^{(+j2\\pi\\frac{ux+vy}{N})} \\; where \\; x,y=0,1,2,...N-1\n\\end{align}\n$$\n\n* $ k(x,y,u,v)=e^{(-j2\\pi\\frac{ux+vy}{N})} $ is called **basis function (kernel function)**\n\nTo find the real and imaginary part of the transformed image:\n\n$$\n\\begin{align}\n* e^{\\pm jx} = \\cos(x)\\pm j\\sin(x)\n\\end{align}\n$$\n\nSince the kernel function in DFT is separable:\n$$\\begin{align}\nk(x,y,u,v)=e^{(-j2\\pi\\frac{ux+vy}{N})} = e^{(-j2\\pi\\frac{ux}{N})}e^{(-j2\\pi\\frac{vy}{N})}\n\\end{align}$$\n\n$$\\begin{align}\nk(x,y,u,v) = k_1(x,u).k_2(v,y)\n\\end{align}\n$$\n\nSo, the 2D-DFT formula can be computed as a sequence of two 1D-DFT transform. That is, each row of the original image is transformed and then each column of the previous result is transformed. This can be visualized as follows and was taken from [here](http://web.cs.wpi.edu/~emmanuel/courses/cs545/S14/slides/lecture10.pdf):\n\n\n\nSimilarly, we can also apply the same technique to compute the inverse transformation:\n\nFor the forward transformation:\n\n$$\\begin{align}\nF(u, v) = k_f(u,x) \\;f(x,y) \\; k_f(y,v)^{T*} \\; where \\; T* = Matrix \\; transpose \\; and \\; conjugate \n\\end{align}\n$$\n\nAnd for the inverse transformation:\n\n$$\\begin{align}\nf(x, y) = k_i(x,u) \\; F(u,v) \\; k_i^{T*} \n\\end{align}\n$$\n\nWhere:\n* $ k_f $ = **kernel** function of the **forward** transformation\n\n* $ k_i $= **kernel** function of the **inverse** transformation*\n\n* $ k_i = k_f^{-1} $ and $ k_i = k_f^T $ (Since the kernel function is **orthogonal**).\n\n* And $ k_f = k_f^{T}$ (Since it is a **symmetric** function)\n\n* So, $ k_i = k_f^{*T}$\n\nTherefore:\n$$\\begin{align}\nf(x, y) = k_f(x,u)^{*} \\; F(u,v) \\; k_f\n\\end{align}\n$$\n\nIn the next section, the forward DFT will be implemented in python. Finally they will be tested with images of different sizes. And their running time will be computed and visualized.\n\n\n\n## Python Implementation\n\nFirst of all, let's import the necessary python libraries\n\n\n```python\nimport numpy as np\n\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\n#import matplotlib.image as img\nimport PIL.Image as Image \n\nimport math\nimport cmath\n\nimport time\n\nimport csv\n```\n\nNow let's start with creating common image functions.\n\n\n```python\ndef generateBlackAndWhiteSquareImage(imgSize):\n \"\"\"\n Generates a square-sized black and white image with a given input size.\n\n Parameters\n ----------\n imgSize : int\n Input number that stores the dimension of the square image to be generated.\n\n Returns\n -------\n imge : ndarray\n The generated black and white square image.\n \"\"\"\n\n #Creating a matrix with a given size where all the stored values are only zeros (for initialization)\n imge = np.zeros([imgSize, imgSize], dtype=int)\n\n #Starting and ending indices of the white part of the image.\n ind1 = imgSize/4\n ind2 = ind1 + (imgSize/2)\n\n #Make a part of the image as white (255)\n imge[ind1:ind2, ind1:ind2] = np.ones([imgSize/2, imgSize/2], dtype=int)*255\n\n #return the resulting image\n return imge\n \ndef generateImagesWithResizedWhite(imge):\n \"\"\"\n Generates images with the same size as the original but with a resized white part of them.\n \"\"\"\n\n N = imge.shape[0]\n\n imges = []\n i = N/2\n while i >= 4:\n j = (N - i)/2\n\n #Starting and ending indices for the white part.\n indx1 = j\n indx2 = j+i\n\n #Draw the image.\n imgeNew = np.zeros([N, N],dtype=int)\n imgeNew[indx1:indx2, indx1:indx2] = np.ones([i, i], dtype=int)*255\n\n #Add the image to the list.\n imges.append(imgeNew)\n\n i = i/2\n\n return imges\n\ndef resizeImage(imge, newSize): \n \"\"\"\n Reduces the size of the given image.\n\n Parameters\n ----------\n imge : ndarray\n Input array that stores the image to be resized.\n\n Returns\n -------\n newSize : int\n The size of the newly generated image.\n \"\"\"\n\n #Compute the size of the original image (in this case, only # of rows as it is square)\n N = imge.shape[0]\n\n #The ratio of the original image as compared to the new one.\n stepSize = N/newSize\n\n #Creating a new matrix (image) with a black color (values of zero)\n newImge = np.zeros([N/stepSize, N/stepSize])\n\n #Average the adjacent four pixel values to compute the new intensity value for the new image.\n for i in xrange(0, N, stepSize):\n for j in xrange(0, N, stepSize):\n newImge[i/stepSize, j/stepSize] = np.mean(imge[i:i+stepSize, j:j+stepSize])\n\n #Return the new image\n return newImge\n\n```\n\nAs a next step, the main class that implements a 2D DFT. Both the forward and inverse DFT will be implemented here.\n\n*Note: All the input images are assumed to be square in size. But the implementation can easily be modified to work with rectangular images (not squares).*\n\n\n```python\nclass DFT(object):\n \"\"\"\n This class DFT implements all the procedures for transforming a given 2D digital image\n into its corresponding frequency-domain image (Forward DFT Transform)\n \"\"\"\n \n @classmethod\n def __computeConjugate(self, mat):\n \"\"\"\n Computes the conjugate of a complex square-matrix.\n\n Parameters\n ----------\n mat : ndarray\n Input matrix of complex numbers.\n\n Returns\n -------\n result : ndarray\n The conjugate of the input matrix.\n \"\"\"\n \n N = mat.shape[0]\n result = np.zeros([N, N], dtype=np.complex)\n \n for i in range(N):\n for j in range(N):\n result[i, j] = (mat[i, j].real) - (mat[i, j].imag*1j)\n\n return result\n \n @classmethod\n def __multiplyMatrices(self, mat1, mat2):\n \"\"\"\n Computes the multiplication of two complex square matrices.\n\n Parameters\n ----------\n mat1 : ndarray\n First input matrix of complex numbers.\n mat2 : ndarray\n Second input matrix of complex numbers.\n \n Returns\n -------\n result : ndarray\n The multiplication result of the two matrices.\n \"\"\"\n \n N = mat1.shape[0]\n \n result = np.zeros([N, N], np.complex)\n #For each column and row...\n for i in range(N):\n row = mat1[i, :]\n for j in range(N):\n col = mat2[j, :]\n total = 0 + 0j\n for k in range(N):\n total += row[k]*col[k]\n result[i, j] = total\n \n return result\n \n #Compute the two separable kernels for the forward DFT.\n @classmethod\n def computeXForwardKernel(self, size):\n \"\"\"\n Computes/generates the first forward kernel function.\n\n Parameters\n ----------\n size : int\n Size of the kernel to be generated.\n\n Returns\n -------\n xKernel : ndarray\n The generated kernel as a matrix.\n \"\"\"\n \n #Initialize the kernel\n xKernel = np.zeros([size, size], dtype=np.complex)\n \n #Compute each value of the kernel...\n for u in range(size):\n for x in range(size):\n \n #Rounding it is used here for making the values integers as it will insert very small fractions.\n xKernel[u, x] = math.cos((2*math.pi*u*x)/size) - (1j*math.sin((2*math.pi*u*x)/size))\n \n #Return the resulting kernel\n return xKernel\n\n @classmethod\n def computeYForwardKernel(self, xKernel):\n \"\"\"\n Computes/generates the second forward kernel function.\n\n Parameters\n ----------\n xKernel : ndarray\n The first forward kernel function.\n\n Returns\n -------\n yKernel : ndarray\n The generated kernel as a matrix.\n \"\"\"\n #yKernel = np.conj(xKernel) ## In numpy package.\n N = xKernel.shape[0]\n \n #For each value, find the conjugate...\n yKernel = np.zeros([N, N], dtype=np.complex)\n for i in range(N):\n for j in range(N):\n yKernel[i, j] = (xKernel[i, j].real) - (xKernel[i, j].imag*1j)\n \n # Return the resulting kernel (Since the original kernel is symmetric, transpose is not needed)\n return yKernel\n \n @classmethod\n def computeCenteredImage(self, imge):\n \"\"\"\n Centers a given image.\n\n Parameters\n ----------\n imge : ndarray\n Input array that stores the image to be centered.\n\n Returns\n -------\n newImge : int\n The new and centered version of the input image.\n \"\"\"\n \n #Compute the dimensions of the image\n M, N = imge.shape\n #centeringMatrix = np.zeros([M, N], dtype=int)\n newImge = np.zeros([M, N], dtype=int)\n for x in range(M):\n for y in range(N):\n newImge[x, y] = imge[x, y] * ((-1)**(x+y))\n\n #newImge = imge * centeringMatrix\n return newImge\n \n @classmethod\n def computeForward2DDFTWithSeparability(self, imge):\n \"\"\"\n Computes/generates the 2D DFT by computing the two forward kernels first (Separability).\n\n Parameters\n ----------\n imge : ndarray\n The input image to be transformed.\n\n Returns\n -------\n final2DDFT : ndarray\n The transformed image.\n \"\"\"\n \n N = imge.shape[0]\n xKernel = DFT.computeXForwardKernel(N)\n yKernel = DFT.computeYForwardKernel(xKernel)\n\n #row1DDFT = (1.0/size) * np.dot(xKernel, imge)\n intermediate2DDFT = (1.0/N) * DFT.__multiplyMatrices(xKernel, imge)\n final2DDFT = (1.0/N) * DFT.__multiplyMatrices(intermediate2DDFT, yKernel)\n\n return final2DDFT\n \n @classmethod\n def __computeSinglePoint2DFT(self, imge, u, v, N):\n \"\"\"\n A private method that computes a single value of the 2DDFT from a given image.\n\n Parameters\n ----------\n imge : ndarray\n The input image.\n \n u : ndarray\n The index in x-dimension.\n \n v : ndarray\n The index in y-dimension.\n\n N : int\n Size of the image.\n \n Returns\n -------\n result : complex number\n The computed single value of the DFT.\n \"\"\"\n result = 0 + 0j\n for x in xrange(N):\n for y in xrange(N):\n result += (imge[x, y] * (math.cos((2*math.pi*(u*x + v*y))/N) - \n (1j*math.sin((2*math.pi*(u*x + v*y))/N))))\n return result\n \n @classmethod\n def computeForward2DDFTNoSeparability(self, imge):\n \"\"\"\n Computes/generates the 2D DFT by computing without separating the kernels.\n\n Parameters\n ----------\n imge : ndarray\n The input image to be transformed.\n\n Returns\n -------\n final2DDFT : ndarray\n The transformed image.\n \"\"\"\n \n # Assuming a square image\n N = imge.shape[0]\n final2DDFT = np.zeros([N, N], dtype=np.complex)\n for u in xrange(N):\n for v in xrange(N):\n #Compute the DFT value for each cells/points in the resulting transformed image.\n final2DDFT[u, v] = DFT.__computeSinglePoint2DFT(imge, u, v, N)\n return ((1.0/(N**2))*final2DDFT)\n \n @classmethod\n def computeInverse2DDFTWithSeparability(self, dftImge):\n \"\"\"\n Computes the inverse 2D DFT by computing the two inverse kernels first (Separability).\n\n Parameters\n ----------\n dftImge : ndarray\n The dft transformed image as input.\n\n Returns\n -------\n imge : ndarray\n The resulting image in spatial domain from the inverse DFT.\n \"\"\"\n \n N = dftImge.shape[0]\n \n #Here the kernels are interchanged from the forward DFT\n yKernel = DFT.computeXForwardKernel(N)\n xKernel = DFT.computeYForwardKernel(yKernel)\n\n intermediateImge = DFT.__multiplyMatrices(xKernel, dftImge)\n imge = DFT.__multiplyMatrices(intermediateImge, yKernel)\n \n #imge = np.real(imge)\n\n return imge \n\n @classmethod\n def compute2DDFTFourierSpectrum(self, dftImge):\n \"\"\"\n Computes the fourier spectrum of the transformed image.\n\n Parameters\n ----------\n dftImge : ndarray\n The input transformed image.\n\n Returns\n -------\n fourierSpect : ndarray\n The computed fourier spectrum.\n \"\"\"\n N = dftImge.shape[0]\n \n fourierSpect = np.zeros([N, N], dtype=float)\n #Calculate the magnitude of each point(complex number) in the DFT image\n for i in xrange(N):\n for j in xrange(N):\n v = dftImge[i, j]\n fourierSpect[i, j] = math.sqrt((v.real)**2 + (v.imag)**2)\n return fourierSpect\n \n @classmethod\n def normalize2DDFTByLog(self, dftImge):\n \"\"\"\n Computes the log transformation of the transformed DFT image to make the range\n of the fourier values b/n 0 to 255\n \n Parameters\n ----------\n dftImge : ndarray\n The input transformed image.\n\n Returns\n -------\n dftNormImge : ndarray\n The normalized version of the transformed image.\n \"\"\"\n \n #Compute the fourier spectrum of the transformed image:\n dftFourierSpect = DFT.compute2DDFTFourierSpectrum(dftImge)\n \n #Normalize the fourier spectrum values:\n dftNormFourierSpect = (255.0/ math.log10(255)) * np.log10(1 + (255.0/(np.max(dftFourierSpect))*dftFourierSpect))\n \n return dftNormFourierSpect\n \n```\n\n\n\n\n\n## Testing the Code and Visualizing the DFT Running Time\n\n### Testing the DFT algorithm\n\nFor testing purposes, the 4x4 separable DFT kernels are computed:\n\n\n```python\n# The numbers are rounded for visualization\nxKernel = np.round(DFT.computeXForwardKernel(4))\nprint \"The first 4x4 forward kernel:\"\nxKernel\n```\n\n The first 4x4 forward kernel:\n\n\n\n\n\n array([[ 1.+0.j, 1.+0.j, 1.+0.j, 1.+0.j],\n [ 1.+0.j, 0.-1.j, -1.-0.j, -0.+1.j],\n [ 1.+0.j, -1.-0.j, 1.+0.j, -1.-0.j],\n [ 1.+0.j, -0.+1.j, -1.-0.j, 0.-1.j]])\n\n\n\n\n```python\n# The second kernel is the conjugate of the first (as the kernels are symmetric, we don't need to transpose)\nyKernel = np.round(DFT.computeYForwardKernel(xKernel))\nprint \"The first 4x4 forward kernel:\"\nyKernel\n```\n\n The first 4x4 forward kernel:\n\n\n\n\n\n array([[ 1.+0.j, 1.+0.j, 1.+0.j, 1.+0.j],\n [ 1.+0.j, 0.+1.j, -1.+0.j, -0.-1.j],\n [ 1.+0.j, -1.+0.j, 1.+0.j, -1.+0.j],\n [ 1.+0.j, -0.-1.j, -1.+0.j, 0.+1.j]])\n\n\n\nHere, we generate an 8-bit gray scale image as a 64x64 matrix\n\n\n```python\nimge = generateBlackAndWhiteSquareImage(64)\n```\n\nGenerate images of the same size as above but with different white part size:\n\n\n```python\nimges = generateImagesWithResizedWhite(imge)\n```\n\nTo test the DFT with different images having different white size:\n\nHere, we will generate the images, compute the DFT and visualize the results:\n\n\n```python\n#For visualization:\nN = len(imges) \nfig, axarr = plt.subplots(N, 4, figsize=(13, 13))\n\n#Compute DFT for each generated image...\ndftImges = []\nfor i, imge in enumerate(imges):\n \n #Center the generated image\n centeredImge = DFT.computeCenteredImage(imge)\n \n #Compute the 2D DFT transformation for both centered and uncentered images:\n dftUncenteredImge = DFT.computeForward2DDFTWithSeparability(imge)\n dftCenteredImge = DFT.computeForward2DDFTWithSeparability(centeredImge)\n \n #Save the centered DFT images...\n dftImges.append(dftCenteredImge)\n \n #Normalize the computed DFT results:\n dftUncenteredNormImge = DFT.normalize2DDFTByLog(dftUncenteredImge)\n dftCenteredNormImge = DFT.normalize2DDFTByLog(dftCenteredImge)\n \n #Display the normalized versions of the centered and uncentered images\n axarr[i][0].imshow(imge, cmap=plt.get_cmap('gray'), vmin=0, vmax=255)\n axarr[i][0].set_title('Original Image')\n\n axarr[i][1].imshow(dftUncenteredNormImge, cmap=plt.get_cmap('gray'), vmin=0, vmax=255)\n axarr[i][1].set_title('Normalized Uncentered DFT')\n\n axarr[i][2].imshow(DFT.compute2DDFTFourierSpectrum(dftCenteredImge), cmap=plt.get_cmap('gray'))\n axarr[i][2].set_title('Unnormalized Centered DFT')\n\n axarr[i][3].imshow(dftCenteredNormImge, cmap=plt.get_cmap('gray'), vmin=0, vmax=255)\n axarr[i][3].set_title('Normalized Centered DFT')\n \n#fig.suptitle(\"DFT FOR 64x64 IMAGES HAVING DIFFERENT WHITE COLOR SIZE\")\n#fig.subplots_adjust(top=2)\nplt.show()\n```\n\nFrom the above results, we can see that the white color size in the original and transformed images are inversely proportional. This is similar to $\\delta x \\; and \\; \\frac{1}{\\delta x} $ which are inversely proportional to one another.\n\nNow let's compute the inverse DFT on the transformed images to check the correctness of our code:\n\n\n```python\n#For visualization:\nN = len(dftImges)\nfig, axarr = plt.subplots(2, 2, figsize=(10,7))\n\n#Compute the inverse DFT for only the first two transformed images...\nfor i, dftImge in enumerate(dftImges[:2]):\n \n #Compute the inverse DFT and take the real part\n imge = np.real(DFT.computeInverse2DDFTWithSeparability(dftImge))\n \n #Due to the floating point precision, we can get very small decimal points,\n #So let's round them to the nearest integer.\n imge = np.round(imge)\n \n #Since the images were originally centered, let's decenter them now\n imge = DFT.computeCenteredImage(imge)\n \n #Display the dft and the resulting images found with inverse DFT:\n dftNormImge = DFT.normalize2DDFTByLog(dftImge)\n axarr[i][0].imshow(dftNormImge, cmap=plt.get_cmap('gray'))\n axarr[i][0].set_title('Centered DFT Image')\n \n axarr[i][1].imshow(imge, cmap=plt.get_cmap('gray'))\n axarr[i][1].set_title('Original Image')\n\n#fig.suptitle(\"The original 64x64 images found by applying inverse DFT\", fontsize=14)\n#fig.subplots_adjust(top=1.55)\n\nplt.show()\n```\n\n### Computing and Visualizing the DFT Running Time\n\nIn this part, we will compute and visualize the running time of DFT for different image sizes.\n\nFirst, the images with different sizes are generated:\n\n\n```python\ndef generateImages(imgSizes=[128, 64, 32, 16, 8]): \n\n #Create an empty list of images to save the generated images with different sizes.\n images = []\n\n #Generate the first and biggest image\n imge = generateBlackAndWhiteSquareImage(imgSizes[0])\n\n #Add to the images list\n images.append(imge)\n\n #Generate the resized and smaller images with different sizes.\n for i in range(1, len(imgSizes)):\n size = imgSizes[i]\n images.append(resizeImage(imge, size))\n \n return images\n```\n\nNext, the DFT algorithm will be run for all the generated images with different sizes. In addition, the running time will also be saved.\n\n\n```python\n#Generate images\nimgSizes = [128, 64, 32, 16, 8]\nimages = generateImages(imgSizes)\n\n# A list that stores the running time of the DFT algorithm for images with different size.\nrunningTimeDFT = []\n\n#For each image...\nfor i, imge in enumerate(images):\n \n #Compute the image size\n N = imge.shape[0]\n \n print \"Computing for \", N, \"x\", N, \"image...\"\n \n #Step 1: Center the image\n centeredImge = DFT.computeCenteredImage(imge)\n\n #Save the starting time.\n startTime = time.time()\n\n #Step 2: Compute the DFT of the image using the matrix multiplication form. \n dftImge = DFT.computeForward2DDFTNoSeparability(centeredImge)\n \n #Save the running time\n runningTimeDFT.append((time.time() - startTime)/60.00)\n```\n\n Computing for 128 x 128 image...\n Computing for 64 x 64 image...\n Computing for 32 x 32 image...\n Computing for 16 x 16 image...\n Computing for 8 x 8 image...\n\n\nSave the running time to file:\n\n\n```python\nresult = zip(imgSizes, runningTimeDFT)\nnp.savetxt(\"RunningTimes/runningTimeDFT.csv\", np.array(result), delimiter=',')\n```\n\n\n```python\n#Plot the running times\nplt.plot(xrange(len(runningTimeDFT)), runningTimeDFT, '-d')\n\nxlabels = [str(imge.shape[0]) + 'x' + str(imge.shape[0]) for imge in images]\nplt.xticks(xrange(len(runningTimeDFT)), xlabels)\nplt.xlabel(\"Image Size(Pixels)\")\nplt.ylabel(\"Time(Minutes)\")\nplt.show()\n```\n\n## Conclusion\n\nIn this post, we have implemented Discrete Fourier Transform (forward and reverse) from scratch. Then, we applied it to 2D images. \n", "meta": {"hexsha": "1a6240d91a0fa6f3211510e418c4607551fe0594", "size": 192518, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Notebooks_Teoricos/Image-Processing-Operations/01-Implementing-Discrete-Fourier-Transform-Using-Python.ipynb", "max_stars_repo_name": "lucas-althoff/PDI-UnB", "max_stars_repo_head_hexsha": "eae5de886739807bd7f66d5cb9dbe7b541efa4ff", "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_Teoricos/Image-Processing-Operations/01-Implementing-Discrete-Fourier-Transform-Using-Python.ipynb", "max_issues_repo_name": "lucas-althoff/PDI-UnB", "max_issues_repo_head_hexsha": "eae5de886739807bd7f66d5cb9dbe7b541efa4ff", "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_Teoricos/Image-Processing-Operations/01-Implementing-Discrete-Fourier-Transform-Using-Python.ipynb", "max_forks_repo_name": "lucas-althoff/PDI-UnB", "max_forks_repo_head_hexsha": "eae5de886739807bd7f66d5cb9dbe7b541efa4ff", "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": 181.4495758718, "max_line_length": 113784, "alphanum_fraction": 0.8728170872, "converted": true, "num_tokens": 6005, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897558991953, "lm_q2_score": 0.9343951657380187, "lm_q1q2_score": 0.8790693998880588}} {"text": "```python\n#derivative (slope at given point)\n\nfrom sympy import *\nimport numpy as np\n```\n\n\n```python\nx,y,z = sym.symbols('x y z')\n```\n\n\n```python\n# single variable ftns\nsym.diff(x**3)\n```\n\n\n\n\n$\\displaystyle 3 x^{2}$\n\n\n\n\n```python\n# product rule (use cos from sympy lib)\nsym.diff((x**3 + 18) * sym.cos(x))\n```\n\n\n\n\n$\\displaystyle 3 x^{2} \\cos{\\left(x \\right)} - \\left(x^{3} + 18\\right) \\sin{\\left(x \\right)}$\n\n\n\n\n```python\n#chain rule (der = der of an outer ftn * inner ftn, then multipled by der of inner ftn.)\nsym.diff((x**2 - 3*x +5)**3)\n```\n\n\n\n\n$\\displaystyle \\left(6 x - 9\\right) \\left(x^{2} - 3 x + 5\\right)^{2}$\n\n\n\n\n```python\n# multi-variable partial derivative for x\nsym.diff(x**3 * y, x)\n```\n\n\n\n\n$\\displaystyle 3 x^{2} y$\n\n\n\n\n```python\n# multi-variable partial derivative for y\nsym.diff(x**3 * y, y)\n```\n\n\n\n\n$\\displaystyle x^{3}$\n\n\n\n\n```python\n# set ftn to variable\nf = x**3 * y * z**2\n```\n\n\n```python\nsym.diff(f, z)\n```\n\n\n\n\n$\\displaystyle 2 x^{3} y z$\n\n\n\n\n```python\n# der of sigmoid ftn\nsym.diff(1/1 + sym.exp(-x))\n```\n\n\n\n\n$\\displaystyle - e^{- x}$\n\n\n\n\n```python\nsym.integrate(sym.exp(-x), (x, 0, sym.oo))\n```\n\n\n\n\n$\\displaystyle 1$\n\n\n\n\n```python\nintegrate(exp(-x), (x,0, oo))\n```\n\n\n\n\n$\\displaystyle 1$\n\n\n\n\n```python\n\n#sigmoid for binary classification\nimport matplotlib.pyplot as plt\nimport numpy as np\n\ndef sigmoid(x):\n s=1/(1+np.exp(-x))\n ds=s*(1-s) \n return s,ds\nx=np.arange(-6,6,0.01)\nsigmoid(x)\n# Setup centered axes\nfig, ax = plt.subplots(figsize=(9, 5))\nax.spines['left'].set_position('center')\nax.spines['right'].set_color('none')\nax.spines['top'].set_color('none')\nax.xaxis.set_ticks_position('bottom')\nax.yaxis.set_ticks_position('left')\n# Create and show plot\nax.plot(x,sigmoid(x)[0], color=\"#307EC7\", linewidth=3, label=\"sigmoid\")\nax.plot(x,sigmoid(x)[1], color=\"#9621E2\", linewidth=1, label=\"derivative\")\nax.legend(loc=\"upper right\", frameon=False)\nfig.show()\n```\n\n\n```python\n#> sigmoid, easier optmization, values -1 to 1, centers to zero?, suffers from vanishing gradient problem\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\ndef tanh(x):\n t=(np.exp(x)-np.exp(-x))/(np.exp(x)+np.exp(-x))\n dt=1-t**2\n return t,dt\nz=np.arange(-4,4,0.01)\ntanh(z)[0].size,tanh(z)[1].size\n# Setup centered axes\nfig, ax = plt.subplots(figsize=(9, 5))\nax.spines['left'].set_position('center')\nax.spines['bottom'].set_position('center')\nax.spines['right'].set_color('none')\nax.spines['top'].set_color('none')\nax.xaxis.set_ticks_position('bottom')\nax.yaxis.set_ticks_position('left')\n# Create and show plot\nax.plot(z,tanh(z)[0], color=\"#307EC7\", linewidth=3, label=\"tanh\")\nax.plot(z,tanh(z)[1], color=\"#9621E2\", linewidth=1, label=\"derivative\")\nax.legend(loc=\"upper right\", frameon=False)\nfig.show()\n```\n\n\n```python\n# ReLu, less comp espensive than tanh and sigmoid, avoid vanishing gradient, should only be used in hidden layers of NN model, can result in dead neurons.\n```\n", "meta": {"hexsha": "845648024ab8173fd70711bb276b844b432e0ce7", "size": 119561, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "derivatives.ipynb", "max_stars_repo_name": "masonkadem/mathfunctions", "max_stars_repo_head_hexsha": "7733880da524be712ba8bac0632b2ca00557f387", "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": "derivatives.ipynb", "max_issues_repo_name": "masonkadem/mathfunctions", "max_issues_repo_head_hexsha": "7733880da524be712ba8bac0632b2ca00557f387", "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": "derivatives.ipynb", "max_forks_repo_name": "masonkadem/mathfunctions", "max_forks_repo_head_hexsha": "7733880da524be712ba8bac0632b2ca00557f387", "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": 305.0025510204, "max_line_length": 60212, "alphanum_fraction": 0.9326285327, "converted": true, "num_tokens": 925, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9621075733703927, "lm_q2_score": 0.9136765204755286, "lm_q1q2_score": 0.8790550999602147}} {"text": "Suppose $x_1, ... x_n \\sim IG(\\mu, \\lambda)$ with density:\n\n$$\np(x) = \\bigg(\\frac{\\lambda}{2 \\pi x^3} \\bigg)^{1/2} \\exp \\bigg[- \\frac{\\lambda}{2 \\mu^2} \\frac{(x - \\mu)^2}{x} \\bigg]\n$$\n\nthen, ignoring irrelevant terms the log-likelihood, is given by:\n\n$$\nlog L(\\mu, \\lambda) = \\frac{n}{2} \\log \\lambda - \\frac{\\lambda}{2 \\mu^2} \\sum_{i=1}^{n} \\frac{(x_i - \\mu)^2}{x_i}\n$$\n\n(a) The score equations for the MLE are given by:\n\n$$\n\\begin{align}\n\\frac{\\partial}{\\partial \\mu} \\log L(\\mu, \\lambda) & = \\frac{\\lambda}{\\mu^3} \\sum_{i=1}^{n} \\frac{(x_i - \\mu)^2}{x_i} + \\frac{\\lambda} {\\mu^2} \\sum_{i=1}^{n} \\frac{(x_i - \\mu)}{x_i} \\\\\n& = \\frac{\\lambda}{\\mu^3} \\sum_{i=1}^{n} \\frac{(x_i - \\mu)^2}{x_i} \\bigg[1 + \\frac{\\mu}{(x_i - \\mu)} \\bigg] \\\\\n& = \\frac{\\lambda}{\\mu^3} \\bigg[ \\sum_{i=1}^{n} x_i - n \\mu \\bigg] \\\\\n& = \\frac{n \\lambda}{\\mu^3}[\\bar{x} - \\mu] = 0\n\\end{align}\n$$\nand\n$$\n\\frac{\\partial}{\\partial \\lambda} \\log L(\\mu, \\lambda) = \\frac{n}{2 \\lambda} - \\frac{1}{2 \\mu^2} \\sum_{i=1}^{n} \\frac{(x_i - \\mu)^2}{x_i} = 0\n$$\n\nThe MLEs are the solutions to the above equations and are given by:\n\n$$\n\\hat{\\mu} = \\bar{x}\n$$\n\nand \n\n$$\n\\begin{align}\n0 & = \\frac{n}{2 \\hat{\\lambda}} - \\frac{1}{2 \\bar{x}^2} \\sum_{i=1}^n \\frac{(x_i - \\bar{x})^2}{x_i} \\\\\n& = \\frac{n}{2 \\hat{\\lambda}} - \\frac{1}{2 \\bar{x}^2} \\sum_{i=1}^n \\bigg( x_i - 2 \\bar{x} + \\frac{\\bar{x}^2}{x_i} \\bigg) \\\\\n& = \\frac{n}{2 \\hat{\\lambda}} - \\frac{1}{2 \\bar{x}^2} \\bigg( n \\bar{x} - 2n \\bar{x} + \\bar{x}^2 \\sum_{i=1}^n \\frac{1}{x_i} \\bigg) \\\\\n& = \\frac{n}{2 \\hat{\\lambda}} - \\frac{n}{2} \\bigg( \\frac{1}{n} \\sum_{i=1}^n \\frac{1}{x_i} - \\frac{1}{\\bar{x}} \\bigg) \\\\\n& = \\frac{n}{2} \\bigg[ \\frac{1}{\\hat{\\lambda}} - \\bigg( \\frac{1}{n} \\sum_{i=1}^n \\frac{1}{x_i} - \\frac{1}{\\bar{x}} \\bigg) \\bigg]\n\\end{align}\n$$\n\nSo:\n$$\n\\hat{\\lambda} = \\bigg( \\frac{1}{\\tilde{x}} - \\frac{1}{\\bar{x}} \\bigg)^{-1}\n$$\n\nwhere the harmonic sample mean is given by:\n\n$$\n\\tilde{x} = \\frac{n}{\\sum_{i=1}^n \\frac{1}{x_i}}\n$$\n\n(b) The off-diagonal elements of the Fisher information matrix are given by:\n\n$$\n- \\frac{\\partial^2}{\\partial \\lambda \\partial \\mu} \\log L(\\mu, \\lambda) \\bigg|_{\\mu = \\hat{\\mu}, \\lambda = \\hat{\\lambda}} = \\frac{\\partial^2}{ \\partial \\mu \\partial \\lambda} \\log L(\\mu, \\lambda) \\bigg|_{\\mu = \\hat{\\mu}, \\lambda = \\hat{\\lambda}} = 0\n$$\n\nThe diagonal elements are given by:\n\n$$\n- \\frac{\\partial^2}{\\partial \\mu^2} \\log L(\\mu, \\lambda) \\bigg|_{\\mu = \\hat{\\mu}, \\lambda = \\hat{\\lambda}} = \\frac{n \\hat{\\lambda}}{\\bar{x}^3}\n$$\n\nand\n\n$$\n- \\frac{\\partial^2}{\\partial \\lambda^2} \\log L(\\mu, \\lambda) \\bigg|_{\\mu = \\hat{\\mu}, \\lambda = \\hat{\\lambda}} = \\frac{n}{\\hat{\\lambda}^2}\n$$\n", "meta": {"hexsha": "59a0e43b943555b954ff2e82b359fd5fb003e190", "size": 4159, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "python/chapter-3/exercises/EX3-11.ipynb", "max_stars_repo_name": "covuworie/in-all-likelihood", "max_stars_repo_head_hexsha": "6638bec8bb4dde7271adb5941d1c66e7fbe12526", "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/chapter-3/exercises/EX3-11.ipynb", "max_issues_repo_name": "covuworie/in-all-likelihood", "max_issues_repo_head_hexsha": "6638bec8bb4dde7271adb5941d1c66e7fbe12526", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-03-24T17:53:04.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-23T20:16:17.000Z", "max_forks_repo_path": "python/chapter-3/exercises/EX3-11.ipynb", "max_forks_repo_name": "covuworie/in-all-likelihood", "max_forks_repo_head_hexsha": "6638bec8bb4dde7271adb5941d1c66e7fbe12526", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-11-21T10:24:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-21T10:24:59.000Z", "avg_line_length": 36.1652173913, "max_line_length": 289, "alphanum_fraction": 0.4416927146, "converted": true, "num_tokens": 1179, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9790357561234475, "lm_q2_score": 0.8976952996340947, "lm_q1q2_score": 0.8788757964457307}} {"text": "# Modeling and Simulation in Python\n\nChapter 9\n\nCopyright 2017 Allen Downey\n\nLicense: [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0)\n\n\n\n```python\n# Configure Jupyter to display the assigned value after an assignment\n%config InteractiveShell.ast_node_interactivity='last_expr_or_assign'\n\n# import everything from SymPy.\nfrom sympy import *\n\n# Set up Jupyter notebook to display math.\ninit_printing() \n```\n\nThe following displays SymPy expressions and provides the option of showing results in LaTeX format.\n\n\n```python\nfrom sympy.printing import latex\n\ndef show(expr, show_latex=False):\n \"\"\"Display a SymPy expression.\n \n expr: SymPy expression\n show_latex: boolean\n \"\"\"\n if show_latex:\n print(latex(expr))\n return expr\n```\n\n### Analysis with SymPy\n\nCreate a symbol for time.\n\n\n```python\nt = symbols('t')\n```\n\nIf you combine symbols and numbers, you get symbolic expressions.\n\n\n```python\nexpr = t + 1\n```\n\nThe result is an `Add` object, which just represents the sum without trying to compute it.\n\n\n```python\ntype(expr)\n```\n\n`subs` can be used to replace a symbol with a number, which allows the addition to proceed.\n\n\n```python\nexpr.subs(t, 2)\n```\n\n`f` is a special class of symbol that represents a function.\n\n\n```python\nf = Function('f')\n```\n\nThe type of `f` is `UndefinedFunction`\n\n\n```python\ntype(f)\n```\n\nSymPy understands that `f(t)` means `f` evaluated at `t`, but it doesn't try to evaluate it yet.\n\n\n```python\nf(t)\n```\n\n`diff` returns a `Derivative` object that represents the time derivative of `f`\n\n\n```python\ndfdt = diff(f(t), t)\n```\n\n\n```python\ntype(dfdt)\n```\n\nWe need a symbol for `alpha`\n\n\n```python\nalpha = symbols('alpha')\n```\n\nNow we can write the differential equation for proportional growth.\n\n\n```python\neq1 = Eq(dfdt, alpha*f(t))\n```\n\nAnd use `dsolve` to solve it. The result is the general solution.\n\n\n```python\nsolution_eq = dsolve(eq1)\n```\n\nWe can tell it's a general solution because it contains an unspecified constant, `C1`.\n\nIn this example, finding the particular solution is easy: we just replace `C1` with `p_0`\n\n\n```python\nC1, p_0 = symbols('C1 p_0')\n```\n\n\n```python\nparticular = solution_eq.subs(C1, p_0)\n```\n\nIn the next example, we have to work a little harder to find the particular solution.\n\n### Solving the quadratic growth equation \n\nWe'll use the (r, K) parameterization, so we'll need two more symbols:\n\n\n```python\nr, K = symbols('r K')\n```\n\nNow we can write the differential equation.\n\n\n```python\neq2 = Eq(diff(f(t), t), r * f(t) * (1 - f(t)/K))\n```\n\nAnd solve it.\n\n\n```python\nsolution_eq = dsolve(eq2)\n```\n\nThe result, `solution_eq`, contains `rhs`, which is the right-hand side of the solution.\n\n\n```python\ngeneral = solution_eq.rhs\n```\n\nWe can evaluate the right-hand side at $t=0$\n\n\n```python\nat_0 = general.subs(t, 0)\n```\n\nNow we want to find the value of `C1` that makes `f(0) = p_0`.\n\nSo we'll create the equation `at_0 = p_0` and solve for `C1`. Because this is just an algebraic identity, not a differential equation, we use `solve`, not `dsolve`.\n\nThe result from `solve` is a list of solutions. In this case, [we have reason to expect only one solution](https://en.wikipedia.org/wiki/Picard%E2%80%93Lindel%C3%B6f_theorem), but we still get a list, so we have to use the bracket operator, `[0]`, to select the first one.\n\n\n```python\nsolutions = solve(Eq(at_0, p_0), C1)\ntype(solutions), len(solutions)\n```\n\n\n```python\nvalue_of_C1 = solutions[0]\n```\n\nNow in the general solution, we want to replace `C1` with the value of `C1` we just figured out.\n\n\n```python\nparticular = general.subs(C1, value_of_C1)\n```\n\nThe result is complicated, but SymPy provides a method that tries to simplify it.\n\n\n```python\nparticular = simplify(particular)\n```\n\nOften simplicity is in the eye of the beholder, but that's about as simple as this expression gets.\n\nJust to double-check, we can evaluate it at `t=0` and confirm that we get `p_0`\n\n\n```python\nparticular.subs(t, 0)\n```\n\nThis solution is called the [logistic function](https://en.wikipedia.org/wiki/Population_growth#Logistic_equation).\n\nIn some places you'll see it written in a different form:\n\n$f(t) = \\frac{K}{1 + A e^{-rt}}$\n\nwhere $A = (K - p_0) / p_0$.\n\nWe can use SymPy to confirm that these two forms are equivalent. First we represent the alternative version of the logistic function:\n\n\n```python\nA = (K - p_0) / p_0\n```\n\n\n```python\nlogistic = K / (1 + A * exp(-r*t))\n```\n\nTo see whether two expressions are equivalent, we can check whether their difference simplifies to 0.\n\n\n```python\nsimplify(particular - logistic)\n```\n\nThis test only works one way: if SymPy says the difference reduces to 0, the expressions are definitely equivalent (and not just numerically close).\n\nBut if SymPy can't find a way to simplify the result to 0, that doesn't necessarily mean there isn't one. Testing whether two expressions are equivalent is a surprisingly hard problem; in fact, there is no algorithm that can solve it in general.\n\n### Exercises\n\n**Exercise:** Solve the quadratic growth equation using the alternative parameterization\n\n$\\frac{df(t)}{dt} = \\alpha f(t) + \\beta f^2(t) $\n\n\n```python\n# Solution goes here\n```\n\n\n```python\n# Solution goes here\n```\n\n\n```python\n# Solution goes here\n```\n\n\n```python\n# Solution goes here\n```\n\n\n```python\n# Solution goes here\n```\n\n\n```python\n# Solution goes here\n```\n\n\n```python\n# Solution goes here\n```\n\n**Exercise:** Use [WolframAlpha](https://www.wolframalpha.com/) to solve the quadratic growth model, using either or both forms of parameterization:\n\n df(t) / dt = alpha f(t) + beta f(t)^2\n\nor\n\n df(t) / dt = r f(t) (1 - f(t)/K)\n\nFind the general solution and also the particular solution where `f(0) = p_0`.\n\n\n```python\n\n```\n", "meta": {"hexsha": "ce3e1c0ac987073deb015dbfe1ba33298ece2c7e", "size": 13169, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "code/chap09sympy.ipynb", "max_stars_repo_name": "hkRho/ModSimPy", "max_stars_repo_head_hexsha": "099c2759010dbc11ff4d80ee379ba4add56e0eae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-04-27T22:43:12.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-11T15:12:23.000Z", "max_issues_repo_path": "notebooks/chap09sympy.ipynb", "max_issues_repo_name": "ffriass/ModSimPy", "max_issues_repo_head_hexsha": "c36a476a20042acb33773e47d12aea5b0c413e60", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 33, "max_issues_repo_issues_event_min_datetime": "2019-10-09T18:50:22.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-21T01:39:48.000Z", "max_forks_repo_path": "notebooks/chap09sympy.ipynb", "max_forks_repo_name": "ffriass/ModSimPy", "max_forks_repo_head_hexsha": "c36a476a20042acb33773e47d12aea5b0c413e60", "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": 20.804107425, "max_line_length": 279, "alphanum_fraction": 0.5284379983, "converted": true, "num_tokens": 1552, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.972830765707344, "lm_q2_score": 0.9032942080055512, "lm_q1q2_score": 0.8787523960330491}} {"text": "Taylor Series Expansion with Python from Data Science Fabric\n\nhttps://dsfabric.org/taylor-series-expansion-with-python\n\n# LAB 9 Taylor Series\n\n**Universidad Naional de Colombia - Sede Bogotá**\n\n**Metodos Numericos**\n\n**Docente:** _German Hernandez_\n\n**Estudiante:**\n * Luis Miguel Báez Aponte - lmbaeza@unal.edu.co\n\n\n```python\n\nfrom sympy import series, Symbol\nfrom sympy.functions import sin, cos, exp, log\nfrom sympy.plotting import plot\nimport numpy as np\nimport matplotlib.pyplot as plt\n```\n\n\n```python\n# Define symbol\nx = Symbol('x')\n```\n\n\n```python\n\n# Function for Taylor Series Expansion\n\ndef taylor(function, x0, n):\n \"\"\"\n Parameter \"function\" is our function which we want to approximate\n \"x0\" is the point where to approximate\n \"n\" is the order of approximation\n \"\"\"\n return function.series(x,x0,n).removeO()\n```\n\n\n```python\nprint('sin(x) ≅', taylor(sin(x), 0, 4))\n\nprint('ln(x+1) ≅', taylor(log(x+1), 0, 4))\n\n```\n\n sin(x) ≅ -x**3/6 + x\n ln(x+1) ≅ x**3/3 - x**2/2 + x\n\n\n\n```python\nprint('sin(1) =', taylor(sin(x), 0, 4).subs(x,1))\n\nprint('ln(1+1) =', taylor(log(x+1), 0, 4).subs(x,1))\n\n```\n\n sin(1) = 5/6\n ln(1+1) = 5/6\n\n\n\n```python\nprint('Taylor 0 sin(x) ≅', taylor(sin(x), 0, 0))\nprint('Taylor 1 sin(x) ≅', taylor(sin(x), 0, 1))\nprint('Taylor 2 sin(x) ≅', taylor(sin(x), 0, 2))\nprint('Taylor 3 sin(x) ≅', taylor(sin(x), 0, 3))\nprint('Taylor 4 sin(x) ≅', taylor(sin(x), 0, 4))\nprint('Taylor 5 sin(x) ≅', taylor(sin(x), 0, 5))\nprint('Taylor 6 sin(x) ≅', taylor(sin(x), 0, 6))\nprint('Taylor 7 sin(x) ≅', taylor(sin(x), 0, 7))\nprint('Taylor 8 sin(x) ≅', taylor(sin(x), 0, 8))\n```\n\n Taylor 0 sin(x) ≅ 0\n Taylor 1 sin(x) ≅ 0\n Taylor 2 sin(x) ≅ x\n Taylor 3 sin(x) ≅ x\n Taylor 4 sin(x) ≅ -x**3/6 + x\n Taylor 5 sin(x) ≅ -x**3/6 + x\n Taylor 6 sin(x) ≅ x**5/120 - x**3/6 + x\n Taylor 7 sin(x) ≅ x**5/120 - x**3/6 + x\n Taylor 8 sin(x) ≅ -x**7/5040 + x**5/120 - x**3/6 + x\n\n\n\n```python\nprint('Taylor 0 ln(x+1) ≅', taylor(log(x+1), 0, 0).subs(x,2),' = ',taylor(log(x+1), 0, 0).subs(x,2).evalf())\nprint('Taylor 1 ln(x+1) ≅', taylor(log(x+1), 0, 1).subs(x,2),' = ',taylor(log(x+1), 0, 1).subs(x,2).evalf())\nprint('Taylor 2 ln(x+1) ≅', taylor(log(x+1), 0, 2).subs(x,2),' = ',taylor(log(x+1), 0, 2).subs(x,2).evalf())\nprint('Taylor 3 ln(x+1) ≅', taylor(log(x+1), 0, 3).subs(x,2),' = ',taylor(log(x+1), 0, 3).subs(x,2).evalf())\nprint('Taylor 4 ln(x+1) ≅', taylor(log(x+1), 0, 4).subs(x,2),' = ',taylor(log(x+1), 0, 4).subs(x,2).evalf())\nprint('Taylor 5 ln(x+1) ≅', taylor(log(x+1), 0, 5).subs(x,2),' = ',taylor(log(x+1), 0, 5).subs(x,2).evalf())\nprint('Taylor 6 ln(x+1) ≅', taylor(log(x+1), 0, 6).subs(x,2),' = ',taylor(log(x+1), 0, 6).subs(x,2).evalf())\nprint('Taylor 7 ln(x+1) ≅', taylor(log(x+1), 0, 8).subs(x,2),' = ',taylor(log(x+1), 0, 7).subs(x,2).evalf())\n```\n\n Taylor 0 ln(x+1) ≅ 0 = 0\n Taylor 1 ln(x+1) ≅ 0 = 0\n Taylor 2 ln(x+1) ≅ 2 = 2.00000000000000\n Taylor 3 ln(x+1) ≅ 0 = 0\n Taylor 4 ln(x+1) ≅ 8/3 = 2.66666666666667\n Taylor 5 ln(x+1) ≅ -4/3 = -1.33333333333333\n Taylor 6 ln(x+1) ≅ 76/15 = 5.06666666666667\n Taylor 7 ln(x+1) ≅ 444/35 = -5.60000000000000\n\n\n\n```python\nimport math\nprint('sympy sin(x)subs(x,2) =', sin(x).subs(x,2))\nprint('sympy sin(x).subs(x,2).evalf() =', sin(x).subs(x,2).evalf())\nprint('math.sin(2) =', math.sin(2))\n```\n\n sympy sin(x)subs(x,2) = sin(2)\n sympy sin(x).subs(x,2).evalf() = 0.909297426825682\n math.sin(2) = 0.9092974268256817\n\n\n\n```python\nimport math\nprint('sympy ln(x+1)subs(x,2) =', log(x+1).subs(x,2))\nprint('sympy ln(x+1).subs(x,2).evalf() =', log(x+1).subs(x,2).evalf())\nprint('math.ln(2+1) =', math.log(2+1))\n```\n\n sympy ln(x+1)subs(x,2) = log(3)\n sympy ln(x+1).subs(x,2).evalf() = 1.09861228866811\n math.ln(2+1) = 1.0986122886681098\n\n\n\n```python\nimport math\nimport numpy as np\nimport matplotlib.pyplot as plt\n# if using a Jupyter notebook, include:\n%matplotlib inline\n\nvalues = np.arange(-5,5,0.1)\np_exp = np.exp(values)\nt_exp1 = [taylor(exp(x), 0, 1).subs(x,v) for v in values]\nlegends = ['exp() ','Taylor 1 (constant)']\n\nfig, ax = plt.subplots()\nax.plot(values,p_exp, color ='red')\nax.plot(values,t_exp1)\n\nax.set_ylim([-5,5])\nax.axhline(y=0.0, xmin=-5.0, xmax=5.0, color='black')\nax.axvline(x=0.0, ymin=-10.0, ymax=10.0, color='black')\nax.legend(legends)\n\nplt.show()\n```\n\n\n```python\nimport math\nimport numpy as np\nimport matplotlib.pyplot as plt\n# if using a Jupyter notebook, include:\n%matplotlib inline\n\nvalues = np.arange(-5,5,0.1)\np_sin = np.sin(values)\nt_sin2 = [taylor(sin(x), 0, 2).subs(x,v) for v in values]\nlegends = ['sin() ','Taylor 2 (linear)']\n\nfig, ax = plt.subplots()\nax.plot(values,p_sin, color ='red')\nax.plot(values,t_sin2)\n\nax.set_ylim([-5,5])\nax.axhline(y=0.0, xmin=-5.0, xmax=5.0, color='black')\nax.axvline(x=0.0, ymin=-10.0, ymax=10.0, color='black')\nax.legend(legends)\n\nplt.show()\n```\n\n\n```python\nimport math\nimport numpy as np\nimport matplotlib.pyplot as plt\n# if using a Jupyter notebook, include:\n%matplotlib inline\n\nvalues = np.arange(-5,5,0.1)\np_log = np.log(values)\nt_log2 = [taylor(log(x+1), 0, 2).subs(x,v) for v in values]\nlegends = ['ln(x+1) ','Taylor 2 (linear)']\n\nfig, ax = plt.subplots()\nax.plot(values,p_log, color ='red')\nax.plot(values,t_log2)\n\nax.set_ylim([-5,5])\nax.axhline(y=0.0, xmin=-5.0, xmax=5.0, color='black')\nax.axvline(x=0.0, ymin=-10.0, ymax=10.0, color='black')\nax.legend(legends)\n\nplt.show()\n```\n\n\n```python\nimport math\nimport numpy as np\nimport matplotlib.pyplot as plt\n# if using a Jupyter notebook, include:\n%matplotlib inline\n\nvalues = np.arange(-5,5,0.1)\np_sin = np.sin(values)\nt_sin3 = [taylor(sin(x), 0, 3).subs(x,v) for v in values]\nlegends = ['sin(x) ','Taylor 3 (quadratic)']\n\nfig, ax = plt.subplots()\nax.plot(values,p_sin, color ='red')\nax.plot(values,t_sin3)\n\nax.set_ylim([-5,5])\nax.axhline(y=0.0, xmin=-5.0, xmax=5.0, color='black')\nax.axvline(x=0.0, ymin=-10.0, ymax=10.0, color='black')\nax.legend(legends)\n\nplt.show()\n```\n\n\n```python\nimport math\nimport numpy as np\nimport matplotlib.pyplot as plt\n# if using a Jupyter notebook, include:\n%matplotlib inline\n\nvalues = np.arange(-5,5,0.1)\np_log = np.log(values)\nt_log3 = [taylor(log(x+1), 0, 3).subs(x,v) for v in values]\nlegends = ['log(x+1) ','Taylor 3 (quadratic)']\n\nfig, ax = plt.subplots()\nax.plot(values,p_log, color ='red')\nax.plot(values,t_log3)\n\nax.set_ylim([-5,5])\nax.axhline(y=0.0, xmin=-5.0, xmax=5.0, color='black')\nax.axvline(x=0.0, ymin=-10.0, ymax=10.0, color='black')\nax.legend(legends)\n\nplt.show()\n```\n\n\n```python\nimport math\nimport numpy as np\nimport matplotlib.pyplot as plt\n# if using a Jupyter notebook, include:\n%matplotlib inline\n\nvalues = np.arange(-5,5,0.1)\np_sin = np.sin(values)\nt_sin4 = [taylor(sin(x), 0, 4).subs(x,v) for v in values]\nlegends = ['sin(x) ','Taylor 4 (cubic)']\n\nfig, ax = plt.subplots()\nax.plot(values,p_sin, color ='red')\nax.plot(values,t_sin4)\n\nax.set_ylim([-5,5])\nax.axhline(y=0.0, xmin=-5.0, xmax=5.0, color='black')\nax.axvline(x=0.0, ymin=-10.0, ymax=10.0, color='black')\nax.legend(legends)\n\nplt.show()\n```\n\n\n```python\nimport math\nimport numpy as np\nimport matplotlib.pyplot as plt\n# if using a Jupyter notebook, include:\n%matplotlib inline\n\nvalues = np.arange(-5,5,0.1)\np_log = np.log(values)\nt_log4 = [taylor(log(x+1), 0, 4).subs(x,v) for v in values]\nlegends = ['ln(x+1) ','Taylor 4 (cubic)']\n\nfig, ax = plt.subplots()\nax.plot(values,p_log, color ='red')\nax.plot(values,t_log4)\n\nax.set_ylim([-5,5])\nax.axhline(y=0.0, xmin=-5.0, xmax=5.0, color='black')\nax.axvline(x=0.0, ymin=-10.0, ymax=10.0, color='black')\nax.legend(legends)\n\nplt.show()\n```\n\n\n```python\nimport math\nimport numpy as np\nimport matplotlib.pyplot as plt\n# if using a Jupyter notebook, include:\n%matplotlib inline\n\nvalues = np.arange(-5,5,0.1)\np_sin = np.sin(values)\nt_sin1 = [taylor(sin(x), 0, 1).subs(x,v) for v in values]\nt_sin2 = [taylor(sin(x), 0, 2).subs(x,v) for v in values]\nt_sin3 = [taylor(sin(x), 0, 3).subs(x,v) for v in values]\nt_sin4 = [taylor(sin(x), 0, 4).subs(x,v) for v in values]\nlegends = ['sin() ','Taylor 1 (constant)','Taylor 3 (linear)','Taylor 3 (quadratic)','Taylor 4 (cubic)']\n\nfig, ax = plt.subplots()\nax.plot(values,p_sin)\nax.plot(values,t_sin1)\nax.plot(values,t_sin2)\nax.plot(values,t_sin3)\nax.plot(values,t_sin4)\n\nax.set_ylim([-5,5])\nax.axhline(y=0.0, xmin=-5.0, xmax=5.0, color='black')\nax.axvline(x=0.0, ymin=-10.0, ymax=10.0, color='black')\nax.legend(legends)\n\nplt.show()\n```\n\n\n```python\nimport math\nimport numpy as np\nimport matplotlib.pyplot as plt\n# if using a Jupyter notebook, include:\n%matplotlib inline\n\nvalues = np.arange(-5,5,0.1)\np_log = np.log(values)\nt_log1 = [taylor(log(x+1), 0, 1).subs(x,v) for v in values]\nt_log2 = [taylor(log(x+1), 0, 2).subs(x,v) for v in values]\nt_log3 = [taylor(log(x+1), 0, 3).subs(x,v) for v in values]\nt_log4 = [taylor(log(x+1), 0, 4).subs(x,v) for v in values]\nlegends = ['ln(x+1) ','Taylor 1 (constant)','Taylor 3 (linear)','Taylor 3 (quadratic)','Taylor 4 (cubic)']\n\nfig, ax = plt.subplots()\nax.plot(values,p_log)\nax.plot(values,t_log1)\nax.plot(values,t_log2)\nax.plot(values,t_log3)\nax.plot(values,t_log4)\n\nax.set_ylim([-5,5])\nax.axhline(y=0.0, xmin=-5.0, xmax=5.0, color='black')\nax.axvline(x=0.0, ymin=-10.0, ymax=10.0, color='black')\nax.legend(legends)\n\nplt.show()\n```\n", "meta": {"hexsha": "0709fcf18ca1bbd32690ad4e574ff05a9993cf02", "size": 182779, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Lab09/lab9_lmbaeza_taylor_sympy_in_python.ipynb", "max_stars_repo_name": "lmbaeza/numerical-methods-2021", "max_stars_repo_head_hexsha": "9e3d1ec7039067cf2a33a10328b307e7a27479c7", "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": "Lab09/lab9_lmbaeza_taylor_sympy_in_python.ipynb", "max_issues_repo_name": "lmbaeza/numerical-methods-2021", "max_issues_repo_head_hexsha": "9e3d1ec7039067cf2a33a10328b307e7a27479c7", "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": "Lab09/lab9_lmbaeza_taylor_sympy_in_python.ipynb", "max_forks_repo_name": "lmbaeza/numerical-methods-2021", "max_forks_repo_head_hexsha": "9e3d1ec7039067cf2a33a10328b307e7a27479c7", "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": 235.8438709677, "max_line_length": 28466, "alphanum_fraction": 0.8991240788, "converted": true, "num_tokens": 3573, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475762847495, "lm_q2_score": 0.9314625022115511, "lm_q1q2_score": 0.8786928938613949}} {"text": "# EM\n\nEM algorithm applies to a large faimily of estimation problems with latent variables, e.g GMM.\n\nSuppose we have a training set $\\{x^{(1)},...,x^{(n)}\\}$ with $z$ being the latent variable, by marginal probabilities:\n\n$$p(x;\\theta) = \\sum_{z}p(x, z; \\theta)$$\n\nWe wish to fit the parameters $\\theta$ by maximizing the log-likelihood of the data:\n\n$$\n\\begin{equation}\n\\begin{split}\nl(\\theta) =& \\sum_{i=1}^{n}\\log{p(x^{(i)};\\theta)} \\\\\n=& \\sum_{i=1}^{n}\\log\\sum_{z^{(i)}}p(x^{(i)}, z^{(i)}; \\theta)\n\\end{split}\n\\end{equation}\n$$\n\nMaximizing $l(\\theta)$ directly might be difficult. \n\nOur strategy will be to instead repeatedly construct a lower-bound on $l$ (E-step), and then optimize that lower-bound (M-step).\n\n## Lower Bound\n\nLet $Q$ be a distribution over $z$, then:\n\n$$\n\\begin{equation}\n\\begin{split}\n\\log{p(x;\\theta)} =& \\log\\sum_{z}p(x,z;\\theta)\\\\\n=& \\log\\sum_{z}Q(z)\\frac{p(x,z;\\theta)}{Q(z)}\\\\\n\\ge& \\sum_{z}Q(z)\\log{\\frac{p(x,z;\\theta)}{Q(z)}}\\quad\\mbox{(log is concave)}\n\\end{split}\n\\end{equation}\n$$\n\nWe call this bound the *evidence lower bound(ELBO)* and denote it by:\n\n$$\\mbox{ELBO}(x;Q,\\theta) = \\sum_{z}Q(z)\\log\\frac{p(x,z;\\theta)}{Q(z)}$$\n\nTo hold with equality, it is sufficient that:\n\n$$\\frac{p(x,z;\\theta)}{Q(z)} = c$$\n\nwhich is equivalent to:\n\n$$Q(z) = p(z|x;\\theta)$$\n\n## The EM Algorithm\n\nTaking all instances into account, for any distributions $Q_{1},...,Q_{n}$:\n\n$$\n\\begin{equation}\n\\begin{split}\nl(\\theta) \\ge& \\sum_{i}\\mbox{ELBO}(x^{(i)};Q_{i},\\theta)\\\\\n=& \\sum_{i}\\sum_{z^{(i)}}Q_{i}(z^{(i)})\\log\\frac{p(x^{(i)},z^{(i)};\\theta)}{Q_{i}(z^{(i)})}\n\\end{split}\n\\end{equation}\n$$\n\nequality holds when $Q_{i}$ equal to the posterior distribution in this setting of $\\theta$:\n\n$$\\mbox{E-step:}\\quad{Q_{i}{(z^{(i)})}} = p(z^{(i)}|x^{(i)};\\theta)$$\n\nM-step maximize the lower bound with respect to $\\theta$ while keeping $Q_{i}$ fixed.\n\n$$\n\\theta := \\underset{\\theta}{\\mbox{argmax}}\\sum_{i}\\mbox{ELBO}(x^{(i)};Q_{i},\\theta)\n$$\n\nEM algorithm ensures $l(\\theta^{(t)}) \\le l(\\theta^{(t+1)})$, thus ensures convergence.\n\n\n```python\n\n```\n", "meta": {"hexsha": "51b42d6f2d7cb873c930caaeb0f6a8e581985d0c", "size": 3537, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "machine-learning-book/d4.EM.ipynb", "max_stars_repo_name": "newfacade/jupyters", "max_stars_repo_head_hexsha": "12d3c8bf1b91a7fc2f84e89b5a55efa176f4da23", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-10T16:20:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-10T16:20:34.000Z", "max_issues_repo_path": "machine-learning-book/d4.EM.ipynb", "max_issues_repo_name": "newfacade/jupyters", "max_issues_repo_head_hexsha": "12d3c8bf1b91a7fc2f84e89b5a55efa176f4da23", "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-book/d4.EM.ipynb", "max_forks_repo_name": "newfacade/jupyters", "max_forks_repo_head_hexsha": "12d3c8bf1b91a7fc2f84e89b5a55efa176f4da23", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.9918032787, "max_line_length": 134, "alphanum_fraction": 0.4877014419, "converted": true, "num_tokens": 757, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.959154287592778, "lm_q2_score": 0.9161096090086367, "lm_q1q2_score": 0.8786904593855773}} {"text": "# Monte Carlo experiments\nThe Monte Carlo method is a way of using random numbers to solve problems that can otherwise be quite complicated. Essentially, the idea is to replace uncertain values with a large list of values, assume those values have no uncertaintly, and compute a large list of results. Analysis of the results can often lead you to the solution to the original problem.\n\nThe following story is based on the Dart method, described in the following book by Thijsse, J. M. (2006), Computational Physics, Cambridge University Press, p. 273, ISBN 978-0-521-57588-1\n\n### Approximating $\\pi$\n\nLet's use the Monte Carlo method to approximate $\\pi$. First, the area of a circle is $A = \\pi r^2,$\nso that the unit circle ($r=1$) has an area $A = \\pi$. Second, we define the square domain in which the unit circle just fits (2x2), and plot both:\n\n\n```python\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom scipy.stats import uniform\n\ndef circle():\n theta = np.linspace(0, 2*np.pi, num=1000)\n x = [np.cos(n) for n in theta]\n y = [np.sin(n) for n in theta]\n return x, y\n\ndef square():\n x = [-1,1,1,-1,-1]\n y = [-1,-1,1,1,-1]\n return x, y\n\nplt.plot(*circle(), 'k')\nplt.plot(*square(), 'k')\nplt.axis('equal')\nplt.show()\n```\n\nConsider a random point (x,y) inside the square.\n\n**The probability that a random point from a square domain lies inside the biggest circle that fits inside the square is equal to the area of the circle divided by the area of the square.** \n\nOur square is $2\\times 2=4$ and our circle has an area of $\\pi$, so if we pick many points, statistically, we expect $\\pi/4$ of them to fall inside the circle. \n\n### Our first few points\n\nLet's create a function that will give us random points from a uniform distribution inside the square domain, and generate a few random points.\n\n\n```python\nnp.random.seed(seed=345) # remove/change the seed if you want different random numbers\n\ndef monte_carlo(n):\n x = uniform.rvs(loc=-1, scale=2, size=n)\n y = uniform.rvs(loc=-1, scale=2, size=n)\n return x, y\n\nmc_x, mc_y = monte_carlo(28)\nplt.plot(*circle(), 'k')\nplt.plot(*square(), 'k')\nplt.scatter(mc_x, mc_y, c='green')\nplt.axis('equal')\nplt.show()\n```\n\nLet's colour the points depending on whether they are within 1 unit of the origin or not:\n\n\n```python\ndef dist(x, y):\n return np.sqrt(x**2 + y**2)\n\ndef inside(x, y):\n return dist(x, y) < 1\n\ndef outside(x, y):\n return dist(x, y) > 1\n\nnp.random.seed(seed=345) # remove the command or change the value if you want different random numbers\n\nx, y = monte_carlo(28)\nins = inside(x, y)\nouts = outside(x, y)\n\nplt.plot(*square(), 'k')\nplt.plot(*circle(), 'k')\nplt.scatter(x[ins], y[ins], c='blue',label=len(x[ins]))\nplt.scatter(x[outs], y[outs], c='red', label=len(x[outs]))\nplt.axis('equal')\nplt.legend()\nplt.show()\n```\n\nIf you left the np.random seed as 345, and generated 28 points, then your output should have 22 blue points (inside the circle) and 6 red points (outside the circle).\n\nSo, if 22 out of 28 (around 76%) of the points are inside the circle, we can approximate $\\pi$ from this.\n\n$$\n\\begin{align}\n\\pi \\approx 4(22/28) = 22/7 = 3.142857.\n\\end{align}\n$$\n\n$22/7$ is a common approximation of $\\pi$, and this seed value happens to get us to this ratio. If you vary the random seed, however, you will see that this ratio for only a small number of points can vary quite a lot!\n\nTo produce a more robust approximation for $\\pi$, we will need many more random points.\n\n### 250 points\n\n\n```python\nx, y = monte_carlo(250)\nins = inside(x, y)\nouts = outside(x, y)\npi = 4 * len(x[ins])/len(x)\n\nplt.plot(*square(), 'k')\nplt.scatter(x[ins], y[ins], c='blue', label=len(x[ins]))\nplt.scatter(x[outs], y[outs], c='red', label=len(x[outs]))\nplt.axis('equal')\nplt.legend()\nplt.title('π ≈ {}'.format(pi))\nplt.show()\n```\n\n### 1000 points\n\n\n```python\nx, y = monte_carlo(1000)\nins = inside(x, y)\nouts = outside(x, y)\npi = 4 * len(x[ins])/len(x)\n\nplt.plot(*square(), 'k')\nplt.scatter(x[ins], y[ins], c='blue', label=len(x[ins]))\nplt.scatter(x[outs], y[outs], c='red', label=len(x[outs]))\nplt.axis('equal')\nplt.legend()\nplt.title('π ≈ {}'.format(pi))\nplt.show()\n```\n\n## 25000 points\n\n\n```python\nx, y = monte_carlo(25000)\nins = inside(x, y)\nouts = outside(x, y)\npi = 4 * len(x[ins])/len(x)\n\nplt.plot(*square(), 'k')\nplt.scatter(x[ins], y[ins], c='blue', label=len(x[ins]))\nplt.scatter(x[outs], y[outs], c='red', label=len(x[outs]))\nplt.axis('equal')\nplt.legend()\nplt.title('π ≈ {}'.format(pi))\nplt.show()\n```\n\nWith many points, you should see a completely blue circle in an otherwise red square, **and** a decent estimate of $\\pi$.\n\n## The mcerp3 package\nThere is a Python package, `mcerp3`, which handles Monte Carlo calculations automatically. It was originally written by Abraham Lee and has recently been updated by Paul Freeman to support Python3. This package is available on [PyPI](https://pypi.org/project/mcerp3/). If you want to use in this notebook in the cloud, you will have to do an install (which can take a bit of time):\n\n\n```python\n#!pip install mcerp3 # or use conda install -y mcerp3 -c freemapa\n!conda install -y mcerp3 -c freemapa\nimport mcerp3 as mc\nfrom mcerp3.umath import sqrt\n```\n\n Fetching package metadata ...............\n Solving package specifications: .\n \n Package plan for installation in environment /home/nbuser/anaconda3_420:\n \n The following NEW packages will be INSTALLED:\n \n _libgcc_mutex: 0.1-main \n mcerp3: 1.0.3-py_0 freemapa\n readline: 7.0-ha6073c6_4 \n \n The following packages will be UPDATED:\n \n conda: 4.3.31-py35_0 --> 4.5.11-py35_0 \n conda-env: 2.6.0-h36134e3_1 --> 2.6.0-1 \n libgcc: 4.8.5-2 --> 7.2.0-h69d50b8_2 \n pycosat: 0.6.1-py35_1 --> 0.6.3-py35h6b6bb97_0\n \n _libgcc_mutex- 100% |################################| Time: 0:00:00 2.34 MB/s\n conda-env-2.6. 100% |################################| Time: 0:00:00 4.14 MB/s\n libgcc-7.2.0-h 100% |################################| Time: 0:00:00 18.35 MB/s\n readline-7.0-h 100% |################################| Time: 0:00:00 12.00 MB/s\n pycosat-0.6.3- 100% |################################| Time: 0:00:00 5.85 MB/s\n mcerp3-1.0.3-p 100% |################################| Time: 0:00:00 4.87 MB/s\n conda-4.5.11-p 100% |################################| Time: 0:00:00 13.23 MB/s\n\n\n\n```python\nx = mc.U(-1, 1)\ny = mc.U(-1, 1)\nins = sqrt(x**2 + y**2) < 1\nprint('percentage of points in the circle =', ins)\nprint('pi ≈', 4 * ins)\n```\n\n percentage of points in the circle = 0.7865\n pi ≈ 3.146\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "0e5e116c42691669152461a3d67093b684a6f231", "size": 127206, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "21_Probability_and_Statistics.ipynb", "max_stars_repo_name": "PALab/mathematical-notebooks-for-the-physical-sciences", "max_stars_repo_head_hexsha": "f5b759aa4746c54ea9cac8c0001093b2204047d4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2018-05-31T02:29:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-16T15:02:38.000Z", "max_issues_repo_path": "21_Probability_and_Statistics.ipynb", "max_issues_repo_name": "PALab/mathematical-notebooks-for-the-physical-sciences", "max_issues_repo_head_hexsha": "f5b759aa4746c54ea9cac8c0001093b2204047d4", "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": "21_Probability_and_Statistics.ipynb", "max_forks_repo_name": "PALab/mathematical-notebooks-for-the-physical-sciences", "max_forks_repo_head_hexsha": "f5b759aa4746c54ea9cac8c0001093b2204047d4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2018-06-22T00:45:17.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-16T14:25:40.000Z", "avg_line_length": 597.2112676056, "max_line_length": 25467, "alphanum_fraction": 0.9279122054, "converted": true, "num_tokens": 2057, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566342012360933, "lm_q2_score": 0.9184802445831379, "lm_q1q2_score": 0.8786496151279218}} {"text": "# Orthogonal polynomials\n\n\n```python\nimport numpy as np\nimport numpy.linalg as la\nimport matplotlib.pyplot as pt\n```\n\n## Mini-Introduction to `sympy`\n\n\n```python\nimport sympy as sym\n\n# Enable \"pretty-printing\" in IPython\nsym.init_printing()\n```\n\nMake a new `Symbol` and work with it:\n\n\n```python\nx = sym.Symbol(\"x\")\n\nmyexpr = (x**2-3)**2\nmyexpr\n```\n\n\n```python\nmyexpr = (x**2-3)**2\nmyexpr\nmyexpr.expand()\n```\n\n\n```python\nsym.integrate(myexpr, x)\n```\n\n\n```python\nsym.integrate(myexpr, (x, -1, 1))\n```\n\n## Orthogonal polynomials\n\nNow write a function `inner_product(f, g)`:\n\n\n```python\ndef inner_product(f, g):\n return sym.integrate(f*g, (x, -1, 1))\n```\n\nShow that it works:\n\n\n```python\ninner_product(1, 1)\n```\n\n\n```python\ninner_product(1, x)\n```\n\nNext, define a `basis` consisting of a few monomials:\n\n\n```python\nbasis = [1, x, x**2, x**3]\n#basis = [1, x, x**2, x**3, x**4, x**5]\n```\n\nAnd run Gram-Schmidt on it:\n\n\n```python\north_basis = []\n\nfor q in basis:\n for prev_q in orth_basis:\n q = q - inner_product(prev_q, q)*prev_q / inner_product(prev_q,prev_q)\n orth_basis.append(q)\n\nlegendre_basis = [orth_basis[0],]\n\n#to compute Legendre polynomials need to normalize so that q(1)=1 rather than ||q||=1\nfor q in orth_basis[1:]:\n q = q / q.subs(x,1)\n legendre_basis.append(q)\n```\n\n\n```python\nlegendre_basis\n```\n\nThese are called the *Legendre polynomials*.\n\n--------------------\nWhat do they look like?\n\n\n```python\nmesh = np.linspace(-1, 1, 100)\n\npt.figure(figsize=(8,8))\nfor f in legendre_basis:\n f = sym.lambdify(x, f)\n pt.plot(mesh, [f(xi) for xi in mesh])\n```\n\n-----\nThese functions are important enough to be included in `scipy.special` as `eval_legendre`:\n\n\n```python\nimport scipy.special as sps\n\nfor i in range(10):\n pt.plot(mesh, sps.eval_legendre(i, mesh))\n```\n\nWhat can we find out about the conditioning of the generalized Vandermonde matrix for Legendre polynomials?\n\n\n```python\n#keep\nn = 20\nxs = np.linspace(-1, 1, n)\nV = np.array([\n sps.eval_legendre(i, xs)\n for i in range(n)\n]).T\n\nla.cond(V)\n```\n\nThe Chebyshev basis can similarly be defined by Gram-Schmidt, but now with respect to a different inner-product weight function,\n$$w(x) = 1/\\sqrt{1-x^2}.$$\n\n\n```python\nw = 1 / sym.sqrt(1-x**2)\ndef cheb_inner_product(f, g):\n return sym.integrate(w*f*g, (x, -1, 1))\n\north_basis = []\n\nfor q in basis:\n for prev_q in orth_basis:\n q = q - cheb_inner_product(prev_q, q)*prev_q / cheb_inner_product(prev_q,prev_q)\n orth_basis.append(q)\n\ncheb_basis = [1,]\n\n#to compute Legendre polynomials need to normalize so that q(1)=1 rather than ||q||=1\nfor q in orth_basis[1:]:\n q = q / q.subs(x,1)\n cheb_basis.append(q)\ncheb_basis\n```\n\n\n```python\nfor i in range(10):\n pt.plot(mesh, np.cos(i*np.arccos(mesh)))\n```\n\nChebyshev polynomials achieve similar good, but imperfect conditioning on a uniform grid (but perfect conditioning on a grid of Chebyshev nodes).\n\n\n```python\n#keep\nn = 20\nxs = np.linspace(-1, 1, n)\nV = np.array([\n np.cos(i*np.arccos(xs))\n for i in range(n)\n]).T\n\nla.cond(V)\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "14d10b36ecdbd06408cc2c8cfc59f098e5c9b2be", "size": 283845, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "interpolation/Orthogonal Polynomials.ipynb", "max_stars_repo_name": "JiaheXu/MATH", "max_stars_repo_head_hexsha": "9cb2b412ba019794702cacf213471742745d17a6", "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": "interpolation/Orthogonal Polynomials.ipynb", "max_issues_repo_name": "JiaheXu/MATH", "max_issues_repo_head_hexsha": "9cb2b412ba019794702cacf213471742745d17a6", "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": "interpolation/Orthogonal Polynomials.ipynb", "max_forks_repo_name": "JiaheXu/MATH", "max_forks_repo_head_hexsha": "9cb2b412ba019794702cacf213471742745d17a6", "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": 512.3555956679, "max_line_length": 104482, "alphanum_fraction": 0.9370712889, "converted": true, "num_tokens": 957, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9637799441350252, "lm_q2_score": 0.9111797106148062, "lm_q1q2_score": 0.8781767305933064}} {"text": "# day06: Gradient Descent for Linear Regression\n\n# Objectives\n\n* Learn how to fit weight parameters of Linear Regression to a simple dataset via gradient descent\n* Understand impact of step size\n* Understand impact of initialization\n\n\n# Outline\n* [Part 1: Loss and Gradient for 1-dim. Linear Regression](#part1)\n* [Part 2: Gradient Descent Algorithm in a few lines of Python](#part2)\n* [Part 3: Debugging with Trace Plots](#part3)\n* [Part 4: Selecting the step size](#part4)\n* [Part 5: Selecting the initialization](#part5)\n* [Part 6: Using SciPy's built-in routines](#part6)\n\n# Takeaways\n\n\n* Gradient descent is a simple algorithm that can be implemented in a few lines of Python\n* * Practical issues include selecting step size and initialization\n* Step size matters a lot\n* * Need to select carefully for each problem\n\n* Initialization of the parameters can matter too!\n\n* scipy offers some useful tools for gradient-based optimization\n* * scipy's toolbox cannot do scalable \"stochastic\" methods (requires a modest size dataset, not too big)\n* * \"L-BFGS-B\" method is highly recommended if you have your loss and gradient functions available\n\n\n\n```python\nimport numpy as np\n```\n\n\n```python\n# import plotting libraries\nimport matplotlib\nimport matplotlib.pyplot as plt\n\n%matplotlib inline\nplt.style.use('seaborn') # pretty matplotlib plots\n\nimport seaborn as sns\nsns.set('notebook', font_scale=1.25, style='whitegrid')\n```\n\n# Create simple dataset: y = 1.234 * x + noise\n\nWe will *intentionally* create a toy dataset where we know that a good solution has slope near 1.234.\n\nNaturally, the best slope for the finite dataset of N=100 examples we create won't be exactly 1.234 (because of the noise added plus the fact that our dataset size is limited).\n\n\n```python\ndef create_dataset(N=100, slope=1.234, noise_stddev=0.1, random_state=0):\n random_state = np.random.RandomState(int(random_state))\n\n # input features\n x_N = np.linspace(-2, 2, N)\n \n # output features\n y_N = slope * x_N + random_state.randn(N) * noise_stddev\n \n return x_N, y_N\n```\n\n\n```python\nx_N, y_N = create_dataset(N=50, noise_stddev=0.3)\n```\n\n\n```python\nfig, ax = plt.subplots(nrows=1, ncols=1, figsize=(5,5))\nplt.plot(x_N, y_N, 'k.');\nplt.xlabel('x');\nplt.ylabel('y');\n```\n\n# Part 1: Gradient Descent for 1-dim. Linear Regression\n\n## Define model\n\nConsider the *simplest* linear regression model. A single weight parameter $w \\in \\mathbb{R}$ representing the slope of the prediction line. No bias/intercept.\n\nTo make predictions, we just compute the weight multiplied by the input feature\n$$\n\\hat{y}(x) = w \\cdot x\n$$\n\n## Define loss function\n\nWe want to minimize the total *squared error* across all N observed data examples (input features $x_n$, output responses $y_n$)\n\n\\begin{align}\n \\min_{w \\in \\mathbb{R}} ~~ &\\ell(w)\n \\\\\n \\text{calc_loss}(w) = \\ell(w) &= \\sum_{n=1}^N (y_n - w x_n)^2\n\\end{align}\n\n### Exercise 1A: Complete the code below\n\nYou should make it match the math expression above.\n\n\n```python\ndef calc_loss(w):\n ''' Compute loss for slope-only least-squares linear regression\n \n Args\n ----\n w : float\n Value of slope parameter\n\n Returns\n -------\n loss : float\n Sum of squared error loss at provided w value\n '''\n yhat_N = x_N * w\n sum_squared_error = 0.0 # todo compute the sum of squared error between y and yhat\n return sum_squared_error\n```\n\n# Define the gradient function\n\n\\begin{align}\n\\text{calc_grad}(w) = \\ell'(w) &= \\frac{\\partial}{\\partial w} [ \\sum_{n=1}^N (y_n - w x_n)^2] \n\\\\\n&= \\sum_{n=1}^N 2 (y_n - w x_n) (-x_n)\n\\\\\n&= 2 \\sum_{n=1}^N (w x_n - y_n) (x_n)\n\\\\\n&= 2 w \\left( \\sum_{n=1}^N x_n^2 \\right) - 2 \\sum_{n=1}^N y_n x_n\n\\end{align}\n\nBelow, we've implemented the gradient calculation in code for you\n\n\n```python\ndef calc_grad(w):\n ''' Compute gradient for slope-only least-squares linear regression\n \n Args\n ----\n w : float\n Value of slope parameter\n\n Returns\n -------\n g : float\n Value of derivative of loss function at provided w value\n '''\n g = 2.0 * w * np.sum(np.square(x_N)) - 2.0 * np.sum(x_N * y_N)\n return g\n```\n\n## Plot loss evaluated at each w from -3 to 8\n\nWe should see a \"bowl\" shape with one *global* minima, because our optimization problem is \"convex\"\n\n\n```python\nw_grid = np.linspace(-3, 8, 300) # create array of 300 values between -3 and 8\n```\n\n\n```python\nloss_grid = np.asarray([calc_loss(w) for w in w_grid])\nplt.plot(w_grid, loss_grid, 'b.-');\nplt.xlabel('w');\nplt.ylabel('loss(w)');\n```\n\n### Discussion 1b: Visually, at what value of $w$ does the loss function have a minima? Is it near where you would expect (hint: look above for the \"true\" slope value used to generate the data)\n\n### Exercise 1c: Write NumPy code to identify which entry in the w_grid array corresponds to the lowest entry in the loss_grid array\n\nHint: use np.argmin\n\n\n```python\n# TODO write code here\n```\n\n## Sanity check: plot gradient evaluated at each w from -3 to 8\n\n\n```python\ngrad_grid = np.asarray([calc_grad(w) for w in w_grid])\nplt.plot(w_grid, grad_grid, 'b.-');\nplt.xlabel('w');\nplt.ylabel('grad(w)');\n```\n\n### Discussion 1d: Visually, at what value of $w$ does the gradient function cross zero? Is it the same place as the location of the minimum in the loss above?\n\nTODO interpret the graph above and write your answer here, then discuss with your group\n\n### Exercise 1d: Numerically, at which value of w does grad_grid cross zero?\n\nWe might try to estimate numerically where the gradient crosses zero.\n\nWe could do this in a few steps:\n\n1) Compute the distance from each gradient in `grad_grid` to 0.0 (we could use just absolute distance)\n\n2) Find the index of `grad_grid` with smallest distance (using `np.argmin`)\n\n3) Plug that index into `w_grid` to get the $w$ value corresponding to that zero-crossing\n\n\n```python\ndist_from_zero_G = np.abs(grad_grid - 0.0)\n\nzero_cross_index = 0 # TODO fix me for step 2 above\n\nprint(\"Zero crossing occurs at w = %.4f\" % w_grid[0]) # TODO fix me for step 3 above\n```\n\n## Part 2: Gradient Descent (GD) as an algorithm in Python\n\n\n### Define minimize_via_grad_descent algorithm\n\nCan you understand what each step of this algorithm does?\n\n\n```python\ndef minimize_via_grad_descent(calc_loss, calc_grad, init_w=0.0, step_size=0.001, max_iters=100):\n ''' Perform minimization of provided loss function via gradient descent\n \n Args\n ----\n calc_loss : function\n calc_grad : function\n init_w : float\n step_size : float\n max_iters : positive int\n \n Return\n ----\n wopt: float\n array of optimized weights that approximately gives the least error\n info_dict : dict\n Contains information about the optimization procedure useful for debugging\n Entries include:\n * trace_loss_list : list of loss values\n * trace_grad_list : list of gradient values\n '''\n w = 1.0 * init_w \n grad = calc_grad(w)\n\n # Create some lists to track progress over time (for debugging)\n trace_loss_list = []\n trace_w_list = []\n trace_grad_list = []\n\n for iter_id in range(max_iters):\n if iter_id > 0:\n w = w - step_size * grad\n \n loss = calc_loss(w)\n grad = calc_grad(w) \n\n print(\" iter %5d/%d | w % 13.5f | loss % 13.4f | grad % 13.4f\" % (\n iter_id, max_iters, w, loss, grad))\n \n trace_loss_list.append(loss)\n trace_w_list.append(w)\n trace_grad_list.append(grad)\n \n wopt = w\n info_dict = dict(\n trace_loss_list=trace_loss_list,\n trace_w_list=trace_w_list, \n trace_grad_list=trace_grad_list)\n \n return wopt, info_dict\n```\n\n### Discussion 2a: Which line of the above function does the *parameter update* happen?\n\nRemember, in math, the parameter update of gradient descent is this:\n$$\nw \\gets w - \\alpha \\nabla_w \\ell(w)\n$$\n\nwhere $\\alpha > 0$ is the step size.\n\nIn words, this math says *move* the parameter $w$ from its current value a *small step* in the \"downhill\" direction (indicated by gradient).\n\nTODO write down here which line above *you* think it is, then discuss with your group\n\n\n```python\n\n```\n\n### Try it! Run GD with step_size = 0.001\n\nRunning the cell below will have the following effects:\n\n1) one line will be printed for every iteration, indicating the current w value and its associated loss\n\n2) the \"optimal\" value of w will be stored in the variable named `wopt` returned by this function\n\n3) a dictionary of information useful for debugging will be stored in the `info_dict` returned by this function\n\n\n```python\nwopt, info_dict = minimize_via_grad_descent(calc_loss, calc_grad, step_size=0.001);\n```\n\n### Discussion 2b: Does it appear from the *loss* values in trace above that the GD procedure converged?\n\n### Discussion 2c: Does it appear from the *parameter* values in trace above that the GD procedure converged?\n\n### Exercise 2d: What exactly is the gradient of the returned \"optimal\" value of w?\n\nUse your `calc_grad` function to check the result. What is the gradient of the returned `wopt`?\n\nDoes this look totally converged? Can you find a $w$ value that would be even better?\n\n\n```python\n# TODO call calc_grad on the return value from above\n```\n\n## Part 3: Diagnostic plots for gradient descent\n\nLet's look at some trace functions.\n\nWhenever you run gradient descent, an *excellent* debugging strategy is the ability to plot the loss, the gradient magnitude, and the parameter of interest at every step of the algorithm.\n\n\n```python\nfig, axes = plt.subplots(nrows=1, ncols=3, sharex=True, sharey=False, figsize=(18,3.6))\n\naxes[0].plot(info_dict['trace_loss_list']);\naxes[0].set_title('loss');\naxes[1].plot(info_dict['trace_grad_list']);\naxes[1].set_title('grad');\naxes[2].plot(info_dict['trace_w_list']);\naxes[2].set_title('w');\n\nplt.xlim([0, 100]);\n```\n\n### Discussion 3a: What value do we expect the *loss* to converge to? Should it always be zero?\n\n### Discussion 3b: What value do we expect the *gradient* to converge to? Should it always be zero?\n\n# Part 4: Larger step sizes\n\n## Try with larger step_size = 0.014\n\n\n```python\nwopt, info_dict = minimize_via_grad_descent(calc_loss, calc_grad, step_size=0.014);\n```\n\n\n```python\nfig, axes = plt.subplots(nrows=1, ncols=3, sharex=True, sharey=False, figsize=(12,3))\n\naxes[0].plot(info_dict['trace_loss_list'], '.-');\naxes[0].set_title('loss');\naxes[1].plot(info_dict['trace_grad_list'], '.-');\naxes[1].set_title('grad');\naxes[2].plot(info_dict['trace_w_list'], '.-');\naxes[2].set_title('w');\n```\n\n### Discussion 4a: What happens here? How is this step size different than in Part 3 above?\n\nTODO discuss with your group\n\n## Try with even larger step size 0.1\n\n\n```python\nwopt, info_dict = minimize_via_grad_descent(calc_loss, calc_grad, step_size=0.1, max_iters=25);\n```\n\n### Discussion 3b: What happens here with this even larger step size? Is it converging?\n\n### Exercise 3c: What is the largest step size you can get to converge reasonably?\n\n\n```python\n# TODO try some other step sizes here\nwopt, info_dict = minimize_via_grad_descent(calc_loss, calc_grad, step_size=0) # TODO fix step_size\n```\n\n# Part 5: Sensitivity to initial conditions\n\n\n\n### Exercise 5a: Try to call the defined procedure with a different initial condition for $w$. What happens?\n\nYou could try $w = 5.0$ or something else.\n\n\n```python\n# TODO try some other initial condition for init_w\nwopt2, info_dict2 = minimize_via_grad_descent(calc_loss, calc_grad, init_w=0, step_size=0.001, max_iters=10) # TODO fix step_size\n```\n\n### Exercise 5b: Try again with another initial value. \n\n\n```python\n# TODO try some other initial condition for init_w\nwopt3, info_dict3 = minimize_via_grad_descent(calc_loss, calc_grad, init_w=0, step_size=0.001, max_iters=10) # TODO fix\n```\n\n### Exercise 5c: Make a trace plot\n\nMake a trace plot showing convergence from multiple different starting values for $w$. What do you notice?\n\n\n```python\n# TODO\n```\n\n# Part 6: Using scipy's built-in gradient optimization tools\n\n\n\n```python\nimport scipy.optimize\n```\n\nTake a look at SciPy's built in minimization toolbox\n\n\n\nWe'll use \"L-BFGS\", a second-order method that uses the function and its gradient.\n\nThis is a \"quasi-newton\" method, which you can get an intuition for here:\n\nhttps://en.wikipedia.org/wiki/Newton%27s_method_in_optimization\n\n\n```python\nresult = scipy.optimize.minimize(calc_loss, 0.0, jac=calc_grad, method='L-BFGS-B')\n\n# Returns an object with several fields, let's print the result to get an idea\nprint(result)\n```\n\n\n```python\nprint(str(result.message))\n```\n\n\n```python\nbest_w = result.x\nprint(best_w)\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "a66ef7949342423cbfe31a713a743156ea08c60a", "size": 21863, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "labs/day06_GradientDescent_LinearRegression.ipynb", "max_stars_repo_name": "ypark12/comp135-20f-assignments", "max_stars_repo_head_hexsha": "653ac71d59230563ec60276678569b313e744d1e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2020-09-09T21:44:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-06T11:42:58.000Z", "max_issues_repo_path": "labs/day06_GradientDescent_LinearRegression.ipynb", "max_issues_repo_name": "ypark12/comp135-20f-assignments", "max_issues_repo_head_hexsha": "653ac71d59230563ec60276678569b313e744d1e", "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": "labs/day06_GradientDescent_LinearRegression.ipynb", "max_forks_repo_name": "ypark12/comp135-20f-assignments", "max_forks_repo_head_hexsha": "653ac71d59230563ec60276678569b313e744d1e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 39, "max_forks_repo_forks_event_min_datetime": "2020-09-11T19:16:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-07T19:43:57.000Z", "avg_line_length": 26.9248768473, "max_line_length": 201, "alphanum_fraction": 0.5525774139, "converted": true, "num_tokens": 3423, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308184368928, "lm_q2_score": 0.9407897546541052, "lm_q1q2_score": 0.878162150663825}} {"text": "# Scientific Computing with Python\n
This notebook by Xiaozhou Li is licensed under a Creative Commons Attribution 4.0 International License. \nAll code examples are also licensed under the [MIT license](http://opensource.org/licenses/MIT).\n\n\n```python\n# what is this line all about?\n%matplotlib inline\nimport matplotlib.pyplot as plt\n```\n\n## Numpy and Scipy\n### Introduction\nThe numpy package (module) is used in almost all numerical computation using Python. It is a package that provide high-performance vector, matrix and higher-dimensional data structures for Python. It is implemented in C and Fortran so when calculations are vectorized (formulated with vectors and matrices), performance is very good.\n\nThe SciPy framework builds on top of the low-level NumPy framework for multidimensional arrays, and provides a large number of higher-level scientific algorithms. \n\n### Fitting to polynomial\n\n\n```python\nimport numpy as np\n```\n\n\n```python\nnp.random.seed(12)\n\nx = np.linspace(0, 1, 20)\ny = np.cos(x) + 0.3*np.random.rand(20)\np = np.poly1d(np.polyfit(x, y, 16))\n\nt = np.linspace(0, 1, 200)\nplt.plot(x, y, 'o', t, p(t), '-')\nplt.show()\n```\n\n### Fit in a Chebyshev basis\n\n\n```python\nnp.random.seed(0)\n\nx = np.linspace(-1, 1, 2000)\ny = np.cos(x) + 0.3*np.random.rand(2000)\np = np.polynomial.Chebyshev.fit(x, y, 90)\n\nt = np.linspace(-1, 1, 200)\nplt.plot(x, y, 'r.')\nplt.plot(t, p(t), 'k-', lw=3)\nplt.show()\n```\n\n### A demo of 1D interpolation\n\n\n```python\nnp.random.seed(0)\nmeasured_time = np.linspace(0, 1, 10)\nnoise = 1e-1 * (np.random.random(10)*2 - 1)\nmeasures = np.sin(2 * np.pi * measured_time) + noise\n\n# Interpolate it to new time points\nfrom scipy.interpolate import interp1d\nlinear_interp = interp1d(measured_time, measures)\ninterpolation_time = np.linspace(0, 1, 50)\nlinear_results = linear_interp(interpolation_time)\ncubic_interp = interp1d(measured_time, measures, kind='cubic')\ncubic_results = cubic_interp(interpolation_time)\n\n# Plot the data and the interpolation\nfrom matplotlib import pyplot as plt\nplt.figure(figsize=(6, 4))\nplt.plot(measured_time, measures, 'o', ms=6, label='measures')\nplt.plot(interpolation_time, linear_results, label='linear interp')\nplt.plot(interpolation_time, cubic_results, label='cubic interp')\nplt.legend()\nplt.show()\n```\n\n### Minima and roots of a function\n\\begin{equation}\n f(x) = x^2 + 10\\sin(x)\n\\end{equation}\n\n**(1) find minima**\n\n\n```python\ndef f(x):\n return x**2 + 10*np.sin(x)\n\nfrom scipy import optimize\n\n# Global optimization\ngrid = (-10, 10, 0.1)\nxmin_global = optimize.brute(f, (grid, ))\nprint(\"Global minima found %s\" % xmin_global)\n\n# Constrain optimization\nxmin_local = optimize.fminbound(f, 0, 10)\nprint(\"Local minimum found %s\" % xmin_local)\n```\n\n Global minima found [-1.30641113]\n Local minimum found 3.8374671194983834\n\n\n**(2) root finding**\n\n\n```python\nroot = optimize.root(f, 1) # our initial guess is 1\nprint(\"First root found %s\" % root.x)\nroot2 = optimize.root(f, -2.5)\nprint(\"Second root found %s\" % root2.x)\n```\n\n First root found [0.]\n Second root found [-2.47948183]\n\n\n**(3) Plot function, minima, and roots**\n\n\n```python\nfig = plt.figure(figsize=(6, 4))\nax = fig.add_subplot(111)\n\nx = np.arange(-10, 10, 0.1)\n# Plot the function\nax.plot(x, f(x), 'b-', label=\"f(x)\")\n\n# Plot the minima\nxmins = np.array([xmin_global[0], xmin_local])\nax.plot(xmins, f(xmins), 'go', label=\"Minima\")\n\n# Plot the roots\nroots = np.array([root.x, root2.x])\nax.plot(roots, f(roots), 'kv', label=\"Roots\")\n\n# Decorate the figure\nax.legend(loc='best')\nax.set_xlabel('x')\nax.set_ylabel('f(x)')\nax.axhline(0, color='gray')\nplt.show()\n```\n\n## Matplotlib\n### Introduction\nMatplotlib is an excellent 2D and 3D graphics library for generating scientific figures.\n\n### Reading and writing a panda\n\n**(1) original figure**\n\n\n```python\nplt.figure()\nimg = plt.imread('../data/panda.jpg')\nplt.imshow(img)\nplt.imsave(\"original.jpg\",img)\n```\n\n**(2) red channel displayed in grey**\n\n\n```python\nplt.figure()\nimg_red = img[:, :, 0]\nplt.imshow(img_red, cmap=plt.cm.gray)\n```\n\n**(3) lower resolution (compression)**\n\n\n```python\nplt.figure()\nimg_tiny = img[::8, ::8]\nplt.imshow(img_tiny, interpolation='nearest') \n#plt.savefig(\"compressed.jpg\")\nplt.imsave(\"compressed.jpg\",img_tiny)\n```\n\n### Mandlebrot Set (Mandelbrot fractal)\n\n\n```python\ndef compute_mandelbrot(N_max, some_threshold, nx, ny):\n # A grid of c-values\n x = np.linspace(-2, 1, nx)\n y = np.linspace(-1.5, 1.5, ny)\n\n c = x[:,np.newaxis] + 1j*y[np.newaxis,:]\n\n # Mandelbrot iteration\n\n z = c\n for j in range(N_max):\n z = z**2 + c\n\n mandelbrot_set = (abs(z) < some_threshold)\n\n return mandelbrot_set\n\nmandelbrot_set = compute_mandelbrot(50, 50., 601, 401)\n\nplt.imshow(mandelbrot_set.T, extent=[-2, 1, -1.5, 1.5])\nplt.gray()\nplt.show()\n```\n\n### A simple example of 3D plotting\n$$ z = \\sin(\\sqrt{x^2 + y^2}) $$\n\n\n```python\nfrom mpl_toolkits.mplot3d import Axes3D\n\nfig = plt.figure()\nax = Axes3D(fig)\nX = np.arange(-4, 4, 0.25)\nY = np.arange(-4, 4, 0.25)\nX, Y = np.meshgrid(X, Y)\nR = np.sqrt(X ** 2 + Y ** 2)\nZ = np.sin(R)\n\nax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=plt.cm.hot)\nax.contourf(X, Y, Z, zdir='z', offset=-2, cmap=plt.cm.hot)\nax.set_zlim(-2, 2)\n\nplt.show()\n```\n\n### An example displaying the contours of a function\n$$ f(x,y) = \\left(1 - \\frac{x}{2} + x^5 + y^3\\right)e^{-x^2-y^2}.$$\n\n\n```python\ndef f(x,y):\n return (1 - x / 2 + x**5 + y**3) * np.exp(-x**2 -y**2)\n\nn = 256\nx = np.linspace(-3, 3, n)\ny = np.linspace(-3, 3, n)\nX,Y = np.meshgrid(x, y)\n\nplt.axes([0.025, 0.025, 0.95, 0.95])\n\nplt.contourf(X, Y, f(X, Y), 8, alpha=.75, cmap=plt.cm.hot)\nC = plt.contour(X, Y, f(X, Y), 8, colors='black')\nplt.clabel(C, inline=1, fontsize=10)\n\nplt.xticks(())\nplt.yticks(())\nplt.show()\n```\n\n## Sympy - Symbolic algebra in Python\n\n### Introduction\nThere are two notable Computer Algebra Systems (CAS) for Python:\n\n* [SymPy](http://sympy.org/en/index.html) - A python module that can be used in any Python program, or in an IPython session, that provides powerful CAS features. \n* [Sage](http://www.sagemath.org/) - Sage is a full-featured and very powerful CAS enviroment that aims to provide an open source system that competes with Mathematica and Maple. Sage is not a regular Python module, but rather a CAS environment that uses Python as its programming language.\n\nSage is in some aspects more powerful than SymPy, but both offer very comprehensive CAS functionality. The advantage of SymPy is that it is a regular Python module and integrates well with the Jupyter notebook. \n\n\n```python\nfrom sympy import *\n\ninit_printing()\n```\n\n### Expand, factor and simplify\n\n\n```python\nx, y = symbols('x y')\n\n(x+1)*(x+2)*(x+3)*(x+4)*(x+5)\n```\n\n\n```python\nexpand((x+1)*(x+2)*(x+3)*(x+4)*(x+5))\n```\n\n\n```python\nsin(x+y)\n```\n\n\n```python\nexpand(sin(x+y), trig=True)\n```\n\n\n```python\nexpand((x+y)**8)\n```\n\n\n```python\nx**3 + 6 * x**2 + 11*x + 6\n```\n\n\n```python\nfactor(x**3 + 6 * x**2 + 11*x + 6)\n```\n\n\n```python\nsin(x)**2 + cos(x)**2\n```\n\n\n```python\nsimplify(sin(x)**2 + cos(x)**2)\n```\n\n\n```python\ncos(x)/sin(x)\n```\n\n\n```python\nsimplify(cos(x)/sin(x))\n```\n\n### Calculus\n**(1) differentiation and integration**\n\n$f(x) = (x+1)^2$\n\n\n```python\nf = (x+1)**2\nf\n```\n\nComputing $\\frac{d f}{dx}$, $\\frac{d f^2}{dx}$\n\n\n```python\ndiff(f,x)\n```\n\n\n```python\ndiff(f**2,x)\n```\n\nComputing $\\frac{d \\sin(f)}{dx}$, $\\frac{d^2 \\sin(f)}{dx^2}$\n\n\n```python\ndiff(sin(f),x)\n```\n\n\n```python\ndiff(sin(f),x,2)\n```\n\n\n```python\ndiff(sin(f),x,4)\n```\n\n$$ f(x,y) = \\sin(xy) + \\cos(xy),$$\ncomputing\n$$ \\frac{\\partial^3 f}{\\partial x \\partial y^2},\\quad \\int f(x,y)\\,dx,\\quad \\int_{-1}^{1}f(x,y)\\,dx$$\n\n\n```python\nf = sin(x*y) + cos(y*x)\nf\n```\n\n\n```python\ndiff(f, x, 1, y, 2)\n```\n\n\n```python\nintegrate(f, x)\n```\n\n\n```python\nintegrate(f, (x, -1, 1))\n```\n\nComputing $\\int_{-\\infty}^\\infty e^{-x^2}\\,dx$\n\n\n```python\nintegrate(exp(-x**2), (x, -oo, oo))\n```\n\n**(2) limits**\n$$ \\lim\\limits_{x\\rightarrow 0}\\frac{\\sin(x)}{x},\\quad \\lim\\limits_{x\\rightarrow 0^{+}}\\frac{1}{x},\\quad \\lim\\limits_{x\\rightarrow 0^{-}}\\frac{1}{x}$$\n\n\n```python\nlimit(sin(x)/x, x, 0)\n```\n\n\n```python\nlimit(1/x, x, 0, dir=\"+\")\n```\n\n\n```python\nlimit(1/x, x, 0, dir=\"-\")\n```\n\n**(3) series**\n\n\n```python\nexp(x)\n```\n\n\n```python\nseries(exp(x), x)\n```\n\n\n```python\nseries(exp(x), x, 1)\n```\n\n\n```python\nseries(sin(x), x, 0, 12)\n```\n\n\n```python\nseries(sin(x)*cos(x), x, 0, 8)\n```\n\n\n```python\nseries(sin(x)*cos(x)*exp(x), x, 0, 12)\n```\n\n### Linear algebra: Matrices\n\n\n```python\nm11, m12, m21, m22 = symbols(\"m11, m12, m21, m22\")\nb1, b2 = symbols(\"b1, b2\")\n```\n\n\n```python\nA = Matrix([[m11, m12],[m21, m22]])\nA\n```\n\n\n```python\nb = Matrix([[b1], [b2]])\nb\n```\n\n\n```python\nA**2\n```\n\n\n```python\nA**5\n```\n\n\n```python\nA * b\n```\n\n\n```python\nA.det()\n```\n\n\n```python\nA.inv()\n```\n\n### Solving equations\nSolving \n$$ x^2 - 1 = 0,\\quad x^4 - x^2 - 1 = 0$$\n\n\n```python\nsolve(x**2 - 1, x)\n```\n\n\n```python\nsolve(x**4 + x**3 - x**2 - 1, x)\n```\n\nSolving systems:\n$$ x + y - 1 = 0,\\quad x - y - 1 = 0,$$\nand\n$$ x + y - a = 0,\\quad x - y - b = 0.$$\n\n\n```python\nsolve([x + y - 1, x - y - 1], [x,y])\n```\n\n\n```python\na, b = symbols('a, b')\nsolve([x + y - a, x - y - b], [x,y])\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "467ebfabfc0ab9ede9458ee30777bab3199e5de3", "size": 819906, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Other/Scientific_Python.ipynb", "max_stars_repo_name": "xiaozhouli/Jupyter", "max_stars_repo_head_hexsha": "68d5a384dd939b3e8079da4470d6401d11b63a4c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2020-02-27T13:09:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-14T09:50:30.000Z", "max_issues_repo_path": "Other/Scientific_Python.ipynb", "max_issues_repo_name": "xiaozhouli/Jupyter", "max_issues_repo_head_hexsha": "68d5a384dd939b3e8079da4470d6401d11b63a4c", "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": "Other/Scientific_Python.ipynb", "max_forks_repo_name": "xiaozhouli/Jupyter", "max_forks_repo_head_hexsha": "68d5a384dd939b3e8079da4470d6401d11b63a4c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2018-10-18T10:20:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-24T08:09:27.000Z", "avg_line_length": 443.1924324324, "max_line_length": 231688, "alphanum_fraction": 0.9340668321, "converted": true, "num_tokens": 3126, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897442783527, "lm_q2_score": 0.9334308063998764, "lm_q1q2_score": 0.8781621296544763}} {"text": "# Lab 4\n## Introduction\nThe Euler method is a method for numerically solving a DE of the form\n\\begin{align}\n\\frac{\\mathrm{d}y}{\\mathrm{d}x} = f(x,y).\n\\end{align}\n\nIt is often necessary to solve DEs this way as analytical solutions are the exception\nrather than the rule.\n\n\n\nEuler’s method works by approximating small segments of the curve solution to the DE\nwith the straight-line tangent or slope of the curve. As long as we keep the segments\nsmall enough, they will approximately match what the actual curve looks like. It requires us to ”know” an initial value $y(x_0) = y_0$ so we can start the calculation.\n\nTo calculate the first segment we start off with our known start point $(x_0, y_0)$, and calculate the end point, $(x_1, y_1)$. We can define $\\Delta x$ to be some constant small distance so that we always increment the $x$ value by the same amount. Then, $\\Delta y = m \\Delta x$ and $(x_1, y_1)=(x_0, y_0)+(\\Delta x, m\\Delta x)$.\n\n\n\nBut, we also know that $m$, the slope of the line, is given by $\\mathrm{d}y/\\mathrm{d}x$, i.e., $f(x, y)$ evaluated at $(x_0, y_0)$. So actually, $\\Delta y = f(x_0, y_0) \\Delta x$.\n\nThe final step is to calculate the new point: the point at the end of the first line segment. This point is then given by $(x_1, y_1) = (x_0 + \\Delta x, y_0 + f(x_0, y_0) \\Delta x)$.\n\nWe then do it again to calculate $(x_2, y_2)$ using $(x_1, y_1)$ as our starting point. We then do it again to calculate $(x_3, y_3)$ using $(x_2, y_2)$ as our starting point and so on.\n\n**Summary:** The Euler method for evaluating a DE of the form\n\\begin{align}\n\\frac{\\mathrm{d}y}{\\mathrm{d}x} = f(x,y).\n\\end{align}\ninvolves the iterative calculation of\n\\begin{align}\nx_{n+1} &= x_n + \\Delta x\\\\\n\\text{and}\\quad y_{n+1} &= y_n + f(x_n,y_n)\\Delta x.\n\\end{align}\n\n### Implementation\n\nFirst import the necessary functions from NumPy and SciPy and set up Plotly.\n\n\n```python\nfrom numpy import arange, empty, exp\nfrom plotly import graph_objs as go\n```\n\nNow let's write a function that implements Euler's method. We will model it on `scipy.integrate.odeint`. We will make slight changes to the parameters because we want to input $\\Delta x$. Note that the string (delimited by triple quotes) immediately after the function definition is a _docstring_. It tells us what the function does and is good programming practice. The prodigious comments in the function body are not generally necessary but are included for you.\n\n\n```python\ndef euler(func, y0, x0, xn, Dx):\n \"\"\"\n Integrate an ordinary differential equation using Euler's method.\n \n Solves the initial value problem for systems of first order ode-s::\n dy/dx = func(y, x).\n \n Parameters\n ----------\n func : callable(y, x)\n Computes the derivative of y at x.\n y0 : float\n Initial condition on y.\n x0 : float\n Initial condition on x.\n xn : float\n Upper limit to value of x.\n Dx : float\n x increment.\n \n Returns\n -------\n x : float\n Array containing the value of x for each value of x0 + n * Dx,\n where n ranges from zero to floor( (xn - x0) / Dx ).\n y : float\n Array containing the value of y for each value of x.\n \"\"\"\n x = arange(x0, xn, Dx) # Create the x array\n y = empty(len(x)) # Create an empty y array of the same length as x\n y[0] = y0 # Set the first value of y to y0\n for n in range(len(x) - 1): # Loop to populate the rest of the values of y\n y[n+1] = y[n] + func(y[n], x[n]) * Dx # Euler's method\n \n return x, y # Return x and y as a pair\n```\n\nFirst try solving\n\\begin{align}\n\\frac{\\mathrm{d}y}{\\mathrm{d}x} = y.\n\\end{align}\nfor $y(0)=1$ for $x$ between 1 and 5 and using $\\Delta x=1$.\n\n\n```python\ndef diff_eq(y, x):\n return y\n\nx, y = euler(diff_eq, 1, 0, 5.01, 1)\n```\n\nWhy was `xn` set to 5.01 rather than 5?\n\nWe know that the analytic solution to the above IVP is $y=\\mathrm{e}^x$, so calculate that as well.\n\n\n```python\nx_analytic = arange(0, 5.01, 0.1)\ny_analytic = exp(x_analytic)\n```\n\nNow plot them both for comparison.\n\n\n```python\nfig = go.Figure()\nfig.add_trace(go.Scatter(x=x, y=y,\n name='Euler'))\nfig.add_trace(go.Scatter(x=x_analytic,\n y=y_analytic,\n name='Truth'))\nfig.show('png')\n```\n\nReproduce the comparison plot below but with $\\Delta x=0.1$.\n\n\n```python\nx, y = euler(diff_eq, 1, 0, 5.01, 0.1)\n\nx_analytic = arange(0, 5.01, 0.1)\ny_analytic = exp(x_analytic)\n\nfig = go.Figure()\nfig.add_trace(go.Scatter(x=x, y=y,\n name='Euler'))\nfig.add_trace(go.Scatter(x=x_analytic,\n y=y_analytic,\n name='Truth'))\nfig.show('png')\n```\n\n\nIt is possible to quantify the error in the Euler solution compared to the analytic solution. To do this you need to re-calculate the analytic solution at the same $x$ points as you calculated your Euler solution. Then you can do a Mean Squared Error (MSE) comparison between the two.\n\n\n```python\nx, y = euler(diff_eq, 1, 0, 5.01, 1)\ny_analytic = exp(x)\n((y_analytic - y)**2).mean()\n```\n\n\n\n\n 2533.317105161909\n\n\n\nNote that `((y_analytic - y)**2)` returned an `array` object, and then we called the `mean` method that was _bound_ to that object.\n\nWhat is the MSE if $\\Delta x = 0.1$?\n\n\n```python\nx, y = euler(diff_eq, 1, 0, 5.01, 0.1)\ny_analytic = exp(x)\n((y_analytic - y)**2).mean()\n```\n\n\n\n\n 88.60637343780924\n\n\n\n## Exercises\n\nIn this lab you will try Euler's method for a couple of differential equations.\n\n1. a. Consider the IVP\n\\begin{align}\n\\frac{\\mathrm{d}y}{\\mathrm{d}x} = 2x\\quad\\text{where}\\quad y(-2)=4.\n\\end{align}\nCalculate the Euler approximation on the interval $x=[-2,2]$ using a step size of $\\Delta x = 0.5$. On the same figure, plot your approximation and the analytic solution.\n\n\n```python\nfrom scipy.integrate import odeint\n\ndef diff_eq(y, x):\n return 2*x\n\nx, y = euler(diff_eq, 4, -2, 2.01, 0.5)\n\nx_analytic = arange(-2, 2.01, 0.1)\ny_analytic = odeint(diff_eq, 4, x_analytic).flatten()\n\nfig = go.Figure()\nfig.add_trace(go.Scatter(x=x, y=y,\n name='Euler'))\nfig.add_trace(go.Scatter(x=x_analytic,\n y=y_analytic,\n name='Truth'))\nfig.show('png')\n```\n\n1. b. Calculate the mean squared error (MSE) of the approximation.\n\n\n```python\nx, y = euler(diff_eq, 4, -2, 2.01, 0.5)\ny_analytic = odeint(diff_eq, 4, x_analytic)\n((y_analytic - y)**2).mean()\n```\n\n\n\n\n 4.658533377001063\n\n\n\n1. c. Reproduce your plot from 1a except with $\\Delta x=0.1$.\n\n\n```python\ndef diff_eq(y, x):\n return 2*x\n\nx, y = euler(diff_eq, 4, -2, 2.01, 0.1)\n\nx_analytic = arange(-2, 2.01, 0.1)\ny_analytic = odeint(diff_eq, 4, x_analytic).flatten()\n\nfig = go.Figure()\nfig.add_trace(go.Scatter(x=x, y=y,\n name='Euler'))\nfig.add_trace(go.Scatter(x=x_analytic,\n y=y_analytic,\n name='Truth'))\nfig.show('png')\n```\n\n1. d. Recalculate the MSE.\n\n\n```python\nx, y = euler(diff_eq, 4, -2, 2.01, 0.1)\ny_analytic = odeint(diff_eq, 4, x_analytic)\n((y_analytic - y)**2).mean()\n```\n\n\n\n\n 3.184400008820671\n\n\n\n2. a. The following is the DE for the arrow problem from class.\n\\begin{align}\n\\frac{\\mathrm{d}y}{\\mathrm{d}t} = 294\\mathrm{e}^{-0.04t}-245\\quad\\text{where}\\quad y(0)=0\n\\end{align}\nCalculate the Euler approximation to the solution on the interval $t=[0,10]$ with $\\Delta t=0.5$. Plot your approximation and the analytic solution on the same figure.\n\n\n```python\ndef diff_eq(y, x):\n return 294*exp(-0.04*x) - 245\n\nx, y = euler(diff_eq, 0, 0, 10.01, 0.5)\n\nx_analytic = arange(0, 10.01, 0.1)\ny_analytic = odeint(diff_eq, 0, x_analytic).flatten()\n\nfig = go.Figure()\nfig.add_trace(go.Scatter(x=x, y=y,\n name='Euler'))\nfig.add_trace(go.Scatter(x=x_analytic,\n y=y_analytic,\n name='Truth'))\nfig.show('png')\n```\n\n2. b. Calculate the MSE of the approximation.\n\n\n```python\nx, y = euler(diff_eq, 0, 0, 10.01, 0.5)\ny_analytic = odeint(diff_eq, 0, x_analytic)\n((y_analytic - y)**2).mean()\n```\n\n\n\n\n 3132.157528098768\n\n\n\n2. c. Reproduce your plot from 2a except with $\\Delta t=0.1$.\n\n\n```python\ndef diff_eq(y, x):\n return 294*exp(-0.04*x) - 245\n\nx, y = euler(diff_eq, 0, 0, 10.01, 0.1)\n\nx_analytic = arange(0, 10.01, 0.1)\ny_analytic = odeint(diff_eq, 0, x_analytic).flatten()\n\nfig = go.Figure()\nfig.add_trace(go.Scatter(x=x, y=y,\n name='Euler'))\nfig.add_trace(go.Scatter(x=x_analytic,\n y=y_analytic,\n name='Truth'))\nfig.show('png')\n```\n\n2. d. Recalculate the MSE.\n\n\n```python\nx, y = euler(diff_eq, 0, 0, 10.01, 0.1)\ny_analytic = odeint(diff_eq, 0, x_analytic)\n((y_analytic - y)**2).mean()\n```\n\n\n\n\n 2870.2127242316765\n\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "589891269d422690ba0b6b2eafa9589acde21e30", "size": 251321, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/lab-04.ipynb", "max_stars_repo_name": "AF641/mm-labs", "max_stars_repo_head_hexsha": "6d92f89e6ac4009b5a531dbe3c449c776feb4dab", "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": "notebooks/lab-04.ipynb", "max_issues_repo_name": "AF641/mm-labs", "max_issues_repo_head_hexsha": "6d92f89e6ac4009b5a531dbe3c449c776feb4dab", "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": "notebooks/lab-04.ipynb", "max_forks_repo_name": "AF641/mm-labs", "max_forks_repo_head_hexsha": "6d92f89e6ac4009b5a531dbe3c449c776feb4dab", "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": 342.8663028649, "max_line_length": 42577, "alphanum_fraction": 0.9338654549, "converted": true, "num_tokens": 2805, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533107374444, "lm_q2_score": 0.9416541581602784, "lm_q1q2_score": 0.8780485373462327}} {"text": "# Plotting a Torus \n\nTo plot a surface in 3D do you first need to find the \nparametrization of the surface you wish to plot. \n\nFor a Torus the parametrization looks like this:\n\\begin{align}\nx &= [c + a \\cos v] \\cos u \\\\\ny &= [c + a \\cos v] \\sin u \\\\\nz &= a \\sin v\n\\end{align}\n\n\nwhere $a$ represents the radius of the tube and $c$ is the radius of the \ncenter hole of the torus tube. See https://mathworld.wolfram.com/Torus.html for further information.\n\n\n\nBegin by activating matplotlib notebook and importing numpy and \nmatplotlib\n\n\n```python\n%matplotlib notebook \n# This enables you to drag and rotate the figure\n\nfrom mpl_toolkits.mplot3d import Axes3D # needed to do the 3D Plots\nimport numpy as np\nimport matplotlib.pyplot as plt\n```\n\n\n```python\nfig = plt.figure()\nax = fig.gca(projection='3d')\n\nu = np.linspace(0, 2*np.pi, 100)\nv = np.linspace(0, 2*np.pi, 100)\nu, v = np.meshgrid(u, v) # Make coordinate matrices from coordinate vectors.\na, c = 0.2, 1.0 # Set a and c from the torus parametrization\n\n# Paramatrization\nx = (c + a*np.cos(v))*np.cos(u)\ny = (c + a*np.cos(v))*np.sin(u)\nz = a*np.sin(v)\n\n\nax.plot_surface(x, y, z)\n\nax.set_xlim3d(-1, 1)\nax.set_ylim3d(-1, 1)\nax.set_zlim3d(-1, 1)\nplt.show()\n```\n\n# Make a surface plot of a sphere\n\nPlot a sphere the parametrization is:\n\n\\begin{align}\nx &= r \\cos \\theta \\sin \\phi \\\\\ny &= r \\sin \\theta \\sin \\phi \\\\\nz &= r \\cos \\phi \n\\end{align}\n\nwhere $\\theta$ is the loggitude coorinate running from $0$ to $2\\pi$, \n$\\phi$ is the colatitude coordinate running from $0$ to $\\pi$ and $r$ is the radius.\n\n\n```python\nfig = plt.figure()\nax = fig.gca(projection='3d')\n\n# Fill inn the rest\n```\n\n# Make a surface plot of a Mobius strip\n\nThe parametrization is:\n\\begin{align}\nx &= \\left(1 + \\frac{v}{2}\\cos \\frac{u}{2} \\right)\\cos u \\\\\ny &= \\left(1 + \\frac{v}{2}\\cos v \\right)\\sin u \\\\\nz &= \\frac{v}{2}\\sin \\frac{u}{2} \n\\end{align}\n\nwhere $u$ is running from $0$ to $2\\pi$ and $v$ is running from $-1$ to $1$.\n\n\n```python\nfig = plt.figure()\nax = fig.gca(projection='3d')\n\n# Fill inn the rest\n\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "3a3607ace5a95e7e7d1446c13857f2a4f8fd92a7", "size": 4031, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "problem_candidates/Plotting surfacees.ipynb", "max_stars_repo_name": "KJE2001/seminars", "max_stars_repo_head_hexsha": "b42c5c0a945795f6f625db35cafefa6662e5ce7e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2017-02-04T01:34:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-12T12:27:37.000Z", "max_issues_repo_path": "problem_candidates/Plotting surfacees.ipynb", "max_issues_repo_name": "KJE2001/seminars", "max_issues_repo_head_hexsha": "b42c5c0a945795f6f625db35cafefa6662e5ce7e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2020-03-30T11:00:35.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-12T05:42:24.000Z", "max_forks_repo_path": "problem_candidates/Plotting surfacees.ipynb", "max_forks_repo_name": "KJE2001/seminars", "max_forks_repo_head_hexsha": "b42c5c0a945795f6f625db35cafefa6662e5ce7e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2016-04-26T20:42:43.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-06T11:12:57.000Z", "avg_line_length": 24.4303030303, "max_line_length": 109, "alphanum_fraction": 0.5038451997, "converted": true, "num_tokens": 682, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474233166328, "lm_q2_score": 0.9196425377849806, "lm_q1q2_score": 0.8779343790688008}} {"text": "# Tensor Manipulation: Psi4 and NumPy manipulation routines\nContracting tensors together forms the core of the Psi4NumPy project. First let us consider the popluar [Einstein Summation Notation](https://en.wikipedia.org/wiki/Einstein_notation) which allows for very succinct descriptions of a given tensor contraction.\n\nFor example, let us consider a [inner (dot) product](https://en.wikipedia.org/wiki/Dot_product):\n$$c = \\sum_{ij} A_{ij} * B_{ij}$$\n\nWith the Einstein convention, all indices that are repeated are considered summed over, and the explicit summation symbol is dropped:\n$$c = A_{ij} * B_{ij}$$\n\nThis can be extended to [matrix multiplication](https://en.wikipedia.org/wiki/Matrix_multiplication):\n\\begin{align}\n\\rm{Conventional}\\;\\;\\; C_{ik} &= \\sum_{j} A_{ij} * B_{jk} \\\\\n\\rm{Einstein}\\;\\;\\; C &= A_{ij} * B_{jk} \\\\\n\\end{align}\n\nWhere the $C$ matrix has *implied* indices of $C_{ik}$ as the only repeated index is $j$.\n\nHowever, there are many cases where this notation fails. Thus we often use the generalized Einstein convention. To demonstrate let us examine a [Hadamard product](https://en.wikipedia.org/wiki/Hadamard_product_(matrices)):\n$$C_{ij} = \\sum_{ij} A_{ij} * B_{ij}$$\n\n\nThis operation is nearly identical to the dot product above, and is not able to be written in pure Einstein convention. The generalized convention allows for the use of indices on the left hand side of the equation:\n$$C_{ij} = A_{ij} * B_{ij}$$\n\nUsually it should be apparent within the context the exact meaning of a given expression.\n\nFinally we also make use of Matrix notation:\n\\begin{align}\n{\\rm Matrix}\\;\\;\\; \\bf{D} &= \\bf{A B C} \\\\\n{\\rm Einstein}\\;\\;\\; D_{il} &= A_{ij} B_{jk} C_{kl}\n\\end{align}\n\nNote that this notation is signified by the use of bold characters to denote matrices and consecutive matrices next to each other imply a chain of matrix multiplications! \n\n## Einsum\n\nTo perform most operations we turn to [NumPy's einsum function](https://docs.scipy.org/doc/numpy/reference/generated/numpy.einsum.html) which allows the Einsten convention as an input. In addition to being much easier to read, manipulate, and change, it is also much more efficient that a pure Python implementation.\n\nTo begin let us consider the construction of the following tensor (which you may recognize):\n$$G_{pq} = 2.0 * I_{pqrs} D_{rs} - 1.0 * I_{prqs} D_{rs}$$ \n\nFirst let us import our normal suite of modules:\n\n\n```python\nimport numpy as np\nimport psi4\nimport time\n```\n\nWe can then use conventional Python loops and einsum to perform the same task. Keep size relatively small as these 4-index tensors grow very quickly in size.\n\n\n```python\nsize = 20\n\nif size > 30:\n raise Exception(\"Size must be smaller than 30.\")\nD = np.random.rand(size, size)\nI = np.random.rand(size, size, size, size)\n\n# Build the fock matrix using loops, while keeping track of time\ntstart_loop = time.time()\nGloop = np.zeros((size, size))\nfor p in range(size):\n for q in range(size):\n for r in range(size):\n for s in range(size):\n Gloop[p, q] += 2 * I[p, q, r, s] * D[r, s]\n Gloop[p, q] -= I[p, r, q, s] * D[r, s]\n\ng_loop_time = time.time() - tstart_loop\n\n# Build the fock matrix using einsum, while keeping track of time\ntstart_einsum = time.time()\nJ = np.einsum('pqrs,rs', I, D)\nK = np.einsum('prqs,rs', I, D)\nG = 2 * J - K\n\neinsum_time = time.time() - tstart_einsum\n\n# Make sure the correct answer is obtained\nprint('The loop and einsum fock builds match: %s\\n' % np.allclose(G, Gloop))\n# Print out relative times for explicit loop vs einsum Fock builds\nprint('Time for loop G build: %14.4f seconds' % g_loop_time)\nprint('Time for einsum G build: %14.4f seconds' % einsum_time)\nprint('G builds with einsum are {:3.4f} times faster than Python loops!'.format(g_loop_time / einsum_time))\n```\n\n The loop and einsum fock builds match: True\n \n Time for loop G build: 0.2845 seconds\n Time for einsum G build: 0.0005 seconds\n G builds with einsum are 536.7238 times faster than Python loops!\n\n\nAs you can see, the einsum function is considerably faster than the pure Python loops and, in this author's opinion, much cleaner and easier to use.\n\n## Dot\n\nNow let us turn our attention to a more canonical matrix multiplication example such as:\n$$D_{il} = A_{ij} B_{jk} C_{kl}$$\n\nWe could perform this operation using einsum; however, matrix multiplication is an extremely common operation in all branches of linear algebra. Thus, these functions have been optimized to be more efficient than the `einsum` function. The matrix product will explicitly compute the following operation:\n$$C_{ij} = A_{ij} * B_{ij}$$\n\nThis can be called with [NumPy's dot function](https://docs.scipy.org/doc/numpy/reference/generated/numpy.dot.html#numpy.dot).\n\n\n```python\nsize = 200\nA = np.random.rand(size, size)\nB = np.random.rand(size, size)\nC = np.random.rand(size, size)\n\n# First compute the pair product\ntmp_dot = np.dot(A, B)\ntmp_einsum = np.einsum('ij,jk->ik', A, B)\nprint(\"Pair product allclose: %s\" % np.allclose(tmp_dot, tmp_einsum))\n```\n\n Pair product allclose: True\n\n\nNow that we have proved exactly what the dot product does, let us consider the full chain and do a timing comparison:\n\n\n```python\nD_dot = np.dot(A, B).dot(C)\nD_einsum = np.einsum('ij,jk,kl->il', A, B, C)\nprint(\"Chain multiplication allclose: %s\" % np.allclose(D_dot, D_einsum))\n\nprint(\"\\nnp.dot time:\")\n%timeit np.dot(A, B).dot(C)\n\nprint(\"\\nnp.einsum time\")\n%timeit np.einsum('ij,jk,kl->il', A, B, C)\n```\n\n Chain multiplication allclose: True\n \n np.dot time:\n 1000 loops, best of 3: 288 µs per loop\n \n np.einsum time\n 1 loop, best of 3: 1.68 s per loop\n\n\nOn most machines the `np.dot` times are roughly ~3,000 times faster. The reason is twofold:\n - The `np.dot` routines typically call [Basic Linear Algebra Subprograms (BLAS)](https://en.wikipedia.org/wiki/Basic_Linear_Algebra_Subprograms). The BLAS routines are highly optimized and threaded versions of the code.\n - The `np.einsum` code will not factorize the operation; Thus, the overall cost is ${\\cal O}(N^4)$ (as there are four indices) rather than the factored $(\\bf{A B}) \\bf{C}$ which runs ${\\cal O}(N^3)$.\n \nThe first issue is difficult to overcome; however, the second issue can be resolved by the following:\n\n\n```python\nprint(\"np.einsum factorized time:\")\n%timeit np.einsum('ik,kl->il', np.einsum('ij,jk->ik', A, B), C)\n```\n\n np.einsum factorized time:\n 100 loops, best of 3: 5.24 ms per loop\n\n\nOn most machines the factorized `einsum` expression is only ~20 times slower than `np.dot`. While a massive improvement, this is a clear demonstration the BLAS usage is usually recommended. It is a tradeoff between speed and readability. The Psi4NumPy project tends to lean toward `einsum` usage except in case where the benefit is too large to pass up.\n\nIt should be noted that in NumPy 1.12 the [einsum function](https://docs.scipy.org/doc/numpy/reference/generated/numpy.einsum.html) has a `optimize` flag which will automatically factorize the einsum code for you. However, NumPy 1.12 was recently released and is not in most installations yet.\n\n## Complex tensor manipulations\nLet us consider a popular index transformation example:\n$$M_{pqrs} = C_{pi} C_{qj} I_{ijkl} C_{rk} C_{sl}$$\n\nHere, a naive `einsum` call would scale like $\\mathcal{O}(N^8)$ which translates to an extremely costly computation for all but the smallest $N$.\n\n\n```python\n# Grab orbitals\nsize = 15\nif size > 15:\n raise Exception(\"Size must be smaller than 15.\")\n \nC = np.random.rand(size, size)\nI = np.random.rand(size, size, size, size)\n\n# Numpy einsum N^8 transformation.\nprint(\"\\nStarting Numpy's N^8 transformation...\")\nn8_tstart = time.time()\nMO_n8 = np.einsum('pI,qJ,pqrs,rK,sL->IJKL', C, C, I, C, C)\nn8_time = time.time() - n8_tstart\nprint(\"...transformation complete in %.3f seconds.\" % (n8_time))\n\n# Numpy einsum N^5 transformation.\nprint(\"\\n\\nStarting Numpy's N^5 transformation with einsum...\")\nn5_tstart = time.time()\nMO_n5 = np.einsum('pA,pqrs->Aqrs', C, I)\nMO_n5 = np.einsum('qB,Aqrs->ABrs', C, MO_n5)\nMO_n5 = np.einsum('rC,ABrs->ABCs', C, MO_n5)\nMO_n5 = np.einsum('sD,ABCs->ABCD', C, MO_n5)\nn5_time = time.time() - n5_tstart\nprint(\"...transformation complete in %.3f seconds.\" % n5_time)\nprint(\"\\nN^5 %4.2f faster than N^8 algorithm!\" % (n8_time / n5_time))\nprint(\"Allclose: %s\" % np.allclose(MO_n8, MO_n5))\n\n# Numpy GEMM N^5 transformation.\n# Try to figure this one out!\nprint(\"\\n\\nStarting Numpy's N^5 transformation with dot...\")\ndgemm_tstart = time.time()\nMO = np.dot(C.T, I.reshape(size, -1))\nMO = np.dot(MO.reshape(-1, size), C)\nMO = MO.reshape(size, size, size, size).transpose(1, 0, 3, 2)\n\nMO = np.dot(C.T, MO.reshape(size, -1))\nMO = np.dot(MO.reshape(-1, size), C)\nMO = MO.reshape(size, size, size, size).transpose(1, 0, 3, 2)\ndgemm_time = time.time() - dgemm_tstart\nprint(\"...transformation complete in %.3f seconds.\" % dgemm_time)\nprint(\"\\nAllclose: %s\" % np.allclose(MO_n8, MO))\nprint(\"N^5 %4.2f faster than N^8 algorithm!\" % (n8_time / dgemm_time))\n```\n\n \n Starting Numpy's N^8 transformation...\n ...transformation complete in 22.304 seconds.\n \n Starting Numpy's N^5 transformation with einsum...\n ...transformation complete in 0.004 seconds.\n \n N^5 5277.95 faster than N^8 algorithm!\n Allclose: True\n \n \n Starting Numpy's N^5 transformation with dot...\n ...transformation complete in 0.001 seconds.\n \n Allclose: True\n N^5 22712.25 faster than N^8 algorithm!\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "44dc9df0a84fe66d4bc1c977ba0d1673c8d72130", "size": 14080, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Tutorials/01_Psi4NumPy-Basics/1f_tensor-manipulation.ipynb", "max_stars_repo_name": "PhillCli/psi4numpy", "max_stars_repo_head_hexsha": "31d405e351edaaa81285a12d2230e96aad160043", "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/01_Psi4NumPy-Basics/1f_tensor-manipulation.ipynb", "max_issues_repo_name": "PhillCli/psi4numpy", "max_issues_repo_head_hexsha": "31d405e351edaaa81285a12d2230e96aad160043", "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/01_Psi4NumPy-Basics/1f_tensor-manipulation.ipynb", "max_forks_repo_name": "PhillCli/psi4numpy", "max_forks_repo_head_hexsha": "31d405e351edaaa81285a12d2230e96aad160043", "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": 35.8269720102, "max_line_length": 362, "alphanum_fraction": 0.5855113636, "converted": true, "num_tokens": 2774, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067195846918, "lm_q2_score": 0.9314625112488223, "lm_q1q2_score": 0.8779096758932465}} {"text": "```python\nfrom sympy import *\n```\n\n\n```python\ninit_printing(use_unicode=True)\n```\n\n\n```python\n# A Matrix object is constructed by providing a list \n# of row vectors that make up the matrix\n```\n\n\n```python\nA = Matrix([1,2,3])\n```\n\n\n```python\nprint(A)\n```\n\n Matrix([[1], [2], [3]])\n\n\n\n```python\n# For pretty printing\nA\n```\n\n\n```python\nAA = Matrix([[1,2],[3,4]])\n```\n\n\n```python\nAA\n```\n\n\n```python\nprint(AA)\n```\n\n Matrix([[1, 2], [3, 4]])\n\n\n\n```python\n## Matrix transpose\nB = AA.T\n```\n\n\n```python\nB\n```\n\n\n```python\n# Matrix multiplication\nM = Matrix([[1,2,3],[4,5,6]])\n```\n\n\n```python\nM\n```\n\n\n```python\nN = M.T\n```\n\n\n```python\nN\n```\n\n\n```python\nMN = M*N\n```\n\n\n```python\nMN\n```\n\n\n```python\n# shape of the metrix. Number of rows and columns.\nM.shape\n```\n\n\n```python\nMN.shape\n```\n\n\n```python\n# accessing entries\nM = Matrix([[1,2,3],[4,5,6]])\n```\n\n\n```python\nM\n```\n\n\n```python\nM.row(0)\n```\n\n\n```python\nM.col(1)\n```\n\n\n```python\n# last column\nM.col(-1)\n```\n\n\n```python\nM[:,1]\n```\n\n\n```python\nM[0,:]\n```\n\n\n```python\n# insert row/col after a particular row/col\nM = M.row_insert(1,Matrix([[0,4,9]]))\n```\n\n\n```python\nM\n```\n\n\n```python\nN = 2*M\n```\n\n\n```python\nN\n```\n\n\n```python\nN**2\n```\n\n\n```python\nN**-1\n```\n\n\n```python\nNNinv = N.inv()\n```\n\n\n```python\nNNinv\n```\n\n\n```python\n# determinant of a matrix\nNdet = N.det()\n```\n\n\n```python\nNdet\n```\n\n\n```python\nNNinv.det()\n```\n\n\n```python\n# matrix constructors\nI = eye(4)\n```\n\n\n```python\nI\n```\n\n\n```python\nZ = zeros(3,4)\n```\n\n\n```python\nZ\n```\n\n\n```python\nones(2,3)\n```\n\n\n```python\nA = Matrix([[1,-1,0],[-1,2,-1],[0,-1,1]])\nA\n```\n\n\n```python\nA.eigenvals()\n```\n\n\n```python\nA.eigenvects()\n```\n\n\n```python\n# diagonalisation A = P*D*Pinv\nP, D = A.diagonalize()\n```\n\n\n```python\nD\n```\n\n\n```python\nP\n```\n\n\n```python\nP*D*P**-1 == A\n```\n\n\n\n\n True\n\n\n\n\n```python\n# characteristic polynomials\nlamda = symbols('lamda')\n```\n\n\n```python\np = A.charpoly(lamda)\n```\n\n\n```python\np\n```\n\n\n```python\nfactor(p)\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "772a6bc44cf940ac85298c2f4b2949f9646b37e1", "size": 53358, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "5-matrices.ipynb", "max_stars_repo_name": "chennachaos/SA2CTechChatSymPy", "max_stars_repo_head_hexsha": "9f1dbb48655ff5f8bdd6b4ced48b58aed0ba5bf4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "5-matrices.ipynb", "max_issues_repo_name": "chennachaos/SA2CTechChatSymPy", "max_issues_repo_head_hexsha": "9f1dbb48655ff5f8bdd6b4ced48b58aed0ba5bf4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "5-matrices.ipynb", "max_forks_repo_name": "chennachaos/SA2CTechChatSymPy", "max_forks_repo_head_hexsha": "9f1dbb48655ff5f8bdd6b4ced48b58aed0ba5bf4", "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": 49.0873965041, "max_line_length": 4616, "alphanum_fraction": 0.7484163574, "converted": true, "num_tokens": 688, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966717067252, "lm_q2_score": 0.9273633016692238, "lm_q1q2_score": 0.877839014823047}} {"text": "Create python definitions of the following 5 functions and their derivatives:\n\n$f(x) = ln(x^3)$\n\n$f(x) = exp(x^{1/3})$\n\n$f(x) = x^2 sin(x)$\n\n$f(x) = \\frac{\\sqrt{2}}{sin(x) cos(x)}$\n\n$f(x) = \\sigma(x)$ // this is the sigmoid function, important historically for neural nets\n\n\n```\n# LAMBDA SCHOOL\n#\n# MACHINE LEARNING\n#\n# MIT LICENSE\n\n# Your code goes here...\n```\n\nPlot the above five functions each on separate plots.\n\n\n```\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# Your code goes here\n\ndef f_1(x):\n return np.log(np.power(x, 3))\n\ndef f_2(x):\n return np.exp(np.cbrt(x))\n\ndef f_3(x):\n return x**2 * np.sin(x)\n\ndef f_4(x):\n return np.sqrt(2) / (np.sin(x) * np.cos(x))\n\ndef f_5(x):\n return 1 / (1 + np.exp(-x))\n\nx = np.linspace(-10, 10, 5000)\n\ny = f_1(x)\nplt.plot(x, y);\nplt.show()\n\ny = f_2(x)\nplt.plot(x, y);\nplt.show()\n\ny = f_3(x)\nplt.plot(x, y);\nplt.show()\n\ny = f_4(x)\nupper_lim = 100\nlower_lim = -100\ny[y>upper_lim] = np.inf\ny[y0 $\n\nWhile the derivative of f_1(x) approaches zero as x approaches infinity, it is never equal to zero.\n\n---\n\n$ \\frac{df_2(x)}{dx} = exp(x^{1/3}) * \\frac{d}{dx}(x^{1/3}) $ \n\n$ = exp(x^{1/3}) * \\frac{x^{-2/3}}{3} $\n\n$ = \\frac{exp(x^{1/3})}{3x^{2/3}}, x \\neq 0 $ \n\nThe derivative of f_2(x) is never equal to zero.\n\n---\n\n$ \\frac{df_3(x)}{dx} = x^2 \\frac{d}{dx}(sin(x)) + sin(x)\\frac{d}{dx}(x^2) $\n\n$ = x^2 cos(x) + 2xsin(x) $\n\nThis derivative function has infinitely many zeros. One at x = 0, and then more whenever $x^2 cos(x) = 2xsin(x)$, or in other terms, $\\frac{tan(x)}{x} = \\frac{1}{2}$ Since the tangent function is periodic and cycles through all the real numbers, there are infinitely many instances of this.\n\n---\n\n$ \\frac{df_4(x)}{dx} = \\sqrt{2} \\frac{-1}{sin^2(x)cos^2(x)}\\frac{d}{dx}(sin(x)cos(x)) $\n\n$ = \\sqrt{2} \\frac{-1}{sin^2(x)cos^2(x)} (-sin^2(x) + cos^2(x)) $\n\n$ = \\sqrt{2} \\frac{sin^2(x) - cos^2(x)}{sin^2(x)cos^2(x)} $\n\n$ = \\sqrt{2}(sec^2(x) - csc^2(x)) $\n\nThis derivative is equal to zero whenever $ sec^2(x) = cos^2(x) $, which is equivalent to whenever $ |sin(x)| = |cos(x)| $.\nThis happens whenever $ x = n\\pi - \\frac{\\pi}{4}, x = n\\pi - \\frac{3\\pi}{4} $ so there are infinitely many zeros.\n\n---\n\n$ \\frac{df_4(x)}{dx} = \\frac{-1}{(1 + exp(-x))^2} \\frac{d}{dx}(1 + exp(-x))$\n\n$ = \\frac{-1}{(1 + exp(-x))^2} (-exp(-x)) $\n\n$ = \\frac{exp(-x)}{(1 + exp(-x))^2} $\n\nThe sigmoid function has derivatives that approach zero as x approaches infinity, and as x approaches negative infinity, but nowhere does the derivative equal exactly zero.\n\n\n```\nimport sympy as sym\n\ndef my_ln_prime(a):\n x = sym.Symbol('x')\n y = sym.log(x**3)\n yprime = y.diff(x)\n \n f = sym.lambdify(x, yprime)\n return f(a)\n\nmy_ln_prime(1)\n```\n\n\n\n\n 3.0\n\n\n", "meta": {"hexsha": "e22c061779a3f241240e0682adc8bc980cd0606f", "size": 116458, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Week 01 Mathematical Foundations/Function Optimization.ipynb", "max_stars_repo_name": "rayheberer/LambdaCodingChallenges", "max_stars_repo_head_hexsha": "ae73493f2161264a0c39b809347e0ccea9576e51", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 29, "max_stars_repo_stars_event_min_datetime": "2018-04-18T07:43:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-13T17:24:24.000Z", "max_issues_repo_path": "Week 01 Mathematical Foundations/Function Optimization.ipynb", "max_issues_repo_name": "SNOmad1/LambdaSchoolDataScience", "max_issues_repo_head_hexsha": "ae73493f2161264a0c39b809347e0ccea9576e51", "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 01 Mathematical Foundations/Function Optimization.ipynb", "max_forks_repo_name": "SNOmad1/LambdaSchoolDataScience", "max_forks_repo_head_hexsha": "ae73493f2161264a0c39b809347e0ccea9576e51", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 46, "max_forks_repo_forks_event_min_datetime": "2018-08-18T15:59:15.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-17T02:14:51.000Z", "avg_line_length": 328.9774011299, "max_line_length": 34812, "alphanum_fraction": 0.9086623504, "converted": true, "num_tokens": 1226, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475810629193, "lm_q2_score": 0.9304582579046466, "lm_q1q2_score": 0.8777455468743663}} {"text": "# Transformations, Eigenvectors, and Eigenvalues\n\nMatrices and vectors are used together to manipulate spatial dimensions. This has a lot of applications, including the mathematical generation of 3D computer graphics, geometric modeling, and the training and optimization of machine learning algorithms. We're not going to cover the subject exhaustively here; but we'll focus on a few key concepts that are useful to know when you plan to work with machine learning.\n\n## Linear Transformations\nYou can manipulate a vector by multiplying it with a matrix. The matrix acts a function that operates on an input vector to produce a vector output. Specifically, matrix multiplications of vectors are *linear transformations* that transform the input vector into the output vector.\n\nFor example, consider this matrix ***A*** and vector ***v***:\n\n$$ A = \\begin{bmatrix}2 & 3\\\\5 & 2\\end{bmatrix} \\;\\;\\;\\; \\vec{v} = \\begin{bmatrix}1\\\\2\\end{bmatrix}$$\n\nWe can define a transformation ***T*** like this:\n\n$$ T(\\vec{v}) = A\\vec{v} $$\n\nTo perform this transformation, we simply calculate the dot product by applying the *RC* rule; multiplying each row of the matrix by the single column of the vector:\n\n$$\\begin{bmatrix}2 & 3\\\\5 & 2\\end{bmatrix} \\cdot \\begin{bmatrix}1\\\\2\\end{bmatrix} = \\begin{bmatrix}8\\\\9\\end{bmatrix}$$\n\nHere's the calculation in Python:\n\n\n```python\nimport numpy as np\n\nv = np.array([1,2])\nA = np.array([[2,3],\n [5,2]])\n\nt = A@v\nprint (t)\n```\n\n [8 9]\n\n\nIn this case, both the input vector and the output vector have 2 components - in other words, the transformation takes a 2-dimensional vector and produces a new 2-dimensional vector; which we can indicate like this:\n\n$$ T: \\rm I\\!R^{2} \\to \\rm I\\!R^{2} $$\n\nNote that the output vector may have a different number of dimensions from the input vector; so the matrix function might transform the vector from one space to another - or in notation, ${\\rm I\\!R}$n -> ${\\rm I\\!R}$m.\n\nFor example, let's redefine matrix ***A***, while retaining our original definition of vector ***v***:\n\n$$ A = \\begin{bmatrix}2 & 3\\\\5 & 2\\\\1 & 1\\end{bmatrix} \\;\\;\\;\\; \\vec{v} = \\begin{bmatrix}1\\\\2\\end{bmatrix}$$\n\nNow if we once again define ***T*** like this:\n\n$$ T(\\vec{v}) = A\\vec{v} $$\n\nWe apply the transformation like this:\n\n$$\\begin{bmatrix}2 & 3\\\\5 & 2\\\\1 & 1\\end{bmatrix} \\cdot \\begin{bmatrix}1\\\\2\\end{bmatrix} = \\begin{bmatrix}8\\\\9\\\\3\\end{bmatrix}$$\n\nSo now, our transformation transforms the vector from 2-dimensional space to 3-dimensional space:\n\n$$ T: \\rm I\\!R^{2} \\to \\rm I\\!R^{3} $$\n\nHere it is in Python:\n\n\n```python\nimport numpy as np\nv = np.array([1,2])\nA = np.array([[2,3],\n [5,2],\n [1,1]])\n\nt = A@v\nprint (t)\n```\n\n [8 9 3]\n\n\n\n```python\nimport numpy as np\nv = np.array([1,2])\nA = np.array([[1,2],\n [2,1]])\n\nt = A@v\nprint (t)\n```\n\n [5 4]\n\n\n## Transformations of Magnitude and Amplitude\n\nWhen you multiply a vector by a matrix, you transform it in at least one of the following two ways:\n* Scale the length (*magnitude*) of the matrix to make it longer or shorter\n* Change the direction (*amplitude*) of the matrix\n\nFor example consider the following matrix and vector:\n\n$$ A = \\begin{bmatrix}2 & 0\\\\0 & 2\\end{bmatrix} \\;\\;\\;\\; \\vec{v} = \\begin{bmatrix}1\\\\0\\end{bmatrix}$$\n\nAs before, we transform the vector ***v*** by multiplying it with the matrix ***A***:\n\n\\begin{equation}\\begin{bmatrix}2 & 0\\\\0 & 2\\end{bmatrix} \\cdot \\begin{bmatrix}1\\\\0\\end{bmatrix} = \\begin{bmatrix}2\\\\0\\end{bmatrix}\\end{equation}\n\nIn this case, the resulting vector has changed in length (*magnitude*), but has not changed its direction (*amplitude*).\n\nLet's visualize that in Python:\n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\nv = np.array([1,0])\nA = np.array([[2,0],\n [0,2]])\n\nt = A@v\nprint (t)\n\n# Plot v and t\nvecs = np.array([t,v])\norigin = [0], [0]\nplt.axis('equal')\nplt.grid()\nplt.ticklabel_format(style='sci', axis='both', scilimits=(0,0))\nplt.quiver(*origin, *v, color=['blue'], scale=10)\nplt.quiver(*origin, *t, color=['orange'], scale=10)\nplt.show()\n```\n\nThe original vector ***v*** is shown in orange, and the transformed vector ***t*** is shown in blue - note that ***t*** has the same direction (*amplitude*) as ***v*** but a greater length (*magnitude*).\n\nNow let's use a different matrix to transform the vector ***v***:\n\\begin{equation}\\begin{bmatrix}0 & -1\\\\1 & 0\\end{bmatrix} \\cdot \\begin{bmatrix}1\\\\0\\end{bmatrix} = \\begin{bmatrix}0\\\\1\\end{bmatrix}\\end{equation}\n\nThis time, the resulting vector has been changed to a different amplitude, but has the same magnitude.\n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\nv = np.array([1,0])\nA = np.array([[0,-1],\n [1,0]])\n\nt = A@v\nprint (t)\n\n# Plot v and t\nvecs = np.array([v,t])\norigin = [0], [0]\nplt.axis('equal')\nplt.grid()\nplt.ticklabel_format(style='sci', axis='both', scilimits=(0,0))\nplt.quiver(*origin, *v, color=['orange'], scale=10)\nplt.quiver(*origin, *t, color=['blue'], scale=10)\nplt.show()\n```\n\nNow let's see change the matrix one more time:\n\\begin{equation}\\begin{bmatrix}2 & 1\\\\1 & 2\\end{bmatrix} \\cdot \\begin{bmatrix}1\\\\0\\end{bmatrix} = \\begin{bmatrix}2\\\\1\\end{bmatrix}\\end{equation}\n\nNow our resulting vector has been transformed to a new amplitude *and* magnitude - the transformation has affected both direction and scale.\n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\nv = np.array([1,0])\nA = np.array([[2,1],\n [1,2]])\n\nt = A@v\nprint (t)\n\n# Plot v and t\nvecs = np.array([v,t])\norigin = [0], [0]\nplt.axis('equal')\nplt.grid()\nplt.ticklabel_format(style='sci', axis='both', scilimits=(0,0))\nplt.quiver(*origin, *v, color=['orange'], scale=10)\nplt.quiver(*origin, *t, color=['blue'], scale=10)\nplt.show()\n```\n\n### Afine Transformations\nAn Afine transformation multiplies a vector by a matrix and adds an offset vector, sometimes referred to as *bias*; like this:\n\n$$T(\\vec{v}) = A\\vec{v} + \\vec{b}$$\n\nFor example:\n\n\\begin{equation}\\begin{bmatrix}5 & 2\\\\3 & 1\\end{bmatrix} \\cdot \\begin{bmatrix}1\\\\1\\end{bmatrix} + \\begin{bmatrix}-2\\\\-6\\end{bmatrix} = \\begin{bmatrix}5\\\\-2\\end{bmatrix}\\end{equation}\n\nThis kind of transformation is actually the basis of linear regression, which is a core foundation for machine learning. The matrix defines the *features*, the first vector is the *coefficients*, and the bias vector is the *intercept*.\n\nhere's an example of an Afine transformation in Python:\n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\nv = np.array([1,1])\nA = np.array([[5,2],\n [3,1]])\nb = np.array([-2,-6])\n\nt = A@v + b\nprint (t)\n\n# Plot v and t\nvecs = np.array([v,t])\norigin = [0], [0]\nplt.axis('equal')\nplt.grid()\nplt.ticklabel_format(style='sci', axis='both', scilimits=(0,0))\nplt.quiver(*origin, *v, color=['orange'], scale=15)\nplt.quiver(*origin, *t, color=['blue'], scale=15)\nplt.show()\n```\n\n## Eigenvectors and Eigenvalues\nSo we can see that when you transform a vector using a matrix, we change its direction, length, or both. When the transformation only affects scale (in other words, the output vector has a different magnitude but the same amplitude as the input vector), the matrix multiplication for the transformation is the equivalent operation as some scalar multiplication of the vector.\n\nFor example, earlier we examined the following transformation that dot-mulitplies a vector by a matrix:\n\n$$\\begin{bmatrix}2 & 0\\\\0 & 2\\end{bmatrix} \\cdot \\begin{bmatrix}1\\\\0\\end{bmatrix} = \\begin{bmatrix}2\\\\0\\end{bmatrix}$$\n\nYou can achieve the same result by mulitplying the vector by the scalar value ***2***:\n\n$$2 \\times \\begin{bmatrix}1\\\\0\\end{bmatrix} = \\begin{bmatrix}2\\\\0\\end{bmatrix}$$\n\nThe following python performs both of these calculation and shows the results, which are identical.\n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\nv = np.array([1,0])\nA = np.array([[2,0],\n [0,2]])\n\nt1 = A@v\nprint (t1)\nt2 = 2*v\nprint (t2)\n\nfig = plt.figure()\na=fig.add_subplot(1,1,1)\n# Plot v and t1\nvecs = np.array([t1,v])\norigin = [0], [0]\nplt.axis('equal')\nplt.grid()\nplt.ticklabel_format(style='sci', axis='both', scilimits=(0,0))\nplt.quiver(*origin, *v, color=['orange'], scale=10)\nplt.quiver(*origin, *t1, color=['blue'], scale=10)\nplt.show()\na=fig.add_subplot(1,2,1)\n# Plot v and t2\nvecs = np.array([t2,v])\norigin = [0], [0]\nplt.axis('equal')\nplt.grid()\nplt.ticklabel_format(style='sci', axis='both', scilimits=(0,0))\nplt.quiver(*origin, *v, color=['orange'], scale=10)\nplt.quiver(*origin, *t2, color=['blue'], scale=10)\nplt.show()\n```\n\nIn cases like these, where a matrix transformation is the equivelent of a scalar-vector multiplication, the scalar-vector pairs that correspond to the matrix are known respectively as eigenvalues and eigenvectors. We generally indicate eigenvalues using the Greek letter lambda (λ), and the formula that defines eigenvalues and eigenvectors with respect to a transformation is:\n\n$$ T(\\vec{v}) = \\lambda\\vec{v}$$\n\nWhere the vector ***v*** is an eigenvector and the value ***λ*** is an eigenvalue for transformation ***T***.\n\nWhen the transformation ***T*** is represented as a matrix multiplication, as in this case where the transformation is represented by matrix ***A***:\n\n$$ T(\\vec{v}) = A\\vec{v} = \\lambda\\vec{v}$$\n\nThen ***v*** is an eigenvector and ***λ*** is an eigenvalue of ***A***.\n\nA matrix can have multiple eigenvector-eigenvalue pairs, and you can calculate them manually. However, it's generally easier to use a tool or programming language. For example, in Python you can use the ***linalg.eig*** function, which returns an array of eigenvalues and a matrix of the corresponding eigenvectors for the specified matrix.\n\nHere's an example that returns the eigenvalue and eigenvector pairs for the following matrix:\n\n$$A=\\begin{bmatrix}2 & 0\\\\0 & 3\\end{bmatrix}$$\n\n\n```python\nimport numpy as np\nA = np.array([[2,0],\n [0,3]])\neVals, eVecs = np.linalg.eig(A)\nprint(eVals)\nprint(eVecs)\n```\n\n [2. 3.]\n [[1. 0.]\n [0. 1.]]\n\n\nSo there are two eigenvalue-eigenvector pairs for this matrix, as shown here:\n\n$$ \\lambda_{1} = 2, \\vec{v_{1}} = \\begin{bmatrix}1 \\\\ 0\\end{bmatrix} \\;\\;\\;\\;\\;\\; \\lambda_{2} = 3, \\vec{v_{2}} = \\begin{bmatrix}0 \\\\ 1\\end{bmatrix} $$\n\nLet's verify that multiplying each eigenvalue-eigenvector pair corresponds to the dot-product of the eigenvector and the matrix. Here's the first pair:\n\n$$ 2 \\times \\begin{bmatrix}1 \\\\ 0\\end{bmatrix} = \\begin{bmatrix}2 \\\\ 0\\end{bmatrix} \\;\\;\\;and\\;\\;\\; \\begin{bmatrix}2 & 0\\\\0 & 3\\end{bmatrix} \\cdot \\begin{bmatrix}1 \\\\ 0\\end{bmatrix} = \\begin{bmatrix}2 \\\\ 0\\end{bmatrix} $$\n\nSo far so good. Now let's check the second pair:\n\n$$ 3 \\times \\begin{bmatrix}0 \\\\ 1\\end{bmatrix} = \\begin{bmatrix}0 \\\\ 3\\end{bmatrix} \\;\\;\\;and\\;\\;\\; \\begin{bmatrix}2 & 0\\\\0 & 3\\end{bmatrix} \\cdot \\begin{bmatrix}0 \\\\ 1\\end{bmatrix} = \\begin{bmatrix}0 \\\\ 3\\end{bmatrix} $$\n\nSo our eigenvalue-eigenvector scalar multiplications do indeed correspond to our matrix-eigenvector dot-product transformations.\n\nHere's the equivalent code in Python, using the ***eVals*** and ***eVecs*** variables you generated in the previous code cell:\n\n\n```python\nvec1 = eVecs[:,0]\nlam1 = eVals[0]\n\nprint('Matrix A:')\nprint(A)\nprint('-------')\n\nprint('lam1: ' + str(lam1))\nprint ('v1: ' + str(vec1))\nprint ('Av1: ' + str(A@vec1))\nprint ('lam1 x v1: ' + str(lam1*vec1))\n\nprint('-------')\n\nvec2 = eVecs[:,1]\nlam2 = eVals[1]\n\nprint('lam2: ' + str(lam2))\nprint ('v2: ' + str(vec2))\nprint ('Av2: ' + str(A@vec2))\nprint ('lam2 x v2: ' + str(lam2*vec2))\n```\n\n Matrix A:\n [[2 0]\n [0 3]]\n -------\n lam1: 2.0\n v1: [1. 0.]\n Av1: [2. 0.]\n lam1 x v1: [2. 0.]\n -------\n lam2: 3.0\n v2: [0. 1.]\n Av2: [0. 3.]\n lam2 x v2: [0. 3.]\n\n\nYou can use the following code to visualize these transformations:\n\n\n```python\nt1 = lam1*vec1\nprint (t1)\nt2 = lam2*vec2\nprint (t2)\n\nfig = plt.figure()\na=fig.add_subplot(1,1,1)\n# Plot v and t1\nvecs = np.array([t1,vec1])\norigin = [0], [0]\nplt.axis('equal')\nplt.grid()\nplt.ticklabel_format(style='sci', axis='both', scilimits=(0,0))\nplt.quiver(*origin, *v, color=['orange'], scale=10)\nplt.quiver(*origin, *t1, color=['blue'], scale=10)\nplt.show()\na=fig.add_subplot(1,2,1)\n# Plot v and t2\nvecs = np.array([t2,vec2])\norigin = [0], [0]\nplt.axis('equal')\nplt.grid()\nplt.ticklabel_format(style='sci', axis='both', scilimits=(0,0))\nplt.quiver(*origin, *v, color=['orange'], scale=10)\nplt.quiver(*origin, *t2, color=['blue'], scale=10)\nplt.show()\n```\n\nSimilarly, earlier we examined the following matrix transformation:\n\n$$\\begin{bmatrix}2 & 0\\\\0 & 2\\end{bmatrix} \\cdot \\begin{bmatrix}1\\\\0\\end{bmatrix} = \\begin{bmatrix}2\\\\0\\end{bmatrix}$$\n\nAnd we saw that you can achieve the same result by mulitplying the vector by the scalar value ***2***:\n\n$$2 \\times \\begin{bmatrix}1\\\\0\\end{bmatrix} = \\begin{bmatrix}2\\\\0\\end{bmatrix}$$\n\nThis works because the scalar value 2 and the vector (1,0) are an eigenvalue-eigenvector pair for this matrix.\n\nLet's use Python to determine the eigenvalue-eigenvector pairs for this matrix:\n\n\n```python\nimport numpy as np\nA = np.array([[2,0],\n [0,2]])\neVals, eVecs = np.linalg.eig(A)\nprint(eVals)\nprint(eVecs)\n```\n\n [2. 2.]\n [[1. 0.]\n [0. 1.]]\n\n\nSo once again, there are two eigenvalue-eigenvector pairs for this matrix, as shown here:\n\n$$ \\lambda_{1} = 2, \\vec{v_{1}} = \\begin{bmatrix}1 \\\\ 0\\end{bmatrix} \\;\\;\\;\\;\\;\\; \\lambda_{2} = 2, \\vec{v_{2}} = \\begin{bmatrix}0 \\\\ 1\\end{bmatrix} $$\n\nLet's verify that multiplying each eigenvalue-eigenvector pair corresponds to the dot-product of the eigenvector and the matrix. Here's the first pair:\n\n$$ 2 \\times \\begin{bmatrix}1 \\\\ 0\\end{bmatrix} = \\begin{bmatrix}2 \\\\ 0\\end{bmatrix} \\;\\;\\;and\\;\\;\\; \\begin{bmatrix}2 & 0\\\\0 & 2\\end{bmatrix} \\cdot \\begin{bmatrix}1 \\\\ 0\\end{bmatrix} = \\begin{bmatrix}2 \\\\ 0\\end{bmatrix} $$\n\nWell, we already knew that. Now let's check the second pair:\n\n$$ 2 \\times \\begin{bmatrix}0 \\\\ 1\\end{bmatrix} = \\begin{bmatrix}0 \\\\ 2\\end{bmatrix} \\;\\;\\;and\\;\\;\\; \\begin{bmatrix}2 & 0\\\\0 & 2\\end{bmatrix} \\cdot \\begin{bmatrix}0 \\\\ 1\\end{bmatrix} = \\begin{bmatrix}0 \\\\ 2\\end{bmatrix} $$\n\nNow let's use Pythonto verify and plot these transformations:\n\n\n```python\nvec1 = eVecs[:,0]\nlam1 = eVals[0]\n\nprint('Matrix A:')\nprint(A)\nprint('-------')\n\nprint('lam1: ' + str(lam1))\nprint ('v1: ' + str(vec1))\nprint ('Av1: ' + str(A@vec1))\nprint ('lam1 x v1: ' + str(lam1*vec1))\n\nprint('-------')\n\nvec2 = eVecs[:,1]\nlam2 = eVals[1]\n\nprint('lam2: ' + str(lam2))\nprint ('v2: ' + str(vec2))\nprint ('Av2: ' + str(A@vec2))\nprint ('lam2 x v2: ' + str(lam2*vec2))\n\n\n# Plot the resulting vectors\nt1 = lam1*vec1\nt2 = lam2*vec2\n\nfig = plt.figure()\na=fig.add_subplot(1,1,1)\n# Plot v and t1\nvecs = np.array([t1,vec1])\norigin = [0], [0]\nplt.axis('equal')\nplt.grid()\nplt.ticklabel_format(style='sci', axis='both', scilimits=(0,0))\nplt.quiver(*origin, *v, color=['orange'], scale=10)\nplt.quiver(*origin, *t1, color=['blue'], scale=10)\nplt.show()\na=fig.add_subplot(1,2,1)\n# Plot v and t2\nvecs = np.array([t2,vec2])\norigin = [0], [0]\nplt.axis('equal')\nplt.grid()\nplt.ticklabel_format(style='sci', axis='both', scilimits=(0,0))\nplt.quiver(*origin, *v, color=['orange'], scale=10)\nplt.quiver(*origin, *t2, color=['blue'], scale=10)\nplt.show()\n```\n\nLet's take a look at one more, slightly more complex example. Here's our matrix:\n\n$$\\begin{bmatrix}2 & 1\\\\1 & 2\\end{bmatrix}$$\n\nLet's get the eigenvalue and eigenvector pairs:\n\n\n```python\nimport numpy as np\n\nA = np.array([[2,1],\n [1,2]])\n\neVals, eVecs = np.linalg.eig(A)\nprint(eVals)\nprint(eVecs)\n```\n\n [3. 1.]\n [[ 0.70710678 -0.70710678]\n [ 0.70710678 0.70710678]]\n\n\nThis time the eigenvalue-eigenvector pairs are:\n\n$$ \\lambda_{1} = 3, \\vec{v_{1}} = \\begin{bmatrix}0.70710678 \\\\ 0.70710678\\end{bmatrix} \\;\\;\\;\\;\\;\\; \\lambda_{2} = 1, \\vec{v_{2}} = \\begin{bmatrix}-0.70710678 \\\\ 0.70710678\\end{bmatrix} $$\n\nSo let's check the first pair:\n\n$$ 3 \\times \\begin{bmatrix}0.70710678 \\\\ 0.70710678\\end{bmatrix} = \\begin{bmatrix}2.12132034 \\\\ 2.12132034\\end{bmatrix} \\;\\;\\;and\\;\\;\\; \\begin{bmatrix}2 & 1\\\\0 & 2\\end{bmatrix} \\cdot \\begin{bmatrix}0.70710678 \\\\ 0.70710678\\end{bmatrix} = \\begin{bmatrix}2.12132034 \\\\ 2.12132034\\end{bmatrix} $$\n\nNow let's check the second pair:\n\n$$ 1 \\times \\begin{bmatrix}-0.70710678 \\\\ 0.70710678\\end{bmatrix} = \\begin{bmatrix}-0.70710678\\\\0.70710678\\end{bmatrix} \\;\\;\\;and\\;\\;\\; \\begin{bmatrix}2 & 1\\\\1 & 2\\end{bmatrix} \\cdot \\begin{bmatrix}-0.70710678 \\\\ 0.70710678\\end{bmatrix} = \\begin{bmatrix}-0.70710678\\\\0.70710678\\end{bmatrix} $$\n\nWith more complex examples like this, it's generally easier to do it with Python:\n\n\n```python\nvec1 = eVecs[:,0]\nlam1 = eVals[0]\n\nprint('Matrix A:')\nprint(A)\nprint('-------')\n\nprint('lam1: ' + str(lam1))\nprint ('v1: ' + str(vec1))\nprint ('Av1: ' + str(A@vec1))\nprint ('lam1 x v1: ' + str(lam1*vec1))\n\nprint('-------')\n\nvec2 = eVecs[:,1]\nlam2 = eVals[1]\n\nprint('lam2: ' + str(lam2))\nprint ('v2: ' + str(vec2))\nprint ('Av2: ' + str(A@vec2))\nprint ('lam2 x v2: ' + str(lam2*vec2))\n\n\n# Plot the results\nt1 = lam1*vec1\nt2 = lam2*vec2\n\nfig = plt.figure()\na=fig.add_subplot(1,1,1)\n# Plot v and t1\nvecs = np.array([t1,vec1])\norigin = [0], [0]\nplt.axis('equal')\nplt.grid()\nplt.ticklabel_format(style='sci', axis='both', scilimits=(0,0))\nplt.quiver(*origin, *v, color=['orange'], scale=10)\nplt.quiver(*origin, *t1, color=['blue'], scale=10)\nplt.show()\na=fig.add_subplot(1,2,1)\n# Plot v and t2\nvecs = np.array([t2,vec2])\norigin = [0], [0]\nplt.axis('equal')\nplt.grid()\nplt.ticklabel_format(style='sci', axis='both', scilimits=(0,0))\nplt.quiver(*origin, *v, color=['orange'], scale=10)\nplt.quiver(*origin, *t2, color=['blue'], scale=10)\nplt.show()\n```\n\n## Eigendecomposition\nSo we've learned a little about eigenvalues and eigenvectors; but you may be wondering what use they are. Well, one use for them is to help decompose transformation matrices.\n\nRecall that previously we found that a matrix transformation of a vector changes its magnitude, amplitude, or both. Without getting too technical about it, we need to remember that vectors can exist in any spatial orientation, or *basis*; and the same transformation can be applied in different *bases*.\n\nWe can decompose a matrix using the following formula:\n\n$$A = Q \\Lambda Q^{-1}$$\n\nWhere ***A*** is a trasformation that can be applied to a vector in its current base, ***Q*** is a matrix of eigenvectors that defines a change of basis, and ***Λ*** is a matrix with eigenvalues on the diagonal that defines the same linear transformation as ***A*** in the base defined by ***Q***.\n\nLet's look at these in some more detail. Consider this matrix:\n\n$$A=\\begin{bmatrix}3 & 2\\\\1 & 0\\end{bmatrix}$$\n\n***Q*** is a matrix in which each column is an eigenvector of ***A***; which as we've seen previously, we can calculate using Python:\n\n\n```python\nimport numpy as np\n\nA = np.array([[3,2],\n [1,0]])\n\nl, Q = np.linalg.eig(A)\nprint(Q)\n```\n\n [[ 0.96276969 -0.48963374]\n [ 0.27032301 0.87192821]]\n\n\nSo for matrix ***A***, ***Q*** is the following matrix:\n\n$$Q=\\begin{bmatrix}0.96276969 & -0.48963374\\\\0.27032301 & 0.87192821\\end{bmatrix}$$\n\n***Λ*** is a matrix that contains the eigenvalues for ***A*** on the diagonal, with zeros in all other elements; so for a 2x2 matrix, Λ will look like this:\n\n$$\\Lambda=\\begin{bmatrix}\\lambda_{1} & 0\\\\0 & \\lambda_{2}\\end{bmatrix}$$\n\nIn our Python code, we've already used the ***linalg.eig*** function to return the array of eigenvalues for ***A*** into the variable ***l***, so now we just need to format that as a matrix:\n\n\n```python\nL = np.diag(l)\nprint (L)\n```\n\n [[ 3.56155281 0. ]\n [ 0. -0.56155281]]\n\n\nSo ***Λ*** is the following matrix:\n\n$$\\Lambda=\\begin{bmatrix}3.56155281 & 0\\\\0 & -0.56155281\\end{bmatrix}$$\n\nNow we just need to find ***Q-1***, which is the inverse of ***Q***:\n\n\n```python\nQinv = np.linalg.inv(Q)\nprint(Qinv)\n```\n\n [[ 0.89720673 0.50382896]\n [-0.27816009 0.99068183]]\n\n\nThe inverse of ***Q*** then, is:\n\n$$Q^{-1}=\\begin{bmatrix}0.89720673 & 0.50382896\\\\-0.27816009 & 0.99068183\\end{bmatrix}$$\n\nSo what does that mean? Well, it means that we can decompose the transformation of *any* vector multiplied by matrix ***A*** into the separate operations ***QΛQ-1***:\n\n$$A\\vec{v} = Q \\Lambda Q^{-1}\\vec{v}$$\n\nTo prove this, let's take vector ***v***:\n\n$$\\vec{v} = \\begin{bmatrix}1\\\\3\\end{bmatrix} $$\n\nOur matrix transformation using ***A*** is:\n\n$$\\begin{bmatrix}3 & 2\\\\1 & 0\\end{bmatrix} \\cdot \\begin{bmatrix}1\\\\3\\end{bmatrix} $$\n\nSo let's show the results of that using Python:\n\n\n```python\nv = np.array([1,3])\nt = A@v\n\nprint(t)\n\n# Plot v and t\nvecs = np.array([v,t])\norigin = [0], [0]\nplt.axis('equal')\nplt.grid()\nplt.ticklabel_format(style='sci', axis='both', scilimits=(0,0))\nplt.quiver(*origin, *v, color=['orange'], scale=10)\nplt.quiver(*origin, *t, color=['blue'], scale=10)\nplt.show()\n```\n\nAnd now, let's do the same thing using the ***QΛQ-1*** sequence of operations:\n\n\n```python\nimport math\nimport numpy as np\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\nt = (Q@(L@(Qinv)))@v\n\n# Plot v and t\nvecs = np.array([v,t])\norigin = [0], [0]\nplt.axis('equal')\nplt.grid()\nplt.ticklabel_format(style='sci', axis='both', scilimits=(0,0))\nplt.quiver(*origin, *v, color=['orange'], scale=10)\nplt.quiver(*origin, *t, color=['blue'], scale=10)\nplt.show()\n```\n\nSo ***A*** and ***QΛQ-1*** are equivalent.\n\nIf we view the intermediary stages of the decomposed transformation, you can see the transformation using ***A*** in the original base for ***v*** (orange to blue) and the transformation using ***Λ*** in the change of basis decribed by ***Q*** (red to magenta):\n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\nt1 = Qinv@v\nt2 = L@t1\nt3 = Q@t2\n\n# Plot the transformations\nvecs = np.array([v,t1, t2, t3])\norigin = [0], [0]\nplt.axis('equal')\nplt.grid()\nplt.ticklabel_format(style='sci', axis='both', scilimits=(0,0))\nplt.quiver(*origin, *v, color=['orange'], scale=20)\nplt.quiver(*origin, *t1, color=['blue'], scale=20)\nplt.quiver(*origin, *t2, color=['red'], scale=20)\nplt.quiver(*origin, *t3, color=['magenta'], scale=20)\nplt.show()\n```\n\nSo from this visualization, it should be apparent that the transformation ***Av*** can be performed by changing the basis for ***v*** using ***Q*** (from orange to red in the above plot) applying the equivalent linear transformation in that base using ***Λ*** (red to magenta), and switching back to the original base using ***Q-1*** (magenta to blue).\n\n## Rank of a Matrix\n\nThe **rank** of a square matrix is the number of non-zero eigenvalues of the matrix. A **full rank** matrix has the same number of non-zero eigenvalues as the dimension of the matrix. A **rank-deficient** matrix has fewer non-zero eigenvalues as dimensions. The inverse of a rank deficient matrix is singular and so does not exist (this is why in a previous notebook we noted that some matrices have no inverse).\n\nConsider the following matrix ***A***:\n\n$$A=\\begin{bmatrix}1 & 2\\\\4 & 3\\end{bmatrix}$$\n\nLet's find its eigenvalues (***Λ***):\n\n\n```python\nimport numpy as np\nA = np.array([[1,2],\n [4,3]])\nl, Q = np.linalg.eig(A)\nL = np.diag(l)\nprint(L)\n```\n\n [[-1. 0.]\n [ 0. 5.]]\n\n\n$$\\Lambda=\\begin{bmatrix}-1 & 0\\\\0 & 5\\end{bmatrix}$$\n\nThis matrix has full rank. The dimensions of the matrix is 2. There are two non-zero eigenvalues. \n\nNow consider this matrix:\n\n$$B=\\begin{bmatrix}3 & -3 & 6\\\\2 & -2 & 4\\\\1 & -1 & 2\\end{bmatrix}$$\n\nNote that the second and third columns are just scalar multiples of the first column.\n\nLet's examine it's eigenvalues:\n\n\n```python\nB = np.array([[3,-3,6],\n [2,-2,4],\n [1,-1,2]])\nlb, Qb = np.linalg.eig(B)\nLb = np.diag(lb)\nprint(Lb)\n```\n\n [[ 3.00000000e+00 0.00000000e+00 0.00000000e+00]\n [ 0.00000000e+00 -6.00567308e-17 0.00000000e+00]\n [ 0.00000000e+00 0.00000000e+00 3.57375398e-16]]\n\n\n$$\\Lambda=\\begin{bmatrix}3 & 0& 0\\\\0 & -6\\times10^{-17} & 0\\\\0 & 0 & 3.6\\times10^{-16}\\end{bmatrix}$$\n\nNote that matrix has only 1 non-zero eigenvalue. The other two eigenvalues are so extremely small as to be effectively zero. This is an example of a rank-deficient matrix; and as such, it has no inverse.\n\n## Inverse of a Square Full Rank Matrix\nYou can calculate the inverse of a square full rank matrix by using the following formula:\n\n$$A^{-1} = Q \\Lambda^{-1} Q^{-1}$$\n\nLet's apply this to matrix ***A***:\n\n$$A=\\begin{bmatrix}1 & 2\\\\4 & 3\\end{bmatrix}$$\n\nLet's find the matrices for ***Q***, ***Λ-1***, and ***Q-1***:\n\n\n```python\nimport numpy as np\nA = np.array([[1,2],\n [4,3]])\n\nl, Q = np.linalg.eig(A)\nL = np.diag(l)\nprint(Q)\nLinv = np.linalg.inv(L)\nQinv = np.linalg.inv(Q)\nprint(Linv)\nprint(Qinv)\n```\n\n [[-0.70710678 -0.4472136 ]\n [ 0.70710678 -0.89442719]]\n [[-1. -0. ]\n [ 0. 0.2]]\n [[-0.94280904 0.47140452]\n [-0.74535599 -0.74535599]]\n\n\nSo:\n\n$$A^{-1}=\\begin{bmatrix}-0.70710678 & -0.4472136\\\\0.70710678 & -0.89442719\\end{bmatrix}\\cdot\\begin{bmatrix}-1 & -0\\\\0 & 0.2\\end{bmatrix}\\cdot\\begin{bmatrix}-0.94280904 & 0.47140452\\\\-0.74535599 & -0.74535599\\end{bmatrix}$$\n\nLet's calculate that in Python:\n\n\n```python\nAinv = (Q@(Linv@(Qinv)))\nprint(Ainv)\n```\n\n [[-0.6 0.4]\n [ 0.8 -0.2]]\n\n\nThat gives us the result:\n\n$$A^{-1}=\\begin{bmatrix}-0.6 & 0.4\\\\0.8 & -0.2\\end{bmatrix}$$\n\nWe can apply the ***np.linalg.inv*** function directly to ***A*** to verify this:\n\n\n```python\nprint(np.linalg.inv(A))\n```\n\n [[-0.6 0.4]\n [ 0.8 -0.2]]\n\n", "meta": {"hexsha": "a327d953e0a2f466925f6d82dd371ea0f009f851", "size": 150137, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "4_oreilly-book/code/ch13/ML-Math-Notebooks/Copy_of_03_05_Transformations_Eigenvectors_and_Eigenvalues.ipynb", "max_stars_repo_name": "lynnlangit/learning-quantum", "max_stars_repo_head_hexsha": "8da57597efe7e213b4368fc115d67e8b42b906c6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2021-02-10T10:20:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T05:21:30.000Z", "max_issues_repo_path": "4_oreilly-book/code/ch13/ML-Math-Notebooks/Copy_of_03_05_Transformations_Eigenvectors_and_Eigenvalues.ipynb", "max_issues_repo_name": "lynnlangit/learning-quantum", "max_issues_repo_head_hexsha": "8da57597efe7e213b4368fc115d67e8b42b906c6", "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_oreilly-book/code/ch13/ML-Math-Notebooks/Copy_of_03_05_Transformations_Eigenvectors_and_Eigenvalues.ipynb", "max_forks_repo_name": "lynnlangit/learning-quantum", "max_forks_repo_head_hexsha": "8da57597efe7e213b4368fc115d67e8b42b906c6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-03-23T13:34:24.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T18:51:00.000Z", "avg_line_length": 87.3397324026, "max_line_length": 8862, "alphanum_fraction": 0.7774765714, "converted": true, "num_tokens": 8544, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.970239909496136, "lm_q2_score": 0.9046505318875316, "lm_q1q2_score": 0.87772805018419}} {"text": "### Solution\n\n\n```python\n# Special command for plotting in jupyter notebooks\n%matplotlib inline\n```\n\nFirst import the required modules - `numpy` and `matplotlib`. \n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\n```\n\nInitially, it is good to have a look at our reference solution. Based on the given formula for the trajectory of the partical, we can work out the formula for its velocity as:\n\n\\begin{align}\nv_x &= -\\dfrac{1}{T_1}\\exp \\left( -\\dfrac{t}{T_1} \\right) \n\\\\\nv_y &= -\\dfrac{2}{T_2} \\sin \\left(\\dfrac{t}{T_2}\\right)\n\\end{align}\n\nand acceleration as:\n\n\\begin{align}\na_x &= \\dfrac{1}{T^2_1} \\exp \\left( -\\dfrac{t}{T_1} \\right) \n\\\\\na_y &= -\\dfrac{2}{T^2_2} \\cos\\left(\\dfrac{t}{T_2}\\right)\n\\end{align}\n\nWe declare our constants as followed.\n\n\n```python\n# Declare the time constants\nT1 = 1.0\nT2 = 1.0/3.0\n```\n\nThen initialise the array to store our reference results. Here, our positions, velocities and accelerations of the particles in time are stored as 2D array of vectors - the first column corresponds to the $x$ component, and the second the $y$ component. \n\n\n```python\n# Initialise array for position, velocity and acceleration\nnum_points = 500\nr_ref = np.zeros((num_points, 2))\nv_ref = np.zeros((num_points, 2))\na_ref = np.zeros((num_points, 2))\n\n# Generate the reference time vector\nt_ref = np.linspace(0, 2*np.pi, num_points)\n```\n\nThe results can be calculated using the formula provided above.\n\n\n```python\n# Calculate the x and y coordinates of the particle\nr_ref[:, 0] = np.exp(-t_ref/T1)\nr_ref[:, 1] = 2.0*np.cos(t_ref/T2)\n\n# Exact solution for velocity\nv_ref[:, 0] = -(1.0/T1)*np.exp(-t_ref/T1)\nv_ref[:, 1] = -(2.0/T2)*np.sin(t_ref/T2)\n\n# Exact solution for acceleration\na_ref[:, 0] = (1.0/(T1**2))*np.exp(-t_ref/T1)\na_ref[:, 1] = -(2.0/(T2**2))*np.cos(t_ref/T2)\n```\n\nWe can now plot the postion, velocity and acceleration fields.\n\n\n```python\n# Plot the solutions\n# Initilise the figure\nfig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(24, 6))\n\n# Plot the position\nax1.plot(r_ref[:, 0], r_ref[:, 1], linewidth=2.0)\nax1.set_title('Position')\nax1.set_xlabel('x')\nax1.set_ylabel('y')\n\n# Plot the velocity\nax2.plot(v_ref[:, 0], v_ref[:, 1], linewidth=2.0)\nax2.set_title('Velocity')\nax2.set_xlabel('x')\nax2.set_ylabel('y')\n\n# Plot the acceleration\nax3.plot(a_ref[:, 0], a_ref[:, 1], linewidth=2.0)\nax3.set_title('Acceleration')\nax3.set_xlabel('x')\nax3.set_ylabel('y');\n```\n\n### Numerical differentiation\n\n#### Forward difference method\n\nNow we assume that we only have a finite number of points for the location of the particle, `r`, in time. For this solution, we assume that we only have 20 data points, i.e. `num_points = 20`, for the particle's trajectory in time interval $t = 0 - 2 \\pi$s.\n\n\n```python\n# Generate our finite time vector, with 20 points\nnum_points = 20\nt = np.linspace(0, 2*np.pi, num_points)\n\n# Calculate the position used for the numerical term\nr_num = np.zeros((num_points, 2))\nr_num[:, 0] = np.exp(-t/T1)\nr_num[:, 1] = 2.0*np.cos(t/T2)\n```\n\nTo calculate the particles velocity and acceleration we need to calculate the first and second derivatives of its position, `r`, with respect to time. Reminds ourselve that here we only have discrete number of points, rather than a continuous function. Hence, a numerical scheme is required.\n\nPython offers the `np.diff()` comand to calculate the difference between consecutive elements in a `numpy` array. The resulting vector is one element shorter than the original, e.g. if `x=[1, 4, 3, 5]`, then `np.diff(x)` returns `[3, -1, 2]`. \n\nWith `dx = np.diff(x)` and `dt = np.diff(t)` the division `dx/dt` gives an approximation of the particle’s velocity in the x direction. The second derivative can be calculated using: \n\n np.diff(x,2)/(np.power(dt[0:num_points - 2], 2)\n\nwhere `np.diff(x,2)` is the second order difference of `x` – using the above example `np.diff(x,2)` returns `[-4, 3]`. \n\nFor our case, we need to apply the differentiation for the $x$ and $y$ direction of the position, which are stored in the first and the second column of `r`, respectively.\n\n\n```python\n# Initialise array for velocity and acceleration\n# calculated using forward difference method\nv_f = np.zeros((num_points-1, 2))\na_f = np.zeros((num_points-2, 2))\n\n# Forward difference method to calculate velocity\nv_f[:, 0] = np.diff(r_num[:, 0]) / np.diff(t)\nv_f[:, 1] = np.diff(r_num[:, 1]) / np.diff(t)\n# And then the acceleration\n# Calculate acceleration\na_f[:, 0] = np.diff(r_num[:, 0], 2) / (np.power(np.diff(t)[0:num_points-2], 2))\na_f[:, 1] = np.diff(r_num[:, 1], 2) / (np.power(np.diff(t)[0:num_points-2], 2))\n```\n\nWe can look at our forward difference scheme, with 20 data points, compared to the reference - 'smooth' - result. \n\n\n```python\n# Generate the subplots\nfig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(24, 6))\n\n# Plot the position\nax1.plot(r_num[:, 0], r_num[:, 1], linewidth=2.0, label='Forward')\nax1.plot(r_ref[:, 0], r_ref[:, 1], linewidth=2.0, label='Reference')\nax1.set_title('Position')\nax1.legend()\n\n# Plot the velocity\nax2.plot(v_f[:, 0], v_f[:, 1], linewidth=2.0, label='Forward')\nax2.plot(v_ref[:, 0], v_ref[:, 1], linewidth=2.0, label='Reference')\nax2.set_title('Velocity')\nax2.legend(loc=2)\n\n# Plot the acceleration\nax3.plot(a_f[:, 0], a_f[:, 1], linewidth=2.0, label='Forward')\nax3.plot(a_ref[:, 0], a_ref[:, 1], linewidth=2.0, label='Reference')\nax3.set_title('Acceleration')\nax3.legend();\n```\n\n#### Central difference method\n\nIn the forward difference method, the current velocity is calculated using the current and the following position. The current acceleration is calculated using the previous and next velocity. This leads to a *mismatch* between velocity on one hand and position and acceleration on the other by one timestep. The centre difference method allows to calculate velocities and accelerations at the same positions over the interval `[1, N-1]`. This method is implemented below, and full understanding is not required. \n\n\n```python\n# Initialise array for velocity and acceleration\n# calculated using central difference method\nv_c = np.zeros((num_points-1, 2))\na_c = np.zeros((num_points-2, 2))\n\n# Positions and time difference between adjacent\n# elements of position and time. The argument axis=0\n# indicates that we carry out np.diff on column-wise \n# of r\ndr = np.diff(r_num, axis=0)\ndt = np.diff(t)\n\n# Centre difference method\nfor i in range(1, num_points-1):\n v_c[i-1, :] = (dr[i, :] + dr[i-1, :])/(dt[i] + dt[i-1])\n a_c[i-1, :] = (dr[i, :]/dt[i] - dr[i-1, :]/dt[i-1])/(0.5*(dt[i] + dt[i-1]))\n```\n\nWe can quantitatively examine the difference between the forward and central difference scheme to calculate the velocity and the acceleration. Again, here we stick to only 20 data points as before.\n\n\n```python\n# Generate the subplots\nfig, (ax1, ax2) = plt.subplots(1, 2, figsize=(16, 6))\n\n# Plot the velocity\nax1.plot(v_ref[:, 0], v_ref[:, 1], label='Reference', lw=3.0, ls='--')\nax1.plot(v_f[:, 0], v_f[:, 1], label='Forward')\nax1.plot(v_c[:, 0], v_c[:, 1], label='Central')\nax1.set_title('Velocity')\nax1.legend(loc=2)\n\n# Plot the acceleration\nax2.plot(a_ref[:, 0], a_ref[:, 1], label='Reference', lw=3.0, ls='--')\nax2.plot(a_f[:, 0], a_f[:, 1], label='Forward')\nax2.plot(a_c[:, 0], a_c[:, 1], label='Central')\nax2.set_title('Acceleration')\nax2.legend();\n```\n\n#### A programmer approach - with interactive!\n\nWe can define functions that do our calculations for the forward and central difference method as followed. \n\n\n```python\ndef forward_method(r, t):\n n = len(t)\n \n # Initialise array for velocity and acceleration\n # calculated using forward difference method\n v_for = np.zeros((n-1, 2))\n a_for = np.zeros((n-2, 2))\n\n # Forward difference method to calculate velocity\n v_for[:, 0] = np.diff(r[:, 0]) / np.diff(t)\n v_for[:, 1] = np.diff(r[:, 1]) / np.diff(t)\n \n # And then the acceleration\n # Calculate acceleration\n a_for[:, 0] = np.diff(r[:, 0], 2) / (np.power(np.diff(t)[0:n-2], 2))\n a_for[:, 1] = np.diff(r[:, 1], 2) / (np.power(np.diff(t)[0:n-2], 2))\n\n return v_for, a_for\n```\n\n\n```python\ndef central_method(r, t):\n # Initialise array for velocity and acceleration\n # calculated using central difference method\n n = len(t)\n v_cen = np.zeros((n, 2))\n a_cen = np.zeros((n, 2))\n\n # Positions and time difference between adjacent\n # elements of position and time\n dr = np.diff(r, axis=0)\n dt = np.diff(t)\n\n # Centre difference method\n for i in range(1, n-2):\n v_cen[i-1, :] = (dr[i, :] + dr[i-1, :])/(dt[i] + dt[i-1])\n a_cen[i-1, :] = (dr[i, :]/dt[i] - dr[i-1, :]/dt[i-1]) / (0.5*(dt[i] + dt[i-1]))\n\n return v_cen, a_cen\n```\n\nBy doing so, we can easily calculate the results achieved from either scheme. We can call these functions for the interactive widget, which illustrates the dependence of these two methods on the number of available data points. Full understanding of the code is not required, yet curious students are encouraged to explore. \n\n\n```python\n# Interactive notebook to compare the two methods\nfrom ipywidgets import *\n```\n\n\n```python\ndef compare_difference(num_points):\n t = np.linspace(0, 2*np.pi, num_points)\n\n # Calculate the position used for the numerical term\n r_num = np.zeros((num_points, 2))\n r_num[:, 0] = np.exp(-t/T1)\n r_num[:, 1] = 2.0*np.cos(t/T2)\n\n # Forward difference method\n v_for, a_for = forward_method(r_num, t)\n\n # Central difference metho\n v_cen, a_cen = central_method(r_num, t)\n\n # Generate the subplots\n fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(16, 6))\n\n # Plot the velocity\n ax1.plot(v_ref[:, 0], v_ref[:, 1], label='Reference', lw=3.0, ls='--')\n ax1.plot(v_for[:, 0], v_for[:, 1], label='Forward')\n ax1.plot(v_cen[:, 0], v_cen[:, 1], label='Central')\n ax1.set_title('Velocity')\n ax1.legend(loc=2)\n\n # Plot the acceleration\n ax2.plot(a_ref[:, 0], a_ref[:, 1], label='Reference', lw=3.0, ls='--')\n ax2.plot(a_for[:, 0], a_for[:, 1], label='Forward')\n ax2.plot(a_cen[:, 0], a_cen[:, 1], label='Central')\n ax2.set_title('Acceleration')\n ax2.legend()\n```\n\n\n```python\ninteract(compare_difference, num_points=IntSlider(\n min=10, max=200, step=10, value=20, description='No. points'));\n```\n\n# Lecture 1: solving ordinary differential equations\n\nThis lecture introduces ordinary differential equations, and some techniques for solving first order equations. This notebook uses computer algebra via [Sympy]() to solve some ODE examples from the lecture notes.\n\n# Importing SymPy\n\nTo use Sympy, we first need to import it and call `init_printing()` to get nicely typeset equations:\n\n\n```python\nimport sympy\nfrom sympy import symbols, Eq, Derivative, init_printing, Function, dsolve, exp, classify_ode, checkodesol\n\n# This initialises pretty printing\ninit_printing()\nfrom IPython.display import display\n\n# Support for interactive plots\nfrom ipywidgets import interact\n\n# This command makes plots appear inside the browser window\n%matplotlib inline\n```\n\n# Example: car breaking\n\nDuring braking a car’s velocity is given by $v = v_{0} e^{−t/\\tau}$. Calculate the distance travelled.\n\nWe first define the symbols in the equation ($t$, $\\tau$ and $v_{0}$), and the function ($x$, for the displacement):\n\n\n```python\n\n```\n\nNext, we define the differential equation, and print it to the screen for checking:\n\n\n```python\neqn = Eq(Derivative(x(t), t), v0*exp(-t/(tau)))\ndisplay(eqn)\n```\n\nThe `dsolve` function solves the differential equation symbolically:\n\n\n```python\nx = dsolve(eqn, x(t))\ndisplay(x)\n```\n\nwhere $C_{1}$ is a constant. As expected for a first-order equation, there is one constant.\n\nSymPy is not yet very good at eliminating constants from initial conditions, so we will do this manually assuming that $x = 0$ and $t = 0$:\n\n\n```python\nx = x.subs('C1', v0*tau)\ndisplay(x)\n```\n\nSpecifying a value for $v_{0}$, we create an interactive plot of $x$ as a function of the parameter $\\tau$:\n\n\n```python\nx = x.subs(v0, 100)\n\ndef plot(τ=1.0):\n x1 = x.subs(tau, τ)\n\n # Plot position vs time\n sympy.plot(x1.args[1], (t, 0.0, 10.0), xlabel=\"time\", ylabel=\"position\");\n\ninteract(plot, τ=(0.0, 10, 0.2));\n```\n\n\n

Failed to display Jupyter Widget of type interactive.

\n

\n If you're reading this message in Jupyter Notebook or JupyterLab, 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 notebook 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# Classification\n\nWe can ask SymPy to classify our ODE, e.g. show that it is first order):\n\n\n```python\nclassify_ode(eqn)\n```\n\n\n\n\n ('separable',\n '1st_exact',\n '1st_linear',\n 'Bernoulli',\n '1st_power_series',\n 'lie_group',\n 'nth_linear_constant_coeff_undetermined_coefficients',\n 'nth_linear_constant_coeff_variation_of_parameters',\n 'separable_Integral',\n '1st_exact_Integral',\n '1st_linear_Integral',\n 'Bernoulli_Integral',\n 'nth_linear_constant_coeff_variation_of_parameters_Integral')\n\n\n\n# Parachutist\n\nFind the variation of speed with time of a parachutist subject to a drag force of $kv^{2}$.\n\nThe equations to solve is\n\n$$\n\\frac{m}{k} \\frac{dv}{dt} = \\alpha^{2} - v^{2}\n$$\n\nwhere $m$ is mass, $k$ is a prescribed constant, $v$ is the velocity, $t$ is time and $\\alpha^{2} = mg/k$ ($g$ is acceleration due to gravity).\n\nWe specify the symbols, unknown function $v$ and the differential equation\n\n\n```python\nt, m, k, alpha = symbols(\"t m k alpha\")\nv = Function(\"v\")\neqn = Eq((m/k)*Derivative(v(t), t), alpha*alpha - v(t)*v(t))\ndisplay(eqn)\n```\n\nFirst, let's classify the ODE:\n\n\n```python\nclassify_ode(eqn)\n```\n\n\n\n\n ('separable', '1st_power_series', 'lie_group', 'separable_Integral')\n\n\n\nWe see that it is not linear, but it is separable. Using `dsolve` again,\n\n\n```python\nv = dsolve(eqn, v(t))\ndisplay(v)\n```\n\nSymPy can verify that an expression is a solution to an ODE:\n\n\n```python\nprint(\"Is v a solution to the ODE: {}\".format(checkodesol(eqn, v)))\n```\n\n Is v a solution to the ODE: (True, 0)\n\n\nTry adding the code to plot velocity $v$ against time $t$.\n\n\n```python\n\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "4ca4868b6192c277863ac587523769fda0ef7cc0", "size": 572988, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": ".ipynb_checkpoints 2/Assignment solution-checkpoint.ipynb", "max_stars_repo_name": "hphilamore/ILAS_PyEv2019", "max_stars_repo_head_hexsha": "b3c8ebe00d6795f67879a50ce6ef517353b069c1", "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": ".ipynb_checkpoints 2/Assignment solution-checkpoint.ipynb", "max_issues_repo_name": "hphilamore/ILAS_PyEv2019", "max_issues_repo_head_hexsha": "b3c8ebe00d6795f67879a50ce6ef517353b069c1", "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": ".ipynb_checkpoints 2/Assignment solution-checkpoint.ipynb", "max_forks_repo_name": "hphilamore/ILAS_PyEv2019", "max_forks_repo_head_hexsha": "b3c8ebe00d6795f67879a50ce6ef517353b069c1", "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": 612.1666666667, "max_line_length": 168072, "alphanum_fraction": 0.932050933, "converted": true, "num_tokens": 4284, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122684798184, "lm_q2_score": 0.9161096221783882, "lm_q1q2_score": 0.8775526463570892}} {"text": "## Minimum of a set of Exponentially Distributed Random Variables\n\nLet $\\{X_i\\}$ be a set of exponentially distributed random variables. Let $y=min\\{X_i\\}$ be the minimum value of that set. \n\nThe cumulative distribution function that $y$ should be smaller or equal all of $\\{X_i\\}$ is given by:\n\n\\begin{equation}\np(y\\leq\\{X_i\\}) = \\prod_i p(X_i \\geq y) = \\lambda^n \\exp-n\\lambda y\n\\end{equation}\n\nThe cumulative probability depends on the probability that $y$ assumes a *specific* value: \n\n\\begin{equation}\np(y\\leq\\{X_i\\}) = \\int_0^\\infty p(y)\n\\end{equation}\n\nSo that $p(y)$ can be found by taking the derivative:\n\n\\begin{equation}\np(y) = n\\lambda^n\\exp-n\\lambda y\n\\end{equation}\n\n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nscale = 1\nn = 5\nsamples = 5000\n\nX = np.random.exponential(scale=scale,size=[n,samples])\nminX = np.min(X,axis=0)\n\ndef pdf_x(x):\n return (1/scale)*np.exp(-x/scale)\n\ndef pdf_min(y):\n return n*(1/scale)**n * np.exp(-n*y/scale)\n```\n\n\n```python\nx = np.linspace(0,10,1000)\n\nplt.figure(figsize=(12,8))\n\n_ = plt.hist(X.flatten(),bins = x,density=True)\n_ = plt.hist(minX,bins = x,density=True)\n\nplt.plot(x,pdf_x(x),linewidth=4)\nplt.plot(x,pdf_min(x),linewidth=4)\n```\n\n## Maximum of a set of Exponentially Distributed Random Variables\n\nSimilarly,\n\n\\begin{equation}\np(y\\geq\\{X_i\\}) = \\prod_i p(Y>X_i = (1-\\lambda\\exp-\\lambda y)^n\n\\end{equation}\n\nImplying:\n\n\\begin{equation}\np(y) = n\\lambda(1-\\exp-\\lambda y)^{n-1} \\exp-\\lambda y\n\\end{equation}\n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nscale = 1\nn = 5\nsamples = 5000\n\nX = np.random.exponential(scale=scale,size=[n,samples])\nmaxX = np.max(X,axis=0)\n\ndef pdf_x(x):\n return (1/scale)*np.exp(-x/scale)\n\ndef pdf_max(y):\n return n * (1/scale) * (1-np.exp(-y/scale))**(n-1) * np.exp(-y/scale)\n```\n\n\n```python\nx = np.linspace(0,10,1000)\n\nplt.figure(figsize=(12,8))\n\n_ = plt.hist(X.flatten(),bins = x,density=True)\n_ = plt.hist(maxX,bins = x,density=True)\n\nplt.plot(x,pdf_x(x),linewidth=4)\nplt.plot(x,pdf_max(x),linewidth=4)\n```\n", "meta": {"hexsha": "47d23bcd45862615507a2b0ecd01f22430fb0aa3", "size": 50782, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Probability - Minimum and Maximum of Exponentially Distributed Random Variables.ipynb", "max_stars_repo_name": "jpbm/probabilism", "max_stars_repo_head_hexsha": "a2f5c1595aed616236b2b889195604f365175899", "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": "Probability - Minimum and Maximum of Exponentially Distributed Random Variables.ipynb", "max_issues_repo_name": "jpbm/probabilism", "max_issues_repo_head_hexsha": "a2f5c1595aed616236b2b889195604f365175899", "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": "Probability - Minimum and Maximum of Exponentially Distributed Random Variables.ipynb", "max_forks_repo_name": "jpbm/probabilism", "max_forks_repo_head_hexsha": "a2f5c1595aed616236b2b889195604f365175899", "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": 256.4747474747, "max_line_length": 29712, "alphanum_fraction": 0.9262927809, "converted": true, "num_tokens": 680, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.964321452198369, "lm_q2_score": 0.9099070115349837, "lm_q1q2_score": 0.8774428507288935}} {"text": "## Calculation of exponent function using Maclaurin Series for x = 1\n\\begin{align}\ne^x = \\sum\\limits_{n=0}^{\\infty}\\frac{x^n}{n!}\n\\end{align}\n\n\n```python\n# importing dependency functions\nfrom math import exp as ideal_exp\nfrom matplotlib import pyplot as plt\n\n\n# initial guess for iteration number\niter_num = 25\n\n# implementation of factorial function\ndef custom_factorial(n):\n# base case to stop recursion\n if n < 1: return 1 \n# general case to compute factorial\n return n * custom_factorial(n-1)\n\n# implementation of power function\ndef custom_power(base, degree):\n# base case to stop recursion\n if degree < 1: return 1\n# general case to compute power\n return base * custom_power(base, degree - 1)\n\n# recursive implementation of exponential function\ndef custom_exp_recursive(x, counter=0, limit = iter_num):\n# base case to stop recursion\n if counter == limit - 1: return custom_power(x, counter)/custom_factorial(counter)\n# general case to compute exponent\n return custom_power(x, counter) / custom_factorial(counter) + custom_exp_recursive(x, counter + 1, limit)\n\n# loop implementation of exponential function to analyze error function\ndef custom_exp_analysis(x, iter_num=iter_num):\n# computing math library exponent as reference\n ideal = ideal_exp(x)\n# initialization of final result and error vector\n result = 0\n error_vec = [ideal]\n# Maclaurin iteration loop\n for i in range(iter_num):\n result += custom_power(x, i)/custom_factorial(i)\n error_vec.append((ideal - result) / ideal)\n return result, error_vec\n\nprint(\"Calculated exponent value is {} using {} iterations of Maclaurin series\".format(custom_exp_recursive(1), iter_num))\n```\n\n Calculated exponent value is 2.718281828459045 using 25 iterations of Maclaurin series\n\n\n## True relative error analysis.\n\nAfter each iteration term is added, the relative error is computed and plotted \n\n\n```python\n# plotting true error function\nplt.plot(custom_exp_analysis(1)[1])\nplt.ylabel('True error')\nplt.xlabel('# of iterations')\nplt.grid(color='b', linestyle='--', linewidth=0.5)\nplt.show()\n```\n\n## Precision test\n\nSuppose that $10^-15$ is a principal precision for custom exponent function. How many Maclaurin terms is needed in order to reach the given precision?\n\n\n```python\n# zoom plotting to explore precision\nplt.plot(custom_exp_analysis(1)[1])\nplt.ylabel('True relative error')\nplt.xlabel('# of iterations')\nplt.xlim(15, 25)\nplt.ylim(-1e-15, 1e-15)\nplt.grid(color='b', linestyle='--', linewidth=0.5)\nplt.show()\n```\n\nFrom above plot it is clearly seen that 17 iterations are enough to reach e-15 precision, since error function fits into e-15 precision boundaries.\n\n## Truncation error test\n\nAfter 19th iteration, result is not improving anymore. Why?\n\nIncreasing number of iterations has no any effect to error function anymore. To understand causes let's analyze 19th cycle process. 19th Maclaurin element is calculated as 1/19! and added to global result. Let's see what we get by dividing 1 to 19!.\n\n\n```python\nfrom decimal import Decimal\nprint(Decimal(1/custom_factorial(19)))\n```\n\n 8.2206352466243294955370400408296422011147285715637438030523043153152684681117534637451171875E-18\n\n\nIt is not 0, so cause is not from this term. \n\n\n```python\nsmall_term = 1/custom_factorial(19)\nadded_something = 0.99 + small_term\nprint(Decimal(added_something))\n```\n\n 0.9899999999999999911182158029987476766109466552734375\n\n\nSomething strange happens when we add 0.99 to 19th Maclauring series. Resulting value becomes less than 0.99.\n\n\n```python\nadded_something = 2599999999999999990000.999999 + small_term\nprint(Decimal(added_something))\n```\n\n 2600000000000000000000\n\n\nEven 10000 difference is rounded here to obtain number without fractions.\n\n\n```python\nprint(type(small_term))\n```\n\n \n\n\nIn Python there is 53 bits of precision available for floating numbers. \n\n### Precision tests using x = 2 and x = 10\n\n\n```python\n# plotting true error function\nplt.plot(custom_exp_analysis(2)[1])\nplt.ylabel('True relative error')\nplt.xlabel('# of iterations')\nplt.grid(color='b', linestyle='--', linewidth=0.5)\nplt.show()\n```\n\n\n```python\n# zoom plotting to explore precision\nplt.plot(custom_exp_analysis(2, iter_num=25)[1])\nplt.ylabel('True relative error')\nplt.xlabel('# of iterations')\nplt.xlim(15, 25)\nplt.ylim(-1e-15, 1e-15)\nplt.grid(color='b', linestyle='--', linewidth=0.5)\nplt.show()\n```\n\nThis time, we could reach e-15 accuracy in 22 iterations.\n\n\n```python\n# plotting true error function\nplt.plot(custom_exp_analysis(10)[1])\nplt.ylabel('True relative error')\nplt.xlabel('# of iterations')\nplt.grid(color='b', linestyle='--', linewidth=0.5)\nplt.show()\n```\n\n\n```python\n# zoom plotting to explore precision\nplt.plot(custom_exp_analysis(10, iter_num=50)[1])\nplt.ylabel('True error')\nplt.xlabel('# of iterations')\nplt.xlim(40, 50)\nplt.ylim(-1e-15, 1e-15)\nplt.grid(color='b', linestyle='--', linewidth=0.5)\nplt.show()\n```\n\nIn the case when x = 10, error function converged to e-15 precision at 45th Maclaurin iteration. \n\n### Conclusion about approximations\n\nMost decimal fractions cannot be represented exactly as binary fractions. Therefore, in general, the decimal floating-point numbers are only approximated by the binary floating-point numbers actually stored in the machine. For instance 1/3 fraction will be stored in bits in following way 0.0001100110011001100110011001100110011001100110011... and it consumes all bits allocated for current variable. To save space, Python stops its binary iterations at some step to approximate value and save bits. This may be a reason of such strange behaviour of floating number operations and early approximations.\n\n\n```python\n\n```\n", "meta": {"hexsha": "2f621e33228403607ef161db5eaed5352f4920a7", "size": 110190, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "exponent.ipynb", "max_stars_repo_name": "BatyaGG/numerical_methods", "max_stars_repo_head_hexsha": "40036c07ed4db2fb03fe0d188feeb440aa260ce2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-06-23T12:19:55.000Z", "max_stars_repo_stars_event_max_datetime": "2018-06-23T12:19:55.000Z", "max_issues_repo_path": "exponent.ipynb", "max_issues_repo_name": "BatyaGG/numerical_methods", "max_issues_repo_head_hexsha": "40036c07ed4db2fb03fe0d188feeb440aa260ce2", "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": "exponent.ipynb", "max_forks_repo_name": "BatyaGG/numerical_methods", "max_forks_repo_head_hexsha": "40036c07ed4db2fb03fe0d188feeb440aa260ce2", "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": 256.8531468531, "max_line_length": 18092, "alphanum_fraction": 0.9278337417, "converted": true, "num_tokens": 1455, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067244294588, "lm_q2_score": 0.9304582497090321, "lm_q1q2_score": 0.8769631571516273}} {"text": "# Number theory and a Google recruitment puzzle\n\n## Find the first 10-digit prime in the decimal expansion of 17π\n\nDescription: The first 5 digits in the decimal expansion of π are 14159. The first 4-digit prime in the decimal expansion of π are 4159. You are asked to find the first 10-digit prime in the decimal expansion of 17π. \n\nThere are three main steps to this question. \n 1) Generate an arbitrary large expansion of a mathematical expression \n 2) Check if a number is prime \n 3) Generate sliding windows of a specified width from a long iterable \n \nWe will start with the first step. The goal is to return an arbitrary expansion (expansion after the decimal) of a mathematical expression. The user inputs will be the mathematical expression along with the multiplier (can be 1) and the number of digits of the expansion.\n \nI first tried using the decimal library to expand the mathematical expression \"pi\", but I realized I was approximating pi by using the expression \"355/113\" and I could not find a more accurate way to expand pi, so I opted to use the sympy library. I used the decimal library to expand \"e\". \n \nOne important thing to note is that a multiplier of the mathematical expression can be an input like \"2e\" or \"3pi\". The multiplier must be a separate input from the expression. \n\n\n```python\nfrom decimal import *\nfrom sympy import *\n\ndef expansion(multiplier, expression, n):\n \"\"\"\n Input: mathematical expression, a multiplier of the expression, and number of digits of prime number\n Behavior: expands mathematical expression\n Output: an arbitrary expansion (specified by user) of a mathematical expressions pi or e \n \"\"\"\n if expression == \"pi\":\n # N function captures number of digits, so use log formula to capture number of specified digits after decimal\n x = N(multiplier*pi, n + log(multiplier*pi, 10) + 1)\n # obtain digits after decimal and return as integer \n # integers that start with 0 will not capture the 0\n before, after = str(x).split('.')\n return int(after)\n \n if expression == \"e\":\n # set number of digits for expansion\n getcontext().prec = n\n x = (Decimal(1).exp())*multiplier\n before, after = str(x).split('.')\n return int(after)\n \n # can only generate expansions of pi and e\n else:\n return \"Can not solve\"\n```\n\nThe next step is to determine if a number is prime. To make this function efficient, we can loop through divisors in the range from 2 to the square root of the number rounded up using the ceiling function from the math module and check whether that number is a factor. The mathematical intution behind this is that a number that is not prime will have at least one factor that is less than its square root (and one factor greater). So, if a number has no factors less than its square root, it must be prime. For example, let's take the number 11. The square root of 11 rounded up is 4, so the loop will run from 2 to 4. If there are no factors in that range, that 11 is prime, which is the case. I used this mathematical intuition because looping through all numbers in the range to the specified number is very inefficient, especially because we are working with such large numbers in this question. \n\n\n```python\nfrom math import sqrt, ceil\n\ndef prime_num(n):\n \"\"\"\n Input: number\n Behavior: returns true if number is prime\n Output: true or false\n \"\"\"\n # prime numbers have to be greater than 1\n if n > 1:\n # loop through numbers in range 2 to the ceiling of the square root of the specified number\n for number in range(2, ceil(sqrt(n))):\n # return to outer for loop and increment by one if input number is not divisible by number\n if (n % number) == 0:\n # number is not prime (divisible by a number other than one and itself)\n return False\n else:\n # number is prime, so return true\n return True\n else: \n # return false if number is not greater than 1\n return False\n```\n\nThe next step is to write the final helper function. The goal is to generate sliding windows of a specified width from a long iterable.\n\nI tried a lot of different things to generate sliding windows including using itertools, but decided that using list comprehensions would be equally succinct in accomplishing this task. \n \nFirst, we will make the iterable (input number) into a list of its digits as strings. For example, 1234 becomes ['1','2','3','4']. Then, we will create a window of a specified size for each element (digit) in the range of the number until a window of the specified size cannot be made. For example, if we want a window of size 3, we will loop through all the elements in range of the length of the list of digits minus the size of the window plus one. So, using our example, the loop will run from '1' to '2'. For each iteration, the window will be appeneded as a list to a list of windows. So, from our example, [['1','2','3'],['2','3','4']] will be the output from the loop. Next, we want to return a list of integers, so we will combine the digits into one number and convert to an integer. From our example, the output would be [123, 234].\n\n\n```python\ndef sliding_window(iterable, size):\n \"\"\"\n Input: integer and size of window \n Behavior: generates sliding windows of a specified width from a long iterable\n Output: list of windows\n \"\"\"\n window_list = []\n \n # length of number has to be greater than the window size\n if len(str(iterable)) >= size:\n # make iterable into list of its digits\n it_list = [str(x) for x in str(iterable)]\n \n # create window as a list by grabbing elements in range of current element through the elements in the window size\n windows = [it_list[x:x+size] for x in range(len(it_list) - size + 1)]\n \n # convert list of digits in window to a single integer and append to list\n for window in windows:\n a_string = \"\".join(window)\n an_integer = int(a_string)\n window_list.append(an_integer)\n \n # returns list of integers\n return window_list\n else:\n return \"Size of window bigger than iterable\"\n```\n\nThe final step is to create a function with these helper functions to return a specified digit-length prime in the decimal expansion of a mathematical expression like \"pi\". First, we will create the decimal expansion using the expansion helper function. Then, we will create the list of sliding windows given the size of the prime number we want using the sliding windows helper function. Finally, we will check whether each number in each window is prime using the prime helper function and return the first prime number. \n\n\n```python\ndef prime_expanded_expression(size, multiplier, expression, digits):\n \"\"\"\n Input: size of window, multiplier of expression, mathematical expression, and number of digits to expand\n Behavior: returns a specified digit-length prime in the decimal expansion of a mathematical expression\n Output: number\n \"\"\"\n # create decimal expansion of mathematical expression\n expanded = expansion(multiplier, expression, digits)\n # create list of sliding windows of decimal expansion given size of window\n expansion_window = sliding_window(expanded, size)\n # check whether each window (number) is a prime and if it is, return that number\n for number in expansion_window:\n # numbers that are less than a length of 10 start with 0, so cannot be prime\n if len(str(number)) == 10:\n # check whether number is prime\n if prime_num(number):\n return number\n```\n\nNow, we will write unit tests for each function to assert that they are returning the correct values and to check edge cases. Two tests are written for each function.\n\n\n```python\nimport unittest\n\nclass TestNotebook(unittest.TestCase):\n \n def test_expansion(self):\n \"\"\"test expansion.\"\"\"\n self.assertEqual(expansion(1, \"pi\", 5), 14159)\n self.assertEqual(expansion(17, \"pi\", 9), 407075111)\n \n def test_prime_num(self):\n \"\"\"test prime_num.\"\"\"\n self.assertFalse(prime_num(1))\n self.assertTrue(prime_num(4159))\n \n def test_sliding_window(self):\n \"\"\"test sliding_window.\"\"\"\n self.assertEqual(sliding_window(407075111, 4), [4070, 707, 7075, 751, 7511, 5111])\n self.assertEqual(sliding_window(1234, 5), \"Size of window bigger than iterable\")\n \n def prime_expanded_expression(self):\n \"\"\"test prime_expanded_expression.\"\"\"\n self.assertEqual(prime_expanded_expression(10, 1, \"e\", 110), 7427466391)\n self.assertEqual(prime_expanded_expression(4, 1, \"pi\", 110), 4159)\n\nunittest.main(argv=[''], verbosity=2, exit=False)\n```\n\n test_expansion (__main__.TestNotebook)\n test expansion. ... ok\n test_prime_num (__main__.TestNotebook)\n test prime_num. ... ok\n test_sliding_window (__main__.TestNotebook)\n test sliding_window. ... ok\n \n ----------------------------------------------------------------------\n Ran 3 tests in 0.015s\n \n OK\n\n\n\n\n\n \n\n\n\nFinally, let's solve the problem! The first 10-digit prime in the decimal expansion of 17π is 8649375157.\n\n\n```python\nprint(prime_expanded_expression(10, 17, \"pi\", 110))\n```\n\n 8649375157\n\n", "meta": {"hexsha": "cc7ff3c27365a4be579c01f5fcee40e23109d881", "size": 12778, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "_notebooks/2021-09-17-numbertheory.ipynb", "max_stars_repo_name": "saahithirao/bios-823-blog", "max_stars_repo_head_hexsha": "23644cb773a0bdea3810cc807fb15b40387ce625", "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-09-17-numbertheory.ipynb", "max_issues_repo_name": "saahithirao/bios-823-blog", "max_issues_repo_head_hexsha": "23644cb773a0bdea3810cc807fb15b40387ce625", "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-09-17-numbertheory.ipynb", "max_forks_repo_name": "saahithirao/bios-823-blog", "max_forks_repo_head_hexsha": "23644cb773a0bdea3810cc807fb15b40387ce625", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.462585034, "max_line_length": 907, "alphanum_fraction": 0.5946157458, "converted": true, "num_tokens": 2143, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9678992923570261, "lm_q2_score": 0.905989815306765, "lm_q1q2_score": 0.8769069011180907}} {"text": "# Poisson's problem\n\n## General formulation\n\nHere I provide the \"Hello, world!\" of FEM. The Poisson's problem subject to Dirichlet boundary conditions is stated as:\n\nFind $u \\in \\mathbb{C}^2(\\overline{\\Omega})$ in a closed domain $\\overline{\\Omega}\\subset \\mathbb{R}^n\\,(n=1,2,3)$ such that:\n\n\\begin{equation}\n\\left\\{\n\\begin{aligned}\n- &\\Delta u = f(x), \\quad \\forall x \\in \\Omega \\\\\n&\\left. u \\right|_{\\partial \\Omega} = g(x)\n\\end{aligned}\n\\right.\n\\end{equation}\nwhere $\\overline{\\Omega} := \\Omega \\cup \\partial \\Omega$ denotes the closed domain, $\\Omega$ is the open domain and $\\partial \\Omega$ is the domain's boundary (the closure). Note that $\\Omega \\cap \\partial \\Omega = \\emptyset$. The solution is a scalar field such that $u: \\overline{\\Omega} \\to \\mathbb{R}$. Also, we have the \"source term\" that is a scalar field of the same form, $f: \\overline{\\Omega} \\to \\mathbb{R}$, but this function is a given data to the (direct) problem. The $g(x)$ is a prescribed function applied to the boundary, which is also a given data to the problem.\n\nP.S.: I will not discuss the ill problems formulation, neither others mathematical requirements to assert the well-posedness of the problem.\n\n## 1D simplification\n\nIn some scenarios, the mathematical modeling approach can be simplified to the 1D case, which is written as follows:\n\nFind $u \\in \\mathbb{C}^2$ such that:\n\n\\begin{equation}\n\\left\\{\n\\begin{aligned}\n- &u'' = f(x), \\quad \\forall x \\in ((x_1, x_2) \\subset \\mathbb{R}) \\\\\n&u(x_1) = u_1 \\\\\n&u(x_2) = u_2\n\\end{aligned}\n\\right.\n\\end{equation}\n\nwhere $u_1, u_2 \\in \\mathbb{R}$ are the prescribed boundary condition values, $u'(x) \\equiv \\dfrac{d u}{d x}$ and thus $u''(x) \\equiv \\dfrac{d^2 u}{d x^2}$. For the sake of simplicity, I will omit the argument of $u$ function. Such aforementioned problems are known as Two-Point Boundary Value problems.\n\n### Variational formulation and Galerkin approximation\n\nOne can find the derivation of the weak form, but I will just give its result below.\n\nGiven the space of admissible solution:\n\n\\begin{equation}\n\\mathcal{U} (\\overline{\\Omega}) := \\left\\{ u \\in H^1 (\\overline{\\Omega}) \\left| \\,u(x_1) = u_1, u(x_2) = u_2 \\right. \\right\\}\n\\end{equation}\n\nand the space of suitable variations as\n\n\\begin{equation}\n\\mathcal{V} (\\overline{\\Omega}) := \\left\\{ v \\in H^1 (\\overline{\\Omega}) \\left| \\,u(x_1) = u(x_2) = 0 \\right. \\right\\}\n\\end{equation}\n\nThe discretization of the above spaces is performed by Galerkin approximation with Lagrangean function space $\\mathbb{P}$ of order $k$ defined over $\\overline{\\Omega}$. Thus we define here:\n\n\\begin{equation}\n \\mathcal{S}_h^k(\\overline{\\Omega}) := \\left\\{ \\varphi_h \\in \\mathcal{C}(\\Omega^e): \\left.\\varphi\\right|_{\\Omega^e} \n \\in \\mathbb{P}_k(\\Omega^e), \\forall \\Omega^e \\in \\mathcal{T}_h \\right\\}\n\\end{equation}\n\nthe space of Lagrange polynomials subject to a domain partition $\\mathcal{T}_h:=\\cup \\Omega^e \\approx \\overline{\\Omega}$ and $\\cap \\Omega^e = \\emptyset$ (non-overlapping elements). Thus\n\n\\begin{equation}\n \\mathcal{U}_h := \\mathcal{U} \\cap \\mathcal{S}_h^k \\quad \\text{and} \\quad\n \\mathcal{V}_h := \\mathcal{V} \\cap \\mathcal{S}_h^k\n\\end{equation}\n\nwe have the discretized spaces.\n\nNow, we can stated out our \"discretized\" Variational Formulation as:\n\nFind $u_h \\in \\mathcal{U}_h$ such that\n\n\\begin{equation}\na(u_h, v_h) = F(v_h), \\quad \\forall v_h \\in \\mathcal{V}_h\n\\end{equation}\n\nwhere\n\n\\begin{align}\na(u, v) &:= \\int_{\\Omega} u' v' dx \\\\\nF(v) &:= \\int_{\\Omega} f v dx\n\\end{align}\n\nand the domain is $\\overline{\\Omega} \\equiv [x_1, x_2]$.\n\n### A practical FEniCS example\n\nSolve this in FEniCS is very straightforward compared to classical FEM codes. The FEniCS framework provides a high-level interface which eases the pain at most.\n\nJust for learning purpose, let the given data be setted as:\n\n\\begin{align*}\n&f(x) \\equiv f = 1 \\\\\n&u_1 = u_2 = 0 \\\\\n&x_1 = 0, \\quad x_2 = 1\n\\end{align*}\n\nWith the source term as $f(x) = 1$, the exact solution can be easily obtained:\n\n\\begin{equation}\nu(x) = \\frac{1}{2}\\left(x_1^2 - x^2\\right) + \\left[\\frac{1}{2}(x_1 + x_2) + \\frac{u_1 - u_2}{x_1 - x_2} \\right] (x - x_1) + u_1\n\\end{equation}\n\nSo, how to solve the problem with FEniCS? We will construct the procedures stepwisely.\n\n* Importing all the libs we'll need. \n\n\n```python\nfrom fenics import * # all the FEniCS namespace (not a recommended Python practice)\nimport matplotlib.pyplot as plt\nfrom matplotlib import rc\nimport numpy as np\n```\n\n* Defining the domain and related mesh\n\n\n```python\nx_left = 0.0\nx_right = 1.0\nnumel = 15\nmesh = IntervalMesh(numel, x_left, x_right) # IntervalMesh(num_of_elements, inf_interval, sup_interval)\nmesh_ref = IntervalMesh(100, x_left, x_right)\n```\n\n* Setting the degree of the functions in the Continuous Galerkin method and the variation space. Additionaly, we define here a space to be employed in the projection of the reference analytical solution\n\n\n```python\np = 1\nV = FunctionSpace(mesh, \"CG\", p) # \"CG\" stands for Continuous Galerkin, p is the degree\nVref = FunctionSpace(mesh_ref, \"CG\", p)\n```\n\n* Defining a Python function which marks the boundaries\n\n\n```python\ndef left(x, on_boundary):\n return x < 0+DOLFIN_EPS\ndef right(x, on_boundary):\n return x > 1-DOLFIN_EPS\n```\n\n* Setting the prescribed boundary values\n\n\n```python\nu1, u2 = 0.0, 0.0\ng_left = Constant(u1)\ng_right = Constant(u2)\n```\n\n* Now we modify the spaces, as expected\n\n\n```python\nbc_left = DirichletBC(V, g_left, left)\nbc_right = DirichletBC(V, g_right, right)\ndirichlet_condition = [bc_left, bc_right]\n```\n\n* Here we define the source function over the domain\n\n\n```python\nf = Constant(1)\n```\n\n* Now comes the good part. We set up the Trial and Test functions from the admissible space\n\n\n```python\nu_h = TrialFunction(V)\nv_h = TestFunction(V)\n```\n\n* Then we write the bilinear form, very much like it is written in mathematical form\n\n\\begin{equation}\na(u_h, v_h) \\equiv \\left(u_h', v_h'\\right) = \\int_{\\Omega} u_h' v_h' dx\n\\end{equation}\n\n\n```python\na = inner(grad(v_h), grad(u_h))*dx\n```\n\n* Also we define the associated linear form\n\n\\begin{equation}\nL(v) := (f, v_h) = \\int_{\\Omega} f v_h dx\n\\end{equation}\n\n\n```python\nL = f*v_h*dx\n```\n\n* Now we declare the solution variable, which means that `u_sol` is a function over the space $\\mathcal{V}$\n\n\n```python\nu_sol = Function(V)\n```\n\n* Thus we set the discretized variational problem to be solved. The problem is declared with the FEniCS function `LinearVariationalProblem`, that has as arguments the LHS, the RHS, the variable where the solution will be stored and computed and the essential boundary conditions to be considered\n\n\n```python\nproblem = LinearVariationalProblem(a, L, u_sol, dirichlet_condition)\n```\n\n* And we go further and solve it with no difficulties!\n\n\n```python\nsolver = LinearVariationalSolver(problem)\nsolver.solve()\n```\n\n* But we will need to check if the solution is \"good enough\". So we compare with the available exact solution\n\n\n```python\nsol_exact = Expression(\n \"(1. / 2.) * (pow(x_1,2.0) - pow(x[0],2.0)) + \\\n ((1./2.) * (x_1 + x_2) + (u_1 - u_2) / (x_1 - x_2)) * (x[0] - x_1) + u_1\", \n degree=p+1, \n u_1=u1, \n u_2=u2, \n x_1=x_left, \n x_2=x_right\n)\nu_e = interpolate(sol_exact, Vref)\n```\n\n* Now, lets plot our results!\n\n\n```python\nplot(u_sol, marker='x', label='Approx')\nplot(u_e, label='Exact')\n# Setting the font\nplt.rc('text',usetex=True)\nplt.rc('font', size=14)\n# Plotting\nplt.xlim(x_left, x_right) # Limites do eixo x\nplt.ylim(np.min(u_sol.vector().get_local()), 1.02*np.max(u_e.vector().get_local())) # Limites do eixo y\nplt.grid(True, linestyle='--') # Ativa o grid do grafico\nplt.xlabel(r'$x$') # Legenda do eixo x\nplt.ylabel(r'$u(x)$') # Legenda do eixo y\nplt.legend(loc='best',borderpad=0.5) # Ativa legenda no grafico e diz para se posicionar na melhor localizacao detectada\nplt.show() # Exibe o grafico em tela\n```\n", "meta": {"hexsha": "14c22682018cff501457ac8113e1bf6d69e4eaeb", "size": 40472, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "fem/fenics/Poisson1D.ipynb", "max_stars_repo_name": "volpatto/quick-ipython-notebooks", "max_stars_repo_head_hexsha": "4c97f0c8fbf918a76f74d8198720562538eaf5a2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-06-09T16:49:11.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-09T16:49:11.000Z", "max_issues_repo_path": "fem/fenics/Poisson1D.ipynb", "max_issues_repo_name": "volpatto/quick-ipython-notebooks", "max_issues_repo_head_hexsha": "4c97f0c8fbf918a76f74d8198720562538eaf5a2", "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": "fem/fenics/Poisson1D.ipynb", "max_forks_repo_name": "volpatto/quick-ipython-notebooks", "max_forks_repo_head_hexsha": "4c97f0c8fbf918a76f74d8198720562538eaf5a2", "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": 87.7917570499, "max_line_length": 26984, "alphanum_fraction": 0.8278562957, "converted": true, "num_tokens": 2519, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9609517106286379, "lm_q2_score": 0.9124361676202372, "lm_q1q2_score": 0.8768070961141056}} {"text": "# Scientific Computing with Python\n
This notebook by Xiaozhou Li is licensed under a Creative Commons Attribution 4.0 International License. \nAll code examples are also licensed under the [MIT license](http://opensource.org/licenses/MIT).\n\n\n```python\n# what is this line all about?\n%matplotlib inline\nimport matplotlib.pyplot as plt\n```\n\n## Numpy and Scipy\n### Introduction\nThe numpy package (module) is used in almost all numerical computation using Python. It is a package that provide high-performance vector, matrix and higher-dimensional data structures for Python. It is implemented in C and Fortran so when calculations are vectorized (formulated with vectors and matrices), performance is very good.\n\nThe SciPy framework builds on top of the low-level NumPy framework for multidimensional arrays, and provides a large number of higher-level scientific algorithms. \n\n### Fitting to polynomial\n\n\n```python\nimport numpy as np\n```\n\n\n```python\nnp.random.seed(12)\n\nx = np.linspace(0, 1, 20)\ny = np.cos(x) + 0.3*np.random.rand(20)\np = np.poly1d(np.polyfit(x, y, 16))\n\nt = np.linspace(0, 1, 200)\nplt.plot(x, y, 'o', t, p(t), '-')\nplt.show()\n```\n\n### Fit in a Chebyshev basis\n\n\n```python\nnp.random.seed(0)\n\nx = np.linspace(-1, 1, 2000)\ny = np.cos(x) + 0.3*np.random.rand(2000)\np = np.polynomial.Chebyshev.fit(x, y, 90)\n\nt = np.linspace(-1, 1, 200)\nplt.plot(x, y, 'r.')\nplt.plot(t, p(t), 'k-', lw=3)\nplt.show()\n```\n\n### A demo of 1D interpolation\n\n\n```python\nnp.random.seed(0)\nmeasured_time = np.linspace(0, 1, 10)\nnoise = 1e-1 * (np.random.random(10)*2 - 1)\nmeasures = np.sin(2 * np.pi * measured_time) + noise\n\n# Interpolate it to new time points\nfrom scipy.interpolate import interp1d\nlinear_interp = interp1d(measured_time, measures)\ninterpolation_time = np.linspace(0, 1, 50)\nlinear_results = linear_interp(interpolation_time)\ncubic_interp = interp1d(measured_time, measures, kind='cubic')\ncubic_results = cubic_interp(interpolation_time)\n\n# Plot the data and the interpolation\nfrom matplotlib import pyplot as plt\nplt.figure(figsize=(6, 4))\nplt.plot(measured_time, measures, 'o', ms=6, label='measures')\nplt.plot(interpolation_time, linear_results, label='linear interp')\nplt.plot(interpolation_time, cubic_results, label='cubic interp')\nplt.legend()\nplt.show()\n```\n\n### Minima and roots of a function\n\\begin{equation}\n f(x) = x^2 + 10\\sin(x)\n\\end{equation}\n\n**(1) find minima**\n\n\n```python\ndef f(x):\n return x**2 + 10*np.sin(x)\n\nfrom scipy import optimize\n\n# Global optimization\ngrid = (-10, 10, 0.1)\nxmin_global = optimize.brute(f, (grid, ))\nprint(\"Global minima found %s\" % xmin_global)\n\n# Constrain optimization\nxmin_local = optimize.fminbound(f, 0, 10)\nprint(\"Local minimum found %s\" % xmin_local)\n```\n\n Global minima found [-1.30641113]\n Local minimum found 3.8374671194983834\n\n\n**(2) root finding**\n\n\n```python\nroot = optimize.root(f, 1) # our initial guess is 1\nprint(\"First root found %s\" % root.x)\nroot2 = optimize.root(f, -2.5)\nprint(\"Second root found %s\" % root2.x)\n```\n\n First root found [0.]\n Second root found [-2.47948183]\n\n\n**(3) Plot function, minima, and roots**\n\n\n```python\nfig = plt.figure(figsize=(6, 4))\nax = fig.add_subplot(111)\n\nx = np.arange(-10, 10, 0.1)\n# Plot the function\nax.plot(x, f(x), 'b-', label=\"f(x)\")\n\n# Plot the minima\nxmins = np.array([xmin_global[0], xmin_local])\nax.plot(xmins, f(xmins), 'go', label=\"Minima\")\n\n# Plot the roots\nroots = np.array([root.x, root2.x])\nax.plot(roots, f(roots), 'kv', label=\"Roots\")\n\n# Decorate the figure\nax.legend(loc='best')\nax.set_xlabel('x')\nax.set_ylabel('f(x)')\nax.axhline(0, color='gray')\nplt.show()\n```\n\n## Matplotlib\n### Introduction\nMatplotlib is an excellent 2D and 3D graphics library for generating scientific figures.\n\n### Reading and writing a panda\n\n**(1) original figure**\n\n\n```python\nplt.figure()\nimg = plt.imread('../data/panda.jpg')\nplt.imshow(img)\nplt.imsave(\"original.jpg\",img)\n\nprint (np.shape(img))\n```\n\n**(2) red channel displayed in grey**\n\n\n```python\nplt.figure()\nimg_red = img[:, :, 0]\nplt.imshow(img_red, cmap=plt.cm.gray)\n```\n\n**(3) lower resolution (compression)**\n\n\n```python\nplt.figure()\nimg_tiny = img[::8, ::8]\nplt.imshow(img_tiny, interpolation='nearest') \n#plt.savefig(\"compressed.jpg\")\nplt.imsave(\"compressed.jpg\",img_tiny)\n```\n\n### Mandlebrot Set (Mandelbrot fractal)\n\n\n```python\ndef compute_mandelbrot(N_max, some_threshold, nx, ny):\n # A grid of c-values\n x = np.linspace(-2, 1, nx)\n y = np.linspace(-1.5, 1.5, ny)\n\n c = x[:,np.newaxis] + 1j*y[np.newaxis,:]\n\n # Mandelbrot iteration\n\n z = c\n for j in range(N_max):\n z = z**2 + c\n\n mandelbrot_set = (abs(z) < some_threshold)\n\n return mandelbrot_set\n\nmandelbrot_set = compute_mandelbrot(50, 50., 601, 401)\n\nplt.imshow(mandelbrot_set.T, extent=[-2, 1, -1.5, 1.5])\nplt.gray()\nplt.show()\n```\n\n### A simple example of 3D plotting\n$$ z = \\sin(\\sqrt{x^2 + y^2}) $$\n\n\n```python\nfrom mpl_toolkits.mplot3d import Axes3D\n\nfig = plt.figure()\nax = Axes3D(fig)\nX = np.arange(-4, 4, 0.25)\nY = np.arange(-4, 4, 0.25)\nX, Y = np.meshgrid(X, Y)\nR = np.sqrt(X ** 2 + Y ** 2)\nZ = np.sin(R)\n\nax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=plt.cm.hot)\nax.contourf(X, Y, Z, zdir='z', offset=-2, cmap=plt.cm.hot)\nax.set_zlim(-2, 2)\n\nplt.show()\n```\n\n### An example displaying the contours of a function\n$$ f(x,y) = \\left(1 - \\frac{x}{2} + x^5 + y^3\\right)e^{-x^2-y^2}.$$\n\n\n```python\ndef f(x,y):\n return (1 - x / 2 + x**5 + y**3) * np.exp(-x**2 -y**2)\n\nn = 256\nx = np.linspace(-3, 3, n)\ny = np.linspace(-3, 3, n)\nX,Y = np.meshgrid(x, y)\n\nplt.axes([0.025, 0.025, 0.95, 0.95])\n\nplt.contourf(X, Y, f(X, Y), 8, alpha=.75, cmap=plt.cm.hot)\nC = plt.contour(X, Y, f(X, Y), 8, colors='black')\nplt.clabel(C, inline=1, fontsize=10)\n\nplt.xticks(())\nplt.yticks(())\nplt.show()\n```\n\n## Sympy - Symbolic algebra in Python\n\n### Introduction\nThere are two notable Computer Algebra Systems (CAS) for Python:\n\n* [SymPy](http://sympy.org/en/index.html) - A python module that can be used in any Python program, or in an IPython session, that provides powerful CAS features. \n* [Sage](http://www.sagemath.org/) - Sage is a full-featured and very powerful CAS enviroment that aims to provide an open source system that competes with Mathematica and Maple. Sage is not a regular Python module, but rather a CAS environment that uses Python as its programming language.\n\nSage is in some aspects more powerful than SymPy, but both offer very comprehensive CAS functionality. The advantage of SymPy is that it is a regular Python module and integrates well with the Jupyter notebook. \n\n\n```python\nfrom sympy import *\n\ninit_printing()\n```\n\n### Expand, factor and simplify\n\n\n```python\nx, y = symbols('x y')\n\n(x+1)*(x+2)*(x+3)*(x+4)*(x+5)\n```\n\n\n```python\nexpand((x+1)*(x+2)*(x+3)*(x+4)*(x+5))\n```\n\n\n```python\nsin(x+y)\n```\n\n\n```python\nexpand(sin(x+y), trig=True)\n```\n\n\n```python\nexpand((x+y)**8)\n```\n\n\n```python\nx**3 + 6 * x**2 + 11*x + 6\n```\n\n\n```python\nfactor(x**3 + 6 * x**2 + 11*x + 6)\n```\n\n\n```python\nsin(x)**2 + cos(x)**2\n```\n\n\n```python\nsimplify(sin(x)**2 + cos(x)**2)\n```\n\n\n```python\ncos(x)/sin(x)\n```\n\n\n```python\nsimplify(cos(x)/sin(x))\n```\n\n### Calculus\n**(1) differentiation and integration**\n\n$f(x) = (x+1)^2$\n\n\n```python\nf = (x+1)**2\nf\n```\n\nComputing $\\frac{d f}{dx}$, $\\frac{d f^2}{dx}$\n\n\n```python\ndiff(f,x)\n```\n\n\n```python\ndiff(f**2,x)\n```\n\nComputing $\\frac{d \\sin(f)}{dx}$, $\\frac{d^2 \\sin(f)}{dx^2}$\n\n\n```python\ndiff(sin(f),x)\n```\n\n\n```python\ndiff(sin(f),x,2)\n```\n\n\n```python\ndiff(sin(f),x,4)\n```\n\n$$ f(x,y) = \\sin(xy) + \\cos(xy),$$\ncomputing\n$$ \\frac{\\partial^3 f}{\\partial x \\partial y^2},\\quad \\int f(x,y)\\,dx,\\quad \\int_{-1}^{1}f(x,y)\\,dx$$\n\n\n```python\nf = sin(x*y) + cos(y*x)\nf\n```\n\n\n```python\ndiff(f, x, 1, y, 2)\n```\n\n\n```python\nintegrate(f, x)\n```\n\n\n```python\nintegrate(f, (x, -1, 1))\n```\n\nComputing $\\int_{-\\infty}^\\infty e^{-x^2}\\,dx$\n\n\n```python\nintegrate(exp(-x**2), (x, -oo, oo))\n```\n\n**(2) limits**\n$$ \\lim\\limits_{x\\rightarrow 0}\\frac{\\sin(x)}{x},\\quad \\lim\\limits_{x\\rightarrow 0^{+}}\\frac{1}{x},\\quad \\lim\\limits_{x\\rightarrow 0^{-}}\\frac{1}{x}$$\n\n\n```python\nlimit(sin(x)/x, x, 0)\n```\n\n\n```python\nlimit(1/x, x, 0, dir=\"+\")\n```\n\n\n```python\nlimit(1/x, x, 0, dir=\"-\")\n```\n\n**(3) series**\n\n\n```python\nexp(x)\n```\n\n\n```python\nseries(exp(x), x)\n```\n\n\n```python\nseries(exp(x), x, 1)\n```\n\n\n```python\nseries(sin(x), x, 0, 12)\n```\n\n\n```python\nseries(sin(x)*cos(x), x, 0, 8)\n```\n\n\n```python\nseries(sin(x)*cos(x)*exp(x), x, 0, 12)\n```\n\n### Linear algebra: Matrices\n\n\n```python\nm11, m12, m21, m22 = symbols(\"m11, m12, m21, m22\")\nb1, b2 = symbols(\"b1, b2\")\n```\n\n\n```python\nA = Matrix([[m11, m12],[m21, m22]])\nA\n```\n\n\n```python\nb = Matrix([[b1], [b2]])\nb\n```\n\n\n```python\nA**2\n```\n\n\n```python\nA**5\n```\n\n\n```python\nA * b\n```\n\n\n```python\nA.det()\n```\n\n\n```python\nA.inv()\n```\n\n### Solving equations\nSolving \n$$ x^2 - 1 = 0,\\quad x^4 - x^2 - 1 = 0$$\n\n\n```python\nsolve(x**2 - 1, x)\n```\n\n\n```python\nsolve(x**4 + x**3 - x**2 - 1, x)\n```\n\nSolving systems:\n$$ x + y - 1 = 0,\\quad x - y - 1 = 0,$$\nand\n$$ x + y - a = 0,\\quad x - y - b = 0.$$\n\n\n```python\nsolve([x + y - 1, x - y - 1], [x,y])\n```\n\n\n```python\na, b = symbols('a, b')\nsolve([x + y - a, x - y - b], [x,y])\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "5a7fef66e1431fc87c367c88ae2ee9840bd5b4c0", "size": 906623, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Scientific_Computing/Scientific_Python.ipynb", "max_stars_repo_name": "xiaozhouli/Jupyter", "max_stars_repo_head_hexsha": "68d5a384dd939b3e8079da4470d6401d11b63a4c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2020-02-27T13:09:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-14T09:50:30.000Z", "max_issues_repo_path": "Scientific_Computing/Scientific_Python.ipynb", "max_issues_repo_name": "xiaozhouli/Jupyter", "max_issues_repo_head_hexsha": "68d5a384dd939b3e8079da4470d6401d11b63a4c", "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": "Scientific_Computing/Scientific_Python.ipynb", "max_forks_repo_name": "xiaozhouli/Jupyter", "max_forks_repo_head_hexsha": "68d5a384dd939b3e8079da4470d6401d11b63a4c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2018-10-18T10:20:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-24T08:09:27.000Z", "avg_line_length": 483.0170484816, "max_line_length": 231684, "alphanum_fraction": 0.9367730578, "converted": true, "num_tokens": 3132, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465062370313, "lm_q2_score": 0.9372107979795823, "lm_q1q2_score": 0.8766168454978225}} {"text": "# Appendix B.2 $\\quad$ Complex Numbers in Linear Algebra\n\n### Example 1\n\nSolve the following linear system\n\\begin{eqnarray*}\n% \\nonumber to remove numbering (before each equation)\n (1+i)x_1 + (2+i)x_2 &=& 5, \\\\\n (2-2i)x_1 +ix_2 &=& 1+2i.\n\\end{eqnarray*}\n\n\n```python\nfrom sympy import *\n\nx1, x2 = symbols('x1 x2');\nEq1 = (1+1j)*x1 + (2+1j)*x2 - 5;\nEq2 = (2-2j)*x1 + 1j*x2 - (1+2j);\n\nsolve([Eq1, Eq2], (x1, x2))\n```\n\n\n\n\n {x2: 2.0 - 1.0*I, x1: 0.0}\n\n\n\n### Example 2\n\nFind the determinant of the coefficient matrix in Example 1.\n\n\n```python\nfrom sympy import *\n\nA = Matrix([[1+1j, 2+1j], [2-2j, 1j]]);\n\nA.det()\n```\n\n\n\n\n -7.0 + 3.0*I\n\n\n\n### Example 3\n\nFind the eigenvalues and eigenvector of\n\\begin{equation*}\n A =\n \\left[\n \\begin{array}{cc}\n 1 & 1 \\\\\n -1 & 1 \\\\\n \\end{array}\n \\right]\n\\end{equation*}\n\n\n```python\nfrom sympy import *\n\nA = Matrix([[1, 1], [-1, 1]]);\n\nA.eigenvects()\n```\n\n\n\n\n [(1 - I, 1, [Matrix([\n [I],\n [1]])]), (1 + I, 1, [Matrix([\n [-I],\n [ 1]])])]\n\n\n\n### Example 4\n\nFind the eigenvalues and eigenvector of\n\\begin{equation*}\n A = \\left[\n \\begin{array}{ccc}\n 2 & 0 & 0\\\\\n 0 & 2 & i \\\\\n 0 & -i & 2\\\\\n \\end{array}\n \\right]\n\\end{equation*}\n\n\n```python\nfrom sympy import *\n\nA = Matrix([[2, 0, 0], [0, 2, 1j], [0, -1j, 2]]);\n\nA.eigenvects()\n```\n\n\n\n\n [(1.00000000000000, 1, [Matrix([\n [ 0],\n [-1.0*I],\n [ 1.0]])]), (2.00000000000000, 1, [Matrix([\n [1.0],\n [ 0],\n [ 0]])]), (3.00000000000000, 1, [Matrix([\n [ 0],\n [1.0*I],\n [ 1.0]])])]\n\n\n\n**Remark:** If $A$ is a Hermitian matrix (i.e., $\\overline{A^T} = A$), then



\n", "meta": {"hexsha": "5893464555eaccfe3a277aa1182b7c2c027d9ebe", "size": 4609, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Jupyter_Notes/Lecture37_Appdx-B2_ComplexNumbersLinearAlgebra.ipynb", "max_stars_repo_name": "xiuquan0418/MAT341", "max_stars_repo_head_hexsha": "2fb7ec4e5f0771f10719cb5e4a00a7ab07c49b59", "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_Notes/Lecture37_Appdx-B2_ComplexNumbersLinearAlgebra.ipynb", "max_issues_repo_name": "xiuquan0418/MAT341", "max_issues_repo_head_hexsha": "2fb7ec4e5f0771f10719cb5e4a00a7ab07c49b59", "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_Notes/Lecture37_Appdx-B2_ComplexNumbersLinearAlgebra.ipynb", "max_forks_repo_name": "xiuquan0418/MAT341", "max_forks_repo_head_hexsha": "2fb7ec4e5f0771f10719cb5e4a00a7ab07c49b59", "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": 19.3655462185, "max_line_length": 107, "alphanum_fraction": 0.4135387286, "converted": true, "num_tokens": 700, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240177362488, "lm_q2_score": 0.934395157516935, "lm_q1q2_score": 0.8765785393230822}} {"text": "## Maximum Likelihood Estimation\n\nMaximum likelihood estimation is one of the key techniques employed in statistical signal processing for a wide variety of applications from signal detection to parameter estimation. In the following, we consider a simple experiment and work through the details of maximum likelihood estimation to ensure that we understand the concept in one of its simplest applications.\n\n### Setting up the Coin Flipping Experiment\n\nSuppose we have coin and want to estimate the probability of heads ($p$) for it. The coin is Bernoulli distributed:\n\n$$ \\phi(x)= p^x (1-p)^{(1-x)} $$\n\nwhere $x$ is the outcome, *1* for heads and *0* for tails. The $n$ independent flips, we have the likelihood:\n\n$$ \\mathcal{L}(p|\\mathbf{x})= \\prod_{i=1}^n p^{ x_i }(1-p)^{1-x_i} $$\n\nThis is basically notation. We have just substituted everything into $ \\phi(x)$ under the independent-trials assumption. \n\nThe idea of *maximum likelihood* is to maximize this as the function of $p$ after plugging in all of the $x_i$ data. This means that our estimator, $\\hat{p}$ , is a function of the observed $x_i$ data, and as such, is a random variable with its own distribution.\n\n### Simulating the Experiment\n\nWe need the following code to simulate coin flipping.\n\n\n```\n%matplotlib inline\nfrom __future__ import division\nfrom scipy.stats import bernoulli \nimport numpy as np\n\np_true=1/2 # this is the value we will try to estimate from the observed data\nfp=bernoulli(p_true)\n\ndef sample(n=10):\n 'simulate coin flipping'\n return fp.rvs(n)# flip it n times\n\nxs = sample(100) # generate some samples\n```\n\nNow, we can write out the likelihood function using `sympy`\n\n\n```\nimport sympy\nfrom sympy.abc import x, z\np=sympy.symbols('p',positive=True)\n\nL=p**x*(1-p)**(1-x)\nJ=np.prod([L.subs(x,i) for i in xs]) # objective function to maximize\n```\n\nBelow, we find the maximum using basic calculus. Note that taking the `log` of $J$ makes the maximization problem tractable but doesn't change the extrema.\n\n\n```\nlogJ=sympy.expand_log(sympy.log(J))\nsol=sympy.solve(sympy.diff(logJ,p),p)[0]\n\nx=linspace(0,1,100)\nplot(x,map(sympy.lambdify(p,logJ,'numpy'),x),sol,logJ.subs(p,sol),'o',\n p_true,logJ.subs(p,p_true),'s',)\nxlabel('$p$',fontsize=18)\nylabel('Likelihood',fontsize=18)\ntitle('Estimate not equal to true value',fontsize=18)\n```\n\nNote that our estimator $\\hat{p}$ (red circle) is not equal to the true value of $p$ (green square), but it is at the maximum of the likelihood function. This may sound disturbing, but keep in mind this estimate is a function of the random data; and since that data can change, the ultimate estimate can likewise change. I invite you to run this notebook a few times to observe this. Remember that the estimator is a *function* of the data and is thus also a *random variable*, just like the data is. \n\nLet's write some code to empirically examine the behavior of the maximum likelihood estimator using a simulation of multiple trials. All we're doing here is combining the last few blocks of code.\n\n\n```\ndef estimator_gen(niter=10,ns=100):\n 'generate data to estimate distribution of maximum likelihood estimator'\n out=[]\n x=sympy.symbols('x',real=True)\n L= p**x*(1-p)**(1-x)\n for i in range(niter):\n xs = sample(ns) # generate some samples from the experiment\n J=np.prod([L.subs(x,i) for i in xs]) # objective function to maximize\n logJ=sympy.expand_log(sympy.log(J)) \n sol=sympy.solve(sympy.diff(logJ,p),p)[0]\n out.append(float(sol.evalf()))\n return out if len(out)>1 else out[0] # return scalar if list contains only 1 term\n \netries = estimator_gen(100) # this may take awhile, depending on how much data you want to generate\nhist(etries) # histogram of maximum likelihood estimator\ntitle('$\\mu=%3.3f,\\sigma=%3.3f$'%(mean(etries),std(etries)),fontsize=18)\n```\n\nNote that the mean of the estimator ($\\mu$) is pretty close to the true value, but looks can be deceiving. The only way to know for sure is to check if the estimator is unbiased, namely, if\n\n$$ \\mathbb{E}(\\hat{p}) = p $$\n\nBecause this problem is simple, we can solve for this in general noting that since $x=0$ or $x=1$, the terms in the product of $\\mathcal{L}$ above are either $p$, if $x_i=1$ or $1-p$ if $x_i=0$. This means that we can write\n\n$$ \\mathcal{L}(p|\\mathbf{x})= p^{\\sum_{i=1}^n x_i}(1-p)^{n-\\sum_{i=1}^n x_i} $$\n\nwith corresponding log as\n\n$$ J=\\log(\\mathcal{L}(p|\\mathbf{x})) = \\log(p) \\sum_{i=1}^n x_i + \\log(1-p) \\left(n-\\sum_{i=1}^n x_i\\right)$$ \n\nTaking the derivative of this gives:\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\nand solving this leads to\n\n$$ \\hat{p} = \\frac{1}{ n} \\sum_{i=1}^n x_i $$\n\nThis is our *estimator* for $p$. Up til now, we have been using `sympy` to solve for this based on the data $x_i$ but now we have it generally and don't have to solve for it again. To check if this estimator is biased, we compute its expectation:\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\nby linearity of the expectation and where\n\n$$\\mathbb{E}(x_i) = p$$\n\nTherefore,\n\n$$ \\mathbb{E}\\left(\\hat{p}\\right) =p $$\n\nThis means that the esimator is unbiased. This is good news. We almost always want our estimators to be unbiased. Similarly, \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\nand where\n\n$$ \\mathbb{E}\\left(x_i^2\\right) =p$$\n\nand by the independence assumption,\n\n$$ \\mathbb{E}\\left(x_i x_j\\right) =\\mathbb{E}(x_i)\\mathbb{E}( x_j) =p^2$$\n\nThus,\n\n$$ \\mathbb{E}\\left(\\hat{p}^2\\right) =\\left(\\frac{1}{n^2}\\right) n \n\\left[\np+(n-1)p^2\n\\right]\n$$\n\nSo, the variance of the estimator, $\\hat{p}$ is the following:\n\n$$ \\sigma_\\hat{p}^2 = \\mathbb{E}\\left(\\hat{p}^2\\right)- \\mathbb{E}\\left(\\hat{p}\\right)^2 = \\frac{p(1-p)}{n} $$\n\nNote that the $n$ in the denominator means that the variance asymptotically goes to zero as $n$ increases (i.e. we consider more and more samples). This is good news also because it means that more and more coin flips leads to a better estimate of the underlying $p$.\n\nUnfortunately, this formula for the variance is practically useless because we have to know $p$ to compute it and $p$ is the parameter we are trying to estimate in the first place! But, looking at $ \\sigma_\\hat{p}^2 $, we can immediately notice that if $p=0$, then there is no estimator variance because the outcomes are guaranteed to be tails. Also, the maximum of this variance, for whatever $n$, happens at $p=1/2$. This is our worst case scenario and the only way to compensate is with more samples (i.e. larger $n$). \n\n\nAll we have computed is the mean and variance of the estimator. In general, this is insufficient to characterize the underlying probability density of $\\hat{p}$, except if we somehow knew that $\\hat{p}$ were normally distributed. This is where the powerful [*central limit theorem*](http://mathworld.wolfram.com/CentralLimitTheorem.html) comes in. The form of the estimator, which is just a mean estimator, implies that we can apply this theorem and conclude that $\\hat{p}$ is normally distributed. However, there's a wrinkle here: the theorem tells us that $\\hat{p}$ is asymptotically normal, it doesn't quantify how many samples $n$ we need to approach this asymptotic paradise. In our simulation this is no problem since we can generate as much data as we like, but in the real world, with a costly experiment, each sample may be precious. In the following, we won't apply this theorem and instead proceed analytically.\n\n\n### Probability Density for the Estimator\n\nTo write out the full density for $\\hat{p}$, we first have to ask what is the probability that the estimator will equal a specific value and the tally up all the ways that could happen with their corresponding probabilities. For example, what is the probability that\n\n$$ \\hat{p} = \\frac{1}{n}\\sum_{i=1}^n x_i = 0 $$\n\nThis can only happen one way: when $x_i=0 \\hspace{0.5em} \\forall i$. The probability of this happening can be computed from the density\n\n$$ f(\\mathbf{x},p)= \\prod_{i=1}^n \\left(p^{x_i} (1-p)^{1-x_i} \\right) $$\n\n$$ f\\left(\\sum_{i=1}^n x_i = 0,p\\right)= \\left(1-p\\right)^n $$\n\nLikewise, if $\\lbrace x_i \\rbrace$ has one $i^{th}$ value equal to one, then\n\n$$ f\\left(\\sum_{i=1}^n x_i = 1,p\\right)= n p \\prod_{i=1}^{n-1} \\left(1-p\\right)$$\n\nwhere the $n$ comes from the $n$ ways to pick one value equal to one from the $n$ elements $x_i$. Continuing this way, we can construct the entire density as\n\n$$ f\\left(\\sum_{i=1}^n x_i = k,p\\right)= \\binom{n}{k} p^k (1-p)^{n-k} $$\n\nwhere the term on the left is the binomial coefficient of $n$ things taken $k$ at a time. This is the binomial distribution and it's not the density for $\\hat{p}$, but rather for $n\\hat{p}$. We'll leave this as-is because it's easier to work with below. We just have to remember to keep track 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 meaningful questions. For example,\n\n$$ \\mathbb{P}\\left( | \\hat{p}-p | \\le \\epsilon p \\right) $$\n\nOr, in words, what is the probability we can get within $\\epsilon$ percent of the true value of $p$. Rewriting,\n\n$$ \\mathbb{P}\\left( p - \\epsilon p \\lt \\hat{p} \\lt p + \\epsilon p \\right) = \\mathbb{P}\\left( n p - n \\epsilon p \\lt \\sum_{i=1}^n x_i \\lt n p + n \\epsilon p \\right)$$\n\nLet's plug in some live numbers here for our worst case scenario where $p=1/2$. Then, if $\\epsilon = 1/100$, we have\n\n$$ \\mathbb{P}\\left( \\frac{99 n}{100} \\lt \\sum_{i=1}^n x_i \\lt \\frac{101 n}{100} \\right)$$\n\nSince the sum in integer-valued, we need $n> 100$ to even compute this. Thus, if $n=101$ we have\n\n$$ \\mathbb{P}\\left( \\frac{9999}{200} \\lt \\sum_{i=1}^{101} x_i \\lt \\frac{10201}{200} \\right) = f\\left(\\sum_{i=1}^{101} x_i = 50,p\\right)= \\binom{101}{50} (1/2)^{50} (1-1/2)^{101-50} = 0.079$$\n\nThis means that in the worst-case scenario for $p=1/2$, given $n=101$ trials, we will only get within 1% of the actual $p=1/2$ about 8% of the time. If you feel disappointed, that only means you've been paying attention. What if the coin was really heavy and it was costly to repeat this 101 times? Then, we would be within 1% of the actual value only 8% of the time. Those odds are terrible.\n\nLet's come at this another way: given I could only flip the coin 100 times, how close could I come to the true underlying value with high probability (say, 95%)? In this case we are seeking to solve for $\\epsilon$. Plugging in gives,\n\n$$ \\mathbb{P}\\left( 50 - 50 \\epsilon \\lt \\sum_{i=1}^{100} x_i \\lt 50 + 50 \\epsilon \\right) = 0.95$$\n\nwhich we have to solve for $\\epsilon$. Fortunately, all the tools we need to solve for this are already in `scipy`.\n\n\n```\nimport scipy.stats\n\nb=scipy.stats.binom(100,.5) # n=100, p = 0.5, distribution of the estimator \\hat{p}\n\nf,ax= subplots()\nax.stem(arange(0,101),b.pmf(arange(0,101))) # heres the density of the sum of x_i\n\ng = lambda i:b.pmf(arange(-i,i)+50).sum() # symmetric sum the probability around the mean\nprint 'this is pretty close to 0.95:%r'%g(10)\nax.vlines( [50+10,50-10],0 ,ax.get_ylim()[1] ,color='r',lw=3.)\n\n```\n\nThe two vertical lines in the plot show how far out from the mean we have to go to accumulate 95% of the probability. Now, we can solve this as\n\n$$ 50 + 50 \\epsilon = 60 $$\n\nwhich makes $\\epsilon=1/5$ or 20%. So, flipping 100 times means I can only get within 20% of the real $p$ 95% of the time in the worst case scenario (i.e. $p=1/2$).\n\n\n\n```\nb=scipy.stats.bernoulli(.5) # coin distribution\nxs = b.rvs(100) # flip it 100 times\nphat = mean(xs) # estimated p\n\nprint abs(phat-0.5) < 0.5*0.20 # did I make it w/in interval 95% of the time?\n```\n\n True\n\n\nLet's keep doing this and see if we can get within this interval 95% of the time.\n\n\n```\nout=[]\nb=scipy.stats.bernoulli(.5) # coin distribution\nfor i in range(500): # number of tries\n xs = b.rvs(100) # flip it 100 times\n phat = mean(xs) # estimated p\n out.append(abs(phat-0.5) < 0.5*0.20 ) # within 20% \n\nprint 'Percentage of tries within 20 interval = %3.2f'%(100*sum(out)/float(len(out) ))\n```\n\n Percentage of tries within 20 interval = 97.20\n\n\nWell, that seems to work. Now we have a way to get at the quality of the estimator, $\\hat{p}$. \n\n## Summary\n\nIn this section, we explored the concept of maximum likelihood estimation using a coin flipping experiment both analytically and numerically with the scientific Python tool chain. There are two key points to remember. First, maximum likelihood estimation produces a function of the data that is itself a random variable, with its own statistics and distribution. Second, it's worth considering how to analytically derive the density function of the estimator rather than relying on canned packages to compute confidence intervals wherever possible. This is especially true when data is hard to come by and the approximations made in the central limit theorem are therefore harder to justify.\n\n### References\n\nThis [IPython notebook](www.ipython.org) is available for [download](https://github.com/unpingco/Python-for-Signal-Processing/blob/master/Maximum_likelihood.ipynb). I urge you to experiment with the calculations for different parameters. As always, corrections and comments are welcome!\n", "meta": {"hexsha": "cf7a331f3ce88e08167b6ddbd5af1ba995341819", "size": 58946, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Maximum_likelihood.ipynb", "max_stars_repo_name": "harunpehlivan/Python-for-Signal-Processing", "max_stars_repo_head_hexsha": "d9a1c8e32a68528b4d44c4176d47beb4e8eaccf5", "max_stars_repo_licenses": ["CC-BY-3.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": "Maximum_likelihood.ipynb", "max_issues_repo_name": "harunpehlivan/Python-for-Signal-Processing", "max_issues_repo_head_hexsha": "d9a1c8e32a68528b4d44c4176d47beb4e8eaccf5", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Maximum_likelihood.ipynb", "max_forks_repo_name": "harunpehlivan/Python-for-Signal-Processing", "max_forks_repo_head_hexsha": "d9a1c8e32a68528b4d44c4176d47beb4e8eaccf5", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 114.6809338521, "max_line_length": 19606, "alphanum_fraction": 0.8058731721, "converted": true, "num_tokens": 3982, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632302488963, "lm_q2_score": 0.9207896682831526, "lm_q1q2_score": 0.8764658280318113}} {"text": "### Gradient Descent\n\nJay Urbain, PhD\n\nCredits: \n- https://gist.github.com/sagarmainkar\n \n \n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\n```\n\n\n```python\nplt.style.use(['ggplot'])\n```\n\n# Create Data\n\n
Generate some data with:\n\\begin{equation} \\theta_0= 4 \\end{equation} \n\\begin{equation} \\theta_1= 3 \\end{equation} \n\nAdd some Gaussian noise to the data\n\n\n```python\nX = 2 * np.random.rand(100,1)\ny = 4 +3 * X+np.random.randn(100,1)\n```\n\nLet's plot our data to check the relation between X and Y\n\n\n```python\n\nplt.plot(X,y,'b.')\nplt.xlabel(\"$x$\", fontsize=18)\nplt.ylabel(\"$y$\", rotation=0, fontsize=18)\n_ =plt.axis([0,2,0,15])\n```\n\n# Analytical way of Linear Regression\n\n\n```python\nX_b = np.c_[np.ones((100,1)),X]\ntheta_best = np.linalg.inv(X_b.T.dot(X_b)).dot(X_b.T).dot(y)\nprint(theta_best)\n```\n\n [[4.19057743]\n [2.98123237]]\n\n\n
This is close to our real thetas 4 and 3. It cannot be accurate due to the noise I have introduced in data\n\n\n```python\nX_new = np.array([[0],[2]])\nX_new_b = np.c_[np.ones((2,1)),X_new]\ny_predict = X_new_b.dot(theta_best)\ny_predict\n```\n\n\n\n\n array([[ 4.19057743],\n [10.15304217]])\n\n\n\n
Let's plot prediction line with calculated:theta\n\n\n```python\nplt.plot(X_new,y_predict,'r-')\nplt.plot(X,y,'b.')\nplt.xlabel(\"$x_1$\", fontsize=18)\nplt.ylabel(\"$y$\", rotation=0, fontsize=18)\nplt.axis([0,2,0,15])\n\n```\n\n# Gradient Descent\n\n## Cost Function & Gradients\n\n

The equation for calculating cost function and gradients are as shown below. Please note the cost function is for Linear regression. For other algorithms the cost function will be different and the gradients would have to be derived from the cost functions\n\n\n\nCost\n\\begin{equation}\nJ(\\theta) = 1/2m \\sum_{i=1}^{m} (h(\\theta)^{(i)} - y^{(i)})^2 \n\\end{equation}\n\nGradient\n\n\\begin{equation}\n\\frac{\\partial J(\\theta)}{\\partial \\theta_j} = 1/m\\sum_{i=1}^{m}(h(\\theta^{(i)} - y^{(i)}).X_j^{(i)}\n\\end{equation}\n\nGradients\n\\begin{equation}\n\\theta_0: = \\theta_0 -\\alpha . (1/m .\\sum_{i=1}^{m}(h(\\theta^{(i)} - y^{(i)}).X_0^{(i)})\n\\end{equation}\n\\begin{equation}\n\\theta_1: = \\theta_1 -\\alpha . (1/m .\\sum_{i=1}^{m}(h(\\theta^{(i)} - y^{(i)}).X_1^{(i)})\n\\end{equation}\n\\begin{equation}\n\\theta_2: = \\theta_2 -\\alpha . (1/m .\\sum_{i=1}^{m}(h(\\theta^{(i)} - y^{(i)}).X_2^{(i)})\n\\end{equation}\n\n\\begin{equation}\n\\theta_j: = \\theta_j -\\alpha . (1/m .\\sum_{i=1}^{m}(h(\\theta^{(i)} - y^{(i)}).X_0^{(i)})\n\\end{equation}\n\n\n```python\n\ndef cal_cost(theta,X,y):\n '''\n \n Calculates the cost for given X and Y. The following shows and example of a single dimensional X\n theta = Vector of thetas \n X = Row of X's np.zeros((2,j))\n y = Actual y's np.zeros((2,1))\n \n where:\n j is the no of features\n '''\n \n m = len(y)\n \n predictions = X.dot(theta)\n cost = (1/2*m) * np.sum(np.square(predictions-y))\n return cost\n\n```\n\n\n```python\ndef gradient_descent(X,y,theta,learning_rate=0.01,iterations=100):\n '''\n X = Matrix of X with added bias units\n y = Vector of Y\n theta=Vector of thetas np.random.randn(j,1)\n learning_rate \n iterations = no of iterations\n \n Returns the final theta vector and array of cost history over no of iterations\n '''\n m = len(y)\n cost_history = np.zeros(iterations)\n theta_history = np.zeros((iterations,2))\n for it in range(iterations):\n \n prediction = np.dot(X,theta)\n \n theta = theta -(1/m)*learning_rate*( X.T.dot((prediction - y)))\n theta_history[it,:] =theta.T\n cost_history[it] = cal_cost(theta,X,y)\n \n return theta, cost_history, theta_history\n \n \n \n```\n\n

Let's start with 1000 iterations and a learning rate of 0.01. Start with theta from a Gaussian distribution\n\n\n```python\nlr =0.01\nn_iter = 1000\n\ntheta = np.random.randn(2,1)\n\nX_b = np.c_[np.ones((len(X),1)),X]\ntheta,cost_history,theta_history = gradient_descent(X_b,y,theta,lr,n_iter)\n\n\nprint('Theta0: {:0.3f},\\nTheta1: {:0.3f}'.format(theta[0][0],theta[1][0]))\nprint('Final cost/MSE: {:0.3f}'.format(cost_history[-1]))\n```\n\n Theta0: 4.063,\n Theta1: 3.088\n Final cost/MSE: 5864.178\n\n\n

Let's plot the cost history over iterations\n\n\n```python\nfig,ax = plt.subplots(figsize=(12,8))\n\nax.set_ylabel('J(Theta)')\nax.set_xlabel('Iterations')\n_=ax.plot(range(n_iter),cost_history,'b.')\n```\n\n

After around 150 iterations the cost is flat so the remaining iterations are not needed or will not result in any further optimization. Let us zoom in till iteration 200 and see the curve\n\n\n```python\n\nfig,ax = plt.subplots(figsize=(10,8))\n_=ax.plot(range(200),cost_history[:200],'b.')\n```\n\nIt is worth while to note that the cost drops faster initially and then the gain in cost reduction is not as much\n\n### It would be great to see the effect of different learning rates and iterations together\n\n### Let us build a function which can show the effects together and also show how gradient decent actually is working\n\n\n```python\n\ndef plot_GD(n_iter,lr,ax,ax1=None):\n \"\"\"\n n_iter = no of iterations\n lr = Learning Rate\n ax = Axis to plot the Gradient Descent\n ax1 = Axis to plot cost_history vs Iterations plot\n\n \"\"\"\n _ = ax.plot(X,y,'b.')\n theta = np.random.randn(2,1)\n\n tr =0.1\n cost_history = np.zeros(n_iter)\n for i in range(n_iter):\n pred_prev = X_b.dot(theta)\n theta,h,_ = gradient_descent(X_b,y,theta,lr,1)\n pred = X_b.dot(theta)\n\n cost_history[i] = h[0]\n\n if ((i % 25 == 0) ):\n _ = ax.plot(X,pred,'r-',alpha=tr)\n if tr < 0.8:\n tr = tr+0.2\n if not ax1== None:\n _ = ax1.plot(range(n_iter),cost_history,'b.') \n```\n\n### Plot the graphs for different iterations and learning rates combination\n\n\n```python\nfig = plt.figure(figsize=(30,25),dpi=200)\nfig.subplots_adjust(hspace=0.4, wspace=0.4)\n\nit_lr =[(2000,0.001),(500,0.01),(200,0.05),(100,0.1)]\ncount =0\nfor n_iter, lr in it_lr:\n count += 1\n \n ax = fig.add_subplot(4, 2, count)\n count += 1\n \n ax1 = fig.add_subplot(4,2,count)\n \n ax.set_title(\"lr:{}\".format(lr))\n ax1.set_title(\"Iterations:{}\".format(n_iter))\n plot_GD(n_iter,lr,ax,ax1)\n \n```\n\n See how useful it is to visualize the effect of learning rates and iterations on gradient descent. The red lines show how the gradient descent starts and then slowly gets closer to the final value\n\n## You can always plot Indiviual graphs to zoom in\n\n\n```python\n_,ax = plt.subplots(figsize=(14,10))\nplot_GD(100,0.1,ax)\n```\n\n# Stochastic Gradient Descent\n\n\n```python\ndef stocashtic_gradient_descent(X,y,theta,learning_rate=0.01,iterations=10):\n '''\n X = Matrix of X with added bias units\n y = Vector of Y\n theta=Vector of thetas np.random.randn(j,1)\n learning_rate \n iterations = no of iterations\n \n Returns the final theta vector and array of cost history over no of iterations\n '''\n m = len(y)\n cost_history = np.zeros(iterations)\n \n \n for it in range(iterations):\n cost =0.0\n for i in range(m):\n rand_ind = np.random.randint(0,m)\n X_i = X[rand_ind,:].reshape(1,X.shape[1])\n y_i = y[rand_ind].reshape(1,1)\n prediction = np.dot(X_i,theta)\n\n theta = theta -(1/m)*learning_rate*( X_i.T.dot((prediction - y_i)))\n cost += cal_cost(theta,X_i,y_i)\n cost_history[it] = cost\n \n return theta, cost_history\n```\n\n\n```python\nlr =0.5\nn_iter = 50\n\ntheta = np.random.randn(2,1)\n\nX_b = np.c_[np.ones((len(X),1)),X]\ntheta,cost_history = stocashtic_gradient_descent(X_b,y,theta,lr,n_iter)\n\n\nprint('Theta0: {:0.3f},\\nTheta1: {:0.3f}'.format(theta[0][0],theta[1][0]))\nprint('Final cost/MSE: {:0.3f}'.format(cost_history[-1]))\n```\n\n Theta0: 4.116,\n Theta1: 2.981\n Final cost/MSE: 51.160\n\n\n\n```python\nfig,ax = plt.subplots(figsize=(10,8))\n\nax.set_ylabel('{J(Theta)}',rotation=0)\nax.set_xlabel('{Iterations}')\ntheta = np.random.randn(2,1)\n\n_=ax.plot(range(n_iter),cost_history,'b.')\n```\n\n# Mini Batch Gradient Descent\n\n\n```python\ndef minibatch_gradient_descent(X,y,theta,learning_rate=0.01,iterations=10,batch_size =20):\n '''\n X = Matrix of X without added bias units\n y = Vector of Y\n theta=Vector of thetas np.random.randn(j,1)\n learning_rate \n iterations = no of iterations\n \n Returns the final theta vector and array of cost history over no of iterations\n '''\n m = len(y)\n cost_history = np.zeros(iterations)\n n_batches = int(m/batch_size)\n \n for it in range(iterations):\n cost =0.0\n indices = np.random.permutation(m)\n X = X[indices]\n y = y[indices]\n for i in range(0,m,batch_size):\n X_i = X[i:i+batch_size]\n y_i = y[i:i+batch_size]\n \n X_i = np.c_[np.ones(len(X_i)),X_i]\n \n prediction = np.dot(X_i,theta)\n\n theta = theta -(1/m)*learning_rate*( X_i.T.dot((prediction - y_i)))\n cost += cal_cost(theta,X_i,y_i)\n cost_history[it] = cost\n \n return theta, cost_history\n```\n\n\n```python\nlr =0.1\nn_iter = 200\n\ntheta = np.random.randn(2,1)\n\n\ntheta,cost_history = minibatch_gradient_descent(X,y,theta,lr,n_iter)\n\n\nprint('Theta0: {:0.3f},\\nTheta1: {:0.3f}'.format(theta[0][0],theta[1][0]))\nprint('Final cost/MSE: {:0.3f}'.format(cost_history[-1]))\n```\n\n Theta0: 4.060,\n Theta1: 3.092\n Final cost/MSE: 1171.808\n\n\n\n```python\nfig,ax = plt.subplots(figsize=(10,8))\n\nax.set_ylabel('{J(Theta)}',rotation=0)\nax.set_xlabel('{Iterations}')\ntheta = np.random.randn(2,1)\n\n_=ax.plot(range(n_iter),cost_history,'b.')\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "34a32234da6637bf35212418eb5d4f023d5580fa", "size": 963818, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/GradientDescent.ipynb", "max_stars_repo_name": "larsonma/DataScienceIntro", "max_stars_repo_head_hexsha": "7aa776cbadffb38e678e5da195a4208c22b86488", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2018-09-04T13:07:38.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-20T18:39:15.000Z", "max_issues_repo_path": "notebooks/GradientDescent.ipynb", "max_issues_repo_name": "larsonma/DataScienceIntro", "max_issues_repo_head_hexsha": "7aa776cbadffb38e678e5da195a4208c22b86488", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2018-09-06T14:48:10.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-06T19:39:21.000Z", "max_forks_repo_path": "notebooks/GradientDescent.ipynb", "max_forks_repo_name": "larsonma/DataScienceIntro", "max_forks_repo_head_hexsha": "7aa776cbadffb38e678e5da195a4208c22b86488", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10, "max_forks_repo_forks_event_min_datetime": "2018-08-21T16:19:11.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-20T20:44:48.000Z", "avg_line_length": 1027.5245202559, "max_line_length": 814688, "alphanum_fraction": 0.952878033, "converted": true, "num_tokens": 2971, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947163538936, "lm_q2_score": 0.9273632986579697, "lm_q1q2_score": 0.8763534173722993}} {"text": "# Lab 4\n## Introduction\nThe Euler method is a method for numerically solving a DE of the form\n\\begin{align}\n\\frac{\\mathrm{d}y}{\\mathrm{d}x} = f(x,y).\n\\end{align}\n\nIt is often necessary to solve DEs this way as analytical solutions are the exception\nrather than the rule.\n\n\n\nEuler’s method works by approximating small segments of the curve solution to the DE\nwith the straight-line tangent or slope of the curve. As long as we keep the segments\nsmall enough, they will approximately match what the actual curve looks like. It requires us to ”know” an initial value $y(x_0) = y_0$ so we can start the calculation.\n\nTo calculate the first segment we start off with our known start point $(x_0, y_0)$, and calculate the end point, $(x_1, y_1)$. We can define $\\Delta x$ to be some constant small distance so that we always increment the $x$ value by the same amount. Then, $\\Delta y = m \\Delta x$ and $(x_1, y_1)=(x_0, y_0)+(\\Delta x, m\\Delta x)$.\n\n\n\nBut, we also know that $m$, the slope of the line, is given by $\\mathrm{d}y/\\mathrm{d}x$, i.e., $f(x, y)$ evaluated at $(x_0, y_0)$. So actually, $\\Delta y = f(x_0, y_0) \\Delta x$.\n\nThe final step is to calculate the new point: the point at the end of the first line segment. This point is then given by $(x_1, y_1) = (x_0 + \\Delta x, y_0 + f(x_0, y_0) \\Delta x)$.\n\nWe then do it again to calculate $(x_2, y_2)$ using $(x_1, y_1)$ as our starting point. We then do it again to calculate $(x_3, y_3)$ using $(x_2, y_2)$ as our starting point and so on.\n\n**Summary:** The Euler method for evaluating a DE of the form\n\\begin{align}\n\\frac{\\mathrm{d}y}{\\mathrm{d}x} = f(x,y).\n\\end{align}\ninvolves the iterative calculation of\n\\begin{align}\nx_{n+1} &= x_n + \\Delta x\\\\\n\\text{and}\\quad y_{n+1} &= y_n + f(x_n,y_n)\\Delta x.\n\\end{align}\n\n### Implementation\n\nFirst import the necessary functions from NumPy and SciPy and set up Plotly.\n\n\n```python\nfrom numpy import arange, empty, exp\nfrom plotly import graph_objs as go\n```\n\nNow let's write a function that implements Euler's method. We will model it on `scipy.integrate.odeint`. We will make slight changes to the parameters because we want to input $\\Delta x$. Note that the string (delimited by triple quotes) immediately after the function definition is a _docstring_. It tells us what the function does and is good programming practice. The prodigious comments in the function body are not generally necessary but are included for you.\n\n\n```python\ndef euler(func, y0, x0, xn, Dx):\n \"\"\"\n Integrate an ordinary differential equation using Euler's method.\n \n Solves the initial value problem for systems of first order ode-s::\n dy/dx = func(y, x).\n \n Parameters\n ----------\n func : callable(y, x)\n Computes the derivative of y at x.\n y0 : float\n Initial condition on y.\n x0 : float\n Initial condition on x.\n xn : float\n Upper limit to value of x.\n Dx : float\n x increment.\n \n Returns\n -------\n x : float\n Array containing the value of x for each value of x0 + n * Dx,\n where n ranges from zero to floor( (xn - x0) / Dx ).\n y : float\n Array containing the value of y for each value of x.\n \"\"\"\n x = arange(x0, xn, Dx) # Create the x array\n y = empty(len(x)) # Create an empty y array of the same length as x\n y[0] = y0 # Set the first value of y to y0\n for n in range(len(x) - 1): # Loop to populate the rest of the values of y\n y[n+1] = y[n] + func(y[n], x[n]) * Dx # Euler's method\n \n return x, y # Return x and y as a pair\n```\n\nFirst try solving\n\\begin{align}\n\\frac{\\mathrm{d}y}{\\mathrm{d}x} = y.\n\\end{align}\nfor $y(0)=1$ for $x$ between 1 and 5 and using $\\Delta x=1$.\n\n\n```python\ndef diff_eq(y, x):\n return y\n\nx, y = euler(diff_eq, 1, 0, 5.01, 1)\n```\n\nWhy was `xn` set to 5.01 rather than 5?\n\nWe know that the analytic solution to the above IVP is $y=\\mathrm{e}^x$, so calculate that as well.\n\n\n```python\nx_analytic = arange(0, 5.01, 0.1)\ny_analytic = exp(x_analytic)\n```\n\nNow plot them both for comparison.\n\n\n```python\nfig = go.Figure()\nfig.add_trace(go.Scatter(x=x, y=y,\n name='Euler'))\nfig.add_trace(go.Scatter(x=x_analytic,\n y=y_analytic,\n name='Truth'))\nfig.show('png')\n```\n\nReproduce the comparison plot below but with $\\Delta x=0.1$.\n\n\n```python\n\n```\n\n\nIt is possible to quantify the error in the Euler solution compared to the analytic solution. To do this you need to re-calculate the analytic solution at the same $x$ points as you calculated your Euler solution. Then you can do a Mean Squared Error (MSE) comparison between the two.\n\n\n```python\nx, y = euler(diff_eq, 1, 0, 5.01, 1)\ny_analytic = exp(x)\n((y_analytic - y)**2).mean()\n```\n\nNote that `((y_analytic - y)**2)` returned an `array` object, and then we called the `mean` method that was _bound_ to that object.\n\nWhat is the MSE if $\\Delta x = 0.1$?\n\n\n```python\n\n```\n\n## Exercises\n\nIn this lab you will try Euler's method for a couple of differential equations.\n\n1. a. Consider the IVP\n\\begin{align}\n\\frac{\\mathrm{d}y}{\\mathrm{d}x} = 2x\\quad\\text{where}\\quad y(-2)=4.\n\\end{align}\nCalculate the Euler approximation on the interval $x=[-2,2]$ using a step size of $\\Delta x = 0.5$. On the same figure, plot your approximation and the analytic solution.\n\n\n```python\n\n```\n\n1. b. Calculate the mean squared error (MSE) of the approximation.\n\n\n```python\n\n```\n\n1. c. Reproduce your plot from 1a except with $\\Delta x=0.1$.\n\n\n```python\n\n```\n\n1. d. Recalculate the MSE.\n\n\n```python\n\n```\n\n2. a. The following is the DE for the arrow problem from class.\n\\begin{align}\n\\frac{\\mathrm{d}y}{\\mathrm{d}t} = 294\\mathrm{e}^{-0.04t}-245\\quad\\text{where}\\quad y(0)=0\n\\end{align}\nCalculate the Euler approximation to the solution on the interval $t=[0,10]$ with $\\Delta t=0.5$. Plot your approximation and the analytic solution on the same figure.\n\n\n```python\n\n```\n\n2. b. Calculate the MSE of the approximation.\n\n\n```python\n\n```\n\n2. c. Reproduce your plot from 2a except with $\\Delta t=0.1$.\n\n\n```python\n\n```\n\n2. d. Recalculate the MSE.\n\n\n```python\n\n```\n", "meta": {"hexsha": "9702a81b4b6cc20a8ccc8d4f6c305d5c1a7ec227", "size": 13497, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/lab-04.ipynb", "max_stars_repo_name": "StuartClive/mm-labs", "max_stars_repo_head_hexsha": "2f0d4529144f7f666e73bbd98a7636bfa86f2aec", "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": "notebooks/lab-04.ipynb", "max_issues_repo_name": "StuartClive/mm-labs", "max_issues_repo_head_hexsha": "2f0d4529144f7f666e73bbd98a7636bfa86f2aec", "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": "notebooks/lab-04.ipynb", "max_forks_repo_name": "StuartClive/mm-labs", "max_forks_repo_head_hexsha": "2f0d4529144f7f666e73bbd98a7636bfa86f2aec", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-07-27T07:23:17.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-27T07:23:17.000Z", "avg_line_length": 26.3099415205, "max_line_length": 472, "alphanum_fraction": 0.5353782322, "converted": true, "num_tokens": 1823, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632976542184, "lm_q2_score": 0.9449947171284515, "lm_q1q2_score": 0.8763534171420562}} {"text": "# The $\\chi^2$ Distribution\n\n## $\\chi^2$ Test Statistic\n\nIf we make $n$ ranom samples (observations) from Gaussian (Normal) distributions with known means, $\\mu_i$, and known variances, $\\sigma_i^2$, it is seen that the total squared deviation,\n\n$$\n\\chi^2 = \\sum_{i=1}^{n} \\left(\\frac{x_i - \\mu_i}{\\sigma_i}\\right)^2\\,,\n$$\n\nfollows a $\\chi^2$ distribution with $n$ degrees of freedom.\n\n## Probability Distribution Function\n\nThe $\\chi^2$ probability distribution function for $k$ degrees of freedom (the number of parameters that are allowed to vary) is given by\n\n$$\nf\\left(\\chi^2\\,;k\\right) = \\frac{\\displaystyle 1}{\\displaystyle 2^{k/2} \\,\\Gamma\\left(k\\,/2\\right)}\\, \\chi^{k-2}\\,e^{-\\chi^2/2}\\,,\n$$\n\nwhere if there are no constrained variables the number of degrees of freedom, $k$, is equal to the number of observations, $k=n$. The p.d.f. is often abbreviated in notation from $f\\left(\\chi^2\\,;k\\right)$ to $\\chi^2_k$.\n\nA reminder that for integer values of $k$, the Gamma function is $\\Gamma\\left(k\\right) = \\left(k-1\\right)!$, and that $\\Gamma\\left(x+1\\right) = x\\Gamma\\left(x\\right)$, and $\\Gamma\\left(1/2\\right) = \\sqrt{\\pi}$.\n\n## Mean\n\nLetting $\\chi^2=z$, and noting that the form of the Gamma function is\n\n$$\n\\Gamma\\left(z\\right) = \\int\\limits_{0}^{\\infty} x^{z-1}\\,e^{-x}\\,dx,\n$$\n\nit is seen that the mean of the $\\chi^2$ distribution $f\\left(\\chi^2 ; k\\right)$ is\n\n$$\n\\begin{align}\n\\mu &= \\textrm{E}\\left[z\\right] = \\displaystyle\\int\\limits_{0}^{\\infty} z\\, \\frac{\\displaystyle 1}{\\displaystyle 2^{k/2} \\,\\Gamma\\left(k\\,/2\\right)}\\, z^{k/2-1}\\,e^{-z\\,/2}\\,dz \\\\\n &= \\displaystyle \\frac{\\displaystyle 1}{\\displaystyle \\Gamma\\left(k\\,/2\\right)} \\int\\limits_{0}^{\\infty} \\left(\\frac{z}{2}\\right)^{k/2}\\,e^{-z\\,/2}\\,dz = \\displaystyle \\frac{\\displaystyle 1}{\\displaystyle \\Gamma\\left(k\\,/2\\right)} \\int\\limits_{0}^{\\infty} x^{k/2}\\,e^{-x}\\,2 \\,dx \\\\\n &= \\displaystyle \\frac{\\displaystyle 2 \\,\\Gamma\\left(k\\,/2 + 1\\right)}{\\displaystyle \\Gamma\\left(k\\,/2\\right)} \\\\\n &= \\displaystyle 2 \\frac{k}{2} \\frac{\\displaystyle \\Gamma\\left(k\\,/2\\right)}{\\displaystyle \\Gamma\\left(k\\,/2\\right)} \\\\\n &= k.\n\\end{align}\n$$\n\n## Variance\n\nLikewise, the variance is\n\n$$\n\\begin{align}\n\\textrm{Var}\\left[z\\right] &= \\textrm{E}\\left[\\left(z-\\textrm{E}\\left[z\\right]\\right)^2\\right] = \\displaystyle\\int\\limits_{0}^{\\infty} \\left(z - k\\right)^2\\, \\frac{\\displaystyle 1}{\\displaystyle 2^{k/2} \\,\\Gamma\\left(k\\,/2\\right)}\\, z^{k/2-1}\\,e^{-z\\,/2}\\,dz \\\\\n &= \\displaystyle\\int\\limits_{0}^{\\infty} z^2\\, f\\left(z \\,; k\\right)\\,dz - 2k\\int\\limits_{0}^{\\infty} z\\,\\,f\\left(z \\,; k\\right)\\,dz + k^2\\int\\limits_{0}^{\\infty} f\\left(z \\,; k\\right)\\,dz \\\\\n &= \\displaystyle\\int\\limits_{0}^{\\infty} z^2 \\frac{\\displaystyle 1}{\\displaystyle 2^{k/2} \\,\\Gamma\\left(k\\,/2\\right)}\\, z^{k/2-1}\\,e^{-z\\,/2}\\,dz - 2k^2 + k^2\\\\\n &= \\displaystyle\\int\\limits_{0}^{\\infty} \\frac{\\displaystyle 1}{\\displaystyle 2^{k/2} \\,\\Gamma\\left(k\\,/2\\right)}\\, z^{k/2+1}\\,e^{-z\\,/2}\\,dz - k^2\\\\\n &= \\frac{\\displaystyle 2}{\\displaystyle \\Gamma\\left(k\\,/2\\right)} \\displaystyle\\int\\limits_{0}^{\\infty} \\left(\\frac{z}{2}\\right)^{k/2+1}\\,e^{-z\\,/2}\\,dz - k^2 = \\frac{\\displaystyle 2}{\\displaystyle \\Gamma\\left(k\\,/2\\right)} \\displaystyle\\int\\limits_{0}^{\\infty} x^{k/2+1}\\,e^{-x}\\,2\\,dx - k^2 \\\\\n &= \\displaystyle \\frac{\\displaystyle 4 \\,\\Gamma\\left(k\\,/2 + 2\\right)}{\\displaystyle \\Gamma\\left(k\\,/2\\right)} - k^2 \\\\\n &= \\displaystyle 4 \\left(\\frac{k}{2} + 1\\right) \\frac{\\displaystyle \\Gamma\\left(k\\,/2 + 1\\right)}{\\displaystyle \\Gamma\\left(k\\,/2\\right)} - k^2 \\\\\n &= \\displaystyle 4 \\left(\\frac{k}{2} + 1\\right) \\frac{k}{2} - k^2 \\\\\n &= k^2 + 2k - k^2 \\\\\n &= 2k,\n\\end{align}\n$$\n\nsuch that the standard deviation is\n\n$$\n\\sigma = \\sqrt{2k}\\,.\n$$\n\nGiven this information we now plot the $\\chi^2$ p.d.f. with various numbers of degrees of freedom to visualize how the distribution's behaviour\n\n\n```python\nimport numpy as np\nimport scipy.stats as stats\n\nimport matplotlib.pyplot as plt\n```\n\n\n```python\n# Plot the chi^2 distribution\nx = np.linspace(0.0, 10.0, num=1000)\n\n[plt.plot(x, stats.chi2.pdf(x, df=ndf), label=fr\"$k = ${ndf}\") for ndf in range(1, 7)]\n\nplt.ylim(-0.01, 0.5)\n\nplt.xlabel(r\"$x=\\chi^2$\")\nplt.ylabel(r\"$f\\left(x;k\\right)$\")\nplt.title(r\"$\\chi^2$ distribution for various degrees of freedom\")\n\nplt.legend(loc=\"best\")\n\nplt.show();\n```\n\n## Cumulative Distribution Function\n\nThe cumulative distribution function (CDF) for the $\\chi^2$ distribution is (letting $z=\\chi^2$)\n\n$$\n\\begin{split}\nF_{\\chi^2}\\left(x\\,; k\\right) &= \\int\\limits_{0}^{x} f_{\\chi^2}\\left(z\\,; k\\right) \\,dz \\\\\n &= \\int\\limits_{0}^{x} \\frac{\\displaystyle 1}{\\displaystyle 2^{k/2} \\,\\Gamma\\left(k\\,/2\\right)}\\, z^{k/2-1}\\,e^{-z/2} \\,dz \\\\\n &= \\int\\limits_{0}^{x} \\frac{\\displaystyle 1}{\\displaystyle 2 \\,\\Gamma\\left(k\\,/2\\right)}\\, \\left(\\frac{z}{2}\\right)^{k/2-1}\\,e^{-z/2} \\,dz = \\frac{1}{\\displaystyle 2 \\,\\Gamma\\left(k\\,/2\\right)}\\int\\limits_{0}^{x/2} t^{k/2-1}\\,e^{-t} \\,2\\,dt \\\\\n &= \\frac{1}{\\displaystyle \\Gamma\\left(k\\,/2\\right)}\\int\\limits_{0}^{x/2} t^{k/2-1}\\,e^{-t} \\,dt\n\\end{split}\n$$\n\nNoting the form of the [lower incomplete gamma function](https://en.wikipedia.org/wiki/Incomplete_gamma_function) is\n\n$$\n\\gamma\\left(s,x\\right) = \\int\\limits_{0}^{x} t^{s-1}\\,e^{-t} \\,dt\\,,\n$$\n\nand the form of the [regularized Gamma function](https://en.wikipedia.org/wiki/Incomplete_gamma_function#Regularized_Gamma_functions_and_Poisson_random_variables) is\n\n$$\nP\\left(s,x\\right) = \\frac{\\gamma\\left(s,x\\right)}{\\Gamma\\left(s\\right)}\\,,\n$$\n\nit is seen that\n\n$$\n\\begin{split}\nF_{\\chi^2}\\left(x\\,; k\\right) &= \\frac{1}{\\displaystyle \\Gamma\\left(k\\,/2\\right)}\\int\\limits_{0}^{x/2} t^{k/2-1}\\,e^{-t} \\,dt \\\\\n &= \\frac{\\displaystyle \\gamma\\left(\\frac{k}{2},\\frac{x}{2}\\right)}{\\displaystyle \\Gamma\\left(\\frac{k}{2}\\right)} \\\\\n &= P\\left(\\frac{k}{2},\\frac{x}{2}\\right)\\,.\n\\end{split}\n$$\n\nThus, it is seen that the compliment to the CDF (the complementary cumulative distribution function (CCDF)),\n\n$$\n\\bar{F}_{\\chi^2}\\left(x\\,; k\\right) = 1-F_{\\chi^2}\\left(x\\,; k\\right),\n$$\n\nrepresents a one-sided (one-tailed) $p$-value for observing a $\\chi^2$ given a model — that is, the probability to observe a $\\chi^2$ value greater than or equal to that which was observed.\n\n\n```python\ndef chi2_ccdf(x, df):\n \"\"\"The complementary cumulative distribution function\n\n Args:\n x: the value of chi^2\n df: the number of degrees of freedom\n\n Returns:\n 1 - the cumulative distribution function\n \"\"\"\n return 1.0 - stats.chi2.cdf(x=x, df=df)\n```\n\n\n```python\nx = np.linspace(0.0, 10.0, num=1000)\nfig, axes = plt.subplots(nrows=1, ncols=2, figsize=(14, 4.5))\n\nfor ndf in range(1, 7):\n axes[0].plot(x, stats.chi2.cdf(x, df=ndf), label=fr\"$k = ${ndf}\")\n axes[1].plot(x, chi2_ccdf(x, df=ndf), label=fr\"$k = ${ndf}\")\n\naxes[0].set_xlabel(r\"$x=\\chi^2$\")\naxes[0].set_ylabel(r\"$F\\left(x;k\\right)$\")\naxes[0].set_title(r\"$\\chi^2$ CDF for various degrees of freedom\")\n\naxes[0].legend(loc=\"best\")\n\naxes[1].set_xlabel(r\"$x=\\chi^2$\")\naxes[1].set_ylabel(r\"$\\bar{F}\\left(x;k\\right) = p$-value\")\naxes[1].set_title(r\"$\\chi^2$ CCDF ($p$-value) for various degrees of freedom\")\n\naxes[1].legend(loc=\"best\")\n\nplt.show();\n```\n\n## Binned $\\chi^2$ per Degree of Freedom\n\nTODO\n\n## References\n\n- \\[1\\] G. Cowan, _Statistical Data Analysis_, Oxford University Press, 1998\n- \\[2\\] G. Cowan, \"Goodness of fit and Wilk's theorem\", Notes, 2013\n", "meta": {"hexsha": "4d167b6ca37e89b420b3ca15def2abf0006d0085", "size": 12646, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "book/notebooks/Introductory/Chi-Squared-Distribution.ipynb", "max_stars_repo_name": "matthewfeickert/Statistics-Notes", "max_stars_repo_head_hexsha": "088181920b0f560fdd2ed593d3653f67baa56190", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 18, "max_stars_repo_stars_event_min_datetime": "2018-02-15T15:22:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-18T07:28:57.000Z", "max_issues_repo_path": "book/notebooks/Introductory/Chi-Squared-Distribution.ipynb", "max_issues_repo_name": "matthewfeickert/Statistics-Notes", "max_issues_repo_head_hexsha": "088181920b0f560fdd2ed593d3653f67baa56190", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2018-05-08T22:51:03.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-08T03:58:30.000Z", "max_forks_repo_path": "book/notebooks/Introductory/Chi-Squared-Distribution.ipynb", "max_forks_repo_name": "matthewfeickert/Statistics-Notes", "max_forks_repo_head_hexsha": "088181920b0f560fdd2ed593d3653f67baa56190", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2018-10-24T17:15:44.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-13T00:27:06.000Z", "avg_line_length": 30.4722891566, "max_line_length": 341, "alphanum_fraction": 0.5019769097, "converted": true, "num_tokens": 2793, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541544761565, "lm_q2_score": 0.9304582487448421, "lm_q1q2_score": 0.8761698754971896}} {"text": "# Working with Matrices\n\n\n```python\nimport numpy as np\n```\n\n## Matrices and liner combinations\n\n### Post-multiplication with vector\n\nMatrix-vector multiplication is a linear combination of the columns of the matrix\n\n$$\n\\begin{bmatrix}\n1 & 2 \\\\\n3 & 4 \\\\\n5 & 6\n\\end{bmatrix}\n\\begin{bmatrix}\n2 \\\\ 3\n\\end{bmatrix} =\n2 \\begin{bmatrix}\n1 \\\\ 3 \\\\ 5\n\\end{bmatrix} +\n3 \\begin{bmatrix}\n2 \\\\ 4 \\\\ 6\n\\end{bmatrix} =\n\\begin{bmatrix}\n8 \\\\\n18 \\\\\n28\n\\end{bmatrix}\n$$\n\n$$\n\\begin{bmatrix}\n1 & 2 \\\\\n3 & 4 \\\\\n5 & 6\n\\end{bmatrix}\n\\begin{bmatrix}\n1 \\\\ 4\n\\end{bmatrix} =\n1 \\begin{bmatrix}\n1 \\\\ 3 \\\\ 5\n\\end{bmatrix} +\n4 \\begin{bmatrix}\n2 \\\\ 4 \\\\ 6\n\\end{bmatrix} =\n\\begin{bmatrix}\n9 \\\\\n19 \\\\\n29\n\\end{bmatrix}\n$$\n\nWe can stack the columns horizontally to get matrix multiplication.\n\n$$\n\\begin{bmatrix}\n1 & 2 \\\\\n3 & 4 \\\\\n5 & 6\n\\end{bmatrix}\n\\begin{bmatrix}\n2 & 1 \\\\ 3 & 4\n\\end{bmatrix} =\n\\begin{bmatrix}\n8 & 9 \\\\\n18 & 19 \\\\\n28 & 29\n\\end{bmatrix}\n$$\n\n\n```python\nA = np.arange(1, 7).reshape((3,2))\nx1 = np.array([2, 3]).reshape((2,1))\nx2 = np.array([1,4]).reshape((2,1))\n```\n\n\n```python\nA @ x1\n```\n\n\n\n\n array([[ 8],\n [18],\n [28]])\n\n\n\n\n```python\nA @ x2\n```\n\n\n\n\n array([[ 9],\n [19],\n [29]])\n\n\n\n\n```python\nnp.c_[x1, x2]\n```\n\n\n\n\n array([[2, 1],\n [3, 4]])\n\n\n\n\n```python\nA @ np.c_[x1, x2]\n```\n\n\n\n\n array([[ 8, 9],\n [18, 19],\n [28, 29]])\n\n\n\n### Pre-multiplication with vector\n\nVector-matrix multiplication is a linear combination of the rows of the matrix\n\n$$\n\\begin{bmatrix}\n1 & 2 & 3\n\\end{bmatrix}\n\\begin{bmatrix}\n1 & 2 \\\\\n3 & 4 \\\\\n5 & 6\n\\end{bmatrix}=\n1 \\begin{bmatrix}\n1 & 2\n\\end{bmatrix} +\n2 \\begin{bmatrix}\n3 & 4\n\\end{bmatrix} +\n3 \\begin{bmatrix}\n5 & 6\n\\end{bmatrix} =\n\\begin{bmatrix}\n22 & 28\n\\end{bmatrix}\n$$\n\n$$\n\\begin{bmatrix}\n4 & 5 & 6\n\\end{bmatrix}\n\\begin{bmatrix}\n1 & 2 \\\\\n3 & 4 \\\\\n5 & 6\n\\end{bmatrix}=\n4 \\begin{bmatrix}\n1 & 2\n\\end{bmatrix} +\n5 \\begin{bmatrix}\n3 & 4\n\\end{bmatrix} +\n6 \\begin{bmatrix}\n5 & 6\n\\end{bmatrix} =\n\\begin{bmatrix}\n49 & 64\n\\end{bmatrix}\n$$\n\nWe can stack the rows vertically to get matrix multiplication.\n\n$$\n\\begin{bmatrix}\n1 & 2 & 3 \\\\\n4 & 5 & 4\n\\end{bmatrix}\n\\begin{bmatrix}\n1 & 2 \\\\\n3 & 4 \\\\\n5 & 6\n\\end{bmatrix} =\n\\begin{bmatrix}\n22 & 28 \\\\\n49 & 64\n\\end{bmatrix}\n$$\n\nMatrix-matrix multiplication can be seen as the horizontal stacking of column operations or as the vertical stacking of row operations.\n\n\n```python\ny1 = np.array([1,2,3]).reshape((1,3))\ny2 = np.array([4,5,6]).reshape((1,3))\n```\n\n\n```python\ny1 @ A\n```\n\n\n\n\n array([[22, 28]])\n\n\n\n\n```python\ny2 @ A\n```\n\n\n\n\n array([[49, 64]])\n\n\n\n\n```python\nnp.r_[y1, y2]\n```\n\n\n\n\n array([[1, 2, 3],\n [4, 5, 6]])\n\n\n\n\n```python\nnp.r_[y1, y2] @ A\n```\n\n\n\n\n array([[22, 28],\n [49, 64]])\n\n\n\n### Extract columns of a matrix by post-multiplication with standard unit column vector\n\n\n```python\nA\n```\n\n\n\n\n array([[1, 2],\n [3, 4],\n [5, 6]])\n\n\n\n\n```python\ne2 = np.array([0,1]).reshape((-1,1))\n```\n\n\n```python\nA @ e2\n```\n\n\n\n\n array([[2],\n [4],\n [6]])\n\n\n\n### Extract rows of a matrix by pre-multiplication with standard unit row vector\n\n\n```python\ne2 = np.array([0,1,0]).reshape((-1, 1))\n```\n\n\n```python\ne2.T @ A\n```\n\n\n\n\n array([[3, 4]])\n\n\n\n## Permutation matrices\n\nFrom the column extraction by post-multiplication with a standard unit column vector, we generalize to permutation matrices (identity matrix with permuted columns). Post-multiplication of a matrix $A$ with a permutation matrix $P$ rearranges the columns of $A$. To recover the original matrix, multiply with $P^T$ - i.e. $P^{-1} = P^T$ and the inverse of $P$ is its inverse, $P$ being our first example of an orthogonal matrix.\n\n\n```python\nA = np.arange(1, 17).reshape((4,4))\nA\n```\n\n\n\n\n array([[ 1, 2, 3, 4],\n [ 5, 6, 7, 8],\n [ 9, 10, 11, 12],\n [13, 14, 15, 16]])\n\n\n\n\n```python\nI = np.eye(4, dtype='int')\nI\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\n```python\nA @ I\n```\n\n\n\n\n array([[ 1, 2, 3, 4],\n [ 5, 6, 7, 8],\n [ 9, 10, 11, 12],\n [13, 14, 15, 16]])\n\n\n\n\n```python\np = I[:, [2,1,3,0]]\np\n```\n\n\n\n\n array([[0, 0, 0, 1],\n [0, 1, 0, 0],\n [1, 0, 0, 0],\n [0, 0, 1, 0]])\n\n\n\n\n```python\nA @ p\n```\n\n\n\n\n array([[ 3, 2, 4, 1],\n [ 7, 6, 8, 5],\n [11, 10, 12, 9],\n [15, 14, 16, 13]])\n\n\n\n\n```python\nA @ p @ p.T\n```\n\n\n\n\n array([[ 1, 2, 3, 4],\n [ 5, 6, 7, 8],\n [ 9, 10, 11, 12],\n [13, 14, 15, 16]])\n\n\n\n## Matrix partitioning \n\nWe see above that matrix multiplication can be seen as separate operations on the row or column vectors. We can actually partition matrices into blocks (not just vectors) for matrix multiplication. Suppose we want to calculate $AB$, where\n\n\\begin{align}\nA = \\begin{bmatrix}\n1 & 0 & 1 & 0 \\\\\n0 & 1 & 0 & 1 \\\\\n0 & 0 & 2 & 0 \\\\\n0 & 0 & 0 & 3\n\\end{bmatrix}&, & B = \\begin{bmatrix}\n1 & 2 & 3 & 4 \\\\\n5 & 6 & 7 & 8 \\\\\n0 & 0 & 1 & 0 \\\\\n0 & 0 & 0 & 1\n\\end{bmatrix}\n\\end{align}\n\nWe can consider (say) $A$ and $B$ as each being a $2 \\times 2$ matrix where each element is a $2 \\times 2$ sub-matrix (or block). This simplifies the computation since many blocks are the identity or null matrix.\n\n\\begin{align}\nA = \\begin{bmatrix}\nA_{11} & A_{12} \\\\\nA_{21} & A_{22}\n\\end{bmatrix}&, & B = \\begin{bmatrix}\nB_{11} & B_{12} \\\\\nB_{21} & B_{22}\n\\end{bmatrix}\n\\end{align}\n\nand \n\n$$\nAB = \\begin{bmatrix}\nA_{11}B_{11} + A_{12}B_{21} & A_{11}B_{12} + A_{12}B_{22} \\\\\nA_{21}B_{11} + A_{22}B_{22} & A_{21}B_{12} + A_{22}B_{22}\n\\end{bmatrix}\n$$\n\nIn fact, we can see by inspection that the result will be\n\n$$\nAB = \\begin{bmatrix}\nB_{11} & B_{12}+I_2 \\\\\n0_2 & A_{22}\n\\end{bmatrix} = \\begin{bmatrix}\n1 & 2 & 4 & 4 \\\\\n5 & 6 & 7 & 9 \\\\\n0 & 0 & 2 & 0 \\\\\n0 & 0 & 0 & 3\n\\end{bmatrix}\n$$\n\nIn general, any sub-block structure consistent with matrix multiplication (more formally, $A$ and $B$ are *conformable* for multiplication) is fine. In particular, the blocks do not have to be square.\n\n\n```python\na11 = np.eye(2)\na12 = np.eye(2)\na21 = np.zeros((2,2))\na22 = np.diag((2,3))\n\nb11 = np.array([\n [1,2],\n [5,6] \n])\nb12 = np.array([\n [3,4],\n [7,8]\n])\nb21 = np.zeros((2,2))\nb22 = np.eye(2)\n```\n\n\n```python\nA = np.block([\n [a11, a12],\n [a21, a22]\n]).astype('int')\nA\n```\n\n\n\n\n array([[1, 0, 1, 0],\n [0, 1, 0, 1],\n [0, 0, 2, 0],\n [0, 0, 0, 3]])\n\n\n\n\n```python\nB = np.block([\n [b11, b12],\n [b21, b22]\n]).astype('int')\nB\n```\n\n\n\n\n array([[1, 2, 3, 4],\n [5, 6, 7, 8],\n [0, 0, 1, 0],\n [0, 0, 0, 1]])\n\n\n\n\n```python\nA @ B\n```\n\n\n\n\n array([[1, 2, 4, 4],\n [5, 6, 7, 9],\n [0, 0, 2, 0],\n [0, 0, 0, 3]])\n\n\n\n\n```python\nnp.block([\n [a11@b11 + a12@b21, a11@b12 + a12@b22],\n [a21@b11 + a22@b21, a21@b12 + a22@b22]\n]).astype('int')\n```\n\n\n\n\n array([[1, 2, 4, 4],\n [5, 6, 7, 9],\n [0, 0, 2, 0],\n [0, 0, 0, 3]])\n\n\n", "meta": {"hexsha": "09de35240901682dec84f7726bdeefc8131617ad", "size": 16756, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/S08A_Matrices_Linear_Combinations_Annotated.ipynb", "max_stars_repo_name": "cjuracek/sta-663-2020", "max_stars_repo_head_hexsha": "9f0e81e783000b1485951322561b3e47acef5072", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 47, "max_stars_repo_stars_event_min_datetime": "2020-01-08T21:45:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T09:25:59.000Z", "max_issues_repo_path": "notebooks/S08A_Matrices_Linear_Combinations_Annotated.ipynb", "max_issues_repo_name": "cjuracek/sta-663-2020", "max_issues_repo_head_hexsha": "9f0e81e783000b1485951322561b3e47acef5072", "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/S08A_Matrices_Linear_Combinations_Annotated.ipynb", "max_forks_repo_name": "cjuracek/sta-663-2020", "max_forks_repo_head_hexsha": "9f0e81e783000b1485951322561b3e47acef5072", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 54, "max_forks_repo_forks_event_min_datetime": "2020-01-08T21:46:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-15T05:04:00.000Z", "avg_line_length": 20.3844282238, "max_line_length": 434, "alphanum_fraction": 0.4128073526, "converted": true, "num_tokens": 2806, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.972830769252026, "lm_q2_score": 0.9005297787765764, "lm_q1q2_score": 0.8760630774215736}} {"text": "# Quadratic Equations\n\nConsider the following equation:\n\n\\begin{equation}y = 2(x - 1)(x + 2)\\end{equation}\n\nIf you multiply out the factored ***x*** expressions, this equates to:\n\n\\begin{equation}y = 2x^{2} + 2x - 4\\end{equation}\n\nNote that the highest ordered term includes a squared variable (x2).\n\nLet's graph this equation for a range of ***x*** values:\n\n\n```python\nimport pandas as pd\n\n# Create a dataframe with an x column containing values to plot\ndf = pd.DataFrame ({'x': range(-9, 9)})\n\n# Add a y column by applying the quadratic equation to x\ndf['y'] = 2*df['x']**2 + 2 *df['x'] - 4\n\n# Plot the line\n%matplotlib inline\nfrom matplotlib import pyplot as plt\n\nplt.plot(df.x, df.y, color=\"grey\")\nplt.xlabel('x')\nplt.ylabel('y')\nplt.grid()\nplt.axhline()\nplt.axvline()\nplt.show()\n```\n\nNote that the graph shows a *parabola*, which is an arc-shaped line that reflects the x and y values calculated for the equation.\n\nNow let's look at another equation that includes an ***x2*** term:\n\n\\begin{equation}y = -2x^{2} + 6x + 7\\end{equation}\n\nWhat does that look like as a graph?:\n\n\n```python\nimport pandas as pd\n\n# Create a dataframe with an x column containing values to plot\ndf = pd.DataFrame ({'x': range(-8, 12)})\n\n# Add a y column by applying the quadratic equation to x\ndf['y'] = -2*df['x']**2 + 6*df['x'] + 7\n\n# Plot the line\n%matplotlib inline\nfrom matplotlib import pyplot as plt\n\nplt.plot(df.x, df.y, color=\"grey\")\nplt.xlabel('x')\nplt.ylabel('y')\nplt.grid()\nplt.axhline()\nplt.axvline()\nplt.show()\n```\n\nAgain, the graph shows a parabola, but this time instead of being open at the top, the parabola is open at the bottom.\n\nEquations that assign a value to ***y*** based on an expression that includes a squared value for ***x*** create parabolas. If the relationship between ***y*** and ***x*** is such that ***y*** is a *positive* multiple of the ***x2*** term, the parabola will be open at the top; when ***y*** is a *negative* multiple of the ***x2*** term, then the parabola will be open at the bottom.\n\nThese kinds of equations are known as *quadratic* equations, and they have some interesting characteristics. There are several ways quadratic equations can be written, but the *standard form* for quadratic equation is:\n\n\\begin{equation}y = ax^{2} + bx + c\\end{equation}\n\nWhere ***a***, ***b***, and ***c*** are numeric coefficients or constants.\n\nLet's start by examining the parabolas generated by quadratic equations in more detail.\n\n## Parabola Vertex and Line of Symmetry\nParabolas are symmetrical, with x and y values converging exponentially towards the highest point (in the case of a downward opening parabola) or lowest point (in the case of an upward opening parabola). The point where the parabola meets the line of symmetry is known as the *vertex*.\n\nRun the following cell to see the line of symmetry and vertex for the two parabolas described previously (don't worry about the calculations used to find the line of symmetry and vertex - we'll explore that later):\n\n\n```python\n%matplotlib inline\n\ndef plot_parabola(a, b, c):\n import pandas as pd\n import numpy as np\n from matplotlib import pyplot as plt\n \n # get the x value for the line of symmetry\n vx = (-1*b)/(2*a)\n \n # get the y value when x is at the line of symmetry\n vy = a*vx**2 + b*vx + c\n\n # Create a dataframe with an x column containing values from x-10 to x+10\n minx = int(vx - 10)\n maxx = int(vx + 11)\n df = pd.DataFrame ({'x': range(minx, maxx)})\n\n # Add a y column by applying the quadratic equation to x\n df['y'] = a*df['x']**2 + b *df['x'] + c\n\n # get min and max y values\n miny = df.y.min()\n maxy = df.y.max()\n\n # Plot the line\n plt.plot(df.x, df.y, color=\"grey\")\n plt.xlabel('x')\n plt.ylabel('y')\n plt.grid()\n plt.axhline()\n plt.axvline()\n\n # plot the line of symmetry\n sx = [vx, vx]\n sy = [miny, maxy]\n plt.plot(sx,sy, color='magenta')\n\n # Annotate the vertex\n plt.scatter(vx,vy, color=\"red\")\n plt.annotate('vertex',(vx, vy), xytext=(vx - 1, (vy + 5)* np.sign(a)))\n\n plt.show()\n\n\nplot_parabola(2, 2, -4) \n\nplot_parabola(-2, 3, 5) \n```\n\n## Parabola Intercepts\nRecall that linear equations create lines that intersect the **x** and **y** axis of a graph, and we call the points where these intersections occur *intercepts*. Now look at the graphs of the parabolas we've worked with so far. Note that these parabolas both have a y-intercept; a point where the line intersects the y axis of the graph (in other words, when x is 0). However, note that the parabolas have *two* x-intercepts; in other words there are two points at which the line crosses the x axis (and y is 0). Additionally, imagine a downward opening parabola with its vertex at -1, -1. This is perfectly possible, and the line would never have an x value greater than -1, so it would have *no* x-intercepts.\n\nRegardless of whether the parabola crosses the x axis or not, other than the vertex, for every ***y*** point in the parabola, there are *two* ***x*** points; one on the right (or positive) side of the axis of symmetry, and one of the left (or negative) side. The implications of this are what make quadratic equations so interesting. When we solve the equation for ***x***, there are *two* correct answers.\n\nLet's take a look at an example to demonstrate this. Let's return to the first of our quadratic equations, and we'll look at it in its *factored* form:\n\n\\begin{equation}y = 2(x - 1)(x + 2)\\end{equation}\n\nNow, let's solve this equation for a ***y*** value of 0. We can restate the equation like this:\n\n\\begin{equation}2(x - 1)(x + 2) = 0\\end{equation}\n\nThe equation is the product of two expressions **2(x - 1)** and **(x + 2)**. In this case, we know that the product of these expressions is 0, so logically *one or both of the expressions must return 0*.\n\nLet's try the first one:\n\n\\begin{equation}2(x - 1) = 0\\end{equation}\n\nIf we distrbute this, we get:\n\n\\begin{equation}2x - 2 = 0\\end{equation}\n\nThis simplifies to:\n\n\\begin{equation}2x = 2\\end{equation}\n\nWhich gives us a value for *x* of **1**.\n\nNow let's try the other expression:\n\n\\begin{equation}x + 2 = 0\\end{equation}\n\nThis gives us a value for *x* of **-2**.\n\nSo, when *y* is **0**, *x* is **-2** or **1**. Let's plot these points on our parabola:\n\n\n```python\nimport pandas as pd\n\n# Assign the calculated x values\nx1 = -2\nx2 = 1\n\n# Create a dataframe with an x column containing some values to plot\ndf = pd.DataFrame ({'x': range(x1-5, x2+6)})\n\n# Add a y column by applying the quadratic equation to x\ndf['y'] = 2*(df['x'] - 1) * (df['x'] + 2)\n\n# Get x at the line of symmetry (halfway between x1 and x2)\nvx = (x1 + x2) / 2\n\n# Get y when x is at the line of symmetry\nvy = 2*(vx -1)*(vx + 2)\n\n# get min and max y values\nminy = df.y.min()\nmaxy = df.y.max()\n\n# Plot the line\n%matplotlib inline\nfrom matplotlib import pyplot as plt\n\nplt.plot(df.x, df.y, color=\"grey\")\nplt.xlabel('x')\nplt.ylabel('y')\nplt.grid()\nplt.axhline()\nplt.axvline()\n\n# Plot calculated x values for y = 0\nplt.scatter([x1,x2],[0,0], color=\"green\")\nplt.annotate('x1',(x1, 0))\nplt.annotate('x2',(x2, 0))\n\n# plot the line of symmetry\nsx = [vx, vx]\nsy = [miny, maxy]\nplt.plot(sx,sy, color='magenta')\n\n# Annotate the vertex\nplt.scatter(vx,vy, color=\"red\")\nplt.annotate('vertex',(vx, vy), xytext=(vx - 1, (vy - 5)))\n\nplt.show()\n```\n\nSo from the plot, we can see that both of the values we calculated for ***x*** align with the parabola when ***y*** is 0. Additionally, because the parabola is symmetrical, we know that every pair of ***x*** values for each ***y*** value will be equidistant from the line of symmetry, so we can calculate the ***x*** value for the line of symmetry as the average of the ***x*** values for any value of ***y***. This in turn means that we know the ***x*** coordinate for the vertex (it's on the line of symmetry), and we can use the quadratic equation to calculate ***y*** for this point.\n\n## Solving Quadratics Using the Square Root Method\nThe technique we just looked at makes it easy to calculate the two possible values for ***x*** when ***y*** is 0 if the equation is presented as the product two expressions. If the equation is in standard form, and it can be factored, you could do the necessary manipulation to restate it as the product of two expressions. Otherwise, you can calculate the possible values for x by applying a different method that takes advantage of the relationship between squared values and the square root.\n\nLet's consider this equation:\n\n\\begin{equation}y = 3x^{2} - 12\\end{equation}\n\nNote that this is in the standard quadratic form, but there is no *b* term; in other words, there's no term that contains a coeffecient for ***x*** to the first power. This type of equation can be easily solved using the square root method. Let's restate it so we're solving for ***x*** when ***y*** is 0:\n\n\\begin{equation}3x^{2} - 12 = 0\\end{equation}\n\nThe first thing we need to do is to isolate the ***x2*** term, so we'll remove the constant on the left by adding 12 to both sides:\n\n\\begin{equation}3x^{2} = 12\\end{equation}\n\nThen we'll divide both sides by 3 to isolate x2:\n\n\\begin{equation}x^{2} = 4\\end{equation}\n\nNo we can isolate ***x*** by taking the square root of both sides. However, there's an additional consideration because this is a quadratic equation. The ***x*** variable can have two possibe values, so we must calculate the *principle* and *negative* square roots of the expression on the right:\n\n\\begin{equation}x = \\pm\\sqrt{4}\\end{equation}\n\nThe principle square root of 4 is 2 (because 22 is 4), and the corresponding negative root is -2 (because -22 is also 4); so *x* is **2** or **-2**.\n\nLet's see this in Python, and use the results to calculate and plot the parabola with its line of symmetry and vertex:\n\n\n```python\nimport pandas as pd\nimport math\n\ny = 0\nx1 = int(- math.sqrt(y + 12 / 3))\nx2 = int(math.sqrt(y + 12 / 3))\n\n# Create a dataframe with an x column containing some values to plot\ndf = pd.DataFrame ({'x': range(x1-10, x2+11)})\n\n# Add a y column by applying the quadratic equation to x\ndf['y'] = 3*df['x']**2 - 12\n\n# Get x at the line of symmetry (halfway between x1 and x2)\nvx = (x1 + x2) / 2\n\n# Get y when x is at the line of symmetry\nvy = 3*vx**2 - 12\n\n# get min and max y values\nminy = df.y.min()\nmaxy = df.y.max()\n\n# Plot the line\n%matplotlib inline\nfrom matplotlib import pyplot as plt\n\nplt.plot(df.x, df.y, color=\"grey\")\nplt.xlabel('x')\nplt.ylabel('y')\nplt.grid()\nplt.axhline()\nplt.axvline()\n\n# Plot calculated x values for y = 0\nplt.scatter([x1,x2],[0,0], color=\"green\")\nplt.annotate('x1',(x1, 0))\nplt.annotate('x2',(x2, 0))\n\n# plot the line of symmetry\nsx = [vx, vx]\nsy = [miny, maxy]\nplt.plot(sx,sy, color='magenta')\n\n# Annotate the vertex\nplt.scatter(vx,vy, color=\"red\")\nplt.annotate('vertex',(vx, vy), xytext=(vx - 1, (vy - 20)))\n\nplt.show()\n```\n\n## Solving Quadratics Using the Completing the Square Method\nIn quadratic equations where there is a *b* term; that is, a term containing **x** to the first power, it is impossible to directly calculate the square root. However, with some algebraic manipulation, you can take advantage of the ability to factor a polynomial expression in the form *a2 + 2ab + b2* as a binomial *perfect square* expression in the form *(a + b)2*.\n\nAt first this might seem like some sort of mathematical sleight of hand, but follow through the steps carefull and you'll see that there's nothing up my sleeve!\n\nThe underlying basis of this approach is that a trinomial expression like this:\n\n\\begin{equation}x^{2} + 24x + 12^{2}\\end{equation}\n\nCan be factored to this:\n\n\\begin{equation}(x + 12)^{2}\\end{equation}\n\nOK, so how does this help us solve a quadratic equation? Well, let's look at an example:\n\n\\begin{equation}y = x^{2} + 6x - 7\\end{equation}\n\nLet's start as we've always done so far by restating the equation to solve ***x*** for a ***y*** value of 0:\n\n\\begin{equation}x^{2} + 6x - 7 = 0\\end{equation}\n\nNow we can move the constant term to the right by adding 7 to both sides:\n\n\\begin{equation}x^{2} + 6x = 7\\end{equation}\n\nOK, now let's look at the expression on the left: *x2 + 6x*. We can't take the square root of this, but we can turn it into a trinomial that will factor into a perfect square by adding a squared constant. The question is, what should that constant be? Well, we know that we're looking for an expression like *x2 + 2**c**x + **c**2*, so our constant **c** is half of the coefficient we currently have for ***x***. This is **6**, making our constant **3**, which when squared is **9** So we can create a trinomial expression that will easily factor to a perfect square by adding 9; giving us the expression *x2 + 6x + 9*.\n\nHowever, we can't just add something to one side without also adding it to the other, so our equation becomes:\n\n\\begin{equation}x^{2} + 6x + 9 = 16\\end{equation}\n\nSo, how does that help? Well, we can now factor the trinomial expression as a perfect square binomial expression:\n\n\\begin{equation}(x + 3)^{2} = 16\\end{equation}\n\nAnd now, we can use the square root method to find x + 3:\n\n\\begin{equation}x + 3 =\\pm\\sqrt{16}\\end{equation}\n\nSo, x + 3 is **-4** or **4**. We isolate ***x*** by subtracting 3 from both sides, so ***x*** is **-7** or **1**:\n\n\\begin{equation}x = -7, 1\\end{equation}\n\nLet's see what the parabola for this equation looks like in Python:\n\n\n```python\nimport pandas as pd\nimport math\n\nx1 = int(- math.sqrt(16) - 3)\nx2 = int(math.sqrt(16) - 3)\n\n# Create a dataframe with an x column containing some values to plot\ndf = pd.DataFrame ({'x': range(x1-10, x2+11)})\n\n# Add a y column by applying the quadratic equation to x\ndf['y'] = ((df['x'] + 3)**2) - 16\n\n# Get x at the line of symmetry (halfway between x1 and x2)\nvx = (x1 + x2) / 2\n\n# Get y when x is at the line of symmetry\nvy = ((vx + 3)**2) - 16\n\n# get min and max y values\nminy = df.y.min()\nmaxy = df.y.max()\n\n# Plot the line\n%matplotlib inline\nfrom matplotlib import pyplot as plt\n\nplt.plot(df.x, df.y, color=\"grey\")\nplt.xlabel('x')\nplt.ylabel('y')\nplt.grid()\nplt.axhline()\nplt.axvline()\n\n# Plot calculated x values for y = 0\nplt.scatter([x1,x2],[0,0], color=\"green\")\nplt.annotate('x1',(x1, 0))\nplt.annotate('x2',(x2, 0))\n\n# plot the line of symmetry\nsx = [vx, vx]\nsy = [miny, maxy]\nplt.plot(sx,sy, color='magenta')\n\n# Annotate the vertex\nplt.scatter(vx,vy, color=\"red\")\nplt.annotate('vertex',(vx, vy), xytext=(vx - 1, (vy - 10)))\n\nplt.show()\n```\n\n## Vertex Form\nLet's look at another example of a quadratic equation in standard form:\n\n\\begin{equation}y = 2x^{2} - 16x + 2\\end{equation}\n\nWe can start to solve this by subtracting 2 from both sides to move the constant term from the right to the left:\n\n\\begin{equation}y - 2 = 2x^{2} - 16x\\end{equation}\n\nNow we can factor out the coefficient for x2, which is **2**. 2x2 is 2 • x2, and -16x is 2 • 8x:\n\n\\begin{equation}y - 2 = 2(x^{2} - 8x)\\end{equation}\n\nNow we're ready to complete the square, so we add the square of half of the -8x coefficient on the right side to the parenthesis. Half of -8 is -4, and -42 is 16, so the right side of the equation becomes *2(x2 - 8x + 16)*. Of course, we can't add something to one side of the equation without also adding it to the other side, and we've just added 2 • 16 (which is 32) to the right, so we must also add that to the left.\n\n\\begin{equation}y - 2 + 32 = 2(x^{2} - 8x + 16)\\end{equation}\n\nNow we can simplify the left and factor out a perfect square binomial expression on the right:\n\n\\begin{equation}y + 30 = 2(x - 4)^{2}\\end{equation}\n\nWe now have a squared term for ***x***, so we could use the square root method to solve the equation. However, we can also isolate ***y*** by subtracting 30 from both sides. So we end up restating the original equation as:\n\n\\begin{equation}y = 2(x - 4)^{2} - 30\\end{equation}\n\nLet's just quickly check our math with Python:\n\n\n```python\nfrom random import randint\nx = randint(1,100)\n\n2*x**2 - 16*x + 2 == 2*(x - 4)**2 - 30\n```\n\n\n\n\n True\n\n\n\nSo we've managed to take the expression ***2x2 - 16x + 2*** and change it to ***2(x - 4)2 - 30***. How does that help?\n\nWell, when a quadratic equation is stated this way, it's in *vertex form*, which is generically described as:\n\n\\begin{equation}y = a(x - h)^{2} + k\\end{equation}\n\nThe neat thing about this form of the equation is that it tells us the coordinates of the vertex - it's at ***h,k***.\n\nSo in this case, we know that the vertex of our equation is 4, -30. Moreover, we know that the line of symmetry is at ***x = 4***.\n\nWe can then just use the equation to calculate two more points, and the three points will be enough for us to determine the shape of the parabola. We can simply choose any ***x*** value we like and substitute it into the equation to calculate the corresponding ***y*** value. For example, let's calculate ***y*** when x is **0**:\n\n\\begin{equation}y = 2(0 - 4)^{2} - 30\\end{equation}\n\nWhen we work through the equation, it gives us the answer **2**, so we know that the point 0, 2 is in our parabola.\n\nSo, we know that the line of symmetry is at ***x = h*** (which is 4), and we now know that the ***y*** value when ***x*** is 0 (***h*** - ***h***) is 2. The ***y*** value at the same distance from the line of symmetry in the negative direction will be the same as the value in the positive direction, so when ***x*** is ***h*** + ***h***, the ***y*** value will also be 2.\n\nThe following Python code encapulates all of this in a function that draws and annotates a parabola using only the ***a***, ***h***, and ***k*** values from a quadratic equation in vertex form:\n\n\n```python\ndef plot_parabola_from_vertex_form(a, h, k):\n import pandas as pd\n import math\n\n # Create a dataframe with an x column a range of x values to plot\n df = pd.DataFrame ({'x': range(h-10, h+11)})\n\n # Add a y column by applying the quadratic equation to x\n df['y'] = (a*(df['x'] - h)**2) + k\n\n # get min and max y values\n miny = df.y.min()\n maxy = df.y.max()\n\n # calculate y when x is 0 (h+-h)\n y = a*(0 - h)**2 + k\n\n # Plot the line\n %matplotlib inline\n from matplotlib import pyplot as plt\n\n plt.plot(df.x, df.y, color=\"grey\")\n plt.xlabel('x')\n plt.ylabel('y')\n plt.grid()\n plt.axhline()\n plt.axvline()\n\n # Plot calculated y values for x = 0 (h-h and h+h)\n plt.scatter([h-h, h+h],[y,y], color=\"green\")\n plt.annotate(str(h-h) + ',' + str(y),(h-h, y))\n plt.annotate(str(h+h) + ',' + str(y),(h+h, y))\n\n # plot the line of symmetry (x = h)\n sx = [h, h]\n sy = [miny, maxy]\n plt.plot(sx,sy, color='magenta')\n\n # Annotate the vertex (h,k)\n plt.scatter(h,k, color=\"red\")\n plt.annotate('v=' + str(h) + ',' + str(k),(h, k), xytext=(h - 1, (k - 10)))\n\n plt.show()\n\n \n# Call the function for the example discussed above\nplot_parabola_from_vertex_form(2, 4, -30)\n```\n\nIt's important to note that the vertex form specifically requires a *subtraction* operation in the factored perfect square term. For example, consider the following equation in the standard form:\n\n\\begin{equation}y = 3x^{2} + 6x + 2\\end{equation}\n\nThe steps to solve this are:\n1. Move the constant to the left side:\n\\begin{equation}y - 2 = 3x^{2} + 6x\\end{equation}\n2. Factor the ***x*** expressions on the right:\n\\begin{equation}y - 2 = 3(x^{2} + 2x)\\end{equation}\n3. Add the square of half the x coefficient to the right, and the corresponding multiple on the left:\n\\begin{equation}y - 2 + 3 = 3(x^{2} + 2x + 1)\\end{equation}\n4. Factor out a perfect square binomial:\n\\begin{equation}y + 1 = 3(x + 1)^{2}\\end{equation}\n5. Move the constant back to the right side:\n\\begin{equation}y = 3(x + 1)^{2} - 1\\end{equation}\n\nTo express this in vertex form, we need to convert the addition in the parenthesis to a subtraction:\n\n\\begin{equation}y = 3(x - -1)^{2} - 1\\end{equation}\n\nNow, we can use the a, h, and k values to define a parabola:\n\n\n```python\nplot_parabola_from_vertex_form(3, -1, -1)\n```\n\n## Shortcuts for Solving Quadratic Equations\nWe've spent some time in this notebook discussing how to solve quadratic equations to determine the vertex of a parabola and the ***x*** values in relation to ***y***. It's important to understand the techniques we've used, which incude:\n- Factoring\n- Calculating the Square Root\n- Completing the Square\n- Using the vertex form of the equation\n\nThe underlying algebra for all of these techniques is the same, and this consistent algebra results in some shortcuts that you can memorize to make it easier to solve quadratic equations without going through all of the steps:\n\n### Calculating the Vertex from Standard Form\nYou've already seen that converting a quadratic equation to the vertex form makes it easy to identify the vertex coordinates, as they're encoded as ***h*** and ***k*** in the equation itself - like this:\n\n\\begin{equation}y = a(x - \\textbf{h})^{2} + \\textbf{k}\\end{equation}\n\nHowever, what if you have an equation in standard form?:\n\n\\begin{equation}y = ax^{2} + bx + c\\end{equation}\n\nThere's a quick and easy technique you can apply to get the vertex coordinates. \n\n1. To find ***h*** (which is the x-coordinate of the vertex), apply the following formula:\n\\begin{equation}h = \\frac{-b}{2a}\\end{equation}\n2. After you've found ***h***, use it in the quadratic equation to solve for ***k***:\n\\begin{equation}\\textbf{k} = a\\textbf{h}^{2} + b\\textbf{h} + c\\end{equation}\n\nFor example, here's the quadratic equation in standard form that we previously converted to the vertex form:\n\n\\begin{equation}y = 2x^{2} - 16x + 2\\end{equation}\n\nTo find ***h***, we perform the following calculation:\n\n\\begin{equation}h = \\frac{-b}{2a}\\;\\;\\;\\;=\\;\\;\\;\\;\\frac{-1 \\cdot16}{2\\cdot2}\\;\\;\\;\\;=\\;\\;\\;\\;\\frac{16}{4}\\;\\;\\;\\;=\\;\\;\\;\\;4\\end{equation}\n\nThen we simply plug the value we've obtained for ***h*** into the quadratic equation in order to find ***k***:\n\n\\begin{equation}k = 2\\cdot(4^{2}) - 16\\cdot4 + 2\\;\\;\\;\\;=\\;\\;\\;\\;32 - 64 + 2\\;\\;\\;\\;=\\;\\;\\;\\;-30\\end{equation}\n\nNote that a vertex at 4,-30 is also what we previously calculated for the vertex form of the same equation:\n\n\\begin{equation}y = 2(x - 4)^{2} - 30\\end{equation}\n\n### The Quadratic Formula\nAnother useful formula to remember is the *quadratic formula*, which makes it easy to calculate values for ***x*** when ***y*** is **0**; or in other words:\n\n\\begin{equation}ax^{2} + bx + c = 0\\end{equation}\n\nHere's the formula:\n\n\\begin{equation}x = \\frac{-b \\pm \\sqrt{b^{2} - 4ac}}{2a}\\end{equation}\n\nLet's apply that formula to our equation, which you may remember looks like this:\n\n\\begin{equation}y = 2x^{2} - 16x + 2\\end{equation}\n\nOK, let's plug the ***a***, ***b***, and ***c*** variables from our equation into the quadratic formula:\n\n\\begin{equation}x = \\frac{--16 \\pm \\sqrt{-16^{2} - 4\\cdot2\\cdot2}}{2\\cdot2}\\end{equation}\n\nThis simplifes to:\n\n\\begin{equation}x = \\frac{16 \\pm \\sqrt{256 - 16}}{4}\\end{equation}\n\nThis in turn (with the help of a calculator) simplifies to:\n\n\\begin{equation}x = \\frac{16 \\pm 15.491933384829668}{4}\\end{equation}\n\nSo our positive value for ***x*** is:\n\n\\begin{equation}x = \\frac{16 + 15.491933384829668}{4}\\;\\;\\;\\;=7.872983346207417\\end{equation}\n\nAnd the negative value for ***x*** is:\n\n\\begin{equation}x = \\frac{16 - 15.491933384829668}{4}\\;\\;\\;\\;=0.12701665379258298\\end{equation}\n\n\n\nThe following Python code uses the vertex formula and the quadtratic formula to calculate the vertex and the -x and +x for y = 0, and then plots the resulting parabola:\n\n\n```python\ndef plot_parabola_from_formula (a, b, c):\n import math\n\n # Get vertex\n print('CALCULATING THE VERTEX')\n print('vx = -b / 2a')\n\n nb = -b\n a2 = 2*a\n print('vx = ' + str(nb) + ' / ' + str(a2))\n\n vx = -b/(2*a)\n print('vx = ' + str(vx))\n\n print('\\nvy = ax^2 + bx + c')\n print('vy =' + str(a) + '(' + str(vx) + '^2) + ' + str(b) + '(' + str(vx) + ') + ' + str(c))\n\n avx2 = a*vx**2\n bvx = b*vx\n print('vy =' + str(avx2) + ' + ' + str(bvx) + ' + ' + str(c))\n\n vy = avx2 + bvx + c\n print('vy = ' + str(vy))\n\n print ('\\nv = ' + str(vx) + ',' + str(vy))\n\n # Get +x and -x (showing intermediate calculations)\n print('\\nCALCULATING -x AND +x FOR y=0')\n print('x = -b +- sqrt(b^2 - 4ac) / 2a')\n\n\n b2 = b**2\n ac4 = 4*a*c\n print('x = ' + str(nb) + '+-sqrt(' + str(b2) + ' - ' + str(ac4) + ')/' + str(a2))\n\n sr = math.sqrt(b2 - ac4)\n print('x = ' + str(nb) + ' +- ' + str(sr) + ' / ' + str(a2))\n print('-x = ' + str(nb) + ' - ' + str(sr) + ' / ' + str(a2))\n print('+x = ' + str(nb) + ' + ' + str(sr) + ' / ' + str(a2))\n\n posx = (nb + sr) / a2\n negx = (nb - sr) / a2\n print('-x = ' + str(negx))\n print('+x = ' + str(posx))\n\n\n print('\\nPLOTTING THE PARABOLA')\n import pandas as pd\n\n # Create a dataframe with an x column a range of x values to plot\n df = pd.DataFrame ({'x': range(round(vx)-10, round(vx)+11)})\n\n # Add a y column by applying the quadratic equation to x\n df['y'] = a*df['x']**2 + b*df['x'] + c\n\n # get min and max y values\n miny = df.y.min()\n maxy = df.y.max()\n\n # Plot the line\n %matplotlib inline\n from matplotlib import pyplot as plt\n\n plt.plot(df.x, df.y, color=\"grey\")\n plt.xlabel('x')\n plt.ylabel('y')\n plt.grid()\n plt.axhline()\n plt.axvline()\n\n # Plot calculated x values for y = 0\n plt.scatter([negx, posx],[0,0], color=\"green\")\n plt.annotate('-x=' + str(negx) + ',' + str(0),(negx, 0), xytext=(negx - 3, 5))\n plt.annotate('+x=' + str(posx) + ',' + str(0),(posx, 0), xytext=(posx - 3, -10))\n\n # plot the line of symmetry\n sx = [vx, vx]\n sy = [miny, maxy]\n plt.plot(sx,sy, color='magenta')\n\n # Annotate the vertex\n plt.scatter(vx,vy, color=\"red\")\n plt.annotate('v=' + str(vx) + ',' + str(vy),(vx, vy), xytext=(vx - 1, vy - 10))\n\n plt.show()\n \n\nplot_parabola_from_formula (2, -16, 2)\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "dc5621f23c28153b93192305f3e19781fcc36bf2", "size": 214773, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Basics Of Algebra by Hiren/01-07-Quadratic Equations.ipynb", "max_stars_repo_name": "serkin/Basic-Mathematics-for-Machine-Learning", "max_stars_repo_head_hexsha": "ac0ae9fad82a9f0429c93e3da744af6e6d63e5ab", "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": "Basics Of Algebra by Hiren/01-07-Quadratic Equations.ipynb", "max_issues_repo_name": "serkin/Basic-Mathematics-for-Machine-Learning", "max_issues_repo_head_hexsha": "ac0ae9fad82a9f0429c93e3da744af6e6d63e5ab", "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": "Basics Of Algebra by Hiren/01-07-Quadratic Equations.ipynb", "max_forks_repo_name": "serkin/Basic-Mathematics-for-Machine-Learning", "max_forks_repo_head_hexsha": "ac0ae9fad82a9f0429c93e3da744af6e6d63e5ab", "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": 212.4362017804, "max_line_length": 24240, "alphanum_fraction": 0.8907404562, "converted": true, "num_tokens": 8095, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465152482724, "lm_q2_score": 0.9362850070814366, "lm_q1q2_score": 0.8757509186528257}} {"text": "---\nauthor: Nathan Carter (ncarter@bentley.edu)\n---\n\nThis answer assumes you have imported SymPy as follows.\n\n\n```python\nfrom sympy import * # load all math functions\ninit_printing( use_latex='mathjax' ) # use pretty math output\n```\n\nIf your equation has just one variable, simply call `solve` on it.\nNote that you may get a list of more than one solution.\n\n\n```python\nvar( 'x' )\nequation = Eq( x**2 + 3*x, -x + 9 )\nsolve( equation )\n```\n\n\n\n\n$\\displaystyle \\left[ -2 + \\sqrt{13}, \\ - \\sqrt{13} - 2\\right]$\n\n\n\nSometimes you get no solutions, which is shown as a Python empty list.\n\n\n```python\nsolve( Eq( x+1, x+2 ) )\n```\n\n\n\n\n$\\displaystyle \\left[ \\right]$\n\n\n\nSometimes the answers include complex numbers.\n\n\n```python\nsolve( Eq( x**3, -1 ) )\n```\n\n\n\n\n$\\displaystyle \\left[ -1, \\ \\frac{1}{2} - \\frac{\\sqrt{3} i}{2}, \\ \\frac{1}{2} + \\frac{\\sqrt{3} i}{2}\\right]$\n\n\n\nTo restrict the solution to the real numbers, use `solveset` instead,\nand specify the real numbers as the domain.\n\n\n```python\nsolveset( Eq( x**3, -1 ), domain=S.Reals )\n```\n\n\n\n\n$\\displaystyle \\left\\{-1\\right\\}$\n\n\n\nYou can solve systems of equations by calling `solve` on them.\n\n\n```python\nvar( 'x y' )\nsystem = [\n Eq( x + 2*y, 1 ),\n Eq( x - 9*y, 5 )\n]\nsolve( system )\n```\n\n\n\n\n$\\displaystyle \\left\\{ x : \\frac{19}{11}, \\ y : - \\frac{4}{11}\\right\\}$\n\n\n", "meta": {"hexsha": "8d92093649ff00ff34fd291cf5e3a5ab984970da", "size": 4264, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "database/tasks/How to solve symbolic equations/Python, using SymPy.ipynb", "max_stars_repo_name": "nathancarter/how2data", "max_stars_repo_head_hexsha": "7d4f2838661f7ce98deb1b8081470cec5671b03a", "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": "database/tasks/How to solve symbolic equations/Python, using SymPy.ipynb", "max_issues_repo_name": "nathancarter/how2data", "max_issues_repo_head_hexsha": "7d4f2838661f7ce98deb1b8081470cec5671b03a", "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": "database/tasks/How to solve symbolic equations/Python, using SymPy.ipynb", "max_forks_repo_name": "nathancarter/how2data", "max_forks_repo_head_hexsha": "7d4f2838661f7ce98deb1b8081470cec5671b03a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-07-18T19:01:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T06:47:11.000Z", "avg_line_length": 21.4271356784, "max_line_length": 143, "alphanum_fraction": 0.4683395872, "converted": true, "num_tokens": 427, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9609517050371972, "lm_q2_score": 0.9111797033789887, "lm_q1q2_score": 0.8755996895573267}} {"text": "# Binray Heap\n\n## Properties:\n1. must be complemet binary tree: assume node at index i, then the index for parent node is arr[(i-1) / 2], left child is arr[2i + 1], right child is arr[2i + 2] \n2. the key of any node is no smaller than the key of its children(max heap) \n\n\n## build heap\nHeapify procedure can be applied to a node only if its children nodes are heapified. So the heapification must be performed in the bottom up order.\n\n## running time\nTo analyze the running time, consider what happens when we’re looking at a node x that’s\nin level h (where we say that the bottom level is level 0, so the level is the height). We might have to sink x all the way to the bottom, which takes time h. But there are at most ceil(n/2^(h+1)) nodes at level h. So the total cost is only\n\\begin{equation}\n\\sum_{h=0}^{log\\,n} h\\cdot n/2^{h+1} \\,\\,\\leq\\,\\, \\sum_{h=0}^{log\\,n} n\\cdot h/2^{h+1} \\,\\,\\leq\\,\\, O(n)\n\\end{equation}\n\n\n```python\narr = [12, 3, 45, 66, 7, 8, 9, 11, 13]\ndef heapify(arr, n, i):\n largest = i\n l = 2 * i + 1\n r = 2 * i + 2\n if l < n and arr[largest] < arr[l]:\n largest = l\n if r < n and arr[largest] < arr[r]:\n largest = r\n if largest != i:\n arr[largest], arr[i] = arr[i], arr[largest]\n heapify(arr, n, largest)\n \ndef build(arr):\n n = len(arr)\n for i in range(n, -1, -1):\n heapify(arr, n, i)\n\nbuild(arr)\narr\n```\n\n\n\n\n [66, 13, 45, 12, 7, 8, 9, 11, 3]\n\n\n\n## heap sort\nAfter building a max heap, extract the elements one by one.\n## running time\nTime complexity for heapify is O(logn), since there are n loops, the total running time is O(nlogn)\n\n\n```python\ndef heap_sort(arr):\n n = len(arr)\n for i in range(n - 1, -1, -1): \n arr[i], arr[0] = arr[0], arr[i] \n heapify(arr, i, 0)\nheap_sort(arr)\narr\n```\n\n\n\n\n [3, 7, 8, 9, 11, 12, 13, 45, 66]\n\n\n\n## deletion, insertion, decrease key is similar to the operations shown above\nfor deletion, we can swap x with the last node, remove x, and then\nrestore heap order by sinking down. This takes O(log n) time. \n\nfor insertion, we begin by inserting x into the next open spot, then we have it swim up until we restore the heap order. This takes O(log n) time. \n\nfor decrease key, we can just decrease the key of x, and have it swim up until we\nrestore heap order. This takes O(log n) time.\n\n\n```python\n\n```\n", "meta": {"hexsha": "2677524e56d53ac13258e34d04c9fb49910a061f", "size": 4235, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "working related/binary_heap.ipynb", "max_stars_repo_name": "xinyaoliu/xinyaoliu.github.io", "max_stars_repo_head_hexsha": "e8ea104231ff8be55ca577b00d1e73fbb7ef0c66", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2019-02-05T22:58:30.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-05T23:10:08.000Z", "max_issues_repo_path": "working related/binary_heap.ipynb", "max_issues_repo_name": "xinyaoliu/xinyaoliu.github.io", "max_issues_repo_head_hexsha": "e8ea104231ff8be55ca577b00d1e73fbb7ef0c66", "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": "working related/binary_heap.ipynb", "max_forks_repo_name": "xinyaoliu/xinyaoliu.github.io", "max_forks_repo_head_hexsha": "e8ea104231ff8be55ca577b00d1e73fbb7ef0c66", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-02-05T22:58:18.000Z", "max_forks_repo_forks_event_max_datetime": "2019-02-05T22:58:18.000Z", "avg_line_length": 27.6797385621, "max_line_length": 249, "alphanum_fraction": 0.518772137, "converted": true, "num_tokens": 757, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768620069626, "lm_q2_score": 0.9273632996617212, "lm_q1q2_score": 0.8755949702150264}} {"text": "# Finite difference method\n\n\n## Finite differences\n\nAnother method of solving boundary-value problems (and also partial differential equations, as we'll see later) involves **finite differences**, which are numerical approximations to exact derivatives.\n\nRecall that the exact derivative of a function $f(x)$ at some point $x$ is defined as:\n\\begin{equation}\nf^{\\prime}(x) = \\frac{df}{dx}(x) = \\lim_{\\Delta x \\rightarrow 0} \\frac{f(x+\\Delta x) - f(x)}{\\Delta x}\n\\end{equation}\n\nSo, we can *approximate* this derivative using a finite difference (rather than an infinitesimal difference as in the exact derivative):\n\\begin{equation}\nf^{\\prime}(x) \\approx \\frac{f(x+\\Delta x) - f(x)}{\\Delta x}\n\\end{equation}\nwhich involves some error. This is a **forward difference** for approximating the first derivative.\nWe can also approximate the first derivative using a **backward difference**:\n\\begin{equation}\nf^{\\prime}(x) \\approx \\frac{f(x) - f(x - \\Delta x)}{\\Delta x}\n\\end{equation}\n\nTo understand the error involved in these differences, we can use Taylor's theorem to obtain Taylor series expansions:\n\\begin{align}\nf(x + \\Delta x) &= f(x) + \\Delta x \\, f^{\\prime}(x) + \\Delta x^2 \\frac{1}{2!} f^{\\prime\\prime}(x) + \\cdots \\\\\n\\rightarrow \\frac{f(x + \\Delta x) - f(x)}{\\Delta x} &= f^{\\prime}(x) + \\mathcal{O}\\left( \\Delta x \\right) \\\\\nf(x - \\Delta x) &= f(x) - \\Delta x \\, f^{\\prime}(x) + \\Delta x^2 \\frac{1}{2!} f^{\\prime\\prime}(x) + \\cdots \\\\\n\\rightarrow \\frac{f(x) - f(x - \\Delta x)}{\\Delta x} &= f^{\\prime}(x) + \\mathcal{O}\\left( \\Delta x \\right) \\\\\n\\end{align}\nwhere the $\\mathcal{O}()$ notation stands for \"order of magnitude of\". So, we can see that each of these approximations is *first-order accurate*.\n\n## Second-order finite differences\n\nWe can obtain higher-order approximations for the first derivative, and an approximations for the second derivative, by combining these Taylor series expansions:\n\\begin{align}\nf(x + \\Delta x) &= f(x) + \\Delta x \\, f^{\\prime}(x) + \\Delta x^2 \\frac{1}{2!} f^{\\prime\\prime}(x) + \\mathcal{O}\\left( \\Delta x^3 \\right) \\\\\nf(x - \\Delta x) &= f(x) - \\Delta x \\, f^{\\prime}(x) + \\Delta x^2 \\frac{1}{2!} f^{\\prime\\prime}(x) + \\mathcal{O}\\left( \\Delta x^3 \\right)\n\\end{align}\n\nSubtracting the Taylor series for $f(x+\\Delta x)$ by that for $f(x-\\Delta x)$ gives:\n\\begin{align}\nf(x + \\Delta x) - f(x - \\Delta x) &= 2 \\Delta x \\, f^{\\prime}(x) + \\mathcal{O}\\left( \\Delta x^3 \\right) \\\\\nf^{\\prime}(x) &= \\frac{f(x + \\Delta x) - f(x - \\Delta x)}{2 \\Delta x} + \\mathcal{O}\\left( \\Delta x^2 \\right)\n\\end{align}\nwhich is a *second-order accurate* approximation for the first derivative.\n\nAdding the Taylor series for $f(x+\\Delta x)$ to that for $f(x-\\Delta x)$ gives:\n\\begin{align}\nf(x + \\Delta x) + f(x - \\Delta x) &= 2 f(x) + \\Delta x^2 f^{\\prime\\prime}(x) + \\mathcal{O}\\left( \\Delta x^3 \\right) \\\\\nf^{\\prime\\prime}(x) &= \\frac{f(x + \\Delta x) - 2 f(x) + f(x - \\Delta x)}{\\Delta x^2} + \\mathcal{O}\\left( \\Delta x^2 \\right)\n\\end{align}\nwhich is a *second-order accurate* approximation for the second derivative.\n\n## Solving ODEs with finite differences\n\nWe can use finite differences to solve ODEs by substituting them for exact derivatives, and then applying the equation at discrete locations in the domain. This gives us a system of simultaneous equations to solve.\n\nFor example, let's consider the ODE\n\\begin{equation}\ny^{\\prime\\prime} + x y^{\\prime} - x y = 2 x \\;,\n\\end{equation}\nwith the boundary conditions $y(0) = 1$ and $y(2) = 8$.\n\nFirst, we *discretize* the continuous domain: divide it into a number of discrete segments. For now, let's choose $\\Delta x = 0.5$, which creates four segments and thus five points: $x_1 = 0, x_2 = 0.5, x_3 = 1.0, x_4 = 1.5, x_5 = 2.0$. \n\nOur goal is then to find approximate values of $y(x)$ at these points: $y_1$ through $y_5$. So, we have five unknowns, and need five equations to solve for them. We can use the ODE to provide these equations, by replacing the derivatives with finite differences, and applying the equation at particular discrete locations.\n\nRecall that $y(x)$ is a function just like $f(x)$, and so we can apply the above finite difference equations to $y(x)$ and $y(x+\\Delta x)$. Now that we have points, or nodes, at locations separated by $\\Delta x$, we can consider a point $x_i$ where $y(x_i) = y_i$, $y(x_i + \\Delta x) = y(x_{i+1}) = y_{i+1}$, and $y(x_i - \\Delta x) = y(x_{i-1}) = y_{i-1}$.\n\nTo do this, we'll follow a few steps:\n\n1.) Replace exact derivatives in the original ODE with finite differences, and apply the equation at a particular location $(x_i, y_i)$.\n\nFor our example, this gives:\n\\begin{equation}\n\\frac{y_{i+1} - 2y_i + y_{i-1}}{\\Delta x^2} + x_i \\left( \\frac{y_{i+1} - y_{i-1}}{2 \\Delta x}\\right) - x_i y_i = 2 x_i\n\\end{equation}\nwhich applies at location $(x_i, y_i)$.\n\n2.) Next, rearrange the equation into a *recursion formula*:\n\\begin{equation}\ny_{i-1} \\left(1 - x_i \\frac{\\Delta x}{2}\\right) + y_i \\left( -2 -\\Delta x^2 x_i \\right) + y_{i+1} \\left(1 + x_i \\frac{\\Delta x}{2}\\right) = 2 x_i \\Delta x^2\n\\end{equation}\nWe can use this equation to get an equation for each of the interior points in the domain.\n\nFor the first and last points—the boundary points—we already have equations, given by the boundary conditions.\n\n3.) Set up system of linear equations\n\nApplying the recursion formula to the interior points, and the boundary conditions for the boundary points, we can get a system of simultaneous linear equations:\n\\begin{align}\ny_1 &= 1 \\\\\ny_1 (0.875) + y_2 (-2.125) + y_3 (1.125) &= 0.25 \\\\\ny_2 (0.75) + y_3 (-2.25) + y_4 (1.25) &= 0.5 \\\\\ny_3 (0.625) + y_4 (-2.375) + y_5 (1.375) &= 0.75 \\\\\ny_5 &= 8\n\\end{align}\n\nThis is a system of five equations and five unknowns, which we can solve! But, solving using substitution would be painful, so let's represent this system of equations using a matrix and vectors:\n\\begin{equation}\n\\begin{bmatrix}\n1 & 0 & 0 & 0 & 0 \\\\\n0.875 & -2.125 & 1.125 & 0 & 0 \\\\\n0 & 0.75 & -2.25 & 1.25 & 0 \\\\\n0 & 0 & 0.625 & -2.375 & 1.375 \\\\\n0 & 0 & 0 & 0 & 1\n\\end{bmatrix} \n\\begin{bmatrix} y_1 \\\\ y_2 \\\\ y_3 \\\\ y_4 \\\\ y_5 \\end{bmatrix} = \n\\begin{bmatrix} 1 \\\\ 0.25 \\\\ 0.5 \\\\ 0.75 \\\\ 8 \\end{bmatrix}\n\\end{equation}\nor, more compactly, $A \\mathbf{y} = \\mathbf{b}$.\n\n4.) Solve the linear system of equations\n\nThe final step is just to solve. We can do this in Matlab with `y = A \\ b`. (This is equivalent to `y = inv(A)*b`, but faster.)\n\n\n```matlab\nA = [1.0 0 0 0 0;\n 0.875 -2.125 1.125 0 0;\n 0 0.75 -2.25 1.25 0;\n 0 0 0.625 -2.375 1.375;\n 0 0 0 0 1];\n\nb = [1.0; 0.25; 0.5; 0.75; 8.0];\n\nx = [0 : 0.5 : 2];\ny = A \\ b;\nplot(x, y, 'o-');\n```\n\n### Matlab implementation\n\nOf course, all of this will be easier if we implement in Matlab in a general way. We'll use a `for` loop to populate the coefficient matrix $A$ and right-hand-side vector $\\mathbf{b}$:\n\n\n```matlab\nclear all; clc\n\ndx = 0.5;\nx = [0 : dx : 2];\nn = length(x);\nA = zeros(n,n); b = zeros(n,1);\n\nfor i = 1 : n\n if i == 1\n A(1,1) = 1;\n b(1) = 1;\n elseif i == n\n A(n,n) = 1;\n b(n) = 8;\n else\n A(i, i-1) = 1 - x(i)*dx/2;\n A(i, i) = -2 - x(i)*dx^2;\n A(i, i+1) = 1 + x(i)*dx/2;\n b(i) = 2*x(i)*dx^2;\n end\nend\ny = A \\ b;\nplot(x, y, 'o-')\n```\n\nThis looks good, but we can get a more-accurate solution by reducing our step size $\\Delta x$:\n\n\n```matlab\nclear all; clc\n\ndx = 0.001;\nx = [0 : dx : 2];\nn = length(x);\nA = zeros(n,n); b = zeros(n,1);\n\nfor i = 1 : n\n if i == 1\n A(1,1) = 1;\n b(1) = 1;\n elseif i == n\n A(n,n) = 1;\n b(n) = 8;\n else\n A(i, i-1) = 1 - x(i)*dx/2;\n A(i, i) = -2 - x(i)*dx^2;\n A(i, i+1) = 1 + x(i)*dx/2;\n b(i) = 2*x(i)*dx^2;\n end\nend\ny = A \\ b;\nplot(x, y)\n```\n\n## Boundary conditions\n\nWe will encounter four main kinds of boundary conditions. Consider the ODE $y^{\\prime\\prime} + y = 0$, on the domain $0 \\leq x \\leq L$.\n\n- First type, or Dirichlet, boundary conditions specify fixed values of $y$ at the boundaries: $y(0) = a$ and $y(L) = b$.\n- Second type, or Neumann, boundary conditions specify values of the derivative at the boundaries: $y^{\\prime}(0) = a$ and $y^{\\prime}(L) = b$.\n- Third type, or Robin, boundary conditions specify a linear combination of the function value and its derivative at the boundaries: $a \\, y(0) + b \\, y^{\\prime}(0) = g(0)$ and $a \\, y(L) + b \\, y^{\\prime}(L) = g(L)$, where $g(x)$ is some function.\n- Mixed boundary conditions, which combine any of these three at the different boundaries. For example, we could have $y(0) = a$ and $y^{\\prime}(L) = b$.\n\nWhichever type of boundary condition we are dealing with, the goal will be to construct an equation representing the boundary condition to incorporate in our system of equations.\n\nIf we have a fixed value boundary condition, such as $y(0) = a$, then this equation is straightforward:\n\\begin{equation}\ny_1 = a\n\\end{equation}\nwhere $y_1$ is the first point in the grid of points, corresponding to $x_1 = 0$. (We saw this in the example above.) In Matlab, we can implement this equation with\n```OCTAVE\nA(1,1) = 1;\nb(1) = a;\n```\n\nIf we have a fixed derivative boundary condition, such as $y^{\\prime}(0) = 0$, then we need to use a finite difference to represent the derivative. When the boundary condition is at the starting location, $x=0$, the easiest way to do this is with a **forward difference**:\n\\begin{align}\ny^{\\prime}(0) \\approx \\frac{y_2 - y_1}{\\Delta x} &= 0 \\\\\n-y_1 + y_2 &= 0\n\\end{align}\nWe can implement this in Matlab with\n```OCTAVE\nA(1,1) = -1;\nA(1,2) = 1;\nb(1) = 0;\n```\n\nWhen we have this sort of derivative boundary condition at the right side of the domain, at $x=L$, then we can use a **backward difference** to represent the derivative:\n\\begin{align}\ny^{\\prime}(L) \\approx \\frac{y_n - y_{n_1}}{\\Delta x} &= 0 \\\\\n-y_{n-1} + y_n &= 0\n\\end{align}\nwhere $y_n$ is the final point ($x_n = L$) and $y_{n-1}$ is the second-to-last point ($x_{n-1} = L - \\Delta x$). We can implement this in Matlab with\n```OCTAVE\nA(n,n-1) = -1;\nA(n,n) = 1;\nb(n) = 0;\n```\n\nIf we have a linear combination of a fixed value and fixed derivative, like $a \\, y(0) + b \\, y^{\\prime}(0) = c$, then we can combine the above approaches using a forward difference:\n\\begin{align}\na y(0) + b y^{\\prime}(0) \\approx a y_1 + b \\frac{y_2 - y_1}{\\Delta x} &= c \\\\\n(a \\Delta x - b) y_1 + b y_2 &= c \\Delta x\n\\end{align}\nand in Matlab:\n```OCTAVE\nA(1,1) = a*dx - b;\nA(1,2) = b;\nb(1) = c * dx;\n```\n\n### Using central differences for derivative BCs\n\nWhen a boundary condition involves a derivative, we can use a *central difference* to approximate the first derivative; this is more accurate than a forward or backward difference.\n\nConsider the formula for a central difference at $x=0$, applied for the boundary condition $y^{\\prime}(0) = 0$:\n\\begin{align}\ny^{\\prime}(0) \\approx \\frac{y_2 - y_0}{2 \\Delta x} &= 0 \\\\\ny_0 &= y_2\n\\end{align}\nwhere $y_0$ is an imaginary, or ghost, node *outside* the domain. We can't actually keep this point in our implementation, because it isn't a real point.\n\nWe still need an equation *for* the point at the boundary, $y_1$. To get this, we'll apply the regular recursion formula, normally used at interior points:\n\\begin{align}\na y_{i-1} + b y_i + c y_{i+1} = f(x_i) \\\\\na y_0 + b y_1 + c y_2 = f(x_1) \\;,\n\\end{align}\nwhere $a$, $b$, $c$, and $f(x)$ depend on the problem. Normally we wouldn't use this at the boundary node, $y_1$, because it references a point outside the domain to the left—but we have an equation for that! From above, based on the boundary condition, we have $y_0 = y_2$. If we incorporate that into the recursion formula, we can eliminate the ghost node $y_0$:\n\\begin{align}\na y_2 + b y_1 + c y_2 &= f(x_1) \\\\\nb y_1 + (a + c) y_2 &= f(x_1) \\,\n\\end{align}\nwhich is the equation we can actually use at the boundary point.\nIn Matlab, this looks like \n```OCTAVE\nA(1,1) = b;\nA(1,2) = a + c;\nb(1) = f(x(1));\n```\n\n## Example: nonlinear BVP\n\nSo far we've seen how to handle a linear boundary value problem, but what if we have a **nonlinear** BVP? This is going to be trickier, because our work so far relies on using linear algebra to solve the system of (linear) equations.\n\nFor example, consider the 2nd-order ODE\n\\begin{equation}\ny^{\\prime\\prime} = 3y + x^2 + 100 y^2\n\\end{equation}\nwith the boundary conditions $y(0) = y(1) = 0$. This is nonlinear, due to the $y^3$ term on the right-hand side.\n\nTo solve this, let's first convert it into a discrete form, by replacing the second derivative with a finite difference and any $x$/$y$ present with $x_i$ and $y_i$. We'll also move any constants (i.e., terms that don't contain $y_i$) and the nonlinear term to the right-hand side:\n\\begin{equation}\n\\frac{y_{i-1} - 2y_i + y_{i+1}}{\\Delta x^2} - 3y_i = x_i^2 + 100 y_i^2\n\\end{equation}\nwhere the boundary conditions are now $y_1 = 0$ and $y_n = 0$, with $n$ as the number of grid points. We can rearrange and simplify into our recursion formula:\n\\begin{equation}\ny_{i-1} + y_i \\left( -2 - 3 \\Delta x^2 \\right) + y_{i+1} = x_i^2 \\Delta x^2 + 100 \\Delta x^2 y_i^2\n\\end{equation}\n\nThe question is: how do we solve this now? The nonlinear term involving $y_i^3$ on the right-hand side complicates things, but we know how to set up and solve this *without* the nonlinear term. We can use an approach known as **successive iteration**:\n\n1. Solve the ODE without the nonlinear term to get an initial \"guess\" to the solution for $y$.\n2. Then, incorporate that guess solution in the nonlinear term on the right-hand side, treating it as a constant. We can call this $y_{\\text{old}}$. Then, solve the full system for a new $y$ solution.\n3. Check whether the new $y$ matches $y_{\\text{old}}$ with some tolerance. For example, check whether $\\max\\left(\\left| y - y_{\\text{old}} \\right| \\right) < $ some tolerance, such as $10^{-6}$. If this is true, then we can consider the solution *converged*. If it is not true, then set $y_{\\text{old}} = y$, and repeat the process starting at step 2.\n\nLet's implement that process in Matlab:\n\n\n```matlab\n%% Initial setup\nclear all; clc\n\ndx = 0.01;\nx = 0 : dx : 1;\nn = length(x);\n\nA = zeros(n, n);\nb = zeros(n, 1);\n\n%% First, solve the problem without the nonlinear term:\nfor i = 1 : n\n if i == 1 % x = 0 boundary condition\n A(1,1) = 1;\n b(1) = 0;\n elseif i == n % x = L boundary condition\n A(n,n) = 1;\n b(n) = 0;\n else % interior nodes, use recursion formula\n A(i, i-1) = 1;\n A(i, i) = -2 - 3*dx^2;\n A(i, i+1) = 1;\n b(i) = x(i)^2 * dx^2;\n end\nend\n% get solution without nonlinear term\ny = A \\ b;\n\nplot(x, y, '--'); hold on\n\n%% Now, set up iterative process to solve while incorporating nonlinear terms\niter = 1;\ny_old = zeros(n, 1);\nwhile max(abs(y - y_old)) > 1e-6\n y_old = y;\n % A matrix is not changed, but the b vector does\n for i = 2 : n - 1\n b(i) = x(i)^2 * dx^2 + 100*(dx^2)*(y_old(i)^2);\n end\n \n y = A \\ b;\n iter = iter + 1;\nend\n\nfprintf('Number of iterations: %d\\n', iter);\nplot(x, y)\nlegend('Initial solution', 'Final solution')\n```\n\nAnother option is just to set our \"guess\" for the $y$ solution to be zero, rather than solve the problem in two steps:\n\n\n```matlab\n%% Initial setup\nclear all; clc\n\ndx = 0.01;\nx = 0 : dx : 1;\nn = length(x);\n\nA = zeros(n, n);\nb = zeros(n, 1);\n\n%% Set up the coefficient matrix, which does not change\nfor i = 1 : n\n if i == 1 % x = 0 boundary condition\n A(1,1) = 1;\n b(1) = 0;\n elseif i == n % x = L boundary condition\n A(n,n) = 1;\n b(n) = 0;\n else % interior nodes, use recursion formula\n A(i, i-1) = 1;\n A(i, i) = -2 - 3*dx^2;\n A(i, i+1) = 1;\n b(i) = x(i)^2 * dx^2;\n end\nend\n\n% just use zeros as our initial guess for the solution\ny = zeros(n, 1);\n\n%% Successive iteration\niter = 1;\ny_old = 100 * rand(n, 1); % setting this to some random values, just to enter the while loop\nwhile max(abs(y - y_old)) > 1e-6\n y_old = y;\n % A matrix is not changed, but the b vector does\n for i = 2 : n - 1\n b(i) = x(i)^2 * dx^2 + 100*(dx^2)*(y_old(i)^2);\n end\n \n y = A \\ b;\n iter = iter + 1;\nend\n\nfprintf('Number of iterations: %d\\n', iter);\n```\n\n Number of iterations: 17\n\n\nThis made our process take slightly more iterations, because the initial guess was slightly further away from the final solution. For other problems, having a bad initial guess could make the process take much longer, so coming up with a good initial guess may be important.\n\n## Example: heat transfer through a fin\n\nLet's now consider a more complicated example: heat transfer through an extended surface (a fin).\n\n:::{figure-md} fig-fin\n\n\nGeometry of a heat transfer fin\n:::\n\nIn this situation, we have the temperature of the body $T_b$, the temperature of the ambient fluid $T_{\\infty}$; the length $L$, width $w$, and thickness $t$ of the fin; the thermal conductivity of the fin material $k$; and convection heat transfer coefficient $h$.\n\nThe boundary conditions can be defined in different ways, but generally we can say that the temperature of the fin at the wall is the same as the body temperature, and that the fin is insulated at the tip. This gives us\n\\begin{align}\nT(x=0) &= T_b \\\\\nq(x=L) = 0 \\rightarrow \\frac{dT}{dx} (x=0) &= 0\n\\end{align}\n\nOur goal is to solve for the temperature distribution $T(x)$. To do this, we need to set up a governing differential equation. Let's do a control volume analysis of heat transfer through the fin:\n\n:::{figure-md} fig-control-volume\n\n\nControl volume for heat transfer through the fin\n:::\n\nGiven a particular volumetric slice of the fin, we can define the heat transfer rates of conduction through the fin and convection from the fin to the air:\n\\begin{align}\nq_{\\text{conv}} &= h P \\left( T - T_{\\infty} \\right) dx \\\\\nq_{\\text{cond}, x} &= -k A_c \\left(\\frac{dT}{dx}\\right)_{x} \\\\\nq_{\\text{cond}, x+\\Delta x} &= -k A_c \\left(\\frac{dT}{dx}\\right)_{x+\\Delta x} \\;,\n\\end{align}\nwhere $P$ is the perimeter (so that $P \\, dx$ is the heat transfer area to the fluid) and $A_c$ is the cross-sectional area.\n\nPerforming a balance through the control volume:\n\\begin{align}\nq_{\\text{cond}, x+\\Delta x} &= q_{\\text{cond}, x} - q_{\\text{conv}} \\\\\n-k A_c \\left(\\frac{dT}{dx}\\right)_{x+\\Delta x} &= -k A_c \\left(\\frac{dT}{dx}\\right)_{x} - h P \\left( T - T_{\\infty} \\right) dx \\\\\n-k A_c \\frac{\\left.\\frac{dT}{dx}\\right|_{x+\\Delta x} - \\left.\\frac{dT}{dx}\\right|_{x}}{dx} &= -h P ( T - T_{\\infty} ) \\\\\n\\lim_{\\Delta x \\rightarrow 0} : -k A_c \\left. \\frac{d^2 T}{dx^2} \\right|_x &= -h P (T - T_{\\infty}) \\\\\n\\frac{d^2 T}{dx^2} &= \\frac{h P}{k A_c} (T - T_{\\infty}) \\\\\n\\frac{d^2 T}{dx^2} &= m^2 (T - T_{\\infty})\n\\end{align}\nthen we have as a governing equation\n\\begin{equation}\n\\frac{d^2 T}{dx^2} - m^2 (T - T_{\\infty}) = 0 \\;,\n\\end{equation}\nwhere $m^2 = (h P)/(k A_c)$.\n\nWe can obtain an exact solution for this ODE. For convenience, let's define a new variable, $\\theta$, which is a normalized temperature:\n\\begin{equation}\n\\theta \\equiv T - T_{\\infty}\n\\end{equation}\nwhere $\\theta^{\\prime} = T^{\\prime}$ and $\\theta^{\\prime\\prime} = T^{\\prime\\prime}$.\nThis gives us a new governing equation:\n\\begin{equation}\n\\theta^{\\prime\\prime} - m^2 \\theta = 0 \\;.\n\\end{equation}\nThis is a 2nd-order homogeneous ODE, which looks a lot like $y^{\\prime\\prime} + a y = 0$. The exact solution is then\n\\begin{align}\n\\theta(x) &= c_1 e^{-m x} + c_2 e^{m x} \\\\\nT(x) &= T_{\\infty} + c_1 e^{-m x} + c_2 e^{m x}\n\\end{align}\nWe'll use this to look at the accuracy of a numerical solution, but we will not be able to find an exact solution for more complicated versions of this problem.\n\nWe can also solve this numerically using the finite difference method. Let's replace the derivative with a finite difference:\n\\begin{align}\n\\frac{d^2 T}{dx^2} - m^2 (T - T_{\\infty}) &= 0 \\\\\n\\frac{T_{i-1} - 2T_i + T_{i+1}}{\\Delta x^2} - m^2 \\left( T_i - T_{\\infty} \\right) &= 0\n\\end{align}\nwhich we can rearrange into a recursion formula:\n\\begin{equation}\nT_{i-1} + T_i \\left( -2 - \\Delta x^2 m^2 \\right) + T_{i+1} = -m^2 \\Delta x^2 \\, T_{\\infty}\n\\end{equation}\nThis gives us an equation for all the interior nodes; we can use the above boundary conditions to get equations for the boundary nodes. For the boundary condition at $x=L$, $T^{\\prime}(x=L) = 0$, let's use a *backward difference*:\n\\begin{align}\nT_1 &= T_b \\\\\n\\frac{T_n - T_{n-1}}{\\Delta x} = 0 \\rightarrow - T_{n-1} + T_n &= 0\n\\end{align}\n\nCombining all these equations, we can construct a linear system: $A \\mathbf{T} = \\mathbf{b}$.\n\n### Heat transfer with radiation\n\nLet's now consider a more-complicated case, where we also have radiation heat transfer occuring along the length of the fin. Now, our governing ODE is\n\\begin{equation}\n\\frac{d^2 T}{dx^2} - \\frac{h P}{k A_c} \\left(T - T_{\\infty}\\right) - \\frac{\\sigma \\epsilon P}{h A_c} \\left(T^4 - T_{\\infty}^4 \\right) = 0\n\\end{equation}\n\nThis is a bit trickier to solve because of the nonlinear term involving $T^4$. But, we can handle it via the iterative solution method discussed above.\n", "meta": {"hexsha": "4c8a10524b129145c3e7e74c914dab90f6064fcb", "size": 89687, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "docs/_sources/content/bvps/finite-difference.ipynb", "max_stars_repo_name": "kyleniemeyer/ME373-book", "max_stars_repo_head_hexsha": "66a9ef0f69a8c4e1656c02080aebfb5704e1a089", "max_stars_repo_licenses": ["CC-BY-4.0", "BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "docs/_sources/content/bvps/finite-difference.ipynb", "max_issues_repo_name": "kyleniemeyer/ME373-book", "max_issues_repo_head_hexsha": "66a9ef0f69a8c4e1656c02080aebfb5704e1a089", "max_issues_repo_licenses": ["CC-BY-4.0", "BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/_sources/content/bvps/finite-difference.ipynb", "max_forks_repo_name": "kyleniemeyer/ME373-book", "max_forks_repo_head_hexsha": "66a9ef0f69a8c4e1656c02080aebfb5704e1a089", "max_forks_repo_licenses": ["CC-BY-4.0", "BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 136.095599393, "max_line_length": 24980, "alphanum_fraction": 0.8303879046, "converted": true, "num_tokens": 7070, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693674025231, "lm_q2_score": 0.9219218418270454, "lm_q1q2_score": 0.8755209323224591}} {"text": "# Final project\nThe Allen–Cahn equation (after John W. Cahn and Sam Allen) is a reaction–diffusion equation of mathematical physics which describes the process of phase separation in multi-component alloy systems, including order-disorder transitions.\n\nThe equation describes the time evolution of a scalar-valued state variable $\\eta$ on a domain $\\Omega=[0,1]$ during a time interval $[0,T]$, and is given (in one dimension) by:\n\n$$\n\\frac{\\partial \\eta}{\\partial t} - \\varepsilon^2 \\eta'' + f'(\\eta) = 0, \\qquad \\eta'(0, t) = \\eta'(1, t) = 0,\\qquad\\eta(x,0) = \\eta_0(x)\n$$\n\nwhere $f$ is a double-well potential, $\\eta_0$ is the initial condition, and $\\varepsilon$ is the characteristic width of the phase transition.\n\nThis equation is the L2 gradient flow of the Ginzburg–Landau free energy functional, and it is closely related to the Cahn–Hilliard equation.\n\nA typical example of double well potential is given by the following function\n\n$$\nf(\\eta) = \\eta^2(\\eta-1)^2\n$$\n\nwhich has two minima in $0$ and $1$ (the two wells, where its value is zero), one local maximum in $0.5$, and it is always greater or equal than zero.\n\nThe two minima above behave like \"attractors\" for the phase $\\eta$. Think of a solid-liquid phase transition (say water+ice) occupying the region $[0,1]$. When $\\eta = 0$, then the material is liquid, while when $\\eta = 1$ the material is solid (or viceversa).\n\nAny other value for $\\eta$ is *unstable*, and the equation will pull that region towards either $0$ or $1$.\n\nDiscretisation of this problem can be done by finite difference in time. For example, a fully explicity discretisation in time would lead to the following algorithm.\n\nWe split the interval $[0,T]$ in `n_steps` intervals, of dimension `dt = T/n_steps`. Given the solution at time `t[k] = k*dt`, it i possible to compute the next solution at time `t[k+1]` as\n\n$$\n\\eta_{k+1} = \\eta_{k} + \\Delta t \\varepsilon^2 \\eta_k'' - \\Delta t f'(\\eta_k)\n$$\n\nSuch a solution will not be stable. A possible remedy that improves the stability of the problem, is to treat the linear term $\\Delta t \\varepsilon^2 \\eta_k''$ implicitly, and keep the term $-f'(\\eta_k)$ explicit, that is:\n\n$$\n\\eta_{k+1} - \\Delta t \\varepsilon^2 \\eta_k'' = \\eta_{k} - \\Delta t f'(\\eta_k)\n$$\n\nGrouping together the terms on the right hand side, this problem is identical to the one we solved in the python notebook number 9, with the exception of the constant $\\Delta t \\varepsilon^2$ in front the stiffness matrix.\n\nIn particular, given a set of basis functions $v_i$, representing $\\eta = \\eta^j v_j$ (sum is implied), we can solve the problem using finite elements by computing\n\n$$\n\\big((v_i, v_j) + \\Delta t \\varepsilon^2 (v_i', v_j')\\big) \\eta^j_{k+1} = \\big((v_i, v_j) \\eta^j_{k} - \\Delta t (v_i, f'(\\eta_k)\\big)\n$$\nwhere a sum is implied over $j$ on both the left hand side and the right hand side. Let us remark that while writing this last version of the equation we moved from a forward Euler scheme to a backward Euler scheme for the second spatial derivative term: that is, we used $\\eta^j_{k+1}$ instead of $\\eta^j_{k}$. \n\nThis results in a linear system\n\n$$\nA x = b\n$$\n\nwhere \n\n$$\nA_{ij} = M_{ij}+ \\Delta t \\varepsilon^2 K_{ij} = \\big((v_i, v_j) + \\Delta t \\varepsilon^2 (v_i', v_j')\\big) \n$$\n\nand \n\n$$\nb_i = M_{ij} \\big(\\eta_k^j - \\Delta t f'(\\eta_k^j)\\big)\n$$\n\nwhere we simplified the integration on the right hand side, by computing the integral of the interpolation of $f'(\\eta)$.\n\n## Step 1\n\nWrite a finite element solver, to solve one step of the problem above, given the solution at the previous time step, using the same techniques used in notebook number 9.\n\nIn particular:\n\n1. Write a function that takes in input a vector representing $\\eta$, an returns a vector containing $f'(\\eta)$. Call this function `F`.\n\n2. Write a function that takes in input a vector of support points of dimension `ndofs` and the degree `degree` of the polynomial basis, and returns a list of basis functions (piecewise polynomial objects of type `PPoly`) of dimension `ndofs`, representing the interpolatory spline basis of degree `degree`\n\n3. Write a function that, given a piecewise polynomial object of type `PPoly` and a number `n_gauss_quadrature_points`, computes the vector of global_quadrature_points and global_quadrature_weights, that contains replicas of a Gauss quadrature formula with `n_gauss_quadrature_points` on each of the intervals defined by `unique(PPoly.x)`\n\n4. Write a function that, given the basis and the quadrature points and weights, returns the two matrices $M$ and $K$ \n\n## Step 2\n\nSolve the Allen-Cahan equation on the interval $[0,1]$, from time $t=0$ and time $t=1$, given a time step `dt`, a number of degrees of freedom `ndofs`, and a polynomial degree `k`.\n\n1. Write a function that takes the initial value of $\\eta_0$ as a function, eps, dt, ndofs, and degree, and returns a matrix of dimension `(int(T/dt), ndofs)` containing all the coefficients $\\eta_k^i$ representing the solution, and the set of basis functions used to compute the solution\n\n2. Write a function that takes all the solutions `eta`, the basis functions, a stride number `s`, and a resolution `res`, and plots on a single plot the solutions $\\eta_0$, $\\eta_s$, $\\eta_{2s}$, computed on `res` equispaced points between zero and one\n\n## Step 3\n\nSolve the problem for all combinations of\n\n1. eps = [01, .001]\n\n2. ndofs = [16, 32, 64, 128]\n\n3. degree = [1, 2, 3]\n\n3. dt = [.25, .125, .0625, .03125, .015625]\n\nwith $\\eta_0 = \\sin(2 \\pi x)+1$.\n\nPlot the final solution at $t=1$ in all cases. What do you observe? What happens when you increase ndofs and keep dt constant? \n\n## Step 4 (Optional)\n\nInstead of solving the problem explicitly, solve it implicitly, by using backward euler method also for the non linear term. This requires the solution of a Nonlinear problem at every step. Use scipy and numpy methods to solve the non linear iteration.\n\n\n```python\n%pylab inline\nimport sympy as sym\nimport scipy\nfrom scipy.interpolate import *\nfrom scipy.integrate import *\n```\n\n\n```python\n# Step 1.1\n\ndef F(eta):\n # Fill in with the derivative of the double well potential function\n return eta\n```\n\n\n```python\n# Step 1.2\n\ndef compute_basis_functions(support_points, degree):\n # Insert here what was in notebook 9\n\n # after you have computed the basis, return it\n # return basis\n return\n```\n\n\n```python\n# Step 1.3\n\ndef compute_global_quadrature(basis, n_gauss_quadrature_points):\n # Create a Gauss quadrature formula with n_gauss_quadrature_points, extract the intervals from basis (i.e., unique(basis.x)), and \n # create len(x)-1 shifted and scaled Gauss quadrature formulas that can be used to integrate on each interval. Put all of these \n # together, and return the result\n \n # return gloabl_quadrature, global_weights\n return\n```\n\n\n```python\n# Step 1.4\n\ndef compute_system_matrices(basis, gloabl_quadrature, global_weights):\n # Compute the matrices M_ij = (v_i, v_j) and K_ij = (v_i', v_j') and return them\n \n # return M, K\n return\n```\n\n\n```python\n# Step 2.1\n\ndef solve_allen_cahan(eta_0_function, eps, dt, ndofs, degree):\n # put together all the above functions, loop over time, and produce the result matrix eta, containing the solution at all points\n \n #return eta, basis\n```\n\n\n```python\n# Step 2.2 \n\ndef plot_solution(eta, basis, stride, resolution):\n # plot eta[::stride], on x = linspace(0,1,resolution)\n x = linspace(0,1,resolution)\n \n # plot(...)\n```\n", "meta": {"hexsha": "68a613a4044b15da1b30a8239bb270f7b4858da8", "size": 10190, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "final_project/final_project_2019-2020.ipynb", "max_stars_repo_name": "victorplesco/DSSC-Numerical_Analysis_19-20_COURSE", "max_stars_repo_head_hexsha": "808dbf0de86e2a7b2155f5e64d1888d72e82dbf8", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2017-10-10T14:35:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-15T18:15:49.000Z", "max_issues_repo_path": "final_project/final_project_2019-2020.ipynb", "max_issues_repo_name": "victorplesco/DSSC-Numerical_Analysis_19-20_COURSE", "max_issues_repo_head_hexsha": "808dbf0de86e2a7b2155f5e64d1888d72e82dbf8", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2018-01-31T12:05:45.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-26T18:24:57.000Z", "max_forks_repo_path": "final_project/final_project_2019-2020.ipynb", "max_forks_repo_name": "victorplesco/DSSC-Numerical_Analysis_19-20_COURSE", "max_forks_repo_head_hexsha": "808dbf0de86e2a7b2155f5e64d1888d72e82dbf8", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 129, "max_forks_repo_forks_event_min_datetime": "2017-10-05T09:08:27.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-13T20:30:07.000Z", "avg_line_length": 41.762295082, "max_line_length": 347, "alphanum_fraction": 0.6021589794, "converted": true, "num_tokens": 2089, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810496235895, "lm_q2_score": 0.9241418121440552, "lm_q1q2_score": 0.875514439990081}} {"text": "## Exercise 2.5\nIn this exercise, we prove that the beta distribution, given by \n\n$$\n\\mathrm{Beta}(\\mu|a, b) = \\frac{\\Gamma(a+b)}{\\Gamma(a)\\Gamma(b)}\\mu^{a-1}(1-\\mu)^{b-1},\n$$\n\n\nis correctly normalized, so that $\\int_0^1\\mathrm{Beta}(\\mu|a, b)d\\mu = 1$. \n\n### Solution\nThis is equivalent to showing that\n\n$$\n\\int_0^1\\mu^{a-1}(1-\\mu)^{b-1}d\\mu = \\frac{\\Gamma(a+b)}{\\Gamma(a)\\Gamma(b)}\n$$\n\nFrom the definition of the gamma function, we have\n\n$$\n\\Gamma(a)\\Gamma(b) = \\int_0^\\infty\\exp(-x)x^{a-1}dx\\int_0^\\infty\\exp(-y)y^{b-1}dy\n$$\n\nLet $t = y + x$, we obtain\n\n\\begin{align}\n\\Gamma(a)\\Gamma(b) & = \\int_0^\\infty x^{a-1}\\left\\{\\int_x^\\infty \\exp(-t)(t-x)^{b-1}\\mathrm{d}t\\right\\}\\mathrm{d}x \\\\\n& = \\int_0^\\infty\\int_0^t x^{a-1}\\exp(-t)(t-x)^{b-1}\\mathrm{d}x\\mathrm{d}t\n\\end{align}\n\nChange the variables in the $x$ integral using $x=t\\mu$ to give\n\n\\begin{aligned}\n\\Gamma(a)\\Gamma(b) & = \\int_0^\\infty\\exp(-t)t^{a-1}t^{b-1}t\\mathrm{d}t\\int_0^1\\mu^{a-1}(1-\\mu)^{b-1}\\mathrm{d}\\mu \\\\\n& = \\Gamma(a+b)\\int_0^1\\mu^{a-1}(1-\\mu)^{b-1}\\mathrm{d}\\mu\n\\end{aligned}\n", "meta": {"hexsha": "7f2bfe28700671d4b67e45f39438c72a68338eef", "size": 2022, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "bishop/chapter02/q05-Beta-Distributions.ipynb", "max_stars_repo_name": "yusueliu/murphy-book", "max_stars_repo_head_hexsha": "71d62cc083a683fb861be1e5acb8eeb948b00c54", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-03-25T22:22:23.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-29T20:46:58.000Z", "max_issues_repo_path": "bishop/chapter02/q05-Beta-Distributions.ipynb", "max_issues_repo_name": "yusueliu/murphy-book", "max_issues_repo_head_hexsha": "71d62cc083a683fb861be1e5acb8eeb948b00c54", "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": "bishop/chapter02/q05-Beta-Distributions.ipynb", "max_forks_repo_name": "yusueliu/murphy-book", "max_forks_repo_head_hexsha": "71d62cc083a683fb861be1e5acb8eeb948b00c54", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-24T01:14:12.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-24T01:14:12.000Z", "avg_line_length": 27.698630137, "max_line_length": 141, "alphanum_fraction": 0.4792284866, "converted": true, "num_tokens": 467, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9752018455701406, "lm_q2_score": 0.8976953023710936, "lm_q1q2_score": 0.8754341156319358}} {"text": "# Circular Bump Function\n\n\n```julia\nusing Plots\n\nt = collect(-1:0.01:1)\ncb(t) = abs(t)<1/2 ? sqrt.(0.25 .- t.^2) : 0\np = plot(t,cb.(t), xlim=[-1,1], ylim=[-0.1,1], label=:false, linewidth=4, xlabel=\"t\")\n```\n\n\n\n\n \n\n \n\n\n\n# Fourier transform \n\nConsidering that the signal is read and even:\n\n$$\n\\begin{align}\ny(t) &= \\frac{a_0}{2} + \\sum_{n=1}^{\\infty} a_n \\frac{cos(n\\pi t)}{L} \\\\\n\\end{align}\n$$\n\nThe following integral is derived with Mathematica online calculator.\n\n$$\n\\begin{align}\na(0) &= \\int_{-L}^{+L} y(t) dt \\\\\n&= \\int_{-0.5}^{+0.5} \\sqrt{\\frac{1}{4}-t^2} dt \\\\\n&= 0.392699\n\\end{align}\n$$\n\nAnd, \n\n$$\n\\begin{align}\na(n) &= \\frac{1}{L} \\int_{-L}^{+L} y(t) cos(\\frac{n \\pi t}{L}) dt \\\\\n&= \\int_{-0.5}^{+0.5} \\sqrt{\\frac{1}{4}-t^2} cos(n \\pi t) dt \\\\\n&= \\frac{J_1(\\frac{n\\pi}{2})}{2n}\n\\end{align}\n$$\n\n\n\n## M program\n\n\n```julia\nusing SpecialFunctions\n\nfunction Mp(m, t)\n a0 = 0.392699\n y = (a0/2)*ones(size(t))\n for n=1:m\n an = besselj(1, n*π/2)/(2*n)\n y += an*cos.(n*π*t) \n end\n y\nend \n```\n\n\n\n\n Mp (generic function with 1 method)\n\n\n\n\n```julia\nm = [0, 1, 5, 10, 25, 50]\n\nfor k in m\n y = Mp(k, t)\n p = plot!(p, t,y, linewidth=3, label=\"m=\"*string(k), title=\"Fourier series for differnt M\")\nend\n\ndisplay(p)\n```\n\n\n \n\n \n\n\n## RMS error\n\n\n```julia\nfunction err(m)\n t = collect(-1:0.01:1)\n sqrt(sum((Mp(m, t)-cb.(t)).^2)/size(t,1))\nend\n\nplot(m,err.(m), seriestype=:scatter, xlabel=\"Number of terms in Fourier sum\"\n , ylabel=\"RMS error\", title=\"RMS error\", label=:false)\n```\n\n\n\n\n \n\n \n\n\n\n## Adjourn\n\n\n```julia\nusing Dates\nprintln(\"mahdiar\")\nDates.format(now(), \"Y/U/d HH:MM\") \n```\n\n mahdiar\n\n\n\n\n\n \"2021/February/4 16:53\"\n\n\n", "meta": {"hexsha": "8f5d8b845572b422d458273577e0a175ce4c2f05", "size": 158203, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "HW02/2.ipynb", "max_stars_repo_name": "mahdiarsadeghi/NumericalAnalysis", "max_stars_repo_head_hexsha": "95a0914c06963b0510971388f006a6b2fc0c4ef9", "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": "HW02/2.ipynb", "max_issues_repo_name": "mahdiarsadeghi/NumericalAnalysis", "max_issues_repo_head_hexsha": "95a0914c06963b0510971388f006a6b2fc0c4ef9", "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": "HW02/2.ipynb", "max_forks_repo_name": "mahdiarsadeghi/NumericalAnalysis", "max_forks_repo_head_hexsha": "95a0914c06963b0510971388f006a6b2fc0c4ef9", "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": 222.5077355837, "max_line_length": 24453, "alphanum_fraction": 0.6857708134, "converted": true, "num_tokens": 676, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541610257063, "lm_q2_score": 0.9294404023468588, "lm_q1q2_score": 0.8752114222953262}} {"text": "```python\n# This cell just imports relevant modules\n\nimport numpy\nimport pylab\nfrom sympy import sin, cos, exp, ln, Function, Symbol, diff, integrate, limit, oo, series, factorial\nfrom math import pi\nimport mpmath\n%matplotlib inline\nimport matplotlib.pyplot as plt\n```\n\n\n```python\n###### SEQUENCES ######\n###### Lecture 6, slide 10 ######\n# Finite sequence example. The elements of the sequence are stored in a list\nfinite_sequence = [2*k for k in range(1, 5)] \n# Remember: range(A,B) generates integers from A up to B-1, so we need to use B=5 here\n```\n\n\n```python\n###### CONVERGENCE OF SEQUENCES ######\n###### Lecture 6, slide 11, 13, 14 ######\nk = Symbol('k')\nprint(\"As k->infinity, the sequence {k} tends to: %f\" % limit(k, k, oo) ) \n# The 'oo' here is SymPy's notation for infinity\n\nprint(\"As k->infinity, the sequence {1/k} tends to: %f\" % limit(1.0/k, k, oo)) \n\nprint(\"As k->infinity, the sequence {exp(1/k)} tends to: %f\" % limit(exp(1.0/k), k, oo)) \n\nprint(\"As k->infinity, the sequence {(k**3 + 2*k - 4)/(k**3 + 1)} tends to: %f\" \n % limit((k**3 + 2*k - 4)/(k**3 + 1), k, oo)) \n```\n\n\n```python\n###### SERIES ######\n###### Lecture 6, slide 15 ######\n# Using list comprehension:\nprint(\"The sum of 3*k + 1 (from k=0 to k=4) is: %f\" % sum([3*k + 1 for k in range(0,5)])) \n# Note: we could also use the nsum function (part of the module mpmath): \n# import mpmath\n# print mpmath.nsum(lambda k: 3*k + 1, [0, 4])\n\nx = 1\nprint(\"The sum of (x**k)/(k!) from k=0 to k=4, with x = 1, is: %f\" % sum([x**k/factorial(k) for k in range(1,5)])) \n```\n\n\n```python\n###### ARITHMETIC PROGRESSION ######\n###### Lecture 6, slide 18 ######\nprint(\"The sum of 5 + 4*k up to the 11th term (i.e. up to k=10) is: %f\" % sum([5 + 4*k for k in range(0,11)])) \n```\n\n\n```python\n###### GEOMETRIC PROGRESSION ######\n###### Lecture 6, slide 21 ######\nprint(\"The sum of 3**k up to the 7th term (i.e. up to k=6) is: %f\" % sum([3**k for k in range(0,7)])) \n```\n\n\n```python\n###### INFINITE SERIES ######\n###### Lecture 6, slide 23, 24, 25 ######\nprint(\"The sum of the infinite series sum(1/(2**k)) is: %f\" % mpmath.nsum(lambda k: 1/(2**k), [1, mpmath.inf])) \nprint(\"The sum of the infinite alternating series sum(((-1)**(k+1))/k) is: %f\" \n % mpmath.nsum(lambda k: ((-1)**(k+1))/k, [1, mpmath.inf])) \n```\n\n\n```python\n###### RATIO TEST ######\n###### Lecture 6, slide 27 ######\n# A divergent example\nk = Symbol('k')\nf = (2**k)/(3*k)\nf1 = (2**(k+1))/(3*(k+1))\nratio = f1/f\n\nlim = limit(ratio, k, oo) \nprint(\"As k -> infinity, the ratio tends to: %f\" % lim) \nif(lim < 1.0):\n print(\"The series converges\") \nelif(lim > 1.0):\n print(\"The series diverges\") \nelse:\n print(\"The series either converges or diverges\") \n\n# A converging example\nf = (2**k)/(5**k)\nf1 = (2**(k+1))/(5**(k+1))\nratio = f1/f\n```\n\n\n```python\n###### POWER SERIES ######\n###### Lecture 6, slide 30 ######\nk = Symbol('k')\nx = Symbol('x')\n\na = 1.0/k\nf = a*(x**k)\n\na1 = 1.0/(k+1)\nf1 = a1*(x**(k+1))\n\nratio = abs(a/a1)\nR = limit(ratio, k, oo)\nprint(\"The radius of convergence (denoted R) is: %f\" % R) \n\nx = 0.5\nif(abs(x) < 1):\n print(\"The series converges for |x| = %f (< R)\" % abs(x)) \nelif(abs(x) > 1):\n print(\"The series diverges for |x| = %f (> R)\" % abs(x)) \nelse:\n print(\"The series either converges or diverges for |x| = %f (== R)\\n\" % abs(x)) \n```\n\n\n```python\n###### USEFUL SERIES ######\n###### Lecture 6, slide 34 ######\nx = Symbol('x')\nr = Symbol('r')\n\n# Note: the optional argument 'n' allows us to truncate the series\n# after a certain order of x has been reached.\nprint(\"1/(1+x) = \", series(1.0/(1.0+x), x, n=4)) \nprint(\"1/(1-x) = \", series(1.0/(1.0-x), x, n=4)) \nprint(\"ln(1+x) = \", series(ln(1.0+x), x, n=4)) \nprint(\"exp(x) = \", series(exp(x), x, n=4)) \nprint(\"cos(x) = \", series(cos(x), x, n=7)) \nprint(\"sin(x) = \", series(sin(x), x, n=8)) \n```\n\n\n```python\n### plot taylor series for ln(1+x) with different number of terms n\n\ndef ln_taylor(x, n):\n y = 0\n for i in range(1,n):\n y += (-1)**(i+1) * (x**i)/(factorial(i))\n return y\n\nx = numpy.array([0.01*i for i in range(-50, 50)])\n\nln = numpy.log(1+x)\n\nn = numpy.array([i for i in range(1, 6)])\n\ny_ln = {}\n\nfor i in range(len(n)):\n y_ln['n='+str(n[i])] = []\n for j in range(len(x)):\n y_ln['n='+str(n[i])].append(ln_taylor(x[j], n[i]))\n\ncolour = ['c', 'b', 'g', 'y', 'r'] \n\nplt.figure(figsize=(9, 9))\nfor i in range(len(n)):\n plt.plot(x, y_ln['n='+str(n[i])], colour[i], label='n=%.d' % (n[i]))\nplt.plot(x, ln, 'k', label='y=ln(1+x)')\nplt.xlabel('x')\nplt.ylabel('y')\nplt.title('Compare function ln(1+x) with taylor series containing different number of terms', fontsize=14)\nplt.legend(loc='best', fontsize=14)\nplt.grid(True)\nplt.show()\n```\n\n\n```python\n### plot taylor series for exp(x) with different number of terms n\n\ndef exp_taylor(x, n):\n y = 0\n for i in range(n):\n y += x**i / factorial(i)\n return y\n\n\nx = numpy.array([0.01*i for i in range(0, 500)])\n\nexpx = numpy.exp(x)\n\nn = numpy.array([i for i in range(1, 6)])\n\ny_exp = {}\n\nfor i in range(len(n)):\n y_exp['n='+str(n[i])] = []\n for j in range(len(x)):\n y_exp['n='+str(n[i])].append(exp_taylor(x[j], n[i]))\n\ncolour = ['c', 'g', 'b', 'y', 'r'] \n\nplt.figure(figsize=(7, 7))\nfor i in range(len(n)):\n plt.plot(x, y_exp['n='+str(n[i])], colour[i], label='n=%.d' % (n[i]))\nplt.plot(x, expx, 'k', label='y=exp(x)')\nplt.xlabel('x')\nplt.ylabel('y')\nplt.title('Compare function exp(x) with taylor series containing different number of terms', fontsize=14)\nplt.legend(loc='best', fontsize=14)\nplt.grid(True)\nplt.show()\n```\n\n\n```python\n### plot taylor series for sin(x) with different number of terms n\n\ndef sin_taylor(x, n):\n y = 0\n for i in range(n):\n y += (-1)**(i)*(x**(2*i+1) / factorial(2*i+1))\n return y\n\nx = numpy.array([0.01*i for i in range(-500, 500)])\n\nsinx = numpy.sin(x)\n\nn = numpy.array([i for i in range(1, 6)])\n\ny_sin = {}\n\nfor i in range(len(n)):\n y_sin['n='+str(n[i])] = []\n for j in range(len(x)):\n y_sin['n='+str(n[i])].append(sin_taylor(x[j], n[i]))\n\ncolour = ['r', 'y', 'g', 'b', 'c'] \n\nplt.figure(figsize=(9, 9))\nfor i in range(len(n)):\n plt.plot(x, y_sin['n='+str(n[i])], colour[i], label='n=%.d' % (n[i]))\nplt.plot(x, sinx, 'k', label='y=sin(x)')\nplt.xlabel('x')\nplt.ylabel('y')\nplt.title('Compare function sin(x) with taylor series containing different number of terms', fontsize=14)\nplt.legend(loc='best', fontsize=14)\nplt.grid(True)\nplt.show()\n```\n", "meta": {"hexsha": "b479a6923713458ed3a5ea3fe2b5a0cb92130034", "size": 148773, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "mathematics/mm1/Lecture_6_Series.ipynb", "max_stars_repo_name": "jrper/thebe-test", "max_stars_repo_head_hexsha": "554484b1422204a23fe47da41c6dc596a681340f", "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/mm1/Lecture_6_Series.ipynb", "max_issues_repo_name": "jrper/thebe-test", "max_issues_repo_head_hexsha": "554484b1422204a23fe47da41c6dc596a681340f", "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/mm1/Lecture_6_Series.ipynb", "max_forks_repo_name": "jrper/thebe-test", "max_forks_repo_head_hexsha": "554484b1422204a23fe47da41c6dc596a681340f", "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": 399.9274193548, "max_line_length": 52944, "alphanum_fraction": 0.9286967393, "converted": true, "num_tokens": 2269, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545289551958, "lm_q2_score": 0.9230391690674338, "lm_q1q2_score": 0.875183768554328}} {"text": "```python\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.animation import FuncAnimation\nfrom sympy import *\nfrom IPython import display\n```\n\n### EXAMPLE 2.1\nA stirred-tank blending process with a constant liquid holdup of 2 $m^3$ is used to blend two streams whose densities are both approximately 900 $kg/m^3$. The density does not change during mixing.\n\n\n\n**(a)** Assume that the process has been operating for a long period of time with flow rates of $w_1$ = 500 kg/min and\n$w_2$ = 200 kg/min, and feed compositions (mass fractions) of $x_1$ = 0.4 and $x_2$ = 0.75. What is the steady-state value of x?\n\n\n```python\nw1=500 # 500kg/min\nw2=200 # kg/min\nx1=0.4\nx2=0.75\n# since the process is assumed to be at steady state then\nw=w1+w2\n\n# since wx=w1*x1+w2*x2\nx=(w1*x1+w2*x2)/w\nprint(\"x = \",x)\n```\n\n x = 0.5\n\n\n**(b)** Suppose that $w_1$ changes suddenly from 500 to 400 kg/min and remains at the new value. Determine an expression for x(t) and plot it.\n\n\n```python\n# if we want to know the new steady state after the change we can repeate the same calculation in (a) but\n# using different value for w1\nw1=400 # kg/min\nw=w1+w2\nx=(w1*x1+w2*x2)/w\nprint(\"The new steady state will be at x = \",x)\n```\n\n The new steady state will be at x = 0.5166666666666667\n\n\n\n```python\n# However, the question is asking us to plot how x reached to the new steady-state over time?\n# So, we have to use the differential equations that model the tank:\n\n# d(rho*V)/dt=w1+w2-w\n# d(rho*V*x)/dt=w1*x1+w2*x2-w*x\n\n# since both rho (density) and volume is assume to be constants then the steady state for the\n# mass balance still holds:\nw1=400\nw2=200\nx1=0.4\nx2=0.75\nw=w1+w2\n\n# for the composition equation:\n# V*rho*(dx/dt) + wx = w1*x1+w2*x2 dividing by w we get:\n# tau*(dx/dt) + x = m where tau=(V*rho)/w and m=(w1*x1+w2*x2)/w\nV = 2 # m3\nrho=900 # kg/m3\ntau=V*rho/w\nm=(w1*x1+w2*x2)/w\n\n# solving the differential equation manually using the following intial condition\n# x(0)=0.5 we get the following equation that describe the dynamics process of the tank\nx0=0.5\n\ndef f(t):\n return (x0-m)*np.exp(-t/tau)+m\nt=np.linspace(0,25)\nx=f(t)\nplt.plot(t,x)\nplt.show()\n```\n\n\n```python\n# using sympy module to find the analytic solution for the ODE\n\ninit_printing()\ntau,m, t = symbols('tau m t')\nx = Function('x')\node = Eq(tau*diff(x(t), t)+x(t), m)\node\n```\n\n\n```python\nsol = dsolve(ode, x(t))\nsol\n```\n\n\n```python\n# using scipy.integrate to numerically solve the ODE for part b of the question\n\nfrom scipy.integrate import odeint\nV=2 # m3\nrho= 900 #kg/m3\nw1=400 # kg/min\nw2=200 # kg/min\nx1=0.4\nx2=0.75\nw=w1+w2\ndef model(x,t):\n tau=V*rho/w\n m=(w1*x1+w2*x2)/w\n return (m-x)/tau\nt=np.linspace(1,25,100)\nx0=0.5\nx=odeint(model,x0,t)\nplt.plot(t,x)\nplt.show()\n```\n\n**(c)** Repeat part **(b)** for the case where $w_2$ (instead of $w_1$) changes suddenly from 200 to 100 kg/min and remains\nthere.\n\n\n```python\nw1=500\nw2=100\nx1=0.4\nx2=0.75\nw=w1+w2\ntau=V*rho/w\nm=(w1*x1+w2*x2)/w\nt=np.linspace(0,25,100)\nx=f(t)\nplt.plot(t,x)\nplt.show()\n```\n\n**(d)** Repeat part **(c)** for the case where $x_1$ suddenly changes\nfrom 0.4 to 0.6 (in addition to the change in $w_2$).\n\n\n```python\nw1=500\nw2=100\nx1=0.6\nx2=0.75\nw=w1+w2\ntau=V*rho/w\nm=(w1*x1+w2*x2)/w\nt=np.linspace(0,25)\nx=f(t)\nplt.plot(t,x)\nplt.show()\n```\n\n**(e)** For parts **(b)** through **(d)**, plot the normalized response $x_N(t)$,\n$$x_N(t) = \\frac{x(t) − x(0)}{\nx(∞) − x(0)}$$\n\n\nThe individual responses have the same normalized response:\n$$\\frac{x(t) − x(0)}{x(∞) − x(0)} = 1 − e^{−\\frac{t}{\\tau}}$$\n\n\n```python\ndef normal_response(t):\n return 1-np.exp(-t/tau)\nxn=normal_response(t)\nplt.plot(t,xn) \nplt.show()\n```\n\n\n```python\nfig,ax=plt.subplots()\nax.set_xlim(0,25)\nax.set_ylim(0.4,.6)\ncurve,=ax.plot(t[0],x0)\nt_data=[]\nx_data=[]\ndef animation_frame(i):\n t_data.append(t[i])\n x_data.append(f(t[i]))\n curve.set_data((t_data,x_data))\n\nanimation=FuncAnimation(fig,func=animation_frame,frames=100,interval=200)\nvideo=animation.to_html5_video()\nhtml=display.HTML(video)\ndisplay.display(html)\nplt.close()\n```\n\n\n\n\n\n\n```python\npip install ffmpeg-python\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "9689e2fb0e83314d3e1124f50595f3fc22c2a902", "size": 111739, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "chapter-2.ipynb", "max_stars_repo_name": "AhmadAlsaadi/ENCH421", "max_stars_repo_head_hexsha": "6f0bdaf043059517b7616b2f603da8dbcbee6fbf", "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": "chapter-2.ipynb", "max_issues_repo_name": "AhmadAlsaadi/ENCH421", "max_issues_repo_head_hexsha": "6f0bdaf043059517b7616b2f603da8dbcbee6fbf", "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": "chapter-2.ipynb", "max_forks_repo_name": "AhmadAlsaadi/ENCH421", "max_forks_repo_head_hexsha": "6f0bdaf043059517b7616b2f603da8dbcbee6fbf", "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": 151.2029769959, "max_line_length": 16808, "alphanum_fraction": 0.8936539615, "converted": true, "num_tokens": 1462, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.923039160069787, "lm_q2_score": 0.9481545276733135, "lm_q1q2_score": 0.8751837588399409}} {"text": "# Numerical Integration\n\nNumerical integration can be expressed as the following approximate sum:\n\n$$I = \\int_a^b f(x) dx \\approx \\sum_{i=1}^{n} A_i f(x_i)$$\n\nwhere $A_i$ are the weights associated with the function evaluated at $x_i$. Typically, $n+1$ data points $x_i, i = 0,1,2, \\ldots , n$ are selected starting from $a$ upto $b$, and the function is evaluated at each of these ordinates. The weighted sum above is an approximation to the integral we are attemptying to evaluate.\n\nThere are two main approaches to carrying out numerical integration. The first approach based on Newton-Cotes formulae divides the interval $a$ to $b$ into a certain number of panels, usually of equal width. If $n$ is the number of panels, then $n+1$ is the number of ordinates, and the function is evaluated at each of these ordinates. For such methods, accuracy usually increases with the number of panels. The second approach is based on Gauss Quadrature. These methods evaluate the function at only a few specified ordinates. Gauss quadrature usually gives accurate results even with only a few function evaluations and can be used even when the limits tend to infinity.\n\n## Newton-Cotes Formulas\nNewton-Cotes formulas are based on approximating the given function by a polynomial and computing the integral of the polynomial.\n\n$$I = \\int_a^b f(x) dx \\approx \\int_a^b f_n(x) dx$$\n\nwhere $f_n(x)$ is a polynomial of the form $f_n(x) = a_0 + a_1 c + a_2 x^2 + \\cdots + a_{n-1} x^{n-1} + a_n x^n$.\n\nTrapezoidal Rule is Newton-Cotes formula with $n=1$, which is the equation of a straigt line. Simpson's 1/3 Rule is Newton-Cotes formula with $n=2$, which is a parabola. Trapezoidal rule requires us to determine two unknowns, $a_0$ and $a_1$, thereby requiring two points whereas Simpson's 1/3 rule requires three unknowns $a_0$, $a_1$ and $a_2$, thereby requiring three points. It is easier to obtain the coefficients $a_i$ if the panels are of equal width. The formula for Trapezoidal rule is as follows:\n\n$$I \\approx \\frac{h}{2} \\left[ f(a) + f(a+h) \\right]$$\n\nSimpson's 1/3 rule is as follows:\n\n$$I \\approx \\frac{h}{3} \\left[ f(a) + 4 f(a+h) + f(a+2h) \\right]$$\n\n## Example\nLet us consider the function $f(x) = e^{-x^2}$ and integrate it between the limits $a=0$ to $b=1$, $I = \\int_{0}^{1} e^{-x^2} dx$. Let us first use SymPy to calculate the exact answer. In SymPy we must define the symbols that we will use for variables, in this case $x$. We will then define the equation that we wish to integrate, the symbol for the variable and the lower and upper limits of integration. Method **`doit()`** evaluates the integral and the function **`N()`** calculates the numerical value of the integral.\n\n\n```python\nfrom __future__ import division, print_function\n\nfrom sympy import *\nx = symbols('x')\ninit_printing()\n\nc = Integral(exp(-x**2), (x, 0, 1))\nEq(c, c.doit())\n```\n\n\n```python\nd = N(c.doit())\nprint(d)\n```\n\n 0.746824132812427\n\n\nWe now have the value of the integral stored in the object $d$, which we can use later.\n\nThe two methods of numerical integration that we will use are the Trapezoidal Rule and Simpson's 1/3 Rule. Both methods require that the interval $a \\text{ to } b$ be divided into equal panels, but the latter method also requires that the number of panels be an even number.\n\n## Composite Trapezoidal Rule\nLet the range $a$ to $b$ be divided into $n$ equal panels, each of width $h = \\frac{b - a}{n}$. Thus the number of data points is $n+1$ and the ordinate of the points is $x_i = a + (i \\cdot h), i = 0, 1, \\ldots , n$.\n\nTrapezoidal rule assumes the function to vary linearly between successive data points, and the resulting approximation to the integral is given as:\n\n$$I = \\int_a^b f(x) dx \\approx \\frac{h}{2} \\left( y_0 + 2 \\sum_{i=1}^{n-2} y_i + y_{n-1} \\right)$$\n\nwhere $y_i = f(x_i)$ is the value of the function evaluated at each ordindate.\n\n\n```python\nimport numpy as np\n\ndef f(x):\n return np.exp(-x**2)\n\ndef trap(f, a, b, n, verbose=False):\n x = np.linspace(a, b, n+1)\n y = f(x)\n if verbose:\n for xx, yy in zip(x, y):\n print(\"%10.4f %20.16f\" % (xx, yy))\n h = float(b - a) / n\n s = h * (y[0] + y[-1] + 2 * sum(y[1:-1])) / 2.0\n return s\n\na = 0.0\nb = 1.0\nfor n in [10, 50, 100]:\n s = trap(f, a, b, n)\n print(\"%5d %20.16f %8.4f\" % (n, s, (s - d) * 100 / d))\n```\n\n 10 0.7462107961317495 -0.0821\n 50 0.7467996071893513 -0.0033\n 100 0.7468180014679697 -0.0008\n\n\n## Composite Simpson's 1/3 Rule\nIf the interval from $a$ to $b$ is divided into $n$ equal panels each of width $h = \\frac{b - a}{n}$ and $n+1$ is the number of ordinates, for Simpson's 1/3 rule, $n$ must be an even number (and $n+1$, obviously must be an odd number).\n\nSimpson's 1/3 rule fits a parabola (polynomial of order two) between three successive points and approximates the integral for the two consecutive panels. To be able to do so, the number of data points must be atleast 3 and the number of panels must be an even number. The composite Simpson's 1/3 rule for $n$ data points (where $n$ must be odd), and $n-1$ panels (where $n-1$ must be even) is given below:\n\n$$I = \\int_a^b f(x) dx \\approx \\frac{h}{3} \\left( y_0 + 4 \\sum_{i=1, 3, 5,\\ldots}^{n-2} y_i + 2 \\sum_{j=2,4,6,\\ldots}^{n-3} y_j \\right)$$\n\n\n```python\ndef simp(f, a, b, npanels, verbose=False):\n x = np.linspace(a, b, npanels+1)\n y = f(x)\n if verbose:\n for xx, yy in zip(x, y):\n print(\"%10.4f %20.16f\" % (xx, yy))\n h = float(b - a) / n\n s = h * (y[0] + y[-1] + 4*sum(y[1:-1:2]) + 2*sum(y[2:-2:2])) / 3.0\n return s\n\nf = lambda x: np.exp(-x*x)\na = 0.0\nb = 1.0\nfor n in [10, 50, 100]:\n s = simp(f, a, b, n)\n print(\"%5d %20.16f %14.10f\" % (n, s, (s - d)*100/d))\n```\n\n 10 0.7468249482544435 0.0001091880\n 50 0.7468241341203178 0.0000001751\n 100 0.7468241328941762 0.0000000109\n\n\nUsually we are given the function, the lower and upper limits of the interval and the number of equal panels and we have to generate both the ordinates $x_i$ as well as the value of the function $y_i$ at these ordinates. However, sometimes the data points and value of the function at these ordinates are either already evaluated, or are obtained from an experimental observation, In such case, we must merely calculate the numerical integral. In the latter case, the panel width is calculated as $x_1 - x_0$ or the difference between any two consecutive data points. The functions for Trapezoidal and Simpson's 1/3 rules to calculate numerical integration from digitized data are given below:\n\n\n```python\ndef trap1(x, y):\n assert (len(x) == len(y)), 'x and y must have same length'\n m = len(x)\n h = x[1] - x[0]\n return h * (y[0] + 2*sum(y[1:-1]) + y[-1]) / 2.0\n\nfor n in [10, 50, 100]:\n x = np.linspace(0, 1, n+1)\n y = f(x)\n s = trap1(x, y)\n print(\"%5d %20.16f %20.16f\" % (n, s, (s-d)/s*100))\n```\n\n 10 0.7462107961317495 -0.0821934879335684\n 50 0.7467996071893513 -0.0032840969437502\n 100 0.7468180014679697 -0.0008209958042266\n\n\n\n```python\ndef simp1(x, y):\n assert (len(x) == len(y)), 'x and y must have same length'\n m = len(x)\n h = x[1] - x[0]\n return h / 3 * (y[0] + 4*sum(y[1:-1:2])+2*sum(y[2:-2:2])+y[-1])\n\na = 0.0; b = 1.0; n = 10\nfor n in [10, 50, 100]:\n x = np.linspace(a, b, n+1)\n y = f(x)\n s = simp1(x, y)\n print(\"%5d %20.16f %20.16f\" % (n, s, (s-d)/s*100))\n```\n\n 10 0.7468249482544436 0.0001091878382589\n 50 0.7468241341203179 0.0000001751270275\n 100 0.7468241328941762 0.0000000109462401\n\n\nAccuracy of the integral computed by the Trapezoidal Rule and Simpson's 1/3 Rule depend greatly on the number of panels into which the interval is divided. However, it is inefficient to divide the interval into a large number of panels and carry out the integration. If it is possible to determine an optimum number of panels that will give us a desired accuracy, it would be a good idea. However, the optimal number of divisions depends greatly on the nature of variation of the function being integrated. Trapezoidal rule offers a simple approach to implement it recursively and we can stop when we don't see a noticable change in the integral on subsequent iterations. This is called the recursive Trapezoidal Rule. The number of divisions is doubled each time and a recursive equation is obtained giving the change to be made to the previously calculated integrand. When this change is smaller than the required accuracy, we can stop the recursion.\n\n\\begin{align*}I_1 &= \\frac{b - a}{2} \\left[ f(x_a) + f(x_b) \\right] \\\\\nI_k &= \\frac{1}{2} I_{k-1} + \\frac{H}{2^{k-1}} \\sum_{i=1}^{2^{k-2}} f\\left( a + \\frac{(2i-1)H}{2^{k-1}} \\right),\\quad k=2,3, \\ldots \\\\\n\\text{where } H &= b - a\n\\end{align*}\n\n\n```python\ndef trap3(f, a, b, tol=1e-12, maxiter=50):\n h = float(b - a)\n s1 = h / 2.0 * (f(a) + f(b))\n k = 1\n while (k < maxiter):\n n = 2**(k-2) + 1\n s = 0.0\n for i in range(1, int(n)):\n x = a + (2*i-1)*h/2**(k-1)\n s += f(x)\n s *= h / 2**(k-1)\n s2 = s1 / 2.0 + s\n print(\"%5d %21.16f %21.16f %21.16f\" % (k, s1, s2, (s2-s1)/s2))\n if abs(s2 - s1)/s2 < tol:\n return k, s2\n else:\n s1 = s2\n k += 1\n return k, None\n\ni, s = trap3(f, 0.0, 1.0, 1e-6)\nprint(i, s)\n```\n\n 1 0.6839397205857212 0.3419698602928606 -1.0000000000000000\n 2 0.3419698602928606 0.5603853216821327 0.3897594261278027\n 3 0.5603853216821327 0.6574916327271660 0.1476920864258796\n 4 0.6574916327271660 0.7031193823090877 0.0648933178773671\n 5 0.7031193823090877 0.7252114805199178 0.0304629736349346\n 6 0.7252114805199178 0.7360776965181424 0.0147623220342430\n 7 0.7360776965181424 0.7414658845707519 0.0072669399425287\n 8 0.7414658845707519 0.7441487510080799 0.0036052824568926\n 9 0.7441487510080799 0.7454873774793834 0.0017956393518421\n 10 0.7454873774793834 0.7461559890375631 0.0008960747725714\n 11 0.7461559890375631 0.7464901193978701 0.0004476018524888\n 12 0.7464901193978701 0.7466571407233649 0.0002236921290713\n 13 0.7466571407233649 0.7467406404224493 0.0001118188760118\n 14 0.7467406404224493 0.7467823875310751 0.0000559026422193\n 15 0.7467823875310751 0.7468032604001609 0.0000279496223338\n 16 0.7468032604001609 0.7468136966633958 0.0000139743864923\n 17 0.7468136966633958 0.7468189147521860 0.0000069870870797\n 18 0.7468189147521860 0.7468215237858743 0.0000034935169987\n 19 0.7468215237858743 0.7468228283000390 0.0000017467518604\n 20 0.7468228283000390 0.7468234805564580 0.0000008733742792\n 20 0.746823480556\n\n\n\n```python\ndef trap4(f, a, b, Iold, k):\n '''Recursive Trapezoidal Rule'''\n n = int(2**(k-2))\n h = float(b - a) / n\n x = a + h / 2.0\n s = 0.0\n for i in range(n):\n s += f(x)\n x += h\n Inew = (Iold + h*s) / 2.0\n return Inew\n\nIold = float(b - a) * (f(a) + f(b)) / 2.0\nfor k in range(2, 11):\n Inew = trap4(f, 0.0, 1.0, Iold, k)\n print(\"%5d %21.16f\" % (k, Inew))\n Iold = Inew\n```\n\n 2 0.7313702518285630\n 3 0.7429840978003812\n 4 0.7458656148456952\n 5 0.7465845967882216\n 6 0.7467642546522943\n 7 0.7468091636378279\n 8 0.7468203905416179\n 9 0.7468231972461524\n 10 0.7468238989209475\n\n\nThe points to be considered when writing functions that operate on digitized data are:\n\n1. The ordinates and function values must either be available as observed data or generated in advance\n2. Data digitization must be at equal intervals\n\n## Gauss Quadrature\n\n\\begin{align*}\nI &=\\int_{a}^{b} w(x) \\, f(x) \\, dx \\approx \\sum_{i=1}^{n} (A_i y_i) \\\\\nA_i &= \\text{weights, calculated based on number of points} \\\\\nx_i &= \\text{ordinates at which function is evaluated} \\\\\ny_i &= f(x_i)\n\\end{align*}\n\n### Gauss-Legendre Quadrature\n\\begin{align*}\nI &=\\int_{-1}^{1} w(x) \\, f(x) \\, dx \\approx \\sum_{i=1}^{n} (A_i y_i)\n\\end{align*}\n\nMethods based on Newton-Cotes formulas depend on the number of points at which the function is evaluated to increas ccuracy of the integral. Typically, larger the number of function evaluations, more accurate is the integral. On the other hand, Gauss quadrature requires only a few function evaluations but yield fairly accurate integrals. The points at which the function is evaluated is critical in Gauss quadrature.\n\n\nFor Gauss-Legendre quadrature, the values of $x_i$ and $A_i$ for the limits $-1$ to $+1$ are as follows:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
**Number of Points****Points** $x_i$**Weights** $A_i$
102.000000
2$-\\sqrt{\\frac{1}{3}}=-0.577350$1.000000
$+\\sqrt{\\frac{1}{3}}=+0.577350$1.000000
3$-\\sqrt{\\frac{3}{5}}=-0.774597$$\\frac{5}{9}=0.555556$
$0$$\\frac{8}{9}=0.888889$
$+\\sqrt{\\frac{3}{5}}=+0.774597$$\\frac{5}{9}=0.555555$
\n\nIf the limits of integration are $a$ to $b$ instead of $-1$ to $1$, we can transform the formulation assuming $x = c_1 t + c_2$, with $x=a$ at $t=-1$ and $x=b$ at $t=+1$, resulting in $c_1 = \\frac{b-a}{2}$ and $c_2 = \\frac{b+a}{2}$. This leads to\n\n\\begin{align*}\nx &= \\frac{b-a}{2} \\, t + \\frac{b+a}{2} \\\\\ndx &= \\frac{b-a}{2} \\, dt\n\\end{align*}\n\nLet us consider the numerical integration of the following function\n\\begin{align*}\nf(x) = e^{-5t} \\, \\sin(\\frac {4 \\pi }{t})\n\\end{align*}\n\n\n```python\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\nt = np.arange(0.0, 1.01, 0.01)\ns = np.sin(2*2*np.pi*t)\n\nplt.fill(t, s*np.exp(-5*t), 'r')\nplt.grid(True)\nplt.show()\n```\n\n\n```python\ndef f(x):\n return 120.0*(x+0.5)*(x+0.25)*x*(x-1.0/3.0)*(x-0.2)*(x-1.0)\n\nx = np.linspace(-0.5, 0.5, 101)\ny = f(x)\nplt.plot(x, y)\nplt.grid()\nplt.show()\n```\n\n\n```python\ndef horner(a, x):\n n = len(a)\n p = a[-1]\n for k in range(n-2, -1, -1):\n p = a[k] + p * x\n return p\n\na = np.array([5.0, -1.0, 3.0], dtype=float)\nx = np.array([-2, -1, 0, 1, 2], dtype=float)\nprint(a)\nprint(horner(a, 1.0))\nprint(horner(a, 2.0))\nprint(horner(a, x))\n```\n\n [ 5. -1. 3.]\n 7.0\n 15.0\n [ 19. 9. 5. 7. 15.]\n\n\n\n```python\ndef f(x):\n return 0.2+25*x-200*x**2+675*x**3-900*x**4+400.0*x**5\n\nx = np.linspace(0, 0.8, 201)\ny = f(x)\nplt.plot(x, y)\nplt.grid()\nxx = np.linspace(0, 0.8, 5)\nyy = f(xx)\nplt.plot(xx, yy, 'b')\nplt.fill(xx, yy, 'c')\nplt.stem(xx, yy, 'b')\nplt.show()\n```\n\n\n```python\ndef f(x):\n return np.exp(-x**2)\n\nx = np.linspace(0, 1, 11)\ny = f(x)\nplt.plot(x, y)\nplt.grid()\nplt.show()\nprint(trap1(x, y))\nprint(simp1(x, y))\n```\n\n\n```python\ndef gauss_legendre(f, a, b, n=2, debug=False):\n if n == 1:\n t = np.array([0.0])\n A = np.array([2.0])\n elif n == 2:\n t1 = np.sqrt(1.0/3.0)\n t = np.array([-t1, t1])\n A = np.array([1.0, 1.0])\n elif n == 3:\n t1 = np.sqrt(3.0/5.0)\n A1 = 5.0 / 9.0\n A2 = 8.0 / 9.0\n t = np.array([-t1, 0.0, t1])\n A = np.array([A1, A2, A1])\n elif n == 4:\n t1 = np.sqrt(3.0/7 - 2.0/7*np.sqrt(6.0/5))\n t2 = np.sqrt(3.0/7 + 2.0/7*np.sqrt(6.0/5))\n A1 = (18.0 + np.sqrt(30.0)) / 36.0\n A2 = (18.0 - np.sqrt(30.0)) / 36.0\n t = np.array([-t2, -t1, t1, t2])\n A = np.array([A2, A1, A1, A2])\n else:\n t1 = (np.sqrt(5.0 - 2.0 * np.sqrt(10.0/7))) / 3.0\n t2 = (np.sqrt(5.0 + 2.0 * np.sqrt(10.0/7))) / 3.0\n A1 = (322.0 + 13 * np.sqrt(70.0)) / 900.0\n A2 = (322.0 - 13 * np.sqrt(70.0)) / 900.0\n A3 = 128.0 / 225.0\n t = np.array([-t2, -t1, 0.0, t1, t2])\n A = np.array([A2, A1, A3, A1, A2])\n\n c1 = (b - a) / 2.0\n c2 = (b + a) / 2.0\n x = c1 * t + c2\n y = f(x)\n\n if debug:\n for tt, xx, yy, AA in zip(t, x, y, A):\n print(\"%12.6f %12.6f %12.6f %12.6f %12.6f\" % (tt, xx, yy, AA, AA*yy))\n\n return c1 * sum(y*A)\n\nfrom scipy.special import erf\n\nprint('Correct answer =', np.sqrt(np.pi) * erf(1.0) / 2.0)\n\nfor n in [1, 2, 3, 4, 5]:\n I = gauss_legendre(f, 0, 1, n)\n print('n =', n, 'I =', I)\n```\n\n Correct answer = 0.746824132812\n n = 1 I = 0.778800783071\n n = 2 I = 0.746594688283\n n = 3 I = 0.746814584191\n n = 4 I = 0.746824468131\n n = 5 I = 0.746824126766\n\n\n\n```python\ndef f(x):\n return (np.sin(x) / x)**2\n\nprint('Exact I =', 1.41815)\nfor n in [2, 3, 4, 5]:\n print('n =', n, 'I =', gauss_legendre(f, 0, np.pi, n))\n```\n\n Exact I = 1.41815\n n = 2 I = 1.45031180528\n n = 3 I = 1.41618742467\n n = 4 I = 1.4182150179\n n = 5 I = 1.4181502678\n\n\n\n```python\ndef f(x):\n return np.log(x) / (x**2 - 2.0*x + 2.0)\n\nfor n in [2, 3, 4, 5]:\n print('n =', n, 'I =', gauss_legendre(f, 1, np.pi, n))\n```\n\n n = 2 I = 0.606725022862\n n = 3 I = 0.581686953277\n n = 4 I = 0.584768036213\n n = 5 I = 0.58500930387\n\n\n\n```python\ndef f(x):\n return np.sin(x) * np.log(x)\n\nfor n in [2, 3, 4, 5]:\n print('n =', n, 'I =', gauss_legendre(f, 0, np.pi, n))\n```\n\n n = 2 I = 0.481728993916\n n = 3 I = 0.626557170805\n n = 4 I = 0.634859692783\n n = 5 I = 0.638388665011\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "5118f6ebbf28f7c1c5a5f9bcf6fe7879746870d9", "size": 94130, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "bvbcet/Num_Meth_Numerical_Integration.ipynb", "max_stars_repo_name": "satish-annigeri/Notebooks", "max_stars_repo_head_hexsha": "92a7dc1d4cf4aebf73bba159d735a2e912fc88bb", "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": "bvbcet/Num_Meth_Numerical_Integration.ipynb", "max_issues_repo_name": "satish-annigeri/Notebooks", "max_issues_repo_head_hexsha": "92a7dc1d4cf4aebf73bba159d735a2e912fc88bb", "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": "bvbcet/Num_Meth_Numerical_Integration.ipynb", "max_forks_repo_name": "satish-annigeri/Notebooks", "max_forks_repo_head_hexsha": "92a7dc1d4cf4aebf73bba159d735a2e912fc88bb", "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": 116.3535228677, "max_line_length": 23336, "alphanum_fraction": 0.8230107298, "converted": true, "num_tokens": 6627, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361676202372, "lm_q2_score": 0.9591542845278916, "lm_q1q2_score": 0.87516705953116}} {"text": "# Lab Assignment 1\n\n\n\n### Sam Dauncey, s2028017\n\n## Task 1\n\nUse `SymPy` to solve the differential equation $y' = -y^2\\sin(x)$, with $y(0)=1$, and plot the solution.\n\n\n```python\nfrom sympy import *\ninit_printing()\nfrom IPython.display import display_latex\n\n# Define our symbols for sympy to work with.\nx = symbols(\"x\")\ny = Function(\"y\")\ny_prime = y(x).diff(x)\n\n# Define the differential equation and print it into the console.\ndiff_eq = Eq(y_prime,\n -(y(x)**2)*sin(x))\n\nprint(\"Equation:\")\ndisplay_latex(diff_eq)\n\n# Solve it and print the solution into the console.\nsol = dsolve(diff_eq, ics={y(0):1})\n\nprint(\"Has solution (for y(0) = 1):\")\ndisplay_latex(sol)\n\n# Plot the solution\nplotting.plot(sol.rhs, (x,0,2), xlabel = 'x', ylabel = 'y')\n```\n\n## Task 2\n\nUse `SciPy`'s `odeint` function to solve the system of equations\n\n$$ \\begin{align*}\\frac{dx}{dt} &= y \\\\ \\frac{dy}{dt}&=x-x^3\\end{align*} $$\n\nProduce a plot of the solutions for $0\\leq t\\leq 10$ with initial conditions $x(0)=0$ and $y(0)\\in\\{0, 0.5, 1, \\ldots, 3\\}$.\n\nHow many curves do you expect to see plotted? How many do you actually see, and why is this?\n\n\n```python\n# Imports for numerical integration and plotting\nfrom scipy.integrate import odeint\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# Setup a figure and axes\nfig, ax = plt.subplots(figsize=(18, 10))\n\n\n#\ndef dX_dt(X, t):\n x, y = X\n return (y, x - x**3)\n\n\nt_range = np.linspace(0, 10, 1000)\n\nfor i in range(7):\n y_0 = i/2\n X = odeint(dX_dt, (0, y_0), t_range)\n ax.plot(*X.T, label=f\"$y_0 =$ {y_0}\")\n \nax.legend()\n```\n\n\nWe don't see the solution plotted for $(x_0, y_0) = (0, 0)$. This is because at this point both $\\frac{dx}{dt}$ and $\\frac{dy}{dt}$ are $0$; so the $x$ and $y$ values of our solution won't change as time progresses.\n\nNote that our differential equation gives the level curves to:\n\n$$ F(x, y) = \\frac{1}{4}(2 y^2 + x^4 - 2x^2) $$\n\nHence why our plot looks like a contour plot (because it is).\n\n\n```python\n\n```\n", "meta": {"hexsha": "ad1f2a5494a5158fdc26cb3f8f6d8d0405228172", "size": 136979, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": ".ipynb_checkpoints/Lab 1 assignment-checkpoint.ipynb", "max_stars_repo_name": "SamD770/hons-diff-eqs-notebooks", "max_stars_repo_head_hexsha": "48503988b75f113760b67979713c8dcf5f143fa4", "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": ".ipynb_checkpoints/Lab 1 assignment-checkpoint.ipynb", "max_issues_repo_name": "SamD770/hons-diff-eqs-notebooks", "max_issues_repo_head_hexsha": "48503988b75f113760b67979713c8dcf5f143fa4", "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": ".ipynb_checkpoints/Lab 1 assignment-checkpoint.ipynb", "max_forks_repo_name": "SamD770/hons-diff-eqs-notebooks", "max_forks_repo_head_hexsha": "48503988b75f113760b67979713c8dcf5f143fa4", "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": 603.4317180617, "max_line_length": 116160, "alphanum_fraction": 0.9460501245, "converted": true, "num_tokens": 655, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012701768145, "lm_q2_score": 0.9252299601846025, "lm_q1q2_score": 0.8750836715482405}} {"text": "```python\nimport numpy as np\nfrom sympy import preview\n\nscalar = 3\nprint(f'Scalar Value:\\n{scalar}\\n')\n\nvector = np.array([1,2,3,4,5], dtype=np.int)\nprint(f'Vector Value:\\n{vector}\\n')\n\nmatrix = np.array([\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n [17, 18, 19, 20],\n])\nprint(f'Matrix Value:\\n{matrix}\\n')\n\ntensor = np.array([\n np.array(list(range(1, 21))).reshape((5,4)), \n np.array(list(range(21, 41))).reshape((5,4)),\n np.array(list(range(41, 61))).reshape((5,4)),\n ])\n\n [[[ 1 2 3 4]\n [ 5 6 7 8]\n [ 9 10 11 12]\n [13 14 15 16]\n [17 18 19 20]]\n\n [[21 22 23 24]\n [25 26 27 28]\n [29 30 31 32]\n [33 34 35 36]\n [37 38 39 40]]\n\n [[41 42 43 44]\n [45 46 47 48]\n [49 50 51 52]\n [53 54 55 56]\n [57 58 59 60]]]\nprint(f'Matrix Value:\\n{tensor}\\n')\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "bb963e441c5579df1a04328f847614114cf514b6", "size": 2451, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "tensor.ipynb", "max_stars_repo_name": "mrhajbabaei/linear-algebra-learning-path", "max_stars_repo_head_hexsha": "bba380a15823b4ce9572469c867698ea40120b35", "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": "tensor.ipynb", "max_issues_repo_name": "mrhajbabaei/linear-algebra-learning-path", "max_issues_repo_head_hexsha": "bba380a15823b4ce9572469c867698ea40120b35", "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": "tensor.ipynb", "max_forks_repo_name": "mrhajbabaei/linear-algebra-learning-path", "max_forks_repo_head_hexsha": "bba380a15823b4ce9572469c867698ea40120b35", "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": 25.53125, "max_line_length": 267, "alphanum_fraction": 0.4863321093, "converted": true, "num_tokens": 382, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.970239907775086, "lm_q2_score": 0.9019206837793828, "lm_q1q2_score": 0.8750794410505509}} {"text": "# Lab 4\n## Introduction\nThe Euler method is a method for numerically solving a DE of the form\n\\begin{align}\n\\frac{\\mathrm{d}y}{\\mathrm{d}x} = f(x,y).\n\\end{align}\n\nIt is often necessary to solve DEs this way as analytical solutions are the exception\nrather than the rule.\n\n\n\nEuler’s method works by approximating small segments of the curve solution to the DE\nwith the straight-line tangent or slope of the curve. As long as we keep the segments\nsmall enough, they will approximately match what the actual curve looks like. It requires us to ”know” an initial value $y(x_0) = y_0$ so we can start the calculation.\n\nTo calculate the first segment we start off with our known start point $(x_0, y_0)$, and calculate the end point, $(x_1, y_1)$. We can define $\\Delta x$ to be some constant small distance so that we always increment the $x$ value by the same amount. Then, $\\Delta y = m \\Delta x$ and $(x_1, y_1)=(x_0, y_0)+(\\Delta x, m\\Delta x)$.\n\n\n\nBut, we also know that $m$, the slope of the line, is given by $\\mathrm{d}y/\\mathrm{d}x$, i.e., $f(x, y)$ evaluated at $(x_0, y_0)$. So actually, $\\Delta y = f(x_0, y_0) \\Delta x$.\n\nThe final step is to calculate the new point: the point at the end of the first line segment. This point is then given by $(x_1, y_1) = (x_0 + \\Delta x, y_0 + f(x_0, y_0) \\Delta x)$.\n\nWe then do it again to calculate $(x_2, y_2)$ using $(x_1, y_1)$ as our starting point. We then do it again to calculate $(x_3, y_3)$ using $(x_2, y_2)$ as our starting point and so on.\n\n**Summary:** The Euler method for evaluating a DE of the form\n\\begin{align}\n\\frac{\\mathrm{d}y}{\\mathrm{d}x} = f(x,y).\n\\end{align}\ninvolves the iterative calculation of\n\\begin{align}\nx_{n+1} &= x_n + \\Delta x\\\\\n\\text{and}\\quad y_{n+1} &= y_n + f(x_n,y_n)\\Delta x.\n\\end{align}\n\n### Implementation\n\nFirst import the necessary functions from NumPy and SciPy and set up Plotly.\n\n\n```python\nfrom numpy import arange, empty, exp\nfrom plotly import graph_objs as go\n```\n\nNow let's write a function that implements Euler's method. We will model it on `scipy.integrate.odeint`. We will make slight changes to the parameters because we want to input $\\Delta x$. Note that the string (delimited by triple quotes) immediately after the function definition is a _docstring_. It tells us what the function does and is good programming practice. The prodigious comments in the function body are not generally necessary but are included for you.\n\n\n```python\ndef euler(func, y0, x0, xn, Dx):\n \"\"\"\n Integrate an ordinary differential equation using Euler's method.\n \n Solves the initial value problem for systems of first order ode-s::\n dy/dx = func(y, x).\n \n Parameters\n ----------\n func : callable(y, x)\n Computes the derivative of y at x.\n y0 : float\n Initial condition on y.\n x0 : float\n Initial condition on x.\n xn : float\n Upper limit to value of x.\n Dx : float\n x increment.\n \n Returns\n -------\n x : float\n Array containing the value of x for each value of x0 + n * Dx,\n where n ranges from zero to floor( (xn - x0) / Dx ).\n y : float\n Array containing the value of y for each value of x.\n \"\"\"\n x = arange(x0, xn, Dx) # Create the x array\n y = empty(len(x)) # Create an empty y array of the same length as x\n y[0] = y0 # Set the first value of y to y0\n for n in range(len(x) - 1): # Loop to populate the rest of the values of y\n y[n+1] = y[n] + func(y[n], x[n]) * Dx # Euler's method\n \n return x, y # Return x and y as a pair\n```\n\nFirst try solving\n\\begin{align}\n\\frac{\\mathrm{d}y}{\\mathrm{d}x} = y.\n\\end{align}\nfor $y(0)=1$ for $x$ between 1 and 5 and using $\\Delta x=1$.\n\n\n```python\ndef diff_eq(y, x):\n return y\n\nx, y = euler(diff_eq, 1, 0, 5.01, 1)\n```\n\nWhy was `xn` set to 5.01 rather than 5?\n\nWe know that the analytic solution to the above IVP is $y=\\mathrm{e}^x$, so calculate that as well.\n\n\n```python\nx_analytic = arange(0, 5.01, 0.1)\ny_analytic = exp(x_analytic)\n```\n\nNow plot them both for comparison.\n\n\n```python\ny_analytic\n```\n\n\n\n\n array([ 1. , 1.10517092, 1.22140276, 1.34985881,\n 1.4918247 , 1.64872127, 1.8221188 , 2.01375271,\n 2.22554093, 2.45960311, 2.71828183, 3.00416602,\n 3.32011692, 3.66929667, 4.05519997, 4.48168907,\n 4.95303242, 5.47394739, 6.04964746, 6.68589444,\n 7.3890561 , 8.16616991, 9.0250135 , 9.97418245,\n 11.02317638, 12.18249396, 13.46373804, 14.87973172,\n 16.44464677, 18.17414537, 20.08553692, 22.19795128,\n 24.5325302 , 27.11263892, 29.96410005, 33.11545196,\n 36.59823444, 40.44730436, 44.70118449, 49.40244911,\n 54.59815003, 60.3402876 , 66.68633104, 73.6997937 ,\n 81.45086866, 90.0171313 , 99.48431564, 109.94717245,\n 121.51041752, 134.28977968, 148.4131591 ])\n\n\n\n\n```python\nfig = go.Figure()\nfig.add_trace(go.Scatter(x=x, y=y,\n name='Euler'))\nfig.add_trace(go.Scatter(x=x_analytic,\n y=y_analytic,\n name='Truth'))\nfig.show('png')\n```\n\nReproduce the comparison plot below but with $\\Delta x=0.1$.\n\n\n```python\nx, y = euler(diff_eq, 1, 0, 5.01, 0.1)\n\nfig = go.Figure()\nfig.add_trace(go.Scatter(x=x, y=y,\n name='Euler'))\nfig.add_trace(go.Scatter(x=x_analytic,\n y=y_analytic,\n name='Truth'))\nfig.show('png')\n```\n\n\nIt is possible to quantify the error in the Euler solution compared to the analytic solution. To do this you need to re-calculate the analytic solution at the same $x$ points as you calculated your Euler solution. Then you can do a Mean Squared Error (MSE) comparison between the two.\n\n\n```python\nx, y = euler(diff_eq, 1, 0, 5.01, 1)\ny_analytic = exp(x)\n((y_analytic - y)**2).mean()\n```\n\n\n\n\n 2533.317105161909\n\n\n\nNote that `((y_analytic - y)**2)` returned an `array` object, and then we called the `mean` method that was _bound_ to that object.\n\nWhat is the MSE if $\\Delta x = 0.1$?\n\n\n```python\nx, y = euler(diff_eq, 1, 0, 5.01, 0.1)\ny_analytic = exp(x)\n((y_analytic - y)**2).mean()\n```\n\n\n\n\n 88.60637343780924\n\n\n\n## Exercises\n\nIn this lab you will try Euler's method for a couple of differential equations.\n\n1. a. Consider the IVP\n\\begin{align}\n\\frac{\\mathrm{d}y}{\\mathrm{d}x} = 2x\\quad\\text{where}\\quad y(-2)=4.\n\\end{align}\nCalculate the Euler approximation on the interval $x=[-2,2]$ using a step size of $\\Delta x = 0.5$. On the same figure, plot your approximation and the analytic solution.\n\n\n```python\ndef diff_eq(y, x): \n return 2*x \n\nx, y = euler(diff_eq, 4, -2, 2.01, 0.5) \nx_analytic = arange (-2, 2.01, 0.5) \ny_analytic - x_analytic**2 \nfig = go.Figure() \nfig.add_trace(go.Scatter(x=x, y=y, \n name='euler')) \nfig.add_trace(go.Scatter(x=x_analytic, \n y=y_analytic, \n name='truth'))\nfig.show('png')\n```\n\n1. b. Calculate the mean squared error (MSE) of the approximation.\n\n\n```python\nx, y = euler(diff_eq, 4, -2, 2.01, 0.5)\ny_analytic = exp(x)\n((y_analytic - y)**2).mean()\n```\n\n\n\n\n 18842.214252135294\n\n\n\n1. c. Reproduce your plot from 1a except with $\\Delta x=0.1$.\n\n\n```python\nx, y = euler(diff_eq, 4, -2, 2.01, 0.1)\ny_analytic = exp(x)\n((y_analytic - y)**2).mean()\n```\n\n\n\n\n 17085.888972071974\n\n\n\n1. d. Recalculate the MSE.\n\n\n```python\nx, y = euler(diff_eq, 4, -2, 2.01, 0.5)\ny_analytic = exp(x)\n((y_analytic - y)**2).mean()\n```\n\n\n\n\n 18842.214252135294\n\n\n\n2. a. The following is the DE for the arrow problem from class.\n\\begin{align}\n\\frac{\\mathrm{d}y}{\\mathrm{d}t} = 294\\mathrm{e}^{-0.04t}-245\\quad\\text{where}\\quad y(0)=0\n\\end{align}\nCalculate the Euler approximation to the solution on the interval $t=[0,10]$ with $\\Delta t=0.5$. Plot your approximation and the analytic solution on the same figure.\n\n\n```python\nfrom scipy.integrate import odeint\n\ndef diff_eq(y, x):\n return 294*exp(-0.04*x) - 245\n\nx, y = euler(diff_eq, 0, 0, 10.01, 0.5)\n\nx_analytic = arange(0, 10.01, 0.1)\ny_analytic = odeint(diff_eq, 0, x_analytic).flatten()\n\nfig = go.Figure()\nfig.add_trace(go.Scatter(x=x, y=y,\nname='Euler'))\nfig.add_trace(go.Scatter(x=x_analytic,\ny=y_analytic,\nname='Truth'))\nfig.show('png')\n```\n\n2. b. Calculate the MSE of the approximation.\n\n\n```python\nx, y = euler(diff_eq, 0, 0, 10.01, 0.5)\ny_analytic = (-7350*exp(-0.04*x)) - 245*x + 7350\n((y_analytic - y)**2).mean()\n```\n\n\n\n\n 221.1226824539981\n\n\n\n2. c. Reproduce your plot from 2a except with $\\Delta t=0.1$.\n\n\n```python\nx, y = euler(diff_eq, 0, 0, 10.01, 0.1)\ny_analytic = (-7350*exp(-0.04*x)) - 245*x + 7350\n((y_analytic - y)**2).mean()\n```\n\n\n\n\n 8.673112166785117\n\n\n\n2. d. Recalculate the MSE.\n\n\n```python\nx, y = euler(diff_eq, 1, 0, 5.01, 0.1)\ny_analytic = 7350*exp(-0.)\n((y_analytic - y)**2).mean()\n```\n", "meta": {"hexsha": "a4d156bba63d0f054d366647975f97a9f7d22b0d", "size": 177573, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/lab-04.ipynb", "max_stars_repo_name": "liamgoldsworthy/mm-labs", "max_stars_repo_head_hexsha": "0019a5cdbb8c208925808d26fcceaba7d366e994", "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": "notebooks/lab-04.ipynb", "max_issues_repo_name": "liamgoldsworthy/mm-labs", "max_issues_repo_head_hexsha": "0019a5cdbb8c208925808d26fcceaba7d366e994", "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": "notebooks/lab-04.ipynb", "max_forks_repo_name": "liamgoldsworthy/mm-labs", "max_forks_repo_head_hexsha": "0019a5cdbb8c208925808d26fcceaba7d366e994", "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": 245.2665745856, "max_line_length": 44321, "alphanum_fraction": 0.9209113998, "converted": true, "num_tokens": 3009, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088045171237, "lm_q2_score": 0.9425067220070753, "lm_q1q2_score": 0.8750315390279418}} {"text": "**Laboratorio de métodos computacionales**\n\n**Universidad de los Andes**\n\n**Profesor: Diego Alberto Castro Rodríguez**\n\n\n```python\nimport numpy as np\n#!pip3 install sympy\nimport sympy as sp\n```\n\n## Método del rectángulo\n\n\n\n$$\\int_a^b f(x) \\, dx\\approx \nh\\sum_{j=0}^{n-1}f(x_j)\n$$\n\n* $n$ es el número de rectángulos. \n* $h$ es el tamaño de cada partición: $(b-a)/n$. \n* $x_j=a+jh$. \n* Un nodo será cada punto donde se evalue la función (ver código a continuación).\n\n\n```python\nx_ini = 0\nx_fin = 10\nnodos = 11\n\ndef f(x):\n return x**2\n\ndef rect_left_integrate(f, x_ini, x_fin, nodos):\n x, h = np.linspace(x_ini, x_fin, num=nodos-1, retstep=True, endpoint=False)\n return h*np.sum(f(x))\n\n\nrect_left_integrate(f, x_ini, x_fin, nodos)\n\n```\n\n\n\n\n 285.0\n\n\n\n## Método del rectángulo centrado\n\n\n\n$$\\int_a^b f(x) \\, dx\\approx \nh\\sum_{j=0}^{n-1}f\\left( \\frac{x_j+x_{j+1}}{2} \\right)\n$$\n\n\n```python\ndef rect_center_integrate(f, x_ini, x_fin, nodos):\n x, h = np.linspace(x_ini, x_fin, num=nodos-1, retstep=True, endpoint=False)\n x = x + 0.5*h\n return h*np.sum(f(x))\n\nrect_center_integrate(f, x_ini, x_fin, nodos)\n```\n\n\n\n\n 332.5\n\n\n\n## Método del trapecio\n\n\n\n$$\\int_a^b f(x) \\, dx\\approx \n\\frac{h}{2}\\left(f(x_0)+f(x_n)\\right)+h\\sum_{j=1}^{n-1}f(x_j)\n$$\n\n\n```python\ndef trap_integrate(f, x_ini, x_fin, nodos):\n x, h = np.linspace(x_ini, x_fin, num=nodos, retstep=True)\n return 0.5*h*(f(x[0]) + f(x[-1])) + h*np.sum(f(x[1:-1]))\n\ntrap_integrate(f, x_ini, x_fin, nodos)\n```\n\n\n\n\n 335.0\n\n\n\n## Método de Simpson 1/3 compuesta!\n\n\n\n$$\\int_a^b f(x) \\, dx\\approx \n\\frac{h}{3}\\bigg[f(x_0)+2\\sum_{j=1}^{n/2-1}f(x_{2j})+\n4\\sum_{j=1}^{n/2}f(x_{2j-1})+f(x_n)\n\\bigg]$$\n\nSe exije que $n$ sea par.\n\n\n```python\ndef simpson_integrate_f(f, x_ini, x_fin, nodos):\n x, h = np.linspace(x_ini, x_fin, num = nodos, retstep=True)\n return (f(x[0]) + 2*np.sum(f(x[2:-1:2])) + 4*np.sum(f(x[1:len(x):2])) + f(x[-1]))*h/3\n\nsimpson_integrate_f(f, x_ini, x_fin, nodos)\n```\n\n\n\n\n 333.3333333333333\n\n\n\n## Cuadratura de Gauss-Legendre\n\n\n\n$$\\int_{-1}^1 f(x)\\,dx \\approx \\sum_{i=1}^n w_i f(x_i)$$\n\n\n```python\nX = np.array([-np.sqrt(1/3), np.sqrt(1/3)])\nW = np.array([1, 1])\n\ndef gauss_legendre_integrate(f,X,W):\n return np.sum(W*f(X))\n\ngauss_legendre_integrate(f,X,W)\n\n```\n\n\n\n\n 0.6666666666666666\n\n\n\n## Cuadratura de Gauss-Legendre para intervalo arbitrario\n\nEl cambio de variable \n\n$$x = \\frac{b-a}{2}\\xi + \\frac{a+b}{2}\\,\\,\\,\\,\\,\\,\\,\\,\\,\\,\\rightarrow \\,\\,\\,\\,\\,\\,\\,\\,\\,\\, dx = \\frac{b-a}{2}d\\xi$$\npermite cambiar los limites de integración:\n\n\n$$\\int_a^b f(x)\\,dx = \\frac{b-a}{2} \\int_{-1}^1 f\\left(\\frac{b-a}{2}\\xi + \\frac{a+b}{2}\\right)\\,d\\xi.$$\n\nPara el caso discreto resulta\n\n$$\\int_a^b f(x)\\,dx \\approx \\frac{b-a}{2} \\sum_{i=1}^m w_i f\\left(\\frac{b-a}{2}\\xi_i + \\frac{a+b}{2}\\right)$$\n\n$m$ es el grado del método de cuadratura de Gauss\n\n\n\n```python\ndef gauss_legendre_integrate_ab(f,X,W,a,b):\n c1 = 0.5*(b-a)\n c2 = 0.5*(a+b)\n return c1*np.sum(W*f(c1*X + c2))\n\ngauss_legendre_integrate_ab(f,X,W,x_ini,x_fin)\n```\n\n\n\n\n 333.33333333333337\n\n\n\n\n```python\nX, W = np.polynomial.legendre.leggauss(2)\n\ngauss_legendre_integrate_ab(f,X,W,x_ini, x_fin)\n```\n\n\n\n\n 333.33333333333337\n\n\n\n## Cuadratura de Gauss-Legendre compuesta\n\n$$\\int_a^b f(x)\\,dx \\approx \\sum_{j = 0}^{n-1}\\left[\\frac{x_{j+1}-x_j}{2} \\sum_{i=1}^m w_i f\\left(\\frac{x_{j+1}-x_j}{2}\\xi_i + \\frac{x_{j}+x_{j+1}}{2}\\right)\\right]$$\n\n\n\n\n```python\ndef gauss_legendre_integrate_trosos(func, x_ini, x_fin,X, W):\n limits, h = np.linspace(x_ini, x_fin, num=nodos-1, retstep=True, endpoint=False)\n suma = 0\n for limit in limits: \n suma += gauss_legendre_integrate_ab(func, X, W, limit, limit + h)\n return suma\n\ngauss_legendre_integrate_trosos(f, x_ini, x_fin, X, W)\n```\n\n\n\n\n 333.33333333333337\n\n\n", "meta": {"hexsha": "fc89e3242a1ea73b7b99634afa90283edbcd6d28", "size": 86121, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Notebooks/04_integracion_numerica.ipynb", "max_stars_repo_name": "JohanGB/CompMetodosComputacionales", "max_stars_repo_head_hexsha": "096c215fc33387e785f7cb13859c4c0d035071ca", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-09-28T01:27:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-28T01:27:44.000Z", "max_issues_repo_path": "Notebooks/04_integracion_numerica.ipynb", "max_issues_repo_name": "JohanGB/CompMetodosComputacionales", "max_issues_repo_head_hexsha": "096c215fc33387e785f7cb13859c4c0d035071ca", "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_integracion_numerica.ipynb", "max_forks_repo_name": "JohanGB/CompMetodosComputacionales", "max_forks_repo_head_hexsha": "096c215fc33387e785f7cb13859c4c0d035071ca", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2021-08-13T11:48:44.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-14T18:27:13.000Z", "avg_line_length": 189.6938325991, "max_line_length": 23332, "alphanum_fraction": 0.9053192601, "converted": true, "num_tokens": 1476, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741241296944, "lm_q2_score": 0.918480237330998, "lm_q1q2_score": 0.8749205076060094}} {"text": "### Sum of Poisson Random Variables\n\nThe poisson distribution gives the probability of observing $k$ events within $\\lambda = ct$ time.\n\n\n#### The long way\n\n\\begin{equation}\np(k) = \\frac{\\lambda^k e^{-\\lambda}}{k!}\n\\end{equation}\n\nThe sum of a set of $n$ poisson random variables has probability:\n\n\\begin{equation}\n\\begin{array}{ll}\np(s) &= \\sum_{\\sum k_i = s} \\frac{\\lambda^{k_1}...\\lambda^{k_n} e^{-n\\lambda}}{k_1!...k_n!}\\\\\n&= \\frac{e^{-n\\lambda}}{s!} \\sum_{\\sum k_i = s} \\left(\\begin{array}{c} s \\\\ k_1...k_n\\end{array}\\right)\\lambda^{k_1}...\\lambda^{k_n}\\\\\n&= \\frac{(n\\lambda)^s e^{-n\\lambda}}{s!}\n\\end{array}\n\\end{equation}\n\nWhere the second step made use of the multinomial expansion.\n\n#### The quick way, using moment generating functions\n\nFor a linear combination of independent random variables $y=\\sum a_i X_i$, the moment generating function is given by: \n\n\\begin{equation}\nM_y(t) = \\prod_i M_i(t) = \\prod_i \\left< e^{X_it} \\right>\n\\end{equation}\n\nIn this case, then:\n\n\\begin{equation}\nM_y(t) = \\prod_i \\exp\\left(\\lambda_i (e^t -1) \\right) = \\exp\\left(n\\lambda(e^t-1)\\right)\n\\end{equation}\n\nWhich is the moment generating function of a poisson random variable with parameter $n\\lambda$.\n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\nn = 5\nsamples = 5000\n\nlam = 1\n\nX = np.random.poisson(lam=lam,size=[n,samples])\nY = np.sum(X,axis=0)\n\ndef factorial(x):\n if x == 0:\n return 1\n else:\n res = 1\n for i in range(1,x+1):\n res *= i\n return res\n\ndef p_x(x,lam=lam):\n return lam**x * np.exp(-lam) / factorial(x)\n\ndef p_s(x,n,lam=lam):\n return p_x(x,lam=n*lam)\n```\n\n\n```python\nx = list(range(15))\n_ = plt.hist(X.flatten(),bins = x,density=True)\n_ = plt.hist(Y,bins=x,density=True)\n\nplt.plot(x,[p_x(i) for i in x])\nplt.plot(x,[p_s(i,n) for i in x])\n```\n", "meta": {"hexsha": "f012ec4b7d3cf4780dbe8c3edaf3836dc6cd9d07", "size": 19653, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Probability - Sum of Poisson Variables.ipynb", "max_stars_repo_name": "jpbm/probabilism", "max_stars_repo_head_hexsha": "a2f5c1595aed616236b2b889195604f365175899", "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": "Probability - Sum of Poisson Variables.ipynb", "max_issues_repo_name": "jpbm/probabilism", "max_issues_repo_head_hexsha": "a2f5c1595aed616236b2b889195604f365175899", "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": "Probability - Sum of Poisson Variables.ipynb", "max_forks_repo_name": "jpbm/probabilism", "max_forks_repo_head_hexsha": "a2f5c1595aed616236b2b889195604f365175899", "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": 139.3829787234, "max_line_length": 16028, "alphanum_fraction": 0.8779830051, "converted": true, "num_tokens": 612, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172630429475, "lm_q2_score": 0.9219218273467447, "lm_q1q2_score": 0.8748275371454258}} {"text": "# Operators\n\nOperators are one or more characters that can be used to perform operations on data. For example the `+` character is used to perform the addition operation between two numbers. \n\n## Arithmetic Operators\n\nArithmetic operators are used to perform mathematical calculations. Here's a list of arithmetic operators that are supported in Python\n\n| Operator | Function | Syntax |\n| -------- | -------------- | ------ |\n| + | Addition | a + b |\n| - | Subtraction | a - b |\n| * | Multiplication | a * b |\n| / | Division | a / b |\n| // | Floor Division | a // b |\n| % | Modulo | a % b |\n| ** | Power | a ** b |\n\n\n```python\na = 10\nb = 4\n\n# Addition\na + b\n```\n\n\n```python\n# Subtraction\na - b\n```\n\n\n```python\n# Multiplication\na * b\n```\n\n\n```python\n# Division\na / b\n```\n\n\n```python\n# Floor Division\na // b\n```\n\n\n```python\n# Modulo\na % b\n```\n\n\n```python\n# Power\na ** b\n```\n\n## String Operators\n\nSome operators work differently on different types of data. For strings, the `+` operator will concatenate two strings together:\n\n\n```python\nline_1 = 'Good night! Good night! ' # <-- Note the space at the end of this string\nline_2 = 'Parting is such sweet sorrow.'\n\n# Concatenate two strings using the + operator\ncombined = line_1 + line_2\ncombined\n```\n\nThe `*` operator can be used to duplicate a string and concatinate the results:\n\n\n```python\nhello = 'Hello! ' * 5\nhello\n```\n\nOther operators won't work on strings, however, because the behavoir is not well defined. What would dividing one string by another produce? Power?\n\n## List Operators\n\nSimilar to strings, the `+` operator can be used to combine two lists:\n\n\n```python\nlist_a = ['A', 'B', 'C']\nlist_b = ['D', 'E', 'F']\n\ncombined = list_a + list_b\ncombined\n```\n\nThe `*` operator can also be used with lists to duplicate the contents of a list many times:\n\n\n```python\nrepeating_pattern = [1, 2, 3] * 3\nrepeating_pattern\n```\n\n# Exercise\n\nThe equation of a line is: \n\n\\begin{equation}\n\\label{eq:sedov}\ny = mx + b\n\\end{equation}\n\nUse the arithmetic operators to calculate y given the following values for m, x, and b.\n\n\n```python\n# Given\nm = 5\nx = 10\nb = 2\n\n# Write your code here\ny = None\n\n# This code checks your code\nif y != 52:\n print(f\"I'm sorry, {y} is not the correct answer!\")\nelse:\n print(f\"{y} is correct!\")\n```\n\nGiven the following equation:\n\n\\begin{equation}\n\\label{eq:sedov}\nc = \\left(a^2 + b^2\\right)^{0.5}\n\\end{equation}\n\n\nWrite the code to calcuate `c` given `a` and `b`\n\n\n```python\n# Given\na = 4\nb = 3\n\n# Write your code here\nc = None\n\n# This code checks your code\nif c != 5.0:\n print(f\"I'm sorry, {c} is not the correct answer!\")\nelse:\n print(f\"{c} is correct!\")\n```\n", "meta": {"hexsha": "b036a6388b87c2d041ebc6bc42bd82ae9249f4b4", "size": 6515, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "05 - Operators.ipynb", "max_stars_repo_name": "Aquaveo/python_basics", "max_stars_repo_head_hexsha": "c0aef8332f88fa797aa1196c0fac678c3e2faf5a", "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": "05 - Operators.ipynb", "max_issues_repo_name": "Aquaveo/python_basics", "max_issues_repo_head_hexsha": "c0aef8332f88fa797aa1196c0fac678c3e2faf5a", "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": "05 - Operators.ipynb", "max_forks_repo_name": "Aquaveo/python_basics", "max_forks_repo_head_hexsha": "c0aef8332f88fa797aa1196c0fac678c3e2faf5a", "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": 21.2214983713, "max_line_length": 184, "alphanum_fraction": 0.4834996163, "converted": true, "num_tokens": 790, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966686936262, "lm_q2_score": 0.9241418158002492, "lm_q1q2_score": 0.8747895642369947}} {"text": "# FSETC Workshops: Introduction to Functions in MATLAB\n*Functions* are a way for programmers to generalize some piece of code so that it can be reused. Functions isolate the implementation details and variables used from your main program.\n\n

▶️Press the spacebar to continue

\n\n## Anonymous Functions\n*Anonymous functions* are the simplest possible function. They can only be on one line, and therefore can only be one executable statement. The following creates an anonymous function called `func`, that takes one input called `input`. Read the full documentation [here](https://www.mathworks.com/help/matlab/matlab_prog/anonymous-functions.html).\n\n\n```octave\nfunc = @(input) outputStatement;\n```\n\n### Example\nLet's create a function that does some computation with the $\\sin$ function:\n\n\n```octave\nf = @(x) sin(3*x) + 15;\nf(0)\n```\n\n ans = 15\r\n\n\n### What's the deal with the `.`?\n* MATLAB defaults all operations to matrix operations\n* If we want to square all the elements in a list, use the `dot` to do element-wise operations\n(Visual to show the difference)\n\n\n```octave\nf = @(x) x.^2; %try removing the dot\nf([1, 2, 5])\n```\n\n ans =\n \n 1 4 25\n \n\n\n### Combining Anonymous Functions\n* There are times when we might want to combine multiple anonymous functions\n* The following code is equivalent to \n\n\\begin{align}\n f(t) &= \\sin(t)\\\\\n g(t) &= \\cos(t)\\\\\n h(t) &= f(t)g(t) \\\\\n &= \\sin(t)\\cos(t)\n\\end{align}\n\n\n```octave\nf = @(t) sin(t);\ng = @(t) cos(t);\nh = @(t) f(t) * g(t); %Note that you need to call the function inside the new function.\n```\n\n## Regular Functions\n* The following is the MATLAB syntax for defining a function. You can see the full documentation [here](https://www.mathworks.com/help/matlab/ref/function.html)\n* Variables within a function are limited to the scope of the function\n* You can pass in one function to another function\n\n```octave\nfunction [output] = functionName(input)\n output = %set function output\nend\n```\n\n### Example: Addition\nLet's define a very simple function that adds two input arguments. The function will be called `add`. The function will take two input arguments, `a` and `b`, and will return the result, `c`. Arguments are passed by position.\n\n\n```octave\nfunction [c] = add(a, b)\n c = a + b;\nend\nadd(1, 2)\n```\n\n ans = 3\n\n\n### Example: Summation\nLet's create a function that will sum all of the elements of a vector. The function is:\n$$\n\\sum_{i=1}^N x_i\n$$\n\nwhere $N$ is the number of elements and $x_i$ is the $i$th element of the vector $x$.\n\n\n```octave\nfunction [total] = mySum(items)\n total = 0; % Initialize the summation\n for i = 1:length(items)\n total = total + items(i); % get the ith item; add to the total\n end\nend\nmySum([0, 1, 2, 3])\n```\n\n ans = 6\n\n\n### Multiple Return Values\n* Functions can return more than one piece of data\n* The variable name used when called doesn't matter\n\n\n```octave\nfunction [total, mean] = stats(values)\n total = sum(values);\n mean = total/length(values);\nend\n[out1, out2] = stats([0, 1, 2])\n```\n\n out1 = 3\n out2 = 1\n\n\n## Your turn\n\nCreate a function, `Integrate`, that computes the definite integral with trapezoidal rule from the lower bound, `a`, to an upper bound, `b`, with a spacing, `dx`. See [here](https://en.wikipedia.org/wiki/Trapezoidal_rule) for trapezoidal rule theory.\n\\begin{align}\nI &= \\int_a^b f(x) dx \\\\\n &\\approx \\frac{1}{2} \\Delta x \\left[ f(a) + 2\\sum_{i=1}^{n-2} f(x_i) + f(b) \\right]\n\\end{align}\n\nwhere $x_i = a + i \\Delta x$, $\\Delta x=\\frac{b-a}{n}$, and $i=[1, 2, ..., n-2]$.\n\n\n```octave\nfunction [I] = Integrate(f, a, b, Nsegments)\n % Describe function here\n \nend\n\n% Some code verification\nf = @(x) sin(x);\nIntegrate(f, 0, 1, 10) % our function\nx = 0:0.1:1;\ntrapz(x, f(x)) % built-in function to compare output\n```\n\n ans = 0.45931\n\n\n## Important [Gotchas](https://en.wikipedia.org/wiki/Gotcha_(programming))\n\n* MATLAB functions should be in a separate file and the function name should match the name of the file.\n * [Local functions](https://www.mathworks.com/help/matlab/matlab_prog/local-functions.html) (only available within the current script) can be added to the bottom of script files; no other code can follow it.\n* You can't directly run a MATLAB function, because they require inputs.\n * Always call your function from another file or the command window.\n* Function names cannot have paretheses, spaces, etc. They follow the same rules as variable names.\n\n## More Notebooks\n\n* [Basics](Basics.ipynb)\n* [Functions](Functions.ipynb)\n* [Control Flow](Control%20Flow.ipynb)\n* [Matrix Indexing](Matrix%20Indexing.ipynb)\n* [Plotting](Plotting.ipynb)\n* [Printing](Printing.ipynb)\n* [Building Matricies](Building%20Matricies.ipynb)\n", "meta": {"hexsha": "fde199505233776085a6e4c7360e9bea2c0a8538", "size": 10311, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Functions.ipynb", "max_stars_repo_name": "BrianChevalier/MATLAB101", "max_stars_repo_head_hexsha": "7a8d7ced44c296fe3ae4f90944d96ea14bf453a6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-06T03:42:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-06T03:42:13.000Z", "max_issues_repo_path": "Functions.ipynb", "max_issues_repo_name": "BrianChevalier/MATLAB101", "max_issues_repo_head_hexsha": "7a8d7ced44c296fe3ae4f90944d96ea14bf453a6", "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": "Functions.ipynb", "max_forks_repo_name": "BrianChevalier/MATLAB101", "max_forks_repo_head_hexsha": "7a8d7ced44c296fe3ae4f90944d96ea14bf453a6", "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.55, "max_line_length": 356, "alphanum_fraction": 0.5327320338, "converted": true, "num_tokens": 1367, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582593509315, "lm_q2_score": 0.9399133519298964, "lm_q1q2_score": 0.874550141377391}} {"text": "# Linear Regression\n## Unique variable\n\nWe have a dataset formed by $n$ values of $(x,y)$.\n\n*Problem*\n\nIf we get some $x_{new}$ value could we estimate a correspondent $y_{new}$?\n\n*Hypothesis 1*\n\nWe admit a linear relation between $x$ and $y$, i.e.,\n\\begin{equation}\n\\hat{y} = a x + b\n\\end{equation}\nwhere $a$ is the linear coeficient or slope and $b$ is the independent term.\n\nAs we have any guarantee that our hypothesis holds, it's probable that our estimative $\\hat{y}$ differs from the actual $y$. Therefore we have a potential associated error, which we will call residual $r$:\n\\begin{equation}\nr = y - \\hat{y} = y - (a x + b) = \\sum_i^n r_i \\implies r_i = y_i - ax_i -b_i\n\\end{equation}\n\nOur estimative could be:\n1. above the actual value, i.e., $y < \\hat{y} \\implies y - \\hat{y} = r < 0$\n2. below the actual value, i.e., $y > \\hat{y} \\implies y - \\hat{y} = r > 0$\n3. equal the actual value, i.e., $y = \\hat{y} \\implies y = \\hat{y} = r = 0$\n\nIn order to be able to deal with all these cases, we square this residual:\n\\begin{equation}\nr^2 = (y - \\hat{y})^2 = (y - (a x + b))^2\n\\end{equation}\n\nLet's improve the notation, treating each sample as $i$. And calculate the sum $S$ of the squared residuals:\n\\begin{equation}\nS(a,b) = \\sum_{i=1}^n r_i^2 = \\sum_{i=1}(y_i - \\hat{y}_i)^2 = \\sum_{i=1}(y_i - a x_i - b)^2\n\\end{equation}\nas our $n$ $(x,y)$ variables are known, we have a function of the coeficients $(a,b)$.\n\nIn order to minimize this sum $S$, we will partially derivate this expression towards each variable $a,b$; apply the chain rule and equalize this to zero.\n\\begin{align}\n\\frac{\\partial S}{\\partial a} &\n= \\frac{\\partial S}{\\partial r}\\frac{\\partial r}{\\partial a} = 0\\\\\n\\frac{\\partial S}{\\partial b} & \n= \\frac{\\partial S}{\\partial r}\\frac{\\partial r}{\\partial b} = 0\n\\end{align}\n\nEach term is calculated by means of:\n\\begin{align}\n\\frac{\\partial S}{\\partial r} &\n= \\frac{\\mathrm{d} \\sum_{i=1}^n r_i^2}{\\mathrm{d} r_i} = 2 \\sum_{i=1}^n r_i\n= 2\\sum_{i=1}^n (y_i-ax_i-b)\\\\\n\\frac{\\partial r_i}{\\partial a} &= \\frac{\\partial (y_i-ax_i-b)}{\\partial a} = -x_i\\\\\n\\frac{\\partial r_i}{\\partial b} &= \\frac{\\partial (y_i-ax_i-b)}{\\partial b} = -1\n\\end{align}\n\nWe could replace as:\n\\begin{align}\n\\frac{\\partial S}{\\partial r}\\frac{\\partial r}{\\partial a}\n& = 2\\sum_{i=1}^n(y_i-ax_i-b) (-x_i) = - 2 \\sum_{i=1}^n x_i (y_i-ax_i-b)\n= 0 \\\\\n\\frac{\\partial S}{\\partial r}\\frac{\\partial r}{\\partial b}\n& = 2 \\sum_{i=1}^n (y_i-ax_i-b) (-1) \n= -2 \\sum_{i=1}^n (y_i-ax_i-b)\n= 0\n\\end{align}\n\nIf we evaluate the second expression:\n\\begin{align}\n0 &= \\sum_{i=1}^n (y_i-ax_i-b)\n= \\sum_{i=1}^n y_i - \\sum_{i=1}^n a x_i - \\sum_{i=1}^n b \n\\end{align}\n\nDividing by $n$ samples we get mean values:\n\\begin{align}\n0 = \\frac{\\sum_{i=1}^n y_i}{n} - \\frac{\\sum_{i=1}^n a x_i}{n} - \\frac{\\sum_{i=1}^n b}{n}\n= \\bar{y} - a \\bar{x} - b\n\\implies b = \\bar{y} - a \\bar{x}\n\\end{align}\n\nIf we replace $b$ in the first derivative expression:\n\\begin{align}\n0 &= \\sum_{i=1}^n x_i (y_i-ax_i-b)\n= \\sum_{i=1}^n x_i (y_i-ax_i-(\\bar{y} - a \\bar{x})) \\\\\n& = \\sum_{i=1}^n x_i (y_i - ax_i - \\bar{y} + a \\bar{x})\n= \\sum_{i=1}^n x_i ( y_i - \\bar{y}) - a \\sum_{i=1}^n x_i ( x_i - \\bar{x})\n\\end{align}\n\nIsolating $a$\n\\begin{align}\na = \\frac{\\sum_{i=1}^n x_i ( y_i - \\bar{y})}{\\sum_{i=1}^n x_i ( x_i - \\bar{x})}\n\\end{align}\n\nIn a nutshell, linear regression for one variable consist in admit a linear relation between $x$ and $y$, i.e., $\\hat{y}=a+bx$, where the coeficients are determined by:\n\\begin{align}\na &= \\frac{\\sum_{i=1}^n x_i ( y_i - \\bar{y})}{\\sum_{i=1}^n x_i ( x_i - \\bar{x})}\\\\\nb &= \\bar{y} - a \\bar{x}\n\\end{align}\nwith the sample means:\n\\begin{align}\n\\bar{x} = \\frac{\\sum_{i=1}^n x_i}{n}, \\qquad \\bar{y} &= \\frac{\\sum_{i=1}^n y_i}{n}\n\\end{align}\n\n## Multivariate\n\nHypothesis:\n\nAdmit a linear relation:\n\\begin{equation}\ny = Xb + r\n\\end{equation}\n\nDefine the residual as:\n\\begin{equation}\nr = y - Xb\n\\end{equation}\n\nCompute the squared residual as:\n\\begin{align}\nS(b) &= (y - X b)^T (y - X b)\\\\\n&= ( y^T - (X b)^T ) (y - X b)\\\\\n&= ( y^T - b^T X^T ) (y - X b)\\\\\n&= y^T y - b^T X^T y - y^T X b + b^T X^T X b\n\\end{align}\n\nThe second and third term are equal, like we can see through:\n\\begin{equation}\nb^T X^T y = (X b)^T y = y^T X b = X^T y b\n\\end{equation}\n\nThe last term could be rewritten as:\n\\begin{equation}\nb^T X^T X b = (X^T X b)^T b = X^T X b b^T\n\\end{equation}\n\nIf we calculate the partial derivative and equals the result to zero i.e., (null residual):\n\\begin{align}\n\\frac{\\partial S}{\\partial b} \n& = - 2 X^T y \\frac{\\partial b^T}{\\partial b} \n+ X^T X \\frac{\\partial b^Tb}{\\partial b}\\\\\n&= - 2 X^T y + 2 X^T X b = 0\n\\end{align}\n\nTherefore we get the coefficient vector as:\n\\begin{align}\nX^T y = X^T X b \\implies b = (X^T X)^{-1} X^T y \n\\end{align}\n\nNotice the consistence as we recover our initial hypothesis for the case with a null residual through:\n\\begin{align}\nb = (X^T X)^{-1} X^T y = X^{-1}X^{-T} X^T y = X^{-1} y\n\\end{align}\n\nIn a nutshell\n\\begin{equation}\ny = Xb + r, \\qquad b = (X^T X)^{-1} X^T y\n\\end{equation}\n\nObservation:\nRemember to add the independent variable as $ x^0=1 $:\n\n\\begin{equation}\n\\begin{Bmatrix}\ny_1 \\\\\ny_2 \\\\\n\\vdots \\\\\ny_n\n\\end{Bmatrix}\n=\n\\begin{bmatrix}\n1 & x^{1}_{1} & x^{2}_{1} & \\cdots & x^{m}_{1} \\\\\n1 & x^{1}_{2} & x^{2}_{2} & \\cdots & x^{m}_{2} \\\\\n\\vdots & \\vdots & \\vdots & \\ddots & \\vdots\\\\\n1 & x^{1}_{n} & x^{2}_{n} & \\cdots & x^{m}_{n}\n\\end{bmatrix}\n\\times\n\\begin{Bmatrix}\nb_0 \\\\\nb_1 \\\\\n\\vdots \\\\\nb_m\n\\end{Bmatrix}\n+\n\\begin{Bmatrix}\nr_1 \\\\\nr_2 \\\\\n\\vdots \\\\\nr_n\n\\end{Bmatrix}\n\\end{equation}\n\nHypothesis:\n1. Fixed regressors (X not stochastic)\n2. Aleatory error with null mean\n3. Constant error variance (homoscedasticity)\n4. No error correlation\n5. b constant\n6. Linear model\n7. Error normal distributed\n\n\n## $R^2$\n\n$R^2$ determination coeficient\n* quality of estimative\n* $R^2$ of the $y$ variance explained by the $X$ variance\n\\begin{equation}\nR^2 = 1 - \\frac{SS_{res}}{SS_{tot}}, \\qquad\nSS_{res} = \\sum_{i=1}^n r_i^2, \\qquad\nSS_{tot} = \\sum_{i=1}^n (y_i - \\bar{y})^2\n\\end{equation}\n* $SS_{res}$: squared sum of the residuals $r$\n* $SS_{tot}$: squared sum of the distance of each variable to $y_i$ to average $\\bar{y}$\n\nEstimative and residual\n\\begin{equation}\n\\hat{y} = Xb, \\qquad\nr_i = \\hat{y}_i - y_i\n\\end{equation}\n\n\nEstimator has a normal distribution\n\\begin{equation}\nb\\sim \\mathcal{N}\\left(\\beta,\\sigma^2(X^T X)^{-1}\\right)\n\\end{equation}\n\nSample variance approximation\n\\begin{equation}\ns^2 = \\frac{SS_{res}}{n-(m+1)}\n\\end{equation}\n* $n$: number of samples\n* $m$: number of variables\n* 1: $x_0$\n\nt-Student-statistic\n\\begin{equation}\nt_i = \\frac{b_i}{s\\sqrt{(X^T X)^{-1}_{ii}}}\n\\end{equation}\n\nNull hypothesis ($H_0$)\n* $\\beta_i=0$\n* the coeficients have no influence\n\n\nIf $|t_i| > t(1-\\alpha) \\implies H_0$ could be rejected with at least $(1-\\alpha)$ confidence.\n\nwhere $\\alpha$ is the significance level\n\n\n\n\n## Homemade implementation\n\n\n```\n# Multivariate Linear Regression\n# Author: Vinícius Rios Fuck\n# Date: 20/07/2020\n\n\nimport pandas as pd\nimport numpy as np\nfrom scipy.stats import t\n\n# Sample input\n# Source: https://pt.wikipedia.org/wiki/M%C3%A9todo_dos_m%C3%ADnimos_quadrados\n\nd = {\"i\": [1,2,3,4,5,6,7,8,9,10],\n \"y\": [122,114,86,134,146,107,68,117,71,98],\n \"x1\": [139,126,90,144,163,136,61,62,41,120],\n \"x2\": [0.115,0.120,0.105,0.090,0.100,0.120,0.105,0.080,0.100,0.115]\n}\ndf = pd.DataFrame(data=d)\n\n# Adjust input data\n\n# select the y variable\ny = df['y'].to_numpy()\n# select the X variables\nX = df.iloc[:,2:].to_numpy()\n# add x_0 column of ones (independent coeficient)\nX = np.c_[ np.ones(len(X)), X ]\n```\n\n\n```\ndef LR_predict(x, b):\n y_hat = x @ b\n return y_hat\n\n\ndef squared_sum(x):\n squared_x_sum = np.square(x).sum()\n return squared_x_sum\n\n\ndef residual_f(actual, predict):\n residual = actual - predict\n return residual\n\n\ndef R_2_score(squared_residuals_sum, squared_y_y_bar_distance_sum):\n R_2 = 1 - squared_residuals_sum / squared_y_y_bar_distance_sum\n return R_2\n\n\ndef adjusted_R_2_score(R_2, n, dof):\n adjusted_R_2 = 1 - (n-1)/dof * (1-R_2)\n return adjusted_R_2\n\n\n# Standard Deviation\ndef std_sample(squared_residuals_sum, dof):\n sd_sample = (squared_residuals_sum / dof)**0.5\n return sd_sample\n\n\ndef t_stat(b, sd_sample, XtX_inv):\n t_student_coef = b / (sd_sample * np.diag(XtX_inv)**0.5)\n return t_student_coef\n\ndef significance(confidence=0.975):\n alpha = 1 - confidence\n return alpha\n\n\ndef critical_value_calc(dof, confidence=0.975):\n critical_value = t.ppf(confidence, dof)\n return critical_value\n\n\ndef round_3(input):\n return round(input, 3)\n\n\ndef exp_2(input):\n return '{:.2e}'.format(input)\n\n\ndef print_hypothesis(b, p_value, t_student_coef, critical_value, alpha):\n cv_out = round_3(critical_value)\n alpha_out = round_3(alpha)\n print(\"H0: null hypothesis: the coefficients bi are not relevant\\n\")\n\n accept_H0_critical_value = np.zeros(len(b))\n accept_H0_p_value = np.zeros(len(b))\n\n for i in range(len(b)): # all variables\n t_out = round_3(abs(t_student_coef[i]))\n # interpret via critical value\n accept_H0_critical_value[i] = (abs(t_student_coef[i]) <= critical_value)\n if accept_H0_critical_value[i]:\n print(f'Accept H0 that b{i} is not relevant.')\n print(f't_student = {t_out} <= critical_value = {cv_out}\\n')\n else:\n print(f'Reject H0 that b{i} is not relevant.')\n print(f't_student = {t_out} > critical_value = {cv_out}\\n')\n\n p_out = exp_2(p_value[i])\n # interpret via p-value\n accept_H0_p_value[i] = (p_value[i] > alpha)\n if accept_H0_p_value[i]:\n print(f'Accept H0 that b{i} is not relevant.')\n print(f'p_value = {p_out} > alpha = {alpha_out}\\n')\n else:\n print(f'Reject H0 that b{i} is not relevant.')\n print(f'p_value = {p_out} <= alpha = {alpha_out}\\n')\n\n return accept_H0_critical_value, accept_H0_p_value\n\n```\n\n\n```\n# R^2 (quality of estimative)\ndef R2_SqResidSum(X, y, b):\n # y mean\n y_bar = y.mean()\n # predicted y\n y_hat = LR_predict(X, b=b)\n # residual\n residual = residual_f(y, y_hat)\n # squared residuals sum\n squared_residuals_sum = squared_sum(residual)\n # squared_y_y_bar_distance_sum\n squared_y_y_bar_distance_sum = squared_sum(y - y_bar)\n # R_2\n R_2 = R_2_score(squared_residuals_sum, squared_y_y_bar_distance_sum)\n return R_2, squared_residuals_sum\n```\n\n\n```\n# t-Student stats (statistical relevance)\ndef t_student_stats(XtX_inv, b, squared_residuals_sum, R_2,\n confidence=0.975, n=len(y)):\n # sample size\n # n = len(y)\n # number of variables # already take in account the independent coeficient\n # m = X.shape[1]\n m = len(b)\n # degree of freedom\n dof = n - m\n # adjusted_R_2\n adjusted_R_2 = adjusted_R_2_score(R_2, n, dof)\n # Standard Deviation\n sd_sample = std_sample(squared_residuals_sum, dof)\n # t_student_coef\n t_student_coef = t_stat(b, sd_sample, XtX_inv)\n alpha = significance(confidence)\n critical_value = critical_value_calc(dof, confidence)\n # calculate the p-value\n # 2: two-tailed distribution\n p_value = (1 - t.cdf(abs(t_student_coef), dof)) * 2\n (accept_H0_critical_value,\n accept_H0_p_value) = print_hypothesis(b, p_value, t_student_coef,\n critical_value, alpha)\n\n dict_H0 = {\"t_student\": t_student_coef,\n 'p_value': p_value,\n 'accept_H0_critical_value': accept_H0_critical_value,\n 'accept_H0_p_value': accept_H0_p_value\n }\n df_H0 = pd.DataFrame(data=dict_H0)\n\n \n return adjusted_R_2, sd_sample, t_student_coef, critical_value, df_H0\n```\n\n\n```\n# Minimum Least Squares\n\n# XtX_inv\nXtX_inv = np.linalg.inv(X.T @ X)\n# coeficient vector \nb = XtX_inv @ X.T @ y\n\n# R^2 (quality of estimative)\nR_2, squared_residuals_sum = R2_SqResidSum(X, y, b)\n\n# t-Student stats (statistical relevance)\n(adjusted_R_2, sd_sample, t_student_coef, \n critical_value, df_H0) = t_student_stats(XtX_inv, b,squared_residuals_sum, R_2,\n confidence=0.975, n=len(y))\ndf_H0\n\n```\n\n H0: null hypothesis: the coefficients bi are not relevant\n \n Reject H0 that b0 is not relevant.\n t_student = 5.641 > critical_value = 2.365\n \n Reject H0 that b0 is not relevant.\n p_value = 7.82e-04 <= alpha = 0.025\n \n Reject H0 that b1 is not relevant.\n t_student = 7.307 > critical_value = 2.365\n \n Reject H0 that b1 is not relevant.\n p_value = 1.62e-04 <= alpha = 0.025\n \n Reject H0 that b2 is not relevant.\n t_student = 3.874 > critical_value = 2.365\n \n Reject H0 that b2 is not relevant.\n p_value = 6.10e-03 <= alpha = 0.025\n \n\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \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_studentp_valueaccept_H0_critical_valueaccept_H0_p_value
05.6412070.0007820.00.0
17.3069170.0001620.00.0
2-3.8739540.0061000.00.0
\n
\n\n\n\n## Validation with Sklearn\n\n\n```\nfrom sklearn.linear_model import LinearRegression\n\nreg = LinearRegression().fit(X, y)\n\n# coeficients b\nb_skt = reg.coef_.copy()\n# reference issue: without .copy()\n# reg.score changes from 0.88728964083039 to -36.13590607656064\n# because it changes reg.coef_[0]\nb_skt[0] = reg.intercept_\n\nprint('b from sklearn and homemade implementation are equal?', \n np.allclose(b, b_skt))\n\n# R^2\nR_2_skt = reg.score(X, y)\nprint('R^2 from sklearn and homemade implementation are equal?', \n np.allclose(R_2, R_2_skt))\n\n# predict\nx_new = np.array([[1, 3, 5]])\nskt_predict = reg.predict(x_new)\nprint('predict from sklearn and homemade implementation are equal?', \n np.allclose(LR_predict(x_new, b), skt_predict))\n\n```\n\n b from sklearn and homemade implementation are equal? True\n R^2 from sklearn and homemade implementation are equal? True\n predict from sklearn and homemade implementation are equal? True\n\n\n\n```\n\n```\n\n# Logistic Regression\n", "meta": {"hexsha": "a6010ddbef141950eb94ab32e4ddc3beefcdea30", "size": 20180, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "GoogleColab/LinearRegression.ipynb", "max_stars_repo_name": "viniciusriosfuck/dscodenation", "max_stars_repo_head_hexsha": "b59fb4417f6b348538f500123fe0ed4d048e2505", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-11-09T18:18:41.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-09T18:18:41.000Z", "max_issues_repo_path": "GoogleColab/LinearRegression.ipynb", "max_issues_repo_name": "inaborges/dscodenation", "max_issues_repo_head_hexsha": "710113aeed64f3302fe207201a967cc7cdc9e8e7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2020-07-21T17:28:07.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-05T22:30:35.000Z", "max_forks_repo_path": "GoogleColab/LinearRegression.ipynb", "max_forks_repo_name": "inaborges/dscodenation", "max_forks_repo_head_hexsha": "710113aeed64f3302fe207201a967cc7cdc9e8e7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-07-21T22:40:33.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-21T22:40:33.000Z", "avg_line_length": 20180.0, "max_line_length": 20180, "alphanum_fraction": 0.6049554014, "converted": true, "num_tokens": 5070, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9755769074605843, "lm_q2_score": 0.8962513814471134, "lm_q1q2_score": 0.8743621510194514}} {"text": "# CPLEX Basics on Linear Programming\n\n## Introduction\n* Widely used\n* Used to represent many practical problems\n* Elements\n * A linear objective function\n * Linear (in)equalities\n \n\n## The standard Form\n\\begin{align}\n\\text{minimize}\\ & f(x) \\\\\n\\text{subject to } & \\\\\n& a_1x &&\\geq b_1 \\\\\n& a_2x + c && \\geq b_2 \\\\\n& x &&\\geq 0\n\\end{align}\n\n\n\n# CPLEX Basics: Linear Model\n## Mathematical Model\n\\begin{align}\n\\text{minimize}\\ & 5x + 4y \\\\\n\\text{subject to } & \\\\\n& \\ \\ x+\\ \\ y &&\\geq \\ \\ 8 \\\\\n& 2x + \\ \\ y &&\\geq 10 \\\\\n& \\ \\ x + 4y &&\\geq 11 \\\\\n& \\ \\ x &&\\geq \\ \\ 0 \\\\\n& \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ y &&\\geq \\ \\ 0\n\\end{align}\n\n## Graphical representation of the problem\n\n\n\n```python\nfrom IPython.display import Image\nfrom IPython.display import display\ngraphs = ['fr', 'fr_o1', 'fr_o3']\nfor g in graphs:\n display(Image(filename = g+'.png'))\n```\n\n# Code in Python using docplex\n## Step 1: Importing docplex package\n\n\n```python\nfrom docplex.mp.model import Model\n```\n\n## Step 2: Create an optimization model\nModel constructor. Initially, no variables or constraints.\n``` python\nModel(name = '')\n```\n\n\n```python\nopt_mod = Model(name = \"Linear Program\")\n```\n\n## Step 3: Add decision variables\nAdd a continuous decision variable to a model.\n``` python\n\nModel.continuous_var(lb=None, #(optional) lower bound, default is 0.\n ub=None, #(optional) upper bound, default is infinity.\n name=None) #(optional) name\n \n```\n\n\n```python\nx = opt_mod.continuous_var(name = 'x', lb = 0)\ny = opt_mod.continuous_var(name = 'y', lb = 0)\n```\n\n## Step 4: Add the constraints\nAdd a constraint to a model. \n```python\nModel.add_constraint(ct, # \n ctname = None) # name of the constraint\n```\n\n\n```python\nc1 = opt_mod.add_constraint( x + y >= 8, ctname = 'c1')\nc2 = opt_mod.add_constraint(2*x + y >= 10, ctname = 'c2')\nc3 = opt_mod.add_constraint( x + 4*y >= 11, ctname = 'c3')\n```\n\n## Step 5: Define the objective function\nSet the model objective equal to a expression\n``` python\nModel.set_objective(sense, # “max” for maximization, “min” for minimization \n expr) # New objective expression\n\n```\n\n\n```python\nobj_fn = 5*x + 4*y\nopt_mod.set_objective('min', obj_fn)\n\nopt_mod.print_information()\n```\n\n## Step 6: Solve the model\n\n``` python\nModel.solve() # solve the model\n```\n\n\n```python\nopt_mod.solve() # solve the model\n```\n\n## Step 7: Output the result\n\n\n```python\nopt_mod.print_solution()\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "b16dca8deb6e7f436e69ea46fd738915d23bd22f", "size": 5393, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "mathematicalProgramming/Video07/Video07.ipynb", "max_stars_repo_name": "codingperspective/videoMaterials", "max_stars_repo_head_hexsha": "8c9665466d8912c6f0c701c25ad9eb4802fb73a3", "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": "mathematicalProgramming/Video07/Video07.ipynb", "max_issues_repo_name": "codingperspective/videoMaterials", "max_issues_repo_head_hexsha": "8c9665466d8912c6f0c701c25ad9eb4802fb73a3", "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": "mathematicalProgramming/Video07/Video07.ipynb", "max_forks_repo_name": "codingperspective/videoMaterials", "max_forks_repo_head_hexsha": "8c9665466d8912c6f0c701c25ad9eb4802fb73a3", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2021-11-21T05:02:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-17T04:44:57.000Z", "avg_line_length": 22.4708333333, "max_line_length": 86, "alphanum_fraction": 0.4796959021, "converted": true, "num_tokens": 763, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9706877675527112, "lm_q2_score": 0.90052978812007, "lm_q1q2_score": 0.8741332496449868}} {"text": "# Error propagation using Bayesian methods\n\nFor a Bayesian, everything is a probability distribution. This means that the way to do \"error propagation\" is to figure out how to combine two probability distributions to generate a third one.\n\nSpecifically, suppose that $Z=f(X,Y)$, and that we already know the pdf ${\\rm pr}(X,Y|I)$. We want to compute ${\\rm pr}(Z|I)$. Using marginalization introduce the variables $X$ and $Y$.\n\n\n```python\n\n```\n\nNow use the relationship between $Z$ and $X,Y$ to rewrite ${\\rm pr}(Z|X,Y)$. The result should be a formula involving the function $f$ and the joint pdf ${\\rm pr}(X,Y|I)$. \n\n\n```python\n\n```\n\nWe will call this the \"master formula\" for combining $X$ and $Y$.\n\n## Example 1: $Z=X+Y$, independent Gaussians\n\nNow write down Gaussian pdfs for $X$ and $Y$. Choose the means to be $x_0$ and $y_0$ respectively, and the standard deviations $\\sigma_x$ and $\\sigma_y$. \n\n\n```python\n\n```\n\nPut your results into the master formula, choose $f(X,Y)=X+Y$, and then combine the Gaussians. \n\n\n```python\n\n```\n\nComplete the square, and so obtain the result that the pdf for Z is:\n\n\\begin{equation}\n{\\rm pr}(Z|I)=\\frac{1}{\\sqrt{2 \\pi} \\sigma_z} \\exp\\left[-\\frac{(Z-z_0)^2}{2 \\sigma_z^2}\\right].\n\\end{equation}\nwith $z_0=x_0 + y_0$ and $\\sigma_z^2=\\sigma_x^2 + \\sigma_y^2$.\n\n## Example 2: $Z=X+Y$, $X$ and $Y$ are correlated Gaussians \n\nNow re-do the analysis for the case that $X$ and $Y$ are not independent. Specifically, choose:\n\n\\begin{equation}\n{\\rm pr}(X,Y|I)=\\frac{1}{\\sqrt{2 \\pi \\, {\\rm det} C}} \\exp\\left[-\\frac{1}{2}(X \\, \\, \\,Y)C^{-1}\\begin{pmatrix}\nX\\\\\nY\n\\end{pmatrix}\\right],\n\\end{equation}\nwith \n\\begin{equation}\nC \\equiv \\begin{pmatrix} \\sigma_x^2 & \\rho \\sigma_x \\sigma_y\\\\\n\\rho \\sigma_x \\sigma_y & \\sigma_y^2 \\end{pmatrix}.\n\\end{equation}\n\nBefore we get too far into combining $X$ and $Y$ you should check what happens if you set $\\rho=0$ here.....does the answer make sense?\n\n\n```python\n\n```\n\nPut the above equation for ${\\rm pr}(X,Y|I)$ into the master formula for the case $f(X,Y)=X+Y$ and compute the pdf for $Z$.\n\n\n```python\n\n```\n\nCheck the limit $\\rho=0$. Do you get back what you got in Example 1?\n\n\n```python\n\n```\n\nWhat happens in thew limit $\\rho=1$? What about $\\rho=-1$? Do those results make sense?\n\n## Example 3: $\\vec{Z}=f(\\vec{X},\\vec{Y})$, independent multi-variate Gaussians for ${\\rm pr}(\\vec{X}|I)$ and ${\\rm pr}(\\vec{Y}|I)$.\n\nNow take \n\n\\begin{eqnarray}\n{\\rm pr}(\\vec{X}|I) \\propto \\exp\\left[-\\frac{1}{2} (\\vec{X} - \\vec{\\mu_X})^T \\Sigma_X^{-1} (\\vec{X} - \\vec{\\mu_X})\\right];\\\\\n{\\rm pr}(\\vec{Y}|I) \\propto \\exp\\left[-\\frac{1}{2} (\\vec{Y} - \\vec{\\mu_Y})^T \\Sigma_Y^{-1} (\\vec{Y} - \\vec{\\mu_Y})\\right].\n\\end{eqnarray} \nA short way to notate this is \n\n\\begin{equation}\nX \\sim N(\\vec{\\mu}_X,\\Sigma_X); Y \\sim N(\\vec{\\mu}_Y,\\Sigma_Y).\n\\end{equation}\n\nI.e., we specify that they are given by normal distributions with particular (vector) means and covariance matrices.\n\nGo back to the master formula and generalize it for a vector $\\vec{Z}$ that is related to $\\vec{X}$ and $\\vec{Y}$ as $\\vec{Z}=f(\\vec{X},\\vec{Y})$. What do you get? This should not take longer than 90 seconds. :)\n\n\n```python\n\n```\n\nTake $\\vec{Z}=a \\vec{X} + b \\vec{Y}$ with $a$ and $b$ real scalars. Complete the square, do the integral and show that:\n\n\\begin{equation}\n\\vec{Z} \\sim N(a \\vec{\\mu}_X + b \\vec{\\mu}_Y, a^2 \\Sigma_X + b^2 \\Sigma_Y)\n\\end{equation}\n\n\n```python\n\n```\n\nComment on this result for a=b=1.\n\n\n```python\n\n```\n\nComment on this result for a=1, b=-1, i.e. the case $\\vec{Z}=\\vec{X}-\\vec{Y}$.\n\n\n```python\n\n```\n", "meta": {"hexsha": "3cbcd503976e2696d746c7ac3d408c15e8395595", "size": 7194, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "topics/basics-of-bayesian-statistics/Error_Propagation.ipynb", "max_stars_repo_name": "asemposki/Bayes2019", "max_stars_repo_head_hexsha": "bea9dbe5205fbf5939a154b1c3773e6c3baf39a4", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 13, "max_stars_repo_stars_event_min_datetime": "2019-06-06T17:55:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-16T08:26:26.000Z", "max_issues_repo_path": "topics/basics-of-bayesian-statistics/Error_Propagation.ipynb", "max_issues_repo_name": "asemposki/Bayes2019", "max_issues_repo_head_hexsha": "bea9dbe5205fbf5939a154b1c3773e6c3baf39a4", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-06-14T16:17:36.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-15T04:41:39.000Z", "max_forks_repo_path": "topics/basics-of-bayesian-statistics/Error_Propagation.ipynb", "max_forks_repo_name": "asemposki/Bayes2019", "max_forks_repo_head_hexsha": "bea9dbe5205fbf5939a154b1c3773e6c3baf39a4", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 17, "max_forks_repo_forks_event_min_datetime": "2019-06-10T18:23:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-22T15:38:30.000Z", "avg_line_length": 25.4204946996, "max_line_length": 223, "alphanum_fraction": 0.5219627467, "converted": true, "num_tokens": 1209, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566342037088041, "lm_q2_score": 0.9136765298777718, "lm_q1q2_score": 0.8740542196070457}} {"text": "## Roots.jl and NLsolve.jl\n\nRoots.jl and NLSolve.jl are two libraries for root finding in Julia. Roots.jl is for univariate problems and NLsolve.jl is for multivariate problems. NLsolve.jl uses the autodifferentiation libraries and Optim.jl to improve its calculations.\n\n### Problem 1\n\nUse Roots.jl to solve [the Kepler equation](https://github.com/JuliaMath/Roots.jl#usage-examples):\n\n$$ f(x) = 10 - x + e \\sin(x) $$\n\n### Problem 2\n\nUse NLsolve.jl to solve for the roots of the following equation:\n\n$$\\begin{align}\nf_1(x_1,x_2,x_3) &= x_1 + x_2 + x_3^2 - 12 \\\\\nf_2(x_1,x_2,x_3) &= x_1^2 - x_2 + x_3 - 2 \\\\\nf_3(x_1,x_2,x_3) &= 2x_1 - x_2^2 + x_3 -1\n\\end{align}$$\n\nSolve it first with finite differencing, then utilize autodifferentiation.\n\n[Use an in-place updating function to make the solving more efficient!]\n", "meta": {"hexsha": "4642d44fdcb3544b2657a2d0da530606ef5a1030", "size": 1457, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Notebooks/.ipynb_checkpoints/NonlinearSolve-checkpoint.ipynb", "max_stars_repo_name": "jla524/IntroToJulia", "max_stars_repo_head_hexsha": "2301ed94f1459893dcc67f67fc9b65df8d45d0ee", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 251, "max_stars_repo_stars_event_min_datetime": "2016-05-17T06:47:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-30T16:07:03.000Z", "max_issues_repo_path": "Notebooks/.ipynb_checkpoints/NonlinearSolve-checkpoint.ipynb", "max_issues_repo_name": "jla524/IntroToJulia", "max_issues_repo_head_hexsha": "2301ed94f1459893dcc67f67fc9b65df8d45d0ee", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 50, "max_issues_repo_issues_event_min_datetime": "2016-10-25T16:11:42.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-02T12:08:06.000Z", "max_forks_repo_path": "Notebooks/.ipynb_checkpoints/NonlinearSolve-checkpoint.ipynb", "max_forks_repo_name": "jla524/IntroToJulia", "max_forks_repo_head_hexsha": "2301ed94f1459893dcc67f67fc9b65df8d45d0ee", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 98, "max_forks_repo_forks_event_min_datetime": "2016-05-24T16:44:39.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-19T18:13:08.000Z", "avg_line_length": 29.7346938776, "max_line_length": 251, "alphanum_fraction": 0.5490734386, "converted": true, "num_tokens": 277, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.959154280587323, "lm_q2_score": 0.9111797148356994, "lm_q1q2_score": 0.8739619238689973}} {"text": "# SymPy\n\n\n```python\nimport sympy as sp\nsp.init_printing(use_unicode=True)\nfrom scipy import constants as cons # physical constants\nimport numpy as np\nimport matplotlib.pyplot as plt\n```\n\n## Basics\n\nInitialization\n\n\n```python\nx, y, z = sp.symbols('x y z')\n```\n\nDefinition of Sympy symbols (variables).\n\n\n```python\nexpr1 = (2*x + 3) * (x - 6)\nexpr1b = (x - 6) * (2*x + 3)\nexpr2 = 2*x**2 -9*x - 18\n```\n\n\n```python\nexpr1 == expr1b, expr1 == expr2\n```\n\n\n\n\n (True, False)\n\n\n\nThe first 2 expressions are identical, despite different term order.\nThe 3rd expression is syntactically different, but mathematically identical.\n\n\n```python\nexpr1 - expr2\n```\n\n\n```python\nsp.simplify(expr1 - expr2)\n```\n\nSimplify reveals that expr1 and expr2 are identical.\n\n\n```python\nexpr1.subs(x, sp.pi)\n```\n\n\n```python\nsp.simplify(expr1.subs(x, expr1))\n```\n\nSubstitution of variables\n\n\n```python\nsp.integrate(expr1, x)\n```\n\n\n```python\nsp.integrate(expr1, (x, 2, 10))\n```\n\nIntegration without and with given interval\n\n\n```python\n1/2, sp.S(1) / 2\n```\n\nDefition of numbers as symbols\n\n## Example 1: Kinetic Energy in Special Relativity\n\n\n```python\nbeta, c, m = sp.symbols(['beta', 'c', 'm'])\n```\n\n\n```python\ngamma = 1/sp.sqrt(1-beta**2)\ngamma\n```\n\n\n```python\nEkin = (gamma - 1)*m*c**2\nEkin\n```\n\n\n```python\nEkin.subs(c, cons.c).subs(beta, 0.1).subs(m, 1)\n```\n\nKinetic energy (in J) of 1kg moving at 10% speed of light.\n\n\n```python\nv = beta * c\nEkin_nr = sp.S(1)/2*m*v**2\nEkin_nr\n```\n\nNon-relativistic formula for kinetic energy.\n\n\n```python\nEkin.series(beta)\n```\n\nThe non-relativistic formula is actually the first term of the Taylor expansion of the relativistic kinetic energy equation.\n\n\n```python\nerr = sp.simplify(Ekin / Ekin_nr)\nerr\n```\n\nRatio of actual kinetic energy to non-relativistic approximation\n\n## Plotting\n\n### Plotting with Sympy\n\n\n```python\nsp.plotting.plot(err, (beta, 0, 0.9))\n```\n\n### Plotting using Numpy\n\n\n```python\nf = sp.lambdify(beta, err) # converts Sympy expression into function\nf\n```\n\n\n\n\n \n\n\n\n\n```python\nx = np.linspace(0.0001, 1, 100)\n```\n\n\n```python\nplt.plot(x, f(x))\n```\n\n## Example 2: Tsiolkovsky's Rocket Equation\n\nhttps://en.wikipedia.org/wiki/Tsiolkovsky_rocket_equation\n\n### Derivation of the Equation from Newton's Law\n\n\n```python\nmdot, ve, m0, mdry, t, Dv = sp.symbols('mdot v_e m_0 m_dry t \\Delta{V}', \n positive=True, real=True) # assumptions given here\n # for formula simplification by Sympy\n```\n\n\n```python\nF_exh = mdot * ve # thrust force is mass flow times exhaust velocity\nF_exh\n```\n\n\n```python\nm = m0 - mdot * t # current mass\nm\n```\n\n\n```python\na = F_exh / m # current acceleration\na\n```\n\n\n```python\nt_max = (m0 - mdry) / mdot # time the thrust is applied until reaction mass is consumed\nt_max\n```\n\n\n```python\nDv = sp.integrate(a, (t, 0, t_max)).simplify()\nDv\n```\n\n\n```python\nsp.expand_log(Dv)\n```\n\nOne can trivially reformulate this equation into the textbook one using\n\n$$\n \\log{a} - log{b} = \\log{\\frac{a}{b}}\n$$\n\n\n```python\nDv_textbook = ve * sp.log(m0/mdry)\nDv_textbook\n```\n\n### Calculating Mass Ratio for Earth Orbit\n\n\n```python\nv_leo = 9700 # low earth orbit, in m/s\nve_HO = 4400 # exhaust velocity for liquid hydrogen+ oxygen rockets\n```\n\n\n```python\nm0_result = sp.solve(Dv.subs(mdry, 1).subs(ve, ve_HO) - v_leo, m0)\nm0_result[0].evalf() # the solver returns a list of results, even if it is only 1 element like here\n```\n\nAccording to the rocket equation, a 1 stage hydrogen/oxygen rocket must must carry more than 8 times the dry mass (i.e. payload, tanks, engines, etc.) in fuel to reach low-earth orbit.\n\nIn practice this ratio is even higher because air friction and gravitational pull has been neglected here.\n", "meta": {"hexsha": "a25e248ca7f938f833e43a802d741adaa4b83008", "size": 78713, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/symbolic_computation.ipynb", "max_stars_repo_name": "lungben/python_tutorial", "max_stars_repo_head_hexsha": "b5cab0bee30cdebe6db2d671cce0c9230896b402", "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/symbolic_computation.ipynb", "max_issues_repo_name": "lungben/python_tutorial", "max_issues_repo_head_hexsha": "b5cab0bee30cdebe6db2d671cce0c9230896b402", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-07-30T16:59:31.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-30T16:59:31.000Z", "max_forks_repo_path": "notebooks/symbolic_computation.ipynb", "max_forks_repo_name": "lungben/python_tutorial", "max_forks_repo_head_hexsha": "b5cab0bee30cdebe6db2d671cce0c9230896b402", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-12-25T14:41:27.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-25T14:41:27.000Z", "avg_line_length": 87.5561735261, "max_line_length": 13540, "alphanum_fraction": 0.8468994956, "converted": true, "num_tokens": 1145, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9658995723244552, "lm_q2_score": 0.9046505376715775, "lm_q1q2_score": 0.8738015674400652}} {"text": "# Differential equations (symbolic)\n\nThis workbook uses symbolic computation to investigate the solutions of linear differential equations.\n\n## First-order system\n\nWe consider a system governed by the differential equation\n$$y(t) + RC \\frac{dy(t)}{dt} = x(t)$$\nwhere $x(t)$ is the input and $y(t)$ the output. We want to find the step response of this system, or in other words the output of the system when the input is the unit step $x(t) = u(t)$.\n\n## Basic code functionality\n\nThe cell below sets up the environment for symbolic computation. The rest sets up the `display` function for a symbolic expression to make pretty output.\n\n\n```python\nimport sympy as sp\nfrom IPython.display import display\nsp.init_printing() # pretty printing\n```\n\nWe define `imp` as the Dirac delta or unit impulse $\\delta(t)$, and `ustep` as the unit (or Heaviside) step function. When the unit step is differentiated we get the unit impulse. \n\n\n```python\n# Define impulse and unit step as functions of t\nt = sp.symbols('t');\nimp = sp.DiracDelta(t);\nustep = sp.Heaviside(t);\n#ustep = sp.Piecewise( (0, t<1), (1, True)); # diff() doesn't give delta function?!\n\n# Derivative of step is impulse\ndisplay(ustep);\ndisplay(sp.diff(ustep, t)); # derivative is dirac delta\n#sp.plot(ustep, (t,-4,4)); # sympy plot() not numpy plot()!\n```\n\nThe next block sets up variables and defines the differential equation. The `print` function on the symbolic expression gives the code representation of the relation, while `display` renders the result in a human friendly form.\n\n\n```python\n# Setup differential equation\nx = sp.Function('x'); y = sp.Function('y');\nRC = sp.symbols('RC');#, real=True);\nlp1de = sp.Eq(y(t) + RC*sp.diff(y(t), t), x(t));\n\nprint(lp1de); display(lp1de);\n```\n\nWe can solve the differential equation for $y(t)$. Note the result has an undetermined symbolic constant $C_1$ in the expression. We will need to set its value based on an auxiliary constraint.\n\n\n```python\n# Generic solution\ny_sl0e = sp.dsolve(lp1de, y(t));\ny_sl0r = y_sl0e.rhs # take only right hand side\n\ndisplay(y_sl0e); #display(y_sl0r);\n```\n\nTo use the symbolic expresion above requirest specifying the value $C_1$. The code below defines an equation for the initial value constraint of the form $y(-1) = a_0$, where $a_0$ is a symbolic variable.\n\n\n```python\n# Initial condition\na0 = sp.symbols('a0');\ncnd1 = sp.Eq(y_sl0r.subs(t, -1), a0); # y(-1) = a0\n#cnd2 = sy.Eq(y_sl0.diff(t).subs(t, 0), b0) # y'(0) = b0\n\nprint(cnd1); display(cnd1);\n```\n\nWe want to solve the above expression for $C_1$ so that we can substitute back into our generic solution. The result is returned in a form useful later.\n\n\n```python\n# Solve for C1: magic brackets in solve() returns result as dictionary\nC1 = sp.symbols('C1') # generic constants\nC1_sl = sp.solve([cnd1], (C1))\n\nprint(C1_sl); display(C1_sl);\n```\n\nSubstituting the expression obtained into the generic solution gives the solution expressed in terms of the initial value $a_0$ based on the constraint $y(-1) = a_0$.\n\n\n```python\n# Substitute back for solution in terms of a0\ny_sl1 = y_sl0r.subs(C1_sl);\n\ndisplay(sp.Eq(y(t), y_sl1))\n```\n\nAt this stage we're ready to substitute values and evaluate. This problem specified requires the step response, where the onset of the step occurs at $t=0$. We consider the case where the system was quiet before the step arrived, or an *initial rest* condition, so that $y(t)=0$ for $t<0$. This constraint meanst hat $y(-1) = 0$, so specifying $a_0=0$ for the constraint equation is appropriate. A value of $RC = 1$ is also assumed.\n\n\n```python\n# Set values for constants\ny_sl1s = y_sl1.subs({RC:1,a0:0}).doit()\n\ndisplay(sp.Eq(y(t), y_sl1s))\n```\n\nFinally we can make the substitution $x(t) = u(t)$ and evaluate the result. This provides the output of the system when the input is the unit step, and is thus the required step response.\n\n\n```python\n# Set input function and solve\ny_sl1sx = y_sl1s.subs({x(t):ustep}).doit()\n\nprint(sp.Eq(y(t), y_sl1sx)); display(sp.Eq(y(t), y_sl1sx))\nsp.plot(y_sl1sx, (t,-4,8))\n```\n\n## Code\n\nThe script below combines all the steps above to find and plot the step response.\n\n\n```python\n%run src/labX_preamble.py # For internal notebook functions\n```\n\n\n```python\n%%writefileexec src/lab_symdiffeq-1.py -s # dump cell to file before execute\n\nimport sympy as sp\nfrom IPython.display import display\nsp.init_printing() # pretty printing\n\n# Define impulse and unit step as functions of t\nt = sp.symbols('t');\nimp = sp.DiracDelta(t);\nustep = sp.Heaviside(t);\n#ustep = sp.Piecewise( (0, t<1), (1, True)); # diff() doesn't give delta function?!\n\n# Setup differential equation\nx = sp.Function('x'); y = sp.Function('y');\nRC = sp.symbols('RC');#, real=True);\nlp1de = sp.Eq(y(t) + RC*sp.diff(y(t), t), x(t));\n#print(lp1de); display(lp1de);\n\n# Generic solution\ny_sl0e = sp.dsolve(lp1de, y(t));\ny_sl0r = y_sl0e.rhs # take only right hand side\n#print(y_sl0e); display(y_sl0e);\n\n# Initial condition\na0 = sp.symbols('a0');\ncnd1 = sp.Eq(y_sl0r.subs(t, -1), a0); # y(-1) = a0\n#cnd2 = sp.Eq(y_sl0r.diff(t).subs(t, -1), b0) # y'(-1) = b0\n#print(cnd1); display(cnd1);\n\n# Solve for C1: magic brackets in solve() returns result as dictionary\nC1 = sp.symbols('C1') # generic constants\nC1_sl = sp.solve([cnd1], (C1))\n#C1C2_sl = sp.solve([cnd1, cnd2], (C1, C2))\n#print(C1_sl); display(C1_sl);\n\n# Substitute back for solution in terms of a0\ny_sl1 = y_sl0r.subs(C1_sl);\n#print(sp.Eq(y(t), y_sl1)); display(sp.Eq(y(t), y_sl1));\n\n# Set values for constants\ny_sl1s = y_sl1.subs({RC:1,a0:0}).doit()\n#print(sp.Eq(y(t), y_sl1s)); display(sp.Eq(y(t), y_sl1s));\n\n# Set input function and solve\ny_sl1sx = y_sl1s.subs({x(t):ustep}).doit()\nprint(sp.Eq(y(t), y_sl1sx)); display(sp.Eq(y(t), y_sl1sx))\n\n# Plot output\nsp.plot(y_sl1sx, (t,-4,8))\n```\n\n# Tasks\n\nThese tasks involve writing code, or modifying existing code, to meet the objectives described.\n\n1. Find and plot the impulse responses of the first-order lowpass circuit for $RC = 1, 2, 4$ on the same set of axes and over the range $-4$ to 12.
\n
\nYou should observe that the system reaches $1/e \\approx 0.368$ of its initial value after time $\\tau = RC$ has passed. This is called the *time constant* or sometimes the *RC time constant*$ of the circuit. A long time constant means that the circuit is slow to respond to changes, and involves a higher degree of lowpass filtering.

\n\n2. Any linear constant coefficient differential equation corresponds to a linear time invariant system. Thus \n$$y(t) - 0.1 \\frac{dy(t)}{dt} = x(t)$$\nis a valid system. It happens to correspond to a value of $RC=-0.1$ in the formulation above, so all the mathematics applies, although the system cannot be implemented with any real resistor and capacitor combination. Find the step response of this system under initial rest conditions, and plot it over the range $t=-4$ to $t=12$.
\n
\nIn this case the differential equation corresponds to an unstable system: a bounded input can produce an unbounded output.

\n\n3. The RLC circuit \n\nis governed by the second-order differential equation \n$$y(t) + \\frac{L}{R} y'(t) + LC y''(t) = \\frac{L}{R} x'(t).$$\nOn the same set of axes find and plot the step responses of the circuit over the range $t=-4$ to $t=12$ for $L=C=1$ and the cases $R=1/4$, $R=1/2$, and $R=1$. Use the auxiliary condition $y(-1)=0$ as before, along with the additional condition $y'(-1)=0$.
\n
\nThe quantity $\\omega_0 = 1/\\sqrt{LC}$ is the *resonant frequency* of the system and $\\alpha = 1/(2RC)$ is the *damping attenuation*. The three cases above respectively correspond to $\\alpha>\\omega_0$ (overdamped), $\\alpha=\\omega_0$ (critically damped), and $\\alpha<\\omega_0$ (underdamped).\n\n\n```python\n\n```\n", "meta": {"hexsha": "20fc00721908429ae2ff22ef16d4edc2c3798634", "size": 63684, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "lab_symdiffeq.ipynb", "max_stars_repo_name": "maxnvdm/notebooks", "max_stars_repo_head_hexsha": "c719a43d02e330bdc25dceea33d5e6c2b156e02d", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2019-07-17T09:03:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-01T05:28:21.000Z", "max_issues_repo_path": "lab_symdiffeq.ipynb", "max_issues_repo_name": "maxnvdm/notebooks", "max_issues_repo_head_hexsha": "c719a43d02e330bdc25dceea33d5e6c2b156e02d", "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": "lab_symdiffeq.ipynb", "max_forks_repo_name": "maxnvdm/notebooks", "max_forks_repo_head_hexsha": "c719a43d02e330bdc25dceea33d5e6c2b156e02d", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 20, "max_forks_repo_forks_event_min_datetime": "2017-08-21T12:06:52.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-02T16:52:18.000Z", "avg_line_length": 104.4, "max_line_length": 11690, "alphanum_fraction": 0.8119778908, "converted": true, "num_tokens": 2329, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897475985936, "lm_q2_score": 0.9284087946129328, "lm_q1q2_score": 0.8734374755522155}} {"text": "```python\nimport numpy as np\nimport matplotlib.pyplot as plt\n```\n\n# More on Numeric Optimization\n\nRecall that in homework 2, in one problem you were asked to maximize the following function:\n \n\\begin{align}\nf(x) & = -7x^2 + 930x + 30\n\\end{align}\n \nUsing calculus, you found that $x^* = 930/14=66.42857$ maximizes $f$. You also used a brute force method to find $x^*$ that involved computing $f$ over a grid of $x$ values. That approach works but is inefficient.\n\nAn alternative would be to use an optimizaton algorithm that takes an initial guess and proceeds in a deliberate way. The `fmin` function from `scipy.optimize` executes such an algorithm. `fmin` takes as arguments a *function* and an ititial guess. It iterates, computing updates to the initial guess until the function appears to be close to a *minimum*. It's standard for optimization routines to minimize functions. If you want to maximize a function, supply the negative of the desired function to `fmin`.\n\n## Example using `fmin`\n\nLet's use `fmin` to solve the problem from Homework 2. First, import `fmin`.\n\n\n```python\nfrom scipy.optimize import fmin\n```\n\nNext, define a function that returns $-(-7x^2 + 930x + 30)$. We'll talk in class later about how to do this.\n\n\n```python\ndef quadratic(x):\n return -(-7*x**2 + 930*x + 30)\n```\n\nNow call `fmin`. We know that the exact solution, but let's guess something kind of far off. Like $x_0 = 10$.\n\n\n```python\nx_star = fmin(quadratic,x0=10)\n\nprint()\nprint('fmin solution: ',x_star[0])\nprint('exact solution:',930/14)\n```\n\n Optimization terminated successfully.\n Current function value: -30919.285714\n Iterations: 26\n Function evaluations: 52\n \n fmin solution: 66.4285888671875\n exact solution: 66.42857142857143\n\n\n`fmin` iterated 26 times and evaluated the function $f$ only 52 times. The solution is accurate to 4 digits. The same accuracy in the assignment would be obtained by setting the step to 0.00001 in constructing `x`.Wtih min and max values of 0 and 100, `x` would have 10,000,000 elements implying that the funciton $f$ would have to be evaluated that many times. Greater accuracy would imply ever larger numbers of function evaluations.\n\nTo get a sense of the iterative process that `fmin` uses, we can request that the function return the value of $x$ at each iteration using the argument `retall=True`.\n\n\n```python\nx_star, x_values = fmin(quadratic,x0=10,retall=True)\n\nprint()\nprint('fmin solution: ',x_star[0])\nprint('exact solution:',930/14)\n```\n\n Optimization terminated successfully.\n Current function value: -30919.285714\n Iterations: 26\n Function evaluations: 52\n \n fmin solution: 66.4285888671875\n exact solution: 66.42857142857143\n\n\nWe can plot the iterated values to see how the routine converges.\n\n\n```python\nfig = plt.figure()\nax = fig.add_subplot(1,1,1)\nax.set_xlabel('Iteration of fmin')\nax.set_ylabel('x')\nax.plot(x_values,label=\"Computed by fmin\")\nax.plot(np.zeros(len(x_values))+930/14,'--',label=\"True $x^*$\")\nax.legend(loc='center left', bbox_to_anchor=(1, 0.5))\n```\n\nAccuracy of the `fmin` result can be improved by reducing the `xtol` and `ftol` arguments. These arguments specify the required maximum magnitide between iterations of $x$ and $f$ that is acceptable for algorithm convergence. Both default to 0.0001.\n\nLet's try `xtol=1e-7`.\n\n\n```python\nfmin(quadratic,x0=10,xtol=1e-7)\n```\n\n Optimization terminated successfully.\n Current function value: -30919.285714\n Iterations: 36\n Function evaluations: 75\n\n\n\n\n\n array([66.42857122])\n\n\n\nThe result is accurate to an additional decimal place. Greater accuracy will be hard to achieve with `fmin` because the function is large in absolute value at the maximum. We can improve accuracy by scaling the function by 1/30,000.\n\n\n```python\ndef quadratic_2(x):\n return -(-7*(x)**2 + 930*(x) + 30)/30000\n\nx_star = fmin(quadratic_2,x0=930/14,xtol=1e-7)\nprint()\nprint('fmin solution: ',x_star[0])\nprint('exact solution:',930/14)\n```\n\n Optimization terminated successfully.\n Current function value: -1.030643\n Iterations: 26\n Function evaluations: 54\n \n fmin solution: 66.42857142857143\n exact solution: 66.42857142857143\n\n\nNow the computed solution is accurate to 14 decimal places.\n\n## Another example\n\nConsider the polynomial function:\n\n\\begin{align}\nf(x) & = -\\frac{(x-1)(x-2)(x-7)(x-9)}{200}\n\\end{align}\n\nThe function has two local maxima which can be seen by plotting.\n\n\n```python\ndef polynomial(x):\n '''Funciton for computing the NEGATIVE of the polynomial'''\n return (x-1)*(x-2)*(x-7)*(x-9)/200\n\nfig = plt.figure()\nax = fig.add_subplot(1,1,1)\nax.set_xlabel('y')\nax.set_ylabel('x')\nax.set_title('$f(x) = -(x-1)(x-2)(x-7)(x-9)/200$')\n\nx = np.linspace(0,10,1000)\nplt.plot(x,-polynomial(x))\n```\n\nNow, let's use `fmin` to compute the maximum of $f(x)$. Suppose that our initial guess is $x_0=4$.\n\n\n```python\nx_star,x_values = fmin(polynomial,x0=4,retall=True)\n\nprint()\nprint('fmin solution: ',x_star[0])\n```\n\n Optimization terminated successfully.\n Current function value: -0.051881\n Iterations: 18\n Function evaluations: 36\n \n fmin solution: 1.4611328124999978\n\n\nThe routine apparently converges on a value that is only a local maximum because the inital guess was not properly chosen. To see how `fmin` proceeded, plot the steps of the iterations on the curve:\n\n\n```python\n# Redefine x_values because it is a list of one-dimensional Numpy arrays. Not convenient.\nx_values = np.array(x_values).T[0]\n\nfig = plt.figure()\nax = fig.add_subplot(1,1,1)\nax.set_xlabel('y')\nax.set_ylabel('x')\nax.set_title('$f(x) = -(x-1)(x-2)(x-7)(x-9)/200$')\n\nplt.plot(x,-polynomial(x))\nplt.plot(x_values,-polynomial(x_values),'o',alpha=0.5,label='iterated values')\nax.legend(loc='center left', bbox_to_anchor=(1, 0.5))\n```\n\n`fmin` takes the intial guess and climbs the hill to the left. So apparently the ability of the routine to find the maximum depends on the quality of the initial guess. That's why plotting is important. We can see that beyond about 5.5, the function ascends to the global max. So let's guess $x_0 = 6$.\n\n\n```python\nx_star,x_values = fmin(polynomial,x0=6,retall=True)\n\nprint()\nprint('fmin solution: ',x_star[0])\n```\n\n Optimization terminated successfully.\n Current function value: -0.214917\n Iterations: 17\n Function evaluations: 34\n \n fmin solution: 8.147973632812505\n\n\n\n```python\n# Redefine x_values because it is a list of one-dimensional Numpy arrays. Not convenient.\nx_values = np.array(x_values).T[0]\n\nfig = plt.figure()\nax = fig.add_subplot(1,1,1)\nax.set_xlabel('y')\nax.set_ylabel('x')\nax.set_title('$f(x) = -(x-1)(x-2)(x-7)(x-9)/200$')\n\nplt.plot(x,-polynomial(x))\nplt.plot(x_values,-polynomial(x_values),'o',alpha=0.5,label='iterated values')\nax.legend(loc='center left', bbox_to_anchor=(1, 0.5))\n```\n\n`fmin` converges to the global maximum.\n\n\n\n## Solving systems of equations\n\nA related problem to numeric optimization is finding the solutions to systems of equations. Consider the problem of mximizing utility:\n\n\\begin{align}\nU(x,1,x_2) & = x_1^{\\alpha} x_2^{\\beta}\n\\end{align}\n\nsubject to the budget constraint:\n\n\\begin{align}\nM & = p_1x_1 + p_2x_2\n\\end{align}\n\nby choosing $x_1$ and $x_2$. Solve this by constructing the Lagrangian function:\n\n\\begin{align}\n\\mathcal{L}(x_1,x_2,\\lambda) & = x_1^{\\alpha} x_2^{\\beta} + \\lambda \\left(M - p_1x_1 - p_2x_2\\right)\n\\end{align}\n\nwhere $\\lambda$ is the Lagrange multiplier on the constraint. The first-order conditions represent a system of equations to be solved:\n\n\\begin{align}\n\\alpha x1^{\\alpha-1} x2^{\\beta} - \\lambda p_1 & = 0\\\\\n\\beta x1^{\\alpha} x2^{\\beta-1} - \\lambda p_2 & = 0\\\\\nM - p_1x_1 - p_2 x_2 & = 0\\\\\n\\end{align}\n\nSolved by hand, you find:\n\n\\begin{align}\nx_1^* & = \\left(\\frac{\\alpha}{\\alpha+\\beta}\\right)\\frac{M}{p_1}\\\\\nx_1^* & = \\left(\\frac{\\beta}{\\alpha+\\beta}\\right)\\frac{M}{p_2}\\\\\n\\lambda^* & = \\left(\\frac{\\alpha}{p_1}\\right)^{\\alpha}\\left(\\frac{\\beta}{p_2}\\right)^{\\beta}\\left(\\frac{M}{\\alpha+\\beta}\\right)^{\\alpha+\\beta - 1}\n\\end{align}\n\nBut solving this problem by hand was tedious. If we knew values for $\\alpha$, $\\beta$, $p_1$, $p_2$, and $M$, then we could use an equation solver to solve the system. The one we'll use is called `fsolve` from `scipy.optimize`.\n\nFor the rest of the example, assumethe following parameter values:\n\n| $\\alpha$ | $\\beta$ | $p_1$ | $p_2$ | $M$ |\n|----------|---------|-------|-------|-------|\n| 0.25 | 0.75 | 1 | 2 | 100 |\n\nFirst, import `fsolve`.\n\n\n```python\nfrom scipy.optimize import fsolve\n```\n\nDefine variables to store parameter values and compute exact solution\n\n\n```python\n# Parameters\nalpha = 0.25\nbeta = 0.75\np1 = 1\np2 = 2\nm = 100\n\n# Solution\nx1_star = m/p1*alpha/(alpha+beta)\nx2_star = m/p2*beta/(alpha+beta)\nlam_star = x_star = alpha**alpha*beta**beta*p1**-alpha*p2**-beta\n\nexact_soln = np.array([x1_star,x2_star,lam_star])\n```\n\nNext, define a function that returns the system of equations solved for zero. I.e., when the solution is input into the function, it return an array of zeros.\n\n\n```python\ndef system(x):\n \n x1,x2,lam = x\n \n retval = np.zeros(3)\n\n retval[0] = alpha*x1**(alpha-1)*x2**beta - lam*p1\n retval[1] = beta*x1**alpha*x2**(beta-1) - lam*p2\n retval[2] = m - p1*x1 - p2*x2\n \n return retval\n```\n\nSolve the system with `fsolve`. Set initial guess for $x_1$, $x_2$, and $\\lambda$ to 1, 1, and 1.\n\n\n```python\napprox_soln = fsolve(system,x0=[1,1,1])\n\nprint('Approximated solution:',approx_soln)\nprint('Exact solution: ',exact_soln)\n```\n\n Approximated solution: [25. 37.5 0.33885075]\n Exact solution: [25. 37.5 0.33885075]\n\n\nApparently the solution form fsolve is highly accurate. However, we can (and should) verify that original system is in fact equal to zero at the values returned by `fsolve`. Use `np.isclose` to test.\n\n\n```python\nnp.isclose(system(approx_soln),0)\n```\n\n\n\n\n array([ True, True, True])\n\n\n\nNote that like `fmin`, the results of `fsolve` are sensitive to the intial guess. Suppose we guess 1000 for $x_1$ and $x_2$.\n\n\n```python\napprox_soln = fsolve(system,x0=[1000,1000,1])\n\napprox_soln\n```\n\n /Users/bcjenkin/opt/anaconda3/lib/python3.7/site-packages/ipykernel_launcher.py:7: RuntimeWarning: invalid value encountered in double_scalars\n import sys\n /Users/bcjenkin/opt/anaconda3/lib/python3.7/site-packages/ipykernel_launcher.py:8: RuntimeWarning: invalid value encountered in double_scalars\n \n /Users/bcjenkin/opt/anaconda3/lib/python3.7/site-packages/scipy/optimize/minpack.py:162: RuntimeWarning: The iteration is not making good progress, as measured by the \n improvement from the last ten iterations.\n warnings.warn(msg, RuntimeWarning)\n\n\n\n\n\n array([1000., 1000., 1.])\n\n\n\nThe routine does not converge on the solution. The lesson is that with numerical routines for optimization and equation solving, you have to use juedgment in setting initial guesses and it helps to think carefully about the problem that you are solving beforehand.\n", "meta": {"hexsha": "705f7b83759d6c613cfb0452424d7da512bcb1c7", "size": 96254, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Examples/Optimization_and_Equation_Solving.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": "Examples/Optimization_and_Equation_Solving.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": "Examples/Optimization_and_Equation_Solving.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": 131.8547945205, "max_line_length": 21424, "alphanum_fraction": 0.8764518877, "converted": true, "num_tokens": 3282, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.921921841290738, "lm_q2_score": 0.947381044980928, "lm_q1q2_score": 0.8734112773927606}} {"text": "\n\n# RREF Calculation\nUsing the `SymPy` library (Symbolic Python), we can obtain the exact unique RREF of any matrix easily. With the help of `sympy.Matrix().rref()` method, we can put a matrix into Reduced Row Echelon Form. `Matrix().rref()` returns a tuple of two elements. The first is the Reduced Row Echelon Form (RREF), and the second is a tuple of indices of the pivot columns (columns with leading 1s).\n\n\n```python\nimport sympy as sp\nfrom sympy import Matrix, linsolve, symbols\nsp.init_printing(use_unicode=True)\n```\n\n#Example\n\nSolve the following system of linear equations:\n\n$\n\\left\\{\\begin{aligned} \nx+3y+5z &=8 \\\\\n-2x+4y+9z &=3 \\\\\n-x+7y+14z &=11 \\end{aligned}\\right.\n$\n\n\n```python\nA = sp.Matrix([[1,3,5,8],[-2,4,9,3],[-1,7,14,11]])\nA\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}1 & 3 & 5 & 8\\\\-2 & 4 & 9 & 3\\\\-1 & 7 & 14 & 11\\end{matrix}\\right]$\n\n\n\n\n```python\n#get the exact RREF of A with the pivot columns identified\nB = A.rref()\nB \n```\n\n\n\n\n$\\displaystyle \\left( \\left[\\begin{matrix}1 & 0 & - \\frac{7}{10} & \\frac{23}{10}\\\\0 & 1 & \\frac{19}{10} & \\frac{19}{10}\\\\0 & 0 & 0 & 0\\end{matrix}\\right], \\ \\left( 0, \\ 1\\right)\\right)$\n\n\n\n\n```python\n# reduced matrix only\nB[0]\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}1 & 0 & - \\frac{7}{10} & \\frac{23}{10}\\\\0 & 1 & \\frac{19}{10} & \\frac{19}{10}\\\\0 & 0 & 0 & 0\\end{matrix}\\right]$\n\n\n\n\n```python\n# pivot columns only\nB[1]\n```\n", "meta": {"hexsha": "02ce056e6c7db2b840d30dff2f54ac5b87b1c578", "size": 7066, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "RREF_Gaussian_Elimination.ipynb", "max_stars_repo_name": "tofighi/Linear-Algebra", "max_stars_repo_head_hexsha": "bea7d2a4a81e0c49b324f23c47cf03db72e376cf", "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": "RREF_Gaussian_Elimination.ipynb", "max_issues_repo_name": "tofighi/Linear-Algebra", "max_issues_repo_head_hexsha": "bea7d2a4a81e0c49b324f23c47cf03db72e376cf", "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": "RREF_Gaussian_Elimination.ipynb", "max_forks_repo_name": "tofighi/Linear-Algebra", "max_forks_repo_head_hexsha": "bea7d2a4a81e0c49b324f23c47cf03db72e376cf", "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": 33.6476190476, "max_line_length": 942, "alphanum_fraction": 0.4692895556, "converted": true, "num_tokens": 536, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474207360067, "lm_q2_score": 0.9149009491921664, "lm_q1q2_score": 0.8734078313752259}} {"text": "## Maximum Likelihood Estimation\n\nMaximum likelihood estimation is one of the key techniques employed in statistical signal processing for a wide variety of applications from signal detection to parameter estimation. In the following, we consider a simple experiment and work through the details of maximum likelihood estimation to ensure that we understand the concept in one of its simplest applications.\n\n### Setting up the Coin Flipping Experiment\n\nSuppose we have coin and want to estimate the probability of heads ($p$) for it. The coin is Bernoulli distributed:\n\n$$ \\phi(x)= p^x (1-p)^{(1-x)} $$\n\nwhere $x$ is the outcome, *1* for heads and *0* for tails. The $n$ independent flips, we have the likelihood:\n\n$$ \\mathcal{L}(p|\\mathbf{x})= \\prod_{i=1}^n p^{ x_i }(1-p)^{1-x_i} $$\n\nThis is basically notation. We have just substituted everything into $ \\phi(x)$ under the independent-trials assumption. \n\nThe idea of *maximum likelihood* is to maximize this as the function of $p$ after plugging in all of the $x_i$ data. This means that our estimator, $\\hat{p}$ , is a function of the observed $x_i$ data, and as such, is a random variable with its own distribution.\n\n### Simulating the Experiment\n\nWe need the following code to simulate coin flipping.\n\n\n```\n%matplotlib inline\nfrom __future__ import division\nfrom scipy.stats import bernoulli \nimport numpy as np\n\np_true=1/2 # this is the value we will try to estimate from the observed data\nfp=bernoulli(p_true)\n\ndef sample(n=10):\n 'simulate coin flipping'\n return fp.rvs(n)# flip it n times\n\nxs = sample(100) # generate some samples\n```\n\nNow, we can write out the likelihood function using `sympy`\n\n\n```\nimport sympy\nfrom sympy.abc import x, z\np=sympy.symbols('p',positive=True)\n\nL=p**x*(1-p)**(1-x)\nJ=np.prod([L.subs(x,i) for i in xs]) # objective function to maximize\n```\n\nBelow, we find the maximum using basic calculus. Note that taking the `log` of $J$ makes the maximization problem tractable but doesn't change the extrema.\n\n\n```\nlogJ=sympy.expand_log(sympy.log(J))\nsol=sympy.solve(sympy.diff(logJ,p),p)[0]\n\nx=linspace(0,1,100)\nplot(x,map(sympy.lambdify(p,logJ,'numpy'),x),sol,logJ.subs(p,sol),'o',\n p_true,logJ.subs(p,p_true),'s',)\nxlabel('$p$',fontsize=18)\nylabel('Likelihood',fontsize=18)\ntitle('Estimate not equal to true value',fontsize=18)\n```\n\nNote that our estimator $\\hat{p}$ (red circle) is not equal to the true value of $p$ (green square), but it is at the maximum of the likelihood function. This may sound disturbing, but keep in mind this estimate is a function of the random data; and since that data can change, the ultimate estimate can likewise change. I invite you to run this notebook a few times to observe this. Remember that the estimator is a *function* of the data and is thus also a *random variable*, just like the data is. \n\nLet's write some code to empirically examine the behavior of the maximum likelihood estimator using a simulation of multiple trials. All we're doing here is combining the last few blocks of code.\n\n\n```\ndef estimator_gen(niter=10,ns=100):\n 'generate data to estimate distribution of maximum likelihood estimator'\n out=[]\n x=sympy.symbols('x',real=True)\n L= p**x*(1-p)**(1-x)\n for i in range(niter):\n xs = sample(ns) # generate some samples from the experiment\n J=np.prod([L.subs(x,i) for i in xs]) # objective function to maximize\n logJ=sympy.expand_log(sympy.log(J)) \n sol=sympy.solve(sympy.diff(logJ,p),p)[0]\n out.append(float(sol.evalf()))\n return out if len(out)>1 else out[0] # return scalar if list contains only 1 term\n \netries = estimator_gen(100) # this may take awhile, depending on how much data you want to generate\nhist(etries) # histogram of maximum likelihood estimator\ntitle('$\\mu=%3.3f,\\sigma=%3.3f$'%(mean(etries),std(etries)),fontsize=18)\n```\n\nNote that the mean of the estimator ($\\mu$) is pretty close to the true value, but looks can be deceiving. The only way to know for sure is to check if the estimator is unbiased, namely, if\n\n$$ \\mathbb{E}(\\hat{p}) = p $$\n\nBecause this problem is simple, we can solve for this in general noting that since $x=0$ or $x=1$, the terms in the product of $\\mathcal{L}$ above are either $p$, if $x_i=1$ or $1-p$ if $x_i=0$. This means that we can write\n\n$$ \\mathcal{L}(p|\\mathbf{x})= p^{\\sum_{i=1}^n x_i}(1-p)^{n-\\sum_{i=1}^n x_i} $$\n\nwith corresponding log as\n\n$$ J=\\log(\\mathcal{L}(p|\\mathbf{x})) = \\log(p) \\sum_{i=1}^n x_i + \\log(1-p) \\left(n-\\sum_{i=1}^n x_i\\right)$$ \n\nTaking the derivative of this gives:\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\nand solving this leads to\n\n$$ \\hat{p} = \\frac{1}{ n} \\sum_{i=1}^n x_i $$\n\nThis is our *estimator* for $p$. Up til now, we have been using `sympy` to solve for this based on the data $x_i$ but now we have it generally and don't have to solve for it again. To check if this estimator is biased, we compute its expectation:\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\nby linearity of the expectation and where\n\n$$\\mathbb{E}(x_i) = p$$\n\nTherefore,\n\n$$ \\mathbb{E}\\left(\\hat{p}\\right) =p $$\n\nThis means that the esimator is unbiased. This is good news. We almost always want our estimators to be unbiased. Similarly, \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\nand where\n\n$$ \\mathbb{E}\\left(x_i^2\\right) =p$$\n\nand by the independence assumption,\n\n$$ \\mathbb{E}\\left(x_i x_j\\right) =\\mathbb{E}(x_i)\\mathbb{E}( x_j) =p^2$$\n\nThus,\n\n$$ \\mathbb{E}\\left(\\hat{p}^2\\right) =\\left(\\frac{1}{n^2}\\right) n \n\\left[\np+(n-1)p^2\n\\right]\n$$\n\nSo, the variance of the estimator, $\\hat{p}$ is the following:\n\n$$ \\sigma_\\hat{p}^2 = \\mathbb{E}\\left(\\hat{p}^2\\right)- \\mathbb{E}\\left(\\hat{p}\\right)^2 = \\frac{p(1-p)}{n} $$\n\nNote that the $n$ in the denominator means that the variance asymptotically goes to zero as $n$ increases (i.e. we consider more and more samples). This is good news also because it means that more and more coin flips leads to a better estimate of the underlying $p$.\n\nUnfortunately, this formula for the variance is practically useless because we have to know $p$ to compute it and $p$ is the parameter we are trying to estimate in the first place! But, looking at $ \\sigma_\\hat{p}^2 $, we can immediately notice that if $p=0$, then there is no estimator variance because the outcomes are guaranteed to be tails. Also, the maximum of this variance, for whatever $n$, happens at $p=1/2$. This is our worst case scenario and the only way to compensate is with more samples (i.e. larger $n$). \n\n\nAll we have computed is the mean and variance of the estimator. In general, this is insufficient to characterize the underlying probability density of $\\hat{p}$, except if we somehow knew that $\\hat{p}$ were normally distributed. This is where the powerful [*central limit theorem*](http://mathworld.wolfram.com/CentralLimitTheorem.html) comes in. The form of the estimator, which is just a mean estimator, implies that we can apply this theorem and conclude that $\\hat{p}$ is normally distributed. However, there's a wrinkle here: the theorem tells us that $\\hat{p}$ is asymptotically normal, it doesn't quantify how many samples $n$ we need to approach this asymptotic paradise. In our simulation this is no problem since we can generate as much data as we like, but in the real world, with a costly experiment, each sample may be precious. In the following, we won't apply this theorem and instead proceed analytically.\n\n\n### Probability Density for the Estimator\n\nTo write out the full density for $\\hat{p}$, we first have to ask what is the probability that the estimator will equal a specific value and the tally up all the ways that could happen with their corresponding probabilities. For example, what is the probability that\n\n$$ \\hat{p} = \\frac{1}{n}\\sum_{i=1}^n x_i = 0 $$\n\nThis can only happen one way: when $x_i=0 \\hspace{0.5em} \\forall i$. The probability of this happening can be computed from the density\n\n$$ f(\\mathbf{x},p)= \\prod_{i=1}^n \\left(p^{x_i} (1-p)^{1-x_i} \\right) $$\n\n$$ f\\left(\\sum_{i=1}^n x_i = 0,p\\right)= \\left(1-p\\right)^n $$\n\nLikewise, if $\\lbrace x_i \\rbrace$ has one $i^{th}$ value equal to one, then\n\n$$ f\\left(\\sum_{i=1}^n x_i = 1,p\\right)= n p \\prod_{i=1}^{n-1} \\left(1-p\\right)$$\n\nwhere the $n$ comes from the $n$ ways to pick one value equal to one from the $n$ elements $x_i$. Continuing this way, we can construct the entire density as\n\n$$ f\\left(\\sum_{i=1}^n x_i = k,p\\right)= \\binom{n}{k} p^k (1-p)^{n-k} $$\n\nwhere the term on the left is the binomial coefficient of $n$ things taken $k$ at a time. This is the binomial distribution and it's not the density for $\\hat{p}$, but rather for $n\\hat{p}$. We'll leave this as-is because it's easier to work with below. We just have to remember to keep track 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 meaningful questions. For example,\n\n$$ \\mathbb{P}\\left( | \\hat{p}-p | \\le \\epsilon p \\right) $$\n\nOr, in words, what is the probability we can get within $\\epsilon$ percent of the true value of $p$. Rewriting,\n\n$$ \\mathbb{P}\\left( p - \\epsilon p \\lt \\hat{p} \\lt p + \\epsilon p \\right) = \\mathbb{P}\\left( n p - n \\epsilon p \\lt \\sum_{i=1}^n x_i \\lt n p + n \\epsilon p \\right)$$\n\nLet's plug in some live numbers here for our worst case scenario where $p=1/2$. Then, if $\\epsilon = 1/100$, we have\n\n$$ \\mathbb{P}\\left( \\frac{99 n}{200} \\lt \\sum_{i=1}^n x_i \\lt \\frac{101 n}{200} \\right)$$\n\nSince the sum in integer-valued, we need $n> 100$ to even compute this. Thus, if $n=101$ we have\n\n$$ \\mathbb{P}\\left( \\frac{9999}{200} \\lt \\sum_{i=1}^{101} x_i \\lt \\frac{10201}{200} \\right) = f\\left(\\sum_{i=1}^{101} x_i = 50,p\\right)= \\binom{101}{50} (1/2)^{50} (1-1/2)^{101-50} = 0.079$$\n\nThis means that in the worst-case scenario for $p=1/2$, given $n=101$ trials, we will only get within 1% of the actual $p=1/2$ about 8% of the time. If you feel disappointed, that only means you've been paying attention. What if the coin was really heavy and it was costly to repeat this 101 times? Then, we would be within 1% of the actual value only 8% of the time. Those odds are terrible.\n\nLet's come at this another way: given I could only flip the coin 100 times, how close could I come to the true underlying value with high probability (say, 95%)? In this case we are seeking to solve for $\\epsilon$. Plugging in gives,\n\n$$ \\mathbb{P}\\left( 50 - 50 \\epsilon \\lt \\sum_{i=1}^{100} x_i \\lt 50 + 50 \\epsilon \\right) = 0.95$$\n\nwhich we have to solve for $\\epsilon$. Fortunately, all the tools we need to solve for this are already in `scipy`.\n\n\n```\nimport scipy.stats\n\nb=scipy.stats.binom(100,.5) # n=100, p = 0.5, distribution of the estimator \\hat{p}\n\nf,ax= subplots()\nax.stem(arange(0,101),b.pmf(arange(0,101))) # heres the density of the sum of x_i\n\ng = lambda i:b.pmf(arange(-i,i)+50).sum() # symmetric sum the probability around the mean\nprint 'this is pretty close to 0.95:%r'%g(10)\nax.vlines( [50+10,50-10],0 ,ax.get_ylim()[1] ,color='r',lw=3.)\n\n```\n\nThe two vertical lines in the plot show how far out from the mean we have to go to accumulate 95% of the probability. Now, we can solve this as\n\n$$ 50 + 50 \\epsilon = 60 $$\n\nwhich makes $\\epsilon=1/5$ or 20%. So, flipping 100 times means I can only get within 20% of the real $p$ 95% of the time in the worst case scenario (i.e. $p=1/2$).\n\n\n\n```\nb=scipy.stats.bernoulli(.5) # coin distribution\nxs = b.rvs(100) # flip it 100 times\nphat = mean(xs) # estimated p\n\nprint abs(phat-0.5) < 0.5*0.20 # did I make it w/in interval 95% of the time?\n```\n\n True\n\n\nLet's keep doing this and see if we can get within this interval 95% of the time.\n\n\n```\nout=[]\nb=scipy.stats.bernoulli(.5) # coin distribution\nfor i in range(500): # number of tries\n xs = b.rvs(100) # flip it 100 times\n phat = mean(xs) # estimated p\n out.append(abs(phat-0.5) < 0.5*0.20 ) # within 20% \n\nprint 'Percentage of tries within 20 interval = %3.2f'%(100*sum(out)/float(len(out) ))\n```\n\n Percentage of tries within 20 interval = 96.20\n\n\nWell, that seems to work. Now we have a way to get at the quality of the estimator, $\\hat{p}$. \n\n## Summary\n\nIn this section, we explored the concept of maximum likelihood estimation using a coin flipping experiment both analytically and numerically with the scientific Python tool chain. There are two key points to remember. First, maximum likelihood estimation produces a function of the data that is itself a random variable, with its own statistics and distribution. Second, it's worth considering how to analytically derive the density function of the estimator rather than relying on canned packages to compute confidence intervals wherever possible. This is especially true when data is hard to come by and the approximations made in the central limit theorem are therefore harder to justify.\n\n### References\n\nThis [IPython notebook](www.ipython.org) is available for [download](https://github.com/unpingco/Python-for-Signal-Processing/blob/master/Maximum_likelihood.ipynb). I urge you to experiment with the calculations for different parameters. As always, corrections and comments are welcome!\n", "meta": {"hexsha": "11f8e072715451ddaf49785eb1aa3cdba5a5f135", "size": 68237, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "4-assets/BOOKS/Jupyter-Notebooks/Overflow/Maximum_likelihood.ipynb", "max_stars_repo_name": "impastasyndrome/Lambda-Resource-Static-Assets", "max_stars_repo_head_hexsha": "7070672038620d29844991250f2476d0f1a60b0a", "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": "4-assets/BOOKS/Jupyter-Notebooks/Overflow/Maximum_likelihood.ipynb", "max_issues_repo_name": "impastasyndrome/Lambda-Resource-Static-Assets", "max_issues_repo_head_hexsha": "7070672038620d29844991250f2476d0f1a60b0a", "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": "4-assets/BOOKS/Jupyter-Notebooks/Overflow/Maximum_likelihood.ipynb", "max_forks_repo_name": "impastasyndrome/Lambda-Resource-Static-Assets", "max_forks_repo_head_hexsha": "7070672038620d29844991250f2476d0f1a60b0a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-11-05T07:48:26.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-05T07:48:26.000Z", "avg_line_length": 132.4990291262, "max_line_length": 24391, "alphanum_fraction": 0.8341369052, "converted": true, "num_tokens": 3982, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693674025231, "lm_q2_score": 0.9196425333801889, "lm_q1q2_score": 0.8733563429116177}} {"text": "[sympy](https://docs.sympy.org/latest/index.html)\n\n\n```python\n# pip install sympy\n# Jacobian https://docs.sympy.org/latest/modules/matrices/matrices.html\n\nfrom sympy import sin, cos, Matrix\nfrom sympy.abc import rho, phi\nX = Matrix([rho*cos(phi), rho*sin(phi), rho**2])\nY = Matrix([rho, phi])\nX.jacobian(Y)\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}\\cos{\\left(\\phi \\right)} & - \\rho \\sin{\\left(\\phi \\right)}\\\\\\sin{\\left(\\phi \\right)} & \\rho \\cos{\\left(\\phi \\right)}\\\\2 \\rho & 0\\end{matrix}\\right]$\n\n\n\n\n```python\nX = Matrix([rho*cos(phi), rho*sin(phi)])\nX.jacobian(Y)\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}\\cos{\\left(\\phi \\right)} & - \\rho \\sin{\\left(\\phi \\right)}\\\\\\sin{\\left(\\phi \\right)} & \\rho \\cos{\\left(\\phi \\right)}\\end{matrix}\\right]$\n\n\n\n\n```python\n\n```\n\n\n```python\nfrom sympy import MatrixSymbol, Matrix,diff\nX = MatrixSymbol('X', 3, 3)\nY = MatrixSymbol('Y', 3, 3)\nZ = (X.T*X).I*Y\n```\n\n\n```python\nZ = (X.T*Y)*X\nZ.diff(X).simplify()\n\n# from sympy import derive_by_array\n# derive_by_array(Z, X)\n\nn=5\nA = MatrixSymbol(\"A\", n, n)\nx = MatrixSymbol(\"x\", n, 1)\ndiff(A.T*x, x)\n\n```\n\n\n\n\n$\\displaystyle A$\n\n\n\n\n```python\n# https://github.com/sympy/sympy/issues/5858\nx = MatrixSymbol(\"x\", n, n)\ndiff(A.T*x, x)\n```\n\n\n\n\n$\\displaystyle \\frac{\\partial}{\\partial x} A^{T} x$\n\n\n", "meta": {"hexsha": "99206a919f282cd95b13f524f0461bc50a58fc86", "size": 4220, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "automatic_and_symbolic_differentiation/symbolic_differentiation.ipynb", "max_stars_repo_name": "shadialameddin/numerical_tools_and_friends", "max_stars_repo_head_hexsha": "cc9f10f58886ee286ed89080e38ebd303d3c72a5", "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": "automatic_and_symbolic_differentiation/symbolic_differentiation.ipynb", "max_issues_repo_name": "shadialameddin/numerical_tools_and_friends", "max_issues_repo_head_hexsha": "cc9f10f58886ee286ed89080e38ebd303d3c72a5", "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": "automatic_and_symbolic_differentiation/symbolic_differentiation.ipynb", "max_forks_repo_name": "shadialameddin/numerical_tools_and_friends", "max_forks_repo_head_hexsha": "cc9f10f58886ee286ed89080e38ebd303d3c72a5", "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": 23.3149171271, "max_line_length": 233, "alphanum_fraction": 0.4924170616, "converted": true, "num_tokens": 440, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632234212403, "lm_q2_score": 0.9173026567597713, "lm_q1q2_score": 0.8731466637162235}} {"text": "\n\n# SymPy Expressions\n\nSymPy expressions reason about mathematics and generate numeric code.\n\n\n```\nfrom sympy import *\nfrom sympy.abc import x, y, z\ninit_printing(use_latex='mathjax')\n```\n\n### Operations on SymPy objects create expressions\n\n\n```\nx + y\n```\n\n\n\n\n$$x + y$$\n\n\n\n\n```\ntype(x + y)\n```\n\n\n\n\n sympy.core.add.Add\n\n\n\n### These expressions can be somewhat complex\n\n\n```\nexpr = sin(x)**2 + 2*cos(x)\nexpr\n```\n\n\n\n\n$$\\sin^{2}{\\left (x \\right )} + 2 \\cos{\\left (x \\right )}$$\n\n\n\n### We generate numeric code from these expressions\n\n\n```\nccode(expr) # C\n```\n\n\n\n\n 'pow(sin(x), 2) + 2*cos(x)'\n\n\n\n\n```\nfcode(expr) # Fortran\n```\n\n\n\n\n ' sin(x)**2 + 2*cos(x)'\n\n\n\n\n```\njscode(expr) # JavaScript\n```\n\n\n\n\n 'Math.pow(Math.sin(x), 2) + 2*Math.cos(x)'\n\n\n\n\n```\nlatex(expr) # Even LaTeX\n```\n\n\n\n\n '\\\\sin^{2}{\\\\left (x \\\\right )} + 2 \\\\cos{\\\\left (x \\\\right )}'\n\n\n\n### We also reason about expressions\n\n\n```\nexpr\n```\n\n\n\n\n$$\\sin^{2}{\\left (x \\right )} + 2 \\cos{\\left (x \\right )}$$\n\n\n\n\n```\nexpr.diff(x)\n```\n\n\n\n\n$$2 \\sin{\\left (x \\right )} \\cos{\\left (x \\right )} - 2 \\sin{\\left (x \\right )}$$\n\n\n\n\n```\nexpr.diff(x).diff(x)\n```\n\n\n\n\n$$- 2 \\sin^{2}{\\left (x \\right )} + 2 \\cos^{2}{\\left (x \\right )} - 2 \\cos{\\left (x \\right )}$$\n\n\n\n### And then can generate code\n\n\n```\nccode(expr.diff(x).diff(x))\n```\n\n\n\n\n '-2*pow(sin(x), 2) + 2*pow(cos(x), 2) - 2*cos(x)'\n\n\n\n### Combining reasoning and code generation gives us more efficient code\n\n\n```\nexpr.diff(x).diff(x)\n```\n\n\n\n\n$$- 2 \\sin^{2}{\\left (x \\right )} + 2 \\cos^{2}{\\left (x \\right )} - 2 \\cos{\\left (x \\right )}$$\n\n\n\n\n```\nsimplify(expr.diff(x).diff(x))\n```\n\n\n\n\n$$- 2 \\cos{\\left (x \\right )} + 2 \\cos{\\left (2 x \\right )}$$\n\n\n\n\n```\nccode(simplify(expr.diff(x).diff(x))) # Faster code\n```\n\n\n\n\n '-2*cos(x) + 2*cos(2*x)'\n\n\n\n# Final Thoughts\n\nWe combine high-level reasoning with low-level code generation.\n\nBlaze does the same thing, just swap out calculus and trig with relational and linear algebra.\n", "meta": {"hexsha": "9f58702d6de86f52b4f9e49578339939e1797086", "size": 8395, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "docs/source/_static/notebooks/sympy-expressions.ipynb", "max_stars_repo_name": "quantopian-enterprise/blaze", "max_stars_repo_head_hexsha": "6b686bed87993494b11676ed25e7b30f18ca2248", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2106, "max_stars_repo_stars_event_min_datetime": "2015-08-20T11:53:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T19:42:11.000Z", "max_issues_repo_path": "docs/source/_static/notebooks/sympy-expressions.ipynb", "max_issues_repo_name": "quantopian-enterprise/blaze", "max_issues_repo_head_hexsha": "6b686bed87993494b11676ed25e7b30f18ca2248", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 479, "max_issues_repo_issues_event_min_datetime": "2015-08-20T06:09:38.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-21T13:44:57.000Z", "max_forks_repo_path": "docs/source/_static/notebooks/sympy-expressions.ipynb", "max_forks_repo_name": "quantopian-enterprise/blaze", "max_forks_repo_head_hexsha": "6b686bed87993494b11676ed25e7b30f18ca2248", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 280, "max_forks_repo_forks_event_min_datetime": "2015-08-20T08:42:01.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-16T08:05:19.000Z", "avg_line_length": 21.0929648241, "max_line_length": 114, "alphanum_fraction": 0.41048243, "converted": true, "num_tokens": 655, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9609517028006208, "lm_q2_score": 0.9086179000259899, "lm_q1q2_score": 0.8731379182250992}} {"text": "# Lab 4\n## Introduction\nThe Euler method is a method for numerically solving a DE of the form\n\\begin{align}\n\\frac{\\mathrm{d}y}{\\mathrm{d}x} = f(x,y).\n\\end{align}\n\nIt is often necessary to solve DEs this way as analytical solutions are the exception\nrather than the rule.\n\n\n\nEuler’s method works by approximating small segments of the curve solution to the DE\nwith the straight-line tangent or slope of the curve. As long as we keep the segments\nsmall enough, they will approximately match what the actual curve looks like. It requires us to ”know” an initial value $y(x_0) = y_0$ so we can start the calculation.\n\nTo calculate the first segment we start off with our known start point $(x_0, y_0)$, and calculate the end point, $(x_1, y_1)$. We can define $\\Delta x$ to be some constant small distance so that we always increment the $x$ value by the same amount. Then, $\\Delta y = m \\Delta x$ and $(x_1, y_1)=(x_0, y_0)+(\\Delta x, m\\Delta x)$.\n\n\n\nBut, we also know that $m$, the slope of the line, is given by $\\mathrm{d}y/\\mathrm{d}x$, i.e., $f(x, y)$ evaluated at $(x_0, y_0)$. So actually, $\\Delta y = f(x_0, y_0) \\Delta x$.\n\nThe final step is to calculate the new point: the point at the end of the first line segment. This point is then given by $(x_1, y_1) = (x_0 + \\Delta x, y_0 + f(x_0, y_0) \\Delta x)$.\n\nWe then do it again to calculate $(x_2, y_2)$ using $(x_1, y_1)$ as our starting point. We then do it again to calculate $(x_3, y_3)$ using $(x_2, y_2)$ as our starting point and so on.\n\n**Summary:** The Euler method for evaluating a DE of the form\n\\begin{align}\n\\frac{\\mathrm{d}y}{\\mathrm{d}x} = f(x,y).\n\\end{align}\ninvolves the iterative calculation of\n\\begin{align}\nx_{n+1} &= x_n + \\Delta x\\\\\n\\text{and}\\quad y_{n+1} &= y_n + f(x_n,y_n)\\Delta x.\n\\end{align}\n\n### Implementation\n\nFirst import the necessary functions from NumPy and SciPy and set up Plotly.\n\n\n```python\nfrom numpy import arange, empty, exp\nfrom plotly import graph_objs as go\n```\n\nNow let's write a function that implements Euler's method. We will model it on `scipy.integrate.odeint`. We will make slight changes to the parameters because we want to input $\\Delta x$. Note that the string (delimited by triple quotes) immediately after the function definition is a _docstring_. It tells us what the function does and is good programming practice. The prodigious comments in the function body are not generally necessary but are included for you.\n\n\n```python\ndef euler(func, y0, x0, xn, Dx):\n \"\"\"\n Integrate an ordinary differential equation using Euler's method.\n \n Solves the initial value problem for systems of first order ode-s::\n dy/dx = func(y, x).\n \n Parameters\n ----------\n func : callable(y, x)\n Computes the derivative of y at x.\n y0 : float\n Initial condition on y.\n x0 : float\n Initial condition on x.\n xn : float\n Upper limit to value of x.\n Dx : float\n x increment.\n \n Returns\n -------\n x : float\n Array containing the value of x for each value of x0 + n * Dx,\n where n ranges from zero to floor( (xn - x0) / Dx ).\n y : float\n Array containing the value of y for each value of x.\n \"\"\"\n x = arange(x0, xn, Dx) # Create the x array\n y = empty(len(x)) # Create an empty y array of the same length as x\n y[0] = y0 # Set the first value of y to y0\n for n in range(len(x) - 1): # Loop to populate the rest of the values of y\n y[n+1] = y[n] + func(y[n], x[n]) * Dx # Euler's method\n \n return x, y # Return x and y as a pair\n```\n\nFirst try solving\n\\begin{align}\n\\frac{\\mathrm{d}y}{\\mathrm{d}x} = y.\n\\end{align}\nfor $y(0)=1$ for $x$ between 1 and 5 and using $\\Delta x=1$.\n\n\n```python\ndef diff_eq(y, x):\n return y\n\nx, y = euler(diff_eq, 1, 0, 5.01, 1)\n```\n\nWhy was `xn` set to 5.01 rather than 5?\n\nWe know that the analytic solution to the above IVP is $y=\\mathrm{e}^x$, so calculate that as well.\n\n\n```python\nx_analytic = arange(0, 5.01, 0.1)\ny_analytic = exp(x_analytic)\n```\n\nNow plot them both for comparison.\n\n\n```python\nfig = go.Figure()\nfig.add_trace(go.Scatter(x=x, y=y,\n name='Euler'))\nfig.add_trace(go.Scatter(x=x_analytic,\n y=y_analytic,\n name='Truth'))\nfig.show('png')\n```\n\nReproduce the comparison plot below but with $\\Delta x=0.1$.\n\n\n```python\ndef diff_eq(y, x):\n return y\n\nx, y = euler(diff_eq, 1, 0, 5.01, 0.1)\nx_analytic = arange(0, 5.01, 0.1)\ny_analytic = exp(x_analytic)\nfig = go.Figure()\nfig.add_trace(go.Scatter(x=x, y=y,\n name='Euler'))\nfig.add_trace(go.Scatter(x=x_analytic,\n y=y_analytic,\n name='Truth'))\nfig.show('png')\n```\n\n\nIt is possible to quantify the error in the Euler solution compared to the analytic solution. To do this you need to re-calculate the analytic solution at the same $x$ points as you calculated your Euler solution. Then you can do a Mean Squared Error (MSE) comparison between the two.\n\n\n```python\nx, y = euler(diff_eq, 1, 0, 5.01, 1)\ny_analytic = exp(x)\n((y_analytic - y)**2).mean()\n```\n\n\n\n\n 2533.317105161909\n\n\n\nNote that `((y_analytic - y)**2)` returned an `array` object, and then we called the `mean` method that was _bound_ to that object.\n\nWhat is the MSE if $\\Delta x = 0.1$?\n\n\n```python\nx, y = euler(diff_eq, 1, 0, 5.01, 0.1)\ny_analytic = exp(x)\n((y_analytic - y)**2).mean()\n```\n\n\n\n\n 88.60637343780924\n\n\n\n## Exercises\n\nIn this lab you will try Euler's method for a couple of differential equations.\n\n1. a. Consider the IVP\n\\begin{align}\n\\frac{\\mathrm{d}y}{\\mathrm{d}x} = 2x\\quad\\text{where}\\quad y(-2)=4.\n\\end{align}\nCalculate the Euler approximation on the interval $x=[-2,2]$ using a step size of $\\Delta x = 0.5$. On the same figure, plot your approximation and the analytic solution.\n\n\n```python\ndef diff_eq(y, x):\n return 2*x\n\nx, y = euler(diff_eq, 4, -2, 2.01, 0.5)\nx_analytic = arange(-2.01, 2.01, 0.5)\ny_analytic = (x_analytic**2)\nfig = go.Figure()\nfig.add_trace(go.Scatter(x=x, y=y,\n name='Euler'))\nfig.add_trace(go.Scatter(x=x_analytic,\n y=y_analytic,\n name='Truth'))\nfig.show('png')\n```\n\n1. b. Calculate the mean squared error (MSE) of the approximation.\n\n\n```python\nx, y = euler(diff_eq, 4, -2, 2.01, 0.5)\ny_analytic = exp(x)\n((y_analytic - y)**2).mean()\n```\n\n\n\n\n 9.51151128124883\n\n\n\n1. c. Reproduce your plot from 1a except with $\\Delta x=0.1$.\n\n\n```python\ndef diff_eq(y, x):\n return 2*x\n\nx, y = euler(diff_eq, 4, -2, 2.01, 0.1)\nx_analytic = arange(-2.01, 2.01, 0.1)\ny_analytic = exp(x_analytic)\nfig = go.Figure()\nfig.add_trace(go.Scatter(x=x, y=y,\n name='Euler'))\nfig.add_trace(go.Scatter(x=x_analytic,\n y=y_analytic,\n name='Truth'))\nfig.show('png')\n```\n\n1. d. Recalculate the MSE.\n\n\n```python\nx, y = euler(diff_eq, 4, -2, 2.01, 0.1)\ny_analytic = exp(x)\n((y_analytic - y)**2).mean()\n```\n\n\n\n\n 4.21824682630169\n\n\n\n2. a. The following is the DE for the arrow problem from class.\n\\begin{align}\n\\frac{\\mathrm{d}y}{\\mathrm{d}t} = 294\\mathrm{e}^{-0.04t}-245\\quad\\text{where}\\quad y(0)=0\n\\end{align}\nCalculate the Euler approximation to the solution on the interval $t=[0,10]$ with $\\Delta t=0.5$. Plot your approximation and the analytic solution on the same figure.\n\n\n```python\nfrom scipy.integrate import odeint\n \ndef diff_eq(y, x):\n return 294*exp(-0.04*x) - 245\n\nx, y = euler(diff_eq, 0, 0, 10.01, 0.5)\nx_analytic = arange(0, 10.01, 0.1)\ny_analytic = odeint(diff_eq, 0, x_analytic).flatten()\nfig = go.Figure()\nfig.add_trace(go.Scatter(x=x, y=y,\nname='Euler'))\nfig.add_trace(go.Scatter(x=x_analytic,\ny=y_analytic,\nname='Truth'))\nfig.show('png')\n\n```\n\n2. b. Calculate the MSE of the approximation.\n\n\n```python\nx, y = euler(diff_eq, 0, 0, 10.01, 0.5)\ny_analytic = (-7350*exp(-0.04*x)) - 245*x + 7350\n((y_analytic - y)**2).mean()\n```\n\n\n\n\n 221.1226824539981\n\n\n\n2. c. Reproduce your plot from 2a except with $\\Delta t=0.1$.\n\n\n```python\n\nx, y = euler(diff_eq, 0, 0, 10.01, 0.1)\nx_analytic = arange(0, 10.01, 0.1)\ny_analytic = odeint(diff_eq, 0, x_analytic).flatten()\nfig = go.Figure()\nfig.add_trace(go.Scatter(x=x, y=y,\nname='Euler'))\nfig.add_trace(go.Scatter(x=x_analytic,\ny=y_analytic,\nname='Truth'))\nfig.show('png')\n```\n\n2. d. Recalculate the MSE.\n\n\n```python\nx, y = euler(diff_eq, 0, 0, 10.01, 0.1)\ny_analytic = (-7350*exp(-0.04*x)) - 245*x + 7350\n((y_analytic - y)**2).mean()\n```\n\n\n\n\n 8.673112166785117\n\n\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "e1c9161310c446b612ba527ab2934dd5828de176", "size": 248097, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/lab-04.ipynb", "max_stars_repo_name": "18lejoh/mm-labs", "max_stars_repo_head_hexsha": "9cc81a388034c661a1de18921110146424cf41e2", "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": "notebooks/lab-04.ipynb", "max_issues_repo_name": "18lejoh/mm-labs", "max_issues_repo_head_hexsha": "9cc81a388034c661a1de18921110146424cf41e2", "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": "notebooks/lab-04.ipynb", "max_forks_repo_name": "18lejoh/mm-labs", "max_forks_repo_head_hexsha": "9cc81a388034c661a1de18921110146424cf41e2", "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": 333.0161073826, "max_line_length": 43173, "alphanum_fraction": 0.9355131259, "converted": true, "num_tokens": 2783, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308165850443, "lm_q2_score": 0.9353465147977104, "lm_q1q2_score": 0.8730812610976021}} {"text": "```python\n# linear algebra concerns itself with linear systems, but represents them through vector spaces and matrices.\n\n```\n\n\n```python\n# vector is an arrow in space with a specific direction and length, often representing a piece of data.\n# It is the central building block to linear algebra, including matrices and linear transformations. \n\n\n# Declaring a vector in Python using a list\n\nv = [3, 2]\nprint(v)\n```\n\n [3, 2]\n\n\n\n```python\n# Declaring a vector in Python using NumPy\n\nimport numpy as np\nv = np.array([3, 2])\nprint(v)\n\n```\n\n [3 2]\n\n\n\n```python\n# Declaring a 3-dimensional vector in Python using NumPy\n\nv = np.array([4, 1, 2])\nprint(v)\n\n```\n\n [4 1 2]\n\n\n\n```python\n# Adding two vectors in Python using NumPy\n\nfrom numpy import array\nv = array([3,2])\nw = array([2,-1])\n\n# sum the vectors\nv_plus_w = v + w\n\n# display summed vector\nprint(v_plus_w)\n```\n\n [5 1]\n\n\n\n```python\n# Scaling a number in Python using NumPy\n\nv = array([3,1])\n\n# scale the vector\nscaled_v = 2.0 * v\n\n# display scaled vector\nprint(scaled_v)\n```\n\n [6. 2.]\n\n\n\n```python\n# A matrix is a collection of vectors \n# , can have multiple rows and columns,\n# and is a convenient way to package data. \n```\n\n\n```python\n# Matrix vector multiplication in NumPy\n\n# compose basis matrix with i-hat and j-hat\nbasis = array(\n [[3, 0],\n [0, 2]]\n )\n\n# declare vector v\nv = array([1,1])\n\n# create new vector\n# by transforming v with dot product\nnew_v = basis.dot(v)\n\nprint(new_v)\n```\n\n [3 2]\n\n\n\n```python\n# When thinking in terms of basis vectors,\n# I prefer to break out the basis vectors and then compose them together into a matrix.\n# Just note you will need to transpose, or swap the columns and rows.\n# This is because NumPy’s array() function will do the opposite orientation we want,\n# populating each vector as a row rather than a column.\n\n# Declare i-hat and j-hat\ni_hat = array([2, 0])\nj_hat = array([0, 3])\n\n# compose basis matrix using i-hat and j-hat\n# also need to transpose rows into columns\nbasis = array([i_hat, j_hat]).transpose()\n\n# declare vector v\nv = array([1,1])\n\n# create new vector\n# by transforming v with dot product\nnew_v = basis.dot(v)\n\nprint(new_v)\n```\n\n [2 3]\n\n\n\n```python\n# Transforming a vector using NumPy\n\n# Declare i-hat and j-hat\ni_hat = array([2, 0])\nj_hat = array([0, 3])\n\n# compose basis matrix using i-hat and j-hat\n# also need to transpose rows into columns\nbasis = array([i_hat, j_hat]).transpose()\n\n# declare vector v 0\nv = array([2,1])\n\n# create new vector\n# by transforming v with dot product\nnew_v = basis.dot(v)\n\nprint(new_v)\n```\n\n [4 3]\n\n\n\n```python\n# Transformation 1\ni_hat1 = array([0, 1])\nj_hat1 = array([-1, 0])\ntransform1 = array([i_hat1, j_hat1]).transpose()\n\n# Transformation 2\ni_hat2 = array([1, 0])\nj_hat2 = array([1, 1])\ntransform2 = array([i_hat2, j_hat2]).transpose()\n\n# Combine Transformations\ncombined = transform2 @ transform1\n\n# Test\nprint(\"COMBINED MATRIX:\\n {}\".format(combined))\n\nv = array([1, 2])\nprint(combined.dot(v))\n```\n\n COMBINED MATRIX:\n [[ 1 -1]\n [ 1 0]]\n [-1 1]\n\n\n\n```python\n# Determinants describe how much a sampled area in a vector space changes in scale with linear transformations,\n# and this can provide helpful information about the transformation\n\nfrom numpy.linalg import det\n\n\ni_hat = array([3, 0])\nj_hat = array([0, 2])\n\nbasis = array([i_hat, j_hat]).transpose()\n\ndeterminant = det(basis)\n\nprint(determinant)\n```\n\n 6.0\n\n\n\n```python\n# testing for a 0 determinant is highly helpful to determine if a transformation has linear dependence.\n# When you encounter this you will likely find a difficult or unsolvable problem on your hands.\n\ni_hat = array([-2, 1])\nj_hat = array([3, -1.5])\n\nbasis = array([i_hat, j_hat]).transpose()\n\ndeterminant = det(basis)\n\nprint(determinant)\n```\n\n 0.0\n\n\n\n```python\nfrom sympy import *\n\n# 4x + 2y + 4z = 44\n# 5x + 3y + 7z = 56\n# 9x + 3y + 6z = 72\n\nA = Matrix([\n [4, 2, 4],\n [5, 3, 7],\n [9, 3, 6]\n])\n\n# dot product between A and its inverse\n# will produce identity function\ninverse = A.inv()\nidentity = inverse * A\n\n# prints Matrix([[-1/2, 0, 1/3], [11/2, -2, -4/3], [-2, 1, 1/3]])\nprint(\"INVERSE: {}\".format(inverse))\n\n# prints Matrix([[1, 0, 0], [0, 1, 0], [0, 0, 1]])\nprint(\"IDENTITY: {}\".format(identity))\n```\n\n INVERSE: Matrix([[-1/2, 0, 1/3], [11/2, -2, -4/3], [-2, 1, 1/3]])\n IDENTITY: Matrix([[1, 0, 0], [0, 1, 0], [0, 0, 1]])\n\n\n\n```python\n# 4x + 2y + 4z = 44\n# 5x + 3y + 7z = 56\n# 9x + 3y + 6z = 72\nfrom numpy import array\n\nfrom numpy.linalg import inv\n\nA = array([[4, 2, 4],[5, 3, 7],[9, 3, 6]])\n\nB = array([44,56,72])\n\nX = inv(A).dot(B)\n\nprint(X)\n```\n\n [ 2. 34. -8.]\n\n\n\n```python\n# Performing eigendecomposition in NumPy\n\nfrom numpy import array, diag\nfrom numpy.linalg import eig, inv\n\nA = array([\n [1, 2],\n [4, 5]\n])\n\neigenvals, eigenvecs = eig(A)\n\nprint(\"EIGENVALUES\")\nprint(eigenvals)\nprint(\"\\nEIGENVECTORS\")\nprint(eigenvecs)\n```\n\n EIGENVALUES\n [-0.46410162 6.46410162]\n \n EIGENVECTORS\n [[-0.80689822 -0.34372377]\n [ 0.59069049 -0.9390708 ]]\n\n\n\n```python\n# Decomposing and recomposing a matrix in NumPy\n\n\n```\n", "meta": {"hexsha": "b1e4756163d12ab6ce11a5c915bfdade7306184d", "size": 10337, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Maths/Linear Algebra/Linear Algebra.ipynb", "max_stars_repo_name": "rishi9504/Data-Science", "max_stars_repo_head_hexsha": "10344bf641c601bf16451ddd9eaa28ab4c0fc75b", "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": "Maths/Linear Algebra/Linear Algebra.ipynb", "max_issues_repo_name": "rishi9504/Data-Science", "max_issues_repo_head_hexsha": "10344bf641c601bf16451ddd9eaa28ab4c0fc75b", "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": "Maths/Linear Algebra/Linear Algebra.ipynb", "max_forks_repo_name": "rishi9504/Data-Science", "max_forks_repo_head_hexsha": "10344bf641c601bf16451ddd9eaa28ab4c0fc75b", "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": 21.6708595388, "max_line_length": 121, "alphanum_fraction": 0.4757666634, "converted": true, "num_tokens": 1658, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.945801271704518, "lm_q2_score": 0.9230391568941467, "lm_q1q2_score": 0.8730116084235501}} {"text": "# Least Squares Regression\n\nWe're going to tackle one of the most simple and yet powerful tool of Machine Learning, the Least Squares estimator. Given a function in the shape of \n\n\\begin{equation}\n\\hat y = w^T\\Phi\\left(x\\right) + b \\label{linear}\n\\end{equation}\n\nwhere $\\hat y, b \\in \\mathbb{R}$ and $\\Phi$ is a mapping from our input space to a given feature space such that $\\Phi: \\mathbb{R}^m \\to \\mathbb{R}^n$, we want to estimate the optimal $w$ which minimizes\n\n\\begin{equation}\ne = \\sum^{N}_{i = 1} \\left(y - \\hat y\\right)^2 \\label{sse}\n\\end{equation}\n\n## Problem: fit the a straight line through a number of points\n\nThis is the most basic and common use case, so we need to see it in action. Let's generate a number of random points between $\\left[0, 1\\right]$ according to the following model\n\n\\begin{equation}\ny = 2x + 1 + e\n\\end{equation}\n\nwhere $e \\sim \\mathcal{N} \\left(0, 0.2^2\\right)$. In this case $w \\in \\mathbb{R}$ and is equal to $2$, $x \\in \\mathcal{U} \\left(0, 1\\right)$ and $b=1$\n\n\n\n```python\n%matplotlib inline\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\nn = 100\nx = np.random.uniform(size=n)\ne = np.random.normal(scale=0.2, size=n)\ny = 2*x + 1 + e\n\n#\nplt.scatter(x=x, y=y)\nplt.show()\n\n```\n\n### How to find the best $w$ and $b$?\n\nLet's derive this one time so that you understand the most basic concepts of all these algorithms. We are interested in finding the weight vector $w$ which minimizes the sum of the square error\n\n\\begin{equation}\n\\underset{w}{\\operatorname{argmin}} e = \\sum^{N}_{i = 1} \\left(y_i - w^T \\Phi(x_i) - b \\right)^2 \n\\end{equation}\n\nWe can augment $w$ such that $w_0 = b$ and $w \\in \\mathbb{R}^{n+1}$ and rerite the expression above as\n\n\\begin{equation}\n\\underset{w}{\\operatorname{argmin}} e = \\sum^{N}_{i = 1} \\left(y_i - w^T \\left[\\begin{matrix}\\Phi(x_i) \\\\ 1 \\end{matrix} \\right] \\right)^2 \n\\end{equation}\n\n\nSince the equation is linear, it has a closed-form solution. Let's start by finding the $w$ which gives as a null gradient. We're also going to make use of an important property of matrix derivatives, in this case applied to vectors\n\n\\begin{equation}\n\\frac{d x^Ta}{dx} = a\n\\end{equation}\n\nfor $a, x \\in \\mathbb{R}^n$.\n\n\\begin{eqnarray}\n\\frac{d}{dw} \\sum^{N}_{i = 1} \\left(y_i - w^T \\left[\\begin{matrix}\\Phi(x_i) \\\\ 1 \\end{matrix} \\right] \\right)^2 & = & 0 \\\\\n\\sum^{N}_{i = 1} \\frac{d}{dw} \\left(y_i - w^T \\left[\\begin{matrix}\\Phi(x_i) \\\\ 1 \\end{matrix} \\right] \\right)^2 & = & 0 \\\\\n\\sum^{N}_{i = 1} -2 \\left[\\begin{matrix}\\Phi(x_i) \\\\ 1 \\end{matrix} \\right] \\left(y_i - w^T \\left[\\begin{matrix}\\Phi(x_i) \\\\ 1 \\end{matrix} \\right] \\right) & = & 0 \\\\\n\\sum^{N}_{i = 1} \\left[\\begin{matrix}\\Phi(x_i) \\\\ 1 \\end{matrix} \\right] \\left(\\left[\\begin{matrix}\\Phi(x_i)^T & 1 \\end{matrix} \\right] w - y_i\\right) & = & 0 \\\\\n\\sum^{N}_{i = 1} \\left[\\begin{matrix}\\Phi(x_i) \\\\ 1 \\end{matrix} \\right] \\left[\\begin{matrix}\\Phi(x_i)^T & 1 \\end{matrix} \\right] w & = & \\sum^{N}_{i = 1} \\left[\\begin{matrix}\\Phi(x_i) \\\\ 1 \\end{matrix} \\right] y_i \\\\\n\\sum^{N}_{i = 1} \\left[\\begin{matrix}\\Phi(x_i)\\Phi(x_i)^T & \\Phi(x_i) \\\\ \\Phi(x_i)^T & 1 \\end{matrix} \\right] w & = & \\sum^{N}_{i = 1} \\left[\\begin{matrix}\\Phi(x_i) \\\\ 1 \\end{matrix} \\right] y_i \\\\\n \\left[\\begin{matrix}\\sum^{N}_{i = 1} \\Phi(x_i)\\Phi(x_i)^T & \\sum^{N}_{i = 1} \\Phi(x_i) \\\\ \\sum^{N}_{i = 1} \\Phi(x_i)^T & N \\end{matrix} \\right] w & = & \\left[\\begin{matrix} \\sum^{N}_{i = 1}\\Phi(x_i) y_i \\\\ \\sum^{N}_{i = 1}y_i \\end{matrix} \\right]\n\\end{eqnarray}\n\nresulting of course in\n\n\\begin{equation}\n w = \\left[\\begin{matrix}\\sum^{N}_{i = 1} \\Phi(x_i)\\Phi(x_i)^T & \\sum^{N}_{i = 1} \\Phi(x_i) \\\\ \\sum^{N}_{i = 1} \\Phi(x_i)^T & N \\end{matrix} \\right]^{-1}\\left[\\begin{matrix} \\sum^{N}_{i = 1}\\Phi(x_i) y_i \\\\ \\sum^{N}_{i = 1}y_i \\end{matrix} \\right]\\\\\n\\end{equation}\n\nLet's apply this proof to our case. First we need to figure what is what. We know the data was generated under the following model\n\n\\begin{equation}\ny = 2x + 1\n\\end{equation}\n\nplus some added noise. In this case the $\\Phi(x) = x$, $w = 2$ and $b = 1$.\n\n\n\n\n```python\nX = np.array([[np.dot(x, x), np.sum(x)],[np.sum(x), n]])\nY = np.array([np.dot(x,y), np.sum(y)])\ntheta = np.linalg.solve(X,Y)\nprint(theta)\n```\n\n [1.95328232 0.98646063]\n\n\n\n```python\nplt.plot(x, y, 'o', label='original data')\nplt.plot(x, theta[0]*x + theta[1], 'r', label='fitted line')\nplt.legend()\nplt.show()\n```\n\nScikit already provides linear regression capabilities among others. So everything we went through could have been replaced by\n\n\n```python\nimport sklearn\nfrom sklearn import linear_model\n\nregr = linear_model.LinearRegression()\nregr.fit(x.reshape(-1,1), y)\n\n# The coefficients\nprint('Coefficients: \\n', regr.coef_)\nprint('Intercept: \\n', regr.intercept_)\n```\n\n Coefficients: \n [1.95328232]\n Intercept: \n 0.9864606337778363\n\n\n /usr/local/lib/python3.6/site-packages/scipy/linalg/basic.py:1226: RuntimeWarning: internal gelsd driver lwork query error, required iwork dimension not returned. This is likely the result of LAPACK bug 0038, fixed in LAPACK 3.2.2 (released July 21, 2010). Falling back to 'gelss' driver.\n warnings.warn(mesg, RuntimeWarning)\n\n\n### Normal Equations\n\n\\begin{equation}\n w = \\left[\\begin{matrix}\\sum^{N}_{i = 1} \\Phi(x_i)\\Phi(x_i)^T & \\sum^{N}_{i = 1} \\Phi(x_i)^T \\\\ \\sum^{N}_{i = 1} \\Phi(x_i) & N \\end{matrix} \\right]^{-1}\\left[\\begin{matrix} \\sum^{N}_{i = 1}\\Phi(x_i) y_i \\\\ \\sum^{N}_{i = 1}y_i \\end{matrix} \\right]\\\\\n\\end{equation}\n\nCan be written in another way commonly know as the **normal equations**. Just like before, consider you have $N$ samples and you stack your features and your target like this\n\n\\begin{equation}\nX = \\left[\\begin{matrix}\\Phi(x_1)^T & \\dots & 1 \\\\\n \\vdots & \\ddots & \\vdots \\\\\n \\Phi(x_N)^T & \\dots & 1 \\end{matrix}\\right]\n\\end{equation}\n\n\\begin{equation}\n\\textbf{y} = \\left[\\begin{matrix} y_1 \\\\ \\vdots \\\\ y_N \\end{matrix}\\right]\n\\end{equation}\n\n\nThe best $w$ is given by\n\n\\begin{equation}\n\\hat{w} = (X^TX)^{-1} X^T \\textbf{y}\n\\end{equation}\n\nLet's test it.\n\n\n```python\nX = np.matrix([x, np.ones(len(x))]).T\nY = np.matrix(y).T\nprint(\"X shape:\\n\", X.shape)\nprint(\"Y shape:\\n\", Y.shape)\n\nw = np.linalg.solve(X.T * X, X.T * Y)\nprint(\"w:\\n\", w)\n```\n\n X shape:\n (100, 2)\n Y shape:\n (100, 1)\n w:\n [[1.95328232]\n [0.98646063]]\n\n\n**Homework**: Prove it!\n\n## Issues\n\nIf you run into troubles or find mistakes, bugs, please open an issue on the [issue tracker](https://github.com/SergioRAgostinho/bootstrap-ml/issues).\n\n", "meta": {"hexsha": "6e2866804247c3e5a8579014c4b9b50a4e1396b0", "size": 33988, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "least_squares.ipynb", "max_stars_repo_name": "SergioRAgostinho/bootstrap-ml", "max_stars_repo_head_hexsha": "1f96c58ee09a8a7fcb61e5f1017c9dea74c31805", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2018-03-22T10:54:52.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-16T09:55:42.000Z", "max_issues_repo_path": "least_squares.ipynb", "max_issues_repo_name": "SergioRAgostinho/bootstrap-ml", "max_issues_repo_head_hexsha": "1f96c58ee09a8a7fcb61e5f1017c9dea74c31805", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2018-03-22T20:24:35.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-26T09:07:32.000Z", "max_forks_repo_path": "least_squares.ipynb", "max_forks_repo_name": "SergioRAgostinho/bootstrap-ml", "max_forks_repo_head_hexsha": "1f96c58ee09a8a7fcb61e5f1017c9dea74c31805", "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": 114.0536912752, "max_line_length": 14172, "alphanum_fraction": 0.830763799, "converted": true, "num_tokens": 2326, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109784205503, "lm_q2_score": 0.9184802429095673, "lm_q1q2_score": 0.8729337063236267}} {"text": "# Analytical problem\nDefining a problem with an explicit mathematical representation is straightforwars.\n\nAs an example, consider the following multiobjective optimization problem\n\n\\begin{equation}\n\\begin{aligned}\n& \\underset{\\mathbf x}{\\text{min}}\n& & x_1^2 - x_2; x_2^2 - 3x_1 \\\\\n& \\text{s.t.} & & x_1 + x_2 \\leq 10 \\\\\n& & & \\mathbf{x} \\; \\in S, \\\\\n\\end{aligned}\n\\end{equation}\n\nwhere the feasible region is\n\n\\begin{equation}\nx_i \\in \\left[-5, 5\\right] \\; \\forall i \\;\\in \\left[1,2\\right].\n\\end{equation}\n\nBegin by importing the necessary classes:\n\n\n```python\nfrom desdeov2.problem.Problem import ScalarMOProblem\nfrom desdeov2.problem.Objective import ScalarObjective\nfrom desdeov2.problem.Variable import Variable\nfrom desdeov2.problem.Constraint import ScalarConstraint\n```\n\nDefine the variables:\n\n\n```python\n# Args: name, starting value, lower bound, upper bound\nx1 = Variable(\"x_1\", 0, -0.5, 0.5)\nx2 = Variable(\"x_2\", 0, -0.5, 0.5)\n```\n\nDefine the objectives, notice the argument of the callable objective function, it is assumed to be array-like.\n\n\n```python\n# Args: name, callable\nobj1 = ScalarObjective(\"f_1\", lambda x: x[0]**2 - x[1])\nobj2 = ScalarObjective(\"f_2\", lambda x: x[1]**2 - 3*x[0])\n```\n\nDefine the constraints. Constraint may depend on objective function as well (second argument to the lambda, notice the underscore). In that case, the objectives should not be defined inline, like above, but as their own function definitions. The constraint should be defined so, that when evaluated, it should return a positive value, if the constraint is adhered to, and a negative, if the constraint is breached.\n\n\n```python\n# Args: name, n of variables, n of objectives, callable\ncons1 = ScalarConstraint(\"c_1\", 2, 2, lambda x, _: 10 - (x[0] + x[1]))\n```\n\nFinally, put it all together and create the problem.\n\n\n```python\n# Args: list of objevtives, variables and constraints\nproblem = ScalarMOProblem([obj1, obj2]\n ,[x1, x2]\n ,[cons1])\n```\n\nNow, the problem is fully specified and can be evaluated and played around with.\n\n\n```python\nimport numpy as np\n\nprint(\"N of objectives:\", problem.n_of_objectives)\nprint(\"N of variables:\", problem.n_of_variables)\nprint(\"N of constraints:\", problem.n_of_constraints)\n\nres1, eval_cons1 = problem.evaluate(np.array([2, 4]))\nres2, eval_cons2 = problem.evaluate(np.array([6, 6]))\nres3, eval_cons3 = problem.evaluate(np.array([[6, 3], [4,3], [7,4]]))\n\nprint(\"Single feasible decision variables:\", res1, \"with constraint values\", eval_cons1)\nprint(\"Single non-feasible decision variables:\", res2, \"with constraint values\", eval_cons2)\nprint(\"Multiple decision variables:\", res3, \"with constraint values\", eval_cons3)\n```\n", "meta": {"hexsha": "62f4b411b18df3ff4d60773c795725dc6ec5e25e", "size": 4737, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/analytical_problem.ipynb", "max_stars_repo_name": "gialmisi/DESDEOv2", "max_stars_repo_head_hexsha": "0eeb4687d2e539845ab86a5018ff99b92e4ca5cf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-08-08T05:11:21.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-08T05:11:21.000Z", "max_issues_repo_path": "notebooks/analytical_problem.ipynb", "max_issues_repo_name": "gialmisi/DESDEOv2", "max_issues_repo_head_hexsha": "0eeb4687d2e539845ab86a5018ff99b92e4ca5cf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2019-08-25T08:49:33.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-06T08:06:46.000Z", "max_forks_repo_path": "notebooks/analytical_problem.ipynb", "max_forks_repo_name": "gialmisi/DESDEOv2", "max_forks_repo_head_hexsha": "0eeb4687d2e539845ab86a5018ff99b92e4ca5cf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-11-07T14:42:29.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-07T14:42:29.000Z", "avg_line_length": 28.7090909091, "max_line_length": 420, "alphanum_fraction": 0.5685032721, "converted": true, "num_tokens": 751, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9724147193720649, "lm_q2_score": 0.8976952989498448, "lm_q1q2_score": 0.8729321222099352}} {"text": "```python\nimport numpy as np\nimport pandas as pd\nimport statsmodels.api as sm\nimport matplotlib.pyplot as plt\nplt.style.use('classic')\n%matplotlib inline\n```\n\n# Class 10: Stochastic Time Series Processes\n\nMost models of the business cycle are *stochastic* time series models. That is, the models incorporate randomness as a determinant of equilibrium. Randomness is necessary for two reasons. First, from a practical point of view, any model will be incomplete and will not fit the data perfectly and so randomness in a macroeconomic model is analagous to an error term in an OLS model. Second, from a philosophical perspective, randomness in a macroeconomic model reflects economists' consensus that fundamentally unpredictable forces cause the business cycle.\n\n\n## Simulating Normal Random Variables with Numpy\n\nRecall that the `numpy.random` module has functions for generating (pseudo) random variables. Learn more about the module by reading the documentation: https://docs.scipy.org/doc/numpy/reference/routines.random.html\n\nWe use the `numpy.random.normal()` function to crate arrays of random draws from the normal distribution. The function takes three arguments:\n* `loc`: the mean of the distribution (default=0)\n* `scale`: the standard deviation of the distribution (default=1)\n* `size`: how many to numbers to draw (default = `None`)\n\nThe default is to draw numbers from the *standard normal* distribution.\n\n### Example\n\nDraw 500 values each from the $\\mathcal{N}(0,1)$ and $\\mathcal{N}(0,2^2)$ distributions. Plot.\n\n\n```python\n# Set the seed for the random number generator to 126\nnp.random.seed(126)\n\n# Create two arrays:\n# x: 500 draws from the normal(0,1) distribution\n# y: 500 draws from the normal(0,4) distribution\nx = np.random.normal(loc=0,scale=1,size=500)\ny = np.random.normal(loc=0,scale=2,size=500)\n\n# Plot x and y\nplt.plot(x,lw=2,alpha = 0.6,label='$\\sigma=1$')\nplt.plot(y,lw=2,alpha = 0.6,label='$\\sigma=2$')\nplt.legend(loc='center left', bbox_to_anchor=(1, 0.5))\nplt.grid()\n```\n\n## The White Noise Process\n\nIn the previous example, we created two variables that stored draws from normal distrbutions with means of zero but with different standard deviations. Both of the variables were simulations of *white noise processes*. A white noise process is a random variable $\\epsilon_t$ with constant mean and constant variance. We are concerned only with the zero-mean white noise process and we'll denote that a variable is a zero-mean white noise process with the following shorthand notation:\n\n\\begin{align}\n\\epsilon_t & \\sim \\text{WN}(0,\\sigma^2),\n\\end{align}\n\nwhere $\\sigma^2$ is the variance of the processes. Strictly speaking, a white noise process can follow any distribution as long as the mean and variance are constant, but we'll concentrate exclusively white noise process drawn from the normal distribution.\n\n## The AR(1) Process\n\nA random variable $y_t$ is an *autoregressive process of order 1* or AR(1) process if it can be written in the following form:\n\n\\begin{align}\ny_t & = \\rho y_{t-1} + \\epsilon_t,\n\\end{align}\n\nwhere $\\rho$ is a constant and $\\epsilon \\sim \\text{WN}(0,\\sigma^2)$. The AR(1) process is the stochastic analog of the first-order difference equation where the random variable $\\epsilon_t$ replaces the exogenous variable $w_t$.\n\n### Example\n\nSimulate an AR(1) process for 101 periods ($t = 0,\\ldots, 100$) using the following parameter values:\n\n\\begin{align}\n\\rho & = 0.5\\\\\n\\sigma & = 1\\\\\ny_0 & = 0\n\\end{align}\n\nPlot the simulated values for $y$.\n\n\n```python\n# Set the seed for the random number generator to 126\nnp.random.seed(126)\n\n# Initialize values for T, y0, rho, and sigma\nT = 101\ny0 = 0\nrho = 0.5\nsigma = 1\n\n# Initialize an array of zeros for y\ny = np.zeros(T)\n\n# Set the first value of y equal to y0\ny[0] = y0\n\n# Create a variable called 'epsilon' equal to an array containing T draws from the normal(0,sigma^2) process\neps= np.random.normal(loc=0,scale=sigma,size=T)\n\n# Iterate over t in range(T-1) to compute y\nfor t in range(T-1):\n y[t+1] = rho*y[t] + eps[t+1]\n \n# Plot y\nplt.plot(y,lw=2)\nplt.grid(linestyle=':')\n```\n\nThe AR(1) process wtih $\\rho = 0.5$ seems to fluctuate around the value $y=0$ and so the process appears to be stable.\n\n### Example\n\nSimulate an AR(1) process for 101 periods ($t = 0,\\ldots, 100$) using the following parameter values:\n\n\\begin{align}\n\\rho & = 1.5\\\\\n\\sigma & = 1\\\\\ny_0 & = 0\n\\end{align}\n\nPlot the simulated values for $y$.\n\n\n```python\n# Set the seed for the random number generator to 126\nnp.random.seed(126)\n\n# Initialize values for T, y0, rho, and sigma\nT = 101\ny0 = 0\nrho = 1.5\nsigma = 1\n\n# Initialize an array of zeros for y\ny = np.zeros(T)\n\n# Set the first value of y equal to y0\ny[0] = y0\n\n# Create a variable called 'epsilon' equal to an array containing T draws from the normal(0,sigma^2) process\neps= np.random.normal(loc=0,scale=sigma,size=T)\n\n# Iterate over t in range(T-1) to compute y\nfor t in range(T-1):\n y[t+1] = rho*y[t] + eps[t+1]\n \n# Plot y\nplt.plot(y,lw=2)\nplt.grid(linestyle=':')\n```\n\nThe AR(1) process wtih $\\rho = 1.5$ seems to be approaching infinity in magnitude and so the process appears to be explosive.\n\nIn general, like the first-order difference equation, if $|\\rho| < 1$, the the AR(1) process is stable. If $|\\rho|>1$ then the process is explosive. A special case is the *random walk process* which is an AR(1) process with $\\rho = 1$. The random walk process has many important applications including asset pricing theory.\n\nThe function in the next cell computes a simulation of an AR(1) process.\n\n\n```python\n# Define a function for simulating an AR(1) process. CELL PROVIDED\ndef ar1_sim(rho=0,sigma=1,y0=0,T=25):\n '''Funciton for simulating an AR(1) process for T periods\n \n Args:\n rho (float): autoregressive parameter\n sigma (float): standard deviation of the white noise process\n y0 (float): initial value of the process\n T (int): number of periods to simulate\n \n Returns:\n numpy array\n '''\n \n # initialize y array\n y = np.zeros(T)\n y[0] = y0\n \n # draw random numbers for white noise process\n eps= np.random.normal(loc=0,scale=sigma,size=T-1)\n for t in range(T-1):\n y[t+1] = rho*y[t] + eps[t]\n \n return y\n```\n\n### Example:\n\nUse the `ar1_sim()` function to simulate an AR(1) process for 201 periods ($t = 0,\\ldots, 200$) using the following parameter values:\n\n\\begin{align}\n\\rho & = -0.99\\\\\n\\sigma & = 0.5\\\\\ny_0 & = 0\n\\end{align}\n\nSet the seed for the NumPy random number generator to 126. Plot the simulated values for $y$.\n\n\n```python\n# Set the seed for the random number generator to 126\nnp.random.seed(126)\n\n# Simulate y and plot\ny = ar1_sim(rho=-0.99,sigma=0.5,y0=0,T=201)\nplt.plot(y)\nplt.grid()\n```\n\n## Application: Estimate TFP as an AR(1) process\n\nIt is routine to model quarterly fulctuations in TFP as an AR(1) process and we will encounter this in our business cycle models. Here we will fit the following AR(1) model to US data:\n\n\\begin{align}\n\\log\\left(A_t/A^{trend}_t\\right) & = \\rho \\log\\left(A_{t-1}/A^{trend}_{t-1}\\right) + \\epsilon_t\n\\end{align}\n\nwhere $\\log\\left(A_t/A^{trend}_t\\right) = \\log A_t - \\log A^{trend}$ is the log-deviation of TFP from its trend and $\\epsilon_t$ is a white noise process with mean 0 and variance $\\sigma^2$.\n\n\n### The Data\nThe file `rbc_data_actual_trend.csv`, available at https://github.com/letsgoexploring/econ126/raw/master/Data/Csv/rbc_data_actual_trend.csv, contains actual and trend data for real GDP per capita, real consumption per capita, real investment per capita, real physical capital per capita, TFP, and hours per capita at quarterly frequency. The GDP, consumption, investment, and capital data are in terms of 2012 dollars. Hours is measured as an index with the value in October 2012 set to 100. All of the data are *real* quantities. That is, there are no *nominal* quantities like money or inflation or a nominal interest rate. The reason is that the first theory that we will encounter is called *real business cycle* or RBC theory and, in that theory, there is no place for nominal quantities. RBC theory seeks to explain fluctuations in real quantities as being primarily due to TFP shocks; i.e., shocks to the production function.\n\n### Objectives\n\n1. Import TFP data (trend and actual) and compute cyclical component as log-deviation from trend.\n2. Construct a scatter plot of log-deviation of TFP from trend against *lagged* log-deviation of TFP from trend.\n3. Estimate the AR(1) model of log-deviation of TFP from trend to obtain estimates of $\\rho$ and $\\sigma$.\n\n\n```python\n# Read business_cycle_data_actual_trend.csv into a Pandas DataFrame called 'df' with the first column set as the index and parse_dates=True\ndf = pd.read_csv('https://github.com/letsgoexploring/econ126/raw/master/Data/Csv/rbc_data_actual_trend.csv',index_col=0,parse_dates=True)\n```\n\n\n```python\n# Construct a plot of TFP with its trend with:\n# 1. Actual line: blue with lw=1, alpha=0.7, label = 'actual'\n# 2. Trend line: red with lw=3, alpha=0.7, label = 'trend'\nplt.plot(df['tfp'],lw=2,alpha=0.6,label='Actual')\nplt.plot(df['tfp_trend'],'r',lw=2,alpha=0.6,label='Trend')\nplt.title('TFP for US from '+df.index[0].strftime('%B %Y')+' to '+df.index[-1].strftime('%B %Y'))\nplt.legend(loc='center left', bbox_to_anchor=(1, 0.5))\nplt.grid()\n```\n\nNow we need to compute the log-deviation of TFP from its trend. Note that since $\\log(a/b) = \\log(a) - \\log(b)$, we can write:\n\n\\begin{align}\n\\log A_t - \\log A^{trend} & = \\log\\left(A_t/A^{trend}_t\\right)\n\\end{align}\n\nThe term on the right will make the AR(1) model easier to read.\n\n\n\\begin{align}\n\\log\\left(A_t/A^{trend}_t\\right) & = \\rho \\log\\left(A_{t-1}/A^{trend}_{t-1}\\right) + \\epsilon_t\n\\end{align}\n\n\n\n\n\n```python\n# Create a new column to df called tfp_cycle equal to the log difference between actual TFP and it's trend:\ndf['tfp_cycle'] = np.log(df['tfp']/df['tfp_trend'])\n```\n\n\n```python\n# Plot the log deviation of TFP from its trend (times 100)\nplt.plot(df['tfp_cycle'],lw=2,alpha=0.6)\nplt.title('TFP for US from '+df.index[0].strftime('%B %Y')+' to '+df.index[-1].strftime('%B %Y'))\nplt.grid()\n```\n\n\n```python\n# Create a new column to df called tfp_cycle_lag that, for each date, contains values \n# in 'tfp_cycle' at the previous date\ndf['tfp_cycle_lag'] = df['tfp_cycle'].shift()\n\n# Print the first five rows of only the 'tfp_cycle' and 'tfp_cycle_lag' columns. PROVIDED\nprint(df[['tfp_cycle','tfp_cycle_lag']].head())\n```\n\n tfp_cycle tfp_cycle_lag\n 1948-01-01 0.003250 NaN\n 1948-04-01 0.009117 0.003250\n 1948-07-01 -0.001220 0.009117\n 1948-10-01 -0.005680 -0.001220\n 1949-01-01 -0.019553 -0.005680\n\n\nNotice that there is a missing value inthe `tfp_cycle_lag` column for the first date in the index because there is no prior observation in the `tfp_cycle` column. To proceed with the estimation, we need to get rid of the row with missing values.\n\n\n```python\n# Use dropna() method on df to remove the row iwth the missing value\ndf= df.dropna()\n\n# Print the first five rows of only the 'tfp_cycle' and 'tfp_cycle_lag' columns. PROVIDED\nprint(df[['tfp_cycle','tfp_cycle_lag']].head())\n```\n\n tfp_cycle tfp_cycle_lag\n 1948-04-01 0.009117 0.003250\n 1948-07-01 -0.001220 0.009117\n 1948-10-01 -0.005680 -0.001220\n 1949-01-01 -0.019553 -0.005680\n 1949-04-01 -0.020787 -0.019553\n\n\nNext, we should make a scatter plot of log-deviation of TFP from trend against the one-period lag of log-deviation of TFP from trend to see if out AR(1) model is a good idea.\n\n\n```python\n# Construct a scatter plot of log-deviation of TFP from trend against the one-period lag of log-deviation \n# of TFP from trend with:\n# 1. scatter points sized at least 50, opacity (alpha) no greater than 0.25\n# 2. x- and y-axis limits: [-0.04,0.04]\nplt.scatter(df['tfp_cycle_lag'],df['tfp_cycle'],s=50,alpha=0.25)\nplt.xlabel('Lag log-deviation from trend')\nplt.ylabel('Current log-deviation from trend')\nplt.title('TFP for US from '+df.index[0].strftime('%B %Y')+' to '+df.index[-1].strftime('%B %Y'))\nplt.xlim([-0.04,0.04])\nplt.ylim([-0.04,0.04])\nplt.grid()\n```\n\nNow we use StatsModels to fit the model. First we estimate the AR(1) model to obtain an estimate of $\\rho$. Then we find the standard deviation of the residuals of the regression to estimate $\\sigma$.\n\n\n```python\n# Create a variable 'X' to be the independent variable of the OLS model. Do not add a constant to X\nX = df['tfp_cycle_lag']\n\n# Create a variable 'Y' to be the dependent variable of the OLS model.\nY = df['tfp_cycle']\n\n# Create a variable called 'model' that initializes the OLS model\nmodel = sm.OLS(Y,X)\n\n# Create a variable called 'results' that stores the results of the estimated OLS model\nresults = model.fit()\n\n# Print output of summary2() method of results\nprint(results.summary2())\n```\n\n Results: Ordinary least squares\n ================================================================================\n Model: OLS Adj. R-squared (uncentered): 0.553 \n Dependent Variable: tfp_cycle AIC: -2130.2726\n Date: 2021-02-04 15:30 BIC: -2126.6028\n No. Observations: 290 Log-Likelihood: 1066.1 \n Df Model: 1 F-statistic: 360.3 \n Df Residuals: 289 Prob (F-statistic): 1.01e-52 \n R-squared (uncentered): 0.555 Scale: 3.7653e-05\n ------------------------------------------------------------------------------------\n Coef. Std.Err. t P>|t| [0.025 0.975]\n ------------------------------------------------------------------------------------\n tfp_cycle_lag 0.7463 0.0393 18.9804 0.0000 0.6689 0.8237\n --------------------------------------------------------------------------------\n Omnibus: 4.758 Durbin-Watson: 1.834\n Prob(Omnibus): 0.093 Jarque-Bera (JB): 5.687\n Skew: -0.127 Prob(JB): 0.058\n Kurtosis: 3.637 Condition No.: 1 \n ================================================================================\n \n\n\nEstimated coefficients are stored as a Pandas `Series` in the `params` attribute of `results`. Index values correspond to names of columns in the dependent variable `X`\n\n\n```python\n# Print the contents of the params method of results\nprint(results.params)\n```\n\n tfp_cycle_lag 0.746324\n dtype: float64\n\n\n\n```python\n# Create a variable called 'rho' that equals the value of the estimated coefficient on df['tfp_cycle_lag']\nrho = results.params['tfp_cycle_lag']\n```\n\nThe residuals from the regression are stored in an attribute of `results` called `resid`\n\n\n```python\n# Create a variable called 'sigma' that equals the standard deviation of the residuals of the regression\nsigma = results.resid.std()\n\n# Print the value of sigma\nprint(sigma)\n```\n\n 0.00613621877954209\n\n\nAnd that's how you estimate the parameters of an AR(1) model of the cyclical component of TFP for the US.\n\n## Application: A Stochastic Solow Growth Model (Optional)\n\nConsider the Solow growth model with written in \"per worker\" terms:\n\n\\begin{align}\ny_t & = A_tk_t^{\\alpha}\\\\\nk_{t+1} & = i_t + (1-\\delta)k_{t}\\\\\ny_t & = c_t + i_t\\\\\nc_t & = (1-s)y_t,\n\\end{align}\n\nwhere $y_t$ is output per worker, $k_t$ is capital per worker, $c_t$ is consumption per worker, $i_t$ is investment per worker, and $A_t$ is time-varying TFP. Assume:\n\n\\begin{align}\n\\log A_{t+1} & = \\rho \\log A_{t} + \\epsilon_{t+1}\n\\end{align}\n\nwhere $\\epsilon_t$ is a white noise process with mean 0 and variance $\\sigma^2$. Since capital and TFP are the only two variables, that depend on past value of themselves, they are the two state variables of the model. Therefore, we can simulate simulate the model in two steps. First, simulate $k_t$ and $A_t$ using the following two laws of motion:\n\n\\begin{align}\nk_{t+1} & = sAk_t^{\\alpha} + (1-\\delta)k_{t} \\label{eqn:capital_solution}\\\\\n\\log A_{t+1} & = \\rho \\log A_{t} + \\epsilon_{t+1}. \\label{eqn:tfp_solution}\n\\end{align}\n\nSecond, compute simulated values for $y_t$, $c_t$, and $i_t$ using the following static relationships:\n\n\\begin{align}\ny_t & = A_tk_t^{\\alpha}\\\\\ni_t & = sA_tk_t^{\\alpha}\\\\\nc_t & = (1-s)A_tk_t^{\\alpha},\n\\end{align}\n\nIn the previous example, we estimated $\\rho$ and $\\sigma$ for the US so let's use those values for this simulation. For the other parameter, use the following values for the simulation:\n\n| $$A_0$$ | $$k_0$$ | $$s$$ | $$\\alpha$$ | $$\\delta $$ | $$T$$ |\n|---------|---------|-------|------------|-------------|--------|\n| 1 | 8.43 | 0.1 | 0.35 | 0.025 | 201 |\n\nWhere $T$ is the total number of simulation periods (i.e., $t$ will range from $0$ to $200$).\n\n### Function\n\nThe function in the next cell simulates a stochastic Solow growth model. It returns a `DataFrame` with columns equal to the log-deviations of the simulated variables relative to the trend (i.e., nonstochastic steady state) implied by the model.\n\n\n```python\n# Define a function that returns a DataFrame of simulated value from the Solow model with exogenous labor and TFP growth. CELL PROVIDED\ndef solow_stochastic(s,alpha,delta,k0,A0,rho,sigma,T):\n \n '''Function for computing a simulation of the Solow growth model with exogenous labor and TFP growth.\n \n y[t] = A[t]*K[t]^alpha\n k[t+1] = i[t] + (1-delta)*k[t]\n y[t] = c[t] + i[t]\n c[t] = (1-s)*y[t]\n A[t+1] = exp(rho*logA[t] + epsilon[t+1])\n \n Args:\n s (float): Saving rate\n alpha (float): Capital share in Cobb-Douglas production function\n delta (float): Capital depreciation rate\n T (int): Number of periods to simulate\n k0 (float): Initial value of capital per worker\n A0 (float): Initial TFP\n rho (float): AR coeficient for log A[t]\n sigma (float): Standard deviation of shock to log A[t]\n \n Returns:\n Pandas DataFrame\n '''\n # Create epsilon values\n epsilon = np.random.normal(scale=sigma,size=T)\n \n # Initialize capital values\n capital = np.zeros(T)\n\n # Set first value of capital equal to k0\n capital[0] = k0\n \n # Initialize TFP values\n tfp = np.zeros(T)\n\n # Set first value of TFP equal to A0\n tfp[0] = A0\n\n # Iterate over t in range(T-1) to update subsequent values in the capital and tfp arrays\n for t in range(T-1):\n capital[t+1] = s*tfp[t]*capital[t]**alpha + (1-delta)*capital[t]\n tfp[t+1] = np.exp(rho*np.log(tfp[t]) + epsilon[t])\n \n # Compute the values of the other aggregate variables\n output = tfp*capital**alpha\n consumption = (1-s)*output\n investment = s*output\n \n # Compute steady state (or trend) of endogenous vars\n capital_ss = (s/delta)**(1/(1-alpha))\n tfp_ss = 1 \n output_ss = tfp_ss*capital_ss**alpha\n consumption_ss = (1-s)*output_ss\n investment_ss = s*output_ss\n \n \n # Put simulated data into a DataFrame\n df = pd.DataFrame({'output_log_dev':np.log(output/output_ss),\n 'consumption_log_dev':np.log(consumption/consumption_ss),\n 'investment_log_dev':np.log(investment/investment_ss),\n 'capital_log_dev':np.log(capital/capital_ss),\n 'tfp_log_dev':np.log(tfp/tfp_ss)})\n \n # Return the simulated data\n return df\n```\n\n### Simulate the Stochastic Solow Model\n\n\n```python\n# CELL PROVIDED\n# Set parameters for simulation\nalpha=0.35\ns = 0.1\ndelta = 0.025\nk0 = 8.43\nA0=1\nT = 201\n\nnp.random.seed(126)\n# Simulate the model and store output in a variable called 'solow_df'\nsolow_df = solow_stochastic(s,alpha,delta,k0,A0,rho,sigma,T)\n\n# Plot\nfig = plt.figure()\nax = fig.add_subplot(1,1,1)\nsolow_df.plot(ax=ax,grid=True)\nax.legend(loc='center left', bbox_to_anchor=(1, 0.5))\n```\n\n### Simulation Results\n\nCompute the standard deviation of the simulated data and the correlation coefficients of the simulated data.\n\n\n```python\n# Standard deviations. CELL PROVIDED\nsolow_df.std()*100\n```\n\n\n\n\n output_log_dev 0.837875\n consumption_log_dev 0.837875\n investment_log_dev 0.837875\n capital_log_dev 0.187482\n tfp_log_dev 0.829267\n dtype: float64\n\n\n\n\n```python\n# Correlation coefficients. CELL PROVIDED\nsolow_df.corr()\n```\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
output_log_devconsumption_log_devinvestment_log_devcapital_log_devtfp_log_dev
output_log_dev1.0000001.0000001.0000000.1696560.996955
consumption_log_dev1.0000001.0000001.0000000.1696560.996955
investment_log_dev1.0000001.0000001.0000000.1696560.996955
capital_log_dev0.1696560.1696560.1696561.0000000.092288
tfp_log_dev0.9969550.9969550.9969550.0922881.000000
\n
\n\n\n\nIt looks like the stochastic Solow model does a good job replicating the volatility (standard deviation) of ouput and consumption relative to the data. However the simulated investment volatility is too small by about a factor of 6. The stochastic Solow model does capture the correlation between output, consumption, and investment, but it implies perfect correlation which is too much.\n\n## The Random Walk Process (Optional)\n\nThe *random walk process* is an AR(1) process with $\\rho=1$:\n\n\\begin{align}\ny_t = y_{t-1} + \\epsilon_t\n\\end{align}\n\nThe random walk process has an important place in finance since the evidence suggests that stock prices follow a random walk process.\n\n### Example\n\nSimulate 7 random walk processes for 501 periods. Set $\\sigma = 1$. Plot all 7 simulated processes on the same axes.\n\n\n```python\n# CELL PROVIDED \nnp.random.seed(126)\nfor i in range(7):\n plt.plot(ar1_sim(rho=1,T=501))\n \nplt.title('Seven random walk processes')\nplt.grid()\n```\n", "meta": {"hexsha": "ea9b28448af9db5662a4b389faf0fe4d01adc7d4", "size": 374417, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Lecture Notebooks/Econ126_Class_10.ipynb", "max_stars_repo_name": "letsgoexploring/econ126", "max_stars_repo_head_hexsha": "05f50d2392dd1c7c38b14950cb8d7eff7ff775ee", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-12-12T16:28:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-24T12:11:04.000Z", "max_issues_repo_path": "Lecture Notebooks/Econ126_Class_10.ipynb", "max_issues_repo_name": "letsgoexploring/econ126", "max_issues_repo_head_hexsha": "05f50d2392dd1c7c38b14950cb8d7eff7ff775ee", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-04-29T08:50:41.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-29T08:51:05.000Z", "max_forks_repo_path": "Lecture Notebooks/Econ126_Class_10.ipynb", "max_forks_repo_name": "letsgoexploring/econ126", "max_forks_repo_head_hexsha": "05f50d2392dd1c7c38b14950cb8d7eff7ff775ee", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 19, "max_forks_repo_forks_event_min_datetime": "2019-03-08T18:49:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T23:27:16.000Z", "avg_line_length": 351.8956766917, "max_line_length": 62956, "alphanum_fraction": 0.9230029619, "converted": true, "num_tokens": 6604, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9539660976007597, "lm_q2_score": 0.9149009526726545, "lm_q1q2_score": 0.8727844915123495}} {"text": "# SymPy demo\n\nIf you need to install SymPy:\n\n pip install sympy\n\n\n```python\nimport sympy\nsympy.__version__\n```\n\n\n\n\n '1.6.2'\n\n\n\n\n```python\nsympy.init_printing(use_latex='mathjax')\n```\n\n## Rearrange and simplify equations\n\nWe have an expression for Vp in terms of Young's modulus, $E$, and shear modulus, $\\mu$:\n\n$$ V_\\mathrm{P} = \\sqrt{\\frac{\\mu\\,(E-4\\mu)}{\\rho\\,(E-3\\mu)}} $$\n\nWe need single symbols for quantities, so I'll use $\\alpha$ for $V_\\mathrm{P}$ and $\\beta$ for $V_\\mathrm{S}$, and $\\gamma$ for their ratio.\n\n\n```python\nalpha, beta, gamma = sympy.symbols(\"alpha, beta, gamma\")\nlamda, mu, E, K, M, rho = sympy.symbols(\"lamda, mu, E, K, M, rho\")\n```\n\nNow we can use these symbols to make an expression.\n\n\n```python\nfrom sympy import sqrt\n\nalpha_expr = sqrt((mu * (E - 4*mu)) / (rho * (E - 3*mu)))\nalpha_expr\n```\n\n\n\n\n$\\displaystyle \\sqrt{\\frac{\\mu \\left(E - 4 \\mu\\right)}{\\rho \\left(E - 3 \\mu\\right)}}$\n\n\n\n\n```python\nprint(sympy.latex(alpha_expr))\n```\n\n \\sqrt{\\frac{\\mu \\left(E - 4 \\mu\\right)}{\\rho \\left(E - 3 \\mu\\right)}}\n\n\nWe also know that\n\n$$ \\mu = \\frac{3KE}{9K-E} $$\n\n\n```python\nmu_expr = (3 * K * E) / (9 * K - E)\n```\n\nNow we can substitute this into the first expression.\n\n\n```python\nsubs = alpha_expr.subs(mu, mu_expr)\nsubs\n```\n\n\n\n\n$\\displaystyle \\sqrt{3} \\sqrt{\\frac{E K \\left(- \\frac{12 E K}{- E + 9 K} + E\\right)}{\\rho \\left(- E + 9 K\\right) \\left(- \\frac{9 E K}{- E + 9 K} + E\\right)}}$\n\n\n\nThis is a bit ugly! Let's simplify it:\n\n\n```python\nfrom sympy import simplify\n\nsimplify(subs)\n```\n\n\n\n\n$\\displaystyle \\sqrt{3} \\sqrt{\\frac{K \\left(E + 3 K\\right)}{\\rho \\left(- E + 9 K\\right)}}$\n\n\n\nWe can get this as LaTeX plain-text if we want.\n\n\n```python\nprint(sympy.latex(simplify(subs)))\n```\n\n \\sqrt{3} \\sqrt{\\frac{K \\left(E + 3 K\\right)}{\\rho \\left(- E + 9 K\\right)}}\n\n\n## Solve an equation\n\nWe'll solve\n\n $$ x + 2y = 3 $$\n $$ 3x + 4y = 17 $$ \n \nWe'll re-write this using $x_1$ and $x_2$ instead of $x$ and $y$. They are just the names for the unknowns, but it's easier if we just think of there being one, multi-valued unknown. \n\n $$ x_1 + 2x_2 = 3 $$\n $$ 3x_1 + 4x_2 = 17 $$ \n \nMulti-valued quantities are _vectors_, usually written in bold face: $\\mathbf{x} = [x_1, x_2]$.\n \nNow we can rewrite this in the form $\\mathbf{A}\\mathbf{x} = \\mathbf{b}$ (which is analogous to the $\\mathbf{G}\\mathbf{m} = \\mathbf{d}$ form of many geophysical problems). $\\mathbf{A}$ is the matrix containing all the parameters, or coefficients, of the variables (the unknowns in this case) on the left-hand side of the equation. And $\\mathbf{b}$ is a vector containing the known outputs — the right-hand side of the equation.\n \n $$ \\mathbf{A}\\mathbf{x} = \\mathbf{b} $$\n \n $$ \\begin{bmatrix} 1, 2 \\\\ 3, 4 \\end{bmatrix} \\begin{bmatrix} x_1 \\\\ x_2 \\end{bmatrix} = \\begin{bmatrix} 3 \\\\ 17 \\end{bmatrix}$$\n\nTo multiply a matrix by a vector, we multiply the first row by the vector and add the result. So the first row yields $(1 x_1 + 2 x_2)$ — the first of the two equations we started with. And the second row gives us $(3 x_1 + 4 x_2)$ — the second equation.\n\nSo now 'all' we have to do is find the vector $\\mathbf{x}$ that satisfies this new algebraic equation:\n\n $$ \\mathbf{A}\\mathbf{x} = \\mathbf{b} $$\n $$ \\Rightarrow \\mathbf{x} = \\mathbf{A}^{-1} \\mathbf{b}$$\n \nThere's one catch... That symbol $\\mathrm{A}^{-1}$ doesn't mean the reciprocal. It means the inverse. And that's where the fun starts.\n\nWe won't go into it now, but the inverse can be hard to compute. Sometimes it's impossible. So mathematicians have come up with lots of other ways to solve this kind of equation. Welcome to the world of **linear algebra**!\n\n### Solve with SymPy\n\n\n```python\nfrom sympy.solvers import solve\nfrom sympy import symbols\n\n# Define the symbols we are going to use.\nx_1, x_2 = symbols('x_1, x_2')\n\n# Define the equations, making them equal zero.\nequations = [x_1 + 2*x_2 - 3,\n 3*x_1 + 4*x_2 - 17]\n\n# Solve for x_1 and x_2.\nsolve(equations, (x_1, x_2))\n```\n\n\n\n\n$\\displaystyle \\left\\{ x_{1} : 11, \\ x_{2} : -4\\right\\}$\n\n\n\nWe can also solve it as a linear system.\n\nThis requires us to formulate the equations as a single matrix, called an _augmented matrix_. It might look a bit funny, but it's a standard way to solve this kind of problem:\n\n\n```python\nfrom sympy import Matrix, solve_linear_system\n\nx_1, x_2 = symbols('x_1, x_2')\n\nsystem = Matrix([[1, 2, 3],\n [3, 4, 17]])\n\nsolve_linear_system(system, x_1, x_2)\n```\n\n\n\n\n$\\displaystyle \\left\\{ x_{1} : 11, \\ x_{2} : -4\\right\\}$\n\n\n\n### Solve with `np.linalg`\n\nWe can solve linear systems without SymPy.\n\n\n```python\nimport numpy as np\n\nA = np.array([[1, 2],\n [3, 4]])\n\nb = np.array([3, 17])\n```\n\n\n```python\nx = np.linalg.inv(A) @ b\n\nx\n```\n\n\n\n\n array([11., -4.])\n\n\n\nWe can check that this is actually a solution:\n\n\n```python\nA @ x\n```\n\n\n\n\n array([ 3., 17.])\n\n\n\nIndeed, this is the `b` we started with. However, not all matrices are invertible, so this method won't always work. Sometimes we need `solve`:\n\n\n```python\nnp.linalg.solve(A, b)\n```\n\n\n\n\n array([11., -4.])\n\n\n\nLeast squares is another option:\n\n\n```python\nx, *_ = np.linalg.lstsq(A, b, rcond=-1)\n\nx\n```\n\n\n\n\n array([11., -4.])\n\n\n\n----\n\n© 2020 Agile Scientific — licensed CC-BY\n", "meta": {"hexsha": "78b473dcd0fac3e17fcc8e508f65fa9994282993", "size": 12101, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "SymPy_demo.ipynb", "max_stars_repo_name": "EvanBianco/geocomputing_demos", "max_stars_repo_head_hexsha": "96dd8e0d7293077d39099d13f102709fb6812961", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-07-29T15:17:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-29T15:17:15.000Z", "max_issues_repo_path": "SymPy_demo.ipynb", "max_issues_repo_name": "EvanBianco/geocomputing_demos", "max_issues_repo_head_hexsha": "96dd8e0d7293077d39099d13f102709fb6812961", "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": "SymPy_demo.ipynb", "max_forks_repo_name": "EvanBianco/geocomputing_demos", "max_forks_repo_head_hexsha": "96dd8e0d7293077d39099d13f102709fb6812961", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-07-30T18:03:32.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-30T18:03:32.000Z", "avg_line_length": 23.6810176125, "max_line_length": 449, "alphanum_fraction": 0.4713660028, "converted": true, "num_tokens": 1751, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9539661002182845, "lm_q2_score": 0.9149009462917594, "lm_q1q2_score": 0.872784487819968}} {"text": "```python\n# Symbolic computation is the task of computation of mathematical objects symbolically, \n# meaning that the objects are represented exactly, not approximately.\n\nimport math\nmath.sqrt(100)\n```\n\n\n\n\n 10.0\n\n\n\n\n```python\nimport sympy\nsympy.sqrt(100)\n```\n\n\n\n\n 10\n\n\n\n\n```python\nmath.sqrt(3)\n```\n\n\n\n\n 1.7320508075688772\n\n\n\n\n```python\nsympy.sqrt(3)\n```\n\n\n\n\n sqrt(3)\n\n\n\n\n```python\nmath.sqrt(8)\n```\n\n\n\n\n 2.8284271247461903\n\n\n\n\n```python\nsympy.sqrt(8)\n```\n\n\n\n\n 2*sqrt(2)\n\n\n\n\n```python\ntype(math.sqrt(8))\n```\n\n\n\n\n float\n\n\n\n\n```python\ntype(sympy.sqrt(8))\n```\n\n\n\n\n sympy.core.mul.Mul\n\n\n\n\n```python\n# sqrt(3) is an irrational number\n# 1.7320508075688772 an only approximation for sqrt(3).\n# sqrt(3) will be slightly different if we change the data type, for example, double or long double.\n#\n# This is how symbolic computation is different from the \"normal/standard\" \n# numerical computation most of us are familiar with\n# \n# Symbolic computation is also known as computer algebra\n```\n\n\n```python\n# Advantages\n# * work with equations in their natural mathematical form\n# * working with mathematical objects and equations at the fundamental level, without approximations\n# * compute derivatives/integrals of an expression\n# * useful in prototyping of new (mathematical) models and gain insights\n# Disadvantages\n# * symbolic computations are significantly slow when compared to numerical computations\n# * limited to simple problems, for example, solutions of PDEs.\n```\n\n\n```python\n# Why SymPy?\n# Why might you want to learn SymPy?\n\n# There are many software for symbolic computations, with Mathematica and Maple being the players.\n# Matlab/Octave also supports symbolic computations.\n# Others: SageMath, Cadabra\n\n# * Mathematica, Maple and Matlab are not open source\n# * Mathematica's syntax and formatting is ugly (my personal opinion)\n# * Matlab and Sage are heavy (requires a lot of disk space)\n#\n# * SymPy is open source; easy to modify and extend/customise\n# * SymPy is lightweight.\n# * SymPy uses Python; enhance your Python skills (for avid users)\n# * Useful for interactive online teaching of courses on basic maths using Jupyter notebooks\n\n```\n", "meta": {"hexsha": "09cd42c78f607c5bd4e6db94aff0aaf669be4dfe", "size": 5300, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "1-Intro.ipynb", "max_stars_repo_name": "chennachaos/SA2CTechChatSymPy", "max_stars_repo_head_hexsha": "9f1dbb48655ff5f8bdd6b4ced48b58aed0ba5bf4", "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": "1-Intro.ipynb", "max_issues_repo_name": "chennachaos/SA2CTechChatSymPy", "max_issues_repo_head_hexsha": "9f1dbb48655ff5f8bdd6b4ced48b58aed0ba5bf4", "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-Intro.ipynb", "max_forks_repo_name": "chennachaos/SA2CTechChatSymPy", "max_forks_repo_head_hexsha": "9f1dbb48655ff5f8bdd6b4ced48b58aed0ba5bf4", "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": 21.5447154472, "max_line_length": 109, "alphanum_fraction": 0.5322641509, "converted": true, "num_tokens": 536, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404096760998, "lm_q2_score": 0.9390248191350351, "lm_q1q2_score": 0.8727676125928925}} {"text": "#Table of Contents\n\n\n# Lecture 1\n\n\n\nThis lecture introduces ordinary differential equations, and some techniques for solving first order equations. This notebook uses the computer algebra via Sympy () to solve some ODE examples from the lecture notes.\n\n## Solving ordinary differential equations\n\nTo use Sympy, we first need to import it and call `init_printing()` to get nicely typeset equations:\n\n\n```\nfrom sympy import *\n\n# This initialises pretty printing\ninit_printing()\nfrom IPython.display import display\n\n# This command makes plots appear inside the browser window\n%matplotlib inline\n```\n\n### Example: car breaking\n\nDuring braking a car’s velocity is given by $v = v_{0} e^{−t/\\tau}$. Calculate the distance travelled.\n\nWe first define the symbols in the equation ($t$, $\\tau$ abd $v_{0}$), and the function ($x$, for the displacement):\n\n\n```\nt, tau, v0 = symbols(\"t tau v0\")\nx = Function(\"x\")\n```\n\nNext, we define the differential equation, and print it to the screen:\n\n\n```\neqn = Eq(Derivative(x(t), t) , v0*exp(-t/(tau)))\ndisplay(eqn)\n```\n\nThe `dsolve` function solves the differential equation symbolically:\n\n\n```\nx = dsolve(eqn, x(t))\ndisplay(x)\n```\n\nwhere $C_{1}$ is a constant. As expected for a first-order equation, there is one constant.\n\nSymPy is not yet very good at eliminating constants from initial conditions, so we will do this manually assuming that $x = 0$ and $t = 0$:\n\n\n```\nv0 = symbols('v0')\nx = x.subs('C1', v0*tau)\ndisplay(x)\n```\n\nSpecifying values for $v_{0}$ and $\\tau$, when can plot the velocity as a function of time:\n\n\n```\n# Specify values for v0 and tau\nx = x.subs(v0, 100)\nx = x.subs(tau, 2)\n\n# Plot velocity vs time\nplot(x.args[1], (t, 0.0, 10.0), xlabel=\"time\", ylabel=\"velocity\")\n```\n\n#### Classification\n\nWe can ask SymPy to classify our ODE, e.g. show that it is first order):\n\n\n```\nclassify_ode(eqn)\n```\n\n\n\n\n ('separable',\n '1st_exact',\n '1st_linear',\n 'Bernoulli',\n '1st_power_series',\n 'lie_group',\n 'nth_linear_constant_coeff_undetermined_coefficients',\n 'nth_linear_constant_coeff_variation_of_parameters',\n 'separable_Integral',\n '1st_exact_Integral',\n '1st_linear_Integral',\n 'Bernoulli_Integral',\n 'nth_linear_constant_coeff_variation_of_parameters_Integral')\n\n\n\n### Parachutist\n\nFind the variation of speed with time of a parachutist subject to a drag force of $kv^{2}$.\n\nThe equations to solve is\n\n$$\n\\frac{m}{k} \\frac{dv}{dt} = \\alpha^{2} - v^{2}\n$$\n\nwhere $m$ is mass, $k$ is a prescribed constant, $v$ is the velocity, $t$ is time and $\\alpha^{2} = mg/k$ ($g$ is acceleration due to gravity).\n\nWe specify the symbols, unknown function $v$ and the differential equation\n\n\n```\nt, m, k, alpha = symbols(\"t m k alpha\")\nv = Function(\"v\")\neqn = Eq((m/k)*Derivative(v(t), t), alpha*alpha - v(t)*v(t))\ndisplay(eqn)\n```\n\nFirst, let's classify the ODE:\n\n\n```\nclassify_ode(eqn)\n```\n\n\n\n\n ('separable', '1st_power_series', 'lie_group', 'separable_Integral')\n\n\n\nWe see that it is not linear, but it is separable. Using `dsolve` again,\n\n\n```\nv = dsolve(eqn, v(t))\ndisplay(v)\n```\n\nSymPy can verify that an expression is a solution to an ODE:\n\n\n```\nprint(\"Is v a solution to the ODE: {}\".format(checkodesol(eqn, v)))\n```\n\n Is v a solution to the ODE: (True, 0)\n\n", "meta": {"hexsha": "49a0b13e22612745415b87d21ccccbff7dc55b70", "size": 27139, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/Lecture1.ipynb", "max_stars_repo_name": "quang-ha/IA-maths-Ipython", "max_stars_repo_head_hexsha": "8ff8533d64a3d8db8e4813a7b6dfee39339fd846", "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": "notebooks/Lecture1.ipynb", "max_issues_repo_name": "quang-ha/IA-maths-Ipython", "max_issues_repo_head_hexsha": "8ff8533d64a3d8db8e4813a7b6dfee39339fd846", "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": "notebooks/Lecture1.ipynb", "max_forks_repo_name": "quang-ha/IA-maths-Ipython", "max_forks_repo_head_hexsha": "8ff8533d64a3d8db8e4813a7b6dfee39339fd846", "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": 66.5171568627, "max_line_length": 9797, "alphanum_fraction": 0.7615977007, "converted": true, "num_tokens": 927, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.960361159764527, "lm_q2_score": 0.9086178956955642, "lm_q1q2_score": 0.872601336092996}} {"text": "# Tutorial for Homework 5 - Interference of Light\n\n\n```python\n# setup by importing some good modules\nimport sympy as sp\n# All calls to sympy require sp. at the beginning\n# One could use \"from sympy import *\", but then it's difficult to know what is sympy\n# and what is another module when importing multiple modules.\n# print things all pretty\nfrom sympy.abc import *\nsp.init_printing(use_latex='mathjax')\n\n```\n\nThe sympy module (http://docs.sympy.org) allows one to plot functions without having to digitize the independent variable. Let's take a look at how to use it to plot functions. In the first example, we'll plot cosine, sine, and both together. These functions are built into sympy. Simply give it the range of x-axis values you want plotted. NOTE: The text in between \\$ is LaTeX typesetting.\n\n\n```python\nsp.plot(sp.cos(x), (x,-sp.pi, sp.pi), legend=True, line_color='red', xlabel='$\\\\theta$', ylabel='Amplitude')\nsp.plot(sp.sin(x), (x,-sp.pi, sp.pi), legend=True, line_color='blue', xlabel='$\\\\theta$', ylabel='Amplitude')\nsp.plot(sp.sin(x), sp.cos(x), (x,-sp.pi, sp.pi), legend=True, line_color='red', xlabel='$\\\\theta$', ylabel='Amplitude')\n```\n\nAs you can see, once we plot two functions, we lose the ability to decorate them individually. Let's see how we can decorate them individually. To do this we'll need to make the graph an object and show the graph after we decorate it.\n\n\n```python\n#Define the graph as an object p\np = sp.plot(sp.sin(x), sp.cos(x), (x,-sp.pi, sp.pi), show=False, legend=True, xlabel='$\\\\theta$', ylabel='Amplitude')\np[0].line_color='red' #color the first data element as red\np[1].line_color='blue'#color the second data element as blue\np.show()\n```\n\n### Your turn\nUsing the cell below, try plotting $\\cos^2(x)$ and $\\sin^2(x)$ on the same graph. HINT: Squaring in Python is done with ```**2```. Make the cosine function purple and the sine function orange.\n\n\n```python\n\n```\n\n## Diffraction\n\nNow, let's look at a function that is relevant to our homework. The intensity pattern of light diffracting through a single slit is\n\n$$I = I_o \\left[\\frac{\\sin \\left(\\beta\\right)}{\\beta}\\right]^2$$\n\nTo simplify the plotting, we'll define $\\beta$ to be our $x$ variable. We will need to create this function since it does not exist in Sympy. We need to define the variables we plan to use as \"symbols\" for the independent and dependent variables. Once we define them, SymPy will also format them to look like pretty mathematics.\n\n\n```python\n#Define x and I as real-valued symbols\nx, I= symbols(\"x, I\", real = True)\n# Define I\nI = (sp.sin(x)/x)**2\nI # This causes it to output formatted nicely. The print command formats it as computer code\n```\n\n\n\n\n$$\\frac{1}{x^{2}} \\sin^{2}{\\left (x \\right )}$$\n\n\n\n\n```python\n#Plot the intensity of diffraction from -10 to 10\nsp.plot(I, (x,-10, 10))\n```\n\n### Your turn\nIn the cell below, plot the same diffraction data as above but label the axes with \"Intensity\" and \"$\\theta$\".\n\n\n```python\n\n```\n\nFrom the plot of the diffraction intensity function, we know the intensity equation must have a maximum in the center, i.e., when $\\beta\\rightarrow0$. L'H$\\hat{\\rm{o}}$pital's rule says\n\n$$\\lim_{\\beta\\to 0} \\frac{\\sin\\beta}{\\beta} = 1$$\n\nWe could also take a derivative if the intensity function and find the maximum. More on that later. We get the central maximum at $\\beta=0$ since the limit is 1, the intensity is $I_o$ at $\\beta = 0$. We read in the textbook that there is a first order minimum when \n\n$$D \\sin\\left(\\theta\\right) = m\\lambda$$\n\nand $m=1$. Minima will occur when $\\beta = m\\pi$ in the intensity equation above because $\\sin(m\\pi)=0$. Rearrarange the destructive interference condition equation above to solve for $m$; multiply by $\\pi$ and substitute this into the first equation for $\\beta$.\n\nYou should get\n\n$$I = I_o \\left[\\frac{\\sin \\left(\\frac{\\pi D\\sin\\left(\\theta\\right)}{\\lambda}\\right)}{\\frac{\\pi D\\sin\\left(\\theta\\right)}{\\lambda}}\\right]^2$$\n\nThis means, we can determine the size of the single slit if we know the wavelength of light we are using. You did this in lab. Let's make a plot of this function by first defining $D=\\lambda$ and $\\lambda=500$ nm. Recall that $\\sin\\left(\\theta\\right)\\approx\\frac{y}{L}$, where $y$ is the distance away from the central point on the screen, and $L$ is the distance the screen is from the diffraction slit. You should also define $L = 1$ meter.\n\n### Your turn\nBelow, edit the code to set the known variables and to create the function of diffraction intensity. Then, in the cell below the next one, plot the intensity function. Be sure to decorate your graph with axis labels and colors.\n\n\n```python\n#Create your constants\nwl=0 #variable for wavelength\nD=0 #variable for slit width\nL=0 #variable for screen distance from slit\n#Define x and I as real-valued symbols\nx, I= symbols(\"x, I\", real = True)\n# Define I for real\nI = x\nI # This causes it to output formatted nicely. The print command formats it as computer code\n```\n\n\n\n\n$$x$$\n\n\n\n\n```python\n#Plot your intensity function\n```\n\nTry changing the wavelength. What happens to the diffraction pattern when $D\\gt\\lambda$? What happens to the diffraction pattern when $D\\lt\\lambda$?\n\n## Interference\n\nNext, let's look at interference. We expect interference to have constructive maxima following the relationship\n\n$$d \\sin\\left(\\theta\\right) = m\\lambda$$\n\nThe angle $\\theta$ is the same as for diffraction. It is the angle away from a straight traveling beam. In this case $d$ is the spacing between two slits. From this pattern of constructive interference, we get a bright spot when $\\theta=0$ and again when $\\sin\\left(\\theta\\right) = \\lambda$. This means we'll get a bright spot on the screen when\n\n$$\\sin\\left(\\theta\\right) \\approx \\frac{y}{L} = \\frac{m\\lambda}{d}$$\n\n$$y = \\frac{mL\\lambda}{d}$$\n\nThus, we expect repeated constructive interference bright spots every integer multiple of\n\n$$\\frac{L\\lambda}{d}$$\n\nSince the interference has a bright spot when $\\theta = 0$, we can write the intensity function as a cosine. There will be high intensity at the same locations as the conditional equation $d \\sin\\left(\\theta\\right) = m\\lambda$. We know the cosine function should be maximum (have an argument of $m\\pi$) at these locations. We also know that intensity is the square of the electric field of the light. This means the cosine function will be squared. This prevents a negative intensity, which makes no sense.\n\n$$I = I_o \\cos^2\\left(\\alpha\\right)$$\n\nSimilar to the diffraction arguments, the angle $\\alpha = m\\pi$ is constructive interference. This gives\n\n$$\\alpha = \\frac{\\pi d \\sin\\left(\\theta\\right)}{\\lambda}$$\n\n### Your turn\nIn the cells below, plot the interference intensity function. You will need to define a value for $d$. Let's use $d = 1 \\rm{\\mu m}$. Be sure to give the function a new name, ```Iint``` for example. Once you get it to plot, try changing $d$ to values between $\\lambda/2$ and $2\\lambda$. What happens to the constructive interference fringes?\n\n\n```python\n#Define x and I as real-valued symbols\nd = 1e-5 #double slit spacing\n#wavelength is defined above already. You can redefine it anywhere with wl\n# Define your symbols x and Iint\n# Define interference intensity\nIint = sp.cos(sp.pi*d*x/500e-9/3)**2\nIint # This causes it to output formatted nicely. The print command formats it as computer code\n```\n\n\n\n\n$$\\cos^{2}{\\left (6.66666666666667 \\pi x \\right )}$$\n\n\n\n\n```python\n#Plot the intensity of an interference pattern.\nsp.plot(Iint, (x, -0.5,0.5))\n```\n\n## Putting Diffraction and Interference Together\nThe combined effect of diffraction and interference is the product of the two functions. This gives\n\n$$I = I_o \\left[\\frac{\\sin \\left(\\frac{\\pi D\\sin\\left(\\theta\\right)}{\\lambda}\\right)}{\\frac{\\pi D\\sin\\left(\\theta\\right)}{\\lambda}}\\right]^2 \\cos^2\\left(\\frac{\\pi d \\sin\\left(\\theta\\right)}{\\lambda}\\right)$$\n\n### Your turn\nCreate a new function (give it a new name such as ```Itot```) for the combined diffraction and interference. Then, plot this function. Also plot the intensity function from diffraction. It should still be defined by ```I``` from above.\n\nTest what happens when $D$ increases or decreases. Test what happens when $d$ increases or decreases. Test what happens when $\\lambda$ increases or decreases.\n\n\n```python\n#Plot the combined diffraction and interference function along with the diffraction intensity function.\n```\n\n## Derivatives, Maxima, Minima\nAnother powerful tool in SymPy is its ability to calculate derivatives. It is really simple too! The command ```diff``` will calculate a derivative of any existing function. Below, I differentiate cosine and store it in the symbol dcos.\n\n\n```python\ndcos = sp.diff(sp.cos(x), x)\ndcos\n```\n\n\n\n\n$$- \\sin{\\left (x \\right )}$$\n\n\n\n### Your turn\nTry differentiating sine below.\n\n\n```python\n\n```\n\nWhen it is a user defined function, the ```(x)``` is not necessary. Here is an example where I define a polynomial function related to the acceleration due to gravity and differentiate it to obtain the velocity function.\n\n\n```python\nt, poly = symbols(\"t, poly\", real = True)\npoly = 0.5*(-9.8)*t**2+20*t+1\ndpoly = sp.diff(poly, t)\npoly, dpoly\n```\n\n\n\n\n$$\\left ( - 4.9 t^{2} + 20 t + 1, \\quad - 9.8 t + 20\\right )$$\n\n\n\nI can solve for extrema too. To do this I use the SymPy ```solveset``` function. According to SymPy's documentation... The first argument for ```solveset()``` is an equation (equaled to zero by solveset) and the second argument is the symbol that we want to solve the equation for (usually your independent variable). Thus, ```solveset``` finds the roots of a function, i.e., where it is equal to zero.\n\n\n```python\nextrema = sp.solveset(dpoly, t) \nextrema\n```\n\n\n\n\n$$\\left\\{2.04081632653061\\right\\}$$\n\n\n\nIt's telling me there is a maximum or minimum at $t = 2.04$ seconds. We know this polynomial has no upper and lower limits. As $t\\to\\pm\\infty$, the function goes to $\\pm\\infty$ depending on the concavity (2nd derivative). Let's plot ```poly``` to see if this extremum is true. First, I will find the zeros (where the function evaluates to zero) and plot over that range. This would correspond to an object going from the ground, upward to maximum height, and then back to the ground. Keep in mind my function implies I threw the object upward from a height of 1 meter.\n\n\n```python\npolyzeros = sp.solveset(poly, t)\npolyzeros\n```\n\n\n\n\n$$\\left\\{-0.0494020618888763, 4.1310347149501\\right\\}$$\n\n\n\n\n```python\nsp.plot(poly, (t, -0.0494, 4.131))\n```\n\nIt does appear that there is a maximum at $t=2.04$ seconds.\n\n### Your turn\nFind the derivative of your total intensity function. I have written the function below, but you should already have it defined above.\n\n\n```python\n#Define x and I as real-valued symbols\nx, Itot = symbols(\"x, Itot\", real=True)\nL = 1\nwl = 5e-7\nD = 2e-7\ndd = 1e-6 #double slit spacing\n# Define your symbols x and Iint\n# Define interference intensity\nItot = (sp.sin(sp.pi*D*x/(wl*L))/(sp.pi*D*x/(wl*L))*sp.cos(sp.pi*dd*x/(wl*L)))**2\nItot # This causes it to output formatted nicely. The print command formats it as computer code\n```\n\n\n\n\n$$\\frac{6.25}{\\pi^{2} x^{2}} \\sin^{2}{\\left (0.4 \\pi x \\right )} \\cos^{2}{\\left (2.0 \\pi x \\right )}$$\n\n\n\n\n```python\nsp.plot(Itot, (x, -5, 5))\n```\n\n\n```python\nItotdiff = sp.diff(x,x)\nItotdiff\n```\n\n\n\n\n$$1$$\n\n\n\nOuch! That is quite a derivative!!! We can try to find the roots using ```solveset```. Give it a shot. To limit the range that Python tries to search, use the argument ```sp.Interval```. NOTE: You'll need to change ```y``` to the appropriate function.\n\n\n```python\nItotextreme = sp.solveset(y, x, sp.Interval(-0.1,0.1))\nItotextreme\n```\n\n\n\n\n$$\\emptyset$$\n\n\n\nThe result is pretty difficult to interpret when the function is so complicated. Let's plot the derivative to see if we can find the global maximum and first two minima. To do this choose a range of x values to plot that will zoom in on the region of the total intensity where you expect these to be.\n\n\n```python\nsp.plot(x, (x,-1,1))\n```\n\n## Integrals\nYou don't have integrals on your homework, but we might as well look at how to evaluate them using SymPy while we are learning about SymPy.\n\nTo take the integral of a function is as simple as taking a derivative. The exception is that integrals can be definite or indefinite. Let's look at an example of both using SymPy's ```integrate``` function.\n\nFirst, we'll take the indefinite integral of cosine.\n\n\n```python\nsp.integrate(sp.cos(x),x)\n```\n\n\n\n\n$$\\sin{\\left (x \\right )}$$\n\n\n\nExcellent! We could have stored that in a variable ```intcos = sp.integrate(sp.cos(x),x)``` if we wanted to use the integral later. Now, let's integrate over a range (definite integral). We'll continue with the cosine function. Before we do, let's think about what we expect to obtain from the integral. Say we integrate cosine from $-\\pi$ to $\\pi$. This is one period of cosine. What do you expect to get from the integral?\n\n\n```python\nsp.integrate(sp.cos(x),(x,-1, 1))\n```\n\n\n\n\n$$2 \\sin{\\left (1 \\right )}$$\n\n\n\n### Your turn\nCreate a function that describes a projectile's velocity as a function of time. Give the object an initial upward velocity of 10 m/s and downward acceleration due to gravity. Integrate this function to obtain the position vs. time function. First, do this as an indefinite integral. Then, integrate over the range of times that correspond to the object leaving the ground and reaching its maximum height. Do each of these in their own cell. You may want to plot your velocity and position functions to visually inspect that they are what you expect. After you obtain your results, create a markdown cell to explain the results at the bottom. Use LaTeX in your markdown to typeset the equations for velocity and position functions.\n\n\n```python\n\n```\n", "meta": {"hexsha": "d4c1d61d9a0597c67e0bb242547879ebf26d5a50", "size": 219371, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "HW5-Interference-Tutorial.ipynb", "max_stars_repo_name": "guygastineau/Jupyter", "max_stars_repo_head_hexsha": "5d97e1a57cc812e1131f1d39edbd6b15341f38ed", "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": "HW5-Interference-Tutorial.ipynb", "max_issues_repo_name": "guygastineau/Jupyter", "max_issues_repo_head_hexsha": "5d97e1a57cc812e1131f1d39edbd6b15341f38ed", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2018-08-06T17:55:54.000Z", "max_issues_repo_issues_event_max_datetime": "2018-08-07T18:47:52.000Z", "max_forks_repo_path": "HW5-Interference-Tutorial.ipynb", "max_forks_repo_name": "guygastineau/Jupyter", "max_forks_repo_head_hexsha": "5d97e1a57cc812e1131f1d39edbd6b15341f38ed", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-08-06T17:39:08.000Z", "max_forks_repo_forks_event_max_datetime": "2018-08-06T17:39:08.000Z", "avg_line_length": 255.3795110594, "max_line_length": 30116, "alphanum_fraction": 0.9195426925, "converted": true, "num_tokens": 3668, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810481379379, "lm_q2_score": 0.9207896699134005, "lm_q1q2_score": 0.8723386825971432}} {"text": "```python\nimport numpy as np\nimport pandas as pd\nimport statsmodels.api as sm\nimport matplotlib.pyplot as plt\nplt.style.use('classic')\n%matplotlib inline\n```\n\n# Class 10: Stochastic Time Series Processes\n\nMost models of the business cycle are *stochastic* time series models. That is, the models incorporate randomness as a determinant of equilibrium. Randomness is necessary for two reasons. First, from a practical point of view, any model will be incomplete and will not fit the data perfectly and so randomness in a macroeconomic model is analagous to an error term in an OLS model. Second, from a philosophical perspective, randomness in a macroeconomic model reflects economists' consensus that fundamentally unpredictable forces cause the business cycle.\n\n\n## Simulating Normal Random Variables with Numpy\n\nRecall that the `numpy.random` module has functions for generating (pseudo) random variables. Learn more about the module by reading the documentation: https://docs.scipy.org/doc/numpy/reference/routines.random.html\n\nWe use the `numpy.random.normal()` function to crate arrays of random draws from the normal distribution. The function takes three arguments:\n* `loc`: the mean of the distribution (default=0)\n* `scale`: the standard deviation of the distribution (default=1)\n* `size`: how many to numbers to draw (default = `None`)\n\nThe default is to draw numbers from the *standard normal* distribution.\n\n### Example\n\nDraw 500 values each from the $\\mathcal{N}(0,1)$ and $\\mathcal{N}(0,2^2)$ distributions. Plot.\n\n\n```python\n# Set the seed for the random number generator to 126\nnp.random.seed(126)\n\n# Create two arrays:\n# x: 500 draws from the normal(0,1) distribution\n# y: 500 draws from the normal(0,4) distribution\nx = np.random.normal(loc=0,scale=1,size=500)\ny = np.random.normal(loc=0,scale=2,size=500)\n\n# Plot x and y\nplt.plot(x,lw=2,alpha = 0.6,label='$\\sigma=1$')\nplt.plot(y,lw=2,alpha = 0.6,label='$\\sigma=2$')\nplt.legend(loc='center left', bbox_to_anchor=(1, 0.5))\nplt.grid()\n```\n\n## The White Noise Process\n\nIn the previous example, we created two variables that stored draws from normal distrbutions with means of zero but with different standard deviations. Both of the variables were simulations of *white noise processes*. A white noise process is a random variable $\\epsilon_t$ with constant mean and constant variance. We are concerned only with the zero-mean white noise process and we'll denote that a variable is a zero-mean white noise process with the following shorthand notation:\n\n\\begin{align}\n\\epsilon_t & \\sim \\text{WN}(0,\\sigma^2),\n\\end{align}\n\nwhere $\\sigma^2$ is the variance of the processes. Strictly speaking, a white noise process can follow any distribution as long as the mean and variance are constant, but we'll concentrate exclusively white noise process drawn from the normal distribution.\n\n## The AR(1) Process\n\nA random variable $y_t$ is an *autoregressive process of order 1* or AR(1) process if it can be written in the following form:\n\n\\begin{align}\ny_t & = \\rho y_{t-1} + \\epsilon_t,\n\\end{align}\n\nwhere $\\rho$ is a constant and $\\epsilon \\sim \\text{WN}(0,\\sigma^2)$. The AR(1) process is the stochastic analog of the first-order difference equation where the random variable $\\epsilon_t$ replaces the exogenous variable $w_t$.\n\n### Example\n\nSimulate an AR(1) process for 101 periods ($t = 0,\\ldots, 100$) using the following parameter values:\n\n\\begin{align}\n\\rho & = 0.5\\\\\n\\sigma & = 1\\\\\ny_0 & = 0\n\\end{align}\n\nPlot the simulated values for $y$.\n\n\n```python\n# Set the seed for the random number generator to 126\nnp.random.seed(126)\n\n# Initialize values for T, y0, rho, and sigma\nT = 101\ny0 = 0\nrho = 0.5\nsigma = 1\n\n# Initialize an array of zeros for y\ny = np.zeros(T)\n\n# Set the first value of y equal to y0\ny[0] = y0\n\n# Create a variable called 'epsilon' equal to an array containing T draws from the normal(0,sigma^2) process\neps= np.random.normal(loc=0,scale=sigma,size=T)\n\n# Iterate over t in range(T-1) to compute y\nfor t in range(T-1):\n y[t+1] = rho*y[t] + eps[t+1]\n \n# Plot y\nplt.plot(y,lw=2)\nplt.grid(linestyle=':')\n```\n\nThe AR(1) process wtih $\\rho = 0.5$ seems to fluctuate around the value $y=0$ and so the process appears to be stable\n\n### Example\n\nSimulate an AR(1) process for 101 periods ($t = 0,\\ldots, 100$) using the following parameter values:\n\n\\begin{align}\n\\rho & = 1.5\\\\\n\\sigma & = 1\\\\\ny_0 & = 0\n\\end{align}\n\nPlot the simulated values for $y$.\n\n\n```python\n# Set the seed for the random number generator to 126\nnp.random.seed(126)\n\n# Initialize values for T, y0, rho, and sigma\nT = 101\ny0 = 0\nrho = 1.5\nsigma = 1\n\n# Initialize an array of zeros for y\ny = np.zeros(T)\n\n# Set the first value of y equal to y0\ny[0] = y0\n\n# Create a variable called 'epsilon' equal to an array containing T draws from the normal(0,sigma^2) process\neps= np.random.normal(loc=0,scale=sigma,size=T)\n\n# Iterate over t in range(T-1) to compute y\nfor t in range(T-1):\n y[t+1] = rho*y[t] + eps[t+1]\n \n# Plot y\nplt.plot(y,lw=2)\nplt.grid(linestyle=':')\n```\n\nThe AR(1) process wtih $\\rho = 1.5$ seems to be approaching infinity in magnitude and so the process appears to be explosive.\n\nIn general, like the first-order difference equation, if $|\\rho| < 1$, the the AR(1) process is stable. If $|\\rho|>1$ then the process is explosive. A special case is the *random walk process* which is an AR(1) process with $\\rho = 1$. The random walk process has many important applications including asset pricing theory.\n\nThe function in the next cell \n\n\n```python\n# Define a function for simulating an AR(1) process. CELL PROVIDED\ndef ar1_sim(rho=0,sigma=1,y0=0,T=25):\n '''Funciton for simulating an AR(1) process for T periods\n \n Args:\n rho (float): autoregressive parameter\n sigma (float): standard deviation of the white noise process\n y0 (float): initial value of the process\n T (int): number of periods to simulate\n \n Returns:\n numpy array\n '''\n \n # initialize y array\n y = np.zeros(T)\n y[0] = y0\n \n # draw random numbers for white noise process\n eps= np.random.normal(loc=0,scale=sigma,size=T-1)\n for t in range(T-1):\n y[t+1] = rho*y[t] + eps[t]\n \n return y\n```\n\n### Example:\n\nUse the `ar1_sim()` function to simulate an AR(1) process for 201 periods ($t = 0,\\ldots, 200$) using the following parameter values:\n\n\\begin{align}\n\\rho & = -0.99\\\\\n\\sigma & = 0.5\\\\\ny_0 & = 0\n\\end{align}\n\nSet the seed for the NumPy random number generator to 126. Plot the simulated values for $y$.\n\n\n```python\n# Set the seed for the random number generator to 126\nnp.random.seed(126)\n\n# Simulate y and plot\nplt.plot(ar1_sim(rho=-0.99,sigma=0.5,y0=0,T=201))\nplt.grid()\n```\n\n## Application: Estimate TFP as an AR(1) process\n\nIt is routine to model quarterly fulctuations in TFP as an AR(1) process and we will encounter this in our business cycle models. Here we will fit the following AR(1) model to US data:\n\n\\begin{align}\n\\log\\left(A_t/A^{trend}_t\\right) & = \\rho \\log\\left(A_{t-1}/A^{trend}_{t-1}\\right) + \\epsilon_t\n\\end{align}\n\nwhere $\\log\\left(A_t/A^{trend}_t\\right) = \\log A_t - \\log A^{trend}$ is the log-deviation of TFP from its trend and $\\epsilon_t$ is a white noize process with mean 0 and variance $\\sigma^2$.\n\n\n### The Data\nThe file `rbc_data_actual_trend.csv`, available at https://github.com/letsgoexploring/econ126/raw/master/Data/Csv/rbc_data_actual_trend.csv, contains actual and trend data for real GDP per capita, real consumption per capita, real investment per capita, real physical capital per capita, TFP, and hours per capita at quarterly frequency. The GDP, consumption, investment, and capital data are in terms of 2012 dollars. Hours is measured as an index with the value in October 2012 set to 100. All of the data are *real* quantities. That is, there are no *nominal* quantities like money or inflation or a nominal interest rate. The reason is that the first theory that we will encounter is called *real business cycle* or RBC theory and, in that theory, there is no place for nominal quantities. RBC theory seeks to explain fluctuations in real quantities as being primarily due to TFP shocks; i.e., shocks to the production function.\n\n### Objectives\n\n1. Import TFP data (trend and actual) and compute cyclical component as log-deviation from trend.\n2. Construct a scatter plot of log-deviation of TFP from trend against *lagged* log-deviation of TFP from trend.\n3. Estimate the AR(1) model of log-deviation of TFP from trend to obtain estimates of $\\rho$ and $\\sigma$.\n\n\n```python\n# Read business_cycle_data_actual_trend.csv into a Pandas DataFrame called 'df' with the first column set as the index and parse_dates=True\ndf = pd.read_csv('https://github.com/letsgoexploring/econ126/raw/master/Data/Csv/rbc_data_actual_trend.csv',index_col=0,parse_dates=True)\n```\n\n\n```python\n# Construct a plot of TFP with its trend with:\n# 1. Actual line: blue with lw=1, alpha=0.7, label = 'actual'\n# 2. Trend line: red with lw=3, alpha=0.7, label = 'trend'\nplt.plot(df['tfp'],lw=2,alpha=0.6,label='Actual')\nplt.plot(df['tfp_trend'],'r',lw=2,alpha=0.6,label='Trend')\nplt.title('TFP for US from '+df.index[0].strftime('%B %Y')+' to '+df.index[-1].strftime('%B %Y'))\nplt.legend(loc='center left', bbox_to_anchor=(1, 0.5))\nplt.grid()\n```\n\nNow we need to compute the log-deviation of TFP from its trend. Note that since $\\log(a/b) = \\log(a) - \\log(b)$, we can write:\n\n\\begin{align}\n\\log A_t - \\log A^{trend} & = \\log\\left(A_t/A^{trend}_t\\right)\n\\end{align}\n\nThe term on the right will make the AR(1) model easier to read.\n\n\n\\begin{align}\n\\log\\left(A_t/A^{trend}_t\\right) & = \\rho \\log\\left(A_{t-1}/A^{trend}_{t-1}\\right) + \\epsilon_t\n\\end{align}\n\n\n\n\n\n```python\n# Create a new column to df called tfp_cycle equal to the log difference between actual TFP and it's trend:\ndf['tfp_cycle'] = np.log(df['tfp']/df['tfp_trend'])\n```\n\n\n```python\n# Plot the log deviation of TFP from its trend (times 100)\nplt.plot(df['tfp_cycle'],lw=2,alpha=0.6)\nplt.title('TFP for US from '+df.index[0].strftime('%B %Y')+' to '+df.index[-1].strftime('%B %Y'))\nplt.grid()\n```\n\n\n```python\n# Create a new column to df called tfp_cycle_lag that, for each date, contains values \n# in 'tfp_cycle' at the previous date\ndf['tfp_cycle_lag'] = df['tfp_cycle'].shift()\n\n# Print the first five rows of only the 'tfp_cycle' and 'tfp_cycle_lag' columns. PROVIDED\nprint(df[['tfp_cycle','tfp_cycle_lag']].head())\n```\n\n tfp_cycle tfp_cycle_lag\n 1948-01-01 0.003328 NaN\n 1948-04-01 0.009235 0.003328\n 1948-07-01 -0.001173 0.009235\n 1948-10-01 -0.005672 -0.001173\n 1949-01-01 -0.019633 -0.005672\n\n\nNotice that there is a missing value inthe `tfp_cycle_lag` column for the first date in the index because there is no prior observation in the `tfp_cycle` column. To proceed with the estimation, we need to get rid of the row with missing values\n\n\n```python\n# Use dropna() method on df to remove the row iwth the missing value\ndf= df.dropna()\n\n# Print the first five rows of only the 'tfp_cycle' and 'tfp_cycle_lag' columns. PROVIDED\nprint(df[['tfp_cycle','tfp_cycle_lag']].head())\n```\n\n tfp_cycle tfp_cycle_lag\n 1948-04-01 0.009235 0.003328\n 1948-07-01 -0.001173 0.009235\n 1948-10-01 -0.005672 -0.001173\n 1949-01-01 -0.019633 -0.005672\n 1949-04-01 -0.020813 -0.019633\n\n\nNext, we should make a scatter plot of log-deviation of TFP from trend against the one-period lag of log-deviation of TFP from trend to see if out AR(1) model is a good idea.\n\n\n```python\n# Construct a scatter plot of log-deviation of TFP from trend against the one-period lag of log-deviation \n# of TFP from trend with:\n# 1. scatter points sized at least 50, opacity (alpha) no greater than 0.25\n# 2. x- and y-axis limits: [-0.04,0.04]\nplt.scatter(df['tfp_cycle_lag'],df['tfp_cycle'],s=50,alpha=0.25)\nplt.xlabel('Lag log-deviation from trend')\nplt.ylabel('Current log-deviation from trend')\nplt.title('TFP for US from '+df.index[0].strftime('%B %Y')+' to '+df.index[-1].strftime('%B %Y'))\nplt.xlim([-0.04,0.04])\nplt.ylim([-0.04,0.04])\nplt.grid()\n```\n\nNow we use StatsModels to fit the model. First we estimate the AR(1) model to obtain an estimate of $\\rho$. Then we find the standard deviation of the residuals of the regression to estimate $\\sigma$.\n\n\n```python\n# Create variable 'X' to be the independent variable of the OLS model. Do not add a constant to X\nX = df['tfp_cycle_lag']\n\n# Create variable 'Y' to be the dependent variable of the OLS model.\nY = df['tfp_cycle']\n\n# Create a variable called 'model' that initializes the OLS model\nmodel = sm.OLS(Y,X)\n\n# Create a variable called 'results' that stores the results of the estimated OLS model\nresults = model.fit()\n\n# Print output of summary2() mdethod of results\nprint(results.summary2())\n```\n\n Results: Ordinary least squares\n ===================================================================\n Model: OLS Adj. R-squared: 0.565 \n Dependent Variable: tfp_cycle AIC: -2072.6530\n Date: 2019-02-14 09:40 BIC: -2069.0110\n No. Observations: 282 Log-Likelihood: 1037.3 \n Df Model: 1 F-statistic: 367.8 \n Df Residuals: 281 Prob (F-statistic): 5.49e-53 \n R-squared: 0.567 Scale: 3.7497e-05\n --------------------------------------------------------------------\n Coef. Std.Err. t P>|t| [0.025 0.975]\n --------------------------------------------------------------------\n tfp_cycle_lag 0.7530 0.0393 19.1785 0.0000 0.6757 0.8303\n -------------------------------------------------------------------\n Omnibus: 5.031 Durbin-Watson: 1.836\n Prob(Omnibus): 0.081 Jarque-Bera (JB): 5.460\n Skew: -0.191 Prob(JB): 0.065\n Kurtosis: 3.564 Condition No.: 1 \n ===================================================================\n \n\n\nEstimated coefficients are stored as a Pandas `Series` in the `params` attribute of `results`. Index values correspond to names of columns in the dependent variable `X`\n\n\n```python\n# Print the contents of the params method of results\nprint(results.params)\n```\n\n tfp_cycle_lag 0.753038\n dtype: float64\n\n\n\n```python\n# Create a variable called 'rho' that equals the value of the estimated coefficient on df['tfp_cycle_lag']\nrho = results.params['tfp_cycle_lag']\n```\n\nThe residuals from the regression are stored in an attribute of `results` called `resid`\n\n\n```python\n# Create a variable called 'sigma' that equals the standard deviation of the residuals of the regression\nsigma = results.resid.std()\n\n# Print the value of sigma\nprint(sigma)\n```\n\n 0.006123478152733714\n\n\nAnd that's how you estimate the parameters of an AR(1) model of the cyclical component of TFP fr the US.\n\n## Application: A Stochastic Solow Growth Model (Optional)\n\nConsider the Solow growth model with written in \"per worker\" terms:\n\n\\begin{align}\ny_t & = A_tk_t^{\\alpha}\\\\\nk_{t+1} & = i_t + (1-\\delta)k_{t}\\\\\ny_t & = c_t + i_t\\\\\nc_t & = (1-s)y_t,\n\\end{align}\n\nwhere $y_t$ is output per worker, $k_t$ is capital per worker, $c_t$ is consumption per worker, $i_t$ is investment per worker, and $A_t$ is time-varying TFP. Assume:\n\n\\begin{align}\n\\log A_{t+1} & = \\rho \\log A_{t} + \\epsilon_{t+1}\n\\end{align}\n\nwhere $\\epsilon_t$ is a white noise process with mean 0 and variance $\\sigma^2$. Since capital and TFP are the only two variables, that depend on past value of themselves, they are the two state variables of the model. Therefore, we can simulate simulate the model in two steps. First, simulate $k_t$ and $A_t$ using the following two laws of motion:\n\n\\begin{align}\nk_{t+1} & = sAk_t^{\\alpha} + (1-\\delta)k_{t} \\label{eqn:capital_solution}\\\\\n\\log A_{t+1} & = \\rho \\log A_{t} + \\epsilon_{t+1}. \\label{eqn:tfp_solution}\n\\end{align}\n\nSecond, compute simulated values for $y_t$, $c_t$, and $i_t$ using the following static relationships:\n\n\\begin{align}\ny_t & = A_tk_t^{\\alpha}\\\\\ni_t & = sA_tk_t^{\\alpha}\\\\\nc_t & = (1-s)A_tk_t^{\\alpha},\n\\end{align}\n\nIn the previous example, we estimated $\\rho$ and $\\sigma$ for the US so let's use those values for this simulation. For the other parameter, use the following values for the simulation:\n\n| $A_0$ | $k_0$ | $s$ | $\\alpha$ | $\\delta $ | $T$ |\n|-------|-------|-----|----------|-----------|------|\n| 1 | 8.43 | 0.1 | 0.35 | 0.025 | 201 |\n\nWhere $T$ is the total number of simulation periods (i.e., $t$ will range from $0$ to $200$).\n\n### Function\n\nThe function in the next cell simulates a stochastic Solow growth model. It returns a `DataFrame` with colums equal to the log-deviations of the simulated variables relative to the trend (i.e., nonstochastic steady state) implied by the model.\n\n\n```python\n# Define a function that returns a DataFrame of simulated value from the Solow model with exogenous labor and TFP growth. CELL PROVIDED\ndef solow_stochastic(s,alpha,delta,k0,A0,rho,sigma,T):\n \n '''Function for computing a simulation of the Solow growth model with exogenous labor and TFP growth.\n \n y[t] = A[t]*K[t]^alpha\n k[t+1] = i[t] + (1-delta)*k[t]\n y[t] = c[t] + i[t]\n c[t] = (1-s)*y[t]\n A[t+1] = exp(rho*logA[t] + epsilon[t+1])\n \n Args:\n s (float): Saving rate\n alpha (float): Capital share in Cobb-Douglas production function\n delta (float): Capital depreciation rate\n T (int): Number of periods to simulate\n k0 (float): Initial value of capital per worker\n A0 (float): Initial TFP\n rho (float): AR coeficient for log A[t]\n sigma (float): Standard deviation of shock to log A[t]\n \n Returns:\n Pandas DataFrame\n '''\n # Create epsilon values\n epsilon = np.random.normal(scale=sigma,size=T)\n \n # Initialize capital values\n capital = np.zeros(T)\n\n # Set first value of capital equal to k0\n capital[0] = k0\n \n # Initialize TFP values\n tfp = np.zeros(T)\n\n # Set first value of TFP equal to A0\n tfp[0] = A0\n\n # Iterate over t in range(T-1) to update subsequent values in the capital and tfp arrays\n for t in range(T-1):\n capital[t+1] = s*tfp[t]*capital[t]**alpha + (1-delta)*capital[t]\n tfp[t+1] = np.exp(rho*np.log(tfp[t]) + epsilon[t])\n \n # Compute the values of the other aggregate variables\n output = tfp*capital**alpha\n consumption = (1-s)*output\n investment = s*output\n \n # Compute steady state (or trend) of endogenous vars\n capital_ss = (s/delta)**(1/(1-alpha))\n tfp_ss = 1 \n output_ss = tfp_ss*capital_ss**alpha\n consumption_ss = (1-s)*output_ss\n investment_ss = s*output_ss\n \n \n # Put simulated data into a DataFrame\n df = pd.DataFrame({'output_log_dev':np.log(output/output_ss),\n 'consumption_log_dev':np.log(consumption/consumption_ss),\n 'investment_log_dev':np.log(investment/investment_ss),\n 'capital_log_dev':np.log(capital/capital_ss),\n 'tfp_log_dev':np.log(tfp/tfp_ss)})\n \n # Return the simulated data\n return df\n```\n\n### Simulate the Stochastic Solow Model\n\n\n```python\n# CELL PROVIDED\n# Set parameters for simulation\nalpha=0.35\ns = 0.1\ndelta = 0.025\nk0 = 8.43\nA0=1\nT = 201\n\nnp.random.seed(126)\n# Simulate the model and store output in a variable called 'solow_df'\nsolow_df = solow_stochastic(s,alpha,delta,k0,A0,rho,sigma,T)\n\n# Plot\nfig = plt.figure()\nax = fig.add_subplot(1,1,1)\nsolow_df.plot(ax=ax,grid=True)\nax.legend(loc='center left', bbox_to_anchor=(1, 0.5))\n```\n\n### Simulation Results\n\nCompute the standard deviation of the simulated data and the correlation coefficients of the simulated data\n\n\n```python\n# Standard deviations. CELL PROVIDED\nsolow_df.std()*100\n```\n\n\n\n\n output_log_dev 0.989194\n consumption_log_dev 0.989194\n investment_log_dev 0.989194\n capital_log_dev 0.570985\n tfp_log_dev 0.902910\n dtype: float64\n\n\n\n\n```python\n# Correlation coefficients. CELL PROVIDED\nsolow_df.corr()\n```\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
output_log_devconsumption_log_devinvestment_log_devcapital_log_devtfp_log_dev
output_log_dev1.0000001.0000001.0000000.5139350.981810
consumption_log_dev1.0000001.0000001.0000000.5139350.981810
investment_log_dev1.0000001.0000001.0000000.5139350.981810
capital_log_dev0.5139350.5139350.5139351.0000000.341714
tfp_log_dev0.9818100.9818100.9818100.3417141.000000
\n
\n\n\n\nIt looks like the stochastic Solow model does a god job replicating the volatility (standard deviation) of ouput and consumption relative to the data. However the simulated investment is too small by about a factor of 6. The stochastic Solow model does captures the correlation between output, consumption, and investment, but it implies perfect correlation which is too much.\n\n## The Random Walk Process (Optional)\n\nThe *random walk process* is an AR(1) process with $\\rho=1$:\n\n\\begin{align}\ny_t = y_{t-1} + \\epsilon_t\n\\end{align}\n\nThe random walk process has an important place in finance since the evidence suggests that stock prices follow a random walk process.\n\n### Example\n\nSimulate 7 random walk processes for 501 periods. Set $\\sigma = 1$. Plot all 7 simulated processes on the same ayes.\n\n\n```python\n# CELL PROVIDED \nnp.random.seed(126)\nfor i in range(7):\n plt.plot(ar1_sim(rho=1,T=501))\n \nplt.title('Seven random walk processes')\nplt.grid()\n```\n", "meta": {"hexsha": "dec0b473208f9c3e5a82debfe7e1241cb6882d60", "size": 375924, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Lecture Notebooks/Econ126_Class_10.ipynb", "max_stars_repo_name": "pmezap/computational-macroeconomics", "max_stars_repo_head_hexsha": "b703f46176bb16e712badf752784f8a7b996cdb1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 30, "max_stars_repo_stars_event_min_datetime": "2020-02-29T06:09:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T13:14:13.000Z", "max_issues_repo_path": "Lecture Notebooks/Econ126_Class_10.ipynb", "max_issues_repo_name": "letsgoexploring/computational-macroeconomics", "max_issues_repo_head_hexsha": "b703f46176bb16e712badf752784f8a7b996cdb1", "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 Notebooks/Econ126_Class_10.ipynb", "max_forks_repo_name": "letsgoexploring/computational-macroeconomics", "max_forks_repo_head_hexsha": "b703f46176bb16e712badf752784f8a7b996cdb1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 18, "max_forks_repo_forks_event_min_datetime": "2019-09-24T07:48:49.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T21:36:30.000Z", "avg_line_length": 353.6444026341, "max_line_length": 63440, "alphanum_fraction": 0.9217687618, "converted": true, "num_tokens": 6580, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947117065459, "lm_q2_score": 0.9230391584819669, "lm_q1q2_score": 0.8722671234635191}} {"text": "# Householder triangularization\n\n## Householder Reflections\n\nThe stable way to get a $QR$ factorization is to operate orthogonally (unitarily) in order to produce a triangular $R$. Similar to Gaussian elimination, we proceed one column at a time, zeroing entries below the sub-diagonal. Instead of elementary triangular row operations, though, we can choose from reflections or rotations.\n\n$$\n\\begin{bmatrix} \\times & \\times & \\times \\\\ \\times & \\times & \\times \\\\ \\times & \\times & \\times \\\\ \\times & \\times & \\times \\\\ \\times & \\times & \\times \\\\ \\end{bmatrix} \\stackrel{Q_1}{\\to} \\begin{bmatrix} \\times & \\times & \\times \\\\ 0 & \\times & \\times \\\\ 0 & \\times & \\times \\\\ 0 & \\times & \\times \\\\ 0 & \\times & \\times \\\\ \\end{bmatrix} \\stackrel{Q_2}{\\to} \\begin{bmatrix} \\times & \\times & \\times \\\\ 0 & \\times & \\times \\\\ 0 & 0 & \\times \\\\ 0 & 0 & \\times \\\\ 0 & 0 & \\times \\\\ \\end{bmatrix} \\stackrel{Q_3}{\\to} \\begin{bmatrix} \\times & \\times & \\times \\\\ 0 & \\times & \\times \\\\ 0 & 0 & \\times \\\\ 0 & 0 & 0 \\\\ 0 & 0 & 0 \\\\ \\end{bmatrix}\n$$\n\nThe key step is to find, given $\\mathbf{x}$, a unitary $F$ such that $F\\mathbf{x}=\\alpha \\mathbf{e}_1$ for a scalar $\\alpha$. Since $F$ preserves the 2-norm, $\\alpha= \\pm \\|\\mathbf{x}\\|_2$. One can simply exhibit the solution. Define $\\mathbf{v}=\\alpha \\mathbf{e}_1 - \\mathbf{x}$ and set $$ F = I - 2 \\frac{\\mathbf{v}\\mathbf{v}^*}{\\mathbf{v}^*\\mathbf{v}}.$$\n\nNotice the similarity to the orthogonal projector.\n\n\n\n\n```julia\nm = 5;\nI = eye(m);\nx = randn(m); alpha = norm(x);\nv = alpha*[1;zeros(m-1)] - x;\nF = I - 2*(v*v')/dot(v,v);\nnorm(F'*F-I)\n```\n\n\n\n\n 6.274366372228879e-16\n\n\n\n\n```julia\nF*x\n```\n\n\n\n\n 5-element Array{Float64,1}:\n 2.28349 \n 0.0 \n -5.55112e-17\n 0.0 \n 0.0 \n\n\n\nIn context, $\\mathbf{x}$ is drawn from rows $j$ to $m$ of column $j$, so that $F$ (applied to the lower rows) puts zeros below the diagonal as desired. For example,\n\n\n```julia\nn = 3;\nA = randn(m,n); \nx = A[:,1]; \nv = [ x[1]+sign(x[1])*norm(x); x[2:end] ]; \nv = v/norm(v);\nF = I - 2*(v*v');\nF*A\n```\n\n\n\n\n 5×3 Array{Float64,2}:\n -2.25396 -1.58784 -0.134974 \n 1.71196e-16 0.948728 -0.569928 \n 3.75608e-17 -0.0738045 0.0430322\n -3.20111e-17 -0.261579 0.961307 \n -6.93889e-18 0.558271 1.08048 \n\n\n\nOnce $j$ sweeps from 1 to $n$, the matrix will be transformed into the $R$. If we accumulate the actions of these reflectors, we end up with the $Q$ as well (the full one or the thin one, as we choose). \n\nThere is an some important shortcut to know. In applications we rarely want the actual $Q$ or even the thin $\\hat{Q}$; instead we want the capability of applying $Q$ or $Q^*$ to a given vector. It's more efficient to store the $\\mathbf{v}$ vectors of the reflectors and apply them on demand, using \n\n$$F\\mathbf{z} = \\mathbf{z} - 2\\frac{\\mathbf{v}^*\\mathbf{z}}{\\mathbf{v}^*\\mathbf{v}}v.$$\n\nIn Julia, the `qrfact` command returns the $R$ and the Householder vectors in a compact format. \n\n\n```julia\nQR = qrfact(A)\n```\n\n\n\n\n Base.LinAlg.QRCompactWY{Float64,Array{Float64,2}}([-2.25396 -1.58784 -0.134974; -0.535659 -1.13385 0.169457; … ; -0.37069 -0.125603 0.555754; 0.0120276 0.268067 0.81829],[1.40147 1.24606 0.206231; 6.94734e-310 1.83673 -0.211877; 6.94734e-310 6.94734e-310 1.01089])\n\n\n\nA better-known format is used by LAPACK, which can be called directly (overwriting the input matrix):\n\n\n```julia\nQR = copy(A);\nBase.LinAlg.LAPACK.geqrf!(QR);\n@show QR;\n```\n\n QR = [-2.25396 -1.58784 -0.134974; -0.535659 -1.13385 0.169457; -0.0508576 -0.035439 -1.5458; -0.37069 -0.125603 0.555754; 0.0120276 0.268067 0.81829]\n\n\nThe upper triangle is just $R$, while the lower triangle contains the Householder vectors with first element normalized to 1.\n\n\n```julia\nR = triu(QR); \nHH(v) = eye(length(v)) - 2*(v*v')./(v'*v);\nv1 = [1;QR[2:m,1]]; F1 = HH(v1);\nv2 = [1;QR[3:m,2]]; F2 = HH(v2);\nv3 = [1;QR[4:m,3]]; F3 = HH(v3);\n```\n\n\n```julia\nQ = F1*cat([1,2],eye(1),F2)*cat([1,2],eye(2),F3); # block diagonal constructions\n@show norm(Q*R-A);\n```\n\n norm(Q * R - A) = 5.770966355010983e-16\n\n\n# Complexity of Orthogonal Triangularization\n\n## Complexity of Householder's Algorithm\n\n> ** THEOREM. ** Householder orthogonalization has the following asymptotic operation count is $\\sim 2mn^2-\\frac{2}{3} n^3$, i.e.: $$\\lim_{m,n\\to \\infty} \\frac{\\# \\text{flops}}{2mn^2-\\frac{2}{3}n^3} = 1.$$\n\nIn particular, Householder's Algorithm requires significantly less flops to run than either the classical Gram-Schmidt or the modified Gram-Schmidt.\n\n## Orthogonal Triangularization vs. Triangular Orthogonalization\n\nThe `qr` function in Julia (and Matlab and SciPy), in contrast, defaults to using a Householder QR algorithm. This gives an orthogonal $Q$ matrix and an accurate $R$:\n\n\n```julia\n# Classical Gram–Schmidt (Trefethen algorithm 7.1), implemented in the simplest way\n# (We could make it faster by unrolling loops to avoid temporaries arrays etc.)\nfunction clgs(A)\n m,n = size(A)\n Q = similar(A)\n R = zeros(eltype(A),n,n)\n for j = 1:n\n aⱼ = A[:,j]\n vⱼ = copy(aⱼ) # use copy so that modifying vⱼ doesn't change aⱼ\n for i = 1:j-1\n qᵢ = Q[:,i]\n R[i,j] = dot(qᵢ, aⱼ)\n vⱼ -= R[i,j] * qᵢ\n end\n R[j,j] = norm(vⱼ)\n Q[:,j] = vⱼ / R[j,j]\n end\n return Q, R\nend\n\n# Modified Gram–Schmidt (Trefethen algorithm 8.1)\nfunction mgs(A)\n m,n = size(A)\n Q = similar(A)\n R = zeros(eltype(A),n,n)\n for j = 1:n\n aⱼ = A[:,j]\n vⱼ = copy(aⱼ)\n for i = 1:j-1\n qᵢ = Q[:,i]\n R[i,j] = dot(qᵢ, vⱼ) # ⟵ NOTICE: mgs has vⱼ, clgs has aⱼ\n vⱼ -= R[i,j] * qᵢ\n end\n R[j,j] = norm(vⱼ)\n Q[:,j] = vⱼ / R[j,j]\n end\n return Q, R\nend\n```\n\n\n\n\n mgs (generic function with 1 method)\n\n\n\n\n```julia\n(U,s,V) = svd(randn(80,80));\ns = 2.0.^(-1:-1:-80);\nA = U*diagm(s)*V';\n(Qc,Rc) = clgs(A); # classical\n(Qm,Rm) = mgs(A); # modified\n(Qh,Rh) = qr(A); # Householder\n```\n\n\n\n\n (\n [-0.1891 0.17465 … 0.0313284 -0.0725869; 0.263572 -0.0759909 … -0.101085 -0.0149264; … ; -0.0281206 -0.088226 … -0.0229401 -0.024252; 0.108626 0.0728708 … -0.198116 0.0716586],\n \n [-0.0423232 -0.0273643 … -0.017747 -0.0449594; 0.0 -0.0236431 … 0.0041207 -0.0553444; … ; 0.0 0.0 … 5.03546e-18 -3.3892e-18; 0.0 0.0 … 0.0 8.54912e-18])\n\n\n\n\n```julia\nusing PyPlot\nn = size(A,2)\n```\n\n\n\n\n 80\n\n\n\n\n```julia\nsemilogy(abs(diag(Rh)), \"s\", mfc=\"none\"); semilogy(diag(Rc), \"bo\"); semilogy(diag(Rm), \"rx\")\nsemilogy(2.0 .^ -(1:n), \"k-\"); semilogy(ones(n)*sqrt(eps()), \"b--\"); semilogy(ones(n)*eps(), \"r--\")\nlegend([\"Householder\",\"classical\",\"modified\",L\"2^{-j}\", L\"\\sqrt{\\epsilon_\\mathrm{mach}}\", L\"\\epsilon_\\mathrm{mach}\"], loc=\"lower left\")\nylabel(L\"r_{jj}\"); xlabel(L\"j\")\n```\n\n## A worked example\n\nConsider the following matrix:\n\n$$\nA = \\begin{bmatrix} 12 & -51 & 4\\\\ 6 & 167 & -68\\\\ -4 & 24 & -41 \\end{bmatrix}\n$$\n\nWe want to find the QR factorization via Householder reflectors.\n\nFirst, we need to find a reflection that transforms the first column of matrix A, vector $\\mathbf{a}_1 = (12, 6, -4)^T$, into $\\|\\mathbf{a}_1\\| \\;\\mathrm{e}_1 = (14, 0, 0)^T.$\n\nNow, \n$$\\mathbf{u} = \\mathbf{x} - \\alpha\\mathbf{e}_1,\\quad \\text{and}\\quad \\mathbf{v} = {\\mathbf{u}\\over\\|\\mathbf{u}\\|}.$$\n\nHere, $\\alpha =14$ and $\\mathbf{x} = \\mathbf{a}_1 = (12, 6, -4)^T$\n\nTherefore:\n$$\n\\mathbf{u} = (-2, 6, -4)^T=({2})(-1, 3, -2)^T\\quad \\text{and}\\quad \\mathbf{v} = {1 \\over \\sqrt{14}}(-1, 3, -2)^T,\n$$\n\n\n\\begin{align}\nQ_1 &= I - {2 \\over \\sqrt{14} \\sqrt{14}} \\begin{pmatrix} -1 \\\\ 3 \\\\ -2 \\end{pmatrix}\\begin{pmatrix} -1 & 3 & -2 \\end{pmatrix}\\\\\n&=I - {1 \\over 7}\\begin{pmatrix}\n1 & -3 & 2 \\\\\n-3 & 9 & -6 \\\\\n2 & -6 & 4\n\\end{pmatrix}\\\\\n&= \\begin{pmatrix}\n6/7 & 3/7 & -2/7 \\\\\n3/7 &-2/7 & 6/7 \\\\\n-2/7 & 6/7 & 3/7 \\\\\n\\end{pmatrix}.\n\\end{align}\n\nNow observe:\n\n$$\nQ_{1}A=\\begin{pmatrix}\n14 & 21 & -14 \\\\\n0 & -49 & -14 \\\\\n0 & 168 & -77 \\end{pmatrix},\n$$\n\nso we already have almost a triangular matrix. We only need to zero the $(3, 2)$ entry.\n\nTake the $(1, 1)$ minor, and then apply the process again to\n\n$$\nA^\\prime = M_{11} = \\begin{pmatrix}\n-49 & -14 \\\\\n168 & -77 \\end{pmatrix}.\n$$\n\nBy the same method as above, we obtain the matrix of the Householder transformation\n\n$$\nQ_2 = \\begin{pmatrix}\n1 & 0 & 0 \\\\\n0 & -7/25 & 24/25 \\\\\n0 & 24/25 & 7/25 \\end{pmatrix}\n$$\n\nafter performing a direct sum with 1 to make sure the next step in the process works properly.\n\nNow, we find\n\n$$\nQ=Q_1^T Q_2^T=\\begin{pmatrix}\n6/7 & -69/175 & 58/175 \\\\\n3/7 & 158/175 & -6/175 \\\\\n-2/7 & 6/35 & 33/35 \\end{pmatrix}.\n$$\n\n$$\nR=Q_2Q_1A=Q^T A=\\begin{pmatrix}\n14 & 21 & -14 \\\\\n0 & 175 & -70 \\\\\n0 & 0 & -35 \\end{pmatrix}.\n$$\n\nThe matrix $Q$ is orthogonal and $R$ is upper triangular, so $A = QR$ is the required QR-decomposition. \n\n\n```julia\n\n```\n", "meta": {"hexsha": "717f93279c0ee49cedd70389196a5297a97909fb", "size": 86838, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Householder Triangularization.ipynb", "max_stars_repo_name": "Twelve33/NumericalLinearAlgebra", "max_stars_repo_head_hexsha": "4122cf464712855f81be82eb0e92de27aad1ea31", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-05-23T23:55:16.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-23T23:55:16.000Z", "max_issues_repo_path": "Householder Triangularization.ipynb", "max_issues_repo_name": "Twelve33/NumericalLinearAlgebra", "max_issues_repo_head_hexsha": "4122cf464712855f81be82eb0e92de27aad1ea31", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-04-06T04:19:20.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-28T05:56:52.000Z", "max_forks_repo_path": "Householder Triangularization.ipynb", "max_forks_repo_name": "Twelve33/NumericalLinearAlgebra", "max_forks_repo_head_hexsha": "4122cf464712855f81be82eb0e92de27aad1ea31", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-04-06T04:04:45.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-06T04:04:45.000Z", "avg_line_length": 107.075215783, "max_line_length": 64146, "alphanum_fraction": 0.8503535319, "converted": true, "num_tokens": 3485, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.949669363129097, "lm_q2_score": 0.9184802507195635, "lm_q1q2_score": 0.8722525547475012}} {"text": "# Lab #1: Python Basics\n\nThese exercises are meant to give you some practice with the concepts from Tutorial #1. There's a prompt or two for each section, as well as a final question that brings it all together. GLHF!\n\n***\n## Basic Arithmetic\n\n1. Use the Pythagorean theorem, $a^2 + b^2 = c^2$, to find the hypotenuse length of a right triangle with side lengths $a = 6.1$ and $b = 5.6$.\n\n\n```python\n# Your answer below:\n\n```\n\n2. Use the distance modulus, $m_v - M_v = 5log(d/10 \\text{ pc})$, to find the distance to a star with apparent magnitude $m_v = 0.5$ and absolute magnitude $M_v = -5.85$.\n\n\n```python\n# Your answer below:\n\n```\n\n***\n## Comments\n\n1. Write a single-line comment containing your Swings order.\n\n\n```python\n# Your answer below:\n\n```\n\n2. Write a multi-line comment describing your favorite astronomy fact.\n\n\n```python\n# Your answer below: \n\n```\n\n***\n## Printing\n\n1. Print your favorite letter, number and symbol on the same line.\n\n\n```python\n# Your answer here:\n\n```\n\n***\n## Data types\n\n1. Use both string multiplication and concatenation to print 3 different animal noises\n\n\n```python\n# Your answer here:\n\n```\n\n2. Print a true statement using four comparison operators.\n\n\n```python\n# Your answer here:\n\n```\n\n***\n## Variables\n\n1. Use the quadratic equation, $x = \\frac{-b \\pm \\sqrt{b^2 - 4ac}}{2a}$, to find the roots of $5x^2 + 3x - 1$ by calculating the numerator and denominator separately. (**Tip:** When parintheses in a big equation get a little hard to read, breaking it up like this is a good way to make code easier to read.)\n\n\n```python\n# Your answer here:\n\n```\n\n***\n## User input\n\n1. Prompt the user for their age and calculate the percent of their life they've completed assuming they live to 80 years old.\n\n\n```python\n# Your answer here:\n\n```\n\n***\n## Debugging\n\n1. Rewrite the code below, fixing the errors and formatting with best practices.\n\n\n```python\nX1 = 17.4\nY1 = 15.6\nX2 = 15.1\nY2 = 11.1\n\nDist = sqrt((X2-X1)^2-(Y2+Y1)^2))\nprint(Dist)\n```\n\n***\n\n## Indexing\n\n1. Print the 4th, 9th, and 15th letter and the letter at the 20th, 3rd, and 12th indices of the word \"pneumonoultramicroscopicsilicovolcanoconiosis\" by indexing.\n\n\n```python\n# Your answer below:\n\n```\n\n2. Print the strings \"pneumono,\" \"ultra,\" \"volcano,\" and \"coniosis\" by slicing the word from part one.\n\n\n```python\n# Your answer below:\n\n```\n\n3. Add together every third number in the list [155,2,54,34,5,16,7,38,26,10] and print the result.\n\n\n```python\n# Your answer below\n\n```\n\n## Manipulating strings and lists\n\n1. Fix the string \"peea7nut. bt-tt9r\" with string (or list) functions.\n\n\n```python\n# Your code below:\n\n```\n\n## `numpy` arrays\n\n1. Use the Wien displacement law to calculate the temperatures of blackbodies with 20 peak wavelengths between 300nm and 700nm using arrays.\n\n\\begin{equation}\n \\lambda_{peak}T = 0.29 \\text{ cm K}\n\\end{equation}\n\n\n```python\n# Your code below:\n\n```\n\n***\n\n## Practice: DMS/HMS Converter\n\nWhile DMS (degrees, minutes, seconds) and HMS (hours, minutes, seconds) formats for celestial coordinates have their place (e.g. in every database ever), having them in decimal degrees is often more convenient for calculations. Write two scripts: one that allows the user to enter in a DMS coordinate and prints it in decimal degrees, and another for HMS coordinates.\n\n\n```python\n# Your answer here:\n\n\n```\n", "meta": {"hexsha": "263e9354b3f05e4183b05d765284dfb11d06cd3a", "size": 7903, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "files/ASTR211_Lab1-1.ipynb", "max_stars_repo_name": "mvtea/mvtea.github.io", "max_stars_repo_head_hexsha": "91cb2558e570bba35e2f0718c4c658cd7317bd5d", "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": "files/ASTR211_Lab1-1.ipynb", "max_issues_repo_name": "mvtea/mvtea.github.io", "max_issues_repo_head_hexsha": "91cb2558e570bba35e2f0718c4c658cd7317bd5d", "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": "files/ASTR211_Lab1-1.ipynb", "max_forks_repo_name": "mvtea/mvtea.github.io", "max_forks_repo_head_hexsha": "91cb2558e570bba35e2f0718c4c658cd7317bd5d", "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": 22.388101983, "max_line_length": 373, "alphanum_fraction": 0.5322029609, "converted": true, "num_tokens": 933, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693716759489, "lm_q2_score": 0.9184802356574272, "lm_q1q2_score": 0.8722525482935664}} {"text": "\n\n- __Example 1:__ \n\nFind $logS_t$ for $S \\sim GBM(s,\\mu,\\sigma^2)$, where the dynamics $dS_t = \\mu S_t dt + \\sigma S_t dW_t$ with $S_0 = s.$\n\n__Soln:__\n\nBy using Ito-Doeblin Formula, we have\n\n\\begin{equation}\n\\begin{aligned}\ndlnS_t &= \\frac{1}{S_t} dS_t - \\frac {1}{2} \\frac{1}{S_t^2} \\cdot \\sigma^2 S_t^2dW_tdW_t \\\\\n&= \\mu dt + \\sigma dW_t - \\frac{1}{2} \\sigma^2 dt \\\\\n&= (\\mu - \\frac{1}{2} \\sigma^2)dt + \\sigma dW_t \\\\\n\\end{aligned}\n\\end{equation}\n\nThen, transform this integral form into derivative form, we will get that\n\n\\begin{equation}\n\\begin{aligned}\nlnS_t - lnS_0 &= \\int_0^t (\\mu - \\frac{1}{2} \\sigma^2) \\, ds + \\int_0^t \\sigma dW_s \\\\\nlnS_t &= lns + (\\mu - \\frac{1}{2} \\sigma^2) \\cdot t + \\sigma W_t. \\\\\n\\end{aligned}\n\\end{equation}\n", "meta": {"hexsha": "9e2678bd4a0059c4d14fdb71656887430a29e7f9", "size": 2005, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "src/Hw6_Geometric_Brownian_Motion.ipynb", "max_stars_repo_name": "Jun-629/20MA573", "max_stars_repo_head_hexsha": "addad663d2dede0422ae690e49b230815aea4c70", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Hw6_Geometric_Brownian_Motion.ipynb", "max_issues_repo_name": "Jun-629/20MA573", "max_issues_repo_head_hexsha": "addad663d2dede0422ae690e49b230815aea4c70", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Hw6_Geometric_Brownian_Motion.ipynb", "max_forks_repo_name": "Jun-629/20MA573", "max_forks_repo_head_hexsha": "addad663d2dede0422ae690e49b230815aea4c70", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-02-05T21:42:08.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-05T21:42:08.000Z", "avg_line_length": 32.3387096774, "max_line_length": 251, "alphanum_fraction": 0.4798004988, "converted": true, "num_tokens": 364, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572778073288128, "lm_q2_score": 0.9111797027760038, "lm_q1q2_score": 0.8722521079559323}} {"text": "# Linear Blending Problem\n\n## Problem Statement\n\nA brewery receives an order for 100 gallons of 4% ABV (alchohol by volume) beer. The brewery has on hand beer A that is 4.5% ABV that cost \\\\$0.32 per gallon to make, and beer B that is 3.7% ABV and cost \\\\$0.25 per gallon. Water could also be used as a blending agent at a cost of \\\\$0.05 per gallon. Find the minimum cost blend that meets the customer requirements.\n\n### Solution\n\nWe will use this problem as an opportunity to write a Python function that accepts data on raw materials and customer specifications to produce the lowest cost blend.\n\n#### Representing Problem Data as a Python Dictionary\n\nThe first step is to represent the problem data in a generic manner that could, if needed, be extended to include additional blending components. Here we use a dictionary of materials, each key denoting a blending agent. For each key there is a sub-dictionary containing attributes of each blending component.\n\n\n```python\ndata = {\n 'A': {'abv': 0.045, 'cost': 0.32},\n 'B': {'abv': 0.037, 'cost': 0.25},\n 'W': {'abv': 0.000, 'cost': 0.05},\n}\n```\n\n#### Objective Function\n\nIf we let subscript $c$ denote a blending component from the set of blending components $C$, and denote the volume of $c$ used in the blend as $x_c$, the cost of the blend is\n\n\\begin{align}\n\\mbox{cost} & = \\sum_{c\\in C} x_c P_c\n\\end{align}\n\nwhere $P_c$ is the price per unit volume of $c$. Using the Python data dictionary defined above, the price $P_c$ is given by `data[c]['cost']`.\n\n#### Volume Constraint\n\nThe customer requirement is produce a total volume $V$. Assuming ideal solutions, the constraint is given by\n\n\\begin{align}\nV & = \\sum_{c\\in C} x_c\n\\end{align}\n\nwhere $x_c$ denotes the volume of component $c$ used in the blend.\n\n#### Product Composition Constraint\n\nThe product composition is specified as 4% alchohol by volume. Denoting this as $\\bar{A}$, the constraint may be written as\n\n\\begin{align}\n\\bar{A} & = \\frac{\\sum_{c\\in C}x_c A_c}{\\sum_{c\\in C} x_c}\n\\end{align}\n\nwhere $A_c$ is the alcohol by volume for component $c$. As written, this is a nonlinear constraint. Multiplying both sides of the equation by the denominator yields a linear constraint\n\n\\begin{align}\n\\bar{A}\\sum_{c\\in C} x_c & = \\sum_{c\\in C}x_c A_c\n\\end{align}\n\nA final form for this constraint can be given in either of two versions. In the first version we subtract the left-hand side from the right to give\n\n\\begin{align}\n0 & = \\sum_{c\\in C}x_c \\left(A_c - \\bar{A}\\right) & \\mbox{ Version 1 of the linear blending constraint}\n\\end{align}\n\nAlternatively, the summation on the left-hand side corresponds to total volume. Since that is known as part of the problem specification, the blending constraint could also be written as\n\n\\begin{align}\n\\bar{A}V & = \\sum_{c\\in C}x_c A_c & \\mbox{ Version 2 of the linear blending constraint}\n\\end{align}\n\nWhich should you use? Either will generally work well. The advantage of version 1 is that it is fully specified by a product requirement $\\bar{A}$, which is sometimes helpful in writing elegant Python code.\n\n#### Pyomo Model\n\nA Pyomo implementation of this blending model is shown in the next cell. The model is contained within a Python function so that it can be more easily reused for additional calculations, or eventually for use by the process operator.\n\nNote that the pyomo library has been imported with the prefix `pyomo`. This is good programming practive to avoid namespace collisions with problem data.\n\n\n```python\nimport pyomo.environ as pyomo\n\nvol = 100\nabv = 0.040\n\ndef beer_blend(vol, abv, data):\n \n C = data.keys()\n \n model = pyomo.ConcreteModel()\n \n model.x = pyomo.Var(C, domain=pyomo.NonNegativeReals)\n \n model.cost = pyomo.Objective(expr = sum(model.x[c]*data[c]['cost'] for c in C))\n \n model.vol = pyomo.Constraint(expr = vol == sum(model.x[c] for c in C))\n model.abv = pyomo.Constraint(expr = 0 == sum(model.x[c]*(data[c]['abv'] - abv) for c in C))\n\n solver = pyomo.SolverFactory('glpk')\n solver.solve(model)\n\n print('Optimal Blend')\n for c in data.keys():\n print(' ', c, ':', model.x[c](), 'gallons')\n print()\n print('Volume = ', model.vol(), 'gallons')\n print('Cost = $', model.cost())\n \nbeer_blend(vol, abv, data)\n```\n\n Optimal Blend\n A : 37.5 gallons\n B : 62.5 gallons\n W : 0.0 gallons\n \n Volume = 100.0 gallons\n Cost = $ 27.625\n\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "312ae504b19b361f49425329e91c97a603441a54", "size": 7017, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Mathematics/Mathematical Modeling/06.06-Linear-Blending-Problem.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/06.06-Linear-Blending-Problem.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/06.06-Linear-Blending-Problem.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.0410958904, "max_line_length": 379, "alphanum_fraction": 0.5664814023, "converted": true, "num_tokens": 1222, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951625409307, "lm_q2_score": 0.9334308045480275, "lm_q1q2_score": 0.8721932283363659}} {"text": "```python\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nxc = np.linspace(0, 1, 101) # x coordinates for plotting\n\ndef f(x):\n return 1 + 2*x*(1-x)\n\nimport sympy as sym\nx = sym.symbols('x')\npsi_0 = 1\npsi_1 = sym.sin(sym.pi*x)\n\nhalf = sym.Rational(1,2)\nu = 1*psi_0 + half*psi_1\n\n# How to combine c_0*psi_0 + c_1*psi_1 to match f?\n# Intuitively, c_0=c_1=1...\n# Turn u to function so we can plot and compute with it\nu = sym.lambdify([x], u, modules='numpy')\n\nprint('L2 error of intuitive approximation:', end=' ')\ne = f(xc) - u(xc)\ndx = xc[1] - xc[0]\nprint(np.sqrt(dx*np.sum(e**2)))\n\nplt.plot(xc, f(xc), 'r--')\nplt.plot(xc, u(xc), 'b-')\nplt.legend(['exact', 'intuitive approximation'])\nplt.savefig('tmp1.png'); plt.savefig('tmp1.pdf')\n\n# Do the calculations in the least squares or project method\nA = sym.zeros(2, 2)\nb = sym.zeros(2, 1)\nA[0,0] = sym.integrate(psi_0*psi_0, (x, 0, 1))\nA[0,1] = sym.integrate(psi_0*psi_1, (x, 0, 1))\nA[1,0] = A[0,1]\nA[1,1] = sym.integrate(psi_1*psi_1, (x, 0, 1))\nb[0] = sym.integrate(f(x)*psi_0, (x, 0, 1))\nb[1] = sym.integrate(f(x)*psi_1, (x, 0, 1))\nprint('A:', A)\nprint('b:', b)\nc = A.LUsolve(b)\nc = [sym.simplify(c[i,0]) for i in range(c.shape[0])]\nprint('c:', c, [c_.evalf() for c_ in c])\nu = c[0]*psi_0 + c[1]*psi_1\nprint('u:', u)\nprint(sym.latex(u))\nprint(sym.latex(A))\nprint(sym.latex(c))\nprint(sym.latex(b))\n# Turn u to function so we can plot it\nu = sym.lambdify([x], u, modules='numpy')\n\nprint('L2 error of least squares approximation:', end=' ')\ne = f(xc) - u(xc)\ndx = xc[1] - xc[0]\nprint(np.sqrt(dx*np.sum(e**2)))\n\nplt.plot(xc, u(xc), 'k-')\nplt.legend(['exact', 'guess', 'least squares approx.'],\n loc='lower center')\nplt.savefig('tmp2.png'); plt.savefig('tmp2.pdf')\nplt.show()\n\n\n\n\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "a38dc395357696b808ce81240b321977f0d804d2", "size": 30252, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Data Science and Machine Learning/Machine-Learning-In-Python-THOROUGH/EXAMPLES/FINITE_ELEMENTS/INTRO/EXERCICES/18_PARABOLA_SIN.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": "Data Science and Machine Learning/Machine-Learning-In-Python-THOROUGH/EXAMPLES/FINITE_ELEMENTS/INTRO/EXERCICES/18_PARABOLA_SIN.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": "Data Science and Machine Learning/Machine-Learning-In-Python-THOROUGH/EXAMPLES/FINITE_ELEMENTS/INTRO/EXERCICES/18_PARABOLA_SIN.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": 220.8175182482, "max_line_length": 25836, "alphanum_fraction": 0.8959407642, "converted": true, "num_tokens": 680, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377237352755, "lm_q2_score": 0.9099070017626536, "lm_q1q2_score": 0.8721801862803633}} {"text": "# Sympy - Symbolic algebra in Python\n\nJ.R. Johansson (jrjohansson at gmail.com)\n\nThe latest version of this [IPython notebook](http://ipython.org/notebook.html) lecture is available at [http://github.com/jrjohansson/scientific-python-lectures](http://github.com/jrjohansson/scientific-python-lectures).\n\nThe other notebooks in this lecture series are indexed at [http://jrjohansson.github.io](http://jrjohansson.github.io).\n\n\n```python\n%matplotlib inline\nimport matplotlib.pyplot as plt\n```\n\n## Introduction\n\nThere are two notable Computer Algebra Systems (CAS) for Python:\n\n* [SymPy](http://sympy.org/en/index.html) - A python module that can be used in any Python program, or in an IPython session, that provides powerful CAS features. \n* [Sage](http://www.sagemath.org/) - Sage is a full-featured and very powerful CAS enviroment that aims to provide an open source system that competes with Mathematica and Maple. Sage is not a regular Python module, but rather a CAS environment that uses Python as its programming language.\n\nSage is in some aspects more powerful than SymPy, but both offer very comprehensive CAS functionality. The advantage of SymPy is that it is a regular Python module and integrates well with the IPython notebook. \n\nIn this lecture we will therefore look at how to use SymPy with IPython notebooks. If you are interested in an open source CAS environment I also recommend to read more about Sage.\n\nTo get started using SymPy in a Python program or notebook, import the module `sympy`:\n\n\n```python\nfrom sympy import *\n```\n\nTo get nice-looking $\\LaTeX$ formatted output run:\n\n\n```python\ninit_printing()\n\n# or with older versions of sympy/ipython, load the IPython extension\n#%load_ext sympy.interactive.ipythonprinting\n# or\n#%load_ext sympyprinting\n```\n\n## Symbolic variables\n\nIn SymPy we need to create symbols for the variables we want to work with. We can create a new symbol using the `Symbol` class:\n\n\n```python\nx = Symbol('x')\n```\n\n\n```python\n(pi + x)**2\n```\n\n\n```python\n# alternative way of defining symbols\na, b, c = symbols(\"a, b, c\")\n```\n\n\n```python\ntype(a)\n```\n\nWe can add assumptions to symbols when we create them:\n\n\n```python\nx = Symbol('x', real=True)\n```\n\n\n```python\nx.is_imaginary\n```\n\n\n```python\nx = Symbol('x', positive=True)\n```\n\n\n```python\nx > 0\n```\n\n### Complex numbers\n\nThe imaginary unit is denoted `I` in Sympy. \n\n\n```python\n1+1*I\n```\n\n\n```python\nI**2\n```\n\n\n```python\n(x * I + 1)**2\n```\n\n### Rational numbers\n\nThere are three different numerical types in SymPy: `Real`, `Rational`, `Integer`: \n\n\n```python\nr1 = Rational(4,5)\nr2 = Rational(5,4)\n```\n\n\n```python\nr1\n```\n\n\n```python\nr1+r2\n```\n\n\n```python\nr1/r2\n```\n\n## Numerical evaluation\n\nSymPy uses a library for artitrary precision as numerical backend, and has predefined SymPy expressions for a number of mathematical constants, such as: `pi`, `e`, `oo` for infinity.\n\nTo evaluate an expression numerically we can use the `evalf` function (or `N`). It takes an argument `n` which specifies the number of significant digits.\n\n\n```python\npi.evalf(n=50)\n```\n\n\n```python\ny = (x + pi)**2\n```\n\n\n```python\nN(y, 5) # same as evalf\n```\n\nWhen we numerically evaluate algebraic expressions we often want to substitute a symbol with a numerical value. In SymPy we do that using the `subs` function:\n\n\n```python\ny.subs(x, 1.5)\n```\n\n\n```python\nN(y.subs(x, 1.5))\n```\n\nThe `subs` function can of course also be used to substitute Symbols and expressions:\n\n\n```python\ny.subs(x, a+pi)\n```\n\nWe can also combine numerical evolution of expressions with NumPy arrays:\n\n\n```python\nimport numpy\n```\n\n\n```python\nx_vec = numpy.arange(0, 10, 0.1)\n```\n\n\n```python\ny_vec = numpy.array([N(((x + pi)**2).subs(x, xx)) for xx in x_vec])\n```\n\n\n```python\nfig, ax = plt.subplots()\nax.plot(x_vec, y_vec);\n```\n\nHowever, this kind of numerical evolution can be very slow, and there is a much more efficient way to do it: Use the function `lambdify` to \"compile\" a Sympy expression into a function that is much more efficient to evaluate numerically:\n\n\n```python\nf = lambdify([x], (x + pi)**2, 'numpy') # the first argument is a list of variables that\n # f will be a function of: in this case only x -> f(x)\n```\n\n\n```python\ny_vec = f(x_vec) # now we can directly pass a numpy array and f(x) is efficiently evaluated\n```\n\nThe speedup when using \"lambdified\" functions instead of direct numerical evaluation can be significant, often several orders of magnitude. Even in this simple example we get a significant speed up:\n\n\n```python\n%%timeit\n\ny_vec = numpy.array([N(((x + pi)**2).subs(x, xx)) for xx in x_vec])\n```\n\n\n```python\n%%timeit\n\ny_vec = f(x_vec)\n```\n\n## Algebraic manipulations\n\nOne of the main uses of an CAS is to perform algebraic manipulations of expressions. For example, we might want to expand a product, factor an expression, or simply an expression. The functions for doing these basic operations in SymPy are demonstrated in this section.\n\n### Expand and factor\n\nThe first steps in an algebraic manipulation \n\n\n```python\n(x+1)*(x+2)*(x+3)\n```\n\n\n```python\nexpand((x+1)*(x+2)*(x+3))\n```\n\nThe `expand` function takes a number of keywords arguments which we can tell the functions what kind of expansions we want to have performed. For example, to expand trigonometric expressions, use the `trig=True` keyword argument:\n\n\n```python\nsin(a+b)\n```\n\n\n```python\nexpand(sin(a+b), trig=True)\n```\n\nSee `help(expand)` for a detailed explanation of the various types of expansions the `expand` functions can perform.\n\nThe opposite a product expansion is of course factoring. The factor an expression in SymPy use the `factor` function: \n\n\n```python\nfactor(x**3 + 6 * x**2 + 11*x + 6)\n```\n\n### Simplify\n\nThe `simplify` tries to simplify an expression into a nice looking expression, using various techniques. More specific alternatives to the `simplify` functions also exists: `trigsimp`, `powsimp`, `logcombine`, etc. \n\nThe basic usages of these functions are as follows:\n\n\n```python\n# simplify expands a product\nsimplify((x+1)*(x+2)*(x+3))\n```\n\n\n```python\n# simplify uses trigonometric identities\nsimplify(sin(a)**2 + cos(a)**2)\n```\n\n\n```python\nsimplify(cos(x)/sin(x))\n```\n\n### apart and together\n\nTo manipulate symbolic expressions of fractions, we can use the `apart` and `together` functions:\n\n\n```python\nf1 = 1/((a+1)*(a+2))\n```\n\n\n```python\nf1\n```\n\n\n```python\napart(f1)\n```\n\n\n```python\nf2 = 1/(a+2) + 1/(a+3)\n```\n\n\n```python\nf2\n```\n\n\n```python\ntogether(f2)\n```\n\nSimplify usually combines fractions but does not factor: \n\n\n```python\nsimplify(f2)\n```\n\n## Calculus\n\nIn addition to algebraic manipulations, the other main use of CAS is to do calculus, like derivatives and integrals of algebraic expressions.\n\n### Differentiation\n\nDifferentiation is usually simple. Use the `diff` function. The first argument is the expression to take the derivative of, and the second argument is the symbol by which to take the derivative:\n\n\n```python\ny\n```\n\n\n```python\ndiff(y**2, x)\n```\n\nFor higher order derivatives we can do:\n\n\n```python\ndiff(y**2, x, x)\n```\n\n\n```python\ndiff(y**2, x, 2) # same as above\n```\n\nTo calculate the derivative of a multivariate expression, we can do:\n\n\n```python\nx, y, z = symbols(\"x,y,z\")\n```\n\n\n```python\nf = sin(x*y) + cos(y*z)\n```\n\n$\\frac{d^3f}{dxdy^2}$\n\n\n```python\ndiff(f, x, 1, y, 2)\n```\n\n## Integration\n\nIntegration is done in a similar fashion:\n\n\n```python\nf\n```\n\n\n```python\nintegrate(f, x)\n```\n\nBy providing limits for the integration variable we can evaluate definite integrals:\n\n\n```python\nintegrate(f, (x, -1, 1))\n```\n\nand also improper integrals\n\n\n```python\nintegrate(exp(-x**2), (x, -oo, oo))\n```\n\nRemember, `oo` is the SymPy notation for inifinity.\n\n### Sums and products\n\nWe can evaluate sums and products using the functions: 'Sum'\n\n\n```python\nn = Symbol(\"n\")\n```\n\n\n```python\nSum(1/n**2, (n, 1, 10))\n```\n\n\n```python\nSum(1/n**2, (n,1, 10)).evalf()\n```\n\n\n```python\nSum(1/n**2, (n, 1, oo)).evalf()\n```\n\nProducts work much the same way:\n\n\n```python\nProduct(n, (n, 1, 10)) # 10!\n```\n\n## Limits\n\nLimits can be evaluated using the `limit` function. For example, \n\n\n```python\nlimit(sin(x)/x, x, 0)\n```\n\nWe can use 'limit' to check the result of derivation using the `diff` function:\n\n\n```python\nf\n```\n\n\n```python\ndiff(f, x)\n```\n\n$\\displaystyle \\frac{\\mathrm{d}f(x,y)}{\\mathrm{d}x} = \\frac{f(x+h,y)-f(x,y)}{h}$\n\n\n```python\nh = Symbol(\"h\")\n```\n\n\n```python\nlimit((f.subs(x, x+h) - f)/h, h, 0)\n```\n\nOK!\n\nWe can change the direction from which we approach the limiting point using the `dir` keywork argument:\n\n\n```python\nlimit(1/x, x, 0, dir=\"+\")\n```\n\n\n```python\nlimit(1/x, x, 0, dir=\"-\")\n```\n\n## Series\n\nSeries expansion is also one of the most useful features of a CAS. In SymPy we can perform a series expansion of an expression using the `series` function:\n\n\n```python\nseries(exp(x), x)\n```\n\nBy default it expands the expression around $x=0$, but we can expand around any value of $x$ by explicitly include a value in the function call:\n\n\n```python\nseries(exp(x), x, 1)\n```\n\nAnd we can explicitly define to which order the series expansion should be carried out:\n\n\n```python\nseries(exp(x), x, 1, 10)\n```\n\nThe series expansion includes the order of the approximation, which is very useful for keeping track of the order of validity when we do calculations with series expansions of different order:\n\n\n```python\ns1 = cos(x).series(x, 0, 5)\ns1\n```\n\n\n```python\ns2 = sin(x).series(x, 0, 2)\ns2\n```\n\n\n```python\nexpand(s1 * s2)\n```\n\nIf we want to get rid of the order information we can use the `removeO` method:\n\n\n```python\nexpand(s1.removeO() * s2.removeO())\n```\n\nBut note that this is not the correct expansion of $\\cos(x)\\sin(x)$ to $5$th order:\n\n\n```python\n(cos(x)*sin(x)).series(x, 0, 6)\n```\n\n## Linear algebra\n\n### Matrices\n\nMatrices are defined using the `Matrix` class:\n\n\n```python\nm11, m12, m21, m22 = symbols(\"m11, m12, m21, m22\")\nb1, b2 = symbols(\"b1, b2\")\n```\n\n\n```python\nA = Matrix([[m11, m12],[m21, m22]])\nA\n```\n\n\n```python\nb = Matrix([[b1], [b2]])\nb\n```\n\nWith `Matrix` class instances we can do the usual matrix algebra operations:\n\n\n```python\nA**2\n```\n\n\n```python\nA * b\n```\n\nAnd calculate determinants and inverses, and the like:\n\n\n```python\nA.det()\n```\n\n\n```python\nA.inv()\n```\n\n## Solving equations\n\nFor solving equations and systems of equations we can use the `solve` function:\n\n\n```python\nsolve(x**2 - 1, x)\n```\n\n\n```python\nsolve(x**4 - x**2 - 1, x)\n```\n\nSystem of equations:\n\n\n```python\nsolve([x + y - 1, x - y - 1], [x,y])\n```\n\nIn terms of other symbolic expressions:\n\n\n```python\nsolve([x + y - a, x - y - c], [x,y])\n```\n\n## Further reading\n\n* http://sympy.org/en/index.html - The SymPy projects web page.\n* https://github.com/sympy/sympy - The source code of SymPy.\n* http://live.sympy.org - Online version of SymPy for testing and demonstrations.\n\n## Versions\n\n\n```python\n%reload_ext version_information\n\n%version_information numpy, matplotlib, sympy\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "42f8439be4a2c344eb96b6df38474951e5d82284", "size": 32378, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "001-Jupyter/001-Tutorials/004-Scientific-Python-Lectures/Lecture-5-Sympy.ipynb", "max_stars_repo_name": "jhgoebbert/jupyter-jsc-notebooks", "max_stars_repo_head_hexsha": "bcd08ced04db00e7a66473b146f8f31f2e657539", "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": "001-Jupyter/001-Tutorials/004-Scientific-Python-Lectures/Lecture-5-Sympy.ipynb", "max_issues_repo_name": "jhgoebbert/jupyter-jsc-notebooks", "max_issues_repo_head_hexsha": "bcd08ced04db00e7a66473b146f8f31f2e657539", "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": "001-Jupyter/001-Tutorials/004-Scientific-Python-Lectures/Lecture-5-Sympy.ipynb", "max_forks_repo_name": "jhgoebbert/jupyter-jsc-notebooks", "max_forks_repo_head_hexsha": "bcd08ced04db00e7a66473b146f8f31f2e657539", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-13T18:49:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-13T18:49:12.000Z", "avg_line_length": 18.5866819747, "max_line_length": 299, "alphanum_fraction": 0.5100067947, "converted": true, "num_tokens": 3070, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625107731765, "lm_q2_score": 0.936285002192296, "lm_q1q2_score": 0.8721143789413052}} {"text": "# Specific simulation techniques #\n\n## Simulation through plug-in ##\n\nIn serveral cases it is more convenient to exploit known analytical relations between a random variable $X$ and one or more other variables $Y_1, \\dots, Y_n$, that is $X = g(Y_1, \\dots, Y_n)$ for some function $g$, in order to simulate $X$ itself. This is particularly convenient when the direct simulation of $Y_i$'s is simpler than that of $X$, and the computation of $g$ is not heavy. In such cases the simulation is said to be performed through a _plug-in_ approach.\n\nThe simplest relation to be exploited is based on the sum of random variables, and it leads to the so-called _decompositional_ simulating approach. Simply put, if $X = Y_1 + \\dots + Y_n$ simulating $X$ can be translated into generating separately values $y_1, \\dots, y_n$ for $Y_1, \\dots, Y_n$ and subsequently sum them.\n\nThis approach is on the basis of a simple simulation procedure for the binomial distribution that avoids the somehow complex procedure based on the inverse transformation technique: as any random variable $X$ following a binomial distribution of parameters $n \\in \\mathbb N$ and $p \\in [0, 1]$ can be expressed as the sum of $n$ i.i.d. Bernoulli variables $Y_1, \\dots, Y_n$ with parameter $p$, the following procedure arises.\n\n\n```python\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport math\nfrom scipy import random\nfrom ipywidgets import widgets, interact\nfrom IPython.display import display, clear_output\n\ndef binomial(n, p):\n return sum([1 if random.random() <= p else 0 for i in range(n)])\n```\n\n\n```python\n%matplotlib notebook\n\nfrom scipy.special import binom\n\ndef ecdf(data):\n sorted = np.sort(data)\n yvals = np.arange(len(sorted))/float(len(sorted))\n return((sorted, yvals))\n\nbinom_button = widgets.Button(description='Simulate')\nbinom_n_selector = widgets.IntSlider(min=2, max=10, value=4, description='$n$')\nbinom_p_selector = widgets.FloatSlider(min=0, max=1, value=.6, description='$p$')\n\nfig_binom_simulation, ax_binom_simulation = plt.subplots()\n\ndef binomial_simulation(n, p):\n data = [binomial(n, p) for i in range(1000)]\n vals = np.arange(0, n+1)\n probs = [binom(n, i) * p**i * (1-p)**(n-i) for i in vals]\n cum_probs = np.cumsum(probs)\n\n clear_output()\n ax_binom_simulation.clear()\n \n for line in zip(zip(vals[:-1], vals[1:]), cum_probs):\n ax_binom_simulation.plot(line[0], [line[1]]*2, 'b')\n \n x_ecdf, y_ecdf = ecdf(data)\n ax_binom_simulation.plot(x_ecdf, y_ecdf, 'ko', markersize=2, alpha=.7)\n plt.ylim(0, 1.1)\n plt.xlim(0, max(vals)*1.1)\n \n display(fig_binom_simulation)\n\n\nbinom_button.on_click(lambda b: binomial_simulation(binom_n_selector.value, binom_p_selector.value))\ndisplay(binom_button)\n\ninteract(binomial_simulation, n=binom_n_selector, p=binom_p_selector)\n```\n\n\n \n\n\n\n\n\n\nThe same approach can be applied to a random variable $X$ following a Gamma distribution, whose density depends from two parameters $k \\in \\mathbb N$ and $\\lambda \\in \\mathbb R^+$ as follows\n\n$$\nf_X(x) = \\frac{\\lambda^k}{\\Gamma(k)} x^{k-1} \\mathrm e^{-\\lambda x} \\mathrm I_{\\mathbb R^+}(x),\n$$\n\nwhere $\\Gamma(z) = \\int_0^{+\\infty} x^{z-1} \\mathrm e^{-x} \\mathrm d x$ is the gamma function, characterized by the property $\\Gamma(z+1) = z \\Gamma(z)$ and thus representing an extension of the factorial function defined for all positive real numbers. As it can be shown that $X$ has the same distribution of the sum of $k$ independent exponential random variables with paramter $\\lambda$, the following panel implements a routine that simulates the gamma distribution using the decompositional approach and tests it.\n\n\n```python\nfrom scipy import stats\n\ndef gamma(k, _lambda):\n return sum([-1/_lambda * math.log(random.random()) for i in range(int(k))])\n\ngamma_button = widgets.Button(description='Simulate')\ngamma_k_selector = widgets.IntSlider(min=2, max=10, value=4, description='$k$')\ngamma_l_selector = widgets.FloatSlider(min=0, max=4, value=.6, description='$\\\\lambda$')\n\nfig_gamma_simulation, ax_gamma_simulation = plt.subplots()\n\ndef gamma_simulation(k, _lambda):\n data = [gamma(k, _lambda) for i in range(1000)]\n vals = np.arange(0, 10, .1)\n\n clear_output()\n ax_gamma_simulation.clear()\n \n x_ecdf, y_ecdf = ecdf(data)\n ax_gamma_simulation.plot(x_ecdf, y_ecdf, 'ko', markersize=2, alpha=.7)\n \n cdfs = map(lambda x: stats.gamma.cdf(x, k, scale=1/_lambda), vals)\n ax_gamma_simulation.plot(vals, cdfs, 'b')\n \n display(fig_gamma_simulation)\n\n\ngamma_button.on_click(lambda b: gamma_simulation(gamma_k_selector.value, gamma_l_selector.value))\ndisplay(binom_button)\n\ninteract(gamma_simulation, k=gamma_k_selector, _lambda=gamma_l_selector)\n```\n\n\n \n\n\n\n\n\n\nMore in general, any relation among random variables can be exploited. Consider for instance the fact that a specification of a geometric distribution of parameter $p \\in (0, 1]$ can be interpreted as the number of consecutive insuccesses in a sequence of independent Bernoulli experiments of parameter $p$ before the first success. Therefore, a generated value, say $n$, for a geometric random variable can be converted into a sequence of $n$ values, that is $n-1$ zeroes followed by a one. The use of a python generator allow to obtain an elegant implementation of this technique.\n\n\n```python\ndef bernoulli(p):\n while True:\n insuccesses = (int) (math.log(random.random())/math.log(1-p))+1\n for i in range(insuccesses-1):\n yield 0\n yield 1\n\nbernoulli_button = widgets.Button(description='Simulate')\nbernoulli_p_selector = widgets.FloatSlider(min=0, max=1, value=0.25)\n\nfig_bernoulli_simulation, ax_bernoulli_simulation = plt.subplots()\n\ndef bernoulli_simulation(p):\n bg = bernoulli(p)\n data = [bg.next() for i in range(1000)]\n vals = (0, 1)\n probs = (1-p, p)\n cum_probs = np.cumsum(probs)\n\n clear_output()\n ax_bernoulli_simulation.clear()\n \n for line in zip(zip(vals[:-1], vals[1:]), cum_probs):\n ax_bernoulli_simulation.plot(line[0], [line[1]]*2, 'b')\n \n x_ecdf, y_ecdf = ecdf(data)\n ax_bernoulli_simulation.plot(x_ecdf, y_ecdf, 'ko', markersize=2, alpha=.7)\n plt.ylim(0, 1.1)\n plt.xlim(0, max(vals)*1.1)\n \n display(fig_bernoulli_simulation)\n\n\nbernoulli_button.on_click(lambda b: bernoulli_simulation(bernoulli_p_selector.value))\ndisplay(bernoulli_button)\n\ninteract(bernoulli_simulation, p=bernoulli_p_selector)\n \n```\n\n\n \n\n\n\n\n\n\nAnother example of relation to be exploited for optimizing a simulation procedure is that linking the exponential and Poisson distributions. Indeed, in a Poisson process of parameter $\\lambda$ the inter-occurrence time of events is distributed according to an exponential distribution of parameter $\\lambda$, and the number of occurrences of events in an interval of unitary length follows a Poisson distribution having the same parameter. Thus, instead of relying on the trivial application of the inverse transformation technique, the Poisson distribution can be simulated through repeated generation of exponential inter-occurrence times until getting an event whose occurrence time exceeds 1. In formal terms, denoting by $n$ the specification of the Poisson variable and with $e_1, \\dots, e_n, \\dots$ a succession of specifications of the exponential variables in the related process,\n\n$$\nn = \\max_{m \\in \\mathbb N} \\left\\{ \\sum_{i=1}^m e_i \\leq 1 \\right\\}.\n$$\n\nReplacing $e_i$ with the corresponding expression simulating the exponential random variable in funtion of a specification $u_i$ of a uniform distibution over $[0, 1]$ we obtain\n\n$$\nn = \\max_{m \\in \\mathbb N} \\left\\{ \\sum_{i=1}^m -\\frac{1}{\\lambda} \\ln u_i \\leq 1 \\right\\},\n$$\n\nand the latter expression is equivalent to\n\n$$\nn = \\max_{m \\in \\mathbb N} \\left\\{ \\prod_{i=1}^m u_i \\geq \\mathrm e^{-\\lambda} \\right\\}\n = \\min_{m \\in \\mathbb N} \\left\\{ \\prod_{i=1}^m u_i < \\mathrm e^{-\\lambda} \\right\\} - 1.\n$$\n\nNote how the last form is suitable for an algorithmic implementation, in that the only way to acknowledge that the maximum value $m$ such that the product of $m$ terms exceeds a threshold has been reached is through detection of the first time that this threshold is not exceeded. Note also that the implementation should rely on the fact that $\\prod_{i=1}^0 u_i = 1$, as a counterpart of $\\sum_{i=1}^0 e_i = 0$.\n\n\n```python\ndef poisson(_lambda):\n n = 0\n u = 1\n while u >= math.exp(-_lambda):\n u *= random.random()\n n += 1\n return n-1\n\npoiss_button = widgets.Button(description='Simulate')\npoiss_l_selector = widgets.FloatSlider(min=0.01, max=10, value=3, description='$\\lambda$')\n\nfig_poiss_simulation, ax_poiss_simulation = plt.subplots()\n\ndef poisson_simulation(_lambda):\n data = [poisson(_lambda) for i in range(1000)]\n max_x = 9\n vals = np.arange(0, max_x)\n probs = [math.exp(-_lambda)]\n for i in range(1, max_x+1):\n probs.append(probs[-1]* _lambda /i)\n cum_probs = np.cumsum(probs)\n\n clear_output()\n ax_poiss_simulation.clear()\n \n for line in zip(zip(vals[:-1], vals[1:]), cum_probs):\n ax_poiss_simulation.plot(line[0], [line[1]]*2, 'b')\n \n x_ecdf, y_ecdf = ecdf(data)\n ax_poiss_simulation.plot(x_ecdf, y_ecdf, 'ko', markersize=2, alpha=.7)\n plt.ylim(0, 1)\n plt.xlim(0, max_x)\n \n display(fig_poiss_simulation)\n\n\npoiss_button.on_click(lambda b: poisson_simulation(poiss_l_selector.value))\ndisplay(poiss_button)\n\n_ = interact(poisson_simulation, _lambda=poiss_l_selector)\n```\n\n\n \n\n\n\n\n\n\nThere are several distributions explicitly defined as specific functions of other distributions: in these cases, applying the plug-in principle is straightforward. There is a special set of distributions describing the efficiency of usual estimators when dealing with a normal population, such as the Student's t distribution (which we met as an introductory example to the course and which was actually simulated via plug-in) or the chi-squared distribution. The latter is described as the distribution of the sum of $k$ squared standard normal random variables, where $k \\in \\mathbb N$ parametrizes the distribution. This definition suggests the following implementation for a simulating algorithm, based on the approximated generation of standard normal variables introduced in the previous lecture.\n\n\n```python\ndef std_random_appr():\n return sum([random.random() for i in range(12)]) - 6\n\ndef chi_square(k):\n return sum([std_random_appr()**2 for i in range(int(k))])\n\nchisq_button = widgets.Button(description='Simulate')\nchisq_k_selector = widgets.IntSlider(min=1, max=10, value=4, description='$k$')\n\nfig_chisq_simulation, ax_chisq_simulation = plt.subplots()\n\ndef chi_square_simulation(k):\n data = [chi_square(k) for i in range(1000)]\n vals = np.arange(0, 30, .5)\n\n clear_output()\n ax_chisq_simulation.clear()\n \n x_ecdf, y_ecdf = ecdf(data)\n ax_chisq_simulation.plot(x_ecdf, y_ecdf, 'ko', markersize=2, alpha=.7)\n \n cdfs = map(lambda x: stats.chi2.cdf(x, k), vals)\n ax_chisq_simulation.plot(vals, cdfs, 'b')\n \n display(fig_chisq_simulation)\n\n\nchisq_button.on_click(lambda b: chi_square_simulation(chisq_k_selector.value))\ndisplay(chisq_button)\n\n_ = interact(chi_square_simulation, k=chisq_k_selector)\n```\n\n\n \n\n\n\n\n\n\n## Compositional method ##\n\nInstead of simulating a given distribution, in several occasions arises the need of simulating a _mixture_ of distributions. More precisely, one wants to pick at random one among $n$ distributions (defined over a same domain) and simulate it. Think for instance to a video game programmer who aims at generating a set of characters who can be, say, humans, trolls, or elves, and each of these populations is characterized by a specific variety in physical qualities such as for instance gender, height and so on. In these cases, the so-called _compositional method_ comes to the rescue: it consists simply in using one of the simulation algorithms for discrete distributions in order to preliminary select one of the populations to be subsequently simulated.\n\nThe following cell implements a general version of this technique, accepting as first argument a list of function each simulating the different populations and as second argument another list containing the probability values of a discrete distribution over the populations. The latter distribution is simulated using the basic approach introduced in Lecture 3.\n\n\n```python\ndef simulate_discrete_rv(vals, probs, n=1):\n cum_probs = np.cumsum(probs)\n result = []\n for k in range(n):\n u = random.random()\n i = 0\n while u >= cum_probs[i]:\n i += 1\n result.append(vals[i])\n return result if n > 1 else result[0]\n\ndef mixture(pops, weights, n=1):\n s = sum(weights)\n if s != 1:\n weights = np.array(weights) / s\n \n ind = simulate_discrete_rv(range(len(weights)), weights, n)\n return [pops[i]() for i in ind] if n>1 else pops[ind]()\n```\n\nIn order to test this implementation, let's consider a mixture of three normal distributions: as a first step, we implement two functions that obtain the density and c.d.f. of a mixture from those of their components:\n\n\n```python\ndef mixture_cdf(x, mus, sigmas):\n return sum(np.array([stats.norm.cdf(x, *p)\n for p in zip(mus, sigmas)])*weights)\n\ndef mixture_pdf(x, mus, sigmas):\n return sum(np.array([stats.norm.pdf(x, *p)\n for p in zip(mus, sigmas)])*weights)\n\nmus = (1, 2, 3)\nsigmas = (.1, .2, .1)\nweights = (.3, .6, .1)\n\nplt.figure()\nvals = np.arange(0, 4, 0.01)\nplt.plot(vals, map(lambda x: mixture_pdf(x, mus, sigmas), vals))\nplt.show()\n```\n\n\n \n\n\n\n\n\n\nThe only missing tool is a function simulating a generic normal distribution: we can resort to the one introduced at the end of Lecture 4, which in turn relies on the previously used approximated method for the standard normal distribution.\n\n\n```python\ndef gen_normal(mu, sigma):\n z = std_random_appr()\n return mu + sigma * z\n\nmixture(map(lambda p: (lambda: gen_normal(*p)), zip(mus, sigmas)),\n weights, 10)\n```\n\n\n\n\n [1.5349802705606732,\n 2.03369682720166,\n 1.010061456822578,\n 2.5268213652288525,\n 2.102624127083847,\n 1.9883270447716723,\n 1.090887177547244,\n 2.129834310706286,\n 1.8989867616114329,\n 2.0582829711447173]\n\n\n\nWe have now everything in place to perform a simulation of the gaussian mixture: the following panel tests the implementation, generating a new sample at each button press and superimposing as usual the graphs of theorical and empirical c.d.f.s.\n\n\n```python\nmixture_button = widgets.Button(description='Simulate')\nfig_mixture_simulation, ax_mixture_simulation = plt.subplots()\n\ndef mixture_simulation(b):\n ax_mixture_simulation.clear()\n clear_output()\n\n data = mixture(map(lambda p: (lambda: gen_normal(*p)), zip(mus, sigmas)),\n weights, 1000)\n\n x_ecdf, y_ecdf = ecdf(data)\n ax_mixture_simulation.plot(x_ecdf, y_ecdf, 'ko', markersize=2, alpha=.7)\n\n vals = np.arange(0, 4, .1)\n cdfs = map(mixture_cdf, vals)\n ax_mixture_simulation.plot(vals, cdfs, 'b')\n display(fig_mixture_simulation)\n \n\nmixture_simulation(mixture_button)\nmixture_button.on_click(mixture_simulation)\ndisplay(mixture_button)\n\n```\n\n\n \n\n\n\n\n\n\n## Acceptance-rejection methods ##\n\nLet $X$ denote a discrete random variable which we are interested in simulating. Suppose that we don't know how to do it, or how to do it efficiently. Suppose also that we are able, instead, to simulate another discrete random variable $Y$ defined over the same domain of $X$. Denote $p_i = \\mathrm P(X=i)$, $q_i = \\mathrm P(Y=i)$ for all meaningful $i$ and assume that $c \\in \\mathbb R$ is a constant such that $p_i/q_i \\leq c$ for all $i$ such that $p_i > 0$. Consider the following algorithm:\n\n- do\n - $i$ = simulate($Y$)\n - $u$ = random()\n - accept = $\\left( u < \\frac{p_i}{c q_i} \\right)$\n- while(!accept)\n- return $i$\n\n**Theorem** The repeated invocation of this algorithm, the set of returned values is indistinguishable from a sample drawn from $X$, that is, denoted $X_G$ the random variable accounting for the values returned by the algorithm, for each $i$ we have $\\mathrm P(X_G=i) = p_i$. Moreover, the number of iterations in the above loop follows a geometric distribution of parameter $1/c$.\n\n_Proof_ For a generic $i$ we have\n\n$$\n\\mathrm P(Y=i \\cap \\text{the loop ends}) = \\mathrm P(Y=i) \\mathrm P(\\text{the loop ends}|Y=i)\n= q_i \\frac{p_i}{c q_i} = \\frac{p_i}{c}.\n$$\n\nNow, the number of iterations before the loop ends is obviously described by a geometric distribution whose parameter equals the probability that after one iteration the loop ends. The latter probability amounts to\n\n$$\n\\mathrm P(\\text{the loop ends}) = \\sum_i \\mathrm P(Y=i \\cap \\text{the loop ends})\n= \\sum_i \\frac{p_i}{c} = \\frac{1}{c}.\n$$\n\nFinally,\n\n$$\\begin{align}\n\\mathrm P(X_G=i) &= \\sum_{n=1}^{+\\infty} P(Y=i \\cap \\text{the loop ends after $n$ iterations}) \\\\\n &= \\sum_{n=1}^{+\\infty} \\left( 1 - \\frac{1}{c} \\right)^{n-1} \\frac{p_i}{c} \\\\\n &= \\frac{p_i}{c} \\sum_{m=0}^{+\\infty} \\left( 1 - \\frac{1}{c} \\right)^m \\\\\n &= \\frac{p_i}{c} \\frac{1}{1-\\left( 1 - \\frac{1}{c} \\right)} = p_i,\n\\end{align}$$\n\nwhere the infinite sum converges because $p_i/q_i \\leq c$ is equivalent to $\\sum_i p_i \\leq c \\sum_i q_i$ and thus $c \\geq 1$: this ensures that $\\left| 1 - \\frac{1}{c} \\right| = 1 - \\frac{1}{c}$, thus the convergence criterion will be $1 - \\frac{1}{c} < 1$ or, equivalently, $c > 0$, which is implied by $c \\geq 1$. ∎\n\nNote that, being the number of loop iterations distributed according to a geometric law of parameter $\\frac{1}{c}$, the average number of terations will be $c$ and thus it will be convenient to choose such values as small as possible.\n\nAs an example, consider the following probability mass function of a random variable $X$:\n\n$$\n\\mathrm P(X=i) = \\frac{(1-p)^i}{(- \\ln p) i} \\mathrm I_{\\mathbb N \\backslash \\{ 0 \\}}(i) =: p_i,\n$$\n\nfor $p \\in (0, 1)$. Such a variable is said to follow a _logarithmic_ distribution, taking its name from the fact that the analytical form of the probability mass function is linked to the McLaurin expansion a particular logarithmic function. Indeed, if $f(q) = \\ln (1-q)$,\n\n$$\\begin{align}\nf^{(i)}(q) = -(i-1)!(1-q)^{-i} \\\\\nf^{(i)}(0) = -(i-1)! \\\\\nf(0) = 0\n\\end{align}$$\n\nThus the McLaurin expansion of $f$ is\n\n$$\n\\ln(1-q) = \\sum_{i=1}^{+\\infty} \\frac{-(i-1)!}{i!}q^i = \\sum_{i=1}^{+\\infty} -\\frac{q^i}{i}.\n$$\n\nNow, substituting $p = 1 - q$ in the above relation gives as result\n\n$$\n-\\ln p = \\sum_{i=1}^{+\\infty} \\frac{(1-p)^i}{i},\n$$\n\nso that the $\\sum_{i=1}^{+\\infty}p_i = 1$.\n\nIn order to simulate the logarithmic distribution through the acceptance-rejection method, it is necessary to find out the equivalent of the distribution of $Y$ and the value for $c$ in the method formulation. Note that\n\n$$\np_i = \\frac{(1-p)^i}{(-\\ln p) i} = \\frac{1}{-\\ln p} \\frac{1-p}{i} (1-p)^{i-1},\n$$\n\nso that $\\frac{1}{-\\ln p}$ emerges as a possible value for $c$. Moreover, it is easy to show that\n\n$$\n\\frac{1-p}{i} \\leq p \\leftrightarrow p \\geq \\frac{1}{2}.\n$$\n\nThus, assuming that $p \\geq \\frac{1}{2}$ holds we have $p_i \\leq c p(1-p)^{i-1} =: c q_i$, with $q_i$ identifies a geometric distribution with parameter $p$. In order to finalize the simulation algorithm, note that\n\n$$\n\\frac{p_i}{c q_i} = \\frac{(1-p)^i}{(-ln p) i} \\frac{-\\ln p}{p(1-p)^{i-1}} = \\frac{1-p}{ip}.\n$$\n\nThus the logarithmic distribution can be simulated through the following algorithm:\n\n- do\n - $i = \\left\\lceil \\frac{\\ln \\text{random()}}{\\ln (1-p)} \\right\\rceil$\n - accept $= \\left( \\text{random()} \\leq \\frac{1-p}{ip} \\right)$\n- while !accept\n- return $i$\n\nNote also that the average number of iterations of this algorithm will be $-\\ln p$.\n\n\n```python\ndef logarithmic(p):\n accept = False\n while(not accept):\n i = int(math.log(random.random())/math.log(1-p))+1\n accept = (random.random() <= (1-p)/(i*p))\n\n return i\n\nlog_button = widgets.Button(description='Simulate')\nlog_p_selector = widgets.FloatSlider(min=0.5, max=0.99, value=.3, description='$p$')\n\nfig_log_simulation, ax_log_simulation = plt.subplots()\n\ndef logarithmic_simulation(p):\n data = [logarithmic(p) for i in range(1000)]\n max_x = 10\n vals = np.arange(1, max_x+1)\n probs = [(1-p)**i / (-math.log(p)*i) for i in vals]\n cum_probs = np.cumsum(probs)\n\n clear_output()\n ax_log_simulation.clear()\n \n for line in zip(zip(vals[:-1], vals[1:]), cum_probs):\n ax_log_simulation.plot(line[0], [line[1]]*2, 'b')\n \n x_ecdf, y_ecdf = ecdf(data)\n ax_log_simulation.plot(x_ecdf, y_ecdf, 'ko', markersize=2, alpha=.7)\n plt.ylim(0, 1)\n plt.xlim(0, max_x+1)\n \n display(fig_log_simulation)\n\n\nlog_button.on_click(lambda b: logarithmic_simulation(log_p_selector.value))\ndisplay(log_button)\n\n_ = interact(logarithmic_simulation, p=log_p_selector)\n```\n\n\n \n\n\n\n\n\n\nWhen dealing with continuous distributions, the acceptance-rejection algorithm is essentially unchanged, although now it deals with densities rather than with probability masses: as in the discrete case, let $X$, $Y$, $f_X$, and $f_Y$ denote, respectively, the random variable we aim at simulating and a random variable which we can efficiently simulate, and lthe corresponding densities. Given a constant $c$ such that $\\frac{f_X(x)}{f_Y(x) \\leq c$ for each $x$, the algorithm implementing the acceptance-rejection technique has the following form:\n\n- do\n - $y$ = simulate($Y$)\n - $u$ = random()\n - accept = $\\left( u < \\frac{f_X(y)}{c f_Y(y)} \\right)$\n- while(!accept)\n- return $y$\n\nThe previously introduced proof can be trivially transferred to this new form of the algorithm, so that also in this case it ca be proven that the random variable $X_G$ accounting for the values returned by this algorithm will be distributed according to a density equal to $f_X$, and the number of iterations of the algorithm will follow a geometric distribution of parameter $\\frac{1}{c}$.\n\nAs an application example, consider the following density:\n\n$$\nf_X(x) = \\frac{1}{B(a, b)} x ^{a-1} (1-x)^{b-1} \\mathrm I_{(0, 1)}(x),\n$$\n\nwith $a, b \\in \\mathbb R^+$ and $B(a, b) = \\frac{\\Gamma(a)\\Gamma(b)}{\\Gamma(a+b)}$ is the so-called beta function. A random variable whose density can be expressed as $f_X$ is said to follow the _beta distribution_. In order to simulate this distribution using the acceptance-rejection technique it is necessary to find a second random variable which we known how to simulate and the corresponding value for the constant $c$. Concerning the first choice, note that as the domain of the beta distribution is $[0, 1]$ it is possible to refer to a random variable $U$ uniformly distributed over the same set. In this case, being $f_U(x)=1$, $c$ should satisfy the relation\n\n$$\n\\frac{f_X(x)}{f_U(x)} = f_X(x) \\leq c.\n$$\n\nThus, a strategy for chosing $c$ consists in setting it to the maximum value of $f_X$, which in turn can be found through nullifying the first derivative of the density. This derivative assumes the form\n\n$$\nf_X'(x) = \\frac{1}{B(a, b)} \\left( (a-1) x^{a-2} (1-x)^{b-1} + (b-1) x^{a-1} (1-x)^{b-2} \\right),\n$$\n\nand $f_X'(x) = 0$ if and only if $(a-1)(1-x) = (b-1) x$, which in turn is equivalent to\n\n$$\nx = \\frac{a-1}{a+b-2}.\n$$\n\nThis implies that\n\n$$\nc = f_X\\left( \\frac{a-1}{a+b-2} \\right)\n = \\frac{1}{B(a, b)} \\left( \\frac{a-1}{a+b-2} \\right) \\left( \\frac{b-1}{a+b-2} \\right).\n$$\n\nFinally,\n\n$$\n\\frac{f_X(x)}{c f_U(x)} = \\frac{\\frac{1}{B(a, b)} x ^{a-1} (1-x)^{b-1}}{\\frac{1}{B(a, b)} \\left( \\frac{a-1}{a+b-2} \\right) \\left( \\frac{b-1}{a+b-2} \\right)}\n= \\left( x \\frac{a+b-2}{a-1} \\right) \\left( (1-x) \\frac{a+b-2}{b-1} \\right)\n$$\n\nSumming up, the acceptance-rejection technique for the beta distribution translates to the following algorithm:\n\n- do\n - $u$ = random()\n - $u_{\\mathrm{acc}}$ = random()\n - accept = $\\left( u_{\\mathrm{acc}} \\leq \\left( u \\frac{a+b-2}{a-1} \\right) \\left( (1-u) \\frac{a+b-2}{b-1} \\right) \\right)$\n- while(!accept)\n- return $u$\n\nThe following cell implements this algorithm.\n\n\n```python\ndef beta(a, b):\n accept = False\n while not accept:\n u = random.random()\n u_acc = random.random()\n accept = (u_acc <= (u*(a+b-2)/(a-1))**(a-1) * ((1-u)*(a+b-2)/(b-1))**(b-1))\n return u\n```\n\nIn order to test this implementation we can set up a function that accepts a value for $a$ and $b$ and produces a graph comparing the c.d.f. of the corresponding beta distribution and the empirical c.d.f. obtained from a set of 500 simulated values from the same distribution.\n\n\n```python\ndef simulate_beta(a, b):\n plt.figure()\n \n data = [beta(a, b) for i in range(500)]\n \n x_ecdf, y_ecdf = ecdf(data)\n plt.plot(x_ecdf, y_ecdf, 'ko', markersize=2, alpha=.7)\n\n vals = np.arange(0, 2, .01)\n cdfs = map(lambda x: stats.beta.cdf(x, a, b), vals)\n plt.plot(vals, cdfs, 'b')\n plt.show()\n```\n\nThe following cell tests the simulation for $a=2$ and $b=5$.\n\n\n```python\nsimulate_beta(2, 5)\n```\n\n\n \n\n\n\n\n\n\nAnalogously, the following cell tests the values $a = b = 9$.\n\n\n```python\nsimulate_beta(9, 9)\n```\n\n\n \n\n\n\n\n\n\nThings are different if we consider $a = 0.9$ and $b = 0.5$:\n\n\n```python\nsimulate_beta(.9, .5)\n```\n\n\n \n\n\n\n\n\n\nIn this case the tests fails because for this choice of parameters we obtain a value $c < 1$: \n\n\n```python\nfrom scipy import special\n\ndef c(a, b):\n return special.beta(a, b) * ((a-1)/(a+b-2)) * ((b-1)/(a+b-2))\n\nc(.9, .5)\n```\n\n\n\n\n 0.29649440549928935\n\n\n\nThe acceptance-rejection tecnique can be applied exploiting a different choice of the companion distribution. Consider for instance a random variable $Y$ with density $f_Y(y) = a y^{a-1} \\mathrm I_{(0, 1)}(y)$, so that\n\n$$\n\\frac{f_X(x)}{f_Y(x)} = \\frac{1}{a B(a, b)} (1-x)^{b-2} \\leq \\frac{1}{a B(a, b)} =: c,\n$$\n\nand the ratio $\\frac{f_x(x)}{c f_Y(x)}$ amounts to $(1-x)^{b-1}$. Finally, note that as $F_Y(y) = y^a$, the random variable $Y$ can be easily simulated through a direct application of the inverse transformation method obtaining $Y = \\sqrt[a]{U}$, and $X$ can therefore be simulated as follows:\n\n- do\n - $u$ = random()\n - $y = \\sqrt[a]{u}$\n - $u_{\\mathrm{acc}}$ = random()\n - accept = $\\left( u_{\\mathrm{acc}} \\leq (1-y)^{b-1} \\right)$\n- while(!accept)\n- return $y$\n\n## Exercises ##\n\n- The simulation of a Bernoulli distribution exploiting the plug-in principle through generation of a geometric random variable can be optimized in function of the involved parameter $p$. Indeed when $p > \\frac{1}{2}$ the procedure can be made more efficient if it generates the subsequent number of successes rather than the number of insuccesses. Modify the proposed implementation in order to apply this enhancement.\n", "meta": {"hexsha": "0711dfef088ab8a7c300f3e30145d478f44d9bf1", "size": 696948, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "lecture-5-specific-simulation-techniques.ipynb", "max_stars_repo_name": "dariomalchiodi/simulation-book", "max_stars_repo_head_hexsha": "f8722fd6ca4e68e05f06659b5d006a1afd6ae1a4", "max_stars_repo_licenses": ["CC-BY-3.0", "MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2017-03-04T11:21:22.000Z", "max_stars_repo_stars_event_max_datetime": "2017-06-07T23:09:07.000Z", "max_issues_repo_path": "lecture-5-specific-simulation-techniques.ipynb", "max_issues_repo_name": "dariomalchiodi/simulation-book", "max_issues_repo_head_hexsha": "f8722fd6ca4e68e05f06659b5d006a1afd6ae1a4", "max_issues_repo_licenses": ["CC-BY-3.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": "lecture-5-specific-simulation-techniques.ipynb", "max_forks_repo_name": "dariomalchiodi/simulation-book", "max_forks_repo_head_hexsha": "f8722fd6ca4e68e05f06659b5d006a1afd6ae1a4", "max_forks_repo_licenses": ["CC-BY-3.0", "MIT"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2017-02-28T08:11:03.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-17T16:58:16.000Z", "avg_line_length": 72.0657636232, "max_line_length": 41369, "alphanum_fraction": 0.6767090228, "converted": true, "num_tokens": 7794, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850057480346, "lm_q2_score": 0.931462503162843, "lm_q1q2_score": 0.8721143751279011}} {"text": "(motion_in_1d)=\n# Motion in 1D\n\n## Position, velocity, and acceleration\n\nThe position of a body as a function of time, denoted by \\\\(x(t)\\\\), is relative to some arbitrary chosen origin where \\\\(x=0\\\\).\n\n**Velocity $v(t)$** is a measure of **how rapidly and the direction which the position of the body is changing**:\n\n\\\\[v=\\frac{\\Delta x}{\\Delta t}=\\frac{x(t+\\Delta t)-x(t)}{\\Delta t}\\\\]\n\nAs \\\\(\\Delta t\\to 0\\\\):\n\n\\\\[v=\\frac{dx}{dt}\\\\]\n\n**Acceleration \\\\(a(t)\\\\)** is a measure of **how fast and in which direction the velocity is changing**:\n\n\\\\[a=\\frac{\\Delta v}{\\Delta t}=\\frac{v(t+\\Delta t)-v(t)}{\\Delta t}\\\\]\n\nAs \\\\(\\Delta t\\to 0\\\\):\n\n\\\\[a=\\frac{dv}{dt}=\\frac{d^2x}{dt^2}\\\\]\n\n## Force\n\nA force is **any interaction that changes the motion of an object**. This is encapsulated by Newton's first and second law of motion.\n\n**Newton's first law of motion** states that a body continues to move at the same velocity if not acted upon by external forces. This concept is referred to as intertia, the tendency of a body to maintain its motion when no net force acts on that body.\n\n**Newton's second law of motion** states that the acceleration of a body is proportional to the net force acting on that body, and inversely proportional to the mass of that body. In other words:\n\n\\\\[F=ma\\\\]\n\nFrom this, the unit of force in SI units is \\\\(kgms^{-2}\\\\), which is defined as Newton (\\\\(N\\\\)).\n\nForces are broadly classified into **contact forces**, which involves physical contact between bodies, and **non-contact forces**, which can act at a distance. Therefore, pulling of a rope is a contact force, whereas magnetism is a non-contact force.\n\n### Gravity\n\nGravitational force is a non-contact, attractive force that acts between any pair of bodies with mass. It is proportional to the mass of each body, inversely proportional to the square of the distance between the centre of those bodies, and acts in a direction that aligns with a straight line connecting the centre of the bodies. Mathematically:\n\n\\\\[F=\\frac{Gm_am_b}{R_{ab}^2}\\\\]\n\nwhere \\\\(m_a\\\\) is the mass of body A, \\\\(m_b\\\\) is the mass of body B, \\\\(R_{ab}\\\\) is the distance between the two bodies, and \\\\(G\\\\) is the gravitational constant equal to \\\\(6.674*10^{-11}m^3kg^{-1}s^{-2}\\\\).\n\nThe force acting upon a body of unit mass m by the Earth with mass \\\\(5.972\\times10^{24}kg\\\\) and radius \\\\(6.371\\times10^3m\\\\) is:\n\n\\\\[F=\\frac{m(5.972\\times10^{24})(6.674\\times10^{-11})}{(6.371\\times10^3)^2}=9.8m=mg\\\\]\n\nwhere \\\\(g=9.8ms^{-2}\\\\), or acceleration due to gravity.\n\n### Falling objects\n\nConsidering objects free-falling solely under gravity:\n\n\\\\[\\frac{d^2x}{dt^2}=-g,\\\\\\\\\\\\\n\\frac{dx}{dt}=v=v_0-gt,\\\\\\\\\\\\\nx=x_0+v_0t-\\frac{1}{2}gt^2\\\\]\n\nwhere \\\\(x_0\\\\) and \\\\(v_0\\\\) are initial position and initial velocity respectively.\n\nFirst we will include libraries needed in the solutions:\n\n\n```python\nimport numpy as np\n%matplotlib inline\nimport matplotlib.pyplot as plt\nfrom sympy import Function, Symbol, diff, dsolve, pprint, integrate\nfrom matplotlib import animation, rc\nfrom IPython.display import HTML\n```\n\n## Tutorial Problem 1.2\n\nIf a rock were ejected from a volcano at an initial speed of \\\\(200m/s\\\\), what would be the maximum height that it reaches above the top of the volcano? And how long will it take to reach that height?\n\n\n```python\ndef x(x0, v0, t, g=9.81):\n return x0 + v0*t - g*t**2/2 \n\nx0 = 0 # initial position\nv0 = 200 # initial velocity\n\n# x = 0 when rock at top of volcano\n# (-9.8t**2)/2 + 200t = 0\n# t = 0s or 40.8s\n#choosing this time span for graph purposes\n\ntime = np.arange(0, 40.8, 0.1) \n\n#try different time spans to check if the max value changes\n\nposition = x(x0, v0, time)\n \nprint(\"Max height reached = %.f m\" % (max(position))) \nresult = np.where(position == max(position)) # find index of maximum position\nprint(\"Time needed for the body to reach that height = %.2fs\" % (time[result[0][0]]))\n\n\n# plot position over time\nfig = plt.figure(figsize=(6,4))\n\nplt.plot(time, position, 'k')\nplt.plot(time[result[0][0]], max(position), 'ro')\nplt.xlabel('time (s)')\nplt.ylabel('height (m)')\nplt.title('Motion of the rock over time', fontsize=14)\nplt.grid(True)\n\nplt.show()\n```\n\n### More about contact forces\n\n**Newton's third law of motion** states that when two bodies interact, when a force is exerted from a body A to body B, a force **equal in magnitude and opposite in direction** is exerted by body B to body A. \n\nTherefore, on the surface of contact between two bodies, there is contact force and a **normal force \\\\(N\\\\)** with the same magnitude and in opposite direction to that of the contact force.\n\n### Friction\n\nFriction is a contact force that always acts **tangential** to the contact surface between two bodies, and acts in a direction that **prevents relative motion** between those bodies. \n\nThe maximum friction that can be exerted is equal to \\\\(\\mu_dN\\\\) where \\\\(\\mu_d\\\\) is the **coefficient of friction**. If the force exerted in tangential direction is less than \\\\(\\mu_dN\\\\), friction is not overcome and there won't be relative motion.\n\nWhen tangential force \\\\(F\\\\) is larger than \\\\(\\mu_dN\\\\), net force on the body in the tangential direction is \\\\((F-\\mu_dN)N\\\\).\n\n## Tutorial Problem 1.3\n\nConsider a stone of mass \\\\(m = 24kg\\\\) sitting on a flat valley floor, being hit by a gust of wind that exerts a horizontal force \\\\(F = 5N\\\\) on it for a period of time \\\\(T = 5s\\\\). Assuming the coefficient of friction between the rock and the ground is \\\\(\\mu = 0.01\\\\), find the distance travelled by the rock before it stops sliding.\n\n\n```python\nm = 24 # mass (kg)\nF = 5 # force of wind (N)\nT = 5 # time wind exert force on rock (s)\nu = 0.01 # coefficient of friction\ng = 9.81 # m/s2\n\ntime1 = np.arange(0., 5.01, 0.01) # time blown by wind\n\ntime2 = np.arange(0.01, 5.63, 0.01) # time before stopping\n\ntime = np.arange(0, 10.63, 0.01) # total amount of time\n\nx = np.zeros(len(time))\n\nv = np.zeros(len(time))\n\n# Newton's second law to find acceleration\n# net force = F - uN\n# N = mg\n# a = (F-umg)/m\n\n# x = x0 + v0t + at**2/2\nx[:501] = ((F-u*m*g)*time1**2)/(2*m) # distance over time travelled when blown by wind\n\n# v = v0 + at\nv[:501] = (F-u*m*g)*time1/m # velocity over time when blown by wind\n\n# net force = -umg\n# a = -umg/m = -ug\n# x0 = last element calculated in x\n# v0 = last element calculated in v\n\n# x = x0 + v0t - at**2/2\nx[501:] = x[500] + v[500]*time2 - u*g*time2**2/2 # distance over time without wind\n\n# v = v0 + at\nv[501:] = v[500] - u*g*time2 # velocity over time without wind\n\nprint(\"Total distance travelled = %.2fm\" % (x[-1]))\n\n\n# plot figure of distance and velocity of the rock over time\n\nfig = plt.figure(figsize=(12,6))\n\nax1 = fig.add_subplot(121)\nax1.plot(time, x, 'r')\nax1.set_xlabel('time (s)')\nax1.set_ylabel('distance (m)')\nax1.set_ylim(0, 3)\nax1.set_title('Position of rock over time', fontsize=14)\nax1.grid(True)\n\nax2 = fig.add_subplot(122)\nax2.plot(time, v, 'b')\nax2.set_xlabel('time (s)')\nax2.set_ylabel('velocity (m/s)')\nax2.set_ylim(0, 0.6)\nax2.set_title('Velocity of rock over time', fontsize=14)\nax2.grid(True)\n\nplt.show()\n```\n\n### Viscous drag force\n\n\n\nResistance from fluid arise from its **viscosity** \\\\(\\mu\\\\), and it is called the viscous drag force.\n\nFor a spherical solid particle moving through a stationary fluid, or a fluid flowing past a stationary body, Stoke's law states that:\n\n\\\\[F=-6\\pi \\mu Rv\\\\]\n\nwhere \\\\(R\\\\) is the radius of the particle, and \\\\(v\\\\) is the relative velocity between the body and the fluid. The minus sign implies it opposes the particle's motion.\n\nWeight of the grain \\\\(F_w\\\\) is given by:\n\n\\\\[F_w=m_sg=\\rho_sVg=\\rho_s\\frac{4}{3}\\pi R^{3}g\\\\]\n\nwhere \\\\(m_s\\\\) is mass of the particle, \\\\(\\rho_s\\\\) is its density, and \\\\(V\\\\) its volume.\n\nBuoyancy force \\\\(F_b\\\\) is the weight of water displaced:\n\n\\\\[F_b=m_wg=\\rho_wVg=\\rho_w\\frac{4}{3}\\pi R^3g\\\\]\n\nAccounting all these forces into Newton's second law:\n\n\\\\[\\frac{4}{3}\\pi\\rho_sR^3\\frac{d^2x}{dt^2}=\\rho_s\\frac{4}{3}\\pi R^3g-\\rho_w\\frac{4}{3}\\pi R^3g-6\\pi \\mu Rv\\\\]\n\nRearranging this gives an ODE:\n\n\\\\[\\rho_s\\frac{dv}{dt}=(\\rho_s-\\rho_w)g-\\frac{9}{2}\\frac{\\mu v}{R^2}\\\\]\n\nwhich can be solved analytically.\n\n## Tutorial Problem 1.5\n\nFind the terminal velocity of spherical particles with densities \\\\(\\rho_s=2.65\\times10^3kgm^{-3}\\\\), and radii \\\\(10\\mu m\\\\), \\\\(100\\mu m\\\\), \\\\(1mm\\\\), and \\\\(1cm\\\\). \n\nDensity of water \\\\(\\rho_w=1000kgm^{-3}\\\\), viscosity of water \\\\(\\mu=10^{-3}\\\\), and the velocity of a sphere from rest through a viscous fluid is given by:\n\n\\\\[v=\\frac{2(\\rho_s-\\rho_w)gR^2}{9\\mu}(1-e^{\\frac{-9\\mu t}{2\\rho_sR^2}})\\\\]\n\nAs \\\\(t\\to \\infty\\\\), \\\\(v\\to \\frac{2(\\rho_s-\\rho_w)gR^2}{9\\mu}\\\\), which is the terminal velocity.\n\n\n```python\ndef velocity(t, R, ps=2650, pw=1000, g=9.81, mu=10e-3):\n return (2*(ps-pw)*g*R**2)/(9*mu) * (1-np.exp((-9*mu*t)/(2*ps*R**2))) # analytical solution to ode\n\ndef t_v(radius, start, end, interval):\n t = np.arange(start, end, interval)\n v = np.zeros(len(t))\n for i in range(len(t)):\n v[i] = velocity(t[i], radius)\n return t, v # obtain list of time and velocity for particles with different radius over a time interval\n\nt_1cm, v_1cm = t_v(1e-2, 0, 50, 0.05)\nt_1mm, v_1mm = t_v(1e-3, 0, 0.5, 0.0005)\nt_10um, v_10um = t_v(10e-6, 0, 1e-4, 1e-7)\nt_1um, v_1um = t_v(1e-6, 0, 5e-7, 5e-10)\n\nprint(\"Terminal velocity of 1um grain is %.2e m/s\" % (v_1um[-1]))\nprint(\"Terminal velocity of 10um grain is %.2e m/s\" % (v_10um[-1]))\nprint(\"Terminal velocity of 1mm grain is %.2f m/s\" % (v_1mm[-1]))\nprint(\"Terminal velocity of 1cm grain is %.2f m/s\" % (v_1cm[-1]))\n\n# plot figures of velocity over time for grains of different radii\n\nfig = plt.figure(figsize=(16,12))\n\nax1 = fig.add_subplot(221)\nax1.plot(t_1um, v_1um, 'r')\nax1.set_xlabel('time (s)')\nax1.set_ylabel('velocity (m/s)')\nax1.set_title('Velocity of sand grains with radius 1um over time')\nax1.grid(True)\n\nax2 = fig.add_subplot(222)\nax2.plot(t_10um, v_10um, 'y')\nax2.set_xlabel('time (s)')\nax2.set_ylabel('velocity (m/s)')\nax2.set_title('Velocity of sand grain with radius 10um over time')\nax2.grid(True)\n\nax3 = fig.add_subplot(223)\nax3.plot(t_1mm, v_1mm, 'g')\nax3.set_xlabel('time (s)')\nax3.set_ylabel('velocity (m/s)')\nax3.set_title('Velocity of sand grain with radius 1mm over time')\nax3.grid(True)\n\nax4 = fig.add_subplot(224)\nax4.plot(t_1cm, v_1cm, 'b')\nax4.set_xlabel('time (s)')\nax4.set_ylabel('velocity (m/s)')\nax4.set_title('Velocity of sand grain with radius 1cm over time')\nax4.grid(True)\n\nplt.show()\n```\n\n### Elastic Spring Forces\n\nAccording to Hooke's law, the force applied to the spring \\\\(F\\\\) is directly proportional to its extension \\\\(x\\\\). Mathematically:\n\n\\\\[F=kx\\\\]\n\nwhere k is the spring constant in \\\\(Nm^{-1}\\\\).\n\n#### Coupled Oscillators\n\nConsider two masses, \\\\(m_1\\\\) and \\\\(m_2\\\\), connected by a spring with spring constant \\\\(k\\\\). Let the position of \\\\(m_1\\\\) be \\\\(x_1\\\\), and the position of \\\\(m_2\\\\) be \\\\(x_2\\\\).\n\nFrom this, the length of the spring is \\\\((x_2-x_1)\\\\), and the change in length is \\\\(\\Delta(x_2-x_1)=\\Delta x_2-\\Delta x_1\\\\).\n\nApplying Hooke's law into Newton's second law to \\\\(m_1\\\\):\n\n\\\\[k(\\Delta x_2-\\Delta x_1)=m_1\\frac{d^2x_1}{dt^2}\\\\]\n\nApplying the same laws for \\\\(m_2\\\\), and considering Newton's third law:\n\n\\\\(-k(\\Delta x_2-\\Delta x_1)=m_2\\frac{d^2x_2}{dt^2}\\\\)\n\nThese two equations are coupled and must be solved simultaneously.\n\n## Tutorial Problem 1.6\n\n\n\nThe oscillatory solutions to the problem are of the form \\\\(x_1=A_1e^{i\\omega t}\\\\), \\\\(x_2=A_2e^{i\\omega t}\\\\). Substitute these expressions into the coupled equations, and solve the eigenvalue problem, finding the two values of \\\\(\\omega\\\\) which are the eigenvalues, and the ratio \\\\(\\frac{A_2}{A_1}\\\\) that corresponds to each eigenvalue.\n\nDiscuss your results.\n\nHint: solving the problem analytically, you should obtain the following:\n\nWhen \\\\(\\omega_1=0\\\\), \\\\(A_1=A_2\\\\)\n\nWhen \\\\(\\omega_2=\\sqrt{\\frac{2k}{m}}\\\\), \\\\(A_1=-A_2\\\\)\n\n\n```python\nimport cmath\n\nw = np.pi\n\nt = np.arange(0, 2*np.pi, 0.01)\nX1 = np.zeros(len(t))\nX2 = np.zeros(len(t))\nX3 = np.zeros(len(t))\nX4 = np.zeros(len(t))\n\nfor i in range(len(t)):\n # w1 = 0\n # A1 = A2\n z1 = cmath.exp(1j*w*t[i])+1\n X1[i] = z1.real\n z2 = cmath.exp(1j*w*t[i])-1\n X2[i] = z2.real\n \n # w2 = (2k/m)**0.5\n # A1 = -A2\n # starting at different initial positions\n z3 = cmath.exp(1j*w*t[i])+1\n X3[i] = z3.real\n z4 = -(cmath.exp(1j*w*t[i]))-1\n X4[i] = z4.real\n```\n\n\n```python\n# now we make a nice animation\nnframes = len(t)\n\n# Plot background axes\nfig, axes = plt.subplots(2,1, figsize=(7,5))\n\nline1, = axes[0].plot([], [], 'ro', lw=2)\nline2, = axes[0].plot([], [], 'go', lw=2)\nline3, = axes[1].plot([], [], 'yo', lw=2)\nline4, = axes[1].plot([], [], 'bo', lw=2)\n\nfor ax in axes:\n ax.set_xlim(-2,2)\n ax.set_ylim(-0.1,0.1)\n \naxes[0].set_title('A1 = A2')\naxes[1].set_title('A1 = -A2')\n \nlines = [line1, line2, line3, line4]\n \nplt.subplots_adjust(hspace=0.5)\n\n# Plot background for each frame\ndef init():\n for line in lines:\n line.set_data([], [])\n return lines\n\n# Set what data to plot in each frame\ndef animate(i):\n \n x1 = X1[i]\n y1 = 0\n lines[0].set_data(x1, y1)\n \n x2 = X2[i]\n y2 = 0\n lines[1].set_data(x2, y2)\n \n x3 = X3[i]\n y3=0\n lines[2].set_data(x3, y3)\n \n x4 = X4[i]\n y4 = 0\n lines[3].set_data(x4, y4)\n \n return lines\n\n# Call the animator\nanim = animation.FuncAnimation(fig, animate, init_func=init,\n frames=nframes, interval=10, blit=True)\n```\n\n\n```python\nHTML(anim.to_html5_video())\n```\n\n\n\n\n\n\n\n\n### References\n\nCourse notes from Lecture 1 of the module ESE 95011 Mechanics\n", "meta": {"hexsha": "97d87778a3229cf99394cba9ca3b0b2c09b08c19", "size": 238617, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/a_modules/mechanics/1_Motion_in_1D.ipynb", "max_stars_repo_name": "primer-computational-mathematics/book", "max_stars_repo_head_hexsha": "305941b4f1fc4f15d472fd11f2c6e90741fb8b64", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-08-02T07:32:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-16T16:40:43.000Z", "max_issues_repo_path": "notebooks/a_modules/mechanics/1_Motion_in_1D.ipynb", "max_issues_repo_name": "primer-computational-mathematics/book", "max_issues_repo_head_hexsha": "305941b4f1fc4f15d472fd11f2c6e90741fb8b64", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2020-07-27T10:45:26.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-12T15:09:14.000Z", "max_forks_repo_path": "notebooks/a_modules/mechanics/1_Motion_in_1D.ipynb", "max_forks_repo_name": "primer-computational-mathematics/book", "max_forks_repo_head_hexsha": "305941b4f1fc4f15d472fd11f2c6e90741fb8b64", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2020-08-05T13:57:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-02T19:03:57.000Z", "avg_line_length": 148.3936567164, "max_line_length": 65040, "alphanum_fraction": 0.8809933911, "converted": true, "num_tokens": 4460, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632329799585, "lm_q2_score": 0.9161096216057903, "lm_q1q2_score": 0.872011066185734}} {"text": "# https://en.wikipedia.org/wiki/Finite_difference\n\nThree forms are commonly considered: forward, backward, and central differences.[1][2][3]\n\nA forward difference is an expression of the form\n\n$$ \\displaystyle \\Delta _{h}[f](x)=f(x+\\Delta x)-f(x).$$\nDepending on the application, the spacing h may be variable or constant. When omitted, $\\Delta x=h$ is taken to be 1: Δ[ f ](x) = Δ1[ f ](x).\n\nA backward difference uses the function values at x and x − \\Delta, instead of the values at x + \\Delta and x:\n\n$$ \\displaystyle \\nabla _{h}[f](x)=f(x)-f(x-\\Delta x).$$\n\nFinally, the central difference is given by\n\n$$\\displaystyle \\delta _{h}[f](x) = f\\left(x+{\\tfrac {1}{2}}\\Delta x\\right)-f\\left(x-{\\tfrac {1}{2}}\\Delta x \\right) $$\n\nThe derivative of a function f at a point x is defined by the limit.\n\n$$ f'(x)=\\lim_{h\\to 0} {\\frac {f(x+h)-f(x)}{h}} $$\n\n\n```python\n# red dashes, blue squares and green triangles\n#Example: [a,b], n\n# https://matplotlib.org/users/pyplot_tutorial.html\nimport numpy as np\nimport matplotlib.pyplot as plt\na=0\nb=1\nn=3\ndeltax=(b-a)/n\ndeltax\n# evenly sampled time at delta x intervals\nx = np.arange(a, b+deltax, deltax)\n#x = np.linspace(a, b, n+1)\nx\nx = np.linspace(-3, 3, 50)\ny2 = x**2+1\n\n\nplt.figure()\n#set x limits\nplt.xlim((0, 2))\nplt.ylim((0, 3))\n\n# set new sticks\nnew_sticks = np.linspace(0, 2, 5)\nplt.xticks(new_sticks)\n# set tick labels\nplt.yticks(np.arange(0, 5, step=1))\n\n# set line styles\n\nl2, = plt.plot(x, y2, color='red', linewidth=1.0, linestyle='--', label='f(x)= x^2+1')\n\nplt.legend(loc='upper left')\n\nplt.show()\n```\n\n\n \n\n\nplot a secant line pass the points (0,1) and (1,2)\n\n\n\n```python\nimport matplotlib.pyplot as plt\nimport numpy as np\n\ndef main():\n # x = np.linspace(-2,2,100)\n a=-2\n b=3\n divx=0.01\n x = np.arange(a, b, divx)\n x1=0\n p1 = int((x1-a)/divx) #starts from zero\n deltax=1\n count_deltax=int(deltax/divx)\n p2 = p1+ count_deltax #starts from zero\n\n y1 = main_func(x)\n y2 = calculate_secant(x, y1, p1, p2)\n plot(x, y1, y2)\n plt.show()\n\ndef main_func(x):\n return x**2+1\n\ndef calculate_secant(x, y, p1, p2):\n points = [p1, p2]\n m, b = np.polyfit(x[points], y[points], 1)\n return m * x + b\n\ndef plot(x, y1, y2):\n plt.plot(x, y1)\n plt.plot(x, y2)\n #set x limits\n plt.xlim((-2, 2))\n #set x limits\n plt.ylim((0, 4))\n\nmain()\n```\n\nQ1: Please draw a tangent line at the poit (1,2) of the function f(x).\n\n\n```python\nimport matplotlib.pyplot as plt\nimport numpy as np\n\ndef main():\n # x = np.linspace(-2,2,100)\n a=-2\n b=2\n divx=0.001\n x = np.arange(a, b, divx)\n x1=1\n p1 = int((x1-a)/divx) #starts from zero\n deltax=0.01\n x2=x1+deltax\n count_deltax=int((x2-x1)/divx)\n p2 = p1+ count_deltax #starts from zero\n\n y1 = main_func(x)\n y2 = calculate_secant(x, y1, p1, p2)\n plot(x, y1, y2)\n plt.show()\n\ndef main_func(x):\n return x**2+1\n\ndef calculate_secant(x, y, p1, p2):\n points = [p1, p2]\n m, b = np.polyfit(x[points], y[points], 1)\n print(m)\n return m * x + b\n\ndef plot(x, y1, y2):\n plt.plot(x, y1)\n plt.plot(x, y2)\n #set x limits\n plt.xlim((-2, 2))\n #set x limits\n plt.ylim((0, 4))\n\nmain()\n```\n\nQ2: Please calculate the approximate value of the slope of a tangent line at the poit (1,2) of the function f(x).\n\nThe slope of the tangent line at a point $x=1$ is equal to the value of the derivative of a function f at a point $x=1$.\n\nThe derivative of a function f at a point $x=1$ is defined by the limit.\n\n$$ f'(x)=\\lim_{h\\to 0} {\\frac {f(x+h)-f(x)}{h}}=2x $$\n$$ f'(x)={\\frac{d}{dx}} f(x)={\\frac{d}{dx}}x^2=2x $$\n$$ f'(x=1)=2*1=2 $$\n\n\n\nThe derivative of a function f at a point $x=1$ is defined by the limit.\nh=0.01\n$$ f'(x=1)=\\lim_{h\\to 0} {\\frac {f(x+h)-f(x)}{h}} $$\nh=0.01\n\n\n```python\nfrom sympy import diff, Symbol, sin, tan\nx = Symbol('x')\ndiff(main_func(x), x)\n```\n\n\n\n\n 2*x\n\n\n\nforward difference\n\n\n```python\nx=1\nh=0.01\nslope=(main_func(x+h)-main_func(x))/h\nprint(slope)\n```\n\n 2.010000000000023\n\n\nThe derivative of a function f at a point x is defined by the limit.\n\n$$ f'(x)=\\lim_{h\\to 0} {\\frac {f(x+h)-f(x)}{h}} $$\n\nhttp://www.math.unl.edu/~s-bbockel1/833-notes/node23.html\nforward difference approximation:\n$$ f'(x)={\\frac {f(x+h)-f(x)}{h}}+O(h) $$\n\n$$ f'(1)=?$$\n\nNewton's method\nhttps://en.wikipedia.org/wiki/Newton%27s_method\n", "meta": {"hexsha": "86c7c9f5e9f8e6cf62e8a98cda443cd771aac6c9", "size": 45460, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "derivative.ipynb", "max_stars_repo_name": "bonnielin1111/Numerical_Analysis", "max_stars_repo_head_hexsha": "2a8b9193a04f2f206e191f7c1791b18301232752", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-03-16T15:26:47.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-16T15:26:47.000Z", "max_issues_repo_path": "derivative.ipynb", "max_issues_repo_name": "bonnielin1111/Numerical_Analysis", "max_issues_repo_head_hexsha": "2a8b9193a04f2f206e191f7c1791b18301232752", "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": "derivative.ipynb", "max_forks_repo_name": "bonnielin1111/Numerical_Analysis", "max_forks_repo_head_hexsha": "2a8b9193a04f2f206e191f7c1791b18301232752", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-10-29T03:52:02.000Z", "max_forks_repo_forks_event_max_datetime": "2018-12-10T02:43:51.000Z", "avg_line_length": 128.0563380282, "max_line_length": 18924, "alphanum_fraction": 0.8724373075, "converted": true, "num_tokens": 1603, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404077216355, "lm_q2_score": 0.9381240142763573, "lm_q1q2_score": 0.8719303663224749}} {"text": "# Quadratic forms\n\nA *quadratic form* is a polynomial in $n$ variables with all terms of degree two. Therefore, a quadratic form is a mapping $q:\\mathbb{R}^n \\rightarrow \\mathbb{R}$. The term \"form\" is another name for \"homogeneous polynomial\", which is a polynomial whose all nonzero terms have the same degree. \n\nHere are some examples of quadratic forms in one, two and three variables.\n\n
\n\n$$ q(x) = a x^2 $$\n\n
\n\n$$\n\\begin{split}\nq(x,y) &= a x^2 + 2b xy + c y^2 \\\\\n &= x(ax + by) + y(bx + cy) \n\\end{split}\n$$\n\n
\n\n$$\n\\begin{split}\nq(x,y,z) &= a x^2 + d y^2 + f z^2 + 2b xy + 2c xz + 2e yz \\\\\n &= x(ax + by + cz) + y (bx + dy + ez) + z (cx + ey + fz) \n\\end{split}\n$$\n\n
\n\n\nAs the number of variables increases, more and more terms arise in the polynomial. Linear algebra allows to express quadratic forms with a more compact notation which is invariant from the number of variables.\n\nThe examples above can then be expressed as follows.\n\n
\n\n$$ \nq(x) = \n\\begin{bmatrix}\nx\n\\end{bmatrix}\n\\begin{bmatrix}\na\n\\end{bmatrix}\n\\begin{bmatrix}\nx\n\\end{bmatrix}\n= \\boldsymbol{x}^\\intercal A \\boldsymbol{x}\n$$\n\n
\n\n$$ \nq(x,y) = \n\\begin{bmatrix}\nx & y\n\\end{bmatrix}\n\\begin{bmatrix}\na & b \\\\\nb & c\n\\end{bmatrix}\n\\begin{bmatrix}\nx \\\\\ny\n\\end{bmatrix}\n= \\boldsymbol{x}^\\intercal A \\boldsymbol{x}\n$$ \n\n
\n\n$$ \nq(x,y,z) =\n\\begin{bmatrix}\nx & y & z\n\\end{bmatrix}\n\\begin{bmatrix}\na & b & c \\\\\nb & d & e \\\\\nc & e & f\n\\end{bmatrix}\n\\begin{bmatrix}\nx \\\\\ny \\\\\nz\n\\end{bmatrix}\n= \\boldsymbol{x}^\\intercal A \\boldsymbol{x}\n$$ \n\n
\n\nNotice that the matrices $A$s are all symmetric.\n\nLet's verify the correctness of the vectorized expressions above using the *sympy* module.\n\n\n\n```python\nfrom sympy import *\nx, y, z = symbols('x y z')\na, b, c, d, e, f = symbols('a b c d e f')\n```\n\n### q(x,y)\n\n\n```python\nx_2d = Matrix([x, y])\nA_2x2 = Matrix([[a, b], [b, c]])\n\nx_2d.T * A_2x2 * x_2d\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}x \\left(a x + b y\\right) + y \\left(b x + c y\\right)\\end{matrix}\\right]$\n\n\n\n### q(x,y,z)\n\n\n```python\nx_3d = Matrix([x, y, z])\nA_3x3 = Matrix([[a, b, c], [b, d, e], [c, e, f]])\n\nx_3d.T * A_3x3 * x_3d\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}x \\left(a x + b y + c z\\right) + y \\left(b x + d y + e z\\right) + z \\left(c x + e y + f z\\right)\\end{matrix}\\right]$\n\n\n\nIn the general case of an arbitrary number of variables $n$, the quadratic form can still be written using the same compact notation.\n\n
\n\n$$\n\\begin{split}\nq(x_1,\\dots,x_n) &= &\\, x_{1} (a_{11} {x_1} + \\, &\\dots + a_{1n} {x_n}) \\, + \\\\\n& &\\, x_{2} (a_{21} {x_1} + \\, &\\dots + a_{2n} {x_n}) \\, + \\\\ \n& & &\\,\\, \\vdots \\\\\n& &\\, x_{n} (a_{n1} {x_1} + \\, &\\dots + a_{nn} {x_n}) \\\\\n& = &\\, \\boldsymbol{x}^\\intercal A \\boldsymbol{x} &\n\\end{split}\n$$\n\n
\n\nWhere\n\n$$\nA =\n\\begin{split}\n\\begin{bmatrix} \n a_{11} & \\dots & a_{1n} \\\\\n \\vdots & \\ddots & \\vdots \\\\\n a_{n1} & \\dots & a_{nn} \n \\end{bmatrix}\n\\end{split}\n$$\n\n
\n\nand\n\n
\n\n$$\n\\boldsymbol{x} =\n\\begin{split}\n\\begin{bmatrix} \n x_1 \\\\\n \\vdots \\\\\n x_n\n \\end{bmatrix}\n\\end{split}\n$$\n\n
\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "5b281d114b05d4b33c375f4fef3a51b7ced1e399", "size": 6263, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "_notebooks/2021-10-03-Quadratic_Forms.ipynb", "max_stars_repo_name": "lorebucs/zenzo", "max_stars_repo_head_hexsha": "7ac6f1eb6ca9bdded0636e309dfb8ce99e456fa0", "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-10-03-Quadratic_Forms.ipynb", "max_issues_repo_name": "lorebucs/zenzo", "max_issues_repo_head_hexsha": "7ac6f1eb6ca9bdded0636e309dfb8ce99e456fa0", "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-10-03-Quadratic_Forms.ipynb", "max_forks_repo_name": "lorebucs/zenzo", "max_forks_repo_head_hexsha": "7ac6f1eb6ca9bdded0636e309dfb8ce99e456fa0", "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": 23.7234848485, "max_line_length": 310, "alphanum_fraction": 0.4287082868, "converted": true, "num_tokens": 1167, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.963779943094681, "lm_q2_score": 0.9046505280315008, "lm_q1q2_score": 0.871884034426773}} {"text": "# Calculators\n\n**CS1302 Introduction to Computer Programming**\n___\n\n\n```python\nimport math\nfrom math import cos, exp, log, pi, sin, tan\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom ipywidgets import interact\n\n# interactive plot with ipympl\n%matplotlib widget \n```\n\nThe following code is a Python one-liner that creates a calculator.\n\n- Evaluate the cell with `Ctrl+Enter`.\n- Enter `1+1` and see the result.\n\n\n```python\nprint(eval(input()))\n```\n\n---\n\n**Tip**\n\nTry some calculations below using this calculator: \n\n1. $2^3$ by entering `2**3`;\n1. $\\frac23$ by entering `2/3`;\n1. $\\left\\lceil\\frac32\\right\\rceil$ by entering `3//2`;\n1. $3\\mod 2$ by entering `3%2`;\n1. $\\sqrt{2}$ by entering `2**0.5`; and\n1. $\\sin(\\pi/6)$ by entering `sin(pi/6)`;\n\n---\n\nFor this lab, you will create more powerful and dedicated calculators. \nWe will first show you a demo. Then, it will be your turn to create the calculators.\n\n## Hypotenuse Calculator\n\n---\n\n**Proposition** \n\nBy the Pythagoras theorem, given a right-angled triangle,\n\n\n\nthe length of the hypotenuse is\n\n$$\nc = \\sqrt{a^2 + b^2}\n$$ (hypotenuse)\n\nwhere $a$ and $b$ are the lengths of the other sides of the triangle.\n\n---\n\nWe can define the following function to calculate the length `c` of the hypotenuse when given the lengths `a` and `b` of the other sides: \n\n\n```python\ndef length_of_hypotenuse(a, b):\n c = (a**2 + b**2)**(0.5) # Pythagoras\n return c\n```\n\n---\n\n**Important**\n\nYou need not understand how a function is defined, but\n\n- you should know how to *write the formula {eq}`hypotenuse` as a Python expression* using the exponentiation operator `**`, and\n- *assign the variable* `c` the value of the expression (Line 2) using the assignment operator `=`.\n\n---\n\nFor example, you may be asked to write Line 2, while Line 1 and 3 are given to you:\n\n**Exercise** Complete the function below to return the length `c` of the hypotenuse given the lengths `a` and `b`.\n\n\n```python\ndef length_of_hypotenuse(a, b):\n # YOUR CODE HERE\n raise NotImplementedError()\n return c\n```\n\n---\n\n**Caution**\n\n- Complete the above exercise to get the credit even though the answer was already revealed as a demo. Instead of copy-and-paste the answer, type it yourself.\n- Note that indentation affects the execution of Python code. In particular, the assignment statement must be indented to indicate that it is part of the *body* of the function. \n\n---\n\nWe will use `ipywidgets` to let user interact with the calculator more easily:\n\n- After running the cell, move the sliders to change the values of `a` and `b`. \n- Observer that the value of `c` is updated immediately.\n\n\n```python\n# hypotenuse calculator\n@interact(a=(0, 10, 1), b=(0, 10, 1))\ndef calculate_hypotenuse(a=3, b=4):\n print(\"c: {:.2f}\".format(length_of_hypotenuse(a, b)))\n```\n\n---\n\n**Important**\n\nYou need not know how to write widgets, but you should know how to *format a floating point number* (Line 3).\n\n---\n\nYou can check your code with a few cases listed in the test cell below.\n\n\n```python\n# tests\ndef test_length_of_hypotenuse(a, b, c):\n c_ = length_of_hypotenuse(a, b)\n correct = math.isclose(c, c_)\n if not correct:\n print(f\"For a={a} and b={b}, c should be {c}, not {c_}.\")\n assert correct\n\n\ntest_length_of_hypotenuse(3, 4, 5)\ntest_length_of_hypotenuse(0, 0, 0)\ntest_length_of_hypotenuse(4, 7, 8.06225774829855)\n```\n\n## Quadratic equation\n\n### Graphical calculator for parabola\n\n \n\n---\n\n**Definition** Parabola\n\n\nThe collection of points $(x,y)$ satisfying the following equation forms a *parabola*:\n\n$$\ny=ax^2+bx+c\n$$ (parabola)\n\nwhere $a$, $b$, and $c$ are real numbers called the *coefficients*.\n\n---\n\n**Exercise** Given the variables `x`, `a`, `b`, and `c` store the $x$-coordinate and the coefficients $a$, $b$, and $c$ respectively, assign `y` the corresponding $y$-coordinate of the parabola {eq}`parabola`.\n\n\n```python\ndef get_y(x, a, b, c):\n # YOUR CODE HERE\n raise NotImplementedError()\n return y\n```\n\nTo test your code:\n\n\n```python\n# tests\ndef test_get_y(y, x, a, b, c):\n y_ = get_y(x, a, b, c)\n correct = math.isclose(y, y_)\n if not correct:\n print(f\"With (x, a, b, c)={x,a,b,c}, y should be {y} not {y_}.\")\n assert correct\n\n\ntest_get_y(0, 0, 0, 0, 0)\ntest_get_y(1, 0, 1, 2, 1)\ntest_get_y(2, 0, 2, 1, 2)\n```\n\n\n```python\n# hidden tests\n```\n\nTo run the graphical calculator:\n\n\n```python\n# graphical calculator for parabola\nfig, ax = plt.subplots()\nxmin, xmax, ymin, ymax, resolution = -10, 10, -10, 10, 50\nx = np.linspace(xmin, xmax, resolution)\nax.set_title(r'$y=ax^2+bx+c$')\nax.set_xlabel(r'$x$')\nax.set_ylabel(r'$y$')\nax.set_xlim([xmin, xmax])\nax.set_ylim([ymin, ymax])\nax.grid()\np, = ax.plot(x, get_y(x, 0, 0, 0))\n\n@interact(a=(-10, 10, 1), b=(-10, 10, 1), c=(-10, 10, 1))\ndef plot_parabola(a, b, c):\n p.set_ydata(get_y(x, a, b, c))\n```\n\n### Quadratic equation solver\n\n \n\n---\n\n**Proposition**\n\nFor the quadratic equation\n\n$$\nax^2+bx+c=0,\n$$ (quadratic)\nthe *roots* (solutions for $x$) are give by\n\n$$\n\\frac{-b-\\sqrt{b^2-4ac}}{2a},\\frac{-b+\\sqrt{b^2-4ac}}{2a}.\n$$ (quadratic_roots)\n\n---\n\n**Exercise** Assign to `root1` and `root2` the values of the first and second roots above respectively.\n\n\n```python\ndef get_roots(a, b, c):\n # YOUR CODE HERE\n raise NotImplementedError()\n return root1, root2\n```\n\nTo test your code:\n\n\n```python\n# tests\ndef test_get_roots(roots, a, b, c):\n def mysort(c):\n return c.real, c.imag\n roots_ = get_roots(a, b, c)\n assert np.isclose(sorted(roots, key=mysort), \n sorted(roots_, key=mysort)).all()\n\ntest_get_roots((-1.0, 0.0), 1, 1, 0)\ntest_get_roots((-1.0, -1.0), 1, 2, 1)\ntest_get_roots((-2.0, -1.0), 1, 3, 2)\ntest_get_roots([(-0.5-0.5j), (-0.5+0.5j)], 2, 2, 1)\n```\n\n\n```python\n# hidden tests\n```\n\nTo run the calculator:\n\n\n```python\n# quadratic equations solver\n@interact(a=(-10,10,1),b=(-10,10,1),c=(-10,10,1))\ndef quadratic_equation_solver(a=1,b=2,c=1):\n print('Roots: {}, {}'.format(*get_roots(a,b,c)))\n```\n\n## Number conversion\n\n### Byte-to-Decimal calculator\n\n\n\nDenote a binary number stored in a byte ($8$ bits) as\n\n$$ \nb_7\\circ b_6\\circ b_5\\circ b_4\\circ b_3\\circ b_2\\circ b_1\\circ b_0, \n$$\nwhere $\\circ$ concatenates $b_i$'s together into a binary string.\n\nThe binary string can be converted to a decimal number by the formula\n\n$$ \nb_7\\cdot 2^7 + b_6\\cdot 2^6 + b_5\\cdot 2^5 + b_4\\cdot 2^4 + b_3\\cdot 2^3 + b_2\\cdot 2^2 + b_1\\cdot 2^1 + b_0\\cdot 2^0. \n$$\n\nE.g., the binary string `'11111111'` is the largest integer represented by a byte:\n\n$$\n2^7+2^6+2^5+2^4+2^3+2^2+2^1+2^0=255=2^8-1.\n$$\n\n**Exercise** Assign to `decimal` the *integer* value represented by the binary sequence `b7,b6,b5,b4,b3,b2,b1,b0` of *characters* `'0'` or `'1'`.\n\n\n```python\ndef byte_to_decimal(b7, b6, b5, b4, b3, b2, b1, b0):\n \"\"\"\n Parameters:\n -----------\n b7, ..., b0 are single characters either '0' or '1'.\n \"\"\"\n # YOUR CODE HERE\n raise NotImplementedError()\n return decimal\n```\n\nTo test your code:\n\n\n```python\n# tests\ndef test_byte_to_decimal(decimal, b7, b6, b5, b4, b3, b2, b1, b0):\n decimal_ = byte_to_decimal(b7, b6, b5, b4, b3, b2, b1, b0)\n assert decimal == decimal_ and isinstance(decimal_, int)\n\n\ntest_byte_to_decimal(38, '0', '0', '1', '0', '0', '1', '1', '0')\ntest_byte_to_decimal(20, '0', '0', '0', '1', '0', '1', '0', '0')\ntest_byte_to_decimal(22, '0', '0', '0', '1', '0', '1', '1', '0')\n```\n\n\n```python\n# hidden tests\n```\n\nTo run the calculator:\n\n\n```python\n# byte-to-decimal calculator\nbit = ['0', '1']\n\n\n@interact(b7=bit, b6=bit, b5=bit, b4=bit, b3=bit, b2=bit, b1=bit, b0=bit)\ndef convert_byte_to_decimal(b7, b6, b5, b4, b3, b2, b1, b0):\n print('decimal:', byte_to_decimal(b7, b6, b5, b4, b3, b2, b1, b0))\n```\n\n### Decimal-to-Byte calculator\n\n\n\n**Exercise** Assign to `byte` a *string of 8 bits* that represents the value of `decimal`, a non-negative decimal integer from $0$ to $2^8-1=255$. \n*Hint: Use `//` and `%`.*\n\n\n```python\ndef decimal_to_byte(decimal):\n # YOUR CODE HERE\n raise NotImplementedError()\n return byte\n```\n\nTo test your code:\n\n\n```python\n# tests\ndef test_decimal_to_byte(byte,decimal):\n byte_ = decimal_to_byte(decimal)\n assert byte == byte_ and isinstance(byte, str) and len(byte) == 8\n\n\ntest_decimal_to_byte('01100111', 103)\ntest_decimal_to_byte('00000011', 3)\ntest_decimal_to_byte('00011100', 28)\n```\n\n\n```python\n# hidden tests\n```\n\nTo run the calculator:\n\n\n```python\n# decimal-to-byte calculator\n@interact(decimal=(0,255,1))\ndef convert_decimal_to_byte(decimal=0):\n print('byte:', decimal_to_byte(decimal))\n```\n\n## Symbolic calculator (optional)\n\nCan we do complicated arithmetics with Python. What about Calculus? \n\n$$\n\\int \\tan(x)\\, dx = \\color{red}{?}\n$$\n\nSolution: \n\n---\n\n**Tip**\n\n- Take a look at the different panels to learn about the solution: `Steps`, `Plot`, and `Derivative`.\n- Try different [random examples](https://gamma.sympy.org/).\n\n---\n\n**How does SymPy Gamma work?**\n\n[SymPy Gamma](https://gamma.sympy.org/) is a web application running [SymPy](https://docs.sympy.org/latest/index.html), which is a python library for symbolic computation.\n\n**How to use SymPy?**\n\nTo import the library:\n\n\n```python\nimport sympy as sp\n```\n\nWe need to define a symbolic variable and assign it to a python variable.\n\n\n```python\nx = sp.symbols('x')\nx\n```\n\nThe SymPy expression for $\\tan(x)$ is:\n\n\n```python\nf = sp.tan(x)\nf\n```\n\nTo compute the integration:\n\n\n```python\nint_f = sp.integrate(f)\nint_f\n```\n\nTo compute the derivative:\n\n\n```python\ndiff_int_f = sp.diff(int_f)\ndiff_int_f\n```\n\nThe answer can be simplified as expected:\n\n\n```python\ndiff_int_f.simplify()\n```\n\nTo plot:\n\n\n```python\np = sp.plot(f, int_f, (x, -sp.pi/4, sp.pi/4))\n```\n\n**Exercise**\n\nTry to compute the following in SymPy and in jupyter notebook:\n\n- $\\frac{d}{dx} x^x$\n- $\\frac{d}{dx} \\frac{1}{\\sqrt{1 - x^2}}$.\n\n---\n\n**Hint**\n\nUse `sp.sqrt` or `**(sp.S(1)/2)` for square root instead of `**0.5`. See [SymPy gotchas](https://docs.sympy.org/latest/gotchas.html).\n\n---\n", "meta": {"hexsha": "99335bb2abdebb154ac954aec75a54d506a9d380", "size": 32432, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Lab2/Calculators.ipynb", "max_stars_repo_name": "ccha23/CS1302", "max_stars_repo_head_hexsha": "b5d55a9844c3e6b80ec9029509b5d572b24b6be3", "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": "Lab2/Calculators.ipynb", "max_issues_repo_name": "ccha23/CS1302", "max_issues_repo_head_hexsha": "b5d55a9844c3e6b80ec9029509b5d572b24b6be3", "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": "Lab2/Calculators.ipynb", "max_forks_repo_name": "ccha23/CS1302", "max_forks_repo_head_hexsha": "b5d55a9844c3e6b80ec9029509b5d572b24b6be3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2021-01-22T06:54:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-20T06:05:01.000Z", "avg_line_length": 21.4497354497, "max_line_length": 215, "alphanum_fraction": 0.5076159349, "converted": true, "num_tokens": 3260, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088005554475, "lm_q2_score": 0.939024823827629, "lm_q1q2_score": 0.8717989103815994}} {"text": "Problem: Monte Carlo Estimate of $\\int_0^1 \\frac{1}{1+x} \\mathrm{d}x$\n\n\\begin{equation}\n\\begin{split}\n\\int_0^1 \\frac{1}{1+x} \\mathrm{d}x & = \\ln(x+1)+C |_0^1 \\\\\n & = \\ln(2) - \\ln(1) \\\\\n & = 0.693147 \\\\\n\\end{split}\n\\end{equation}\n\nSource: https://en.wikipedia.org/wiki/Antithetic_variates\n\n\n```python\n# Calculate the truth\nimport math\ntruth = math.log(2)-math.log(1)\n```\n\n\n```python\n# Classical Estimate\nimport numpy as np\nfrom sklearn.metrics import mean_squared_error\n\ndef f(x): return 1.0/(1+x)\ndef sampling(n): return np.random.uniform(0,1,n)\n\nn = 1500\nrand = sampling(2*n)\nsamples = map(f, rand)\n\nprint \"==== Classical Estimate ====\"\nprint \"Estimate: \", np.mean(samples)\nprint \"Variance: \", np.var(samples)\n```\n\n ==== Classical Estimate ====\n Estimate: 0.6935116995264258\n Variance: 0.019320749240938653\n\n\n\n```python\n# Antithetic Variates\nimport numpy as np\nfrom sklearn.metrics import mean_squared_error\n\ndef f(x): return 1.0/(1+x)\ndef sampling(n): return np.random.uniform(0,1,n)\n\nn = 1500\nrand = sampling(n)\nrand_anti = 1-rand\nsamples = np.add(map(f, rand), map(f, rand_anti))/2.0\n\nprint \"==== Antithetic Variates ====\"\nprint \"Estimate: \", np.mean(samples)\nprint \"Variance: \", np.var(samples)\n```\n\n ==== Antithetic Variates ====\n Estimate: 0.6925277753075945\n Variance: 0.0005805944133518291\n\n", "meta": {"hexsha": "4e9e371b4cfb98fc4ed8103523b81adce975cef1", "size": 2761, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "011519_antithetic_variates.ipynb", "max_stars_repo_name": "kinsumliu/notes", "max_stars_repo_head_hexsha": "3601c50a11966bed84c5d792778f3b103ba801d2", "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": "011519_antithetic_variates.ipynb", "max_issues_repo_name": "kinsumliu/notes", "max_issues_repo_head_hexsha": "3601c50a11966bed84c5d792778f3b103ba801d2", "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": "011519_antithetic_variates.ipynb", "max_forks_repo_name": "kinsumliu/notes", "max_forks_repo_head_hexsha": "3601c50a11966bed84c5d792778f3b103ba801d2", "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.2016806723, "max_line_length": 81, "alphanum_fraction": 0.5052517204, "converted": true, "num_tokens": 437, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191322715435, "lm_q2_score": 0.9124361616674908, "lm_q1q2_score": 0.8716677222173651}} {"text": "# Lagrange interpolating polynomials\nGiven equation:\n\\begin{align}\nf(x) = \\frac{1}{1 + 25x^2}\n\\end{align}\n\n\n```python\n# dependency import\nfrom matplotlib import pyplot as plt\nimport numpy as np\n%matplotlib notebook\n```\n\n\n```python\n# functions\ndef f(x):\n return 1/(1 + 25*(x**2))\n\ndef lagrange(x, x_given, i):\n res = 1\n for x_j in x_given[:i] + x_given[i + 1:]:\n res *= (x - x_j) / (x_given[i] - x_j)\n return res\n\ndef poly_interpolate(x, x_given, y_given, n, i=0):\n if i + 1 in [len(x_given), n]: return lagrange(x, x_given, i) * y_given[i]\n return lagrange(x, x_given, i) * y_given[i] + poly_interpolate(x, x_given, y_given, n, i + 1)\n```\n\n\n```python\nx_given = [-1, -0.75, -0.5, -0.25, 0, 0.25, 0.5, 0.75, 1]\ny_given = [f(x) for x in x_given]\n```\n\n\n```python\nplt.plot(np.linspace(-1, 1, num=100), [f(x) for x in np.linspace(-1, 1, num=100)], '--', label='Actual f(x)')\nplt.plot(x_given, y_given, 'x', color='red', label='Known f(x)')\nplt.xlabel('x')\nplt.ylabel('f(x)')\nplt.legend()\nplt.grid()\nplt.show()\n```\n\n\n \n\n\n\n\n\n\n## Lagrange Interpolating polynomial\n\n\n```python\nplt.subplots_adjust(hspace=1)\nfor i in range(1, 9):\n ax = plt.subplot(420 + i)\n ax.plot(np.linspace(-1, 1, num=100), [f(x) for x in np.linspace(-1, 1, num=100)], '--')\n ax.plot(np.linspace(-1, 1, num=100), [poly_interpolate(x, x_given, y_given, i) for x in np.linspace(-1, 1, num=100)])\n ax.plot(x_given, y_given, 'x', color='red', label='Known f(x)')\n plt.title('Polynomial degree is: ' + str(i))\n ax.grid()\nplt.show()\n```\n\n\n \n\n\n\n\n\n", "meta": {"hexsha": "b9d27e6fd4522851814b230360edbf4cb364390c", "size": 228789, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "lagrange_poly.ipynb", "max_stars_repo_name": "BatyaGG/numerical_methods", "max_stars_repo_head_hexsha": "40036c07ed4db2fb03fe0d188feeb440aa260ce2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-06-23T12:19:55.000Z", "max_stars_repo_stars_event_max_datetime": "2018-06-23T12:19:55.000Z", "max_issues_repo_path": "lagrange_poly.ipynb", "max_issues_repo_name": "BatyaGG/numerical_methods", "max_issues_repo_head_hexsha": "40036c07ed4db2fb03fe0d188feeb440aa260ce2", "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": "lagrange_poly.ipynb", "max_forks_repo_name": "BatyaGG/numerical_methods", "max_forks_repo_head_hexsha": "40036c07ed4db2fb03fe0d188feeb440aa260ce2", "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": 134.1870967742, "max_line_length": 101019, "alphanum_fraction": 0.8098378856, "converted": true, "num_tokens": 561, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566342012360932, "lm_q2_score": 0.9111797118207757, "lm_q1q2_score": 0.8716656758002014}} {"text": "## Deriving the transfer function of the Simper SVF filter structure\n\nHTML output built with: jupyter nbconvert --to html svf_z_domain_tf.ipynb\n\nSource:\nhttps://cytomic.com/files/dsp/SvfLinearTrapOptimised2.pdf\n\nWe will follow the second form of the algorithm, found on page 6.\n\nSympy can't (very easily) be bent to display transfer functions in terms of $z^{-1}, z^{-2}, ...$ which is the convention. Plain $z$ will be used here instead - keep in mind it actually means $z^{-1}$.\n\n\n```python\nfrom sympy import *\ninit_printing()\n\nz = symbols(\"z\")\n```\n\nStart with the parameters.\n\n```\ng = Tan[π * cutoff / samplerate];\nk = 1/Q = 2 - 2*res;\na1 = 1/(1 + g*(g + k));\na2 = g*a1;\n```\n\nThe other coefficients defining the shape of the filter (`m0, m1, m2`) will be ignored for now, as they are only used to \"mix\" the output.\n\n\n```python\ng, k = symbols(\"g k\")\na1 = 1/(1 + g*(g + k))\na2 = g*a1\n\n(a1, a2)\n```\n\nThen the computation.\n\nThe variable `v0` represents the input signal - we will consider it to represent the z-transform of the input over time. `v1` and `v2` represent two other nodes in the block diagram.\n\nThe state variables `ic1eq` and `ic2eq` will be defined as unknowns first, and then we will solve them using their equations.\n\nThe relevant lines of the algorithm are:\n\n```\nv1 = a1 * ic1eq + a2 * (v0 - ic2eq);\nv2 = ic2eq + g * v1;\n```\n\nNotice that the `ic1eq` and `ic2eq` actually refer to the _previous_ values of these samples. This corresponds to multiplying by $z$ (contrary to convetion!) in the z-domain.\n\n\n```python\nv0, ic1eq, ic2eq = symbols(\"v0 ic_1 ic_2\")\n\nv1 = a1 * ic1eq * z + a2 * (v0 - ic2eq * z)\nv2 = ic2eq * z + g * v1\n\n(v1, v2)\n```\n\nThe \"new\" values for `ic1eq, ic2eq` are computed as follows:\n\n```\nic1eq = 2*v1 - ic1eq;\nic2eq = 2*v2 - ic2eq;\n```\n\ndepending on the current values of `v1, v2`, and the previous values of `ic1eq, ic2eq`.\n\nConsider this as a system of equations, and solve it:\n\n\n```python\nequations = [\n 2*v1 - ic1eq * z - ic1eq, # = 0\n 2*v2 - ic2eq * z - ic2eq, # = 0\n]\nsolution = solve(equations, (ic1eq, ic2eq))\n\nsolution\n```\n\nWe may now subsitute the solution into `v1` and `v2` to obtain the transfer functions\n\n$$\n\\begin{aligned}\nH_0(z) &= \\frac {v_0(z)} {v_0(z)} = 1 \\\\\nH_1(z) &= \\frac {v_1(z)} {v_0(z)} \\\\\nH_2(z) &= \\frac {v_2(z)} {v_0(z)}\n\\end{aligned}\n$$\n\n\n```python\nH0 = 1\nH1 = v1.subs(solution) / v0\nH2 = v2.subs(solution) / v0\n\nH1 = collect(simplify(H1), z)\nH2 = collect(simplify(H2), z)\n\n(H1, H2)\n```\n\nHow convenient, the denominators seem to be the same! That is to be expected of course,\nsince taking linear combinations of $H_1, H_2$ cannot result in anything that has more than two poles, because the order of the system is 2.\n\n\n```python\n(H1_num, H1_denom) = fraction(H1)\n(H2_num, H2_denom) = fraction(H2)\n\nassert H1_denom == H2_denom\ndenom = H1_denom\ndenom\n```\n\nWe can now assemble the complete transfer function, taking into account the mix coefficients `m0, m1, m2`.\n\n$$\nH(z) = m_0 H_0(z) + m_1 H_1(z) + m_2 H_2(z)\n$$\n\n\n```python\nm0, m1, m2 = symbols(\"m0 m1 m2\")\n\nH = m0 * H0 + (m1 * H1_num + m2 * H2_num) / denom\n\nprint(H)\nH\n```\n\n## Sanity check: High pass filter\n\n\n```python\nfrom sympy.functions import tan, exp\n\nsamplerate = 40_000\ncutoff = sqrt(samplerate/2)\nQ = 0.9\n\nf = symbols(\"f\")\n\nH_hp_f = H.subs({\n g: tan(pi * cutoff / samplerate),\n k: 1/Q,\n m0: 1,\n m1: -1/Q, # = -k\n m2: -1,\n z: exp(2*I*pi * f / samplerate)**-1,\n})\n\nplot(abs(H_hp_f), (f, 1, samplerate/2), xscale='log', yscale='log')\n```\n", "meta": {"hexsha": "c0bcadbf010656d4d245dcb9735677bb5a176b06", "size": 68241, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "svf_z_domain_tf.ipynb", "max_stars_repo_name": "ollpu/dsp-math-notes", "max_stars_repo_head_hexsha": "0b09a18cba6478699f32b18407dfc435fe576241", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-07-26T21:47:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-26T21:47:41.000Z", "max_issues_repo_path": "svf_z_domain_tf.ipynb", "max_issues_repo_name": "ollpu/dsp-math-notes", "max_issues_repo_head_hexsha": "0b09a18cba6478699f32b18407dfc435fe576241", "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": "svf_z_domain_tf.ipynb", "max_forks_repo_name": "ollpu/dsp-math-notes", "max_forks_repo_head_hexsha": "0b09a18cba6478699f32b18407dfc435fe576241", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-05-05T00:54:16.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-05T00:54:16.000Z", "avg_line_length": 166.4414634146, "max_line_length": 14220, "alphanum_fraction": 0.8717340016, "converted": true, "num_tokens": 1229, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566342012360931, "lm_q2_score": 0.9111797118207757, "lm_q1q2_score": 0.8716656758002013}} {"text": "# Contravariant & Covariant indices in Tensors (Symbolic)\n\n\n```python\nfrom einsteinpy.symbolic import ChristoffelSymbols, RiemannCurvatureTensor\nfrom einsteinpy.symbolic.predefined import Schwarzschild\nimport sympy\nsympy.init_printing()\n```\n\n### Analysing the schwarzschild metric along with performing various operations\n\n\n```python\nsch = Schwarzschild()\nsch.tensor()\n```\n\n\n```python\nsch_inv = sch.inv()\nsch_inv.tensor()\n```\n\n\n```python\nsch.order\n```\n\n\n```python\nsch.config\n```\n\n\n\n\n 'll'\n\n\n\n### Obtaining Christoffel Symbols from Metric Tensor\n\n\n```python\nchr = ChristoffelSymbols.from_metric(sch_inv) # can be initialized from sch also\nchr.tensor()\n```\n\n\n```python\nchr.config\n```\n\n\n\n\n 'ull'\n\n\n\n### Changing the first index to covariant\n\n\n```python\nnew_chr = chr.change_config('lll') # changing the configuration to (covariant, covariant, covariant)\nnew_chr.tensor()\n```\n\n\n```python\nnew_chr.config\n```\n\n\n\n\n 'lll'\n\n\n\n### Any arbitary index configuration would also work!\n\n\n```python\nnew_chr2 = new_chr.change_config('lul')\nnew_chr2.tensor()\n```\n\n### Obtaining Riemann Tensor from Christoffel Symbols and manipulating it's indices\n\n\n```python\nrm = RiemannCurvatureTensor.from_christoffels(new_chr2)\nrm[0,0,:,:]\n```\n\n\n```python\nrm.config\n```\n\n\n\n\n 'ulll'\n\n\n\n\n```python\nrm2 = rm.change_config(\"uuuu\")\nrm2[0,0,:,:]\n```\n\n\n```python\nrm3 = rm2.change_config(\"lulu\")\nrm3[0,0,:,:]\n```\n\n\n```python\nrm4 = rm3.change_config(\"ulll\")\nrm4.simplify()\nrm4[0,0,:,:]\n```\n\n#### It is seen that `rm` and `rm4` are same as they have the same configuration\n", "meta": {"hexsha": "da3149b2aad7c4c060fb0be3d6a3d8fce54e2d32", "size": 151373, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "docs/source/examples/Playing with Contravariant and Covariant Indices in Tensors(Symbolic).ipynb", "max_stars_repo_name": "bibek22/einsteinpy", "max_stars_repo_head_hexsha": "78bf5d942cbb12393852f8e4d7a8426f1ffe6f23", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-06-01T18:37:53.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-01T18:37:53.000Z", "max_issues_repo_path": "docs/source/examples/Playing with Contravariant and Covariant Indices in Tensors(Symbolic).ipynb", "max_issues_repo_name": "bibek22/einsteinpy", "max_issues_repo_head_hexsha": "78bf5d942cbb12393852f8e4d7a8426f1ffe6f23", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2019-04-08T17:39:50.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-11T03:10:09.000Z", "max_forks_repo_path": "docs/source/examples/Playing with Contravariant and Covariant Indices in Tensors(Symbolic).ipynb", "max_forks_repo_name": "bibek22/einsteinpy", "max_forks_repo_head_hexsha": "78bf5d942cbb12393852f8e4d7a8426f1ffe6f23", "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": 235.7834890966, "max_line_length": 27584, "alphanum_fraction": 0.8229208644, "converted": true, "num_tokens": 426, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9621075690244281, "lm_q2_score": 0.9059898191142621, "lm_q1q2_score": 0.871659662428904}} {"text": "**Rational numbers**\n\n\n```python\n# source: https://scipy-lectures.org/packages/sympy.html\n\nimport sympy as sym\nfrom sympy import pprint\nprint(\"SymPy defines three numerical types: Real, Rational and Integer.\")\na=sym.Rational(1,2)\nb=sym.Rational(1,3)\nprint(\"a:\",a)\nprint(\"b:\",b)\nprint(\"Rational arithmetic can be performed\")\nprint(\"a+b:\",a+b)\nprint(\"2a:\",2*a)\n```\n\n SymPy defines three numerical types: Real, Rational and Integer.\n a: 1/2\n b: 1/3\n Rational arithmetic can be performed\n a+b: 5/6\n 2a: 1\n\n\n\n```python\nprint(\"special constants, like e, pi, oo (Infinity), are treated as symbols and can be evaluated with arbitrary precision\")\npprint(2*sym.pi)\npprint(sym.pi**2)\npprint(sym.exp(1))\nprint(\"\\nEvaluating the value using evalf function\")\nprint(\"2pi:\",(2*sym.pi).evalf())\nprint(\"pi^2:\",(sym.pi**2).evalf())\nprint(\"e^1:\",(sym.exp(1)).evalf())\nprint(\"Infinity + 1:\",sym.oo+1)\nprint(\"\\nOne can adjust the precision required using the evalf\")\nprint(\"2pi:\",(2*sym.pi).evalf(3))\nprint(\"100 decimal precision of Square root of 2\")\nprint((sym.sqrt(2)).evalf(100))\n```\n\n special constants, like e, pi, oo (Infinity), are treated as symbols and can be evaluated with arbitrary precision\n 2⋅π\n 2\n π \n ℯ\n \n Evaluating the value using evalf function\n 2pi: 6.28318530717959\n pi^2: 9.86960440108936\n e^1: 2.71828182845905\n Infinity + 1: oo\n \n One can adjust the precision required using the evalf\n 2pi: 6.28\n 100 decimal precision of Square root of 2\n 1.414213562373095048801688724209698078569671875376948073176679737990732478462107038850387534327641573\n\n\n**Expand and simplify**\n\n\n```python\nx=sym.Symbol('x')\ny=sym.Symbol('y')\nprint(x+y+x-y)\nprint((x+y)*(x-y))\nprint(sym.expand((x+y)**4))\nprint(\"Adding additional arguments to expand command\")\npprint(sym.expand(x+y,complex=True))\nprint(sym.expand(sym.cos(x+y),trig=True))\npprint(sym.expand((x+y)*(x-y)))\nprint(sym.expand((x+y)**6))\n\nprint(\"Using simplify command\")\nprint(sym.simplify((x + x * y) / x))\nprint(sym.simplify(sym.sin(x)/sym.cos(x),trig=True))\n```\n\n 2*x\n (x - y)*(x + y)\n x**4 + 4*x**3*y + 6*x**2*y**2 + 4*x*y**3 + y**4\n Adding additional arguments to expand command\n re(x) + re(y) + ⅈ⋅im(x) + ⅈ⋅im(y)\n -sin(x)*sin(y) + cos(x)*cos(y)\n 2 2\n x - y \n x**6 + 6*x**5*y + 15*x**4*y**2 + 20*x**3*y**3 + 15*x**2*y**4 + 6*x*y**5 + y**6\n Using simplify command\n y + 1\n tan(x)\n\n\n**Calculus and pretty printing**\n\n\n```python\nprint(\"syntax for limits limit(function, variable, point)\")\nprint(sym.limit(sym.sin(x)/x,x,0))\nprint(sym.limit(1/x,x,sym.oo))\nprint(\"\\nsyntax for differentiation diff(function, variable, order)\")\nprint(sym.diff(sym.log(x),x))\npprint(sym.diff(sym.tan(x),x))\nprint(\"\\ncheck\")\npprint(sym.limit((sym.tan(x+y)-sym.tan(x))/y,y,0))\nprint(\"\\nCalculating higher derivatives using diff command\")\npprint(sym.diff(x**9,x,6))\nprint(\"\\ncheck\")\nfor i in range(1,10):\n pprint(sym.diff(x**9,x,i))\n```\n\n syntax for limits limit(function, variable, point)\n 1\n 0\n \n syntax for differentiation diff(function, variable, order)\n 1/x\n 2 \n tan (x) + 1\n \n check\n 2 \n tan (x) + 1\n \n Calculating higher derivatives using diff command\n 3\n 60480⋅x \n \n check\n 8\n 9⋅x \n 7\n 72⋅x \n 6\n 504⋅x \n 5\n 3024⋅x \n 4\n 15120⋅x \n 3\n 60480⋅x \n 2\n 181440⋅x \n 362880⋅x\n 362880\n\n\n**Taylor Series expansion**\n\n\n```python\nprint(\"Syntax series(expression, variable)\")\npprint(sym.series(sym.cos(x),x))\npprint(sym.series((1/sym.cos(x)),x))\n```\n\n Syntax series(expression, variable)\n 2 4 \n x x ⎛ 6⎞\n 1 - ── + ── + O⎝x ⎠\n 2 24 \n 2 4 \n x 5⋅x ⎛ 6⎞\n 1 + ── + ──── + O⎝x ⎠\n 2 24 \n\n\n**Integration**\n\n\n```python\nprint(\"syntax: integrate(function,(variable,lowlimit,highlimit))\")\npprint(sym.integrate(6*x**5+y,x))\npprint(sym.integrate(sym.log(x),x))\n\nprint(\"\\nDefinite integrals\")\nprint(sym.integrate(x**3,(x,-1,1)))\nprint(sym.integrate(sym.sin(x),(x,0,sym.pi/2)))\nprint(sym.integrate((sym.cos(x)),(x,-sym.pi/2,sym.pi/2)))\nprint(sym.integrate(sym.exp(-x),(x,0,sym.oo)))\nprint(\"integrating the following function from from -infinity to infinity\")\npprint(sym.exp(-x ** 2))\nprint(\"gives\")\npprint(sym.integrate(sym.exp(-x**2),(x,-sym.oo,sym.oo)))\n```\n\n syntax: integrate(function,(variable,lowlimit,highlimit))\n 6 \n x + x⋅y\n x⋅log(x) - x\n \n Definite integrals\n 0\n 1\n 2\n 1\n integrating the following function from from -infinity to infinity\n 2\n -x \n ℯ \n gives\n √π\n\n\n**Solving equations**\n\n\n```python\nprint(\"for solving algebraic equations use solveset(function,variable), for solving SLE use solve((eq1,eq2),(var1,var2))\")\npprint(sym.solveset(x**4-1,x))\npprint(sym.solveset(sym.exp(x)+1,x))\n\nsol=sym.solve((x + 5 * y - 2, -3 * x + 6 * y - 15),(x,y))\nprint(sol)\nprint(sol[x])\nprint(sym.solve((x+y-2,2*x+y),(x,y)))\n\nprint(\"\\nfactorization of a polynomial\")\nf=x**4-3*x**2+1\npprint(f)\npprint(sym.factor(f))\n\nprint(\"\\nSolving boolean expressions\")\npprint(sym.satisfiable((~x|y)&(~y|x)))\n```\n\n for solving algebraic equations use solveset(function,variable), for solving SLE use solve((eq1,eq2),(var1,var2))\n {-1, 1, -ⅈ, ⅈ}\n {ⅈ⋅(2⋅n⋅π + π) | n ∊ ℤ}\n {x: -3, y: 1}\n -3\n {x: -2, y: 4}\n \n factorization of a polynomial\n 4 2 \n x - 3⋅x + 1\n ⎛ 2 ⎞ ⎛ 2 ⎞\n ⎝x - x - 1⎠⋅⎝x + x - 1⎠\n \n Solving boolean expressions\n {x: False, y: False}\n\n\n**Finding the value of a function at various points**\n\n\n```python\ndef f(x):\n return sym.exp(x)**4-3*x**2+1\nfor i in range(1,4):\n pprint(f(i))\n print(f(i).evalf())\n```\n\n 4\n -2 + ℯ \n 52.5981500331442\n 8\n -11 + ℯ \n 2969.95798704173\n 12\n -26 + ℯ \n 162728.791419004\n\n\n**Linear algebra**\n\n\n```python\nA=sym.Matrix([[1,2,3],[3,4,5]])\npprint(A)\nprint(\"unlike a NumPy array, you can also put Symbols in it\")\nx,y=sym.symbols('x,y')\nA=sym.Matrix([[1,x],[y,1]])\npprint(A)\n```\n\n ⎡1 2 3⎤\n ⎢ ⎥\n ⎣3 4 5⎦\n unlike a NumPy array, you can also put Symbols in it\n ⎡1 x⎤\n ⎢ ⎥\n ⎣y 1⎦\n\n\n**Differential equations**\n\n\n```python\nf, g = sym.symbols('f g', cls=sym.Function) #create an undefined function by passing cls=Function \n# f(x), will represent an unknown function\npprint(f(x).diff(x)+f(x))\npprint(f(x).diff(x,x)+f(x))\nprint(\"solving differential equations\")\npprint(sym.dsolve(f(x).diff(x,x)+f(x),f(x)))\n# pprint(sym.dsolve(sym.sin(x) * sym.cos(f(x)) + sym.cos(x) * sym.sin(f(x)) * f(x).diff(x), f(x), hint='separable')) #solve as seperable equation\npprint((f(x).diff(x)*x+f(x)-f(x)**2))\npprint(sym.dsolve(f(x).diff(x)*x+f(x)-f(x)**2,f(x)))\n```\n\n d \n f(x) + ──(f(x))\n dx \n 2 \n d \n f(x) + ───(f(x))\n 2 \n dx \n solving differential equations\n f(x) = C₁⋅sin(x) + C₂⋅cos(x)\n d 2 \n x⋅──(f(x)) - f (x) + f(x)\n dx \n -C₁ \n f(x) = ───────\n -C₁ + x\n\n", "meta": {"hexsha": "9d28c43aa4e28dac690e03039ce754332f22fe4c", "size": 12251, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "basics_of_sympy.ipynb", "max_stars_repo_name": "rsatwik/Python_Practice", "max_stars_repo_head_hexsha": "3ab027be3cabac96a41e8e616296fb2497916f7b", "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": "basics_of_sympy.ipynb", "max_issues_repo_name": "rsatwik/Python_Practice", "max_issues_repo_head_hexsha": "3ab027be3cabac96a41e8e616296fb2497916f7b", "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": "basics_of_sympy.ipynb", "max_forks_repo_name": "rsatwik/Python_Practice", "max_forks_repo_head_hexsha": "3ab027be3cabac96a41e8e616296fb2497916f7b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-01-09T17:00:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-09T17:00:13.000Z", "avg_line_length": 25.364389234, "max_line_length": 154, "alphanum_fraction": 0.4633907436, "converted": true, "num_tokens": 2565, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9539660989095222, "lm_q2_score": 0.9136765263519308, "lm_q1q2_score": 0.8716164315091547}} {"text": "# Python - Symbolic Mathematics (`sympy`)\n\n\n```python\nimport sympy as sp\nimport numpy as np\nimport matplotlib.pyplot as plt\n```\n\n\n```python\nsp.init_printing()\n```\n\n### `sympy` treats stuff fundementally different than `numpy`\n\n\n```python\nnp.sqrt(8)\n```\n\n\n```python\ntype(np.sqrt(8))\n```\n\n\n```python\nsp.sqrt(8)\n```\n\n\n```python\ntype(sp.sqrt(8))\n```\n\n\n```python\nnp.sqrt(8) == sp.sqrt(8)\n```\n\n\n```python\nnp.pi\n```\n\n\n```python\nnp.pi + 4\n```\n\n\n```python\nsp.pi\n```\n\n\n```python\nsp.pi + 4\n```\n\n#### You can use `np.float64()` to turn a `sympy` float to a `numpy` float\n\n\n```python\nmy_sympy_to_numpy_pi = np.float64(sp.pi)\n```\n\n\n```python\ntype(my_sympy_to_numpy_pi)\n```\n\n\n```python\nmy_sympy_to_numpy_pi + 4\n```\n\n### sympy has its own way to handle rational numbers\n\n\n```python\nsp.Rational(3,5)\n```\n\n\n```python\nsp.Rational(3,5) + sp.Rational(1,3)\n```\n\n#### Adding `.n()` to the end of a sympy expression will `evaluate` expression\n\n\n```python\nsp.Rational(3,5).n()\n```\n\n\n```python\nsp.pi.n()\n```\n\n#### You can add a value to `.n(value)` to set the number of significant figures\n\n\n```python\nsp.Rational(222,7).n()\n```\n\n\n```python\nsp.Rational(222,7).n(1)\n```\n\n\n```python\nsp.Rational(222,7).n(3)\n```\n\n#### `nsimplify()` will sort-of do the reverse of `.n()`\n\n\n```python\nsp.nsimplify(0.6)\n```\n\n\n```python\nsp.nsimplify(4.242640687119286)\n```\n\n\n```python\nsp.nsimplify(sp.pi, tolerance=1e-2)\n```\n\n\n```python\nsp.nsimplify(sp.pi, tolerance=1e-5)\n```\n\n\n```python\nsp.nsimplify(sp.pi, tolerance=1e-6)\n```\n\n### ... to $\\infty$ and beyond\n\n\n```python\nsp.oo\n```\n\n\n```python\nsp.oo + 3\n```\n\n\n```python\n1e199 < sp.oo\n```\n\n---\n## Matrix\n\n* There are a couple of different ways to create a Matrix\n* `Matrix(rows of lists)`\n* `Matrix(shape, list)`\n\n#### `rows of lists` is pretty straightforward\n\n\n```python\nsp.Matrix([[1,2],[3,4]])\n```\n\n#### `shape, list` gives you more flexibility\n\n\n```python\nsp.Matrix(2,2,[1,2,3,4])\n```\n\n\n```python\nsp.Matrix(1,4,[1,2,3,4])\n```\n\n\n```python\nsp.Matrix(4,1,[1,2,3,4])\n```\n\n\n```python\nmy_matrix = sp.Matrix(2,2,[1,2,3,4])\n\nmy_matrix\n```\n\n\n```python\nmy_matrix.det()\n```\n\n\n```python\nmy_matrix ** -1\n```\n\n\n```python\n(my_matrix ** -1) * my_matrix\n```\n\n---\n# Symbolic\n\n### You have to explicitly tell `SymPy` what symbols you want to use.\n\n* Once you declare symbols to use in `sympy` they are unavaliable for other packages\n\n\n```python\nx, y = sp.symbols('x y')\na, b, c = sp.symbols('a b c')\n```\n\n### Expressions are then able use these symbols\n\n\n```python\nmy_equation = (a * x**2 * y) + (b * x * y) + (c * x * y**2) + 6\n\nmy_equation\n```\n\n\n```python\nmy_equation + 3\n```\n\n\n```python\nmy_equation / x\n```\n\n\n```python\nsp.simplify(my_equation / x)\n```\n\n\n```python\nsp.collect(my_equation,x)\n```\n\n\n```python\nsp.collect(my_equation,y)\n```\n\n### You can evaluate equations for specific values\n\n\n```python\nmy_equation_x = sp.collect(my_equation,x)\n\nmy_equation_x\n```\n\n\n```python\nmy_equation_x.subs({y:sp.Rational(1,2), a:4, b:2, c:8})\n```\n\n### You can evaluate equations sybolically\n\n\n```python\nmy_equation_x\n```\n\n\n```python\nmy_y = (2*x + 3)\n\nmy_y\n```\n\n#### Replace $y$ with $2x + 3$ using `.subs()`\n\n\n```python\nmy_equation_x.subs(y, my_y)\n```\n\n#### Multiply everything through using `.expand()`\n\n\n```python\nsp.expand(my_equation_x.subs(y, my_y))\n```\n\n#### Collect the terms of $x$ using `.collect()`\n\n\n```python\nsp.collect(sp.expand(my_equation_x.subs(y, my_y)),x)\n```\n\n#### Evaluate the expression for some values of $a, b, c$ using `.subs()`\n\n\n```python\nsp.collect(sp.expand(my_equation_x.subs(y, my_y)),x).subs({a:4, b:2, c:8})\n```\n\n---\n## Calculus\n\n\n```python\nmy_equation\n```\n\n\n```python\nsp.diff(my_equation,x)\n```\n\n\n```python\nsp.diff(my_equation,x,2)\n```\n\n\n```python\nsp.integrate(my_equation,x)\n```\n\n\n```python\nsp.integrate(my_equation,(x,0,5)) # limits x = 0 to 5\n```\n\n\n```python\nsp.integrate(my_equation,(x,0,5)).n()\n```\n\n\n```python\nsp.integrate(my_equation,(x,0,5)).subs({y:sp.Rational(1,2), a:4, b:2, c:8})\n```\n\n\n```python\nsp.integrate(my_equation,(x,0,5)).subs({y:sp.Rational(1,2), a:4, b:2, c:8}).n()\n```\n\n---\n# Solving equations - `solve`\n\n* Need to rearrange equation so that it is set to equal zero \n\n### One equation\n\n$$ \\large\n3x - 3 = 30 \\hspace{1cm} \\rightarrow \\hspace{1cm} 3x - 33 = 0\n$$\n\n\n```python\nequation_in_x = 3 * x - 33\n\nequation_in_x\n```\n\n\n```python\nsp.solve([equation_in_x], [x])\n```\n\n### System of equations\n\n$$ \\large\n\\begin{array}{c}\n9x - 2y = 5\\\\\n-2x + 6y = 10\\\\\n\\end{array}\n$$\n\n\n```python\nequation_a = 9*x - 2*y - 5\nequation_b = -2*x + 6*y - 10\n```\n\n\n```python\nsp.solve([equation_a, equation_b], [x,y])\n```\n\n---\n\n### We can also do it the Matrix way\n\n$$ \\large\n\\begin{bmatrix}\n9 & -2 \\\\\n-2 & 6 \\\\\n\\end{bmatrix}\n\\begin{bmatrix}\nx \\\\\ny\n\\end{bmatrix}\n=\n\\begin{bmatrix}\n5 \\\\\n10\n\\end{bmatrix}\n$$\n\n$$ \\large\nA \\vec x = b\n$$\n\n\n```python\nmy_A = sp.Matrix(2,2,[9, -2,-2, 6])\n\nmy_A\n```\n\n\n```python\nmy_b = sp.Matrix(2,1,[5,10])\n\nmy_b\n```\n\n$$ \\large\n\\vec x = A^{-1}b\n$$\n\n\n```python\nmy_A ** -1 * my_b\n```\n\n---\n## Let's do some graphing stuff ...\n\n### In the following examples - notice the difference between `numpy` variables and `sympy` variables!\n\n\n \n\n$$\n\\large f(x) = 2\\,\\cos(5x) \\ e^{-x}\n$$\n\n \n\n### Need to create a `numpy` arrays to do the graphing\n\n\n```python\n# 200 points between -pi and pi\n\nmy_np_x = np.linspace(-np.pi, np.pi, 200)\n```\n\n\n```python\nmy_np_fx = 2 * np.cos(5 * my_np_x) * np.exp(-my_np_x)\n```\n\n\n```python\nplt.style.use('ggplot')\n```\n\n\n```python\nfig,ax = plt.subplots(1,1)\nfig.set_size_inches(10,6)\n\nfig.tight_layout()\n\nax.set_ylim(-11,11)\nax.set_xlim(-np.pi,np.pi)\n\nax.set_xlabel(\"This is X\", fontsize = 14)\nax.set_ylabel(\"This is Y\", fontsize = 14)\n\nax.plot(my_np_x, my_np_fx, \n color = (1.0, 0.0, 0.0, 0.5), \n marker='None', \n linestyle='-', \n linewidth = 6,\n label = \"f(x)\")\n\nax.legend(loc = 0, fontsize = 24, shadow = True);\n```\n\n---\n## Taylor Series\n\n* Taylor series are polynomial approximations at a specific point\n\n\n```python\nmy_sp_fx = 2 * sp.cos(5 * x) * sp.exp(-x)\nmy_sp_fx\n```\n\n### Taylor series of f(x) at f(x) = 0\n\n\n```python\nmy_taylor = sp.series(my_sp_fx, x, x0 = 0)\n\nmy_taylor\n```\n\n### If you want differnt number of terms\n\n* n = magnitude of the highest term\n* n = 4 means all terms up to x$^{4}$ or $\\mathcal{O}(4)$\n\n\n```python\nmy_taylor = sp.series(my_sp_fx, x, x0 = 0, n=4)\n\nmy_taylor\n```\n\n\n```python\nmy_taylor.removeO()\n```\n\n\n```python\nmy_taylor.removeO().n(3)\n```\n\n\n```python\n# Make NumPy versions of the term to plot\n\nmy_np_1term = -2.0 * my_np_x + 2.0\nmy_np_2term = -24.0 * my_np_x**2 - 2.0 * my_np_x + 2.0\nmy_np_3term = 24.7 * my_np_x**3 - 24.0 * my_np_x**2 - 2.0 * my_np_x + 2.0\n```\n\n\n```python\nfig,ax = plt.subplots(1,1)\nfig.set_size_inches(10,8)\n\nfig.tight_layout()\n\nax.set_ylim(-4,4)\nax.set_xlim(-1,1)\n\nax.set_xlabel(\"This is X\", fontsize = 14)\nax.set_ylabel(\"This is Y\", fontsize = 14)\n\nax.plot(my_np_x, my_np_fx, \n color = (1.0, 0.0, 0.0, 0.5), \n marker='None', \n linestyle='-', \n linewidth = 10,\n label = \"f(x)\")\n\nax.plot(my_np_x, my_np_1term, color='b', marker='None', linestyle='--', label=\"1-term\")\nax.plot(my_np_x, my_np_2term, color='g', marker='None', linestyle='--', label=\"2-term\")\nax.plot(my_np_x, my_np_3term, color='k', marker='None', linestyle='--', label=\"3-term\")\n\nax.legend(loc = 0, fontsize = 18);\n```\n\n---\n## General Equation Solving - `nsolve`\n\n$$\n\\Large f(x) = 2\\,\\cos(5x) \\ e^{-x} \\\\[10pt]\n\\Large g(x) = \\frac{3}{2} \\left [\\frac{x^3}{\\pi} - \\pi x \\right]\\\\\n$$\n\n### Make a `numpy` version of g(x)\n\n\n```python\nmy_np_gx = 3/2 * (my_np_x ** 3 / np.pi - np.pi * my_np_x)\n```\n\n### Where do they cross? - The graph\n\n\n```python\nfig,ax = plt.subplots(1,1)\nfig.set_size_inches(10,6)\n\nfig.tight_layout()\n\nax.set_ylim(-7,7)\nax.set_xlim(-np.pi,np.pi)\n\nax.set_xlabel(\"This is X\", fontsize = 14)\nax.set_ylabel(\"This is Y\", fontsize = 14)\n\nax.plot(my_np_x, my_np_fx, \n color = (1.0, 0.0, 0.0, 0.5), \n marker='None', \n linestyle='-', \n linewidth = 6,\n label = \"f(x)\")\n\nax.plot(my_np_x, my_np_gx, \n color = (0.25, 0.0, 0.75, 0.5), \n marker='None', \n linestyle='-', \n linewidth = 6,\n label = \"g(x)\")\n\n\nax.legend(loc = 0, fontsize = 24);\n```\n\n### Where do they cross? - The `sympy` solution\n\n### Make a `sympy` version of g(x)\n\n\n```python\nmy_sp_gx = sp.Rational(3,2) * (x ** 3 / sp.pi - sp.pi * x)\n\nmy_sp_gx\n```\n\n\n```python\nmy_sp_fx, my_sp_gx\n```\n\n### Need to provide an initial guess\n\n\n```python\nmy_guess = 3.0\n\nsp.nsolve(my_sp_fx - my_sp_gx, x, my_guess)\n```\n\n\n```python\nall_guesses = (3.0, 0, -1.0)\n\nfor val in all_guesses:\n result = sp.nsolve(my_sp_fx - my_sp_gx, x, val)\n print(result)\n```\n\n### Your guess has to be (somewhat) close or the solution will not converge:\n\n\n```python\nmy_guess = -40\n\nsp.nsolve(my_sp_fx - my_sp_gx, x, my_guess)\n```\n\n---\n## Primes\n\n\n```python\n# List of primes in the range 0 -> 100\n\nlist(sp.primerange(0,100))\n```\n\n\n```python\n# The 100th prime number\n\nsp.prime(100)\n```\n\n\n```python\n# The next prime after 2020\n\nsp.nextprime(2020)\n```\n\n\n```python\n# The prime factors of this year\n\nsp.factorint(2022)\n```\n\n# `SymPy` can do *so* much more. It really is magic. \n\n## Complete documentation can be found [here](http://docs.sympy.org/latest/index.html)\n", "meta": {"hexsha": "e37e741db22ba6ce9ce42f7639effaa4399fefd9", "size": 28282, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Python_SymPy.ipynb", "max_stars_repo_name": "UWashington-Astro300/Astro300-W22", "max_stars_repo_head_hexsha": "371eb704030a104cb8e826bb14c353e5a863b0f3", "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_SymPy.ipynb", "max_issues_repo_name": "UWashington-Astro300/Astro300-W22", "max_issues_repo_head_hexsha": "371eb704030a104cb8e826bb14c353e5a863b0f3", "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_SymPy.ipynb", "max_forks_repo_name": "UWashington-Astro300/Astro300-W22", "max_forks_repo_head_hexsha": "371eb704030a104cb8e826bb14c353e5a863b0f3", "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": 18.317357513, "max_line_length": 110, "alphanum_fraction": 0.4734460081, "converted": true, "num_tokens": 3228, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122732859021, "lm_q2_score": 0.9099070145888366, "lm_q1q2_score": 0.871611096823581}} {"text": "# Monte Carlo methods - A Sandbox/Demo\n\nMonte Carlo broadly refers to random sampling methods. Here we will focus mainly on Monte Carlo sampling in the context of molecular simulations, but it's worth briefly considering an example of Monte Carlo integration. Particularly, we can use Monte Carlo integration to calculate $\\pi$ with just a few lines of code.\n\n## Calculating $\\pi$ via MC integration\n\nSo, let's calculate $\\pi$ by doing MC integration. Particularly, let's consider a drawing random numbers between -1 and 1, and then imagine a circle centered at (0, 0). Consider the area of that circle (of radius 1) to that of the full square spanned by our random numbers (2 units wide). Particularly, if $R$ is the radius of the circle, then the ratio of the areas is:\n\\begin{equation}\n\\frac{A_{sq}}{A_{cir}} = \\frac{(2R)^2}{\\pi R^2} = \\frac{4}{\\pi} \n\\end{equation}\n\nso we find\n\\begin{equation}\n\\pi = \\frac{4 A_{cir}}{A_{sq}}\n\\end{equation}\n\nSo, if we randomly place points in an interval -1 to 1, and then check to see how many fall within a square versus within a circle, we can use the ratio of counts (related to the ratio of the areas) to determine $\\pi$.\n\n\n```python\n#Import modules we need\nimport numpy\nimport numpy.random\n\n#Number of data points to sample\nNtrials = 1000\n\n#Randomly generate array of XY positions - spanning -1 to 1\nXY = 2.*numpy.random.rand( Ntrials, 2)-1.\n\n#Compute distance from each point to center of the circle\ndistances = numpy.sqrt( numpy.sum( XY*XY, axis=1))\n\n#Find indices of data points which are within the unit circle\n#Note that you could code this in a more straightforward - but slower - way by setting up a \n#'for' loop over data points and checking to see where the distance is less than 1.\nindices_inside = numpy.where( distances < 1)\n\n#Find how many points are here\nnum_inside = len( indices_inside[0] )\n\n#Calculate estimate of pi\npi_estimate = 4.*num_inside/float(Ntrials)\nprint(pi_estimate)\n```\n\n 3.228\n\n\n### Let's take a look at what we've done here, graphically. \nWe can plot the points inside and outside in two different colors to see.\n\n\n```python\n%pylab inline\n\n#After the code above, indices_inside has the numbers of points which are inside our unit circle.\n#We would also like indices of points which are outside the unit circle\nindices_outside = numpy.where( distances > 1)\n\n#Make our plot of points inside and outside using circles for the data points\n#blue for inside, red for outside\nplot(XY[indices_inside[0],0], XY[indices_inside[0],1], 'bo')\nplot(XY[indices_outside[0],0], XY[indices_outside[0],1], 'ro')\n\n#Adjust plot settings to look nicer\naxis('equal') #Set to have equal axes\nF = pylab.gcf() #Get handle of current figure\nF.set_size_inches(5,5) #Set size to be square (default view is rectangular)\n\n#Bonus: Drawing a unit circle on the graph is up to you\n```\n\n# Let's revisit the LJ particles we saw in the MD sandbox\n\nIn our last sandbox, we looked at molecular dynamics on a pair of Lennard-Jones particles. Now let's revisit that, but within the Metropolis Monte Carlo framework. Optionally, you could make things a little more interesting here by considering an extra particle. But for now let's just start with the same two particles as last time to make visualization easy.. \n\nHere, we'll apply the Metropolis MC framework as discussed in lecture, where every step we:\n* Randomly pick a particle\n* Change each of x, y, and z a small amount between $-\\Delta r_{max}$ and $\\Delta r_{max}$\n* Compute the energy change $\\Delta U$\n* Apply the Metropolis criterion to decide whether to accept the move or reject it\n * If $\\Delta U < 0$, accept the move\n * If $\\Delta U > 0$, accept with the probability $P_{acc} = e^{-\\Delta U/T}$\n* If accepted, keep the new configuration\n* Regardless of whether we accept it or not, update any running averages with the current state and energy\n\n\n## Let's run some MC \n\n(Before doing the below, you need to compile the `mc_sandbox` Fortran library as you've done for other libraries previously; typically it will look something like `f2py -c -m mc_sandbox mc_sandbox.f90` on the command-line.)\n\n### First, we set up our system:\n\n\n```python\nimport mc_sandbox\nimport numpy as np\nimport numpy.random\n\n#Let's define the variables we'll need\nCut = 2.5\nL = 3.0 #Let's put these in a small box so they don't lose each other\nmax_displacement = 0.1 #Maximum move size\nT = 1. #You should play with this and see how the results change. Don't make it an integer - use a floating point value (i.e. 1., not 1)\n\n#Choose N for number of particles; you could adjust this later.\nN = 2\n\n#Allocate position array - initially just zeros\nPos = np.zeros((N,3), float)\n\n#Let's place the first two particles just as we did in MD Sandbox:\nPos[0,:] = np.array([0,0,0])\n#We'll place the second one fairly nearby - at this point using the same starting location\n#as in the MD sandbox\nPos[1,:] = np.array([1.5,0,0])\n\n#If you have any other particles, let's just place them randomly\nfor i in range(2,N):\n Pos[i,:] = L*np.random.random( 3 )\n```\n\n### Now let's run a step of MC!\n\n\n```python\n#Set maximum number of steps to run\nmax_steps = 10000\n\n#Set up storage for position vs step\nPos_t = np.zeros(( N,3,max_steps), float)\n#Store initial positions\nPos_t[:,:,0] = Pos\n\n#Evaluate initial energy\nU = mc_sandbox.calcenergy(Pos, L, Cut)\n\n#Pick a random particle\nnum = np.random.randint(N) #Random integer from 0 up to but not including N\n\n#Store old position in case we need to revert\n#Note that it's necessary here to make a copy, otherwise both still point to the same \n#coordinates (try OldPos = Pos to see).\nOldPos = Pos.copy() \n\n#Pick a move - adjusting to make it between -DeltaX and +DeltaX\nmove = max_displacement * (np.random.random( 3)*2.-1.)\n\n#Update position\nPos[num, :] += move\n\n#Evaluate new energy\nUnew = mc_sandbox.calcenergy( Pos, L, Cut)\nDeltaU = Unew - U\nprint(\"U, Unew, DeltaU: \", U, Unew, DeltaU) #Just for debugging purposes so we can see what's happening.\n\n#Print acceptance probability\nPacc = np.exp(-DeltaU/T)\nprint(\"Acceptance probability Pacc=\", Pacc) #Just for debugging purposes so we can see what's happening.\n\n#We can handle the uphill and downhill cases with a single 'if' statement\nif np.random.rand() < Pacc:\n print(\"Accepted\") #Just for debugging purposes so we can see what's happening.\n U = Unew\nelse: #Revert\n Pos = OldPos\n print(\"Rejected\") #Just for debugging purposes so we can see what's happening.\n\n\n#Remember, at the end, if we are tracking energy, we update running averages/tracking data \n#with the current position and energy\nPos_t[:, :, 1] = Pos\n```\n\n U, Unew, DeltaU: -0.3366534854145746 -0.4458429221834246 -0.10918943676884996\n Acceptance probability Pacc= 1.1153736231\n Accepted\n\n\n## Now let's again define that get_r function so we can look at the separation between our particles over time\nLast time, I was lazy and didn't handle the minimum image convention (in part because I knew we weren't giving the particles enough energy initially that they wouldn't fly apart). Here, because T (effectively, the kinetic energy) is an adjustable parameter we might end up with them flying apart, so we need to use the minimum image convention to properly measure the distance between particles. In other words, if a particle crosses the box edge and then finds the other particle and interacts with it, we want our distance measurement to notice that they are interacting rather than reporting that they are very distant. (The Fortran code we have is using this convention for its energy calculations).\n\nSo, we define a new get_r function which handles this:\n\n\n```python\ndef get_r(Pos, L):\n \"\"\"Calculate r, the distance between particles, for a position array containing just two particles. Return it.\n Unlike in MD sandbox, here we also implement the minimum image convention\"\"\"\n \n #Get displacement\n disp = Pos[1,:] - Pos[0,:]\n #Apply minimum image convention\n disp = disp - L*np.round(disp/L) \n #Calculate distance\n d = np.sqrt( np.dot( disp, disp))\n return d\n```\n\n## Now, write your own code - adapting the code from above for a single step - to run an MC simulation of your pair of LJ particles\n\nBecause a little more code is required than for the MD assignment, I provide some comments guiding you through the steps you'll need to do. And I also provide code to generate a plot at the end.\n\nBe sure to track the acceptance probability over all suggested moves. (This could be used to adjust the size of the moves you suggest).\n\n\n```python\n# Put your code here\n\n```\n\n\n```python\n##GET READY TO PLOT\n#Find x axis (MC steps rather than time, as it was in the MD sandbox)\nt = np.arange(0,max_steps)\n#Find y axis (r values)\nr_vs_t = []\nfor i in range(max_steps):\n r=get_r(Pos_t[:,:,i], L)\n r_vs_t.append(r)\n\nr_vs_t = np.array(r_vs_t)\n\n#Plot\nfigure()\nplot(t, r_vs_t)\n```\n\n## Other things to be sure to try\n* See what happens if you adjust the temperature. Particularly, check what happens in the limit of T becoming very small (approaching zero). Are uphill moves ever accepted? What does an MC search end up doing?\n* Try making the box size reasonably big and see what happens at a moderate temperature\n* Adjust the move size (`max_displacement`) to make the acceptance probability 30-50%. How big can you make it? \n\n## Other things to try if you have extra time\n* Check the probability distribution of separations and see how it varies with temperature. \n", "meta": {"hexsha": "f3ce173d1e36ea2dde68f274169c89f6df62a6b0", "size": 39780, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "uci-pharmsci/lectures/MC/MC Sandbox.ipynb", "max_stars_repo_name": "inferential/drug-computing", "max_stars_repo_head_hexsha": "25ff2f04b2a1f7cb71c552f62e722edb26cc297f", "max_stars_repo_licenses": ["CC-BY-4.0", "MIT"], "max_stars_count": 103, "max_stars_repo_stars_event_min_datetime": "2017-10-21T18:49:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T22:05:21.000Z", "max_issues_repo_path": "uci-pharmsci/lectures/MC/MC Sandbox.ipynb", "max_issues_repo_name": "inferential/drug-computing", "max_issues_repo_head_hexsha": "25ff2f04b2a1f7cb71c552f62e722edb26cc297f", "max_issues_repo_licenses": ["CC-BY-4.0", "MIT"], "max_issues_count": 29, "max_issues_repo_issues_event_min_datetime": "2017-10-23T20:57:17.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-15T21:57:09.000Z", "max_forks_repo_path": "uci-pharmsci/lectures/MC/MC Sandbox.ipynb", "max_forks_repo_name": "inferential/drug-computing", "max_forks_repo_head_hexsha": "25ff2f04b2a1f7cb71c552f62e722edb26cc297f", "max_forks_repo_licenses": ["CC-BY-4.0", "MIT"], "max_forks_count": 36, "max_forks_repo_forks_event_min_datetime": "2018-01-18T20:22:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-16T13:08:09.000Z", "avg_line_length": 108.9863013699, "max_line_length": 26148, "alphanum_fraction": 0.8475615887, "converted": true, "num_tokens": 2420, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122696813394, "lm_q2_score": 0.9099070023734244, "lm_q1q2_score": 0.8716110818424708}} {"text": "```python\n# setup SymPy\nfrom sympy import *\ninit_printing()\nx, y, z, t = symbols('x y z t')\nalpha, beta = symbols('alpha beta')\n\n```\n\n# Linearity\n\n\n```python\nb, m = symbols('b m')\n\ndef f(x):\n return m*x\n```\n\n\n```python\nf(1)\n```\n\n\n```python\nf(2)\n```\n\n\n```python\nf(1+2)\n```\n\n\n```python\nf(1) + f(2)\n```\n\n\n```python\nexpand(f(x+y)) == f(x) + f(y)\n```\n\n\n\n\n True\n\n\n\n## What about vector inputs?\n\n\n```python\nm_1, m_2 = symbols('m_1 m_2')\n\ndef T(vec):\n \"\"\"A function that takes a 2D vector and returns a number.\"\"\"\n return m_1*vec[0] + m_2*vec[1]\n```\n\n\n```python\nu_1, u_2 = symbols('u_1 u_2')\nu = Matrix([u_1,u_2])\nv_1, v_2 = symbols('v_1 v_2')\nv = Matrix([v_1,v_2])\n```\n\n\n```python\nT(u)\n```\n\n\n```python\nT(v)\n```\n\n\n```python\nT(u) + T(v)\n```\n\n\n```python\nexpand( T(u+v) )\n```\n\n\n```python\nsimplify( T(alpha*u + beta*v) - alpha*T(u) - beta*T(v) )\n```\n\n# Linear transformations\n\nA linear transformation is function that takes vectors as inputs, and produces vectors as outputs:\n\n$$\n T: \\mathbb{R}^n \\to \\mathbb{R}^m.\n$$\n\nsee page 116 in book\n\n\n```python\nm_11, m_12, m_21, m_22 = symbols('m_11 m_12 m_21 m_22')\n\ndef T(vec):\n \"\"\"A linear transformations R^2 --> R^2.\"\"\"\n out_1 = m_11*vec[0] + m_12*vec[1]\n out_2 = m_21*vec[0] + m_22*vec[1]\n return Matrix([out_1, out_2])\n```\n\n\n```python\nT(u)\n```\n\n\n```python\nT(v)\n```\n\n\n```python\nT(u+v)\n```\n\n## Linear transformations as matrix-vector products \n\nsee page 113\n\n\n```python\ndef T_impl(vec):\n \"\"\"A linear transformations implemented as matrix-vector product.\"\"\"\n M_T = Matrix([[m_11, m_12], \n [m_21, m_22]])\n return M_T*vec\n```\n\n\n```python\nT_impl(u)\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "39338c917b901b0885978e2bdbb10f835bbc2b4f", "size": 19422, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "chapter02_linearity_intuition.ipynb", "max_stars_repo_name": "ChidinmaKO/noBSLAnotebooks", "max_stars_repo_head_hexsha": "c0102473f1e6625fa5fb62768d4545059959fa26", "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": "chapter02_linearity_intuition.ipynb", "max_issues_repo_name": "ChidinmaKO/noBSLAnotebooks", "max_issues_repo_head_hexsha": "c0102473f1e6625fa5fb62768d4545059959fa26", "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": "chapter02_linearity_intuition.ipynb", "max_forks_repo_name": "ChidinmaKO/noBSLAnotebooks", "max_forks_repo_head_hexsha": "c0102473f1e6625fa5fb62768d4545059959fa26", "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.9218436874, "max_line_length": 1792, "alphanum_fraction": 0.7055915972, "converted": true, "num_tokens": 597, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122684798183, "lm_q2_score": 0.909907001151883, "lm_q1q2_score": 0.8716110795790689}} {"text": "# Modeling and Simulation in Python\n\nChapter 9\n\nCopyright 2017 Allen Downey\n\nLicense: [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0)\n\n\n\n```python\n# import everything from SymPy.\nfrom sympy import *\n\n# Set up Jupyter notebook to display math.\ninit_printing() \n```\n\nThe following displays SymPy expressions and provides the option of showing results in LaTeX format.\n\n\n```python\nfrom sympy.printing import latex\n\ndef show(expr, show_latex=False):\n \"\"\"Display a SymPy expression.\n \n expr: SymPy expression\n show_latex: boolean\n \"\"\"\n if show_latex:\n print(latex(expr))\n return expr\n```\n\n### Analysis with SymPy\n\nCreate a symbol for time.\n\n\n```python\nt = symbols('t')\nt\n```\n\nIf you combine symbols and numbers, you get symbolic expressions.\n\n\n```python\nexpr = t + 1\nexpr\n```\n\nThe result is an `Add` object, which just represents the sum without trying to compute it.\n\n\n```python\ntype(expr)\n```\n\n\n\n\n sympy.core.add.Add\n\n\n\n`subs` can be used to replace a symbol with a number, which allows the addition to proceed.\n\n\n```python\nexpr.subs(t, 2)\n```\n\n`f` is a special class of symbol that represents a function.\n\n\n```python\nf = Function('f')\nf\n```\n\n\n\n\n f\n\n\n\nThe type of `f` is `UndefinedFunction`\n\n\n```python\ntype(f)\n```\n\n\n\n\n sympy.core.function.UndefinedFunction\n\n\n\nSymPy understands that `f(t)` means `f` evaluated at `t`, but it doesn't try to evaluate it yet.\n\n\n```python\nf(t)\n```\n\n`diff` returns a `Derivative` object that represents the time derivative of `f`\n\n\n```python\ndfdt = diff(f(t), t)\ndfdt\n```\n\n\n```python\ntype(dfdt)\n```\n\n\n\n\n sympy.core.function.Derivative\n\n\n\nWe need a symbol for `alpha`\n\n\n```python\nalpha = symbols('alpha')\nalpha\n```\n\nNow we can write the differential equation for proportional growth.\n\n\n```python\neq1 = Eq(dfdt, alpha*f(t))\neq1\n```\n\nAnd use `dsolve` to solve it. The result is the general solution.\n\n\n```python\nsolution_eq = dsolve(eq1)\nsolution_eq\n```\n\nWe can tell it's a general solution because it contains an unspecified constant, `C1`.\n\nIn this example, finding the particular solution is easy: we just replace `C1` with `p_0`\n\n\n```python\nC1, p_0 = symbols('C1 p_0')\n```\n\n\n```python\nparticular = solution_eq.subs(C1, p_0)\nparticular\n```\n\nIn the next example, we have to work a little harder to find the particular solution.\n\n### Solving the quadratic growth equation \n\nWe'll use the (r, K) parameterization, so we'll need two more symbols:\n\n\n```python\nr, K = symbols('r K')\n```\n\nNow we can write the differential equation.\n\n\n```python\neq2 = Eq(diff(f(t), t), r * f(t) * (1 - f(t)/K))\neq2\n```\n\nAnd solve it.\n\n\n```python\nsolution_eq = dsolve(eq2)\nsolution_eq\n```\n\nThe result, `solution_eq`, contains `rhs`, which is the right-hand side of the solution.\n\n\n```python\ngeneral = solution_eq.rhs\ngeneral\n```\n\nWe can evaluate the right-hand side at $t=0$\n\n\n```python\nat_0 = general.subs(t, 0)\nat_0\n```\n\nNow we want to find the value of `C1` that makes `f(0) = p_0`.\n\nSo we'll create the equation `at_0 = p_0` and solve for `C1`. Because this is just an algebraic identity, not a differential equation, we use `solve`, not `dsolve`.\n\nThe result from `solve` is a list of solutions. In this case, [we have reason to expect only one solution](https://en.wikipedia.org/wiki/Picard%E2%80%93Lindel%C3%B6f_theorem), but we still get a list, so we have to use the bracket operator, `[0]`, to select the first one.\n\n\n```python\nsolutions = solve(Eq(at_0, p_0), C1)\ntype(solutions), len(solutions)\n```\n\n\n\n\n (list, 1)\n\n\n\n\n```python\nvalue_of_C1 = solutions[0]\nvalue_of_C1\n```\n\nNow in the general solution, we want to replace `C1` with the value of `C1` we just figured out.\n\n\n```python\nparticular = general.subs(C1, value_of_C1)\nparticular\n```\n\nThe result is complicated, but SymPy provides a method that tries to simplify it.\n\n\n```python\nparticular = simplify(particular)\nparticular\n```\n\nOften simplicity is in the eye of the beholder, but that's about as simple as this expression gets.\n\nJust to double-check, we can evaluate it at `t=0` and confirm that we get `p_0`\n\n\n```python\nparticular.subs(t, 0)\n```\n\nThis solution is called the [logistic function](https://en.wikipedia.org/wiki/Population_growth#Logistic_equation).\n\nIn some places you'll see it written in a different form:\n\n$f(t) = \\frac{K}{1 + A e^{-rt}}$\n\nwhere $A = (K - p_0) / p_0$.\n\nWe can use SymPy to confirm that these two forms are equivalent. First we represent the alternative version of the logistic function:\n\n\n```python\nA = (K - p_0) / p_0\nA\n```\n\n\n```python\nlogistic = K / (1 + A * exp(-r*t))\nlogistic\n```\n\nTo see whether two expressions are equivalent, we can check whether their difference simplifies to 0.\n\n\n```python\nsimplify(particular - logistic)\n```\n\nThis test only works one way: if SymPy says the difference reduces to 0, the expressions are definitely equivalent (and not just numerically close).\n\nBut if SymPy can't find a way to simplify the result to 0, that doesn't necessarily mean there isn't one. Testing whether two expressions are equivalent is a surprisingly hard problem; in fact, there is no algorithm that can solve it in general.\n\n### Exercises\n\n**Exercise:** Solve the quadratic growth equation using the alternative parameterization\n\n$\\frac{df(t)}{dt} = \\alpha f(t) + \\beta f^2(t) $\n\n\n```python\n# Solution\n\nalpha, beta = symbols('alpha beta')\n```\n\n\n```python\n# Solution\n\neq3 = Eq(diff(f(t), t), alpha*f(t) + beta*f(t)**2)\neq3\n```\n\n\n```python\n# Solution\n\nsolution_eq = dsolve(eq3)\nsolution_eq\n```\n\n\n```python\n# Solution\n\ngeneral = solution_eq.rhs\ngeneral\n```\n\n\n```python\n# Solution\n\nat_0 = general.subs(t, 0)\n```\n\n\n```python\n# Solution\n\nsolutions = solve(Eq(at_0, p_0), C1)\nvalue_of_C1 = solutions[0]\nvalue_of_C1\n```\n\n\n```python\n# Solution\n\nparticular = general.subs(C1, value_of_C1)\nparticular.simplify()\n```\n\n**Exercise:** Use [WolframAlpha](https://www.wolframalpha.com/) to solve the quadratic growth model, using either or both forms of parameterization:\n\n df(t) / dt = alpha f(t) + beta f(t)^2\n\nor\n\n df(t) / dt = r f(t) (1 - f(t)/K)\n\nFind the general solution and also the particular solution where `f(0) = p_0`.\n\n\n```python\n\n```\n", "meta": {"hexsha": "aa6929e0dc9c34fd9af0b1188cce655ad66d5be4", "size": 81329, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "soln/chap09soln.ipynb", "max_stars_repo_name": "kanhaiyap/ModSimPy", "max_stars_repo_head_hexsha": "af16c079ec398ff9b3822d3dcda75873ce900ced", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-04-27T22:43:12.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-11T15:12:23.000Z", "max_issues_repo_path": "soln/chap09soln.ipynb", "max_issues_repo_name": "ffriass/ModSimPy", "max_issues_repo_head_hexsha": "c36a476a20042acb33773e47d12aea5b0c413e60", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 33, "max_issues_repo_issues_event_min_datetime": "2019-10-09T18:50:22.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-21T01:39:48.000Z", "max_forks_repo_path": "soln/chap09soln.ipynb", "max_forks_repo_name": "ffriass/ModSimPy", "max_forks_repo_head_hexsha": "c36a476a20042acb33773e47d12aea5b0c413e60", "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": 70.8440766551, "max_line_length": 5440, "alphanum_fraction": 0.8126867415, "converted": true, "num_tokens": 1710, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741288419873, "lm_q2_score": 0.9149009526726545, "lm_q1q2_score": 0.8715109779688581}} {"text": "# Symbolically Understanding Christoffel Symbol and Riemann Curvature Tensor using EinsteinPy\n\n\n```python\nimport sympy\nfrom einsteinpy.symbolic import MetricTensor, ChristoffelSymbols, RiemannCurvatureTensor\n\nsympy.init_printing() # enables the best printing available in an environment\n```\n\n### Defining the metric tensor for 3d spherical coordinates\n\n\n```python\nsyms = sympy.symbols('r theta phi')\n# define the metric for 3d spherical coordinates\nmetric = [[0 for i in range(3)] for i in range(3)]\nmetric[0][0] = 1\nmetric[1][1] = syms[0]**2\nmetric[2][2] = (syms[0]**2)*(sympy.sin(syms[1])**2)\n# creating metric object\nm_obj = MetricTensor(metric, syms)\nm_obj.tensor()\n```\n\n### Calculating the christoffel symbols\n\n\n```python\nch = ChristoffelSymbols.from_metric(m_obj)\nch.tensor()\n```\n\n\n```python\nch.tensor()[1,1,0]\n```\n\n### Calculating the Riemann Curvature tensor\n\n\n```python\n# Calculating Riemann Tensor from Christoffel Symbols\nrm1 = RiemannCurvatureTensor.from_christoffels(ch)\nrm1.tensor()\n```\n\n\n```python\n# Calculating Riemann Tensor from Metric Tensor\nrm2 = RiemannCurvatureTensor.from_metric(m_obj)\nrm2.tensor()\n```\n\n### Calculating the christoffel symbols for Schwarzschild Spacetime Metric\n - The expressions are unsimplified\n\n\n```python\nsyms = sympy.symbols(\"t r theta phi\")\nG, M, c, a = sympy.symbols(\"G M c a\")\n# using metric values of schwarschild space-time\n# a is schwarzschild radius\nlist2d = [[0 for i in range(4)] for i in range(4)]\nlist2d[0][0] = 1 - (a / syms[1])\nlist2d[1][1] = -1 / ((1 - (a / syms[1])) * (c ** 2))\nlist2d[2][2] = -1 * (syms[1] ** 2) / (c ** 2)\nlist2d[3][3] = -1 * (syms[1] ** 2) * (sympy.sin(syms[2]) ** 2) / (c ** 2)\nsch = MetricTensor(list2d, syms)\nsch.tensor()\n```\n\n\n```python\n# single substitution\nsubs1 = sch.subs(a,0)\nsubs1.tensor()\n```\n\n\n```python\n# multiple substitution\nsubs2 = sch.subs([(a,0), (c,1)])\nsubs2.tensor()\n```\n\n\n```python\nsch_ch = ChristoffelSymbols.from_metric(sch)\nsch_ch.tensor()\n```\n\n### Calculating the simplified expressions\n\n\n```python\nsimplified = sch_ch.simplify()\nsimplified\n```\n", "meta": {"hexsha": "9d9a3a48628adad033418ba3b5683714d11108c3", "size": 133955, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "docs/source/examples/Symbolically Understanding Christoffel Symbol and Riemann Curvature Tensor using EinsteinPy.ipynb", "max_stars_repo_name": "iamhardikat11/einsteinpy", "max_stars_repo_head_hexsha": "7bf0ca0020b273e616b6e7c19aed7a5e13925444", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 485, "max_stars_repo_stars_event_min_datetime": "2019-02-04T09:15:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-19T13:50:17.000Z", "max_issues_repo_path": "docs/source/examples/Symbolically Understanding Christoffel Symbol and Riemann Curvature Tensor using EinsteinPy.ipynb", "max_issues_repo_name": "iamhardikat11/einsteinpy", "max_issues_repo_head_hexsha": "7bf0ca0020b273e616b6e7c19aed7a5e13925444", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 570, "max_issues_repo_issues_event_min_datetime": "2019-02-02T10:57:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-26T16:37:05.000Z", "max_forks_repo_path": "docs/source/examples/Symbolically Understanding Christoffel Symbol and Riemann Curvature Tensor using EinsteinPy.ipynb", "max_forks_repo_name": "iamhardikat11/einsteinpy", "max_forks_repo_head_hexsha": "7bf0ca0020b273e616b6e7c19aed7a5e13925444", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 250, "max_forks_repo_forks_event_min_datetime": "2019-01-30T14:14:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-28T21:18:18.000Z", "avg_line_length": 232.9652173913, "max_line_length": 33924, "alphanum_fraction": 0.826501437, "converted": true, "num_tokens": 654, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741241296943, "lm_q2_score": 0.9149009567332237, "lm_q1q2_score": 0.8715109775255699}} {"text": "# Support Vector Machines\n\n## Motivating Support Vector Machines\n### Developing the Intuition\n\nSupport vector machines (SVM) are a powerful and flexible class of supervised algorithms. Developed in the 1990s, SVM have shown to perform well in a variety of settings which explains their popularity. Though the underlying mathematics can become somewhat complicated, the basic concept of a SVM is easily understood. Therefore, in what follows we develop an intuition, introduce the mathematical basics of SVM and ultimately look into how we can apply SVM with Python.\n\nAs an introductory example, borrowed from VanderPlas (2016), consider the following simplified two-dimensional classification task, where the two classes (indicated by the colors) are well separated. \n\n\n\nA linear discriminant classifier as discussed in chapter 8 would attempt to draw a separating hyperplane (which in two dimensions is nothing but a line) in order to distinguish the two classes. For two-dimensional data, we could even do this by hand. However, one problem arises: there are more than one separating hyperplane between the two classes.\n\n\n\nThere exist an infinite number of possible hyperplanes that perfectly discriminate between the two classes in the training data. In above figure we visualize but three of them. Depending on what hyperplane we choose, a new data point (e.g. the one marked by the red \"X\") will be assigned a different label. Yet, so far we have no decision criteria established to decide which one of the three hyperplanes we should choose. \n\nHow do we decide which line best separates the two classes? The idea of SVM is to add a margin of some width to both sides of each hyperplane - up to the nearest point. This might look something like this:\n\n\n\nIn SVM, the hyperplane that maximizes the margin to the nearest points is the one that is chosen as decision boundary. In other words, the maximum margin estimator is what we are looking for. Below figure shows the optimal solution for a (linear) SVM. Of all possible hyperplanes, the solid line has the largest margins (dashed lines) - measured from the decision boundary (solid line) to the nearest points (circled points). \n\n\n\n### Support Vector\n\nThe three circled sample points in above figure represent the nearest points. All three lie along the (dashed) margin line and in terms of perpendicular distance are equidistant from the decision boundary (solid line). Together they form the so called **support vector**. The support vector \"supports\" the maximal margin hyperplane in the sense that if one of the observations were moved slightly, the maximal margin hyperplane would move as well. In other words, they dictate slope and intercept of the hyperplane. Interestingly, any points further from the margin that are on the correct side do not modify the decision boundary. For example points at $(x_1, x_2) = (2.5, 1)$ or $(1, 4.2)$ have no effect on the decision boundary. Technically, this is because these points do not contribute to the loss function used to fit the model, so their position and number do not matter so long as they do not cross the margin (VanderPlas (2016)) . This is an important and helpful property as it simplifies calculations significantly. It is not surprising that computations are a lot faster if a model has only a few data points (in the support vector) to consider (James et al. (2013)). \n\n## Developing the Mathematical Intuition\n### Hyperplanes\n\nTo start, let us do a brief (and superficial) refresher on hyperplanes. In a $p$-dimensional space, a hyperplane is a flat (affine) subspace of dimension $p - 1$. Affine simply indicates that the subspace need not pass through the origin. As we have seen above, in two dimensions a hyperplane is just a line. In three dimensions it is a plane. For $p > 3$ visualization is hardly possible but the notion applies in similar fashion. Mathematically a $p$-dimensional hyperplane is defined by the expression \n\n\\begin{equation}\n\\beta_0 + \\beta_1 x_1 + \\beta_2 x_2 + \\ldots + \\beta_p x_p = 0\n\\end{equation}\n\n\nIf a point $\\mathbf{x}^* = (x^*_1, x^*_2, \\ldots, x^*_p)^T$ (i.e. a vector of length $p$) satisfies the above equation, then $\\mathbf{x}^*$ lies on the hyperplane. If $\\mathbf{x}^{*}$ does not satisfy above equation but yields a value $>0$, that is\n\n\\begin{equation}\n\\beta_0 + \\beta_1 x^*_1 + \\beta_2 x^*_2 + \\ldots + \\beta_p x^*_p > 0\n\\end{equation}\n\nthen this tells us that $\\mathbf{x}^*$ lies on one side of the hyperplane. Similarly, \n\n\\begin{equation}\n\\beta_0 + \\beta_1 x^*_1 + \\beta_2 x^*_2 + \\ldots + \\beta_p x^*_p < 0\n\\end{equation}\n\ntells us that $\\mathbf{x}^*$ lies on the other side of the plane. \n\n### Separating Hyperplanes\n\nSuppose our training sample is a $n \\times p$ data matrix $\\mathbf{X}$ that consists of $n$ observations in $p$-dimensional space, \n\n\\begin{equation*}\n\\mathbf{x}_1 = \n\\begin{pmatrix}\nx_{11} \\\\\n\\vdots \\\\\nx_{1p}\n\\end{pmatrix}, \\; \\ldots, \\; \\mathbf{x}_n = \n\\begin{pmatrix}\nx_{n1} \\\\\n\\vdots \\\\\nx_{np}\n\\end{pmatrix}\n\\end{equation*}\n\nand each observation falls into one of two classes: $y_1, \\ldots, y_n \\in \\{-1, 1\\}$. Then a separating hyperplane has the helpful property that\n\n\\begin{align}\nf(x) = \\beta_0 + \\beta_1 x_{i1} + \\beta_2 x_{i2} + \\ldots + \\beta_p x_{ip} \\quad \\text{is} \\quad\n\\begin{cases}\n> 0 & \\quad \\text{if } y_i =1 \\\\\n< 0 & \\quad \\text{if } y_i = -1 \n\\end{cases}\n\\end{align}\n\nGiven such a hyperplane exists, it can be used to construct a very intuitive classifier: a test observation is assigned to a class based on the side of the hyperplane it lies. This means we simply calculate $f(x^*)$ and if the result is positive, we assign the test observation to class 1, and to class -1 otherwise.\n\n### Maximal Margin Classifier\n\nIf our data can be perfectly separated, then - as alluded to above - there exist an infinite number of separating hyperplanes. Therefore we seek to maximize the margin to the closest training observations (support vector). The result is what we call the *maximal margin hyperplane*. \n\nLet us consider how such a maximal margin hyperplane is constructed. We follow Raschka (2015) in deriving the objective function as this approach is appealing to the intuition. For a mathematically more sound derivation, see e.g. Friedman et al. (2001, chapter 4.5). As before we assume to have a set of $n$ training observations $\\mathbf{x}_1, \\mathbf{x}_2, \\ldots, \\mathbf{x}_n \\in \\mathbb{R}^p$ with corresponding class labels $y_1, y_2, \\ldots, y_n \\in \\{-1, 1\\}$. The hyperplane as our decision boundary we have introduced above. Here is the same in vector notation, where $\\mathbf{\\beta}$ and $\\mathbf{x}$ are vector of dimension $[p \\times 1]$:\n\n\\begin{equation}\n\\beta_0 + \\mathbf{\\beta}^T \\mathbf{x}_{\\text{hyper}} = 0\n\\end{equation}\n\nThis way of writing is much more concise and therefore we will stick to it moving forward. Let us further define the positive and negative margin hyperplanes, which lie parallel to the decision boundary:\n\\begin{align}\n\\beta_0 + \\mathbf{\\beta}^T \\mathbf{x}_{\\text{pos}} &= 1 &\\text{pos. margin} \\\\\n\\beta_0 + \\mathbf{\\beta}^T \\mathbf{x}_{\\text{neg}} &= -1 &\\text{neg. margin}\n\\end{align}\n\n\nBelow you find a visual representationof the above. Notice that the two margin hyperplanes are parallel and the values for $\\beta_0, \\mathbf{\\beta}$ are identical\n\n\n\nIf we subtract the equation for the negative margin from the positive, we get:\n\n\\begin{equation}\n\\mathbf{\\beta}^T (\\mathbf{x}_{\\text{pos}} - \\mathbf{x}_{\\text{neg}}) = 2\n\\end{equation}\n\nLet us normalize both sides of the equation by the length of the vector $\\mathbf{\\beta}$, that is the norm, which is defined as follows:\n\n\\begin{equation}\n\\Vert \\mathbf{\\beta} \\Vert := \\sqrt{\\sum_{i=1}^p \\beta_i^2} = 1\n\\end{equation}\n\nWith that we arrive at the following expression:\n\n\\begin{equation}\n\\frac{\\mathbf{\\beta}^T (\\mathbf{x}_{\\text{pos}} - \\mathbf{x}_{\\text{neg}})}{\\Vert \\mathbf{\\beta}\\Vert} = \\frac{2}{\\Vert \\mathbf{\\beta} \\Vert}\n\\end{equation}\n\nThe left side of the equation can be interpreted as the normalized distance between the positive (upper) and negative (lower) margin. This distance we aim to maximize. Since maximizing the lefthand side of above expression is similar to maximizing the right hand side, we can summarize this in the following optimization problem:\n\n\\begin{equation}\n\\begin{aligned}\n& \\underset{\\beta_0, \\beta_1, \\ldots, \\beta_p}{\\text{maximize}}\n& & \\frac{2}{\\Vert \\mathbf{\\beta} \\Vert} \\\\\n& \\text{subject to} & & \\beta_0 + \\mathbf{\\beta}^T \\mathbf{x}_{i} \\geq \\;\\; 1 \\quad \\text{if } y_i = 1 \\\\\n&&& \\beta_0 + \\mathbf{\\beta}^T \\mathbf{x}_{i} \\leq -1 \\quad \\text{if } y_i = -1 \\\\\n&&& \\text{for } i = 1, \\ldots, N.\n\\end{aligned}\n\\end{equation}\n\nThe two constraints make sure that all positive samples ($y_i = 1$) fall on or above the positive side of the positive margin hyperplane and all negative samples ($y_i = -1$) are on or below the negative margin hyperplane. A few tweaks allow us to write the two constraints as one. We show this by transforming the second constraint, in which case $y_i = -1$:\n\n\\begin{align}\n \\beta_0 + \\mathbf{\\beta}^T \\mathbf{x}_i &\\leq -1 \\\\\n \\Leftrightarrow \\qquad y_i (\\beta_0 + \\mathbf{\\beta}^T \\mathbf{x}_i) &\\geq (-1)y_i \\\\\n \\Leftrightarrow \\qquad y_i (\\beta_0 + \\mathbf{\\beta}^T \\mathbf{x}_i) &\\geq 1\n\\end{align}\n\nThe same can be done for the first constraint - it will yield the same expression. Therefore, our maximization problem can be restated in a slightly simpler form:\n\n\\begin{equation}\n\\begin{aligned}\n& \\underset{\\beta_0, \\beta_1, \\ldots, \\beta_p}{\\text{maximize}}\n& & \\frac{2}{\\Vert \\mathbf{\\beta} \\Vert} \\\\\n& \\text{subject to} & & y_i(\\beta_0 + \\mathbf{\\beta}^T \\mathbf{x}_{i}) \\geq 1 \\quad \\text{for } i = 1, \\ldots, N.\n\\end{aligned}\n\\end{equation}\n\nThis is a convex optimization problem (quadratic criterion with linear inequality constraints) and can be solved with Lagrange. For details refer to appendix (D1) of the script.\n\nNote that in practice it is easier to minimize the reciprocal term of the squared norm of $\\mathbf{\\beta}$, $\\frac{1}{2} \\Vert\\mathbf{\\beta} \\Vert^2$. Therefore the objective function is often given as\n\n\\begin{equation}\n\\begin{aligned}\n& \\underset{\\beta_0, \\beta}{\\text{minimize}}\n& & \\frac{1}{2}\\Vert \\mathbf{\\beta} \\Vert^2 \\\\\n& \\text{subject to} & & y_i(\\beta_0 + \\mathbf{\\beta}^T \\mathbf{x}_{i}) \\geq 1 \\quad \\text{for } i = 1, \\ldots, N.\n\\end{aligned}\n\\end{equation}\n\nThis transformation does not change the optimization problem yet at the same time is computationally easier to be handled by quadratic programming. A detailed discussion of quadratic programming goes beyond the scope of this course. For details, see e.g. Vapnik (2000) or [Burges (1998)](http://www.cmap.polytechnique.fr/~mallat/papiers/svmtutorial.pdf).**\n\n## Support Vector Classifier\n\n### Non-Separable Data\n\nGiven our data is separable into two classes, the maximal margin classifier from before seems like a natural approach. However, it is easy to see that **when the data is not clearly discriminable, no separable hyperplane exists and therefore such a classifier does not exist**. In that case the above maximization problem has no solution. What makes the situation even more complicated is that the maximal margin classifier is very sensitive to changes in the support vectors. This means that this classifier might suffer from inappropriate sensitivity to individual observations and thus it has a substantial risk of overfitting the training data. That is why we might be willing to consider a classifier on a hyperplane that does not perfectly separate the two classes but allows for greater robustness to individual observations and better classification of most of the training observations. In other words it could be worthwhile to misclassify a few training observations in order to do a better job in classifying the test data (James et al. (2013)). \n\n### Details of the Support Vector Classifier\n\nThis is where the Support Vector Classifier (SVC) comes into play. It allows a certain number of observations to be on the 'wrong' side of the hyperplane while seeking a solution where the majority of data points are still on the 'correct' side of the hyperplane. The following figure visualizes this.\n\n\n\nThe SVC still classifies a test observation based on which side of a hyperplane it lies. However, when we train the model, the margins are now somewhat softened. This means that the model allows for a limited number of training observations to be on the wrong side of the margin and hyperplane, respectively. \n\nLet us briefly discuss in general terms how the support vector classifier reaches its optimal solution. For this we extend the optimization problem from the maximum margin classifier as follows: \n\n\\begin{equation}\n\\begin{aligned}\n& \\underset{\\beta_0, \\beta}{\\text{minimize}}\n& & \\frac{1}{2}\\Vert \\mathbf{\\beta} \\Vert^2 + C \\left(\\sum_{i=1}^n \\epsilon_i \\right) \\\\\n& \\text{subject to} & & \\beta_0 + \\mathbf{\\beta}^T \\mathbf{x}_{i} \\geq (1-\\epsilon_i) \\quad \\text{for } i = 1, \\ldots, N. \\\\\n& & & \\epsilon_i \\geq 0 \\quad \\forall i\n\\end{aligned}\n\\end{equation}\n\nThis, again, can be solved with Lagrange similar to the way it is shown for the maximum margin classifier (see appendix (D1)) and it is left to the reader as an exercise to derive the Lagrange (primal and dual) objective function. For the impatient readers will find a solution draft in Friedman et al. (2001), section 12.2.1.\n\nLet us now focus on the added term $C \\left(\\sum_{i=1}^n \\epsilon_i \\right)$. Here, $\\epsilon_1, \\epsilon_2, \\ldots, \\epsilon_n$ are slack variables that allow the individual observations to be on the wrong side of the margin or the hyperplane. They contain information on where the $i$th observation is located, relative to the hyperplane and relative to the margin. \n\n* If $\\epsilon_i = 0$ then the $i$th observation is on the correct side of the margin, \n* if $1 \\geq \\epsilon_i > 0$ it is on the wrong side of the margin but correct side of the hyperplane, and \n* if $\\epsilon_i > 1$ it is on the wrong side of the hyperplane. \n\nThe tuning parameter $C$ can be interpreted as a penalty factor for misclassification. It is defined by the user. Large values of $C$ correspond to a significant error penalty, whereas small values are used if we are less strict about misclassification errors. By controlling for $C$ we indirectly control for the margin and therefore actively tune the bias-variance trade-off. Decreasing the value of $C$ increases the bias but lowers the variance of the model. \n\nBelow figure shows how $C$ impacts the decision boundary and its corresponding margin.\n\n\n\n### Solving Nonlinear Problems\n\nSo far we worked with data that is linearly separable. What makes SVM so powerful and popular is that it can be kernelized to solve nonlinear classification problems. We start our discussion again with illustrations to build an intuition.\n\n\n\nClearly the data is not linear and the resulting (linear) decision boundary is useless. How, then, do we deal with this? With mapping functions. The basic idea is to project the data via some mapping function $\\phi$ onto a higher dimension such that a linear separator would be sufficient. The idea is similar to using quadratic and cubic terms of the predictor in linear regression in order to address non-linearity $(y = \\beta_0 + \\beta_1 x_i + \\beta_2 x_i^2 + \\beta_3 x_i^3 + \\ldots)$ . For example, for the data in the preceding figure we could use the following mapping function $\\phi: \\mathbb{R}^2 \\rightarrow \\mathbb{R}^3$.\n\n\\begin{equation}\n\\phi(x_1, x_2) = (z_1, z_2, z_3) = \\left(x_1, x_2, x_1^2 + x_2^2 \\right)\n\\end{equation}\n\n\n\nHere we enlarge our feature space from $\\mathbb{R}^2 \\rightarrow \\mathbb{R}^3$ in oder to accommodate a non-linear boundary. The transformed data becomes trivially linearly separable. All we have to do is find a plane in $\\mathbb{R}^3$. If we project this decision boundary back onto the original feature space $\\mathbb{R}^2$ (with $\\phi^{-1}$), we have a nonlinear decision boundary. \n\n\n\nHere's an animated visualization of this concept.\n\n\n```python\nfrom IPython.display import YouTubeVideo\nYouTubeVideo('3liCbRZPrZA')\n```\n\n\n\n\n\n\n\n\n\n\n### The Problem with Mapping Functions\nOne could think that this is the recipe to work with nonlinear data: Transform all training data onto a higher-dimensional feature space via some mapping function $\\phi$ train a linear SVM model and use the same function $\\phi$ to transform new (test) data to classify it. \n\nAs attractive as this idea seems, it is unfortunately unfeasible because it quickly becomes computationally very expensive. Here is a hands-on example why: Consider for example a degree-2 polynomial (kernel) transformation of the form $\\phi(x_1, x_2) = (x_1^2, x_2^2, \\sqrt{2} x_1 x_2, \\sqrt{2c} x_1, \\sqrt{2c} x_2, c)$. This means that for a dataset in $\\mathbb{R}^2$ the transformation adds four additional dimensions ($\\mathbb{R}^2 \\rightarrow \\mathbb{R}^6$). If we generalize this, it means that a $d$-dimensional polynomial (Kernel) transformation maps from $\\mathbb{R}^p$ to an ${p + d}\\choose{d}$-dimensional space [(Balcan (2011))](http://www.cs.cmu.edu/%7Eninamf/ML11/lect1020.pdf). Thus for datasets with $p$ large, naively performing such transformations will force most computers to its knees. \n\n### The Kernel Trick\n\nThankfully, not all is lost. It turns out that one does not need to explicitly work in the higher-dimensional space. One can show that when using Lagrange to solve our optimization problem, the training samples are only used to compute the pair-wise dot products $\\langle x_i, x_{j}\\rangle$ (where $x_i, x_{j} \\in \\mathbb{R}^{p}$). This is significant because there exist functions that, given two vectors $x_i$ and $x_{j}$ in $\\mathbb{R}^p$, implicitly compute the dot product between the two vectors in a higher-dimension $\\mathbb{R}^q$ (with $q > p$) without explicitly transforming $x_i, x_{j}$ onto a higher dimension $\\mathbb{R}^q$. Such functions are called **Kernel** functions, written $K(x_i, x_{j})$ [(Kim (2013))](http://www.eric-kim.net/eric-kim-net/posts/1/kernel_trick.html#[6]). \n\nLet us show an example of such a Kernel function (following [Hofmann (2006)](http://www.cogsys.wiai.uni-bamberg.de/teaching/ss06/hs_svm/slides/SVM_Seminarbericht_Hofmann.pdf)). For ease of reading we use $x = (x_1, x_2)$ and $z=(z_1, z_2)$ instead of $x_i$ and $x_{j}$. Consider the Kernel function $K(x, z) = (x^T z)^2$ and the mapping function $\\phi(x) = (x_1^2, \\sqrt{2}x_1 x_2, x_2^2)$. If we were to solve our optimization problem from above with Lagrange, the mapping function appears in the form $\\phi(x)^T \\phi(z)$.\n\n\\begin{align}\n\\phi(x)^T \\phi(z) &= (x_1^2, \\sqrt{2}x_1 x_2, x_2^2)^T (z_1^2, \\sqrt{2}z_1 z_2, z_2^2) \\\\\n &= x_1^2 z_1^2 + 2x_1 z_1 x_2 z_2 + x_2^2 z_2^2 \\\\\n &= (x_1 z_1 + x_2 z_2)^2 \\\\\n &= (x^T z)^2 \\\\\n &= K(x, z)\n\\end{align}\n\nThe mapping function would have transformed the data from $\\mathbb{R}^2 \\rightarrow \\mathbb{R}^3$ and back. The Kernel function, however, stays in $\\mathbb{R}^2$. This is of course only one (toy) example and far away from a proper proof but it provides the intuition of what can be generalized: that by using a Kernel function where $K(x_i, x_j) = (x^T z)^2 = \\phi(x_i)^T \\phi(x_j)$, we implicitly transforms our data to a higher-dimension without having to explicitly apply a mapping function $\\phi$. This so called \"Kernel Trick\" allows us to efficiently learn nonlinear decision boundaries for SVM. \n\n### Popular Kernel Functions\nNot every random mapping function is also a Kernel function. For a function to be a Kernel function, it needs to have certain properties (see e.g. [Balcan (2011)](http://www.cogsys.wiai.uni-bamberg.de/teaching/ss06/hs_svm/slides/SVM_Seminarbericht_Hofmann.pdf) or [Hofmann (2006)](http://www.cogsys.wiai.uni-bamberg.de/teaching/ss06/hs_svm/slides/SVM_Seminarbericht_Hofmann.pdf) for a discussion). In SVM literature, the following three Kernel functions have emerged as popular choices (Friedman et al. (2001)):\n\n\\begin{align}\nd\\text{th-Degree polynomial} \\qquad K(x_i, x_j) &= (r + \\gamma \\langle x_i, x_j \\rangle)^d \\\\\n\\text{Radial Basis (RBF)} \\qquad K(x_i, x_j) &= \\exp(-\\gamma \\Vert x_i - x_j \\Vert^2) \\\\\n\\text{Sigmoid} \\qquad K(x_i, x_j) &= \\tanh(\\gamma \\langle x_i, x_j \\rangle + r)\n\\end{align}\n\nIn general there is no \"best choice\". With each Kernel having some degree of variability, one has to find the optimal solution by experimenting with different Kernels and playing with their parameter ($\\gamma, r, d$). \n\n### Optimization with Lagrange\n\nWe have mentioned before that the optimization problem of the maximum margin classifier and support vector classifier can be solved with Lagrange. The details of which are beyond the scope of this notebook. However, the interested reader is encouraged to learn the details in the appendix of the script (and the recommended reference sources) as these are crucial in understanding the mathematics/core of SVM and the application of Kernel functions.\n\n## SVM with Scikit-Learn\n### Preparing the Data\n\nHaving build an intuition of how SVM work, let us now see this algorithm applied in Python. We will again use the Scikit-learn package that has an optimized class implemented. The data we will work with is called \"Polish Companies Bankruptcy Data Set\" and was used in Zieba et al. (2014). The full set comprises five data files. Each file contains 64 features plus a class label. The features are ratios derived from the financial statements of the more than 10'000 manufacturing companies considered during the period of 2000 - 2013 (from EBITDA margin to equity ratio to liquidity ratios (quick ratio etc.)). The five files differ in that the first contains data with companies that defaulted/were still running **five** years down the road ('1year.csv'), the second **four** years down the road ('2year.csv') etc. Details can be found in the original publication (Zikeba et al. (2016)) or in the [description provided on the UCI Machine Learning Repository site](https://archive.ics.uci.edu/ml/datasets/Polish+companies+bankruptcy+data) where the data was downloaded from. For our purposes we will use the '5year.csv' file where we should predict defaults within the next year. \n\n\n```python\n%matplotlib inline\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nplt.style.use('seaborn-whitegrid')\nplt.rcParams['font.size'] = 14\n```\n\n\n```python\n# Load data\ndf = pd.read_csv('Data/5year.csv', sep=',')\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
Attr1Attr2Attr3Attr4Attr5Attr6Attr7Attr8Attr9Attr10...Attr56Attr57Attr58Attr59Attr60Attr61Attr62Attr63Attr64class
00.0882380.554720.011341.0205-66.52000.3420400.1094900.577521.08810.32036...0.0809550.2754300.919050.0020247.27114.7343142.7602.55683.25970
1-0.0062020.484650.232981.59986.18250.000000-0.0062021.063401.27570.51535...-0.028591-0.0120351.004700.1522206.09113.2749111.1403.28413.37000
20.1302400.221420.577513.6082120.04000.1876400.1621203.059001.14150.67731...0.1239600.1922900.876040.0000008.79342.987071.5315.10275.61880
3-0.0899510.887000.269271.5222-55.9920-0.073957-0.0899510.127401.27540.11300...0.418840-0.7960200.590742.8787007.65243.3302147.5602.47355.92990
40.0481790.550410.107651.2437-22.95900.0000000.0592800.816821.51500.44959...0.2404000.1071600.770480.13938010.11804.0950106.4303.42943.36220
\n

5 rows × 65 columns

\n
\n\n\n\n\n```python\n# Check for NA values\ndf.isnull().sum()\n```\n\n\n\n\n Attr1 3\n Attr2 3\n Attr3 3\n Attr4 21\n Attr5 11\n Attr6 3\n Attr7 3\n Attr8 18\n Attr9 1\n Attr10 3\n Attr11 3\n Attr12 21\n Attr13 0\n Attr14 3\n Attr15 6\n Attr16 18\n Attr17 18\n Attr18 3\n Attr19 0\n Attr20 0\n Attr21 103\n Attr22 3\n Attr23 0\n Attr24 135\n Attr25 3\n Attr26 18\n Attr27 391\n Attr28 107\n Attr29 3\n Attr30 0\n ... \n Attr36 3\n Attr37 2548\n Attr38 3\n Attr39 0\n Attr40 21\n Attr41 84\n Attr42 0\n Attr43 0\n Attr44 0\n Attr45 268\n Attr46 21\n Attr47 35\n Attr48 3\n Attr49 0\n Attr50 18\n Attr51 3\n Attr52 36\n Attr53 107\n Attr54 107\n Attr55 0\n Attr56 0\n Attr57 3\n Attr58 0\n Attr59 3\n Attr60 268\n Attr61 15\n Attr62 0\n Attr63 21\n Attr64 107\n class 0\n Length: 65, dtype: int64\n\n\n\n\n```python\n# Calculate % of missing values for 'Attr37'\ndf['Attr37'].isnull().sum() / (len(df))\n```\n\n\n\n\n 0.43113367174280881\n\n\n\nAttribute 37 sticks out with 2'548 of 5'910 (43.1%) missing values. This attribute considers *\"(current assets - inventories) / long-term liabilities\"*. Due to the many missing values we can not use a fill method so let us drop this feature column. \n\n\n```python\ndf = df.drop('Attr37', axis=1)\ndf.iloc[:, 30:38].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
Attr31Attr32Attr33Attr34Attr35Attr36Attr38Attr39
00.077287155.3302.34980.243770.1352301.44930.321010.095457
10.000778108.0503.37792.70750-0.0364751.27570.59380-0.028591
20.14349081.6534.47010.658780.1458601.16980.677310.129100
3-0.138650253.9101.43750.835670.0140271.27540.438300.010998
40.039129140.1202.65832.133600.3642001.51500.512250.240400
\n
\n\n\n\nAs for the other missing values we are left to decide whether we want to remove the corresponding observations (rows) or apply a filling method. The problem with dropping all rows with missing values is that we might lose a lot of valuable information. Therefore in this case we prefer to use a common interpolation technique and impute `NaN` values with the feature mean. Alternatively we could use '`median`' or '`most_frequent`' as strategy. A convenient way to achieve this imputation is to use the `Imputer` class from `sklearn`.\n\n\n```python\nfrom sklearn.preprocessing import Imputer\n\n# Impute missing values by mean (axis=0 --> along columns)\nipr = Imputer(missing_values='NaN', strategy='mean', axis=0)\nipr = ipr.fit(df.values)\nimputed_data = ipr.transform(df.values)\n\n# Assign imputed values to 'df' and check for 'NaN' values\ndf = pd.DataFrame(imputed_data, columns=df.columns)\ndf.isnull().sum().sum()\n```\n\n\n\n\n 0\n\n\n\nNow let us check if we have some categorical features that we need to transform. For this we compare the number of cells in the dataframe with the sum of numeric values (`np.isreal()`). If the result is 0, we do not need to apply a One-Hot-Encoding or LabelEncoding procedure. \n\n\n```python\ndf.shape[0] * df.shape[1] - df.applymap(np.isreal).sum().sum()\n```\n\n\n\n\n 0\n\n\n\nAs we see, the dataframe only consists of real values. Therefore, we can proceed by assigning columns 1-63 to variable `X` and column 64 to `y`.\n\n\n```python\nX = df.iloc[:, :-1].values\ny = df.iloc[:, -1].values\n```\n\n### Applying SVM\n\nHaving assigned the data to `X` and `y` we are now ready to divide the dataset into separate training and test sets.\n\n\n```python\nfrom sklearn.model_selection import train_test_split\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, \n test_size=0.2, \n random_state=0, \n stratify=y)\n```\n\nUnlike e.g. decision tree algorithms SVM are sensitive to the magnitude the data. Therefore scaling our data is recommended. \n\n\n```python\nfrom sklearn.preprocessing import StandardScaler\n\n# Create StandardScaler object\nsc = StandardScaler()\n\n# Standardize features; equal results as if done in two\n# separate steps (first .fit() and then .transform())\nX_train_std = sc.fit_transform(X_train)\n\n# Transform test set\nX_test_std = sc.transform(X_test)\n```\n\nWith the data standardized, we can finally apply a SVM on the data. We import the `SVC` (for Support Vector Classifier) from the Scikit-learn toolbox and create a `svm_linear` object that represents a linear SVM with `C=0`. Recall that `C` helps us control the penalty for misclassification. Large values of `C` correspond to large error penalties and vice-versa. More parameter can be specified. Details are best explained in the function's [documentation page](http://scikit-learn.org/stable/modules/generated/sklearn.svm.SVC.html).\n\n\n```python\nfrom sklearn.svm import SVC\nfrom sklearn import metrics\nimport matplotlib.pyplot as plt\n\n# Create object\nsvm_linear = SVC(kernel='linear', C=1.0)\nsvm_linear\n```\n\n\n\n\n SVC(C=1.0, cache_size=200, class_weight=None, coef0=0.0,\n decision_function_shape='ovr', degree=3, gamma='auto', kernel='linear',\n max_iter=-1, probability=False, random_state=None, shrinking=True,\n tol=0.001, verbose=False)\n\n\n\nWith the `svm_linear` object ready we can now fit the object to the training data and check for the model's accuracy.\n\n\n```python\n# Fit linear SVM to standardized training set\nsvm_linear.fit(X_train_std, y_train)\n\n# Print results\nprint(\"Observed probability of default: {:.2f}\".format(np.count_nonzero(y==0) / len(y)))\nprint(\"Train score: {:.2f}\".format(svm_linear.score(X_train_std, y_train)))\nprint(\"Test score: {:.2f}\".format(svm_linear.score(X_test_std, y_test)))\n```\n\n Observed probability of default: 0.93\n Train score: 0.93\n Test score: 0.93\n\n\n\n```python\n# Predict classes\ny_pred = svm_linear.predict(X_test_std)\n\n# Manual confusion matrix as pandas DataFrame\nconfm = pd.DataFrame({'Predicted': y_pred,\n 'True': y_test})\nconfm.replace(to_replace={0:'Non-Default', 1:'Default'}, inplace=True)\nprint(confm.groupby(['True','Predicted'], sort=False).size().unstack('Predicted'))\n```\n\n Predicted Non-Default Default\n True \n Non-Default 1096.0 4.0\n Default 82.0 NaN\n\n\nIn the same way we can run a Kernel SVM on the data. We have four Kernel options: one linear as introduced above and three non-linear. All of them have hyperparameter available. If these are not specified, default values are taken. [Check the documentation for details](http://scikit-learn.org/stable/modules/generated/sklearn.svm.SVC.html).\n\n* `linear`: linear SVM as shown above with `C` as hyperparameter\n* `rbf`: Radial basis function Kernel with `C, gamma` as hyperparameter\n* `poly`: Polynomial Kernel with `C, degree, gamma, coef0` as hyperparameter\n* `sigmoid`: Sigmoid Kernel with `C, gamma, coef0` as hyperparameter\n\nLet us apply a polynomial Kernel as example.\n\n\n```python\nsvm_poly = SVC(kernel='poly', random_state=1)\nsvm_poly\n```\n\n\n\n\n SVC(C=1.0, cache_size=200, class_weight=None, coef0=0.0,\n decision_function_shape='ovr', degree=3, gamma='auto', kernel='poly',\n max_iter=-1, probability=False, random_state=1, shrinking=True,\n tol=0.001, verbose=False)\n\n\n\nNot having specified hyperparameter `C, degree, gamma`, and `coef0` we see that the algorithm has taken default values. For `C` it is equal to 1, default `degree` is 3, `gamma=auto` means that the value will be calculated as $1/n_{\\text{features}}$, and `coef0` is set to 0 as default. \n\n\n```python\n# Fit polynomial SVM to standardized training set\nsvm_poly.fit(X_train_std, y_train)\n\n# Print results\nprint(\"Observed probability of default: {:.2f}\".format(np.count_nonzero(y==0) / len(y)))\nprint(\"Train score: {:.2f}\".format(svm_poly.score(X_train_std, y_train)))\nprint(\"Test score: {:.2f}\".format(svm_poly.score(X_test_std, y_test)))\n```\n\n Observed probability of default: 0.93\n Train score: 0.94\n Test score: 0.93\n\n\n\n```python\n# Predict classes\ny_pred = svm_poly.predict(X_test_std)\n\n# Manual confusion matrix as pandas DataFrame\nconfm = pd.DataFrame({'Predicted': y_pred,\n 'True': y_test})\nconfm.replace(to_replace={0:'Non-Default', 1:'Default'}, inplace=True)\nprint(confm.groupby(['True','Predicted'], sort=False).size().unstack('Predicted'))\n```\n\n Predicted Non-Default Default\n True \n Non-Default 1096 4\n Default 81 1\n\n\nAs it looks linear and polynomial SVM yield similar results. What is clearly unsatisfactory is the number of true defaults that the SVM missed to detect. Both linear as well as non linear SVM miss to label $\\geq$ 80 defaults [sic]. From a financial perspective, this is unacceptable and raises questions regarding\n* Class imbalance\n* Hyperparameter fine-tuning through cross validation and grid search\n* Feature selection\n* Noise & dimension reduction\n\nwhich we want to address in the next section.\n\n## Dealing with Class Imbalance\n\nWhen we deal with default data sets we observe that the ratio of non-default to default records is heavily skewed towards non-default. This is a common problem in real-world data set: Samples from one class or multiple classes are over-represented. For the present data set we are talking 93% non-defaults vs. 7% defaults. Having an algorithm that predicts non-default 100 out of a 100 times is right in 93% of the cases. Therefore, training a model on such a data set that achieves the same 93% test accuracy (as our SVM above) means nothing else than our model hasn't learned anything informative from the features provided in this data set. Thus, when assessing a classifier on an imbalanced data set we have learned that other metrics such as precision, recall, ROC curve etc. might be more informative. \n\nHaving said that, what we have to consider is that a class imbalance might influences a learning algorithm during the model fitting itself. Machine learning algorithms typically optimize a reward or cost function. This means that an algorithm implicitly learns the model that optimizes the predictions based on the most abundant class in the dataset in order to minimize the cost or maximize the reward during the training phase. And this in turn might yield skewed results in case of imbalanced data sets.\n\nThere are several options to deal with class imbalance, we will discuss two of them. The first option is to set the `class_weight` parameter to `class_weight='balanced'`. Most classifier hae this option implemented (of the introduced classifiers, KNN, LDA and QDA lack such a parameter). This will assign a larger penalty to wrong predictions on the minority class.\n\n\n```python\n# Initiate and fit a polynomial SVM to training set\nsvm_poly = SVC(kernel='poly', random_state=1, class_weight='balanced')\nsvm_poly.fit(X_train_std, y_train)\n\n# Predict classes and print results\ny_pred = svm_poly.predict(X_test_std)\nprint(metrics.classification_report(y_test, y_pred))\nprint(metrics.confusion_matrix(y_test, y_pred))\nprint(\"Test score: {:.2f}\".format(svm_poly.score(X_test_std, y_test)))\n```\n\n precision recall f1-score support\n \n 0.0 0.93 0.99 0.96 1100\n 1.0 0.12 0.02 0.04 82\n \n avg / total 0.88 0.92 0.89 1182\n \n [[1086 14]\n [ 80 2]]\n Test score: 0.92\n\n\nThe second option we want to discuss is up- & downsampling of the minority/majority class. Both up- and downsampling are implemented in Scikit-learn through the `resample` function and depending on the data and given the task at hand, one might be better suited than the other. For the upsampling, scikit-learn will apply a bootstrapping to draw new samples from the datasets with replacement. This means that the function will repeatedly draw new samples from the minority class until it contains the number of samples we define. Here's a code example:\n\n\n```python\nfrom sklearn.utils import resample\n\n# Upsampling\nX_upsampled, y_upsampled = resample(X[y==1], y[y==1],\n replace=True,\n n_samples=X[y==0].shape[0],\n random_state=1)\nprint('No. of default samples BEFORE upsampling: {:.0f}'.format(y.sum()))\nprint('No. of default samples AFTER upsampling: {:.0f}'.format(y_upsampled.sum()))\n```\n\n No. of default samples BEFORE upsampling: 410\n No. of default samples AFTER upsampling: 5500\n\n\nDownsampling works in similar fashion. \n\n\n```python\n# Downsampling\nX_dnsampled, y_dnsampled = resample(X[y==0], y[y==0],\n replace=False,\n n_samples=X[y==1].shape[0],\n random_state=1)\n```\n\nRunning the SVM algorighm on the balanced dataset works now as you would expect:\n\n\n```python\n# Combine datasets\nX_bal = np.vstack((X[y==1], X_dnsampled))\ny_bal = np.hstack((y[y==1], y_dnsampled))\n\n# Train test split\nX_train_bal, X_test_bal, y_train_bal, y_test_bal = \\\n train_test_split(X_bal, y_bal, \n test_size=0.2, \n random_state=0, \n stratify=y_bal)\n \n# Standardize features; equal results as if done in two\n# separate steps (first .fit() and then .transform())\nX_train_bal_std = sc.fit_transform(X_train_bal)\n\n# Transform test set\nX_test_bal_std = sc.transform(X_test_bal)\n\n# Initiate and fit a polynomial SVM to training set\nsvm_poly_bal = SVC(kernel='poly', random_state=1)\nsvm_poly_bal.fit(X_train_bal_std, y_train_bal)\n\n\n# Predict classes and print results\ny_pred_bal = svm_poly_bal.predict(X_test_bal_std)\nprint(metrics.classification_report(y_test_bal, y_pred_bal))\nprint(metrics.confusion_matrix(y_test_bal, y_pred_bal))\nprint(\"Test score: {:.2f}\".format(svm_poly_bal.score(X_test_bal_std, y_test_bal)))\n```\n\n precision recall f1-score support\n \n 0.0 0.51 1.00 0.68 82\n 1.0 1.00 0.05 0.09 82\n \n avg / total 0.76 0.52 0.39 164\n \n [[82 0]\n [78 4]]\n Test score: 0.52\n\n\nBy applying a SVM to a balanced set of data we improve our model slightly. Yet there remains some work to be done. The polynomial SVM still misses out on 95.1% (=78/82) of the default cases. \n\nIt should be said that in general using an upsampled set is to be preferred over a downsampled set. However, here we are talking 11'000 observations times 63 features for the upsampled set and this can easily take quite some time to run models on, especially if we compute a grid search as in the next section. For this reason the downsampled set was used.\n\n## Hyperparameter Fine-Tuning\n### Pipelines\n\nAnother tool that is of help in optimizing our model is the `GridSearchCV` function introduced in the previous chapter that finds the best hyperparameter through a brute-force (cross validation) approach. Yet before we simply copy-past the code from the last chapter we ought to address a subtle yet important difference between the decision tree and SVM (or most other ML) algorithms that has implications on the application: Decision tree algorithms are of the few models where data scaling is not necessary. SVM on the other hand are (as most ML algorithms) fairly sensitive to the magnitude of the data. Now you might say that this is precisely why we standardized the data at the very beginning and with that we are good to go. In principle, this is correct. However, if we are precise, we commit a subtle yet possibly significant thought error. \n\nIf we decide to apply a grid search using cross validation to find the optimal hyperparameter for e.g. a SVM we unfortunately can not just scale the full data set at the very beginning and then be good for the rest of the process. Conceptually it is important to understand why. Assume we have a data set. As we learned in the chapter on feature scaling and cross validation, applying a scaling on the combined data set and splitting the set into training and holdout set after the scaling is wrong. The reason is that information from the test set found its way into the model and distorts the results. The training set is scaled with not only based on information from that set but also based on information from the test set. \n\nNow the same is true if we apply a gridsearch process with cross validation on a training set. For each fold in the CV, some part of the training set will be declared as the training part, and some the test part. The test part within this split is used to measure the performance of our model trained on the training part. However, if we simply scale the training set and then apply gridsearch-CV on the scaled training set we would commit the same thought error as if we simply scale the full set at the very beginning. The test fold (of the CV split) would no longer be independent but implicitly already be part of the training set we used to fit the model. This is fundamentally different from how new data looks to the model. The test data within each cross validation split would no longer correctly mirrors how new data would look to the modeling process. Information already leaked from the test data into our modeling process. This would lead to overly optimistic results during cross validation, and possibly the selection of suboptimal parameter (Müller & Guido (2017)).\n\nWe have not addressed this problem in the chapter on cross validation because so far we have not introduced the tool to deal with it. Furthermore, if our data set is homogeneous and of some size, this is less of an issue. Yet as Scikit-learn provides a fantastic tool to deal with this (and many other) issue(s), we want to introduce it here. The tool is called **pipelines** and allows to combine multiple processing steps in a very convenient and proper way. Let us look at how we can use the `Pipeline` class to express the end-to-end workflow. First we build a pipeline object. This object is provided a list of steps. Each step is a tuple containing a name (you define) and an instance of an estimator. \n\n\n```python\nfrom sklearn.pipeline import Pipeline\n\n# Create pipeline object with standard scaler and SVC estimator\npipe = Pipeline([('scaler', StandardScaler()), \n ('svm_poly', SVC(kernel='poly', random_state=0))])\n```\n\nNext we define a parameter grid to search over and construct a `GridSearchCV` from the pipeline and the parameter grid. Notice that we have to specify for each parameter which step of the pipeline it belongs to. This is done by calling the name we gave this step, followed by a double underscore and the parameter name. For the present example, let us compare different degrees, and `C` values.\n\n\n```python\n# Define parameter grid\nparam_grid = {'svm_poly__C': [0.1, 1, 10, 100],\n 'svm_poly__degree': [1, 2, 3, 5, 7]}\n```\n\nWith that we can run a `GridSearchCV` as usual.\n\n\n```python\nfrom sklearn.model_selection import GridSearchCV\n\n# Run grid search\ngrid = GridSearchCV(pipe, param_grid=param_grid, cv=5, n_jobs=-1)\ngrid.fit(X_train_bal, y_train_bal)\n\n# Print results\nprint('Best CV accuracy: {:.2f}'.format(grid.best_score_))\nprint('Test score: {:.2f}'.format(grid.score(X_test_bal, y_test_bal)))\nprint('Best parameters: {}'.format(grid.best_params_))\n```\n\n Best CV accuracy: 0.73\n Test score: 0.78\n Best parameters: {'svm_poly__C': 100, 'svm_poly__degree': 1}\n\n\nNotice that thanks to the pipeline object, now for each split in the cross validation the `StandardScaler` is refit with only the training splits and no information is leaked from the test split into the parameter search. \n\nDepending on the grid you search, computations might take quite some time. One way to improve speed is by reducing the feature space; that is reducing the number of features. We will discuss feature selection and dimension reduction options in the next section but for the moment, let us just apply a method called Principal Component Analysis (PCA). PCA effectively transforms the feature space from $\\mathbb{R}^{p} \\rightarrow \\mathbb{R}^{q}$ with $q$ being a user specified value (but usually $q < < p$). PCA is similar to other preprocessing steps and can be included in pipelines as e.g. `StandardScaler`. \n\nHere we reduce the feature space from $\\mathbb{R}^{63}$ (i.e. $p=63$ features) to $\\mathbb{R}^{2}$. This will make the fitting process faster. However, this comes at a cost: by reducing the feature space we might not only get rid of noise but also lose part of the information available in the full dataset. Our model accuracy might suffer as a consequence. Furthermore, the speed that we gain by fitting a model to a smaller subset can be set off by the additional computations it takes to calculate the PCA. In the example of the upsampled data set we would be talking of an $[11'000 \\cdot 0.8 \\cdot 0.8 \\times 63]$ matrix (0.8 for the train/test-split and each cv fold) for which eigenvector and eigenvalues need to be calculated. This means up to 63 eigenvalues per grid search loop. \n\n\n```python\nfrom sklearn.decomposition import PCA\n\n# Create pipeline object with standard scaler, PCA and SVC estimator\npipe = Pipeline([('scaler', StandardScaler()), \n ('pca', PCA(n_components=2)),\n ('svm_poly', SVC(kernel='poly', random_state=0))])\n\n# Define parameter grid\nparam_grid = {'svm_poly__C': [100],\n 'svm_poly__degree': [1, 2, 3]}\n\n# Run grid search\ngrid = GridSearchCV(pipe, param_grid=param_grid, cv=5, n_jobs=-1)\ngrid.fit(X_train_bal, y_train_bal)\n\n# Print results\nprint('Best CV accuracy: {:.2f}'.format(grid.best_score_))\nprint('Test score: {:.2f}'.format(grid.score(X_test_bal, y_test_bal)))\nprint('Best parameters: {}'.format(grid.best_params_))\n```\n\n Best CV accuracy: 0.64\n Test score: 0.74\n Best parameters: {'svm_poly__C': 100, 'svm_poly__degree': 2}\n\n\nOther so called preprocessing steps can be included in the pipeline too. This shows how seamless such workflows can be steered through pipelines. We can even combine multiple models as we show in the next code snippet. By now you are probably aware that trying all possible solutions is not a viable machine learning strategy. Computational power is certainly going to be an issue. Nevertheless, for the record we provide below an example where we apply logistic regression and a SVM with RBF kernel to find the best solution (details see section on PCA below). \n\n\n```python\nfrom sklearn.linear_model import LogisticRegression\n\n# Create pipeline object with standard scaler, PCA and SVC estimator\npipe = Pipeline([('scaler', StandardScaler()), \n ('classifier', SVC(random_state=0))])\n\n# Define parameter grid\nparam_grid = [{'scaler': [StandardScaler()],\n 'classifier': [SVC(kernel='rbf')],\n 'classifier__gamma': [1, 10],\n 'classifier__C': [10, 100]},\n {'scaler': [StandardScaler(), None],\n 'classifier': [LogisticRegression()],\n 'classifier__C': [10, 100]}]\n\n# Run grid search\ngrid = GridSearchCV(pipe, param_grid, cv=5, n_jobs=-1)\ngrid.fit(X_train_bal, y_train_bal)\n\n# Print results\nprint('Best CV accuracy: {:.2f}'.format(grid.best_score_))\nprint('Test score: {:.2f}'.format(grid.score(X_test_bal, y_test_bal)))\nprint('Best parameters: {}'.format(grid.best_params_))\n```\n\n Best CV accuracy: 0.76\n Test score: 0.79\n Best parameters: {'classifier': LogisticRegression(C=100, class_weight=None, dual=False, fit_intercept=True,\n intercept_scaling=1, max_iter=100, multi_class='ovr', n_jobs=1,\n penalty='l2', random_state=None, solver='liblinear', tol=0.0001,\n verbose=0, warm_start=False), 'classifier__C': 100, 'scaler': StandardScaler(copy=True, with_mean=True, with_std=True)}\n\n\nFrom the above output we see that surprisingly the Logistic regression yields the best accuracy (with `C=100`).\n\n## Feature Selection and Dimensionality Reduction\n### Complexity and the Curse of Overfitting\n\nIf we observe that a model performs much better on training than on test data, we have an indication that the model suffers from overfitting. The reason for the overfitting is most probably that our model is too complex for the given training data. Common solutions to reduce the generalization error are (Raschka (2015)):\n* Collect more (training) data\n* Introduce a penalty for complexity via regularization\n* Choose a simpler model with fewer parameter\n* Reduce the dimensionality of the data\n\nCollecting more data is self explanatory but often not applicable. Regularization via a complexity penalty term is a technique that is primarily applicable to regression settings (e.g. logistic regression). We will not discuss it here but the interested reader will easily find helpful information in e.g. James et al. (2013) chapter 6 or Raschka (2015) chapter 4. Here we will look at one commonly used solution to reduce overfitting: dimensionality reduction via feature selection. \n\n\n### Feature Selection\n\nA useful approach to select relevant features from a data set is to use information from the random forest algorithm we introduced in the previous chapter. There we elaborated how decision trees rank the feature importance based on a impurity decrease. Conveniently, we can access this feature importance rank directly from the `RandomForestClassifier` object. By executing below code - following the example in Raschka (2015) - we will train a random forest model on the balanced default data set (from before) and rank the features by their respective importance measure.\n\n\n```python\nfrom sklearn.ensemble import RandomForestClassifier\n\n# Extract feature labels\nfeat_labels = df.columns[:-1]\n\n# Create Random Forest object, fit data and\n# extract feature importance attributes\nforest = RandomForestClassifier(random_state=1)\nforest.fit(X_train_bal, y_train_bal)\nimportances = forest.feature_importances_\n```\n\n\n```python\n# Sort output (by relative importance) and \n# print top 15 features\nindices = np.argsort(importances)[::-1]\nn = 15\nfor i in range(n):\n print('{0:2d}) {1:7s} {2:6.4f}'.format(i + 1, \n feat_labels[indices[i]],\n importances[indices[i]]))\n```\n\n 1) Attr39 0.0811\n 2) Attr27 0.0684\n 3) Attr15 0.0471\n 4) Attr13 0.0447\n 5) Attr16 0.0421\n 6) Attr21 0.0355\n 7) Attr26 0.0339\n 8) Attr11 0.0310\n 9) Attr23 0.0303\n 10) Attr7 0.0292\n 11) Attr46 0.0251\n 12) Attr25 0.0228\n 13) Attr34 0.0212\n 14) Attr41 0.0201\n 15) Attr9 0.0185\n\n\nThe value in decimal is the relative importance for the respective feature. We can also plot this result to have a better overview. Below code shows one way of doing it.\n\n\n```python\n# Get cumsum of the n most important features\nfeat_imp = np.sort(importances)[::-1]\nsum_feat_imp = np.cumsum(feat_imp)[:n]\n```\n\n\n```python\n# Plot Feature Importance (both cumul., individual)\nplt.figure(figsize=(12, 8))\nplt.bar(range(n), importances[indices[:n]], align='center')\nplt.xticks(range(n), feat_labels[indices[:n]], rotation=90)\nplt.xlim([-1, n])\nplt.xlabel('Feature')\nplt.ylabel('Rel. Feature Importance')\nplt.step(range(n), sum_feat_imp, where='mid', \n label='Cumulative importance')\nplt.tight_layout();\n```\n\nExecuting the code will rank the different features according to their relative importance. The definition of each `AttrXX` we would have to [look up in the data description](https://archive.ics.uci.edu/ml/datasets/Polish+companies+bankruptcy+data). Note that the feature importance values are normalized such that they sum up to 1.\n\nFeature selection in the way shown in the preceding code snippets will not work in combination with a `pipeline` object. However, Scikit-learn has implemented such a function that could be used in a preprocessing step. Its name is `SelectFromModel` and details can be found [here](http://scikit-learn.org/stable/modules/feature_selection.html#feature-selection-using-selectfrommodel). Instead of selecting the top $n$ features you define a threshold, which selects those features whose importance is greater or equal to said threshold (e.g. mean, median etc.). For reference, below it is shown how the function is applied inside a pipeline.\n\n\n```python\nfrom sklearn.feature_selection import SelectFromModel\n\npipe = Pipeline([('feature_selection', SelectFromModel(RandomForestClassifier(), threshold='median')),\n ('scaler', StandardScaler()),\n ('classification', SVC())])\npipe.fit(X_train_bal, y_train_bal).score(X_test_bal, y_test_bal)\n```\n\n\n\n\n 0.78658536585365857\n\n\n\n### Principal Component Analysis\n\nIn the previous section you learned an approach for reducing the dimensionality of a data set through feature selection. An alternative to feature selection is feature extraction, of which Principal Component Analysis (PCA) is the best known and most popular approach. It is an unsupervised method that aims to summarize the information content of a data set by transforming it onto a new feature subspace of lower dimensionality than the original one. With the rise of big data, this is a field that is gaining importance by the day. PCA is widely used in a variety of field - e.g. in finance to de-noise signals in stock market trading, create factor models, for feature selection in bankruptcy prediction, dimensionality reduction of high frequency data etc.. Unfortunately, the scope of this course does not allow us to discuss PCA in great detail. Nevertheless the fundamentals shall be addressed here briefly so that the reader has a good understanding of how PCA helps in reducing dimensionality. \n\nTo build an intuition for PCA we quote the excellent James et al. (2013, p. 375): *\"PCA finds a low-dimensional representation of a dataset that contains as much as possible of the **variation**. The idea is that each of the $n$ observations lives in $p$-dimensional space, but not all of these dimensions are equally interesting. PCA seeks a small number of dimensions that are as interesting as possible, where the concept of interesting is measured by the amount that the observation vary along each dimension. Each of the dimensions found by PCA is a linear combination of the $p$ features.\"* Since each principal component is required to be orthogonal to all other principal components, we basically take correlated original variables (features) and replace them with a small set of principal components that capture their joint variation. \n\nBelow figures aim at visualizing the idea of principal components. In both figures we see the same two-dimensional dataset. PCA searches for the principal axis along which the data varies most. These principal axis measure the variance of the data when projected onto that axis. The two vectors (arrows) in the left plot visualize this. Notice that given an $[n \\times p]$ feature matrix $\\mathbf{X}$ there are at most $\\min(n-1, p)$ principal components. The figure on the right-hand side displays the projection of the data points projected onto the first principal axis. In this way we have reduced the dimensionality from $\\mathbf{R}^2$ to $\\mathbf{R}^1$. In practice, PCA is of course primarily used for datasets with $p$ large and the selected number of principal components $q$ is usually much smaller than the dimension of the original dataset ($q << p)$.\n\n\n\nThe first principal component is the direction in space along which (orthogonal) projections have the largest variance. The second principal component is the direction which maximizes variance among all directions while being orthogonal to the first. The $k^{\\text{th}}$ component is the variance-maximizing direction orthogonal to the previous $k-1$ components. \n\nHow do we express this in mathematical terms? Let $\\mathbf{X}$ be an $n \\times p$ dataset and let it be centered (i.e. each column mean is zero; notice that standardization is very important in PCA). The $p \\times p$ variance-covariance matrix $\\mathbf{C}$ is then equal to $\\mathbf{C} = \\frac{1}{n} \\mathbf{X}^T \\mathbf{X}$. Additionally, let $\\mathbf{\\phi}$ be a unit $p$-dimensional vector, i.e. $\\phi \\in \\mathbb{R}^p$ and let $\\sum_{i=1}^p \\phi_{i1}^2 = \\mathbf{\\phi}^T \\mathbf{\\phi} = 1$.\n\nThe projections of the individual data points onto the principal axis are given by the linear combination of the form \n\n\\begin{equation}\nZ_{i} = \\phi_{1i} X_{1} + \\phi_{2i} X_{2} + \\ldots + \\phi_{pi} X_{p}.\n\\end{equation}\n\nIn matrix notation we write\n\n\\begin{equation}\n\\mathbf{Z} = \\mathbf{X \\phi}\n\\end{equation}\n\nSince each column vector $X_i$ is standardized, i.e. $\\frac{1}{n} \\sum_{i=1}^n x_{ip} = 0$, the average of $Z_i$ (the column vector for feature $i$) will be zero as well. With that, the variance of $\\mathbf{Z}$ is \n\n\\begin{align}\n\\text{Var}(\\mathbf{Z}) &= \\frac{1}{n} (\\mathbf{X \\phi})^T (\\mathbf{X \\phi}) \\\\\n &= \\frac{1}{n} \\mathbf{\\phi}^T \\mathbf{X}^T \\mathbf{X \\phi} \\\\\n &= \\mathbf{\\phi}^T \\frac{\\mathbf{X}^T \\mathbf{X}}{n} \\mathbf{\\phi} \\\\\n &= \\mathbf{\\phi}^T \\mathbf{C} \\mathbf{\\phi}\n\\end{align}\n\nNote that it is common standard to use the population estimation of variance (division by $n$) instead of the sample variance (division by $n-1$). \n\nNow, PCA seeks to solve a sequence of optimization problems:\n\n\\begin{equation}\n\\begin{aligned}\n& \\underset{\\mathbf{\\phi}}{\\text{maximize}} & & \\text{Var}(\\mathbf{Z})\\\\\n& \\text{subject to} & & \\mathbf{\\phi}^T \\mathbf{\\phi}=1, \\quad \\phi \\in \\mathbb{R}^p \\\\\n&&& \\mathbf{Z}^T \\mathbf{Z} = \\mathbf{ZZ}^T = \\mathbf{I}.\n\\end{aligned}\n\\end{equation}\n\nLooking at the above term it should be clear why we haver restricted vector $\\mathbf{\\phi}$ to be a unit vector. If not, we could simply increase $\\mathbf{\\phi}$ - which is not what we want. This problem can be solved with Lagrange and via an eigen decomposition (a standard technique in linear algebra). The details of which are explained in the appendix of the script. \n\nHow we apply PCA within a pipeline workflow we have shown above. A more general setup is shown in below code snippet. We again make use of the polish bankruptcy set introduced above.\n\n\n```python\nfrom sklearn.decomposition import PCA\n\n# Define no. of PC\nq = 10\n\n# Create PCA object and fit to find \n# first q principal components\npca = PCA(n_components=q)\npca.fit(X_train_bal)\npca\n```\n\n\n\n\n PCA(copy=True, iterated_power='auto', n_components=10, random_state=None,\n svd_solver='auto', tol=0.0, whiten=False)\n\n\n\nTo close, one last code snippet is provided. Running it will visualize the cumulative explained variance ratio as a function of the number of components. (Mathematically, the explained variance ratio is the ratio of the eigenvalue of principal component $i$ to the sum of the eigenvalues, $\\frac{\\lambda_i}{\\sum_{i}^p \\lambda_i}$. See the appendix in the script to better understand the meaning of eigenvalues in this context.) In practice, this might be helpful in deciding on the number of principal components $q$ to use.\n\n\n```python\n# Run PCA for all possible PCs\npca = PCA().fit(X_train_bal)\n\n# Define max no. of PC\nq = X_train_bal.shape[1]\n\n# Get cumsum of the PC 1-q\nexpl_var = pca.explained_variance_ratio_\nsum_expl_var = np.cumsum(expl_var)[:q]\n```\n\n\n```python\n# Plot Feature Importance (both cumul., individual)\nplt.figure(figsize=(12, 6))\nplt.bar(range(1, q + 1), expl_var, align='center')\nplt.xticks(range(1, q + 1, 5))\nplt.xlim([0, q + 1])\nplt.xlabel('Principal Components')\nplt.ylabel('Explained Variance Ratio')\nplt.step(range(1, 1 + q), sum_expl_var, where='mid')\nplt.tight_layout();\n```\n\nThis shows us that the first 5 principal components explain basically all variation in the data. Therefore we could focus to work with only these. \n\n# Further Ressources\n\n\nIn writing this notebook, many ressources were consulted. For internet ressources the links are provided within the textflow above and will therefore not be listed again. Beyond these links, the following ressources were consulted and are recommended as further reading on the discussed topics:\n\n* Burges, Christopher J.C., 1998, A tutorial on support vector machines for pattern recognition, Data mining and knowledge discovery 2.2, 121-167.\n* Friedman, Jerome, Trevor Hastie, and Robert Tibshirani, 2001, *The Elements of Statistical Learning* (Springer, New York, NY).\n* James, Gareth, Daniela Witten, Trevor Hastie, and Robert Tibshirani, 2013, *An Introduction to Statistical Learning: With Applications in R* (Springer Science & Business Media, New York, NY).\n* Müller, Andreas C., and Sarah Guido, 2017, *Introduction to Machine Learning with Python* (O’Reilly Media, Sebastopol, CA).\n* Raschka, Sebastian, 2015, *Python Machine Learning* (Packt Publishing Ltd., Birmingham, UK).\n* Shalizi, Cosma Rohilla, 2017, Advanced Data Analysis from an Elementary Point of View from website, http://www.stat.cmu.edu/~cshalizi/ADAfaEPoV/ADAfaEPoV.pdf, 08/24/17.\n* VanderPlas, Jake, 2016, *Python Data Science Handbook* (O'Reilly Media, Sebastopol, CA).\n* Vapnik, Vladimir N., 2013, *The Nature of Statistical Learning* (Springer, New York, NY).\n\n\n", "meta": {"hexsha": "2068dfd4b940eb63ba4ea4fda8f2bd2dea90df92", "size": 153134, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "0211_SVM.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": "0211_SVM.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": "0211_SVM.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": 73.3049305888, "max_line_length": 26366, "alphanum_fraction": 0.7398095785, "converted": true, "num_tokens": 17502, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.936285002192296, "lm_q2_score": 0.9304582588688366, "lm_q1q2_score": 0.8711741129448486}} {"text": "# Final project\nThe Allen–Cahn equation (after John W. Cahn and Sam Allen) is a reaction–diffusion equation of mathematical physics which describes the process of phase separation in multi-component alloy systems, including order-disorder transitions.\n\nThe equation describes the time evolution of a scalar-valued state variable $\\eta$ on a domain $\\Omega=[0,1]$ during a time interval $[0,T]$, and is given (in one dimension) by:\n\n$$\n\\frac{\\partial \\eta}{\\partial t} - \\varepsilon^2 \\eta'' + f'(\\eta) = 0, \\qquad \\eta'(0, t) = \\eta'(1, t) = 0,\\qquad\\eta(x,0) = \\eta_0(x)\n$$\n\nwhere $f$ is a double-well potential, $\\eta_0$ is the initial condition, and $\\varepsilon$ is the characteristic width of the phase transition.\n\nThis equation is the L2 gradient flow of the Ginzburg–Landau free energy functional, and it is closely related to the Cahn–Hilliard equation.\n\nA typical example of double well potential is given by the following function\n\n$$\nf(\\eta) = \\eta^2(\\eta-1)^2\n$$\n\nwhich has two minima in $0$ and $1$ (the two wells, where its value is zero), one local maximum in $0.5$, and it is always greater or equal than zero.\n\nThe two minima above behave like \"attractors\" for the phase $\\eta$. Think of a solid-liquid phase transition (say water+ice) occupying the region $[0,1]$. When $\\eta = 0$, then the material is liquid, while when $\\eta = 1$ the material is solid (or viceversa).\n\nAny other value for $\\eta$ is *unstable*, and the equation will pull that region towards either $0$ or $1$.\n\nDiscretisation of this problem can be done by finite difference in time. For example, a fully explicity discretisation in time would lead to the following algorithm.\n\nWe split the interval $[0,T]$ in `n_steps` intervals, of dimension `dt = T/n_steps`. Given the solution at time `t[k] = k*dt`, it i possible to compute the next solution at time `t[k+1]` as\n\n$$\n\\eta_{k+1} = \\eta_{k} + \\Delta t \\varepsilon^2 \\eta_k'' - \\Delta t f'(\\eta_k)\n$$\n\nSuch a solution will not be stable. A possible remedy that improves the stability of the problem, is to treat the linear term $\\Delta t \\varepsilon^2 \\eta_k''$ implicitly, and keep the term $-f'(\\eta_k)$ explicit, that is:\n\n$$\n\\eta_{k+1} - \\Delta t \\varepsilon^2 \\eta_k'' = \\eta_{k} - \\Delta t f'(\\eta_k)\n$$\n\nGrouping together the terms on the right hand side, this problem is identical to the one we solved in the python notebook number 9, with the exception of the constant $\\Delta t \\varepsilon^2$ in front the stiffness matrix.\n\nIn particular, given a set of basis functions $v_i$, representing $\\eta = \\eta^j v_j$ (sum is implied), we can solve the problem using finite elements by computing\n\n$$\n\\big((v_i, v_j) + \\Delta t \\varepsilon^2 (v_i', v_j')\\big) \\eta^j_{k+1} = \\big((v_i, v_j) \\eta^j_{k} - \\Delta t (v_i, f'(\\eta_k)\\big)\n$$\nwhere a sum is implied over $j$ on both the left hand side and the right hand side. Let us remark that while writing this last version of the equation we moved from a forward Euler scheme to a backward Euler scheme for the second spatial derivative term: that is, we used $\\eta^j_{k+1}$ instead of $\\eta^j_{k}$. \n\nThis results in a linear system\n\n$$\nA x = b\n$$\n\nwhere \n\n$$\nA_{ij} = M_{ij}+ \\Delta t \\varepsilon^2 K_{ij} = \\big((v_i, v_j) + \\Delta t \\varepsilon^2 (v_i', v_j')\\big) \n$$\n\nand \n\n$$\nb_i = M_{ij} \\big(\\eta_k^j - \\Delta t f'(\\eta_k^j)\\big)\n$$\n\nwhere we simplified the integration on the right hand side, by computing the integral of the interpolation of $f'(\\eta)$.\n\n## Step 1\n\nWrite a finite element solver, to solve one step of the problem above, given the solution at the previous time step, using the same techniques used in notebook number 9.\n\nIn particular:\n\n1. Write a function that takes in input a vector representing $\\eta$, an returns a vector containing $f'(\\eta)$. Call this function `F`.\n\n2. Write a function that takes in input a vector of support points of dimension `ndofs` and the degree `degree` of the polynomial basis, and returns a list of basis functions (piecewise polynomial objects of type `PPoly`) of dimension `ndofs`, representing the interpolatory spline basis of degree `degree`\n\n3. Write a function that, given a piecewise polynomial object of type `PPoly` and a number `n_gauss_quadrature_points`, computes the vector of global_quadrature_points and global_quadrature_weights, that contains replicas of a Gauss quadrature formula with `n_gauss_quadrature_points` on each of the intervals defined by `unique(PPoly.x)`\n\n4. Write a function that, given the basis and the quadrature points and weights, returns the two matrices $M$ and $K$ \n\n## Step 2\n\nSolve the Allen-Cahan equation on the interval $[0,1]$, from time $t=0$ and time $t=1$, given a time step `dt`, a number of degrees of freedom `ndofs`, and a polynomial degree `k`.\n\n1. Write a function that takes the initial value of $\\eta_0$ as a function, eps, dt, ndofs, and degree, and returns a matrix of dimension `(int(T/dt), ndofs)` containing all the coefficients $\\eta_k^i$ representing the solution, and the set of basis functions used to compute the solution\n\n2. Write a function that takes all the solutions `eta`, the basis functions, a stride number `s`, and a resolution `res`, and plots on a single plot the solutions $\\eta_0$, $\\eta_s$, $\\eta_{2s}$, computed on `res` equispaced points between zero and one\n\n## Step 3\n\nSolve the problem for all combinations of\n\n1. eps = [01, .001]\n\n2. ndofs = [16, 32, 64, 128]\n\n3. degree = [1, 2, 3]\n\n3. dt = [.25, .125, .0625, .03125, .015625]\n\nwith $\\eta_0 = \\sin(2 \\pi x)+1$.\n\nPlot the final solution at $t=1$ in all cases. What do you observe? What happens when you increase ndofs and keep dt constant? \n\n## Step 4 (Optional)\n\nInstead of solving the problem explicitly, solve it implicitly, by using backward euler method also for the non linear term. This requires the solution of a Nonlinear problem at every step. Use scipy and numpy methods to solve the non linear iteration.\n\n\n```python\n%pylab inline\nimport sympy as sym\nimport scipy\nfrom scipy.interpolate import *\nfrom scipy.integrate import *\n```\n\n Populating the interactive namespace from numpy and matplotlib\n\n\n\n```python\nn = 1025 # number of sample points for evaluation\nm = 16 # number of support points (i.e. dimension of vector space for approximation)\nx = linspace(0,1, n) # equispaced points in interval for evaluation\nq = linspace(0,1, m)\ndegree = 1\neta_init_func = lambda x: sin( 2 * pi * x ) + 1\n\ndef f(eta):\n '''\n Input : * 1D ndarray, points in interval where to evaluate standard double well potential \n \n Output: * 1D ndarray, evaluation of standard double well potential at inputs\n '''\n return eta**2 * (eta-1.)**2\n\ndef ref_sol(x, f):\n return 0.5 * sign(f(x)-0.5) + 0.5\n```\n\n\n```python\n_ = plot(x, eta_init_func(x))\n```\n\n\n```python\n_ = plot(x,f(x))\n```\n\n\n```python\n# Step 1.1\n\ndef F(eta):\n '''\n Input : * 1D ndarray, points in interval where to evaluate derivative of standard double well potential \n \n Output: * 1D ndarray, evaluation of derivative of standard double well potential at inputs\n '''\n return 2. * eta * ( 2. * eta**2 - 3. * eta +1. )\n```\n\n\n```python\n_ = plot(x,F(x))\n```\n\n\n```python\n# Step 1.2\n\ndef compute_basis_functions(support_points, degree):\n '''\n Input : * 1D ndarray support_points, points in interval giving support points for constructing \n basis of piecewise polynomial objects.\n * int degree, specifies degree of the spline fit on each sub-interval.\n \n Output: * list basis, list of piecewise polynomials (objects of class scipy.interpolate.PPoly) \n with basis of space of polynomials of degree at most support_points.shape-1 \n contructed by interpolating splines of input degree. \n * list dbasis, list of piecewise polynomials (objects of class scipy.interpolate.PPoly) \n with derivatives of basis functions.\n '''\n basis = []\n M = support_points.shape[0]\n for i in range(M):\n c = zeros(M)\n c[i] = 1\n bi = PPoly.from_spline(splrep(support_points,c,k=degree))\n basis.append(bi)\n return basis\n```\n\n\n```python\nB = compute_basis_functions(q, degree)\n```\n\n\n```python\ndef evaluate_list_functions(x, list_functions):\n N = x.shape[0]9\n M = len(list_functions)\n E = zeros((N, M))\n for i in range(M):\n E[:,i] = list_functions[i](x)\n return E\n```\n\n\n```python\n_ = plot(x, evaluate_list_functions(x,B))\n```\n\n\n```python\n_ = plot(x, evaluate_list_functions(x, [b_i.derivative(1) for b_i in B]))\n```\n\n\n```python\n# Step 1.3\n\ndef compute_global_quadrature(basis, n_gauss_quadrature_points):\n '''\n Input : * list basis, list of objects of class scipy.interpolate.PPoly defining same piecewise subdivision, \n for instance as given by piecewise polynomial basis.\n * int n_gauss_quadrature_points, number of sample points and weights for each subinterval \n (d+1 if considering piecewise interpolation with degree d splines).\n \n Output: * global_quadrature, 1D ndarray containing sample points for exact integration on interval [0,1]\n * global_weights, 1D ndarray containing weigths for exact integration over [0,1]\n '''\n \n # extract interval of piecewise subdivision \n intervals = unique(basis[0].x)\n \n # compute quadrature points and weights and rescale for interval [0,1]\n qp, w = numpy.polynomial.legendre.leggauss(n_gauss_quadrature_points)\n qp = (qp+1)/2.\n w /= 2.\n \n # replicate points and weights in all the intervals of piecewise subdivision\n h = diff(intervals)\n global_quadrature = array([intervals[i]+h[i]*qp for i in range(len(h))]).reshape((-1,))\n global_weights = array([w*h[i] for i in range(len(h))]).reshape((-1,))\n \n return global_quadrature, global_weights\n```\n\n\n```python\n# Step 1.4\n\ndef compute_system_matrices(basis, global_quadrature, global_weights):\n '''\n Input : \n \n Output: \n '''\n dbasis = [b_i.derivative(1) for b_i in basis]\n Bq = array([b_i(global_quadrature) for b_i in basis]).T\n dBq = array([db_i(global_quadrature) for db_i in dbasis]).T\n M = einsum('ki, k, kj', Bq, global_weights, Bq)\n K = einsum('ki, k, kj', dBq, global_weights, dBq)\n\n return M, K\n```\n\n\n```python\n# Step 2.1\n\ndef solve_allen_cahan(eta_0_function, eps, dt, ndofs, degree):\n ## prepare matrix for results\n T = 1. \n n_times = int(T/dt)\n eta = zeros((n_times+1, ndofs))\n \n # calculate time independent parts of the system\n support_points = linspace(0,1, ndofs)\n basis = compute_basis_functions(support_points, degree)\n Q, W = compute_global_quadrature(basis, degree + 1)\n M, K = compute_system_matrices(basis, Q, W)\n A = M + dt * eps**2 * K\n \n eta[0,:] = eta_0_function(support_points)\n for i in range(n_times):\n rhs = M.dot(eta[i,:] - dt * F(eta[i,:]))\n eta[i+1,:] = linalg.solve(A, rhs)\n \n return eta, basis \n```\n\n\n```python\n# Step 2.2 \n\ndef plot_solution(eta, basis, stride, resolution):\n x = linspace(0,1,resolution)\n plot(x, (evaluate_list_functions(x,basis).dot(eta.T))[:,::stride])\n plot(x, ref_sol(x,eta_init_func), color = 'r')\n```\n\n\n```python\neta, b = solve_allen_cahan(eta_init_func, 0.001, 0.0625/4, 64, 3)\n```\n\n\n```python\nplot_solution(eta, b, 64, 1025)\n```\n\n\n```python\nx[eta_init_func(x)>0.5].shape\n```\n\n\n\n\n (684,)\n\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "7a0926ac0a87ddff49739d650d3189ed6e561de2", "size": 158906, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "project_solution/final_project_2019-2020.ipynb", "max_stars_repo_name": "saliei/P1.4_seed", "max_stars_repo_head_hexsha": "a56e0aaa4b17527ce29d2984a7a42bb8d647d412", "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": "project_solution/final_project_2019-2020.ipynb", "max_issues_repo_name": "saliei/P1.4_seed", "max_issues_repo_head_hexsha": "a56e0aaa4b17527ce29d2984a7a42bb8d647d412", "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": "project_solution/final_project_2019-2020.ipynb", "max_forks_repo_name": "saliei/P1.4_seed", "max_forks_repo_head_hexsha": "a56e0aaa4b17527ce29d2984a7a42bb8d647d412", "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": 301.5294117647, "max_line_length": 48744, "alphanum_fraction": 0.9211357658, "converted": true, "num_tokens": 3188, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693716759488, "lm_q2_score": 0.9173026573249612, "lm_q1q2_score": 0.871134238218474}} {"text": "***Welcome to Cowcooloose***,\n\nHere we will learn how cows are cool and often loosely correlated to math.\n```\n /; ;\\\n __ \\____//\n /{_\\_/ `'\\____\n \\___ ---(=)--(=)--}\n _____________________________/ :--'\n ,-,'`@@@@@@@@ @@@@@@ \\_ `__\\\n ;:( @@@@@@@@@ @@@ \\___(o'o)\n :: ) @@@@ @@@@@@ ,'@@( `===='\n :: : @@@@@: @@@@ `@@@:\n :: \\ @@@@@: @@@@@@@) ( '@@@'\n ;; /\\ /`, @@@@@@@@@\\\\ :@@@@@)\n ::/ ) {_----------------: :~`, ;\n ;;'`; : ) : / `; ;\n;;;; : : ; : ; ; :\n`'`' / : : : : : :\n )_ \\__; \";\" :_ ; \\_\\ `,','\n :__\\ \\ * `,'* \\ \\ : \\ * 8`;'* *\n `^' \\ :/ `^' `-^-' \\v/ : \\/ -Bill Ames- \n```\n\nA cow walks 3.2 miles in 1.5 hours, hungry for the patch of grass ahead\nWhat is the speed of the cow in \"mi/h\"?\n\nCows like imperial units btw... Weirdos...\n\n\n```python\n''' since dist = 3.2, and time = 1.5, and speed = distance / time '''\n\ndist = 3.2\ntime = 1.5\n\nspeed = dist / time\n\nprint('The cow walks at', speed, 'mi per hour')\n```\n\n The cow walks at 2.1333333333333333 mi per hour\n\n\n----\n----\nNow, what if as the cow walked, she *accelerated* (she's in a rush you see).\n\n\nIf she sped up 1.2 mi per hour per hour, how fast is she going in 2 hrs?\n\n\n```python\naccel = 1.2 # mi/hr per hr\ntime = 2.0\n\nspeed = speed + accel * time # mi/hr + (mi/hr)/hr * hr\n\nprint('The cow walks at', speed, 'mi per hour after', time, 'hours')\n```\n\n The cow walks at 4.533333333333333 mi per hour after 2.0 hours\n\n\nNow, more realistically, the cow will *oscillate* in speed...\n\nLet's use sine ```y = sin(x)``` to model how she changes speed...\n\n**So, let's try** ```speed = 2 * sin(time / 2) + 2```\n\n**IMPORTANT** Change of units for time, let time be in MINUTES\n\n*... What does that look like on a graph?*\n\n\n```python\nimport sympy\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ntime = sympy.symbols('time')\nspeed = 2 * sympy.sin( (time / 2)*(time / 60) ) + 2\n\n# lamdify() is a great function.\n# It turns sympy \"symbolic\" functions into real ones that can be USED!\nspeed_numpy = sympy.lambdify( time, # speed(time)\n speed, # speed function (symbolic)\n modules=['numpy'] # use numpy's functions to make it real\n )\n```\n\n\n```python\ntime_walking = 60.0 # spend 60 minutes walking\ntimes = np.linspace(0, time_walking, 200) # make 100 points between 0 and 60 min\nspeeds = speed_numpy(times) # make 100 speeds at each time in times\n\nplt.plot(times, speeds)\nplt.title(\"speed = 2 * sympy.sin( (time / 2)*(time / 60) ) + 2\")\nplt.xlabel(\"Time [minutes]\")\nplt.ylabel(\"Cow Speed [mi/h]\")\nplt.show()\n\n# \n```\n\nA trickier one now... \n\n**How FAR does she walk in 60 minutes at this\nalternating speed?**\n\n*This is impossible to get perfect without calculus btw...*\n\n----\n----\n\n**To do this, basically we do this:**\n\nFigure out the **Integral of Speed between time = 0 and time = 60**\n\n- *What does that mean?*\n\nIn a nutshell it means to do this:\n\n- for a ton of tiny slices of time (like really small, seriously):\n get the speed value at the start of that time slice\n\n\n- take the `speed * the width of the time slice`\n (essentially get the area of the rectangle...\n (see whiteboard explanation for details))\n\n\n- add that `speed*timewidth` to a running total of areas\n\n\n- at the end, the **total area gathered** will be the amount of **distance covered in that time**...\n\n**Isn't that kind of crazy?**\n\n----\n\nNone of that actually matters, in practice, though.\n\nAll you have to do is this: \n\n\n```python\n# Remember, we already defined speed and time up above when we plotted\ndistance = sympy.integrate(speed, (time, 0, time_walking) )\n\n# Evaluate result into a float (decimal number)\ndistance_walked = distance.evalf()\n```\n\n\n```python\nprint('The cow walks a grand total of', distance_walked, 'miles in',\n time_walking, 'minutes')\n\nprint(\"That's a fast cow!\")\n\nprint(\"The cow's distance function is:\", sympy.integrate(speed, time))\n```\n\n The cow walks a grand total of 347.273352127154 miles in 60.0 minutes\n That's a fast cow!\n The cow's distance function is: 2*time + 3*sqrt(15)*sqrt(pi)*fresnels(sqrt(15)*time/(30*sqrt(pi)))*gamma(3/4)/gamma(7/4)\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "f5611625ec3005d6b1aca67696b4a6a2a6679fb2", "size": 60159, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Math Magic/Week14_Notebook_Cowcooloose.ipynb", "max_stars_repo_name": "jonnyhyman/Programming-Classes", "max_stars_repo_head_hexsha": "f56a9cf90e3b8e4aafad99644f1ed7e87ba14995", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 23, "max_stars_repo_stars_event_min_datetime": "2018-12-15T01:10:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-02T05:23:45.000Z", "max_issues_repo_path": "Math Magic/Week14_Notebook_Cowcooloose.ipynb", "max_issues_repo_name": "jonnyhyman/Programming-Classes", "max_issues_repo_head_hexsha": "f56a9cf90e3b8e4aafad99644f1ed7e87ba14995", "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 Magic/Week14_Notebook_Cowcooloose.ipynb", "max_forks_repo_name": "jonnyhyman/Programming-Classes", "max_forks_repo_head_hexsha": "f56a9cf90e3b8e4aafad99644f1ed7e87ba14995", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2020-02-15T12:47:42.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-28T03:01:19.000Z", "avg_line_length": 212.5759717314, "max_line_length": 52392, "alphanum_fraction": 0.905234462, "converted": true, "num_tokens": 1320, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693702514737, "lm_q2_score": 0.9173026488471135, "lm_q1q2_score": 0.8711342288606471}} {"text": "# Newton's Method\n\n## imports\nFor this project it will be useful to import the numpy and matplotlib libraries.\n\n\n```python\nimport numpy as np\nfrom matplotlib import pyplot as plt\n```\n\n## Deduction and implementation of the algorithm\n\nLet $f$ be a function such that: \\begin{cases}\nf \\in C^2[a, b] \\\\\nf(\\lambda) = 0 \\text{ , } \\lambda \\in [a, b] \\text{ for some $ a, b \\in Dom(f) $.}\n\\end{cases}\n\nConsidering the first degree Taylor polynomial centered at some $ x_0 \\in [a, b] $ for $f$, we have:\n\\begin{equation}\nf(x) = f(x_0) + (x - x_0)f'(x_0) + \\frac{(x - x_0)^2}{2}f''(\\xi) \\text{ , with } \\xi = \\xi(x_0)\n\\end{equation}\n\nIf we let $x_0$ be an approximation for $\\lambda$ such that $f'(x_0) \\neq 0 $ then: \n\\begin{equation}\nf(\\lambda) = f(x_0) + (\\lambda - x_0)f'(x_0) + \\frac{(\\lambda - x_0)^2}{2}f''(\\xi) \\\\\n\\Rightarrow 0 = f(x_0) + (\\lambda - x_0)f'(x_0) + \\frac{(\\lambda - x_0)^2}{2}f''(\\xi) \\\\\n\\Rightarrow 0 \\approx f(x_0) + (\\lambda - x_0)f'(x_0) \\\\\n\\Rightarrow -(\\lambda - x_0)f'(x_0) \\approx f(x_0) \\\\\n\\Rightarrow (\\lambda - x_0) \\approx -\\frac{f(x_0)}{f'(x_0)} \\\\\n\\therefore \\lambda \\approx x_0 - \\frac{f(x_0)}{f'(x_0)}\n\\end{equation}\n\nThat is, $\\exists x_1 \\in [a, b] $ such that $ x_1 = x_0 - \\frac{f(x_0)}{f'(x_0)} $ is a better approximation for $\\lambda$\n\nAppling the same method repeatedly ($n$ times), we get $\\lambda \\approx x_n = x_{n-1} - \\frac{f(x_{n-1})}{f'(x_{n-1})}$.\n\nAssuming the convergence of the sequence $ (x_n)_{n=0}^{\\infty} $, we can stop the $n$ iterations once $(x_n - x_{n-1}) < \\epsilon $ , for some chosen precision $\\epsilon$.\n\n\n```python\ndef NewtonMethod(f, f_prime, x_0, a, b, epsilon=10**-4, max_it=100, ylim=10):\n \"\"\"Finds the root of the real function which is assumed C^2 in some interval closed interval between and containing and the root.\n Also prints a simple table of the values for each iteration and plots all the tangents generated by the method.\n\n Args:\n f : function which root is desired to approximate\n f_prime : derivative of \n x_0 : initial approximation\n [a, b]: endpoints of the interval containing the root\n epsilon : precision\n max_it : maximum number of iterations\n ylim: Oy axis limits in the plot\n\n Returns:\n x_1 : numerical approximation for the root\n \"\"\"\n \n # iterations table\n print('%7s %6s %2s %12s' % ('Iteration', 'x', '', 'f(x)'))\n print('%4d %14f %2s %10.15f' % (0, x_0, '', f(x_0)))\n\n # plotting the iterations\n t = np.linspace(a, b, 301) # 301 points is an arbitrarily large and odd number (this way the plot will be \"smooth\" and the division by zero will be considered)\n with np.errstate(divide='ignore'): # ignores (in the graph) possible division problems\n y = f(t)\n plt.plot(t, y)\n plt.plot(t, 0*t, 'k') # Ox axis\n plt.xlim(a, b)\n plt.ylim(-ylim, ylim)\n plt.grid()\n\n\n # algorithm \n if abs(f(x_0)) < epsilon:\n return x_0 # if the initial approximation is good enough, there's no need for further calculations\n \n for k in range(max_it):\n if ( f_prime(x_0) != 0 ):\n x_1 = x_0 - ( f(x_0) / f_prime(x_0) )\n \n tangent = ( f_prime(x_0) * (t - x_0) ) + f(x_0)\n plt.plot(t, tangent)\n print('%4d %14.7f %2s %10.15f' % (k+1, x_1, '', f(x_1)))\n else:\n print(\"\\n f'(x_%d) = 0 , therefore the method does not converge\" % k)\n plt.show()\n return None\n \n if abs(f(x_1)) < epsilon:\n return x_1\n x_0 = x_1\n \n return x_1\n```\n\n## Examples\n\n### #1\n\nThe Newton's Method can be easily adapted to solve equations with real roots. \n\nLet's look at the equation: \n$ \\frac{1}{x} = 1+ x^3 $\n\n\n```python\nx = np.linspace(-10, 10, 301) # 301 points is an arbitrarily large and odd number (this way the plot will be \"smooth\" and the division by zero will be considered)\n\ny_a1 = 1 + x**3\n\nwith np.errstate(divide='ignore'): # ignoring the undefined division\n y_a2 = x**-1\n\nplt.plot(x, y_a1, 'b', label=r'$y = 1 + x^{3}$')\nplt.plot(x, y_a2, 'r', label=r'$y = \\frac{1}{x}$')\nplt.legend()\nplt.xlim(-10, 10)\nplt.ylim(-10, 10)\nplt.grid()\n```\n\nSince there are two intersections in the graphs of the functions, the equation has two real roots.\n\nFor simplicity, let's take a closer look exclusively at the positive one.\n\n\n```python\nplt.plot(x, y_a1, 'b', label=r'$y = 1 + x^{3}$')\nplt.plot(x, y_a2, 'r', label=r'$y = \\frac{1}{x}$')\nplt.legend()\nplt.xlim(-1, 3)\nplt.ylim(0, 3)\nplt.grid()\n```\n\nFrom the new plot we can let $[a, b] = [0, 1.5]$\n\nBut we should notice that the Newton's Method is applicable to functions, therefore we should write the equation as: \n\n$ y(x) = 1 + x^3 - \\frac{1}{x} $ , for some $x$ such that $y = 0$.\n\n\n```python\ndef a(x):\n return 1 + x**3 - x**-1\n \ndef a_prime(x):\n return 3*(x**2) + x**-2\n```\n\n\n```python\ny_a = y_a1 - y_a2\nplt.plot(x, y_a, 'c', label=r'$y(x) = 1 + x^{3} - \\frac{1}{x}$')\nplt.plot(x, 0*x, 'k')\nplt.legend()\nplt.xlim(0, 1.5)\nplt.ylim(-10, 10)\nplt.grid()\n```\n\n\n```python\nroot = NewtonMethod(a, a_prime, 0.7, 0, 1.5, epsilon=10**-5)\nprint(f\"\\nThe intersection between the curves (1 + x^3) and (1/x) is, approximately, at x = %.5f.\" % root)\n```\n\n### #2\n\nAnother application of the Newton's Method is to find the reciprocal of number.\n\n$ \\pi^{-1} $ , for example, is the zero of the function: $ f(x) = \\pi - \\frac{1}{x} $\n\n\n```python\ndef b(x):\n return np.pi - x**-1\n\ndef b_prime(x):\n return x**-2\n```\n\n\n```python\nx = np.linspace(-10, 10, 301) # 301 points is an arbitrarily large and odd number (this way the plot will be \"smooth\" and the division by zero will be considered)\n\nwith np.errstate(divide='ignore'): # ignoring the undefined division\n y_b = np.pi - x**-1\n\n\nplt.plot(x, y_b, label=r'$f(x) = \\pi - \\frac{1}{x}$')\nplt.plot(x, 0*x, 'k')\nplt.legend()\nplt.xlim(-10, 10)\nplt.ylim(-10, 10)\nplt.grid()\n```\n\n\n```python\n# zooming in\nplt.plot(x, y_b, label=r'$f(x) = \\pi - \\frac{1}{x}$')\nplt.plot(x, 0*x, 'k')\nplt.legend()\nplt.xlim(-1, 2)\nplt.ylim(-2.5, 2.5)\nplt.grid()\n```\n\n\n```python\n# Let's try to use an initial approximation of x_0 = 0.5\n\nNewtonMethod(b, b_prime, .5, -1, 2, epsilon=10**-7, ylim=2.5)\n```\n\n\n```python\n# zooming in\ninverse_05 = NewtonMethod(b, b_prime, .5, .15, .45, epsilon=10**-7, ylim=.5)\nprint(f\"\\n If the initial approximation is x_0 = 0.5, the reciprocal of pi is approximately equal to %.7f.\" % inverse_05)\n```\n\n\n```python\n# Now, what happens if we try to use x_0 = 0.7 ?\n\nNewtonMethod(b, b_prime, .7, -10, 10, epsilon=10**-7, max_it=15)\n```\n\nIn this example we could experience the sensibility of the Method regarding the initial approximation. That is, $x_0$ must be somewhat good as an approximation for the method to return a reasonable value for the root.\n\nIn this case, even though close, $x_0 = 0.5$ and $x_0=0.7$ resulted in completely different outcomes. Using $x_0 = 0.5$ the method was successful. However, with $x_0 = 0.7$, the method diverged.\n", "meta": {"hexsha": "c336e5c869beb7dbdc89c0bdf1e983f5c0fb4ce8", "size": 376511, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "code.ipynb", "max_stars_repo_name": "matheus-ft/newton-method", "max_stars_repo_head_hexsha": "4f611d310d34118ad4b1b8e329070d4386f3969b", "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": "code.ipynb", "max_issues_repo_name": "matheus-ft/newton-method", "max_issues_repo_head_hexsha": "4f611d310d34118ad4b1b8e329070d4386f3969b", "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": "code.ipynb", "max_forks_repo_name": "matheus-ft/newton-method", "max_forks_repo_head_hexsha": "4f611d310d34118ad4b1b8e329070d4386f3969b", "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": 586.4657320872, "max_line_length": 27760, "alphanum_fraction": 0.7306532877, "converted": true, "num_tokens": 2368, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107861416413, "lm_q2_score": 0.9294404106533318, "lm_q1q2_score": 0.8710815779402191}} {"text": "# Expanding the robot\n\nOur initial simplification had the robot a point - well, the ropes met a point. The real robot has dimensions, and the ropes are tied to four corners of the robot. Let's assume:\n\n- a box, with the ropes tied to the upper face, and the claw at the centroid of the lower face\n- the box dimensions are $2b \\times 2d \\times h$ \n - the factor of 2 is for convenience in the equations: instead of $x - \\frac{b'}{2}$, we can use $x - b$\n- the claw is at $(x, y, z)$.\n\n\n\n\nThen, our original equations for $l_i$ become:\n\n$$\n\\begin{align}\nl_1^2 &=& (0 - (x - b))^2 + (0 - (y - d))^2 + (H - (z + h))^2 &=& (x - b)^2 + (y - d)^2 + (H - h - z)^2 \\\\\nl_2^2 &=& (0 - (x - b))^2 + (D - (y + d))^2 + (H - (z + h))^2 &=& (x - b)^2 + (D - d - y)^2 + (H - h - z)^2 \\\\\nl_3^2 &=& (B - (x + b))^2 + (D - (y + d))^2 + (H - (z + h))^2 &=& (B - b - x)^2 + (D - d - y)^2 + (H - h - z)^2 \\\\\nl_4^2 &=& (B - (x + b))^2 + (0 - (y - d))^2 + (H - (z + h))^2 &=& (B - b - x)^2 + (y - d)^2 + (H - h - z)^2\n\\end{align}\n$$\n\nAs before, we can subtract pairs of equations to eliminate two of $x, y, z$ and get the remaining one:\n\n\n$$\n\\begin{align}\nl_1^2 - l_2^2 &=& (y - d)^2 - (D - d - y)^2 \\\\ \n &=& (y - d + D - d - y)(y - d - D + d + y)\\\\ \n &=& (D - 2d)(D + 2y) \\\\\n\\therefore y &=& \\frac{1}{2}\\left(\\frac{l_1^2 - l_2^2}{D - 2d} - D\\right)\n\\end{align}\n$$\n\nSimilarly, for $x$:\n\n\n$$\n\\begin{align}\nl_2^2 - l_3^2 &=& (x - b)^2 - (B - b - x)^2 \\\\ \n &=& (x - b + B - b - x)(x - b - B + b + x)\\\\ \n &=& (B - 2b)(B + 2x) \\\\\n\\therefore x &=& \\frac{1}{2}\\left(\\frac{l_2^2 - l_3^2}{B - 2b} - B\\right)\n\\end{align}\n$$\n\nWhile the equations for $x$ and $y$ have changed a bit, the constraint on the rope lengths remains the same:\n\n$$\nl_1^2 - l_2^2 = l_4^2 - l_3^2\n$$\n\n\n```python\n\n```\n", "meta": {"hexsha": "235342f8bb499d7c679b8e7a4a7fea171874ae8f", "size": 2944, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Suspended_Robot/Paperwork.ipynb", "max_stars_repo_name": "Machine-Learning-Tokyo/Agritech", "max_stars_repo_head_hexsha": "855569561140bb06a13cce81495673bea471cbd0", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2019-07-29T23:16:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-02T14:08:47.000Z", "max_issues_repo_path": "Suspended_Robot/Paperwork.ipynb", "max_issues_repo_name": "Machine-Learning-Tokyo/Agritech", "max_issues_repo_head_hexsha": "855569561140bb06a13cce81495673bea471cbd0", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2019-08-21T02:59:05.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-25T09:28:40.000Z", "max_forks_repo_path": "Suspended_Robot/Paperwork.ipynb", "max_forks_repo_name": "Machine-Learning-Tokyo/Agritech", "max_forks_repo_head_hexsha": "855569561140bb06a13cce81495673bea471cbd0", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-01-11T01:06:22.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-11T01:06:22.000Z", "avg_line_length": 30.9894736842, "max_line_length": 186, "alphanum_fraction": 0.4375, "converted": true, "num_tokens": 755, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813526452771, "lm_q2_score": 0.9111797166446537, "lm_q1q2_score": 0.8710708180208964}} {"text": "# Eigenvalue and eigenvectors calculation\n\n$$\nA\\mathbf{x} = \\lambda \\mathbf{x}\n$$\n\n### Power method (vector iteration)\n- find the largest eigenvalue $\\lambda_{max}$\n\\begin{align}\n\\mathbf{q}_k & = \\frac{\\mathbf{z}_{k-1}}{\\|\\mathbf{z}_{k-1}\\|_2}\\\\\n\\mathbf{z}_k & = A\\mathbf{q}_{k}\\\\\n\\lambda_{max}^k & = \\mathbf{q}^T_k \\mathbf{z}_k\n\\end{align}\n\n\n```python\n%matplotlib inline\nfrom numpy import *\nfrom matplotlib.pyplot import *\nimport numpy.linalg\nimport scipy.linalg\n```\n\n\n```python\nn = 9\nh = 1./(n-1)\nx=linspace(0,1,n)\n\n# construct matrix\na = -ones((n-1,))\nb = 2*ones((n,))\nA = (diag(a, -1) + diag(b, 0) + diag(a, +1))\nA /= h**2\n\n#print A\n```\n\n\n```python\nz0 = ones_like(x) # starting \n\ndef PM(A, z0, tol=1e-5, nmax=500):\n q = z0/numpy.linalg.norm(z0,2)\n it = 0\n err = tol + 1.\n while (it < nmax and err > tol):\n z = dot(A,q)\n l = dot(q.T,z)\n err = numpy.linalg.norm(z-l*q,2)\n q = z/numpy.linalg.norm(z,2)\n \n it += 1\n print(\"error =\", err, \"iterations =\", it)\n print(\"lambda_max =\", l)\n return l,q\n\nl,x = PM(A,z0) \nl_np, x_np = numpy.linalg.eig(A)\n\nprint(\"numpy\")\nprint(l_np)\n```\n\n error = 8.456086478475517e-06 iterations = 82\n lambda_max = 249.73523408577807\n numpy\n [249.73523409 231.55417528 203.23651229 167.55417528 128.\n 6.26476591 24.44582472 88.44582472 52.76348771]\n\n\n### Inverse power method\n- find the eigenvalue $\\lambda$ **closest** to $\\mu$\n\\begin{align}\nM & = A-\\mu I\\\\\nM & = LU \\\\\n& \\\\\nM\\mathbf{x}_k &= \\mathbf q_{k-1}\\\\\n\\mathbf{q}_k & = \\frac{\\mathbf{x}_k}{\\|\\mathbf{x}_k\\|_2}\\\\\n\\mathbf{z}_k & = A\\mathbf{q}_{k}\\\\\n\\lambda^k & = \\mathbf{q}^T_k \\mathbf{z}_k\n\\end{align}\n\n\n\n```python\ndef IPM(A, x0, mu, tol=1e-5, nmax=500):\n M = A - mu*eye(len(A))\n P,L,U = scipy.linalg.lu(M)\n err = tol + 1.\n it = 0\n q = x0/numpy.linalg.norm(x0,2)\n while (it < nmax and err > tol):\n y = scipy.linalg.solve_triangular(L, dot(P.T,q), lower=True)\n x = scipy.linalg.solve_triangular(U, y)\n q = x/numpy.linalg.norm(x,2)\n z = dot(A,q)\n l = dot(q.T,z)\n err = numpy.linalg.norm(z-l*q,2)\n it += 1\n print(\"error =\", err, \"iterations =\", it)\n print(\"lambda =\", l)\n return l,q\n\n\nl,x = IPM(A,z0,6.)\n```\n\n error = 2.6310164587523326e-06 iterations = 3\n lambda = 6.2647659142204954\n\n", "meta": {"hexsha": "3bfb88ccb4493315028021ee13c22833ac48d7d3", "size": 5544, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/GR_lab05_eigenvalues.ipynb", "max_stars_repo_name": "mapenzo-ph/numerical-analysis-2021-2022", "max_stars_repo_head_hexsha": "952808d7fa7a9e718274592104be24882acef3ec", "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": "notebooks/GR_lab05_eigenvalues.ipynb", "max_issues_repo_name": "mapenzo-ph/numerical-analysis-2021-2022", "max_issues_repo_head_hexsha": "952808d7fa7a9e718274592104be24882acef3ec", "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": "notebooks/GR_lab05_eigenvalues.ipynb", "max_forks_repo_name": "mapenzo-ph/numerical-analysis-2021-2022", "max_forks_repo_head_hexsha": "952808d7fa7a9e718274592104be24882acef3ec", "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": 28.1421319797, "max_line_length": 87, "alphanum_fraction": 0.4036796537, "converted": true, "num_tokens": 881, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377249197138, "lm_q2_score": 0.9086179062123119, "lm_q1q2_score": 0.8709445406420633}} {"text": "# Modeling and Simulation in Python\n\nChapter 9\n\nCopyright 2017 Allen Downey\n\nLicense: [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0)\n\n\n\n```python\n# Configure Jupyter to display the assigned value after an assignment\n%config InteractiveShell.ast_node_interactivity='last_expr_or_assign'\n\n# import everything from SymPy.\nfrom sympy import *\n\n# Set up Jupyter notebook to display math.\ninit_printing() \n```\n\nThe following displays SymPy expressions and provides the option of showing results in LaTeX format.\n\n\n```python\nfrom sympy.printing import latex\n\ndef show(expr, show_latex=False):\n \"\"\"Display a SymPy expression.\n \n expr: SymPy expression\n show_latex: boolean\n \"\"\"\n if show_latex:\n print(latex(expr))\n return expr\n```\n\n### Analysis with SymPy\n\nCreate a symbol for time.\n\n\n```python\nt = symbols('t')\n```\n\nIf you combine symbols and numbers, you get symbolic expressions.\n\n\n```python\nexpr = t + 1\n```\n\nThe result is an `Add` object, which just represents the sum without trying to compute it.\n\n\n```python\ntype(expr)\n```\n\n\n\n\n sympy.core.add.Add\n\n\n\n`subs` can be used to replace a symbol with a number, which allows the addition to proceed.\n\n\n```python\nexpr.subs(t, 2)\n```\n\n`f` is a special class of symbol that represents a function.\n\n\n```python\nf = Function('f')\n```\n\n\n\n\n f\n\n\n\nThe type of `f` is `UndefinedFunction`\n\n\n```python\ntype(f)\n```\n\n\n\n\n sympy.core.function.UndefinedFunction\n\n\n\nSymPy understands that `f(t)` means `f` evaluated at `t`, but it doesn't try to evaluate it yet.\n\n\n```python\nf(t)\n```\n\n`diff` returns a `Derivative` object that represents the time derivative of `f`\n\n\n```python\ndfdt = diff(f(t), t)\n```\n\n\n```python\ntype(dfdt)\n```\n\n\n\n\n sympy.core.function.Derivative\n\n\n\nWe need a symbol for `alpha`\n\n\n```python\nalpha = symbols('alpha')\n```\n\nNow we can write the differential equation for proportional growth.\n\n\n```python\neq1 = Eq(dfdt, alpha*f(t))\n```\n\nAnd use `dsolve` to solve it. The result is the general solution.\n\n\n```python\nsolution_eq = dsolve(eq1)\n```\n\nWe can tell it's a general solution because it contains an unspecified constant, `C1`.\n\nIn this example, finding the particular solution is easy: we just replace `C1` with `p_0`\n\n\n```python\nC1, p_0 = symbols('C1 p_0')\n```\n\n\n```python\nparticular = solution_eq.subs(C1, p_0)\n```\n\nIn the next example, we have to work a little harder to find the particular solution.\n\n### Solving the quadratic growth equation \n\nWe'll use the (r, K) parameterization, so we'll need two more symbols:\n\n\n```python\nr, K = symbols('r K')\n```\n\nNow we can write the differential equation.\n\n\n```python\neq2 = Eq(diff(f(t), t), r * f(t) * (1 - f(t)/K))\n```\n\nAnd solve it.\n\n\n```python\nsolution_eq = dsolve(eq2)\n```\n\nThe result, `solution_eq`, contains `rhs`, which is the right-hand side of the solution.\n\n\n```python\ngeneral = solution_eq.rhs\n```\n\nWe can evaluate the right-hand side at $t=0$\n\n\n```python\nat_0 = general.subs(t, 0)\n```\n\nNow we want to find the value of `C1` that makes `f(0) = p_0`.\n\nSo we'll create the equation `at_0 = p_0` and solve for `C1`. Because this is just an algebraic identity, not a differential equation, we use `solve`, not `dsolve`.\n\nThe result from `solve` is a list of solutions. In this case, [we have reason to expect only one solution](https://en.wikipedia.org/wiki/Picard%E2%80%93Lindel%C3%B6f_theorem), but we still get a list, so we have to use the bracket operator, `[0]`, to select the first one.\n\n\n```python\nsolutions = solve(Eq(at_0, p_0), C1)\ntype(solutions), len(solutions)\n```\n\n\n\n\n (list, 1)\n\n\n\n\n```python\nvalue_of_C1 = solutions[0]\n```\n\nNow in the general solution, we want to replace `C1` with the value of `C1` we just figured out.\n\n\n```python\nparticular = general.subs(C1, value_of_C1)\n```\n\nThe result is complicated, but SymPy provides a method that tries to simplify it.\n\n\n```python\nparticular = simplify(particular)\n```\n\nOften simplicity is in the eye of the beholder, but that's about as simple as this expression gets.\n\nJust to double-check, we can evaluate it at `t=0` and confirm that we get `p_0`\n\n\n```python\nparticular.subs(t, 0)\n```\n\nThis solution is called the [logistic function](https://en.wikipedia.org/wiki/Population_growth#Logistic_equation).\n\nIn some places you'll see it written in a different form:\n\n$f(t) = \\frac{K}{1 + A e^{-rt}}$\n\nwhere $A = (K - p_0) / p_0$.\n\nWe can use SymPy to confirm that these two forms are equivalent. First we represent the alternative version of the logistic function:\n\n\n```python\nA = (K - p_0) / p_0\n```\n\n\n```python\nlogistic = K / (1 + A * exp(-r*t))\n```\n\nTo see whether two expressions are equivalent, we can check whether their difference simplifies to 0.\n\n\n```python\nsimplify(particular - logistic)\n```\n\nThis test only works one way: if SymPy says the difference reduces to 0, the expressions are definitely equivalent (and not just numerically close).\n\nBut if SymPy can't find a way to simplify the result to 0, that doesn't necessarily mean there isn't one. Testing whether two expressions are equivalent is a surprisingly hard problem; in fact, there is no algorithm that can solve it in general.\n\n### Exercises\n\n**Exercise:** Solve the quadratic growth equation using the alternative parameterization\n\n$\\frac{df(t)}{dt} = \\alpha f(t) + \\beta f^2(t) $\n\n\n```python\nalpha = symbols('alpha')\nbeta = symbols('beta')\neq = Eq(diff(f(t), t),alpha * f(t) + beta * (f(t))**2)\n\ndsolve(eq)\n```\n\n**Exercise:** Use [WolframAlpha](https://www.wolframalpha.com/) to solve the quadratic growth model, using either or both forms of parameterization:\n\n df(t) / dt = alpha f(t) + beta f(t)^2\n\nor\n\n df(t) / dt = r f(t) (1 - f(t)/K)\n\nFind the general solution and also the particular solution where `f(0) = p_0`.\n\n#### Get general equation for t = 0\n\n\n```python\ngen = dsolve(eq).subs(t, 0)\n```\n\n#### Solution for C1 at t_0\n\n\n```python\nat_0 = gen.subs(t, 0)\nsolutions = solve(Eq(at_0, p_0), C1)\n\nsolutions[0]\n```\n\n#### Substitute 1950 for p_0\n\n\n```python\nsolutions[0].subs(p_0, 1950)\n```\n", "meta": {"hexsha": "0385fd8a59d4a48795bb7fe163ca5888eff77d23", "size": 70610, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/chap09.ipynb", "max_stars_repo_name": "jitsen-design/ModSimPy", "max_stars_repo_head_hexsha": "985d1f6e84b96aaa2cc6ad41567a8369f45efac6", "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/chap09.ipynb", "max_issues_repo_name": "jitsen-design/ModSimPy", "max_issues_repo_head_hexsha": "985d1f6e84b96aaa2cc6ad41567a8369f45efac6", "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/chap09.ipynb", "max_forks_repo_name": "jitsen-design/ModSimPy", "max_forks_repo_head_hexsha": "985d1f6e84b96aaa2cc6ad41567a8369f45efac6", "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.6861198738, "max_line_length": 4088, "alphanum_fraction": 0.7711089081, "converted": true, "num_tokens": 1662, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377237352755, "lm_q2_score": 0.9086179049750476, "lm_q1q2_score": 0.8709445383798969}} {"text": "# Tutorial\n\nWe will here use a computer to gain some evidence to help tackle the following\nproblem.\n\n```{admonition} Problem\n\nConsider the following polynomial:\n\n$$\n p(n) = n ^ 2 + n + 41\n$$\n\n1. Verify that $p(n)$ is prime for $n\\in \\mathbb{Z}$ up until $n=20$.\n2. What is the smallest value of $n$ for which $p(n)$ is no longer prime?\n\n```\n\nWe will start by defining a function for $p(n)$:\n\n\n```python\ndef p(n):\n \"\"\"\n Return the value of n ^ 2 + n + 41 for a given value of n.\n \"\"\"\n return n ** 2 + n + 41\n```\n\nWe will use `sympy` to check if a number is prime.\n\n\n```python\nimport sympy as sym\n\nsym.isprime(3)\n```\n\n\n\n\n True\n\n\n\n\n```python\nsym.isprime(4)\n```\n\n\n\n\n False\n\n\n\nNow to answer the first question we will use a list comprehension to create a\nlist of boolean variables that confirm if $p(n)$ is prime.\n\n```{tip}\nThis is similar to what we did in {ref}`probability`.\n```\n\n\n```python\nchecks = [sym.isprime(p(n)) for n in range(21)]\nchecks\n```\n\n\n\n\n [True,\n True,\n True,\n True,\n True,\n True,\n True,\n True,\n True,\n True,\n True,\n True,\n True,\n True,\n True,\n True,\n True,\n True,\n True,\n True,\n True]\n\n\n\nWe can use the `all` tool to check if all the boolean values are true:\n\n\n```python\nall(checks)\n```\n\n\n\n\n True\n\n\n\n```{attention}\nUsing list comprehensions is a mathematical way of repeating code but at times\nit might prove useful to repeat code in a different way using a standard `for`\nstatement.\n```\n\nIn that case we can essentially repeat the previous exercise using:\n\n\n```python\nchecks = []\nfor n in range(21):\n value = p(n)\n is_prime = sym.isprime(value)\n checks.append(is_prime)\nall(checks)\n```\n\n\n\n\n True\n\n\n\nThe main difference between the two approaches is that we can include multiple\nlines of indented code to be repeated for every value of `n` in `range(21)`.\n\n```{attention}\nA `for` loop or a list comprehension should be used when we know how many\nrepetitions we want to make.\n```\n\nTo answer the second question we will repeat the code until the value of $p(n)$\nis no longer prime.\n\n\n```python\nn = 0\nwhile sym.isprime(p(n)):\n n += 1\nn\n```\n\n\n\n\n 40\n\n\n\n```{attention}\nA `while` loop should be used when we do not know how many times a repetition\nshould be made **but** we know under what conditions is should be made\n```\n\nIndeed for that value of $n$ we have:\n\n\n```python\np(n)\n```\n\n\n\n\n 1681\n\n\n\nand\n\n\n```python\nsym.isprime(p(n))\n```\n\n\n\n\n False\n\n\n\n`sympy` can also factor the number for us:\n\n\n```python\nsym.factorint(p(n))\n```\n\n\n\n\n {41: 2}\n\n\n\nIndeed:\n\n\n```python\n41 ** 2\n```\n\n\n\n\n 1681\n\n\n", "meta": {"hexsha": "c806c18ac30ac49772f3ed0e7482bc2e22a4f26b", "size": 7314, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "book/building-tools/01-variables-conditionals-loops/tutorial/.main.md.bcp.ipynb", "max_stars_repo_name": "11michalis11/pfm", "max_stars_repo_head_hexsha": "c91b1eda70d7cde3fbe065db4667f84853947850", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2020-09-24T21:02:41.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-14T08:37:21.000Z", "max_issues_repo_path": "book/building-tools/01-variables-conditionals-loops/tutorial/.main.md.bcp.ipynb", "max_issues_repo_name": "11michalis11/pfm", "max_issues_repo_head_hexsha": "c91b1eda70d7cde3fbe065db4667f84853947850", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 87, "max_issues_repo_issues_event_min_datetime": "2020-09-21T15:54:23.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-19T23:26:15.000Z", "max_forks_repo_path": "book/building-tools/01-variables-conditionals-loops/tutorial/.main.md.bcp.ipynb", "max_forks_repo_name": "11michalis11/pfm", "max_forks_repo_head_hexsha": "c91b1eda70d7cde3fbe065db4667f84853947850", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-10-02T09:21:27.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-08T14:46:27.000Z", "avg_line_length": 18.9481865285, "max_line_length": 88, "alphanum_fraction": 0.4644517364, "converted": true, "num_tokens": 726, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012701768144, "lm_q2_score": 0.9207896796948869, "lm_q1q2_score": 0.8708840486211261}} {"text": "# Solutions\n\n## Question 1\n\n> 1. For each of the following functions calculate $\\frac{df}{dx}$,\n> $\\frac{d^2f}{dx^2}$ and $\\int f(x) dx$.\n\n> $f(x) = x$\n\n\n```python\nimport sympy as sym\n\nx = sym.Symbol(\"x\")\nexpression = x\nsym.diff(expression, x)\n```\n\n\n\n\n$\\displaystyle 1$\n\n\n\n\n```python\nsym.diff(expression, x, 2)\n```\n\n\n\n\n$\\displaystyle 0$\n\n\n\n\n```python\nsym.integrate(expression, x)\n```\n\n\n\n\n$\\displaystyle \\frac{x^{2}}{2}$\n\n\n\n> $f(x) = x ^{\\frac{1}{3}}$\n\n\n```python\nexpression = x ** (sym.S(1) / 3)\nsym.diff(expression, x)\n```\n\n\n\n\n$\\displaystyle \\frac{1}{3 x^{\\frac{2}{3}}}$\n\n\n\n\n```python\nsym.diff(expression, x, 2)\n```\n\n\n\n\n$\\displaystyle - \\frac{2}{9 x^{\\frac{5}{3}}}$\n\n\n\n\n```python\nsym.integrate(expression, x)\n```\n\n\n\n\n$\\displaystyle \\frac{3 x^{\\frac{4}{3}}}{4}$\n\n\n\n> $f(x) = 2 x (x - 3) (\\sin(x) - 5)$\n\n\n```python\nexpression = 2 * x * (x - 3) * (sym.sin(x) - 5)\nsym.diff(expression, x)\n```\n\n\n\n\n$\\displaystyle 2 x \\left(x - 3\\right) \\cos{\\left(x \\right)} + 2 x \\left(\\sin{\\left(x \\right)} - 5\\right) + \\left(x - 3\\right) \\left(2 \\sin{\\left(x \\right)} - 10\\right)$\n\n\n\n\n```python\nsym.diff(expression, x, 2)\n```\n\n\n\n\n$\\displaystyle 2 \\left(- x \\left(x - 3\\right) \\sin{\\left(x \\right)} + 2 x \\cos{\\left(x \\right)} + 2 \\left(x - 3\\right) \\cos{\\left(x \\right)} + 2 \\sin{\\left(x \\right)} - 10\\right)$\n\n\n\n\n```python\nsym.integrate(expression, x)\n```\n\n\n\n\n$\\displaystyle - \\frac{10 x^{3}}{3} - 2 x^{2} \\cos{\\left(x \\right)} + 15 x^{2} + 4 x \\sin{\\left(x \\right)} + 6 x \\cos{\\left(x \\right)} - 6 \\sin{\\left(x \\right)} + 4 \\cos{\\left(x \\right)}$\n\n\n\n> $f(x) = 3 x ^ 3 + 6 \\sqrt{x} + 3$\n\n\n```python\nexpression = 3 * x ** 3 + 6 * sym.sqrt(x) + 3\nsym.diff(expression, x)\n```\n\n\n\n\n$\\displaystyle 9 x^{2} + \\frac{3}{\\sqrt{x}}$\n\n\n\n\n```python\nsym.diff(expression, x, 2)\n```\n\n\n\n\n$\\displaystyle 3 \\left(6 x - \\frac{1}{2 x^{\\frac{3}{2}}}\\right)$\n\n\n\n\n```python\nsym.integrate(expression, x)\n```\n\n\n\n\n$\\displaystyle 4 x^{\\frac{3}{2}} + \\frac{3 x^{4}}{4} + 3 x$\n\n\n\n## Question 2\n\n> `2`. Consider the function $f(x)=2x+1$. By differentiating _from first\n> principles_ show that $f'(x)=2$.\n\nUsing the definition of the derivative:\n\n\n```python\nh = sym.Symbol(\"h\")\nexpression = 2 * x + 1\nsym.limit((expression - expression.subs({x: x - h})) / h, h, 0)\n```\n\n\n\n\n$\\displaystyle 2$\n\n\n\n## Question 3\n\n> `3`. Consider the second derivative $f''(x)=6x+4$ of some cubic function $f(x)$.\n\n> `1`. Find $f'(x)$\n\nWe know the derivative will be the integral of the second derivative with a\nconstant:\n\n\n```python\nc1 = sym.Symbol(\"c1\")\n\nsecond_derivative = 6 * x + 4\nderivative = sym.integrate(second_derivative, x) + c1\nderivative\n```\n\n\n\n\n$\\displaystyle c_{1} + 3 x^{2} + 4 x$\n\n\n\n> `2`. You are given that $f(0)=10$ and $f(1)=13$, find $f(x)$.\n\nWe know that the cubic will be the integral of the derivative with constant:\n\n\n```python\nc2 = sym.Symbol(\"c2\")\n\ncubic = sym.integrate(derivative, x) + c2\ncubic\n```\n\n\n\n\n$\\displaystyle c_{1} x + c_{2} + x^{3} + 2 x^{2}$\n\n\n\nWe substitute $x=0$:\n\n\n```python\ncubic.subs({x: 0})\n```\n\n\n\n\n$\\displaystyle c_{2}$\n\n\n\nThis gives $c_2=10$. We substitute that back in to our expression for the cubic:\n\n\n```python\ncubic = cubic.subs({c2: 10})\ncubic\n```\n\n\n\n\n$\\displaystyle c_{1} x + x^{3} + 2 x^{2} + 10$\n\n\n\nand now substitute $x=1$:\n\n\n```python\ncubic.subs({x: 1})\n```\n\n\n\n\n$\\displaystyle c_{1} + 13$\n\n\n\nwhich gives $c_1=0$ which we substitute back in to our expression for the cubic:\n\n\n```python\ncubic = cubic.subs({c1: 0})\ncubic\n```\n\n\n\n\n$\\displaystyle x^{3} + 2 x^{2} + 10$\n\n\n\n> `3`. Find all the stationary points of $f(x)$ and determine their nature.\n\nThe stationary points are the points that give $\\frac{df}{dx}=0$:\n\n\n```python\nstationary_points = sym.solveset(sym.diff(cubic, x), x)\nstationary_points\n```\n\n\n\n\n$\\displaystyle \\left\\{- \\frac{4}{3}, 0\\right\\}$\n\n\n\nWe determine the nature of these turning points by considering the sign of $\\frac{d^2f}{dx^2}$ at each point.\n\n\n```python\nsecond_derivative.subs({x: -4 / sym.S(3)})\n```\n\n\n\n\n$\\displaystyle -4$\n\n\n\nThis is negative, so it is a local maximum.\n\n\n```python\nsecond_derivative.subs({x: 0})\n```\n\n\n\n\n$\\displaystyle 4$\n\n\n\nThis is positive, so it is a local minimum.\n\n## Question 4\n\n> `4`. Consider the function $f(x)=\\frac{2}{3}x ^ 3 + b x ^ 2 + 2 x + 3$, where\n> $b$ is some undetermined coefficient.\n\n> `1`. Find $f'(x)$ and $f''(x)$\n\n\n```python\nb = sym.Symbol(\"b\")\nexpression = sym.S(2) / 3 * x ** 3 + b * x ** 2 + 2 * x + 3\nderivative = sym.diff(expression, x)\nderivative\n```\n\n\n\n\n$\\displaystyle 2 b x + 2 x^{2} + 2$\n\n\n\n\n```python\nsecond_derivative = sym.diff(expression, x, 2)\n```\n\n> `2`. You are given that $f(x)$ has a stationary point at $x=2$. Use this\n> information to find $b$.\n\nWe solve the equation that arises when substituting $x=2$ in to the derivative:\n\n\n```python\nequation = sym.Eq(derivative.subs({x: 2}), 0)\nequation\n```\n\n\n\n\n$\\displaystyle 4 b + 10 = 0$\n\n\n\n\n```python\nsym.solveset(equation, b)\n```\n\n\n\n\n$\\displaystyle \\left\\{- \\frac{5}{2}\\right\\}$\n\n\n\n> `3`. Find the coordinates of the other stationary point.\n\nWe substitute this value of $b$ in to the expression:\n\n\n```python\nb_value = -sym.S(5) / 2\nexpression = expression.subs({b: b_value})\nexpression\n```\n\n\n\n\n$\\displaystyle \\frac{2 x^{3}}{3} - \\frac{5 x^{2}}{2} + 2 x + 3$\n\n\n\nand the derivative and then solve the equation:\n\n\n```python\nderivative = derivative.subs({b: b_value})\nsym.solveset(derivative)\n```\n\n\n\n\n$\\displaystyle \\left\\{\\frac{1}{2}, 2\\right\\}$\n\n\n\n> `4`. Determine the nature of both stationary points.\n\nSubstituting both values in to the second derivative:\n\n\n```python\nsecond_derivative = second_derivative.subs({b: b_value})\nsecond_derivative.subs({x: sym.S(1) / 2})\n```\n\n\n\n\n$\\displaystyle -3$\n\n\n\nThis is negative so it is a local maxima.\n\n\n```python\nsecond_derivative.subs({x: 2})\n```\n\n\n\n\n$\\displaystyle 3$\n\n\n\nThis is positive so it is a local minima.\n\n## Question 5\n\n> `5`. Consider the functions $f(x)=-x^2+4x+4$ and $g(x)=3x^2-2x-2$.\n\n> `1`. Create a variable `turning_points` which has value the turning points of\n> $f(x)$.\n\n\n```python\nf = -(x ** 2) + 4 * x + 4\nderivative = sym.diff(f, x)\nturning_points = sym.solveset(derivative, x)\n```\n\n> `2`. Create variable `intersection_points` which has value of the points where\n> $f(x)$ and $g(x)$ intersect.\n\n\n```python\ng = 3 * x ** 2 - 2 * x - 2\nequation = sym.Eq(f, g)\nintersection_points = sym.solveset(equation, x)\nintersection_points\n```\n\n\n\n\n$\\displaystyle \\left\\{\\frac{3}{4} - \\frac{\\sqrt{33}}{4}, \\frac{3}{4} + \\frac{\\sqrt{33}}{4}\\right\\}$\n\n\n\n> `3`. Using your answers to parts 2., calculate the area of the region between\n> $f$ and $g$. Assign this value to a variable `area_between`.\n\nThe area between $f$ and $g$ corresponds to the integral of $\\pm (f - g)$\nbetween the points of intersection. We here use $f - g$, if the outcome was\nnegative we would take the opposite.\n\n\n```python\narea_between = sym.integrate(\n f - g, (x, sym.S(3) / 4 - sym.sqrt(33) / 4, sym.S(3) / 4 + sym.sqrt(33) / 4)\n)\nsym.simplify(area_between)\n```\n\n\n\n\n$\\displaystyle \\frac{11 \\sqrt{33}}{4}$\n\n\n", "meta": {"hexsha": "c8a4b94be54c59c092791b904d2d0057710729dd", "size": 20477, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "book/tools-for-mathematics/03-calculus/solutions/.main.md.bcp.ipynb", "max_stars_repo_name": "11michalis11/pfm", "max_stars_repo_head_hexsha": "c91b1eda70d7cde3fbe065db4667f84853947850", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2020-09-24T21:02:41.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-14T08:37:21.000Z", "max_issues_repo_path": "book/tools-for-mathematics/03-calculus/solutions/.main.md.bcp.ipynb", "max_issues_repo_name": "11michalis11/pfm", "max_issues_repo_head_hexsha": "c91b1eda70d7cde3fbe065db4667f84853947850", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 87, "max_issues_repo_issues_event_min_datetime": "2020-09-21T15:54:23.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-19T23:26:15.000Z", "max_forks_repo_path": "book/tools-for-mathematics/03-calculus/solutions/.main.md.bcp.ipynb", "max_forks_repo_name": "11michalis11/pfm", "max_forks_repo_head_hexsha": "c91b1eda70d7cde3fbe065db4667f84853947850", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-10-02T09:21:27.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-08T14:46:27.000Z", "avg_line_length": 20.3548707753, "max_line_length": 213, "alphanum_fraction": 0.4528495385, "converted": true, "num_tokens": 2405, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.951863233662724, "lm_q2_score": 0.9149009544128984, "lm_q1q2_score": 0.8708605809485739}} {"text": "## Plotting the Ekman spiral\n\n### a) The top Ekman spiral\n\nThe equations for the Ekman spiral are \n\n\\begin{align}\n u_E (z) & = u_s \\cos⁡\\left(\\frac{𝜋}{4} + \\frac{\\pi}{D} z\\right) e^{\\frac{\\pi}{D}z} \\\\\n v_E (z) & = -u_s \\sin⁡\\left(\\frac{𝜋}{4} + \\frac{\\pi}{D} z\\right) e^{\\frac{\\pi}{D}z}\n\\end{align}\n \n\nWhere $u_s = 1$ m/s is the flow at the surface and $D=\\pi\\sqrt{2K/f}$ is the Ekman layer thickness. \n\nPlot these two functions for $f=10^{-4} s^{-1}$, $K=2\\times10^{-2} m^2/s$ and `z=np.arange(-100, 0.01, 5)`. \n\nMake three plots:\n1. $u_E$ and $v_E$ as two lines as a function of depth. Put depth on the y-axis\n2. A scatter-line-plot of $u_E$ vs. $v_E$, with each point color-coded for depth\n3. a 3D quiver plot, you can use the code below to show the vector components $u_E$ and $v_E$\n\n ```\n import matplotlib.pyplot as plt\n from mpl_toolkits.mplot3d import Axes3D \n fig = plt.figure(figsize=(7, 5)) \n ax = fig.gca(projection='3d') \n zs = np.zeros(len(z)) \n ax.set_xlim((-.1,.1))\n ax.set_ylim((-.1,.1))\n ax.set_zlim((-100,0))\n ax.quiver(zs, zs, z, uE, vE, zs) \n ax.set_xlabel('zonal velocity [m/s]') \n ax.set_ylabel('meridional velocity [m/s]') \n ax.set_zlabel('Depth [m]') \n plt.show()\n ```\n \nExplain the figures.\n\n\n```python\n\n```\n\n### b) Bottom Ekman Layer\nAt the bottom there is also an Ekman layer, but only if the ocean interior geostrophic velocity is non-zero so that a no-slip boundary condition can be satisfied. The Ekman spiral looks like this:\n\n\n\\begin{align}\n u_E (z) & = u_g - e^{z/D} \\left[u_g \\cos(z/D) + v_g \\sin(z/D) \\right] \\\\\n v_E (z) & = v_g + e^{z/D} \\left[u_g \\sin(z/D) - v_g \\cos(z/D) \\right]\n\\end{align}\n\nHere $u_g$ and $v_g$ are the geoestrophic velocities in the ocean's interior.\n\nThe derivation is similar to that of the surface Ekman layer and can be found in chapter 5.7.3 of _Atmospheric and Oceanic Fluid Dynamics_ (2nd edition) by Vallis or chapter 5.3.2 of _Dynamical Oceanography_ by Dijkstra.\n\nPlot the same three figures as in (a) for $u_g = 0.1 m/s$, $v_g = 0 m/s$, and assuming the same $D$ and $f$ for the 250 meters above the sea floor (for simplicity, the sea floor can now be set to 0 and $z$ is still pointing up).\n\nExplain the figures.\n\n\n```python\n\n```\n", "meta": {"hexsha": "d7a7153e386e8324ae10346e3f334b9845b612c0", "size": 3625, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Ch03_SurfacedriftGyres_Plastic/Ch03_EkmanSpiral.ipynb", "max_stars_repo_name": "OceanCurrentsBook/Exercises", "max_stars_repo_head_hexsha": "60a91a794edec53d333fbce8679ff68ac9aa6cf9", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2020-08-28T21:59:36.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-19T18:40:54.000Z", "max_issues_repo_path": "Ch03_SurfacedriftGyres_Plastic/Ch03_EkmanSpiral.ipynb", "max_issues_repo_name": "OceanCurrentsBook/Exercises", "max_issues_repo_head_hexsha": "60a91a794edec53d333fbce8679ff68ac9aa6cf9", "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": "Ch03_SurfacedriftGyres_Plastic/Ch03_EkmanSpiral.ipynb", "max_forks_repo_name": "OceanCurrentsBook/Exercises", "max_forks_repo_head_hexsha": "60a91a794edec53d333fbce8679ff68ac9aa6cf9", "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": 32.6576576577, "max_line_length": 237, "alphanum_fraction": 0.5348965517, "converted": true, "num_tokens": 777, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.959762057376384, "lm_q2_score": 0.9073122232403329, "lm_q1q2_score": 0.8708038460598829}} {"text": "\n\n# Exemplos de soluções numéricas para ODEs com o método de Euler\n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\nplt.style.use('seaborn-poster')\n```\n\n## Exemplo 1 \n Considere o problema de valor inicial:\n\n \\begin{equation}\n\\dot{u}(t) = 2u\n \\end{equation}\n\n com $u(t=0) = 1$\n\n Use o método de Euler para encontrar a solução aproximada. Compare-a com solução analítica $u(t) = e^{2t}$.\n\n\n```python\n# Definindo os parâmetros\nh = 0.1 # passo\ntfim = 5\nnt = int(tfim/h) # numero de iterações\ns0 = 1 # Condição Inicial\n```\n\n\n```python\nu = np.zeros(nt)\nu[0] = s0\nfor k in np.arange(1,nt):\n u[k] = u[k-1]+2*h*u[k-1]\n\n```\n\n\n```python\nt = np.linspace(0,tfim,nt)\n```\n\n\n```python\nplt.figure(figsize = (12, 8))\nplt.plot(t, u, 'bo--', label='Numérica')\nplt.plot(t, np.exp(2*t), 'g', label='Analítica')\nplt.title('Solução Aproximada \\\nSolução Analítica')\nplt.xlabel('t')\nplt.ylabel('f(t)')\nplt.grid()\nplt.legend(loc='upper left')\nplt.show()\n```\n\nÉ útil definir uma função para automatizar o gráfico acima:\n\n\n```python\ndef faz_grafico_euler(tempo,y,f_analitica,h=0.01):\n plt.figure(figsize = (12, 8))\n plt.plot(tempo, y, 'bo--', label='Numérica com h={}'.format(h))\n plt.plot(tempo,f_analitica, 'g', label='Analítica')\n plt.title('Solução Aproximada \\\n Solução Analítica')\n plt.xlabel('t')\n plt.ylabel('f(t)')\n plt.grid()\n plt.legend(loc='upper left')\n plt.show() \n```\n\n## Exemplo 2\n\nEscreva uma função generalizada para o método de Euler.\n\n\n```python\ndef Euler(f,h=0.01,s0=1,tmax=10):\n nt = int(tmax/h)\n u = np.zeros(nt)\n tempo = np.linspace(0,tmax,nt)\n u[0] = s0\n \n for k in np.arange(1,nt):\n u[k] = u[k-1] + h*f(tempo[k-1],u[k-1]) \n \n\n return tempo,u\n\n\n\n```\n\n\n```python\n# Testando para o exemplo 1\n\nf = lambda t,u: 2*u # ODE\nh = 0.1\ns0=1\ntmax = 5\n```\n\n\n```python\n\ntempo,y = Euler(h,f,s0,tmax)\n```\n\n\n```python\nfaz_grafico_euler(tempo,y,np.exp(2*tempo),0.1)\n```\n\n## Exemplo 3 \n\nTeste a função Euler para o problema de valor inicial:\n\n\\begin{equation}\n\\dot{u} = u(t)(1-u(t))\n\\end{equation}\n\ncom $u(0) = 0.5$.\nCompare com a solução analítica: $u(t)=e^t/(1+e^{t})$\n\n\n```python\n# Resolvendo o exemplo 3\n\nf = lambda t,u: u*(1-u) # ODE\nh = 0.1\ns0=.5\ntmax = 5\n```\n\n\n```python\ntempo,y = Euler(h,f,s0,tmax)\n```\n\n\n```python\nf_analitica = lambda t: np.exp(t)/(1+np.exp(t))\n```\n\n\n```python\nfaz_grafico_euler(tempo,y,f_analitica(tempo),h)\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "ad7c78821005ad726287f762f94b72271b348151", "size": 132993, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "SC_Metodo_Euler.ipynb", "max_stars_repo_name": "aschelin/SimulacoesAGFE", "max_stars_repo_head_hexsha": "5294771ff8bf85a1129611bd3406780ef64ac75a", "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": "SC_Metodo_Euler.ipynb", "max_issues_repo_name": "aschelin/SimulacoesAGFE", "max_issues_repo_head_hexsha": "5294771ff8bf85a1129611bd3406780ef64ac75a", "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": "SC_Metodo_Euler.ipynb", "max_forks_repo_name": "aschelin/SimulacoesAGFE", "max_forks_repo_head_hexsha": "5294771ff8bf85a1129611bd3406780ef64ac75a", "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": 363.368852459, "max_line_length": 42862, "alphanum_fraction": 0.9297632206, "converted": true, "num_tokens": 925, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133481428691, "lm_q2_score": 0.9263037379231739, "lm_q1q2_score": 0.8706452477086251}} {"text": "# M2AA3 Chapter 3, Lesson 1 - Lagrange Interpolation\n\n\n```python\nimport sympy as sp\n```\n\nGiven points $\\{(z_i, f_i) \\}_{i=0}^n$, where $\\forall i, z_i, f_i \\in \\mathbb{C}$, and $z_i$ are distinct. We would like to find a polynomial $p_n \\in \\mathbb{P}_n$ such that $\\forall i, p_n(z_i) = f_i$.\n\nThe following polynomials work:\n$$p_n(z) = \\sum_{i=0}^n f_i l_i(z)$$ where $l_i (z)$ is the Largrange's basis function\n$$l_i(z) = \\prod_{\\substack{0 \\leq k \\leq n \\\\ k \\neq i}} \\frac{z - z_k}{z_i - z_k}$$\nThe function 'lagrange' inputs 'zs' (list of $z_i$) and 'fs' (list of $f_i$) and output polynomials. \n\n\n```python\nx = sp.symbols('x')\nl = sp.Function('l')\np = sp.Function('p')\n```\n\nStep 1 - Find Largrange Basis\n\n\n```python\ndef basis(zs,i):\n \n # Initialization\n zi = zs[i]\n l = 1\n \n # Loop for Product\n for zj in zs:\n if zj != zi:\n l = l * (x-zj)/(zi-zj)\n \n l = sp.simplify(l)\n return l\n```\n\nStep 2 - Find Polynomial\n\n\n```python\ndef lagrange(zs,fs):\n \n # Initialization\n p = 0\n \n # Loop for Sum\n for i in range(len(fs)):\n p += fs[i]*basis(zs,i)\n \n p = sp.simplify(p)\n return p\n```\n\nExample - Use the following data to find the largrange polynomial.\n\n\n```python\nxs = [-1, 0, 2, 5]\nys = [-3, -1, 4, 1]\n```\n\n\n```python\nlagrange(xs,ys)\n```\n\n\n\n\n -13*x**3/90 + 14*x**2/45 + 221*x/90 - 1\n\n\n", "meta": {"hexsha": "aa4925ccce3cedd3f6cabef43debd9cfecf6d530", "size": 3284, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "M2AA3/M2AA3-Polynomials/Lesson 01 - Basics/Largrange Interpolation.ipynb", "max_stars_repo_name": "ImperialCollegeLondon/Random-Stuff", "max_stars_repo_head_hexsha": "219bc0e26ea6f5ee7548009c849959b268f54821", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-05-16T04:08:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-27T12:56:10.000Z", "max_issues_repo_path": "M2AA3/M2AA3-Polynomials/Lesson 01 - Basics/Largrange Interpolation.ipynb", "max_issues_repo_name": "ImperialCollegeLondon/Random-Stuff", "max_issues_repo_head_hexsha": "219bc0e26ea6f5ee7548009c849959b268f54821", "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": "M2AA3/M2AA3-Polynomials/Lesson 01 - Basics/Largrange Interpolation.ipynb", "max_forks_repo_name": "ImperialCollegeLondon/Random-Stuff", "max_forks_repo_head_hexsha": "219bc0e26ea6f5ee7548009c849959b268f54821", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-03-31T00:23:13.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-13T15:01:46.000Z", "avg_line_length": 21.0512820513, "max_line_length": 221, "alphanum_fraction": 0.4631546894, "converted": true, "num_tokens": 500, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566341999997376, "lm_q2_score": 0.9099070145888367, "lm_q1q2_score": 0.8704481689753414}} {"text": "# Solving equations by addition\n\nLet's solve a linear equation using addition.\n\n**Note**: Lesson inspired by https://www.basic-mathematics.com/solving-equations-using-addition.html\n\nHere we import a few functions from SymPy. Each of these functions will be explained.\n\n\n```python\nfrom sympy import symbols, Eq, simplify, solve\n```\n\n## Overview\n\nGiven we have an equation\n\n$$x + -b = c$$\n\nwe want to solve for the value of $x$.\n\nWe need to \"move\" the $b$ value over to the other side so we can have $x$ by itself.\n\nNotice the negative or minus sign in front of $b$. We can add a postive version of the negative $b$ to move it over to the other side.\n\n$$x + -b + b = c + b$$\n\nOnce we do this, the negative and positive $b$ values will cancel out to zero.\n\n$$x + 0 = c + b$$\n\nThis will simplify to having $x$ on one side like we want it to.\n\n$$x = c + b$$\n\n## Setup\n\nThe above uses variables instead of numbers. Let's play around with this ourselves with Python and SymPy using real numbers.\n\nLet's say we want to solve for $x$ in the following equation.\n\n$$x + (-2) = 8$$\n\nFirst we need to create our $x$ variable for our equation using the `symbols()` function.\n\n\n```python\nx = symbols('x')\n```\n\nWe can write Python code very similar to our equation above.\n\nLet us define our equation. This can be done using the `Eq()` function.\n\nThe first and second arguments for this function are the left and right sides of the equal side, respectively.\n\n\n```python\neq1 = Eq(x + (-2), 8)\neq1\n```\n\n\n\n\n$\\displaystyle x - 2 = 8$\n\n\n\nYou may notice the left side of our equation looks a bit different from above, which was $x + (-2)$.\n\nThese two expressions are equal and Python can check this for us.\n\n\n```python\nx + (-2) == x - 2\n```\n\n\n\n\n True\n\n\n\n## Using Python and SymPy to Help Us\n\nAnother great thing about Python and SymPy is that we can solve our equation using the `solve()` function. Why show this? Because we can have an end point we can go towards to check our math work immediately.\n\nThe `solve()` function takes two parameters, the first one is the equation and the second one is variable symbol you want to solve for.\n\n\n```python\nsolve(eq1, x)\n```\n\n\n\n\n [10]\n\n\n\nThis tells us that solving for $x$ in our equation $x + (-2) = 8$ requires $x$ to be $10$, or $x = 10$.\n\nLet's use math to double check this.\n\n## Adding on both sides\n\nBased on our Overview above, we want to add the positive version of our values on both sides of the equation.\n\nWe can access the left hand side and the right hand side using the methods `.lhs` and `rhs` on our equation object, respectively.\n\n\n```python\n# Left side of the equals\neq1.lhs\n```\n\n\n\n\n$\\displaystyle x - 2$\n\n\n\n\n```python\n# Right side of the equals\neq1.rhs\n```\n\n\n\n\n$\\displaystyle 8$\n\n\n\nNow that we have the left and right sides, let's add the positive version of 2 because we are subtracting from it.\n\n\n```python\neq1 = Eq(eq1.lhs + 2, eq1.rhs + 2)\neq1\n```\n\n\n\n\n$\\displaystyle x = 10$\n\n\n\n## Exercise\n\nSolve the following equation using addition.\n\n$$x + (-6) = 5$$\n\n**Hint**: Start by translating the math equation in to a SymPy equation using the `Eq()` function.\n\n\n```python\n\n```\n", "meta": {"hexsha": "5da8828e61eda631945b9d40ca311670a61f4933", "size": 7177, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "algebra/solve_equations_by_addition.ipynb", "max_stars_repo_name": "erictleung/machine-learning", "max_stars_repo_head_hexsha": "9467e9dc951697a962062b2c1c1caa225cc65bb8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-02-04T20:16:35.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-15T20:02:23.000Z", "max_issues_repo_path": "algebra/solve_equations_by_addition.ipynb", "max_issues_repo_name": "erictleung/data-science", "max_issues_repo_head_hexsha": "9467e9dc951697a962062b2c1c1caa225cc65bb8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2017-06-10T18:14:31.000Z", "max_issues_repo_issues_event_max_datetime": "2017-11-01T02:32:51.000Z", "max_forks_repo_path": "algebra/solve_equations_by_addition.ipynb", "max_forks_repo_name": "erictleung/machine-learning", "max_forks_repo_head_hexsha": "9467e9dc951697a962062b2c1c1caa225cc65bb8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-02-04T20:16:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-13T15:03:09.000Z", "avg_line_length": 21.881097561, "max_line_length": 217, "alphanum_fraction": 0.5127490595, "converted": true, "num_tokens": 822, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566341987633822, "lm_q2_score": 0.9099070084811306, "lm_q1q2_score": 0.8704481620075324}} {"text": "#
An Overview of SymPy
\n\n
\n\n
\n\n###
Dr. Subir Sarkar
Arya Vidyapeeth College
Guwahati - 781 016
Assam.
\n\n# Importing Sympy\n\n>```python\nfrom sympy import *\n```\n\n\n```python\nfrom sympy import *\n```\n\n# Symbols\n\nSymbols can be created in a few different ways in SymPy, for example,
\n`sympy.Symbol`, `sympy.symbols`, and `sympy.var`\n\n\n```python\nx = Symbol('x')\nx\n```\n\n\n\n\n$\\displaystyle x$\n\n\n\nThe variable $x$ now represents an abstract mathematical symbol which could, for example, represent a real number, an integer, a complex number, a function, as well as a large number of other possibilities.
\nIf we have a mathematical variable $y$ that is known to be a real number, we can use the `real=True` keyword argument when creating the corresponding symbol instance. We can verify that SymPy indeed recognizes that the symbol is real by using\nthe `is_real` attribute of the Symbol class:\n\n\n```python\ny = Symbol('y', real=True)\ny.is_real\n```\n\n\n\n\n True\n\n\n\nIf, on the other hand we were to use `is_real` to query the previously defined symbol $x$, which was not explicitly specified to real, and therefore can represent both real and nonreal variables, we get None as result:\n\n\n```python\nx.is_real is None\n```\n\n\n\n\n False\n\n\n\n`is_real` returns **True** if the symbol is known to be **real**, **False** if the symbol is known to be **not real**, and **None** if it is not known if the symbol is real or not\n\n\n```python\nSymbol('z', imaginary=True).is_real\n```\n\n\n\n\n False\n\n\n\nExplicitly specifying when creating new symbols as real and positive or anything else as required, can help SymPy to simplify various expressions further than otherwise possible.\n\n\n```python\nx = Symbol('x')\ny = Symbol('y', positive=True)\n```\n\n\n```python\nsqrt(x**2)\n```\n\n\n\n\n$\\displaystyle \\sqrt{x^{2}}$\n\n\n\n\n```python\nsqrt(y**2)\n```\n\n\n\n\n$\\displaystyle y$\n\n\n\nWhen working with mathematical symbols that represent integers, rather than real numbers, it is also useful to explicitly specify this when creating the corresponding SymPy symbols, using, for example, the integer=True, or even=True or odd=True, if applicable. This may also allow SymPy to analytically simplify certain expressions and function evaluations.\n\n\n```python\nn1 = Symbol('n')\nn2 = Symbol('n', integer=True)\nn3 = Symbol('n', odd=True)\n```\n\n\n```python\ncos(n1*pi)\n```\n\n\n\n\n$\\displaystyle \\cos{\\left(\\pi n \\right)}$\n\n\n\n\n```python\ncos(n2*pi)\n```\n\n\n\n\n$\\displaystyle \\left(-1\\right)^{n}$\n\n\n\n\n```python\ncos(n3*pi)\n```\n\n\n\n\n$\\displaystyle -1$\n\n\n\nUsing Python’s tuple unpacking syntax together with a call to `sympy.symbols` is a convenient way to create multiple symbols:\n\n\n```python\na, b, c = symbols('a, b, c', negative=True)\nd, e, f = symbols('d, e, f', positive=True)\n```\n\n# Constants and Special Symbols\n\nSelected mathematical constants and special symbols and their corresponding symbols in SymPy:\n\n|Mathematical Symbol|SymPy Symbol|Description\n|:---|:---|:---\n|$\\pi$|`pi`|Ratio of the circumference to the diameter of a circle.\n|$e$|`E`|The base of the natural logarithm $e = exp (1)$.\n|$\\gamma$|`EulerGamma`|Euler's constant\n|$i$|`I`|The imaginary unit.\n|$\\infty$|`oo`|Infinity\n\n# Functions\n\n## Undefined Functions\n\n\n```python\nx, y, z = symbols('x, y, z')\nf = Function('f')\ntype(f)\n```\n\n\n\n\n sympy.core.function.UndefinedFunction\n\n\n\n\n```python\nf(x)\n```\n\n\n\n\n$\\displaystyle f{\\left(x \\right)}$\n\n\n\n\n```python\ng = Function('g')(x, y, z)\ng\n```\n\n\n\n\n$\\displaystyle g{\\left(x,y,z \\right)}$\n\n\n\n\n```python\ng.free_symbols\n```\n\n\n\n\n {x, y, z}\n\n\n\n## Defined Functions\n\n\n```python\ntype(sin)\n```\n\n\n\n\n sympy.core.function.FunctionClass\n\n\n\n\n```python\nsin(1.5*pi)\n```\n\n\n\n\n$\\displaystyle -1$\n\n\n\n\n```python\nn = Symbol('n')\nsin(n*pi)\n```\n\n\n\n\n$\\displaystyle \\sin{\\left(\\pi n \\right)}$\n\n\n\n\n```python\nn = Symbol('n', integer=True)\nsin(n*pi)\n```\n\n\n\n\n$\\displaystyle 0$\n\n\n\n## Lambda Functions\n\nIt can be created `sympy.Lambda`\n\n\n```python\nf = Lambda(x, x**2)\nf\n```\n\n\n\n\n$\\displaystyle \\left( x \\mapsto x^{2} \\right)$\n\n\n\n\n```python\nf(1.5)\n```\n\n\n\n\n$\\displaystyle 2.25$\n\n\n\n\n```python\nf(1 + x)\n```\n\n\n\n\n$\\displaystyle \\left(x + 1\\right)^{2}$\n\n\n\n# Expressions\n\nIn SymPy, mathematical expressions are represented as trees where leafs are symbols, and nodes are class instances that represent mathematical operations.
\nExamples of these classes are `Add`, `Mul`, and `Pow` for basic arithmetic operators, and `Sum`, `Product`, `Integral`, and `Derivative` for analytical mathematical operations.\n\n\n```python\nx = symbols('x')\nexpr = 1 + x + x**2 + x**3\nexpr\n```\n\n\n\n\n$\\displaystyle x^{3} + x^{2} + x + 1$\n\n\n\n\n```python\nexpr.args\n```\n\n\n\n\n (1, x, x**2, x**3)\n\n\n\n\n```python\nexpr.args[0]\n```\n\n\n\n\n$\\displaystyle 1$\n\n\n\n\n```python\nexpr.args[1]\n```\n\n\n\n\n$\\displaystyle x$\n\n\n\n\n```python\nexpr.args[2]\n```\n\n\n\n\n$\\displaystyle x^{2}$\n\n\n\n\n```python\nexpr.args[3]\n```\n\n\n\n\n$\\displaystyle x^{3}$\n\n\n\n# Manipulating Expressions\n\n## Simplification\n\n\n```python\nexpr = 2 * (x**2 - x) - x * (x + 1)\nexpr\n```\n\n\n\n\n$\\displaystyle 2 x^{2} - x \\left(x + 1\\right) - 2 x$\n\n\n\n\n```python\nsimplify(expr)\n```\n\n\n\n\n$\\displaystyle x \\left(x - 3\\right)$\n\n\n\n\n```python\nexpr.simplify()\n```\n\n\n\n\n$\\displaystyle x \\left(x - 3\\right)$\n\n\n\n\n```python\nexpr\n```\n\n\n\n\n$\\displaystyle 2 x^{2} - x \\left(x + 1\\right) - 2 x$\n\n\n\n\n```python\nexpr = 2 * cos(x) * sin(x)\nexpr\n```\n\n\n\n\n$\\displaystyle 2 \\sin{\\left(x \\right)} \\cos{\\left(x \\right)}$\n\n\n\n\n```python\nexpr.simplify()\n```\n\n\n\n\n$\\displaystyle \\sin{\\left(2 x \\right)}$\n\n\n\n\n```python\nexpr = exp(x)*exp(y)\nexpr\n```\n\n\n\n\n$\\displaystyle e^{x} e^{y}$\n\n\n\n\n```python\nsimplify(expr)\n```\n\n\n\n\n$\\displaystyle e^{x + y}$\n\n\n\nEach specific type of simplification can also be carried out with more specialized functions, such as `sympy.trigsimp` and `sympy.powsimp`, for trigonometric and power simplifications, respectively.
\nSummary of selected SymPy functions for simplifying expressions:\n\n|Function|Description\n|:---|:---\n|`sympy.simplify`| Attempt various methods and approaches to obtain a simpler form of a given expression.\n|`sympy.trigsimp`| Attempt to simplify an expression using trigonometric identities.\n|`sympy.powsimp`| Attempt to simplify an expression using laws of powers.\n|`sympy.compsimp`| Simplify combinatorial expressions.\n|`sympy.ratsimp`| Simplify an expression by writing on a common denominator\n\n## Expand\n\n\n```python\nexpr = (x + 1) * (x + 2)\nexpr\n```\n\n\n\n\n$\\displaystyle \\left(x + 1\\right) \\left(x + 2\\right)$\n\n\n\n\n```python\nexpand(expr)\n```\n\n\n\n\n$\\displaystyle x^{2} + 3 x + 2$\n\n\n\n\n```python\nsin(x + y).expand(trig=True)\n```\n\n\n\n\n$\\displaystyle \\sin{\\left(x \\right)} \\cos{\\left(y \\right)} + \\sin{\\left(y \\right)} \\cos{\\left(x \\right)}$\n\n\n\n\n```python\nlog(x * y).expand(log=True)\n```\n\n\n\n\n$\\displaystyle \\log{\\left(x y \\right)}$\n\n\n\n\n```python\na, b = symbols('a, b', positive=True)\nlog(a*b).expand(log=True)\n```\n\n\n\n\n$\\displaystyle \\log{\\left(a \\right)} + \\log{\\left(b \\right)}$\n\n\n\n\n```python\nexpr = exp(a + I*b)\nexpr\n```\n\n\n\n\n$\\displaystyle e^{a + i b}$\n\n\n\n\n```python\nexpr.expand(complex=True)\n```\n\n\n\n\n$\\displaystyle i e^{a} \\sin{\\left(b \\right)} + e^{a} \\cos{\\left(b \\right)}$\n\n\n\n## Factor, Collect and Combine\n\n\n```python\nexpr = x**2 - 1\nfactor(expr)\n```\n\n\n\n\n$\\displaystyle \\left(x - 1\\right) \\left(x + 1\\right)$\n\n\n\n\n```python\nexpr = x*cos(y) + x*sin(z)\nfactor(expr)\n```\n\n\n\n\n$\\displaystyle x \\left(\\sin{\\left(z \\right)} + \\cos{\\left(y \\right)}\\right)$\n\n\n\n\n```python\nexpr = log(a) - log(b)\nlogcombine(expr)\n```\n\n\n\n\n$\\displaystyle \\log{\\left(\\frac{a}{b} \\right)}$\n\n\n\n\n```python\nexpr = x + y + x*z + x*y\nexpr.collect(x)\n```\n\n\n\n\n$\\displaystyle x \\left(y + z + 1\\right) + y$\n\n\n\n\n```python\nexpr.collect(y)\n```\n\n\n\n\n$\\displaystyle x z + x + y \\left(x + 1\\right)$\n\n\n\n## Apart, Together and Cancel\n\n\n```python\napart(1/(x**2 + 3*x + 2), x)\n```\n\n\n\n\n$\\displaystyle - \\frac{1}{x + 2} + \\frac{1}{x + 1}$\n\n\n\n\n```python\ntogether(1 / (y * x + y) + 1 / (1+x))\n```\n\n\n\n\n$\\displaystyle \\frac{y + 1}{y \\left(x + 1\\right)}$\n\n\n\n\n```python\ncancel(y / (y * x + y))\n```\n\n\n\n\n$\\displaystyle \\frac{1}{x + 1}$\n\n\n\n## Substitutions\n\n\n```python\n(x + y).subs(x, y)\n```\n\n\n\n\n$\\displaystyle 2 y$\n\n\n\n\n```python\nexpr = sin(x*exp(x))\nexpr\n```\n\n\n\n\n$\\displaystyle \\sin{\\left(x e^{x} \\right)}$\n\n\n\n\n```python\nexpr.subs(x, y)\n```\n\n\n\n\n$\\displaystyle \\sin{\\left(y e^{y} \\right)}$\n\n\n\nFor muliple substitutions, we can pass a dictionary as first and only argument to `subs`, which maps old symbols or expressions to new symbols or expressions:\n\n\n```python\nexpr = sin(x * z)\nexpr\n```\n\n\n\n\n$\\displaystyle \\sin{\\left(x z \\right)}$\n\n\n\n\n```python\nexpr.subs({sin:cos, x:y, z:exp(x)})\n```\n\n\n\n\n$\\displaystyle \\cos{\\left(y e^{x} \\right)}$\n\n\n\n\n```python\nexpr = x*y + z**2* x\n```\n\nTo substitute numerical values in place of symbolic number,\nfor numerical evaluation, a convenient way of doing this is to\ndefine a dictionary that translates the symbols to numerical values, and passing this dictionary as argument\nto the subs method.\n\n\n```python\nexpr\n```\n\n\n\n\n$\\displaystyle x y + x z^{2}$\n\n\n\n\n```python\nvalues = {x:1.25,\n y:0.04,\n z:3.2}\n```\n\n\n```python\nexpr.subs(values)\n```\n\n\n\n\n$\\displaystyle 12.85$\n\n\n\n# Numerical Evaluation\n\nEven when working with symbolic mathematics, it is almost invariably sooner or later required to evaluate\nthe symbolic expressions numerically, for example, when producing plots or concrete numerical results.\nA SymPy expression can be evaluated using either the `sympy.N` function, or the `evalf` method of SymPy\nexpression instances.
\nBoth `sympy.N` and the `evalf` method take an optional argument that specifies the number of significant\ndigits to which the expression is to be evaluated.\n\n\n```python\nN(1 + pi)\n```\n\n\n\n\n$\\displaystyle 4.14159265358979$\n\n\n\n\n```python\nN(pi, 10)\n```\n\n\n\n\n$\\displaystyle 3.141592654$\n\n\n\n\n```python\n(x + 1/pi).evalf()\n```\n\n\n\n\n$\\displaystyle x + 0.318309886183791$\n\n\n\n\n```python\n(x + 1/pi).evalf(5)\n```\n\n\n\n\n$\\displaystyle x + 0.31831$\n\n\n\n`sympy.lambdify` function takes a set of free symbols and an expression as arguments, and generates a function that efficiently evaluates the numerical value of the expression.\nThe produced function takes the same number of arguments as the number of free symbols passed as first argument to `sympy.lambdify`.\n\n\n```python\nx = symbols('x')\nexpr = sin(pi*x*exp(x))\nexpr\n```\n\n\n\n\n$\\displaystyle \\sin{\\left(\\pi x e^{x} \\right)}$\n\n\n\n\n```python\nexpr_num = lambdify(x, expr)\nexpr_num(10)\n```\n\n\n\n\n 0.879393997597802\n\n\n\nBy passing the optional argument 'numpy' as third argument to `sympy.lambdify` SymPy creates a vectorized function that accepts NumPy arrays as input.\n\n\n```python\nexpr_num = lambdify(x, expr, 'numpy')\nimport numpy as np\nxvalues = np.arange(1, 10)\nexpr_num(xvalues)\n```\n\n\n\n\n array([ 0.77394269, 0.64198244, 0.72163867, 0.94361635, 0.20523391,\n 0.97398794, 0.97734066, -0.87034418, -0.69512687])\n\n\n\n# Calculas\n\n## Derivatives\n\nIn SymPy we can calculate the derivative of a function using `sympy.diff`\n\n\n```python\nx = Symbol('x')\nf = Function('f')(x)\ndiff(f, x)\n```\n\n\n\n\n$\\displaystyle \\frac{d}{d x} f{\\left(x \\right)}$\n\n\n\n\n```python\ndiff(f, x, x)\n```\n\n\n\n\n$\\displaystyle \\frac{d^{2}}{d x^{2}} f{\\left(x \\right)}$\n\n\n\n\n```python\ndiff(f, x, 3)\n```\n\n\n\n\n$\\displaystyle \\frac{d^{3}}{d x^{3}} f{\\left(x \\right)}$\n\n\n\nFor multivariate functions -\n\n\n```python\nx, y, z = symbols('x, y, z')\ng = Function('g')(x, y)\ng.diff(x, y)\n```\n\n\n\n\n$\\displaystyle \\frac{\\partial^{2}}{\\partial y\\partial x} g{\\left(x,y \\right)}$\n\n\n\n\n```python\ng.diff(x, 3, y, 2)\n```\n\n\n\n\n$\\displaystyle \\frac{\\partial^{5}}{\\partial y^{2}\\partial x^{3}} g{\\left(x,y \\right)}$\n\n\n\nFor defined functions -\n\n\n```python\nexpr = x**4 + x**3 + x**2 + x + 1\nexpr.diff(x)\n```\n\n\n\n\n$\\displaystyle 4 x^{3} + 3 x^{2} + 2 x + 1$\n\n\n\n\n```python\nexpr.diff(x, x)\n```\n\n\n\n\n$\\displaystyle 2 \\left(6 x^{2} + 3 x + 1\\right)$\n\n\n\n\n```python\nexpr = (x + 1)**3 * y**2 *(z - 1)\nexpr.diff(x, y, z)\n```\n\n\n\n\n$\\displaystyle 6 y \\left(x + 1\\right)^{2}$\n\n\n\nFor trigonometric functions -\n\n\n```python\nexpr = sin(x * y) * cos(x / 2)\nexpr.diff(x)\n```\n\n\n\n\n$\\displaystyle y \\cos{\\left(\\frac{x}{2} \\right)} \\cos{\\left(x y \\right)} - \\frac{\\sin{\\left(\\frac{x}{2} \\right)} \\sin{\\left(x y \\right)}}{2}$\n\n\n\nAlternative way (delayed evaluation) -\n\n\n```python\nexpr = exp(cos(x))\nd = Derivative(expr, x)\nd\n```\n\n\n\n\n$\\displaystyle \\frac{d}{d x} e^{\\cos{\\left(x \\right)}}$\n\n\n\n\n```python\nd.doit()\n```\n\n\n\n\n$\\displaystyle - e^{\\cos{\\left(x \\right)}} \\sin{\\left(x \\right)}$\n\n\n\n## Integrals\n\n\n```python\na, b, x, y = symbols('a, b, x, y')\nf = Function('f')(x)\nintegrate(f)\n```\n\n\n\n\n$\\displaystyle \\int f{\\left(x \\right)}\\, dx$\n\n\n\n\n```python\nintegrate(f, (x, a, b))\n```\n\n\n\n\n$\\displaystyle \\int\\limits_{a}^{b} f{\\left(x \\right)}\\, dx$\n\n\n\n\n```python\nintegrate(sin(x))\n```\n\n\n\n\n$\\displaystyle - \\cos{\\left(x \\right)}$\n\n\n\n\n```python\nintegrate(sin(x), (x, a, b))\n```\n\n\n\n\n$\\displaystyle \\cos{\\left(a \\right)} - \\cos{\\left(b \\right)}$\n\n\n\n\n```python\nintegrate(exp(-x**2), (x, 0, oo))\n```\n\n\n\n\n$\\displaystyle \\frac{\\sqrt{\\pi}}{2}$\n\n\n\nSymPy will not be able to give symbolic results for any integral. When SymPy fails to evaluate an integral, an\ninstance of `sympy.Integral`, representing the formal integral, is returned instead.\n\n\n```python\nintegrate(sin(x*cos(x)), x)\n```\n\n\n\n\n$\\displaystyle \\int \\sin{\\left(x \\cos{\\left(x \\right)} \\right)}\\, dx$\n\n\n\nMultibariable expressions -\n\n\n```python\nintegrate(sin(x*exp(y)), x)\n```\n\n\n\n\n$\\displaystyle - e^{- y} \\cos{\\left(x e^{y} \\right)}$\n\n\n\n\n```python\nexpr = (x + y)**2\nintegrate(expr, x)\n```\n\n\n\n\n$\\displaystyle \\frac{x^{3}}{3} + x^{2} y + x y^{2}$\n\n\n\nBy passing more than one symbol, or more than one tuple that contain symbols and their integration limits, we can carry out multiple integration:\n\n\n```python\nexpr = (x + y)**2\nintegrate(expr, (x, 0, 1), (y, 0, 1))\n```\n\n\n\n\n$\\displaystyle \\frac{7}{6}$\n\n\n\n## Series\n\n\n```python\nx = Symbol('x')\nf = Function('f')(x)\nseries(f, x)\n```\n\n\n\n\n$\\displaystyle f{\\left(0 \\right)} + x \\left. \\frac{d}{d x} f{\\left(x \\right)} \\right|_{\\substack{ x=0 }} + \\frac{x^{2} \\left. \\frac{d^{2}}{d x^{2}} f{\\left(x \\right)} \\right|_{\\substack{ x=0 }}}{2} + \\frac{x^{3} \\left. \\frac{d^{3}}{d x^{3}} f{\\left(x \\right)} \\right|_{\\substack{ x=0 }}}{6} + \\frac{x^{4} \\left. \\frac{d^{4}}{d x^{4}} f{\\left(x \\right)} \\right|_{\\substack{ x=0 }}}{24} + \\frac{x^{5} \\left. \\frac{d^{5}}{d x^{5}} f{\\left(x \\right)} \\right|_{\\substack{ x=0 }}}{120} + O\\left(x^{6}\\right)$\n\n\n\nTo change the point around which the function is expanded, we specify $x_0$ argument -\n\n\n```python\nx0 = Symbol('{x_0}')\nf.series(x, x0, n=2)\n```\n\n\n\n\n$\\displaystyle f{\\left({x_0} \\right)} + \\left(x - {x_0}\\right) \\left. \\frac{d}{d \\xi_{1}} f{\\left(\\xi_{1} \\right)} \\right|_{\\substack{ \\xi_{1}={x_0} }} + O\\left(\\left(x - {x_0}\\right)^{2}; x\\rightarrow {x_0}\\right)$\n\n\n\n\n```python\nf.series(x, x0, n=2).removeO()\n```\n\n\n\n\n$\\displaystyle \\left(x - {x_0}\\right) \\left. \\frac{d}{d \\xi_{1}} f{\\left(\\xi_{1} \\right)} \\right|_{\\substack{ \\xi_{1}={x_0} }} + f{\\left({x_0} \\right)}$\n\n\n\nFor specified functions -\n\n\n```python\nsin(x).series()\n```\n\n\n\n\n$\\displaystyle x - \\frac{x^{3}}{6} + \\frac{x^{5}}{120} + O\\left(x^{6}\\right)$\n\n\n\n\n```python\ncos(x).series()\n```\n\n\n\n\n$\\displaystyle 1 - \\frac{x^{2}}{2} + \\frac{x^{4}}{24} + O\\left(x^{6}\\right)$\n\n\n\n\n```python\nexp(x).series()\n```\n\n\n\n\n$\\displaystyle 1 + x + \\frac{x^{2}}{2} + \\frac{x^{3}}{6} + \\frac{x^{4}}{24} + \\frac{x^{5}}{120} + O\\left(x^{6}\\right)$\n\n\n\n\n```python\n(1/(1 + x)).series()\n```\n\n\n\n\n$\\displaystyle 1 - x + x^{2} - x^{3} + x^{4} - x^{5} + O\\left(x^{6}\\right)$\n\n\n\nFor arbitrary expressions of symbols and functions, which in general can also be evaluated.\n\n\n```python\nexpr = cos(x)/(1 + sin(x*y))\nexpr.series(x, n=4)\n```\n\n\n\n\n$\\displaystyle 1 - x y + x^{2} \\left(y^{2} - \\frac{1}{2}\\right) + x^{3} \\left(- \\frac{5 y^{3}}{6} + \\frac{y}{2}\\right) + O\\left(x^{4}\\right)$\n\n\n\n\n```python\nexpr.series(y, n=4)\n```\n\n\n\n\n$\\displaystyle \\cos{\\left(x \\right)} - x y \\cos{\\left(x \\right)} + x^{2} y^{2} \\cos{\\left(x \\right)} - \\frac{5 x^{3} y^{3} \\cos{\\left(x \\right)}}{6} + O\\left(y^{4}\\right)$\n\n\n\n## Limits\n\nIn SymPy, limits can be evaluated using the `sympy.limit` function, which takes an expression, a symbol it depends on, as well as the value that the symbol approaches in the limit. \n\n\n```python\nlimit(sin(x)/x, x, 0)\n```\n\n\n\n\n$\\displaystyle 1$\n\n\n\n\n```python\nf = Function('f')\nx, h = symbols('x, h')\ndiff_limit = (f(x + h) - f(x))/h\nlimit(diff_limit.subs(f, cos), h, 0)\n```\n\n\n\n\n$\\displaystyle - \\sin{\\left(x \\right)}$\n\n\n\n\n```python\nlimit(diff_limit.subs(f, sin), h, 0)\n```\n\n\n\n\n$\\displaystyle \\cos{\\left(x \\right)}$\n\n\n\n## Sums and Products\n\n\n```python\nn = symbols('n', integer=True)\nx = Sum(1/n**2, (n, 1, oo))\nx\n```\n\n\n\n\n$\\displaystyle \\sum_{n=1}^{\\infty} \\frac{1}{n^{2}}$\n\n\n\n\n```python\nx.doit()\n```\n\n\n\n\n$\\displaystyle \\frac{\\pi^{2}}{6}$\n\n\n\n\n```python\nx = Product(n, (n, 1, 7))\nx\n```\n\n\n\n\n$\\displaystyle \\prod_{n=1}^{7} n$\n\n\n\n\n```python\nx.doit()\n```\n\n\n\n\n$\\displaystyle 5040$\n\n\n\n# Equations\n\n\n```python\nx = Symbol('x')\nsolve(x**2 + 2*x -3)\n```\n\n\n\n\n [-3, 1]\n\n\n\n\n```python\na, b, c, x = symbols('a, b, c, x')\nsolve(a*x**2 + b*x + c, x)\n```\n\n\n\n\n [(-b + sqrt(-4*a*c + b**2))/(2*a), -(b + sqrt(-4*a*c + b**2))/(2*a)]\n\n\n\nTrigonometric Functions -\n\n\n```python\nsolve(sin(x) - cos(x), x)\n```\n\n\n\n\n [-3*pi/4, pi/4]\n\n\n\nSolving a system of equations for more than one unknown variable in SymPy is a straightforward generalization of the procedure used for univariate equations. Instead of passing a single expression as first argument to `sympy.solve`, a list of expressions that represent the system of equations is used, and in this case the second argument should be a list of symbols to solve for. \n\n\n```python\neq1 = x + 2*y -1\neq2 = x - y + 1\n\nsolve([eq1, eq2], [x, y], dict=True)\n```\n\n\n\n\n [{x: -1/3, y: 2/3}]\n\n\n\n\n```python\neq1 = x**2 - y\neq2 = y**2 - x\n\nsols = solve([eq1, eq2], [x, y], dict=True)\nsols\n```\n\n\n\n\n [{x: 0, y: 0},\n {x: 1, y: 1},\n {x: (-1/2 - sqrt(3)*I/2)**2, y: -1/2 - sqrt(3)*I/2},\n {x: (-1/2 + sqrt(3)*I/2)**2, y: -1/2 + sqrt(3)*I/2}]\n\n\n\nVerification -\n\n\n```python\n[eq1.subs(sol).simplify() == 0 and eq2.subs(sol).simplify() == 0 for sol in sols]\n```\n\n\n\n\n [True, True, True, True]\n\n\n\n# Linear Algebra\n\n\n```python\nMatrix([1, 2])\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}1\\\\2\\end{matrix}\\right]$\n\n\n\n\n```python\nMatrix([ [1, 2 ] ])\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}1 & 2\\end{matrix}\\right]$\n\n\n\n\n```python\nMatrix( [[1, 2], [3, 4] ])\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}1 & 2\\\\3 & 4\\end{matrix}\\right]$\n\n\n\n\n```python\nMatrix(3, 4, lambda m, n: 10*m + n)\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}0 & 1 & 2 & 3\\\\10 & 11 & 12 & 13\\\\20 & 21 & 22 & 23\\end{matrix}\\right]$\n\n\n\n\n```python\na, b, c, d = symbols('a, b, c, d')\nM = Matrix([[a, b], [c, d] ] )\nM\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}a & b\\\\c & d\\end{matrix}\\right]$\n\n\n\n\n```python\nM * M\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}a^{2} + b c & a b + b d\\\\a c + c d & b c + d^{2}\\end{matrix}\\right]$\n\n\n\n\n```python\nx = Matrix(symbols(\"x_1, x_2\"))\nx\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}x_{1}\\\\x_{2}\\end{matrix}\\right]$\n\n\n\n\n```python\nM * x\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}a x_{1} + b x_{2}\\\\c x_{1} + d x_{2}\\end{matrix}\\right]$\n\n\n\n# Practical Examples\n\n## 1. Newton's Law of Cooling\n### By Analytical Way using SymPy\n$$\\frac{dT(t)}{dt} = k(T(t) - T_a)$$\nat $t=0$, $T(0)=T_0$.\n\n\n```python\nfrom sympy import *\n```\n\n\n```python\nT, Ta, T0, k, t = symbols('T, T_a, T_0, k, t')\nT = Function('T')\ndiff_eq = Eq(T(t).diff(t),-k*(T(t) - Ta))\ndiff_eq\n```\n\n\n\n\n$\\displaystyle \\frac{d}{d t} T{\\left(t \\right)} = - k \\left(- T_{a} + T{\\left(t \\right)}\\right)$\n\n\n\n\n```python\nsol = dsolve(diff_eq)\nsol\n```\n\n\n\n\n$\\displaystyle T{\\left(t \\right)} = C_{1} e^{- k t} + T_{a}$\n\n\n\n\n```python\nic = Eq(sol.rhs.subs(t, 0), T0)\nic\n```\n\n\n\n\n$\\displaystyle C_{1} + T_{a} = T_{0}$\n\n\n\n\n```python\nconst = solve(ic)\nconst\n```\n\n\n\n\n [{C1: T_0 - T_a}]\n\n\n\n\n```python\nfinal_sol = sol.subs(const[0])\nfinal_sol\n```\n\n\n\n\n$\\displaystyle T{\\left(t \\right)} = T_{a} + \\left(T_{0} - T_{a}\\right) e^{- k t}$\n\n\n\n\n```python\nT =lambdify([Ta, T0, k, t], final_sol.rhs)\nT\n```\n\n\n\n\n \n\n\n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nk = 0.5\nTa = 22\nT0 = 100\nt = np.linspace(0, 10, 100)\n\nfig, ax = plt.subplots(figsize=(8, 4))\nax.plot(t, T(Ta, T0, k, t), color='red', label=\"\"\"$T_a$ = %0.1f,\n$T_0$ = %0.1f,\n k = %0.2f\"\"\"%(Ta, T0, k))\nax.set_xlabel('Time ($t$) in sec.', fontsize=16)\nax.set_ylabel('Temperature ($T$) in $^{\\circ}C$', fontsize=16)\nax.set_title('Cooling Curve', fontsize=20)\n\n# removing top and right spines\nax.spines['right'].set_color('none')\nax.spines['top'].set_color('none')\n\n# move bottom and left spine to x = 0 and y = 0\nax.spines['bottom'].set_position(('data', 0))\nax.spines['left'].set_position(('data', 0))\n\nax.set_xticks(range(0, 11, 1))\nax.set_yticks(range(0, 110, 10))\n\nax.legend(frameon=False)\nax.grid(False)\n\n```\n\n\n\n## 2. Damped harmonic Oscillator\n$$\\frac{d^2 x(t)}{dt^2} + 2\\gamma \\omega_0 \\frac{d x(t)}{dt} + \\omega_0^2 x(t) = 0$$\nwhere $x(t)$ is the position of the oscillator at time $t$, $\\omega_0$ is the frequency of the oscillator in the undamped case and $\\gamma$ is the damping ratio.\n\n\n```python\nt, omega0, gamma = symbols('t, omega_0, gamma', positive=True)\nx = Function('x')\n\node = x(t).diff(t, 2) + 2*gamma*omega0*x(t).diff(t) + omega0**2 *x(t)\node\n```\n\n\n\n\n$\\displaystyle 2 \\gamma \\omega_{0} \\frac{d}{d t} x{\\left(t \\right)} + \\omega_{0}^{2} x{\\left(t \\right)} + \\frac{d^{2}}{d t^{2}} x{\\left(t \\right)}$\n\n\n\n\n```python\nEq(ode)\n```\n\n\n\n\n$\\displaystyle 2 \\gamma \\omega_{0} \\frac{d}{d t} x{\\left(t \\right)} + \\omega_{0}^{2} x{\\left(t \\right)} + \\frac{d^{2}}{d t^{2}} x{\\left(t \\right)} = 0$\n\n\n\n\n```python\node_sol = dsolve(Eq(ode))\node_sol\n```\n\n\n\n\n$\\displaystyle x{\\left(t \\right)} = C_{1} e^{\\omega_{0} t \\left(- \\gamma - \\sqrt{\\gamma - 1} \\sqrt{\\gamma + 1}\\right)} + C_{2} e^{\\omega_{0} t \\left(- \\gamma + \\sqrt{\\gamma - 1} \\sqrt{\\gamma + 1}\\right)}$\n\n\n\n#### Initial conditions:\n\n> 1. at time $t=0$, displacement of the oscillator, $x(t) = 1$\n1. at time $t=0$, velocity of the oscillator, $\\frac{d x(t)}{dt} = 0$\n\n\n```python\nic1 = x(t).subs(t, 0)\nic2 = x(t).diff(t).subs(t, 0)\nics = {ic1:1, ic2:0}\nics\n```\n\n\n\n\n {x(0): 1, Subs(Derivative(x(t), t), t, 0): 0}\n\n\n\n\n```python\neq1 = Eq(ode_sol.rhs.subs(t, 0), 1)\neq2 = Eq(ode_sol.rhs.diff(t).subs(t, 0), 0)\nconstants = solve([eq1, eq2])\nx_t_sol = ode_sol.subs(constants[0])\nx_t_sol\n\n```\n\n\n\n\n$\\displaystyle x{\\left(t \\right)} = \\left(- \\frac{\\gamma}{2 \\sqrt{\\gamma^{2} - 1}} + \\frac{1}{2}\\right) e^{\\omega_{0} t \\left(- \\gamma - \\sqrt{\\gamma - 1} \\sqrt{\\gamma + 1}\\right)} + \\left(\\frac{\\gamma}{2 \\sqrt{\\gamma^{2} - 1}} + \\frac{1}{2}\\right) e^{\\omega_{0} t \\left(- \\gamma + \\sqrt{\\gamma - 1} \\sqrt{\\gamma + 1}\\right)}$\n\n\n\n\n```python\nx_t_critical = limit(x_t_sol.rhs, gamma, 1)\nx_t_critical\n```\n\n\n\n\n$\\displaystyle \\left(\\omega_{0} t + 1\\right) e^{- \\omega_{0} t}$\n\n\n\n\n```python\nfig, ax = plt.subplots(figsize=(14, 8))\ntt = np.linspace(0, 3, 300)\nw0 = 2* np.pi\nfor g in [0.1, 0.5, 1, 2.0, 5.0]:\n if g == 1:\n x_t = lambdify(t, x_t_critical.subs({omega0:w0, gamma:g}), 'numpy')\n else:\n x_t = lambdify(t, x_t_sol.rhs.subs({omega0:w0, gamma:g}), 'numpy')\n ax.plot(tt, x_t(tt).real, label=\"$\\gamma = %.1f$\" % g )\nax.set_xlabel(r\"$t$\", fontsize=18)\nax.set_ylabel(r\"$x(t)$\", fontsize=18)\nax.set_title('Damped Harmonic Oscillator', fontsize=20)\n\n# removing top and right spines\nax.spines['right'].set_color('none')\nax.spines['top'].set_color('none')\n\n# move bottom and left spine to x = 0 and y = 0\nax.spines['bottom'].set_position(('data', 0))\nax.spines['left'].set_position(('data', 0))\n\nax.set_xticks(np.arange(0, 4, 1))\nax.set_yticks(np.arange(-1, 1.5, 0.5))\n\nax.legend(frameon=False)\nax.grid(False)\nplt.legend(frameon=False, loc='upper right')\nplt.grid(False)\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "1123d738327a49d335a8f220df4f7f281e8cfaf7", "size": 168341, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "_notebooks/SymPy.ipynb", "max_stars_repo_name": "SubirSarkar2021/CompPhyWithPython", "max_stars_repo_head_hexsha": "d7506f4b89f00cd8cb6dd6096d1d0ff652571e97", "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/SymPy.ipynb", "max_issues_repo_name": "SubirSarkar2021/CompPhyWithPython", "max_issues_repo_head_hexsha": "d7506f4b89f00cd8cb6dd6096d1d0ff652571e97", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-02-26T10:50:49.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-26T10:50:49.000Z", "max_forks_repo_path": "_notebooks/SymPy.ipynb", "max_forks_repo_name": "SubirSarkar2021/CompPhyWithPython", "max_forks_repo_head_hexsha": "d7506f4b89f00cd8cb6dd6096d1d0ff652571e97", "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": 47.2337261504, "max_line_length": 72752, "alphanum_fraction": 0.7438235486, "converted": true, "num_tokens": 8116, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897542390751, "lm_q2_score": 0.9252299643080207, "lm_q1q2_score": 0.870446870735971}} {"text": "```python\n\nfrom sympy import *\nt, dt, n, w = symbols('t dt n w', real=True)\n\n# Finite difference operators\n\ndef D_t_forward(u):\n return (u(t + dt) - u(t))/dt\n\ndef D_t_backward(u):\n return (u(t) - u(t-dt))/dt\n\ndef D_t_centered(u):\n return (u(t + dt/2) - u(t-dt/2))/dt\n\ndef D_2t_centered(u):\n return (u(t + dt) - u(t-dt))/(2*dt)\n\ndef D_t_D_t(u):\n return (u(t + dt) - 2*u(t) + u(t-dt))/(dt**2)\n\n\nop_list = [D_t_forward, D_t_backward,\n D_t_centered, D_2t_centered, D_t_D_t]\n\ndef ft1(t):\n return t\n\ndef ft2(t):\n return t**2\n\ndef ft3(t):\n return t**3\n\ndef f_expiwt(t):\n return exp(I*w*t)\n\ndef f_expwt(t):\n return exp(w*t)\n\nfunc_list = [ft1, ft2, ft3, f_expiwt, f_expwt]\nimport inspect\n\nfor func in func_list:\n print(('\\n--- Function:', inspect.getsource(func), '---'))\n for op in op_list:\n print(('\\nOperator:', op.__name__))\n f = func\n e = op(f)\n e = simplify(expand(e))\n print(('simplify(expand(operator(function)):', e))\n if func in [f_expiwt, f_expwt]:\n e = e/f(t)\n e = e.subs(t, n*dt)\n print(('t -> n*dt:', expand(e)))\n print(('factor(simplify(expand(e))):', factor(simplify(expand(e)))))\n \n \n# https://github.com/sympy/sympy/wiki/Generating-tables-of-derivatives-and-integrals\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "7970eec7bd3457e14de5028243c33bbaef3adc02", "size": 2504, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Data Science and Machine Learning/Machine-Learning-In-Python-THOROUGH/EXAMPLES/FINITE_ELEMENTS/INTRO/SRC/13_DIFFOP_LIB.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": "Data Science and Machine Learning/Machine-Learning-In-Python-THOROUGH/EXAMPLES/FINITE_ELEMENTS/INTRO/SRC/13_DIFFOP_LIB.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": "Data Science and Machine Learning/Machine-Learning-In-Python-THOROUGH/EXAMPLES/FINITE_ELEMENTS/INTRO/SRC/13_DIFFOP_LIB.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": 25.04, "max_line_length": 90, "alphanum_fraction": 0.4568690096, "converted": true, "num_tokens": 436, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9539660936744719, "lm_q2_score": 0.91243616285804, "lm_q1q2_score": 0.8704331620090087}} {"text": "```python\nfrom sympy import *\ninit_printing()\n\n'''\nr_GEO = 36000 + 6371 KM\nr_LEO = 2000 + 6371 KM\n\nG = 6.674e-11\nMe = 5.972e24\n'''\n\nM, E = symbols(\"M E\", Functions = True)\ne_c, a, G, M_e, r, mu = symbols(\"e_c a G M_e r mu\", Contstants = True)\nT_circular, T_elliptical, T_GEO, T_GTO, T_LEO, r_LEO, r_GEO, T_tot = symbols(\"T_circular T_elliptical T_GEO T_GTO T_LEO r_LEO r_GEO T_tot\", Constants = True)\nt, x, y, Y = symbols(\"t x y Y\", Variables = True)\n\nmu_calculated = (6.674e-11 * 5.972e24)\n```\n\nThe orbital period of a circular Orbit:\n\n\n```python\nEq(T_circular, 2*pi*sqrt(r**3 / mu))\n```\n\nWhere mu is: \n\n\n```python\nEq(mu, G*M_e)\n```\n\nThen, the GEO's orbital period in hours is:\n\n\n```python\nr_GEO_Calculated = (36000 + 6371)*1000\nT_GEO_Calculated = 2*pi*sqrt(r_GEO_Calculated**3 / mu_calculated)\nEq(T_GEO, T_GEO_Calculated.evalf()/60/60)\n```\n\nAnd the LEO's orbital period in hours is:\n\n\n```python\nr_LEO_Calculated = (2000 + 6371)*1000\nT_LEO_Calculated = 2*pi*sqrt(r_LEO_Calculated**3 / mu_calculated)\nEq(T_LEO, T_LEO_Calculated.evalf()/60/60)\n```\n\n_____________________________________________\n# Finding the GTO.\nThe goal is to get both 'e' (the eccentricity of our GTO) and 'a' (its semi-major axis). So, we need 2 eqns.\n\nThe equation of the GEO (A circle equation):\n\n\n```python\ngeo = Eq(y**2, r**2-x**2)\ngeo\n```\n\nThe equation of the GTO (An ellipse equation):\n\n\n```python\ngto = Eq(((x+a*e_c)**2/a**2)+(y**2/a**2*(1-e_c**2)), 1)\ngto\n```\n\nWe Wanna solve these two eqns to get the semi-major axis of our GTO and the raduis of our LEO.\n\nfirst, substitute the GEO's eqn in the GTO's eqn.\n\n\n```python\ntoSolve = gto.subs({y**2:geo.rhs})\ntoSolve\n```\n\nNow we can solve for x.\n\n\n```python\nsolX = solveset(toSolve, x)\nsolX\n```\n\nNow we can calculate the y coordinate for each x.\n\n\n```python\nsolY1 = solveset(Eq(geo.lhs, geo.rhs.subs({x:list(solX)[0]})), y)\nsolY1\n```\n\n\n```python\nsolY2 = solveset(Eq(geo.lhs, geo.rhs.subs({x:list(solX)[1]})), y)\nsolY2\n```\n\nWe have 4 different possible points for the intersection between a circle and an ellipse, but the intersection between the GEO and the GTO is going to be at only one point with an x coordinate of '-r_GEO' (the radius of the GEO). \n\nNow, we can get the first eqn.\n\n\n```python\ngeoAndGtoIntersection = solveset(Eq(list(solX)[0], -r_GEO).subs({r:r_GEO}), a)\ngeoAndGtoIntersection\n```\n\nSurbrisingly, there are 2 possible values for a. But we're not interrested in the negative value. So our first eqn is:\n\n\n```python\neqn1 = Eq(a, list(list(geoAndGtoIntersection.args)[2])[1])\neqn1\n```\n\nTo get another eqn, we can do the same but this time with the LOE.\n\nThe intersection between our LEO and GTO is exactly at the x coordinate of 'r_LEO'.\n\n\n```python\ngtoAndLeoIntersection = solveset(Eq(list(solX)[1], r).subs({r:r_LEO}), a)\ngtoAndLeoIntersection\n```\n\nAgain, there are 2 possible values for 'r_LEO' but we need the positive one.\n\n\n```python\neqn2 = Eq(a, list(list(gtoAndLeoIntersection.args)[2])[0])\neqn2\n```\n\nThis is the positive because 0 < e_c < 1.\n\nNow, we have 2 eqns and 2 variables. And we're ready to get 'a' and 'e_c'\n\n\n```python\ne_c_Exp = Eq(e_c, solveset(eqn1.subs({a:eqn2.rhs, r_GEO:r_GEO_Calculated, r_LEO:r_LEO_Calculated}), e_c).args[0])\ne_c_Calculated = e_c_Exp.rhs\ne_c_Exp\n```\n\n\n```python\ns = solveset(eqn2.subs({r_LEO:r_LEO_Calculated, e_c:e_c_Calculated})).args[0]\na_Exp = Eq(a, s)\na_Calculated = a_Exp.rhs\na_Exp\n```\n\nThere's another way for finding 'a'.\n\n\n```python\np1 = plot(sqrt(r_GEO_Calculated**2-x**2), -sqrt(r_GEO_Calculated**2-x**2), sqrt(r_LEO_Calculated**2-x**2), -sqrt(r_LEO_Calculated**2-x**2), sqrt(a_Calculated**2*(1-e_c_Calculated**2)*(1-((x+a_Calculated*e_c_Calculated)**2/a_Calculated**2))), -sqrt(a_Calculated**2*(1-e_c_Calculated**2)*(1-((x+a_Calculated*e_c_Calculated)**2/a_Calculated**2))),(x, -5*10**7, 5*10**7),xlim = (-7.5*10**7, 7.5*10**7), ylim=((-5*10**7, 5*10**7)))\n```\n\nFrom the geometry we can say that:\n\n\n```python\nEq(a, (r_LEO + r_GEO)/2)\n```\n\nThis could've saved us a lot of math work :)\n\n__________________________________\n# Now let's calculate the periods.\n\nThe orbital period of an elliptical orbit is:\n\n\n```python\nEq(T_elliptical, 2*pi*sqrt(a**3 / mu))\n```\n\n\n```python\nT_GTO_Calculated = 2*pi*sqrt(a_Calculated**3/mu_calculated)\nEq(T_GTO, T_GTO_Calculated.evalf()/60/60)\n```\n\nSo, the total time required to put our satellite in a GEO using Hohmann transfer is:\n\n\n```python\nEq(T_tot, T_GTO / 2 + T_LEO / 2)\n```\n\nThe total time required to put our satellite in a GEO of a 36,000 Kilometers above sea level in hours is:\n\n\n```python\nEq(T_tot, (T_GTO_Calculated / 2 + T_LEO_Calculated / 2).evalf()/60/60)\n```\n", "meta": {"hexsha": "1e53111d5c0a13baee4c6e7b73cb80cf171ffb77", "size": 108030, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Python Notebooks/Hohmann Transfer.ipynb", "max_stars_repo_name": "Yaamani/Satellite-Simulation", "max_stars_repo_head_hexsha": "f9b3363e79b62a30724c53c99fdb097a68ff324d", "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 Notebooks/Hohmann Transfer.ipynb", "max_issues_repo_name": "Yaamani/Satellite-Simulation", "max_issues_repo_head_hexsha": "f9b3363e79b62a30724c53c99fdb097a68ff324d", "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 Notebooks/Hohmann Transfer.ipynb", "max_forks_repo_name": "Yaamani/Satellite-Simulation", "max_forks_repo_head_hexsha": "f9b3363e79b62a30724c53c99fdb097a68ff324d", "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": 125.7625145518, "max_line_length": 21864, "alphanum_fraction": 0.8483013978, "converted": true, "num_tokens": 1628, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741295151718, "lm_q2_score": 0.9136765240013699, "lm_q1q2_score": 0.870344619509053}} {"text": "# EIGENVALUES and EIGENVECTORS\n## Prachee Javiya\n---\n# Notes\n\n * The most basic equation for eigenvalues is $Ax=\\lambda x$. The number $\\lambda$ is an eigenvalue of A.\n * To solve the above equation, calculate the roots of $(A-\\lambda I)x=0$\n * Calculate the eigenvectors corresponding to an eigenvalue\n * The eigenvectors \"x\" do NOT change direction when you multiply by A.\n * Eigenvectors make understanding linear transformations easy.\n * The eigenvalue $\\lambda$ tells whether the special vector x is stretched or shrunk or reversed or left unchanged-when it is multiplied by A\n * When $\\lambda$ is 0, the vector x lies in the nullspace of A.\n * If A is the identity matrix, every vector has Ax= x. All vectors are eigenvectors of I.\n * |A-$\\lambda$I|=0 ,always. Reason:For a particular value of $\\lambda$, the vector Ax is parallel to $\\lambda$x. \n #### Calculating eigenvectors and eigenvalues :\n\n* The 2x2 identity matrix has $\\lambda$=1 which occurs twice.\n\n\n```python\nimport sympy as sp\n```\n\n\n```python\nA=sp.Matrix([[1,0],[0,1]])\nA.eigenvals()\n```\n\n\n\n\n {1: 2}\n\n\n\n* Eigenvalues for a 2x2 permutation matrix \n * any x in the plane is unchanged by P. The equation hence formed is Px=x\n * Any x perpendicular to the plane, equation becomes Px=0\n\n\n```python\nB=sp.Matrix([[0,1],[1,0]])\nB.eigenvals()\n```\n\n\n\n\n {-1: 1, 1: 1}\n\n\n\nLet λ be an eigenvalue of P for the eigenvector v. You have $\\lambda^2v=P^2v=Pv=\\lambda v$. Because v≠0 it must be $\\lambda^2=\\lambda$. The solutions of the last equation are λ1=0 and λ2=1. Those are the only possible eigenvalues the projection might have.\n\n### Properties of eigenvectors and eigenvalues:\n - Trace of the matrix A is equal to the sum of its eigenvalues.
\n - Additive property for calculating Evalues of two matrices does not hold. \n >$ Ax=\\lambda x$ \n >$ Bx=\\gamma x$ \n >$ (A+B)x\\neq (\\lambda+\\gamma) x $ \n - Because it is not necessary that the vector x will be same for both matrices A and B\n - A matrix A will have zero as an eigenvalue if and only if it is singular.
\n - Eigenvalue and eigenvector of $A^{-1}$ $$ Av=\\lambda v$$ Multiplying both sides by $A^{-1}$, we get, $$ v=\\lambda A^{-1}v$$ $$=A^{-1}v=\\frac{1}{\\lambda} v $$ \n \n**NOTE** :
\n When $\\lambda=0, A^{-1}$ does not exist.\n\n- When we take a multiple of I (eg 3I) the eigenvalues get multiplied by a factor 3 and the eigenvectors remain **same**\n\n\n```python\nC=sp.Matrix([[3,1],[1,3]])\nC.eigenvals()\n```\n\n\n\n\n {4: 1, 2: 1}\n\n\n\n\n```python\nC.eigenvects()\n```\n\n\n\n\n [(2, 1, [Matrix([\n [-1],\n [ 1]])]), (4, 1, [Matrix([\n [1],\n [1]])])]\n\n\n\n* Eigenvalues of anti-symmetric matrices are purely imaginary\n* Repeated eigenvalues leads to shortage of eigenvectors(not enough linearly independant eigenvectors)
\n _DEGENERATE MATRIX_\n\n\n```python\nD=sp.Matrix([[3,1],[0,3]])\nD.eigenvals()\n```\n\n\n\n\n {3: 2}\n\n\n\n\n```python\nD.eigenvects()\n```\n\n\n\n\n [(3, 2, [Matrix([\n [1],\n [0]])])]\n\n\n\n### DIAGONALISATION \n##### A matrix is diagonalisable when there exists a matrix S and $\\Lambda$ such that $$A=S\\Lambda S^{-1}$$\n---\n* Λ is the diagonal matrix, with the entries being the corresponding eigenvalues of A\n* $AS=S\\Lambda$ (Be careful when the matrix S is imaginary,conjugate terms will take part, $A^H={A^T}^C$,where $A^H$ is a hermetian matrix\n* If a square matrix A has a full set of eigenvectors, then the matrix can be constructed by this formula.\n* Multiply by $S^{-1}$ on both sides to get the diagonal matrix i.e. $$AS=S \\Lambda $$ $$S^{-1}AS=\\Lambda$$ \n\n_Diagonalizability is concerned with the number of eigenvectors - too few or enough_\n\n#### AM/GM\n---\nAM(Algebraic multiplicity) is the number of times an **eigenvalue** appears in the characteristic equation.
\nGM(Geometric multiplicity) is the number of **eigenvectors** corresponding to an eigenvalue.\n\n### Real Symmetric Matrices-Eigenvalues\n---\n- When $A=A^T$ for any matrix A, it is known as a symmetric matrix\n- Evalues for a symmetric matrix are real\n- Eigenvectors of real symmetric matrices are **orthogonal** \n$\\therefore$ the matrix S will have orthonormal columns
\nAnd, $$A=Q\\Lambda Q^{-1}$$\n- For orthonormal columns, $A^T=A^{-1}$\n$$\\therefore A=Q\\Lambda Q^T$$\n- Every symmetric matrix is a combination of perpendicular projection matrices\n\n### Difference equation\n---\n$$u_{k+1}=Au_{k}$$\nGiven vector $u_0$,
\n$u_1=Au_0, u_2=A^2u_0.... u_k=A^ku_0$\nTo solve, $$u_0=c_1x_1+c_2x_2+..+c_nx_n=Sc$$\n$$Au_0=\\lambda_1x_1+c_2\\lambda_2x_2+..+c_n\\lambda_nx_n$$ \n$$A^{100}u_0=\\lambda_1^{100}x_1+c_2\\lambda_2^{100}x_2+..+c_n\\lambda_n^{100}x_n$$\n$$=\\Lambda^{100}Sc$$\n\n## Fibonacci equation\n---\n$$F_{k+2}=F_{k+1}+F_k$$\n$$F_{k+1}=F_{k+1}$$\n$$ u_k=\n\\begin{bmatrix}\nF_{k+1}\\\\\nF_k\n\\end{bmatrix}\n$$\n$$u_{k+1}=\n\\begin{bmatrix}\n1 & 1\\\\ 1 & 0\n\\end{bmatrix}u_k\n$$\n\n## Positive Definiteness of symmetric matrix\nHow to tell if a matrix is positive symmetric?\n$$\\begin{bmatrix}\na & b \\\\\nc & d\n\\end{bmatrix}\n$$\n 1. Eigenvalues are positive\n 2. $a>0 , ac-b^2>0$\n 3. $x^TAx>0$
\n \n**Borderline case example,**\n\n\n```python\nimport sympy as sp\nA=sp.Matrix([[2,6],[6,18]])\nA\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}2 & 6\\\\6 & 18\\end{matrix}\\right]$\n\n\n\nTesting:\n$$\n\\begin{bmatrix}\nx_1 & x_2\n\\end{bmatrix}\n\\begin{bmatrix}\n2 & 6\\\\\n6 & 18\n\\end{bmatrix}\n\\begin{bmatrix}\nx_1 \\\\\nx_2\n\\end{bmatrix}\n$$\n\n$$=2x_1^2+12x_1x_2+18x_2^2$$\n\nQuadratic form : $ax^2+2bxy+cy^2$
\n**IF THE ABOVE QUADRATIC IS POSITIVE FOR ALL x1,x2, THEN A IS POSITIVE DEFINITE**
\nIn the above case, the matrix is definite psitive for all values greater than 18\n\n### Left Inverse/Right inverse and Pseude inverse\n---\n- Left Inverse\n - For a full rank(columns are independant) mxn matrix, $(A^TA)^{-1}A^T$ is the left inverse of the matrix A.\n - A rectangular matrix cannot have two sided inverse because $m \\neq n $ and there will be some free variables around\n- Right Inverse \n - $A^T(AA^T)^{-1}$ is the right inverse.$AA^T(AA^T)^{-1}=I$)\n - We have independant rows and $N(A^T)={0}$.\n - Rank r=mIntroduction

\n\n

From

\n\n

What is Symbolic Computation?

\n\n

Symbolic computation deals with the computation of mathematical objects symbolically. This means that the mathematical objects are represented exactly, not approximately, and mathematical expressions with unevaluated variables are left in symbolic form.

\n\n

Let's take an example. Say we wanted to use the built-in Python functions to compute square roots. We might do something like this

\n\n\n```julia\n >>> import math\n >>> math.sqrt(9)\n 3.0\n```\n\n
In Julia:
\n\n
    \n
  • Of course, sqrt is already there:

    \n
  • \n
\n\n\n```julia\nsqrt(9)\n```\n\n\n\n\n 3.0\n\n\n\n
\n\n

9 is a perfect square, so we got the exact answer, 3. But suppose we computed the square root of a number that isn't a perfect square

\n\n\n```julia\n >>> math.sqrt(8)\n 2.82842712475\n```\n\n
In Julia:
\n\n\n```julia\nsqrt(8)\n```\n\n\n\n\n 2.8284271247461903\n\n\n\n
\n\n

Here we got an approximate result. 2.82842712475 is not the exact square root of 8 (indeed, the actual square root of 8 cannot be represented by a finite decimal, since it is an irrational number). If all we cared about was the decimal form of the square root of 8, we would be done.

\n\n

But suppose we want to go further. Recall that $\\sqrt{8} = \\sqrt{4\\cdot 2} = 2\\sqrt{2}$. We would have a hard time deducing this from the above result. This is where symbolic computation comes in. With a symbolic computation system like SymPy, square roots of numbers that are not perfect squares are left unevaluated by default

\n\n\n```julia\n >>> import sympy\n >>> sympy.sqrt(3)\n sqrt(3)\n```\n\n
In Julia:
\n\n\n```julia\nusing SymPy\nsympy.sqrt(3)\n```\n\n\n\n\n\\begin{equation*}\\sqrt{3}\\end{equation*}\n\n\n\n
    \n
  • When SymPy is loaded, the sqrt function is overloaded for symbolic objects, so this could also be done through:

    \n
  • \n
\n\n\n```julia\nsqrt(Sym(3))\n```\n\n\n\n\n\\begin{equation*}\\sqrt{3}\\end{equation*}\n\n\n\n
\n\n

Furthermore–-and this is where we start to see the real power of symbolic computation–-symbolic results can be symbolically simplified.

\n\n\n```julia\n >>> sympy.sqrt(8)\n 2*sqrt(2)\n```\n\n
In Julia:
\n\n\n```julia\nsympy.sqrt(8)\n```\n\n\n\n\n\\begin{equation*}2 \\sqrt{2}\\end{equation*}\n\n\n\n
\n\n

A More Interesting Example

\n\n

The above example starts to show how we can manipulate irrational numbers exactly using SymPy. But it is much more powerful than that. Symbolic computation systems (which by the way, are also often called computer algebra systems, or just CASs) such as SymPy are capable of computing symbolic expressions with variables.

\n\n

As we will see later, in SymPy, variables are defined using symbols. Unlike many symbolic manipulation systems, variables in SymPy must be defined before they are used (the reason for this will be discussed in the :ref:next section <tutorial-gotchas-symbols>).

\n\n

Let us define a symbolic expression, representing the mathematical expression x + 2y.

\n\n\n```julia\n >>> from sympy import symbols\n >>> x, y = symbols('x y')\n >>> expr = x + 2*y\n >>> expr\n x + 2*y\n```\n\n
In Julia:
\n\n
    \n
  • the command from sympy import * is essentially run (only functions are \"imported\", not all objects), so this becomes the same after adjusting the quotes:

    \n
  • \n
\n\n\n```julia\nx, y = symbols(\"x y\")\nexpr = x + 2*y\nexpr\n```\n\n\n\n\n\\begin{equation*}x + 2 y\\end{equation*}\n\n\n\n
\n\n

Note that we wrote x + 2*y just as we would if x and y were ordinary Python variables. But in this case, instead of evaluating to something, the expression remains as just x + 2*y. Now let us play around with it:

\n\n\n```julia\n >>> expr + 1\n x + 2*y + 1\n >>> expr - x\n 2*y\n```\n\n
In Julia:
\n\n\n```julia\nexpr + 1\n```\n\n\n\n\n\\begin{equation*}x + 2 y + 1\\end{equation*}\n\n\n\n\n```julia\nexpr - x\n```\n\n\n\n\n\\begin{equation*}2 y\\end{equation*}\n\n\n\n
\n\n

Notice something in the above example. When we typed expr - x, we did not get x + 2*y - x, but rather just 2*y. The x and the -x automatically canceled one another. This is similar to how sqrt(8) automatically turned into 2*sqrt(2) above. This isn't always the case in SymPy, however:

\n\n\n```julia\n >>> x*expr\n x*(x + 2*y)\n```\n\n
In Julia:
\n\n\n```julia\nx*expr\n```\n\n\n\n\n\\begin{equation*}x \\left(x + 2 y\\right)\\end{equation*}\n\n\n\n
\n\n

Here, we might have expected x(x + 2y) to transform into x^2 + 2xy, but instead we see that the expression was left alone. This is a common theme in SymPy. Aside from obvious simplifications like x - x = 0 and \\sqrt{8} = 2\\sqrt{2}, most simplifications are not performed automatically. This is because we might prefer the factored form x(x + 2y), or we might prefer the expanded form x^2 + 2xy. Both forms are useful in different circumstances. In SymPy, there are functions to go from one form to the other

\n\n\n```julia\n >>> from sympy import expand, factor\n >>> expanded_expr = expand(x*expr)\n >>> expanded_expr\n x**2 + 2*x*y\n >>> factor(expanded_expr)\n x*(x + 2*y)\n```\n\n
In Julia:
\n\n\n```julia\nexpanded_expr = expand(x*expr)\nexpanded_expr\n```\n\n\n\n\n\\begin{equation*}x^{2} + 2 x y\\end{equation*}\n\n\n\n\n```julia\nfactor(expanded_expr)\n```\n\n\n\n\n\\begin{equation*}x \\left(x + 2 y\\right)\\end{equation*}\n\n\n\n
\n\n

The Power of Symbolic Computation

\n\n

The real power of a symbolic computation system such as SymPy is the ability to do all sorts of computations symbolically. SymPy can simplify expressions, compute derivatives, integrals, and limits, solve equations, work with matrices, and much, much more, and do it all symbolically. It includes modules for plotting, printing (like 2D pretty printed output of math formulas, or \\LaTeX), code generation, physics, statistics, combinatorics, number theory, geometry, logic, and more. Here is a small sampling of the sort of symbolic power SymPy is capable of, to whet your appetite.

\n\n\n```julia\n >>> from sympy import *\n >>> x, t, z, nu = symbols('x t z nu')\n```\n\n
In Julia:
\n\n
    \n
  • again, the functions in the sympy module are already imported:

    \n
  • \n
\n\n\n```julia\nx, t, z, nu = symbols(\"x t z nu\")\n```\n\n\n\n\n (x, t, z, nu)\n\n\n\n
\n\n

This will make all further examples pretty print with unicode characters.

\n\n\n```julia\n >>> init_printing(use_unicode=True)\n```\n\n
In Julia:
\n\n
    \n
  • The printing in Julia is controlled by show and the appropriate MIME type.

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

Take the derivative of $\\sin{(x)}e^x$.

\n\n\n```julia\n >>> diff(sin(x)*exp(x), x)\n x x\n ℯ ⋅sin(x) + ℯ ⋅cos(x)\n```\n\n
In Julia:
\n\n\n```julia\ndiff(sin(x)*exp(x), x)\n```\n\n\n\n\n\\begin{equation*}e^{x} \\sin{\\left (x \\right )} + e^{x} \\cos{\\left (x \\right )}\\end{equation*}\n\n\n\n
\n\n

Compute $\\int(e^x\\sin{(x)} + e^x\\cos{(x)})\\,dx$.

\n\n\n```julia\n >>> integrate(exp(x)*sin(x) + exp(x)*cos(x), x)\n x\n ℯ ⋅sin(x)\n```\n\n
In Julia:
\n\n\n```julia\nintegrate(exp(x)*sin(x) + exp(x)*cos(x), x)\n```\n\n\n\n\n\\begin{equation*}e^{x} \\sin{\\left (x \\right )}\\end{equation*}\n\n\n\n
\n\n

Compute $\\int_{-\\infty}^\\infty \\sin{(x^2)}\\,dx$.

\n\n\n```julia\n >>> integrate(sin(x**2), (x, -oo, oo))\n √2⋅√π\n ─────\n 2\n```\n\n
In Julia:
\n\n
    \n
  • In Julia ** is ^:

    \n
  • \n
\n\n\n```julia\nintegrate(sin(x^2), (x, -oo, oo))\n```\n\n\n\n\n\\begin{equation*}\\frac{\\sqrt{2} \\sqrt{\\pi}}{2}\\end{equation*}\n\n\n\n
\n\n

Find $\\lim_{x\\to 0}\\frac{\\sin{(x)}}{x}$.

\n\n\n```julia\n >>> limit(sin(x)/x, x, 0)\n 1\n```\n\n
In Julia:
\n\n\n```julia\nlimit(sin(x)/x, x, 0)\n```\n\n\n\n\n\\begin{equation*}1\\end{equation*}\n\n\n\n
\n\n

Solve $x^2 - 2 = 0$.

\n\n\n```julia\n >>> solve(x**2 - 2, x)\n [-√2, √2]\n```\n\n
In Julia:
\n\n\n```julia\nsolve(x^2 - 2, x)\n```\n\n\n\n\n\\[ \\left[ \\begin{array}{r}- \\sqrt{2}\\\\\\sqrt{2}\\end{array} \\right] \\]\n\n\n\n
\n\n

Solve the differential equation y'' - y = e^t.

\n\n\n```julia\n >>> y = Function('y')\n >>> dsolve(Eq(y(t).diff(t, t) - y(t), exp(t)), y(t))\n -t ⎛ t⎞ t\n y(t) = C₂⋅ℯ + ⎜C₁ + ─⎟⋅ℯ\n ⎝ 2⎠\n```\n\n
In Julia:
\n\n
    \n
  • Function is not a function, so is not exported. We must qualify its use:

    \n
  • \n
\n\n\n```julia\ny = sympy.Function(\"y\")\ndsolve(Eq(y(t).diff(t, t) - y(t), exp(t)), y(t))\n```\n\n\n\n\n\\begin{equation*}y{\\left (t \\right )} = C_{2} e^{- t} + \\left(C_{1} + \\frac{t}{2}\\right) e^{t}\\end{equation*}\n\n\n\n
    \n
  • This is made more familiar looking with the SymFunction class:

    \n
  • \n
\n\n\n```julia\ny = SymFunction(\"y\")\ndsolve(y''(t) - y(t) - exp(t), y(t))\n```\n\n\n\n\n\\begin{equation*}y{\\left (t \\right )} = C_{2} e^{- t} + \\left(C_{1} + \\frac{t}{2}\\right) e^{t}\\end{equation*}\n\n\n\n
\n\n

Find the eigenvalues of \\left[\\begin{smallmatrix}1 & 2\\\\2 & 2\\end{smallmatrix}\\right].

\n\n\n```julia\n >>> Matrix([[1, 2], [2, 2]]).eigenvals()\n ⎧3 √17 √17 3 ⎫\n ⎨─ + ───: 1, - ─── + ─: 1⎬\n ⎩2 2 2 2 ⎭\n```\n\n
In Julia:
\n\n
    \n
  • Like Function, Matrix is not imported and its use must by qualified:

    \n
  • \n
\n\n\n```julia\nout = sympy.Matrix([[1, 2], [2, 2]]).eigenvals()\n```\n\n\n\n\n Dict{Any,Any} with 2 entries:\n -sqrt(17)/2 + 3/2 => 1\n 3/2 + sqrt(17)/2 => 1\n\n\n\n
    \n
  • This can be pretty printed if the keys become symbolic:

    \n
  • \n
\n\n\n```julia\nconvert(Dict{Sym, Any}, out)\n```\n\n\n\n\n\\begin{equation*}\\begin{cases}- \\frac{\\sqrt{17}}{2} + \\frac{3}{2} & \\text{=>} &1\\\\\\frac{3}{2} + \\frac{\\sqrt{17}}{2} & \\text{=>} &1\\\\\\end{cases}\\end{equation*}\n\n\n\n
\n\n

Rewrite the Bessel function $J_{\\nu}\\left(z\\right)$ in terms of the spherical Bessel function $j_\\nu(z)$.

\n\n\n```julia\n >>> besselj(nu, z).rewrite(jn)\n √2⋅√z⋅jn(ν - 1/2, z)\n ────────────────────\n √π\n```\n\n
In Julia:
\n\n
    \n
  • we need to call in SpecialFunctions

    \n
  • \n
  • jn is imported as a function object and this is not what SymPy expects, instead we pass in the object sympy.jn

    \n
  • \n
\n\n\n```julia\nusing SpecialFunctions\nbesselj(nu, z).rewrite(sympy.jn)\n```\n\n\n\n\n\\begin{equation*}\\frac{\\sqrt{2} \\sqrt{z} j_{\\nu - \\frac{1}{2}}\\left(z\\right)}{\\sqrt{\\pi}}\\end{equation*}\n\n\n\n
\n\n

Print $\\int_{0}^{\\pi} \\cos^{2}{\\left (x \\right )}\\, dx$ using $\\LaTeX$.

\n\n\n```julia\n >>> latex(Integral(cos(x)**2, (x, 0, pi)))\n \\int_{0}^{\\pi} \\cos^{2}{\\left (x \\right )}\\, dx\n```\n\n
In Julia:
\n\n
    \n
  • Latex printing occurs when the mime type is requested. However, the latex function can be called directly. However, this is not imported by default to avoid name collisions, and so must be qualified. Below, the latex is output as a string, though

    \n
  • \n
  • Integral, like Function and Matrix is not a function and must be qualified

    \n
  • \n
  • ** must become ^

    \n
  • \n
  • and we use PI, an alias for sympy.pi, the symbolic value for $\\pi$:

    \n
  • \n
\n\n\n```julia\nsympy.latex(sympy.Integral(cos(x)^2, (x, 0, PI)))\n```\n\n\n\n\n\\int_{0}^{\\pi} \\cos^{2}{\\left (x \\right )}\\, dx\n\n\n\n
\n\n

Why SymPy?

\n\n

There are many computer algebra systems out there. This <http://en.wikipedia.org/wiki/List_of_computer_algebra_systems>_ Wikipedia article lists many of them. What makes SymPy a better choice than the alternatives?

\n\n

First off, SymPy is completely free. It is open source, and licensed under the liberal BSD license, so you can modify the source code and even sell it if you want to. This contrasts with popular commercial systems like Maple or Mathematica that cost hundreds of dollars in licenses.

\n\n

Second, SymPy uses Python. Most computer algebra systems invent their own language. Not SymPy. SymPy is written entirely in Python, and is executed entirely in Python. This means that if you already know Python, it is much easier to get started with SymPy, because you already know the syntax (and if you don't know Python, it is really easy to learn). We already know that Python is a well-designed, battle-tested language. The SymPy developers are confident in their abilities in writing mathematical software, but programming language design is a completely different thing. By reusing an existing language, we are able to focus on those things that matter: the mathematics.

\n\n

Another computer algebra system, Sage also uses Python as its language. But Sage is large, with a download of over a gigabyte. An advantage of SymPy is that it is lightweight. In addition to being relatively small, it has no dependencies other than Python, so it can be used almost anywhere easily. Furthermore, the goals of Sage and the goals of SymPy are different. Sage aims to be a full featured system for mathematics, and aims to do so by compiling all the major open source mathematical systems together into one. When you call some function in Sage, such as integrate, it calls out to one of the open source packages that it includes. In fact, SymPy is included in Sage. SymPy on the other hand aims to be an independent system, with all the features implemented in SymPy itself.

\n\n

A final important feature of SymPy is that it can be used as a library. Many computer algebra systems focus on being usable in interactive environments, but if you wish to automate or extend them, it is difficult to do. With SymPy, you can just as easily use it in an interactive Python environment or import it in your own Python application. SymPy also provides APIs to make it easy to extend it with your own custom functions.

\n\n
In Julia:
\n\n

There are other symbolic packages for Julia:

\n\n
    \n
  • Reduce.jl

    \n
  • \n
  • Symata.jl

    \n
  • \n
  • SymEngine.jl

    \n
  • \n
  • Nemo.jl

    \n
  • \n
\n\n

SymPy is an attractive alternative as PyCall makes most all of its functinality directly available and SymPy is fairly feature rich.

\n\n
\n\n

return to index

\n", "meta": {"hexsha": "45dfa31c9e0290560656802379482358d4c372c6", "size": 27451, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "examples/intro.ipynb", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/SymPy.jl-24249f21-da20-56a4-8eb1-6a02cf4ae2e6", "max_stars_repo_head_hexsha": "a6e5a24b3d1ad069a413d0c28f01052c5fa4c6cc", "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": "examples/intro.ipynb", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/SymPy.jl-24249f21-da20-56a4-8eb1-6a02cf4ae2e6", "max_issues_repo_head_hexsha": "a6e5a24b3d1ad069a413d0c28f01052c5fa4c6cc", "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": "examples/intro.ipynb", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/SymPy.jl-24249f21-da20-56a4-8eb1-6a02cf4ae2e6", "max_forks_repo_head_hexsha": "a6e5a24b3d1ad069a413d0c28f01052c5fa4c6cc", "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": 178.2532467532, "max_line_length": 864, "alphanum_fraction": 0.6557502459, "converted": true, "num_tokens": 4797, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810511092412, "lm_q2_score": 0.9184802378888549, "lm_q1q2_score": 0.8701507731942093}} {"text": "```python\nimport sympy as sy\nimport numpy as np\nfrom sympy.functions import sin, cos, ln\nimport matplotlib.pyplot as plt\nplt.style.use(\"ggplot\")\n\n# Factorial function\ndef factorial(n):\n if n <= 0:\n return 1\n else:\n return n * factorial(n - 1)\n\n# Taylor approximation at x0 of the function 'function'\ndef taylor(function, x0, n, x = sy.Symbol('x')):\n i = 0\n p = 0\n while i <= n:\n p = p + (function.diff(x, i).subs(x, x0))/(factorial(i))*(x - x0)**i\n i += 1\n return p\n\ndef plot(f, x0 = 0, n = 9, by = 2, x_lims = [-5, 5], y_lims = [-5, 5], npoints = 800, x = sy.Symbol('x')):\n x1 = np.linspace(x_lims[0], x_lims[1], npoints)\n # Approximate up until n starting from 1 and using steps of by\n for j in range(1, n + 1, by):\n func = taylor(f, x0, j)\n taylor_lambda = sy.lambdify(x, func, \"numpy\")\n print('Taylor expansion at n=' + str(j), func)\n plt.plot(x1, taylor_lambda(x1), label = 'Order '+ str(j))\n # Plot the function to approximate (sine, in this case)\n func_lambda = sy.lambdify(x, f, \"numpy\")\n plt.plot(x1, func_lambda(x1), label = 'Function of x')\n \n plt.xlim(x_lims)\n plt.ylim(y_lims)\n plt.xlabel('x')\n plt.ylabel('y')\n plt.legend()\n plt.grid(True)\n plt.title('Taylor series approximation')\n plt.show()\n\n# Define the variable and the function to approximate\nx = sy.Symbol('x')\nf = ln(1 + x)\nplot(f)\n```\n", "meta": {"hexsha": "ef1c67cbb527da7495c78f18e5feba32809ad724", "size": 34638, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Datathon/Untitled.ipynb", "max_stars_repo_name": "ivaylokanov/Deep_Machine_Learning", "max_stars_repo_head_hexsha": "942a6f87c928b8c21d72c61a0322d02e1a116095", "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": "Datathon/Untitled.ipynb", "max_issues_repo_name": "ivaylokanov/Deep_Machine_Learning", "max_issues_repo_head_hexsha": "942a6f87c928b8c21d72c61a0322d02e1a116095", "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": "Datathon/Untitled.ipynb", "max_forks_repo_name": "ivaylokanov/Deep_Machine_Learning", "max_forks_repo_head_hexsha": "942a6f87c928b8c21d72c61a0322d02e1a116095", "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": 312.0540540541, "max_line_length": 31374, "alphanum_fraction": 0.9092615047, "converted": true, "num_tokens": 454, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9706877675527112, "lm_q2_score": 0.8962513786759491, "lm_q1q2_score": 0.8699802499329966}} {"text": "```python\nimport sympy as sp\nimport pandas as pd\n```\n\n\n```python\nx = sp.symbols('x')\nf = sp.exp(x)\n```\n\n\n```python\nnodes = [-0.3, -0.2, -0.1, 0, 0.1, 0.3]\nvalues = [f.evalf(subs={x: n}) for n in nodes]\n```\n\n\n```python\nnew_value = 0.8\ntrue_node = sp.log(0.8)\n```\n\n\n```python\ndef construct_lagrange_polynom(nodes, values, x):\n polynom = 0\n for i in range(len(nodes)):\n term = 1\n for j in range(len(nodes)):\n if i == j:\n continue\n term *= x - nodes[j]\n term /= nodes[i] - nodes[j]\n polynom += term * values[i]\n return polynom\n```\n\n\n```python\npolynom = construct_lagrange_polynom(nodes, values, x)\n```\n\n\n```python\nsolutions = sp.solve(polynom - new_value)\n```\n\n\n```python\npd.DataFrame([[true_node], [solutions[0]], [true_node - solutions[0]]],\n index=['Exact value', 'Estimated', 'Error'], columns=[''])\n```\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
Exact value-0.223143551314210
Estimated-0.223143564849920
Error1.35357104968925e-8
\n
\n\n\n", "meta": {"hexsha": "41e86861d72c3d075a0df9c7d8d7498ff6146144", "size": 3848, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "year-2/computational-workshop/task-2.ipynb", "max_stars_repo_name": "Sergobot/university", "max_stars_repo_head_hexsha": "7cd8c07fc660f1e19127c6488991ddd59d99643c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2019-09-05T08:43:47.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-05T08:43:52.000Z", "max_issues_repo_path": "year-2/computational-workshop/task-2.ipynb", "max_issues_repo_name": "Sergobot/university", "max_issues_repo_head_hexsha": "7cd8c07fc660f1e19127c6488991ddd59d99643c", "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": "year-2/computational-workshop/task-2.ipynb", "max_forks_repo_name": "Sergobot/university", "max_forks_repo_head_hexsha": "7cd8c07fc660f1e19127c6488991ddd59d99643c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-10-04T07:40:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-18T07:12:08.000Z", "avg_line_length": 23.1807228916, "max_line_length": 80, "alphanum_fraction": 0.4368503119, "converted": true, "num_tokens": 487, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9736446479186301, "lm_q2_score": 0.8933094039240554, "lm_q1q2_score": 0.8697659200660384}} {"text": "# Exercise 2\nWrite a function to compute the roots of a mathematical equation of the form\n\\begin{align}\n ax^{2} + bx + c = 0.\n\\end{align}\nYour function should be sensitive enough to adapt to situations in which a user might accidentally set $a=0$, or $b=0$, or even $a=b=0$. For example, if $a=0, b\\neq 0$, your function should print a warning and compute the roots of the resulting linear function. It is up to you on how to handle the function header: feel free to use default keyword arguments, variable positional arguments, variable keyword arguments, or something else as you see fit. Try to make it user friendly.\n\nYour function should return a tuple containing the roots of the provided equation.\n\n**Hint:** Quadratic equations can have complex roots of the form $r = a + ib$ where $i=\\sqrt{-1}$ (Python uses the notation $j=\\sqrt{-1}$). To deal with complex roots, you should import the `cmath` library and use `cmath.sqrt` when computing square roots. `cmath` will return a complex number for you. You could handle complex roots yourself if you want, but you might as well use available libraries to save some work.\n", "meta": {"hexsha": "b9503f0daf695d089c5a284124874e0279f7a51c", "size": 1783, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "lectures/L5/Exercise_2.ipynb", "max_stars_repo_name": "xuwd11/cs207_Weidong_Xu", "max_stars_repo_head_hexsha": "00442657239c7a4040501bf7fa0f6697c731fe94", "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": "lectures/L5/Exercise_2.ipynb", "max_issues_repo_name": "xuwd11/cs207_Weidong_Xu", "max_issues_repo_head_hexsha": "00442657239c7a4040501bf7fa0f6697c731fe94", "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/L5/Exercise_2.ipynb", "max_forks_repo_name": "xuwd11/cs207_Weidong_Xu", "max_forks_repo_head_hexsha": "00442657239c7a4040501bf7fa0f6697c731fe94", "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.4523809524, "max_line_length": 496, "alphanum_fraction": 0.6348850252, "converted": true, "num_tokens": 275, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109728022221, "lm_q2_score": 0.9149009486120849, "lm_q1q2_score": 0.8695319005880875}} {"text": "Vamos continuar nossa trilha em computação simbólica estendendo o conhecimento sobre o tipo `bool`, expressões e testes lógicos.\n\n## Operadores lógicos\n\nVimos que `True` e `False` são os dois valores atribuíves a um objeto de tipo `bool`. Eles são úteis para testar condições, realizar verificações e comparar quantidades. Vamos estudar *operadores de comparação*, *operadores de pertencimento* e *operadores de identidade*.\n\n### Operadores de comparação\n\nA tabela abaixo resume os operadores de comparação utilizados em Python.\n\n| operador | significado | símbolo matemático | \n|---|---|---| \n| `<` | menor do que | $<$ |\n| `<=` | menor ou igual a | $\\leq$ |\n| `>` | maior do que | $>$ |\n| `>=` | maior ou igual a | $\\geq$ |\n| `==` | igual a | $=$ |\n| `!=` | diferente de | $\\neq$ |\n\nPodemos usá-los para comparar objetos. \n\n**Nota:** `==` está relacionado à igualdade, ao passo que `=` é uma atribuição. São conceitos operadores com finalidade distinta. \n\n\n```python\n2 < 3 # o resultado é um 'bool'\n```\n\n\n\n\n True\n\n\n\n\n```python\n5 < 2 # isto é falso\n```\n\n\n\n\n False\n\n\n\n\n```python\n2 <= 2 # isto é verdadeiro\n```\n\n\n\n\n True\n\n\n\n\n```python\n4 >= 3 # isto é verdadeiro\n```\n\n\n\n\n True\n\n\n\n\n```python\n6 != -2 \n```\n\n\n\n\n True\n\n\n\n\n```python\n4 == 4 # isto não é uma atribuição! \n```\n\n\n\n\n True\n\n\n\nPodemos realizar comparações aninhadas:\n\n\n```python\nx = 2\n1 < x < 3\n```\n\n\n\n\n True\n\n\n\n\n```python\n3 > x > 4\n```\n\n\n\n\n False\n\n\n\n\n```python\n2 == x > 3 \n```\n\n\n\n\n False\n\n\n\nAs comparações aninhadas acima são resolvidas da esquerda para a direita e em partes. Isso nos leva a introduzir os seguintes operadores.\n\n| operador | símbolo matemático | significado | uso relacionado a |\n|---|---|---|---|\n| `or` | $\\vee$ | \"ou\" booleano | união, disjunção |\n| `and` | $\\wedge$ | \"e\" booleano | interseção, conjunção |\n| `not` | $\\neg$ | \"não\" booleano | exclusão, negação |\n\n\n```python\n# parênteses não são necessários aqui\n(2 == x) and (x > 3) # 1a. comparação: 'True'; 2a.: 'False'. Portanto, ambas: 'False'\n```\n\n\n\n\n False\n\n\n\n\n```python\n# parênteses não são necessários aqui\n(x < 1) or (x < 2) # nenhuma das duas é True. Portanto, \n```\n\n\n\n\n False\n\n\n\n\n```python\nnot (x == 2) # nega o \"valor-verdade\" que é 'True'\n```\n\n\n\n\n False\n\n\n\n\n```python\nnot x + 1 > 3 # estude a precedência deste exemplo. Por que é 'True'?\n```\n\n\n\n\n True\n\n\n\n\n```python\nnot (x + 1 > 3) # estude a precedência deste exemplo. Por que também é 'True'?\n```\n\n\n\n\n True\n\n\n\n### Operadores de pertencimento\n\nA tabela abaixo resume os operadores de pertencimento. \n\n| operador | significado | símbolo matemático\n|---|---|---|\n| `in` | pertence a | $\\in$ |\n| `not in` | não pertence a | $\\notin$ |\n\nEles terão mais utilidade quando falarmos sobre sequências, listas. Neste momento, vejamos exemplos com objetos `str`.\n\n\n```python\n'2' in '2 4 6 8 10' # o caracter '2' pertence à string\n```\n\n\n\n\n True\n\n\n\n\n```python\nfrase_teste = 'maior do que' \n'maior' in frase_teste\n```\n\n\n\n\n True\n\n\n\n\n```python\n'menor' in frase_teste # a palavra 'menor' está na frase\n```\n\n\n\n\n False\n\n\n\n\n```python\n1 in 2 # 'in' e 'not in' não são aplicáveis aqui\n```\n\n### Operadores de identidade\n\nA tabela abaixo resume os operadores de identidade. \n\n| operador | significado \n|---|---|\n| `is` | \"aponta para o mesmo objeto\" \n| `is not` | \"não aponta para o mesmo objeto\" |\n\nEsses operadores são úteis para verificar se duas variáveis se referem ao mesmo objeto. Exemplo: \n\n```python\na is b\na is not b\n```\n\n- `is` é `True` se `a` e `b` se referem ao mesmo objeto; `False`, caso contrário.\n- `is not` é `False` se `a` e `b` se referem ao mesmo objeto; `True`, caso contrário.\n\n\n```python\na = 2\nb = 3\na is b # valores distintos\n```\n\n\n\n\n False\n\n\n\n\n```python\na = 2\nb = a\na is b # mesmos valores\n```\n\n\n\n\n True\n\n\n\n\n```python\na = 2\nb = 3\na is not b # de fato, valores não são distintos\n```\n\n\n\n\n True\n\n\n\n\n```python\na = 2\nb = a\na is not b # de fato, valores são distintos\n```\n\n\n\n\n False\n\n\n\n## Equações simbólicas\n\nEquações simbólicas podem ser formadas por meio de `Eq` e não com `=` ou `==`.\n\n\n```python\n# importação\nfrom sympy.abc import a,b\nimport sympy as sy \nsy.init_printing(pretty_print=True)\n```\n\n\n```python\nsy.Eq(a,b) # equação simbólica\n```\n\n\n```python\nsy.Eq(sy.cos(a), b**3) # os objetos da equação são simbólicos\n```\n\n### Resolução de equações algébricas simbólicas\n\nPodemos resolver equações algébricas da seguinte forma:\n\n```python\nsolveset(equação,variável,domínio)\n```\n\n**Exemplo:** resolva $x^2 = 1$ no conjunto $\\mathbb{R}$.\n\n\n```python\nfrom sympy.abc import x\nsy.solveset( sy.Eq( x**2, 1), x,domain=sy.Reals)\n```\n\nPodemos reescrever a equação como: $x^2 - 1 = 0$.\n\n\n```python\nsy.solveset( sy.Eq( x**2 - 1, 0), x,domain=sy.Reals)\n```\n\nCom `solveset`, não precisamos de `Eq`. Logo, a equação é passada diretamente.\n\n\n```python\nsy.solveset( x**2 - 1, x,domain=sy.Reals)\n```\n\n**Exemplo:** resolva $x^2 + 1 = 0$ no conjunto $\\mathbb{R}$.\n\n\n```python\nsy.solveset( x**2 + 1, x,domain=sy.Reals) # não possui solução real\n```\n\n**Exemplo:** resolva $x^2 + 1 = 0$ no conjunto $\\mathbb{C}$.\n\n\n```python\nsy.solveset( x**2 + 1, x,domain=sy.Complexes) # possui soluções complexas\n```\n\n**Exemplo:** resolva $\\textrm{sen}(2x) = 3 + x$ no conjunto $\\mathbb{R}$.\n\n\n```python\nsy.solveset( sy.sin(2*x) - x - 3,x,sy.Reals) # a palavra 'domain' também pode ser omitida.\n```\n\nO conjunto acima indica que nenhuma solução foi encontrada.\n\n**Exemplo:** resolva $\\textrm{sen}(2x) = 1$ no conjunto $\\mathbb{R}$.\n\n\n```python\nsy.solveset( sy.sin(2*x) - 1,x,sy.Reals)\n```\n\n## Expansão, simplificação e fatoração de polinômios\n\nVejamos exemplos de polinômios em uma variável. \n\n\n```python\na0, a1, a2, a3 = sy.symbols('a0 a1 a2 a3') # coeficientes\nP3x = a0 + a1*x + a2*x**2 + a3*x**3 # polinômio de 3o. grau em x\nP3x\n```\n\n\n```python\nb0, b1, b2, b3 = sy.symbols('b0 b1 b2 b3') # coeficientes\nQ3x = b0 + b1*x + b2*x**2 + b3*x**3 # polinômio de 3o. grau em x\nQ3x\n```\n\n\n```python\nR3x = P3x*Q3x # produto polinomial\nR3x\n```\n\n\n```python\nR3x_e = sy.expand(R3x) # expande o produto\nR3x_e\n```\n\n\n```python\nsy.simplify(R3x_e) # simplify às vezes não funciona como esperado\n```\n\n\n```python\nsy.factor(R3x_e) # 'factor' pode funcionar melhor\n```\n\n\n```python\n# simplify funciona para casos mais gerais \nident_trig = sy.sin(x)**2 + sy.cos(x)**2\nident_trig\n```\n\n\n```python\nsy.simplify(ident_trig)\n```\n\n## Identidades trigonométricas \n\nPodemos usar `expand_trig` para expandir funções trigonométricas. \n\n\n```python\nsy.expand_trig( sy.sin(a + b) ) # sin(a+b)\n```\n\n\n```python\nsy.expand_trig( sy.cos(a + b) ) # cos(a+b)\n```\n\n\n```python\nsy.expand_trig( sy.sec(a - b) ) # sec(a-b)\n```\n\n## Propriedades de logaritmo\n\n\nCom `expand_log`, podemos aplicar propriedades válidas de logaritmo.\n\n\n```python\nsy.expand_log( sy.log(a*b) )\n```\n\nA identidade não foi validada pois `a` e `b` são símbolos irrestritos.\n\n\n```python\na,b = sy.symbols('a b',positive=True) # impomos que a,b > 0\n```\n\n\n```python\nsy.expand_log( sy.log(a*b) ) # identidade validada\n```\n\n\n```python\nsy.expand_log( sy.log(a/b) )\n```\n\n\n```python\nm = sy.symbols('m', real = True) # impomos que m seja um no. real\nsy.expand_log( sy.log(a**m) )\n```\n\nCom `logcombine`, compactamos as propriedades.\n\n\n```python\nsy.logcombine( sy.log(a) + sy.log(b) ) # identidade recombinada\n```\n\n## Fatorial \n\nA função `factorial(n)` pode ser usada para calcular o fatorial de um número.\n\n\n```python\nsy.factorial(m)\n```\n\n\n```python\nsy.factorial(m).subs(m,10) # 10! \n```\n\n\n```python\nsy.factorial(10) # diretamente\n```\n\n**Exemplo:** Sejam $m,n,x$ inteiros positivos. Se $f(m) = 2m!$, $g(n) = \\frac{(n + 1)!}{n^2!}$ e $h(x) = f(x)g(x)$, qual é o valor de $h(2)$? \n\n\n```python\nfrom sympy.abc import m,n,x\n\nf = 2*sy.factorial(m)\ng = sy.factorial(n + 1)/sy.factorial(n**2)\n\nh = (f.subs(m,x)*g.subs(n,x)).subs(x,4)\nh\n```\n\n## Funções anônimas \n\nA terceira classe de funções que iremos aprender é a de *funções anônimas*. Uma **função anônima** em Python consiste em uma função cujo nome não é explicitamente definido e que pode ser criada em apenas uma linha de código para executar uma tarefa específica.\n\nFunções anônimas são baseadas na palavra-chave `lambda`. Este nome tem inspiração em uma área da ciência da computação chamada de cálculo-$\\lambda$.\n\nUma função anônima tem a seguinte forma: \n\n```python\nlambda lista_de_parâmetros: expressão\n```\n\nFunções anônimas podem são bastante úteis para tornar um código mais conciso. \n\nPor exemplo, na aula anterior, definimos a função\n\n```python\ndef repasse(V): \n return 0.0103*V\n```\n\npara calcular o repasse financeiro ao corretor imobiliário. \n\nCom uma função anônima, a mesma função seria escrita como:\n\n\n```python\nrepasse = lambda V: 0.0103*V\n```\n\nNão necessariamente temos que atribui-la a uma variável. Neste caso, teríamos:\n\n\n```python\nlambda V: 0.0103*V\n```\n\n\n\n\n (V)>\n\n\n\nPara usar a função, passamos um valor:\n\n\n```python\nrepasse(100000) # repasse sobre R$ 100.000,00\n```\n\nO modelo completo com \"bonificação\" seria escrito como:\n\n\n```python\nr3 = lambda c,V,b: c*V + b # aqui há 3 parâmetros necessários\n```\n\nRedefinamos objetos simbólicos:\n\n\n```python\nfrom sympy.abc import b,c,V\nr3(b,c,V)\n```\n\nO resultado anterior continua sendo um objeto simbólico, mas obtido de uma maneira mais direta. Podemos usar funções anônimas para tarefas de menor complexidade.\n\n## \"Lambdificação\" simbólica\n\nUsando `lambdify`, podemos converter uma expressão simbólica do *sympy* para uma expressão que pode ser numericamente avaliada em outra biblioteca. Essa função desempenha papel similar a uma função *lambda* (anônima).\n\n\n```python\nexpressao = sy.sin(x) + sy.sqrt(x) # expressão simbólica\nf = sy.lambdify(x,expressao,\"math\") # lambdificação para o módulo math\nf(0.2) # avalia\n```\n\nPara avaliações simples como a anterior, podemos usar `evalf` e `subs`. A lambdificação será útil quando quisermos avaliar uma função em vários pontos, por exemplo. Na próxima aula, introduziremos sequencias e listas. Para mostrar um exemplo de lambdificação melhor veja o seguinte exemplo.\n\n\n```python\nfrom numpy import arange # importação de função do módulo numpy\n\nX = arange(40) # gera 40 valores de 0 a 39\n```\n\n\n```python\nX\n```\n\n\n\n\n array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,\n 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33,\n 34, 35, 36, 37, 38, 39])\n\n\n\n\n```python\nf = sy.lambdify(x,expressao,\"numpy\")(X) # avalia 'expressao' em X\nf\n```\n\n\n\n\n array([0. , 1.84147098, 2.32351099, 1.87317082, 1.2431975 ,\n 1.2771437 , 2.17007424, 3.30273791, 3.81778537, 3.41211849,\n 2.61825655, 2.31663458, 2.9275287 , 4.02571831, 4.73226474,\n 4.52327119, 3.71209668, 3.16170813, 3.49165344, 4.50877615,\n 5.38508121, 5.41923133, 4.68156445, 3.94961112, 3.99340112,\n 4.86764825, 5.86157796, 6.15252835, 5.56240841, 4.72153092,\n 4.48919395, 5.16372672, 6.20828093, 6.74447451, 6.36003458,\n 5.48789711, 5.00822115, 5.4392244 , 6.46078258, 7.20879338])\n\n\n", "meta": {"hexsha": "d440ed060512e9bbbad8690d855d75f4753f79f5", "size": 108869, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "_build/html/_sources/ipynb/02b-computacao-simbolica.ipynb", "max_stars_repo_name": "gcpeixoto/FMECD", "max_stars_repo_head_hexsha": "9bca72574c6630d1594396fffef31cfb8d58dec2", "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": "_build/html/_sources/ipynb/02b-computacao-simbolica.ipynb", "max_issues_repo_name": "gcpeixoto/FMECD", "max_issues_repo_head_hexsha": "9bca72574c6630d1594396fffef31cfb8d58dec2", "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": "_build/html/_sources/ipynb/02b-computacao-simbolica.ipynb", "max_forks_repo_name": "gcpeixoto/FMECD", "max_forks_repo_head_hexsha": "9bca72574c6630d1594396fffef31cfb8d58dec2", "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": 62.74870317, "max_line_length": 8308, "alphanum_fraction": 0.7897197549, "converted": true, "num_tokens": 3873, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308073258009, "lm_q2_score": 0.9314625031628428, "lm_q1q2_score": 0.8694557963210038}} {"text": "# 17 Importance Sampling\n\nThe Monte Carlo integration procedure with uniform sampling \n\n$$\nI = \\int_{a_1}^{b_1} \\cdots \\int_{a_M}^{b_M} f(x_1, \\dots, x_M) dx_1\\cdots dx_M \\approx V \\langle f \\rangle_\\text{mc}\n$$\n\nworks well with monotonic and smooth integrands $f$. However, \n\n* sharply peaked\n* oscillating\n\nintegrands are problematic (like for any integration method).\n\nOscillations increase fluctuations in random sampling and require more sampling.\n\nSharp peaks are especially annoying for *uniform sampling* because most of the samples will come from regions outside the peak and not contribute to the integral.\n\n## Importance sampling method\n\n**Importance sampling** is a method to turn a non-smooth $f(x)$ into a smoother $g(x)$ by separating the integrand\n\n$$\n\\int_a^b \\! f(x) dx = \\int_a^b \\! \\frac{f(x)}{P(x)} P(x) dx = \\int_a^b \\! g(x) P(x) dx, \\quad g(x) := \\frac{f(x)}{P(x)}\n$$\n\nThe new function $g(x)$ is supposed to be smoother than $f(x)$. \n\n$P(x)$ is a known probability distribution and we are again calculating a *weighted average*, this time over our new function $g(x)$. The trick will be to generate samples according to $P(x)$ and then calculate the average $\\langle g \\rangle_\\text{mc}$:\n\n$$\n\\int_a^b \\! f(x) dx = \\langle g \\rangle_\\text{mc} = \\frac{1}{N} \\sum_{i=1}^N g(x_i) = \\frac{1}{N} \\sum_{i=1}^N \\frac{f(x_i)}{P(x_i)}\n$$\n\n* The average $\\langle g \\rangle_\\text{mc}$ *must* be calculated for samples $x \\sim P$.\n* The probability distribution $P(x)$ should be chosen so that the modified integrand $g(x) = f(x)/P(x)$ should become as smooth as possible (ideally, close to uniform).\n* The integration volume does not explicitly appear in the importance sampling equation. It is taken into account implicitly by the sampling process.\n* Importance sampling with the uniform distribution $P(x) = (b-a)^{-1}$ reduces to the *weighted average method*.\n* Importance sampling generalizes to $M$ dimensions just as standard MC sampling.\n\n## Example\n\nThe integral\n$$\n\\int_a^b \\! f(x) dx = \\int_0^\\infty \\! \\cos x \\, e^{-x} dx = \\frac{1}{2}\n$$\noscillates and is strongly peaked at the origin.\n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef f(x):\n return np.cos(x) * np.exp(-x)\n\nX = np.linspace(0, 100, 400)\nplt.plot(X, f(X))\nplt.xlabel(\"x\"); plt.ylabel(\"f(x)\");\n```\n\nOscillations are not so problematic but if we want to integrate \"to infinity\" then we really should take care of the peak at the origin.\n\nChoose the exponential distribution\n$$\nP(x) = e^{-x}\n$$\nwhich is already normalized on the interval $[0, +\\infty[$.\n\nWe then get\n$$\ng(x) = \\frac{f(x)}{P(x)} = \\cos x.\n$$\n\n\n\n\n```python\ndef g(x):\n return np.cos(x)\n```\n\n\n```python\nplt.plot(X, g(X), X, np.exp(-X))\nplt.legend((r\"$g(x)$\", r\"$P(x)$\"))\nplt.xlabel(\"x\");\n```\n\nNote that the exponential distribution stretches to infinity. However, it is very unlikely to draw samples for large $x$ values.\n\nBut how do we sample from the exponential distribution?\n\n1. Look through the docs for the [distributions](https://numpy.org/doc/stable/reference/random/generator.html#distributions) that [numpy's Random Generator](https://numpy.org/doc/stable/reference/random/generator.html) can provide, namely the [exponential distribution](https://numpy.org/doc/stable/reference/random/generated/numpy.random.Generator.exponential.html#numpy.random.Generator.exponential).\n2. Transform samples from the *uniform* distribution to the exponential distribution.\n\n### Exponential distribution with `numpy.random.Generator.exponential`\n\nIf we have well-tested, documented, and high performance code then we should know how to use it:\n\n\n```python\nimport numpy as np\nrng = np.random.default_rng()\n```\n\n\n```python\nN = 1000\nx = rng.exponential(scale=1.0, size=N)\nfMC = np.mean(g(x))\n\nfanalytical = 1/2\nerror = 1 - fMC/fanalytical\n\nprint(f\"fMC = {fMC} ({N} samples)\")\nprint(f\"f = {fanalytical} (error = {error})\")\n```\n\n fMC = 0.48969567139965026 (1000 samples)\n f = 0.5 (error = 0.020608657200699487)\n\n\nThe error decreases with increasing sample size (as can be seen by modifying `N`).\n\nNote that the samples are overwhelmingly appearing in the region where the function $f(x)$ was peaked, i.e., near the origin, and so $g(x)$ is only evaluated near the origin. Hence only those *important* data points contribute to the average. To obtain samples farther out ($x>10$) requires many samples to be drawn. The integration boundaries are implicitly taken into account via the sampling from the exponential distribution: in principle, a sample for very large $x$ *could* be drawn even though it is overwhelmingly unlikely.\n\n\n```python\nplt.plot(X, g(X), X, np.exp(-X))\nplt.plot(x, g(x), 'k.')\nplt.legend((r\"$g(x)$\", r\"$P(x)$\", \"MC\"))\nplt.xlim(0, 20)\nplt.xlabel(\"x\");\n```\n\n### Exponential distribution with inverse transform\n(follows *Computational Methods* Ch 10.B)\n\nWe often have to draw samples from a nonuniform distribution. The general approach is to draw samples from the [uniform distribution](https://en.wikipedia.org/wiki/Continuous_uniform_distribution) $\\mathcal{U}_\\text{[a, b]}$ over the interval $[a, b]$:\n\n\\begin{align}\nx &\\sim \\mathcal{U}_\\text{[a, b]}\\\\\np_x(x) &= \\begin{cases}\n \\frac{1}{b -a }, \\quad a \\le x \\le b\\\\\n 0, \\text{otherwise}\n \\end{cases}\n\\end{align} \n\nand then transform the random samples $x$ to the desired samples $y \\sim p_y$ that are non-uniformly distributed according to $p_y(y)$.\n\nIn the best case, we can obtain the nonuniform distribution *analytically* by using the *inverse transform method*. Let's assume that the transformation\n$$\ny = G(x)\n$$\nexists, which transforms a sample $x \\sim p_x$ into $y \\sim p_y$.\n\nThe derivation starts from the *conservation of probability*\n$$\n|p_y(y) dy| = |p_x(x) dx|\n$$\n\nThe probability in $[y, y+dy]$ must equal the probability in the corresponding interval $[x, x+dx]$ because $G: x \\mapsto y=G(x)$ in a one-to-one fashion.\n\nLet's sample from the uniform distribution $\\mathcal{U}_\\text{[0, 1]}$ so $p_x(x) = 1$.\n\nIntegrate the conservation of probability equation (and pulling the absolute magnitude out of the integral because $\\sum_i |a_i| = \\left|\\sum_i a_i\\right|$ if $a_i \\ge 0\\ \\forall i$):\n\n\\begin{gather}\n\\left|\\int p_y(y) dy\\right| = \\int 1 dx = x\\\\\nF(y) := \\left|\\int p_y(y) dy\\right| = x\\\\\nF(y) = x\n\\end{gather}\n\nIf we can solve the integral $\\int p_y(y) dy$ analytically and if the inverse of $F(x)$ exists,\n$$\ny = F^{-1}(x) = G(x)\n$$\nthen we have the **inverse transform**.\n\nApply to the *exponential distribution*:\n\\begin{gather}\np_y(y) = e^{-y}\\\\\nF(y) = \\left|\\int p_y(y) dy\\right| = \\left|-e^{-y}\\right| = e^{-y}\\\\\nF(y) = x\\\\\ne^{-y} = x\\\\\n\\end{gather}\n\nto yield the inverse transform\n\n$$\ny = -\\ln(x), \\quad 0 \\le x \\le 1, \\ 0 \\le y \\le + \\infty\n$$\n\nThe logarithm is the inverse transform of the exponential.\n\nThus the logarithm of a uniform sample in $[0, 1]$ yields a sample that is exponentially distributed. It \"squishes\" the samples near $x=1$ towards $y=0$ and expands the samples near $y=0$ towards infinity.\n\n\n\nOur MC importance sampling now just has one extra step: transform the uniform samples:\n\n\n```python\nN = 1000\nx = rng.uniform(low=0, high=1, size=N)\ny = -np.log(x)\nfMC = np.mean(g(y))\n\nfanalytical = 1/2\nerror = 1 - fMC/fanalytical\n\nprint(f\"fMC = {fMC} ({N} samples)\")\nprint(f\"f = {fanalytical} (error = {error})\")\n```\n\n fMC = 0.49704661874486056 (1000 samples)\n f = 0.5 (error = 0.0059067625102788845)\n\n\n\n```python\nplt.plot(X, g(X), X, np.exp(-X))\nplt.plot(y, g(y), 'k.')\nplt.plot(x, np.zeros_like(x), 'y|')\nplt.legend((r\"$g(x)$\", r\"$P(x)$\", \"MC\", \"uniform\"))\nplt.xlim(0, 20)\nplt.xlabel(\"x\");\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "da71e8ecb3de2fbd4dcd590360a988910e6fe101", "size": 123082, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "17_MonteCarlo/importance_sampling.ipynb", "max_stars_repo_name": "Py4Phy/PHY432-resources", "max_stars_repo_head_hexsha": "c26d95eaf5c28e25da682a61190e12ad6758a938", "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": "17_MonteCarlo/importance_sampling.ipynb", "max_issues_repo_name": "Py4Phy/PHY432-resources", "max_issues_repo_head_hexsha": "c26d95eaf5c28e25da682a61190e12ad6758a938", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-03-03T21:47:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-03T21:47:56.000Z", "max_forks_repo_path": "17_MonteCarlo/importance_sampling.ipynb", "max_forks_repo_name": "Py4Phy/PHY432-resources", "max_forks_repo_head_hexsha": "c26d95eaf5c28e25da682a61190e12ad6758a938", "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": 253.7773195876, "max_line_length": 41300, "alphanum_fraction": 0.920435157, "converted": true, "num_tokens": 2255, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418158002492, "lm_q2_score": 0.9407897430332622, "lm_q1q2_score": 0.8694231414130088}} {"text": "# Poincare-Lindstedt method\n\n## Swing pendulum\n\nThe equation for the swing pendulum is nonlinear due to the rotation nature of the movement.\n$$\\ddot{x}+\\sin x\\approx\\ddot{x}+x-\\frac{1}{6}x^3=0$$\nRewrite the equation as\n$$\\ddot{x}+x=\\epsilon x^3,\\quad\\epsilon=-1/6$$\nThe value $\\epsilon$ can be considered as small parameter.\n\\begin{align}\nx(t)&\\approx x_0(\\omega t)+\\epsilon x_1(\\omega t)+\\dots=x_0(t')+\\epsilon x_1(t')+\\dots\\\\\n\\omega&\\approx1+\\epsilon \\omega_1 + \\epsilon^2\\omega_2+\\dots\n\\end{align}\nChange time scale again, once $\\omega$ in steady state solution is a function of amplitude. Scaling the time in this way makes frequency in solution independent of amplitude.\n$$\\hat{t}=\\omega t,\\quad\\frac{d^2}{dt^2}=\\omega^2\\frac{d^2}{dt'^2}$$\nThe equation after changing time scale\n$$(1+\\epsilon \\omega_1+\\dots)^2(\\ddot{x}_0+\\epsilon \\ddot{x}_1+\\dots)+x_0+\\epsilon x_1+\\dots=\\epsilon (x_0+\\epsilon x_1+\\dots)^3$$\nExpand and collect terms with the same power of the small parameter $\\epsilon$:\n$$(\\ddot{x}_0+x_0)+\\epsilon(\\ddot{x}_1+x_1)+\\dots=0+\\epsilon(x_0^3-2\\omega_1\\ddot{x_0})+\\dots$$\nwhich can be broken down into sequence of equation:\n\\begin{align}\n\\ddot{x}_0+x_0&=0\\\\\n\\ddot{x}_1+x_1&=-2\\omega_1\\ddot{x}_0+x_0^3\n\\end{align}\nwith initial conditions like this $x_0(0)=a$, $\\dot{x}_0(0)=0$, $x_1(0)=0$, $\\dot{x}_1(0)=0$\n\nSolution to the 1st equation:\n$$x_0=a\\cos t$$\nSubstituting to the next equation yields\n$$\\ddot{x}_1+x_1=\\color{brown}{a(2\\omega_1+\\frac{3}{4}a^2)\\cos t}+\\frac{1}{4}a^3\\cos 3t=\\frac{1}{4}a^3\\cos 3t$$\nwhere the term resulting in secular (aperiodic) solution is highlighted with brown color. Equating to zero the coefficient in this term results in condition for the first order correction to the frequency:\n$$\\omega_1=-\\frac{3}{8}a^2,\\quad x_1=\\frac{1}{32}a^3(\\cos 3t-\\cos t)$$\nSolution accounting for the next harmonic\n$$x\\approx a\\cos\\omega t-\\frac{a^3}{192}(\\cos 3\\omega t-\\cos\\omega t),\\quad \\omega\\approx 1-\\frac{1}{16}a^2$$\n\n## Secular terms\n\nThis is aperiodic terms in solution appering because of equation of idealized system does not account for dessipation processes usually limiting the amplitude in real world. For instance, the spicific solution to this equation\n$$\\ddot{x}+x=\\sin(t),\\quad\\implies\\quad x=-\\frac{t}{2}\\cos t$$\nThe solution is not a steady state.\n\n## Compare numerical solution with analytical approximation\n\nEquation\n\\begin{equation}\n\\ddot{x}+\\sin x=0 \\qquad\nx(0) = x_0 \\quad\n\\dot{x}(0) = 0\n\\end{equation}\nintroducing new variable\n\\begin{equation}\nz_1 = x \\quad\nz_2 = \\dot{x}\n\\end{equation}\nget the system of 1st order equation for numerical procedure\n\\begin{equation}\n\\frac{d}{dt}\n\\begin{pmatrix}\nz_1 \\\\ z_2\n\\end{pmatrix}=\n\\begin{pmatrix}\nz_2 \\\\\n-\\sin z_1\n\\end{pmatrix}\n\\end{equation}\n\n\n```python\nimport numpy as np\nfrom scipy.integrate import odeint\nimport matplotlib.pyplot as plt\n```\n\n\n```python\ndef duffing_eqs(z, t):\n return [ z[1], -np.sin(z[0]) ]\n```\n\nNumerical solution\n\n\n```python\nx1 = 0.1 # rad\nx2 = np.pi/2\nx3 = 0.9*np.pi\n\nt = np.linspace(0, 5*2*np.pi, 100)\n\nsol1 = odeint(duffing_eqs, [x1, 0], t)\nsol2 = odeint(duffing_eqs, [x2, 0], t)\nsol3 = odeint(duffing_eqs, [x3, 0], t)\n```\n\n\n```python\ndef plot_duffing(t, sol, fcn, *, title):\n plt.plot(t, sol, t, fcn)\n plt.xlabel('t')\n plt.ylabel('x')\n plt.legend(['numerical', 'analytic'])\n plt.title(title)\n```\n\nApproximation to analytical solution with frequency correction\n$$x(t)\\approx x_0\\cdot\\cos\\left(\\left(1-\\frac{1}{16}x_0^2\\right)t\\right)$$\n\n\n```python\ndef approx_sol_1(t, x0):\n w = 1 - x0**2 / 16\n return x0 * np.cos(w*t)\n```\n\n\n```python\ndef approx_sol_2(t, x0):\n w = 1 - x0**2 / 16\n return x0 * np.cos(w*t) - \\\n x0**3 / 192 * (np.cos(3*w*t) - np.cos(w*t))\n```\n\nSolution for different amplitudes from $\\left[0, \\pi\\right)$ range\n\n\n```python\nplt.figure(figsize=(15,10))\nplt.subplot(2,2,1)\nplot_duffing(t, sol1[:,0], x1*np.cos(t),\n title='small amplitude')\nplt.subplot(2,2,2)\nplot_duffing(t, sol2[:,0], x2*np.cos(t),\n title='$x_0=0.5\\pi$, no freq. correction')\nplt.subplot(2,2,3)\nplot_duffing(t, sol2[:,0], approx_sol_1(t, x2),\n title='$x_0=0.5\\pi$, with freq. correction')\nplt.subplot(2,2,4)\nplot_duffing(t, sol3[:,0],\n np.append(np.reshape(approx_sol_1(t, x3), (len(t),1)),\n np.reshape(approx_sol_2(t, x3), (len(t),1)),\n axis=1),\n title='$x_0=0.9\\pi$, with correction')\nplt.show()\n```\n\n\n```python\nplt.plot(sol1[:,0], sol1[:,1],\n sol2[:,0], sol2[:,1],\n sol3[:,0], sol3[:,1])\nplt.title('Phase plane')\nplt.xlabel('$x$')\nplt.ylabel('$\\dot{x}$')\nplt.legend(['$x_0=0.1\\pi$','$x_0=0.5\\pi$','$x_0=0.9\\pi$'])\nplt.show()\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "c0b17ef9ba18b71380889b55753b576d8078cb8b", "size": 325134, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "duffing-oscillator/duffing-poincare-lindstedt.ipynb", "max_stars_repo_name": "vr050714/nonlinear-vibration-seminar", "max_stars_repo_head_hexsha": "663584d46708857383b637610e54fafa753250e2", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-05-26T05:38:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-26T05:38:38.000Z", "max_issues_repo_path": "duffing-oscillator/duffing-poincare-lindstedt.ipynb", "max_issues_repo_name": "vr050714/nonlinear-vibration-seminar", "max_issues_repo_head_hexsha": "663584d46708857383b637610e54fafa753250e2", "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": "duffing-oscillator/duffing-poincare-lindstedt.ipynb", "max_forks_repo_name": "vr050714/nonlinear-vibration-seminar", "max_forks_repo_head_hexsha": "663584d46708857383b637610e54fafa753250e2", "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": 1048.8193548387, "max_line_length": 166203, "alphanum_fraction": 0.8256811038, "converted": true, "num_tokens": 1703, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768557238083, "lm_q2_score": 0.9207896829553822, "lm_q1q2_score": 0.869388307635735}} {"text": "```python\nimport numpy as np\nimport sympy\nimport matplotlib.pyplot as plt\nfrom scipy import integrate\nfrom scipy.special import legendre\nfrom numpy.polynomial.legendre import Legendre\nimport matplotlib.ticker as mtick\nimport itertools\n\n\n# Legendre polynomial\ndef leg(n, x): \n return Legendre(np.concatenate((np.zeros(n), np.array([1]))))(x)\n\ndef hbasis(i,x):\n# Evaluates the function Ni at x\n if i==0:\n Ni=0.5 *(1-x)\n elif i==1:\n Ni=0.5 *(1+x)\n else:\n Ni=(np.sqrt(1/(4*(i+1)-6)))*(leg(i,x)-leg(i-2,x))\n return Ni\n\n\ndef stifness_matrix(p):\n#evaluates the elemental stifness matrix of size (p+1)x(p+1)\n K=np.zeros((p+1,p+1))\n K[0,0]=K[1,1]=0.5\n K[0,1]=K[1,0]=-0.5\n if p>=1:\n for i in range(2,p+1):\n K[i,i]=1\n return K\n\ndef stifness_matrix(p):\n#evaluates the elemental stifness matrix of size (p+1)x(p+1)\n K=np.zeros((p+1,p+1))\n K[0,0]=K[1,1]=0.5\n K[0,1]=K[1,0]=-0.5\n if p>=1:\n for i in range(2,p+1):\n K[i,i]=1\n return K\n\ndef mass_matrix(p):\n# Evaluates the elemental mass matrix of size (p+1)x(p+1)\n G=np.zeros((p+1,p+1))\n G[0,0]=G[1,1]=2/3\n G[0,1]=G[1,0]=1/3\n if p>=2:\n G[0,2]=G[1,2]=G[2,0]=G[2,1]=-1/np.sqrt(6)\n for i in range(2,p+1):\n G[i,i]=2/((2*(i+1)-1)*((2*(i+1)-5)))\n if p>=3:\n G[0,3]=G[3,0]=1/3*np.sqrt(10)\n G[1,3]=G[3,1]=-1/3*np.sqrt(10)\n for i in range(2,p+1):\n if i+2=interval[0] and point
Basic Python for Geosciences

\n\n

Session 1

\n\nPut your name here\n\n
\n

🏋 \n Exercise 1: \n \nIf the Average velocity to the target is 3000 m/sec and the target depth is 5000 m, calculate the two way time to the target according to the following formula:\n\n\\begin{align}\nTWT=2*( \\frac{Depth}{Velocity})\n\\end{align}\n\nDefine the variables and use the formula to obtain the TWT.\n\n

\n\n\n```python\n\n```\n\n
\n

🏋 \n Exercise 2: \n \nThe relation between velocity and depth is related according to the following formula:\n\n \n\\begin{align}\nVelocity (m/sec)=2800 + 0.7 * Depth (m)\n\\end{align}\n\n \n* What is the Velocity (m/sec) at 3000 meters? \n* What is the Velocity (m/sec) at 6000 feet? \n\nThe conversion factor from ft to m is 0.3048\n\n

\n\n\n```python\n\n```\n\n
\n

🏋 \n Exercise 3: \n \n* How much time takes a wave to travel through water in 2220 m, V=1500 m/s? \n* How much time takes a wave to travel through air in 500 m, V=340 m/s?\n* Write a small piece of code in Python to calculate the travel times and also find which is longer.\n \n

\n\n\n```python\n\n```\n\n
\n

🏋 \n Exercise 4: Write a dictionary with the following composition (weight %) of a granite:\n \n Quartz 25 \n Orthoclase 50 \n Plagioclase 10 \n Micas 10 \n Anphibole 5 \n \nUsing Python, present the values for orthoclase and micas\n

\n\n\n```python\n\n```\n\n
\n

🏋 \n Exercise 5: Write in Python a variable with the following string:\n\n\"A subsurface body of rock having sufficient porosity and permeability to store and transmit fluids. Metamorphic rocks are the most common reservoir rocks because they have more porosity than most igneous and sedimentary rocks and form under temperature conditions at which hydrocarbons can be preserved. A reservoir is a critical component of a complete petroleum system.\"\n \n* Print the variable in the screen \n* Correct the mistakes in the variable using the replace method \n* Verify if temperature is in the string \n* Verify if kritical is in the string \n* What is the string length? \n

\n\n\n```python\n\n```\n\n
\n

🏋 \n Exercise 6: These are the horizon tops and its depths (m):\n\n Surface 0 \n Cretaceous 1500 \n Jurassic 2000 \n Triassic 3000 \n Paleozoic 4500 \n\nWrite one tuple with the horizons name and the corresponding depths. Print the name and the depth of the third horizon in the list.\n \n

\n\n\n```python\n\n```\n\n
\n

🏋 \n Exercise 7: These are the horizon tops and its depths (m):\n\n Surface 0 \n Cretaceous 1500 \n Jurassic 2000 \n Triassic 3000 \n Paleozoic 4500 \n\n* Store the list of horizons and its corresponding depths in a list variable \n* Print the lists \n* Print the name and the depth of the third horizon in the list \n* What is the maximum depth? \n* What is the minimum depth? \n* What is the average depth? \n* How many horizons are in the list \n* Verify that the number of horizons names and number of horizons tops are the same\n

\n\n\n```python\n\n```\n\n
\n

🏋 \n Exercise 8: Create a matrix (list of lists) with the following values:\n\n\n | 6 8 12 24 33| \n |11 4 12 6 67| \n |23 9 67 10 43| \n | 1 12 34 18 2| \n | 7 11 2 23 78| \n | 8 24 1 5 23| \n\n* Print the matrix \n* Print the row 3 \n* Calculate the dimensions of the matrix \n* Print the element [3,4] \n* What is the minimum of the line 3 \n* What is the maximum of the line 2 \n

\n\n\n```python\n\n```\n\n
\n

🏋 \n Exercise 9: \n \n* Generate a 5x5 matrix of constant value equal to 10 \n* Generate a random 6x6 matrix\n* Print the values of the third column of both arrays \n* Print the attributes of both matrices \n* Generate a 3 million elements array and calculate all its attributes \n\n

\n\n\n```python\n\n```\n\n
\n

🏋 \n Exercise 10: Generate two 5x5 matrices, one with constant value equal to 10, and the other with random values\n\n* Determine if the matrices are singular (Determinant=0) \n* Calculate the inverse of the matrices \n* Sum both matrices \n* Convert the constant matrix to zero matrix \n\n

\n\n\n```python\n\n```\n\n
\n

🏋 \n Exercise 11: Solve the following Linear equations system:\n\n\\begin{align}\n1x+3y-2z = 5 \\\\\n3x+5y+6z = 7 \\\\\n2x+4y+3z = 8 \n\\end{align}\n\nRemember the linear system can be represented in linear algebra as dot product of the corresponding arrays:\n\n\\begin{align}\nA \\cdot x=b\n\\end{align}\n\n\nThe solution will be:\n\n\\begin{align}\nx=A^{-1} \\cdot b\n\\end{align}\n\n\n

\n\n
\n

🏋 \n Exercise 12: \n \n* Create a NumPy array with some random values\n* Calculate the maximum and the minimum of the array\n* Calculate the Average of the terms\n* Print the numbers rounded to 6 decimals\n\n

\n\n
\n

🏋 \n Exercise 13: \n \nPractice with a couple of examples on how to convert between float, int and str \n\n

\n\n
\n

🏋 \n Exercise 14: \n \nIn a cell write a small program for temperature conversion between Celsius to Fahrenheit with user interactive input\n\n

\n\n
\n

🏋 \n Exercise 15: Generate a range between 1 and 3000000\n\n* Calculate the average\n* Calculate the minimum\n* Calculate the maximum\n\n

\n\n
\n

🏋 \n Exercise 16: Create a function to convert from Fahrenheit to Celsius\n\n

\n\n
\n

🏋 \n Exercise 17: Create a function to calculate and return the following values of a list:\n \n* Average\n* Minimum\n* Maximum\n

\n", "meta": {"hexsha": "f240225efa4dcb0e91ae721d89f952e003172154", "size": 12447, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Session_1/Session_1_exercises.ipynb", "max_stars_repo_name": "mdsoto/log_analysis_usb_aapg", "max_stars_repo_head_hexsha": "4faf60a5c3a3f0f2e07c12c63e93fc4f3b32f57e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-09-30T09:26:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-30T09:26:02.000Z", "max_issues_repo_path": "Session_1/Session_1_exercises.ipynb", "max_issues_repo_name": "mdsoto/USB_AAPG_2021", "max_issues_repo_head_hexsha": "4faf60a5c3a3f0f2e07c12c63e93fc4f3b32f57e", "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": "Session_1/Session_1_exercises.ipynb", "max_forks_repo_name": "mdsoto/USB_AAPG_2021", "max_forks_repo_head_hexsha": "4faf60a5c3a3f0f2e07c12c63e93fc4f3b32f57e", "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": 27.1768558952, "max_line_length": 384, "alphanum_fraction": 0.5254278139, "converted": true, "num_tokens": 1922, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.953966093674472, "lm_q2_score": 0.9111797166446536, "lm_q1q2_score": 0.8692345549229125}} {"text": "# Symbolic Computation\nSymbolic computation deals with symbols, representing them exactly, instead of numerical approximations (floating point). \n\nWe will start with the following [borrowed](https://docs.sympy.org/latest/tutorial/intro.html) tutorial to introduce the concepts of SymPy. Devito uses SymPy heavily and builds upon it in its DSL. \n\n\n```python\nimport math\n\nmath.sqrt(3)\n```\n\n\n\n\n 1.7320508075688772\n\n\n\n\n```python\nmath.sqrt(8)\n```\n\n\n\n\n 2.8284271247461903\n\n\n\n$\\sqrt(8) = 2\\sqrt(2)$, but it's hard to see that here\n\n\n```python\nimport sympy\nsympy.sqrt(3)\n```\n\n\n\n\n$\\displaystyle \\sqrt{3}$\n\n\n\nSymPy can even simplify symbolic computations\n\n\n```python\nsympy.sqrt(8)\n```\n\n\n\n\n$\\displaystyle 2 \\sqrt{2}$\n\n\n\n\n```python\nsympy.sqrt(20)\n```\n\n\n\n\n$\\displaystyle 2 \\sqrt{5}$\n\n\n\n\n```python\nfrom sympy import symbols\nx, y, z = symbols('x y z')\nexpr = x + 2*y\nexpr\n```\n\n\n\n\n$\\displaystyle x + 2 y$\n\n\n\nNote that simply adding two symbols creates an expression. Now let's play around with it. \n\n\n```python\nexpr + 1\n```\n\n\n\n\n$\\displaystyle x + 2 y + 1$\n\n\n\n\n```python\nexpr - x\n```\n\n\n\n\n$\\displaystyle 2 y$\n\n\n\nNote that `expr - x` was not `x + 2y -x`\n\n\n```python\nx*expr\n```\n\n\n\n\n$\\displaystyle x \\left(x + 2 y\\right)$\n\n\n\n\n```python\nfrom sympy import expand, factor\nexpanded_expr = expand(x*expr)\nexpanded_expr\n```\n\n\n\n\n$\\displaystyle x^{2} + 2 x y$\n\n\n\n\n```python\nfactor(expanded_expr)\n```\n\n\n\n\n$\\displaystyle x \\left(x + 2 y\\right)$\n\n\n\n\n```python\nfrom sympy import diff, sin, exp\n\ndiff(sin(x)*exp(x), x)\n```\n\n\n\n\n$\\displaystyle e^{x} \\sin{\\left(x \\right)} + e^{x} \\cos{\\left(x \\right)}$\n\n\n\n\n```python\nfrom sympy import limit\n\nlimit(sin(x)/x, x, 0)\n```\n\n\n\n\n$\\displaystyle 1$\n\n\n\n\n```python\nfrom sympy import symbols\nequation = x**2 + z*x*y + z**3\nequation\n```\n\n\n\n\n$\\displaystyle x^{2} + x z^{2} + z^{3}$\n\n\n\n\n```python\nx * equation\n```\n\n\n\n\n$\\displaystyle x \\left(x^{2} + x y z + z^{3}\\right)$\n\n\n\n\n```python\nexpanded_equation = expand(x * equation)\nexpanded_equation\n```\n\n\n\n\n$\\displaystyle x^{3} + x^{2} y z + x z^{3}$\n\n\n\n\n```python\nfactor(expanded_equation)\n```\n\n\n\n\n$\\displaystyle x \\left(x^{2} + x y z + z^{3}\\right)$\n\n\n\n\n```python\ndiff(expanded_equation,x)\n```\n\n\n\n\n$\\displaystyle 3 x^{2} + 2 x y z + z^{3}$\n\n\n\n### Exercise\n\nSolve $x^2 - 2 = 0$ using sympy.solve\n\n\n```python\n# Type solution here\nfrom sympy import solve\nsolve(x**2 - 2, x)\n```\n\n\n\n\n$\\displaystyle \\left[ - \\sqrt{2}, \\ \\sqrt{2}\\right]$\n\n\n\n## Pretty printing\n\n\n```python\nfrom sympy import init_printing, Integral, sqrt\n\ninit_printing(use_latex='mathjax')\n```\n\n\n```python\nIntegral(sqrt(1/x), x)\n```\n\n\n\n\n$\\displaystyle \\int \\sqrt{\\frac{1}{x}}\\, dx$\n\n\n\n\n```python\nfrom sympy import latex\n\nlatex(Integral(sqrt(1/x), x))\n```\n\n\n\n\n '\\\\int \\\\sqrt{\\\\frac{1}{x}}\\\\, dx'\n\n\n\nMore symbols.\nExercise: fix the following piece of code\n\n\n```python\n# NBVAL_SKIP\n# The following piece of code is supposed to fail as it is\n# The exercise is to fix the code\nexpr2 = x + 2*y +3*z\n```\n\n### Exercise \n\nSolve $x + 2*y + 3*z$ for $x$\n\n\n```python\n# Solution here\nfrom sympy import solve\nexpression = x + 2 * y + 3 * z\nsolve(expression,x)\n```\n\n\n\n\n$\\displaystyle \\left[ - 2 y - 3 z\\right]$\n\n\n\nDifference between symbol name and python variable name\n\n\n```python\nx, y = symbols(\"y z\")\n```\n\n\n```python\nx\n```\n\n\n\n\n$\\displaystyle y$\n\n\n\n\n```python\ny\n```\n\n\n\n\n$\\displaystyle z$\n\n\n\n\n```python\n# NBVAL_SKIP\n# The following code will error until the code in cell 16 above is\n# fixed\nz\n```\n\n\n\n\n$\\displaystyle z$\n\n\n\nSymbol names can be more than one character long\n\n\n```python\ncrazy = symbols('unrelated')\n\ncrazy + 1\n```\n\n\n\n\n$\\displaystyle unrelated + 1$\n\n\n\n\n```python\nx = symbols(\"x\")\nexpr = x + 1\nx = 2\n```\n\nWhat happens when I print expr now? Does it print 3?\n\n\n```python\nprint(expr)\n```\n\n x + 1\n\n\nHow do we get 3?\n\n\n```python\nx = symbols(\"x\")\nexpr = x + 1\nexpr.subs(x, 2)\n```\n\n\n\n\n$\\displaystyle 3$\n\n\n\n## Equalities\n\n\n```python\nx + 1 == 4\n```\n\n\n\n\n False\n\n\n\n\n```python\nfrom sympy import Eq\n\nEq(x + 1, 4)\n```\n\n\n\n\n$\\displaystyle x + 1 = 4$\n\n\n\nSuppose we want to ask whether $(x + 1)^2 = x^2 + 2x + 1$\n\n\n```python\n(x + 1)**2 == x**2 + 2*x + 1\n```\n\n\n\n\n False\n\n\n\n\n```python\nfrom sympy import simplify\n\na = (x + 1)**2\nb = x**2 + 2*x + 1\n\nsimplify(a-b)\n```\n\n\n\n\n$\\displaystyle 0$\n\n\n\n### Exercise \nWrite a function that takes two expressions as input, and returns a tuple of two booleans. The first if they are equal symbolically, and the second if they are equal mathematically.\n\n## More operations\n\n\n```python\nz = symbols(\"z\")\nexpr = x**3 + 4*x*y - z\nexpr.subs([(x, 2), (y, 4), (z, 0)])\n```\n\n\n\n\n$\\displaystyle 36$\n\n\n\n\n```python\nfrom sympy import sympify\n\nstr_expr = \"x**2 + 3*x - 1/2\"\nexpr = sympify(str_expr)\nexpr\n```\n\n\n\n\n$\\displaystyle x^{2} + 3 x - \\frac{1}{2}$\n\n\n\n\n```python\nexpr.subs(x, 2)\n```\n\n\n\n\n$\\displaystyle \\frac{19}{2}$\n\n\n\n\n```python\nexpr = sqrt(8)\n```\n\n\n```python\nexpr\n```\n\n\n\n\n$\\displaystyle 2 \\sqrt{2}$\n\n\n\n\n```python\nexpr.evalf()\n```\n\n\n\n\n$\\displaystyle 2.82842712474619$\n\n\n\n\n```python\nfrom sympy import pi\n\npi.evalf(100)\n```\n\n\n\n\n$\\displaystyle 3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117068$\n\n\n\n\n```python\npi.evalf(1000)\n```\n\n\n\n\n$\\displaystyle 3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117067982148086513282306647093844609550582231725359408128481117450284102701938521105559644622948954930381964428810975665933446128475648233786783165271201909145648566923460348610454326648213393607260249141273724587006606315588174881520920962829254091715364367892590360011330530548820466521384146951941511609433057270365759591953092186117381932611793105118548074462379962749567351885752724891227938183011949129833673362440656643086021394946395224737190702179860943702770539217176293176752384674818467669405132000568127145263560827785771342757789609173637178721468440901224953430146549585371050792279689258923542019956112129021960864034418159813629774771309960518707211349999998372978049951059731732816096318595024459455346908302642522308253344685035261931188171010003137838752886587533208381420617177669147303598253490428755468731159562863882353787593751957781857780532171226806613001927876611195909216420199$\n\n\n\n\n```python\nfrom sympy import cos\n\nexpr = cos(2*x)\nexpr.evalf(subs={x: 2.4})\n```\n\n\n\n\n$\\displaystyle 0.0874989834394464$\n\n\n\n### Exercise\n\n\n\n```python\nfrom IPython.core.display import Image \nImage(filename='figures/comic.png')\n```\n\nWrite a function that takes a symbolic expression (like pi), and determines the first place where 789 appears.\nTip: Use the string representation of the number. Python starts counting at 0, but the decimal point offsets this\n\n## Solving an ODE\n\n\n```python\nfrom sympy import Function\n\nf, g = symbols('f g', cls=Function)\nf(x)\n```\n\n\n\n\n$\\displaystyle f{\\left(y \\right)}$\n\n\n\n\n```python\nf(x).diff()\n```\n\n\n\n\n$\\displaystyle \\frac{d}{d y} f{\\left(y \\right)}$\n\n\n\n\n```python\ndiffeq = Eq(f(x).diff(x, x) - 2*f(x).diff(x) + f(x), sin(x))\ndiffeq\n```\n\n\n\n\n$\\displaystyle f{\\left(y \\right)} - 2 \\frac{d}{d y} f{\\left(y \\right)} + \\frac{d^{2}}{d y^{2}} f{\\left(y \\right)} = \\sin{\\left(y \\right)}$\n\n\n\n\n```python\nfrom sympy import dsolve\n\ndsolve(diffeq, f(x))\n```\n\n\n\n\n$\\displaystyle f{\\left(y \\right)} = \\left(C_{1} + C_{2} y\\right) e^{y} + \\frac{\\cos{\\left(y \\right)}}{2}$\n\n\n\n## Finite Differences\n\n\n```python\n\nf = Function('f')\ndfdx = f(x).diff(x)\ndfdx.as_finite_difference()\n```\n\n\n\n\n$\\displaystyle - f{\\left(y - \\frac{1}{2} \\right)} + f{\\left(y + \\frac{1}{2} \\right)}$\n\n\n\n\n```python\nfrom sympy import Symbol\n\nd2fdx2 = f(x).diff(x, 2)\nh = Symbol('h')\nd2fdx2.as_finite_difference(h)\n```\n\n\n\n\n$\\displaystyle - \\frac{2 f{\\left(y \\right)}}{h^{2}} + \\frac{f{\\left(- h + y \\right)}}{h^{2}} + \\frac{f{\\left(h + y \\right)}}{h^{2}}$\n\n\n\nNow that we have seen some relevant features of vanilla SymPy, let's move on to Devito, which could be seen as SymPy finite differences on steroids!\n", "meta": {"hexsha": "40c65c0eed5c9ae91349ddd95d4cd39352f86cde", "size": 33978, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "tinkered with examples/userapi/00_sympy.ipynb", "max_stars_repo_name": "ofmla/Devito-playbox", "max_stars_repo_head_hexsha": "f3547c7c1bfd82cc32b51179c178f685ecf12e84", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-08T20:09:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-08T20:09:00.000Z", "max_issues_repo_path": "tinkered with examples/userapi/00_sympy.ipynb", "max_issues_repo_name": "ofmla/Devito-playbox", "max_issues_repo_head_hexsha": "f3547c7c1bfd82cc32b51179c178f685ecf12e84", "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": "tinkered with examples/userapi/00_sympy.ipynb", "max_forks_repo_name": "ofmla/Devito-playbox", "max_forks_repo_head_hexsha": "f3547c7c1bfd82cc32b51179c178f685ecf12e84", "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.2873481058, "max_line_length": 1639, "alphanum_fraction": 0.5189534405, "converted": true, "num_tokens": 2561, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810444238085, "lm_q2_score": 0.9173026556293917, "lm_q1q2_score": 0.8690351479429064}} {"text": "Determine the transformation of an aperture diameter of 7.5 kpc at the redshift of abell 370 to pixels. First transform the diameter in absolute size (kpc) to apparent size (arcseconds). Then transform apparent size to pixels using WCS.\n\n\n```python\nimport numpy as np \n\nfrom astropy.io import fits\nfrom astropy import units as u \nfrom astropy import cosmology\nfrom astropy.wcs import WCS\n```\n\n### Load Data\n\n\n```python\ninput_data_path = \"https://archive.stsci.edu/pub/hlsp/frontier/abell370/images/hst/v1.0-epoch2/hlsp_frontier_hst_wfc3-30mas-bkgdcor_abell370_f105w_v1.0-epoch2_drz.fits\"\n\nhdul = fits.open(input_data_path)\nhdu = hdul[0]\n\ndata = hdu.data\nheader = hdu.header\nwcs = WCS(header)\n```\n\n### Given\n\n\n```python\n# Given \naperture_diameter = (7.5 * u.kpc).to(u.Mpc)\n```\n\nNED data for abell 370:\n\nhttp://ned.ipac.caltech.edu/cgi-bin/objsearch?search_type=Obj_id&objid=132527&objname=1&img_stamp=YES&hconst=73.0&omegam=0.27&omegav=0.73&corr_z=1\n\n\n```python\n\"\"\"\nCosmology-Corrected Quantities [Ho = 70.50 km/sec/Mpc, Ωmatter = 0.27, Ωvacuum = 0.73]\n[Redshift 0.374247 as corrected to the Reference Frame defined by the 3K Microwave Background Radiation]\nLuminosity Distance : 2011 Mpc (m-M) = 41.52 mag\nAngular-Size Distance : 1065 Mpc (m-M) = 40.14 mag\nCo-Moving Radial Distance : 1463 Mpc (m-M) = 40.83 mag\nCo-Moving Tangential Dist. : 1463 Mpc (m-M) = 40.83 mag\nCo-Moving Volume : 13.1 Gpc^3\nLight Travel-Time : 4.073 Gyr\nAge at Redshift 0.374247 : 9.698 Gyr\nAge of Universe : 13.770 Gyr\nScale (Cosmology Corrected): 5161 pc/arcsec = 5.161 kpc/arcsec = 309.67 kpc/arcmin = 18.58 Mpc/degree\nSurface Brightness Dimming : Flux Density per Unit Area = 0.28038; Magnitude per Unit Area = 1.381 mag\n\"\"\"\n```\n\n\n\n\n '\\nCosmology-Corrected Quantities [Ho = 70.50 km/sec/Mpc, Ωmatter = 0.27, Ωvacuum = 0.73]\\n[Redshift 0.374247 as corrected to the Reference Frame defined by the 3K Microwave Background Radiation]\\nLuminosity Distance : 2011 Mpc (m-M) = 41.52 mag\\nAngular-Size Distance : 1065 Mpc (m-M) = 40.14 mag\\nCo-Moving Radial Distance : 1463 Mpc (m-M) = 40.83 mag\\nCo-Moving Tangential Dist. : 1463 Mpc (m-M) = 40.83 mag\\nCo-Moving Volume : 13.1 Gpc^3\\nLight Travel-Time : 4.073 Gyr\\nAge at Redshift 0.374247 : 9.698 Gyr\\nAge of Universe : 13.770 Gyr\\nScale (Cosmology Corrected): 5161 pc/arcsec = 5.161 kpc/arcsec = 309.67 kpc/arcmin = 18.58 Mpc/degree\\nSurface Brightness Dimming : Flux Density per Unit Area = 0.28038; Magnitude per Unit Area = 1.381 mag\\n'\n\n\n\n\n```python\nabell370_z = 0.375000\nabell370_distance = 1463 * u.Mpc # Comoving\n```\n\n### Equations\n\n\\begin{align}\n\\theta = \\frac{(z+1) * Diameter}{Distance_{Comoving}} = \\frac{Diameter}{Distance_{Angular Diameter} } \\\\\n\\end{align}\n\n### Compute angular diameter distance\n\n\n```python\ndef compute_angular_diameter_distance(d, z):\n return d/(z+1)\n```\n\n\n```python\nangular_diameter_distance = compute_angular_diameter_distance(abell370_distance, abell370_z)\nangular_diameter_distance\n```\n\n\n\n\n$1064 \\; \\mathrm{Mpc}$\n\n\n\n\n```python\n# check astropy cosmology\ncosmology.WMAP5.angular_diameter_distance(abell370_z)\n```\n\n\n\n\n$1068.4053 \\; \\mathrm{Mpc}$\n\n\n\n### Find angular diameter\n\n\n```python\nangular_diameter = np.tan((aperture_diameter / angular_diameter_distance).value) * u.rad \nangular_diameter \n```\n\n\n\n\n$7.0488722 \\times 10^{-6} \\; \\mathrm{rad}$\n\n\n\n\n```python\n# check astropy cosmology\n(cosmology.WMAP5.arcsec_per_kpc_proper(abell370_z) * aperture_diameter.to('kpc')).to('rad')\n```\n\n\n\n\n$7.0198082 \\times 10^{-6} \\; \\mathrm{rad}$\n\n\n\n### Convert to arcsec\n\n\n```python\nangular_diameter = angular_diameter.to(\"arcsec\")\nangular_diameter\n```\n\n\n\n\n$1.4539343 \\; \\mathrm{{}^{\\prime\\prime}}$\n\n\n\n### Find Pixel Size \n\nIn this section we convert the angular size into pixel size. The way we do this is by adding the angular size to the `CRVAL` of the WCS and then converting that world coordinate to pixel values. After getting the new pixel values we subtract the `CRPIX` values to find the difference (angular size). Because RA-DEC is an equatorial coordinate system, I have decided its best to add the angular size to the Dec component of the WCS CRVAL (Dec axis is a great circle). It looks like the image `CRVAL` is sufficiently away from the pols of the celestial sphere, so no need to worry about loops around +/- 90 degrees. \n\n\n```python\n# Load center pixel from data's WCS \n\nra_0 = wcs.wcs.crval[0] * u.Unit(wcs.wcs.cunit[0])\ndec_0 = wcs.wcs.crval[1] * u.Unit(wcs.wcs.cunit[1])\n\nprint(ra_0, \",\", dec_0)\n```\n\n 39.96301 deg , -1.5882933 deg\n\n\n\n```python\n# Add angular_diameter to center Dec value \n\nra_1 = ra_0\ndec_1 = dec_0 + angular_diameter\n\nprint(ra_1, \",\", dec_1)\n```\n\n 39.96301 deg , -1.5878894293737262 deg\n\n\n\n```python\n# Convert ra_1, dec_1 into pixels\n\nworld = np.array([[ra_1.value, dec_1.value],], dtype=np.float64) * u.deg\npixcrd = wcs.wcs_world2pix(world, 1)\n\npixcrd\n```\n\n\n\n\n array([[4800. , 6648.46447515]])\n\n\n\n\n```python\n# Look at the center pixel values\nwcs.wcs.crpix\n```\n\n\n\n\n array([4800., 6600.])\n\n\n\n\n```python\n# Find the difference b/w the center pixel and the angular offset pixel:\npixel_diff = pixcrd - wcs.wcs.crpix \nassert abs(pixel_diff[0,0]) < 1e-10\npixel_diff[0,1]\n```\n\n\n\n\n 48.46447515439377\n\n\n\n\n```python\n# Find ceiling of pixel diff to conclude pixel size\npixel_size = int(np.ceil(pixel_diff[0,1]))\n\npixel_size\n```\n\n\n\n\n 49\n\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "a310fed721bc3069bbe0e01101e193737b2cd8e1", "size": 11445, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/cosmology/Aperture Diameter of 7.5 kpc at Abell 370.ipynb", "max_stars_repo_name": "robelgeda/lcbg", "max_stars_repo_head_hexsha": "5fb999c7cab17d1e516387314529ba54a2fd1df7", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-09-20T14:29:39.000Z", "max_stars_repo_stars_event_max_datetime": "2017-09-20T14:29:39.000Z", "max_issues_repo_path": "notebooks/cosmology/Aperture Diameter of 7.5 kpc at Abell 370.ipynb", "max_issues_repo_name": "robelgeda/lcbg", "max_issues_repo_head_hexsha": "5fb999c7cab17d1e516387314529ba54a2fd1df7", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 26, "max_issues_repo_issues_event_min_datetime": "2020-03-13T16:42:53.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-09T18:06:47.000Z", "max_forks_repo_path": "notebooks/cosmology/Aperture Diameter of 7.5 kpc at Abell 370.ipynb", "max_forks_repo_name": "robelgeda/lcbg", "max_forks_repo_head_hexsha": "5fb999c7cab17d1e516387314529ba54a2fd1df7", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-07-13T19:47:08.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-13T18:26:39.000Z", "avg_line_length": 24.7192224622, "max_line_length": 872, "alphanum_fraction": 0.5332459589, "converted": true, "num_tokens": 1807, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750387190132, "lm_q2_score": 0.9111797082028671, "lm_q1q2_score": 0.8686048716170672}} {"text": "We will be exploring the *relative entropy* or Kullback-Leibler divergence (KL).\n\n$$ D_{q}(p) = \\mathbb{E}_{p}\\bigg[\\log\\frac{p(x)}{q(x)}\\bigg] $$\n\nTo build an intuition about what this important quantity is computing we examine the right hand side more closely. For continuous random vairables the KL is computed as follows\n\n\\begin{align}\n\\mathbb{E}_{p}\\bigg[\\log\\frac{p(x)}{q(x)}\\bigg] & = \\int p(x) \\log \\frac{p(x)}{q(x)} dx \\\\\n& = -\\int p(x) \\log \\frac{q(x)}{p(x)} dx \\\\\n& = -\\int p(x) \\log q(x) dx - \\bigg(-\\int p(x) \\log p(x) \\bigg ) dx\\\\\n& = H_q(p) - H(p) \\\\\n\\end{align}\n\n$H(p)$ is the entropy of $p$, or average amount of information received when observing a value from $p$. $H_q(p)$ is the cross entropy which is how much more information we need to represent an observation from $q$ by $p$. The KL is their difference, a measure of how imprecise we are when describing events from $p$ with $q$. In terms of inference KL measures what we gain by changing our prior from $q$ to $p$.\n\nLet's take a look at how the KL changes as a function of some simple distributions. Let's let $p$ be a bimodal mixture of gaussians and q, a unimodal gaussian.\n\n\\begin{align}\np(x) & = \\frac{2}{5}\\mathcal{N}(x\\lvert -3,1) + \\frac{3}{5}\\mathcal{N}(x,\\lvert 3,1) \\\\\nq(x) & = \\mathcal{N}(x \\lvert 0,1) \\\\\n\\end{align}\n\n\n```python\nimport matplotlib.pyplot as plt\n%matplotlib inline\nfrom ipywidgets import interactive\nfrom scipy.stats import norm\nimport numpy as np\n\nclass gmm: # gaussian mixture model\n \n def __init__(self, pis, params):\n self.params = params # [[mu1, sig1], [mu2, sig2],...]\n self.components = params.shape[0]\n self.pis = pis\n \n def __call__(self, x):\n pis = self.pis\n p = self.params\n sz = self.components\n return np.array([pis[i]*norm.pdf(x,*(p[i])) for i in range(sz)]).sum(axis=0)\n \n def sample(self, n_samples):\n mode_id = np.random.choice(self.components, size=n_samples, replace=True)\n return np.array([norm.rvs(*(self.params[i])) for i in mode_id]) \n\n \np = gmm([0.4,0.6], np.array([[-3,1],[3,1]]))\nq = gmm([1], np.array([[0,1]]))\n\n\nfig, ax = plt.subplots(1, 1)\nx = np.linspace(-7,7,1000)\nax.plot(x, p(x), c='r', lw=4, label='$p(x)$')\nax.plot(x, q(x), c='b', lw=4, label='$q(x)$')\nax.legend()\nplt.show()\n```\n\nTo calculate $D_q(p)$ we observe that the integral must be evaluated over all values of the sample space. Often times we cannot calculate the integral analytically. However with a sufficiently large sample $N$ we can approximate it\n\n\\begin{align}\nD_q(p) & = \\int_a^b p(x) \\log \\frac{p(x)}{q(x)} dx \\\\\n& \\approx \\frac{b-a}{N} \\sum_{n=1}^N p(x_n) \\log \\frac{p(x_n)}{q(x_n)}\n\\end{align}\n\n\n```python\ndef forward_kl_int(p,q,n_samples):\n a = -10\n b = 10\n samples = np.linspace(a,b,n_samples)\n ps = p(samples)\n return (ps*np.log(ps/q(samples))).sum()*((b-a)/n_samples)\n\nkls = []\nfor i in range(10,200):\n kls.append(forward_kl_int(p,q,i))\n\nplt.plot(kls);\nplt.show()\n```\n\n\n```python\ndef forward_kl_samp(p,q,n_samples):\n samples = p.sample(n_samples)\n ps = p(samples)\n return np.log(ps/q(samples)).sum()/n_samples\n\nkls = []\nfor i in range(10,500):\n kls.append(forward_kl_samp(p,q,i))\n\nplt.plot(kls);\nplt.show()\n```\n\nLet us examine how the KL changes as we modify the parameters of $q$\n\n\n```python\nx = np.linspace(-7,7,1000)\nkls = []\n\ndef f(mu, sig):\n q = gmm([1], np.array([[mu,sig]]))\n kl = forward_kl_int(p,q,200)\n kls.append(kl)\n fig, ax = plt.subplots(1, 2, figsize=(15,5), dpi=80)\n ax[0].plot(x, p(x), c='r', lw=4, label='$p(x)$')\n ax[0].plot(x, q(x), c='b', lw=4, label='$q(x)$')\n ax[0].legend()\n ax[1].plot(kls)\n plt.show()\n\ninteractive_plot = interactive(f, mu=(-3, 3, 0.1), sig=(0.05, 4, 0.1))\noutput = interactive_plot.children[-1]\noutput.layout.height = '35px'\ninteractive_plot\n```\n\nWe find the minimum occurs when the mean of $q$ is between the two means of $p$. We can begin to see why this is by examining $D_q(p)$. We reproduce it here for reference.\n\n\\begin{align}\nD_q(p) & = \\int p(x) \\log \\frac{p(x)}{q(x)} dx \\\\\n& = H_q(p) - H(p) \\\\\n\\end{align}\n\nNoticing that the entropy of $p$, $H(p)$, does not depend on $q$ we see that minimizing $D_q(p)$ with respect to $q$ amounts to minimizing the cross entropy term $H_q(p)$ with respect to $q$.\n\n\\begin{equation}\nH_q(p) = \\int p(x) \\log \\frac{1}{q(x)} dx \\\\\n\\end{equation}\n\nWhen $p$ is small, the logarithm term will not contribute much to the integral. To keep the integral small then, we need the logarithm term to be small when $p$ is large. In other words $D_q(p)$ is minimized when $q$ is chosen to be as large as possible whenever $p$ is large. Because $q$ is unimodal, this is achieved when $q$ is between the peaks of the mixture model and has high tails. This way it allocates high probability density on both modes.\n\n### Forward vs Reverse KL\n\nWhen $q$ is the variable distribution, $D_q(p)$ is called the *forward KL*. The forward KL tells us how inefficient it us for us to represent $q$ by $p$. So by minimizing the KL with respect to $q$ we found the optimal distribution $q^*$ that $p$ could represent. This is often not the goal in machine learning. More often we are presented with a distribution, or samples from it, and would like to find the optimal distribution to represent it. This is the reverse problem, and it can be conveniently expressed using the *reverse KL*, $D_p(q)$.\n\n\\begin{align}\nD_p(q) & = \\int q(x) \\log \\frac{q(x)}{p(x)} dx \\\\\n& = H_p(q) - H(q) \\\\\n\\end{align}\n\nIt is important to note that we interpret the KL as either forward or reverse soley by which distribution is free. \n\n\n```python\ndef reverse_kl_int(q,p,n_samples):\n a = -7\n b = 7\n samples = np.linspace(a,b,n_samples)\n qs = q(samples)\n return (qs*np.log(qs/p(samples))).sum()*((b-a)/n_samples)\n\nkls = []\nfor i in range(10,400):\n kls.append(reverse_kl_int(q,p,i))\n\nplt.plot(kls);\nplt.show()\n```\n\n\n```python\nx = np.linspace(-7,7,1000)\nkls = []\n\ndef f(mu, sig):\n q = gmm([1], np.array([[mu,sig]]))\n kl = reverse_kl_int(q,p,2000)\n kls.append(kl)\n fig, ax = plt.subplots(1, 2, figsize=(15,5), dpi=80)\n ax[0].plot(x, p(x), c='r', lw=4, label='$p(x)$')\n ax[0].plot(x, q(x), c='b', lw=4, label='$q(x)$')\n ax[0].legend()\n ax[1].plot(kls)\n plt.show()\n\ninteractive_plot = interactive(f, mu=(-3, 3, 0.1), sig=(0.05, 6, 0.1))\noutput = interactive_plot.children[-1]\noutput.layout.height = '35px'\ninteractive_plot\n```\n\nCode from Tuan Anh Le's Blog for showing the difference between Forward and Reverse KL. Blog - http://www.tuananhle.co.uk/notes/reverse-forward-kl.html\n\n\n```python\nimport numpy as np\nimport scipy as sp\nimport scipy.stats\nimport matplotlib.pyplot as plt\n\n\nclass GaussianMixture1D:\n def __init__(self, mixture_probs, means, stds):\n self.num_mixtures = len(mixture_probs)\n self.mixture_probs = mixture_probs\n self.means = means\n self.stds = stds\n\n def sample(self, num_samples=1):\n mixture_ids = np.random.choice(self.num_mixtures, size=num_samples, p=self.mixture_probs)\n result = np.zeros([num_samples])\n for sample_idx in range(num_samples):\n result[sample_idx] = np.random.normal(\n loc=self.means[mixture_ids[sample_idx]],\n scale=self.stds[mixture_ids[sample_idx]]\n )\n return result\n\n def logpdf(self, samples):\n mixture_logpdfs = np.zeros([len(samples), self.num_mixtures])\n for mixture_idx in range(self.num_mixtures):\n mixture_logpdfs[:, mixture_idx] = scipy.stats.norm.logpdf(\n samples,\n loc=self.means[mixture_idx],\n scale=self.stds[mixture_idx]\n )\n return sp.misc.logsumexp(mixture_logpdfs + np.log(self.mixture_probs), axis=1)\n\n def pdf(self, samples):\n return np.exp(self.logpdf(samples))\n\n\ndef approx_kl(gmm_1, gmm_2, xs):\n ys = gmm_1.pdf(xs) * (gmm_1.logpdf(xs) - gmm_2.logpdf(xs))\n return np.trapz(ys, xs)\n\n\ndef minimize_pq(p, xs, q_means, q_stds):\n q_mean_best = None\n q_std_best = None\n kl_best = np.inf\n for q_mean in q_means:\n for q_std in q_stds:\n q = GaussianMixture1D(np.array([1]), np.array([q_mean]), np.array([q_std]))\n kl = approx_kl(p, q, xs)\n if kl < kl_best:\n kl_best = kl\n q_mean_best = q_mean\n q_std_best = q_std\n\n q_best = GaussianMixture1D(np.array([1]), np.array([q_mean_best]), np.array([q_std_best]))\n return q_best, kl_best\n\n\ndef minimize_qp(p, xs, q_means, q_stds):\n q_mean_best = None\n q_std_best = None\n kl_best = np.inf\n for q_mean in q_means:\n for q_std in q_stds:\n q = GaussianMixture1D(np.array([1]), np.array([q_mean]), np.array([q_std]))\n kl = approx_kl(q, p, xs)\n if kl < kl_best:\n kl_best = kl\n q_mean_best = q_mean\n q_std_best = q_std\n\n q_best = GaussianMixture1D(np.array([1]), np.array([q_mean_best]), np.array([q_std_best]))\n return q_best, kl_best\n\n\ndef main():\n p_second_means_min = 0\n p_second_means_max = 10\n num_p_second_means = 5\n p_second_mean_list = np.linspace(p_second_means_min, p_second_means_max, num_p_second_means)\n\n p = [None] * num_p_second_means\n q_best_forward = [None] * num_p_second_means\n kl_best_forward = [None] * num_p_second_means\n q_best_reverse = [None] * num_p_second_means\n kl_best_reverse = [None] * num_p_second_means\n\n for p_second_mean_idx, p_second_mean in enumerate(p_second_mean_list):\n p_mixture_probs = np.array([0.5, 0.5])\n p_means = np.array([0, p_second_mean])\n p_stds = np.array([1, 1])\n p[p_second_mean_idx] = GaussianMixture1D(p_mixture_probs, p_means, p_stds)\n\n q_means_min = np.min(p_means) - 1\n q_means_max = np.max(p_means) + 1\n num_q_means = 20\n q_means = np.linspace(q_means_min, q_means_max, num_q_means)\n\n q_stds_min = 0.1\n q_stds_max = 5\n num_q_stds = 20\n q_stds = np.linspace(q_stds_min, q_stds_max, num_q_stds)\n\n trapz_xs_min = np.min(np.append(p_means, q_means_min)) - 3 * np.max(np.append(p_stds, q_stds_max))\n trapz_xs_max = np.max(np.append(p_means, q_means_min)) + 3 * np.max(np.append(p_stds, q_stds_max))\n num_trapz_points = 1000\n trapz_xs = np.linspace(trapz_xs_min, trapz_xs_max, num_trapz_points)\n\n q_best_forward[p_second_mean_idx], kl_best_forward[p_second_mean_idx] = minimize_pq(\n p[p_second_mean_idx], trapz_xs, q_means, q_stds\n )\n q_best_reverse[p_second_mean_idx], kl_best_reverse[p_second_mean_idx] = minimize_qp(\n p[p_second_mean_idx], trapz_xs, q_means, q_stds\n )\n\n # plotting\n fig, axs = plt.subplots(nrows=1, ncols=num_p_second_means, sharex=True, sharey=True)\n fig.set_size_inches(8, 1.5)\n for p_second_mean_idx, p_second_mean in enumerate(p_second_mean_list):\n xs_min = -5\n xs_max = 15\n num_plot_points = 1000\n xs = np.linspace(xs_min, xs_max, num_plot_points)\n axs[p_second_mean_idx].plot(xs, p[p_second_mean_idx].pdf(xs), label='$p$', color='black')\n axs[p_second_mean_idx].plot(xs, q_best_forward[p_second_mean_idx].pdf(xs), label='$\\mathrm{argmin}_q \\,\\mathrm{KL}(p || q)$', color='black', linestyle='dashed')\n axs[p_second_mean_idx].plot(xs, q_best_reverse[p_second_mean_idx].pdf(xs), label='$\\mathrm{argmin}_q \\,\\mathrm{KL}(q || p)$', color='black', linestyle='dotted')\n\n axs[p_second_mean_idx].spines['right'].set_visible(False)\n axs[p_second_mean_idx].spines['top'].set_visible(False)\n axs[p_second_mean_idx].set_yticks([])\n axs[p_second_mean_idx].set_xticks([])\n\n axs[2].legend(ncol=3, loc='upper center', bbox_to_anchor=(0.5, 0), fontsize='small')\n filenames = ['reverse_forward_kl.pdf', 'reverse_forward_kl.png']\n for filename in filenames:\n fig.savefig(filename, bbox_inches='tight', dpi=200)\n print('Saved to {}'.format(filename))\n\n\nif __name__ == '__main__':\n main()\n```\n\n /Users/nathancrock/anaconda3/lib/python3.6/site-packages/ipykernel/__main__.py:32: DeprecationWarning: `logsumexp` is deprecated!\n Importing `logsumexp` from scipy.misc is deprecated in scipy 1.0.0. Use `scipy.special.logsumexp` instead.\n\n\n Saved to reverse_forward_kl.pdf\n Saved to reverse_forward_kl.png\n\n\n$$I(x) = -\\log p(x)$$\n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\nx = np.linspace(0.001,1.2,1000)\ny = -np.log(x)\nplt.plot(x,y)\nplt.plot([0,1.2],[0,0],ls='dashed',c='k')\nplt.show()\n```\n\n$$ H(p) = \\mathbb{E}_{p}\\big[-\\log p(x)\\big] = \\int p(x) \\big(- \\log p(x) \\big) dx$$\n\n\n```python\nx = np.linspace(0.001,0.9999,1000)\ny = x*(-np.log2(x)) + (1-x)*(-np.log2(1-x))\nplt.plot(x,y)\nplt.plot([0,0.99],[0,0],ls='dashed',c='k')\nplt.show()\n```\n\n$$ \\min_{q(x)} KL(q(x)||p(x)) $$\n\n\n```python\n\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "15bf2ca84279a51404903882db9c5259aa6a2397", "size": 184789, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "dissertation/Kullback-Leibler Divergence.ipynb", "max_stars_repo_name": "mathnathan/notebooks", "max_stars_repo_head_hexsha": "63ae2f17fd8e1cd8d80fef8ee3b0d3d11d45cd28", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-12-04T11:04:45.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-04T11:04:45.000Z", "max_issues_repo_path": "dissertation/Kullback-Leibler Divergence.ipynb", "max_issues_repo_name": "mathnathan/notebooks", "max_issues_repo_head_hexsha": "63ae2f17fd8e1cd8d80fef8ee3b0d3d11d45cd28", "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": "dissertation/Kullback-Leibler Divergence.ipynb", "max_forks_repo_name": "mathnathan/notebooks", "max_forks_repo_head_hexsha": "63ae2f17fd8e1cd8d80fef8ee3b0d3d11d45cd28", "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": 302.9327868852, "max_line_length": 39298, "alphanum_fraction": 0.9087283334, "converted": true, "num_tokens": 3937, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572777987970316, "lm_q2_score": 0.9073122232403329, "lm_q1q2_score": 0.8685498478851468}} {"text": "# Exponential Smoothing Procedures\n\n\n```python\nimport pandas as pd\nimport numpy as np\nimport statsmodels as sm\n```\n\n\n```python\nsm.__version__\n```\n\n## Aims of Exponential Smoothing Procedures\n* In the naive forecasting method we assumed that the most recent observation was the most important.\n* In the average method, we used all observations, but gave them all equal weight (they were all equally important).\n* Exponential smoothing falls between these two extremes.\n * ES forecasts are weighted averages of past observations.\n * More recent observations carry more weight than older ones;\n * Or to put it another way: the weights decrease exponentially as the observations get older.\n\n\n## Types of Exponential Smoothing Procedure\n* **Simple Exponential Smoothing (SES)**\n * No trend or seasonality\n* **Holt's Linear Method**\n * Extends (SES) to include a linear trend\n* **Holt-Winters Exponential Smoothing (HW)**\n * The most complex procedure that handles both trend and seasonality\n \nBoth Holt's linear method and HW can include a damped trend.\n\n## Simple Exponential Smoothing (SES)\nSES consists of two equations the forecast equation (1.1) and the smoothing equation (1.2):\n
SES\n\n$F_{t+h} = l_t \\tag{1.1}$\n\n$l_{t} = \\alpha y_t + (1 - \\alpha) l_{t-1} \\tag{1.2} $\n
\n\n**where** \n* $\\alpha$ = a smoothing parameter between 0 and 1.\n* $l_t$ = the current level at time t.\n* $y_t$ = The ground truth / real world observation at time t\n\nIf you haven't worked with equations for a while this might look complicated. The reality is that it is a very simple method. To output a forecast involves plugging a few numbers.\n\nEquation (1.2) is called the smoothing or level equation. In words level ($l_{t}$) is based on weighting the most recent observation ($y_t$) by a smoothing constant called $\\alpha$ and weighting the previous level by $(1-\\alpha)$. \n\n**Smoothing Example 1**\n\n* $y_t = 150$\n* $l_{t-1} = 120$\n* $alpha = 0.2$\n* $l_{t} = \\alpha y_t + (1 - \\alpha) l_{t-1}$\n\n\n```python\ndef smooth_level(obs, level, alpha):\n '''Returns a exponentially smoothed level assuming \n no trend or seasonality'''\n return (alpha * obs) + ((1 - alpha)*level)\n```\n\n\n```python\ncurrent_obs = 150\nlast_level = 120\nalpha = 0.2\n\n#call the function that implements the smoothing eq.\nsmooth_level(current_obs, last_level, alpha)\n```\n\n**Smoothing Example 2**\n\n* $y_t = 150$\n* $l_{t-1} = 120$\n* $alpha = 0.8$\n\n**Question: What happens when alpha is set to 0.0 or 1.0?**\n\n**What does this tell you about the role of alpha?**\n\n\n```python\ncurrent_obs = 150 #y_t\nlast_level = 120 #l_t-1\nalpha = 0.8 \n\n#call the function that implements the smoothing eq.\nsmooth_level(current_obs, last_level, alpha)\n```\n\n**Equation (1.1)** is called the *forecast equation*. In words is means that the forecast h steps ahead is equal to the current level. In otherwords **it is a flat forecast**. It just carries the last value produced the smoothing equation forward. We will see a visual example of that shortly.\n\n**SES Forecast Example**\n\nGiven the following inputs, create a 6 step ahead forecast.\n\n* $y_t = 150$\n* $l_{t-1} = 120$\n* $alpha = 0.2$\n\n\n```python\ndef flat_forecast(level, horizon):\n '''Returns a vector of length horizon with all values \n set to level'''\n return np.full(shape=horizon, fill_value=level)\n```\n\n\n```python\ncurrent_obs = 150\nlast_level = 120\nALPHA = 0.2\nHORIZON = 6\n\n#call the function that implements the smoothing eq.\nnew_level = smooth_level(current_obs, last_level, ALPHA)\nflat_forecast(new_level, HORIZON)\n```\n\n\n\n**The good news is that you do not need to implement SES or the other more complex versions of Exponential Smoothing.**\n\n[statsmodels](https://www.statsmodels.org/stable/index.html) is a Python module that provides classes and functions for the estimation of many different statistical models, as well as for conducting statistical tests, and statistical data exploration. \n\nThere are two statsmodels libraries that you can use for SES.\n\n```python\nstatsmodels.tsa.holtwinters.SimpleExpSmoothing\n```\nThe `SimpleExpSmoothing` [class](https://www.statsmodels.org/stable/generated/statsmodels.tsa.holtwinters.SimpleExpSmoothing.html?highlight=simpleexpsmoothing#statsmodels.tsa.holtwinters.SimpleExpSmoothing) implements the SES equations described above. It is fast easy to use and provides an optimisation procedure to automatically select the best $\\alpha$ value.\n\n```python\nstatsmodels.tsa.statespace.exponential_smoothing.ExponentialSmoothing\n```\n\nThe `ExponentialSmoothing` class implements SES as a **statistical model**. The theory of this is beyond the scope of this tutorial, but the fundermental idea is that the class provides a statistical model that is equivalent to the mathematical model outlined above. The advantage of the statistical model is that point forecasts can be enhanced with a **prediction interval**. Where possible, it is recommended that point forecasts are always accompanied by a prediction interval. For this reason it is recommended that the [statespace implementation](https://www.statsmodels.org/stable/generated/statsmodels.tsa.statespace.exponential_smoothing.ExponentialSmoothing.html?highlight=statespace%20exponential) is used over and above `SimpleExpSmoothing`.\n\nFor more information on the statespace formulation I recommend reading the relevant [chapter](https://otexts.com/fpp2/ets.html) Prof Rob Hyndman's free and open book on forecasting.\n\n**SES Example: Nile flow data 1871 to 1930**\n\n\n```python\nnile = pd.read_csv('data/nile.csv', index_col='year', parse_dates=True)\nnile.index.freq = \"AS\"\n```\n\n\n```python\nnile['flow'].plot(figsize=(12,4))\n```\n\n\n```python\nfrom statsmodels.tsa.statespace.exponential_smoothing import ExponentialSmoothing\n```\n\n\n```python\n#lets predict the next dacade of flow.\nHORIZON = 10\n\n#for SES pass in the endog argument as your data\nmodel = ExponentialSmoothing(endog=nile['flow'])\nresults = model.fit()\n\npreds = results.get_forecast(steps=HORIZON)\n\n#the summary_frame() method returns a pandas data frame.\n#here alpha refers to alpha for a prediction interval 0.2 = 80% pred interval.\n#make sure you don't confuse this alpha with the SES smoothing parameter!\npreds.summary_frame(alpha=0.2).head(3)\n```\n\n\n```python\n#plot the fitted values and prediction\nax = nile['flow'].plot(figsize=(12,4))\nforecast_80 = preds.summary_frame(alpha=0.2)[['mean', 'mean_ci_lower', 'mean_ci_upper']]\nforecast_90 = preds.summary_frame(alpha=0.1)[['mean', 'mean_ci_lower', 'mean_ci_upper']]\n\n\nax.fill_between(forecast_90.index,forecast_90['mean_ci_lower'], forecast_90['mean_ci_upper'], \n alpha=0.5,\n label='90% PI');\n\nax.fill_between(forecast_80.index,forecast_80['mean_ci_lower'], forecast_80['mean_ci_upper'], \n alpha=0.5,\n label='80% PI');\n\nforecast_80['mean'].plot(ax=ax, label='forecast', color='red');\n\nresults.fittedvalues.plot(ax=ax, label='fitted', color='green', linestyle='--')\n\nax.legend(loc=3);\n```\n\n\n```python\n#lets have a look at the fitted model\nresults.summary()\n```\n\n## Holt's Method for Linear Trend\n\nHolt's linear method adds a second smoothing parameter $\\beta$ and a third equation representing the trend.\n\n
Holt's Linear Method\n\n$F_{t+h} = l_t + hb_t \\tag{2.1}$\n\n\\begin{equation}\n l_t = \\alpha Y_t + (1 - \\alpha) (l_{t-1} + b_{t-1}) \\tag{2.2}\n\\end{equation} \n\n\\begin{equation}\n b_t = \\beta (l_t - l_{t-1}) + (1 - \\beta)b_{t-1} \\tag{2.3}\n\\end{equation}\n
\n\n\n**Example: US Gross Domestic Product 1920 to 2019.**\n\n\n```python\ntrain = pd.read_csv('data/GDPCA.csv', index_col='DATE', parse_dates=True)\ntrain.index.freq = 'AS'\ntrain.plot(figsize=(12,4));\n```\n\n\n```python\n#forecast 30 years ahead.\nHORIZON = 30\n\n#pass in the trend parameter as true\nmodel = ExponentialSmoothing(endog=train, trend=True)\nresults = model.fit()\n\npreds = results.get_forecast(steps=HORIZON)\n\n#here alpha refers to alpha for a prediction interval \n#(not to be confused with the smoothing parameter!)\npreds.summary_frame(alpha=0.2).head(2)\n```\n\n\n```python\nax = train.plot(figsize=(12,4))\n\nforecast_80 = preds.summary_frame(alpha=0.2)[['mean', 'mean_ci_lower', 'mean_ci_upper']]\nforecast_90 = preds.summary_frame(alpha=0.1)[['mean', 'mean_ci_lower', 'mean_ci_upper']]\n\n\nax.fill_between(forecast_90.index,forecast_90['mean_ci_lower'], forecast_90['mean_ci_upper'], \n alpha=0.5,\n label='90% PI');\n\nax.fill_between(forecast_80.index,forecast_80['mean_ci_lower'], forecast_80['mean_ci_upper'], \n alpha=0.5,\n label='80% PI');\n\nforecast_90['mean'].plot(ax=ax, color='red')\nresults.fittedvalues.plot(ax=ax, color='green', linestyle='--')\nax.legend(['train', 'point forecast', 'fitted','90%PI', '80% PI']);\n```\n\n\n```python\nresults.summary()\n```\n\n### Introducing a damped trend.\n\nIt is often beneficial to introduce a damped trend into long term forecasting. The following code illustrates the procedure.\n\n\n```python\n#forecast 30 years ahead.\nHORIZON = 30\n\n#note the damped_trend parameter\nmodel = ExponentialSmoothing(endog=train, trend=True, damped_trend=True)\nresults = model.fit()\npreds = results.get_forecast(steps=HORIZON)\n\nax = train.plot(figsize=(12,4))\nforecast_80 = preds.summary_frame(alpha=0.2)[['mean', 'mean_ci_lower', 'mean_ci_upper']]\nforecast_90 = preds.summary_frame(alpha=0.1)[['mean', 'mean_ci_lower', 'mean_ci_upper']]\nax.fill_between(forecast_90.index,forecast_90['mean_ci_lower'], forecast_90['mean_ci_upper'], \n alpha=0.5,\n label='90% PI');\nax.fill_between(forecast_80.index,forecast_80['mean_ci_lower'], forecast_80['mean_ci_upper'], \n alpha=0.5,\n label='80% PI');\nforecast_90['mean'].plot(ax=ax, color='red')\nresults.fittedvalues.plot(ax=ax, color='green', linestyle='--')\nax.legend(['train', 'point forecast', 'fitted','90%PI', '80% PI']);\n```\n\n## Holt-Winters Exponential Smoothing\n\n* Holt-Winters (HW) Exponential Smoothing procedures handle **trend and seasonality**. \n* There are two versions of HW that that handle additive and multiplicative seasonality.\n* In both cases a seasonality equation and a seasonal smoothing constant $\\gamma$ are added.\n* The level $l_t$ is seasonally adjusted\n * additive model: the seasonal component is an absolute value subtracted from the level\n * multiplicative model: the seasonal component is a percentage. The level is divided by it.\n\n\n\n\n\n### Additive Method\n\nThe additive approach is used when the variance in the data is roughly constant. \n\n\n
HW Additive\n\n$F_{t+h} = l_t + hb_t + s_{t+h-m(k+1)}\\tag{3.1}$\n\n\\begin{equation}\n l_t = \\alpha (y_t - s_{t-m}) + (1 - \\alpha) (l_{t-1} + b_{t-1}) \\tag{3.2}\n\\end{equation} \n\n\\begin{equation}\n b_t = \\beta (l_t - l_{t-1}) + (1 - \\beta)b_{t-1} \\tag{3.3}\n\\end{equation}\n\n\\begin{equation}\n s_t = \\gamma (y_t - l_t - s_{t-m}) + (1 - \\gamma) s_{t-m} \\tag{3.4}\n\\end{equation}\n
\n
\n\n**Additive example. Australian quarterly beer production**\n\n\n```python\nfrom pmdarima.datasets import load_ausbeer\n```\n\n\n```python\nausbeer = load_ausbeer(as_series=True)\n#index is 1956:Q1 to 2008:Q3\nausbeer.index = pd.date_range(start='1956Q1', periods=212, freq='Q')\nausbeer.plot(figsize=(12,4));\n```\n\n\n```python\n#lets predict the next 10 years\nHORIZON = 40\n\n#for SES pass in the endog argument as your data\nmodel = ExponentialSmoothing(endog=ausbeer, seasonal=4)\nresults = model.fit()\n\npreds = results.get_forecast(steps=HORIZON)\npreds.summary_frame(alpha=0.2).head(3)\n```\n\n\n```python\nax = ausbeer.plot(figsize=(12,4))\nforecast_80 = preds.summary_frame(alpha=0.2)[['mean', 'mean_ci_lower', 'mean_ci_upper']]\nforecast_90 = preds.summary_frame(alpha=0.1)[['mean', 'mean_ci_lower', 'mean_ci_upper']]\nax.fill_between(forecast_90.index,forecast_90['mean_ci_lower'], forecast_90['mean_ci_upper'], \n alpha=0.5,\n label='90% PI');\nax.fill_between(forecast_80.index,forecast_80['mean_ci_lower'], forecast_80['mean_ci_upper'], \n alpha=0.5,\n label='80% PI');\nforecast_90['mean'].plot(ax=ax, color='red')\nresults.fittedvalues.plot(ax=ax, color='green', linestyle='--')\nax.legend(['train', 'point forecast', 'fitted','90%PI', '80% PI'], bbox_to_anchor=(1.05, 1), loc=2);\n```\n\n\n```python\nresults.summary()\n```\n\n### Multiplicative Method\n\nThe multiplicative approach is used when variance in the data increases/decreases over time.\n\n\n
HW Mutliplicative\n$F_{t+h} = (l_t + hb_t)s_{t+h-m(k+1)}\\tag{3.5}$\n\n\\begin{equation}\n l_t = \\alpha \\frac{y_t}{s_{t-m}} + (1 - \\alpha) (l_{t-1} + b_{t-1}) \\tag{3.6}\n\\end{equation} \n\n\\begin{equation}\n b_t = \\beta (l_t - l_{t-1}) + (1 - \\beta)b_{t-1} \\tag{3.7}\n\\end{equation}\n\n\\begin{equation}\n s_t = \\gamma \\frac{y_t}{l_t - s_{t-m}} + (1 - \\gamma) s_{t-m} \\tag{3.8}\n\\end{equation}\n
\n
\n\n\n**Multiplicative Seasonality Example: Alcohol Sales $m**\n\n\n```python\n#Example sales of beer wine IN $m\ntrain = pd.read_csv('data/Alcohol_Sales.csv', index_col='DATE', parse_dates=True)\ntrain.index.freq = 'MS'\ntrain.plot(figsize=(12,4));\n```\n\n\n```python\nfrom statsmodels.tsa.holtwinters import ExponentialSmoothing\n```\n\n\n```python\n#forecast 120 months ahead.\nHORIZON = 120\n\n#trend='add' means model with a linear trend. seasonal='mul' means to use multiplicative seasoniality.\nmodel = ExponentialSmoothing(endog=train, trend='add', seasonal='mul', \n seasonal_periods=12)\nresults = model.fit()\npreds = results.forecast(steps=HORIZON)\n```\n\n\n```python\nidx = pd.date_range(start='2020-01-01', periods=HORIZON, freq='MS')\nax = train.plot(figsize=(12,4))\nresults.fittedvalues.plot(ax=ax, color='green', linestyle='--')\npd.Series(preds, index=idx).plot(ax=ax);\nax.legend(['train', 'point forecast', 'fitted']);\n```\n\n* **Question: what happens if we assume additive seasonality or multiplicative trend?**\n\n\n```python\n#let's have a look at the fitted model\nresults.summary()\n```\n", "meta": {"hexsha": "e92bbb20a5358db2cd7c71a4487ba1c74e7670d8", "size": 21664, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "8_Lecture_ExpSmoothing.ipynb", "max_stars_repo_name": "TomMonks/psma-forecasting", "max_stars_repo_head_hexsha": "ea8be4d194cad069d1cd19d6bc11b1f6e0179ac3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-28T17:00:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-28T17:00:45.000Z", "max_issues_repo_path": "8_Lecture_ExpSmoothing.ipynb", "max_issues_repo_name": "TomMonks/psma-forecasting", "max_issues_repo_head_hexsha": "ea8be4d194cad069d1cd19d6bc11b1f6e0179ac3", "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": "8_Lecture_ExpSmoothing.ipynb", "max_forks_repo_name": "TomMonks/psma-forecasting", "max_forks_repo_head_hexsha": "ea8be4d194cad069d1cd19d6bc11b1f6e0179ac3", "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": 31.812041116, "max_line_length": 766, "alphanum_fraction": 0.5744553176, "converted": true, "num_tokens": 3913, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632282005997, "lm_q2_score": 0.912436161072216, "lm_q1q2_score": 0.8685144298051619}} {"text": "# Exercise 1 - The Mandelbrot Set\n\nThe mandelbrot set is a beautiful fractal ([Wikipedia](http://en.wikipedia.org/wiki/Mandelbrot_set)). \nMore precisely, it contains all numbers from the complex plane where the complex quadratic polynomial \n\n\\begin{align}\n z_{n+1} = z_{n}^2 + c\n\\end{align}\n\nremains bounded. A complex number $c$ is part of the Mandelbrot set when starting with $z_0=0$ and applying the iteration repeatedly, the absolute value of $z_n$ remains smaller or equal than 2 regardless how large $n$ becomes.\n\nMoreover, one can draw very beautiful images by looking at the *escape time* of a numerical computation:\nWe will numerically determine whether a complex number $c$ belongs to the set, and if not we will keep track how many iterations are needed until $|z_n| > 2$. Plotting the escape times of a sampled grid of complex numbers as a 2D image will yield the famous *Apfelmaennchen* you might have seen before.\n\n#Task:#\n\n* Write a function ``mandelbrot(relim, imlim, resteps, imsteps, maxiterations)`` that computes and returns the escape times for the mandelbrot set.\n * ``relim`` and ``imlim`` are tuples that define the boundary of the complex plane (e.g. ``relim=(-2,1)`` and ``imlim=(-1,1)``), for convenience ``imlim`` should contain real numbers although it represents the complex axis.\n * ``resteps`` and ``imsteps`` are integers and define the sampling resolution along each axis (e.g. 300 and 200 steps).\n * ``maxiterations`` is an integer defining the maximum number of iterations (e.g. 50).\n \n * The function should sample complex numbers from the plane as defined by the parameters ``relim, imlim, resteps, imsteps`` and repeatedly apply the quadratic polynomial from above until the absolute value of a complex number is larger than 2. In case a maximum number of iterations is reached (``maxiterations``) the number is believed to be part of the set. \n * The function should return a 2D array containing the number of iterations needed for every sampled complex number and two 1D arrays containing the sampled values along each axis. Escape times in the 2D array of exactly ``maxiterations`` indicate complex numbers that are believed to be part of the set.\n* Make a 2D color plot of the escape times, you might want to look at matplotlib's [imshow](http://www.mathworks.de/de/help/images/ref/imshow.html) function.\n \n###Hints how the function ``mandelbrot`` may work:###\n* Create a 2D numpy array containing the escape times, in the beginning filled with zeros. \n\n* Secondly, create two 1D arrays sampling each dimension of the complex plane. You might want to take a look at the [np.linspace](http://docs.scipy.org/doc/numpy/reference/generated/numpy.linspace.html) function. You can multiply one of the arrays with ``1j`` to create the imaginary axis. Later on you can calculate each starting complex number simply from summing individual elements of both arrays.\n\n* The easy brute-force solution involves three nested for loops. Be aware that you can use python's ``break`` statement to leave a for loop and spare unnecessary computations.\n\n* Iterate at most ``maxiterations`` times for any value in your complex plane and apply the quadratic polynomial from above. If the absolute value gets larger than 2 you can stop iterating and store the number of iterations you have needed in the 2D escape array. Thus, for complex numbers that are actually part of the Mandelbrot set, the 2D array of escape times should contain the value ``maxiterations``.\n\n\n###Hints for optimization:###\n* You can aim for an optimized version that uses vectorized computation. Here you should only need a single for loop.\n\n* Create a second and third 2D array containing the starting complex numbers and the intermediate values, checkout the [meshgrid](http://docs.scipy.org/doc/numpy/reference/generated/numpy.meshgrid.html) function to create these.\n\n* Use the second 2D array to iteratively update all values in the third array at once (vectorized computation!). Mask all values that already escaped the boundary via boolean indexing to speed up the computation.\n\n* Remember that boolean indexing creates copies, not views! So you need to find a smart way to only apply the polynomial\nto values that haven't escaped without always keeping the full 2D array, otherwise internally numpy has to reiterate the full array every timestep. If you also create mesh grids of matrix indices you can reduce the 2D arrays each iteration to 1D arrays containing only the currently not escaped values. This is tricky!\n\n* Now you can use finer resolutions than above!\n\n# Brute-Force Solution\n\n\n```\nimport numpy as np\n\ndef mandelbrot(relim=(-2,1), imlim=(-1, 1), resteps=300, imsteps=200, maxiterations=50):\n \"\"\"Computes the *escape times* of the numeric approximation of the Mandelbrot set.\n \n Values of ``maxiterations`` refer to complex numbers that are believed to be part of the set.\n \n :param relim: The limits of the real axis\n :param imlim: The limits of the imaginary axis\n :param resteps: Sampling resolution along real axis\n :param imsteps: Sampling resolution along the imaginary axis\n :param maxiterations: Maximum number of iterations\n \n :return:\n \n 2D Array of escape times\n 1D Array of real samples\n 1D Array of imaginary samples\n \n \"\"\"\n realaxis = np.linspace(relim[0], relim[1], resteps) # Sample the real axis\n imaxis = np.linspace(imlim[0], imlim[1], imsteps) * 1j # Sample the imaginary axis\n escape = np.zeros((imsteps, resteps), dtype=int) # 2D array of escape times\n \n for irun in range(resteps): # Iterate over real axis\n for jrun in range(imsteps): # Iterate over imaginary axis\n c = realaxis[irun] + imaxis[jrun] # Starting value\n z = 0.0 # Helper variable\n for krun in range(maxiterations): # Compute the escape time\n z = z**2 + c\n if np.abs(z) >= 2:\n break # c is not part of the Mandelbrot set\n else:\n krun = maxiterations # If the for loop did not break c is part of the set\n escape[jrun, irun] = krun\n \n return escape, realaxis, imaxis\n \n```\n\n\n```\nxlim = (-2,1)\nylim = (-1,1)\nxsteps = 300\nysteps = 200\nmaxiterations = 50\n```\n\n\n```\nescape, realaxis, imaxis = mandelbrot(xlim, ylim, xsteps, ysteps, maxiterations)\n```\n\n\n```\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\nplt.imshow(escape, aspect='auto', origin='lower')\nplt.xticks(np.arange(xsteps)[::50], ['%.2f' % x for x in realaxis[::50]])\nplt.yticks(np.arange(ysteps)[::50], ['%.2f' % x.imag for x in imaxis[::50]])\nplt.xlabel('real axis')\nplt.ylabel('imaginary axis')\n```\n\n# Optimized Version\n\n\n```\ndef mandelbrot_pro(relim=(-2,1), imlim=(-1, 1), resteps=1500, imsteps=1000, maxiterations=50):\n \"\"\"As function mandelbrot, but faster if the number of maxiterations is rather low.\n \n It uses a vectorized approach.\n \n \"\"\"\n realaxis = np.linspace(relim[0], relim[1], resteps)\n imaxis = np.linspace(imlim[0], imlim[1], imsteps) * 1j\n escape = np.ones((imsteps, resteps), dtype=int) * maxiterations\n \n realarray, imarray = np.meshgrid(realaxis, imaxis)\n complexarray = realarray + imarray\n \n indices_real = np.arange(len(realaxis)) # index array\n indices_im = np.arange(len(imaxis)) # index array\n mesh_indices_real, mesh_indices_im = np.meshgrid(indices_real, indices_im) # Create a mesh version\n \n zarray = complexarray.copy()\n \n for irun in range(maxiterations):\n \n if len(zarray) == 0:\n break\n \n zarray *= zarray # Application of the polinomial\n zarray += complexarray\n \n mask = np.abs(zarray) >= 2 # Mask all values that already escaped\n \n escape[mesh_indices_im[mask], mesh_indices_real[mask]]=irun # Remembert the escape time\n \n inv_mask = np.invert(mask) # Invert the mask to keep only values that have not escaped, yet\n mesh_indices_real = mesh_indices_real[inv_mask] # Filter the indeices\n mesh_indices_im = mesh_indices_im[inv_mask]\n zarray = zarray[inv_mask] # Filter the z values\n complexarray = complexarray[inv_mask] # Filter the starting values\n \n return escape, realaxis, imaxis\n```\n\n\n```\nxlim = (-2,1)\nylim = (-1,1)\nxsteps = 1500\nysteps = 1000\nmaxiterations = 50\n```\n\n\n```\nescape, realaxis, imaxis = mandelbrot_pro(xlim, ylim, xsteps, ysteps, maxiterations)\n```\n\n\n```\nplt.imshow(escape, aspect='auto', origin='lower')\nplt.xticks(np.arange(xsteps)[::100], ['%.2f' % x for x in realaxis[::100]])\nplt.yticks(np.arange(ysteps)[::100], ['%.2f' % x.imag for x in imaxis[::100]])\nplt.xlabel('real axis')\nplt.ylabel('imaginary axis')\n```\n\n\n```\n\"\"\"Short timing test\"\"\"\n%timeit mandelbrot((-2,1), (-1,1), 45, 30, 10)\n%timeit mandelbrot_pro((-2,1), (-1,1), 45, 30, 10)\n```\n\n 10 loops, best of 3: 41.9 ms per loop\n 1000 loops, best of 3: 673 µs per loop\n\n\n# Exercise 2 - Numerical Integration of a Neuron Model\n\nWe are going to simulate our first neuron model with Euler integration ([Wikipedia](http://en.wikipedia.org/wiki/Euler_method)).\nBasically, our neuron model consists of a single differential equation that describes the development of the membrane voltage over time. For now let's assume this equation is an arbitrary function $f$:\n\\begin{align}\n \\frac{dV}{dt} = f(V)\n\\end{align}\nTo obtain the voltage as a function of time, i.e. $V(t)$, we have to solve the differential equation. Lucky for you, we are in the computer practical and not the analytical tutorial. We are going to solve it numerically, so there's no need for a complicated Ansatz :-)\n\nAs said before, we will use simple Euler integration. Accordingly, if we assume discretized time we can easily compute $V(t+1)$, the membrane voltage of the next time step, in case we now the previous voltage $V(t)$:\n\\begin{align}\nV(t+1) = V(t) + f(V) * dt\n\\end{align}\nwith $dt$ the size of the discretized timesteps.\n\nIf we start with a chosen initial value of $V(0)$ we can iteratively solve the differential equation.\n\nBy this method we can simulate very complex neuron models. Let's simulate a rescaled version of the exponential integrate and fire neuron ([Scholarpedia](http://www.scholarpedia.org/article/Adaptive_exponential_integrate-and-fire_model)):\n\\begin{align}\n \\frac{dV}{dt} = -V + \\exp(V) + I\n\\end{align}\n\n$I$ describes a fixed input current. We will simulate several neurons fed with different current values.\nFor some values of $I$ the membrane potential $V$ will rise to infinity, this corresponds to the upstroke of an action potential (you remember action potentials from a neurobio course, right?). However, our neuron model cannot recover from this upstroke by itself. For a smooth recovery we would need a second differential equation. However, we will keep our model simple and add a so called *reset rule*: whenever $V$ crosses a particular threshold $V(t)\\geq V_t$ then we set it back to a reset value at the next timestep $V(t+1)=V_r$.\n\n#Task#\n\n* Write a function ``expIF_neuron(V, I, Vt, Vr, duration, dt)`` that simulates one or more exponetial integrate-and-fire neurons.\n * The parameter ``V`` can be a scalar or numpy array describing the initial conditions\n * The parameter ``I`` can be a scalar or numpy array describing the input currents\n * The parameter ``Vt`` is a scalar value defining the spiking threshold\n * The parameter ``Vr`` is a scalar defining the reset value after threshold crossing\n * The parameter ``duration`` gives the length of the simulation\n * The parameter ``dt`` describes the stepsize of the Euler integration\n * The function should return \n * A 2D array of voltage traces, i.e. the simulated development of the membrane potential\n * First dimension is the number of neurons, second dimension the voltage trace over time\n * First entries in second dimension should contain the initial values\n * A 1D array containing the discretized timesteps\n * In case ``V`` and ``I`` are arrays, the function should be vectorized, i.e. there should only be a single loop over all timesteps, but no loop over all neurons!\n \n* Simulate 5 neurons at once (do NOT call the function 5 times!) with 5 different input currents $I\\in\\{-3.0, -2.0, -1.0, 0.0, 1.0\\}$.\n * Choose the other parameters as\n * $V_r=-1.0$\n * $V_t=5.0$\n * $duration=10.0$\n * $dt = 0.01$\n * Set the initial $V$ values to $V_r$\n* Plot all 5 voltage traces in a single plot, add a legend and label the axis.\n\n###Hints###\n* You can use the template provided below. This exercise can be solved in just a handful of lines ;-)\n* To incorporate the reset rule you may try boolean indexing.\n\n\n\n```\n## The template: ##\n\ndef expIF_neuron(V=-1.0, I=0.0, Vt=5.0, Vr=-1.0, duration=10.0, dt=0.01):\n \"\"\"Numerically integrates the expIF neuron membrane equation with the Euler-Method.\n \n The neurons obey a reset rule, when the membrane potential crosses `Vt`\n it is set back to `Vr`.\n \n :param V: array of initial membrane values (or a scalar)\n :param VT: spiking threshold (scalar)\n :param I: array of input currents (or scalar)\n :param duration: duration of experiment (scalar)\n :param dt: stepsize of Euler integration (scalar)\n \n :return:\n \n 2D array of voltage time series, first dimension the neurons, \n second dimension the voltage trace. \n First entries contain the initial values.\n \n 1D array of simulation times\n \n \"\"\"\n \n steps = int(duration/dt) # Calculate the number of simulation steps\n \n if isinstance(V, np.ndarray): # V can be scalar or an array, we need to check first\n nneurons = len(V) # Infer the number of neurons from the length of the initial conditions\n else:\n nneurons = 1\n \n V_series = np.zeros((nneurons, steps+1)) # Array that will contain the voltage traces\n # 1st dim neurons, 2nd dim voltage traces\n # i.e. V[2,10] would return the voltage of neuron #2 at the 10th timestep!\n # Wee need steps+1 since the 0th entry should contain the initial conditions\n \n V_series[:, 0] = V # Set initial conditions\n \n times = np.zeros(steps+1) # Array of timesteps\n \n for step in range(1, steps+1): # Loop starting from step 1 (0th contains initial conditions)\n \n ############# Your code ##############\n \n # Manipulate V_series here to simulate the neuron model\n # Iteratively compute f(V(t)) = -V(t) + exp(V(t)) + I and V(t+1) = V(t) + f(V(t)) * dt \n # Do not introduce another for loop, try to think vectorized\n # Try using boolean indexing to implement the threshold crossing and voltage reset\n \n ######### End of your code ###########\n \n times[step] = times[step-1] + dt # You actually don't need the times explicitly, but returning them\n # will make plotting easier\n \n return V_series, times\n \n```\n\n\n```\ndef expIF_neuron(V=-1.0, I=0.0, Vt=5.0, Vr=-1.0, duration=10.0, dt=0.01):\n \"\"\"Numerically integrates the expIF neuron membrane equation with the Euler-Method.\n \n The neurons obey a reset rule, when the membrane potential crosses `Vt`\n it is set back to `Vr`.\n \n :param V: array of initial membrane values (or a scalar)\n :param VT: spiking threshold (scalar)\n :param I: array of input currents (or scalar)\n :param duration: duration of experiment (scalar)\n :param dt: stepsize of Euler integration (scalar)\n \n :return:\n \n 2D array of voltage time series, first dimension the neurons, \n second dimension the voltage trace. \n First entry contains the initial values.\n \n 1D array of simulation times\n \n \"\"\"\n \n steps = int(duration/dt) # Calculate the number of simulation steps\n \n if isinstance(V, np.ndarray): # V can be scalar or array, we need to check first\n nneurons = len(V)\n else:\n nneurons = 1\n \n V_series = np.zeros((nneurons, steps+1)) # Array that will contain the voltage traces\n # 1st dim neurons, 2nd dim voltage traces\n # i.e. V[2,10] would return the voltage of neuron 3 at the 11th timestep!\n # Wee need steps+1 since the 0th entry should contain the initial conditions\n V_series[:, 0] = V # Set initial conditions\n \n times = np.zeros(steps+1) # Array of timesteps\n \n for step in range(1, steps+1): # Loop starting from step 1 (0th contains initial conditions)\n \n prev_V = V_series[:, step-1]\n dV = -prev_V + np.exp(prev_V) + I\n \n next_V = prev_V + dt * dV # Euler step\n next_V[prev_V>=Vt] = Vr # Voltage reset\n prev_V[prev_V>=Vt] = Vt # For better plotting we bound also the previous step\n \n V_series[:, step] = next_V\n \n times[step] = times[step-1] + dt # You actually don't need the times explicitly, but returning them\n # will make plotting easier\n \n return V_series, times\n \n \n \n```\n\n\n```\nnneurons = 5\nVt = 5.0\nVr = -1.0\ndt = 0.01\nduration = 10.0\nI = np.linspace(-3.,1.0, nneurons)\nV = np.ones(nneurons)*-1.0\n```\n\n\n```\nV_series, times = expIF_neuron(V, I, Vt, Vr, duration, dt)\n```\n\n\n```\nfor neuron in range(nneurons):\n plt.plot(times, V_series[neuron,:], linewidth=2, label='I=%.1f' % (I[neuron]))\n\nax = plt.gca()\nax.ticklabel_format(useOffset=False) # prevents strange units\nplt.xlabel('time')\nplt.ylabel('V')\nplt.legend()\n```\n\n\n```\n\n```\n", "meta": {"hexsha": "3e247b75359cad32ac60e937b35c81a65633ce54", "size": 168068, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "python-beginner/PCC_Exercise_2_with_solutions.ipynb", "max_stars_repo_name": "BCCN-Prog/materials", "max_stars_repo_head_hexsha": "4317ab52521093cc84c33b41ab027b46d1e5e48a", "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-beginner/PCC_Exercise_2_with_solutions.ipynb", "max_issues_repo_name": "BCCN-Prog/materials", "max_issues_repo_head_hexsha": "4317ab52521093cc84c33b41ab027b46d1e5e48a", "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-beginner/PCC_Exercise_2_with_solutions.ipynb", "max_forks_repo_name": "BCCN-Prog/materials", "max_forks_repo_head_hexsha": "4317ab52521093cc84c33b41ab027b46d1e5e48a", "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": 280.1133333333, "max_line_length": 57249, "alphanum_fraction": 0.8951495823, "converted": true, "num_tokens": 4513, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.940789754239075, "lm_q2_score": 0.9230391568941467, "lm_q1q2_score": 0.8683857815674872}} {"text": "# Pearson Correlation Vs. Z-normalized Euclidean Distance\n\nIt is [well understood](https://arxiv.org/pdf/1601.02213.pdf) that the z-normalized Euclidean distance, $ED_{z-norm}$, and the Pearson correlation, $PC$, between any two subsequences with length $m$ share the following relationship:\n\n$ED_{z-norm} = \\sqrt {2 * m * (1 - PC)}$\n\nNaturally, when the two subsequences are perfectly correlated (i.e., $PC = 1$), then we get:\n\n\\begin{align}\n ED_{z-norm} ={}&\n \\sqrt {2 * m * (1 - PC)}\n \\\\\n ={}&\n \\sqrt {2 * m * (1 - 1)}\n \\\\\n ={}&\n \\sqrt {2 * m * 0}\n \\\\\n ={}&\n \\sqrt {0}\n \\\\\n ={}&\n 0\n \\\\\n\\end{align}\n\nSimilarly, when the two subsequences are completely uncorrelated (i.e., $PC = 0$), then we get:\n\n\\begin{align}\n ED_{z-norm} ={}&\n \\sqrt {2 * m * (1 - PC)}\n \\\\\n ={}&\n \\sqrt {2 * m * (1 - 0)}\n \\\\\n ={}&\n \\sqrt {2 * m * 1}\n \\\\\n ={}&\n \\sqrt {2 * m}\n \\\\\n\\end{align}\n\nIn other words, the largest possible z-normalized distance between any pair of subsequences with length $m$ is $\\sqrt{2 * m}$. The maximum distance can never be bigger!\n\nFinally, when two subsequences are anti-correlated (i.e., $PC = -1$), then we get:\n\n\\begin{align}\n ED_{z-norm} ={}&\n \\sqrt {2 * m * (1 - PC)}\n \\\\\n ={}&\n \\sqrt {2 * m * (1 - (-1))}\n \\\\\n ={}&\n \\sqrt {2 * m * 2}\n \\\\\n ={}&\n \\sqrt {4 * m}\n \\\\\n ={}&\n 2 * \\sqrt {m}\n \\\\\n\\end{align}\n\n\n```python\n\n```\n", "meta": {"hexsha": "0b5cbab1825e9e60847d65fba2eebff969dc282e", "size": 2853, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "docs/Pearson.ipynb", "max_stars_repo_name": "profintegra/stumpy", "max_stars_repo_head_hexsha": "66b3402d91820005b466e1da6fe353b61e6246c5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2296, "max_stars_repo_stars_event_min_datetime": "2019-05-03T19:26:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T20:42:08.000Z", "max_issues_repo_path": "docs/Pearson.ipynb", "max_issues_repo_name": "profintegra/stumpy", "max_issues_repo_head_hexsha": "66b3402d91820005b466e1da6fe353b61e6246c5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 436, "max_issues_repo_issues_event_min_datetime": "2019-05-06T14:14:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T20:39:31.000Z", "max_forks_repo_path": "docs/Pearson.ipynb", "max_forks_repo_name": "profintegra/stumpy", "max_forks_repo_head_hexsha": "66b3402d91820005b466e1da6fe353b61e6246c5", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 318, "max_forks_repo_forks_event_min_datetime": "2019-05-04T01:36:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T20:31:11.000Z", "avg_line_length": 27.1714285714, "max_line_length": 241, "alphanum_fraction": 0.4227129338, "converted": true, "num_tokens": 497, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109756113862, "lm_q2_score": 0.913676521650809, "lm_q1q2_score": 0.8683681943353633}} {"text": "# Linear Equations\nThe equations in the previous lab included one variable, for which you solved the equation to find its value. Now let's look at equations with multiple variables. For reasons that will become apparent, equations with two variables are known as linear equations.\n\n## Solving a Linear Equation\nConsider the following equation:\n\n\\begin{equation}2y + 3 = 3x - 1 \\end{equation}\n\nThis equation includes two different variables, **x** and **y**. These variables depend on one another; the value of x is determined in part by the value of y and vice-versa; so we can't solve the equation and find absolute values for both x and y. However, we *can* solve the equation for one of the variables and obtain a result that describes a relative relationship between the variables.\n\nFor example, let's solve this equation for y. First, we'll get rid of the constant on the right by adding 1 to both sides:\n\n\\begin{equation}2y + 4 = 3x \\end{equation}\n\nThen we'll use the same technique to move the constant on the left to the right to isolate the y term by subtracting 4 from both sides:\n\n\\begin{equation}2y = 3x - 4 \\end{equation}\n\nNow we can deal with the coefficient for y by dividing both sides by 2:\n\n\\begin{equation}y = \\frac{3x - 4}{2} \\end{equation}\n\nOur equation is now solved. We've isolated **y** and defined it as 3x-4/2\n\nWhile we can't express **y** as a particular value, we can calculate it for any value of **x**. For example, if **x** has a value of 6, then **y** can be calculated as:\n\n\\begin{equation}y = \\frac{3\\cdot6 - 4}{2} \\end{equation}\n\nThis gives the result 14/2 which can be simplified to 7.\n\nYou can view the values of **y** for a range of **x** values by applying the equation to them using the following Python code:\n\n\n```python\nimport pandas as pd\n\n# Create a dataframe with an x column containing values from -10 to 10\ndf = pd.DataFrame ({'x': range(-10, 11)})\n\n# Add a y column by applying the solved equation to x\ndf['y'] = (3*df['x'] - 4) / 2\n\n#Display the dataframe\ndf\n```\n\nWe can also plot these values to visualize the relationship between x and y as a line. For this reason, equations that describe a relative relationship between two variables are known as *linear equations*:\n\n\n```python\n%matplotlib inline\nfrom matplotlib import pyplot as plt\n\nplt.plot(df.x, df.y, color=\"grey\", marker = \"o\")\nplt.xlabel('x')\nplt.ylabel('y')\nplt.grid()\nplt.show()\n```\n\nIn a linear equation, a valid solution is described by an ordered pair of x and y values. For example, valid solutions to the linear equation above include:\n- (-10, -17)\n- (0, -2)\n- (9, 11.5)\n\nThe cool thing about linear equations is that we can plot the points for some specific ordered pair solutions to create the line, and then interpolate the x value for any y value (or vice-versa) along the line.\n\n## Intercepts\nWhen we use a linear equation to plot a line, we can easily see where the line intersects the X and Y axes of the plot. These points are known as *intercepts*. The *x-intercept* is where the line intersects the X (horizontal) axis, and the *y-intercept* is where the line intersects the Y (horizontal) axis.\n\nLet's take a look at the line from our linear equation with the X and Y axis shown through the origin (0,0).\n\n\n```python\nplt.plot(df.x, df.y, color=\"grey\")\nplt.xlabel('x')\nplt.ylabel('y')\nplt.grid()\n\n## add axis lines for 0,0\nplt.axhline()\nplt.axvline()\nplt.show()\n```\n\nThe x-intercept is the point where the line crosses the X axis, and at this point, the **y** value is always 0. Similarly, the y-intercept is where the line crosses the Y axis, at which point the **x** value is 0. So to find the intercepts, we need to solve the equation for **x** when **y** is 0.\n\nFor the x-intercept, our equation looks like this:\n\n\\begin{equation}0 = \\frac{3x - 4}{2} \\end{equation}\n\nWhich can be reversed to make it look more familar with the x expression on the left:\n\n\\begin{equation}\\frac{3x - 4}{2} = 0 \\end{equation}\n\nWe can multiply both sides by 2 to get rid of the fraction:\n\n\\begin{equation}3x - 4 = 0 \\end{equation}\n\nThen we can add 4 to both sides to get rid of the constant on the left:\n\n\\begin{equation}3x = 4 \\end{equation}\n\nAnd finally we can divide both sides by 3 to get the value for x:\n\n\\begin{equation}x = \\frac{4}{3} \\end{equation}\n\nWhich simplifies to:\n\n\\begin{equation}x = 1\\frac{1}{3} \\end{equation}\n\nSo the x-intercept is 11/3 (approximately 1.333).\n\nTo get the y-intercept, we solve the equation for y when x is 0:\n\n\\begin{equation}y = \\frac{3\\cdot0 - 4}{2} \\end{equation}\n\nSince 3 x 0 is 0, this can be simplified to:\n\n\\begin{equation}y = \\frac{-4}{2} \\end{equation}\n\n-4 divided by 2 is -2, so:\n\n\\begin{equation}y = -2 \\end{equation}\n\nThis gives us our y-intercept, so we can plot both intercepts on the graph:\n\n\n```python\nplt.plot(df.x, df.y, color=\"grey\")\nplt.xlabel('x')\nplt.ylabel('y')\nplt.grid()\n\n## add axis lines for 0,0\nplt.axhline()\nplt.axvline()\nplt.annotate('x-intercept',(1.333, 0))\nplt.annotate('y-intercept',(0,-2))\nplt.show()\n```\n\nThe ability to calculate the intercepts for a linear equation is useful, because you can calculate only these two points and then draw a straight line through them to create the entire line for the equation.\n\n## Slope\nIt's clear from the graph that the line from our linear equation describes a slope in which values increase as we travel up and to the right along the line. It can be useful to quantify the slope in terms of how much **x** increases (or decreases) for a given change in **y**. In the notation for this, we use the greek letter Δ (*delta*) to represent change:\n\n\\begin{equation}slope = \\frac{\\Delta{y}}{\\Delta{x}} \\end{equation}\n\nSometimes slope is represented by the variable ***m***, and the equation is written as:\n\n\\begin{equation}m = \\frac{y_{2} - y_{1}}{x_{2} - x_{1}} \\end{equation}\n\nAlthough this form of the equation is a little more verbose, it gives us a clue as to how we calculate slope. What we need is any two ordered pairs of x,y values for the line - for example, we know that our line passes through the following two points:\n- (0,-2)\n- (6,7)\n\nWe can take the x and y values from the first pair, and label them x1 and y1; and then take the x and y values from the second point and label them x2 and y2. Then we can plug those into our slope equation:\n\n\\begin{equation}m = \\frac{7 - -2}{6 - 0} \\end{equation}\n\nThis is the same as:\n\n\\begin{equation}m = \\frac{7 + 2}{6 - 0} \\end{equation}\n\nThat gives us the result 9/6 which is 11/2 or 1.5 .\n\nSo what does that actually mean? Well, it tells us that for every change of **1** in x, **y** changes by 11/2 or 1.5. So if we start from any point on the line and move one unit to the right (along the X axis), we'll need to move 1.5 units up (along the Y axis) to get back to the line.\n\nYou can plot the slope onto the original line with the following Python code to verify it fits:\n\n\n```python\nplt.plot(df.x, df.y, color=\"grey\")\nplt.xlabel('x')\nplt.ylabel('y')\nplt.grid()\nplt.axhline()\nplt.axvline()\n\n# set the slope\nm = 1.5\n\n# get the y-intercept\nyInt = -2\n\n# plot the slope from the y-intercept for 1x\nmx = [0, 1]\nmy = [yInt, yInt + m]\nplt.plot(mx,my, color='red', lw=5)\n\nplt.show()\n```\n\n### Slope-Intercept Form\nOne of the great things about algebraic expressions is that you can write the same equation in multiple ways, or *forms*. The *slope-intercept form* is a specific way of writing a 2-variable linear equation so that the equation definition includes the slope and y-intercept. The generalised slope-intercept form looks like this:\n\n\\begin{equation}y = mx + b \\end{equation}\n\nIn this notation, ***m*** is the slope and ***b*** is the y-intercept.\n\nFor example, let's look at the solved linear equation we've been working with so far in this section:\n\n\\begin{equation}y = \\frac{3x - 4}{2} \\end{equation}\n\nNow that we know the slope and y-intercept for the line that this equation defines, we can rewrite the equation as:\n\n\\begin{equation}y = 1\\frac{1}{2}x + -2 \\end{equation}\n\nYou can see intuitively that this is true. In our original form of the equation, to find y we multiply x by three, subtract 4, and divide by two - in other words, x is half of 3x - 4; which is 1.5x - 2. So these equations are equivalent, but the slope-intercept form has the advantages of being simpler, and including two key pieces of information we need to plot the line represented by the equation. We know the y-intecept that the line passes through (0, -2), and we know the slope of the line (for every x, we add 1.5 to y.\n\nLet's recreate our set of test x and y values using the slope-intercept form of the equation, and plot them to prove that this describes the same line:\n\n\n```python\n%matplotlib inline\n\nimport pandas as pd\nfrom matplotlib import pyplot as plt\n\n# Create a dataframe with an x column containing values from -10 to 10\ndf = pd.DataFrame ({'x': range(-10, 11)})\n\n# Define slope and y-intercept\nm = 1.5\nyInt = -2\n\n# Add a y column by applying the slope-intercept equation to x\ndf['y'] = m*df['x'] + yInt\n\n# Plot the line\nfrom matplotlib import pyplot as plt\n\nplt.plot(df.x, df.y, color=\"grey\")\nplt.xlabel('x')\nplt.ylabel('y')\nplt.grid()\nplt.axhline()\nplt.axvline()\n\n# label the y-intercept\nplt.annotate('y-intercept',(0,yInt))\n\n# plot the slope from the y-intercept for 1x\nmx = [0, 1]\nmy = [yInt, yInt + m]\nplt.plot(mx,my, color='red', lw=5)\n\nplt.show()\n```\n", "meta": {"hexsha": "718cf3d635a11434dd5c600d7b64f255e8080fff", "size": 13174, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Basics Of Algebra by Hiren/01-02-Linear Equations.ipynb", "max_stars_repo_name": "awesome-archive/Basic-Mathematics-for-Machine-Learning", "max_stars_repo_head_hexsha": "b6699a9c29ec070a0b1615c46952cb0deeb73b54", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 401, "max_stars_repo_stars_event_min_datetime": "2018-08-29T04:55:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T11:03:39.000Z", "max_issues_repo_path": "Basics Of Algebra by Hiren/01-02-Linear Equations.ipynb", "max_issues_repo_name": "aligeekk/Basic-Mathematics-for-Machine-Learning", "max_issues_repo_head_hexsha": "8662076d60e89f58a6e81e4ca1377569472760a2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-09-28T13:52:53.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-28T18:13:53.000Z", "max_forks_repo_path": "Basics Of Algebra by Hiren/01-02-Linear Equations.ipynb", "max_forks_repo_name": "aligeekk/Basic-Mathematics-for-Machine-Learning", "max_forks_repo_head_hexsha": "8662076d60e89f58a6e81e4ca1377569472760a2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 135, "max_forks_repo_forks_event_min_datetime": "2018-08-29T05:04:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T07:04:25.000Z", "avg_line_length": 38.633431085, "max_line_length": 536, "alphanum_fraction": 0.592227114, "converted": true, "num_tokens": 2728, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768620069626, "lm_q2_score": 0.919642532278991, "lm_q1q2_score": 0.8683052002953144}} {"text": "### Quadratic Interpolation\n\nGiven a smooth, well-behaved function $f(t)$ that is known to have no more than one root within the range $t_a \\le t \\le t_b$, we want to find an iterative procedure to quickly narrow in on a value $t_0$ in that range such that $f(t_0) \\approx 0$. The function $f$ may be expensive to compute, so we would like to evaluate it as few times as possible. We will use quadratic interpolation, where we approximate $f$ as a parabola.\n\nFirst find the midpoint time $t_m$ between $t_a$ and $t_b$:\n\n\\begin{align}\n\\\\\nt_m = \\frac {t_b + t_a} {2}\n\\end{align}\n\nDefine a parameter $x$ that has the linear range $-1 \\le x \\le +1$ over the search interval:\n\n\\begin{align}\n\\\\\nx = \\frac {t - t_m} {t_b - t_m}\n\\end{align}\n\nA generic parabolic function over this range is\n\n\\begin{align}\n\\\\\np(x) = Q x^2 + R x + S\n\\end{align}\n\nEvaluate $f$ at the left, middle, and right points. These correspond to $x=-1$, $x=0$, and $x=+1$.\n\n\\begin{align}\n\\\\\nf_a &= f(t_a) \\\\\nf_m &= f(t_m) \\\\\nf_b &= f(t_b)\n\\end{align}\n\nNow we can relate these 3 values to a unique parabola that passes exactly through the points $(t_a, f_a)$, $(t_m, f_m)$, and $(t_b, f_b)$ as\n\n\\begin{align}\n\\\\\np(-1) &= f_a = Q - R + S \\\\\np(0) &= f_m = S\\\\\np(+1) &= f_b = Q + R + S \n\\end{align}\n\nSolving this system of equations in terms of the known values $f_a$, $f_m$, and $f_b$, we obtain\n\n\\begin{align}\n\\\\\nQ &= \\frac{f_b + f_a}{2} - f_m \\\\\nR &= \\frac{f_b - f_a}{2} \\\\\nS &= f_m\n\\end{align}\n\nLet's test these formulas:\n\n\n```python\nimport math\n\nclass Parabola:\n def __init__(self, f, ta, tb):\n tm = (tb + ta)/2\n fa = f(ta)\n fb = f(tb)\n fm = f(tm)\n self.Q = (fb + fa)/2 - fm\n self.R = (fb - fa)/2\n self.S = fm\n \n def Eval(self, x):\n return self.Q*x*x + self.R*x + self.S\n \n def Slope(self, x):\n return 2*self.Q*x + self.R\n\ndef Func(t):\n return math.cos(t) - t\n\nta = 0.6\ntb = 0.8\ntm = (ta + tb)/2\np = Parabola(Func, ta, tb)\nprint('Q={:0.6f}, R={:0.6f}, S={:0.6f}'.format(p.Q, p.R, p.S))\nprint('p(-1)={:0.6f}, f(ta)={:0.6f}'.format(p.Eval(-1), Func(ta)))\nprint('p( 0)={:0.6f}, f(tm)={:0.6f}'.format(p.Eval( 0), Func(tm)))\nprint('p(+1)={:0.6f}, f(tb)={:0.6f}'.format(p.Eval(+1), Func(tb)))\n\n```\n\n Q=-0.003821, R=-0.164314, S=0.064842\n p(-1)=0.225336, f(ta)=0.225336\n p( 0)=0.064842, f(tm)=0.064842\n p(+1)=-0.103293, f(tb)=-0.103293\n\n\nNow that we have a parabola that passes through the 3 points, let's solve for the value of $x$ such that $p(x)=0$. The quadratic formula gives us two values of $x$:\n\n\\begin{align}\n\\\\\nx = \\frac {-R \\pm \\sqrt{R^2 - 4QS}} {2Q}\n\\end{align}\n\nFor our purposes, the solution must have a real value and must lie in the range $-1 \\le x \\le +1$. We expect exactly one such solution. If there are zero or two such values of $x$, our search will return a null value.\n\n\n```python\ndef Solve(p):\n if p.Q == 0:\n # This is not a parabola but a straight line\n # p(x) = Rx + S = 0\n # Therefore x = -S/R\n if p.R == 0:\n return None\n x = -p.S / p.R\n if -1 <= x <= +1:\n return x\n return None\n \n # Let u = the quantity inside the square root.\n u = p.R*p.R - 4*p.Q*p.S\n if u <= 0:\n # If u<0, then both solutions are complex-valued.\n # If u=0, the parabola is tangent to the axis, not crossing it.\n return None\n \n ru = math.sqrt(u)\n x1 = (-p.R + ru) / (2 * p.Q)\n x2 = (-p.R - ru) / (2 * p.Q)\n \n if -1 <= x1 <= +1:\n if -1 <= x2 <= +1:\n return None\n return x1\n \n if -1 <= x2 <= +1:\n return x2\n \n return None\n```\n\n\n```python\nx = Solve(p)\nprint(x)\n```\n\n 0.39106619198014525\n\n\nConvert the value $x$ back into a time value $t$.\n\n\n```python\nt = tm + x*(tb-tm)\nprint(t)\n```\n\n 0.7391066191980145\n\n\nSee how close this is to the correct solution.\n\n\n```python\nf = Func(t)\nprint(f)\n```\n\n -3.595936996025895e-05\n\n\nWe want to iterate and do another parabolic interpolation, but the problem is we don't know where to choose a new time range $\\bar{t}_a \\le t \\le \\bar{t}_b$. We want this new range to be as small as possible while definitely bracketing the place where $f(t)$ crosses the $t$-axis. If we knew where that was, we would have already solved the problem and wouldn't need to do this!\n\nWe are actually more interested in finding $t_0$ within a sufficiently small window $\\Delta t$ that definitely brackets the root, than we are in finding a very small value $\\left|{f(t)}\\right|$.\n\nWe can keep track of the bounding values of $t$ that most closely bracket where the root must be, and iterate with quadratic interpolation around each successive approximation of $t_0$. The trick might be to just create another parabola through the $t$ value we just found by picking a new value of $t_a$ and $t_b$ around it, without worrying about whether the parabola crosses the $t$-axis between the new $t_a$ and $t_b$, so long as it stays inside the original range.\n\n\n```python\n\n```\n", "meta": {"hexsha": "b7edc4ef8f295b1fe92acf069438ad37e8160c49", "size": 8070, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "theory/quadratic_interpolation.ipynb", "max_stars_repo_name": "matheo/astronomy", "max_stars_repo_head_hexsha": "3a1d4ea47a0c04d83bd8ede43dc564e956e999fe", "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": "theory/quadratic_interpolation.ipynb", "max_issues_repo_name": "matheo/astronomy", "max_issues_repo_head_hexsha": "3a1d4ea47a0c04d83bd8ede43dc564e956e999fe", "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": "theory/quadratic_interpolation.ipynb", "max_forks_repo_name": "matheo/astronomy", "max_forks_repo_head_hexsha": "3a1d4ea47a0c04d83bd8ede43dc564e956e999fe", "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.5604395604, "max_line_length": 476, "alphanum_fraction": 0.49244114, "converted": true, "num_tokens": 1659, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768557238084, "lm_q2_score": 0.9196425333801889, "lm_q1q2_score": 0.8683051955567842}} {"text": "# Finding Roots of Equations\n\n## Calculus review\n\n\n```python\n%matplotlib inline\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport scipy as scipy\nfrom scipy.interpolate import interp1d\n```\n\nLet's review the theory of optimization for multivariate functions. Recall that in the single-variable case, extreme values (local extrema) occur at points where the first derivative is zero, however, the vanishing of the first derivative is not a sufficient condition for a local max or min. Generally, we apply the second derivative test to determine whether a candidate point is a max or min (sometimes it fails - if the second derivative either does not exist or is zero). In the multivariate case, the first and second derivatives are *matrices*. In the case of a scalar-valued function on $\\mathbb{R}^n$, the first derivative is an $n\\times 1$ vector called the *gradient* (denoted $\\nabla f$). The second derivative is an $n\\times n$ matrix called the *Hessian* (denoted $H$)\n\nJust to remind you, the gradient and Hessian are given by:\n\n$$\\nabla f(x) = \\left(\\begin{matrix}\\frac{\\partial f}{\\partial x_1}\\\\ \\vdots \\\\\\frac{\\partial f}{\\partial x_n}\\end{matrix}\\right)$$\n\n\n$$H = \\left(\\begin{matrix}\n \\dfrac{\\partial^2 f}{\\partial x_1^2} & \\dfrac{\\partial^2 f}{\\partial x_1\\,\\partial x_2} & \\cdots & \\dfrac{\\partial^2 f}{\\partial x_1\\,\\partial x_n} \\\\[2.2ex]\n \\dfrac{\\partial^2 f}{\\partial x_2\\,\\partial x_1} & \\dfrac{\\partial^2 f}{\\partial x_2^2} & \\cdots & \\dfrac{\\partial^2 f}{\\partial x_2\\,\\partial x_n} \\\\[2.2ex]\n \\vdots & \\vdots & \\ddots & \\vdots \\\\[2.2ex]\n \\dfrac{\\partial^2 f}{\\partial x_n\\,\\partial x_1} & \\dfrac{\\partial^2 f}{\\partial x_n\\,\\partial x_2} & \\cdots & \\dfrac{\\partial^2 f}{\\partial x_n^2}\n\\end{matrix}\\right)$$\n\nOne of the first things to note about the Hessian - it's symmetric. This structure leads to some useful properties in terms of interpreting critical points.\n\nThe multivariate analog of the test for a local max or min turns out to be a statement about the gradient and the Hessian matrix. Specifically, a function $f:\\mathbb{R}^n\\rightarrow \\mathbb{R}$ has a critical point at $x$ if $\\nabla f(x) = 0$ (where zero is the zero vector!). Furthermore, the second derivative test at a critical point is as follows:\n\n* If $H(x)$ is positive-definite ($\\iff$ it has all positive eigenvalues), $f$ has a local minimum at $x$\n* If $H(x)$ is negative-definite ($\\iff$ it has all negative eigenvalues), $f$ has a local maximum at $x$\n* If $H(x)$ has both positive and negative eigenvalues, $f$ has a saddle point at $x$.\n\nIf you have $m$ equations with $n$ variables, then the $m \\times n$ matrix of first partial derivatives is known as the Jacobian $J(x)$. For example, for two equations $f(x, y)$ and $g(x, y)$, we have\n\n$$\nJ(x) = \\begin{bmatrix}\n\\frac{\\delta f}{\\delta x} & \\frac{\\delta f}{\\delta y} \\\\\n\\frac{\\delta g}{\\delta x} & \\frac{\\delta g}{\\delta y} \n\\end{bmatrix}\n$$\n\nWe can now express the multivariate form of Taylor polynomials in a familiar format.\n\n$$\nf(x + \\delta x) = f(x) + \\delta x \\cdot J(x) + \\frac{1}{2} \\delta x^T H(x) \\delta x + \\mathcal{O}(\\delta x^3)\n$$\n\n## Main Issues in Root Finding in One Dimension\n\n* Separating close roots\n* Numerical Stability\n* Rate of Convergence\n* Continuity and Differentiability\n\n## Bisection Method\n\nThe bisection method is one of the simplest methods for finding zeros of a non-linear function. It is guaranteed to find a root - but it can be slow. The main idea comes from the intermediate value theorem: If $f(a)$ and $f(b)$ have different signs and $f$ is continuous, then $f$ must have a zero between $a$ and $b$. We evaluate the function at the midpoint, $c = \\frac12(a+b)$. $f(c)$ is either zero, has the same sign as $f(a)$ or the same sign as $f(b)$. Suppose $f(c)$ has the same sign as $f(a)$ (as pictured below). We then repeat the process on the interval $[c,b]$. \n\n\n```python\ndef f(x):\n return x**3 + 4*x**2 -3\n\nx = np.linspace(-3.1, 0, 100)\nplt.plot(x, x**3 + 4*x**2 -3)\n\na = -3.0\nb = -0.5\nc = 0.5*(a+b)\n\nplt.text(a,-1,\"a\")\nplt.text(b,-1,\"b\")\nplt.text(c,-1,\"c\")\n\nplt.scatter([a,b,c], [f(a), f(b),f(c)], s=50, facecolors='none')\nplt.scatter([a,b,c], [0,0,0], s=50, c='red')\n\nxaxis = plt.axhline(0)\npass\n```\n\n\n```python\nx = np.linspace(-3.1, 0, 100)\nplt.plot(x, x**3 + 4*x**2 -3)\n\nd = 0.5*(b+c)\n\nplt.text(d,-1,\"d\")\nplt.text(b,-1,\"b\")\nplt.text(c,-1,\"c\")\n\nplt.scatter([d,b,c], [f(d), f(b),f(c)], s=50, facecolors='none')\nplt.scatter([d,b,c], [0,0,0], s=50, c='red')\n\nxaxis = plt.axhline(0)\npass\n```\n\nWe can terminate the process whenever the function evaluated at the new midpoint is 'close enough' to zero. This method is an example of what are known as 'bracketed methods'. This means the root is 'bracketed' by the end-points (it is somewhere in between). Another class of methods are 'open methods' - the root need not be somewhere in between the end-points (but it usually needs to be close!)\n\n## Secant Method\n\nThe secant method also begins with two initial points, but without the constraint that the function values are of opposite signs. We use the secant line to extrapolate the next candidate point.\n\n\n```python\ndef f(x):\n return (x**3-2*x+7)/(x**4+2)\n\nx = np.arange(-3,5, 0.1);\ny = f(x)\n\np1=plt.plot(x, y)\nplt.xlim(-3, 4)\nplt.ylim(-.5, 4)\nplt.xlabel('x')\nplt.axhline(0)\nt = np.arange(-10, 5., 0.1)\n\nx0=-1.2\nx1=-0.5\nxvals = []\nxvals.append(x0)\nxvals.append(x1)\nnotconverge = 1\ncount = 0\ncols=['r--','b--','g--','y--']\nwhile (notconverge==1 and count < 3):\n slope=(f(xvals[count+1])-f(xvals[count]))/(xvals[count+1]-xvals[count])\n intercept=-slope*xvals[count+1]+f(xvals[count+1])\n plt.plot(t, slope*t + intercept, cols[count])\n nextval = -intercept/slope\n if abs(f(nextval)) < 0.001:\n notconverge=0\n else:\n xvals.append(nextval)\n count = count+1\n\nplt.show()\n```\n\nThe secant method has the advantage of fast convergence. While the bisection method has a linear convergence rate (i.e. error goes to zero at the rate that $h(x) = x$ goes to zero, the secant method has a convergence rate that is faster than linear, but not quite quadratic (i.e. $\\sim x^\\alpha$, where $\\alpha = \\frac{1+\\sqrt{5}}2 \\approx 1.6$) however, the trade-off is that the secant method is not guaranteed to find a root in the brackets.\n\nA variant of the secant method is known as the **method of false positions**. Conceptually it is identical to the secant method, except that instead of always using the last two values of $x$ for linear interpolation, it chooses the two most recent values that maintain the bracket property (i.e $f(a) f(b) < 0$). It is slower than the secant, but like the bisection, is safe.\n\n## Newton-Raphson Method\n\nWe want to find the value $\\theta$ so that some (differentiable) function $g(\\theta)=0$. \nIdea: start with a guess, $\\theta_0$. Let $\\tilde{\\theta}$ denote the value of $\\theta$ for which $g(\\theta) = 0$ and define $h = \\tilde{\\theta} - \\theta_0$. Then:\n\n$$\n\\begin{eqnarray*}\ng(\\tilde{\\theta}) &=& 0 \\\\\\\\\n&=&g(\\theta_0 + h) \\\\\\\\\n&\\approx& g(\\theta_0) + hg'(\\theta_0)\n\\end{eqnarray*}\n$$\n\nThis implies that \n\n$$ h\\approx \\frac{g(\\theta_0)}{g'(\\theta_0)}$$\n\nSo that\n\n$$\\tilde{\\theta}\\approx \\theta_0 - \\frac{g(\\theta_0)}{g'(\\theta_0)}$$\n\nThus, we set our next approximation:\n\n$$\\theta_1 = \\theta_0 - \\frac{g(\\theta_0)}{g'(\\theta_0)}$$\n\nand we have developed an iterative procedure with:\n\n$$\\theta_n = \\theta_{n-1} - \\frac{g(\\theta_{n-1})}{g'(\\theta_{n-1})}$$\n\n#### Example\n\nLet $$g(x) = \\frac{x^3-2x+7}{x^4+2}$$\n\n\n```python\nx = np.arange(-5,5, 0.1);\ny = (x**3-2*x+7)/(x**4+2)\n\np1=plt.plot(x, y)\nplt.xlim(-4, 4)\nplt.ylim(-.5, 4)\nplt.xlabel('x')\nplt.axhline(0)\nplt.title('Example Function')\nplt.show()\n```\n\n\n```python\nx = np.arange(-5,5, 0.1);\ny = (x**3-2*x+7)/(x**4+2)\n\np1=plt.plot(x, y)\nplt.xlim(-4, 4)\nplt.ylim(-.5, 4)\nplt.xlabel('x')\nplt.axhline(0)\nplt.title('Good Guess')\nt = np.arange(-5, 5., 0.1)\n\nx0=-1.5\nxvals = []\nxvals.append(x0)\nnotconverge = 1\ncount = 0\ncols=['r--','b--','g--','y--','c--','m--','k--','w--']\nwhile (notconverge==1 and count < 6):\n funval=(xvals[count]**3-2*xvals[count]+7)/(xvals[count]**4+2)\n slope=-((4*xvals[count]**3 *(7 - 2 *xvals[count] + xvals[count]**3))/(2 + xvals[count]**4)**2) + (-2 + 3 *xvals[count]**2)/(2 + xvals[count]**4)\n \n intercept=-slope*xvals[count]+(xvals[count]**3-2*xvals[count]+7)/(xvals[count]**4+2)\n\n plt.plot(t, slope*t + intercept, cols[count])\n nextval = -intercept/slope\n if abs(funval) < 0.01:\n notconverge=0\n else:\n xvals.append(nextval)\n count = count+1\n\n\n```\n\nFrom the graph, we see the zero is near -2. We make an initial guess of $$x=-1.5$$\n\nWe have made an excellent choice for our first guess, and we can see rapid convergence!\n\n\n```python\nfunval\n```\n\nIn fact, the Newton-Raphson method converges quadratically. However, NR (and the secant method) have a fatal flaw:\n\n\n```python\nx = np.arange(-5,5, 0.1);\ny = (x**3-2*x+7)/(x**4+2)\n\np1=plt.plot(x, y)\nplt.xlim(-4, 4)\nplt.ylim(-.5, 4)\nplt.xlabel('x')\nplt.axhline(0)\nplt.title('Bad Guess')\nt = np.arange(-5, 5., 0.1)\n\nx0=-0.5\nxvals = []\nxvals.append(x0)\nnotconverge = 1\ncount = 0\ncols=['r--','b--','g--','y--','c--','m--','k--','w--']\nwhile (notconverge==1 and count < 6):\n funval=(xvals[count]**3-2*xvals[count]+7)/(xvals[count]**4+2)\n slope=-((4*xvals[count]**3 *(7 - 2 *xvals[count] + xvals[count]**3))/(2 + xvals[count]**4)**2) + (-2 + 3 *xvals[count]**2)/(2 + xvals[count]**4)\n \n intercept=-slope*xvals[count]+(xvals[count]**3-2*xvals[count]+7)/(xvals[count]**4+2)\n\n plt.plot(t, slope*t + intercept, cols[count])\n nextval = -intercept/slope\n if abs(funval) < 0.01:\n notconverge = 0\n else:\n xvals.append(nextval)\n count = count+1\n```\n\nWe have stumbled on the horizontal asymptote. The algorithm fails to converge. \n\n### Convergence Rate\n\nThe following is a derivation of the convergence rate of the NR method:\n\n\nSuppose $x_k \\; \\rightarrow \\; x^*$ and $g'(x^*) \\neq 0$. Then we may write:\n\n$$x_k = x^* + \\epsilon_k$$.\n\nNow expand $g$ at $x^*$:\n\n$$g(x_k) = g(x^*) + g'(x^*)\\epsilon_k + \\frac12 g''(x^*)\\epsilon_k^2 + ...$$\n$$g'(x_k)=g'(x^*) + g''(x^*)\\epsilon_k$$\n\nWe have that\n\n\n\\begin{eqnarray}\n\\epsilon_{k+1} &=& \\epsilon_k + \\left(x_{k-1}-x_k\\right)\\\\\n&=& \\epsilon_k -\\frac{g(x_k)}{g'(x_k)}\\\\\n&\\approx & \\frac{g'(x^*)\\epsilon_k + \\frac12g''(x^*)\\epsilon_k^2}{g'(x^*)+g''(x^*)\\epsilon_k}\\\\\n&\\approx & \\frac{g''(x^*)}{2g'(x^*)}\\epsilon_k^2\n\\end{eqnarray}\n\n## Gauss-Newton\n\nFor 1D, the Newton method is\n$$\nx_{n+1} = x_n - \\frac{f(x_n)}{f'(x_n)}\n$$\n\nWe can generalize to $k$ dimensions by \n$$\nx_{n+1} = x_n - J^{-1} f(x_n)\n$$\nwhere $x$ and $f(x)$ are now vectors, and $J^{-1}$ is the inverse Jacobian matrix. In general, the Jacobian is not a square matrix, and we use the generalized inverse $(J^TJ)^{-1}J^T$ instead, giving\n$$\nx_{n+1} = x_n - (J^TJ)^{-1}J^T f(x_n)\n$$\n\nIn multivariate nonlinear estimation problems, we can find the vector of parameters $\\beta$ by minimizing the residuals $r(\\beta)$, \n$$\n\\beta_{n+1} = \\beta_n - (J^TJ)^{-1}J^T r(\\beta_n)\n$$\nwhere the entries of the Jacobian matrix $J$ are\n$$\nJ_{ij} = \\frac{\\partial r_i(\\beta)}{\\partial \\beta_j}\n$$\n\n## Inverse Quadratic Interpolation\n\nInverse quadratic interpolation is a type of polynomial interpolation. Polynomial interpolation simply means we find the polynomial of least degree that fits a set of points. In quadratic interpolation, we use three points, and find the quadratic polynomial that passes through those three points. \n\n\n```python\n\ndef f(x):\n return (x - 2) * x * (x + 2)**2\n\n\nx = np.arange(-5,5, 0.1);\nplt.plot(x, f(x))\nplt.xlim(-3.5, 0.5)\nplt.ylim(-5, 16)\nplt.xlabel('x')\nplt.axhline(0)\nplt.title(\"Quadratic Interpolation\")\n\n#First Interpolation\nx0=np.array([-3,-2.5,-1.0])\ny0=f(x0)\nf2 = interp1d(x0, y0,kind='quadratic')\n\n#Plot parabola\nxs = np.linspace(-3, -1, num=10000, endpoint=True)\nplt.plot(xs, f2(xs))\n\n#Plot first triplet\nplt.plot(x0, f(x0),'ro');\nplt.scatter(x0, f(x0), s=50, c='yellow');\n\n#New x value\nxnew=xs[np.where(abs(f2(xs))==min(abs(f2(xs))))]\n\nplt.scatter(np.append(xnew,xnew), np.append(0,f(xnew)), c='black');\n\n#New triplet\nx1=np.append([-3,-2.5],xnew)\ny1=f(x1)\nf2 = interp1d(x1, y1,kind='quadratic')\n\n#New Parabola\nxs = np.linspace(min(x1), max(x1), num=100, endpoint=True)\nplt.plot(xs, f2(xs))\n\nxnew=xs[np.where(abs(f2(xs))==min(abs(f2(xs))))]\nplt.scatter(np.append(xnew,xnew), np.append(0,f(xnew)), c='green');\n\n\n```\n\nSo that's the idea behind quadratic interpolation. Use a quadratic approximation, find the zero of interest, use that as a new point for the next quadratic approximation.\n\n\nInverse quadratic interpolation means we do quadratic interpolation on the *inverse function*. So, if we are looking for a root of $f$, we approximate $f^{-1}(x)$ using quadratic interpolation. This just means fitting $x$ as a function of $y$, so that the quadratic is turned on its side and we are guaranteed that it cuts the x-axis somewhere. Note that the secant method can be viewed as a *linear* interpolation on the inverse of $f$. We can write:\n\n$$f^{-1}(y) = \\frac{(y-f(x_n))(y-f(x_{n-1}))}{(f(x_{n-2})-f(x_{n-1}))(f(x_{n-2})-f(x_{n}))}x_{n-2} + \\frac{(y-f(x_n))(y-f(x_{n-2}))}{(f(x_{n-1})-f(x_{n-2}))(f(x_{n-1})-f(x_{n}))}x_{n-1} + \\frac{(y-f(x_{n-2}))(y-f(x_{n-1}))}{(f(x_{n})-f(x_{n-2}))(f(x_{n})-f(x_{n-1}))}x_{n-1}$$\n\nWe use the above formula to find the next guess $x_{n+1}$ for a zero of $f$ (so $y=0$):\n\n$$x_{n+1} = \\frac{f(x_n)f(x_{n-1})}{(f(x_{n-2})-f(x_{n-1}))(f(x_{n-2})-f(x_{n}))}x_{n-2} + \\frac{f(x_n)f(x_{n-2})}{(f(x_{n-1})-f(x_{n-2}))(f(x_{n-1})-f(x_{n}))}x_{n-1} + \\frac{f(x_{n-2})f(x_{n-1})}{(f(x_{n})-f(x_{n-2}))(f(x_{n})-f(x_{n-1}))}x_{n}$$\n\nWe aren't so much interested in deriving this as we are understanding the procedure:\n\n\n\n\n\n```python\nx = np.arange(-5,5, 0.1);\nplt.plot(x, f(x))\nplt.xlim(-3.5, 0.5)\nplt.ylim(-5, 16)\nplt.xlabel('x')\nplt.axhline(0)\nplt.title(\"Inverse Quadratic Interpolation\")\n\n#First Interpolation\nx0=np.array([-3,-2.5,1])\ny0=f(x0)\nf2 = interp1d(y0, x0,kind='quadratic')\n\n#Plot parabola\nxs = np.linspace(min(f(x0)), max(f(x0)), num=10000, endpoint=True)\nplt.plot(f2(xs), xs)\n\n#Plot first triplet\nplt.plot(x0, f(x0),'ro');\nplt.scatter(x0, f(x0), s=50, c='yellow');\n```\n\nConvergence rate is approximately $1.8$. The advantage of the inverse method is that we will *always* have a real root (the parabola will always cross the x-axis). A serious disadvantage is that the initial points must be very close to the root or the method may not converge.\n\nThat is why it is usually used in conjunction with other methods.\n\n## Brentq Method\n\nBrent's method is a combination of bisection, secant and inverse quadratic interpolation. Like bisection, it is a 'bracketed' method (starts with points $(a,b)$ such that $f(a)f(b)<0$.\n\nRoughly speaking, the method begins by using the secant method to obtain a third point $c$, then uses inverse quadratic interpolation to generate the next possible root. Without going into too much detail, the algorithm attempts to assess when interpolation will go awry, and if so, performs a bisection step. Also, it has certain criteria to reject an iterate. If that happens, the next step will be linear interpolation (secant method). \n\nTo find zeros, use \n\n\n```python\nx = np.arange(-5,5, 0.1);\np1=plt.plot(x, f(x))\nplt.xlim(-4, 4)\nplt.ylim(-10, 20)\nplt.xlabel('x')\nplt.axhline(0)\npass\n```\n\n\n```python\nfrom scipy import optimize\n```\n\n\n```python\nscipy.optimize.brentq(f,-1,.5)\n```\n\n\n```python\nscipy.optimize.brentq(f,.5,3)\n```\n\n## Roots of polynomials\n\nOne method for finding roots of polynomials converts the problem into an eigenvalue one by using the **companion matrix** of a polynomial. For a polynomial \n\n$$\np(x) = a_0 + a_1x + a_2 x^2 + \\ldots + a_m x^m\n$$\n\nthe companion matrix is\n\n$$\nA = \\begin{bmatrix}\n-a_{m-1}/a_m & -a_{m-2}/a_m & \\ldots & -a_0/a_m \\\\\n1 & 0 & \\ldots & 0 \\\\\n0 & 1 & \\ldots & 0 \\\\\n\\vdots & \\vdots & \\ldots & \\vdots \\\\\n0 & 0 & \\ldots & 0\n\\end{bmatrix}\n$$\n\nThe characteristic polynomial of the companion matrix is $\\lvert \\lambda I - A \\rvert$ which expands to \n\n$$\na_0 + a_1 \\lambda + a_2 \\lambda^2 + \\ldots + a_m \\lambda^m\n$$\n\nIn other words, the roots we are seeking are the eigenvalues of the companion matrix.\n\nFor example, to find the cube roots of unity, we solve $x^3 - 1 = 0$. The `roots` function uses the companion matrix method to find roots of polynomials.\n\n\n```python\n# Coefficients of $x^3, x^2, x^1, x^0$\n\npoly = np.array([1, 0, 0, -1])\n```\n\nManual construction\n\n\n```python\nA = np.array([\n [0,0,1],\n [1,0,0],\n [0,1,0]\n])\n```\n\n\n```python\nscipy.linalg.eigvals(A)\n```\n\nUsing built-in function\n\n\n```python\nx = np.roots(poly)\nx\n```\n\n\n```python\nplt.scatter([z.real for z in x], [z.imag for z in x])\ntheta = np.linspace(0, 2*np.pi, 100)\nu = np.cos(theta)\nv = np.sin(theta)\nplt.plot(u, v, ':')\nplt.axis('square')\npass\n```\n\n## Using `scipy.optimize`\n\n### Finding roots of univariate equations\n\n\n```python\ndef f(x):\n return x**3-3*x+1\n```\n\n\n```python\nx = np.linspace(-3,3,100)\nplt.axhline(0, c='red')\nplt.plot(x, f(x))\npass\n```\n\n\n```python\nfrom scipy.optimize import brentq, newton\n```\n\n#### `brentq` is the recommended method\n\n\n```python\nbrentq(f, -3, 0), brentq(f, 0, 1), brentq(f, 1,3)\n```\n\n#### Secant method\n\n\n```python\nnewton(f, -3), newton(f, 0), newton(f, 3)\n```\n\n#### Newton-Raphson method\n\n\n```python\nfprime = lambda x: 3*x**2 - 3\nnewton(f, -3, fprime), newton(f, 0, fprime), newton(f, 3, fprime)\n```\n\n### Finding fixed points\n\nFinding the fixed points of a function $g(x) = x$ is the same as finding the roots of $g(x) - x$. However, specialized algorithms also exist - e.g. using `scipy.optimize.fixedpoint`.\n\n\n```python\nfrom scipy.optimize import fixed_point\n```\n\n\n```python\nx = np.linspace(-3,3,100)\nplt.plot(x, f(x), color='red')\nplt.plot(x, x)\npass\n```\n\n\n```python\nfixed_point(f, 0), fixed_point(f, -3), fixed_point(f, 3)\n```\n\n### Mutlivariate roots and fixed points\n\nUse `root` to solve polynomial equations. Use `fsolve` for non-polynomial equations.\n\n\n```python\nfrom scipy.optimize import root, fsolve\n```\n\nSuppose we want to solve a sysetm of $m$ equations with $n$ unknowns\n\n\\begin{align}\nf(x_0, x_1) &= x_1 - 3x_0(x_0+1)(x_0-1) \\\\\ng(x_0, x_1) &= 0.25 x_0^2 + x_1^2 - 1\n\\end{align}\n\nNote that the equations are non-linear and there can be multiple solutions. These can be interpreted as fixed points of a system of differential equations.\n\n\n```python\ndef f(x):\n return [x[1] - 3*x[0]*(x[0]+1)*(x[0]-1),\n .25*x[0]**2 + x[1]**2 - 1]\n```\n\n\n```python\nsol = root(f, (0.5, 0.5))\nsol.x\n```\n\n\n```python\nfsolve(f, (0.5, 0.5))\n```\n\n\n```python\nr0 = root(f,[1,1])\nr1 = root(f,[0,1])\nr2 = root(f,[-1,1.1])\nr3 = root(f,[-1,-1])\nr4 = root(f,[2,-0.5])\n\nroots = np.c_[r0.x, r1.x, r2.x, r3.x, r4.x]\n```\n\n\n```python\nY, X = np.mgrid[-3:3:100j, -3:3:100j]\nU = Y - 3*X*(X + 1)*(X-1)\nV = .25*X**2 + Y**2 - 1\n\nplt.streamplot(X, Y, U, V, color=U, linewidth=2, cmap=plt.cm.autumn)\nplt.scatter(roots[0], roots[1], s=50, c='none', edgecolors='k', linewidth=2)\npass\n```\n\n#### We can also give the Jacobian\n\n\n```python\ndef jac(x):\n return [[-6*x[0], 1], [0.5*x[0], 2*x[1]]]\n```\n\n\n```python\nsol = root(f, (0.5, 0.5), jac=jac)\nsol.x, sol.fun\n```\n\n#### Check that values found are really roots\n\n\n\n```python\nnp.allclose(f(sol.x), 0)\n```\n\n#### Starting from other initial conditions, different roots may be found\n\n\n```python\nsol = root(f, (12,12))\nsol.x\n```\n\n\n```python\nnp.allclose(f(sol.x), 0)\n```\n", "meta": {"hexsha": "509c810d8ef9496a287bfb5908550168541e93ba", "size": 31540, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/T07B_Root_Finding.ipynb", "max_stars_repo_name": "Yijia17/sta-663-2021", "max_stars_repo_head_hexsha": "e6484e3116c041b8c8eaae487eff5f351ff499c9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 18, "max_stars_repo_stars_event_min_datetime": "2021-01-19T16:35:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-01T02:12:30.000Z", "max_issues_repo_path": "notebooks/T07B_Root_Finding.ipynb", "max_issues_repo_name": "Yijia17/sta-663-2021", "max_issues_repo_head_hexsha": "e6484e3116c041b8c8eaae487eff5f351ff499c9", "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/T07B_Root_Finding.ipynb", "max_forks_repo_name": "Yijia17/sta-663-2021", "max_forks_repo_head_hexsha": "e6484e3116c041b8c8eaae487eff5f351ff499c9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 24, "max_forks_repo_forks_event_min_datetime": "2021-01-19T16:26:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-15T05:10:14.000Z", "avg_line_length": 28.9357798165, "max_line_length": 798, "alphanum_fraction": 0.5220355105, "converted": true, "num_tokens": 6676, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273633016692238, "lm_q2_score": 0.9362850004144266, "lm_q1q2_score": 0.8682763492876933}} {"text": "# Calculate Jensen-Shannon Divergence Between Luke and John\n\nThe KL Divergence between two discrete distributions $P$ and $Q$ with pdfs $p$ and $q$, defined over the same sample space $X=\\{x_0,x_1, \\dots, x_N\\}$, is given by\n\n\\begin{equation}\nKL(P||Q) = \\sum_{i=0}^N p(x_i) \\ln \\Big( \\frac{p(x_i)}{q(x_i)} \\Big)\n\\end{equation}\n\nThis divergence is not a metric because it is not symmetric, i.e. it is often the case that $KL(P||Q) \\ne KL(Q||P)$. To address this, we will use the Jensen-Shannon Divergence which is a true metric and is defined as\n\n\\begin{equation}\nJSD(P||Q) = \\frac{1}{2}KL(P||R) + \\frac{1}{2}KL(Q||R)\n\\end{equation}\n\nwhere $R$ is defined as the average of the two distributions $R=\\frac{P+Q}{2}$\n\n---\n\n\n```python\nfrom PIL import Image\nimport numpy as np\n```\n\n\n```python\nluke = Image.open(\"/home/nathan/Downloads/Luke_Van_Poppering.jpeg\")\nluke.thumbnail((300,300)) # Thanks for this, John....\njohn = Image.open(\"/home/nathan/Downloads/John_Abascal.jpg\")\njohn.thumbnail((300,300))\n```\n\n\n```python\nluke\n```\n\n\n```python\njohn\n```\n\n---\nIf we assume that our histograms are exact, then we can trivally calculate the Jensen-Shannon Divergence between them by normalizing the histograms and summing up the terms on the RHS of the JSD equation...\n\n\n```python\ndef KL(p: np.array, q: np.array):\n val = 0\n for i,pi in enumerate(p):\n if pi == 0:\n continue\n val += pi*np.log2(pi/q[i])\n return val\n\ndef JSD(p: np.array, q: np.array):\n r = (p+q)/2\n p = p[r != 0] # If r_i is zero, then it is in neither p nor q and can be ignored\n q = q[r != 0]\n r = r[r != 0] \n val = 0.5*(KL(p,r)+KL(q,r))\n return val\n\ndef hist_loss(im1, im2):\n im1_channels = im1.split()\n im2_channels = im2.split()\n loss = []\n for im1_c, im2_c in zip(im1_channels,im2_channels):\n hist1 = np.array(im1_c.histogram())\n hist2 = np.array(im2_c.histogram())\n loss.append(JSD(hist1/hist1.sum(), hist2/hist2.sum()))\n return np.mean(loss)\n```\n\n---\nIt is symmetric...\n\n\n```python\nhist_loss(luke, john) == hist_loss(john, luke)\n```\n\n\n\n\n True\n\n\n\nand returns zero when operating on the same image...\n\n\n```python\nhist_loss(john, john)\n```\n\n\n\n\n 0.0\n\n\n\n\n```python\nhist_loss(luke, luke)\n```\n\n\n\n\n 0.0\n\n\n\n\n```python\nhist_loss(np.zeros(255),np.ones(255))\n```\n\n\n```python\nJSD(np.zeros(255),np.ones(255)/255)\n```\n\n\n\n\n 0.49999999999999845\n\n\n", "meta": {"hexsha": "05dbbd2422d21c439070913746de0ec83dbdf9d4", "size": 254719, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "JSD_Example.ipynb", "max_stars_repo_name": "mathnathan/notebooks", "max_stars_repo_head_hexsha": "63ae2f17fd8e1cd8d80fef8ee3b0d3d11d45cd28", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-12-04T11:04:45.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-04T11:04:45.000Z", "max_issues_repo_path": "JSD_Example.ipynb", "max_issues_repo_name": "mathnathan/notebooks", "max_issues_repo_head_hexsha": "63ae2f17fd8e1cd8d80fef8ee3b0d3d11d45cd28", "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": "JSD_Example.ipynb", "max_forks_repo_name": "mathnathan/notebooks", "max_forks_repo_head_hexsha": "63ae2f17fd8e1cd8d80fef8ee3b0d3d11d45cd28", "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": 906.4733096085, "max_line_length": 132136, "alphanum_fraction": 0.9492264024, "converted": true, "num_tokens": 757, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9653811611608242, "lm_q2_score": 0.8991213826762113, "lm_q1q2_score": 0.8679948444324866}} {"text": "```python\n%matplotlib inline\n%config InlineBackend.figure_format = 'retina'\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\nfrom scipy.stats import pearsonr\nfrom scipy.stats import t as tdist\n```\n\n# DIY t-test\n\nAs a first exercise lets try to mimic a t-test using simulated data. As the t-test is just a theoretic representation of what we are doing here, our empirical result from the simulation should be the very close to the theoretical one. To generate a so called null-distribution for the correlation coefficient we repeatedly draw __uncorrelated__ samples from a normal distribution and correlate them with each other saving the result.\n\n\n```python\n# Total number of samples\nnsample = 10000\n# Number of observations in each sample\nnobs = 100 \n\n# Initialization of a variable for all our samples\nr_sample= np.zeros(nsample)\n\n# Draw samples and correlate\nfor i in range(nsample):\n x = np.random.randn(nobs)\n y = np.random.randn(nobs)\n r, p = pearsonr(x, y)\n r_sample[i] = r\n```\n\nWe can take a look at the samples and how they are distributed using a histogram. Note that they have a mean value of 0. The width of the distribution changes with the number of observations we correlate in each of the samples. Go ahead and give that a try, by changing the value of `nobs` above.\n\n\n```python\nplt.hist(r_sample, histtype='step')\nplt.xlabel('$r$')\n```\n\nFor the t-test we use the value of $r$ and the number of observations to calculate the test statistic, the t-value using the following formula:\n\n\\begin{align}\n t = r \\frac{\\sqrt{n - 2}}{\\sqrt{1 - r^2}}\n\\end{align}\n\nbelow this formula is implemented in a function and than applied to the sample of $r$'s that we have produced above.\n\n\n```python\ndef calc_t(r, n):\n \"\"\"Calculate t statistic for Pearsons r\"\"\"\n t = r * np.sqrt(n - 2) / np.sqrt(1 - r**2)\n return t\n```\n\n\n```python\nt_sample = calc_t(r_sample, nobs)\n```\n\nTo be able to compare the sample with the theoretical distribution of this variable, the t-distribution we need to have a range of t-values that spans the range of our samples:\n\n\n```python\nt_plot = np.linspace(np.min(t_sample), np.max(t_sample), 100)\n```\n\nNow we have everything to compare our empirical distribution with the theoretical one:\n\n\n```python\nplt.hist(t_sample, histtype='step', density=True, label='empirical')\nplt.plot(t_plot, tdist.pdf(t_plot, nobs - 2), label='theoretical')\nplt.legend()\n```\n\nThey should be a pretty close match as the theory is exactly describing what we have done before, just for infinitly many samples.\n\nLets now compare the $r$ value of the time series in the slides to both the theoretical and empirical ones. Recall. that $r=0.27$ and we had 99 observations in the correlation.\n\n\n```python\nr_data = 0.27\nnobs = 99\n```\n\nFirst lets test the value using the classical t-test:\n\n\n```python\nt_data = calc_t(r_data, nobs)\nprint('t = %.2f' % t_data)\n\np_theoretical = 2 * (1 - tdist.cdf(t_data, nobs - 2))\n\nprint('Theoretical p-value: %.3f' % p_theoretical)\n```\n\nNow lets use the code from above to generate a sample for r and for t that we can test these values against.\n\n\n```python\n# Total number of samples\nnsample = 10000\n# Number of observations in each sample\n# Initialization of a variable for all our samples\nr_sample= np.zeros(nsample)\n# Draw samples and correlate\nfor i in range(nsample):\n x = np.random.randn(nobs)\n y = np.random.randn(nobs)\n r, p = pearsonr(x, y)\n r_sample[i] = r\n \nt_sample = calc_t(r_sample, nobs)\n```\n\nWe can test both the fraction of simulated t-values that are larger than the t-value for the data as well as the r-value directly to obtain an empirical p-value for our data.\n\n\n```python\nnp.mean(np.abs(t_sample) >= t_data)\n```\n\n\n```python\nnp.mean(np.abs(r_sample) >= r_data)\n```\n\nAgain, these values should be very close to the theoretical one as they are essenitally generated the same way, just with a finite number of samples.\n\nSo why was this important, when the result is the same as in the t-test anyway?\n\nThe t-test as per the theory is not always applicable, depending on the data or the type of statistic that we are looking at. The same is true for any other statistical test. However, as long as you can generate an empirical null-distribution, you will have something to test against. You will not be limited to the special cases that the usual tests are usefull for! So this a very important tool to have.\n", "meta": {"hexsha": "0dcca953c1096e1018c8816bd486d9d29066e29d", "size": 7487, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "01-DIY_t-test.ipynb", "max_stars_repo_name": "terhardt/ICAT-stats", "max_stars_repo_head_hexsha": "5e74aff69a4c1b65c7756cb4edcd0db1df8a60fc", "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": "01-DIY_t-test.ipynb", "max_issues_repo_name": "terhardt/ICAT-stats", "max_issues_repo_head_hexsha": "5e74aff69a4c1b65c7756cb4edcd0db1df8a60fc", "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": "01-DIY_t-test.ipynb", "max_forks_repo_name": "terhardt/ICAT-stats", "max_forks_repo_head_hexsha": "5e74aff69a4c1b65c7756cb4edcd0db1df8a60fc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.6858237548, "max_line_length": 439, "alphanum_fraction": 0.590490183, "converted": true, "num_tokens": 1104, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240090865198, "lm_q2_score": 0.9252299524531926, "lm_q1q2_score": 0.8679804323223191}} {"text": "# Logistic Regression\n[source](https://www.youtube.com/watch?v=hSXFuypLukA)\n### Step 1: Function Set \nWe want to find $P_{w,b}(C1|x)$ \nif $P_{w,b}(C_1|x) \\geq 0.5$, output $C_1$, otherwise, output $C_2$ \n\n$P_{w,b}(C_1|x) = \\sigma(z)$ \n$$z = w \\cdot x + b = \\sum_{i}wi xi + b \\\\ \n\\sigma(z) = \\frac{1}{1+exp(-z)}$$ \n\n$\\begin{equation}\n\\large{f_{w,b}(x) = \\sigma(\\sum_{i}w_i x_i + b)} \n\\end{equation}$ \nOutput should between 0 and 1\n\n\n### Step 2: Goodness of a Function\nTraining Data$\n\\ x^1 \\ x^2 \\ x^3 \\ ... \\ x^N \\\\\n\\ C_1 \\ C_2 \\ C_1 \\ ... \\ C_1 \n$ \nAssume the data is generated based on $f_{w,b}(x) = P_{w,b}(C_1|x)$ \nGiven a set of w and b, what is its probability of generating the data? \n$\\begin{equation}\n\\large L(w,b) = f_{w,b}(x^)(1 - f_{w,b}(x^2))f_{w,b}(x^3)...f_{w,b}(x^N)\n\\end{equation}$ \n\nThe most likely $w^*$ and $b^*$ is the one with the largest $L(w,b)$. \n\n$$w^*,b^* = arg\\ max_{w,b}L(w,b) = \nw^*, b^* = arg\\min_{w,b}-lnL(w,b)$$ \n$$\nx^1 \\qquad x^2 \\qquad x^3 \\qquad ... \\\\\n\\hat{y}^1=1 \\quad \\hat{y}^2=0 \\quad \\hat{y}^3=1 ... \\\\\n\\hat{y}^n : 1 \\text{ for class 1, 0 for class 2}\n$$\n\n\n右側省略w,b\n\n左右兩側相等, 故可寫成下列公式\n$$\n\\large{\\sum_{n}-[\\hat{y}^n ln f_{w,b}(x^n) + (1-\\hat{y}^n) ln (1- f_{w,b}(x^n))]} \\\\\n\\text{Cross entropy between two Bernoulli distribution}\n$$ \n\n\n### Step 3: Find the best function\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "f45b72617adfed2b01dc8751d64e5d79aee9d0bc", "size": 2877, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Machine learning/Logistic Regression/notebook.ipynb", "max_stars_repo_name": "Sean2525/notebooks", "max_stars_repo_head_hexsha": "10afea47674f437441426ba32c42f2bb5d25c19f", "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": "Machine learning/Logistic Regression/notebook.ipynb", "max_issues_repo_name": "Sean2525/notebooks", "max_issues_repo_head_hexsha": "10afea47674f437441426ba32c42f2bb5d25c19f", "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/Logistic Regression/notebook.ipynb", "max_forks_repo_name": "Sean2525/notebooks", "max_forks_repo_head_hexsha": "10afea47674f437441426ba32c42f2bb5d25c19f", "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": 27.932038835, "max_line_length": 99, "alphanum_fraction": 0.469933959, "converted": true, "num_tokens": 593, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9637799472560581, "lm_q2_score": 0.9005297901222472, "lm_q1q2_score": 0.8679125536265285}} {"text": "# Linear Programming\n\n## Introduction\n* Widely used\n* Used to represent many practical problems\n* Elements\n * A linear objective function\n * Linear (in)equalities\n \n\n## The standard Form\n\\begin{align}\n\\text{minimize}\\ & f(x) \\\\\n\\text{subject to } & \\\\\n& a_1x &&\\geq b_1 \\\\\n& a_2x + c && \\geq b_2 \\\\\n& x &&\\geq 0\n\\end{align}\n\n\n\n# Gurobi Basics: Linear Model\n## Mathematical Model\n\\begin{align}\n\\text{minimize}\\ & 5x + 4y \\\\\n\\text{subject to } & \\\\\n& \\ \\ x+\\ \\ y &&\\geq \\ \\ 8 \\\\\n& 2x + \\ \\ y &&\\geq 10 \\\\\n& \\ \\ x + 4y &&\\geq 11 \\\\\n& \\ \\ x &&\\geq \\ \\ 0 \\\\\n& \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ y &&\\geq \\ \\ 0\n\\end{align}\n\n## Graphical representation of the problem\n\n\n\n```python\nfrom IPython.display import Image\nfrom IPython.display import display\ngraphs = ['fr', 'fr_o1', 'fr_o3']\nfor g in graphs:\n display(Image(filename = g+'.png'))\n```\n\n# Code in Python using gurobipy\n## Step 1: Importing gurobipy package\n\n\n```python\nfrom gurobipy import *\n```\n\n## Step 2: Create an optimization model\nModel constructor. Initially, no variables or constraints.\n``` python\nModel(name = '')\n```\n\n\n```python\nopt_mod = Model(name = \"linear program\")\n```\n\n## Step 3: Add decision variables\nAdd a decision variable to a model.\n``` python\n\nModel.addVar(lb = 0.0, #(optional) lower bound\n ub = float('inf'), #(optional) upper bound\n obj = 0.0, #(optional) objective coefficient\n vtype = GRB.CONTINUOUS, #(optional) variable type\n name = \"\") #(optional) name\n \n```\n\n\n```python\nx = opt_mod.addVar(name = 'x', vtype = GRB.CONTINUOUS, lb = 0)\ny = opt_mod.addVar(name = 'y', vtype = GRB.CONTINUOUS, lb = 0)\n```\n\n## Step 4: Define the objective function\nSet the model objective equal to a expression\n``` python\n\nModel.setObjective(expr, #New objective expression \n sense = None) #GRB.MINIMIZE for minimization, \n #GRB.MAXIMIZE for maximization\n```\n\n\n```python\nobj_fn = 5*x + 4*y\nopt_mod.setObjective(obj_fn, GRB.MINIMIZE)\n```\n\n## Step 5: Add the constraints\nAdd a constraint to a model. \n```python\nModel.addConstr(constr, # constraint object \n name=\"\") # name of the constraint\n```\n\n\n```python\nc1 = opt_mod.addConstr( x + y >= 8, name = 'c1')\nc2 = opt_mod.addConstr(2*x + y >= 10, name = 'c2')\nc3 = opt_mod.addConstr( x + 4*y >= 11, name = 'c3')\n```\n\n## Step 6: Solve the model\n\n``` python\nModel.optimize() # optimize the model\n\nModel.write(filename) # write model to a file\n```\n\n\n```python\nopt_mod.optimize() # solve the model\nopt_mod.write(\"linear_model.lp\") # output the LP file of the model\n```\n\n## Step 7: Output the result\n\n\n```python\nprint('Objective Function Value: %f' % opt_mod.objVal)\n# Get values of the decision variables\nfor v in opt_mod.getVars():\n print('%s: %g' % (v.varName, v.x))\n```\n", "meta": {"hexsha": "e63554b9421e43f7a6ea8052d54aecdbc4881de6", "size": 5685, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "mathematicalProgramming/Video02/video_02.ipynb", "max_stars_repo_name": "codingperspective/videoMaterials", "max_stars_repo_head_hexsha": "8c9665466d8912c6f0c701c25ad9eb4802fb73a3", "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": "mathematicalProgramming/Video02/video_02.ipynb", "max_issues_repo_name": "codingperspective/videoMaterials", "max_issues_repo_head_hexsha": "8c9665466d8912c6f0c701c25ad9eb4802fb73a3", "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": "mathematicalProgramming/Video02/video_02.ipynb", "max_forks_repo_name": "codingperspective/videoMaterials", "max_forks_repo_head_hexsha": "8c9665466d8912c6f0c701c25ad9eb4802fb73a3", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2021-11-21T05:02:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-17T04:44:57.000Z", "avg_line_length": 23.8865546218, "max_line_length": 79, "alphanum_fraction": 0.4765171504, "converted": true, "num_tokens": 860, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9748211604938802, "lm_q2_score": 0.8902942275774318, "lm_q1q2_score": 0.8678776521080348}} {"text": "```python\nfrom sympy import *\ninit_printing(use_latex='mathjax')\n```\n\n\n```python\ndef get_diff(symbol, expression):\n return diff(expression, symbol)\n```\n\n\n```python\nx = symbols('x')\nget_diff(x, (x + 2) * (3 * x - 3))\n```\n\n\n\n\n$$6 x + 3$$\n\n\n\n\n```python\nx = symbols('x')\nget_diff(x, exp(x) * ( x ** 2 + 7 * x - 3 - sin(x) ))\n```\n\n\n\n\n$$\\left(2 x - \\cos{\\left (x \\right )} + 7\\right) e^{x} + \\left(x^{2} + 7 x - \\sin{\\left (x \\right )} - 3\\right) e^{x}$$\n\n\n\n\n```python\nf = (x**2 - 2 * x + 5)\n```\n\n\n```python\ng = (sin(x) + cos(x))\n```\n\n\n```python\nx = symbols('x')\nfp=get_diff(x, f)\n```\n\n\n```python\nx = symbols('x')\ngp=get_diff(x, g)\n```\n\n\n```python\nf * gp + g * fp\n```\n\n\n\n\n$$\\left(2 x - 2\\right) \\left(\\sin{\\left (x \\right )} + \\cos{\\left (x \\right )}\\right) + \\left(- \\sin{\\left (x \\right )} + \\cos{\\left (x \\right )}\\right) \\left(x^{2} - 2 x + 5\\right)$$\n\n\n\n\n```python\nx = symbols('x')\nfp = get_diff(x, exp(x) * (3 * x - 2 ) * sin(x))\nfactor(simplify(fp))\n```\n\n\n\n\n$$\\left(3 x \\sin{\\left (x \\right )} + 3 x \\cos{\\left (x \\right )} + \\sin{\\left (x \\right )} - 2 \\cos{\\left (x \\right )}\\right) e^{x}$$\n\n\n\n\n```python\nx = symbols('x')\nfp = get_diff(x, - 1 / 3 * ( exp(x) - 1) ** 2 + (exp(x) - 1) + 1/5)\nsimplify(fp)\n```\n\n\n\n\n$$\\left(- 0.666666666666667 e^{x} + 1.66666666666667\\right) e^{x}$$\n\n\n\n\n```python\nx = symbols('x')\nfp = get_diff(x, sqrt(x ** 3 - 2 * x ) )\nfp\n```\n\n\n\n\n$$\\frac{\\frac{3 x^{2}}{2} - 1}{\\sqrt{x^{3} - 2 x}}$$\n\n\n\n\n```python\nx = symbols('x')\nfp = get_diff(x, exp(x ** 3 - 3 ))\nfp\n```\n\n\n\n\n$$3 x^{2} e^{x^{3} - 3}$$\n\n\n\n\n```python\nx = symbols('x')\nfp = get_diff(x, sqrt(exp(x + 2)))\nsimplify(fp)\n```\n\n\n\n\n$$\\frac{1}{2} \\sqrt{e^{x + 2}}$$\n\n\n\n\n```python\nx = symbols('x')\nfp = get_diff(x, x ** (3/2) + pi * x ** 2 + sqrt(7))\nfp\n```\n\n\n\n\n$$1.5 x^{0.5} + 2 \\pi x$$\n\n\n\n\n```python\nx = symbols('x')\nfp = get_diff(x, x ** 3 * cos(x) * exp(x))\nfp\n```\n\n\n\n\n$$- x^{3} e^{x} \\sin{\\left (x \\right )} + x^{3} e^{x} \\cos{\\left (x \\right )} + 3 x^{2} e^{x} \\cos{\\left (x \\right )}$$\n\n\n\n\n```python\nx = symbols('x')\nfp = get_diff(x, exp((x + 1) ** 2))\nfp\n```\n\n\n\n\n$$\\left(2 x + 2\\right) e^{\\left(x + 1\\right)^{2}}$$\n\n\n\n\n```python\nx = symbols('x')\nfp = get_diff(x, x ** 2 * cos(x ** 3))\nfp\n```\n\n\n\n\n$$- 3 x^{4} \\sin{\\left (x^{3} \\right )} + 2 x \\cos{\\left (x^{3} \\right )}$$\n\n\n\n\n```python\nx = symbols('x')\nfp = get_diff(x, sin(x) * exp(cos(x)))\nfp\n```\n\n\n\n\n$$- e^{\\cos{\\left (x \\right )}} \\sin^{2}{\\left (x \\right )} + e^{\\cos{\\left (x \\right )}} \\cos{\\left (x \\right )}$$\n\n\n\n\n```python\nfp.evalf(subs={x: pi})\n```\n\n\n\n\n$$-0.367879441171442$$\n\n\n\n\n```python\nnsimplify(6.28, [pi], tolerance=0.01)\n```\n\n\n\n\n$$2 \\pi$$\n\n\n\n\n```python\n(1 / exp(1)).evalf()\n```\n\n\n\n\n$$0.367879441171442$$\n\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "245826173219a3900496e21780aa06a2b8abaaa1", "size": 10328, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Certification 2/Week1.1 - Differential.ipynb", "max_stars_repo_name": "The-Brains/MathForMachineLearning", "max_stars_repo_head_hexsha": "5cbd9006f166059efaa2f312b741e64ce584aa1f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2018-04-16T02:53:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-16T06:51:57.000Z", "max_issues_repo_path": "Certification 2/Week1.1 - Differential.ipynb", "max_issues_repo_name": "The-Brains/MathForMachineLearning", "max_issues_repo_head_hexsha": "5cbd9006f166059efaa2f312b741e64ce584aa1f", "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": "Certification 2/Week1.1 - Differential.ipynb", "max_forks_repo_name": "The-Brains/MathForMachineLearning", "max_forks_repo_head_hexsha": "5cbd9006f166059efaa2f312b741e64ce584aa1f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2019-05-20T02:06:55.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-18T06:21:41.000Z", "avg_line_length": 20.4110671937, "max_line_length": 212, "alphanum_fraction": 0.3865220759, "converted": true, "num_tokens": 1125, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122756889437, "lm_q2_score": 0.9059898210180105, "lm_q1q2_score": 0.8678587712023812}} {"text": "\n\n

Linear Regression with Gradient Descent Using a Made Up Example

\n\n\n## Gradient descent algorithm\nFrom our [video](https://youtu.be/fkS3FkVAPWU) on linear regression, we derived the equation to update the linear model parameters as: \n\n\n\\begin{equation}\n\\theta^{+} = \\theta^{-} + \\frac{\\alpha}{m} (y_{i} - h(x_{i}) )\\bar{x}\n\\end{equation}\n\nThis minimizes the following cost function\n\n\\begin{equation}\nJ(x, \\theta, y) = \\frac{1}{2m}\\sum_{i=1}^{m}(h(x_i) - y_i)^2\n\\end{equation}\n\nwhere\n\\begin{equation}\nh(x_i) = \\theta^T \\bar{x}\n\\end{equation}\n\n### Batch gradient descent\n```FOR j FROM 0 -> max_iteration: \n FOR i FROM 0 -> m: \n theta += (alpha / m) * (y[i] - h(x[i])) * x_bar\n ENDLOOP\nENDLOOP\n```\n\n### Stochastic gradient descent\n```shuffle(x, y)\nFOR i FROM 0 -> m:\n theta += (alpha / m) * (y[i] - h(x[i])) * x_bar \nENDLOOP\n```\n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\n```\n\n\n```python\n\"\"\"Generate data\"\"\"\ntrue_slope = 10.889\ntrue_intercept = 3.456\ninput_var = np.arange(0.0,100.0)\noutput_var = true_slope * input_var + true_intercept + 500.0 * np.random.rand(len(input_var))\n```\n\n\n```python\n%matplotlib notebook\nplt.figure()\nplt.scatter(input_var, output_var)\nplt.xlabel('x')\nplt.ylabel('y')\nplt.show()\n```\n\n\n```python\ndef compute_cost(input_var, output_var, params):\n \"Compute linear regression cost\"\n num_samples = len(input_var)\n cost_sum = 0.0\n for x,y in zip(input_var, output_var):\n y_hat = np.dot(params, np.array([1.0, x]))\n cost_sum += (y_hat - y) ** 2\n \n cost = cost_sum / (num_samples * 2.0)\n \n return cost\n```\n\n\n```python\ndef lin_reg_batch_gradient_descent(input_var, output_var, params, alpha, max_iter):\n \"\"\"Compute the params for linear regression using batch gradient descent\"\"\" \n iteration = 0\n num_samples = len(input_var)\n cost = np.zeros(max_iter)\n params_store = np.zeros([2, max_iter])\n \n while iteration < max_iter:\n cost[iteration] = compute_cost(input_var, output_var, params)\n params_store[:, iteration] = params\n \n print('--------------------------')\n print(f'iteration: {iteration}')\n print(f'cost: {cost[iteration]}')\n \n for x,y in zip(input_var, output_var):\n y_hat = np.dot(params, np.array([1.0, x]))\n gradient = np.array([1.0, x]) * (y - y_hat)\n params += alpha * gradient/num_samples\n \n iteration += 1\n \n return params, cost, params_store\n \n```\n\n\n```python\n\"\"\"Train the model\"\"\"\nfrom sklearn.model_selection import train_test_split\nx_train, x_test, y_train, y_test = train_test_split(input_var, output_var, test_size=0.20)\n\nparams_0 = np.array([20.0, 80.0])\n\nalpha_batch = 1e-3\nmax_iter = 500\nparams_hat_batch, cost_batch, params_store_batch =\\\n lin_reg_batch_gradient_descent(x_train, y_train, params_0, alpha_batch, max_iter)\n```\n\n\n```python\ndef lin_reg_stoch_gradient_descent(input_var, output_var, params, alpha):\n \"\"\"Compute the params for linear regression using stochastic gradient descent\"\"\"\n num_samples = len(input_var)\n cost = np.zeros(num_samples)\n params_store = np.zeros([2, num_samples])\n \n i = 0\n for x,y in zip(input_var, output_var):\n cost[i] = compute_cost(input_var, output_var, params)\n params_store[:, i] = params\n \n print('--------------------------')\n print(f'iteration: {i}')\n print(f'cost: {cost[i]}')\n \n y_hat = np.dot(params, np.array([1.0, x]))\n gradient = np.array([1.0, x]) * (y - y_hat)\n params += alpha * gradient/num_samples\n \n i += 1\n \n return params, cost, params_store\n```\n\n\n```python\nalpha = 1e-3\nparams_0 = np.array([20.0, 80.0])\nparams_hat, cost, params_store =\\\nlin_reg_stoch_gradient_descent(x_train, y_train, params_0, alpha)\n```\n\n\n```python\nplt.figure()\nplt.scatter(x_test, y_test)\nplt.plot(x_test, params_hat_batch[0] + params_hat_batch[1]*x_test, 'g', label='batch')\nplt.plot(x_test, params_hat[0] + params_hat[1]*x_test, '-r', label='stochastic')\nplt.xlabel('x')\nplt.ylabel('y')\nplt.legend()\nplt.show()\nprint(f'batch T0, T1: {params_hat_batch[0]}, {params_hat_batch[1]}')\nprint(f'stochastic T0, T1: {params_hat[0]}, {params_hat[1]}')\nrms_batch = np.sqrt(np.mean(np.square(params_hat_batch[0] + params_hat_batch[1]*x_test - y_test)))\nrms_stochastic = np.sqrt(np.mean(np.square(params_hat[0] + params_hat[1]*x_test - y_test)))\nprint(f'batch rms: {rms_batch}')\nprint(f'stochastic rms: {rms_stochastic}')\n```\n\n\n```python\nplt.figure()\nplt.plot(np.arange(max_iter), cost_batch, 'r', label='batch')\nplt.plot(np.arange(len(cost)), cost, 'g', label='stochastic')\nplt.xlabel('iteration')\nplt.ylabel('normalized cost')\nplt.legend()\nplt.show()\nprint(f'min cost with BGD: {np.min(cost_batch)}')\nprint(f'min cost with SGD: {np.min(cost)}')\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "0f41b1279b6130ca77a96eefde32e32f58f64d04", "size": 9051, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/linear-regression.ipynb", "max_stars_repo_name": "endlesseng/ml-vid-code", "max_stars_repo_head_hexsha": "3bf8bfb6a5a692d4e36e9f7b20eb6837d9cff957", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2020-07-01T12:38:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-25T16:10:54.000Z", "max_issues_repo_path": "notebooks/linear-regression.ipynb", "max_issues_repo_name": "endlesseng/ml-vid-code", "max_issues_repo_head_hexsha": "3bf8bfb6a5a692d4e36e9f7b20eb6837d9cff957", "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": "notebooks/linear-regression.ipynb", "max_forks_repo_name": "endlesseng/ml-vid-code", "max_forks_repo_head_hexsha": "3bf8bfb6a5a692d4e36e9f7b20eb6837d9cff957", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 32, "max_forks_repo_forks_event_min_datetime": "2019-03-26T09:44:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T20:50:02.000Z", "avg_line_length": 27.0988023952, "max_line_length": 147, "alphanum_fraction": 0.5182852723, "converted": true, "num_tokens": 1400, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9591542805873231, "lm_q2_score": 0.9046505312448598, "lm_q1q2_score": 0.8676994294791032}} {"text": "#Matrice\nRappresentazione di un insieme di vettori si può utilizzare una visualizzaione in tabella.\n$$\nv_0 = (30, 10, 10) \\\\\nv_1 = (20, 20, 5) \\\\\nv_2 = (15, 15 ,10) \\\\\n\\begin{bmatrix}\n30 & 10 & 10 \\\\\n20 & 20 & 5 \\\\\n15 & 15 & 10 \\\\\n\\end{bmatrix}\n$$\nQuesta rappresentazione in tabella è definita matrice. \nIl numero di righe e colonne dipende dall'applicazione ma non esiste un limite predefinito. \n$$\n\\begin{pmatrix}\n0 & 3 & 4 & 1 \\\\\n0 & 1 & 1 & 1 \\\\\n1 & -1 & 0 & 0\n\\end{pmatrix}\n$$\nAnche la scelta delle parentesi non ha un significato a priori. \nQuindi una matrice $A$ con $m$ righe e $n$ colonne avrà il seguente schema\n$$\nA = \n\\begin{bmatrix}\na_{11} & \\cdots & a_{1n} \\\\\n\\vdots & \\ddots & \\vdots \\\\\na_{m1} & \\cdots & a_{mn} \n\\end{bmatrix}\n$$\nSecondo questa notazione l'elemento di valore 3 della tabella precedente sarà l'elemento $a_{12}$. \nOgni elemento quindi può essere identificato da una riga e una colonna.\n##Spazio delle righe e delle colonne\nGuardando la tabella, guardando le righe, ogni riga è una n-upla. Quindi vedendo ogni riga come un vettore queste generano uno spazio vettoriale in $R^n$. \nAllo stesso modo le colonne, vista ognuna come un vettore, generano un'altro spazio vettoriale questa volta sottospazio di $R^m$. \nPer esempio data la matrice:\n$$\nA = \n\\begin{bmatrix}\n1 & 1 & 1 \\\\\n2 & 1 & 0\n\\end{bmatrix}\n$$\n*Spazio delle righe*\n$$\nr_0 = (1, 1, 1) \\\\\nr_1 = (2, 1, 0) \\\\\n\\subseteq R^3\n$$\n*Spazio delle colonne*\n$$\nc_1 = (1, 2) \\\\\nc_2 = (1, 1) \\\\\nc_3 = (1, 0) \\\\\n\\subseteq R^2\n$$\nQuindi una stessa matrice può dare origini a spazi di righe e colonne molto diversi.\n#Rango di una matrice\nQuando lavoro con una matrice posso identificare la dimensione degli spazi delle righe e degli spazi delle colonne. Questi coincidono e coincidono anche con il rango della matrice stessa.\n$$\n\\dim{L(R_1, \\dots, R_m)} \\\\\n= \\\\\n\\dim{L(C_1, \\dots, C_n)} \\\\\n= \\\\\n\\text{Rango di }A = \\rho(A)\n$$\nData la matrice;\n$$\nA = \n\\begin{pmatrix}\n1 & 2 & 1 \\\\\n0 & 1 & 3 \\\\\n\\end{pmatrix}\n$$\nSpazio delle righe\n$$\nR_1 = (1, 2, 1) \\\\\nR_2 = (0 ,1, 3) \\\\\nl.i \\Rightarrow \\dim{L(R_1, R_2)} = 2 \\\\\n\\rho(A) = 2\n$$\nSpazio delle colonne\n$$\nC_1 = (1, 0) \\\\\nC_2 = (2, 1) \\\\\nC_3 = (1, 3) \\\\\n\\dim{L(C_1, C_2, C_3)} = 2 \\\\\n\\rho(A) = 2\n$$\nQuesto modo di procedere per quanto semplice non è ottimale man mano che la matrice cresce di dimensioni. \n$$\nA = \n\\begin{pmatrix}\n1 & 2 & 1 \\\\\n0 & 1 & 3 \\\\\n0 & 5 & 0 \\\\\n\\end{pmatrix}\n$$\nQuesta matrice è gia più complessa ma posso notare facilmente che\n * La prima riga non è nulla\n * La seconda riga, avendo uno 0 dove la prima ha un 1, non può essere multipla della prima.\n * Lo stesso vale per la terza riga.\n \nLa presenza di 0 in posizioni strategiche permette di capire facilmente quando due vettori sono indipendenti e di conseguenza capire la dimensione dello spazio vettoriale e di conseguenza del campo della matrice. \n##Matrici ridotte per righe\n$$\nA = \n\\begin{pmatrix}\n\\diamond & \\square & \\diamond & \\diamond & \\diamond \\\\\n\\square & 0 & \\diamond & \\diamond & \\diamond \\\\\n0 & 0 & \\square & \\diamond & \\diamond \\\\\n0 & 0 & 0 & \\diamond & \\square \\\\\n0 & 0 & 0 & \\diamond & 0 \\\\\n\\end{pmatrix} \\\\\n\\begin{align}\n\\square & = \\text{elemento speciale != 0} \\\\\n\\diamond & = \\text{elemento qualsiasi}\\\\\n0 & = \\text{zero}\n\\end{align}\n$$\nI numeri speciali sono quei numeri sotto i quali, nella stessa colonna, si trovono solo 0. \nUna matrice di questi tipo ha un rango pari il numero delle righe non nulle. \n\nIl medesimo ragionamento può essere fatto per le colonne.\n$$\nA = \n\\begin{pmatrix}\n\\diamond & \\square & 0 & 0 & 0 \\\\\n\\square & 0 & 0 & 0 & 0 \\\\\n\\diamond & \\diamond & \\square & 0 & 0 \\\\\n\\diamond & \\diamond & \\diamond & \\diamond & \\diamond \\\\\n\\diamond & \\diamond & \\diamond & \\square & 0 \\\\\n\\end{pmatrix} \\\\\n$$\n\nIl problema è che raramente le matrici su cui lavorare sono ridotte per righe o per colonne. \nDevo cercare quindi un'operazione che mi permette di trovare una matrice $A^1$ ridotta che abbia lo stesso rango della matrice di origine. \nMi servno delle operazioni che conservano il rango della matrice. \n#Trasformazione elementare (sulle righe)\n 1. Moltiplicazione di una riga\nPosso moltiplicare tutti i valori di una riga per un valore $a \\neq 0$ e il rango della matrice non cambia.\n 2. Scambiare di posto le righe\nPosso scambare di posto la riga $R_i$ e la righa $R_j$ con $i \\neq j$ e il rango della matrica non cambia\n 3. Somma al multiplo\nPosso prendere una riga $R_i$ e una riga $R_j$ con $i \\neq j$. \nQuindi sostituire la riga $R_i$ con una nuova riga alla quale sommo a ogni valore di $R_i$ i valori di $R_j$ moltiplicati per un $a \\neq 0$. \nAnche in questo caso il rango non cambia\n\n###Esempio delle operazioni\n$$\nA = \n\\begin{pmatrix}\n1 & 1 & 1 \\\\\n2 & 1 & 1 \\\\\n3 & 1 & -1 \n\\end{pmatrix}\n\\rightarrow R_2 - 1R_1 \\\\ \\rightarrow \n\\begin{pmatrix}\n1 & 1 & 1 \\\\\n1 & 0 & 0 \\\\\n3 & 1 & -1 \n\\end{pmatrix} \n\\rightarrow R_3 + R_1 \\\\ \\rightarrow \n\\begin{pmatrix}\n1 & 1 & 1 \\\\\n1 & 0 & 0 \\\\\n4 & 2 & 0 \n\\end{pmatrix} \n\\rightarrow R_3 - 4R_2 \\\\ \\rightarrow \n\\begin{pmatrix}\n1 & 1 & 1 \\\\\n1 & 0 & 0 \\\\\n0 & 2 & 0 \n\\end{pmatrix} \n\\rightarrow \\text{ Matrice ridotta per righe } \\rho(a) = 3\n$$\n\nTutto questo vale anche per le colonne. \n\n##Applicazione agli spazi vettoriali\nCreando una matrice che ha come righe i generatori di uno spazio vettoriale e calcolando il rango della matrice in realtà sto calcolando la dimensione dello spazio vettoriale dato dai generatori utilizzati. \nDato uno spazio vettoriale generato da:\n$$\nR_0 = (1, 1, 2, 1) \\\\\nR_1 = (2, 1, 0, 3) \\\\\nR_3 = (4, 4, 1, 0) \\\\\n$$\nGenero la matrice:\n$$\n\\begin{pmatrix}\n1 & 1 & 2 & 1 \\\\\n2 & 1 & 0 & 3 \\\\\n4 & 4 & 1 & 0 \n\\end{pmatrix}\n$$\nTramite le trasformazioni elementari la riduco\n$$\n\\begin{pmatrix}\n1 & 1 & 2 & 1 \\\\\n2 & 1 & 0 & 3 \\\\\n4 & 4 & 1 & 0 \n\\end{pmatrix} \\\\\n\\downarrow \\\\\n\\begin{pmatrix}\n1 & 1 & 2 & 1 \\\\\n2 & 1 & 0 & 3 \\\\\n7 & 7 & 0 & -1 \n\\end{pmatrix} \\\\\n\\downarrow \\\\\n\\begin{pmatrix}\n1 & 1 & 2 & 1 \\\\\n2 & 1 & 0 & 3 \\\\\n-7 & 0 & 0 & -22 \\\\ \n\\end{pmatrix} \\\\\n$$\nMatrice di rango 3, quindi lo spazio vettoriale è di dimensione 3\n\n", "meta": {"hexsha": "69e212c132d01490a92be46ec8889941e3c747ef", "size": 9344, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Algebra 20 Matrici 1 rango e riduzione.ipynb", "max_stars_repo_name": "pscamodio/appunti_algebra", "max_stars_repo_head_hexsha": "0ad0a47a743d996dd7710b6430fc10dcd40d0805", "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": "Algebra 20 Matrici 1 rango e riduzione.ipynb", "max_issues_repo_name": "pscamodio/appunti_algebra", "max_issues_repo_head_hexsha": "0ad0a47a743d996dd7710b6430fc10dcd40d0805", "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": "Algebra 20 Matrici 1 rango e riduzione.ipynb", "max_forks_repo_name": "pscamodio/appunti_algebra", "max_forks_repo_head_hexsha": "0ad0a47a743d996dd7710b6430fc10dcd40d0805", "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": 39.2605042017, "max_line_length": 225, "alphanum_fraction": 0.4724957192, "converted": true, "num_tokens": 2389, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625012602594, "lm_q2_score": 0.931462512200114, "lm_q1q2_score": 0.8676224014440831}} {"text": "# Homework 1: Solving an ODE\n\nGiven an ordinary differential equation:\n\n$$\n\\frac{d}{dt}x(t) = cos(t)\n$$\n\nwith initial condition $x(0)=0.0$\n\n## Part 1: Julia's ODE solver\n\nPlease **solve** the ODE using `DifferentialEquations.jl` for $t \\in [0.0, 4 \\pi]$ and **plot** the time series. **Compare** it to the analytical solution *in one plot*.\n\n## Part 2: The forward Euler method\n\nPlease **try** a range of dts to **solve** the ODE using the (home-made) forward Euler method for $t \\in [0.0, 4 \\pi]$, **plot** the time series, and **compare** them to the analytical solution *in one plot*.\n\n**About the math**\n\nWe treat the solution curve as a straight line locally. In each step, the next state variables ($\\vec{u}_{n+1}$) is accumulated by time step (dt) multiplied the derivative (tangent slope) at the current state ($\\vec{u}_{n}$):\n\n$$ \n\\vec{u}_{n+1} = \\vec{u}_{n} + dt \\cdot f(\\vec{u}_{n}, t_{n})\n$$\n\n\n```julia\n# The ODE model. Exponential decay in this example\n# The input/output format is compatible to Julia DiffEq ecosystem AND YOU SHOULD KEEP IT.\nmodel(u, p, t) = cos(t)\n\n# Forward Euler stepper \nstep_euler(model, u, p, t, dt) = u .+ dt .* model(u, p, t)\n\n# In house ODE solver\nfunction mysolve(model, u0, tspan, p; dt=0.1, stepper=step_euler)\n # Time points\n ts = tspan[1]:dt:tspan[end]\n # State variable at those time points\n us = zeros(length(ts), length(u0))\n # Initial conditions\n us[1, :] .= u0\n # Iterations\n for i in 1:length(ts)-1\n us[i+1, :] .= stepper(model, us[i, :], p, ts[i], dt)\n end\n # Results\n return (t = ts, u = us)\nend\n\ntspan = (0.0, 4.0π)\np = nothing\nu0 = 0.0\n\nsol = mysolve(model, u0, tspan, p, dt=0.2, stepper=step_euler)\n\n# Visualization\nusing Plots\nPlots.gr(lw=2)\n\n# Numerical solution\nplot(sol.t, sol.u, label=\"FE method\")\nplot!(sin, tspan..., label = \"Analytical solution\", linestyle=:dash)\n```\n\n## Part 3: The RK4 method\n\n1. Please **try** a range of dts to **solve** the ODE using the (home-made) fourth order Runge-Kutta ([RK4](https://en.wikipedia.org/wiki/Runge%E2%80%93Kutta_methods)) method for $t \\in [0.0, 4 \\pi]$, **plot** the time series, and **compare** them to the analytical solution *in one plot*.\n2. Compared to the forward Eular method, which one is more efficient in terms of \ntime step needed for the same accuracy? You could make a visual comparison by plotting the analytical and numerical solutions together. \n\n**About the math**\n\nWe use more steps to eliminate some of the nonlinear terms of error. In each iteration, the next state is calculated in 5 steps.\n\n$$\n\\begin{align}\nk_1 &= dt \\cdot f(\\vec{u}_{n}, t_n) \\\\\nk_2 &= dt \\cdot f(\\vec{u}_{n} + 0.5k_1, t_n + 0.5dt) \\\\\nk_3 &= dt \\cdot f(\\vec{u}_{n} + 0.5k_2, t_n + 0.5dt) \\\\\nk_4 &= dt \\cdot f(\\vec{u}_{n} + k_3, t_n + dt) \\\\\nu_{n+1} &= \\vec{u}_{n} + \\frac{1}{6}(k_1 + 2k_2 + 2k_3 + k_4)\n\\end{align}\n$$\n\nHint: replace the Euler stepper with the RK4 one\n\n```julia\n# Forward Euler stepper \nstep_euler(model, u, p, t, dt) = u .+ dt .* model(u, p, t)\n# Your RK4 version\nstep_rk4(model, u, p, t, dt) = \"\"\"TODO\"\"\"\n```\n", "meta": {"hexsha": "5594f6be23e94d8ba0001269488be63e4dad57ff", "size": 4615, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "docs/hw/hw-01.ipynb", "max_stars_repo_name": "NTUMitoLab/mmsb-bebi-5009", "max_stars_repo_head_hexsha": "5ab98e5a11bc3c1e5c4df1aab9ab94f05acc4062", "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/hw/hw-01.ipynb", "max_issues_repo_name": "NTUMitoLab/mmsb-bebi-5009", "max_issues_repo_head_hexsha": "5ab98e5a11bc3c1e5c4df1aab9ab94f05acc4062", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 25, "max_issues_repo_issues_event_min_datetime": "2021-10-04T14:28:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-15T08:29:54.000Z", "max_forks_repo_path": "docs/hw/hw-01.ipynb", "max_forks_repo_name": "ntumitolab/mmsb-bebi-5009", "max_forks_repo_head_hexsha": "813610f812b23970f26d473e55e33fc0088e7d9f", "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.9642857143, "max_line_length": 300, "alphanum_fraction": 0.5271939328, "converted": true, "num_tokens": 1033, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533032291501, "lm_q2_score": 0.9304582497090322, "lm_q1q2_score": 0.8676088684580004}} {"text": "# Vector operators in Cartesian coordinates\n\n``continuum_mechanics`` support major vector operators such as:\n\n- gradient of a scalar function;\n\n- divergence of a vector function;\n\n- curl of a vector function;\n\n- gradient of a vector function;\n\n- divergence of a tensor;\n\n- Laplace operator of a scalar function;\n\n- Laplace operator of a vector function; and\n\n- Biharmonic operator of a scalar function.\n\nAll these operators are in the module `vector`.\n\n\n```python\nfrom sympy import *\nfrom continuum_mechanics import vector\n```\n\nBy default Cartesian coordinates are given by $x$, $y$ and $z$.\nIf these coordinates are used there is not necessary to specify\nthem when calling the vector operators\n\n\n```python\ninit_printing()\nx, y, z = symbols(\"x y z\")\n```\n\nFollowing, we have some examples of vector operators in Cartesian coordinates.\n\n## Gradient of a scalar function\n\nThe gradient takes as input a scalar and returns a vector,\nrepresented by a 3 by 1 matrix.\n\n\n```python\nf = 2*x + 3*y**2 - sin(z)\nf\n```\n\n\n```python\nvector.grad(f)\n```\n\n## Divergence of a vector function\n\nThe divergence takes as input a vector (represented by a 3 by 1 matrix) and returns a scalar.\n\n\n```python\nvector.div(Matrix([x, y, z]))\n```\n\n\n```python\nvector.div(Matrix([\n x**2 + y*z,\n y**2 + x*z,\n z**2 + x*y]))\n```\n\n## Divergence of a tensor function\n\nThe divergence of a tensor (represented by a 3 by 3 matrix)\nreturns a vector.\n\n\n```python\nAxx, Axy, Axz = symbols(\"A_xx A_xy A_xz\", cls=Function)\nAyx, Ayy, Ayz = symbols(\"A_yx A_yy A_yz\", cls=Function)\nAzx, Azy, Azz = symbols(\"A_zx A_zy A_zz\", cls=Function)\n```\n\n\n```python\ntensor = Matrix([\n [Axx(x, y, z), Axy(x, y, z), Axz(x, y, z)],\n [Ayx(x, y, z), Ayy(x, y, z), Ayz(x, y, z)],\n [Azx(x, y, z), Azy(x, y, z), Azz(x, y, z)]])\ntensor\n```\n\n\n```python\nvector.div_tensor(tensor)\n```\n\n## Curl of a vector function\n\nLet us check the identity\n\n$$\\nabla \\times \\nabla f(x, y, z) = \\mathbf{0}\\, .$$\n\n\n```python\nfun = symbols(\"fun\", cls=Function)\nvector.curl(vector.grad(fun(x, y, z)))\n```\n", "meta": {"hexsha": "91913e42612ae2f25b3e794d6e49914a183a241b", "size": 21418, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "docs/cartesian_coordinates.ipynb", "max_stars_repo_name": "nicoguaro/continuum_mechanics", "max_stars_repo_head_hexsha": "f8149b69b8461784f6ed721294cd1a49ffdfa3d7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 21, "max_stars_repo_stars_event_min_datetime": "2018-12-09T15:02:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-16T09:28:38.000Z", "max_issues_repo_path": "docs/cartesian_coordinates.ipynb", "max_issues_repo_name": "nicoguaro/continuum_mechanics", "max_issues_repo_head_hexsha": "f8149b69b8461784f6ed721294cd1a49ffdfa3d7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 223, "max_issues_repo_issues_event_min_datetime": "2019-05-06T16:31:50.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T21:21:03.000Z", "max_forks_repo_path": "docs/cartesian_coordinates.ipynb", "max_forks_repo_name": "nicoguaro/continuum_mechanics", "max_forks_repo_head_hexsha": "f8149b69b8461784f6ed721294cd1a49ffdfa3d7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2020-01-29T10:03:52.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-25T19:34:37.000Z", "avg_line_length": 56.5118733509, "max_line_length": 4756, "alphanum_fraction": 0.7320011206, "converted": true, "num_tokens": 602, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9648551525886194, "lm_q2_score": 0.8991213840277783, "lm_q1q2_score": 0.8675219001818127}} {"text": "# Neural Networks - Representation\n\n## 1. Model Representation\n\nNeural Networks were developed as simulating networks of neurons in the brain. So, to start understanding the representation of these hypotheses, let's start by understanding how a single neuron in the brain works: \n\n\n\nThe components of the neuron are:\n\n- A cell body;\n- Input wires (dendrites);\n- Output wire (axon).\n\nThe axon often goes to the dendrites of other neurons, forming a network.\n\nThe neurons communicate via pulses of electricity.\n\n### Neuron model: Logistic unit\n\nGiven the above, we're going to use a very simple model of the neuron:\n\n\n\nwhere \n\n$$\nh_{\\theta}(x) = \\frac{1}{1 + e^{-\\theta^T x}} = g(\\theta^T x)\n$$\n\nwith $x=[x_0 \\quad x_1 \\quad x_2 \\quad x_3]^T$ and $\\theta=[\\theta_0 \\quad \\theta_1 \\quad \\theta_2 \\quad \\theta_3]^T$.\n\nHere, we are using the sigmoid (logistic) function as the **activation function**. Other functions such as $\\tanh(\\cdot)$ or $\\mathrm{ReLU(\\cdot)}=\\max\\{0, \\cdot\\}$ are also used often.\n\n### Neural network\n\nA neural networks is a group of these neurons acting together:\n\n\n\nIn this network:\n\n- $a_i^{(j)}$ is the activation of unit $i$ in layer $j$.\n- $\\Theta^{(j)}$ is the matrix of weights controlling function mapping from layer $j$ to layer $j+1$.\n\nThus:\n\n\\begin{align}\na_1^{(2)} &= g(\\Theta_{10}^{(1)} x_0 + \\Theta_{11}^{(1)} x_1 + \\Theta_{12}^{(1)} x_2 + \\Theta_{13}^{(1)} x_3) \\\\\na_2^{(2)} &= g(\\Theta_{20}^{(1)} x_0 + \\Theta_{21}^{(1)} x_1 + \\Theta_{22}^{(1)} x_2 + \\Theta_{23}^{(1)} x_3) \\\\\na_3^{(2)} &= g(\\Theta_{30}^{(1)} x_0 + \\Theta_{31}^{(1)} x_1 + \\Theta_{32}^{(1)} x_2 + \\Theta_{33}^{(1)} x_3) \\\\\n& \\\\\nh_{\\Theta}(x) &= a_1^{(3)} = g(\\Theta_{10}^{(3)} a_0^{(2)} + \\Theta_{11}^{(2)} a_1^{(2)} + \\Theta_{32}^{(2)} a_2^{(2)} + \\Theta_{33}^{(2)} a_3^{(2)})\n\\end{align}\n\nIn this setting $\\Theta^{(1)} \\in \\mathbb{R}^{3 \\times 4}$ and $\\Theta^{(2)} \\in \\mathbb{R}^{1 \\times 4}$.\n\nIn general, if a network has $s_j$ units in layer $j$, and $s_{j+1}$ units in layer $j+1$, then $\\Theta^{(j)}$ will be of dimension $s_{j+1} \\times (1 + s_j)$.\n\nIn the above setting, we can define intermediate variables \n\n$$\nz^{(j+1)}_i = \\Theta_{i0}^{(j)} a_0^{(j)} + \\Theta_{i1}^{(j)} a_1^{(j)} + \\Theta_{i2}^{(j)} a_2^{(j)} + \\Theta_{i3}^{(j)} a_3^{(j)},\n$$\n\nand in terms of $z^{(j+1)}_i$ we can define $a^{(j+1)}_i$ as:\n\n$$\na^{(j+1)}_i = g(z^{(j+1)}_i).\n$$\n\nMoreover, we can write the above in a vectorized efficient form as:\n\n\\begin{align}\na^{(1)} = x\\\\\nz^{(2)} &= \\Theta^{(1)} \\left[\\begin{array}{c} 1 \\\\ a^{(1)} \\end{array}\\right] \\\\\na^{(2)} &= g(z^{(2)}) \\\\\nz^{(3)} &= \\Theta^{(2)} \\left[\\begin{array}{c} 1 \\\\ a^{(2)} \\end{array}\\right] \\\\\na^{(3)} &= g(z^{(3)}).\n\\end{align}\n\nwhere\n\n$$\nx = \\left[\\begin{array}{c} x_1 \\\\ x_2 \\\\ x_3 \\end{array}\\right], \\qquad z^{(2)} = \\left[\\begin{array}{c} z^{(2)}_1 \\\\ z^{(2)}_2 \\\\ z^{(2)}_3 \\end{array}\\right], \\qquad a^{(2)} = \\left[\\begin{array}{c} a^{(2)}_1 \\\\ a^{(2)}_2 \\\\ a^{(2)}_3 \\end{array}\\right], \\qquad z^{(3)} = z^{(3)}_1, \\qquad a^{(3)} = a^{(3)}_1,\n$$\n\nand\n\n$$\n\\Theta^{(1)} = \\left[\n\\begin{array}{cccc}\n\\Theta_{10}^{(1)} & \\Theta_{11}^{(1)} & \\Theta_{12}^{(1)} & \\Theta_{13}^{(1)} \\\\\n\\Theta_{20}^{(1)} & \\Theta_{21}^{(1)} & \\Theta_{22}^{(1)} & \\Theta_{23}^{(1)} \\\\\n\\Theta_{30}^{(1)} & \\Theta_{31}^{(1)} & \\Theta_{32}^{(1)} & \\Theta_{33}^{(1)} \n\\end{array}\\right],\n\\qquad \n\\Theta^{(2)} = \\left[\n\\begin{array}{cccc}\n\\Theta_{10}^{(2)} & \\Theta_{11}^{(2)} & \\Theta_{12}^{(2)} & \\Theta_{13}^{(2)} \n\\end{array}\\right],\n$$\n\nThis algorithm is called **forward propagation**.\n\n\n\n
\nCreated with Jupyter by Esteban Jiménez Rodríguez. Based on the content of the Machine Learning course offered through coursera by Prof. Andrew Ng.\n
\n", "meta": {"hexsha": "1a036e82ff8f469886394e62cd96a99003b52619", "size": 6695, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Week4/2NeuralNetworksRepresentation.ipynb", "max_stars_repo_name": "esjimenezro/ml_course", "max_stars_repo_head_hexsha": "5967489aeda57451228014df13c30ca356c79b84", "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": "Week4/2NeuralNetworksRepresentation.ipynb", "max_issues_repo_name": "esjimenezro/ml_course", "max_issues_repo_head_hexsha": "5967489aeda57451228014df13c30ca356c79b84", "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": "Week4/2NeuralNetworksRepresentation.ipynb", "max_forks_repo_name": "esjimenezro/ml_course", "max_forks_repo_head_hexsha": "5967489aeda57451228014df13c30ca356c79b84", "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": 31.1395348837, "max_line_length": 349, "alphanum_fraction": 0.483793876, "converted": true, "num_tokens": 1476, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.960361157495521, "lm_q2_score": 0.9032942125614059, "lm_q1q2_score": 0.8674886755344768}} {"text": "# Systems of Equations\nImagine you are at a casino, and you have a mixture of £10 and £25 chips. You know that you have a total of 16 chips, and you also know that the total value of chips you have is £250. Is this enough information to determine how many of each denomination of chip you have?\n\nWell, we can express each of the facts that we have as an equation. The first equation deals with the total number of chips - we know that this is 16, and that it is the number of £10 chips (which we'll call ***x*** ) added to the number of £25 chips (***y***).\n\nThe second equation deals with the total value of the chips (£250), and we know that this is made up of ***x*** chips worth £10 and ***y*** chips worth £25.\n\nHere are the equations\n\n\\begin{equation}x + y = 16 \\end{equation}\n\\begin{equation}10x + 25y = 250 \\end{equation}\n\nTaken together, these equations form a *system of equations* that will enable us to determine how many of each chip denomination we have.\n\n## Graphing Lines to Find the Intersection Point\nOne approach is to determine all possible values for x and y in each equation and plot them.\n\nA collection of 16 chips could be made up of 16 £10 chips and no £25 chips, no £10 chips and 16 £25 chips, or any combination between these.\n\nSimilarly, a total of £250 could be made up of 25 £10 chips and no £25 chips, no £10 chips and 10 £25 chips, or a combination in between.\n\nLet's plot each of these ranges of values as lines on a graph:\n\n\n```R\nlibrary(ggplot2)\nlibrary(repr)\noptions(repr.plot.width=4, repr.plot.height=4)\n\n## Create a data frames with the extreems of the possible values of chips\nchips = data.frame(x = c(16,0), y = c(0,16))\n\n## A second data frame with the extreems of the values of the chips\nvalues = data.frame(x = c(25,0), y = c(0,10))\n\nggplot() + geom_line(data = chips, aes(x,y), color = 'blue', size = 1) +\n geom_line(data = values, aes(x,y), color = 'orange', size = 1)\n```\n\nLooking at the graph, you can see that there is only a single combination of £10 and £25 chips that is on both the line for all possible combinations of 16 chips and the line for all possible combinations of £250. The point where the line intersects is (10, 6); or put another way, there are ten £10 chips and six £25 chips.\n\n### Solving a System of Equations with Elimination\nYou can also solve a system of equations mathematically. Let's take a look at our two equations:\n\n\\begin{equation}x + y = 16 \\end{equation}\n\\begin{equation}10x + 25y = 250 \\end{equation}\n\nWe can combine these equations to eliminate one of the variable terms and solve the resulting equation to find the value of one of the variables. Let's start by combining the equations and eliminating the x term.\n\nWe can combine the equations by adding them together, but first, we need to manipulate one of the equations so that adding them will eliminate the x term. The first equation includes the term ***x***, and the second includes the term ***10x***, so if we multiply the first equation by -10, the two x terms will cancel each other out. So here are the equations with the first one multiplied by -10:\n\n\\begin{equation}-10(x + y) = -10(16) \\end{equation}\n\\begin{equation}10x + 25y = 250 \\end{equation}\n\nAfter we apply the multiplication to all of the terms in the first equation, the system of equations look like this:\n\n\\begin{equation}-10x + -10y = -160 \\end{equation}\n\\begin{equation}10x + 25y = 250 \\end{equation}\n\nNow we can combine the equations by adding them. The ***-10x*** and ***10x*** cancel one another, leaving us with a single equation like this:\n\n\\begin{equation}15y = 90 \\end{equation}\n\nWe can isolate ***y*** by dividing both sides by 15:\n\n\\begin{equation}y = \\frac{90}{15} \\end{equation}\n\nSo now we have a value for ***y***:\n\n\\begin{equation}y = 6 \\end{equation}\n\nSo how does that help us? Well, now we have a value for ***y*** that satisfies both equations. We can simply use it in either of the equations to determine the value of ***x***. Let's use the first one:\n\n\\begin{equation}x + 6 = 16 \\end{equation}\n\nWhen we work through this equation, we get a value for ***x***:\n\n\\begin{equation}x = 10 \\end{equation}\n\nSo now we've calculated values for ***x*** and ***y***, and we find, just as we did with the graphical intersection method, that there are ten £10 chips and six £25 chips.\n\nYou can run the following R code to verify that the equations are both true with an ***x*** value of 10 and a ***y*** value of 6.\n\n\n```R\nx = 10\ny = 6\nprint((x + y == 16) & ((10*x) + (25*y) == 250))\n```\n\n [1] TRUE\n\n", "meta": {"hexsha": "e220b514236918aa181f5588a46ec453afa2589c", "size": 12961, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "R/Module01/01-03-Systems of Equations.ipynb", "max_stars_repo_name": "joelgenter/Essential-Math", "max_stars_repo_head_hexsha": "2e76546a82fb0ad2b8698c7dc0f48f0aad0762bb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 33, "max_stars_repo_stars_event_min_datetime": "2018-01-11T20:44:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T16:10:41.000Z", "max_issues_repo_path": "R/Module01/01-03-Systems of Equations.ipynb", "max_issues_repo_name": "joelgenter/Essential-Math", "max_issues_repo_head_hexsha": "2e76546a82fb0ad2b8698c7dc0f48f0aad0762bb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2018-11-19T23:54:27.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-20T00:15:39.000Z", "max_forks_repo_path": "R/Module01/01-03-Systems of Equations.ipynb", "max_forks_repo_name": "joelgenter/Essential-Math", "max_forks_repo_head_hexsha": "2e76546a82fb0ad2b8698c7dc0f48f0aad0762bb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 35, "max_forks_repo_forks_event_min_datetime": "2018-03-08T15:42:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-03T06:11:43.000Z", "avg_line_length": 84.1623376623, "max_line_length": 6668, "alphanum_fraction": 0.7798009413, "converted": true, "num_tokens": 1239, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.927363293639213, "lm_q2_score": 0.9353465102920899, "lm_q1q2_score": 0.8674060204784165}} {"text": "Lagrange's work on Kepler equation suggests that an equation of the form \n\\begin{equation}\ny=x+\\alpha \\phi(y)\n\\end{equation}\nIts solution is approximated by the series expansion:\n\\begin{equation}\ny=x+\\sum_{n=1}^{\\infty} \\frac{\\alpha^{n}}{n !} \\frac{d^{n-1}}{d x^{n-1}} \\phi(x)^{n}\n\\end{equation}\n\n\n```python\nimport numpy as np # calculations\nimport pathlib # needed to create folder\nimport matplotlib.pyplot as plt # needed for graphs\nimport sympy as sp\nfrom sympy.abc import E, e, n, M, o\n```\n\nKepler's equation is \n\\begin{equation}\nE=M+e \\sin E\n\\end{equation}\nIts solution is approximated by the series expansion:\n\\begin{equation}\ny=M+\\sum_{n=1}^{\\infty} \\frac{e^{n}}{n !} \\frac{d^{n-1}}{d E^{n-1}} \\sin(M)^{n}\n\\end{equation}\nWe plan to evaluate the series expression E(M) up to order n=3 and n=10 for eccentrities e=0.3 and e=0.9.\n\nWe're using python's package Sympy to do our symbolic interpretation.\nFrom sympy.abc we're importing these symbols. Their usage is:\nE = Eccentric anomaly of Kepler's Equation\nM = Mean Anomaly of Kepler's Equation\ne = Eccentricity\nn = index of summation\no = upper bound of summation\n\nSome starting setup\n\n\n```python\ndpisiz=100\ndef savim(dir,name):\n path = pathlib.Path(f\"./{dir}\")\n path.mkdir(exist_ok=True,parents=True)\n plt.savefig(f'./{dir}/{name}.png',dpi=dpisiz)\n```\n\n\n\n\n```python\nfract = e ** n / sp.factorial(n)\nfunc = (sp.sin(M)) ** n\ndif_func = (sp.Derivative(func, (M, n - 1)))\nsumo = sp.Sum(fract * dif_func, (n, 1, o))\nsum3 = (sumo.subs(o, 3)).doit() #The form asked for n=3. Could add .simplify() as well\nsum10 = (sumo.subs(o, 10)).doit() #The form asked for n=3. Could add .simplify() as well\nE3 = sum3 + M\nE10 = sum10 + M\nEn3_e3 = sp.trigsimp(E3.subs(e, 0.3))\nEn10_e3 = sp.trigsimp(E10.subs(e, 0.3))\nEn3_e9 = sp.trigsimp(E3.subs(e, 0.9))\nEn10_e9 = sp.trigsimp(E10.subs(e, 0.9))\n```\n\nUse sp.lambdify to create our lambda functions and plot our graphs.\nCould have used sp.plot but I prefer having more options with matplotlib.\n\n\n```python\n\nnumberoftries = 10000\nxx = np.linspace(0, 2 * np.pi, 10000)\nEn3_e3f = sp.lambdify(M, En3_e3)(xx)\nEn10_e3f = sp.lambdify(M, En10_e3)(xx)\nEn3_e9f = sp.lambdify(M, En3_e9)(xx)\nEn10_e9f = sp.lambdify(M, En10_e9)(xx)\n\nfig = plt.figure()\nax = plt.axes()\n\n\ndata = np.genfromtxt(fname=\"data.csv\", delimiter=',') #Importing data from task 1\nax.set_ylabel('E')\nax.set_xlabel('M')\nax.plot(data[:, 0], data[:, 2], label='E for e=0.3', color='tab:pink')\nax.plot(xx, En3_e3f, label='E for n=3, e=0.3', linestyle='dashed', color='tab:red')\nax.plot(xx, En10_e3f, label='E for n=10, e=0.3', linestyle='dotted', color='tab:blue')\nax.legend()\nsavim('pr1_task2','e_03')\nfig1 = plt.figure()\nax1 = plt.axes()\nax1.plot(data[:, 0], data[:, 5], label='E for e=0.9', color='black' )\nax1.plot(xx, En3_e9f, label='E for n=3, e=0.9', color='tan')\nax1.plot(xx, En10_e9f, label='E for n=10, e=0.9', color='fuchsia')\nax1.legend()\nax1.set_ylabel('E')\nax1.set_xlabel('M')\nsavim('pr1_task2','e_09')\n```\n\nAs we can see from our results, for lower eccentricities both n=3 and n=10 are nearly identical compared to the Newton-Raphson method.\nHowever, for 0.9, this is no longer the case. In this case there are some sinusoidal curves appearing except the middle of the curve (There are still some curvature showing at the middle, however it's close to the Newton-Raphson method).\n\nRegarding the form \\begin{equation}\nE=M+\\sum_{n} \\Pi_{n}(e) \\sin (n M)\n\\end{equation}\nLagrange's theorem states that for any f\n\\begin{equation}\n\\begin{aligned}\nf(y)=f(z) &+\\frac{x}{1 !} F(z) f^{\\prime}(z) \\\\\n&+\\frac{x^{2}}{2 !} \\frac{d}{d z}\\left[\\{F(z)\\}^{2} f^{\\prime}(z)\\right] \\\\\n&+\\frac{x^{3}}{3 !} \\frac{d^{2}}{d z^{2}}\\left[\\{F(z)\\}^{3} f^{\\prime}(z)\\right] \\\\\n&+\\cdots \\\\\n&+\\frac{x^{n}}{n !} \\frac{d^{n-1}}{d z^{n-1}}\\left[\\{F(z)\\}^{n} f^{\\prime}(z)\\right] \\\\\n&+\\cdots\n\\end{aligned}\n\\end{equation}\nApplying the above theorem to Kepler's equation\n\\begin{equation}\nE=M+e \\sin E\n\\end{equation}\nit yields\n\\begin{equation}\n\\begin{aligned}\nE=M+e \\sin M &+\\frac{e^{2}}{2 !} \\frac{d}{d M}\\left[\\sin ^{2} M\\right]+\\frac{e^{3}}{3 !} \\frac{d^{2}}{d M^{2}}\\left[\\sin ^{3} M\\right]+\\frac{e^{4}}{4 !} \\frac{d^{3}}{d M^{3}}\\left[\\sin ^{4} M\\right]+\\cdots \\\\\n&+\\frac{e^{n}}{n !} \\frac{d^{n-1}}{d M^{n-1}}\\left[\\sin ^{n} M\\right]+\\cdots\n\\end{aligned}\n\\end{equation}\nNeglecting higher orders of derivatives\n\\begin{equation}\n\\begin{aligned}\n\\frac{d}{d M} \\sin ^{2} M &=2 \\cos M \\sin M=\\sin 2 M \\\\\n\\frac{d^{2}}{d M^{2}} \\sin ^{3} M &=6 \\cos ^{2} M \\sin M-3 \\sin ^{3} M=\\frac{1}{4}(9 \\sin 3 M-3 \\sin M) \\\\\n&=\\frac{1}{2^{2}}\\left(3^{3} \\sin 3 M-3 \\sin M\\right) \\\\\n\\frac{d^{3}}{d M^{3}} \\sin ^{4} M &=24 \\cos ^{3} M \\sin M-40 \\cos M \\sin ^{3} M=8 \\sin 4 M-4 \\sin 2 M \\\\\n&=\\frac{1}{2^{3}}\\left(4^{3} \\sin 4 M-2^{3} \\cdot 4 \\sin 2 M\\right) \\\\\n\\frac{d^{4}}{d M^{4}} \\sin ^{5} M &=120 \\cos ^{4} M \\sin M-440 \\cos ^{2} M \\sin ^{3} M+65 \\operatorname{coin}^{5} M \\\\\n&=\\frac{1}{16}(625 \\sin 5 M-405 \\sin 3 M+10 \\sin M) \\\\\n&=\\frac{1}{2^{4}}\\left(5^{4} \\sin 5 M-3^{4} \\cdot 5 \\sin 3 M+10 \\sin M\\right) \\\\\n\\frac{d^{5}}{d M^{5}} \\sin ^{6} M &=720 \\cos ^{5} M \\sin M-4800 \\cos ^{3} M \\sin ^{3} M+2256 \\cos M \\sin ^{5} M \\\\\n&=243 \\sin 6 M-192 \\sin 4 M+15 \\sin 2 M \\\\\n&=\\frac{1}{2^{5}}\\left(6^{5} \\sin 6 M-4^{5} \\cdot 6 \\sin 4 M+2^{5} \\cdot 15 \\cos 2 M\\right)\n\\end{aligned}\n\\end{equation}\nInserting the above derivatives to our series expression we get\n\\begin{equation}\n\\begin{aligned}\nE=M &+e \\sin M+\\frac{e^{2}}{2 !} \\sin 2 M+\\frac{e^{3}}{3 ! 2^{2}}\\left(3^{2} \\sin 3 M-3 \\sin M\\right)+\\frac{e^{4}}{4 ! 2^{3}}\\left(4^{3} \\sin 4 M-2^{3} \\cdot 4 \\sin 2 M\\right) \\\\\n&+\\frac{e^{5}}{5 ! 2^{4}}\\left(5^{4} \\sin 5 M-3^{4} \\cdot 5 \\sin 3 M+10 \\sin M\\right)+\\frac{e^{6}}{6 ! 2^{5}}\\left(6^{5} \\sin 6 M-4^{5} \\cdot 6 \\sin 4 M+2^{5} \\cdot 15 \\sin 2 M\\right)+\\cdots\n\\end{aligned}\n\\end{equation}\nwhich simplifies to\n\\begin{equation}\n\\begin{aligned}\nE=M &+\\left(e-\\frac{1}{8} e^{3}+\\frac{1}{192} e^{5}+\\cdots\\right) \\sin M+\\left(\\frac{1}{2} e^{2}-\\frac{1}{6} e^{4}+\\frac{1}{48} e^{6}+\\cdots\\right) \\sin 2 M \\\\\n&+\\left(\\frac{3}{8} e^{3}-\\frac{27}{128} e^{5}+\\cdots\\right) \\sin 3 M+\\left(\\frac{1}{3} e^{4}-\\frac{4}{15} e^{6}+\\cdots\\right) \\sin 4 M \\\\\n&+\\left(\\frac{125}{384} e^{5}+\\cdots\\right) \\sin 5 M+\\left(\\frac{27}{80} e^{6}+\\cdots\\right) \\sin 6 M+\\cdots\n\\end{aligned}\n\\end{equation}\n", "meta": {"hexsha": "7eaecdc3643397da81e30d50ffa375484ed4fecc", "size": 46870, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Project 1/Project1_Task2.ipynb", "max_stars_repo_name": "od1sm/CoPh", "max_stars_repo_head_hexsha": "2d03f00c5e8aeacb7b0704b5ff77b953cea6b7f1", "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": "Project 1/Project1_Task2.ipynb", "max_issues_repo_name": "od1sm/CoPh", "max_issues_repo_head_hexsha": "2d03f00c5e8aeacb7b0704b5ff77b953cea6b7f1", "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": "Project 1/Project1_Task2.ipynb", "max_forks_repo_name": "od1sm/CoPh", "max_forks_repo_head_hexsha": "2d03f00c5e8aeacb7b0704b5ff77b953cea6b7f1", "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": 162.1799307958, "max_line_length": 21352, "alphanum_fraction": 0.8609131641, "converted": true, "num_tokens": 2623, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632876167044, "lm_q2_score": 0.9353465147977104, "lm_q1q2_score": 0.8674060190236311}} {"text": "# Modeling and Simulation in Python\n\nChapter 9\n\nCopyright 2017 Allen Downey\n\nLicense: [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0)\n\n\n\n```python\n# Configure Jupyter to display the assigned value after an assignment\n%config InteractiveShell.ast_node_interactivity='last_expr_or_assign'\n\n# import everything from SymPy.\nfrom sympy import *\n\n# Set up Jupyter notebook to display math.\ninit_printing() \n```\n\nThe following displays SymPy expressions and provides the option of showing results in LaTeX format.\n\n\n```python\nfrom sympy.printing import latex\n\ndef show(expr, show_latex=False):\n \"\"\"Display a SymPy expression.\n\n expr: SymPy expression\n show_latex: boolean\n \"\"\"\n if show_latex:\n print(latex(expr))\n return expr\n```\n\n### Analysis with SymPy\n\nCreate a symbol for time.\n\n\n```python\nt = symbols('t')\n```\n\nIf you combine symbols and numbers, you get symbolic expressions.\n\n\n```python\nexpr = t + 1\n```\n\nThe result is an `Add` object, which just represents the sum without trying to compute it.\n\n\n```python\ntype(expr)\n```\n\n\n\n\n sympy.core.add.Add\n\n\n\n`subs` can be used to replace a symbol with a number, which allows the addition to proceed.\n\n\n```python\nexpr.subs(t, 2)\n```\n\n`f` is a special class of symbol that represents a function.\n\n\n```python\nf = Function('f')\n```\n\n\n\n\n f\n\n\n\nThe type of `f` is `UndefinedFunction`\n\n\n```python\ntype(f)\n```\n\n\n\n\n sympy.core.function.UndefinedFunction\n\n\n\nSymPy understands that `f(t)` means `f` evaluated at `t`, but it doesn't try to evaluate it yet.\n\n\n```python\nf(t)\n```\n\n`diff` returns a `Derivative` object that represents the time derivative of `f`\n\n\n```python\ndfdt = diff(f(t), t)\n```\n\n\n```python\ntype(dfdt)\n```\n\n\n\n\n sympy.core.function.Derivative\n\n\n\nWe need a symbol for `alpha`\n\n\n```python\nalpha = symbols('alpha')\n```\n\nNow we can write the differential equation for proportional growth.\n\n\n```python\neq1 = Eq(dfdt, alpha*f(t))\n```\n\nAnd use `dsolve` to solve it. The result is the general solution.\n\n\n```python\nsolution_eq = dsolve(eq1)\n```\n\nWe can tell it's a general solution because it contains an unspecified constant, `C1`.\n\nIn this example, finding the particular solution is easy: we just replace `C1` with `p_0`\n\n\n```python\nC1, p_0 = symbols('C1 p_0')\n```\n\n\n```python\nparticular = solution_eq.subs(C1, p_0)\n```\n\nIn the next example, we have to work a little harder to find the particular solution.\n\n### Solving the quadratic growth equation \n\nWe'll use the (r, K) parameterization, so we'll need two more symbols:\n\n\n```python\nr, K = symbols('r K')\n```\n\nNow we can write the differential equation.\n\n\n```python\neq2 = Eq(diff(f(t), t), r * f(t) * (1 - f(t)/K))\n```\n\nAnd solve it.\n\n\n```python\nsolution_eq = dsolve(eq2)\n```\n\nThe result, `solution_eq`, contains `rhs`, which is the right-hand side of the solution.\n\n\n```python\ngeneral = solution_eq.rhs\n```\n\nWe can evaluate the right-hand side at $t=0$\n\n\n```python\nat_0 = general.subs(t, 0)\n```\n\nNow we want to find the value of `C1` that makes `f(0) = p_0`.\n\nSo we'll create the equation `at_0 = p_0` and solve for `C1`. Because this is just an algebraic identity, not a differential equation, we use `solve`, not `dsolve`.\n\nThe result from `solve` is a list of solutions. In this case, [we have reason to expect only one solution](https://en.wikipedia.org/wiki/Picard%E2%80%93Lindel%C3%B6f_theorem), but we still get a list, so we have to use the bracket operator, `[0]`, to select the first one.\n\n\n```python\nsolutions = solve(Eq(at_0, p_0), C1)\n```\n\n\n```python\nvalue_of_C1 = solutions[0]\n```\n\nNow in the general solution, we want to replace `C1` with the value of `C1` we just figured out.\n\n\n```python\nparticular = general.subs(C1, value_of_C1)\n```\n\nThe result is complicated, but SymPy provides a method that tries to simplify it.\n\n\n```python\nparticular = simplify(particular)\n```\n\nOften simplicity is in the eye of the beholder, but that's about as simple as this expression gets.\n\nJust to double-check, we can evaluate it at `t=0` and confirm that we get `p_0`\n\n\n```python\nparticular.subs(t, 0)\n```\n\nThis solution is called the [logistic function](https://en.wikipedia.org/wiki/Population_growth#Logistic_equation).\n\nIn some places you'll see it written in a different form:\n\n$f(t) = \\frac{K}{1 + A e^{-rt}}$\n\nwhere $A = (K - p_0) / p_0$.\n\nWe can use SymPy to confirm that these two forms are equivalent. First we represent the alternative version of the logistic function:\n\n\n```python\nA = (K - p_0) / p_0\n```\n\n\n```python\nlogistic = K / (1 + A * exp(-r*t))\n```\n\nTo see whether two expressions are equivalent, we can check whether their difference simplifies to 0.\n\n\n```python\nsimplify(particular - logistic)\n```\n\nThis test only works one way: if SymPy says the difference reduces to 0, the expressions are definitely equivalent (and not just numerically close).\n\nBut if SymPy can't find a way to simplify the result to 0, that doesn't necessarily mean there isn't one. Testing whether two expressions are equivalent is a surprisingly hard problem; in fact, there is no algorithm that can solve it in general.\n\n### Exercises\n\n**Exercise:** Solve the quadratic growth equation using the alternative parameterization\n\n$\\frac{df(t)}{dt} = \\alpha f(t) + \\beta f^2(t) $\n\n\n```python\nalpha = symbols('alpha')\nbeta = symbols('beta')\nt = symbols('t')\nf = Function('f')\np_0 = symbols('p_0')\nC1 = symbols('C1')\n```\n\n\n```python\na_eq = Eq(diff(f(t),t), alpha*f(t)+beta*f(t)**2)\n```\n\n\n```python\na_sol = dsolve(a_eq)\n```\n\n\n```python\na_gen = a_sol.rhs\n```\n\n\n```python\nc1_particular = solve(Eq(a_gen.subs(t, 0), p_0), C1)\n```\n\n\n```python\na_part = a_gen.subs(C1, c1_particular)\n```\n\n\n```python\na_sol_full = simplify(a_gen + a_part)\n```\n\n**Exercise:** Use [WolframAlpha](https://www.wolframalpha.com/) to solve the quadratic growth model, using either or both forms of parameterization:\n\n df(t) / dt = alpha f(t) + beta f(t)^2\n\nor\n\n df(t) / dt = r f(t) (1 - f(t)/K)\n\nFind the general solution and also the particular solution where `f(0) = p_0`.\n\n\n```python\n\n```\n", "meta": {"hexsha": "bffc158dc7cd71af943efec573f1cd25e9a0f370", "size": 56507, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "code/chap09mine.ipynb", "max_stars_repo_name": "SSModelGit/ModSimPy", "max_stars_repo_head_hexsha": "4d1e3d8c3b878ea876e25e6a74509535f685f338", "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": "code/chap09mine.ipynb", "max_issues_repo_name": "SSModelGit/ModSimPy", "max_issues_repo_head_hexsha": "4d1e3d8c3b878ea876e25e6a74509535f685f338", "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": "code/chap09mine.ipynb", "max_forks_repo_name": "SSModelGit/ModSimPy", "max_forks_repo_head_hexsha": "4d1e3d8c3b878ea876e25e6a74509535f685f338", "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": 48.7129310345, "max_line_length": 2209, "alphanum_fraction": 0.7170085122, "converted": true, "num_tokens": 1665, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572778000158575, "lm_q2_score": 0.9059898248255075, "lm_q1q2_score": 0.8672839463457139}} {"text": "# About Feature Scaling\nScale down or scale up the data in order to standardise the range of features/ variable\n\n\n## Sections\n\n- [Min Max normalization](#Min-Max-normalization)\n- [Z Score normalization](#Z-Score-normalization)\n- [Decimal Scaling normalization](#Z-Score-normalization)\n\n\nLet us define a list with random numbers as our independent variable\n\n\n```python\nimport random\nrandom.seed(332)\n\ndata = []\n\nfor x in range(100):\n data.append(random.randint(1,101))\n\nprint (data)\n```\n\n## Min-Max-scaling-normalization\nMin-Max normalization is a simple technique where the technique can specifically fit the data in a pre-defined boundary.\n\n\\begin{equation} X_{norm} = \\frac{X - X_{min}}{X_{max}-X_{min}} \\end{equation}\n\n\nIn the cell below we will use the *data* list and use the min-max scaling normalisation to normalise it\n- *min_max_normal* is the list of scaled output\n- *X_min* is the minimum value of the data\n- *x_max* is the maximum value of the data\n- *D* upper boundry of the predefined range\n- *C* lower boundry of the predefined range \n\n\n```python\nmin_max_normal = []\nX_min = min(data)\nX_max = max(data)\nD = 1\nC = 0\n\nfor element in data:\n X_norm = (float(element - X_min)/(X_max - X_min))*(D - C) + C\n min_max_normal.append(X_norm)\n\nprint (min_max_normal)\n```\n\n## Z-Score-normalization\nWe scale the feature so that transformed features are with an mean of zero and standard deviation of one.\n\n\\begin{equation} z = \\frac{x - \\mu}{\\sigma}\\end{equation} \n\nIn the cell below we will use the *data* list and use the min-max scaling normalisation to normalise it\n- *z_score_normal* is the list of scaled output\n- *mean* is the minimum value of the data\n- *std* is the maximum value of the data\n\n\n```python\nimport math \n\ndef mean(column):\n \"\"\"\n takes input the list of variables from the data\n returns mean of the variables in the list\n \"\"\"\n sum_ = 0\n for element in column:\n sum_ = sum_ + element\n \n return float(sum_)/len(column)\n\ndef std(column):\n \"\"\"\n takes input the list of variables from the data\n returns standard deviation of the variables in the list\n \"\"\"\n if len(column) <= 1:\n return 0.0\n\n mean_data, sd = mean(column), 0.0\n\n # calculate stan. dev.\n for el in column:\n sd += (float(el) - mean_data)**2\n sd = math.sqrt(sd / float(len(column)-1))\n\n return sd\n```\n\n\n```python\nz_normal = []\n\nmean_data = mean(data)\nstd_data = std(data)\n\nfor element in data:\n z_norm = float(element - mean_data)/std_data\n z_normal.append(z_norm)\n\nprint (z_normal)\n```\n\n## Decimal Scaling Normalisation\n\nWe normalize by moving the decimal point of values of features. The number of decimal points moved depends on the maximum absolute value in the features, it provides the range between -1 and 1\n\n- Take the maximum number of digits. For eg. 3031, then maximum digits is 4\n- Calculate power of 10. 10^4 = 10000.\n- Divide each number by 10000.\n\n\n```python\nds_normal =[]\nmax_digits = 10**len(str(max(data)))\n\nfor element in data:\n ds_norm = float(element)/max_digits\n ds_normal.append(ds_norm)\n\nprint (ds_normal)\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "87a4062ebed336cbe2820f10a98195acbb16b476", "size": 5496, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "DataPreperation/4_Normalization.ipynb", "max_stars_repo_name": "sumandeepb/A10_DataPreperationAndVisualization", "max_stars_repo_head_hexsha": "ee3192169d0e8f06a0a3c7598d29a1ca9d72bba8", "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": "DataPreperation/4_Normalization.ipynb", "max_issues_repo_name": "sumandeepb/A10_DataPreperationAndVisualization", "max_issues_repo_head_hexsha": "ee3192169d0e8f06a0a3c7598d29a1ca9d72bba8", "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": "DataPreperation/4_Normalization.ipynb", "max_forks_repo_name": "sumandeepb/A10_DataPreperationAndVisualization", "max_forks_repo_head_hexsha": "ee3192169d0e8f06a0a3c7598d29a1ca9d72bba8", "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.2966507177, "max_line_length": 201, "alphanum_fraction": 0.537845706, "converted": true, "num_tokens": 824, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338101862455, "lm_q2_score": 0.9019206745523101, "lm_q1q2_score": 0.8672272226880314}} {"text": "# Week 1 worksheet: Introduction to elliptic PDEs\n\nThis worksheet contains a number of exercises covering both the analytical and numerical aspects of the course. This means that some parts require you to solve the problem by hand, i.e. with pen and paper, while other parts require you to write code. It should usually be obvious which parts require which.\n\n#### Suggested reading\n\nYou will see lists of links to further reading and resources throughout the worksheets, in sections titled **Learn more:**. These will include links to the Python documentation on the topic at hand, or links to relevant book sections or other online resources. Unless explicitly indicated, these are not mandatory reading, although of course we strongly recommend that you consult them!\n\n#### Displaying solutions\n\nSolutions will be released after the workshop, as a new `.txt` file in the same GitHub repository. After pulling the file to Noteable, **run the following cell** to create clickable buttons under each exercise, which will allow you to reveal the solutions.\n\n\n```python\n%run scripts/create_widgets.py W01\n```\n\n\n\n\n\n\n \n\n\n Buttons created!\n\n\n*How it works: You will see cells located below each exercise, each containing a command starting with `%run scripts/show_solutions.py`. You don't need to run those yourself; the command above runs a script which automatically runs these specific cells for you. The commands in each of these cells each create the button for the corresponding exercise. The Python code to achieve this is contained in `scripts/show_solutions.py`, and relies on [IPython widgets](https://ipywidgets.readthedocs.io/en/latest/examples/Widget%20Basics.html) --- feel free to take a look at the code if you are curious.*\n\n\n```javascript\n%%javascript\nMathJax.Hub.Config({\n TeX: { equationNumbers: { autoNumber: \"AMS\" } }\n});\n```\n\n\n \n\n\n## Exercise 1\n\nConsider the the function\n$$\nu(x,y) = x^4 - 6x^2y^2 + y^4\n$$\n\n### Part a)\n\nVerify that $u(x,y)$ satisfies the Laplace equation.\n\n\n\n\n```python\nimport sympy as sp\nx,y = sp.symbols('x y')\nu = x**4-6*x**2*y**2+y**4\ndx = sp.diff(u,x)\ndx2 = sp.diff(dx,x)\ndy = sp.diff(u,y)\ndy2 = sp.diff(dy,y)\nprint(f'{dx2} and {dy2}')\nif dx2+dy2 ==0:\n print(f'The function {u} satisfies the elliptical Laplacian Partial Differential Equation')\n```\n\n 12*x**2 - 12*y**2 and -12*x**2 + 12*y**2\n The function x**4 - 6*x**2*y**2 + y**4 satisfies the elliptical Laplacian Partial Differential Equation\n\n\n### Part b)\n\nGenerate a surface plot of $u(x,y)$ in the square given by $0\\le x\\le1$ and $0\\le y\\le 1$.\n\n- Check the [numpy.meshgrid](https://numpy.org/doc/stable/reference/generated/numpy.meshgrid.html) documentation\n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib import cm\ndef u(x,y):\n return x**4-6*x**2*y**2+y**4\n\nvalues_x = np.linspace(0,1,100)\nvalues_y = np.linspace(0,1,100)\nX,Y = np.meshgrid(values_x,values_y)\nZ = u(X, Y)\nfig = plt.figure()\nax = plt.axes(projection='3d')\n#ax.contour3D(X, Y, Z, 50, cmap='binary')\nax.set_xlabel('x')\nax.set_ylabel('y')\nax.set_zlabel('z')\nsurf = ax.plot_surface(X, Y, Z,cmap = cm.coolwarm,linewidth=0, antialiased=False)\nplt.show()\n\ndef y_zero_x_in_range_from_zero_to_one():\n y_zero = 0\n x_zero = np.linspace(0,1,10)\n z_values = []\n for i in x_zero:\n z_values.append(u(i,y_zero))\n plt.plot(x_zero,z_values, label = 'y = 0')\n print('The boundary condition for u(x,0) = x**4 on the range 0<=x<=1')\n plt.xlabel('x-axis')\n plt.ylabel('z_axis')\n plt.legend()\n return plt.show()\ny_zero_x_in_range_from_zero_to_one()\n\ndef y_one_x_in_range_from_zero_to_one():\n y_one = 1\n x_one= np.linspace(0,1,10)\n z_values = []\n for i in x_one:\n z_values.append(u(i,y_one))\n plt.plot(x_one,z_values,label = 'y = 1')\n print('The boundary condition for u(x,1) = x**4-6*x**2*+1 on the range 0<=x<=1')\n plt.xlabel('x-axis')\n plt.ylabel('z_axis')\n plt.legend()\n return plt.show()\ny_one_x_in_range_from_zero_to_one()\n\ndef x_one_y_in_range_from_zero_to_one():\n y_one = np.linspace(0,1,10)\n x_one= 1\n z_values = []\n for i in y_one:\n z_values.append(u(x_one,i))\n plt.plot(y_one,z_values,label = 'x = 1')\n print('The boundary condition for u(1,y) = x**4-6*x**2*+1 on the range 0<=y<=1')\n plt.xlabel('y-axis')\n plt.ylabel('z_axis')\n plt.legend()\n return plt.show()\nx_one_y_in_range_from_zero_to_one()\n\ndef x_zero_y_in_range_from_zero_to_one():\n y_one = np.linspace(0,1,10)\n x_one= 0\n z_values = []\n for i in y_one:\n z_values.append(u(x_one,i))\n plt.plot(y_one,z_values, label = 'x = 0')\n print('The boundary condition for u(0,y) = x**4 on the range 0<=y<=1')\n plt.xlabel('y-axis')\n plt.ylabel('z_axis')\n plt.legend()\n return plt.show()\nx_zero_y_in_range_from_zero_to_one()\n\ndef e():\n x_value = np.linspace(0,1,100)\n y_value = []\n for i in x_value:\n y_value.append(i**4-6*i**2+1)\n plt.plot(x_value,y_value, label = 'e^-x')\n plt.xlabel('x_axis')\n plt.ylabel('y_axis')\n return plt.show()\n```\n\n### Part c)\n\nGive the boundary conditions fulfilled by $u(x,y)$ on the boundaries of the square given by $0\\le x\\le1$ and $0\\le y\\le 1$.\n\n\n\n\n```python\n%run scripts/show_solutions.py W01-ex1_partc\n```\n\n## Exercise 2\n\nConsider the the function\n$$\nu(x,y) = e^{-x} \\sin(y)\n$$\n\n### Part a)\n\nVerify that $u(x,y)$ satisfies the Laplace equation.\n\n\n\n\n```python\nimport sympy as sp\nx,y = sp.symbols('x y')\nu = sp.exp(-x)*sp.sin(y)\ndx = sp.diff(u,x)\ndx2 = sp.diff(dx,x)\ndy = sp.diff(u,y)\ndy2 = sp.diff(dy,y)\nprint(f'{dx2} and {dy2}')\nif dx2+dy2 ==0:\n print(f'The function {u} satisfies the elliptical Laplacian Partial Differential Equation')\n```\n\n exp(-x)*sin(y) and -exp(-x)*sin(y)\n The function exp(-x)*sin(y) satisfies the elliptical Laplacian Partial Differential Equation\n\n\n### Part b)\n\nGenerate a surface plot of $u(x,y)$ in the square given by $0\\le x\\le1$ and $0\\le y\\le \\pi$.\n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib import cm\ndef u(x,y):\n return np.exp(-x)*np.sin(y)\n\nvalues_x = np.linspace(0,1,100)\nvalues_y = np.linspace(0,1,100)\nX,Y = np.meshgrid(values_x,values_y)\nZ = u(X, Y)\nfig = plt.figure()\nax = plt.axes(projection='3d')\n#ax.contour3D(X, Y, Z, 50, cmap='binary')\nax.set_xlabel('x')\nax.set_ylabel('y')\nax.set_zlabel('z')\nax.plot_surface(X, Y, Z,cmap = cm.coolwarm,linewidth=0, antialiased=False)\n\n\nplt.show()\n\ndef y_zero_x_in_range_from_zero_to_one():\n y_zero = 0\n x_zero = np.linspace(0,1,10)\n z_values = []\n for i in x_zero:\n z_values.append(u(i,y_zero))\n plt.plot(x_zero,z_values, label = 'y = 0')\n print('The boundary condition for u(x,0) = 0 on the range 0<=x<=1')\n plt.xlabel('x-axis')\n plt.ylabel('z_axis')\n plt.legend()\n return plt.show()\ny_zero_x_in_range_from_zero_to_one()\n\ndef y_one_x_in_range_from_zero_to_one():\n y_one = 1\n x_one= np.linspace(0,1,10)\n z_values = []\n for i in x_one:\n z_values.append(u(i,y_one))\n plt.plot(x_one,z_values,label = 'y = 1')\n print('The boundary condition for u(x,1) = exp(-x)*sin(1) on the range 0<=x<=1')\n plt.xlabel('x-axis')\n plt.ylabel('z_axis')\n plt.legend()\n return plt.show()\ny_one_x_in_range_from_zero_to_one()\n\ndef x_one_y_in_range_from_zero_to_one():\n y_one = np.linspace(0,1,10)\n x_one= 1\n z_values = []\n for i in y_one:\n z_values.append(u(x_one,i))\n plt.plot(y_one,z_values,label = 'x = 1')\n print('The boundary condition for u(1,y) = exp(-1)*sin(x) on the range 0<=y<=1')\n plt.xlabel('y-axis')\n plt.ylabel('z_axis')\n plt.legend()\n return plt.show()\nx_one_y_in_range_from_zero_to_one()\n\ndef x_zero_y_in_range_from_zero_to_one():\n y_one = np.linspace(0,1,10)\n x_one= 0\n z_values = []\n for i in y_one:\n z_values.append(u(x_one,i))\n plt.plot(y_one,z_values, label = 'x = 0')\n print('The boundary condition for u(0,y) = sin(x) on the range 0<=y<=1')\n plt.xlabel('y-axis')\n plt.ylabel('z_axis')\n plt.legend()\n return plt.show()\nx_zero_y_in_range_from_zero_to_one()\n\ndef e():\n x_value = np.linspace(0,1,100)\n y_value = []\n for i in x_value:\n y_value.append(np.exp(-i)*np.sin(1))\n plt.plot(x_value,y_value, label = 'e^-x')\n plt.xlabel('x_axis')\n plt.ylabel('y_axis')\n return plt.show()\n\n```\n\n\n```python\n%run scripts/show_solutions.py W01-ex2_partb\n```\n\n### Part c)\n\nGive the boundary conditions fulfilled by $u(x,y)$ on the boundaries of the square given by $0\\le x\\le1$ and $0\\le y\\le \\pi$.\n\n\n```python\n\n```\n\n\n\n\n```python\n\n```\n\n\n```python\n%run scripts/show_solutions.py W01-ex2_partc\n```\n\n\n## Exercise 3\n\nShow that the function\n$$\nu(x,t) = e^{-kt} \\cos(mx) \\cos(nt)\n$$\nis a solution to the partial differential equation\n$$\nc^2 \\pdderiv{u}{x} = \\pdderiv{u}{t} + 2k \\pderiv{u}{t}\n$$\nif the constants with parameters $k$, $m$, $n$ and $c$ are related by the equation\n$$\nn^2 + k^2 = c^2 m^2\n$$\n\n\n\n\n\n\n```python\nimport math\nimport numpy as np\nimport matplotlib.pyplot as plt\nx,t,k,n,m,c = sp.symbols('x t k n m c')\nu = sp.exp(-k*t)*sp.cos(m*x)*sp.cos(n*t)\ndx = sp.diff(u,x)\ndx2 = sp.diff(dx,x)\ndt = sp.diff(u,t)\ndt2 = sp.diff(dy,t)\n#print(f'{dt2} and {dt} and {dx2}')\n\nprint( dt2 +2*k*dt)\nprint(c**2*dx2)\n\n```\n\n 2*k*(-k*exp(-k*t)*cos(m*x)*cos(n*t) - n*exp(-k*t)*sin(n*t)*cos(m*x))\n -c**2*m**2*exp(-k*t)*cos(m*x)*cos(n*t)\n\n\n\n```python\n%run scripts/show_solutions.py W01-ex3\n```\n", "meta": {"hexsha": "146ef0724c9d19e03fba1bf33083d80a63e08167", "size": 372097, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "laboratories/W01_PDE3_Elliptic_PDEs.ipynb", "max_stars_repo_name": "oliver779/PDE3", "max_stars_repo_head_hexsha": "cdca09d610478573c1dae498196f299ebd39a082", "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": "laboratories/W01_PDE3_Elliptic_PDEs.ipynb", "max_issues_repo_name": "oliver779/PDE3", "max_issues_repo_head_hexsha": "cdca09d610478573c1dae498196f299ebd39a082", "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": "laboratories/W01_PDE3_Elliptic_PDEs.ipynb", "max_forks_repo_name": "oliver779/PDE3", "max_forks_repo_head_hexsha": "cdca09d610478573c1dae498196f299ebd39a082", "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": 89.0823557577, "max_line_length": 39170, "alphanum_fraction": 0.7684904743, "converted": true, "num_tokens": 2901, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107878954105, "lm_q2_score": 0.925229951422338, "lm_q1q2_score": 0.8671354917569617}} {"text": "Loading libraries and setting up the environment\n\n\n```python\nimport sympy\nsympy.init_printing()\n```\n\n# Newtonian Case\n\nEquation of motion\n\n\n```python\nm = sympy.Symbol('m', positive=True) # Mass of the bullet\nv = sympy.Symbol('v', positive=True) # Velocity\nt = sympy.Symbol('t', positive=True) # Time\nA = sympy.Symbol('A', positive=True) # Bullet cross section\np = sympy.Symbol('p') # Pressure\neqn_of_motion = sympy.Eq(v(t).diff(t)*m,A*p)\neqn_of_motion\n```\n\nConservation of the Riemann invariant\n\n\n```python\nc_0 = sympy.Symbol('c_0', positive=True) # Initial speed of sound\nc = sympy.Symbol('c', positive=True) # Speed of sound\neta = sympy.Symbol('eta', positive=True) # Adiabatic index (I'm not using gamma to avoid confusion with the Lorentz factor)\nriemann_invariant_conservation = sympy.Eq(v+2*c/(eta-1),2*c_0/(eta-1))\nriemann_invariant_conservation\n```\n\nIsentropic relation\n\n\n```python\nrho = sympy.Symbol('rho') # Density\nrho_0 = sympy.Symbol('rho_0', positive=True) # Initial density\np_0 = sympy.Symbol('p_0', positive=True) # Initial pressure\nentropy_conservation = sympy.Eq(p/rho**eta,p_0/rho_0**eta)\nentropy_conservation\n```\n\nIt will be more useful to relate the pressure to the speed of sound\n\n\n```python\ntemp = entropy_conservation\ntemp = temp.subs(rho, eta*p/c**2)\ntemp = temp.subs(rho_0, eta*p_0/c_0**2)\ntemp = sympy.expand_power_base(temp,force=True).simplify()\nentropy_p_vs_c = temp\nentropy_p_vs_c\n```\n\nPressure as a function of velocity\n\n\n```python\ntemp = entropy_conservation\ntemp = temp.subs(rho,eta*p/c**2)\ntemp = temp.subs(rho_0,eta*p_0/c_0**2)\ntemp = temp.subs(sympy.solve(riemann_invariant_conservation,c,dict=True)[0])\ntemp = sympy.expand_power_base(temp,force=True)\ntemp = sympy.solve(temp,p)[0]\ntemp = sympy.expand_power_base(temp, force=True).simplify()\np_vs_v = temp\nsympy.Eq(p,p_vs_v)\n```\n\nTerminal velocity\n\n\n```python\ntemp = riemann_invariant_conservation\ntemp = sympy.solve(temp.subs(c,0),v)[0]\nterminal_velocity = temp\nterminal_velocity\n```\n\nSolving the equation of motion\n\n\n```python\ny = sympy.Symbol('y', positive=True)\nv_t = sympy.Symbol('v_t', positive=True)\ntemp = eqn_of_motion\ntemp = temp.subs(p, p_vs_v.subs(v,terminal_velocity*(1-y)))\ntemp = temp.subs(v(t), -terminal_velocity*(1-y(t)))\ntemp = temp.doit()\ntemp = sympy.expand_power_base(temp, force=True)\ntemp = temp.simplify()\ntemp = temp.subs(y(t).diff(t),y/t)\ntemp = sympy.solve(temp,y)[0]\ntemp = (temp*terminal_velocity).subs(c_0,v_t*(eta-1)/2)\ntemp = sympy.expand_power_base(temp,force=True).simplify()\nasymptotic_velocity = temp\nasymptotic_velocity\n```\n\nThe thickness of the bullet (size along the direction of motion) increases with time according to\n\n\n```python\nw_0 = sympy.Symbol('w_0', positive=True) # Initial thickness\ntemp = w_0*(p/p_0)**(-1/eta)\ntemp = temp.subs(sympy.solve(entropy_p_vs_c,p,dict=True)[0])\ntemp = temp.subs(c_0, v_t)\ntemp = temp.subs(c, asymptotic_velocity)\ntemp = sympy.expand_power_base(temp).simplify()\nthickness_history = temp\nthickness_history\n```\n\nTime when the bullet is broken apart by the Rayleigh Taylor instability\n\n\n```python\nw = sympy.Symbol('w', positive=True) # Current thickness of the bullet\na = sympy.Symbol('a', positive=True) # Acceleration\ntemp = sympy.Eq(t*sympy.sqrt(a/w),1)\ntemp = temp.subs(a,-asymptotic_velocity.diff(t)).simplify()\ntemp = temp.subs(w, thickness_history)\nsympy.expand_power_base(temp).simplify()\n```\n\nWe have two timescales in this problem: the sound crossing time of the bullet $w_0/v_t$, and the acceleration time $m v_t/A p_0$. If the acceleration time is larger than the sound crossing time, then the bullet disintegrates right at the beginning. If not, then it never will.\n\n# Relativistic Case\n\nEquation of motion\n\n\n```python\ngamma = sympy.Symbol('gamma', positive=True) # Lorentz factor\nC = sympy.Symbol('C', positive=True) # Speed of light\nur_eqn_of_motion = sympy.Eq(C*m*gamma(t).diff(t), A*p)\nur_eqn_of_motion\n```\n\nConservation of the relativistic Riemann invariant\n\n\n```python\nur_riemann_invariant_conservation = sympy.Eq(p,p_0*gamma**(-sympy.sqrt(eta-1)/eta))\nur_riemann_invariant_conservation\n```\n\nSolving the equation of motion\n\n\n```python\ntemp = ur_eqn_of_motion.subs(p,ur_riemann_invariant_conservation.rhs)\ntemp = temp.subs(gamma(t).diff(t),gamma/t)\nlf_history = sympy.solve(temp,gamma)[0]\nlf_history\n```\n\nPressure history\n\n\n```python\ntemp = ur_riemann_invariant_conservation.rhs\nur_pressure_history = temp.subs(gamma, lf_history).simplify()\nur_pressure_history\n```\n\nDensity history\n\n\n```python\neta2 = sympy.Symbol('eta2', positive=True)\ntemp = rho_0*(p/p_0)**(1/eta)\ntemp = temp.subs(p,ur_pressure_history)\ntemp = temp.subs(eta,eta2+1)\nur_density_history = sympy.expand_power_base(temp,force=True).simplify().subs(eta2, eta-1)\nur_density_history\n```\n\nNow, let us turn our attention to the Riemann problem. On the left (negative) side, there's a photon gas with pressure $p_l$. On the right, there's a cold baryonic matter with mass density $\\rho_r$. Both fluids are stationary. In the case where $p_l/\\rho_r \\ll c^2$, then the first shock is non relativistic, and what we get is basically the non relativistic problem, boosted to a relativistic velocity. If, on the other hand $p_l/\\rho_r \\gg c^2$, then the first shock is relativistic. We call the second case the genuinely relativistic case.\n\n## Boosted Newtonian Case\n\nThickness of the bullet in the fluid frame\n\n\n```python\ntemp = w_0*rho_0/rho\ntemp = temp.subs(rho, ur_density_history)\nff_bullet_thickness = temp\nff_bullet_thickness\n```\n\nBreakup time\n\n\n```python\ntemp = (t/gamma)**2*a/ff_bullet_thickness\ntemp = temp.subs(gamma, lf_history)\ntemp = temp.subs(a, lf_history/t)\ntemp = temp.subs(eta, eta2+1)\ntemp = sympy.expand_power_base(temp, force=True).simplify().subs(eta2, eta-1).simplify()\ntentative_growth_factor=temp\ntentative_growth_factor\n```\n\n\n```python\nt*sympy.log(tentative_growth_factor).diff(t).simplify()\n```\n\n\n```python\nbn_t_breakup = sympy.solve(tentative_growth_factor-1,t)[0]\n[bn_t_breakup,\n sympy.expand_power_base(bn_t_breakup, force=True).simplify().subs(eta,sympy.Rational(4,3)).simplify()]\n```\n\n## Genuinely Relativistic Case\n\nIn this case the initial pressure in the bullet will be different from the initial pressure in the barrel. To determine this pressre, we need to find the intersection between the relative Hugoniot (Taub) curve of the bullet and the rarefaction curve of the barrel\n\n\n```python\ntaub_curve = sympy.Eq(p, rho_0*C**2*gamma**2)\ntaub_curve\n```\n\n\n```python\nrel_riemann_problem_intersection = sympy.solve([taub_curve, ur_riemann_invariant_conservation],[p,gamma])[1]\nrel_riemann_problem_intersection\n```\n\nWhen calculating the growth factor, one has to take into account the contribution of the pressure to the intertia\n\n\n```python\ntemp = (t/gamma)*(a/w)*(rho*C**2/p)\ntemp = temp.subs(w,w_0*(rho_0/rho))\ntemp = temp.subs(rho, rho_0*(p/p_0)**(1/eta))\ntemp = temp.subs(p,rel_riemann_problem_intersection[1]*(gamma/rel_riemann_problem_intersection[0])**(sympy.sqrt(eta-1)/eta))\ntemp = temp.subs(a, gamma/t)\ntemp = temp.subs(gamma, lf_history)\ntemp = temp.subs(eta,eta2+1)\ntemp = sympy.expand_power_base(temp, force=True)\ntemp = temp.simplify()\ntemp = temp.subs(eta2, eta-1).simplify()\ngr_growth_factor = temp\ngr_growth_factor\n```\n\nBreakup time\n\n\n```python\ntemp = sympy.solve(gr_growth_factor-1,t)[0]\ntemp = temp.subs(eta, eta2+1)\ngr_breakup_time = sympy.expand_power_base(temp, force=True).simplify().subs(eta2, eta-1)\ngr_breakup_time\n```\n\nFor an equation of state with $\\eta=\\frac{4}{3}$\n\n\n```python\ngr_breakup_time.subs(eta,sympy.Rational(4,3)).simplify()\n```\n\nWe note that the relativistic Rayleigh Taylor rate is approximately $\\sqrt{k a\\frac{\\rho_2-\\rho_1}{\\rho_1+\\rho_2+p/c^2}}$. As one might expect, the difference with respect to the newtonian rate is the inclusion of the pressure term as part of the inertia (denominator). It does not appear in the driving term (numerator) because it is the same of both sides.\n\n\n```python\n\n```\n", "meta": {"hexsha": "5c3e8aa3a0e541e7cfa73ebdab0533abd7506ca2", "size": 135108, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "disintegrating_bullet.ipynb", "max_stars_repo_name": "bolverk/disintegrating_bullet", "max_stars_repo_head_hexsha": "676bd2f575a70497ee0bebee801405f59df7bc9a", "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": "disintegrating_bullet.ipynb", "max_issues_repo_name": "bolverk/disintegrating_bullet", "max_issues_repo_head_hexsha": "676bd2f575a70497ee0bebee801405f59df7bc9a", "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": "disintegrating_bullet.ipynb", "max_forks_repo_name": "bolverk/disintegrating_bullet", "max_forks_repo_head_hexsha": "676bd2f575a70497ee0bebee801405f59df7bc9a", "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": 116.1719690456, "max_line_length": 16682, "alphanum_fraction": 0.7603324748, "converted": true, "num_tokens": 2325, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9658995782141545, "lm_q2_score": 0.8976952914230971, "lm_q1q2_score": 0.8670835033504021}} {"text": "# Quadratic Programming\n\n- Mathematical optimization problems with quadratic functions\n- Developed in the 1950s\n- Widely used in\n - Optimization of financial portfolios,\n - Image and signal processing,\n - Regression,\n - Scheduling in chemical plants, etc.\n- Solution methods\n - Interior point,\n - Augmented Lagrange,\n - Gradient-based,\n - Extensions of the simplex algortihm.\n \n## Problem Formulation\nOur objective is to find $\\mathbf{x}\\in\\mathbb{R}^n$ in the following problem:\n\n\\begin{align}\n\\text{minimize}\\ & \\frac{1}{2}\\mathbf{x}^T Q \\mathbf{x} + \\mathbf{c}^T\\mathbf{x}, \\\\\n\\text{subject to } & \\\\\n& A\\mathbf{x} \\ \\leq \\mathbf{b}, \\\\\n\\end{align}\nwhere\n- $\\mathbf{c} \\in \\mathbb{R}^n$,\n- $Q \\in \\mathbb{R}^{n \\times n}$,\n- $A \\in \\mathbb{R}^{m \\times n}$,\n- $\\mathbf{b} \\in \\mathbb{R}^{m}$.\n\n## Coding in Python\nThe model:\n\\begin{align}\n\\text{minimize}\\ & x^2 + 2y^2 + \\frac{1}{2}z^2 , \\\\\n\\text{subject to } & \\\\\n& x + 3y + 2z \\geq 5, \\\\\n& y + z \\geq 2.5, \\\\\n& x, y \\geq 0, \\\\\n& y \\in \\mathbb{Z} \\\\\n& z \\in \\{0, 1\\}\n\\end{align}\n### Step 1: Import Package\n\n\n```python\nfrom gurobipy import *\n```\n\n### Step 2: Create a model\n\n\n```python\nquadratic_model = Model('quadratic')\n```\n\n### Step 3: Define decision variables\n\n\n```python\nx = quadratic_model.addVar(vtype=GRB.CONTINUOUS, lb = 0, name=\"x\")\ny = quadratic_model.addVar(vtype=GRB.INTEGER, lb = 0, name=\"y\")\nz = quadratic_model.addVar(vtype=GRB.BINARY, name=\"z\")\n```\n\n### Step 4: Define the objective function\n\n\n```python\nobj_fn = x**2 + 2*y**2 + 0.5*z**2\nquadratic_model.setObjective(obj_fn, GRB.MINIMIZE)\n```\n\n### Step 5: Add constraints\n\n\n```python\n# x + 3y + 2z >= 5\nquadratic_model.addConstr(x + 3*y + 2*z >= 5)\n# y + z >= 2.5\nquadratic_model.addConstr(y + z >= 2.5)\n```\n\n### Step 6: Solve model and output the result\n\n\n```python\nquadratic_model.setParam('OutputFlag',False)\nquadratic_model.optimize()\n\nprint('Optimization is done. Objective Function Value: %.2f' % quadratic_model.objVal)\n# Get values of the decision variables\nfor v in quadratic_model.getVars():\n print('%s: %g' % (v.varName, v.x))\n```\n\n### Extras: Update the type of a decision variable\n\nLet us change the requirement of integrality on the decision variable $y$:\n\n\n```python\ny.vType = GRB.CONTINUOUS\n\nquadratic_model.optimize()\n\nprint('Optimization is done. Objective Function Value: %.2f' % quadratic_model.objVal)\n# Get values of the decision variables\nfor v in quadratic_model.getVars():\n print('%s: %g' % (v.varName, v.x))\n```\n\n### Extras: Add a quadratic constraint\n\nLet us add a quadratic constraint: $x^2 \\geq y^2 + z^2$\n\n\n```python\nquadratic_model.addConstr(z**2 + y**2 <= x**2)\n\nquadratic_model.optimize()\n\nprint('Optimization is done. Objective Function Value: %.2f' % quadratic_model.objVal)\n# Get values of the decision variables\nfor v in quadratic_model.getVars():\n print('%s: %g' % (v.varName, v.x))\n```\n", "meta": {"hexsha": "e5185c1ff992aa9fa9f87580ab2826a72c72733e", "size": 5538, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "mathematicalProgramming/Video05/Video05.ipynb", "max_stars_repo_name": "codingperspective/videoMaterials", "max_stars_repo_head_hexsha": "8c9665466d8912c6f0c701c25ad9eb4802fb73a3", "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": "mathematicalProgramming/Video05/Video05.ipynb", "max_issues_repo_name": "codingperspective/videoMaterials", "max_issues_repo_head_hexsha": "8c9665466d8912c6f0c701c25ad9eb4802fb73a3", "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": "mathematicalProgramming/Video05/Video05.ipynb", "max_forks_repo_name": "codingperspective/videoMaterials", "max_forks_repo_head_hexsha": "8c9665466d8912c6f0c701c25ad9eb4802fb73a3", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2021-11-21T05:02:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-17T04:44:57.000Z", "avg_line_length": 24.7232142857, "max_line_length": 103, "alphanum_fraction": 0.5128205128, "converted": true, "num_tokens": 934, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9790357542883922, "lm_q2_score": 0.8856314723088732, "lm_q1q2_score": 0.867064876513457}} {"text": "###### Content under Creative Commons Attribution license CC-BY 4.0, code under MIT license (c)2014 L.A. Barba, G.F. Forsyth, C. Cooper. Based on [CFDPython](https://github.com/barbagroup/CFDPython), (c)2013 L.A. Barba, also under CC-BY license.\n\n# Space & Time\n\n## 1-D Diffusion\n\nWelcome back! This is the third Jupyter Notebook of the series *Space and Time — Introduction of Finite-difference solutions of PDEs*, the second module of [\"Practical Numerical Methods with Python\"](https://openedx.seas.gwu.edu/courses/course-v1:MAE+MAE6286+2017/about). \n\nIn the previous Jupyter notebooks of this series, we studied the numerical solution of the linear and non-linear convection equations using the finite-difference method, and learned about the CFL condition. Now, we will look at the one-dimensional diffusion equation:\n\n$$\n\\begin{equation}\n\\frac{\\partial u}{\\partial t}= \\nu \\frac{\\partial^2 u}{\\partial x^2}\n\\end{equation}\n$$\n\nwhere $\\nu$ is a constant known as the *diffusion coefficient*.\n\nThe first thing you should notice is that this equation has a second-order derivative. We first need to learn what to do with it!\n\n### Discretizing 2nd-order derivatives\n\nThe second-order derivative can be represented geometrically as the line tangent to the curve given by the first derivative. We will discretize the second-order derivative with a Central Difference scheme: a combination of forward difference and backward difference of the first derivative. Consider the Taylor expansion of $u_{i+1}$ and $u_{i-1}$ around $u_i$:\n\n$$\nu_{i+1} = u_i + \\Delta x \\frac{\\partial u}{\\partial x}\\big|_i + \\frac{\\Delta x^2}{2!} \\frac{\\partial ^2 u}{\\partial x^2}\\big|_i + \\frac{\\Delta x^3}{3!} \\frac{\\partial ^3 u}{\\partial x^3}\\big|_i + {\\mathcal O}(\\Delta x^4)\n$$\n\n$$\nu_{i-1} = u_i - \\Delta x \\frac{\\partial u}{\\partial x}\\big|_i + \\frac{\\Delta x^2}{2!} \\frac{\\partial ^2 u}{\\partial x^2}\\big|_i - \\frac{\\Delta x^3}{3!} \\frac{\\partial ^3 u}{\\partial x^3}\\big|_i + {\\mathcal O}(\\Delta x^4)\n$$\n\nIf we add these two expansions, the odd-numbered derivatives will cancel out. Neglecting any terms of ${\\mathcal O}(\\Delta x^4)$ or higher (and really, those are very small), we can rearrange the sum of these two expansions to solve for the second-derivative. \n\n$$\nu_{i+1} + u_{i-1} = 2u_i+\\Delta x^2 \\frac{\\partial ^2 u}{\\partial x^2}\\big|_i + {\\mathcal O}(\\Delta x^4)\n$$\n\nAnd finally:\n\n$$\n\\begin{equation}\n\\frac{\\partial ^2 u}{\\partial x^2}=\\frac{u_{i+1}-2u_{i}+u_{i-1}}{\\Delta x^2} + {\\mathcal O}(\\Delta x^2)\n\\end{equation}\n$$\n\nThe central difference approximation of the 2nd-order derivative is 2nd-order accurate.\n\n### Back to diffusion\n\nWe can now write the discretized version of the diffusion equation in 1D:\n\n$$\n\\begin{equation}\n\\frac{u_{i}^{n+1}-u_{i}^{n}}{\\Delta t}=\\nu\\frac{u_{i+1}^{n}-2u_{i}^{n}+u_{i-1}^{n}}{\\Delta x^2}\n\\end{equation}\n$$\n\nAs before, we notice that once we have an initial condition, the only unknown is $u_{i}^{n+1}$, so we re-arrange the equation to isolate this term:\n\n$$\n\\begin{equation}\nu_{i}^{n+1}=u_{i}^{n}+\\frac{\\nu\\Delta t}{\\Delta x^2}(u_{i+1}^{n}-2u_{i}^{n}+u_{i-1}^{n})\n\\end{equation}\n$$\n\nThis discrete equation allows us to write a program that advances a solution in time—but we need an initial condition. Let's continue using our favorite: the hat function. So, at $t=0$, $u=2$ in the interval $0.5\\le x\\le 1$ and $u=1$ everywhere else.\n\n### Stability of the diffusion equation\n\nThe diffusion equation is not free of stability constraints. Just like the linear and non-linear convection equations, there are a set of discretization parameters $\\Delta x$ and $\\Delta t$ that will make the numerical solution blow up. For the diffusion equation and the discretization used here, the stability condition for diffusion is\n\n$$\n\\begin{equation}\n\\nu \\frac{\\Delta t}{\\Delta x^2} \\leq \\frac{1}{2}\n\\end{equation}\n$$\n\n### And solve!\n\n We are ready to number-crunch!\n\nThe next two code cells initialize the problem by loading the needed libraries, then defining the solution parameters and initial condition. This time, we don't let the user choose just *any* $\\Delta t$, though; we have decided this is not safe: people just like to blow things up. Instead, the code calculates a value of $\\Delta t$ that will be in the stable range, according to the spatial discretization chosen! You can now experiment with different solution parameters to see how the numerical solution changes, but it won't blow up.\n\n\n```python\nimport numpy\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\n```\n\n\n```python\n# Set parameters.\nnx = 41 # number spatial grid points\nL = 2.0 # length of the domain\ndx = L / (nx - 1) # spatial grid size\nnu = 0.3 # viscosity\nsigma = 0.2 # CFL limit\ndt = sigma * dx**2 / nu # time-step size\nnt = 20 # number of time steps to compute\n\n# Get the grid point coordinates.\nx = numpy.linspace(0.0, L, num=nx)\n\n# Set the initial conditions.\nu0 = numpy.ones(nx)\nmask = numpy.where(numpy.logical_and(x >= 0.5, x <= 1.0))\nu0[mask] = 2.0\n```\n\n\n```python\n# Integrate in time.\nu = u0.copy()\nfor n in range(nt):\n u[1:-1] = u[1:-1] + nu * dt / dx**2 * (u[2:] - 2 * u[1:-1] + u[:-2])\n```\n\n\n```python\n# Plot the solution after nt time steps\n# along with the initial conditions.\npyplot.figure(figsize=(6.0, 4.0))\npyplot.xlabel('x')\npyplot.ylabel('u')\npyplot.grid()\npyplot.plot(x, u0, label='Initial',\n color='C0', linestyle='--', linewidth=2)\npyplot.plot(x, u, label='nt = {}'.format(nt),\n color='C1', linestyle='-', linewidth=2)\npyplot.legend(loc='upper right')\npyplot.xlim(0.0, L)\npyplot.ylim(0.5, 2.5);\n```\n\n## Animations\n\nLooking at before-and-after plots of the wave in motion is helpful, but it's even better if we can see it changing! \n\nFirst, let's import the `animation` module of `matplotlib` as well as a special IPython display method called `HTML` (more on this in a bit).\n\n##### Note\n\nYou will also have to install a video encoder/decoder named `ffmpeg`.\n\nIf you use Linux or OSX, you can install ffmpeg using conda:\n```\nconda install -c conda-forge ffmpeg\n```\n\nIf you use Windows, installation instructions can be found [here](http://adaptivesamples.com/how-to-install-ffmpeg-on-windows/).\n\n\n```python\nfrom matplotlib import animation\nfrom IPython.display import HTML\n```\n\nWe are going to create an animation.\nThis takes a few steps, but it's actually not hard to do!\n\nFirst, we define a function, called `diffusion`, that computes the numerical solution of the 1D diffusion equation over the time steps.\n(The function returns a list with `nt` elements, each one being a Numpy array.)\n\n\n```python\ndef diffusion(u0, sigma=0.5, nt=20):\n \"\"\"\n Computes the numerical solution of the 1D diffusion equation\n over the time steps.\n \n Parameters\n ----------\n u0 : numpy.ndarray\n The initial conditions as a 1D array of floats.\n sigma : float, optional\n The value of nu * dt / dx^2;\n default: 0.5.\n nt : integer, optional\n The number of time steps to compute;\n default: 20.\n \n Returns\n -------\n u_hist : list of numpy.ndarray objects\n The history of the numerical solution.\n \"\"\"\n u_hist = [u0.copy()]\n u = u0.copy()\n for n in range(nt):\n u[1:-1] = u[1:-1] + sigma * (u[2:] - 2 * u[1:-1] + u[:-2])\n u_hist.append(u.copy())\n return u_hist\n```\n\nWe now call the function to store the history of the solution:\n\n\n```python\n# Compute the history of the numerical solution.\nu_hist = diffusion(u0, sigma=sigma, nt=nt)\n```\n\nNext, we create a Matplotlib figure that we want to animate.\nFor now, the figure contains the initial solution (our top-hat function).\n\n\n```python\nfig = pyplot.figure(figsize=(6.0, 4.0))\npyplot.xlabel('x')\npyplot.ylabel('u')\npyplot.grid()\nline = pyplot.plot(x, u0,\n color='C0', linestyle='-', linewidth=2)[0]\npyplot.xlim(0.0, L)\npyplot.ylim(0.5, 2.5)\nfig.tight_layout()\n```\n\n**Note**: `pyplot.plot()` can (optionally) return several values. Since we're only creating one line, we ask it for the \"zeroth\" (and only...) line by adding `[0]` after the `pyplot.plot()` call.\n\nNow that our figure is initialized, we define a function `update_plot` to update the data of the line plot based on the time-step index.\n\n\n```python\ndef update_plot(n, u_hist):\n \"\"\"\n Update the line y-data of the Matplotlib figure.\n \n Parameters\n ----------\n n : integer\n The time-step index.\n u_hist : list of numpy.ndarray objects\n The history of the numerical solution.\n \"\"\"\n fig.suptitle('Time step {:0>2}'.format(n))\n line.set_ydata(u_hist[n])\n```\n\nNext, we create an `animation.FuncAnimation` object with the following arguments:\n\n* `fig`: the name of our figure,\n* `diffusion`: the name of our solver function,\n* `frames`: the number of frames to dra (which we set equal to `nt`),\n* `fargs`: extra arguments to pass to the function `diffusion`,\n* `interval`: the number of milliseconds each frame appears for.\n\n\n```python\n# Create an animation.\nanim = animation.FuncAnimation(fig, update_plot,\n frames=nt, fargs=(u_hist,),\n interval=100)\n```\n\nOk! Time to display the animation.\nWe use the `HTML` display method that we imported above and the `to_html5_video` method of the animation object to make it web compatible.\n\n\n```python\n# Display the video.\nHTML(anim.to_html5_video())\n```\n\n\n\n\n\n\n\n\n---\n\n###### The cell below loads the style of the notebook.\n\n\n```python\nfrom IPython.core.display import HTML\ncss_file = '../../styles/numericalmoocstyle.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\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "a3d1a2b82374c9bff7d64f7264b625d82fec5562", "size": 73130, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "lessons/02_spacetime/02_03_1DDiffusion.ipynb", "max_stars_repo_name": "eschew-art/numerical-mooc", "max_stars_repo_head_hexsha": "1b8317b77686c33f9423600f189cf8896762eab0", "max_stars_repo_licenses": ["CC-BY-3.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": "lessons/02_spacetime/02_03_1DDiffusion.ipynb", "max_issues_repo_name": "eschew-art/numerical-mooc", "max_issues_repo_head_hexsha": "1b8317b77686c33f9423600f189cf8896762eab0", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lessons/02_spacetime/02_03_1DDiffusion.ipynb", "max_forks_repo_name": "eschew-art/numerical-mooc", "max_forks_repo_head_hexsha": "1b8317b77686c33f9423600f189cf8896762eab0", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 75.7823834197, "max_line_length": 19228, "alphanum_fraction": 0.7864761384, "converted": true, "num_tokens": 3766, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418116217417, "lm_q2_score": 0.9381240142763573, "lm_q1q2_score": 0.8669596260792135}} {"text": "# Orthogonal polynomials\n\nCopyright (C) 2020 Andreas Kloeckner\n\n
\nMIT License\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n
\n\n\n```python\nimport numpy as np\nimport numpy.linalg as la\nimport matplotlib.pyplot as pt\n```\n\n## Mini-Introduction to `sympy`\n\n\n```python\nimport sympy as sym\n\n# Enable \"pretty-printing\" in IPython\nsym.init_printing()\n```\n\nMake a new `Symbol` and work with it:\n\n\n```python\n\n```\n\n\n```python\nmyexpr = (x**2-3)**2\nmyexpr\nmyexpr.expand()\n```\n\n\n```python\nsym.integrate(myexpr, x)\n```\n\n\n```python\nsym.integrate(myexpr, (x, -1, 1))\n```\n\n## Orthogonal polynomials\n\nNow write a function `inner_product(f, g)`:\n\n\n```python\n\n```\n\nShow that it works:\n\n\n```python\n\n```\n\n\n```python\n\n```\n\nNext, define a `basis` consisting of a few monomials:\n\n\n```python\n\n```\n\nAnd run Gram-Schmidt on it:\n\n\n```python\north_basis = []\n\nfor q in basis:\n for prev_q in orth_basis:\n q = q - inner_product(prev_q, q)*prev_q / inner_product(prev_q,prev_q)\n orth_basis.append(q)\n\nlegendre_basis = [orth_basis[0],]\n\n#to compute Legendre polynomials need to normalize so that q(1)=1 rather than ||q||=1\nfor q in orth_basis[1:]:\n q = q / q.subs(x,1)\n legendre_basis.append(q)\n```\n\n\n```python\nlegendre_basis\n```\n\nThese are called the *Legendre polynomials*.\n\n--------------------\nWhat do they look like?\n\n\n```python\nmesh = np.linspace(-1, 1, 100)\n\npt.figure(figsize=(8,8))\nfor f in legendre_basis:\n f = sym.lambdify(x, f)\n pt.plot(mesh, [f(xi) for xi in mesh])\n```\n\n-----\nThese functions are important enough to be included in `scipy.special` as `eval_legendre`:\n\n\n```python\nimport scipy.special as sps\n\nfor i in range(10):\n pt.plot(mesh, sps.eval_legendre(i, mesh))\n```\n\nWhat can we find out about the conditioning of the generalized Vandermonde matrix for Legendre polynomials?\n\n\n```python\n#keep\nn = 20\nxs = np.linspace(-1, 1, n)\nV = np.array([\n sps.eval_legendre(i, xs)\n for i in range(n)\n]).T\n\nla.cond(V)\n```\n\nThe Chebyshev basis can similarly be defined by Gram-Schmidt, but now with respect to a different inner-product weight function,\n$$w(x) = 1/\\sqrt{1-x^2}.$$\n\n\n```python\n\n```\n\n\n```python\nfor i in range(10):\n pt.plot(mesh, np.cos(i*np.arccos(mesh)))\n```\n\nChebyshev polynomials achieve similar good, but imperfect conditioning on a uniform grid (but perfect conditioning on a grid of Chebyshev nodes).\n\n\n```python\n#keep\nn = 20\nxs = np.linspace(-1, 1, n)\nV = np.array([\n np.cos(i*np.arccos(xs))\n for i in range(n)\n]).T\n\nla.cond(V)\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "aeb5d48d99398b895b8b12191e8997e85b9e1577", "size": 8701, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "cleared-demos/interpolation/Orthogonal Polynomials.ipynb", "max_stars_repo_name": "xywei/numerics-notes", "max_stars_repo_head_hexsha": "70e67e17d855b7bb06a0de7e3570d40ad50f941b", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 20, "max_stars_repo_stars_event_min_datetime": "2021-01-24T21:12:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-02T19:58:25.000Z", "max_issues_repo_path": "cleared-demos/interpolation/Orthogonal Polynomials.ipynb", "max_issues_repo_name": "xywei/numerics-notes", "max_issues_repo_head_hexsha": "70e67e17d855b7bb06a0de7e3570d40ad50f941b", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2021-08-24T17:48:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-14T21:22:02.000Z", "max_forks_repo_path": "cleared-demos/interpolation/Orthogonal Polynomials.ipynb", "max_forks_repo_name": "xywei/numerics-notes", "max_forks_repo_head_hexsha": "70e67e17d855b7bb06a0de7e3570d40ad50f941b", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2020-11-23T09:56:26.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-24T17:30:26.000Z", "avg_line_length": 24.86, "max_line_length": 155, "alphanum_fraction": 0.4650040225, "converted": true, "num_tokens": 936, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947117065458, "lm_q2_score": 0.917302651107873, "lm_q1q2_score": 0.8668461543313346}} {"text": "# Assignment 1: Part 1 - kNN Basics\nIn this assignment you will implement a kNN model from scratch. The objectives are:\n- To familiarise yourself with Python and some aspects of Numpy if you are not accustomed to it\n- To gain some hands-on experience with a simple machine learning model\n- Classify a set of test data\n\n\n\n```python\nimport numpy as np\nfrom sklearn.datasets import make_classification \nfrom sklearn.model_selection import train_test_split\nimport matplotlib.pyplot as plt\n```\n\n# Data exploration\nWe can use sklearn to generate random data. For now we will classify data with two input features that may belong to one of two classes.\nThe full dataset is split 50/50 into a training and test set.\nFor now we will not do any pre-processing on the data.\n\nAt a later stage we will look at real-world datasets and some of the problems that might be experienced with real-world data.\n\n\n```python\nX, Y = make_classification(n_samples=500, n_features=2, n_redundant=0, n_informative=1, n_classes=2, n_clusters_per_class=1)\nX_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.5)\n```\n\nIt is very useful to know the shape of the data you are working with. Very often it serves as a quick way to debug parts of your code. If you are working with Python lists you can use the `len()` function, but you would have to use it for each dimension of your data. e.g.\\\n`dim1 = len(my_list)` ,\n`dim2 = len(my_list[0])` ,\n`dim3 = len(my_list([0][0])`\\\nNumpy provides easy access to the shape of n-dimensional arrays `ndarrays` e.g. \\\n`my_array.shape => (dim1, dim2, dim3)` \\\nYou will notice that I have provided clues about the shape of the data for each function where necessary.\n\nYou can use the cell block below to examine the data however you wish. It will not be graded. I suggest confirming that the data shapes make sense. For example the data matix $\\mathbf{X}$ would be given by\n\\begin{align}\n\\mathbf{X} &= \\begin{bmatrix}\n\t\t\t\\mathbf{x_1}^T \\\\\n\t\t\t\\mathbf{x_2}^T \\\\\n\t\t\t\\vdots \\\\\n\t\t\t\\mathbf{x_n}^T\n\t\t\\end{bmatrix}\n\t\t=\n\t\t\\begin{bmatrix}\n\t\t\tx_{1}^{[1]} & x_{2}^{[1]} & \\dots & x_{m}^{[1]} \\\\\n\t\t\tx_{1}^{[2]} & x_{2}^{[2]} & \\dots & x_{m}^{[2]} \\\\\n\t\t\t\\vdots & \\vdots & \\ddots & \\vdots \\\\\n\t\t\tx_{1}^{[n]} & x_{2}^{[n]} & \\dots & x_{m}^{[n]}\n\t\t\\end{bmatrix}\n\\end{align}\nWhere there are $n$ number of examples and $m$ number of features\n\n\n```python\n# You can use this block to play around. n = number of examples, m = number of features => each row is an example\n# Just make sure not to change the generated data as these are global variables.\n# You can re-run the data generating block to create new data\nY_train.shape\n```\n\n\n\n\n (250,)\n\n\n\n# Data Visualisation\nIt's useful to visualise the data. Here it is easy because we only have two features. High-dimensional inputs need additional tools in order to help visualise them. \n\n\n```python\nfig = plt.figure(figsize=(6,6))\nplt.scatter(X_train[:, 0], X_train[:, 1], c=Y_train, cmap='cool')\nplt.ylabel('$x_2$')\nplt.xlabel('$x_1$')\nplt.show()\n```\n\n\n```python\n# You can use this block play around \n# notation: superscript = example, subscript = feature \nx_a = [0, 1]\nx_b = [0, 5]\n```\n\n# Task 1: Distance Function\nYour first task is to develop a function that takes in two feature vectors (numpy arrays), $\\mathbf{x}^{[a]}$, and $\\mathbf{x}^{[b]}$ and ouputs the Euclidean distance between them\n\n$$\nd\\left(\\mathbf{x}^{[a]}, \\mathbf{x}^{[b]}\\right) = \\sqrt{\\sum\\limits_{j=1}^m\\left(x_j^{[a]} - x_j^{[b]}\\right)^2}\n$$\n\nSome helpful functions:\\\n`np.sqrt()`, `np.sum()` and `np.pow()`\n\n\n```python\ndef euclideanDistance(x_a, x_b):\n \"\"\"\n Calculates the Euclidean distance between two vectors\n \n Arguments:\n x_a (array): shape [m_features, ] a single vector a\n x_b (array): shape [m_features, ] a single vector b\n \n Returns:\n distance (float): distance between vectors x_a and x_b\n \"\"\"\n \n # YOUR CODE HERE\n # Each x_a, x_b are examples in D. They each have m features \n # Steps: \n # 1. find the difference between each corresponding element in x_a and x_b. Store in array\n # 2. square each of these values \n # 3. Sum all these elements together. And take the root\n \n distance = np.sum((x_a - x_b)**2)**(1/2)\n \n #raise NotImplementedError()\n return distance\n```\n\n\n```python\n# Free cell\nD = np.array([[1, 4], [2, 5], [2, 2], [3, 1], [4, 3], [5, 1]])\nxt = np.array([3, 2])\n\ndist_list = []\n\nfor example in D:\n dist_list.append(euclideanDistance(example, xt))\n\nprint(dist_list)\n```\n\n [2.8284271247461903, 3.1622776601683795, 1.0, 1.0, 1.4142135623730951, 2.23606797749979]\n\n\n\n```python\n# The following tests are visible to you\nx1_grade = np.array((-1.0, 2.0))\nx2_grade = np.array((2.5, -2.0))\nassert euclideanDistance(x1_grade, x2_grade) == 5.315072906367325\n\nx1_grade = np.array((1.0, -1.0, 0))\nx2_grade = np.array((-2.0, 2.6, 1.8))\nassert euclideanDistance(x1_grade, x2_grade) == 5.019960159204453\n\n```\n\n# Task 2: Calculate list of distances\nFor the kNN algorithm you need to generate the distances between a single test example and all possible training examples.To do this you will need to write a function that takes in a test example and a list of examples, calculates the distance between the test example and each of the other example, and outputs a list of distances. The distances should be in the correct order as they correspond to a specific training example. To give you an idea what the output should be:\n\n$$\n\\mathcal{distance\\_list} = \\left[d\\left(\\mathbf{x}^{[t]}, \\mathbf{x}^{[1]}\\right), \\ldots, d\\left(\\mathbf{x}^{[t]}, \\mathbf{x}^{[n]}\\right)\\right]\n$$\n\nwhere $d\\left(\\mathbf{x}^{[t]}, \\mathbf{x}^{[1]}\\right)$ is the distance function from task 1\n\nThe distances must be stored in a Python list, not a numpy array.\n\nSome helpful functions:\\\nPython's built-in `append()` function\n\n\n```python\ndef calculateDistances(x_test, X_in):\n \"\"\"\n Calculates the distance between a single test example, x_test,\n and a list of examples X_in. \n \n Args:\n x_test (array): shape [n_features,] a single test example\n X_in (array): shape [n_samples, n_features] a list of examples to compare against.\n \n Returns:\n distance_list (list of float): The list containing the distances \n \"\"\"\n \n distance_list = []\n for example in X_in:\n distance_list.append(euclideanDistance(example, x_test))\n return distance_list\n```\n\n\n```python\n# Free cell\nD = np.array([[1, 4], [2, 5], [2, 2], [3, 1], [4, 3], [5, 1]])\nxt = np.array([3, 2])\n\ndist_list = calculateDistances(xt, D)\n\nprint(dist_list)\n```\n\n [2.8284271247461903, 3.1622776601683795, 1.0, 1.0, 1.4142135623730951, 2.23606797749979]\n\n\n\n```python\n# The following tests are visible to you\nx1_grade = np.array((1.0, -1.0))\nx2_grade = np.array([(2.0, -1.0),\n (-1.5, 2.5),\n (-2, -2),\n (0, 0)])\n\nassert calculateDistances(x1_grade, x2_grade) == [1.0, 4.301162633521313, 3.1622776601683795, 1.4142135623730951]\n\n```\n\n# Task 3: Determine k Nearest Neighbours\nThis task is broken into subtasks that will create a set of the k nearest neighbours to a single test example.\n$$\n\\mathcal{D}_k = \\{(\\mathbf{x}^{[i]}, \\mathbf{y}^{[i]}), \\ldots, (\\mathbf{x}^{[k]}, \\mathbf{y}^{[k]})\\}\n$$\n## Task 3.1 Sorting the distances and returning indices \nTo find the k nearest neighbours you first need to sort the list of distances in ascending order. For a naive kNN we don't care about the actual distances, so we only need to know which examples are responsible for the k smallest distances. We can do this by sorting the list of distances while keeping track of the corresponding indices so that we can pull the examples from the original training data at those indices. \n\nYour function must return a numpy array (it will make indexing the original dataset easier compared to python lists)\n\nSome helpful functions:\\\n`np.argsort()`\n\n\n```python\ndef kNearestIndices(distance_list, k):\n \"\"\"\n Determines the indices of the k nearest neighbours\n \n Arguments:\n distance_list (list of float): list of distances between a test point \n and every training example\n k (int): the number of nearest neighbours to consider\n \n Returns:\n k_nearest_indices (array of int): shape [k,] array of the indices \n corresponding to the k nearest neighbours\n \"\"\"\n \n # YOUR CODE HERE\n k_nearest_indices = np.array( np.argsort(distance_list)[:k] )\n return k_nearest_indices\n```\n\n\n```python\n# Free cell\nD = np.array([[1, 4], [2, 5], [2, 2], [3, 1], [4, 3], [5, 1]])\nxt = np.array([3, 2])\n\ndl = calculateDistances(xt, D)\n\nkNearestIndices(dl, 3) + 1\n```\n\n\n\n\n array([3, 4, 5])\n\n\n\n\n```python\n# The following tests are visible to you\ndistance_list_grade = [5.0, 3.5, 2.5, 1.0]\nk_grade = 3\nassert kNearestIndices(distance_list_grade, k_grade).tolist() == [3, 2, 1]\n\ndistance_list_grade = [5.0, 3.0, 3.5, 1.0, 10.0]\nk_grade = 4\nassert kNearestIndices(distance_list_grade, k_grade).tolist() == [3, 1, 2, 0]\n\n\n```\n\n## Task 3.2: Create $\\mathcal{D}_k$\nNow write a function that samples the original training set to produce the set of k nearest neighbours. \nFor now the function should return the `X_k` and `Y_k` data matrices seperately as indicated.\n\n\n```python\ndef kNearestNeighbours(k_nearest_indices, X_in, Y_in):\n \"\"\"\n Creates the dataset of k nearest neighbours\n \n Arguments:\n k_nearest_indices (array of int): shape [k,] array of the indices \n corresponding to the k nearest neighbours\n X_in (array): shape [n_examples, n_features] the example data matrix to sample from\n Y_in (array): shape [n_examples, ] the label data matrix to sample from\n \n Returns:\n X_k (array): shape [k, n_features] the k nearest examples\n Y_k (array): shape [k, ] the labels corresponding to the k nearest examples\n \"\"\"\n \n X_k = []\n Y_k = []\n\n for i in k_nearest_indices:\n X_k.append(X_in[i])\n Y_k.append(Y_in[i])\n \n X_k = np.array(X_k)\n Y_k = np.array(Y_k)\n return X_k, Y_k\n```\n\n\n```python\n# Free cell\nD = np.array([([1, 4], 1), ([2, 5], 1), ([2, 2], 1), ([3, 1], 0), ([4, 3], 0), ([5, 1], 0)])\nxt = np.array([3, 2])\n\nX = []\nY = []\nfor p in D:\n X.append(p[0])\n Y.append(p[1])\nX = np.array(X)\nY = np.array(Y)\n\n\ndl = calculateDistances(xt, X)\nkNN = kNearestIndices(dl, 3) \n\nkNearestNeighbours(kNN, X, Y)\n```\n\n\n\n\n (array([[2, 2],\n [3, 1],\n [4, 3]]),\n array([1, 0, 0]))\n\n\n\n\n```python\n# The following tests are visible to you\n\n# dummy dataset for autograding purposes\nX_train_grade = np.array([[1, 1],\n [0, 2],\n [1, 2],\n [2, 2],\n [10, 10],\n [5, 10],\n [6, 6],\n [2, 3]])\nY_train_grade = np.array([0, 0, 0, 0, 1, 1, 1, 0])\n\nX_k_grade, Y_k_grade = kNearestNeighbours([0, 1, 3], X_train_grade, Y_train_grade)\nassert np.equal(X_k_grade, np.array([[1, 1],[0, 2],[2, 2]])).all()\nassert np.equal(Y_k_grade, np.array([0, 0, 0])).all()\n\n```\n\n# Task 4: Predict Class\nYou can now write a function to predict the class of a test example by choosing the class the appears most frequently in ground truth labels for the k nearest neighbours i.e. the mode.\n$$\nh(\\mathbf{x}^{[t]}) = mode(\\{y^{[i]}, \\ldots, y^{[k]}\\})\n$$\n\nSome helpful functions:\\\n`mode()` function from scipy. \n\n\n```python\nfrom scipy.stats import mode\ndef predict(x_test, X_in, Y_in, k):\n \"\"\"\n Predicts the class of a single test example\n \n Arguments:\n x_test (array): shape [n_features, ] the test example to classify\n X_in (array): shape [n_input_examples, n_features] the example data matrix to sample from\n Y_in (array): shape [n_input_labels, ] the label data matrix to sample from\n \n Returns:\n prediction (array): shape [1,] the number corresponding to the class \n \"\"\"\n \n distance_list = calculateDistances(x_test, X_in)\n kNN_indices = kNearestIndices(distance_list, k)\n X_k, Y_k = kNearestNeighbours(kNN_indices, X_in, Y_in)\n prediction = mode(Y_k, axis=None)[0]\n\n return prediction\n```\n\n\n```python\n# Free cell\nfrom scipy.stats import mode\nk = 3\nD = np.array([([1, 4], 1), ([2, 5], 1), ([2, 2], 1), ([3, 1], 0), ([4, 3], 0), ([5, 1], 0)])\nxt = np.array([3, 2])\n\nX = []\nY = []\nfor p in D:\n X.append(p[0])\n Y.append(p[1])\nX = np.array(X)\nY = np.array(Y)\n\n\ndl = calculateDistances(xt, X)\nkNI = kNearestIndices(dl, k) \n\nkNN = kNearestNeighbours(kNI, X, Y)\nDk = list(zip(kNN[0].tolist(), kNN[1].tolist()))\n\np = predict(xt, X, Y, k)\nprint( p == 0)\nprint(type(p))\n```\n\n [ True]\n \n\n\n\n```python\n# The following tests are visible to you\n\n# dummy dataset for autograding purposes\nX_train_grade = np.array([[1, 1],\n [0, 2],\n [2, 1],\n [1, 3],\n [10, 10],\n [5, 10],\n [6, 8],\n [2, 3]])\nY_train_grade = np.array([0, 0, 0, 0, 1, 1, 1, 0])\n\nx1_grade = np.array([1, 2])\nk_grade = 3\nassert predict(x1_grade, X_train_grade, Y_train_grade, k_grade) == 0\n\nx1_grade = np.array([6, 9])\nk_grade = 2\nassert predict(x1_grade, X_train_grade, Y_train_grade, k_grade) == 1\n\n```\n\n# Task 5: Predict for an entire batch of test examples\nAfter you can successfully classify a single test example you need to repeat this across an entire batch of examples so we can apply performance metrics to assess the model.\n\\begin{align}\n\\hat{\\mathbf{Y}}(\\mathbf{X}_{test}) &= \\{h(\\mathbf{x}_{test}^{[i]}), \\ldots, h(\\mathbf{x}_{test}^{[j]})\\} \\\\\n&= \\{\\hat{y}^{[1]}, \\ldots, \\hat{y}^{[j]}\\}\n\\end{align}\n\nSklearn and many other machine learning libraries will provide the data in terms of numpy arrays or similar (i.e. the tensors are commonly used by libraries such as tensorflow and pytorch and in most cases will work similarly to numpy arrays). If you take a slice of label data for example: \\\nSlicing the first 3 labels from Y, `Y[:3] => array([0, 1, 1])`. The shape of this would be (n_train_labels, ) *more generally (n_train_labels, n_output_features) if your output is a vector. If you had a python list it would appear as `Y[:3] => [0, 1, 1]`\n\nYou want to make sure that a batch of predicted outputs from your model matches the same form as a batch of labels for when you start making calculations such as accuracy. e.g, you want `y_hat.shape => (n_test_labels,)` to have the same shape as the lables `y.shape => (n_test_labels,)`. \n\nMost libraries will have this as part of how they create their models, but when building your own algorithms you may have intermediate steps that do not produce it exactly like this. These kinds of errors regarding data shape and dimensions pop up very often in practise. \n\nSome helpful functions:\\\nTo combine multiple arrays: `np.concatenate()` *beware of axis when concatenating or for convenience `np.vstack()`\nTo change the shape of an array: `ndarray.reshape(shape)` or sometimes conventiently `ndarray.flatten()`\n\n\n```python\ndef predictBatch(X_t, X_in, Y_in, k):\n \"\"\"\n Performs predictions over a batch of test examples\n \n Arguments:\n X_t (array): shape [n_test_examples, n_features]\n X_in (array): shape [n_input_examples, n_features]\n Y_in (array): shape [n_input_labels, ]\n k (int): number of nearest neighbours to consider\n \n Returns:\n predictions (array): shape [n_test_examples,] the array of predictions\n \n \"\"\"\n predictions = []\n for x_t_i in X_t:\n predictions.append(predict(x_t_i, X_in, Y_in, k)[0])\n \n return np.array(predictions)\n```\n\n\n```python\nX_train_grade = np.array([[1, 1],\n [0, 2],\n [2, 1],\n [1, 3],\n [10, 10],\n [5, 10],\n [6, 8],\n [2, 3]])\nY_train_grade = np.array([0, 0, 0, 0, 1, 1, 1, 0])\n\nX_test_grade = np.array([[0, 0],\n [0, 1],\n [6, 10],\n [9, 8]])\nY_test_grade = np.array([0, 0, 1, 1])\nk_grade=2\n\np = predictBatch(X_test_grade, X_train_grade, Y_train_grade, k=k_grade)\nprint(p.shape)\nprint(type(p))\n```\n\n (4,)\n \n\n\n\n```python\n# The following tests are visible to you\n# dummy dataset for grading purposes\nX_train_grade = np.array([[1, 1],\n [0, 2],\n [2, 1],\n [1, 3],\n [10, 10],\n [5, 10],\n [6, 8],\n [2, 3]])\nY_train_grade = np.array([0, 0, 0, 0, 1, 1, 1, 0])\n\nX_test_grade = np.array([[0, 0],\n [0, 1],\n [6, 10],\n [9, 8]])\nY_test_grade = np.array([0, 0, 1, 1])\nk_grade=1\nassert np.equal(predictBatch(X_test_grade, X_train_grade, Y_train_grade, k=k_grade), Y_test_grade).all()\n```\n\n# Task 6: Accuracy metric\nIn this task you will create a function to measure the overall accuracy of your model. \n$$\nACC = \\frac{\\# correct predictions}{\\# total examples}\n$$\n\n\n```python\ndef accuracy(Y_pred, Y_test):\n \"\"\"\n Calculates the accuracy of the model \n \n Arguments:\n Y_pred (array): shape [n_test_examples,] an array of model predictions\n Y_test (array): shape [n_test_labels,] an array of test labels to \n evaluate the predictions against\n \n Returns:\n accuracy (float): the accuracy of the model\n \"\"\"\n assert(Y_pred.shape == Y_test.shape)\n \n correct = 0\n total = len(Y_test)\n\n for i in range(total):\n if (Y_pred[i] == Y_test[i]):\n correct += 1\n \n accuracy = correct/total\n return accuracy\n \n```\n\n\n```python\n# Free cell\nYt = np.array([0, 1, 0, 1])\nYp = np.array([1, 0, 1, 1])\n\naccuracy(Yp, Yt)\n```\n\n\n\n\n 0.25\n\n\n\n\n```python\n# The following tests are visible to you\n\nY_test_grade = np.array([0, 1, 0, 0])\nY_pred_grade = np.array([0, 1, 1, 0])\n\nassert accuracy(Y_pred_grade, Y_test_grade) == 0.75\n\nY_pred_grade = np.array([1, 0, 0, 0])\nassert accuracy(Y_pred_grade, Y_test_grade) == 0.5\n\n```\n\n# Task 7: Test your model\nNow you can combine the rest of the functions you've built into on function run your model with the generated training and test to data evaluate your model. This is really just to make running multiple tests more convenient. \n\n\n```python\ndef run(X_train, X_test, Y_train, Y_test, k):\n \"\"\"\n Evaluates the model on the test data\n \n Arguments:\n X_train (array): shape [n_train_examples, n_features]\n X_test (array): shape [n_test_examples, n_features]\n Y_train (array): shape [n_train_examples, ]\n Y_test (array): shape [n_test_examples, ]\n k (int): number of nearest neighbours to consider\n \n Returns:\n test_accuracy (float): the final accuracy of your model \n \"\"\"\n Y_pred = predictBatch(X_test, X_train, Y_train, k)\n test_accuracy = accuracy(Y_pred, Y_test)\n\n return test_accuracy\n```\n\n\n```python\nX_train_grade = np.array([[1, 1],\n [0, 2],\n [2, 1],\n [1, 3],\n [10, 10],\n [5, 10],\n [6, 8],\n [2, 3]])\nY_train_grade = np.array([0, 0, 0, 0, 1, 1, 1, 0])\n\nX_test_grade = np.array([[0, 0],\n [0, 1],\n [8, 3],\n [6, 10],\n [9, 8],\n [2, 9]])\nY_test_grade = np.array([0, 0, 0, 1, 1, 1])\nk_grade=1 #Outlier in i=3, using k=2 improves\n\nprint( run(X_train_grade, X_test_grade, Y_train_grade, Y_test_grade, k_grade) ) \n```\n\n 0.8333333333333334\n\n\n\n```python\n# I can't show you an example test because it would give away the answer\n```\n\n# End of Part 1\nThat concludes this part of assignment 1. \n", "meta": {"hexsha": "ab8e30f1bf075e50a02ce8b44954786749cff990", "size": 74253, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "part1.ipynb", "max_stars_repo_name": "yusufheylen/kNN_Distance_metric_learning", "max_stars_repo_head_hexsha": "b1f37391b2a4005069eac4c2522044e2c351400c", "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": "part1.ipynb", "max_issues_repo_name": "yusufheylen/kNN_Distance_metric_learning", "max_issues_repo_head_hexsha": "b1f37391b2a4005069eac4c2522044e2c351400c", "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": "part1.ipynb", "max_forks_repo_name": "yusufheylen/kNN_Distance_metric_learning", "max_forks_repo_head_hexsha": "b1f37391b2a4005069eac4c2522044e2c351400c", "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.7454954955, "max_line_length": 34696, "alphanum_fraction": 0.7327650061, "converted": true, "num_tokens": 5833, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086179043564153, "lm_q2_score": 0.9539660928564954, "lm_q1q2_score": 0.8667906721183464}} {"text": "# Euler Lagrange - pendulum with oscillating support \n\nWe define Lagrange function as a difference between kinetic and potential energy:\n\n\\begin{equation}\n\\label{eq:Lagangian}\nL = E_k - E_p\n\\end{equation}\n\nThen equation of motion are given by:\n\n\\begin{equation}\n\\label{eq:EL}\n\\frac{d}{dt} \\left (\\frac{\\partial L}{\\partial \\dot{\\varphi}}\\right ) - \\frac{\\partial L}{\\partial \\varphi} = 0\n\\end{equation}\n\nSince this formulation in invariant with respect to the change of system off coordinates, we can use it for many problems in mechanics with constraints. \n\n \n\n## System definition\n\nLet us define a system, \n\n\n```python\nload('cas_utils.sage')\n```\n\n\n```python\nvar('l g w0')\nxy_wsp = ['x','y']\nuv_wsp = [('phi',r'\\varphi')]\n\nto_fun, to_var = make_symbols(xy_wsp, uv_wsp)\n```\n\n### Horizontal oscillations of a support point\n\nWe parametrize the system similarily to mathematical pendulum, \n\n\\begin{eqnarray}\n\\label{eq:parametic}\nx = a \\sin\\left(\\omega t\\right) + l \\sin\\left({\\varphi}\\right) \\\\\ny = -l \\cos\\left({\\varphi}\\right)\n\\end{eqnarray}\n\n\n\n\n```python\n# horizontal\nvar('a omega t')\nx2u = {x:l*sin(phi)+a*sin(omega*t),y:-l*cos(phi)}\nshowmath(x2u)\n```\n\n**Step 1: Kinetic energy**\n\n\nWe have to write kinetic energy in terms of generalized coordinates:\n\n\\begin{equation}\n\\label{eq:Ekin}\n E_k = \\frac{1}{2}(\\dot x^2 + \\dot y^2)\n\\end{equation}\n\nUsing transformation dictionary, to generalized coordinates we have $E_k(\\varphi,,\\dot\\varphi)$:\n\n\n```python\nEk = 1/2*sum([x_.subs(x2u).subs(to_fun).diff(t).subs(to_var)^2 for x_ in [x,y]])\nEk = Ek.trig_simplify()\nshowmath(Ek)\n```\n\n**Step 2: Potential energy**\n\nSimilarily we have to express potential energy:\n\n\\begin{equation}\n\\label{eq:Ekin}\n E_p = g y\n\\end{equation}\n\nas a function of $E_P(\\varphi)$\n\n\n```python\nEp = g*y.subs(x2u)\nshowmath(Ep)\n```\n\n**Step 3: Langranian**\n\nNow we have Lagrangian $L(\\varphi,\\dot\\varphi)$:\n\n\n```python\nL = Ek - Ep\nshowmath(L)\n```\n\n## Derivation of equations of motion\n\nUsing Euler-Lagrange formulas \\ref{eq:EL} we write equation of motion in generalized coordinate $\\varphi$. Note, we can differentiate over $\\varphi$ and $\\dot\\varphi$. However to perform time derivative we first replace symbols representing variables with functions (i.e. Sage symbolic functions) of time. We have ``to_fun`` dictionary which automatizes this step. Then we use symbolic differenctiation ``diff``. After this operation we bring thhe result back to symbolic variable $\\varphi$ and $\\dot\\varphi$ with ``to_var`` dictionary.\n\n\n```python\nEL1 = L.diff(phid).subs(to_fun).diff(t).subs(to_var) - L.diff(phi)\n```\n\n\n```python\nshowmath(EL1)\n```\n\n## Analysis\n\n### Small angle approximation\n\nLet see what happens if oscillations are small. We can expand in Taylor seried the equations of motion:\n\n\n```python\neq_lin = EL1.taylor(phi,0,1)\nshowmath(eq_lin)\n```\n\n\n```python\nvar('alpha,omega0')\neq_lin2 = (eq_lin/l^2).expand().subs({a:l*alpha,g:l*omega0^2})\nshowmath(eq_lin2)\n```\n\nWe see that the equations are essentially equivalent to forced harmonic oscillator. The difference might be that the effective amplitude of forcing depends on forcing frequency.\n\n\n```python\nassume(g>0)\nassume(omega0>0)\nphi_anal = desolve((eq_lin/l^2).expand()\\\n .subs({a:l*alpha,g:l*omega0^2})\\\n .subs(to_fun).subs({l:1}),\\\n dvar=Phi,ivar=t,contrib_ode=True)\nshowmath(phi_anal)\n```\n\n\n```python\nshowmath(eq_lin2)\n```\n\n### Numerical integration\n\nWe can numerically compare if the linear approximation works for selected initial conditions and parameters. For this purpose we need to solve Euler-Lagrange equation for $\\ddot\\varphi$, and for following system od 1st order ODEs:\n\n\\begin{eqnarray}\n\\label{eq:ode}\n\\frac{d\\varphi}{dt} &=& \\dot\\varphi\\\\\n\\frac{d\\dot\\varphi}{dt} &=& \\frac{a \\omega^{2} \\cos\\left({\\varphi}\\right) \\sin\\left(\\omega t\\right)}{l} - \\frac{g \\sin\\left({\\varphi}\\right)}{l}\n\\end{eqnarray}\n\nNote that we threat $\\varphi$ and $\\dot\\varphi$ as independent variables. Since in Sage we use formulas where there are represented by different symbolic variables: `phi` and `dphi`, there will be no confusion of \"dot\" and derivative operator. \n\n\n\n```python\nrhs = EL1.solve(phidd)[0].rhs()\nshowmath(rhs().expand())\n```\n\nLinear system can be derived in similar way:\n\n\n```python\nrhs_lin = eq_lin.solve(phidd)[0].rhs()\nshowmath(rhs_lin)\n```\n\n\n```python\npars = {l:1,g:1,a:.03,omega:1.31}\nt_end = 60\nw0 = sqrt(g/l).subs(pars)\n```\n\nNow we can plug the system of ODE into ``desolve_odeint`` solver:\n\n\n```python\node = [phid, rhs.subs(pars)]\ntimes = srange(0,t_end,0.1)\nics = [0.0, 0.1]\nsol = desolve_odeint(ode, ics, times, [phi, phid])\nline( zip(times,sol[::1,0]),figsize=(6,2), )\n```\n\n\n```python\node_lin = [phid, rhs_lin.subs(pars)]\ntimes = srange(0,t_end,0.1)\nics = [0.0, 0.1]\nsol_lin = desolve_odeint(ode_lin, ics, times, [phi,phid])\n\nline( zip(times[0:],sol[0:,0]),figsize=(6,2) )\\\n +line( zip(times[0:],sol_lin[0:,0]),color='red')\n\n```\n\nWe see that for small oscillations the for some time. Then they diverge. One can experiment and simulate both systems for longer times to see that the divergence grows. Also larger amplitudes of driving will make them differ significantly.\n\n### Vertical oscillations\n\nIn the case of vertical oscillations of a support point, the transformation to generalized coordinates reads:\n\n\\begin{eqnarray}\n\\label{eq:oscil_vert}\nx = l \\sin\\left({\\varphi}\\right)\\\\\ny= -a \\cos\\left(\\omega t\\right) - l \\cos\\left({\\varphi}\\right),\n\\end{eqnarray}\n\n\n```python\n# vertical\nvar('a omega t')\nx2u = {x:l*sin(phi), y:-l*cos(phi)-a*cos(omega*t)}\nshowmath(x2u)\n```\n\nLet us once again calculate Lagrangian and derive symbolically equations of motion:\n\n\n```python\nEk = 1/2*sum([x_.subs(x2u).subs(to_fun).diff(t).subs(to_var)^2 for x_ in [x,y]])\nEk = Ek.trig_simplify()\nEp = g*y.subs(x2u)\nL = Ek - Ep\nEL1 = L.diff(phid).subs(to_fun).diff(t).subs(to_var) - L.diff(phi)\nshowmath(EL1)\n```\n\n\n```python\nrhs = EL1.solve(phidd)[0].rhs()\nshowmath( rhs.expand().collect(sin(phi)) )\n```\n\nLet's try to obtain a linear approximation for small $\\varphi$, as in previous case:\n\n\n```python\nshowmath(EL1.taylor(phi,0,1) )\n```\n\nWe see that in this case we do not obtain a harmonic oscillator. Forcing term is multiplied by $\\varphi$, i.e. the linearized equation is fundamentally different.\n\n### Stable inverted pendulum\n\nVertical driving of a support point as a remarkable property - under some conditions the upper steady state can become a stable one. \n\nFor example for following parameters and initial condition:\n\n\n```python\npars = {l:1,a:.2,g:1,omega:10.}\nw0 = sqrt(g/l).subs(pars)\n\node = [phid, rhs.subs(pars) ]\ntimes = srange(0, 60, 0.1)\nics = [pi-1e-1, .0]\n\nsol = desolve_odeint(ode, ics, times, [phi,phid])\n\n#plt = line( zip(times,sol[::1,0]),figsize=(8,3), ticks=[None,pi/4],\\\n# tick_formatter=[None,pi],gridlines=[[],[pi.n()*i for i in range(-100,100,1)]])\nplt = line( zip(times,sol[::1,0]),figsize=(6,2) )\n\nplt.show()\n```\n\nWe observe that for above inital conditions the pendulum oscillates around **$x=\\pi$ state** which is normally unstable fix point. \n\n\n```python\npendulum = [vector([x,y]).subs(x2u).subs(pars).subs({phi:phi_,t:t_})\\\n for t_,phi_ in zip(times,sol[:,0])]\no_point = [vector([x,y]).subs(x2u).subs(l==0).subs(pars).subs(t==t_)\\\n for t_ in times ]\n```\n\n\n```python\n#@interact\ndef draw_pendulum(ith = slider(0, len(pendulum)-1,1)):\n p1,p2 = pendulum[ith], o_point[ith]\n plt = line( [p1,p2],xmin=-1, xmax=1, ymin=-1.4, ymax=1.4,\\\n aspect_ratio=1,figsize=2,axes=False, title='t=%0.2f'%times[ith])\n plt += points([p1,p2],color='red',size=30,gridlines=[None,[0]],\\\n figsize=3,axes=False)\n plt += line(pendulum[:ith],thickness=0.9,color='gray',zorder=-10)\n return plt\n```\n\n\n```python\n#draw_pendulum(1200).save('inverted_pend.png',figsize=8)\n```\n\nTime evolution of the inverted stable pendulum:\n\n\n\n\n\n### System with damping\n\nAdding damping to the system will make inverted state an stable atractor.\n\n$$\\ddot\\varphi = -2\\gamma \\dot\\varphi + ( -\\omega_0^2 - \\frac{a}{l} \\omega^2 \\cos(\\omega t))\\sin(\\varphi)$$\n\n\n```python\nvar('omega,omega0,gama,t,a')\npars = {l:1,a:0.152,omega0:1,omega:14.,gama:.1}\node = [phid,\\\n (-2*gama*phid+(-omega0^2-a/l*omega^2*cos(omega*t))*sin(phi)).subs(pars)]\ntimes = srange(0,30,0.01)\nics = [0,2.1]\nsol = desolve_odeint(ode,ics,times,[phi,phid])\nline( zip(times,sol[::1,0]),figsize=(8,2), ticks=[None,pi/4],\\\n tick_formatter=[None,pi],gridlines=[[],[pi.n()*i for i in range(-100,100,1)]])\n```\n\n\\newpage\n", "meta": {"hexsha": "11a552a489854de792000bbf6417f4355e6e9dfc", "size": 15755, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "05-Langrange_oscillating_support.ipynb", "max_stars_repo_name": "marcinofulus/Mechanics_with_SageMath", "max_stars_repo_head_hexsha": "6d13cb2e83cd4be063c9cfef6ce536564a25cf57", "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": "05-Langrange_oscillating_support.ipynb", "max_issues_repo_name": "marcinofulus/Mechanics_with_SageMath", "max_issues_repo_head_hexsha": "6d13cb2e83cd4be063c9cfef6ce536564a25cf57", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-01-30T16:45:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-30T16:45:58.000Z", "max_forks_repo_path": "05-Langrange_oscillating_support.ipynb", "max_forks_repo_name": "marcinofulus/Mechanics_with_SageMath", "max_forks_repo_head_hexsha": "6d13cb2e83cd4be063c9cfef6ce536564a25cf57", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-11-15T08:26:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-12T13:07:16.000Z", "avg_line_length": 26.3021702838, "max_line_length": 552, "alphanum_fraction": 0.5386861314, "converted": true, "num_tokens": 2714, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.953966096291997, "lm_q2_score": 0.9086178950769319, "lm_q1q2_score": 0.8667906663875921}} {"text": "---\ntitle: \"The Monte Carlo Approach\"\nsummary: \"Simulation is easier than algebra\"\ndate: 2020-05-10\nsource: jupyter\n---\n\nIn *Monte Carlo* approaches, we use random simulations to answer questions \nthat might otherwise require some difficult equations.\nConfusingly, they're also known in some fields \nas *numerical* approaches, and are contrasted with *analytic* approaches,\nwhere you just work out the correct equation.\n[Wikipedia tells us](https://en.wikipedia.org/wiki/Monte_Carlo_method#History) that,\nyes, Monte Carlo methods are named after the casino.\n\nThe best-known Monte Carlo method is \n[Markov Chain Monte Carlo](https://en.wikipedia.org/wiki/Markov_chain_Monte_Carlo),\nwhich comes up a lot in Bayesian statistics.\nIn this post, I cover a much simpler example.\nHere's a simple Monte Carlo example.\nLet's say you want to know the area of a circle\nwith a radius of $r$.\nWe'll use a unit circle, $r=1$, in this example.\n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib import rcParams\nimport seaborn as sns\nsns.set_style('whitegrid')\nrcParams['figure.figsize'] = (6, 4)\nrcParams['font.size'] = 18\n\ndef circle_plot():\n fig, ax = plt.subplots(figsize=(5, 5))\n plt.hlines([-1, 1], -1, 1)\n plt.vlines([-1, 1], -1, 1)\n plt.plot([0, 1], [0, 0], color='k')\n plt.scatter(0, 0, marker='+', color='k')\n plt.xlim(-1.05, 1.05)\n plt.ylim(-1.05, 1.05)\n circle = plt.Circle((0, 0), 1, facecolor='None', edgecolor='r')\n ax.add_artist(circle)\n return fig, ax\n\ncircle_plot();\n```\n\nAnalytically, you know that the answer is \n\n$$\\text{Area} = \\pi r^2$$ \n\nWhat if we didn't know this equation?\nThe Monte Carlo solution is as follows.\nWe know that the area of the bounding square is $2r \\times 2r = 4r^2$\nWe need to figure out what proportion of this square is taken up by the circle.\nTo find out, we randomly select a large number of points in the square,\nand check if they're within $r$ of the center point $[0, 0]$.\n\n\n```python\nn = 1000 # Number of points to simulate\nx = np.random.uniform(low=-1, high=1, size=n)\ny = np.random.uniform(low=-1, high=1, size=n)\n# Distance from center (Pythagoras)\ndist_from_origin = np.sqrt(x**2 + y**2)\n# Check is distance is less than radius\nis_in_circle = dist_from_origin < 1\n\n# Plot results\ncircle_plot()\nplt.scatter(x[is_in_circle], y[is_in_circle], color='b', s=2) # Points in circle\nplt.scatter(x[~is_in_circle], y[~is_in_circle], color='k', s=2); # Points outside circle\n\nm = is_in_circle.mean()\nprint('%.4f of points are in the circle' % m)\n```\n\nSince the area of the square is $4r^2$,\nand the circle takes up ~$0.78$ of the square,\nthe area of the circle is roughly \n\n$$\n\\begin{align}\n\\text{Area} \n &\\approx 0.78 \\times 4r^2 \\newline\n &= 3.14r^2 \\newline\n &\\approx \\pi r^2\n\\end{align}\n$$\n\nWe've discovered $\\pi$.\n", "meta": {"hexsha": "d6c8114fd53b42410fb00e6f4aaadb06d4505217", "size": 54419, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "content/post/montecarlo/index.ipynb", "max_stars_repo_name": "EoinTravers/hugo.eointravers.com", "max_stars_repo_head_hexsha": "62c493e8022ba800f7491745c178eef4e403016c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-08-24T09:55:27.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-24T09:55:27.000Z", "max_issues_repo_path": "content/post/montecarlo/index.ipynb", "max_issues_repo_name": "EoinTravers/hugo.eointravers.com", "max_issues_repo_head_hexsha": "62c493e8022ba800f7491745c178eef4e403016c", "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/post/montecarlo/index.ipynb", "max_forks_repo_name": "EoinTravers/hugo.eointravers.com", "max_forks_repo_head_hexsha": "62c493e8022ba800f7491745c178eef4e403016c", "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": 294.1567567568, "max_line_length": 31200, "alphanum_fraction": 0.9247872986, "converted": true, "num_tokens": 833, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191322715435, "lm_q2_score": 0.9073122226137632, "lm_q1q2_score": 0.8667727252067458}} {"text": "# Part 1 - Scalars and Vectors\n\nFor the questions below it is not sufficient to simply provide answer to the questions, but you must solve the problems and show your work using python (the NumPy library will help a lot!) Translate the vectors and matrices into their appropriate python representations and use numpy or functions that you write yourself to demonstrate the result or property. \n\n\n```\n# importing the libraries used in class\n\nimport matplotlib.pyplot as plt\nimport math\nimport numpy as np\nfrom mpl_toolkits.mplot3d import Axes3D\n```\n\n## 1.1 Create a two-dimensional vector and plot it on a graph\n\n\n```\n# Done in class\n# plt.arrow(x,y,dx,dy) draws an arrow from (x,y) to (dx,dy) \n# xlim and ylim is range of the borders of the graph, title sets the title\n\ntwod_vector = [0.5,0.5]\nplt.arrow(0,0,twod_vector[0],twod_vector[1],head_width=0.02,head_length=0.02,color=\"green\")\nplt.xlim(0,1)\nplt.ylim(0,1)\nplt.title(\"Two Dimensional Vector\")\nplt.show()\n```\n\n## 1.2 Create a three-dimensional vecor and plot it on a graph\n\n\n```\n# Done in class\n\nvector_3d = [0.6, 0.8, 0.3]\nvector_3d_v = np.array([[0,0,0,0.6,0.8,0.3]])\n\n# From what I understand, quiver creates a vector from point (X,Y,Z) to (U,V,W) so in this case the shown vector is from (0,0,0) to (0.6,0.8,0.3)\n# The line below makes X, Y, Z, U, V, W into 1 element tuples with the corresponding value in the array, don't know why \"X, Y, Z, U, V, W = 0,0,0,0.6,0.8,0.3\" wasn't used instead\nX, Y, Z, U, V, W = zip((*vector_3d_v))\nfig = plt.figure()\nax = fig.add_subplot(111,projection='3d')\nax.quiver(X,Y,Z,U,V,W,length=1)\nax.set_xlim([0,1])\nax.set_ylim([0,1])\nax.set_zlim([0,1])\nax.set_xlabel(\"X\")\nax.set_ylabel(\"Y\")\nax.set_zlabel(\"Z\")\nplt.show()\n```\n\n\n```\n# First 3 lines of the above code block is replaced by the 1st line in this code block, same output\nX, Y, Z, U, V, W = 0,0,0,0.6,0.8,0.3\nfig = plt.figure()\nax = fig.add_subplot(111,projection='3d')\nax.quiver(X, Y, Z, U, V, W,length=1)\nax.set_xlim([0,1])\nax.set_ylim([0,1])\nax.set_zlim([0,1])\nax.set_xlabel(\"X\")\nax.set_ylabel(\"Y\")\nax.set_zlabel(\"Z\")\nplt.show()\n```\n\n## 1.3 Scale the vectors you created in 1.1 by $5$, $\\pi$, and $-e$ and plot all four vectors (original + 3 scaled vectors) on a graph. What do you notice about these vectors? \n\n\n```\n# I use the math library to get e and pi.\n# I need to plot them from biggest to smallest so the smallest ones don't get covered.\n# These vectors are all in the same direction. Each of these vectors can be multiplied by a factor to be equal to any of these vectors.\n\nplt.arrow(0,0,5*twod_vector[0],5*twod_vector[1],head_width=0.02,head_length=0.02,color=\"green\")\nplt.arrow(0,0,math.pi*twod_vector[0],math.pi*twod_vector[1],head_width=0.02,head_length=0.02,color=\"red\")\nplt.arrow(0,0,twod_vector[0],twod_vector[1],head_width=0.02,head_length=0.02,color=\"blue\")\nplt.arrow(0,0,-math.e*twod_vector[0],-math.e*twod_vector[1],head_width=0.02,head_length=0.02,color=\"yellow\")\nplt.xlim(-3,5)\nplt.ylim(-3,5)\nplt.title(\"Scaled Vectors\")\nplt.show()\n```\n\n## 1.4 Graph vectors $\\vec{a}$ and $\\vec{b}$ and plot them on a graph\n\n\\begin{align}\n\\vec{a} = \\begin{bmatrix} 5 \\\\ 7 \\end{bmatrix}\n\\qquad\n\\vec{b} = \\begin{bmatrix} 3 \\\\4 \\end{bmatrix}\n\\end{align}\n\n\n```\n# Similar to 1.1 except the vectors are given\n\na = [5,7]\nb = [3,4]\nplt.arrow(0,0,a[0],a[1],head_width=0.02,head_length=0.1,color=\"red\",width=0.05)\nplt.arrow(0,0,b[0],b[1],head_width=0.02,head_length=0.1,color=\"blue\",width=0.05)\nplt.xlim(0,8)\nplt.ylim(0,8)\n```\n\n## 1.5 find $\\vec{a} - \\vec{b}$ and plot the result on the same graph as $\\vec{a}$ and $\\vec{b}$. Is there a relationship between vectors $\\vec{a} \\thinspace, \\vec{b} \\thinspace \\text{and} \\thinspace \\vec{a-b}$\n\n\n```\n# The relationship between a,b, and a-b is that a-b+b = a. a-b = [2,3], if I add b to it, I'll get: a-b+b = [2+3,3+4] = [5,7] which is a\n# Also, (a-b)+b = b+(a-b), they all end up at the same place [5,7]\nplt.arrow(0,0,a[0],a[1],head_width=0.02,head_length=0.1,color=\"red\",width=0.05)\nplt.arrow(0,0,b[0],b[1],head_width=0.02,head_length=0.1,color=\"blue\",width=0.05)\nplt.arrow(0,0,a[0]-b[0],a[1]-b[1],head_width=0.02,head_length=0.1,color=\"purple\",width=0.05)\nplt.xlim(0,8)\nplt.ylim(0,8)\nplt.show()\n```\n\n## 1.6 Find $c \\cdot d$\n\n\\begin{align}\n\\vec{c} = \\begin{bmatrix}7 & 22 & 4 & 16\\end{bmatrix}\n\\qquad\n\\vec{d} = \\begin{bmatrix}12 & 6 & 2 & 9\\end{bmatrix}\n\\end{align}\n\n\n\n```\n# dot product is the sum of the products of the corresponding entries \n\ndef dot(x,y): # x and y are lists with the same length, representing vectors\n Dot = 0\n for n in range(len(x)):\n Dot+=x[n]*y[n]\n return Dot\n```\n\n\n```\ndot([7,22,4,16],[12,6,2,9])\n```\n\n\n\n\n 368\n\n\n\n\n```\n#np.dot returns the dot product of 2 arrays\n\nc = np.array([7,22,4,16])\nd = np.array([12,6,2,9])\n\nnp.dot(c,d)\n```\n\n\n\n\n 368\n\n\n\n## 1.7 Find $e \\times f$\n\n\\begin{align}\n\\vec{e} = \\begin{bmatrix} 5 \\\\ 7 \\\\ 2 \\end{bmatrix}\n\\qquad\n\\vec{f} = \\begin{bmatrix} 3 \\\\4 \\\\ 6 \\end{bmatrix}\n\\end{align}\n\n\n```\n# Cross Product\n# if p = [a,b,c] and q = [x,y,z] p cross q would be [bz-cy,-(az-cx),ay-bx]\n# these components are the determinants of the 2x2 matrix that excludes a column, for example: bz - cy is the determinant of the matrix below, it excludes the 1st column (a z)\n# b c\n# y z\n# so if e = [5,7,2] and f = [3,4,6], e cross f would be [(7)(6)-(2)(4),-((5)(6)-(3)(2)), (5)(4)-(3)(7)] = [42 - 8, -(30 - 6), 20-21] = [34,-24,1]\n```\n\n\n```\ndef cross(x,y): # x and y are vectors with 3 dimensions (lists with 3 numbers) in this instance\n a = x[1]*y[2] - x[2]*y[1]\n b = -(x[0]*y[2] - y[0]*x[2])\n c = x[0]*y[1] - x[1]*y[0]\n return [a,b,c]\n```\n\n\n```\ncross([5,7,2],[3,4,6])\n```\n\n\n\n\n [34, -24, -1]\n\n\n\n\n```\n# np.cross returns the cross product of 2 vectors\n\ne = np.array([5,7,2])\nf = np.array([3,4,6])\n\nnp.cross(e,f)\n```\n\n\n\n\n array([ 34, -24, -1])\n\n\n\n## 1.8 Find $||g||$ and then find $||h||$. Which is longer?\n\n\\begin{align}\n\\vec{g} = \\begin{bmatrix} 1 \\\\ 1 \\\\ 1 \\\\ 8 \\end{bmatrix}\n\\qquad\n\\vec{h} = \\begin{bmatrix} 3 \\\\3 \\\\ 3 \\\\ 3 \\end{bmatrix}\n\\end{align}\n\n\n```\n# ||x|| is the sqrt of the sum of squares of the values\n# ||g|| = sqrt(1^2 + 1^2 + 1^2 + 8^2) = sqrt(1+1+1+64) = sqrt(67)\n```\n\n\n```\ndef mag(vec): #vec is vector which is a list\n leng = 0\n for n in vec:\n leng+=n**2\n return leng**0.5\n```\n\n\n```\nprint(\"||g|| is\", mag([1,1,1,8])) #sqrt(67)\nprint(\"||h|| is\", mag([3,3,3,3])) #sqrt(36) \n\n```\n\n ||g|| is 8.18535277187245\n ||h|| is 6.0\n\n\n\n```\n# np.linalg.norm can also be used to figure out ||x||\n\ng = np.array([1,1,1,8]) \nh = np.array([3,3,3,3]) \n\nprint(\"||g|| is\", np.linalg.norm(g))\nprint(\"||h|| is\", np.linalg.norm(h))\n```\n\n ||g|| is 8.18535277187245\n ||h|| is 6.0\n\n\n# Part 2 - Matrices\n\n## 2.1 What are the dimensions of the following matrices? Which of the following can be multiplied together? See if you can find all of the different legal combinations.\n\\begin{align}\nA = \\begin{bmatrix}\n1 & 2 \\\\\n3 & 4 \\\\\n5 & 6\n\\end{bmatrix}\n\\qquad\nB = \\begin{bmatrix}\n2 & 4 & 6 \\\\\n\\end{bmatrix}\n\\qquad\nC = \\begin{bmatrix}\n9 & 6 & 3 \\\\\n4 & 7 & 11\n\\end{bmatrix}\n\\qquad\nD = \\begin{bmatrix}\n1 & 0 & 0 \\\\\n0 & 1 & 0 \\\\\n0 & 0 & 1\n\\end{bmatrix}\n\\qquad\nE = \\begin{bmatrix}\n1 & 3 \\\\\n5 & 7\n\\end{bmatrix}\n\\end{align}\n\n\n```\n# to multiply matrices, with dimensions rows by columns, the columns of 1st matrix = rows of 2nd matrix\n# and the product has rows of 1st matrix by columns of 2nd matrix\n# m*n matrix times n*p matrix equals m*p matrix\n\n# Purpose of the code below is to answer the question \"Which of the following [matrices] can be multiplied together?\"\n# Value is set to dimensions of corresponding Key matrix\n# Using dictionary so I can print out the letters.\n\nDimdict = {\"A\":[3,2],\n \"B\":[1,3],\n \"C\":[2,3],\n \"D\":[3,3],\n \"E\":[2,2]}\n\n\n# testings all 25 combinations, x[0] is rows, x[1] is columns, \n\nfor m in Dimdict:\n for n in Dimdict:\n if Dimdict[m][1]==Dimdict[n][0]:\n print(f'{m}{n} is a legal combination. The dimensions are {Dimdict[m]} * {Dimdict[n]}.')\n\n\n```\n\n AC is a legal combination. The dimensions are [3, 2] * [2, 3].\n AE is a legal combination. The dimensions are [3, 2] * [2, 2].\n BA is a legal combination. The dimensions are [1, 3] * [3, 2].\n BD is a legal combination. The dimensions are [1, 3] * [3, 3].\n CA is a legal combination. The dimensions are [2, 3] * [3, 2].\n CD is a legal combination. The dimensions are [2, 3] * [3, 3].\n DA is a legal combination. The dimensions are [3, 3] * [3, 2].\n DD is a legal combination. The dimensions are [3, 3] * [3, 3].\n EC is a legal combination. The dimensions are [2, 2] * [2, 3].\n EE is a legal combination. The dimensions are [2, 2] * [2, 2].\n\n\n## 2.2 Find the following products: CD, AE, and BA. What are the dimensions of the resulting matrices? How does that relate to the dimensions of their factor matrices?\n\n\n```\n\n```\n\n## 2.3 Find $F^{T}$. How are the numbers along the main diagonal (top left to bottom right) of the original matrix and its transpose related? What are the dimensions of $F$? What are the dimensions of $F^{T}$?\n\n\\begin{align}\nF = \n\\begin{bmatrix}\n20 & 19 & 18 & 17 \\\\\n16 & 15 & 14 & 13 \\\\\n12 & 11 & 10 & 9 \\\\\n8 & 7 & 6 & 5 \\\\\n4 & 3 & 2 & 1\n\\end{bmatrix}\n\\end{align}\n\n# Part 3 - Square Matrices\n\n## 3.1 Find $IG$ (be sure to show your work) 😃\n\nYou don't have to do anything crazy complicated here to show your work, just create the G matrix as specified below, and a corresponding 2x2 Identity matrix and then multiply them together to show the result. You don't need to write LaTeX or anything like that (unless you want to).\n\n\\begin{align}\nG= \n\\begin{bmatrix}\n13 & 14 \\\\\n21 & 12 \n\\end{bmatrix}\n\\end{align}\n\n## 3.2 Find $|H|$ and then find $|J|$.\n\n\\begin{align}\nH= \n\\begin{bmatrix}\n12 & 11 \\\\\n7 & 10 \n\\end{bmatrix}\n\\qquad\nJ= \n\\begin{bmatrix}\n0 & 1 & 2 \\\\\n7 & 10 & 4 \\\\\n3 & 2 & 0\n\\end{bmatrix}\n\\end{align}\n\n\n## 3.3 Find $H^{-1}$ and then find $J^{-1}$\n\n## 3.4 Find $HH^{-1}$ and then find $J^{-1}J$. Is $HH^{-1} == J^{-1}J$? Why or Why not? \n\nPlease ignore Python rounding errors. If necessary, format your output so that it rounds to 5 significant digits (the fifth decimal place).\n\n# Go Beyond: \n\nA reminder that these challenges are optional. If you finish your work quickly we welcome you to work on them. If there are other activities that you feel like will help your understanding of the above topics more, feel free to work on that. Topics from the Stretch Goals sections will never end up on Sprint Challenges. You don't have to do these in order, you don't have to do all of them. \n\n- Write a function that can calculate the dot product of any two vectors of equal length that are passed to it.\n- Write a function that can calculate the norm of any vector\n- Prove to yourself again that the vectors in 1.9 are orthogonal by graphing them. \n- Research how to plot a 3d graph with animations so that you can make the graph rotate (this will be easier in a local notebook than in google colab)\n- Create and plot a matrix on a 2d graph.\n- Create and plot a matrix on a 3d graph.\n- Plot two vectors that are not collinear on a 2d graph. Calculate the determinant of the 2x2 matrix that these vectors form. How does this determinant relate to the graphical interpretation of the vectors?\n\n\n", "meta": {"hexsha": "65845051b4d175a32e81287f7be242c673ef1acd", "size": 144264, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Copy_of_Vectors_and_Matricest.ipynb", "max_stars_repo_name": "dealom/Vectors-and-Matrices", "max_stars_repo_head_hexsha": "6edeb8b9d3e5852d2b63f08d17ac98ad1d731f33", "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_Vectors_and_Matricest.ipynb", "max_issues_repo_name": "dealom/Vectors-and-Matrices", "max_issues_repo_head_hexsha": "6edeb8b9d3e5852d2b63f08d17ac98ad1d731f33", "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_Vectors_and_Matricest.ipynb", "max_forks_repo_name": "dealom/Vectors-and-Matrices", "max_forks_repo_head_hexsha": "6edeb8b9d3e5852d2b63f08d17ac98ad1d731f33", "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": 167.7488372093, "max_line_length": 37982, "alphanum_fraction": 0.8764418011, "converted": true, "num_tokens": 3948, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067147399244, "lm_q2_score": 0.9196425300765949, "lm_q1q2_score": 0.8667692597576037}} {"text": "# Gaussian Distribution (Normal or Bell Curve)\n\nThink of a Jupyter Notebook file as a Python script, but with comments given the seriousness they deserve, meaning inserted Youtubes if necessary. We also adopt a more conversational style with the reader, and with Python, pausing frequently to take stock, because we're telling a story.\n\nOne might ask, what is the benefit of computer programs if we read through them this slowly? Isn't the whole point that they run blazingly fast, and nobody needs to read them except those tasked with maintaining them, the programmer cast?\n\nFirst, lets point out the obvious: even when reading slowly, we're not keeping Python from doing its part as fast as it can, and what it does would have taken a single human ages to do, and would have occupied a team of secretaries for ages. Were you planning to pay them? Python effectively puts a huge staff at your disposal, ready to do your bidding. But that doesn't let you off the hook. They need to be managed, told what to do.\n\nHere's what you'll find at the top of your average script. A litany of players, a congress of agents, need to be assembled and made ready for the job at hand. But don't worry, as you remember to include necessary assets, add them at will as you need them. We rehearse the script over and over while building it. Nobody groans, except maybe you, when the director says \"take it from the top\" once again.\n\n\n```python\nimport numpy as np\nimport scipy.stats as st\nimport matplotlib.pyplot as plt\nimport math\n```\n\nYou'll be glad to have np.linspace as a friend, as so often you know exactly what the upper and lower bounds, of a domain, might be. You'll be computing a range. Do you remember these terms from high school? A domain is like a pile of cannon balls that we feed to our cannon, which them fires them, testing our knowledge of ballistics. It traces a parabola. We plot that in our tables. A lot of mathematics traces to developing tables for battle field use. Leonardo da Vinci, a great artist, was also an architect of defensive fortifications.\n\nAnyway, np.linspace lets to give exactly the number of points you would like of this linear one dimensional array space, as a closed set, meaning -5 and 5 are included, the minimum and maximum you specify. Ask for a healthy number of points, as points are cheap. All they require is memory. But then it's up to you not to overdo things. Why waste CPU cycles on way too many points?\n\nI bring up this niggling detail about points as a way of introducing what they're calling \"hyperparameters\" in Machine Learning, meaning settings or values that come from outside the data, so also \"metadata\" in some ways. You'll see in other notebooks how we might pick a few hyperparameters and ask scikit-learn to try all combinations of same.\n\nHere's what you'll be saying then:\n\nfrom sklearn.model_selection import GridSearchCV #CV = cross-validation\n\n\n```python\ndomain = np.linspace(-5, 5, 100)\n```\n\nI know mu sounds like \"mew\", the sound a kitten makes, and that's sometimes insisted upon by sticklers, for when we have a continuous function, versus one that's discrete. Statisticians make a big deal about the difference between digital and analog, where the former is seen as a \"sampling\" of the latter. Complete data may be an impossibility. We're always stuck with something digital trying to approximate something analog, or so it seems. Turn that around in your head sometimes: we smooth it over as an approximation, because a discrete treatment would require too high a level of precision.\n\nThe sticklers say \"mu\" for continuous, but \"x-bar\" (an x with a bar over it) for plain old \"average\" of discrete sets. I don't see this conventions holding water necessarily, for one thing because it's inconvenient to always reach for the most fancy typography. Python does have full access to Unicode, and to LaTex, but do we have to bother? Lets leave that question for another day and move on to...\n\n## The Guassian (Binomial if Discrete)\n\n\n```python\nmu = 0 # might be x-bar if discrete\nsigma = 1 # standard deviation, more below\n```\n\nWhat we have here (below) is a typical Python numeric function, although it does get its pi from numpy instead of math. That won't matter. The sigma and mu in this function are globals and set above. Some LaTex would be in order here, I realize. Let me scavange the internet for something appropriate...\n\n$pdf(x,\\mu,\\sigma) = \\frac{1}{ \\sigma \\sqrt{2 \\pi}} e^{\\left(-\\frac{{\\left(\\mu - x\\right)}^{2}}{2 \\, \\sigma^{2}}\\right)}$\n\nUse of dollar signs is key.\n\nHere's another way, in a code cell instead of a Markdown cell.\n\n\n```python\nfrom IPython.display import display, Latex\n\nltx = '$ pdf(x,\\\\mu,\\\\sigma) = \\\\frac{1}{ \\\\sigma' + \\\n '\\\\sqrt{2 \\\\pi}} e^{\\\\left(-\\\\frac{{\\\\left(\\\\mu - ' + \\\n 'x\\\\right)}^{2}}{2 \\\\, \\\\sigma^{2}}\\\\right)} $'\ndisplay(Latex(ltx))\n```\n\n\n$ pdf(x,\\mu,\\sigma) = \\frac{1}{ \\sigma\\sqrt{2 \\pi}} e^{\\left(-\\frac{{\\left(\\mu - x\\right)}^{2}}{2 \\, \\sigma^{2}}\\right)} $\n\n\nI'm really tempted to try out [PrettyPy](https://github.com/charliekawczynski/prettyPy).\n\n\n```python\ndef g(x):\n return (1/(sigma * math.sqrt(2 * np.pi))) * math.exp(-0.5 * ((mu - x)/sigma)**2)\n```\n\nWhat I do below is semi-mysterious, and something I'd like to get to in numpy in more detail. The whole idea behind numpy is every function, or at least the unary ones, are vectorized, meaning the work element-wise through every cell, with no need for any for loops.\n\nMy Gaussian formula above won't natively understand how to have relations with a numpy array, unless we store it in vectorized form. I'm not claiming this will make it run any faster than under the control of for loops, we can test that. Even without a speedup, here we have a recipe for shortening our code.\n\nAs many have proclaimed around numpy: one of its primary benefits is it allows one to \"lose the loops\".\n\n\n```python\n%timeit vg = np.vectorize(g)\n```\n\n The slowest run took 5.55 times longer than the fastest. This could mean that an intermediate result is being cached.\n 100000 loops, best of 3: 4.1 µs per loop\n\n\nAt any rate, this way, with a list comprehension, is orders of magnitude slower:\n\n\n```python\n%timeit vg2 = np.array([g(x) for x in domain])\n```\n\n 1000 loops, best of 3: 263 µs per loop\n\n\n\n```python\nvg = np.vectorize(g)\n```\n\n\n```python\n%matplotlib inline\n%timeit plt.plot(domain, vg(domain))\n```\n\nI bravely built my own version of the Gaussian distribution, a continuous function (any real number input is OK, from negative infinity to infinity, but not those (keep it in between). The thing about a Gaussian is you can shrink it and grow it while keeping the curve itself, self similar. Remember \"hyperparamters\"? They control the shape. We should be sure to play around with those parameters.\n\nOf course the stats.norm section of scipy comes pre-equipped with the same PDF (probability distribution function). You'll see this curve called many things in the literature.\n\n\n```python\n%timeit plt.plot(domain, st.norm.pdf(domain))\n```\n\n\n```python\nmu = 0\nsigma = math.sqrt(0.2)\nplt.plot(domain, vg(domain), color = 'blue')\nsigma = math.sqrt(1)\nplt.plot(domain, vg(domain), color = 'red')\nsigma = math.sqrt(5)\nplt.plot(domain, vg(domain), color = 'orange')\nmu = -2\nsigma = math.sqrt(.5)\nplt.plot(domain, vg(domain), color = 'green')\nplt.title(\"Gaussian Distributions\")\n```\n\n[see Wikipedia figure](https://en.wikipedia.org/wiki/Gaussian_function#Properties)\n\nThese are Gaussian PDFs or Probability Density Functions.\n\n68.26% of values happen within -1 and 1.\n\n\n```python\nfrom IPython.display import YouTubeVideo\nYouTubeVideo(\"xgQhefFOXrM\")\n```\n\n\n\n\n\n\n\n\n\n\n\n```python\na = st.norm.cdf(-1) # Cumulative distribution function\nb = st.norm.cdf(1)\nb - a\n```\n\n\n\n\n 0.68268949213708585\n\n\n\n\n```python\na = st.norm.cdf(-2)\nb = st.norm.cdf(2)\nb - a\n```\n\n\n\n\n 0.95449973610364158\n\n\n\n\n```python\n# 99.73% is more correct than 99.72% \na = st.norm.cdf(-3)\nb = st.norm.cdf(3)\nb - a\n```\n\n\n\n\n 0.99730020393673979\n\n\n\n\n```python\n# 95%\na = st.norm.cdf(-1.96)\nb = st.norm.cdf(1.96)\nb - a\n```\n\n\n\n\n 0.95000420970355903\n\n\n\n\n```python\n# 99% \na = st.norm.cdf(-2.58)\nb = st.norm.cdf(2.58)\nb - a\n```\n\n\n\n\n 0.9901199684844586\n\n\n\n\n```python\nfrom IPython.display import YouTubeVideo\nYouTubeVideo(\"zZWd56VlN7w\")\n```\n\n\n\n\n\n\n\n\n\n\nWhat are the chances a value is less than -1.32?\n\n\n```python\nst.norm.cdf(-1.32)\n```\n\n\n\n\n 0.093417508993471787\n\n\n\nWhat are the chances a value is between -0.21 and 0.85?\n\n\n```python\n1 - st.norm.sf(-0.21) # filling in from the right (survival function)\n```\n\n\n\n\n 0.41683383651755768\n\n\n\n\n```python\na = st.norm.cdf(0.85) # filling in from the left\na\n```\n\n\n\n\n 0.80233745687730762\n\n\n\n\n```python\nb = st.norm.cdf(-0.21) # from the left\nb\n```\n\n\n\n\n 0.41683383651755768\n\n\n\n\n```python\na-b # getting the difference (per the Youtube)\n```\n\n\n\n\n 0.38550362035974994\n\n\n\nLets plot the integral of the Bell Curve. This curve somewhat describes the temporal pattern whereby a new technology is adopted, first by early adopters, then comes the bandwagon effect, then come the stragglers. Not the every technology gets adopted in this way. Only some do.\n\n\n```python\nplt.plot(domain, st.norm.cdf(domain))\n```\n\n[Standard Deviation](https://en.wikipedia.org/wiki/Standard_deviation)\n\nAbove is the Bell Curve integral.\n\nRemember the derivative is obtain from small differences: (f(x+h) - f(x))/x\n\nGiven x is our entire domain and operations are vectorized, it's easy enough to plot said derivative.\n\n\n```python\nx = st.norm.cdf(domain)\ndiff = st.norm.cdf(domain + 0.01)\nplt.plot(domain, (diff-x)/0.01)\n```\n\n\n```python\nx = st.norm.pdf(domain)\ndiff = st.norm.pdf(domain + 0.01)\nplt.plot(domain, (diff-x)/0.01)\n```\n\n\n```python\nx = st.norm.pdf(domain)\nplt.plot(domain, x, color = \"red\")\n\nx = st.norm.pdf(domain)\ndiff = st.norm.pdf(domain + 0.01)\nplt.plot(domain, (diff-x)/0.01, color = \"blue\")\n```\n\n# Integrating the Gaussian\n\nApparently there's no closed form, however sympy is able to do an integration somehow.\n\n\n```python\nfrom sympy import var, Lambda, integrate, sqrt, pi, exp, latex\n\nfig = plt.gcf()\nfig.set_size_inches(8,5)\nvar('a b x sigma mu')\npdf = Lambda((x,mu,sigma),\n (1/(sigma * sqrt(2*pi)) * exp(-(mu-x)**2 / (2*sigma**2)))\n)\ncdf = Lambda((a,b,mu,sigma),\n integrate(\n pdf(x,mu,sigma),(x,a,b)\n )\n)\ndisplay(Latex('$ cdf(a,b,\\mu,\\sigma) = ' + latex(cdf(a,b,mu,sigma)) + '$'))\n```\n\n\n$ cdf(a,b,\\mu,\\sigma) = - \\frac{1}{2} \\operatorname{erf}{\\left (\\frac{\\sqrt{2} \\left(a - \\mu\\right)}{2 \\sigma} \\right )} + \\frac{1}{2} \\operatorname{erf}{\\left (\\frac{\\sqrt{2} \\left(b - \\mu\\right)}{2 \\sigma} \\right )}$\n\n\n\n \n\n\nLets stop right here and note the pdf and cdf have been defined, using sympy's Lambda and integrate, and the cdf will be fed a lot of data, one hundred points, along with mu and sigma. Then it's simply a matter of plotting.\n\nWhat's amazing is our ability to get something from sympy that works to give a cdf, independently of scipy.stats.norm.\n\n\n```python\nx = np.linspace(50,159,100)\ny = np.array([cdf(-1e99,v,100,15) for v in x],dtype='float')\nplt.grid(True)\nplt.title('Cumulative Distribution Function')\nplt.xlabel('IQ')\nprint(type(plt.xlabel))\nplt.ylabel('Y')\nplt.text(65,.75,'$\\mu = 100$',fontsize=16)\nplt.text(65,.65,'$\\sigma = 15$',fontsize=16)\nplt.plot(x,y,color='gray')\nplt.fill_between(x,y,0,color='#c0f0c0')\nplt.show()\n```\n\nThe above is truly a testament to Python's power, or the Python ecosystem's power. We've brought in sympy, able to do symbolic integration, and talk LaTeX at the same time. That's impressive. Here's [the high IQ source](https://arachnoid.com/IPython/normal_distribution.html) for the original version of the above code.\n\nThere's no indefinite integral of the Gaussian, but there's a definite one. sympy comes with its own generic sympy.stats.cdf function which produces Lambdas (symbolic expressions) when used to integrate different types of probability spaces, such as Normal (a continuous PDF). It also accepts discrete PMFs as well.\n\n
\nExamples\n========\n    \n>>> from sympy.stats import density, Die, Normal, cdf\n>>> from sympy import Symbol\n    \n>>> D = Die('D', 6)\n>>> X = Normal('X', 0, 1)\n    \n>>> density(D).dict\n{1: 1/6, 2: 1/6, 3: 1/6, 4: 1/6, 5: 1/6, 6: 1/6}\n>>> cdf(D)\n{1: 1/6, 2: 1/3, 3: 1/2, 4: 2/3, 5: 5/6, 6: 1}\n>>> cdf(3*D, D > 2)\n{9: 1/4, 12: 1/2, 15: 3/4, 18: 1}\n    \n>>> cdf(X)\nLambda(_z, -erfc(sqrt(2)*_z/2)/2 + 1)\n
\n\n## LAB: convert the Normal Distribution Below to IQ Curve...\n\n\nThat means domain is 0-200, standard deviation 15, mean = 100.\n\n\n```python\ndomain = np.linspace(0, 200, 3000)\nIQ = st.norm.pdf(domain, 100, 15)\nplt.plot(domain, IQ, color = \"red\")\n```\n\n\n```python\ndomain = np.linspace(0, 200, 3000)\nmu = 100\nsigma = 15\nIQ = vg(domain)\nplt.plot(domain, IQ, color = \"green\")\n```\n", "meta": {"hexsha": "ae608d598bae3cec01df48fea259e6f867344a4d", "size": 219103, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "BellCurve.ipynb", "max_stars_repo_name": "4dsolutions/Python5", "max_stars_repo_head_hexsha": "8d80753e823441a571b827d24d21577446409b52", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2016-08-17T00:15:26.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-17T21:31:10.000Z", "max_issues_repo_path": "BellCurve.ipynb", "max_issues_repo_name": "4dsolutions/Python5", "max_issues_repo_head_hexsha": "8d80753e823441a571b827d24d21577446409b52", "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": "BellCurve.ipynb", "max_forks_repo_name": "4dsolutions/Python5", "max_forks_repo_head_hexsha": "8d80753e823441a571b827d24d21577446409b52", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2017-02-22T05:15:52.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-08T06:17:34.000Z", "avg_line_length": 216.0779092702, "max_line_length": 24088, "alphanum_fraction": 0.9042915889, "converted": true, "num_tokens": 3620, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.947381042195331, "lm_q2_score": 0.9149009532527357, "lm_q1q2_score": 0.8667598185980786}} {"text": "```python\nimport numpy as np\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\n```\n\n\n```python\nplt.style.use(['ggplot'])\n```\n\n# Create Data\n\n
Generate some data with:\n\\begin{equation} \\theta_0= 4 \\end{equation} \n\\begin{equation} \\theta_1= 3 \\end{equation} \n\nAdd some Gaussian noise to the data\n\n\n```python\nX = 2 * np.random.rand(100,1)\ny = 4 +3 * X+np.random.randn(100,1)\n```\n\nLet's plot our data to check the relation between X and Y\n\n\n```python\nplt.plot(X,y,'b.')\nplt.xlabel(\"$x$\", fontsize=18)\nplt.ylabel(\"$y$\", rotation=0, fontsize=18)\n_ =plt.axis([0,2,0,15])\n```\n\n# Analytical way of Linear Regression\n\n\n```python\nX_b = np.c_[np.ones((100,1)),X]\nprint(\"X_b shape: {}\".format(X_b.shape))\ntheta_best = np.linalg.inv(X_b.T.dot(X_b)).dot(X_b.T).dot(y)\nprint(theta_best)\n```\n\n X_b shape: (100, 2)\n [[4.24558664]\n [2.79700746]]\n\n\n
This is close to our real thetas 4 and 3. It cannot be accurate due to the noise I have introduced in data\n\n\n```python\nX_new = np.array([[0],[2]])\nX_new_b = np.c_[np.ones((2,1)),X_new]\ny_predict = X_new_b.dot(theta_best)\ny_predict\n```\n\n\n\n\n array([[ 4.00988308],\n [10.01872123]])\n\n\n\n
Let's plot prediction line with calculated:theta\n\n\n```python\nplt.plot(X_new,y_predict,'r-')\nplt.plot(X,y,'b.')\nplt.xlabel(\"$x_1$\", fontsize=18)\nplt.ylabel(\"$y$\", rotation=0, fontsize=18)\nplt.axis([0,2,0,15])\n```\n\n# Gradient Descent\n\n## Cost Function & Gradients\n\n

The equation for calculating cost function and gradients are as shown below. Please note the cost function is for Linear regression. For other algorithms the cost function will be different and the gradients would have to be derived from the cost functions\n\n\n\nCost\n\\begin{equation}\nJ(\\theta) = 1/2m \\sum_{i=1}^{m} (h(\\theta)^{(i)} - y^{(i)})^2 \n\\end{equation}\n\nGradient\n\n\\begin{equation}\n\\frac{\\partial J(\\theta)}{\\partial \\theta_j} = 1/m\\sum_{i=1}^{m}(h(\\theta^{(i)} - y^{(i)}).X_j^{(i)}\n\\end{equation}\n\nGradients\n\\begin{equation}\n\\theta_0: = \\theta_0 -\\alpha . (1/m .\\sum_{i=1}^{m}(h(\\theta^{(i)} - y^{(i)}).X_0^{(i)})\n\\end{equation}\n\\begin{equation}\n\\theta_1: = \\theta_1 -\\alpha . (1/m .\\sum_{i=1}^{m}(h(\\theta^{(i)} - y^{(i)}).X_1^{(i)})\n\\end{equation}\n\\begin{equation}\n\\theta_2: = \\theta_2 -\\alpha . (1/m .\\sum_{i=1}^{m}(h(\\theta^{(i)} - y^{(i)}).X_2^{(i)})\n\\end{equation}\n\n\\begin{equation}\n\\theta_j: = \\theta_j -\\alpha . (1/m .\\sum_{i=1}^{m}(h(\\theta^{(i)} - y^{(i)}).X_0^{(i)})\n\\end{equation}\n\n\n```python\ndef cal_cost(theta,X,y):\n '''\n Calculates the cost for given X and Y. The following shows and example of a single dimensional X\n theta = Vector of thetas \n X = Row of X's np.zeros((2,j))\n y = Actual y's np.zeros((2,1))\n \n where:\n j is the no of features\n '''\n \n m = len(y)\n \n predictions = X.dot(theta)\n cost = (1/2*m) * np.sum(np.square(predictions-y))\n return cost\n```\n\n\n```python\ndef gradient_descent(X,y,theta,learning_rate=0.01,iterations=100):\n '''\n X = Matrix of X with added bias units\n y = Vector of Y\n theta=Vector of thetas np.random.randn(j,1)\n learning_rate \n iterations = no of iterations\n \n Returns the final theta vector and array of cost history over no of iterations\n '''\n m = len(y)\n cost_history = np.zeros(iterations)\n theta_history = np.zeros((iterations,2))\n for it in range(iterations):\n \n prediction = np.dot(X,theta)\n \n theta = theta -(1/m)*learning_rate*( X.T.dot((prediction - y)))\n# print(\"theta size: {}, trans: {}\".format(theta.shape, theta.T.shape))\n theta_history[it,:] =theta.T\n cost_history[it] = cal_cost(theta,X,y)\n \n return theta, cost_history, theta_history\n```\n\n

Let's start with 1000 iterations and a learning rate of 0.01. Start with theta from a Gaussian distribution\n\n\n```python\nlr =0.01\nn_iter = 1000\n\ntheta = np.random.randn(2,1)\n\nX_b = np.c_[np.ones((len(X),1)),X]\nprint(\"X_b size: {}, y size: {}, theta size: {}\".format(X_b.shape, y.shape, theta.shape))\ntheta,cost_history,theta_history = gradient_descent(X_b,y,theta,lr,n_iter)\n\n\nprint('Theta0: {:0.3f},\\nTheta1: {:0.3f}'.format(theta[0][0],theta[1][0]))\nprint('Final cost/MSE: {:0.3f}'.format(cost_history[-1]))\n```\n\n X_b size: (100, 2), y size: (100, 1), theta size: (2, 1)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n theta size: (2, 1), trans: (1, 2)\n Theta0: 3.719,\n Theta1: 3.252\n Final cost/MSE: 5960.308\n\n\n

Let's plot the cost history over iterations\n\n\n```python\nfig,ax = plt.subplots(figsize=(12,8))\n\nax.set_ylabel('J(Theta)')\nax.set_xlabel('Iterations')\n_=ax.plot(range(n_iter),cost_history,'b.')\n```\n\n

After around 150 iterations the cost is flat so the remaining iterations are not needed or will not result in any further optimization. Let us zoom in till iteration 200 and see the curve\n\n\n```python\nfig,ax = plt.subplots(figsize=(10,8))\n_=ax.plot(range(200),cost_history[:200],'b.')\n```\n\nIt is worth while to note that the cost drops faster initially and then the gain in cost reduction is not as much\n\n### It would be great to see the effect of different learning rates and iterations together\n\n### Let us build a function which can show the effects together and also show how gradient decent actually is working\n\n\n```python\ndef plot_GD(n_iter,lr,ax,ax1=None):\n \"\"\"\n n_iter = no of iterations\n lr = Learning Rate\n ax = Axis to plot the Gradient Descent\n ax1 = Axis to plot cost_history vs Iterations plot\n\n \"\"\"\n _ = ax.plot(X,y,'b.')\n theta = np.random.randn(2,1)\n\n tr =0.1\n cost_history = np.zeros(n_iter)\n for i in range(n_iter):\n pred_prev = X_b.dot(theta)\n theta,h,_ = gradient_descent(X_b,y,theta,lr,1)\n pred = X_b.dot(theta)\n\n cost_history[i] = h[0]\n\n if ((i % 25 == 0) ):\n _ = ax.plot(X,pred,'r-',alpha=tr)\n if tr < 0.8:\n tr = tr+0.2\n if not ax1== None:\n _ = ax1.plot(range(n_iter),cost_history,'b.') \n```\n\n### Plot the graphs for different iterations and learning rates combination\n\n\n```python\nfig = plt.figure(figsize=(30,25))\nfig.subplots_adjust(hspace=0.4, wspace=0.4)\n\nit_lr =[(2000,0.001),(500,0.01),(200,0.05),(100,0.1)]\ncount =0\nfor n_iter, lr in it_lr:\n count += 1\n \n ax = fig.add_subplot(4, 2, count)\n count += 1\n \n ax1 = fig.add_subplot(4,2,count)\n \n ax.set_title(\"lr:{}\".format(lr))\n ax1.set_title(\"Iterations:{}\".format(n_iter))\n plot_GD(n_iter,lr,ax,ax1)\n```\n\n See how useful it is to visualize the effect of learning rates and iterations on gradient descent. The red lines show how the gradient descent starts and then slowly gets closer to the final value\n\n## You can always plot Indiviual graphs to zoom in\n\n\n```python\n_,ax = plt.subplots(figsize=(14,10))\nplot_GD(100,0.1,ax)\n```\n\n# Stochastic Gradient Descent\n\n\n```python\ndef stocashtic_gradient_descent(X,y,theta,learning_rate=0.01,iterations=10):\n '''\n X = Matrix of X with added bias units\n y = Vector of Y\n theta=Vector of thetas np.random.randn(j,1)\n learning_rate \n iterations = no of iterations\n \n Returns the final theta vector and array of cost history over no of iterations\n '''\n m = len(y)\n cost_history = np.zeros(iterations)\n \n \n for it in range(iterations):\n cost =0.0\n for i in range(m):\n rand_ind = np.random.randint(0,m)\n X_i = X[rand_ind,:].reshape(1,X.shape[1])\n y_i = y[rand_ind].reshape(1,1)\n prediction = np.dot(X_i,theta)\n\n theta = theta -(1/m)*learning_rate*( X_i.T.dot((prediction - y_i)))\n cost += cal_cost(theta,X_i,y_i)\n cost_history[it] = cost\n \n return theta, cost_history\n```\n\n\n```python\nlr =0.5\nn_iter = 50\n\ntheta = np.random.randn(2,1)\n\nX_b = np.c_[np.ones((len(X),1)),X]\ntheta,cost_history = stocashtic_gradient_descent(X_b,y,theta,lr,n_iter)\n\n\nprint('Theta0: {:0.3f},\\nTheta1: {:0.3f}'.format(theta[0][0],theta[1][0]))\nprint('Final cost/MSE: {:0.3f}'.format(cost_history[-1]))\n```\n\n Theta0: 4.095,\n Theta1: 3.055\n Final cost/MSE: 49.489\n\n\n\n```python\nfig,ax = plt.subplots(figsize=(10,8))\n\nax.set_ylabel('{J(Theta)}',rotation=0)\nax.set_xlabel('{Iterations}')\ntheta = np.random.randn(2,1)\n\n_=ax.plot(range(n_iter),cost_history,'b.')\n```\n\n# Mini Batch Gradient Descent\n\n\n```python\ndef minibatch_gradient_descent(X,y,theta,learning_rate=0.01,iterations=10,batch_size =20):\n '''\n X = Matrix of X without added bias units\n y = Vector of Y\n theta=Vector of thetas np.random.randn(j,1)\n learning_rate \n iterations = no of iterations\n \n Returns the final theta vector and array of cost history over no of iterations\n '''\n m = len(y)\n cost_history = np.zeros(iterations)\n n_batches = int(m/batch_size)\n \n for it in range(iterations):\n cost =0.0\n indices = np.random.permutation(m)\n X = X[indices]\n y = y[indices]\n for i in range(0,m,batch_size):\n X_i = X[i:i+batch_size]\n y_i = y[i:i+batch_size]\n \n X_i = np.c_[np.ones(len(X_i)),X_i]\n \n prediction = np.dot(X_i,theta)\n\n theta = theta -(1/m)*learning_rate*( X_i.T.dot((prediction - y_i)))\n cost += cal_cost(theta,X_i,y_i)\n cost_history[it] = cost\n \n return theta, cost_history\n```\n\n\n```python\nlr =0.1\nn_iter = 200\n\ntheta = np.random.randn(2,1)\n\n\ntheta,cost_history = minibatch_gradient_descent(X,y,theta,lr,n_iter)\n\n\nprint('Theta0: {:0.3f},\\nTheta1: {:0.3f}'.format(theta[0][0],theta[1][0]))\nprint('Final cost/MSE: {:0.3f}'.format(cost_history[-1]))\n```\n\n Theta0: 4.084,\n Theta1: 3.047\n Final cost/MSE: 944.948\n\n\n\n```python\nfig,ax = plt.subplots(figsize=(10,8))\n\nax.set_ylabel('{J(Theta)}',rotation=0)\nax.set_xlabel('{Iterations}')\ntheta = np.random.randn(2,1)\n\n_=ax.plot(range(n_iter),cost_history,'b.')\n```\n\n\n```python\nimport random\n\n\nclass LinearRegression:\n def __init__(self, l_rate, n_epoch, n_train_size):\n self.l_rate = l_rate\n self.n_epoch = n_epoch\n self.n_train_size = n_train_size\n self.coeff = [0.0, 0.0, 0.0]\n\n def fit(self, X, y):\n \"\"\"\n Fit linear model with SGD.\n \"\"\"\n for epoch in range(self.n_epoch):\n sum_loss = self.get_loss(X, y)\n print('>epoch=%d, lrate=%.3f, error=%.3f' % (epoch, self.l_rate, sum_loss))\n \n def get_coeff(self):\n return self.coeff[1:]\n \n def get_intercept(self):\n return self.coeff[0]\n \n # get the loss based on input X and label data y\n # J(θ)=1/(2m) ∑(hθ(x(i))−y(i))^2\n def get_loss(self, X, y):\n sum_loss = 0.0\n for X_row, y_row in zip(X, y):\n yhat = self.predict(X_row, self.coeff)\n loss = yhat - y_row\n sum_loss += loss**2\n self.coeff[0] = self.coeff[0] - self.l_rate * loss / n_train_size\n for i in range(len(X_row)):\n self.coeff[i+1] = self.coeff[i+1] - self.l_rate * loss * X_row[i] / n_train_size\n return sum_loss / 2 / n_train_size\n \n # make a prediction using coeff\n # hθ(x) = θTx=θ0 + θ1*x1 + θ2*x2\n def predict(self, X_row, coeff):\n yhat = coeff[0]\n for i in range(len(X_row)):\n yhat += coeff[i+1] * X_row[i]\n return yhat\n```\n\n\n```python\nif __name__ == '__main__':\n X = [[random.randint(1, 30), random.randint(1, 30)] for _ in range(20)]\n y = [x[0] + 5 * x[1] + 7 for x in X]\n l_rate = 0.005\n n_epoch = 8000\n n_train_size = len(X)\n print(\"n_train_size: {}\".format(n_train_size))\n linear_reg = LinearRegression(l_rate, n_epoch, n_train_size)\n linear_reg.fit(X, y)\n delta = 0.1\n intercept = linear_reg.get_intercept()\n coeff = linear_reg.get_coeff()\n print(\"intercept: {}\".format(intercept))\n print(\"coeff: {}\".format(coeff))\n assert abs(coeff[0] - 1) < delta\n assert abs(coeff[1] - 5) < delta\n assert abs(intercept - 7) < delta\n```\n\n n_train_size: 20\n >epoch=0, lrate=0.005, error=1223.403\n >epoch=1, lrate=0.005, error=129.169\n >epoch=2, lrate=0.005, error=91.426\n >epoch=3, lrate=0.005, error=64.452\n >epoch=4, lrate=0.005, error=45.839\n >epoch=5, lrate=0.005, error=33.033\n >epoch=6, lrate=0.005, error=24.223\n >epoch=7, lrate=0.005, error=18.164\n >epoch=8, lrate=0.005, error=13.997\n >epoch=9, lrate=0.005, error=11.132\n >epoch=10, lrate=0.005, error=9.161\n >epoch=11, lrate=0.005, error=7.806\n >epoch=12, lrate=0.005, error=6.874\n >epoch=13, lrate=0.005, error=6.232\n >epoch=14, lrate=0.005, error=5.790\n >epoch=15, lrate=0.005, error=5.485\n >epoch=16, lrate=0.005, error=5.273\n >epoch=17, lrate=0.005, error=5.126\n >epoch=18, lrate=0.005, error=5.023\n >epoch=19, lrate=0.005, error=4.950\n >epoch=20, lrate=0.005, error=4.898\n >epoch=21, lrate=0.005, error=4.859\n >epoch=22, lrate=0.005, error=4.830\n >epoch=23, lrate=0.005, error=4.808\n >epoch=24, lrate=0.005, error=4.790\n >epoch=25, lrate=0.005, error=4.774\n >epoch=26, lrate=0.005, error=4.761\n >epoch=27, lrate=0.005, error=4.749\n >epoch=28, lrate=0.005, error=4.738\n >epoch=29, lrate=0.005, error=4.728\n >epoch=30, lrate=0.005, error=4.718\n >epoch=31, lrate=0.005, error=4.708\n >epoch=32, lrate=0.005, error=4.698\n >epoch=33, lrate=0.005, error=4.689\n >epoch=34, lrate=0.005, error=4.679\n >epoch=35, lrate=0.005, error=4.669\n >epoch=36, lrate=0.005, error=4.660\n >epoch=37, lrate=0.005, error=4.651\n >epoch=38, lrate=0.005, error=4.641\n >epoch=39, lrate=0.005, error=4.632\n >epoch=40, lrate=0.005, error=4.622\n >epoch=41, lrate=0.005, error=4.613\n >epoch=42, lrate=0.005, error=4.603\n >epoch=43, lrate=0.005, error=4.594\n >epoch=44, lrate=0.005, error=4.584\n >epoch=45, lrate=0.005, error=4.575\n >epoch=46, lrate=0.005, error=4.566\n >epoch=47, lrate=0.005, error=4.556\n >epoch=48, lrate=0.005, error=4.547\n >epoch=49, lrate=0.005, error=4.537\n >epoch=50, lrate=0.005, error=4.528\n >epoch=51, lrate=0.005, error=4.519\n >epoch=52, lrate=0.005, error=4.509\n >epoch=53, lrate=0.005, error=4.500\n >epoch=54, lrate=0.005, error=4.491\n >epoch=55, lrate=0.005, error=4.482\n >epoch=56, lrate=0.005, error=4.472\n >epoch=57, lrate=0.005, error=4.463\n >epoch=58, lrate=0.005, error=4.454\n >epoch=59, lrate=0.005, error=4.445\n >epoch=60, lrate=0.005, error=4.436\n >epoch=61, lrate=0.005, error=4.427\n >epoch=62, lrate=0.005, error=4.417\n >epoch=63, lrate=0.005, error=4.408\n >epoch=64, lrate=0.005, error=4.399\n >epoch=65, lrate=0.005, error=4.390\n >epoch=66, lrate=0.005, error=4.381\n >epoch=67, lrate=0.005, error=4.372\n >epoch=68, lrate=0.005, error=4.363\n >epoch=69, lrate=0.005, error=4.354\n >epoch=70, lrate=0.005, error=4.345\n >epoch=71, lrate=0.005, error=4.336\n >epoch=72, lrate=0.005, error=4.327\n >epoch=73, lrate=0.005, error=4.318\n >epoch=74, lrate=0.005, error=4.309\n >epoch=75, lrate=0.005, error=4.300\n >epoch=76, lrate=0.005, error=4.292\n >epoch=77, lrate=0.005, error=4.283\n >epoch=78, lrate=0.005, error=4.274\n >epoch=79, lrate=0.005, error=4.265\n >epoch=80, lrate=0.005, error=4.256\n >epoch=81, lrate=0.005, error=4.248\n >epoch=82, lrate=0.005, error=4.239\n >epoch=83, lrate=0.005, error=4.230\n >epoch=84, lrate=0.005, error=4.221\n >epoch=85, lrate=0.005, error=4.213\n >epoch=86, lrate=0.005, error=4.204\n >epoch=87, lrate=0.005, error=4.195\n >epoch=88, lrate=0.005, error=4.187\n >epoch=89, lrate=0.005, error=4.178\n >epoch=90, lrate=0.005, error=4.169\n >epoch=91, lrate=0.005, error=4.161\n >epoch=92, lrate=0.005, error=4.152\n >epoch=93, lrate=0.005, error=4.144\n >epoch=94, lrate=0.005, error=4.135\n >epoch=95, lrate=0.005, error=4.127\n >epoch=96, lrate=0.005, error=4.118\n >epoch=97, lrate=0.005, error=4.109\n >epoch=98, lrate=0.005, error=4.101\n >epoch=99, lrate=0.005, error=4.093\n >epoch=100, lrate=0.005, error=4.084\n >epoch=101, lrate=0.005, error=4.076\n >epoch=102, lrate=0.005, error=4.067\n >epoch=103, lrate=0.005, error=4.059\n >epoch=104, lrate=0.005, error=4.051\n >epoch=105, lrate=0.005, error=4.042\n >epoch=106, lrate=0.005, error=4.034\n >epoch=107, lrate=0.005, error=4.026\n >epoch=108, lrate=0.005, error=4.017\n >epoch=109, lrate=0.005, error=4.009\n >epoch=110, lrate=0.005, error=4.001\n >epoch=111, lrate=0.005, error=3.992\n >epoch=112, lrate=0.005, error=3.984\n >epoch=113, lrate=0.005, error=3.976\n >epoch=114, lrate=0.005, error=3.968\n >epoch=115, lrate=0.005, error=3.960\n >epoch=116, lrate=0.005, error=3.951\n >epoch=117, lrate=0.005, error=3.943\n >epoch=118, lrate=0.005, error=3.935\n >epoch=119, lrate=0.005, error=3.927\n >epoch=120, lrate=0.005, error=3.919\n >epoch=121, lrate=0.005, error=3.911\n >epoch=122, lrate=0.005, error=3.903\n >epoch=123, lrate=0.005, error=3.895\n >epoch=124, lrate=0.005, error=3.887\n >epoch=125, lrate=0.005, error=3.879\n >epoch=126, lrate=0.005, error=3.871\n >epoch=127, lrate=0.005, error=3.863\n >epoch=128, lrate=0.005, error=3.855\n >epoch=129, lrate=0.005, error=3.847\n >epoch=130, lrate=0.005, error=3.839\n >epoch=131, lrate=0.005, error=3.831\n >epoch=132, lrate=0.005, error=3.823\n >epoch=133, lrate=0.005, error=3.815\n >epoch=134, lrate=0.005, error=3.807\n >epoch=135, lrate=0.005, error=3.799\n >epoch=136, lrate=0.005, error=3.792\n >epoch=137, lrate=0.005, error=3.784\n >epoch=138, lrate=0.005, error=3.776\n >epoch=139, lrate=0.005, error=3.768\n >epoch=140, lrate=0.005, error=3.760\n >epoch=141, lrate=0.005, error=3.753\n >epoch=142, lrate=0.005, error=3.745\n >epoch=143, lrate=0.005, error=3.737\n >epoch=144, lrate=0.005, error=3.730\n >epoch=145, lrate=0.005, error=3.722\n >epoch=146, lrate=0.005, error=3.714\n >epoch=147, lrate=0.005, error=3.706\n >epoch=148, lrate=0.005, error=3.699\n >epoch=149, lrate=0.005, error=3.691\n >epoch=150, lrate=0.005, error=3.684\n >epoch=151, lrate=0.005, error=3.676\n >epoch=152, lrate=0.005, error=3.668\n >epoch=153, lrate=0.005, error=3.661\n >epoch=154, lrate=0.005, error=3.653\n >epoch=155, lrate=0.005, error=3.646\n >epoch=156, lrate=0.005, error=3.638\n >epoch=157, lrate=0.005, error=3.631\n >epoch=158, lrate=0.005, error=3.623\n >epoch=159, lrate=0.005, error=3.616\n >epoch=160, lrate=0.005, error=3.608\n >epoch=161, lrate=0.005, error=3.601\n >epoch=162, lrate=0.005, error=3.593\n >epoch=163, lrate=0.005, error=3.586\n >epoch=164, lrate=0.005, error=3.579\n >epoch=165, lrate=0.005, error=3.571\n >epoch=166, lrate=0.005, error=3.564\n >epoch=167, lrate=0.005, error=3.557\n >epoch=168, lrate=0.005, error=3.549\n >epoch=169, lrate=0.005, error=3.542\n >epoch=170, lrate=0.005, error=3.535\n >epoch=171, lrate=0.005, error=3.527\n >epoch=172, lrate=0.005, error=3.520\n >epoch=173, lrate=0.005, error=3.513\n >epoch=174, lrate=0.005, error=3.506\n >epoch=175, lrate=0.005, error=3.498\n >epoch=176, lrate=0.005, error=3.491\n >epoch=177, lrate=0.005, error=3.484\n >epoch=178, lrate=0.005, error=3.477\n >epoch=179, lrate=0.005, error=3.470\n >epoch=180, lrate=0.005, error=3.462\n >epoch=181, lrate=0.005, error=3.455\n >epoch=182, lrate=0.005, error=3.448\n >epoch=183, lrate=0.005, error=3.441\n >epoch=184, lrate=0.005, error=3.434\n >epoch=185, lrate=0.005, error=3.427\n >epoch=186, lrate=0.005, error=3.420\n >epoch=187, lrate=0.005, error=3.413\n >epoch=188, lrate=0.005, error=3.406\n >epoch=189, lrate=0.005, error=3.399\n >epoch=190, lrate=0.005, error=3.392\n >epoch=191, lrate=0.005, error=3.385\n >epoch=192, lrate=0.005, error=3.378\n >epoch=193, lrate=0.005, error=3.371\n >epoch=194, lrate=0.005, error=3.364\n >epoch=195, lrate=0.005, error=3.357\n >epoch=196, lrate=0.005, error=3.350\n >epoch=197, lrate=0.005, error=3.343\n >epoch=198, lrate=0.005, error=3.336\n >epoch=199, lrate=0.005, error=3.329\n >epoch=200, lrate=0.005, error=3.322\n >epoch=201, lrate=0.005, error=3.315\n >epoch=202, lrate=0.005, error=3.309\n >epoch=203, lrate=0.005, error=3.302\n >epoch=204, lrate=0.005, error=3.295\n >epoch=205, lrate=0.005, error=3.288\n >epoch=206, lrate=0.005, error=3.281\n >epoch=207, lrate=0.005, error=3.275\n >epoch=208, lrate=0.005, error=3.268\n >epoch=209, lrate=0.005, error=3.261\n >epoch=210, lrate=0.005, error=3.254\n >epoch=211, lrate=0.005, error=3.248\n >epoch=212, lrate=0.005, error=3.241\n >epoch=213, lrate=0.005, error=3.234\n >epoch=214, lrate=0.005, error=3.228\n >epoch=215, lrate=0.005, error=3.221\n >epoch=216, lrate=0.005, error=3.214\n >epoch=217, lrate=0.005, error=3.208\n >epoch=218, lrate=0.005, error=3.201\n >epoch=219, lrate=0.005, error=3.195\n >epoch=220, lrate=0.005, error=3.188\n >epoch=221, lrate=0.005, error=3.181\n >epoch=222, lrate=0.005, error=3.175\n >epoch=223, lrate=0.005, error=3.168\n >epoch=224, lrate=0.005, error=3.162\n >epoch=225, lrate=0.005, error=3.155\n >epoch=226, lrate=0.005, error=3.149\n >epoch=227, lrate=0.005, error=3.142\n >epoch=228, lrate=0.005, error=3.136\n >epoch=229, lrate=0.005, error=3.129\n >epoch=230, lrate=0.005, error=3.123\n >epoch=231, lrate=0.005, error=3.116\n >epoch=232, lrate=0.005, error=3.110\n >epoch=233, lrate=0.005, error=3.104\n >epoch=234, lrate=0.005, error=3.097\n >epoch=235, lrate=0.005, error=3.091\n >epoch=236, lrate=0.005, error=3.084\n >epoch=237, lrate=0.005, error=3.078\n >epoch=238, lrate=0.005, error=3.072\n >epoch=239, lrate=0.005, error=3.065\n >epoch=240, lrate=0.005, error=3.059\n >epoch=241, lrate=0.005, error=3.053\n >epoch=242, lrate=0.005, error=3.046\n >epoch=243, lrate=0.005, error=3.040\n >epoch=244, lrate=0.005, error=3.034\n >epoch=245, lrate=0.005, error=3.028\n >epoch=246, lrate=0.005, error=3.021\n >epoch=247, lrate=0.005, error=3.015\n >epoch=248, lrate=0.005, error=3.009\n >epoch=249, lrate=0.005, error=3.003\n >epoch=250, lrate=0.005, error=2.997\n >epoch=251, lrate=0.005, error=2.990\n >epoch=252, lrate=0.005, error=2.984\n >epoch=253, lrate=0.005, error=2.978\n >epoch=254, lrate=0.005, error=2.972\n >epoch=255, lrate=0.005, error=2.966\n >epoch=256, lrate=0.005, error=2.960\n >epoch=257, lrate=0.005, error=2.954\n >epoch=258, lrate=0.005, error=2.947\n >epoch=259, lrate=0.005, error=2.941\n >epoch=260, lrate=0.005, error=2.935\n >epoch=261, lrate=0.005, error=2.929\n >epoch=262, lrate=0.005, error=2.923\n >epoch=263, lrate=0.005, error=2.917\n >epoch=264, lrate=0.005, error=2.911\n >epoch=265, lrate=0.005, error=2.905\n >epoch=266, lrate=0.005, error=2.899\n >epoch=267, lrate=0.005, error=2.893\n >epoch=268, lrate=0.005, error=2.887\n >epoch=269, lrate=0.005, error=2.881\n >epoch=270, lrate=0.005, error=2.875\n >epoch=271, lrate=0.005, error=2.869\n >epoch=272, lrate=0.005, error=2.863\n >epoch=273, lrate=0.005, error=2.858\n >epoch=274, lrate=0.005, error=2.852\n >epoch=275, lrate=0.005, error=2.846\n >epoch=276, lrate=0.005, error=2.840\n >epoch=277, lrate=0.005, error=2.834\n >epoch=278, lrate=0.005, error=2.828\n >epoch=279, lrate=0.005, error=2.822\n >epoch=280, lrate=0.005, error=2.817\n >epoch=281, lrate=0.005, error=2.811\n >epoch=282, lrate=0.005, error=2.805\n >epoch=283, lrate=0.005, error=2.799\n >epoch=284, lrate=0.005, error=2.793\n >epoch=285, lrate=0.005, error=2.788\n >epoch=286, lrate=0.005, error=2.782\n >epoch=287, lrate=0.005, error=2.776\n >epoch=288, lrate=0.005, error=2.770\n >epoch=289, lrate=0.005, error=2.765\n >epoch=290, lrate=0.005, error=2.759\n >epoch=291, lrate=0.005, error=2.753\n >epoch=292, lrate=0.005, error=2.748\n >epoch=293, lrate=0.005, error=2.742\n >epoch=294, lrate=0.005, error=2.736\n >epoch=295, lrate=0.005, error=2.731\n >epoch=296, lrate=0.005, error=2.725\n >epoch=297, lrate=0.005, error=2.719\n >epoch=298, lrate=0.005, error=2.714\n >epoch=299, lrate=0.005, error=2.708\n >epoch=300, lrate=0.005, error=2.703\n >epoch=301, lrate=0.005, error=2.697\n >epoch=302, lrate=0.005, error=2.692\n >epoch=303, lrate=0.005, error=2.686\n >epoch=304, lrate=0.005, error=2.680\n >epoch=305, lrate=0.005, error=2.675\n >epoch=306, lrate=0.005, error=2.669\n >epoch=307, lrate=0.005, error=2.664\n >epoch=308, lrate=0.005, error=2.658\n >epoch=309, lrate=0.005, error=2.653\n >epoch=310, lrate=0.005, error=2.647\n >epoch=311, lrate=0.005, error=2.642\n >epoch=312, lrate=0.005, error=2.637\n >epoch=313, lrate=0.005, error=2.631\n >epoch=314, lrate=0.005, error=2.626\n >epoch=315, lrate=0.005, error=2.620\n >epoch=316, lrate=0.005, error=2.615\n >epoch=317, lrate=0.005, error=2.609\n >epoch=318, lrate=0.005, error=2.604\n >epoch=319, lrate=0.005, error=2.599\n >epoch=320, lrate=0.005, error=2.593\n >epoch=321, lrate=0.005, error=2.588\n >epoch=322, lrate=0.005, error=2.583\n >epoch=323, lrate=0.005, error=2.577\n >epoch=324, lrate=0.005, error=2.572\n >epoch=325, lrate=0.005, error=2.567\n >epoch=326, lrate=0.005, error=2.561\n >epoch=327, lrate=0.005, error=2.556\n >epoch=328, lrate=0.005, error=2.551\n >epoch=329, lrate=0.005, error=2.546\n >epoch=330, lrate=0.005, error=2.540\n >epoch=331, lrate=0.005, error=2.535\n >epoch=332, lrate=0.005, error=2.530\n >epoch=333, lrate=0.005, error=2.525\n >epoch=334, lrate=0.005, error=2.519\n >epoch=335, lrate=0.005, error=2.514\n >epoch=336, lrate=0.005, error=2.509\n >epoch=337, lrate=0.005, error=2.504\n >epoch=338, lrate=0.005, error=2.499\n >epoch=339, lrate=0.005, error=2.494\n >epoch=340, lrate=0.005, error=2.488\n >epoch=341, lrate=0.005, error=2.483\n >epoch=342, lrate=0.005, error=2.478\n >epoch=343, lrate=0.005, error=2.473\n >epoch=344, lrate=0.005, error=2.468\n >epoch=345, lrate=0.005, error=2.463\n >epoch=346, lrate=0.005, error=2.458\n >epoch=347, lrate=0.005, error=2.453\n >epoch=348, lrate=0.005, error=2.448\n >epoch=349, lrate=0.005, error=2.443\n >epoch=350, lrate=0.005, error=2.438\n >epoch=351, lrate=0.005, error=2.433\n >epoch=352, lrate=0.005, error=2.428\n >epoch=353, lrate=0.005, error=2.423\n >epoch=354, lrate=0.005, error=2.418\n >epoch=355, lrate=0.005, error=2.413\n >epoch=356, lrate=0.005, error=2.408\n >epoch=357, lrate=0.005, error=2.403\n >epoch=358, lrate=0.005, error=2.398\n >epoch=359, lrate=0.005, error=2.393\n >epoch=360, lrate=0.005, error=2.388\n >epoch=361, lrate=0.005, error=2.383\n >epoch=362, lrate=0.005, error=2.378\n >epoch=363, lrate=0.005, error=2.373\n >epoch=364, lrate=0.005, error=2.368\n >epoch=365, lrate=0.005, error=2.363\n >epoch=366, lrate=0.005, error=2.358\n >epoch=367, lrate=0.005, error=2.354\n >epoch=368, lrate=0.005, error=2.349\n >epoch=369, lrate=0.005, error=2.344\n >epoch=370, lrate=0.005, error=2.339\n >epoch=371, lrate=0.005, error=2.334\n >epoch=372, lrate=0.005, error=2.329\n >epoch=373, lrate=0.005, error=2.325\n >epoch=374, lrate=0.005, error=2.320\n >epoch=375, lrate=0.005, error=2.315\n >epoch=376, lrate=0.005, error=2.310\n >epoch=377, lrate=0.005, error=2.305\n >epoch=378, lrate=0.005, error=2.301\n >epoch=379, lrate=0.005, error=2.296\n >epoch=380, lrate=0.005, error=2.291\n >epoch=381, lrate=0.005, error=2.286\n >epoch=382, lrate=0.005, error=2.282\n >epoch=383, lrate=0.005, error=2.277\n >epoch=384, lrate=0.005, error=2.272\n >epoch=385, lrate=0.005, error=2.268\n >epoch=386, lrate=0.005, error=2.263\n >epoch=387, lrate=0.005, error=2.258\n >epoch=388, lrate=0.005, error=2.254\n >epoch=389, lrate=0.005, error=2.249\n >epoch=390, lrate=0.005, error=2.244\n >epoch=391, lrate=0.005, error=2.240\n >epoch=392, lrate=0.005, error=2.235\n >epoch=393, lrate=0.005, error=2.231\n >epoch=394, lrate=0.005, error=2.226\n >epoch=395, lrate=0.005, error=2.221\n >epoch=396, lrate=0.005, error=2.217\n >epoch=397, lrate=0.005, error=2.212\n >epoch=398, lrate=0.005, error=2.208\n >epoch=399, lrate=0.005, error=2.203\n >epoch=400, lrate=0.005, error=2.199\n >epoch=401, lrate=0.005, error=2.194\n >epoch=402, lrate=0.005, error=2.189\n >epoch=403, lrate=0.005, error=2.185\n >epoch=404, lrate=0.005, error=2.180\n >epoch=405, lrate=0.005, error=2.176\n >epoch=406, lrate=0.005, error=2.171\n >epoch=407, lrate=0.005, error=2.167\n >epoch=408, lrate=0.005, error=2.163\n >epoch=409, lrate=0.005, error=2.158\n >epoch=410, lrate=0.005, error=2.154\n >epoch=411, lrate=0.005, error=2.149\n >epoch=412, lrate=0.005, error=2.145\n >epoch=413, lrate=0.005, error=2.140\n >epoch=414, lrate=0.005, error=2.136\n >epoch=415, lrate=0.005, error=2.131\n >epoch=416, lrate=0.005, error=2.127\n >epoch=417, lrate=0.005, error=2.123\n >epoch=418, lrate=0.005, error=2.118\n >epoch=419, lrate=0.005, error=2.114\n >epoch=420, lrate=0.005, error=2.110\n >epoch=421, lrate=0.005, error=2.105\n >epoch=422, lrate=0.005, error=2.101\n >epoch=423, lrate=0.005, error=2.097\n >epoch=424, lrate=0.005, error=2.092\n >epoch=425, lrate=0.005, error=2.088\n >epoch=426, lrate=0.005, error=2.084\n >epoch=427, lrate=0.005, error=2.079\n >epoch=428, lrate=0.005, error=2.075\n >epoch=429, lrate=0.005, error=2.071\n >epoch=430, lrate=0.005, error=2.067\n >epoch=431, lrate=0.005, error=2.062\n >epoch=432, lrate=0.005, error=2.058\n >epoch=433, lrate=0.005, error=2.054\n >epoch=434, lrate=0.005, error=2.050\n >epoch=435, lrate=0.005, error=2.045\n >epoch=436, lrate=0.005, error=2.041\n >epoch=437, lrate=0.005, error=2.037\n >epoch=438, lrate=0.005, error=2.033\n >epoch=439, lrate=0.005, error=2.028\n >epoch=440, lrate=0.005, error=2.024\n >epoch=441, lrate=0.005, error=2.020\n >epoch=442, lrate=0.005, error=2.016\n >epoch=443, lrate=0.005, error=2.012\n >epoch=444, lrate=0.005, error=2.008\n >epoch=445, lrate=0.005, error=2.003\n >epoch=446, lrate=0.005, error=1.999\n >epoch=447, lrate=0.005, error=1.995\n >epoch=448, lrate=0.005, error=1.991\n >epoch=449, lrate=0.005, error=1.987\n >epoch=450, lrate=0.005, error=1.983\n >epoch=451, lrate=0.005, error=1.979\n >epoch=452, lrate=0.005, error=1.975\n >epoch=453, lrate=0.005, error=1.971\n >epoch=454, lrate=0.005, error=1.967\n >epoch=455, lrate=0.005, error=1.963\n >epoch=456, lrate=0.005, error=1.959\n >epoch=457, lrate=0.005, error=1.954\n >epoch=458, lrate=0.005, error=1.950\n >epoch=459, lrate=0.005, error=1.946\n >epoch=460, lrate=0.005, error=1.942\n >epoch=461, lrate=0.005, error=1.938\n >epoch=462, lrate=0.005, error=1.934\n >epoch=463, lrate=0.005, error=1.930\n >epoch=464, lrate=0.005, error=1.926\n >epoch=465, lrate=0.005, error=1.922\n >epoch=466, lrate=0.005, error=1.918\n >epoch=467, lrate=0.005, error=1.915\n >epoch=468, lrate=0.005, error=1.911\n >epoch=469, lrate=0.005, error=1.907\n >epoch=470, lrate=0.005, error=1.903\n >epoch=471, lrate=0.005, error=1.899\n >epoch=472, lrate=0.005, error=1.895\n >epoch=473, lrate=0.005, error=1.891\n >epoch=474, lrate=0.005, error=1.887\n >epoch=475, lrate=0.005, error=1.883\n >epoch=476, lrate=0.005, error=1.879\n >epoch=477, lrate=0.005, error=1.875\n >epoch=478, lrate=0.005, error=1.872\n >epoch=479, lrate=0.005, error=1.868\n >epoch=480, lrate=0.005, error=1.864\n >epoch=481, lrate=0.005, error=1.860\n >epoch=482, lrate=0.005, error=1.856\n >epoch=483, lrate=0.005, error=1.852\n >epoch=484, lrate=0.005, error=1.849\n >epoch=485, lrate=0.005, error=1.845\n >epoch=486, lrate=0.005, error=1.841\n >epoch=487, lrate=0.005, error=1.837\n >epoch=488, lrate=0.005, error=1.833\n >epoch=489, lrate=0.005, error=1.830\n >epoch=490, lrate=0.005, error=1.826\n >epoch=491, lrate=0.005, error=1.822\n >epoch=492, lrate=0.005, error=1.818\n >epoch=493, lrate=0.005, error=1.814\n >epoch=494, lrate=0.005, error=1.811\n >epoch=495, lrate=0.005, error=1.807\n >epoch=496, lrate=0.005, error=1.803\n >epoch=497, lrate=0.005, error=1.800\n >epoch=498, lrate=0.005, error=1.796\n >epoch=499, lrate=0.005, error=1.792\n >epoch=500, lrate=0.005, error=1.788\n >epoch=501, lrate=0.005, error=1.785\n >epoch=502, lrate=0.005, error=1.781\n >epoch=503, lrate=0.005, error=1.777\n >epoch=504, lrate=0.005, error=1.774\n >epoch=505, lrate=0.005, error=1.770\n >epoch=506, lrate=0.005, error=1.766\n >epoch=507, lrate=0.005, error=1.763\n >epoch=508, lrate=0.005, error=1.759\n >epoch=509, lrate=0.005, error=1.756\n >epoch=510, lrate=0.005, error=1.752\n >epoch=511, lrate=0.005, error=1.748\n >epoch=512, lrate=0.005, error=1.745\n >epoch=513, lrate=0.005, error=1.741\n >epoch=514, lrate=0.005, error=1.738\n >epoch=515, lrate=0.005, error=1.734\n >epoch=516, lrate=0.005, error=1.730\n >epoch=517, lrate=0.005, error=1.727\n >epoch=518, lrate=0.005, error=1.723\n >epoch=519, lrate=0.005, error=1.720\n >epoch=520, lrate=0.005, error=1.716\n >epoch=521, lrate=0.005, error=1.713\n >epoch=522, lrate=0.005, error=1.709\n >epoch=523, lrate=0.005, error=1.706\n >epoch=524, lrate=0.005, error=1.702\n >epoch=525, lrate=0.005, error=1.698\n >epoch=526, lrate=0.005, error=1.695\n >epoch=527, lrate=0.005, error=1.691\n >epoch=528, lrate=0.005, error=1.688\n >epoch=529, lrate=0.005, error=1.685\n >epoch=530, lrate=0.005, error=1.681\n >epoch=531, lrate=0.005, error=1.678\n >epoch=532, lrate=0.005, error=1.674\n >epoch=533, lrate=0.005, error=1.671\n >epoch=534, lrate=0.005, error=1.667\n >epoch=535, lrate=0.005, error=1.664\n >epoch=536, lrate=0.005, error=1.660\n >epoch=537, lrate=0.005, error=1.657\n >epoch=538, lrate=0.005, error=1.654\n >epoch=539, lrate=0.005, error=1.650\n >epoch=540, lrate=0.005, error=1.647\n >epoch=541, lrate=0.005, error=1.643\n >epoch=542, lrate=0.005, error=1.640\n >epoch=543, lrate=0.005, error=1.637\n >epoch=544, lrate=0.005, error=1.633\n >epoch=545, lrate=0.005, error=1.630\n >epoch=546, lrate=0.005, error=1.626\n >epoch=547, lrate=0.005, error=1.623\n >epoch=548, lrate=0.005, error=1.620\n >epoch=549, lrate=0.005, error=1.616\n >epoch=550, lrate=0.005, error=1.613\n >epoch=551, lrate=0.005, error=1.610\n >epoch=552, lrate=0.005, error=1.606\n >epoch=553, lrate=0.005, error=1.603\n >epoch=554, lrate=0.005, error=1.600\n >epoch=555, lrate=0.005, error=1.596\n >epoch=556, lrate=0.005, error=1.593\n >epoch=557, lrate=0.005, error=1.590\n >epoch=558, lrate=0.005, error=1.587\n >epoch=559, lrate=0.005, error=1.583\n >epoch=560, lrate=0.005, error=1.580\n >epoch=561, lrate=0.005, error=1.577\n >epoch=562, lrate=0.005, error=1.574\n >epoch=563, lrate=0.005, error=1.570\n >epoch=564, lrate=0.005, error=1.567\n >epoch=565, lrate=0.005, error=1.564\n >epoch=566, lrate=0.005, error=1.561\n >epoch=567, lrate=0.005, error=1.557\n >epoch=568, lrate=0.005, error=1.554\n >epoch=569, lrate=0.005, error=1.551\n >epoch=570, lrate=0.005, error=1.548\n >epoch=571, lrate=0.005, error=1.545\n >epoch=572, lrate=0.005, error=1.541\n >epoch=573, lrate=0.005, error=1.538\n >epoch=574, lrate=0.005, error=1.535\n >epoch=575, lrate=0.005, error=1.532\n >epoch=576, lrate=0.005, error=1.529\n >epoch=577, lrate=0.005, error=1.526\n >epoch=578, lrate=0.005, error=1.522\n >epoch=579, lrate=0.005, error=1.519\n >epoch=580, lrate=0.005, error=1.516\n >epoch=581, lrate=0.005, error=1.513\n >epoch=582, lrate=0.005, error=1.510\n >epoch=583, lrate=0.005, error=1.507\n >epoch=584, lrate=0.005, error=1.504\n >epoch=585, lrate=0.005, error=1.501\n >epoch=586, lrate=0.005, error=1.498\n >epoch=587, lrate=0.005, error=1.494\n >epoch=588, lrate=0.005, error=1.491\n >epoch=589, lrate=0.005, error=1.488\n >epoch=590, lrate=0.005, error=1.485\n >epoch=591, lrate=0.005, error=1.482\n >epoch=592, lrate=0.005, error=1.479\n >epoch=593, lrate=0.005, error=1.476\n >epoch=594, lrate=0.005, error=1.473\n >epoch=595, lrate=0.005, error=1.470\n >epoch=596, lrate=0.005, error=1.467\n >epoch=597, lrate=0.005, error=1.464\n >epoch=598, lrate=0.005, error=1.461\n >epoch=599, lrate=0.005, error=1.458\n >epoch=600, lrate=0.005, error=1.455\n >epoch=601, lrate=0.005, error=1.452\n >epoch=602, lrate=0.005, error=1.449\n >epoch=603, lrate=0.005, error=1.446\n >epoch=604, lrate=0.005, error=1.443\n >epoch=605, lrate=0.005, error=1.440\n >epoch=606, lrate=0.005, error=1.437\n >epoch=607, lrate=0.005, error=1.434\n >epoch=608, lrate=0.005, error=1.431\n >epoch=609, lrate=0.005, error=1.428\n >epoch=610, lrate=0.005, error=1.425\n >epoch=611, lrate=0.005, error=1.422\n >epoch=612, lrate=0.005, error=1.419\n >epoch=613, lrate=0.005, error=1.416\n >epoch=614, lrate=0.005, error=1.413\n >epoch=615, lrate=0.005, error=1.411\n >epoch=616, lrate=0.005, error=1.408\n >epoch=617, lrate=0.005, error=1.405\n >epoch=618, lrate=0.005, error=1.402\n >epoch=619, lrate=0.005, error=1.399\n >epoch=620, lrate=0.005, error=1.396\n >epoch=621, lrate=0.005, error=1.393\n >epoch=622, lrate=0.005, error=1.390\n >epoch=623, lrate=0.005, error=1.387\n >epoch=624, lrate=0.005, error=1.385\n >epoch=625, lrate=0.005, error=1.382\n >epoch=626, lrate=0.005, error=1.379\n >epoch=627, lrate=0.005, error=1.376\n >epoch=628, lrate=0.005, error=1.373\n >epoch=629, lrate=0.005, error=1.370\n >epoch=630, lrate=0.005, error=1.367\n >epoch=631, lrate=0.005, error=1.365\n >epoch=632, lrate=0.005, error=1.362\n >epoch=633, lrate=0.005, error=1.359\n >epoch=634, lrate=0.005, error=1.356\n >epoch=635, lrate=0.005, error=1.353\n >epoch=636, lrate=0.005, error=1.351\n >epoch=637, lrate=0.005, error=1.348\n >epoch=638, lrate=0.005, error=1.345\n >epoch=639, lrate=0.005, error=1.342\n >epoch=640, lrate=0.005, error=1.340\n >epoch=641, lrate=0.005, error=1.337\n >epoch=642, lrate=0.005, error=1.334\n >epoch=643, lrate=0.005, error=1.331\n >epoch=644, lrate=0.005, error=1.329\n >epoch=645, lrate=0.005, error=1.326\n >epoch=646, lrate=0.005, error=1.323\n >epoch=647, lrate=0.005, error=1.320\n >epoch=648, lrate=0.005, error=1.318\n >epoch=649, lrate=0.005, error=1.315\n >epoch=650, lrate=0.005, error=1.312\n >epoch=651, lrate=0.005, error=1.309\n >epoch=652, lrate=0.005, error=1.307\n >epoch=653, lrate=0.005, error=1.304\n >epoch=654, lrate=0.005, error=1.301\n >epoch=655, lrate=0.005, error=1.299\n >epoch=656, lrate=0.005, error=1.296\n >epoch=657, lrate=0.005, error=1.293\n >epoch=658, lrate=0.005, error=1.291\n >epoch=659, lrate=0.005, error=1.288\n >epoch=660, lrate=0.005, error=1.285\n >epoch=661, lrate=0.005, error=1.283\n >epoch=662, lrate=0.005, error=1.280\n >epoch=663, lrate=0.005, error=1.277\n >epoch=664, lrate=0.005, error=1.275\n >epoch=665, lrate=0.005, error=1.272\n >epoch=666, lrate=0.005, error=1.270\n >epoch=667, lrate=0.005, error=1.267\n >epoch=668, lrate=0.005, error=1.264\n >epoch=669, lrate=0.005, error=1.262\n >epoch=670, lrate=0.005, error=1.259\n >epoch=671, lrate=0.005, error=1.257\n >epoch=672, lrate=0.005, error=1.254\n >epoch=673, lrate=0.005, error=1.251\n >epoch=674, lrate=0.005, error=1.249\n >epoch=675, lrate=0.005, error=1.246\n >epoch=676, lrate=0.005, error=1.244\n >epoch=677, lrate=0.005, error=1.241\n >epoch=678, lrate=0.005, error=1.238\n >epoch=679, lrate=0.005, error=1.236\n >epoch=680, lrate=0.005, error=1.233\n >epoch=681, lrate=0.005, error=1.231\n >epoch=682, lrate=0.005, error=1.228\n >epoch=683, lrate=0.005, error=1.226\n >epoch=684, lrate=0.005, error=1.223\n >epoch=685, lrate=0.005, error=1.221\n >epoch=686, lrate=0.005, error=1.218\n >epoch=687, lrate=0.005, error=1.216\n >epoch=688, lrate=0.005, error=1.213\n >epoch=689, lrate=0.005, error=1.211\n >epoch=690, lrate=0.005, error=1.208\n >epoch=691, lrate=0.005, error=1.206\n >epoch=692, lrate=0.005, error=1.203\n >epoch=693, lrate=0.005, error=1.201\n >epoch=694, lrate=0.005, error=1.198\n >epoch=695, lrate=0.005, error=1.196\n >epoch=696, lrate=0.005, error=1.193\n >epoch=697, lrate=0.005, error=1.191\n >epoch=698, lrate=0.005, error=1.188\n >epoch=699, lrate=0.005, error=1.186\n >epoch=700, lrate=0.005, error=1.183\n >epoch=701, lrate=0.005, error=1.181\n >epoch=702, lrate=0.005, error=1.179\n >epoch=703, lrate=0.005, error=1.176\n >epoch=704, lrate=0.005, error=1.174\n >epoch=705, lrate=0.005, error=1.171\n >epoch=706, lrate=0.005, error=1.169\n >epoch=707, lrate=0.005, error=1.167\n >epoch=708, lrate=0.005, error=1.164\n >epoch=709, lrate=0.005, error=1.162\n >epoch=710, lrate=0.005, error=1.159\n >epoch=711, lrate=0.005, error=1.157\n >epoch=712, lrate=0.005, error=1.155\n >epoch=713, lrate=0.005, error=1.152\n >epoch=714, lrate=0.005, error=1.150\n >epoch=715, lrate=0.005, error=1.147\n >epoch=716, lrate=0.005, error=1.145\n >epoch=717, lrate=0.005, error=1.143\n >epoch=718, lrate=0.005, error=1.140\n >epoch=719, lrate=0.005, error=1.138\n >epoch=720, lrate=0.005, error=1.136\n >epoch=721, lrate=0.005, error=1.133\n >epoch=722, lrate=0.005, error=1.131\n >epoch=723, lrate=0.005, error=1.129\n >epoch=724, lrate=0.005, error=1.126\n >epoch=725, lrate=0.005, error=1.124\n >epoch=726, lrate=0.005, error=1.122\n >epoch=727, lrate=0.005, error=1.119\n >epoch=728, lrate=0.005, error=1.117\n >epoch=729, lrate=0.005, error=1.115\n >epoch=730, lrate=0.005, error=1.112\n >epoch=731, lrate=0.005, error=1.110\n >epoch=732, lrate=0.005, error=1.108\n >epoch=733, lrate=0.005, error=1.106\n >epoch=734, lrate=0.005, error=1.103\n >epoch=735, lrate=0.005, error=1.101\n >epoch=736, lrate=0.005, error=1.099\n >epoch=737, lrate=0.005, error=1.096\n >epoch=738, lrate=0.005, error=1.094\n >epoch=739, lrate=0.005, error=1.092\n >epoch=740, lrate=0.005, error=1.090\n >epoch=741, lrate=0.005, error=1.087\n >epoch=742, lrate=0.005, error=1.085\n >epoch=743, lrate=0.005, error=1.083\n >epoch=744, lrate=0.005, error=1.081\n >epoch=745, lrate=0.005, error=1.079\n >epoch=746, lrate=0.005, error=1.076\n >epoch=747, lrate=0.005, error=1.074\n >epoch=748, lrate=0.005, error=1.072\n >epoch=749, lrate=0.005, error=1.070\n >epoch=750, lrate=0.005, error=1.067\n >epoch=751, lrate=0.005, error=1.065\n >epoch=752, lrate=0.005, error=1.063\n >epoch=753, lrate=0.005, error=1.061\n >epoch=754, lrate=0.005, error=1.059\n >epoch=755, lrate=0.005, error=1.056\n >epoch=756, lrate=0.005, error=1.054\n >epoch=757, lrate=0.005, error=1.052\n >epoch=758, lrate=0.005, error=1.050\n >epoch=759, lrate=0.005, error=1.048\n >epoch=760, lrate=0.005, error=1.046\n >epoch=761, lrate=0.005, error=1.043\n >epoch=762, lrate=0.005, error=1.041\n >epoch=763, lrate=0.005, error=1.039\n >epoch=764, lrate=0.005, error=1.037\n >epoch=765, lrate=0.005, error=1.035\n >epoch=766, lrate=0.005, error=1.033\n >epoch=767, lrate=0.005, error=1.031\n >epoch=768, lrate=0.005, error=1.028\n >epoch=769, lrate=0.005, error=1.026\n >epoch=770, lrate=0.005, error=1.024\n >epoch=771, lrate=0.005, error=1.022\n >epoch=772, lrate=0.005, error=1.020\n >epoch=773, lrate=0.005, error=1.018\n >epoch=774, lrate=0.005, error=1.016\n >epoch=775, lrate=0.005, error=1.014\n >epoch=776, lrate=0.005, error=1.012\n >epoch=777, lrate=0.005, error=1.010\n >epoch=778, lrate=0.005, error=1.007\n >epoch=779, lrate=0.005, error=1.005\n >epoch=780, lrate=0.005, error=1.003\n >epoch=781, lrate=0.005, error=1.001\n >epoch=782, lrate=0.005, error=0.999\n >epoch=783, lrate=0.005, error=0.997\n >epoch=784, lrate=0.005, error=0.995\n >epoch=785, lrate=0.005, error=0.993\n >epoch=786, lrate=0.005, error=0.991\n >epoch=787, lrate=0.005, error=0.989\n >epoch=788, lrate=0.005, error=0.987\n >epoch=789, lrate=0.005, error=0.985\n >epoch=790, lrate=0.005, error=0.983\n >epoch=791, lrate=0.005, error=0.981\n >epoch=792, lrate=0.005, error=0.979\n >epoch=793, lrate=0.005, error=0.977\n >epoch=794, lrate=0.005, error=0.975\n >epoch=795, lrate=0.005, error=0.973\n >epoch=796, lrate=0.005, error=0.971\n >epoch=797, lrate=0.005, error=0.969\n >epoch=798, lrate=0.005, error=0.967\n >epoch=799, lrate=0.005, error=0.965\n >epoch=800, lrate=0.005, error=0.963\n >epoch=801, lrate=0.005, error=0.961\n >epoch=802, lrate=0.005, error=0.959\n >epoch=803, lrate=0.005, error=0.957\n >epoch=804, lrate=0.005, error=0.955\n >epoch=805, lrate=0.005, error=0.953\n >epoch=806, lrate=0.005, error=0.951\n >epoch=807, lrate=0.005, error=0.949\n >epoch=808, lrate=0.005, error=0.947\n >epoch=809, lrate=0.005, error=0.945\n >epoch=810, lrate=0.005, error=0.943\n >epoch=811, lrate=0.005, error=0.941\n >epoch=812, lrate=0.005, error=0.939\n >epoch=813, lrate=0.005, error=0.937\n >epoch=814, lrate=0.005, error=0.935\n >epoch=815, lrate=0.005, error=0.933\n >epoch=816, lrate=0.005, error=0.931\n >epoch=817, lrate=0.005, error=0.930\n >epoch=818, lrate=0.005, error=0.928\n >epoch=819, lrate=0.005, error=0.926\n >epoch=820, lrate=0.005, error=0.924\n >epoch=821, lrate=0.005, error=0.922\n >epoch=822, lrate=0.005, error=0.920\n >epoch=823, lrate=0.005, error=0.918\n >epoch=824, lrate=0.005, error=0.916\n >epoch=825, lrate=0.005, error=0.914\n >epoch=826, lrate=0.005, error=0.912\n >epoch=827, lrate=0.005, error=0.911\n >epoch=828, lrate=0.005, error=0.909\n >epoch=829, lrate=0.005, error=0.907\n >epoch=830, lrate=0.005, error=0.905\n >epoch=831, lrate=0.005, error=0.903\n >epoch=832, lrate=0.005, error=0.901\n >epoch=833, lrate=0.005, error=0.899\n >epoch=834, lrate=0.005, error=0.897\n >epoch=835, lrate=0.005, error=0.896\n >epoch=836, lrate=0.005, error=0.894\n >epoch=837, lrate=0.005, error=0.892\n >epoch=838, lrate=0.005, error=0.890\n >epoch=839, lrate=0.005, error=0.888\n >epoch=840, lrate=0.005, error=0.886\n >epoch=841, lrate=0.005, error=0.885\n >epoch=842, lrate=0.005, error=0.883\n >epoch=843, lrate=0.005, error=0.881\n >epoch=844, lrate=0.005, error=0.879\n >epoch=845, lrate=0.005, error=0.877\n >epoch=846, lrate=0.005, error=0.876\n >epoch=847, lrate=0.005, error=0.874\n >epoch=848, lrate=0.005, error=0.872\n >epoch=849, lrate=0.005, error=0.870\n >epoch=850, lrate=0.005, error=0.868\n >epoch=851, lrate=0.005, error=0.867\n >epoch=852, lrate=0.005, error=0.865\n >epoch=853, lrate=0.005, error=0.863\n >epoch=854, lrate=0.005, error=0.861\n >epoch=855, lrate=0.005, error=0.859\n >epoch=856, lrate=0.005, error=0.858\n >epoch=857, lrate=0.005, error=0.856\n >epoch=858, lrate=0.005, error=0.854\n >epoch=859, lrate=0.005, error=0.852\n >epoch=860, lrate=0.005, error=0.851\n >epoch=861, lrate=0.005, error=0.849\n >epoch=862, lrate=0.005, error=0.847\n >epoch=863, lrate=0.005, error=0.845\n >epoch=864, lrate=0.005, error=0.844\n >epoch=865, lrate=0.005, error=0.842\n >epoch=866, lrate=0.005, error=0.840\n >epoch=867, lrate=0.005, error=0.838\n >epoch=868, lrate=0.005, error=0.837\n >epoch=869, lrate=0.005, error=0.835\n >epoch=870, lrate=0.005, error=0.833\n >epoch=871, lrate=0.005, error=0.831\n >epoch=872, lrate=0.005, error=0.830\n >epoch=873, lrate=0.005, error=0.828\n >epoch=874, lrate=0.005, error=0.826\n >epoch=875, lrate=0.005, error=0.825\n >epoch=876, lrate=0.005, error=0.823\n >epoch=877, lrate=0.005, error=0.821\n >epoch=878, lrate=0.005, error=0.820\n >epoch=879, lrate=0.005, error=0.818\n >epoch=880, lrate=0.005, error=0.816\n >epoch=881, lrate=0.005, error=0.814\n >epoch=882, lrate=0.005, error=0.813\n >epoch=883, lrate=0.005, error=0.811\n >epoch=884, lrate=0.005, error=0.809\n >epoch=885, lrate=0.005, error=0.808\n >epoch=886, lrate=0.005, error=0.806\n >epoch=887, lrate=0.005, error=0.804\n >epoch=888, lrate=0.005, error=0.803\n >epoch=889, lrate=0.005, error=0.801\n >epoch=890, lrate=0.005, error=0.800\n >epoch=891, lrate=0.005, error=0.798\n >epoch=892, lrate=0.005, error=0.796\n >epoch=893, lrate=0.005, error=0.795\n >epoch=894, lrate=0.005, error=0.793\n >epoch=895, lrate=0.005, error=0.791\n >epoch=896, lrate=0.005, error=0.790\n >epoch=897, lrate=0.005, error=0.788\n >epoch=898, lrate=0.005, error=0.786\n >epoch=899, lrate=0.005, error=0.785\n >epoch=900, lrate=0.005, error=0.783\n >epoch=901, lrate=0.005, error=0.782\n >epoch=902, lrate=0.005, error=0.780\n >epoch=903, lrate=0.005, error=0.778\n >epoch=904, lrate=0.005, error=0.777\n >epoch=905, lrate=0.005, error=0.775\n >epoch=906, lrate=0.005, error=0.774\n >epoch=907, lrate=0.005, error=0.772\n >epoch=908, lrate=0.005, error=0.770\n >epoch=909, lrate=0.005, error=0.769\n >epoch=910, lrate=0.005, error=0.767\n >epoch=911, lrate=0.005, error=0.766\n >epoch=912, lrate=0.005, error=0.764\n >epoch=913, lrate=0.005, error=0.762\n >epoch=914, lrate=0.005, error=0.761\n >epoch=915, lrate=0.005, error=0.759\n >epoch=916, lrate=0.005, error=0.758\n >epoch=917, lrate=0.005, error=0.756\n >epoch=918, lrate=0.005, error=0.755\n >epoch=919, lrate=0.005, error=0.753\n >epoch=920, lrate=0.005, error=0.751\n >epoch=921, lrate=0.005, error=0.750\n >epoch=922, lrate=0.005, error=0.748\n >epoch=923, lrate=0.005, error=0.747\n >epoch=924, lrate=0.005, error=0.745\n >epoch=925, lrate=0.005, error=0.744\n >epoch=926, lrate=0.005, error=0.742\n >epoch=927, lrate=0.005, error=0.741\n >epoch=928, lrate=0.005, error=0.739\n >epoch=929, lrate=0.005, error=0.738\n >epoch=930, lrate=0.005, error=0.736\n >epoch=931, lrate=0.005, error=0.735\n >epoch=932, lrate=0.005, error=0.733\n >epoch=933, lrate=0.005, error=0.732\n >epoch=934, lrate=0.005, error=0.730\n >epoch=935, lrate=0.005, error=0.729\n >epoch=936, lrate=0.005, error=0.727\n >epoch=937, lrate=0.005, error=0.726\n >epoch=938, lrate=0.005, error=0.724\n >epoch=939, lrate=0.005, error=0.723\n >epoch=940, lrate=0.005, error=0.721\n >epoch=941, lrate=0.005, error=0.720\n >epoch=942, lrate=0.005, error=0.718\n >epoch=943, lrate=0.005, error=0.717\n >epoch=944, lrate=0.005, error=0.715\n >epoch=945, lrate=0.005, error=0.714\n >epoch=946, lrate=0.005, error=0.712\n >epoch=947, lrate=0.005, error=0.711\n >epoch=948, lrate=0.005, error=0.709\n >epoch=949, lrate=0.005, error=0.708\n >epoch=950, lrate=0.005, error=0.706\n >epoch=951, lrate=0.005, error=0.705\n >epoch=952, lrate=0.005, error=0.703\n >epoch=953, lrate=0.005, error=0.702\n >epoch=954, lrate=0.005, error=0.701\n >epoch=955, lrate=0.005, error=0.699\n >epoch=956, lrate=0.005, error=0.698\n >epoch=957, lrate=0.005, error=0.696\n >epoch=958, lrate=0.005, error=0.695\n >epoch=959, lrate=0.005, error=0.693\n >epoch=960, lrate=0.005, error=0.692\n >epoch=961, lrate=0.005, error=0.691\n >epoch=962, lrate=0.005, error=0.689\n >epoch=963, lrate=0.005, error=0.688\n >epoch=964, lrate=0.005, error=0.686\n >epoch=965, lrate=0.005, error=0.685\n >epoch=966, lrate=0.005, error=0.683\n >epoch=967, lrate=0.005, error=0.682\n >epoch=968, lrate=0.005, error=0.681\n >epoch=969, lrate=0.005, error=0.679\n >epoch=970, lrate=0.005, error=0.678\n >epoch=971, lrate=0.005, error=0.676\n >epoch=972, lrate=0.005, error=0.675\n >epoch=973, lrate=0.005, error=0.674\n >epoch=974, lrate=0.005, error=0.672\n >epoch=975, lrate=0.005, error=0.671\n >epoch=976, lrate=0.005, error=0.669\n >epoch=977, lrate=0.005, error=0.668\n >epoch=978, lrate=0.005, error=0.667\n >epoch=979, lrate=0.005, error=0.665\n >epoch=980, lrate=0.005, error=0.664\n >epoch=981, lrate=0.005, error=0.663\n >epoch=982, lrate=0.005, error=0.661\n >epoch=983, lrate=0.005, error=0.660\n >epoch=984, lrate=0.005, error=0.658\n >epoch=985, lrate=0.005, error=0.657\n >epoch=986, lrate=0.005, error=0.656\n >epoch=987, lrate=0.005, error=0.654\n >epoch=988, lrate=0.005, error=0.653\n >epoch=989, lrate=0.005, error=0.652\n >epoch=990, lrate=0.005, error=0.650\n >epoch=991, lrate=0.005, error=0.649\n >epoch=992, lrate=0.005, error=0.648\n >epoch=993, lrate=0.005, error=0.646\n >epoch=994, lrate=0.005, error=0.645\n >epoch=995, lrate=0.005, error=0.644\n >epoch=996, lrate=0.005, error=0.642\n >epoch=997, lrate=0.005, error=0.641\n >epoch=998, lrate=0.005, error=0.640\n >epoch=999, lrate=0.005, error=0.638\n >epoch=1000, lrate=0.005, error=0.637\n >epoch=1001, lrate=0.005, error=0.636\n >epoch=1002, lrate=0.005, error=0.634\n >epoch=1003, lrate=0.005, error=0.633\n >epoch=1004, lrate=0.005, error=0.632\n >epoch=1005, lrate=0.005, error=0.631\n >epoch=1006, lrate=0.005, error=0.629\n >epoch=1007, lrate=0.005, error=0.628\n >epoch=1008, lrate=0.005, error=0.627\n >epoch=1009, lrate=0.005, error=0.625\n >epoch=1010, lrate=0.005, error=0.624\n >epoch=1011, lrate=0.005, error=0.623\n >epoch=1012, lrate=0.005, error=0.621\n >epoch=1013, lrate=0.005, error=0.620\n >epoch=1014, lrate=0.005, error=0.619\n >epoch=1015, lrate=0.005, error=0.618\n >epoch=1016, lrate=0.005, error=0.616\n >epoch=1017, lrate=0.005, error=0.615\n >epoch=1018, lrate=0.005, error=0.614\n >epoch=1019, lrate=0.005, error=0.613\n >epoch=1020, lrate=0.005, error=0.611\n >epoch=1021, lrate=0.005, error=0.610\n >epoch=1022, lrate=0.005, error=0.609\n >epoch=1023, lrate=0.005, error=0.608\n >epoch=1024, lrate=0.005, error=0.606\n >epoch=1025, lrate=0.005, error=0.605\n >epoch=1026, lrate=0.005, error=0.604\n >epoch=1027, lrate=0.005, error=0.603\n >epoch=1028, lrate=0.005, error=0.601\n >epoch=1029, lrate=0.005, error=0.600\n >epoch=1030, lrate=0.005, error=0.599\n >epoch=1031, lrate=0.005, error=0.598\n >epoch=1032, lrate=0.005, error=0.596\n >epoch=1033, lrate=0.005, error=0.595\n >epoch=1034, lrate=0.005, error=0.594\n >epoch=1035, lrate=0.005, error=0.593\n >epoch=1036, lrate=0.005, error=0.591\n >epoch=1037, lrate=0.005, error=0.590\n >epoch=1038, lrate=0.005, error=0.589\n >epoch=1039, lrate=0.005, error=0.588\n >epoch=1040, lrate=0.005, error=0.587\n >epoch=1041, lrate=0.005, error=0.585\n >epoch=1042, lrate=0.005, error=0.584\n >epoch=1043, lrate=0.005, error=0.583\n >epoch=1044, lrate=0.005, error=0.582\n >epoch=1045, lrate=0.005, error=0.581\n >epoch=1046, lrate=0.005, error=0.579\n >epoch=1047, lrate=0.005, error=0.578\n >epoch=1048, lrate=0.005, error=0.577\n >epoch=1049, lrate=0.005, error=0.576\n >epoch=1050, lrate=0.005, error=0.575\n >epoch=1051, lrate=0.005, error=0.573\n >epoch=1052, lrate=0.005, error=0.572\n >epoch=1053, lrate=0.005, error=0.571\n >epoch=1054, lrate=0.005, error=0.570\n >epoch=1055, lrate=0.005, error=0.569\n >epoch=1056, lrate=0.005, error=0.568\n >epoch=1057, lrate=0.005, error=0.566\n >epoch=1058, lrate=0.005, error=0.565\n >epoch=1059, lrate=0.005, error=0.564\n >epoch=1060, lrate=0.005, error=0.563\n >epoch=1061, lrate=0.005, error=0.562\n >epoch=1062, lrate=0.005, error=0.561\n >epoch=1063, lrate=0.005, error=0.559\n >epoch=1064, lrate=0.005, error=0.558\n >epoch=1065, lrate=0.005, error=0.557\n >epoch=1066, lrate=0.005, error=0.556\n >epoch=1067, lrate=0.005, error=0.555\n >epoch=1068, lrate=0.005, error=0.554\n >epoch=1069, lrate=0.005, error=0.553\n >epoch=1070, lrate=0.005, error=0.551\n >epoch=1071, lrate=0.005, error=0.550\n >epoch=1072, lrate=0.005, error=0.549\n >epoch=1073, lrate=0.005, error=0.548\n >epoch=1074, lrate=0.005, error=0.547\n >epoch=1075, lrate=0.005, error=0.546\n >epoch=1076, lrate=0.005, error=0.545\n >epoch=1077, lrate=0.005, error=0.543\n >epoch=1078, lrate=0.005, error=0.542\n >epoch=1079, lrate=0.005, error=0.541\n >epoch=1080, lrate=0.005, error=0.540\n >epoch=1081, lrate=0.005, error=0.539\n >epoch=1082, lrate=0.005, error=0.538\n >epoch=1083, lrate=0.005, error=0.537\n >epoch=1084, lrate=0.005, error=0.536\n >epoch=1085, lrate=0.005, error=0.535\n >epoch=1086, lrate=0.005, error=0.533\n >epoch=1087, lrate=0.005, error=0.532\n >epoch=1088, lrate=0.005, error=0.531\n >epoch=1089, lrate=0.005, error=0.530\n >epoch=1090, lrate=0.005, error=0.529\n >epoch=1091, lrate=0.005, error=0.528\n >epoch=1092, lrate=0.005, error=0.527\n >epoch=1093, lrate=0.005, error=0.526\n >epoch=1094, lrate=0.005, error=0.525\n >epoch=1095, lrate=0.005, error=0.524\n >epoch=1096, lrate=0.005, error=0.523\n >epoch=1097, lrate=0.005, error=0.521\n >epoch=1098, lrate=0.005, error=0.520\n >epoch=1099, lrate=0.005, error=0.519\n >epoch=1100, lrate=0.005, error=0.518\n >epoch=1101, lrate=0.005, error=0.517\n >epoch=1102, lrate=0.005, error=0.516\n >epoch=1103, lrate=0.005, error=0.515\n >epoch=1104, lrate=0.005, error=0.514\n >epoch=1105, lrate=0.005, error=0.513\n >epoch=1106, lrate=0.005, error=0.512\n >epoch=1107, lrate=0.005, error=0.511\n >epoch=1108, lrate=0.005, error=0.510\n >epoch=1109, lrate=0.005, error=0.509\n >epoch=1110, lrate=0.005, error=0.508\n >epoch=1111, lrate=0.005, error=0.507\n >epoch=1112, lrate=0.005, error=0.506\n >epoch=1113, lrate=0.005, error=0.505\n >epoch=1114, lrate=0.005, error=0.503\n >epoch=1115, lrate=0.005, error=0.502\n >epoch=1116, lrate=0.005, error=0.501\n >epoch=1117, lrate=0.005, error=0.500\n >epoch=1118, lrate=0.005, error=0.499\n >epoch=1119, lrate=0.005, error=0.498\n >epoch=1120, lrate=0.005, error=0.497\n >epoch=1121, lrate=0.005, error=0.496\n >epoch=1122, lrate=0.005, error=0.495\n >epoch=1123, lrate=0.005, error=0.494\n >epoch=1124, lrate=0.005, error=0.493\n >epoch=1125, lrate=0.005, error=0.492\n >epoch=1126, lrate=0.005, error=0.491\n >epoch=1127, lrate=0.005, error=0.490\n >epoch=1128, lrate=0.005, error=0.489\n >epoch=1129, lrate=0.005, error=0.488\n >epoch=1130, lrate=0.005, error=0.487\n >epoch=1131, lrate=0.005, error=0.486\n >epoch=1132, lrate=0.005, error=0.485\n >epoch=1133, lrate=0.005, error=0.484\n >epoch=1134, lrate=0.005, error=0.483\n >epoch=1135, lrate=0.005, error=0.482\n >epoch=1136, lrate=0.005, error=0.481\n >epoch=1137, lrate=0.005, error=0.480\n >epoch=1138, lrate=0.005, error=0.479\n >epoch=1139, lrate=0.005, error=0.478\n >epoch=1140, lrate=0.005, error=0.477\n >epoch=1141, lrate=0.005, error=0.476\n >epoch=1142, lrate=0.005, error=0.475\n >epoch=1143, lrate=0.005, error=0.474\n >epoch=1144, lrate=0.005, error=0.473\n >epoch=1145, lrate=0.005, error=0.472\n >epoch=1146, lrate=0.005, error=0.471\n >epoch=1147, lrate=0.005, error=0.470\n >epoch=1148, lrate=0.005, error=0.469\n >epoch=1149, lrate=0.005, error=0.468\n >epoch=1150, lrate=0.005, error=0.467\n >epoch=1151, lrate=0.005, error=0.466\n >epoch=1152, lrate=0.005, error=0.466\n >epoch=1153, lrate=0.005, error=0.465\n >epoch=1154, lrate=0.005, error=0.464\n >epoch=1155, lrate=0.005, error=0.463\n >epoch=1156, lrate=0.005, error=0.462\n >epoch=1157, lrate=0.005, error=0.461\n >epoch=1158, lrate=0.005, error=0.460\n >epoch=1159, lrate=0.005, error=0.459\n >epoch=1160, lrate=0.005, error=0.458\n >epoch=1161, lrate=0.005, error=0.457\n >epoch=1162, lrate=0.005, error=0.456\n >epoch=1163, lrate=0.005, error=0.455\n >epoch=1164, lrate=0.005, error=0.454\n >epoch=1165, lrate=0.005, error=0.453\n >epoch=1166, lrate=0.005, error=0.452\n >epoch=1167, lrate=0.005, error=0.451\n >epoch=1168, lrate=0.005, error=0.450\n >epoch=1169, lrate=0.005, error=0.449\n >epoch=1170, lrate=0.005, error=0.449\n >epoch=1171, lrate=0.005, error=0.448\n >epoch=1172, lrate=0.005, error=0.447\n >epoch=1173, lrate=0.005, error=0.446\n >epoch=1174, lrate=0.005, error=0.445\n >epoch=1175, lrate=0.005, error=0.444\n >epoch=1176, lrate=0.005, error=0.443\n >epoch=1177, lrate=0.005, error=0.442\n >epoch=1178, lrate=0.005, error=0.441\n >epoch=1179, lrate=0.005, error=0.440\n >epoch=1180, lrate=0.005, error=0.439\n >epoch=1181, lrate=0.005, error=0.438\n >epoch=1182, lrate=0.005, error=0.438\n >epoch=1183, lrate=0.005, error=0.437\n >epoch=1184, lrate=0.005, error=0.436\n >epoch=1185, lrate=0.005, error=0.435\n >epoch=1186, lrate=0.005, error=0.434\n >epoch=1187, lrate=0.005, error=0.433\n >epoch=1188, lrate=0.005, error=0.432\n >epoch=1189, lrate=0.005, error=0.431\n >epoch=1190, lrate=0.005, error=0.430\n >epoch=1191, lrate=0.005, error=0.429\n >epoch=1192, lrate=0.005, error=0.429\n >epoch=1193, lrate=0.005, error=0.428\n >epoch=1194, lrate=0.005, error=0.427\n >epoch=1195, lrate=0.005, error=0.426\n >epoch=1196, lrate=0.005, error=0.425\n >epoch=1197, lrate=0.005, error=0.424\n >epoch=1198, lrate=0.005, error=0.423\n >epoch=1199, lrate=0.005, error=0.422\n >epoch=1200, lrate=0.005, error=0.422\n >epoch=1201, lrate=0.005, error=0.421\n >epoch=1202, lrate=0.005, error=0.420\n >epoch=1203, lrate=0.005, error=0.419\n >epoch=1204, lrate=0.005, error=0.418\n >epoch=1205, lrate=0.005, error=0.417\n >epoch=1206, lrate=0.005, error=0.416\n >epoch=1207, lrate=0.005, error=0.416\n >epoch=1208, lrate=0.005, error=0.415\n >epoch=1209, lrate=0.005, error=0.414\n >epoch=1210, lrate=0.005, error=0.413\n >epoch=1211, lrate=0.005, error=0.412\n >epoch=1212, lrate=0.005, error=0.411\n >epoch=1213, lrate=0.005, error=0.410\n >epoch=1214, lrate=0.005, error=0.410\n >epoch=1215, lrate=0.005, error=0.409\n >epoch=1216, lrate=0.005, error=0.408\n >epoch=1217, lrate=0.005, error=0.407\n >epoch=1218, lrate=0.005, error=0.406\n >epoch=1219, lrate=0.005, error=0.405\n >epoch=1220, lrate=0.005, error=0.405\n >epoch=1221, lrate=0.005, error=0.404\n >epoch=1222, lrate=0.005, error=0.403\n >epoch=1223, lrate=0.005, error=0.402\n >epoch=1224, lrate=0.005, error=0.401\n >epoch=1225, lrate=0.005, error=0.400\n >epoch=1226, lrate=0.005, error=0.400\n >epoch=1227, lrate=0.005, error=0.399\n >epoch=1228, lrate=0.005, error=0.398\n >epoch=1229, lrate=0.005, error=0.397\n >epoch=1230, lrate=0.005, error=0.396\n >epoch=1231, lrate=0.005, error=0.395\n >epoch=1232, lrate=0.005, error=0.395\n >epoch=1233, lrate=0.005, error=0.394\n >epoch=1234, lrate=0.005, error=0.393\n >epoch=1235, lrate=0.005, error=0.392\n >epoch=1236, lrate=0.005, error=0.391\n >epoch=1237, lrate=0.005, error=0.391\n >epoch=1238, lrate=0.005, error=0.390\n >epoch=1239, lrate=0.005, error=0.389\n >epoch=1240, lrate=0.005, error=0.388\n >epoch=1241, lrate=0.005, error=0.387\n >epoch=1242, lrate=0.005, error=0.387\n >epoch=1243, lrate=0.005, error=0.386\n >epoch=1244, lrate=0.005, error=0.385\n >epoch=1245, lrate=0.005, error=0.384\n >epoch=1246, lrate=0.005, error=0.383\n >epoch=1247, lrate=0.005, error=0.383\n >epoch=1248, lrate=0.005, error=0.382\n >epoch=1249, lrate=0.005, error=0.381\n >epoch=1250, lrate=0.005, error=0.380\n >epoch=1251, lrate=0.005, error=0.379\n >epoch=1252, lrate=0.005, error=0.379\n >epoch=1253, lrate=0.005, error=0.378\n >epoch=1254, lrate=0.005, error=0.377\n >epoch=1255, lrate=0.005, error=0.376\n >epoch=1256, lrate=0.005, error=0.376\n >epoch=1257, lrate=0.005, error=0.375\n >epoch=1258, lrate=0.005, error=0.374\n >epoch=1259, lrate=0.005, error=0.373\n >epoch=1260, lrate=0.005, error=0.372\n >epoch=1261, lrate=0.005, error=0.372\n >epoch=1262, lrate=0.005, error=0.371\n >epoch=1263, lrate=0.005, error=0.370\n >epoch=1264, lrate=0.005, error=0.369\n >epoch=1265, lrate=0.005, error=0.369\n >epoch=1266, lrate=0.005, error=0.368\n >epoch=1267, lrate=0.005, error=0.367\n >epoch=1268, lrate=0.005, error=0.366\n >epoch=1269, lrate=0.005, error=0.366\n >epoch=1270, lrate=0.005, error=0.365\n >epoch=1271, lrate=0.005, error=0.364\n >epoch=1272, lrate=0.005, error=0.363\n >epoch=1273, lrate=0.005, error=0.363\n >epoch=1274, lrate=0.005, error=0.362\n >epoch=1275, lrate=0.005, error=0.361\n >epoch=1276, lrate=0.005, error=0.360\n >epoch=1277, lrate=0.005, error=0.360\n >epoch=1278, lrate=0.005, error=0.359\n >epoch=1279, lrate=0.005, error=0.358\n >epoch=1280, lrate=0.005, error=0.357\n >epoch=1281, lrate=0.005, error=0.357\n >epoch=1282, lrate=0.005, error=0.356\n >epoch=1283, lrate=0.005, error=0.355\n >epoch=1284, lrate=0.005, error=0.354\n >epoch=1285, lrate=0.005, error=0.354\n >epoch=1286, lrate=0.005, error=0.353\n >epoch=1287, lrate=0.005, error=0.352\n >epoch=1288, lrate=0.005, error=0.352\n >epoch=1289, lrate=0.005, error=0.351\n >epoch=1290, lrate=0.005, error=0.350\n >epoch=1291, lrate=0.005, error=0.349\n >epoch=1292, lrate=0.005, error=0.349\n >epoch=1293, lrate=0.005, error=0.348\n >epoch=1294, lrate=0.005, error=0.347\n >epoch=1295, lrate=0.005, error=0.347\n >epoch=1296, lrate=0.005, error=0.346\n >epoch=1297, lrate=0.005, error=0.345\n >epoch=1298, lrate=0.005, error=0.344\n >epoch=1299, lrate=0.005, error=0.344\n >epoch=1300, lrate=0.005, error=0.343\n >epoch=1301, lrate=0.005, error=0.342\n >epoch=1302, lrate=0.005, error=0.342\n >epoch=1303, lrate=0.005, error=0.341\n >epoch=1304, lrate=0.005, error=0.340\n >epoch=1305, lrate=0.005, error=0.339\n >epoch=1306, lrate=0.005, error=0.339\n >epoch=1307, lrate=0.005, error=0.338\n >epoch=1308, lrate=0.005, error=0.337\n >epoch=1309, lrate=0.005, error=0.337\n >epoch=1310, lrate=0.005, error=0.336\n >epoch=1311, lrate=0.005, error=0.335\n >epoch=1312, lrate=0.005, error=0.335\n >epoch=1313, lrate=0.005, error=0.334\n >epoch=1314, lrate=0.005, error=0.333\n >epoch=1315, lrate=0.005, error=0.332\n >epoch=1316, lrate=0.005, error=0.332\n >epoch=1317, lrate=0.005, error=0.331\n >epoch=1318, lrate=0.005, error=0.330\n >epoch=1319, lrate=0.005, error=0.330\n >epoch=1320, lrate=0.005, error=0.329\n >epoch=1321, lrate=0.005, error=0.328\n >epoch=1322, lrate=0.005, error=0.328\n >epoch=1323, lrate=0.005, error=0.327\n >epoch=1324, lrate=0.005, error=0.326\n >epoch=1325, lrate=0.005, error=0.326\n >epoch=1326, lrate=0.005, error=0.325\n >epoch=1327, lrate=0.005, error=0.324\n >epoch=1328, lrate=0.005, error=0.324\n >epoch=1329, lrate=0.005, error=0.323\n >epoch=1330, lrate=0.005, error=0.322\n >epoch=1331, lrate=0.005, error=0.322\n >epoch=1332, lrate=0.005, error=0.321\n >epoch=1333, lrate=0.005, error=0.320\n >epoch=1334, lrate=0.005, error=0.320\n >epoch=1335, lrate=0.005, error=0.319\n >epoch=1336, lrate=0.005, error=0.318\n >epoch=1337, lrate=0.005, error=0.318\n >epoch=1338, lrate=0.005, error=0.317\n >epoch=1339, lrate=0.005, error=0.316\n >epoch=1340, lrate=0.005, error=0.316\n >epoch=1341, lrate=0.005, error=0.315\n >epoch=1342, lrate=0.005, error=0.314\n >epoch=1343, lrate=0.005, error=0.314\n >epoch=1344, lrate=0.005, error=0.313\n >epoch=1345, lrate=0.005, error=0.313\n >epoch=1346, lrate=0.005, error=0.312\n >epoch=1347, lrate=0.005, error=0.311\n >epoch=1348, lrate=0.005, error=0.311\n >epoch=1349, lrate=0.005, error=0.310\n >epoch=1350, lrate=0.005, error=0.309\n >epoch=1351, lrate=0.005, error=0.309\n >epoch=1352, lrate=0.005, error=0.308\n >epoch=1353, lrate=0.005, error=0.307\n >epoch=1354, lrate=0.005, error=0.307\n >epoch=1355, lrate=0.005, error=0.306\n >epoch=1356, lrate=0.005, error=0.306\n >epoch=1357, lrate=0.005, error=0.305\n >epoch=1358, lrate=0.005, error=0.304\n >epoch=1359, lrate=0.005, error=0.304\n >epoch=1360, lrate=0.005, error=0.303\n >epoch=1361, lrate=0.005, error=0.302\n >epoch=1362, lrate=0.005, error=0.302\n >epoch=1363, lrate=0.005, error=0.301\n >epoch=1364, lrate=0.005, error=0.301\n >epoch=1365, lrate=0.005, error=0.300\n >epoch=1366, lrate=0.005, error=0.299\n >epoch=1367, lrate=0.005, error=0.299\n >epoch=1368, lrate=0.005, error=0.298\n >epoch=1369, lrate=0.005, error=0.297\n >epoch=1370, lrate=0.005, error=0.297\n >epoch=1371, lrate=0.005, error=0.296\n >epoch=1372, lrate=0.005, error=0.296\n >epoch=1373, lrate=0.005, error=0.295\n >epoch=1374, lrate=0.005, error=0.294\n >epoch=1375, lrate=0.005, error=0.294\n >epoch=1376, lrate=0.005, error=0.293\n >epoch=1377, lrate=0.005, error=0.293\n >epoch=1378, lrate=0.005, error=0.292\n >epoch=1379, lrate=0.005, error=0.291\n >epoch=1380, lrate=0.005, error=0.291\n >epoch=1381, lrate=0.005, error=0.290\n >epoch=1382, lrate=0.005, error=0.290\n >epoch=1383, lrate=0.005, error=0.289\n >epoch=1384, lrate=0.005, error=0.288\n >epoch=1385, lrate=0.005, error=0.288\n >epoch=1386, lrate=0.005, error=0.287\n >epoch=1387, lrate=0.005, error=0.287\n >epoch=1388, lrate=0.005, error=0.286\n >epoch=1389, lrate=0.005, error=0.285\n >epoch=1390, lrate=0.005, error=0.285\n >epoch=1391, lrate=0.005, error=0.284\n >epoch=1392, lrate=0.005, error=0.284\n >epoch=1393, lrate=0.005, error=0.283\n >epoch=1394, lrate=0.005, error=0.282\n >epoch=1395, lrate=0.005, error=0.282\n >epoch=1396, lrate=0.005, error=0.281\n >epoch=1397, lrate=0.005, error=0.281\n >epoch=1398, lrate=0.005, error=0.280\n >epoch=1399, lrate=0.005, error=0.280\n >epoch=1400, lrate=0.005, error=0.279\n >epoch=1401, lrate=0.005, error=0.278\n >epoch=1402, lrate=0.005, error=0.278\n >epoch=1403, lrate=0.005, error=0.277\n >epoch=1404, lrate=0.005, error=0.277\n >epoch=1405, lrate=0.005, error=0.276\n >epoch=1406, lrate=0.005, error=0.276\n >epoch=1407, lrate=0.005, error=0.275\n >epoch=1408, lrate=0.005, error=0.274\n >epoch=1409, lrate=0.005, error=0.274\n >epoch=1410, lrate=0.005, error=0.273\n >epoch=1411, lrate=0.005, error=0.273\n >epoch=1412, lrate=0.005, error=0.272\n >epoch=1413, lrate=0.005, error=0.272\n >epoch=1414, lrate=0.005, error=0.271\n >epoch=1415, lrate=0.005, error=0.270\n >epoch=1416, lrate=0.005, error=0.270\n >epoch=1417, lrate=0.005, error=0.269\n >epoch=1418, lrate=0.005, error=0.269\n >epoch=1419, lrate=0.005, error=0.268\n >epoch=1420, lrate=0.005, error=0.268\n >epoch=1421, lrate=0.005, error=0.267\n >epoch=1422, lrate=0.005, error=0.267\n >epoch=1423, lrate=0.005, error=0.266\n >epoch=1424, lrate=0.005, error=0.265\n >epoch=1425, lrate=0.005, error=0.265\n >epoch=1426, lrate=0.005, error=0.264\n >epoch=1427, lrate=0.005, error=0.264\n >epoch=1428, lrate=0.005, error=0.263\n >epoch=1429, lrate=0.005, error=0.263\n >epoch=1430, lrate=0.005, error=0.262\n >epoch=1431, lrate=0.005, error=0.262\n >epoch=1432, lrate=0.005, error=0.261\n >epoch=1433, lrate=0.005, error=0.261\n >epoch=1434, lrate=0.005, error=0.260\n >epoch=1435, lrate=0.005, error=0.260\n >epoch=1436, lrate=0.005, error=0.259\n >epoch=1437, lrate=0.005, error=0.258\n >epoch=1438, lrate=0.005, error=0.258\n >epoch=1439, lrate=0.005, error=0.257\n >epoch=1440, lrate=0.005, error=0.257\n >epoch=1441, lrate=0.005, error=0.256\n >epoch=1442, lrate=0.005, error=0.256\n >epoch=1443, lrate=0.005, error=0.255\n >epoch=1444, lrate=0.005, error=0.255\n >epoch=1445, lrate=0.005, error=0.254\n >epoch=1446, lrate=0.005, error=0.254\n >epoch=1447, lrate=0.005, error=0.253\n >epoch=1448, lrate=0.005, error=0.253\n >epoch=1449, lrate=0.005, error=0.252\n >epoch=1450, lrate=0.005, error=0.252\n >epoch=1451, lrate=0.005, error=0.251\n >epoch=1452, lrate=0.005, error=0.251\n >epoch=1453, lrate=0.005, error=0.250\n >epoch=1454, lrate=0.005, error=0.250\n >epoch=1455, lrate=0.005, error=0.249\n >epoch=1456, lrate=0.005, error=0.249\n >epoch=1457, lrate=0.005, error=0.248\n >epoch=1458, lrate=0.005, error=0.248\n >epoch=1459, lrate=0.005, error=0.247\n >epoch=1460, lrate=0.005, error=0.246\n >epoch=1461, lrate=0.005, error=0.246\n >epoch=1462, lrate=0.005, error=0.245\n >epoch=1463, lrate=0.005, error=0.245\n >epoch=1464, lrate=0.005, error=0.244\n >epoch=1465, lrate=0.005, error=0.244\n >epoch=1466, lrate=0.005, error=0.243\n >epoch=1467, lrate=0.005, error=0.243\n >epoch=1468, lrate=0.005, error=0.242\n >epoch=1469, lrate=0.005, error=0.242\n >epoch=1470, lrate=0.005, error=0.241\n >epoch=1471, lrate=0.005, error=0.241\n >epoch=1472, lrate=0.005, error=0.240\n >epoch=1473, lrate=0.005, error=0.240\n >epoch=1474, lrate=0.005, error=0.239\n >epoch=1475, lrate=0.005, error=0.239\n >epoch=1476, lrate=0.005, error=0.238\n >epoch=1477, lrate=0.005, error=0.238\n >epoch=1478, lrate=0.005, error=0.237\n >epoch=1479, lrate=0.005, error=0.237\n >epoch=1480, lrate=0.005, error=0.237\n >epoch=1481, lrate=0.005, error=0.236\n >epoch=1482, lrate=0.005, error=0.236\n >epoch=1483, lrate=0.005, error=0.235\n >epoch=1484, lrate=0.005, error=0.235\n >epoch=1485, lrate=0.005, error=0.234\n >epoch=1486, lrate=0.005, error=0.234\n >epoch=1487, lrate=0.005, error=0.233\n >epoch=1488, lrate=0.005, error=0.233\n >epoch=1489, lrate=0.005, error=0.232\n >epoch=1490, lrate=0.005, error=0.232\n >epoch=1491, lrate=0.005, error=0.231\n >epoch=1492, lrate=0.005, error=0.231\n >epoch=1493, lrate=0.005, error=0.230\n >epoch=1494, lrate=0.005, error=0.230\n >epoch=1495, lrate=0.005, error=0.229\n >epoch=1496, lrate=0.005, error=0.229\n >epoch=1497, lrate=0.005, error=0.228\n >epoch=1498, lrate=0.005, error=0.228\n >epoch=1499, lrate=0.005, error=0.227\n >epoch=1500, lrate=0.005, error=0.227\n >epoch=1501, lrate=0.005, error=0.226\n >epoch=1502, lrate=0.005, error=0.226\n >epoch=1503, lrate=0.005, error=0.226\n >epoch=1504, lrate=0.005, error=0.225\n >epoch=1505, lrate=0.005, error=0.225\n >epoch=1506, lrate=0.005, error=0.224\n >epoch=1507, lrate=0.005, error=0.224\n >epoch=1508, lrate=0.005, error=0.223\n >epoch=1509, lrate=0.005, error=0.223\n >epoch=1510, lrate=0.005, error=0.222\n >epoch=1511, lrate=0.005, error=0.222\n >epoch=1512, lrate=0.005, error=0.221\n >epoch=1513, lrate=0.005, error=0.221\n >epoch=1514, lrate=0.005, error=0.220\n >epoch=1515, lrate=0.005, error=0.220\n >epoch=1516, lrate=0.005, error=0.220\n >epoch=1517, lrate=0.005, error=0.219\n >epoch=1518, lrate=0.005, error=0.219\n >epoch=1519, lrate=0.005, error=0.218\n >epoch=1520, lrate=0.005, error=0.218\n >epoch=1521, lrate=0.005, error=0.217\n >epoch=1522, lrate=0.005, error=0.217\n >epoch=1523, lrate=0.005, error=0.216\n >epoch=1524, lrate=0.005, error=0.216\n >epoch=1525, lrate=0.005, error=0.216\n >epoch=1526, lrate=0.005, error=0.215\n >epoch=1527, lrate=0.005, error=0.215\n >epoch=1528, lrate=0.005, error=0.214\n >epoch=1529, lrate=0.005, error=0.214\n >epoch=1530, lrate=0.005, error=0.213\n >epoch=1531, lrate=0.005, error=0.213\n >epoch=1532, lrate=0.005, error=0.212\n >epoch=1533, lrate=0.005, error=0.212\n >epoch=1534, lrate=0.005, error=0.212\n >epoch=1535, lrate=0.005, error=0.211\n >epoch=1536, lrate=0.005, error=0.211\n >epoch=1537, lrate=0.005, error=0.210\n >epoch=1538, lrate=0.005, error=0.210\n >epoch=1539, lrate=0.005, error=0.209\n >epoch=1540, lrate=0.005, error=0.209\n >epoch=1541, lrate=0.005, error=0.209\n >epoch=1542, lrate=0.005, error=0.208\n >epoch=1543, lrate=0.005, error=0.208\n >epoch=1544, lrate=0.005, error=0.207\n >epoch=1545, lrate=0.005, error=0.207\n >epoch=1546, lrate=0.005, error=0.206\n >epoch=1547, lrate=0.005, error=0.206\n >epoch=1548, lrate=0.005, error=0.206\n >epoch=1549, lrate=0.005, error=0.205\n >epoch=1550, lrate=0.005, error=0.205\n >epoch=1551, lrate=0.005, error=0.204\n >epoch=1552, lrate=0.005, error=0.204\n >epoch=1553, lrate=0.005, error=0.203\n >epoch=1554, lrate=0.005, error=0.203\n >epoch=1555, lrate=0.005, error=0.203\n >epoch=1556, lrate=0.005, error=0.202\n >epoch=1557, lrate=0.005, error=0.202\n >epoch=1558, lrate=0.005, error=0.201\n >epoch=1559, lrate=0.005, error=0.201\n >epoch=1560, lrate=0.005, error=0.201\n >epoch=1561, lrate=0.005, error=0.200\n >epoch=1562, lrate=0.005, error=0.200\n >epoch=1563, lrate=0.005, error=0.199\n >epoch=1564, lrate=0.005, error=0.199\n >epoch=1565, lrate=0.005, error=0.198\n >epoch=1566, lrate=0.005, error=0.198\n >epoch=1567, lrate=0.005, error=0.198\n >epoch=1568, lrate=0.005, error=0.197\n >epoch=1569, lrate=0.005, error=0.197\n >epoch=1570, lrate=0.005, error=0.196\n >epoch=1571, lrate=0.005, error=0.196\n >epoch=1572, lrate=0.005, error=0.196\n >epoch=1573, lrate=0.005, error=0.195\n >epoch=1574, lrate=0.005, error=0.195\n >epoch=1575, lrate=0.005, error=0.194\n >epoch=1576, lrate=0.005, error=0.194\n >epoch=1577, lrate=0.005, error=0.194\n >epoch=1578, lrate=0.005, error=0.193\n >epoch=1579, lrate=0.005, error=0.193\n >epoch=1580, lrate=0.005, error=0.192\n >epoch=1581, lrate=0.005, error=0.192\n >epoch=1582, lrate=0.005, error=0.192\n >epoch=1583, lrate=0.005, error=0.191\n >epoch=1584, lrate=0.005, error=0.191\n >epoch=1585, lrate=0.005, error=0.190\n >epoch=1586, lrate=0.005, error=0.190\n >epoch=1587, lrate=0.005, error=0.190\n >epoch=1588, lrate=0.005, error=0.189\n >epoch=1589, lrate=0.005, error=0.189\n >epoch=1590, lrate=0.005, error=0.188\n >epoch=1591, lrate=0.005, error=0.188\n >epoch=1592, lrate=0.005, error=0.188\n >epoch=1593, lrate=0.005, error=0.187\n >epoch=1594, lrate=0.005, error=0.187\n >epoch=1595, lrate=0.005, error=0.187\n >epoch=1596, lrate=0.005, error=0.186\n >epoch=1597, lrate=0.005, error=0.186\n >epoch=1598, lrate=0.005, error=0.185\n >epoch=1599, lrate=0.005, error=0.185\n >epoch=1600, lrate=0.005, error=0.185\n >epoch=1601, lrate=0.005, error=0.184\n >epoch=1602, lrate=0.005, error=0.184\n >epoch=1603, lrate=0.005, error=0.183\n >epoch=1604, lrate=0.005, error=0.183\n >epoch=1605, lrate=0.005, error=0.183\n >epoch=1606, lrate=0.005, error=0.182\n >epoch=1607, lrate=0.005, error=0.182\n >epoch=1608, lrate=0.005, error=0.182\n >epoch=1609, lrate=0.005, error=0.181\n >epoch=1610, lrate=0.005, error=0.181\n >epoch=1611, lrate=0.005, error=0.180\n >epoch=1612, lrate=0.005, error=0.180\n >epoch=1613, lrate=0.005, error=0.180\n >epoch=1614, lrate=0.005, error=0.179\n >epoch=1615, lrate=0.005, error=0.179\n >epoch=1616, lrate=0.005, error=0.179\n >epoch=1617, lrate=0.005, error=0.178\n >epoch=1618, lrate=0.005, error=0.178\n >epoch=1619, lrate=0.005, error=0.178\n >epoch=1620, lrate=0.005, error=0.177\n >epoch=1621, lrate=0.005, error=0.177\n >epoch=1622, lrate=0.005, error=0.176\n >epoch=1623, lrate=0.005, error=0.176\n >epoch=1624, lrate=0.005, error=0.176\n >epoch=1625, lrate=0.005, error=0.175\n >epoch=1626, lrate=0.005, error=0.175\n >epoch=1627, lrate=0.005, error=0.175\n >epoch=1628, lrate=0.005, error=0.174\n >epoch=1629, lrate=0.005, error=0.174\n >epoch=1630, lrate=0.005, error=0.174\n >epoch=1631, lrate=0.005, error=0.173\n >epoch=1632, lrate=0.005, error=0.173\n >epoch=1633, lrate=0.005, error=0.172\n >epoch=1634, lrate=0.005, error=0.172\n >epoch=1635, lrate=0.005, error=0.172\n >epoch=1636, lrate=0.005, error=0.171\n >epoch=1637, lrate=0.005, error=0.171\n >epoch=1638, lrate=0.005, error=0.171\n >epoch=1639, lrate=0.005, error=0.170\n >epoch=1640, lrate=0.005, error=0.170\n >epoch=1641, lrate=0.005, error=0.170\n >epoch=1642, lrate=0.005, error=0.169\n >epoch=1643, lrate=0.005, error=0.169\n >epoch=1644, lrate=0.005, error=0.169\n >epoch=1645, lrate=0.005, error=0.168\n >epoch=1646, lrate=0.005, error=0.168\n >epoch=1647, lrate=0.005, error=0.168\n >epoch=1648, lrate=0.005, error=0.167\n >epoch=1649, lrate=0.005, error=0.167\n >epoch=1650, lrate=0.005, error=0.167\n >epoch=1651, lrate=0.005, error=0.166\n >epoch=1652, lrate=0.005, error=0.166\n >epoch=1653, lrate=0.005, error=0.165\n >epoch=1654, lrate=0.005, error=0.165\n >epoch=1655, lrate=0.005, error=0.165\n >epoch=1656, lrate=0.005, error=0.164\n >epoch=1657, lrate=0.005, error=0.164\n >epoch=1658, lrate=0.005, error=0.164\n >epoch=1659, lrate=0.005, error=0.163\n >epoch=1660, lrate=0.005, error=0.163\n >epoch=1661, lrate=0.005, error=0.163\n >epoch=1662, lrate=0.005, error=0.162\n >epoch=1663, lrate=0.005, error=0.162\n >epoch=1664, lrate=0.005, error=0.162\n >epoch=1665, lrate=0.005, error=0.161\n >epoch=1666, lrate=0.005, error=0.161\n >epoch=1667, lrate=0.005, error=0.161\n >epoch=1668, lrate=0.005, error=0.160\n >epoch=1669, lrate=0.005, error=0.160\n >epoch=1670, lrate=0.005, error=0.160\n >epoch=1671, lrate=0.005, error=0.159\n >epoch=1672, lrate=0.005, error=0.159\n >epoch=1673, lrate=0.005, error=0.159\n >epoch=1674, lrate=0.005, error=0.158\n >epoch=1675, lrate=0.005, error=0.158\n >epoch=1676, lrate=0.005, error=0.158\n >epoch=1677, lrate=0.005, error=0.157\n >epoch=1678, lrate=0.005, error=0.157\n >epoch=1679, lrate=0.005, error=0.157\n >epoch=1680, lrate=0.005, error=0.157\n >epoch=1681, lrate=0.005, error=0.156\n >epoch=1682, lrate=0.005, error=0.156\n >epoch=1683, lrate=0.005, error=0.156\n >epoch=1684, lrate=0.005, error=0.155\n >epoch=1685, lrate=0.005, error=0.155\n >epoch=1686, lrate=0.005, error=0.155\n >epoch=1687, lrate=0.005, error=0.154\n >epoch=1688, lrate=0.005, error=0.154\n >epoch=1689, lrate=0.005, error=0.154\n >epoch=1690, lrate=0.005, error=0.153\n >epoch=1691, lrate=0.005, error=0.153\n >epoch=1692, lrate=0.005, error=0.153\n >epoch=1693, lrate=0.005, error=0.152\n >epoch=1694, lrate=0.005, error=0.152\n >epoch=1695, lrate=0.005, error=0.152\n >epoch=1696, lrate=0.005, error=0.151\n >epoch=1697, lrate=0.005, error=0.151\n >epoch=1698, lrate=0.005, error=0.151\n >epoch=1699, lrate=0.005, error=0.150\n >epoch=1700, lrate=0.005, error=0.150\n >epoch=1701, lrate=0.005, error=0.150\n >epoch=1702, lrate=0.005, error=0.150\n >epoch=1703, lrate=0.005, error=0.149\n >epoch=1704, lrate=0.005, error=0.149\n >epoch=1705, lrate=0.005, error=0.149\n >epoch=1706, lrate=0.005, error=0.148\n >epoch=1707, lrate=0.005, error=0.148\n >epoch=1708, lrate=0.005, error=0.148\n >epoch=1709, lrate=0.005, error=0.147\n >epoch=1710, lrate=0.005, error=0.147\n >epoch=1711, lrate=0.005, error=0.147\n >epoch=1712, lrate=0.005, error=0.147\n >epoch=1713, lrate=0.005, error=0.146\n >epoch=1714, lrate=0.005, error=0.146\n >epoch=1715, lrate=0.005, error=0.146\n >epoch=1716, lrate=0.005, error=0.145\n >epoch=1717, lrate=0.005, error=0.145\n >epoch=1718, lrate=0.005, error=0.145\n >epoch=1719, lrate=0.005, error=0.144\n >epoch=1720, lrate=0.005, error=0.144\n >epoch=1721, lrate=0.005, error=0.144\n >epoch=1722, lrate=0.005, error=0.144\n >epoch=1723, lrate=0.005, error=0.143\n >epoch=1724, lrate=0.005, error=0.143\n >epoch=1725, lrate=0.005, error=0.143\n >epoch=1726, lrate=0.005, error=0.142\n >epoch=1727, lrate=0.005, error=0.142\n >epoch=1728, lrate=0.005, error=0.142\n >epoch=1729, lrate=0.005, error=0.141\n >epoch=1730, lrate=0.005, error=0.141\n >epoch=1731, lrate=0.005, error=0.141\n >epoch=1732, lrate=0.005, error=0.141\n >epoch=1733, lrate=0.005, error=0.140\n >epoch=1734, lrate=0.005, error=0.140\n >epoch=1735, lrate=0.005, error=0.140\n >epoch=1736, lrate=0.005, error=0.139\n >epoch=1737, lrate=0.005, error=0.139\n >epoch=1738, lrate=0.005, error=0.139\n >epoch=1739, lrate=0.005, error=0.139\n >epoch=1740, lrate=0.005, error=0.138\n >epoch=1741, lrate=0.005, error=0.138\n >epoch=1742, lrate=0.005, error=0.138\n >epoch=1743, lrate=0.005, error=0.137\n >epoch=1744, lrate=0.005, error=0.137\n >epoch=1745, lrate=0.005, error=0.137\n >epoch=1746, lrate=0.005, error=0.137\n >epoch=1747, lrate=0.005, error=0.136\n >epoch=1748, lrate=0.005, error=0.136\n >epoch=1749, lrate=0.005, error=0.136\n >epoch=1750, lrate=0.005, error=0.135\n >epoch=1751, lrate=0.005, error=0.135\n >epoch=1752, lrate=0.005, error=0.135\n >epoch=1753, lrate=0.005, error=0.135\n >epoch=1754, lrate=0.005, error=0.134\n >epoch=1755, lrate=0.005, error=0.134\n >epoch=1756, lrate=0.005, error=0.134\n >epoch=1757, lrate=0.005, error=0.134\n >epoch=1758, lrate=0.005, error=0.133\n >epoch=1759, lrate=0.005, error=0.133\n >epoch=1760, lrate=0.005, error=0.133\n >epoch=1761, lrate=0.005, error=0.132\n >epoch=1762, lrate=0.005, error=0.132\n >epoch=1763, lrate=0.005, error=0.132\n >epoch=1764, lrate=0.005, error=0.132\n >epoch=1765, lrate=0.005, error=0.131\n >epoch=1766, lrate=0.005, error=0.131\n >epoch=1767, lrate=0.005, error=0.131\n >epoch=1768, lrate=0.005, error=0.131\n >epoch=1769, lrate=0.005, error=0.130\n >epoch=1770, lrate=0.005, error=0.130\n >epoch=1771, lrate=0.005, error=0.130\n >epoch=1772, lrate=0.005, error=0.129\n >epoch=1773, lrate=0.005, error=0.129\n >epoch=1774, lrate=0.005, error=0.129\n >epoch=1775, lrate=0.005, error=0.129\n >epoch=1776, lrate=0.005, error=0.128\n >epoch=1777, lrate=0.005, error=0.128\n >epoch=1778, lrate=0.005, error=0.128\n >epoch=1779, lrate=0.005, error=0.128\n >epoch=1780, lrate=0.005, error=0.127\n >epoch=1781, lrate=0.005, error=0.127\n >epoch=1782, lrate=0.005, error=0.127\n >epoch=1783, lrate=0.005, error=0.127\n >epoch=1784, lrate=0.005, error=0.126\n >epoch=1785, lrate=0.005, error=0.126\n >epoch=1786, lrate=0.005, error=0.126\n >epoch=1787, lrate=0.005, error=0.125\n >epoch=1788, lrate=0.005, error=0.125\n >epoch=1789, lrate=0.005, error=0.125\n >epoch=1790, lrate=0.005, error=0.125\n >epoch=1791, lrate=0.005, error=0.124\n >epoch=1792, lrate=0.005, error=0.124\n >epoch=1793, lrate=0.005, error=0.124\n >epoch=1794, lrate=0.005, error=0.124\n >epoch=1795, lrate=0.005, error=0.123\n >epoch=1796, lrate=0.005, error=0.123\n >epoch=1797, lrate=0.005, error=0.123\n >epoch=1798, lrate=0.005, error=0.123\n >epoch=1799, lrate=0.005, error=0.122\n >epoch=1800, lrate=0.005, error=0.122\n >epoch=1801, lrate=0.005, error=0.122\n >epoch=1802, lrate=0.005, error=0.122\n >epoch=1803, lrate=0.005, error=0.121\n >epoch=1804, lrate=0.005, error=0.121\n >epoch=1805, lrate=0.005, error=0.121\n >epoch=1806, lrate=0.005, error=0.121\n >epoch=1807, lrate=0.005, error=0.120\n >epoch=1808, lrate=0.005, error=0.120\n >epoch=1809, lrate=0.005, error=0.120\n >epoch=1810, lrate=0.005, error=0.120\n >epoch=1811, lrate=0.005, error=0.119\n >epoch=1812, lrate=0.005, error=0.119\n >epoch=1813, lrate=0.005, error=0.119\n >epoch=1814, lrate=0.005, error=0.119\n >epoch=1815, lrate=0.005, error=0.118\n >epoch=1816, lrate=0.005, error=0.118\n >epoch=1817, lrate=0.005, error=0.118\n >epoch=1818, lrate=0.005, error=0.118\n >epoch=1819, lrate=0.005, error=0.117\n >epoch=1820, lrate=0.005, error=0.117\n >epoch=1821, lrate=0.005, error=0.117\n >epoch=1822, lrate=0.005, error=0.117\n >epoch=1823, lrate=0.005, error=0.117\n >epoch=1824, lrate=0.005, error=0.116\n >epoch=1825, lrate=0.005, error=0.116\n >epoch=1826, lrate=0.005, error=0.116\n >epoch=1827, lrate=0.005, error=0.116\n >epoch=1828, lrate=0.005, error=0.115\n >epoch=1829, lrate=0.005, error=0.115\n >epoch=1830, lrate=0.005, error=0.115\n >epoch=1831, lrate=0.005, error=0.115\n >epoch=1832, lrate=0.005, error=0.114\n >epoch=1833, lrate=0.005, error=0.114\n >epoch=1834, lrate=0.005, error=0.114\n >epoch=1835, lrate=0.005, error=0.114\n >epoch=1836, lrate=0.005, error=0.113\n >epoch=1837, lrate=0.005, error=0.113\n >epoch=1838, lrate=0.005, error=0.113\n >epoch=1839, lrate=0.005, error=0.113\n >epoch=1840, lrate=0.005, error=0.112\n >epoch=1841, lrate=0.005, error=0.112\n >epoch=1842, lrate=0.005, error=0.112\n >epoch=1843, lrate=0.005, error=0.112\n >epoch=1844, lrate=0.005, error=0.112\n >epoch=1845, lrate=0.005, error=0.111\n >epoch=1846, lrate=0.005, error=0.111\n >epoch=1847, lrate=0.005, error=0.111\n >epoch=1848, lrate=0.005, error=0.111\n >epoch=1849, lrate=0.005, error=0.110\n >epoch=1850, lrate=0.005, error=0.110\n >epoch=1851, lrate=0.005, error=0.110\n >epoch=1852, lrate=0.005, error=0.110\n >epoch=1853, lrate=0.005, error=0.110\n >epoch=1854, lrate=0.005, error=0.109\n >epoch=1855, lrate=0.005, error=0.109\n >epoch=1856, lrate=0.005, error=0.109\n >epoch=1857, lrate=0.005, error=0.109\n >epoch=1858, lrate=0.005, error=0.108\n >epoch=1859, lrate=0.005, error=0.108\n >epoch=1860, lrate=0.005, error=0.108\n >epoch=1861, lrate=0.005, error=0.108\n >epoch=1862, lrate=0.005, error=0.107\n >epoch=1863, lrate=0.005, error=0.107\n >epoch=1864, lrate=0.005, error=0.107\n >epoch=1865, lrate=0.005, error=0.107\n >epoch=1866, lrate=0.005, error=0.107\n >epoch=1867, lrate=0.005, error=0.106\n >epoch=1868, lrate=0.005, error=0.106\n >epoch=1869, lrate=0.005, error=0.106\n >epoch=1870, lrate=0.005, error=0.106\n >epoch=1871, lrate=0.005, error=0.106\n >epoch=1872, lrate=0.005, error=0.105\n >epoch=1873, lrate=0.005, error=0.105\n >epoch=1874, lrate=0.005, error=0.105\n >epoch=1875, lrate=0.005, error=0.105\n >epoch=1876, lrate=0.005, error=0.104\n >epoch=1877, lrate=0.005, error=0.104\n >epoch=1878, lrate=0.005, error=0.104\n >epoch=1879, lrate=0.005, error=0.104\n >epoch=1880, lrate=0.005, error=0.104\n >epoch=1881, lrate=0.005, error=0.103\n >epoch=1882, lrate=0.005, error=0.103\n >epoch=1883, lrate=0.005, error=0.103\n >epoch=1884, lrate=0.005, error=0.103\n >epoch=1885, lrate=0.005, error=0.103\n >epoch=1886, lrate=0.005, error=0.102\n >epoch=1887, lrate=0.005, error=0.102\n >epoch=1888, lrate=0.005, error=0.102\n >epoch=1889, lrate=0.005, error=0.102\n >epoch=1890, lrate=0.005, error=0.101\n >epoch=1891, lrate=0.005, error=0.101\n >epoch=1892, lrate=0.005, error=0.101\n >epoch=1893, lrate=0.005, error=0.101\n >epoch=1894, lrate=0.005, error=0.101\n >epoch=1895, lrate=0.005, error=0.100\n >epoch=1896, lrate=0.005, error=0.100\n >epoch=1897, lrate=0.005, error=0.100\n >epoch=1898, lrate=0.005, error=0.100\n >epoch=1899, lrate=0.005, error=0.100\n >epoch=1900, lrate=0.005, error=0.099\n >epoch=1901, lrate=0.005, error=0.099\n >epoch=1902, lrate=0.005, error=0.099\n >epoch=1903, lrate=0.005, error=0.099\n >epoch=1904, lrate=0.005, error=0.099\n >epoch=1905, lrate=0.005, error=0.098\n >epoch=1906, lrate=0.005, error=0.098\n >epoch=1907, lrate=0.005, error=0.098\n >epoch=1908, lrate=0.005, error=0.098\n >epoch=1909, lrate=0.005, error=0.098\n >epoch=1910, lrate=0.005, error=0.097\n >epoch=1911, lrate=0.005, error=0.097\n >epoch=1912, lrate=0.005, error=0.097\n >epoch=1913, lrate=0.005, error=0.097\n >epoch=1914, lrate=0.005, error=0.097\n >epoch=1915, lrate=0.005, error=0.096\n >epoch=1916, lrate=0.005, error=0.096\n >epoch=1917, lrate=0.005, error=0.096\n >epoch=1918, lrate=0.005, error=0.096\n >epoch=1919, lrate=0.005, error=0.096\n >epoch=1920, lrate=0.005, error=0.095\n >epoch=1921, lrate=0.005, error=0.095\n >epoch=1922, lrate=0.005, error=0.095\n >epoch=1923, lrate=0.005, error=0.095\n >epoch=1924, lrate=0.005, error=0.095\n >epoch=1925, lrate=0.005, error=0.094\n >epoch=1926, lrate=0.005, error=0.094\n >epoch=1927, lrate=0.005, error=0.094\n >epoch=1928, lrate=0.005, error=0.094\n >epoch=1929, lrate=0.005, error=0.094\n >epoch=1930, lrate=0.005, error=0.093\n >epoch=1931, lrate=0.005, error=0.093\n >epoch=1932, lrate=0.005, error=0.093\n >epoch=1933, lrate=0.005, error=0.093\n >epoch=1934, lrate=0.005, error=0.093\n >epoch=1935, lrate=0.005, error=0.092\n >epoch=1936, lrate=0.005, error=0.092\n >epoch=1937, lrate=0.005, error=0.092\n >epoch=1938, lrate=0.005, error=0.092\n >epoch=1939, lrate=0.005, error=0.092\n >epoch=1940, lrate=0.005, error=0.092\n >epoch=1941, lrate=0.005, error=0.091\n >epoch=1942, lrate=0.005, error=0.091\n >epoch=1943, lrate=0.005, error=0.091\n >epoch=1944, lrate=0.005, error=0.091\n >epoch=1945, lrate=0.005, error=0.091\n >epoch=1946, lrate=0.005, error=0.090\n >epoch=1947, lrate=0.005, error=0.090\n >epoch=1948, lrate=0.005, error=0.090\n >epoch=1949, lrate=0.005, error=0.090\n >epoch=1950, lrate=0.005, error=0.090\n >epoch=1951, lrate=0.005, error=0.089\n >epoch=1952, lrate=0.005, error=0.089\n >epoch=1953, lrate=0.005, error=0.089\n >epoch=1954, lrate=0.005, error=0.089\n >epoch=1955, lrate=0.005, error=0.089\n >epoch=1956, lrate=0.005, error=0.089\n >epoch=1957, lrate=0.005, error=0.088\n >epoch=1958, lrate=0.005, error=0.088\n >epoch=1959, lrate=0.005, error=0.088\n >epoch=1960, lrate=0.005, error=0.088\n >epoch=1961, lrate=0.005, error=0.088\n >epoch=1962, lrate=0.005, error=0.087\n >epoch=1963, lrate=0.005, error=0.087\n >epoch=1964, lrate=0.005, error=0.087\n >epoch=1965, lrate=0.005, error=0.087\n >epoch=1966, lrate=0.005, error=0.087\n >epoch=1967, lrate=0.005, error=0.087\n >epoch=1968, lrate=0.005, error=0.086\n >epoch=1969, lrate=0.005, error=0.086\n >epoch=1970, lrate=0.005, error=0.086\n >epoch=1971, lrate=0.005, error=0.086\n >epoch=1972, lrate=0.005, error=0.086\n >epoch=1973, lrate=0.005, error=0.085\n >epoch=1974, lrate=0.005, error=0.085\n >epoch=1975, lrate=0.005, error=0.085\n >epoch=1976, lrate=0.005, error=0.085\n >epoch=1977, lrate=0.005, error=0.085\n >epoch=1978, lrate=0.005, error=0.085\n >epoch=1979, lrate=0.005, error=0.084\n >epoch=1980, lrate=0.005, error=0.084\n >epoch=1981, lrate=0.005, error=0.084\n >epoch=1982, lrate=0.005, error=0.084\n >epoch=1983, lrate=0.005, error=0.084\n >epoch=1984, lrate=0.005, error=0.084\n >epoch=1985, lrate=0.005, error=0.083\n >epoch=1986, lrate=0.005, error=0.083\n >epoch=1987, lrate=0.005, error=0.083\n >epoch=1988, lrate=0.005, error=0.083\n >epoch=1989, lrate=0.005, error=0.083\n >epoch=1990, lrate=0.005, error=0.083\n >epoch=1991, lrate=0.005, error=0.082\n >epoch=1992, lrate=0.005, error=0.082\n >epoch=1993, lrate=0.005, error=0.082\n >epoch=1994, lrate=0.005, error=0.082\n >epoch=1995, lrate=0.005, error=0.082\n >epoch=1996, lrate=0.005, error=0.082\n >epoch=1997, lrate=0.005, error=0.081\n >epoch=1998, lrate=0.005, error=0.081\n >epoch=1999, lrate=0.005, error=0.081\n >epoch=2000, lrate=0.005, error=0.081\n >epoch=2001, lrate=0.005, error=0.081\n >epoch=2002, lrate=0.005, error=0.081\n >epoch=2003, lrate=0.005, error=0.080\n >epoch=2004, lrate=0.005, error=0.080\n >epoch=2005, lrate=0.005, error=0.080\n >epoch=2006, lrate=0.005, error=0.080\n >epoch=2007, lrate=0.005, error=0.080\n >epoch=2008, lrate=0.005, error=0.080\n >epoch=2009, lrate=0.005, error=0.079\n >epoch=2010, lrate=0.005, error=0.079\n >epoch=2011, lrate=0.005, error=0.079\n >epoch=2012, lrate=0.005, error=0.079\n >epoch=2013, lrate=0.005, error=0.079\n >epoch=2014, lrate=0.005, error=0.079\n >epoch=2015, lrate=0.005, error=0.078\n >epoch=2016, lrate=0.005, error=0.078\n >epoch=2017, lrate=0.005, error=0.078\n >epoch=2018, lrate=0.005, error=0.078\n >epoch=2019, lrate=0.005, error=0.078\n >epoch=2020, lrate=0.005, error=0.078\n >epoch=2021, lrate=0.005, error=0.077\n >epoch=2022, lrate=0.005, error=0.077\n >epoch=2023, lrate=0.005, error=0.077\n >epoch=2024, lrate=0.005, error=0.077\n >epoch=2025, lrate=0.005, error=0.077\n >epoch=2026, lrate=0.005, error=0.077\n >epoch=2027, lrate=0.005, error=0.076\n >epoch=2028, lrate=0.005, error=0.076\n >epoch=2029, lrate=0.005, error=0.076\n >epoch=2030, lrate=0.005, error=0.076\n >epoch=2031, lrate=0.005, error=0.076\n >epoch=2032, lrate=0.005, error=0.076\n >epoch=2033, lrate=0.005, error=0.076\n >epoch=2034, lrate=0.005, error=0.075\n >epoch=2035, lrate=0.005, error=0.075\n >epoch=2036, lrate=0.005, error=0.075\n >epoch=2037, lrate=0.005, error=0.075\n >epoch=2038, lrate=0.005, error=0.075\n >epoch=2039, lrate=0.005, error=0.075\n >epoch=2040, lrate=0.005, error=0.074\n >epoch=2041, lrate=0.005, error=0.074\n >epoch=2042, lrate=0.005, error=0.074\n >epoch=2043, lrate=0.005, error=0.074\n >epoch=2044, lrate=0.005, error=0.074\n >epoch=2045, lrate=0.005, error=0.074\n >epoch=2046, lrate=0.005, error=0.074\n >epoch=2047, lrate=0.005, error=0.073\n >epoch=2048, lrate=0.005, error=0.073\n >epoch=2049, lrate=0.005, error=0.073\n >epoch=2050, lrate=0.005, error=0.073\n >epoch=2051, lrate=0.005, error=0.073\n >epoch=2052, lrate=0.005, error=0.073\n >epoch=2053, lrate=0.005, error=0.072\n >epoch=2054, lrate=0.005, error=0.072\n >epoch=2055, lrate=0.005, error=0.072\n >epoch=2056, lrate=0.005, error=0.072\n >epoch=2057, lrate=0.005, error=0.072\n >epoch=2058, lrate=0.005, error=0.072\n >epoch=2059, lrate=0.005, error=0.072\n >epoch=2060, lrate=0.005, error=0.071\n >epoch=2061, lrate=0.005, error=0.071\n >epoch=2062, lrate=0.005, error=0.071\n >epoch=2063, lrate=0.005, error=0.071\n >epoch=2064, lrate=0.005, error=0.071\n >epoch=2065, lrate=0.005, error=0.071\n >epoch=2066, lrate=0.005, error=0.071\n >epoch=2067, lrate=0.005, error=0.070\n >epoch=2068, lrate=0.005, error=0.070\n >epoch=2069, lrate=0.005, error=0.070\n >epoch=2070, lrate=0.005, error=0.070\n >epoch=2071, lrate=0.005, error=0.070\n >epoch=2072, lrate=0.005, error=0.070\n >epoch=2073, lrate=0.005, error=0.070\n >epoch=2074, lrate=0.005, error=0.069\n >epoch=2075, lrate=0.005, error=0.069\n >epoch=2076, lrate=0.005, error=0.069\n >epoch=2077, lrate=0.005, error=0.069\n >epoch=2078, lrate=0.005, error=0.069\n >epoch=2079, lrate=0.005, error=0.069\n >epoch=2080, lrate=0.005, error=0.069\n >epoch=2081, lrate=0.005, error=0.068\n >epoch=2082, lrate=0.005, error=0.068\n >epoch=2083, lrate=0.005, error=0.068\n >epoch=2084, lrate=0.005, error=0.068\n >epoch=2085, lrate=0.005, error=0.068\n >epoch=2086, lrate=0.005, error=0.068\n >epoch=2087, lrate=0.005, error=0.068\n >epoch=2088, lrate=0.005, error=0.067\n >epoch=2089, lrate=0.005, error=0.067\n >epoch=2090, lrate=0.005, error=0.067\n >epoch=2091, lrate=0.005, error=0.067\n >epoch=2092, lrate=0.005, error=0.067\n >epoch=2093, lrate=0.005, error=0.067\n >epoch=2094, lrate=0.005, error=0.067\n >epoch=2095, lrate=0.005, error=0.066\n >epoch=2096, lrate=0.005, error=0.066\n >epoch=2097, lrate=0.005, error=0.066\n >epoch=2098, lrate=0.005, error=0.066\n >epoch=2099, lrate=0.005, error=0.066\n >epoch=2100, lrate=0.005, error=0.066\n >epoch=2101, lrate=0.005, error=0.066\n >epoch=2102, lrate=0.005, error=0.065\n >epoch=2103, lrate=0.005, error=0.065\n >epoch=2104, lrate=0.005, error=0.065\n >epoch=2105, lrate=0.005, error=0.065\n >epoch=2106, lrate=0.005, error=0.065\n >epoch=2107, lrate=0.005, error=0.065\n >epoch=2108, lrate=0.005, error=0.065\n >epoch=2109, lrate=0.005, error=0.065\n >epoch=2110, lrate=0.005, error=0.064\n >epoch=2111, lrate=0.005, error=0.064\n >epoch=2112, lrate=0.005, error=0.064\n >epoch=2113, lrate=0.005, error=0.064\n >epoch=2114, lrate=0.005, error=0.064\n >epoch=2115, lrate=0.005, error=0.064\n >epoch=2116, lrate=0.005, error=0.064\n >epoch=2117, lrate=0.005, error=0.063\n >epoch=2118, lrate=0.005, error=0.063\n >epoch=2119, lrate=0.005, error=0.063\n >epoch=2120, lrate=0.005, error=0.063\n >epoch=2121, lrate=0.005, error=0.063\n >epoch=2122, lrate=0.005, error=0.063\n >epoch=2123, lrate=0.005, error=0.063\n >epoch=2124, lrate=0.005, error=0.063\n >epoch=2125, lrate=0.005, error=0.062\n >epoch=2126, lrate=0.005, error=0.062\n >epoch=2127, lrate=0.005, error=0.062\n >epoch=2128, lrate=0.005, error=0.062\n >epoch=2129, lrate=0.005, error=0.062\n >epoch=2130, lrate=0.005, error=0.062\n >epoch=2131, lrate=0.005, error=0.062\n >epoch=2132, lrate=0.005, error=0.062\n >epoch=2133, lrate=0.005, error=0.061\n >epoch=2134, lrate=0.005, error=0.061\n >epoch=2135, lrate=0.005, error=0.061\n >epoch=2136, lrate=0.005, error=0.061\n >epoch=2137, lrate=0.005, error=0.061\n >epoch=2138, lrate=0.005, error=0.061\n >epoch=2139, lrate=0.005, error=0.061\n >epoch=2140, lrate=0.005, error=0.061\n >epoch=2141, lrate=0.005, error=0.060\n >epoch=2142, lrate=0.005, error=0.060\n >epoch=2143, lrate=0.005, error=0.060\n >epoch=2144, lrate=0.005, error=0.060\n >epoch=2145, lrate=0.005, error=0.060\n >epoch=2146, lrate=0.005, error=0.060\n >epoch=2147, lrate=0.005, error=0.060\n >epoch=2148, lrate=0.005, error=0.060\n >epoch=2149, lrate=0.005, error=0.059\n >epoch=2150, lrate=0.005, error=0.059\n >epoch=2151, lrate=0.005, error=0.059\n >epoch=2152, lrate=0.005, error=0.059\n >epoch=2153, lrate=0.005, error=0.059\n >epoch=2154, lrate=0.005, error=0.059\n >epoch=2155, lrate=0.005, error=0.059\n >epoch=2156, lrate=0.005, error=0.059\n >epoch=2157, lrate=0.005, error=0.058\n >epoch=2158, lrate=0.005, error=0.058\n >epoch=2159, lrate=0.005, error=0.058\n >epoch=2160, lrate=0.005, error=0.058\n >epoch=2161, lrate=0.005, error=0.058\n >epoch=2162, lrate=0.005, error=0.058\n >epoch=2163, lrate=0.005, error=0.058\n >epoch=2164, lrate=0.005, error=0.058\n >epoch=2165, lrate=0.005, error=0.058\n >epoch=2166, lrate=0.005, error=0.057\n >epoch=2167, lrate=0.005, error=0.057\n >epoch=2168, lrate=0.005, error=0.057\n >epoch=2169, lrate=0.005, error=0.057\n >epoch=2170, lrate=0.005, error=0.057\n >epoch=2171, lrate=0.005, error=0.057\n >epoch=2172, lrate=0.005, error=0.057\n >epoch=2173, lrate=0.005, error=0.057\n >epoch=2174, lrate=0.005, error=0.056\n >epoch=2175, lrate=0.005, error=0.056\n >epoch=2176, lrate=0.005, error=0.056\n >epoch=2177, lrate=0.005, error=0.056\n >epoch=2178, lrate=0.005, error=0.056\n >epoch=2179, lrate=0.005, error=0.056\n >epoch=2180, lrate=0.005, error=0.056\n >epoch=2181, lrate=0.005, error=0.056\n >epoch=2182, lrate=0.005, error=0.056\n >epoch=2183, lrate=0.005, error=0.055\n >epoch=2184, lrate=0.005, error=0.055\n >epoch=2185, lrate=0.005, error=0.055\n >epoch=2186, lrate=0.005, error=0.055\n >epoch=2187, lrate=0.005, error=0.055\n >epoch=2188, lrate=0.005, error=0.055\n >epoch=2189, lrate=0.005, error=0.055\n >epoch=2190, lrate=0.005, error=0.055\n >epoch=2191, lrate=0.005, error=0.055\n >epoch=2192, lrate=0.005, error=0.054\n >epoch=2193, lrate=0.005, error=0.054\n >epoch=2194, lrate=0.005, error=0.054\n >epoch=2195, lrate=0.005, error=0.054\n >epoch=2196, lrate=0.005, error=0.054\n >epoch=2197, lrate=0.005, error=0.054\n >epoch=2198, lrate=0.005, error=0.054\n >epoch=2199, lrate=0.005, error=0.054\n >epoch=2200, lrate=0.005, error=0.053\n >epoch=2201, lrate=0.005, error=0.053\n >epoch=2202, lrate=0.005, error=0.053\n >epoch=2203, lrate=0.005, error=0.053\n >epoch=2204, lrate=0.005, error=0.053\n >epoch=2205, lrate=0.005, error=0.053\n >epoch=2206, lrate=0.005, error=0.053\n >epoch=2207, lrate=0.005, error=0.053\n >epoch=2208, lrate=0.005, error=0.053\n >epoch=2209, lrate=0.005, error=0.053\n >epoch=2210, lrate=0.005, error=0.052\n >epoch=2211, lrate=0.005, error=0.052\n >epoch=2212, lrate=0.005, error=0.052\n >epoch=2213, lrate=0.005, error=0.052\n >epoch=2214, lrate=0.005, error=0.052\n >epoch=2215, lrate=0.005, error=0.052\n >epoch=2216, lrate=0.005, error=0.052\n >epoch=2217, lrate=0.005, error=0.052\n >epoch=2218, lrate=0.005, error=0.052\n >epoch=2219, lrate=0.005, error=0.051\n >epoch=2220, lrate=0.005, error=0.051\n >epoch=2221, lrate=0.005, error=0.051\n >epoch=2222, lrate=0.005, error=0.051\n >epoch=2223, lrate=0.005, error=0.051\n >epoch=2224, lrate=0.005, error=0.051\n >epoch=2225, lrate=0.005, error=0.051\n >epoch=2226, lrate=0.005, error=0.051\n >epoch=2227, lrate=0.005, error=0.051\n >epoch=2228, lrate=0.005, error=0.050\n >epoch=2229, lrate=0.005, error=0.050\n >epoch=2230, lrate=0.005, error=0.050\n >epoch=2231, lrate=0.005, error=0.050\n >epoch=2232, lrate=0.005, error=0.050\n >epoch=2233, lrate=0.005, error=0.050\n >epoch=2234, lrate=0.005, error=0.050\n >epoch=2235, lrate=0.005, error=0.050\n >epoch=2236, lrate=0.005, error=0.050\n >epoch=2237, lrate=0.005, error=0.050\n >epoch=2238, lrate=0.005, error=0.049\n >epoch=2239, lrate=0.005, error=0.049\n >epoch=2240, lrate=0.005, error=0.049\n >epoch=2241, lrate=0.005, error=0.049\n >epoch=2242, lrate=0.005, error=0.049\n >epoch=2243, lrate=0.005, error=0.049\n >epoch=2244, lrate=0.005, error=0.049\n >epoch=2245, lrate=0.005, error=0.049\n >epoch=2246, lrate=0.005, error=0.049\n >epoch=2247, lrate=0.005, error=0.049\n >epoch=2248, lrate=0.005, error=0.048\n >epoch=2249, lrate=0.005, error=0.048\n >epoch=2250, lrate=0.005, error=0.048\n >epoch=2251, lrate=0.005, error=0.048\n >epoch=2252, lrate=0.005, error=0.048\n >epoch=2253, lrate=0.005, error=0.048\n >epoch=2254, lrate=0.005, error=0.048\n >epoch=2255, lrate=0.005, error=0.048\n >epoch=2256, lrate=0.005, error=0.048\n >epoch=2257, lrate=0.005, error=0.048\n >epoch=2258, lrate=0.005, error=0.047\n >epoch=2259, lrate=0.005, error=0.047\n >epoch=2260, lrate=0.005, error=0.047\n >epoch=2261, lrate=0.005, error=0.047\n >epoch=2262, lrate=0.005, error=0.047\n >epoch=2263, lrate=0.005, error=0.047\n >epoch=2264, lrate=0.005, error=0.047\n >epoch=2265, lrate=0.005, error=0.047\n >epoch=2266, lrate=0.005, error=0.047\n >epoch=2267, lrate=0.005, error=0.047\n >epoch=2268, lrate=0.005, error=0.046\n >epoch=2269, lrate=0.005, error=0.046\n >epoch=2270, lrate=0.005, error=0.046\n >epoch=2271, lrate=0.005, error=0.046\n >epoch=2272, lrate=0.005, error=0.046\n >epoch=2273, lrate=0.005, error=0.046\n >epoch=2274, lrate=0.005, error=0.046\n >epoch=2275, lrate=0.005, error=0.046\n >epoch=2276, lrate=0.005, error=0.046\n >epoch=2277, lrate=0.005, error=0.046\n >epoch=2278, lrate=0.005, error=0.046\n >epoch=2279, lrate=0.005, error=0.045\n >epoch=2280, lrate=0.005, error=0.045\n >epoch=2281, lrate=0.005, error=0.045\n >epoch=2282, lrate=0.005, error=0.045\n >epoch=2283, lrate=0.005, error=0.045\n >epoch=2284, lrate=0.005, error=0.045\n >epoch=2285, lrate=0.005, error=0.045\n >epoch=2286, lrate=0.005, error=0.045\n >epoch=2287, lrate=0.005, error=0.045\n >epoch=2288, lrate=0.005, error=0.045\n >epoch=2289, lrate=0.005, error=0.045\n >epoch=2290, lrate=0.005, error=0.044\n >epoch=2291, lrate=0.005, error=0.044\n >epoch=2292, lrate=0.005, error=0.044\n >epoch=2293, lrate=0.005, error=0.044\n >epoch=2294, lrate=0.005, error=0.044\n >epoch=2295, lrate=0.005, error=0.044\n >epoch=2296, lrate=0.005, error=0.044\n >epoch=2297, lrate=0.005, error=0.044\n >epoch=2298, lrate=0.005, error=0.044\n >epoch=2299, lrate=0.005, error=0.044\n >epoch=2300, lrate=0.005, error=0.044\n >epoch=2301, lrate=0.005, error=0.043\n >epoch=2302, lrate=0.005, error=0.043\n >epoch=2303, lrate=0.005, error=0.043\n >epoch=2304, lrate=0.005, error=0.043\n >epoch=2305, lrate=0.005, error=0.043\n >epoch=2306, lrate=0.005, error=0.043\n >epoch=2307, lrate=0.005, error=0.043\n >epoch=2308, lrate=0.005, error=0.043\n >epoch=2309, lrate=0.005, error=0.043\n >epoch=2310, lrate=0.005, error=0.043\n >epoch=2311, lrate=0.005, error=0.043\n >epoch=2312, lrate=0.005, error=0.042\n >epoch=2313, lrate=0.005, error=0.042\n >epoch=2314, lrate=0.005, error=0.042\n >epoch=2315, lrate=0.005, error=0.042\n >epoch=2316, lrate=0.005, error=0.042\n >epoch=2317, lrate=0.005, error=0.042\n >epoch=2318, lrate=0.005, error=0.042\n >epoch=2319, lrate=0.005, error=0.042\n >epoch=2320, lrate=0.005, error=0.042\n >epoch=2321, lrate=0.005, error=0.042\n >epoch=2322, lrate=0.005, error=0.042\n >epoch=2323, lrate=0.005, error=0.042\n >epoch=2324, lrate=0.005, error=0.041\n >epoch=2325, lrate=0.005, error=0.041\n >epoch=2326, lrate=0.005, error=0.041\n >epoch=2327, lrate=0.005, error=0.041\n >epoch=2328, lrate=0.005, error=0.041\n >epoch=2329, lrate=0.005, error=0.041\n >epoch=2330, lrate=0.005, error=0.041\n >epoch=2331, lrate=0.005, error=0.041\n >epoch=2332, lrate=0.005, error=0.041\n >epoch=2333, lrate=0.005, error=0.041\n >epoch=2334, lrate=0.005, error=0.041\n >epoch=2335, lrate=0.005, error=0.040\n >epoch=2336, lrate=0.005, error=0.040\n >epoch=2337, lrate=0.005, error=0.040\n >epoch=2338, lrate=0.005, error=0.040\n >epoch=2339, lrate=0.005, error=0.040\n >epoch=2340, lrate=0.005, error=0.040\n >epoch=2341, lrate=0.005, error=0.040\n >epoch=2342, lrate=0.005, error=0.040\n >epoch=2343, lrate=0.005, error=0.040\n >epoch=2344, lrate=0.005, error=0.040\n >epoch=2345, lrate=0.005, error=0.040\n >epoch=2346, lrate=0.005, error=0.040\n >epoch=2347, lrate=0.005, error=0.039\n >epoch=2348, lrate=0.005, error=0.039\n >epoch=2349, lrate=0.005, error=0.039\n >epoch=2350, lrate=0.005, error=0.039\n >epoch=2351, lrate=0.005, error=0.039\n >epoch=2352, lrate=0.005, error=0.039\n >epoch=2353, lrate=0.005, error=0.039\n >epoch=2354, lrate=0.005, error=0.039\n >epoch=2355, lrate=0.005, error=0.039\n >epoch=2356, lrate=0.005, error=0.039\n >epoch=2357, lrate=0.005, error=0.039\n >epoch=2358, lrate=0.005, error=0.039\n >epoch=2359, lrate=0.005, error=0.039\n >epoch=2360, lrate=0.005, error=0.038\n >epoch=2361, lrate=0.005, error=0.038\n >epoch=2362, lrate=0.005, error=0.038\n >epoch=2363, lrate=0.005, error=0.038\n >epoch=2364, lrate=0.005, error=0.038\n >epoch=2365, lrate=0.005, error=0.038\n >epoch=2366, lrate=0.005, error=0.038\n >epoch=2367, lrate=0.005, error=0.038\n >epoch=2368, lrate=0.005, error=0.038\n >epoch=2369, lrate=0.005, error=0.038\n >epoch=2370, lrate=0.005, error=0.038\n >epoch=2371, lrate=0.005, error=0.038\n >epoch=2372, lrate=0.005, error=0.038\n >epoch=2373, lrate=0.005, error=0.037\n >epoch=2374, lrate=0.005, error=0.037\n >epoch=2375, lrate=0.005, error=0.037\n >epoch=2376, lrate=0.005, error=0.037\n >epoch=2377, lrate=0.005, error=0.037\n >epoch=2378, lrate=0.005, error=0.037\n >epoch=2379, lrate=0.005, error=0.037\n >epoch=2380, lrate=0.005, error=0.037\n >epoch=2381, lrate=0.005, error=0.037\n >epoch=2382, lrate=0.005, error=0.037\n >epoch=2383, lrate=0.005, error=0.037\n >epoch=2384, lrate=0.005, error=0.037\n >epoch=2385, lrate=0.005, error=0.037\n >epoch=2386, lrate=0.005, error=0.036\n >epoch=2387, lrate=0.005, error=0.036\n >epoch=2388, lrate=0.005, error=0.036\n >epoch=2389, lrate=0.005, error=0.036\n >epoch=2390, lrate=0.005, error=0.036\n >epoch=2391, lrate=0.005, error=0.036\n >epoch=2392, lrate=0.005, error=0.036\n >epoch=2393, lrate=0.005, error=0.036\n >epoch=2394, lrate=0.005, error=0.036\n >epoch=2395, lrate=0.005, error=0.036\n >epoch=2396, lrate=0.005, error=0.036\n >epoch=2397, lrate=0.005, error=0.036\n >epoch=2398, lrate=0.005, error=0.036\n >epoch=2399, lrate=0.005, error=0.035\n >epoch=2400, lrate=0.005, error=0.035\n >epoch=2401, lrate=0.005, error=0.035\n >epoch=2402, lrate=0.005, error=0.035\n >epoch=2403, lrate=0.005, error=0.035\n >epoch=2404, lrate=0.005, error=0.035\n >epoch=2405, lrate=0.005, error=0.035\n >epoch=2406, lrate=0.005, error=0.035\n >epoch=2407, lrate=0.005, error=0.035\n >epoch=2408, lrate=0.005, error=0.035\n >epoch=2409, lrate=0.005, error=0.035\n >epoch=2410, lrate=0.005, error=0.035\n >epoch=2411, lrate=0.005, error=0.035\n >epoch=2412, lrate=0.005, error=0.035\n >epoch=2413, lrate=0.005, error=0.034\n >epoch=2414, lrate=0.005, error=0.034\n >epoch=2415, lrate=0.005, error=0.034\n >epoch=2416, lrate=0.005, error=0.034\n >epoch=2417, lrate=0.005, error=0.034\n >epoch=2418, lrate=0.005, error=0.034\n >epoch=2419, lrate=0.005, error=0.034\n >epoch=2420, lrate=0.005, error=0.034\n >epoch=2421, lrate=0.005, error=0.034\n >epoch=2422, lrate=0.005, error=0.034\n >epoch=2423, lrate=0.005, error=0.034\n >epoch=2424, lrate=0.005, error=0.034\n >epoch=2425, lrate=0.005, error=0.034\n >epoch=2426, lrate=0.005, error=0.034\n >epoch=2427, lrate=0.005, error=0.033\n >epoch=2428, lrate=0.005, error=0.033\n >epoch=2429, lrate=0.005, error=0.033\n >epoch=2430, lrate=0.005, error=0.033\n >epoch=2431, lrate=0.005, error=0.033\n >epoch=2432, lrate=0.005, error=0.033\n >epoch=2433, lrate=0.005, error=0.033\n >epoch=2434, lrate=0.005, error=0.033\n >epoch=2435, lrate=0.005, error=0.033\n >epoch=2436, lrate=0.005, error=0.033\n >epoch=2437, lrate=0.005, error=0.033\n >epoch=2438, lrate=0.005, error=0.033\n >epoch=2439, lrate=0.005, error=0.033\n >epoch=2440, lrate=0.005, error=0.033\n >epoch=2441, lrate=0.005, error=0.033\n >epoch=2442, lrate=0.005, error=0.032\n >epoch=2443, lrate=0.005, error=0.032\n >epoch=2444, lrate=0.005, error=0.032\n >epoch=2445, lrate=0.005, error=0.032\n >epoch=2446, lrate=0.005, error=0.032\n >epoch=2447, lrate=0.005, error=0.032\n >epoch=2448, lrate=0.005, error=0.032\n >epoch=2449, lrate=0.005, error=0.032\n >epoch=2450, lrate=0.005, error=0.032\n >epoch=2451, lrate=0.005, error=0.032\n >epoch=2452, lrate=0.005, error=0.032\n >epoch=2453, lrate=0.005, error=0.032\n >epoch=2454, lrate=0.005, error=0.032\n >epoch=2455, lrate=0.005, error=0.032\n >epoch=2456, lrate=0.005, error=0.032\n >epoch=2457, lrate=0.005, error=0.031\n >epoch=2458, lrate=0.005, error=0.031\n >epoch=2459, lrate=0.005, error=0.031\n >epoch=2460, lrate=0.005, error=0.031\n >epoch=2461, lrate=0.005, error=0.031\n >epoch=2462, lrate=0.005, error=0.031\n >epoch=2463, lrate=0.005, error=0.031\n >epoch=2464, lrate=0.005, error=0.031\n >epoch=2465, lrate=0.005, error=0.031\n >epoch=2466, lrate=0.005, error=0.031\n >epoch=2467, lrate=0.005, error=0.031\n >epoch=2468, lrate=0.005, error=0.031\n >epoch=2469, lrate=0.005, error=0.031\n >epoch=2470, lrate=0.005, error=0.031\n >epoch=2471, lrate=0.005, error=0.031\n >epoch=2472, lrate=0.005, error=0.031\n >epoch=2473, lrate=0.005, error=0.030\n >epoch=2474, lrate=0.005, error=0.030\n >epoch=2475, lrate=0.005, error=0.030\n >epoch=2476, lrate=0.005, error=0.030\n >epoch=2477, lrate=0.005, error=0.030\n >epoch=2478, lrate=0.005, error=0.030\n >epoch=2479, lrate=0.005, error=0.030\n >epoch=2480, lrate=0.005, error=0.030\n >epoch=2481, lrate=0.005, error=0.030\n >epoch=2482, lrate=0.005, error=0.030\n >epoch=2483, lrate=0.005, error=0.030\n >epoch=2484, lrate=0.005, error=0.030\n >epoch=2485, lrate=0.005, error=0.030\n >epoch=2486, lrate=0.005, error=0.030\n >epoch=2487, lrate=0.005, error=0.030\n >epoch=2488, lrate=0.005, error=0.030\n >epoch=2489, lrate=0.005, error=0.029\n >epoch=2490, lrate=0.005, error=0.029\n >epoch=2491, lrate=0.005, error=0.029\n >epoch=2492, lrate=0.005, error=0.029\n >epoch=2493, lrate=0.005, error=0.029\n >epoch=2494, lrate=0.005, error=0.029\n >epoch=2495, lrate=0.005, error=0.029\n >epoch=2496, lrate=0.005, error=0.029\n >epoch=2497, lrate=0.005, error=0.029\n >epoch=2498, lrate=0.005, error=0.029\n >epoch=2499, lrate=0.005, error=0.029\n >epoch=2500, lrate=0.005, error=0.029\n >epoch=2501, lrate=0.005, error=0.029\n >epoch=2502, lrate=0.005, error=0.029\n >epoch=2503, lrate=0.005, error=0.029\n >epoch=2504, lrate=0.005, error=0.029\n >epoch=2505, lrate=0.005, error=0.029\n >epoch=2506, lrate=0.005, error=0.028\n >epoch=2507, lrate=0.005, error=0.028\n >epoch=2508, lrate=0.005, error=0.028\n >epoch=2509, lrate=0.005, error=0.028\n >epoch=2510, lrate=0.005, error=0.028\n >epoch=2511, lrate=0.005, error=0.028\n >epoch=2512, lrate=0.005, error=0.028\n >epoch=2513, lrate=0.005, error=0.028\n >epoch=2514, lrate=0.005, error=0.028\n >epoch=2515, lrate=0.005, error=0.028\n >epoch=2516, lrate=0.005, error=0.028\n >epoch=2517, lrate=0.005, error=0.028\n >epoch=2518, lrate=0.005, error=0.028\n >epoch=2519, lrate=0.005, error=0.028\n >epoch=2520, lrate=0.005, error=0.028\n >epoch=2521, lrate=0.005, error=0.028\n >epoch=2522, lrate=0.005, error=0.028\n >epoch=2523, lrate=0.005, error=0.027\n >epoch=2524, lrate=0.005, error=0.027\n >epoch=2525, lrate=0.005, error=0.027\n >epoch=2526, lrate=0.005, error=0.027\n >epoch=2527, lrate=0.005, error=0.027\n >epoch=2528, lrate=0.005, error=0.027\n >epoch=2529, lrate=0.005, error=0.027\n >epoch=2530, lrate=0.005, error=0.027\n >epoch=2531, lrate=0.005, error=0.027\n >epoch=2532, lrate=0.005, error=0.027\n >epoch=2533, lrate=0.005, error=0.027\n >epoch=2534, lrate=0.005, error=0.027\n >epoch=2535, lrate=0.005, error=0.027\n >epoch=2536, lrate=0.005, error=0.027\n >epoch=2537, lrate=0.005, error=0.027\n >epoch=2538, lrate=0.005, error=0.027\n >epoch=2539, lrate=0.005, error=0.027\n >epoch=2540, lrate=0.005, error=0.027\n >epoch=2541, lrate=0.005, error=0.026\n >epoch=2542, lrate=0.005, error=0.026\n >epoch=2543, lrate=0.005, error=0.026\n >epoch=2544, lrate=0.005, error=0.026\n >epoch=2545, lrate=0.005, error=0.026\n >epoch=2546, lrate=0.005, error=0.026\n >epoch=2547, lrate=0.005, error=0.026\n >epoch=2548, lrate=0.005, error=0.026\n >epoch=2549, lrate=0.005, error=0.026\n >epoch=2550, lrate=0.005, error=0.026\n >epoch=2551, lrate=0.005, error=0.026\n >epoch=2552, lrate=0.005, error=0.026\n >epoch=2553, lrate=0.005, error=0.026\n >epoch=2554, lrate=0.005, error=0.026\n >epoch=2555, lrate=0.005, error=0.026\n >epoch=2556, lrate=0.005, error=0.026\n >epoch=2557, lrate=0.005, error=0.026\n >epoch=2558, lrate=0.005, error=0.026\n >epoch=2559, lrate=0.005, error=0.025\n >epoch=2560, lrate=0.005, error=0.025\n >epoch=2561, lrate=0.005, error=0.025\n >epoch=2562, lrate=0.005, error=0.025\n >epoch=2563, lrate=0.005, error=0.025\n >epoch=2564, lrate=0.005, error=0.025\n >epoch=2565, lrate=0.005, error=0.025\n >epoch=2566, lrate=0.005, error=0.025\n >epoch=2567, lrate=0.005, error=0.025\n >epoch=2568, lrate=0.005, error=0.025\n >epoch=2569, lrate=0.005, error=0.025\n >epoch=2570, lrate=0.005, error=0.025\n >epoch=2571, lrate=0.005, error=0.025\n >epoch=2572, lrate=0.005, error=0.025\n >epoch=2573, lrate=0.005, error=0.025\n >epoch=2574, lrate=0.005, error=0.025\n >epoch=2575, lrate=0.005, error=0.025\n >epoch=2576, lrate=0.005, error=0.025\n >epoch=2577, lrate=0.005, error=0.025\n >epoch=2578, lrate=0.005, error=0.025\n >epoch=2579, lrate=0.005, error=0.024\n >epoch=2580, lrate=0.005, error=0.024\n >epoch=2581, lrate=0.005, error=0.024\n >epoch=2582, lrate=0.005, error=0.024\n >epoch=2583, lrate=0.005, error=0.024\n >epoch=2584, lrate=0.005, error=0.024\n >epoch=2585, lrate=0.005, error=0.024\n >epoch=2586, lrate=0.005, error=0.024\n >epoch=2587, lrate=0.005, error=0.024\n >epoch=2588, lrate=0.005, error=0.024\n >epoch=2589, lrate=0.005, error=0.024\n >epoch=2590, lrate=0.005, error=0.024\n >epoch=2591, lrate=0.005, error=0.024\n >epoch=2592, lrate=0.005, error=0.024\n >epoch=2593, lrate=0.005, error=0.024\n >epoch=2594, lrate=0.005, error=0.024\n >epoch=2595, lrate=0.005, error=0.024\n >epoch=2596, lrate=0.005, error=0.024\n >epoch=2597, lrate=0.005, error=0.024\n >epoch=2598, lrate=0.005, error=0.024\n >epoch=2599, lrate=0.005, error=0.023\n >epoch=2600, lrate=0.005, error=0.023\n >epoch=2601, lrate=0.005, error=0.023\n >epoch=2602, lrate=0.005, error=0.023\n >epoch=2603, lrate=0.005, error=0.023\n >epoch=2604, lrate=0.005, error=0.023\n >epoch=2605, lrate=0.005, error=0.023\n >epoch=2606, lrate=0.005, error=0.023\n >epoch=2607, lrate=0.005, error=0.023\n >epoch=2608, lrate=0.005, error=0.023\n >epoch=2609, lrate=0.005, error=0.023\n >epoch=2610, lrate=0.005, error=0.023\n >epoch=2611, lrate=0.005, error=0.023\n >epoch=2612, lrate=0.005, error=0.023\n >epoch=2613, lrate=0.005, error=0.023\n >epoch=2614, lrate=0.005, error=0.023\n >epoch=2615, lrate=0.005, error=0.023\n >epoch=2616, lrate=0.005, error=0.023\n >epoch=2617, lrate=0.005, error=0.023\n >epoch=2618, lrate=0.005, error=0.023\n >epoch=2619, lrate=0.005, error=0.023\n >epoch=2620, lrate=0.005, error=0.022\n >epoch=2621, lrate=0.005, error=0.022\n >epoch=2622, lrate=0.005, error=0.022\n >epoch=2623, lrate=0.005, error=0.022\n >epoch=2624, lrate=0.005, error=0.022\n >epoch=2625, lrate=0.005, error=0.022\n >epoch=2626, lrate=0.005, error=0.022\n >epoch=2627, lrate=0.005, error=0.022\n >epoch=2628, lrate=0.005, error=0.022\n >epoch=2629, lrate=0.005, error=0.022\n >epoch=2630, lrate=0.005, error=0.022\n >epoch=2631, lrate=0.005, error=0.022\n >epoch=2632, lrate=0.005, error=0.022\n >epoch=2633, lrate=0.005, error=0.022\n >epoch=2634, lrate=0.005, error=0.022\n >epoch=2635, lrate=0.005, error=0.022\n >epoch=2636, lrate=0.005, error=0.022\n >epoch=2637, lrate=0.005, error=0.022\n >epoch=2638, lrate=0.005, error=0.022\n >epoch=2639, lrate=0.005, error=0.022\n >epoch=2640, lrate=0.005, error=0.022\n >epoch=2641, lrate=0.005, error=0.022\n >epoch=2642, lrate=0.005, error=0.021\n >epoch=2643, lrate=0.005, error=0.021\n >epoch=2644, lrate=0.005, error=0.021\n >epoch=2645, lrate=0.005, error=0.021\n >epoch=2646, lrate=0.005, error=0.021\n >epoch=2647, lrate=0.005, error=0.021\n >epoch=2648, lrate=0.005, error=0.021\n >epoch=2649, lrate=0.005, error=0.021\n >epoch=2650, lrate=0.005, error=0.021\n >epoch=2651, lrate=0.005, error=0.021\n >epoch=2652, lrate=0.005, error=0.021\n >epoch=2653, lrate=0.005, error=0.021\n >epoch=2654, lrate=0.005, error=0.021\n >epoch=2655, lrate=0.005, error=0.021\n >epoch=2656, lrate=0.005, error=0.021\n >epoch=2657, lrate=0.005, error=0.021\n >epoch=2658, lrate=0.005, error=0.021\n >epoch=2659, lrate=0.005, error=0.021\n >epoch=2660, lrate=0.005, error=0.021\n >epoch=2661, lrate=0.005, error=0.021\n >epoch=2662, lrate=0.005, error=0.021\n >epoch=2663, lrate=0.005, error=0.021\n >epoch=2664, lrate=0.005, error=0.021\n >epoch=2665, lrate=0.005, error=0.020\n >epoch=2666, lrate=0.005, error=0.020\n >epoch=2667, lrate=0.005, error=0.020\n >epoch=2668, lrate=0.005, error=0.020\n >epoch=2669, lrate=0.005, error=0.020\n >epoch=2670, lrate=0.005, error=0.020\n >epoch=2671, lrate=0.005, error=0.020\n >epoch=2672, lrate=0.005, error=0.020\n >epoch=2673, lrate=0.005, error=0.020\n >epoch=2674, lrate=0.005, error=0.020\n >epoch=2675, lrate=0.005, error=0.020\n >epoch=2676, lrate=0.005, error=0.020\n >epoch=2677, lrate=0.005, error=0.020\n >epoch=2678, lrate=0.005, error=0.020\n >epoch=2679, lrate=0.005, error=0.020\n >epoch=2680, lrate=0.005, error=0.020\n >epoch=2681, lrate=0.005, error=0.020\n >epoch=2682, lrate=0.005, error=0.020\n >epoch=2683, lrate=0.005, error=0.020\n >epoch=2684, lrate=0.005, error=0.020\n >epoch=2685, lrate=0.005, error=0.020\n >epoch=2686, lrate=0.005, error=0.020\n >epoch=2687, lrate=0.005, error=0.020\n >epoch=2688, lrate=0.005, error=0.020\n >epoch=2689, lrate=0.005, error=0.019\n >epoch=2690, lrate=0.005, error=0.019\n >epoch=2691, lrate=0.005, error=0.019\n >epoch=2692, lrate=0.005, error=0.019\n >epoch=2693, lrate=0.005, error=0.019\n >epoch=2694, lrate=0.005, error=0.019\n >epoch=2695, lrate=0.005, error=0.019\n >epoch=2696, lrate=0.005, error=0.019\n >epoch=2697, lrate=0.005, error=0.019\n >epoch=2698, lrate=0.005, error=0.019\n >epoch=2699, lrate=0.005, error=0.019\n >epoch=2700, lrate=0.005, error=0.019\n >epoch=2701, lrate=0.005, error=0.019\n >epoch=2702, lrate=0.005, error=0.019\n >epoch=2703, lrate=0.005, error=0.019\n >epoch=2704, lrate=0.005, error=0.019\n >epoch=2705, lrate=0.005, error=0.019\n >epoch=2706, lrate=0.005, error=0.019\n >epoch=2707, lrate=0.005, error=0.019\n >epoch=2708, lrate=0.005, error=0.019\n >epoch=2709, lrate=0.005, error=0.019\n >epoch=2710, lrate=0.005, error=0.019\n >epoch=2711, lrate=0.005, error=0.019\n >epoch=2712, lrate=0.005, error=0.019\n >epoch=2713, lrate=0.005, error=0.019\n >epoch=2714, lrate=0.005, error=0.019\n >epoch=2715, lrate=0.005, error=0.018\n >epoch=2716, lrate=0.005, error=0.018\n >epoch=2717, lrate=0.005, error=0.018\n >epoch=2718, lrate=0.005, error=0.018\n >epoch=2719, lrate=0.005, error=0.018\n >epoch=2720, lrate=0.005, error=0.018\n >epoch=2721, lrate=0.005, error=0.018\n >epoch=2722, lrate=0.005, error=0.018\n >epoch=2723, lrate=0.005, error=0.018\n >epoch=2724, lrate=0.005, error=0.018\n >epoch=2725, lrate=0.005, error=0.018\n >epoch=2726, lrate=0.005, error=0.018\n >epoch=2727, lrate=0.005, error=0.018\n >epoch=2728, lrate=0.005, error=0.018\n >epoch=2729, lrate=0.005, error=0.018\n >epoch=2730, lrate=0.005, error=0.018\n >epoch=2731, lrate=0.005, error=0.018\n >epoch=2732, lrate=0.005, error=0.018\n >epoch=2733, lrate=0.005, error=0.018\n >epoch=2734, lrate=0.005, error=0.018\n >epoch=2735, lrate=0.005, error=0.018\n >epoch=2736, lrate=0.005, error=0.018\n >epoch=2737, lrate=0.005, error=0.018\n >epoch=2738, lrate=0.005, error=0.018\n >epoch=2739, lrate=0.005, error=0.018\n >epoch=2740, lrate=0.005, error=0.018\n >epoch=2741, lrate=0.005, error=0.018\n >epoch=2742, lrate=0.005, error=0.017\n >epoch=2743, lrate=0.005, error=0.017\n >epoch=2744, lrate=0.005, error=0.017\n >epoch=2745, lrate=0.005, error=0.017\n >epoch=2746, lrate=0.005, error=0.017\n >epoch=2747, lrate=0.005, error=0.017\n >epoch=2748, lrate=0.005, error=0.017\n >epoch=2749, lrate=0.005, error=0.017\n >epoch=2750, lrate=0.005, error=0.017\n >epoch=2751, lrate=0.005, error=0.017\n >epoch=2752, lrate=0.005, error=0.017\n >epoch=2753, lrate=0.005, error=0.017\n >epoch=2754, lrate=0.005, error=0.017\n >epoch=2755, lrate=0.005, error=0.017\n >epoch=2756, lrate=0.005, error=0.017\n >epoch=2757, lrate=0.005, error=0.017\n >epoch=2758, lrate=0.005, error=0.017\n >epoch=2759, lrate=0.005, error=0.017\n >epoch=2760, lrate=0.005, error=0.017\n >epoch=2761, lrate=0.005, error=0.017\n >epoch=2762, lrate=0.005, error=0.017\n >epoch=2763, lrate=0.005, error=0.017\n >epoch=2764, lrate=0.005, error=0.017\n >epoch=2765, lrate=0.005, error=0.017\n >epoch=2766, lrate=0.005, error=0.017\n >epoch=2767, lrate=0.005, error=0.017\n >epoch=2768, lrate=0.005, error=0.017\n >epoch=2769, lrate=0.005, error=0.017\n >epoch=2770, lrate=0.005, error=0.016\n >epoch=2771, lrate=0.005, error=0.016\n >epoch=2772, lrate=0.005, error=0.016\n >epoch=2773, lrate=0.005, error=0.016\n >epoch=2774, lrate=0.005, error=0.016\n >epoch=2775, lrate=0.005, error=0.016\n >epoch=2776, lrate=0.005, error=0.016\n >epoch=2777, lrate=0.005, error=0.016\n >epoch=2778, lrate=0.005, error=0.016\n >epoch=2779, lrate=0.005, error=0.016\n >epoch=2780, lrate=0.005, error=0.016\n >epoch=2781, lrate=0.005, error=0.016\n >epoch=2782, lrate=0.005, error=0.016\n >epoch=2783, lrate=0.005, error=0.016\n >epoch=2784, lrate=0.005, error=0.016\n >epoch=2785, lrate=0.005, error=0.016\n >epoch=2786, lrate=0.005, error=0.016\n >epoch=2787, lrate=0.005, error=0.016\n >epoch=2788, lrate=0.005, error=0.016\n >epoch=2789, lrate=0.005, error=0.016\n >epoch=2790, lrate=0.005, error=0.016\n >epoch=2791, lrate=0.005, error=0.016\n >epoch=2792, lrate=0.005, error=0.016\n >epoch=2793, lrate=0.005, error=0.016\n >epoch=2794, lrate=0.005, error=0.016\n >epoch=2795, lrate=0.005, error=0.016\n >epoch=2796, lrate=0.005, error=0.016\n >epoch=2797, lrate=0.005, error=0.016\n >epoch=2798, lrate=0.005, error=0.016\n >epoch=2799, lrate=0.005, error=0.016\n >epoch=2800, lrate=0.005, error=0.016\n >epoch=2801, lrate=0.005, error=0.015\n >epoch=2802, lrate=0.005, error=0.015\n >epoch=2803, lrate=0.005, error=0.015\n >epoch=2804, lrate=0.005, error=0.015\n >epoch=2805, lrate=0.005, error=0.015\n >epoch=2806, lrate=0.005, error=0.015\n >epoch=2807, lrate=0.005, error=0.015\n >epoch=2808, lrate=0.005, error=0.015\n >epoch=2809, lrate=0.005, error=0.015\n >epoch=2810, lrate=0.005, error=0.015\n >epoch=2811, lrate=0.005, error=0.015\n >epoch=2812, lrate=0.005, error=0.015\n >epoch=2813, lrate=0.005, error=0.015\n >epoch=2814, lrate=0.005, error=0.015\n >epoch=2815, lrate=0.005, error=0.015\n >epoch=2816, lrate=0.005, error=0.015\n >epoch=2817, lrate=0.005, error=0.015\n >epoch=2818, lrate=0.005, error=0.015\n >epoch=2819, lrate=0.005, error=0.015\n >epoch=2820, lrate=0.005, error=0.015\n >epoch=2821, lrate=0.005, error=0.015\n >epoch=2822, lrate=0.005, error=0.015\n >epoch=2823, lrate=0.005, error=0.015\n >epoch=2824, lrate=0.005, error=0.015\n >epoch=2825, lrate=0.005, error=0.015\n >epoch=2826, lrate=0.005, error=0.015\n >epoch=2827, lrate=0.005, error=0.015\n >epoch=2828, lrate=0.005, error=0.015\n >epoch=2829, lrate=0.005, error=0.015\n >epoch=2830, lrate=0.005, error=0.015\n >epoch=2831, lrate=0.005, error=0.015\n >epoch=2832, lrate=0.005, error=0.015\n >epoch=2833, lrate=0.005, error=0.014\n >epoch=2834, lrate=0.005, error=0.014\n >epoch=2835, lrate=0.005, error=0.014\n >epoch=2836, lrate=0.005, error=0.014\n >epoch=2837, lrate=0.005, error=0.014\n >epoch=2838, lrate=0.005, error=0.014\n >epoch=2839, lrate=0.005, error=0.014\n >epoch=2840, lrate=0.005, error=0.014\n >epoch=2841, lrate=0.005, error=0.014\n >epoch=2842, lrate=0.005, error=0.014\n >epoch=2843, lrate=0.005, error=0.014\n >epoch=2844, lrate=0.005, error=0.014\n >epoch=2845, lrate=0.005, error=0.014\n >epoch=2846, lrate=0.005, error=0.014\n >epoch=2847, lrate=0.005, error=0.014\n >epoch=2848, lrate=0.005, error=0.014\n >epoch=2849, lrate=0.005, error=0.014\n >epoch=2850, lrate=0.005, error=0.014\n >epoch=2851, lrate=0.005, error=0.014\n >epoch=2852, lrate=0.005, error=0.014\n >epoch=2853, lrate=0.005, error=0.014\n >epoch=2854, lrate=0.005, error=0.014\n >epoch=2855, lrate=0.005, error=0.014\n >epoch=2856, lrate=0.005, error=0.014\n >epoch=2857, lrate=0.005, error=0.014\n >epoch=2858, lrate=0.005, error=0.014\n >epoch=2859, lrate=0.005, error=0.014\n >epoch=2860, lrate=0.005, error=0.014\n >epoch=2861, lrate=0.005, error=0.014\n >epoch=2862, lrate=0.005, error=0.014\n >epoch=2863, lrate=0.005, error=0.014\n >epoch=2864, lrate=0.005, error=0.014\n >epoch=2865, lrate=0.005, error=0.014\n >epoch=2866, lrate=0.005, error=0.014\n >epoch=2867, lrate=0.005, error=0.013\n >epoch=2868, lrate=0.005, error=0.013\n >epoch=2869, lrate=0.005, error=0.013\n >epoch=2870, lrate=0.005, error=0.013\n >epoch=2871, lrate=0.005, error=0.013\n >epoch=2872, lrate=0.005, error=0.013\n >epoch=2873, lrate=0.005, error=0.013\n >epoch=2874, lrate=0.005, error=0.013\n >epoch=2875, lrate=0.005, error=0.013\n >epoch=2876, lrate=0.005, error=0.013\n >epoch=2877, lrate=0.005, error=0.013\n >epoch=2878, lrate=0.005, error=0.013\n >epoch=2879, lrate=0.005, error=0.013\n >epoch=2880, lrate=0.005, error=0.013\n >epoch=2881, lrate=0.005, error=0.013\n >epoch=2882, lrate=0.005, error=0.013\n >epoch=2883, lrate=0.005, error=0.013\n >epoch=2884, lrate=0.005, error=0.013\n >epoch=2885, lrate=0.005, error=0.013\n >epoch=2886, lrate=0.005, error=0.013\n >epoch=2887, lrate=0.005, error=0.013\n >epoch=2888, lrate=0.005, error=0.013\n >epoch=2889, lrate=0.005, error=0.013\n >epoch=2890, lrate=0.005, error=0.013\n >epoch=2891, lrate=0.005, error=0.013\n >epoch=2892, lrate=0.005, error=0.013\n >epoch=2893, lrate=0.005, error=0.013\n >epoch=2894, lrate=0.005, error=0.013\n >epoch=2895, lrate=0.005, error=0.013\n >epoch=2896, lrate=0.005, error=0.013\n >epoch=2897, lrate=0.005, error=0.013\n >epoch=2898, lrate=0.005, error=0.013\n >epoch=2899, lrate=0.005, error=0.013\n >epoch=2900, lrate=0.005, error=0.013\n >epoch=2901, lrate=0.005, error=0.013\n >epoch=2902, lrate=0.005, error=0.013\n >epoch=2903, lrate=0.005, error=0.013\n >epoch=2904, lrate=0.005, error=0.013\n >epoch=2905, lrate=0.005, error=0.012\n >epoch=2906, lrate=0.005, error=0.012\n >epoch=2907, lrate=0.005, error=0.012\n >epoch=2908, lrate=0.005, error=0.012\n >epoch=2909, lrate=0.005, error=0.012\n >epoch=2910, lrate=0.005, error=0.012\n >epoch=2911, lrate=0.005, error=0.012\n >epoch=2912, lrate=0.005, error=0.012\n >epoch=2913, lrate=0.005, error=0.012\n >epoch=2914, lrate=0.005, error=0.012\n >epoch=2915, lrate=0.005, error=0.012\n >epoch=2916, lrate=0.005, error=0.012\n >epoch=2917, lrate=0.005, error=0.012\n >epoch=2918, lrate=0.005, error=0.012\n >epoch=2919, lrate=0.005, error=0.012\n >epoch=2920, lrate=0.005, error=0.012\n >epoch=2921, lrate=0.005, error=0.012\n >epoch=2922, lrate=0.005, error=0.012\n >epoch=2923, lrate=0.005, error=0.012\n >epoch=2924, lrate=0.005, error=0.012\n >epoch=2925, lrate=0.005, error=0.012\n >epoch=2926, lrate=0.005, error=0.012\n >epoch=2927, lrate=0.005, error=0.012\n >epoch=2928, lrate=0.005, error=0.012\n >epoch=2929, lrate=0.005, error=0.012\n >epoch=2930, lrate=0.005, error=0.012\n >epoch=2931, lrate=0.005, error=0.012\n >epoch=2932, lrate=0.005, error=0.012\n >epoch=2933, lrate=0.005, error=0.012\n >epoch=2934, lrate=0.005, error=0.012\n >epoch=2935, lrate=0.005, error=0.012\n >epoch=2936, lrate=0.005, error=0.012\n >epoch=2937, lrate=0.005, error=0.012\n >epoch=2938, lrate=0.005, error=0.012\n >epoch=2939, lrate=0.005, error=0.012\n >epoch=2940, lrate=0.005, error=0.012\n >epoch=2941, lrate=0.005, error=0.012\n >epoch=2942, lrate=0.005, error=0.012\n >epoch=2943, lrate=0.005, error=0.012\n >epoch=2944, lrate=0.005, error=0.012\n >epoch=2945, lrate=0.005, error=0.011\n >epoch=2946, lrate=0.005, error=0.011\n >epoch=2947, lrate=0.005, error=0.011\n >epoch=2948, lrate=0.005, error=0.011\n >epoch=2949, lrate=0.005, error=0.011\n >epoch=2950, lrate=0.005, error=0.011\n >epoch=2951, lrate=0.005, error=0.011\n >epoch=2952, lrate=0.005, error=0.011\n >epoch=2953, lrate=0.005, error=0.011\n >epoch=2954, lrate=0.005, error=0.011\n >epoch=2955, lrate=0.005, error=0.011\n >epoch=2956, lrate=0.005, error=0.011\n >epoch=2957, lrate=0.005, error=0.011\n >epoch=2958, lrate=0.005, error=0.011\n >epoch=2959, lrate=0.005, error=0.011\n >epoch=2960, lrate=0.005, error=0.011\n >epoch=2961, lrate=0.005, error=0.011\n >epoch=2962, lrate=0.005, error=0.011\n >epoch=2963, lrate=0.005, error=0.011\n >epoch=2964, lrate=0.005, error=0.011\n >epoch=2965, lrate=0.005, error=0.011\n >epoch=2966, lrate=0.005, error=0.011\n >epoch=2967, lrate=0.005, error=0.011\n >epoch=2968, lrate=0.005, error=0.011\n >epoch=2969, lrate=0.005, error=0.011\n >epoch=2970, lrate=0.005, error=0.011\n >epoch=2971, lrate=0.005, error=0.011\n >epoch=2972, lrate=0.005, error=0.011\n >epoch=2973, lrate=0.005, error=0.011\n >epoch=2974, lrate=0.005, error=0.011\n >epoch=2975, lrate=0.005, error=0.011\n >epoch=2976, lrate=0.005, error=0.011\n >epoch=2977, lrate=0.005, error=0.011\n >epoch=2978, lrate=0.005, error=0.011\n >epoch=2979, lrate=0.005, error=0.011\n >epoch=2980, lrate=0.005, error=0.011\n >epoch=2981, lrate=0.005, error=0.011\n >epoch=2982, lrate=0.005, error=0.011\n >epoch=2983, lrate=0.005, error=0.011\n >epoch=2984, lrate=0.005, error=0.011\n >epoch=2985, lrate=0.005, error=0.011\n >epoch=2986, lrate=0.005, error=0.011\n >epoch=2987, lrate=0.005, error=0.011\n >epoch=2988, lrate=0.005, error=0.011\n >epoch=2989, lrate=0.005, error=0.010\n >epoch=2990, lrate=0.005, error=0.010\n >epoch=2991, lrate=0.005, error=0.010\n >epoch=2992, lrate=0.005, error=0.010\n >epoch=2993, lrate=0.005, error=0.010\n >epoch=2994, lrate=0.005, error=0.010\n >epoch=2995, lrate=0.005, error=0.010\n >epoch=2996, lrate=0.005, error=0.010\n >epoch=2997, lrate=0.005, error=0.010\n >epoch=2998, lrate=0.005, error=0.010\n >epoch=2999, lrate=0.005, error=0.010\n >epoch=3000, lrate=0.005, error=0.010\n >epoch=3001, lrate=0.005, error=0.010\n >epoch=3002, lrate=0.005, error=0.010\n >epoch=3003, lrate=0.005, error=0.010\n >epoch=3004, lrate=0.005, error=0.010\n >epoch=3005, lrate=0.005, error=0.010\n >epoch=3006, lrate=0.005, error=0.010\n >epoch=3007, lrate=0.005, error=0.010\n >epoch=3008, lrate=0.005, error=0.010\n >epoch=3009, lrate=0.005, error=0.010\n >epoch=3010, lrate=0.005, error=0.010\n >epoch=3011, lrate=0.005, error=0.010\n >epoch=3012, lrate=0.005, error=0.010\n >epoch=3013, lrate=0.005, error=0.010\n >epoch=3014, lrate=0.005, error=0.010\n >epoch=3015, lrate=0.005, error=0.010\n >epoch=3016, lrate=0.005, error=0.010\n >epoch=3017, lrate=0.005, error=0.010\n >epoch=3018, lrate=0.005, error=0.010\n >epoch=3019, lrate=0.005, error=0.010\n >epoch=3020, lrate=0.005, error=0.010\n >epoch=3021, lrate=0.005, error=0.010\n >epoch=3022, lrate=0.005, error=0.010\n >epoch=3023, lrate=0.005, error=0.010\n >epoch=3024, lrate=0.005, error=0.010\n >epoch=3025, lrate=0.005, error=0.010\n >epoch=3026, lrate=0.005, error=0.010\n >epoch=3027, lrate=0.005, error=0.010\n >epoch=3028, lrate=0.005, error=0.010\n >epoch=3029, lrate=0.005, error=0.010\n >epoch=3030, lrate=0.005, error=0.010\n >epoch=3031, lrate=0.005, error=0.010\n >epoch=3032, lrate=0.005, error=0.010\n >epoch=3033, lrate=0.005, error=0.010\n >epoch=3034, lrate=0.005, error=0.010\n >epoch=3035, lrate=0.005, error=0.010\n >epoch=3036, lrate=0.005, error=0.010\n >epoch=3037, lrate=0.005, error=0.010\n >epoch=3038, lrate=0.005, error=0.009\n >epoch=3039, lrate=0.005, error=0.009\n >epoch=3040, lrate=0.005, error=0.009\n >epoch=3041, lrate=0.005, error=0.009\n >epoch=3042, lrate=0.005, error=0.009\n >epoch=3043, lrate=0.005, error=0.009\n >epoch=3044, lrate=0.005, error=0.009\n >epoch=3045, lrate=0.005, error=0.009\n >epoch=3046, lrate=0.005, error=0.009\n >epoch=3047, lrate=0.005, error=0.009\n >epoch=3048, lrate=0.005, error=0.009\n >epoch=3049, lrate=0.005, error=0.009\n >epoch=3050, lrate=0.005, error=0.009\n >epoch=3051, lrate=0.005, error=0.009\n >epoch=3052, lrate=0.005, error=0.009\n >epoch=3053, lrate=0.005, error=0.009\n >epoch=3054, lrate=0.005, error=0.009\n >epoch=3055, lrate=0.005, error=0.009\n >epoch=3056, lrate=0.005, error=0.009\n >epoch=3057, lrate=0.005, error=0.009\n >epoch=3058, lrate=0.005, error=0.009\n >epoch=3059, lrate=0.005, error=0.009\n >epoch=3060, lrate=0.005, error=0.009\n >epoch=3061, lrate=0.005, error=0.009\n >epoch=3062, lrate=0.005, error=0.009\n >epoch=3063, lrate=0.005, error=0.009\n >epoch=3064, lrate=0.005, error=0.009\n >epoch=3065, lrate=0.005, error=0.009\n >epoch=3066, lrate=0.005, error=0.009\n >epoch=3067, lrate=0.005, error=0.009\n >epoch=3068, lrate=0.005, error=0.009\n >epoch=3069, lrate=0.005, error=0.009\n >epoch=3070, lrate=0.005, error=0.009\n >epoch=3071, lrate=0.005, error=0.009\n >epoch=3072, lrate=0.005, error=0.009\n >epoch=3073, lrate=0.005, error=0.009\n >epoch=3074, lrate=0.005, error=0.009\n >epoch=3075, lrate=0.005, error=0.009\n >epoch=3076, lrate=0.005, error=0.009\n >epoch=3077, lrate=0.005, error=0.009\n >epoch=3078, lrate=0.005, error=0.009\n >epoch=3079, lrate=0.005, error=0.009\n >epoch=3080, lrate=0.005, error=0.009\n >epoch=3081, lrate=0.005, error=0.009\n >epoch=3082, lrate=0.005, error=0.009\n >epoch=3083, lrate=0.005, error=0.009\n >epoch=3084, lrate=0.005, error=0.009\n >epoch=3085, lrate=0.005, error=0.009\n >epoch=3086, lrate=0.005, error=0.009\n >epoch=3087, lrate=0.005, error=0.009\n >epoch=3088, lrate=0.005, error=0.009\n >epoch=3089, lrate=0.005, error=0.009\n >epoch=3090, lrate=0.005, error=0.009\n >epoch=3091, lrate=0.005, error=0.009\n >epoch=3092, lrate=0.005, error=0.008\n >epoch=3093, lrate=0.005, error=0.008\n >epoch=3094, lrate=0.005, error=0.008\n >epoch=3095, lrate=0.005, error=0.008\n >epoch=3096, lrate=0.005, error=0.008\n >epoch=3097, lrate=0.005, error=0.008\n >epoch=3098, lrate=0.005, error=0.008\n >epoch=3099, lrate=0.005, error=0.008\n >epoch=3100, lrate=0.005, error=0.008\n >epoch=3101, lrate=0.005, error=0.008\n >epoch=3102, lrate=0.005, error=0.008\n >epoch=3103, lrate=0.005, error=0.008\n >epoch=3104, lrate=0.005, error=0.008\n >epoch=3105, lrate=0.005, error=0.008\n >epoch=3106, lrate=0.005, error=0.008\n >epoch=3107, lrate=0.005, error=0.008\n >epoch=3108, lrate=0.005, error=0.008\n >epoch=3109, lrate=0.005, error=0.008\n >epoch=3110, lrate=0.005, error=0.008\n >epoch=3111, lrate=0.005, error=0.008\n >epoch=3112, lrate=0.005, error=0.008\n >epoch=3113, lrate=0.005, error=0.008\n >epoch=3114, lrate=0.005, error=0.008\n >epoch=3115, lrate=0.005, error=0.008\n >epoch=3116, lrate=0.005, error=0.008\n >epoch=3117, lrate=0.005, error=0.008\n >epoch=3118, lrate=0.005, error=0.008\n >epoch=3119, lrate=0.005, error=0.008\n >epoch=3120, lrate=0.005, error=0.008\n >epoch=3121, lrate=0.005, error=0.008\n >epoch=3122, lrate=0.005, error=0.008\n >epoch=3123, lrate=0.005, error=0.008\n >epoch=3124, lrate=0.005, error=0.008\n >epoch=3125, lrate=0.005, error=0.008\n >epoch=3126, lrate=0.005, error=0.008\n >epoch=3127, lrate=0.005, error=0.008\n >epoch=3128, lrate=0.005, error=0.008\n >epoch=3129, lrate=0.005, error=0.008\n >epoch=3130, lrate=0.005, error=0.008\n >epoch=3131, lrate=0.005, error=0.008\n >epoch=3132, lrate=0.005, error=0.008\n >epoch=3133, lrate=0.005, error=0.008\n >epoch=3134, lrate=0.005, error=0.008\n >epoch=3135, lrate=0.005, error=0.008\n >epoch=3136, lrate=0.005, error=0.008\n >epoch=3137, lrate=0.005, error=0.008\n >epoch=3138, lrate=0.005, error=0.008\n >epoch=3139, lrate=0.005, error=0.008\n >epoch=3140, lrate=0.005, error=0.008\n >epoch=3141, lrate=0.005, error=0.008\n >epoch=3142, lrate=0.005, error=0.008\n >epoch=3143, lrate=0.005, error=0.008\n >epoch=3144, lrate=0.005, error=0.008\n >epoch=3145, lrate=0.005, error=0.008\n >epoch=3146, lrate=0.005, error=0.008\n >epoch=3147, lrate=0.005, error=0.008\n >epoch=3148, lrate=0.005, error=0.008\n >epoch=3149, lrate=0.005, error=0.008\n >epoch=3150, lrate=0.005, error=0.008\n >epoch=3151, lrate=0.005, error=0.008\n >epoch=3152, lrate=0.005, error=0.007\n >epoch=3153, lrate=0.005, error=0.007\n >epoch=3154, lrate=0.005, error=0.007\n >epoch=3155, lrate=0.005, error=0.007\n >epoch=3156, lrate=0.005, error=0.007\n >epoch=3157, lrate=0.005, error=0.007\n >epoch=3158, lrate=0.005, error=0.007\n >epoch=3159, lrate=0.005, error=0.007\n >epoch=3160, lrate=0.005, error=0.007\n >epoch=3161, lrate=0.005, error=0.007\n >epoch=3162, lrate=0.005, error=0.007\n >epoch=3163, lrate=0.005, error=0.007\n >epoch=3164, lrate=0.005, error=0.007\n >epoch=3165, lrate=0.005, error=0.007\n >epoch=3166, lrate=0.005, error=0.007\n >epoch=3167, lrate=0.005, error=0.007\n >epoch=3168, lrate=0.005, error=0.007\n >epoch=3169, lrate=0.005, error=0.007\n >epoch=3170, lrate=0.005, error=0.007\n >epoch=3171, lrate=0.005, error=0.007\n >epoch=3172, lrate=0.005, error=0.007\n >epoch=3173, lrate=0.005, error=0.007\n >epoch=3174, lrate=0.005, error=0.007\n >epoch=3175, lrate=0.005, error=0.007\n >epoch=3176, lrate=0.005, error=0.007\n >epoch=3177, lrate=0.005, error=0.007\n >epoch=3178, lrate=0.005, error=0.007\n >epoch=3179, lrate=0.005, error=0.007\n >epoch=3180, lrate=0.005, error=0.007\n >epoch=3181, lrate=0.005, error=0.007\n >epoch=3182, lrate=0.005, error=0.007\n >epoch=3183, lrate=0.005, error=0.007\n >epoch=3184, lrate=0.005, error=0.007\n >epoch=3185, lrate=0.005, error=0.007\n >epoch=3186, lrate=0.005, error=0.007\n >epoch=3187, lrate=0.005, error=0.007\n >epoch=3188, lrate=0.005, error=0.007\n >epoch=3189, lrate=0.005, error=0.007\n >epoch=3190, lrate=0.005, error=0.007\n >epoch=3191, lrate=0.005, error=0.007\n >epoch=3192, lrate=0.005, error=0.007\n >epoch=3193, lrate=0.005, error=0.007\n >epoch=3194, lrate=0.005, error=0.007\n >epoch=3195, lrate=0.005, error=0.007\n >epoch=3196, lrate=0.005, error=0.007\n >epoch=3197, lrate=0.005, error=0.007\n >epoch=3198, lrate=0.005, error=0.007\n >epoch=3199, lrate=0.005, error=0.007\n >epoch=3200, lrate=0.005, error=0.007\n >epoch=3201, lrate=0.005, error=0.007\n >epoch=3202, lrate=0.005, error=0.007\n >epoch=3203, lrate=0.005, error=0.007\n >epoch=3204, lrate=0.005, error=0.007\n >epoch=3205, lrate=0.005, error=0.007\n >epoch=3206, lrate=0.005, error=0.007\n >epoch=3207, lrate=0.005, error=0.007\n >epoch=3208, lrate=0.005, error=0.007\n >epoch=3209, lrate=0.005, error=0.007\n >epoch=3210, lrate=0.005, error=0.007\n >epoch=3211, lrate=0.005, error=0.007\n >epoch=3212, lrate=0.005, error=0.007\n >epoch=3213, lrate=0.005, error=0.007\n >epoch=3214, lrate=0.005, error=0.007\n >epoch=3215, lrate=0.005, error=0.007\n >epoch=3216, lrate=0.005, error=0.007\n >epoch=3217, lrate=0.005, error=0.007\n >epoch=3218, lrate=0.005, error=0.007\n >epoch=3219, lrate=0.005, error=0.007\n >epoch=3220, lrate=0.005, error=0.007\n >epoch=3221, lrate=0.005, error=0.007\n >epoch=3222, lrate=0.005, error=0.006\n >epoch=3223, lrate=0.005, error=0.006\n >epoch=3224, lrate=0.005, error=0.006\n >epoch=3225, lrate=0.005, error=0.006\n >epoch=3226, lrate=0.005, error=0.006\n >epoch=3227, lrate=0.005, error=0.006\n >epoch=3228, lrate=0.005, error=0.006\n >epoch=3229, lrate=0.005, error=0.006\n >epoch=3230, lrate=0.005, error=0.006\n >epoch=3231, lrate=0.005, error=0.006\n >epoch=3232, lrate=0.005, error=0.006\n >epoch=3233, lrate=0.005, error=0.006\n >epoch=3234, lrate=0.005, error=0.006\n >epoch=3235, lrate=0.005, error=0.006\n >epoch=3236, lrate=0.005, error=0.006\n >epoch=3237, lrate=0.005, error=0.006\n >epoch=3238, lrate=0.005, error=0.006\n >epoch=3239, lrate=0.005, error=0.006\n >epoch=3240, lrate=0.005, error=0.006\n >epoch=3241, lrate=0.005, error=0.006\n >epoch=3242, lrate=0.005, error=0.006\n >epoch=3243, lrate=0.005, error=0.006\n >epoch=3244, lrate=0.005, error=0.006\n >epoch=3245, lrate=0.005, error=0.006\n >epoch=3246, lrate=0.005, error=0.006\n >epoch=3247, lrate=0.005, error=0.006\n >epoch=3248, lrate=0.005, error=0.006\n >epoch=3249, lrate=0.005, error=0.006\n >epoch=3250, lrate=0.005, error=0.006\n >epoch=3251, lrate=0.005, error=0.006\n >epoch=3252, lrate=0.005, error=0.006\n >epoch=3253, lrate=0.005, error=0.006\n >epoch=3254, lrate=0.005, error=0.006\n >epoch=3255, lrate=0.005, error=0.006\n >epoch=3256, lrate=0.005, error=0.006\n >epoch=3257, lrate=0.005, error=0.006\n >epoch=3258, lrate=0.005, error=0.006\n >epoch=3259, lrate=0.005, error=0.006\n >epoch=3260, lrate=0.005, error=0.006\n >epoch=3261, lrate=0.005, error=0.006\n >epoch=3262, lrate=0.005, error=0.006\n >epoch=3263, lrate=0.005, error=0.006\n >epoch=3264, lrate=0.005, error=0.006\n >epoch=3265, lrate=0.005, error=0.006\n >epoch=3266, lrate=0.005, error=0.006\n >epoch=3267, lrate=0.005, error=0.006\n >epoch=3268, lrate=0.005, error=0.006\n >epoch=3269, lrate=0.005, error=0.006\n >epoch=3270, lrate=0.005, error=0.006\n >epoch=3271, lrate=0.005, error=0.006\n >epoch=3272, lrate=0.005, error=0.006\n >epoch=3273, lrate=0.005, error=0.006\n >epoch=3274, lrate=0.005, error=0.006\n >epoch=3275, lrate=0.005, error=0.006\n >epoch=3276, lrate=0.005, error=0.006\n >epoch=3277, lrate=0.005, error=0.006\n >epoch=3278, lrate=0.005, error=0.006\n >epoch=3279, lrate=0.005, error=0.006\n >epoch=3280, lrate=0.005, error=0.006\n >epoch=3281, lrate=0.005, error=0.006\n >epoch=3282, lrate=0.005, error=0.006\n >epoch=3283, lrate=0.005, error=0.006\n >epoch=3284, lrate=0.005, error=0.006\n >epoch=3285, lrate=0.005, error=0.006\n >epoch=3286, lrate=0.005, error=0.006\n >epoch=3287, lrate=0.005, error=0.006\n >epoch=3288, lrate=0.005, error=0.006\n >epoch=3289, lrate=0.005, error=0.006\n >epoch=3290, lrate=0.005, error=0.006\n >epoch=3291, lrate=0.005, error=0.006\n >epoch=3292, lrate=0.005, error=0.006\n >epoch=3293, lrate=0.005, error=0.006\n >epoch=3294, lrate=0.005, error=0.006\n >epoch=3295, lrate=0.005, error=0.006\n >epoch=3296, lrate=0.005, error=0.006\n >epoch=3297, lrate=0.005, error=0.006\n >epoch=3298, lrate=0.005, error=0.006\n >epoch=3299, lrate=0.005, error=0.006\n >epoch=3300, lrate=0.005, error=0.006\n >epoch=3301, lrate=0.005, error=0.006\n >epoch=3302, lrate=0.005, error=0.005\n >epoch=3303, lrate=0.005, error=0.005\n >epoch=3304, lrate=0.005, error=0.005\n >epoch=3305, lrate=0.005, error=0.005\n >epoch=3306, lrate=0.005, error=0.005\n >epoch=3307, lrate=0.005, error=0.005\n >epoch=3308, lrate=0.005, error=0.005\n >epoch=3309, lrate=0.005, error=0.005\n >epoch=3310, lrate=0.005, error=0.005\n >epoch=3311, lrate=0.005, error=0.005\n >epoch=3312, lrate=0.005, error=0.005\n >epoch=3313, lrate=0.005, error=0.005\n >epoch=3314, lrate=0.005, error=0.005\n >epoch=3315, lrate=0.005, error=0.005\n >epoch=3316, lrate=0.005, error=0.005\n >epoch=3317, lrate=0.005, error=0.005\n >epoch=3318, lrate=0.005, error=0.005\n >epoch=3319, lrate=0.005, error=0.005\n >epoch=3320, lrate=0.005, error=0.005\n >epoch=3321, lrate=0.005, error=0.005\n >epoch=3322, lrate=0.005, error=0.005\n >epoch=3323, lrate=0.005, error=0.005\n >epoch=3324, lrate=0.005, error=0.005\n >epoch=3325, lrate=0.005, error=0.005\n >epoch=3326, lrate=0.005, error=0.005\n >epoch=3327, lrate=0.005, error=0.005\n >epoch=3328, lrate=0.005, error=0.005\n >epoch=3329, lrate=0.005, error=0.005\n >epoch=3330, lrate=0.005, error=0.005\n >epoch=3331, lrate=0.005, error=0.005\n >epoch=3332, lrate=0.005, error=0.005\n >epoch=3333, lrate=0.005, error=0.005\n >epoch=3334, lrate=0.005, error=0.005\n >epoch=3335, lrate=0.005, error=0.005\n >epoch=3336, lrate=0.005, error=0.005\n >epoch=3337, lrate=0.005, error=0.005\n >epoch=3338, lrate=0.005, error=0.005\n >epoch=3339, lrate=0.005, error=0.005\n >epoch=3340, lrate=0.005, error=0.005\n >epoch=3341, lrate=0.005, error=0.005\n >epoch=3342, lrate=0.005, error=0.005\n >epoch=3343, lrate=0.005, error=0.005\n >epoch=3344, lrate=0.005, error=0.005\n >epoch=3345, lrate=0.005, error=0.005\n >epoch=3346, lrate=0.005, error=0.005\n >epoch=3347, lrate=0.005, error=0.005\n >epoch=3348, lrate=0.005, error=0.005\n >epoch=3349, lrate=0.005, error=0.005\n >epoch=3350, lrate=0.005, error=0.005\n >epoch=3351, lrate=0.005, error=0.005\n >epoch=3352, lrate=0.005, error=0.005\n >epoch=3353, lrate=0.005, error=0.005\n >epoch=3354, lrate=0.005, error=0.005\n >epoch=3355, lrate=0.005, error=0.005\n >epoch=3356, lrate=0.005, error=0.005\n >epoch=3357, lrate=0.005, error=0.005\n >epoch=3358, lrate=0.005, error=0.005\n >epoch=3359, lrate=0.005, error=0.005\n >epoch=3360, lrate=0.005, error=0.005\n >epoch=3361, lrate=0.005, error=0.005\n >epoch=3362, lrate=0.005, error=0.005\n >epoch=3363, lrate=0.005, error=0.005\n >epoch=3364, lrate=0.005, error=0.005\n >epoch=3365, lrate=0.005, error=0.005\n >epoch=3366, lrate=0.005, error=0.005\n >epoch=3367, lrate=0.005, error=0.005\n >epoch=3368, lrate=0.005, error=0.005\n >epoch=3369, lrate=0.005, error=0.005\n >epoch=3370, lrate=0.005, error=0.005\n >epoch=3371, lrate=0.005, error=0.005\n >epoch=3372, lrate=0.005, error=0.005\n >epoch=3373, lrate=0.005, error=0.005\n >epoch=3374, lrate=0.005, error=0.005\n >epoch=3375, lrate=0.005, error=0.005\n >epoch=3376, lrate=0.005, error=0.005\n >epoch=3377, lrate=0.005, error=0.005\n >epoch=3378, lrate=0.005, error=0.005\n >epoch=3379, lrate=0.005, error=0.005\n >epoch=3380, lrate=0.005, error=0.005\n >epoch=3381, lrate=0.005, error=0.005\n >epoch=3382, lrate=0.005, error=0.005\n >epoch=3383, lrate=0.005, error=0.005\n >epoch=3384, lrate=0.005, error=0.005\n >epoch=3385, lrate=0.005, error=0.005\n >epoch=3386, lrate=0.005, error=0.005\n >epoch=3387, lrate=0.005, error=0.005\n >epoch=3388, lrate=0.005, error=0.005\n >epoch=3389, lrate=0.005, error=0.005\n >epoch=3390, lrate=0.005, error=0.005\n >epoch=3391, lrate=0.005, error=0.005\n >epoch=3392, lrate=0.005, error=0.005\n >epoch=3393, lrate=0.005, error=0.005\n >epoch=3394, lrate=0.005, error=0.005\n >epoch=3395, lrate=0.005, error=0.005\n >epoch=3396, lrate=0.005, error=0.005\n >epoch=3397, lrate=0.005, error=0.005\n >epoch=3398, lrate=0.005, error=0.005\n >epoch=3399, lrate=0.005, error=0.005\n >epoch=3400, lrate=0.005, error=0.004\n >epoch=3401, lrate=0.005, error=0.004\n >epoch=3402, lrate=0.005, error=0.004\n >epoch=3403, lrate=0.005, error=0.004\n >epoch=3404, lrate=0.005, error=0.004\n >epoch=3405, lrate=0.005, error=0.004\n >epoch=3406, lrate=0.005, error=0.004\n >epoch=3407, lrate=0.005, error=0.004\n >epoch=3408, lrate=0.005, error=0.004\n >epoch=3409, lrate=0.005, error=0.004\n >epoch=3410, lrate=0.005, error=0.004\n >epoch=3411, lrate=0.005, error=0.004\n >epoch=3412, lrate=0.005, error=0.004\n >epoch=3413, lrate=0.005, error=0.004\n >epoch=3414, lrate=0.005, error=0.004\n >epoch=3415, lrate=0.005, error=0.004\n >epoch=3416, lrate=0.005, error=0.004\n >epoch=3417, lrate=0.005, error=0.004\n >epoch=3418, lrate=0.005, error=0.004\n >epoch=3419, lrate=0.005, error=0.004\n >epoch=3420, lrate=0.005, error=0.004\n >epoch=3421, lrate=0.005, error=0.004\n >epoch=3422, lrate=0.005, error=0.004\n >epoch=3423, lrate=0.005, error=0.004\n >epoch=3424, lrate=0.005, error=0.004\n >epoch=3425, lrate=0.005, error=0.004\n >epoch=3426, lrate=0.005, error=0.004\n >epoch=3427, lrate=0.005, error=0.004\n >epoch=3428, lrate=0.005, error=0.004\n >epoch=3429, lrate=0.005, error=0.004\n >epoch=3430, lrate=0.005, error=0.004\n >epoch=3431, lrate=0.005, error=0.004\n >epoch=3432, lrate=0.005, error=0.004\n >epoch=3433, lrate=0.005, error=0.004\n >epoch=3434, lrate=0.005, error=0.004\n >epoch=3435, lrate=0.005, error=0.004\n >epoch=3436, lrate=0.005, error=0.004\n >epoch=3437, lrate=0.005, error=0.004\n >epoch=3438, lrate=0.005, error=0.004\n >epoch=3439, lrate=0.005, error=0.004\n >epoch=3440, lrate=0.005, error=0.004\n >epoch=3441, lrate=0.005, error=0.004\n >epoch=3442, lrate=0.005, error=0.004\n >epoch=3443, lrate=0.005, error=0.004\n >epoch=3444, lrate=0.005, error=0.004\n >epoch=3445, lrate=0.005, error=0.004\n >epoch=3446, lrate=0.005, error=0.004\n >epoch=3447, lrate=0.005, error=0.004\n >epoch=3448, lrate=0.005, error=0.004\n >epoch=3449, lrate=0.005, error=0.004\n >epoch=3450, lrate=0.005, error=0.004\n >epoch=3451, lrate=0.005, error=0.004\n >epoch=3452, lrate=0.005, error=0.004\n >epoch=3453, lrate=0.005, error=0.004\n >epoch=3454, lrate=0.005, error=0.004\n >epoch=3455, lrate=0.005, error=0.004\n >epoch=3456, lrate=0.005, error=0.004\n >epoch=3457, lrate=0.005, error=0.004\n >epoch=3458, lrate=0.005, error=0.004\n >epoch=3459, lrate=0.005, error=0.004\n >epoch=3460, lrate=0.005, error=0.004\n >epoch=3461, lrate=0.005, error=0.004\n >epoch=3462, lrate=0.005, error=0.004\n >epoch=3463, lrate=0.005, error=0.004\n >epoch=3464, lrate=0.005, error=0.004\n >epoch=3465, lrate=0.005, error=0.004\n >epoch=3466, lrate=0.005, error=0.004\n >epoch=3467, lrate=0.005, error=0.004\n >epoch=3468, lrate=0.005, error=0.004\n >epoch=3469, lrate=0.005, error=0.004\n >epoch=3470, lrate=0.005, error=0.004\n >epoch=3471, lrate=0.005, error=0.004\n >epoch=3472, lrate=0.005, error=0.004\n >epoch=3473, lrate=0.005, error=0.004\n >epoch=3474, lrate=0.005, error=0.004\n >epoch=3475, lrate=0.005, error=0.004\n >epoch=3476, lrate=0.005, error=0.004\n >epoch=3477, lrate=0.005, error=0.004\n >epoch=3478, lrate=0.005, error=0.004\n >epoch=3479, lrate=0.005, error=0.004\n >epoch=3480, lrate=0.005, error=0.004\n >epoch=3481, lrate=0.005, error=0.004\n >epoch=3482, lrate=0.005, error=0.004\n >epoch=3483, lrate=0.005, error=0.004\n >epoch=3484, lrate=0.005, error=0.004\n >epoch=3485, lrate=0.005, error=0.004\n >epoch=3486, lrate=0.005, error=0.004\n >epoch=3487, lrate=0.005, error=0.004\n >epoch=3488, lrate=0.005, error=0.004\n >epoch=3489, lrate=0.005, error=0.004\n >epoch=3490, lrate=0.005, error=0.004\n >epoch=3491, lrate=0.005, error=0.004\n >epoch=3492, lrate=0.005, error=0.004\n >epoch=3493, lrate=0.005, error=0.004\n >epoch=3494, lrate=0.005, error=0.004\n >epoch=3495, lrate=0.005, error=0.004\n >epoch=3496, lrate=0.005, error=0.004\n >epoch=3497, lrate=0.005, error=0.004\n >epoch=3498, lrate=0.005, error=0.004\n >epoch=3499, lrate=0.005, error=0.004\n >epoch=3500, lrate=0.005, error=0.004\n >epoch=3501, lrate=0.005, error=0.004\n >epoch=3502, lrate=0.005, error=0.004\n >epoch=3503, lrate=0.005, error=0.004\n >epoch=3504, lrate=0.005, error=0.004\n >epoch=3505, lrate=0.005, error=0.004\n >epoch=3506, lrate=0.005, error=0.004\n >epoch=3507, lrate=0.005, error=0.004\n >epoch=3508, lrate=0.005, error=0.004\n >epoch=3509, lrate=0.005, error=0.004\n >epoch=3510, lrate=0.005, error=0.004\n >epoch=3511, lrate=0.005, error=0.004\n >epoch=3512, lrate=0.005, error=0.004\n >epoch=3513, lrate=0.005, error=0.004\n >epoch=3514, lrate=0.005, error=0.004\n >epoch=3515, lrate=0.005, error=0.004\n >epoch=3516, lrate=0.005, error=0.004\n >epoch=3517, lrate=0.005, error=0.004\n >epoch=3518, lrate=0.005, error=0.004\n >epoch=3519, lrate=0.005, error=0.004\n >epoch=3520, lrate=0.005, error=0.004\n >epoch=3521, lrate=0.005, error=0.003\n >epoch=3522, lrate=0.005, error=0.003\n >epoch=3523, lrate=0.005, error=0.003\n >epoch=3524, lrate=0.005, error=0.003\n >epoch=3525, lrate=0.005, error=0.003\n >epoch=3526, lrate=0.005, error=0.003\n >epoch=3527, lrate=0.005, error=0.003\n >epoch=3528, lrate=0.005, error=0.003\n >epoch=3529, lrate=0.005, error=0.003\n >epoch=3530, lrate=0.005, error=0.003\n >epoch=3531, lrate=0.005, error=0.003\n >epoch=3532, lrate=0.005, error=0.003\n >epoch=3533, lrate=0.005, error=0.003\n >epoch=3534, lrate=0.005, error=0.003\n >epoch=3535, lrate=0.005, error=0.003\n >epoch=3536, lrate=0.005, error=0.003\n >epoch=3537, lrate=0.005, error=0.003\n >epoch=3538, lrate=0.005, error=0.003\n >epoch=3539, lrate=0.005, error=0.003\n >epoch=3540, lrate=0.005, error=0.003\n >epoch=3541, lrate=0.005, error=0.003\n >epoch=3542, lrate=0.005, error=0.003\n >epoch=3543, lrate=0.005, error=0.003\n >epoch=3544, lrate=0.005, error=0.003\n >epoch=3545, lrate=0.005, error=0.003\n >epoch=3546, lrate=0.005, error=0.003\n >epoch=3547, lrate=0.005, error=0.003\n >epoch=3548, lrate=0.005, error=0.003\n >epoch=3549, lrate=0.005, error=0.003\n >epoch=3550, lrate=0.005, error=0.003\n >epoch=3551, lrate=0.005, error=0.003\n >epoch=3552, lrate=0.005, error=0.003\n >epoch=3553, lrate=0.005, error=0.003\n >epoch=3554, lrate=0.005, error=0.003\n >epoch=3555, lrate=0.005, error=0.003\n >epoch=3556, lrate=0.005, error=0.003\n >epoch=3557, lrate=0.005, error=0.003\n >epoch=3558, lrate=0.005, error=0.003\n >epoch=3559, lrate=0.005, error=0.003\n >epoch=3560, lrate=0.005, error=0.003\n >epoch=3561, lrate=0.005, error=0.003\n >epoch=3562, lrate=0.005, error=0.003\n >epoch=3563, lrate=0.005, error=0.003\n >epoch=3564, lrate=0.005, error=0.003\n >epoch=3565, lrate=0.005, error=0.003\n >epoch=3566, lrate=0.005, error=0.003\n >epoch=3567, lrate=0.005, error=0.003\n >epoch=3568, lrate=0.005, error=0.003\n >epoch=3569, lrate=0.005, error=0.003\n >epoch=3570, lrate=0.005, error=0.003\n >epoch=3571, lrate=0.005, error=0.003\n >epoch=3572, lrate=0.005, error=0.003\n >epoch=3573, lrate=0.005, error=0.003\n >epoch=3574, lrate=0.005, error=0.003\n >epoch=3575, lrate=0.005, error=0.003\n >epoch=3576, lrate=0.005, error=0.003\n >epoch=3577, lrate=0.005, error=0.003\n >epoch=3578, lrate=0.005, error=0.003\n >epoch=3579, lrate=0.005, error=0.003\n >epoch=3580, lrate=0.005, error=0.003\n >epoch=3581, lrate=0.005, error=0.003\n >epoch=3582, lrate=0.005, error=0.003\n >epoch=3583, lrate=0.005, error=0.003\n >epoch=3584, lrate=0.005, error=0.003\n >epoch=3585, lrate=0.005, error=0.003\n >epoch=3586, lrate=0.005, error=0.003\n >epoch=3587, lrate=0.005, error=0.003\n >epoch=3588, lrate=0.005, error=0.003\n >epoch=3589, lrate=0.005, error=0.003\n >epoch=3590, lrate=0.005, error=0.003\n >epoch=3591, lrate=0.005, error=0.003\n >epoch=3592, lrate=0.005, error=0.003\n >epoch=3593, lrate=0.005, error=0.003\n >epoch=3594, lrate=0.005, error=0.003\n >epoch=3595, lrate=0.005, error=0.003\n >epoch=3596, lrate=0.005, error=0.003\n >epoch=3597, lrate=0.005, error=0.003\n >epoch=3598, lrate=0.005, error=0.003\n >epoch=3599, lrate=0.005, error=0.003\n >epoch=3600, lrate=0.005, error=0.003\n >epoch=3601, lrate=0.005, error=0.003\n >epoch=3602, lrate=0.005, error=0.003\n >epoch=3603, lrate=0.005, error=0.003\n >epoch=3604, lrate=0.005, error=0.003\n >epoch=3605, lrate=0.005, error=0.003\n >epoch=3606, lrate=0.005, error=0.003\n >epoch=3607, lrate=0.005, error=0.003\n >epoch=3608, lrate=0.005, error=0.003\n >epoch=3609, lrate=0.005, error=0.003\n >epoch=3610, lrate=0.005, error=0.003\n >epoch=3611, lrate=0.005, error=0.003\n >epoch=3612, lrate=0.005, error=0.003\n >epoch=3613, lrate=0.005, error=0.003\n >epoch=3614, lrate=0.005, error=0.003\n >epoch=3615, lrate=0.005, error=0.003\n >epoch=3616, lrate=0.005, error=0.003\n >epoch=3617, lrate=0.005, error=0.003\n >epoch=3618, lrate=0.005, error=0.003\n >epoch=3619, lrate=0.005, error=0.003\n >epoch=3620, lrate=0.005, error=0.003\n >epoch=3621, lrate=0.005, error=0.003\n >epoch=3622, lrate=0.005, error=0.003\n >epoch=3623, lrate=0.005, error=0.003\n >epoch=3624, lrate=0.005, error=0.003\n >epoch=3625, lrate=0.005, error=0.003\n >epoch=3626, lrate=0.005, error=0.003\n >epoch=3627, lrate=0.005, error=0.003\n >epoch=3628, lrate=0.005, error=0.003\n >epoch=3629, lrate=0.005, error=0.003\n >epoch=3630, lrate=0.005, error=0.003\n >epoch=3631, lrate=0.005, error=0.003\n >epoch=3632, lrate=0.005, error=0.003\n >epoch=3633, lrate=0.005, error=0.003\n >epoch=3634, lrate=0.005, error=0.003\n >epoch=3635, lrate=0.005, error=0.003\n >epoch=3636, lrate=0.005, error=0.003\n >epoch=3637, lrate=0.005, error=0.003\n >epoch=3638, lrate=0.005, error=0.003\n >epoch=3639, lrate=0.005, error=0.003\n >epoch=3640, lrate=0.005, error=0.003\n >epoch=3641, lrate=0.005, error=0.003\n >epoch=3642, lrate=0.005, error=0.003\n >epoch=3643, lrate=0.005, error=0.003\n >epoch=3644, lrate=0.005, error=0.003\n >epoch=3645, lrate=0.005, error=0.003\n >epoch=3646, lrate=0.005, error=0.003\n >epoch=3647, lrate=0.005, error=0.003\n >epoch=3648, lrate=0.005, error=0.003\n >epoch=3649, lrate=0.005, error=0.003\n >epoch=3650, lrate=0.005, error=0.003\n >epoch=3651, lrate=0.005, error=0.003\n >epoch=3652, lrate=0.005, error=0.003\n >epoch=3653, lrate=0.005, error=0.003\n >epoch=3654, lrate=0.005, error=0.003\n >epoch=3655, lrate=0.005, error=0.003\n >epoch=3656, lrate=0.005, error=0.003\n >epoch=3657, lrate=0.005, error=0.003\n >epoch=3658, lrate=0.005, error=0.003\n >epoch=3659, lrate=0.005, error=0.003\n >epoch=3660, lrate=0.005, error=0.003\n >epoch=3661, lrate=0.005, error=0.003\n >epoch=3662, lrate=0.005, error=0.003\n >epoch=3663, lrate=0.005, error=0.003\n >epoch=3664, lrate=0.005, error=0.003\n >epoch=3665, lrate=0.005, error=0.003\n >epoch=3666, lrate=0.005, error=0.003\n >epoch=3667, lrate=0.005, error=0.003\n >epoch=3668, lrate=0.005, error=0.003\n >epoch=3669, lrate=0.005, error=0.003\n >epoch=3670, lrate=0.005, error=0.003\n >epoch=3671, lrate=0.005, error=0.003\n >epoch=3672, lrate=0.005, error=0.003\n >epoch=3673, lrate=0.005, error=0.003\n >epoch=3674, lrate=0.005, error=0.003\n >epoch=3675, lrate=0.005, error=0.003\n >epoch=3676, lrate=0.005, error=0.003\n >epoch=3677, lrate=0.005, error=0.003\n >epoch=3678, lrate=0.005, error=0.003\n >epoch=3679, lrate=0.005, error=0.003\n >epoch=3680, lrate=0.005, error=0.003\n >epoch=3681, lrate=0.005, error=0.003\n >epoch=3682, lrate=0.005, error=0.003\n >epoch=3683, lrate=0.005, error=0.003\n >epoch=3684, lrate=0.005, error=0.002\n >epoch=3685, lrate=0.005, error=0.002\n >epoch=3686, lrate=0.005, error=0.002\n >epoch=3687, lrate=0.005, error=0.002\n >epoch=3688, lrate=0.005, error=0.002\n >epoch=3689, lrate=0.005, error=0.002\n >epoch=3690, lrate=0.005, error=0.002\n >epoch=3691, lrate=0.005, error=0.002\n >epoch=3692, lrate=0.005, error=0.002\n >epoch=3693, lrate=0.005, error=0.002\n >epoch=3694, lrate=0.005, error=0.002\n >epoch=3695, lrate=0.005, error=0.002\n >epoch=3696, lrate=0.005, error=0.002\n >epoch=3697, lrate=0.005, error=0.002\n >epoch=3698, lrate=0.005, error=0.002\n >epoch=3699, lrate=0.005, error=0.002\n >epoch=3700, lrate=0.005, error=0.002\n >epoch=3701, lrate=0.005, error=0.002\n >epoch=3702, lrate=0.005, error=0.002\n >epoch=3703, lrate=0.005, error=0.002\n >epoch=3704, lrate=0.005, error=0.002\n >epoch=3705, lrate=0.005, error=0.002\n >epoch=3706, lrate=0.005, error=0.002\n >epoch=3707, lrate=0.005, error=0.002\n >epoch=3708, lrate=0.005, error=0.002\n >epoch=3709, lrate=0.005, error=0.002\n >epoch=3710, lrate=0.005, error=0.002\n >epoch=3711, lrate=0.005, error=0.002\n >epoch=3712, lrate=0.005, error=0.002\n >epoch=3713, lrate=0.005, error=0.002\n >epoch=3714, lrate=0.005, error=0.002\n >epoch=3715, lrate=0.005, error=0.002\n >epoch=3716, lrate=0.005, error=0.002\n >epoch=3717, lrate=0.005, error=0.002\n >epoch=3718, lrate=0.005, error=0.002\n >epoch=3719, lrate=0.005, error=0.002\n >epoch=3720, lrate=0.005, error=0.002\n >epoch=3721, lrate=0.005, error=0.002\n >epoch=3722, lrate=0.005, error=0.002\n >epoch=3723, lrate=0.005, error=0.002\n >epoch=3724, lrate=0.005, error=0.002\n >epoch=3725, lrate=0.005, error=0.002\n >epoch=3726, lrate=0.005, error=0.002\n >epoch=3727, lrate=0.005, error=0.002\n >epoch=3728, lrate=0.005, error=0.002\n >epoch=3729, lrate=0.005, error=0.002\n >epoch=3730, lrate=0.005, error=0.002\n >epoch=3731, lrate=0.005, error=0.002\n >epoch=3732, lrate=0.005, error=0.002\n >epoch=3733, lrate=0.005, error=0.002\n >epoch=3734, lrate=0.005, error=0.002\n >epoch=3735, lrate=0.005, error=0.002\n >epoch=3736, lrate=0.005, error=0.002\n >epoch=3737, lrate=0.005, error=0.002\n >epoch=3738, lrate=0.005, error=0.002\n >epoch=3739, lrate=0.005, error=0.002\n >epoch=3740, lrate=0.005, error=0.002\n >epoch=3741, lrate=0.005, error=0.002\n >epoch=3742, lrate=0.005, error=0.002\n >epoch=3743, lrate=0.005, error=0.002\n >epoch=3744, lrate=0.005, error=0.002\n >epoch=3745, lrate=0.005, error=0.002\n >epoch=3746, lrate=0.005, error=0.002\n >epoch=3747, lrate=0.005, error=0.002\n >epoch=3748, lrate=0.005, error=0.002\n >epoch=3749, lrate=0.005, error=0.002\n >epoch=3750, lrate=0.005, error=0.002\n >epoch=3751, lrate=0.005, error=0.002\n >epoch=3752, lrate=0.005, error=0.002\n >epoch=3753, lrate=0.005, error=0.002\n >epoch=3754, lrate=0.005, error=0.002\n >epoch=3755, lrate=0.005, error=0.002\n >epoch=3756, lrate=0.005, error=0.002\n >epoch=3757, lrate=0.005, error=0.002\n >epoch=3758, lrate=0.005, error=0.002\n >epoch=3759, lrate=0.005, error=0.002\n >epoch=3760, lrate=0.005, error=0.002\n >epoch=3761, lrate=0.005, error=0.002\n >epoch=3762, lrate=0.005, error=0.002\n >epoch=3763, lrate=0.005, error=0.002\n >epoch=3764, lrate=0.005, error=0.002\n >epoch=3765, lrate=0.005, error=0.002\n >epoch=3766, lrate=0.005, error=0.002\n >epoch=3767, lrate=0.005, error=0.002\n >epoch=3768, lrate=0.005, error=0.002\n >epoch=3769, lrate=0.005, error=0.002\n >epoch=3770, lrate=0.005, error=0.002\n >epoch=3771, lrate=0.005, error=0.002\n >epoch=3772, lrate=0.005, error=0.002\n >epoch=3773, lrate=0.005, error=0.002\n >epoch=3774, lrate=0.005, error=0.002\n >epoch=3775, lrate=0.005, error=0.002\n >epoch=3776, lrate=0.005, error=0.002\n >epoch=3777, lrate=0.005, error=0.002\n >epoch=3778, lrate=0.005, error=0.002\n >epoch=3779, lrate=0.005, error=0.002\n >epoch=3780, lrate=0.005, error=0.002\n >epoch=3781, lrate=0.005, error=0.002\n >epoch=3782, lrate=0.005, error=0.002\n >epoch=3783, lrate=0.005, error=0.002\n >epoch=3784, lrate=0.005, error=0.002\n >epoch=3785, lrate=0.005, error=0.002\n >epoch=3786, lrate=0.005, error=0.002\n >epoch=3787, lrate=0.005, error=0.002\n >epoch=3788, lrate=0.005, error=0.002\n >epoch=3789, lrate=0.005, error=0.002\n >epoch=3790, lrate=0.005, error=0.002\n >epoch=3791, lrate=0.005, error=0.002\n >epoch=3792, lrate=0.005, error=0.002\n >epoch=3793, lrate=0.005, error=0.002\n >epoch=3794, lrate=0.005, error=0.002\n >epoch=3795, lrate=0.005, error=0.002\n >epoch=3796, lrate=0.005, error=0.002\n >epoch=3797, lrate=0.005, error=0.002\n >epoch=3798, lrate=0.005, error=0.002\n >epoch=3799, lrate=0.005, error=0.002\n >epoch=3800, lrate=0.005, error=0.002\n >epoch=3801, lrate=0.005, error=0.002\n >epoch=3802, lrate=0.005, error=0.002\n >epoch=3803, lrate=0.005, error=0.002\n >epoch=3804, lrate=0.005, error=0.002\n >epoch=3805, lrate=0.005, error=0.002\n >epoch=3806, lrate=0.005, error=0.002\n >epoch=3807, lrate=0.005, error=0.002\n >epoch=3808, lrate=0.005, error=0.002\n >epoch=3809, lrate=0.005, error=0.002\n >epoch=3810, lrate=0.005, error=0.002\n >epoch=3811, lrate=0.005, error=0.002\n >epoch=3812, lrate=0.005, error=0.002\n >epoch=3813, lrate=0.005, error=0.002\n >epoch=3814, lrate=0.005, error=0.002\n >epoch=3815, lrate=0.005, error=0.002\n >epoch=3816, lrate=0.005, error=0.002\n >epoch=3817, lrate=0.005, error=0.002\n >epoch=3818, lrate=0.005, error=0.002\n >epoch=3819, lrate=0.005, error=0.002\n >epoch=3820, lrate=0.005, error=0.002\n >epoch=3821, lrate=0.005, error=0.002\n >epoch=3822, lrate=0.005, error=0.002\n >epoch=3823, lrate=0.005, error=0.002\n >epoch=3824, lrate=0.005, error=0.002\n >epoch=3825, lrate=0.005, error=0.002\n >epoch=3826, lrate=0.005, error=0.002\n >epoch=3827, lrate=0.005, error=0.002\n >epoch=3828, lrate=0.005, error=0.002\n >epoch=3829, lrate=0.005, error=0.002\n >epoch=3830, lrate=0.005, error=0.002\n >epoch=3831, lrate=0.005, error=0.002\n >epoch=3832, lrate=0.005, error=0.002\n >epoch=3833, lrate=0.005, error=0.002\n >epoch=3834, lrate=0.005, error=0.002\n >epoch=3835, lrate=0.005, error=0.002\n >epoch=3836, lrate=0.005, error=0.002\n >epoch=3837, lrate=0.005, error=0.002\n >epoch=3838, lrate=0.005, error=0.002\n >epoch=3839, lrate=0.005, error=0.002\n >epoch=3840, lrate=0.005, error=0.002\n >epoch=3841, lrate=0.005, error=0.002\n >epoch=3842, lrate=0.005, error=0.002\n >epoch=3843, lrate=0.005, error=0.002\n >epoch=3844, lrate=0.005, error=0.002\n >epoch=3845, lrate=0.005, error=0.002\n >epoch=3846, lrate=0.005, error=0.002\n >epoch=3847, lrate=0.005, error=0.002\n >epoch=3848, lrate=0.005, error=0.002\n >epoch=3849, lrate=0.005, error=0.002\n >epoch=3850, lrate=0.005, error=0.002\n >epoch=3851, lrate=0.005, error=0.002\n >epoch=3852, lrate=0.005, error=0.002\n >epoch=3853, lrate=0.005, error=0.002\n >epoch=3854, lrate=0.005, error=0.002\n >epoch=3855, lrate=0.005, error=0.002\n >epoch=3856, lrate=0.005, error=0.002\n >epoch=3857, lrate=0.005, error=0.002\n >epoch=3858, lrate=0.005, error=0.002\n >epoch=3859, lrate=0.005, error=0.002\n >epoch=3860, lrate=0.005, error=0.002\n >epoch=3861, lrate=0.005, error=0.002\n >epoch=3862, lrate=0.005, error=0.002\n >epoch=3863, lrate=0.005, error=0.002\n >epoch=3864, lrate=0.005, error=0.002\n >epoch=3865, lrate=0.005, error=0.002\n >epoch=3866, lrate=0.005, error=0.002\n >epoch=3867, lrate=0.005, error=0.002\n >epoch=3868, lrate=0.005, error=0.002\n >epoch=3869, lrate=0.005, error=0.002\n >epoch=3870, lrate=0.005, error=0.002\n >epoch=3871, lrate=0.005, error=0.002\n >epoch=3872, lrate=0.005, error=0.002\n >epoch=3873, lrate=0.005, error=0.002\n >epoch=3874, lrate=0.005, error=0.002\n >epoch=3875, lrate=0.005, error=0.002\n >epoch=3876, lrate=0.005, error=0.002\n >epoch=3877, lrate=0.005, error=0.002\n >epoch=3878, lrate=0.005, error=0.002\n >epoch=3879, lrate=0.005, error=0.002\n >epoch=3880, lrate=0.005, error=0.002\n >epoch=3881, lrate=0.005, error=0.002\n >epoch=3882, lrate=0.005, error=0.002\n >epoch=3883, lrate=0.005, error=0.002\n >epoch=3884, lrate=0.005, error=0.002\n >epoch=3885, lrate=0.005, error=0.002\n >epoch=3886, lrate=0.005, error=0.002\n >epoch=3887, lrate=0.005, error=0.002\n >epoch=3888, lrate=0.005, error=0.002\n >epoch=3889, lrate=0.005, error=0.002\n >epoch=3890, lrate=0.005, error=0.002\n >epoch=3891, lrate=0.005, error=0.002\n >epoch=3892, lrate=0.005, error=0.002\n >epoch=3893, lrate=0.005, error=0.002\n >epoch=3894, lrate=0.005, error=0.002\n >epoch=3895, lrate=0.005, error=0.002\n >epoch=3896, lrate=0.005, error=0.002\n >epoch=3897, lrate=0.005, error=0.002\n >epoch=3898, lrate=0.005, error=0.002\n >epoch=3899, lrate=0.005, error=0.002\n >epoch=3900, lrate=0.005, error=0.002\n >epoch=3901, lrate=0.005, error=0.002\n >epoch=3902, lrate=0.005, error=0.002\n >epoch=3903, lrate=0.005, error=0.002\n >epoch=3904, lrate=0.005, error=0.002\n >epoch=3905, lrate=0.005, error=0.002\n >epoch=3906, lrate=0.005, error=0.002\n >epoch=3907, lrate=0.005, error=0.002\n >epoch=3908, lrate=0.005, error=0.002\n >epoch=3909, lrate=0.005, error=0.002\n >epoch=3910, lrate=0.005, error=0.002\n >epoch=3911, lrate=0.005, error=0.002\n >epoch=3912, lrate=0.005, error=0.002\n >epoch=3913, lrate=0.005, error=0.002\n >epoch=3914, lrate=0.005, error=0.002\n >epoch=3915, lrate=0.005, error=0.002\n >epoch=3916, lrate=0.005, error=0.002\n >epoch=3917, lrate=0.005, error=0.002\n >epoch=3918, lrate=0.005, error=0.002\n >epoch=3919, lrate=0.005, error=0.002\n >epoch=3920, lrate=0.005, error=0.002\n >epoch=3921, lrate=0.005, error=0.002\n >epoch=3922, lrate=0.005, error=0.002\n >epoch=3923, lrate=0.005, error=0.002\n >epoch=3924, lrate=0.005, error=0.002\n >epoch=3925, lrate=0.005, error=0.002\n >epoch=3926, lrate=0.005, error=0.002\n >epoch=3927, lrate=0.005, error=0.002\n >epoch=3928, lrate=0.005, error=0.002\n >epoch=3929, lrate=0.005, error=0.002\n >epoch=3930, lrate=0.005, error=0.002\n >epoch=3931, lrate=0.005, error=0.002\n >epoch=3932, lrate=0.005, error=0.001\n >epoch=3933, lrate=0.005, error=0.001\n >epoch=3934, lrate=0.005, error=0.001\n >epoch=3935, lrate=0.005, error=0.001\n >epoch=3936, lrate=0.005, error=0.001\n >epoch=3937, lrate=0.005, error=0.001\n >epoch=3938, lrate=0.005, error=0.001\n >epoch=3939, lrate=0.005, error=0.001\n >epoch=3940, lrate=0.005, error=0.001\n >epoch=3941, lrate=0.005, error=0.001\n >epoch=3942, lrate=0.005, error=0.001\n >epoch=3943, lrate=0.005, error=0.001\n >epoch=3944, lrate=0.005, error=0.001\n >epoch=3945, lrate=0.005, error=0.001\n >epoch=3946, lrate=0.005, error=0.001\n >epoch=3947, lrate=0.005, error=0.001\n >epoch=3948, lrate=0.005, error=0.001\n >epoch=3949, lrate=0.005, error=0.001\n >epoch=3950, lrate=0.005, error=0.001\n >epoch=3951, lrate=0.005, error=0.001\n >epoch=3952, lrate=0.005, error=0.001\n >epoch=3953, lrate=0.005, error=0.001\n >epoch=3954, lrate=0.005, error=0.001\n >epoch=3955, lrate=0.005, error=0.001\n >epoch=3956, lrate=0.005, error=0.001\n >epoch=3957, lrate=0.005, error=0.001\n >epoch=3958, lrate=0.005, error=0.001\n >epoch=3959, lrate=0.005, error=0.001\n >epoch=3960, lrate=0.005, error=0.001\n >epoch=3961, lrate=0.005, error=0.001\n >epoch=3962, lrate=0.005, error=0.001\n >epoch=3963, lrate=0.005, error=0.001\n >epoch=3964, lrate=0.005, error=0.001\n >epoch=3965, lrate=0.005, error=0.001\n >epoch=3966, lrate=0.005, error=0.001\n >epoch=3967, lrate=0.005, error=0.001\n >epoch=3968, lrate=0.005, error=0.001\n >epoch=3969, lrate=0.005, error=0.001\n >epoch=3970, lrate=0.005, error=0.001\n >epoch=3971, lrate=0.005, error=0.001\n >epoch=3972, lrate=0.005, error=0.001\n >epoch=3973, lrate=0.005, error=0.001\n >epoch=3974, lrate=0.005, error=0.001\n >epoch=3975, lrate=0.005, error=0.001\n >epoch=3976, lrate=0.005, error=0.001\n >epoch=3977, lrate=0.005, error=0.001\n >epoch=3978, lrate=0.005, error=0.001\n >epoch=3979, lrate=0.005, error=0.001\n >epoch=3980, lrate=0.005, error=0.001\n >epoch=3981, lrate=0.005, error=0.001\n >epoch=3982, lrate=0.005, error=0.001\n >epoch=3983, lrate=0.005, error=0.001\n >epoch=3984, lrate=0.005, error=0.001\n >epoch=3985, lrate=0.005, error=0.001\n >epoch=3986, lrate=0.005, error=0.001\n >epoch=3987, lrate=0.005, error=0.001\n >epoch=3988, lrate=0.005, error=0.001\n >epoch=3989, lrate=0.005, error=0.001\n >epoch=3990, lrate=0.005, error=0.001\n >epoch=3991, lrate=0.005, error=0.001\n >epoch=3992, lrate=0.005, error=0.001\n >epoch=3993, lrate=0.005, error=0.001\n >epoch=3994, lrate=0.005, error=0.001\n >epoch=3995, lrate=0.005, error=0.001\n >epoch=3996, lrate=0.005, error=0.001\n >epoch=3997, lrate=0.005, error=0.001\n >epoch=3998, lrate=0.005, error=0.001\n >epoch=3999, lrate=0.005, error=0.001\n >epoch=4000, lrate=0.005, error=0.001\n >epoch=4001, lrate=0.005, error=0.001\n >epoch=4002, lrate=0.005, error=0.001\n >epoch=4003, lrate=0.005, error=0.001\n >epoch=4004, lrate=0.005, error=0.001\n >epoch=4005, lrate=0.005, error=0.001\n >epoch=4006, lrate=0.005, error=0.001\n >epoch=4007, lrate=0.005, error=0.001\n >epoch=4008, lrate=0.005, error=0.001\n >epoch=4009, lrate=0.005, error=0.001\n >epoch=4010, lrate=0.005, error=0.001\n >epoch=4011, lrate=0.005, error=0.001\n >epoch=4012, lrate=0.005, error=0.001\n >epoch=4013, lrate=0.005, error=0.001\n >epoch=4014, lrate=0.005, error=0.001\n >epoch=4015, lrate=0.005, error=0.001\n >epoch=4016, lrate=0.005, error=0.001\n >epoch=4017, lrate=0.005, error=0.001\n >epoch=4018, lrate=0.005, error=0.001\n >epoch=4019, lrate=0.005, error=0.001\n >epoch=4020, lrate=0.005, error=0.001\n >epoch=4021, lrate=0.005, error=0.001\n >epoch=4022, lrate=0.005, error=0.001\n >epoch=4023, lrate=0.005, error=0.001\n >epoch=4024, lrate=0.005, error=0.001\n >epoch=4025, lrate=0.005, error=0.001\n >epoch=4026, lrate=0.005, error=0.001\n >epoch=4027, lrate=0.005, error=0.001\n >epoch=4028, lrate=0.005, error=0.001\n >epoch=4029, lrate=0.005, error=0.001\n >epoch=4030, lrate=0.005, error=0.001\n >epoch=4031, lrate=0.005, error=0.001\n >epoch=4032, lrate=0.005, error=0.001\n >epoch=4033, lrate=0.005, error=0.001\n >epoch=4034, lrate=0.005, error=0.001\n >epoch=4035, lrate=0.005, error=0.001\n >epoch=4036, lrate=0.005, error=0.001\n >epoch=4037, lrate=0.005, error=0.001\n >epoch=4038, lrate=0.005, error=0.001\n >epoch=4039, lrate=0.005, error=0.001\n >epoch=4040, lrate=0.005, error=0.001\n >epoch=4041, lrate=0.005, error=0.001\n >epoch=4042, lrate=0.005, error=0.001\n >epoch=4043, lrate=0.005, error=0.001\n >epoch=4044, lrate=0.005, error=0.001\n >epoch=4045, lrate=0.005, error=0.001\n >epoch=4046, lrate=0.005, error=0.001\n >epoch=4047, lrate=0.005, error=0.001\n >epoch=4048, lrate=0.005, error=0.001\n >epoch=4049, lrate=0.005, error=0.001\n >epoch=4050, lrate=0.005, error=0.001\n >epoch=4051, lrate=0.005, error=0.001\n >epoch=4052, lrate=0.005, error=0.001\n >epoch=4053, lrate=0.005, error=0.001\n >epoch=4054, lrate=0.005, error=0.001\n >epoch=4055, lrate=0.005, error=0.001\n >epoch=4056, lrate=0.005, error=0.001\n >epoch=4057, lrate=0.005, error=0.001\n >epoch=4058, lrate=0.005, error=0.001\n >epoch=4059, lrate=0.005, error=0.001\n >epoch=4060, lrate=0.005, error=0.001\n >epoch=4061, lrate=0.005, error=0.001\n >epoch=4062, lrate=0.005, error=0.001\n >epoch=4063, lrate=0.005, error=0.001\n >epoch=4064, lrate=0.005, error=0.001\n >epoch=4065, lrate=0.005, error=0.001\n >epoch=4066, lrate=0.005, error=0.001\n >epoch=4067, lrate=0.005, error=0.001\n >epoch=4068, lrate=0.005, error=0.001\n >epoch=4069, lrate=0.005, error=0.001\n >epoch=4070, lrate=0.005, error=0.001\n >epoch=4071, lrate=0.005, error=0.001\n >epoch=4072, lrate=0.005, error=0.001\n >epoch=4073, lrate=0.005, error=0.001\n >epoch=4074, lrate=0.005, error=0.001\n >epoch=4075, lrate=0.005, error=0.001\n >epoch=4076, lrate=0.005, error=0.001\n >epoch=4077, lrate=0.005, error=0.001\n >epoch=4078, lrate=0.005, error=0.001\n >epoch=4079, lrate=0.005, error=0.001\n >epoch=4080, lrate=0.005, error=0.001\n >epoch=4081, lrate=0.005, error=0.001\n >epoch=4082, lrate=0.005, error=0.001\n >epoch=4083, lrate=0.005, error=0.001\n >epoch=4084, lrate=0.005, error=0.001\n >epoch=4085, lrate=0.005, error=0.001\n >epoch=4086, lrate=0.005, error=0.001\n >epoch=4087, lrate=0.005, error=0.001\n >epoch=4088, lrate=0.005, error=0.001\n >epoch=4089, lrate=0.005, error=0.001\n >epoch=4090, lrate=0.005, error=0.001\n >epoch=4091, lrate=0.005, error=0.001\n >epoch=4092, lrate=0.005, error=0.001\n >epoch=4093, lrate=0.005, error=0.001\n >epoch=4094, lrate=0.005, error=0.001\n >epoch=4095, lrate=0.005, error=0.001\n >epoch=4096, lrate=0.005, error=0.001\n >epoch=4097, lrate=0.005, error=0.001\n >epoch=4098, lrate=0.005, error=0.001\n >epoch=4099, lrate=0.005, error=0.001\n >epoch=4100, lrate=0.005, error=0.001\n >epoch=4101, lrate=0.005, error=0.001\n >epoch=4102, lrate=0.005, error=0.001\n >epoch=4103, lrate=0.005, error=0.001\n >epoch=4104, lrate=0.005, error=0.001\n >epoch=4105, lrate=0.005, error=0.001\n >epoch=4106, lrate=0.005, error=0.001\n >epoch=4107, lrate=0.005, error=0.001\n >epoch=4108, lrate=0.005, error=0.001\n >epoch=4109, lrate=0.005, error=0.001\n >epoch=4110, lrate=0.005, error=0.001\n >epoch=4111, lrate=0.005, error=0.001\n >epoch=4112, lrate=0.005, error=0.001\n >epoch=4113, lrate=0.005, error=0.001\n >epoch=4114, lrate=0.005, error=0.001\n >epoch=4115, lrate=0.005, error=0.001\n >epoch=4116, lrate=0.005, error=0.001\n >epoch=4117, lrate=0.005, error=0.001\n >epoch=4118, lrate=0.005, error=0.001\n >epoch=4119, lrate=0.005, error=0.001\n >epoch=4120, lrate=0.005, error=0.001\n >epoch=4121, lrate=0.005, error=0.001\n >epoch=4122, lrate=0.005, error=0.001\n >epoch=4123, lrate=0.005, error=0.001\n >epoch=4124, lrate=0.005, error=0.001\n >epoch=4125, lrate=0.005, error=0.001\n >epoch=4126, lrate=0.005, error=0.001\n >epoch=4127, lrate=0.005, error=0.001\n >epoch=4128, lrate=0.005, error=0.001\n >epoch=4129, lrate=0.005, error=0.001\n >epoch=4130, lrate=0.005, error=0.001\n >epoch=4131, lrate=0.005, error=0.001\n >epoch=4132, lrate=0.005, error=0.001\n >epoch=4133, lrate=0.005, error=0.001\n >epoch=4134, lrate=0.005, error=0.001\n >epoch=4135, lrate=0.005, error=0.001\n >epoch=4136, lrate=0.005, error=0.001\n >epoch=4137, lrate=0.005, error=0.001\n >epoch=4138, lrate=0.005, error=0.001\n >epoch=4139, lrate=0.005, error=0.001\n >epoch=4140, lrate=0.005, error=0.001\n >epoch=4141, lrate=0.005, error=0.001\n >epoch=4142, lrate=0.005, error=0.001\n >epoch=4143, lrate=0.005, error=0.001\n >epoch=4144, lrate=0.005, error=0.001\n >epoch=4145, lrate=0.005, error=0.001\n >epoch=4146, lrate=0.005, error=0.001\n >epoch=4147, lrate=0.005, error=0.001\n >epoch=4148, lrate=0.005, error=0.001\n >epoch=4149, lrate=0.005, error=0.001\n >epoch=4150, lrate=0.005, error=0.001\n >epoch=4151, lrate=0.005, error=0.001\n >epoch=4152, lrate=0.005, error=0.001\n >epoch=4153, lrate=0.005, error=0.001\n >epoch=4154, lrate=0.005, error=0.001\n >epoch=4155, lrate=0.005, error=0.001\n >epoch=4156, lrate=0.005, error=0.001\n >epoch=4157, lrate=0.005, error=0.001\n >epoch=4158, lrate=0.005, error=0.001\n >epoch=4159, lrate=0.005, error=0.001\n >epoch=4160, lrate=0.005, error=0.001\n >epoch=4161, lrate=0.005, error=0.001\n >epoch=4162, lrate=0.005, error=0.001\n >epoch=4163, lrate=0.005, error=0.001\n >epoch=4164, lrate=0.005, error=0.001\n >epoch=4165, lrate=0.005, error=0.001\n >epoch=4166, lrate=0.005, error=0.001\n >epoch=4167, lrate=0.005, error=0.001\n >epoch=4168, lrate=0.005, error=0.001\n >epoch=4169, lrate=0.005, error=0.001\n >epoch=4170, lrate=0.005, error=0.001\n >epoch=4171, lrate=0.005, error=0.001\n >epoch=4172, lrate=0.005, error=0.001\n >epoch=4173, lrate=0.005, error=0.001\n >epoch=4174, lrate=0.005, error=0.001\n >epoch=4175, lrate=0.005, error=0.001\n >epoch=4176, lrate=0.005, error=0.001\n >epoch=4177, lrate=0.005, error=0.001\n >epoch=4178, lrate=0.005, error=0.001\n >epoch=4179, lrate=0.005, error=0.001\n >epoch=4180, lrate=0.005, error=0.001\n >epoch=4181, lrate=0.005, error=0.001\n >epoch=4182, lrate=0.005, error=0.001\n >epoch=4183, lrate=0.005, error=0.001\n >epoch=4184, lrate=0.005, error=0.001\n >epoch=4185, lrate=0.005, error=0.001\n >epoch=4186, lrate=0.005, error=0.001\n >epoch=4187, lrate=0.005, error=0.001\n >epoch=4188, lrate=0.005, error=0.001\n >epoch=4189, lrate=0.005, error=0.001\n >epoch=4190, lrate=0.005, error=0.001\n >epoch=4191, lrate=0.005, error=0.001\n >epoch=4192, lrate=0.005, error=0.001\n >epoch=4193, lrate=0.005, error=0.001\n >epoch=4194, lrate=0.005, error=0.001\n >epoch=4195, lrate=0.005, error=0.001\n >epoch=4196, lrate=0.005, error=0.001\n >epoch=4197, lrate=0.005, error=0.001\n >epoch=4198, lrate=0.005, error=0.001\n >epoch=4199, lrate=0.005, error=0.001\n >epoch=4200, lrate=0.005, error=0.001\n >epoch=4201, lrate=0.005, error=0.001\n >epoch=4202, lrate=0.005, error=0.001\n >epoch=4203, lrate=0.005, error=0.001\n >epoch=4204, lrate=0.005, error=0.001\n >epoch=4205, lrate=0.005, error=0.001\n >epoch=4206, lrate=0.005, error=0.001\n >epoch=4207, lrate=0.005, error=0.001\n >epoch=4208, lrate=0.005, error=0.001\n >epoch=4209, lrate=0.005, error=0.001\n >epoch=4210, lrate=0.005, error=0.001\n >epoch=4211, lrate=0.005, error=0.001\n >epoch=4212, lrate=0.005, error=0.001\n >epoch=4213, lrate=0.005, error=0.001\n >epoch=4214, lrate=0.005, error=0.001\n >epoch=4215, lrate=0.005, error=0.001\n >epoch=4216, lrate=0.005, error=0.001\n >epoch=4217, lrate=0.005, error=0.001\n >epoch=4218, lrate=0.005, error=0.001\n >epoch=4219, lrate=0.005, error=0.001\n >epoch=4220, lrate=0.005, error=0.001\n >epoch=4221, lrate=0.005, error=0.001\n >epoch=4222, lrate=0.005, error=0.001\n >epoch=4223, lrate=0.005, error=0.001\n >epoch=4224, lrate=0.005, error=0.001\n >epoch=4225, lrate=0.005, error=0.001\n >epoch=4226, lrate=0.005, error=0.001\n >epoch=4227, lrate=0.005, error=0.001\n >epoch=4228, lrate=0.005, error=0.001\n >epoch=4229, lrate=0.005, error=0.001\n >epoch=4230, lrate=0.005, error=0.001\n >epoch=4231, lrate=0.005, error=0.001\n >epoch=4232, lrate=0.005, error=0.001\n >epoch=4233, lrate=0.005, error=0.001\n >epoch=4234, lrate=0.005, error=0.001\n >epoch=4235, lrate=0.005, error=0.001\n >epoch=4236, lrate=0.005, error=0.001\n >epoch=4237, lrate=0.005, error=0.001\n >epoch=4238, lrate=0.005, error=0.001\n >epoch=4239, lrate=0.005, error=0.001\n >epoch=4240, lrate=0.005, error=0.001\n >epoch=4241, lrate=0.005, error=0.001\n >epoch=4242, lrate=0.005, error=0.001\n >epoch=4243, lrate=0.005, error=0.001\n >epoch=4244, lrate=0.005, error=0.001\n >epoch=4245, lrate=0.005, error=0.001\n >epoch=4246, lrate=0.005, error=0.001\n >epoch=4247, lrate=0.005, error=0.001\n >epoch=4248, lrate=0.005, error=0.001\n >epoch=4249, lrate=0.005, error=0.001\n >epoch=4250, lrate=0.005, error=0.001\n >epoch=4251, lrate=0.005, error=0.001\n >epoch=4252, lrate=0.005, error=0.001\n >epoch=4253, lrate=0.005, error=0.001\n >epoch=4254, lrate=0.005, error=0.001\n >epoch=4255, lrate=0.005, error=0.001\n >epoch=4256, lrate=0.005, error=0.001\n >epoch=4257, lrate=0.005, error=0.001\n >epoch=4258, lrate=0.005, error=0.001\n >epoch=4259, lrate=0.005, error=0.001\n >epoch=4260, lrate=0.005, error=0.001\n >epoch=4261, lrate=0.005, error=0.001\n >epoch=4262, lrate=0.005, error=0.001\n >epoch=4263, lrate=0.005, error=0.001\n >epoch=4264, lrate=0.005, error=0.001\n >epoch=4265, lrate=0.005, error=0.001\n >epoch=4266, lrate=0.005, error=0.001\n >epoch=4267, lrate=0.005, error=0.001\n >epoch=4268, lrate=0.005, error=0.001\n >epoch=4269, lrate=0.005, error=0.001\n >epoch=4270, lrate=0.005, error=0.001\n >epoch=4271, lrate=0.005, error=0.001\n >epoch=4272, lrate=0.005, error=0.001\n >epoch=4273, lrate=0.005, error=0.001\n >epoch=4274, lrate=0.005, error=0.001\n >epoch=4275, lrate=0.005, error=0.001\n >epoch=4276, lrate=0.005, error=0.001\n >epoch=4277, lrate=0.005, error=0.001\n >epoch=4278, lrate=0.005, error=0.001\n >epoch=4279, lrate=0.005, error=0.001\n >epoch=4280, lrate=0.005, error=0.001\n >epoch=4281, lrate=0.005, error=0.001\n >epoch=4282, lrate=0.005, error=0.001\n >epoch=4283, lrate=0.005, error=0.001\n >epoch=4284, lrate=0.005, error=0.001\n >epoch=4285, lrate=0.005, error=0.001\n >epoch=4286, lrate=0.005, error=0.001\n >epoch=4287, lrate=0.005, error=0.001\n >epoch=4288, lrate=0.005, error=0.001\n >epoch=4289, lrate=0.005, error=0.001\n >epoch=4290, lrate=0.005, error=0.001\n >epoch=4291, lrate=0.005, error=0.001\n >epoch=4292, lrate=0.005, error=0.001\n >epoch=4293, lrate=0.005, error=0.001\n >epoch=4294, lrate=0.005, error=0.001\n >epoch=4295, lrate=0.005, error=0.001\n >epoch=4296, lrate=0.005, error=0.001\n >epoch=4297, lrate=0.005, error=0.001\n >epoch=4298, lrate=0.005, error=0.001\n >epoch=4299, lrate=0.005, error=0.001\n >epoch=4300, lrate=0.005, error=0.001\n >epoch=4301, lrate=0.005, error=0.001\n >epoch=4302, lrate=0.005, error=0.001\n >epoch=4303, lrate=0.005, error=0.001\n >epoch=4304, lrate=0.005, error=0.001\n >epoch=4305, lrate=0.005, error=0.001\n >epoch=4306, lrate=0.005, error=0.001\n >epoch=4307, lrate=0.005, error=0.001\n >epoch=4308, lrate=0.005, error=0.001\n >epoch=4309, lrate=0.005, error=0.001\n >epoch=4310, lrate=0.005, error=0.001\n >epoch=4311, lrate=0.005, error=0.001\n >epoch=4312, lrate=0.005, error=0.001\n >epoch=4313, lrate=0.005, error=0.001\n >epoch=4314, lrate=0.005, error=0.001\n >epoch=4315, lrate=0.005, error=0.001\n >epoch=4316, lrate=0.005, error=0.001\n >epoch=4317, lrate=0.005, error=0.001\n >epoch=4318, lrate=0.005, error=0.001\n >epoch=4319, lrate=0.005, error=0.001\n >epoch=4320, lrate=0.005, error=0.001\n >epoch=4321, lrate=0.005, error=0.001\n >epoch=4322, lrate=0.005, error=0.001\n >epoch=4323, lrate=0.005, error=0.001\n >epoch=4324, lrate=0.005, error=0.001\n >epoch=4325, lrate=0.005, error=0.001\n >epoch=4326, lrate=0.005, error=0.001\n >epoch=4327, lrate=0.005, error=0.001\n >epoch=4328, lrate=0.005, error=0.001\n >epoch=4329, lrate=0.005, error=0.001\n >epoch=4330, lrate=0.005, error=0.001\n >epoch=4331, lrate=0.005, error=0.001\n >epoch=4332, lrate=0.005, error=0.001\n >epoch=4333, lrate=0.005, error=0.001\n >epoch=4334, lrate=0.005, error=0.001\n >epoch=4335, lrate=0.005, error=0.001\n >epoch=4336, lrate=0.005, error=0.001\n >epoch=4337, lrate=0.005, error=0.001\n >epoch=4338, lrate=0.005, error=0.001\n >epoch=4339, lrate=0.005, error=0.001\n >epoch=4340, lrate=0.005, error=0.001\n >epoch=4341, lrate=0.005, error=0.001\n >epoch=4342, lrate=0.005, error=0.001\n >epoch=4343, lrate=0.005, error=0.001\n >epoch=4344, lrate=0.005, error=0.001\n >epoch=4345, lrate=0.005, error=0.001\n >epoch=4346, lrate=0.005, error=0.001\n >epoch=4347, lrate=0.005, error=0.001\n >epoch=4348, lrate=0.005, error=0.001\n >epoch=4349, lrate=0.005, error=0.001\n >epoch=4350, lrate=0.005, error=0.001\n >epoch=4351, lrate=0.005, error=0.001\n >epoch=4352, lrate=0.005, error=0.001\n >epoch=4353, lrate=0.005, error=0.001\n >epoch=4354, lrate=0.005, error=0.001\n >epoch=4355, lrate=0.005, error=0.001\n >epoch=4356, lrate=0.005, error=0.001\n >epoch=4357, lrate=0.005, error=0.001\n >epoch=4358, lrate=0.005, error=0.001\n >epoch=4359, lrate=0.005, error=0.001\n >epoch=4360, lrate=0.005, error=0.001\n >epoch=4361, lrate=0.005, error=0.001\n >epoch=4362, lrate=0.005, error=0.001\n >epoch=4363, lrate=0.005, error=0.001\n >epoch=4364, lrate=0.005, error=0.001\n >epoch=4365, lrate=0.005, error=0.001\n >epoch=4366, lrate=0.005, error=0.001\n >epoch=4367, lrate=0.005, error=0.001\n >epoch=4368, lrate=0.005, error=0.001\n >epoch=4369, lrate=0.005, error=0.001\n >epoch=4370, lrate=0.005, error=0.001\n >epoch=4371, lrate=0.005, error=0.001\n >epoch=4372, lrate=0.005, error=0.001\n >epoch=4373, lrate=0.005, error=0.001\n >epoch=4374, lrate=0.005, error=0.001\n >epoch=4375, lrate=0.005, error=0.001\n >epoch=4376, lrate=0.005, error=0.001\n >epoch=4377, lrate=0.005, error=0.001\n >epoch=4378, lrate=0.005, error=0.001\n >epoch=4379, lrate=0.005, error=0.001\n >epoch=4380, lrate=0.005, error=0.001\n >epoch=4381, lrate=0.005, error=0.001\n >epoch=4382, lrate=0.005, error=0.001\n >epoch=4383, lrate=0.005, error=0.001\n >epoch=4384, lrate=0.005, error=0.001\n >epoch=4385, lrate=0.005, error=0.001\n >epoch=4386, lrate=0.005, error=0.001\n >epoch=4387, lrate=0.005, error=0.001\n >epoch=4388, lrate=0.005, error=0.001\n >epoch=4389, lrate=0.005, error=0.001\n >epoch=4390, lrate=0.005, error=0.001\n >epoch=4391, lrate=0.005, error=0.001\n >epoch=4392, lrate=0.005, error=0.001\n >epoch=4393, lrate=0.005, error=0.001\n >epoch=4394, lrate=0.005, error=0.001\n >epoch=4395, lrate=0.005, error=0.001\n >epoch=4396, lrate=0.005, error=0.001\n >epoch=4397, lrate=0.005, error=0.001\n >epoch=4398, lrate=0.005, error=0.001\n >epoch=4399, lrate=0.005, error=0.001\n >epoch=4400, lrate=0.005, error=0.001\n >epoch=4401, lrate=0.005, error=0.001\n >epoch=4402, lrate=0.005, error=0.001\n >epoch=4403, lrate=0.005, error=0.001\n >epoch=4404, lrate=0.005, error=0.001\n >epoch=4405, lrate=0.005, error=0.001\n >epoch=4406, lrate=0.005, error=0.001\n >epoch=4407, lrate=0.005, error=0.001\n >epoch=4408, lrate=0.005, error=0.001\n >epoch=4409, lrate=0.005, error=0.001\n >epoch=4410, lrate=0.005, error=0.001\n >epoch=4411, lrate=0.005, error=0.001\n >epoch=4412, lrate=0.005, error=0.001\n >epoch=4413, lrate=0.005, error=0.001\n >epoch=4414, lrate=0.005, error=0.001\n >epoch=4415, lrate=0.005, error=0.001\n >epoch=4416, lrate=0.005, error=0.001\n >epoch=4417, lrate=0.005, error=0.001\n >epoch=4418, lrate=0.005, error=0.001\n >epoch=4419, lrate=0.005, error=0.001\n >epoch=4420, lrate=0.005, error=0.001\n >epoch=4421, lrate=0.005, error=0.001\n >epoch=4422, lrate=0.005, error=0.001\n >epoch=4423, lrate=0.005, error=0.001\n >epoch=4424, lrate=0.005, error=0.001\n >epoch=4425, lrate=0.005, error=0.001\n >epoch=4426, lrate=0.005, error=0.001\n >epoch=4427, lrate=0.005, error=0.001\n >epoch=4428, lrate=0.005, error=0.001\n >epoch=4429, lrate=0.005, error=0.001\n >epoch=4430, lrate=0.005, error=0.001\n >epoch=4431, lrate=0.005, error=0.001\n >epoch=4432, lrate=0.005, error=0.001\n >epoch=4433, lrate=0.005, error=0.001\n >epoch=4434, lrate=0.005, error=0.001\n >epoch=4435, lrate=0.005, error=0.001\n >epoch=4436, lrate=0.005, error=0.001\n >epoch=4437, lrate=0.005, error=0.001\n >epoch=4438, lrate=0.005, error=0.001\n >epoch=4439, lrate=0.005, error=0.001\n >epoch=4440, lrate=0.005, error=0.001\n >epoch=4441, lrate=0.005, error=0.001\n >epoch=4442, lrate=0.005, error=0.001\n >epoch=4443, lrate=0.005, error=0.001\n >epoch=4444, lrate=0.005, error=0.001\n >epoch=4445, lrate=0.005, error=0.001\n >epoch=4446, lrate=0.005, error=0.001\n >epoch=4447, lrate=0.005, error=0.001\n >epoch=4448, lrate=0.005, error=0.001\n >epoch=4449, lrate=0.005, error=0.001\n >epoch=4450, lrate=0.005, error=0.001\n >epoch=4451, lrate=0.005, error=0.001\n >epoch=4452, lrate=0.005, error=0.001\n >epoch=4453, lrate=0.005, error=0.001\n >epoch=4454, lrate=0.005, error=0.001\n >epoch=4455, lrate=0.005, error=0.001\n >epoch=4456, lrate=0.005, error=0.001\n >epoch=4457, lrate=0.005, error=0.001\n >epoch=4458, lrate=0.005, error=0.001\n >epoch=4459, lrate=0.005, error=0.001\n >epoch=4460, lrate=0.005, error=0.001\n >epoch=4461, lrate=0.005, error=0.001\n >epoch=4462, lrate=0.005, error=0.001\n >epoch=4463, lrate=0.005, error=0.001\n >epoch=4464, lrate=0.005, error=0.000\n >epoch=4465, lrate=0.005, error=0.000\n >epoch=4466, lrate=0.005, error=0.000\n >epoch=4467, lrate=0.005, error=0.000\n >epoch=4468, lrate=0.005, error=0.000\n >epoch=4469, lrate=0.005, error=0.000\n >epoch=4470, lrate=0.005, error=0.000\n >epoch=4471, lrate=0.005, error=0.000\n >epoch=4472, lrate=0.005, error=0.000\n >epoch=4473, lrate=0.005, error=0.000\n >epoch=4474, lrate=0.005, error=0.000\n >epoch=4475, lrate=0.005, error=0.000\n >epoch=4476, lrate=0.005, error=0.000\n >epoch=4477, lrate=0.005, error=0.000\n >epoch=4478, lrate=0.005, error=0.000\n >epoch=4479, lrate=0.005, error=0.000\n >epoch=4480, lrate=0.005, error=0.000\n >epoch=4481, lrate=0.005, error=0.000\n >epoch=4482, lrate=0.005, error=0.000\n >epoch=4483, lrate=0.005, error=0.000\n >epoch=4484, lrate=0.005, error=0.000\n >epoch=4485, lrate=0.005, error=0.000\n >epoch=4486, lrate=0.005, error=0.000\n >epoch=4487, lrate=0.005, error=0.000\n >epoch=4488, lrate=0.005, error=0.000\n >epoch=4489, lrate=0.005, error=0.000\n >epoch=4490, lrate=0.005, error=0.000\n >epoch=4491, lrate=0.005, error=0.000\n >epoch=4492, lrate=0.005, error=0.000\n >epoch=4493, lrate=0.005, error=0.000\n >epoch=4494, lrate=0.005, error=0.000\n >epoch=4495, lrate=0.005, error=0.000\n >epoch=4496, lrate=0.005, error=0.000\n >epoch=4497, lrate=0.005, error=0.000\n >epoch=4498, lrate=0.005, error=0.000\n >epoch=4499, lrate=0.005, error=0.000\n >epoch=4500, lrate=0.005, error=0.000\n >epoch=4501, lrate=0.005, error=0.000\n >epoch=4502, lrate=0.005, error=0.000\n >epoch=4503, lrate=0.005, error=0.000\n >epoch=4504, lrate=0.005, error=0.000\n >epoch=4505, lrate=0.005, error=0.000\n >epoch=4506, lrate=0.005, error=0.000\n >epoch=4507, lrate=0.005, error=0.000\n >epoch=4508, lrate=0.005, error=0.000\n >epoch=4509, lrate=0.005, error=0.000\n >epoch=4510, lrate=0.005, error=0.000\n >epoch=4511, lrate=0.005, error=0.000\n >epoch=4512, lrate=0.005, error=0.000\n >epoch=4513, lrate=0.005, error=0.000\n >epoch=4514, lrate=0.005, error=0.000\n >epoch=4515, lrate=0.005, error=0.000\n >epoch=4516, lrate=0.005, error=0.000\n >epoch=4517, lrate=0.005, error=0.000\n >epoch=4518, lrate=0.005, error=0.000\n >epoch=4519, lrate=0.005, error=0.000\n >epoch=4520, lrate=0.005, error=0.000\n >epoch=4521, lrate=0.005, error=0.000\n >epoch=4522, lrate=0.005, error=0.000\n >epoch=4523, lrate=0.005, error=0.000\n >epoch=4524, lrate=0.005, error=0.000\n >epoch=4525, lrate=0.005, error=0.000\n >epoch=4526, lrate=0.005, error=0.000\n >epoch=4527, lrate=0.005, error=0.000\n >epoch=4528, lrate=0.005, error=0.000\n >epoch=4529, lrate=0.005, error=0.000\n >epoch=4530, lrate=0.005, error=0.000\n >epoch=4531, lrate=0.005, error=0.000\n >epoch=4532, lrate=0.005, error=0.000\n >epoch=4533, lrate=0.005, error=0.000\n >epoch=4534, lrate=0.005, error=0.000\n >epoch=4535, lrate=0.005, error=0.000\n >epoch=4536, lrate=0.005, error=0.000\n >epoch=4537, lrate=0.005, error=0.000\n >epoch=4538, lrate=0.005, error=0.000\n >epoch=4539, lrate=0.005, error=0.000\n >epoch=4540, lrate=0.005, error=0.000\n >epoch=4541, lrate=0.005, error=0.000\n >epoch=4542, lrate=0.005, error=0.000\n >epoch=4543, lrate=0.005, error=0.000\n >epoch=4544, lrate=0.005, error=0.000\n >epoch=4545, lrate=0.005, error=0.000\n >epoch=4546, lrate=0.005, error=0.000\n >epoch=4547, lrate=0.005, error=0.000\n >epoch=4548, lrate=0.005, error=0.000\n >epoch=4549, lrate=0.005, error=0.000\n >epoch=4550, lrate=0.005, error=0.000\n >epoch=4551, lrate=0.005, error=0.000\n >epoch=4552, lrate=0.005, error=0.000\n >epoch=4553, lrate=0.005, error=0.000\n >epoch=4554, lrate=0.005, error=0.000\n >epoch=4555, lrate=0.005, error=0.000\n >epoch=4556, lrate=0.005, error=0.000\n >epoch=4557, lrate=0.005, error=0.000\n >epoch=4558, lrate=0.005, error=0.000\n >epoch=4559, lrate=0.005, error=0.000\n >epoch=4560, lrate=0.005, error=0.000\n >epoch=4561, lrate=0.005, error=0.000\n >epoch=4562, lrate=0.005, error=0.000\n >epoch=4563, lrate=0.005, error=0.000\n >epoch=4564, lrate=0.005, error=0.000\n >epoch=4565, lrate=0.005, error=0.000\n >epoch=4566, lrate=0.005, error=0.000\n >epoch=4567, lrate=0.005, error=0.000\n >epoch=4568, lrate=0.005, error=0.000\n >epoch=4569, lrate=0.005, error=0.000\n >epoch=4570, lrate=0.005, error=0.000\n >epoch=4571, lrate=0.005, error=0.000\n >epoch=4572, lrate=0.005, error=0.000\n >epoch=4573, lrate=0.005, error=0.000\n >epoch=4574, lrate=0.005, error=0.000\n >epoch=4575, lrate=0.005, error=0.000\n >epoch=4576, lrate=0.005, error=0.000\n >epoch=4577, lrate=0.005, error=0.000\n >epoch=4578, lrate=0.005, error=0.000\n >epoch=4579, lrate=0.005, error=0.000\n >epoch=4580, lrate=0.005, error=0.000\n >epoch=4581, lrate=0.005, error=0.000\n >epoch=4582, lrate=0.005, error=0.000\n >epoch=4583, lrate=0.005, error=0.000\n >epoch=4584, lrate=0.005, error=0.000\n >epoch=4585, lrate=0.005, error=0.000\n >epoch=4586, lrate=0.005, error=0.000\n >epoch=4587, lrate=0.005, error=0.000\n >epoch=4588, lrate=0.005, error=0.000\n >epoch=4589, lrate=0.005, error=0.000\n >epoch=4590, lrate=0.005, error=0.000\n >epoch=4591, lrate=0.005, error=0.000\n >epoch=4592, lrate=0.005, error=0.000\n >epoch=4593, lrate=0.005, error=0.000\n >epoch=4594, lrate=0.005, error=0.000\n >epoch=4595, lrate=0.005, error=0.000\n >epoch=4596, lrate=0.005, error=0.000\n >epoch=4597, lrate=0.005, error=0.000\n >epoch=4598, lrate=0.005, error=0.000\n >epoch=4599, lrate=0.005, error=0.000\n >epoch=4600, lrate=0.005, error=0.000\n >epoch=4601, lrate=0.005, error=0.000\n >epoch=4602, lrate=0.005, error=0.000\n >epoch=4603, lrate=0.005, error=0.000\n >epoch=4604, lrate=0.005, error=0.000\n >epoch=4605, lrate=0.005, error=0.000\n >epoch=4606, lrate=0.005, error=0.000\n >epoch=4607, lrate=0.005, error=0.000\n >epoch=4608, lrate=0.005, error=0.000\n >epoch=4609, lrate=0.005, error=0.000\n >epoch=4610, lrate=0.005, error=0.000\n >epoch=4611, lrate=0.005, error=0.000\n >epoch=4612, lrate=0.005, error=0.000\n >epoch=4613, lrate=0.005, error=0.000\n >epoch=4614, lrate=0.005, error=0.000\n >epoch=4615, lrate=0.005, error=0.000\n >epoch=4616, lrate=0.005, error=0.000\n >epoch=4617, lrate=0.005, error=0.000\n >epoch=4618, lrate=0.005, error=0.000\n >epoch=4619, lrate=0.005, error=0.000\n >epoch=4620, lrate=0.005, error=0.000\n >epoch=4621, lrate=0.005, error=0.000\n >epoch=4622, lrate=0.005, error=0.000\n >epoch=4623, lrate=0.005, error=0.000\n >epoch=4624, lrate=0.005, error=0.000\n >epoch=4625, lrate=0.005, error=0.000\n >epoch=4626, lrate=0.005, error=0.000\n >epoch=4627, lrate=0.005, error=0.000\n >epoch=4628, lrate=0.005, error=0.000\n >epoch=4629, lrate=0.005, error=0.000\n >epoch=4630, lrate=0.005, error=0.000\n >epoch=4631, lrate=0.005, error=0.000\n >epoch=4632, lrate=0.005, error=0.000\n >epoch=4633, lrate=0.005, error=0.000\n >epoch=4634, lrate=0.005, error=0.000\n >epoch=4635, lrate=0.005, error=0.000\n >epoch=4636, lrate=0.005, error=0.000\n >epoch=4637, lrate=0.005, error=0.000\n >epoch=4638, lrate=0.005, error=0.000\n >epoch=4639, lrate=0.005, error=0.000\n >epoch=4640, lrate=0.005, error=0.000\n >epoch=4641, lrate=0.005, error=0.000\n >epoch=4642, lrate=0.005, error=0.000\n >epoch=4643, lrate=0.005, error=0.000\n >epoch=4644, lrate=0.005, error=0.000\n >epoch=4645, lrate=0.005, error=0.000\n >epoch=4646, lrate=0.005, error=0.000\n >epoch=4647, lrate=0.005, error=0.000\n >epoch=4648, lrate=0.005, error=0.000\n >epoch=4649, lrate=0.005, error=0.000\n >epoch=4650, lrate=0.005, error=0.000\n >epoch=4651, lrate=0.005, error=0.000\n >epoch=4652, lrate=0.005, error=0.000\n >epoch=4653, lrate=0.005, error=0.000\n >epoch=4654, lrate=0.005, error=0.000\n >epoch=4655, lrate=0.005, error=0.000\n >epoch=4656, lrate=0.005, error=0.000\n >epoch=4657, lrate=0.005, error=0.000\n >epoch=4658, lrate=0.005, error=0.000\n >epoch=4659, lrate=0.005, error=0.000\n >epoch=4660, lrate=0.005, error=0.000\n >epoch=4661, lrate=0.005, error=0.000\n >epoch=4662, lrate=0.005, error=0.000\n >epoch=4663, lrate=0.005, error=0.000\n >epoch=4664, lrate=0.005, error=0.000\n >epoch=4665, lrate=0.005, error=0.000\n >epoch=4666, lrate=0.005, error=0.000\n >epoch=4667, lrate=0.005, error=0.000\n >epoch=4668, lrate=0.005, error=0.000\n >epoch=4669, lrate=0.005, error=0.000\n >epoch=4670, lrate=0.005, error=0.000\n >epoch=4671, lrate=0.005, error=0.000\n >epoch=4672, lrate=0.005, error=0.000\n >epoch=4673, lrate=0.005, error=0.000\n >epoch=4674, lrate=0.005, error=0.000\n >epoch=4675, lrate=0.005, error=0.000\n >epoch=4676, lrate=0.005, error=0.000\n >epoch=4677, lrate=0.005, error=0.000\n >epoch=4678, lrate=0.005, error=0.000\n >epoch=4679, lrate=0.005, error=0.000\n >epoch=4680, lrate=0.005, error=0.000\n >epoch=4681, lrate=0.005, error=0.000\n >epoch=4682, lrate=0.005, error=0.000\n >epoch=4683, lrate=0.005, error=0.000\n >epoch=4684, lrate=0.005, error=0.000\n >epoch=4685, lrate=0.005, error=0.000\n >epoch=4686, lrate=0.005, error=0.000\n >epoch=4687, lrate=0.005, error=0.000\n >epoch=4688, lrate=0.005, error=0.000\n >epoch=4689, lrate=0.005, error=0.000\n >epoch=4690, lrate=0.005, error=0.000\n >epoch=4691, lrate=0.005, error=0.000\n >epoch=4692, lrate=0.005, error=0.000\n >epoch=4693, lrate=0.005, error=0.000\n >epoch=4694, lrate=0.005, error=0.000\n >epoch=4695, lrate=0.005, error=0.000\n >epoch=4696, lrate=0.005, error=0.000\n >epoch=4697, lrate=0.005, error=0.000\n >epoch=4698, lrate=0.005, error=0.000\n >epoch=4699, lrate=0.005, error=0.000\n >epoch=4700, lrate=0.005, error=0.000\n >epoch=4701, lrate=0.005, error=0.000\n >epoch=4702, lrate=0.005, error=0.000\n >epoch=4703, lrate=0.005, error=0.000\n >epoch=4704, lrate=0.005, error=0.000\n >epoch=4705, lrate=0.005, error=0.000\n >epoch=4706, lrate=0.005, error=0.000\n >epoch=4707, lrate=0.005, error=0.000\n >epoch=4708, lrate=0.005, error=0.000\n >epoch=4709, lrate=0.005, error=0.000\n >epoch=4710, lrate=0.005, error=0.000\n >epoch=4711, lrate=0.005, error=0.000\n >epoch=4712, lrate=0.005, error=0.000\n >epoch=4713, lrate=0.005, error=0.000\n >epoch=4714, lrate=0.005, error=0.000\n >epoch=4715, lrate=0.005, error=0.000\n >epoch=4716, lrate=0.005, error=0.000\n >epoch=4717, lrate=0.005, error=0.000\n >epoch=4718, lrate=0.005, error=0.000\n >epoch=4719, lrate=0.005, error=0.000\n >epoch=4720, lrate=0.005, error=0.000\n >epoch=4721, lrate=0.005, error=0.000\n >epoch=4722, lrate=0.005, error=0.000\n >epoch=4723, lrate=0.005, error=0.000\n >epoch=4724, lrate=0.005, error=0.000\n >epoch=4725, lrate=0.005, error=0.000\n >epoch=4726, lrate=0.005, error=0.000\n >epoch=4727, lrate=0.005, error=0.000\n >epoch=4728, lrate=0.005, error=0.000\n >epoch=4729, lrate=0.005, error=0.000\n >epoch=4730, lrate=0.005, error=0.000\n >epoch=4731, lrate=0.005, error=0.000\n >epoch=4732, lrate=0.005, error=0.000\n >epoch=4733, lrate=0.005, error=0.000\n >epoch=4734, lrate=0.005, error=0.000\n >epoch=4735, lrate=0.005, error=0.000\n >epoch=4736, lrate=0.005, error=0.000\n >epoch=4737, lrate=0.005, error=0.000\n >epoch=4738, lrate=0.005, error=0.000\n >epoch=4739, lrate=0.005, error=0.000\n >epoch=4740, lrate=0.005, error=0.000\n >epoch=4741, lrate=0.005, error=0.000\n >epoch=4742, lrate=0.005, error=0.000\n >epoch=4743, lrate=0.005, error=0.000\n >epoch=4744, lrate=0.005, error=0.000\n >epoch=4745, lrate=0.005, error=0.000\n >epoch=4746, lrate=0.005, error=0.000\n >epoch=4747, lrate=0.005, error=0.000\n >epoch=4748, lrate=0.005, error=0.000\n >epoch=4749, lrate=0.005, error=0.000\n >epoch=4750, lrate=0.005, error=0.000\n >epoch=4751, lrate=0.005, error=0.000\n >epoch=4752, lrate=0.005, error=0.000\n >epoch=4753, lrate=0.005, error=0.000\n >epoch=4754, lrate=0.005, error=0.000\n >epoch=4755, lrate=0.005, error=0.000\n >epoch=4756, lrate=0.005, error=0.000\n >epoch=4757, lrate=0.005, error=0.000\n >epoch=4758, lrate=0.005, error=0.000\n >epoch=4759, lrate=0.005, error=0.000\n >epoch=4760, lrate=0.005, error=0.000\n >epoch=4761, lrate=0.005, error=0.000\n >epoch=4762, lrate=0.005, error=0.000\n >epoch=4763, lrate=0.005, error=0.000\n >epoch=4764, lrate=0.005, error=0.000\n >epoch=4765, lrate=0.005, error=0.000\n >epoch=4766, lrate=0.005, error=0.000\n >epoch=4767, lrate=0.005, error=0.000\n >epoch=4768, lrate=0.005, error=0.000\n >epoch=4769, lrate=0.005, error=0.000\n >epoch=4770, lrate=0.005, error=0.000\n >epoch=4771, lrate=0.005, error=0.000\n >epoch=4772, lrate=0.005, error=0.000\n >epoch=4773, lrate=0.005, error=0.000\n >epoch=4774, lrate=0.005, error=0.000\n >epoch=4775, lrate=0.005, error=0.000\n >epoch=4776, lrate=0.005, error=0.000\n >epoch=4777, lrate=0.005, error=0.000\n >epoch=4778, lrate=0.005, error=0.000\n >epoch=4779, lrate=0.005, error=0.000\n >epoch=4780, lrate=0.005, error=0.000\n >epoch=4781, lrate=0.005, error=0.000\n >epoch=4782, lrate=0.005, error=0.000\n >epoch=4783, lrate=0.005, error=0.000\n >epoch=4784, lrate=0.005, error=0.000\n >epoch=4785, lrate=0.005, error=0.000\n >epoch=4786, lrate=0.005, error=0.000\n >epoch=4787, lrate=0.005, error=0.000\n >epoch=4788, lrate=0.005, error=0.000\n >epoch=4789, lrate=0.005, error=0.000\n >epoch=4790, lrate=0.005, error=0.000\n >epoch=4791, lrate=0.005, error=0.000\n >epoch=4792, lrate=0.005, error=0.000\n >epoch=4793, lrate=0.005, error=0.000\n >epoch=4794, lrate=0.005, error=0.000\n >epoch=4795, lrate=0.005, error=0.000\n >epoch=4796, lrate=0.005, error=0.000\n >epoch=4797, lrate=0.005, error=0.000\n >epoch=4798, lrate=0.005, error=0.000\n >epoch=4799, lrate=0.005, error=0.000\n >epoch=4800, lrate=0.005, error=0.000\n >epoch=4801, lrate=0.005, error=0.000\n >epoch=4802, lrate=0.005, error=0.000\n >epoch=4803, lrate=0.005, error=0.000\n >epoch=4804, lrate=0.005, error=0.000\n >epoch=4805, lrate=0.005, error=0.000\n >epoch=4806, lrate=0.005, error=0.000\n >epoch=4807, lrate=0.005, error=0.000\n >epoch=4808, lrate=0.005, error=0.000\n >epoch=4809, lrate=0.005, error=0.000\n >epoch=4810, lrate=0.005, error=0.000\n >epoch=4811, lrate=0.005, error=0.000\n >epoch=4812, lrate=0.005, error=0.000\n >epoch=4813, lrate=0.005, error=0.000\n >epoch=4814, lrate=0.005, error=0.000\n >epoch=4815, lrate=0.005, error=0.000\n >epoch=4816, lrate=0.005, error=0.000\n >epoch=4817, lrate=0.005, error=0.000\n >epoch=4818, lrate=0.005, error=0.000\n >epoch=4819, lrate=0.005, error=0.000\n >epoch=4820, lrate=0.005, error=0.000\n >epoch=4821, lrate=0.005, error=0.000\n >epoch=4822, lrate=0.005, error=0.000\n >epoch=4823, lrate=0.005, error=0.000\n >epoch=4824, lrate=0.005, error=0.000\n >epoch=4825, lrate=0.005, error=0.000\n >epoch=4826, lrate=0.005, error=0.000\n >epoch=4827, lrate=0.005, error=0.000\n >epoch=4828, lrate=0.005, error=0.000\n >epoch=4829, lrate=0.005, error=0.000\n >epoch=4830, lrate=0.005, error=0.000\n >epoch=4831, lrate=0.005, error=0.000\n >epoch=4832, lrate=0.005, error=0.000\n >epoch=4833, lrate=0.005, error=0.000\n >epoch=4834, lrate=0.005, error=0.000\n >epoch=4835, lrate=0.005, error=0.000\n >epoch=4836, lrate=0.005, error=0.000\n >epoch=4837, lrate=0.005, error=0.000\n >epoch=4838, lrate=0.005, error=0.000\n >epoch=4839, lrate=0.005, error=0.000\n >epoch=4840, lrate=0.005, error=0.000\n >epoch=4841, lrate=0.005, error=0.000\n >epoch=4842, lrate=0.005, error=0.000\n >epoch=4843, lrate=0.005, error=0.000\n >epoch=4844, lrate=0.005, error=0.000\n >epoch=4845, lrate=0.005, error=0.000\n >epoch=4846, lrate=0.005, error=0.000\n >epoch=4847, lrate=0.005, error=0.000\n >epoch=4848, lrate=0.005, error=0.000\n >epoch=4849, lrate=0.005, error=0.000\n >epoch=4850, lrate=0.005, error=0.000\n >epoch=4851, lrate=0.005, error=0.000\n >epoch=4852, lrate=0.005, error=0.000\n >epoch=4853, lrate=0.005, error=0.000\n >epoch=4854, lrate=0.005, error=0.000\n >epoch=4855, lrate=0.005, error=0.000\n >epoch=4856, lrate=0.005, error=0.000\n >epoch=4857, lrate=0.005, error=0.000\n >epoch=4858, lrate=0.005, error=0.000\n >epoch=4859, lrate=0.005, error=0.000\n >epoch=4860, lrate=0.005, error=0.000\n >epoch=4861, lrate=0.005, error=0.000\n >epoch=4862, lrate=0.005, error=0.000\n >epoch=4863, lrate=0.005, error=0.000\n >epoch=4864, lrate=0.005, error=0.000\n >epoch=4865, lrate=0.005, error=0.000\n >epoch=4866, lrate=0.005, error=0.000\n >epoch=4867, lrate=0.005, error=0.000\n >epoch=4868, lrate=0.005, error=0.000\n >epoch=4869, lrate=0.005, error=0.000\n >epoch=4870, lrate=0.005, error=0.000\n >epoch=4871, lrate=0.005, error=0.000\n >epoch=4872, lrate=0.005, error=0.000\n >epoch=4873, lrate=0.005, error=0.000\n >epoch=4874, lrate=0.005, error=0.000\n >epoch=4875, lrate=0.005, error=0.000\n >epoch=4876, lrate=0.005, error=0.000\n >epoch=4877, lrate=0.005, error=0.000\n >epoch=4878, lrate=0.005, error=0.000\n >epoch=4879, lrate=0.005, error=0.000\n >epoch=4880, lrate=0.005, error=0.000\n >epoch=4881, lrate=0.005, error=0.000\n >epoch=4882, lrate=0.005, error=0.000\n >epoch=4883, lrate=0.005, error=0.000\n >epoch=4884, lrate=0.005, error=0.000\n >epoch=4885, lrate=0.005, error=0.000\n >epoch=4886, lrate=0.005, error=0.000\n >epoch=4887, lrate=0.005, error=0.000\n >epoch=4888, lrate=0.005, error=0.000\n >epoch=4889, lrate=0.005, error=0.000\n >epoch=4890, lrate=0.005, error=0.000\n >epoch=4891, lrate=0.005, error=0.000\n >epoch=4892, lrate=0.005, error=0.000\n >epoch=4893, lrate=0.005, error=0.000\n >epoch=4894, lrate=0.005, error=0.000\n >epoch=4895, lrate=0.005, error=0.000\n >epoch=4896, lrate=0.005, error=0.000\n >epoch=4897, lrate=0.005, error=0.000\n >epoch=4898, lrate=0.005, error=0.000\n >epoch=4899, lrate=0.005, error=0.000\n >epoch=4900, lrate=0.005, error=0.000\n >epoch=4901, lrate=0.005, error=0.000\n >epoch=4902, lrate=0.005, error=0.000\n >epoch=4903, lrate=0.005, error=0.000\n >epoch=4904, lrate=0.005, error=0.000\n >epoch=4905, lrate=0.005, error=0.000\n >epoch=4906, lrate=0.005, error=0.000\n >epoch=4907, lrate=0.005, error=0.000\n >epoch=4908, lrate=0.005, error=0.000\n >epoch=4909, lrate=0.005, error=0.000\n >epoch=4910, lrate=0.005, error=0.000\n >epoch=4911, lrate=0.005, error=0.000\n >epoch=4912, lrate=0.005, error=0.000\n >epoch=4913, lrate=0.005, error=0.000\n >epoch=4914, lrate=0.005, error=0.000\n >epoch=4915, lrate=0.005, error=0.000\n >epoch=4916, lrate=0.005, error=0.000\n >epoch=4917, lrate=0.005, error=0.000\n >epoch=4918, lrate=0.005, error=0.000\n >epoch=4919, lrate=0.005, error=0.000\n >epoch=4920, lrate=0.005, error=0.000\n >epoch=4921, lrate=0.005, error=0.000\n >epoch=4922, lrate=0.005, error=0.000\n >epoch=4923, lrate=0.005, error=0.000\n >epoch=4924, lrate=0.005, error=0.000\n >epoch=4925, lrate=0.005, error=0.000\n >epoch=4926, lrate=0.005, error=0.000\n >epoch=4927, lrate=0.005, error=0.000\n >epoch=4928, lrate=0.005, error=0.000\n >epoch=4929, lrate=0.005, error=0.000\n >epoch=4930, lrate=0.005, error=0.000\n >epoch=4931, lrate=0.005, error=0.000\n >epoch=4932, lrate=0.005, error=0.000\n >epoch=4933, lrate=0.005, error=0.000\n >epoch=4934, lrate=0.005, error=0.000\n >epoch=4935, lrate=0.005, error=0.000\n >epoch=4936, lrate=0.005, error=0.000\n >epoch=4937, lrate=0.005, error=0.000\n >epoch=4938, lrate=0.005, error=0.000\n >epoch=4939, lrate=0.005, error=0.000\n >epoch=4940, lrate=0.005, error=0.000\n >epoch=4941, lrate=0.005, error=0.000\n >epoch=4942, lrate=0.005, error=0.000\n >epoch=4943, lrate=0.005, error=0.000\n >epoch=4944, lrate=0.005, error=0.000\n >epoch=4945, lrate=0.005, error=0.000\n >epoch=4946, lrate=0.005, error=0.000\n >epoch=4947, lrate=0.005, error=0.000\n >epoch=4948, lrate=0.005, error=0.000\n >epoch=4949, lrate=0.005, error=0.000\n >epoch=4950, lrate=0.005, error=0.000\n >epoch=4951, lrate=0.005, error=0.000\n >epoch=4952, lrate=0.005, error=0.000\n >epoch=4953, lrate=0.005, error=0.000\n >epoch=4954, lrate=0.005, error=0.000\n >epoch=4955, lrate=0.005, error=0.000\n >epoch=4956, lrate=0.005, error=0.000\n >epoch=4957, lrate=0.005, error=0.000\n >epoch=4958, lrate=0.005, error=0.000\n >epoch=4959, lrate=0.005, error=0.000\n >epoch=4960, lrate=0.005, error=0.000\n >epoch=4961, lrate=0.005, error=0.000\n >epoch=4962, lrate=0.005, error=0.000\n >epoch=4963, lrate=0.005, error=0.000\n >epoch=4964, lrate=0.005, error=0.000\n >epoch=4965, lrate=0.005, error=0.000\n >epoch=4966, lrate=0.005, error=0.000\n >epoch=4967, lrate=0.005, error=0.000\n >epoch=4968, lrate=0.005, error=0.000\n >epoch=4969, lrate=0.005, error=0.000\n >epoch=4970, lrate=0.005, error=0.000\n >epoch=4971, lrate=0.005, error=0.000\n >epoch=4972, lrate=0.005, error=0.000\n >epoch=4973, lrate=0.005, error=0.000\n >epoch=4974, lrate=0.005, error=0.000\n >epoch=4975, lrate=0.005, error=0.000\n >epoch=4976, lrate=0.005, error=0.000\n >epoch=4977, lrate=0.005, error=0.000\n >epoch=4978, lrate=0.005, error=0.000\n >epoch=4979, lrate=0.005, error=0.000\n >epoch=4980, lrate=0.005, error=0.000\n >epoch=4981, lrate=0.005, error=0.000\n >epoch=4982, lrate=0.005, error=0.000\n >epoch=4983, lrate=0.005, error=0.000\n >epoch=4984, lrate=0.005, error=0.000\n >epoch=4985, lrate=0.005, error=0.000\n >epoch=4986, lrate=0.005, error=0.000\n >epoch=4987, lrate=0.005, error=0.000\n >epoch=4988, lrate=0.005, error=0.000\n >epoch=4989, lrate=0.005, error=0.000\n >epoch=4990, lrate=0.005, error=0.000\n >epoch=4991, lrate=0.005, error=0.000\n >epoch=4992, lrate=0.005, error=0.000\n >epoch=4993, lrate=0.005, error=0.000\n >epoch=4994, lrate=0.005, error=0.000\n >epoch=4995, lrate=0.005, error=0.000\n >epoch=4996, lrate=0.005, error=0.000\n >epoch=4997, lrate=0.005, error=0.000\n >epoch=4998, lrate=0.005, error=0.000\n >epoch=4999, lrate=0.005, error=0.000\n >epoch=5000, lrate=0.005, error=0.000\n >epoch=5001, lrate=0.005, error=0.000\n >epoch=5002, lrate=0.005, error=0.000\n >epoch=5003, lrate=0.005, error=0.000\n >epoch=5004, lrate=0.005, error=0.000\n >epoch=5005, lrate=0.005, error=0.000\n >epoch=5006, lrate=0.005, error=0.000\n >epoch=5007, lrate=0.005, error=0.000\n >epoch=5008, lrate=0.005, error=0.000\n >epoch=5009, lrate=0.005, error=0.000\n >epoch=5010, lrate=0.005, error=0.000\n >epoch=5011, lrate=0.005, error=0.000\n >epoch=5012, lrate=0.005, error=0.000\n >epoch=5013, lrate=0.005, error=0.000\n >epoch=5014, lrate=0.005, error=0.000\n >epoch=5015, lrate=0.005, error=0.000\n >epoch=5016, lrate=0.005, error=0.000\n >epoch=5017, lrate=0.005, error=0.000\n >epoch=5018, lrate=0.005, error=0.000\n >epoch=5019, lrate=0.005, error=0.000\n >epoch=5020, lrate=0.005, error=0.000\n >epoch=5021, lrate=0.005, error=0.000\n >epoch=5022, lrate=0.005, error=0.000\n >epoch=5023, lrate=0.005, error=0.000\n >epoch=5024, lrate=0.005, error=0.000\n >epoch=5025, lrate=0.005, error=0.000\n >epoch=5026, lrate=0.005, error=0.000\n >epoch=5027, lrate=0.005, error=0.000\n >epoch=5028, lrate=0.005, error=0.000\n >epoch=5029, lrate=0.005, error=0.000\n >epoch=5030, lrate=0.005, error=0.000\n >epoch=5031, lrate=0.005, error=0.000\n >epoch=5032, lrate=0.005, error=0.000\n >epoch=5033, lrate=0.005, error=0.000\n >epoch=5034, lrate=0.005, error=0.000\n >epoch=5035, lrate=0.005, error=0.000\n >epoch=5036, lrate=0.005, error=0.000\n >epoch=5037, lrate=0.005, error=0.000\n >epoch=5038, lrate=0.005, error=0.000\n >epoch=5039, lrate=0.005, error=0.000\n >epoch=5040, lrate=0.005, error=0.000\n >epoch=5041, lrate=0.005, error=0.000\n >epoch=5042, lrate=0.005, error=0.000\n >epoch=5043, lrate=0.005, error=0.000\n >epoch=5044, lrate=0.005, error=0.000\n >epoch=5045, lrate=0.005, error=0.000\n >epoch=5046, lrate=0.005, error=0.000\n >epoch=5047, lrate=0.005, error=0.000\n >epoch=5048, lrate=0.005, error=0.000\n >epoch=5049, lrate=0.005, error=0.000\n >epoch=5050, lrate=0.005, error=0.000\n >epoch=5051, lrate=0.005, error=0.000\n >epoch=5052, lrate=0.005, error=0.000\n >epoch=5053, lrate=0.005, error=0.000\n >epoch=5054, lrate=0.005, error=0.000\n >epoch=5055, lrate=0.005, error=0.000\n >epoch=5056, lrate=0.005, error=0.000\n >epoch=5057, lrate=0.005, error=0.000\n >epoch=5058, lrate=0.005, error=0.000\n >epoch=5059, lrate=0.005, error=0.000\n >epoch=5060, lrate=0.005, error=0.000\n >epoch=5061, lrate=0.005, error=0.000\n >epoch=5062, lrate=0.005, error=0.000\n >epoch=5063, lrate=0.005, error=0.000\n >epoch=5064, lrate=0.005, error=0.000\n >epoch=5065, lrate=0.005, error=0.000\n >epoch=5066, lrate=0.005, error=0.000\n >epoch=5067, lrate=0.005, error=0.000\n >epoch=5068, lrate=0.005, error=0.000\n >epoch=5069, lrate=0.005, error=0.000\n >epoch=5070, lrate=0.005, error=0.000\n >epoch=5071, lrate=0.005, error=0.000\n >epoch=5072, lrate=0.005, error=0.000\n >epoch=5073, lrate=0.005, error=0.000\n >epoch=5074, lrate=0.005, error=0.000\n >epoch=5075, lrate=0.005, error=0.000\n >epoch=5076, lrate=0.005, error=0.000\n >epoch=5077, lrate=0.005, error=0.000\n >epoch=5078, lrate=0.005, error=0.000\n >epoch=5079, lrate=0.005, error=0.000\n >epoch=5080, lrate=0.005, error=0.000\n >epoch=5081, lrate=0.005, error=0.000\n >epoch=5082, lrate=0.005, error=0.000\n >epoch=5083, lrate=0.005, error=0.000\n >epoch=5084, lrate=0.005, error=0.000\n >epoch=5085, lrate=0.005, error=0.000\n >epoch=5086, lrate=0.005, error=0.000\n >epoch=5087, lrate=0.005, error=0.000\n >epoch=5088, lrate=0.005, error=0.000\n >epoch=5089, lrate=0.005, error=0.000\n >epoch=5090, lrate=0.005, error=0.000\n >epoch=5091, lrate=0.005, error=0.000\n >epoch=5092, lrate=0.005, error=0.000\n >epoch=5093, lrate=0.005, error=0.000\n >epoch=5094, lrate=0.005, error=0.000\n >epoch=5095, lrate=0.005, error=0.000\n >epoch=5096, lrate=0.005, error=0.000\n >epoch=5097, lrate=0.005, error=0.000\n >epoch=5098, lrate=0.005, error=0.000\n >epoch=5099, lrate=0.005, error=0.000\n >epoch=5100, lrate=0.005, error=0.000\n >epoch=5101, lrate=0.005, error=0.000\n >epoch=5102, lrate=0.005, error=0.000\n >epoch=5103, lrate=0.005, error=0.000\n >epoch=5104, lrate=0.005, error=0.000\n >epoch=5105, lrate=0.005, error=0.000\n >epoch=5106, lrate=0.005, error=0.000\n >epoch=5107, lrate=0.005, error=0.000\n >epoch=5108, lrate=0.005, error=0.000\n >epoch=5109, lrate=0.005, error=0.000\n >epoch=5110, lrate=0.005, error=0.000\n >epoch=5111, lrate=0.005, error=0.000\n >epoch=5112, lrate=0.005, error=0.000\n >epoch=5113, lrate=0.005, error=0.000\n >epoch=5114, lrate=0.005, error=0.000\n >epoch=5115, lrate=0.005, error=0.000\n >epoch=5116, lrate=0.005, error=0.000\n >epoch=5117, lrate=0.005, error=0.000\n >epoch=5118, lrate=0.005, error=0.000\n >epoch=5119, lrate=0.005, error=0.000\n >epoch=5120, lrate=0.005, error=0.000\n >epoch=5121, lrate=0.005, error=0.000\n >epoch=5122, lrate=0.005, error=0.000\n >epoch=5123, lrate=0.005, error=0.000\n >epoch=5124, lrate=0.005, error=0.000\n >epoch=5125, lrate=0.005, error=0.000\n >epoch=5126, lrate=0.005, error=0.000\n >epoch=5127, lrate=0.005, error=0.000\n >epoch=5128, lrate=0.005, error=0.000\n >epoch=5129, lrate=0.005, error=0.000\n >epoch=5130, lrate=0.005, error=0.000\n >epoch=5131, lrate=0.005, error=0.000\n >epoch=5132, lrate=0.005, error=0.000\n >epoch=5133, lrate=0.005, error=0.000\n >epoch=5134, lrate=0.005, error=0.000\n >epoch=5135, lrate=0.005, error=0.000\n >epoch=5136, lrate=0.005, error=0.000\n >epoch=5137, lrate=0.005, error=0.000\n >epoch=5138, lrate=0.005, error=0.000\n >epoch=5139, lrate=0.005, error=0.000\n >epoch=5140, lrate=0.005, error=0.000\n >epoch=5141, lrate=0.005, error=0.000\n >epoch=5142, lrate=0.005, error=0.000\n >epoch=5143, lrate=0.005, error=0.000\n >epoch=5144, lrate=0.005, error=0.000\n >epoch=5145, lrate=0.005, error=0.000\n >epoch=5146, lrate=0.005, error=0.000\n >epoch=5147, lrate=0.005, error=0.000\n >epoch=5148, lrate=0.005, error=0.000\n >epoch=5149, lrate=0.005, error=0.000\n >epoch=5150, lrate=0.005, error=0.000\n >epoch=5151, lrate=0.005, error=0.000\n >epoch=5152, lrate=0.005, error=0.000\n >epoch=5153, lrate=0.005, error=0.000\n >epoch=5154, lrate=0.005, error=0.000\n >epoch=5155, lrate=0.005, error=0.000\n >epoch=5156, lrate=0.005, error=0.000\n >epoch=5157, lrate=0.005, error=0.000\n >epoch=5158, lrate=0.005, error=0.000\n >epoch=5159, lrate=0.005, error=0.000\n >epoch=5160, lrate=0.005, error=0.000\n >epoch=5161, lrate=0.005, error=0.000\n >epoch=5162, lrate=0.005, error=0.000\n >epoch=5163, lrate=0.005, error=0.000\n >epoch=5164, lrate=0.005, error=0.000\n >epoch=5165, lrate=0.005, error=0.000\n >epoch=5166, lrate=0.005, error=0.000\n >epoch=5167, lrate=0.005, error=0.000\n >epoch=5168, lrate=0.005, error=0.000\n >epoch=5169, lrate=0.005, error=0.000\n >epoch=5170, lrate=0.005, error=0.000\n >epoch=5171, lrate=0.005, error=0.000\n >epoch=5172, lrate=0.005, error=0.000\n >epoch=5173, lrate=0.005, error=0.000\n >epoch=5174, lrate=0.005, error=0.000\n >epoch=5175, lrate=0.005, error=0.000\n >epoch=5176, lrate=0.005, error=0.000\n >epoch=5177, lrate=0.005, error=0.000\n >epoch=5178, lrate=0.005, error=0.000\n >epoch=5179, lrate=0.005, error=0.000\n >epoch=5180, lrate=0.005, error=0.000\n >epoch=5181, lrate=0.005, error=0.000\n >epoch=5182, lrate=0.005, error=0.000\n >epoch=5183, lrate=0.005, error=0.000\n >epoch=5184, lrate=0.005, error=0.000\n >epoch=5185, lrate=0.005, error=0.000\n >epoch=5186, lrate=0.005, error=0.000\n >epoch=5187, lrate=0.005, error=0.000\n >epoch=5188, lrate=0.005, error=0.000\n >epoch=5189, lrate=0.005, error=0.000\n >epoch=5190, lrate=0.005, error=0.000\n >epoch=5191, lrate=0.005, error=0.000\n >epoch=5192, lrate=0.005, error=0.000\n >epoch=5193, lrate=0.005, error=0.000\n >epoch=5194, lrate=0.005, error=0.000\n >epoch=5195, lrate=0.005, error=0.000\n >epoch=5196, lrate=0.005, error=0.000\n >epoch=5197, lrate=0.005, error=0.000\n >epoch=5198, lrate=0.005, error=0.000\n >epoch=5199, lrate=0.005, error=0.000\n >epoch=5200, lrate=0.005, error=0.000\n >epoch=5201, lrate=0.005, error=0.000\n >epoch=5202, lrate=0.005, error=0.000\n >epoch=5203, lrate=0.005, error=0.000\n >epoch=5204, lrate=0.005, error=0.000\n >epoch=5205, lrate=0.005, error=0.000\n >epoch=5206, lrate=0.005, error=0.000\n >epoch=5207, lrate=0.005, error=0.000\n >epoch=5208, lrate=0.005, error=0.000\n >epoch=5209, lrate=0.005, error=0.000\n >epoch=5210, lrate=0.005, error=0.000\n >epoch=5211, lrate=0.005, error=0.000\n >epoch=5212, lrate=0.005, error=0.000\n >epoch=5213, lrate=0.005, error=0.000\n >epoch=5214, lrate=0.005, error=0.000\n >epoch=5215, lrate=0.005, error=0.000\n >epoch=5216, lrate=0.005, error=0.000\n >epoch=5217, lrate=0.005, error=0.000\n >epoch=5218, lrate=0.005, error=0.000\n >epoch=5219, lrate=0.005, error=0.000\n >epoch=5220, lrate=0.005, error=0.000\n >epoch=5221, lrate=0.005, error=0.000\n >epoch=5222, lrate=0.005, error=0.000\n >epoch=5223, lrate=0.005, error=0.000\n >epoch=5224, lrate=0.005, error=0.000\n >epoch=5225, lrate=0.005, error=0.000\n >epoch=5226, lrate=0.005, error=0.000\n >epoch=5227, lrate=0.005, error=0.000\n >epoch=5228, lrate=0.005, error=0.000\n >epoch=5229, lrate=0.005, error=0.000\n >epoch=5230, lrate=0.005, error=0.000\n >epoch=5231, lrate=0.005, error=0.000\n >epoch=5232, lrate=0.005, error=0.000\n >epoch=5233, lrate=0.005, error=0.000\n >epoch=5234, lrate=0.005, error=0.000\n >epoch=5235, lrate=0.005, error=0.000\n >epoch=5236, lrate=0.005, error=0.000\n >epoch=5237, lrate=0.005, error=0.000\n >epoch=5238, lrate=0.005, error=0.000\n >epoch=5239, lrate=0.005, error=0.000\n >epoch=5240, lrate=0.005, error=0.000\n >epoch=5241, lrate=0.005, error=0.000\n >epoch=5242, lrate=0.005, error=0.000\n >epoch=5243, lrate=0.005, error=0.000\n >epoch=5244, lrate=0.005, error=0.000\n >epoch=5245, lrate=0.005, error=0.000\n >epoch=5246, lrate=0.005, error=0.000\n >epoch=5247, lrate=0.005, error=0.000\n >epoch=5248, lrate=0.005, error=0.000\n >epoch=5249, lrate=0.005, error=0.000\n >epoch=5250, lrate=0.005, error=0.000\n >epoch=5251, lrate=0.005, error=0.000\n >epoch=5252, lrate=0.005, error=0.000\n >epoch=5253, lrate=0.005, error=0.000\n >epoch=5254, lrate=0.005, error=0.000\n >epoch=5255, lrate=0.005, error=0.000\n >epoch=5256, lrate=0.005, error=0.000\n >epoch=5257, lrate=0.005, error=0.000\n >epoch=5258, lrate=0.005, error=0.000\n >epoch=5259, lrate=0.005, error=0.000\n >epoch=5260, lrate=0.005, error=0.000\n >epoch=5261, lrate=0.005, error=0.000\n >epoch=5262, lrate=0.005, error=0.000\n >epoch=5263, lrate=0.005, error=0.000\n >epoch=5264, lrate=0.005, error=0.000\n >epoch=5265, lrate=0.005, error=0.000\n >epoch=5266, lrate=0.005, error=0.000\n >epoch=5267, lrate=0.005, error=0.000\n >epoch=5268, lrate=0.005, error=0.000\n >epoch=5269, lrate=0.005, error=0.000\n >epoch=5270, lrate=0.005, error=0.000\n >epoch=5271, lrate=0.005, error=0.000\n >epoch=5272, lrate=0.005, error=0.000\n >epoch=5273, lrate=0.005, error=0.000\n >epoch=5274, lrate=0.005, error=0.000\n >epoch=5275, lrate=0.005, error=0.000\n >epoch=5276, lrate=0.005, error=0.000\n >epoch=5277, lrate=0.005, error=0.000\n >epoch=5278, lrate=0.005, error=0.000\n >epoch=5279, lrate=0.005, error=0.000\n >epoch=5280, lrate=0.005, error=0.000\n >epoch=5281, lrate=0.005, error=0.000\n >epoch=5282, lrate=0.005, error=0.000\n >epoch=5283, lrate=0.005, error=0.000\n >epoch=5284, lrate=0.005, error=0.000\n >epoch=5285, lrate=0.005, error=0.000\n >epoch=5286, lrate=0.005, error=0.000\n >epoch=5287, lrate=0.005, error=0.000\n >epoch=5288, lrate=0.005, error=0.000\n >epoch=5289, lrate=0.005, error=0.000\n >epoch=5290, lrate=0.005, error=0.000\n >epoch=5291, lrate=0.005, error=0.000\n >epoch=5292, lrate=0.005, error=0.000\n >epoch=5293, lrate=0.005, error=0.000\n >epoch=5294, lrate=0.005, error=0.000\n >epoch=5295, lrate=0.005, error=0.000\n >epoch=5296, lrate=0.005, error=0.000\n >epoch=5297, lrate=0.005, error=0.000\n >epoch=5298, lrate=0.005, error=0.000\n >epoch=5299, lrate=0.005, error=0.000\n >epoch=5300, lrate=0.005, error=0.000\n >epoch=5301, lrate=0.005, error=0.000\n >epoch=5302, lrate=0.005, error=0.000\n >epoch=5303, lrate=0.005, error=0.000\n >epoch=5304, lrate=0.005, error=0.000\n >epoch=5305, lrate=0.005, error=0.000\n >epoch=5306, lrate=0.005, error=0.000\n >epoch=5307, lrate=0.005, error=0.000\n >epoch=5308, lrate=0.005, error=0.000\n >epoch=5309, lrate=0.005, error=0.000\n >epoch=5310, lrate=0.005, error=0.000\n >epoch=5311, lrate=0.005, error=0.000\n >epoch=5312, lrate=0.005, error=0.000\n >epoch=5313, lrate=0.005, error=0.000\n >epoch=5314, lrate=0.005, error=0.000\n >epoch=5315, lrate=0.005, error=0.000\n >epoch=5316, lrate=0.005, error=0.000\n >epoch=5317, lrate=0.005, error=0.000\n >epoch=5318, lrate=0.005, error=0.000\n >epoch=5319, lrate=0.005, error=0.000\n >epoch=5320, lrate=0.005, error=0.000\n >epoch=5321, lrate=0.005, error=0.000\n >epoch=5322, lrate=0.005, error=0.000\n >epoch=5323, lrate=0.005, error=0.000\n >epoch=5324, lrate=0.005, error=0.000\n >epoch=5325, lrate=0.005, error=0.000\n >epoch=5326, lrate=0.005, error=0.000\n >epoch=5327, lrate=0.005, error=0.000\n >epoch=5328, lrate=0.005, error=0.000\n >epoch=5329, lrate=0.005, error=0.000\n >epoch=5330, lrate=0.005, error=0.000\n >epoch=5331, lrate=0.005, error=0.000\n >epoch=5332, lrate=0.005, error=0.000\n >epoch=5333, lrate=0.005, error=0.000\n >epoch=5334, lrate=0.005, error=0.000\n >epoch=5335, lrate=0.005, error=0.000\n >epoch=5336, lrate=0.005, error=0.000\n >epoch=5337, lrate=0.005, error=0.000\n >epoch=5338, lrate=0.005, error=0.000\n >epoch=5339, lrate=0.005, error=0.000\n >epoch=5340, lrate=0.005, error=0.000\n >epoch=5341, lrate=0.005, error=0.000\n >epoch=5342, lrate=0.005, error=0.000\n >epoch=5343, lrate=0.005, error=0.000\n >epoch=5344, lrate=0.005, error=0.000\n >epoch=5345, lrate=0.005, error=0.000\n >epoch=5346, lrate=0.005, error=0.000\n >epoch=5347, lrate=0.005, error=0.000\n >epoch=5348, lrate=0.005, error=0.000\n >epoch=5349, lrate=0.005, error=0.000\n >epoch=5350, lrate=0.005, error=0.000\n >epoch=5351, lrate=0.005, error=0.000\n >epoch=5352, lrate=0.005, error=0.000\n >epoch=5353, lrate=0.005, error=0.000\n >epoch=5354, lrate=0.005, error=0.000\n >epoch=5355, lrate=0.005, error=0.000\n >epoch=5356, lrate=0.005, error=0.000\n >epoch=5357, lrate=0.005, error=0.000\n >epoch=5358, lrate=0.005, error=0.000\n >epoch=5359, lrate=0.005, error=0.000\n >epoch=5360, lrate=0.005, error=0.000\n >epoch=5361, lrate=0.005, error=0.000\n >epoch=5362, lrate=0.005, error=0.000\n >epoch=5363, lrate=0.005, error=0.000\n >epoch=5364, lrate=0.005, error=0.000\n >epoch=5365, lrate=0.005, error=0.000\n >epoch=5366, lrate=0.005, error=0.000\n >epoch=5367, lrate=0.005, error=0.000\n >epoch=5368, lrate=0.005, error=0.000\n >epoch=5369, lrate=0.005, error=0.000\n >epoch=5370, lrate=0.005, error=0.000\n >epoch=5371, lrate=0.005, error=0.000\n >epoch=5372, lrate=0.005, error=0.000\n >epoch=5373, lrate=0.005, error=0.000\n >epoch=5374, lrate=0.005, error=0.000\n >epoch=5375, lrate=0.005, error=0.000\n >epoch=5376, lrate=0.005, error=0.000\n >epoch=5377, lrate=0.005, error=0.000\n >epoch=5378, lrate=0.005, error=0.000\n >epoch=5379, lrate=0.005, error=0.000\n >epoch=5380, lrate=0.005, error=0.000\n >epoch=5381, lrate=0.005, error=0.000\n >epoch=5382, lrate=0.005, error=0.000\n >epoch=5383, lrate=0.005, error=0.000\n >epoch=5384, lrate=0.005, error=0.000\n >epoch=5385, lrate=0.005, error=0.000\n >epoch=5386, lrate=0.005, error=0.000\n >epoch=5387, lrate=0.005, error=0.000\n >epoch=5388, lrate=0.005, error=0.000\n >epoch=5389, lrate=0.005, error=0.000\n >epoch=5390, lrate=0.005, error=0.000\n >epoch=5391, lrate=0.005, error=0.000\n >epoch=5392, lrate=0.005, error=0.000\n >epoch=5393, lrate=0.005, error=0.000\n >epoch=5394, lrate=0.005, error=0.000\n >epoch=5395, lrate=0.005, error=0.000\n >epoch=5396, lrate=0.005, error=0.000\n >epoch=5397, lrate=0.005, error=0.000\n >epoch=5398, lrate=0.005, error=0.000\n >epoch=5399, lrate=0.005, error=0.000\n >epoch=5400, lrate=0.005, error=0.000\n >epoch=5401, lrate=0.005, error=0.000\n >epoch=5402, lrate=0.005, error=0.000\n >epoch=5403, lrate=0.005, error=0.000\n >epoch=5404, lrate=0.005, error=0.000\n >epoch=5405, lrate=0.005, error=0.000\n >epoch=5406, lrate=0.005, error=0.000\n >epoch=5407, lrate=0.005, error=0.000\n >epoch=5408, lrate=0.005, error=0.000\n >epoch=5409, lrate=0.005, error=0.000\n >epoch=5410, lrate=0.005, error=0.000\n >epoch=5411, lrate=0.005, error=0.000\n >epoch=5412, lrate=0.005, error=0.000\n >epoch=5413, lrate=0.005, error=0.000\n >epoch=5414, lrate=0.005, error=0.000\n >epoch=5415, lrate=0.005, error=0.000\n >epoch=5416, lrate=0.005, error=0.000\n >epoch=5417, lrate=0.005, error=0.000\n >epoch=5418, lrate=0.005, error=0.000\n >epoch=5419, lrate=0.005, error=0.000\n >epoch=5420, lrate=0.005, error=0.000\n >epoch=5421, lrate=0.005, error=0.000\n >epoch=5422, lrate=0.005, error=0.000\n >epoch=5423, lrate=0.005, error=0.000\n >epoch=5424, lrate=0.005, error=0.000\n >epoch=5425, lrate=0.005, error=0.000\n >epoch=5426, lrate=0.005, error=0.000\n >epoch=5427, lrate=0.005, error=0.000\n >epoch=5428, lrate=0.005, error=0.000\n >epoch=5429, lrate=0.005, error=0.000\n >epoch=5430, lrate=0.005, error=0.000\n >epoch=5431, lrate=0.005, error=0.000\n >epoch=5432, lrate=0.005, error=0.000\n >epoch=5433, lrate=0.005, error=0.000\n >epoch=5434, lrate=0.005, error=0.000\n >epoch=5435, lrate=0.005, error=0.000\n >epoch=5436, lrate=0.005, error=0.000\n >epoch=5437, lrate=0.005, error=0.000\n >epoch=5438, lrate=0.005, error=0.000\n >epoch=5439, lrate=0.005, error=0.000\n >epoch=5440, lrate=0.005, error=0.000\n >epoch=5441, lrate=0.005, error=0.000\n >epoch=5442, lrate=0.005, error=0.000\n >epoch=5443, lrate=0.005, error=0.000\n >epoch=5444, lrate=0.005, error=0.000\n >epoch=5445, lrate=0.005, error=0.000\n >epoch=5446, lrate=0.005, error=0.000\n >epoch=5447, lrate=0.005, error=0.000\n >epoch=5448, lrate=0.005, error=0.000\n >epoch=5449, lrate=0.005, error=0.000\n >epoch=5450, lrate=0.005, error=0.000\n >epoch=5451, lrate=0.005, error=0.000\n >epoch=5452, lrate=0.005, error=0.000\n >epoch=5453, lrate=0.005, error=0.000\n >epoch=5454, lrate=0.005, error=0.000\n >epoch=5455, lrate=0.005, error=0.000\n >epoch=5456, lrate=0.005, error=0.000\n >epoch=5457, lrate=0.005, error=0.000\n >epoch=5458, lrate=0.005, error=0.000\n >epoch=5459, lrate=0.005, error=0.000\n >epoch=5460, lrate=0.005, error=0.000\n >epoch=5461, lrate=0.005, error=0.000\n >epoch=5462, lrate=0.005, error=0.000\n >epoch=5463, lrate=0.005, error=0.000\n >epoch=5464, lrate=0.005, error=0.000\n >epoch=5465, lrate=0.005, error=0.000\n >epoch=5466, lrate=0.005, error=0.000\n >epoch=5467, lrate=0.005, error=0.000\n >epoch=5468, lrate=0.005, error=0.000\n >epoch=5469, lrate=0.005, error=0.000\n >epoch=5470, lrate=0.005, error=0.000\n >epoch=5471, lrate=0.005, error=0.000\n >epoch=5472, lrate=0.005, error=0.000\n >epoch=5473, lrate=0.005, error=0.000\n >epoch=5474, lrate=0.005, error=0.000\n >epoch=5475, lrate=0.005, error=0.000\n >epoch=5476, lrate=0.005, error=0.000\n >epoch=5477, lrate=0.005, error=0.000\n >epoch=5478, lrate=0.005, error=0.000\n >epoch=5479, lrate=0.005, error=0.000\n >epoch=5480, lrate=0.005, error=0.000\n >epoch=5481, lrate=0.005, error=0.000\n >epoch=5482, lrate=0.005, error=0.000\n >epoch=5483, lrate=0.005, error=0.000\n >epoch=5484, lrate=0.005, error=0.000\n >epoch=5485, lrate=0.005, error=0.000\n >epoch=5486, lrate=0.005, error=0.000\n >epoch=5487, lrate=0.005, error=0.000\n >epoch=5488, lrate=0.005, error=0.000\n >epoch=5489, lrate=0.005, error=0.000\n >epoch=5490, lrate=0.005, error=0.000\n >epoch=5491, lrate=0.005, error=0.000\n >epoch=5492, lrate=0.005, error=0.000\n >epoch=5493, lrate=0.005, error=0.000\n >epoch=5494, lrate=0.005, error=0.000\n >epoch=5495, lrate=0.005, error=0.000\n >epoch=5496, lrate=0.005, error=0.000\n >epoch=5497, lrate=0.005, error=0.000\n >epoch=5498, lrate=0.005, error=0.000\n >epoch=5499, lrate=0.005, error=0.000\n >epoch=5500, lrate=0.005, error=0.000\n >epoch=5501, lrate=0.005, error=0.000\n >epoch=5502, lrate=0.005, error=0.000\n >epoch=5503, lrate=0.005, error=0.000\n >epoch=5504, lrate=0.005, error=0.000\n >epoch=5505, lrate=0.005, error=0.000\n >epoch=5506, lrate=0.005, error=0.000\n >epoch=5507, lrate=0.005, error=0.000\n >epoch=5508, lrate=0.005, error=0.000\n >epoch=5509, lrate=0.005, error=0.000\n >epoch=5510, lrate=0.005, error=0.000\n >epoch=5511, lrate=0.005, error=0.000\n >epoch=5512, lrate=0.005, error=0.000\n >epoch=5513, lrate=0.005, error=0.000\n >epoch=5514, lrate=0.005, error=0.000\n >epoch=5515, lrate=0.005, error=0.000\n >epoch=5516, lrate=0.005, error=0.000\n >epoch=5517, lrate=0.005, error=0.000\n >epoch=5518, lrate=0.005, error=0.000\n >epoch=5519, lrate=0.005, error=0.000\n >epoch=5520, lrate=0.005, error=0.000\n >epoch=5521, lrate=0.005, error=0.000\n >epoch=5522, lrate=0.005, error=0.000\n >epoch=5523, lrate=0.005, error=0.000\n >epoch=5524, lrate=0.005, error=0.000\n >epoch=5525, lrate=0.005, error=0.000\n >epoch=5526, lrate=0.005, error=0.000\n >epoch=5527, lrate=0.005, error=0.000\n >epoch=5528, lrate=0.005, error=0.000\n >epoch=5529, lrate=0.005, error=0.000\n >epoch=5530, lrate=0.005, error=0.000\n >epoch=5531, lrate=0.005, error=0.000\n >epoch=5532, lrate=0.005, error=0.000\n >epoch=5533, lrate=0.005, error=0.000\n >epoch=5534, lrate=0.005, error=0.000\n >epoch=5535, lrate=0.005, error=0.000\n >epoch=5536, lrate=0.005, error=0.000\n >epoch=5537, lrate=0.005, error=0.000\n >epoch=5538, lrate=0.005, error=0.000\n >epoch=5539, lrate=0.005, error=0.000\n >epoch=5540, lrate=0.005, error=0.000\n >epoch=5541, lrate=0.005, error=0.000\n >epoch=5542, lrate=0.005, error=0.000\n >epoch=5543, lrate=0.005, error=0.000\n >epoch=5544, lrate=0.005, error=0.000\n >epoch=5545, lrate=0.005, error=0.000\n >epoch=5546, lrate=0.005, error=0.000\n >epoch=5547, lrate=0.005, error=0.000\n >epoch=5548, lrate=0.005, error=0.000\n >epoch=5549, lrate=0.005, error=0.000\n >epoch=5550, lrate=0.005, error=0.000\n >epoch=5551, lrate=0.005, error=0.000\n >epoch=5552, lrate=0.005, error=0.000\n >epoch=5553, lrate=0.005, error=0.000\n >epoch=5554, lrate=0.005, error=0.000\n >epoch=5555, lrate=0.005, error=0.000\n >epoch=5556, lrate=0.005, error=0.000\n >epoch=5557, lrate=0.005, error=0.000\n >epoch=5558, lrate=0.005, error=0.000\n >epoch=5559, lrate=0.005, error=0.000\n >epoch=5560, lrate=0.005, error=0.000\n >epoch=5561, lrate=0.005, error=0.000\n >epoch=5562, lrate=0.005, error=0.000\n >epoch=5563, lrate=0.005, error=0.000\n >epoch=5564, lrate=0.005, error=0.000\n >epoch=5565, lrate=0.005, error=0.000\n >epoch=5566, lrate=0.005, error=0.000\n >epoch=5567, lrate=0.005, error=0.000\n >epoch=5568, lrate=0.005, error=0.000\n >epoch=5569, lrate=0.005, error=0.000\n >epoch=5570, lrate=0.005, error=0.000\n >epoch=5571, lrate=0.005, error=0.000\n >epoch=5572, lrate=0.005, error=0.000\n >epoch=5573, lrate=0.005, error=0.000\n >epoch=5574, lrate=0.005, error=0.000\n >epoch=5575, lrate=0.005, error=0.000\n >epoch=5576, lrate=0.005, error=0.000\n >epoch=5577, lrate=0.005, error=0.000\n >epoch=5578, lrate=0.005, error=0.000\n >epoch=5579, lrate=0.005, error=0.000\n >epoch=5580, lrate=0.005, error=0.000\n >epoch=5581, lrate=0.005, error=0.000\n >epoch=5582, lrate=0.005, error=0.000\n >epoch=5583, lrate=0.005, error=0.000\n >epoch=5584, lrate=0.005, error=0.000\n >epoch=5585, lrate=0.005, error=0.000\n >epoch=5586, lrate=0.005, error=0.000\n >epoch=5587, lrate=0.005, error=0.000\n >epoch=5588, lrate=0.005, error=0.000\n >epoch=5589, lrate=0.005, error=0.000\n >epoch=5590, lrate=0.005, error=0.000\n >epoch=5591, lrate=0.005, error=0.000\n >epoch=5592, lrate=0.005, error=0.000\n >epoch=5593, lrate=0.005, error=0.000\n >epoch=5594, lrate=0.005, error=0.000\n >epoch=5595, lrate=0.005, error=0.000\n >epoch=5596, lrate=0.005, error=0.000\n >epoch=5597, lrate=0.005, error=0.000\n >epoch=5598, lrate=0.005, error=0.000\n >epoch=5599, lrate=0.005, error=0.000\n >epoch=5600, lrate=0.005, error=0.000\n >epoch=5601, lrate=0.005, error=0.000\n >epoch=5602, lrate=0.005, error=0.000\n >epoch=5603, lrate=0.005, error=0.000\n >epoch=5604, lrate=0.005, error=0.000\n >epoch=5605, lrate=0.005, error=0.000\n >epoch=5606, lrate=0.005, error=0.000\n >epoch=5607, lrate=0.005, error=0.000\n >epoch=5608, lrate=0.005, error=0.000\n >epoch=5609, lrate=0.005, error=0.000\n >epoch=5610, lrate=0.005, error=0.000\n >epoch=5611, lrate=0.005, error=0.000\n >epoch=5612, lrate=0.005, error=0.000\n >epoch=5613, lrate=0.005, error=0.000\n >epoch=5614, lrate=0.005, error=0.000\n >epoch=5615, lrate=0.005, error=0.000\n >epoch=5616, lrate=0.005, error=0.000\n >epoch=5617, lrate=0.005, error=0.000\n >epoch=5618, lrate=0.005, error=0.000\n >epoch=5619, lrate=0.005, error=0.000\n >epoch=5620, lrate=0.005, error=0.000\n >epoch=5621, lrate=0.005, error=0.000\n >epoch=5622, lrate=0.005, error=0.000\n >epoch=5623, lrate=0.005, error=0.000\n >epoch=5624, lrate=0.005, error=0.000\n >epoch=5625, lrate=0.005, error=0.000\n >epoch=5626, lrate=0.005, error=0.000\n >epoch=5627, lrate=0.005, error=0.000\n >epoch=5628, lrate=0.005, error=0.000\n >epoch=5629, lrate=0.005, error=0.000\n >epoch=5630, lrate=0.005, error=0.000\n >epoch=5631, lrate=0.005, error=0.000\n >epoch=5632, lrate=0.005, error=0.000\n >epoch=5633, lrate=0.005, error=0.000\n >epoch=5634, lrate=0.005, error=0.000\n >epoch=5635, lrate=0.005, error=0.000\n >epoch=5636, lrate=0.005, error=0.000\n >epoch=5637, lrate=0.005, error=0.000\n >epoch=5638, lrate=0.005, error=0.000\n >epoch=5639, lrate=0.005, error=0.000\n >epoch=5640, lrate=0.005, error=0.000\n >epoch=5641, lrate=0.005, error=0.000\n >epoch=5642, lrate=0.005, error=0.000\n >epoch=5643, lrate=0.005, error=0.000\n >epoch=5644, lrate=0.005, error=0.000\n >epoch=5645, lrate=0.005, error=0.000\n >epoch=5646, lrate=0.005, error=0.000\n >epoch=5647, lrate=0.005, error=0.000\n >epoch=5648, lrate=0.005, error=0.000\n >epoch=5649, lrate=0.005, error=0.000\n >epoch=5650, lrate=0.005, error=0.000\n >epoch=5651, lrate=0.005, error=0.000\n >epoch=5652, lrate=0.005, error=0.000\n >epoch=5653, lrate=0.005, error=0.000\n >epoch=5654, lrate=0.005, error=0.000\n >epoch=5655, lrate=0.005, error=0.000\n >epoch=5656, lrate=0.005, error=0.000\n >epoch=5657, lrate=0.005, error=0.000\n >epoch=5658, lrate=0.005, error=0.000\n >epoch=5659, lrate=0.005, error=0.000\n >epoch=5660, lrate=0.005, error=0.000\n >epoch=5661, lrate=0.005, error=0.000\n >epoch=5662, lrate=0.005, error=0.000\n >epoch=5663, lrate=0.005, error=0.000\n >epoch=5664, lrate=0.005, error=0.000\n >epoch=5665, lrate=0.005, error=0.000\n >epoch=5666, lrate=0.005, error=0.000\n >epoch=5667, lrate=0.005, error=0.000\n >epoch=5668, lrate=0.005, error=0.000\n >epoch=5669, lrate=0.005, error=0.000\n >epoch=5670, lrate=0.005, error=0.000\n >epoch=5671, lrate=0.005, error=0.000\n >epoch=5672, lrate=0.005, error=0.000\n >epoch=5673, lrate=0.005, error=0.000\n >epoch=5674, lrate=0.005, error=0.000\n >epoch=5675, lrate=0.005, error=0.000\n >epoch=5676, lrate=0.005, error=0.000\n >epoch=5677, lrate=0.005, error=0.000\n >epoch=5678, lrate=0.005, error=0.000\n >epoch=5679, lrate=0.005, error=0.000\n >epoch=5680, lrate=0.005, error=0.000\n >epoch=5681, lrate=0.005, error=0.000\n >epoch=5682, lrate=0.005, error=0.000\n >epoch=5683, lrate=0.005, error=0.000\n >epoch=5684, lrate=0.005, error=0.000\n >epoch=5685, lrate=0.005, error=0.000\n >epoch=5686, lrate=0.005, error=0.000\n >epoch=5687, lrate=0.005, error=0.000\n >epoch=5688, lrate=0.005, error=0.000\n >epoch=5689, lrate=0.005, error=0.000\n >epoch=5690, lrate=0.005, error=0.000\n >epoch=5691, lrate=0.005, error=0.000\n >epoch=5692, lrate=0.005, error=0.000\n >epoch=5693, lrate=0.005, error=0.000\n >epoch=5694, lrate=0.005, error=0.000\n >epoch=5695, lrate=0.005, error=0.000\n >epoch=5696, lrate=0.005, error=0.000\n >epoch=5697, lrate=0.005, error=0.000\n >epoch=5698, lrate=0.005, error=0.000\n >epoch=5699, lrate=0.005, error=0.000\n >epoch=5700, lrate=0.005, error=0.000\n >epoch=5701, lrate=0.005, error=0.000\n >epoch=5702, lrate=0.005, error=0.000\n >epoch=5703, lrate=0.005, error=0.000\n >epoch=5704, lrate=0.005, error=0.000\n >epoch=5705, lrate=0.005, error=0.000\n >epoch=5706, lrate=0.005, error=0.000\n >epoch=5707, lrate=0.005, error=0.000\n >epoch=5708, lrate=0.005, error=0.000\n >epoch=5709, lrate=0.005, error=0.000\n >epoch=5710, lrate=0.005, error=0.000\n >epoch=5711, lrate=0.005, error=0.000\n >epoch=5712, lrate=0.005, error=0.000\n >epoch=5713, lrate=0.005, error=0.000\n >epoch=5714, lrate=0.005, error=0.000\n >epoch=5715, lrate=0.005, error=0.000\n >epoch=5716, lrate=0.005, error=0.000\n >epoch=5717, lrate=0.005, error=0.000\n >epoch=5718, lrate=0.005, error=0.000\n >epoch=5719, lrate=0.005, error=0.000\n >epoch=5720, lrate=0.005, error=0.000\n >epoch=5721, lrate=0.005, error=0.000\n >epoch=5722, lrate=0.005, error=0.000\n >epoch=5723, lrate=0.005, error=0.000\n >epoch=5724, lrate=0.005, error=0.000\n >epoch=5725, lrate=0.005, error=0.000\n >epoch=5726, lrate=0.005, error=0.000\n >epoch=5727, lrate=0.005, error=0.000\n >epoch=5728, lrate=0.005, error=0.000\n >epoch=5729, lrate=0.005, error=0.000\n >epoch=5730, lrate=0.005, error=0.000\n >epoch=5731, lrate=0.005, error=0.000\n >epoch=5732, lrate=0.005, error=0.000\n >epoch=5733, lrate=0.005, error=0.000\n >epoch=5734, lrate=0.005, error=0.000\n >epoch=5735, lrate=0.005, error=0.000\n >epoch=5736, lrate=0.005, error=0.000\n >epoch=5737, lrate=0.005, error=0.000\n >epoch=5738, lrate=0.005, error=0.000\n >epoch=5739, lrate=0.005, error=0.000\n >epoch=5740, lrate=0.005, error=0.000\n >epoch=5741, lrate=0.005, error=0.000\n >epoch=5742, lrate=0.005, error=0.000\n >epoch=5743, lrate=0.005, error=0.000\n >epoch=5744, lrate=0.005, error=0.000\n >epoch=5745, lrate=0.005, error=0.000\n >epoch=5746, lrate=0.005, error=0.000\n >epoch=5747, lrate=0.005, error=0.000\n >epoch=5748, lrate=0.005, error=0.000\n >epoch=5749, lrate=0.005, error=0.000\n >epoch=5750, lrate=0.005, error=0.000\n >epoch=5751, lrate=0.005, error=0.000\n >epoch=5752, lrate=0.005, error=0.000\n >epoch=5753, lrate=0.005, error=0.000\n >epoch=5754, lrate=0.005, error=0.000\n >epoch=5755, lrate=0.005, error=0.000\n >epoch=5756, lrate=0.005, error=0.000\n >epoch=5757, lrate=0.005, error=0.000\n >epoch=5758, lrate=0.005, error=0.000\n >epoch=5759, lrate=0.005, error=0.000\n >epoch=5760, lrate=0.005, error=0.000\n >epoch=5761, lrate=0.005, error=0.000\n >epoch=5762, lrate=0.005, error=0.000\n >epoch=5763, lrate=0.005, error=0.000\n >epoch=5764, lrate=0.005, error=0.000\n >epoch=5765, lrate=0.005, error=0.000\n >epoch=5766, lrate=0.005, error=0.000\n >epoch=5767, lrate=0.005, error=0.000\n >epoch=5768, lrate=0.005, error=0.000\n >epoch=5769, lrate=0.005, error=0.000\n >epoch=5770, lrate=0.005, error=0.000\n >epoch=5771, lrate=0.005, error=0.000\n >epoch=5772, lrate=0.005, error=0.000\n >epoch=5773, lrate=0.005, error=0.000\n >epoch=5774, lrate=0.005, error=0.000\n >epoch=5775, lrate=0.005, error=0.000\n >epoch=5776, lrate=0.005, error=0.000\n >epoch=5777, lrate=0.005, error=0.000\n >epoch=5778, lrate=0.005, error=0.000\n >epoch=5779, lrate=0.005, error=0.000\n >epoch=5780, lrate=0.005, error=0.000\n >epoch=5781, lrate=0.005, error=0.000\n >epoch=5782, lrate=0.005, error=0.000\n >epoch=5783, lrate=0.005, error=0.000\n >epoch=5784, lrate=0.005, error=0.000\n >epoch=5785, lrate=0.005, error=0.000\n >epoch=5786, lrate=0.005, error=0.000\n >epoch=5787, lrate=0.005, error=0.000\n >epoch=5788, lrate=0.005, error=0.000\n >epoch=5789, lrate=0.005, error=0.000\n >epoch=5790, lrate=0.005, error=0.000\n >epoch=5791, lrate=0.005, error=0.000\n >epoch=5792, lrate=0.005, error=0.000\n >epoch=5793, lrate=0.005, error=0.000\n >epoch=5794, lrate=0.005, error=0.000\n >epoch=5795, lrate=0.005, error=0.000\n >epoch=5796, lrate=0.005, error=0.000\n >epoch=5797, lrate=0.005, error=0.000\n >epoch=5798, lrate=0.005, error=0.000\n >epoch=5799, lrate=0.005, error=0.000\n >epoch=5800, lrate=0.005, error=0.000\n >epoch=5801, lrate=0.005, error=0.000\n >epoch=5802, lrate=0.005, error=0.000\n >epoch=5803, lrate=0.005, error=0.000\n >epoch=5804, lrate=0.005, error=0.000\n >epoch=5805, lrate=0.005, error=0.000\n >epoch=5806, lrate=0.005, error=0.000\n >epoch=5807, lrate=0.005, error=0.000\n >epoch=5808, lrate=0.005, error=0.000\n >epoch=5809, lrate=0.005, error=0.000\n >epoch=5810, lrate=0.005, error=0.000\n >epoch=5811, lrate=0.005, error=0.000\n >epoch=5812, lrate=0.005, error=0.000\n >epoch=5813, lrate=0.005, error=0.000\n >epoch=5814, lrate=0.005, error=0.000\n >epoch=5815, lrate=0.005, error=0.000\n >epoch=5816, lrate=0.005, error=0.000\n >epoch=5817, lrate=0.005, error=0.000\n >epoch=5818, lrate=0.005, error=0.000\n >epoch=5819, lrate=0.005, error=0.000\n >epoch=5820, lrate=0.005, error=0.000\n >epoch=5821, lrate=0.005, error=0.000\n >epoch=5822, lrate=0.005, error=0.000\n >epoch=5823, lrate=0.005, error=0.000\n >epoch=5824, lrate=0.005, error=0.000\n >epoch=5825, lrate=0.005, error=0.000\n >epoch=5826, lrate=0.005, error=0.000\n >epoch=5827, lrate=0.005, error=0.000\n >epoch=5828, lrate=0.005, error=0.000\n >epoch=5829, lrate=0.005, error=0.000\n >epoch=5830, lrate=0.005, error=0.000\n >epoch=5831, lrate=0.005, error=0.000\n >epoch=5832, lrate=0.005, error=0.000\n >epoch=5833, lrate=0.005, error=0.000\n >epoch=5834, lrate=0.005, error=0.000\n >epoch=5835, lrate=0.005, error=0.000\n >epoch=5836, lrate=0.005, error=0.000\n >epoch=5837, lrate=0.005, error=0.000\n >epoch=5838, lrate=0.005, error=0.000\n >epoch=5839, lrate=0.005, error=0.000\n >epoch=5840, lrate=0.005, error=0.000\n >epoch=5841, lrate=0.005, error=0.000\n >epoch=5842, lrate=0.005, error=0.000\n >epoch=5843, lrate=0.005, error=0.000\n >epoch=5844, lrate=0.005, error=0.000\n >epoch=5845, lrate=0.005, error=0.000\n >epoch=5846, lrate=0.005, error=0.000\n >epoch=5847, lrate=0.005, error=0.000\n >epoch=5848, lrate=0.005, error=0.000\n >epoch=5849, lrate=0.005, error=0.000\n >epoch=5850, lrate=0.005, error=0.000\n >epoch=5851, lrate=0.005, error=0.000\n >epoch=5852, lrate=0.005, error=0.000\n >epoch=5853, lrate=0.005, error=0.000\n >epoch=5854, lrate=0.005, error=0.000\n >epoch=5855, lrate=0.005, error=0.000\n >epoch=5856, lrate=0.005, error=0.000\n >epoch=5857, lrate=0.005, error=0.000\n >epoch=5858, lrate=0.005, error=0.000\n >epoch=5859, lrate=0.005, error=0.000\n >epoch=5860, lrate=0.005, error=0.000\n >epoch=5861, lrate=0.005, error=0.000\n >epoch=5862, lrate=0.005, error=0.000\n >epoch=5863, lrate=0.005, error=0.000\n >epoch=5864, lrate=0.005, error=0.000\n >epoch=5865, lrate=0.005, error=0.000\n >epoch=5866, lrate=0.005, error=0.000\n >epoch=5867, lrate=0.005, error=0.000\n >epoch=5868, lrate=0.005, error=0.000\n >epoch=5869, lrate=0.005, error=0.000\n >epoch=5870, lrate=0.005, error=0.000\n >epoch=5871, lrate=0.005, error=0.000\n >epoch=5872, lrate=0.005, error=0.000\n >epoch=5873, lrate=0.005, error=0.000\n >epoch=5874, lrate=0.005, error=0.000\n >epoch=5875, lrate=0.005, error=0.000\n >epoch=5876, lrate=0.005, error=0.000\n >epoch=5877, lrate=0.005, error=0.000\n >epoch=5878, lrate=0.005, error=0.000\n >epoch=5879, lrate=0.005, error=0.000\n >epoch=5880, lrate=0.005, error=0.000\n >epoch=5881, lrate=0.005, error=0.000\n >epoch=5882, lrate=0.005, error=0.000\n >epoch=5883, lrate=0.005, error=0.000\n >epoch=5884, lrate=0.005, error=0.000\n >epoch=5885, lrate=0.005, error=0.000\n >epoch=5886, lrate=0.005, error=0.000\n >epoch=5887, lrate=0.005, error=0.000\n >epoch=5888, lrate=0.005, error=0.000\n >epoch=5889, lrate=0.005, error=0.000\n >epoch=5890, lrate=0.005, error=0.000\n >epoch=5891, lrate=0.005, error=0.000\n >epoch=5892, lrate=0.005, error=0.000\n >epoch=5893, lrate=0.005, error=0.000\n >epoch=5894, lrate=0.005, error=0.000\n >epoch=5895, lrate=0.005, error=0.000\n >epoch=5896, lrate=0.005, error=0.000\n >epoch=5897, lrate=0.005, error=0.000\n >epoch=5898, lrate=0.005, error=0.000\n >epoch=5899, lrate=0.005, error=0.000\n >epoch=5900, lrate=0.005, error=0.000\n >epoch=5901, lrate=0.005, error=0.000\n >epoch=5902, lrate=0.005, error=0.000\n >epoch=5903, lrate=0.005, error=0.000\n >epoch=5904, lrate=0.005, error=0.000\n >epoch=5905, lrate=0.005, error=0.000\n >epoch=5906, lrate=0.005, error=0.000\n >epoch=5907, lrate=0.005, error=0.000\n >epoch=5908, lrate=0.005, error=0.000\n >epoch=5909, lrate=0.005, error=0.000\n >epoch=5910, lrate=0.005, error=0.000\n >epoch=5911, lrate=0.005, error=0.000\n >epoch=5912, lrate=0.005, error=0.000\n >epoch=5913, lrate=0.005, error=0.000\n >epoch=5914, lrate=0.005, error=0.000\n >epoch=5915, lrate=0.005, error=0.000\n >epoch=5916, lrate=0.005, error=0.000\n >epoch=5917, lrate=0.005, error=0.000\n >epoch=5918, lrate=0.005, error=0.000\n >epoch=5919, lrate=0.005, error=0.000\n >epoch=5920, lrate=0.005, error=0.000\n >epoch=5921, lrate=0.005, error=0.000\n >epoch=5922, lrate=0.005, error=0.000\n >epoch=5923, lrate=0.005, error=0.000\n >epoch=5924, lrate=0.005, error=0.000\n >epoch=5925, lrate=0.005, error=0.000\n >epoch=5926, lrate=0.005, error=0.000\n >epoch=5927, lrate=0.005, error=0.000\n >epoch=5928, lrate=0.005, error=0.000\n >epoch=5929, lrate=0.005, error=0.000\n >epoch=5930, lrate=0.005, error=0.000\n >epoch=5931, lrate=0.005, error=0.000\n >epoch=5932, lrate=0.005, error=0.000\n >epoch=5933, lrate=0.005, error=0.000\n >epoch=5934, lrate=0.005, error=0.000\n >epoch=5935, lrate=0.005, error=0.000\n >epoch=5936, lrate=0.005, error=0.000\n >epoch=5937, lrate=0.005, error=0.000\n >epoch=5938, lrate=0.005, error=0.000\n >epoch=5939, lrate=0.005, error=0.000\n >epoch=5940, lrate=0.005, error=0.000\n >epoch=5941, lrate=0.005, error=0.000\n >epoch=5942, lrate=0.005, error=0.000\n >epoch=5943, lrate=0.005, error=0.000\n >epoch=5944, lrate=0.005, error=0.000\n >epoch=5945, lrate=0.005, error=0.000\n >epoch=5946, lrate=0.005, error=0.000\n >epoch=5947, lrate=0.005, error=0.000\n >epoch=5948, lrate=0.005, error=0.000\n >epoch=5949, lrate=0.005, error=0.000\n >epoch=5950, lrate=0.005, error=0.000\n >epoch=5951, lrate=0.005, error=0.000\n >epoch=5952, lrate=0.005, error=0.000\n >epoch=5953, lrate=0.005, error=0.000\n >epoch=5954, lrate=0.005, error=0.000\n >epoch=5955, lrate=0.005, error=0.000\n >epoch=5956, lrate=0.005, error=0.000\n >epoch=5957, lrate=0.005, error=0.000\n >epoch=5958, lrate=0.005, error=0.000\n >epoch=5959, lrate=0.005, error=0.000\n >epoch=5960, lrate=0.005, error=0.000\n >epoch=5961, lrate=0.005, error=0.000\n >epoch=5962, lrate=0.005, error=0.000\n >epoch=5963, lrate=0.005, error=0.000\n >epoch=5964, lrate=0.005, error=0.000\n >epoch=5965, lrate=0.005, error=0.000\n >epoch=5966, lrate=0.005, error=0.000\n >epoch=5967, lrate=0.005, error=0.000\n >epoch=5968, lrate=0.005, error=0.000\n >epoch=5969, lrate=0.005, error=0.000\n >epoch=5970, lrate=0.005, error=0.000\n >epoch=5971, lrate=0.005, error=0.000\n >epoch=5972, lrate=0.005, error=0.000\n >epoch=5973, lrate=0.005, error=0.000\n >epoch=5974, lrate=0.005, error=0.000\n >epoch=5975, lrate=0.005, error=0.000\n >epoch=5976, lrate=0.005, error=0.000\n >epoch=5977, lrate=0.005, error=0.000\n >epoch=5978, lrate=0.005, error=0.000\n >epoch=5979, lrate=0.005, error=0.000\n >epoch=5980, lrate=0.005, error=0.000\n >epoch=5981, lrate=0.005, error=0.000\n >epoch=5982, lrate=0.005, error=0.000\n >epoch=5983, lrate=0.005, error=0.000\n >epoch=5984, lrate=0.005, error=0.000\n >epoch=5985, lrate=0.005, error=0.000\n >epoch=5986, lrate=0.005, error=0.000\n >epoch=5987, lrate=0.005, error=0.000\n >epoch=5988, lrate=0.005, error=0.000\n >epoch=5989, lrate=0.005, error=0.000\n >epoch=5990, lrate=0.005, error=0.000\n >epoch=5991, lrate=0.005, error=0.000\n >epoch=5992, lrate=0.005, error=0.000\n >epoch=5993, lrate=0.005, error=0.000\n >epoch=5994, lrate=0.005, error=0.000\n >epoch=5995, lrate=0.005, error=0.000\n >epoch=5996, lrate=0.005, error=0.000\n >epoch=5997, lrate=0.005, error=0.000\n >epoch=5998, lrate=0.005, error=0.000\n >epoch=5999, lrate=0.005, error=0.000\n >epoch=6000, lrate=0.005, error=0.000\n >epoch=6001, lrate=0.005, error=0.000\n >epoch=6002, lrate=0.005, error=0.000\n >epoch=6003, lrate=0.005, error=0.000\n >epoch=6004, lrate=0.005, error=0.000\n >epoch=6005, lrate=0.005, error=0.000\n >epoch=6006, lrate=0.005, error=0.000\n >epoch=6007, lrate=0.005, error=0.000\n >epoch=6008, lrate=0.005, error=0.000\n >epoch=6009, lrate=0.005, error=0.000\n >epoch=6010, lrate=0.005, error=0.000\n >epoch=6011, lrate=0.005, error=0.000\n >epoch=6012, lrate=0.005, error=0.000\n >epoch=6013, lrate=0.005, error=0.000\n >epoch=6014, lrate=0.005, error=0.000\n >epoch=6015, lrate=0.005, error=0.000\n >epoch=6016, lrate=0.005, error=0.000\n >epoch=6017, lrate=0.005, error=0.000\n >epoch=6018, lrate=0.005, error=0.000\n >epoch=6019, lrate=0.005, error=0.000\n >epoch=6020, lrate=0.005, error=0.000\n >epoch=6021, lrate=0.005, error=0.000\n >epoch=6022, lrate=0.005, error=0.000\n >epoch=6023, lrate=0.005, error=0.000\n >epoch=6024, lrate=0.005, error=0.000\n >epoch=6025, lrate=0.005, error=0.000\n >epoch=6026, lrate=0.005, error=0.000\n >epoch=6027, lrate=0.005, error=0.000\n >epoch=6028, lrate=0.005, error=0.000\n >epoch=6029, lrate=0.005, error=0.000\n >epoch=6030, lrate=0.005, error=0.000\n >epoch=6031, lrate=0.005, error=0.000\n >epoch=6032, lrate=0.005, error=0.000\n >epoch=6033, lrate=0.005, error=0.000\n >epoch=6034, lrate=0.005, error=0.000\n >epoch=6035, lrate=0.005, error=0.000\n >epoch=6036, lrate=0.005, error=0.000\n >epoch=6037, lrate=0.005, error=0.000\n >epoch=6038, lrate=0.005, error=0.000\n >epoch=6039, lrate=0.005, error=0.000\n >epoch=6040, lrate=0.005, error=0.000\n >epoch=6041, lrate=0.005, error=0.000\n >epoch=6042, lrate=0.005, error=0.000\n >epoch=6043, lrate=0.005, error=0.000\n >epoch=6044, lrate=0.005, error=0.000\n >epoch=6045, lrate=0.005, error=0.000\n >epoch=6046, lrate=0.005, error=0.000\n >epoch=6047, lrate=0.005, error=0.000\n >epoch=6048, lrate=0.005, error=0.000\n >epoch=6049, lrate=0.005, error=0.000\n >epoch=6050, lrate=0.005, error=0.000\n >epoch=6051, lrate=0.005, error=0.000\n >epoch=6052, lrate=0.005, error=0.000\n >epoch=6053, lrate=0.005, error=0.000\n >epoch=6054, lrate=0.005, error=0.000\n >epoch=6055, lrate=0.005, error=0.000\n >epoch=6056, lrate=0.005, error=0.000\n >epoch=6057, lrate=0.005, error=0.000\n >epoch=6058, lrate=0.005, error=0.000\n >epoch=6059, lrate=0.005, error=0.000\n >epoch=6060, lrate=0.005, error=0.000\n >epoch=6061, lrate=0.005, error=0.000\n >epoch=6062, lrate=0.005, error=0.000\n >epoch=6063, lrate=0.005, error=0.000\n >epoch=6064, lrate=0.005, error=0.000\n >epoch=6065, lrate=0.005, error=0.000\n >epoch=6066, lrate=0.005, error=0.000\n >epoch=6067, lrate=0.005, error=0.000\n >epoch=6068, lrate=0.005, error=0.000\n >epoch=6069, lrate=0.005, error=0.000\n >epoch=6070, lrate=0.005, error=0.000\n >epoch=6071, lrate=0.005, error=0.000\n >epoch=6072, lrate=0.005, error=0.000\n >epoch=6073, lrate=0.005, error=0.000\n >epoch=6074, lrate=0.005, error=0.000\n >epoch=6075, lrate=0.005, error=0.000\n >epoch=6076, lrate=0.005, error=0.000\n >epoch=6077, lrate=0.005, error=0.000\n >epoch=6078, lrate=0.005, error=0.000\n >epoch=6079, lrate=0.005, error=0.000\n >epoch=6080, lrate=0.005, error=0.000\n >epoch=6081, lrate=0.005, error=0.000\n >epoch=6082, lrate=0.005, error=0.000\n >epoch=6083, lrate=0.005, error=0.000\n >epoch=6084, lrate=0.005, error=0.000\n >epoch=6085, lrate=0.005, error=0.000\n >epoch=6086, lrate=0.005, error=0.000\n >epoch=6087, lrate=0.005, error=0.000\n >epoch=6088, lrate=0.005, error=0.000\n >epoch=6089, lrate=0.005, error=0.000\n >epoch=6090, lrate=0.005, error=0.000\n >epoch=6091, lrate=0.005, error=0.000\n >epoch=6092, lrate=0.005, error=0.000\n >epoch=6093, lrate=0.005, error=0.000\n >epoch=6094, lrate=0.005, error=0.000\n >epoch=6095, lrate=0.005, error=0.000\n >epoch=6096, lrate=0.005, error=0.000\n >epoch=6097, lrate=0.005, error=0.000\n >epoch=6098, lrate=0.005, error=0.000\n >epoch=6099, lrate=0.005, error=0.000\n >epoch=6100, lrate=0.005, error=0.000\n >epoch=6101, lrate=0.005, error=0.000\n >epoch=6102, lrate=0.005, error=0.000\n >epoch=6103, lrate=0.005, error=0.000\n >epoch=6104, lrate=0.005, error=0.000\n >epoch=6105, lrate=0.005, error=0.000\n >epoch=6106, lrate=0.005, error=0.000\n >epoch=6107, lrate=0.005, error=0.000\n >epoch=6108, lrate=0.005, error=0.000\n >epoch=6109, lrate=0.005, error=0.000\n >epoch=6110, lrate=0.005, error=0.000\n >epoch=6111, lrate=0.005, error=0.000\n >epoch=6112, lrate=0.005, error=0.000\n >epoch=6113, lrate=0.005, error=0.000\n >epoch=6114, lrate=0.005, error=0.000\n >epoch=6115, lrate=0.005, error=0.000\n >epoch=6116, lrate=0.005, error=0.000\n >epoch=6117, lrate=0.005, error=0.000\n >epoch=6118, lrate=0.005, error=0.000\n >epoch=6119, lrate=0.005, error=0.000\n >epoch=6120, lrate=0.005, error=0.000\n >epoch=6121, lrate=0.005, error=0.000\n >epoch=6122, lrate=0.005, error=0.000\n >epoch=6123, lrate=0.005, error=0.000\n >epoch=6124, lrate=0.005, error=0.000\n >epoch=6125, lrate=0.005, error=0.000\n >epoch=6126, lrate=0.005, error=0.000\n >epoch=6127, lrate=0.005, error=0.000\n >epoch=6128, lrate=0.005, error=0.000\n >epoch=6129, lrate=0.005, error=0.000\n >epoch=6130, lrate=0.005, error=0.000\n >epoch=6131, lrate=0.005, error=0.000\n >epoch=6132, lrate=0.005, error=0.000\n >epoch=6133, lrate=0.005, error=0.000\n >epoch=6134, lrate=0.005, error=0.000\n >epoch=6135, lrate=0.005, error=0.000\n >epoch=6136, lrate=0.005, error=0.000\n >epoch=6137, lrate=0.005, error=0.000\n >epoch=6138, lrate=0.005, error=0.000\n >epoch=6139, lrate=0.005, error=0.000\n >epoch=6140, lrate=0.005, error=0.000\n >epoch=6141, lrate=0.005, error=0.000\n >epoch=6142, lrate=0.005, error=0.000\n >epoch=6143, lrate=0.005, error=0.000\n >epoch=6144, lrate=0.005, error=0.000\n >epoch=6145, lrate=0.005, error=0.000\n >epoch=6146, lrate=0.005, error=0.000\n >epoch=6147, lrate=0.005, error=0.000\n >epoch=6148, lrate=0.005, error=0.000\n >epoch=6149, lrate=0.005, error=0.000\n >epoch=6150, lrate=0.005, error=0.000\n >epoch=6151, lrate=0.005, error=0.000\n >epoch=6152, lrate=0.005, error=0.000\n >epoch=6153, lrate=0.005, error=0.000\n >epoch=6154, lrate=0.005, error=0.000\n >epoch=6155, lrate=0.005, error=0.000\n >epoch=6156, lrate=0.005, error=0.000\n >epoch=6157, lrate=0.005, error=0.000\n >epoch=6158, lrate=0.005, error=0.000\n >epoch=6159, lrate=0.005, error=0.000\n >epoch=6160, lrate=0.005, error=0.000\n >epoch=6161, lrate=0.005, error=0.000\n >epoch=6162, lrate=0.005, error=0.000\n >epoch=6163, lrate=0.005, error=0.000\n >epoch=6164, lrate=0.005, error=0.000\n >epoch=6165, lrate=0.005, error=0.000\n >epoch=6166, lrate=0.005, error=0.000\n >epoch=6167, lrate=0.005, error=0.000\n >epoch=6168, lrate=0.005, error=0.000\n >epoch=6169, lrate=0.005, error=0.000\n >epoch=6170, lrate=0.005, error=0.000\n >epoch=6171, lrate=0.005, error=0.000\n >epoch=6172, lrate=0.005, error=0.000\n >epoch=6173, lrate=0.005, error=0.000\n >epoch=6174, lrate=0.005, error=0.000\n >epoch=6175, lrate=0.005, error=0.000\n >epoch=6176, lrate=0.005, error=0.000\n >epoch=6177, lrate=0.005, error=0.000\n >epoch=6178, lrate=0.005, error=0.000\n >epoch=6179, lrate=0.005, error=0.000\n >epoch=6180, lrate=0.005, error=0.000\n >epoch=6181, lrate=0.005, error=0.000\n >epoch=6182, lrate=0.005, error=0.000\n >epoch=6183, lrate=0.005, error=0.000\n >epoch=6184, lrate=0.005, error=0.000\n >epoch=6185, lrate=0.005, error=0.000\n >epoch=6186, lrate=0.005, error=0.000\n >epoch=6187, lrate=0.005, error=0.000\n >epoch=6188, lrate=0.005, error=0.000\n >epoch=6189, lrate=0.005, error=0.000\n >epoch=6190, lrate=0.005, error=0.000\n >epoch=6191, lrate=0.005, error=0.000\n >epoch=6192, lrate=0.005, error=0.000\n >epoch=6193, lrate=0.005, error=0.000\n >epoch=6194, lrate=0.005, error=0.000\n >epoch=6195, lrate=0.005, error=0.000\n >epoch=6196, lrate=0.005, error=0.000\n >epoch=6197, lrate=0.005, error=0.000\n >epoch=6198, lrate=0.005, error=0.000\n >epoch=6199, lrate=0.005, error=0.000\n >epoch=6200, lrate=0.005, error=0.000\n >epoch=6201, lrate=0.005, error=0.000\n >epoch=6202, lrate=0.005, error=0.000\n >epoch=6203, lrate=0.005, error=0.000\n >epoch=6204, lrate=0.005, error=0.000\n >epoch=6205, lrate=0.005, error=0.000\n >epoch=6206, lrate=0.005, error=0.000\n >epoch=6207, lrate=0.005, error=0.000\n >epoch=6208, lrate=0.005, error=0.000\n >epoch=6209, lrate=0.005, error=0.000\n >epoch=6210, lrate=0.005, error=0.000\n >epoch=6211, lrate=0.005, error=0.000\n >epoch=6212, lrate=0.005, error=0.000\n >epoch=6213, lrate=0.005, error=0.000\n >epoch=6214, lrate=0.005, error=0.000\n >epoch=6215, lrate=0.005, error=0.000\n >epoch=6216, lrate=0.005, error=0.000\n >epoch=6217, lrate=0.005, error=0.000\n >epoch=6218, lrate=0.005, error=0.000\n >epoch=6219, lrate=0.005, error=0.000\n >epoch=6220, lrate=0.005, error=0.000\n >epoch=6221, lrate=0.005, error=0.000\n >epoch=6222, lrate=0.005, error=0.000\n >epoch=6223, lrate=0.005, error=0.000\n >epoch=6224, lrate=0.005, error=0.000\n >epoch=6225, lrate=0.005, error=0.000\n >epoch=6226, lrate=0.005, error=0.000\n >epoch=6227, lrate=0.005, error=0.000\n >epoch=6228, lrate=0.005, error=0.000\n >epoch=6229, lrate=0.005, error=0.000\n >epoch=6230, lrate=0.005, error=0.000\n >epoch=6231, lrate=0.005, error=0.000\n >epoch=6232, lrate=0.005, error=0.000\n >epoch=6233, lrate=0.005, error=0.000\n >epoch=6234, lrate=0.005, error=0.000\n >epoch=6235, lrate=0.005, error=0.000\n >epoch=6236, lrate=0.005, error=0.000\n >epoch=6237, lrate=0.005, error=0.000\n >epoch=6238, lrate=0.005, error=0.000\n >epoch=6239, lrate=0.005, error=0.000\n >epoch=6240, lrate=0.005, error=0.000\n >epoch=6241, lrate=0.005, error=0.000\n >epoch=6242, lrate=0.005, error=0.000\n >epoch=6243, lrate=0.005, error=0.000\n >epoch=6244, lrate=0.005, error=0.000\n >epoch=6245, lrate=0.005, error=0.000\n >epoch=6246, lrate=0.005, error=0.000\n >epoch=6247, lrate=0.005, error=0.000\n >epoch=6248, lrate=0.005, error=0.000\n >epoch=6249, lrate=0.005, error=0.000\n >epoch=6250, lrate=0.005, error=0.000\n >epoch=6251, lrate=0.005, error=0.000\n >epoch=6252, lrate=0.005, error=0.000\n >epoch=6253, lrate=0.005, error=0.000\n >epoch=6254, lrate=0.005, error=0.000\n >epoch=6255, lrate=0.005, error=0.000\n >epoch=6256, lrate=0.005, error=0.000\n >epoch=6257, lrate=0.005, error=0.000\n >epoch=6258, lrate=0.005, error=0.000\n >epoch=6259, lrate=0.005, error=0.000\n >epoch=6260, lrate=0.005, error=0.000\n >epoch=6261, lrate=0.005, error=0.000\n >epoch=6262, lrate=0.005, error=0.000\n >epoch=6263, lrate=0.005, error=0.000\n >epoch=6264, lrate=0.005, error=0.000\n >epoch=6265, lrate=0.005, error=0.000\n >epoch=6266, lrate=0.005, error=0.000\n >epoch=6267, lrate=0.005, error=0.000\n >epoch=6268, lrate=0.005, error=0.000\n >epoch=6269, lrate=0.005, error=0.000\n >epoch=6270, lrate=0.005, error=0.000\n >epoch=6271, lrate=0.005, error=0.000\n >epoch=6272, lrate=0.005, error=0.000\n >epoch=6273, lrate=0.005, error=0.000\n >epoch=6274, lrate=0.005, error=0.000\n >epoch=6275, lrate=0.005, error=0.000\n >epoch=6276, lrate=0.005, error=0.000\n >epoch=6277, lrate=0.005, error=0.000\n >epoch=6278, lrate=0.005, error=0.000\n >epoch=6279, lrate=0.005, error=0.000\n >epoch=6280, lrate=0.005, error=0.000\n >epoch=6281, lrate=0.005, error=0.000\n >epoch=6282, lrate=0.005, error=0.000\n >epoch=6283, lrate=0.005, error=0.000\n >epoch=6284, lrate=0.005, error=0.000\n >epoch=6285, lrate=0.005, error=0.000\n >epoch=6286, lrate=0.005, error=0.000\n >epoch=6287, lrate=0.005, error=0.000\n >epoch=6288, lrate=0.005, error=0.000\n >epoch=6289, lrate=0.005, error=0.000\n >epoch=6290, lrate=0.005, error=0.000\n >epoch=6291, lrate=0.005, error=0.000\n >epoch=6292, lrate=0.005, error=0.000\n >epoch=6293, lrate=0.005, error=0.000\n >epoch=6294, lrate=0.005, error=0.000\n >epoch=6295, lrate=0.005, error=0.000\n >epoch=6296, lrate=0.005, error=0.000\n >epoch=6297, lrate=0.005, error=0.000\n >epoch=6298, lrate=0.005, error=0.000\n >epoch=6299, lrate=0.005, error=0.000\n >epoch=6300, lrate=0.005, error=0.000\n >epoch=6301, lrate=0.005, error=0.000\n >epoch=6302, lrate=0.005, error=0.000\n >epoch=6303, lrate=0.005, error=0.000\n >epoch=6304, lrate=0.005, error=0.000\n >epoch=6305, lrate=0.005, error=0.000\n >epoch=6306, lrate=0.005, error=0.000\n >epoch=6307, lrate=0.005, error=0.000\n >epoch=6308, lrate=0.005, error=0.000\n >epoch=6309, lrate=0.005, error=0.000\n >epoch=6310, lrate=0.005, error=0.000\n >epoch=6311, lrate=0.005, error=0.000\n >epoch=6312, lrate=0.005, error=0.000\n >epoch=6313, lrate=0.005, error=0.000\n >epoch=6314, lrate=0.005, error=0.000\n >epoch=6315, lrate=0.005, error=0.000\n >epoch=6316, lrate=0.005, error=0.000\n >epoch=6317, lrate=0.005, error=0.000\n >epoch=6318, lrate=0.005, error=0.000\n >epoch=6319, lrate=0.005, error=0.000\n >epoch=6320, lrate=0.005, error=0.000\n >epoch=6321, lrate=0.005, error=0.000\n >epoch=6322, lrate=0.005, error=0.000\n >epoch=6323, lrate=0.005, error=0.000\n >epoch=6324, lrate=0.005, error=0.000\n >epoch=6325, lrate=0.005, error=0.000\n >epoch=6326, lrate=0.005, error=0.000\n >epoch=6327, lrate=0.005, error=0.000\n >epoch=6328, lrate=0.005, error=0.000\n >epoch=6329, lrate=0.005, error=0.000\n >epoch=6330, lrate=0.005, error=0.000\n >epoch=6331, lrate=0.005, error=0.000\n >epoch=6332, lrate=0.005, error=0.000\n >epoch=6333, lrate=0.005, error=0.000\n >epoch=6334, lrate=0.005, error=0.000\n >epoch=6335, lrate=0.005, error=0.000\n >epoch=6336, lrate=0.005, error=0.000\n >epoch=6337, lrate=0.005, error=0.000\n >epoch=6338, lrate=0.005, error=0.000\n >epoch=6339, lrate=0.005, error=0.000\n >epoch=6340, lrate=0.005, error=0.000\n >epoch=6341, lrate=0.005, error=0.000\n >epoch=6342, lrate=0.005, error=0.000\n >epoch=6343, lrate=0.005, error=0.000\n >epoch=6344, lrate=0.005, error=0.000\n >epoch=6345, lrate=0.005, error=0.000\n >epoch=6346, lrate=0.005, error=0.000\n >epoch=6347, lrate=0.005, error=0.000\n >epoch=6348, lrate=0.005, error=0.000\n >epoch=6349, lrate=0.005, error=0.000\n >epoch=6350, lrate=0.005, error=0.000\n >epoch=6351, lrate=0.005, error=0.000\n >epoch=6352, lrate=0.005, error=0.000\n >epoch=6353, lrate=0.005, error=0.000\n >epoch=6354, lrate=0.005, error=0.000\n >epoch=6355, lrate=0.005, error=0.000\n >epoch=6356, lrate=0.005, error=0.000\n >epoch=6357, lrate=0.005, error=0.000\n >epoch=6358, lrate=0.005, error=0.000\n >epoch=6359, lrate=0.005, error=0.000\n >epoch=6360, lrate=0.005, error=0.000\n >epoch=6361, lrate=0.005, error=0.000\n >epoch=6362, lrate=0.005, error=0.000\n >epoch=6363, lrate=0.005, error=0.000\n >epoch=6364, lrate=0.005, error=0.000\n >epoch=6365, lrate=0.005, error=0.000\n >epoch=6366, lrate=0.005, error=0.000\n >epoch=6367, lrate=0.005, error=0.000\n >epoch=6368, lrate=0.005, error=0.000\n >epoch=6369, lrate=0.005, error=0.000\n >epoch=6370, lrate=0.005, error=0.000\n >epoch=6371, lrate=0.005, error=0.000\n >epoch=6372, lrate=0.005, error=0.000\n >epoch=6373, lrate=0.005, error=0.000\n >epoch=6374, lrate=0.005, error=0.000\n >epoch=6375, lrate=0.005, error=0.000\n >epoch=6376, lrate=0.005, error=0.000\n >epoch=6377, lrate=0.005, error=0.000\n >epoch=6378, lrate=0.005, error=0.000\n >epoch=6379, lrate=0.005, error=0.000\n >epoch=6380, lrate=0.005, error=0.000\n >epoch=6381, lrate=0.005, error=0.000\n >epoch=6382, lrate=0.005, error=0.000\n >epoch=6383, lrate=0.005, error=0.000\n >epoch=6384, lrate=0.005, error=0.000\n >epoch=6385, lrate=0.005, error=0.000\n >epoch=6386, lrate=0.005, error=0.000\n >epoch=6387, lrate=0.005, error=0.000\n >epoch=6388, lrate=0.005, error=0.000\n >epoch=6389, lrate=0.005, error=0.000\n >epoch=6390, lrate=0.005, error=0.000\n >epoch=6391, lrate=0.005, error=0.000\n >epoch=6392, lrate=0.005, error=0.000\n >epoch=6393, lrate=0.005, error=0.000\n >epoch=6394, lrate=0.005, error=0.000\n >epoch=6395, lrate=0.005, error=0.000\n >epoch=6396, lrate=0.005, error=0.000\n >epoch=6397, lrate=0.005, error=0.000\n >epoch=6398, lrate=0.005, error=0.000\n >epoch=6399, lrate=0.005, error=0.000\n >epoch=6400, lrate=0.005, error=0.000\n >epoch=6401, lrate=0.005, error=0.000\n >epoch=6402, lrate=0.005, error=0.000\n >epoch=6403, lrate=0.005, error=0.000\n >epoch=6404, lrate=0.005, error=0.000\n >epoch=6405, lrate=0.005, error=0.000\n >epoch=6406, lrate=0.005, error=0.000\n >epoch=6407, lrate=0.005, error=0.000\n >epoch=6408, lrate=0.005, error=0.000\n >epoch=6409, lrate=0.005, error=0.000\n >epoch=6410, lrate=0.005, error=0.000\n >epoch=6411, lrate=0.005, error=0.000\n >epoch=6412, lrate=0.005, error=0.000\n >epoch=6413, lrate=0.005, error=0.000\n >epoch=6414, lrate=0.005, error=0.000\n >epoch=6415, lrate=0.005, error=0.000\n >epoch=6416, lrate=0.005, error=0.000\n >epoch=6417, lrate=0.005, error=0.000\n >epoch=6418, lrate=0.005, error=0.000\n >epoch=6419, lrate=0.005, error=0.000\n >epoch=6420, lrate=0.005, error=0.000\n >epoch=6421, lrate=0.005, error=0.000\n >epoch=6422, lrate=0.005, error=0.000\n >epoch=6423, lrate=0.005, error=0.000\n >epoch=6424, lrate=0.005, error=0.000\n >epoch=6425, lrate=0.005, error=0.000\n >epoch=6426, lrate=0.005, error=0.000\n >epoch=6427, lrate=0.005, error=0.000\n >epoch=6428, lrate=0.005, error=0.000\n >epoch=6429, lrate=0.005, error=0.000\n >epoch=6430, lrate=0.005, error=0.000\n >epoch=6431, lrate=0.005, error=0.000\n >epoch=6432, lrate=0.005, error=0.000\n >epoch=6433, lrate=0.005, error=0.000\n >epoch=6434, lrate=0.005, error=0.000\n >epoch=6435, lrate=0.005, error=0.000\n >epoch=6436, lrate=0.005, error=0.000\n >epoch=6437, lrate=0.005, error=0.000\n >epoch=6438, lrate=0.005, error=0.000\n >epoch=6439, lrate=0.005, error=0.000\n >epoch=6440, lrate=0.005, error=0.000\n >epoch=6441, lrate=0.005, error=0.000\n >epoch=6442, lrate=0.005, error=0.000\n >epoch=6443, lrate=0.005, error=0.000\n >epoch=6444, lrate=0.005, error=0.000\n >epoch=6445, lrate=0.005, error=0.000\n >epoch=6446, lrate=0.005, error=0.000\n >epoch=6447, lrate=0.005, error=0.000\n >epoch=6448, lrate=0.005, error=0.000\n >epoch=6449, lrate=0.005, error=0.000\n >epoch=6450, lrate=0.005, error=0.000\n >epoch=6451, lrate=0.005, error=0.000\n >epoch=6452, lrate=0.005, error=0.000\n >epoch=6453, lrate=0.005, error=0.000\n >epoch=6454, lrate=0.005, error=0.000\n >epoch=6455, lrate=0.005, error=0.000\n >epoch=6456, lrate=0.005, error=0.000\n >epoch=6457, lrate=0.005, error=0.000\n >epoch=6458, lrate=0.005, error=0.000\n >epoch=6459, lrate=0.005, error=0.000\n >epoch=6460, lrate=0.005, error=0.000\n >epoch=6461, lrate=0.005, error=0.000\n >epoch=6462, lrate=0.005, error=0.000\n >epoch=6463, lrate=0.005, error=0.000\n >epoch=6464, lrate=0.005, error=0.000\n >epoch=6465, lrate=0.005, error=0.000\n >epoch=6466, lrate=0.005, error=0.000\n >epoch=6467, lrate=0.005, error=0.000\n >epoch=6468, lrate=0.005, error=0.000\n >epoch=6469, lrate=0.005, error=0.000\n >epoch=6470, lrate=0.005, error=0.000\n >epoch=6471, lrate=0.005, error=0.000\n >epoch=6472, lrate=0.005, error=0.000\n >epoch=6473, lrate=0.005, error=0.000\n >epoch=6474, lrate=0.005, error=0.000\n >epoch=6475, lrate=0.005, error=0.000\n >epoch=6476, lrate=0.005, error=0.000\n >epoch=6477, lrate=0.005, error=0.000\n >epoch=6478, lrate=0.005, error=0.000\n >epoch=6479, lrate=0.005, error=0.000\n >epoch=6480, lrate=0.005, error=0.000\n >epoch=6481, lrate=0.005, error=0.000\n >epoch=6482, lrate=0.005, error=0.000\n >epoch=6483, lrate=0.005, error=0.000\n >epoch=6484, lrate=0.005, error=0.000\n >epoch=6485, lrate=0.005, error=0.000\n >epoch=6486, lrate=0.005, error=0.000\n >epoch=6487, lrate=0.005, error=0.000\n >epoch=6488, lrate=0.005, error=0.000\n >epoch=6489, lrate=0.005, error=0.000\n >epoch=6490, lrate=0.005, error=0.000\n >epoch=6491, lrate=0.005, error=0.000\n >epoch=6492, lrate=0.005, error=0.000\n >epoch=6493, lrate=0.005, error=0.000\n >epoch=6494, lrate=0.005, error=0.000\n >epoch=6495, lrate=0.005, error=0.000\n >epoch=6496, lrate=0.005, error=0.000\n >epoch=6497, lrate=0.005, error=0.000\n >epoch=6498, lrate=0.005, error=0.000\n >epoch=6499, lrate=0.005, error=0.000\n >epoch=6500, lrate=0.005, error=0.000\n >epoch=6501, lrate=0.005, error=0.000\n >epoch=6502, lrate=0.005, error=0.000\n >epoch=6503, lrate=0.005, error=0.000\n >epoch=6504, lrate=0.005, error=0.000\n >epoch=6505, lrate=0.005, error=0.000\n >epoch=6506, lrate=0.005, error=0.000\n >epoch=6507, lrate=0.005, error=0.000\n >epoch=6508, lrate=0.005, error=0.000\n >epoch=6509, lrate=0.005, error=0.000\n >epoch=6510, lrate=0.005, error=0.000\n >epoch=6511, lrate=0.005, error=0.000\n >epoch=6512, lrate=0.005, error=0.000\n >epoch=6513, lrate=0.005, error=0.000\n >epoch=6514, lrate=0.005, error=0.000\n >epoch=6515, lrate=0.005, error=0.000\n >epoch=6516, lrate=0.005, error=0.000\n >epoch=6517, lrate=0.005, error=0.000\n >epoch=6518, lrate=0.005, error=0.000\n >epoch=6519, lrate=0.005, error=0.000\n >epoch=6520, lrate=0.005, error=0.000\n >epoch=6521, lrate=0.005, error=0.000\n >epoch=6522, lrate=0.005, error=0.000\n >epoch=6523, lrate=0.005, error=0.000\n >epoch=6524, lrate=0.005, error=0.000\n >epoch=6525, lrate=0.005, error=0.000\n >epoch=6526, lrate=0.005, error=0.000\n >epoch=6527, lrate=0.005, error=0.000\n >epoch=6528, lrate=0.005, error=0.000\n >epoch=6529, lrate=0.005, error=0.000\n >epoch=6530, lrate=0.005, error=0.000\n >epoch=6531, lrate=0.005, error=0.000\n >epoch=6532, lrate=0.005, error=0.000\n >epoch=6533, lrate=0.005, error=0.000\n >epoch=6534, lrate=0.005, error=0.000\n >epoch=6535, lrate=0.005, error=0.000\n >epoch=6536, lrate=0.005, error=0.000\n >epoch=6537, lrate=0.005, error=0.000\n >epoch=6538, lrate=0.005, error=0.000\n >epoch=6539, lrate=0.005, error=0.000\n >epoch=6540, lrate=0.005, error=0.000\n >epoch=6541, lrate=0.005, error=0.000\n >epoch=6542, lrate=0.005, error=0.000\n >epoch=6543, lrate=0.005, error=0.000\n >epoch=6544, lrate=0.005, error=0.000\n >epoch=6545, lrate=0.005, error=0.000\n >epoch=6546, lrate=0.005, error=0.000\n >epoch=6547, lrate=0.005, error=0.000\n >epoch=6548, lrate=0.005, error=0.000\n >epoch=6549, lrate=0.005, error=0.000\n >epoch=6550, lrate=0.005, error=0.000\n >epoch=6551, lrate=0.005, error=0.000\n >epoch=6552, lrate=0.005, error=0.000\n >epoch=6553, lrate=0.005, error=0.000\n >epoch=6554, lrate=0.005, error=0.000\n >epoch=6555, lrate=0.005, error=0.000\n >epoch=6556, lrate=0.005, error=0.000\n >epoch=6557, lrate=0.005, error=0.000\n >epoch=6558, lrate=0.005, error=0.000\n >epoch=6559, lrate=0.005, error=0.000\n >epoch=6560, lrate=0.005, error=0.000\n >epoch=6561, lrate=0.005, error=0.000\n >epoch=6562, lrate=0.005, error=0.000\n >epoch=6563, lrate=0.005, error=0.000\n >epoch=6564, lrate=0.005, error=0.000\n >epoch=6565, lrate=0.005, error=0.000\n >epoch=6566, lrate=0.005, error=0.000\n >epoch=6567, lrate=0.005, error=0.000\n >epoch=6568, lrate=0.005, error=0.000\n >epoch=6569, lrate=0.005, error=0.000\n >epoch=6570, lrate=0.005, error=0.000\n >epoch=6571, lrate=0.005, error=0.000\n >epoch=6572, lrate=0.005, error=0.000\n >epoch=6573, lrate=0.005, error=0.000\n >epoch=6574, lrate=0.005, error=0.000\n >epoch=6575, lrate=0.005, error=0.000\n >epoch=6576, lrate=0.005, error=0.000\n >epoch=6577, lrate=0.005, error=0.000\n >epoch=6578, lrate=0.005, error=0.000\n >epoch=6579, lrate=0.005, error=0.000\n >epoch=6580, lrate=0.005, error=0.000\n >epoch=6581, lrate=0.005, error=0.000\n >epoch=6582, lrate=0.005, error=0.000\n >epoch=6583, lrate=0.005, error=0.000\n >epoch=6584, lrate=0.005, error=0.000\n >epoch=6585, lrate=0.005, error=0.000\n >epoch=6586, lrate=0.005, error=0.000\n >epoch=6587, lrate=0.005, error=0.000\n >epoch=6588, lrate=0.005, error=0.000\n >epoch=6589, lrate=0.005, error=0.000\n >epoch=6590, lrate=0.005, error=0.000\n >epoch=6591, lrate=0.005, error=0.000\n >epoch=6592, lrate=0.005, error=0.000\n >epoch=6593, lrate=0.005, error=0.000\n >epoch=6594, lrate=0.005, error=0.000\n >epoch=6595, lrate=0.005, error=0.000\n >epoch=6596, lrate=0.005, error=0.000\n >epoch=6597, lrate=0.005, error=0.000\n >epoch=6598, lrate=0.005, error=0.000\n >epoch=6599, lrate=0.005, error=0.000\n >epoch=6600, lrate=0.005, error=0.000\n >epoch=6601, lrate=0.005, error=0.000\n >epoch=6602, lrate=0.005, error=0.000\n >epoch=6603, lrate=0.005, error=0.000\n >epoch=6604, lrate=0.005, error=0.000\n >epoch=6605, lrate=0.005, error=0.000\n >epoch=6606, lrate=0.005, error=0.000\n >epoch=6607, lrate=0.005, error=0.000\n >epoch=6608, lrate=0.005, error=0.000\n >epoch=6609, lrate=0.005, error=0.000\n >epoch=6610, lrate=0.005, error=0.000\n >epoch=6611, lrate=0.005, error=0.000\n >epoch=6612, lrate=0.005, error=0.000\n >epoch=6613, lrate=0.005, error=0.000\n >epoch=6614, lrate=0.005, error=0.000\n >epoch=6615, lrate=0.005, error=0.000\n >epoch=6616, lrate=0.005, error=0.000\n >epoch=6617, lrate=0.005, error=0.000\n >epoch=6618, lrate=0.005, error=0.000\n >epoch=6619, lrate=0.005, error=0.000\n >epoch=6620, lrate=0.005, error=0.000\n >epoch=6621, lrate=0.005, error=0.000\n >epoch=6622, lrate=0.005, error=0.000\n >epoch=6623, lrate=0.005, error=0.000\n >epoch=6624, lrate=0.005, error=0.000\n >epoch=6625, lrate=0.005, error=0.000\n >epoch=6626, lrate=0.005, error=0.000\n >epoch=6627, lrate=0.005, error=0.000\n >epoch=6628, lrate=0.005, error=0.000\n >epoch=6629, lrate=0.005, error=0.000\n >epoch=6630, lrate=0.005, error=0.000\n >epoch=6631, lrate=0.005, error=0.000\n >epoch=6632, lrate=0.005, error=0.000\n >epoch=6633, lrate=0.005, error=0.000\n >epoch=6634, lrate=0.005, error=0.000\n >epoch=6635, lrate=0.005, error=0.000\n >epoch=6636, lrate=0.005, error=0.000\n >epoch=6637, lrate=0.005, error=0.000\n >epoch=6638, lrate=0.005, error=0.000\n >epoch=6639, lrate=0.005, error=0.000\n >epoch=6640, lrate=0.005, error=0.000\n >epoch=6641, lrate=0.005, error=0.000\n >epoch=6642, lrate=0.005, error=0.000\n >epoch=6643, lrate=0.005, error=0.000\n >epoch=6644, lrate=0.005, error=0.000\n >epoch=6645, lrate=0.005, error=0.000\n >epoch=6646, lrate=0.005, error=0.000\n >epoch=6647, lrate=0.005, error=0.000\n >epoch=6648, lrate=0.005, error=0.000\n >epoch=6649, lrate=0.005, error=0.000\n >epoch=6650, lrate=0.005, error=0.000\n >epoch=6651, lrate=0.005, error=0.000\n >epoch=6652, lrate=0.005, error=0.000\n >epoch=6653, lrate=0.005, error=0.000\n >epoch=6654, lrate=0.005, error=0.000\n >epoch=6655, lrate=0.005, error=0.000\n >epoch=6656, lrate=0.005, error=0.000\n >epoch=6657, lrate=0.005, error=0.000\n >epoch=6658, lrate=0.005, error=0.000\n >epoch=6659, lrate=0.005, error=0.000\n >epoch=6660, lrate=0.005, error=0.000\n >epoch=6661, lrate=0.005, error=0.000\n >epoch=6662, lrate=0.005, error=0.000\n >epoch=6663, lrate=0.005, error=0.000\n >epoch=6664, lrate=0.005, error=0.000\n >epoch=6665, lrate=0.005, error=0.000\n >epoch=6666, lrate=0.005, error=0.000\n >epoch=6667, lrate=0.005, error=0.000\n >epoch=6668, lrate=0.005, error=0.000\n >epoch=6669, lrate=0.005, error=0.000\n >epoch=6670, lrate=0.005, error=0.000\n >epoch=6671, lrate=0.005, error=0.000\n >epoch=6672, lrate=0.005, error=0.000\n >epoch=6673, lrate=0.005, error=0.000\n >epoch=6674, lrate=0.005, error=0.000\n >epoch=6675, lrate=0.005, error=0.000\n >epoch=6676, lrate=0.005, error=0.000\n >epoch=6677, lrate=0.005, error=0.000\n >epoch=6678, lrate=0.005, error=0.000\n >epoch=6679, lrate=0.005, error=0.000\n >epoch=6680, lrate=0.005, error=0.000\n >epoch=6681, lrate=0.005, error=0.000\n >epoch=6682, lrate=0.005, error=0.000\n >epoch=6683, lrate=0.005, error=0.000\n >epoch=6684, lrate=0.005, error=0.000\n >epoch=6685, lrate=0.005, error=0.000\n >epoch=6686, lrate=0.005, error=0.000\n >epoch=6687, lrate=0.005, error=0.000\n >epoch=6688, lrate=0.005, error=0.000\n >epoch=6689, lrate=0.005, error=0.000\n >epoch=6690, lrate=0.005, error=0.000\n >epoch=6691, lrate=0.005, error=0.000\n >epoch=6692, lrate=0.005, error=0.000\n >epoch=6693, lrate=0.005, error=0.000\n >epoch=6694, lrate=0.005, error=0.000\n >epoch=6695, lrate=0.005, error=0.000\n >epoch=6696, lrate=0.005, error=0.000\n >epoch=6697, lrate=0.005, error=0.000\n >epoch=6698, lrate=0.005, error=0.000\n >epoch=6699, lrate=0.005, error=0.000\n >epoch=6700, lrate=0.005, error=0.000\n >epoch=6701, lrate=0.005, error=0.000\n >epoch=6702, lrate=0.005, error=0.000\n >epoch=6703, lrate=0.005, error=0.000\n >epoch=6704, lrate=0.005, error=0.000\n >epoch=6705, lrate=0.005, error=0.000\n >epoch=6706, lrate=0.005, error=0.000\n >epoch=6707, lrate=0.005, error=0.000\n >epoch=6708, lrate=0.005, error=0.000\n >epoch=6709, lrate=0.005, error=0.000\n >epoch=6710, lrate=0.005, error=0.000\n >epoch=6711, lrate=0.005, error=0.000\n >epoch=6712, lrate=0.005, error=0.000\n >epoch=6713, lrate=0.005, error=0.000\n >epoch=6714, lrate=0.005, error=0.000\n >epoch=6715, lrate=0.005, error=0.000\n >epoch=6716, lrate=0.005, error=0.000\n >epoch=6717, lrate=0.005, error=0.000\n >epoch=6718, lrate=0.005, error=0.000\n >epoch=6719, lrate=0.005, error=0.000\n >epoch=6720, lrate=0.005, error=0.000\n >epoch=6721, lrate=0.005, error=0.000\n >epoch=6722, lrate=0.005, error=0.000\n >epoch=6723, lrate=0.005, error=0.000\n >epoch=6724, lrate=0.005, error=0.000\n >epoch=6725, lrate=0.005, error=0.000\n >epoch=6726, lrate=0.005, error=0.000\n >epoch=6727, lrate=0.005, error=0.000\n >epoch=6728, lrate=0.005, error=0.000\n >epoch=6729, lrate=0.005, error=0.000\n >epoch=6730, lrate=0.005, error=0.000\n >epoch=6731, lrate=0.005, error=0.000\n >epoch=6732, lrate=0.005, error=0.000\n >epoch=6733, lrate=0.005, error=0.000\n >epoch=6734, lrate=0.005, error=0.000\n >epoch=6735, lrate=0.005, error=0.000\n >epoch=6736, lrate=0.005, error=0.000\n >epoch=6737, lrate=0.005, error=0.000\n >epoch=6738, lrate=0.005, error=0.000\n >epoch=6739, lrate=0.005, error=0.000\n >epoch=6740, lrate=0.005, error=0.000\n >epoch=6741, lrate=0.005, error=0.000\n >epoch=6742, lrate=0.005, error=0.000\n >epoch=6743, lrate=0.005, error=0.000\n >epoch=6744, lrate=0.005, error=0.000\n >epoch=6745, lrate=0.005, error=0.000\n >epoch=6746, lrate=0.005, error=0.000\n >epoch=6747, lrate=0.005, error=0.000\n >epoch=6748, lrate=0.005, error=0.000\n >epoch=6749, lrate=0.005, error=0.000\n >epoch=6750, lrate=0.005, error=0.000\n >epoch=6751, lrate=0.005, error=0.000\n >epoch=6752, lrate=0.005, error=0.000\n >epoch=6753, lrate=0.005, error=0.000\n >epoch=6754, lrate=0.005, error=0.000\n >epoch=6755, lrate=0.005, error=0.000\n >epoch=6756, lrate=0.005, error=0.000\n >epoch=6757, lrate=0.005, error=0.000\n >epoch=6758, lrate=0.005, error=0.000\n >epoch=6759, lrate=0.005, error=0.000\n >epoch=6760, lrate=0.005, error=0.000\n >epoch=6761, lrate=0.005, error=0.000\n >epoch=6762, lrate=0.005, error=0.000\n >epoch=6763, lrate=0.005, error=0.000\n >epoch=6764, lrate=0.005, error=0.000\n >epoch=6765, lrate=0.005, error=0.000\n >epoch=6766, lrate=0.005, error=0.000\n >epoch=6767, lrate=0.005, error=0.000\n >epoch=6768, lrate=0.005, error=0.000\n >epoch=6769, lrate=0.005, error=0.000\n >epoch=6770, lrate=0.005, error=0.000\n >epoch=6771, lrate=0.005, error=0.000\n >epoch=6772, lrate=0.005, error=0.000\n >epoch=6773, lrate=0.005, error=0.000\n >epoch=6774, lrate=0.005, error=0.000\n >epoch=6775, lrate=0.005, error=0.000\n >epoch=6776, lrate=0.005, error=0.000\n >epoch=6777, lrate=0.005, error=0.000\n >epoch=6778, lrate=0.005, error=0.000\n >epoch=6779, lrate=0.005, error=0.000\n >epoch=6780, lrate=0.005, error=0.000\n >epoch=6781, lrate=0.005, error=0.000\n >epoch=6782, lrate=0.005, error=0.000\n >epoch=6783, lrate=0.005, error=0.000\n >epoch=6784, lrate=0.005, error=0.000\n >epoch=6785, lrate=0.005, error=0.000\n >epoch=6786, lrate=0.005, error=0.000\n >epoch=6787, lrate=0.005, error=0.000\n >epoch=6788, lrate=0.005, error=0.000\n >epoch=6789, lrate=0.005, error=0.000\n >epoch=6790, lrate=0.005, error=0.000\n >epoch=6791, lrate=0.005, error=0.000\n >epoch=6792, lrate=0.005, error=0.000\n >epoch=6793, lrate=0.005, error=0.000\n >epoch=6794, lrate=0.005, error=0.000\n >epoch=6795, lrate=0.005, error=0.000\n >epoch=6796, lrate=0.005, error=0.000\n >epoch=6797, lrate=0.005, error=0.000\n >epoch=6798, lrate=0.005, error=0.000\n >epoch=6799, lrate=0.005, error=0.000\n >epoch=6800, lrate=0.005, error=0.000\n >epoch=6801, lrate=0.005, error=0.000\n >epoch=6802, lrate=0.005, error=0.000\n >epoch=6803, lrate=0.005, error=0.000\n >epoch=6804, lrate=0.005, error=0.000\n >epoch=6805, lrate=0.005, error=0.000\n >epoch=6806, lrate=0.005, error=0.000\n >epoch=6807, lrate=0.005, error=0.000\n >epoch=6808, lrate=0.005, error=0.000\n >epoch=6809, lrate=0.005, error=0.000\n >epoch=6810, lrate=0.005, error=0.000\n >epoch=6811, lrate=0.005, error=0.000\n >epoch=6812, lrate=0.005, error=0.000\n >epoch=6813, lrate=0.005, error=0.000\n >epoch=6814, lrate=0.005, error=0.000\n >epoch=6815, lrate=0.005, error=0.000\n >epoch=6816, lrate=0.005, error=0.000\n >epoch=6817, lrate=0.005, error=0.000\n >epoch=6818, lrate=0.005, error=0.000\n >epoch=6819, lrate=0.005, error=0.000\n >epoch=6820, lrate=0.005, error=0.000\n >epoch=6821, lrate=0.005, error=0.000\n >epoch=6822, lrate=0.005, error=0.000\n >epoch=6823, lrate=0.005, error=0.000\n >epoch=6824, lrate=0.005, error=0.000\n >epoch=6825, lrate=0.005, error=0.000\n >epoch=6826, lrate=0.005, error=0.000\n >epoch=6827, lrate=0.005, error=0.000\n >epoch=6828, lrate=0.005, error=0.000\n >epoch=6829, lrate=0.005, error=0.000\n >epoch=6830, lrate=0.005, error=0.000\n >epoch=6831, lrate=0.005, error=0.000\n >epoch=6832, lrate=0.005, error=0.000\n >epoch=6833, lrate=0.005, error=0.000\n >epoch=6834, lrate=0.005, error=0.000\n >epoch=6835, lrate=0.005, error=0.000\n >epoch=6836, lrate=0.005, error=0.000\n >epoch=6837, lrate=0.005, error=0.000\n >epoch=6838, lrate=0.005, error=0.000\n >epoch=6839, lrate=0.005, error=0.000\n >epoch=6840, lrate=0.005, error=0.000\n >epoch=6841, lrate=0.005, error=0.000\n >epoch=6842, lrate=0.005, error=0.000\n >epoch=6843, lrate=0.005, error=0.000\n >epoch=6844, lrate=0.005, error=0.000\n >epoch=6845, lrate=0.005, error=0.000\n >epoch=6846, lrate=0.005, error=0.000\n >epoch=6847, lrate=0.005, error=0.000\n >epoch=6848, lrate=0.005, error=0.000\n >epoch=6849, lrate=0.005, error=0.000\n >epoch=6850, lrate=0.005, error=0.000\n >epoch=6851, lrate=0.005, error=0.000\n >epoch=6852, lrate=0.005, error=0.000\n >epoch=6853, lrate=0.005, error=0.000\n >epoch=6854, lrate=0.005, error=0.000\n >epoch=6855, lrate=0.005, error=0.000\n >epoch=6856, lrate=0.005, error=0.000\n >epoch=6857, lrate=0.005, error=0.000\n >epoch=6858, lrate=0.005, error=0.000\n >epoch=6859, lrate=0.005, error=0.000\n >epoch=6860, lrate=0.005, error=0.000\n >epoch=6861, lrate=0.005, error=0.000\n >epoch=6862, lrate=0.005, error=0.000\n >epoch=6863, lrate=0.005, error=0.000\n >epoch=6864, lrate=0.005, error=0.000\n >epoch=6865, lrate=0.005, error=0.000\n >epoch=6866, lrate=0.005, error=0.000\n >epoch=6867, lrate=0.005, error=0.000\n >epoch=6868, lrate=0.005, error=0.000\n >epoch=6869, lrate=0.005, error=0.000\n >epoch=6870, lrate=0.005, error=0.000\n >epoch=6871, lrate=0.005, error=0.000\n >epoch=6872, lrate=0.005, error=0.000\n >epoch=6873, lrate=0.005, error=0.000\n >epoch=6874, lrate=0.005, error=0.000\n >epoch=6875, lrate=0.005, error=0.000\n >epoch=6876, lrate=0.005, error=0.000\n >epoch=6877, lrate=0.005, error=0.000\n >epoch=6878, lrate=0.005, error=0.000\n >epoch=6879, lrate=0.005, error=0.000\n >epoch=6880, lrate=0.005, error=0.000\n >epoch=6881, lrate=0.005, error=0.000\n >epoch=6882, lrate=0.005, error=0.000\n >epoch=6883, lrate=0.005, error=0.000\n >epoch=6884, lrate=0.005, error=0.000\n >epoch=6885, lrate=0.005, error=0.000\n >epoch=6886, lrate=0.005, error=0.000\n >epoch=6887, lrate=0.005, error=0.000\n >epoch=6888, lrate=0.005, error=0.000\n >epoch=6889, lrate=0.005, error=0.000\n >epoch=6890, lrate=0.005, error=0.000\n >epoch=6891, lrate=0.005, error=0.000\n >epoch=6892, lrate=0.005, error=0.000\n >epoch=6893, lrate=0.005, error=0.000\n >epoch=6894, lrate=0.005, error=0.000\n >epoch=6895, lrate=0.005, error=0.000\n >epoch=6896, lrate=0.005, error=0.000\n >epoch=6897, lrate=0.005, error=0.000\n >epoch=6898, lrate=0.005, error=0.000\n >epoch=6899, lrate=0.005, error=0.000\n >epoch=6900, lrate=0.005, error=0.000\n >epoch=6901, lrate=0.005, error=0.000\n >epoch=6902, lrate=0.005, error=0.000\n >epoch=6903, lrate=0.005, error=0.000\n >epoch=6904, lrate=0.005, error=0.000\n >epoch=6905, lrate=0.005, error=0.000\n >epoch=6906, lrate=0.005, error=0.000\n >epoch=6907, lrate=0.005, error=0.000\n >epoch=6908, lrate=0.005, error=0.000\n >epoch=6909, lrate=0.005, error=0.000\n >epoch=6910, lrate=0.005, error=0.000\n >epoch=6911, lrate=0.005, error=0.000\n >epoch=6912, lrate=0.005, error=0.000\n >epoch=6913, lrate=0.005, error=0.000\n >epoch=6914, lrate=0.005, error=0.000\n >epoch=6915, lrate=0.005, error=0.000\n >epoch=6916, lrate=0.005, error=0.000\n >epoch=6917, lrate=0.005, error=0.000\n >epoch=6918, lrate=0.005, error=0.000\n >epoch=6919, lrate=0.005, error=0.000\n >epoch=6920, lrate=0.005, error=0.000\n >epoch=6921, lrate=0.005, error=0.000\n >epoch=6922, lrate=0.005, error=0.000\n >epoch=6923, lrate=0.005, error=0.000\n >epoch=6924, lrate=0.005, error=0.000\n >epoch=6925, lrate=0.005, error=0.000\n >epoch=6926, lrate=0.005, error=0.000\n >epoch=6927, lrate=0.005, error=0.000\n >epoch=6928, lrate=0.005, error=0.000\n >epoch=6929, lrate=0.005, error=0.000\n >epoch=6930, lrate=0.005, error=0.000\n >epoch=6931, lrate=0.005, error=0.000\n >epoch=6932, lrate=0.005, error=0.000\n >epoch=6933, lrate=0.005, error=0.000\n >epoch=6934, lrate=0.005, error=0.000\n >epoch=6935, lrate=0.005, error=0.000\n >epoch=6936, lrate=0.005, error=0.000\n >epoch=6937, lrate=0.005, error=0.000\n >epoch=6938, lrate=0.005, error=0.000\n >epoch=6939, lrate=0.005, error=0.000\n >epoch=6940, lrate=0.005, error=0.000\n >epoch=6941, lrate=0.005, error=0.000\n >epoch=6942, lrate=0.005, error=0.000\n >epoch=6943, lrate=0.005, error=0.000\n >epoch=6944, lrate=0.005, error=0.000\n >epoch=6945, lrate=0.005, error=0.000\n >epoch=6946, lrate=0.005, error=0.000\n >epoch=6947, lrate=0.005, error=0.000\n >epoch=6948, lrate=0.005, error=0.000\n >epoch=6949, lrate=0.005, error=0.000\n >epoch=6950, lrate=0.005, error=0.000\n >epoch=6951, lrate=0.005, error=0.000\n >epoch=6952, lrate=0.005, error=0.000\n >epoch=6953, lrate=0.005, error=0.000\n >epoch=6954, lrate=0.005, error=0.000\n >epoch=6955, lrate=0.005, error=0.000\n >epoch=6956, lrate=0.005, error=0.000\n >epoch=6957, lrate=0.005, error=0.000\n >epoch=6958, lrate=0.005, error=0.000\n >epoch=6959, lrate=0.005, error=0.000\n >epoch=6960, lrate=0.005, error=0.000\n >epoch=6961, lrate=0.005, error=0.000\n >epoch=6962, lrate=0.005, error=0.000\n >epoch=6963, lrate=0.005, error=0.000\n >epoch=6964, lrate=0.005, error=0.000\n >epoch=6965, lrate=0.005, error=0.000\n >epoch=6966, lrate=0.005, error=0.000\n >epoch=6967, lrate=0.005, error=0.000\n >epoch=6968, lrate=0.005, error=0.000\n >epoch=6969, lrate=0.005, error=0.000\n >epoch=6970, lrate=0.005, error=0.000\n >epoch=6971, lrate=0.005, error=0.000\n >epoch=6972, lrate=0.005, error=0.000\n >epoch=6973, lrate=0.005, error=0.000\n >epoch=6974, lrate=0.005, error=0.000\n >epoch=6975, lrate=0.005, error=0.000\n >epoch=6976, lrate=0.005, error=0.000\n >epoch=6977, lrate=0.005, error=0.000\n >epoch=6978, lrate=0.005, error=0.000\n >epoch=6979, lrate=0.005, error=0.000\n >epoch=6980, lrate=0.005, error=0.000\n >epoch=6981, lrate=0.005, error=0.000\n >epoch=6982, lrate=0.005, error=0.000\n >epoch=6983, lrate=0.005, error=0.000\n >epoch=6984, lrate=0.005, error=0.000\n >epoch=6985, lrate=0.005, error=0.000\n >epoch=6986, lrate=0.005, error=0.000\n >epoch=6987, lrate=0.005, error=0.000\n >epoch=6988, lrate=0.005, error=0.000\n >epoch=6989, lrate=0.005, error=0.000\n >epoch=6990, lrate=0.005, error=0.000\n >epoch=6991, lrate=0.005, error=0.000\n >epoch=6992, lrate=0.005, error=0.000\n >epoch=6993, lrate=0.005, error=0.000\n >epoch=6994, lrate=0.005, error=0.000\n >epoch=6995, lrate=0.005, error=0.000\n >epoch=6996, lrate=0.005, error=0.000\n >epoch=6997, lrate=0.005, error=0.000\n >epoch=6998, lrate=0.005, error=0.000\n >epoch=6999, lrate=0.005, error=0.000\n >epoch=7000, lrate=0.005, error=0.000\n >epoch=7001, lrate=0.005, error=0.000\n >epoch=7002, lrate=0.005, error=0.000\n >epoch=7003, lrate=0.005, error=0.000\n >epoch=7004, lrate=0.005, error=0.000\n >epoch=7005, lrate=0.005, error=0.000\n >epoch=7006, lrate=0.005, error=0.000\n >epoch=7007, lrate=0.005, error=0.000\n >epoch=7008, lrate=0.005, error=0.000\n >epoch=7009, lrate=0.005, error=0.000\n >epoch=7010, lrate=0.005, error=0.000\n >epoch=7011, lrate=0.005, error=0.000\n >epoch=7012, lrate=0.005, error=0.000\n >epoch=7013, lrate=0.005, error=0.000\n >epoch=7014, lrate=0.005, error=0.000\n >epoch=7015, lrate=0.005, error=0.000\n >epoch=7016, lrate=0.005, error=0.000\n >epoch=7017, lrate=0.005, error=0.000\n >epoch=7018, lrate=0.005, error=0.000\n >epoch=7019, lrate=0.005, error=0.000\n >epoch=7020, lrate=0.005, error=0.000\n >epoch=7021, lrate=0.005, error=0.000\n >epoch=7022, lrate=0.005, error=0.000\n >epoch=7023, lrate=0.005, error=0.000\n >epoch=7024, lrate=0.005, error=0.000\n >epoch=7025, lrate=0.005, error=0.000\n >epoch=7026, lrate=0.005, error=0.000\n >epoch=7027, lrate=0.005, error=0.000\n >epoch=7028, lrate=0.005, error=0.000\n >epoch=7029, lrate=0.005, error=0.000\n >epoch=7030, lrate=0.005, error=0.000\n >epoch=7031, lrate=0.005, error=0.000\n >epoch=7032, lrate=0.005, error=0.000\n >epoch=7033, lrate=0.005, error=0.000\n >epoch=7034, lrate=0.005, error=0.000\n >epoch=7035, lrate=0.005, error=0.000\n >epoch=7036, lrate=0.005, error=0.000\n >epoch=7037, lrate=0.005, error=0.000\n >epoch=7038, lrate=0.005, error=0.000\n >epoch=7039, lrate=0.005, error=0.000\n >epoch=7040, lrate=0.005, error=0.000\n >epoch=7041, lrate=0.005, error=0.000\n >epoch=7042, lrate=0.005, error=0.000\n >epoch=7043, lrate=0.005, error=0.000\n >epoch=7044, lrate=0.005, error=0.000\n >epoch=7045, lrate=0.005, error=0.000\n >epoch=7046, lrate=0.005, error=0.000\n >epoch=7047, lrate=0.005, error=0.000\n >epoch=7048, lrate=0.005, error=0.000\n >epoch=7049, lrate=0.005, error=0.000\n >epoch=7050, lrate=0.005, error=0.000\n >epoch=7051, lrate=0.005, error=0.000\n >epoch=7052, lrate=0.005, error=0.000\n >epoch=7053, lrate=0.005, error=0.000\n >epoch=7054, lrate=0.005, error=0.000\n >epoch=7055, lrate=0.005, error=0.000\n >epoch=7056, lrate=0.005, error=0.000\n >epoch=7057, lrate=0.005, error=0.000\n >epoch=7058, lrate=0.005, error=0.000\n >epoch=7059, lrate=0.005, error=0.000\n >epoch=7060, lrate=0.005, error=0.000\n >epoch=7061, lrate=0.005, error=0.000\n >epoch=7062, lrate=0.005, error=0.000\n >epoch=7063, lrate=0.005, error=0.000\n >epoch=7064, lrate=0.005, error=0.000\n >epoch=7065, lrate=0.005, error=0.000\n >epoch=7066, lrate=0.005, error=0.000\n >epoch=7067, lrate=0.005, error=0.000\n >epoch=7068, lrate=0.005, error=0.000\n >epoch=7069, lrate=0.005, error=0.000\n >epoch=7070, lrate=0.005, error=0.000\n >epoch=7071, lrate=0.005, error=0.000\n >epoch=7072, lrate=0.005, error=0.000\n >epoch=7073, lrate=0.005, error=0.000\n >epoch=7074, lrate=0.005, error=0.000\n >epoch=7075, lrate=0.005, error=0.000\n >epoch=7076, lrate=0.005, error=0.000\n >epoch=7077, lrate=0.005, error=0.000\n >epoch=7078, lrate=0.005, error=0.000\n >epoch=7079, lrate=0.005, error=0.000\n >epoch=7080, lrate=0.005, error=0.000\n >epoch=7081, lrate=0.005, error=0.000\n >epoch=7082, lrate=0.005, error=0.000\n >epoch=7083, lrate=0.005, error=0.000\n >epoch=7084, lrate=0.005, error=0.000\n >epoch=7085, lrate=0.005, error=0.000\n >epoch=7086, lrate=0.005, error=0.000\n >epoch=7087, lrate=0.005, error=0.000\n >epoch=7088, lrate=0.005, error=0.000\n >epoch=7089, lrate=0.005, error=0.000\n >epoch=7090, lrate=0.005, error=0.000\n >epoch=7091, lrate=0.005, error=0.000\n >epoch=7092, lrate=0.005, error=0.000\n >epoch=7093, lrate=0.005, error=0.000\n >epoch=7094, lrate=0.005, error=0.000\n >epoch=7095, lrate=0.005, error=0.000\n >epoch=7096, lrate=0.005, error=0.000\n >epoch=7097, lrate=0.005, error=0.000\n >epoch=7098, lrate=0.005, error=0.000\n >epoch=7099, lrate=0.005, error=0.000\n >epoch=7100, lrate=0.005, error=0.000\n >epoch=7101, lrate=0.005, error=0.000\n >epoch=7102, lrate=0.005, error=0.000\n >epoch=7103, lrate=0.005, error=0.000\n >epoch=7104, lrate=0.005, error=0.000\n >epoch=7105, lrate=0.005, error=0.000\n >epoch=7106, lrate=0.005, error=0.000\n >epoch=7107, lrate=0.005, error=0.000\n >epoch=7108, lrate=0.005, error=0.000\n >epoch=7109, lrate=0.005, error=0.000\n >epoch=7110, lrate=0.005, error=0.000\n >epoch=7111, lrate=0.005, error=0.000\n >epoch=7112, lrate=0.005, error=0.000\n >epoch=7113, lrate=0.005, error=0.000\n >epoch=7114, lrate=0.005, error=0.000\n >epoch=7115, lrate=0.005, error=0.000\n >epoch=7116, lrate=0.005, error=0.000\n >epoch=7117, lrate=0.005, error=0.000\n >epoch=7118, lrate=0.005, error=0.000\n >epoch=7119, lrate=0.005, error=0.000\n >epoch=7120, lrate=0.005, error=0.000\n >epoch=7121, lrate=0.005, error=0.000\n >epoch=7122, lrate=0.005, error=0.000\n >epoch=7123, lrate=0.005, error=0.000\n >epoch=7124, lrate=0.005, error=0.000\n >epoch=7125, lrate=0.005, error=0.000\n >epoch=7126, lrate=0.005, error=0.000\n >epoch=7127, lrate=0.005, error=0.000\n >epoch=7128, lrate=0.005, error=0.000\n >epoch=7129, lrate=0.005, error=0.000\n >epoch=7130, lrate=0.005, error=0.000\n >epoch=7131, lrate=0.005, error=0.000\n >epoch=7132, lrate=0.005, error=0.000\n >epoch=7133, lrate=0.005, error=0.000\n >epoch=7134, lrate=0.005, error=0.000\n >epoch=7135, lrate=0.005, error=0.000\n >epoch=7136, lrate=0.005, error=0.000\n >epoch=7137, lrate=0.005, error=0.000\n >epoch=7138, lrate=0.005, error=0.000\n >epoch=7139, lrate=0.005, error=0.000\n >epoch=7140, lrate=0.005, error=0.000\n >epoch=7141, lrate=0.005, error=0.000\n >epoch=7142, lrate=0.005, error=0.000\n >epoch=7143, lrate=0.005, error=0.000\n >epoch=7144, lrate=0.005, error=0.000\n >epoch=7145, lrate=0.005, error=0.000\n >epoch=7146, lrate=0.005, error=0.000\n >epoch=7147, lrate=0.005, error=0.000\n >epoch=7148, lrate=0.005, error=0.000\n >epoch=7149, lrate=0.005, error=0.000\n >epoch=7150, lrate=0.005, error=0.000\n >epoch=7151, lrate=0.005, error=0.000\n >epoch=7152, lrate=0.005, error=0.000\n >epoch=7153, lrate=0.005, error=0.000\n >epoch=7154, lrate=0.005, error=0.000\n >epoch=7155, lrate=0.005, error=0.000\n >epoch=7156, lrate=0.005, error=0.000\n >epoch=7157, lrate=0.005, error=0.000\n >epoch=7158, lrate=0.005, error=0.000\n >epoch=7159, lrate=0.005, error=0.000\n >epoch=7160, lrate=0.005, error=0.000\n >epoch=7161, lrate=0.005, error=0.000\n >epoch=7162, lrate=0.005, error=0.000\n >epoch=7163, lrate=0.005, error=0.000\n >epoch=7164, lrate=0.005, error=0.000\n >epoch=7165, lrate=0.005, error=0.000\n >epoch=7166, lrate=0.005, error=0.000\n >epoch=7167, lrate=0.005, error=0.000\n >epoch=7168, lrate=0.005, error=0.000\n >epoch=7169, lrate=0.005, error=0.000\n >epoch=7170, lrate=0.005, error=0.000\n >epoch=7171, lrate=0.005, error=0.000\n >epoch=7172, lrate=0.005, error=0.000\n >epoch=7173, lrate=0.005, error=0.000\n >epoch=7174, lrate=0.005, error=0.000\n >epoch=7175, lrate=0.005, error=0.000\n >epoch=7176, lrate=0.005, error=0.000\n >epoch=7177, lrate=0.005, error=0.000\n >epoch=7178, lrate=0.005, error=0.000\n >epoch=7179, lrate=0.005, error=0.000\n >epoch=7180, lrate=0.005, error=0.000\n >epoch=7181, lrate=0.005, error=0.000\n >epoch=7182, lrate=0.005, error=0.000\n >epoch=7183, lrate=0.005, error=0.000\n >epoch=7184, lrate=0.005, error=0.000\n >epoch=7185, lrate=0.005, error=0.000\n >epoch=7186, lrate=0.005, error=0.000\n >epoch=7187, lrate=0.005, error=0.000\n >epoch=7188, lrate=0.005, error=0.000\n >epoch=7189, lrate=0.005, error=0.000\n >epoch=7190, lrate=0.005, error=0.000\n >epoch=7191, lrate=0.005, error=0.000\n >epoch=7192, lrate=0.005, error=0.000\n >epoch=7193, lrate=0.005, error=0.000\n >epoch=7194, lrate=0.005, error=0.000\n >epoch=7195, lrate=0.005, error=0.000\n >epoch=7196, lrate=0.005, error=0.000\n >epoch=7197, lrate=0.005, error=0.000\n >epoch=7198, lrate=0.005, error=0.000\n >epoch=7199, lrate=0.005, error=0.000\n >epoch=7200, lrate=0.005, error=0.000\n >epoch=7201, lrate=0.005, error=0.000\n >epoch=7202, lrate=0.005, error=0.000\n >epoch=7203, lrate=0.005, error=0.000\n >epoch=7204, lrate=0.005, error=0.000\n >epoch=7205, lrate=0.005, error=0.000\n >epoch=7206, lrate=0.005, error=0.000\n >epoch=7207, lrate=0.005, error=0.000\n >epoch=7208, lrate=0.005, error=0.000\n >epoch=7209, lrate=0.005, error=0.000\n >epoch=7210, lrate=0.005, error=0.000\n >epoch=7211, lrate=0.005, error=0.000\n >epoch=7212, lrate=0.005, error=0.000\n >epoch=7213, lrate=0.005, error=0.000\n >epoch=7214, lrate=0.005, error=0.000\n >epoch=7215, lrate=0.005, error=0.000\n >epoch=7216, lrate=0.005, error=0.000\n >epoch=7217, lrate=0.005, error=0.000\n >epoch=7218, lrate=0.005, error=0.000\n >epoch=7219, lrate=0.005, error=0.000\n >epoch=7220, lrate=0.005, error=0.000\n >epoch=7221, lrate=0.005, error=0.000\n >epoch=7222, lrate=0.005, error=0.000\n >epoch=7223, lrate=0.005, error=0.000\n >epoch=7224, lrate=0.005, error=0.000\n >epoch=7225, lrate=0.005, error=0.000\n >epoch=7226, lrate=0.005, error=0.000\n >epoch=7227, lrate=0.005, error=0.000\n >epoch=7228, lrate=0.005, error=0.000\n >epoch=7229, lrate=0.005, error=0.000\n >epoch=7230, lrate=0.005, error=0.000\n >epoch=7231, lrate=0.005, error=0.000\n >epoch=7232, lrate=0.005, error=0.000\n >epoch=7233, lrate=0.005, error=0.000\n >epoch=7234, lrate=0.005, error=0.000\n >epoch=7235, lrate=0.005, error=0.000\n >epoch=7236, lrate=0.005, error=0.000\n >epoch=7237, lrate=0.005, error=0.000\n >epoch=7238, lrate=0.005, error=0.000\n >epoch=7239, lrate=0.005, error=0.000\n >epoch=7240, lrate=0.005, error=0.000\n >epoch=7241, lrate=0.005, error=0.000\n >epoch=7242, lrate=0.005, error=0.000\n >epoch=7243, lrate=0.005, error=0.000\n >epoch=7244, lrate=0.005, error=0.000\n >epoch=7245, lrate=0.005, error=0.000\n >epoch=7246, lrate=0.005, error=0.000\n >epoch=7247, lrate=0.005, error=0.000\n >epoch=7248, lrate=0.005, error=0.000\n >epoch=7249, lrate=0.005, error=0.000\n >epoch=7250, lrate=0.005, error=0.000\n >epoch=7251, lrate=0.005, error=0.000\n >epoch=7252, lrate=0.005, error=0.000\n >epoch=7253, lrate=0.005, error=0.000\n >epoch=7254, lrate=0.005, error=0.000\n >epoch=7255, lrate=0.005, error=0.000\n >epoch=7256, lrate=0.005, error=0.000\n >epoch=7257, lrate=0.005, error=0.000\n >epoch=7258, lrate=0.005, error=0.000\n >epoch=7259, lrate=0.005, error=0.000\n >epoch=7260, lrate=0.005, error=0.000\n >epoch=7261, lrate=0.005, error=0.000\n >epoch=7262, lrate=0.005, error=0.000\n >epoch=7263, lrate=0.005, error=0.000\n >epoch=7264, lrate=0.005, error=0.000\n >epoch=7265, lrate=0.005, error=0.000\n >epoch=7266, lrate=0.005, error=0.000\n >epoch=7267, lrate=0.005, error=0.000\n >epoch=7268, lrate=0.005, error=0.000\n >epoch=7269, lrate=0.005, error=0.000\n >epoch=7270, lrate=0.005, error=0.000\n >epoch=7271, lrate=0.005, error=0.000\n >epoch=7272, lrate=0.005, error=0.000\n >epoch=7273, lrate=0.005, error=0.000\n >epoch=7274, lrate=0.005, error=0.000\n >epoch=7275, lrate=0.005, error=0.000\n >epoch=7276, lrate=0.005, error=0.000\n >epoch=7277, lrate=0.005, error=0.000\n >epoch=7278, lrate=0.005, error=0.000\n >epoch=7279, lrate=0.005, error=0.000\n >epoch=7280, lrate=0.005, error=0.000\n >epoch=7281, lrate=0.005, error=0.000\n >epoch=7282, lrate=0.005, error=0.000\n >epoch=7283, lrate=0.005, error=0.000\n >epoch=7284, lrate=0.005, error=0.000\n >epoch=7285, lrate=0.005, error=0.000\n >epoch=7286, lrate=0.005, error=0.000\n >epoch=7287, lrate=0.005, error=0.000\n >epoch=7288, lrate=0.005, error=0.000\n >epoch=7289, lrate=0.005, error=0.000\n >epoch=7290, lrate=0.005, error=0.000\n >epoch=7291, lrate=0.005, error=0.000\n >epoch=7292, lrate=0.005, error=0.000\n >epoch=7293, lrate=0.005, error=0.000\n >epoch=7294, lrate=0.005, error=0.000\n >epoch=7295, lrate=0.005, error=0.000\n >epoch=7296, lrate=0.005, error=0.000\n >epoch=7297, lrate=0.005, error=0.000\n >epoch=7298, lrate=0.005, error=0.000\n >epoch=7299, lrate=0.005, error=0.000\n >epoch=7300, lrate=0.005, error=0.000\n >epoch=7301, lrate=0.005, error=0.000\n >epoch=7302, lrate=0.005, error=0.000\n >epoch=7303, lrate=0.005, error=0.000\n >epoch=7304, lrate=0.005, error=0.000\n >epoch=7305, lrate=0.005, error=0.000\n >epoch=7306, lrate=0.005, error=0.000\n >epoch=7307, lrate=0.005, error=0.000\n >epoch=7308, lrate=0.005, error=0.000\n >epoch=7309, lrate=0.005, error=0.000\n >epoch=7310, lrate=0.005, error=0.000\n >epoch=7311, lrate=0.005, error=0.000\n >epoch=7312, lrate=0.005, error=0.000\n >epoch=7313, lrate=0.005, error=0.000\n >epoch=7314, lrate=0.005, error=0.000\n >epoch=7315, lrate=0.005, error=0.000\n >epoch=7316, lrate=0.005, error=0.000\n >epoch=7317, lrate=0.005, error=0.000\n >epoch=7318, lrate=0.005, error=0.000\n >epoch=7319, lrate=0.005, error=0.000\n >epoch=7320, lrate=0.005, error=0.000\n >epoch=7321, lrate=0.005, error=0.000\n >epoch=7322, lrate=0.005, error=0.000\n >epoch=7323, lrate=0.005, error=0.000\n >epoch=7324, lrate=0.005, error=0.000\n >epoch=7325, lrate=0.005, error=0.000\n >epoch=7326, lrate=0.005, error=0.000\n >epoch=7327, lrate=0.005, error=0.000\n >epoch=7328, lrate=0.005, error=0.000\n >epoch=7329, lrate=0.005, error=0.000\n >epoch=7330, lrate=0.005, error=0.000\n >epoch=7331, lrate=0.005, error=0.000\n >epoch=7332, lrate=0.005, error=0.000\n >epoch=7333, lrate=0.005, error=0.000\n >epoch=7334, lrate=0.005, error=0.000\n >epoch=7335, lrate=0.005, error=0.000\n >epoch=7336, lrate=0.005, error=0.000\n >epoch=7337, lrate=0.005, error=0.000\n >epoch=7338, lrate=0.005, error=0.000\n >epoch=7339, lrate=0.005, error=0.000\n >epoch=7340, lrate=0.005, error=0.000\n >epoch=7341, lrate=0.005, error=0.000\n >epoch=7342, lrate=0.005, error=0.000\n >epoch=7343, lrate=0.005, error=0.000\n >epoch=7344, lrate=0.005, error=0.000\n >epoch=7345, lrate=0.005, error=0.000\n >epoch=7346, lrate=0.005, error=0.000\n >epoch=7347, lrate=0.005, error=0.000\n >epoch=7348, lrate=0.005, error=0.000\n >epoch=7349, lrate=0.005, error=0.000\n >epoch=7350, lrate=0.005, error=0.000\n >epoch=7351, lrate=0.005, error=0.000\n >epoch=7352, lrate=0.005, error=0.000\n >epoch=7353, lrate=0.005, error=0.000\n >epoch=7354, lrate=0.005, error=0.000\n >epoch=7355, lrate=0.005, error=0.000\n >epoch=7356, lrate=0.005, error=0.000\n >epoch=7357, lrate=0.005, error=0.000\n >epoch=7358, lrate=0.005, error=0.000\n >epoch=7359, lrate=0.005, error=0.000\n >epoch=7360, lrate=0.005, error=0.000\n >epoch=7361, lrate=0.005, error=0.000\n >epoch=7362, lrate=0.005, error=0.000\n >epoch=7363, lrate=0.005, error=0.000\n >epoch=7364, lrate=0.005, error=0.000\n >epoch=7365, lrate=0.005, error=0.000\n >epoch=7366, lrate=0.005, error=0.000\n >epoch=7367, lrate=0.005, error=0.000\n >epoch=7368, lrate=0.005, error=0.000\n >epoch=7369, lrate=0.005, error=0.000\n >epoch=7370, lrate=0.005, error=0.000\n >epoch=7371, lrate=0.005, error=0.000\n >epoch=7372, lrate=0.005, error=0.000\n >epoch=7373, lrate=0.005, error=0.000\n >epoch=7374, lrate=0.005, error=0.000\n >epoch=7375, lrate=0.005, error=0.000\n >epoch=7376, lrate=0.005, error=0.000\n >epoch=7377, lrate=0.005, error=0.000\n >epoch=7378, lrate=0.005, error=0.000\n >epoch=7379, lrate=0.005, error=0.000\n >epoch=7380, lrate=0.005, error=0.000\n >epoch=7381, lrate=0.005, error=0.000\n >epoch=7382, lrate=0.005, error=0.000\n >epoch=7383, lrate=0.005, error=0.000\n >epoch=7384, lrate=0.005, error=0.000\n >epoch=7385, lrate=0.005, error=0.000\n >epoch=7386, lrate=0.005, error=0.000\n >epoch=7387, lrate=0.005, error=0.000\n >epoch=7388, lrate=0.005, error=0.000\n >epoch=7389, lrate=0.005, error=0.000\n >epoch=7390, lrate=0.005, error=0.000\n >epoch=7391, lrate=0.005, error=0.000\n >epoch=7392, lrate=0.005, error=0.000\n >epoch=7393, lrate=0.005, error=0.000\n >epoch=7394, lrate=0.005, error=0.000\n >epoch=7395, lrate=0.005, error=0.000\n >epoch=7396, lrate=0.005, error=0.000\n >epoch=7397, lrate=0.005, error=0.000\n >epoch=7398, lrate=0.005, error=0.000\n >epoch=7399, lrate=0.005, error=0.000\n >epoch=7400, lrate=0.005, error=0.000\n >epoch=7401, lrate=0.005, error=0.000\n >epoch=7402, lrate=0.005, error=0.000\n >epoch=7403, lrate=0.005, error=0.000\n >epoch=7404, lrate=0.005, error=0.000\n >epoch=7405, lrate=0.005, error=0.000\n >epoch=7406, lrate=0.005, error=0.000\n >epoch=7407, lrate=0.005, error=0.000\n >epoch=7408, lrate=0.005, error=0.000\n >epoch=7409, lrate=0.005, error=0.000\n >epoch=7410, lrate=0.005, error=0.000\n >epoch=7411, lrate=0.005, error=0.000\n >epoch=7412, lrate=0.005, error=0.000\n >epoch=7413, lrate=0.005, error=0.000\n >epoch=7414, lrate=0.005, error=0.000\n >epoch=7415, lrate=0.005, error=0.000\n >epoch=7416, lrate=0.005, error=0.000\n >epoch=7417, lrate=0.005, error=0.000\n >epoch=7418, lrate=0.005, error=0.000\n >epoch=7419, lrate=0.005, error=0.000\n >epoch=7420, lrate=0.005, error=0.000\n >epoch=7421, lrate=0.005, error=0.000\n >epoch=7422, lrate=0.005, error=0.000\n >epoch=7423, lrate=0.005, error=0.000\n >epoch=7424, lrate=0.005, error=0.000\n >epoch=7425, lrate=0.005, error=0.000\n >epoch=7426, lrate=0.005, error=0.000\n >epoch=7427, lrate=0.005, error=0.000\n >epoch=7428, lrate=0.005, error=0.000\n >epoch=7429, lrate=0.005, error=0.000\n >epoch=7430, lrate=0.005, error=0.000\n >epoch=7431, lrate=0.005, error=0.000\n >epoch=7432, lrate=0.005, error=0.000\n >epoch=7433, lrate=0.005, error=0.000\n >epoch=7434, lrate=0.005, error=0.000\n >epoch=7435, lrate=0.005, error=0.000\n >epoch=7436, lrate=0.005, error=0.000\n >epoch=7437, lrate=0.005, error=0.000\n >epoch=7438, lrate=0.005, error=0.000\n >epoch=7439, lrate=0.005, error=0.000\n >epoch=7440, lrate=0.005, error=0.000\n >epoch=7441, lrate=0.005, error=0.000\n >epoch=7442, lrate=0.005, error=0.000\n >epoch=7443, lrate=0.005, error=0.000\n >epoch=7444, lrate=0.005, error=0.000\n >epoch=7445, lrate=0.005, error=0.000\n >epoch=7446, lrate=0.005, error=0.000\n >epoch=7447, lrate=0.005, error=0.000\n >epoch=7448, lrate=0.005, error=0.000\n >epoch=7449, lrate=0.005, error=0.000\n >epoch=7450, lrate=0.005, error=0.000\n >epoch=7451, lrate=0.005, error=0.000\n >epoch=7452, lrate=0.005, error=0.000\n >epoch=7453, lrate=0.005, error=0.000\n >epoch=7454, lrate=0.005, error=0.000\n >epoch=7455, lrate=0.005, error=0.000\n >epoch=7456, lrate=0.005, error=0.000\n >epoch=7457, lrate=0.005, error=0.000\n >epoch=7458, lrate=0.005, error=0.000\n >epoch=7459, lrate=0.005, error=0.000\n >epoch=7460, lrate=0.005, error=0.000\n >epoch=7461, lrate=0.005, error=0.000\n >epoch=7462, lrate=0.005, error=0.000\n >epoch=7463, lrate=0.005, error=0.000\n >epoch=7464, lrate=0.005, error=0.000\n >epoch=7465, lrate=0.005, error=0.000\n >epoch=7466, lrate=0.005, error=0.000\n >epoch=7467, lrate=0.005, error=0.000\n >epoch=7468, lrate=0.005, error=0.000\n >epoch=7469, lrate=0.005, error=0.000\n >epoch=7470, lrate=0.005, error=0.000\n >epoch=7471, lrate=0.005, error=0.000\n >epoch=7472, lrate=0.005, error=0.000\n >epoch=7473, lrate=0.005, error=0.000\n >epoch=7474, lrate=0.005, error=0.000\n >epoch=7475, lrate=0.005, error=0.000\n >epoch=7476, lrate=0.005, error=0.000\n >epoch=7477, lrate=0.005, error=0.000\n >epoch=7478, lrate=0.005, error=0.000\n >epoch=7479, lrate=0.005, error=0.000\n >epoch=7480, lrate=0.005, error=0.000\n >epoch=7481, lrate=0.005, error=0.000\n >epoch=7482, lrate=0.005, error=0.000\n >epoch=7483, lrate=0.005, error=0.000\n >epoch=7484, lrate=0.005, error=0.000\n >epoch=7485, lrate=0.005, error=0.000\n >epoch=7486, lrate=0.005, error=0.000\n >epoch=7487, lrate=0.005, error=0.000\n >epoch=7488, lrate=0.005, error=0.000\n >epoch=7489, lrate=0.005, error=0.000\n >epoch=7490, lrate=0.005, error=0.000\n >epoch=7491, lrate=0.005, error=0.000\n >epoch=7492, lrate=0.005, error=0.000\n >epoch=7493, lrate=0.005, error=0.000\n >epoch=7494, lrate=0.005, error=0.000\n >epoch=7495, lrate=0.005, error=0.000\n >epoch=7496, lrate=0.005, error=0.000\n >epoch=7497, lrate=0.005, error=0.000\n >epoch=7498, lrate=0.005, error=0.000\n >epoch=7499, lrate=0.005, error=0.000\n >epoch=7500, lrate=0.005, error=0.000\n >epoch=7501, lrate=0.005, error=0.000\n >epoch=7502, lrate=0.005, error=0.000\n >epoch=7503, lrate=0.005, error=0.000\n >epoch=7504, lrate=0.005, error=0.000\n >epoch=7505, lrate=0.005, error=0.000\n >epoch=7506, lrate=0.005, error=0.000\n >epoch=7507, lrate=0.005, error=0.000\n >epoch=7508, lrate=0.005, error=0.000\n >epoch=7509, lrate=0.005, error=0.000\n >epoch=7510, lrate=0.005, error=0.000\n >epoch=7511, lrate=0.005, error=0.000\n >epoch=7512, lrate=0.005, error=0.000\n >epoch=7513, lrate=0.005, error=0.000\n >epoch=7514, lrate=0.005, error=0.000\n >epoch=7515, lrate=0.005, error=0.000\n >epoch=7516, lrate=0.005, error=0.000\n >epoch=7517, lrate=0.005, error=0.000\n >epoch=7518, lrate=0.005, error=0.000\n >epoch=7519, lrate=0.005, error=0.000\n >epoch=7520, lrate=0.005, error=0.000\n >epoch=7521, lrate=0.005, error=0.000\n >epoch=7522, lrate=0.005, error=0.000\n >epoch=7523, lrate=0.005, error=0.000\n >epoch=7524, lrate=0.005, error=0.000\n >epoch=7525, lrate=0.005, error=0.000\n >epoch=7526, lrate=0.005, error=0.000\n >epoch=7527, lrate=0.005, error=0.000\n >epoch=7528, lrate=0.005, error=0.000\n >epoch=7529, lrate=0.005, error=0.000\n >epoch=7530, lrate=0.005, error=0.000\n >epoch=7531, lrate=0.005, error=0.000\n >epoch=7532, lrate=0.005, error=0.000\n >epoch=7533, lrate=0.005, error=0.000\n >epoch=7534, lrate=0.005, error=0.000\n >epoch=7535, lrate=0.005, error=0.000\n >epoch=7536, lrate=0.005, error=0.000\n >epoch=7537, lrate=0.005, error=0.000\n >epoch=7538, lrate=0.005, error=0.000\n >epoch=7539, lrate=0.005, error=0.000\n >epoch=7540, lrate=0.005, error=0.000\n >epoch=7541, lrate=0.005, error=0.000\n >epoch=7542, lrate=0.005, error=0.000\n >epoch=7543, lrate=0.005, error=0.000\n >epoch=7544, lrate=0.005, error=0.000\n >epoch=7545, lrate=0.005, error=0.000\n >epoch=7546, lrate=0.005, error=0.000\n >epoch=7547, lrate=0.005, error=0.000\n >epoch=7548, lrate=0.005, error=0.000\n >epoch=7549, lrate=0.005, error=0.000\n >epoch=7550, lrate=0.005, error=0.000\n >epoch=7551, lrate=0.005, error=0.000\n >epoch=7552, lrate=0.005, error=0.000\n >epoch=7553, lrate=0.005, error=0.000\n >epoch=7554, lrate=0.005, error=0.000\n >epoch=7555, lrate=0.005, error=0.000\n >epoch=7556, lrate=0.005, error=0.000\n >epoch=7557, lrate=0.005, error=0.000\n >epoch=7558, lrate=0.005, error=0.000\n >epoch=7559, lrate=0.005, error=0.000\n >epoch=7560, lrate=0.005, error=0.000\n >epoch=7561, lrate=0.005, error=0.000\n >epoch=7562, lrate=0.005, error=0.000\n >epoch=7563, lrate=0.005, error=0.000\n >epoch=7564, lrate=0.005, error=0.000\n >epoch=7565, lrate=0.005, error=0.000\n >epoch=7566, lrate=0.005, error=0.000\n >epoch=7567, lrate=0.005, error=0.000\n >epoch=7568, lrate=0.005, error=0.000\n >epoch=7569, lrate=0.005, error=0.000\n >epoch=7570, lrate=0.005, error=0.000\n >epoch=7571, lrate=0.005, error=0.000\n >epoch=7572, lrate=0.005, error=0.000\n >epoch=7573, lrate=0.005, error=0.000\n >epoch=7574, lrate=0.005, error=0.000\n >epoch=7575, lrate=0.005, error=0.000\n >epoch=7576, lrate=0.005, error=0.000\n >epoch=7577, lrate=0.005, error=0.000\n >epoch=7578, lrate=0.005, error=0.000\n >epoch=7579, lrate=0.005, error=0.000\n >epoch=7580, lrate=0.005, error=0.000\n >epoch=7581, lrate=0.005, error=0.000\n >epoch=7582, lrate=0.005, error=0.000\n >epoch=7583, lrate=0.005, error=0.000\n >epoch=7584, lrate=0.005, error=0.000\n >epoch=7585, lrate=0.005, error=0.000\n >epoch=7586, lrate=0.005, error=0.000\n >epoch=7587, lrate=0.005, error=0.000\n >epoch=7588, lrate=0.005, error=0.000\n >epoch=7589, lrate=0.005, error=0.000\n >epoch=7590, lrate=0.005, error=0.000\n >epoch=7591, lrate=0.005, error=0.000\n >epoch=7592, lrate=0.005, error=0.000\n >epoch=7593, lrate=0.005, error=0.000\n >epoch=7594, lrate=0.005, error=0.000\n >epoch=7595, lrate=0.005, error=0.000\n >epoch=7596, lrate=0.005, error=0.000\n >epoch=7597, lrate=0.005, error=0.000\n >epoch=7598, lrate=0.005, error=0.000\n >epoch=7599, lrate=0.005, error=0.000\n >epoch=7600, lrate=0.005, error=0.000\n >epoch=7601, lrate=0.005, error=0.000\n >epoch=7602, lrate=0.005, error=0.000\n >epoch=7603, lrate=0.005, error=0.000\n >epoch=7604, lrate=0.005, error=0.000\n >epoch=7605, lrate=0.005, error=0.000\n >epoch=7606, lrate=0.005, error=0.000\n >epoch=7607, lrate=0.005, error=0.000\n >epoch=7608, lrate=0.005, error=0.000\n >epoch=7609, lrate=0.005, error=0.000\n >epoch=7610, lrate=0.005, error=0.000\n >epoch=7611, lrate=0.005, error=0.000\n >epoch=7612, lrate=0.005, error=0.000\n >epoch=7613, lrate=0.005, error=0.000\n >epoch=7614, lrate=0.005, error=0.000\n >epoch=7615, lrate=0.005, error=0.000\n >epoch=7616, lrate=0.005, error=0.000\n >epoch=7617, lrate=0.005, error=0.000\n >epoch=7618, lrate=0.005, error=0.000\n >epoch=7619, lrate=0.005, error=0.000\n >epoch=7620, lrate=0.005, error=0.000\n >epoch=7621, lrate=0.005, error=0.000\n >epoch=7622, lrate=0.005, error=0.000\n >epoch=7623, lrate=0.005, error=0.000\n >epoch=7624, lrate=0.005, error=0.000\n >epoch=7625, lrate=0.005, error=0.000\n >epoch=7626, lrate=0.005, error=0.000\n >epoch=7627, lrate=0.005, error=0.000\n >epoch=7628, lrate=0.005, error=0.000\n >epoch=7629, lrate=0.005, error=0.000\n >epoch=7630, lrate=0.005, error=0.000\n >epoch=7631, lrate=0.005, error=0.000\n >epoch=7632, lrate=0.005, error=0.000\n >epoch=7633, lrate=0.005, error=0.000\n >epoch=7634, lrate=0.005, error=0.000\n >epoch=7635, lrate=0.005, error=0.000\n >epoch=7636, lrate=0.005, error=0.000\n >epoch=7637, lrate=0.005, error=0.000\n >epoch=7638, lrate=0.005, error=0.000\n >epoch=7639, lrate=0.005, error=0.000\n >epoch=7640, lrate=0.005, error=0.000\n >epoch=7641, lrate=0.005, error=0.000\n >epoch=7642, lrate=0.005, error=0.000\n >epoch=7643, lrate=0.005, error=0.000\n >epoch=7644, lrate=0.005, error=0.000\n >epoch=7645, lrate=0.005, error=0.000\n >epoch=7646, lrate=0.005, error=0.000\n >epoch=7647, lrate=0.005, error=0.000\n >epoch=7648, lrate=0.005, error=0.000\n >epoch=7649, lrate=0.005, error=0.000\n >epoch=7650, lrate=0.005, error=0.000\n >epoch=7651, lrate=0.005, error=0.000\n >epoch=7652, lrate=0.005, error=0.000\n >epoch=7653, lrate=0.005, error=0.000\n >epoch=7654, lrate=0.005, error=0.000\n >epoch=7655, lrate=0.005, error=0.000\n >epoch=7656, lrate=0.005, error=0.000\n >epoch=7657, lrate=0.005, error=0.000\n >epoch=7658, lrate=0.005, error=0.000\n >epoch=7659, lrate=0.005, error=0.000\n >epoch=7660, lrate=0.005, error=0.000\n >epoch=7661, lrate=0.005, error=0.000\n >epoch=7662, lrate=0.005, error=0.000\n >epoch=7663, lrate=0.005, error=0.000\n >epoch=7664, lrate=0.005, error=0.000\n >epoch=7665, lrate=0.005, error=0.000\n >epoch=7666, lrate=0.005, error=0.000\n >epoch=7667, lrate=0.005, error=0.000\n >epoch=7668, lrate=0.005, error=0.000\n >epoch=7669, lrate=0.005, error=0.000\n >epoch=7670, lrate=0.005, error=0.000\n >epoch=7671, lrate=0.005, error=0.000\n >epoch=7672, lrate=0.005, error=0.000\n >epoch=7673, lrate=0.005, error=0.000\n >epoch=7674, lrate=0.005, error=0.000\n >epoch=7675, lrate=0.005, error=0.000\n >epoch=7676, lrate=0.005, error=0.000\n >epoch=7677, lrate=0.005, error=0.000\n >epoch=7678, lrate=0.005, error=0.000\n >epoch=7679, lrate=0.005, error=0.000\n >epoch=7680, lrate=0.005, error=0.000\n >epoch=7681, lrate=0.005, error=0.000\n >epoch=7682, lrate=0.005, error=0.000\n >epoch=7683, lrate=0.005, error=0.000\n >epoch=7684, lrate=0.005, error=0.000\n >epoch=7685, lrate=0.005, error=0.000\n >epoch=7686, lrate=0.005, error=0.000\n >epoch=7687, lrate=0.005, error=0.000\n >epoch=7688, lrate=0.005, error=0.000\n >epoch=7689, lrate=0.005, error=0.000\n >epoch=7690, lrate=0.005, error=0.000\n >epoch=7691, lrate=0.005, error=0.000\n >epoch=7692, lrate=0.005, error=0.000\n >epoch=7693, lrate=0.005, error=0.000\n >epoch=7694, lrate=0.005, error=0.000\n >epoch=7695, lrate=0.005, error=0.000\n >epoch=7696, lrate=0.005, error=0.000\n >epoch=7697, lrate=0.005, error=0.000\n >epoch=7698, lrate=0.005, error=0.000\n >epoch=7699, lrate=0.005, error=0.000\n >epoch=7700, lrate=0.005, error=0.000\n >epoch=7701, lrate=0.005, error=0.000\n >epoch=7702, lrate=0.005, error=0.000\n >epoch=7703, lrate=0.005, error=0.000\n >epoch=7704, lrate=0.005, error=0.000\n >epoch=7705, lrate=0.005, error=0.000\n >epoch=7706, lrate=0.005, error=0.000\n >epoch=7707, lrate=0.005, error=0.000\n >epoch=7708, lrate=0.005, error=0.000\n >epoch=7709, lrate=0.005, error=0.000\n >epoch=7710, lrate=0.005, error=0.000\n >epoch=7711, lrate=0.005, error=0.000\n >epoch=7712, lrate=0.005, error=0.000\n >epoch=7713, lrate=0.005, error=0.000\n >epoch=7714, lrate=0.005, error=0.000\n >epoch=7715, lrate=0.005, error=0.000\n >epoch=7716, lrate=0.005, error=0.000\n >epoch=7717, lrate=0.005, error=0.000\n >epoch=7718, lrate=0.005, error=0.000\n >epoch=7719, lrate=0.005, error=0.000\n >epoch=7720, lrate=0.005, error=0.000\n >epoch=7721, lrate=0.005, error=0.000\n >epoch=7722, lrate=0.005, error=0.000\n >epoch=7723, lrate=0.005, error=0.000\n >epoch=7724, lrate=0.005, error=0.000\n >epoch=7725, lrate=0.005, error=0.000\n >epoch=7726, lrate=0.005, error=0.000\n >epoch=7727, lrate=0.005, error=0.000\n >epoch=7728, lrate=0.005, error=0.000\n >epoch=7729, lrate=0.005, error=0.000\n >epoch=7730, lrate=0.005, error=0.000\n >epoch=7731, lrate=0.005, error=0.000\n >epoch=7732, lrate=0.005, error=0.000\n >epoch=7733, lrate=0.005, error=0.000\n >epoch=7734, lrate=0.005, error=0.000\n >epoch=7735, lrate=0.005, error=0.000\n >epoch=7736, lrate=0.005, error=0.000\n >epoch=7737, lrate=0.005, error=0.000\n >epoch=7738, lrate=0.005, error=0.000\n >epoch=7739, lrate=0.005, error=0.000\n >epoch=7740, lrate=0.005, error=0.000\n >epoch=7741, lrate=0.005, error=0.000\n >epoch=7742, lrate=0.005, error=0.000\n >epoch=7743, lrate=0.005, error=0.000\n >epoch=7744, lrate=0.005, error=0.000\n >epoch=7745, lrate=0.005, error=0.000\n >epoch=7746, lrate=0.005, error=0.000\n >epoch=7747, lrate=0.005, error=0.000\n >epoch=7748, lrate=0.005, error=0.000\n >epoch=7749, lrate=0.005, error=0.000\n >epoch=7750, lrate=0.005, error=0.000\n >epoch=7751, lrate=0.005, error=0.000\n >epoch=7752, lrate=0.005, error=0.000\n >epoch=7753, lrate=0.005, error=0.000\n >epoch=7754, lrate=0.005, error=0.000\n >epoch=7755, lrate=0.005, error=0.000\n >epoch=7756, lrate=0.005, error=0.000\n >epoch=7757, lrate=0.005, error=0.000\n >epoch=7758, lrate=0.005, error=0.000\n >epoch=7759, lrate=0.005, error=0.000\n >epoch=7760, lrate=0.005, error=0.000\n >epoch=7761, lrate=0.005, error=0.000\n >epoch=7762, lrate=0.005, error=0.000\n >epoch=7763, lrate=0.005, error=0.000\n >epoch=7764, lrate=0.005, error=0.000\n >epoch=7765, lrate=0.005, error=0.000\n >epoch=7766, lrate=0.005, error=0.000\n >epoch=7767, lrate=0.005, error=0.000\n >epoch=7768, lrate=0.005, error=0.000\n >epoch=7769, lrate=0.005, error=0.000\n >epoch=7770, lrate=0.005, error=0.000\n >epoch=7771, lrate=0.005, error=0.000\n >epoch=7772, lrate=0.005, error=0.000\n >epoch=7773, lrate=0.005, error=0.000\n >epoch=7774, lrate=0.005, error=0.000\n >epoch=7775, lrate=0.005, error=0.000\n >epoch=7776, lrate=0.005, error=0.000\n >epoch=7777, lrate=0.005, error=0.000\n >epoch=7778, lrate=0.005, error=0.000\n >epoch=7779, lrate=0.005, error=0.000\n >epoch=7780, lrate=0.005, error=0.000\n >epoch=7781, lrate=0.005, error=0.000\n >epoch=7782, lrate=0.005, error=0.000\n >epoch=7783, lrate=0.005, error=0.000\n >epoch=7784, lrate=0.005, error=0.000\n >epoch=7785, lrate=0.005, error=0.000\n >epoch=7786, lrate=0.005, error=0.000\n >epoch=7787, lrate=0.005, error=0.000\n >epoch=7788, lrate=0.005, error=0.000\n >epoch=7789, lrate=0.005, error=0.000\n >epoch=7790, lrate=0.005, error=0.000\n >epoch=7791, lrate=0.005, error=0.000\n >epoch=7792, lrate=0.005, error=0.000\n >epoch=7793, lrate=0.005, error=0.000\n >epoch=7794, lrate=0.005, error=0.000\n >epoch=7795, lrate=0.005, error=0.000\n >epoch=7796, lrate=0.005, error=0.000\n >epoch=7797, lrate=0.005, error=0.000\n >epoch=7798, lrate=0.005, error=0.000\n >epoch=7799, lrate=0.005, error=0.000\n >epoch=7800, lrate=0.005, error=0.000\n >epoch=7801, lrate=0.005, error=0.000\n >epoch=7802, lrate=0.005, error=0.000\n >epoch=7803, lrate=0.005, error=0.000\n >epoch=7804, lrate=0.005, error=0.000\n >epoch=7805, lrate=0.005, error=0.000\n >epoch=7806, lrate=0.005, error=0.000\n >epoch=7807, lrate=0.005, error=0.000\n >epoch=7808, lrate=0.005, error=0.000\n >epoch=7809, lrate=0.005, error=0.000\n >epoch=7810, lrate=0.005, error=0.000\n >epoch=7811, lrate=0.005, error=0.000\n >epoch=7812, lrate=0.005, error=0.000\n >epoch=7813, lrate=0.005, error=0.000\n >epoch=7814, lrate=0.005, error=0.000\n >epoch=7815, lrate=0.005, error=0.000\n >epoch=7816, lrate=0.005, error=0.000\n >epoch=7817, lrate=0.005, error=0.000\n >epoch=7818, lrate=0.005, error=0.000\n >epoch=7819, lrate=0.005, error=0.000\n >epoch=7820, lrate=0.005, error=0.000\n >epoch=7821, lrate=0.005, error=0.000\n >epoch=7822, lrate=0.005, error=0.000\n >epoch=7823, lrate=0.005, error=0.000\n >epoch=7824, lrate=0.005, error=0.000\n >epoch=7825, lrate=0.005, error=0.000\n >epoch=7826, lrate=0.005, error=0.000\n >epoch=7827, lrate=0.005, error=0.000\n >epoch=7828, lrate=0.005, error=0.000\n >epoch=7829, lrate=0.005, error=0.000\n >epoch=7830, lrate=0.005, error=0.000\n >epoch=7831, lrate=0.005, error=0.000\n >epoch=7832, lrate=0.005, error=0.000\n >epoch=7833, lrate=0.005, error=0.000\n >epoch=7834, lrate=0.005, error=0.000\n >epoch=7835, lrate=0.005, error=0.000\n >epoch=7836, lrate=0.005, error=0.000\n >epoch=7837, lrate=0.005, error=0.000\n >epoch=7838, lrate=0.005, error=0.000\n >epoch=7839, lrate=0.005, error=0.000\n >epoch=7840, lrate=0.005, error=0.000\n >epoch=7841, lrate=0.005, error=0.000\n >epoch=7842, lrate=0.005, error=0.000\n >epoch=7843, lrate=0.005, error=0.000\n >epoch=7844, lrate=0.005, error=0.000\n >epoch=7845, lrate=0.005, error=0.000\n >epoch=7846, lrate=0.005, error=0.000\n >epoch=7847, lrate=0.005, error=0.000\n >epoch=7848, lrate=0.005, error=0.000\n >epoch=7849, lrate=0.005, error=0.000\n >epoch=7850, lrate=0.005, error=0.000\n >epoch=7851, lrate=0.005, error=0.000\n >epoch=7852, lrate=0.005, error=0.000\n >epoch=7853, lrate=0.005, error=0.000\n >epoch=7854, lrate=0.005, error=0.000\n >epoch=7855, lrate=0.005, error=0.000\n >epoch=7856, lrate=0.005, error=0.000\n >epoch=7857, lrate=0.005, error=0.000\n >epoch=7858, lrate=0.005, error=0.000\n >epoch=7859, lrate=0.005, error=0.000\n >epoch=7860, lrate=0.005, error=0.000\n >epoch=7861, lrate=0.005, error=0.000\n >epoch=7862, lrate=0.005, error=0.000\n >epoch=7863, lrate=0.005, error=0.000\n >epoch=7864, lrate=0.005, error=0.000\n >epoch=7865, lrate=0.005, error=0.000\n >epoch=7866, lrate=0.005, error=0.000\n >epoch=7867, lrate=0.005, error=0.000\n >epoch=7868, lrate=0.005, error=0.000\n >epoch=7869, lrate=0.005, error=0.000\n >epoch=7870, lrate=0.005, error=0.000\n >epoch=7871, lrate=0.005, error=0.000\n >epoch=7872, lrate=0.005, error=0.000\n >epoch=7873, lrate=0.005, error=0.000\n >epoch=7874, lrate=0.005, error=0.000\n >epoch=7875, lrate=0.005, error=0.000\n >epoch=7876, lrate=0.005, error=0.000\n >epoch=7877, lrate=0.005, error=0.000\n >epoch=7878, lrate=0.005, error=0.000\n >epoch=7879, lrate=0.005, error=0.000\n >epoch=7880, lrate=0.005, error=0.000\n >epoch=7881, lrate=0.005, error=0.000\n >epoch=7882, lrate=0.005, error=0.000\n >epoch=7883, lrate=0.005, error=0.000\n >epoch=7884, lrate=0.005, error=0.000\n >epoch=7885, lrate=0.005, error=0.000\n >epoch=7886, lrate=0.005, error=0.000\n >epoch=7887, lrate=0.005, error=0.000\n >epoch=7888, lrate=0.005, error=0.000\n >epoch=7889, lrate=0.005, error=0.000\n >epoch=7890, lrate=0.005, error=0.000\n >epoch=7891, lrate=0.005, error=0.000\n >epoch=7892, lrate=0.005, error=0.000\n >epoch=7893, lrate=0.005, error=0.000\n >epoch=7894, lrate=0.005, error=0.000\n >epoch=7895, lrate=0.005, error=0.000\n >epoch=7896, lrate=0.005, error=0.000\n >epoch=7897, lrate=0.005, error=0.000\n >epoch=7898, lrate=0.005, error=0.000\n >epoch=7899, lrate=0.005, error=0.000\n >epoch=7900, lrate=0.005, error=0.000\n >epoch=7901, lrate=0.005, error=0.000\n >epoch=7902, lrate=0.005, error=0.000\n >epoch=7903, lrate=0.005, error=0.000\n >epoch=7904, lrate=0.005, error=0.000\n >epoch=7905, lrate=0.005, error=0.000\n >epoch=7906, lrate=0.005, error=0.000\n >epoch=7907, lrate=0.005, error=0.000\n >epoch=7908, lrate=0.005, error=0.000\n >epoch=7909, lrate=0.005, error=0.000\n >epoch=7910, lrate=0.005, error=0.000\n >epoch=7911, lrate=0.005, error=0.000\n >epoch=7912, lrate=0.005, error=0.000\n >epoch=7913, lrate=0.005, error=0.000\n >epoch=7914, lrate=0.005, error=0.000\n >epoch=7915, lrate=0.005, error=0.000\n >epoch=7916, lrate=0.005, error=0.000\n >epoch=7917, lrate=0.005, error=0.000\n >epoch=7918, lrate=0.005, error=0.000\n >epoch=7919, lrate=0.005, error=0.000\n >epoch=7920, lrate=0.005, error=0.000\n >epoch=7921, lrate=0.005, error=0.000\n >epoch=7922, lrate=0.005, error=0.000\n >epoch=7923, lrate=0.005, error=0.000\n >epoch=7924, lrate=0.005, error=0.000\n >epoch=7925, lrate=0.005, error=0.000\n >epoch=7926, lrate=0.005, error=0.000\n >epoch=7927, lrate=0.005, error=0.000\n >epoch=7928, lrate=0.005, error=0.000\n >epoch=7929, lrate=0.005, error=0.000\n >epoch=7930, lrate=0.005, error=0.000\n >epoch=7931, lrate=0.005, error=0.000\n >epoch=7932, lrate=0.005, error=0.000\n >epoch=7933, lrate=0.005, error=0.000\n >epoch=7934, lrate=0.005, error=0.000\n >epoch=7935, lrate=0.005, error=0.000\n >epoch=7936, lrate=0.005, error=0.000\n >epoch=7937, lrate=0.005, error=0.000\n >epoch=7938, lrate=0.005, error=0.000\n >epoch=7939, lrate=0.005, error=0.000\n >epoch=7940, lrate=0.005, error=0.000\n >epoch=7941, lrate=0.005, error=0.000\n >epoch=7942, lrate=0.005, error=0.000\n >epoch=7943, lrate=0.005, error=0.000\n >epoch=7944, lrate=0.005, error=0.000\n >epoch=7945, lrate=0.005, error=0.000\n >epoch=7946, lrate=0.005, error=0.000\n >epoch=7947, lrate=0.005, error=0.000\n >epoch=7948, lrate=0.005, error=0.000\n >epoch=7949, lrate=0.005, error=0.000\n >epoch=7950, lrate=0.005, error=0.000\n >epoch=7951, lrate=0.005, error=0.000\n >epoch=7952, lrate=0.005, error=0.000\n >epoch=7953, lrate=0.005, error=0.000\n >epoch=7954, lrate=0.005, error=0.000\n >epoch=7955, lrate=0.005, error=0.000\n >epoch=7956, lrate=0.005, error=0.000\n >epoch=7957, lrate=0.005, error=0.000\n >epoch=7958, lrate=0.005, error=0.000\n >epoch=7959, lrate=0.005, error=0.000\n >epoch=7960, lrate=0.005, error=0.000\n >epoch=7961, lrate=0.005, error=0.000\n >epoch=7962, lrate=0.005, error=0.000\n >epoch=7963, lrate=0.005, error=0.000\n >epoch=7964, lrate=0.005, error=0.000\n >epoch=7965, lrate=0.005, error=0.000\n >epoch=7966, lrate=0.005, error=0.000\n >epoch=7967, lrate=0.005, error=0.000\n >epoch=7968, lrate=0.005, error=0.000\n >epoch=7969, lrate=0.005, error=0.000\n >epoch=7970, lrate=0.005, error=0.000\n >epoch=7971, lrate=0.005, error=0.000\n >epoch=7972, lrate=0.005, error=0.000\n >epoch=7973, lrate=0.005, error=0.000\n >epoch=7974, lrate=0.005, error=0.000\n >epoch=7975, lrate=0.005, error=0.000\n >epoch=7976, lrate=0.005, error=0.000\n >epoch=7977, lrate=0.005, error=0.000\n >epoch=7978, lrate=0.005, error=0.000\n >epoch=7979, lrate=0.005, error=0.000\n >epoch=7980, lrate=0.005, error=0.000\n >epoch=7981, lrate=0.005, error=0.000\n >epoch=7982, lrate=0.005, error=0.000\n >epoch=7983, lrate=0.005, error=0.000\n >epoch=7984, lrate=0.005, error=0.000\n >epoch=7985, lrate=0.005, error=0.000\n >epoch=7986, lrate=0.005, error=0.000\n >epoch=7987, lrate=0.005, error=0.000\n >epoch=7988, lrate=0.005, error=0.000\n >epoch=7989, lrate=0.005, error=0.000\n >epoch=7990, lrate=0.005, error=0.000\n >epoch=7991, lrate=0.005, error=0.000\n >epoch=7992, lrate=0.005, error=0.000\n >epoch=7993, lrate=0.005, error=0.000\n >epoch=7994, lrate=0.005, error=0.000\n >epoch=7995, lrate=0.005, error=0.000\n >epoch=7996, lrate=0.005, error=0.000\n >epoch=7997, lrate=0.005, error=0.000\n >epoch=7998, lrate=0.005, error=0.000\n >epoch=7999, lrate=0.005, error=0.000\n intercept: 6.998228695360654\n coeff: [1.0000383592190238, 5.000055846375979]\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "7eaa013600be6f07f9446de3cbf56f8fddb5950a", "size": 803214, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "gradient_descent.ipynb", "max_stars_repo_name": "louis-xu-ustc/machine_learning_basics", "max_stars_repo_head_hexsha": "92839d0c24c469ff0094e6027a8d34313b87312f", "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": "gradient_descent.ipynb", "max_issues_repo_name": "louis-xu-ustc/machine_learning_basics", "max_issues_repo_head_hexsha": "92839d0c24c469ff0094e6027a8d34313b87312f", "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": "gradient_descent.ipynb", "max_forks_repo_name": "louis-xu-ustc/machine_learning_basics", "max_forks_repo_head_hexsha": "92839d0c24c469ff0094e6027a8d34313b87312f", "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": 80.1530785351, "max_line_length": 215110, "alphanum_fraction": 0.7228621513, "converted": true, "num_tokens": 180713, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582554941719, "lm_q2_score": 0.9314625102975306, "lm_q1q2_score": 0.8666869823896625}} {"text": "# Notes\n\nHere I will present a couple of notes and important concepts that I deem necessary or important. This is, after all, an attempt to teach myself Dynamical Systems so I would like to have these concepts in a handy place.\n\n## Concepts\n\n1. **Flow:** Where is the system moving towards? Given a system\n\n $$\\dot{x} = f(x) $$\n \n the _flow_ will be moving towards the **right** if $\\dot{x} > 0$ and towards the **left** if $\\dot{x} < 0.$\n \n2. **Fixed points:** Every point where there is **no flow**, i.e. $\\dot{x} = 0.$ There can be two types of _fixed points:_\n \n a. **Stable:** _flow_ is **towards them**, and they are also called _attractors_ or _sinks._\n \n b. **Unstable:** _flow_ moves **away from them**, and they are also known as _repellers_ or _sources._\n\n### Exercise 2.1.\n\nIn the next three exercises, interpret $$\\dot{x} = \\sin{x}$$ as a _flow_ on the line.\n\n### 2.1.1. Find all the fixed points of the flow.\n\nTo answer this question one must find all values that satisfy\n$$\\dot{x} = \\sin{x} = 0,$$\n**analytically** it's quite simple, one must solve\n$$\\sin{x} = 0$$\nwhich has solutions\n$$x = n \\pi ,\\ n \\in \\mathbb{Z}.$$\n\n\n```julia\n# Numerically, one can find the roots and plot them\n# First, import the necessary libraries\nusing Roots\nusing Plots\nusing LaTeXStrings\npyplot()\n```\n\n\n\n\n Plots.PyPlotBackend()\n\n\n\n\n```julia\n# Define the function\nf(x) = sin(x)\n# Find all the zeros of this function within the interval\n# x ∈ [-10π, 10π]\nsolutions = fzeros(f, -5π, 5π)\n```\n\n\n\n\n 11-element Array{Float64,1}:\n -15.707963267948966\n -12.566370614359172\n -9.42477796076938 \n -6.283185307179586\n -3.141592653589793\n 0.0 \n 3.141592653589793\n 6.283185307179586\n 9.42477796076938 \n 12.566370614359172\n 15.707963267948966\n\n\n\nHere we can see that our analytical result is right, every zero from this function is an integer multiple of $\\pi,$ which is the desired result.\n\nWe can now plot this in order to see a picture of the expected result.\n\n\n```julia\n# Now we plot these points\nx_vals = range(-5π, 5π, length=500)\nplot(x_vals, f.(x_vals), lab = L\"sin(x)\", leg = :topright)\n# This is a black line for reference, just to know where zero is\nplot!(x_vals, zeros(length(x_vals)), color = :black, lab = \"Reference\")\n# And these are the fixed points.\nscatter!(solutions, zeros(length(solutions)), marker = (:hexagon, 10, :red), lab = \"Fixed Points\")\n```\n\nJust a quick note about the _fixed points_ we just found. These points are both the **stable** and **unstable** _fixed points_, we are not making a difference between them in this plot.\n\n### 2.1.2. At which points $x$ does the flow have greatest velocity to the right?\n\nRecall that in the book we have the following picture.\n\n\n```julia\n# Create a new set of solutions, a smaller set\nsolutions = fzeros(f, -3π, 3π)\n# Now we plot these points\nx_vals = range(-3π, 3π, length=500)\nplot(x_vals, f.(x_vals), lab = L\"sin(x)\", leg = :topright)\n# This is a black line for reference, just to know where zero is\nplot!(x_vals, zeros(length(x_vals)), color = :black, lab = \"Reference\")\n\n# Create the \"attractors\"\nattractors = zeros(length(solutions))\nfor i = 1:length(solutions)\n # We round to nearest to also incluse negative values\n attractors[i] = rem2pi(solutions[i], RoundNearest)\nend\nscatter!(attractors, zeros(length(solutions)), marker = (:circle, 10, :green), lab = \"Attractors\")\n\n# And now create the \"sinks\"\nsinks = zeros(length(solutions))\nfor i = 1:length(solutions)\n # Every other value from the attractors, also rounded to nearest\n sinks[i] = 2*rem2pi(solutions[i], RoundNearest)\nend\nscatter!(sinks, zeros(length(solutions)), marker = (:hexagon, 10, :red), lab = \"Sinks\")\n\n# Create arrows to the left\nl_arr = range(-5π/2, stop=3π/2, step=2π)\nscatter!(l_arr, zeros(length(l_arr)), marker = (:ltriangle, 20, :black), lab = \"Flow Left\")\n# Create arrows to the right\nr_arr = range(-3π/2, stop=5π/2, step=2π)\nscatter!(r_arr, zeros(length(r_arr)), marker = (:rtriangle, 20, :black), lab = \"Flow Right\")\n```\n\nMaybe not as pretty as the original, but the idea here is that we must observe the values where the _flow_ has _greatest_ velocity to the **right,** but we have already done this while plotting this graph!\n\nHow? Recall that while the _flow_ is leaving a _source_ it starts to speed up quite quickly until it reaches a certain value. Can you spot it? It corresponds to the values where the **right arrows** are **plotted**, thus the **local maximum** within every period.\n\nThis is $$x = \\frac{\\pi}{2}, \\frac{3\\pi}{2},\\frac{5\\pi}{2}, \\cdots ,$$\nand so on, or in a simplified expression,\n$$ x = \\frac{n \\pi}{2},\\quad n \\in \\mathbb{Z}.$$\n\n### 2.1.3. a) Find the flow's acceleration $\\ddot{x}$ as a function of $x.$\n\nSo part _a_ is quite simple, we are asked to differentiate one time the system in question. From the fundamental rules of calculus we have:\n\\begin{equation}\n\\frac{d}{dx} \\left( \\dot{x} = \\sin{x} \\right),\\quad \\text{differentiation is associative} \\\\\n\\frac{d}{dx} \\dot{x} = \\frac{d}{dx} \\sin{x},\\quad \\text{we then apply the chain rule} \\\\\n\\ddot{x} = \\dot{x} \\cos{x}, \\quad \\text{and substituting back the original equation} \\\\\n\\ddot{x} = \\sin{x} \\cos{x},\\quad \\text{finally, using}\\ 2 \\sin{x} \\cos{x} = \\sin{2x}\\ \\text{we have} \\\\\n\\ddot{x} = \\frac{1}{2} \\sin{2x}\n\\end{equation}\n\n\n```julia\n# Is it possible to do it in Julia? Yes, at least using SymPy\nusing SymPy\n\n# First, define the needed symbols\nx = Symbol(\"x\")\ny = sympy.sin(x)\nF = sympy.Function(\"f\")\n```\n\n\n\n\n PyObject f\n\n\n\nA quick note here. It turns out that we [_cannot_](https://docs.sympy.org/latest/modules/core.html?highlight=function#derivative) (or maybe I'm wrong all along) create a symbolic derivative when the function depends on another variable. In other words, because we are performing _implicit differentiation_ given a function, SymPy cannot handle this and we must do the chain rule by hand.\n\n\n```julia\n# First, we find the first derivative, i.e. the velocity\ndf = diff(F(x))\n```\n\n\n\n\n\\begin{equation*}\\frac{d}{d x} f{\\left (x \\right )}\\end{equation*}\n\n\n\n\n```julia\n# We apply the chain rule to the LHS of the equation\nchain = diff(y) * df\n```\n\n\n\n\n\\begin{equation*}\\cos{\\left (x \\right )} \\frac{d}{d x} f{\\left (x \\right )}\\end{equation*}\n\n\n\n\n```julia\n# We then differentiate once more, and add the chain result\n# so we obtain f''(x) - g(x) = 0\nres = diff(df) - chain\n# And finally we simplify the expression\nres.subs(df, y).simplify()\n```\n\n\n\n\n\\begin{equation*}- \\frac{\\sin{\\left (2 x \\right )}}{2} + \\frac{d}{d x} \\sin{\\left (x \\right )}\\end{equation*}\n\n\n\nThis is the answer we are looking for, nicely formatted in $\\LaTeX$. Not bad at all. We cannot readily evaluate this function though, we need to solve the equation in order to do so but there is no need here.\n\n### b) Find the points where the flow has maximum positive acceleration.\n\nThis is exactly as before, but now we have a different expression. To see what I mean, we are asked to find all points such that the following expression\n$$ \\ddot{x} = \\frac{1}{2} \\sin{2x} = 0 $$\nis satisfied. But recall that this is just finding the _fixed points_, and we are asked the **local maximum** within each interval.\n\nFirst, analitycally we have the following\n\\begin{equation}\n\\frac{1}{2} \\sin{2x} = 0,\\quad \\text{this is equivalent to} \\\\\n\\sin{2x} = 0 .\n\\end{equation}\n\nSo, to find the _local maxima_ we can differentiate the previous expression once and find the zeros of the new function. This will yield all _inflection points_ and we can apply either the _first_ or the _second_ derivative test. I prefer the _second derivative test._\n\n\\begin{equation}\nf'(x) = \\frac{d}{dx} \\left( \\sin{2x} = 0 \\right), \\\\\nf'(x) = \\frac{d}{dx} \\left( \\sin{2x} \\right) = 2 \\cos{2x} = 0 . \\\\\n\\end{equation}\n\nWe now find the zeros of the latter expression, which is quite simple because we have\n\\begin{equation}\n2x = n \\pi + \\frac{\\pi}{2}, \\\\\nx = \\frac{n \\pi}{2} + \\frac{\\pi}{4},\\quad n \\in \\mathbb{Z} .\n\\end{equation}\n\nThese are the _inflection points_, and we now proceed to differentiate once more to apply the _second derivative test._\n\n\\begin{equation}\nf''(x) = \\frac{df'(x)}{dx} = \\frac{d}{dx} \\left( 2 \\cos{2x} \\right), \\\\\nf''(x) = -4 \\sin{2x}\n\\end{equation}\n\nand with this expression in hand we evaluate the _inflection points_ found earlier. But notice that we actually have an infinite number, so we will only do the test with two of them, when $n$ is _odd_ and when $n$ is _even._\n\nWithout loss of generality, take $n = 0$ to be the _even_ value, then\n$$f''(0) = -4 \\sin{(0 + \\pi / 2)} = -4$$\nand because this value is negative, i.e. $f''(x_o) < 0$, we actually have a **local maximum.**\n\nAgain, without loss of generality, take $n = 1$ to be the _odd_ value, then\n$$f''(0) = -4 \\sin{(\\pi + \\pi/2)} = 4$$\nand we have a positive value, i.e. $f''(x_o) > 0$, we actually have a **local minimum.**\n\nBut remember that we only want the _greatest acceleration values_, so we keep only half of the _inflection points_, onyl those that yield **local maximum**, so the actual answer is\n\n$$x = \\frac{n \\pi}{2} + \\frac{n \\pi}{2} + \\frac{\\pi}{4} = n \\pi + \\frac{\\pi}{4},\\quad n \\in \\mathbb{Z} ,$$\n\nwhere I add half a period to skip over all the _mimima._\n\nCan we do this in _Julia_? Well, of course! By using [Optim.jl](http://julianlsolvers.github.io/Optim.jl/stable/#).\n\n\n```julia\n# Import Optim, be sure to check the documentation for more\n# info on the library.\nusing Optim\n```\n\n\n```julia\n# Define the LHS of the original expression\n# but multiply by -1 to define the function to maximize.\nf(x) = -0.5*sin(2.0*x)\n\n# Define some starting points\nx0 = 0.0:10.0\n# Create an array to store the results\nresults = zeros(length(x0))\n\n# Call the optimization routine from Optim\nfor (i, j) in enumerate(x0)\n # I use Simulated Annealing just for fun, it's a cool algorithm\n res = optimize(x->f(first(x)), [j], SimulatedAnnealing())\n # Store the value that minimize the function\n results[i] = first(Optim.minimizer(res))\nend\n```\n\n\n```julia\n# Sort the values and print them\nsort(results)\n```\n\n\n\n\n 11-element Array{Float64,1}:\n -11.781148353042045 \n -5.498234272779726 \n -5.4974772128143625\n -5.495061887961648 \n -2.3560419723502397\n -2.3533994926713073\n 3.9259440648999857\n 3.926360610564821 \n 3.9278604127942196\n 7.061749767097781 \n 10.211715679558322 \n\n\n\nYou can actually see that these are the values we were looking for. Try pluggin in a few integers in the expression we found before\n\n$$ n \\pi + \\frac{\\pi}{4},\\quad n \\in \\mathbb{Z} $$\n\nand you will see what I mean.\n\nI will explain briefly what I did here. So `Optim.jl` actually minimizes a multivariate function using one of several optimization algorithms defined in the library. First, I had to redefine the original function by multiplying it by -1 so the problem is now a maximization problem. Second, I defined a few initial points for the search because there are infinite number of maximum values for the expression. And at the end I just stored the values in an array and sorted them to get a better picture. You should notice that most of the values are repeated and this is fine, it's expected behavior, it's actually my fault for not defining specific search intervals.\n\nA *note* on **simulated annealing:** I chose this algorithm because it actually hits home for me as a physicist, and because it's actually a perfect fit for this problem. This algorithm is based on statistical mechanics as shown in the [original paper](https://sci2s.ugr.es/sites/default/files/files/Teaching/GraduatesCourses/Metaheuristicas/Bibliography/1983-Science-Kirkpatrick-sim_anneal.pdf)\nand statistical mechanics is the branch of physics I specialized when doing my undergraduate degree. But aside from that, it works fantastically well when there are no _global optima_ such as this problem.\n\n[This](http://katrinaeg.com/simulated-annealing.html) is a more fitting introduction to this algorithm if you are interested.\n\n## 2.1.4. a) Given $x_0 = \\pi /4$ show that the solution is\n$$x(t) = 2 \\tan^{-1}{\\left( \\frac{e^t}{\\sqrt{2} + 1} \\right)} .$$\nConclude that $x(t) \\to \\pi$ as $t \\to \\infty.$\n\nTo find the solution, we need to solve the original differential equations. But wait, it's already solved, and we alredy have the solution.\n\n$$ t = \\log{\\left| \\frac{\\csc{x_0} \\cdot \\cot{x_0}}{\\csc{x} \\cdot \\cot{x}} \\right|}$$\n\nAnd from this expression we can plug in the initial conditions so we have the following new expression\n\n\\begin{equation}\nt = \\log{\\left| \\frac{\\csc{\\pi/4} \\cdot \\cot{\\pi/4}}{\\csc{x} \\cdot \\cot{x}} \\right|},\\quad\n\\text{which is equivalent to} \\\\\nt = \\log{\\left| \\frac{\\sqrt{2} + 1}{\\csc{x} \\cdot \\cot{x}} \\right|}, \n\\end{equation}\n\nand doing some basic algebra we arrive at the following expression\n\n$$\\frac{1}{\\csc{x} \\cdot \\cot{x}} = \\frac{e^t}{\\sqrt{2} + 1}$$\n\nand using the trigonometric identity $\\csc{x} \\cdot \\cot{x} = \\cot{x/2}$\n\nwe have the final answer:\n\n\\begin{equation}\n\\frac{1}{\\csc{x} \\cdot \\cot{x}} = \\frac{e^t}{\\sqrt{2} + 1} = \\\\\n= \\frac{1}{\\cot{\\frac{x}{2}}} = \\frac{e^t}{\\sqrt{2} + 1} = \\\\\n= \\tan{\\frac{x}{2}} = \\frac{e^t}{\\sqrt{2} + 1}, \\\\\nx(t) = 2\\tan^{-1}{\\frac{e^t}{\\sqrt{2} + 1}}\n\\end{equation}\n\nLastly, we must show that $x(t) \\to \\pi$ as $t \\to \\infty,$ in order to do this we must do one more algebraic manipulation to the final solution.\n\nStart with the following expression\n\n$$\\frac{1}{\\cot{\\frac{x}{2}}} = \\frac{e^t}{\\sqrt{2} + 1}$$\n\nand by inverting the whole expression we arrive at the following\n\n\\begin{equation}\n\\frac{1}{\\cot{\\frac{x}{2}}} = \\frac{e^t}{\\sqrt{2} + 1} = \\\\\n= \\cot{\\frac{x}{2}} = e^{-t} (\\sqrt{2} + 1), \\\\\nx(t) = 2\\cot^{-1}{\\left( e^{-t} (\\sqrt{2} + 1) \\right) } .\n\\end{equation}\n\nWith this last expression we now evaluate the following limit\n\n\\begin{equation}\n\\lim_{t \\to \\infty}{x(t)} = \\lim_{t \\to \\infty}{2\\cot^{-1}{\\left( e^{-t} (\\sqrt{2} + 1) \\right) }},\n\\quad \\text{and by the properties of limits in continuous functions we have} \\\\\n\\lim_{t \\to \\infty}{x(t)} = 2\\cot^{-1}{\\left((\\sqrt{2} + 1) \\lim_{t \\to \\infty}{e^{-t}} \\right) },\n\\quad \\text{and this evaluates to zero, hence} \\\\\n\\lim_{t \\to \\infty}{x(t)} = 2\\cot^{-1}{(0)} = 2 \\cdot \\frac{\\pi}{2} = \\pi\n\\end{equation}\n\nand this is the expected result.\n\n### b)\nThe analytical solution for any _arbitrary_ condition is as simple as\n\n$$x(t) = 2\\tan^{-1}{\\left( \\frac{e^t}{\\csc{x_0} \\cdot \\cot{x_0}} \\right)}$$\n\nwhere we can plug in any such condition provided that $\\csc{x_0} \\cdot \\cot{x_0} \\neq 0$ and we have a solution.\n\nLet's do this now in Julia. There are several options here, one is to keep using `SymPy.jl` and solve the symbolic problem. The approach I will do here is purely numerical, by using [DifferentialEquations.jl](https://docs.juliadiffeq.org/latest/index.html).\n\n\n```julia\n# Import the library\nusing DifferentialEquations\n```\n\n\n```julia\n# The API demands to create a three-variable function for the LHS of the\n# ODE problem\nh(x, p, t) = sin(x)\n# Define the initial conditions\nx0 = pi/4\n# Create a tuple for the time span\ntspan = (0.0, 10.0)\n# Create and ODEProblem as defined in the documentation\nprob = ODEProblem(h, x0, tspan)\n# Solve the problem\nsol = DifferentialEquations.solve(prob, reltol=1e-8, abstol=1e-8)\n# Plot the results\nplot(sol, lab = \"Numerical solution\", ylabel=L\"x(t)\")\n# Define the analytical solution and plot it as well\ntrue_val(x) = 2.0*atan(exp(x)/(sqrt(2)+1))\nplot!(sol.t, true_val.(sol.t), lw=3, ls=:dash, lab = \"True value\")\n```\n\nWe may not have the analytical expression with this approach, but it is amazing how precise it is (but don't forget we are skipping over the approximation errors).\n\nI think this approach is more beautiful in a sense, we may not know anything about the problem, it might be even hard (or impossible) to solve analytically, but numerical analysis never fails, and `DifferentialEquations.jl` is actually a very mature, fast and performant library. This will be our workhorse throughout the entire journey.\n\nIn closing, instead of doing the analytical evaluation of the limit, have a closer look at the plot.\n\nCan you see that, as time passes by, $x(t)$ approaches the value of $\\pi$?\n\nAnd it's not even in a very long period of time, you can actually see the value of pi being steady as quick as when $t = 6.$ If we only knew how to code we need only the problem and the initial conditions and by looking at the graph everything would be clear, we would have all the information we needed without even knowing Calculus!\n\n\n```julia\n\n```\n", "meta": {"hexsha": "57511964b532cdfb0002a64d16bef64a968dee04", "size": 136240, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "ch-02/Exercise-2.1.ipynb", "max_stars_repo_name": "edwinb-ai/nonlinear-dynamics", "max_stars_repo_head_hexsha": "178e283870fa77362d7034c0fb6f4d1da332755a", "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": "ch-02/Exercise-2.1.ipynb", "max_issues_repo_name": "edwinb-ai/nonlinear-dynamics", "max_issues_repo_head_hexsha": "178e283870fa77362d7034c0fb6f4d1da332755a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-10-17T00:07:57.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-17T00:07:57.000Z", "max_forks_repo_path": "ch-02/Exercise-2.1.ipynb", "max_forks_repo_name": "edwinb-ai/nonlinear-dynamics", "max_forks_repo_head_hexsha": "178e283870fa77362d7034c0fb6f4d1da332755a", "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": 201.837037037, "max_line_length": 43965, "alphanum_fraction": 0.8952216676, "converted": true, "num_tokens": 5073, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088025362857, "lm_q2_score": 0.9334308101035739, "lm_q1q2_score": 0.866605380658734}} {"text": "Load libraries and set up environment\n\n\n```python\nimport sympy\nsympy.init_printing()\n```\n\nWe consider two gravitating point objects with masses $M_1$ and $M_2$, separated by a distance $a$. The orbital frequency is given by $\\Omega = \\sqrt{G \\left(M_1 + M_2\\right)/a^3}$.\n\nThe energy is given by\n\n\n```python\nM_1 = sympy.Symbol('M_1', positive=True)\nM_2 = sympy.Symbol('M_2', positive=True)\na = sympy.Symbol('a', positive=True)\nOmega = sympy.Symbol('Omega', positive=True) # Orbital frequency\nG = sympy.Symbol('G', positive=True) # Gravitation constant\ntemp = -G*M_1*M_2/a + M_1*(Omega*a*M_2/(M_1+M_2))**2/2 + M_2*(Omega*a*M_1/(M_1+M_2))**2\ntemp = temp.subs(Omega, sympy.sqrt(G*(M_1+M_2)/a**3))\nbefore_energy = temp.simplify()\nbefore_energy\n```\n\nThe angular momentum is given by\n\n\n```python\ntemp = M_1*Omega*(a*M_2/(M_1+M_2))**2 + M_2*Omega*(a*M_1/(M_1+M_2))**2\ntemp = temp.subs(Omega, sympy.sqrt(G*(M_1+M_2)/a**3))\nbefore_angular_momentum = temp.simplify()\nbefore_angular_momentum\n```\n\nNow suppose that body $M_1$ undergoes an explosion. This explosion has two effects which change the orbit. First, $M_1$ expels some of its mass, so the mass of the remaining body is $\\chi M_1$. Second, $M_1$ receives a kick. The magnitude of the kick velocity is $v_n$ (where subscript $n$ stands for natal kick, instead of subscript $k$, which might be confused with the Keplerian velocity). We denote the angle between the kick velocity and the angular momentum by $\\theta$, and the angle between the kick velocity and the orbital velocity before the explosion, in the plane of motion, by $\\phi$. We proceed to calculate the new energy and angular momentum.\n\n\n```python\nbefore_velocity_vector = sympy.Matrix([Omega*a*M_2/(M_1+M_2),0,0]).subs(Omega, sympy.sqrt(G*(M_1+M_2)/a**3))\nbefore_velocity_vector\n```\n\n\n```python\nv_n = sympy.Symbol('v_n', positive=True)\ntheta = sympy.Symbol('theta', positive=True)\nphi = sympy.Symbol('phi', positive=True)\nkick_velocity_vector = v_n*sympy.Matrix([sympy.sin(theta)*sympy.cos(phi), \n sympy.sin(theta)*sympy.sin(phi), \n sympy.cos(theta)])\nkick_velocity_vector\n```\n\n\n```python\nafter_velocity_vector = before_velocity_vector+kick_velocity_vector\nchi = sympy.Symbol('chi', positive=True)\ntemp = -G*M_1*M_2*chi/a + M_2*(Omega*a*M_1/(M_1+M_2))**2/2 + after_velocity_vector.dot(after_velocity_vector)*chi*M_1/2\ntemp = temp.subs(Omega, sympy.sqrt(G*(M_1+M_2)/a**3))\nafter_energy = temp\nafter_energy\n```\n\n\n```python\nafter_velocity_vector.dot(after_velocity_vector)\n```\n\n\n```python\nafter_L_x = chi*M_1*after_velocity_vector[2]*a*M_2/(M_1+M_2)\nafter_L_x\n```\n\n\n```python\ntemp = chi*M_1*after_velocity_vector[0]*a*M_2/(M_1+M_2) + M_2*Omega*(a*M_1/(M_1+M_2))**2\ntemp = temp.subs(Omega, sympy.sqrt(G*(M_1+M_2)/a**3))\nafter_L_z = temp\nafter_L_z\n```\n\n\n```python\nafter_angular_momentum = sympy.sqrt(after_L_x**2 + after_L_z**2)\nafter_angular_momentum\n```\n\n# Keplerian orbit parameters\n\nWe begin with a short derivation of the Keplerian orbit parameters. The vector equations of motion for the two masses are\n\n$\\ddot{\\mathbf{R}}_1 = \\frac{G M_2}{|\\mathbf{R}_2 - \\mathbf{R}_1|^3} \\left(\\mathbf{R}_2 - \\mathbf{R}_1 \\right)$\n\n$\\ddot{\\mathbf{R}}_2 = -\\frac{G M_1}{|\\mathbf{R}_2 - \\mathbf{R}_1|^3} \\left(\\mathbf{R}_2 - \\mathbf{R}_1 \\right)$\n\nWe don't care about centre of mass motion, so $M_1 \\mathbf{R}_1 + M_2 \\mathbf{R}_2 = 0$. We want to express the equation of motion in terms of the difference between the two position vectors $\\mathbf{r} = \\mathbf{R}_2 - \\mathbf{R}_1$. Expressing the two positions in terms of the position difference\n\n\n$\\mathbf{R}_1 = -\\frac{M_2}{M_1 + M_2} \\mathbf{r}$\n\n$\\mathbf{R}_2 = \\frac{M_1}{M_1+M_2} \\mathbf{r}$\n\nSubstituting into either equation of motion yields\n\n$\\ddot{\\mathbf{r}} = - \\frac{G \\left(M_1 + M_2 \\right)}{r^3} \\mathbf{r}$\n\nThis substitution reduces the problem to the degenerate Kepler problem, where a test particle goes around a much more massive body with mass $M_1 + M_2$. The solution is\n\n$r = \\frac{r_l}{1 + e \\cos \\theta}$\n\nConservation of angular momentum\n\n$L = M_1 R_1^2 \\dot{\\theta} + M_2 R_2^2 \\dot{\\theta}$\n\n\n```python\nR_1 = sympy.Symbol('R_1', positive=True)\nR_2 = sympy.Symbol('R_2', positive=True)\nr = sympy.Symbol('r', positive=True)\nL = sympy.Symbol('L', positive=True)\nt = sympy.Symbol('t', positive=True)\ntemp = M_1*R_1**2*sympy.Derivative(theta,t)+M_2*R_2**2*sympy.Derivative(theta,t)\ntemp = temp.subs(R_1, -r*M_2/(M_1+M_2))\ntemp = temp.subs(R_2, r*M_1/(M_1+M_2))\ntemp = temp.simplify()\nkeplerian_angular_momentum = sympy.Eq(temp,L)\nkeplerian_angular_momentum\n```\n\nEnergy conservation\n\n$U = - \\frac{G M_1 M_2}{r} + \\frac{1}{2} M_1 \\left(\\dot{R}_1^2 + R_1^2 \\dot{\\theta}^2 \\right) + \\frac{1}{2} M_2 \\left( \\dot{R}_2^2 + R_2^2 \\dot{\\theta}^2 \\right)$\n\n\n```python\ne = sympy.Symbol('e', positive=True)\nr_l = sympy.Symbol('r_l', positive=True)\nU = sympy.Symbol('U')\ntemp = (-G*M_1*M_2/r+\n M_1*(sympy.Derivative(R_1,t)**2+R_1**2*sympy.Derivative(theta,t)**2)/2+\n M_2*(sympy.Derivative(R_2,t)**2+R_2**2*sympy.Derivative(theta,t)**2)/2)\ntemp = temp.subs(sympy.Derivative(R_1, t), sympy.Derivative(R_1, theta)*sympy.Derivative(theta, t))\ntemp = temp.subs(sympy.Derivative(R_2, t), sympy.Derivative(R_2, theta)*sympy.Derivative(theta, t))\ntemp = temp.subs(sympy.solve(keplerian_angular_momentum, sympy.Derivative(theta, t), dict=True)[0])\ntemp = temp.subs(R_1, -r*M_2/(M_1+M_2))\ntemp = temp.subs(R_2, r*M_1/(M_1+M_2))\ntemp = temp.subs(r, r_l/(1+e*sympy.cos(theta)))\ntemp = temp.doit()\ntemp = sympy.Eq(U, temp.simplify())\nkeplerian_orbit_parameters = sympy.solve([temp.subs(theta,0), temp.subs(theta, sympy.pi/2)], [e, r_l], dict=True)[1]\nkeplerian_orbit_parameters\n```\n\nThe semi major axis is given by $a = \\frac{r_l}{1-e^2}$\n\n\n```python\n\n```\n", "meta": {"hexsha": "610b208e46ce248659738021abdb472ba1b5e419", "size": 58258, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "natal_kicks.ipynb", "max_stars_repo_name": "bolverk/gaia_black_hole_binaries", "max_stars_repo_head_hexsha": "966c35cf122e46923fcb8c0b4d9a6bbb66174751", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-06-30T01:15:10.000Z", "max_stars_repo_stars_event_max_datetime": "2018-06-30T01:15:10.000Z", "max_issues_repo_path": "natal_kicks.ipynb", "max_issues_repo_name": "bolverk/gaia_black_hole_binaries", "max_issues_repo_head_hexsha": "966c35cf122e46923fcb8c0b4d9a6bbb66174751", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2017-11-09T18:46:04.000Z", "max_issues_repo_issues_event_max_datetime": "2018-02-16T16:53:52.000Z", "max_forks_repo_path": "natal_kicks.ipynb", "max_forks_repo_name": "bolverk/gaia_black_hole_binaries", "max_forks_repo_head_hexsha": "966c35cf122e46923fcb8c0b4d9a6bbb66174751", "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.9279588336, "max_line_length": 7926, "alphanum_fraction": 0.784613272, "converted": true, "num_tokens": 2045, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9669140216112958, "lm_q2_score": 0.8962513738264114, "lm_q1q2_score": 0.8665980202411443}} {"text": "

Solvers

\n\n

From

\n\n\n```julia\n >>> from sympy import *\n >>> x, y, z = symbols(\"x y z\")\n >>> init_printing(use_unicode=True)\n```\n\n
In Julia:
\n\n\n```julia\nusing SymPy\nx, y, z = symbols(\"x y z\")\n```\n\n\n\n\n (x, y, z)\n\n\n\n
\n\n

A Note about Equations

\n\n

Recall from the :ref:gotchas <tutorial_gotchas_equals> section of this tutorial that symbolic equations in SymPy are not represented by = or ==, but by Eq.

\n\n\n```julia\n >>> Eq(x, y)\n x = y\n```\n\n
In Julia:
\n\n\n```julia\nEq(x, y)\n```\n\n\n\n\n\\begin{equation*}x = y\\end{equation*}\n\n\n\n
\n\n

However, there is an even easier way. In SymPy, any expression not in an Eq is automatically assumed to equal 0 by the solving functions. Since a = b if and only if a - b = 0, this means that instead of using x == y, you can just use x - y. For example

\n\n\n```julia\n >>> solveset(Eq(x**2, 1), x)\n {-1, 1}\n >>> solveset(Eq(x**2 - 1, 0), x)\n {-1, 1}\n >>> solveset(x**2 - 1, x)\n {-1, 1}\n```\n\n
In Julia:
\n\n\n```julia\nsolveset(Eq(x^2, 1), x)\n```\n\n\n\n\n\\begin{equation*}\\left\\{-1, 1\\right\\}\\end{equation*}\n\n\n\n\n```julia\nsolveset(Eq(x^2 - 1, 0), x)\n```\n\n\n\n\n\\begin{equation*}\\left\\{-1, 1\\right\\}\\end{equation*}\n\n\n\n\n```julia\nsolveset(x^2 - 1, x)\n```\n\n\n\n\n\\begin{equation*}\\left\\{-1, 1\\right\\}\\end{equation*}\n\n\n\n
\n\n

This is particularly useful if the equation you wish to solve is already equal to 0. Instead of typing solveset(Eq(expr, 0), x), you can just use solveset(expr, x).

\n\n

Solving Equations Algebraically

\n\n

The main function for solving algebraic equations is solveset. The syntax for solveset is solveset(equation, variable=None, domain=S.Complexes) Where equations may be in the form of Eq instances or expressions that are assumed to be equal to zero.

\n\n

Please note that there is another function called solve which can also be used to solve equations. The syntax is solve(equations, variables) However, it is recommended to use solveset instead.

\n\n

When solving a single equation, the output of solveset is a FiniteSet or an Interval or ImageSet of the solutions.

\n\n\n```julia\n >>> solveset(x**2 - x, x)\n {0, 1}\n >>> solveset(x - x, x, domain=S.Reals)\n ℝ\n >>> solveset(sin(x) - 1, x, domain=S.Reals)\n ⎧ π ⎫\n ⎨2⋅n⋅π + ─ | n ∊ ℤ⎬\n ⎩ 2 ⎭\n```\n\n
In Julia:
\n\n
    \n
  • S is not exported, as it is not a function, so we create an alias:

    \n
  • \n
\n\n\n```julia\nconst S = sympy.S\nsolveset(x^2 - x, x)\n```\n\n\n\n\n\\begin{equation*}\\left\\{0, 1\\right\\}\\end{equation*}\n\n\n\n\n```julia\nsolveset(x - x, x, domain=S.Reals)\n```\n\n\n\n\n\\begin{equation*}\\mathbb{R}\\end{equation*}\n\n\n\n\n```julia\nsolveset(sin(x) - 1, x, domain=S.Reals)\n```\n\n\n\n\n\\begin{equation*}\\left\\{2 n \\pi + \\frac{\\pi}{2}\\; |\\; n \\in \\mathbb{Z}\\right\\}\\end{equation*}\n\n\n\n
\n\n

If there are no solutions, an EmptySet is returned and if it is not able to find solutions then a ConditionSet is returned.

\n\n\n```julia\n >>> solveset(exp(x), x) # No solution exists\n ∅\n >>> solveset(cos(x) - x, x) # Not able to find solution\n {x | x ∊ ℂ ∧ -x + cos(x) = 0}\n```\n\n
In Julia:
\n\n\n```julia\nsolveset(exp(x), x) # No solution exists\n```\n\n\n\n\n\\begin{equation*}\\emptyset\\end{equation*}\n\n\n\n\n```julia\nsolveset(cos(x) - x, x) # Not able to find solution\n```\n\n\n\n\n\\begin{equation*}\\left\\{x \\mid x \\in \\mathbb{C} \\wedge - x + \\cos{\\left (x \\right )} = 0 \\right\\}\\end{equation*}\n\n\n\n
\n\n

In the solveset module, the linear system of equations is solved using linsolve. In future we would be able to use linsolve directly from solveset. Following is an example of the syntax of linsolve.

\n\n
    \n
  • List of Equations Form:

    \n
  • \n
\n\n\n```julia\n >>> linsolve([x + y + z - 1, x + y + 2*z - 3 ], (x, y, z))\n```\n\n
In Julia:
\n\n\n```julia\nlinsolve([x + y + z - 1, x + y + 2*z - 3 ], (x, y, z))\n```\n\n\n\n\n\\begin{equation*}\\emptyset\\end{equation*}\n\n\n\n
\n\n
    \n
  • Augmented

    \n
  • \n
\n\n

Matrix Form:

\n\n\n```julia\n\t>>> linsolve(Matrix(([1, 1, 1, 1], [1, 1, 2, 3])), (x, y, z))\n\t{(-y - 1, y, 2)}\n```\n\n
In Julia:
\n\n\n```julia\nlinsolve(sympy.Matrix(([1, 1, 1, 1], [1, 1, 2, 3])), (x, y, z))\n```\n\n\n\n\n\\begin{equation*}\\left\\{\\left ( - y - 1, \\quad y, \\quad 2\\right )\\right\\}\\end{equation*}\n\n\n\n
\n\n
    \n
  • A*x = b Form

    \n
  • \n
\n\n\n```julia\n\t>>> M = Matrix(((1, 1, 1, 1), (1, 1, 2, 3)))\n\t>>> system = A, b = M[:, :-1], M[:, -1]\n\t>>> linsolve(system, x, y, z)\n\t{(-y - 1, y, 2)}\n```\n\n
In Julia:
\n\n\n```julia\nM = sympy.Matrix(((1, 1, 1, 1), (1, 1, 2, 3)))\nsystem = A, b = M[:, 1:end-1], M[:, end]\nlinsolve(system, x, y, z)\n```\n\n\n\n\n\\begin{equation*}\\left\\{\\left ( - y - 1, \\quad y, \\quad 2\\right )\\right\\}\\end{equation*}\n\n\n\n
\n\n

Note

The order of solution corresponds the order of given symbols.

\n
\n\n

In the solveset module, the non linear system of equations is solved using nonlinsolve. Following are examples of nonlinsolve.

\n\n
    \n
  1. When only real solution is present:

    \n
  2. \n
\n\n\n```julia\n\t>>> a, b, c, d = symbols('a, b, c, d', real=True)\n\t>>> nonlinsolve([a**2 + a, a - b], [a, b])\n\t{(-1, -1), (0, 0)}\n\t>>> nonlinsolve([x*y - 1, x - 2], x, y)\n\t{(2, 1/2)}\n```\n\n
In Julia:
\n\n
    \n
  • we pass [a,b] as either a, b or using a tuple, as in (a,b), but not as a vector, as this gets mapped into a vector of symbolic objects which causes issues with nonlinsolve:

    \n
  • \n
\n\n\n```julia\na, b, c, d = symbols(\"a, b, c, d\", real=true)\nnonlinsolve([a^2 + a, a - b], a, b)\n```\n\n\n\n\n\\begin{equation*}\\left\\{\\left ( -1, \\quad -1\\right ), \\left ( 0, \\quad 0\\right )\\right\\}\\end{equation*}\n\n\n\n\n```julia\nnonlinsolve([x*y - 1, x - 2], x, y)\n```\n\n\n\n\n\\begin{equation*}\\left\\{\\left ( 2, \\quad \\frac{1}{2}\\right )\\right\\}\\end{equation*}\n\n\n\n
\n\n
    \n
  1. When only complex solution is present:

    \n
  2. \n
\n\n\n```julia\n\t>>> nonlinsolve([x**2 + 1, y**2 + 1], [x, y])\n\t{(-ⅈ, -ⅈ), (-ⅈ, ⅈ), (ⅈ, -ⅈ), (ⅈ, ⅈ)}\n```\n\n
In Julia:
\n\n\n```julia\nnonlinsolve([x^2 + 1, y^2 + 1], (x, y))\n```\n\n\n\n\n\\begin{equation*}\\left\\{\\left ( - i, \\quad - i\\right ), \\left ( - i, \\quad i\\right ), \\left ( i, \\quad - i\\right ), \\left ( i, \\quad i\\right )\\right\\}\\end{equation*}\n\n\n\n
\n\n
    \n
  1. When both real and complex solution is present:

    \n
  2. \n
\n\n\n```julia\n\t>>> from sympy import sqrt\n\t>>> system = [x**2 - 2*y**2 -2, x*y - 2]\n\t>>> vars = [x, y]\n\t>>> nonlinsolve(system, vars)\n\t{(-2, -1), (2, 1), (-√2⋅ⅈ, √2⋅ⅈ), (√2⋅ⅈ, -√2⋅ⅈ)}\n\n\t>>> n = Dummy('n')\n\t>>> system = [exp(x) - sin(y), 1/y - 3]\n\t>>> real_soln = (log(sin(S(1)/3)), S(1)/3)\n\t>>> img_lamda = Lambda(n, 2*n*I*pi + Mod(log(sin(S(1)/3)), 2*I*pi))\n\t>>> complex_soln = (ImageSet(img_lamda, S.Integers), S(1)/3)\n\t>>> soln = FiniteSet(real_soln, complex_soln)\n\t>>> nonlinsolve(system, [x, y]) == soln\n\tTrue\n```\n\n
In Julia:
\n\n
    \n
  • we must remove the spaces within []

    \n
  • \n
  • we must pass vars as a tuple:

    \n
  • \n
\n\n\n```julia\nsystem = [x^2-2*y^2-2, x*y-2]\nvars = (x, y)\nnonlinsolve(system, vars)\n```\n\n\n\n\n\\begin{equation*}\\left\\{\\left ( -2, \\quad -1\\right ), \\left ( 2, \\quad 1\\right ), \\left ( - \\sqrt{2} i, \\quad \\sqrt{2} i\\right ), \\left ( \\sqrt{2} i, \\quad - \\sqrt{2} i\\right )\\right\\}\\end{equation*}\n\n\n\n

However, the next bit requires some modifications to run:

\n\n
    \n
  • the system array definition must have extra spaces removed

    \n
  • \n
  • Dummy, Lambda, Mod, ImageSet, FiniteSet aren't exported

    \n
  • \n
  • we need PI, not pi to have a symbolic value

    \n
  • \n
\n\n\n```julia\nn = sympy.Dummy(\"n\")\nsystem = [exp(x)-sin(y), 1/y-3]\nreal_soln = (log(sin(S(1)/3)), S(1)/3)\nimg_lamda = sympy.Lambda(n, 2*n*IM*PI + sympy.Mod(log(sin(S(1)/3)), 2*IM*PI))\ncomplex_soln = (sympy.ImageSet(img_lamda, S.Integers), S(1)/3)\nsoln = sympy.FiniteSet(real_soln, complex_soln)\nnonlinsolve(system, (x, y)) == soln\n```\n\n\n\n\n true\n\n\n\n
\n\n
    \n
  1. If non linear system of equations is Positive dimensional system (A system with

    \n
  2. \n
\n\n

infinitely many solutions is said to be positive-dimensional):

\n\n\n```julia\n\t>>> nonlinsolve([x*y, x*y - x], [x, y])\n\t{(0, y)}\n\n\t>>> system = [a**2 + a*c, a - b]\n\t>>> nonlinsolve(system, [a, b])\n\t{(0, 0), (-c, -c)}\n```\n\n
In Julia:
\n\n
    \n
  • again, we use a tuple for the variables:

    \n
  • \n
\n\n\n```julia\nnonlinsolve([x*y, x*y-x], (x, y))\n```\n\n\n\n\n\\begin{equation*}\\left\\{\\left ( 0, \\quad y\\right )\\right\\}\\end{equation*}\n\n\n\n\n```julia\nsystem = [a^2+a*c, a-b]\nnonlinsolve(system, (a, b))\n```\n\n\n\n\n\\begin{equation*}\\left\\{\\left ( 0, \\quad 0\\right ), \\left ( - c, \\quad - c\\right )\\right\\}\\end{equation*}\n\n\n\n
\n\n
\n

Note:

\n
\n\n
    \n
  1. The order of solution corresponds the order of given symbols.

    \n
  2. \n
  3. Currently nonlinsolve doesn't return solution in form of LambertW (if there

    \n
  4. \n
\n\n

is solution present in the form of LambertW).

\n\n

solve can be used for such cases:

\n\n\n```julia\n >>> solve([x**2 - y**2/exp(x)], [x, y], dict=True)\n ⎡⎧ ⎛y⎞⎫⎤\n ⎢⎨x: 2⋅LambertW⎜─⎟⎬⎥\n ⎣⎩ ⎝2⎠⎭⎦\n```\n\n
In Julia:
\n\n

it is similar

\n\n\n```julia\nu = solve([x^2 - y^2/exp(x)], [x, y], dict=true)\n```\n\n\n\n\n 1-element Array{Dict{Any,Any},1}:\n Dict(x=>2*LambertW(y/2))\n\n\n\n

To get prettier output, the dict may be converted to have one with symbolic keys:

\n\n\n```julia\nconvert(Dict{SymPy.Sym, Any}, first(u))\n```\n\n\n\n\n\\begin{equation*}\\begin{cases}x & \\text{=>} &2 \\operatorname{LambertW}{\\left (\\frac{y}{2} \\right )}\\\\\\end{cases}\\end{equation*}\n\n\n\n
\n\n
    \n
  1. Currently nonlinsolve is not properly capable of solving the system of equations

    \n
  2. \n
\n\n

having trigonometric functions.

\n\n

solve can be used for such cases(not all solution):

\n\n\n```julia\n >>> solve([sin(x + y), cos(x - y)], [x, y])\n ⎡⎛-3⋅π 3⋅π⎞ ⎛-π π⎞ ⎛π 3⋅π⎞ ⎛3⋅π π⎞⎤\n ⎢⎜─────, ───⎟, ⎜───, ─⎟, ⎜─, ───⎟, ⎜───, ─⎟⎥\n ⎣⎝ 4 4 ⎠ ⎝ 4 4⎠ ⎝4 4 ⎠ ⎝ 4 4⎠⎦\n```\n\n
In Julia:
\n\n\n```julia\nsolve([sin(x + y), cos(x - y)], [x, y])\n```\n\n\n\n\n 4-element Array{Tuple{SymPy.Sym,SymPy.Sym},1}:\n (-3*pi/4, 3*pi/4)\n (-pi/4, pi/4) \n (pi/4, 3*pi/4) \n (3*pi/4, pi/4) \n\n\n\n
\n\n

solveset reports each solution only once. To get the solutions of a polynomial including multiplicity use roots.

\n\n\n```julia\n >>> solveset(x**3 - 6*x**2 + 9*x, x)\n {0, 3}\n >>> roots(x**3 - 6*x**2 + 9*x, x)\n {0: 1, 3: 2}\n```\n\n
In Julia:
\n\n\n```julia\nsolveset(x^3 - 6*x^2 + 9*x, x)\n```\n\n\n\n\n\\begin{equation*}\\left\\{0, 3\\right\\}\\end{equation*}\n\n\n\n\n```julia\nroots(x^3 - 6*x^2 + 9*x, x) |> d -> convert(Dict{Sym, Any}, d) # prettier priting\n```\n\n\n\n\n\\begin{equation*}\\begin{cases}3 & \\text{=>} &2\\\\0 & \\text{=>} &1\\\\\\end{cases}\\end{equation*}\n\n\n\n
\n\n

The output {0: 1, 3: 2} of roots means that 0 is a root of multiplicity 1 and 3 is a root of multiplicity 2.

\n\n
\n

Note:

\n
\n\n

Currently solveset is not capable of solving the following types of equations:

\n\n
    \n
  • Equations solvable by LambertW (Transcendental equation solver).

    \n
  • \n
\n\n

solve can be used for such cases:

\n\n\n```julia\n >>> solve(x*exp(x) - 1, x )\n [LambertW(1)]\n```\n\n
In Julia:
\n\n\n```julia\nsolve(x*exp(x) - 1, x )\n```\n\n\n\n\n\\[ \\left[ \\begin{array}{r}\\operatorname{LambertW}{\\left (1 \\right )}\\end{array} \\right] \\]\n\n\n\n
\n\n

Solving Differential Equations

\n\n

To solve differential equations, use dsolve. First, create an undefined function by passing cls=Function to the symbols function.

\n\n\n```julia\n >>> f, g = symbols('f g', cls=Function)\n```\n\n
In Julia:
\n\n\n```julia\nf, g = symbols(\"f g\", cls=sympy.Function)\n```\n\n\n\n\n (PyObject f, PyObject g)\n\n\n\n
\n\n

f and g are now undefined functions. We can call f(x), and it will represent an unknown function.

\n\n\n```julia\n >>> f(x)\n f(x)\n```\n\n
In Julia:
\n\n\n```julia\nf(x)\n```\n\n\n\n\n\\begin{equation*}f{\\left (x \\right )}\\end{equation*}\n\n\n\n
\n\n

Derivatives of f(x) are unevaluated.

\n\n\n```julia\n >>> f(x).diff(x)\n d\n ──(f(x))\n dx\n```\n\n
In Julia:
\n\n\n```julia\nf(x).diff(x)\n```\n\n\n\n\n\\begin{equation*}\\frac{d}{d x} f{\\left (x \\right )}\\end{equation*}\n\n\n\n
\n\n

(see the :ref:Derivatives <tutorial-derivatives> section for more on derivatives).

\n\n

To represent the differential equation $f''(x) - 2f'(x) + f(x) = \\sin(x)$, we would thus use

\n\n\n```julia\n >>> diffeq = Eq(f(x).diff(x, x) - 2*f(x).diff(x) + f(x), sin(x))\n >>> diffeq\n 2\n d d\n f(x) - 2⋅──(f(x)) + ───(f(x)) = sin(x)\n dx 2\n dx\n```\n\n
In Julia:
\n\n\n```julia\ndiffeq = Eq(f(x).diff(x, x) - 2*f(x).diff(x) + f(x), sin(x))\ndiffeq\n```\n\n\n\n\n\\begin{equation*}f{\\left (x \\right )} - 2 \\frac{d}{d x} f{\\left (x \\right )} + \\frac{d^{2}}{d x^{2}} f{\\left (x \\right )} = \\sin{\\left (x \\right )}\\end{equation*}\n\n\n\n
\n\n

To solve the ODE, pass it and the function to solve for to dsolve.

\n\n\n```julia\n >>> dsolve(diffeq, f(x))\n x cos(x)\n f(x) = (C₁ + C₂⋅x)⋅ℯ + ──────\n 2\n```\n\n
In Julia:
\n\n
    \n
  • we use dsolve for initial value proplems

    \n
  • \n
\n\n\n```julia\ndsolve(diffeq, f(x))\n```\n\n\n\n\n\\begin{equation*}f{\\left (x \\right )} = \\left(C_{1} + C_{2} x\\right) e^{x} + \\frac{\\cos{\\left (x \\right )}}{2}\\end{equation*}\n\n\n\n
\n\n

dsolve returns an instance of Eq. This is because in general, solutions to differential equations cannot be solved explicitly for the function.

\n\n\n```julia\n >>> dsolve(f(x).diff(x)*(1 - sin(f(x))), f(x))\n f(x) + cos(f(x)) = C₁\n```\n\n
In Julia:
\n\n\n```julia\ndsolve(f(x).diff(x)*(1 - sin(f(x))), f(x))\n```\n\n\n\n\n\\begin{equation*}f{\\left (x \\right )} + \\cos{\\left (f{\\left (x \\right )} \\right )} = C_{1}\\end{equation*}\n\n\n\n
\n\n

The arbitrary constants in the solutions from dsolve are symbols of the form C1, C2, C3, and so on.

\n\n

Julia alternative interface

\n\n

SymPy.jl adds a SymFunction class, that makes it a bit easier to set up a differential equation, though not as general.

\n\n

We use either the SymFunction constructor

\n\n\n```julia\nf = SymFunction(\"f\")\n```\n\n\n\n\n\\begin{equation*}f\\end{equation*}\n\n\n\n

or the @symfuns macro, as in @symfuns f.

\n\n

to define symbolic functions. For these, rather than use diff to specify derivatives, the prime notation can be used. We then have, with f defined above:

\n\n\n```julia\ndiffeq = Eq(f''(x) - 2*f'(x) + f(x), sin(x))\ndsolve(diffeq, f(x))\n```\n\n\n\n\n\\begin{equation*}f{\\left (x \\right )} = \\left(C_{1} + C_{2} x\\right) e^{x} + \\frac{\\cos{\\left (x \\right )}}{2}\\end{equation*}\n\n\n\n

Or:

\n\n\n```julia\ndsolve(f'(x)*(1 - sin(f(x))), f(x))\n```\n\n\n\n\n\\begin{equation*}f{\\left (x \\right )} + \\cos{\\left (f{\\left (x \\right )} \\right )} = C_{1}\\end{equation*}\n\n\n\n

This interface allows a different specification of initial conditions than does sympy.dsolve.

\n\n

For the initial condition f'(x0) = y0, this would be specified with a tuple (f', x0, y0).

\n\n

For example, to solve the exponential equation $f'(x) = f(x), f(0) = a$ we would have:

\n\n\n```julia\nf = SymFunction(\"f\")\nx, a = symbols(\"x, a\")\ndsolve(f'(x) - f(x), f(x), ics = (f, 0, a))\n```\n\n\n\n\n\\begin{equation*}f{\\left (x \\right )} = a e^{x}\\end{equation*}\n\n\n\n

To solve the simple harmonic equation, where two initial conditions are specified, we combine the tuple for each within another tuple:

\n\n\n```julia\nics = ((f, 0, 1), (f', 0, 2))\ndsolve(f''(x) - f(x), f(x), ics=ics)\n```\n\n\n\n\n\\begin{equation*}f{\\left (x \\right )} = \\frac{3 e^{x}}{2} - \\frac{e^{- x}}{2}\\end{equation*}\n\n\n\n
\n\n

return to index

\n", "meta": {"hexsha": "f08d65f1b435b3b2d5a53a18ab5244e47c58b26e", "size": 33746, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "examples/solvers.ipynb", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/SymPy.jl-24249f21-da20-56a4-8eb1-6a02cf4ae2e6", "max_stars_repo_head_hexsha": "a6e5a24b3d1ad069a413d0c28f01052c5fa4c6cc", "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": "examples/solvers.ipynb", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/SymPy.jl-24249f21-da20-56a4-8eb1-6a02cf4ae2e6", "max_issues_repo_head_hexsha": "a6e5a24b3d1ad069a413d0c28f01052c5fa4c6cc", "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": "examples/solvers.ipynb", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/SymPy.jl-24249f21-da20-56a4-8eb1-6a02cf4ae2e6", "max_forks_repo_head_hexsha": "a6e5a24b3d1ad069a413d0c28f01052c5fa4c6cc", "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": 176.6806282723, "max_line_length": 608, "alphanum_fraction": 0.6165767795, "converted": true, "num_tokens": 6691, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.935346511643776, "lm_q2_score": 0.9263037374145591, "lm_q1q2_score": 0.8664149695133001}} {"text": "# Lab 4\n## Introduction\nThe Euler method is a method for numerically solving a DE of the form\n\\begin{align}\n\\frac{\\mathrm{d}y}{\\mathrm{d}x} = f(x,y).\n\\end{align}\n\nIt is often necessary to solve DEs this way as analytical solutions are the exception\nrather than the rule.\n\n\n\nEuler’s method works by approximating small segments of the curve solution to the DE\nwith the straight-line tangent or slope of the curve. As long as we keep the segments\nsmall enough, they will approximately match what the actual curve looks like. It requires us to ”know” an initial value $y(x_0) = y_0$ so we can start the calculation.\n\nTo calculate the first segment we start off with our known start point $(x_0, y_0)$, and calculate the end point, $(x_1, y_1)$. We can define $\\Delta x$ to be some constant small distance so that we always increment the $x$ value by the same amount. Then, $\\Delta y = m \\Delta x$ and $(x_1, y_1)=(x_0, y_0)+(\\Delta x, m\\Delta x)$.\n\n\n\nBut, we also know that $m$, the slope of the line, is given by $\\mathrm{d}y/\\mathrm{d}x$, i.e., $f(x, y)$ evaluated at $(x_0, y_0)$. So actually, $\\Delta y = f(x_0, y_0) \\Delta x$.\n\nThe final step is to calculate the new point: the point at the end of the first line segment. This point is then given by $(x_1, y_1) = (x_0 + \\Delta x, y_0 + f(x_0, y_0) \\Delta x)$.\n\nWe then do it again to calculate $(x_2, y_2)$ using $(x_1, y_1)$ as our starting point. We then do it again to calculate $(x_3, y_3)$ using $(x_2, y_2)$ as our starting point and so on.\n\n**Summary:** The Euler method for evaluating a DE of the form\n\\begin{align}\n\\frac{\\mathrm{d}y}{\\mathrm{d}x} = f(x,y).\n\\end{align}\ninvolves the iterative calculation of\n\\begin{align}\nx_{n+1} &= x_n + \\Delta x\\\\\n\\text{and}\\quad y_{n+1} &= y_n + f(x_n,y_n)\\Delta x.\n\\end{align}\n\n### Implementation\n\nFirst import the necessary functions from NumPy and SciPy and set up Plotly.\n\n\n```python\nfrom numpy import arange, empty, exp\nfrom plotly import graph_objs as go\n```\n\nNow let's write a function that implements Euler's method. We will model it on `scipy.integrate.odeint`. We will make slight changes to the parameters because we want to input $\\Delta x$. Note that the string (delimited by triple quotes) immediately after the function definition is a _docstring_. It tells us what the function does and is good programming practice. The prodigious comments in the function body are not generally necessary but are included for you.\n\n\n```python\ndef euler(func, y0, x0, xn, Dx):\n \"\"\"\n Integrate an ordinary differential equation using Euler's method.\n \n Solves the initial value problem for systems of first order ode-s::\n dy/dx = func(y, x).\n \n Parameters\n ----------\n func : callable(y, x)\n Computes the derivative of y at x.\n y0 : float\n Initial condition on y.\n x0 : float\n Initial condition on x.\n xn : float\n Upper limit to value of x.\n Dx : float\n x increment.\n \n Returns\n -------\n x : float\n Array containing the value of x for each value of x0 + n * Dx,\n where n ranges from zero to floor( (xn - x0) / Dx ).\n y : float\n Array containing the value of y for each value of x.\n \"\"\"\n x = arange(x0, xn, Dx) # Create the x array\n y = empty(len(x)) # Create an empty y array of the same length as x\n y[0] = y0 # Set the first value of y to y0\n for n in range(len(x) - 1): # Loop to populate the rest of the values of y\n y[n+1] = y[n] + func(y[n], x[n]) * Dx # Euler's method\n \n return x, y # Return x and y as a pair\n```\n\nFirst try solving\n\\begin{align}\n\\frac{\\mathrm{d}y}{\\mathrm{d}x} = y.\n\\end{align}\nfor $y(0)=1$ for $x$ between 1 and 5 and using $\\Delta x=1$.\n\n\n```python\ndef diff_eq(y, x):\n return y\n\nx, y = euler(diff_eq, 1, 0, 5.01, 1)\n```\n\nWhy was `xn` set to 5.01 rather than 5?\n\nWe know that the analytic solution to the above IVP is $y=\\mathrm{e}^x$, so calculate that as well.\n\n\n```python\nx_analytic = arange(0, 5.01, 0.1)\ny_analytic = exp(x_analytic)\n```\n\nNow plot them both for comparison.\n\n\n```python\nfig = go.Figure()\nfig.add_trace(go.Scatter(x=x, y=y,\n name='Euler'))\nfig.add_trace(go.Scatter(x=x_analytic,\n y=y_analytic,\n name='Truth'))\nfig.show('png')\n```\n\nReproduce the comparison plot below but with $\\Delta x=0.1$.\n\n\n```python\nx, y = euler(diff_eq, 1, 0, 5.01, 0.1)\n\nfig = go.Figure()\nfig.add_trace(go.Scatter(x=x, y=y,\n name='Euler'))\nfig.add_trace(go.Scatter(x=x_analytic,\n y=y_analytic,\n name='Truth'))\nfig.show('png')\n```\n\n\nIt is possible to quantify the error in the Euler solution compared to the analytic solution. To do this you need to re-calculate the analytic solution at the same $x$ points as you calculated your Euler solution. Then you can do a Mean Squared Error (MSE) comparison between the two.\n\n\n```python\nx, y = euler(diff_eq, 1, 0, 5.01, 1)\ny_analytic = exp(x)\n((y_analytic - y)**2).mean()\n```\n\n\n\n\n 2533.317105161909\n\n\n\nNote that `((y_analytic - y)**2)` returned an `array` object, and then we called the `mean` method that was _bound_ to that object.\n\nWhat is the MSE if $\\Delta x = 0.1$?\n\n\n```python\nx, y = euler(diff_eq, 1, 0, 5.01, 0.1)\ny_analytic = exp(x)\n((y_analytic - y)**2).mean()\n```\n\n\n\n\n 88.60637343780924\n\n\n\n## Exercises\n\nIn this lab you will try Euler's method for a couple of differential equations.\n\n1. a. Consider the IVP\n\\begin{align}\n\\frac{\\mathrm{d}y}{\\mathrm{d}x} = 2x\\quad\\text{where}\\quad y(-2)=4.\n\\end{align}\nCalculate the Euler approximation on the interval $x=[-2,2]$ using a step size of $\\Delta x = 0.5$. On the same figure, plot your approximation and the analytic solution.\n\n\n```python\ndef diff_eq(y, x):\n return 2*x\n\nx, y = euler(diff_eq, 4, -2, 2.01, 0.5)\n\nx_analytic = arange(-2, 2.01, 0.5)\ny_analytic = (x_analytic)**2\n\nfig = go.Figure()\nfig.add_trace(go.Scatter(x=x, y=y,\n name='Euler'))\nfig.add_trace(go.Scatter(x=x_analytic,\n y=y_analytic,\n name='Truth'))\nfig.show('png')\n```\n\n1. b. Calculate the mean squared error (MSE) of the approximation.\n\n\n```python\nx, y = euler(diff_eq, 4, -2, 2.01, 0.5)\ny_analytic = (x)**2\n((y_analytic - y)**2).mean()\n```\n\n\n\n\n 1.4166666666666667\n\n\n\n1. c. Reproduce your plot from 1a except with $\\Delta x=0.1$.\n\n\n```python\nx, y = euler(diff_eq, 4, -2, 2.01, 0.1)\n\nx_analytic = arange(-2, 2.01, 0.5)\ny_analytic = (x_analytic)**2\n\nfig = go.Figure()\nfig.add_trace(go.Scatter(x=x, y=y,\n name='Euler'))\nfig.add_trace(go.Scatter(x=x_analytic,\n y=y_analytic,\n name='Truth'))\nfig.show('png')\n```\n\n1. d. Recalculate the MSE.\n\n\n```python\nx, y = euler(diff_eq, 4, -2, 2.01, 0.1)\ny_analytic = (x)**2\n((y_analytic - y)**2).mean()\n```\n\n\n\n\n 0.053999999999998854\n\n\n\n2. a. The following is the DE for the arrow problem from class.\n\\begin{align}\n\\frac{\\mathrm{d}y}{\\mathrm{d}t} = 294\\mathrm{e}^{-0.04t}-245\\quad\\text{where}\\quad y(0)=0\n\\end{align}\nCalculate the Euler approximation to the solution on the interval $t=[0,10]$ with $\\Delta t=0.5$. Plot your approximation and the analytic solution on the same figure.\n\n\n```python\ndef diff_eq(y, x):\n return (294*exp(-0.04*x)) - 245\n\nx, y = euler(diff_eq, 0, 0, 10.01, 0.5)\n\nx_analytic = arange(0, 10.01, 0.5)\ny_analytic = (-7350*exp(-0.04*x_analytic)) - 245*x + 7350\n\nfig = go.Figure()\nfig.add_trace(go.Scatter(x=x, y=y,\n name='Euler'))\nfig.add_trace(go.Scatter(x=x_analytic,\n y=y_analytic,\n name='Truth'))\nfig.show('png')\n```\n\n2. b. Calculate the MSE of the approximation.\n\n\n```python\nx, y = euler(diff_eq, 0, 0, 10.01, 0.5)\ny_analytic = (-7350*exp(-0.04*x)) - 245*x + 7350\n((y_analytic - y)**2).mean()\n```\n\n\n\n\n 221.1226824539981\n\n\n\n2. c. Reproduce your plot from 2a except with $\\Delta t=0.1$.\n\n\n```python\nx, y = euler(diff_eq, 0, 0, 10.01, 0.1)\n\nx_analytic = arange(0, 10.01, 0.1)\ny_analytic = (-7350*exp(-0.04*x_analytic)) - 245*x +7350\n\nfig = go.Figure()\nfig.add_trace(go.Scatter(x=x, y=y,\n name='Euler'))\nfig.add_trace(go.Scatter(x=x_analytic,\n y=y_analytic,\n name='Truth'))\nfig.show('png')\n```\n\n2. d. Recalculate the MSE.\n\n\n```python\nx, y = euler(diff_eq, 0, 0, 10.01, 0.1)\ny_analytic = (-7350*exp(-0.04*x)) - 245*x +7350\n((y_analytic - y)**2).mean()\n```\n\n\n\n\n 8.673112166785117\n\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "9abd7420853a86bf456b7411d026eb8cb960fba7", "size": 248784, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/lab-04.ipynb", "max_stars_repo_name": "sanai004/mm-labs", "max_stars_repo_head_hexsha": "9004d6f0c0e2f94183dfaf542660aa7e9bf7f602", "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": "notebooks/lab-04.ipynb", "max_issues_repo_name": "sanai004/mm-labs", "max_issues_repo_head_hexsha": "9004d6f0c0e2f94183dfaf542660aa7e9bf7f602", "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": "notebooks/lab-04.ipynb", "max_forks_repo_name": "sanai004/mm-labs", "max_forks_repo_head_hexsha": "9004d6f0c0e2f94183dfaf542660aa7e9bf7f602", "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": 344.5761772853, "max_line_length": 42577, "alphanum_fraction": 0.9340391665, "converted": true, "num_tokens": 2729, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037323284109, "lm_q2_score": 0.9353465165999584, "lm_q1q2_score": 0.8664149693469194}} {"text": "```python\n%matplotlib inline\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\nfrom scipy.stats import norm\nfrom scipy.stats import t as tdist\nfrom scipy.stats import pearsonr\n\nfrom ar1 import sample_ar1\n```\n\n# Correlation of time series with memory\n\nIn this example, you will see how to generate an empirical null-distribution for the correlation coefficient between two auto-correlated time series and how to test the correlation coefficient against this null distribution.\n\nIn the end you will also see a nice formula to correct for the effect of the auto-correlation without doing a simulation experiment. It's rare that we are so lucky, but sometimes it does happen.\n\nFirst, we genrate our \"observations\", two ramdom time series, that are un-correlated but do exhibit an autocorrelation that would not be uncommon for a climate variable:\n\n\n```python\nn = 250\nphi = 0.75\nnp.random.seed(12358)\ny1, y2 = sample_ar1(n, phi, size=2)\n```\n\n\n```python\nfig, axes = plt.subplots(figsize=(13, 8), nrows=2, sharex=True, sharey=False)\n\naxes[0].plot(y1, 'C0-', lw=1)\naxes[0].set_ylabel('$y_0$')\naxes[1].plot(y2, 'C1-', lw=1)\naxes[1].set_ylabel('$y_1$')\n\naxes[-1].set_xlabel('Sample')\n```\n\nAfter taking a look at the time series we calculate the correlatrion coefficient between the two time series.\n\n\n```python\nr, p_wn = pearsonr(y1, -1 * y2)\nprint('r=%.4f (p=%.4f, N=%u)'% (r, p_wn, n))\n```\n\nConveniently, the scipy function `pearsonr` also returns the p-value for the correlation coefficient and it seems that the correlation is highly significant!\n\n## Red noise null distribution\n\nUnfortunately the test assumes white-noise timeseries as the null distribution which is a terrible assumption in this case.\n\nTo use a more realistic null-hypothesis we check the correlation coefficient against a null-distribution for auto-correlated time series.\n\nFor that we generate a large number of pairs of samples from an AR(1) process with the same number of observations and auto-correlation as our data and calculate the correlation between the two.\n\nWe than compare the correlation coefficient against this empirical null-distribution to check at which percentile of the distribution the correlation of our real data is, following the theory that underlies the classical t-test.\n\n\n```python\nnsamples = 20000\n\nsample_r = np.zeros(nsamples)\n\nfor i in range(nsamples):\n s1 = sample_ar1(n, phi)\n s2 = sample_ar1(n, phi)\n sample_r[i] = pearsonr(s1, s2)[0]\n```\n\n\n```python\nplt.hist(sample_r, bins=50, histtype='step')\nplt.xlabel('$r$')\nplt.axvline(r)\n```\n\n\n```python\n# Empirical p-value from sampled correlation coefficients\np_empirical = np.mean(np.abs(sample_r) >= np.abs(r))\nprint('Empirical p-value from simulation: %.4f' % p_empirical)\n```\n\nIn the case of simple AR(1) processes, there is a formula that we can use to account for the reduced degrees of freedom due to the autocorrelation:\n\n\\begin{align}\n n_\\mathrm{eff} = n \\frac{1 - \\phi_1 \\phi_2}{1 + \\phi_1 \\phi_2}\n\\end{align}\n\nwhere $\\phi_1$ and $\\phi_2$ are the lag-one autocorrelations of the two correlated time series.\n\nYou can see below that the autocorrelation of the time series dramatically decreases the effective number of observations!\n\n\n```python\n# Calculate reduced degrees of freedom:\nneff = n * (1 - phi * phi) / (1 + phi * phi)\nprint('Number of samples: %u' % n)\nprint('Effective sample size: %u' % neff)\n```\n\nWe can than use this value for the calculation of the t-statistic and for the degrees of freedom of the t-distribution that we check the value agains.\n\nThis value agrees well with the empirical value optained above.\n\n\n```python\n# Use reduced number of freedoms to test against theoretical t-distribution\nt = r * np.sqrt(neff) / np.sqrt(1 - r**2)\np_theory = 2 * (1 - tdist.cdf(t, neff))\nprint('Theoretical p-value using reduced DOF: %.4f' % p_theory)\n```\n", "meta": {"hexsha": "ae9bfc554d4ab0cec6eec6c0b979e073f93e8914", "size": 6303, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "03-AR1_correlation.ipynb", "max_stars_repo_name": "terhardt/ICAT-stats", "max_stars_repo_head_hexsha": "5e74aff69a4c1b65c7756cb4edcd0db1df8a60fc", "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": "03-AR1_correlation.ipynb", "max_issues_repo_name": "terhardt/ICAT-stats", "max_issues_repo_head_hexsha": "5e74aff69a4c1b65c7756cb4edcd0db1df8a60fc", "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": "03-AR1_correlation.ipynb", "max_forks_repo_name": "terhardt/ICAT-stats", "max_forks_repo_head_hexsha": "5e74aff69a4c1b65c7756cb4edcd0db1df8a60fc", "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.1578947368, "max_line_length": 234, "alphanum_fraction": 0.5990798033, "converted": true, "num_tokens": 1000, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037262250327, "lm_q2_score": 0.935346511643776, "lm_q1q2_score": 0.8664149590472157}} {"text": "# Symbolic Computation\nSymbolic computation deals with symbols, representing them exactly, instead of numerical approximations (floating point)\n\n\n```python\nimport math\n\nmath.sqrt(3)\n```\n\n\n\n\n 1.7320508075688772\n\n\n\n\n```python\nmath.sqrt(8)\n```\n\n\n\n\n 2.8284271247461903\n\n\n\n$\\sqrt(8) = 2\\sqrt(2)$, but it's hard to see that here\n\n\n```python\nimport sympy\nsympy.sqrt(3)\n```\n\n\n\n\n$\\displaystyle \\sqrt{3}$\n\n\n\nSympy can even simplify symbolic computations\n\n\n```python\nsympy.sqrt(8)\n```\n\n\n\n\n$\\displaystyle 2 \\sqrt{2}$\n\n\n\n\n```python\nfrom sympy import symbols\nx, y = symbols('x y')\nexpr = x + 2*y\nexpr\n\n```\n\n\n\n\n$\\displaystyle x + 2 y$\n\n\n\nNote that simply adding two symbols creates an expression. Now let's play around with it. \n\n\n```python\nexpr + 1\n```\n\n\n\n\n$\\displaystyle x + 2 y + 1$\n\n\n\n\n```python\nexpr - x\n```\n\n\n\n\n$\\displaystyle 2 y$\n\n\n\nNote that `expr - x` was not `x + 2y -x`\n\n\n```python\nx*expr\n```\n\n\n\n\n$\\displaystyle x \\left(x + 2 y\\right)$\n\n\n\n\n```python\nfrom sympy import expand, factor\nexpanded_expr = expand(x*expr)\nexpanded_expr\n```\n\n\n\n\n$\\displaystyle x^{2} + 2 x y$\n\n\n\n\n```python\nfactor(expanded_expr)\n```\n\n\n\n\n$\\displaystyle x \\left(x + 2 y\\right)$\n\n\n\n\n```python\nfrom sympy import diff, sin, exp\n\ndiff(sin(x)*exp(x), x)\n```\n\n\n\n\n$\\displaystyle e^{x} \\sin{\\left(x \\right)} + e^{x} \\cos{\\left(x \\right)}$\n\n\n\n\n```python\nfrom sympy import limit\n\nlimit(sin(x)/x, x, 0)\n```\n\n\n\n\n$\\displaystyle 1$\n\n\n\n### Exercise\n\nSolve $x^2 - 2 = 0$ using sympy.solve\n\n\n```python\n# Type solution here\nfrom sympy import solve\n```\n\n## Pretty printing\n\n\n```python\nfrom sympy import init_printing, Integral, sqrt\n\ninit_printing(use_latex=True)\n```\n\n\n```python\nIntegral(sqrt(1/x), x)\n```\n\n\n```python\nfrom sympy import latex\n\nlatex(Integral(sqrt(1/x), x))\n```\n\n\n\n\n '\\\\int \\\\sqrt{\\\\frac{1}{x}}\\\\, dx'\n\n\n\nMore symbols\n\n\n```python\nexpr2 = x + 2*y +3*z\n```\n\n### Exercise \n\nSolve $x + 2*y + 3*z$ for $x$\n\n\n```python\n# Solution here\nsolve()\n```\n\nDifference between symbol name and python variable name\n\n\n```python\nx, y = symbols(\"y z\")\n```\n\n\n```python\nx\n```\n\n\n```python\ny\n```\n\n\n```python\nz\n```\n\nSymbol names can be more than one character long\n\n\n```python\ncrazy = symbols('unrelated')\n\ncrazy + 1\n```\n\n\n```python\nx = symbols(\"x\")\nexpr = x + 1\nx = 2\n```\n\nWhat happens when I print expr now? Does it print 3?\n\n\n```python\nprint(expr)\n```\n\n x + 1\n\n\nHow do we get 3?\n\n\n```python\nx = symbols(\"x\")\nexpr = x + 1\nexpr.subs(x, 2)\n```\n\n## Equalities\n\n\n```python\nx + 1 == 4\n```\n\n\n\n\n False\n\n\n\n\n```python\nfrom sympy import Eq\n\nEq(x + 1, 4)\n```\n\nSuppose we want to ask whether $(x + 1)^2 = x^2 + 2x + 1$\n\n\n```python\n(x + 1)**2 == x**2 + 2*x + 1\n```\n\n\n\n\n False\n\n\n\n\n```python\nfrom sympy import simplify\n\na = (x + 1)**2\nb = x**2 + 2*x + 1\n\nsimplify(a-b)\n```\n\n### Exercise \nWrite a function that takes two expressions as input, and returns a tuple of two booleans. The first if they are equal symbolically, and the second if they are equal mathematically.\n\n## More operations\n\n\n```python\nz = symbols(\"z\")\nexpr = x**3 + 4*x*y - z\nexpr.subs([(x, 2), (y, 4), (z, 0)])\n```\n\n\n```python\nfrom sympy import sympify\n\nstr_expr = \"x**2 + 3*x - 1/2\"\nexpr = sympify(str_expr)\nexpr\n```\n\n\n```python\nexpr.subs(x, 2)\n```\n\n\n```python\nexpr = sqrt(8)\n```\n\n\n```python\nexpr\n```\n\n\n```python\nexpr.evalf()\n```\n\n\n```python\nfrom sympy import pi\n\npi.evalf(100)\n```\n\n\n```python\nfrom sympy import cos\n\nexpr = cos(2*x)\nexpr.evalf(subs={x: 2.4})\n```\n\n### Exercise\n\n\n\n```python\nfrom IPython.core.display import Image \nImage(filename='figures/comic.png') \n```\n\nWrite a function that takes a symbolic expression (like pi), and determines the first place where 999999 appears.\nTip: Use the string representation of the number. Python starts counting at 0, but the decimal point offsets this\n\n## Solving an ODE\n\n\n```python\nfrom sympy import Function\n\nf, g = symbols('f g', cls=Function)\nf(x)\n```\n\n\n```python\nf(x).diff()\n```\n\n\n```python\ndiffeq = Eq(f(x).diff(x, x) - 2*f(x).diff(x) + f(x), sin(x))\ndiffeq\n```\n\n\n```python\nfrom sympy import dsolve\n\ndsolve(diffeq, f(x))\n```\n\n## Finite Differences\n\n\n```python\nfrom sympy import as_finite_diff\n\nf = Function('f')\ndfdx = f(x).diff(x)\nas_finite_diff(dfdx)\n```\n\n\n```python\nfrom sympy import Symbol\n\nd2fdx2 = f(x).diff(x, 2)\nh = Symbol('h')\nas_finite_diff(d2fdx2, h)\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "cac19828a646146ace3097ff3e8f3e0ec53415b2", "size": 130548, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "01-sympy.ipynb", "max_stars_repo_name": "navjotk/devitoworkshop", "max_stars_repo_head_hexsha": "ebb5dcd40ba32caf2be520bfc420251c32ad2079", "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": "01-sympy.ipynb", "max_issues_repo_name": "navjotk/devitoworkshop", "max_issues_repo_head_hexsha": "ebb5dcd40ba32caf2be520bfc420251c32ad2079", "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": "01-sympy.ipynb", "max_forks_repo_name": "navjotk/devitoworkshop", "max_forks_repo_head_hexsha": "ebb5dcd40ba32caf2be520bfc420251c32ad2079", "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": 106.9189189189, "max_line_length": 75420, "alphanum_fraction": 0.872828385, "converted": true, "num_tokens": 1379, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850110816423, "lm_q2_score": 0.925229957607466, "lm_q1q2_score": 0.8662789411115737}} {"text": "# Sympy\n\n\n## Introducción\n\nHay dos sistemas de álgebra computarizada (CAS) notables para Python:\n\n* [SymPy](http://sympy.org/en/index.html): un módulo de Python que se puede utilizar en cualquier programa de Python, o en una sesión de IPython, que proporciona potentes funciones de CAS.\n* [Sage](http://www.sagemath.org/) - Sage es un entorno CAS muy potente y con todas las funciones que tiene como objetivo proporcionar un sistema de código abierto que compita con Mathematica y Maple. Sage no es un módulo Python normal, sino un entorno CAS que utiliza Python como lenguaje de programación.\n\n`Sage` es en algunos aspectos más poderoso que `SymPy`, pero ambos ofrecen una funcionalidad CAS muy completa. La ventaja de SymPy es que es un módulo Python normal y se integra bien con el portátil IPython.\n\nPara comenzar a usar SymPy en un programa o cuaderno de Python, importe el módulo `sympy`:\n\n\n```python\nfrom sympy import *\n```\n\nPara obtener una salida con formato $\\LaTeX $ atractiva, ejecute:\n\n\n```python\ninit_printing()\n\n# or with older versions of sympy/ipython, load the IPython extension\n#%load_ext sympy.interactive.ipythonprinting\n# or\n#%load_ext sympyprinting\n```\n\n## Variables simbólicas\n\nEn `SymPy` necesitamos crear símbolos para las variables con las que queremos trabajar. Podemos crear un nuevo símbolo usando la clase `Symbol`:\n\n\n```python\nx = Symbol('x')\n```\n\n\n```python\n(pi + x)**2\n```\n\n\n```python\n# alternative way of defining symbols\na, b, c = symbols(\"a, b, c\")\n```\n\n\n```python\ntype(a)\n```\n\n\n\n\n sympy.core.symbol.Symbol\n\n\n\nPodemos agregar suposiciones a los símbolos cuando los creamos:\n\n\n```python\nx = Symbol('x', real=True)\n```\n\n\n```python\nx.is_imaginary\n```\n\n\n\n\n False\n\n\n\n\n```python\nx = Symbol('x', positive=True)\n```\n\n\n```python\nx > 0\n```\n\n### Números complejos\n\nLa unidad imaginaria se denota \"I\" en `Sympy`.\n\n\n```python\n1+1*I\n```\n\n\n```python\nI**2\n```\n\n\n```python\n(x * I + 1)**2\n```\n\n### Numeros racionales\n\nHay tres tipos numéricos diferentes en SymPy: `Real`,` Rational`, ʻInteger`:\n\n\n```python\nr1 = Rational(4,5)\nr2 = Rational(5,4)\n```\n\n\n```python\nr1\n```\n\n\n```python\nr1+r2\n```\n\n\n```python\nr1/r2\n```\n\n## Evaluación numérica\n\n`SymPy` usa una biblioteca para precisión artística como backend numérico, y tiene expresiones `SymPy` predefinidas para una serie de constantes matemáticas, como: `pi`, ʻe`, ʻoo` para infinito.\n\nPara evaluar una expresión numéricamente podemos usar la función `evalf` (o `N`). Toma un argumento \"n\" que especifica el número de dígitos significativos.\n\n\n```python\npi.evalf(n=50)\n```\n\n\n```python\ny = (x + pi)**2\n```\n\n\n```python\nN(y, 5) # same as evalf\n```\n\nCuando evaluamos numéricamente expresiones algebraicas, a menudo queremos sustituir un símbolo por un valor numérico. En `SymPy` lo hacemos usando la función `subs`:\n\n\n```python\ny.subs(x, 1.5)\n```\n\n\n```python\nN(y.subs(x, 1.5))\n```\n\nPor supuesto, la función `subs` también se puede utilizar para sustituir símbolos y expresiones:\n\n\n```python\ny.subs(x, a+pi)\n```\n\nTambién podemos combinar la evolución numérica de expresiones con matrices `Numpy`:\n\n\n```python\nimport numpy\nimport matplotlib.pyplot as plt\n\n```\n\n\n```python\nx_vec = numpy.arange(0, 10, 0.1)\n```\n\n\n```python\ny_vec = numpy.array([N(((x + pi)**2).subs(x, xx)) for xx in x_vec])\n```\n\n\n```python\nfig, ax = plt.subplots()\nax.plot(x_vec, y_vec);\n```\n\nSin embargo, este tipo de evolución numérica puede ser muy lenta, y hay una manera mucho más eficiente de hacerlo: use la función `lambdify` para\" compilar \"una expresión Sympy en una función que sea mucho más eficiente para evaluar numéricamente:\n\n\n```python\nf = lambdify([x], (x + pi)**2, 'numpy') # the first argument is a list of variables that\n # f will be a function of: in this case only x -> f(x)\n```\n\n\n```python\ny_vec = f(x_vec) # now we can directly pass a numpy array and f(x) is efficiently evaluated\n```\n\nLa aceleración cuando se utilizan funciones `lambdify` en lugar de una evaluación numérica directa puede ser significativa, a menudo de varios órdenes de magnitud. Incluso en este ejemplo simple obtenemos una velocidad significativa:\n\n\n```python\n%%timeit\n\ny_vec = numpy.array([N(((x + pi)**2).subs(x, xx)) for xx in x_vec])\n```\n\n 16.9 ms ± 473 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n\n\n\n```python\n%%timeit\n\ny_vec = f(x_vec)\n```\n\n 2.89 µs ± 48.3 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)\n\n\n## Manipulaciones algebraicas\n\nUno de los usos principales de un CAS es realizar manipulaciones algebraicas de expresiones. Por ejemplo, podríamos querer expandir un producto, factorizar una expresión o simplemente una expresión. Las funciones para realizar estas operaciones básicas en SymPy se muestran en esta sección.\n\n### Expandir y factorizar\n\nLos primeros pasos en una manipulación algebraica\n\n\n```python\n(x+1)*(x+2)*(x+3)\n```\n\n\n```python\nexpand((x+1)*(x+2)*(x+3))\n```\n\nLa función `expand` toma un número de argumentos de palabras clave que podemos decirle a las funciones qué tipo de expansiones queremos que se realicen. Por ejemplo, para expandir expresiones trigonométricas, use el argumento de palabra clave `trig = True`:\n\n\n```python\nsin(a+b)\n```\n\n\n```python\nexpand(sin(a+b), trig=True)\n```\n\nConsulte `help (expand)` para obtener una explicación detallada de los distintos tipos de expansiones que pueden realizar las funciones de ʻexpand`.\n\nLo contrario, una expansión de producto es, por supuesto, factorización. El factor de una expresión en SymPy usa la función `factor`:\n\n\n```python\nfactor(x**3 + 6 * x**2 + 11*x + 6)\n```\n\n### Simplificar\n\nEl \"simplificar\" intenta simplificar una expresión en una expresión agradable, utilizando varias técnicas. También existen alternativas más específicas a las funciones `simplify`:` trigsimp`, `powsimp`,` logcombine`, etc.\n\nLos usos básicos de estas funciones son los siguientes:\n\n\n```python\n# simplify expands a product\nsimplify((x+1)*(x+2)*(x+3))\n```\n\n\n```python\n# simplify uses trigonometric identities\nsimplify(sin(a)**2 + cos(a)**2)\n```\n\n\n```python\nsimplify(cos(x)/sin(x))\n```\n\n### Separados y juntos\n\nPara manipular expresiones simbólicas de fracciones, podemos usar las funciones `apart` y `together`:\n\n**apart**\n\n\n```python\nf1 = 1/((a+1)*(a+2))\n```\n\n\n```python\nf1\n```\n\n\n```python\napart(f1)\n```\n\n**together**\n\n\n```python\nf2 = 1/(a+2) + 1/(a+3)\n```\n\n\n```python\nf2\n```\n\n\n```python\ntogether(f2)\n```\n\nSimplificar generalmente combina fracciones pero no factoriza:\n\n\n```python\nsimplify(f2)\n```\n\n## Cálculo\n\nAdemás de las manipulaciones algebraicas, el otro uso principal de CAS es hacer cálculo, como derivadas e integrales de expresiones algebraicas.\n\n### Diferenciación\n\nLa diferenciación suele ser sencilla. Utilice la función `diff`. El primer argumento es la expresión para tomar la derivada y el segundo argumento es el símbolo por el cual tomar la derivada:\n\n\n```python\ny\n```\n\n\n```python\ndiff(y**2, x)\n```\n\nPara derivados de orden superior podemos hacer:\n\n\n```python\ndiff(y**2, x, x)\n```\n\n\n```python\ndiff(y**2, x, 2) # same as above\n```\n\nPara calcular la derivada de una expresión multivariante, podemos hacer:\n\n\n```python\nx, y, z = symbols(\"x,y,z\")\n```\n\n\n```python\nf = sin(x*y) + cos(y*z)\n```\n\n$\\frac{d^3f}{dxdy^2}$\n\n\n```python\ndiff(f, x, 1, y, 2)\n```\n\n### Integración\n\nLa integración se realiza de manera similar:\n\n\n```python\nf\n```\n\n\n```python\nintegrate(f, x)\n```\n\nAl proporcionar límites para la variable de integración, podemos evaluar integrales definidas:\n\n\n```python\nintegrate(f, (x, -1, 1))\n```\n\ny también integrales impropias:\n\n\n```python\nintegrate(exp(-x**2), (x, -oo, oo))\n```\n\nRecuerde, `oo` es la notación SymPy para infinito.\n\n### Sumas y productos\n\nPodemos evaluar sumas y productos usando las funciones: 'Suma'\n\n\n```python\nn = Symbol(\"n\")\n```\n\n\n```python\nSum(1/n**2, (n, 1, 10))\n```\n\n\n```python\nSum(1/n**2, (n,1, 10)).evalf()\n```\n\n\n```python\nSum(1/n**2, (n, 1, oo)).evalf()\n```\n\nLos productos funcionan de la misma manera:\n\n\n```python\nProduct(n, (n, 1, 10)) # 10!\n```\n\n### Límites\n\nLos límites se pueden evaluar utilizando la función `limit`. Por ejemplo,\n\n\n```python\nlimit(sin(x)/x, x, 0)\n```\n\nPodemos usar `limit` para verificar el resultado de la derivación usando la función `diff`:\n\n\n```python\nf\n```\n\n\n```python\ndiff(f, x)\n```\n\n$\\displaystyle \\frac{\\mathrm{d}f(x,y)}{\\mathrm{d}x} = \\frac{f(x+h,y)-f(x,y)}{h}$\n\n\n```python\nh = Symbol(\"h\")\n```\n\n\n```python\nlimit((f.subs(x, x+h) - f)/h, h, 0)\n```\n\nPodemos cambiar la dirección desde la que nos acercamos al punto límite usando el argumento `dir`:\n\n\n```python\nlimit(1/x, x, 0, dir=\"+\")\n```\n\n\n```python\nlimit(1/x, x, 0, dir=\"-\")\n```\n\n### Serie\n\nLa expansión de la serie también es una de las características más útiles de un CAS. En SymPy podemos realizar una expansión en serie de una expresión usando la función `series`:\n\n\n```python\nseries(exp(x), x)\n```\n\nDe forma predeterminada, expande la expresión alrededor de $x = 0$, pero podemos expandir alrededor de cualquier valor de $x$ al incluir explícitamente un valor en la llamada a la función:\n\n\n```python\nseries(exp(x), x, 1)\n```\n\nY podemos definir explícitamente en qué orden se debe realizar la expansión de la serie:\n\n\n```python\nseries(exp(x), x, 1, 10)\n```\n\nLa expansión de la serie incluye el orden de la aproximación, lo cual es muy útil para realizar un seguimiento del orden de validez cuando hacemos cálculos con expansiones de la serie de diferente orden:\n\n\n```python\ns1 = cos(x).series(x, 0, 5)\ns1\n```\n\n\n```python\ns2 = sin(x).series(x, 0, 2)\ns2\n```\n\n\n```python\nexpand(s1 * s2)\n```\n\nSi queremos deshacernos de la información del error, podemos usar el método `removeO`:\n\n\n```python\nexpand(s1.removeO() * s2.removeO())\n```\n\nPero tenga en cuenta que esta no es la expansión correcta de $ \\cos(x) \\sin(x)$ a $ 5 $ ésimo orden:\n\n\n```python\n(cos(x)*sin(x)).series(x, 0, 6)\n```\n\n## Álgebra lineal\n\n### Matrices\n\nLas matrices se definen usando la clase `Matrix`:\n\n\n```python\nm11, m12, m21, m22 = symbols(\"m11, m12, m21, m22\")\nb1, b2 = symbols(\"b1, b2\")\n```\n\n\n```python\nA = Matrix([[m11, m12],[m21, m22]])\nA\n```\n\n\n```python\nb = Matrix([[b1], [b2]])\nb\n```\n\nCon las instancias de la clase `Matrix` podemos hacer las operaciones habituales de álgebra matricial:\n\n\n```python\nA**2\n```\n\n\n```python\nA * b\n```\n\nY calcular determinantes e inversas, y similares:\n\n\n```python\nA.det()\n```\n\n\n```python\nA.inv()\n```\n\n## Resolver ecuaciones\n\nPara resolver ecuaciones y sistemas de ecuaciones podemos usar la función `resolver`:\n\n\n```python\nsolve(x**2 - 1, x)\n```\n\n\n```python\nsolve(x**4 - x**2 - 1, x)\n```\n\nSistema de ecuaciones:\n\n\n```python\nsolve([x + y - 1, x - y - 1], [x,y])\n```\n\nEn cuanto a otras expresiones simbólicas:\n\n\n```python\nsolve([x + y - a, x - y - c], [x,y])\n```\n\n## Referencias\n\n* [The SymPy projects web page](http://sympy.org/en/index.html)\n* [The source code of SymPy](https://github.com/sympy/sympy)\n* [Online version of SymPy for testing and demonstrations](http://live.sympy.org)\n", "meta": {"hexsha": "0d1218a613d112294727b0b0170318c189483270", "size": 208660, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "lectures/data_manipulation/scientific_computing/sympy.ipynb", "max_stars_repo_name": "dannyowen1/mat281_portfolio_dannyowen1", "max_stars_repo_head_hexsha": "c7dbcfc5f7724d8bef1d48d2381f9c065a6d6f20", "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": "lectures/data_manipulation/scientific_computing/sympy.ipynb", "max_issues_repo_name": "dannyowen1/mat281_portfolio_dannyowen1", "max_issues_repo_head_hexsha": "c7dbcfc5f7724d8bef1d48d2381f9c065a6d6f20", "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/data_manipulation/scientific_computing/sympy.ipynb", "max_forks_repo_name": "dannyowen1/mat281_portfolio_dannyowen1", "max_forks_repo_head_hexsha": "c7dbcfc5f7724d8bef1d48d2381f9c065a6d6f20", "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": 77.5687732342, "max_line_length": 14644, "alphanum_fraction": 0.830489792, "converted": true, "num_tokens": 3327, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299550303293, "lm_q2_score": 0.936285002192296, "lm_q1q2_score": 0.8662789304739499}} {"text": "# Lecture 3: Birthday Problem, Properties of Probability\n\n## The Birthday Problem\nGiven $k$ people, what is the probability of at least 2 people having the same birthday?\n\nFirst, we need to define the problem:\n\n1. there are 365 days in a year (no leap-years)\n1. births can be on any day with equal probability (birthdays are independent of one another)\n1. treat people as distinguishable, because.\n\n$k \\le 1$ is meaningless, so we will not consider those cases.\n\nNow consider the case where you have more people than there are days in a year. In such a case, \n\n$$ P(k\\ge365) = 1$$\n\nNow think about the event of _no matches_. We can compute this probability using the naïve definition of probability:\n\n$$ P(\\text{no match}) = \\frac{365 \\times 364 \\times \\cdots \\times 365-k+1}{365^k} $$\n\nNow the event of _at least one match_ is the complement of _no matches_, so \n\n\\begin{align}\n P(\\text{at least one match}) &= 1 - P(\\text{no match}) \\\\\n &= 1 - \\frac{365 \\times 364 \\times \\cdots \\times 365-k+1}{365^k}\n\\end{align}\n\n\n\n\n```python\ndef bday_prob(k):\n def no_match(k):\n num = 1.0\n for n in [(365-e) for e in range(k)]:\n num *= n \n return num / 365**k \n return 1.0 - no_match(k) \n\nprint(\"At k=23 people, the probability of a match is {:0f}, already exceeding 0.5.\".format(bday_prob(23)))\nprint(\"And at k=50 people, the probability of a match is {:0f} is very close to 1.0.\".format(bday_prob(50)))\n```\n\n At k=23 people, the probability of a match is 0.507297, already exceeding 0.5.\n And at k=50 people, the probability of a match is 0.970374 is very close to 1.0.\n\n\n## Properties\n\nLet's derive some properties using nothing but the 2 axioms stated earlier.\n\n### Property 1\n> _The probability of an event $A$ is 1 minus the probability of that event's inverse (or complement)._\n>\n> \\begin\\{align\\}\n> P(A^{c}) &= 1 - P(A) \\\\\\\\\n> \\\\\\\\\n> \\because 1 &= P(S) \\\\\\\\\n> &= P(A \\cup A^{c}) \\\\\\\\\n> &= P(A) + P(A^{c}) & \\quad \\text{since } A \\cap A^{c} = \\emptyset ~~ \\blacksquare\n> \\end\\{align\\}\n\n### Property 2\n\n> _If $A$ is contained within $B$, then the probability of $A$ must be less than or equal to that for $B$._\n>\n> \\begin\\{align\\}\n> \\text{If } A &\\subseteq B \\text{, then } P(A) \\leq P(B) \\\\\\\\\n> \\\\\\\\\n> \\because B &= A \\cup ( B \\cap A^{c}) \\\\\\\\\n> P(B) &= P(A) + P(B \\cap A^{c}) \\\\\\\\\n> \\\\\\\\\n> \\implies P(B) &\\geq P(A) \\text{, since } P(B \\cap A^{c}) \\geq 0 & \\quad \\blacksquare\n> \\end\\{align\\}\n\n### Property 3, or the Inclusion/Exclusion Principle\n\n_The probability of a union of 2 events $A$ and $B$_\n\n> \\begin\\{align\\}\n> P(A \\cup B) &= P(A) + P(B) - P(A \\cap B) \\\\\\\\\n> \\\\\\\\\n> \\text{since } P(A \\cup B) &= P(A \\cup (B \\cap A^{c})) \\\\\\\\\n> &= P(A) + P(B \\cap A^{c}) \\\\\\\\ \n> \\\\\\\\\n> \\text{but note that } P(B) &= P(B \\cap A) + P(B \\cap A^{c}) \\\\\\\\\n> \\text{and since } P(B) - P(A \\cap B) &= P(B \\cap A^{c}) \\\\\\\\\n> \\\\\\\\\n> \\implies P(A \\cup B) &= P(A) + P(B) - P(A \\cap B) ~~~~ \\blacksquare\n> \\end\\{align\\}\n\n\n\nThis is the simplest case of the [principle of inclusion/exclusion](https://en.wikipedia.org/wiki/Inclusion%E2%80%93exclusion_principle).\n\nConsidering the 3-event case, we have:\n\n> \\begin\\{align\\}\n> P(A \\cup B \\cup C) &= P(A) + P(B) + P(C) - P(A \\cap B) - P(B \\cap C) - P(A \\cap C) + P(A \\cap B \\cap C)\n> \\end\\{align\\}\n>\n> ...where we sum up all of the separate events;\n> and then subtract each of the pair-wise intersections;\n> and finally add back in that 3-event intersection since that was subtracted in the previous step.\n\n\n\nFor the general case, we have:\n\n$$\n P(A_1 \\cup A_2 \\cup \\cdots \\cup A_n) = \\sum_{j=1}^n P(A_{j}) - \\sum_{iDerivatives are a fundamental tool of calculus. For example, the derivative of the position of a moving object with respect to time is the object's velocity: this measures how quickly the position of the object changes when time advances.\n\nThe derivative of f with respect to x is given by \n\n$ f'(x) = \\lim_{h \\to 0} \\frac{f(x+h) - f(x)}{h}$ \n\nwhen this limit exits.\n\n#### Basic derivative properties\n\nAssuming *c* and *n* to be real constants, then these theorems hold true:\n\nand if you want [proofs.](http://www2.bc.cc.ca.us/resperic/Math6A/Lectures/ch2/3/DerivativeRuleProofs.htm)\n\n>**1**. *The derivative of a constant is 0*\n\n$ \\frac{d}{dx}c = 0 $ \n\n\n```python\nc = 1\ndiff(c)\n```\n\n>**2**. *The derivative of a variable is 1*\n\n$ \\frac{d}{dx}x = 1 $\n\n\n```python\ndiff(x)\n```\n\n>**3**. *The derivative of a constant times a function is the same as the deriviative of that function times the constant*\n\n$ \\frac{d}{dx}(c \\cdot f(x)) = c \\cdot \\frac{d}{dx}f(x) = c \\cdot f'(x) $ \n\n\n```python\ndiff(1/x * c)\n```\n\n\n```python\nc * diff(1/x)\n```\n\n -1/x**2\n\n\n>**4**. The derivative of a function plus or minus another function is the same as if we took the derivative separately\n\n$ \\frac{d}{dx}(f(x) + g(x)) = f'(x) + g'(x) $ (true for minus as well) \n\n\n```python\ndiff(1/x + ln(x))\n```\n\n\n```python\ndiff(1/x) + diff(ln(x))\n```\n\n>**5**. The derivative\n\n$ \\frac{d}{dx}x^n = n \\cdot x^{n-1} $ the power rule\n\n\n```python\n## can you show that this rule holds?\n```\n\n\n```python\n## here is a way to write partial derivatives\nexpr = Derivative(1/x+y,x)\nexpr\n\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "4322961557bb5ceed89587e9bced77b836b22d6b", "size": 14824, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "math-essentials/calculus/sympy-primer.ipynb", "max_stars_repo_name": "chyld/demoX", "max_stars_repo_head_hexsha": "27f26a553aeb6682173f6b1b8dc8969101993324", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16, "max_stars_repo_stars_event_min_datetime": "2018-09-21T23:14:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-21T10:38:52.000Z", "max_issues_repo_path": "math-essentials/calculus/sympy-primer.ipynb", "max_issues_repo_name": "chyld/demoX", "max_issues_repo_head_hexsha": "27f26a553aeb6682173f6b1b8dc8969101993324", "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-essentials/calculus/sympy-primer.ipynb", "max_forks_repo_name": "chyld/demoX", "max_forks_repo_head_hexsha": "27f26a553aeb6682173f6b1b8dc8969101993324", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 27, "max_forks_repo_forks_event_min_datetime": "2018-01-08T22:59:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-09T06:44:38.000Z", "avg_line_length": 32.2260869565, "max_line_length": 1328, "alphanum_fraction": 0.6467215326, "converted": true, "num_tokens": 1007, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966671870766, "lm_q2_score": 0.9149009526726545, "lm_q1q2_score": 0.8660421926062161}} {"text": "# Section 4.3 $\\quad$ Subspaces (cont)\n\n## Definition of Linear Combination\n\nLet $\\mathbf{v}_1$, $\\mathbf{v}_2$, $\\cdots$, $\\mathbf{v}_k$ be vectors in a vector space $V$.



\n\n### Example 1\n\nEvery polynomial of degree $\\leq 2$ is a linear combination of $t^2$, $t$, $1$.\n\n### Example 2\n\nShow that the set of all vectors in $\\mathbb{R}^3$ of the form $\\left[\\begin{array}{c}a \\\\ b \\\\ a+b \\end{array}\\right]$ is a linear combination of $\\mathbf{v}_1 = \\left[\\begin{array}{c}1 \\\\ 0 \\\\ 1 \\end{array}\\right]$ and $\\mathbf{v}_2 = \\left[\\begin{array}{c}0 \\\\ 1 \\\\ 1 \\end{array}\\right]$.\n\n### Example 3\n\nIn $\\mathbb{R}^3$, let\n\\begin{equation*}\n \\mathbf{v}_1 = \\left[\\begin{array}{c}1 \\\\ 2 \\\\ 1 \\end{array}\\right],~~~\n \\mathbf{v}_2 = \\left[\\begin{array}{c}1 \\\\ 0 \\\\ 2 \\end{array}\\right],~~~\n \\mathbf{v}_3 = \\left[\\begin{array}{c}1 \\\\ 1 \\\\ 0 \\end{array}\\right]\n\\end{equation*}\nVerify that the vector\n\\begin{equation*}\n\\mathbf{v} = \\left[\\begin{array}{c}2 \\\\ 1 \\\\ 5 \\end{array}\\right]\n\\end{equation*}\nis a linear combination of $\\mathbf{v}_1$, $\\mathbf{v}_2$, and $\\mathbf{v}_3$.\n\n\n```python\nfrom sympy import *\n\na, b, c = symbols('a b c');\n\nEq1 = a + b + c - 2;\nEq2 = 2*a + c - 1;\nEq3 = a + 2*b - 5;\n\nsolve([Eq1, Eq2, Eq3], (a, b, c))\n```\n\n\n\n\n {a: 1, b: 2, c: -1}\n\n\n\n### Example 4\n\nConsider the homogeneous system\n$$A\\mathbf{x} = \\mathbf{0}$$\nwhere $A$ is an $m\\times n$ matrix. The set $W$ of solutions is a subset of $\\mathbb{R}^n$. Verify that $W$ is a subspace of $\\mathbb{R}^n$ (called **solution space**).\n\n**Remark** The set of all solutions of the linear system $A\\mathbf{x} = \\mathbf{b}$, with $\\mathbf{b} \\neq \\mathbf{0}$, is



\n", "meta": {"hexsha": "77c2398c3b038694e26635a70f0890b5192ef6cc", "size": 3645, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Jupyter_Notes/Lecture15_Sec4-3_SubspacesPart2.ipynb", "max_stars_repo_name": "xiuquan0418/MAT341", "max_stars_repo_head_hexsha": "2fb7ec4e5f0771f10719cb5e4a00a7ab07c49b59", "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_Notes/Lecture15_Sec4-3_SubspacesPart2.ipynb", "max_issues_repo_name": "xiuquan0418/MAT341", "max_issues_repo_head_hexsha": "2fb7ec4e5f0771f10719cb5e4a00a7ab07c49b59", "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_Notes/Lecture15_Sec4-3_SubspacesPart2.ipynb", "max_forks_repo_name": "xiuquan0418/MAT341", "max_forks_repo_head_hexsha": "2fb7ec4e5f0771f10719cb5e4a00a7ab07c49b59", "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.9802631579, "max_line_length": 324, "alphanum_fraction": 0.4803840878, "converted": true, "num_tokens": 659, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425311777929, "lm_q2_score": 0.9416541597976658, "lm_q1q2_score": 0.8659852150104232}} {"text": "###### Content under Creative Commons Attribution license CC-BY 4.0, code under MIT license (c)2014 L.A. Barba, G.F. Forsyth, C. Cooper. Based on [CFDPython](https://github.com/barbagroup/CFDPython), (c)2013 L.A. Barba, also under CC-BY license.\n\n# Space & Time\n\n## 1-D Diffusion\n\nWelcome back! This is the third Jupyter Notebook of the series *Space and Time — Introduction of Finite-difference solutions of PDEs*, the second module of [\"Practical Numerical Methods with Python\"](https://openedx.seas.gwu.edu/courses/course-v1:MAE+MAE6286+2017/about). \n\nIn the previous Jupyter notebooks of this series, we studied the numerical solution of the linear and non-linear convection equations using the finite-difference method, and learned about the CFL condition. Now, we will look at the one-dimensional diffusion equation:\n\n$$\n\\begin{equation}\n\\frac{\\partial u}{\\partial t}= \\nu \\frac{\\partial^2 u}{\\partial x^2}\n\\end{equation}\n$$\n\nwhere $\\nu$ is a constant known as the *diffusion coefficient*.\n\nThe first thing you should notice is that this equation has a second-order derivative. We first need to learn what to do with it!\n\n### Discretizing 2nd-order derivatives\n\nThe second-order derivative can be represented geometrically as the line tangent to the curve given by the first derivative. We will discretize the second-order derivative with a Central Difference scheme: a combination of forward difference and backward difference of the first derivative. Consider the Taylor expansion of $u_{i+1}$ and $u_{i-1}$ around $u_i$:\n\n$$\nu_{i+1} = u_i + \\Delta x \\frac{\\partial u}{\\partial x}\\big|_i + \\frac{\\Delta x^2}{2!} \\frac{\\partial ^2 u}{\\partial x^2}\\big|_i + \\frac{\\Delta x^3}{3!} \\frac{\\partial ^3 u}{\\partial x^3}\\big|_i + {\\mathcal O}(\\Delta x^4)\n$$\n\n$$\nu_{i-1} = u_i - \\Delta x \\frac{\\partial u}{\\partial x}\\big|_i + \\frac{\\Delta x^2}{2!} \\frac{\\partial ^2 u}{\\partial x^2}\\big|_i - \\frac{\\Delta x^3}{3!} \\frac{\\partial ^3 u}{\\partial x^3}\\big|_i + {\\mathcal O}(\\Delta x^4)\n$$\n\nIf we add these two expansions, the odd-numbered derivatives will cancel out. Neglecting any terms of ${\\mathcal O}(\\Delta x^4)$ or higher (and really, those are very small), we can rearrange the sum of these two expansions to solve for the second-derivative. \n\n$$\nu_{i+1} + u_{i-1} = 2u_i+\\Delta x^2 \\frac{\\partial ^2 u}{\\partial x^2}\\big|_i + {\\mathcal O}(\\Delta x^4)\n$$\n\nAnd finally:\n\n$$\n\\begin{equation}\n\\frac{\\partial ^2 u}{\\partial x^2}=\\frac{u_{i+1}-2u_{i}+u_{i-1}}{\\Delta x^2} + {\\mathcal O}(\\Delta x^2)\n\\end{equation}\n$$\n\nThe central difference approximation of the 2nd-order derivative is 2nd-order accurate.\n\n### Back to diffusion\n\nWe can now write the discretized version of the diffusion equation in 1D:\n\n$$\n\\begin{equation}\n\\frac{u_{i}^{n+1}-u_{i}^{n}}{\\Delta t}=\\nu\\frac{u_{i+1}^{n}-2u_{i}^{n}+u_{i-1}^{n}}{\\Delta x^2}\n\\end{equation}\n$$\n\nAs before, we notice that once we have an initial condition, the only unknown is $u_{i}^{n+1}$, so we re-arrange the equation to isolate this term:\n\n$$\n\\begin{equation}\nu_{i}^{n+1}=u_{i}^{n}+\\frac{\\nu\\Delta t}{\\Delta x^2}(u_{i+1}^{n}-2u_{i}^{n}+u_{i-1}^{n})\n\\end{equation}\n$$\n\nThis discrete equation allows us to write a program that advances a solution in time—but we need an initial condition. Let's continue using our favorite: the hat function. So, at $t=0$, $u=2$ in the interval $0.5\\le x\\le 1$ and $u=1$ everywhere else.\n\n### Stability of the diffusion equation\n\nThe diffusion equation is not free of stability constraints. Just like the linear and non-linear convection equations, there are a set of discretization parameters $\\Delta x$ and $\\Delta t$ that will make the numerical solution blow up. For the diffusion equation and the discretization used here, the stability condition for diffusion is\n\n$$\n\\begin{equation}\n\\nu \\frac{\\Delta t}{\\Delta x^2} \\leq \\frac{1}{2}\n\\end{equation}\n$$\n\n### And solve!\n\n We are ready to number-crunch!\n\nThe next two code cells initialize the problem by loading the needed libraries, then defining the solution parameters and initial condition. This time, we don't let the user choose just *any* $\\Delta t$, though; we have decided this is not safe: people just like to blow things up. Instead, the code calculates a value of $\\Delta t$ that will be in the stable range, according to the spatial discretization chosen! You can now experiment with different solution parameters to see how the numerical solution changes, but it won't blow up.\n\n\n```python\nimport numpy\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\n```\n\n\n```python\n# Set parameters.\nnx = 41 # number spatial grid points\nL = 2.0 # length of the domain\ndx = L / (nx - 1) # spatial grid size\nnu = 0.3 # viscosity\nsigma = 0.2 # CFL limit\ndt = sigma * dx**2 / nu # time-step size\nnt = 20 # number of time steps to compute\n\n# Get the grid point coordinates.\nx = numpy.linspace(0.0, L, num=nx)\n\n# Set the initial conditions.\nu0 = numpy.ones(nx)\nmask = numpy.where(numpy.logical_and(x >= 0.5, x <= 1.0))\nu0[mask] = 2.0\n```\n\n\n```python\n# Integrate in time.\nu = u0.copy()\nfor n in range(nt):\n u[1:-1] = u[1:-1] + nu * dt / dx**2 * (u[2:] - 2 * u[1:-1] + u[:-2])\n```\n\n\n```python\n# Plot the solution after nt time steps\n# along with the initial conditions.\npyplot.figure(figsize=(6.0, 4.0))\npyplot.xlabel('x')\npyplot.ylabel('u')\npyplot.grid()\npyplot.plot(x, u0, label='Initial',\n color='C0', linestyle='--', linewidth=2)\npyplot.plot(x, u, label='nt = {}'.format(nt),\n color='C1', linestyle='-', linewidth=2)\npyplot.legend(loc='upper right')\npyplot.xlim(0.0, L)\npyplot.ylim(0.5, 2.5);\n```\n\n## Animations\n\nLooking at before-and-after plots of the wave in motion is helpful, but it's even better if we can see it changing! \n\nFirst, let's import the `animation` module of `matplotlib` as well as a special IPython display method called `HTML` (more on this in a bit).\n\n##### Note\n\nYou will also have to install a video encoder/decoder named `ffmpeg`.\n\nIf you use Linux or OSX, you can install ffmpeg using conda:\n```\nconda install -c conda-forge ffmpeg\n```\n\nIf you use Windows, installation instructions can be found [here](http://adaptivesamples.com/how-to-install-ffmpeg-on-windows/).\n\n\n```python\nfrom matplotlib import animation\nfrom IPython.display import HTML\n```\n\nWe are going to create an animation.\nThis takes a few steps, but it's actually not hard to do!\n\nFirst, we define a function, called `diffusion`, that computes the numerical solution of the 1D diffusion equation over the time steps.\n(The function returns a list with `nt` elements, each one being a Numpy array.)\n\n\n```python\ndef diffusion(u0, sigma=0.5, nt=20):\n \"\"\"\n Computes the numerical solution of the 1D diffusion equation\n over the time steps.\n \n Parameters\n ----------\n u0 : numpy.ndarray\n The initial conditions as a 1D array of floats.\n sigma : float, optional\n The value of nu * dt / dx^2;\n default: 0.5.\n nt : integer, optional\n The number of time steps to compute;\n default: 20.\n \n Returns\n -------\n u_hist : list of numpy.ndarray objects\n The history of the numerical solution.\n \"\"\"\n u_hist = [u0.copy()]\n u = u0.copy()\n for n in range(nt):\n u[1:-1] = u[1:-1] + sigma * (u[2:] - 2 * u[1:-1] + u[:-2])\n u_hist.append(u.copy())\n return u_hist\n```\n\nWe now call the function to store the history of the solution:\n\n\n```python\n# Compute the history of the numerical solution.\nu_hist = diffusion(u0, sigma=sigma, nt=nt)\n```\n\nNext, we create a Matplotlib figure that we want to animate.\nFor now, the figure contains the initial solution (our top-hat function).\n\n\n```python\nfig = pyplot.figure(figsize=(6.0, 4.0))\npyplot.xlabel('x')\npyplot.ylabel('u')\npyplot.grid()\nline = pyplot.plot(x, u0,\n color='C0', linestyle='-', linewidth=2)[0]\npyplot.xlim(0.0, L)\npyplot.ylim(0.5, 2.5)\nfig.tight_layout()\n```\n\n**Note**: `pyplot.plot()` can (optionally) return several values. Since we're only creating one line, we ask it for the \"zeroth\" (and only...) line by adding `[0]` after the `pyplot.plot()` call.\n\nNow that our figure is initialized, we define a function `update_plot` to update the data of the line plot based on the time-step index.\n\n\n```python\ndef update_plot(n, u_hist):\n \"\"\"\n Update the line y-data of the Matplotlib figure.\n \n Parameters\n ----------\n n : integer\n The time-step index.\n u_hist : list of numpy.ndarray objects\n The history of the numerical solution.\n \"\"\"\n fig.suptitle('Time step {:0>2}'.format(n))\n line.set_ydata(u_hist[n])\n```\n\nNext, we create an `animation.FuncAnimation` object with the following arguments:\n\n* `fig`: the name of our figure,\n* `diffusion`: the name of our solver function,\n* `frames`: the number of frames to dra (which we set equal to `nt`),\n* `fargs`: extra arguments to pass to the function `diffusion`,\n* `interval`: the number of milliseconds each frame appears for.\n\n\n```python\n# Create an animation.\nanim = animation.FuncAnimation(fig, update_plot,\n frames=nt, fargs=(u_hist,),\n interval=100)\n```\n\nOk! Time to display the animation.\nWe use the `HTML` display method that we imported above and the `to_html5_video` method of the animation object to make it web compatible.\n\n\n```python\n# Display the video.\nHTML(anim.to_html5_video())\n```\n\n---\n\n###### The cell below loads the style of the notebook.\n\n\n```python\nfrom IPython.core.display import HTML\ncss_file = '../../styles/numericalmoocstyle.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\n```python\n\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "2614972cc69a9a6d894bb0e6a6c9625a917fd49e", "size": 45724, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "lessons/02_spacetime/02_03_1DDiffusion.ipynb", "max_stars_repo_name": "Fluidentity/numerical-mooc", "max_stars_repo_head_hexsha": "083bbe9dc923b0ada6db2ebfbe13392fb66c6fbc", "max_stars_repo_licenses": ["CC-BY-3.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": "lessons/02_spacetime/02_03_1DDiffusion.ipynb", "max_issues_repo_name": "Fluidentity/numerical-mooc", "max_issues_repo_head_hexsha": "083bbe9dc923b0ada6db2ebfbe13392fb66c6fbc", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lessons/02_spacetime/02_03_1DDiffusion.ipynb", "max_forks_repo_name": "Fluidentity/numerical-mooc", "max_forks_repo_head_hexsha": "083bbe9dc923b0ada6db2ebfbe13392fb66c6fbc", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 63.0675862069, "max_line_length": 18832, "alphanum_fraction": 0.7099991252, "converted": true, "num_tokens": 3761, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391664210672, "lm_q2_score": 0.9381240142763573, "lm_q1q2_score": 0.8659252081372342}} {"text": "# AMATH 301 - HW0\nUniversity of Washington\\\nDue 10/6/2021\n\n\n```python\n# Import block\nimport numpy as np\nfrom sympy import *\ninit_printing() # Format outputs to LaTeX pretty print where possible\nimport matplotlib.pyplot as plt\n%matplotlib inline\n```\n\nProblem 1: Install Matlab/Python. Done.\n\n\n```python\n# Problem 2\n\n# Symbolic functions\nt = symbols('t')\nf = t*sin(3*t) - exp(t)\ndf = diff(f)\ndisplay(f,df)\n```\n\n\n```python\n# Problem 2\n\n# Define domain\ndx = 0.1\nx = np.arange(-10,10+dx,dx)\n\n# Define Function\nf = lambda x: x*np.sin(3*x) - np.exp(x)\nflabel = 'f(x) = xsin(3x) - exp(x)'\n\n# Define 1st Derivative of Function\ndf = lambda x: 3*x*np.cos(3*x) - np.exp(x) + np.sin(3*x)\ndflabel = 'df/dx = 3*x*cos(3*x) - exp(x) + sin(3*x)'\n\n# Plot function to verify\nplt.style.use('dark_background') # Comment out for light background\nplt.figure(figsize=(15,8))\nplt.plot(x,f(x),label=flabel)\nplt.plot(x,df(x),label=dflabel)\n# plt.xlim(x[0],x[len(x)-1])\n# plt.ylim(-15,15)\nplt.axis([x[0],x[len(x)-1],-15,15])\nplt.legend();\n```\n\n\n```python\ndef nrsolv(fc,dfc,x0,tol):\n \"\"\"\n Newton-Raphson Method\n x0 = initial guess\n fc = defined function\n dfc = 1st derivative of defined function\n tol = tolerance\n \"\"\"\n # Run max 100 iterations\n for j in range(1, 101):\n if ( abs(fc(x0)) < 10e-6 ):\n display(\"Convergence at x = \" + str(x0))\n display(\"Iterations: \" + str(j))\n break\n elif j == 100:\n display(\"No convergence!\")\n else:\n x0 = x0 - fc(x0)/dfc(x0)\n```\n\n\n```python\nnrsolv(f,df,1,10e-6)\n```\n\n\n 'Convergence at x = -0.8857712789927595'\n\n\n\n 'Iterations: 6'\n\n\n\n```python\n# Problem 3\n\nA = Matrix([[1,2],\n [-1,1]])\nB = 2*eye(2)\nC = B.col_insert(2,Matrix([-3,-1]))\nD = Matrix([[1,2],\n [2,3],\n [-1,0]])\nx = Matrix([1,0])\ny = Matrix([0,1])\nz = Matrix([1,2,-1])\n```\n\n\n```python\n# 3a\ndisplay(A+B)\n\n#3b\ndisplay(3*x-4*y)\n\n#4b\n```\n\n\n$\\displaystyle \\left[\\begin{matrix}3 & 2\\\\-1 & 3\\end{matrix}\\right]$\n\n\n\n$\\displaystyle \\left[\\begin{matrix}3\\\\-4\\end{matrix}\\right]$\n\n", "meta": {"hexsha": "78f724f819b64a88482f9b560d007b2861c66341", "size": 87044, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "scientific_computing_UW-AMATH301/HW_Python/AMATH301_HW0.ipynb", "max_stars_repo_name": "jot33/learn_data_science", "max_stars_repo_head_hexsha": "8324672acff2523bc7a98eacaec96dd97335af09", "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": "scientific_computing_UW-AMATH301/HW_Python/AMATH301_HW0.ipynb", "max_issues_repo_name": "jot33/learn_data_science", "max_issues_repo_head_hexsha": "8324672acff2523bc7a98eacaec96dd97335af09", "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": "scientific_computing_UW-AMATH301/HW_Python/AMATH301_HW0.ipynb", "max_forks_repo_name": "jot33/learn_data_science", "max_forks_repo_head_hexsha": "8324672acff2523bc7a98eacaec96dd97335af09", "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": 315.3768115942, "max_line_length": 76764, "alphanum_fraction": 0.9278410919, "converted": true, "num_tokens": 718, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240108164656, "lm_q2_score": 0.9230391669503405, "lm_q1q2_score": 0.8659252054401426}} {"text": "# Quadratic Equations\n\nConsider the following equation:\n\n\\begin{equation}y = 2(x - 1)(x + 2)\\end{equation}\n\nIf you multiply out the factored ***x*** expressions, this equates to:\n\n\\begin{equation}y = 2x^{2} + 2x - 4\\end{equation}\n\nNote that the highest ordered term includes a squared variable (x2).\n\nLet's graph this equation for a range of ***x*** values:\n\n\n```python\nimport pandas as pd\n\n# Create a dataframe with an x column containing values to plot\ndf = pd.DataFrame ({'x': range(-9, 9)})\n\n# Add a y column by applying the quadratic equation to x\ndf['y'] = 2*df['x']**2 + 2 *df['x'] - 4\n\n# Plot the line\n%matplotlib inline\nfrom matplotlib import pyplot as plt\n\nplt.plot(df.x, df.y, color=\"grey\")\nplt.xlabel('x')\nplt.ylabel('y')\nplt.grid()\nplt.axhline()\nplt.axvline()\nplt.show()\n```\n\nNote that the graph shows a *parabola*, which is an arc-shaped line that reflects the x and y values calculated for the equation.\n\nNow let's look at another equation that includes an ***x2*** term:\n\n\\begin{equation}y = -2x^{2} + 6x + 7\\end{equation}\n\nWhat does that look like as a graph?:\n\n\n```python\nimport pandas as pd\n\n# Create a dataframe with an x column containing values to plot\ndf = pd.DataFrame ({'x': range(-8, 12)})\n\n# Add a y column by applying the quadratic equation to x\ndf['y'] = -2*df['x']**2 + 6*df['x'] + 7\n\n# Plot the line\n%matplotlib inline\nfrom matplotlib import pyplot as plt\n\nplt.plot(df.x, df.y, color=\"grey\")\nplt.xlabel('x')\nplt.ylabel('y')\nplt.grid()\nplt.axhline()\nplt.axvline()\nplt.show()\n```\n\nAgain, the graph shows a parabola, but this time instead of being open at the top, the parabola is open at the bottom.\n\nEquations that assign a value to ***y*** based on an expression that includes a squared value for ***x*** create parabolas. If the relationship between ***y*** and ***x*** is such that ***y*** is a *positive* multiple of the ***x2*** term, the parabola will be open at the top; when ***y*** is a *negative* multiple of the ***x2*** term, then the parabola will be open at the bottom.\n\nThese kinds of equations are known as *quadratic* equations, and they have some interesting characteristics. There are several ways quadratic equations can be written, but the *standard form* for quadratic equation is:\n\n\\begin{equation}y = ax^{2} + bx + c\\end{equation}\n\nWhere ***a***, ***b***, and ***c*** are numeric coefficients or constants.\n\nLet's start by examining the parabolas generated by quadratic equations in more detail.\n\n## Parabola Vertex and Line of Symmetry\nParabolas are symmetrical, with x and y values converging exponentially towards the highest point (in the case of a downward opening parabola) or lowest point (in the case of an upward opening parabola). The point where the parabola meets the line of symmetry is known as the *vertex*.\n\nRun the following cell to see the line of symmetry and vertex for the two parabolas described previously (don't worry about the calculations used to find the line of symmetry and vertex - we'll explore that later):\n\n\n```python\n%matplotlib inline\n\ndef plot_parabola(a, b, c):\n import pandas as pd\n import numpy as np\n from matplotlib import pyplot as plt\n \n # get the x value for the line of symmetry\n vx = (-1*b)/(2*a)\n \n # get the y value when x is at the line of symmetry\n vy = a*vx**2 + b*vx + c\n\n # Create a dataframe with an x column containing values from x-10 to x+10\n minx = int(vx - 10)\n maxx = int(vx + 11)\n df = pd.DataFrame ({'x': range(minx, maxx)})\n\n # Add a y column by applying the quadratic equation to x\n df['y'] = a*df['x']**2 + b *df['x'] + c\n\n # get min and max y values\n miny = df.y.min()\n maxy = df.y.max()\n\n # Plot the line\n plt.plot(df.x, df.y, color=\"grey\")\n plt.xlabel('x')\n plt.ylabel('y')\n plt.grid()\n plt.axhline()\n plt.axvline()\n\n # plot the line of symmetry\n sx = [vx, vx]\n sy = [miny, maxy]\n plt.plot(sx,sy, color='magenta')\n\n # Annotate the vertex\n plt.scatter(vx,vy, color=\"red\")\n plt.annotate('vertex',(vx, vy), xytext=(vx - 1, (vy + 5)* np.sign(a)))\n\n plt.show()\n\n\nplot_parabola(2, 2, -4) \n\nplot_parabola(-2, 3, 5) \n```\n\n## Parabola Intercepts\nRecall that linear equations create lines that intersect the **x** and **y** axis of a graph, and we call the points where these intersections occur *intercepts*. Now look at the graphs of the parabolas we've worked with so far. Note that these parabolas both have a y-intercept; a point where the line intersects the y axis of the graph (in other words, when x is 0). However, note that the parabolas have *two* x-intercepts; in other words there are two points at which the line crosses the x axis (and y is 0). Additionally, imagine a downward opening parabola with its vertex at -1, -1. This is perfectly possible, and the line would never have an x value greater than -1, so it would have *no* x-intercepts.\n\nRegardless of whether the parabola crosses the x axis or not, other than the vertex, for every ***y*** point in the parabola, there are *two* ***x*** points; one on the right (or positive) side of the axis of symmetry, and one of the left (or negative) side. The implications of this are what make quadratic equations so interesting. When we solve the equation for ***x***, there are *two* correct answers.\n\nLet's take a look at an example to demonstrate this. Let's return to the first of our quadratic equations, and we'll look at it in its *factored* form:\n\n\\begin{equation}y = 2(x - 1)(x + 2)\\end{equation}\n\nNow, let's solve this equation for a ***y*** value of 0. We can restate the equation like this:\n\n\\begin{equation}2(x - 1)(x + 2) = 0\\end{equation}\n\nThe equation is the product of two expressions **2(x - 1)** and **(x + 2)**. In this case, we know that the product of these expressions is 0, so logically *one or both of the expressions must return 0*.\n\nLet's try the first one:\n\n\\begin{equation}2(x - 1) = 0\\end{equation}\n\nIf we distrbute this, we get:\n\n\\begin{equation}2x - 2 = 0\\end{equation}\n\nThis simplifies to:\n\n\\begin{equation}2x = 2\\end{equation}\n\nWhich gives us a value for *x* of **1**.\n\nNow let's try the other expression:\n\n\\begin{equation}x + 2 = 0\\end{equation}\n\nThis gives us a value for *x* of **-2**.\n\nSo, when *y* is **0**, *x* is **-2** or **1**. Let's plot these points on our parabola:\n\n\n```python\nimport pandas as pd\n\n# Assign the calculated x values\nx1 = -2\nx2 = 1\n\n# Create a dataframe with an x column containing some values to plot\ndf = pd.DataFrame ({'x': range(x1-5, x2+6)})\n\n# Add a y column by applying the quadratic equation to x\ndf['y'] = 2*(df['x'] - 1) * (df['x'] + 2)\n\n# Get x at the line of symmetry (halfway between x1 and x2)\nvx = (x1 + x2) / 2\n\n# Get y when x is at the line of symmetry\nvy = 2*(vx -1)*(vx + 2)\n\n# get min and max y values\nminy = df.y.min()\nmaxy = df.y.max()\n\n# Plot the line\n%matplotlib inline\nfrom matplotlib import pyplot as plt\n\nplt.plot(df.x, df.y, color=\"grey\")\nplt.xlabel('x')\nplt.ylabel('y')\nplt.grid()\nplt.axhline()\nplt.axvline()\n\n# Plot calculated x values for y = 0\nplt.scatter([x1,x2],[0,0], color=\"green\")\nplt.annotate('x1',(x1, 0))\nplt.annotate('x2',(x2, 0))\n\n# plot the line of symmetry\nsx = [vx, vx]\nsy = [miny, maxy]\nplt.plot(sx,sy, color='magenta')\n\n# Annotate the vertex\nplt.scatter(vx,vy, color=\"red\")\nplt.annotate('vertex',(vx, vy), xytext=(vx - 1, (vy - 5)))\n\nplt.show()\n```\n\nSo from the plot, we can see that both of the values we calculated for ***x*** align with the parabola when ***y*** is 0. Additionally, because the parabola is symmetrical, we know that every pair of ***x*** values for each ***y*** value will be equidistant from the line of symmetry, so we can calculate the ***x*** value for the line of symmetry as the average of the ***x*** values for any value of ***y***. This in turn means that we know the ***x*** coordinate for the vertex (it's on the line of symmetry), and we can use the quadratic equation to calculate ***y*** for this point.\n\n## Solving Quadratics Using the Square Root Method\nThe technique we just looked at makes it easy to calculate the two possible values for ***x*** when ***y*** is 0 if the equation is presented as the product two expressions. If the equation is in standard form, and it can be factored, you could do the necessary manipulation to restate it as the product of two expressions. Otherwise, you can calculate the possible values for x by applying a different method that takes advantage of the relationship between squared values and the square root.\n\nLet's consider this equation:\n\n\\begin{equation}y = 3x^{2} - 12\\end{equation}\n\nNote that this is in the standard quadratic form, but there is no *b* term; in other words, there's no term that contains a coeffecient for ***x*** to the first power. This type of equation can be easily solved using the square root method. Let's restate it so we're solving for ***x*** when ***y*** is 0:\n\n\\begin{equation}3x^{2} - 12 = 0\\end{equation}\n\nThe first thing we need to do is to isolate the ***x2*** term, so we'll remove the constant on the left by adding 12 to both sides:\n\n\\begin{equation}3x^{2} = 12\\end{equation}\n\nThen we'll divide both sides by 3 to isolate x2:\n\n\\begin{equation}x^{2} = 4\\end{equation}\n\nNo we can isolate ***x*** by taking the square root of both sides. However, there's an additional consideration because this is a quadratic equation. The ***x*** variable can have two possibe values, so we must calculate the *principle* and *negative* square roots of the expression on the right:\n\n\\begin{equation}x = \\pm\\sqrt{4}\\end{equation}\n\nThe principle square root of 4 is 2 (because 22 is 4), and the corresponding negative root is -2 (because -22 is also 4); so *x* is **2** or **-2**.\n\nLet's see this in Python, and use the results to calculate and plot the parabola with its line of symmetry and vertex:\n\n\n```python\nimport pandas as pd\nimport math\n\ny = 0\nx1 = int(- math.sqrt(y + 12 / 3))\nx2 = int(math.sqrt(y + 12 / 3))\n\n# Create a dataframe with an x column containing some values to plot\ndf = pd.DataFrame ({'x': range(x1-10, x2+11)})\n\n# Add a y column by applying the quadratic equation to x\ndf['y'] = 3*df['x']**2 - 12\n\n# Get x at the line of symmetry (halfway between x1 and x2)\nvx = (x1 + x2) / 2\n\n# Get y when x is at the line of symmetry\nvy = 3*vx**2 - 12\n\n# get min and max y values\nminy = df.y.min()\nmaxy = df.y.max()\n\n# Plot the line\n%matplotlib inline\nfrom matplotlib import pyplot as plt\n\nplt.plot(df.x, df.y, color=\"grey\")\nplt.xlabel('x')\nplt.ylabel('y')\nplt.grid()\nplt.axhline()\nplt.axvline()\n\n# Plot calculated x values for y = 0\nplt.scatter([x1,x2],[0,0], color=\"green\")\nplt.annotate('x1',(x1, 0))\nplt.annotate('x2',(x2, 0))\n\n# plot the line of symmetry\nsx = [vx, vx]\nsy = [miny, maxy]\nplt.plot(sx,sy, color='magenta')\n\n# Annotate the vertex\nplt.scatter(vx,vy, color=\"red\")\nplt.annotate('vertex',(vx, vy), xytext=(vx - 1, (vy - 20)))\n\nplt.show()\n```\n\n## Solving Quadratics Using the Completing the Square Method\nIn quadratic equations where there is a *b* term; that is, a term containing **x** to the first power, it is impossible to directly calculate the square root. However, with some algebraic manipulation, you can take advantage of the ability to factor a polynomial expression in the form *a2 + 2ab + b2* as a binomial *perfect square* expression in the form *(a + b)2*.\n\nAt first this might seem like some sort of mathematical sleight of hand, but follow through the steps carefull and you'll see that there's nothing up my sleeve!\n\nThe underlying basis of this approach is that a trinomial expression like this:\n\n\\begin{equation}x^{2} + 24x + 12^{2}\\end{equation}\n\nCan be factored to this:\n\n\\begin{equation}(x + 12)^{2}\\end{equation}\n\nOK, so how does this help us solve a quadratic equation? Well, let's look at an example:\n\n\\begin{equation}y = x^{2} + 6x - 7\\end{equation}\n\nLet's start as we've always done so far by restating the equation to solve ***x*** for a ***y*** value of 0:\n\n\\begin{equation}x^{2} + 6x - 7 = 0\\end{equation}\n\nNow we can move the constant term to the right by adding 7 to both sides:\n\n\\begin{equation}x^{2} + 6x = 7\\end{equation}\n\nOK, now let's look at the expression on the left: *x2 + 6x*. We can't take the square root of this, but we can turn it into a trinomial that will factor into a perfect square by adding a squared constant. The question is, what should that constant be? Well, we know that we're looking for an expression like *x2 + 2**c**x + **c**2*, so our constant **c** is half of the coefficient we currently have for ***x***. This is **6**, making our constant **3**, which when squared is **9** So we can create a trinomial expression that will easily factor to a perfect square by adding 9; giving us the expression *x2 + 6x + 9*.\n\nHowever, we can't just add something to one side without also adding it to the other, so our equation becomes:\n\n\\begin{equation}x^{2} + 6x + 9 = 16\\end{equation}\n\nSo, how does that help? Well, we can now factor the trinomial expression as a perfect square binomial expression:\n\n\\begin{equation}(x + 3)^{2} = 16\\end{equation}\n\nAnd now, we can use the square root method to find x + 3:\n\n\\begin{equation}x + 3 =\\pm\\sqrt{16}\\end{equation}\n\nSo, x + 3 is **-4** or **4**. We isolate ***x*** by subtracting 3 from both sides, so ***x*** is **-7** or **1**:\n\n\\begin{equation}x = -7, 1\\end{equation}\n\nLet's see what the parabola for this equation looks like in Python:\n\n\n```python\nimport pandas as pd\nimport math\n\nx1 = int(- math.sqrt(16) - 3)\nx2 = int(math.sqrt(16) - 3)\n\n# Create a dataframe with an x column containing some values to plot\ndf = pd.DataFrame ({'x': range(x1-10, x2+11)})\n\n# Add a y column by applying the quadratic equation to x\ndf['y'] = ((df['x'] + 3)**2) - 16\n\n# Get x at the line of symmetry (halfway between x1 and x2)\nvx = (x1 + x2) / 2\n\n# Get y when x is at the line of symmetry\nvy = ((vx + 3)**2) - 16\n\n# get min and max y values\nminy = df.y.min()\nmaxy = df.y.max()\n\n# Plot the line\n%matplotlib inline\nfrom matplotlib import pyplot as plt\n\nplt.plot(df.x, df.y, color=\"grey\")\nplt.xlabel('x')\nplt.ylabel('y')\nplt.grid()\nplt.axhline()\nplt.axvline()\n\n# Plot calculated x values for y = 0\nplt.scatter([x1,x2],[0,0], color=\"green\")\nplt.annotate('x1',(x1, 0))\nplt.annotate('x2',(x2, 0))\n\n# plot the line of symmetry\nsx = [vx, vx]\nsy = [miny, maxy]\nplt.plot(sx,sy, color='magenta')\n\n# Annotate the vertex\nplt.scatter(vx,vy, color=\"red\")\nplt.annotate('vertex',(vx, vy), xytext=(vx - 1, (vy - 10)))\n\nplt.show()\n```\n\n## Vertex Form\nLet's look at another example of a quadratic equation in standard form:\n\n\\begin{equation}y = 2x^{2} - 16x + 2\\end{equation}\n\nWe can start to solve this by subtracting 2 from both sides to move the constant term from the right to the left:\n\n\\begin{equation}y - 2 = 2x^{2} - 16x\\end{equation}\n\nNow we can factor out the coefficient for x2, which is **2**. 2x2 is 2 • x2, and -16x is 2 • 8x:\n\n\\begin{equation}y - 2 = 2(x^{2} - 8x)\\end{equation}\n\nNow we're ready to complete the square, so we add the square of half of the -8x coefficient on the right side to the parenthesis. Half of -8 is -4, and -42 is 16, so the right side of the equation becomes *2(x2 - 8x + 16)*. Of course, we can't add something to one side of the equation without also adding it to the other side, and we've just added 2 • 16 (which is 32) to the right, so we must also add that to the left.\n\n\\begin{equation}y - 2 + 32 = 2(x^{2} - 8x + 16)\\end{equation}\n\nNow we can simplify the left and factor out a perfect square binomial expression on the right:\n\n\\begin{equation}y + 30 = 2(x - 4)^{2}\\end{equation}\n\nWe now have a squared term for ***x***, so we could use the square root method to solve the equation. However, we can also isolate ***y*** by subtracting 30 from both sides. So we end up restating the original equation as:\n\n\\begin{equation}y = 2(x - 4)^{2} - 30\\end{equation}\n\nLet's just quickly check our math with Python:\n\n\n```python\nfrom random import randint\nx = randint(1,100)\n\n2*x**2 - 16*x + 2 == 2*(x - 4)**2 - 30\n```\n\nSo we've managed to take the expression ***2x2 - 16x + 2*** and change it to ***2(x - 4)2 - 30***. How does that help?\n\nWell, when a quadratic equation is stated this way, it's in *vertex form*, which is generically described as:\n\n\\begin{equation}y = a(x - h)^{2} + k\\end{equation}\n\nThe neat thing about this form of the equation is that it tells us the coordinates of the vertex - it's at ***h,k***.\n\nSo in this case, we know that the vertex of our equation is 4, -30. Moreover, we know that the line of symmetry is at ***x = 4***.\n\nWe can then just use the equation to calculate two more points, and the three points will be enough for us to determine the shape of the parabola. We can simply choose any ***x*** value we like and substitute it into the equation to calculate the corresponding ***y*** value. For example, let's calculate ***y*** when x is **0**:\n\n\\begin{equation}y = 2(0 - 4)^{2} - 30\\end{equation}\n\nWhen we work through the equation, it gives us the answer **2**, so we know that the point 0, 2 is in our parabola.\n\nSo, we know that the line of symmetry is at ***x = h*** (which is 4), and we now know that the ***y*** value when ***x*** is 0 (***h*** - ***h***) is 2. The ***y*** value at the same distance from the line of symmetry in the negative direction will be the same as the value in the positive direction, so when ***x*** is ***h*** + ***h***, the ***y*** value will also be 2.\n\nThe following Python code encapulates all of this in a function that draws and annotates a parabola using only the ***a***, ***h***, and ***k*** values from a quadratic equation in vertex form:\n\n\n```python\ndef plot_parabola_from_vertex_form(a, h, k):\n import pandas as pd\n import math\n\n # Create a dataframe with an x column a range of x values to plot\n df = pd.DataFrame ({'x': range(h-10, h+11)})\n\n # Add a y column by applying the quadratic equation to x\n df['y'] = (a*(df['x'] - h)**2) + k\n\n # get min and max y values\n miny = df.y.min()\n maxy = df.y.max()\n\n # calculate y when x is 0 (h+-h)\n y = a*(0 - h)**2 + k\n\n # Plot the line\n %matplotlib inline\n from matplotlib import pyplot as plt\n\n plt.plot(df.x, df.y, color=\"grey\")\n plt.xlabel('x')\n plt.ylabel('y')\n plt.grid()\n plt.axhline()\n plt.axvline()\n\n # Plot calculated y values for x = 0 (h-h and h+h)\n plt.scatter([h-h, h+h],[y,y], color=\"green\")\n plt.annotate(str(h-h) + ',' + str(y),(h-h, y))\n plt.annotate(str(h+h) + ',' + str(y),(h+h, y))\n\n # plot the line of symmetry (x = h)\n sx = [h, h]\n sy = [miny, maxy]\n plt.plot(sx,sy, color='magenta')\n\n # Annotate the vertex (h,k)\n plt.scatter(h,k, color=\"red\")\n plt.annotate('v=' + str(h) + ',' + str(k),(h, k), xytext=(h - 1, (k - 10)))\n\n plt.show()\n\n \n# Call the function for the example discussed above\nplot_parabola_from_vertex_form(2, 4, -30)\n```\n\nIt's important to note that the vertex form specifically requires a *subtraction* operation in the factored perfect square term. For example, consider the following equation in the standard form:\n\n\\begin{equation}y = 3x^{2} + 6x + 2\\end{equation}\n\nThe steps to solve this are:\n1. Move the constant to the left side:\n\\begin{equation}y - 2 = 3x^{2} + 6x\\end{equation}\n2. Factor the ***x*** expressions on the right:\n\\begin{equation}y - 2 = 3(x^{2} + 2x)\\end{equation}\n3. Add the square of half the x coefficient to the right, and the corresponding multiple on the left:\n\\begin{equation}y - 2 + 3 = 3(x^{2} + 2x + 1)\\end{equation}\n4. Factor out a perfect square binomial:\n\\begin{equation}y + 1 = 3(x + 1)^{2}\\end{equation}\n5. Move the constant back to the right side:\n\\begin{equation}y = 3(x + 1)^{2} - 1\\end{equation}\n\nTo express this in vertex form, we need to convert the addition in the parenthesis to a subtraction:\n\n\\begin{equation}y = 3(x - -1)^{2} - 1\\end{equation}\n\nNow, we can use the a, h, and k values to define a parabola:\n\n\n```python\nplot_parabola_from_vertex_form(3, -1, -1)\n```\n\n## Shortcuts for Solving Quadratic Equations\nWe've spent some time in this notebook discussing how to solve quadratic equations to determine the vertex of a parabola and the ***x*** values in relation to ***y***. It's important to understand the techniques we've used, which incude:\n- Factoring\n- Calculating the Square Root\n- Completing the Square\n- Using the vertex form of the equation\n\nThe underlying algebra for all of these techniques is the same, and this consistent algebra results in some shortcuts that you can memorize to make it easier to solve quadratic equations without going through all of the steps:\n\n### Calculating the Vertex from Standard Form\nYou've already seen that converting a quadratic equation to the vertex form makes it easy to identify the vertex coordinates, as they're encoded as ***h*** and ***k*** in the equation itself - like this:\n\n\\begin{equation}y = a(x - \\textbf{h})^{2} + \\textbf{k}\\end{equation}\n\nHowever, what if you have an equation in standard form?:\n\n\\begin{equation}y = ax^{2} + bx + c\\end{equation}\n\nThere's a quick and easy technique you can apply to get the vertex coordinates. \n\n1. To find ***h*** (which is the x-coordinate of the vertex), apply the following formula:\n\\begin{equation}h = \\frac{-b}{2a}\\end{equation}\n2. After you've found ***h***, use it in the quadratic equation to solve for ***k***:\n\\begin{equation}\\textbf{k} = a\\textbf{h}^{2} + b\\textbf{h} + c\\end{equation}\n\nFor example, here's the quadratic equation in standard form that we previously converted to the vertex form:\n\n\\begin{equation}y = 2x^{2} - 16x + 2\\end{equation}\n\nTo find ***h***, we perform the following calculation:\n\n\\begin{equation}h = \\frac{-b}{2a}\\;\\;\\;\\;=\\;\\;\\;\\;\\frac{-1 \\cdot16}{2\\cdot2}\\;\\;\\;\\;=\\;\\;\\;\\;\\frac{16}{4}\\;\\;\\;\\;=\\;\\;\\;\\;4\\end{equation}\n\nThen we simply plug the value we've obtained for ***h*** into the quadratic equation in order to find ***k***:\n\n\\begin{equation}k = 2\\cdot(4^{2}) - 16\\cdot4 + 2\\;\\;\\;\\;=\\;\\;\\;\\;32 - 64 + 2\\;\\;\\;\\;=\\;\\;\\;\\;-30\\end{equation}\n\nNote that a vertex at 4,-30 is also what we previously calculated for the vertex form of the same equation:\n\n\\begin{equation}y = 2(x - 4)^{2} - 30\\end{equation}\n\n### The Quadratic Formula\nAnother useful formula to remember is the *quadratic formula*, which makes it easy to calculate values for ***x*** when ***y*** is **0**; or in other words:\n\n\\begin{equation}ax^{2} + bx + c = 0\\end{equation}\n\nHere's the formula:\n\n\\begin{equation}x = \\frac{-b \\pm \\sqrt{b^{2} - 4ac}}{2a}\\end{equation}\n\nLet's apply that formula to our equation, which you may remember looks like this:\n\n\\begin{equation}y = 2x^{2} - 16x + 2\\end{equation}\n\nOK, let's plug the ***a***, ***b***, and ***c*** variables from our equation into the quadratic formula:\n\n\\begin{equation}x = \\frac{--16 \\pm \\sqrt{-16^{2} - 4\\cdot2\\cdot2}}{2\\cdot2}\\end{equation}\n\nThis simplifes to:\n\n\\begin{equation}x = \\frac{16 \\pm \\sqrt{256 - 16}}{4}\\end{equation}\n\nThis in turn (with the help of a calculator) simplifies to:\n\n\\begin{equation}x = \\frac{16 \\pm 15.491933384829668}{4}\\end{equation}\n\nSo our positive value for ***x*** is:\n\n\\begin{equation}x = \\frac{16 + 15.491933384829668}{4}\\;\\;\\;\\;=7.872983346207417\\end{equation}\n\nAnd the negative value for ***x*** is:\n\n\\begin{equation}x = \\frac{16 - 15.491933384829668}{4}\\;\\;\\;\\;=0.12701665379258298\\end{equation}\n\n\n\nThe following Python code uses the vertex formula and the quadtratic formula to calculate the vertex and the -x and +x for y = 0, and then plots the resulting parabola:\n\n\n```python\ndef plot_parabola_from_formula (a, b, c):\n import math\n\n # Get vertex\n print('CALCULATING THE VERTEX')\n print('vx = -b / 2a')\n\n nb = -b\n a2 = 2*a\n print('vx = ' + str(nb) + ' / ' + str(a2))\n\n vx = -b/(2*a)\n print('vx = ' + str(vx))\n\n print('\\nvy = ax^2 + bx + c')\n print('vy =' + str(a) + '(' + str(vx) + '^2) + ' + str(b) + '(' + str(vx) + ') + ' + str(c))\n\n avx2 = a*vx**2\n bvx = b*vx\n print('vy =' + str(avx2) + ' + ' + str(bvx) + ' + ' + str(c))\n\n vy = avx2 + bvx + c\n print('vy = ' + str(vy))\n\n print ('\\nv = ' + str(vx) + ',' + str(vy))\n\n # Get +x and -x (showing intermediate calculations)\n print('\\nCALCULATING -x AND +x FOR y=0')\n print('x = -b +- sqrt(b^2 - 4ac) / 2a')\n\n\n b2 = b**2\n ac4 = 4*a*c\n print('x = ' + str(nb) + '+-sqrt(' + str(b2) + ' - ' + str(ac4) + ')/' + str(a2))\n\n sr = math.sqrt(b2 - ac4)\n print('x = ' + str(nb) + ' +- ' + str(sr) + ' / ' + str(a2))\n print('-x = ' + str(nb) + ' - ' + str(sr) + ' / ' + str(a2))\n print('+x = ' + str(nb) + ' + ' + str(sr) + ' / ' + str(a2))\n\n posx = (nb + sr) / a2\n negx = (nb - sr) / a2\n print('-x = ' + str(negx))\n print('+x = ' + str(posx))\n\n\n print('\\nPLOTTING THE PARABOLA')\n import pandas as pd\n\n # Create a dataframe with an x column a range of x values to plot\n df = pd.DataFrame ({'x': range(round(vx)-10, round(vx)+11)})\n\n # Add a y column by applying the quadratic equation to x\n df['y'] = a*df['x']**2 + b*df['x'] + c\n\n # get min and max y values\n miny = df.y.min()\n maxy = df.y.max()\n\n # Plot the line\n %matplotlib inline\n from matplotlib import pyplot as plt\n\n plt.plot(df.x, df.y, color=\"grey\")\n plt.xlabel('x')\n plt.ylabel('y')\n plt.grid()\n plt.axhline()\n plt.axvline()\n\n # Plot calculated x values for y = 0\n plt.scatter([negx, posx],[0,0], color=\"green\")\n plt.annotate('-x=' + str(negx) + ',' + str(0),(negx, 0), xytext=(negx - 3, 5))\n plt.annotate('+x=' + str(posx) + ',' + str(0),(posx, 0), xytext=(posx - 3, -10))\n\n # plot the line of symmetry\n sx = [vx, vx]\n sy = [miny, maxy]\n plt.plot(sx,sy, color='magenta')\n\n # Annotate the vertex\n plt.scatter(vx,vy, color=\"red\")\n plt.annotate('v=' + str(vx) + ',' + str(vy),(vx, vy), xytext=(vx - 1, vy - 10))\n\n plt.show()\n \n\nplot_parabola_from_formula (2, -16, 2)\n```\n", "meta": {"hexsha": "099a1147ef2573df16fb43b984e0674a7ec3c5b8", "size": 34434, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Basics Of Algebra by Hiren/01-07-Quadratic Equations.ipynb", "max_stars_repo_name": "awesome-archive/Basic-Mathematics-for-Machine-Learning", "max_stars_repo_head_hexsha": "b6699a9c29ec070a0b1615c46952cb0deeb73b54", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 401, "max_stars_repo_stars_event_min_datetime": "2018-08-29T04:55:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T11:03:39.000Z", "max_issues_repo_path": "Basics Of Algebra by Hiren/01-07-Quadratic Equations.ipynb", "max_issues_repo_name": "aligeekk/Basic-Mathematics-for-Machine-Learning", "max_issues_repo_head_hexsha": "8662076d60e89f58a6e81e4ca1377569472760a2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-09-28T13:52:53.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-28T18:13:53.000Z", "max_forks_repo_path": "Basics Of Algebra by Hiren/01-07-Quadratic Equations.ipynb", "max_forks_repo_name": "aligeekk/Basic-Mathematics-for-Machine-Learning", "max_forks_repo_head_hexsha": "8662076d60e89f58a6e81e4ca1377569472760a2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 135, "max_forks_repo_forks_event_min_datetime": "2018-08-29T05:04:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T07:04:25.000Z", "avg_line_length": 41.4368231047, "max_line_length": 721, "alphanum_fraction": 0.5520125457, "converted": true, "num_tokens": 8082, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582516374121, "lm_q2_score": 0.9304582607972163, "lm_q1q2_score": 0.8657525665629651}} {"text": "# First Order Initial Value Problem\n \n\nThe more general form of a first order Ordinary Differential Equation is: \n\\begin{equation}\n\\label{general ODE}\ny^{'}=f(t,y).\n\\end{equation}\nThis can be solved analytically by integrating both sides but this is not straight forward for most problems.\nNumerical methods can be used to approximate the solution at discrete points.\n\n\n## Euler method\n\nThe simplest one step numerical method is the Euler Method named after the most prolific of mathematicians [Leonhard Euler](https://en.wikipedia.org/wiki/Leonhard_Euler) (15 April 1707 – 18 September 1783) .\n\nThe general Euler formula to the first order equation\n$$ y^{'} = f(t,y) $$\napproximates the derivative at time point $t_i$\n$$y^{'}(t_i) \\approx \\frac{w_{i+1}-w_i}{t_{i+1}-t_{i}} $$\nwhere $w_i$ is the approximate solution of $y$ at time $t_i$.\nThis substitution changes the differential equation into a __difference__ equation of the form \n$$ \n\\frac{w_{i+1}-w_i}{t_{i+1}-t_{i}}=f(t_i,w_i) $$\nAssuming uniform stepsize $t_{i+1}-t_{i}$ is replaced by $h$, re-arranging the equation gives\n$$ w_{i+1}=w_i+hf(t_i,w_i),$$\n This can be read as the future $w_{i+1}$ can be approximated by the present $w_i$ and the addition of the input to the system $f(t,y)$ times the time step.\n\n\n\n```python\n## Library\nimport numpy as np\nimport math \n\n%matplotlib inline\nimport matplotlib.pyplot as plt # side-stepping mpl backend\nimport matplotlib.gridspec as gridspec # subplots\nimport warnings\n\nwarnings.filterwarnings(\"ignore\")\n\n```\n\n## Population growth\n\nThe general form of the population growth differential equation is: \n$$ y^{'}=\\epsilon y $$\nwhere $\\epsilon$ is the growth rate. The initial population at time $a$ is \n$$ y(a)=A $$\n$$ a\\leq t \\leq b. $$\nIntegrating gives the general analytic (exact) solution: \n$$ y=Ae^{\\epsilon x}. $$\nWe will use this equation to illustrate the application of the Euler method.\n \n## Discrete Interval\nThe continuous time $a\\leq t \\leq b $ is discretised into $N$ points seperated by a constant stepsize\n$$ h=\\frac{b-a}{N}.$$\nHere the interval is $0\\leq t \\leq 2$ \n$$ h=\\frac{2-0}{20}=0.1.$$\nThis gives the 21 discrete points:\n$$ t_0=0, \\ t_1=0.1, \\ ... t_{20}=2. $$\nThis is generalised to \n$$ t_i=0+i0.1, \\ \\ \\ i=0,1,...,20.$$\nThe plot below shows the discrete time steps.\n\n\n```python\n### Setting up time\nt_end=2.0\nt_start=0\nN=20\nh=(t_end-t_start)/(N)\ntime=np.arange(t_start,t_end+0.01,h)\nfig = plt.figure(figsize=(10,4))\nplt.plot(time,0*time,'o:',color='red')\nplt.xlim((0,2))\nplt.title('Illustration of discrete time points for h=%s'%(h))\n```\n\n## Initial Condition\nTo get a specify solution to a first order initial value problem, an __initial condition__ is required.\n\nFor our population problem the intial condition is:\n$$y(0)=10$$.\nThis gives the analytic solution\n$$y=10e^{\\epsilon t}.$$\n### Growth rate \nLet the growth rate $$\\epsilon=0.5$$ giving the analytic solution.\n$$y=10e^{0.5 t}.$$\nThe plot below shows the exact solution on the discrete time steps.\n\n\n```python\n## Analytic Solution y\ny=10*np.exp(0.5*time)\n\nfig = plt.figure(figsize=(10,4))\nplt.plot(time,y,'o:',color='black')\nplt.xlim((0,2))\nplt.xlabel('time')\nplt.ylabel('y')\nplt.title('Analytic (Exact) solution')\n```\n\n## Numerical approximation of Population growth\nThe differential equation is transformed using the Euler method into a difference equation of the form\n $$ w_{i+1}=w_{i}+h \\epsilon w_i. $$\nThis approximates a series of of values $w_0, \\ w_1, \\ ..., w_{N}$.\nFor the specific example of the population equation the difference equation is\n $$ w_{i+1}=w_{i}+h 0.5 w_i. $$\nwhere $w_0=10$. From this initial condition the series is approximated.\nThe plot below shows the exact solution $y$ in black circles and Euler approximation $w$ in blue squares. \n\n\n```python\nw=np.zeros(N+1)\nw[0]=10\nfor i in range (0,N):\n w[i+1]=w[i]+h*(0.5)*w[i]\n\nfig = plt.figure(figsize=(10,4))\nplt.plot(time,y,'o:',color='black',label='exact')\nplt.plot(time,w,'s:',color='blue',label='Euler')\nplt.xlim((0,2))\nplt.xlabel('time')\nplt.legend(loc='best')\nplt.title('Analytic and Euler solution')\n```\n\n## Error\nWith a numerical solution there are two types of error: \n* local truncation error at one time step; \n* global error which is the propagation of local error. \n\n### Derivation of Euler Local truncation error\nThe left hand side of a initial value problem $\\frac{dy}{dt}$ is approximated by __Taylors theorem__ expand about a point $t_0$ giving:\n\\begin{equation}y(t_1) = y(t_0)+(t_1-t_0)y^{'}(t_0) + \\frac{(t_1-t_0)^2}{2!}y^{''}(\\xi), \\ \\ \\ \\ \\ \\ \\xi \\in [t_0,t_1]. \\end{equation}\nRearranging and letting $h=t_1-t_0$ the equation becomes\n$$y^{'}(t_0)=\\frac{y(t_1)-y(t_0)}{h}-\\frac{h}{2}y^{''}(\\xi). $$\nFrom this the local truncation error is\n$$\\tau y^{'}(t_0)\\leq \\frac{h}{2}M $$\nwhere $y^{''}(t) \\leq M $.\n#### Derivation of Euler Local truncation error for the Population Growth\nIn most cases $y$ is unknown but in our example problem there is an exact solution which can be used to estimate the local truncation\n$$y'(t)=5e^{0.5 t}$$\n$$y''(t)=2.5e^{0.5 t}$$\nFrom this a maximum upper limit can be calculated for $y^{''} $ on the interval $[t_0,t_1]=[0,0.1]$\n$$y''(0.1)=2.5e^{0.1\\times 0.5}=2.63=M$$\n$$\\tau=\\frac{h}{2}2.63=0.1315 $$\nThe plot below shows the exact local truncation error $|y-w|$ (red triangle) and the upper limit of the Truncation error (black v) for the first two time points $t_0$ and $t_1$.\n\n\n```python\nfig = plt.figure(figsize=(10,4))\nplt.plot(time[0:2],np.abs(w[0:2]-y[0:2]),'^:'\n ,color='red',label='Error |y-w|')\nplt.plot(time[0:2],0.1*2.63/2*np.ones(2),'v:'\n ,color='black',label='Upper Local Truncation')\nplt.xlim((0,.15))\nplt.xlabel('time')\nplt.legend(loc='best')\nplt.title('Local Truncation Error')\n```\n\n## Global Error\nThe error does not stay constant accross the time this is illustrated in the figure below for the population growth equation. The actual error (red triangles) increases over time while the local truncation error (black v) remains constant.\n\n\n```python\nfig = plt.figure(figsize=(10,4))\nplt.plot(time,np.abs(w-y),'^:'\n ,color='red',label='Error |y-w|')\nplt.plot(time,0.1*2.63/2*np.ones(N+1),'v:'\n ,color='black',label='Upper Local Truncation')\nplt.xlim((0,2))\nplt.xlabel('time')\nplt.legend(loc='best')\nplt.title('Why Local Truncation does not extend to global')\n```\n\n## Theorems\nTo theorem below proves an upper limit of the global truncation error.\n### Euler Global Error\n__Theorem Global Error__\n\nSuppose $f$ is continuous and satisfies a Lipschitz Condition with constant\nL on $D=\\{(t,y)|a\\leq t \\leq b, -\\infty < y < \\infty \\}$ and that a constant M\nexists with the property that \n$$ |y^{''}(t)|\\leq M. $$\nLet $y(t)$ denote the unique solution of the Initial Value Problem\n$$ y^{'}=f(t,y) \\ \\ \\ a\\leq t \\leq b \\ \\ \\ y(a)=\\alpha $$\nand $w_0,w_1,...,w_N$ be the approx generated by the Euler method for some\npositive integer N. Then for $i=0,1,...,N$\n$$ |y(t_i)-w_i| \\leq \\frac{Mh}{2L}|e^{L(t_i-a)}-1|. $$\n\n### Theorems about Ordinary Differential Equations\n__Definition__\n\nA function $f(t,y)$ is said to satisfy a __Lipschitz Condition__ in the variable $y$ on \nthe set $D \\subset R^2$ if a constant $L>0$ exist with the property that\n$$ |f(t,y_1)-f(t,y_2)| < L|y_1-y_2| $$\nwhenever $(t,y_1),(t,y_2) \\in D$. The constant L is call the Lipschitz Condition\nof $f$.\n\n__Theorem__\nSuppose $f(t,y)$ is defined on a convex set $D \\subset R^2$. If a constant\n$L>0$ exists with\n$$ \\left|\\frac{\\partial f(t,y)}{\\partial y}\\right|\\leq L $$\nthen $f$ satisfies a Lipschitz Condition an $D$ in the variable $y$ with\nLipschitz constant L.\n\n\n### Global truncation error for the population equation\nFor the population equation specific values $L$ and $M$ can be calculated.\n\nIn this case $f(t,y)=\\epsilon y$ is continuous and satisfies a Lipschitz Condition with constant\n$$ \\left|\\frac{\\partial f(t,y)}{\\partial y}\\right|\\leq L $$\n$$ \\left|\\frac{\\partial \\epsilon y}{\\partial y}\\right|\\leq \\epsilon=0.5=L $$\n\non $D=\\{(t,y)|0\\leq t \\leq 2, 10 < y < 30 \\}$ and that a constant $M$\nexists with the property that \n$$ |y^{''}(t)|\\leq M. $$\n$$ |y^{''}(t)|=2.5e^{0.5\\times 2} \\leq 2.5 e=6.8. $$\nLet $y(t)$ denote the unique solution of the Initial Value Problem\n$$ y^{'}=0.5 y \\ \\ \\ 0\\leq t \\leq 10 \\ \\ \\ y(0)=10 $$\nand $w_0,w_1,...,w_N$ be the approx generated by the Euler method for some\npositive integer N. Then for $i=0,1,...,N$\n$$ |y(t_i)-w_i| \\leq \\frac{6.8 h}{2\\times 0.5}|e^{0.5(t_i-0)}-1| $$\n\nThe figure below shows the exact error $y-w$ in red triangles and the upper global error in black x's.\n\n\n```python\nfig = plt.figure(figsize=(10,4))\nplt.plot(time,np.abs(w-y),'^:'\n ,color='red',label='Error |y-w|')\nplt.plot(time,0.1*6.8*(np.exp(0.5*time)-1),'x:'\n ,color='black',label='Upper Global Truncation')\nplt.xlim((0,2))\nplt.xlabel('time')\nplt.legend(loc='best')\nplt.title('Global Truncation Error')\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "566f16d4ebb94a9e756ae822dfba10cfac4a1d2f", "size": 137873, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Chapter 01 - Euler Methods/.ipynb_checkpoints/01_Euler_method_with_Theorems_Growth_function-checkpoint.ipynb", "max_stars_repo_name": "jjcrofts77/Numerical-Analysis-Python", "max_stars_repo_head_hexsha": "97e4b9274397f969810581ff95f4026f361a56a2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 69, "max_stars_repo_stars_event_min_datetime": "2019-09-05T21:39:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T14:00:25.000Z", "max_issues_repo_path": "Chapter 01 - Euler Methods/.ipynb_checkpoints/01_Euler_method_with_Theorems_Growth_function-checkpoint.ipynb", "max_issues_repo_name": "jjcrofts77/Numerical-Analysis-Python", "max_issues_repo_head_hexsha": "97e4b9274397f969810581ff95f4026f361a56a2", "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": "Chapter 01 - Euler Methods/.ipynb_checkpoints/01_Euler_method_with_Theorems_Growth_function-checkpoint.ipynb", "max_forks_repo_name": "jjcrofts77/Numerical-Analysis-Python", "max_forks_repo_head_hexsha": "97e4b9274397f969810581ff95f4026f361a56a2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 13, "max_forks_repo_forks_event_min_datetime": "2021-06-17T15:34:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T14:53:43.000Z", "avg_line_length": 283.1067761807, "max_line_length": 28516, "alphanum_fraction": 0.9185699883, "converted": true, "num_tokens": 2861, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947070591977, "lm_q2_score": 0.9161096084360388, "lm_q1q2_score": 0.8657187310581309}} {"text": "# Solve a nonlinear system\n\\begin{align}\n3x_1 - \\cos(x_2x_3) - \\frac{1}{2}& = 0\\\\\nx_1^2 - 81(x_2+0.1)^2 + \\sin(x_3) +1.06& = 0\\\\\ne^{-x_1x_2} + 20 x_3 + \\frac{10\\pi-3}{3}& = 0\n\\end{align}\n\n\n\n```julia\nusing Printf\nusing ForwardDiff\nusing LinearAlgebra\nusing NLsolve\n```\n\n## Hand Coded Jacobian\n\n\n```julia\nfunction F(x)\n return [3*x[1] - cos(x[2]*x[3]) - 0.5\n x[1]^2 - 81 * (x[2]+0.1)^2 + sin(x[3])+1.06\n exp(-x[1]*x[2]) + 20 * x[3] + (10 * π-3)/3];\nend\n\n\nfunction J(x)\n J_ = zeros(3,3);\n J_[1,1] = 3;\n J_[1,2] = x[3] * sin(x[2]*x[3]);\n J_[1,3] = x[2] * sin(x[2]*x[3]); \n \n J_[2,1] = 2*x[1];\n J_[2,2] =-162 * (x[2]+0.1);\n J_[2,3] = cos(x[3]);\n \n J_[3,1] = -x[2] * exp(-x[1]*x[2]);\n J_[3,2] = -x[1] * exp(-x[1]*x[2]) \n J_[3,3] = 20;\n return J_\nend\n```\n\n\n```julia\nF(zeros(3))\n```\n\n\n```julia\nJ([0., 0., 0.])\n```\n\n\n```julia\n# starting guess\nx = zeros(3);\nδ = zeros(3);\nn_iters = 20;\ntol = 1e-10;\n\nfor n in 1:n_iters\n δ .= -J(x)\\F(x);\n @. x += δ;\n f_err = norm(F(x));\n @printf(\"%d: ||F(x)|| = %g\\n\",n, f_err);\n \n if(f_err ForwardDiff.jacobian(F, x);\n```\n\n\n```julia\nJ_auto(x)\n```\n\n\n```julia\n# starting guess\nx = zeros(3);\nδ = zeros(3);\nn_iters = 20;\ntol = 1e-10;\n\nfor n in 1:n_iters\n δ .= -J_auto(x)\\F(x);\n @. x += δ;\n f_err = norm(F(x));\n @printf(\"%d: ||F(x)|| = %g\\n\",n, f_err);\n \n if(f_err0$ is the investment accelerator coefficient - equation $(2)$ asserts that people invest in physical capital when income is increasing and disinvest when it is decreasing\n\nEquations $(1), (2), and (3)$ imply the following second-order linear difference equation for national income: \n\n* $Y_t = (a+b) Y_{t-1} - b Y_{t-2} + (\\gamma + G_t)$\n\nor\n\n* $Y_t = \\rho_1 Y_{t-1} + \\rho_2 Y_{t-2} + (\\gamma + G_t)$ $(4)$\n\nwhere $ρ_1=(a+b)$ and $ρ_2=−b$\n\nTo complete the model, we require two initial conditions\n\nIf the model is to generate time series for $t=0, \\ldots, T$, we require initial values,\n\n* $Y_{-1} = \\bar Y_{-1}, \\quad Y_{-2} = \\bar Y_{-2}$\n\nWe’ll ordinarily set the parameters $(a,b)$ so that starting from an arbitrary pair of initial conditions $(\\bar Y_{-1}, \\bar Y_{-2})$, national income $Y_t$ converges to a constant value as $t$ becomes large.\n\nWe are interested in studying\n\n* the transient fluctuations in $Y_t$ as it converges to its **steady state** level\n* the **rate** at which it converges to a steady state level\n\nThe deterministic version of the model described so far — meaning that no random shocks hit aggregate demand — has only transient fluctuations.\n\nWe can convert the model to one that has persistent irregular fluctuations by adding a random shock to aggregate demand\n\n##### Stochastic version of the model\n\nWe create a **random** or **stochastic** version of the model by adding a random process of **shocks** or **disturbances** $\\{\\sigma \\epsilon_t \\}$ to the right side of equation $(4)$, leading to the second-order scalar linear stochastic difference equation:\n\n* $Y_t = G_t + a (1-b) Y_{t-1} - a b Y_{t-2} + \\sigma \\epsilon_{t}$ $(5)$\n\n##### Mathematical analysis of the model\n\nTo get started, let’s set $G_t≡0$, $σ=0$, and $γ=0$.\n\nThen we can write equation $(5)$ as\n\n* $Y_t = \\rho_1 Y_{t-1} + \\rho_2 Y_{t-2}$\n\nor\n\n* $Y_{t+2} - \\rho_1 Y_{t+1} - \\rho_2 Y_t = 0$ $(6)$\n\nTo discover the properties of the solution of $(6)$, it is useful first to form the characteristic polynomial for $(6)$:\n\n* $z^2−ρ_1z−ρ_2$ $(7)$\n\nwhere $z$ is possibly a complex number\n\nWe want to find the two zeros (a.k.a. roots) – namely $λ_1,λ_2$ – of the characteristic polynomial.\n\nThese are two special values of $z$, say $z=λ_1$ and $z=λ_2$, such that if we set $z$ equal to one of these values in expression $(7)$, the characteristic polynomial $(7)$ equals zero:\n\n* $z^2−ρ_1z−ρ_2=(z−λ_1)(z−λ_2)=0$ $(8)$\n\nEquation $(8)$ is said to **factor** the characteristic polynomial\n\nWhen the roots are complex, they will occur as a *complex conjugate pair*\n\nWhen the roots are complex, it is convenient to represent them in the polar form\n\n* $λ_1=re^{iω}, λ2=re^{−iω}$\n\nwhere $r$ is the amplitude of the complex number and $ω$ is its angle or phase\n\nThese can also be represented as\n\n* $λ_1=r(cos(ω)+isin(ω))\\\\ λ_2=r(cos(ω)−isin(ω))$\n\nGiven initial conditions $Y_{−1},Y_{−2}$, we want to generate a solution of the difference equation $(6)$\n\nIt can be represented as\n* $Y_t = λ_1^t c_1 + λ_2^t c_2$\n\nwhere $c1$ and $c2$ are constants that depend on the two initial conditions and on $ρ_1,ρ_2$\n\nWhen the roots are complex, it is useful to pursue the following calculations\n\nNotice that:\n\n* $$\n\\begin{eqnarray}\nY_t & = & c_1 (r e^{i ω})^t + c_2 (r e^{-i ω})^t \\\\\n& = & c_1 r^t e^{iω t} + c_2 r^t e^{-i ω t} \\\\\n& = & c_1 r^t [\\cos(ω t) + i \\sin(ω t) ] + c_2 r^t [\\cos(ω t) - i \\sin(ω t) ] \\\\\n& = & (c_1 + c_2) r^t \\cos(ω t) + i (c_1 - c_2) r^t \\sin(ω t)\n\\end{eqnarray}\n$$\n\nThe only way that $Y_t$\ncan be a real number for each t is if $c_1+c_2$ is a real number and $c_1−c_2$ is an imaginary number This happens only when $c_1$ and $c_2$ are complex conjugates, in which case they can be written in the polar forms $c_1=ve^{iθ}, c_2=ve^{−iθ}$\n\nSo we can write\n\n* $$\n\\begin{eqnarray}\nY_t & = & v e^{i \\theta} r^t e^{i \\omega t} + v e ^{- i \\theta} r^t e^{-i \\omega t} \\\\\n& = & v r^t [ e^{i(\\omega t + \\theta)} + e^{-i (\\omega t +\\theta)}] \\\\\n& = & 2 v r^t \\cos (\\omega t + \\theta)\n\\end{eqnarray}\n$$\n\nwhere $v$ and $θ$ are constants that must be chosen to satisfy initial conditions for $Y_1,Y_2$\n\nwhere $~c_1, ~c_2$ is a pair of constants chosen to satisfy the given initial conditions for $Y_1,Y_2$\n\nThis formula shows that when the roots are complex, $Y_t$ displays oscillations with period $\\check p =\n\\frac{2π}{ω}$ and damping factor $r$ We say that $\\check p$ is the period because in that amount of time the cosine wave $cos(ωt+θ)$\n\ngoes through exactly one complete cycles (Draw a cosine funtion to convince yourself of this please)\n\nRemark: Following [Sam39], we want to choose the parameters $a,b$\nof the model so that the absolute values (of the possibly complex) roots $λ_1,λ_2$ of the characteristic polynomial are both strictly less than one:\n\n* $|λ_j|<1 \\text{ for } j=1,2$\n\nRemark: When both roots $λ_1,λ_2$ of the characteristic polynomial have absolute values strictly less than one, the absolute value of the larger one governs the rate of convergence to the steady state of the non stochastic version of the model\n\n##### Things this lecture does\n\nWe write a function to generate simulations of a ${Y_t}$ sequence as a function of time\n\nThe function requires that we put in initial conditions for $Y_1,Y_2$\n\nThe function checks that $a,b$ are set so that $λ_1,λ_2$ are less than unity in absolute value (also called “modulus”)\n\nThe function also tells us whether the roots are complex, and, if they are complex, returns both their real and complex parts\n\nIf the roots are both real, the function returns their values We use our function written to simulate paths that are stochastic (when $σ>0$)\n\nWe have written the function in a way that allows us to input ${G_t}$ paths of a few simple forms, e.g.,\n\n* one time jumps in G at some time\n* a permanent jump in G that occurs at some time\n\nWe proceed to use the Samuelson multiplier-accererator model as a laboratory to make a simple OOP example\n\nThe “state” that determines next period’s $Y_{t+1}$ is now not just the current value $Y_t$ but also the once lagged value $Y_{t−1}$\n\nThis involves a little more bookkeeping than is required in the Solow model class definition\n\n**We use the Samuelson multiplier-accelerator model as a vehicle for teaching how we can gradually add more features to the class.**\n\nWe want to have a method in the class that automatically generates a simulation, either nonstochastic $(σ=0)$ or stochastic $(σ>0)$\n\nWe also show how to map the Samuelson model into a simple instance of the `LinearStateSpace` class described here\n\nWe can use a `LinearStateSpace` instance to do various things that we did above with our homemade function and class\n\nAmong other things, we show by example that the eigenvalues of the matrix $A$\n\nthat we use to form the instance of the LinearStateSpace class for the Samuelson model equal the roots of the characteristic polynomial $(7)$ for the Samuelson multiplier accelerator model\n\nHere is the formula for the matrix $A$\nin the linear state space system in the case that government expenditures are a constant $G$\n\n* $A = \\begin{bmatrix} 1 & 0 & 0 \\cr \\gamma + G & \\rho_1 & \\rho_2 \\cr 0 & 1 & 0 \\end{bmatrix}$\n\n##### Implementation\n\nWe’ll start by drawing an informative graph from page 189 of [Sar87]\n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\ndef param_plot():\n\n \"\"\"this function creates the graph on page 189 of Sargent Macroeconomic Theory, second edition, 1987\"\"\"\n\n fig, ax = plt.subplots(figsize=(12, 8))\n ax.set_aspect('equal')\n\n # Set axis\n xmin, ymin = -3, -2\n xmax, ymax = -xmin, -ymin\n plt.axis([xmin, xmax, ymin, ymax])\n\n # Set axis labels\n ax.set(xticks=[], yticks=[])\n ax.set_xlabel(r'$\\rho_2$', fontsize=16)\n ax.xaxis.set_label_position('top')\n ax.set_ylabel(r'$\\rho_1$', rotation=0, fontsize=16)\n ax.yaxis.set_label_position('right')\n\n # Draw (t1, t2) points\n ρ1 = np.linspace(-2, 2, 100)\n ax.plot(ρ1, -abs(ρ1) + 1, c='black')\n ax.plot(ρ1, np.ones_like(ρ1) * -1, c='black')\n ax.plot(ρ1, -(ρ1**2 / 4), c='black')\n\n # Turn normal axes off\n for spine in ['left', 'bottom', 'top', 'right']:\n ax.spines[spine].set_visible(False)\n\n # Add arrows to represent axes\n axes_arrows = {'arrowstyle': '<|-|>', 'lw': 1.3}\n ax.annotate('', xy=(xmin, 0), xytext=(xmax, 0), arrowprops=axes_arrows)\n ax.annotate('', xy=(0, ymin), xytext=(0, ymax), arrowprops=axes_arrows)\n\n # Annotate the plot with equations\n plot_arrowsl = {'arrowstyle': '-|>', 'connectionstyle': \"arc3, rad=-0.2\"}\n plot_arrowsr = {'arrowstyle': '-|>', 'connectionstyle': \"arc3, rad=0.2\"}\n ax.annotate(r'$\\rho_1 + \\rho_2 < 1$', xy=(0.5, 0.3), xytext=(0.8, 0.6),\n arrowprops=plot_arrowsr, fontsize='12')\n ax.annotate(r'$\\rho_1 + \\rho_2 = 1$', xy=(0.38, 0.6), xytext=(0.6, 0.8),\n arrowprops=plot_arrowsr, fontsize='12')\n ax.annotate(r'$\\rho_2 < 1 + \\rho_1$', xy=(-0.5, 0.3), xytext=(-1.3, 0.6),\n arrowprops=plot_arrowsl, fontsize='12')\n ax.annotate(r'$\\rho_2 = 1 + \\rho_1$', xy=(-0.38, 0.6), xytext=(-1, 0.8),\n arrowprops=plot_arrowsl, fontsize='12')\n ax.annotate(r'$\\rho_2 = -1$', xy=(1.5, -1), xytext=(1.8, -1.3),\n arrowprops=plot_arrowsl, fontsize='12')\n ax.annotate(r'${\\rho_1}^2 + 4\\rho_2 = 0$', xy=(1.15, -0.35),\n xytext=(1.5, -0.3), arrowprops=plot_arrowsr, fontsize='12')\n ax.annotate(r'${\\rho_1}^2 + 4\\rho_2 < 0$', xy=(1.4, -0.7),\n xytext=(1.8, -0.6), arrowprops=plot_arrowsr, fontsize='12')\n\n # Label categories of solutions\n ax.text(1.5, 1, 'Explosive\\n growth', ha='center', fontsize=16)\n ax.text(-1.5, 1, 'Explosive\\n oscillations', ha='center', fontsize=16)\n ax.text(0.05, -1.5, 'Explosive oscillations', ha='center', fontsize=16)\n ax.text(0.09, -0.5, 'Damped oscillations', ha='center', fontsize=16)\n\n # Add small marker to y-axis\n ax.axhline(y=1.005, xmin=0.495, xmax=0.505, c='black')\n ax.text(-0.12, -1.12, '-1', fontsize=10)\n ax.text(-0.12, 0.98, '1', fontsize=10)\n\n return fig\n\nparam_plot()\nplt.show()\n```\n\nThe graph portrays regions in which the $(λ_1,λ_2)$ root pairs implied by the $(ρ_1=(a+b),ρ_2=−b)$ difference equation parameter pairs in the Samuelson model are such that:\n\n* $(λ_1,λ_2)$ are complex with modulus less than 1 - in this case, the ${Y_t}$ sequence displays damped oscillations\n* $(λ_1,λ_2)$ are both real, but one is strictly greater than 1 - this leads to explosive growth\n* $(λ_1,λ_2)$ are both real, but one is strictly less than −1 - this leads to explosive oscillations\n* $(λ_1,λ_2)$ are both real and both are less than 1 in absolute value - in this case, there is smooth convergence to the steady state without damped cycles\n\nLater we’ll present the graph with a red mark showing the particular point implied by the setting of $(a,b)$\n\n##### **Function to describe implications of characteristic polynomial**\n\n\n```python\ndef categorize_solution(ρ1, ρ2):\n \"\"\"this function takes values of ρ1 and ρ2 and uses them to classify the type of solution\"\"\"\n\n discriminant = ρ1 ** 2 + 4 * ρ2\n if ρ2 > 1 + ρ1 or ρ2 < -1:\n print('Explosive oscillations')\n elif ρ1 + ρ2 > 1:\n print('Explosive growth')\n elif discriminant < 0:\n print('Roots are complex with modulus less than one; therefore damped oscillations')\n else:\n print('Roots are real and absolute values are less than zero; therefore get smooth convergence to a steady state')\n```\n\n\n```python\n### Test the categorize_solution function\n\ncategorize_solution(1.3, -.4)\n```\n\n Roots are real and absolute values are less than zero; therefore get smooth convergence to a steady state\n\n\n##### **Function for plotting $Y_t$ paths**\n\n* A useful function for our work below\n\n\n```python\ndef plot_y(function=None):\n \"\"\"function plots path of Y_t\"\"\"\n plt.subplots(figsize=(12, 8))\n plt.plot(function)\n plt.xlabel('Time $t$')\n plt.ylabel('$Y_t$', rotation=0)\n plt.grid()\n plt.show()\n```\n\n#### **Manual or “by hand” root calculations**\n\nThe following function calculates roots of the characteristic polynomial using high school algebra\n\n(We’ll calculate the roots in other ways later)\n\nThe function also plots a $Y_t$ starting from initial conditions that we set\n\n\n```python\nfrom cmath import sqrt\n\n##=== This is a 'manual' method ===#\n\ndef y_nonstochastic(y_0=100, y_1=80, α=.92, β=.5, γ=10, n=80):\n\n \"\"\"Takes values of parameters and computes roots of characteristic polynomial.\n It tells whether they are real or complex and whether they are less than unity in absolute value.\n It also computes a simulation of length n starting from the two given initial conditions for national income\"\"\"\n\n roots = []\n\n ρ1 = α + β\n ρ2 = -β\n\n print(f'ρ_1 is {ρ1}')\n print(f'ρ_2 is {ρ2}')\n\n discriminant = ρ1 ** 2 + 4 * ρ2\n\n if discriminant == 0:\n roots.append(-ρ1 / 2)\n print('Single real root: ')\n print(''.join(str(roots)))\n elif discriminant > 0:\n roots.append((-ρ1 + sqrt(discriminant).real) / 2)\n roots.append((-ρ1 - sqrt(discriminant).real) / 2)\n print('Two real roots: ')\n print(''.join(str(roots)))\n else:\n roots.append((-ρ1 + sqrt(discriminant)) / 2)\n roots.append((-ρ1 - sqrt(discriminant)) / 2)\n print('Two complex roots: ')\n print(''.join(str(roots)))\n\n if all(abs(root) < 1 for root in roots):\n print('Absolute values of roots are less than one')\n else:\n print('Absolute values of roots are not less than one')\n\n def transition(x, t): return ρ1 * x[t - 1] + ρ2 * x[t - 2] + γ\n\n y_t = [y_0, y_1]\n\n for t in range(2, n):\n y_t.append(transition(y_t, t))\n\n return y_t\n\nplot_y(y_nonstochastic())\n\n```\n\n##### **Reverse engineering parameters to generate damped cycles**\n\nThe next cell writes code that takes as inputs the modulus $r$ and phase $ϕ$ of a conjugate pair of complex numbers in polar form\n$λ_1=r \\space exp(iϕ),\\space λ_2=r \\space exp(−iϕ)$\n\n* The code assumes that these two complex numbers are the roots of the characteristic polynomial\n* It then reverse engineers $(a,b)$ and $(ρ_1,ρ_2)$, pairs that would generate those roots\n\n\n```python\n### code to reverse engineer a cycle\n### y_t = r^t (c_1 cos(ϕ t) + c2 sin(ϕ t))\n###\n\nimport cmath\nimport math\n\ndef f(r, ϕ):\n \"\"\"\n Takes modulus r and angle ϕ of complex number r exp(j ϕ)\n and creates ρ1 and ρ2 of characteristic polynomial for which\n r exp(j ϕ) and r exp(- j ϕ) are complex roots.\n\n Returns the multiplier coefficient a and the accelerator coefficient b\n that verifies those roots.\n \"\"\"\n g1 = cmath.rect(r, ϕ) # Generate two complex roots\n g2 = cmath.rect(r, -ϕ)\n ρ1 = g1 + g2 # Implied ρ1, ρ2\n ρ2 = -g1 * g2\n b = -ρ2 # Reverse engineer a and b that validate these\n a = ρ1 - b\n return ρ1, ρ2, a, b\n\n## Now let's use the function in an example\n## Here are the example paramters\n\nr = .95\nperiod = 10 # Length of cycle in units of time\nϕ = 2 * math.pi/period\n\n## Apply the function\n\nρ1, ρ2, a, b = f(r, ϕ)\n\nprint(f\"a, b = {a}, {b}\")\nprint(f\"ρ1, ρ2 = {ρ1}, {ρ2}\")\n```\n\n a, b = (0.6346322893124001+0j), (0.9024999999999999-0j)\n ρ1, ρ2 = (1.5371322893124+0j), (-0.9024999999999999+0j)\n\n\n\n```python\n\n\n## Print the real components of ρ1 and ρ2\n\nρ1 = ρ1.real\nρ2 = ρ2.real\n\nρ1, ρ2\n\n\n```\n\n\n\n\n (1.5371322893124, -0.9024999999999999)\n\n\n\n#### **Root finding using numpy**\n\nHere we’ll use numpy to compute the roots of the characteristic polynomial\n\n\n```python\nr1, r2 = np.roots([1, -ρ1, -ρ2])\n\np1 = cmath.polar(r1)\np2 = cmath.polar(r2)\n\nprint(f\"r, ϕ = {r}, {ϕ}\")\nprint(f\"p1, p2 = {p1}, {p2}\")\n# print(f\"g1, g2 = {g1}, {g2}\")\n\nprint(f\"a, b = {a}, {b}\")\nprint(f\"ρ1, ρ2 = {ρ1}, {ρ2}\")\n```\n\n r, ϕ = 0.95, 0.6283185307179586\n p1, p2 = (0.95, 0.6283185307179586), (0.95, -0.6283185307179586)\n a, b = (0.6346322893124001+0j), (0.9024999999999999-0j)\n ρ1, ρ2 = 1.5371322893124, -0.9024999999999999\n\n\n\n```python\n##=== This method uses numpy to calculate roots ===#\n\n\ndef y_nonstochastic(y_0=100, y_1=80, α=.9, β=.8, γ=10, n=80):\n\n \"\"\" Rather than computing the roots of the characteristic polynomial by hand as we did earlier, this function\n enlists numpy to do the work for us \"\"\"\n\n # Useful constants\n ρ1 = α + β\n ρ2 = -β\n\n categorize_solution(ρ1, ρ2)\n\n # Find roots of polynomial\n roots = np.roots([1, -ρ1, -ρ2])\n print(f'Roots are {roots}')\n\n # Check if real or complex\n if all(isinstance(root, complex) for root in roots):\n print('Roots are complex')\n else:\n print('Roots are real')\n\n # Check if roots are less than one\n if all(abs(root) < 1 for root in roots):\n print('Roots are less than one')\n else:\n print('Roots are not less than one')\n\n # Define transition equation\n def transition(x, t): return ρ1 * x[t - 1] + ρ2 * x[t - 2] + γ\n\n # Set initial conditions\n y_t = [y_0, y_1]\n\n # Generate y_t series\n for t in range(2, n):\n y_t.append(transition(y_t, t))\n\n return y_t\n\nplot_y(y_nonstochastic())\n```\n\n##### **Reverse engineered complex roots: example**\n\nThe next cell studies the implications of reverse engineered complex roots\n\nWe’ll generate an **undamped** cycle of period **10**\n\n\n```python\nr = 1 # generates undamped, nonexplosive cycles\n\nperiod = 10 # length of cycle in units of time\nϕ = 2 * math.pi/period\n\n## Apply the reverse engineering function f\n\nρ1, ρ2, a, b = f(r, ϕ)\n\na = a.real # drop the imaginary part so that it is a valid input into y_nonstochastic\nb = b.real\n\nprint(f\"a, b = {a}, {b}\")\n\nytemp = y_nonstochastic(α=a, β=b, y_0=20, y_1=30)\nplot_y(ytemp)\n```\n\n##### **Digression**: *using sympy to find roots*\n\nWe can also use sympy to compute analytic formulas for the roots\n\n\n```python\nimport sympy\nfrom sympy import Symbol, init_printing\ninit_printing()\n\nr1 = Symbol(\"ρ_1\")\nr2 = Symbol(\"ρ_2\")\nz = Symbol(\"z\")\n\nsympy.solve(z**2 - r1*z - r2, z)\n```\n\n\n```python\na = Symbol(\"α\")\nb = Symbol(\"β\")\nr1 = a + b\nr2 = -b\n\nsympy.solve(z**2 - r1*z - r2, z)\n```\n\n##### **Stochastic shocks**\n\nNow we’ll construct some code to simulate the stochastic version of the model that emerges when we add a random shock process to aggregate demand\n\n\n```python\ndef y_stochastic(y_0=0, y_1=0, α=0.8, β=0.2, γ=10, n=100, σ=5):\n\n \"\"\"This function takes parameters of a stochastic version of the model and proceeds to analyze\n the roots of the characteristic polynomial and also generate a simulation\"\"\"\n\n # Useful constants\n ρ1 = α + β\n ρ2 = -β\n\n # Categorize solution\n categorize_solution(ρ1, ρ2)\n\n # Find roots of polynomial\n roots = np.roots([1, -ρ1, -ρ2])\n print(roots)\n\n # Check if real or complex\n if all(isinstance(root, complex) for root in roots):\n print('Roots are complex')\n else:\n print('Roots are real')\n\n # Check if roots are less than one\n if all(abs(root) < 1 for root in roots):\n print('Roots are less than one')\n else:\n print('Roots are not less than one')\n\n # Generate shocks\n ϵ = np.random.normal(0, 1, n)\n\n # Define transition equation\n def transition(x, t): return ρ1 * \\\n x[t - 1] + ρ2 * x[t - 2] + γ + σ * ϵ[t]\n\n # Set initial conditions\n y_t = [y_0, y_1]\n\n # Generate y_t series\n for t in range(2, n):\n y_t.append(transition(y_t, t))\n\n return y_t\n\nplot_y(y_stochastic())\n```\n\nLet’s do a simulation in which there are shocks and the characteristic polynomial has complex roots\n\n\n```python\nr = .97\n\nperiod = 10 # length of cycle in units of time\nϕ = 2 * math.pi/period\n\n### apply the reverse engineering function f\n\nρ1, ρ2, a, b = f(r, ϕ)\n\na = a.real # drop the imaginary part so that it is a valid input into y_nonstochastic\nb = b.real\n\nprint(f\"a, b = {a}, {b}\")\nplot_y(y_stochastic(y_0=40, y_1 = 42, α=a, β=b, σ=2, n=100))\n```\n\n##### **Government spending**\n\nThis function computes a response to either a permanent or one-off increase in government expenditures\n\n\n```python\ndef y_stochastic_g(y_0=20,\n y_1=20,\n α=0.8,\n β=0.2,\n γ=10,\n n=100,\n σ=2,\n g=0,\n g_t=0,\n duration='permanent'):\n\n \"\"\"This program computes a response to a permanent increase in government expenditures that occurs\n at time 20\"\"\"\n\n # Useful constants\n ρ1 = α + β\n ρ2 = -β\n\n # Categorize solution\n categorize_solution(ρ1, ρ2)\n\n # Find roots of polynomial\n roots = np.roots([1, -ρ1, -ρ2])\n print(roots)\n\n # Check if real or complex\n if all(isinstance(root, complex) for root in roots):\n print('Roots are complex')\n else:\n print('Roots are real')\n\n # Check if roots are less than one\n if all(abs(root) < 1 for root in roots):\n print('Roots are less than one')\n else:\n print('Roots are not less than one')\n\n # Generate shocks\n ϵ = np.random.normal(0, 1, n)\n\n def transition(x, t, g):\n\n # Non-stochastic - separated to avoid generating random series when not needed\n if σ == 0:\n return ρ1 * x[t - 1] + ρ2 * x[t - 2] + γ + g\n\n # Stochastic\n else:\n ϵ = np.random.normal(0, 1, n)\n return ρ1 * x[t - 1] + ρ2 * x[t - 2] + γ + g + σ * ϵ[t]\n\n # Create list and set initial conditions\n y_t = [y_0, y_1]\n\n # Generate y_t series\n for t in range(2, n):\n\n # No government spending\n if g == 0:\n y_t.append(transition(y_t, t))\n\n # Government spending (no shock)\n elif g != 0 and duration == None:\n y_t.append(transition(y_t, t))\n\n # Permanent government spending shock\n elif duration == 'permanent':\n if t < g_t:\n y_t.append(transition(y_t, t, g=0))\n else:\n y_t.append(transition(y_t, t, g=g))\n\n # One-off government spending shock\n elif duration == 'one-off':\n if t == g_t:\n y_t.append(transition(y_t, t, g=g))\n else:\n y_t.append(transition(y_t, t, g=0))\n return y_t\n\n```\n\n\n\nA permanent government spending shock can be simulated as follows\n\n\n```python\n\n\nplot_y(y_stochastic_g(g=10, g_t=20, duration='permanent'))\n```\n\nWe can also see the response to a one time jump in government expenditures\n\n\n```python\nplot_y(y_stochastic_g(g=500, g_t=50, duration='one-off'))\n```\n\n#### **Wrapping everything into a class**\n\nUp to now we have written functions to do the work\n\nNow we’ll roll up our sleeves and write a Python class called `Samuelson` for the Samuleson model\n\n\n```python\nclass Samuelson():\n\n r\"\"\"This class represents the Samuelson model, otherwise known as the\n multiple-accelerator model. The model combines the Keynesian multiplier\n with the accelerator theory of investment.\n\n The path of output is governed by a linear second-order difference equation\n\n .. math::\n\n Y_t = + \\alpha (1 + \\beta) Y_{t-1} - \\alpha \\beta Y_{t-2}\n\n Parameters\n ----------\n y_0 : scalar\n Initial condition for Y_0\n y_1 : scalar\n Initial condition for Y_1\n α : scalar\n Marginal propensity to consume\n β : scalar\n Accelerator coefficient\n n : int\n Number of iterations\n σ : scalar\n Volatility parameter. Must be greater than or equal to 0. Set\n equal to 0 for non-stochastic model.\n g : scalar\n Government spending shock\n g_t : int\n Time at which government spending shock occurs. Must be specified\n when duration != None.\n duration : {None, 'permanent', 'one-off'}\n Specifies type of government spending shock. If none, government\n spending equal to g for all t.\n\n \"\"\"\n\n def __init__(self,\n y_0=100,\n y_1=50,\n α=1.3,\n β=0.2,\n γ=10,\n n=100,\n σ=0,\n g=0,\n g_t=0,\n duration=None):\n\n self.y_0, self.y_1, self.α, self.β = y_0, y_1, α, β\n self.n, self.g, self.g_t, self.duration = n, g, g_t, duration\n self.γ, self.σ = γ, σ\n self.ρ1 = α + β\n self.ρ2 = -β\n self.roots = np.roots([1, -self.ρ1, -self.ρ2])\n\n def root_type(self):\n if all(isinstance(root, complex) for root in self.roots):\n return 'Complex conjugate'\n elif len(self.roots) > 1:\n return 'Double real'\n else:\n return 'Single real'\n\n def root_less_than_one(self):\n if all(abs(root) < 1 for root in self.roots):\n return True\n\n def solution_type(self):\n ρ1, ρ2 = self.ρ1, self.ρ2\n discriminant = ρ1 ** 2 + 4 * ρ2\n if ρ2 >= 1 + ρ1 or ρ2 <= -1:\n return 'Explosive oscillations'\n elif ρ1 + ρ2 >= 1:\n return 'Explosive growth'\n elif discriminant < 0:\n return 'Damped oscillations'\n else:\n return 'Steady state'\n\n def _transition(self, x, t, g):\n\n # Non-stochastic - separated to avoid generating random series when not needed\n if self.σ == 0:\n return self.ρ1 * x[t - 1] + self.ρ2 * x[t - 2] + self.γ + g\n\n # Stochastic\n else:\n ϵ = np.random.normal(0, 1, self.n)\n return self.ρ1 * x[t - 1] + self.ρ2 * x[t - 2] + self.γ + g + self.σ * ϵ[t]\n\n def generate_series(self):\n\n # Create list and set initial conditions\n y_t = [self.y_0, self.y_1]\n\n # Generate y_t series\n for t in range(2, self.n):\n\n # No government spending\n if self.g == 0:\n y_t.append(self._transition(y_t, t))\n\n # Government spending (no shock)\n elif self.g != 0 and self.duration == None:\n y_t.append(self._transition(y_t, t))\n\n # Permanent government spending shock\n elif self.duration == 'permanent':\n if t < self.g_t:\n y_t.append(self._transition(y_t, t, g=0))\n else:\n y_t.append(self._transition(y_t, t, g=self.g))\n\n # One-off government spending shock\n elif self.duration == 'one-off':\n if t == self.g_t:\n y_t.append(self._transition(y_t, t, g=self.g))\n else:\n y_t.append(self._transition(y_t, t, g=0))\n return y_t\n\n def summary(self):\n print('Summary\\n' + '-' * 50)\n print(f'Root type: {self.root_type()}')\n print(f'Solution type: {self.solution_type()}')\n print(f'Roots: {str(self.roots)}')\n\n if self.root_less_than_one() == True:\n print('Absolute value of roots is less than one')\n else:\n print('Absolute value of roots is not less than one')\n\n if self.σ > 0:\n print('Stochastic series with σ = ' + str(self.σ))\n else:\n print('Non-stochastic series')\n\n if self.g != 0:\n print('Government spending equal to ' + str(self.g))\n\n if self.duration != None:\n print(self.duration.capitalize() +\n ' government spending shock at t = ' + str(self.g_t))\n\n def plot(self):\n fig, ax = plt.subplots(figsize=(12, 8))\n ax.plot(self.generate_series())\n ax.set(xlabel='Iteration', xlim=(0, self.n))\n ax.set_ylabel('$Y_t$', rotation=0)\n ax.grid()\n\n # Add parameter values to plot\n paramstr = f'$\\\\alpha={self.α:.2f}$ \\n $\\\\beta={self.β:.2f}$ \\n $\\\\gamma={self.γ:.2f}$ \\n \\\n$\\\\sigma={self.σ:.2f}$ \\n $\\\\rho_1={self.ρ1:.2f}$ \\n $\\\\rho_2={self.ρ2:.2f}$'\n props = dict(fc='white', pad=10, alpha=0.5)\n ax.text(0.87, 0.05, paramstr, transform=ax.transAxes,\n fontsize=12, bbox=props, va='bottom')\n\n return fig\n\n def param_plot(self):\n\n # Uses the param_plot() function defined earlier (it is then able\n # to be used standalone or as part of the model)\n\n fig = param_plot()\n ax = fig.gca()\n\n # Add λ values to legend\n for i, root in enumerate(self.roots):\n if isinstance(root, complex):\n operator = ['+', ''] # Need to fill operator for positive as string is split apart\n label = rf'$\\lambda_{i+1} = {sam.roots[i].real:.2f} {operator[i]} {sam.roots[i].imag:.2f}i$'\n else:\n label = rf'$\\lambda_{i+1} = {sam.roots[i].real:.2f}$'\n ax.scatter(0, 0, 0, label=label) # dummy to add to legend\n\n # Add ρ pair to plot\n ax.scatter(self.ρ1, self.ρ2, 100, 'red', '+', label=r'$(\\ \\rho_1, \\ \\rho_2 \\ )$', zorder=5)\n\n plt.legend(fontsize=12, loc=3)\n\n return fig\n\n```\n\n#### **Illustration of Samuelson class**\n\nNow we’ll put our Samuelson class to work on an example\n\n\n```python\nsam = Samuelson(α=0.8, β=0.5, σ=2, g=10, g_t=20, duration='permanent')\nsam.summary()\n```\n\n Summary\n --------------------------------------------------\n Root type: Complex conjugate\n Solution type: Damped oscillations\n Roots: [0.65+0.27838822j 0.65-0.27838822j]\n Absolute value of roots is less than one\n Stochastic series with σ = 2\n Government spending equal to 10\n Permanent government spending shock at t = 20\n\n\n\n```python\nsam.plot()\nplt.show()\n```\n\n#### Using the graph\n\nWe’ll use our graph to show where the roots lie and how their location is consistent with the behavior of the path just graphed\n\nThe red $+$ sign shows the location of the roots\n\n\n```python\nsam.param_plot()\nplt.show()\n```\n\n#### **Using the LinearStateSpace class**\n\nIt turns out that we can use the QuantEcon.py LinearStateSpace class to do much of the work that we have done from scratch above\n\nHere is how we map the Samuelson model into an instance of a `LinearStateSpace` class\n\n\n```python\nfrom quantecon import LinearStateSpace\n\n\"\"\" This script maps the Samuelson model in the the LinearStateSpace class\"\"\"\nα = 0.8\nβ = 0.9\nρ1 = α + β\nρ2 = -β\nγ = 10\nσ = 1\ng = 10\nn = 100\n\nA = [[1, 0, 0],\n [γ + g, ρ1, ρ2],\n [0, 1, 0]]\n\nG = [[γ + g, ρ1, ρ2], # this is Y_{t+1}\n [γ, α, 0], # this is C_{t+1}\n [0, β, -β]] # this is I_{t+1}\n\nμ_0 = [1, 100, 100]\nC = np.zeros((3,1))\nC[1] = σ # stochastic\n\nsam_t = LinearStateSpace(A, C, G, mu_0=μ_0)\n\nx, y = sam_t.simulate(ts_length=n)\n\nfig, axes = plt.subplots(3, 1, sharex=True, figsize=(15, 8))\ntitles = ['Output ($Y_t$)', 'Consumption ($C_t$)', 'Investment ($I_t$)']\ncolors = ['darkblue', 'red', 'purple']\nfor ax, series, title, color in zip(axes, y, titles, colors):\n ax.plot(series, color=color)\n ax.set(title=title, xlim=(0, n))\n ax.grid()\n\naxes[-1].set_xlabel('Iteration')\n\nplt.show()\n\n```\n\n#### **Other methods in the LinearStateSpace class**\n\nLet’s plot **impulse response functions** for the instance of the Samuelson model using a method in the `LinearStateSpace` class\n\n\n```python\nimres = sam_t.impulse_response()\nimres = np.asarray(imres)\ny1 = imres[:, :, 0]\ny2 = imres[:, :, 1]\ny1.shape\n```\n\nNow let’s compute the zeros of the characteristic polynomial by simply calculating the eigenvalues of $A$\n\n\n```python\nA = np.asarray(A)\nw, v = np.linalg.eig(A)\nprint(w)\n```\n\n [0.85+0.42130749j 0.85-0.42130749j 1. +0.j ]\n\n\n##### **Inheriting methods from** `LinearStateSpace`\n\nWe could also create a subclass of `LinearStateSpace` (inheriting all its methods and attributes) to add more functions to use\n\n\n```python\nclass SamuelsonLSS(LinearStateSpace):\n\n \"\"\"\n this subclass creates a Samuelson multiplier-accelerator model\n as a linear state space system\n \"\"\"\n def __init__(self,\n y_0=100,\n y_1=100,\n α=0.8,\n β=0.9,\n γ=10,\n σ=1,\n g=10):\n\n self.α, self.β = α, β\n self.y_0, self.y_1, self.g = y_0, y_1, g\n self.γ, self.σ = γ, σ\n\n # Define intial conditions\n self.μ_0 = [1, y_0, y_1]\n\n self.ρ1 = α + β\n self.ρ2 = -β\n\n # Define transition matrix\n self.A = [[1, 0, 0],\n [γ + g, self.ρ1, self.ρ2],\n [0, 1, 0]]\n\n # Define output matrix\n self.G = [[γ + g, self.ρ1, self.ρ2], # this is Y_{t+1}\n [γ, α, 0], # this is C_{t+1}\n [0, β, -β]] # this is I_{t+1}\n\n self.C = np.zeros((3, 1))\n self.C[1] = σ # stochastic\n\n # Initialize LSS with parameters from Samuleson model\n LinearStateSpace.__init__(self, self.A, self.C, self.G, mu_0=self.μ_0)\n\n def plot_simulation(self, ts_length=100, stationary=True):\n\n # Temporarily store original parameters\n temp_μ = self.μ_0\n temp_Σ = self.Sigma_0\n\n # Set distribution parameters equal to their stationary values for simulation\n if stationary == True:\n try:\n self.μ_x, self.μ_y, self.σ_x, self.σ_y = self.stationary_distributions()\n self.μ_0 = self.μ_y\n self.Σ_0 = self.σ_y\n # Exception where no convergence achieved when calculating stationary distributions\n except ValueError:\n print('Stationary distribution does not exist')\n\n x, y = self.simulate(ts_length)\n\n fig, axes = plt.subplots(3, 1, sharex=True, figsize=(15, 8))\n titles = ['Output ($Y_t$)', 'Consumption ($C_t$)', 'Investment ($I_t$)']\n colors = ['darkblue', 'red', 'purple']\n for ax, series, title, color in zip(axes, y, titles, colors):\n ax.plot(series, color=color)\n ax.set(title=title, xlim=(0, n))\n ax.grid()\n\n axes[-1].set_xlabel('Iteration')\n\n # Reset distribution parameters to their initial values\n self.μ_0 = temp_μ\n self.Sigma_0 = temp_Σ\n\n return fig\n\n def plot_irf(self, j=5):\n\n x, y = self.impulse_response(j)\n\n # Reshape into 3 x j matrix for plotting purposes\n yimf = np.array(y).flatten().reshape(j+1, 3).T\n\n fig, axes = plt.subplots(3, 1, sharex=True, figsize=(15, 8))\n labels = ['$Y_t$', '$C_t$', '$I_t$']\n colors = ['darkblue', 'red', 'purple']\n for ax, series, label, color in zip(axes, yimf, labels, colors):\n ax.plot(series, color=color)\n ax.set(xlim=(0, j))\n ax.set_ylabel(label, rotation=0, fontsize=14, labelpad=10)\n ax.grid()\n\n axes[0].set_title('Impulse Response Functions')\n axes[-1].set_xlabel('Iteration')\n\n return fig\n\n def multipliers(self, j=5):\n x, y = self.impulse_response(j)\n return np.sum(np.array(y).flatten().reshape(j+1, 3), axis=0)\n```\n\n##### **Illustrations**\n\nLet’s show how we can use the `SamuelsonLSS`\n\n\n```python\nsamlss = SamuelsonLSS()\nsamlss.plot_simulation(100, stationary=False)\nplt.show()\n```\n\n\n```python\nsamlss.plot_simulation(100, stationary=True)\nplt.show()\n```\n\n\n```python\nsamlss.plot_irf(100)\nplt.show()\n```\n\n\n```python\nsamlss.multipliers()\n```\n\n\n\n\n array([7.414389, 6.835896, 0.578493])\n\n\n\n##### **Pure multiplier model**\n\nLet’s shut down the accelerator by setting $b=0$ to get a pure multiplier model\n\n* the absence of cycles gives an idea about why Samuelson included the accelerator\n\n\n\n```python\npure_multiplier = SamuelsonLSS(α=0.95, β=0)\npure_multiplier.plot_simulation()\n```\n\n\n```python\npure_multiplier = SamuelsonLSS(α=0.8, β=0)\npure_multiplier.plot_simulation()\n```\n\n\n```python\npure_multiplier.plot_irf(100)\n```\n", "meta": {"hexsha": "e51ca9a3b902eaeffa674d8936944d4a4c4f0327", "size": 1021062, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Part 3.2.ipynb", "max_stars_repo_name": "planetnoob/QuantEcon-Python", "max_stars_repo_head_hexsha": "affeb711619607ee5d1be553f6f933e9b6cf0360", "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": "Part 3.2.ipynb", "max_issues_repo_name": "planetnoob/QuantEcon-Python", "max_issues_repo_head_hexsha": "affeb711619607ee5d1be553f6f933e9b6cf0360", "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": "Part 3.2.ipynb", "max_forks_repo_name": "planetnoob/QuantEcon-Python", "max_forks_repo_head_hexsha": "affeb711619607ee5d1be553f6f933e9b6cf0360", "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": 519.3601220753, "max_line_length": 89284, "alphanum_fraction": 0.9380311871, "converted": true, "num_tokens": 11446, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067179697694, "lm_q2_score": 0.9184802440252811, "lm_q1q2_score": 0.8656738003163406}} {"text": "```python\n%pylab inline\n%config InlineBackend.figure_format = 'retina'\nfrom ipywidgets import interact\n```\n\n Populating the interactive namespace from numpy and matplotlib\n\n\n# Question 1\nConsider the approximation to the first derivative\n$$ f'(a) \\approx \\frac{f(a+h) - f(a )}{h}.$$\nThe discretization error for this formula is $O(h)$. Suppose that the absolute error in evaluating the function $f$ is bounded by machine epsilon, $\\epsilon$, with\n$$ \\vert \\hat{f}(x) - f(x) \\vert \\leq \\epsilon, $$\nwhere $\\hat{f}(x)$ is the floating point approximation of the exact function evaluation $f(x)$. For simplicity, let us ignore the errors generated in basic arithmetic operations. Suppose further that there is a constant $M>0$ such that $\\vert f’’(x)\\vert \\leq M$ for all $x$.\n\n**Ignore the floating point error in approximating $h$ with a floating point value in the denominator.**\n\n## A. \nShow that the total computational error (truncation and rounding combined) is bounded by\n$$ \\frac{Mh}{2} + \\frac{2\\epsilon}{h}.$$ \n\n---------------------------------------\n## Solution\nThe first part is the discretization error we derived in Homework 2. The second part,\n$$ \\mathcal{E}_{\\rm roundoff} = \\frac{2\\epsilon}{h},$$\nis due to roundoff error. The second term follows from the bound on error in evaluating the function. Using the triangle inequality, we have\n\\begin{align}\n\\frac{\\vert f({\\rm fl}(a+h)) - f({\\rm fl}(a) ) - (f(a+h) - f(a ))\\vert}{h} \n & \\leq \\frac{\\vert f({\\rm fl}(a+h)) - f(a+h)\\vert + \\vert f({\\rm fl}(a) ) - f(a )\\vert )\\vert}{h} \\\\\n & \\leq \\frac{\\epsilon + \\epsilon}{h} = \\frac{2\\epsilon}{h}.\n\\end{align}\n\n## B. \nTreat the above bound as an approximation of the absolute error. At what value of $h$ is the error estimate in part A minimized?\n\n---------------------------------------\n## Solution\nTake the derivative of the total error with respect to $h$, set it to zero, and solve for $h_{\\rm opt}$,\n$$ \\frac{M}{2} - \\frac{2\\epsilon}{h_{\\rm opt}^2} = 0,$$\nwhich yields\n$$h_{\\rm opt} = \\sqrt{\\frac{4\\epsilon}{M}} .$$\n\n## C. \nCopy and paste Example 2 in the Week 2 Python notebook into a new notebook. Plot the error estimate derived in part A (again treating the bound as an approximation) along with the empirical computational error (the numerically computed error) and the estimate of the discretization error (both of these are already plotted in the example). Is the error estimate from part A a better error estimate? Why? Plot the minimum predicted in part B. Does it agree with the minimum of the empirical error? **For the graph, use $\\epsilon = 10^{-16}$ and $M = |f''(a)|$.**\n\n\n```python\nx0 = 1.2 ## point that we compute the derivative at (ie d/dx sin(x) at x = x0)\nf0 = sin(x0) ## f(x0)\nfp = cos(x0) ## f'(x0) the `p` means 'prime'\nfpp = -sin(x0) ## f''(x0)\n\ni = linspace(-20, 0, 40) ## `linspace` gives a range of values between two end points\n## in this case 40 points, between -20 and 0\nh = 10.0**i ## this is our approx parameter, it is an array of values \n## between 10^(-20) and 10^(0)\nfp_approx = (sin(x0 + h) - f0)/h ## the derivative approximation\nerr = absolute(fp - fp_approx) ## the full absolute error\nd_err = h/2*absolute(fpp) ## the formula for the discretization error, derived above\n\n### New code here\nmachine_epsilon = np.finfo(float).eps # 2.2e-16\nepsilon = 1e-16\nM = absolute(fpp)\nh_opt = sqrt(4.*epsilon/M)\nerr_opt = M*h_opt/2. + 2.*epsilon/h_opt\nerr_tot = M*h/2. + 2.*epsilon/h\n## we can get a slightly improved error estimate if we account for the fact \n## that h = epsilon_machine ~ 2e-16 is the lowest possible value that can\n## be achieved\nerr_max_from_underflow = 2.*epsilon/machine_epsilon\nerr_tot_clipped = clip(err_tot, -inf, err_max_from_underflow)\n####################\n \nfigure(1, [10, 5]) ## creates a blank figure 7 inches (wide) by 5 inches (height)\nloglog(h, err, '-*', label='empirical error') ## makes a plot with a double log scale\nloglog(h, d_err, 'r-', label='estimate:\\ndiscretization error')\n\n### New code here\nloglog(h_opt, err_opt, 'og', ms=15, label='optimal h')\nloglog(h, err_tot_clipped, 'g', label='estimate:\\ntotal error')\n####################\n\n### some new code below too, but just plotting stuff\nxlabel('h', fontsize=20) ## puts a label on the x axis\nylabel('absolute error', fontsize=20) ## puts a label on the y axis\nxlim(1e-25, 1e0)\nylim(1e-13, 2) ## places limits on the yaxis for our plot\nlegend(loc='lower left', fontsize=18); ## creates a figure legend (uses the `label=...` \n ## arguments in the plot command)\n```\n\n# Question 2\nSuppose we invent a new representation for finite precision real numbers based on rational numbers instead of floating point numbers. Rational numbers are dense on the reals, and we can approximate any real number to any desired precision with a rational number. For this to work, our data structure must use only integers and arithmetic operations ($+,-,\\cdot, /$) on integers. \n\nLet $x = I_1 / I_2$ where $I_1$ and $I_2$ are 16bit integers. Assume for simplicity that $0 \\leq I_1 \\leq I_{\\rm max}$ and $0 < I_2 \\leq I_{\\rm max}$. Hence, each real number represented in finite precision with our new system uses 32bits to store in memory.\n\n## A\nDevise formulas to perform addition, multiplication, and division that use only arithmetic operations on integers. Arithmetic operations should take as input two numbers in our format and return a single new number also in our format. For example, if $x_1 = I_{11}/I_{21}$ and $x_2 = I_{12}/I_{22}$, then $x_1 + x_2 = x_3$, where $x_3$ is expressed as the ratio of two integers. For each operation, you need to write $x_3$ as the ratio of two integers each of which are functions of the integers $I_{11},I_{21}, I_{12}, I_{22}$.\n\n---------------------------------------\n## Solution\nAssume the output of a given operation is $y = y_1/y_2$ for integers $y_1$ and $y_2$.\n 1. Multiplication $x_1x_2$:\n $$ y_{1} = I_{11}I_{12},\\quad y_2 = I_{21}I_{22} $$\n 2. Division $x_1/x_2$:\n $$y_{1} = I_{11}I_{22},\\quad y_2 = I_{21}I_{12}$$\n 3. Addition and subtraction $x_1 \\pm x_2$:\n $$ y_{1} = I_{11}I_{22} \\pm I_{12}I_{21}, \\quad y_{2} = I_{21}I_{22}$$\n\n## B\nWhat is $I_{max}$ for a non negative 16bit integer?\n\n---------------------------------------\n## Solution\n$$ 2^{16} - 1 = 65,535 $$\n\n## C\nWhat is the smallest possible nonzero value that can be represented by our numbers (remember that we are assuming they are non negative)?\n\n---------------------------------------\n## Solution\n$$\\approx 2^{-16} \\approx 10^{-5}$$\n\n## D \nWhat is the largest possible value that can be represented by our numbers?\n\n---------------------------------------\n## Solution\n$$\\approx 2^{16} \\approx 10^5$$\n\n## E\nWhat is the smallest (in absolute value) possible absolute difference between two numbers $x_1$ and $x_2$ such that $x_1 \\neq x_2$? \n\n---------------------------------------\n## Solution\nNot shown\n\n## F\nWhat is the smallest (in absolute value) possible relative difference between two numbers $x_1$ and $x_2$ such that $x_1 \\neq x_2$? Use the following for relative difference $$\\frac{|x_1 - x_2| }{ \\max(x_1, x_2)}$$\n\n---------------------------------------\n## Solution\nNot shown\n\n---------------------------------------\n## Solution\n\n## G \nHow do the above answers compare to 32bit floating point numbers? Is this a good way to represent real numbers on a computer? Why or why not?\n\n---------------------------------------\n## Solution\nOur numbers based on rational numbers are not nearly as good as 32 bit floating point numbers.\n 1. The range of values is much smaller. The larges values are $\\approx 10^5$ compared to $\\approx 10^{38}$ for 32bit float. The smallest values follow a similar trend.\n 2. The accuracy, or machine epsilon, is much larger\n 3. Several students pointed out that the floating point operations would likely be much slower\n", "meta": {"hexsha": "2f358da9b058036dbad15e56688ec409a335ae7f", "size": 119214, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Homework 3 Solutions.ipynb", "max_stars_repo_name": "newby-jay/MATH381-Fall2021-JupyterNotebooks", "max_stars_repo_head_hexsha": "9181fb6e154081de26fb267e0794a67f60ae11a0", "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": "Homework 3 Solutions.ipynb", "max_issues_repo_name": "newby-jay/MATH381-Fall2021-JupyterNotebooks", "max_issues_repo_head_hexsha": "9181fb6e154081de26fb267e0794a67f60ae11a0", "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": "Homework 3 Solutions.ipynb", "max_forks_repo_name": "newby-jay/MATH381-Fall2021-JupyterNotebooks", "max_forks_repo_head_hexsha": "9181fb6e154081de26fb267e0794a67f60ae11a0", "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": 365.6871165644, "max_line_length": 107504, "alphanum_fraction": 0.922802691, "converted": true, "num_tokens": 2249, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.918480237330998, "lm_q2_score": 0.9425067211996142, "lm_q1q2_score": 0.8656737969734825}} {"text": "# Estimation of pi using Monte Carlo method\n\n**Statement of problem**\n\nLet two random variables $X$ and $Y$ be in $[-1,1]$ and distributed uniformly. Probability that point given with coordinates $(X, Y)$ lies in unit circle (i.e. $X^2 + Y^2 < 1$) is:\n\n\\begin{equation}\np = \\frac{S_C}{S_S} = \\frac{r^2 \\pi}{a^2} = \\frac{\\pi}{4}\n\\end{equation}\n\n**Method**\n\nGenerate $N$ pairs of $(X, Y)$ and calculate how many of them lay in unit circle, $N_<$. Then estimate probability that point is in circle by:\n\n\\begin{equation}\np_< = \\frac{N_<}{N}\n\\end{equation}\n\nBy law of large numbers, this number will converge to $p$ as $N \\to \\infty$. Hence, our estimation of $\\pi$ is:\n\n\\begin{equation}\n\\hat \\pi = 4p_< \n\\end{equation}\n\n**Tasks**\n\n1. Generate $N$ pairs of $(X, Y)$, calculate for each $N$ how many of them are in unit circle $N<$. Choose $N$ so that you are able to see how $\\hat \\pi$ approaches $\\pi$ by increasing $N$. (for example, use $N$ log-scaled)\n\n2. Save data as array with informations: how many points have been used and estimation of pi.\n\n3. Plot the data.\n\n\n```python\n\n```\n", "meta": {"hexsha": "9d7fc7787e1ffb357b78d7651b21a87d4b086352", "size": 2181, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Monte Carlo/piTask.ipynb", "max_stars_repo_name": "PhyProg/RCT", "max_stars_repo_head_hexsha": "07f02dca1bd5258b8a0a1d1d83a923ea33176161", "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": "Monte Carlo/piTask.ipynb", "max_issues_repo_name": "PhyProg/RCT", "max_issues_repo_head_hexsha": "07f02dca1bd5258b8a0a1d1d83a923ea33176161", "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": "Monte Carlo/piTask.ipynb", "max_forks_repo_name": "PhyProg/RCT", "max_forks_repo_head_hexsha": "07f02dca1bd5258b8a0a1d1d83a923ea33176161", "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": 25.6588235294, "max_line_length": 235, "alphanum_fraction": 0.5318661165, "converted": true, "num_tokens": 338, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9808759660443167, "lm_q2_score": 0.8824278649085117, "lm_q1q2_score": 0.8655522844565602}} {"text": "## Spherically symmetric waves\n\nSpherically symmetric three-dimensional\nwaves propagate in the radial direction $r$ only so that\n$u = u(r,t)$. The fully three-dimensional wave equation\n\n$$\n\\frac{\\partial^2u}{\\partial t^2}=\\nabla\\cdot (c^2\\nabla u) + f\n$$\n\nthen reduces to the spherically symmetric wave equation\n\n\n
\n\n$$\n\\begin{equation}\n\\frac{\\partial^2u}{\\partial t^2}=\\frac{1}{r^2}\\frac{\\partial}{\\partial r}\n\\left(c^2(r)r^2\\frac{\\partial u}{\\partial t}\\right)\n+ f(r),\\quad r\\in (0,R),\\ t>0\n\\thinspace . \n\\label{_auto1} \\tag{1}\n\\end{equation}\n$$\n\nAssume that the wave velocity $c$ is constant. One can easily show\nthat the function $v(r,t) = ru(r,t)$ fulfills a standard wave equation\nin Cartesian coordinates. To this end, insert $u=v/r$ in\n\n$$\n\\frac{1}{r^2}\\frac{\\partial}{\\partial r}\n\\left(c^2(r)r^2\\frac{\\partial u}{\\partial t}\\right)\n$$\n\nto obtain\n\n$$\nr\\left(\\frac{d c^2}{dr}\\frac{\\partial v}{\\partial r} +\nc^2\\frac{\\partial^2 v}{\\partial r^2}\\right) - \\frac{d c^2}{dr}v\n\\thinspace .\n$$\n\nThe two terms in the parenthesis can be combined to\n\n$$\nr\\frac{\\partial}{\\partial r}\\left( c^2\\frac{\\partial v}{\\partial r}\\right),\n$$\n\nwhich is recognized as the variable-coefficient Laplace operator in\none Cartesian coordinate. The spherically symmetric wave equation in\nterms of $v(r,t)$ now becomes\n\n\n
\n\n$$\n\\begin{equation}\n\\frac{\\partial^2u}{\\partial t^2}=\n\\frac{\\partial}{\\partial r}\n\\left(c^2(r)\\frac{\\partial v}{\\partial t}\n-\\frac{1}{r}\\frac{d c^2}{dr}v\\right) + rf(r),\\quad r\\in (0,R),\\ t>0\n\\thinspace . \n\\label{_auto2} \\tag{2}\n\\end{equation}\n$$\n\nIn the case of constant wave velocity $c$, this equation reduces to\nthe wave equation in a single Cartesian coordinate:\n\n\n
\n\n$$\n\\begin{equation}\n\\frac{\\partial^2u}{\\partial t^2}=\n\\frac{\\partial}{\\partial r}\n\\left(c^2(r)\\frac{\\partial v}{\\partial t}\\right)\n+ rf(r),\\quad r\\in (0,R),\\ t>0\n\\thinspace . \n\\label{wave:app:rsymm:Cart} \\tag{3}\n\\end{equation}\n$$\n\nThat is, any program for solving the one-dimensional wave equation\nin a Cartesian coordinate system can be used to\nsolve ([3](#wave:app:rsymm:Cart)), provided the source term is\nmultiplied by the coordinate. Moreover, if $r=0$ is included in the\ndomain, spherical symmetry demands that $\\partial u/\\partial r=0$ at\n$r=0$, which means that\n\n$$\n\\frac{\\partial u}{\\partial r} = \\frac{1}{r^2}\\left(\nr\\frac{\\partial v}{\\partial r} - v\\right) = 0,\\quad r=0,\n$$\n\nimplying $v(0,t)=0$ as a necessary condition. For practical applications,\nwe exclude $r=0$ from the domain and assume that some boundary\ncondition is assigned at $r=\\epsilon$, for some $\\epsilon >0$.\n", "meta": {"hexsha": "f446d923e8dd1d22e804564153886b98e0ccea48", "size": 5286, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "fdm-devito-notebooks/02_wave/spherical.ipynb", "max_stars_repo_name": "devitocodes/devito_book", "max_stars_repo_head_hexsha": "30405c3d440a1f89df69594fd0704f69650c1ded", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2020-07-17T13:19:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-27T05:21:09.000Z", "max_issues_repo_path": "fdm-devito-notebooks/02_wave/spherical.ipynb", "max_issues_repo_name": "devitocodes/devito_book", "max_issues_repo_head_hexsha": "30405c3d440a1f89df69594fd0704f69650c1ded", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 73, "max_issues_repo_issues_event_min_datetime": "2020-07-14T15:38:52.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-25T11:54:59.000Z", "max_forks_repo_path": "fdm-devito-notebooks/02_wave/spherical.ipynb", "max_forks_repo_name": "devitocodes/devito_book", "max_forks_repo_head_hexsha": "30405c3d440a1f89df69594fd0704f69650c1ded", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-03-27T05:21:14.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-27T05:21:14.000Z", "avg_line_length": 25.1714285714, "max_line_length": 92, "alphanum_fraction": 0.5181611805, "converted": true, "num_tokens": 904, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741281688026, "lm_q2_score": 0.9086178895092415, "lm_q1q2_score": 0.8655258939378432}} {"text": "# Symbolic Computation with SymPy\nSymbolic computation deals with the computation of mathematical objects symbolically. This means that the mathematical objects are represented exactly, not approximately, and mathematical expressions with unevaluated variables are left in symbolic form.\n\n\n```python\nfrom sympy import *\n```\n\nHere is a brief example, if you wanted to compute a square root in python you would do:\n\n\n```python\nimport math\nmath.sqrt(8)\n```\n\n\n\n\n 2.8284271247461903\n\n\n\nThis is an approximate solution because $\\sqrt{8}$ is an irrational number. But if you were to use the sympy version of of the square root function:\n\n\n```python\nsqrt(8)\n```\n\n\n\n\n$\\displaystyle 2 \\sqrt{2}$\n\n\n\nNotice that this is an exact solution, where the irrational part is left unevaluated by default.\n\nLet's move to a more interesting examples\n\n---\n## The power of symbolic computation\n\n\n```python\nx, y = symbols('x y')\ntype(x)\n```\n\n\n\n\n sympy.core.symbol.Symbol\n\n\n\n\n```python\ny\n```\n\n\n\n\n$\\displaystyle y$\n\n\n\nNow the code understands that `x` and `y` are symbols, not variables. These symbols can be used to build expressions:\n\n\n```python\nexpr = x + 2*y\nexpr\n```\n\n\n\n\n$\\displaystyle x + 2 y$\n\n\n\n\n```python\nexpr + 1\n```\n\n\n\n\n$\\displaystyle x + 2 y + 1$\n\n\n\n\n```python\n(x**2)*expr\n```\n\n\n\n\n$\\displaystyle x^{2} \\left(x + 2 y\\right)$\n\n\n\nNotice that in this last expression, the $x^2$ term was not distributed, but that can be requested.\n\n\n```python\nexpand((x**2)*expr)\n```\n\n\n\n\n$\\displaystyle x^{3} + 2 x^{2} y$\n\n\n\nThe reverse operation of `expand` is `factor`:\n\n\n```python\nfactor(x**2 + x)\n```\n\n\n\n\n$\\displaystyle x \\left(x + 1\\right)$\n\n\n\nHere are a few more interesting examples:\n\n\n```python\nsp.diff(x*sin(x), x)\n```\n\n\n\n\n$\\displaystyle x \\cos{\\left(x \\right)} + \\sin{\\left(x \\right)}$\n\n\n\n\n```python\nsp.integrate(x*cos(x) + sin(x), x)\n```\n\n\n\n\n$\\displaystyle x \\sin{\\left(x \\right)}$\n\n\n\n\n```python\nsp.integrate(sin(x**2), (x, -oo, oo))\n```\n\n\n\n\n$\\displaystyle \\frac{\\sqrt{2} \\sqrt{\\pi}}{2}$\n\n\n\n\n```python\nsp.limit(sin(x)/x, x, 0)\n```\n\n\n\n\n$\\displaystyle 1$\n\n\n\n\n```python\nsp.solve(x**2-4, x)\n```\n\n\n\n\n [-2, 2]\n\n\n\n\n```python\nt = symbols('t')\ny = Function('y')\node = dsolve(Eq(y(t).diff(t, t) - y(t), exp(t)), y(t))\node\n```\n\n\n\n\n$\\displaystyle y{\\left(t \\right)} = C_{2} e^{- t} + \\left(C_{1} + \\frac{t}{2}\\right) e^{t}$\n\n\n\n\n```python\nlatex(ode)\n```\n\n\n\n\n 'y{\\\\left(t \\\\right)} = C_{2} e^{- t} + \\\\left(C_{1} + \\\\frac{t}{2}\\\\right) e^{t}'\n\n\n\n---\n## Symbols VS Variables\n\nLet's understand a bit of details of SymPy's implementation.\n\n`symbols` takes a string of variable names separated by spaces or commas, and creates Symbols out of them. We can then assign these to variable names.\n\n\n```python\nx, y, z = symbols('x, y, z')\n```\n\nThe important thing to notice here is that the name of a Symbol and the name of the variable it is assigned to need not have anything to do with one another. In other words, **the variable and the symbol are not the same thing**.\n\n\n```python\na, b, c = symbols('x, y, z')\n```\n\n\n```python\na\n```\n\n\n\n\n$\\displaystyle x$\n\n\n\n\n```python\ncrazy = symbols('unralated')\ncrazy + 1\n```\n\n\n\n\n$\\displaystyle unralated + 1$\n\n\n\nTake the following example. Changing `x` to 2 had no effect on `expr`. This is because `x = 2` changes the Python variable `x` to 2, but has no effect on the SymPy Symbol x, which was what we used in creating `expr`.\n\n\n```python\nx = symbols('x')\nexpr = x + 1\nx = 2\ndisplay(expr)\n```\n\n\n$\\displaystyle x + 1$\n\n\n---\n## Basic Operations\nHere we discuss some of the most basic operations needed for expression manipulation in SymPy.\n\n\n```python\nx, y, z = symbols(\"x y z\")\n```\n\nOne of the most common things you might want to do with a mathematical expression is **substitution**. Substitution replaces all instances of something in an expression with something else. It is done using the `subs` method. For example:\n\n\n```python\nexpr = cos(x) + 1\nexpr.subs(x, y)\n```\n\n\n\n\n$\\displaystyle \\cos{\\left(y \\right)} + 1$\n\n\n\n\n```python\nexpr.subs(x, 0)\n```\n\n\n\n\n$\\displaystyle 2$\n\n\n\n\n```python\nexpr.subs(x, 2)\n```\n\n\n\n\n$\\displaystyle \\cos{\\left(2 \\right)} + 1$\n\n\n\nNotice that this last example the value of the expression was not evaluated. That is because $\\cos\\left(2\\right)$ is irrational (proof [here](https://math.stackexchange.com/questions/94478/sin-1-circ-is-irrational-but-how-do-i-prove-it-in-a-slick-way-and-tan1)). If we wanted to evaluate the expression, we would use the `evalf` method.\n\n\n```python\nexpr.subs(x, 2).evalf()\n```\n\n\n\n\n$\\displaystyle 0.583853163452858$\n\n\n\nNotice that the output has the traditional 15 decimal places. But the `evalf` method lets you choose how many digits you want.\n\n\n```python\nexpr.subs(x, 2).evalf(30)\n```\n\n\n\n\n$\\displaystyle 0.583853163452857613002431770499$\n\n\n\nTake a look at the first 100 digits of $\\pi$\n\n\n```python\npi.evalf(100)\n```\n\n\n\n\n$\\displaystyle 3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117068$\n\n\n\nTo perform multiple substitutions at once, pass a list of `(old, new)` pairs to `subs`.\n\n\n```python\nexpr = x**3 + 4*x*y - z\nexpr.subs([(x, 2), (y, 4), (z, 0)])\n```\n\n\n\n\n$\\displaystyle 40$\n\n\n\nYou can use python's list comprehensions to generate substitutions. In the example below we replace all instances of $x$ that have an even power with $y$.\n\n\n```python\nexpr = x**4 - 4*x**3 + 4*x**2 - 2*x + 3\nreplacements = [(x**i, y**i) for i in range(5) if i % 2 == 0]\nexpr.subs(replacements)\n```\n\n\n\n\n$\\displaystyle - 4 x^{3} - 2 x + y^{4} + 4 y^{2} + 3$\n\n\n\n---\n## Printing\nAs you may have noticed, the output of symbolyc expressions in the jupyter notebook environment automatically prints the rendered $\\LaTeX$ expression. But you can print outputs in other formats as well.\n\n\n```python\nexpr = Integral(sqrt(1/x), x)\nexpr\n```\n\n\n\n\n$\\displaystyle \\int \\sqrt{\\frac{1}{x}}\\, dx$\n\n\n\nYou can ask for the latex source code.\n\n\n```python\nlatex(expr)\n```\n\n\n\n\n '\\\\int \\\\sqrt{\\\\frac{1}{x}}\\\\, dx'\n\n\n\nUse the `pprint` to print the expression using Unicode characters.\n\n\n```python\npprint(expr)\n```\n\n ⌠ \n ⎮ ___ \n ⎮ ╱ 1 \n ⎮ ╱ ─ dx\n ⎮ ╲╱ x \n ⌡ \n\n\nOr non-unicode charcters\n\n\n```python\npprint(expr, use_unicode=False)\n```\n\n / \n | \n | ___ \n | / 1 \n | / - dx\n | \\/ x \n | \n / \n\n\n---\n## Simplification\nOne of the most useful features of a symbolic manipulation system is the ability to simplify mathematical expressions. SymPy has dozens of functions to perform various kinds of simplification. There is also one general function called `simplify()` that attempts to apply all of these functions in an intelligent way to arrive at the simplest form of an expression.\n\n\n```python\nx, y, z = symbols('x y z')\n```\n\nSymPy knows trigonometrical identities\n\n\n```python\nsimplify(sin(x)**2 + cos(x)**2)\n```\n\n\n\n\n$\\displaystyle 1$\n\n\n\nFacotoring out commom factors in polynomials\n\n\n```python\nsimplify((x**3 + x**2 - x - 1)/(x**2 + 2*x + 1))\n```\n\n\n\n\n$\\displaystyle x - 1$\n\n\n\nAnd even understands identities from big formulas of statitistical distributions, like the gamma function.\n\n\n```python\nsimplify(gamma(x)/gamma(x - 2))\n```\n\n\n\n\n$\\displaystyle \\left(x - 2\\right) \\left(x - 1\\right)$\n\n\n\nThere is a caveat: \"simplify\" does not have a well-defined target, so the `simplify()` method might not be what you need.\n\n\n```python\nexpand((x + 1)**2)\n```\n\n\n\n\n$\\displaystyle x^{2} + 2 x + 1$\n\n\n\n\n```python\nfactor(x**2*z + 4*x*y*z + 4*y**2*z)\n```\n\n\n\n\n$\\displaystyle z \\left(x + 2 y\\right)^{2}$\n\n\n\nAnother powerfull tool is the `rewrite` method. The example below rewrites the tangent functions in terms of the sine function\n\n\n```python\ntan(x).rewrite(sin)\n```\n\n\n\n\n$\\displaystyle \\frac{2 \\sin^{2}{\\left(x \\right)}}{\\sin{\\left(2 x \\right)}}$\n\n\n\nAnd the factorial faction using the gamma function.\n\n\n```python\nfactorial(x).rewrite(gamma)\n```\n\n\n\n\n$\\displaystyle \\Gamma\\left(x + 1\\right)$\n\n\n\nThere are other types of simplifications as well, for powers, more elaborate trigonometric identities, logarithims, etc. Check out the documentations [here](https://docs.sympy.org/latest/tutorial/simplification.html).\n\n---\n## Calculus\n\n\n```python\nx, y, z = symbols('x y z')\n```\n\n\n```python\nexpr = exp(x**2 * y**2)\nexpr\n```\n\n\n\n\n$\\displaystyle e^{x^{2} y^{2}}$\n\n\n\nThe first steps we usually take in calculus usually envolves limits.\n\n\n```python\nlimit(sin(x)/x, x, 0)\n```\n\n\n\n\n$\\displaystyle 1$\n\n\n\nand we learn that limits might be different from the right and from the left.\n\n\n```python\nlimit(1/x, x, 0, '+')\n```\n\n\n\n\n$\\displaystyle \\infty$\n\n\n\n\n```python\nlimit(1/x, x, 0, '-')\n```\n\n\n\n\n$\\displaystyle -\\infty$\n\n\n\nYou can take analytical derivatives with the `diff` method\n\n\n```python\ndiff(expr, x)\n```\n\n\n\n\n$\\displaystyle 2 x y^{2} e^{x^{2} y^{2}}$\n\n\n\nYou can also take multiple derivatives by chaining input arguments\n\n\n```python\ndiff(expr, x, x, y)\n```\n\n\n\n\n$\\displaystyle 4 y \\left(2 x^{4} y^{4} + 5 x^{2} y^{2} + 1\\right) e^{x^{2} y^{2}}$\n\n\n\nThe same idea can be used for integrals.\n\n\n```python\nintegrate(cos(x), x)\n```\n\n\n\n\n$\\displaystyle \\sin{\\left(x \\right)}$\n\n\n\n\n```python\nintegrate(cos(x), y)\n```\n\n\n\n\n$\\displaystyle y \\cos{\\left(x \\right)}$\n\n\n\nTo evaluate an integral, pass variable and their limits as tuples\n\n\n```python\nintegrate(cos(x), (x, 0, pi/2))\n```\n\n\n\n\n$\\displaystyle 1$\n\n\n\n\n```python\nintegrate(cos(x), (y, 0, pi/2))\n```\n\n\n\n\n$\\displaystyle \\frac{\\pi \\cos{\\left(x \\right)}}{2}$\n\n\n\nYou can even integrate to infinity\n\n\n```python\nintegrate(exp(-x**2 - y**2), (x, -oo, oo), (y, -oo, oo))\n```\n\n\n\n\n$\\displaystyle \\pi$\n\n\n\n\n```python\nintegrate(exp(-x**2 - y**2), (x, -oo, oo), (y, -oo, oo))\n```\n\n\n\n\n$\\displaystyle \\pi$\n\n\n\nSymPy can also do taylor expansions aroundo a given point. The example below make a 4th degree approximation to the sine function aroun $x=0$.\n\n\n```python\nsin(x).series(x, 0, 4)\n```\n\n\n\n\n$\\displaystyle x - \\frac{x^{3}}{6} + O\\left(x^{4}\\right)$\n\n\n\nAnd if you are an economist and do not care the $O(x^n)$ notation, you can remove it.\n\n\n```python\nsin(x).series(x, 0, 4).removeO()\n```\n\n\n\n\n$\\displaystyle - \\frac{x^{3}}{6} + x$\n\n\n\n---\n## Solvers\n\nWriting equations in SymPy assumes $=0$ at the end, unless you are explicit about the right side.\n\n\n```python\nEq(x**2 -1)\n```\n\n\n\n\n$\\displaystyle x^{2} - 1 = 0$\n\n\n\n\n```python\nEq(x**2, 1)\n```\n\n\n\n\n$\\displaystyle x^{2} = 1$\n\n\n\n\n```python\nEq(x**2, x-1)\n```\n\n\n\n\n$\\displaystyle x^{2} = x - 1$\n\n\n\nWe can solve equations\n\n\n```python\nexpr = Eq(x**2 - 5*x + 6)\nsolve(expr, x)\n```\n\n\n\n\n [2, 3]\n\n\n\nSympy can even give elaborate answers to solutions. In this case, use `solveset` instead of `solve` \n\n\n```python\nsolveset(x - x, x, domain=S.Reals)\n```\n\n\n\n\n$\\displaystyle \\mathbb{R}$\n\n\n\n\n```python\nsolveset(x - x, x)\n```\n\n\n\n\n$\\displaystyle \\mathbb{C}$\n\n\n\n\n```python\nsolveset(sin(x) - 1, x)\n```\n\n\n\n\n$\\displaystyle \\left\\{2 n \\pi + \\frac{\\pi}{2}\\; |\\; n \\in \\mathbb{Z}\\right\\}$\n\n\n\n\n```python\nsolveset(x**2 + 1, x)\n```\n\n\n\n\n$\\displaystyle \\left\\{- i, i\\right\\}$\n\n\n\n---\n## Solving Differential Equations\nThe first step is to declare functions\n\n\n```python\nf, g = symbols('f, g', cls=Function)\n```\n\n`f` and `g` are now undefined functions. We can call `f(x)`, and it will represent an unknown function.\n\n\n```python\nf(x)\n```\n\n\n\n\n$\\displaystyle f{\\left(x \\right)}$\n\n\n\n\n```python\nf(x).diff()\n```\n\n\n\n\n$\\displaystyle \\frac{d}{d x} f{\\left(x \\right)}$\n\n\n\n\n```python\ndiffeq = Eq(f(x).diff(x, x) - 2*f(x).diff(x) + f(x), sin(x))\ndiffeq\n```\n\n\n\n\n$\\displaystyle f{\\left(x \\right)} - 2 \\frac{d}{d x} f{\\left(x \\right)} + \\frac{d^{2}}{d x^{2}} f{\\left(x \\right)} = \\sin{\\left(x \\right)}$\n\n\n\nTo solve the equation, use the `dsolve` method.\n\n\n```python\ndsolve(diffeq, f(x))\n```\n\n\n\n\n$\\displaystyle f{\\left(x \\right)} = \\left(C_{1} + C_{2} x\\right) e^{x} + \\frac{\\cos{\\left(x \\right)}}{2}$\n\n\n\nHere, $C_{i}$ denotes arbitrary constants.\n\n---\n## Matrices\nMatrix operations in SymPy are the same as in numpy. The only diffenrence is that now we can use symbols.\n\n\n```python\nx, y = symbols('x, y')\nM = Matrix([[1, 2, 3], [x, 3, 1], [4, y, 6]])\nM\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}1 & 2 & 3\\\\x & 3 & 1\\\\4 & y & 6\\end{matrix}\\right]$\n\n\n\n\n```python\nM.det()\n```\n\n\n\n\n$\\displaystyle 3 x y - 12 x - y - 10$\n\n\n\nNow take an example of a mtrix with incomplete rank\n\n\n```python\nM = Matrix([[1, 1, 2], [2 ,1 , 3], [3 , 1, 4]])\nM\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}1 & 1 & 2\\\\2 & 1 & 3\\\\3 & 1 & 4\\end{matrix}\\right]$\n\n\n\n\n```python\nM.nullspace() # or \"kernel of the linear transformation\"\n```\n\n\n\n\n [Matrix([\n [-1],\n [-1],\n [ 1]])]\n\n\n\n\n```python\nM.columnspace() # or \"span of the linear transformation\"\n```\n\n\n\n\n [Matrix([\n [1],\n [2],\n [3]]), Matrix([\n [1],\n [1],\n [1]])]\n\n\n\nNotice that each output is a sympy object\n\n\n```python\ndisplay(M.diagonalize()[0])\ndisplay(M.diagonalize()[1])\n```\n\n\n$\\displaystyle \\left[\\begin{matrix}-1 & - \\frac{2 \\sqrt{11}}{7} - \\frac{3}{7} & - \\frac{3}{7} + \\frac{2 \\sqrt{11}}{7}\\\\-1 & \\frac{2}{7} - \\frac{\\sqrt{11}}{7} & \\frac{2}{7} + \\frac{\\sqrt{11}}{7}\\\\1 & 1 & 1\\end{matrix}\\right]$\n\n\n\n$\\displaystyle \\left[\\begin{matrix}0 & 0 & 0\\\\0 & 3 - \\sqrt{11} & 0\\\\0 & 0 & 3 + \\sqrt{11}\\end{matrix}\\right]$\n\n\nAll of this was to get to the following example, the Jacobian Matrix:\n\n\n```python\nfrom sympy.abc import rho, phi\nX = Matrix([rho*cos(phi), rho*sin(phi), rho**2])\nY = Matrix([rho, phi])\nX.jacobian(Y)\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}\\cos{\\left(\\phi \\right)} & - \\rho \\sin{\\left(\\phi \\right)}\\\\\\sin{\\left(\\phi \\right)} & \\rho \\cos{\\left(\\phi \\right)}\\\\2 \\rho & 0\\end{matrix}\\right]$\n\n\n\nJust to grab a better view of what is happening here, let us build a simpler example\n\n\n```python\nx, y, z = symbols('x, y, z')\neq1 = 2*x**2 + 3*y**3 - 2*z\neq2 = 4*x + y**2 - 2*z**3\neq3 = 3*x + 2*y - 3*z**4\nM1 = Matrix([eq1, eq2, eq3])\nM2 = Matrix([x, y])\nM1.jacobian(M2)\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}4 x & 9 y^{2}\\\\4 & 2 y\\\\3 & 2\\end{matrix}\\right]$\n\n\n\nThis kind of structure will be perfect for DSGE models\n", "meta": {"hexsha": "e66a2ec8d8378bd87231748ac5fbd18a9bb87c87", "size": 43645, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Python Lectures/Section 11 - Symbolic Computation with Sympy.ipynb", "max_stars_repo_name": "Finance-Hub/FinanceHubMaterials", "max_stars_repo_head_hexsha": "e06cae52ac34873413e946810ad5e6bf79b1c0dc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 38, "max_stars_repo_stars_event_min_datetime": "2019-11-12T04:52:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-12T09:27:08.000Z", "max_issues_repo_path": "Python Lectures/Section 11 - Symbolic Computation with Sympy.ipynb", "max_issues_repo_name": "antoniosalomao/FinanceHubMaterials", "max_issues_repo_head_hexsha": "0e2aead9c2a7c92a6826b6b47970afbfa30fb1b2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-04-04T03:03:17.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-04T03:03:17.000Z", "max_forks_repo_path": "Python Lectures/Section 11 - Symbolic Computation with Sympy.ipynb", "max_forks_repo_name": "antoniosalomao/FinanceHubMaterials", "max_forks_repo_head_hexsha": "0e2aead9c2a7c92a6826b6b47970afbfa30fb1b2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 20, "max_forks_repo_forks_event_min_datetime": "2019-06-28T15:35:10.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-04T02:34:10.000Z", "avg_line_length": 19.8566878981, "max_line_length": 370, "alphanum_fraction": 0.4575323634, "converted": true, "num_tokens": 4405, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191297273498, "lm_q2_score": 0.9059898140375993, "lm_q1q2_score": 0.8655094006882428}} {"text": "# Linear Modelling - Maxiumum Likelihood\n\nOne approach to learning parameters is minimizing the loss function, another method is to incorporate a random variable to denote _noise_, which has considerable advantages over are former approach.\n\n## The Gaussian (normal) distribution\n\nA Gaussian distribution is defined over the sample space of all real numbers with the pdf for a random varaible $Y$ as the following:\n\n$$\np(y \\mid \\mu, \\sigma^2) = \\frac{1}{\\sigma \\sqrt{2 \\pi}} \\exp{\\left\\{ - \\frac{1}{2 \\sigma^2} (y - \\mu)^2 \\right\\}}\n$$\n\nThe common shorthand notation is the following:\n\n$$\np(y \\mid \\mu, \\sigma^2) = \\mathcal{N}(\\mu, \\sigma^2)\n$$\n\n\n```python\n%matplotlib inline\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.stats import norm\n\nx_axis = np.linspace(-5, 10, 100)\n\nplt.plot(x_axis, norm.pdf(x_axis,-2,0.1 ** 0.5), 'r', label=\"$\\mu = -2, \\sigma^2 = 0.1$\")\nplt.plot(x_axis, norm.pdf(x_axis,0,0.3 ** 0.5), 'g', label=\"$\\mu = 0, \\sigma^2 = 0.3$\")\nplt.plot(x_axis, norm.pdf(x_axis,5,2 ** 0.5), 'b', label=\"$\\mu = 5, \\sigma^2 = 2$\")\nplt.legend()\nplt.show()\n```\n\n## Multivariate Gaussian\n\nWe can generalize the gaussain distribution to define a density function over vectors. For a vector $\\mathbf{x} = [x_1, ... x_D]^T$ the density function is defined as:\n\n$$\np(\\mathbf{x}) = \\frac{1}{(2 \\pi)^{\\frac{D}{2}}{\\begin{vmatrix}\\mathbf{\\Sigma}\\end{vmatrix}^{\\frac{1}{2}}}} \\exp \\left\\{ - \\frac{1}{2} (\\mathbf{x} - \\mathbf{\\mu})^T \\mathbf{\\Sigma}^{-1} (\\mathbf{x} - \\mathbf{\\mu}) \\right\\}\n$$\n\nwhere $\\mathbf{\\mu}$ is a vector of mean values, and the variance a $D \\times D$ covariance matrix (a matrix whose element in the $i$, $j$ position is the covariance between the $i$ th and $j$ th elements).\n\n\n```python\nfrom scipy.stats import multivariate_normal\nfrom mpl_toolkits.mplot3d import Axes3D\n\ndef plot_m_gauss(mu, variance):\n #Create grid and multivariate normal\n x = np.linspace(-2,5,500)\n y = np.linspace(5,-2,500)\n X, Y = np.meshgrid(x,y)\n pos = np.empty(X.shape + (2,))\n pos[:, :, 0] = X; pos[:, :, 1] = Y\n rv = multivariate_normal(mu, variance)\n\n #Make a 3D plot\n fig = plt.figure()\n ax = fig.gca(projection='3d')\n ax.plot_surface(X, Y, rv.pdf(pos),cmap='viridis',linewidth=0)\n ax.set_xlabel('x1')\n ax.set_ylabel('x2')\n plt.show()\n\n plt.contour(X, Y, rv.pdf(pos))\n plt.show()\n \n\nmu_1 = np.array([2, 1]).T\nvariance_1 = np.array([[1, 0], [0, 1]])\nprint(\"mu = {}, Epsilon = {}\".format(mu_1, variance_1))\nplot_m_gauss(mu_1, variance_1)\n\nmu_2 = np.array([2, 1]).T\nvariance_2 = np.array([[1, 0.8], [0.8, 1]])\nprint(\"mu = {}, Epsilon = {}\".format(mu_2, variance_2))\nplot_m_gauss(mu_2, variance_2)\n```\n\nA special case of the multivariate Gaussian is where the two variables are independent, hence:\n\n$$\n\\mathbf{\\Sigma} = \\begin{bmatrix} 1 & 0 \\\\ 0 & 1 \\end{bmatrix} = \\mathbf{I}\n$$\n\n$$\n\\begin{align}\np(\\mathbf{x}) &= \\frac{1}{(2 \\pi)^{\\frac{D}{2}} \\begin{vmatrix}\\mathbf{I}\\end{vmatrix}^{\\frac{1}{2}} } \\exp \\left\\{ - \\frac{1}{2} (\\mathbf{x} - \\mathbf{\\mu})^T \\mathbf{I}^{-1} (\\mathbf{x} - \\mathbf{\\mu}) \\right\\} \\\\\n&= \\frac{1}{(2 \\pi)^{\\frac{D}{2}} \\begin{vmatrix}\\mathbf{I}\\end{vmatrix}^{\\frac{1}{2}} } \\exp \\left\\{ - \\frac{1}{2} (\\mathbf{x} - \\mathbf{\\mu})^T (\\mathbf{x} - \\mathbf{\\mu}) \\right\\} \\\\\n&= \\frac{1}{(2 \\pi)^{\\frac{D}{2}} \\begin{vmatrix}\\mathbf{I}\\end{vmatrix}^{\\frac{1}{2}} } \\exp \\left\\{ - \\frac{1}{2} \\sum_{d=1}^D (x_d - \\mu_d)^2 \\right\\}\n\\end{align}\n$$\n\nThe exponential of a sum is a product of exponentials thus\n\n$$\np(\\mathbf{x}) = \\frac{1}{(2 \\pi)^{\\frac{D}{2}} \\begin{vmatrix}\\mathbf{I}\\end{vmatrix}^{\\frac{1}{2}} } \\prod_{d=1}^D \\exp \\left\\{ - \\frac{1}{2} (x_d - \\mu_d)^2 \\right\\}\n$$\n\nThe determinant of $\\mathbf{I}$ is 1, and $(2 \\pi)^{\\frac{D}{2}}$ can be written as $\\prod_{d=1}^D (2 \\pi)^{\\frac{1}{2}}$ thus we arrive at:\n\n$$\np(\\mathbf{x}) = \\prod_{d=1}^D \\frac{1}{\\sqrt{2 \\pi} } \\exp \\left\\{ - \\frac{1}{2} (x_d - \\mu_d)^2 \\right\\}\n$$\n\nEach term in the product in a univariate Gaussian (with mean $\\mu_d$ and variance $1$), thus by definition of independence ($p(A \\cup B) = p(A)p(B)$ iff $A$ and $B$ are independent), the elements of $\\mathbf{x}$ is independent. This will work for any $\\mathbf{\\Sigma}$ with non-zero elements only in the diagonal positions.\n\n## Thinking generatively\n\nIf we think how we could generate mens 100m times that looks like the data we observe we would arive at the following:\n\n$$\nt_n = \\mathbf{w}^T \\mathbf{x}_n + \\epsilon_n\n$$\n\nwhere $\\epsilon_n$ is a random variable.\n\nNow we need to determine the distribution for $\\epsilon_n$. Our model is continous thus $\\epsilon_n$ is must be a continous random varible. Their is a random variable for each Olympic year, and its a resonable assumption that these values are independent.\n\n$$\np(\\epsilon_1, ..., \\epsilon_n) = \\prod_{n=1}^N p(\\epsilon_n)\n$$\n\nLets assume $p(\\epsilon_n)$ follows a Gaussian distribution with a zero mean and variance $\\sigma$. Our model can now be described as two components:\n\n1. A _deterministic_ component ($\\mathbf{w}^T \\mathbf{x}_n$) referred to as a _trend_ or _drift_\n2. A random component ($\\epsilon_n$) referred to as _noise_\n\nIn our case the noise is _additive_ but some applications might call for _mulitiplicative_ noise such as pixel degradation.\n\n## Likelihood\n\nOur model is of the following form:\n\n$$\nt_n = f(x_n; \\mathbf{w}) + \\epsilon_n \\quad \\epsilon_n \\sim \\mathcal{N}(0, \\sigma^2)\n$$\n\nWe cant minimize the loss since $t_n$ is no longer a fixed value, its a random variable. Adding a constant ($\\mathbf{w}^T \\mathbf{x}_n$) to a Gausian distributed random variable is equivalent to a new Gausian random variable with the constant added to the mean. Thus $t_n$ has the following pdf:\n\n$$\np(t_n \\mid \\mathbf{x}_n, \\mathbf{w}, \\sigma^2) = \\mathcal{N}(\\mathbf{w}^T \\mathbf{x}_n, \\sigma^2)\n$$\n\nWe can use this to find optimal values for $\\mathbf{w}$ and $\\sigma^2$, consider the year 1980, using the values for $\\mathbf{w}$ we found previously and assuming $\\sigma^2 = 0.05$ we can plot:\n\n$$\np\\left(t_n \\mid \\mathbf{x}_n = \\begin{bmatrix}1\\\\1980\\end{bmatrix}, \\mathbf{w} = \\begin{bmatrix}36.416\\\\-0.0133\\end{bmatrix}, \\sigma^2 = 0.05 \\right)\n$$\n\n\n```python\nmu = 36.41645590250286 - 0.013330885710960602 * 1980\nsigma2 = 0.05 \n\nprint(\"mu = {}, sigma^2 = {}\".format(mu, sigma2))\n\nx_axis = np.linspace(9, 11, 50)\n\nplt.plot(x_axis, norm.pdf(x_axis, mu, sigma2 ** 0.5), 'r')\nplt.show()\n```\n\nAccording to the graph the most _likely_ winning time for 1980 is $10.02$ seconds. The actuall time was $10.25$, thus we need to tune the parameters $\\mathbf{w}$ and $\\sigma^2$ to make the density as high as possible at $t = 10.25$.\n\n## Dataset likelihood\n\nWe can extend this to the whole dataset by finding the joint conditional density:\n\n$$\np(t_1, ..., t_N \\mid \\mathbf{x}_1, ..., \\mathbf{x}_N, \\mathbf{w}, \\sigma^2)\n$$\n\nBy using the vector notation defined previously and the assumption that the noise at each datapoint is independent, we get the following:\n\n$$\nL = p(\\mathbf{t} \\mid \\mathbf{X}, \\mathbf{w}, \\sigma^2) = \\prod_{n=1}^N p(t_n \\mid \\mathbf{x_n}, \\mathbf{w}, \\sigma^2) = \\prod_{n=1}^N \\mathcal{N}(\\mathbf{w}^T \\mathbf{x}_n, \\sigma^2)\n$$\n\n## Maximum likelihood\n\nTo find $\\widehat{\\mathbf{w}}$ and $\\widehat{\\sigma^2}$ clearly we need to maximize the value of $L$, to do this we will maximize the log-likelyhood (for analytical reasons)\n\n$$\n\\begin{align}\nL &= \\prod_{n=1}^N \\mathcal{N}(\\mathbf{w}^T \\mathbf{x}_n, \\sigma^2) \\\\\n\\log L &= \\log \\left(\\prod_{n=1}^N \\mathcal{N}(\\mathbf{w}^T \\mathbf{x}_n, \\sigma^2) \\right) \\\\\n&= \\sum_{n=1}^N \\log \\mathcal{N}(\\mathbf{w}^T \\mathbf{x}_n, \\sigma^2) \\\\\n&= \\sum_{n=1}^N \\log \\left( \\frac{1}{\\sigma \\sqrt{2 \\pi}} \\exp{\\left\\{ - \\frac{1}{2 \\sigma^2} (t_n - \\mathbf{w}^T \\mathbf{x}_n)^2 \\right\\}} \\right) \\\\\n&= \\sum_{n=1}^N \\left( -\\frac{1}{2} \\log(2 \\pi) - \\log \\sigma - \\frac{1}{2 \\sigma^2} (t_n - \\mathbf{w}^T \\mathbf{x}_n)^2 \\right) \\\\\n&= -\\frac{N}{2} \\log(2 \\pi) - N \\log \\sigma - \\frac{1}{2 \\sigma^2} \\sum_{n=1}^N (t_n - \\mathbf{w}^T \\mathbf{x}_n)^2 \\\\\n\\end{align}\n$$\n\nAs previosly we differentiate and set to zero to find the turning point, in this case we want a maximum.\n\n$$\n\\begin{align}\n\\frac{\\partial \\log L}{\\partial \\mathbf{w}} &= \\frac{1}{\\sigma^2} \\sum^N_{n=1} \\mathbf{x}_n(t_n - \\mathbf{x}_n^T \\mathbf{w}) \\\\\n&= \\frac{1}{\\sigma^2} \\sum^N_{n=1} \\mathbf{x}_n t_n - \\mathbf{x}_n \\mathbf{x}_n^T \\mathbf{w} \\\\\n\\end{align}\n$$\n\nUsing the vector/matix notation from earlier, $\\sum_{n=1}^N \\mathbf{x}_n t_n$ becomes $\\mathbf{X}^T \\mathbf{t}$ and $\\sum_{n=1}^N \\mathbf{x}_n \\mathbf{x}_n^T \\mathbf{w}$ becomes $\\mathbf{X}^T \\mathbf{Xw}$, thus the derivitive becomes:\n\n$$\n\\frac{\\partial \\log L}{\\partial \\mathbf{w}} = \\frac{1}{\\sigma^2} (\\mathbf{X}^T \\mathbf{t} - \\mathbf{X}^t \\mathbf{Xw})\n$$\n\nSetting the derivitive to $\\mathbf{0}$ (a vector with all zeros) and solving for $\\mathbf{w}$ gives us:\n\n$$\n\\begin{align}\n\\frac{1}{\\sigma^2} (\\mathbf{X}^T \\mathbf{t} - \\mathbf{X}^t \\mathbf{Xw}) &= \\mathbf{0} \\\\\n\\mathbf{X}^T \\mathbf{t} - \\mathbf{X}^t \\mathbf{Xw} &= \\mathbf{0} \\\\\n- \\mathbf{X}^t \\mathbf{Xw} &= - \\mathbf{X}^T \\mathbf{t} \\\\\n\\mathbf{X}^t \\mathbf{Xw} &= \\mathbf{X}^T \\mathbf{t} \\\\\n\\widehat{\\mathbf{w}} &= (\\mathbf{X}^T \\mathbf{X})^{-1} \\mathbf{X}^T \\mathbf{t} \\\\\n\\end{align}\n$$\n\nThis is the same result as minimizing the squared loss. Minimising the squared loss is equivalent to the maximum likelihood solution if the noise is assumed to be Gaussian.\n\nNow we repeat the process for $\\sigma^2$\n\n$$\n\\begin{align}\n\\frac{\\partial \\log L}{\\partial \\sigma} &= - \\frac{N}{\\sigma} + \\frac{1}{\\sigma^3} \\sum_{n=1}^N (t_n - \\mathbf{x}^T \\widehat{\\mathbf{w}})^2\n\\end{align}\n$$\n\n$$\n\\begin{align}\n- \\frac{N}{\\sigma} + \\frac{1}{\\sigma^3} \\sum_{n=1}^N (t_n - \\mathbf{x}^T \\widehat{\\mathbf{w}})^2 &= 0 \\\\ \n\\frac{1}{\\sigma^3} \\sum_{n=1}^N (t_n - \\mathbf{x}^T \\widehat{\\mathbf{w}})^2 &= \\frac{N}{\\sigma} \\\\\n\\sum_{n=1}^N (t_n - \\mathbf{x}^T \\widehat{\\mathbf{w}})^2 &= N \\sigma^2 \\\\\n\\widehat{\\sigma^2} &= \\frac{1}{N} \\sum_{n=1}^N (t_n - \\mathbf{x}^T \\widehat{\\mathbf{w}})^2 \\\\\n\\end{align}\n$$\n\nThis makes sence, the variance is the average square error. We can use the fact that $\\sum_{n=1}^N (t_n - \\mathbf{x}^T \\widehat{\\mathbf{w}})^2$ is equivalent to $(\\mathbf{t} - \\mathbf{X}\\widehat{\\mathbf{w}})^T (\\mathbf{t} - \\mathbf{X}\\widehat{\\mathbf{w}})$\n\n$$\n\\begin{align}\n\\widehat{\\sigma^2} &= \\frac{1}{N} (\\mathbf{t} - \\mathbf{X}\\widehat{\\mathbf{w}})^T (\\mathbf{t} - \\mathbf{X}\\widehat{\\mathbf{w}}) \\\\\n&= \\frac{1}{N} (\\mathbf{t}^T \\mathbf{t} - 2 \\mathbf{t}^T \\mathbf{X} \\widehat{\\mathbf{w}} + \\widehat{\\mathbf{w}}^T \\mathbf{X}^T \\mathbf{X} \\widehat{\\mathbf{w}}) \\\\\n\\end{align}\n$$\n\nNow using $\\widehat{\\mathbf{w}} = (\\mathbf{X}^T \\mathbf{X})^{-1} \\mathbf{X}^T \\mathbf{t}$ and $\\widehat{\\mathbf{w}}^T = \\mathbf{t}^T \\mathbf{X} (\\mathbf{X}^T \\mathbf{X})^{-1}$\n\n$$\n\\begin{align}\n\\widehat{\\sigma^2} &= \\frac{1}{N} (\\mathbf{t}^T \\mathbf{t} - 2 \\mathbf{t}^T \\mathbf{X} (\\mathbf{X}^T \\mathbf{X})^{-1} \\mathbf{X}^T \\mathbf{t} + \\mathbf{t}^T \\mathbf{X} (\\mathbf{X}^T \\mathbf{X})^{-1} \\mathbf{X}^T \\mathbf{X} (\\mathbf{X}^T \\mathbf{X})^{-1} \\mathbf{X}^T \\mathbf{t}) \\\\\n&= \\frac{1}{N} (\\mathbf{t}^T \\mathbf{t} - 2 \\mathbf{t}^T \\mathbf{X} (\\mathbf{X}^T \\mathbf{X})^{-1} \\mathbf{X}^T \\mathbf{t} + \\mathbf{t}^T \\mathbf{X} (\\mathbf{X}^T \\mathbf{X})^{-1} \\mathbf{X}^T \\mathbf{t}) \\\\\n&= \\frac{1}{N} (\\mathbf{t}^T \\mathbf{t} - \\mathbf{t}^T \\mathbf{X} (\\mathbf{X}^T \\mathbf{X})^{-1} \\mathbf{X}^T \\mathbf{t}) \\\\\n&= \\frac{1}{N} (\\mathbf{t}^T \\mathbf{t} - \\mathbf{t}^T \\mathbf{X} \\widehat{\\mathbf{w}}) \\\\\n\\end{align}\n$$\n\n\n```python\nx_values = [1896, 1900, 1904, 1906, 1908, 1912, 1920, 1924, 1928, 1932, 1936, 1948, 1952, 1956, 1960, 1964, \n 1968, 1972, 1976, 1980, 1984, 1988, 1992, 1996, 2000, 2004, 2008]\nt_values = [12.00, 11.00, 11.00, 11.20, 10.80, 10.80, 10.80, 10.60, 10.80, 10.30, 10.30, 10.30, 10.40, 10.50, \n 10.20, 10.00, 9.95, 10.14, 10.06, 10.25, 9.99, 9.92, 9.96, 9.84, 9.87, 9.85, 9.69]\n\nN = len(x_values)\nX = np.matrix([[1,x] for x in x_values])\n\ndef get_params(X_mat):\n XT = np.transpose(X_mat)\n tT = np.matrix([t_values])\n t = np.transpose(tT)\n\n best_w = ((XT * X_mat) ** -1) * XT * t\n best_sigma2 = (1/N) * (tT * t - tT * X_mat * best_w)\n\n return (best_w, best_sigma2)\n \nprint(\"w = {}\\n\\nsigma^2 = {}\".format(*get_params(X)))\n```\n\n w = [[ 3.64164559e+01]\n [ -1.33308857e-02]]\n \n sigma^2 = [[ 0.05030711]]\n\n\n## Checking the turning point\n\nPreviously we had differentatiated the loss function twice to check the turning point was a minimum, we would like to do the same here to check if the likelihood is maximum.\n\nSince the dirivative is with respect to a vector, we need to form a Hessian matrix, a square matrix with all the second order patrial derivatives of a function, for example for a function $f(\\mathbf{x}; \\mathbf{w})$ where $\\mathbf{w} = [w_1, ..., w_K]^T$\n\n$$\n\\mathbf{H} = \\begin{bmatrix}\n\\dfrac{\\partial^2 f}{\\partial w_1^2} & \\dfrac{\\partial^2 f}{\\partial w_1 \\partial w_2} & \\cdots & \\dfrac{\\partial^2 f}{\\partial w_1 \\partial w_K} \\\\\n\\dfrac{\\partial^2 f}{\\partial w_2 \\partial w_1} & \\dfrac{\\partial^2 f}{\\partial w_2^2} & \\cdots & \\dfrac{\\partial^2 f}{\\partial w_2 \\partial w_K} \\\\\n\\vdots & \\vdots & \\ddots & \\vdots \\\\\n\\dfrac{\\partial^2 f}{\\partial w_K \\partial w_1} & \\dfrac{\\partial^2 f}{\\partial w_K \\partial w_2} & \\cdots & \\dfrac{\\partial^2 f}{\\partial w_K^2} \\\\\n\\end{bmatrix}\n$$\n\nThe turning point is maximum if the matix is negative definite. A real-valued matrix is negative definite if $\\mathbf{x}^T \\mathbf{H} \\mathbf{x} < 0$ for all real values of $\\mathbf{x}$\n\nThe first order derivative was\n\n$$\n\\frac{\\partial \\log L}{\\partial \\mathbf{w}} = \\frac{1}{\\sigma^2} (\\mathbf{X}^T \\mathbf{t} - \\mathbf{X}^t \\mathbf{Xw})\n$$\n\nIntegrating with repect to $\\mathbf{w}^T$ gives us the Hessian matrix:\n\n$$\n\\frac{\\partial \\log L}{\\partial \\mathbf{w} \\partial \\mathbf{w}^T} = - \\frac{1}{\\sigma^2} \\mathbf{X}^T \\mathbf{X}\n$$\n\nNow to check the matrix is negative definite we must show\n\n$$\n- \\frac{1}{\\sigma^2} \\mathbf{z}^T \\mathbf{X}^T \\mathbf{X} \\mathbf{z} < 0\n$$\n\nfor any vector $\\mathbf{z}$ or equivalently (since $\\sigma^2$ must be positive)\n\n$$\n\\mathbf{z}^T \\mathbf{X}^T \\mathbf{X} \\mathbf{z} > 0\n$$\n\nSo that we can explicitly multiply out the various terms, we will rescrict $\\mathbf{X}$ to\n\n$$\n\\mathbf{X} \n= \n\\begin{bmatrix}\n\\mathbf{x}^T_1 \\\\\n\\mathbf{x}^T_2 \\\\\n\\vdots \\\\\n\\mathbf{x}^T_N\n\\end{bmatrix}\n=\n\\begin{bmatrix}\nx_{11} & x_{12} \\\\\nx_{21} & x_{22} \\\\\n\\vdots & \\vdots \\\\\nx_{N1} & x_{N2}\n\\end{bmatrix}\n$$\n\nThus $\\mathbf{X}^T \\mathbf{X}$ becomes\n\n$$\n\\mathbf{X}^T \\mathbf{X} \n= \n\\begin{bmatrix}\n\\sum_{i=1}^N{x^2_{i1}} & \\sum_{i=1}^N{x_{i1} x_{i2}} \\\\\n\\sum_{i=1}^N{x_{i2} x_{i1}} & \\sum_{i=1}^N{x^2_{i2}}\n\\end{bmatrix}\n$$\n\nPre and post multiplying with the arbitary vector $\\mathbf{z} = \\begin{bmatrix} z_1 \\\\ z_2 \\end{bmatrix}$ gives us:\n\n$$\n\\begin{align}\n\\mathbf{z}^T \\mathbf{X}^T \\mathbf{X} \\mathbf{z} &= \\mathbf{z}^T \n\\begin{bmatrix}\n\\sum_{i=1}^N{x^2_{i1}} & \\sum_{i=1}^N{x_{i1} x_{i2}} \\\\\n\\sum_{i=1}^N{x_{i2} x_{i1}} & \\sum_{i=1}^N{x^2_{i2}}\n\\end{bmatrix}\n\\mathbf{z} \\\\\n&=\n\\begin{bmatrix}\nz_1 \\sum_{i=1}^N{x^2_{i1}} + z_2 \\sum_{i=1}^N{x_{i2} x_{i1}} &\nz_1 \\sum_{i=1}^N{x_{i1} x_{i2}} + z_2 \\sum_{i=1}^N{x^2_{i2}}\n\\end{bmatrix}\n\\mathbf{z} \\\\\n&= z_1^2 \\sum_{i=1}^N{x^2_{i1}} + 2 z_1 z_2 \\sum_{i=1}^N{x_{i1} x_{i2}} + z^2_2 \\sum_{i=1}^N{x^2_{i2}}\n\\end{align}\n$$\n\nThe terms $z_1^2 \\sum_{i=1}^N{x^2_{i1}}$ and $z^2_2 \\sum_{i=1}^N{x^2_{i2}}$ are always positive thus proving $\\mathbf{z}^T \\mathbf{X}^T \\mathbf{X} \\mathbf{z}$ is positive is equivalent to\n\n$$\nz_1^2 \\sum_{i=1}^N{x^2_{i1}} + z^2_2 \\sum_{i=1}^N{x^2_{i2}} > 2 z_1 z_2 \\sum_{i=1}^N{x_{i1} x_{i2}}\n$$\n\nThe sum of the positive terms must be greater that the other term so that the whole term is greater than zero. Now let $y_{i1} = z_1 x_{i1}$ and $y_{i2} = z_2 x_{i2}$.\n\n$$\n\\begin{align}\nz_1^2 \\sum_{i=1}^N{x^2_{i1}} + z^2_2 \\sum_{i=1}^N{x^2_{i2}} &> 2 z_1 z_2 \\sum_{i=1}^N{x_{i1} x_{i2}}\\\\\n\\sum_{i=1}^N{y^2_{i1}} + \\sum_{i=1}^N{y^2_{i2}} &> 2 \\sum_{i=1}^N{y_{i1} y_{i2}}\\\\\n\\sum_{i=1}^N{\\left(y^2_{i1} + y^2_{i2} \\right)} &> 2 \\sum_{i=1}^N{y_{i1} y_{i2}}\n\\end{align}\n$$\n\nNow consider an arbitary $i$\n\n$$\n\\begin{align}\ny^2_{i1} + y^2_{i2} &> 2 y_{i1} y_{i2} \\\\\ny^2_{i1} - 2 y_{i1} y_{i2} + y^2_{i2} &> 0 \\\\\n(y_{i1} - y_{i2})^2 &> 0\n\\end{align}\n$$\n\nThus the only case where this is not true is when $y_{i1}^2 = y_{i2}^2$ and thus $x_{i1} = x_{i2}$, somthing that is unlikely to happen in practive. Thus for an arbitary $i$, $y^2_{i1} + y^2_{i2} > 2 y_{i1} y_{i2}$ holds, and thus the summation of the terms holds. Hence, $\\mathbf{z}^T \\mathbf{X}^T \\mathbf{X} \\mathbf{z}$ is always positive, thus $\\mathbf{H}$, our Hessian matrix is negative definite, thus the solution is a maximum.\n\nLikewise, to check $\\widehat{\\sigma^2}$ corrsponds to the maximum, we diffentiate\n\n$$\n\\frac{\\partial \\log L}{\\partial \\sigma} = - \\frac{N}{\\sigma} + \\frac{1}{\\sigma^3} \\sum_{n=1}^N (t_n - \\mathbf{x}^T \\widehat{\\mathbf{w}})^2\n$$\n\nAgain with respect to $\\sigma$, giving us\n\n$$\n\\frac{\\partial \\log L}{\\partial \\sigma^2} = - \\frac{N}{\\sigma^2} + \\frac{3}{\\sigma^4} \\sum_{n=1}^N (t_n - \\mathbf{x}^T \\widehat{\\mathbf{w}})^2\n$$\n\nSubstituting $\\widehat{\\sigma^2} = \\frac{1}{N} \\sum_{n=1}^N (t_n - \\mathbf{x}^T \\widehat{\\mathbf{w}})^2$\n\n$$\n\\begin{align}\n\\frac{\\partial \\log L}{\\partial \\sigma^2} &= - \\frac{N}{\\widehat{\\sigma^2}} + \\frac{3}{\\left(\\widehat{\\sigma^2}\\right)^2} N \\widehat{\\sigma^2} \\\\\n&= - \\frac{2N}{\\widehat{\\sigma^2}}\n\\end{align}\n$$\n\nThus $\\widehat{\\sigma^2}$ corresponds to a maximum.\n\n## Maximum likelihood favours complexity\n\nBy substituting $\\widehat{\\sigma^2}$ into $\\log L$ gives the value of the log-likelihood at the maximum\n\n$$\n\\begin{align}\n\\log L &= -\\frac{N}{2} \\log(2 \\pi) - N \\log \\sigma - \\frac{1}{2 \\sigma^2} \\sum_{n=1}^N (t_n - \\mathbf{w}^T \\mathbf{x}_n)^2 \\\\\n&= -\\frac{N}{2} \\log(2 \\pi) - N \\log \\sqrt{\\widehat{\\sigma^2}} - \\frac{1}{2 \\widehat{\\sigma^2}} N\\widehat{\\sigma^2} \\\\\n&= -\\frac{N}{2} \\log(2 \\pi) - \\frac{N}{2} \\log \\widehat{\\sigma^2} - \\frac{N}{2}\\\\\n&= -\\frac{N}{2} (1 + \\log 2 \\pi) - \\frac{N}{2} \\log \\widehat{\\sigma^2}\\\\\n\\end{align}\n$$\n\nThus by decreasing $\\widehat{\\sigma^2}$ we increase the log-likeliness. One way to decrease $\\widehat{\\sigma^2}$ is to modify $f(\\mathbf{x};\\mathbf{w})$ so that it can capture more of the noise. The same tradeoff between overfitting and generalization as we saw last time occors. Before we used regularization to peanalize complex models, _prior distributions_ on parameter values can acieve the same thing with probablistic models.\n\n\n```python\n# Normalize x, for numerical stability\nstable_x = np.array([float(x) for x in x_values]) - x_values[0]\nstable_x *= 0.4\n\norders = list(range(2, 9))\nlog_Ls = []\nfor order in orders:\n X = np.matrix([[x**o for o in range(0, order)] for x in stable_x])\n (_, ss) = get_params(X)\n log_L = -(N/2)*(1+np.log(2 * np.pi)) - (N/2) * np.log(ss)\n log_Ls.append(log_L.item(0))\n \nplt.plot(orders, log_Ls, 'r')\nplt.xlabel('Polynomial order')\nplt.ylabel('log L')\nplt.show()\n```\n\n## Effect of noise on estimates\n\nIt would be useful to determine how much confidence we have in our parameters. Firstly is our estimator $\\widehat{w}$ _unbiased_.\n\nOur current model takes the form:\n\n$$\nt_n = \\mathbf{w}^T \\mathbf{x}_n + \\epsilon_n\n$$\n\nSince we defined $\\epsilon_n$ to be normally distributed, the _generating_ distribution (or likelihood) is a product of normal densities:\n\n$$\np(\\mathbf{t} \\mid \\mathbf{X}, \\mathbf{w}, \\sigma^2) = \\prod^N_{n=1} p(t_n \\mid \\mathbf{x}_n \\mathbf{w}) = \\prod^N_{n=1} \\mathcal{N}(\\mathbf{w}^T \\mathbf{x}_n, \\sigma^2)\n$$\n\nWe have shown that a product of univariant Gaussians can be rewritten as a multivariant Gaussian with a diangonal covariance, thus\n\n$$\np(\\mathbf{t} \\mid \\mathbf{X}, \\mathbf{w}, \\sigma^2) = \\prod^N_{n=1} \\mathcal{N}(\\mathbf{w}^T \\mathbf{x}_n, \\sigma^2) = \\mathcal{N}(\\mathbf{Xw}, \\sigma^2 \\mathbf{I})\n$$\n", "meta": {"hexsha": "1feb49de67f37b2d72ae60d51cebd4e5bec66632", "size": 282401, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Linear Modelling - Maximum Likelihood.ipynb", "max_stars_repo_name": "bongo227/machine-learning-notes", "max_stars_repo_head_hexsha": "ddefb5119c9a11983a79a7657493513ef07b9ddf", "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": "Linear Modelling - Maximum Likelihood.ipynb", "max_issues_repo_name": "bongo227/machine-learning-notes", "max_issues_repo_head_hexsha": "ddefb5119c9a11983a79a7657493513ef07b9ddf", "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": "Linear Modelling - Maximum Likelihood.ipynb", "max_forks_repo_name": "bongo227/machine-learning-notes", "max_forks_repo_head_hexsha": "ddefb5119c9a11983a79a7657493513ef07b9ddf", "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": 402.2806267806, "max_line_length": 74540, "alphanum_fraction": 0.9198550997, "converted": true, "num_tokens": 8065, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422199928904, "lm_q2_score": 0.9099070115349837, "lm_q1q2_score": 0.8654509749384809}} {"text": "# 13 Linear Algebra: Singular Value Decomposition (Students)\n\nOne can always decompose a matrix $\\mathsf{A}$ \n\n\\begin{gather}\n\\mathsf{A} = \\mathsf{U}\\,\\text{diag}(w_j)\\,\\mathsf{V}^{T}\\\\\n\\mathsf{U}^T \\mathsf{U} = \\mathsf{U} \\mathsf{U}^T = 1\\\\\n\\mathsf{V}^T \\mathsf{V} = \\mathsf{V} \\mathsf{V}^T = 1\n\\end{gather}\n\nwhere $\\mathsf{U}$ and $\\mathsf{V}$ are orthogonal matrices and the $w_j$ are the _singular values_ that are assembled into a diagonal matrix $\\mathsf{W}$.\n\n$$\n\\mathsf{W} = \\text{diag}(w_j)\n$$\n\nThe inverse (if it exists) can be directly calculated from the SVD:\n\n$$\n\\mathsf{A}^{-1} = \\mathsf{V} \\text{diag}(1/w_j) \\mathsf{U}^T\n$$\n\n## Solving ill-conditioned coupled linear equations \n\n\n```python\nimport numpy as np\n```\n\n### Non-singular matrix \nSolve the linear system of equations\n\n$$\n\\mathsf{A}\\mathbf{x} = \\mathbf{b}\n$$\n\nUsing the standard linear solver in numpy:\n\n\n```python\nA = np.array([\n [1, 2, 3],\n [3, 2, 1],\n [-1, -2, -6],\n ])\nb = np.array([0, 1, -1])\n```\n\n\n```python\n\n```\n\nUsing the inverse from SVD:\n\n$$\n\\mathbf{x} = \\mathsf{A}^{-1} \\mathbf{b}\n$$\n\n\n```python\n\n```\n\nFirst check that the SVD really factors $\\mathsf{A} = \\mathsf{U}\\,\\text{diag}(w_j)\\,\\mathsf{V}^{T}$:\n\n\n```python\n\n```\n\nNow calculate the matrix inverse $\\mathsf{A}^{-1} = \\mathsf{V} \\text{diag}(1/w_j) \\mathsf{U}^T$:\n\n\n```python\n\n```\n\nCheck that this is the same that we get from `numpy.linalg.inv()`:\n\n\n```python\n\n```\n\nNow, *finally* solve (and check against `numpy.linalg.solve()`):\n\n\n```python\n\n```\n\n### Singular matrix\n\nIf the matrix $\\mathsf{A}$ is *singular* (i.e., its rank (linearly independent rows or columns) is less than its dimension and hence the linear system of equation does not have a unique solution):\n\nFor example, the following matrix has the same row twice:\n\n\n```python\nC = np.array([\n [ 0.87119148, 0.9330127, -0.9330127],\n [ 1.1160254, 0.04736717, -0.04736717],\n [ 1.1160254, 0.04736717, -0.04736717],\n ])\nb1 = np.array([ 2.3674474, -0.24813392, -0.24813392])\nb2 = np.array([0, 1, 1])\n```\n\nNOTE: failure is not always that obvious: numerically, a matrix can be *almost* singular: Try solving the linear system of equations \n\n$$\n\\mathsf{D}\\mathbf{x} = \\mathbf{b}_1\n$$\nwith matrix $\\mathsf{D}$ below:\n\n\n```python\nD = C.copy()\nD[2, :] = C[0] - 3*C[1]\nD\n```\n\nSolve:\n\n\n```python\n\n```\n\nNote that some of the values are huge, and suspiciously like the inverse of machine precision? Sign of a nearly singular matrix.\n\nNow back to the example with $\\mathsf{C}$:\n\n#### SVD for singular matrices\nIf a matrix is *singular* or *near singular* then one can *still* apply SVD. \n\nOne can then compute the *pseudo inverse*\n\n\\begin{align}\n\\mathsf{A}^{-1} &= \\mathsf{V} \\text{diag}(\\alpha_j) \\mathsf{U}^T \\\\\n\\alpha_j &= \\begin{cases}\n \\frac{1}{w_j}, &\\quad\\text{if}\\ w_j \\neq 0\\\\\n 0, &\\quad\\text{if}\\ w_j = 0\n \\end{cases}\n\\end{align}\n\ni.e., any singular $w_j = 0$ is being \"augmented\" by setting\n\n$$\n\\frac{1}{w_j} \\rightarrow 0 \\quad\\text{if}\\quad w_j = 0\n$$\n\nin $\\text{diag}(1/w_j)$.\n\nPerform the SVD for the singular matrix $\\mathsf{C}$:\n\n\n```python\n\n```\n\nNote the third value $w_2 \\approx 0$: sign of a singular matrix.\n\nTest that the SVD really decomposes $\\mathsf{A} = \\mathsf{U}\\,\\text{diag}(w_j)\\,\\mathsf{V}^{T}$:\n\n\n```python\n\n```\n\nThere are the **singular values** (let's say, $|w_i| < 10^{-12}$):\n\n\n```python\n\n```\n\n#### Pseudo-inverse\n\nCalculate the **pseudo-inverse** from the SVD\n\n\\begin{align}\n\\mathsf{A}^{-1} &= \\mathsf{V} \\text{diag}(\\alpha_j) \\mathsf{U}^T \\\\\n\\alpha_j &= \\begin{cases}\n \\frac{1}{w_j}, &\\quad\\text{if}\\ w_j \\neq 0\\\\\n 0, &\\quad\\text{if}\\ w_j = 0\n \\end{cases}\n\\end{align}\n\n\nAugment:\n\n\n```python\n\n```\n\nNow solve the linear problem with SVD:\n\n\n```python\n\n```\n\nThus, using the pseudo-inverse $\\mathsf{C}^{-1}$ we can obtain solutions to the equation\n\n$$\n\\mathsf{C} \\mathbf{x}_1 = \\mathbf{b}_1\n$$\n\nHowever, $\\mathbf{x}_1$ is not the only solution: there's a whole line of solutions that are formed by the special solution and a combination of the basis vectors in the *null space* of the matrix:\n\nThe (right) *kernel* or *null space* contains all vectors $\\mathbf{x^0}$ for which\n\n$$\n\\mathsf{C} \\mathbf{x^0} = 0\n$$\n\n(The dimension of the null space corresponds to the number of singular values.) You can find a basis that spans the null space. Any linear combination of null space basis vectors will also end up in the null space when $\\mathbf{A}$ is applied to it.\n\n\nSpecifically, if $\\mathbf{x}_1$ is a special solution and $\\lambda_1 \\mathbf{x}^0_1 + \\lambda_2 \\mathbf{x}^0_2 + \\dots$ is a vector in the null space then\n\n$$\n\\mathbf{x} = \\mathbf{x}_1 + ( \\lambda_1 \\mathbf{x}^0_1 + \\lambda_2 \\mathbf{x}^0_2 + \\dots )\n$$\n\nis **also a solution** because\n\n$$\n\\mathsf{C} \\mathbf{x} = \\mathsf{C} \\mathbf{x_1} + \\mathsf{C} ( \\lambda_1 \\mathbf{x}^0_1 + \\lambda_2 \\mathbf{x}^0_2 + \\dots ) = \\mathsf{C} \\mathbf{x_1} + 0 = \\mathbf{b}_1 + 0 = \\mathbf{b}_1\n$$\n\nThe $\\lambda_i$ are arbitrary real numbers and hence there is an infinite number of solutions.\n\nIn SVD:\n\n* The columns $U_{\\cdot, i}$ of $\\mathsf{U}$ (i.e. `U.T[i]` or `U[:, i]`) corresponding to non-zero $w_i$, i.e. $\\{i : w_i \\neq 0\\}$, form the basis for the _range_ of the matrix $\\mathsf{A}$.\n* The columns $V_{\\cdot, i}$ of $\\mathsf{V}$ (i.e. `V.T[i]` or `V[:, i]`) corresponding to zero $w_i$, i.e. $\\{i : w_i = 0\\}$, form the basis for the _null space_ of the matrix $\\mathsf{A}$.\n\nNote that `x1` can be written as a linear combination of `U.T[0]` and `U.T[1]`:\n\n$$\n\\mathbf{x}_1 = (\\mathbf{x}_1\\cdot \\mathsf{U}^T_{0,.}) \\mathsf{U}^T_{0,.} + (\\mathbf{x}_1\\cdot \\mathsf{U}^T_{1,.}) \\mathsf{U}^T_{1,.}\n$$\n\n\n```python\n\n```\n\nThus, **all** solutions are\n```\nx1 + lambda * VT[2]\n```\n\n\nThe solution vector $x_2$ is in the null space: \n\n\n```python\n\n```\n\n(For more details see the solution notebook.)\n\n## SVD for fewer equations than unknowns\n$M$ equations for $N$ unknowns with $M < N$:\n\n* no unique solutions (underdetermined)\n* $N-M$ dimensional family of solutions\n* SVD: at least $N-M$ zero or negligible $w_j$: columns of $\\mathsf{V}$ corresponding to singular $w_j$ span the solution space when added to a particular solution.\n\nSame as the above **Solving ill-conditioned coupled linear equations**.\n\n## SVD for more equations than unknowns\n$M$ equations for $N$ unknowns with $M > N$:\n\n* no exact solutions in general (overdetermined)\n* but: SVD can provide best solution in the least-square sense\n $$\n \\mathbf{x} = \\mathsf{V}\\, \\text{diag}(1/w_j)\\, \\mathsf{U}^{T}\\, \\mathbf{b}\n $$\n where \n\n * $\\mathbf{x}$ is a $N$-dimensional vector of the unknowns,\n * $\\mathsf{V}$ is a $N \\times M$ matrix\n * the $w_j$ form a square $M \\times M$ matrix,\n * $\\mathsf{U}$ is a $N \\times M$ matrix (and $\\mathsf{U}^T$ is a $M \\times N$ matrix), and\n * $\\mathbf{b}$ is the $M$-dimensional vector of the given values\n \nIt provides the $\\mathbf{x}$ that minimizes the residual\n\n$$\n\\mathbf{r} := |\\mathsf{A}\\mathbf{x} - \\mathbf{b}|.\n$$\n\n\n### Linear least-squares fitting \n\nThis is the *linear least-squares fitting problem*: Given data points $(x_i, y_i)$, fit to a linear model $y(x)$, which can be any linear combination of functions of $x$.\n\nFor example: \n\n$$\ny(x) = a_1 + a_2 x + a_3 x^2 + \\dots + a_M x^{M-1}\n$$\n\nor in general\n$$\ny(x) = \\sum_{k=1}^M a_k X_k(x)\n$$\n\nThe goal is to determine the coefficients $a_k$.\n\nDefine the **merit function**\n$$\n\\chi^2 = \\sum_{i=1}^N \\left[ \\frac{y_i - \\sum_{k=1}^M a_k X_k(x_i)}{\\sigma_i}\\right]^2\n$$\n(sum of squared deviations, weighted with standard deviations $\\sigma_i$ on the $y_i$).\n\nBest parameters $a_k$ are the ones that *minimize $\\chi^2$*.\n\n*Design matrix* $\\mathsf{A}$ ($N \\times M$, $N \\geq M$), vector of measurements $\\mathbf{b}$ ($N$-dim) and parameter vector $\\mathbf{a}$ ($M$-dim):\n\n\\begin{align}\nA_{ij} &= \\frac{X_j(x_i)}{\\sigma_i}\\\\\nb_i &= \\frac{y_i}{\\sigma_i}\\\\\n\\mathbf{a} &= (a_1, a_2, \\dots, a_M)\n\\end{align}\n\n\nMinimum occurs when the derivative vanishes:\n$$\n0 = \\frac{\\partial\\chi^2}{\\partial a_k} = \\sum_{i=1}^N {\\sigma_i}^{-2} \\left[ y_i - \\sum_{k=1}^M a_k X_k(x_i) \\right] X_k(x_i), \\quad 1 \\leq k \\leq M\n$$\n($M$ coupled equations)\n\\begin{align}\n\\sum_{j=1}^{M} \\alpha_{kj} a_j &= \\beta_k\\\\\n\\mathsf{\\alpha}\\mathbf{a} = \\mathsf{\\beta}\n\\end{align}\nwith the $M \\times M$ matrix\n\\begin{align}\n\\alpha_{kj} &= \\sum_{i=1}^N \\frac{X_j(x_i) X_k(x_i)}{\\sigma_i^2}\\\\\n\\mathsf{\\alpha} &= \\mathsf{A}^T \\mathsf{A}\n\\end{align}\nand the vector of length $M$\n\\begin{align}\n\\beta_{k} &= \\sum_{i=1}^N \\frac{y_i X_k(x_i)}{\\sigma_i^2}\\\\\n\\mathsf{\\beta} &= \\mathsf{A}^T \\mathbf{b}\n\\end{align}\n\nThe inverse of $\\mathsf{\\alpha}$ is related to the uncertainties in the parameters:\n$$\n\\mathsf{C} := \\mathsf{\\alpha}^{-1}\n$$\nin particular\n$$\n\\sigma(a_i) = C_{ii}\n$$\n(and the $C_{ij}$ are the co-variances).\n\n#### Solution of the linear least-squares fitting problem with SVD\nWe need to solve the overdetermined system of $M$ coupled equations\n\\begin{align}\n\\sum_{j=1}^{M} \\alpha_{kj} a_j &= \\beta_k\\\\\n\\mathsf{\\alpha}\\mathbf{a} = \\mathsf{\\beta}\n\\end{align}\n\nSVD finds $\\mathbf{a}$ that minimizes\n$$\n\\chi^2 = |\\mathsf{A}\\mathbf{a} - \\mathbf{b}|\n$$\n\n(proof in _Numerical Recipes_ Ch 2.)\n\nThe errors are\n$$\n\\sigma^2(a_j) = \\sum_{i=1}^{M} \\left(\\frac{V_{ji}}{w_i}\\right)^2\n$$\n(see _Numerical Recipes_ Ch. 15)\n\n#### Example\nSynthetic data \n\n$$\ny(x) = 3\\sin x - 2\\sin 3x + \\sin 4x\n$$\n\nwith noise $r$ added (uniform in range $-5 < r < 5$).\n\n\n```python\nimport matplotlib\nimport matplotlib.pyplot as plt\n%matplotlib inline\nmatplotlib.style.use('ggplot')\n\nimport numpy as np\n```\n\n\n```python\ndef signal(x, noise=0):\n r = np.random.uniform(-noise, noise, len(x))\n return 3*np.sin(x) - 2*np.sin(3*x) + np.sin(4*x) + r\n```\n\n\n```python\nX = np.linspace(-10, 10, 500)\nY = signal(X, noise=5)\n```\n\n\n```python\nplt.plot(X, Y, 'r-', X, signal(X, noise=0), 'k--')\n```\n\n\n```python\ndef fitfunc(x, a):\n return a[0]*np.cos(x) + a[1]*np.sin(x) + \\\n a[2]*np.cos(2*x) + a[3]*np.sin(2*x) + \\\n a[4]*np.cos(3*x) + a[5]*np.sin(3*x) + \\\n a[6]*np.cos(4*x) + a[7]*np.sin(4*x)\n\ndef basisfuncs(x):\n return np.array([np.cos(x), np.sin(x), \n np.cos(2*x), np.sin(2*x), \n np.cos(3*x), np.sin(3*x), \n np.cos(4*x), np.sin(4*x)])\n```\n\n\n```python\nM = 8\nsigma = 1.\nalpha = np.zeros((M, M))\nbeta = np.zeros(M)\nfor x in X:\n Xk = basisfuncs(x)\n for k in range(M):\n for j in range(M):\n alpha[k, j] += Xk[k]*Xk[j]\nfor x, y in zip(X, Y):\n beta += y * basisfuncs(x)/sigma\n```\n\nNow use SVD!\n\n\n```python\n\n```\n\nIn this case, the singular values do not immediately show if any basis functions are superfluous (this would be the case for values close to 0).\n\n\n```python\nw\n```\n\n... nevertheless, remember to routinely mask any singular values or close to singular values:\n\n\n```python\n\n```\n\nCompare the fitted values to the original parameters $a_j = 0, +3, 0, 0, 0, -2, 0, +1$.\n\n\n```python\n\n```\n\n\n```python\nplt.plot(X, fitfunc(X, a_values), 'b-', label=\"fit\")\nplt.plot(X, signal(X, noise=0), 'k--', label=\"signal\")\nplt.legend(loc=\"best\", fontsize=\"small\")\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "07071c2b3f60de4e1dc4578421688c9de9258be4", "size": 21855, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "13_linear_algebra/13_SVD-Students-1.ipynb", "max_stars_repo_name": "Py4Phy/PHY432-resources", "max_stars_repo_head_hexsha": "c26d95eaf5c28e25da682a61190e12ad6758a938", "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": "13_linear_algebra/13_SVD-Students-1.ipynb", "max_issues_repo_name": "Py4Phy/PHY432-resources", "max_issues_repo_head_hexsha": "c26d95eaf5c28e25da682a61190e12ad6758a938", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-03-03T21:47:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-03T21:47:56.000Z", "max_forks_repo_path": "13_linear_algebra/13_SVD-Students-1.ipynb", "max_forks_repo_name": "Py4Phy/PHY432-resources", "max_forks_repo_head_hexsha": "c26d95eaf5c28e25da682a61190e12ad6758a938", "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.3917410714, "max_line_length": 258, "alphanum_fraction": 0.493891558, "converted": true, "num_tokens": 3951, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422199928904, "lm_q2_score": 0.9099070084811306, "lm_q1q2_score": 0.8654509720338323}} {"text": "```python\nimport sympy as sym\nfrom scipy import integrate\nimport numpy as np\nimport matplotlib.pyplot as plt\n```\n\n\n```python\nS, I, R = sym.Function(\"S\"), sym.Function(\"I\"), sym.Function(\"V\")\nN, mu, alpha, beta, t = sym.symbols(\"N, mu, alpha, beta, t\")\n```\n\n\n```python\neq1 = sym.Derivative(S(t), t) - (- alpha * S(t) * I(t) - mu * R(t))\neq2 = sym.Derivative(I(t), t) - (alpha * I(t) * S(t) / N - beta * I(t))\neq3 = sym.Derivative(R(t), t) - (beta * I(t) + mu * R(t))\n```\n\n\n```python\nsym.dsolve((eq1, eq2, eq3))\n```\n\nFurther investigation shows that an exact solution to this system of differential equations is difficult. Let us do this numerically:\n\n\n```python\ndef dx(x, t, alpha, beta, mu):\n\n return (- alpha * x[1] * x[0] - mu * x[0],\n alpha * x[1] * x[0] - beta * x[1],\n beta * x[1] + mu * x[0])\n```\n\n\n```python\nalpha = 1 / 1000 # Every 1000 interactions leads to infection\nbeta = 1 / 5 # take 5 time units to recover\nN = 10 ** 4 # Population of 10 thousand people\nmu = 0 # 0 vaccination percentage\n\nts = np.linspace(0, 10, 5000)\nxs = integrate.odeint(func=dx, y0=np.array([N - 1, 1, 0]), t=ts, args=(alpha, beta, mu))\nS, I, R = xs.T\nplt.figure()\nplt.plot(ts, S, label=\"Susceptibles\")\nplt.plot(ts, I, label=\"Infected\")\nplt.plot(ts, R, label=\"Recovered\")\nplt.legend()\nplt.title(f\"$\\max(I)={round(max(I))}$ ($\\\\alpha={alpha}$, $\\\\beta={beta}$, $\\mu={mu}$)\")\nplt.savefig(\"base_scenario.pdf\");\n```\n\n\n```python\nmu = 1 / 2 # Vaccinate half the population\nts = np.linspace(0, 10, 5000)\nxs = integrate.odeint(func=dx, y0=np.array([N - 1, 1, 0]), t=ts, args=(alpha, beta, mu))\nS, I, R = xs.T\nplt.figure()\nplt.plot(ts, S, label=\"Susceptibles\")\nplt.plot(ts, I, label=\"Infected\")\nplt.plot(ts, R, label=\"Recovered\")\nplt.legend()\nplt.title(f\"$\\max(I)={round(max(I))}$ ($\\\\alpha={alpha}$, $\\\\beta={beta}$, $\\mu={mu}$)\")\nplt.savefig(\"moderate_vaccination_rate.pdf\");\n```\n\n\n```python\nmu = 99 / 100 # Vaccinate 99% of the population\nts = np.linspace(0, 10, 5000)\nxs = integrate.odeint(func=dx, y0=np.array([N - 1, 1, 0]), t=ts, args=(alpha, beta, mu))\nS, I, R = xs.T\nplt.figure()\nplt.plot(ts, S, label=\"Susceptibles\")\nplt.plot(ts, I, label=\"Infected\")\nplt.plot(ts, R, label=\"Recovered\")\nplt.legend()\nplt.title(f\"$\\max(I)={round(max(I))}$ ($\\\\alpha={alpha}$, $\\\\beta={beta}$, $\\mu={mu}$)\")\nplt.savefig(\"high_vaccination_rate.pdf\");\n```\n\n\n```python\nvaccination_rates = np.linspace(0, 1, 500)\nmax_percent_of_infected = []\nfor mu in vaccination_rates:\n xs = integrate.odeint(func=dx, y0=np.array([N - 1, 1, 0]), t=ts, args=(alpha, beta, mu))\n S, I, R = xs.T\n max_percent_of_infected.append(max(I) / N)\nplt.figure()\nplt.plot(vaccination_rates, max_percent_of_infected)\nplt.xlabel(\"$\\mu$\")\nplt.ylabel(\"% of population infected\")\nplt.savefig(\"effect_of_vaccination_rate.pdf\");\n```\n", "meta": {"hexsha": "77b20038a74e92a0044d418e4df7516270f31fd5", "size": 100640, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "assets/rsc/sir/main.ipynb", "max_stars_repo_name": "geraintpalmer/cfm", "max_stars_repo_head_hexsha": "fa3f98cf45b225015f28be461e8ae661fa966b61", "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": "assets/rsc/sir/main.ipynb", "max_issues_repo_name": "geraintpalmer/cfm", "max_issues_repo_head_hexsha": "fa3f98cf45b225015f28be461e8ae661fa966b61", "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": "assets/rsc/sir/main.ipynb", "max_forks_repo_name": "geraintpalmer/cfm", "max_forks_repo_head_hexsha": "fa3f98cf45b225015f28be461e8ae661fa966b61", "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": 409.1056910569, "max_line_length": 27136, "alphanum_fraction": 0.935572337, "converted": true, "num_tokens": 957, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.956634196290671, "lm_q2_score": 0.9046505312448598, "lm_q1q2_score": 0.8654196338813551}} {"text": "# Gradient descent\n\n## Simple linear regression\n\nIn a previous notebook, we solved the problem of simple linear regression - finding a straight line that best fits a data set with two variables.\nIn that case, we were able to find the exact solution.\nIn this notebook, we'll use a common technique to approximate that solution.\n\nWhy would we want to approximate a solution when we can easily find an exact solution?\nWe don't - it's just that the technique we discuss here can also be used in situations where we can't find an exact solution or don't want to try, for whatever reason.\nThe approximation technique is called gradient descent.\n\n### Preliminaries\n\n\n```python\n# numpy efficiently deals with numerical multi-dimensional arrays.\nimport numpy as np\n\n# matplotlib is a plotting library, and pyplot is its easy-to-use module.\nimport matplotlib.pyplot as pl\n\n# This just sets the default plot size to be bigger.\npl.rcParams['figure.figsize'] = (16.0, 8.0)\n```\n\n### Simple linear regression model\nIn simple linear regression, we have some data points $(x_i, y_i)$, and we decide that they belong to a straight line with a little bit of error involved.\nStraight lines in two dimensions are of the form $y = mx + c$, and to fit a line to our data points we must find appropriate values for $m$ and $c$.\nNumpy has a function called `polyfit` that finds such values for us.\n\n\n```python\nw = np.arange(1.0, 16.0, 1.0)\nd = 5.0 * w + 10.0 + np.random.normal(0.0, 5.0, w.size)\n\nm, c = np.polyfit(w, d, 1)\nprint(\"Best fit is m = %f and c = %f\" % (m, c))\n\n# Plot the best fit line.\npl.plot(w, d, 'k.', label='Original data')\npl.plot(w, m * w + c, 'b-', label='Best fit: $%0.1f x + %0.1f$' % (m,c))\npl.legend()\npl.show()\n```\n\n### Gradient descent\nIn gradient descent, we select a random guess of a parameter and iteratively improve that guess.\nFor instance, we might pick $1.0$ as our initial guess for $m$ and then create a `for` loop to iteratively improve the value of $m$.\nThe way we improve $m$ is to first take the partial derivative of our cost function with respect to $m$.\n\n### Cost function\nRecall that our cost function for simple linear regression is:\n\n$$\nCost(m, c) = \\sum_i (y_i - mx_i - c)^2\n$$\n\n### Calculate the partial derivatives\nWe calculate the partial derivative of $Cost$ with respect to $m$ while treating $c$ as a constant.\nNote that the $x_i$ and $y_i$ values are all just constants.\nWe'll also calculate the partial derivative with respect to $c$ here.\n\n$$\n\\begin{align}\nCost(m, c) &= \\sum_i (y_i - mx_i - c)^2 \\\\[1cm]\n\\frac{\\partial Cost}{\\partial m} &= \\sum 2(y_i - m x_i -c)(-x_i) \\\\\n &= -2 \\sum x_i (y_i - m x_i -c) \\\\[0.5cm]\n\\frac{\\partial Cost}{\\partial c} & = \\sum 2(y_i - m x_i -c)(-1) \\\\\n & = -2 \\sum (y_i - m x_i -c) \\\\\n\\end{align}\n$$\n\n### Code the partial derivatives\nOnce we've calculated the partial derivatives, we'll code them up in python.\nHere we create two functions, each taking four parameters.\nThe first two parameters are arrays with our $x_i$ and $y_i$ data set values.\nThe second two are our current guesses for $m$ and $c$.\n\n\n```python\ndef grad_m(x, y, m, c):\n return -2.0 * np.sum(x * (y - m * x - c))\n```\n\n\n```python\ndef grad_c(x, y, m , c):\n return -2.0 * np.sum(y - m * x - c)\n```\n\n### Iterate\nNow we can run our gradient descent algorithm.\nFor $m$, we keep replacing its value with $m - \\eta grad\\_m(x, y, m, c)$ until it doesn't change.\nFor $c$, we keep replacing its value with $c - \\eta grad\\_c(x, y, m, c)$ until it doesn't change.\n\nWhat is $\\eta$? It is called the learning rate and we set it to a small value relative to the data points.\n\nYou can see on each iteration, $m$ and $c$ are getting closer to their true values.\n\n\n```python\neta = 0.0001\nm, c = 1.0, 1.0\ndelta = 0.0000001\n\nmold, cold = m - 1.0, c - 1.0\ni = 0\nwhile abs(mold - m) > delta and abs(cold - c) > delta:\n mold, cold = m, c\n m = mold - eta * grad_m(w, d, mold, cold)\n c = cold - eta * grad_c(w, d, mold, cold)\n\n i = i + 1\n if i % 1000 == 0:\n print(\"m: %20.16f c: %20.16f\" % (m, c))\n```\n\n m: 5.7149506777702488 c: 4.5518695120877757\n m: 5.5629397868829846 c: 6.1183980049248472\n m: 5.4852588608786546 c: 6.9189286986499470\n m: 5.4455621902673004 c: 7.3280175818245992\n m: 5.4252763139437015 c: 7.5370710455442040\n m: 5.4149097826482908 c: 7.6439019874021357\n m: 5.4096122559659570 c: 7.6984949605832087\n m: 5.4069051027099357 c: 7.7263931768575951\n m: 5.4055216875445105 c: 7.7406497821666767\n m: 5.4048147318094859 c: 7.7479352226744274\n m: 5.4044534617990276 c: 7.7516582438453998\n m: 5.4042688448364773 c: 7.7535607899748742\n\n\n## Newton's method for square roots\nNewton's method for square roots is a method for approximating the square root of a number $x$.\nWe begin with an initial guess $z_0$ of the square root - it doesn't have to be particularly good.\nWe then apply the following calculation repeatedly, to calculate $z_1$, then $z_2$, and so on:\n\n$$\nz_{i+1} = z_i - \\frac{z_i^2 - x}{2z_i}\n$$\n\n### Coding the calculation\nWe can create a function that calculates the next value of $z$ based on the current value of $z$ as follows.\n\n\n```python\ndef next_z(x, z):\n return z - (z**2 - x) / (2 * z)\n```\n\n### Calculating the square root of $x$\nSuppose we want to calculate the square root of $x$.\nWe start with a random guess for the square root, $z_0$.\nWe then apply the `next_z` function repeatedly until the value of $z$ stops changing.\nLet's create a function to do this.\nWe'll include the next_z function inside the `newtsqrt` function to make it one all-inclusive package.\n\n\n```python\ndef newtsqrt(x):\n next_z = lambda x, z: z - (z**2 - x) / (2 * z)\n z = 2.0\n n = next_z(x, z)\n \n while z != n:\n z, n = n, next_z(x, n)\n print(z)\n \n return z\n\nnewtsqrt(11)\n```\n\n 3.75\n 3.341666666666667\n 3.316718620116376\n 3.3166247916826186\n 3.3166247903554\n\n\n\n\n\n 3.3166247903554\n\n\n\n### Comparison with the standard library\nWe can compare our square root method return value to the value calculated by Python's `math` standard library package. It has a `sqrt` function.\n\n\n```python\nimport math\nmath.sqrt(11)\n```\n\n\n\n\n 3.3166247903554\n\n\n\n### Being careful\nDue to the complexities of floating point numbers, the `nextsqrt` function could get into an infinite loop.\nFor instance, calculating the square root of 10 gives an infinite loop.\n\n\n```python\n# Uncommenting will result in infinite loop.\n# newtsqrt(10)\n```\n\nTo counteract this problem, the condition of the loop is better written as:\n```python\nabs(z - n) > 0.001\n```\n\n## Gradient descent for square roots\nNewton's method for square roots is efficient, but we can also use gradient descent to approximate the square root of a real number $x$.\nHere, we use the following cost function.\n\n$$\nCost(z \\mid x) = (x - z^2)^2\n$$\n\n### Example value\nLet's use it to calculate the square root of 20, i.e. $x = 20$.\nThen the cost function is:\n\n$$\nCost(z \\mid x=20) = (20 - z^2)^2\n$$\n\nOur goal is to find the $z$ that minimises this.\n\n### Plotting the cost function\nLet's plot the cost function.\nGiven that we know the best $z$ will be between $4$ and $5$, we'll let $z$ range over 0 to 10.\n\n\n```python\ni = np.linspace(0.0, 10.0, 1000)\nj = (20.0 - i**2)**2\n\npl.plot(i, j, 'k-', label='$(20-z^2)^2$')\npl.legend()\npl.show()\n```\n\n### The derivative\nLooks like there's a low point at about $4.5$.\nLet's take the derivative of the cost function with respect to $z$.\n\n$$\n\\begin{align}\nCost(z) &= ( 20.0 - z^2 )^2 \\\\\n\\Rightarrow \\frac{\\partial Cost}{\\partial z} &= 2(20.0 - z^2)(-2z) \\\\\n &= 4z(z^2 - 20) \\\\\n &= 4z^3 - 80z\n\\end{align}\n$$\n\nThe derivative tells us what the slope of the tangent to the curve is at any point on the cost function.\nWhat does that mean?\nIt means that if we pick a value of $z$, e.g. $8.0$, that the derivative tells us that a line going through the point $(8.0, (20.0 - (8.0)^2)^2)$ with the slope $4(8.0)^3 - 80(8.0)$ perfectly touches the graph above.\nLet's plot that.\n\nWhen you simply, the point $(8.0, (20.0 - (8.0)^2)^2)$ becomes $(8,1936)$.\nThe slope is $4(8.0)^3 - 80(8.0)$ which when simplified becomes $1408$.\nSo, the claim is that the line with slope $1408$ going through the point $(8,1936)$ touches the graph.\nTo calculate the equation of the line, we'll use $(y - y_1) = m(x - x_1)$:\n\n$$\ny - 1936 = 1408(x - 8) \\\\\n\\Rightarrow y = 1408x - 11264 + 1936 \\\\\n\\Rightarrow y = 1408x - 9328\n$$\n\nLet's plot that line and the cost function together.\n\n\n```python\ni = np.linspace(0.0, 10.0, 1000)\nj = (20.0 - i**2)**2\nk = 1408 * i - 9328\n\npl.plot(i, j, 'k-', label='$(20-z^2)^2$')\npl.plot(i, k, 'b-', label='$1408z - 9328$')\npl.legend()\npl.show()\n```\n\n### Why do we care about the slope?\nIt's a bit hard to see, but the blue line is perfectly touching the curve.\nWe care about this because the slope of the blue line tells us in which way to change $z$ in order to make the cost less.\nIf we increase $z$ the cost goes up.\nIf we decrease it the cost goes down.\n\n### Gradient descent\nLet's use the gradient descent algorithm to calculate the best $z$.\nWe'll start with the guess $z=8$, and then use the derivative to move $z$ ever so slightly in the direction that decreases the cost.\nBy ever so slightly, we mean $0.001$ times the slope:\n\n$$\n\\begin{align}\nz_{i+1} &= z_i - \\eta \\frac{\\partial Cost}{\\partial z} \\\\\n &= z_i - (0.001) (4 z_i^3 - 80 z_i)\n\\end{align}\n$$\n\nSo, for our initial guess $z_0 = 8.0$ we get:\n\n$$\n\\begin{align}\nz_1 &= 8.0 - (0.001) (4 (8.0)^3 - 80 (8.0)) \\\\\n &= 8.0 - 1.408 = 6.592\n\\end{align}\n$$\n\nLet's code it up.\n\n\n```python\ndef next_z(z, x, eta=0.001):\n return z - eta * (4.0 * z**3 - 80 * z)\n\ndef sqrt_grad_desc(x, z, verbose=False):\n while abs(z - next_z(z, x)) > 0.001:\n if verbose:\n print(\"Current: %14.8f\\tNext: %14.8f\" % (z, next_z(z, x)))\n z = next_z(z, x)\n return z\n\nans =sqrt_grad_desc(20.0, 8.0, True)\nprint(\"Square root:\", ans, \"\\tSquared:\", ans**2)\n```\n\n Current: 8.00000000\tNext: 6.59200000\n Current: 6.59200000\tNext: 5.97355269\n Current: 5.97355269\tNext: 5.59881186\n Current: 5.59881186\tNext: 5.34469983\n Current: 5.34469983\tNext: 5.16157297\n Current: 5.16157297\tNext: 5.02444369\n Current: 5.02444369\tNext: 4.91903017\n Current: 4.91903017\tNext: 4.83645229\n Current: 4.83645229\tNext: 4.77084541\n Current: 4.77084541\tNext: 4.71815685\n Current: 4.71815685\tNext: 4.67548576\n Current: 4.67548576\tNext: 4.64069702\n Current: 4.64069702\tNext: 4.61218330\n Current: 4.61218330\tNext: 4.58871218\n Current: 4.58871218\tNext: 4.56932433\n Current: 4.56932433\tNext: 4.55326362\n Current: 4.55326362\tNext: 4.53992784\n Current: 4.53992784\tNext: 4.52883326\n Current: 4.52883326\tNext: 4.51958845\n Current: 4.51958845\tNext: 4.51187478\n Current: 4.51187478\tNext: 4.50543157\n Current: 4.50543157\tNext: 4.50004463\n Current: 4.50004463\tNext: 4.49553736\n Current: 4.49553736\tNext: 4.49176369\n Current: 4.49176369\tNext: 4.48860255\n Current: 4.48860255\tNext: 4.48595333\n Current: 4.48595333\tNext: 4.48373229\n Current: 4.48373229\tNext: 4.48186965\n Current: 4.48186965\tNext: 4.48030717\n Current: 4.48030717\tNext: 4.47899619\n Current: 4.47899619\tNext: 4.47789603\n Square root: 4.477896027970839 \tSquared: 20.05155283731702\n\n\n### A question\nLet's try some other initial guesses: 4.0, 1.0 and -1.0.\nCan you explain the square root returned with -1.0?\n\n\n```python\nprint(\"With initial guess %6.2f: %10.6f\" % (4.0, sqrt_grad_desc(20.0, 4.0, False)))\nprint(\"With initial guess %6.2f: %10.6f\" % (1.0, sqrt_grad_desc(20.0, 1.0, False)))\nprint(\"With initial guess %6.2f: %10.6f\" % (-1.0, sqrt_grad_desc(20.0, -1.0, False)))\n```\n\n With initial guess 4.00: 4.465951\n With initial guess 1.00: 4.465963\n With initial guess -1.00: -4.465963\n\n\n### End\n", "meta": {"hexsha": "f0c2d20fc1537019ec6b3e812093d08cea42499e", "size": 66582, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "gradient-descent.ipynb", "max_stars_repo_name": "sean-meade/jupyter-teaching-notebooks", "max_stars_repo_head_hexsha": "2f2a2bf6925fba479d1a73481122faebd201bdba", "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": "gradient-descent.ipynb", "max_issues_repo_name": "sean-meade/jupyter-teaching-notebooks", "max_issues_repo_head_hexsha": "2f2a2bf6925fba479d1a73481122faebd201bdba", "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": "gradient-descent.ipynb", "max_forks_repo_name": "sean-meade/jupyter-teaching-notebooks", "max_forks_repo_head_hexsha": "2f2a2bf6925fba479d1a73481122faebd201bdba", "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": 100.4253393665, "max_line_length": 17800, "alphanum_fraction": 0.8347000691, "converted": true, "num_tokens": 4165, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012701768145, "lm_q2_score": 0.9149009538328171, "lm_q1q2_score": 0.8653144842210575}} {"text": "## Task 01: \nUse the Multi Segment Simpsons 1/3 rule for finding Integral of the following function within the closed interval of $[0,1]$ and Plot the Relative Absolute Error for the different number of segments. The the integrad is as follows: \n$$ f(x) = 15\\sqrt{x^{3}} + 8\\sqrt[\\leftroot{-1}\\uproot{2}\\scriptstyle 3]{x^{2}} + x $$\n\n\n\n```\nfrom sympy import sympify, symbols, integrate\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n%matplotlib inline\n \n\nx = symbols('x')\n# original simpsons 1/3 method\ndef simpsons_one_third(f= None, a = 0, b = 0): \n #Fixing the values of X\n X = np.array([[a,(a+b)/2,b]]).T\n #Fixing the values of Y\n Y = np.vectorize(lambda t: f.subs(x,t))(X)\n #Taking the powers of X\n X = np.concatenate((X**0,X**1,X**2),axis = 1)\n #Solving for A\n A = np.linalg.inv(X)@Y\n #Substituted values of X after integration stored in b_a\n b_a = np.array([(b-a),(b**2-a**2)/2,(b**3-a**3)/3])\n result = b_a@A\n return float(result)\n\ndef simpsons_three_eight(f= None, a = 0, b = 0):\n #setting the value of h\n h = (b-a)/3\n #Fixing the values of X\n X = np.array([[a+i*h for i in range(3+1)]]).T\n #Fixing the values of Y\n Y = np.vectorize(lambda t: f.subs(x,t))(X)\n #Taking the powers of X\n X = np.concatenate(tuple([X**i for i in range(4)]),axis = 1)\n #Solving for A\n A = np.linalg.inv(X)@Y\n #Substituted values of X after integration stored in b_a\n b_a = np.array([(b**i-a**i)/i for i in range(1,5)])\n result = b_a@A\n return float(result)\n\n# multisegment simpsons 1/3 method\ndef multi_segment_simpsons_one_third(f, a=0, b=0, n=2, verbose = False):\n n = n//2\n h = (b-a)/n\n X = [a+i*h for i in range(n+1)]\n result = 0\n for i in range(n):\n result += simpsons_one_third(f,X[i],X[i+1])\n return result \n\n# multisegment simpsons 3/8 method\ndef multi_segment_simpsons_three_eight(f, a=0, b=0, n=3, verbose = False):\n n = n//3\n h = (b-a)/n\n X = [a+i*h for i in range(n+1)]\n result = 0\n for i in range(n):\n result += simpsons_three_eight(f,X[i],X[i+1])\n return result \n\ndef combined_simpsons(f, a=0, b=0, n=5, verbose = False):\n n = n//5\n h = (b-a)/n\n X = [a+i*h for i in range(n+1)]\n result = 0\n for i in range(n):\n s = (X[i+1]-X[i])/5*2\n result += simpsons_one_third(f,X[i],X[i]+s)\n result += simpsons_three_eight(f,X[i]+s,X[i+1])\n return result \n```\n\n\n```\ndef simpsons_13(f= None, a = 0, b = 0): \n #Fixing the values of X\n X = np.array([[a,(a+b)/2,b]]).T\n #Fixing the values of Y\n Y = np.vectorize(lambda t: f.subs(x,t))(X)\n h = (b-a)/2\n result = h/3 *(Y[0]+4*Y[1]+Y[2])\n return float(result)\n\ndef simpsons_38(f= None, a = 0, b = 0):\n #setting the value of h\n h = (b-a)/3\n #Fixing the values of X\n X = np.array([[a+i*h for i in range(3+1)]]).T\n #Fixing the values of Y\n Y = np.vectorize(lambda t: f.subs(x,t))(X)\n result = h*3/8 * (Y[0]+3*Y[1]+3*Y[2]+Y[3])\n return float(result)\n\ndef trap(f= None, a = 0, b = 0):\n fa = f.subs(x,a)\n fb = f.subs(x,b)\n result = (b-a)/2*(fa+fb)\n return float(result)\n```\n\n\n```\nf = '-9.1688*10**-6*x**3+2.7961*10**-3*x**2-2.8487*10**-1*x+9.6778'\n[a,b] = [0,100] \nf = sympify(f)\nprint(f'Numerical Prediction with simpsons 1/3 rule: {simpsons_13(f, a= a, b = b)}')\n```\n\n Numerical Prediction with simpsons 1/3 rule: 246.24333333333337\n\n\n# Input Parameters\n\n\n```\n# Testing Stub\nf = '15*(x^(1.5)) + 8*(x ^(0.6666667)) + x'\n[a,b] = [0,1] \nf = sympify(f)\nprint(f'Given Integrad: {f}')\nintegral_f = integrate(f, x)\nprint(f'Original Integration: {integral_f}')\noriginal_value = integral_f.subs(x, 1)- integral_f.subs(x, 0)\nprint('Original Result:', original_value) \nprint(f'Numerical Prediction with simpsons 1/3 rule: {simpsons_one_third(f, a= 0, b = 1)}')\nprint(f'Numerical Prediction with multiple segment simpsons 1/3 rule: {multi_segment_simpsons_one_third(f, a= 0, b = 1, n= 16, verbose = False)}')\nprint(f'Numerical Prediction with simpsons 3/8 rule: {simpsons_three_eight(f, a= 0, b = 1)}')\nprint(f'Numerical Prediction with multiple segment simpsons 3/8 rule: {multi_segment_simpsons_three_eight(f, a= 0, b = 1, n= 15, verbose = False)}')\nprint(f'Numerical Prediction with combined simpsons rule: {combined_simpsons(f, a= 0, b = 1, n= 15, verbose = False)}')\n\n```\n\n# Error Calculation:\n\n\n```\nerrors_one_third = []\nerrors_three_eight = []\nerrors_combined = []\nn_value_one_third = []\nn_value_three_eight = []\nn_value_combined = []\nfor i in range(2, 61, 2):\n errors_one_third.append((original_value - multi_segment_simpsons_one_third(f, a= 0, b = 1, n= i, verbose = False))/original_value*100)\n n_value_one_third.append(i)\n\nfor i in range(3, 61, 3):\n errors_three_eight.append((original_value - multi_segment_simpsons_three_eight(f, a= 0, b = 1, n= i, verbose = False))/original_value*100)\n n_value_three_eight.append(i)\n\nfor i in range(5, 61, 5):\n errors_combined.append((original_value - combined_simpsons(f, a= 0, b = 1, n= i, verbose = False))/original_value*100)\n n_value_combined.append(i)\n\n\n```\n\n# Error Plotting\n\n\n```\nplt.Figure(facecolor='black', linewidth=2)\nplt.rcParams[\"figure.figsize\"] = (20,15)\n# plt.plot(n_value, errors, 'r-*', markercolor = 'b')\n#plt.plot(n_value, errors, color='red', linestyle='dashed', marker='*', markerfacecolor='blue', markersize=10)\nplt.plot(n_value_one_third, errors_one_third, \"k--\", label=\"multiple segment simpsons 1/3 rule\",marker='*',color='red')\nplt.plot(n_value_three_eight, errors_three_eight, \"k:\", label=\"multiple segment simpsons 3/8 rule\",marker='.',color='green')\nplt.plot(n_value_combined, errors_combined, \"k\", label=\"combined simpsons rule\",marker='+',color='blue')\nplt.grid(axis = 'both')\nplt.xlabel('Intercepts: (n)')\nplt.ylabel('Relative Approximate Error')\nplt.title('Error Analysis of Simpsons Methods')\nplt.legend(loc=\"upper right\", shadow=True, fontsize=\"large\")\nplt.show()\n```\n\n\n```\nf = '15*(x^(1.5)) + 8*(x ^(0.6666667)) + x'\n\n```\n", "meta": {"hexsha": "432a321d24acb7106710c6ff3874c3f8940045cf", "size": 149956, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "NUM/lab4/Multi_segment_Simpsons_1_3_and_3_8_Rule.ipynb", "max_stars_repo_name": "5AF1/LabWorksML", "max_stars_repo_head_hexsha": "ddd702678aad1f62ce25b1d971ea1fc666c24f9d", "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": "NUM/lab4/Multi_segment_Simpsons_1_3_and_3_8_Rule.ipynb", "max_issues_repo_name": "5AF1/LabWorksML", "max_issues_repo_head_hexsha": "ddd702678aad1f62ce25b1d971ea1fc666c24f9d", "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": "NUM/lab4/Multi_segment_Simpsons_1_3_and_3_8_Rule.ipynb", "max_forks_repo_name": "5AF1/LabWorksML", "max_forks_repo_head_hexsha": "ddd702678aad1f62ce25b1d971ea1fc666c24f9d", "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": 493.2763157895, "max_line_length": 73641, "alphanum_fraction": 0.7872109152, "converted": true, "num_tokens": 2051, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009503523291, "lm_q2_score": 0.945801271704518, "lm_q1q2_score": 0.865314482326905}} {"text": "# Excercises : Finite-difference basics\n\n\n\n\n```python\n%matplotlib notebook\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nsns.set()\n```\n\n## Create a numpy array representing a one-dimensional mesh\n\n\n```python\n# Create a uniform mesh for the domain [-1,1]\n# x = \n```\n\n## Discretize a function on the mesh\n\nLet's start with a very simple function\n\n\\begin{equation}\nf(x) = x\n\\end{equation}\n\nWe know the function, $f(x)$, is continuous over the entire domain, $(-\\infty, \\infty)$. Using a numpy array, how do we define this function on the discrete mesh we created in the previous step?\n\n\n```python\n#f =\n```\n\n\n```python\n# Let's plot the function\nfig, ax = plt.subplots(nrows=1, ncols=1, figsize=(9, 6))\n\nline = ax.plot(f, x, lw=2, color='b', label=r'$f(x) = x')\n\nax.set_xlim((0.0, 1.0))\n\nax.set_title(r'Plot of the function $f(x)$', fontsize=15) \nax.legend(loc=4, fontsize=15)\nax.set_xlabel(r'$x$', fontsize=15.0)\nax.set_ylabel(r'$f(x)$', fontsize=15.0) \n```\n\n## Change the number of points in the mesh\n\nOften we will want to study the behavior of a numerical method we different levels of refinement. For a uniform mesh, refinement simply means increasing the total number of discrete points (nodes) used to define the mesh of the computational domain. Good practice is to use three levels of successive refinement. We will define a base number of mesh points, $N$, and the a **coarse** mesh with half the number of points, and a **fine** mesh with double the number of points.\n\nTo simplify the notation, let's refer to these as $N_0$, $N_1$, and $N_2$\n\n\\begin{equation}\nN_\\textrm{coarse} = N_0 = \\frac{N}{2}\n\\end{equation}\n\n\\begin{equation}\nN_\\textrm{base} = N_1 = N\n\\end{equation}\n\n\\begin{equation}\nN_\\textrm{fine} = N_2 = 2 N\n\\end{equation}\n\n\n\n\n\n```python\n# Create three uniform meshs for the domain [-1,1]\n# - x_coarse = x_0\n# - x_base = x_1\n# - x_fine = x_2\n```\n\n## Discretize a function on each mesh\n\nLet's use a slightly more complex function, \n\n\\begin{equation}\nf(x) = x^2\n\\end{equation}\n\nRecall we are interested in how the derivatives of a function are computed on a discrete domain (mesh) using a finite-difference approximation. Since the derivative of $f(x) = x^2$, is easy to compute analytically, $f^{\\prime}(x) = x$, we can use it to confirm wether or not our finite-difference approximation is qualitiatively correct. \n\n\n```python\n# f_0 =\n# f_1 =\n# f_2 =\n```\n\n## Compute the finite-difference approximation of the first derivative\n\nCompute $f^{\\prime}(x)$ at each mesh point using the following finite-difference approximation for the first derivative:\n\n\\begin{equation}\n\\frac{\\textrm{d} f}{\\textrm{d} x} \\approx \\frac{ f(x_i + \\Delta x) - f(x_i) }{\\Delta x} = \\frac{f_{i+1} - f_i }{\\Delta x}\n\\end{equation}\n\nTo analyze how our approximations might change for different number of mesh points, compute the first derivative for each of the different size meshes.\n\n\n```python\n# dfdx_1 =\n# dfdx_2 = \n# dfdx_3 =\n```\n\n## How do we know our finite-difference approximations are accurate?\n\n\n```python\n\n```\n\n## Convert the finite-difference approximation into a matrix operator \n\nAs discussed during lecture, we can write the finite-difference approximations at each point in the mesh as a matrix operator, $\\mathbf{A}$. Consider the 1-D, advection equation, \n\n\\begin{equation}\n\\frac{\\partial u}{\\partial t} + a \\frac{\\partial u}{\\partial x} = 0\n\\end{equation}\n\nUsing the method of lines, we can write a numerical approximation to the 1-D, advection equation like\n\n\\begin{equation}\n\\frac{\\textrm{d} \\mathbf{u} }{\\textrm{d} t} = \\mathbf{A} \\mathbf{u}\n\\end{equation}\n\nwhere the vector $\\mathbf{u} = [u(x_0,t), u(x_1,t), \\dots, u(x_N,t)]$ where the matrix $\\mathbf{A}$ is \n\n\\begin{equation}\n\\mathbf{A} = -a \\mathcal{D}\n\\end{equation}\n\nwhere $\\mathcal{D}$ is the difference-operator, sometimes it is written as $\\delta_x$ or as $\\mathcal{D}_x$, where the subscript means the difference-operator is an approximation of the first-derivative with respect to $x$, $\\delta_{xx}$ would be an approximationof the second-derivative with respect to $x$.\n\nUsing the approximation of the first derivative, \n\n\\begin{equation}\n\\frac{\\textrm{d} u}{\\textrm{d} x} \\approx \\frac{ u(x_i + \\Delta x) - u(x_i) }{\\Delta x} = \\frac{u_{i+1} - u_i }{\\Delta x}\n\\end{equation}\n\nwhat is the matrix operator for the one-dimensional, advection equation. Assume the initial condition for $u(x,t)$ is given as\n\n\\begin{equation}\nu(x,0) = f(x)\n\\end{equation}\n\nwhere $f(x) = x^2$ \n\n\n\n```python\n# what is Dx? \n```\n\n## Compute the RHS using the matrix operator\n\nCompute $\\mathbf{A}\\mathbf{u}$. There are a few ways to do this, and which way is best really depends on the scale of the problem we are trying to solve. Recall that $\\mathbf{A}$ is a sparse matrix with most of the elements in the matrix being zero. Is there some pattern to the non-zero entries of $\\mathbf{A}$ we can use to design a more compact way to represesnting the matrix? What about the fact that for periodic boundaries, the matrix $\\mathbf{A}$ is circulant?\n\nThe answer to all of those questions is yes. There are ways to effeciently represent the sparse matrix $\\mathbf{A}$, and yes we should do this (if only because it real-world applications you must, and because it is good practice to write memory efficient programs). \n\n**But**, let's start with a naive implementation. Use $N=4$.\n\nHow do you know it is correct?\n\n\n```python\n# A = -a D\n# u = [u0, u1, u2, ..., uN]\n\n# Au = -a * dudx\n```\n\n## Can A be represented as a banded-matrix?\n\nA banded matrix is a matrix whose only non-zero elements are along the diagonals of the matrix. For non-periodic boundary conditions, the matrix $\\mathbf{A}$ is banded. (We can modify how we treat the periodicity of the domain if we want to use a periodic matrix, we just can not encode all that information into the matrix $\\mathbf{A}$.)\n\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "f016ac04dc467c2978ca1c50066f260d1167408b", "size": 9397, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Exercises/Exercise-1-FiniteDifference.ipynb", "max_stars_repo_name": "jcschulz/ae269", "max_stars_repo_head_hexsha": "5c467a6e70808bb00e27ffdb8bb0495e0c820ca0", "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/Exercise-1-FiniteDifference.ipynb", "max_issues_repo_name": "jcschulz/ae269", "max_issues_repo_head_hexsha": "5c467a6e70808bb00e27ffdb8bb0495e0c820ca0", "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/Exercise-1-FiniteDifference.ipynb", "max_forks_repo_name": "jcschulz/ae269", "max_forks_repo_head_hexsha": "5c467a6e70808bb00e27ffdb8bb0495e0c820ca0", "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.8098360656, "max_line_length": 483, "alphanum_fraction": 0.5705012238, "converted": true, "num_tokens": 1706, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850110816422, "lm_q2_score": 0.9241418152779357, "lm_q1q2_score": 0.865260129758511}} {"text": "# Solution {-}\n\nThe stationary process $X(t)$ has an autocorrelation function of the form:\n\n\\begin{equation}\n R_X(t) = \\sigma^2 e^{-\\beta|\\tau|}\n\\end{equation}\n\nAnother process $Y(t)$ is related to $X(t)$ by the deterministic equation:\n\n\\begin{equation}\n Y(t) = aX(t) + b\n\\end{equation}\n\n\n$X(t)$ is stationary, so Y(t) is also stationary.\n\n\\begin{align}\n R_Y(t) =& E[Y(t) \\cdot Y (t + \\tau)] \\\\\n =& E[(aX(t) + b)(aX(t + \\tau) + b)] \\\\\n =& E[(a^2 X(t)X(t + \\tau)] + E[abX(t)] + E[baX(t)] + E[b^2] \\\\\n =& a^2 R_X(t) + b^2 \\\\\n =& a^2 \\sigma^2 e^{-\\beta|\\tau|} + b^2 \\\\\n\\end{align}\n", "meta": {"hexsha": "9f2b713c348b8b2e7b318cb2763f9bf2626e8a61", "size": 1369, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Problem 2.12.ipynb", "max_stars_repo_name": "mfkiwl/GMPE340", "max_stars_repo_head_hexsha": "3602b8ba859a2c7db2cab96862472597dc1ac793", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-09-07T09:36:36.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-07T09:36:36.000Z", "max_issues_repo_path": "Problem 2.12.ipynb", "max_issues_repo_name": "mfkiwl/GMPE340", "max_issues_repo_head_hexsha": "3602b8ba859a2c7db2cab96862472597dc1ac793", "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": "Problem 2.12.ipynb", "max_forks_repo_name": "mfkiwl/GMPE340", "max_forks_repo_head_hexsha": "3602b8ba859a2c7db2cab96862472597dc1ac793", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-09-20T18:48:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-20T18:48:20.000Z", "avg_line_length": 24.4464285714, "max_line_length": 83, "alphanum_fraction": 0.449963477, "converted": true, "num_tokens": 232, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.966914019704466, "lm_q2_score": 0.8947894527758052, "lm_q1q2_score": 0.8651844665726133}} {"text": "```python\nimport numpy as np\nimport sympy as sp\nimport math\n\nimport yx_ODE as p1\nimport unstable_ODE as p2\n\nimport matplotlib.pyplot as plt\n\n# Needed only in Jupyter to render properly in-notebook\n%matplotlib inline\n```\n\n# Chinmai Raman\n\n## Homework 6\n\n## C.3 Solving an ODE Numerically and Symbolically\n\n$\\frac{dy}{dx} = \\frac{1}{2(y-1)}, y(0) = 1 + \\sqrt{\\epsilon}, x \\subset [0,4], \\epsilon = 10^{-3}$\n\nThe approximation of y for x = 4 using Euler's method given a step size of 1:\n\n\n```python\nprint p1.euler(1, 1 + np.sqrt(1e-3))[1][-1]\n```\n\n 16.9375021945\n\n\nThe approximation of y for x = 4 using Euler's method given a step size of 0.25:\n\n\n```python\nprint p1.euler(0.25, 1 + np.sqrt(1e-3))[1][-1]\n```\n\n 5.43162981571\n\n\nThe approximation of y for x = 4 using Euler's method given a step size of 0.01:\n\n\n```python\nprint p1.euler(0.01, 1 + np.sqrt(1e-3))[1][-1]\n```\n\n 3.01196145341\n\n\nThe exact solution to the differential equation can be calculated symbolically. The value of C1 depends on the epsilon value.\n\n\n```python\np1.sym_solve()\n```\n\n\n\n\n f(x) == sqrt(C1 + x) + 1\n\n\n\nThe graph below shows Euler's method implemented for a step size of 1 (red), 0.25 (green), and 0.01 (blue). It also shows the exact solution (yellow). The problem is hard to solve numerically because it requires an extremely large number of points to come even close to estimating the exact solution.\n\n\n```python\np1.graph_euler()\n```\n\n## C.4 Demonstrating instability of an ODE\n\n$u^` = \\alpha u, u(0) = u_0$\n\nThe graphs below show that $u_k = (1 + \\alpha \\Delta t)^k u_0$ and that the numerical solution of the above ODE problem will oscillate if $\\Delta t > \\frac{-1}{\\alpha}$\n\n$\\alpha = -1, \\Delta t = 1.1$\n\n\n```python\np2.graph(-1, 1, 1.1, 0, 20)\n```\n\n$\\alpha = -1, \\Delta t = 1.5$\n\n\n```python\np2.graph(-1, 1, 1.5, 0, 20)\n```\n\n$\\alpha = -1, \\Delta t = 1.9$\n\n\n```python\np2.graph(-1, 1, 1.9, 0, 120)\n```\n\n$\\alpha = -1, \\Delta t = 2.1$\n\n\n```python\np2.graph(-1, 1, 2.1, 0, 120)\n```\n\n$\\alpha = -1, \\Delta t = 1$\n\n\n```python\np2.graph(-1, 1, 1, 0, 120)\n```\n\nThese graphs show that as $ \\Delta t$ increases (when $\\frac{-1}{\\alpha} < \\Delta t < \\frac{-2}{\\alpha}$), the value of u as $k -> \\infty$ converges to 0, but at a decreasing rate and with oscillations that fall lower into the fourth quadrant. This is because the term $(1 + \\alpha \\Delta t)^k$ will converge to 0 when the value inside the parenthesis is a fraction. It follows that when the value inside the parenthesis is $>1$, the sequence will diverge, as is the case when $\\Delta t > \\frac{-2}{\\alpha}$\n", "meta": {"hexsha": "9b7640324d110de98ceccf6d098c027820e6192e", "size": 76679, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "hw6.ipynb", "max_stars_repo_name": "chapman-phys227-2016s/hw-6-ChinmaiRaman", "max_stars_repo_head_hexsha": "8e5312bf5475e6e6cee85697ec6a91e671587101", "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": "hw6.ipynb", "max_issues_repo_name": "chapman-phys227-2016s/hw-6-ChinmaiRaman", "max_issues_repo_head_hexsha": "8e5312bf5475e6e6cee85697ec6a91e671587101", "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": "hw6.ipynb", "max_forks_repo_name": "chapman-phys227-2016s/hw-6-ChinmaiRaman", "max_forks_repo_head_hexsha": "8e5312bf5475e6e6cee85697ec6a91e671587101", "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": 207.8021680217, "max_line_length": 17274, "alphanum_fraction": 0.9089711655, "converted": true, "num_tokens": 868, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768525822309, "lm_q2_score": 0.9161096198879968, "lm_q1q2_score": 0.8649694975261527}} {"text": "# Computing gradients in tensorflow\n\n## Partial derivatives using pure python\n\nLet's say we have a derivable function:\n\n\\begin{equation}\nf(x) = 2 x_1^2 + 3 x_1 x_2\n\\end{equation}\n\n\n```python\ndef f(x1, x2):\n return 2 * x1 ** 2 + 3 * x1 * x2\n```\n\nIt's easy to find analytically the derivative of this function:\n\n\\begin{align}\n\\frac{\\partial{f}}{\\partial x_1} & = 4x_1 + 3x_2\\\\\n\\frac{\\partial{f}}{\\partial x_2} & = 3x_1 \n\\end{align}\n\nSo, for the point $x=(2,1)$, the result will be $(11,6)$. To check that everything goes as expected, we can compute the partial derivatives with regard to both variables using the definition:\n\n\\begin{equation}\n\\frac{\\partial}{{\\partial x}}f \\left( x \\right) = \\mathop {\\lim }\\limits_{\\epsilon \\to 0} \\frac{{f\\left( {x + \\epsilon } \\right) - f\\left( x \\right)}}{\\epsilon }\n\\end{equation}\n\n\n```python\nx1, x2 = 2, 1\neps = 1e-04\n```\n\n\n```python\n(f(x1 + eps, x2) - f(x1, x2)) / (eps)\n```\n\n\n\n\n 11.000200000026439\n\n\n\n\n```python\n(f(x1, x2 + eps) - f(x1, x2)) / (eps)\n```\n\n\n\n\n 6.00000000000378\n\n\n\nGreat!\n\n## Partial derivatives using tensorflow\n\nWe will do the same, but this time we will use tensorlfow to calculate the results. It may not be as interesting, but it will certainly be more efficient.\n\n\n```python\nimport tensorflow as tf\n```\n\n\n```python\nx1, x2 = tf.Variable(2.), tf.Variable(1.)\n```\n\n\n```python\nwith tf.GradientTape() as tape:\n y = f(x1, x2)\ngradients = tape.gradient(y, [x1, x2])\n```\n\n\n```python\n[g.numpy() for g in gradients]\n```\n\n\n\n\n [11.0, 6.0]\n\n\n\nWithin the `tf.GradientTape` context, tensorflow will track each operation applied to any variable. But be careful! To save memory, tensorflow will remove the tape contents after calling the `.gradient()` method. To avoid this, you can explicitly indicate that you do not want them to disappear (with the `persistent=True` parameter of the `GradientTape`), but try not to do so if there is no good reason, or even remove it from memory once you've done with it.\n\nBy default, the tape will record all the operations involving variables (because de default value for the tape's `watch_accessed_variables` parameter is `True`). We can track the operations that involves a constant adding `tape.watch(my_constant)` at the begining of the context, or setting `watch_accessed_variables=False` and select the variables we want to track through the `watch` method. This is useful if we want to add information about the variation of the inputs in our loss function.\n\n## Higher order derivatives\n\nWe can even compute second (or higher) order derivatives by nesting tapes. For example:\n\n\n```python\ndef f(x):\n return 5*x**3\n```\n\nIn this case,\n\n\\begin{equation}\n\\frac{\\partial f}{\\partial x} = 15 x ^2 \\\\\n\\frac{\\partial^2 f}{\\partial x^2} = 30 x\n\\end{equation}\n\n\n```python\nx = tf.Variable(0.1)\nwith tf.GradientTape() as tape1:\n with tf.GradientTape() as tape2:\n y = f(x)\n dy_dx = tape2.gradient(y, x)\nd2y_dx2 = tape1.gradient(dy_dx, x)\n\nprint(f\"dy/dx at x={x.numpy():.2f}: {dy_dx.numpy():.2f}\")\nprint(f\"d2y/dx2 at x={x.numpy():.2f}: {d2y_dx2.numpy():.2f}\")\n```\n\n dy/dx at x=0.10: 0.15\n d2y/dx2 at x=0.10: 3.00\n\n\n## Derivatives of different variables\n\nIf we try to calculate the gradient of several variables separately, tensorlow will calculate the sum of the gradients.\n\n**Tip:** Until now we have only used the `.gradient()` method with variables or lists of variables for its two main parameters. However, it also accepts dictionaries.\n\n\n```python\nx = tf.Variable(2.0)\nwith tf.GradientTape(persistent=True) as tape:\n y0 = x**2\n y1 = -4 * x\n\nprint(tape.gradient({'y0': y0, 'y1': y1}, x).numpy())\nprint(tape.gradient(y0, x).numpy(), tape.gradient(y1, x).numpy())\n```\n\n 0.0\n 4.0 -4.0\n\n\nHowever, if we compute the gradients of a single variable, contaning several components (all of them affected by the same calculations), we will get the gradients of each component.\n\n\n```python\nx = tf.linspace(-1.0, 1.0, 3)\n\nwith tf.GradientTape() as tape:\n tape.watch(x) # x is a constant\n y = tf.nn.sigmoid(x)\n\ndy_dx = tape.gradient(y, x)\ndy_dx.numpy()\n```\n\n\n\n\n array([0.19661194, 0.25 , 0.19661193], dtype=float32)\n\n\n\n## Jacobian\n\nNow we know how to compute the derivatives of a single value regarding a set of variables. Let's see now how to compute the derivatives of a vector (two-dimensional tensor).\n\nIf you want to compute, for example, gradients for an array of losses, tensorflow will compute the gradients of the sum of all of them. To compute all the derivatives one step before, we will need to use the tape's `jacobian()` method.\n\n\n```python\ndef f(x):\n x1 = 2 * x[0] ** 2\n x2 = x[1] ** 3\n x3 = x[2] + x[1]\n return tf.stack([x1, x2, x3])\n```\n\n\\begin{equation}\n\\mathcal{J}_u(x_1, x_2, x_3) =\n\\begin{bmatrix}\n \\frac{\\partial u_1}{\\partial x_1} & \n \\frac{\\partial u_1}{\\partial x_2} & \n \\frac{\\partial u_1}{\\partial x_3} \\\\[1ex] % <-- 1ex more space between rows of matrix\n \\frac{\\partial u_2}{\\partial x_1} & \n \\frac{\\partial u_2}{\\partial x_2} & \n \\frac{\\partial u_2}{\\partial x_3} \\\\[1ex]\n \\frac{\\partial u_3}{\\partial x_1} & \n \\frac{\\partial u_3}{\\partial x_2} & \n \\frac{\\partial u_3}{\\partial x_3}\n\\end{bmatrix}\n\\end{equation}\n\n\n```python\nx = tf.Variable([1.0, 1.0, 1.0])\nwith tf.GradientTape() as tape:\n y = f(x)\ntape.jacobian(y, x)\n```\n\n\n\n\n \n\n\n\n## Derivatives involving matrix operations\n\nWe can also calculate the derivatives of any variable involved in matrix operations.\n\n\n```python\nW = tf.Variable(tf.random.normal((3, 1)), name='W')\nb = tf.Variable(tf.zeros(1, dtype=tf.float32), name='b')\nX = tf.constant([[1., 2., 3.], [4., 5., 6.]])\ny_true = tf.constant([[5.], [16.]])\n\nwith tf.GradientTape(persistent=True) as tape:\n y = X @ W + b\n loss = tf.reduce_mean((y - y_true)**2)\n```\n\n\n```python\ndloss_dW, dloss_db = tape.gradient(loss, [W, b])\nprint(dloss_dW.numpy(), dloss_db.numpy())\n```\n\n [[ -79.16642]\n [-104.15854]\n [-129.15067]] [-24.992123]\n\n\nThis is especially useful when working with deep learning models, and of course, we can do exacly the same with the variable inside a keras layer/model:\n\n\n```python\nlayer = tf.keras.layers.Dense(1, activation='relu')\n\nwith tf.GradientTape() as tape:\n # Forward pass\n y = layer(X)\n loss = tf.reduce_mean((y - y_true)**2)\n\n# Calculate gradients with respect to every trainable variable\ngrad = tape.gradient(loss, layer.trainable_variables)\n```\n\n\n```python\n[g.numpy() for g in grad]\n```\n\n\n\n\n [array([[-41.165585],\n [-52.70707 ],\n [-64.24856 ]], dtype=float32),\n array([-11.541485], dtype=float32)]\n\n\n", "meta": {"hexsha": "07d39d3536248fdaac1376c0c087ff1ed1843991", "size": 13329, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/06 - Gradients.ipynb", "max_stars_repo_name": "ivanCanaveral/tensorflow-tips", "max_stars_repo_head_hexsha": "1f97380e392bdf897330d0ae085ca2df9dab0694", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-08-10T12:35:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-10T12:35:21.000Z", "max_issues_repo_path": "notebooks/06 - Gradients.ipynb", "max_issues_repo_name": "ivanCanaveral/tensorflow-tips", "max_issues_repo_head_hexsha": "1f97380e392bdf897330d0ae085ca2df9dab0694", "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/06 - Gradients.ipynb", "max_forks_repo_name": "ivanCanaveral/tensorflow-tips", "max_forks_repo_head_hexsha": "1f97380e392bdf897330d0ae085ca2df9dab0694", "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.9730215827, "max_line_length": 500, "alphanum_fraction": 0.5187185835, "converted": true, "num_tokens": 2079, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750440288019, "lm_q2_score": 0.9073122301325987, "lm_q1q2_score": 0.8649181061275234}} {"text": "# Setup notebook\n\n\n```python\nimport numpy as np\nimport scipy as sp\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\nimport sympy as sm\nfrom scipy.integrate import trapz\nimport time\nimport mpmath\nfrom scipy.integrate import simps\n```\n\n# Trapezoidal Method\n\n

$\\int_a^b f(x) dx \\approx 0.5 * (f(a)+f(b)) * (a-b)$\n\n\n\n```python\nfx = lambda x: np.sin(x) + x**0.5\nx = np.linspace(0,20,101)\ny = fx(x)\n\nplt.figure()\nplt.plot(x,y,'b-')\nplt.title('function to be integrated')\nplt.xlabel('x')\nplt.ylabel('y')\nplt.show()\n```\n\n\n```python\n#use step size of 2.5\nx_node = np.array([i*2.5 for i in range(0,int(20//2.5) + 1)])\n```\n\n\n```python\ny_node = fx(x_node)\n```\n\n\n```python\nx_base = np.zeros(x_node.shape)\n```\n\n\n```python\n#create coordinate of vertical lines for plotting\nv_line_start = [(i,j) for i,j in zip(x_node,x_base)]\nv_line_start\n```\n\n\n\n\n [(0.0, 0.0),\n (2.5, 0.0),\n (5.0, 0.0),\n (7.5, 0.0),\n (10.0, 0.0),\n (12.5, 0.0),\n (15.0, 0.0),\n (17.5, 0.0),\n (20.0, 0.0)]\n\n\n\n\n```python\nv_line_end = [(i,j) for i,j in zip(x_node,y_node)]\nv_line_end\n```\n\n\n\n\n [(0.0, 0.0),\n (2.5, 2.1796109741881464),\n (5.0, 1.2771437028366512),\n (7.5, 3.6766127643005695),\n (10.0, 2.6182565492790095),\n (12.5, 3.469212008581537),\n (15.0, 4.5232711863645338),\n (17.5, 3.2076741272022202),\n (20.0, 5.3850812057272073)]\n\n\n\n\n```python\nmpl.rc('font',size = 15)\nplt.figure(figsize = (8,6))\nplt.plot(x_node,y_node,'-r')\nplt.fill_between(x_node,y_node,color = 'red', alpha = 0.1,\n label = 'Trapezoidal integration')\nfor line in range(len(v_line_end)):\n x_line = [v_line_start[line][0],v_line_end[line][0]]\n y_line = [v_line_start[line][1],v_line_end[line][1]]\n plt.plot(x_line,y_line, '-r')\nplt.plot(x,y,'b-', label = 'Function to be integrated')\nplt.xlabel('x')\nplt.ylabel('y')\nplt.legend(bbox_to_anchor=(1, 1))\nplt.title('Trapezoidal Integration Approximation')\nplt.show()\n```\n\n## Trapezoidal Manual Integration\n\n\n```python\ndef T_man1():\n # using list comprehension\n x_node = np.array([i*2.5 for i in range(0,int(20//2.5) + 1)])\n y_node = fx(x_node)\n area_section = [(x_node[i+1]-x_node[i]) * 0.5 * (y_node[i+1] + y_node[i])\n for i in range(x_node.shape[0]-1)]\n area_total = sum(area_section)\n print(area_total)\nT_man1()\n```\n\n 59.110804789\n\n\n\n```python\ndef T_man2():\n # using for-loop\n area_total = 0\n for i in range(x_node.shape[0] - 1):\n area_total += 0.5 * (y_node[i] + y_node[i+1]) * (x_node[i+1] - x_node[i])\n print(area_total)\nT_man2()\n```\n\n 59.110804789\n\n\n\n```python\ndef T_man3():\n # using just numpy\n area = ((x_node[1:] - x_node[0:-1]) * (y_node[1:] + y_node[0:-1]) * 0.5).sum()\n print(area)\nT_man3()\n```\n\n 59.110804789\n\n\n## Trapezoidal with Scipy (automatic)\n\n\n```python\n#with input of x_node and y_node\ntrapz(y_node,x_node)\n```\n\n\n\n\n 59.110804789040685\n\n\n\n\n```python\n#with input of y and spacing\ntrapz(y_node,dx = 2.5)\n```\n\n\n\n\n 59.110804789040685\n\n\n\n\n```python\n#with finer discretization\nfor i in range(1,8):\n ans = trapz(fx(np.linspace(0,20,10**i)),np.linspace(0,20,10**i))\n print('i = {:}, integration result = {:}'.format(i,ans))\n```\n\n i = 1, integration result = 59.31141084919463\n i = 2, integration result = 60.19988674564448\n i = 3, integration result = 60.219792428047285\n i = 4, integration result = 60.220378581412135\n i = 5, integration result = 60.220396748580725\n i = 6, integration result = 60.22039731957108\n i = 7, integration result = 60.22039733759288\n\n\n## Analytical Integration with Sympy\n\n\n```python\n#analytical solution\nxs = sm.symbols('x')\nEq = sm.sin(xs) + xs**0.5\nans_aly = sm.integrate(Eq,(xs,0,20))\nans_aly\n```\n\n\n\n\n -cos(20) + 60.6284793999944\n\n\n\n\n```python\nans_aly.evalf()\n```\n\n\n\n\n 60.2203973381810\n\n\n\n## Speed comparison\n\n\n```python\n#speed of scipy.integrate.trapz\n```\n\n\n```python\n%%timeit -n 300 -r 30\ntrapz(y_node,x_node)\n```\n\n 300 loops, best of 30: 8.83 µs per loop\n\n\n\n```python\nclass T_man3_obj():\n def __init__(self,x_node,y_node):\n self.x_node = x_node\n self.y_node = y_node\n def area(self):\n area = ((self.x_node[1:] - self.x_node[0:-1]) * \n (self.y_node[1:] + self.y_node[0:-1]) * 0.5).sum()\n return area\n```\n\n\n```python\nint_obj = T_man3_obj(x_node,y_node)\nint_obj.area()\n```\n\n\n\n\n 59.110804789040685\n\n\n\n\n```python\n#speed of manual integration with numpy array without printing and using object\n```\n\n\n```python\n%%timeit -n 300 -r 30\nint_obj = T_man3_obj(x_node,y_node)\nint_obj.area()\n```\n\n 300 loops, best of 30: 4.78 µs per loop\n\n\n\n```python\nt1 = time.monotonic()\nfor i in range(100000):\n trapz(y_node,x_node)\nt2 = time.monotonic()\ntime_trapz = t2-t1\ntime_trapz\n```\n\n\n\n\n 0.9482589669933077\n\n\n\n\n```python\nt1 = time.monotonic()\nfor i in range(100000):\n int_obj = T_man3_obj(x_node,y_node)\n int_obj.area()\nt2 = time.monotonic()\ntime_numpy_manual = t2-t1\ntime_numpy_manual\n```\n\n\n\n\n 0.5139754059782717\n\n\n\n\n```python\nprint(\"numpy manual method take {:.2f}%\".format(\n (time_trapz - time_numpy_manual)/time_numpy_manual*100)\n +\" of the time taken by scipy.integrate.trapz for this particular case\")\n```\n\n numpy manual method take 84.50% of the time taken by scipy.integrate.trapz for this particular case\n\n\n\n```python\n# What if we put scipy.integrate.trapz inside a class?\n# Will it be any faster?\n```\n\n\n```python\nclass T_scipy():\n def __init__(self,x_node,y_node):\n self.x_node = x_node\n self.y_node = y_node\n def area(self):\n area = trapz(self.y_node,self.x_node)\n return area \n```\n\n\n```python\nint_sp_obj = T_scipy(x_node,y_node)\nint_sp_obj.area()\n```\n\n\n\n\n 59.110804789040685\n\n\n\n\n```python\nt1 = time.monotonic()\nfor i in range(100000):\n int_sp_obj = T_scipy(x_node,y_node)\n int_sp_obj.area()\nt2 = time.monotonic()\nt2-t1\n```\n\n\n\n\n 1.0543863649945706\n\n\n\n\n```python\n#putting scipy.integrate.trapz in an object form does not make it any faster\n```\n\n# Trapezoidal Method (non-uniform discretization)\nDiscretize more when the function change fast\n\n\n```python\nfx2 = lambda x: x**(-x**0.5)*x + 0.1\nx2 = np.linspace(0,20,1000)\ny2 = fx2(x2)\n\nplt.figure()\nplt.plot(x2,y2)\nplt.show()\n```\n\n\n```python\n#use step size of 1\nx2_node = np.linspace(0,20,12)\ny2_node = fx2(x2_node)\nx2_base = np.zeros(x2_node.shape)\n\nv2_line_start = [(i,j) for i,j in zip(x2_node,x2_base)]\nv2_line_end = [(i,j) for i,j in zip(x2_node,y2_node)]\n\nmpl.rc('font',size = 15)\nplt.figure(figsize = (8,6))\nplt.plot(x2_node,y2_node,'-r')\nplt.fill_between(x2_node,y2_node,color = 'red', alpha = 0.1,\n label = 'Trapezoidal integration')\nfor line in range(len(v2_line_end)):\n x2_line = [v2_line_start[line][0],v2_line_end[line][0]]\n y2_line = [v2_line_start[line][1],v2_line_end[line][1]]\n plt.plot(x2_line,y2_line, '-r')\nplt.plot(x2,y2,'b-', label = 'Function to be integrated')\nplt.xlabel('x')\nplt.ylabel('y')\nplt.legend(bbox_to_anchor=(1, 1))\nplt.title('Trapezoidal Integration Approximation\\nnumber of node = 12')\nplt.show()\n```\n\n\n```python\nx2_node.shape\n```\n\n\n\n\n (12,)\n\n\n\n\n```python\nE2 = xs**(-xs**0.5)*xs + 0.1\nmpmath.quad(sm.lambdify('x',E2),[0,20])\n```\n\n\n\n\n mpf('4.952219274610087')\n\n\n\n\n```python\nprint(\"result from sm.integrate(E2,(xs,0,20)) is\")\nprint(\"1.0*(Integral(0.1, (x, 0, 20)) + Integral(1.0*x*x**(-x**0.5), (x, 0, 20)))\")\nprint(\"It took a while to do the \\\"calculation\\\" so the answer is just given\")\n```\n\n result from sm.integrate(E2,(xs,0,20)) is\n 1.0*(Integral(0.1, (x, 0, 20)) + Integral(1.0*x*x**(-x**0.5), (x, 0, 20)))\n It took a while to do the \"calculation\" so the answer is just given\n\n\n\n```python\nsp.integrate.quad(fx2,0,20,epsrel=1e-9)\n```\n\n\n\n\n (4.9522192746106555, 1.7676438091029922e-09)\n\n\n\n\n```python\nexc_ans = trapz(fx2(np.linspace(0,20,100000)),np.linspace(0,20,100000))\nexc_ans\n```\n\n\n\n\n 4.9522192711083974\n\n\n\n\n```python\n#Let's use 21 points with trapz\ntrapz(fx2(np.linspace(0,20,12)),np.linspace(0,20,12))\n```\n\n\n\n\n 4.3244008892861858\n\n\n\n\n```python\n#Let's use 21 points with trapz\n#This time discretize more when function change quick\nx_non_lin = np.r_[np.arange(0,1.6,1.6/4),np.linspace(1.6,8,6),np.array([10,20])]\nx_non_lin\n```\n\n\n\n\n array([ 0. , 0.4 , 0.8 , 1.2 , 1.6 , 2.88, 4.16, 5.44,\n 6.72, 8. , 10. , 20. ])\n\n\n\n\n```python\ny_non_lin = fx2(x_non_lin)\ny_non_lin\n```\n\n\n\n\n array([ 0.1 , 0.81406764, 1.07671743, 1.08274883, 0.98293017,\n 0.57838503, 0.32718818, 0.20468927, 0.14814852, 0.12232368,\n 0.10688212, 0.10003038])\n\n\n\n\n```python\nv2_line_start\n```\n\n\n\n\n [(0.0, 0.0),\n (1.8181818181818181, 0.0),\n (3.6363636363636362, 0.0),\n (5.4545454545454541, 0.0),\n (7.2727272727272725, 0.0),\n (9.0909090909090899, 0.0),\n (10.909090909090908, 0.0),\n (12.727272727272727, 0.0),\n (14.545454545454545, 0.0),\n (16.363636363636363, 0.0),\n (18.18181818181818, 0.0),\n (20.0, 0.0)]\n\n\n\n\n```python\nv2_line_end\n```\n\n\n\n\n [(0.0, 0.10000000000000001),\n (1.8181818181818181, 0.91197457846948538),\n (3.6363636363636362, 0.41011066570291044),\n (5.4545454545454541, 0.20376747996254155),\n (7.2727272727272725, 0.13450424209368694),\n (9.0909090909090899, 0.11170300823532486),\n (10.909090909090908, 0.10407460727896357),\n (12.727272727272727, 0.10145733189457681),\n (14.545454545454545, 0.10053488371899037),\n (16.363636363636363, 0.10020113802157354),\n (18.18181818181818, 0.10007736165847288),\n (20.0, 0.10003038414175187)]\n\n\n\n\n```python\n#use step size of 1\nx2_node = x_non_lin\ny2_node = y_non_lin\nx2_base = np.zeros(x2_node.shape)\n\nv2_line_start = [(i,j) for i,j in zip(x2_node,x2_base)]\nv2_line_end = [(i,j) for i,j in zip(x2_node,y2_node)]\n\nmpl.rc('font',size = 15)\nplt.figure(figsize = (8,6))\nplt.plot(x2_node,y2_node,'-r')\nplt.fill_between(x2_node,y2_node,color = 'red', alpha = 0.1,\n label = 'Trapezoidal integration')\nfor line in range(len(v2_line_end)):\n x2_line = [v2_line_start[line][0],v2_line_end[line][0]]\n y2_line = [v2_line_start[line][1],v2_line_end[line][1]]\n plt.plot(x2_line,y2_line, '-r')\nplt.plot(x2,y2,'b-', label = 'Function to be integrated')\nplt.xlabel('x')\nplt.ylabel('y')\nplt.legend(bbox_to_anchor=(1, 1))\nplt.title('Discretize more when a function changes quick\\nnumber of node = 12')\nplt.show()\n```\n\n\n```python\nx_non_lin.shape\n```\n\n\n\n\n (12,)\n\n\n\n\n```python\nans_non_lin = trapz(y_non_lin,x_non_lin)\nans_non_lin\n```\n\n\n\n\n 4.9878964877783698\n\n\n\n\n```python\nerror = (ans_non_lin-exc_ans)/exc_ans*100\nprint('non-uniform discretization with just 12 poitns give {:.2f}% relative error'.format(error))\n```\n\n non-uniform discretization with just 12 poitns give 0.72% relative error\n\n\n# Benefit of discretize more when a function changes quick\n

\n

1. Faster (use less points). Get high accuracy where it is needed\n

2. More accurate result compared to the case that use the same number of points\n

3. Less numerical error when adding small sections together\n

What if we can discretize the domain into $10^{200}$ sections, then add the result together, will we get an accurate result?\n

Answer: Generally no. More sections are better, but too many is not good. Area from each interval can have about 15 to 16 significante digits. Adding more numbers causing the error from addition to grow quickly!.\n\n\n\n```python\n#Assum that the exact solution is 30\nexact = 5\n```\n\n\n```python\neach_area = exact/1e7\neach_area\n```\n\n\n\n\n 5e-07\n\n\n\n\n```python\ndef err_ex(i):\n ans = 0\n each_area = exact/10**i\n for i in range(int(10**i)):\n ans += each_area\n return ans\n```\n\n\n```python\nerr_mat = [(i,err_ex(i)) for i in range(8)]\nprint('(data to be added (10**i), Addition result)')\nerr_mat\n```\n\n (data to be added (10**i), Addition result)\n\n\n\n\n\n [(0, 5.0),\n (1, 5.0),\n (2, 4.99999999999999),\n (3, 4.999999999999916),\n (4, 4.9999999999999485),\n (5, 4.999999999995016),\n (6, 4.999999999895295),\n (7, 4.999999999633759)]\n\n\n\n\n```python\nrelative_err = [abs((err_mat[i][1]-exact)/exact*100) for i in range(8)]\nrelative_err = np.array(relative_err)\nrelative_err\n```\n\n\n\n\n array([ 0.00000000e+00, 0.00000000e+00, 1.95399252e-13,\n 1.68753900e-12, 1.03028697e-12, 9.96713823e-11,\n 2.09409379e-09, 7.32482519e-09])\n\n\n\n\n```python\nplt.plot(range(8),relative_err,'-ob')\nplt.title('relative error from addition\\n')\nplt.show()\n```\n\n\n```python\n#error is increasing quickly!\n```\n\n# Simpson 1/3: (1 interval): Derivation overview\n\n

\n

1. Use quadratic polynomial to connect the dots, instead of using a straight line\n

2. Use lagrange polynomial interpolation to get the function approximation formula\n

$P(x) = f(a) \\tfrac{(x-m)(x-b)}{(a-m)(a-b)} + f(m) \\tfrac{(x-a)(x-b)}{(m-a)(m-b)} + f(b) \\tfrac{(x-a)(x-m)}{(b-a)(b-m)}$\n

3. Integrate the approximation formula, to get Simpson 1/3 rule\n

$\\int_{a}^{b} P(x) \\, dx =\\tfrac{b-a}{6}\\left[f(a) + 4f\\left(\\tfrac{a+b}{2}\\right)+f(b)\\right]$\n\n## Simpson 1/3: Multiple intervals (composite Simposon's rule)\n## An even number of intervals is needed for this method.\n

\n$\\int_a^b f(x) \\, dx\\approx\\tfrac{h}{3}\\bigg[f(x_0)+2\\sum_{j=1}^{n/2-1}f(x_{2j})+\n4\\sum_{j=1}^{n/2}f(x_{2j-1})+f(x_n)\n\\bigg]$\n\nhttps://en.wikipedia.org/wiki/Simpson%27s_rule\n\n## Composite Simposon 1/3: Scipy\n\n\n```python\nx_simps = np.linspace(0,20,21)\ny_simps = fx2(x_simps)\nsp.integrate.simps(y_simps, x_simps)\n```\n\n\n\n\n 4.9288484690130456\n\n\n\n\n```python\nx_simps = np.linspace(0,20,201)\ny_simps = fx2(x_simps)\nsp.integrate.simps(y_simps, x_simps)\n```\n\n\n\n\n 4.952462118996424\n\n\n\n\n```python\nx_simps = np.linspace(0,20,1001)\ny_simps = fx2(x_simps)\nsp.integrate.simps(y_simps, x_simps)\n```\n\n\n\n\n 4.9522242064467701\n\n\n\n\n```python\nexc_ans\n```\n\n\n\n\n 4.9522192711083974\n\n\n\n\n```python\n#Just 1000 sections (1001 points), get the result very close to 100000 points method\n```\n\n\n```python\nx_simps = np.linspace(0,20,10000001)\ny_simps = fx2(x_simps)\nexc_ans2 = sp.integrate.simps(y_simps, x_simps)\nexc_ans2\n```\n\n\n\n\n 4.9522192746100879\n\n\n\n\n```python\nans_list = []\nfor i in range(2,8):\n x_simps = np.linspace(0,20,10**i+1)\n y_simps = fx2(x_simps)\n ans = sp.integrate.simps(y_simps, x_simps)\n ans_list.append((i,ans))\nans_np = np.array(ans_list)\nplt.figure()\nplt.plot(ans_np[:,0],ans_np[:,1],'-ob')\nplt.show()\nplt.figure()\nplt.plot(ans_np[2:,0],ans_np[2:,1],'-ob')\nplt.show()\n```\n\n\n```python\nans_list\n```\n\n\n\n\n [(2, 4.9534160044915359),\n (3, 4.9522242064467701),\n (4, 4.9522192937324618),\n (5, 4.9522192746854854),\n (6, 4.9522192746103793),\n (7, 4.9522192746100879)]\n\n\n\n# Error from numerical integration\n\n

\nComposite Simpson method: $E=\\mathcal{O(h^4)}$\n

Composite Trapezoidal method: $E=\\mathcal{O(h^2)}$\n\n\nFor Composit Simpson, exact answer is obtained for an integration of 3rd degree polynomial (or less)\n\n\n```python\nfx3 = lambda x: x**3 + x**2 + x + 1\nx_simps = np.linspace(0,20,21)\ny_simps = fx3(x_simps)\nans_simp21 = sp.integrate.simps(y_simps, x_simps)\nx_simps = np.linspace(0,20,201)\ny_simps = fx3(x_simps)\nans_simp41 = sp.integrate.simps(y_simps, x_simps)\nprint(ans_simp21, ans_simp41)\n```\n\n 42886.6666667 42886.6666667\n\n\n\n```python\n#Analytical solution\nfx3_exact = sm.integrate(xs**3+xs**2+xs+1,(xs,0,20)).evalf()\nfx3_exact\n```\n\n\n\n\n 42886.6666666667\n\n\n\n\nWhat exactly is $E=\\mathcal{O}(h^2)$ for trapezoidal method?\n

Generally, when h is 10 times smaller, error = 100 times smaller!\n\n\n\n```python\nx_ = np.linspace(0,20,10000)\ny_ = fx3(x_)\nans1= trapz(y_, x_)\nerr1= ans1 - fx3_exact\nans1,err1\n```\n\n\n\n\n (42886.667080082683, 0.000413416019000579)\n\n\n\n\n```python\nx_ = np.linspace(0,20,100000)\ny_ = fx3(x_)\nans2 = trapz(y_, x_)\nerr2 = ans2 - fx3_exact\nans2,err2\n```\n\n\n\n\n (42886.666670800085, 4.13342058891430e-6)\n\n\n\n\n```python\nerr1/err2\n```\n\n\n\n\n 100.017893197065\n\n\n\n\n```python\n#When interval is 10 times smaller, error is 100 times smallers\n```\n\n\nWhat exactly is $E=\\mathcal{O}(h^4)$ for Simpson method?\n

Generally, when h is 10 times smaller, error = 10000 times smaller!\n\n\n\n```python\nfx4 = lambda x: x**4 + x**3 + x**2 + x + 1\n```\n\n\n```python\nfx4_exact = sm.integrate(xs**4 + xs**3+xs**2+xs+1,(xs,0,20)).evalf()\nfx4_exact\n```\n\n\n\n\n 682886.666666667\n\n\n\n\n```python\nx_ = np.linspace(0,20,11)\ny_ = fx4(x_)\nans1= sp.integrate.simps(y_, x_)\nerr1= ans1 - fx4_exact\nans1,err1\n```\n\n\n\n\n (682929.33333333326, 42.6666666666279)\n\n\n\n\n```python\nx_ = np.linspace(0,20,101)\ny_ = fx4(x_)\nans2= sp.integrate.simps(y_, x_)\nerr2= ans2 - fx4_exact\nans2,err2\n```\n\n\n\n\n (682886.67093333334, 0.00426666671410203)\n\n\n\n\n```python\nerr1/err2\n```\n\n\n\n\n 9999.99988881427\n\n\n\n\n```python\n10**4\n```\n\n\n\n\n 10000\n\n\n\n\n```python\n#When interval is 10 times smaller, error is 10**4 times smallers\n```\n\n## Composite Simposon 1/3: Manual\n$\\int_a^b f(x) \\, dx\\approx\\tfrac{h}{3}\\bigg[f(x_0)+2\\sum_{j=1}^{n/2-1}f(x_{2j})+\n4\\sum_{j=1}^{n/2}f(x_{2j-1})+f(x_n)\n\\bigg]$\n
n is number of interval\n\n\n```python\nclass int_man():\n def __init__(self, fx, x_m, n):\n self.fx = fx\n self.x_m = x_m\n self.n = n\n def sim13m(self):\n return sim_13_m(self.fx, self.x_m, self.n)\n\ndef sim_13_m(fx, x_m, n):\n y_m = fx(x_m)\n h = x_m[1] - x_m[0]\n sum2 = np.array([y_m[2*j] for j in range(1,int(n/2-1+1))],\n dtype = 'longfloat').sum()\n sum3 = np.array([y_m[2*j-1] for j in range(1,int(n/2+1))],\n dtype = 'longfloat').sum()\n simp_m = h/3 * (y_m[0] + 2 * sum2 + 4 * sum3 + y_m[-1])\n return simp_m\n\nn = 20\ncal_fx3 = int_man(fx3, np.linspace(0,20,n+1), n)\nprint('{:.10f}'.format(cal_fx3.sim13m()))\nprint('{:.10f}'.format(sim_13_m(fx3, np.linspace(0,20,n+1), n)))\n```\n\n 42886.6666666667\n 42886.6666666667\n\n\n\n```python\nfx3_exact\n```\n\n\n\n\n 42886.6666666667\n\n\n\n\n```python\ndef simp_in_fn(fx,x):\n return simps(fx(x),x)\n```\n\n\n```python\n%%timeit -n 10 -r 3\nsimps(fx3(np.linspace(0,20,21)),np.linspace(0,20,21))\n```\n\n 10 loops, best of 3: 140 µs per loop\n\n\n\n```python\nt1 = time.monotonic()\nfor i in range(10000):\n simps(fx3(np.linspace(0,20,21)),np.linspace(0,20,21))\nt2 = time.monotonic()\ntime_numpy_manual = t2-t1\nprint('scipy simps')\ntime_numpy_manual\n```\n\n scipy simps\n\n\n\n\n\n 0.6734330859908368\n\n\n\n\n```python\nsimp_in_fn(fx3,np.linspace(0,20,21))\n```\n\n\n\n\n 42886.666666666664\n\n\n\n\n```python\nt1 = time.monotonic()\nfor i in range(10000):\n simp_in_fn(fx3,np.linspace(0,20,21))\nt2 = time.monotonic()\ntime_numpy_manual = t2-t1\nprint('scipy simps in function')\ntime_numpy_manual\n```\n\n scipy simps in function\n\n\n\n\n\n 0.5315435919910669\n\n\n\n\n```python\n%%timeit -n 10 -r 3\nsim_13_m(fx3, np.linspace(0,20,21), 20)\n```\n\n 10 loops, best of 3: 50.4 µs per loop\n\n\n\n```python\nt1 = time.monotonic()\nfor i in range(10000):\n sim_13_m(fx3, np.linspace(0,20,21), 20)\nt2 = time.monotonic()\ntime_numpy_manual = t2-t1\nprint('sim_13_m fn')\ntime_numpy_manual\n```\n\n sim_13_m fn\n\n\n\n\n\n 0.47913683200022206\n\n\n\n\n```python\n%%timeit -n 10 -r 3\ncal_fx3 = int_man(fx3, np.linspace(0,20,21), 20)\ncal_fx3.sim13m()\n```\n\n 10 loops, best of 3: 52.8 µs per loop\n\n\n\n```python\nt1 = time.monotonic()\nfor i in range(10000):\n cal_fx3 = int_man(fx3, np.linspace(0,20,21), 20)\n cal_fx3.sim13m()\nt2 = time.monotonic()\ntime_numpy_manual = t2-t1\nprint('int_man class')\ntime_numpy_manual\n```\n\n int_man class\n\n\n\n\n\n 0.5170318769814912\n\n\n\n## Composite Simposon 3/8\nhttps://en.wikipedia.org/wiki/Simpson%27s_rule#Simpson.27s_3.2F8_rule
\nhttp://mathforcollege.com/nm/mws/gen/07int/mws_gen_int_txt_simpson3by8.pdf
\nhttp://mathfaculty.fullerton.edu/mathews/n2003/Simpson38RuleMod.html\n
\n

One Interval

\n$\\int_{a}^{b} f(x) \\, dx \\approx \\tfrac{3h}{8}\\left[f(a) + 3f\\left(\\tfrac{2a+b}{3}\\right) + 3f\\left(\\tfrac{a+2b}{3}\\right) + f(b)\\right] \\\\\n\\int_{a}^{b} f(x) \\, dx \\approx \\tfrac{(b-a)}{8}\\left[f(a) + 3f\\left(\\tfrac{2a+b}{3}\\right) + 3f\\left(\\tfrac{a+2b}{3}\\right) + f(b)\\right]$\n

Multiple Intervals

\n$\\int_a^b f(x) \\, dx\\approx\\tfrac{3h}{8}\\bigg[f(x_0)+3\\sum_{i=1,4,7,...}^{n-1}f(x_{i})+ \\\\\n3\\sum_{i=2,5,8,...}^{n-1}f(x_{i})+2\\sum_{i=3,6,9,...}^{n-3}f(x_i) + f(x_n)\n\\bigg]$\n
or for $h = \\frac{b-a}{3m}$

\n$\\int_a^b f(x) \\, dx \\approx \\frac{3h}{8}\\sum_{k=1}^{m}(f(x_{3k-3}+3f(x_{3k-2})+3f(x_{3k-1})+f(x_{3k}))$\n

We need 3m interval (multiplication of 3) for Simpson 3/8\n\n\n\n```python\nn = 21\nm = int(n/3)\nh = 20/n\nx_38 = np.linspace(0,20,n+1)\ny_38 = fx3(x_38)\nsum_all = sum([y_38[3*k-3] + 3 * y_38[3*k-2] + 3 * y_38[3*k-1] + y_38[3*k] for k in range(1,m+1)])\nsim_38 = 3 * h / 8 * sum_all\nsim_38\n```\n\n\n\n\n 42886.666666666657\n\n\n\n\n```python\nfx3_exact\n```\n\n\n\n\n 42886.6666666667\n\n\n\n\n```python\n#Exact numerical value of polynomial degree 3 (or lower) integration can be obtained by both Simpson method\n#If number of interval is even, use Simpson 1/3\n#If the number of interval is the multiplication of 3 use Simpson 3/8\n```\n\n# Double Integration\n

\n\nfxy1 = $\\int_1^3\\int_{12}^{16} 1 \\, dx dy$

\nfxy2 = $\\int_1^3\\int_{12}^{16} x^2+7y \\, dx dy$

\nfxy3 = $\\int_1^3\\int_{12}^{y} x^2+7y \\, dx dy$\n\n\n\n```python\nxs, ys = sm.symbols('x y')\n```\n\n## Analytical solution of fxy1\n\n\n```python\nExy1 = sm.integrate(1,(xs,12,16),(ys,1,3))\nExy1\n```\n\n\n\n\n 8\n\n\n\n## Analytical solution of fxy2\n\n\n```python\nExy2 = sm.integrate(xs**2+7*ys,(xs,12,16),(ys,1,3))\nExy2\n```\n\n\n\n\n 5072/3\n\n\n\n\n```python\nExy2_sm = sm.integrate(xs**2+7*ys,(xs),(ys))\nExy2_sm\n```\n\n\n\n\n x**3*y/3 + 7*x*y**2/2\n\n\n\n\n```python\nExy2_xT = Exy2_sm.subs({xs:16})\nExy2_xT\n```\n\n\n\n\n 56*y**2 + 4096*y/3\n\n\n\n\n```python\nExy2_xB = Exy2_sm.subs({xs:12})\nExy2_xB\n```\n\n\n\n\n 42*y**2 + 576*y\n\n\n\n\n```python\nExy2_y_ori = Exy2_xT - Exy2_xB\nExy2_y_ori\n```\n\n\n\n\n 14*y**2 + 2368*y/3\n\n\n\n\n```python\nExy2_y_ori.subs({ys:3}) - Exy2_y_ori.subs({ys:1})\n```\n\n\n\n\n 5072/3\n\n\n\n## Analytical solution of fxy3\n\n\n```python\nExy3 = sm.integrate(xs**2+7*ys,(xs,12,ys),(ys,1,3))\nExy3\n```\n\n\n\n\n -4262/3\n\n\n\n\n```python\nExy3_sm = sm.integrate(xs**2+7*ys,(xs,12,ys))\nExy3_sm\n```\n\n\n\n\n y**3/3 + 7*y**2 - 84*y - 576\n\n\n\n\n```python\nExy3_final = sm.integrate(Exy3_sm,(ys,1,3))\nExy3_final\n```\n\n\n\n\n -4262/3\n\n\n\n\n```python\n-4262/3\n```\n\n\n\n\n -1420.6666666666667\n\n\n\n## Scipy double integration (dblquad) for fxy1\n\n\n```python\nfxy1 = lambda x,y: 1\nsp.integrate.dblquad(fxy1,1,3,lambda y:12, lambda y:16)\n```\n\n\n\n\n (8.0, 8.881784197001252e-14)\n\n\n\n## Scipy double integration (dblquad) for fxy2\n\n\n```python\nfxy2 = lambda x,y: x**2+7*y\nsp.integrate.dblquad(fxy2,1,3,lambda y:12, lambda y:16)\n```\n\n\n\n\n (1690.6666666666667, 1.8770170602995982e-11)\n\n\n\n\n```python\n5072/3\n```\n\n\n\n\n 1690.6666666666667\n\n\n\n## Scipy double integration (dblquad) for fxy3\n\n\n```python\nfxy3 = lambda x,y: x**2+7*y\nsp.integrate.dblquad(fxy3,1,3,lambda y:12, lambda y:y)\n```\n\n\n\n\n (-1420.6666666666665, 1.5772568436508056e-11)\n\n\n\n\n```python\n-4262/3\n#same answer as sympy\n```\n\n\n\n\n -1420.6666666666667\n\n\n\n## Scipy double integration with simps twice! (fxy3)\n### First, calculate $\\int_{12}^y f(x,y) \\, dx$ for every y in np.linspace(1,3,11)
Then use this value to do the outer integration\n\n\n```python\ny_fxy3 = np.linspace(1,3,11)\nfxy3 = lambda x,y: x**2+7*y\n# fy3 is the integration for x = 12 to y at a certain y\nfy3 = lambda y: simps(fxy3(np.linspace(12,y,11),y),np.linspace(12,y,11))\nsimps([fy3(i) for i in y_fxy3],y_fxy3)\n```\n\n\n\n\n -1420.666666666667\n\n\n\n\n```python\n#Notice that the exact solution can be optained in double integration too\n```\n\n\n```python\nplt.plot([0,14],[1,1],'-r',label='y = 1')\nplt.plot([0,14],[3,3],'--r',label='y = 3')\nplt.plot([12,12],[0,13],'-b',label='x = 12')\nplt.plot([0,13],[0,13],'--b',label='x = y')\nplt.fill_between([1,3,12],[1,3,3],[1,1,1],color = 'green', alpha = 0.1)\nplt.legend(bbox_to_anchor=(1.4, 1))\nplt.xlabel('x')\nplt.ylabel('y')\nplt.title('Integration domain for\\n$\\int_1^3\\int_{12}^{y} x^2+7y \\, dx dy$')\nplt.show()\nprint('Integration direction is from solid to dash line, starting with blue line')\n```\n\n\n```python\nx_plot = np.linspace(12,3,11)\nx_plot2 = np.linspace(12,1,11)\nplt.figure(figsize = (10,4))\nplt.scatter(x_plot,fxy3(x_plot,3), c = range(11),\n cmap = 'jet',label='f(x,3), y = 3')\nplt.colorbar()\nplt.scatter(x_plot2,fxy3(x_plot2,1), marker='v', \n c = range(11),cmap = 'plasma',label='f(x,1), y = 1')\nplt.colorbar()\nplt.xlabel('x')\nplt.ylabel('y')\nplt.legend()\nplt.show()\nprint('Color indicates the order of the dot\\nWe are integrating backward from 12 to y')\n```\n", "meta": {"hexsha": "9bff9165746c2a1f3d77e0ad76763511a727a697", "size": 306919, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Ipynb/L09_Integration.ipynb", "max_stars_repo_name": "epmmko/counting_lines_of_code", "max_stars_repo_head_hexsha": "efea2f4ceeef269e06da9b39662ab5acb5c0b4cf", "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": "Ipynb/L09_Integration.ipynb", "max_issues_repo_name": "epmmko/counting_lines_of_code", "max_issues_repo_head_hexsha": "efea2f4ceeef269e06da9b39662ab5acb5c0b4cf", "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": "Ipynb/L09_Integration.ipynb", "max_forks_repo_name": "epmmko/counting_lines_of_code", "max_forks_repo_head_hexsha": "efea2f4ceeef269e06da9b39662ab5acb5c0b4cf", "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": 115.3830827068, "max_line_length": 49984, "alphanum_fraction": 0.8664142657, "converted": true, "num_tokens": 9195, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765210631688, "lm_q2_score": 0.9465966754730989, "lm_q1q2_score": 0.8648831572962223}} {"text": "# Exercise 5, answers\n\n## Task 1\n\nThe stability rule becomes\n$$\n(2x_1,2x_2)-\\lambda(1,1) = (0,0),\n$$\nand completementary rule becomes\n$$\n\\lambda(x_1+x_2-1) = 0.\n$$\nThus, we need to have:\n\n$$\n\\left\\{\n\\begin{align}\n2x_1-\\lambda=0\\quad (1)\\\\\n2x_2-\\lambda=0\\quad (2)\\\\\n\\lambda(x_1+x_2-1) = 0\\quad (3)\n\\end{align}\n\\right.\n$$\n\nNow deducting equation (2), from equation (1) gives $2x_1-2x_2=0$, thus $x_1=x_2$. Now if $\\lambda= 0$, then $x_1=x_2=0$. However, this solution is not feasible. Thus, $\\lambda\\neq0$, which implies $x_1+x_2-1=0$, which gives $x_1=x_2=\\frac12$ and, thus, $\\lambda=1$. These values satisfy KKT conditions.\n\nBecause the problem is quadratic, it has an optimal solution. Since only one solution satisfies KKT conditions, this solution is optimal.\n\n## Task 2\n\nNow,\n$$\n\\begin{align}\n\\nabla_x L_c(x^*,\\lambda^*)& = \\nabla f(x^*)+\\sum_{k=1}^K \\lambda^*_k\\nabla h_k(x^*)+c\\nabla(\\sum_{k=1}^Kh_k(x^*)^2)\\\\\n&=\\nabla f(x^*)+\\sum_{k=1}^K \\lambda^*_k\\nabla h_k(x^*)+2c\\sum_{k=1}^Kh_k(x^*)\\nabla h_k(x^*)\\\\\n&=0+2c\\sum_{k=1}^K0\\nabla h_k(x^*)=0.\n\\end{align}\n$$\nThe first zero is given by the KKT conditions and the second zero is due to the solution being feasible.\n", "meta": {"hexsha": "0a9be9746487549cdac25d5dee919891a7a2816d", "size": 2555, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Exercise 5, answers.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": "Exercise 5, answers.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": "Exercise 5, answers.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": 24.3333333333, "max_line_length": 318, "alphanum_fraction": 0.5107632094, "converted": true, "num_tokens": 484, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404057671714, "lm_q2_score": 0.930458262725596, "lm_q1q2_score": 0.8648055052570952}} {"text": "```python\n%matplotlib inline\nfrom numpy import *\nfrom matplotlib.pyplot import *\nimport sympy as sym\n\n# See 02_non_linear_equations.ipynb for the code\n```\n\nWe use the function $f(x) = \\frac{x}{8}(63x^{4} - 70x^{2} + 15)$, which is the Legendre polynomial of order 5\n\n1. We first **compute the first derivative of this function** through the use of sympy library's `sym.diff`. We'll use this derivative for the Newton's method.\n\n2. We use `sym.lambdify` the function and its derivative in order to make them assume values as parameters.\n\n3. We plot the function with respect to $[-1, 1]$ and put the x axis in evidence. \n\n## Bisection method\n\nFor the bisection method, it is very important **not to choose values that have the same sign**, since we rely on them having different signs in order to perform the bisection step. That's why we start the `bisect` function with \n\n```python\nassert(f(a) * f(b) < 0)\n```\nThe criterion $| x^{k} - \\alpha| < T$, where $T$ is the **tolerance** we are prescribing to the algorithm.\n\nSince this assumption would require us to have $\\alpha$, which is the value we are looking for, it doesn't make sense. We should simply check that $|f(x^{k}| = 0$ since we are converging towards a zero of the function.\n\n\n## Newton's Method\n\nSee the Jupyter Notebook for the implementation\n\n## Chord Method\n\n\n\n\n", "meta": {"hexsha": "65e033499726de532cec6671c2d3ad36a6a289a9", "size": 2480, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "gsarti_notes/lesson_9.ipynb", "max_stars_repo_name": "gsarti/P1.4_seed", "max_stars_repo_head_hexsha": "e09dc4381c5da0c5781e185d7bce69679b8fca66", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-11-08T07:53:28.000Z", "max_stars_repo_stars_event_max_datetime": "2018-11-08T07:53:28.000Z", "max_issues_repo_path": "gsarti_notes/lesson_9.ipynb", "max_issues_repo_name": "gsarti/P1.4_seed", "max_issues_repo_head_hexsha": "e09dc4381c5da0c5781e185d7bce69679b8fca66", "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": "gsarti_notes/lesson_9.ipynb", "max_forks_repo_name": "gsarti/P1.4_seed", "max_forks_repo_head_hexsha": "e09dc4381c5da0c5781e185d7bce69679b8fca66", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-01-26T11:41:55.000Z", "max_forks_repo_forks_event_max_datetime": "2019-01-26T11:41:55.000Z", "avg_line_length": 27.5555555556, "max_line_length": 238, "alphanum_fraction": 0.575, "converted": true, "num_tokens": 351, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582593509315, "lm_q2_score": 0.9294404052785552, "lm_q1q2_score": 0.8648055016659089}} {"text": "\n\n# Basic Calculus: Derivatives, Integrals, Limits\nfrom https://docs.sympy.org/latest/tutorial/basic_operations.html\n\nIntiating symbol printing \n\n\n```python\nfrom sympy import *\nimport sympy as sp\ninit_printing()\nx, y, z = symbols('x y z')\n\n```\n\n\n```python\nprint(sp.__version__)\n```\n\n 1.1.1\n\n\n\n```python\nfrom IPython.display import HTML, Math\ndisplay(HTML(\"\"))\nMath(r\"e^\\alpha\")\n```\n\n\n\n\n\n\n\n\n$$e^\\alpha$$\n\n\n\n# Derivatives\nTo take derivatives, use the diff function.\n\n\n```python\nfigure = diff(cos(x), x)\ndisplay(figure)\n\n```\n\n\n```python\nfigure = diff(exp(x**2), x)\nprint(figure)\ndisplay(figure)\n```\n\ndiff can take multiple derivatives at once. To take multiple derivatives, pass the variable as many times as you wish to differentiate, or pass a number after the variable. For example, both of the following find the third derivative of x^4.\n\n\n```python\ndiff(cos(x), x)\n```\n\nYou can also take derivatives with respect to many variables at once. Just pass each derivative in order, using the same syntax as for single variable derivatives. \n\n\n```python\ndiff(x**4, x, x, x)\n\n```\n\nEvaluate a derivative, https://stackoverflow.com/a/44274950\n\n\n```python\nimport sympy as sym\nimport math\n\n\ndef f(x,y):\n return x**2 + x*y**2\n\n\nx, y = sym.symbols('x y')\n\ndef fprime(x,y):\n return sym.diff(f(x,y),x)\n\nprint(fprime(x,y)) #This works.\n\nDerivativeOfF = sym.lambdify((x,y),fprime(x,y),\"numpy\")\n\nprint(DerivativeOfF(1,1))\n```\n\n 2*x + y**2\n 3\n\n\nPartial Derivatives, https://stackoverflow.com/a/30791631\n\n\n```python\nfrom sympy import symbols, diff\nx, y, z = symbols('x y z', real=True)\nf = 4*x*y + x*sin(z) + x**3 + z**8*y\ndiff(f, x)\n```\n\n# Integrals\nTo compute an integral, use the integrate function. There are two kinds of integrals, definite and indefinite. To compute an indefinite integral, that is, an antiderivative, or primitive, just pass the variable after the expression.\n\n\n```python\nintegrate(cos(x), x)\n```\n\n∞ in SymPy is oo (that’s the lowercase letter “oh” twice). This is because oo looks like ∞, and is easy to type.\nTo compute a definite integral, pass the argument (integration_variable, lower_limit, upper_limit). \n\n\n```python\nintegrate(exp(-x), (x, 0, oo))\n```\n\nAs with indefinite integrals, you can pass multiple limit tuples to perform a multiple integral. \n\n\n```python\nintegrate(exp(-x**2 - y**2), (x, -oo, oo), (y, -oo, oo))\n```\n\n\n```python\n#If integrate is unable to compute an integral, it returns an unevaluated Integral object.\n```\n\n\n```python\nexpr = integrate(x**x, x)\nprint(expr)\nexpr\n```\n\nAs with Derivative, you can create an unevaluated integral using Integral. To later evaluate this integral, call doit.\n\n\n```python\nexpr = Integral(log(x)**2, x)\nexpr\n```\n\n\n```python\nexpr.doit()\n```\n\nintegrate uses powerful algorithms that are always improving to compute both definite and indefinite integrals, including heuristic pattern matching type algorithms, a partial implementation of the Risch algorithm, and an algorithm using Meijer G-functions that is useful for computing integrals in terms of special functions, especially definite integrals. Here is a sampling of some of the power of integrate.\n\n\n```python\ninteg = Integral((x**4 + x**2*exp(x) - x**2 - 2*x*exp(x) - 2*x - exp(x))*exp(x)/((x - 1)**2*(x + 1)**2*(exp(x) + 1)), x)\n\n#integ\n\ninteg.doit()\n```\n\n\n```python\ninteg = Integral(sin(x**2), x)\n\n#integ\n\ninteg.doit()\n```\n\n\n```python\ninteg = Integral(x**y*exp(-x), (x, 0, oo))\n\n#integ\n\n\ninteg.doit()\n```\n\n# Limits\nSymPy can compute symbolic limits with the limit function.\n\n\n```python\nlimit(sin(x)/x, x, 0)\n\n```\n\nLike Derivative and Integral, limit has an unevaluated counterpart, Limit. To evaluate it, use doit.\n\n\n```python\nexpr = Limit((cos(x) - 1)/x, x, 0)\nexpr\n#expr.doit()\n```\n\n\n```python\nTo evaluate a limit at one side only, pass '+' or '-' as a third argument to limit.\n```\n\n\n```python\nexpr = limit(1/x, x, 0, '+')\nexpr\n```\n\n\n```python\nexpr = limit(1/x, x, 0, '-')\nexpr\n```\n\n# Series Expansion¶\n\nSymPy can compute asymptotic series expansions of functions around a point. To compute the expansion of f(x)\naround the point x=x0 terms of order x^n , use f(x).series(x, x0, n). x0 and n can be omitted, in which case the defaults x0=0 and n=6 will be used.\n\n\n\n\n```python\nexpr = exp(sin(x))\nexpr.series(x, 0, 4)\n```\n\n\n```python\n x + x**3 + x**6 + O(x**4)\n```\n\nIf you do not want the order term, use the removeO method.\n\n\n```python\nexpr.series(x, 0, 4).removeO()\n```\n\nThe O notation supports arbitrary limit points (other than 0):\n\n\n\n\n```python\nexp(x - 6).series(x, x0=6)\n\n```\n", "meta": {"hexsha": "ff814ab7fc614a9e408b45d7bfbd23277bdcc5c2", "size": 30003, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "basic_calculus_sympy.ipynb", "max_stars_repo_name": "ricklon/jupytercalculus", "max_stars_repo_head_hexsha": "2c8a4d6b94881eedfe3d3ed54bdebfb5847ba611", "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": "basic_calculus_sympy.ipynb", "max_issues_repo_name": "ricklon/jupytercalculus", "max_issues_repo_head_hexsha": "2c8a4d6b94881eedfe3d3ed54bdebfb5847ba611", "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": "basic_calculus_sympy.ipynb", "max_forks_repo_name": "ricklon/jupytercalculus", "max_forks_repo_head_hexsha": "2c8a4d6b94881eedfe3d3ed54bdebfb5847ba611", "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.1719817768, "max_line_length": 2266, "alphanum_fraction": 0.5721761157, "converted": true, "num_tokens": 1329, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582554941719, "lm_q2_score": 0.9294404018582427, "lm_q1q2_score": 0.8648054948988226}} {"text": "# Contravariant & Covariant indices in Tensors (Symbolic)\n\n\n```python\nfrom einsteinpy.symbolic import SchwarzschildMetric, MetricTensor, ChristoffelSymbols, RiemannCurvatureTensor\nimport sympy\nsympy.init_printing()\n```\n\n### Analysing the schwarzschild metric along with performing various operations\n\n\n```python\nsch = SchwarzschildMetric()\nsch.tensor()\n```\n\n\n```python\nsch_inv = sch.inv()\nsch_inv.tensor()\n```\n\n\n```python\nsch.order\n```\n\n\n```python\nsch.config\n```\n\n\n\n\n 'll'\n\n\n\n### Obtaining Christoffel Symbols from Metric Tensor\n\n\n```python\nchr = ChristoffelSymbols.from_metric(sch_inv) # can be initialized from sch also\nchr.tensor()\n```\n\n\n```python\nchr.config\n```\n\n\n\n\n 'ull'\n\n\n\n### Changing the first index to covariant\n\n\n```python\nnew_chr = chr.change_config('lll') # changing the configuration to (covariant, covariant, covariant)\nnew_chr.tensor()\n```\n\n\n```python\nnew_chr.config\n```\n\n\n\n\n 'lll'\n\n\n\n### Any arbitary index configuration would also work!\n\n\n```python\nnew_chr2 = new_chr.change_config('lul')\nnew_chr2.tensor()\n```\n\n### Obtaining Riemann Tensor from Christoffel Symbols and manipulating it's indices\n\n\n```python\nrm = RiemannCurvatureTensor.from_christoffels(new_chr2)\nrm[0,0,:,:]\n```\n\n\n```python\nrm.config\n```\n\n\n\n\n 'ulll'\n\n\n\n\n```python\nrm2 = rm.change_config(\"uuuu\")\nrm2[0,0,:,:]\n```\n\n\n```python\nrm3 = rm2.change_config(\"lulu\")\nrm3[0,0,:,:]\n```\n\n\n```python\nrm4 = rm3.change_config(\"ulll\")\nrm4[0,0,:,:]\n```\n\n#### It is seen that `rm` and `rm4` are same as they have the same configuration\n", "meta": {"hexsha": "97c58f50b29334ca16e6eb88469ea9fb8a23cf09", "size": 82047, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "docs/source/examples/Playing with Contravariant and Covariant Indices in Tensors(Symbolic).ipynb", "max_stars_repo_name": "r0cketr1kky/einsteinpy", "max_stars_repo_head_hexsha": "d86f412736a42e2cf688a1e21d7b553868a14bc4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-03-08T16:13:56.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-08T16:13:56.000Z", "max_issues_repo_path": "docs/source/examples/Playing with Contravariant and Covariant Indices in Tensors(Symbolic).ipynb", "max_issues_repo_name": "r0cketr1kky/einsteinpy", "max_issues_repo_head_hexsha": "d86f412736a42e2cf688a1e21d7b553868a14bc4", "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/source/examples/Playing with Contravariant and Covariant Indices in Tensors(Symbolic).ipynb", "max_forks_repo_name": "r0cketr1kky/einsteinpy", "max_forks_repo_head_hexsha": "d86f412736a42e2cf688a1e21d7b553868a14bc4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-03-19T18:46:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-19T18:46:13.000Z", "avg_line_length": 126.4206471495, "max_line_length": 14080, "alphanum_fraction": 0.7302277963, "converted": true, "num_tokens": 417, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9648551505674444, "lm_q2_score": 0.896251371748038, "lm_q1q2_score": 0.8647527522342319}} {"text": "```python\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy import signal\n```\n\nFT algorithm receives a trajectory, apply its filters to find the appropriate cycles, and outputs the full set of cyclic components. There are two algorithms:\n\n- the Discrete Fourier Transform (DFT) which requires $O(n^2)$ operations (for n samples)\n- the Fast Fourier Transform (FFT) which requires $O(nlog(n))$ operations\n\n## DFT\n\\begin{equation}\nX_k = \\sum_{n=0}^{N-1} x_n e^{-i 2 \\pi k n / N}\n\\end{equation}\n\n\\begin{equation}\nx_n = \\frac{1}{N} \\sum_{k=0}^{N-1} X_k e^{i 2 \\pi k n / N}\n\\end{equation}\n\nwhere:\n- $X_k$ amount of frequency $k$ in the signal; each $k$th value is a complex number including strength (amplitute) and phase shift\n- $N$ number of samples\n- $n$ current sample, $n\\in{0\\cdots N−1}$\n- $k$ current frequency, between $0$ Hz to $N-1$ Hz\n- $1/N$ not necessary but it gives the actual sizes of the time spikes\n- $n/N$ is the percent of the time we’ve gone through\n- $2\\pi{k}$ the speed in radians/second\n- $e^{−ix}$ the backwards-moving circular path. This last three tell how far we’ve moved, for this speed and time.\n\n\n```python\n# step by step dft\ndef dft_k(x, k):\n N = len(x)\n return sum((x[n]*np.e**(-1j*2*np.pi*k*n/N) for n in range(N)))\n\n# step by step idft\ndef idft_n(X, n):\n N = len(x)\n return sum((1/N * X[k] * np.e**(1j*2*np.pi*k*n/N) for k in range(N)))\n```\n\n\n```python\ndef remove_frequencies(Xn, N, fs, fre_low, fre_high):\n # remove specific frequencies\n Yn = np.copy(Xn)\n fre_low_n = fre_low * N // fs\n fre_high_n = fre_high * N // fs\n # remove two side frequiencies\n Yn[fre_low_n:fre_high_n] = 0\n Yn[N-fre_high_n:N-fre_low_n] = 0\n return Yn\n\n\nN = 1000\nfs = 10000\nT = 1/fs\nt = np.linspace(0, N * T, N)\nx = np.sin(2*np.pi*50*t) + 2 * np.sin(2*np.pi*150*t) + 0.5 * np.sin(2*np.pi*1000*t)\n\n# dft: analysis\nXn = np.zeros(N, dtype=np.complex)\nfor i in range(N):\n X = dft_k(x, i)\n Xn[i] = X\n\n# filter: remove specific requencies\nYn = remove_frequencies(Xn, N, fs, 800, 1200)\n \n# idft: synthesis\nRe = np.zeros(N, dtype=np.complex)\nfor i in range(N):\n Re[i] = idft_n(Yn, i)\n\n# one side frequency range\nxf = np.linspace(0.0, 1.0/(2.0*T), N//2)\nxn = 2.0/N * np.abs(Xn[0:N//2])\nyn = 2.0/N * np.abs(Yn[0:N//2])\n```\n\n\n```python\n#------------------------------------------------------------\n# Set up the plots\nfig = plt.figure(figsize=(10, 10))\nfig.subplots_adjust(left=0.09, bottom=0.09, right=0.95, top=0.95,\n hspace=0.05, wspace=0.05)\n#----------------------------------------\n# plot the origional signal\nax1 = fig.add_subplot(221)\nax1.grid(color='#b7b7b7', linestyle='-', linewidth=0.5, alpha=0.5)\nax1.plot(t, x, '-k', label=r'data $D(x)$')\nplt.setp(ax1.get_xticklabels(), visible=False)\n\n#----------------------------------------\n# plot the dft and area to remove\nax2 = fig.add_subplot(222)\nax2.plot(xf, xn, '-k')\nax2.grid(color='#b7b7b7', linestyle='-', linewidth=0.5, alpha=0.5)\nax2.axvspan(800, 1200, facecolor='#b7b7b7', alpha=0.5)\nax2.yaxis.tick_right()\nplt.setp(ax2.get_xticklabels(), visible=False)\n\n#----------------------------------------\n# plot the left frequencies\nax3 = fig.add_subplot(224, sharex=ax2)\nax3.plot(xf, yn, '-k')\nax3.grid(color='#b7b7b7', linestyle='-', linewidth=0.5, alpha=0.5)\nax3.yaxis.tick_right()\n\n#----------------------------------------\n# plot the filtered signal\nax4 = fig.add_subplot(223, sharex=ax1)\nax4.plot(t, Re.real, '-k')\nax4.grid(color='#b7b7b7', linestyle='-', linewidth=0.5, alpha=0.5)\n\n#------------------------------------------------------------\n# Plot flow arrows\nax = fig.add_axes([0, 0, 1, 1], xticks=[], yticks=[], frameon=False)\n\narrowprops = dict(arrowstyle=\"simple\",\n color=\"#333333\", alpha=0.5,\n shrinkA=5, shrinkB=5,\n patchA=None,\n patchB=None,\n connectionstyle=\"arc3,rad=-0.35\")\n\nax.annotate('', [0.57, 0.57], [0.47, 0.57],\n arrowprops=arrowprops,\n transform=ax.transAxes)\nax.annotate('', [0.57, 0.47], [0.57, 0.57],\n arrowprops=arrowprops,\n transform=ax.transAxes)\nax.annotate('', [0.47, 0.47], [0.57, 0.47],\n arrowprops=arrowprops,\n transform=ax.transAxes)\nplt.show()\n```\n\n## Reference:\n\n- [Fourier Transform: A R Tutorial](http://www.di.fc.ul.pt/~jpn/r/fourier/fourier.html)\n- [An Interactive Guide To The Fourier Transform](https://betterexplained.com/articles/an-interactive-guide-to-the-fourier-transform/)\n- [An Interactive Introduction to Fourier Transforms](http://www.jezzamon.com/fourier/index.html)\n", "meta": {"hexsha": "2383e60b9e60024416a27166a4bb97d40ee08f1a", "size": 6839, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "003_fourier_transform.ipynb", "max_stars_repo_name": "ValleyZw/hill", "max_stars_repo_head_hexsha": "51d4bc76d7c49b3dccf88659fade806906a9b4e2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-07-22T07:19:39.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-22T07:19:39.000Z", "max_issues_repo_path": "003_fourier_transform.ipynb", "max_issues_repo_name": "ValleyZw/hill", "max_issues_repo_head_hexsha": "51d4bc76d7c49b3dccf88659fade806906a9b4e2", "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": "003_fourier_transform.ipynb", "max_forks_repo_name": "ValleyZw/hill", "max_forks_repo_head_hexsha": "51d4bc76d7c49b3dccf88659fade806906a9b4e2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-05-19T17:52:16.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-19T17:52:16.000Z", "avg_line_length": 33.3609756098, "max_line_length": 167, "alphanum_fraction": 0.4994882293, "converted": true, "num_tokens": 1475, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572778036723353, "lm_q2_score": 0.9032942138630786, "lm_q1q2_score": 0.8647035011167766}} {"text": "---\nauthor: Nathan Carter (ncarter@bentley.edu)\n---\n\nThis answer assumes you have imported SymPy as follows.\n\n\n```python\nfrom sympy import * # load all math functions\ninit_printing( use_latex='mathjax' ) # use pretty math output\n```\n\nYou can define any number of variables as follows.\nHere we define $x$, $y$, and $z$.\n\n\n```python\nvar( 'x y z' )\n```\n\n\n\n\n$\\displaystyle \\left( x, \\ y, \\ z\\right)$\n\n\n\nYou can tell that they are variables, because when you ask Python to\nprint them out, it does not print a value (such as a number) but rather\njust the symbol itself.\n\n\n```python\nx\n```\n\n\n\n\n$\\displaystyle x$\n\n\n\nAnd when you use a symbol inside a larger formula, it doesn't attempt to\ncompute a result, but stores the entire formula symbolically.\n\n\n```python\nformula = sqrt(x) + 5\nformula\n```\n\n\n\n\n$\\displaystyle \\sqrt{x} + 5$\n\n\n", "meta": {"hexsha": "104fd8fe20093190b2ed518275942bb1ca62df5d", "size": 2788, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "database/tasks/How to create symbolic variables/Python, using SymPy.ipynb", "max_stars_repo_name": "nathancarter/how2data", "max_stars_repo_head_hexsha": "7d4f2838661f7ce98deb1b8081470cec5671b03a", "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": "database/tasks/How to create symbolic variables/Python, using SymPy.ipynb", "max_issues_repo_name": "nathancarter/how2data", "max_issues_repo_head_hexsha": "7d4f2838661f7ce98deb1b8081470cec5671b03a", "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": "database/tasks/How to create symbolic variables/Python, using SymPy.ipynb", "max_forks_repo_name": "nathancarter/how2data", "max_forks_repo_head_hexsha": "7d4f2838661f7ce98deb1b8081470cec5671b03a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-07-18T19:01:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T06:47:11.000Z", "avg_line_length": 20.6518518519, "max_line_length": 99, "alphanum_fraction": 0.5118364419, "converted": true, "num_tokens": 227, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9744347890464284, "lm_q2_score": 0.8872046026642944, "lm_q1q2_score": 0.8645230298382021}} {"text": "# Pass exam problem\n\n\nLet's say we have 50 questions and to pass we need to answer half of them correctly. Each questions has a 4 answers and our agent guesses at random Let's assume that all guesses are independent events.\n\\begin{align}\np &= 0.25 \\\\\nN &= 50 \\\\\nX &= 25\n\\end{align}\nWhere $p$ is probability to guess correctly, $N$ amount of questions (or trials) and $X$ is how many trials do we need to guess correctly. Then we are trying to calculate:\n\\begin{gather}\nP(X \\geq 25) \\Rightarrow 1-P(X \\leq 24)\\\\\nP(X \\geq 25) = 1 - \\sum_{i=1}^{24} \\binom{50}{i} * 0.25^i * 0.75^{50-i}\n\\end{gather}\n\n\n```python\nfrom scipy.stats import binom \n\nn = 50\np = 0.25\nx = 24\n# defining X values\nk_values = list(range(n+1))\n# obtaining the mean and variance \nmean, var = binom.stats(n, p)\n# getting a distribution\ndist = [binom.pmf(k, n, p) for k in k_values]\nanswer = 1 - binom.cdf(24,50, 0.25)\n\nprint(f'The probability to correctly guess half of the exam questions are approximately equal to {answer:.6%}')\n```\n\n The probability to correctly guess half of the exam questions are approximately equal to 0.012251%\n\n\nSo we can see that posibility to pass exam by sheer luck is not great. Let's look how Probability mass function looks like.\n\n\n```python\nimport matplotlib.pyplot as plt\n\n\nplt.bar(k_values, dist)\nplt.vlines(x, ymin= 0, ymax = 0.13, colors= \"red\")\nplt.xlabel(\"Number of correct guesses\")\nplt.ylabel(\"Probability, p\")\nplt.show()\n```\n", "meta": {"hexsha": "69e77631135115129894f3b3c08e706ac6eaa73a", "size": 11784, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Exam_binomial.ipynb", "max_stars_repo_name": "Dmusulas/Statistical-projects", "max_stars_repo_head_hexsha": "4877b9e8758335f5ed7c17de989dfe78928da506", "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": "Exam_binomial.ipynb", "max_issues_repo_name": "Dmusulas/Statistical-projects", "max_issues_repo_head_hexsha": "4877b9e8758335f5ed7c17de989dfe78928da506", "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": "Exam_binomial.ipynb", "max_forks_repo_name": "Dmusulas/Statistical-projects", "max_forks_repo_head_hexsha": "4877b9e8758335f5ed7c17de989dfe78928da506", "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.5862068966, "max_line_length": 8820, "alphanum_fraction": 0.8622708758, "converted": true, "num_tokens": 431, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9693241965169938, "lm_q2_score": 0.8918110418436166, "lm_q1q2_score": 0.8644540215800467}} {"text": "# Applications of Linear Programming\n\n\n```julia\nusing JuMP\nusing GLPK\n```\n\n## Economy\n\nA manufacturer produces four different products $X_1$, $X_2$, $X_3$ and $X_4$. There are three inputs to this production process:\n\n- labor in man weeks, \n- kilograms of raw material A, and \n- boxes of raw material B.\n\nEach product has different input requirements. In determining each week's production schedule, the manufacturer cannot use more than the available amounts of manpower and the two raw materials:\n\n|Inputs|$X_1$|$X_2$|$X_3$|$X_4$|Availabilities|\n|------|-----|-----|-----|-----|--------------|\n|Person-weeks|1|2|1|2|20|\n|Kilograms of material A|6|5|3|2|100|\n|Boxes of material B|3|4|9|12|75|\n|Production level|$x_1$|$x_2$|$x_3$|$x_4$| |\n\nThese constraints can be written in mathematical form\n\n\\begin{align}\nx_1+2x_2+x_3+2x_4\\le&20\\\\\n6x_1+5x_2+3x_3+2x_4\\le&100\\\\\n3x_1+4x_2+9x_3+12x_4\\le&75\n\\end{align}\n\nBecause negative production levels are not meaningful, we must impose the following nonnegativity constraints on the production levels:\n\n\\begin{equation}\nx_i\\ge0,\\qquad i=1,2,3,4\n\\end{equation}\n\nNow suppose that one unit of product $X_1$ sells for €6 and $X_2$, $X_3$ and $X_4$ sell for €4, €7 and €5, respectively. Then, the total revenue for any production decision $\\left(x_1,x_2,x_3,x_4\\right)$ is\n\n\\begin{equation}\nf\\left(x_1,x_2,x_3,x_4\\right)=6x_1+4x_2+7x_3+5x_4\n\\end{equation}\n\nThe problem is then to maximize $f$ subject to the given constraints.\n\n\n```julia\nmodel = Model(with_optimizer(GLPK.Optimizer, method = GLPK.SIMPLEX))\n@variable(model, 0 <= x1)\n@variable(model, 0 <= x2)\n@variable(model, 0 <= x3)\n@variable(model, 0 <= x4)\n@objective(model, Max, 6*x1 + 4*x2 + 7*x3 + 5*x4)\n@constraint(model, con1, x1 + 2*x2 + x3 + 2*x4 <= 20)\n@constraint(model, con2, 6*x1 + 5*x2 + 3*x3 + 2*x4 <= 100)\n@constraint(model, con3, 3*x1 + 4*x2 + 9*x3 + 12*x4 <= 75)\noptimize!(model)\n```\n\n\n```julia\ntermination_status(model)\n```\n\n\n```julia\nprimal_status(model)\n```\n\n\n```julia\nfor x in (x1, x2, x3, x4)\n println(\"$x = $(value(x))\")\nend\n```\n\n\n```julia\nobjective_value(model)\n```\n\n## Manufacturing\n\nA manufacturer produces two different products $X_1$ and $X_2$ using three machines $M_1$, $M_2$, and $M_3$. Each machine can be used only for a limited amount of time. Production times of each product on each machine are given by \n\n|Machine|Production time $X_1$|Production time $X_2$|Available time|\n|-------|---------------------|---------------------|--------------|\n|$M_1$ |1 |1 |8 |\n|$M_2$ |1 |3 |18 |\n|$M_3$ |2 |1 |14 |\n|Total |4 |5 | |\n\nThe objective is to maximize the combined time of utilization of all three machines.\n\nEvery production decision must satisfy the constraints on the available time. These restrictions can be written down using data from the table.\n\n\\begin{align}\nx_1+x_2&\\le8\\,,\\\\\nx_1+3x_2&\\le18\\,,\\\\\n2x_1+x_2&\\le14\\,,\n\\end{align}\n\nwhere $x_1$ and $x_2$ denote the production levels. The combined production time of all three machines is\n\n\\begin{equation}\nf\\left(x_1,x_2\\right)=4x_1+5x_2\\,.\n\\end{equation}\n\n\n```julia\nmodel = Model(with_optimizer(GLPK.Optimizer, method = GLPK.SIMPLEX))\n@variable(model, 0 <= x1)\n@variable(model, 0 <= x2)\n@objective(model, Max, 4*x1 + 5*x2)\n@constraint(model, con1, x1 + x2 <= 8)\n@constraint(model, con2, x1 + 3*x2 <= 18)\n@constraint(model, con3, 2*x1 + x2 <= 14)\noptimize!(model)\n```\n\n\n```julia\ntermination_status(model)\n```\n\n\n```julia\nprimal_status(model)\n```\n\n\n```julia\nfor x in (x1, x2)\n println(\"$x = $(value(x))\")\nend\n```\n\n\n```julia\nobjective_value(model)\n```\n\n## Transportation\n\nA manufacturing company has plants in cities A, B, and C. The company produces and distributes its product to dealers in various cities. On a particular day, the company has 30 units of its product in A, 40 in B, and 30 in C. The company plans to ship 20 units to D, 20 to E, 25 to F, and 35 to G, following orders received from dealers. The transportation costs per unit of each product between the cities are given by\n\n|From|To D|To E|To F|To G|Supply|\n|----|----|----|----|----|------|\n|A |7 |10 |14 |8 |30 |\n|B |7 |11 |12 |6 |40 |\n|C |5 |8 |15 |9 |30 |\n|Demand|20|20 |25 |35 |100 |\n\nIn the table, the quantities supplied and demanded appear at the right and along the bottom of the table. The quantities to be transported from the plants to different destinations are represented by the decision variables.\n\nThis problem can be stated in the form:\n\n\\begin{equation}\n\\min 7x_{AD}+10x_{AE}+14x_{AF}+8x_{AG}+7x_{BD}+11x_{BE}+12x_{BF}+6x_{BG}+5x_{CD}+8x_{CE}+15x_{CF}+9x_{CG}\n\\end{equation}\n\nsubject to\n\n\\begin{align}\nx_{AD}+x_{AE}+x_{AF}+x_{AG}&=30\\\\\nx_{BD}+x_{BE}+x_{BF}+x_{BG}&=40\\\\\nx_{CD}+x_{CE}+x_{CF}+x_{CG}&=30\\\\\nx_{AD}+x_{BD}+x_{CD}&=20\\\\\nx_{AE}+x_{BE}+x_{CE}&=20\\\\\nx_{AF}+x_{BF}+x_{CF}&=25\\\\\nx_{AG}+x_{BG}+x_{CG}&=35\n\\end{align}\n\nIn this problem, one of the constraint equations is redundant because it can be derived from the rest of the constraint equations. The mathematical formulation of the transportation problem is then in a linear programming form with twelve (3x4) decision variables and six (3 + 4—1) linearly independent constraint equations. Obviously, we also require nonnegativity of the decision variables, since a negative shipment is impossible and does not have any valid interpretation.\n\n\n```julia\nmodel = Model(with_optimizer(GLPK.Optimizer, method = GLPK.SIMPLEX))\n@variable(model, 0 <= x[1:3,1:4])\n@objective(model, Min, 7x[1,1]+10x[1,2]+14x[1,3]+8x[1,4]+7x[2,1]+11x[2,2]+12x[2,3]+6x[2,4]+5x[3,1]+8x[3,2]+15x[3,3]+9x[3,4])\n@constraint(model, con1, sum(x[1,j] for j in 1:4) == 30)\n@constraint(model, con2, sum(x[2,j] for j in 1:4) == 40)\n@constraint(model, con3, sum(x[3,j] for j in 1:4) == 30)\n@constraint(model, con4, sum(x[i,1] for i in 1:3) == 20)\n@constraint(model, con5, sum(x[i,2] for i in 1:3) == 20)\n@constraint(model, con6, sum(x[i,3] for i in 1:3) == 25)\n@constraint(model, con7, sum(x[i,4] for i in 1:3) == 35)\noptimize!(model)\n```\n\n\n```julia\ntermination_status(model)\n```\n\n\n```julia\nprimal_status(model)\n```\n\n\n```julia\nfor i in 1:3\n for j in 1:4\n println(\"x[$i,$j] = $(value(x[i,j]))\")\n end\nend\n```\n\n\n```julia\nobjective_value(model)\n```\n\nThis problem is an _integer linear programming_ problem, i.e. the solution components must be integers.\n\nWe can use the simplex method to find a solution to an ILP problem if the $m\\times n$ matrix $A$ is unimodular, i.e. if all its nonzero $m$th order minors are $\\pm 1$.\n\n## Electricity\n\nAn electric circuit is designed to use a 30 V source to charge 10 V, 6 V, and 20 V batteries connected in parallel. Physical constraints limit the currents $I_1$, $I_2$, $I_3$, $I_4$, and $I_5$ to a maximum of 4 A, 3 A, 3 A, 2 A, and 2 A, respectively. In addition, the batteries must not be discharged, that is, the currents $I_1$, $I_2$, $I_3$, $I_4$, and $I_5$ must not be negative. We wish to find the values of the currents $I_1$, $I_2$, $I_3$, $I_4$, and $I_5$ such that the total power transferred to the batteries is maximized.\n\nThe total power transferred to the batteries is the sum of the powers transferred to each battery, and is given by $10I_2 + 6I_4 + 20I_5$ W. From the circuit, we observe that the currents satisfy the constraints $I_1 = I_2 + I_3$, and $I_3 = I_4 + I_5$. Therefore, the problem can be posed as the following linear program:\n\n\\begin{equation}\n\\max 10I_2+6I_4+20I_5\n\\end{equation}\n\nsubject to\n\n\\begin{align}\nI_1 &= I_2 + I_3\\\\\nI_3 &= I_4 + I_5\\\\\nI_1 &\\le 4\\\\\nI_2 &\\le 3\\\\\nI_3 &\\le 3\\\\\nI_4 &\\le 2\\\\\nI_5 &\\le 2\\\\\n\\end{align}\n\n\n```julia\nmodel = Model(with_optimizer(GLPK.Optimizer, method = GLPK.SIMPLEX))\n@variable(model, 0 <= I[1:5])\n@objective(model, Max, 10*I[2]+6*I[4]+20I[5])\n@constraint(model, con1, I[1] == I[2] + I[3])\n@constraint(model, con2, I[3] == I[4] + I[5])\n@constraint(model, con3, I[1] <= 4)\n@constraint(model, con4, I[2] <= 3)\n@constraint(model, con5, I[3] <= 3)\n@constraint(model, con6, I[4] <= 2)\n@constraint(model, con7, I[5] <= 2)\noptimize!(model)\n```\n\n\n```julia\ntermination_status(model)\n```\n\n\n```julia\nprimal_status(model)\n```\n\n\n```julia\nfor i in 1:5\n println(\"I$i = $(value(I[i]))\")\nend\n```\n\n\n```julia\nobjective_value(model)\n```\n\n## Telecom\n\nConsider a wireless communication system. There are $n$ \"mobile\" users. For each $i$ in $1,\\dots, n$; user $i$ transmits a signal to the base station with power $P_i$ and an attenuation factor of $h_i$ (i.e., the actual received signal power at the basestation from user $i$ is $h_iP_i$). When the basestation is receiving from user $i$, the total received power from all other users is considered \"interference\" (i.e., the interference for user $i$ is $\\sum_{i\\ne j}h_jP_j$). For the communication with user $i$ to be reliable, the signal-to-interference ratio must exceed a threshold $\\gamma_i$, where the \"signal\" is the received power for user $i$.\n\nWe are interested in minimizing the total power transmitted by all the users subject to having reliable communications for all users. We can formulate the problem as a linear programming problem of the form\n\n\\begin{equation}\n\\min \\sum_iP_i\n\\end{equation}\n\nsubject to\n\n\\begin{equation}\n\\forall i \\in 1,\\dots,n\\,:\\,\\begin{cases}\n\\frac{h_iP_i}{\\sum_{i\\ne j}h_jP_j}\\ge\\gamma_i\\\\\nP_i\\ge0\n\\end{cases}\n\\end{equation}\n", "meta": {"hexsha": "0c83bf8fc74e17d91a59737dd5accd19418c9fce", "size": 14360, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Lectures/Lecture 7.ipynb", "max_stars_repo_name": "JuliaTagBot/ES313.jl", "max_stars_repo_head_hexsha": "3601743ca05bdb2562a26efd8b809c1a4f78c7b1", "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": "Lectures/Lecture 7.ipynb", "max_issues_repo_name": "JuliaTagBot/ES313.jl", "max_issues_repo_head_hexsha": "3601743ca05bdb2562a26efd8b809c1a4f78c7b1", "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/Lecture 7.ipynb", "max_forks_repo_name": "JuliaTagBot/ES313.jl", "max_forks_repo_head_hexsha": "3601743ca05bdb2562a26efd8b809c1a4f78c7b1", "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.8604118993, "max_line_length": 671, "alphanum_fraction": 0.5479108635, "converted": true, "num_tokens": 3254, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810496235896, "lm_q2_score": 0.9124361580958426, "lm_q1q2_score": 0.8644247251713548}} {"text": "# Python Number Theory 02 - Sequences\nThis tutorial demonstrate the generation of
\n- Aliquot Sequence,
\n- Fibonacci Sequence, and
\n- Hailstone Sequence\n\n## Example 01 - Aliquot Sequence\n\n### Part (a)\nWrite a function for summing the proper divisor (excluding the number itself) of the input.\n\n\n```python\ndef division_sum(r):\n x = 0\n for i in range(1,r):\n if (r % i == 0):\n x = i + x\n return x\n```\n\n\n```python\n# Testing Cell\ndivision_sum(6)\n```\n\n\n\n\n 6\n\n\n\n### Part (b)\n\nLet $\\sigma(x)$ be a function which returns the sum of proper divisor of $x$. (Note: $\\sigma(0) = 0$) The Aliquot Sequence $(s_n)$ with positive integer $k$ is defined as followed:\n- $s_0 = k$\n- $s_{n+1} = \\sigma(s_n)$ for all $n \\geq 0$.\n\nWrite an aliquot sequence function that returns intermediate values, and terminates either when 'max_iterations' has been reached or when it encounters a value that has occurred before.\n\n\n```python\ndef aliquot(r,max_iteration):\n rlist = [r]\n for i in range(max_iteration):\n r = division_sum(r)\n if r in rlist:\n break\n else:\n rlist.append(r)\n return rlist\n```\n\n\n```python\n# Test\naliquot(24,20)\n```\n\n\n\n\n [24, 36, 55, 17, 1, 0]\n\n\n\n## Example 02 - Fibonacci Sequence\nThe Fibonacci Sequence $F_n$ is defined as followed:\n- $F_1 = F_2 = 1$\n- $F_{n+2} = F_{n+1} + F_n$ for $n \\geq 1$\n\n### Part (a)\nWrite a iterative version of 'fibonacci' function which inputs positive integers $r$ and outputs a list of $F_1, F_2, ... F_r$.\n\n\n```python\ndef fibonacci1(r):\n if r == 1: # Base Case 1\n xlist = [1]\n elif r == 2: # Base Case 2\n xlist = [1,1]\n else:\n #Initialization\n xnminus1 = 1\n xnminus2 = 1\n xlist = [1,1]\n \n #Loop\n for i in range(r-2):\n x = xnminus1 + xnminus2\n xlist.append(x)\n xnminus2 = xnminus1\n xnminus1 = x\n return xlist\n```\n\n### Part (b)\nWrite a recursive function called 'fibonacci_recpair' that, given a positive integer $r$, returns the tuple $(F_{r-1}, F_r)$.\nHence write a version of 'fibonacci' function which calls 'fibonacci_recpair' and return $F_r$.\n\n\n```python\n# Fibonacci Number (Recursion with List)\ndef fibonacci_recpair(r):\n # Base case\n if r==1:\n return (0,1)\n elif r==2:\n return (1,1)\n \n # Recursive Step\n else:\n pair = fibonacci_recpair(r-1)\n return (pair[1], pair[0]+pair[1])\n```\n\n\n```python\n# Fibonacci Function\ndef fibonaccir(r):\n return fibonacci_recpair(r) [1]\n```\n\n### Part (c)\nUsing same idea, Write a recursive version of 'fibonacci' function which inputs positive integers $r$ and output $F_1, ..., F_r$.\n\n\n```python\n# Recursion\ndef fibonacci2(r):\n # Base Case\n if r==1:\n return [1]\n elif r==2:\n return [1,1]\n \n # Recursive Step\n else:\n xlist = fibonacci2(r-1)\n xlist.append(xlist[(r-1)-1] + xlist[(r-2)-1])\n return xlist\n```\n\n### Part (d)\nIn fact we can use sympy module to solve the recurrence relation. Using the solution of recurrence relation we could find a list of $F_1, ..., F_r$ given $r$. \n\n\n```python\n# Setup\nfrom sympy import symbols, Function, rsolve\nn, k = symbols('n k') # For defining variables 'n' and 'k'\nf = Function('f') # For defining functions\n```\n\n\n```python\n# Defining recurrence relation and solve it\nrelation = f(n) - f(n-1) - f(n-2) # Write the recurrence relation as '...' = 0 and let the input be '...'\nsol = rsolve(relation, f(n), {f(1):1, f(2):1}) # Initial Condition is given as dictionary with key 'f(n)'\nprint(sol)\n```\n\n sqrt(5)*(1/2 + sqrt(5)/2)**n/5 - sqrt(5)*(-sqrt(5)/2 + 1/2)**n/5\n\n\n\n```python\n# Fibonacci Function\ndef fibonacci3(r):\n xlist = [int(sol.evalf(subs={n:i})) for i in range(1,r+1)]\n return xlist\n```\n\n### Part (e)\nExplore how time module could measure the running time of a process. Use this module to test the performance of 'fibonacci1' to 'fibonacci3' against each other (both consistency and efficiency).\n\n\n```python\n# Input process_time from time module. This is for finding running time of a process\nfrom time import process_time\n```\n\n\n```python\nr = 30\n```\n\n\n```python\n# Version 1 (Iteration)\nstart1 = process_time()\na = fibonacci1(r)\nend1 = process_time()\nprint(a)\nprint(end1 - start1)\n```\n\n [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418, 317811, 514229, 832040]\n 0.0\n\n\n\n```python\n# Version R (Recursion of List)\ntuplef = fibonaccir(r)\nprint(tuplef)\n```\n\n 832040\n\n\n\n```python\n# Version 2 (Recursion)\nstart2 = process_time()\nb = fibonacci2(r)\nend2 = process_time()\nprint(b)\nprint(end2 - start2)\n```\n\n [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418, 317811, 514229, 832040]\n 0.0\n\n\n\n```python\n# Version 3 (Solution)\nstart3 = process_time()\nc = fibonacci3(r)\nend3 = process_time()\nprint(c)\nprint(end3 - start3)\n```\n\n [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418, 317811, 514229, 832040]\n 0.203125\n\n\n\n```python\n# Check Consistency\nprint(a==b and b==c)\n```\n\n True\n\n\n### Part (f)\nInvestigate $\\frac{F_{r+1}}{F_r}$ as $r$ increases.\n\n\n```python\ndef golden(r):\n flist = fibonacci1(r)\n ratio = [flist[i]/flist[i-1] for i in range(1,r)] \n return ratio\n```\n\n\n```python\nprint(golden(40))\n```\n\n [1.0, 2.0, 1.5, 1.6666666666666667, 1.6, 1.625, 1.6153846153846154, 1.619047619047619, 1.6176470588235294, 1.6181818181818182, 1.6179775280898876, 1.6180555555555556, 1.6180257510729614, 1.6180371352785146, 1.618032786885246, 1.618034447821682, 1.6180338134001253, 1.618034055727554, 1.6180339631667064, 1.6180339985218033, 1.618033985017358, 1.6180339901755971, 1.618033988205325, 1.618033988957902, 1.6180339886704431, 1.6180339887802426, 1.618033988738303, 1.6180339887543225, 1.6180339887482036, 1.6180339887505408, 1.6180339887496482, 1.618033988749989, 1.618033988749859, 1.6180339887499087, 1.6180339887498896, 1.618033988749897, 1.618033988749894, 1.6180339887498951, 1.6180339887498947]\n\n\n## Example 03 - Hailstone Sequence\n\nDefine a function $f$ for positive integer $n$. If $n$ is even, then $f(n) = \\frac{n}{2}$, otherwise $f(n) = 3n + 1$. The hailstone sequence $(a_n)$ for with positive integer $k$ is defined as followed:\n- $a_0$ = k\n- $a_{n+1} = f(a_n)$ for $n \\geq 0$\n\nIt is observed that $k = 1$, the sequence will be repeating in the pattern $1, 8, 4, 2, 1, 8, 4, 2, 1, ...$, and thus we can terminate the hailstone sequence when $a_n$ = 1. Write a hailstone sequence function that returns intermediate values, and terminates either when max_iterations has been reached or the value 1 is encountered. (Thinking question: will the sequence always end at 1?)\n\n\n```python\ndef hailstone(n, max_iterations):\n thelist = [n]\n for i in range(max_iterations):\n if n%2 == 0:\n n = n//2\n else:\n n = 3*n + 1\n thelist.append(n)\n if n == 1:\n break\n return(thelist)\n```\n\n\n```python\n# Test\nhailstone(7,20)\n```\n\n\n\n\n [7, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1]\n\n\n", "meta": {"hexsha": "cfcf7ee58fc3f33a5f8f0d93003cf540b10a4efd", "size": 13343, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "M1C (Python)/M1C-Number-Theory/Python Number Theory 02 - Sequences.ipynb", "max_stars_repo_name": "ImperialCollegeLondon/Random-Stuff", "max_stars_repo_head_hexsha": "219bc0e26ea6f5ee7548009c849959b268f54821", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-05-16T04:08:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-27T12:56:10.000Z", "max_issues_repo_path": "M1C (Python)/M1C-Number-Theory/Python Number Theory 02 - Sequences.ipynb", "max_issues_repo_name": "ImperialCollegeLondon/Random-Stuff", "max_issues_repo_head_hexsha": "219bc0e26ea6f5ee7548009c849959b268f54821", "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": "M1C (Python)/M1C-Number-Theory/Python Number Theory 02 - Sequences.ipynb", "max_forks_repo_name": "ImperialCollegeLondon/Random-Stuff", "max_forks_repo_head_hexsha": "219bc0e26ea6f5ee7548009c849959b268f54821", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-03-31T00:23:13.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-13T15:01:46.000Z", "avg_line_length": 25.3669201521, "max_line_length": 705, "alphanum_fraction": 0.5059581803, "converted": true, "num_tokens": 2556, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425399873764, "lm_q2_score": 0.9399133502467732, "lm_q1q2_score": 0.8643843007889871}} {"text": "# 15.5. A bit of number theory with SymPy\n\n\n```\nfrom sympy import *\nimport sympy.ntheory as nt\ninit_printing()\n```\n\n\n```\nnt.isprime(2017)\n```\n\n\n\n\n True\n\n\n\n\n```\nnt.nextprime(2017)\n```\n\n\n```\nnt.prime(1000)\n```\n\n\n```\nnt.primepi(2017)\n```\n\n\n```\nimport numpy as np\nimport matplotlib.pyplot as plt\n%matplotlib inline\nx = np.arange(2, 10000)\nfig, ax = plt.subplots(1, 1, figsize=(6, 4))\nax.plot(x, list(map(nt.primepi, x)), '-k',\n label='$\\pi(x)$')\nax.plot(x, x / np.log(x), '--k',\n label='$x/\\log(x)$')\nax.legend(loc=2)\n```\n\n\n```\nnt.factorint(1998)\n```\n\n\n```\n2 * 3**3 * 37\n```\n\n\n```\nfrom sympy.ntheory.modular import solve_congruence\nsolve_congruence((1, 3), (2, 4), (3, 5))\n```\n", "meta": {"hexsha": "bec5e8a8820cc76f30f9cbdee2743076f2328494", "size": 62727, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "chapter15_symbolic/05_number_theory.ipynb", "max_stars_repo_name": "guoci/cookbook-2nd-code", "max_stars_repo_head_hexsha": "1e6d8b1b66fcffa6362b13893bbd0e43f2829cb6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 645, "max_stars_repo_stars_event_min_datetime": "2018-02-01T09:16:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-03T17:47:59.000Z", "max_issues_repo_path": "chapter15_symbolic/05_number_theory.ipynb", "max_issues_repo_name": "dnzengou/cookbook-2nd-code", "max_issues_repo_head_hexsha": "85128694cdb9206b4325f95fe0060e01cf72e7f5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2019-03-11T09:47:21.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-11T06:32:00.000Z", "max_forks_repo_path": "chapter15_symbolic/05_number_theory.ipynb", "max_forks_repo_name": "dnzengou/cookbook-2nd-code", "max_forks_repo_head_hexsha": "85128694cdb9206b4325f95fe0060e01cf72e7f5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 418, "max_forks_repo_forks_event_min_datetime": "2018-02-13T03:17:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T21:04:45.000Z", "avg_line_length": 280.03125, "max_line_length": 45144, "alphanum_fraction": 0.9233822756, "converted": true, "num_tokens": 251, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9643214532237354, "lm_q2_score": 0.8962513828326955, "lm_q1q2_score": 0.8642744359470073}} {"text": "# Training the Neural Network\n\n$\\def\\abs#1{\\left\\lvert #1 \\right\\rvert}\n\\def\\Set#1{\\left\\{ #1 \\right\\}}\n\\def\\mc#1{\\mathcal{#1}}\n\\def\\M#1{\\boldsymbol{#1}}\n\\def\\R#1{\\mathsf{#1}}\n\\def\\RM#1{\\boldsymbol{\\mathsf{#1}}}\n\\def\\op#1{\\operatorname{#1}}\n\\def\\E{\\op{E}}\n\\def\\d{\\mathrm{\\mathstrut d}}$\n\n\n```python\n# init\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport tensorboard as tb\nimport torch\nimport torch.optim as optim\nfrom torch import Tensor, nn\nfrom torch.nn import functional as F\nfrom torch.utils.tensorboard import SummaryWriter\n\n%load_ext tensorboard\n%load_ext jdc\n%matplotlib inline\n\nSEED = 0\n\n# create samples\nXY_rng = np.random.default_rng(SEED)\nrho = 1 - 0.19 * XY_rng.random()\nmean, cov, n = [0, 0], [[1, rho], [rho, 1]], 1000\nXY = XY_rng.multivariate_normal(mean, cov, n)\n\nXY_ref_rng = np.random.default_rng(SEED)\ncov_ref, n_ = [[1, 0], [0, 1]], n\nXY_ref = XY_ref_rng.multivariate_normal(mean, cov_ref, n_)\n```\n\nWe will train a neural network with `torch` and use GPU if available:\n\n\n```python\nDEVICE = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n\nif DEVICE == \"cuda\": # print current GPU name if available\n print(\"Using GPU:\", torch.cuda.get_device_name(torch.cuda.current_device()))\n```\n\nWhen GPU is available, you can use [GPU dashboards][gpu] on the left to monitor GPU utilizations.\n\n[gpu]: https://github.com/rapidsai/jupyterlab-nvdashboard\n\n\n\n**How to train a neural network by gradient descent?**\n\nWe will first consider a simple implementation followed by a more practical implementation.\n\n## A simple implementation of gradient descent\n\nConsider solving for a given $z\\in \\mathbb{R}$,\n\n$$ \\inf_{w\\in \\mathbb{R}} \\overbrace{e^{w\\cdot z}}^{L(w):=}.$$\n\nWe will train one parameter, namely, $w$, to minimize the loss $L(w)$.\n\n**Exercise** \n\nWhat is the solution for $z=-1$?\n\nYOUR ANSWER HERE\n\n**How to implement the loss function?**\n\nWe will define the loss function using tensors:\n\n\n```python\nz = Tensor([-1]).to(DEVICE) # default tensor type on a designated device\n\n\ndef L(w):\n return (w * z).exp()\n\n\nL(float(\"inf\"))\n```\n\nThe function `L` is vectorized because `Tensor` operations follow the [broadcasting rules of `numpy`](https://numpy.org/doc/stable/user/basics.broadcasting.html):\n\n\n```python\nww = np.linspace(0, 10, 100)\nax = sns.lineplot(\n x=ww,\n y=L(Tensor(ww).to(DEVICE)).cpu().numpy(), # convert to numpy array for plotting\n)\nax.set(xlabel=r\"$w$\", title=r\"$L(w)=e^{-w}$\")\nax.axhline(L(float(\"inf\")), ls=\"--\", c=\"r\")\nplt.show()\n```\n\n**What is gradient descent?**\n\nA gradient descent algorithm updates the parameter $w$ iteratively starting with some initial $w_0$:\n\n$$w_{i+1} = w_i - s_i \\nabla L(w_i) \\qquad \\text{for }i\\geq 0,$$\n\nwhere $s_i$ is the *learning rate* (*step size*).\n\n**How to compute the gradient?**\n\nWith $w=0$, \n\n$$\\nabla L(0) = \\left.-e^{-w}\\right|_{w=0}=-1,$$ \n\nwhich can be computed using `backward` ([backpropagation][bp]):\n\n[bp]: https://en.wikipedia.org/wiki/Backpropagation\n\n\n```python\nw = Tensor([0]).to(DEVICE).requires_grad_() # requires gradient calculation for w\nL(w).backward() # calculate the gradient by backpropagation\nw.grad\n```\n\nUnder the hood, the function call `L(w)` \n\n- not only return the loss function evaluated at `w`, but also\n- updates a computational graph for calculating the gradient since `w` `requires_grad_()`.\n\n**How to implement the gradient descent?**\n\nWith a learning rate of `0.001`:\n\n\n```python\nfor i in range(1000):\n w.grad = None # zero the gradient to avoid accumulation\n L(w).backward()\n with torch.no_grad(): # updates the weights in place without gradient calculation\n w -= w.grad * 1e-3\n\nprint(\"w:\", w.item(), \"\\nL(w):\", L(w).item())\n```\n\n**What is `torch.no_grad()`?**\n\nIt sets up a context where the computational graph will not be updated. In particular,\n\n```Python\nw -= w.grad * 1e-3\n```\n\nshould not be differentiated in the subsequent calculations of the gradient.\n\n[no_grad]: https://pytorch.org/docs/stable/generated/torch.no_grad.html\n\n**Exercise** \n\nRepeatedly run the above cell until you get `L(w)` below `0.001`. How large is the value of `w`? What is the limitations of the simple gradient descent algorithm?\n\nYOUR ANSWER HERE\n\n## A practical implementation\n\nFor a neural network to approximate a sophisticated function, it should have many parameters (*degrees of freedom*).\n\n**How to define a neural network?**\n\nThe following code [defines a simple neural network][define] with 3 fully-connected (fc) hidden layers:\n\n \n\nwhere \n\n- $\\M{W}_l$ and $\\M{b}_l$ are the weight and bias respectively for the linear transformation $\\M{W}_l \\M{a}_l + \\M{b}_l$ of the $l$-th layer; and\n- $\\sigma$ for the first 2 hidden layers is an activation function called the [*exponential linear unit (ELU)*](https://pytorch.org/docs/stable/generated/torch.nn.ELU.html).\n\n[define]: https://pytorch.org/tutorials/beginner/blitz/neural_networks_tutorial.html#define-the-network\n\n\n```python\nclass Net(nn.Module):\n def __init__(self, input_size=2, hidden_size=100, sigma=0.02):\n super().__init__()\n self.fc1 = nn.Linear(input_size, hidden_size) # fully-connected (fc) layer\n self.fc2 = nn.Linear(hidden_size, hidden_size) # layer 2\n self.fc3 = nn.Linear(hidden_size, 1) # layer 3\n nn.init.normal_(self.fc1.weight, std=sigma) #\n nn.init.constant_(self.fc1.bias, 0)\n nn.init.normal_(self.fc2.weight, std=sigma)\n nn.init.constant_(self.fc2.bias, 0)\n nn.init.normal_(self.fc3.weight, std=sigma)\n nn.init.constant_(self.fc3.bias, 0)\n\n def forward(self, z):\n a1 = F.elu(self.fc1(z))\n a2 = F.elu(self.fc2(a1))\n t = self.fc3(a2)\n return t\n\n\ntorch.manual_seed(SEED) # seed RNG for PyTorch\nnet = Net().to(DEVICE)\nprint(net)\n```\n\nThe neural network is also a vectorized function. E.g., the following call `net` once to plots the density estimate of all $t(\\R{Z}_i)$'s and $t(\\R{Z}'_i)$'s.\n\n\n```python\nZ = Tensor(XY).to(DEVICE)\nZ_ref = Tensor(XY_ref).to(DEVICE)\n\ntZ = (\n net(torch.cat((Z, Z_ref), dim=0)) # compute t(Z_i)'s and t(Z'_i)\n # output needs to be converted back to an array on CPU for plotting\n .cpu() # copy back to CPU\n .detach() # detach from current graph (no gradient calculation)\n .numpy() # convert output back to numpy\n)\n\ntZ_df = pd.DataFrame(data=tZ, columns=[\"t\"])\nsns.kdeplot(data=tZ_df, x=\"t\")\nplt.show()\n```\n\nFor 2D sample $(x,y)\\in \\mc{Z}$, we can plot the neural network $t(x,y)$ as a heatmap. The following code adds a method `plot` to `Net` using [`jdc`](https://alexhagen.github.io/jdc):\n\n\n```python\n%%add_to Net\ndef plot(net, xmin=-5, xmax=5, ymin=-5, ymax=5, xgrids=50, ygrids=50, ax=None):\n \"\"\"Plot a heat map of a neural network net. net can only have two inputs.\"\"\"\n x, y = np.mgrid[xmin : xmax : xgrids * 1j, ymin : ymax : ygrids * 1j]\n xy = np.concatenate((x[:, :, None], y[:, :, None]), axis=2)\n with torch.no_grad():\n z = (\n net(\n torch.cat(\n [\n Tensor(x.reshape(-1, 1)).to(DEVICE),\n Tensor(y.reshape(-1, 1)).to(DEVICE),\n ],\n dim=-1,\n )\n )\n .reshape(x.shape)\n .cpu()\n )\n if ax is None:\n ax = plt.gca()\n im = ax.pcolormesh(x, y, z, cmap=\"RdBu_r\", shading=\"auto\")\n ax.figure.colorbar(im)\n ax.set(xlabel=r\"$x$\", ylabel=r\"$y$\", title=r\"Heatmap of $t(z)$ for $z=(x,y)$\")\n```\n\nTo plot the heatmap:\n\n\n```python\nnet.plot()\n```\n\n**Exercise** \n\nWhy are the values of $t(\\R{Z}_i)$'s and $t(\\R{Z}'_i)$'s concentrated around $0$?\n\nYOUR ANSWER HERE\n\n**How to implements the divergence estimate?**\n\nWe decompose the approximate divergence lower bound in {eq}`avg-DV` as follows:\n\n$$\n\\begin{align}\n\\op{DV}(\\R{Z}^n,\\R{Z'}^{n'},\\theta) &:= \\underbrace{\\frac1{n} \\sum_{i\\in [n]} t(\\R{Z}_i)}_{\\text{(a)}} - \\underbrace{\\log \\frac1{n'} \\sum_{i\\in [n']} e^{t(\\R{Z}'_i)}}_{ \\underbrace{\\log \\sum_{i\\in [n']} e^{t(\\R{Z}'_i)}}_{\\text{(b)}} - \\underbrace{\\log n'}_{\\text{(c)}}} \n\\end{align}\n$$\n\nwhere $\\theta$ is a tuple of parameters (weights and biases) of the neural network that computes $t$:\n\n$$\n\\theta := (\\M{W}_l,\\M{b}_l|l\\in [3]).\n$$\n\n\n```python\ndef DV(Z, Z_ref, net):\n avg_tZ = net(Z).mean() # (a)\n log_avg_etZ_ref = net(Z_ref).logsumexp(dim=0) - np.log(Z_ref.shape[0]) # (b) - (c)\n return avg_tZ - log_avg_etZ_ref\n\n\nDV_estimate = DV(Z, Z_ref, net)\n```\n\n**Exercise** \n\nWhy is it preferrable to use `logsumexp(dim=0)` instead of `.exp().sum().log()`? Try running\n\n```Python\nTensor([100]).exp().log(), Tensor([100]).logsumexp(0)\n```\n\nin a separate console.\n\nYOUR ANSWER HERE\n\nTo calculate the gradient of the divergence estimate with respect to $\\theta$:\n\n\n```python\nnet.zero_grad() # zero the gradient values of all neural network parameters\nDV(Z, Z_ref, net).backward() # calculate the gradient\na_param = next(net.parameters())\n```\n\n`a_param` is a (module) parameter in $\\theta$ retrieved from the parameter iterator `parameters()`.\n\n**Exercise** \n\nCheck that the value of `a_param.grad` is non-zero. Is `a_param` a weight or a bias?\n\nYOUR ANSWER HERE\n\n**How to gradient descend?**\n\nWe will use the [*Adam's* gradient descend algorithm][adam] implemented as an optimizer [`optim.Adam`][optimAdam]:\n\n[adam]: https://en.wikipedia.org/wiki/Stochastic_gradient_descent#cite_note-Adam2014-28\n[optimAdam]: https://pytorch.org/docs/stable/generated/torch.optim.Adam.html#torch.optim.Adam\n\n\n```python\nnet = Net().to(DEVICE)\noptimizer = optim.Adam(\n net.parameters(), lr=1e-3\n) # Allow Adam's optimizer to update the neural network parameters\noptimizer.step() # perform one step of the gradient descent\n```\n\nTo alleviate the problem of overfitting, the gradient is often calculated on randomly chosen batches:\n\n$$\n\\begin{align}\n\\R{L}(\\theta) := - \\bigg[\\frac1{\\abs{\\R{B}}} \\sum_{i\\in \\R{B}} t(\\R{Z}_i) - \\log \\frac1{\\abs{\\R{B}'}} \\sum_{i\\in \\R{B}'} e^{t(\\R{Z}'_i)} - \\log \\abs{\\R{B}'} \\bigg],\n\\end{align}\n$$\n\nwhich is the negative lower bound of the VD formula in {eq}`DV` but on the minibatches \n\n$$\\R{Z}_{\\R{B}}:=(\\R{Z}_i\\mid i\\in \\R{B})\\quad \\text{and}\\quad \\R{Z}'_{\\R{B}'}$$\n\nwhere $\\R{B}$ and $\\R{B}'$ are batches of uniformly randomly chosen indices from $[n]$ and $[n']$ respectively.\n\nThe neural network parameter is updated\n\n$$\n\\theta_{j+1} := \\theta_j - s_j \\nabla \\R{L}_j(\\theta_j),\n$$\n\nstarting with a randomly initialized $\\theta_0$ \nwhere $s_j>0$ is the learning rate and $\\R{L}_j$ is the loss evaluated on the $j$-th randomly chosen batches $\\R{B}_j$ and $\\R{B}'_j$.\n\nThe different batches are often obtained by \n- permuting the samples first, and then\n- partitioning the samples into batches.\n\nThis is illustrated by the figure below:\n\n\n\n\n```python\nn_iters_per_epoch = 10 # ideally a divisor of both n and n'\nbatch_size = int((Z.shape[0] + 0.5) / n_iters_per_epoch)\nbatch_size_ref = int((Z_ref.shape[0] + 0.5) / n_iters_per_epoch)\n```\n\nWe will use `tensorboard` to show the training logs. \nRerun the following to start a new log, for instance, after a change of parameters.\n\n\n```python\nif input(\"New log?[Y/n] \").lower() != \"n\":\n n_iter = n_epoch = 0 # keep counts for logging\n writer = SummaryWriter() # create a new folder under runs/ for logging\n```\n\nThe following code carries out Adam's gradient descent on batch loss:\n\n\n```python\nif input(\"Train? [Y/n]\").lower() != \"n\":\n for i in range(10): # loop through entire data multiple times\n n_epoch += 1\n\n # random indices for selecting samples for all batches in one epoch\n idx = torch.randperm(Z.shape[0])\n idx_ref = torch.randperm(Z_ref.shape[0])\n\n for j in range(n_iters_per_epoch): # loop through multiple batches\n n_iter += 1\n optimizer.zero_grad()\n\n # obtain a random batch of samples\n batch_Z = Z[idx[j : Z.shape[0] : n_iters_per_epoch]]\n batch_Z_ref = Z_ref[idx_ref[j : Z_ref.shape[0] : n_iters_per_epoch]]\n\n # define the loss as negative DV divergence lower bound\n loss = -DV(batch_Z, batch_Z_ref, net)\n loss.backward() # calculate gradient\n optimizer.step() # descend\n\n writer.add_scalar(\"Loss/train\", loss.item(), global_step=n_epoch)\n\n # Estimate the divergence using all data\n with torch.no_grad():\n estimate = DV(Z, Z_ref, net).item()\n writer.add_scalar(\"Estimate\", estimate, global_step=n_epoch)\n net.plot()\n print(\"Divergence estimation:\", estimate)\n```\n\nRun the following to show the losses and divergence estimate in `tensorboard`. You can rerun the above cell to train the neural network more.\n\n\n```python\n%tensorboard --logdir=runs\n```\n\nThe ground truth is given by\n\n$$D(P_{\\R{Z}}\\|P_{\\R{Z}'}) = \\frac12 \\log(1-\\rho^2) $$\n\nwhere $\\rho$ is the randomly generated correlation in the previous notebook. \n\n**Exercise** \n\nCompute the ground truth using the formula above.\n\n\n```python\n# YOUR CODE HERE\nraise NotImplementedError()\nground_truth\n```\n\n**Exercise** \n\nSee if you can get an estimate close to this value by training the neural network repeatedly as shown below.\n\n\n\n## Encapsulation\n\nIt is a good idea to encapsulate the training by a class, so multiple configurations can be run without interfering each other:\n\n\n```python\nclass DVTrainer:\n \"\"\"\n Neural estimator for KL divergence based on the sample DV lower bound.\n\n Estimate D(P_Z||P_Z') using samples Z and Z' by training a network t to maximize\n avg(t(Z)) - log avg(e^t(Z'))\n\n Parameters:\n ----------\n\n Z, Z_ref : Tensors with first dimension indicing the samples of Z and Z' respect.\n net : The neural network t that take Z as input and output a real number for each sample.\n n_iters_per_epoch : Number of iterations per epoch.\n writer_params : Parameters to be passed to SummaryWriter for logging.\n \"\"\"\n\n # constructor\n def __init__(self, Z, Z_ref, net, n_iters_per_epoch, writer_params={}, **kwargs):\n self.Z = Z\n self.Z_ref = Z_ref\n self.net = net\n self.n_iters_per_epoch = n_iters_per_epoch # ideally a divisor of both n and n'\n\n # set optimizer\n self.optimizer = optim.Adam(net.parameters(), **kwargs)\n\n # logging\n self.writer = SummaryWriter(\n **writer_params\n ) # create a new folder under runs/ for logging\n self.n_iter = self.n_epoch = 0 # keep counts for logging\n\n def step(self, epochs=1):\n \"\"\"\n Carries out the gradient descend for a number of epochs and returns\n the divergence estimate evaluated over the entire data.\n\n Loss for each epoch is recorded into the log, but only one divergence\n estimate is computed/logged using the entire dataset. Rerun the method,\n using a loop, to continue to train the neural network and log the result.\n\n Parameters:\n ----------\n epochs : number of epochs\n \"\"\"\n for i in range(epochs):\n self.n_epoch += 1\n\n # random indices for selecting samples for all batches in one epoch\n idx = torch.randperm(self.Z.shape[0])\n idx_ref = torch.randperm(self.Z_ref.shape[0])\n\n for j in range(self.n_iters_per_epoch):\n self.n_iter += 1\n self.optimizer.zero_grad()\n\n # obtain a random batch of samples\n batch_Z = self.Z[idx[i : self.Z.shape[0] : self.n_iters_per_epoch]]\n batch_Z_ref = self.Z_ref[\n idx_ref[i : self.Z_ref.shape[0] : self.n_iters_per_epoch]\n ]\n\n # define the loss as negative DV divergence lower bound\n loss = -DV(batch_Z, batch_Z_ref, self.net)\n loss.backward() # calculate gradient\n self.optimizer.step() # descend\n\n self.writer.add_scalar(\n \"Loss/train\", loss.item(), global_step=self.n_iter\n )\n\n with torch.no_grad():\n estimate = DV(Z, Z_ref, self.net).item()\n self.writer.add_scalar(\"Estimate\", estimate, global_step=self.n_epoch)\n return estimate\n```\n\nTo use the above class to train, we first create an instance:\n\n\n```python\ntorch.manual_seed(SEED)\nnet = Net().to(DEVICE)\ntrainer = DVTrainer(Z, Z_ref, net, n_iters_per_epoch=10)\n```\n\nNext, run `step` iteratively to train the neural network:\n\n\n```python\nif input(\"Train? [Y/n]\").lower() != \"n\":\n for i in range(10):\n print(\"Divergence estimate:\", trainer.step(10))\n net.plot()\n```\n\n\n```python\n%tensorboard --logdir=runs\n```\n\n## Clean-up\n\nIt is important to release the resources if it is no longer used. You can release the memory or GPU memory by `Kernel->Shut Down Kernel`.\n\nTo clear the logs:\n\n\n```python\nif input('Delete logs? [y/N]').lower() == 'y':\n !rm -rf ./runs\n```\n\nTo kill a tensorboard instance without shutting down the notebook kernel:\n\n\n```python\ntb.notebook.list() # list all the running TensorBoard notebooks.\nwhile (pid := input('pid to kill? (press enter to exit)')):\n !kill {pid}\n```\n", "meta": {"hexsha": "a7f329b648869df50e90657bf1703e1521ba4393", "size": 152182, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "part1/Training.ipynb", "max_stars_repo_name": "ccha23/cscit21", "max_stars_repo_head_hexsha": "87de8c48c640406d9a9d282fc10a238122814f53", "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": "part1/Training.ipynb", "max_issues_repo_name": "ccha23/cscit21", "max_issues_repo_head_hexsha": "87de8c48c640406d9a9d282fc10a238122814f53", "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": "part1/Training.ipynb", "max_forks_repo_name": "ccha23/cscit21", "max_forks_repo_head_hexsha": "87de8c48c640406d9a9d282fc10a238122814f53", "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": 111.5703812317, "max_line_length": 69604, "alphanum_fraction": 0.8581106833, "converted": true, "num_tokens": 4747, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850110816423, "lm_q2_score": 0.9230391706552538, "lm_q1q2_score": 0.8642277401257442}} {"text": "# Problems for Computing Laboratory Using Python\n\n## Problem statement 1\nDetermine the rms value of the current given by\n\n\\begin{align}\ni(t) & = 5 \\exp^{-1.25t}\\sin(2 \\pi t) \\quad 0 \\leq t \\leq T/2 \\\\\ni(t) & = 0 \\quad T/2 \\leq t \\leq T \n\\end{align}\n\nRoot Mean Square value of the current is defined as:\n$$\\sqrt{\\frac{1}{T}\\int_0^T i^2 dt}$$\n\nFor the above said case it is given by\n$$\\sqrt{\\frac{1}{T}\\int_0^{T/2} i^2 dt}$$\n\nFor Simpson's $\\frac{1}{3}$ rule,\n\n$$ I = (b-a) \\frac{f(x_0) + 4 \\sum_{i=1,3,5..}^{n-1} f(x_i) + 2 \\sum_{j=2,4,6..}^{n-2}f(x_j) + f(x_n)}{3n}$$\n\nAs an example, let us find the definite integral of the following function: $f(x) = 0.2+25x-200x^2+675x^3-900x^4+400x^5$ from 0 to 0.8\n\n\n```python\nfrom __future__ import division, print_function\n\nimport numpy as np\nimport scipy.integrate as sp\n\nlo_limit = 0.0; up_limit = 0.8; n = 25; total = 0.0; z1 = 0.0; z2 = 0.0;\n#\na = np.linspace(lo_limit, up_limit, n)\ny = lambda x: 0.2 + (25 * x) - (200 * x**2) + (675 * x**3) - (900 * x**4) + (400 * x**5)\n#a = np.linspace(0, 2*np.pi, n)\n#y = lambda x: np.sin(x)\n#y = lambda x: np.exp(-1.5*x)*sin(2*np.pi*x) ** 2\nb = y(a)\nfor i in range(1, n, 2):\n z1 = z1 + 4 * b[i]\nfor i in range(2, n-1, 2):\n z2 = z2 + 2 * b[i]\ntotal = b[0] + b[n-1] + z1 + z2\nint_value = ((up_limit-lo_limit))*total/(3*(n-1))\nprint (int_value)\n#Using Scipy.integrate module\nint_value1 = sp.simps(b, a)\nprint(int_value1)\n```\n\n 1.64052016461\n 1.64052016461\n\n\n#Solution of Single order differential equation\n\n### Problem statement 2\nFor a simple RL circuit, Kirchoff’s voltage law requires that\n\n$$V = iR+L\\frac{di}{dt}$$ with R = 1.5 $\\Omega$, $L=1 H$, and $V=100$\n\n$$\\frac{di}{dt} = (100-iR)\\frac{1}{L}$$\n\n## Using Implicit Euler's Method\n\n\n\n\\begin{align}\ni_{n+1} &= i_n+\\frac{di_{n+1}}{dt} h \\\\\ni_{n+1} &= i_n+\\left(100-i_{n+1}R \\right)\\frac{h}{L} \\\\\ni_{n+1}\\left(1+\\frac{R}{L}h\\right) &= i_n+\\frac{100 h}{L} \\\\\ni_{n+1} &= \\frac{i_n+\\frac{100 h}{L}}{1+\\frac{R}{L}h}\n\\end{align}\n\n\n```python\n%matplotlib inline\nfrom __future__ import division, print_function\n#\nimport numpy as np\nimport matplotlib.pyplot as plt\n#\nind = 1.0; res = 1.5; volt = 100.0; i0 = 0.5; \nini_t = 0; final_t = 1.0; no = 51; t = ini_t\ntime = np.zeros(no, dtype=float); cur = np.zeros(no, dtype=float);\nh = float((final_t-ini_t)/no)\n# \ncount = np.linspace(ini_t, final_t, no)\nfor i in range(len(count)):\n time[i] = t\n cur[i] = i0\n i1 = (i0 + (volt/ind) * h)/(1+(res/ind)*h)\n i0 = i1\n t = ini_t + (i+1) * h\n#\nplt.plot (time, cur)\nplt.grid(True)\nplt.xlabel('t (s)')\nplt.ylabel('i (A)')\nplt.show()\n```\n\n\n```python\n%matplotlib inline\nimport numpy as np\nfrom scipy.integrate import odeint\nimport matplotlib.pyplot as plt\n\ndef deriv(y, t):\n ydot = np.array(100-y[0]*1.5)\n return ydot\n\ntstart = 0\ntend = 5.0\nnumint = 1000\nt = np.linspace(tstart, tend, numint+1)\nyinit = np.array([0.5])\ny = odeint(deriv, yinit, t)\n\nplt.plot(t, y[:, 0])\nplt.grid()\nplt.xlabel('t (s)')\nplt.ylabel('i (A)')\nplt.show()\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "27df39b742ebaec8cc1becbe34d503fb96fb4724", "size": 29530, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "bvbcet/10_example_EE.ipynb", "max_stars_repo_name": "satish-annigeri/Notebooks", "max_stars_repo_head_hexsha": "92a7dc1d4cf4aebf73bba159d735a2e912fc88bb", "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": "bvbcet/10_example_EE.ipynb", "max_issues_repo_name": "satish-annigeri/Notebooks", "max_issues_repo_head_hexsha": "92a7dc1d4cf4aebf73bba159d735a2e912fc88bb", "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": "bvbcet/10_example_EE.ipynb", "max_forks_repo_name": "satish-annigeri/Notebooks", "max_forks_repo_head_hexsha": "92a7dc1d4cf4aebf73bba159d735a2e912fc88bb", "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": 107.3818181818, "max_line_length": 11994, "alphanum_fraction": 0.8478835083, "converted": true, "num_tokens": 1216, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.936285002192296, "lm_q2_score": 0.9230391717138003, "lm_q1q2_score": 0.8642277329116307}} {"text": "# Regression\n\n## 1.Linear models\n\n***\n\n* Formulation\n\n***\n\nAssume instance $ \\mathbf{x} = (x_1, x_2, ... , x_d)^T $, here $T$ means the matrix transpose. Linear model use linear combination of all attributes to do prediction.\n\n\\begin{equation}\nf(\\mathbf{x}) = w_1x_1 + w_2x_2 + ... + w_dx_d + b, \\tag{1}\n\\end{equation}\n\nor\n\n\\begin{equation}\n f(\\mathbf{x}) = \\mathbf{w}^T\\mathbf{x} + b. \\tag{2}\n\\end{equation}\n\n***\n\n* Linear regression\n\n***\n\nUse the linear model to obtain the relationship between the dependent variable (test results, $y_i$) and independent variables (selected features, $x_i$). If only one explanatory variable is considered, it is called simple linear regression, for more than one, it is called multiple linear regression. If multiple dependent variables are considered, it is called multivariate linear regression. Let's start with the simple linear regression.\n\nGiven $x_i$ and $y_i$, how to find w and b so that $f(x_i) = wx_i + b \\rightarrow y_i$?\n\nWe may use the least square approach:\n\n$(w^* , b^*) = \\underset{(w , b)}{\\arg\\min} \\sum\\limits_{i=1}^m (f(x_i) - y_i)^2 = \\underset{(w , b)}{\\arg\\min} \\sum\\limits_{i=1}^m (y_i - wx_i - b)^2$, here $m$ means we have $m$ instances.\n\nLet's set\n$E_{(w, b)} = \\sum\\limits_{i=1}^m (y_i - wx_i - b)^2$, here $E_{(w, b)}$ is the cost function. \n\nPerform parameter estimation of least square approach\n\n\\begin{equation}\n \\frac{\\partial E}{\\partial w} = 2 \\left( w \\sum\\limits_{i=1}^m x_i^2 - \\sum\\limits_{i=1}^m (y_i - b)x_i \\right) = 0, \\tag{3}\n\\end{equation}\n\n\\begin{equation}\n \\frac{\\partial E}{\\partial b} = 2 \\left( mb - \\sum\\limits_{i=1}^m (y_i - wx_i) \\right) = 0. \\tag{4}\n\\end{equation}\n\nWe then have\n\n\\begin{equation}\n w = \\frac{ \\sum\\limits_{i=1}^m y_i (x_i - \\frac{1}{m}\\sum\\limits_{i=1}^m x_i )}{\\sum\\limits_{i=1}^m x_i^2 - \\frac{1}{m} \\left( \\sum\\limits_{i=1}^m x_i \\right)^2}, \\tag{5}\n\\end{equation}\n\n\\begin{equation}\n b = \\frac{1}{m}\\sum\\limits_{i=1}^m (y_i - w x_i). \\tag{6}\n\\end{equation}\n\nSimilarly, the cost function for multiple variables (let's say d varaibles) is: $E_{(\\mathbf{w}, b)} = E_{(w_1, w_2, ..., w_d, b)} = \\sum\\limits_{i=1}^m (y_i - \\mathbf{w}^T\\mathbf{x} - b)^2$. Combine coeficients $\\mathbf{w}$ and $b$, we obtain a new vector $\\hat{\\mathbf{w}} = (\\mathbf{w} ; b)$. The dataset $\\mathbf{XX}$ with the size $m \\times (d+1)$ can be read as \n\n\\begin{equation}\n\\mathbf{XX} = \\begin{pmatrix}\nx_{11} & x_{12} & ... & x_{1d}\\\\\nx_{21} & x_{22} & ... & x_{2d}\\\\\n\\vdots & \\vdots & \\ddots & \\vdots \\\\\nx_{m1} & x_{m2} & ... & x_{md}\n\\end{pmatrix} = \\begin{pmatrix}\n\\mathbf{x_{1}^T} & 1 \\\\\n\\mathbf{x_{2}^T} & 1 \\\\\n\\vdots & \\vdots \\\\\n\\mathbf{x_{m}^T} & 1\n\\end{pmatrix}. \\tag{7}\n\\end{equation}\n\nThe label vector is $\\mathbf{y} = (y_1; y_2; ...; y_m)$. Based on least square method, we need obtain the following\n\n\\begin{equation}\n\\mathbf{\\hat{w}}^* = \\underset{\\mathbf{\\hat{w}}}{\\arg\\min} (\\mathbf{y} - \\mathbf{XX\\hat{w}})^T (\\mathbf{y} - \\mathbf{XX\\hat{w}}). \\tag{8}\n\\end{equation}\n\nLet $E_{\\mathbf{\\hat{w}}} = (\\mathbf{y} - \\mathbf{XX\\hat{w}})^T (\\mathbf{y} - \\mathbf{XX\\hat{w}})$, then the derivative w.r.t. $\\mathbf{\\hat{w}}$ is\n\n\\begin{equation}\n\\frac{\\partial E_{\\mathbf{\\hat{w}}}}{\\partial \\mathbf{\\hat{w}}} = 2\\mathbf{XX}^T (\\mathbf{XX}\\mathbf{\\hat{w}} - \\mathbf{y}) . \\tag{9}\n\\end{equation}\n\nWe then use Gradient Descent method to iterativly update the unknown coefficients\n\n\\begin{equation}\n\\mathbf{\\hat{w}}^{(n+1)} = \\mathbf{\\hat{w}}^{(n)} - \\left ( \\alpha \\frac{\\partial E_{\\mathbf{\\hat{w}}}}{\\partial \\mathbf{\\hat{w}}} \\right)^n. \\tag{10}\n\\end{equation}\n\n***\n\n* Hand-on example\n\n***\n\n\n```python\nimport numpy as np \nimport pandas as pd \nimport math as m\nimport matplotlib.pyplot as plt \n\ndef train_test_split(X, Y, train_size, shuffle):\n ''' Perform tran/test datasets splitting '''\n if shuffle:\n randomize = np.arange(len(X))\n np.random.shuffle(randomize)\n X = X[randomize]\n Y = Y[randomize]\n s_id = int(len(Y) * train_size)\n X_train, X_test = X[:s_id], X[s_id:]\n Y_train, Y_test = Y[:s_id], Y[s_id:]\n\n return X_train, X_test, Y_train, Y_test \n\n\ndef metric_mse(Y_label, Y_pred):\n ''' Evaluate mean squared error (MSE) '''\n return np.mean(np.power(Y_label - Y_pred, 2))\n\ndef metric_rmse(Y_label, Y_pred):\n ''' Evaluate root mean squared error (RMSE) '''\n return m.sqrt(np.mean(np.power(Y_label - Y_pred, 2)))\n\ndef readin_data(path):\n ''' Evaluate root mean squared error (RMSE) '''\n df = pd.read_csv(path) \n X = df.iloc[:,:-1].values \n Y = df.iloc[:,1].values \n return X, Y\n \ndef generate_dataset_simple(beta, n, std_dev):\n ''' Generate dataset '''\n X = np.random.rand(n)\n e = np.random.randn(n) * std_dev\n Y = X * beta + e\n X = X.reshape((n,1))\n return X, Y \n\nclass LinearRegression() : \n ''' Linear Regression model. \n Used to obtain the relationship between dependent variable and independent variables.'''\n def __init__(self, iterations, learning_rate): \n self.lr = learning_rate \n self.it = iterations \n \n def fit(self, X, Y): \n # m instances, d atrributes \n self.m, self.d = X.shape \n # weight initialization \n self.W = np.zeros(self.d+1) \n self.X = X \n self.XX = np.ones((self.m, self.d+1)) \n self.XX[:,:-1] = self.X\n self.Y = Y \n for i in range(self.it): \n self.update_weights() \n return self\n \n def update_weights(self): \n Y_pred = self.predict(self.XX) \n # calculate gradients \n dW = (self.XX.T).dot(Y_pred - self.Y)/self.m \n # update weights \n self.W = self.W - self.lr * dW \n return self\n \n def predict(self, X): \n return X.dot(self.W)\n \ndef main(): \n # Import data\n X, Y = generate_dataset_simple(10, 200, 0.5)\n # Splitting dataset into train and test set \n X_train, X_test, Y_train, Y_test = train_test_split(X, Y, train_size=.5, shuffle=False)\n # Model Learning\n model = LinearRegression(learning_rate = 0.01, iterations = 15000) \n model.fit(X_train, Y_train) \n # Model Working\n M, D = X_test.shape\n TEST = np.ones((M, D+1)) \n TEST[:,:-1] = X_test\n Y_pred = model.predict(TEST) \n # Statistics\n mse = metric_mse(Y_test, Y_pred)\n rmse = metric_rmse(Y_test, Y_pred)\n print('Coefficients: ', 'W = ', model.W[:-1], ', b = ', model.W[-1]) \n print('MSE = ', mse) \n print('RMSE = ', rmse)\n # Visualization\n plt.scatter( X_test, Y_test, color = 'black', s=8) \n plt.plot( X_test, Y_pred, color = 'red', linewidth=3) \n plt.title( 'X_test v.s. Y_test') \n plt.xlabel( 'X_test') \n plt.ylabel( 'Y_test') \n X_actual = np.array([0, 1])\n Y_actual = X_actual*10\n plt.plot(X_actual, Y_actual, 'c--', linewidth=3) \n plt.legend(('Regression Line', 'Actual Line'),loc='upper left', prop={'size': 15})\n plt.show()\n \nif __name__ == '__main__': \n main()\n```\n\n***\n* Additional notes about linear regression\n***\n\n1. When performing **Gradient Descent** approach, all features/attributes must have similar scale, or **feature scaling** is required to increase Gradient Descent convergence. We may import `from sklearn.preprocessing import StandardScaler`, then use `StandardScaler()`. (refer [feature scaling](https://www.analyticsvidhya.com/blog/2020/04/feature-scaling-machine-learning-normalization-standardization/))\n\n2. To avoid local minimum, and to quickly find the global minimum, make sure the cost function is a **convex function** ($\\displaystyle i.e., f(\\frac{a+b}{2}) \\leq \\frac{f(a)+f(b)}{2} $).\n\n3. Linear regression assumptions:\n - Exogeneity weak. Independent variable X is fixed variable, it is not random variable;\n - **Linearity**. $f$ is a linear combination of the parameters/coefficients and the independent variables X. Note that, linearity is a restriction on the parameters, not the independent variables X, e.g., polynomial regression can also be linear regression;\n - **Constant variable(Homoscedasticity)**. The variance of residual is the same for any value of independent variables;\n - **Independence**. Observations are independent of each other. The errors are uncorrelated with each other;\n - **Normality**. For any fixed value of X, Y is normally distributed.\n\n\n```python\n\n```\n", "meta": {"hexsha": "def41b5f7523561a23733efa59672123814cf1cf", "size": 35283, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Regression/Regression.ipynb", "max_stars_repo_name": "Sunnyfred/Machine-Learning-Models", "max_stars_repo_head_hexsha": "e7caeb84d367b1b941695ac64d94c0cca6345a80", "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": "Regression/Regression.ipynb", "max_issues_repo_name": "Sunnyfred/Machine-Learning-Models", "max_issues_repo_head_hexsha": "e7caeb84d367b1b941695ac64d94c0cca6345a80", "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": "Regression/Regression.ipynb", "max_forks_repo_name": "Sunnyfred/Machine-Learning-Models", "max_forks_repo_head_hexsha": "e7caeb84d367b1b941695ac64d94c0cca6345a80", "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": 104.3875739645, "max_line_length": 23024, "alphanum_fraction": 0.8092565825, "converted": true, "num_tokens": 2671, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9706877700966099, "lm_q2_score": 0.8902942166619118, "lm_q1q2_score": 0.8641977079014592}} {"text": "In a previous exercise we plotted the density of states from the DOSCAR file. However, the result from the actual VASP computation can only be a discrete spectrum of energy eigenvalues (like we read from the EIGENVAL file for the band structure plot), so VASP has to perform some kind of post-processing on the energy spectrum to get the DOS. This is called [smearing](https://cms.mpi.univie.ac.at/wiki/index.php/ISMEAR) or [Kernel Density Estimation (KDE)](https://en.wikipedia.org/wiki/Kernel_density_estimation). The goal is to transform a discrete set of values $\\{e_i\\}$ into a continuous density $p(e)$ and the basic idea is to place a small smeared out function, the kernel, at each point $e_i$ and then sum over all of them to estimate $p(e)$.\n\nLet's start with the kernel, in our case a simple, normalized gaussian\n\\begin{equation}\nK(e; e_i, \\sigma) = \\frac{1}{\\sqrt{2\\pi \\sigma^2}} \\exp{ \n \\left\\{ -\\frac{1}{2}\\frac{ (e - e_i)^2 }{\\sigma^2} \\right\\}\n},\n\\end{equation}\nthat is centered on $e_i$ and of width $\\sigma$. The kernel should always be normalized to one, because we want the final density to be normalized to the number of states in the system for obvious reasons. Then we define the KDE as\n$$\np(e; \\sigma) = \\sum_i K(e; e_i, \\sigma),\n$$\nwhere the smearing width $\\sigma$ is an open parameter (in VASP this is controlled by the tag `SIGMA`) you can play around with.\n\nTo get started let's plot a single gaussian first and then figure out how to do the sum.\n\n\n```python\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nx = np.linspace(-5, 5, 100)\nplt.plot(x, np.exp(-x**2/2))\n```\n\nNumpy defines arrays that can be used in arithmetic expressions like scalars, but apply the operations to all their elements.\n\nWe'll make a function that also takes care of the normalized of the gaussian for us\n\n\n```python\ndef gaussian(e, ei, s):\n return np.exp( -0.5 * (e - ei)**2 / s**2 ) / np.sqrt(2 * np.pi * s**2)\n```\n\n\n```python\nplt.plot(x, gaussian(x, 0, 1), label = 'normal')\nplt.plot(x, gaussian(x, 1, 1), label = 'normal shifted')\nplt.plot(x, gaussian(x, 0, 2), label = 'wide')\nplt.legend()\n```\n\nNow with this write a function that takes a list of energy eigenvalues and a list of sample points and computes the corresponding KDE on it.\n\n\n```python\ndef kde(samples, spectrum):\n pass\n```\n\n\n```python\ndef kde(samples, spectrum, sigma = 1):\n K = np.zeros_like(samples)\n for ei in spectrum:\n K += gaussian(samples, ei, sigma)\n \n return K\n\nplt.plot(x, kde(x, [0, 3, 3, 3, 1, 1], .5), label = 'KDE')\nplt.vlines([0, 1, 3], 0, [1, 2, 3], label = 'spectrum')\nplt.legend()\n```\n\nNow that we can compute the KDE, we can look into how to get the energy spectrum. We have to read the energies from the same files as before, so it makes only sense to use the functions we have written for that in the last notebook.\n\n\n```python\ndef read_paragraph(file):\n \"\"\"Read a paragraph from the given file.\"\"\"\n \n lines = [] # we'll save all the lines in a list; [] creates an empty one\n \n while True:\n new = file.readline()\n if new == '\\n' or new == '': # when we've reached the end of the file, readline() will return the empty string ''\n break\n else:\n lines.append(new)\n \n return lines\n\ndef read_meta(paragraph):\n \"\"\"\n Read number of eigenvalues and k points from given paragraph. \n Must be given the first paragraph of EIGENVAL file.\n \"\"\"\n \n line = paragraph[-1] # index -1 is always the last element of a list, -2 the second to last and so on\n elems = line.split() # split the whole line into sub strings on whitespace (\"hello world\".split() -> [\"hello\", \"world\"])\n \n ne = int(elems[0]) # convert from strings to integers\n nk = int(elems[1])\n \n return ne, nk\n```\n\nHowever, since we're not interested in bands anymore, we can simplify the last part a little bit and read all the energy eigenvalues into a single list. There is one important difference; previously we neglected the k point coordinates and the associated weights, because we didn't compute any averages. However, the DOS is an average of the full Brillouin zone, so we have take the weight correctly into account. Start by writing a function that reads a single paragraph and returns all energies in the paragraph together with their weight.\n\n\n```python\ndef read_kpoint(paragraph):\n pass\n```\n\n\n```python\ndef read_kpoint(paragraph):\n line = paragraph[0] # first line contains k point coordinate and weight\n weight = float(line.split()[-1]) # the weight is the last entry on the first line\n \n energies = []\n for line in paragraph[1:]:\n energy = float(line.split()[1])\n energies.append( [energy, weight] )\n \n return energies\n```\n\nNow given this function and the others for reading the EIGENVAL file, write a function that reads all paragraphs from a file, calls `read_kpoint()` on them then adds all the lists together and returns that.\n\n\n```python\ndef read_spectrum(file):\n \n p = read_paragraph(file)\n ne, nk = read_meta(p)\n \n E = []\n for i in range(nk):\n p = read_paragraph(file)\n E += read_kpoint(p)\n \n return E\n```\n\n\n```python\nf = open('EIGENVAL.dos', 'r')\nE = read_spectrum(f)\nf.close()\n```\n\n\n```python\ndef kde_weighted(samples, ewi, sigma):\n K = np.zeros_like(samples)\n for ei, wi in ewi:\n K += wi * gaussian(samples, ei, sigma)\n \n return K\n```\n\n\n```python\nes = np.linspace(-8, 15, 100)\nplt.plot(es, kde_weighted(es, E, .1))\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "1909b54b7f2f257dbce7a2c02e2b2d681b62adb6", "size": 92397, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "DOSPlot.ipynb", "max_stars_repo_name": "pmrv/abinitio-binder", "max_stars_repo_head_hexsha": "5e65722cd4d208c931c25d3429cb3560b795986f", "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": "DOSPlot.ipynb", "max_issues_repo_name": "pmrv/abinitio-binder", "max_issues_repo_head_hexsha": "5e65722cd4d208c931c25d3429cb3560b795986f", "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": "DOSPlot.ipynb", "max_forks_repo_name": "pmrv/abinitio-binder", "max_forks_repo_head_hexsha": "5e65722cd4d208c931c25d3429cb3560b795986f", "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": 254.5371900826, "max_line_length": 29372, "alphanum_fraction": 0.9200082254, "converted": true, "num_tokens": 1475, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.945801271704518, "lm_q2_score": 0.9136765157744067, "lm_q1q2_score": 0.8641564105459869}} {"text": "# Exploring infectious disease dynamics with SIR models\n\n## Numerically solving the SIR equations\n\nAs we saw in lecture, SIR-type models offer a powerful and general way of modeling infectious disease dynamics. Let's take another look at the differential equations for the standard SIR model:\n\n\\begin{eqnarray}\n\t\\frac{dS}{dt} & = & -\\beta S I \\\\\n\t\\frac{dI}{dt} & = & \\beta S I - \\gamma I \\\\ \n\t\\frac{dR}{dt} & = & \\gamma I\n\\end{eqnarray}\n\nUnfortunately, even though they look simple, we cannot analytically solve these equations for $S(t)$, $I(t)$ or $R(t)$ at a given time $t$. The incidence term $\\beta S I$ makes this a ***nonlinear system*** of equations, which in general do not have simple analytical solutions. So intead, we need to ***numerically integrate (solve)*** these differential equations.\n\nTo integrate the equations, we need to consider the change in each variable over a small time step $\\Delta t$. This turns out to be quite easy since the differential equations provide the derivative of each variable with respect time, or in other words, that variable's rate of change. To get the change in a variable, we just need to multiply the rate of change by $\\Delta t$. For example, we can integrate the differential equation for $I$ from time $t$ to time $t + \\Delta t$ as follows: \n\n%%latex\n$$\n I(t + \\Delta t) \\approx I(t) + \\frac{dI}{dt} \\times \\Delta t\n$$\n\nThe problem with this basic scheme is that the amount of error we introduce will depend heavily on $\\Delta t$. Modern numerical integration packages therefore use much more sophisticated integration schemes that can adaptively choose $\\Delta t$ based on the rates of change. We will use [SciPy's integrate](https://docs.scipy.org/doc/scipy/reference/integrate.html) package, which has very efficient methods for solving ODEs.\n\n### Coding the SIR model in Python\n\nWe will implement the SIR model in Python. First we need to import some standard Python packages such as NumPy, SciPy and MatPlotLib. Make sure you hit ***Shift + Return*** in the following cell so that the lines of Python code are run through the interpreter.\n\n\n```python\nimport numpy as np\nimport scipy.integrate as spi\nimport matplotlib.pyplot as plt\n%matplotlib inline\n```\n\nNext, we'll define the parameters of our model, including the transmission rate $\\beta$, the recovery rate $\\gamma$ and the overall host population size $N$:\n\n\n```python\nbeta = 0.3\ngamma = 0.1\nN = 1000.0\n```\n\nAgain make sure you hit ***Shift + Return*** after each block of code so that the commands are evaluated. We will also create a grid of time points at which we will solve for each variable using NumPy's *linspace* function:\n\n\n```python\n# A grid of time points (in days)\nt = np.linspace(0, 100, 21)\nprint(t)\n```\n\n [ 0. 5. 10. 15. 20. 25. 30. 35. 40. 45. 50. 55. 60. 65.\n 70. 75. 80. 85. 90. 95. 100.]\n\n\nThis creates a time point at zero and 20 evenly spaced time points between 0 and 100. Now we will set the initial conditions for each of the state variables, which we'll treat as frequencies. We will store all of these in one variable called *y_init*: \n\n\n```python\n# Initial conditions\"\nS_init = 999.0 / N\nI_init = 1.0 / N\nR_init = 0 / N\ny_init = S_init, I_init, R_init\nprint(\"S = \" + f'{S_init:.3f}; ' + \"I = \" + f'{I_init:.3f}; ' + \"R = \" + f'{R_init:.3f}')\n```\n\n S = 0.999; I = 0.001; R = 0.000\n\n\nIn order to numerically solve the ODE's in SciPy, we must first define a function that will compute and return the rate of change (i.e. the derivatives) for each variable. We do this in Python by using the keyword *def* to define the function and its inputs and the keyword *return* to set which variables are returned:\n\n\n```python\ndef deriv(y, t, N, beta, gamma):\n S, I, R = y\n dS = -beta * S * I\n dI = beta * S * I - gamma * I\n dR = gamma * I\n return dS, dI, dR\n```\n\nWith all of that, we can now use SciPy's *odeint* function to numerically integrate/solve our ODEs. Note the order of the input arguments here: first we list the function we are integrating *deriv*, then the initial conditions *y_init*, then the times at which we are solving *t*, and then a final tuple called *args* which supplies the other parameters in our model:\n\n\n```python\n# Integrate the SIR equations over the time grid t.\nret = spi.odeint(deriv, y_init, t, args=(N, beta, gamma))\n```\n\nNow we can plot the SIR dynamics!\n\n\n```python\n# Set up plot\nimport seaborn as sns # We will use seaborn to make the plots look slightly nicer\nsns.set()\nfig, ax = plt.subplots(1, 1, figsize=(8, 4))\nS, I, R = ret.T\nax.plot(t, S, 'o-', mew=1, ms=8, mec='w', label='S')\nax.plot(t, I, 'o-', mew=1, ms=8, mec='w', label='I')\nax.set_xlabel('Time')\nax.set_ylabel('Frequency')\nax.legend()\n```\n\nWhat happens if we vary the transmission rate $\\beta$ and therefore also $R_{0}$? We can use a *for* loop to iterate through different values of $\\beta$, recompute $R_{0}$ and then plot the epidemic curve of prevalence over time:\n\n\n```python\nfig, ax = plt.subplots(1, 1, figsize=(8, 4))\nbetas = np.linspace(0.1, 0.5, 5) # lets' try beta values of 0.1, 0.2, 0.3, 0.4 and 0.5\nfor beta in betas:\n R0 = beta / gamma\n ret = spi.odeint(deriv, y_init, t, args=(N,beta,gamma))\n S, I, R = ret.T\n ax.plot(t, I, 'o-', mew=1, ms=8, mec='w', label=f'R0={R0:.1f}')\nax.set_xlabel('Time')\nax.set_ylabel('Prevalence')\nax.legend()\n```\n\nAs expected, the epidemic only takes off if $R_{0} > 1$ and we get larger epidemics as we increase $\\beta$.\n\n### Adding host demography\n\nAs we discussed in lecture, nothing really interesting can happen in the basic SIR model. The epidemic just grows until eventually it burns out due to a depletion of susceptible hosts. Let's add host births and deaths to the model so that we get a replenishment of susceptible hosts. Recall the SIR model with demography: \n\n%%latex\n\\begin{eqnarray}\n \\frac{dS}{dt} & = & \\nu -\\beta S I - \\mu S \\\\\n \\frac{dI}{dt} & = & \\beta S I - (\\gamma + \\mu) I \\\\ \n \\frac{dR}{dt} & = & \\gamma I - \\mu R\n\\end{eqnarray}\n\nHere, $\\nu$ is the host birth rate and $\\mu$ the death rate. We'll set this to reasonable values for humans. We will continue to specify time in days so rates are per day:\n\n\n```python\nbeta = 520/365 # per day\ngamma = 1/7 # per day - so average infectious period is 1 week\nN = 1000.0 # pop size\nnu = 1/(70*365) # birth rate per day\nmu = nu # death rate per day\n```\n\nThe host lifespan is 70 years, but since we are working in time units of days, we multply this by 365 days to get the birth rate per day. We'll set $\\mu=\\nu$ so that the host population remains in demographic equilibrium. We will set our grid of time points over a much longer time scale (20 years) so we can see how the long-term dynamics unfold: \n\n\n```python\n# A grid of time points (in days)\nt = np.linspace(0, 365*20, 100)\n```\n\nNow we need to set the initial conditions. We will continue work with frequencies for S, I and R. I've set *S_init* to $1/R_{0}$ so that we start close to the equilbrium number of susceptibles.\n\n\n```python\n# Initial conditions\"\nR0 = beta / (gamma+mu)\nS_init = 1. / R0\nI_init = 1. / N\nR_init = 1. - S_init - I_init\ny_init = S_init, I_init, R_init\nprint(\"S = \" + f'{S_init:.3f}; ' + \"I = \" + f'{I_init:.3f}; ' + \"R = \" + f'{R_init:.3f}')\n```\n\n S = 0.100; I = 0.001; R = 0.899\n\n\nNow I'm going to make you do a little work. I've set up the #deriv# function for the SIR model with host births ***BUT*** I have not added deaths yet. See if you can modify the equations for the rate of change of each variable to include deaths:\n\n\n```python\ndef deriv(y, t, N, beta, gamma):\n S, I, R = y\n dS = nu - beta * S * I # Add deaths\n dI = beta * S * I - gamma * I # Add deaths\n dR = gamma * I # Add deaths\n return dS, dI, dR\n```\n\nAs before, we can integrate our system of differential equations using *odeint*:\n\n\n```python\nret = spi.odeint(deriv, y_init, t, args=(N, beta, gamma))\n```\n\nAnd then plot the prevalence of the disease over a 20 year time span:\n\n\n```python\nfig, ax = plt.subplots(1, 1, figsize=(8, 5))\nS, I, R = ret.T\nax.plot(t/365, I, 'o-', mew=1, ms=8, mec='w')\nax.set_xlabel('Time (years)')\nax.set_ylabel('Prevalence')\n```\n\nAs expected, we get fluctuations with damped oscillations as the system converges to equilbrium. How long do we need to run the dynamics before we hit equlibrium? You can vary the number of years we run this for by changing the number of years in cell 27 above, then resolve the ODEs in cell 30 and plot again in cell 31.\n\nYou may also want to play around with changing the birth rate $\\nu$. What happens if we increase or decrease the birth rate? The following code scales $\\nu$ by 0.5, 1 and 2x.\n\n\n```python\nfig, ax = plt.subplots(1, 1, figsize=(8, 4))\nnu = 1/(70*365) # birth rate per day\nnus = [0.5*nu, 1.0*nu, 2*nu] # let's scale nu by 0.5X, 1X and 2X\nfor nu in nus:\n mu = nu # reset death rate equal to nu\n ret = spi.odeint(deriv, y_init, t, args=(N,beta,gamma))\n S, I, R = ret.T\n ax.plot(t, I, 'o-', mew=1, ms=8, mec='w', label=f'nu={365*nu:.3f}')\nax.set_xlabel('Time')\nax.set_ylabel('Prevalence')\nax.legend()\n```\n\nAs you can see, changing the birth rate changes the periodicity of the oscillations. Higher birth rates lead to more frequent outbreaks with a smaller amplitude.\n\n### Advanced: Koala chlamydia\n\nChlamydia is a major sexually transmitted disease in koalas which can lead to population declines through increased mortality and decreased fertility. Here we will consider a simple SI-type model with both male and female koalas. Since koalas are prodiguous herbivores, we will assume koalas compete with one another for food and that koala mortality naturally increases with greater population densities. The differential equations for our koala SI model are:\n\n%%latex\n\\begin{eqnarray}\n \\frac{dS_{f}}{dt} & = & r (S_{f} + (1-\\alpha) I_{f}) - r S_{f} \\frac{N}{K} - \\beta_{mf} \\frac{S_{f}}{N} I_{m} \\\\\n \\frac{dS_{m}}{dt} & = & r (S_{f} + (1-\\alpha) I_{f}) - r S_{m} \\frac{N}{K} - \\beta_{fm} \\frac{S_{m}}{N} I_{f} \\\\\n \\frac{dI_{f}}{dt} & = & \\beta_{mf} \\frac{S_{f}}{N} I_{m} - r I_{f} \\frac{N}{K} \\\\ \n \\frac{dI_{m}}{dt} & = & \\beta_{fm} \\frac{S_{m}}{N} I_{f} - r I_{m} \\frac{N}{K} \\\\\n N & = & S_{f} + S_{m} + I_{f} + I_{f}\n\\end{eqnarray}\n\n$S_{f}$ and $S_{m}$ are the number of susceptible female and male koalas. Females reproduce at rate $r$, so the term $r(S_{f} + (1-\\alpha) I_{f})$ is the rate at which both susceptible and infected females reproduce. The $\\alpha$ parameter captures the reduced fertility of infected females, such that if $\\alpha=1$, all infected females are completely infertile. We will assume that all koalas die at a rate $r \\frac{N}{K}$, where $N$ is the total population size and $K$ is the carrying capacity, or maximum size, of the population that can be supported given the amount of food resources. Thus, the higher $N$ is relative to $K$, the more density-dependent mortality there is.\n\nNow we need to choose some parameter values for our model:\n\n\n```python\nr = 1.0 # koala reproductive rate\nalpha = 0.4 # reduction in fertility due to infection\nbeta = np.array([[0.0,4.0],[4.6,0.0]]) # Transmission rates from Keeling & Rohani (pg 75)\nK = 200 # carrying capacity\n```\n\nNotice that $\\beta$ is a transmission rate matrix because we now have a structured host population with both males and females. I've set $\\beta_{fm} = 4.0$ and $\\beta_{mf} = 4.6$ such that male to female transmission is a little higher than female to male.\n\nNext we will set the initial conditions. For now we will not include any infected males or females so that we can explore the host population dynamics in the absence of disease:\n\n\n```python\nt = np.linspace(0, 20, 20) # grid of time points to simulate\nSf = 60\nSm = 80\nIf = 0\nIm = 0\ny_init = Sf, Sm, If, Im # initial conditions\n```\n\nThe following code cell defines the #deriv# function for computeing the derivatives of the differential equation model:\n\n\n```python\ndef deriv(y, t, r, beta, alpha, K):\n Sf, Sm, If, Im = y\n N = Sf + Sm + If + Im\n dSf = r*(Sf + (1-alpha) * If) - r*Sf*(N/K) - beta[1,0] * Sf * Im / N\n dSm = r*(Sf + (1-alpha) * If) - r*Sm*(N/K) - beta[0,1] * Sm * If / N\n dIf = beta[1,0] * Sf * Im / N - r*If*(N/K)\n dIm = beta[0,1] * Sm * If / N - r*Im*(N/K)\n return dSf, dSm, dIf, dIm\n```\n\nNow we can numerically integrate the ODEs and plot the population dynamics:\n\n\n```python\nret = spi.odeint(deriv, y_init, t, args=(r,beta,alpha,K)) # Integrate the SIR equations over the time grid, t.\nSf, Sm, If, Im = ret.T\nfig, ax = plt.subplots(1, 1, figsize=(8, 5))\nax.plot(t, Sf, 'o-', mew=1, ms=8, mec='w', label=\"S Females\")\nax.plot(t, Sm, 'o-', mew=1, ms=8, mec='w', label=\"S Males\")\nax.plot(t, If, 'o-', mew=1, ms=8, mec='w', label=\"I Females\")\nax.plot(t, Im, 'o-', mew=1, ms=8, mec='w', label=\"I Males\")\nax.set_xlabel('Time')\nax.set_ylabel('Density')\nax.legend()\n```\n\nRemember we set $I_{f} = 0$ and $I_{m} = 0$, so we have not yet introduced the disease. In the absence of disease, the population quickly equilibrates to its carrying capacity ($K=200$). Now let's go back and seed the epidemic by including one infected male and female pair:\n\n\n```python\nSf = 60\nSm = 80\nIf = 1\nIm = 1\ny_init = Sf, Sm, If, Im # initial conditions\n```\n\n\n```python\nret = spi.odeint(deriv, y_init, t, args=(r,beta,alpha,K)) # Integrate the SIR equations over the time grid, t.\nSf, Sm, If, Im = ret.T\nfig, ax = plt.subplots(1, 1, figsize=(8, 5))\nax.plot(t, Sf, 'o-', mew=1, ms=8, mec='w', label=\"S Females\")\nax.plot(t, Sm, 'o-', mew=1, ms=8, mec='w', label=\"S Males\")\nax.plot(t, If, 'o-', mew=1, ms=8, mec='w', label=\"I Females\")\nax.plot(t, Im, 'o-', mew=1, ms=8, mec='w', label=\"I Males\")\nax.set_xlabel('Time')\nax.set_ylabel('Density')\nax.legend()\n```\n\nNow we see that the number of infected males and females quickly rises to an equilbrium value where about half of the population is infected. What happens if we vary $\\alpha$, the reduction in fertility due to disease? Here, we will vary $\\alpha$ between zero and one and then plot the total prevalence of the disease in both males and females for different $\\alpha$ values:\n\n\n```python\nfig, ax = plt.subplots(1, 1, figsize=(8, 5))\nalphas = np.linspace(0.0, 1.0, 6) # lets' try beta values of 0.1, 0.2, 0.3, 0.4 and 0.5\nt = np.linspace(0, 40, 21)\nfor alpha in alphas:\n ret = spi.odeint(deriv, y_init, t, args=(r,beta,alpha,K))\n Sf, Sm, If, Im = ret.T\n ax.plot(t, If+Im, 'o-', mew=1, ms=8, mec='w', label=f'alpha={alpha:.2f}')\nax.set_xlabel('Time')\nax.set_ylabel('Total prevalence')\nax.legend()\n```\n\nWe can see that high values of $\\alpha$ where infected females have low fertility eventually causes disease prevalence to decline because high amounts of infertility causes the overall host population size to decline. Thus it would be benificial for the pathogen to reduce its virulence in terms of the infertility it causes.\n\nHowever, for many infectious diseases there is a tradeoff between maximizing virulence and maximizing transmissibility. Maximizing transmissability generally requires high within host pathogen growth rates and population sizes, which will also tend to increase virulence. We can add such a tradeoff in our model by rescaling the transmission rates in $\\beta$ by $\\alpha$ such that we get a new transmission rate $\\beta^{\\ast}$ that linearly covaries with the virulence $\\alpha$: \n\n%%latex\n\\begin{equation}\n \\beta^{\\ast} = \\beta \\times \\alpha\n\\end{equation}\n\nNow if we vary $\\alpha$, we will also vary the transmission rates in $\\beta$:\n\n\n```python\nfig, ax = plt.subplots(1, 1, figsize=(8, 5))\nalphas = np.linspace(0.0, 1.0, 6) # lets' try beta values of 0.1, 0.2, 0.3, 0.4 and 0.5\nt = np.linspace(0, 40, 21)\nfor alpha in alphas:\n beta_star = beta * alpha\n ret = spi.odeint(deriv, y_init, t, args=(r,beta_star,alpha,K))\n Sf, Sm, If, Im = ret.T\n ax.plot(t, If+Im, 'o-', mew=1, ms=8, mec='w', label=f'alpha={alpha:.2f}')\nax.set_xlabel('Time')\nax.set_ylabel('Total prevalence')\nax.legend()\n```\n\nNow we can clearly see that there is an intermediate value of $\\alpha$ about 0.6 that maximizes the long-term or equilibrium prevalence of chlamydia in the koala population. Do you think that the pathogen will evolve reduced virulence to maximize its long term fitness? Or would a less virulent strain of chlamydia always be outcompeted by a strain with greater virulence and therefore transmission potential?\n\n\n```python\n\n```\n", "meta": {"hexsha": "eae41bdcef68536eab1f2ecaad0ea5b102e3a155", "size": 358881, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "SIR.ipynb", "max_stars_repo_name": "davidrasm/SIR-binder", "max_stars_repo_head_hexsha": "2358afa8d287c792077b3cbe034015fbaf8e3967", "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": "SIR.ipynb", "max_issues_repo_name": "davidrasm/SIR-binder", "max_issues_repo_head_hexsha": "2358afa8d287c792077b3cbe034015fbaf8e3967", "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": "SIR.ipynb", "max_forks_repo_name": "davidrasm/SIR-binder", "max_forks_repo_head_hexsha": "2358afa8d287c792077b3cbe034015fbaf8e3967", "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": 399.2002224694, "max_line_length": 68032, "alphanum_fraction": 0.9329359871, "converted": true, "num_tokens": 5045, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693617046215, "lm_q2_score": 0.9099070060380482, "lm_q1q2_score": 0.8641108056347164}} {"text": "## 10. Solve Equations\n\n[](https://www.youtube.com/watch?v=c40z75JnT44&list=PLLBUgWXdTBDg1Qgmwt4jKtVn9BWh5-zgy \"Python Data Science\")\n\nEquations are at the root of data science. It is what turns data into actionable information by developing mathematical expressions that mimic physical systems. Some math expressions are simple and can be calculated sequentially such as\n\n$x=1 \\quad y=x^2+2x-4$\n\nThe solution is $x=1$ and $y=1+2-4=-1$. Consider the case where $x$ also depends on $y$.\n\n$x=y \\quad y=x^2+2x-4$\n\nThere are two solutions that are calculated from the quadratic formula $y=\\frac{-b\\pm\\sqrt{b^2-4ac}}{2a}$.\n\n$0=y^2+(2y-y)-4 \\quad y^2+y-4 = 0$ with $a=1$, $b=1$ and $c=-4$.\n\n$y = \\frac{-1 \\pm \\sqrt{17}}{2} = {1.56,-2.56}$\n\nThere are two primary ways to solve this problem. The first method is a **numeric solution** where the computer uses trial and error methods to get to a solution. Numeric methods are best when the number of equations is large and there is no analytic solution. The second method is a **symbolic solution** that produces an exact solution.\n\n\n\n### Numeric Solution\n\nLarge-scale and complex problems require a numeric solution approach such as with `fsolve` or `gekko`. It requires a function that returns the equation error residual. This residual is $f(y)=y^2+y-4$ and is not equal to zero when the value of $y$ is not at the correct solution. An initial guess of `1` or `-2` give a different solution because we are starting close to one or the other.\n\n#### Solution with Scipy fsolve\n\n\n```python\nfrom scipy.optimize import fsolve\ndef f(y):\n return y**2+y-4\nz = fsolve(f,1); print(z)\nz = fsolve(f,-2); print(z)\n```\n\n\n\n**Solution with Python Gekko**\n\n\n```python\nfrom gekko import GEKKO\nm = GEKKO(remote=False)\ny = m.Var(1); m.Equation(y**2+y-4==0)\nm.solve(disp=False); print(y.value)\ny.value = -2\nm.solve(disp=False); print(y.value)\n```\n\n\n\n### Solve 2 Equations\n\nIt is similar when there are two equations instead of one.\n\n$y=x^2+2x-4$\n\n$x=y$\n\nThe function returns the error residual for each equation as a list. Two initial guesses are needed. This same method extends to more equations as well. Equation solvers can find solutions to problems with thousands or millions of variables.\n\n**Solution with Scipy fsolve**\n\n\n```python\nfrom scipy.optimize import fsolve\ndef f(z):\n x,y = z\n return [x-y,y-x**2-2*x+4]\nz = fsolve(f,[1,1]); print(z)\nz = fsolve(f,[-2,-2]); print(z)\n```\n\n\n\n**Solution with Python Gekko**\n\n\n```python\nm = GEKKO(remote=False)\nx=m.Var(); y = m.Var(1);\nm.Equations([y==x**2+2*x-4, x==y])\nm.solve(disp=False)\nprint(x.value, y.value)\n\nx.value=-2; y.value=-2\nm.solve(disp=False)\nprint(x.value, y.value)\n```\n\n\n\n### Solve 3 Equations\n\n$x^2+y^2+z^2=1$\n\n$x-2y+3z=0.5$\n\n$x+y+z=0$\n\nSolve the problem with 3 variables and 3 equations.\n\n\n```python\n\n```\n\n\n\n### Symbolic Solution\n\nSmall problems may have an analytic solution that can be expressed symbolically. A symbolic math package in Python is `sympy`. The `display` function is also available to print the equations in Jupyter notebooks. It requires the import `from IPython.display import display`.\n\n\n```python\nfrom IPython.display import display\nimport sympy as sym\nx = sym.Symbol('x')\ny = sym.Symbol('y')\nans = sym.nonlinsolve([x-y, y-x**2-2*x+4], [x,y])\ndisplay(ans)\n```\n\n\n\n### Solve 3 Equations Symbolically\n\n$x\\,y\\,z=0$\n\n$x\\,y=0$\n\n$x+5\\,y+z$\n\nSolve the problem with 3 variables and 3 equations symbolically. The problem is degenerate (underspecified) so one of the variables will appear in the solution because there are an infinite set.\n\n\n```python\n\n```\n\n\n\n### Linear Equations\n\nLinear equations are also solved in Python but have efficient methods such as `x = np.linalg.solve(A,b)` to solve $A x = b$ equations with matrix $A$ and vectors $x$ and $b$.\n\n$A = \\begin{bmatrix}3 & 2\\\\ 1 & 2 \\end{bmatrix} \\quad b = \\begin{bmatrix}1 \\\\ 0 \\end{bmatrix}$\n\n\n```python\nimport numpy as np\nA = np.array([[3,2],[1,2]])\nb = np.array([1,0])\n\nx = np.linalg.solve(A,b)\nprint(x)\n```\n\nA symbolic solution to this set of linear equations is also available using the `sympy` `linsolve` function. If the problem is linear then `linsolve` is preferred because it is more efficient than `nonlinsolve` but it can solve both.\n\n\n```python\nimport sympy as sym\nx, y = sym.symbols('x y')\nans = sym.linsolve([3*x + 2*y - 1, x + 2*y], (x, y))\nsym.pprint(ans)\n```\n\n\n\n### Optimization\n\nWhen there are more variables than equations, the problem is underspecified and can't be solved with an equation solver such as `fsolve` (for linear or nonlinear) or `linalg.solve` (just for linear problems). Additional information is needed to guide the selection of the extra variables. An objective function $J(x)$ is one way to specify the problem so that a unique solution exists. The objective is to minimize $x_1 x_4 \\left(x_1 + x_2 + x_3\\right) + x_3$. The two equations guide the selection of two variables with inequality $\\left(x_1 x_2 x_3 x_4 \\ge 25\\right)$ and equality $\\left(x_1^2 + x_2^2 + x_3^2 + x_4^2 = 40\\right)$ constraints. All four variables must be between `1` (lower bound) and `5` (upper bound).\n\n$\\quad \\min x_1 x_4 \\left(x_1 + x_2 + x_3\\right) + x_3$\n\n$\\quad \\mathrm{s.t.} \\quad x_1 x_2 x_3 x_4 \\ge 25$\n\n$\\quad x_1^2 + x_2^2 + x_3^2 + x_4^2 = 40$\n\n$\\quad 1\\le x_1, x_2, x_3, x_4 \\le 5$\n\nwith initial guess:\n\n$\\quad x_0 = (1,5,5,1)$\n\nAdditional information on optimization is given in the [Design Optimization Course](https://apmonitor.com/me575) and in the [Design Optimization Book](https://apmonitor.com/me575/index.php/Main/BookChapters). The first solution method is with `scipy.optimize.minimize`. Solvers in this package work well for moderate sized problems with black box models where an objective function is available through a function call.\n\n\n```python\nimport numpy as np\nfrom scipy.optimize import minimize\n\ndef objective(x):\n return x[0]*x[3]*(x[0]+x[1]+x[2])+x[2]\n\ndef constraint1(x):\n return x[0]*x[1]*x[2]*x[3]-25.0\n\ndef constraint2(x):\n sum_eq = 40.0\n for i in range(4):\n sum_eq = sum_eq - x[i]**2\n return sum_eq\n\n# initial guesses\nn = 4\nx0 = np.zeros(n)\nx0[0] = 1.0\nx0[1] = 5.0\nx0[2] = 5.0\nx0[3] = 1.0\n\n# optimize\nb = (1.0,5.0)\nbnds = (b, b, b, b)\ncon1 = {'type': 'ineq', 'fun': constraint1} \ncon2 = {'type': 'eq', 'fun': constraint2}\ncons = ([con1,con2])\nsolution = minimize(objective,x0,method='SLSQP',\\\n bounds=bnds,constraints=cons)\nx = solution.x\n\n# show final objective\nprint('Final Objective: ' + str(objective(x)))\n\n# print solution\nprint('Solution')\nprint('x1 = ' + str(x[0]))\nprint('x2 = ' + str(x[1]))\nprint('x3 = ' + str(x[2]))\nprint('x4 = ' + str(x[3]))\n```\n\n\n\n### Optimization with Gekko\n\n[Python Gekko](https://gekko.readthedocs.io/en/latest/) also solves the problem and uses automatic differentiation and gradient-based solvers such as `APOPT` or `IPOPT` to find a solution. This solution method is better for large-scale problems. [Additional tutorials on Gekko](https://apmonitor.com/wiki/index.php/Main/GekkoPythonOptimization) show how to solve other types of optimization problems.\n\n\n```python\nfrom gekko import GEKKO\nm = GEKKO(remote=False)\n\n# initialize variables\nx1,x2,x3,x4 = [m.Var(lb=1, ub=5) for i in range(4)]\n\n# initial values\nx1.value = 1\nx2.value = 5\nx3.value = 5\nx4.value = 1\n\n# Equations\nm.Equation(x1*x2*x3*x4>=25)\nm.Equation(x1**2+x2**2+x3**2+x4**2==40)\n\n# Objective\nm.Obj(x1*x4*(x1+x2+x3)+x3)\n\n# Solve\nm.solve(disp=False)\n\n# Final objective\nprint('Final Objective: ' + str(m.options.objfcnval))\n\n# Print solution\nprint('Solution')\nprint('x1: ' + str(x1.value))\nprint('x2: ' + str(x2.value))\nprint('x3: ' + str(x3.value))\nprint('x4: ' + str(x4.value))\n```\n\n### TCLab Activity\n\n\n\n### Data Collection\n\n\n\nTurn on heater 1 to 100% and record $T_1$ every 10 seconds for 3 minutes. The data should include a total of 19 data points for each temperature sensor and the recording time, starting at zero. Make a note of the temperature points at 0, 90, and 180 seconds.\n\n\n```python\n\n```\n\n\n\n### Linear Equations\n\nThree points are required to specify a quadratic polynomial of the form $y =a_0 + a_1 \\; x + a_2 \\; x^2$. Create a quadratic regression of $T_2$ by using only the first, middle, and last data points. Suppose these were the following data points for $T_2$:\n\n| Time (sec) | Temperature (°C) |\n|------|------|\n| 0 | 23.0 |\n| 90 | 33.0 |\n| 180 | 43.0 |\n\nSolve the linear regression as a set of three equations that are derived by plugging in the three data points to the polynomial equation to create three separate equations with $y=T_2$ and $x=time$.\n\n$\\quad a_0 + a_1 \\; 0 + a_2 \\; 0^2 = 23.0$\n\n$\\quad a_0 + a_1 \\; 90 + a_2 \\; 90^2 = 33.0$\n\n$\\quad a_0 + a_1 \\; 180 + a_2 \\; 180^2 = 43.0$\n\nIn matrix form, the set of linear equations become: \n\n$\\quad \\begin{bmatrix}1 & 0 & 0 \\\\ 1 & 90 & 90^2 \\\\ 1 & 180 & 180^2 \\end{bmatrix}\\begin{bmatrix}a_0\\\\a_1\\\\a_2\\end{bmatrix} = \\begin{bmatrix}23.0\\\\33.0\\\\43.0\\end{bmatrix}$\n\nSolve this set of equations for the quadratic parameters $a_0$, $a_1$, and $a_2$ with the data collected at the beginning of the TCLab activity. Plot the quadratic fit with the data to ensure that the curve goes through the three specified data points.\n\n\n```python\n\n```\n\n\n\n### Nonlinear Equations\n\nFit the $T_1$ data to a nonlinear correlation using only three data points.\n\n$\\quad T_1 = a + b \\exp{(c \\, time)}$\n\nThree points are required to uniquely specify a model with three parameters. When there are more than the minimum required number of points, a least squares regression is typically performed to minimize the squared error between the measured and predicted values. For this exercise, use only 3 points (first, middle, last) of the $T_1$ data. Suppose these were the following data points for $T_1$:\n\n| Time (sec) | Temperature (°C) |\n|------|------|\n| 0 | 22.0 |\n| 90 | 42.0 |\n| 180 | 52.0 |\n\nSolve for the three parameters from the three equations that exactly intersect the required data points.\n\n$\\quad 22.0 = a + b \\exp{(c \\, 0)}$\n\n$\\quad 42.0 = a + b \\exp{(c \\, 90.3)}$\n\n$\\quad 52.0 = a + b \\exp{(c \\, 180.5)}$\n\nSolve this set of equations for the unknown parameters $a$, $b$, and $c$ with the data collected at the beginning of this notebook. Use guess values of $a=100$, $b=-100$, and $c=-0.01$. Plot the nonlinear fit with the data to ensure that the curve goes through the three specified data points. Add appropriate labels to the plot.\n\n\n```python\n\n```\n", "meta": {"hexsha": "e9b1324149ecee472c4828bcaaeadddd2e376301", "size": 16897, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "10. Solve_Equations.ipynb", "max_stars_repo_name": "kailiu77/data_science", "max_stars_repo_head_hexsha": "630b8e08481d7101876cff01d2557ea4835fe025", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-04-27T02:05:47.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-27T02:05:47.000Z", "max_issues_repo_path": "10. Solve_Equations.ipynb", "max_issues_repo_name": "kailiu77/data_science", "max_issues_repo_head_hexsha": "630b8e08481d7101876cff01d2557ea4835fe025", "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": "10. Solve_Equations.ipynb", "max_forks_repo_name": "kailiu77/data_science", "max_forks_repo_head_hexsha": "630b8e08481d7101876cff01d2557ea4835fe025", "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.0665322581, "max_line_length": 737, "alphanum_fraction": 0.5699236551, "converted": true, "num_tokens": 3239, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218391455085, "lm_q2_score": 0.9372107909645063, "lm_q1q2_score": 0.8640350960730144}} {"text": "# Gradient Descent Optimizations\n\nMini-batch and stochastic gradient descent is widely used in deep learning, where the large number of parameters and limited memory make the use of more sophisticated optimization methods impractical. Many methods have been proposed to accelerate gradient descent in this context, and here we sketch the ideas behind some of the most popular algorithms.\n\n\n```python\n%matplotlib inline\n```\n\n\n```python\nimport matplotlib.pyplot as plt\nimport numpy as np\n```\n\n## Smoothing with exponentially weighted averages\n\n\n```python\nn = 50\nx = np.arange(n) * np.pi\ny = np.cos(x) * np.exp(x/100) - 10*np.exp(-0.01*x)\n```\n\n### Exponentially weighted average\n\nThe exponentially weighted average adds a fraction $\\beta$ of the current value to a leaky running sum of past values. Effectively, the contribution from the $t-n$th value is scaled by\n\n$$\n\\beta^n(1 - \\beta)\n$$\n\nFor example, here are the contributions to the current value after 5 iterations (iteration 5 is the current iteration)\n\n| iteration | contribution |\n| --- | --- |\n| 1 | $\\beta^4(1 - \\beta)$ |\n| 2 | $\\beta^3(1 - \\beta)$ |\n| 3 | $\\beta^2(1 - \\beta)$ |\n| 4 | $\\beta^1(1 - \\beta)$ |\n| 5 | $(1 - \\beta)$ |\n\nSince $\\beta \\lt 1$, the contribution decreases exponentially with the passage of time. Effectively, this acts as a smoother for a function.\n\n\n```python\ndef ewa(y, beta):\n \"\"\"Exponentially weighted average.\"\"\"\n \n n = len(y)\n zs = np.zeros(n)\n z = 0\n for i in range(n):\n z = beta*z + (1 - beta)*y[i]\n zs[i] = z\n return zs\n```\n\n### Exponentially weighted average with bias correction\n\nSince the EWA starts from 0, there is an initial bias. This can be corrected by scaling with \n\n$$\n\\frac{1}{1 - \\beta^t}\n$$\n\nwhere $t$ is the iteration number.\n\n\n```python\ndef ewabc(y, beta):\n \"\"\"Exponentially weighted average with bias correction.\"\"\"\n \n n = len(y)\n zs = np.zeros(n)\n z = 0\n for i in range(n):\n z = beta*z + (1 - beta)*y[i]\n zc = z/(1 - beta**(i+1))\n zs[i] = zc\n return zs\n```\n\n\n```python\nbeta = 0.9\n\nplt.plot(x, y, 'o-')\nplt.plot(x, ewa(y, beta), c='red', label='EWA')\nplt.plot(x, ewabc(y, beta), c='orange', label='EWA with bias correction')\nplt.legend()\npass\n```\n\n## Momentum in 1D\n\nMomentum comes from physics, where the contribution of the gradient is to the velocity, not the position. Hence we create an accessory variable $v$ and increment it with the gradient. The position is then updated with the velocity in place of the gradient. The analogy is that we can think of the parameter $x$ as a particle in an energy well with potential energy $U = mgh$ where $h$ is given by our objective function $f$. The force generated is a function of the rat of change of potential energy $F \\propto \\nabla U \\propto \\nabla f$, and we use $F = ma$ to get that the acceleration $a \\propto \\nabla f$. Finally, we integrate $a$ over time to get the velocity $v$ and integrate $v$ to get the displacement $x$. Note that we need to damp the velocity otherwise the particle would just oscillate forever.\n\nWe use a version of the update that simply treats the velocity as an exponentially weighted average popularized by Andrew Ng in his Coursera course. This is the same as the momentum scheme motivated by physics with some rescaling of constants.\n\n\n```python\ndef f(x):\n return x**2\n```\n\n\n```python\ndef grad(x):\n return 2*x\n```\n\n\n```python\ndef gd(x, grad, alpha, max_iter=10):\n xs = np.zeros(1 + max_iter)\n xs[0] = x\n for i in range(max_iter):\n x = x - alpha * grad(x)\n xs[i+1] = x\n return xs\n```\n\n\n```python\ndef gd_momentum(x, grad, alpha, beta=0.9, max_iter=10):\n xs = np.zeros(1 + max_iter)\n xs[0] = x\n v = 0\n for i in range(max_iter):\n v = beta*v + (1-beta)*grad(x)\n vc = v/(1+beta**(i+1))\n x = x - alpha * vc\n xs[i+1] = x\n return xs\n```\n\n### Gradient descent with moderate step size\n\n\n```python\nalpha = 0.1\nx0 = 1\nxs = gd(x0, grad, alpha)\nxp = np.linspace(-1.2, 1.2, 100)\nplt.plot(xp, f(xp))\nplt.plot(xs, f(xs), 'o-', c='red')\nfor i, (x, y) in enumerate(zip(xs, f(xs)), 1):\n plt.text(x, y+0.2, i, \n bbox=dict(facecolor='yellow', alpha=0.5), fontsize=14)\npass\n```\n\n### Gradient descent with large step size\n\nWhen the step size is too large, gradient descent can oscillate and even diverge.\n\n\n```python\nalpha = 0.95\nxs = gd(1, grad, alpha)\nxp = np.linspace(-1.2, 1.2, 100)\nplt.plot(xp, f(xp))\nplt.plot(xs, f(xs), 'o-', c='red')\nfor i, (x, y) in enumerate(zip(xs, f(xs)), 1):\n plt.text(x*1.2, y, i,\n bbox=dict(facecolor='yellow', alpha=0.5), fontsize=14)\npass\n```\n\n### Gradient descent with momentum\n\nMomentum results in cancellation of gradient changes in opposite directions, and hence damps out oscillations while amplifying consistent changes in the same direction. This is perhaps clearer in the 2D example below.\n\n\n```python\nalpha = 0.95\nxs = gd_momentum(1, grad, alpha, beta=0.9)\nxp = np.linspace(-1.2, 1.2, 100)\nplt.plot(xp, f(xp))\nplt.plot(xs, f(xs), 'o-', c='red')\nfor i, (x, y) in enumerate(zip(xs, f(xs)), 1):\n plt.text(x, y+0.2, i, \n bbox=dict(facecolor='yellow', alpha=0.5), fontsize=14)\npass\n```\n\n## Momentum and RMSprop in 2D\n\n\n```python\ndef f2(x):\n return x[0]**2 + 100*x[1]**2\n```\n\n\n```python\ndef grad2(x):\n return np.array([2*x[0], 200*x[1]])\n```\n\n\n```python\nx = np.linspace(-1.2, 1.2, 100)\ny = np.linspace(-1.2, 1.2, 100)\nX, Y = np.meshgrid(x, y)\nlevels = [0.1,1,2,4,9, 16, 25, 36, 49, 64, 81, 100]\nZ = x**2 + 100*Y**2\nc = plt.contour(X, Y, Z, levels)\npass\n```\n\n\n```python\ndef gd2(x, grad, alpha, max_iter=10):\n xs = np.zeros((1 + max_iter, x.shape[0]))\n xs[0,:] = x\n for i in range(max_iter):\n x = x - alpha * grad(x)\n xs[i+1,:] = x\n return xs\n```\n\n\n```python\ndef gd2_momentum(x, grad, alpha, beta=0.9, max_iter=10):\n xs = np.zeros((1 + max_iter, x.shape[0]))\n xs[0, :] = x\n v = 0\n for i in range(max_iter):\n v = beta*v + (1-beta)*grad(x)\n vc = v/(1+beta**(i+1))\n x = x - alpha * vc\n xs[i+1, :] = x\n return xs\n```\n\n### Gradient descent with large step size\n\nWe get severe oscillations.\n\n\n```python\nalpha = 0.01\nx0 = np.array([-1,-1])\nxs = gd2(x0, grad2, alpha, max_iter=75)\n```\n\n\n```python\nx = np.linspace(-1.2, 1.2, 100)\ny = np.linspace(-1.2, 1.2, 100)\nX, Y = np.meshgrid(x, y)\nlevels = [0.1,1,2,4,9, 16, 25, 36, 49, 64, 81, 100]\nZ = x**2 + 100*Y**2\nc = plt.contour(X, Y, Z, levels)\nplt.plot(xs[:, 0], xs[:, 1], 'o-', c='red')\nplt.title('Vanilla gradient descent')\npass\n```\n\n### Gradient descent with momentum\n\nThe damping effect is clear.\n\n\n```python\nalpha = 0.01\nx0 = np.array([-1,-1])\nxs = gd2_momentum(x0, grad2, alpha, beta=0.9, max_iter=75)\n```\n\n\n```python\nx = np.linspace(-1.2, 1.2, 100)\ny = np.linspace(-1.2, 1.2, 100)\nX, Y = np.meshgrid(x, y)\nlevels = [0.1,1,2,4,9, 16, 25, 36, 49, 64, 81, 100]\nZ = x**2 + 100*Y**2\nc = plt.contour(X, Y, Z, levels)\nplt.plot(xs[:, 0], xs[:, 1], 'o-', c='red')\nplt.title('Gradieent descent with momentum')\npass\n```\n\n### Gradient descent with RMSprop\n\nRMSprop scales the learning rate in each direction by the square root of the exponentially weighted sum of squared gradients. Near a saddle or any plateau, there are directions where the gradient is very small - RMSporp encourages larger steps in those directions, allowing faster escape.\n\n\n```python\ndef gd2_rmsprop(x, grad, alpha, beta=0.9, eps=1e-8, max_iter=10):\n xs = np.zeros((1 + max_iter, x.shape[0]))\n xs[0, :] = x\n v = 0\n for i in range(max_iter):\n v = beta*v + (1-beta)*grad(x)**2\n x = x - alpha * grad(x) / (eps + np.sqrt(v))\n xs[i+1, :] = x\n return xs\n```\n\n\n```python\nalpha = 0.1\nx0 = np.array([-1,-1])\nxs = gd2_rmsprop(x0, grad2, alpha, beta=0.9, max_iter=10)\n```\n\n\n```python\nx = np.linspace(-1.2, 1.2, 100)\ny = np.linspace(-1.2, 1.2, 100)\nX, Y = np.meshgrid(x, y)\nlevels = [0.1,1,2,4,9, 16, 25, 36, 49, 64, 81, 100]\nZ = x**2 + 100*Y**2\nc = plt.contour(X, Y, Z, levels)\nplt.plot(xs[:, 0], xs[:, 1], 'o-', c='red')\nplt.title('Gradient descent with RMSprop')\npass\n```\n\n### ADAM\n\nADAM (Adaptive Moment Estimation) combines the ideas of momentum, RMSprop and bias correction. It is probably the most popular gradient descent method in current deep learning practice.\n\n\n```python\ndef gd2_adam(x, grad, alpha, beta1=0.9, beta2=0.999, eps=1e-8, max_iter=10):\n xs = np.zeros((1 + max_iter, x.shape[0]))\n xs[0, :] = x\n m = 0\n v = 0\n for i in range(max_iter):\n m = beta1*m + (1-beta1)*grad(x)\n v = beta2*v + (1-beta2)*grad(x)**2\n mc = m/(1+beta1**(i+1))\n vc = v/(1+beta2**(i+1))\n x = x - alpha * m / (eps + np.sqrt(vc))\n xs[i+1, :] = x\n return xs\n```\n\n\n```python\nalpha = 0.1\nx0 = np.array([-1,-1])\nxs = gd2_adam(x0, grad2, alpha, beta1=0.9, beta2=0.9, max_iter=10)\n```\n\n\n```python\nx = np.linspace(-1.2, 1.2, 100)\ny = np.linspace(-1.2, 1.2, 100)\nX, Y = np.meshgrid(x, y)\nlevels = [0.1,1,2,4,9, 16, 25, 36, 49, 64, 81, 100]\nZ = x**2 + 100*Y**2\nc = plt.contour(X, Y, Z, levels)\nplt.plot(xs[:, 0], xs[:, 1], 'o-', c='red')\nplt.title('Gradient descent with RMSprop')\npass\n```\n\n## Implementing a custom optimization routine for `scipy.optimize`\n\nGradient descent is not one of the methods available in `scipy.optimize`. However we can implement our own version by following the API of the `minimize` function.\n\n\n```python\nimport scipy.optimize as opt\nimport scipy.linalg as la\n```\n\n\n```python\ndef custmin(fun, x0, args=(), maxfev=None, alpha=0.0002,\n maxiter=100000, tol=1e-10, callback=None, **options):\n \"\"\"Implements simple gradient descent for the Rosen function.\"\"\"\n bestx = x0\n bestf = fun(x0)\n funcalls = 1\n niter = 0\n improved = True\n stop = False\n\n while improved and not stop and niter < maxiter:\n niter += 1\n # the next 2 lines are gradient descent\n step = alpha * rosen_der(bestx)\n bestx = bestx - step\n\n bestf = fun(bestx)\n funcalls += 1\n \n if la.norm(step) < tol:\n improved = False\n if callback is not None:\n callback(bestx)\n if maxfev is not None and funcalls >= maxfev:\n stop = True\n break\n\n return opt.OptimizeResult(fun=bestf, x=bestx, nit=niter,\n nfev=funcalls, success=(niter > 1))\n```\n\n\n```python\ndef reporter(p):\n \"\"\"Reporter function to capture intermediate states of optimization.\"\"\"\n global ps\n ps.append(p)\n```\n\n### Test on Rosenbrock banana function\n\nWe will use the [Rosenbrock \"banana\" function](http://en.wikipedia.org/wiki/Rosenbrock_function) to illustrate unconstrained multivariate optimization. In 2D, this is\n$$\nf(x, y) = b(y - x^2)^2 + (a - x)^2\n$$\n\nThe function has a global minimum at (1,1) and the standard expression takes $a = 1$ and $b = 100$. \n\n#### Conditioning of optimization problem\n\nWith these values for $a$ and $b$, the problem is ill-conditioned. As we shall see, one of the factors affecting the ease of optimization is the condition number of the curvature (Hessian). When the condition number is high, the gradient may not point in the direction of the minimum, and simple gradient descent methods may be inefficient since they may be forced to take many sharp turns.\n\nFor the 2D version, we have\n\n$$\nf(x) = 100(y - x^2)^2 + (1 - x)^2\n$$\n\nand can calculate the Hessian to be \n\n$$\n\\begin{bmatrix}\n802 & -400 \\\\\n-400 & 200\n\\end{bmatrix}\n$$\n\n\n```python\nH = np.array([\n [802, -400],\n [-400, 200]\n])\n```\n\n\n```python\nnp.linalg.cond(H)\n```\n\n\n```python\nU, s, Vt = np.linalg.svd(H)\ns[0]/s[1]\n```\n\n#### Function to minimize\n\n\n```python\ndef rosen(x):\n \"\"\"Generalized n-dimensional version of the Rosenbrock function\"\"\"\n return sum(100*(x[1:]-x[:-1]**2.0)**2.0 +(1-x[:-1])**2.0)\n```\n\n\n```python\ndef rosen_der(x):\n \"\"\"Derivative of generalized Rosen function.\"\"\"\n xm = x[1:-1]\n xm_m1 = x[:-2]\n xm_p1 = x[2:]\n der = np.zeros_like(x)\n der[1:-1] = 200*(xm-xm_m1**2) - 400*(xm_p1 - xm**2)*xm - 2*(1-xm)\n der[0] = -400*x[0]*(x[1]-x[0]**2) - 2*(1-x[0])\n der[-1] = 200*(x[-1]-x[-2]**2)\n return der\n```\n\n#### Why is the condition number so large?\n\n\n```python\nx = np.linspace(-5, 5, 100)\ny = np.linspace(-5, 5, 100)\nX, Y = np.meshgrid(x, y)\nZ = rosen(np.vstack([X.ravel(), Y.ravel()])).reshape((100,100))\n```\n\n\n```python\n# Note: the global minimum is at (1,1) in a tiny contour island\nplt.contour(X, Y, Z, np.arange(10)**5, cmap='jet')\nplt.text(1, 1, 'x', va='center', ha='center', color='red', fontsize=20)\npass\n```\n\n#### Zooming in to the global minimum at (1,1)\n\n\n```python\nx = np.linspace(0, 2, 100)\ny = np.linspace(0, 2, 100)\nX, Y = np.meshgrid(x, y)\nZ = rosen(np.vstack([X.ravel(), Y.ravel()])).reshape((100,100))\n```\n\n\n```python\nplt.contour(X, Y, Z, [rosen(np.array([k, k])) for k in np.linspace(1, 1.5, 10)], cmap='jet')\nplt.text(1, 1, 'x', va='center', ha='center', color='red', fontsize=20)\npass\n```\n\n#### We will use our custom gradient descent to minimize the banana function\n\n#### Helpful Hint \n\nOne of the most common causes of failure of optimization is because the gradient or Hessian function is specified incorrectly. You can check for this using `check_grad` which compares the analytical gradient with one calculated using finite differences.\n\n\n```python\nfrom scipy.optimize import check_grad\n\nfor x in np.random.uniform(-2,2,(10,2)):\n print(x, check_grad(rosen, rosen_der, x))\n```\n\n\n```python\n# Initial starting position\nx0 = np.array([4,-4.1])\nps = [x0]\nopt.minimize(rosen, x0, method=custmin, callback=reporter)\n```\n\n\n```python\nx = np.linspace(-5, 5, 100)\ny = np.linspace(-5, 5, 100)\nX, Y = np.meshgrid(x, y)\nZ = rosen(np.vstack([X.ravel(), Y.ravel()])).reshape((100,100))\n```\n\n\n```python\nps = np.array(ps)\nplt.figure(figsize=(12,4))\nplt.subplot(121)\nplt.contour(X, Y, Z, np.arange(10)**5, cmap='jet')\nplt.plot(ps[:, 0], ps[:, 1], '-ro')\nplt.subplot(122)\nplt.semilogy(range(len(ps)), rosen(ps.T))\npass\n```\n\n### Comparison with standard algorithms\n\nNote that all these methods take far fewer function iterations and function evaluations to find the minimum compared with vanilla gradient descent.\n\nMany of these are based on estimating the Newton direction. Recall Newton's method for finding roots of a univariate function\n\n$$\nx_{K+1} = x_k - \\frac{f(x_k)}{f'(x_k)}\n$$\n\nWhen we are looking for a minimum, we are looking for the roots of the *derivative* $f'(x)$, so\n\n$$\nx_{K+1} = x_k - \\frac{f'(x_k}{f''(x_k)}\n$$\n\nNewton's method can also be seen as a Taylor series approximation\n\n$$\nf(x+h) = f(x) + h f'(x) + \\frac{h^2}{2}f''(x)\n$$\n\nAt the function minimum, the derivative is 0, so\n\\begin{align}\n\\frac{f(x+h) - f(x)}{h} &= f'(x) + \\frac{h}{2}f''(x) \\\\\n0 &= f'(x) + \\frac{h}{2}f''(x) \n\\end{align}\n\nand letting $\\Delta x = \\frac{h}{2}$, we get that the Newton step is\n\n$$\n\\Delta x = - \\frac{f'(x)}{f''(x)}\n$$\n\nThe multivariate analog replaces $f'$ with the Jacobian and $f''$ with the Hessian, so the Newton step is\n\n$$\n\\Delta x = -H^{-1}(x) \\nabla f(x)\n$$\n\nSlightly more rigorously, we can optimize the quadratic multivariate Taylor expansion \n\n$$\nf(x + p) = f(x) + p^T\\nabla f(x) + \\frac{1}{2}p^TH(x)p\n$$\n\nDifferentiating with respect to the direction vector $p$ and setting to zero, we get\n\n$$\nH(x)p = -\\nabla f(x)\n$$\n\ngiving\n\n$$\np = -H(x)^{-1}\\nabla f(x)\n$$\n\n\n```python\nfrom scipy.optimize import rosen, rosen_der, rosen_hess\n```\n\n#### Nelder-Mead\n\nThere are some optimization algorithms not based on the Newton method, but on other heuristic search strategies that do not require any derivatives, only function evaluations. One well-known example is the Nelder-Mead simplex algorithm.\n\n\n```python\nps = [x0]\nopt.minimize(rosen, x0, method='nelder-mead', callback=reporter)\n```\n\n\n```python\nps = np.array(ps)\nplt.figure(figsize=(12,4))\nplt.subplot(121)\nplt.contour(X, Y, Z, np.arange(10)**5, cmap='jet')\nplt.plot(ps[:, 0], ps[:, 1], '-ro')\nplt.subplot(122)\nplt.semilogy(range(len(ps)), rosen(ps.T));\n```\n\n#### BFGS\n\nAs calculating the Hessian is computationally expensive, sometimes first order methods that only use the first derivatives are preferred. Quasi-Newton methods use functions of the first derivatives to approximate the inverse Hessian. A well know example of the Quasi-Newoton class of algorithjms is BFGS, named after the initials of the creators. As usual, the first derivatives can either be provided via the `jac=` argument or approximated by finite difference methods.\n\n\n```python\nps = [x0]\nopt.minimize(rosen, x0, method='Newton-CG', jac=rosen_der, hess=rosen_hess, callback=reporter)\n```\n\n\n```python\nps = np.array(ps)\nplt.figure(figsize=(12,4))\nplt.subplot(121)\nplt.contour(X, Y, Z, np.arange(10)**5, cmap='jet')\nplt.plot(ps[:, 0], ps[:, 1], '-ro')\nplt.subplot(122)\nplt.semilogy(range(len(ps)), rosen(ps.T))\npass\n```\n\n#### Newton-CG\n\nSecond order methods solve for $H^{-1}$ and so require calculation of the Hessian (either provided or approximated using finite differences). For efficiency reasons, the Hessian is not directly inverted, but solved for using a variety of methods such as conjugate gradient. An example of a second order method in the `optimize` package is `Newton-GC`.\n\n\n```python\nps = [x0]\nopt.minimize(rosen, x0, method='Newton-CG', jac=rosen_der, hess=rosen_hess, callback=reporter)\n```\n\n\n```python\nps = np.array(ps)\nplt.figure(figsize=(12,4))\nplt.subplot(121)\nplt.contour(X, Y, Z, np.arange(10)**5, cmap='jet')\nplt.plot(ps[:, 0], ps[:, 1], '-ro')\nplt.subplot(122)\nplt.semilogy(range(len(ps)), rosen(ps.T))\npass\n```\n", "meta": {"hexsha": "d215df73161d0741eb6997781caa3a42feb468d0", "size": 29169, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/copies/lectures/T07G_Gradient_Descent_Optimization.ipynb", "max_stars_repo_name": "robkravec/sta-663-2021", "max_stars_repo_head_hexsha": "4dc8018f7b172eaf81da9edc33174768ff157939", "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/copies/lectures/T07G_Gradient_Descent_Optimization.ipynb", "max_issues_repo_name": "robkravec/sta-663-2021", "max_issues_repo_head_hexsha": "4dc8018f7b172eaf81da9edc33174768ff157939", "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/copies/lectures/T07G_Gradient_Descent_Optimization.ipynb", "max_forks_repo_name": "robkravec/sta-663-2021", "max_forks_repo_head_hexsha": "4dc8018f7b172eaf81da9edc33174768ff157939", "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": 27.6221590909, "max_line_length": 823, "alphanum_fraction": 0.5146559704, "converted": true, "num_tokens": 5605, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107914029486, "lm_q2_score": 0.9219218294919745, "lm_q1q2_score": 0.8640350874298277}} {"text": "# An intuitive introduction to the Entropy\n\nLet $X$ be a discrete random variable (RV) taking values from set $\\mathcal{X}$ with probability mass function $P(X)$.\n\n*Definition* the entropy $H(X)$ of the discrete random variable $X$ is\n\\begin{equation}\nH(X) = \\sum_{x\\in\\mathcal{X}}P(X)\\log \\frac{1}{P(X)} = -\\sum_{x\\in\\mathcal{X}}P(X)\\log P(X).\n\\end{equation}\n\nHow to make sense out of this definition? We'll, rather informally, argue below that the entrpy of an RV provides a lower bound on the amount of information provided by the RV, which we'll dfine as the average number of bits required to transmit the value the RV has taken.\n\nAs a motivating example consider asking your friend for advice. The probabilities of his answers are given in the table below:\n\n| $x$ | $P(x)$ |\n|----------|--------|\n| OK | $1/2$ |\n| Average | $1/4$ |\n| Bad | $1/8$ |\n| Terrible | $1/8$ |\n\nTo transmit the answer of your friend you must introduce an *encoding*, e.g.:\n\n| $x$ | $P(x)$ | Code 1 |\n|----------|--------|--------|\n| OK | $1/2$ | 00 |\n| Average | $1/4$ | 01 |\n| Bad | $1/8$ | 10 |\n| Terrible | $1/8$ | 11 |\n\nUnder this encoding, we spend 2 bits per answer.\n\nHowever, we could also consider a variable length code, that uses shorter codewords for more frequent symbols:\n\n| $x$ | $P(x)$ | Code 2 |\n|----------|--------|--------|\n| OK | $1/2$ | 0 |\n| Average | $1/4$ | 10 |\n| Bad | $1/8$ | 110 |\n| Terrible | $1/8$ | 111 |\n\nUnder this encoding the average number of bits to encode an answer is:\n\\begin{equation}\n\\mathbb{E}[L] = \\frac{1}{2} \\cdot 1 + \\frac{1}{4} \\cdot 2 + \\frac{1}{8} \\cdot 3 + \\frac{1}{8} \\cdot 3 = \\frac{7}{8}\n\\end{equation}\n\nThus, the new code is more efficient. Is it the best we can do?\n\n### The code space\n\nWe'll now try formalize the coding task, i.e. the assignment of code lengths to possible values of the RV. \n\nLet's first observe an important property of our code: in a variable length coding, no codeword can be the prefix of another one. Otherwise, decoding is not deterministic. Therefore, whenever a value is assigned a symbol of length $L$, $1/2^L$ of the code space is reserved and not available to other codes.\n\nThis can be visualised as a code space. Below, we indicate the codes assigned to symbols in the example and grey-out codes that are not available because the shorter codes are used:\n\n\n\nWe can observe, that the length 1 code for \"OK\" uses $1/2$ of the available codes, the langth 2 code for \"Average\" uses $1/4$ and the two length 3 codes for \"Bad\" and \"Terrible\" each use $1/8$ of the code space.\n\nIn general, a code of length $L$ uses $1/2^L$ of the code space. Equivalently, assignign a fraction $f$ of the code space to a symbol makes it use a symbol of length $L=\\log_2(1/f)$.\n\nAssuming that we assign a fraction of a bit to a symbol, our optmal coding problem can be formulated as partitioning the code space into four regions (one for each value of the RV) such that the average length of the code is minised. \n\nFormally, let $p_1, p_2, p_3, p_4$ be the proibabilities asigned to the 4 symbols and let $f_1, f_2, f_3, f_4$ be the coding space fractoins assigned to them.\n\nWe want to:\n\\begin{align}\n\\text{minimize } &p_1 \\log_2 \\frac{1}{f_1} + p_2 \\log_2 \\frac{1}{f_2} + p_3 \\log_2 \\frac{1}{f_3} + p_4 \\log_2 \\frac{1}{f_4} \\\\\n\\text{subject to: } & f_1 + f_2 + f_3 + f_4 = 1\n\\end{align}\n\nFor simplicity, we will solve this problem for the case of only two symbols:\n\\begin{align}\n\\text{minimize } &p_1 \\log_2 \\frac{1}{f_1} + p_2 \\log_2 \\frac{1}{f_2} \\\\\n\\text{subject to: } & f_1 + f_2 = 1\n\\end{align}\n\nNotice first that $p_2 = 1-p_1$ and likewise $f_2 = 1-f_1$. Then our minimization objective becomes\n\\begin{equation}\n\\text{minimize } C = p_1 \\log_2 \\frac{1}{f_1} + (1-p_1) \\log_2 \\frac{1}{1-f_1} \n\\end{equation}\n\nTo get the minimum over $f_1$ we compute the derivative of the expression with respect to $f_1$ and set it to zero:\n\\begin{equation}\n\\frac{\\partial C}{\\partial f_1} = \\frac{p_1}{\\log 2}\\frac{-1}{f_1} + \\frac{1 - p_1}{\\log 2}\\frac{1}{1 - f_1}\n\\end{equation}\n\nMultiplying both sides by $\\log 2 f_1 (1- f_1)$ we obtain:\n\\begin{align}\np_1(1-f_1) &= (1-p_1)f_1 \\\\\np_1 - p_1f_1 & =f_1 - p_1f_1 \\\\\nf_1 &= p_1\n\\end{align}\n\nThus the optimal fraction of code space allocated to symbol 1 is $p_1$, the probability assigned to this symbol and the optimal code length is $\\log_2(\\frac{1}{p_1})$!\n\nWe now see, that the entropy \n\\begin{equation}\nH(X) = \\sum_{x\\in\\mathcal{X}}P(X)\\log \\frac{1}{P(X)}\n\\end{equation}\nis simply the average code length!\n\n### A note about logarithm basis\n\nIt is custommary to copute the entropy using natural logarithms, which gives its value in \"nats\". IF $\\log_2$ were used, the entrpy has units of bits and corresponds and lowerbounds the average amount of bits needed to transmit a value of the RV.\n\n# Further Reading\n1. Chris Olah \"Visual Information theory\": https://colah.github.io/posts/2015-09-Visual-Information/\n2. JA Thomas ad TM Cover, \"Elements of Information Theory\", chapter 2\n", "meta": {"hexsha": "1e5b28fdf3bff6e9c754dc3ef47b78fd21e9fa8f", "size": 11654, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "ML/Lectures/02_entropy.ipynb", "max_stars_repo_name": "TheFebrin/DataScience", "max_stars_repo_head_hexsha": "3e58b89315960e7d4896e44075a8105fcb78f0c0", "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": "ML/Lectures/02_entropy.ipynb", "max_issues_repo_name": "TheFebrin/DataScience", "max_issues_repo_head_hexsha": "3e58b89315960e7d4896e44075a8105fcb78f0c0", "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/Lectures/02_entropy.ipynb", "max_forks_repo_name": "TheFebrin/DataScience", "max_forks_repo_head_hexsha": "3e58b89315960e7d4896e44075a8105fcb78f0c0", "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": 11654.0, "max_line_length": 11654, "alphanum_fraction": 0.7946627767, "converted": true, "num_tokens": 1663, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107861416413, "lm_q2_score": 0.9219218327098193, "lm_q1q2_score": 0.8640350855951126}} {"text": "# Rate of Change\nFunctions are often visualized as a line on a graph, and this line shows how the value returned by the function changes based on changes in the input value.\n\n## Linear Rate of Change\n\nFor example, imagine a function that returns the number of meters travelled by a cyclist based on the number of seconds that the cyclist has been cycling.\n\nHere is such a function:\n\n\\begin{equation}q(x) = 2x + 1\\end{equation}\n\nWe can plot the output for this function for a period of 10 seconds like this:\n\n\n```python\n%matplotlib inline\n\ndef q(x):\n return 2*x + 1\n\n# Plot the function\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\n# Create an array of x values from 0 to 10\nx = np.array(range(0, 11))\n\n# Set up the graph\nplt.xlabel('Seconds')\nplt.ylabel('Meters')\nplt.xticks(range(0,11, 1))\nplt.yticks(range(0, 22, 1))\nplt.grid()\n\n# Plot x against q(x)\nplt.plot(x,q(x), color='green')\n\nplt.show()\n```\n\nIt's clear from the graph that ***q*** is a *linear* function that describes a slope in which distance increases at a constant rate over time. In other words, the cyclist is travelling at a constant speed.\n\nBut what speed?\n\nSpeed, or more technically, velocity is a measure of change - it measures how the distance travelled changes over time (which is why we typically express it as a unit of distance per a unit of time, like *miles-per-hour* or *meters-per-second*). So we're looking for a way to measure the change in the line created by the function.\n\nThe change in values along the line define its *slope*, which we know from a previous lesson is represented like this:\n\n\\begin{equation}m = \\frac{\\Delta{y}}{\\Delta{x}} \\end{equation}\n\nWe can calculate the slope of our function like this:\n\n\\begin{equation}m = \\frac{q(x)_{2} - q(x)_{1}}{x_{2} - x_{1}} \\end{equation}\n\nSo we just need two ordered pairs of ***x*** and ***q(x)*** values from our line to apply this equation.\n\n- After 1 second, ***x*** is 1 and ***q***(1) = **3**.\n- After 10 seconds, ***x*** is 10 and ***q***(10) = 21.\n\nSo we can meassure the rate of change like this:\n\n\\begin{equation}m = \\frac{21 - 3}{10 - 1} \\end{equation}\n\nThis is the same as:\n\n\\begin{equation}m = \\frac{18}{9} \\end{equation}\n\nWhich simplifies to:\n\n\\begin{equation}m = \\frac{2}{1} \\end{equation}\n\nSo our rate of change is 2/1 or put another way, the cyclist is travelling at 2 meters-per-second.\n\n## Average Rate of Change\nOK, let's look at another function that calculates distance travelled for a given number of seconds:\n\n\\begin{equation}r(x) = x^{2} + x\\end{equation}\n\nLet's take a look at that using Python:\n\n\n```python\n%matplotlib inline\n\ndef r(x):\n return x**2 + x\n\n# Plot the function\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\n# Create an array of x values from 0 to 10\nx = np.array(range(0, 11))\n\n# Set up the graph\nplt.xlabel('Seconds')\nplt.ylabel('Meters')\nplt.grid()\n\n# Plot x against r(x)\nplt.plot(x,r(x), color='green')\n\nplt.show()\n```\n\nThis time, the function is not linear. It's actually a quadratic function, and the line from 0 seconds to 10 seconds shows an exponential increase; in other words, the cyclist is *accelerating*.\n\nTechnically, acceleration itself is a measure of change in velocity over time; and velocity, as we've already discussed, is a measure of change in distance over time. So measuring accelleration is pretty complex, and requires *differential calculus*, which we're going to cover shortly. In fact, even just measuring the velocity at a single point in time requires differential calculus; but we can use algebraic methods to calculate an *average* rate of velocity for a given period shown in the graph.\n\nFirst, we need to define a *secant* line that joins two points in our exponential arc to create a straight slope. For example, a secant line for the entire 10 second time span would join the following two points:\n\n- 0, ***r***(0)\n- 10, ***r***(10)\n\nRun the following Python code to visualize this line:\n\n\n```python\n%matplotlib inline\n\ndef r(x):\n return (x)**2 + x\n\n# Plot the function\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\n# Create an array of x values from 0 to 10\nx = np.array(range(0, 11))\n\n# Create an array for the secant line\ns = np.array([0,10])\n\n# Set up the graph\nplt.xlabel('Seconds')\nplt.ylabel('Meters')\nplt.grid()\n\n# Plot x against r(x)\nplt.plot(x,r(x), color='green')\n\n# Plot the secant line\nplt.plot(s,r(s), color='magenta')\n\nplt.show()\n```\n\nNow, because the secant line is straight, we can apply the slope formula we used for a linear function to calculate the average velocity for the 10 second period:\n\n- At 0 seconds, ***x*** is 0 and ***r***(0) = **0**.\n- At 10 seconds, ***x*** is 10 and ***r***(10) = 110.\n\nSo we can meassure the rate of change like this:\n\n\\begin{equation}m = \\frac{110 - 0}{10 - 0} \\end{equation}\n\nThis is the same as:\n\n\\begin{equation}m = \\frac{110}{10} \\end{equation}\n\nWhich simplifies to:\n\n\\begin{equation}m = \\frac{11}{1} \\end{equation}\n\nSo our rate of change is 11/1 or put another way, the cyclist is travelling at an average velocity of 11 meters-per-second over the 10-second period.\n\nOf course, we can measure the average velocity between any two points on the exponential line. Use the following Python code to show the secant line for the period between 2 and 7 seconds, and calculate the average velocity for that period\n\n\n```python\n%matplotlib inline\n\ndef r(x):\n return x**2 + x\n\n# Plot the function\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\n# Create an array of x values from 0 to 10\nx = np.array(range(0, 11))\n\n# Create an array for the secant line\ns = np.array([2,7])\n\n# Calculate rate of change\nx1 = s[0]\nx2 = s[-1]\ny1 = r(x1)\ny2 = r(x2)\na = (y2 - y1)/(x2 - x1)\n\n\n# Set up the graph\nplt.xlabel('Seconds')\nplt.ylabel('Meters')\nplt.grid()\n\n# Plot x against r(x)\nplt.plot(x,r(x), color='green')\n\n# Plot the secant line\nplt.plot(s,r(s), color='magenta')\n\nplt.annotate('Average Velocity =' + str(a) + ' m/s',((x2+x1)/2, (y2+y1)/2))\n\nplt.show()\n\n\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "7056680d6f74a049cc5ade2b0cbdc0f38174ac54", "size": 73995, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Basics of Calculus by Hiren/02-01-Rate of Change.ipynb", "max_stars_repo_name": "serkin/Basic-Mathematics-for-Machine-Learning", "max_stars_repo_head_hexsha": "ac0ae9fad82a9f0429c93e3da744af6e6d63e5ab", "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": "Basics of Calculus by Hiren/02-01-Rate of Change.ipynb", "max_issues_repo_name": "serkin/Basic-Mathematics-for-Machine-Learning", "max_issues_repo_head_hexsha": "ac0ae9fad82a9f0429c93e3da744af6e6d63e5ab", "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": "Basics of Calculus by Hiren/02-01-Rate of Change.ipynb", "max_forks_repo_name": "serkin/Basic-Mathematics-for-Machine-Learning", "max_forks_repo_head_hexsha": "ac0ae9fad82a9f0429c93e3da744af6e6d63e5ab", "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": 220.2232142857, "max_line_length": 17628, "alphanum_fraction": 0.9103858369, "converted": true, "num_tokens": 1688, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.960951703918909, "lm_q2_score": 0.8991213799730775, "lm_q1q2_score": 0.8640122221150497}} {"text": "## Geometric Distribution\n\nSuppose we have a biased coin with $\\mathbb{P}(H) = p$ and we toss it repeatedly, then the sample space will look like \n\n$$\\Omega = \\{H, TH, TTH, \\ldots \\}$$\nThen \n$$\\mathbb{P}(TH) = \\mathbb{P}(T)\\cdot \\mathbb{P}(H) = (1-p)p$$\n\nLet $X$ is the random variable defined as \n\n$$X = \\#\\text{ tosses untill first heads }$$\nThen \n$$\\begin{align}\\mathbb{P}(X=x) &= \\mathbb{P}(x-1 \\text{ tails followed by heads}) \\\\\n&= (1-p)^{x-1}p \\end{align}\n$$\nThis is probability mass function of random variable $X$. If we normalize we will get the probability distribution.\n\n### Practice Problem: The Geometric Distribution\n\nLet $X \\sim \\text {Geo}(p)$ so that\n\n$$p_ X(x) = (1-p)^{x-1} p\\qquad \\text {for }x=1, 2, \\dots $$\n \n**Question:** Show that each of the table entries $p_ X(x)$ is nonnegative for $x = 1, 2, \\dots.$\n\n**Solution:** Since $p$ is a probabiltiy hence $p \\in [0,1]$ then $1-p \\in [0,1]$, also $x-1 \\geq 0$. Hence \n\n$$p_X(x) = \\underbrace{(1-p)^{x-1}}_{\\geq 0}\\cdot \\underbrace{p}_{\\geq 0} \\geq 0.$$ \n\n**Question:**Show that the sum of all the table entries is 1, i.e., $\\sum _{x=1}^\\infty p_ X(x) = 1.$\n\n**Hint:** You may find the following result from calculus helpful: For $r\\in (-1,1),$\n\n$$\\sum _{i=0}^{\\infty }r^{i}=\\frac{1}{1-r}.$$\n\nSolution: For $p\\in (0,1),$\n\n$$\\begin{align}\n\\sum _{x=1}^{\\infty }p_{X}(x)&=\\sum _{x=1}^{\\infty }(1-p)^{x-1}p &\\\\\n&= p \\cdot \\sum _{i=0}^{\\infty }(1-p)^{i}&\\text{where } i = x-1\\\\\n&= p \\cdot \\frac{1}{1-(1-p)}&\\\\\n&= p \\cdot \\frac{1}{p}=1.&\n\\end{align}.$$\n\n### Exercise: The Expectation of a Geometric Distribution\n\nIn this exercise, we use the law of total expectation to find the expected value of a geometric random variable. The law of total expectation says that for a random variable $X$ (with alphabet $\\mathcal{X}$) and a partition $\\mathcal{B}_1,\\dots ,\\mathcal{B}_ n$ of the sample space,\n\n$$\\mathbb {E}[X]=\\sum _{i=1}^{n}\\mathbb {E}[X\\mid \\mathcal{B}_{i}]\\mathbb {P}(\\mathcal{B}_{i}),$$\n \nwhere\n\n$$\\mathbb {E}[X\\mid \\mathcal{B}_{i}] = \\sum _{x\\in \\mathcal{X}}xp_{X\\mid \\mathcal{B}_{i}}(x) = \\sum _{x\\in \\mathcal{X}}x\\frac{\\mathbb {P}(X=x,\\mathcal{B}_{i})}{\\mathbb {P}(\\mathcal{B}_{i})}.$$\n \nLet $X \\sim \\text {Geo}(p)$ be the number of tosses until we get heads for the first time, where the probability of heads is $p$. Let $\\mathcal{B}$ be the event that we get heads in 1 try. Let $\\mathcal{B}^c$ be the event that we get heads in more than 1 try. Note that $\\mathcal{B}$ and $\\mathcal{B}^c$ form a partition of the sample space.\n\n**Question:** What is $\\mathbb {P}(\\mathcal{B})?$\n\n**Solution:** $\\mathcal{B}$ is the event of getting \"head\" in one coin toss. Hence, $\\mathbb {P}(\\mathcal{B})=p.$\n\n**Question:** What is $\\mathbb {E}[X \\mid \\mathcal{B}]?$\n\n**Solution:** \n\n$$\\begin{align}\\require{cancel}\n\\mathbb{E}[X\\mid \\mathcal{B}] &= \\sum_{x=1}^{\\infty} xp_{X\\mid \\mathcal{B}}(x)\\\\\n&= \\sum_{x=1}^{\\infty} x\\frac{\\mathbb {P}(X=x,\\mathcal{B})}{\\mathbb{P}(\\mathcal{B})}\\\\\n&= 1\\times \\frac{\\cancelto{\\mathbb{P}(\\mathcal{B})}{\\mathbb {P}(X=1,\\mathcal{B})}}{\\mathbb{P}(\\mathcal{B})} + \\sum_{x=2}^{\\infty} x\\frac{\\cancelto{0}{\\mathbb {P}(X=x,\\mathcal{B})}}{\\mathbb{P}(\\mathcal{B})}\\\\\n&= 1.\n\\end{align}$$\n\n**Question:** What is $\\mathbb{E}[X \\mid \\mathcal{B}^c]?$ Write your answer in terms of $m \\triangleq \\mathbb {E}[X].$ Note that we do not know $\\mathbb {E}[X]$ for right now, but we can still relate $\\mathbb {E}[X \\mid \\mathcal{B}^ c]$ to $\\mathbb {E}[X].$\n\nHint: If you do not get heads the first time, then starting from the second toss, the distribution for the number of tosses remaining is still geometric!\n\n**Solution:** So we tossed the coin and it was tails, so this took up 1 toss. The number of tosses that remains is just another $\\text {Geo}(p)$ random variable (remember: the tosses are all independent so that initial toss doesn't affect any of the future tosses)!\n\nThus, the expectation of $X$ given that the first toss was tails (i.e., it takes more than 1 try) is\n\n$$\\mathbb {E}[X \\mid \\mathcal{B}^ c] = 1 + \\mathbb {E}[X].$$\n \nThe 1 appears because that's the first toss where we got tails.\n\nUsing the law of total expectation,\n\n$$\\mathbb {E}[X] = \\mathbb {E}[X \\mid \\mathcal{B}]\\mathbb {P}(\\mathcal{B}) + \\mathbb {E}[X \\mid \\mathcal{B}^ c](1 - \\mathbb {P}(\\mathcal{B})).$$\n \nUsing your answers to the previous part, you should now have a recursive equation, meaning that the unknown quantity $\\mathbb {E}[X]$ appears on both sides of the equation, and so you can solve for it.\n\n**Question:** What is $\\mathbb {E}[X]?$\n\nIn this part, please provide your answer as a mathematical formula (and not as Python code). Use ^ for exponentiation, e.g., x^2 denotes x^2. Explicitly include multiplication using *, e.g. x*y is xy.\n\n**Solution:** Putting together the pieces from the previous parts,\n\n$$\\begin{align}\\mathbb {E}[X] &= 1 \\cdot p + (1 + \\mathbb {E}[X]) \\cdot (1 - p)\\\\\t \t \n&= p + 1 - p + \\mathbb {E}[X] - \\mathbb {E}[X] p\\\\\t \t \n&= 1 + \\mathbb {E}[X] - \\mathbb {E}[X] p.\\end{align}$$\n\nRearranging terms yields\n\n$$\\mathbb {E}[X] = \\boxed {\\frac1p}.$$\n\n\n```python\n\n```\n", "meta": {"hexsha": "88c1651fa6af2157e7961f08b728f5ff37b14857", "size": 7305, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "week04/05 Geometric Distribution.ipynb", "max_stars_repo_name": "infimath/Computational-Probability-and-Inference", "max_stars_repo_head_hexsha": "e48cd52c45ffd9458383ba0f77468d31f781dc77", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-04-04T03:07:47.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-04T03:07:47.000Z", "max_issues_repo_path": "week04/05 Geometric Distribution.ipynb", "max_issues_repo_name": "infimath/Computational-Probability-and-Inference", "max_issues_repo_head_hexsha": "e48cd52c45ffd9458383ba0f77468d31f781dc77", "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": "week04/05 Geometric Distribution.ipynb", "max_forks_repo_name": "infimath/Computational-Probability-and-Inference", "max_forks_repo_head_hexsha": "e48cd52c45ffd9458383ba0f77468d31f781dc77", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-02-27T05:33:49.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-27T05:33:49.000Z", "avg_line_length": 40.1373626374, "max_line_length": 356, "alphanum_fraction": 0.5327857632, "converted": true, "num_tokens": 1863, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213691605412, "lm_q2_score": 0.9609517069942015, "lm_q1q2_score": 0.8640122144897857}} {"text": "# Задание 2 Вариант 29\n\nХомутов Евений Васильевич, БПМ-151\n\n\n```python\nfrom sympy.solvers import solve\nfrom sympy import Symbol, diff, sqrt,cos,sin\nfrom scipy.misc import derivative\nimport matplotlib.pyplot as plt\n%matplotlib inline\nimport numpy as np\n```\n\nОпределим необходимые для решения задач методы\n\n\n```python\ndef BisecMethod(f,a,b,epselon):\n n = 0\n A = a\n B = b\n while (B-A) >= 2*epselon:\n n = n + 1\n x = (A+B)/2\n if f(x)*f(A) < 0:\n B = x\n elif f(x)*f(B) < 0:\n A = x\n return x, n\n```\n\n\n```python\ndef NewtoonMethod(f,x,epselon):\n n = 1\n x_old = x\n x_new = x_old - f(x_old)/derivative(f,x_old,dx = epselon)\n while abs(x_new - x_old) >= epselon:\n x_old = x_new\n x_new = x_old - f(x_old)/derivative(f,x_old,dx = epselon)\n n = n + 1\n return x_new, n\n```\n\n\n```python\ndef SimpleIterationMethod(phi,f,x,q,epselon):\n n = 1\n x_old = x\n x_new = phi(x_old,f)\n while abs(x_new - x_old) >= (1 - q)/q*epselon:\n x_old = x_new\n x_new = phi(x_old,f)\n n = n + 1\n return x_new,q, n\n```\n\nЧтобы найти ответы встроеными методами:\n\n\n```python\nx = Symbol('x')\n```\n\n## Задание № 1\n\n\n\n\n```python\ndef f1(x):\n return x**4 - 26/5 * x**2 + 1\ndef g1(x):\n return x**4 - 10 * x**2 + 25\nepselon1 = 10**(-10)\na1 = 0\nb1 = 3\n```\n\nНайдем корни уравнения $f(x) = 0$ встроеными методами:\n\n\n```python\nExactAnswer1 = solve(f1(x),x)\nExactAnswer1\n```\n\n\n\n\n [-2.23606797749979, -0.447213595499958, 0.447213595499958, 2.23606797749979]\n\n\n\nГрафик функции $f(x)$:\n\n\n```python\nX = np.arange(a1, b1, 0.01)\n\nfig = plt.figure() \nplt.plot(X, f1(X))\nplt.show() \n```\n\nИз графика поулчаем что отрезко локализации, например [0;1] и [2;3]\n\n\n```python\nx11 = BisecMethod(f1,0,1,0.1*epselon1)\nx12 = BisecMethod(f1,2,3,0.1*epselon1)\nprint(x11, x12)\n```\n\n (0.447213595485664, 36) (2.2360679774865275, 36)\n\n\nПостроим график функции $g(x)$:\n\n\n```python\nfig = plt.figure()\nplt.plot(X, g1(X))\nplt.show()\n```\n\nИмеем корень четной кратности, следовательно не можем применить метод бисекции\n\nВывод: Мы нашли корни правильно!\n\n## Задание №2\n\n\n\n\n```python\ndef f2(x):\n return np.sqrt(x)-np.cos(x)\nepselon2 = 10**(-6)\n```\n\nНайдем корни уравнения $f(x) = 0$ встроеными методами Wolfram:\n\n\n\nПостроим график функции:\n\n\n```python\nX = np.arange(0, 2,0.1)\nfig = plt.figure()\nplt.plot(X, f2(X))\nplt.show()\n```\n\nИз графика: возьмем отрезок локализации как [0;1]\n\n\n```python\nprint(NewtoonMethod(f2,0.75,epselon2))\nprint(BisecMethod(f2,0,1,epselon2))\n```\n\n (0.6417143708728962, 3)\n (0.6417140960693359, 19)\n\n\nВывод: в пределах точности наши корни совпали, при это число итераций у метода Ньютона в 6 раз меньше чем у метода бисекции\n\n## Задание №3\n\n\n\n\n```python\ndef f3(x):\n return x - np.e**(-x**(2))\nepselon3 = 10**(-5)\n```\n\nГрафик:\n\n\n```python\nX = np.arange(0.1, 1, 0.01)\n\nfig = plt.figure() \nplt.plot(X, f3(X))\nplt.show() \n```\n\nИз графика возьмем отрезок локализации как [0.6;0.7]\n\n\n```python\na3 = .6\nb3 = .7\n```\n\nОпределим константы m и M из графика производной:\n\nОпределим производную функции:\n\n\n```python\ndef ff3(x):\n return 1 + 2*x*np.e**(-x**2)\n```\n\nГрафик производной:\n\n\n```python\nX = np.arange(a3, b3, 0.01)\n\nfig = plt.figure() \nplt.plot(X, ff3(X))\nplt.show() \n```\n\nПроизводная функции монотонно возрастает.\n\nСледовательно для m и M берем значение производной в начале и конце отрезка соответсвенно\n\n\n```python\nm = ff3(a3)\nM = ff3(b3)\n```\n\nОпределим q\n\n\n```python\nq = (M-m)/(M+m)\n```\n\nОпределим функцию $\\phi$\n\n\n```python\n def phi(x,f):\n return x - 2/(M+m)*f(x)\n```\n\nОтвет первым способом:\n\n\n```python\nSimpleIterationMethod(phi,f3,a3+b3/2,q,epselon3)\n```\n\n\n\n\n (0.6529186597988018, 0.005538830287837204, 3)\n\n\n\nВторой способ;\n\nСделаем из метода простой итерации метод Ньютона - потому что все любят Ньютона\n\n\n```python\ndef gamma(x,f):\n return x - f(x)/derivative(f,x,dx = 10**(-5))\n\ndef Gamma(x):\n return (-np.e**(-(x)**2)+x)*(2*np.e**(-x**2)-4*x**2*np.e**(-x**2))/(1+2*x*np.e**(-x**2))**2\n```\n\nГрафик модуля производной функции $\\gamma$\n\n\n```python\nX = np.arange(a3, b3, 0.01)\n\nfig = plt.figure() \nplt.plot(X, abs(Gamma(X)))\nplt.show() \n```\n\nСледовательно Q равен значению гамма в начале отрезка\n\n\n```python\nQ = abs(Gamma(a3))\n```\n\nСравним овтеты метода Ньютона и метода простой итерации, превращеного в метод Ньютона:\n\n\n```python\nSimpleIterationMethod(gamma,f3,a3+b3/2,Q,epselon3)\n```\n\n\n\n\n (0.6529186404213283, 0.011306103997355802, 3)\n\n\n\n\n```python\nNewtoonMethod(f3,a3+b3/2,epselon3)\n```\n\n\n\n\n (0.6529186404213283, 3)\n\n\n\nВывод: все ответы совпали\n", "meta": {"hexsha": "d97f7d40dcff87b612f4c817c820ccd2a75b408e", "size": 702317, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "NumMeth_Khomutov_Task_2_.29.ipynb", "max_stars_repo_name": "evgeniy97/NumericalMethods", "max_stars_repo_head_hexsha": "bc1c51adc9cf7b27a05d5c850bb73f98065f139a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-03-04T23:27:34.000Z", "max_stars_repo_stars_event_max_datetime": "2018-03-04T23:27:34.000Z", "max_issues_repo_path": "NumMeth_Khomutov_Task_2_.29.ipynb", "max_issues_repo_name": "evgeniy97/NumericalMethods", "max_issues_repo_head_hexsha": "bc1c51adc9cf7b27a05d5c850bb73f98065f139a", "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": "NumMeth_Khomutov_Task_2_.29.ipynb", "max_forks_repo_name": "evgeniy97/NumericalMethods", "max_forks_repo_head_hexsha": "bc1c51adc9cf7b27a05d5c850bb73f98065f139a", "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": 958.1405184175, "max_line_length": 220164, "alphanum_fraction": 0.9537516535, "converted": true, "num_tokens": 1852, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582593509314, "lm_q2_score": 0.9284087946129328, "lm_q1q2_score": 0.8638456310016458}} {"text": "Linear Algebra Examples\n====\n\nThis just shows the machanics of linear algebra calculations with python. See Lecture 5 for motivation and understanding.\n\n\n```python\nimport numpy as np\nimport scipy.linalg as la\nimport matplotlib.pyplot as plt\n%matplotlib inline\n```\n\n\n```python\nplt.style.use('ggplot')\n```\n\nResources\n----\n\n- [Tutorial for `scipy.linalg`](http://docs.scipy.org/doc/scipy/reference/tutorial/linalg.html)\n\nExact solution of linear system of equations\n----\n\n\\begin{align}\nx + 2y &= 3 \\\\\n3x + 4y &= 17\n\\end{align}\n\n\n\n```python\nA = np.array([[1,2],[3,4]])\nA\n```\n\n\n\n\n array([[1, 2],\n [3, 4]])\n\n\n\n\n```python\nb = np.array([3,17])\nb\n```\n\n\n\n\n array([ 3, 17])\n\n\n\n\n```python\nx = la.solve(A, b)\nx\n```\n\n\n\n\n array([11., -4.])\n\n\n\n\n```python\nnp.allclose(A @ x, b)\n```\n\n\n\n\n True\n\n\n\n\n```python\nA1 = np.random.random((1000,1000))\nb1 = np.random.random(1000)\n```\n\n### Using solve is faster and more stable numerically than using matrix inversion\n\n\n```python\n%timeit la.solve(A1, b1)\n```\n\n 437 ms ± 115 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n\n\n\n```python\n%timeit la.inv(A1) @ b1\n```\n\n 584 ms ± 127 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n\n\n### Under the hood (Optional)\n\nThe `solve` function uses the `dgesv` fortran function to do the actual work. Here is an example of how to do this directly with the `lapack` function. There is rarely any reason to use `blas` or `lapack` functions directly becuase the `linalg` package provides more convenient functions that also perfrom error checking, but you can use Python to experiment with `lapack` or `blas` before using them in a language like C or Fortran.\n\n- [How to interpret lapack function names](http://www.netlib.org/lapack/lug/node24.html)\n- [Summary of BLAS functions](http://cvxopt.org/userguide/blas.html)\n- [Sumary of Lapack functions](http://cvxopt.org/userguide/lapack.html)\n\n\n```python\nimport scipy.linalg.lapack as lapack\n```\n\n\n```python\nlu, piv, x, info = lapack.dgesv(A, b)\nx\n```\n\nBasic information about a matrix\n----\n\n\n```python\nC = np.array([[1, 2+3j], [3-2j, 4]])\nC\n```\n\n\n\n\n array([[1.+0.j, 2.+3.j],\n [3.-2.j, 4.+0.j]])\n\n\n\n\n```python\nC.conjugate()\n```\n\n\n\n\n array([[1.-0.j, 2.-3.j],\n [3.+2.j, 4.-0.j]])\n\n\n\n#### Trace\n\n\n```python\ndef trace(M):\n return np.diag(M).sum()\n```\n\n\n```python\ntrace(C)\n```\n\n\n\n\n (5+0j)\n\n\n\n\n```python\nnp.allclose(trace(C), la.eigvals(C).sum())\n```\n\n\n\n\n True\n\n\n\n#### Determinant\n\n\n```python\nla.det(C)\n```\n\n\n\n\n (-8-5j)\n\n\n\n#### Rank\n\n\n```python\nnp.linalg.matrix_rank(C)\n```\n\n\n\n\n 2\n\n\n\n#### Norm\n\n\n```python\nla.norm(C, None) # Frobenius (default)\n```\n\n\n\n\n 6.557438524302\n\n\n\n\n```python\nla.norm(C, 2) # largest sinular value\n```\n\n\n\n\n 6.389028023601217\n\n\n\n\n```python\nla.norm(C, -2) # smallest singular value\n```\n\n\n\n\n 1.4765909770949925\n\n\n\n\n```python\nla.svdvals(C)\n```\n\nLeast-squares solution\n----\n\n\n```python\nla.solve(A, b)\n```\n\n\n```python\nx, resid, rank, s = la.lstsq(A, b)\nx\n```\n\n\n```python\nA1 = np.array([[1,2],[2,4]])\nA1\n```\n\n\n```python\nb1 = np.array([3, 17])\nb1\n```\n\n\n```python\ntry:\n la.solve(A1, b1)\nexcept la.LinAlgError as e:\n print(e)\n```\n\n\n```python\nx, resid, rank, s = la.lstsq(A1, b1)\nx\n```\n\n\n```python\nA2 = np.random.random((10,3))\nb2 = np.random.random(10)\n```\n\n\n```python\ntry:\n la.solve(A2, b2)\nexcept ValueError as e:\n print(e)\n```\n\n\n```python\nx, resid, rank, s = la.lstsq(A2, b2)\nx\n```\n\n### Normal equations\n\nOne way to solve least squares equations $X\\beta = y$ for $\\beta$ is by using the formula $\\beta = (X^TX)^{-1}X^Ty$ as you may have learnt in statistical theory classes (or can derive yourself with a bit of calculus). This is implemented below.\n\nNote: This is not how the `la.lstsq` function solves least square problems as it can be inefficent for large matrices.\n\n\n```python\ndef least_squares(X, y):\n return la.solve(X.T @ X, X.T @ y)\n```\n\n\n```python\nleast_squares(A2, b2)\n```\n\nMatrix Decompositions\n----\n\n\n```python\nA = np.array([[1,0.6],[0.6,4]])\nA\n```\n\n\n\n\n array([[1. , 0.6],\n [0.6, 4. ]])\n\n\n\n### LU\n\n\n```python\np, l, u = la.lu(A)\n```\n\n\n```python\np\n```\n\n\n\n\n array([[1., 0.],\n [0., 1.]])\n\n\n\n\n```python\nl\n```\n\n\n\n\n array([[1. , 0. ],\n [0.6, 1. ]])\n\n\n\n\n```python\nu\n```\n\n\n\n\n array([[1. , 0.6 ],\n [0. , 3.64]])\n\n\n\n\n```python\nnp.allclose(p@l@u, A)\n```\n\n\n\n\n True\n\n\n\n### Choleskey\n\n\n```python\nU = la.cholesky(A)\nU\n```\n\n\n\n\n array([[1. , 0.6 ],\n [0. , 1.9078784]])\n\n\n\n\n```python\nnp.allclose(U.T @ U, A)\n```\n\n\n\n\n True\n\n\n\n\n```python\n# If workiing wiht complex matrices\nnp.allclose(U.T.conj() @ U, A)\n```\n\n\n\n\n True\n\n\n\n### QR\n\n\n```python\nQ, R = la.qr(A)\n```\n\n\n```python\nQ\n```\n\n\n\n\n array([[-0.85749293, -0.51449576],\n [-0.51449576, 0.85749293]])\n\n\n\n\n```python\nnp.allclose((la.norm(Q[:,0]), la.norm(Q[:,1])), (1,1))\n```\n\n\n\n\n True\n\n\n\n\n```python\n\n```\n\n\n```python\nnp.allclose(Q@R, A)\n```\n\n\n\n\n True\n\n\n\n### Spectral\n\nWhen matrix is symmetric, you can use la.eigh\n\n\n```python\nu, v = la.eig(A)\n```\n\n\n```python\nu\n```\n\n\n\n\n array([0.88445056+0.j, 4.11554944+0.j])\n\n\n\n\n```python\nv\n```\n\n\n\n\n array([[-0.98195639, -0.18910752],\n [ 0.18910752, -0.98195639]])\n\n\n\n\n```python\nnp.allclose((la.norm(v[:,0]), la.norm(v[:,1])), (1,1))\n```\n\n\n\n\n True\n\n\n\n\n```python\nnp.allclose(v @ np.diag(u) @ v.T, A)\n```\n\n\n\n\n True\n\n\n\n#### Inverting A\n\n\n```python\nnp.allclose(v @ np.diag(1/u) @ v.T, la.inv(A))\n```\n\n#### Powers of A\n\n\n```python\nnp.allclose(v @ np.diag(u**5) @ v.T, np.linalg.matrix_power(A, 5))\n```\n\n### SVD\n\n\n```python\nU, s, V = la.svd(A)\n```\n\n\n```python\nU\n```\n\n\n```python\nnp.allclose((la.norm(U[:,0]), la.norm(U[:,1])), (1,1))\n```\n\n\n```python\ns\n```\n\n\n```python\nV\n```\n\n\n```python\nnp.allclose((la.norm(V[:,0]), la.norm(V[:,1])), (1,1))\n```\n\n\n```python\nnp.allclose(U @ np.diag(s) @ V, A)\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "2a1d4d98a850642594e1987d5c8c14440dae0af8", "size": 19673, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/copies/lectures/T06_Linear_Algebra_Examples.ipynb", "max_stars_repo_name": "robkravec/sta-663-2021", "max_stars_repo_head_hexsha": "4dc8018f7b172eaf81da9edc33174768ff157939", "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/copies/lectures/T06_Linear_Algebra_Examples.ipynb", "max_issues_repo_name": "robkravec/sta-663-2021", "max_issues_repo_head_hexsha": "4dc8018f7b172eaf81da9edc33174768ff157939", "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/copies/lectures/T06_Linear_Algebra_Examples.ipynb", "max_forks_repo_name": "robkravec/sta-663-2021", "max_forks_repo_head_hexsha": "4dc8018f7b172eaf81da9edc33174768ff157939", "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": 17.612354521, "max_line_length": 442, "alphanum_fraction": 0.4515325573, "converted": true, "num_tokens": 1936, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087965937712, "lm_q2_score": 0.9304582540478871, "lm_q1q2_score": 0.8638456279213402}} {"text": "---\nauthor: Nathan Carter (ncarter@bentley.edu)\n---\n\nThis answer assumes you have imported SymPy as follows.\n\n\n```python\nfrom sympy import * # load all math functions\ninit_printing( use_latex='mathjax' ) # use pretty math output\n```\n\nLet's compute the area under $\\sin x$ from $x=0$ to $x=\\pi$.\n\nWe use the same technique as in how to write and evaluate indefinite integrals,\nexcept that we add the lower and upper bounds together with $x$, as shown below.\n\n\n```python\nvar( 'x' )\nformula = sin(x)\nIntegral( formula, (x,0,pi) )\n```\n\n\n\n\n$\\displaystyle \\int\\limits_{0}^{\\pi} \\sin{\\left(x \\right)}\\, dx$\n\n\n\nThe above code just displays the definite integral.\nTo evaluate it, use the `integrate` command.\n\n\n```python\nintegrate( formula, (x,0,pi) )\n```\n\n\n\n\n$\\displaystyle 2$\n\n\n", "meta": {"hexsha": "69773fd3c9a6a20e113ef96cf99b648679c33b38", "size": 2471, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "database/tasks/How to write and evaluate definite integrals/Python, using SymPy.ipynb", "max_stars_repo_name": "nathancarter/how2data", "max_stars_repo_head_hexsha": "7d4f2838661f7ce98deb1b8081470cec5671b03a", "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": "database/tasks/How to write and evaluate definite integrals/Python, using SymPy.ipynb", "max_issues_repo_name": "nathancarter/how2data", "max_issues_repo_head_hexsha": "7d4f2838661f7ce98deb1b8081470cec5671b03a", "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": "database/tasks/How to write and evaluate definite integrals/Python, using SymPy.ipynb", "max_forks_repo_name": "nathancarter/how2data", "max_forks_repo_head_hexsha": "7d4f2838661f7ce98deb1b8081470cec5671b03a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-07-18T19:01:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T06:47:11.000Z", "avg_line_length": 22.0625, "max_line_length": 99, "alphanum_fraction": 0.5078915419, "converted": true, "num_tokens": 220, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9736446502128796, "lm_q2_score": 0.8872045847699185, "lm_q1q2_score": 0.8638219976055703}} {"text": "# Quadratic programming examples\n\nA quadratic programming problem can be expressed in the following form:\n\n$$\n\\begin{align}\n\\text{minimize} & \\quad \\frac{1}{2}x^T Q x + p^T x \\\\\n\\text{subject to} & \\quad\n\\begin{cases}\nG x \\le h \\\\\nA x = b\n\\end{cases}\n\\end{align}\n$$\n\nwhere:\n- $p$ is a real-valued, $n$-dimensional vector;\n- $Q$ is an $n \\times n$-dimensional real symmetric matrix;\n- $G$ is an $m \\times n$-dimensional real matrix;\n- $h$ is an $m$-dimensional real vector;\n- $A$ is a $p \\times n$-dimensional real matrix;\n- $b$ is a $p$-dimensional real vector.\n\nWe will use the [qpsolvers](https://github.com/stephane-caron/qpsolvers) library, together with [numpy](https://numpy.org/), to formulate and solve a few examples of quadratic programming problems. Both libraries can be installed with `pip` as explained in the README file; once installed, we can import them as follows:\n\n\n```python\nimport numpy as np\n\nfrom qpsolvers import solve_qp\n```\n\n## Example 1 \n\nThis example is taken from [CVXOPT](https://cvxopt.org/examples/tutorial/qp) and is formulated as follows:\n\n$$\n\\begin{align}\n\\text{minimize} & \\quad f(x) = 2x_1^2 + x_2^2 + x_1x_2 + x_1 + x_2 \\\\\n\\text{subject to} & \\quad\n\\begin{cases}\nx_1 \\ge 0 \\\\\nx_2 \\ge 0 \\\\\nx_1 + x_2 = 1\n\\end{cases}\n\\end{align}\n$$\n\nWe need to extract the $Q$ matrix first. We have 2 variables, so for the quadratic term we have:\n\n$\n\\begin{align}\nq(x) & = \\dfrac{1}{2}x^T Q x \\\\\n& = \\dfrac{1}{2} \\begin{bmatrix}x_1 & x_2\\end{bmatrix}\\begin{bmatrix}a_{11} & a_{12} \\\\ a_{21} & a_{22}\\end{bmatrix}\\begin{bmatrix}x_1 \\\\ x_2\\end{bmatrix} \\\\\n& = \\dfrac{1}{2} \\sum\\limits_{i=1}^2 \\sum\\limits_{j=1}^2 a_{ij} x_i x_j \\\\\n& = \\dfrac{1}{2} (a_{11} x_1 x_1 + a_{12} x_1 x_2 + a_{21} x_2 x_1 + a_{22} x_2 x_2) \\\\\n& = \\dfrac{1}{2} (a_{11} x_1^2 + a_{22} x_2^2 + (a_{12} + a_{21}) x_1 x_2)\n\\end{align}\n$\n\nSince $Q$ is assumed to be symmetric we have that $a_{12} = a_{21}$, so that:\n\n$\nq(x) = \\dfrac{1}{2} a_{11} x_1^2 + \\dfrac{1}{2} a_{22} x_2^2 + a_{12} x_1 x_2\n$\n\nNow we can find the values for the elements $a_{ij}$:\n\n$\n\\begin{cases}\n\\dfrac{1}{2} a_{11} & = 2 \\implies a_{11} = 4 \\\\\n\\dfrac{1}{2} a_{22} & = 1 \\implies a_{22} = 2 \\\\\na_{12} & = 1\n\\end{cases}\n$\n\nand write the $Q$ matrix as:\n\n$Q = \\begin{bmatrix}4 & 1 \\\\ 1 & 2\\end{bmatrix}$\n\nor, in order to show the quadratic coefficients more clearly, as:\n\n$Q = 2 * \\begin{bmatrix}2 & \\dfrac{1}{2} \\\\ \\dfrac{1}{2} & 1\\end{bmatrix}$\n\n\n```python\nQ = 2 * np.array([[2, 0.5], [0.5, 1]])\n```\n\nThe linear term is straightforward:\n\n$\np(x) = p^T x = \\begin{bmatrix}x_1 & x_2\\end{bmatrix}\\begin{bmatrix}a_1 \\\\ a_2\\end{bmatrix} = a_1 x_1 + a_2 x_2\n$\n\nresulting in:\n\n$\n\\begin{cases}\na_1 = 1 \\\\\na_2 = 1\n\\end{cases}\n$\n\nfrom which the $p$ vector can be written as:\n\n$\np = \\begin{bmatrix}1 & 1\\end{bmatrix}\n$\n\n\n```python\np = np.array([1.0, 1.0])\n```\n\nWe have two inequality constraints, $x_1 \\ge 0$ and $x_2 \\ge 0$. We need to write them in the form $G x \\le h$, so we have:\n\n$\n\\begin{align}\n\\begin{cases}\n-x_1 &+ 0x_2 & \\le 0 \\\\\n0x_2 &- x_2 & \\le 0\n\\end{cases}\n\\end{align}\n$\n\nfrom which we derive:\n\n$\n\\begin{bmatrix}-1 & 0 \\\\ 0 & -1\\end{bmatrix} \\begin{bmatrix}x_1 \\\\ x_2 \\end{bmatrix} \\le \\begin{bmatrix}0 \\\\ 0 \\end{bmatrix} \\implies \nG = \\begin{bmatrix}-1 & 0 \\\\ 0 & -1\\end{bmatrix} , h = \\begin{bmatrix}0 \\\\ 0 \\end{bmatrix}\n$\n\n\n```python\nG = np.array([[-1.0, 0.0], [0.0, -1.0]])\nh = np.array([0.0, 0.0])\n```\n\nFinally, we have an equality constraint $x_1 + x_2 = 1$, that we can represent as:\n\n$\n\\begin{bmatrix}1 & 1\\end{bmatrix} \\begin{bmatrix}x_1 \\\\ x_2 \\end{bmatrix} = \\begin{bmatrix}1\\end{bmatrix} \\implies \nA = \\begin{bmatrix}1 & 1\\end{bmatrix} , b = \\begin{bmatrix}1\\end{bmatrix}\n$\n\n\n```python\nA = np.array([1.0, 1.0])\nb = np.array([1.0])\n```\n\nWe now have everything we need to run the solver, which will return the optimal solution $x^* = \\begin{bmatrix}x^*_1 & x^*_2\\end{bmatrix}$.\n\n\n```python\nx_star = solve_qp(Q, p, G, h, A, b)\nprint(x_star)\n```\n\n [0.25 0.75]\n\n\nThe `solve_qp` method uses the [quadprog](https://pypi.python.org/pypi/quadprog/) solver by default, but it can be used with other solvers as well; take a look at the [project's page](https://github.com/stephane-caron/qpsolvers#solvers) to find the list of supported solvers.\n\n## Example 2 \n\nThis example is taken from the [Northwestern University website](https://optimization.mccormick.northwestern.edu/index.php/Quadratic_programming#Numerical_example) and is formulated as follows:\n\n$$\n\\begin{align}\n\\text{minimize} & \\quad f(x) = 3x_1^2 + x_2^2 + 2x_1x_2 + x_1 + 6x_2 + 2 \\\\\n\\text{subject to} & \\quad\n\\begin{cases}\n2x_1 + 3x_2 \\ge 4 \\\\\nx_1 \\ge 0 \\\\\nx_2 \\ge 0\n\\end{cases}\n\\end{align}\n$$\n\nThe constant term $2$ in the objective function can be discarded. Since there are no equality constraints, we will only have $G$ and $h$; let's keep in mind that the inequality contraints have to be expressed as $Gx \\le h$.\n\n\n```python\nQ = 2 * np.array([[3.0, 1.0], [1.0, 1.0]])\np = np.array([1.0, 6.0])\nG = np.array([[-2.0, -3.0], [-1.0, 0.0], [0.0, -1.0]])\nh = np.array([-4.0, 0.0, 0.0])\n\nx_star = solve_qp(Q, p, G, h)\nprint(x_star)\n```\n\n [0.5 1. ]\n\n\nSince the objective function can be expressed as $f(x) = \\frac{1}{2}x^T Q x + p^T x$, its value in $x^*$ can be found as follows:\n\n\n```python\nf = 0.5 * x_star.T @ Q @ x_star + p.T @ x_star + 2\nprint(f)\n```\n\n 11.25\n\n\n## Example 3\n\nThis example is taken from the [Matlab website](https://uk.mathworks.com/help/optim/ug/quadprog.html) and is formulated as follows:\n\n$$\n\\begin{align}\n\\text{minimize} & \\quad f(x) = \\dfrac{1}{2} x_1^2 + x_2^2 − x_1 x_2 − 2 x_1 − 6 x_2 \\\\\n\\text{subject to} & \\quad\n\\begin{cases}\nx_1 + x_2 \\le 2 \\\\\n-x_1 + 2 x_2 \\le 2 \\\\\n2 x_1 + x_2 \\le 3\n\\end{cases}\n\\end{align}\n$$\n\nThis time, instead of using float numbers, we will declare the type of each variable explicitly with `dtype`:\n\n\n```python\nQ = np.array([[1, -1], [-1, 2]], dtype=np.float)\np = np.array([-2, -6], dtype=np.float)\n\nG = np.array([[1, 1], [-1, 2], [2, 1]], dtype=np.float)\nh = np.array([2, 2, 3], dtype=np.float)\n\nx_star = solve_qp(Q, p, G, h)\nprint(x_star)\n```\n\n [0.66666667 1.33333333]\n\n\nValue of the objective function in $x^*$:\n\n\n```python\nf = 0.5 * x_star.T @ Q @ x_star + p.T @ x_star\nprint(f)\n```\n\n -8.222222222222218\n\n", "meta": {"hexsha": "9eb557f2add12e4728a361dedc2096c9949de778", "size": 10800, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "qp.ipynb", "max_stars_repo_name": "nvitucci/notebook_qp", "max_stars_repo_head_hexsha": "1c8489a597a1caff80c4f179328f14d3ac85de9f", "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": "qp.ipynb", "max_issues_repo_name": "nvitucci/notebook_qp", "max_issues_repo_head_hexsha": "1c8489a597a1caff80c4f179328f14d3ac85de9f", "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": "qp.ipynb", "max_forks_repo_name": "nvitucci/notebook_qp", "max_forks_repo_head_hexsha": "1c8489a597a1caff80c4f179328f14d3ac85de9f", "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.7990074442, "max_line_length": 326, "alphanum_fraction": 0.4927777778, "converted": true, "num_tokens": 2467, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625069680097, "lm_q2_score": 0.9273632931373373, "lm_q1q2_score": 0.8638041378958135}} {"text": "# Optimization in Python\n\nYou might have noticed that we didn't do anything related to sparsity with scikit-learn models. A lot of the work we covered in the machine learning class is very recent research, and as such is typically not implemented by the popular libraries.\n\nIf we want to do things like sparse regression, we're going to have to roll up our sleeves and do it ourselves. For that, we need to be able to solve optimization problems. In Julia, we did this with JuMP. In Python, we'll use a similar library called *pyomo*.\n\n# Installing pyomo\n\nYou can run the following command to install pyomo if you haven't already.\n\n\n```python\n!pip install pyomo --user\n```\n\n# Intro to pyomo\n\nLet's see how we translate a simple, 2 variable LP to pyomo code.\n\n$$\n\\begin{align*}\n\\max_{x,y} \\quad& x + 2y \\\\\n\\text{s.t.}\\quad& x + y \\leq 1 \\\\\n& x, y \\geq 0.\n\\end{align*}\n$$\n\nFirst thing is to import the pyomo functions:\n\n\n```python\nfrom pyomo.environ import *\nfrom pyomo.opt import SolverFactory\n```\n\nNext, we construct a model object. This is a container for everything in our optimization problem: variables, constraints, solver options, etc.\n\n\n```python\nm = ConcreteModel()\n```\n\nNext, we define the two decision variables in our optimization problem. We use the ``Var`` function to create the variables. The `within` keyword is used to specify the bounds on the variables, or equivalently the `bounds` keyword. The variables are added to the model object with names `x` and `y`.\n\n\n```python\nm.x = Var(within=NonNegativeReals)\nm.y = Var(bounds=(0, float('inf')))\n```\n\nWe now add the single constraint of our problem using the ``Constraint`` function. We write it algebraically, and save the result to the model.\n\n\n```python\nm.con = Constraint(expr=m.x + m.y <= 1)\n```\n\nWe specify the objective function with the `Objective` function:\n\n\n```python\nm.obj = Objective(sense=maximize, expr=m.x + 2 * m.y)\n```\n\nWe solve the optimization problem by first specifying a solver using `SolverFactory` and then using this solver to solve the model:\n\n\n```python\nsolver = SolverFactory('gurobi')\nsolver.solve(m)\n```\n\nWe can now inspect the solution values and optimal cost.\n\n\n```python\nm.obj()\n```\n\n\n```python\nm.x.value\n```\n\n\n```python\nm.y.value\n```\n\nLet's put it all together to compare with Julia/JuMP\n\n\n```python\n# Create model\nm = ConcreteModel()\n# Add variables\nm.x = Var(within=NonNegativeReals)\nm.y = Var(bounds=(0, float('inf')))\n# Add constraint\nm.con = Constraint(expr=m.x + m.y <= 1)\n# Add objective\nm.obj = Objective(sense=maximize, expr=m.x + 2 * m.y)\n# Solve model\nsolver = SolverFactory('gurobi')\nsolver.solve(m)\n# Inspect solution\nprint(m.obj())\nprint(m.x.value)\nprint(m.y.value)\n```\n\n```julia\n# Create model\nm = Model(solver=GurobiSolver())\n# Add variables\n@variable(m, x >= 0)\n@variable(m, y >= 0)\n# Add constraint\n@constraint(m, x + y <= 1)\n# Add objective\n@objective(m, Max, x + 2y)\n# Solve model\nsolve(m)\n# Inspect solution\n@show getobjectivevalue(m)\n@show getvalue(x)\n@show getvalue(y)\n```\n\n### Exercise\n\nCode and solve the following optimization problem:\n\n$$\n\\begin{align*}\n\\min_{x,y} \\quad& 3x - y \\\\\n\\text{s.t.}\\quad& x + 2y \\geq 1 \\\\\n& x \\geq 0 \\\\\n& 0 \\leq y \\leq 1.\n\\end{align*}\n$$\n\n\n```python\n# Create the model\nm = ConcreteModel()\n# Add the variables\nm.x = Var(within=NonNegativeReals)\nm.y = Var(bounds=(0, 1))\n# Add the constraint\nm.con = Constraint(expr=m.x + 2 * m.y >= 1)\n# Add the objective\nm.obj = Objective(sense=minimize, expr=3 * m.x - m.y)\n\nsolver = SolverFactory('gurobi')\nsolver.solve(m)\n\nprint(m.x.value, m.y.value)\n```\n\n\n```python\nfor v in m.component_data_objects(Var, active=True):\n print(v, value(v)) # doctest: +SKIP\n```\n\n\n```python\nm.pprint()\n```\n\n# Index sets\n\nLet's now move to a more complicated problem. We'll look at a transportation problem:\n\n$$\n\\begin{align}\n\\min & \\sum\\limits_{i = 1}^{m} \\sum\\limits_{j = 1}^{n} c_{ij} x_{ij}\\\\\n& \\sum\\limits_{j = 1}^{n} x_{ij} \\leq b_i && i = 1, \\ldots, m\\\\\n& \\sum\\limits_{i = 1}^{m} x_{ij} = d_j && j = 1, \\ldots, n\\\\\n& x_{ij} \\ge 0 && i = 1, \\ldots, m, j = 1, \\ldots, n\n\\end{align}\n$$\n\nAnd with some data:\n\n\n```python\nimport numpy as np\n\nm = 2 # Number of supply nodes\nn = 5 # Number of demand nodes\n# Supplies\nb = np.array([1000, 4000])\n# Demands\nd = np.array([500, 900, 1800, 200, 700])\n# Costs\nc = np.array([[2, 4, 5, 2, 1], \n [3, 1, 3, 2, 3]])\n```\n\nNow we can formulate the problem with pyomo\n\n\n```python\nmodel = ConcreteModel()\n```\n\nFirst step is adding variables. We can add variables with indices by passing the relevant index sets to the `Var` constructor. In this case, we need a $m$-by$n$ matrix of variables:\n\n\n```python\nmodel.x = Var(range(m), range(n), within=NonNegativeReals)\n```\n\nNow to add the constraints. We have to add one supply constraint for each factory, so we might try something like:\n\n\n```python\nfor i in range(m):\n model.supply = Constraint(expr=sum(model.x[i, j] for j in range(n)) <= b[i])\n```\n\nCan you see the problem? We are overwriting `model.supply` in each iteration of the loop, and so only the last constraint is applied.\n\nLuckily, pyomo has a (not-so-easy) way to add multiple constraints at a time. We first define a *rule* that takes in the model and any required indices, and then returns the expression for the constraint:\n\n\n```python\ndef supply_rule(model, i):\n return sum(model.x[i, j] for j in range(n)) <= b[i]\n```\n\nWe then add the constraint by referencing this rule along with the index set we want the constraint to be defined over:\n\n\n```python\nmodel.supply2 = Constraint(range(m), rule=supply_rule)\n```\n\nWe then apply the same approach for the demand constraints\n\n\n```python\ndef demand_rule(model, j):\n return sum(model.x[i, j] for i in range(m)) == d[j]\nmodel.demand = Constraint(range(n), rule=demand_rule)\n```\n\nFinally, we add the objective:\n\n\n```python\nmodel.obj = Objective(sense=minimize, \n expr=sum(c[i, j] * model.x[i, j] \n for i in range(m) for j in range(n)))\n```\n\nNow we can solve the problem\n\n\n```python\nsolver = SolverFactory('gurobi')\nsolver.solve(model)\n```\n\nIt solved, so we can extract the results\n\n\n```python\nflows = np.array([[model.x[i, j].value for j in range(n)] for i in range(m)])\nflows\n```\n\nWe can also check the objective value for the cost of this flow\n\n\n```python\nmodel.obj()\n```\n\nFor simplicity, here is the entire formulation and solving code together:\n\n\n```python\nmodel = ConcreteModel()\n# Variables\nmodel.x = Var(range(m), range(n), within=NonNegativeReals)\n# Supply constraint\ndef supply_rule(model, i):\n return sum(model.x[i, j] for j in range(n)) <= b[i]\nmodel.supply2 = Constraint(range(m), rule=supply_rule)\n# Demand constraint\ndef demand_rule(model, j):\n return sum(model.x[i, j] for i in range(m)) == d[j]\nmodel.demand = Constraint(range(n), rule=demand_rule)\n# Objective\nmodel.obj = Objective(sense=minimize, \n expr=sum(c[i, j] * model.x[i, j] \n for i in range(m) for j in range(n)))\n# Solve\nsolver = SolverFactory('gurobi')\nsolver.solve(model)\n# Get results\nflows = np.array([[model.x[i, j].value for j in range(n)] for i in range(m)])\nmodel.obj()\n```\n\n# Machine Learning\n\nNow let's put our pyomo knowledge to use and implement some of the same methods we saw in the machine learning class\n\nFirst, specify your solver executable location:\n\n\n```python\nexecutable='C:/Users/omars/.julia/v0.6/Ipopt/deps/usr/bin/ipopt.exe'\n```\n\nTo use the version left over from Julia\n### On MacOS and Linux\n\n`executable=\"~/.julia/v0.6/Homebrew/deps/usr/Cellar/ipopt/3.12.4_1/bin/ipopt\")`\n\n### On Windows\n\nThe path is probably under WinRPM:\n\n`executable='%HOME%/.julia/v0.6/WinRPM/...')\")`\n\n\n# Linear Regression\n\nLet's just try a simple linear regression\n\n\n```python\ndef linear_regression(X, y):\n n, p = X.shape\n\n # Create model\n m = ConcreteModel()\n\n # Add variables\n m.beta = Var(range(p))\n\n # Add constraints\n\n # Add objective\n m.obj = Objective(sense=minimize, expr=sum(\n pow(y[i] - sum(X[i, j] * m.beta[j] for j in range(p)), 2) \n for i in range(n)))\n\n solver = SolverFactory('ipopt', executable=executable)\n \n ## tee=True enables solver output\n # results = solver.solve(m, tee=True)\n results = solver.solve(m, tee=False)\n\n return [m.beta[j].value for j in range(p)]\n```\n\nLet's load up some data to test it out on:\n\n\n```python\nfrom sklearn.datasets import load_boston\ndata = load_boston()\nX = data.data\ny = data.target\n```\n\nTry our linear regression function:\n\n\n```python\nprint(linear_regression(X, y))\n```\n\nWe can compare with sklearn to make sure it's right:\n\n\n```python\nfrom sklearn.linear_model import LinearRegression\nm = LinearRegression(fit_intercept=False)\nm.fit(X, y)\nm.coef_\n```\n\nJust for reference, let's look back at how we do the same thing in JuMP!\n\n```julia\nusing JuMP, Gurobi\nfunction linear_regression(X, y)\n n, p = size(X)\n m = Model(solver=GurobiSolver())\n @variable(m, beta[1:p])\n @objective(m, Min, sum((y[i] - sum(X[i, j] * beta[j] for j = 1:p)) ^ 2 for i = 1:n))\n solve(m)\n getvalue(beta)\nend\n```\n\nor even\n\n```julia\nusing JuMP, Gurobi\nfunction linear_regression(X, y)\n n, p = size(X)\n m = Model(solver=GurobiSolver())\n @variable(m, beta[1:p])\n @objective(m, Min, sum((y - X * beta) .^ 2))\n solve(m)\n getvalue(beta)\nend\n```\n\nMuch simpler!\n\n### Exercise\n\nModify the linear regression formulation to include an intercept term, and compare to scikit-learn's LinearRegression with `fit_intercept=False` to make sure it's the same\n\n\n```python\ndef linear_regression_intercept(X, y):\n n, p = X.shape\n\n # Create model\n m = ConcreteModel()\n\n # Add variables\n m.beta = Var(range(p))\n m.b0 = Var()\n\n # Add constraints\n\n # Add objective\n m.obj = Objective(sense=minimize, expr=sum(\n pow(y[i] - sum(X[i, j] * m.beta[j] for j in range(p)) - m.b0, 2) \n for i in range(n)))\n\n solver = SolverFactory('ipopt', executable=executable)\n \n ## tee=True enables solver output\n # results = solver.solve(m, tee=True)\n results = solver.solve(m, tee=False)\n\n return [m.beta[j].value for j in range(p)]\n\nlinear_regression_intercept(X, y)\n```\n\n\n```python\nm = LinearRegression(fit_intercept=True)\nm.fit(X, y)\nm.coef_\n```\n\n# Robust Regression\n\nWe saw in the class that both ridge and lasso regression were robust versions of linear regression. Both of these are provided by `sklearn`, but we need to know how to implement them if we want to extend regression ourselves\n\n\n```python\ndef ridge_regression(X, y, rho):\n n, p = X.shape\n\n # Create model\n m = ConcreteModel()\n\n # Add variables\n m.beta = Var(range(p))\n\n # Add objective\n m.obj = Objective(sense=minimize, expr=sum(\n pow(y[i] - sum(X[i, j] * m.beta[j] for j in range(p)),2) \n for i in range(n)) + rho * sum(pow(m.beta[j], 2) for j in range(p)))\n\n solver = SolverFactory('ipopt', executable=executable)\n \n ## tee=True enables solver output\n # results = solver.solve(m, tee=True)\n results = solver.solve(m, tee=False)\n return [m.beta[j].value for j in range(p)]\n```\n\n\n```python\nridge_regression(X, y, 100000)\n```\n\n\n```python\ndef lasso(X, y, rho):\n n, p = X.shape\n\n # Create model\n m = ConcreteModel()\n\n # Add variables\n m.beta = Var(range(p))\n\n # Add objective\n m.obj = Objective(sense=minimize, expr=sum(\n pow(y[i] - sum(X[i, j] * m.beta[j] for j in range(p)),2) \n for i in range(n)) + rho * sum(pow(m.beta[j], 2) for j in range(p)))\n\n solver = SolverFactory('ipopt', executable=executable)\n \n ## tee=True enables solver output\n # results = solver.solve(m, tee=True)\n results = solver.solve(m, tee=False)\n return [m.beta[j].value for j in range(p)]\n```\n\n### Exercise\n\nImplement Lasso regression\n\n\n```python\ndef lasso_regression(X, y, rho):\n n, p = X.shape\n\n # Create model\n m = ConcreteModel()\n\n # Add variables\n m.beta = Var(range(p))\n m.absb = Var(range(p))\n\n # Add constraints\n def absbeta1(m, j):\n return m.beta[j] <= m.absb[j]\n m.absb1 = Constraint(range(p), rule=absbeta1)\n def absbeta2(m, j):\n return -m.beta[j] <= m.absb[j]\n m.absb2 = Constraint(range(p), rule=absbeta2)\n \n\n # Add objective\n m.obj = Objective(sense=minimize, expr=sum(\n pow(y[i] - sum(X[i, j] * m.beta[j] for j in range(p)), 2) \n for i in range(n)) + rho * sum(m.absb[j] for j in range(p)))\n\n solver = SolverFactory('ipopt', executable=executable)\n \n ## tee=True enables solver output\n # results = solver.solve(m, tee=True)\n results = solver.solve(m, tee=False)\n return [m.beta[j].value for j in range(p)]\n```\n\n\n```python\nlasso_regression(X, y, 1000)\n```\n\n# Sparse Regression\n\n\n```python\ndef sparse_regression(X, y, k):\n n, p = X.shape\n M = 1000\n\n # Create model\n m = ConcreteModel()\n\n # Add variables\n m.beta = Var(range(p))\n m.z = Var(range(p), within=Binary)\n\n # Add constraints\n def bigm1(m, j):\n return m.beta[j] <= M * m.z[j]\n m.bigm1 = Constraint(range(p), rule=bigm1)\n def bigm2(m, j):\n return m.beta[j] >= -M * m.z[j]\n m.bigm2 = Constraint(range(p), rule=bigm2)\n \n m.sparsity = Constraint(expr=sum(m.z[j] for j in range(p)) <= k)\n\n # Add objective\n m.obj = Objective(sense=minimize, expr=sum(\n pow(y[i] - sum(X[i, j] * m.beta[j] for j in range(p)), 2) \n for i in range(n)))\n\n solver = SolverFactory('ipopt', executable=executable)\n \n ## tee=True enables solver output\n # results = solver.solve(m, tee=True)\n results = solver.solve(m, tee=False)\n return [m.beta[j].value for j in range(p)]\n```\n\n\n```python\nsparse_regression(X, y, 10)\n```\n\n\n```python\nimport numpy as np\nl = np.array([1,2,3,4])\n\nprint(l**2)\nprint([sqrt(i) for i in l])\n```\n\n### Exercise\n\nTry implementing the algorithmic framework for linear regression:\n- sparsity constraints\n- lasso regularization\n- restrict highly correlated pairs of features\n- nonlinear transformations (just $\\sqrt(x)$ and $x^2$)\n\n\n```python\nimport numpy as np\nfrom sklearn.preprocessing import normalize\n\ndef all_regression(X_orig, y, k, rho):\n n, p_orig = X_orig.shape\n M = 10\n \n X = np.concatenate(\n [X_orig, np.sqrt(X_orig), np.square(X_orig)], axis=1\n )\n p = X.shape[1]\n \n # Normalize data\n X = normalize(X, axis=0)\n y = (y - np.mean(y)) / np.linalg.norm(y)\n\n # Create model\n m = ConcreteModel()\n\n # Add variables\n m.beta = Var(range(p))\n m.z = Var(range(p), within=Binary)\n m.absb = Var(range(p))\n\n # Sparsity constraints\n def bigm1(m, j):\n return m.beta[j] <= M * m.z[j]\n m.bigm1 = Constraint(range(p), rule=bigm1)\n def bigm2(m, j):\n return m.beta[j] >= -M * m.z[j]\n m.bigm2 = Constraint(range(p), rule=bigm2)\n m.sparsity = Constraint(expr=sum(m.z[j] for j in range(p)) <= k)\n \n # Lasso constraints\n def absbeta1(m, j):\n return m.beta[j] <= m.absb[j]\n m.absb1 = Constraint(range(p), rule=absbeta1)\n def absbeta2(m, j):\n return -m.beta[j] <= m.absb[j]\n m.absb2 = Constraint(range(p), rule=absbeta2)\n \n # Correlation constraints\n corX = np.corrcoef(np.transpose(X))\n def cor_rule(m, i, j):\n if i > j and abs(corX[i, j]) > 0.8:\n return (sum(m.z[k] for k in range(i, p, p_orig)) + \n sum(m.z[k] for k in range(j, p, p_orig)) <= 1)\n else:\n return Constraint.Skip\n m.cor = Constraint(range(p_orig), range(p_orig), rule=cor_rule)\n \n # Nonlinear constraints\n def nl_rule(m, i):\n return sum(m.z[k] for k in range(i, p, p_orig)) <= 1\n m.nl = Constraint(range(p_orig), rule=nl_rule)\n\n # Add objective\n m.obj = Objective(sense=minimize, expr=sum(\n pow(y[i] - sum(X[i, j] * m.beta[j] for j in range(p)), 2) \n for i in range(n)) + rho * sum(m.absb[j] for j in range(p)))\n\n solver = SolverFactory('ipopt', executable=executable)\n \n ## tee=True enables solver output\n# results = solver.solve(m, tee=True)\n results = solver.solve(m, tee=False)\n\n return np.array([m.beta[j].value for j in range(p)]).reshape(-1, p_orig)\n```\n\n\n```python\nall_regression(X, y, 6, 0)\n```\n\n# Logistic Regression\n\nLike JuMP, we need to use a new solver for the nonlinear problem. We can use Ipopt as before, except we have to set it up manually. You'll need to download Ipopt and add it to the PATH. \n\nOn Mac, you can do this with Homebrew if you have it:\n\nThe other way is to download a copy of ipopt and specify the path to it exactly when creating the solver. For example, I have a copy of Ipopt left over from JuMP, which I can use by modifying the SolverFactory line as indicated below:\n\n\n```python\ndef logistic_regression(X, y):\n n, p = X.shape\n \n # Convert y to (-1, +1)\n assert np.min(y) == 0\n assert np.max(y) == 1\n Y = y * 2 - 1\n assert np.min(Y) == -1\n assert np.max(Y) == 1\n\n # Create the model\n m = ConcreteModel()\n\n # Add variables\n m.b = Var(range(p))\n m.b0 = Var()\n\n # Set nonlinear objective function\n m.obj = Objective(sense=maximize, expr=-sum(\n log(1 + exp(-Y[i] * (sum(X[i, j] * m.b[j] for j in range(p)) + m.b0)))\n for i in range(n)))\n\n # Solve the model and get the optimal solutions\n solver = SolverFactory('ipopt', executable=executable)\n \n solver.solve(m)\n return [m.b[j].value for j in range(p)], m.b0.value\n```\n\nLoad up some data\n\n\n```python\nfrom sklearn.datasets import load_breast_cancer\ndata = load_breast_cancer()\nX = data.data\ny = data.target\n```\n\n\n```python\nlogistic_regression(X, y)\n```\n\n### Exercise\n\nImplement the regularized versions of logistic regression that scikit-learn provides:\n\n\n\n\n\n\n```python\ndef logistic_regression_l1(X, y, C):\n n, p = X.shape\n \n # Convert y to (-1, +1)\n assert np.min(y) == 0\n assert np.max(y) == 1\n Y = y * 2 - 1\n assert np.min(Y) == -1\n assert np.max(Y) == 1\n\n # Create the model\n m = ConcreteModel()\n\n # Add variables\n m.b = Var(range(p))\n m.b0 = Var()\n \n # Lasso constraints\n m.absb = Var(range(p))\n def absbeta1(m, j):\n return m.b[j] <= m.absb[j]\n m.absb1 = Constraint(range(p), rule=absbeta1)\n def absbeta2(m, j):\n return -m.b[j] <= m.absb[j]\n m.absb2 = Constraint(range(p), rule=absbeta2)\n \n # Set nonlinear objective function\n m.obj = Objective(sense=minimize, expr=sum(m.absb[j] for j in range(p)) + C * sum(\n log(1 + exp(-Y[i] * (sum(X[i, j] * m.b[j] for j in range(p)) + m.b0)))\n for i in range(n)))\n\n # Solve the model and get the optimal solutions\n solver = SolverFactory('ipopt', executable=executable)\n \n solver.solve(m)\n return [m.b[j].value for j in range(p)], m.b0.value\n```\n\n\n```python\nlogistic_regression_l1(X, y, 100)\n```\n\n\n```python\ndef logistic_regression_l2(X, y, C):\n n, p = X.shape\n \n # Convert y to (-1, +1)\n assert np.min(y) == 0\n assert np.max(y) == 1\n Y = y * 2 - 1\n assert np.min(Y) == -1\n assert np.max(Y) == 1\n\n # Create the model\n m = ConcreteModel()\n\n # Add variables\n m.b = Var(range(p))\n m.b0 = Var()\n \n # Set nonlinear objective function\n m.obj = Objective(sense=minimize, expr=0.5 * sum(pow(m.b[j], 2) for j in range(p)) + C * sum(\n log(1 + exp(-Y[i] * (sum(X[i, j] * m.b[j] for j in range(p)) + m.b0)))\n for i in range(n)))\n\n # Solve the model and get the optimal solutions\n solver = SolverFactory('ipopt', executable=executable)\n \n solver.solve(m)\n return [m.b[j].value for j in range(p)], m.b0.value\n```\n\n\n```python\nlogistic_regression_l2(X, y, 1000)\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "53c0c5aa6501dc8ad0b566476cc1816921d3a560", "size": 33877, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "ML3 - Optimization Modeling (Complete).ipynb", "max_stars_repo_name": "oskali/mban_softwareTools", "max_stars_repo_head_hexsha": "60b73c798a1f8447de22c46070d023de41d33a30", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-03-06T21:16:13.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-06T21:16:13.000Z", "max_issues_repo_path": "ML3 - Optimization Modeling (Complete).ipynb", "max_issues_repo_name": "oskali/mban_softwareTools", "max_issues_repo_head_hexsha": "60b73c798a1f8447de22c46070d023de41d33a30", "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": "ML3 - Optimization Modeling (Complete).ipynb", "max_forks_repo_name": "oskali/mban_softwareTools", "max_forks_repo_head_hexsha": "60b73c798a1f8447de22c46070d023de41d33a30", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2019-12-03T22:35:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-04T00:28:02.000Z", "avg_line_length": 26.1396604938, "max_line_length": 305, "alphanum_fraction": 0.5070992119, "converted": true, "num_tokens": 5687, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632896242074, "lm_q2_score": 0.9314625083949473, "lm_q1q2_score": 0.8638041359467542}} {"text": "# Finding the maximum value of 2d function\nGiven equation:\n\\begin{align}\nf(x, y) = 2xy + 2x - x^2 -2y^2\n\\end{align}\n\n### Implementation of needed functions:\n\n\n```python\n# Importing dependency functions and packages\nfrom random import random\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d.axes3d import Axes3D, get_test_data\nfrom matplotlib import cm\nimport numpy as np\n%matplotlib notebook\n\n# function\ndef f(x, y):\n return 2*x*y + 2*x - x**2 - 2*y**2\n\n# random search algorithm\ndef random_search(f, n, xl, xu, yl, yu):\n# generate lists of random x and y values\n x_cand = [xl + (xu - xl)*random() for _ in range(n)]\n y_cand = [yl + (yu - yl)*random() for _ in range(n)]\n \n# calculate appropriate to x and y values function values\n poss_max = [f(x, y) for x, y in zip(x_cand, y_cand)]\n \n# finding index of maximum value (argmax)\n max_val = max(poss_max)\n max_indexes = [i for i, j in enumerate(poss_max) if j == max_val]\n \n# return maximum value of function and its parameters x, y\n return max_val, x_cand[max_indexes[0]], y_cand[max_indexes[0]]\n\n# simple rms error function\ndef rms_error(x_ref, y_ref, x, y):\n return np.sqrt(((x_ref - x)/x_ref)**2 + ((y_ref - y)/y_ref)**2)\n```\n\nThe problem is in guessing limits of parameters (x, y) for random number generation. The smaller limits are, the bigger accuracy we will get. Let's visualize function and judge from there.\n\n\n```python\nfig = plt.figure(figsize=plt.figaspect(0.5))\nax = fig.add_subplot(1, 1, 1, projection='3d')\nx = np.arange(-100, 100, 5)\ny = np.arange(-100, 100, 5)\nx, y = np.meshgrid(x, y)\nz = f(x, y)\nsurf = ax.plot_surface(x, y, z, rstride=1, cstride=1, cmap=cm.coolwarm,\n linewidth=0, antialiased=False)\nfig.colorbar(surf, shrink=0.5, aspect=10)\nplt.show()\n```\n\n\n \n\n\n\n\n\n\nFrom above 3D plot it is seen that solution lies between -50 and 50 for both parameters x, y. \n\n\n```python\nf_ref, x_ref, y_ref = random_search(f, 10000000, -50, 50, -50, 50)\nprint('Using 10000000 random points and ranges between -50 and 50, it is found that maximum value of given function is:', f_ref)\n```\n\n Using 10000000 random points and ranges between -50 and 50, it is found that maximum value of given function is: 1.999732917847197\n\n\nThe roots found using random search method using 10 million points and considered as reference roots and as ideal. This is done in order to determine root-mean-square error somehow and find dependency of error to number of random points. Since reference roots are found using 10 million random points, it is more accurate than roots found below for error plotting reasons.\n\n\n```python\nerror_list = []\nfor n in np.logspace(1, 6, num=20):\n _, x, y = random_search(f, int(n), -50, 50, -50, 50)\n error_list += [rms_error(x_ref, y_ref, x, y)]\nplt.semilogx(np.logspace(1, 6, num=20), error_list, '-')\nplt.grid(which='both')\nplt.xlabel('Number of random points')\nplt.ylabel('RMS error of x and y roots')\nplt.show()\n```\n\n\n \n\n\n\n\n\n\nFrom error vs #of_points plot it is seen that line have linear dependency on number of random points (Exponential shape on log-scale). This confirms the fact that x and y values are generated uniformly and increased number of random points also increases accuracy linearly, distributing on 2d space equally.\n\n\n```python\n\n```\n", "meta": {"hexsha": "20fb6d4674ef559f320ced697b9910437ed9051e", "size": 340591, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "max_value.ipynb", "max_stars_repo_name": "BatyaGG/numerical_methods", "max_stars_repo_head_hexsha": "40036c07ed4db2fb03fe0d188feeb440aa260ce2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-06-23T12:19:55.000Z", "max_stars_repo_stars_event_max_datetime": "2018-06-23T12:19:55.000Z", "max_issues_repo_path": "max_value.ipynb", "max_issues_repo_name": "BatyaGG/numerical_methods", "max_issues_repo_head_hexsha": "40036c07ed4db2fb03fe0d188feeb440aa260ce2", "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": "max_value.ipynb", "max_forks_repo_name": "BatyaGG/numerical_methods", "max_forks_repo_head_hexsha": "40036c07ed4db2fb03fe0d188feeb440aa260ce2", "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": 193.8480364257, "max_line_length": 173019, "alphanum_fraction": 0.8617990493, "converted": true, "num_tokens": 958, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541561135441, "lm_q2_score": 0.9173026533686325, "lm_q1q2_score": 0.8637818559585545}} {"text": "# Ens'IA - Session 2 - Intro to neural networks 1/2\n\nWelcome the **second session** of Ens'IA.\nToday, things are gonna get interesting !\nWe are gonna focus on **neural networks**\nBut first, (what a surprise), neural networks are make of neurons ! So what is a neuron ? \n\n\nTo make sure you understand what it is, we will go back in 1958 and give a look at **the perceptron**. \n\nDuring the oral presentation, you should have seen that a perceptron have one or more inputs and a unique output. \nThe output is given by : \n\\begin{equation}\n s = \\left\\{\n \\begin{array}{ll}\n 1 & \\mbox{if } \\sum_{i=0}^{n} a_{i} \\times w_{i} + b > 0 \\\\\n 0 & \\mbox{otherwise}\n \\end{array}\n \\right.\n\\end{equation}\n\n\nNow, it's your time to *create your own perceptron*.\n\n### Perceptron implementation\n\n\n```\nclass Perceptron:\n\n \"\"\"\n Build of a perceptron\n weights : List of weights\n bias : The bias.\n \"\"\"\n def __init__(self,weights,bias):\n #TODO\n self.bias = bias\n self.weights = weights\n\n \"\"\"\n Function called when you want to get the output from the input\n input : List of input values.\n \"\"\"\n def forward(self,input):\n assert(len(input)==len(self.weights))\n #TODO\n sum = 0\n for inp,w in zip(input,self.weights):\n sum += inp*w\n if sum + self.bias > 0:\n return 1\n else:\n return 0\n```\n\n### Test\n\nNow, let's **test** it !\n\n\n```\n#TODO\nperceptron = Perceptron([1,1],-1)\nassert(perceptron.forward([1,1])==1)\nassert(perceptron.forward([1,0])==0)\nassert(perceptron.forward([0,1])==0)\nassert(perceptron.forward([0,0])==0)\n```\n\nIf you have no message, then it must work! \nHere we have created a perceptron with weights 1 and 1 and the bias is 2. \nDo you notice any link between the inputs and the output? Maybe something you have seen in your processor architecture class...\n\n\n\n\n\n### NAND implementation\n\nYour next mission will be to create a perceptron that reproduces a NAND gate. It will have 2 inputs and a bias, but you have to find which values are the right ones ...\n\n\n\n```\nperceptron_nand = Perceptron([-2,-2],3)\nassert(perceptron_nand.forward([1,1])==0)\nassert(perceptron_nand.forward([1,0])==1)\nassert(perceptron_nand.forward([0,1])==1)\nassert(perceptron_nand.forward([0,0])==1)\n#If you don't get any error messages when running this code, then you have found the right weights and bias!\n```\n\n### XOR implementation\n\nAnd if you now try to find a perceptron that reproduces an XOR gate...?\n\n\n```\n#TODO\n#Spoil : It's impossible :p\n```\n", "meta": {"hexsha": "1540e544b08f18cb27799be0eaff142d8b1f4fec", "size": 4040, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "session2/perceptron.ipynb", "max_stars_repo_name": "YannSia/tutorials", "max_stars_repo_head_hexsha": "eb9847e5ee354e57240ef3c07961674d7cd34803", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-10-03T20:49:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-19T12:46:24.000Z", "max_issues_repo_path": "session2/perceptron.ipynb", "max_issues_repo_name": "YannSia/tutorials", "max_issues_repo_head_hexsha": "eb9847e5ee354e57240ef3c07961674d7cd34803", "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": "session2/perceptron.ipynb", "max_forks_repo_name": "YannSia/tutorials", "max_forks_repo_head_hexsha": "eb9847e5ee354e57240ef3c07961674d7cd34803", "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": 4040.0, "max_line_length": 4040, "alphanum_fraction": 0.6396039604, "converted": true, "num_tokens": 705, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750387190131, "lm_q2_score": 0.9059898210180105, "lm_q1q2_score": 0.8636574817099757}} {"text": "```python\nfrom sympy import *\nfrom sympy.stats import *\nfrom sympy.utilities.lambdify import *\nimport math\n```\n\n\n```python\nx, a, b = var(\"x a b\")\nf = (x-3)/2\ni = integrate(f, (x, a, b))\ni\n```\n\n\n\n\n$\\displaystyle - \\frac{a^{2}}{4} + \\frac{3 a}{2} + \\frac{b^{2}}{4} - \\frac{3 b}{2}$\n\n\n\n\n```python\ni.subs({a: 3, b: 5}) # area da curva deve ser 1\n```\n\n\n\n\n$\\displaystyle 1$\n\n\n\n\n```python\ni.subs({a: 3.3, b: 4}) # medindo a probabilidade\n```\n\n\n\n\n$\\displaystyle 0.2275$\n\n\n\n\n```python\nmu = integrate(x*f, (x, a, b)) # media\nmu\n```\n\n\n\n\n$\\displaystyle - \\frac{a^{3}}{6} + \\frac{3 a^{2}}{4} + \\frac{b^{3}}{6} - \\frac{3 b^{2}}{4}$\n\n\n\n\n```python\nVar = integrate((x**2)*f) - mu**2 # varianca\nVar\n```\n\n\n\n\n$\\displaystyle \\frac{x^{4}}{8} - \\frac{x^{3}}{2} - \\left(- \\frac{a^{3}}{6} + \\frac{3 a^{2}}{4} + \\frac{b^{3}}{6} - \\frac{3 b^{2}}{4}\\right)^{2}$\n\n\n\n\n```python\nx = var('x')\nf = Piecewise(((1/40)*(x-4), And(Ge(x, 8), Lt(x, 10))), (3/20, And(Ge(x, 10), Le(x, 15))), (0, True))\nf\n```\n\n\n\n\n$\\displaystyle \\begin{cases} 0.025 x - 0.1 & \\text{for}\\: x \\geq 8 \\wedge x < 10 \\\\0.15 & \\text{for}\\: x \\geq 10 \\wedge x \\leq 15 \\\\0 & \\text{otherwise} \\end{cases}$\n\n\n\n\n```python\nmu = integrate(x*f, (x, a, b))\nmu.subs({ a: 8, b: 15})\n```\n\n\n\n\n$\\displaystyle 11.6416666666667$\n\n\n\n\n```python\nE2 = integrate((x**2)*f, (x, a, b))\nVar = E2 - (mu**2)\nVar.subs({ a: 8, b: 15})\n```\n\n\n\n\n$\\displaystyle 3.85493055555557$\n\n\n\n\n```python\nintegrate(f, (x, a, b)).subs({ a: 9, b: 12 })\n```\n\n\n\n\n$\\displaystyle 0.4375$\n\n\n\n\n```python\nintegrate(f, (x, a, b)).subs({ a: 8, b: 14 }) / integrate(f, (x, a, b)).subs({ a: 8, b: oo })\n```\n\n\n\n\n$\\displaystyle 0.850000000000001$\n\n\n", "meta": {"hexsha": "b5d707bc51e085588b6a1e081b6c4565171a40f1", "size": 5679, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "probabilidade_v_a_continua.ipynb", "max_stars_repo_name": "GrrriiiM/estudos-python", "max_stars_repo_head_hexsha": "b171fc8f6f29b8dcec80051ac1ce86edd34e0e57", "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": "probabilidade_v_a_continua.ipynb", "max_issues_repo_name": "GrrriiiM/estudos-python", "max_issues_repo_head_hexsha": "b171fc8f6f29b8dcec80051ac1ce86edd34e0e57", "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": "probabilidade_v_a_continua.ipynb", "max_forks_repo_name": "GrrriiiM/estudos-python", "max_forks_repo_head_hexsha": "b171fc8f6f29b8dcec80051ac1ce86edd34e0e57", "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": 21.6755725191, "max_line_length": 204, "alphanum_fraction": 0.4550096848, "converted": true, "num_tokens": 711, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.934395168021653, "lm_q2_score": 0.9241418184118163, "lm_q1q2_score": 0.8635136496907451}} {"text": "# BATEMAN’S EQUATIONS: CHAIN OF DECAYS OF 3 NUCLEAR SPECIES\n\n## Import Libraries\n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib import rcParams; rcParams[\"figure.dpi\"] = 300\nfrom matplotlib.ticker import (AutoMinorLocator)\nplt.style.use('seaborn-bright')\nplt.rc('font', family='serif')\nplt.rc('xtick', labelsize='x-small')\nplt.rc('ytick', labelsize='x-small')\n```\n\nYou will be examining properties of the Bateman equations that govern the decay of multiple nuclear species. While the problem is exactly solvable in iterative form we will consider it as a coupled system of equations, to determine the co-evolution of all species. It is well known that if there is only one nuclear species A the number of radioactive decays is proportional to the number of radioactive nuclei, $N_A$, i.e., the species evolves according to the ordinary differential equation (ODE).
\n$$\\begin{equation}\n\\tag{1}\n\\begin{split}\n\\frac{dN_A}{dt} &= -\\lambda_{A}N_A\n\\end{split}\n\\end{equation}$$
\nwhere $\\lambda_A$ is related to the half-life of the species $A_{t_{1/2},A} = ln(2/\\lambda_A)$
\nNow consider the case of a chain of two decays: one nucleus A decays into another B by one process, then B decays\ninto another C by a new process. The previous equation cannot be applied to the decay chain. Since A decays into B, and B decays into C, the activity of A adds to the total number of B nuclei. Therefore, the number of second generation nuclei B increases as a result of the decay of first generation A nuclei, and decreases as a result of its own decay into the third generation nuclei C, thus, the B species evolves as,
\n$$\\begin{equation}\n\\tag{2}\n\\begin{split}\n\\frac{dN_B}{dt} &= -\\lambda_{B}N_B + \\lambda_{A}N_A\n\\end{split}\n\\end{equation}$$
\nWe will now treat a more interesting possibility, where we have 3 radioactive species, the first generation A decays into second generation B and C. For example, $^{40}K$ has a 89.3% probability of decaying to $^{40}Ca$, and 10.7% to $^{40}Ar$. To make the problem more fun we will add the possibility that species B can, too, decay into species C. We will also consider that C decays into stable nuclei D. Based on the above considerations we have:
\n$$\\begin{equation}\n\\tag{3}\n\\begin{split}\n\\frac{dN_A}{dt} &= -\\lambda_{A}N_A \\\\\n\\frac{dN_B}{dt} &= -\\lambda_{B}N_B + \\lambda_{A,B}N_A \\\\\n\\frac{dN_C}{dt} &= -\\lambda_{C}N_C + \\lambda_{A,C}N_A + \\lambda_{B}N_B \\\\\n\\frac{dN_D}{dt} &= \\lambda_{C}N_C\n\\end{split}\n\\end{equation}$$
\nwhere $\\lambda_{A,B} + \\lambda_{A,C} = \\lambda_{A}$, and $\\lambda_{A,B}/\\lambda_{A,C}$ must equal the ratio of the probability that A will decay into B to the probability that A will decay into C.
\nThis system of equations has an integral (constant) of the motion,
\n$$\\begin{equation}\n\\tag{4}\n\\begin{split}\nN = N_A + N_B + N_C + N_D\n\\end{split}\n\\end{equation}$$
\nwhich is the total number of nuclei and is determined by the initial conditions.
\nThe system (3) has multiple timescales involved, and hence it is not possible to completely non-dimensionalize it.\nIn addition, use N to introduce normalized species numbers $\\tilde N_{i} = N_{i}/N$, i = A,B,C,D, so that the final equations in dimensionless time describe the evolution of the fraction of each species in an initial sample. This way the constant of the motion becomes,
\n$$\\begin{equation}\n\\tag{5}\n\\begin{split}\n \\tilde N_{A} + \\tilde N_{B} + \\tilde N_{C} + \\tilde N_{D} = \\tilde N = 1\n\\end{split}\n\\end{equation}$$
\nThis constant $\\tilde N$ will allow you to validate the quality of the numerical integration of Eq. (3).
\nShow in your term paper the derivation of the the normalized and dimensionless version of (3). To solve this normalized and dimensionless version of (3) you will need to specify initial conditions. Do the following:\n\n### ***QUESTIONS***\n\n**1)** Use RK4 to integrate numerically the dimensionless and normalized version the ODE (3) from t = 0 forward in time and for sufficiently large t until the populations of each species settles. You will need to be plotting $\\tilde N_{i}$ vs $t$ to see if the solution is settling and to determine when to stop the integration. Run a couple of numerical experiments with different parameters to test the dynamics of the species populations.\n\nUse your judgement as to how small a step size you need to solve this system accurately. If you cannot figure this out from pure thought, experiment with different step sizes and use $\\delta \\tilde N = |(\\tilde N(t) - \\tilde N(t=0))/\\tilde N(t=0)|$ to determine this accuracy. If $\\delta\\tilde N$ is smaller than $10^{-3}$ for all integration times, then you have a decent accuracy.\n\n**1)** Use RK4 to integrate numerically the dimensionless and normalized version the ODE (3) from t = 0 forward in time and for sufficiently large t until the populations of each species settles. You will need to be plotting $\\tilde N_{i}$ vs $t$ to see if the solution is settling and to determine when to stop the integration. Run a couple of numerical experiments with different parameters to test the dynamics of the species populations.\n\n## Tools for Numerical Integration \n\n\n```python\n# Define the RK4 Step (Taken from Class)\ndef RK4(RHS,y0,t,h,*P):\n \"\"\"\n Implements a single step of a fourth-order, explicit Runge-Kutta scheme\n \"\"\"\n thalf = t + 0.5*h\n k1 = h*RHS(y0, t, *P)\n k2 = h*RHS(y0+0.5*k1, thalf, *P)\n k3 = h*RHS(y0+0.5*k2, thalf, *P)\n k4 = h*RHS(y0+k3, t+h, *P)\n return y0 + (k1 + 2*k2 + 2*k3 + k4)/6\n\n# Define the ODESolver (Taken from Class)\ndef odeSolve(t0, y0, tmax, h, RHS, method, *P):\n \"\"\"\n ODE driver with constant step-size, allowing systems of ODE's\n \"\"\"\n # make array of times and find length of array\n t = np.arange(t0,tmax+h,h)\n ntimes, = t.shape\n # find out if we are solving a scalar ODE or a system of ODEs, and allocate space accordingly\n if type(y0) in [int, float]: # check if primitive type -- means only one eqn\n neqn = 1\n y = np.zeros(ntimes)\n else: # otherwise assume a numpy array -- a system of more than one eqn\n neqn, = y0.shape\n y = np.zeros((ntimes, neqn))\n # set first element of solution to initial conditions (possibly a vector)\n y[0] = y0\n # march on...\n for i in range(0,ntimes-1):\n y[i+1] = method(RHS,y[i],t[i],h,*P)\n return t,y\n```\n\n## RHS for the 4 Coupled Autonomous Linear ODEs\n\n\n```python\n# Define the RHS \ndef nuclear_species_RHS(y,t,*P): \n lambda_B, lambda_AB, lambda_C, lambda_AC = P ## Unpack Parameters\n NA = y[0]\n NB = y[1]\n NC = y[2]\n ND = y[3]\n dNA_dt = -NA\n dNB_dt = -lambda_B*NB + lambda_AB*NA\n dNC_dt = -lambda_C*NC + lambda_AC*NA + lambda_B*NB\n dND_dt = lambda_C*NC\n array = np.array([dNA_dt, dNB_dt, dNC_dt, dND_dt])\n return array\n```\n\n### CASE 1: Species A decays very SLOWLY \n***\nFirst, consider the case where the A species decays very slowly and test whether it is possible to run out of B and C nuclei. For this experiment you will set $\\lambda_{B}/\\lambda_{A}$ = 5, $\\lambda_{C}/\\lambda_{A}$ = 10, $\\lambda_{A,B}/\\lambda_{A}$ = 0.85 and $\\lambda_{A,C}/\\lambda_{A}$ = 0.15. Consider initial conditions $\\tilde N_{A}$ = 0.5, $\\tilde N_{B}$ = 0.25, $\\tilde N_{C}$ = 0.1, $\\tilde N_{D}$ = 0.15.
\nShow plots of your solution for $\\tilde N_{i}$ v/s t.
\n**QUESTION:** Does this evolution eliminate the species A and B completely?\n\n\n```python\n# Initial Conditions\nt0 = 0.0\ny0 = np.array([0.5, 0.25, 0.1, 0.15])\ntmax = 10\nh = 0.0001\n\n# Parameters\nlambda_B = 5.0 \nlambda_AB = 0.85\nlambda_C = 10.0 \nlambda_AC = 0.15\n\n# Solve the IVP\nt,y = odeSolve(t0, y0, tmax, h, nuclear_species_RHS, RK4, lambda_B, lambda_AB, lambda_C, lambda_AC)\n\n# dN Analysis\nNm = np.array([y[:,0],y[:,1],y[:,2],y[:,3]])\nN = Nm.sum(axis=0)\nNe = N - 1\n```\n\n\n```python\n# Plot Normalized Values v/s Dimensionless Time\nf,a = plt.subplots()\na.plot(t,y[:,0],'r', label=r'$\\tilde N_{A}$')\na.plot(t,y[:,1],'g', label=r'$\\tilde N_{B}$')\na.plot(t,y[:,2],'b', label=r'$\\tilde N_{C}$')\na.plot(t,y[:,3],'k', label=r'$\\tilde N_{D}$') \na.set_xlabel(r'Dimensionless Time ($t$)')\na.set_ylabel(r'Normalized Values ($\\tilde N_{i}$)')\na.set_title(r'$\\tilde N_{i}$ v/s $t$: Species A decays VERY SLOWLY', fontweight='bold')\na.xaxis.set_minor_locator(AutoMinorLocator()) \na.yaxis.set_minor_locator(AutoMinorLocator())\na.tick_params(which='minor', length=2.5, color='k')\na.legend()\na.grid()\nplt.tight_layout()\nplt.show()\n```\n\n\n```python\n# Plot dN v/s Dimensionless Time\nf,a = plt.subplots()\na.plot(t,Ne,'k') \na.set_xlabel(r'Dimensionless Time ($t$)')\na.set_ylabel(r'$\\delta \\tilde N$')\na.set_title(r'$\\delta \\tilde N$ v/s $t$: Species A decays VERY SLOWLY', fontweight='bold')\na.xaxis.set_minor_locator(AutoMinorLocator()) \na.yaxis.set_minor_locator(AutoMinorLocator())\na.tick_params(which='minor', length=2.5, color='k')\na.grid(linestyle=':')\nplt.tight_layout()\nplt.show()\n```\n\n### CASE 2 : Species A decays very RAPIDLY\n***\nSecond, consider the case where the A species decays very rapidly. For this experiment you will set $\\lambda_{B}/\\lambda_{A}$ = 0.05, $\\lambda_{C}/\\lambda_{A}$ = 0.1, $\\lambda_{A,B}/\\lambda_{A}$ = 0.85 and $\\lambda_{A,C}/\\lambda_{A}$ = 0.15. Consider initial conditions $\\tilde N_{A}$ = 0.5, $\\tilde N_{B}$ = 0.25, $\\tilde N_{C}$ = 0.1, $\\tilde N_{D}$ = 0.15.
\nShow plots of your solution for $\\tilde N_{i}$ v/s t.
\n**QUESTION:** How is this evolution different from the previous one?\n\n\n```python\n# Initial Conditions\nt0 = 0.0\ny0 = np.array([0.5, 0.25, 0.1, 0.15])\ntmax = 120\nh = 0.0001\n\n# Parameters\nlambda_B = 0.05 \nlambda_AB = 0.85\nlambda_C = 0.1 \nlambda_AC = 0.15\n\n# Solve the IVP\nt,y = odeSolve(t0, y0, tmax, h, nuclear_species_RHS, RK4, lambda_B, lambda_AB, lambda_C, lambda_AC)\n\n# dN Analysis\nNm = np.array([y[:,0],y[:,1],y[:,2],y[:,3]])\nN = Nm.sum(axis=0)\nNe = N - 1\n```\n\n\n```python\n# Plot Normalized Values v/s Dimensionless Time\nf,a = plt.subplots()\na.plot(t,y[:,0],'r', label=r'$\\tilde N_{A}$')\na.plot(t,y[:,1],'g', label=r'$\\tilde N_{B}$')\na.plot(t,y[:,2],'b', label=r'$\\tilde N_{C}$')\na.plot(t,y[:,3],'k', label=r'$\\tilde N_{D}$') \na.set_xlabel(r'Dimensionless Time ($t$)')\na.set_ylabel(r'Normalized Values ($\\tilde N_{i}$)')\na.set_title(r'$\\tilde N_{i}$ v/s $t$: Species A decays VERY RAPIDLY', fontweight='bold')\na.xaxis.set_minor_locator(AutoMinorLocator()) \na.yaxis.set_minor_locator(AutoMinorLocator())\na.tick_params(which='minor', length=2.5, color='k')\na.legend()\nplt.tight_layout()\nplt.show()\n```\n\n\n```python\n# Plot dN v/s Dimensionless Time\nf,a = plt.subplots()\na.plot(t,Ne,'k') \na.set_xlabel(r'Dimensionless Time ($t$)')\na.set_ylabel(r'$\\delta \\tilde N$')\na.set_title(r'$\\delta \\tilde N$ v/s $t$: Species A decays VERY RAPIDLY', fontweight='bold')\na.xaxis.set_minor_locator(AutoMinorLocator()) \na.yaxis.set_minor_locator(AutoMinorLocator())\na.tick_params(which='minor', length=2.5, color='k')\na.grid(linestyle=':')\nplt.tight_layout()\nplt.show()\n```\n\n\n```python\n### CONVERGENCE ###\n\n# Initial Conditions\nt0 = 0.0\ny0 = np.array([0.5, 0.25, 0.1, 0.15])\ntmax = 120\nh=np.array([1e2,1,0.75,0.6,0.5,0.3,0.1,0.05,0.01,0.005])\n\n# Parameters\nlambda_B = 0.05 \nlambda_AB = 0.85\nlambda_C = 0.1 \nlambda_AC = 0.15\n\n# Solve the IVP and dN Analysis\nfor i in range(len(h)):\n t,y = odeSolve(t0, y0, tmax, h[i], nuclear_species_RHS, RK4, lambda_B, lambda_AB, lambda_C, lambda_AC)\n Nm = np.array([y[:,0],y[:,1],y[:,2],y[:,3]])\n N = Nm.sum(axis=0)\n Ne = N - 1\n\nf,a = plt.subplots()\na.plot(h[0],Ne[int(3.0/h[0])],'b.')\na.plot(h[1],Ne[int(3.0/h[1])],'b.')\na.plot(h[2],Ne[int(3.0/h[2])],'b.')\na.plot(h[3],Ne[int(3.0/h[3])],'b.')\na.plot(h[4],Ne[int(3.0/h[4])],'b.')\na.plot(h[5],Ne[int(3.0/h[5])],'b.')\na.plot(h[6],Ne[int(3.0/h[6])],'b.')\na.plot(h[7],Ne[int(3.0/h[7])],'b.')\na.plot(h[8],Ne[int(3.0/h[8])],'b.')\na.plot(h[9],Ne[int(3.0/h[9])],'b.')\na.set_xlabel('h')\na.set_ylabel(r'$\\delta\\~N(\\~t=3)$')\na.set_title('Constant of Motion Error for Varying Step Sizes',fontsize=18)\na.set_xscale('log')\nplt.show()\nplt.tight_layout()\n```\n\n### CASE 3: Species B remains CONSTANT\n***\nThird, the system of equations has an \"equilibrium\" point for the B species, when $\\lambda_{B} \\tilde N_{B}/ \\lambda_{A} = \\lambda_{A,B} \\tilde N_{b}/\\lambda_{A}$, because then $\\frac{d\\tilde N_{B}}{dt} = 0$, which implies that the number of B species remain constant, and the B decay rate is balanced by the replenishment of B from the decay of A species. You can now study if this \"equilibrium\" is stable, by considering initial conditions that satisfy it. We will keep the same $\\lambda_{A,B}/\\lambda_{A}$ = 0.85 and $\\lambda_{A,C}/\\lambda_{A}$ = 0.15, and initial conditions $\\tilde N_{A}$ = 0.5, $\\tilde N_{B}$ = 0.25, $\\tilde N_{C}$ = 0.1, $\\tilde N_{D}$ = 0.15. The condition $\\lambda_{B} \\tilde N_{B}/ \\lambda_{A} = \\lambda_{A,B} \\tilde N_{b}/\\lambda_{A}$ implies $\\lambda_{B}/\\lambda_{A}$ = 1.7. And set again $\\lambda_{C}/\\lambda_{A}$ = 0.1.
\nShow plots of your solution for $\\tilde N_{i}$ v/s t.
\n**QUESTION:** Does the population of B species remain constant?\n\n\n```python\n# Initial Conditions\nt0 = 0.0\ny0 = np.array([0.5, 0.25, 0.1, 0.15])\ntmax = 60\nh = 0.0001\n\n# Parameters\nlambda_B = 1.7 \nlambda_AB = 0.85\nlambda_C = 0.1 \nlambda_AC = 0.15\n\n# Solve the IVP\nt,y = odeSolve(t0, y0, tmax, h, nuclear_species_RHS, RK4, lambda_B, lambda_AB, lambda_C, lambda_AC)\n\n# dN Analysis\nNm = np.array([y[:,0],y[:,1],y[:,2],y[:,3]])\nN = Nm.sum(axis=0)\nNe = N - 1\n```\n\n\n```python\n# Plot Normalized Values v/s Dimensionless Time\nf,a = plt.subplots()\na.plot(t,y[:,0],'r', label=r'$\\tilde N_{A}$')\na.plot(t,y[:,1],'g', label=r'$\\tilde N_{B}$')\na.plot(t,y[:,2],'b', label=r'$\\tilde N_{C}$')\na.plot(t,y[:,3],'k', label=r'$\\tilde N_{D}$') \na.set_xlabel(r'Dimensionless Time ($t$)')\na.set_ylabel(r'Normalized Values ($\\tilde N_{i}$)')\na.set_title(r'$\\tilde N_{i}$ v/s $t$: Species B remains CONSTANT', fontweight='bold')\na.xaxis.set_minor_locator(AutoMinorLocator()) \na.yaxis.set_minor_locator(AutoMinorLocator())\na.tick_params(which='minor', length=2.5, color='k')\na.legend()\nplt.tight_layout()\nplt.show()\n```\n\n\n```python\n# Plot dN v/s Dimensionless Time\nf,a = plt.subplots()\na.plot(t,Ne,'k') \na.set_xlabel(r'Dimensionless Time ($t$)')\na.set_ylabel(r'$\\delta \\tilde N$')\na.set_title(r'$\\delta \\tilde N$ v/s $t$: Species B remains CONSTANT', fontweight='bold')\na.xaxis.set_minor_locator(AutoMinorLocator()) \na.yaxis.set_minor_locator(AutoMinorLocator())\na.tick_params(which='minor', length=2.5, color='k')\na.grid(linestyle=':')\nplt.tight_layout()\nplt.show()\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "0e45f633863d101ee3dfe2e288dedfbe01910719", "size": 972502, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Term Project/bateman_eqs.ipynb", "max_stars_repo_name": "astroarshn2000/PHYS305S20", "max_stars_repo_head_hexsha": "18f4ebf0a51ba62fba34672cf76bd119d1db6f1e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-09-10T06:45:46.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-20T13:50:11.000Z", "max_issues_repo_path": "Term Project/bateman_eqs.ipynb", "max_issues_repo_name": "astroarshn2000/PHYS305S20", "max_issues_repo_head_hexsha": "18f4ebf0a51ba62fba34672cf76bd119d1db6f1e", "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": "Term Project/bateman_eqs.ipynb", "max_forks_repo_name": "astroarshn2000/PHYS305S20", "max_forks_repo_head_hexsha": "18f4ebf0a51ba62fba34672cf76bd119d1db6f1e", "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": 1607.441322314, "max_line_length": 168788, "alphanum_fraction": 0.9560874939, "converted": true, "num_tokens": 4793, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096044278532, "lm_q2_score": 0.9425067211996142, "lm_q1q2_score": 0.8634394595287714}} {"text": "

GRADIENT DESCENT

\n\nGradient descent is an optimization algorithm used to minimize some function by iteratively moving in the direction of steepest descent as defined by the negative of the gradient. In machine learning, we use gradient descent to update the parameters of our model. Parameters refer to coefficients in Linear Regression and weights in neural networks. (Source. Khan Academy). Gradient descent is best used when the parameters cannot be calculated analytically (e.g. using linear algebra) and must be searched for by an optimization algorithm. \n\n\n\n\n\n# Task\n\nThis is the first an only project not related to the coffee data base. In this project, the idea is to implement the Gradient descent algorithm from scratch without using the code used in class. The algorithm is tested for a one-dimensional and two dimensional functions differentiable in a specific numerical range. \n\n\n\n# One dimensional function\n\nThe function $ x^3-3x^2 + 5 $ is tested. This function is well behaved, with a minimum each time x = y. Furthermore, it has not got many different local minimum which can be problematic for gradient descent algorithm.\n\n\n```python\nfrom numpy import asarray\nfrom numpy import arange\nfrom numpy.random import rand\nimport matplotlib.pyplot as plt\n\n```\n\n\n```python\ndef objective(x):\n return x**3 - 3*x**2 + 5\n \n# derivative of objective function\ndef derivative(x):\n return 3*x**2 - 6*x\n \n# gradient descent algorithm\n#def gradient_descent(objective, derivative, bounds, n_iter, step_size, initial_point, precision):\ndef gradient_descent(objective, derivative, step_size, initial_point, precision):\n # track all solutions\n solutions, scores = list(), list()\n gradient_new = initial_point\n gradient_old = 0\n counter=0\n\n while (gradient_new- gradient_old) > precision:\n counter=counter+1\n gradient_old= gradient_new\n gradient_new = gradient_old - (step_size * derivative(gradient_old))\n # evaluate candidate point\n solution_eval = objective(gradient_new)\n # store solution\n solutions.append(gradient_new)\n scores.append(solution_eval)\n # report progress\n # print('Interaction %d f(%s) = %.5f' % (counter, round (gradient_new, 5), solution_eval))\n return solutions, scores, counter\n```\n\n### Implementing the gradient descent in the 2-d function\n\n\n```python\n# define range for input\nbounds = asarray([[-1.0, 3.0]])\n# define the total iterations\n#n_iter = 15\n# define the step size\nstep_size = 0.3\ninitial_point= 0.01\nprecision= 0.0001\n# perform the gradient descent search\nsolutions, scores, counter = gradient_descent(objective, derivative, step_size, initial_point, precision)\n# sample input range uniformly at 0.1 increments\ninputs = arange(bounds[0,0], bounds[0,1]+0.1, 0.1)\n# compute targets\nresults = objective(inputs)\nplt.figure(figsize=[10,5])\n# create a line plot of input vs result\nplt.plot(inputs, results)\n# plot the solutions found\nplt.plot(solutions, scores, '.-', color='red')\nplt.xlabel(\"w (weight)\", fontsize = 15)\nplt.ylabel(\"f(w)\", fontsize = 15)\nplt.title(\"Gradient descent\", fontsize = 18)\nplt.show()\n# show the plot\n```\n\n### Step size sensitivity analysis\nThe efect of the step size for this particular function is analized as follow. We get the number of iteration for an step size from 0.1 to 0.8, with 0.01 increments. The inital point and precision is fixed. The result is presented in the following plot.\n\n\n```python\nstep_size = np.arange(0.1, 0.8, 0.01)\ninitial_point= 0.01\nprecision= 0.0001\nresult = []\nfor i in (step_size):\n# Gdetting the number of iteraction for each step\n solutions, scores, counter = gradient_descent(objective, derivative, i, initial_point, precision)\n result.append(counter)\nplt.figure(figsize=[10,5])\nplt.plot(step_size, result)\nplt.xlabel(\"Increasing step\", fontsize = 15)\nplt.ylabel(\"Number of iterations\", fontsize = 15)\nplt.title(\"STEP SIZE ANALYSIS\", fontsize = 18)\nplt.show()\n\n```\n\n# Two dimensional Function\nThe function z= $x^2 + y^2 - 2xy$ is tested. This function is well behaved, with a minimum each time x = y. Furthermore, it has not got many different local minimums, which can be problematic for the gradient descent algorithm. I drew the 3D and contour plot for this function and subsequently calculated the gradient descent and the number of required interactions to satisfy a precision value. \n\n\n```python\nfrom numpy import exp,arange\nfrom pylab import meshgrid,cm,imshow,contour,clabel,colorbar,axis,title,show\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom matplotlib import cm\nfrom matplotlib.ticker import LinearLocator, FormatStrFormatter\n\n\n# the function I'm plotting\ndef z_func(x,y):\n return x**2 + y**2 - 2*x*y\n \nx = arange(-3.0,3.0,0.1)\ny = arange(-3.0,3.0,0.1)\n\n# grid of point\nX,Y = meshgrid(x, y) \n# evaluation of the function on the grid\nZ = z_func(X, Y) \n\nfig = plt.figure(figsize=[12,10])\nax = fig.gca(projection='3d')\nsurf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, \n cmap=cm.RdBu,linewidth=0, antialiased=False)\n\nax.zaxis.set_major_locator(LinearLocator(8))\nax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))\nfig.colorbar(surf, shrink=0.5, aspect=5)\nplt.title('3D PLOT $x^2+y^2-2xy$', fontsize = 18)\nax.set_xlabel('x')\nax.set_ylabel('y')\nax.set_zlabel('z')\nplt.show()\n\n\n```\n\n### Finding the result of interactions in the 3D function\n\n\n```python\nfrom sympy import *\n\nx = Symbol('x')\ny = Symbol('y')\nz = Symbol('z')\n\nf = x**2 + y**2 - 2*x*y\n# First partial derivative with respect to x\nfpx = f.diff(x)\n\n# First partial derivative with respect to y\nfpy = f.diff(y)\n\n# Gradient\ngrad = [fpx,fpy]\n\n# Data\ntheta = 10 #initial point x\ntheta1 = 3 #initial point y\nstep_size = 0.1 \ncount = 0\nprecision = 0.00001\nprintData = True\nmaxIterations = 1000\n\nwhile True:\n temptheta = theta - step_size*N(fpx.subs(x,theta).subs(y,theta1)).evalf()\n temptheta1 = theta1 - step_size*N(fpy.subs(y,theta1)).subs(x,theta).evalf()\n\n #If the number of iterations goes up too much, maybe theta is diverging. Stop, the function may not be convex\n count += 1\n if count > maxIterations:\n print(\"Adjust the step size and make sure that the function is convex\")\n printData = False\n break\n\n # Verify the differece between the current value and presvious value is less than the precision, if yes, finish\n if abs(temptheta-theta) < precision and abs(temptheta1-theta1) < precision:\n break\n\n # Update\n theta = temptheta\n theta1 = temptheta1\n\nif printData:\n print(\"The function \"+str(f)+\" converges to a minimum\")\n print(\"Number of iterations:\",count,sep=\" \")\n print(\"Theta (x0) =\",temptheta,sep=\" \")\n print(\"Theta1 (y0) =\",temptheta1,sep=\" \")\n \n \n\n```\n\n The function x**2 - 2*x*y + y**2 converges to a minimum\n Number of iterations: 25\n Theta (x0) = 6.50000995060081\n Theta1 (y0) = 6.49999004939919\n\n\n### Result\nThe gradient descent finds a minimun starting at points 10 and 3, after 25 interactions, using a step size of 0.1. The minimal occurs in the point (6.5, 6.5) which can be verfiy in the 3D plot as well. \n\n", "meta": {"hexsha": "099aeb04cc5e5c245135b67567e045242768bf5f", "size": 272927, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Initial_analysis/Gradient Descent.ipynb", "max_stars_repo_name": "carlosandrade25/TEST-2", "max_stars_repo_head_hexsha": "8b8978c31eee5262a1f29bfde61a4298d14ef643", "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": "Initial_analysis/Gradient Descent.ipynb", "max_issues_repo_name": "carlosandrade25/TEST-2", "max_issues_repo_head_hexsha": "8b8978c31eee5262a1f29bfde61a4298d14ef643", "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": "Initial_analysis/Gradient Descent.ipynb", "max_forks_repo_name": "carlosandrade25/TEST-2", "max_forks_repo_head_hexsha": "8b8978c31eee5262a1f29bfde61a4298d14ef643", "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": 753.9419889503, "max_line_length": 109004, "alphanum_fraction": 0.9514925236, "converted": true, "num_tokens": 1907, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850075259038, "lm_q2_score": 0.9219218391455084, "lm_q1q2_score": 0.8631815961026474}} {"text": "The goal of this notebok is to check the veracity of the following important information you may have seen on social networks\n\n\n\nWe will reproduce the previous equation, step by step as:\n$$\n\\frac{\\pi e^{\\frac{A}{B}} - e^{i E}}{C D}\n$$\n\n\n```python\nfrom sympy import *\ninit_printing(use_latex=True) \nt = Symbol('t')\nk = Symbol('k')\nn = Symbol('n')\n```\n\n\n```python\nA=Limit(2**(2*n) * factorial(n)**2 * log(7) / factorial(2*n) / sqrt(n), n, +oo)\nA\n```\n\n\n```python\nA.doit()\n```\n\n\n```python\nB=Integral(exp(-t**2), (t,0,+oo))\nB\n```\n\n\n```python\nB.doit()\n```\n\n\n```python\nC = Integral(3 / (t**6 + 1), (t,0,+oo))\nC\n\n```\n\n\n```python\nC.doit()\n```\n\n\n```python\nD = Integral(exp(-pi*t**2), (t,-oo,+oo))\nD\n```\n\n\n```python\nD.doit()\n\n```\n\n\n```python\nE=Sum( 8*pi/(4*k+1)/(4*k+3), (k,0,+oo))\nE\n\n```\n\n\n```python\nE.doit().simplify()\n```\n\n# Conclusion\n\n\n```python\ntotal=( pi*exp(A.doit()/B.doit()) - exp(I*(E).doit().simplify()) )/ C.doit() / D.doit()\ntotal.simplify()\n```\n\nWhich leads me to the conclusion the expression is false ! In fact, it seems that the sum expression shoud not have a $\\pi$ in it, and that the both exponentials should be factorized by $\\pi$. \n\nThe original web page with the mistake is http://www.brouty.fr/Maths/anniv.html.\n\n\n```python\ntotal2=( pi*(exp(A.doit()/B.doit()) - exp(I*(E/pi).doit().simplify()) )) / C.doit() / D.doit()\ntotal2\n```\n", "meta": {"hexsha": "2c15e922c552679229ba09c7b7202dad1cddebdf", "size": 19807, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/Checking Equations With SimPy.ipynb", "max_stars_repo_name": "Hash--/documents", "max_stars_repo_head_hexsha": "86a2ba249a3a478cba9bdcd511d02c4f4302d6fc", "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/Checking Equations With SimPy.ipynb", "max_issues_repo_name": "Hash--/documents", "max_issues_repo_head_hexsha": "86a2ba249a3a478cba9bdcd511d02c4f4302d6fc", "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/Checking Equations With SimPy.ipynb", "max_forks_repo_name": "Hash--/documents", "max_forks_repo_head_hexsha": "86a2ba249a3a478cba9bdcd511d02c4f4302d6fc", "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.7436489607, "max_line_length": 2498, "alphanum_fraction": 0.7159085172, "converted": true, "num_tokens": 460, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741241296943, "lm_q2_score": 0.9059898222871762, "lm_q1q2_score": 0.8630224614356242}} {"text": "# Elliptic PDE: Radially Symmetric Singular Solution\nCopyright (C) 2010-2020 Luke Olson
\nCopyright (C) 2020 Andreas Kloeckner\n\n
\nMIT License\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n
\n\n-----\n\nPoisson Problem:\n
Given open domain $\\Omega \\subset \\mathbb{R}^2$
\n$$ -\\nabla \\cdot \\nabla u = f(x)\\quad \\text{in}\\, \\Omega $$\n$$ u = g(x)\\quad \\text{on}\\, \\partial\\Omega $$\nLet:\n$$ f(x) = \\delta(x) $$ \n$\\delta(x)$ is the Dirac delta function. This problem describes a unit charge at the origin.\n\n## Solution\n\nPotential due to point charge:\n$$ u(x,y) = -\\frac{1}{2\\pi}\\ln(r) $$\n\n
$r = \\sqrt{x^2+y^2}$, the distance to the origin.
\n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom matplotlib import cm\nimport math\n\nimport sympy as sym\nsym.init_printing()\n```\n\n## Set up Grid\n\n\n```python\nX = np.arange(-10, 10, 0.2)\nY = np.arange(-10, 10, 0.2)\nX, Y = np.meshgrid(X, Y)\n```\n\n## Solution\n\n\n```python\nr = np.sqrt(X**2 + Y**2)\nZ = -np.log(r)/(2*math.pi)\n```\n\n## Check Symbolically\n\n\n```python\nsx = sym.Symbol(\"x\")\nsy = sym.Symbol(\"y\")\nsr = sym.sqrt(sx**2 + sy**2)\nssol = sym.log(sr)\n\nsym.simplify(sym.diff(ssol, sx, 2) + sym.diff(ssol, sy, 2))\n```\n\n## Plot\n\n\n```python\nfig = plt.figure(figsize=(8, 6))\nax = fig.add_subplot(111, projection='3d')\n#ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.coolwarm,\n# linewidth=0, antialiased=False)\nax.plot_wireframe(X, Y, Z, linewidth=0.2)\n#ax.set_zlim(-1.0, 1.0)\n#plt.show()\n\n```\n\nGiven $C\\log(r)$ as the *free-space Green's function*, can we construct the solution to the PDE with a more general $f$?\n", "meta": {"hexsha": "70d52663d735febfc2925b7a6513bd6f39d63d6b", "size": 116711, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "demos/intro/Elliptic PDE Radially Symmetric Singular Solution.ipynb", "max_stars_repo_name": "inducer/numpde-notes", "max_stars_repo_head_hexsha": "80952b692fc16f185042a64d91312b0e53fafe17", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2020-05-31T23:00:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-25T15:08:14.000Z", "max_issues_repo_path": "demos/intro/Elliptic PDE Radially Symmetric Singular Solution.ipynb", "max_issues_repo_name": "inducer/numpde-notes", "max_issues_repo_head_hexsha": "80952b692fc16f185042a64d91312b0e53fafe17", "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": "demos/intro/Elliptic PDE Radially Symmetric Singular Solution.ipynb", "max_forks_repo_name": "inducer/numpde-notes", "max_forks_repo_head_hexsha": "80952b692fc16f185042a64d91312b0e53fafe17", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2020-08-14T22:49:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-25T15:08:34.000Z", "avg_line_length": 525.7252252252, "max_line_length": 110804, "alphanum_fraction": 0.9464146481, "converted": true, "num_tokens": 758, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312213841788, "lm_q2_score": 0.9511422265713299, "lm_q1q2_score": 0.8629829592688407}} {"text": "```python\nfrom sympy import *\nfrom sympy.solvers.solveset import solveset\ninit_printing()\nx, y, z = symbols('x,y,z')\n```\n\n## Solveset\n\nLa resolución de ecuaciones es una necesidad común y también un elemento común para algoritmos simbólicos más complicados.\n\nAquí presentamos la función `solveset`.\n\n\n```python\nsolveset(x**2 - 4, x)\n```\n\n*Solveset* toma dos argumentos y un argumento opcional que especifica el dominio, una ecuación como $x^2 - 4$ y una variable sobre la cual queremos resolver, como $x$ y un argumento opcional *domain* que especifica la región en la que queremos resolver .\n\n*Solveset* devuelve los valores de la variable, $x$, para los cuales la ecuación, $x^2 - 4$ es igual a 0.\n\n### Ejercicio\n\n¿Qué produciría el siguiente código? ¿Estás seguro?\n\n\n```python\nsolveset(x**2 - 9 == 0, x)\n```\n\n## Soluciones infinitas\n\nUna de las principales mejoras de `solveset` es que también admite una solución infinita.\n\n\n```python\nsolveset(sin(x), x)\n```\n\n## Argumento *domain*\n\n\n```python\nsolveset(exp(x) -1, x)\n```\n\n`solveset` por defecto resuelve todo en el dominio complejo. En el dominio complejo $\\exp(x) = \\cos(x) + i\\sin(x)$ y la solución es básicamente igual a la solución de $\\cos(x) = 1$. Si solo desea una solución real, puede especificar el dominio como `S.Reals`.\n\n\n```python\nsolveset(exp(x) -1, x, domain=S.Reals)\n```\n\n`solveset` no siempre es capaz de resolver una ecuación dada, en tales casos devuelve un objeto` ConditionSet`. `ConditionSet` representa un conjunto que satisface una condición dada.\n\n\n```python\nsolveset(exp(x) + cos(x) + 1, x, domain=S.Reals)\n```\n\n`solveset` tiene como objetivo devolver todas las soluciones de la ecuación. En los casos en que puede encontrar alguna solución pero no todas, devuelve una unión de las soluciones conocidas y `ConditionSet`.\n\n\n```python\nsolveset((x - 1)*(exp(x) + cos(x) + 1), x, domain=S.Reals)\n```\n\n## Uso simbólico de `solveset`\n\nLos resultados de `solveset` no necesitan ser numéricos, como `{-2, 2}`. Podemos usar solveset para realizar manipulaciones algebraicas. Por ejemplo, si conocemos una ecuación simple para el área de un rectángulo\n\n area = largo * ancho\n\npodemos resolver esta ecuación para cualquiera de las variables. Por ejemplo, ¿cómo resolveríamos este sistema para `largo`, dado `area` y `ancho`?\n\n\n```python\nlargo, ancho, area = symbols('largo, ancho, area')\nsolveset(area - largo*ancho, largo)\n```\n\nTen en cuenta que nos hubiera gustado escribir\n\n solveset(area == largo * ancho, largo)\n\nPero el *gotcha* `==` nos muerde. En cambio, recordamos que `solveset` espera una expresión que sea igual a cero, por lo que reescribimos la ecuación\n\n area = largo * ancho\n\nen la ecuación\n\n 0 = largo * ancho - area\n\ny eso es lo que le damos a `solveset`.\n\n### Ejercicio\n\nCalcula el radio de una esfera, dado el volumen. Recuerde, el volumen de una esfera de radio `r` está dado por\n\n$$ V = \\frac{4}{3}\\pi r^3 $$\n\n\n```python\n# Resuelve para el radio de una esfera, dado el volumen\n```\n\nProbablemente obtendrás varias soluciones, eso está bien. La primera es probablemente la que quieres.\n\n## Sustitución\n\nA menudo queremos sustituir en una expresión por otra. Para esto, usamos el método de `subs`\n\n\n```python\nx**2\n```\n\n\n```python\n# Sustituye x por y\n(x**2).subs({x: y})\n```\n\n### Ejercicio\n\nSustituye $x$ por $\\sin(x)$ en la ecuación $x^2 + 2\\cdot x + 1$\n\n\n```python\n# Sustituye x por sin(x)\n\n\n```\n\n## Subs + Solveset\n\nPodemos usar `subs` y `solveset` juntos para conectar la solución de una ecuación a otra\n\n\n```python\n# Resuelve para el largo de un rectangulo dada el area y el ancho\n\nsoln = list(solveset(area - largo*ancho, largo))[0]\nsoln\n```\n\n\n```python\n# Define el perimetro de un rectangulo en terminos del largo y ancho \n\nperimetro = 2*(largo + ancho)\n```\n\n\n```python\n# Sustituye la solucion para el largo en la expresion para el perimetro\n\nperimetro.subs({largo: soln})\n```\n\n### Ejercicio\n\nEn la última sección resolviste para el radio de una esfera dado su volumen\n\n\n```python\nV, r = symbols('V,r', positive=True)\n4*pi/3 * r**3\n```\n\n\n```python\nlist(solveset(V - 4*pi/3 * r**3, r))[0]\n```\n\nAhora vamos a calcular el área de una esfera en términos del volumen. Recuerde que el área de una esfera está dada por\n\n$$ 4 \\pi r^2 $$\n\n\n```python\n(?).subs(?)\n```\n\n¿La expresión se ve bien? ¿Cómo esperas que el área escale con respecto al volumen? ¿Cuál es el exponente en $V$?\n\n## Trazado de gráficas\n\n*Sympy* puede graficar expresiones fácilmente usando la función `plot`. Para esto, la biblioteca por defecto es *matplotlib*.\n\n\n```python\nimport matplotlib.pyplot as plt\n```\n\n\n```python\nplot(x**2)\n```\n\n### Ejercicio\n\nEn el último ejercicio, obtuviste una relación entre el volumen de una esfera y su área. Grafica esta relación usando `plot`.\n\n\n```python\nplot(?)\n```\n\n## Mínimas dependencias\n\n*SymPy* intenta ser un proyecto con pocas dependencia. Nuestra base de usuarios es muy amplia. Algunos aspectos entretenidos resultan. Por ejemplo, `textplot`.\n\n\n```python\ntextplot(x**2, -3, 3)\n```\n\n### Ejercicio\n\nJuega con `textplot` y disfruta :)\n", "meta": {"hexsha": "2ac37e5fd3c3fad4ef18fbc0e4ad54f87b54288e", "size": 10706, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "tutorial_exercises/02-Solveset-Subs-Plot.ipynb", "max_stars_repo_name": "t3rodrig/sympy-tutorial-es", "max_stars_repo_head_hexsha": "5cd5497f799e889d758a26539781cdc72b1e6a74", "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": "tutorial_exercises/02-Solveset-Subs-Plot.ipynb", "max_issues_repo_name": "t3rodrig/sympy-tutorial-es", "max_issues_repo_head_hexsha": "5cd5497f799e889d758a26539781cdc72b1e6a74", "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": "tutorial_exercises/02-Solveset-Subs-Plot.ipynb", "max_forks_repo_name": "t3rodrig/sympy-tutorial-es", "max_forks_repo_head_hexsha": "5cd5497f799e889d758a26539781cdc72b1e6a74", "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": 22.8760683761, "max_line_length": 269, "alphanum_fraction": 0.5469830002, "converted": true, "num_tokens": 1570, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107861416413, "lm_q2_score": 0.9207896769778074, "lm_q1q2_score": 0.8629740170314789}} {"text": "# Logistic Regression Single Neuron\n\nIn this notebook, we briefly introduce the logistic regression single neuron model, then apply it on the CVDs dataset.\n\n---\n\n## Introduce\n\n[Logistic regression](https://en.wikipedia.org/wiki/Logistic_regression) is a statistical model that in its basic form uses a logistic function to model a binary dependent variable. In regression analysis, logistic regression is estimating the parameters of a logistic model.\n\nLogistic regression is used in various fields, including machine learning, most medical fields, and social sciences.\n\n---\n\n## Algorithm\n\nInstead of creating a single neuron model for predicting a class deterministic label, we will next build a single neuron model that predicts a *class probability*.\n\n### Sigmoid activation function\n\nAs before, we must first decide on an activation function before deciding on a cost/ loss function. For this purpose, we choose the *sigmoid* activation function:\n\n$$\n\\sigma(z) = \\frac{1}{1 + e^{-z}}\n$$\n\nThis differentiable function has a range in $(0, 1)$, so it would seem suitable for a possible function to turn the pre-activation value into a value representing a probability. Moreover, the sigmoid function (sometimes called the *logistic function*) has a smooth \"S\"-shape that is perfect for probabilities values transitioning, either growing or shrinking, as the input feature changes.\n\n## Cross Entropy loss function\n\nSuppose that we have two target values, 0 and 1. Now we are wishing to predict that *probability of each of these labels given a single feature measurement*. Thus, we encounter the conditional probability function:\n\n$$\nP\\Big(y^{(i)}\\mid x^{(i)}\\Big)=\\begin{cases}\n \\hat{y}^{(i)}, \\quad & y^{(i)} = 1 \\\\\n 1-\\hat{y}^{(i)}, \\quad & y^{(i)} = 0 \\\\\n \\end{cases}\n$$\n\nNotice that this conditional probability depends on the value of $\\hat{y}^{(i)}$, which in-turn depends on the values of our weight and bias. Moreover, we wish to *maximize* this probability over all training examples since this quantity is largest when our predicted probabilities are close approximations to the true 0-1 labels. Thus, we seek to solve the following maximization problem:\n\n$$\n\\max_{\\mathbf{w}, b} \\sum_{i=1}^{N}P\\Big(y^{(i)}\\mid x^{(i)}\\Big).\n$$\n\nBefore considering this optimization problem, we next recall the famous Bernoulli formula for binary probabilities:\n$$\nP\\Big(y^{(i)}\\mid x^{(i)}\\Big) = [\\hat{y}^{(i)}]^{y}[1 - \\hat{y}^{(i)}]^{(1-y)}\n$$\n\nTaking the logorithm on both sides of this equation yields (dropping the index notation to avoid messy equations):\n$$\n\\begin{align} \n\\log P\\Big(y^{(i)}\\mid x^{(i)}\\Big)&= \\log \\hat{y}^{y}(1 - \\hat{y})^{(1-y)}\\\\ \n&= y\\log \\hat{y} + (1-y) \\log (1 - \\hat{y})\\\\ \n\\end{align}\n$$\n\nSince the logorithmic function is an *increasing function*, maximimizing $P\\Big(y^{(i)}\\mid x^{(i)}\\Big)$ is equivalent to maximizing $\\log P\\Big(y^{(i)}\\mid x^{(i)}\\Big)$. Equivalently, we could also considering minimizing this function. Thus, we arrive at our single neuron coss/loss function for a single entry of data, which implies a full loss function. \n\n### Binary Cross Entropy Loss Function:\n$$\nL(\\mathbf{w}, b) = -\\frac{1}{N} \\sum_{i=1}^{N} \\log P\\Big(y^{(i)}\\mid x^{(i)}\\Big) = \\frac{1}{N}\\sum_{i=1}^{N}\\Big[ -y^{(i)}\\log \\hat{y}^{(i)} - (1-y^{(i)}) \\log (1 - \\hat{y}^{(i)})\\Big ]\n$$\n\n### Calculuting the Gradient of Binary Cross Entropy Loss Function\nIn order to optimize the logistic regression single neuron model with stochastic gradient descent, we first need understand how to calculate the gradient. As before, we will consider the cost function on a single instance of data:\n\n$$\nC(w_1, b; x^{(i)},y^{(i)}) = -y^{(i)}\\log \\hat{y}^{(i)} - (1-y^{(i)}) \\log (1 - \\hat{y}^{(i)})\n$$\n\nWhen considering this equation it is important to remember that $\\hat{y}^{(i)}$ really is a composite function. More specifically, we note\n\n$$\n\\hat{y}^{(i)} = \\sigma(z) = \\sigma(w_1x^{(i)} + b).\n$$\n\nNext we note the particularly nice closed form of the derivative of the sigmoid function.\n\n$$\n\\sigma'(z) = \\sigma(z)(1 - \\sigma(z))\n$$\n\nWith these two equations, we are now ready to compute the partial derivatives of $C(w_1, b; x_{1}^{(i)},y^{(i)})$ with respect to $w_1$ and $b$. Note that this cost function contains two pieces, namely $-y^{(i)}\\log \\hat{y}^{(i)}$ and $- (1-y^{(i)}) \\log (1 - \\hat{y}^{(i)})$. Since the derivative is a linear map, we may calculate $\\partial C/ \\partial w_1$ by calculating the the derivative of each piece of this equation and then add them together. \n\n$$\n\\begin{split}\n\\frac{\\partial}{\\partial w_1}[-y^{(i)}\\log \\hat{y}^{(i)}] & = \\frac{\\partial}{\\partial w_1}[-y^{(i)}\\log \\sigma(w_1 x^{(i)}+b)] \\\\\n & = - \\frac{y^{(i)}}{\\sigma(w_1 x^{(i)}+b)}\\frac{\\partial}{\\partial w_1} [\\sigma(w_1 x^{(i)}+b)] \\\\\n & = - \\frac{y^{(i)}}{\\sigma(w_1 x^{(i)}+b)}\\sigma(w_1 x^{(i)}+b)(1 - \\sigma(w_1 x^{(i)}+b))\\frac{\\partial}{\\partial w_1}[w_1 x^{(i)}+b] \\\\\n & = - y^{(i)}(1 - \\sigma(w_1 x^{(i)}+b))x^{(i)} \\\\\n & = - y^{(i)}(1 - \\hat{y}^{(i)})x^{(i)} \n\\end{split}\n$$\n\n$$\n\\begin{split}\n\\frac{\\partial}{\\partial w_1}[-(1-y^{(i)}) \\log (1 - \\hat{y}^{(i)})] & = \\frac{\\partial}{\\partial w_1}[-(1-y^{(i)})\\log (1 - \\sigma(w_1 x^{(i)}+b))] \\\\\n & = - \\frac{(1 - y^{(i)})}{(1 - \\sigma(w_1 x^{(i)}+b))}\\frac{\\partial}{\\partial w_1} [1 - \\sigma(w_1 x^{(i)}+b) ]\\\\\n & = - \\frac{(1 - y^{(i)})}{(1 - \\sigma(w_1 x^{(i)}+b))} -\\sigma(w_1 x^{(i)}+b)(1 - \\sigma(w_1 x^{(i)}+b))\\frac{\\partial}{\\partial w_1}[w_1 x^{(i)}+b] \\\\\n & = (1 - y^{(i)})\\sigma(w_1 x^{(i)}+b))x^{(i)} \\\\\n & = (1 - y^{(i)})\\hat{y}^{(i)}x^{(i)} \n\\end{split}\n$$\n\nNow that we have calculated the derivative with respect to $w_1$ for each part of the binary cross entropy loss function, we next sum these derivatives:\n\n$$\n\\begin{split}\n\\frac{\\partial C(w_1, b; x^{(i)},y^{(i)})}{\\partial w_1} & = - y^{(i)}(1 - \\hat{y}^{(i)})x^{(i)} + (1 - y^{(i)})\\hat{y}^{(i)}x^{(i)} \\\\\n & = [- y^{(i)}(1 - \\hat{y}^{(i)}) + (1 - y^{(i)})\\hat{y}^{(i)}]x^{(i)} \\\\\n & = [- y^{(i)} + y^{(i)}\\hat{y}^{(i)} + \\hat{y}^{(i)} - y^{(i)}\\hat{y}^{(i)}]x^{(i)} \\\\\n & = (\\hat{y}^{(i)} - y^{(i)}) x^{(i)}\n\n\\end{split}\n$$\n\nA similar calculation also yields the partial derivative of our cost function with respect to the bias $b$:\n\n$$\n\\frac{\\partial C(w_1, b; x^{(i)},y^{(i)})}{\\partial b} = (\\hat{y}^{(i)} - y^{(i)})\n$$\n\n---\n\n## Coding\n\nWe will import the ```SingleNeuron``` Class from [Modules](https://github.com/YulinLi98/Sample_Repo/blob/main/Supervised_Learning/Modules) and define the sigmoid activation function and cross entropy loss function.\n\n\n```python\n# Import the libraries\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nfrom sklearn import preprocessing\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import classification_report\n\n# Set theme for plotting\nsns.set_theme()\n\nimport sys \nsys.path.append('..')\n\n# Import SingleNeuron Class\nfrom Modules.single_neuron import SingleNeuron\n\n# Define sigmoid activation function\ndef sigmoid(z):\n return 1.0/(1.0 + np.exp(-z))\n\n# Define MSE cost function\ndef cross_entropy_loss(y_hat, y):\n return - y*np.log(y_hat) - (1 - y)*np.log(1 - y_hat)\n```\n\nWe load the CVDs data set and preprocess the data.\n\n\n```python\n# Import the data\ndf = pd.read_csv(\"https://raw.githubusercontent.com/YulinLi98/Sample_Repo/main/heart.csv\")\n\n# Data Preprocessing by onehot encoding\ndf.Sex = df.Sex.replace({'M':1, 'F':0})\ndf.ExerciseAngina = df.ExerciseAngina.replace({'Y':1, 'N':0})\n\nChestPainType = pd.get_dummies(df.ChestPainType,drop_first=True)\nRestingECG = pd.get_dummies(df.RestingECG,drop_first=True)\nST_Slope = pd.get_dummies(df.ST_Slope,drop_first=True)\ndf = pd.concat([df,ChestPainType, RestingECG, ST_Slope],axis=1)\ndf.drop(['ChestPainType', 'RestingECG', 'ST_Slope'],axis=1,inplace=True)\n\n# Standardize the data\ndf.Age = preprocessing.scale(df.Age)\ndf.RestingBP = preprocessing.scale(df.RestingBP)\ndf.MaxHR = preprocessing.scale(df.MaxHR)\ndf.Cholesterol = preprocessing.scale(df.Cholesterol)\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
AgeSexRestingBPCholesterolFastingBSMaxHRExerciseAnginaOldpeakHeartDiseaseATANAPTANormalSTFlatUp
0-1.43314010.4109090.82507001.38292800.001001001
1-0.47848401.491752-0.17196100.75415701.010101010
2-1.7513591-0.1295130.7701880-1.52513800.001000101
3-0.58455600.3028250.1390400-1.13215611.510001010
40.05188110.951331-0.0347550-0.58198100.000101001
\n
\n\n\n\nThen we extract the exploratory variables and response variable. We split the data into training set and testing set.\n\n\n```python\nX = df.drop('HeartDisease',axis=1).to_numpy()\ny = df.HeartDisease\n\n# Create a training set and a testing set\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.30, random_state=42)\n```\n\nWe instantiate an instance of logistic regression single neuron class with sigmoid function, cross entropy loss and SinleNeuron class. Then we fit the logit model on the training set.\n\n\n```python\n# Instantiate one instance of logistic regression single neuron class\nnp.random.seed(2)\nnode = SingleNeuron(sigmoid, cross_entropy_loss)\n\n# Call the train method to train the weights and bias of the given instance\nnode.train(X_train, y_train, alpha=0.01, epochs=50)\n```\n\n\n\n\n \n\n\n\n\n```python\nnode.plot_cost_function()\nplt.show()\n```\n\nThe cross entropy cost is decreasing over each epoch, meaning that our logit model is learning. Now let's make prediction on the testing set and check the confusion matrix and classification report.\n\n\n```python\n# Make predictions on testing data\ny_pred = np.rint(node.predict(X_test))\n\n# Calculate the confusion matrix\ncf_matrix = confusion_matrix(y_test, y_pred)\n\n# Print the confusion matrix \nprint(f\"cf_matrix = {cf_matrix} \\n\")\n\n# View the confusion matrix using the seaborn package\nplt.figure(figsize = (10, 8))\nax = sns.heatmap(cf_matrix, annot=True, cmap='Blues', cbar=False)\n\nax.set_title('Seaborn Confusion Matrix with labels\\n\\n');\nax.set_xlabel('\\nPredicted Values')\nax.set_ylabel('Actual Values ');\n\n## Ticket labels - List must be in alphabetical order\nax.xaxis.set_ticklabels(['False','True'])\nax.yaxis.set_ticklabels(['False','True'])\nplt.show()\n```\n\n\n```python\n#Check performance of our model with classification report\nprint(classification_report(y_test, y_pred))\n```\n\n precision recall f1-score support\n \n 0 0.82 0.89 0.85 112\n 1 0.92 0.87 0.89 164\n \n accuracy 0.88 276\n macro avg 0.87 0.88 0.87 276\n weighted avg 0.88 0.88 0.88 276\n \n\n\nThe accuracy is 0.88, which is pretty high when compared with other classification models. Therefore, the logistic regression model performs well on our main data set. Now we will do an experiment by increasing the epoch number to 1_000.\n\n\n```python\n# increase the epochs number to 1000\nnp.random.seed(2)\nnode2 = SingleNeuron(sigmoid, cross_entropy_loss)\nnode2.train(X_train, y_train, alpha=0.01, epochs=1000)\n\nnode2.plot_cost_function()\nplt.show()\n\n# Make predictions on testing data\ny_pred = np.rint(node2.predict(X_test))\n\n# Calculate the confusion matrix\ncf_matrix = confusion_matrix(y_test, y_pred)\n\n# Print the confusion matrix \nprint(f\"cf_matrix = {cf_matrix} \\n\")\n\n# View the confusion matrix using the seaborn package\nplt.figure(figsize = (10, 8))\nax = sns.heatmap(cf_matrix, annot=True, cmap='Blues', cbar=False)\n\nax.set_title('Seaborn Confusion Matrix with labels\\n\\n');\nax.set_xlabel('\\nPredicted Values')\nax.set_ylabel('Actual Values ');\n\n## Ticket labels - List must be in alphabetical order\nax.xaxis.set_ticklabels(['False','True'])\nax.yaxis.set_ticklabels(['False','True'])\nplt.show()\n\n#Check performance of our model with classification report\nprint(classification_report(y_test, y_pred))\n```\n\nBoth the confusion matrix and classification report indicate that increasing the epoch number does not make significant improvement on the model performance. Now let's try performing logistic regression using scikit-learn.\n\n\n```python\nfrom sklearn.linear_model import LogisticRegression\n\nlog_reg = LogisticRegression()\nlog_reg.fit(X_train, y_train)\ny_pred = log_reg.predict(X_test)\n\n# Calculate the confusion matrix\ncf_matrix = confusion_matrix(y_test, y_pred)\n\n# Print the confusion matrix \nprint(f\"cf_matrix = {cf_matrix} \\n\")\n\n# View the confusion matrix using the seaborn package\nplt.figure(figsize = (10, 8))\nax = sns.heatmap(cf_matrix, annot=True, cmap='Blues', cbar=False)\n\nax.set_title('Seaborn Confusion Matrix with labels\\n\\n');\nax.set_xlabel('\\nPredicted Values')\nax.set_ylabel('Actual Values ');\n\n## Ticket labels - List must be in alphabetical order\nax.xaxis.set_ticklabels(['False','True'])\nax.yaxis.set_ticklabels(['False','True'])\nplt.show()\n\n#Check performance of our model with classification report\nprint(classification_report(y_test, y_pred))\n```\n\nThe results from ```LogisticRegression``` are the same as our logit single neuron model.\n\n---\n\n## Conclusion\n\nFrom the result above, we can see that the logistic regression single neuron model performs well on the CVDs data set. Compared with the single neuron perceptron model, the logistic regression model has better performance. The main reason is that the logistic regression model can deal with non-linearly separable data.\n\n\n", "meta": {"hexsha": "707e77db8d208e2f81e4820e6813ca65dd309a13", "size": 138009, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Supervised_Learning/Logistic_Regression/Logistic_Regression.ipynb", "max_stars_repo_name": "YulinLi98/Sample_INDE_Repo", "max_stars_repo_head_hexsha": "290a295e1dd5c46aaec2a380a2c98b2e96820fcd", "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": "Supervised_Learning/Logistic_Regression/Logistic_Regression.ipynb", "max_issues_repo_name": "YulinLi98/Sample_INDE_Repo", "max_issues_repo_head_hexsha": "290a295e1dd5c46aaec2a380a2c98b2e96820fcd", "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": "Supervised_Learning/Logistic_Regression/Logistic_Regression.ipynb", "max_forks_repo_name": "YulinLi98/Sample_INDE_Repo", "max_forks_repo_head_hexsha": "290a295e1dd5c46aaec2a380a2c98b2e96820fcd", "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.4986486486, "max_line_length": 31614, "alphanum_fraction": 0.8770297589, "converted": true, "num_tokens": 4836, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693716759489, "lm_q2_score": 0.9086179055936797, "lm_q1q2_score": 0.8628865954986664}} {"text": "# Week 2 - Crossmatching Catalogues\n#### \n\n\n```python\nimport numpy as np\nimport time\nfrom astropy.coordinates import SkyCoord\nfrom astropy import units as u\n```\n\n### Convert from HMS & DMS notation to Decimal degrees\n\n\n```python\ndef hms2dec(h,m,s):\n return 15*(h + m/60 + s/(60*60))\n\ndef dms2dec(h,m,s):\n return h*(1 + m/(abs(h)*60) + s/(abs(h)*60*60)) \n\n# The first example from the question\nprint(hms2dec(23, 12, 6))\n\n# The second example from the question\nprint(dms2dec(22, 57, 18))\n\n# The third example from the question\nprint(dms2dec(-66, 5, 5.1))\n```\n\n 348.025\n 22.955000000000002\n -66.08475\n\n\n#### \n\n### Haversine Formula for calculating Angular Distance\n###### \n\\begin{align}\nd = 2 \\arcsin \\sqrt{ \\sin^2 \\frac{|\\delta_1 - \\delta_2|}{2} + \\cos \\delta_1 \\cos \\delta_2 \\sin^2 \\frac{|\\alpha_1 - \\alpha_2|}{2} }\n\\end{align}\n\n\n```python\ndef angular_dist(r1,d1,r2,d2):\n r1, r2, d1, d2 = np.radians(r1), np.radians(r2), np.radians(d1), np.radians(d2)\n a = np.sin(np.abs(d1 - d2)/2)**2\n b = np.cos(d1)*np.cos(d2)*np.sin(np.abs(r1 - r2)/2)**2\n d = 2*np.arcsin(np.sqrt(a + b))\n return np.degrees(d)\n\n# Run your function with the first example in the question.\nprint(angular_dist(21.07, 0.1, 21.15, 8.2))\n\n# Run your function with the second example in the question\nprint(angular_dist(10.3, -3, 24.3, -29))\n```\n\n 8.100392318146504\n 29.208498180546595\n\n\n#### \n\n### Reading data from AT20G BSS and SuperCOSMOS catalogues\n\n\n```python\ndef import_bss(path):\n data = np.loadtxt(path, usecols=range(1, 7))\n out = []\n for i, row in enumerate(data, 1):\n out.append((i, hms2dec(row[0], row[1], row[2]), dms2dec(row[3], row[4], row[5]))) \n return out\n\ndef import_super(path):\n data = np.loadtxt(path, delimiter=',', skiprows=1, usecols=[0, 1])\n out = []\n for i, row in enumerate(data, 1):\n out.append((i, row[0], row[1])) \n return out\n\n# Output of the import_bss and import_super functions\nbss_cat = import_bss('Data 2/bss_truncated.dat')\nsuper_cat = import_super('Data 2/super_truncated.csv')\n\nprint('Object ID | Right Ascension° | Declination°\\n')\nprint(bss_cat)\nprint(super_cat)\n```\n\n Object ID | Right Ascension° | Declination°\n \n [(1, 1.1485416666666666, -47.60530555555555), (2, 2.6496666666666666, -30.463416666666664), (3, 2.7552916666666665, -26.209194444444442)]\n [(1, 1.0583407, -52.9162402), (2, 2.6084425, -41.5005753), (3, 2.7302499, -27.706955)]\n\n\n#### \n\n### Finding closest neighbour for a target source (RA°, Dec°) from a catalogue\n\n\n```python\ndef find_closest(data, RA1, Dec1):\n ind = 0\n closest = angular_dist(RA1, Dec1, data[0][1], data[0][2])\n for i, row in enumerate(data, 0):\n test = angular_dist(RA1, Dec1, row[1], row[2])\n if test < closest:\n ind = i\n closest = test\n return (data[ind][0], closest)\n\ncat = import_bss('Data 2/bss.dat')\nprint('ID | Angular Distance°\\n')\n\n# First example from the question\nprint(find_closest(cat, 175.3, -32.5))\n\n# Second example in the question\nprint(find_closest(cat, 32.2, 40.7))\n\n```\n\n ID | Angular Distance°\n \n (156, 3.7670580226469013)\n (26, 57.729135775621295)\n\n\n#### \n\n## Crossmatching 2 catalogues within a given distance\n\n\n```python\ndef crossmatch(cat1, cat2, dist):\n matches, no_matches = [], []\n for i, row in enumerate(cat1,1):\n test = find_closest(cat2, row[1], row[2])\n if test[1] < dist:\n matches.append((i, test[0], test[1]))\n else:\n no_matches.append(i)\n return matches, no_matches\n\nbss_cat = import_bss('Data 2/bss (2).dat')\nsuper_cat = import_super('Data 2/super.csv')\n\n# First example in the question\nmax_dist = 40/3600\nmatches, no_matches = crossmatch(bss_cat, super_cat, max_dist)\nprint('1st Object ID | 2nd Object ID | Angular Distance°\\n')\nprint(matches[:3])\nprint('Unmatched IDs from 1st Catalogue - ', no_matches[:3])\nprint('No. of Unmatched objects in 1st Catalogue = ', len(no_matches), '\\n')\n\n# Second example in the question\nmax_dist = 5/3600\nmatches, no_matches = crossmatch(bss_cat, super_cat, max_dist)\nprint(matches[:3])\nprint('Unmatched IDs from 1st Catalogue - ', no_matches[:3])\nprint('No. of Unmatched objects in 1st Catalogue = ', len(no_matches))\n\n```\n\n 1st Object ID | 2nd Object ID | Angular Distance°\n \n [(1, 2, 0.00010988610939332616), (2, 4, 0.0007649845967220993), (3, 5, 0.00020863352870707666)]\n Unmatched IDs from 1st Catalogue - [5, 6, 11]\n No. of Unmatched objects in 1st Catalogue = 9 \n \n [(1, 2, 0.00010988610939332616), (2, 4, 0.0007649845967220993), (3, 5, 0.00020863352870707666)]\n Unmatched IDs from 1st Catalogue - [5, 6, 11]\n No. of Unmatched objects in 1st Catalogue = 40\n\n\n#### \n\n### Microoptimising the crossmatch\n\n\n```python\ndef angular_dist(r1,d1,r2,d2):\n a = np.sin(np.abs(d1 - d2)/2)**2\n b = np.cos(d1)*np.cos(d2)*np.sin(np.abs(r1 - r2)/2)**2\n d = 2*np.arcsin(np.sqrt(a + b))\n return d\n\ndef find_closest(data, RA1, Dec1):\n ind = 0\n closest = angular_dist(RA1, Dec1, data[0][0], data[0][1])\n for i, row in enumerate(data, 0):\n test = angular_dist(RA1, Dec1, row[0], row[1])\n if test < closest:\n closest = test\n ind = i\n return (ind, closest)\n\ndef crossmatch(cat1, cat2, dist):\n start = time.perf_counter()\n matches, no_matches = [], []\n cat1 = np.radians(cat1)\n cat2 = np.radians(cat2)\n dist = np.radians(dist)\n for i, row in enumerate(cat1,0):\n test = find_closest(cat2, row[0], row[1])\n if test[1] < dist:\n matches.append((i, test[0], np.degrees(test[1])))\n else:\n no_matches.append(i)\n seconds = time.perf_counter() - start\n return matches, no_matches, seconds\n\n\n# The example in the question\ncat1 = np.array([[180, 30], [45, 10], [300, -45]])\ncat2 = np.array([[180, 32], [55, 10], [302, -44]])\nmatches, no_matches, time_taken = crossmatch(cat1, cat2, 5)\nprint('1st Object ID | 2nd Object ID | Angular Distance°\\n')\nprint('matches:', matches)\nprint('unmatched:', no_matches)\nprint('time taken:', time_taken, '\\n')\n\n# A function to create a random catalogue of size n\ndef create_cat(n):\n ras = np.random.uniform(0, 360, size=(n, 1))\n decs = np.random.uniform(-90, 90, size=(n, 1))\n return np.hstack((ras, decs))\n\n# Test your function on random inputs\nnp.random.seed(0)\ncat1 = create_cat(10)\ncat2 = create_cat(20)\nmatches, no_matches, time_taken = crossmatch(cat1, cat2, 5)\nprint('matches:', matches)\nprint('unmatched:', no_matches)\nprint('time taken:', time_taken)\n```\n\n 1st Object ID | 2nd Object ID | Angular Distance°\n \n matches: [(0, 0, 2.0000000000000027), (2, 2, 1.7420109046547023)]\n unmatched: [1]\n time taken: 0.0003623000000061438 \n \n matches: []\n unmatched: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n time taken: 0.005214199999954872\n\n\n#### \n\n### Vectorisation using NumPy\n\n\n```python\ndef crossmatch_vect(cat1, cat2, max_radius):\n start = time.perf_counter()\n max_radius = np.radians(max_radius)\n \n matches, no_matches = [], []\n\n # Convert coordinates to radians\n cat1 = np.radians(cat1)\n cat2 = np.radians(cat2)\n ra2s = cat2[:,0]\n dec2s = cat2[:,1]\n\n for id1, (ra1, dec1) in enumerate(cat1):\n dists = angular_dist(ra1, dec1, ra2s, dec2s)\n min_id = np.argmin(dists)\n min_dist = dists[min_id]\n if min_dist > max_radius:\n no_matches.append(id1)\n else:\n matches.append((id1, min_id, np.degrees(min_dist)))\n \n time_taken = time.perf_counter() - start\n return matches, no_matches, time_taken\n\n# The example in the question\nra1, dec1 = np.radians([180, 30])\ncat2 = [[180, 32], [55, 10], [302, -44]]\ncat2 = np.radians(cat2)\nra2s, dec2s = cat2[:,0], cat2[:,1]\ndists = angular_dist(ra1, dec1, ra2s, dec2s)\nprint('Angular distance° - ', np.degrees(dists), '\\n')\n\ncat1 = np.array([[180, 30], [45, 10], [300, -45]])\ncat2 = np.array([[180, 32], [55, 10], [302, -44]])\nmatches, no_matches, time_taken = crossmatch_vect(cat1, cat2, 5)\nprint('matches:', matches)\nprint('unmatched:', no_matches)\nprint('time taken:', time_taken, '\\n')\n\n# Test your function on random inputs\ncat1 = create_cat(10) # Create a random catalogue of size 10\ncat2 = create_cat(20)\nmatches, no_matches, time_taken = crossmatch_vect(cat1, cat2, 5)\nprint('matches:', matches)\nprint('unmatched:', no_matches)\nprint('time taken:', time_taken)\n```\n\n Angular distance° - [ 2. 113.72587199 132.64478705] \n \n matches: [(0, 0, 2.0000000000000027), (2, 2, 1.7420109046547023)]\n unmatched: [1]\n time taken: 0.00032420000025012996 \n \n matches: []\n unmatched: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n time taken: 0.0007706999999754771\n\n\n#### \n\n### Breaking out after maximum match radius : Searching within -90° < δ° < (δ + r)°\n\n\n```python\ndef crossmatch(cat1, cat2, max_radius):\n start = time.perf_counter()\n max_radius = np.radians(max_radius) \n matches, no_matches = [], []\n\n cat1 = np.radians(cat1)\n cat2 = np.radians(cat2)\n order = np.argsort(cat2[:,1])\n cat2_ordered = cat2[order]\n \n for id1, (ra1, dec1) in enumerate(cat1):\n min_dist = np.inf\n min_id2 = None\n max_dec = dec1 + max_radius\n for id2, (ra2, dec2) in enumerate(cat2_ordered):\n if dec2 > max_dec:\n break\n dist = angular_dist(ra1, dec1, ra2, dec2)\n if dist < min_dist:\n min_id2 = order[id2]\n min_dist = dist\n if min_dist > max_radius:\n no_matches.append(id1)\n else:\n matches.append((id1, min_id2, np.degrees(min_dist)))\n \n time_taken = time.perf_counter() - start\n return matches, no_matches, time_taken\n\n\n# The example in the question\ncat1 = np.array([[180, 30], [45, 10], [300, -45]])\ncat2 = np.array([[180, 32], [55, 10], [302, -44]])\nmatches, no_matches, time_taken = crossmatch(cat1, cat2, 5)\nprint('matches:', matches)\nprint('unmatched:', no_matches)\nprint('time taken:', time_taken, '\\n')\n\n# Test your function on random inputs\nnp.random.seed(0)\ncat1 = create_cat(10)\ncat2 = create_cat(20)\nmatches, no_matches, time_taken = crossmatch(cat1, cat2, 5)\nprint('matches:', matches)\nprint('unmatched:', no_matches)\nprint('time taken:', time_taken)\n```\n\n matches: [(0, 0, 2.0000000000000027), (2, 2, 1.7420109046547023)]\n unmatched: [1]\n time taken: 0.015049199999793927 \n \n matches: []\n unmatched: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n time taken: 0.006830000000263681\n\n\n#### \n\n### Boxing Match : Searching within (δ - r)° < δ° < (δ + r)°\n\n\n```python\ndef crossmatch_boxing(cat1, cat2, max_radius):\n start = time.perf_counter()\n max_radius = np.radians(max_radius) \n matches, no_matches = [], []\n\n cat1 = np.radians(cat1)\n cat2 = np.radians(cat2)\n order = np.argsort(cat2[:,1])\n cat2_ordered = cat2[order]\n \n for id1, (ra1, dec1) in enumerate(cat1):\n min_dist = np.inf\n min_id2 = None\n max_dec = dec1 + max_radius\n index = np.searchsorted(cat2_ordered[:,1], dec1 - max_radius, side='left')\n \n for id2, (ra2, dec2) in enumerate(cat2_ordered[index:,:]):\n if dec2 > max_dec:\n break\n dist = angular_dist(ra1, dec1, ra2, dec2)\n if dist < min_dist:\n min_id2 = order[index:][id2]\n min_dist = dist\n if min_dist > max_radius:\n no_matches.append(id1)\n else:\n matches.append((id1, min_id2, np.degrees(min_dist)))\n \n time_taken = time.perf_counter() - start\n return matches, no_matches, time_taken\n\n\n# The example in the question\ncat1 = np.array([[180, 30], [45, 10], [300, -45]])\ncat2 = np.array([[180, 32], [55, 10], [302, -44]])\nmatches, no_matches, time_taken = crossmatch_boxing(cat1, cat2, 5)\nprint('matches:', matches)\nprint('unmatched:', no_matches)\nprint('time taken:', time_taken, '\\n')\n\n# Test your function on random inputs\nnp.random.seed(0)\ncat1 = create_cat(10)\ncat2 = create_cat(20)\nmatches, no_matches, time_taken = crossmatch_boxing(cat1, cat2, 5)\nprint('matches:', matches)\nprint('unmatched:', no_matches)\nprint('time taken:', time_taken)\n```\n\n matches: [(0, 0, 2.0000000000000027), (2, 2, 1.7420109046547023)]\n unmatched: [1]\n time taken: 0.044778799999676266 \n \n matches: []\n unmatched: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n time taken: 0.0005314999998518033\n\n\n#### \n\n### Crossmatching with k-d Trees\n\n\n```python\ndef crossmatch_kd(cat1, cat2, dist):\n start = time.perf_counter()\n sky_cat1 = SkyCoord(cat1*u.degree, frame='icrs')\n sky_cat2 = SkyCoord(cat2*u.degree, frame='icrs')\n closest_ids, closest_dists, closest_dists3d = sky_cat1.match_to_catalog_sky(sky_cat2) \n matches, no_matches = [], []\n for i, ele in enumerate(closest_dists.value):\n if ele < dist:\n matches.append((i, closest_ids[i], ele))\n else:\n no_matches.append(i)\n seconds = time.perf_counter() - start\n return matches, no_matches, seconds\n\n\n# The example in the question\ncat1 = np.array([[180, 30], [45, 10], [300, -45]])\ncat2 = np.array([[180, 32], [55, 10], [302, -44]])\nmatches, no_matches, time_taken = crossmatch_kd(cat1, cat2, 5)\nprint('matches:', matches)\nprint('unmatched:', no_matches)\nprint('time taken:', time_taken, '\\n')\n\n# Test your function on random inputs\nnp.random.seed(0)\ncat1 = create_cat(10)\ncat2 = create_cat(20)\nmatches, no_matches, time_taken = crossmatch_kd(cat1, cat2, 5)\nprint('matches:', matches)\nprint('unmatched:', no_matches)\nprint('time taken:', time_taken)\n```\n\n matches: [(0, 0, 2.0000000000000036), (2, 2, 1.7420109046547163)]\n unmatched: [1]\n time taken: 2.324950500000341 \n \n matches: []\n unmatched: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n time taken: 0.005834800000229734\n\n", "meta": {"hexsha": "a317d319b0aa247782cb2152703ed7babc01bf4e", "size": 20782, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Week 2 - Crossmatching/Week 2.ipynb", "max_stars_repo_name": "utsav-akhaury/Data-driven-Astronomy", "max_stars_repo_head_hexsha": "7b09c30054a46f915b1a3e88b0cf59f91a4308f5", "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 2 - Crossmatching/Week 2.ipynb", "max_issues_repo_name": "utsav-akhaury/Data-driven-Astronomy", "max_issues_repo_head_hexsha": "7b09c30054a46f915b1a3e88b0cf59f91a4308f5", "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 2 - Crossmatching/Week 2.ipynb", "max_forks_repo_name": "utsav-akhaury/Data-driven-Astronomy", "max_forks_repo_head_hexsha": "7b09c30054a46f915b1a3e88b0cf59f91a4308f5", "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.1882022472, "max_line_length": 153, "alphanum_fraction": 0.5164084304, "converted": true, "num_tokens": 4538, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566341999997378, "lm_q2_score": 0.9019206758704633, "lm_q1q2_score": 0.8628081642245634}} {"text": "# Exercise 1 - The Mandelbrot Set\n\nThe mandelbrot set is a beautiful fractal ([Wikipedia](http://en.wikipedia.org/wiki/Mandelbrot_set)). \nMore precisely, it contains all numbers from the complex plane where the complex quadratic polynomial \n\n\\begin{align}\n z_{n+1} = z_{n}^2 + c\n\\end{align}\n\nremains bounded. A complex number $c$ is part of the Mandelbrot set when starting with $z_0=0$ and applying the iteration repeatedly, the absolute value of $z_n$ remains smaller or equal than 2 regardless how large $n$ becomes.\n\nMoreover, one can draw very beautiful images by looking at the *escape time* of a numerical computation:\nWe will numerically determine whether a complex number $c$ belongs to the set, and if not we will keep track how many iterations are needed until $|z_n| > 2$. Plotting the escape times of a sampled grid of complex numbers as a 2D image will yield the famous *Apfelmaennchen* you might have seen before.\n\n#Task:#\n\n* Write a function ``mandelbrot(relim, imlim, resteps, imsteps, maxiterations)`` that computes and returns the escape times for the mandelbrot set.\n * ``relim`` and ``imlim`` are tuples that define the boundary of the complex plane (e.g. ``relim=(-2,1)`` and ``imlim=(-1,1)``), for convenience ``imlim`` should contain real numbers although it represents the complex axis.\n * ``resteps`` and ``imsteps`` are integers and define the sampling resolution along each axis (e.g. 300 and 200 steps).\n * ``maxiterations`` is an integer defining the maximum number of iterations (e.g. 50).\n \n * The function should sample complex numbers from the plane as defined by the parameters ``relim, imlim, resteps, imsteps`` and repeatedly apply the quadratic polynomial from above until the absolute value of a complex number is larger than 2. In case a maximum number of iterations is reached (``maxiterations``) the number is believed to be part of the set. \n * The function should return a 2D array containing the number of iterations needed for every sampled complex number and two 1D arrays containing the sampled values along each axis. Escape times in the 2D array of exactly ``maxiterations`` indicate complex numbers that are believed to be part of the set.\n* Make a 2D color plot of the escape times, you might want to look at matplotlib's [imshow](http://www.mathworks.de/de/help/images/ref/imshow.html) function.\n \n###Hints how the function ``mandelbrot`` may work:###\n* Create a 2D numpy array containing the escape times, in the beginning filled with zeros. \n\n* Secondly, create two 1D arrays sampling each dimension of the complex plane. You might want to take a look at the [np.linspace](http://docs.scipy.org/doc/numpy/reference/generated/numpy.linspace.html) function. You can multiply one of the arrays with ``1j`` to create the imaginary axis. Later on you can calculate each starting complex number simply from summing individual elements of both arrays.\n\n* The easy brute-force solution involves three nested for loops. Be aware that you can use python's ``break`` statement to leave a for loop and spare unnecessary computations.\n\n* Iterate at most ``maxiterations`` times for any value in your complex plane and apply the quadratic polynomial from above. If the absolute value gets larger than 2 you can stop iterating and store the number of iterations you have needed in the 2D escape array. Thus, for complex numbers that are actually part of the Mandelbrot set, the 2D array of escape times should contain the value ``maxiterations``.\n\n\n###Hints for optimization:###\n* You can aim for an optimized version that uses vectorized computation. Here you should only need a single for loop.\n\n* Create a second and third 2D array containing the starting complex numbers and the intermediate values, checkout the [meshgrid](http://docs.scipy.org/doc/numpy/reference/generated/numpy.meshgrid.html) function to create these.\n\n* Use the second 2D array to iteratively update all values in the third array at once (vectorized computation!). Mask all values that already escaped the boundary via boolean indexing to speed up the computation.\n\n* Remember that boolean indexing creates copies, not views! So you need to find a smart way to only apply the polynomial\nto values that haven't escaped without always keeping the full 2D array, otherwise internally numpy has to reiterate the full array every timestep. If you also create mesh grids of matrix indices you can reduce the 2D arrays each iteration to 1D arrays containing only the currently not escaped values. This is tricky!\n\n* Now you can use finer resolutions than above!\n\n# Exercise 2 - Numerical Integration of a Neuron Model\n\nWe are going to simulate our first neuron model with Euler integration ([Wikipedia](http://en.wikipedia.org/wiki/Euler_method)).\nBasically, our neuron model consists of a single differential equation that describes the development of the membrane voltage over time. For now let's assume this equation is an arbitrary function $f$:\n\\begin{align}\n \\frac{dV}{dt} = f(V)\n\\end{align}\nTo obtain the voltage as a function of time, i.e. $V(t)$, we have to solve the differential equation. Lucky for you, we are in the computer practical and not the analytical tutorial. We are going to solve it numerically, so there's no need for a complicated Ansatz :-)\n\nAs said before, we will use simple Euler integration. Accordingly, if we assume discretized time we can easily compute $V(t+1)$, the membrane voltage of the next time step, in case we now the previous voltage $V(t)$:\n\\begin{align}\nV(t+1) = V(t) + f(V) * dt\n\\end{align}\nwith $dt$ the size of the discretized timesteps.\n\nIf we start with a chosen initial value of $V(0)$ we can iteratively solve the differential equation.\n\nBy this method we can simulate very complex neuron models. Let's simulate a rescaled version of the exponential integrate and fire neuron ([Scholarpedia](http://www.scholarpedia.org/article/Adaptive_exponential_integrate-and-fire_model)):\n\\begin{align}\n \\frac{dV}{dt} = -V + \\exp(V) + I\n\\end{align}\n\n$I$ describes a fixed input current. We will simulate several neurons fed with different current values.\nFor some values of $I$ the membrane potential $V$ will rise to infinity, this corresponds to the upstroke of an action potential (you remember action potentials from a neurobio course, right?). However, our neuron model cannot recover from this upstroke by itself. For a smooth recovery we would need a second differential equation. However, we will keep our model simple and add a so called *reset rule*: whenever $V$ crosses a particular threshold $V(t)\\geq V_t$ then we set it back to a reset value at the next timestep $V(t+1)=V_r$.\n\n#Task#\n\n* Write a function ``expIF_neuron(V, I, Vt, Vr, duration, dt)`` that simulates one or more exponetial integrate-and-fire neurons.\n * The parameter ``V`` can be a scalar or numpy array describing the initial conditions\n * The parameter ``I`` can be a scalar or numpy array describing the input currents\n * The parameter ``Vt`` is a scalar value defining the spiking threshold\n * The parameter ``Vr`` is a scalar defining the reset value after threshold crossing\n * The parameter ``duration`` gives the length of the simulation\n * The parameter ``dt`` describes the stepsize of the Euler integration\n * The function should return \n * A 2D array of voltage traces, i.e. the simulated development of the membrane potential\n * First dimension is the number of neurons, second dimension the voltage trace over time\n * First entries in second dimension should contain the initial values\n * A 1D array containing the discretized timesteps\n * In case ``V`` and ``I`` are arrays, the function should be vectorized, i.e. there should only be a single loop over all timesteps, but no loop over all neurons!\n \n* Simulate 5 neurons at once (do NOT call the function 5 times!) with 5 different input currents $I\\in\\{-3.0, -2.0, -1.0, 0.0, 1.0\\}$.\n * Choose the other parameters as\n * $V_r=-1.0$\n * $V_t=5.0$\n * $duration=10.0$\n * $dt = 0.01$\n * Set the initial $V$ values to $V_r$\n* Plot all 5 voltage traces in a single plot, add a legend and label the axis.\n\n###Hints###\n* You can use the template provided below. This exercise can be solved in just a handful of lines ;-)\n* To incorporate the reset rule you may try boolean indexing.\n\n\n\n```\n## The template: ##\n\ndef expIF_neuron(V=-1.0, I=0.0, Vt=5.0, Vr=-1.0, duration=10.0, dt=0.01):\n \"\"\"Numerically integrates the expIF neuron membrane equation with the Euler-Method.\n \n The neurons obey a reset rule, when the membrane potential crosses `Vt`\n it is set back to `Vr`.\n \n :param V: array of initial membrane values (or a scalar)\n :param VT: spiking threshold (scalar)\n :param I: array of input currents (or scalar)\n :param duration: duration of experiment (scalar)\n :param dt: stepsize of Euler integration (scalar)\n \n :return:\n \n 2D array of voltage time series, first dimension the neurons, \n second dimension the voltage trace. \n First entries contain the initial values.\n \n 1D array of simulation times\n \n \"\"\"\n \n steps = int(duration/dt) # Calculate the number of simulation steps\n \n if isinstance(V, np.ndarray): # V can be scalar or an array, we need to check first\n nneurons = len(V) # Infer the number of neurons from the length of the initial conditions\n else:\n nneurons = 1\n \n V_series = np.zeros((nneurons, steps+1)) # Array that will contain the voltage traces\n # 1st dim neurons, 2nd dim voltage traces\n # i.e. V[2,10] would return the voltage of neuron #2 at the 10th timestep!\n # Wee need steps+1 since the 0th entry should contain the initial conditions\n \n V_series[:, 0] = V # Set initial conditions\n \n times = np.zeros(steps+1) # Array of timesteps\n \n for step in range(1, steps+1): # Loop starting from step 1 (0th contains initial conditions)\n \n ############# Your code ##############\n \n # Manipulate V_series here to simulate the neuron model\n # Iteratively compute f(V(t)) = -V(t) + exp(V(t)) + I and V(t+1) = V(t) + f(V(t)) * dt \n # Do not introduce another for loop, try to think vectorized\n # Try using boolean indexing to implement the threshold crossing and voltage reset\n \n ######### End of your code ###########\n \n times[step] = times[step-1] + dt # You actually don't need the times explicitly, but returning them\n # will make plotting easier\n \n return V_series, times\n \n```\n\n\n```\n\n```\n", "meta": {"hexsha": "c74309d5fd7d40ba42f884773d4ddb5ccc54be40", "size": 13276, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "python-beginner/PCC_Exercise_2.ipynb", "max_stars_repo_name": "BCCN-Prog/materials", "max_stars_repo_head_hexsha": "4317ab52521093cc84c33b41ab027b46d1e5e48a", "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-beginner/PCC_Exercise_2.ipynb", "max_issues_repo_name": "BCCN-Prog/materials", "max_issues_repo_head_hexsha": "4317ab52521093cc84c33b41ab027b46d1e5e48a", "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-beginner/PCC_Exercise_2.ipynb", "max_forks_repo_name": "BCCN-Prog/materials", "max_forks_repo_head_hexsha": "4317ab52521093cc84c33b41ab027b46d1e5e48a", "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.6226415094, "max_line_length": 548, "alphanum_fraction": 0.6253389575, "converted": true, "num_tokens": 2554, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240194661945, "lm_q2_score": 0.9196425234694067, "lm_q1q2_score": 0.8627387405891539}} {"text": "\n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\n```\n\n## Numerical Integration\n\nNumerical integration methods seek an approximate solution to a definite integral\n$$\\int_a^b f(x)\\, dx \\, .$$\n\n\n```python\n# define function\ndef f(x):\n return 1/(1+np.power(x,2))\n\n# domain bounds\na = 0\nb = 3\n\n# plot\nfig = plt.figure(figsize=plt.figaspect(0.5))\nax = fig.add_subplot(111) \n\nx = np.linspace(a-0.1*(b-a), b+0.1*(b-a), 100)\ny = f(x)\nax.plot(x, y,'-', label='$f(x)$')\n\nX = np.linspace(a,b,100)\nY = f(X)\nax.fill_between(X,Y, color='r', alpha=0.2, label=\"$\\int_a^b f(x)\\, dx$\")\n\nax.legend(prop={'size':15})\nplt.show()\n\n```\n\nIn above example, we have chosen \n$$f(x)=\\frac{1}{1+x^2} \\; .$$\nThe integral of this function is known:\n$$\\int \\frac{1}{1+x^2} \\, dx= \\tan^{-1}(x) + C =\\arctan(x) + C$$\nSo we can solve the integral analytically:\n$$\\int_a^b \\frac{1}{1+x^2} \\, dx = \\arctan(b) - \\arctan(a)$$\n\n\n\n```python\n# plot arctan(x)\nfig = plt.figure(figsize=plt.figaspect(0.5))\nax = fig.add_subplot(111) \n\ny = np.arctan(x)\nax.plot(x, y,'-', label='arctan(x)')\nax.axvline(x=a, color='green', linestyle=':')\nax.axvline(x=b, color='red', linestyle=':')\nax.axhline(y=np.arctan(a), color='green', linestyle='--', label='arctan(x=a)')\nax.axhline(y=np.arctan(b), color='red', linestyle='--', label='arctan(x=b)')\n\nax.legend(prop={'size':15})\nplt.show()\n```\n\nHowever, not all functions can be integrated analytically, and even if a closed formulation exists, it may be easier to compute a numerical approximation rather than the antiderivative. Also, the integrand $f(x)$ may only be known at certain points.\n\n### Riemann Sums\n\n\nThe [Riemann Integral](https://en.wikipedia.org/wiki/Riemann_integral) is a natural starting point for considering approximation methods for integrals.\n\nLet's assume that $f(x)$ is a bounded function defined on the interval $[a, b]$ which is divided into $N$ subintervals of length $\\Delta x = \\left| a-b\\right|/N$ defining a partition $\\{x_0, x_1, \\ldots x_{N}\\}$ where $a=x_0 < x_1 < x_2 < \\ldots \n\nIf you populated a hypercube of size $2r$ how much data would be enclosed by the hypersphere\n- as $D$ increases the fractional volume enclosed by the hypersphere goes to 0! \n\nFor example: the SDSS comprises a sample of 357 million sources. \n- each source has 448 measured attributes\n- selecting just 30 (e.g., magnitude, size..) and normalizing the data range $-1$ to $1$\n\nprobability of having one of the 357 million sources reside within a unit hypersphere 1 in 1.4$\\times 10^5$.\n\n\n```python\n%matplotlib inline\nimport numpy as np\nimport scipy.special as sp\nfrom matplotlib import pyplot as plt\n\ndef unitVolume(dimension, radius=1.):\n return 2*(radius**dimension *np.pi**(dimension/2.))/(dimension*sp.gamma(dimension/2.))\n\ndim = np.linspace(1,100)\n\n#------------------------------------------------------------\n# Plot the results\nfig = plt.figure()\nax = fig.add_subplot(111)\nax.plot(dim,unitVolume(dim)/2.**dim)\n\nax.set_yscale('log')\nax.set_xlabel('$Dimension$')\nax.set_ylabel('$Volume$')\n\nplt.show()\n\n```\n\n\n```python\nD=30;unitVolume(D)/(2.**D)\n```\n\n\n\n\n 2.0410263396641429e-14\n\n\n\n## Increasing interest in dimensionality reduction\n\n\n## What can we do to reduce the dimensions##\n\n**Principal component analysis or the Karhunen-Loeve transform**\n\nThe first refuge of a scoundrel...\n\n\n\nPoints are correlated along a particular direction which doesn't align with the initial choice of axes. \n- we should rotate our axes to align with this correlation. \n- rotation preserves the relative ordering of data\n\nChoose rotation to maximize the ability to discriminate between the data points\n* first axis, or principal component, is direction of maximal variance\n* second principal component is orthogonal to the first component and maximizes the residual variance\n* ...\n\n## Derivation of principal component analyses##\n\nSet of data $X$: $N$ observations by $K$ measurements\n\nCenter data by subtracting the mean **Why?**\n\nThe covariance is\n\n>$ \nC_X=\\frac{1}{N-1}X^TX,\n$\n\n$N-1$ as the sample covariance matrix \n\nWe want a projection, $R$, aligned with the directions of maximal variance ($Y= X R$) with covariance \n\n>$\nC_{Y} = R^T X^T X R = R^T C_X R\n$\n\nDerive principal component by maximizing its variance (using Lagrange multipliers and constraint)\n\n> $\n\\phi(r_1,\\lambda_1) = r_1^TC_X r_1 - \\lambda_1(r_1^Tr_1-1).\n$\n\nderivative of $\\phi(r_1,\\lambda)$ with respect to $r_1$ set to 0\n\n> $\nC_Xr_1 - \\lambda_1 r_1 = 0.\n$\n\n$\\lambda_1$ is the root of the equation $\\det(C_X -\n\\lambda_1 {\\bf I})=0$ and the largest eigenvalue\n\n>$\n\\lambda_1 = r_1^T C_X r_1\n$\n\nOther principal components derived by\napplying additional constraint that components are uncorrelated (e.g., $r^T_2 C_X r_1 = 0$).\n\n## Lagrangian mulitpliers\n\n\n## Computation of principal components##\n\nCommon approach is eigenvalue decomposition of the covariance or correlation matrix,\nor singular value decomposition (SVD) of the data matrix\n\n** SVD given by**\n\n>$\nU \\Sigma V^T = \\frac{1}{\\sqrt{N - 1}} X,\n$\n\ncolumns of $U$ are _left-singular vectors_\n\ncolumns of $V$ are the _right-singular vectors_\n\nThe columns of $U$ and $V$ form orthonormal bases ($U^TU = V^TV = I$)\n\nCovariance matrix is\n\n> $\n\\begin{eqnarray}\n C_X &=& \\left[\\frac{1}{\\sqrt{N - 1}}X\\right]^T \\left[\\frac{1}{\\sqrt{N - 1}}X\\right]\\nonumber\\\\\n &=& V \\Sigma U^T U \\Sigma V^T\\nonumber\\\\\n &=& V \\Sigma^2 V^T.\n\\end{eqnarray}\n$\n\nright singular vectors $V$ are the principal components. We can calculate principal components from the SVD of $X$ - we dont need $C_X$.\n\n\nSingular value decomposition (SVD) can factorize an N x K matrix into $U \\Sigma V^T$. There are different conventions for computing the SVD in the literature, and this figure illustrates the convention used in this text. The matrix of singular values $\\Sigma$ is always a square matrix of size [R x R] where R = min(N, K). The shape of the resulting U and V matrices depends on whether N or K is larger. The columns of the matrix U are called the left-singular vectors, and the columns of the matrix V are called the right-singular vectors. The columns are orthonormal bases, and satisfy $U^T U = V^T V = I$.\n\n## Preparing data for PCA##\n\n- Center data by subtracting the mean of each dimension\n- For heterogeneous data (e.g., galaxy shape and flux) divide by variance (whitening). **why?**\n- For spectra or images normalize each row so integrated flux of each object is one. \n\n\n```python\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\nfrom sklearn.decomposition import PCA\nfrom sklearn.decomposition import RandomizedPCA\n\nfrom astroML.datasets import sdss_corrected_spectra\nfrom astroML.decorators import pickle_results\n\n#------------------------------------------------------------\n# Download data\ndata = sdss_corrected_spectra.fetch_sdss_corrected_spectra()\nspectra = sdss_corrected_spectra.reconstruct_spectra(data)\nwavelengths = sdss_corrected_spectra.compute_wavelengths(data)\n\n\n#----------------------------------------------------------------------\n# Compute PCA\ndef compute_PCA(n_components=5):\n# np.random.seed(500)\n nrows = 500\n ind = np.random.randint(spectra.shape[0], size=nrows)\n \n spec_mean = spectra[ind].mean(0)\n# spec_mean = spectra[:50].mean(0)\n\n # PCA: use randomized PCA for speed\n pca = PCA(n_components - 1)\n pca.fit(spectra[ind])\n pca_comp = np.vstack([spec_mean,\n pca.components_])\n evals = pca.explained_variance_ratio_\n\n return pca_comp, evals\n\nn_components = 5\ndecompositions, evals = compute_PCA(n_components)\n\n#----------------------------------------------------------------------\n# Plot the results\nfig = plt.figure(figsize=(10, 8))\nfig.subplots_adjust(left=0.05, right=0.95, wspace=0.05,\n bottom=0.1, top=0.95, hspace=0.05)\n\ntitles = 'PCA components'\n\nfor j in range(n_components):\n ax = fig.add_subplot(n_components, 2, 2*j+2)\n\n ax.yaxis.set_major_formatter(plt.NullFormatter())\n ax.xaxis.set_major_locator(plt.MultipleLocator(1000))\n if j < n_components - 1:\n ax.xaxis.set_major_formatter(plt.NullFormatter())\n else:\n ax.set_xlabel(r'wavelength ${\\rm (\\AA)}$')\n ax.plot(wavelengths, decompositions[j], '-k', lw=1)\n\n # plot zero line\n xlim = [3000, 7999]\n ax.plot(xlim, [0, 0], '-', c='gray', lw=1)\n ax.set_xlim(xlim)\n\n # adjust y limits\n ylim = plt.ylim()\n dy = 0.05 * (ylim[1] - ylim[0]) \n ax.set_ylim(ylim[0] - dy, ylim[1] + 4 * dy)\n\n\n ax2 = fig.add_subplot(n_components, 2, 2*j+1)\n ax2.yaxis.set_major_formatter(plt.NullFormatter())\n ax2.xaxis.set_major_locator(plt.MultipleLocator(1000))\n if j < n_components - 1:\n ax2.xaxis.set_major_formatter(plt.NullFormatter())\n else:\n ax2.set_xlabel(r'wavelength ${\\rm (\\AA)}$')\n ax2.plot(wavelengths, spectra[j], '-k', lw=1)\n \n # plot zero line\n ax2.plot(xlim, [0, 0], '-', c='gray', lw=1)\n ax2.set_xlim(xlim)\n\n if j == 0:\n ax.set_title(titles, fontsize='medium')\n\n if j == 0:\n label = 'mean'\n else:\n label = 'component %i' % j\n\n # adjust y limits\n ylim = plt.ylim()\n dy = 0.05 * (ylim[1] - ylim[0]) \n ax2.set_ylim(ylim[0] - dy, ylim[1] + 4 * dy)\n\n\n ax.text(0.02, 0.95, label, transform=ax.transAxes,\n ha='left', va='top', bbox=dict(ec='w', fc='w'),\n fontsize='small')\n\n\n \n\nplt.show()\n```\n\n## Interpreting the PCA##\n\nReconstruction of spectrum, ${x}(k)$, from the\neigenvectors, ${e}_i(k)$ \n\n>$ \\begin{equation}\n {x}_i(k) = {\\mu}(k) + \\sum_j^R \\theta_{ij} {e}_j(k),\n\\end{equation}\n$\n\nTruncating this expansion (i.e., $r$\\begin{equation}\n{x}_i(k) = {\\mu}(k) + \\sum_i^{r$\\begin{equation}\n\t\\sum_k \\theta_i {w}(k) {e}_i(k) {e}_j(k) =\n\t\\sum_k {w}(k) {x}^o(k) {e}_j(k),\n\\end{equation}\n$\n\nIf $M_{ij} = \\sum_k {w}(k) {e}_i(k) {e}_j(k)$ and $F_i = \\sum_k {w}(k) {x}^o(k) {e}_i(k)$ then \n\n>$\\begin{equation}\n\t\\theta_i = \\sum_j M_{ij}^{-1} F_{j},\n\\end{equation}\n$\n\n- $F_j$ are coefficients derived from gappy data\n- $M_{ij}^{-1}$ shows how correlated eigenvectors are over the missing regions.\n\nAn estimate of the uncertainty on the\nreconstruction coefficients is given by\n\n>$\\begin{equation}\n%Cov(\\theta_i,\\theta_j) = \\frac{1}{N}M_{ij}^{-1}\n{\\rm Cov}(\\theta_i,\\theta_j) = M_{ij}^{-1}.\n\\end{equation}\n$\n\nAccuracy of this reconstruction will depend on the distribution of\nthe gaps within the data vector.\n\n\n```python\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom matplotlib import ticker\n\nfrom astroML.datasets import fetch_sdss_corrected_spectra\nfrom astroML.datasets import sdss_corrected_spectra\n\n#------------------------------------------------------------\n# Get spectra and eigenvectors used to reconstruct them\ndata = fetch_sdss_corrected_spectra()\nspec = sdss_corrected_spectra.reconstruct_spectra(data)\nlam = sdss_corrected_spectra.compute_wavelengths(data)\nevecs = data['evecs']\nmu = data['mu']\nnorms = data['norms']\nmask = data['mask']\n\n#------------------------------------------------------------\n# plot the results\ni_plot = ((lam > 5750) & (lam < 6350))\nlam = lam[i_plot]\n\nspecnums = [20, 8, 9]\nsubplots = [311, 312, 313]\n\nfig = plt.figure(figsize=(8, 10))\nfig.subplots_adjust(hspace=0)\n\nfor subplot, i in zip(subplots, specnums):\n ax = fig.add_subplot(subplot)\n\n # compute eigen-coefficients\n spec_i_centered = spec[i] / norms[i] - mu\n coeffs = np.dot(spec_i_centered, evecs.T)\n\n # blank out masked regions\n spec_i = spec[i]\n mask_i = mask[i]\n spec_i[mask_i] = np.nan\n\n # plot the raw masked spectrum\n ax.plot(lam, spec_i[i_plot], '-', color='k', lw=2,\n label='True spectrum')\n\n # plot two levels of reconstruction\n for nev in [10]:\n if nev == 0:\n label = 'mean'\n else:\n label = 'nev=%i' % nev\n spec_i_recons = norms[i] * (mu + np.dot(coeffs[:nev], evecs[:nev]))\n ax.plot(lam, spec_i_recons[i_plot], label=label)\n\n # plot shaded background in masked region\n ylim = ax.get_ylim()\n mask_shade = ylim[0] + mask[i][i_plot].astype(float) * ylim[1]\n plt.fill(np.concatenate([lam[:1], lam, lam[-1:]]),\n np.concatenate([[ylim[0]], mask_shade, [ylim[0]]]),\n lw=0, fc='k', alpha=0.2)\n\n ax.set_xlim(lam[0], lam[-1])\n ax.set_ylim(ylim)\n ax.yaxis.set_major_formatter(ticker.NullFormatter())\n\n if subplot == 311:\n ax.legend(loc=1, prop=dict(size=14))\n\n ax.set_xlabel('$\\lambda\\ (\\AA)$')\n ax.set_ylabel('normalized flux')\n\nplt.show()\n```\n", "meta": {"hexsha": "8868c9fd15d720b087ad168f364bd5707f399c01", "size": 328775, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "lectures/notes/Lecture4-dimensionality-reduction-2.ipynb", "max_stars_repo_name": "uw-astro/astr-598a-win22", "max_stars_repo_head_hexsha": "65e0f366e164c276f1dfc06873741c6f6c94b300", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 29, "max_stars_repo_stars_event_min_datetime": "2018-01-03T20:41:12.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-12T15:07:00.000Z", "max_issues_repo_path": "lectures/notes/Lecture4-dimensionality-reduction-2.ipynb", "max_issues_repo_name": "uw-astro/astr-598a-win22", "max_issues_repo_head_hexsha": "65e0f366e164c276f1dfc06873741c6f6c94b300", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2018-01-12T03:38:54.000Z", "max_issues_repo_issues_event_max_datetime": "2018-03-16T02:57:16.000Z", "max_forks_repo_path": "lectures/Week-7-Tue.ipynb", "max_forks_repo_name": "dirac-institute/uw-astr598-w18", "max_forks_repo_head_hexsha": "895cd7195ebeaa06cc425b4de730204316c9b3bf", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 19, "max_forks_repo_forks_event_min_datetime": "2018-01-03T20:41:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-17T11:13:50.000Z", "avg_line_length": 427.5357607282, "max_line_length": 109678, "alphanum_fraction": 0.9226401034, "converted": true, "num_tokens": 4094, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.91610961358942, "lm_q2_score": 0.9416541544761566, "lm_q1q2_score": 0.8626584235920238}} {"text": "

Math 267 Project #2\n\n---\n\nSolution notebook\n---\n\n## Euler's method for system of odes.\n\nWe consider the first-order autonomous system \n\n\n$$ x'(t) = f (x, y)$$\n$$ y'(t) = g(x, y) $$\nalong with the initial conditions\n\n$$x(t_0) = x_0 $$\n$$y(t_0) = y_0 $$\n\nNotice that for the autonomous system t is not present in the slope functions f and g. The vector valued function $ F = (f (x, y), g(x, y))$ is called a vector field. We calculate the Euler approximation for this system by iterating the formulas\n\n$$ t_{n+1} =t_n + Δt $$\n$$ x_{n+1} =x_n + f(x_n, y_n) \\Delta t$$\n$$ y_{n+1} = y_n + g(x_n, y_n) \\Delta t$$\n\n---\n\n## Exercise 1. We will demonstrate how Euler's method can be used to solve the predator prey model and graph your results. The model is below.\n\n$$x' = -0.1 x + 0.02 x y $$\n$$y' = 0.2 y - 0.025xy$$\n$$ x(0) = y(0) =6 $$\n\nNote that x(t) represents the fox population at time t and y(t) represents the rabbit population. The populations are measured in thousands. Please see problem 3.3.11 in your text.\n\n### Execute the cell below to import the necessary libraries\n\n\n```python\n# import libraries\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n# uncomment the line below if you are running a macbook\n\n%config InlineBackend.figure_format ='retina'\n```\n\n

The python code to numerically solve the above system is in the cell below. Read the code and understand each instruction.\n Afterwards execute the cell.\n\n\n```python\n# define the slope functions\n\ndef f(x,y):\n return -0.1*x + 0.02*x*y\n\ndef g(x,y):\n return 0.2*y - 0.025*x*y\n\n\nh = 0.1 # set delta t\nt = np.arange(0,100,h)\n\n# Initialeze arrays to store the results.\n\nx = np.zeros_like(t)\ny = np.zeros_like(t)\n\n# Set initial conditions:\n\nx[0] = y[0] = 6\n\n# implement Euler's method\n\nfor i in range (len(t)-1):\n x[i+1] = x[i] + f(x[i],y[i]) * h\n y[i+1] = y[i] + g(x[i],y[i]) * h\n \n \n\n```\n\n### Execute the cell below to graph your results.\nYou should note that the populations are changing periodically\n\n\n```python\nplt.figure(figsize=(8,5))\nplt.plot(t,x,label='foxes')\nplt.plot(t,y,label='rabbits')\nplt.legend()\nplt.grid()\nplt.xlabel('time')\nplt.ylabel('population');\n```\n\n### Execute the cell below to see the trajectory in the phase plane for this problem. See chapter 10 in the text for more details on phase potraits.\n\n\n```python\nplt.figure(figsize=(8,5))\nplt.plot(x,y,linewidth=2)\nplt.xlim(-2,12)\nplt.ylim(-2,12)\nplt.grid()\nplt.xlabel('foxes')\nplt.ylabel('rabbits');\n```\n\n---\n## Exercise 2. Improved Euler’s Method for Systems\n\n\nFrom the discussion above we can readily see how to apply the Improved Euler’s method to the first order autonomous system of equations. All that is required is that we iterate the following formulas.\n\n$$t_{n+1} =t_n + Δt$$\n$$F1 =f(x_n,y_n)$$\n$$G1 = g(x_n, y_n)$$\n$$F2 =f(x_n +F1*Δt, y_n +G1*Δt)$$ \n$$G2 =g(x_n +F1*Δt, y_n +G1*Δt)$$\n$$x_{n+1} =x_n + (F1 +F2)/2*Δt$$\n$$y_{n+1} =y_n +(G1 + G2)/2*Δt$$\n\nRedo the exercise above now using the improved Euler's method. With the improved method h = 1 will work and you only need to compute 100 values. So the following command will create your t array. Cut and past the cells above to recreate the plots. You will know your solution is correct if your phase potrait shows a closed loop instead of a spiral.\n\n```python\nt = np.arange(0,100,1.0)\n\n```\n\n## Improved Euler Method\n\n\n```python\n# define the slope functions\n\ndef f(x,y):\n return -0.1*x + 0.02*x*y\n\ndef g(x,y):\n return 0.2*y - 0.025*x*y\n\n\nh = 1.0 # set delta t\nt = np.arange(0,100,h)\n\n# Initialeze arrays to store the results.\n\nx = np.zeros_like(t)\ny = np.zeros_like(t)\n\n# Set initial conditions:\n\nx[0] = y[0] = 6\n\n# implement Euler's method\n\nfor i in range (len(t)-1):\n \n F1 = f(x[i],y[i])\n G1 = g(x[i],y[i])\n \n F2 = f(x[i]+F1*h,y[i]+G1*h)\n G2 = g(x[i]+F1*h,y[i]+G1*h)\n \n slope1 = (F1+F2)/2\n slope2 = (G1+G2)/2\n \n x[i+1] = x[i] + slope1 * h\n y[i+1] = y[i] + slope2 * h\n \n \n\n```\n\n\n```python\nplt.figure(figsize=(8,5))\nplt.plot(t,x,label='foxes')\nplt.plot(t,y,label='rabbits')\nplt.legend()\nplt.grid()\nplt.xlabel('time')\nplt.ylabel('population');\n```\n\n\n```python\nplt.figure(figsize=(8,5))\nplt.plot(x,y,linewidth=2)\nplt.xlim(-2,12)\nplt.ylim(-2,12)\nplt.grid()\nplt.xlabel('foxes')\nplt.ylabel('rabbits');\nplt.plot(6,6,'o',label=\"initial condition\")\nplt.legend()\n```\n\n---\n### Answer the questions below. Edit the cell and enter your answers.\n---\n\n1. The popuation for the foxes is periodic. Determine the period.\n\n2. Find the value of t for t>0 where the populations are first equal.\n\n3. Find all equilibrium solutions for the predator prey model. Hint: set the vector field equation to zero and solve for x and y. There are two equilibrium solutions ( points in the plane where the \"cork\" will not move.)\n\n\n### 1. Find the period.\n\n\n```python\nvals=np.sort(x)[-2:] # find the two peak values\na=np.where(x==vals[0]) # find location of these peaks\nb=np.where(x==vals[1])\nperiod = int(abs(a[0]-b[0]))\n\nprint(f\"The period for the population is {period}.\")\n```\n\n The period for the population is 45.\n\n\n### 2. Find when the populations are equal.\n\n\n```python\nval=np.argmin(abs((x-y))[1:20])\nprint(f\" The populations are first equal for t>0 at t={val+1}.\")\n\n```\n\n The populations are first equal for t>0 at t=6.\n\n\n### 3. Find the equilibrium points.\n\nWe use sympy to solve the nonlinear system. For documentation on sympy go to https://docs.sympy.org/latest/index.html\n\nBelow we show the two equilbrium points are $$(0,0)\\; \\text {and}\\; (8,5).$$\n\n\n```python\nimport sympy as sym\nsym.init_printing() \n\nx,y = sym.symbols('x,y')\neq1 = sym.Eq(-0.1*x + 0.02*x*y,0)\neq2 = sym.Eq(0.2*y - 0.025*x*y,0)\nresult = sym.solve([eq1,eq2],(x,y))\nprint(result)\n```\n\n [(0.0, 0.0), (8.00000000000000, 5.00000000000000)]\n\n", "meta": {"hexsha": "39c36d72c2a6b7f00658688a100fba4863659e19", "size": 135077, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Project#2_solution.ipynb", "max_stars_repo_name": "rmartin977/math---267-Spring-2022", "max_stars_repo_head_hexsha": "828fce843795318fb1ec32e4dd073b67861e06cf", "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": "Project#2_solution.ipynb", "max_issues_repo_name": "rmartin977/math---267-Spring-2022", "max_issues_repo_head_hexsha": "828fce843795318fb1ec32e4dd073b67861e06cf", "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": "Project#2_solution.ipynb", "max_forks_repo_name": "rmartin977/math---267-Spring-2022", "max_forks_repo_head_hexsha": "828fce843795318fb1ec32e4dd073b67861e06cf", "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": 261.2707930368, "max_line_length": 35244, "alphanum_fraction": 0.9231697476, "converted": true, "num_tokens": 1849, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.933430805473952, "lm_q2_score": 0.9241418205010699, "lm_q1q2_score": 0.862622443882478}} {"text": "# Python Lecture 1: On Numbers, Variables, and Functions\n\n### Lecture Notes by Jakov Ivan S. Dumbrique (jdumbrique@ateneo.edu)\n\nMATH 100.2: Topics in Financial Mathematics II \\\nFirst Semester, S.Y. 2021-2022 \\\nAteneo de Manila University\n\nToday, we will learn four topics in Python:\n\n0. How to put comments in your code\n1. Numbers\n2. Variables\n3. Functions\n\n## Section 0: Comments in Python\n\nWhile your machine's Python compiler will skip comments when it encounters comments, writing comments in your code is still important in order to make your code readable by humans (and your future self).\n\n\n```python\n# Single line comments start with a number symbol.\n\"\"\"\n Multiline strings can be written using three \"s, and are often used as documentation.\n\"\"\"\n \n```\n\n## Section 1: Numbers\n\nNumbers are a primitive datatype in Python. Numbers can either be integers (int) or float.\n\n\n```python\n# You have numbers\n3 # => 3\n\n# Math operations are what you would expect\n1 + 1 # => 2\n8 - 1 # => 7\n10 * 2 # => 20\n35 / 5 # => 7.0\n\n# Integer division rounds down for both positive and negative numbers.\n5 // 3 # => 1\n-5 // 3 # => -2\n5.0 // 3.0 # => 1.0 # works on floats too\n-5.0 // 3.0 # => -2.0\n\n# The result of division is always a float\n10.0 / 3 # => 3.3333333333333335\n\n# Modulo operation\n7 % 3 # => 1\n\n# Exponentiation (x**y, x to the yth power)\n2**3 # => 8\n\n# Enforce precedence with parentheses\n1 + 3 * 2 # => 7\n(1 + 3) * 2 # => 8\n```\n\n\n\n\n 8\n\n\n\n\n```python\n# Comparison operators\n\n# to check equality\n1 == 1 # => True\n1 == 1.0 # => True\n\n# to check inequality\n(3 - 2) != 0 # => True\n\n# other comparison operators\n(3 - 2) > 1 # => False\n(3 - 2) >= 1 # => True\n(3 ** 2) + (4 ** 2) < 5 ** 2 # => False\n(3 ** 2) + (4 ** 2) <= 5 ** 2 # => True\n```\n\n\n\n\n True\n\n\n\n

Definition: Simple Interest

\n\nSuppose that an amount $P$ is invested for $T$ years at an interest rate of $r$ per annum (p.a.). If the interest rate is a **simple rate**, then the terminal value of the investment is\n\\begin{align}\n A &= P + \\underbrace{Pr + Pr + \\cdots + Pr}_{T \\text{ years}} \\nonumber \\\\\n &= P(1 + \\underbrace{r + \\cdots + r}_{T \\text{ years}}) \\nonumber \\\\\n &= P(1+rT). \\label{Simple Interest}\n\\end{align}\n\n

Example 1

\n\nSuppose that $\\$408$ is deposited in a newly created savings account that pays a simple interest of $3.435\\%$ per annum. If no deposits or withdrawals are made on the account since the aforementioned transaction, how much is withdrawn if the account is closed and emptied in $6$ months?\n\n$A = \\$408\\left[1+ 3.435\\% \\left(\\dfrac{6}{12}\\right)\\right] \\approx \\boxed{\\$415.01}.$\n\n\n```python\n408*(1+0.03435*(6/12))\n```\n\n\n\n\n 415.00739999999996\n\n\n\n## Section 2: Variables\n\nVariables provide a way to associate names with Python objects. We use variables in order to reuse names instead of writing explicitly the values repeatedly. \n\nWe use an equal sign (=) to assign a value to a variable.\n\n\n```python\npi = 3.14159\n```\n\n\n```python\npi\n```\n\n\n\n\n 3.14159\n\n\n\nVariable names\n1. Can contain uppercase and lowercase letters, digits (but they cannot start with a digit), and the special character _\n2. Are case-sensitive! (pi is different from Pi)\n3. Cannot be [Python reserved words (or keywords)](https://www.w3schools.com/python/python_ref_keywords.asp)\n\n\n

Example 2: Assign variables to Example 1

\n\nSuppose that $\\$408$ is deposited in a newly created savings account that pays a simple interest of $3.435\\%$ per annum. If no deposits or withdrawals are made on the account since the aforementioned transaction, how much is withdrawn if the account is closed and emptied in $6$ months?\n\n\n```python\nP = 408\nr = 0.03435\nT = 6/12\n\nP * (1 + r*T)\n```\n\n\n\n\n 415.00739999999996\n\n\n\n## Section 3: Functions\n\n1. if you will reuse a piece of code, you should write a function for it\n2. functions are not run in a program until they are “called” or “invoked” in a program\n3. characteristics of a function:\n - has a name\n - has parameters (0 or more)\n - has a docstring (optional but recommended)\n - has a body\n - returns something\n\n

Example 3: Write a function for Example 2

\n\nSuppose that $\\$408$ is deposited in a newly created savings account that pays a simple interest of $3.435\\%$ per annum. If no deposits or withdrawals are made on the account since the aforementioned transaction, how much is withdrawn if the account is closed and emptied in $6$ months?\n\n\n```python\ndef get_future_value_simple(P, r, T):\n \"\"\"\n Input: principal P, simple interest rate r p.a., investment time period T in years\n Returns the future value of a principal P invested for T years at a simple rate r\n \"\"\"\n return P * (1 + r*T)\n```\n\n\n```python\nget_future_value_simple(408, 0.03435, 0.5)\n```\n\n\n\n\n 415.00739999999996\n\n\n\n\n```python\nget_future_value_simple(P=408, r=0.03435, T=0.5)\n```\n\n\n\n\n 415.00739999999996\n\n\n\n\n```python\nP = 408\nr = 0.03435\nT = 6/12\nget_future_value_simple(P, r, T)\n```\n\n\n\n\n 415.00739999999996\n\n\n\nTip: use functions if you will reuse a chunck of code. Think of a function as a black box that hides tedious coding details.\n\n\n

Example 4: Reusing Functions

\n\nSuppose you invest $\\$500$ in an account that pays a simple interest of $5.75\\%$ p.a. How much will it be worth in $1.5$ years? $20$ years?\n\n\n```python\nget_future_value_simple(P=500, r=0.0575, T=1.5)\n```\n\n\n\n\n 543.125\n\n\n\n\n```python\nget_future_value_simple(P=500, r=0.0575, T=20)\n```\n\n\n\n\n 1075.0000000000002\n\n\n\n

Definition: Compound Interest

\n\nSuppose that an amount $P$ is invested for $T$ years at an interest rate of $r$ per annum (p.a.). If the interest rate is **compounded** $\\boldsymbol{m}$ **times a year**, then the terminal value of the investment is\n\\begin{align}\n A = P\\left(1+\\dfrac{r}{m}\\right)^{mT}. \\label{Compounding Interest}\n\\end{align}\n\n

Exercise

\n\nSuppose you invest $\\$500$ in an account that pays a compound interest of $5.75\\%$ p.a. How much will it be worth in $1.5$ years if the interest rate is \n1. compounded annually?\n2. compounded semiannually? \n3. compounded quarterly?\n4. compounded monthly?\n\nWrite a function and reuse that function to answer the above question.\n\n\n```python\ndef get_future_value_comp(P, r, m, T):\n \"\"\"\n Input: principal P, interest rate r p.a. compounded m times a year, investment time period T in years\n Returns the future value of a principal P invested for T years at an \n interest rate r p.a. compounded m times a year\n \"\"\"\n return P * (1 + r/m)**(m*T)\n```\n\n\n```python\nP = 500\nr = 0.0575\nT = 1.5\nget_future_value_comp(P, r, 1, T)\n```\n\n\n\n\n 543.739105494308\n\n\n\n\n```python\nget_future_value_comp(P, r, 2, T)\n```\n\n\n\n\n 544.3767255859376\n\n\n\n\n```python\nget_future_value_comp(P, r, 4, T)\n```\n\n\n\n\n 544.7048313758173\n\n\n\n\n```python\nget_future_value_comp(P, r, 12, T)\n```\n\n\n\n\n 544.9271497450427\n\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "971c8a6299de1d527359e13c1dd4cad88f5661b0", "size": 15004, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "lectures/0Python/20210831_NumbersVariablesFunctions.ipynb", "max_stars_repo_name": "ateneomathdept/math100.2_2021Sem1", "max_stars_repo_head_hexsha": "ac51a30e25d57a50ef8aa25fcfc0db64da0641b9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-12-12T04:44:09.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-12T04:44:09.000Z", "max_issues_repo_path": "lectures/0Python/20210831_NumbersVariablesFunctions.ipynb", "max_issues_repo_name": "ateneomathdept/math100.2_2021Sem1", "max_issues_repo_head_hexsha": "ac51a30e25d57a50ef8aa25fcfc0db64da0641b9", "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/0Python/20210831_NumbersVariablesFunctions.ipynb", "max_forks_repo_name": "ateneomathdept/math100.2_2021Sem1", "max_forks_repo_head_hexsha": "ac51a30e25d57a50ef8aa25fcfc0db64da0641b9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-10-04T04:16:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-04T04:16:18.000Z", "avg_line_length": 24.4763458401, "max_line_length": 297, "alphanum_fraction": 0.5229938683, "converted": true, "num_tokens": 2119, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797075998822, "lm_q2_score": 0.9465966735899122, "lm_q1q2_score": 0.8625196802566774}} {"text": "# Lab 3\n## Introduction\nIn this lab we will analyse population dynamics under the logisitic model with managed harvesting.\n\nFirst import the modules we need.\n\n\n```python\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport pandas as pd\nfrom numpy import meshgrid, linspace, sqrt, arange\nfrom scipy.integrate import odeint\n```\n\n## Harvesting of fish\nA population of fish in a lake, left to its own devices, is modelled by the logistic differential equation\n\\begin{align}\n\\frac{\\mathrm{d}y}{\\mathrm{d}{t}} = 4y(1-y),\n\\end{align}\nwhere the population $y$ is in units of thousands of fish and time $t$ is measured in years.\n\nFirst define a function for $\\mathrm{d}y/\\mathrm{d}x$ in terms of $y$ and $x$.\n\n\n```python\ndef diff_eq(y, x):\n return 4 * y * (1 - y)\n```\n\nNext define a function that creates a Plotly Figure object that contains a slope field and, optionally, a few solutions to initial value problems.\n\nIt automates a few things we did in the last lab.\n\n- `diff_eq` is the differential equation to be plotted\n- `x` and `y` should be outputs from `meshgrid`. \n- `args` is any additional arguments to `diff_eq` (we will use that below).\n- `initial_values` is a list (or array) of starting $y$ values from which approximate solutions will start. The corresponding $x$ value is the minimum element of `x`.\n\nNote that the numerical solutions will plotted for the whole range of $x$ values in `x`, so if they blow up you will probably get a warning and less-than-useful plot.\n\n\n```python\ndef create_slope_field(diff_eq, x, y, args=(), initial_values=()): \n S = diff_eq(y, x, *args)\n L = sqrt(1 + S**2)\n fig, ax = plt.subplots(figsize=(5, 5))\n q = ax.quiver(x, y, 1/L, S/L, scale=25, headwidth=0, headlength=0, color='grey')\n x = linspace(x.min(), x.max())\n data = {'x': x}\n for y0 in initial_values:\n y = odeint(diff_eq, y0, x, args)[:,0]\n data[f'y({x[0]}) = {y0}'] = y\n data = pd.DataFrame(data)\n data = data.melt(id_vars=['x'], value_name='y', var_name='initial value')\n sns.lineplot(data=data, x='x', y='y', hue='initial value')\n return fig, ax\n```\n\nThe slope field below should hopefully give you some idea for the fish population dynamics.\n\nNote that we use `arange` rather than `linspace` this week so that we can carefully control the increments between our grid points. `arange(0, 1.1, 0.25)` returns an array that starts with 0 and increments by 0.25 until it exceeds 1.1.\n\nThe plot also contains the solution curves for \n$y(0) = 1$ and $y(0) = 0.4$. Edit the cell to also include the solution curve for $y(0)=1.4$.\n\n\n```python\nx, y = meshgrid(arange(0, 1.1, 0.05), arange(-0.4, 1.41, 0.05))\nfig, ax = create_slope_field(diff_eq, x, y, initial_values=(0.4, 1))\n```\n\n### Equilibrium solutions\nLooking back to our differential equation, $\\mathrm{d}y/\\mathrm{d}t = 0$ when $y(t) = 0$ or $y(t) = 1$. Looking at the slope field, we see that the equilibrium solution $y(t) = 1$ is stable (this is the carrying capacity here, corresponding to 1000 fish), whereas the equilibrium solution $y(t) = 0$ is unstable. Any non-zero initial population will eventually stabilise at 1000 fish.\n\n### What will happen if harvesting is now commenced at a steady rate?\nFor the simplest harvesting model, assume that $H$ units (thousands) of fish are taken\ncontinuously (smoothly) over the year, rather than at one instant each year.\nNote that the units of $H$ are the same as those of $\\mathrm{d}y/\\mathrm{d}t$, thousands of fish per year, so we simply subtract $H$ from the RHS of our existing equation to give the DE with harvesting as\n\\begin{align}\n\\frac{\\mathrm{d}y}{\\mathrm{d}{t}} = 4y(1-y) - H.\n\\end{align}\nAgain, the (constant) equilibrium solutions are found by setting $\\mathrm{d}y/\\mathrm{d}t = 0$, giving from the quadratic formula (check this),\n\\begin{align}\ny(t) = \\frac{4\\pm\\sqrt{16-16H}}{8} = \\frac{1\\pm\\sqrt{1-H}}{2}.\n\\end{align}\nWhat happens after harvesting starts will depend on the equilibrium solutions, their\nstability and the initial number of fish $y(0)$.\n\nStart by redefining `diff_eq` to include the `H` parameter. Note that defining `diff_eq` again overides our original definition.\n\n\n```python\ndef diff_eq(y, x, H=0):\n return 4 * y * (1 - y) - H\n```\n\nNow set $H = 0.6$ and plot the slope field. This is done by setting `args=(0.6,)` when we call `create_slope_field`. This is exactly how you would pass additional arguments like this one to `odeint` if you were calling it directly.\n\n\n```python\nx, y = meshgrid(arange(0, 1.1, 0.05), arange(-0.4, 1.41, 0.05))\nfig, ax = create_slope_field(diff_eq, x, y, args=(0.6,))\n```\n\nFrom the solutions to the quadratic equation above, the equilibrium solutions of the DE are found to be $y(t) \\approx 0.184$ and $y(t) \\approx 0.816$. The previous equilibrium solution with no harvesting at $y(t) = 0$ has moved up to $y(t) \\approx 0.184$, while the previous equilibrium solution with no harvesting at $y(t) = 1$ has moved down to $y(t) \\approx 0.816$.\n\nFrom the slope field, we see that the equilibrium solution $y(t) \\approx 0.184$ is unstable, whereas the equilibrium solution $y(t) \\approx 0.816$ is stable. If the population ever falls below about 0.184, or 184 fish, it will then drop to 0. This is a new feature, introduced by harvesting.\n\nIn the cell below, use `create_slope_field` to experiment by plotting the solutions to the initial value problems $y(0)=0.183$ and $y(0)=0.25$. Extend the $x$ range of your slope field until the top line is close to equlibrium. Note that if you extend it too far you will break `odeint` (why?). You may also like to increase the increments in `arange` to make the plot clearer.\n\n\n```python\n\n```\n\n## Exercises\n\nIn the following questions we will experiment with how different levels of harvesting affect outcomes for the fish population.\n\nThis week the questions will be a combination of plots and written answers. Written answers go in blank cells, but if a cell says \"Type _Markdown_ and LaTeX: $\\alpha^2$\", you should double-click on it to edit it.\n\n1. Assume that the harvest is now 600 fish per year. **On the same figure,** \n a. plot the slope field, \n b. plot the equilibrium solutions that we found in above, and \n c. plot the solution curves for $y(0)=1$, $y(0)=0.3$, and $y(0)=0.15$.\n\n\n```python\n\n```\n\n1. d. In the cell below, describe the behaviour of the fish population for each of these five initial numbers of fish.\n\n\n\n2. a. i. Assume that $H=0.8$. Plot the slope field and five solutions, one for each equilibrium solution and one for each region between, above, or below them. You can use the equation from the lab to calculate the equilibrium solutions.\n\n\n```python\n\n```\n\n2. a. ii. In the cell below, describe the limiting behaviour of each line.\n\n\n\n2. b. i. Assume that $H=1$. Plot the slope field and three solutions for the equilibrium solution and the regions above and below it.\n\n\n```python\n\n```\n\n2. b. ii. Describe the limiting behaviour of each line.\n\n\n\n2. c. i. Assume that 𝐻=1.2. Plot the slope field and two or three solutions.\n\n\n```python\n\n```\n\n2. c. iii. Describe the limiting behaviour of the lines.\n\n\n\n3. Use `sns.lineplot` to plot a bifurcation graph showing the reulationship between $H$ and the locations of the critical points $c$. $H$ should go on the horizontal axis but you may find it easier to calculate $H$ in terms of $c$ by rewriting the above equations giving the equilibrium solutions. \n\n Hint: your plots won't work unless you add `sort=False` as a keyword argument to `sns.lineplot`, and you may observe some artifacts in your plot unless you also set `estimator=None`.\n\n\n```python\n\n```\n\n4. Summarize what happens to the equilibrium solutions and their stability as $H$\nis increased from 0 to beyond 1. Refer to your plots to support your answers.\n\n\n\n5. What is a reasonable strategy for sustainable fishing in this case?\nDon’t forget to allow qualitatively for minor catastrophes, such as disease or temporary overfishing.\n\n\n", "meta": {"hexsha": "56a75973fe37659f4f7bfeb52fbc342c8f76c929", "size": 15864, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/lab-03.ipynb", "max_stars_repo_name": "BenKaehler/mm-labs", "max_stars_repo_head_hexsha": "5409ba7f6a4d4edb802c96e4bfc47e477fc84329", "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": "notebooks/lab-03.ipynb", "max_issues_repo_name": "BenKaehler/mm-labs", "max_issues_repo_head_hexsha": "5409ba7f6a4d4edb802c96e4bfc47e477fc84329", "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": "notebooks/lab-03.ipynb", "max_forks_repo_name": "BenKaehler/mm-labs", "max_forks_repo_head_hexsha": "5409ba7f6a4d4edb802c96e4bfc47e477fc84329", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 15, "max_forks_repo_forks_event_min_datetime": "2020-07-27T06:33:02.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-27T07:30:41.000Z", "avg_line_length": 29.3234750462, "max_line_length": 395, "alphanum_fraction": 0.5788577912, "converted": true, "num_tokens": 2196, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391685381605, "lm_q2_score": 0.9343951698485602, "lm_q1q2_score": 0.8624833406630883}} {"text": "```python\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n```\n\n## Curve fitting\n\n\\begin{equation}\nRMSE=\\sqrt{\\frac{1}{n}\\sum{(y-\\hat{y})^2}}\\\\\nR^2=1-\\frac{\\sum{(y-\\hat{y})^2}}{\\sum{(y-\\bar{y})^2}}\n\\end{equation}\n\n## Example:\n\n### 1.Fit gas equation\n\\begin{equation}\nPV^\\gamma=constant(K)\\\\\nlogP=logK-\\gamma logV\\\\\ny=a+bx\n\\end{equation}\n\n\n```python\ndf = pd.read_excel('data/gas.xlsx')\ndf\n```\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
volume(cm3)pressure(gm/cm2)
054.361.2
161.849.2
272.437.6
388.728.4
4118.619.2
5194.010.1
\n
\n\n\n\n\n```python\nplt.figure(figsize = [6,6])\nplt.scatter(df['volume(cm3)'],df['pressure(gm/cm2)'])\nplt.xlabel('volume(cm3)')\nplt.ylabel('pressure(gm/cm2)')\nplt.title('Gas')\nplt.show()\n```\n\n\n```python\nn=6\nx=np.log(df['volume(cm3)'])\ny=np.log(df['pressure(gm/cm2)'])\nz=np.polyfit(x, y, 1) # linear fit =y=a+bx\np=np.poly1d(z) # [a,b]\ney=p(x) # expected value\na=\"{:.3}\".format(p[0])\nb=\"{:.3}\".format(p[1])\nK=np.exp(p[0])\ngamma=p[1]\n\nRMSE=np.sqrt(np.sum((y-ey)**2)/n)\nR_square=1-(np.sum(np.sum(np.sum((y-ey)**2))/np.sum((y-np.mean(y))**2)))\nrmse=\"{:.2}\".format(RMSE)\nr2=\"{:.2}\".format(R_square)\n\n\nplt.figure(figsize = [6,6])\nplt.plot(x, y, 'ro',label='observed')\nplt.plot(x, ey, 'b-',label='fitted, a= '+str(a)+', b='+str(b))\nplt.xlabel('log(V)')\nplt.ylabel('log(P)')\nplt.figtext(0.2, 0.3, 'RMSE = '+str(rmse)+',r2='+str(r2))\nplt.legend()\nplt.title('Fitted curve')\nplt.show()\nprint('gamma =',\"{:.2}\".format(-gamma))\nprint('K=',\"{:.2}\".format(K))\n\n```\n\n### 2.Fit \n\\begin{equation}\nf(\\theta)=A+B\\cos\\theta+C\\cos^2\\theta\\\\\ny=A+Bx+Cx^2\n\\end{equation}\n\n\n```python\ndf1 = pd.read_excel('data/scattering.xlsx')\ndf1\n```\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
theta(degree)f(theta)
03011
14513
29016
312017
415014
\n
\n\n\n\n\n```python\nplt.figure(figsize = [6,6])\nplt.scatter(df1['theta(degree)'],df1['f(theta)'])\nplt.xlabel(r'$\\theta$(degree)')\nplt.ylabel(r'f($\\theta$)')\nplt.title('Scattering')\nplt.show()\n```\n\n\n```python\nn1=5\nx1=np.cos(df1['theta(degree)']*np.pi/180)\ny1=df1['f(theta)']\nz1=np.polyfit(x1, y1, 2) # second order fit y=a+bx+cx2\np1=np.poly1d(z1) # [c,b,a]\ney1=p1(x1) #expected value\nA=\"{:.3}\".format(p1[0])\nB=\"{:.3}\".format(p1[1])\nC=\"{:.3}\".format(p1[2])\n\n\nRMSE1=np.sqrt(np.sum((y1-ey1)**2)/n1)\nR_square1=1-(np.sum(np.sum(np.sum((y1-ey1)**2))/np.sum((y1-np.mean(y1))**2)))\nrmse1=\"{:.2}\".format(RMSE1)\nr21=\"{:.2}\".format(R_square1)\n\n\nplt.figure(figsize = [6,6])\nplt.plot(x1, y1, 'ro',label='observed')\nplt.plot(x1, ey1, 'b-',label='fitted, A= '+str(A)+', B='+str(B)+',C='+str(C))\nplt.xlabel(r'cos($\\theta$)')\nplt.ylabel(r'f($\\theta$)')\nplt.figtext(0.2, 0.3, 'RMSE = '+str(rmse1)+',r2='+str(r21))\nplt.legend()\nplt.title('Fitted curve')\nplt.show()\n\n```\n\n### 3.Determination of decay conctant and half life\n\\begin{equation}\nN=N_0~e^{-\\lambda~t}\\\\\nlogN=logN_0-\\lambda~t\\\\\ny=A+BX\n\\end{equation}\n\n\n```python\ndf2 = pd.read_excel('data/env-dec.xlsx')\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
t [s]N [s-1]
0032
1528
21029
31528
42025
.........
783901
793951
804002
814052
824101
\n

83 rows × 2 columns

\n
\n\n\n\n\n```python\nplt.figure(figsize = [6,6])\nplt.scatter(df2['t [s]'],df2['N [s-1]'])\nplt.xlabel('time(s)')\nplt.ylabel('Count($s^{-1}$)')\nplt.title('Decay curve')\nplt.show()\n```\n\n\n```python\nn2=83\nx2=df2['t [s]']\ny2=np.log(df2['N [s-1]'])\nz2=np.polyfit(x2, y2, 1) # second order fit y=a+bx\np2=np.poly1d(z2) # [c,b,a]\ney2=p2(x2) #expected value\nA1=\"{:.3}\".format(p2[0])\nB1=\"{:.3}\".format(-p2[1])\n\n\nRMSE2=np.sqrt(np.sum((y2-ey2)**2)/n2)\nR_square2=1-(np.sum(np.sum(np.sum((y2-ey2)**2))/np.sum((y2-np.mean(y2))**2)))\nrmse2=\"{:.2}\".format(RMSE2)\nr22=\"{:.2}\".format(R_square2)\n\n\nplt.figure(figsize = [6,6])\nplt.plot(x2, y2, 'ro',label='observed')\nplt.plot(x2, ey2, 'b-',label='fitted, A= '+str(A1)+', B='+str(B1))\nplt.xlabel('time(sec)')\nplt.ylabel('ln(A)')\nplt.figtext(0.2, 0.3, 'RMSE = '+str(rmse2)+',r2='+str(r22))\nplt.legend()\nplt.title('Fitted curve')\nplt.show()\n```\n\n\n```python\nprint('decay constant =%0.6f /sec'%-p2[1])\n```\n\n decay constant =0.008246 /sec\n\n\n\n```python\nT=-0.693/p2[1]\nprint('half life = %0.2f sec'%T)\n```\n\n half life = 84.04 sec\n\n\n### 4.Absorption of coefficient\n\\begin{equation}\nN=N_0~e^{-\\mu~x}\\\\\nlogN=logN_0-\\mu~x\\\\\ny=A+BX\n\\end{equation}\n\n\n```python\ndf3 = pd.read_excel('data/env-beta.xlsx')\ndf3\n```\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
nN [s-1]
008.0
116.0
225.0
334.0
443.0
552.0
662.0
772.0
882.0
991.0
10101.0
11111.0
12120.5
13130.5
14140.5
15150.5
16161.0
17170.5
18180.4
19190.3
20200.1
\n
\n\n\n\n\n```python\nplt.figure(figsize = [6,6])\nplt.scatter(0.03*df3['n'],df3['N [s-1]'])# one sheet of Al is 0.03 mm thick\nplt.xlabel('Thickness(mm)')\nplt.ylabel('Count($s^{-1}$)')\nplt.title('Absorption curve')\nplt.show()\n```\n\n\n```python\nn3=20\nx3=0.03*df3['n']\ny3=np.log(df3['N [s-1]'])\nz3=np.polyfit(x3, y3, 1) # second order fit y=a+bx\np3=np.poly1d(z3) # [c,b,a]\ney3=p3(x3) #expected value\nA2=\"{:.3}\".format(p3[0])\nB2=\"{:.3}\".format(-p3[1])\n\n\nRMSE3=np.sqrt(np.sum((y3-ey3)**2)/n3)\nR_square3=1-(np.sum(np.sum(np.sum((y3-ey3)**2))/np.sum((y3-np.mean(y2))**2)))\nrmse3=\"{:.2}\".format(RMSE3)\nr23=\"{:.2}\".format(R_square3)\n\n\nplt.figure(figsize = [6,6])\nplt.plot(x3, y3, 'ro',label='observed')\nplt.plot(x3, ey3, 'b-',label='fitted, A= '+str(A2)+', B='+str(B2))\nplt.xlabel('Thickness(mm)')\nplt.ylabel('ln(N)')\nplt.figtext(0.2, 0.3, 'RMSE = '+str(rmse3)+',r2='+str(r23))\nplt.legend()\nplt.title('Fitted curve')\nplt.show()\n```\n\n\n```python\nprint('absorption coefficient =%0.3f /mm'%-p3[1])\n```\n\n absorption coefficient =5.695 /mm\n\n\n\n```python\ndensity=2.7 # in cgs\nmu_m=-10*p3[1]/density # in cgs\nprint('mass absorption coefficient =%0.3f sq.cm/gm'%mu_m)\n```\n\n mass absorption coefficient =21.091 sq.cm/gm\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "104efcbb3a2897b7cd178c9873ddd8077183f565", "size": 155433, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "PMS_curve.ipynb", "max_stars_repo_name": "joshidot/NPS", "max_stars_repo_head_hexsha": "0b5b7dde9b5a9769c8a437d193b210545f9344ca", "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": "PMS_curve.ipynb", "max_issues_repo_name": "joshidot/NPS", "max_issues_repo_head_hexsha": "0b5b7dde9b5a9769c8a437d193b210545f9344ca", "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": "PMS_curve.ipynb", "max_forks_repo_name": "joshidot/NPS", "max_forks_repo_head_hexsha": "0b5b7dde9b5a9769c8a437d193b210545f9344ca", "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": 163.4416403785, "max_line_length": 24912, "alphanum_fraction": 0.8779474114, "converted": true, "num_tokens": 3999, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9653811651448431, "lm_q2_score": 0.8933094096048377, "lm_q1q2_score": 0.8623840786791701}} {"text": "```python\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport plotutils as pu\nfrom sympy import *\n%matplotlib inline\n```\n\nWe add vectors to get $v + w$. We multiply them by numbers $c$ and $d$ to get $cv$ and $dw$. Combining those two operations (adding $cw$ to $dw$) gives the **linear combination** $cv + dw$.\n\n$$cv + dw = c\\begin{bmatrix}1\\\\1\\end{bmatrix} + d\\begin{bmatrix}2\\\\3\\end{bmatrix} = \\begin{bmatrix}c + 2d\\\\c + 3d\\end{bmatrix}$$\n\nWe can also write a column vector *inline* as $w = (2, 3)$ but that is not the same as the row vector $\\begin{bmatrix}2 & 3\\end{bmatrix}$.\n\n\n```python\nfix, axes = plt.subplots(1, figsize=(3, 3))\npu.setup_axes(axes, xlim=(-1, 4), ylim=(-1, 4))\narrowprops = {'head_length': 0.25, 'head_width': 0.18}\nplt.arrow(0, 0, 1, 1, **arrowprops, ec='r', fc='r')\nplt.arrow(0, 0, 2, 3, **arrowprops, ec='b', fc='b')\n```\n\n## using sympy\nSympy is a wonderful toolkit for doing symbolic programming. We can also use it to *cheat* and help it solve systems of equations for us. Let's put it to work on one of the problems of the linear algebra book.\n\nWrite down the three equations for $c$, $d$ and $e$ so that $cu + dv + ew = b$ and try to find $c$, $d$ and $e$.\n\n$$\nu = \\begin{bmatrix}2\\\\-1\\\\0\\end{bmatrix}\nv = \\begin{bmatrix}-1\\\\2\\\\-1\\end{bmatrix}\nw = \\begin{bmatrix}0\\\\-1\\\\2\\end{bmatrix}\nb = \\begin{bmatrix}1\\\\0\\\\0\\end{bmatrix}\n$$\n\nThe equations are:\n\n$$\n\\begin{cases}\n2c - d &= 1\\\\\n-c + 2d - e &= 0\\\\\n-d + 2e &= 0\\\\\n\\end{cases}\n$$\n\nAnd we could try solve them ourselves which is not that hard to do via elimination but alternatively we can also use `sympy`.\n\n\n```python\ns = [S('2*c - d - 1'), S('-c + 2*d - e'), S('-d + 2*e')]\nsolve(s)\n```\n\n\n\n\n {d: 1/2, c: 3/4, e: 1/4}\n\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "21a3af7e2e3fa0fe3875b453368e8df291ec6106", "size": 6127, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "linear_algebra.ipynb", "max_stars_repo_name": "basp/notes", "max_stars_repo_head_hexsha": "8831f5f44fc675fbf1c3359a8743d2023312d5ca", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2016-12-09T13:58:13.000Z", "max_stars_repo_stars_event_max_datetime": "2016-12-09T13:58:13.000Z", "max_issues_repo_path": "linear_algebra.ipynb", "max_issues_repo_name": "basp/notes", "max_issues_repo_head_hexsha": "8831f5f44fc675fbf1c3359a8743d2023312d5ca", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "linear_algebra.ipynb", "max_forks_repo_name": "basp/notes", "max_forks_repo_head_hexsha": "8831f5f44fc675fbf1c3359a8743d2023312d5ca", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.5761589404, "max_line_length": 2318, "alphanum_fraction": 0.6768402154, "converted": true, "num_tokens": 637, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632288833652, "lm_q2_score": 0.905989826094673, "lm_q1q2_score": 0.862378401201954}} {"text": "# M2AA3 Chapter 2, Lesson 2 - Generating Orthogonal Polynomials\n\n\n```python\n#Setup for Sympy\nimport sympy as sp\n```\n\nWe wish to construct a list of polynomial $\\phi_n(x)$ which is orthogonal with respect to the inner product\n$$\\langle f(x),g(x) \\rangle = \\int_a^b w(x)f(x)g(x)dx$$\nwhere $w(x) > 0$ is the weight function. Let $\\|f(x)\\|^2 = \\langle f(x),f(x) \\rangle$. We may use the following recurrence relation:\n$$\\phi_j(x) = \\bigg(x - \\frac{\\langle x\\phi_{j-1}(x),\\phi_{j-1}(x) \\rangle}{\\|\\phi_{j-1}(x)\\|^2} \\bigg)\\phi_{j-1}(x) - \\frac{\\|\\phi_{j-1}(x)\\|^2}{\\|\\phi_{j-2}(x)\\|^2}\\phi_{j-2}(x), j \\geq 1$$ \nwhere $\\phi_{-1}(x)=0$ and $\\phi_{0}(x)=1$. Therefore we have\n$$\\phi_{1}(x) = x - \\frac{\\langle x,1 \\rangle}{\\| 1 \\|^2} = x - \\frac{\\int_a^b x w(x)dx}{\\int_a^b w(x)dx}$$\nOur aim is to define a function 'ortho', which inputs $w(x)$, $a$, $b$ and $r$ and output a list $\\phi_0(x), ..., \\phi_r(x)$.\n\nStep 1 - Define inner product and norm\n\n\n```python\nx = sp.symbols('x')\nw = sp.Function('w')\nf = sp.Function('f')\ng = sp.Function('g')\n```\n\n\n```python\ndef inner(w,a,b,f,g):\n output = sp.integrate(w*f*g, (x,a,b))\n return output\n\ndef norm(w,a,b,f):\n return sp.sqrt(inner(w,a,b,f,f))\n```\n\nStep 2 - Write the recursive function\n\n\n```python\nphi = sp.Function('phi')\nphiminus1 = sp.Function('phiminus1')\nphiminus2 = sp.Function('phiminus2')\n```\n\n\n```python\ndef ortho(w,a,b,r):\n phiminus2 = 1\n phiminus1 = x - inner(w,a,b,x,1)/(norm(w,a,b,1))**2\n if r == 0:\n return [phiminus2]\n elif r == 1:\n return [phiminus2,phiminus1]\n else:\n philist = [phiminus2,phiminus1]\n for i in range(r-1):\n phi = (x - inner(w,a,b,x*phiminus1,phiminus1)/(norm(w,a,b,phiminus1))**2)*phiminus1 - ((norm(w,a,b,phiminus1)/norm(w,a,b,phiminus2))**2)*phiminus2\n phi = sp.simplify(phi)\n philist.append(phi)\n phiminus2 = phiminus1\n phiminus1 = phi\n return philist\n```\n\n## Legendre Polynomials\nHere is an example of list of polynomials which are orthogonal with $w(x) = 1$. These are called Legendre Polynomials.\n\n\n```python\nolist = ortho(1,-1,1,5)\nprint(olist)\n```\n\n [1, x, x**2 - 1/3, x*(x**2 - 3/5), x**4 - 6*x**2/7 + 3/35, x*(63*x**4 - 70*x**2 + 15)/63]\n\n\nObserve that they are very similar to the Chebyshev Polynomials. Recall that they are defined as followed:\n$$L_j(x) = \\frac{2j-1}{j} x L_{j-1}(x) - \\frac{j-1}{j} L_{j-2}(x)$$\nwhere $L_0(x) = 1, L_1(x) = x$. If $\\phi_j(x)$ is the orthogonal polynomials obtained, then \n$\\phi_j(x) = \\frac{L_j(x)}{a_j}, j \\geq 1$, where $a_j$ is the leading coefficient of $L_j(x)$.\n\nTo verify this let's generate the first $r$ Legendre Polynomials.\n\n\n```python\nP = sp.Function('P')\nPminus1 = sp.Function('Pminus1')\nPminus2 = sp.Function('Pminus2')\n```\n\n\n```python\ndef Leb(r):\n Pminus2 = 1\n Pminus1 = x\n if r == 0:\n return [Pminus2]\n elif r == 1:\n return [Pminus2,Pminus1]\n else:\n Plist = [Pminus2,Pminus1]\n for i in range(2,r+1):\n P = (sp.Rational(2*i-1,i))*x*Pminus1 - sp.Rational(i-1,i)*Pminus2\n P = sp.simplify(P)\n Plist.append(P)\n Pminus2 = Pminus1\n Pminus1 = P\n return Plist\n```\n\nThen we verify that the polynomials are the same.\n\n\n```python\nLeblist = Leb(3)\nprint(Leblist)\nLebdivided = [1]+[sp.simplify(Leblist[i]/sp.polys.polytools.LC(Leblist[i])) for i in range(1,len(Leblist))]\nprint(Lebdivided)\nplist = ortho(1,-1,1,3)\nprint(plist)\nprint(plist == Lebdivided)\n```\n\n [1, x, 3*x**2/2 - 1/2, x*(5*x**2 - 3)/2]\n [1, x, x**2 - 1/3, x*(x**2 - 3/5)]\n [1, x, x**2 - 1/3, x*(x**2 - 3/5)]\n True\n\n\nWe may find the roots of polynomials.\n\n\n```python\nsp.solve(olist[3],x)\n```\n\n\n\n\n [0, -sqrt(15)/5, sqrt(15)/5]\n\n\n\n## Chebyshev Polynomials\nHere is another example of list of polynomials which are orthogonal with $w(x) = \\frac{1}{\\sqrt{1 - x^2}}$.\n\n\n```python\ntlist = ortho(1/sp.sqrt(1-x**2),-1,1,3)\nprint(tlist)\n```\n\n [1, x, x**2 - 1/2, x*(x**2 - 3/4)]\n\n\nObserve that they are very similar to the Chebyshev Polynomials. Recall that they are defined as followed:\n$$T_j(x) = 2x T_{j-1}(x) - T_{j-2}(x), j \\geq 2$$\nwhere $T_0(x) = 1, T_1(x) = x$. It could be proved that $T_j = \\cos (j \\cos^{-1} x)$.\nIf $\\phi_j(x)$ is the orthogonal polynomials obtained, then $\\phi_j(x) = \\frac{T_j(x)}{2^{j-1}}, j \\geq 1$.
\n\nTo verify this let's generate the first $r$ Chebyshev Polynomials.\n\n\n```python\nT = sp.Function('T')\nTminus1 = sp.Function('Tminus1')\nTminus2 = sp.Function('Tminus2')\n```\n\n\n```python\ndef Che(r):\n Tminus2 = 1\n Tminus1 = x\n if r == 0:\n return [Tminus2]\n elif r == 1:\n return [Tminus2,Tminus1]\n else:\n Tlist = [Tminus2,Tminus1]\n for i in range(r-1):\n T = 2*x*Tminus1 - Tminus2\n T = sp.simplify(T)\n Tlist.append(T)\n Tminus2 = Tminus1\n Tminus1 = T\n return Tlist\n```\n\nThen we verify that the polynomials are the same.\n\n\n```python\nChelist = Che(3)\nprint(Chelist)\nChelistdivided = [1] + [sp.simplify(Chelist[i]/(2**(i - 1))) for i in range(1, len(Chelist))]\nprint(Chelistdivided)\ntlist = ortho(1/sp.sqrt(1-x**2),-1,1,3)\nprint(tlist)\nprint(tlist == Chelistdivided)\n```\n\n [1, x, 2*x**2 - 1, x*(4*x**2 - 3)]\n [1, x, x**2 - 1/2, x*(x**2 - 3/4)]\n [1, x, x**2 - 1/2, x*(x**2 - 3/4)]\n True\n\n\nWe may find the roots for the polynomials.\n\n\n```python\nsp.solve(tlist[2],x)\n```\n\n\n\n\n [-sqrt(2)/2, sqrt(2)/2]\n\n\n", "meta": {"hexsha": "6d848739c053f4edcd94be584088cd2332a2de79", "size": 10183, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "M2AA3/M2AA3-Least-Square/Lesson 02 Best Approximation Problem/Orthogonal Polynomial.ipynb", "max_stars_repo_name": "ImperialCollegeLondon/Random-Stuff", "max_stars_repo_head_hexsha": "219bc0e26ea6f5ee7548009c849959b268f54821", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-05-16T04:08:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-27T12:56:10.000Z", "max_issues_repo_path": "M2AA3/M2AA3-Least-Square/Lesson 02 Best Approximation Problem/Orthogonal Polynomial.ipynb", "max_issues_repo_name": "ImperialCollegeLondon/Random-Stuff", "max_issues_repo_head_hexsha": "219bc0e26ea6f5ee7548009c849959b268f54821", "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": "M2AA3/M2AA3-Least-Square/Lesson 02 Best Approximation Problem/Orthogonal Polynomial.ipynb", "max_forks_repo_name": "ImperialCollegeLondon/Random-Stuff", "max_forks_repo_head_hexsha": "219bc0e26ea6f5ee7548009c849959b268f54821", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-03-31T00:23:13.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-13T15:01:46.000Z", "avg_line_length": 25.0196560197, "max_line_length": 222, "alphanum_fraction": 0.4770696258, "converted": true, "num_tokens": 2061, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9669140187510509, "lm_q2_score": 0.8918110440002044, "lm_q1q2_score": 0.8623046005208079}} {"text": "# Notes and excercises from *Structure and Interpretation of Computer Programs*\n\nThe book is [available online on MIT's site](https://mitpress.mit.edu/sites/default/files/sicp/full-text/book/book.html), there are also [recorded lectures on MIT's OCW](https://www.youtube.com/playlist?list=PLE18841CABEA24090).\n\nI'm using the [Calysto Scheme](https://github.com/Calysto/calysto_scheme) notebooks.\n\n```python\npip install calysto_scheme\n```\n\n## Chapter 2. Building Abstractions with Data\n\n### `cons` vs `list`\n\n```scheme\n(list ... )\n```\n\nis equivalent to\n\n```scheme\n(cons \n (cons \n (cons ...\n (cons \n nil) ...)))\n```\n\n\n```scheme\n;; math functions missig from Calysto Scheme\n\n(import \"math\")\n\n(define sin math.sin)\n(define cos math.cos)\n(define tan math.tan)\n(define atan math.atan)\n(define log math.log)\n```\n\n\n```scheme\n(define (gcd a b)\n (if (= b 0)\n a\n (gcd b (remainder a b))))\n\n(define (square x) (* x x))\n\n(define (approx x y) (< (abs (- x y)) 0.01))\n```\n\n\n```scheme\n;; Representing rational numbers\n\n(define (add-rat x y)\n (make-rat (+ (* (numer x) (denom y))\n (* (numer y) (denom x)))\n (* (denom x) (denom y))))\n(define (sub-rat x y)\n (make-rat (- (* (numer x) (denom y))\n (* (numer y) (denom x)))\n (* (denom x) (denom y))))\n(define (mul-rat x y)\n (make-rat (* (numer x) (numer y))\n (* (denom x) (denom y))))\n(define (div-rat x y)\n (make-rat (* (numer x) (denom y))\n (* (denom x) (numer y))))\n(define (equal-rat? x y)\n (= (* (numer x) (denom y))\n (* (numer y) (denom x))))\n\n(define (make-rat n d) (cons n d))\n\n(define (numer x) (car x))\n\n(define (denom x) (cdr x))\n\n(define (print-rat x)\n (newline)\n (display (numer x))\n (display \"/\")\n (display (denom x)))\n```\n\n\n```scheme\n(define one-half (make-rat 1 2))\n(define one-third (make-rat 1 3))\n\n(print-rat one-half)\n(print-rat (add-rat one-half one-third))\n(print-rat (mul-rat one-half one-third))\n(print-rat (add-rat one-third one-third))\n```\n\n \n 1/2\n 5/6\n 1/6\n 6/9\n\n(define (make-rat n d)\n (let ((g (gcd n d)))\n (cons (/ n g) (/ d g))))\n\n(print-rat (add-rat one-third one-third))\n\n\n```scheme\n;; For example, an alternate way to address the problem of reducing rational numbers to lowest terms is to perform\n;; the reduction whenever we access the parts of a rational number, rather than when we construct it. This leads\n;; to different constructor and selector procedures:\n\n(define (make-rat n d)\n (cons n d))\n\n(define (numer x)\n (let ((g (gcd (car x) (cdr x))))\n (/ (car x) g)))\n\n(define (denom x)\n (let ((g (gcd (car x) (cdr x))))\n (/ (cdr x) g)))\n\n(define one-half (make-rat 1 2))\n(define one-third (make-rat 1 3))\n\n(print-rat one-half)\n(print-rat (add-rat one-half one-third))\n(print-rat (mul-rat one-half one-third))\n(print-rat (add-rat one-third one-third))\n```\n\n \n 1/2\n 5/6\n 1/6\n 2/3\n\n**Exercise 2.2.** Consider the problem of representing line segments in a plane. Each segment is represented as a pair of points: a starting point and an ending point. Define a constructor `make-segment` and selectors `start-segment` and `end-segment` that define the representation of segments in terms of points. Furthermore, a point can be represented as a pair of numbers: the $x$ coordinate and the $y$ coordinate. Accordingly, specify a constructor `make-point` and selectors `x-point` and `y-point` that define this representation. Finally, using your selectors and constructors, define a procedure `midpoint-segment` that takes a line segment as argument and returns its midpoint (the point whose coordinates are the average of the coordinates of the endpoints). To try your procedures, you'll need a way to print points:\n\n\n```scheme\n(define (print-point p)\n (newline)\n (display \"(\")\n (display (x-point p))\n (display \",\")\n (display (y-point p))\n (display \")\"))\n```\n\n\n```scheme\n(define (make-point x y)\n (cons x y))\n\n(define (x-point p) (car p))\n\n(define (y-point p) (cdr p))\n\n(assert = (x-point (make-point 1 2)) 1)\n(assert = (y-point (make-point 1 2)) 2)\n\n(print-point (make-point 1 2))\n```\n\n \n (1,2)\n\n\n```scheme\n(define (make-segment start-segment end-segment)\n (list start-segment end-segment))\n\n(define (midpoint-segment segment)\n (define (midpoint selector)\n (/ (+\n (selector (car segment))\n (selector (cadr segment)))\n 2))\n (make-point\n (midpoint x-point)\n (midpoint y-point)))\n\n(assert = (car (midpoint-segment (make-segment (make-point 1 2) (make-point 3 0)))) 2)\n(assert = (cdr (midpoint-segment (make-segment (make-point 1 2) (make-point 3 0)))) 1)\n```\n\n\n\n\n ok\n\n\n\n**Exercise 2.3.** Implement a representation for rectangles in a plane. (Hint: You may want to make use of exercise 2.2.) In terms of your constructors and selectors, create procedures that compute the perimeter and the area of a given rectangle. Now implement a different representation for rectangles. Can you design your system with suitable abstraction barriers, so that the same perimeter and area procedures will work using either representation? \n\n\n```scheme\n(define (rectangle l w) (cons l w))\n(define (get-length rectangle) (car rectangle))\n(define (get-width rectangle) (cdr rectangle))\n\n(define (rectangle-area rectangle)\n (* (get-length rectangle)\n (get-width rectangle)))\n\n(assert = (rectangle-area (rectangle 1 1)) 1)\n(assert = (rectangle-area (rectangle 2 2)) 4)\n(assert = (rectangle-area (rectangle 2 5)) 10)\n\n(define (rectangle-perimeter rectangle)\n (* 2 (+ (get-length rectangle)\n (get-width rectangle))))\n\n(assert = (rectangle-perimeter (rectangle 1 1)) 4)\n(assert = (rectangle-perimeter (rectangle 2 2)) 8)\n(assert = (rectangle-perimeter (rectangle 2 5)) 14)\n```\n\n\n\n\n ok\n\n\n\n\n```scheme\n;; Euclidean distance between two points\n(define (distance p q)\n (sqrt\n (+ (square (- (x-point p) (x-point q)))\n (square (- (y-point p) (y-point q))))))\n\n(assert approx (distance (make-point 1 3) (make-point 4 13)) 10.44)\n(assert approx (distance (make-point 4 13) (make-point 1 3)) 10.44)\n```\n\n\n\n\n ok\n\n\n\n\n```scheme\n;; w\n;; p1 ------- p3\n;; | |\n;; l | | \n;; | | \n;; p2 ------- p4\n;;\n;; p_i = (x_i, y_i)\n\n;; Lousy way of storing it, by storing all the four points\n(define (rectangle p1 p2 p3 p4) (list p1 p2 p3 p4))\n\n(define (get-length rectangle)\n ;; |p3 - p1|\n (distance (car rectangle) (cadr rectangle)))\n\n(define (get-width rectangle)\n ;; |p2 - p1|\n (distance (car rectangle) (caddr rectangle)))\n\n;; (0,1) (2,1)\n;; (0,0) (2,0)\n(assert = (get-length (rectangle (make-point 0 1) (make-point 0 0) (make-point 2 1) (make-point 2 0))) 1)\n(assert = (get-width (rectangle (make-point 0 1) (make-point 0 0) (make-point 2 1) (make-point 2 0))) 2)\n\n;; (0,1) (1,1)\n;; (0,0) (0,0)\n(assert = (rectangle-area (rectangle (make-point 0 1) (make-point 0 0) (make-point 1 1) (make-point 1 0))) 1)\n(assert = (rectangle-perimeter (rectangle (make-point 0 1) (make-point 0 0) (make-point 1 1) (make-point 1 0))) 4)\n\n;; (2,4) (5,4)\n;; (2,2) (5,2)\n(assert = (rectangle-area (rectangle (make-point 2 4) (make-point 2 2) (make-point 5 4) (make-point 5 2))) 6)\n(assert = (rectangle-perimeter (rectangle (make-point 2 4) (make-point 2 2) (make-point 5 4) (make-point 5 2))) 10)\n\n;; Rotated:\n;; (2,4) (5,7)\n;; (4,2) (7,5)\n(assert approx (rectangle-area (rectangle (make-point 2 4) (make-point 4 2) (make-point 5 7) (make-point 7 5))) 12)\n(assert approx (rectangle-perimeter (rectangle (make-point 2 4) (make-point 4 2) (make-point 5 7) (make-point 7 5))) 14.14)\n```\n\n\n\n\n ok\n\n\n\n**Exercise 2.4.** Here is an alternative procedural representation of pairs. For this representation, verify that `(car (cons x y))` yields $x$ for any objects $x$ and $y$.\n\n```scheme\n(define (cons x y)\n (lambda (m) (m x y)))\n\n(define (car z)\n (z (lambda (p q) p)))\n```\n\nWhat is the corresponding definition of `cdr`? (Hint: To verify that this works, make use of the substitution model of section 1.1.5.)\n\n\n```scheme\n(define (λ-cons x y)\n (lambda (m) (m x y)))\n\n(define (λ-car z)\n (z (lambda (p q) p)))\n\n(define (λ-cdr z)\n (z (lambda (p q) q)))\n\n(assert = (λ-car (λ-cons 1 2)) 1)\n(assert = (λ-cdr (λ-cons 1 2)) 2)\n```\n\n\n\n\n ok\n\n\n\n**Exercise 2.5.** Show that we can represent pairs of nonnegative integers using only numbers and arithmetic operations if we represent the pair $a$ and $b$ as the integer that is the product $2^a 3^b$. Give the corresponding definitions of the procedures `cons`, `car`, and `cdr`.\n\n$$\n2^a 3^b = \\underbrace{2 \\cdot 2 \\cdot \\dots \\cdot 2}_{a ~\\times} \\cdot \\underbrace{3 \\cdot 3 \\cdot \\dots \\cdot 3}_{b ~\\times}\n$$\n\nso $(2^a 3^b) \\,/\\, 3 = 2^a 3^{b-1} $ etc.\n\n\n```scheme\n(define (arith-cons a b)\n (* (expt 2 a)\n (expt 3 b)))\n\n(define (arith-car x)\n (define (iter x count)\n (if (= 0 (remainder x 2))\n (iter (/ x 2) (+ 1 count))\n count))\n (iter x 0))\n\n(define (arith-cdr x)\n (define (iter x count)\n (if (= 0 (remainder x 3))\n (iter (/ x 3) (+ 1 count))\n count))\n (iter x 0))\n\n(assert = (arith-car (arith-cons 0 0)) 0)\n(assert = (arith-cdr (arith-cons 0 0)) 0)\n(assert = (arith-car (arith-cons 1 1)) 1)\n(assert = (arith-cdr (arith-cons 1 1)) 1)\n(assert = (arith-car (arith-cons 5 7)) 5)\n(assert = (arith-cdr (arith-cons 5 7)) 7)\n(assert = (arith-car (arith-cons 3 2)) 3)\n(assert = (arith-cdr (arith-cons 3 2)) 2)\n(assert = (arith-car (arith-cons 3 0)) 3)\n(assert = (arith-cdr (arith-cons 0 2)) 2)\n```\n\n\n\n\n ok\n\n\n\n**Exercise 2.6.** In case representing pairs as procedures wasn't mind-boggling enough, consider that, in a language that can manipulate procedures, we can get by without numbers (at least insofar as nonnegative integers are concerned) by implementing 0 and the operation of adding 1 as\n\n```scheme\n(define zero (lambda (f) (lambda (x) x)))\n\n(define (add-1 n)\n (lambda (f) (lambda (x) (f ((n f) x)))))\n```\n\nThis representation is known as Church numerals, after its inventor, Alonzo Church, the logician who invented the $\\lambda$-calculus.\n\nDefine one and two directly (not in terms of `zero` and `add-1`). (Hint: Use substitution to evaluate `(add-1 zero)`). Give a direct definition of the addition procedure `+` (not in terms of repeated application of `add-1`). \n\n\n```scheme\n\n```\n\n\n```scheme\n;; 2.1.4 Extended Exercise: Interval Arithmetic\n\n(define (add-interval x y)\n (make-interval (+ (lower-bound x) (lower-bound y))\n (+ (upper-bound x) (upper-bound y))))\n\n(define (mul-interval x y)\n (let ((p1 (* (lower-bound x) (lower-bound y)))\n (p2 (* (lower-bound x) (upper-bound y)))\n (p3 (* (upper-bound x) (lower-bound y)))\n (p4 (* (upper-bound x) (upper-bound y))))\n (make-interval (min p1 p2 p3 p4)\n (max p1 p2 p3 p4))))\n\n(define (div-interval x y)\n (mul-interval x \n (make-interval (/ 1.0 (upper-bound y))\n (/ 1.0 (lower-bound y)))))\n```\n\nhttps://en.wikipedia.org/wiki/Interval_arithmetic#Interval_operators\n\n$$\\begin{align}\n[x_1, x_2] + [y_1, y_2] &= [x_1+y_1, x_2+y_2] \\\\\n[x_1, x_2] - [y_1, y_2] &= [x_1-y_2, x_2-y_1] \\\\\n[x_1, x_2] \\cdot [y_1, y_2] &= [\\min \\{x_1 y_1,x_1 y_2,x_2 y_1,x_2 y_2\\}, \\max\\{x_1 y_1,x_1 y_2,x_2 y_1,x_2 y_2\\}] \\\\\n\\frac{[x_1, x_2]}{[y_1, y_2]} &= [x_1, x_2] \\cdot \\frac{1}{[y_1, y_2]}\n\\end{align}$$\n\n**Exercise 2.7.** Alyssa's program is incomplete because she has not specified the implementation of the interval abstraction. Here is a definition of the interval constructor:\n\n\n```scheme\n(define (make-interval a b) (cons a b))\n```\n\nDefine selectors `upper-bound` and `lower-bound` to complete the implementation.\n\n\n```scheme\n(define (lower-bound interval) (car interval))\n(define (upper-bound interval) (cdr interval))\n\n(assert = (lower-bound (make-interval 1 2)) 1)\n(assert = (upper-bound (make-interval 1 2)) 2)\n(assert = (car (add-interval (make-interval 1 2) (make-interval 3 4))) 4)\n(assert = (cdr (add-interval (make-interval 1 2) (make-interval 3 4))) 6)\n```\n\n\n\n\n ok\n\n\n\n**Exercise 2.8.** Using reasoning analogous to Alyssa's, describe how the difference of two intervals may be computed. Define a corresponding subtraction procedure, called `sub-interval`.\n\n\n```scheme\n(define (sub-interval x y)\n (make-interval (- (lower-bound x) (upper-bound y))\n (- (upper-bound x) (lower-bound y))))\n\n(assert = (lower-bound (sub-interval (make-interval 10 20) (make-interval 1 2))) 8)\n(assert = (upper-bound (sub-interval (make-interval 10 20) (make-interval 1 2))) 19)\n```\n\n\n\n\n ok\n\n\n\n**Exercise 2.9.** The *width* of an interval is half of the difference between its upper and lower bounds. The width is a measure of the uncertainty of the number specified by the interval. For some arithmetic operations the width of the result of combining two intervals is a function only of the widths of the argument intervals, whereas for others the width of the combination is not a function of the widths of the argument intervals. Show that the width of the sum (or difference) of two intervals is a function only of the widths of the intervals being added (or subtracted). Give examples to show that this is not true for multiplication or division.\n\n\n```scheme\n(define (width interval)\n (/ (- (upper-bound interval)\n (lower-bound interval))\n 2))\n\n(assert = (width (make-interval 0 10)) 5)\n```\n\n\n\n\n ok\n\n\n\n**Exercise 2.10.** Ben Bitdiddle, an expert systems programmer, looks over Alyssa's shoulder and comments that it is not clear what it means to divide by an interval that spans zero. Modify Alyssa's code to check for this condition and to signal an error if it occurs.\n\n\n```scheme\n(define (raises-error? expr)\n (try (begin\n (eval expr)\n #f)\n (catch 'error #t)))\n\n(assert eq? (raises-error? '(raise \"Oh no!\")) #t)\n(assert eq? (raises-error? '(lambda () (+ 2 2))) #f)\n```\n\n\n\n\n ok\n\n\n\n\n```scheme\n(define (div-interval x y)\n (if (> (width y) 0)\n (mul-interval x \n (make-interval (/ 1.0 (upper-bound y))\n (/ 1.0 (lower-bound y))))\n (raise \"Cannot divide by interval with span = 0\")))\n\n(assert eq? (raises-error? '(div-interval (make-interval 0 1) (make-interval 1 2))) #f)\n(assert eq? (raises-error? '(div-interval (make-interval 0 1) (make-interval 1 1))) #t)\n```\n\n\n\n\n ok\n\n\n\n**Exercise 2.11.** In passing, Ben also cryptically comments: \"By testing the signs of the endpoints of the intervals, it is possible to break `mul-interval` into nine cases, only one of which requires more than two multiplications.\" Rewrite this procedure using Ben's suggestion.\n\n\n```scheme\n;; small+ * small+ = small+\n;; large+ * large+ = large+\n;; small+ * large- = moderate-\n;; large+ * small- = moderate-\n;; large+ * small- = moderate-\n;; small+ * large- = moderate-\n;; small- * small- = small-\n;; large- * large- = large-\n\n\n(define (mul-interval-light x y)\n (let ((lx (lower-bound x))\n (ux (upper-bound x))\n (ly (lower-bound y))\n (uy (upper-bound y)))\n (cond\n ((and (> lx 0) (> ux 0) (> ly 0) (> uy 0))\n (make-interval (* (min lx ux) (min ly uy))\n (* (max lx ux) (max ly uy))))\n \n \n )))\n```\n\nAfter debugging her program, Alyssa shows it to a potential user, who complains that her program solves the wrong problem. He wants a program that can deal with numbers represented as a center value and an additive tolerance; for example, he wants to work with intervals such as $3.5\\pm 0.15$ rather than $[3.35, 3.65]$. Alyssa returns to her desk and fixes this problem by supplying an alternate constructor and alternate selectors:\n\n\n```scheme\n(define (make-center-width c w)\n (make-interval (- c w) (+ c w)))\n(define (center i)\n (/ (+ (lower-bound i) (upper-bound i)) 2))\n(define (width i)\n (/ (- (upper-bound i) (lower-bound i)) 2))\n```\n\nUnfortunately, most of Alyssa's users are engineers. Real engineering situations usually involve measurements with only a small uncertainty, measured as the ratio of the width of the interval to the midpoint of the interval. Engineers usually specify percentage tolerances on the parameters of devices, as in the resistor specifications given earlier.\n\n**Exercise 2.12.** Define a constructor `make-center-percent` that takes a center and a percentage tolerance and produces the desired interval. You must also define a selector `percent` that produces the percentage tolerance for a given interval. The `center` selector is the same as the one shown above.\n\n\n```scheme\n(define (make-center-percent c p)\n (let ((w (* c p)))\n (make-interval (- c w) (+ c w))))\n\n(define (width i)\n (/ (- (upper-bound i) (lower-bound i)) 2))\n\n(assert = (width (make-center-percent 10 0.1)) 1)\n(assert = (lower-bound (make-center-percent 10 0.1)) 9)\n(assert = (upper-bound (make-center-percent 10 0.1)) 11)\n\n(assert = (lower-bound (make-center-width 10 1)) (lower-bound (make-center-percent 10 0.1)))\n(assert = (lower-bound (make-center-width 10 1)) (lower-bound (make-center-percent 10 0.1)))\n(assert = (upper-bound (make-center-width 1 0.1)) (upper-bound (make-center-percent 1 0.1)))\n(assert = (upper-bound (make-center-width 1 0.1)) (upper-bound (make-center-percent 1 0.1)))\n```\n\n\n\n\n ok\n\n\n\n**Exercise 2.13.** Show that under the assumption of small percentage tolerances there is a simple formula for the approximate percentage tolerance of the product of two intervals in terms of the tolerances of the factors. You may simplify the problem by assuming that all numbers are positive.\n\n\n```scheme\n\n```\n\nAfter considerable work, Alyssa P. Hacker delivers her finished system. Several years later, after she has forgotten all about it, she gets a frenzied call from an irate user, Lem E. Tweakit. It seems that Lem has noticed that the formula for parallel resistors can be written in two algebraically equivalent ways:\n\n$$\n\\frac{R_1 R_2}{R_1 + R_2}\n$$\n\nand\n\n$$\n\\frac{1}{1/R_1 + 1/R_2}\n$$\n\nHe has written the following two programs, each of which computes the parallel-resistors formula differently:\n\n\n```scheme\n(define (par1 r1 r2)\n (div-interval (mul-interval r1 r2)\n (add-interval r1 r2)))\n\n(define (par2 r1 r2)\n (let ((one (make-interval 1 1))) \n (div-interval one\n (add-interval (div-interval one r1)\n (div-interval one r2)))))\n```\n\nLem complains that Alyssa's program gives different answers for the two ways of computing. This is a serious complaint.\n\n**Exercise 2.14.** Demonstrate that Lem is right. Investigate the behavior of the system on a variety of arithmetic expressions. Make some intervals $A$ and $B$, and use them in computing the expressions $A/A$ and $A/B$. You will get the most insight by using intervals whose width is a small percentage of the center value. Examine the results of the computation in center-percent form (see exercise 2.12).\n\n\n```scheme\n(print (par1 (make-center-percent 10 0.1) (make-center-percent 10 0.1)))\n(print (par2 (make-center-percent 10 0.1) (make-center-percent 10 0.1)))\n(print (par1 (make-center-percent 10 0.1) (make-center-width 1 0.1)))\n(print (par2 (make-center-percent 10 0.1) (make-center-width 1 0.1)))\n(print (par1 (make-center-percent 10 0.5) (make-center-width 1 0.5)))\n(print (par2 (make-center-percent 10 0.5) (make-center-width 1 0.5)))\n```\n\n (3.681818181818182 . 6.722222222222221)\n (4.5 . 5.5)\n (0.6694214876033058 . 1.2222222222222223)\n (0.8181818181818181 . 1.0)\n (0.15151515151515152 . 4.090909090909091)\n (0.45454545454545453 . 1.3636363636363638)\n\n\n**Exercise 2.15.** Eva Lu Ator, another user, has also noticed the different intervals computed by different but algebraically equivalent expressions. She says that a formula to compute with intervals using Alyssa's system will produce tighter error bounds if it can be written in such a form that no variable that represents an uncertain number is repeated. Thus, she says, `par2` is a \"better\" program for parallel resistances than `par1`. Is she right? Why?\n\n\n```scheme\n\n```\n\n**Exercise 2.16.** Explain, in general, why equivalent algebraic expressions may lead to different answers. Can you devise an interval-arithmetic package that does not have this shortcoming, or is this task impossible? (Warning: This problem is very difficult.) \n\n\n```scheme\n\n```\n", "meta": {"hexsha": "4431610dae8da1b8c01092c69de6db4a42fb185f", "size": 33187, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Scheme/SICP-Ch2.ipynb", "max_stars_repo_name": "twolodzko/Learning", "max_stars_repo_head_hexsha": "e5af2bdf6f65648c3c159343e14d63c157384009", "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": "Scheme/SICP-Ch2.ipynb", "max_issues_repo_name": "twolodzko/Learning", "max_issues_repo_head_hexsha": "e5af2bdf6f65648c3c159343e14d63c157384009", "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": "Scheme/SICP-Ch2.ipynb", "max_forks_repo_name": "twolodzko/Learning", "max_forks_repo_head_hexsha": "e5af2bdf6f65648c3c159343e14d63c157384009", "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": 31.1907894737, "max_line_length": 836, "alphanum_fraction": 0.5352397023, "converted": true, "num_tokens": 6025, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026550642018, "lm_q2_score": 0.9399133439350607, "lm_q1q2_score": 0.8621850059219034}} {"text": "# Simple symbolic maniplation in Python\n\nAll is done using [SymPy](https://docs.sympy.org/latest/index.html)\n\n\n```python\nfrom sympy import *\n```\n\nDefine some common symbols to be used as variables, integers, or functions for symbolic purposes\n\n\n```python\nx, y, z, t = symbols('x y z t')\nk, m, n = symbols('k m n', integer=True)\nf, g, h = symbols('f g h', cls=Function)\n```\n\nIntegration\n\n\n```python\nintegrate(cos(x), x)\n```\n\n\n\n\n$\\displaystyle \\sin{\\left(x \\right)}$\n\n\n\nDifferentiation\n\n\n```python\ndiff(atan(x),x)\n```\n\n\n\n\n$\\displaystyle \\frac{1}{x^{2} + 1}$\n\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "24f634526c99cd3a3862cc16b923c802e3284280", "size": 2716, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "SymbolicExamples.ipynb", "max_stars_repo_name": "fedxa/PHYS30471", "max_stars_repo_head_hexsha": "f5c16c50f813945d061dd4929ef6fb356a00ffc2", "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": "SymbolicExamples.ipynb", "max_issues_repo_name": "fedxa/PHYS30471", "max_issues_repo_head_hexsha": "f5c16c50f813945d061dd4929ef6fb356a00ffc2", "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": "SymbolicExamples.ipynb", "max_forks_repo_name": "fedxa/PHYS30471", "max_forks_repo_head_hexsha": "f5c16c50f813945d061dd4929ef6fb356a00ffc2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-11-19T14:53:35.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-19T14:53:35.000Z", "avg_line_length": 18.2281879195, "max_line_length": 102, "alphanum_fraction": 0.4937407953, "converted": true, "num_tokens": 171, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9805806523850543, "lm_q2_score": 0.8791467785920306, "lm_q1q2_score": 0.8620743216939922}} {"text": "### Exercises of Optimization\n\n\n```python\n# import Python libraries\nimport numpy as np\n%matplotlib inline\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport sympy as sym\nfrom sympy.plotting import plot\nimport pandas as pd\nfrom IPython.display import display\nfrom IPython.core.display import Math\n```\n\n**1.) Find the extrema in the function $f(x)=x^3−7.5x^2+18x−10$ analytically and determine if they are minimum or maximum.**\n\n\n\n```python\nx = sym.symbols('x')\nf_de_x = (x**3) - 7.5 * (x**2) + 18*x - 10\nFdiff = sym.expand(sym.diff(f_de_x, x))\nroots = sym.solve(Fdiff, x)\ndisplay(Math(sym.latex('Roots:') + sym.latex(roots)))\n```\n\n\n$$Roots:\\left [ 2.0, \\quad 3.0\\right ]$$\n\n\n\n```python\nf = np.array([1,0])\nf[0] = (roots[0]**3) - 7.5 * (roots[0]**2) + 18*roots[0] - 10\nf[1] = (roots[1]**3) - 7.5 * (roots[1]**2) + 18*roots[1] - 10\n\nprint(\"For the first root, f_de_x is\", f[0])\nprint(\"For the second root, f_de_x is\", f[1])\n```\n\n For the first root, f_de_x is 4\n For the second root, f_de_x is 3\n\n\n\n```python\nprint(\"So, the maximun of f_de_x is \", np.max(f))\nprint(\"and the minimun of f_de_x is \", np.min(f))\n```\n\n So, the maximun of f_de_x is 4\n and the minimun of f_de_x is 3\n\n\n**2.) Find the minimum in the $f(x)=x^3−7.5x^2+18x−10$ using the gradient descent algorithm.**\n\n\n```python\n# From https://en.wikipedia.org/wiki/Gradient_descent\n# The local minimum of $f(x)=x^4-3x^3+2$ is at x=9/4\n\ncur_x = 6 # The algorithm starts at x=6\ngamma = 0.01 # step size multiplier\nprecision = 0.00001\nstep_size = 1 # initial step size\nmax_iters = 10000 # maximum number of iterations\niters = 0 # iteration counter\n\nf = lambda x: (x**3) - 7.5 * (x**2) + 18*x - 10 # lambda function for f(x)\ndf = lambda x: 3*x**2 - 15*x + 18 # lambda function for the gradient of f(x)\n\nwhile (step_size > precision) & (iters < max_iters):\n prev_x = cur_x\n cur_x -= gamma*df(prev_x)\n step_size = abs(cur_x - prev_x)\n iters+=1\n\nprint('True local minimum at {} with function value {}.'.format(9/4, f(9/4)))\nprint('Local minimum by gradient descent at {} with function value {}.'.format(cur_x, f(cur_x)))\n```\n\n True local minimum at 2.25 with function value 3.921875.\n Local minimum by gradient descent at 3.000323195755751 with function value 3.5000001567170003.\n\n", "meta": {"hexsha": "d268d67c94bf1b442d4c31353fb536cacb75a458", "size": 4415, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "courses/modsim2018/tasks/Task_ForLecture19.ipynb", "max_stars_repo_name": "raissabthibes/bmc", "max_stars_repo_head_hexsha": "840800fb94ea3bf188847d0771ca7197dfec68e3", "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": "courses/modsim2018/tasks/Task_ForLecture19.ipynb", "max_issues_repo_name": "raissabthibes/bmc", "max_issues_repo_head_hexsha": "840800fb94ea3bf188847d0771ca7197dfec68e3", "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": "courses/modsim2018/tasks/Task_ForLecture19.ipynb", "max_forks_repo_name": "raissabthibes/bmc", "max_forks_repo_head_hexsha": "840800fb94ea3bf188847d0771ca7197dfec68e3", "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": 25.8187134503, "max_line_length": 132, "alphanum_fraction": 0.5166477916, "converted": true, "num_tokens": 784, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9697854103128328, "lm_q2_score": 0.8887587831798665, "lm_q1q2_score": 0.8619053012152208}} {"text": "```\nimport numpy as np\nimport pandas as pd\nimport random\nimport matplotlib.pyplot as plt\n```\n\n\n```\n#matplotlib parameters\nplt.rcParams[\"figure.figsize\"] = (12, 8)\nplt.rcParams.update({'font.size': 14})\n```\n\n# **What is a stochastic process?**\n**A stochastic process is a collection of random\nvariables: $\\{X_t,t \\in I \\},$ Where: $X_t$ is the set of random variables at time $t$, and $I$ is the index set of the process.**\n\n**Discrete time stochastic processes which we will focus on in this tutorial are sequences of random variables.**\n\n## **Simulation of Gambler's Ruin**\n\n**We can use the famous example of gambler's ruin which is a stochastic process.**\n\n**In our case, a gambler starts off with \\$50. To keep things simple, they can only bet in increments of \\$1. They can only win or lose \\$1 per bet. They will keep gambling until they either lost all their money (leave with \\$0) or if they win \\$100. We can formalize this with the following notation:**\n\n$\\begin{equation}\n X_{g} =\n \\begin{cases}\n \\$+1, & \\text{with a probability of 50%}\\\\\n \\$-1, & \\text{with a probability of 50%}\\\\\n \\end{cases} \n\\end{equation}$\n\n**Where: $X_g$ is the gambling outcome in dollars.**\n\nSource: [Introduction to Stochastic Processes with R](https://www.amazon.com/Introduction-Stochastic-Processes-Robert-Dobrow/dp/1118740653) by Robert P. Dobrow\n\n\n```\ndef gamblers_ruin():\n gambling_money = 50\n gambling_goal = 100\n gambling_simulation = []\n\n while gambling_money in range(1,gambling_goal):\n bet_size = 1\n w_or_l = random.randrange(-1, 2, step = 2)\n gambling_money += bet_size * w_or_l\n gambling_simulation.append(gambling_money)\n return gambling_simulation\n```\n\n\n```\nplt.plot(gamblers_ruin())\nplt.yticks(np.arange(-20,120,10))\nplt.axhline(y=0, color='r', linestyle='-')\nplt.axhline(y=100, color='black', linestyle='-')\nplt.xlabel('Number of bets')\nplt.ylabel('Winnings')\nplt.title('Gambling Simulation');\n```\n\n\n```\ndef prob_of_ruin(gambling_goal, initial_gambling_money):\n return (gambling_goal - initial_gambling_money)/gambling_goal\n```\n\n\n```\nprob_of_ruin(100,50)\n```\n\n\n\n\n 0.5\n\n\n\n\n```\nsim_list = []\n\nwhile len(sim_list) < 500:\n sim_list.append(gamblers_ruin()[-1])\n\nnp.mean(sim_list)\n```\n\n\n\n\n 54.2\n\n\n\nSource: [Introduction to Stochastic Processes with R](https://www.amazon.com/Introduction-Stochastic-Processes-Robert-Dobrow/dp/1118740653) by Robert P. Dobrow\n\n# **Markov Chains**\n\n**A Markov chain is a type of stochastic process.**\n\n**A Markov chain is a collection of random variables ($X_t$) where the future states ($j$) only depend on the current state ($i$). Markov chains can be either discrete or continuous.**\n\n**For a Markov chain transition matrix (denoted as $P$):**\n\n - **Each row must add to one, where: $\\sum\\limits_{j}P_{ij} = 1$.**\n - **The probabilities must be non-negative where: $P_{ij} \\geq 0 \\ \\ \\forall \\ \\ i,j$**\n\nSource: [Introduction to Stochastic Processes with R](https://www.amazon.com/Introduction-Stochastic-Processes-Robert-Dobrow/dp/1118740653) by Robert P. Dobrow\n\nSource: [Markov Chain](https://mathworld.wolfram.com/MarkovChain.html?utm_source=twitterfeed&utm_medium=twitter) from Wolfram MathWorld\n\n## **Markov Chain Simulation**\n\n**A Markov chain can be simulated from an initial distribution and transition matrix. In our case, the initial state is New York City. From the initial state we can travel to: Paris, Cairo, Seoul or even within New York City.**\n\n**The transition matrix contains the one step transition probabilities of\nmoving from state to state.**\n\nSource: [Introduction to Stochastic Processes with R](https://www.amazon.com/Introduction-Stochastic-Processes-Robert-Dobrow/dp/1118740653) by Robert P. Dobrow\n\n\n```\nmc_example = {'NYC': [.25,0,.75,1],\n 'Paris': [.25,.25,0,0],\n 'Cairo': [.25,.25,.25,0],\n 'Seoul': [.25,.5,0,0]}\n\nmc = pd.DataFrame(data = mc_example, index = ['NYC', 'Paris', 'Cairo', 'Seoul'])\n```\n\n### **Markov Transition Graph**\n\n\n\n**We can formalize the movement for the Markov chain at the initial starting point (New York City) with the following notation:**\n\n$P(X_1 = \\text{New York}|X_0 = \\text{New York})=P(X_1 = \\text{Paris}|X_0 = \\text{New York})=P(X_1 = \\text{Cairo}|X_0 = \\text{New York}) = P(X_1 = \\text{Seoul}|X_0 = \\text{New York}) = 25\\%$\n\n\n```\ntravel_sim = []\ntravel_sim.append(mc.iloc[0].index[0])\ncity = np.random.choice(mc.iloc[0].index, p = mc.iloc[0])\ntravel_sim.append(city)\n\nwhile len(travel_sim) < 25:\n city = np.random.choice(mc.iloc[mc.index.get_loc(city)].index, p = mc.iloc[mc.index.get_loc(city)])\n travel_sim.append(city)\n```\n\n\n```\ntravel_sim\n```\n\n\n\n\n ['NYC',\n 'Paris',\n 'Paris',\n 'Seoul',\n 'NYC',\n 'Seoul',\n 'NYC',\n 'Seoul',\n 'NYC',\n 'Cairo',\n 'NYC',\n 'Seoul',\n 'NYC',\n 'Seoul',\n 'NYC',\n 'Seoul',\n 'NYC',\n 'Paris',\n 'Seoul',\n 'NYC',\n 'NYC',\n 'Cairo',\n 'NYC',\n 'Seoul',\n 'NYC']\n\n\n\n\n```\nmc\n```\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
NYCParisCairoSeoul
NYC0.250.250.250.25
Paris0.000.250.250.50
Cairo0.750.000.250.00
Seoul1.000.000.000.00
\n
\n\n\n\n### **Memorylessness: The future is independent of the past given the present**\n\n**An important feature of Markov chains is that they are memorylessness. If we look at our example, the only state that matters is the current state. If our salesperson started in New York City ($X_0 = NYC$) and traveled to Paris ($X_1 = Paris$), then the movement to the next city ($X_2$) only depends on the probabilities of travel from Paris. The fact that the salesperson originally started in New York does not effect the movement to $X_2.$** \n\n## **$n$ Step Transition Matrix**\n\n\n```\nmc.to_numpy()\n```\n\n\n\n\n array([[0.25, 0.25, 0.25, 0.25],\n [0. , 0.25, 0.25, 0.5 ],\n [0.75, 0. , 0.25, 0. ],\n [1. , 0. , 0. , 0. ]])\n\n\n\n\n```\ndef matrix_power(matrix, power):\n if power == 0:\n return np.identity(len(matrix))\n elif power == 1:\n return matrix\n else:\n return np.dot(matrix, matrix_power(matrix, power-1))\n```\n\nSource: [Introduction to Stochastic Processes with R](https://www.amazon.com/Introduction-Stochastic-Processes-Robert-Dobrow/dp/1118740653) by Robert P. Dobrow\n\n\n```\nmatrix_power(mc.to_numpy(), 2)\n```\n\n\n\n\n array([[0.5 , 0.125 , 0.1875, 0.1875],\n [0.6875, 0.0625, 0.125 , 0.125 ],\n [0.375 , 0.1875, 0.25 , 0.1875],\n [0.25 , 0.25 , 0.25 , 0.25 ]])\n\n\n\n\n```\nnp.dot(np.dot(mc.to_numpy(), mc.to_numpy()), mc.to_numpy())\n```\n\n\n\n\n array([[0.453125, 0.15625 , 0.203125, 0.1875 ],\n [0.390625, 0.1875 , 0.21875 , 0.203125],\n [0.46875 , 0.140625, 0.203125, 0.1875 ],\n [0.5 , 0.125 , 0.1875 , 0.1875 ]])\n\n\n\n\n```\nnp.dot(mc.to_numpy(), mc.to_numpy())\n```\n\n\n\n\n array([[0.5 , 0.125 , 0.1875, 0.1875],\n [0.6875, 0.0625, 0.125 , 0.125 ],\n [0.375 , 0.1875, 0.25 , 0.1875],\n [0.25 , 0.25 , 0.25 , 0.25 ]])\n\n\n\n\n```\nmatrix_power(mc.to_numpy(), 3).sum(axis=1)\n```\n\n\n\n\n array([1., 1., 1., 1.])\n\n\n\n**What the above 2-step transition matrix is telling us is if we look at state $i$ for New York, in two steps there is a 50% probability that the salesperson ends up back in New York City, a 12.5% probability that they go onto Paris and an 18.75% chance that they end up in Cairo or Seoul.**\n\n\n```\nfor i in range(1,10,1):\n print(f'n Step Transition Matrix at the nth power {i}\\n', matrix_power(mc.to_numpy(), i),'\\n')\n```\n\n n Step Transition Matrix at the nth power 1\n [[0.25 0.25 0.25 0.25]\n [0. 0.25 0.25 0.5 ]\n [0.75 0. 0.25 0. ]\n [1. 0. 0. 0. ]] \n \n n Step Transition Matrix at the nth power 2\n [[0.5 0.125 0.1875 0.1875]\n [0.6875 0.0625 0.125 0.125 ]\n [0.375 0.1875 0.25 0.1875]\n [0.25 0.25 0.25 0.25 ]] \n \n n Step Transition Matrix at the nth power 3\n [[0.453125 0.15625 0.203125 0.1875 ]\n [0.390625 0.1875 0.21875 0.203125]\n [0.46875 0.140625 0.203125 0.1875 ]\n [0.5 0.125 0.1875 0.1875 ]] \n \n n Step Transition Matrix at the nth power 4\n [[0.453125 0.15234375 0.203125 0.19140625]\n [0.46484375 0.14453125 0.19921875 0.19140625]\n [0.45703125 0.15234375 0.203125 0.1875 ]\n [0.453125 0.15625 0.203125 0.1875 ]] \n \n n Step Transition Matrix at the nth power 5\n [[0.45703125 0.15136719 0.20214844 0.18945312]\n [0.45703125 0.15234375 0.20214844 0.18847656]\n [0.45410156 0.15234375 0.203125 0.19042969]\n [0.453125 0.15234375 0.203125 0.19140625]] \n \n n Step Transition Matrix at the nth power 6\n [[0.45532227 0.15209961 0.20263672 0.18994141]\n [0.4543457 0.15234375 0.20288086 0.19042969]\n [0.45629883 0.15161133 0.20239258 0.18969727]\n [0.45703125 0.15136719 0.20214844 0.18945312]] \n \n n Step Transition Matrix at the nth power 7\n [[0.45574951 0.15185547 0.20251465 0.18988037]\n [0.45617676 0.15167236 0.20239258 0.1897583 ]\n [0.45556641 0.15197754 0.20257568 0.18988037]\n [0.45532227 0.15209961 0.20263672 0.18994141]] \n \n n Step Transition Matrix at the nth power 8\n [[0.45570374 0.15190125 0.20252991 0.18986511]\n [0.45559692 0.15196228 0.20256042 0.18988037]\n [0.45570374 0.15188599 0.20252991 0.18988037]\n [0.45574951 0.15185547 0.20251465 0.18988037]] \n \n n Step Transition Matrix at the nth power 9\n [[0.45568848 0.15190125 0.20253372 0.18987656]\n [0.45569992 0.1518898 0.20252991 0.18988037]\n [0.45570374 0.15189743 0.20252991 0.18986893]\n [0.45570374 0.15190125 0.20252991 0.18986511]] \n \n\n\n**We can see above that as the number of steps increase, the probabilities converge to what is called a stationary distribution (also known as a steady state vector).**\n\n**Let's say that this time our salesperson is starting their trip from Seoul. In this case, we can denote the initial distribution as: $\\alpha = [0,0,0,1]$. Now let's find what the probability of ending up back in Seoul is two trips from now.**\n\n\n```\ninitial_dist = np.asarray([0,0,0,1])\n\nmc_p2 = matrix_power(mc.to_numpy(),2)\n\nnp.dot(initial_dist,mc_p2)\n```\n\n\n\n\n array([0.25, 0.25, 0.25, 0.25])\n\n\n\n# **References and Additional Learning**\n\n## **Online Course**\n\n- **[Introduction to Probability](https://ocw.mit.edu/resources/res-6-012-introduction-to-probability-spring-2018/) from MIT OpenCourseWare**\n\n## **Textbook**\n- **[Introduction to Stochastic Processes with R](https://www.amazon.com/Introduction-Stochastic-Processes-Robert-Dobrow/dp/1118740653) by Robert P. Dobrow**\n\n## **Videos**\n- **[Markov Chains](https://www.youtube.com/watch?v=uvYTGEZQTEs) by patrickJMT**\n\n- **[Markov Steady-State Vectors](https://www.youtube.com/watch?v=D2wvhwOTWIo) by Brandon Foltz**\n\n- **[Origin of Markov chains](https://www.youtube.com/watch?v=Ws63I3F7Moc) from Khan Academy Labs**\n\n# **Connect**\n\n- **Feel free to connect with Adrian on [YouTube](https://www.youtube.com/channel/UCPuDxI3xb_ryUUMfkm0jsRA), [LinkedIn](https://www.linkedin.com/in/adrian-dolinay-frm-96a289106/), [Twitter](https://twitter.com/DolinayG) and [GitHub](https://github.com/ad17171717). Happy coding!**\n", "meta": {"hexsha": "683eeccf9c271e312f33125edf583004e7a4428b", "size": 153545, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Python YouTube Tutorials/An_Intro_to_Markov_chains_with_Python!.ipynb", "max_stars_repo_name": "tudev/Workshops-2020-2021", "max_stars_repo_head_hexsha": "e708f50cc6620bb8903943588260c9d125a9bafb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 24, "max_stars_repo_stars_event_min_datetime": "2020-09-01T00:19:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T05:38:28.000Z", "max_issues_repo_path": "Python YouTube Tutorials/An_Intro_to_Markov_chains_with_Python!.ipynb", "max_issues_repo_name": "ad17171717/Workshops-2020-2021", "max_issues_repo_head_hexsha": "f0bcd92c9171ccc43a1a7ccb5ec645c4e6bffe01", "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 YouTube Tutorials/An_Intro_to_Markov_chains_with_Python!.ipynb", "max_forks_repo_name": "ad17171717/Workshops-2020-2021", "max_forks_repo_head_hexsha": "f0bcd92c9171ccc43a1a7ccb5ec645c4e6bffe01", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 30, "max_forks_repo_forks_event_min_datetime": "2020-08-28T02:20:39.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T05:38:30.000Z", "avg_line_length": 171.3671875, "max_line_length": 79126, "alphanum_fraction": 0.8719007457, "converted": true, "num_tokens": 4132, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037282594921, "lm_q2_score": 0.9304582487448422, "lm_q1q2_score": 0.8618869448021452}} {"text": "

A SymPy tutorial

\n\n

This tutorial provides an introduction to using SymPy within Julia. It owes an enormous debt to the tutorial for using SymPy within Python which may be found here. The overall structure and many examples are taken from that work, with adjustments and additions to illustrate the differences due to using SymPy within Julia.

\n\n

This tutorial can be read as an IJulia notebook here.

\n\n

After installing SymPy, which is discussed in the package's README file, we must first load it into Julia with the standard command using:

\n\n\n```julia\nusing SymPy\n```\n\n

The start up time is a bit lengthy.

\n\n

Symbols

\n\n

At the core of SymPy is the introduction of symbolic variables that differ quite a bit from Julia's variables. Symbolic variables do not immediately evaluate to a value, rather the \"symbolicness\" propagates when interacted with. To keep things manageable, SymPy does some simplifications along the way.

\n\n

Symbolic expressions are primarily of the Sym type and can be constructed in the standard way:

\n\n\n```julia\nx = Sym(\"x\")\n```\n\n\n\n\n\\begin{equation*}x\\end{equation*}\n\n\n\n

This creates a symbolic object x, which can be manipulated through further function calls.

\n\n

There is the @vars macro that makes creating multiple variables a bit less typing, as it creates variables in the local scope – no assignment is necessary. Compare these similar ways to create symbolic variables:

\n\n\n```julia\n@vars a b c\na,b,c = Sym(\"a,b,c\")\n```\n\n\n\n\n (a, b, c)\n\n\n\n

(There is the identical @syms for MATLAB users.)

\n\n

Assumptions

\n\n

Finally, there is the symbols constructor for producing symbolic objects. With symbols it is possible to pass assumptions onto the variables. A list of possible assumptions is here. Some examples are:

\n\n\n```julia\nu = symbols(\"u\")\nx = symbols(\"x\", real=true)\ny1, y2 = symbols(\"y1, y2\", positive=true)\nalpha = symbols(\"alpha\", integer=true, positive=true)\n```\n\n\n\n\n\\begin{equation*}\\alpha\\end{equation*}\n\n\n\n

As seen, the symbols function can be used to make one or more variables with zero, one or more assumptions.

\n\n

We jump ahead for a second to illustrate, but here we see that solve will respect these assumptions, by failing to find solutions to these equations:

\n\n\n```julia\nsolve(x^2 + 1) # ±i are not real\n```\n\n\n\n\n 0-element Array{Any,1}\n\n\n\n\n```julia\nsolve(y1 + 1) # -1 is not positive\n```\n\n\n\n\n 0-element Array{Any,1}\n\n\n\n

The @vars macro can also have assumptions passed in as follows:

\n\n\n```julia\n@vars u1 u2 positive=true\nsolve(u1 + u2) # empty, though solving u1 - u2 is not.\n```\n\n\n\n\n 0-element Array{Any,1}\n\n\n\n

As can be seen, there are several ways to create symbolic values. One caveat is that one can't use Sym to create a variable from a function name in Base.

\n\n

Special constants

\n\n

Julia has its math constants, like pi and e, SymPy as well. A few of these have Julia counterparts provided by SymPy. For example, these two constants are defined (where oo is for infinity):

\n\n\n```julia\nPI, oo\n```\n\n\n\n\n (pi, oo)\n\n\n\n

(The pretty printing of SymPy objects does not work for tuples.)

\n\n

Numeric values themselves can be symbolic. This example shows the difference. The first asin call dispatches to Julia's asin function, the second to SymPy's:

\n\n\n```julia\n[asin(1), asin(Sym(1))]\n```\n\n\n\n\n\\[ \\left[ \\begin{array}{r}1.5707963267949\\\\\\frac{\\pi}{2}\\end{array} \\right] \\]\n\n\n\n

Substitution

\n\n

SymPy provides a means to substitute values in for the symbolic expressions. The specification requires an expression, a variable in the expression to substitute in for, and a new value. For example, this is one way to make a polynomial in a new variable:

\n\n\n```julia\n@vars x y\nex = x^2 + 2x + 1\nex.subs(x, y)\n```\n\n\n\n\n\\begin{equation*}y^{2} + 2 y + 1\\end{equation*}\n\n\n\n

Substitution can also be numeric:

\n\n\n```julia\nex.subs(x, 0)\n```\n\n\n\n\n\\begin{equation*}1\\end{equation*}\n\n\n\n

The output has no free variables, but is still symbolic.

\n\n

Expressions with more than one variable can have multiple substitutions, where each is expressed as a tuple:

\n\n\n```julia\nx,y,z = symbols(\"x,y,z\")\nex = x + y + z\nex.subs((x,1), (y,pi))\n```\n\n\n\n\n\\begin{equation*}x + y + z\\end{equation*}\n\n\n\n

Note

The calling pattern for subs is different from a typical Julia function call. The subs call is object.method(arguments) whereas a more \"Julian\" function call is method(objects, other objects....), as Julia offers multiple dispatch of methods. SymPy uses the Python calling method, adding in Julian style when appropriate for generic usage within Julia. In addition, SymPy imports all functions from the underlying sympy module and specializes them on a symbolic first argument.

\n

For subs, the simple substitution ex.object(x,a) is similar to simple function evaluation, so Julia's call notation will work. To specify the pairing off of x and a, the => pairs notation is used.

\n
\n\n

This calling style will be equivalent to the last:

\n\n\n```julia\nex(x=>1, y=>pi)\n```\n\n\n\n\n\\begin{equation*}z + 4.14159265358979\\end{equation*}\n\n\n\n

A straight call is also possble, where the order of the variables is determined by free_symbols:

\n\n\n```julia\nex(1, pi)\n```\n\n\n\n\n\\begin{equation*}y + 4.14159265358979\\end{equation*}\n\n\n\n

This is useful for expressions of a single variable, but being more explicit through the use of paired values would be recommended.

\n\n

Conversion from symbolic to numeric

\n\n

SymPy provides two identical means to convert a symbolic math expression to a number. One is evalf, the other N. Within Julia we decouple this, using N to also convert to a Julian value and evalf to leave the conversion as a symbolic object. The N function converts symbolic integers, rationals, irrationals, and complex values, while attempting to find an appropriate Julia type for the value.

\n\n

To see the difference, we use both on PI:

\n\n\n```julia\nN(PI) # converts to underlying pi irrational\n```\n\n\n\n\n π = 3.1415926535897...\n\n\n\n

Whereas, evalf will produce a symbolic numeric value:

\n\n\n```julia\n(PI).evalf()\n```\n\n\n\n\n\\begin{equation*}3.14159265358979\\end{equation*}\n\n\n\n

The evalf call allows for a precision argument to be passed through the second argument. This is how 30 digits of $\\pi$ can be extracted:

\n\n\n```julia\nPI.evalf(30)\n```\n\n\n\n\n\\begin{equation*}3.14159265358979323846264338328\\end{equation*}\n\n\n\n

This is a SymPy, symbolic number, not a Julia object. Composing with N

\n\n\n```julia\nN(PI.evalf(30))\n```\n\n\n\n\n 3.141592653589793238462643383279999999999999999999999999999999999999999999999985\n\n\n\n

will produce a Julia number,

\n\n

Explicit conversion via convert(T, ex) can also be done, and is necessary at times if N does not give the desired type.

\n\n

Algebraic expressions

\n\n

SymPy overloads many of Julia's functions to work with symbolic objects, such as seen above with asin. The usual mathematical operations such as +, *, -, / etc. work through Julia's promotion mechanism, where numbers are promoted to symbolic objects, others dispatch internally to related SymPy functions.

\n\n

In most all cases, thinking about this distinction between numbers and symbolic numbers is unnecessary, as numeric values passed to SymPy functions are typically promoted to symbolic expressions. This conversion will take math constants to their corresponding SymPy counterpart, rational expressions to rational expressions, and floating point values to floating point values. However there are edge cases. An expression like 1//2 * pi * x will differ from the seemingly identical 1//2 * (pi * x). The former will produce a floating point value from 1//2 * pi before being promoted to a symbolic instance. Using the symbolic value PI makes this expression work either way.

\n\n

Most of Julia's mathematical functions are overloaded to work with symbolic expressions. Julia's generic definitions are used, as possible. This also introduces some edge cases. For example, x^(-2) will balk due to the negative, integer exponent, but either x^(-2//1) or x^Sym(-2) will work as expected, as the former call first dispatches to a generic defintion, but the latter two expressions do not.

\n\n

SymPy makes it very easy to work with polynomial and rational expressions. First we create some variables:

\n\n\n```julia\n@vars x y z\n```\n\n\n\n\n (x, y, z)\n\n\n\n

The expand, factor, collect, and simplify functions

\n\n

A typical polynomial expression in a single variable can be written in two common ways, expanded or factored form. Using factor and expand can move between the two.

\n\n

For example,

\n\n\n```julia\np = x^2 + 3x + 2\nfactor(p)\n```\n\n\n\n\n\\begin{equation*}\\left(x + 1\\right) \\left(x + 2\\right)\\end{equation*}\n\n\n\n

Or

\n\n\n```julia\nexpand(prod((x-i) for i in 1:5))\n```\n\n\n\n\n\\begin{equation*}x^{5} - 15 x^{4} + 85 x^{3} - 225 x^{2} + 274 x - 120\\end{equation*}\n\n\n\n

The factor function factors over the rational numbers, so something like this with obvious factors is not finished:

\n\n\n```julia\nfactor(x^2 - 2)\n```\n\n\n\n\n\\begin{equation*}x^{2} - 2\\end{equation*}\n\n\n\n

When expressions involve one or more variables, it can be convenient to be able to manipulate them. For example, if we define q by:

\n\n\n```julia\nq = x*y + x*y^2 + x^2*y + x\n```\n\n\n\n\n\\begin{equation*}x^{2} y + x y^{2} + x y + x\\end{equation*}\n\n\n\n

Then we can collect the terms by the variable x:

\n\n\n```julia\ncollect(q, x)\n```\n\n\n\n\n\\begin{equation*}x^{2} y + x \\left(y^{2} + y + 1\\right)\\end{equation*}\n\n\n\n

or the variable y:

\n\n\n```julia\ncollect(q, y)\n```\n\n\n\n\n\\begin{equation*}x y^{2} + x + y \\left(x^{2} + x\\right)\\end{equation*}\n\n\n\n

These are identical expressions, though viewed differently.

\n\n

A more broad-brush approach is to let SymPy simplify the values. In this case, the common value of x is factored out:

\n\n\n```julia\nsimplify(q)\n```\n\n\n\n\n\\begin{equation*}x \\left(x y + y^{2} + y + 1\\right)\\end{equation*}\n\n\n\n

The simplify function attempts to apply the dozens of functions related to simplification that are part of SymPy. It is also possible to apply these functions one at a time, for example trigsimp does trigonometric simplifications.

\n\n

The SymPy tutorial illustrates that expand can also result in simplifications through this example:

\n\n\n```julia\nexpand((x + 1)*(x - 2) - (x - 1)*x)\n```\n\n\n\n\n\\begin{equation*}-2\\end{equation*}\n\n\n\n

These methods are not restricted to polynomial expressions and will work with other expressions. For example, factor identifies the following as a factorable object in terms of the variable exp(x):

\n\n\n```julia\nfactor(exp(2x) + 3exp(x) + 2)\n```\n\n\n\n\n\\begin{equation*}\\left(e^{x} + 1\\right) \\left(e^{x} + 2\\right)\\end{equation*}\n\n\n\n

Rational expressions: apart, together, cancel

\n\n

When working with rational expressions, SymPy does not do much simplification unless asked. For example this expression is not simplified:

\n\n\n```julia\nr = 1/x + 1/x^2\n```\n\n\n\n\n\\begin{equation*}\\frac{1}{x} + \\frac{1}{x^{2}}\\end{equation*}\n\n\n\n

To put the terms of r over a common denominator, the together function is available:

\n\n\n```julia\ntogether(r)\n```\n\n\n\n\n\\begin{equation*}\\frac{x + 1}{x^{2}}\\end{equation*}\n\n\n\n

The apart function does the reverse, creating a partial fraction decomposition from a ratio of polynomials:

\n\n\n```julia\napart( (4x^3 + 21x^2 + 10x + 12) / (x^4 + 5x^3 + 5x^2 + 4x))\n```\n\n\n\n\n\\begin{equation*}\\frac{2 x - 1}{x^{2} + x + 1} - \\frac{1}{x + 4} + \\frac{3}{x}\\end{equation*}\n\n\n\n

Some times SymPy will cancel factors, as here:

\n\n\n```julia\ntop = (x-1)*(x-2)*(x-3)\nbottom = (x-1)*(x-4)\ntop/bottom\n```\n\n\n\n\n\\begin{equation*}\\frac{\\left(x - 3\\right) \\left(x - 2\\right)}{x - 4}\\end{equation*}\n\n\n\n

(This might make math faculty a bit upset, but it is in line with student thinking.)

\n\n

However, with expanded terms, the common factor of (x-1) is not cancelled:

\n\n\n```julia\nr = expand(top) / expand(bottom)\n```\n\n\n\n\n\\begin{equation*}\\frac{x^{3} - 6 x^{2} + 11 x - 6}{x^{2} - 5 x + 4}\\end{equation*}\n\n\n\n

The cancel function instructs SymPy to perform cancellations. It takes rational functions and puts them in a canonical $p/q$ form with no common (rational) factors and leading terms which are integers:

\n\n\n```julia\ncancel(r)\n```\n\n\n\n\n\\begin{equation*}\\frac{x^{2} - 5 x + 6}{x - 4}\\end{equation*}\n\n\n\n

Powers

\n\n

The SymPy tutorial offers a thorough explanation on powers and which get simplified and under what conditions. Basically

\n\n
    \n
  • $x^a x^b = x^{a+b}$\n

    is always true. However

    \n
  • \n
  • $x^a y^a=(xy)^a$\n

    is only true with assumptions, such as $x,y \\geq 0$ and $a$ is real, but not in general. For example, $x=y=-1$ and $a=1/2$ has $x^a \\cdot y^a = i \\cdot i = -1$, where as $(xy)^a = 1$.

    \n
  • \n
  • $(x^a)^b = x^{ab}$\n

    is only true with assumptions. For example $x=-1, a=2$, and $b=1/2$ gives $(x^a)^b = 1^{1/2} = 1$, whereas $x^{ab} = -1^1 = -1$.

    \n
  • \n
\n\n

We see that with assumptions, the following expression does simplify to $0$:

\n\n\n```julia\n@vars x y nonnegative=true a real=true\nsimplify(x^a * y^a - (x*y)^a)\n```\n\n\n\n\n\\begin{equation*}0\\end{equation*}\n\n\n\n

However, without assumptions this is not the case

\n\n\n```julia\nx,y,a = symbols(\"x,y,a\")\nsimplify(x^a * y^a - (x*y)^a)\n```\n\n\n\n\n\\begin{equation*}x^{a} y^{a} - \\left(x y\\right)^{a}\\end{equation*}\n\n\n\n

The simplify function calls powsimp to simplify powers, as above. The powsimp function has the keyword argument force=true to force simplification even if assumptions are not specified:

\n\n\n```julia\npowsimp(x^a * y^a - (x*y)^a, force=true)\n```\n\n\n\n\n\\begin{equation*}0\\end{equation*}\n\n\n\n

Trigonometric simplification

\n\n

For trigonometric expressions, simplify will use trigsimp to simplify:

\n\n\n```julia\ntheta = symbols(\"theta\", real=true)\np = cos(theta)^2 + sin(theta)^2\n```\n\n\n\n\n\\begin{equation*}\\sin^{2}{\\left (\\theta \\right )} + \\cos^{2}{\\left (\\theta \\right )}\\end{equation*}\n\n\n\n

Calling either simplify or trigsimp will apply the Pythagorean identity:

\n\n\n```julia\nsimplify(p)\n```\n\n\n\n\n\\begin{equation*}1\\end{equation*}\n\n\n\n

While often forgotten, the trigsimp function is, of course, aware of the double angle formulas:

\n\n\n```julia\nsimplify(sin(2theta) - 2sin(theta)*cos(theta))\n```\n\n\n\n\n\\begin{equation*}0\\end{equation*}\n\n\n\n

The expand_trig function will expand such expressions:

\n\n\n```julia\nexpand_trig(sin(2theta))\n```\n\n\n\n\n\\begin{equation*}2 \\sin{\\left (\\theta \\right )} \\cos{\\left (\\theta \\right )}\\end{equation*}\n\n\n\n

Coefficients

\n\n

Returning to polynomials, there are a few functions to find various pieces of the polynomials. First we make a general quadratic polynomial:

\n\n\n```julia\na,b,c,x = symbols(\"a, b, c, x\")\np = a*x^2 + b*x + c\n```\n\n\n\n\n\\begin{equation*}a x^{2} + b x + c\\end{equation*}\n\n\n\n

If given a polynomial, like p, there are different means to extract the coefficients:

\n\n
    \n
  • SymPy provides a coeffs method for Poly objects, but p must first be converted to one.

    \n
  • \n
  • SymPy provides the coeff method for expressions, which allows extration of a coeffiecient for a given monomial

    \n
  • \n
\n\n

The ex.coeff(monom) call will return the corresponding coefficient of the monomial:

\n\n\n```julia\np.coeff(x^2) # a\np.coeff(x) # b\n```\n\n\n\n\n\\begin{equation*}b\\end{equation*}\n\n\n\n

The constant can be found through substitution:

\n\n\n```julia\np(x=>0)\n```\n\n\n\n\n\\begin{equation*}c\\end{equation*}\n\n\n\n

Though one could use some trick like this to find all the coefficients:

\n\n\n```julia\nSym[[p.coeff(x^i) for i in N(degree(p,gen=x)):-1:1]; p(x=>0)]\n```\n\n\n\n\n\\[ \\left[ \\begin{array}{r}a\\\\b\\\\c\\end{array} \\right] \\]\n\n\n\n

that is cumbersome, at best. SymPy has a function coeffs, but it is defined for polynomial types, so will fail on p:

\n\n\n```julia\np.coeffs() # fails\n```\n\n\n\n\n KeyError(\"coeffs\")\n\n\n\n\n

Polynomials are a special class in SymPy and must be constructed. The Poly constructor can be used. As there is more than one free variable in p, we specify the variable x below:

\n\n\n```julia\nq = sympy.Poly(p, x)\nq.coeffs()\n```\n\n\n\n\n\\[ \\left[ \\begin{array}{r}a\\\\b\\\\c\\end{array} \\right] \\]\n\n\n\n

Note

The Poly constructor from SymPy is not a function, so is not exported when SymPy is loaded. To access it, the object must be qualified by its containing module, in this case Poly. Were it to be used frequently, an alias could be used, as in const Poly=sympy.Poly or the import_from function, as in import_from(sympy, :Poly). The latter has some attempt to avoid naming collisions.

\n
\n\n

Polynomial roots: solve, real_roots, polyroots, nroots

\n\n

SymPy provides functions to find the roots of a polynomial. In general, a polynomial with real coefficients of degree $n$ will have $n$ roots when multiplicities and complex roots are accounted for. The number of real roots is consequently between $0$ and $n$.

\n\n

For a univariate polynomial expression (a single variable), the real roots, when available, are returned by roots. For example,

\n\n\n```julia\nreal_roots(x^2 - 2)\n```\n\n\n\n\n\\[ \\left[ \\begin{array}{r}- \\sqrt{2}\\\\\\sqrt{2}\\end{array} \\right] \\]\n\n\n\n

Unlike factor – which only factors over rational factors – real_roots finds the two irrational roots here. It is well known (the Abel-Ruffini theorem) that for degree 5 polynomials, or higher, it is not always possible to express the roots in terms of radicals. However, when the roots are rational SymPy can have success:

\n\n\n```julia\np = (x-3)^2*(x-2)*(x-1)*x*(x+1)*(x^2 + x + 1)\nreal_roots(p)\n```\n\n\n\n\n\\[ \\left[ \\begin{array}{r}-1\\\\0\\\\1\\\\2\\\\3\\\\3\\end{array} \\right] \\]\n\n\n\n

In this example, the degree of p is 8, but only the 6 real roots returned, the double root of $3$ is accounted for. The two complex roots of x^2 + x+ 1 are not considered by this function. The complete set of distinct roots can be found with solve:

\n\n\n```julia\nsolve(p)\n```\n\n\n\n\n\\[ \\left[ \\begin{array}{r}-1\\\\0\\\\1\\\\2\\\\3\\\\- \\frac{1}{2} - \\frac{\\sqrt{3} i}{2}\\\\- \\frac{1}{2} + \\frac{\\sqrt{3} i}{2}\\end{array} \\right] \\]\n\n\n\n

This finds the complex roots, but does not account for the double root. The roots function of SymPy does.

\n\n

The output of calling roots will be a dictionary whose keys are the roots and values the multiplicity.

\n\n\n```julia\nroots(p)\n```\n\n\n\n\n Dict{Any,Any} with 7 entries:\n 1 => 1\n -1/2 - sqrt(3)*I/2 => 1\n -1/2 + sqrt(3)*I/2 => 1\n 3 => 2\n 0 => 1\n -1 => 1\n 2 => 1\n\n\n\n

When exact answers are not provided, the roots call is contentless:

\n\n\n```julia\np = x^5 - x + 1\nroots(p)\n```\n\n\n\n\n Dict{Any,Any} with 0 entries\n\n\n\n

Calling solve seems to produce very little as well:

\n\n\n```julia\nrts = solve(p)\n```\n\n\n\n\n\\[ \\left[ \\begin{array}{r}\\operatorname{CRootOf} {\\left(x^{5} - x + 1, 0\\right)}\\\\\\operatorname{CRootOf} {\\left(x^{5} - x + 1, 1\\right)}\\\\\\operatorname{CRootOf} {\\left(x^{5} - x + 1, 2\\right)}\\\\\\operatorname{CRootOf} {\\left(x^{5} - x + 1, 3\\right)}\\\\\\operatorname{CRootOf} {\\left(x^{5} - x + 1, 4\\right)}\\end{array} \\right] \\]\n\n\n\n

But in fact, rts contains lots of information. We can extract numeric values quite easily with N:

\n\n\n```julia\nN.(rts)\n```\n\n\n\n\n 5-element Array{Number,1}:\n -1.167303978261418684256045899854842180720560371525489039140082449275651903429536\n -0.18123244446987538 - 1.0839541013177107im \n -0.18123244446987538 + 1.0839541013177107im \n 0.7648844336005847 - 0.35247154603172626im \n 0.7648844336005847 + 0.35247154603172626im \n\n\n\n

These are numeric approximations to irrational values. For numeric approximations to polynomial roots, the nroots function is also provided, though with this call the answers are still symbolic:

\n\n\n```julia\nnroots(p)\n```\n\n\n\n\n\\[ \\left[ \\begin{array}{r}-1.16730397826142\\\\-0.181232444469875 - 1.08395410131771 i\\\\-0.181232444469875 + 1.08395410131771 i\\\\0.764884433600585 - 0.352471546031726 i\\\\0.764884433600585 + 0.352471546031726 i\\end{array} \\right] \\]\n\n\n\n

The solve function

\n\n

The solve function is more general purpose than just finding roots of univariate polynomials. The function tries to solve for when an expression is 0, or a set of expressions are all 0.

\n\n

For example, it can be used to solve when $\\cos(x) = \\sin(x)$:

\n\n\n```julia\nsolve(cos(x) - sin(x))\n```\n\n\n\n\n\\[ \\left[ \\begin{array}{r}- \\frac{3 \\pi}{4}\\\\\\frac{\\pi}{4}\\end{array} \\right] \\]\n\n\n\n

Though there are infinitely many correct solutions, these are within a certain range.

\n\n

The solveset function appears in version 1.0 of SymPy and is an intended replacement for solve. Here we see it gives all solutions:

\n\n\n```julia\nu = solveset(cos(x) - sin(x))\n```\n\n\n\n\n\\begin{equation*}\\left\\{2 n \\pi + \\frac{5 \\pi}{4}\\; |\\; n \\in \\mathbb{Z}\\right\\} \\cup \\left\\{2 n \\pi + \\frac{\\pi}{4}\\; |\\; n \\in \\mathbb{Z}\\right\\}\\end{equation*}\n\n\n\n

The output of solveset is a set, rather than a vector or dictionary. To get the values requires some work. For finite sets we collect the elements with collect, but first we must convert to a Julia Set:

\n\n\n```julia\nv = solveset(x^2 - 4)\ncollect(Set(v...))\n```\n\n\n\n\n 2-element Array{Any,1}:\n -2\n 2\n\n\n\n

This composition is done in the elements function:

\n\n\n```julia\nelements(v)\n```\n\n\n\n\n\\[ \\left[ \\begin{array}{r}-2\\\\2\\end{array} \\right] \\]\n\n\n\n

The elements function does not work for more complicated (non-finite) sets, such as u. For these, the contains method may be useful to query the underlying elements

\n\n

Solving within Sympy has limits. For example, there is no symbolic solution here:

\n\n\n```julia\nsolve(cos(x) - x)\n```\n\n\n\n\n PyError ($(Expr(:escape, :(ccall(#= /Users/verzani/.julia/packages/PyCall/a5Jd3/src/pyfncall.jl:44 =# @pysym(:PyObject_Call), PyPtr, (PyPtr, PyPtr, PyPtr), o, pyargsptr, kw))))) \n NotImplementedError('multiple generators [x, cos(x)]\\nNo algorithms are implemented to solve equation -x + cos(x)')\n File \"/Users/verzani/.julia/conda/3/lib/python3.7/site-packages/sympy/solvers/solvers.py\", line 1162, in solve\n solution = _solve(f[0], *symbols, **flags)\n File \"/Users/verzani/.julia/conda/3/lib/python3.7/site-packages/sympy/solvers/solvers.py\", line 1735, in _solve\n raise NotImplementedError('\\n'.join([msg, not_impl_msg % f]))\n \n\n\n\n\n

(And hence the error message generated.)

\n\n

For such an equation, a numeric method would be needed, similar to the Roots package. For example:

\n\n\n```julia\nnsolve(cos(x) - x, 1)\n```\n\n\n\n\n\\begin{equation*}0.7390851332151606416553120876738734040134117589007574649656806357732846548836\\end{equation*}\n\n\n\n

Though it can't solve everything, the solve function can also solve equations of a more general type. For example, here it is used to derive the quadratic equation:

\n\n\n```julia\na,b,c = symbols(\"a,b,c\", real=true)\np = a*x^2 + b*x + c\nsolve(p, x)\n```\n\n\n\n\n\\[ \\left[ \\begin{array}{r}\\frac{- b + \\sqrt{- 4 a c + b^{2}}}{2 a}\\\\- \\frac{b + \\sqrt{- 4 a c + b^{2}}}{2 a}\\end{array} \\right] \\]\n\n\n\n

The extra argument x is passed to solve so that solve knows which variable to solve for.

\n\n

The solveset function is similar:

\n\n\n```julia\nsolveset(p, x)\n```\n\n\n\n\n\\begin{equation*}\\left\\{- \\frac{b}{2 a} - \\frac{\\sqrt{- 4 a c + b^{2}}}{2 a}, - \\frac{b}{2 a} + \\frac{\\sqrt{- 4 a c + b^{2}}}{2 a}\\right\\}\\end{equation*}\n\n\n\n

If the x value is not given, solveset will complain and solve tries to find a solution with all the free variables:

\n\n\n```julia\nsolve(p)\n```\n\n\n\n\n 1-element Array{Dict{Any,Any},1}:\n Dict(a=>-(b*x + c)/x^2)\n\n\n\n

Systems of equations can be solved as well. We specify them within a vector of expressions, [ex1, ex2, ..., exn] where a found solution is one where all the expressions are 0. For example, to solve this linear system: $2x + 3y = 6, 3x - 4y=12$, we have:

\n\n\n```julia\nx, y = symbols(\"x,y\", real=true)\nexs = [2x+3y-6, 3x-4y-12]\nd = solve(exs)\n```\n\n\n\n\n Dict{Any,Any} with 2 entries:\n x => 60/17\n y => -6/17\n\n\n\n

We can \"check our work\" by plugging into each equation. We take advantage of how the subs function allows us to pass in a dictionary:

\n\n\n```julia\nmap(ex -> ex.subs(d), exs)\n```\n\n\n\n\n\\[ \\left[ \\begin{array}{r}0\\\\0\\end{array} \\right] \\]\n\n\n\n

In the previous example, the system had two equations and two unknowns. When that is not the case, one can specify the variables to solve for as a vector. In this example, we find a quadratic polynomial that approximates $\\cos(x)$ near $0$:

\n\n\n```julia\na,b,c,h = symbols(\"a,b,c,h\", real=true)\np = a*x^2 + b*x + c\nfn = cos\nexs = [fn(0*h)-p(x=>0), fn(h)-p(x => h), fn(2h)-p(x => 2h)]\nd = solve(exs, [a,b,c])\n```\n\n\n\n\n Dict{Any,Any} with 3 entries:\n a => (-2*cos(h) + cos(2*h) + 1)/(2*h^2)\n b => (4*cos(h) - cos(2*h) - 3)/(2*h)\n c => 1\n\n\n\n

Again, a dictionary is returned. The polynomial itself can be found by substituting back in for a, b, and c:

\n\n\n```julia\nquad_approx = p.subs(d)\n```\n\n\n\n\n\\begin{equation*}1 + \\frac{x \\left(4 \\cos{\\left (h \\right )} - \\cos{\\left (2 h \\right )} - 3\\right)}{2 h} + \\frac{x^{2} \\left(- 2 \\cos{\\left (h \\right )} + \\cos{\\left (2 h \\right )} + 1\\right)}{2 h^{2}}\\end{equation*}\n\n\n\n

(Taking the limit as $h$ goes to 0 produces the answer $1 - x^2/2$.)

\n\n

Finally for solve, we show one way to re-express the polynomial $a_2x^2 + a_1x + a_0$ as $b_2(x-c)^2 + b_1(x-c) + b_0$ using solve (and not, say, an expansion theorem.)

\n\n\n```julia\nn = 3\nx, c = symbols(\"x,c\")\nas = Sym[\"a$i\" for i in 0:(n-1)]\nbs = Sym[\"b$i\" for i in 0:(n-1)]\np = sum([as[i+1]*x^i for i in 0:(n-1)])\nq = sum([bs[i+1]*(x-c)^i for i in 0:(n-1)])\nsolve(p-q, bs)\n```\n\n\n\n\n Dict{Any,Any} with 3 entries:\n b2 => a2\n b0 => a0 + a1*c + a2*c^2\n b1 => a1 + 2*a2*c\n\n\n\n

Solving using logical operators

\n\n

The solve function does not need to just solve ex = 0. There are other means to specify an equation. Ideally, it would be nice to say ex1 == ex2, but the interpretation of == is not for this. Rather, SymPy introduces Eq for equality. So this expression

\n\n\n```julia\nsolve(Eq(x, 1))\n```\n\n\n\n\n\\[ \\left[ \\begin{array}{r}1\\end{array} \\right] \\]\n\n\n\n

gives 1, as expected from solving x == 1.

\n\n

In addition to Eq, there are Lt, Le, Ge, Gt. The Unicode operators are not aliased to these, but there are alternatives \\ll[tab], \\leqq[tab], \\Equal[tab], \\geqq[tab], \\gg[tab] and \\neg[tab] to negate.

\n\n

So, the above could have been written with the following nearly identical expression, though it is entered with \\Equal[tab].

\n\n\n```julia\nsolve(x ⩵ 1)\n```\n\n\n\n\n\\[ \\left[ \\begin{array}{r}1\\end{array} \\right] \\]\n\n\n\n

Here is an alternative way of asking a previous question on a pair of linear equations:

\n\n\n```julia\nx, y = symbols(\"x,y\", real=true)\nexs = [2x+3y ⩵ 6, 3x-4y ⩵ 12] ## Using \\Equal[tab]\nd = solve(exs)\n```\n\n\n\n\n Dict{Any,Any} with 2 entries:\n x => 60/17\n y => -6/17\n\n\n\n

Plotting

\n\n

The Plots package allows many 2-dimensional plots of SymPy objects to be agnostic as to a backend plotting package. SymPy provides recipes that allow symbolic expressions to be used where functions are part of the Plots interface. [See the help page for sympy_plotting.]

\n\n

In particular, the following methods of plot are defined:

\n\n
    \n
  • plot(ex::Sym, a, b) will plot the expression of single variable over the interval [a,b]

    \n
  • \n
  • plot!(ex::Sym, a, b) will add to the current plot a plot of the expression of single variable over the interval [a,b]

    \n
  • \n
  • plot(exs::Vector{Sym}, a, b) will plot each expression over [a,b]

    \n
  • \n
  • plot(ex1, ex2, a, b) will plot a parametric plot of the two expressions over the interval [a,b].

    \n
  • \n
  • contour(xs, ys, ex::Sym) will make a contour plot of the expression of two variables over the grid specifed by the xs and ys.

    \n
  • \n
  • surface(xs, ys, ex::Sym) will make a surface plot of the expression of two variables over the grid specifed by the xs and ys.

    \n
  • \n
\n\n

For example:

\n\n\n```julia\nx = symbols(\"x\")\nusing Plots\npyplot()\n#\nplot(x^2 - 2, -2,2)\n```\n\n

Or a parametric plot:

\n\n\n```julia\nplot(sin(2x), cos(3x), 0, 4pi)\n```\n\n

For plotting with other plotting packages, it is generally faster to first call lambdify on the expression and then generate y values with the resulting Julia function.

\n\n
\n\n

In addition, with PyPlot a few other plotting functions from SymPy are available from its interface to MatplotLib:

\n\n
    \n
  • plot3d_parametric_surface(ex1::Sym, ex2::Sym, ex3::Sym), (uvar, a0, b0), (vvar, a1, b1)) – make a surface plot of the expressions parameterized by the region [a0,b0] x [a1,b1]. The default region is [-5,5]x[-5,5] where the ordering of the variables is given by free_symbols(ex).

    \n
  • \n
  • plot_implicit(predictate, (xvar, a0, b0), (yvar, a1, b1)) – make

    \n
  • \n
\n\n

an implicit equation plot of the expressions over the region [a0,b0] x [a1,b1]. The default region is [-5,5]x[-5,5] where the ordering of the variables is given by free_symbols(ex). To create predicates from the variable, the functions Lt, Le, Eq, Ge, and Gt can be used, as with Lt(x*y, 1). For infix notation, unicode operators can be used: \\ll<tab>, \\leqq<tab>, \\Equal<tab>, \\geqq<tab>, and \\gg<tab>. For example, x*y ≪ 1. To combine terms, the unicode \\vee<tab> (for \"or\"), \\wedge<tab> (for \"and\") can be used.

\n\n

Calculus

\n\n

SymPy has many of the basic operations of calculus provided through a relatively small handful of functions.

\n\n

Limits

\n\n

Limits are computed by the limit function which takes an expression, a variable and a value, and optionally a direction specified by either dir="+" or dir="-".

\n\n

For example, this shows Gauss was right:

\n\n\n```julia\nlimit(sin(x)/x, x, 0)\n```\n\n\n\n\n\\begin{equation*}1\\end{equation*}\n\n\n\n

Alternatively, the second and third arguments can be specified as a pair:

\n\n\n```julia\nlimit(sin(x)/x, x=>0)\n```\n\n\n\n\n\\begin{equation*}1\\end{equation*}\n\n\n\n

Limits at infinity are done by using oo for $\\infty$:

\n\n\n```julia\nlimit((1+1/x)^x, x => oo)\n```\n\n\n\n\n\\begin{equation*}e\\end{equation*}\n\n\n\n

This example computes what L'Hopital reportedly paid a Bernoulli for

\n\n\n```julia\na = symbols(\"a\", positive=true)\nex = (sqrt(2a^3*x-x^4) - a*(a^2*x)^(1//3)) / (a - (a*x^3)^(1//4))\n```\n\n\n\n\n\\begin{equation*}\\frac{- a^{\\frac{5}{3}} \\sqrt[3]{x} + \\sqrt{2 a^{3} x - x^{4}}}{- \\sqrt[4]{a} \\sqrt[4]{x^{3}} + a}\\end{equation*}\n\n\n\n

Substituting $x=a$ gives an indeterminate form:

\n\n\n```julia\nex(x=>a) # or subs(ex, x, a)\n```\n\n\n\n\n\\begin{equation*}\\mathrm{NaN}\\end{equation*}\n\n\n\n

We can see it is of the form $0/0$:

\n\n\n```julia\ndenom(ex)(x => a), numer(ex)(x => a)\n```\n\n\n\n\n (0, 0)\n\n\n\n

And we get

\n\n\n```julia\nlimit(ex, x => a)\n```\n\n\n\n\n\\begin{equation*}\\frac{16 a}{9}\\end{equation*}\n\n\n\n

In a previous example, we defined quad_approx:

\n\n\n```julia\nquad_approx\n```\n\n\n\n\n\\begin{equation*}1 + \\frac{x \\left(4 \\cos{\\left (h \\right )} - \\cos{\\left (2 h \\right )} - 3\\right)}{2 h} + \\frac{x^{2} \\left(- 2 \\cos{\\left (h \\right )} + \\cos{\\left (2 h \\right )} + 1\\right)}{2 h^{2}}\\end{equation*}\n\n\n\n

The limit as h goes to $0$ gives 1 - x^2/2, as expected:

\n\n\n```julia\nlimit(quad_approx, h => 0)\n```\n\n\n\n\n\\begin{equation*}- \\frac{x^{2}}{2} + 1\\end{equation*}\n\n\n\n

Left and right limits

\n\n

The limit is defined when both the left and right limits exist and are equal. But left and right limits can exist and not be equal. The sign function is $1$ for positive $x$, $-1$ for negative $x$ and $0$ when $x$ is 0. It should not have a limit at $0$:

\n\n\n```julia\nlimit(sign(x), x => 0)\n```\n\n\n\n\n\\begin{equation*}1\\end{equation*}\n\n\n\n

Oops. Well, the left and right limits are different anyways:

\n\n\n```julia\nlimit(sign(x), x => 0, dir=\"-\"), limit(sign(x), x => 0, dir=\"+\")\n```\n\n\n\n\n (-1, 1)\n\n\n\n

(The limit function finds the right limit by default. To be careful, either plot or check that both the left and right limit exist and are equal.)

\n\n

Numeric limits

\n\n

The limit function uses the Gruntz algorithm. It is far more reliable then simple numeric attempts at limits. An example of Gruntz is the right limit at $0$ of the function:

\n\n\n```julia\nf(x) = 1/x^(log(log(log(log(1/x)))) - 1)\n```\n\n\n\n\n f (generic function with 1 method)\n\n\n\n

A numeric attempt might be done along these lines:

\n\n\n```julia\nhs = [10.0^(-i) for i in 6:16]\nys = [f(h) for h in hs]\n[hs ys]\n```\n\n\n\n\n 11×2 Array{Float64,2}:\n 1.0e-6 6.14632e-7 \n 1.0e-7 1.42981e-7 \n 1.0e-8 3.43858e-8 \n 1.0e-9 8.52992e-9 \n 1.0e-10 2.17687e-9 \n 1.0e-11 5.70097e-10\n 1.0e-12 1.52866e-10\n 1.0e-13 4.18839e-11\n 1.0e-14 1.17057e-11\n 1.0e-15 3.33197e-12\n 1.0e-16 9.64641e-13\n\n\n\n

With a values appearing to approach $0$. However, in fact these values will ultimately head off to $\\infty$:

\n\n\n```julia\nlimit(f(x), x, 0, dir=\"+\")\n```\n\n\n\n\n\\begin{equation*}\\infty\\end{equation*}\n\n\n\n

Derivatives

\n\n

One could use limits to implement the definition of a derivative:

\n\n\n```julia\nx, h = symbols(\"x,h\")\nf(x) = exp(x)*sin(x)\nlimit((f(x+h) - f(x)) / h, h, 0)\n```\n\n\n\n\n\\begin{equation*}e^{x} \\sin{\\left (x \\right )} + e^{x} \\cos{\\left (x \\right )}\\end{equation*}\n\n\n\n

However, it would be pretty inefficient, as SymPy already does a great job with derivatives. The diff function implements this. The basic syntax is diff(ex, x) to find the first derivative in x of the expression in ex, or its generalization to $k$th derivatives with diff(ex, x, k).

\n\n

The same derivative computed above by a limit could be found with:

\n\n\n```julia\ndiff(f(x), x)\n```\n\n\n\n\n\\begin{equation*}e^{x} \\sin{\\left (x \\right )} + e^{x} \\cos{\\left (x \\right )}\\end{equation*}\n\n\n\n

Similarly, we can compute other derivatives:

\n\n\n```julia\ndiff(x^x, x)\n```\n\n\n\n\n\\begin{equation*}x^{x} \\left(\\log{\\left (x \\right )} + 1\\right)\\end{equation*}\n\n\n\n

Or

\n\n\n```julia\ndiff(exp(-x^2), x, 2)\n```\n\n\n\n\n\\begin{equation*}2 \\left(2 x^{2} - 1\\right) e^{- x^{2}}\\end{equation*}\n\n\n\n

As an alternate to specifying the number of derivatives, multiple variables can be passed to diff:

\n\n\n```julia\ndiff(exp(-x^2), x, x, x) # same as diff(..., x, 3)\n```\n\n\n\n\n\\begin{equation*}4 x \\left(- 2 x^{2} + 3\\right) e^{- x^{2}}\\end{equation*}\n\n\n\n

This could include variables besides x.

\n\n

The output is a simple expression, so diff can be composed with other functions, such as solve. For example, here we find the critical points where the derivative is $0$ of some rational function:

\n\n\n```julia\nf(x) = (12x^2 - 1) / (x^3)\ndiff(f(x), x) |> solve\n```\n\n\n\n\n\\[ \\left[ \\begin{array}{r}- \\frac{1}{2}\\\\\\frac{1}{2}\\end{array} \\right] \\]\n\n\n\n

Partial derivatives

\n\n

The diff function makes finding partial derivatives as easy as specifying the variable to differentiate in. This example computes the mixed partials of an expression in x and y:

\n\n\n```julia\nx,y = symbols(\"x,y\")\nex = x^2*cos(y)\nSym[diff(ex,v1, v2) for v1 in [x,y], v2 in [x,y]]\n```\n\n\n\n\n\\[\\left[ \\begin{array}{rr}2 \\cos{\\left (y \\right )}&- 2 x \\sin{\\left (y \\right )}\\\\- 2 x \\sin{\\left (y \\right )}&- x^{2} \\cos{\\left (y \\right )}\\end{array}\\right]\\]\n\n\n\n

The extra Sym, of the form T[], helps Julia resolve the type of the output.

\n\n

Unevaluated derivatives

\n\n

The Derivative constructor provides unevaluated derivatives, useful with differential equations and the output for unknown functions. Here is an example:

\n\n\n```julia\nex = sympy.Derivative(exp(x*y), x, y, 2)\n```\n\n\n\n\n\\begin{equation*}\\frac{\\partial^{3}}{\\partial y^{2}\\partial x} e^{x y}\\end{equation*}\n\n\n\n

(The y,2 is a replacement for y,y which makes higher order terms easier to type.) These expressions are evaluated with the doit method:

\n\n\n```julia\nex.doit()\n```\n\n\n\n\n\\begin{equation*}x \\left(x y + 2\\right) e^{x y}\\end{equation*}\n\n\n\n

Implicit derivatives

\n\n

SymPy can be used to find derivatives of implicitly defined functions. For example, the task of finding $dy/dx$ for the equation:

\n\n\n$$\ny^4 - x^4 -y^2 + 2x^2 = 0\n$$\n\n\n

As with the mathematical solution, the key is to treat one of the variables as depending on the other. In this case, we think of $y$ locally as a function of $x$. SymPy allows us to create symbolic functions, and we will use one to substitute in for y.

\n\n

In SymPy, symbolic functions use the class name \"Function\", but in SymPy we use SymFunction to avoid a name collision with one of Julia's primary types. The constructor can be used as SymFunction(:F):

\n\n\n```julia\nF, G = SymFunction(\"F\"), SymFunction(\"G\")\n```\n\n\n\n\n (F, G)\n\n\n\n

We can call these functions, but we get a function expression:

\n\n\n```julia\nF(x)\n```\n\n\n\n\n\\begin{equation*}F{\\left (x \\right )}\\end{equation*}\n\n\n\n

SymPy can differentiate symbolically, again with diff:

\n\n\n```julia\ndiff(F(x))\n```\n\n\n\n\n\\begin{equation*}\\frac{d}{d x} F{\\left (x \\right )}\\end{equation*}\n\n\n\n

Of for symbolic functions the more natural F'(x).

\n\n

To get back to our problem, we have our expression:

\n\n\n```julia\nx,y = symbols(\"x, y\")\nex = y^4 - x^4 - y^2 + 2x^2\n```\n\n\n\n\n\\begin{equation*}- x^{4} + 2 x^{2} + y^{4} - y^{2}\\end{equation*}\n\n\n\n

Now we substitute:

\n\n\n```julia\nex1 = ex(y=>F(x))\n```\n\n\n\n\n\\begin{equation*}- x^{4} + 2 x^{2} + F^{4}{\\left (x \\right )} - F^{2}{\\left (x \\right )}\\end{equation*}\n\n\n\n

We want to differentiate \"both\" sides. As the right side is just $0$, there isn't anything to do here, but mentally keep track. As for the left we have:

\n\n\n```julia\nex2 = diff(ex1, x)\n```\n\n\n\n\n\\begin{equation*}- 4 x^{3} + 4 x + 4 F^{3}{\\left (x \\right )} \\frac{d}{d x} F{\\left (x \\right )} - 2 F{\\left (x \\right )} \\frac{d}{d x} F{\\left (x \\right )}\\end{equation*}\n\n\n\n

Now we collect terms and solve in terms of $F'(x)$

\n\n\n```julia\nex3 = solve(ex2, F'(x))[1]\n```\n\n\n\n\n\\begin{equation*}\\frac{2 x^{3} - 2 x}{2 F^{3}{\\left (x \\right )} - F{\\left (x \\right )}}\\end{equation*}\n\n\n\n

Finally, we substitute back into the solution for $F(x)$:

\n\n\n```julia\nex4 = ex3(F(x) => y)\n```\n\n\n\n\n\\begin{equation*}\\frac{2 x^{3} - 2 x}{2 y^{3} - y}\\end{equation*}\n\n\n\n
Example: A Norman Window
\n\n

A classic calculus problem is to maximize the area of a Norman window (in the shape of a rectangle with a half circle atop) when the perimeter is fixed to be $P \\geq 0$.

\n\n

Label the rectangle with $w$ and $h$ for width and height and then the half circle has radius $r=w/2$. With this, we can see that the area is $wh+(1/2)\\pi r^2$ and the perimeter is $w + 2h + \\pi r$. This gives:

\n\n\n```julia\nw, h, P = symbols(\"w, h, P\", nonnegative=true)\nr = w/2\nA = w*h + 1//2 * (pi * r^2)\np = w + 2h + pi*r\n```\n\n\n\n\n\\begin{equation*}2 h + w + \\frac{\\pi w}{2}\\end{equation*}\n\n\n\n

(There is a subtlety above, as m 1//2*pi*r^2 will lose exactness, as the products will be done left to right, and 1//2*pi will be converted to an approximate floating point value before multiplying r^2, as such we rewrite the terms. It may be easier to use PI instead of pi.)

\n\n

We want to solve for h from when p=P (our fixed value) and substitute back into A. We solve P-p==0:

\n\n\n```julia\nh0 = solve(P-p, h)[1]\nA1 = A(h => h0)\n```\n\n\n\n\n\\begin{equation*}\\frac{\\pi w^{2}}{8} + w \\left(\\frac{P}{2} - \\frac{\\pi w}{4} - \\frac{w}{2}\\right)\\end{equation*}\n\n\n\n

Now we note this is a parabola in w, so any maximum will be an endpoint or the vertex, provided the leading term is negative. The leading term can be found through:

\n\n\n```julia\nsympy.Poly(A1, w).coeffs()\n```\n\n\n\n\n\\[ \\left[ \\begin{array}{r}- \\frac{1}{2} - \\frac{\\pi}{8}\\\\\\frac{P}{2}\\end{array} \\right] \\]\n\n\n\n

Or without using the Poly methods, we could do this:

\n\n\n```julia\ncollect(expand(A1), w).coeff(w^2)\n```\n\n\n\n\n\\begin{equation*}- \\frac{1}{2} - \\frac{\\pi}{8}\\end{equation*}\n\n\n\n

Either way, the leading coefficient, $-1/2 - \\pi/8$, is negative, so the maximum can only happen at an endpoint or the vertex of the parabola. Now we check that when $w=0$ (the left endpoint) the area is $0$:

\n\n\n```julia\nA1(w => 0)\n```\n\n\n\n\n\\begin{equation*}0\\end{equation*}\n\n\n\n

The other endpoint is when $h=0$, or

\n\n\n```julia\nb = solve((P-p)(h => 0), w)[1]\n```\n\n\n\n\n\\begin{equation*}\\frac{2 P}{2 + \\pi}\\end{equation*}\n\n\n\n

We will need to check the area at b and at the vertex.

\n\n

To find the vertex, we can use calculus – it will be when the derivative in w is $0$:

\n\n\n```julia\nc = solve(diff(A1, w), w)[1]\n```\n\n\n\n\n\\begin{equation*}\\frac{2 P}{\\pi + 4}\\end{equation*}\n\n\n\n

The answer will be the larger of A1 at b or c:

\n\n\n```julia\natb = A1(w => b)\natc = A1(w => c)\n```\n\n\n\n\n\\begin{equation*}\\frac{\\pi P^{2}}{2 \\left(\\pi + 4\\right)^{2}} + \\frac{2 P \\left(- \\frac{\\pi P}{2 \\left(\\pi + 4\\right)} - \\frac{P}{\\pi + 4} + \\frac{P}{2}\\right)}{\\pi + 4}\\end{equation*}\n\n\n\n

A simple comparison isn't revealing:

\n\n\n```julia\natc - atb\n```\n\n\n\n\n\\begin{equation*}- \\frac{\\pi P^{2}}{2 \\left(2 + \\pi\\right)^{2}} + \\frac{\\pi P^{2}}{2 \\left(\\pi + 4\\right)^{2}} - \\frac{2 P \\left(- \\frac{\\pi P}{2 \\left(2 + \\pi\\right)} - \\frac{P}{2 + \\pi} + \\frac{P}{2}\\right)}{2 + \\pi} + \\frac{2 P \\left(- \\frac{\\pi P}{2 \\left(\\pi + 4\\right)} - \\frac{P}{\\pi + 4} + \\frac{P}{2}\\right)}{\\pi + 4}\\end{equation*}\n\n\n\n

But after simplifying, we can see that this expression is positive if $P$ is:

\n\n\n```julia\nsimplify(atc - atb)\n```\n\n\n\n\n\\begin{equation*}\\frac{2 P^{2}}{16 + \\pi^{3} + 20 \\pi + 8 \\pi^{2}}\\end{equation*}\n\n\n\n

With this observation, we conclude the maximum area happens at c with area atc.

\n\n

Integrals

\n\n

Integration is implemented in SymPy through the integrate function. There are two basic calls: integrate(f(x), x) will find the indefinite integral ($\\int f(x) dx$) and when endpoints are specified through integrate(f(x), (x, a, b)) the definite integral will be found ($\\int_a^b f(x) dx$). The special form integrate(ex, x, a, b) can be used for single integrals, but the specification through a tuple is needed for multiple integrals.

\n\n

Basic integrals are implemented:

\n\n\n```julia\nintegrate(x^3, x)\n```\n\n\n\n\n\\begin{equation*}\\frac{x^{4}}{4}\\end{equation*}\n\n\n\n

Or in more generality:

\n\n\n```julia\nn = symbols(\"n\", real=true)\nex = integrate(x^n, x)\n```\n\n\n\n\n\\begin{equation*}\\begin{cases} \\frac{x^{n + 1}}{n + 1} & \\text{for}\\: n \\neq -1 \\\\\\log{\\left (x \\right )} & \\text{otherwise} \\end{cases}\\end{equation*}\n\n\n\n

The output here is a piecewise function, performing a substitution will choose a branch in this case:

\n\n\n```julia\nex(n => 3)\n```\n\n\n\n\n\\begin{equation*}\\frac{x^{4}}{4}\\end{equation*}\n\n\n\n

Definite integrals are just as easy. Here is Archimedes' answer:

\n\n\n```julia\nintegrate(x^2, (x, 0, 1))\n```\n\n\n\n\n\\begin{equation*}\\frac{1}{3}\\end{equation*}\n\n\n\n

Tedious problems, such as those needing multiple integration-by-parts steps can be done easily:

\n\n\n```julia\nintegrate(x^5*sin(x), x)\n```\n\n\n\n\n\\begin{equation*}- x^{5} \\cos{\\left (x \\right )} + 5 x^{4} \\sin{\\left (x \\right )} + 20 x^{3} \\cos{\\left (x \\right )} - 60 x^{2} \\sin{\\left (x \\right )} - 120 x \\cos{\\left (x \\right )} + 120 \\sin{\\left (x \\right )}\\end{equation*}\n\n\n\n

The SymPy tutorial says:

\n\n
\n

\"integrate uses powerful algorithms that are always improving to compute both definite and indefinite integrals, including heuristic pattern matching type algorithms, a partial implementation of the Risch algorithm, and an algorithm using Meijer G-functions that is useful for computing integrals in terms of special functions, especially definite integrals.\"

\n
\n\n

The tutorial gives the following example:

\n\n\n```julia\nf(x) = (x^4 + x^2 * exp(x) - x^2 - 2x*exp(x) - 2x - exp(x)) * exp(x) / ( (x-1)^2 * (x+1)^2 * (exp(x) + 1) )\nf(x)\n```\n\n\n\n\n\\begin{equation*}\\frac{\\left(x^{4} + x^{2} e^{x} - x^{2} - 2 x e^{x} - 2 x - e^{x}\\right) e^{x}}{\\left(x - 1\\right)^{2} \\left(x + 1\\right)^{2} \\left(e^{x} + 1\\right)}\\end{equation*}\n\n\n\n

With indefinite integral:

\n\n\n```julia\nintegrate(f(x), x)\n```\n\n\n\n\n\\begin{equation*}\\log{\\left (e^{x} + 1 \\right )} + \\frac{e^{x}}{x^{2} - 1}\\end{equation*}\n\n\n\n

Multiple integrals

\n\n

The integrate function uses a tuple, (var, a, b), to specify the limits of a definite integral. This syntax lends itself readily to multiple integration.

\n\n

For example, the following computes the integral of $xy$ over the unit square:

\n\n\n```julia\nx, y = symbols(\"x,y\")\nintegrate(x*y, (y, 0, 1), (x, 0, 1))\n```\n\n\n\n\n\\begin{equation*}\\frac{1}{4}\\end{equation*}\n\n\n\n

The innermost terms can depend on outer ones. For example, the following integrates $x^2y$ over the upper half of the unit circle:

\n\n\n```julia\nintegrate(x^2*y, (y, 0, sqrt(1 - x^2)), (x, -1, 1))\n```\n\n\n\n\n\\begin{equation*}\\frac{2}{15}\\end{equation*}\n\n\n\n

Unevaluated integrals

\n\n

The Integral constructor can stage unevaluated integrals that will be evaluated by calling doit. It is also used when the output is unknown. This example comes from the tutorial:

\n\n\n```julia\ninteg = sympy.Integral(sin(x^2), x)\n```\n\n\n\n\n\\begin{equation*}\\int \\sin{\\left (x^{2} \\right )}\\, dx\\end{equation*}\n\n\n\n\n```julia\ninteg.doit()\n```\n\n\n\n\n\\begin{equation*}\\frac{3 \\sqrt{2} \\sqrt{\\pi} S\\left(\\frac{\\sqrt{2} x}{\\sqrt{\\pi}}\\right) \\Gamma\\left(\\frac{3}{4}\\right)}{8 \\Gamma\\left(\\frac{7}{4}\\right)}\\end{equation*}\n\n\n\n

Taylor series

\n\n

The series function can compute series expansions around a point to a specified order. For example, the following command finds 4 terms of the series expansion of exp(sin(x)) in x about $c=0$:

\n\n\n```julia\ns1 = series(exp(sin(x)), x, 0, 4)\n```\n\n\n\n\n\\begin{equation*}1 + x + \\frac{x^{2}}{2} + O\\left(x^{4}\\right)\\end{equation*}\n\n\n\n

The coefficients are from the Taylor expansion ($a_i=f^{i}(c)/i!$). The big \"O\" term indicates that any other power is no bigger than a constant times $x^4$.

\n\n

Consider what happens when we multiply series of different orders:

\n\n\n```julia\ns2 = series(cos(exp(x)), x, 0, 6)\n```\n\n\n\n\n\\begin{equation*}\\cos{\\left (1 \\right )} - x \\sin{\\left (1 \\right )} + x^{2} \\left(- \\frac{\\sin{\\left (1 \\right )}}{2} - \\frac{\\cos{\\left (1 \\right )}}{2}\\right) - \\frac{x^{3} \\cos{\\left (1 \\right )}}{2} + x^{4} \\left(- \\frac{\\cos{\\left (1 \\right )}}{4} + \\frac{5 \\sin{\\left (1 \\right )}}{24}\\right) + x^{5} \\left(- \\frac{\\cos{\\left (1 \\right )}}{24} + \\frac{23 \\sin{\\left (1 \\right )}}{120}\\right) + O\\left(x^{6}\\right)\\end{equation*}\n\n\n\n\n```julia\nsimplify(s1 * s2)\n```\n\n\n\n\n\\begin{equation*}\\cos{\\left (1 \\right )} + \\sqrt{2} x \\cos{\\left (\\frac{\\pi}{4} + 1 \\right )} - \\frac{3 x^{2} \\sin{\\left (1 \\right )}}{2} - \\sqrt{2} x^{3} \\sin{\\left (\\frac{\\pi}{4} + 1 \\right )} + O\\left(x^{4}\\right)\\end{equation*}\n\n\n\n

The big \"O\" term is $x^4$, as smaller order terms in s2 are covered in this term. The big \"O\" notation is sometimes not desired, in which case the removeO function can be employed:

\n\n\n```julia\ns1.removeO()\n```\n\n\n\n\n\\begin{equation*}\\frac{x^{2}}{2} + x + 1\\end{equation*}\n\n\n\n

Sums

\n\n

SymPy can do sums, including some infinite ones. The summation function performs this task. For example, we have

\n\n\n```julia\ni, n = symbols(\"i, n\")\nsummation(i^2, (i, 1, n))\n```\n\n\n\n\n\\begin{equation*}\\frac{n^{3}}{3} + \\frac{n^{2}}{2} + \\frac{n}{6}\\end{equation*}\n\n\n\n

Like Integrate and Derivative, there is also a Sum function to stage the task until the doit function is called to initiate the sum.

\n\n

Some famous sums can be computed:

\n\n\n```julia\nsn = sympy.Sum(1/i^2, (i, 1, n))\nsn.doit()\n```\n\n\n\n\n\\begin{equation*}\\operatorname{harmonic}{\\left (n,2 \\right )}\\end{equation*}\n\n\n\n

And from this a limit is available:

\n\n\n```julia\nlimit(sn.doit(), n, oo)\n```\n\n\n\n\n\\begin{equation*}\\frac{\\pi^{2}}{6}\\end{equation*}\n\n\n\n

This would have also been possible through summation(1/i^2, (i, 1, oo)).

\n\n

Vector-valued functions

\n\n

Julia makes constructing a vector of symbolic objects easy:

\n\n\n```julia\nx,y = symbols(\"x,y\")\nv = [1,2,x]\nw = [1,y,3]\n```\n\n\n\n\n\\[ \\left[ \\begin{array}{r}1\\\\y\\\\3\\end{array} \\right] \\]\n\n\n\n

The generic definitions of vector operations will work as expected with symbolic objects:

\n\n\n```julia\nusing LinearAlgebra\ndot(v,w)\n```\n\n\n\n\n\\begin{equation*}2 y + 3 \\overline{x} + 1\\end{equation*}\n\n\n\n

Or

\n\n\n```julia\ncross(v,w)\n```\n\n\n\n\n\\[ \\left[ \\begin{array}{r}- x y + 6\\\\x - 3\\\\y - 2\\end{array} \\right] \\]\n\n\n\n

Finding gradients can be done using a comprehension.

\n\n\n```julia\nex = x^2*y - x*y^2\nSym[diff(ex,var) for var in (x,y)]\n```\n\n\n\n\n\\[ \\left[ \\begin{array}{r}2 x y - y^{2}\\\\x^{2} - 2 x y\\end{array} \\right] \\]\n\n\n\n

The mixed partials is similarly done by passing two variables to differentiate in to diff:

\n\n\n```julia\nSym[diff(ex, v1, v2) for v1 in (x,y), v2 in (x,y)]\n```\n\n\n\n\n\\[\\left[ \\begin{array}{rr}2 y&2 \\left(x - y\\right)\\\\2 \\left(x - y\\right)&- 2 x\\end{array}\\right]\\]\n\n\n\n

For this task, SymPy provides the hessian method:

\n\n\n```julia\nhessian(ex, (x,y))\n```\n\n\n\n\n\\[\\left[ \\begin{array}{rr}2 y&2 x - 2 y\\\\2 x - 2 y&- 2 x\\end{array}\\right]\\]\n\n\n\n

Matrices

\n\n

Julia has excellent infrastructure to work with generic matrices, such as Matrix{Sym} objects (matrices with symbolic entries). As well, SymPy has a class for matrices. SymPy, through PyCall, automatically maps mutable SymPy matrices into Julian matrices of type Array{Sym}.

\n\n

Constructing matrices with symbolic entries follows Julia's conventions:

\n\n\n```julia\nx,y = symbols(\"x,y\")\nM = [1 x; x 1]\n```\n\n\n\n\n\\[\\left[ \\begin{array}{rr}1&x\\\\x&1\\end{array}\\right]\\]\n\n\n\n

Construction of symbolic matrices can also be done through the Matrix constructor, which must be qualified. It is passed a vector or row vectors but any symbolic values must be converted into PyObjects:

\n\n\n```julia\nimport PyCall: PyObject\nA = sympy.Matrix([[1,PyObject(x)], [PyObject(x), 1]])\n```\n\n\n\n\n\\[\\left[ \\begin{array}{rr}1&x\\\\x&1\\end{array}\\right]\\]\n\n\n\n

(otherwise, an entry like [1,x] will be mapped to a Vector{Sym} prior to passing to sympy.Matrix and the processing get's done differently, and not as desired.)

\n\n

This is useful if copying SymPy examples, but otherwise unneccesary, these are immediately mapped into Julia arrays by PyCall. **Unless** an immutable array is desired, and then thesympy.ImmutableMatrixconstructor is used. (Though it is *still* necessary to convert symbolic values toPyObject`s.)

\n\n\n```julia\ndiagm(0=>ones(Sym, 5))\nM^2\ndet(M)\n```\n\n\n\n\n\\begin{equation*}- x^{2} + 1\\end{equation*}\n\n\n\n

Similarly,

\n\n\n```julia\nA^2\n```\n\n\n\n\n\\[\\left[ \\begin{array}{rr}x^{2} + 1&2 x\\\\2 x&x^{2} + 1\\end{array}\\right]\\]\n\n\n\n

We can call Julia's generic matrix functions in the usual manner, e.g:

\n\n\n```julia\ndet(A)\n```\n\n\n\n\n\\begin{equation*}- x^{2} + 1\\end{equation*}\n\n\n\n

We can also call SymPy's matrix methods using the dot-call syntax:

\n\n\n```julia\nA.det()\n```\n\n\n\n\n\\begin{equation*}- x^{2} + 1\\end{equation*}\n\n\n\n

Occasionally, the SymPy method has more content:

\n\n\n```julia\neigvecs(M)\n```\n\n\n\n\n\\[\\left[ \\begin{array}{rr}-1&1\\\\1&1\\end{array}\\right]\\]\n\n\n\n

As compared to SymPy's eigenvects which yields:

\n\n\n```julia\nA.eigenvects()\n```\n\n\n\n\n 2-element Array{Tuple{SymPy.Sym,Int64,Array{Array{SymPy.Sym,2},1}},1}:\n (-x + 1, 1, [[-1; 1]])\n (x + 1, 1, [[1; 1]]) \n\n\n\n

(This is a bit misleading, as the generic eigvecs fails on M, so the value is basically just repackaged from A.eigenvects().)

\n\n

This example from the tutorial shows the nullspace function:

\n\n\n```julia\nA = Sym[1 2 3 0 0; 4 10 0 0 1]\nvs = A.nullspace()\n```\n\n\n\n\n 3-element Array{Array{SymPy.Sym,2},1}:\n [-15; 6; 1; 0; 0] \n [0; 0; 0; 1; 0] \n [1; -1/2; 0; 0; 1]\n\n\n\n

And this shows that they are indeed in the null space of M:

\n\n\n```julia\n[A*vs[i] for i in 1:3]\n```\n\n\n\n\n 3-element Array{Array{SymPy.Sym,2},1}:\n [0; 0]\n [0; 0]\n [0; 0]\n\n\n\n

Symbolic expressions can be included in the matrices:

\n\n\n```julia\nA = [1 x; x 1]\nP, D = A.diagonalize() # M = PDP^-1\nA - P*D*inv(P)\n```\n\n\n\n\n\\[\\left[ \\begin{array}{rr}0&0\\\\0&0\\end{array}\\right]\\]\n\n\n\n

Differential equations

\n\n

SymPy has facilities for solving ordinary differential equations. The key is to create a symbolic function expression using SymFunction. Again, this may be done through:

\n\n\n```julia\nF = SymFunction(\"F\")\n```\n\n\n\n\n\\begin{equation*}F\\end{equation*}\n\n\n\n

With this, we can construct a differential equation. Following the SymPy tutorial, we solve $f''(x) - 2f'(x) + f(x) = \\sin(x)$:

\n\n\n```julia\ndiffeq = Eq(diff(F(x), x, 2) - 2*diff(F(x)) + F(x), sin(x))\n```\n\n\n\n\n\\begin{equation*}F{\\left (x \\right )} - 2 \\frac{d}{d x} F{\\left (x \\right )} + \\frac{d^{2}}{d x^{2}} F{\\left (x \\right )} = \\sin{\\left (x \\right )}\\end{equation*}\n\n\n\n

With this, we just need the dsolve function. This is called as dsolve(eq) or dsolve(eq, F(x)):

\n\n\n```julia\nex = dsolve(diffeq, F(x))\n```\n\n\n\n\n\\begin{equation*}F{\\left (x \\right )} = \\left(C_{1} + C_{2} x\\right) e^{x} + \\frac{\\cos{\\left (x \\right )}}{2}\\end{equation*}\n\n\n\n

The dsolve function in SymPy has an extensive list of named arguments to control the underlying algorithm. These can be passed through with the appropriate keyword arguments. (To use SymPy's ics argument, the sympy.dsolve method must be called directly.)

\n\n

More clearly, the SymFunction objects have the ' method defined to find a derivative, so the above could also have been:

\n\n\n```julia\ndiffeq = F''(x) - 2F'(x) + F(x) - sin(x)\nsympy.dsolve(diffeq, F(x))\n```\n\n\n\n\n\\begin{equation*}F{\\left (x \\right )} = \\left(C_{1} + C_{2} x\\right) e^{x} + \\frac{\\cos{\\left (x \\right )}}{2}\\end{equation*}\n\n\n\n

This solution has two constants, $C_1$ and $C_2$, that would be found from initial conditions. Say we know $F(0)=0$ and $F'(0)=1$, can we find the constants? To work with the returned expression, it is most convenient to get just the right hand side. The rhs method will return the right-hand side of a relation:

\n\n\n```julia\nex1 = ex.rhs()\n```\n\n\n\n\n\\begin{equation*}\\left(C_{1} + C_{2} x\\right) e^{x} + \\frac{\\cos{\\left (x \\right )}}{2}\\end{equation*}\n\n\n\n

(The args function also can be used to break up the expression into parts.)

\n\n

With this, we can solve for C1 through substituting in $0$ for $x$:

\n\n\n```julia\nsolve(ex1(x => 0), Sym(\"C1\"))\n```\n\n\n\n\n\\[ \\left[ \\begin{array}{r}- \\frac{1}{2}\\end{array} \\right] \\]\n\n\n\n

We see that $C1=-1/2$, which we substitute in:

\n\n\n```julia\nex2 = ex1(Sym(\"C1\") => -1//2)\n```\n\n\n\n\n\\begin{equation*}\\left(C_{2} x - 0.5\\right) e^{x} + \\frac{\\cos{\\left (x \\right )}}{2}\\end{equation*}\n\n\n\n

We know that $F'(0)=1$ now, so we solve for C2 through

\n\n\n```julia\nsolve( diff(ex2, x)(x => 0) - 1, Sym(\"C2\") )\n```\n\n\n\n\n\\[ \\left[ \\begin{array}{r}1.5\\end{array} \\right] \\]\n\n\n\n

This gives C2=3/2. Again we substitute in to get our answer:

\n\n\n```julia\nex3 = ex2(Sym(\"C2\") => 3//2)\n```\n\n\n\n\n\\begin{equation*}\\left(1.5 x - 0.5\\right) e^{x} + \\frac{\\cos{\\left (x \\right )}}{2}\\end{equation*}\n\n\n\n
Example
\n\n

We do one more example, this one borrowed from here.

\n\n
\n

Find the variation of speed with time of a parachutist subject to a drag force of $k\\cdot v^2$.

\n
\n\n

The equation is

\n\n\n$$\n\\frac{m}{k} \\frac{dv}{dt} = \\alpha^2 - v^2.\n$$\n\n\n

We proceed through:

\n\n\n```julia\nt, m,k,alpha = symbols(\"t,m,k,alpha\")\nv = SymFunction(\"v\")\nex = Eq( (m/k)*v'(t), alpha^2 - v(t)^2 )\n```\n\n\n\n\n\\begin{equation*}\\frac{m \\frac{d}{d t} v{\\left (t \\right )}}{k} = \\alpha^{2} - v^{2}{\\left (t \\right )}\\end{equation*}\n\n\n\n

We can \"classify\" this ODE with the method classify_ode function.

\n\n\n```julia\nsympy.classify_ode(ex)\n```\n\n\n\n\n (\"separable\", \"1st_power_series\", \"lie_group\", \"separable_Integral\")\n\n\n\n

It is linear, but not solvable. Proceeding with dsolve gives:

\n\n\n```julia\ndsolve(ex, v(t))\n```\n\n\n\n\n\\begin{equation*}v{\\left (t \\right )} = - \\frac{\\alpha}{\\tanh{\\left (\\frac{\\log{\\left (e^{\\alpha k \\left(C_{1} - 2 t\\right)} \\right )}}{2 m} \\right )}}\\end{equation*}\n\n\n\n

Initial Value Problems

\n\n

Solving an initial value problem can be a bit tedious with SymPy. The first example shows the steps. This is because the ics argument for sympy.dsolve only works for a few types of equations. These do not include, by default, the familiar \"book\" examples, such as $y'(x) = a\\cdot y(x)$.

\n\n

To work around this, SymPy.jl extends the function dsolve to allow a specification of the initial conditions when solving. Each initial condition is specified with 3-tuple. For example, v(t0)=v0 is specified with (v, t0, v0). The conditions on the values functions may use v, v', ... To illustrate, we follow an example from Wolfram.

\n\n\n```julia\ny = SymFunction(\"y\")\na, x = symbols(\"a,x\")\neqn = y'(x) - 3*x*y(x) - 1\n```\n\n\n\n\n\\begin{equation*}- 3 x y{\\left (x \\right )} + \\frac{d}{d x} y{\\left (x \\right )} - 1\\end{equation*}\n\n\n\n

We solve the initial value problem with $y(0) = 4$ as follows:

\n\n\n```julia\nx0, y0 = 0, 4\nout = dsolve(eqn, x, ics = (y, x0, y0))\n```\n\n\n\n\n\\begin{equation*}y{\\left (x \\right )} = \\left(\\frac{\\sqrt{6} \\sqrt{\\pi} \\operatorname{erf}{\\left (\\frac{\\sqrt{6} x}{2} \\right )}}{6} + 4\\right) e^{\\frac{3 x^{2}}{2}}\\end{equation*}\n\n\n\n

Verifying this requires combining some operations:

\n\n\n```julia\nu = out.rhs()\ndiff(u, x) - 3*x*u - 1\n```\n\n\n\n\n\\begin{equation*}0\\end{equation*}\n\n\n\n

To solve with a general initial condition is similar:

\n\n\n```julia\nx0, y0 = 0, a\nout = dsolve(eqn, x, ics=(y, x0, y0))\n```\n\n\n\n\n\\begin{equation*}y{\\left (x \\right )} = \\left(a + \\frac{\\sqrt{6} \\sqrt{\\pi} \\operatorname{erf}{\\left (\\frac{\\sqrt{6} x}{2} \\right )}}{6}\\right) e^{\\frac{3 x^{2}}{2}}\\end{equation*}\n\n\n\n

To plot this over a range of values for a we have:

\n\n\n```julia\nas = -2:0.6:2\nex = out.rhs()\np = plot(ex(a=>as[1]), -1.8, 1.8, ylims=(-4, 4))\n[plot!(p, ex(a=>i), -1.8, 1.8, ylims=(-4, 4)) for i in as[2:end]]\np\n```\n\n

The comment from the example is \"This plots several integral curves of the equation for different values of $a$. The plot shows that the solutions have an inflection point if the parameter lies between $-1$ and $1$ , while a global maximum or minimum arises for other values of $a$.\"

\n\n
Example
\n\n

We continue with another example from the Wolfram documentation, that of solving $y'' + 5y' + 6y=0$ with values prescribed for both $y$ and $y'$ at $x_0=0$.

\n\n\n```julia\ny = SymFunction(\"y\")\nx = symbols(\"x\")\neqn = y''(x) + 5y'(x) + 6y(x)\n```\n\n\n\n\n\\begin{equation*}6 y{\\left (x \\right )} + 5 \\frac{d}{d x} y{\\left (x \\right )} + \\frac{d^{2}}{d x^{2}} y{\\left (x \\right )}\\end{equation*}\n\n\n\n

To solve with $y(0) = 1$ and $y'(0) = 1$ we have:

\n\n\n```julia\nout = dsolve(eqn, x, ics=((y, 0, 1), (y', 0, 1)))\n```\n\n\n\n\n\\begin{equation*}y{\\left (x \\right )} = \\left(4 - 3 e^{- x}\\right) e^{- 2 x}\\end{equation*}\n\n\n\n

(That is we combine all initial conditions into a tuple.)

\n\n

To make a plot, we only need the right-hand-side of the answer:

\n\n\n```julia\nplot(out.rhs(), -1/3, 2)\n```\n\n
Example
\n\n

Boundary value problems can be solved for, as well, through a similar syntax. Continuing with examples from the Wolfram page, we solve $y''(x) +y(x) = e^x$ over $[0,1]$ with conditions $y(0)=1$, $y(1) = 1/2$:

\n\n\n```julia\neqn = y''(x) + y(x) - exp(x)\ndsolve(eqn, x, ics=((y, 0, 1), (y, 1, 1//2)))\n```\n\n\n\n\n\\begin{equation*}y{\\left (x \\right )} = \\frac{e^{x}}{2} + \\frac{\\left(- e - \\cos{\\left (1 \\right )} + 1\\right) \\sin{\\left (x \\right )}}{2 \\sin{\\left (1 \\right )}} + \\frac{\\cos{\\left (x \\right )}}{2}\\end{equation*}\n\n\n", "meta": {"hexsha": "135077072d4bd3e86a35a347e5ef7437ee184379", "size": 267750, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "examples/tutorial.ipynb", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/SymPy.jl-24249f21-da20-56a4-8eb1-6a02cf4ae2e6", "max_stars_repo_head_hexsha": "a6e5a24b3d1ad069a413d0c28f01052c5fa4c6cc", "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": "examples/tutorial.ipynb", "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/SymPy.jl-24249f21-da20-56a4-8eb1-6a02cf4ae2e6", "max_issues_repo_head_hexsha": "a6e5a24b3d1ad069a413d0c28f01052c5fa4c6cc", "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": "examples/tutorial.ipynb", "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/SymPy.jl-24249f21-da20-56a4-8eb1-6a02cf4ae2e6", "max_forks_repo_head_hexsha": "a6e5a24b3d1ad069a413d0c28f01052c5fa4c6cc", "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": 562.5, "max_line_length": 59932, "alphanum_fraction": 0.8358618114, "converted": true, "num_tokens": 22333, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797100118213, "lm_q2_score": 0.945801275141851, "lm_q1q2_score": 0.8617949316125626}} {"text": "# Prey-predator equations #\n### University of Cambridge | Mathematical Biology - Lent 2020 ### \nRonojoy Adhikari (ra413)\n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.integrate import odeint\n```\n\n### 1. Model ### \n\nConsider a population of prey and predators, denoted by the variables $N$ and $P$. The prey have unbounded resources and hence positive Malthusian growth in the absence of predation. The predators have negative Malthusian growth in the absence of prey. Predation reduces the numbers of prey and increases the number of predators. \n\nThe equation of motion of the interacting population of prey and predators is \n\n$$\n\\begin{align}\n\\frac{dN}{dt} &= aN - bNP = N(a-bP)\\\\\n\\frac{dP}{dt} &= cNP - dp = P(cN-d)\n\\end{align}\n$$\n\nHere, $a$, $d$ are growth rates for prey and predators and $c$, $d$ are coefficients determining the intensity of the effects of predation. We rescale the model to bring into the working form \n\n$$\n\\begin{equation}\n\\frac{du}{dt} = u(1-v),\\quad\\frac{dv}{dt} = -\\alpha v(1-u)\n\\end{equation}\n$$\n\nWe make parameter choices and set up the right hand side of the differential equation for numerical solution. \n\n### 2. Numerical solution ##\n\n\n```python\n# Non-dimensionalised Lotka-Volterra system\n\nalpha = 1.0 # predation coefficient\n\nF = lambda x, t :[ \n x[0]*(1-x[1]), # x[0] -> u - equation for prey\n x[1]*(x[0]-1)*alpha # x[1] -> v - equation for predators\n]\n```\n\n\n```python\n# Numerical integration of the system\n\n# time step, final time, and time points of the solution\ndt = 0.01; tf = 10; t = np.arange(0,tf,dt)\n\n# intial values of prey and predators: prey half as much as predators\nx0 = [1,2] \n\n# integrate\nx = odeint(F,x0,t)\n```\n\n\n```python\n# Plot of the solution\n\nplt.plot(t, x[:, 0], label='prey')\nplt.plot(t, x[:, 1], label='predator')\nplt.xlabel('time'); plt.ylabel('population')\nplt.grid(linestyle=':');plt.legend();plt.show()\n```\n\nThs solution shows that the prey and predator populations oscillate in time. Initially, the predators outnumber the prey, which leads to a decline of both populations (the prey because they are being predated upon, the predators because there is not enough prey). The reduction in the number of predators allows the prey to increase, which leads to an increase in the predators and a repeating cycle.\n\n### 3. Orbits and the constant of motion ###\n\nThe Lotka-Volterra system has the constant of motion\n\n$$ H(u, v) = \\alpha(\\log u - u) + (\\log u - v) $$\n\nas is easily verified by computing its time derivative and using the working form of Lotka-Volterra equations. The constant of motion determines the *orbits*, that is the curve obtained by plotting $u(t)$ against $v(t)$, for each $t$. In other words, the orbit is a curve in the $u-v$ plane parametrised by time. For the numerical solution, we obtain the orbit below, with the center of the dynamics indicated by a circle. \n\n\n```python\n# Plot of the orbit\nplt.plot(x[:,0], x[:, 1])\nplt.plot(1,1,'ro')\nplt.xlabel('prey'); plt.ylabel('predators')\nplt.grid(linestyle=':');plt.show()\n```\n\nThe orbit is closed implying that the oscillations are periodic.\n\n### 4. Phase portrait ###\n\nThe phase portrait of the system is obtained from the plotting the vector field $\\boldsymbol F$ whose components are \n\n$$\nF_1 = u(1-v),\\quad F_2 = -\\alpha(1-u)v\n$$\n\nThe solution \"flows\" along the vector field and the streamlines of the vector field are solution curves. \n\n\n```python\n# Plot of the vector field \n\n# generate a grid of points in the plane\nu, v = np.meshgrid(np.arange(0,2.2,0.15), np.arange(0,2.2,0.15))\n\n# compute the components of the vector field at those points\nF1 = u*(1-v); F2 = -alpha*(1-u)*v\n\n# plot\nfig, ax = plt.subplots(figsize=(6,6))\nclr = np.sqrt(F1*F1 + F2*F2)\nax.quiver(u,v, Fu, Fv, clr, scale=30)\nax.axis([0,2,0,2])\nax.xaxis.set_ticks([]); ax.xaxis.set_label_text('$u$')\nax.yaxis.set_ticks([]); ax.yaxis.set_label_text('$v$')\nax.plot(1,1,'ro')\nplt.show()\n```\n\n### Exercises ###\n\n* Examine the effect of changing the value of $\\alpha$ on the solution, paying attention to the change in period of the oscillations and the lag in time between the maxima of the prey and predators.\n* Examine the effect of changing the initial condition, covering the cases where (a) the prey are initially more numerous (b) the predators are initially more numerous and (c) both prey and predators are equally numerous. \n* Examine the effect of distance $d = \\sqrt{u_0^2 + v_0^2}$ of the initial condition from the center at $(1,1)$ on the shape of the oscillations. What happens when the distance is zero ? \n* Examine, by modifying the codes above, the effect of small amounts of competition within each population on the resulting dynamics. \n", "meta": {"hexsha": "2fc51dbac96feafc9b1cf255486fd4cdfbcd9a7e", "size": 104677, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/epidemics.ipynb", "max_stars_repo_name": "ronojoy/mathematical-biology", "max_stars_repo_head_hexsha": "4e2d8d3ffccd5760f48da812c8e0a2a9320d277b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-06-07T14:50:28.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-07T14:50:28.000Z", "max_issues_repo_path": "notebooks/fitzhugh-nagumo.ipynb", "max_issues_repo_name": "ronojoy/mathematical-biology", "max_issues_repo_head_hexsha": "4e2d8d3ffccd5760f48da812c8e0a2a9320d277b", "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/fitzhugh-nagumo.ipynb", "max_forks_repo_name": "ronojoy/mathematical-biology", "max_forks_repo_head_hexsha": "4e2d8d3ffccd5760f48da812c8e0a2a9320d277b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-03-30T07:45:37.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-30T07:45:37.000Z", "avg_line_length": 344.3322368421, "max_line_length": 35212, "alphanum_fraction": 0.9345128347, "converted": true, "num_tokens": 1301, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012747599251, "lm_q2_score": 0.9111797082028671, "lm_q1q2_score": 0.8617949295536483}} {"text": "## OSY\n\nOsyczka and Kundu used the following six-variable\ntest problem: \n\n**Definition**\n\n\\begin{equation}\n\\newcommand{\\boldx}{\\mathbf{x}}\n\\begin{array}\n\\mbox{Minimize} & f_1(\\boldx) = -\\left[25(x_1-2)^2+(x_2-2)^2 + (x_3-1)^2+(x_4-4)^2 + (x_5-1)^2\\right], \\\\\n\\mbox{Minimize} & f_2(\\boldx) = x_1^2 + x_2^2 + x_3^2 + x_4^2 + x_5^2 + x_6^2, \n\\end{array}\n\\end{equation}\n\n\\begin{equation}\n\\begin{array}\n\\mbox{\\text{subject to}} & C_1(\\boldx) \\equiv x_1 + x_2 - 2 \\geq 0, \\\\\n& C_2(\\boldx) \\equiv 6 - x_1 - x_2 \\geq 0, \\\\\n& C_3(\\boldx) \\equiv 2 - x_2 + x_1 \\geq 0, \\\\\n& C_4(\\boldx) \\equiv 2 - x_1 + 3x_2 \\geq 0, \\\\\n& C_5(\\boldx) \\equiv 4 - (x_3-3)^2 - x_4 \\geq 0, \\\\\n& C_6(\\boldx) \\equiv (x_5-3)^2 + x_6 - 4 \\geq 0, \\\\[2mm]\n& 0 \\leq x_1,x_2,x_6 \\leq 10,\\quad 1 \\leq x_3,x_5 \\leq 5,\\quad 0\\leq x_4 \\leq 6.\n\\end{array}\n\\end{equation}\n\n**Optimum**\n\nThe Pareto-optimal region is a concatenation of\nfive regions. Every region lies on some of the constraints. However, for the\nentire Pareto-optimal region, $x_4^{\\ast} = x_6^{\\ast} = 0$. \nIn table below shows the other variable values in each of the five\nregions and the constraints that are active in each region.\n\n\n\n
\n\n
\n\n**Plot**\n\n\n```python\nfrom pymoo.factory import get_problem\nfrom pymoo.util.plotting import plot\n\nproblem = get_problem(\"osy\")\nplot(problem.pareto_front(), no_fill=True)\n```\n", "meta": {"hexsha": "ac29f0268b41f047ef1f47877e7948ea18628fcc", "size": 40093, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "source/problems/multi/osy.ipynb", "max_stars_repo_name": "SunTzunami/pymoo-doc", "max_stars_repo_head_hexsha": "f82d8908fe60792d49a7684c4bfba4a6c1339daf", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-09-11T06:43:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-10T13:36:09.000Z", "max_issues_repo_path": "source/problems/multi/osy.ipynb", "max_issues_repo_name": "SunTzunami/pymoo-doc", "max_issues_repo_head_hexsha": "f82d8908fe60792d49a7684c4bfba4a6c1339daf", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2021-09-21T14:04:47.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-07T13:46:09.000Z", "max_forks_repo_path": "source/problems/multi/osy.ipynb", "max_forks_repo_name": "SunTzunami/pymoo-doc", "max_forks_repo_head_hexsha": "f82d8908fe60792d49a7684c4bfba4a6c1339daf", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-10-09T02:47:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-10T07:02:37.000Z", "avg_line_length": 262.045751634, "max_line_length": 36396, "alphanum_fraction": 0.9215074951, "converted": true, "num_tokens": 595, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012732322215, "lm_q2_score": 0.9111797094088366, "lm_q1q2_score": 0.8617949293022433}} {"text": "# Mathematics for Machine Learning: Linear Algebra\n## Week1\n## Module 1:\n\n### The relationship between machine learning, linear algebra, and vectors and matrices\n\n#### Motivations for linear algebra\n\n\n```python\nfrom sympy import solve, Poly, Eq, Function, exp\n\nfrom sympy.abc import x, y, z, a, b\n```\n\n$2a + 3b = 8$\n\n$10a +1b = 13$\n\n\n```python\nsolve((2 * a + 3* b- 1, 10 * a + b - 13), a, b)\n```\n\n\n\n\n {a: 19/14, b: -4/7}\n\n\n\n$\\begin{pmatrix} 2 & 3 \\\\ 10 & 1 \\end{pmatrix} \\begin{bmatrix} a \\\\ b \\end{bmatrix} = \\begin{bmatrix} 8 \\\\ 13 \\end{bmatrix}$ \n\n## Getting a handle on vectors\n\n# Operations with vectors\n\n\n```python\nimport numpy as np\nr = [3,2]\ns = [-1,2]\nprint(f'r + s = {np.add(r,s)}')\nprint(f's + r = {np.add(s,r)}')\n```\n\n r + s = [2 4]\n s + r = [2 4]\n\n\n\n```python\nnp.arange(9.0)\n```\n\n\n\n\n array([0., 1., 2., 3., 4., 5., 6., 7., 8.])\n\n\n\n\n```python\nnp.arange(9.0).reshape((3, 3))\n```\n\n\n\n\n array([[0., 1., 2.],\n [3., 4., 5.],\n [6., 7., 8.]])\n\n\n\n\n```python\nnp.arange(3.0)\n```\n\n\n\n\n array([0., 1., 2.])\n\n\n\n\n```python\nx1 = np.arange(9.0).reshape((3, 3))\n\nx2 = np.arange(3.0)\n\nx1 + x2\n```\n\n\n\n\n array([[ 0., 2., 4.],\n [ 3., 5., 7.],\n [ 6., 8., 10.]])\n\n\n\n\n```python\nr2 = [2*x for x in r]\nprint(f'2*r = {r2}')\n```\n\n 2*r = [6, 4]\n\n\n\n```python\nnp.array([1, 2, 3]) * 2\n```\n\n\n\n\n array([2, 4, 6])\n\n\n\n\n```python\nr = np.array([3,2])\ns = np.array([-1,2])\n```\n\n\n```python\nprint(f' r-r = {r-r}')\nprint(f' r-s = {r-s}')\nprint(f' s-r = {s-r}')\n```\n\n r-r = [0 0]\n r-s = [4 0]\n s-r = [-4 0]\n\n\n\n```python\nhouse = np.array([120,2,1,150])\n2*house\n```\n\n\n\n\n array([240, 4, 2, 300])\n\n\n\n\n```python\nhouse + house\n```\n\n\n\n\n array([240, 4, 2, 300])\n\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "795b8dfa06cd09221bfcd71467ae0e1a332374ed", "size": 6897, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "week1/Module1/Module_1.ipynb", "max_stars_repo_name": "FarhadManiCodes/Math_for_ML_Coursera", "max_stars_repo_head_hexsha": "68f06d7be417d625f60a7257e81242084c0cc7d9", "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": "week1/Module1/Module_1.ipynb", "max_issues_repo_name": "FarhadManiCodes/Math_for_ML_Coursera", "max_issues_repo_head_hexsha": "68f06d7be417d625f60a7257e81242084c0cc7d9", "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": "week1/Module1/Module_1.ipynb", "max_forks_repo_name": "FarhadManiCodes/Math_for_ML_Coursera", "max_forks_repo_head_hexsha": "68f06d7be417d625f60a7257e81242084c0cc7d9", "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": 19.59375, "max_line_length": 143, "alphanum_fraction": 0.4607800493, "converted": true, "num_tokens": 714, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338101862454, "lm_q2_score": 0.8962513800615313, "lm_q1q2_score": 0.8617760043552449}} {"text": "# Implementing Discrete Cosine Transform (DCT) Using Python\n\n## Table of Contents\n* [Introduction](#Introduction)\n* [Python Implementation](#Implementation)\n* [Testing the Code](#Testing)\n\n\n\n## Introduction\n\nDiscrete Cosine Transform (DCT) is one of the methods that transform an image in **space-domain** to its corresponding **frequency-domain**. The transformed image can also be returned back to its original format by using the inverse DCT. Discrete Fourier Transform (DFT) is a complex type of transform. That is, the output of DFT is a matrix of complex numbers having both the real and imaginary parts (cosine and sine). However, we may need to change the image only to its corresponding real-number transformation. So, DCT is the one that computes only the real (cosine) part of the transformation while keeping the similar format as the DFT.\n\nLet the size of an input image be NxN.\n\nThe general formula for ***Forward DCT*** is:\n\n$$\n\\begin{align}\nC(u,v) = \\tau(u,v)\\sum_{x=0}^{N-1}\\sum_{y=0}^{N-1}f(x,y) cos(\\frac{(2x+1)}{2N}u\\pi)cos(\\frac{(2y+1)}{2N}v\\pi) \\; where \\; u,v=0,1,2,...N-1\n\\end{align}\n$$\n\n$\\hspace{7cm} \\tau(u, v) = \\frac{1}{N}$ for u=0, v=0\n\n$\\hspace{8.25cm}=\\frac{2}{N}$ for otherwise\n\nThe ***forward DCT kernel*** is:\n$$\n\\begin{align}\ng(x,y,u,v) = \\tau(u,v)\\sum_{x=0}^{N-1}\\sum_{y=0}^{N-1} cos(\\frac{(2x+1)}{2N}u\\pi)cos(\\frac{(2y+1)}{2N}v\\pi)\n\\end{align}\n$$\n\nSimilarly, the ***Inverse DCT*** is:\n$$\n\\begin{align}\nf(x,y) = \\sum_{u=0}^{N-1}\\sum_{v=0}^{N-1}\\tau(u,v)C(u,v) cos(\\frac{(2x+1)}{2N}u\\pi)cos(\\frac{(2y+1)}{2N}v\\pi) \\; where \\; x,y=0,1,2,...N-1\n\\end{align}\n$$\n\nIn the next section, the forward DCT will be implemented in python. It will be tested with real images. Finally, its running time will be computed and visualized by using multiple images having different images.\n\n\n## Python Implementation\n\nFirst of all, let's import the necessary python libraries\n\n\n```python\nimport numpy as np\n\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\n#import matplotlib.image as img\nimport PIL.Image as Image \n\nimport math\nimport cmath\n\nimport time\n\nimport csv\n\nfrom numpy import binary_repr\n\n```\n\nThe functions below implement the common image handling\n\n\n```python\ndef generateBlackAndWhiteSquareImage(imgSize):\n \"\"\"\n Generates a square-sized black and white image with a given input size.\n\n Parameters\n ----------\n imgSize : int\n Input number that stores the dimension of the square image to be generated.\n\n Returns\n -------\n imge : ndarray\n The generated black and white square image.\n \"\"\"\n\n #Creating a matrix with a given size where all the stored values are only zeros (for initialization)\n imge = np.zeros([imgSize, imgSize], dtype=int)\n\n #Starting and ending indices of the white part of the image.\n ind1 = imgSize/4\n ind2 = ind1 + (imgSize/2)\n\n #Make a part of the image as white (255)\n imge[ind1:ind2, ind1:ind2] = np.ones([imgSize/2, imgSize/2], dtype=int)*255\n\n #return the resulting image\n return imge\n \ndef generateImagesWithResizedWhite(imge):\n \"\"\"\n Generates images with the same size as the original but with a resized white part of them.\n \"\"\"\n\n N = imge.shape[0]\n\n imges = []\n i = N/2\n while i >= 4:\n j = (N - i)/2\n\n #Starting and ending indices for the white part.\n indx1 = j\n indx2 = j+i\n\n #Draw the image.\n imgeNew = np.zeros([N, N],dtype=int)\n imgeNew[indx1:indx2, indx1:indx2] = np.ones([i, i], dtype=int)*255\n\n #Add the image to the list.\n imges.append(imgeNew)\n\n i = i/2\n\n return imges\n\ndef resizeImage(imge, newSize): \n \"\"\"\n Reduces the size of the given image.\n\n Parameters\n ----------\n imge : ndarray\n Input array that stores the image to be resized.\n\n Returns\n -------\n newSize : int\n The size of the newly generated image.\n \"\"\"\n\n #Compute the size of the original image (in this case, only # of rows as it is square)\n N = imge.shape[0]\n\n #The ratio of the original image as compared to the new one.\n stepSize = N/newSize\n\n #Creating a new matrix (image) with a black color (values of zero)\n newImge = np.zeros([N/stepSize, N/stepSize])\n\n #Average the adjacent four pixel values to compute the new intensity value for the new image.\n for i in xrange(0, N, stepSize):\n for j in xrange(0, N, stepSize):\n newImge[i/stepSize, j/stepSize] = np.mean(imge[i:i+stepSize, j:j+stepSize])\n\n #Return the new image\n return newImge\n\ndef generateImages(imgSizes=[128, 64, 32, 16, 8]): \n \"\"\"\n Generates images with different sizes\n \"\"\"\n #Create an empty list of images to save the generated images with different sizes.\n images = []\n\n #Generate the first and biggest image\n imge = generateBlackAndWhiteSquareImage(imgSizes[0])\n\n #Add to the images list\n images.append(imge)\n\n #Generate the resized and smaller images with different sizes.\n for i in range(1, len(imgSizes)):\n size = imgSizes[i]\n images.append(resizeImage(imge, size))\n \n return images\n```\n\nThe python class below implements the DCT transformation algorithm.\n\n\n```python\nclass DCT(object):\n \"\"\"\n This class DCT implements all the procedures for transforming a given 2D digital image\n into its corresponding frequency-domain image (Forward DCT Transform)\n \"\"\"\n \n @classmethod\n def __computeSinglePoint2DCT(self, imge, u, v, N):\n \"\"\"\n A private method that computes a single value of the 2D-DCT from a given image.\n\n Parameters\n ----------\n imge : ndarray\n The input image.\n \n u : ndarray\n The index in x-dimension.\n \n v : ndarray\n The index in y-dimension.\n\n N : int\n Size of the image.\n \n Returns\n -------\n result : float\n The computed single value of the DCT.\n \"\"\"\n result = 0\n\n for x in xrange(N):\n for y in xrange(N):\n result += imge[x, y] * math.cos(((2*x + 1)*u*math.pi)/(2*N)) * math.cos(((2*y + 1)*v*math.pi)/(2*N))\n\n #Add the tau value to the result\n if (u==0) and (v==0):\n result = result/N\n elif (u==0) or (v==0):\n result = (math.sqrt(2.0)*result)/N\n else:\n result = (2.0*result)/N\n\n return result\n \n @classmethod\n def __computeSinglePointInverse2DCT(self, imge, x, y, N):\n \"\"\"\n A private method that computes a single value of the 2D-DCT from a given image.\n\n Parameters\n ----------\n imge : ndarray\n The input image.\n \n u : ndarray\n The index in x-dimension.\n \n v : ndarray\n The index in y-dimension.\n\n N : int\n Size of the image.\n \n Returns\n -------\n result : float\n The computed single value of the DCT.\n \"\"\"\n result = 0\n\n for u in xrange(N):\n for v in xrange(N):\n if (u==0) and (v==0):\n tau = 1.0/N\n elif (u==0) or (v==0):\n tau = math.sqrt(2.0)/N\n else:\n tau = 2.0/N \n result += tau * dctImge[u, v] * math.cos(((2*x + 1)*u*math.pi)/(2*N)) * math.cos(((2*y + 1)*v*math.pi)/(2*N))\n\n return result\n \n @classmethod\n def computeForward2DDCT(self, imge):\n \"\"\"\n Computes/generates the 2D DCT of an input image in spatial domain.\n\n Parameters\n ----------\n imge : ndarray\n The input image to be transformed.\n\n Returns\n -------\n final2DDFT : ndarray\n The transformed image.\n \"\"\"\n \n # Assuming a square image\n N = imge.shape[0]\n final2DDCT = np.zeros([N, N], dtype=float)\n for u in xrange(N):\n for v in xrange(N):\n #Compute the DCT value for each cells/points in the resulting transformed image.\n final2DDCT[u, v] = DCT.__computeSinglePoint2DCT(imge, u, v, N)\n return final2DDCT\n \n @classmethod\n def computeInverse2DDCT(self, imge):\n \"\"\"\n Computes/generates the 2D DCT of an input image in spatial domain.\n\n Parameters\n ----------\n imge : ndarray\n The input image to be transformed.\n\n Returns\n -------\n final2DDFT : ndarray\n The transformed image.\n \"\"\"\n \n # Assuming a square image\n N = imge.shape[0]\n finalInverse2DDCT = np.zeros([N, N], dtype=float)\n for x in xrange(N):\n for y in xrange(N):\n #Compute the DCT value for each cells/points in the resulting transformed image.\n finalInverse2DDCT[x, y] = DCT.__computeSinglePointInverse2DCT(imge, x, y, N)\n return finalInverse2DDCT\n \n @classmethod\n def normalize2DDCTByLog(self, dctImge):\n \"\"\"\n Computes the log transformation of the transformed DCT image to make the range\n of the DCT values b/n 0 to 255\n \n Parameters\n ----------\n dctImge : ndarray\n The input DCT transformed image.\n\n Returns\n -------\n dctNormImge : ndarray\n The normalized version of the transformed image.\n \"\"\"\n \n #Normalize the DCT values of a transformed image:\n dctImge = np.absolute(dctImge)\n dctNormImge = (255/ math.log10(255)) * np.log10(1 + (255/(np.max(dctImge))*dctImge))\n \n return dctNormImge\n \n```\n\n\n## Testing the Code\n\n### Testing the DCT Algorithm\n\nFirst, we generate an 8-bit gray scale image as a 64x64 matrix and display it.\n\n\n```python\nimge = generateBlackAndWhiteSquareImage(64)\nprint \"Image Size:\", imge.shape\nplt.figure(figsize=(3,3))\nplt.imshow(imge, cmap=plt.get_cmap('gray'), vmin=0, vmax=255)\nplt.show()\n```\n\nAnd we will also load another image from file:\n\n\n```python\n#Read an image file\nimgeLena = Image.open(\"Images/lena_gray_256.tif\") # open an image\n\n#Convert the image file to a matrix\nimgeLena = np.array(imgeLena)\n\n#Convert the uint datatype of the matrix values into 'int' for using the negative values\nimge = imge.astype('int')\n\n#Display the image:\nprint \"Image Size:\", imgeLena.shape\nplt.imshow(imgeLena, cmap=plt.get_cmap('gray'), vmin=0, vmax=255)\nplt.show()\n```\n\nThe image is then resized to 64x64 for making the DCT algorithm faster:\n\n\n```python\nimgeLena = resizeImage(imgeLena, 64)\n\nprint \"Image Size:\", imgeLena.shape\n\nplt.figure(figsize=(3,3))\nplt.imshow(imgeLena, cmap=plt.get_cmap('gray'), vmin=0, vmax=255)\nplt.show()\n```\n\nNow, the DCT is computed for both the images as follows:\n\n\n```python\n#1. For image 1:\ndctImge = DCT.computeForward2DDCT(imge)\n\n#2. For image 2:\ndctImgeLena = DCT.computeForward2DDCT(imgeLena)\n\n```\n\nNormalize the computed DCT results:\n\n\n```python\n#1. For image 1:\ndctNormImge = DCT.normalize2DDCTByLog(dctImge)\n\n#1. For image 2:\ndctNormImgeLena = DCT.normalize2DDCTByLog(dctImgeLena)\n```\n\nNow, all the results are displayed for both the input images:\n\n\n```python\nfig, axarr = plt.subplots(2, 3, figsize=(10, 10))\n\n#For image 1\naxarr[0][0].imshow(imge, cmap=plt.get_cmap('gray'), vmin=0, vmax=255)\naxarr[0][0].set_title('Original Image')\n\naxarr[0][1].imshow(np.absolute(dctImge), cmap=plt.get_cmap('gray'))\naxarr[0][1].set_title('Unnormalized DCT')\n\naxarr[0][2].imshow(dctNormImge, cmap=plt.get_cmap('gray'))\naxarr[0][2].set_title('Normalized DCT')\n\n#For image 2\naxarr[1][0].imshow(np.absolute(imgeLena), cmap=plt.get_cmap('gray'))\naxarr[1][0].set_title('Original Image')\n\naxarr[1][1].imshow(dctImgeLena, cmap=plt.get_cmap('gray'))\naxarr[1][1].set_title('Unnormalized DCT')\naxarr[1][2].imshow(dctNormImgeLena, cmap=plt.get_cmap('gray'))\naxarr[1][2].set_title('Normalized DCT')\n#fig.set_figwidth(15)\n\nplt.show()\n```\n\nNow, the DCT results can be return back to their original form by using inverse DCT. (Only for the first image done).\n\nNote: the result is rounded to the nearest integer to eliminate the very small decimall points which have come due to floating point precision.\n\n\n```python\ninverseImge = np.round(DCT.computeInverse2DDCT(dctImge))\nplt.imshow(inverseImge, cmap=plt.get_cmap('gray'))\nplt.show()\n```\n\n### Computing and Visualizing the DCT Running Time\n\nAfter the implementation of the DCT algorithm is fully tested, its running time is computed for different image sizes.\n\nFirst the images with different sizes are generated:\n\n\n```python\n#Generate images\nimgSizes = [128, 64, 32, 16, 8]\nimages = generateImages(imgSizes)\n```\n\nAfter the images are generated, the DCT running time is analyzed as follows: \n\n\n```python\n# A list that stores the running time of the DCT algorithm for images with different size.\nrunningTimeDCT = []\n\n#For each image...\nfor i, imge in enumerate(images):\n \n #Compute the image size\n N = imge.shape[0]\n \n print \"Computing for \", N, \"x\", N, \"image...\"\n \n #Save the starting time.\n startTime = time.time()\n\n #Compute the DCT of the image.\n dctImge = DCT.computeForward2DDCT(imge)\n \n #Save the running time\n runningTimeDCT.append((time.time() - startTime)/60.0)\n```\n\n Computing for 128 x 128 image...\n Computing for 64 x 64 image...\n Computing for 32 x 32 image...\n Computing for 16 x 16 image...\n Computing for 8 x 8 image...\n\n\n\n```python\nresult = zip(imgSizes, runningTimeDCT)\nnp.savetxt(\"RunningTimes/runningTimeDCT.csv\", np.array(result), delimiter=',')\n\n#Load the running time for DFT from the separate post\nrunningTimeDFT = np.loadtxt(\"RunningTimes/runningTimeDFT.csv\", delimiter =',')\n```\n\nFinally, the computation times are visualized by using line plot:\n\n\n```python\n#Plot the running times\nplt.plot(xrange(len(runningTimeDCT)), runningTimeDCT, '-d')\nplt.hold\nplt.plot(xrange(len(runningTimeDFT)), runningTimeDFT, '-d')\n\nxlabels = [str(imge.shape[0]) + 'x' + str(imge.shape[0]) for imge in images]\nprint xlabels\nplt.xticks(xrange(len(runningTimeDCT)), xlabels)\nplt.xlabel(\"Image Size(Pixels)\")\nplt.ylabel(\"Time(Sec)\")\nplt.legend(['DCT', 'DFT'])\nplt.show()\n```\n\nFrom the above results, we can conclude that DCT is faster than DFT as it only calculates the real part.\n", "meta": {"hexsha": "33d17e1ec6700d24453743a80aade2adfd1d8a00", "size": 207487, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Notebooks_Teoricos/Image-Processing-Operations/03-Implementing-Discrete-Cosine-Transform-Using-Python.ipynb", "max_stars_repo_name": "lucas-althoff/PDI-UnB", "max_stars_repo_head_hexsha": "eae5de886739807bd7f66d5cb9dbe7b541efa4ff", "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_Teoricos/Image-Processing-Operations/03-Implementing-Discrete-Cosine-Transform-Using-Python.ipynb", "max_issues_repo_name": "lucas-althoff/PDI-UnB", "max_issues_repo_head_hexsha": "eae5de886739807bd7f66d5cb9dbe7b541efa4ff", "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_Teoricos/Image-Processing-Operations/03-Implementing-Discrete-Cosine-Transform-Using-Python.ipynb", "max_forks_repo_name": "lucas-althoff/PDI-UnB", "max_forks_repo_head_hexsha": "eae5de886739807bd7f66d5cb9dbe7b541efa4ff", "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": 246.4216152019, "max_line_length": 89936, "alphanum_fraction": 0.900263631, "converted": true, "num_tokens": 3924, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533144915912, "lm_q2_score": 0.9241418137109956, "lm_q1q2_score": 0.8617190972550884}} {"text": "\n\n# Chapter 2 - Linear Algebra\n\n## 2.1 Scalars, Vectors, Matrices and Tensors\n\n### Q1 [10 Points, M]\nDenote the set of all n-dimensional binary vectors with Cartesian product notation\n\n### Q2 [10 Points, S]\nGiven the vector\n$\n\\boldsymbol{x}=\\left[\\begin{array}{c}\nx_{1} \\\\\nx_{2} \\\\\nx_{3} \\\\\nx_{4} \\\\\n\\end{array}\\right]\n$, \nand the set \n$\nS = \\{2, 4\\}\n$,\nobtain the vectors $\\boldsymbol{x}_{S}$ and $\\boldsymbol{x}_{-S}$\n\n### Q3 [20 Points, S]\nEvaluate the following expressions with broadcasting rules,\n\n$$\n\\left[\\begin{array}{lll}\n0 & 1 & 2\n\\end{array}\\right]+[5]=\n$$\n\n$$\n\\left[\\begin{array}{lll}\n1 & 1 & 1 \\\\\n1 & 1 & 1 \\\\\n1 & 1 & 1\n\\end{array}\\right]+\\left[\\begin{array}{lll}\n0 & 1 & 1\n\\end{array}\\right]=\n$$\n\n$$\n\\left[\\begin{array}{l}\n0 \\\\\n1 \\\\\n2\n\\end{array}\\right]+\\left[\\begin{array}{ll}\n0 & 1 & 2\n\\end{array}\\right]=\n$$\n\n## 2.2-3 Multiplying Matrices and Vectors and Identity and Inverse Matrices\n\n### Q4 [20 Points, H]\nLet $A$ be a $2 \\times 2$ matrix, if $A B=B A$ for every $B$ of the size $2 \\times 2$, Prove that:\n$$\nA=\\left[\\begin{array}{ll}\na & 0 \\\\\n0 & a\n\\end{array}\\right], \\\na \\in \\mathbb{R}\n$$\n\n\n## 2.4 Linear Dependence and Span\n\n### Q5 [10 Points, H]\nProve that if a linear system of equations have two solutions, then it has infinitely many solutions.\n\n### Q6 [5 Points, M]\nGiven $A x=0$, where $A \\in \\mathbb{R}^{m \\times n}$ is any matrix, and $x \\in \\mathbb{R}^{n}$ is a vector of unknown variables to be solved, what is the condition such that there is infinitely many solutions?\n\n## 2.5 Norms\n\n### Q7 [15 Points, M]\nProve that **Max Norm** follows these conditions,\n$$\n\\begin{align}\nf(\\boldsymbol{x})=0 \\Rightarrow \\boldsymbol{x}=\\mathbf{0} \\\\\nf(\\boldsymbol{x}+\\boldsymbol{y}) \\leq f(\\boldsymbol{x})+f(\\boldsymbol{y}) \\\\\n\\forall \\alpha \\in \\mathbb{R}, f(\\alpha \\boldsymbol{x})=|\\alpha| f(\\boldsymbol{x})\n\\end{align}\n$$\n\n## 2.6 Special Kinds of Matrices and Vectors\n\n### Q8 [10 Points, M]\nSolve the following system of equations,\n\n$$\n\\frac{1}{2}\\left[\\begin{array}{cccc}\n1 & 1 & 1 & 1 \\\\\n1 & 1 & -1 & -1 \\\\\n1 & -1 & 1 & -1 \\\\\n1 & -1 & -1 & 1\n\\end{array}\\right] \\left[\\begin{array}{c}\nx_{1} \\\\\nx_{2} \\\\\nx_{3} \\\\\nx_{4} \\\\\n\\end{array}\\right] = \\left[\\begin{array}{c}\n1 \\\\\n2 \\\\\n3 \\\\\n4 \\\\\n\\end{array}\\right]\n$$\n", "meta": {"hexsha": "4a3973de7604531c8a61042c34226df704df2d5c", "size": 6111, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Ch2_Linear-Algebra/Ch2_Exam1.ipynb", "max_stars_repo_name": "arashash/deep_exercises", "max_stars_repo_head_hexsha": "2c40802ee367ba9bf1f6fa5dad96cfa1a74e092b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-12-09T10:27:37.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-09T10:27:37.000Z", "max_issues_repo_path": "Ch2_Linear-Algebra/Ch2_Exam1.ipynb", "max_issues_repo_name": "arashash/deep_exercises", "max_issues_repo_head_hexsha": "2c40802ee367ba9bf1f6fa5dad96cfa1a74e092b", "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": "Ch2_Linear-Algebra/Ch2_Exam1.ipynb", "max_forks_repo_name": "arashash/deep_exercises", "max_forks_repo_head_hexsha": "2c40802ee367ba9bf1f6fa5dad96cfa1a74e092b", "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": 25.6764705882, "max_line_length": 248, "alphanum_fraction": 0.4131893307, "converted": true, "num_tokens": 869, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693716759489, "lm_q2_score": 0.9073122269997507, "lm_q1q2_score": 0.8616466325287592}} {"text": "# How to Draw Ellipse of Covariance Matrix\nGiven a 2x2 covariance matrix, I explain how to draw the ellipse representing it. The following function explains the method to visualize multivariate normal distributions and correlation matrices. Formulae for radii & rotation are provided for covariance matrix shown below\n\\begin{align}\n\\Sigma = \\begin{bmatrix} a & b \\\\ b & c \\end{bmatrix}\n\\end{align}\n\n## Radii and Rotation\n\n\\begin{align}\n\\lambda_{1,2} &= \\frac{a+c}{2} \\pm \\sqrt{\\left( \\frac{a-c}{2} \\right)^{2} + b^{2}} \\\\\n\\theta &= \\begin{cases} 0 & \\text{ if } b = 0 \\text{ and } a \\geq c \\\\\n \\frac{\\pi}{2} & \\text{ if } b = 0 \\text{ and } a < c \\\\\n \\text{atan2}(\\lambda_{1} - a, b) & \\text{ if } b \\neq 0 \n\\end{cases}\n\\end{align}\nHere, $\\theta$ is the angle in radians from positive x-axis to the ellipse's major axis in the counterclockwise direction. $\\sqrt{\\lambda_{1}}$ is the radius of the major axis (the longer radius) and $\\sqrt{\\lambda_{2}}$ is the radius of the minor axis (shorter radius). In $atan2(\\cdot, \\cdot)$, the first parameter is $y$ and second is $x$.\n\n\n```python\nimport random\nimport math\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport time\nfrom scipy.linalg import block_diag\nfrom scipy.special import erfinv\nfrom scipy.stats import t as tdist\nfrom numpy.linalg import inv\nfrom numpy import linalg as LA\nfrom matplotlib.patches import Ellipse\n```\n\n\n```python\ndef GetAngleAndRadii(covar):\n \"\"\"\n Given a covariance matrix, the function GetAngleAndRadii() calculates \n the major axis and minor axis radii and the orientation of the ellipse.\n \n Inputs:\n covar: 2x2 matrix\n \n Output:\n major_radius: Radius of the major axis of ellipse\n minor_radius: Radius of the minor axis of ellipse\n theta : Orientation angle in radians from positive x-axis\n to the ellipse's major axis in the counterclockwise direction\n \"\"\"\n \n # Infer the a,b,c values\n a = covar[0,0]\n b = covar[0,1]\n c = covar[1,1]\n \n if b > a:\n raise Exception(\"Sorry, covariance matrix is invalid - Cov[0,1] should be < Cov[0,0] \")\n \n lambda_1 = (a+c)/2 + math.sqrt(((a-c)/2)**2 + b**2)\n lambda_2 = (a+c)/2 - math.sqrt(((a-c)/2)**2 + b**2)\n \n # Infer the radii\n major_radius = math.sqrt(lambda_1)\n minor_radius = math.sqrt(lambda_2)\n \n # Infer the rotation\n if b == 0:\n if a >= c:\n theta = 0\n else:\n theta = pi/2\n else:\n theta = math.atan2(lambda_1-a, b)\n \n return major_radius, minor_radius, theta\n \n```\n\n\n```python\n# Check the above code\ncovar_check = np.array([[9,5],[5,4]])\nmajor_radius_check, minor_radius_check, theta_check = GetAngleAndRadii(covar_check)\nprint('major axis radius = ', round(major_radius_check,2), \n 'minor axis radius = ', round(minor_radius_check,2), \n 'orientation = ', round(theta_check,2), 'rad')\n```\n\n major axis radius = 3.48 minor axis radius = 0.95 orientation = 0.55 rad\n\n\n\n```python\ndef plot_ellipse(center, cov = None):\n\n # Get the center of ellipse\n x_cent, y_cent = center\n \n print('center x at: ', x_cent)\n print('center y at: ', y_cent)\n \n # Get Ellipse Properties from cov matrix\n if cov is not None:\n major_radius, minor_radius, theta_orient = GetAngleAndRadii(cov)\n print('major axis radius = ', round(major_radius,2), \n 'minor axis radius = ', round(minor_radius,2), \n 'orientation = ', round(theta_orient,2), 'rad')\n eig_vec,eig_val,u = np.linalg.svd(cov)\n\n # Generate data for ellipse structure\n t = np.linspace(0,2*np.pi,1000)\n x = major_radius*np.cos(t)\n y = minor_radius*np.sin(t)\n data = np.array([x,y])\n R = np.array([[np.cos(theta_orient),-np.sin(theta_orient)],\n [np.sin(theta_orient),np.cos(theta_orient)]])\n T = np.dot(R,eig_vec)\n data = np.dot(T,data)\n \n # Center the ellipse at given center\n data[0] += x_cent\n data[1] += y_cent\n\n # Plot the ellipse\n fig,ax = plt.subplots()\n ax.plot(data[0],data[1],color='b',linestyle='-')\n ax.fill(data[0],data[1])\n```\n\n\n```python\ncovar_check = np.array([[9,4],[4,3]])\nplot_ellipse(center = (1,2), cov=covar_check)\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "9e65b9d43597228130778717e3d8e8122f55c6be", "size": 31286, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Draw_Covariance_Ellipse.ipynb", "max_stars_repo_name": "venkatramanrenganathan/Demonstrations", "max_stars_repo_head_hexsha": "6d25f6b6b208b6c74aecb6c1482ad54d44ad8038", "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": "Draw_Covariance_Ellipse.ipynb", "max_issues_repo_name": "venkatramanrenganathan/Demonstrations", "max_issues_repo_head_hexsha": "6d25f6b6b208b6c74aecb6c1482ad54d44ad8038", "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": "Draw_Covariance_Ellipse.ipynb", "max_forks_repo_name": "venkatramanrenganathan/Demonstrations", "max_forks_repo_head_hexsha": "6d25f6b6b208b6c74aecb6c1482ad54d44ad8038", "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": 136.6200873362, "max_line_length": 14972, "alphanum_fraction": 0.8644441603, "converted": true, "num_tokens": 1231, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545348152282, "lm_q2_score": 0.908617890746506, "lm_q1q2_score": 0.8615101735255472}} {"text": "# Fangohr, Hans. Introduction to Python for Computational Science and Engineering, 2015.\nEmbleton | 20160910 | Notes\n\n\n### General Notes\n* Use `help()` with a command for details\n* Use `dir()` with a command for a list of available methods\n\n\n## Chapter 2, A Powerful Calculator\n\n\n```python\nimport math\n```\n\n\n```python\ndir(math)\n\nhelp(math.exp)\n\nmath.pi\n\nmath.e\n```\n\n Help on built-in function exp in module math:\n \n exp(...)\n exp(x)\n \n Return e raised to the power of x.\n \n\n\n\n\n\n 2.718281828459045\n\n\n\n## Chapter 3, Data Types and Structures\n\n* use cmath library to calculate complex results\n* Strings are immutable, lists are mutable\n* `dir(\"\")` outputs a list of available methods\n* Sequences\n * `a[i]` returns the ith element of a\n * `a[i:j]` returns elements i up to j-1\n * `len(a)` returns number of elements in a sequence\n * `min(a)` returns the smallest value in a seq.\n * `max(a)` \n * `x in a` returns True if x is an element in a\n * `a + b` concatenates seq. a and seq. b\n * `n * a` creates n copies of seq. a\n* The `split()` method seperates the string where it finds white space or at a seperator character.\n* The join method is the opposite of split\n* Lists\n * Empty list given by `x = []`\n * You can mix objects within a list\n * You can add lists within lists\n * ? Is this the proper method for making tables?\n * You can use scipy.arrange() or pandas\n * `append()` to add an object to the end of a list, opposite is `remove()`\n * `range()` command common in for loops. Use: range(start, stop, step size)\n * Range is a type! \n* Tuple\n * Immutable\n * Empty tuple given by `t = ()`\n * Tuple containing one object `t = (x,)`. The comma is required.\n* Indexing\n * Use negative numbers to retrieve values from the back of the list\n* Slicing\n * Slicing is different from indicing as it corresponds to the point between two indicies.\n* Dictionaries\n * empty dictionary: `d = {}`\n * look for matches with: `d.has_key()` or `d.has_item()`\n * method `get(key, default)` to retrieve values or default if key not found\n * Keyword can be any immutable object\n * Dictionaries are very fast when retreiving values (when given the key)\n* Passing arguments to functions\n * Modifications to values of an arguement in a function can affect the value of the original object\n* Copying\n * `b = a` does not pass a copy of a to b and create two seperate objects. Instead b and a refer to the same object. Only the lable is copied. To create a copy of a with a differnt label, use something like `c = a[:]`\n * use `id(a)` to determine if objects are the same or different\n* Equality Operators\n * <, >, ==, >=, <=, !=\n * Does not depend on type\n * To compare the id use, `a is b`. Objects with different types will not have the same id\n \n\n\n\n\n\n\n```python\nimport cmath\n\ncmath.sqrt(-1)\n```\n\n\n\n\n 1j\n\n\n\n\n```python\na = 'This is a test sentance'\n\nprint(a)\n\nprint(a.upper())\n\nprint(a.split())\n```\n\n This is a test sentance\n THIS IS A TEST SENTANCE\n ['This', 'is', 'a', 'test', 'sentance']\n\n\n\n```python\nb = \"The dog is hungry. The cat is bored. The snake is awake.\"\nprint(b)\n\ns=b.split(\".\")\n\nprint(s)\n\nprint(\".\".join(s))\n\nprint(\" STOP\".join(s))\n```\n\n The dog is hungry. The cat is bored. The snake is awake.\n ['The dog is hungry', ' The cat is bored', ' The snake is awake', '']\n The dog is hungry. The cat is bored. The snake is awake.\n The dog is hungry STOP The cat is bored STOP The snake is awake STOP\n\n\n\n```python\na = [1, 2, 3]\n\nprint(a)\n\na.append(45)\n\nprint(a)\n\na.remove(2)\n\nprint(a)\n```\n\n [1, 2, 3]\n [1, 2, 3, 45]\n [1, 3, 45]\n\n\n\n```python\nprint(range(3, 10))\n\nfor i in range(3,11):\n print(i**2)\n```\n\n range(3, 10)\n 9\n 16\n 25\n 36\n 49\n 64\n 81\n 100\n\n\n\n```python\na = 100, 200, 'duck'\nprint(a)\nprint(type(a))\n\nx, y = 10, 20\nprint(x)\nprint(y)\n\nx, y = y, x\nprint(x)\nprint(y)\n```\n\n (100, 200, 'duck')\n \n 10\n 20\n 20\n 10\n\n\n\n```python\na = 'dog cat mouse'\na = a.split()\nprint(a[0])\nprint(a[-1])\nprint(a[-2:])\n```\n\n dog\n mouse\n ['cat', 'mouse']\n\n\n\n```python\n## Dictionaries\nd = {}\nd['today'] = [1, 2, 3]\n\nd['yesterday'] = '19 deg C'\n\nprint(d.keys())\nprint(d.values())\nprint(d.items())\n\nprint(d)\nprint(d['today'])\nprint(d['today'][1])\n\n# Other methods for creating dictionaries\nd2 = {2:4, 3:9, 4:16}\nprint(d2)\n\nd3 = dict(a=1, b=2, c=3)\nprint(d3)\nprint(d3['a'])\n\nprint(d.__contains__('today'))\nd.get('today','unknown')\n```\n\n dict_keys(['yesterday', 'today'])\n dict_values(['19 deg C', [1, 2, 3]])\n dict_items([('yesterday', '19 deg C'), ('today', [1, 2, 3])])\n {'yesterday': '19 deg C', 'today': [1, 2, 3]}\n [1, 2, 3]\n 2\n {2: 4, 3: 9, 4: 16}\n {'a': 1, 'c': 3, 'b': 2}\n 1\n True\n\n\n\n\n\n [1, 2, 3]\n\n\n\n\n```python\n# Dictionary Example\n\n# create an empty directory\norder = {}\n\n# add orders as they come in\norder['Peter'] = 'Pint of bitter'\norder['Paul'] = 'Half pint of Hoegarden'\norder['Mary'] = 'Gin Tonic'\n\n# deliver order at bar\nfor person in order.keys():\n print(person, \"requests\", order[person])\n\n```\n\n Paul requests Half pint of Hoegarden\n Mary requests Gin Tonic\n Peter requests Pint of bitter\n\n\n\n```python\n#Copying and Identity\n\na = [1, 2, 3, 4, 5]\nb=a\nb[0] = 42\n\nprint(a)\n\nc = a[:]\nc[1] = 99\n\nprint(a)\nprint(c)\nprint('id a: ', id(a))\nprint('id b: ', id(b))\nprint('id c: ', id(c))\n```\n\n [42, 2, 3, 4, 5]\n [42, 2, 3, 4, 5]\n [42, 99, 3, 4, 5]\n id a: 72139272\n id b: 72139272\n id c: 67450824\n\n\n## Chapter 4, Introspection\n\n* Magic names start and end with a double underscore\n* `isinstance(, )` Returns true if the given object is of the given type.\n* `help()`\n* `help()` Starts aand interactive help utility\n* Provide a docstring for user defined functions\n\n\n\n```python\n# Example of documenting a user defined function and calling it.\n\ndef power2and3(x):\n \"\"\"Returns the tuple (x**2, x**3)\"\"\"\n return x**2 ,x**3\n\nprint(power2and3(2))\n\nprint(power2and3.__doc__)\n\nhelp(power2and3)\n```\n\n (4, 8)\n Returns the tuple (x**2, x**3)\n Help on function power2and3 in module __main__:\n \n power2and3(x)\n Returns the tuple (x**2, x**3)\n \n\n\n## Chapter 5, Input and Output\n\n* String specifiers, reprinted table below\n* Pg 54-55 for a more elegant method of string formatting used in Python 3\n* `fileobject.readlines()` method returns a list of strings\n \n\n\n\n```python\n## Copied from pg 52.\n\nAU = 149597870700 #Astronomical unit in [m]\n\"%g\" %AU\n```\n\n\n\n\n '1.49598e+11'\n\n\n\n|Specifier|Style|Example Output for AU|\n|:---:|:---:|:---|\n|`%f`|Floating Point|149597870700.000000|\n|`%e`|Exponential Notation|1.495979e+11|\n|`%g`|Shorter of %e or %f|1.49598e+11|\n|`%d`|Integer|149597870700|\n|`%s`|String|149597870700|\n|`%r`|repr|149597870700L|\n\n\n\n\n\n```python\na = math.pi\n\nprint(\"Short pi = %.2f. longer pi = %.12f.\" %(a, a))\n```\n\n Short pi = 3.14. longer pi = 3.141592653590.\n\n\n\n```python\n## Reading and Writing Files\n\n#1. Write a File\nout_file = open(\"test.txt\", \"w\") # 'w' stands for Writing\nout_file.write(\"Writing text to file. This is the first line.\\n\"\n \"And the second lineasdfa.\")\nout_file.close() # close the file\n\n#2. Read a File\nin_file = open(\"test.txt\", \"r\") # 'r' stands for Reading\ntext = in_file.read()\n\nin_file.close()\n\n#3. Display Data\nprint (text)\n```\n\n Writing text to file. This is the first line.\n And the second lineasdfa.\n\n\n\n```python\n## Readlines Example\n\nmyexp = open(\"myfile.txt\", \"w\") # 'w' stands for Writing\nmyexp.write(\"This is the first line.\\n\"\n \"This is the second line.\\n\"\n \"This is the third and last line.\")\nmyexp.close()\n\nf = open('myfile.txt', \"r\")\nprint(len(f.read()))\nf.close()\n\nf = open('myfile.txt', \"r\")\nfor line in f.readlines():\n print(\"%d characters\" %len(line))\nf.close()\n```\n\n 81\n 24 characters\n 25 characters\n 32 characters\n\n\n# Chapter 6, Control Flow\n\n* If-then-else statements\n* For loops\n* use logical operators \"`and`\" and \"`or`\" to combine conditions\n* Read chapter 8 for more on errors and exceptiosn, help('exceptions')\n\n\n```python\na = 17\n\nif a == 0:\n print(\"a is zero\")\nelif a < 0:\n print(\"a is negative\")\nelse:\n print(\"a is positive\")\n```\n\n a is positive\n\n\n\n```python\n# for example\nfor animal in ['dog', 'cat', 'mouse']:\n print(animal, animal.upper())\n \nfor i in range(5,10):\n print(i)\n```\n\n dog DOG\n cat CAT\n mouse MOUSE\n 5\n 6\n 7\n 8\n 9\n\n\n## Chapter 7, Functions and Modules\n\n* A function takes an argument and returns a result or return value.\n* Function parameter may have default values.\n * ie. `def print_multi_table(n, upto=10):`\n* Common to have an `if __name__ == \"__main__` to output results and capabilities only seen when program is runnin on its own.\n\nGeneric Function Format:\n\n def my_function(arg1, arg2, ..., argn):\n \"\"\"Optional docstring.\"\"\"\n \n #Implementation of the function\n \n return result #optional\n\n #this is not part of the function\n some_command\n \n\n\n## Chapter 8, Functional Tools\n\n* Examples using the tools `filter`, `reduce`, and `lamda`.\n* An anonymous function is only needed once or needs no name\n * `lambda x : x**2`\n * `(lambda x, y, z: (x + y) * z)(10, 20, 2)`\n* The map function applies function f to all elements in sequence s, `lst2 = map(f,s)`\n * `map(lambda x:x**2, range(10))`\n* The filter function applies the function f to all elements in a sequence s, `lst2 = filter(f, lst)`\n * The filet function should return a true or false.\n * `filter(lambda x:x>5,range(11))`\n* List comprehension is an expression followed by a for clause, then zero or more for or if clauses. More consise then the above methods.\n\n\n\n```python\n## Maps\n\ndef f(x):\n return x**2\n\n# Two methods to print\nprint(list(map(f, range(10))))\n\nfor ch in map(f, range(10)):\n print(ch)\n\n#Combining with Lambda\nprint(list(map(lambda x:x**2,range(10))))\n \n```\n\n [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]\n 0\n 1\n 4\n 9\n 16\n 25\n 36\n 49\n 64\n 81\n [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]\n\n\n\n```python\n## List Comprehensions\n\nvec = [2, 4, 6]\nprint(vec)\nprint([3 * x for x in vec])\nprint([3 * x for x in vec if x >3])\nprint([3 * x for x in vec if x <2])\nprint([[x, x**2] for x in vec])\n```\n\n [2, 4, 6]\n [6, 12, 18]\n [12, 18]\n []\n [[2, 4], [4, 16], [6, 36]]\n\n\n## Chapter 9, Common Tasks\n\n* Illustrates many ways to compute a series to illustrate the differnt methods possible and also illustrate the different methods we've previously discussed. Includes a check method and doc file.\n* `sorted` returns a copy of a sorted list while `sort` changes the list insto a sorted order of elements\n\n\n## Chapter 10, Matlab to Python\n* Common differences\n* The extension library numpy provides matrix functionality similar to Matlab\n\n## Chapter 11, Python Shells\n\n* Useful features of different Python shells\n* iPython, IPython Notebook, Spyder\n\n## Chapter 12, Symbolic Computation\n\n* SymPy is the Python Symbolic library, [SymPy Homepage](http://sympy.org) for full and up-to-date documentation\n* Very slow compared to floating point opperation\n* isympy an exexutable wrapper around python, convenient for figuring out new features or experementing interactively\n* Rational type, Rational(1,2) represents 1/2.\n * Rational class works exactly as opposed to the standard float.\n* If Sympy returns the result in an unfamiliar form, subtract it with the expected form to determine if they are equivalent.\n* Calculate definite integrals with a tuple containing the variable of interest, lower, and upper bounds.\n* Results from dsolve are an Equality class, function needs to be evaluated to a number to be plotted.\n* Covers series expansion\n* LaTeX and Pretty printing\n* `preview()` allows you to display rendered output on the screen\n* Automatic generation of C code via `codegen()`\n\n\n\n```python\n## Symbols\n\nimport sympy\n\nx, y, z = sympy.symbols('x, y, z')\n\na = x + 2*y + 3*z - x\n\nprint(a)\n\nprint(sympy.sqrt(8))\n```\n\n 2*y + 3*z\n 2*sqrt(2)\n\n\n\n```python\nx, y = sympy.symbols('x,y')\na = x + 2*y\nprint(a.subs(x, 10))\nprint(a.subs(x,10).subs(y,3))\nprint(a.subs({x:10, y:3}))\n\nSS_77 = -y + -23.625*x**3 - 5.3065*x**2 + 5.6633*x\nSS_52 = -y + -245.67*x**3 + 31.951*x**2 + 4.4341*x\nSS_36 = -y + -18.58*x**3 - 5.4025*x**2 + 2.1623*x\n\n\n\n#print(\"t0 = 36, 0.5 Strain at %.2f MPa\" % sympy.solve(SS_36.subs(y, 0.5),x)[0])\n#print(\"t0 = 52, 0.5 Strain at %.2f MPa\" % sympy.solve(SS_52.subs(y, 0.5),x)[0])\n#print(\"t0 = 77, 0.5 Strain at %.2f MPa\" % sympy.solve(SS_77.subs(y, 0.5),x)[0])\n\nprint(\"t0 = 36, 0.01 Stress at %.3f Strain\" % sympy.solve(SS_36.subs(x, .01),y)[0])\nprint(\"t0 = 52, 0.01 Stress at %.3f Strain\" % sympy.solve(SS_52.subs(x, .01),y)[0])\nprint(\"t0 = 77, 0.01 Stress at %.3f Strain\" % sympy.solve(SS_77.subs(x, .01),y)[0])\n```\n\n 2*y + 10\n 16\n 16\n t0 = 36, 0.01 Stress at 0.021 Strain\n t0 = 52, 0.01 Stress at 0.047 Strain\n t0 = 77, 0.01 Stress at 0.056 Strain\n\n\n\n```python\na = sympy.Rational(2,3)\nprint(a)\nprint(float(a))\nprint(a.evalf())\nprint(a.evalf(50))\n```\n\n 2/3\n 0.6666666666666666\n 0.666666666666667\n 0.66666666666666666666666666666666666666666666666667\n\n\n\n```python\n# Differentiation\n\nprint(sympy.diff(3*x**4, x))\nprint(sympy.diff(3*x**4, x, x, x))\nprint(sympy.diff(3*x**4, x, 3))\n```\n\n 12*x**3\n 72*x\n 72*x\n\n\n\n```python\n## Integration\n\nfrom sympy import integrate\n\nprint(integrate(sympy.sin(x), y))\nprint(integrate(sympy.sin(x), x))\n\n# Definite Integrals\nprint(integrate(x*2, x))\nprint(integrate(x*2, (x, 0, 2)))\nprint(integrate(x**2, (x,0,2), (x, 0, 2), (y,0,1)))\n```\n\n y*sin(x)\n -cos(x)\n x**2\n 4\n 16/3\n\n\n\n```python\n## Ordinary Differential Equations\n\nfrom sympy import Symbol, dsolve, Function, Derivative, Eq\n\ny = Function(\"y\")\nx = Symbol('x')\ny_ = Derivative(y(x), x)\nprint(dsolve(y_ + 5*y(x), y(x)))\nprint(dsolve(Eq(y_ + 5*y(x), 0), y(x)))\nprint(dsolve(Eq(y_ + 5*y(x), 12), y(x)))\n```\n\n Eq(y(x), C1*exp(-5*x))\n Eq(y(x), C1*exp(-5*x))\n Eq(y(x), C1*exp(-5*x)/5 + 12/5)\n\n\n\n```python\n## Linear Equations and Matrix Inversion\n\nfrom sympy import symbols, Matrix\n\nx, y, z = symbols('x,y,z')\n\nA = Matrix(([3,7], [4,-2]))\nprint(A)\n\nprint(A.inv())\n```\n\n Matrix([[3, 7], [4, -2]])\n Matrix([[1/17, 7/34], [2/17, -3/34]])\n\n\n\n```python\n## Solving Non Linear Equations\n\nimport sympy\n\nx, y, z = sympy.symbols('x,y,z')\neq = x - x**2\nprint(sympy.solve(eq,x))\n```\n\n [0, 1]\n\n\n## Chapter 14, Numerical Calculation\n\n* Limitations of the different number types: int, float, complex, and long.\n* Comparing float and symbolic time to compute.\n\n## Chapter 15, Numerical Python (numpy): arrays\n\n* The data structure, `array`, allows efficient matrix and vector operation\n* An array can only keep elements of the same type, as opposed to lists which can hold a mix.\n* Convert a matrix back tp a list or tuple using, `list(s)` or `tuple(s)`.\n* Computing eiganvectors and eiganvalues\n* Numpy examples at [SciPy.org](http://www.scipy.org/Numpy_Example_List)\n\n\n\n\n```python\n## Vectors (1d-arrays)\n\nimport numpy as N\n\nx = N.array([0, 0.5, 1, 1.5])\n\nprint(x)\n\nprint(N.zeros(4))\na = N.zeros((5,4))\nprint(a)\nprint(a.shape)\n\nprint(a[2,3])\n\nrandom_matrix = N.random.rand(5,5)\nprint(random_matrix)\n\nx = N.random.rand(5)\n\nb = N.dot(random_matrix, x)\nprint(\"b= \", b)\n\n```\n\n [ 0. 0.5 1. 1.5]\n [ 0. 0. 0. 0.]\n [[ 0. 0. 0. 0.]\n [ 0. 0. 0. 0.]\n [ 0. 0. 0. 0.]\n [ 0. 0. 0. 0.]\n [ 0. 0. 0. 0.]]\n (5, 4)\n 0.0\n [[ 0.62986856 0.08414351 0.86029432 0.23673407 0.69039432]\n [ 0.09499312 0.46304194 0.83582097 0.80421487 0.99190126]\n [ 0.98594909 0.58822546 0.86016599 0.41493799 0.31856799]\n [ 0.91495891 0.38045604 0.67692051 0.39180708 0.22073492]\n [ 0.65115666 0.67522929 0.69594017 0.13819881 0.62083603]]\n b= [ 0.39203078 0.83042469 0.85378184 0.62487284 0.88562137]\n\n\n\n```python\n## Curve Fitting of Polynomial Example\n\nimport numpy\n\n# demo curve fitting: xdata and ydata are input data\nxdata = numpy.array([0.0, 1.0, 2.0, 3.0, 4.0, 5.0])\nydata = numpy.array([0.0, 0.8, 0.9, 0.1, -0.8, -1.0])\n\n#now fit for cubic (order = 3) polynomial\nz = numpy.polyfit(xdata, ydata, 3)\n\n#z is an array of coefficients, highest first, i.e.\n# x^3 X^2 X 0\n#z=array([0.08703704, -0.8134, 1.693, -0.0396])\n\nprint(\"z = \", z)\n\n#It is convenient to use `poly1d` objects for dealing with polynomials\np = numpy.poly1d(z) #Creates a polynomial function p from coefficients and p can be evaluated for all x then.\n\nprint(\"p = \",p)\n\n#Create a plot\nxs = [0.1 * i for i in range(50)]\nys = [p(x) for x in xs] # evaluates p(x) for all x in list xs\n\n%matplotlib inline\nimport pylab\npylab.plot(xdata, ydata, 'o', label = 'data')\npylab.plot(xs, ys, label = 'fitted curve')\npylab.ylabel('y')\npylab.xlabel('x')\n#pylab.savefig('polyfit.pdf')\npylab.show()\n```\n\n## Chapter 15, Visualizing Data\n\n* Need to include all the useful links here\n* IPython Inline mode via: `%matplotlib inline`, `%matplotlib qt`, or `%pylab`.\n* `help(pylab.legend)` for legend placement information\n* `help(pylab.plot)` for line style, color, thickness, etc calls\n * Colors can be called out in RGB, Hex, greyscale, etc.\n* Subplot to call more than one plot in one figure, `pylab.subplot(numRows, numCols, plotNum)`.\n* Multiple figures via: `pylab.figure(figNum)`.\n* `pylab.close()` may be used to close one, some, or all figures.\n* Use `pyplot.imshow()` to visualize matrix data (heat plot).\n * Use different color maps with the module `matplotlib.cm`\n* Check out the contour_demo.py example for illustrating `z=f(x,y)`\n* Visual Python is a module that allows you to create and animate 3D scenes.\n * Visual Python [Home Page](http://vpython.org)\n * Useful for illustrating time dependent data\n* Visualising 2D and 3D fields as a function of time with the Visualization Toolkit, [VTK](http://vtk.org).\n* Other modules: Mayavi, Paraview, and VisIt.\n\n\n\n\n```python\n## Plot details example\n\nimport pylab\nimport numpy as N\n\n%matplotlib inline\n\nx = N.arange(-3.14, 3.14, 0.01)\ny1 = N.sin(x)\ny2 = N.cos(x)\n\npylab.figure(figsize=(5,5)) #Sets figure size to 5 x 5 in.\npylab.plot(x, y1, label='sin(x)')\npylab.plot(x, y2, label='cos(x)')\npylab.legend()\npylab.grid()\npylab.xlabel('x')\npylab.title('This is the Title')\npylab.axis([-2,2,-1,1])\npylab.show()\n\n```\n\n\n```python\n## Histogram Example\n\nimport numpy as np\nimport matplotlib.mlab as mlab\nimport matplotlib.pylab as plt\n\n# create data\nmu, sigma = 100, 15\nx = mu + sigma * np.random.randn(10000)\n\n#histogram of the data\nn, bins, patches = plt.hist(x, 50, normed=1, facecolor='green', alpha=0.75)\n\n#fine tuning the plot\nplt.xlabel('Smarts')\nplt.ylabel('Probability')\n\n#LaTeX strings for labels and titles\nplt.title(r'$\\mathrm{Histogram\\ of\\ IQ :}\\ \\mu=100,\\ \\sigma=15$')\nplt.axis([40, 160, 0, 0.03])\nplt.grid(True)\n\n#add a best fit line curve\ny = mlab.normpdf(bins, mu, sigma)\nl = plt.plot(bins, y, 'r--', linewidth=1)\n \n#Save to file\n#plt.savefig('pylabhistogram.pdf')\n#then display\nplt.show()\n\n```\n\n## Chapter 16, Numerical Methods using Python (scipy)\n\n* The `scipy` package privides numerous numerical algorithms\n* All functionality from `numpy` may be available in `scipy`\n* Using `help(scipy)` will detail the package structure. You can call specific sections ie. `import scipy.integrate`.\n* Use `scipy.quad()` to solve integrals of the form $\\int_{a}^{b} f(x)dx$\n * Functions that approach +/- inf may be difficult to handle numerically. Plot results with integand to check\n* Use `scipy.odeint()` to solve differential equations of the type $\\frac{\\partial y}{\\partial t}(t) = f(y,t)$\n * `help(scipy.integrate.odeint)` to explore differnet error tolerance options\n* Using the `bisect()` method to find roots. Requires arguments f(x), lower limit, and upper limit. Optional xtol parameter.\n* Using `fsolve()` to find roots is more efficient, but not garunteed to converge. Input argument is a starting location suspected close to the root.\n* The function `y0 = scipy.interpolate.interp1d(x, y, kind='nearest')` may be used to interpolate the data $(x_i, y_i)$ for all x.\n* A generic curve fitting function is provided with `scipy.optimize.curve_fit()`\n* FFT example below\n* Optimization, using `scipy.optimize.fmin()` to find the minimum of a function. Arguments are the function and starting point.\n\n\n\n\n```python\n## Integral Example\n\nfrom math import cos, exp, pi\nfrom scipy.integrate import quad\n\n#function we want to integrate\ndef f(x):\n return exp(cos(-2 * x * pi)) + 3.2\n\n#call quad to integrate f from -2 to 2\nres, err = quad(f, -2, 2)\n\nprint(\"The numerical result is {:f} (+/-{:.2g})\" .format(res, err))\n```\n\n The numerical result is 17.864264 (+/-1.6e-11)\n\n\n\n```python\n## ODE Example\n\nfrom scipy.integrate import odeint\nimport numpy as N\n\ndef f(y,t):\n \"\"\"This returns the RHS of the ODE to integrate, i.e. dy/dt = f(y,t)\"\"\"\n return(-2 * y * t)\n\ny0 = 1 # initial value\na = 0 # integration limits for t\nb = 2\n\nt = N.arange(a, b, 0.01) # values of t for which we require the solution y(t)\n\ny = odeint(f, y0, t) # actual computation of y(t)\n\nimport pylab # Plotting of results\n\n%matplotlib inline\npylab.plot(t, y)\npylab.xlabel('t'); pylab.ylabel('y(t)')\npylab.show()\n```\n\n\n```python\n## FFT exmaple\n# Create a superposition of 50 and 70 Hz and plot the fft.\n\nimport scipy\nimport matplotlib.pyplot as plt\n%matplotlib inline\npi = scipy.pi\n\nsignal_length = 0.5 # [seconds]\nsample_rate = 500 # sampling rate [Hz]\ndt = 1./sample_rate # delta t [s]\n\ndf = 1/signal_length # frequency between points in the freq. domain [Hz]\n\nt = scipy.arange(0, signal_length, dt) # the time vector\nn_t = len(t) # length of the time vector\n\n# create signal\ny = scipy.sin(2*pi*50*t) + scipy.sin(2*pi*70*t + pi/4)\n\n# compute the fourier transport\nf = scipy.fft(y)\n\n# work out meaningful frequencies in fourier transform\nfreqs = df*scipy.arange(0,(n_t-1)/2.,dtype='d') #d = double precision float\nn_freq = len(freqs)\n\n# plot input data y against time\nplt.subplot(2,1,1)\nplt.plot(t, y, label='input data')\nplt.xlabel('time [s]')\nplt.ylabel('signal')\n\n# plot frequency spectrum\nplt.subplot(2,1,2)\nplt.plot(freqs, abs(f[0:n_freq]), label='abs(fourier transform)')\nplt.xlabel('frequency [Hz]')\nplt.ylabel('abs(DFT(signal))')\n\n# save plot to disk\n#plt.savefig('fft1.pdf')\nplt.show()\n```\n\n## Chapter 17, Where to go from here?\n\n* A list of additional skills for computational science work.\n", "meta": {"hexsha": "4f615a67405c3dbdfe3c62abf137f1122836a929", "size": 134982, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "public/ipy/Fangohr_2015/Fangohr_Python_Intro.ipynb", "max_stars_repo_name": "stembl/stembl.github.io", "max_stars_repo_head_hexsha": "5108fc33dccd8c321e1840b62a4a493309a6eeff", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2016-12-10T04:04:33.000Z", "max_stars_repo_stars_event_max_datetime": "2016-12-10T04:04:33.000Z", "max_issues_repo_path": "public/ipy/Fangohr_2015/Fangohr_Python_Intro.ipynb", "max_issues_repo_name": "stembl/stembl.github.io", "max_issues_repo_head_hexsha": "5108fc33dccd8c321e1840b62a4a493309a6eeff", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2021-05-18T07:27:17.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-26T02:16:11.000Z", "max_forks_repo_path": "public/ipy/Fangohr_2015/Fangohr_Python_Intro.ipynb", "max_forks_repo_name": "stembl/stembl.github.io", "max_forks_repo_head_hexsha": "5108fc33dccd8c321e1840b62a4a493309a6eeff", "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": 84.6282131661, "max_line_length": 27336, "alphanum_fraction": 0.8158643375, "converted": true, "num_tokens": 7348, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218391455085, "lm_q2_score": 0.9343951652812919, "lm_q1q2_score": 0.8614393092648}} {"text": "```python\n#@title Imports { display-mode: \"form\" }\nfrom __future__ import print_function\nfrom __future__ import division\nfrom __future__ import absolute_import\n\nimport numpy as np\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\n\n#try:\n# tf.enable_eager_execution()\n# print('Eager execution enabled')\n#except ValueError:\n# print('Already running in Eager mode')\n\n#tfe = tf.contrib.eager\n!pwd\n```\n\n /Users/jchibueze/Downloads/Tutorials/James\r\n\n\n## Matrix Multiplication\n\n\n```python\n# Define matrix A\nA = np.array(\n [[1.0, 3.0],\n [2.0, 1.0],\n [4.0, 2.0]]\n)\n\n# Define matrix B\nB = np.array(\n [[6.0, 2.0, 1.0],\n [3.0, 4.0, 5.0]]\n)\n\n# Define vector x\nx = np.array([3.0, 2.0])\n\nprint('A.shape is:', A.shape, 'B.shape is:', B.shape, 'x.shape is:', x.shape)\nA\n```\n\n### Matrix-vector multiplication\n\n\n```python\n# Using numpy dot\ny = A.dot(x)\n\nprint('Using dot:\\t y =', y, '\\t y.shape =', y.shape)\n\n# Using einsum\ny = np.einsum('ij, j', A, x)\n\nprint('Using einsum:\\t y =', y, '\\t y.shape =', y.shape)\n\n# Manual version 1\ny = np.array([\n A[0,0] * x[0] + A[0,1] * x[1],\n A[1,0] * x[0] + A[1,1] * x[1],\n A[2,0] * x[0] + A[2,1] * x[1],\n ])\nprint('Manual 1:\\t y =', y, '\\t y.shape =', y.shape)\n\n# Manual version 2: \n# Matrix-vector multiplication can be thought of as a linear combination of the columns of of the matrix\ny = x[0] * A[:,0] + x[1] * A[:, 1]\n\nprint('Manual 2:\\t y =', y, '\\t y.shape =', y.shape)\n```\n\n### Matrix-matrix multiplication\n\n\n```python\n# Using numpy dot\nC = A.dot(B)\n\nprint('Using DOT: C= \\n\\n', C, '\\n\\nC.shape =', C.shape)\n\n# Using einsum\nC = np.einsum('ik, kj', A, B)\nprint('\\n\\nUsing einsum: C= \\n\\n', C, '\\n\\nC.shape =', C.shape)\n\n# Note, the above einsum notation is equivalent to the following\nC = np.einsum('ik, kj -> ij', A, B)\n\n# And in Tensorflow\nC = tf.matmul(A, B)\nprint('\\n\\nUsing Tensorflow: C= \\n\\n', C, '\\n\\nC.shape =', C.shape)\n```\n\nMatrix multiplication is not commutative\n\n\n```python\n# Matrix multiplication is not commutative:\nC = B.dot(A)\nprint('C: \\n', C)\nprint()\nprint('C.shape:', C.shape)\n```\n\n## Computing gradients with TensorFlow\n$y = Ax$\n\nIn the code below, we use Tensorflow to calculate the following derivatives:\n\n$\\frac{dy}{dx}$ \n\nand \n\n$\\frac{\\partial y}{\\partial A}$ \n\n\n```python\nA_tensor = tf.Variable(A)\nx_tensor = tf.Variable(x)\n\nwith tf.GradientTape() as tape:\n y = tf.einsum('ij,j', A_tensor, x_tensor)\n\ndydx, dydA = tape.gradient(y, [x_tensor, A_tensor])\n\nprint('dy/dx =', dydx)\nprint()\nprint('dy/dA =', dydA)\n```\n\n# Neural Network Gradient Example\nIn the following example, we compute the output of a 1 layer neural network and the gradients with respect to its parameters. We define an example input vector and parameters, but keep the computation generic. You can change the values and shapes of x, A and b below and run the rest of the code to compute the output and gradients for your own example.\n\n\n```python\nx = np.array([[-1.], [0.1], [2.1]]) # X has shape (3, 1)\nA = np.array([ # A has shape (2, 3)\n [ 1.1, -2.5, 0.3],\n [-2.1, 0.2, -1.1]\n]) \nb = np.array([[-1.0], [2.0]]) # b has shape (2)\n```\n\nCompute the neural network output\n$\\mathbf{f} = \\operatorname{tanh}(A\\mathbf{x} + \\mathbf{b})$\n\n\n```python\nM, N = A.shape\nz = A.dot(x) + b\nf = np.tanh(z)\n\nprint('f =', f)\n```\n\nCompute the partial derivatives:\n\n\\begin{align}\n\\frac{d\\mathbf{f}}{d\\mathbf{z}} ; \\frac{\\partial\\mathbf{z}}{\\partial\\mathbf{x}} ; \\frac{\\partial\\mathbf{z}}{\\partial\\mathbf{b}} ; \\frac{\\partial\\mathbf{z}}{\\partial\\mathbf{A}}\n\\end{align}\n\n\n```python\n# partial derivatives\ndfdz = 1-f**2 # (derivative of tanh is 1-tanh^2)\nprint('df/dz =', dfdz, '\\nshape:', dfdz.shape)\nprint()\n\ndzdx = A\nprint('dz/dx =\\n', dzdx, '\\n\\nshape:', dzdx.shape)\nprint()\n\ndzdb = np.eye(M)\nprint('dz/db =\\n', dzdb, '\\n\\nshape:', dzdb.shape)\nprint()\n\ndzdA = np.zeros((M, M, N)) # Start with a tensor of zeros of the correct shape\nfor i in range(M): # Then set the diagonal elements of dzdA\n dzdA[i,i,:] = x.T \n\nprint('dz/dA =\\n', dzdA, '\\n\\nshape:', dzdA.shape)\n\n\n```\n\nFinally, we compute the gradients of the neural network output $f$ with respect to the parameters $A$ and $\\mathbf{b}$ and the input $\\mathbf{x}$ using the chain rule:\n\n\\begin{align}\n\\frac{\\partial \\mathbf{f}}{\\partial \\mathbf{x}} &= \\frac{d \\mathbf{f}}{d \\mathbf{z}} \\frac{\\partial \\mathbf{z}}{\\partial \\mathbf{x}} \\ ; \\ \n\\frac{\\partial \\mathbf{f}}{\\partial \\mathbf{b}} = \\frac{d \\mathbf{f}}{d \\mathbf{z}} \\frac{\\partial \\mathbf{z}}{\\partial \\mathbf{b}} \\ ; \\ \n\\frac{\\partial \\mathbf{f}}{\\partial A} = \\frac{d \\mathbf{f}}{d \\mathbf{z}} \\frac{\\partial \\mathbf{z}}{\\partial A} \n\\end{align}\n\n\n```python\ndfdx = np.einsum('il, lj', dfdz, dzdx)\nprint('df/dx =\\n', dfdx, '\\n\\nshape:', dfdx.shape)\nprint()\n\ndfdb = np.einsum('il, lj', dfdz, dzdb)\nprint('df/db =\\n', dfdb, '\\n\\nshape:', dfdb.shape)\nprint()\n\ndfdA = np.einsum('il, ljk', dfdz, dzdA)\nprint('df/dA =\\n', dfdA, '\\n\\nshape:', dfdA.shape)\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "988d990f535754f63c9916df344e2faceb69da1f", "size": 11258, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "PythonIntroduction/WAISSYA_2019_Mathematics_for_Machine_Learning_Examples.ipynb", "max_stars_repo_name": "jielaizhang/pasea", "max_stars_repo_head_hexsha": "08b663e27ffc8d2b119bfa6c3a0bcbe901c11b2f", "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": "PythonIntroduction/WAISSYA_2019_Mathematics_for_Machine_Learning_Examples.ipynb", "max_issues_repo_name": "jielaizhang/pasea", "max_issues_repo_head_hexsha": "08b663e27ffc8d2b119bfa6c3a0bcbe901c11b2f", "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": "PythonIntroduction/WAISSYA_2019_Mathematics_for_Machine_Learning_Examples.ipynb", "max_forks_repo_name": "jielaizhang/pasea", "max_forks_repo_head_hexsha": "08b663e27ffc8d2b119bfa6c3a0bcbe901c11b2f", "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": 25.4130925508, "max_line_length": 359, "alphanum_fraction": 0.5000888257, "converted": true, "num_tokens": 1749, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248242542284, "lm_q2_score": 0.9173026612812898, "lm_q1q2_score": 0.8613699702975991}} {"text": "\n\n# Part 1 - Scalars and Vectors\n\nFor the questions below it is not sufficient to simply provide answer to the questions, but you must solve the problems and show your work using python (the NumPy library will help a lot!) Translate the vectors and matrices into their appropriate python representations and use numpy or functions that you write yourself to demonstrate the result or property. \n\n\n```\nimport math\nimport matplotlib.pyplot as plt\nimport numpy as np\n```\n\n## 1.1 Create a two-dimensional vector and plot it on a graph\n\n\n```\nred = [1, 1]\n\nplt.arrow(0,0, red[0], red[1],head_width=.05, head_length=0.05, color ='red')\n\nplt.xlim(0,2) \nplt.ylim(0,2)\nplt.title(\"One Two-Dimentional Vector\")\n\nplt.show()\n```\n\n## 1.2 Create a three-dimensional vecor and plot it on a graph\n\n\n```\nfrom mpl_toolkits.mplot3d import Axes3D\n\nred_3d = [1, 1, 1]\n\nvectors = np.array([[0, 0, 0, 1, 1, 1]])\n\nX, Y, Z, U, V, W = zip(*vectors)\nfig = plt.figure()\nax = fig.add_subplot(111, projection='3d')\nax.quiver(X, Y, Z, U, V, W, length=1, color='red')\nax.set_xlim([0, 1])\nax.set_ylim([0, 1])\nax.set_zlim([0, 1])\nax.set_xlabel('X')\nax.set_ylabel('Y')\nax.set_zlabel('Z')\nplt.show()\n\n\n\n\n\n```\n\n## 1.3 Scale the vectors you created in 1.1 by $5$, $\\pi$, and $-e$ and plot all four vectors (original + 3 scaled vectors) on a graph. What do you notice about these vectors? \n\n\n```\nred = [1, 1]\n\nblue = np.multiply(5, red)\ngreen = np.multiply(np.pi, red)\nyellow = np.multiply(-np.exp(1), red)\n\nplt.arrow(0,0, red[0], red[1],head_width=.05, head_length=0.05, color ='red', width = 0.05)\nplt.arrow(0,0, blue[0], blue[1],head_width=.05, head_length=0.05, color ='blue')\nplt.arrow(0,0, green[0], green[1],head_width=.05, head_length=0.05, color ='green')\nplt.arrow(0,0, yellow[0], yellow[1],head_width=.05, head_length=0.05, color ='yellow')\n\nplt.xlim(-5,6) \nplt.ylim(-5,6)\nplt.title(\"Scaled Vectors\")\nplt.show()\n\n# The vectors are all in one line, just different lengths.\n# The -e is in the same line but pointed in opposite direction\n```\n\n## 1.4 Graph vectors $\\vec{a}$ and $\\vec{b}$ and plot them on a graph\n\n\\begin{align}\n\\vec{a} = \\begin{bmatrix} 5 \\\\ 7 \\end{bmatrix}\n\\qquad\n\\vec{b} = \\begin{bmatrix} 3 \\\\4 \\end{bmatrix}\n\\end{align}\n\n\n```\na = [5, 7]\nb = [3, 4]\n\nplt.arrow(0,0, a[0], a[1],head_width=.05, head_length=0.05, color ='red')\nplt.arrow(0,0, b[0], b[1],head_width=.05, head_length=0.05, color ='blue')\n\nplt.xlim(0,6) \nplt.ylim(0,8)\nplt.title(\"Plot of a and b Vectors\")\nplt.show()\n```\n\n## 1.5 find $\\vec{a} - \\vec{b}$ and plot the result on the same graph as $\\vec{a}$ and $\\vec{b}$. Is there a relationship between vectors $\\vec{a} \\thinspace, \\vec{b} \\thinspace \\text{and} \\thinspace \\vec{a-b}$\n\n\n```\na = np.array([5, 7])\nb = np.array([3, 4])\n\na_minus_b = np.subtract(a, b)\n\nplt.arrow(0,0, a[0], a[1],head_width=.05, head_length=0.05, color ='red')\nplt.arrow(0,0, b[0], b[1],head_width=.05, head_length=0.05, color ='blue')\nplt.arrow(0,0, a_minus_b[0], a_minus_b[1],head_width=.05, head_length=0.05, color ='green')\n\nplt.xlim(0,6) \nplt.ylim(0,8)\nplt.title(\"a Minus b in Green\")\nplt.show()\n\n# The difference between a and b is intuitively represented by the green vector\n# To get from the tip of blue (b) to the tip of red (a), you go over two and up 3\n# This is exactly the green (a minus b) vector\n```\n\n## 1.6 Find $c \\cdot d$\n\n\\begin{align}\n\\vec{c} = \\begin{bmatrix}7 & 22 & 4 & 16\\end{bmatrix}\n\\qquad\n\\vec{d} = \\begin{bmatrix}12 & 6 & 2 & 9\\end{bmatrix}\n\\end{align}\n\n\n\n```\nc = np.array([7, 22, 4, 16])\nd = np.array([12, 6, 2, 9])\n\nprint('The dot product of c and d:')\nnp.dot(c, d)\n```\n\n The dot product of c and d:\n\n\n\n\n\n 368\n\n\n\n## 1.7 Find $e \\times f$\n\n\\begin{align}\n\\vec{e} = \\begin{bmatrix} 5 \\\\ 7 \\\\ 2 \\end{bmatrix}\n\\qquad\n\\vec{f} = \\begin{bmatrix} 3 \\\\4 \\\\ 6 \\end{bmatrix}\n\\end{align}\n\n\n```\ne = np.array([5, 7, 2])\nf = np.array([3, 4, 6])\n\nprint('The cross product of e and f:')\nnp.cross(e, f)\n```\n\n The cross product of e and f:\n\n\n\n\n\n array([ 34, -24, -1])\n\n\n\n## 1.8 Find $||g||$ and then find $||h||$. Which is longer?\n\n\\begin{align}\n\\vec{g} = \\begin{bmatrix} 1 \\\\ 1 \\\\ 1 \\\\ 8 \\end{bmatrix}\n\\qquad\n\\vec{h} = \\begin{bmatrix} 3 \\\\3 \\\\ 3 \\\\ 3 \\end{bmatrix}\n\\end{align}\n\n\n```\ng = np.array([1, 1, 1, 8])\nh = np.array([3, 3, 3, 3])\n\nprint('Norm of g:')\nprint(np.linalg.norm(g))\nprint('\\n')\nprint('Norm of h:')\nnp.linalg.norm(h)\n\n#The Norm of g is longer\n```\n\n Norm of g:\n 8.18535277187245\n \n \n Norm of h:\n\n\n\n\n\n 6.0\n\n\n\n## 1.9 Show that the following vectors are orthogonal (perpendicular to each other):\n\n\\begin{align}\n\\vec{i} = \\begin{bmatrix} 1 \\\\ 0 \\\\ -1 \\end{bmatrix}\n\\qquad\n\\vec{j} = \\begin{bmatrix} 1 \\\\ \\sqrt{2} \\\\ 1 \\end{bmatrix}\n\\end{align}\n\n\n```\ni = np.array([1, 0, -1])\nj = np.array([1, np.sqrt(2), 1])\n\nnp.dot(i, j)\n\n# These two vectors are orthogonal because their dot product equals zero.\n# This means that these two vectors are linearly independent\n# No way to scale one to get the other -- on different planes\n```\n\n\n\n\n 0.0\n\n\n\n# Part 2 - Matrices\n\n## 2.1 What are the dimensions of the following matrices? Which of the following can be multiplied together? See if you can find all of the different legal combinations.\n\\begin{align}\nA = \\begin{bmatrix}\n1 & 2 \\\\\n3 & 4 \\\\\n5 & 6\n\\end{bmatrix}\n\\qquad\nB = \\begin{bmatrix}\n2 & 4 & 6 \\\\\n\\end{bmatrix}\n\\qquad\nC = \\begin{bmatrix}\n9 & 6 & 3 \\\\\n4 & 7 & 11\n\\end{bmatrix}\n\\qquad\nD = \\begin{bmatrix}\n1 & 0 & 0 \\\\\n0 & 1 & 0 \\\\\n0 & 0 & 1\n\\end{bmatrix}\n\\qquad\nE = \\begin{bmatrix}\n1 & 3 \\\\\n5 & 7\n\\end{bmatrix}\n\\end{align}\n\n\n```\n# Matrices Dimensions\n# A = 3x2\n# B = 1x3\n# C = 2x3\n# D = 3x3\n# E = 2x2\n\n# A*C, A*E\n# B*D\n# C*A, C*D\n# D*A\n# E*C\n\n# There are 7 possible combinations of multiplication\n\n```\n\n## 2.2 Find the following products: CD, AE, and BA. What are the dimensions of the resulting matrices? How does that relate to the dimensions of their factor matrices?\n\n\n```\nA = np.array([[1, 2],\n [3, 4],\n [5, 6]])\n\nB = np.array([[2, 4, 6]])\n\nC = np.array([[9, 6, 3],\n [4, 7, 11]])\n\nD = np.array([[1, 0, 0],\n [0, 1, 0],\n [0, 0, 1]])\n\nE = np.array([[1, 3],\n [5, 7]])\n```\n\n\n```\n# CD\nnp.matmul(C, D)\n```\n\n\n\n\n array([[ 9, 6, 3],\n [ 4, 7, 11]])\n\n\n\n\n```\n#AE\nnp.matmul(A, E)\n```\n\n\n\n\n array([[11, 17],\n [23, 37],\n [35, 57]])\n\n\n\n\n```\n#BA\nnp.matmul(B, A)\n```\n\n\n\n\n array([[44, 56]])\n\n\n\n## 2.3 Find $F^{T}$. How are the numbers along the main diagonal (top left to bottom right) of the original matrix and its transpose related? What are the dimensions of $F$? What are the dimensions of $F^{T}$?\n\n\\begin{align}\nF = \n\\begin{bmatrix}\n20 & 19 & 18 & 17 \\\\\n16 & 15 & 14 & 13 \\\\\n12 & 11 & 10 & 9 \\\\\n8 & 7 & 6 & 5 \\\\\n4 & 3 & 2 & 1\n\\end{bmatrix}\n\\end{align}\n\n\n```\nF = np.array([[20, 19, 18, 17],\n [16, 15, 14, 13],\n [12, 11, 10, 9],\n [8, 7, 6, 5],\n [4, 3, 2, 1]])\n```\n\n\n```\nF.T\n```\n\n\n\n\n array([[20, 16, 12, 8, 4],\n [19, 15, 11, 7, 3],\n [18, 14, 10, 6, 2],\n [17, 13, 9, 5, 1]])\n\n\n\n\n```\n# The main diagonal of F and F^t are the same\n# The the other numbers in F^t are flipped around the main diagonal\n# The dimension of F is 5x4, while the dimension of F is 4x5\n```\n\n# Part 3 - Square Matrices\n\n## 3.1 Find $IG$ (be sure to show your work) 😃\n\n\\begin{align}\nG= \n\\begin{bmatrix}\n12 & 11 \\\\\n7 & 10 \n\\end{bmatrix}\n\\end{align}\n\n\n```\nG = np.array([[12, 11],\n [7, 10]])\n```\n\n\n```\n# Identity matrix\nI = np.array([[1, 0],\n [0, 1]])\n```\n\n\n```\n# The product of any matrix with its Identity Matrix is just the original matrix\nnp.matmul(G, I)\n```\n\n\n\n\n array([[12, 11],\n [ 7, 10]])\n\n\n\n## 3.2 Find $|H|$ and then find $|J|$.\n\n\\begin{align}\nH= \n\\begin{bmatrix}\n12 & 11 \\\\\n7 & 10 \n\\end{bmatrix}\n\\qquad\nJ= \n\\begin{bmatrix}\n0 & 1 & 2 \\\\\n7 & 10 & 4 \\\\\n3 & 2 & 0\n\\end{bmatrix}\n\\end{align}\n\n\n\n```\nH = np.array([[12, 11],\n [7, 10]])\n\nJ = np.array([[0, 1, 2],\n [7, 10, 4],\n [3, 2, 0]])\n```\n\n\n```\n# Determinant of H\n\nnp.linalg.det(H)\n```\n\n\n\n\n 43.000000000000014\n\n\n\n\n```\n# Determinant of J\n\nnp.linalg.det(J)\n```\n\n\n\n\n -19.999999999999996\n\n\n\n## 3.3 Find H^{-1} and then find J^{-1}\n\n\n```\n# Inverse of H\n\nnp.linalg.inv(H)\n```\n\n\n\n\n array([[ 0.23255814, -0.25581395],\n [-0.1627907 , 0.27906977]])\n\n\n\n\n```\n# Inverse of J\n\nnp.linalg.inv(J)\n```\n\n\n\n\n array([[ 0.4 , -0.2 , 0.8 ],\n [-0.6 , 0.3 , -0.7 ],\n [ 0.8 , -0.15, 0.35]])\n\n\n\n## 3.4 Find $HH^{-1}$ and then find $G^{-1}G$. Is $HH^{-1} == G^{-1}G$? Why or Why not?\n\n\n```\n#HH^-1\n\nnp.matmul(H, np.linalg.inv(H))\n```\n\n\n\n\n array([[1.00000000e+00, 5.55111512e-16],\n [2.22044605e-16, 1.00000000e+00]])\n\n\n\n\n```\n#G^-1G\n\nnp.matmul(np.linalg.inv(G), G)\n```\n\n\n\n\n array([[1.00000000e+00, 6.66133815e-16],\n [1.11022302e-16, 1.00000000e+00]])\n\n\n\n\n```\n# The two above results are the same because multiplying any matrix by its\n# inverse will give you an indentiy matrix (i.e. 1's on main diagonal and 0's everywhere else)\n```\n\n# Stretch Goals: \n\nA reminder that these challenges are optional. If you finish your work quickly we welcome you to work on them. If there are other activities that you feel like will help your understanding of the above topics more, feel free to work on that. Topics from the Stretch Goals sections will never end up on Sprint Challenges. You don't have to do these in order, you don't have to do all of them. \n\n- Write a function that can calculate the dot product of any two vectors of equal length that are passed to it.\n- Write a function that can calculate the norm of any vector\n- Prove to yourself again that the vectors in 1.9 are orthogonal by graphing them. \n- Research how to plot a 3d graph with animations so that you can make the graph rotate (this will be easier in a local notebook than in google colab)\n- Create and plot a matrix on a 2d graph.\n- Create and plot a matrix on a 3d graph.\n- Plot two vectors that are not collinear on a 2d graph. Calculate the determinant of the 2x2 matrix that these vectors form. How does this determinant relate to the graphical interpretation of the vectors?\n\n\n\n\n```\n# Dot Product function\n\ndef dot_product(v1, v2):\n dotproduct = 0\n for i,j in zip(v1, v2):\n dotproduct += i * j\n \n return dotproduct\n```\n\n\n```\n# Using same vectors above (c and d) to calculate dot product new function\n\ndot_product(c, d)\n\n# Same result as above with numpy\n```\n\n\n\n\n 368\n\n\n\n\n```\n\n```\n", "meta": {"hexsha": "eaaee515303c15d83877cd889dd9c74877adaed4", "size": 149771, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Linear_Algebra_Assignment.ipynb", "max_stars_repo_name": "tesseract314/100-pandas-puzzles", "max_stars_repo_head_hexsha": "7a4e7c64ddfc354d2703c1c41f423c604a271857", "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": "Linear_Algebra_Assignment.ipynb", "max_issues_repo_name": "tesseract314/100-pandas-puzzles", "max_issues_repo_head_hexsha": "7a4e7c64ddfc354d2703c1c41f423c604a271857", "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": "Linear_Algebra_Assignment.ipynb", "max_forks_repo_name": "tesseract314/100-pandas-puzzles", "max_forks_repo_head_hexsha": "7a4e7c64ddfc354d2703c1c41f423c604a271857", "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": 114.50382263, "max_line_length": 48154, "alphanum_fraction": 0.829733393, "converted": true, "num_tokens": 3765, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966686936261, "lm_q2_score": 0.9099070151996071, "lm_q1q2_score": 0.8613149494089087}} {"text": "# Softening function and damage function\n\n\n```python\n%reset -f\nimport sympy as sp\nfrom sympy.plotting import plot as splot\nsp.init_printing()\n```\n\nLet us consider a softening function of the form\n\\begin{align}\nf(w) = c_1 exp( - c_2 w )\n\\end{align}\nThis is function should describe the decay of stress starting from the material tensile strength and continuously deminishing to zero.\nThe variable $w$ represents the crack opening and the parameters $c_1$ and $c_2$ are the material parameters.\n\n\n```python\nc_1, c_2, w = sp.symbols('c_1,c_2,w')\n```\n\n\n```python\nf = c_1 * sp.exp(-c_2*w)\n```\n\nLet us plot the function to verify its shape for the material parameters set to the value 1\n\n\n```python\nf_w = f.subs({'c_1':1, 'c_2':1})\n```\n\n\n```python\nsplot(f_w, (w, 0, 10))\n```\n\nThe function can be already used in this form. The question is however, how to set the material parameters $c_1$ and $c_2$. They can be directly associated to a particular type of material parameters - namely, to the tensile strength $f_\\mathrm{t}$ and fracture energy $G_\\mathrm{f}$ \n\n\n```python\nf_t, G_f = sp.symbols('f_t, G_f')\n```\n\nSoftening starts at the level of the material strength so that we can set $f(w = 0) = f_\\mathrm{t}$ to obtain the equation\n\n\n```python\nEq1 = f.subs({'w':0}) - f_t\nEq1\n```\n\nBy solving for the $c_1$ we obtain the first substitution for our softening function.\n\n\n```python\nc_1_subs = sp.solve({Eq1}, c_1)\nc_1_subs\n```\n\nThus, $c_1$ is equivalent to the tensile strength $f_\\mathrm{t}$\n\nThe second possible mechanical interpretation is provided by the statement that softening directly represents the energy dissipation of a unit crack area. Thus, for large $w \\rightarrow \\infty$ it is equivalent to the energy producing a stress-free crack. This is the meaning of fracture energy.\n\nWe can thus obtain the fracture energy represented by the softening function by evaluating its integral in the range $w \\in (0, \\infty)$. \n\n\n```python\nint_f_w = sp.integrate(f.subs(c_1_subs), w)\nint_f_w\n```\n\nAs $c_2 > 0$, only the second term matters.\nThe determinate integral\n\\begin{align}\n\\left[ - \\frac{f_\\mathrm{t}}{c_2} \n\\exp(-c_2 w) \\right]_0^{\\infty}\n\\end{align}\nis zero for $w = \\infty$, so that the value in $w = 0$ delivers the result of the integral\n\\begin{align}\n\\frac{f_\\mathrm{t}}{c_2} \n\\end{align}\n\nThis integral is equal to the fracture energy $G_\\mathrm{f}$.\n\n\n```python\nEq2 = -int_f_w.args[1][0].subs({'w':0}) - G_f\nEq2\n```\n\nand the value of $c_2$ delivers the second substitution for the softening function\n\n\n```python\nc_2_subs = sp.solve({Eq2}, c_2)\nc_2_subs\n```\n\nThe softening function with strength and fracture energy as a parameter now obtains the form\n\n\n```python\nf_w = f.subs(c_1_subs).subs(c_2_subs)\nf_w\n```\n\nVerify that the fracture energy is recovered at $w$ in infinity\n\n\n```python\nsp.integrate(f_w, w)\n```\n\n\n```python\n\n```\n\n## How to apply the softening function to a zone?\n\nIf we wish to embed the softening behavior into a finite element simulation we encounter the problem that the deformation is not described by the crack opening $w$. The finite element discretization assumes by definition a smooth stran field $verepilon$ and there is no notion of discontinuity. \n\nAs a consequence, we need to account for a length of the softening zone $L_s$ which is actually equivalent to the size of the finite element.\n\n\n```python\nL_s, epsilon = sp.symbols('L_s, varepsilon')\n```\n\nThe crack opening $w$ is simply substituted by\n\\begin{align}\n w = \\varepsilon L_\\mathrm{s}\n\\end{align}\nto obtain the softening function in terms of strains\n\n\n```python\nf_epsilon = f_w.subs({'w' : epsilon * L_s})\nf_epsilon\n```\n\nNote the important fact that the integral of the softening function over the strains scales the dissipated energy by the term $1/L_\\mathrm{s}$. \n\n\n```python\nsp.integrate(f_epsilon, epsilon)\n```\n\nAs a consequence, by changing the size of the softening zone we also change the total amount of the energy dissipated!!! This feature of the softening function will be exploited in the implementation of the finite elements.\n\n## How to convert a softening function to damage function?\n\nThe shape of the softening function describes the process of deterioration - starting from an undamaged state and ending in a fully damage state. Let us establish an equivalence between softening and damage evolution by requiring that they describe the same kind of stress decay.\n\nConsidering the softening zone of the length $L_s$ let us describe the damage within this zone using the state variable $omega$ and the elastic modulus $E_c$\n\n\n```python\nomega, E_c = sp.symbols('omega, E_c')\n```\n\nThen, the constitute law to be used in a finite element of the zone is given as\n\n\n```python\nsigma = (1 - omega) * E_c * epsilon\n```\n\nThe stress decay described by the damage law and by the softening law should be the same. Let them set equal and solve for the damage variable $omega$. Using the sympy solver we obtain the algebraic solution as\n\n\n```python\nomega_Gf = sp.solve(sigma - f_epsilon, omega)[0]\nomega_Gf\n```\n\nThis new damage function is defined using material parameters with a clear mechanical interpretation. Such kind of material law is attractive because it makes it possible to design tests that focus on an isolated phenomenon, i.e. the determination of the material strength, E modulus or fracture energy. \n\nLet us now visually verify the shape of the damage function.\nThe set of parameters is assembled in a dictionary and then\nthey are all substituted into the damage function.\n\n\n```python\ndata_f = dict(E_c = 28000, f_t = 3, L_s = 1, G_f = 0.01)\nomega_Gf_epsilon = omega_Gf.subs(data_f)\nomega_Gf_epsilon\n```\n\nThe damage function is only valid in an inelastic regime. Therefore, we have to quantify the onset of inelasticity first as\n\\begin{align}\n\\varepsilon_0 = \\frac{f_t}{E_c}\n\\end{align}\n\n\n```python\nepsilon_0 = (f_t / E_c).subs(data_f)\nepsilon_0\n```\n\nThen the damage function can be plotted as\n\n\n```python\nsplot(omega_Gf_epsilon, (epsilon,epsilon_0,epsilon_0*100))\n```\n\nThe corresponding stress strain curve has then the form\n\n\n```python\nsigma = sp.Piecewise( (E_c * epsilon, epsilon < epsilon_0),\n (( 1 - omega_Gf ) * E_c * epsilon, epsilon >= epsilon_0))\nsigma\n```\n\n\n```python\nsplot(sigma.subs(data_f), (epsilon,0,epsilon_0*100))\n```\n\nNote how the stress strain function scales with the change of the fracture energy and of the zone length.\n\nLarger fracture energy makes the stress-strain response more ductile, while smaller makes it brittle.\n\nOn the other hand, larger size of the softening zone makes the softening behavior more brittle and smaller size of the zone makes it more ductile. Why?\n\n\n```python\ng_f = sp.integrate(sigma, epsilon)\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "363076adc51c7bf43261cde2228a0c0904bd265c", "size": 12630, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "tour6_energy/9_1_Softening_law_and_damage_function.ipynb", "max_stars_repo_name": "bmcs-group/bmcs_tutorial", "max_stars_repo_head_hexsha": "4e008e72839fad8820a6b663a20d3f188610525d", "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": "tour6_energy/9_1_Softening_law_and_damage_function.ipynb", "max_issues_repo_name": "bmcs-group/bmcs_tutorial", "max_issues_repo_head_hexsha": "4e008e72839fad8820a6b663a20d3f188610525d", "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": "tour6_energy/9_1_Softening_law_and_damage_function.ipynb", "max_forks_repo_name": "bmcs-group/bmcs_tutorial", "max_forks_repo_head_hexsha": "4e008e72839fad8820a6b663a20d3f188610525d", "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": 25.4124748491, "max_line_length": 311, "alphanum_fraction": 0.5793349169, "converted": true, "num_tokens": 1789, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966709534506, "lm_q2_score": 0.9099070121457543, "lm_q1q2_score": 0.861314948574372}} {"text": "> This is one of the 100 recipes of the [IPython Cookbook](http://ipython-books.github.io/), the definitive guide to high-performance scientific computing and data science in Python.\n\n\n# 15.7. Analyzing a nonlinear differential system: Lotka-Volterra (predator-prey) equations\n\nHere, we conduct a brief analytical study of a famous nonlinear differential system: the Lotka-Volterra equations, also known as predator-prey equations. This simple model describes the evolution of two interacting populations (e.g. sharks and sardines), where the predators eat the preys. This example illustrates how we can use SymPy to obtain exact expressions and results for fixed points and their stability.\n\n\n```python\nfrom sympy import *\ninit_printing()\n```\n\n\n```python\nvar('x y')\nvar('a b c d', positive=True)\n```\n\nThe variables x and y represent the populations of the preys and predators, respectively. The parameters a, b, c and d are positive parameters (described more precisely in \"How it works...\"). The equations are:\n\n$$\\begin{align}\n\\frac{dx}{dt} &= f(x) = x(a-by)\\\\\n\\frac{dy}{dt} &= g(x) = -y(c-dx)\n\\end{align}$$\n\n\n```python\nf = x * (a - b*y)\ng = -y * (c - d*x)\n```\n\nLet's find the fixed points of the system (solving f(x,y) = g(x,y) = 0).\n\n\n```python\nsolve([f, g], (x, y))\n```\n\n\n```python\n(x0, y0), (x1, y1) = _\n```\n\nLet's write the 2D vector with the two equations.\n\n\n```python\nM = Matrix((f, g)); M\n```\n\nNow we can compute the Jacobian of the system, as a function of (x, y).\n\n\n```python\nJ = M.jacobian((x, y)); J\n```\n\nLet's study the stability of the two fixed points by looking at the eigenvalues of the Jacobian at these points.\n\n\n```python\nM0 = J.subs(x, x0).subs(y, y0); M0\n```\n\n\n```python\nM0.eigenvals()\n```\n\nThe parameters a and c are strictly positive, so the eigenvalues are real and of opposite signs, and this fixed point is a saddle point. Since this point is unstable, the extinction of both populations is unlikely in this model.\n\n\n```python\nM1 = J.subs(x, x1).subs(y, y1); M1\n```\n\n\n```python\nM1.eigenvals()\n```\n\nThe eigenvalues are purely imaginary so this fixed point is not hyperbolic, and we cannot draw conclusions about the qualitative behavior of the system around this fixed point from this linear analysis. However, one can show with other methods that oscillations occur around this point.\n\n> You'll find all the explanations, figures, references, and much more in the book (to be released later this summer).\n\n> [IPython Cookbook](http://ipython-books.github.io/), by [Cyrille Rossant](http://cyrille.rossant.net), Packt Publishing, 2014 (500 pages).\n", "meta": {"hexsha": "2884760996397ac75b2dbdde1330ca12cd8ff725", "size": 5494, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/chapter15_symbolic/07_lotka.ipynb", "max_stars_repo_name": "hidenori-t/cookbook-code", "max_stars_repo_head_hexsha": "750f546ed87b09d28532884b8074b96cd8d32a38", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 820, "max_stars_repo_stars_event_min_datetime": "2015-01-01T18:15:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-06T16:15:07.000Z", "max_issues_repo_path": "notebooks/chapter15_symbolic/07_lotka.ipynb", "max_issues_repo_name": "bndxn/cookbook-code", "max_issues_repo_head_hexsha": "90c31341edccf039187e6a3809fb336f83bb758f", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 31, "max_issues_repo_issues_event_min_datetime": "2015-02-25T22:08:09.000Z", "max_issues_repo_issues_event_max_datetime": "2018-09-28T08:41:38.000Z", "max_forks_repo_path": "notebooks/chapter15_symbolic/07_lotka.ipynb", "max_forks_repo_name": "bndxn/cookbook-code", "max_forks_repo_head_hexsha": "90c31341edccf039187e6a3809fb336f83bb758f", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 483, "max_forks_repo_forks_event_min_datetime": "2015-01-02T13:53:11.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T21:05:16.000Z", "avg_line_length": 23.4786324786, "max_line_length": 419, "alphanum_fraction": 0.5649799782, "converted": true, "num_tokens": 691, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465116437761, "lm_q2_score": 0.9207896802383029, "lm_q1q2_score": 0.8612574153684847}} {"text": "```python\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport sympy as sy\nimport simtk.unit as unit\n```\n\n# The Lennard-Jones potential\n\nThe Lennard-Jones (LJ) potential between two particles is defined by the following equation, where $x$ is the distance between the particles, and $\\sigma$ and $\\epsilon$ are two parameters of the potential:\n \n\\begin{equation}\nV(x) = 4 \\epsilon \\left[ \\left( \\frac{\\sigma}{x} \\right)^{12} - \\left( \\frac{\\sigma}{x} \\right)^6 \\right]\n\\end{equation}\n\nLets see the shape of this function:\n\n\n```python\ndef LJ (x, sigma, epsilon):\n \n t = sigma/x\n t6 = t**6\n t12 = t6**2\n \n return 4.0*epsilon*(t12-t6)\n```\n\n\n```python\nsigma = 2.0 * unit.angstrom\nepsilon = 1.0 * unit.kilocalories_per_mole\n\nxlim_figure = [0.01, 6.0]\nylim_figure = [-2.0, 10.0]\n\nx = np.linspace(xlim_figure[0], xlim_figure[1], 100, True) * unit.angstrom\nplt.plot(x, LJ(x, sigma, epsilon))\nplt.xlim(xlim_figure)\nplt.ylim(ylim_figure)\nplt.xlabel('x [{}]'.format(x.unit.get_symbol()))\nplt.ylabel('V [{}]'.format(epsilon.unit.get_symbol()))\nplt.show()\n```\n\nThe way the LJ potential is built, the $\\sigma$ and $\\epsilon$ parameters have a straightforward interpretation. The cut with $y=0$ is located in $x=\\sigma$:\n\n\n```python\nsigma = 2.0 * unit.angstrom\nepsilon = 1.0 * unit.kilocalories_per_mole\n\nxlim_figure = [0.01, 6.0]\nylim_figure = [-2.0, 10.0]\n\nx = np.linspace(xlim_figure[0], xlim_figure[1], 100, True) * unit.angstrom\nplt.plot(x, LJ(x, sigma, epsilon))\nplt.hlines(0, xlim_figure[0], xlim_figure[1], linestyles='dotted', color='gray')\nplt.vlines(sigma._value, ylim_figure[0], ylim_figure[1], linestyles='dashed', color='red')\nplt.text(sigma._value+0.02*xlim_figure[1], 0.7*ylim_figure[1], '$\\sigma$', fontsize=14)\nplt.xlim(xlim_figure)\nplt.ylim(ylim_figure)\nplt.xlabel('x [{}]'.format(x.unit.get_symbol()))\nplt.ylabel('V [{}]'.format(epsilon.unit.get_symbol()))\nplt.show()\n```\n\nAnd $\\epsilon$ is the depth of the minimum measured from $y=0$:\n\n\n```python\nsigma = 2.0 * unit.angstrom\nepsilon = 1.0 * unit.kilocalories_per_mole\n\nxlim_figure = [0.01, 6.0]\nylim_figure = [-2.0, 10.0]\n\nx = np.linspace(xlim_figure[0], xlim_figure[1], 100, True) * unit.angstrom\nplt.plot(x, LJ(x, sigma, epsilon))\nplt.hlines(0, xlim_figure[0], xlim_figure[1], linestyles='dotted', color='gray')\nplt.hlines(-epsilon._value, xlim_figure[0], xlim_figure[1], linestyles='dashed', color='red')\nplt.annotate(text='', xy=(1.0,0.0), xytext=(1.0,-epsilon._value), arrowprops=dict(arrowstyle='<->'))\nplt.text(1.0+0.02*xlim_figure[1], -0.7*epsilon._value, '$\\epsilon$', fontsize=14)\nplt.xlim(xlim_figure)\nplt.ylim(ylim_figure)\nplt.xlabel('x [{}]'.format(x.unit.get_symbol()))\nplt.ylabel('V [{}]'.format(epsilon.unit.get_symbol()))\nplt.show()\n```\n\nNotice that the LJ potential has physical meaning when $\\epsilon>0$ and $\\sigma>0$ only. Actually, the potential vanishes whether $\\epsilon=0$ or $\\sigma=0$.\n\n## The Lennard Jones minimum and the size of the particles\n\nThe LJ potential has a single minimum located in $x_{min}$. Lets equal to $0$ the first derivative of the potential to find the value of $x_{min}$:\n\n\n```python\nx, sigma, epsilon = sy.symbols('x sigma epsilon', real=True, positive=True)\nV = 4.0*epsilon*((sigma/x)**12-(sigma/x)**6)\ngradV = sy.diff(V,x)\nroots=sy.solve(gradV, x)\nx_min = roots[0]\n```\n\n\n```python\nx_min\n```\n\n\n\n\n$\\displaystyle 1.12246204830937 \\sigma$\n\n\n\nThe minimum is then located in:\n\n\\begin{equation}\nx_{min} = 2^{1/6} \\sigma\n\\end{equation}\n\nwhere the potential takes the value:\n\n\\begin{equation}\nV(x_{min}) = -\\epsilon\n\\end{equation}\n\n\n```python\nsigma = 2.0 * unit.angstrom\nepsilon = 1.0 * unit.kilocalories_per_mole\n\nx_min = 2**(1/6)*sigma\ny_min = -epsilon\n\nxlim_figure = [x_min._value-0.4, x_min._value+0.4]\nylim_figure = [y_min._value-0.1, y_min._value+0.5]\n\nx = np.linspace(xlim_figure[0], xlim_figure[1], 100, True) * unit.angstroms\nplt.plot(x, LJ(x, sigma, epsilon))\nplt.hlines(y_min._value, xlim_figure[0], xlim_figure[1], linestyles='dashed', color='gray')\nplt.vlines(x_min._value, ylim_figure[0], ylim_figure[1], linestyles='dashed', color='gray')\nplt.xlim(xlim_figure)\nplt.ylim(ylim_figure)\nplt.xlabel('x [{}]'.format(x.unit.get_symbol()))\nplt.ylabel('V [{}]'.format(epsilon.unit.get_symbol()))\nplt.show()\n```\n\nThis way two particles in the equilibrium position will be placed at a $2^{1/6} \\sigma$ distance. The potential is thereby modeling two \"soft spheres\" atracting each other very lightly. Their radii, given that both particles are equal, are equal to $r$:\n\n\\begin{equation}\nr = \\frac{1}{2} x_{min} = 2^{-5/6} \\sigma\n\\end{equation}\n\nAnd we say these spheres are \"soft\" because their volume is not limited by a hard-wall potential, they can penetrate each other suffering a not infinite repulsive force.\n\n## Time period of the small harmonic oscillations around the minimum\n\nIf we want to perform a molecular simulation of this two particles we should wonder how big the integrator timestep must be. To answer this question we can study the harmonic approximation around the minimum. Lets calculate the time period, $\\tau$, of a small harmonic oscillation around the minimum:\n\n\n```python\nx, sigma, epsilon = sy.symbols('x sigma epsilon', real=True, positive=True)\nV = 4.0*epsilon*((sigma/x)**12-(sigma/x)**6)\ngradV = sy.diff(V,x)\ngrad2V = sy.diff(V,x,x)\n\nx_min = sy.solve(gradV,x)[0]\nk_harm = grad2V.subs(x, x_min)\n```\n\n\n```python\nk_harm\n```\n\n\n\n\n$\\displaystyle \\frac{57.1464378708551 \\epsilon}{\\sigma^{2}}$\n\n\n\nThe harmonic constant of the second degree Taylor polynomial of the LJ potential at $x=x_{min}$ is then:\n\n\\begin{equation}\nk_{harm} = 36·2^{2/3} \\frac{\\epsilon}{\\sigma^2}\n\\end{equation}\n\nThe oscillation period of a particle with $m$ mass in an harmonic potential defined by $\\frac{1}{2} k x²$ is:\n\n\\begin{equation}\n\\tau = 2 \\pi \\sqrt{ \\frac{m}{k}}\n\\end{equation}\n\nAs such, the period of the small harmonic oscillations around the LJ minimum of particle with $m$ mass is:\n\n\\begin{equation}\n\\tau = 2 \\pi \\sqrt{ \\frac{m}{k_{harm}}} = \\frac{\\pi}{3·2^{1/3}} \\sqrt{\\frac{m\\sigma^2}{\\epsilon}}\n\\end{equation}\n\nWith the mass and parameters taking values of amus, angstroms and kilocalories per mole, the time period is in the order of:\n\n\n```python\nmass = 50.0 * unit.amu\nsigma = 2.0 * unit.angstrom\nepsilon = 1.0 * unit.kilocalories_per_mole\n\nk = 36 * 2**(2/3) * epsilon/sigma**2\n\ntau = 2*np.pi * np.sqrt(mass/k)\n\nprint(tau)\n```\n\n 0.5746513694274475 ps\n\n\nBut, is this characteristic time a good threshold for a LJ potential? If the oscillations around the minimum are not small enough, the harmonic potential of the second degree term of the taylor expansion is easily overcome by the sharp left branch of the LJ potential:\n\n\n```python\nsigma = 2.0 * unit.angstrom\nepsilon = 1.0 * unit.kilocalories_per_mole\n\nk = 36 * 2**(2/3) * epsilon/sigma**2\n\nx_min = 2**(1/6)*sigma\ny_min = -epsilon\n\nxlim_figure = [x_min._value-0.2, x_min._value+0.2]\nylim_figure = [y_min._value-0.1, y_min._value+0.6]\n\nx = np.linspace(xlim_figure[0], xlim_figure[1], 100, True) * unit.angstroms\nplt.plot(x, LJ(x, sigma, epsilon))\nplt.plot(x, 0.5*k*(x-x_min)**2+y_min)\nplt.hlines(y_min._value, xlim_figure[0], xlim_figure[1], linestyles='dashed', color='gray')\nplt.vlines(x_min._value, ylim_figure[0], ylim_figure[1], linestyles='dashed', color='gray')\nplt.xlim(xlim_figure)\nplt.ylim(ylim_figure)\nplt.xlabel('x [{}]'.format(x.unit.get_symbol()))\nplt.ylabel('V [{}]'.format(epsilon.unit.get_symbol()))\nplt.show()\n```\n\nLet's imagine the following situation. Let a particle be in the harmonic potential at temperature of 300K. Will the particle be more constrained in space than in the well of the LJ potential? Will the particle feel the harmonic potential softer or sharper than the LJ? Lets make some numbers to evaluate if the oscillation time period of the harmonic approximation can be a good time threshold for the integration timestep of a molecular dynamics of the LJ potential.\n\nThe standard deviation of an harmonic oscillation with the shape $\\frac{1}{2}k x^2$ in contact with a stochastic thermal bath can be computed as:\n\n\\begin{equation}\n\\beta = \\frac{1}{k_{\\rm B} T} \n\\end{equation}\n\n\\begin{equation}\nZ_x = \\int_{-\\infty}^{\\infty} {\\rm e}^{- \\beta \\frac{1}{2}k x^2} = \\sqrt{\\frac{2 \\pi}{\\beta k}}\n\\end{equation}\n\n\\begin{equation}\n\\left< x \\right> = \\frac{1}{Z_x} \\int_{-\\infty}^{\\infty} x {\\rm e}^{-\\beta \\frac{1}{2}k x^2} = 0\n\\end{equation}\n\n\\begin{equation}\n\\left< x^2 \\right> = \\frac{1}{Z_x} \\int_{-\\infty}^{\\infty} x^{2} {\\rm e}^{-\\beta \\frac{1}{2}k x^2} = \\frac{1}{Z_x} \\sqrt{\\frac{2 \\pi}{\\beta³ k^3}} = \\frac{1}{\\beta k}\n\\end{equation}\n\n\n\\begin{equation}\n{\\rm std} = \\left( \\left< x^2 \\right> -\\left< x \\right>^2 \\right)^{1/2} = \\sqrt{ \\frac{k_{\\rm B}T}{k} }\n\\end{equation}\n\n\nThis way, in the case of the harmonic potential obtained as the second degree term of the Taylor expansion around the LJ minimum:\n\n\n```python\nmass = 50.0 * unit.amu\nsigma = 2.0 * unit.angstrom\nepsilon = 1.0 * unit.kilocalories_per_mole\ntemperature = 300 * unit.kelvin\nkB = unit.BOLTZMANN_CONSTANT_kB * unit.AVOGADRO_CONSTANT_NA\n\nk = 36 * 2**(2/3) * epsilon/sigma**2\nstd = np.sqrt(kB*temperature/k)\n\nx_min = 2**(1/6)*sigma\ny_min = -epsilon\n\nxlim_figure = [x_min._value-0.4, x_min._value+0.4]\nylim_figure = [y_min._value-0.1, y_min._value+0.6]\n\nx = np.linspace(xlim_figure[0], xlim_figure[1], 100, True) * unit.angstroms\nplt.plot(x, LJ(x, sigma, epsilon))\nplt.plot(x, 0.5*k*(x-x_min)**2+y_min)\nplt.hlines(y_min._value, xlim_figure[0], xlim_figure[1], linestyles='dashed', color='gray')\nplt.vlines(x_min._value, ylim_figure[0], ylim_figure[1], linestyles='dashed', color='gray')\nplt.axvspan(x_min._value - std._value, x_min._value + std._value, alpha=0.2, color='red')\nplt.annotate(text='', xy=(x_min._value, y_min._value - 0.5*(y_min._value-ylim_figure[0])),\n xytext=(x_min._value-std._value, y_min._value - 0.5*(y_min._value-ylim_figure[0])),\n arrowprops=dict(arrowstyle='<->'))\nplt.text(x_min._value-0.6*std._value, y_min._value - 0.4*(y_min._value-ylim_figure[0]), '$std$', fontsize=14)\nplt.xlim(xlim_figure)\nplt.ylim(ylim_figure)\nplt.xlabel('x [{}]'.format(x.unit.get_symbol()))\nplt.ylabel('V [{}]'.format(epsilon.unit.get_symbol()))\nplt.show()\n```\n\nThe harmonic potential is too soft as approximation. Its oscillation time used as threshold to choose the integration timestep can yield to numeric problems. Let's try with a stiffer potential, let's double the harmonic constant:\n\n\n```python\nmass = 50.0 * unit.amu\nsigma = 2.0 * unit.angstrom\nepsilon = 1.0 * unit.kilocalories_per_mole\ntemperature = 300 * unit.kelvin\nkB = unit.BOLTZMANN_CONSTANT_kB * unit.AVOGADRO_CONSTANT_NA\n\nk = 36 * 2**(2/3) * epsilon/sigma**2\nstd = np.sqrt(kB*temperature/k)\n\nx_min = 2**(1/6)*sigma\ny_min = -epsilon\n\nxlim_figure = [x_min._value-0.4, x_min._value+0.4]\nylim_figure = [y_min._value-0.1, y_min._value+0.6]\n\nx = np.linspace(xlim_figure[0], xlim_figure[1], 100, True) * unit.angstroms\nplt.plot(x, LJ(x, sigma, epsilon))\nplt.plot(x, 0.5*k*(x-x_min)**2+y_min)\nplt.plot(x, k*(x-x_min)**2+y_min, label='2k_{harm}')\nplt.hlines(y_min._value, xlim_figure[0], xlim_figure[1], linestyles='dashed', color='gray')\nplt.vlines(x_min._value, ylim_figure[0], ylim_figure[1], linestyles='dashed', color='gray')\nplt.axvspan(x_min._value - std._value, x_min._value + std._value, alpha=0.2, color='red')\nplt.annotate(text='', xy=(x_min._value, y_min._value - 0.5*(y_min._value-ylim_figure[0])),\n xytext=(x_min._value-std._value, y_min._value - 0.5*(y_min._value-ylim_figure[0])),\n arrowprops=dict(arrowstyle='<->'))\nplt.text(x_min._value-0.6*std._value, y_min._value - 0.4*(y_min._value-ylim_figure[0]), '$std$', fontsize=14)\nplt.xlim(xlim_figure)\nplt.ylim(ylim_figure)\nplt.xlabel('x [{}]'.format(x.unit.get_symbol()))\nplt.ylabel('V [{}]'.format(epsilon.unit.get_symbol()))\nplt.show()\n```\n\nLets take then, as reference, an harmonic potential with constant equal to $2k_{harm}$ could be a better idea. Lets compute then the new time threshold to choose the integration timestep:\n\n\\begin{equation}\n\\tau' = 2 \\pi \\sqrt{ \\frac{m}{2k_{harm}}} = \\frac{\\pi}{3·2^{5/6}} \\sqrt{\\frac{m\\sigma^2}{\\epsilon}} = \\frac{1}{\\sqrt{2}} \\tau\n\\end{equation}\n\n\n```python\nmass = 50.0 * unit.amu\nsigma = 2.0 * unit.angstrom\nepsilon = 1.0 * unit.kilocalories_per_mole\n\nk = 36 * 2**(2/3) * epsilon/sigma**2\n\ntau = 2*np.pi * np.sqrt(mass/(2*k))\n\nprint(tau)\n```\n\n 0.4063398801402841 ps\n\n\nIt is an accepted rule of thumb that the integration timestep must be as large as $\\tau / 10$, being $\\tau$ the oscillation time period of the fastest possible vibration mode. So finally, in this case the integration time step should not be longer than:\n\n\n```python\nmass = 50.0 * unit.amu\nsigma = 2.0 * unit.angstrom\nepsilon = 1.0 * unit.kilocalories_per_mole\n\nk = 36 * 2**(2/3) * epsilon/sigma**2\n\ntau = 2*np.pi * np.sqrt(mass/(2*k))\n\nprint(tau/10.0)\n```\n\n 0.04063398801402841 ps\n\n", "meta": {"hexsha": "021be51a7b5b21c6e6d92f1cf4e46e8a72a3825a", "size": 145290, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "docs/contents/lennard_jones_fluid/LJ_Potential.ipynb", "max_stars_repo_name": "dprada/OpenMolecularSystems", "max_stars_repo_head_hexsha": "5787fc159f87091ec498cf23abd07c1c2aec6138", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-07-02T14:42:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-02T14:42:08.000Z", "max_issues_repo_path": "docs/contents/lennard_jones_fluid/LJ_Potential.ipynb", "max_issues_repo_name": "dprada/OpenMolecularSystems", "max_issues_repo_head_hexsha": "5787fc159f87091ec498cf23abd07c1c2aec6138", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-07-25T02:28:07.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-25T02:28:07.000Z", "max_forks_repo_path": "docs/contents/lennard_jones_fluid/LJ_Potential.ipynb", "max_forks_repo_name": "dprada/OpenMolecularSystems", "max_forks_repo_head_hexsha": "5787fc159f87091ec498cf23abd07c1c2aec6138", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-06-17T18:56:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-17T18:56:55.000Z", "avg_line_length": 206.3778409091, "max_line_length": 29540, "alphanum_fraction": 0.9076536582, "converted": true, "num_tokens": 4151, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465098415279, "lm_q2_score": 0.9207896704568164, "lm_q1q2_score": 0.8612574045599138}} {"text": "#### Distribución Uniforme\n\n##### Distribución Uniforme Discreta\n\nDecimos que una variable aleatoria X tiene una distribución uniforme discreta sobre el conjunto de n números {x1, x2, ..., xn} si **la probabilidad de que X tome cualquiera de estos valores es constante 1/n**. \n\nEsta distribución surge en espacios de probabilidad **equiprobables**, esto es, en situaciones en donde tenemos n resultados diferentes y todos ellos tienen la misma probabilidad de ocurrir.\n\nSe escribe \n\n$X \\sim \\text{unif}\\{x_1, x_2, ..., x_n\\} $\n\nen donde el símbolo \"$\\sim$\" se lee \"se distribuye como\" o \"tiene una distribución\".\n\nLa distribución de probabilidad de esa variable aleatoria es:\n\n\\begin{equation}\n f(x)=\\begin{cases}\n 1/n, & \\text{si x = $x_1, x_2, ..., x_n$}\\\\\n 0, & \\text{en otro caso}.\n \\end{cases}\n\\end{equation}\n\n\n\n\n\n\\begin{equation}\nn = 5 \\text{ donde } n = b − a + 1\n\\end{equation}\n\n**Ejemplos**:\n\n* X: puntuación en el lanzamiento de un dado regular\n\n* X: resultado del lanzamiento de una moneda\n\n* X: resultado de un juego de lotería\n\n\n#### Distribución Uniforme Continua\n\nDecimos que una variable aleatoria X tiene una distribución uniforme continua en el intervalo (a,b), donde a y b son números reales, si su función de densidad es \n\n\\begin{equation}\n f_X(x)=\\begin{cases}\n \\frac{1}{b-a}, & \\text{si $a \\lt x \\lt b$} \\\\\n 0, & \\text{en otro caso}.\n \\end{cases}\n\\end{equation}\n\na y b son los parámetros de la distribución uniforme continua.\n\nLa distribución uniforme asigna probabilidad positiva constante y mayor a cero sólo a valores de la variable aleatoria en determinado rango.\n\n\\begin{equation}\n F_X(x)=\\begin{cases}\n 0, & \\text{si $x \\lt a$} \\\\\n \\frac{x - a}{b - a}, & \\text{si $a \\le x \\lt b$} \\\\\n 1, & \\text{si $x \\ge b$}\n \\end{cases}\n\\end{equation}\n\n\n\n\n**Ejemplos**:\n\n* Una llamada telefónica llegó a in conmutador en un tiempo, al azar, dentro de un período de 1 minuto. El conmutador estuvo ocupado durante 15 segundos en ese minuto. ¿Cuál es la probabilidad de que la llamada haya llegado mientras el conmutador no estuvo ocupado?\n\n* Dos amigos deben encontrarse en una parada de colectivo entre las 9:00 y las 10:00. Cada uno esperará un máximo de 10 minutos. ¿Cuál es la probabilidad de que no se encuentren si el amigo1 llegará a las 9:30?\n\n---\n\nVamos a ver ahora cómo generar datos con estas distibuciones de probabilidad.\n\nNecesitamos un generador de números aleatorios, que expone métodos para generar números aleatorios con alguna distribución de probabilidad especificada. Construimos este generador de este modo `np.random.default_rng()`\n\nhttps://docs.scipy.org/doc/numpy/reference/random/generator.html\n\nEstas son las distribuciones de probabilidad disponibles:\nhttps://docs.scipy.org/doc/numpy/reference/random/generator.html#distributions\n\nPara generar datos con distribución **uniforme discreta** emplearemos el método `choice`\n\nhttps://docs.scipy.org/doc/numpy/reference/random/generated/numpy.random.Generator.choice.html\n\nPara generar datos con distribución **uniforme continua** emplearemos el método `uniform`\n\nhttps://docs.scipy.org/doc/numpy/reference/random/generated/numpy.random.Generator.uniform.html#numpy.random.Generator.uniform\n\n\n\n```python\nimport numpy as np\nrandom_generator = np.random.default_rng()\nrandom_uniform_cont_data = random_generator.uniform(low = 3, high = 17, size = 30)\n\npossible_values = [3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]\nrandom_uniform_disc_data = random_generator.choice(possible_values, size = 30)\n```\n\nUsando la función `distribution_plotter` vamos a graficar los valores generados\n\n\n```python\nimport seaborn as sns\ndef distribution_plotter(data, label, bins=None): \n sns.set(rc={\"figure.figsize\": (10, 7)})\n sns.set_style(\"white\") \n dist = sns.distplot(data, bins= bins, hist_kws={'alpha':0.2}, kde_kws={'linewidth':5})\n dist.set_title('Distribucion de ' + label + '\\n', fontsize=16)\n```\n\n\n```python\nprint(random_uniform_cont_data)\ndistribution_plotter(random_uniform_cont_data, \"uniforme continua\")\n```\n\n\n```python\nprint(random_uniform_disc_data)\n\ndistribution_plotter(random_uniform_disc_data, \"uniforme discreta\", bins=possible_values)\n```\n\n
\n
\n
\n
\n\n
\n
\n
\n
\n\n\n\n\n```python\n# modificar este valor:\nsize_sample = 30\n\nrandom_uniform_cont_data = random_generator.uniform(low = 3, high = 17, size = size_sample)\n\npossible_values = [3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]\nrandom_uniform_disc_data = random_generator.choice(possible_values, size = size_sample)\n\ndistribution_plotter(random_uniform_disc_data, \"uniforme discreta\")\ndistribution_plotter(random_uniform_cont_data, \"uniforme continua\")\n```\n\n#### Referencias\n\nGráficos: https://en.wikipedia.org/wiki/List_of_probability_distributions\n", "meta": {"hexsha": "935eb645439d38c9638fe542b2636a47ad09063e", "size": 8342, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Code/3-numpy/probabilidad/4.1_uniforme.ipynb", "max_stars_repo_name": "Flor91/Data-Science", "max_stars_repo_head_hexsha": "f67ec537341e8b2d8213a56ef8ee63028e46e1b2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-10-06T12:59:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-08T10:58:14.000Z", "max_issues_repo_path": "Code/3-numpy/probabilidad/4.1_uniforme.ipynb", "max_issues_repo_name": "Flor91/Data-Science", "max_issues_repo_head_hexsha": "f67ec537341e8b2d8213a56ef8ee63028e46e1b2", "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": "Code/3-numpy/probabilidad/4.1_uniforme.ipynb", "max_forks_repo_name": "Flor91/Data-Science", "max_forks_repo_head_hexsha": "f67ec537341e8b2d8213a56ef8ee63028e46e1b2", "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.0489795918, "max_line_length": 274, "alphanum_fraction": 0.58726924, "converted": true, "num_tokens": 1490, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896737173119, "lm_q2_score": 0.9353465062370313, "lm_q1q2_score": 0.8612574042906237}} {"text": "\n\n# Some Linear Algebra Basics\n## Python Imports\nAt the beginning of our Python source code we can import packages to extend the functionality of Python. \n\nIn this case we will be importing the NumPy library which supports *efficient* linear algebra calculations.\n\n\n```\n# Import the NumPy library for linear algebra\n\n# we assign 'np' as an alias that we can use later when calling or using\n# anything in the NumPy package\nimport numpy as np\n```\n\n## Summing a vector\nThe following cells will create a vector $$x = \\begin{bmatrix}3&1&4&2\\end{bmatrix}$$ and then calculate the sum of its elements, $$s = \\sum_{i=1}^n x_i$$\n\n\n```\n# Create a vector, x\n\n# np.array is used to define vectors or matrices in NumPy. Here we will \n# initialize our arrays with python lists.\nx = np.array([3, 1, 4, 2])\n\n# Display x (using an f-string)\nprint(f\"x =\\n{x}\")\n```\n\n x =\n [3 1 4 2]\n\n\n\n```\n# Calculate the sum the elements of x\ns = x.sum()\n\n# Display the sum\nprint(f\"Sum of elements of x = {s}\")\n```\n\n Sum of elements of x = 10\n\n\n## Vector Dot-Product\nIn the next few cells we will create a new vector $y = \\begin{bmatrix}1\\\\2\\\\3\\\\4\\end{bmatrix}$.\n\nThen we'll calculate the dot product of $x$ and $y$, $$d = xy = x \\cdot y = \\begin{bmatrix}3&1&4&2\\end{bmatrix} \\cdot \\begin{bmatrix}1\\\\2\\\\3\\\\4\\end{bmatrix}$$\n\n*Please note: While linear algebra rules for the dot-product demand that number of columns in the first argument equal the number of rows in the second argument, NumPy will automatically transpose one of the vectors if two row vectors or two column vectors are passed. So, in NumPy, $\\begin{bmatrix}3&1&4&2\\end{bmatrix} \\cdot \\begin{bmatrix}1&2&3&4\\end{bmatrix}$ or $\\begin{bmatrix}3\\\\1\\\\4\\\\2\\end{bmatrix} \\cdot \\begin{bmatrix}1\\\\2\\\\3\\\\4\\end{bmatrix}$ will produce the same dot-product as shown above.*\n\n\n\n```\n# Create a column vector y\ny = np.array([[1],\n [2],\n [3],\n [4]])\n\n# Display our vectors\nprint(f\"x =\\n{x}\\n\\ny =\\n{y}\")\n```\n\n x =\n [3 1 4 2]\n \n y =\n [[1]\n [2]\n [3]\n [4]]\n\n\n\n```\n# Calculate the dot product of x and y\nd = x @ y\n\n# Display the dot product\nprint(f\"d = x . y = {d}\")\n```\n\n d = x . y = [25]\n\n\n## Matrix Dot-Product\nIn the remaining cells we create two matrices $X = \\begin{bmatrix}3&1\\\\4&2\\end{bmatrix}$ and $Y = \\begin{bmatrix}1&2\\\\3&4\\end{bmatrix}$.\n\nThen we'll calculate the dot product of $X$ and $Y$,$$D = XY = X\\cdot Y = \\begin{bmatrix}3&1\\\\4&2\\end{bmatrix} \\cdot \\begin{bmatrix}1&2\\\\3&4\\end{bmatrix}$$\n\n\n```\n# Create two matrices\nX = np.array([[3, 1], \n [4, 2]]) # This definition is easier to read\n\nY = np.array([[1, 2], [3, 4]]) # This definition is more compact\n\n# Display our matrices\nprint(f\"X =\\n{X}\\n\\nY =\\n{Y}\")\n```\n\n X =\n [[3 1]\n [4 2]]\n \n Y =\n [[1 2]\n [3 4]]\n\n\n\n```\n# Calculate the dot product of X and Y\nD = X @ Y\n\n# Display the dot product\nprint(f\"D = X . Y =\\n{D}\")\n```\n\n D = X . Y =\n [[ 6 10]\n [10 16]]\n\n\n## Exercises\n\n### Exercise 1\n\nCalculate and display $$\\begin{bmatrix}3&1&4\\end{bmatrix} \\cdot \\begin{bmatrix}1\\\\2\\\\3\\end{bmatrix}$$\n\n\n```\n# Create the first vector\n\n# Create the second vector\n\n# Calculate the dot-product\n\n# Display the dot-product\n\n```\n\n### Exercise 2\n\nCalculate and display $$\\begin{bmatrix}5&3\\\\1&2\\end{bmatrix} \\cdot \\begin{bmatrix}7&4\\\\6&8\\end{bmatrix}$$\n\n\n```\n# Create the first matrix\n\n# Create the second matrix\n\n# Calculate the dot-product\n\n# Display the dot-product\n\n```\n\n### Exercise 3\n\nCalculate and display $$\\begin{align}x &= \\begin{bmatrix}3&1&4\\end{bmatrix}\\\\z &= \\sum_{i=1}^n x_i\\end{align}$$\n\n\n```\n# Create the vector\n# x = ...\n\n# Calculate the sum\n# s = ...\n\n# Display the dot-product\n# print(f\"... = {...}\")\n```\n", "meta": {"hexsha": "594347bce6c1281caddc2a57b8b61be7bb1e5a04", "size": 10834, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/extras/Linear_Algebra_Basics.ipynb", "max_stars_repo_name": "paulc00/ML-Intro", "max_stars_repo_head_hexsha": "ac901ec5947f29da7e94fc5badc94391235e2609", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-10-17T01:16:47.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-17T01:16:47.000Z", "max_issues_repo_path": "notebooks/extras/Linear_Algebra_Basics.ipynb", "max_issues_repo_name": "paulc00/ML-Intro", "max_issues_repo_head_hexsha": "ac901ec5947f29da7e94fc5badc94391235e2609", "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/extras/Linear_Algebra_Basics.ipynb", "max_forks_repo_name": "paulc00/ML-Intro", "max_forks_repo_head_hexsha": "ac901ec5947f29da7e94fc5badc94391235e2609", "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": 27.4278481013, "max_line_length": 536, "alphanum_fraction": 0.4325272291, "converted": true, "num_tokens": 1261, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.942506716354847, "lm_q2_score": 0.9136765240013699, "lm_q1q2_score": 0.8611462604470417}} {"text": "```python\nimport numpy as np\n%matplotlib inline\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport sympy as sym\nfrom sympy.plotting import plot\nimport pandas as pd\nfrom IPython.display import display\nfrom IPython.core.display import Math\n```\n\n\n```python\n# EXERCISE 1.Find the extrema in the function f(x)=x^3-7.5x^2+18x-10 \n# analytically and determine if they are minimum or maximum.\n\na = sym.symbols('a')\nV = a**3 - 7.5*a**2 + 18*a - 10\nVdiff = sym.expand(sym.diff(V))\nroots = sym.solve(Vdiff)\ndisplay(Math(sym.latex('Roots:') + sym.latex(roots)))\nroots = np.asarray(roots)\n```\n\n\n$$Roots:\\left [ 2.0, \\quad 3.0\\right ]$$\n\n\n\n```python\ndef f(x):\n return x**3 - 7.5*x**2 + 18*x - 10\n\nx = sym.symbols('x') # x como simbolo para realizar a derivada\n\nfdiff = sym.diff(f(x),x) #derivada\n\nfdiff2 = sym.diff(fdiff, x)\n\nfor i in range(len(roots)):\n\n while fdiff2.evalf(subs ={x: roots[i]}) == 0: # fdiff.evalf(subs ={x: 0}) colocar 0 no lugar do simbolo x // caso a derivada der 0\n fdiff2 = sym.diff(fdiff2,x)\n\n print(fdiff2.evalf(subs ={x: roots[i]})) # mostrar o valor da derivada se =/= 0\n \n if fdiff2.evalf(subs ={x: roots[i]}) <= 0: # determinar maxima ou minima\n print('maxima')\n else:\n print('minima')\n```\n\n -3.00000000000000\n maxima\n 3.00000000000000\n minima\n\n\n\n```python\n# EXERCISE 2. Find the minimum in the f(x)=x^3-7.5x^2+18x-10 \n# using the gradient descent algorithm.\n\ncur_x = 6\ngamma = 0.01\nprecision = 0.00001\nstep_size = 1\nmax_iters = 10000\niters = 0\n\nf = lambda x: x**3 - 7.5*x**2 + 18*x - 10\ndf = lambda x: 3*x**2 - 15*x + 18\n\nwhile (step_size > precision) & (iters < max_iters):\n prev_x = cur_x\n cur_x -= gamma*df(prev_x)\n step_size - abs(cur_x - prev_x)\n iters+=1\n \nprint('True local minimum at {} with function value {}.'.format(9/4, f(9/4)))\nprint('Local minimum by gradient descent at {} with function value {}.'.format(cur_x, f(cur_x)))\n```\n\n True local minimum at 2.25 with function value 3.921875.\n Local minimum by gradient descent at 3.000000000000008 with function value 3.5.\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "4372adc7aae10c4a1824abdf43f48c80dd76d2f5", "size": 4003, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "courses/modsim2018/matheuspiquini/Optmization - 1.ipynb", "max_stars_repo_name": "MatheusKP/bmc", "max_stars_repo_head_hexsha": "5c9c426eeb49b2b686d2da9e5ac092e695428345", "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": "courses/modsim2018/matheuspiquini/Optmization - 1.ipynb", "max_issues_repo_name": "MatheusKP/bmc", "max_issues_repo_head_hexsha": "5c9c426eeb49b2b686d2da9e5ac092e695428345", "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": "courses/modsim2018/matheuspiquini/Optmization - 1.ipynb", "max_forks_repo_name": "MatheusKP/bmc", "max_forks_repo_head_hexsha": "5c9c426eeb49b2b686d2da9e5ac092e695428345", "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": 25.1761006289, "max_line_length": 143, "alphanum_fraction": 0.5103672246, "converted": true, "num_tokens": 715, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133515091156, "lm_q2_score": 0.9161096124442243, "lm_q1q2_score": 0.8610636561821678}} {"text": "# Finding Pattern\n\n\n```python\nimport numpy as np\n```\n\n## Given this array, find the next number in the sequence\n\n\n```python\nmy_teaser_array = np.array([1, 7, 19, 37, 61, 91, 127, 169, 217, 271, 331])\nmy_teaser_array\n```\n\n\n\n\n array([ 1, 7, 19, 37, 61, 91, 127, 169, 217, 271, 331])\n\n\n\n##### for information about numpy.diff, please see: http://docs.scipy.org/doc/numpy/reference/generated/numpy.diff.html\n\n\n```python\nnp.diff(my_teaser_array)\n```\n\n\n\n\n array([ 6, 12, 18, 24, 30, 36, 42, 48, 54, 60])\n\n\n\n\n```python\nnp.diff(my_teaser_array, n=2)\n```\n\n\n\n\n array([6, 6, 6, 6, 6, 6, 6, 6, 6])\n\n\n\n\n```python\nnp.diff(my_teaser_array, n=3)\n```\n\n\n\n\n array([0, 0, 0, 0, 0, 0, 0, 0])\n\n\n\n##### Warning: imports should (usually) appear at top of notebook\n\nIf SymPy is not included on your computer; open a console and type 'conda sympy'\n\n\n```python\nfrom sympy import init_session\ninit_session() \n```\n\n IPython console for SymPy 1.0 (Python 3.5.2-64-bit) (ground types: python)\n \n These commands were executed:\n >>> from __future__ import division\n >>> from sympy import *\n >>> x, y, z, t = symbols('x y z t')\n >>> k, m, n = symbols('k m n', integer=True)\n >>> f, g, h = symbols('f g h', cls=Function)\n >>> init_printing()\n \n Documentation can be found at http://docs.sympy.org/1.0/\n\n\n\n```python\ndiff(x**3)\n```\n\n\n```python\ndiff(x**3, x, 2)\n```\n\n\n```python\ndiff(x**3, x, 3)\n```\n\n\n```python\ndiff(x**3, x, 4)\n```\n\n\n```python\ndef my_guess(n):\n return (n+1)**3 - n**3\n```\n\n\n```python\nmy_guess(np.arange(20))\n```\n\n\n\n\n array([ 1, 7, 19, 37, 61, 91, 127, 169, 217, 271, 331,\n 397, 469, 547, 631, 721, 817, 919, 1027, 1141], dtype=int32)\n\n\n\n\n```python\nmy_teaser_array = np.array([1, 7, 19, 37, 61, 91, 127, 169, 217, 271, 331])\nmy_teaser_array\n```\n\n\n\n\n array([ 1, 7, 19, 37, 61, 91, 127, 169, 217, 271, 331])\n\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "4905bb8680eb01f9b80d911efeb4cd4c40dc72ef", "size": 8838, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "numpy-data-science-essential-training/Ex_Files_NumPy_Data_EssT/Exercise Files/Ch 6/06_04/Finish/Pattern.ipynb", "max_stars_repo_name": "saint1729/in-learning", "max_stars_repo_head_hexsha": "fe58495846f05e2dcd15d1dbb6ff87535d35d6c5", "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": "numpy-data-science-essential-training/Ex_Files_NumPy_Data_EssT/Exercise Files/Ch 6/06_04/Finish/Pattern.ipynb", "max_issues_repo_name": "saint1729/in-learning", "max_issues_repo_head_hexsha": "fe58495846f05e2dcd15d1dbb6ff87535d35d6c5", "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": "numpy-data-science-essential-training/Ex_Files_NumPy_Data_EssT/Exercise Files/Ch 6/06_04/Finish/Pattern.ipynb", "max_forks_repo_name": "saint1729/in-learning", "max_forks_repo_head_hexsha": "fe58495846f05e2dcd15d1dbb6ff87535d35d6c5", "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.6183844011, "max_line_length": 754, "alphanum_fraction": 0.5806743607, "converted": true, "num_tokens": 735, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.950410972802222, "lm_q2_score": 0.9059898197488448, "lm_q1q2_score": 0.8610626659364093}} {"text": "```python\nfrom sympy import *\ninit_printing(use_unicode=True)\nfrom IPython.display import display\n```\n\n# Task 1\n\n\n```python\n#v0, v1= Symbol('v_0'), Symbol('v_1')\n\nv0 = Matrix([[0.5], [0.5], [0.5], [0.5]])\nv1 = Matrix([[0.5], [0.5], [-0.5], [-0.5]])\n\nv0.dot(v1)\n```\n\n#### Answer: 0\n\n# Task 2. \nIf $\\{\\mathbf{v}^{(0)},\\ \\mathbf{v}^{(1)},\\ \\mathbf{v}^{(2)},\\ \\mathbf{v}^{(3)}\\}$ is a full **orthonormal** basis, the following system of equations must be satisfied:\n\n$$\\begin{cases}\n\\langle \\mathbf{v}^{(0)}, \\mathbf{v}^{(3)}\\rangle = 0 \\\\ \n\\langle \\mathbf{v}^{(1)}, \\mathbf{v}^{(3)}\\rangle = 0 \\\\ \n\\langle \\mathbf{v}^{(2)}, \\mathbf{v}^{(3)}\\rangle = 0 \\\\ \n\\langle \\mathbf{v}^{(3)}, \\mathbf{v}^{(3)}\\rangle = 1 \n\\end{cases}$$\n\nLet $\\mathbf{v}^{(3)} = \\begin{pmatrix} a & b & c & d \\end{pmatrix}$.\n\n\n```python\nv2 = Matrix([[0.5], [-0.5], [0.5], [-0.5]])\na, b, c, d = symbols('a b c d')\nv3 = Matrix([[a], [b], [c], [d]])\nanswer = solve([v0.dot(v3), v1.dot(v3), v2.dot(v3), v3.dot(v3)-1], (a, b, c, d))\nanswer\n```\n\n#### Answer: 2\n\n# Task 3.\n\nLet expansion coefficients vector $\\mathbf x = \\begin{pmatrix} a & b & c & d \\end{pmatrix}$.\n\n\n```python\nv3 = Matrix(next(iter(answer)))\ny = Matrix([2.5, 0.5, 1.5, -0.5])\nx = (a, b, c, d)\n\nbasis_matrix = v0.row_join(v1).row_join(v2).row_join(v3)\nlinsolve((basis_matrix, y), x)\n```\n\n#### Answer: 2.0 1.0 2.0 0.0\n\n# Task 4.\nWe just need to solve 4 sytems of linear equations in this task\n\n\n```python\nsolve([y.dot(x), v1.dot(x), v2.dot(x), v3.dot(x)], (a, b, c, d))\n```\n\n\n```python\nsolve([y.dot(x), v0.dot(x), v1.dot(x), v2.dot(x)], (a, b, c, d))\n```\n\n\n```python\nsolve([y.dot(x), v0.dot(x), v2.dot(x), v3.dot(x)], (a, b, c, d))\n```\n\n\n```python\nsolve([y.dot(x), v1.dot(x), v2.dot(x), (v3-2*v1).dot(x)], (a, b, c, d))\n```\n\n#### Answer: cells 1, 3 and 4 must be selected\n\n# Task 5.\nSolution is very simple.\n\nNew $\\mathbf{x'}=\\begin{bmatrix} x_0-x_2 \\\\ x_1-x_0 \\\\ x_2-x_1 \\end{bmatrix} = \\begin{bmatrix} 1 \\cdot x_0 + 0 \\cdot x_1 -1 \\cdot x_2 \\\\ -1 \\cdot x_0 + 1 \\cdot x_1 + 0 \\cdot x_2 \\\\ 0 \\cdot x_0 -1 \\cdot x_1 + 1 \\cdot x_2 \\end{bmatrix} $. Now we can determine the matrix $\\mathbf{F}=\\begin{bmatrix} 1 && 0 && -1 \\\\ -1 && 1 && 0 \\\\ 0 && -1 && 1 \\end{bmatrix}$.\n\n#### Answer: 1 0 -1 -1 1 0 0 -1 1\n\n# Task 6.\nIn the task 5 the matrix $\\mathbf{D}$ was defined, that matrix represents delay by 1 (right shift). In this task the matrix $\\mathbf{A}$ is a delay matrix again.\n\nThus $\\mathbf{A}^4=\\begin{bmatrix} 1 && 0 && 0 && 0 \\\\ 0 && 1 && 0 && 0 \\\\ 0 && 0 && 1 && 0 \\\\ 0 && 0 && 0 && 1 \\end{bmatrix}$.\n\n\n```python\nA = Matrix([[0, 0, 0, 1], [1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0]])\nA**4\n```\n\n#### Answer: 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1\n", "meta": {"hexsha": "af3653bf7a175bb3b5fc6e038c3242a7d4f111b1", "size": 18027, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "hw2.ipynb", "max_stars_repo_name": "hshi24/coursera-dsp-hw", "max_stars_repo_head_hexsha": "b7302b5f2457691e25d28025223ec042c192c371", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-02-06T08:30:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-06T08:30:21.000Z", "max_issues_repo_path": "hw2.ipynb", "max_issues_repo_name": "hshi24/coursera-dsp-hw", "max_issues_repo_head_hexsha": "b7302b5f2457691e25d28025223ec042c192c371", "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": "hw2.ipynb", "max_forks_repo_name": "hshi24/coursera-dsp-hw", "max_forks_repo_head_hexsha": "b7302b5f2457691e25d28025223ec042c192c371", "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": 48.3297587131, "max_line_length": 1604, "alphanum_fraction": 0.709713208, "converted": true, "num_tokens": 1185, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947086083139, "lm_q2_score": 0.9111797075998823, "lm_q1q2_score": 0.8610600022731595}} {"text": "# Ricci Tensor and Scalar Curvature calculations using Symbolic module\n\n\n```python\nimport sympy\nfrom sympy import cos, sin, sinh\nfrom einsteinpy.symbolic import MetricTensor, RicciTensor, RicciScalar\n\nsympy.init_printing()\n```\n\n### Defining the Anti-de Sitter spacetime Metric\n\n\n```python\nsyms = sympy.symbols(\"t chi theta phi\")\nt, ch, th, ph = syms\nm = sympy.diag(-1, cos(t) ** 2, cos(t) ** 2 * sinh(ch) ** 2, cos(t) ** 2 * sinh(ch) ** 2 * sin(th) ** 2).tolist()\nmetric = MetricTensor(m, syms)\n```\n\n### Calculating the Ricci Tensor(with both indices covariant)\n\n\n```python\nRic = RicciTensor.from_metric(metric)\nRic.tensor()\n```\n\n\n\n\n$$\\left[\\begin{matrix}3 & 0 & 0 & 0\\\\0 & - 3 \\cos^{2}{\\left (t \\right )} & 0 & 0\\\\0 & 0 & \\left(\\sin^{2}{\\left (t \\right )} - 1\\right) \\sinh^{2}{\\left (\\chi \\right )} - 2 \\cos^{2}{\\left (t \\right )} \\sinh^{2}{\\left (\\chi \\right )} & 0\\\\0 & 0 & 0 & \\left(\\sin^{2}{\\left (t \\right )} - 1\\right) \\sin^{2}{\\left (\\theta \\right )} \\sinh^{2}{\\left (\\chi \\right )} - 2 \\sin^{2}{\\left (\\theta \\right )} \\cos^{2}{\\left (t \\right )} \\sinh^{2}{\\left (\\chi \\right )}\\end{matrix}\\right]$$\n\n\n\n### Calculating the Ricci Scalar(Scalar Curvature) from the Ricci Tensor\n\n\n```python\nR = RicciScalar.from_riccitensor(Ric)\nR.expr\n```\n\nThe curavture is -12 which is in-line with the theoretical results\n", "meta": {"hexsha": "d30950eaf425c3f1c820906af9136adee034c0ff", "size": 5141, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "docs/source/examples/Ricci Tensor and Scalar Curvature symbolic calculation.ipynb", "max_stars_repo_name": "r0cketr1kky/einsteinpy", "max_stars_repo_head_hexsha": "d86f412736a42e2cf688a1e21d7b553868a14bc4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-03-08T16:13:56.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-08T16:13:56.000Z", "max_issues_repo_path": "docs/source/examples/Ricci Tensor and Scalar Curvature symbolic calculation.ipynb", "max_issues_repo_name": "r0cketr1kky/einsteinpy", "max_issues_repo_head_hexsha": "d86f412736a42e2cf688a1e21d7b553868a14bc4", "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/source/examples/Ricci Tensor and Scalar Curvature symbolic calculation.ipynb", "max_forks_repo_name": "r0cketr1kky/einsteinpy", "max_forks_repo_head_hexsha": "d86f412736a42e2cf688a1e21d7b553868a14bc4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-03-19T18:46:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-19T18:46:13.000Z", "avg_line_length": 33.1677419355, "max_line_length": 540, "alphanum_fraction": 0.4189846333, "converted": true, "num_tokens": 472, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.959154281754899, "lm_q2_score": 0.8976953010025941, "lm_q1q2_score": 0.8610282916678911}} {"text": "# Poisson Distribution - Errors in Text\n\n> This document is written in *R*.\n>\n> ***GitHub***: https://github.com/czs108\n\n## Background\n\n> In a certain long document there is an *average* of **0.5** typographical errors per **100** words of text.\n\n## Question A\n\n> What is the *mean* number of words between errors?\n\n\\begin{equation}\nMean = \\frac{1}{0.5} \\times 100 = 200\n\\end{equation}\n\n## Question B\n\n> What is the probability of finding **4** errors in a text of length **500** words?\n\n\\begin{equation}\n\\lambda = 0.5 \\times \\frac{500}{100} = 2.5\n\\end{equation}\n\n\\begin{equation}\n\\begin{split}\nP(X = 4) &= \\frac{e^{-\\lambda} \\cdot {\\lambda}^{4}}{4!} \\\\\n &= \\frac{e^{-2.5} \\cdot {2.5}^{4}}{4!}\n\\end{split}\n\\end{equation}\n\nUse the `dpois` function.\n\n\n```R\ndpois(x=4, lambda=2.5)\n```\n\n## Question C\n\n> What is the probability of there being *at least* **300** words before the *1st* error?\n\n\\begin{equation}\n\\lambda = 0.5 \\times \\frac{300}{100} = 1.5\n\\end{equation}\n\n\\begin{equation}\n\\begin{split}\nP(X = 0) &= \\frac{e^{-\\lambda} \\cdot {\\lambda}^{0}}{0!} \\\\\n &= e^{-1.5}\n\\end{split}\n\\end{equation}\n\n\n```R\ndpois(x=0, lambda=1.5)\n```\n\n\n0.22313016014843\n\n\nUse the `exp` function.\n\n\n```R\nexp(-1.5)\n```\n\n\n0.22313016014843\n\n\n## Question D\n\n> What is the *minimum* number of words in which the probability of finding an error is *at least* **90%**?\n\nWe know that\n\n\\begin{equation}\nP(X = 1) \\geq 0.9\n\\end{equation}\n\nSo\n\n\\begin{equation}\nP(X = 0) < 0.1\n\\end{equation}\n\nAssume $n$ is the number of words.\n\n\\begin{equation}\n\\lambda = 0.5 \\times \\frac{n}{100}\n\\end{equation}\n\n\\begin{equation}\n\\begin{split}\nP(X = 0) &= \\frac{e^{-\\lambda} \\cdot {\\lambda}^{0}}{0!} \\\\\n &= e^{-\\lambda} \\\\\n &< 0.1\n\\end{split}\n\\end{equation}\n\nThen we get\n\n\\begin{equation}\n\\ln 0.1 = -2.3\n\\end{equation}\n\n\n```R\nlog(0.1)\n```\n\n\n-2.30258509299405\n\n\nWhen $-\\lambda < -2.3$, $P(X = 0) < 0.1$.\n\nSo $\\lambda > 2.3$\n\n\\begin{equation}\nn = 200 \\times \\lambda > 460\n\\end{equation}\n\n## Question E\n\n> How many words would there be on a page, if the probability of **0** errors on a page was **20%**?\n\nAssume $n$ is the number of words on a page.\n\n\\begin{equation}\n\\lambda = 0.5 \\times \\frac{n}{100}\n\\end{equation}\n\n\\begin{equation}\n\\begin{split}\nP(X = 0) &= \\frac{e^{-\\lambda} \\cdot {\\lambda}^{0}}{0!} \\\\\n &= e^{-\\lambda} \\\\\n &= 0.2\n\\end{split}\n\\end{equation}\n\nThen we get\n\n\\begin{align}\n\\ln 0.2 = -\\lambda \\\\\n\\lambda = 1.609\n\\end{align}\n\n\n```R\n-log(0.2)\n```\n\n\n1.6094379124341\n\n\n\\begin{equation}\nn = 200 \\times \\lambda = 322\n\\end{equation}\n\n## Question F\n\n> What is the probability of there being *at least* **2000** words before there are **10** errors?\n\n\\begin{equation}\n\\lambda = 0.5 \\times \\frac{2000}{100} = 10\n\\end{equation}\n\n\\begin{equation}\n\\begin{split}\nP(X \\leq 9) &= \\sum_{i=0}^{9} P(X = i) \\\\\n &= \\sum_{i=0}^{9} \\frac{e^{-10} \\cdot {10}^{i}}{i!}\n\\end{split}\n\\end{equation}\n\n\n```R\nsum(dpois(x=c(0:9), lambda=10))\n```\n\n\n0.457929714471852\n\n\nOr use the `ppois` function.\n\n\n```R\nppois(q=9, lambda=10)\n```\n\n\n0.457929714471852\n\n", "meta": {"hexsha": "8deb79b77b9213abedcf4e063f673efa1e34e132", "size": 8572, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "exercises/Poisson Distribution - Errors in Text.ipynb", "max_stars_repo_name": "czs108/Probability-Theory-Exercises", "max_stars_repo_head_hexsha": "60c6546db1e7f075b311d1e59b0afc3a13d93229", "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/Poisson Distribution - Errors in Text.ipynb", "max_issues_repo_name": "czs108/Probability-Theory-Exercises", "max_issues_repo_head_hexsha": "60c6546db1e7f075b311d1e59b0afc3a13d93229", "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/Poisson Distribution - Errors in Text.ipynb", "max_forks_repo_name": "czs108/Probability-Theory-Exercises", "max_forks_repo_head_hexsha": "60c6546db1e7f075b311d1e59b0afc3a13d93229", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-03-21T05:04:07.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-21T05:04:07.000Z", "avg_line_length": 19.4818181818, "max_line_length": 115, "alphanum_fraction": 0.4366542231, "converted": true, "num_tokens": 1157, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404077216355, "lm_q2_score": 0.9263037221561135, "lm_q1q2_score": 0.8609441091948467}} {"text": "## Classical Mechanics - Week 7\n \n \n### Last Week:\n- Simulated planetary motion\n- Saw the limitations of Euler's Method\n- Gained experience with the Velocity Verlet Method\n\n### This Week:\n- Introduce the SymPy package\n- Visualize Potential Energy surfaces\n- Explore packages in Python\n\n# Why use packages, libraries, and functions in coding?\nAnother great question! \n\n**Simply put:** We could hard code every little algorithm into our program and retype them every time we need them, OR we could call upon the functions from packages and libraries to do these tedious calculations and reduce the possibility of error.\n\nWe have done this with numpy.linalg.norm() to calculate the magnitude of vectors.\n\nWe will be introducing a new package call SymPy, a very useful [symbolic mathematics](https://en.wikipedia.org/wiki/Computer_algebra) library.\n\n\n```python\n# Let's import packages, as usual\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport sympy as sym\nsym.init_printing(use_unicode=True)\n```\n\nLet's analyze a simple projectile motion again, but this time using SymPy. \n\nAssume we have the following equation to express our trajectory in the $x-y$ coordinates:\n\n$y = y_0 - (\\beta -x)^2$, where $y_0$ and $\\beta$ are constants.\n\n\n```python\n# First we must declare and define our variables. Examine the syntax in this cell then run it. Notice that ordering matters\nx, y0, beta = sym.symbols('x, y_0, beta')\n```\n\n\n```python\n# Next we will define our function\ny = y0 - (beta - x)**2\ny # This line outputs a visualization of our equation y(x) below\n```\n\n\n```python\n# Now we will set our constants, but leave x alone so we can plot as a function of x\ny1 = sym.simplify(y.subs({y0:10, beta:1}))\ny1 # This line outputs a visualization of our equation y1(x) below\n```\n\n\n```python\n# Run this cell. What happens as you play around with the constants?\nsym.plot(y1,(x,0,5), title='Height vs Distance',xlabel='x',ylabel='y')\n```\n\n## Q1.) How would you compare plotting with sympy versus what we have done so far? Which method do you prefer?\n\n✅ Double click this cell, erase its content, and put your answer to the above question here.\n\n#### Using what we just learned, please set up the following equation using sympy where $U(\\vec{r})$ is our potential energy:\n\n$U(\\vec{r}) = -e^{-(x^2+y^2)}$\n\n\n```python\n = sym.symbols() ## Set up our variables here. What should be on the left-hand and right-hand side?\nU = -sym.exp() ## What should go in the exp? Notice that using SymPy we need to use the SymPy function for exp\nU\n```\n\n### We have two ways in which we can graph this:\n\nEither perform the substitution $r^2 = x^2+y^2$ in order to plot in a 2D space ($U(r)$) or we could plot in a 3D space keeping $x$ and $y$ in our equation (U(x,y)). \n\n## Q2.) What do you think are the benefits/draw-backs of these two methods of analyzing our equation? Which do you prefer?\n\n✅ Double click this cell, erase its content, and put your answer to the above question here.\n\n#### Now let's graph the potential\nFor now we will use sympy to perform both a 2D and 3D plot. Let's do the 2D version first using what we just learned.\n\n\n```python\nr = sym.symbols('r') # Creating our variables\nU2D = -sym.exp() # Finish the equation using our replacement for x^2 + y^2\nsym.plot(U2D,title='Potential vs Distance',xlabel='Distance (r)',ylabel='Potential (U)')\n```\n\n## Q3.) What can you learn from this 2D graph?\n\n✅ Double click this cell, erase its content, and put your answer to the above question here.\n\nThe cell below imports a function from the sympy package that allows us to graph in 3D. Using the \"plot3d\" call, make a 3D plot of our originally initalized equation. \n\nFor the 3D plot, try setting the x and y plot limits as close as you can to the origin while having a clear picture of what is happening at the origin. For example x and y could range from (-4,4)\n\n\n```python\n# The below import will allow us to plot in 3D with sympy\n# Define \"U\" as your potential\nfrom sympy.plotting import plot3d\n```\n\n\n```python\n# Once you have your potential function set up, execute this cell to obtain a graph\n# Play around with the x and y scale to get a better view of the potential curve\nplot3d(U,(x,-10,10),(y,-10,10))\n```\n\n## Q4.) What can you learn from this 3D graph? (Feel free to make the graph's x and y-range smaller to observe the differences)\n\n✅ Double click this cell, erase its content, and put your answer to the above question here.\n\n##### Let's get some more in-depth coding experience:\nTry to graph this last potential energy function using SymPy or with Numpy (there is a 3d plotting example back in Week 2's notebook).\n\n$U(r) = 3.2\\cdot e^{-(0.5x^2+0.25y^2)}$\n\n\n```python\n## Set up and graph the potential here\n\n\n```\n\n## Q5.) How would you describe the new potential?\n\n✅ Double click this cell, erase its content, and put your answer to the above question here.\n\n### Try this: \nCenter the new potential at (1,1) instead of (0,0). (That is, move the peak of the graph from (0,0) to (1,1).)\n\n\n```python\n## Plot the adjustment here\n```\n\n## Q6.) How did you move the peak of the graph?\n\n✅ Double click this cell, erase its content, and put your answer to the above question here.\n\n# Notebook Wrap-up. \nRun the cell below and copy-paste your answers into their corresponding cells.\n\n\n```python\nfrom IPython.display import HTML\nHTML(\n\"\"\"\n\n\"\"\"\n)\n```\n\n# Congratulations! Another week, another Notebook.\n\nAs we can see, there are many tools we can use to model and analyze different problems in Physics on top of Numerical methods. Libraries and packages are such tools that have been developed by scientists to work on different topics, each package specific to a different application. But this is just food for thought. Although we use some basic package functions, we won't be using advanced scientific packages to do simulations and calculations in this class.\n\n\n```python\n\n```\n", "meta": {"hexsha": "3cbcf15e13755154ea45e27796040309ef74f489", "size": 10370, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "doc/AdminBackground/PHY321/CM_Jupyter_Notebooks/Student_Work/CM_Notebook7.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/AdminBackground/PHY321/CM_Jupyter_Notebooks/Student_Work/CM_Notebook7.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/AdminBackground/PHY321/CM_Jupyter_Notebooks/Student_Work/CM_Notebook7.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": 28.2561307902, "max_line_length": 466, "alphanum_fraction": 0.5824493732, "converted": true, "num_tokens": 1509, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582612793113, "lm_q2_score": 0.925229954514902, "lm_q1q2_score": 0.860887854761472}} {"text": "# Métricas para avaliação de modelos\n\nA escolha da métrica a ser otimizada depende da aplicação!\n\n#### Métricas para regressão\n\nMSE (mean squared error)\n\n$\n\\begin{align}\n\\frac{1}{n} \\sum_{i=1}^{n}(y_i - \\hat{y}_i)^2\n\\end{align}\n$\n\nMAE (mean absolute error)\n\n$\n\\begin{align}\n\\frac{1}{n} \\sum_{i=1}^{n}(y_i - \\hat{y}_i)\n\\end{align}\n$\n\n#### Métricas para classificação\n\nSejam:\n\n$\n\\begin{align}\nTP = true \\ positives \\\\\nTN = true \\ negatives \\\\\nFP = false \\ positives \\ (erro \\ tipo \\ I)\\\\\nFN = false \\ negatives \\ (erro \\ tipo \\ II)\n\\end{align}\n$\n\nPrecisão\n\n$\n\\begin{align}\n\\frac{TP}{TP+FP}\n\\end{align}\n$\n\nRecall / sensibilidade\n\n$\n\\begin{align}\n\\frac{TP}{TP+FN}\n\\end{align}\n$\n\nAcurácia\n\n$\n\\begin{align}\n\\frac{TP+TN}{TP+TN+FP+FN}\n\\end{align}\n$\n\n\nF1 score: média harmônica de precisão e recall\n\n$\n\\begin{align}\n2 \\cdot \\frac{precision \\cdot recall}{precision + recall}\n\\end{align}\n$\n\n## Validação cruzada\n\nConsiste em particionar o dataset em k subconjuntos e treinar o modelo k vezes, usando um subconjunto diferente para validação por vez e os k-1 restantes para treino.\n\nVamos usar uma função auxiliar que recebe uma instância de um modelo, a quantidade de partições $k$, a matriz de *features* $X$, o vetor de *targets* $y$ e uma função que computa a métrica desejada.\n\nExperimente variar $k$ e a função de métrica nos exemplos abaixo: classificação de flores e regressão de valores de casas.\n\n\n```python\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nfrom sklearn.datasets import load_boston, load_iris\nfrom sklearn.linear_model import LinearRegression, LogisticRegression\nfrom sklearn.metrics import accuracy_score, recall_score, f1_score, mean_absolute_error, mean_squared_error\nfrom sklearn.model_selection import KFold\n\n\ndef train_model(model, k, X, y, score_func):\n kfolds = KFold(k)\n scores = []\n for train_idx, test_idx in kfolds.split(X, y):\n X_train, y_train = X[train_idx], y[train_idx]\n X_test, y_test = X[test_idx], y[test_idx]\n model = model.fit(X_train, y_train)\n y_hat = model.predict(X_test)\n scores.append(score_func(y_test, y_hat))\n print('scores: ', np.round(scores,4), '\\nmean: ', np.round(np.mean(scores),4))\n```\n\n#### Classificação de flores\n\nDataset Iris.\n\n\n```python\ndata_iris = load_iris()\ndf_iris = pd.DataFrame(data_iris.data, columns=data_iris.feature_names)\n\nX_iris = df_iris.values\ny_iris = data_iris.target\ncols_iris = data_iris.feature_names\n\ndf_iris.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
sepal length (cm)sepal width (cm)petal length (cm)petal width (cm)
05.13.51.40.2
14.93.01.40.2
24.73.21.30.2
34.63.11.50.2
45.03.61.40.2
\n
\n\n\n\nPodemos visualizar as *features* duas a duas, como no *snippet* abaixo. Experimente variar as *features* (i.e. `X_iris[:,0]` e `X_iris[:,1]`). Não se esqueça de também trocar as labels do gráfico.\n\n\n```python\nplt.scatter(X_iris[:,0], X_iris[:,1], c=y_iris, alpha=0.7)\nplt.xlabel(cols_iris[0])\nplt.ylabel(cols_iris[1])\n```\n\n\n```python\nlr_iris = LogisticRegression(solver='lbfgs', max_iter=200, multi_class='multinomial')\ntrain_model(lr_iris, 5, X_iris, y_iris, accuracy_score)\n```\n\n scores: [1. 1. 0.8667 0.9333 0.8333] \n mean: 0.9267\n\n\n#### Regressão de valores de casas\n\nDataset *Boston Housing*.\n\n\n```python\ndata_boston = load_boston()\ndf_boston = pd.DataFrame(data_boston.data, columns=data_boston.feature_names)\n\nX_boston = df_boston.values\ny_boston = data_boston.target\ncols_boston = data_boston.feature_names\n\ndf_boston.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
CRIMZNINDUSCHASNOXRMAGEDISRADTAXPTRATIOBLSTAT
00.0063218.02.310.00.5386.57565.24.09001.0296.015.3396.904.98
10.027310.07.070.00.4696.42178.94.96712.0242.017.8396.909.14
20.027290.07.070.00.4697.18561.14.96712.0242.017.8392.834.03
30.032370.02.180.00.4586.99845.86.06223.0222.018.7394.632.94
40.069050.02.180.00.4587.14754.26.06223.0222.018.7396.905.33
\n
\n\n\n\n\n```python\nplt.scatter(X_boston[:,0], X_boston[:,1], alpha=0.7)\nplt.xlabel(cols_boston[0])\nplt.ylabel(cols_boston[1])\n```\n\n\n```python\nlr_boston = LinearRegression()\ntrain_model(lr_boston, 10, X_boston, y_boston, mean_absolute_error)\n```\n\n scores: [2.2069 2.8968 2.7867 4.5985 4.1099 3.5647 2.6697 9.6564 5.0227 2.5373] \n mean: 4.0049\n\n", "meta": {"hexsha": "ec73f550860d9e506eefd5ec4883d5764455dada", "size": 58376, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "aulas/aula05_01_metricas.ipynb", "max_stars_repo_name": "flaviobp/introducao-aprendizado-maquina", "max_stars_repo_head_hexsha": "87c2f57352a03dd39e2507a6f6ff33f5dd280aa9", "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": "aulas/aula05_01_metricas.ipynb", "max_issues_repo_name": "flaviobp/introducao-aprendizado-maquina", "max_issues_repo_head_hexsha": "87c2f57352a03dd39e2507a6f6ff33f5dd280aa9", "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": "aulas/aula05_01_metricas.ipynb", "max_forks_repo_name": "flaviobp/introducao-aprendizado-maquina", "max_forks_repo_head_hexsha": "87c2f57352a03dd39e2507a6f6ff33f5dd280aa9", "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": 109.9359698682, "max_line_length": 34416, "alphanum_fraction": 0.8285596821, "converted": true, "num_tokens": 2553, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475715065793, "lm_q2_score": 0.9124361551194692, "lm_q1q2_score": 0.8607444310867518}} {"text": "# First Order Initial Value Problem\n \n\nThe more general form of a first order Ordinary Differential Equation is: \n\\begin{equation}\n\\label{general ODE}\ny^{'}=f(t,y).\n\\end{equation}\nThis can be solved analytically by integrating both sides but this is not straight forward for most problems.\nNumerical methods can be used to approximate the solution at discrete points.\n\n\n## Euler method\n\nThe simplest one step numerical method is the Euler Method named after the most prolific of mathematicians [Leonhard Euler](https://en.wikipedia.org/wiki/Leonhard_Euler) (15 April 1707 – 18 September 1783) .\n\nThe general Euler formula to the first order equation\n$$ y^{'} = f(t,y) $$\napproximates the derivative at time point $t_i$\n$$y^{'}(t_i) \\approx \\frac{w_{i+1}-w_i}{t_{i+1}-t_{i}} $$\nwhere $w_i$ is the approximate solution of $y$ at time $t_i$.\nThis substitution changes the differential equation into a __difference__ equation of the form \n$$ \n\\frac{w_{i+1}-w_i}{t_{i+1}-t_{i}}=f(t_i,w_i) $$\nAssuming uniform stepsize $t_{i+1}-t_{i}$ is replaced by $h$, re-arranging the equation gives\n$$ w_{i+1}=w_i+hf(t_i,w_i),$$\n This can be read as the future $w_{i+1}$ can be approximated by the present $w_i$ and the addition of the input to the system $f(t,y)$ times the time step.\n\n\n\n```python\n## Library\nimport numpy as np\nimport math \n\n%matplotlib inline\nimport matplotlib.pyplot as plt # side-stepping mpl backend\nimport matplotlib.gridspec as gridspec # subplots\nimport warnings\n\nwarnings.filterwarnings(\"ignore\")\n\n```\n\n## Population growth\n\nThe general form of the population growth differential equation is: \n$$ y^{'}=\\epsilon y $$\nwhere $\\epsilon$ is the growth rate. The initial population at time $a$ is \n$$ y(a)=A $$\n$$ a\\leq t \\leq b. $$\nIntegrating gives the general analytic (exact) solution: \n$$ y=Ae^{\\epsilon x}. $$\nWe will use this equation to illustrate the application of the Euler method.\n \n## Discrete Interval\nThe continuous time $a\\leq t \\leq b $ is discretised into $N$ points seperated by a constant stepsize\n$$ h=\\frac{b-a}{N}.$$\nHere the interval is $0\\leq t \\leq 2$ \n$$ h=\\frac{2-0}{20}=0.1.$$\nThis gives the 21 discrete points:\n$$ t_0=0, \\ t_1=0.1, \\ ... t_{20}=2. $$\nThis is generalised to \n$$ t_i=0+i0.1, \\ \\ \\ i=0,1,...,20.$$\nThe plot below shows the discrete time steps.\n\n\n```python\n### Setting up time\nt_end=2.0\nt_start=0\nN=20\nh=(t_end-t_start)/(N)\ntime=np.arange(t_start,t_end+0.01,h)\nfig = plt.figure(figsize=(10,4))\nplt.plot(time,0*time,'o:',color='red')\nplt.xlim((0,2))\nplt.title('Illustration of discrete time points for h=%s'%(h))\n```\n\n## Initial Condition\nTo get a specify solution to a first order initial value problem, an __initial condition__ is required.\n\nFor our population problem the intial condition is:\n$$y(0)=10$$.\nThis gives the analytic solution\n$$y=10e^{\\epsilon t}$$.\n### Growth rate \nLet the growth rate $$\\epsilon=0.5$$ giving the analytic solution.\n$$y=10e^{0.5 t}$$.\nThe plot below shows the exact solution on the discrete time steps.\n\n\n```python\n## Analytic Solution y\ny=10*np.exp(0.5*time)\n\nfig = plt.figure(figsize=(10,4))\nplt.plot(time,y,'o:',color='black')\nplt.xlim((0,2))\nplt.xlabel('time')\nplt.ylabel('y')\nplt.title('Analytic (Exact) solution')\n```\n\n## Numerical approximation of Population growth\nThe differential equation is transformed using the Euler method into a difference equation of the form\n $$ w_{i+1}=w_{i}+h \\epsilon w_i. $$\nThis approximates a series of of values $w_0, \\ w_1, \\ ..., w_{N}$.\nFor the specific example of the population equation the difference equation is\n $$ w_{i+1}=w_{i}+h 0.5 w_i. $$\nwhere $w_0=10$. From this initial condition the series is approximated.\nThe plot below shows the exact solution $y$ in black circles and Euler approximation $w$ in blue squares. \n\n\n```python\nw=np.zeros(N+1)\nw[0]=10\nfor i in range (0,N):\n w[i+1]=w[i]+h*(0.5)*w[i]\n\nfig = plt.figure(figsize=(10,4))\nplt.plot(time,y,'o:',color='black',label='exact')\nplt.plot(time,w,'s:',color='blue',label='Euler')\nplt.xlim((0,2))\nplt.xlabel('time')\nplt.legend(loc='best')\nplt.title('Analytic and Euler solution')\n```\n\n## Error\nWith a numerical solution there are two types of error: \n* local truncation error at one time step; \n* global error which is the propagation of local error. \n\n### Derivation of Euler Local truncation error\nThe left hand side of a initial value problem $\\frac{dy}{dt}$ is approximated by __Taylors theorem__ expand about a point $t_0$ giving:\n\\begin{equation}y(t_1) = y(t_0)+(t_1-t_0)y^{'}(t_0) + \\frac{(t_1-t_0)^2}{2!}y^{''}(\\xi), \\ \\ \\ \\ \\ \\ \\xi \\in [t_0,t_1]. \\end{equation}\nRearranging and letting $h=t_1-t_0$ the equation becomes\n$$y^{'}(t_0)=\\frac{y(t_1)-y(t_0)}{h}-\\frac{h}{2}y^{''}(\\xi). $$\nFrom this the local truncation error is\n$$\\tau y^{'}(t_0)\\leq \\frac{h}{2}M $$\nwhere $y^{''}(t) \\leq M $.\n#### Derivation of Euler Local truncation error for the Population Growth\nIn most cases $y$ is unknown but in our example problem there is an exact solution which can be used to estimate the local truncation\n$$y'(t)=5e^{0.5 t}$$\n$$y''(t)=2.5e^{0.5 t}$$\nFrom this a maximum upper limit can be calculated for $y^{''} $ on the interval $[t_0,t_1]=[0,0.1]$\n$$y''(0.1)=2.5e^{0.1\\times 0.5}=2.63=M$$\n$$\\tau=\\frac{h}{2}2.63=0.1315 $$\nThe plot below shows the exact local truncation error $|y-w|$ (red triangle) and the upper limit of the Truncation error (black v) for the first two time points $t_0$ and $t_1$.\n\n\n```python\nfig = plt.figure(figsize=(10,4))\nplt.plot(time[0:2],np.abs(w[0:2]-y[0:2]),'^:'\n ,color='red',label='Error |y-w|')\nplt.plot(time[0:2],0.1*2.63/2*np.ones(2),'v:'\n ,color='black',label='Upper Local Truncation')\nplt.xlim((0,.15))\nplt.xlabel('time')\nplt.legend(loc='best')\nplt.title('Local Truncation Error')\n```\n\n## Global Error\nThe error does not stay constant accross the time this is illustrated in the figure below for the population growth equation. The actual error (red triangles) increases over time while the local truncation error (black v) remains constant.\n\n\n```python\nfig = plt.figure(figsize=(10,4))\nplt.plot(time,np.abs(w-y),'^:'\n ,color='red',label='Error |y-w|')\nplt.plot(time,0.1*2.63/2*np.ones(N+1),'v:'\n ,color='black',label='Upper Local Truncation')\nplt.xlim((0,2))\nplt.xlabel('time')\nplt.legend(loc='best')\nplt.title('Why Local Truncation does not extend to global')\n```\n\n## Theorems\nTo theorem below proves an upper limit of the global truncation error.\n### Euler Global Error\n__Theorem Global Error__\n\nSuppose $f$ is continuous and satisfies a Lipschitz Condition with constant\nL on $D=\\{(t,y)|a\\leq t \\leq b, -\\infty < y < \\infty \\}$ and that a constant M\nexists with the property that \n$$ |y^{''}(t)|\\leq M. $$\nLet $y(t)$ denote the unique solution of the Initial Value Problem\n$$ y^{'}=f(t,y) \\ \\ \\ a\\leq t \\leq b \\ \\ \\ y(a)=\\alpha $$\nand $w_0,w_1,...,w_N$ be the approx generated by the Euler method for some\npositive integer N. Then for $i=0,1,...,N$\n$$ |y(t_i)-w_i| \\leq \\frac{Mh}{2L}|e^{L(t_i-a)}-1|. $$\n\n### Theorems about Ordinary Differential Equations\n__Definition__\n\nA function $f(t,y)$ is said to satisfy a __Lipschitz Condition__ in the variable $y$ on \nthe set $D \\subset R^2$ if a constant $L>0$ exist with the property that\n$$ |f(t,y_1)-f(t,y_2)| < L|y_1-y_2| $$\nwhenever $(t,y_1),(t,y_2) \\in D$. The constant L is call the Lipschitz Condition\nof $f$.\n\n__Theorem__\nSuppose $f(t,y)$ is defined on a convex set $D \\subset R^2$. If a constant\n$L>0$ exists with\n$$ \\left|\\frac{\\partial f(t,y)}{\\partial y}\\right|\\leq L $$\nthen $f$ satisfies a Lipschitz Condition an $D$ in the variable $y$ with\nLipschitz constant L.\n\n\n### Global truncation error for the population equation\nFor the population equation specific values $L$ and $M$ can be calculated.\n\nIn this case $f(t,y)=\\epsilon y$ is continuous and satisfies a Lipschitz Condition with constant\n$$ \\left|\\frac{\\partial f(t,y)}{\\partial y}\\right|\\leq L $$\n$$ \\left|\\frac{\\partial \\epsilon y}{\\partial y}\\right|\\leq \\epsilon=0.5=L $$\n\non $D=\\{(t,y)|0\\leq t \\leq 2, 10 < y < 30 \\}$ and that a constant $M$\nexists with the property that \n$$ |y^{''}(t)|\\leq M. $$\n$$ |y^{''}(t)|=2.5e^{0.5\\times 2} \\leq 2.5 e=6.8. $$\nLet $y(t)$ denote the unique solution of the Initial Value Problem\n$$ y^{'}=0.5 y \\ \\ \\ 0\\leq t \\leq 10 \\ \\ \\ y(0)=10 $$\nand $w_0,w_1,...,w_N$ be the approx generated by the Euler method for some\npositive integer N. Then for $i=0,1,...,N$\n$$ |y(t_i)-w_i| \\leq \\frac{6.8 h}{2\\times 0.5}|e^{0.5(t_i-0)}-1| $$\n\nThe figure below shows the exact error $y-w$ in red triangles and the upper global error in black x's.\n\n\n```python\nfig = plt.figure(figsize=(10,4))\nplt.plot(time,np.abs(w-y),'^:'\n ,color='red',label='Error |y-w|')\nplt.plot(time,0.1*6.8*(np.exp(0.5*time)-1),'x:'\n ,color='black',label='Upper Global Truncation')\nplt.xlim((0,2))\nplt.xlabel('time')\nplt.legend(loc='best')\nplt.title('Global Truncation Error')\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "c8c213b8678addc2915a703964e102d4d447709c", "size": 120421, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Chapter 01 - Euler Methods/.ipynb_checkpoints/01_Euler_method_with_Theorems_nonlinear_Growth_function-checkpoint.ipynb", "max_stars_repo_name": "jjcrofts77/Numerical-Analysis-Python", "max_stars_repo_head_hexsha": "97e4b9274397f969810581ff95f4026f361a56a2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 69, "max_stars_repo_stars_event_min_datetime": "2019-09-05T21:39:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T14:00:25.000Z", "max_issues_repo_path": "Chapter 01 - Euler Methods/.ipynb_checkpoints/01_Euler_method_with_Theorems_nonlinear_Growth_function-checkpoint.ipynb", "max_issues_repo_name": "jjcrofts77/Numerical-Analysis-Python", "max_issues_repo_head_hexsha": "97e4b9274397f969810581ff95f4026f361a56a2", "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": "Chapter 01 - Euler Methods/.ipynb_checkpoints/01_Euler_method_with_Theorems_nonlinear_Growth_function-checkpoint.ipynb", "max_forks_repo_name": "jjcrofts77/Numerical-Analysis-Python", "max_forks_repo_head_hexsha": "97e4b9274397f969810581ff95f4026f361a56a2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 13, "max_forks_repo_forks_event_min_datetime": "2021-06-17T15:34:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T14:53:43.000Z", "avg_line_length": 245.2566191446, "max_line_length": 24528, "alphanum_fraction": 0.9021848349, "converted": true, "num_tokens": 2861, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897492587141, "lm_q2_score": 0.9149009602137116, "lm_q1q2_score": 0.8607294449560144}} {"text": "### 나이브베이지 가정\n- 모든 차원의 개별 독립변수가 서로 조건부독립이라는 가정을 사용한다.\n- 벡터 x의 결합확률분포함수는 개별 스칼라 원소$x_d$의 확률분포함수의 곱\n$$\nP(x_1, \\ldots, x_D \\mid y = k) = \\prod_{d=1}^D P(x_d \\mid y = k)\n$$\n- 베이즈정리를 사용하여 조건부확률을 계산\n\n$$\n\\begin{align}\nP(y = k \\mid x) \n&= \\dfrac{ P(x_1, \\ldots, x_D \\mid y = k) P(y = k) }{P(x)} \\\\\n&= \\dfrac{ \\left( \\prod_{d=1}^D P(x_{d} \\mid y = k) \\right) P(y = k) }{P(x)}\n\\end{align}\n$$\n\n### 정규분포 나이브베이즈 모형(`GaussianNB`)\n* `theta_`: 정규분포의 기댓값 $\\mu$\n* `sigma_`: 정규분포의 분산 $\\sigma^2$\n\n\n```python\nimport scipy as sp\nnp.random.seed(0)\nrv0 = sp.stats.multivariate_normal([-2, -2], [[1, 0.9], [0.9, 2]])\nrv1 = sp.stats.multivariate_normal([2, 2], [[1.2, -0.8], [-0.8, 2]])\nx0 = rv0.rvs(40)\nx1 = rv1.rvs(60)\nX = np.vstack([x0,x1])\ny = np.hstack([np.zeros(40), np.ones(60)])\n\n```\n\n\n```python\nfrom sklearn.naive_bayes import GaussianNB\nmodel_norm = GaussianNB().fit(X,y)\n\n```\n\n\n```python\nmodel_norm.classes_\n#클래스 2개\n```\n\n\n\n\n array([0., 1.])\n\n\n\n\n```python\nmodel_norm.class_count_\n# 데이터 각각 40개, 60개\n```\n\n\n\n\n array([40., 60.])\n\n\n\n\n```python\nmodel_norm.class_prior_\n#y=0일 확률(사전확률)== 0.4, y=1일 확률==0.6\n```\n\n\n\n\n array([0.4, 0.6])\n\n\n\n\n```python\nmodel_norm.theta_[0], model_norm.sigma_[0]\n# y-0 일때의 기대값. 분포\n```\n\n\n\n\n (array([-1.96197643, -2.00597903]), array([1.02398854, 2.31390497]))\n\n\n\n\n```python\nmodel_norm.theta_[1], model_norm.sigma_[1]\n# y=1 일때의 기대값. 분포\n```\n\n\n\n\n (array([2.19130701, 2.12626716]), array([1.25429371, 1.93742544]))\n\n\n\n### X_new =[0,0]이라면 y는 무엇일지 예측하기\n\n\n```python\nx_new = [0,0]\nmodel_norm.predict_proba([x_new])\n# y=0일 확률 0.48, y=1일확률 0.51\n```\n\n\n\n\n array([[0.48475244, 0.51524756]])\n\n\n\n연습 문제 1\n붓꽃 분류문제를 가우시안 나이브베이즈 모형을 사용하여 풀어보자.\n\n(1) 각각의 종이 선택될 사전확률을 구하라.\n\n(2) 각각의 종에 대해 꽃받침의 길이, 꽃받침의 폭, 꽃잎의 길이, 꽃잎의 폭의 평균과 분산을 구하라.\n\n(3) 학습용 데이터를 사용하여 분류문제를 풀고 다음을 계산하라.\n\n분류결과표\n분류보고서\nROC커브\nAUC\n\n\n```python\nfrom sklearn.datasets import load_iris\nfrom sklearn.metrics import classification_report\nfrom sklearn.naive_bayes import GaussianNB\n\niris = load_iris()\nX = iris.data\ny = iris.target\n\nmodel_norm = GaussianNB().fit(X,y)\nmodel_norm.class_prior_ #각 클래스의 사전확률\n```\n\n\n\n\n array([0.33333333, 0.33333333, 0.33333333])\n\n\n\n\n```python\nmodel_norm.theta_[0], model_norm.sigma_[0]\n```\n", "meta": {"hexsha": "385cf29666dbdc9583c26b4b6971a47b0ff4f6c3", "size": 5568, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "machine_learning/08_naive_bayes.ipynb", "max_stars_repo_name": "dayoungMM/TIL", "max_stars_repo_head_hexsha": "b844ef5621657908d4c256cdfe233462dd075e8b", "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": "machine_learning/08_naive_bayes.ipynb", "max_issues_repo_name": "dayoungMM/TIL", "max_issues_repo_head_hexsha": "b844ef5621657908d4c256cdfe233462dd075e8b", "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/08_naive_bayes.ipynb", "max_forks_repo_name": "dayoungMM/TIL", "max_forks_repo_head_hexsha": "b844ef5621657908d4c256cdfe233462dd075e8b", "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": 20.3956043956, "max_line_length": 90, "alphanum_fraction": 0.4770114943, "converted": true, "num_tokens": 1128, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9603611631680359, "lm_q2_score": 0.8962513655129178, "lm_q1q2_score": 0.8607250038749262}} {"text": "## Linear independence\n\n\n```python\nimport numpy as np\nfrom sympy.solvers import solve\nfrom sympy import Symbol\n\nx = Symbol('x')\ny = Symbol('y')\nz = Symbol('z')\n```\n\nThe set of vectors are called linearly independent because each of the vectors in the set {V0, V1, …, Vn−1} cannot be written as a combination of the others in the set.\n\n### Linear Independent Arrays\n\n\n```python\nA = np.array([1,1,1])\nB = np.array([0,1,1])\nC = np.array([0,0,1])\nZ = np.array([0,0,0])\n```\n\n\n```python\nnp.array_equal(\n Z, \n 0*A + 0*B + 0*C\n)\n```\n\n\n\n\n True\n\n\n\n\n```python\nsolve(x*A + y*B + z*C)\n```\n\n\n\n\n {z: 0, y: 0, x: 0}\n\n\n\n### Linear Dependent Arrays\n\n\n```python\nA = np.array([1,1,1])\nB = np.array([0,0,1])\nC = np.array([1,1,0])\n```\n\n\n```python\n1*A + -1*B + -1*C\n```\n\n\n\n\n array([0, 0, 0])\n\n\n\n\n```python\nsolve(x*A + y*B + z*C)\n```\n\n\n\n\n {y: z, x: -z}\n\n\n\n\n```python\nA = np.array([1,2,3])\nB = np.array([1,-4,-4])\nC = np.array([3,0,2])\n```\n\n\n```python\n2*A + 1*B + -C\n```\n\n\n\n\n array([0, 0, 0])\n\n\n\n\n```python\nsolve(x*A + y*B + z*C)\n```\n\n\n\n\n {y: -z, x: -2*z}\n\n\n", "meta": {"hexsha": "d0516b337d6037d2fdcf41d288b3b9e5810dcd47", "size": 3937, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "juypter/notebooks/linear-algebra/3_linear_independence.ipynb", "max_stars_repo_name": "JamesMcGuigan/ecosystem-research", "max_stars_repo_head_hexsha": "bfd98bd5b0a2165f449eb36b368b54fe972374fe", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-01-01T02:04:27.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-01T02:04:27.000Z", "max_issues_repo_path": "juypter/notebooks/linear-algebra/3_linear_independence.ipynb", "max_issues_repo_name": "JamesMcGuigan/ecosystem-research", "max_issues_repo_head_hexsha": "bfd98bd5b0a2165f449eb36b368b54fe972374fe", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-03-09T17:51:00.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-09T17:51:00.000Z", "max_forks_repo_path": "juypter/notebooks/linear-algebra/3_linear_independence.ipynb", "max_forks_repo_name": "JamesMcGuigan/ecosystem-research", "max_forks_repo_head_hexsha": "bfd98bd5b0a2165f449eb36b368b54fe972374fe", "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": 17.4203539823, "max_line_length": 174, "alphanum_fraction": 0.4419608839, "converted": true, "num_tokens": 397, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9632305339244014, "lm_q2_score": 0.8933094124452288, "lm_q1q2_score": 0.860462902309311}} {"text": "# Variational Inference\nFor many models of practical interest, evaluating the posterior distribution will be intractable either because of the high dimensionality of the latent space or a complex form of the posterior distribution. For such cases, approximation schemes are handy in deriving a good lower or upper bound on the posterior distribution. The approximation schemes fall into 2 categories - deterministic and stochastic. Stochastic methods involve sampling while deterministic methods are based on analytical approximations to the posterior. In this section, we review variational approximations to the posterior.\n\nSuppose we have a fully Bayesian model with a set of $N$ observed variables $X = \\{x_1,x_2,\\ldots,x_N \\}$ and latent variables $Z = \\{z_1,z_2,\\ldots,z_N \\}$. Assume our model specifies the joint distribution $p(X,Z)$ and our goal is to find an approximation for the conditional $p(Z|X)$ which enables us to make predictions on $X$. We can express the log marginal likelihood of the data as: $ \\log {p(X)} = \\mathcal{L}(q) + KL(q||p) $ where\n\n$$ \\begin{align} \\mathcal{L}(q) &= \\int {q(Z) \\log{\\frac{p(X,Z)}{q(Z)}}dZ} \\\\\nKL(q||p) &= \\int{q(Z) \\log{\\frac{p(Z|X)}{q(Z)}}dZ}\\end{align}$$\n\nThe variational inference proceeds by maximizing the lower bound $\\mathcal{L}(q)$ with respect to the distribution $q(Z)$ which is equivalent to minimizing the KL divergence. The KL divergence is minimum (equals 0) when $q(Z) = p(Z|X)$. When the posterior $p(Z|X)$ is intractable, we use a restricted family of distributions for $q(Z)$ and then seek the member of the family that minimizes the KL divergence.\n\n\n## Factorized Distributions\nWe restrict the family of distributions that factorize the joint distribution over the latent variables i.e. $q(Z) = \\prod_{i=1}^M q_i(Z_i)$\nwhere $M$ denotes the number of disjoint groups of latent variables.\n\n$$ \\begin{align} \\mathcal{L}(q) &= \\int{q(Z) \\log{\\frac{p(X,Z)}{q(Z)}}dZ} \\\\\n&= \\int{\\prod_{i=1}^M q_i(Z) \\Big( \\log{p(X,Z)} - \\log{q(Z)} \\Big) dZ } \\\\\n&= \\int{q_j \\Bigg(\\int{\\log{p(X,Z)} \\prod_{i\\ne j}^M q_i dZ_i}\\Bigg) dZ_j} - \\int{q_j \\log{q_j} dZ_j } + \\text{const.} \\\\ \n&= \\int{q_j \\log \\tilde{p}(X,Z_j) dZ_j} - \\int{q_j \\log{q_j} dZ_j } + \\text{const.} \\end{align}$$\nwhere $\\tilde{p}(X,Z_j) = \\mathbb{E}_{i\\ne j}\\left[ \\log p(X,Z)\\right] + \\text{const.}$ representing the expection with respect to the q distributions over all variables $z_i$ for $i \\ne j$.\n\nThus the lower bound $\\mathcal{L}(q_j)$ can be maximized by minimizing the KL divergence between $q_j(Z_j)$ and $\\tilde{p}(X,Z_j)$. Thus we obtain $\\log{q_j^*(Z_j)} = \\mathbb{E}_{i\\ne j}\\left[ \\log p(X,Z)\\right] + \\text{const.}$\n\nWe determine the optimal solution over all the $z_j$ by initializing all the factors $q_j(Z_j)$ and then cycling through the factors replacing each in turn with a revised estimate given the right hand side of the above equation. We can ignore the constant term as it serves to normalize the distribution. Convergence is guaranteed because the bound is convex with respect to each of the factors $q_j(Z_j)$.\n\n## Example\n\nThis is an example to demonstrate the variational approximation and adapted from Figure 4.14 in [1]. This is also the same example used to demonstrate the [Laplace approximation](https://chandrusuresh.github.io/MyNotes/files/DensityEstimation/LaplaceApproximation.html).\n\nSuppose $p(z) \\propto \\sigma(20z+4) \\exp{\\left(\\frac{-z^2}{2}\\right)}$ where $\\sigma(\\cdot)$ is the sigmoid function. This form is very common in classification problems and serves as a good practical example.\n\nThis is a distribution on a scalar random variable $z$ and we seek to approximate it with a Gaussian. The parameters for Gaussian distributions will be determined by variational approximation. To initialize, we introduce conjugate prior distributions for the mean $\\mu$ and precision $\\tau$ given by:\n\n$$ \\begin{align} p(\\tau) &= \\text{Gam}(\\tau|a_0,b_0) \\\\\np(\\mu|\\tau) &= \\mathcal{N}(\\mu|\\mu_0,(\\lambda_0 \\tau)^{-1})\\end{align}$$\n\nWe assume the posterior $q(\\mu,\\tau)$ factorizes as: $q(\\mu,\\tau) = q_{\\mu}(\\mu) \\cdot q_{\\tau}(\\tau)$.\n\n$$ \\begin{align} \\mathcal{L}(q) &= \\int{q(Z) \\ln\\left\\{\\frac{p(X,Z)}{q(Z)}\\right\\}dZ} \\\\\n&= \\int{q_{\\mu} q_{\\tau} \\ln\\left\\{\\frac{p(X|\\mu,\\tau) \\cdot p(\\mu|\\tau) \\cdot p(\\tau)}{q_{\\mu} q_{\\tau}}\\right\\}dZ} \\end{align}$$\n\n\n### Optimal distribution for $\\mu$\n$$\\begin{align}\\Rightarrow \\mathcal{L}(q_{\\mu}) &= \\int{q_{\\mu} \\int{q_{\\tau} \\log{\\left[p(X|\\mu,\\tau) \\cdot p(\\mu|\\tau) \\cdot p(\\tau)\\right]}d\\tau } d\\mu} - \\int q_{\\mu} \\log{q_{\\mu}} d\\mu - \\int q_{\\tau} \\log{q_{\\tau}} d\\tau\\\\ \n&= \\int{q_{\\mu} \\int{q_{\\tau} \\log{\\left[p(X|\\mu,\\tau) \\cdot p(\\mu|\\tau) \\right] }d\\tau} d\\mu} - \\int q_{\\mu} \\log{q_{\\mu}} d\\mu - \\int q_{\\tau} \\log{q_{\\tau}} d\\tau + \\int{q_{\\mu} q_{\\tau} \\log{p(\\tau)}}d\\tau d\\mu\\\\\n&= \\int{q_{\\mu} \\int{q_{\\tau} \\log{\\left[p(X|\\mu,\\tau) \\cdot p(\\mu|\\tau) \\right] }d\\tau} d\\mu} - \\int q_{\\mu} \\log{q_{\\mu}} d\\mu + \\text{const.}\\end{align}$$\n\nThe lower bound can be maximized by maximizing the right hand side. The right hand side is also the negative KL divergence $ KL(q_{\\mu}||\\mathbb{E}_{\\tau} \\left[p(X|\\mu,\\tau) \\cdot p(\\mu|\\tau)\\right])$\n\nThe factorized distribution assumption above implies that $p(\\mu|\\tau) = p(\\mu)$, we can further simplify the above expression as follows:\n\n$$ \\log q^*_{\\mu} = \\mathbb{E}_{\\tau} \\log \\left[p(X|\\mu,\\tau) \\cdot q(\\mu) \\right]) + \\text{const.} $$\nThe optimum factors can be obtained as follows:\n\n$$ \\begin{align} \\log{q_{\\mu}^*(\\mu)} &= \\mathbb{E}_{\\tau} \\left[-\\frac{\\tau}{2} \\sum_{n=1}^N (x_n-\\mu)^2 - \\frac{\\lambda_0 \\tau}{2} (\\mu-\\mu_0)^2 \\right] + \\text{const.} \\\\\n&= -\\frac{\\mathbb{E}(\\tau)}{2} \\left[ \\sum_{n=1}^N (x_n-\\mu)^2 + \\lambda_0(\\mu-\\mu_0)^2\\right] + \\text{const.} \\end{align}$$\n\nNotice that the expression is quadratic and therefore parameters of a Gaussian distribution can be determined by completing the square.\n\n$$ \\begin{align} \\mu_N &= \\frac{\\lambda_0 \\mu_0 + N\\bar{x}}{N + \\lambda_0}\\\\\n\\lambda_N &= (N+\\lambda_0) \\mathbb{E}(\\tau)\\end{align}$$\n\n### Optimal distribution for $\\tau$\n$$\\begin{align}\\Rightarrow \\mathcal{L}(q_{\\tau}) &= \\int{q_{\\tau} \\int{q_{\\mu} \\log{\\left[p(X|\\mu,\\tau) \\cdot p(\\mu|\\tau) \\cdot p(\\tau)\\right]}d\\mu } d\\tau} - \\int q_{\\mu} \\log{q_{\\mu}} d\\mu - \\int q_{\\tau} \\log{q_{\\tau}} d\\tau\\\\ \n&= \\int{q_{\\tau} \\int{q_{\\mu} \\log{\\left[p(X|\\mu,\\tau) \\cdot p(\\mu|\\tau) \\cdot p(\\tau) \\right] }d\\mu} d\\tau} - \\int q_{\\tau} \\log{q_{\\tau}} d\\tau - \\int q_{\\mu} \\log{q_{\\mu}} d\\mu + \\int{q_{\\mu} q_{\\tau} \\log{p(\\mu)}}d\\tau d\\mu\\\\\n&= \\int{q_{\\mu} \\int{q_{\\tau} \\log{\\left[p(X|\\mu,\\tau) \\cdot p(\\mu|\\tau) \\cdot p(\\tau) \\right] }d\\mu} d\\tau} - \\int q_{\\tau} \\log{q_{\\tau}} d\\tau + \\text{const.}\\end{align}$$\n\nThe lower bound can be maximized by maximizing the right hand side. The right hand side is also the negative KL divergence $ KL(q_{\\tau}||\\mathbb{E}_{\\mu} \\left[p(X|\\mu,\\tau) \\cdot p(\\mu|\\tau) \\cdot p(\\tau)\\right])$\n\nFrom the factorized distribution assumption above, we can further simplify the above expression as follows:\n\n$$ \\log q^*_{\\tau} = \\mathbb{E}_{\\mu} \\log \\left[p(X|\\mu,\\tau) \\cdot q(\\mu) \\cdot q(\\tau)\\right]) + \\text{const.} $$\n\nThe optimum factors can be obtained as follows:\n\n$$ \\begin{align} \\log{q_{\\tau}^*} &= \\mathbb{E}_{\\mu} \\left[\\frac{N}{2}\\log{\\tau} -\\frac{\\tau}{2} \\sum_{n=1}^N (x_n-\\mu)^2 - \\frac{\\lambda_0 \\tau}{2} (\\mu-\\mu_0)^2 + (a_0-1)\\log{\\tau} - b \\tau\\right] + \\text{const.} \\\\\n&= \\frac{N}{2}\\log{\\tau} + (a_0-1)\\log{\\tau} - b \\tau - \\frac{\\tau}{2} \\mathbb{E}_{\\mu}\\left[ \\sum_{n=1}^N (x_n-\\mu)^2 + \\lambda_0(\\mu-\\mu_0)^2\\right] + \\text{const.} \\end{align}$$\n\nThis implies that $q_{\\tau}$ is a Gamma distribution with parameters:\n\n$$ \\begin{align} a_N &= a_0 + \\frac{N}{2}\\\\\nb_N &= b_0 + \\frac{1}{2}\\mathbb{E}_{\\mu}\\left[ \\sum_{n=1}^N (x_n-\\mu)^2 + \\lambda_0(\\mu-\\mu_0)^2\\right] \\\\\n&= b_0 + \\frac{\\lambda_0 \\mu_0^2}{2} + \\frac{1}{2} \\left[ \\sum_{n=1}^N{x_n^2} - 2 (N\\bar{x}+\\lambda_0\\mu_0) \\mathbb{E}(\\mu)+(N+\\lambda_0)\\mathbb{E}(\\mu^2) \\right]\\end{align}$$\n\nWe iterate on computing optimal values of $\\mu$ and $\\tau$ till convergence to get the optimal parameters for the posterior distribution.\n\n## Back to the Example\n\n\n```python\nimport numpy as np\nfrom scipy.integrate import trapz,cumtrapz\nfrom scipy.stats import norm\nimport matplotlib.pyplot as plt\nimport matplotlib\n%matplotlib inline\n\nfrom numpy.random import rand\n\ndef sigmoid(x):\n den = 1.0+np.exp(-x)\n return 1.0/den\n\ndef p_z(z):\n p = np.exp(-np.power(z,2)/2)*sigmoid(20*z+4)\n sum_p = trapz(p,z) ## normalize for plotting\n return p,p/sum_p\n\n## Laplace Approximation\ndef findMode(z_init,max_iter = 25,tol = 1E-6):\n iter = 0\n z_next = np.finfo('d').max\n z_cur = z_init\n while (iter < max_iter and np.abs(z_next-z_cur) > tol):\n if iter > 0:\n z_cur = z_next\n y = z_cur - 20*(1-sigmoid(20*z_cur+4))\n der_y = 1 + 400*sigmoid(20*z_cur+4)*(1-sigmoid(20*z_cur+4))\n z_next = z_cur - y/der_y\n iter = iter+1\n return z_next\n\ndef getHessian(z):\n sig_x = sigmoid(20*z+4)\n return 400*sig_x*(1-sig_x) + 1\n\n## Variational Approximation\ndef getMu(X,E_tau,mu0,lambda0):\n N = float(len(X))\n mu_N = (lambda0*mu0 + np.sum(X))/(N+lambda0)\n lambda_N = (N+lambda0)*E_tau\n return mu_N,lambda_N\n\ndef getTau(X,mu_N,lambda_N,mu0,lambda0,a0,b0):\n N = float(len(X))\n a_N = a0 + N/2\n b_N = b0 + 0.5*lambda0*np.power(mu0,2) + 0.5*(np.sum(np.power(X,2)) - 2*mu_N*(N+lambda0)*np.mean(X))\n if lambda_N != 0:\n b_N = b_N + 0.5*(N+lambda0)*(1/lambda_N + np.power(mu_N,2))\n return a_N,b_N\n \ndef VariationalApproximation(X,mu0,lambda0,a0,b0,max_iter=25,tol=1E-6):\n count = 0\n E_tau = 0\n if b0 != 0:\n E_tau = a0/b0\n mu1 = mu0\n lambda1 = lambda0\n a1 = a0\n b1 = b0\n post_prob = []\n while count < max_iter:\n count = count+1\n mu_N,lambda_N = getMu(X,E_tau,mu0,lambda0)\n a_N,b_N = getTau(X,mu_N,lambda_N,mu0,lambda0,a0,b0)\n max_del = np.max(np.array([np.abs(mu_N-mu1),np.abs(lambda_N-lambda1),np.abs(a_N-a1),np.abs(b_N-b1)]))\n# print(count,max_del)\n if max_del <= tol:\n print(\"Converged after Iteration:\"+str(count))\n break\n mu1 = mu_N\n lambda1 = lambda_N\n a1 = a_N\n b1 = b_N\n E_tau = a1/b1\n return mu_N,lambda_N,a_N,b_N\n\ndef sampleData(z,pzn,N):\n x = np.zeros((N,))\n cdf = cumtrapz(pzn,z,initial=0)\n for i in range(N):\n rnd = rand()\n dif = np.abs(cdf-rnd)\n idx = np.where(dif == np.min(dif))[0]\n x[i] = z[idx]\n return x\n```\n\n\n```python\nz = np.linspace(-10,10,10000)\npz,pzn = p_z(z)\n\n## Get Laplace distribution\nz0 = findMode(0)\nA = getHessian(z0)\nz0_idx = np.where(np.abs(z-z0) == np.min(np.abs(z-z0)))[0]\np_z0 = pzn[z0_idx]\n\n## Get approx Gaussian distribution\nq_z_laplace = norm.pdf(z, z0, 1/np.sqrt(A))\n```\n\n\n```python\nz_sample = sampleData(z,pzn,10000)\nmu0=0\nlambda0 = 0\na0=0\nb0=0\nmu_N,lambda_N,a_N,b_N = VariationalApproximation(z_sample,mu0,lambda0,a0,b0)\nprint('mu_opt = ',mu_N)\nprint('lambda_opt = ',lambda_N)\nprint('a_opt = ',a_N)\nprint('b_opt = ',b_N)\nq_z_va = norm.pdf(z, mu_N, np.sqrt(b_N/a_N))\n```\n\n Converged after Iteration:6\n mu_opt = 0.6656897689768977\n lambda_opt = 24425.335351142647\n a_opt = 5000.0\n b_opt = 2047.0548011395454\n\n\n\n```python\nfig,ax = plt.subplots(1,1,figsize=(5,3))\nax.cla()\nax.plot(z,pzn,color=\"orange\")\nax.fill_between(z,pzn, 0,\n facecolor=\"orange\", # The fill color\n color='orange', # The outline color\n alpha=0.2) # Transparency of the fill\n#ax.axvline(x=z0)#,ylim=0,ymax=0.7)\nax.vlines(z0, ymin=0, ymax=p_z0,linestyles='dotted')\nax.plot(z,q_z_laplace,'r')\nax.plot(z,q_z_va,'g')\nax.set_xlim([-2,4]);\nax.set_ylim([0,0.8]);\nax.set_yticks([0,0.2,0.4,0.6,0.8]);\nax.legend(['Original','Laplace','Variational'])\nax.set_title('Laplace & Variational approximations');\n```\n\n## References\n1. Bishop, Christopher M. 2006. Pattern Recognition and Machine Learning. Springer.\n", "meta": {"hexsha": "b7eaf6f61e34f7f13477ff4acb0a80ed240e4e74", "size": 43110, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "files/DensityEstimation/VariationalInference.ipynb", "max_stars_repo_name": "chandrusuresh/MyNotes", "max_stars_repo_head_hexsha": "4e0f86195d6d9eb3168bfb04ca42120e9df17f0b", "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": "files/DensityEstimation/VariationalInference.ipynb", "max_issues_repo_name": "chandrusuresh/MyNotes", "max_issues_repo_head_hexsha": "4e0f86195d6d9eb3168bfb04ca42120e9df17f0b", "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": "files/DensityEstimation/VariationalInference.ipynb", "max_forks_repo_name": "chandrusuresh/MyNotes", "max_forks_repo_head_hexsha": "4e0f86195d6d9eb3168bfb04ca42120e9df17f0b", "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": 115.5764075067, "max_line_length": 26352, "alphanum_fraction": 0.800487126, "converted": true, "num_tokens": 4304, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422186079557, "lm_q2_score": 0.9046505286741726, "lm_q1q2_score": 0.8604513109080125}} {"text": "# [Goldbach’s other conjecture](https://projecteuler.net/problem=46)\n
\nIt was proposed by Christian Goldbach that every odd composite number can be written as the sum of a prime and twice a square.\n\n$\n\\begin{align}\n9 & = 7 + 2 \\times 1^2 \\\\\n15 & = 7 + 2 \\times 2^2 \\\\\n21 & = 3 + 2 \\times 3^2 \\\\\n25 & = 7 + 2 \\times 3^2 \\\\\n27 & = 19 + 2 \\times 2^2 \\\\\n33 & = 31 + 2 \\times 1^2\n\\end{align}\n$\n\nIt turns out that the conjecture was false.\n\nWhat is the smallest odd composite that cannot be written as the sum of a prime and twice a square?\n
\n\nStarting with $9$, check each odd composite number $n$ to see if it is the sum of a prime and twice a square. Only check primes less than $n$ and integers not greater than $\\sqrt{n / 2}$. If $n$ is not such a sum, we are done.\n\n\n```julia\nusing Primes\n\nf(n) = any(n == p + 2 * b^2 for p in primes(n), b in 1:isqrt(n÷2))\nfunction g(n)\n n += 2\n while isprime(n) n += 2; end\n n\nend\n\nn = 9\nwhile f(n)\n n = g(n)\nend\nn\n```\n\n\n\n\n 5777\n\n\n", "meta": {"hexsha": "2462f7198cf721b3475e97a03947579f8511dc61", "size": 2034, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "work/problem046.ipynb", "max_stars_repo_name": "robireton/math-capstone", "max_stars_repo_head_hexsha": "71f4217aef2e11a7e4e63cec38392a185c72598b", "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/problem046.ipynb", "max_issues_repo_name": "robireton/math-capstone", "max_issues_repo_head_hexsha": "71f4217aef2e11a7e4e63cec38392a185c72598b", "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/problem046.ipynb", "max_forks_repo_name": "robireton/math-capstone", "max_forks_repo_head_hexsha": "71f4217aef2e11a7e4e63cec38392a185c72598b", "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.9294117647, "max_line_length": 233, "alphanum_fraction": 0.4926253687, "converted": true, "num_tokens": 342, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338112885303, "lm_q2_score": 0.894789468908171, "lm_q1q2_score": 0.8603703283401136}} {"text": "# Combination - Passwords & Students\n\n> This document is written in *R*.\n>\n> ***GitHub***: https://github.com/czs108\n\n## Question A\n\n> If passwords can consist of **6** *letters*, find the probability that a randomly chosen password will *not* have any *repeated* letters.\n\n\\begin{equation}\nP = \\frac{26 \\times 25 \\times \\cdots \\times 21}{26^{6}}\n\\end{equation}\n\n\n```R\nnorpt <- 0\ncount <- 100000\nfor (i in c(1:count)) {\n pwd <- sample(x=letters, size=6, replace=TRUE)\n if (length(unique(pwd)) == 6) {\n norpt <- norpt + 1\n }\n}\n\nnorpt / count\n```\n\n\n0.53777\n\n\n## Question B\n\n> How many ways can you get a sample of **6** letters *without* *repeated* letters, if the order does *not* matter?\n\n\\begin{equation}\n^{26}C_6 = \\frac{26!}{6! \\times 20!}\n\\end{equation}\n\n\n```R\nchoose(n=26, k=6)\n```\n\n\n230230\n\n\n## Question C\n\n> Use the `sample` command to simulate tossing a coin **10000** times. You can use a `for` loop and record the result of each toss. Then you can the use `table` command to find how often you got *heads* or *tails*.\n\n\n```R\nres <- sample(x=c(\"Head\", \"Tail\"), size=10000, replace=TRUE)\n\nprop.table(table(res))\n```\n\n\n res\n Head Tail \n 0.5015 0.4985 \n\n\n## Question D\n\n> If a class contains **60** *females* and **40** *males* and you choose a random sample of **5** students from the class, what is the probability of getting **5** *females*?\n\n\\begin{equation}\nP = \\frac{^{60}C_5}{^{100}C_{5}}\n\\end{equation}\n\n\n```R\nchoose(n=60, k=5) / choose(n=100, k=5)\n```\n\n\n0.0725420627482483\n\n\nCheck the *Hypergeometric Distribution*.\n\n\n```R\ndhyper(x=c(0:5), m=60, n=40, k=5)\n```\n\n\n
    \n\t
  1. 0.00873993458676817
  2. \n\t
  3. 0.072832788223068
  4. \n\t
  5. 0.232277540819514
  6. \n\t
  7. 0.354528878092943
  8. \n\t
  9. 0.259078795529458
  10. \n\t
  11. 0.0725420627482483
  12. \n
\n\n\n\n## Question E\n\n> Use the `sample` command to simulate the situation in *Question D*. Repeat the sample **10000** times. How often do you get **5** *females*?\n\n\n```R\nstudents <- c(rep(\"Male\", 40), rep(\"Female\", 60))\nnoman <- 0\ncount <- 10000\nfor (i in c(1:count)) {\n group <- sample(x=students, size=5)\n if (group[1] == \"Female\" && length(unique(group)) == 1) {\n noman <- noman + 1\n }\n}\n\nnoman / count\n```\n\n\n0.0771\n\n", "meta": {"hexsha": "351dc578b236a2d8657c6e3e7373b9c704ee3c85", "size": 6639, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "exercises/Combination - Passwords & Students.ipynb", "max_stars_repo_name": "czs108/Probability-Theory-Exercises", "max_stars_repo_head_hexsha": "60c6546db1e7f075b311d1e59b0afc3a13d93229", "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/Combination - Passwords & Students.ipynb", "max_issues_repo_name": "czs108/Probability-Theory-Exercises", "max_issues_repo_head_hexsha": "60c6546db1e7f075b311d1e59b0afc3a13d93229", "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/Combination - Passwords & Students.ipynb", "max_forks_repo_name": "czs108/Probability-Theory-Exercises", "max_forks_repo_head_hexsha": "60c6546db1e7f075b311d1e59b0afc3a13d93229", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-03-21T05:04:07.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-21T05:04:07.000Z", "avg_line_length": 21.1433121019, "max_line_length": 220, "alphanum_fraction": 0.4637746649, "converted": true, "num_tokens": 764, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768604361741, "lm_q2_score": 0.9111797015700341, "lm_q1q2_score": 0.8603147899215648}} {"text": "# 2021-11-03 Software discussion\n\n## Last time\n\n* Running multigrid with PETSc\n* Projects\n* GitHub codesearch, JOSS search\n* Decide what's next: **Finite Element** or Finite Volume\n\n## Today\n\n* Project discussion\n* Weak forms\n\n# Integration by parts\n\n## One dimension\n\n> it's the product rule backwards\n\n\\begin{align} \\int_a^b d(uv) &= \\int_a^b u dv + \\int_a^b v du \\\\\n(uv)_a^b &= \\int_a^b u dv + \\int_a^b v du \\\\\n\\int_a^b u dv &= (uv)_a^b - \\int_a^b v du\n\\end{align}\n\n> you can move the derivative to the other term; it'll cost you a minus sign and a boundary term\n\n## Multiple dimensions\n\n\\begin{align}\n\\int_\\Omega v \\nabla\\cdot \\mathbf f = -\\int_\\Omega \\nabla v \\cdot \\mathbf f + \\int_{\\partial \\Omega} v \\mathbf f \\cdot \\mathbf n\n\\end{align}\n\n## Strong form\n\n$$ -\\nabla\\cdot(\\kappa \\nabla u) = 0 $$\n\n## Weak form\n* multiply by a test function and integrate by parts\n\n\\begin{align} -\\int_\\Omega v \\nabla\\cdot(\\kappa \\nabla u) = 0, \\forall v \\\\\n\\int_\\Omega \\nabla v \\cdot \\kappa \\nabla u - \\int_{\\partial\\Omega} v \\underbrace{\\kappa \\nabla u \\cdot \\mathbf n}_{\\text{boundary condition}} = 0\n\\end{align}\n", "meta": {"hexsha": "03060d68fce4e60e37dcbeb58434483f6257d5aa", "size": 2457, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "slides/2021-11-03-discussion.ipynb", "max_stars_repo_name": "cu-numpde/numpde", "max_stars_repo_head_hexsha": "e5e1a465a622eba56900004f9a503412407cdccf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-01T20:54:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-01T20:54:51.000Z", "max_issues_repo_path": "slides/2021-11-03-discussion.ipynb", "max_issues_repo_name": "amta3208/fall21", "max_issues_repo_head_hexsha": "e5e1a465a622eba56900004f9a503412407cdccf", "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": "slides/2021-11-03-discussion.ipynb", "max_forks_repo_name": "amta3208/fall21", "max_forks_repo_head_hexsha": "e5e1a465a622eba56900004f9a503412407cdccf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-01T20:54:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-01T20:54:46.000Z", "avg_line_length": 23.625, "max_line_length": 169, "alphanum_fraction": 0.5026455026, "converted": true, "num_tokens": 387, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768572945969, "lm_q2_score": 0.9111797009670494, "lm_q1q2_score": 0.8603147864896993}} {"text": "```python\nimport sympy\nsympy.init_printing(use_latex=True)\n```\n\nIf you ever don't feel like taking derivatives, you can use a Python library called `sympy` to do the dirty work.\n\nWhen we have a $g$ function like this:\n\n$$\ng = \\begin{bmatrix}\nu_{\\phi} \\\\\n\\dot{y} - \\sin(\\phi) \\Delta t \\\\\ny + \\dot{y} \\Delta t\n\\end{bmatrix}\n$$\n\nand a state vector like this:\n\n$$\nx = \\begin{bmatrix}\n\\phi \\\\\n\\dot{y} \\\\\ny\n\\end{bmatrix}\n$$\n\n(Note that I'm writing $\\phi$ here instead of $x_{\\phi}$. Like wise with $\\dot{y}$ and $y$)\n\nwe can use sympy to calculate $g'$ as follows:\n\n\n```python\n# 1. define sympy symbols\nu_phi, phi, y_dot, y, dt = sympy.symbols(\n'u_phi, phi, y_dot, y, dt')\n\n# 2. define the state variable\nx = sympy.Matrix([\n phi, \n y_dot, \n y])\n\n# 3. define state transition function\ng = sympy.Matrix([\n u_phi,\n y_dot - sympy.sin(phi) * dt,\n y + y_dot * dt\n])\n\n# 4. take jacobian of g with respect to x\ng.jacobian(x)\n```\n\n\n\n\n$$\\left[\\begin{matrix}0 & 0 & 0\\\\- dt \\cos{\\left (\\phi \\right )} & 1 & 0\\\\0 & dt & 1\\end{matrix}\\right]$$\n\n\n\nYou'd still need to implement this matrix in code, but at least the derivatives have been taken care of!\n", "meta": {"hexsha": "c401e573e96cf8b3d5e1857a0cda7cf7d369359b", "size": 2734, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "jupyter_notebooks/4_State_Estimation/3_Extended_Kalman_Filters/EKF/Sympy Demonstration.ipynb", "max_stars_repo_name": "miker2/FCND-udacity", "max_stars_repo_head_hexsha": "35d8248b3bb17a04279b65b332f0623b870427a9", "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/4_State_Estimation/3_Extended_Kalman_Filters/EKF/Sympy Demonstration.ipynb", "max_issues_repo_name": "miker2/FCND-udacity", "max_issues_repo_head_hexsha": "35d8248b3bb17a04279b65b332f0623b870427a9", "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/4_State_Estimation/3_Extended_Kalman_Filters/EKF/Sympy Demonstration.ipynb", "max_forks_repo_name": "miker2/FCND-udacity", "max_forks_repo_head_hexsha": "35d8248b3bb17a04279b65b332f0623b870427a9", "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": 22.974789916, "max_line_length": 126, "alphanum_fraction": 0.4575713241, "converted": true, "num_tokens": 390, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545333502202, "lm_q2_score": 0.9073122144683576, "lm_q1q2_score": 0.8602721893122005}} {"text": "### Sum of Exponentially Distributed Random Variables\n\nLet $\\{x_i\\}$ be a collection of $n$ independent and identically distributed random variables with exponential distribution:\n\n\\begin{equation}\nX_i \\sim \\lambda e^{-\\lambda x}\\Theta(x)\n\\end{equation}\n\nWhere $\\Theta(\\cdot)$ is the Heaviside unit step function. Define a new random variable, $S$, where $S = \\sum^n_i X_i$.\n\nThis can be done by writing down the joint probability distribution $p(S,X_1,...,X_n)$ using the Dirac Delta function and then obtain $p(S)$ through marginalization. The first of the $n$ integrals is easy because of the Delta function:\n\n\\begin{equation}\n\\begin{array}{ll}\np(S) &= \\int dX^n \\ \\underbrace{\\prod_i^n \\left[ \\lambda e^{-\\lambda X_i}\\Theta(X_i) \\right]}_{p(X_1,...,X_n)}\\ \\underbrace{\\delta(S-\\sum^n_i X_i)}_{P(S|X_1,...,X_n)}\\\\\n&= \\lambda^n \\int dX^{n-1} e^{-\\lambda (\\sum_i^{n-1}X_i)} e^{-\\lambda(s-\\sum_i^{n-1}X_i)}\\left[\\prod_i^{n-1}\\Theta(X_i)\\right]\\Theta(s-\\sum_i^{n-1}X_i)\n\\end{array}\n\\end{equation}\n\nNote that the sums in the exponential will cancel in a way that allows it to be removed from the integral. What remains to solve is an integral over a product of Heaviside functions.\n\n\\begin{equation}\n\\begin{array}{ll}\np(S) &= \\lambda^n e^{-\\lambda s} \\int \\mathrm{d}X^{n-1} \\left[\\prod_i^{n-1}\\Theta(X_i)\\right]\\Theta(s-\\sum_i^{n-1}X_i)\n\\end{array}\n\\end{equation}\n\nThe integral will be a product of the lengths of $n-1$ coordinate intervals where the Heaviside functions have support.\n\n\\begin{equation}\n\\begin{array}{ll}\n&\\ \\int \\mathrm{d}X^{n-1} \\underbrace{\\left[\\prod_i^{n-1}\\Theta(X_i)\\right]\\Theta(s-\\sum_i^{n-1}X_i)}_{I_{n-1}}\\\\\n&= \\int\\mathrm{d}X^{n-2} \\left[\\left[\\prod_i^{n-2}\\Theta(X_i)\\right]X_{n-1}\\right]_{(0,\\infty)\\cap(-\\infty,s-\\sum_i^{n-2}X_i)}\\\\\n&= \\int\\mathrm{d}X^{n-2} \\underbrace{\\left[\\prod_i^{n-2}\\Theta(X_i)\\right]\\Theta(s-\\sum_i^{n-2}X_i)\\left(s-\\sum_i^{n-2}X_i\\right)}_{I_{n-2}}\\\\\n&= \\int\\mathrm{d}X^{n-3} \\underbrace{\\left[\\prod_i^{n-3}\\Theta(X_i)\\right]\\Theta(s-\\sum_i^{n-3}X_i)\\frac{1}{2}\\left(s-\\sum_i^{n-3}X_i\\right)^2}_{I_{n-3}}\\\\\n&\\vdots\\\\\n&= \\int\\mathrm{d}X^{n-m} \\underbrace{\\left[\\prod_i^{n-m}\\Theta(X_i)\\right]\\Theta(s-\\sum_i^{n-m}X_i)\\frac{1}{(m-1)!}\\left(s-\\sum_i^{n-m}X_i\\right)^{m-1}}_{I_{n-m}}\\\\\n&\\vdots\\\\\n&=\\frac{1}{(n-1)!}s^{n-1}\\Theta(s)\n\\end{array}\n\\end{equation}\n\nWhere, in the third row, the length of the interval $(0,\\infty)\\cap(-\\infty,s-\\sum_i^{n-2}X_i)$ is expressed as $\\Theta(s-\\sum_i^{n-2}X_i)\\left(s-\\sum_i^{n-2}X_i\\right)$.\n\nThe expression for the probability of seeing $n$ independent and identically distributed, exponentially distribued random variables with parameter $\\lambda$, add up to a sum $S$, is then:\n\n\\begin{equation}\np(S) = \\frac{s^{n-1}\\lambda^n}{(n-1)!} e^{-\\lambda s}\\Theta(s)\n\\end{equation}\n\nFor $n=1$, this reduces to the expression of a single exponentially distributed random variable.\n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef factorial(x):\n if x == 0:\n return 1\n else:\n res = 1\n for i in range(1,x+1):\n res *= i\n return res\n \n\ndef p_S(s,n):\n \"\"\"\n Analytical solution for the sum of n exponentially distributed random variables\n \"\"\"\n if s < 0:\n return 0\n else:\n return (s**(n-1)*lam**n*np.exp(-lam*s))/factorial(n-1)\n \n \nlam = 1\nss = np.linspace(0,50,100)\nnn = [1,5,10,20]\n\n\"\"\"\nSimulated data\n\"\"\"\nN = 1000\ndata = np.random.exponential(scale=lam,size=(max(nn),N))\n\n\n\"\"\"\nPlotting\n\"\"\"\nplt.figure(figsize=(12,5))\nfor n in nn:\n x = [p_S(s,n) for s in ss]\n plt.plot(ss,x,linewidth=3)\n res = np.sum(data[:n],axis=0)\n plt.hist(res,density=True,bins=ss)\n plt.text(1.2*n,max(x),'n='+str(n),Fontsize=12)\n \n_ = plt.title('Simulated vs. Analytical')\n```\n", "meta": {"hexsha": "6463aa9844aeb7815509831265c6a40b968b374e", "size": 29737, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Probability - Sum of Exponential Random Variables.ipynb", "max_stars_repo_name": "jpbm/probabilism", "max_stars_repo_head_hexsha": "a2f5c1595aed616236b2b889195604f365175899", "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": "Probability - Sum of Exponential Random Variables.ipynb", "max_issues_repo_name": "jpbm/probabilism", "max_issues_repo_head_hexsha": "a2f5c1595aed616236b2b889195604f365175899", "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": "Probability - Sum of Exponential Random Variables.ipynb", "max_forks_repo_name": "jpbm/probabilism", "max_forks_repo_head_hexsha": "a2f5c1595aed616236b2b889195604f365175899", "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": 196.9337748344, "max_line_length": 24116, "alphanum_fraction": 0.8827050476, "converted": true, "num_tokens": 1326, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566342037088041, "lm_q2_score": 0.8991213853793452, "lm_q1q2_score": 0.8601302705399266}} {"text": "#Introduction\nThe goal of this notebook is to solve two examples of linear regression. The first with only one feature and the second with more than one feature, a simple example of a multidimensional case with two features. The notebook follows exercises proposed in the Standford Coursera course by Andrew Ng, but I comment, with my explanations, on many points that I think are relevant for the understanding of the concepts as well as the Python implementation. \n\nThe cost function for this model, namely the linear regression (a special case of the more general class of Generalized linear models) will be given by the mean squared error function\n$$J(\\theta) = \\frac{1}{2} \\sum_{i=1}^m \\left( h^{(i)} - y^{(i)} \\right)^2 = \\frac{1}{2} \\sum_{i=1}^m J(\\theta;x^{(i)}) ,$$\nwhere $m$ is the total number of training examples and $h$ is the hypothesis function considered to be the linear combination $ h= h(\\theta; x^{(i)}) = \\theta^t x^{(i)} $ with $\\theta$ the column vector representing the weights and bias of the model and $x^{(i)}$ the i-th column vector with the features of the model. In particular, for a total of $n$-features, $x^{(i)} \\in \\mathbb{R}^{n+1}$, because we include an extra element $x_0=1$ that is associated with the bias $\\theta_0$. The main purpose of the cost or loss function is to be minimized with respect to a parameter $\\theta$ in order to make sure that the hypothesis converges to the values of the targets $y^{(i)}$, which are single scalar values. A column vector $y \\in \\mathbb{R}^{m}$ can accommodate all the $m$ target values from each training example $(x^{(i)}, y^{(i)} )$. Note that the notation $J(\\theta; x)$ tries to distinguish the role of $\\theta$ from the role of $x$: while $x$ are fixed for each training example, $\\theta$ are the coefficients to be learned by the model. Finally, capital $X$ will denote the design matrix, which is made of rows $(x^t)^{(i)}$. Thus, $X \\in \\mathbb{R}^{(m, n+1)}$ and $\\theta \\in \\mathbb{R}^{(n+1, 1)}$ is a matrix.\n\n\n\n\n```python\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt \n \n#line magic function for plot inside notebook\n%matplotlib inline \nimport seaborn as sns\n#from numpy.core.function_base import linspace\n\n\n```\n\n# Single variable Linear Regression\n\"In this part of this exercise, you will implement linear regression with one\nvariable to predict profits for a food truck. Suppose you are the CEO of a\nrestaurant franchise and are considering different cities for opening a new\noutlet. The chain already has trucks in various cities and you have data for\nprofits and populations from the cities.\n\nYou would like to use this data to help you select which city to expand\nto next.The dataset for our linear regression problem is as follows: The first column is the population of a city and the second column is\nthe profit of a food truck in that city. A negative value for profit indicates a\nloss.\n\nFor this dataset, you can use a scatter plot to visualize the data, since it has only two properties to plot (profit and population). (Many\nother problems that you will encounter in real life are multi-dimensional and\ncan’t be plotted on a 2-d plot.)\" (extract from Stanford-ML-ex01- Andrew Ng)\n\n\n```python\npath = '/content/drive/MyDrive/Machine_Learning_DS/Material/ML_Standford/ex1-octave/ex1data1.txt'\ndata = pd.read_csv(path, header=None, names=['Population', 'Profit'])\n\nm = len(data) #number of training values\nx = np.array(data['Population']) #capital X will be with x0s included...\ny = np.array(data['Profit'])\n\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
PopulationProfit
06.110117.5920
15.52779.1302
28.518613.6620
37.003211.8540
45.85986.8233
\n
\n \n\n \n\n \n
\n
\n\n\n\n\n\n```python\nprint(len(data.columns))\nprint(len(data.index))\n```\n\n 2\n 97\n\n\n\n```python\ndata.info()\n```\n\n \n RangeIndex: 97 entries, 0 to 96\n Data columns (total 2 columns):\n # Column Non-Null Count Dtype \n --- ------ -------------- ----- \n 0 Population 97 non-null float64\n 1 Profit 97 non-null float64\n dtypes: float64(2)\n memory usage: 1.6 KB\n\n\n\n```python\nx.shape\n\n\n```\n\n\n\n\n (97,)\n\n\n\n\n```python\nx = np.array(data['Population']).reshape(m,1)\ny = np.array(data['Profit']).reshape(m,1)\n\n\n\nx.shape\n\n```\n\n\n\n\n (97, 1)\n\n\n\n#To visualize the data\nNote that 'bx' stands for blue crosses (option) , a marker\n\n\n```python\nplt.plot(data['Population'], data['Profit'], 'rx' ) #plt.plot(x, y, 'rx' )\n#plt.figure() # not necessary \nplt.xlabel('population in 10k')\nplt.ylabel('profit in $10k')\nplt.title('Population Vs Profit')\n```\n\n#Cost function\n\nGiven my hypothesis function, consider the cost function\nto be the quadratic cost function, which is a convex function\nand works well with gradient descent.\nVectorization is the best way to go because it avoids using loops...\n\nRecall: $J(\\theta) = \\frac{1}{2m} (X \\theta - y)^T (X \\theta - y)$\nwhere X includes the $x_0=1$ related to the bias $\\theta_0$\n\nObs: numpy.append(arr, values, axis=None)\nAppend values to the end of an array.\n\n\n```python\nX = np.append(np.ones((m,1)), x, axis=1 ) #0 would be along the lines. axis=1 will add x as the next column after a column of ones\nX.shape\n```\n\n\n\n\n (97, 2)\n\n\n\n\n```python\ndef cost_function(X, y, theta):\n \"\"\"Calculate the cost function for the linear regression of a single variable \"\"\"\n global m #or define m again here locally\n return 1/(2*m) * ((np.dot(X,theta)) - y).T @ ( np.dot(X,theta) - y)\n # return 1/(2*m) * ((X @ theta) - y).T @ ((X @ theta) - y) #alternatively: sum(np.square( (X@ theta) - y ))\n```\n\n\n```python\ntheta_initial = np.zeros( (2,1) ) \nprint(cost_function(X, y, theta_initial))\n```\n\n [[32.07273388]]\n\n\n\n```python\n#NOTE these\nprint ((np.dot(X, theta_initial)).shape)\nprint ((np.dot(X, theta_initial).T).shape)\n\n(X @ theta_initial).shape\n```\n\n (97, 1)\n (1, 97)\n\n\n\n\n\n (97, 1)\n\n\n\n#Gradient descent\nAs you want to minimize a cost function, make sure you understand what you are trying to optimize and what is being updated. Keep in mind that the cost $J(\\theta)$ is parameterized by the vector $\\theta$, not $X$ and $y$. That is, we minimize the value of $J(\\theta)$ by changing the values of the matrix $\\theta$\n\n\n```python\ndef gradientdescent(X, y, theta, alpha, itera):\n \"\"\"Gradient to update weights theta. It returns theta and the cost function at each iteration step \"\"\"\n\n m = len(y) #number of training examples\n J_history = np.zeros((itera,1)) \n for i in range(itera):\n theta = theta - (alpha/m) * (X.T @ (np.dot(X,theta) - y )) #vectorized\n J_history[i] = cost_function(X, y, theta) #store J value after updating theta and repeat process\n\n #alternative: theta[0] = theta[0] - ...(np.sum(X@theta - y) * 1 ) #since x0 =1\n # theta[1] = theta[1] - ....(np.sum(X@theta - y).T @ X[:,1:])\n #note that: X[:,1:] is (97,1) and X[:,1] is (97,)\n #\n\n return theta, J_history\n\ntheta = np.zeros( (2,1) )\nalpha = 0.02\nitera = 1500 # TRY 3500 and see better value\n\ntheta, J_history = gradientdescent(X, y, theta, alpha, itera)\nprint(theta)\nz = pd.DataFrame(J_history, columns=['J values']) \nz.head()\n\n```\n\n [[-3.87813769]\n [ 1.19126119]]\n\n\n\n\n\n\n
\n
\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
J values
016.769642
110.407580
27.759183
36.653288
46.188106
\n
\n \n\n \n\n \n
\n
\n\n\n\n\n#Plotting results and making a prediction\n\nYour final values for θ will also be used to make predictions on profits in\nareas of 35,000 and 70,000 people.\n\n\n```python\npredict1 = np.array([1, 3.5]).dot(theta)*10000 #data is given in 10k people and 10k money\npredict2 = np.dot(np.array([1, 7]), theta)*10000 #same for 7 = 70k\nprint(predict1)\nprint(predict2)\n```\n\n [2912.76490368]\n [44606.90671602]\n\n\n\n```python\nplt.figure()\nplt.plot(X[:,1], y, 'rx', label='training' )\nplt.plot(X[:,1], np.dot(X,theta), label='prediction' )\nplt.xlabel('population in 10k')\nplt.ylabel('profit in $10k')\nplt.title('Result')\nplt.legend()\n#plt.show()\n```\n\n\n```python\n#The cost function against the number of iterations below\nplt.plot(J_history, label='cost')\nplt.xlabel('number of iterations')\nplt.ylabel('J($ \\theta $)')\nplt.title('Cost function decay')\nplt.legend()\n```\n\n\n```python\n#now contour plot (surface levels) and surface plot\n\ntheta0vals = np.linspace(-10,10,100)\ntheta1vals = np.linspace(-1,4,100)\n\nJ_values = np.zeros((len(theta0vals), len(theta1vals)))\n\nfor i in range(len(theta0vals)):\n for j in range(len(theta1vals)):\n #t = np.array([ [theta0vals[i]], [theta1vals[j]] ])\n t = [[theta0vals[i]],[theta1vals[j]]]\n J_values[i,j] = cost_function(X,y,t)\n\nJ_values.shape\n#J_values\n```\n\n\n\n\n (100, 100)\n\n\n\n\n```python\n# J_values.T (transpose) is required for the way contour plot works. why?\nscaling = np.logspace(-2,3,20)\nplt.contour(theta0vals, theta1vals, J_values.T, levels = np.logspace(np.log10(0.01),np.log10(1000), 20))\nplt.plot(theta[0], theta[1], 'r+')\nplt.title('A contour plot for bias theta')\n```\n\n\n```python\n#alternatively \n\nJ_matrix = np.array([np.array([cost_function(X,y, [[theta0vals[i]],[theta1vals[j]]]).reshape(1) \n for i in range(len(theta0vals))]).reshape(100) \n for j in range(len(theta1vals))])\n\n#now the matrix needs no transposing this time.. why?\nplt.contour(theta0vals, theta1vals, J_matrix, levels = np.logspace(np.log10(0.01),np.log10(1000), 20) )\nplt.show()\nprint(J_matrix.shape)\nJ_matrix\n```\n\n\n```python\n#Note the role of first and second components i,j in regard to row and colum\nA = [1,2,3,4]\nB= [1,2,3]\nM = np.array([[(a,b) for a in A] for b in B])\nprint(M.shape)\nM.tolist() #removes third dimension. 3 rows(b) and 4 columns(a)\n```\n\n (3, 4, 2)\n\n\n\n\n\n [[[1, 1], [2, 1], [3, 1], [4, 1]],\n [[1, 2], [2, 2], [3, 2], [4, 2]],\n [[1, 3], [2, 3], [3, 3], [4, 3]]]\n\n\n\n\n```python\n#Another way using numpy meshgrid\ntheta0vals = np.linspace(-10,10,100)\ntheta1vals = np.linspace(-1,4,100) \n\ndef f(theta0vals, theta1vals):\n \n Z = np.zeros((len(theta0vals), len(theta1vals)))\n\n for (i, value0) in enumerate(U):\n for (j, value1 ) in enumerate(V):\n t = [[value0[i]],[value1[j]]]\n Z[i,j] = 1/(2*m) * ((np.dot(X,t)) - y).T @ ( np.dot(X,t) - y)\n return Z.T\n#Take transpose as contour plot flips directions\n\nU, V = np.meshgrid(theta0vals, theta1vals)\n\nplt.contour(U,V, f(U,V), levels = np.logspace(np.log10(0.01),np.log10(1000), 20))\nplt.plot(theta[0], theta[1], 'r+')\nplt.title('A contour plot for bias theta')\nplt.show()\n\n```\n\n\n```python\n\n```\n\n#Basic Linear Algebra/Statistics\nFor one feature, the relation between the parameter and the intercept is straightforward and can be easily checked against the covariance matrix and mean values.\n\n\n```python\n#The linear relation, measured by correlation, between the the feature and the target is clear\n#in the following picture\nsns.heatmap(data.corr(), annot=True)\n```\n\n\n```python\ndata.cov()\n```\n\n\n\n\n\n
\n
\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
PopulationProfit
Population14.97599917.86687
Profit17.86687030.36299
\n
\n \n\n \n\n \n
\n
\n\n\n\n\n\n```python\ndata.Population.var()\n```\n\n\n\n\n 14.975998519375002\n\n\n\n\n```python\n#1 feature: theta1 = cov(x,y)/var(x)\nexpected_theta1 = 17.86687/ data.Population.var()\nexpected_theta1\n```\n\n\n\n\n 1.193033638250229\n\n\n\n\n```python\n#Thinking of vectors and subspaces, the first parameter is also given as\nfloat((X[:,1]-X[:,1].mean()).T @ y)/( (X[:,1]-X[:,1].mean()).T @ (X[:,1]-X[:,1].mean())) \n```\n\n\n\n\n 1.1930336441895941\n\n\n\n\n```python\ndata.mean()\n```\n\n\n\n\n Population 8.159800\n Profit 5.839135\n dtype: float64\n\n\n\n\n```python\n#1 feature: theta0 = mean(y) - theta1 * mean(x)\nexpected_theta0 = data.Profit.mean() - (17.86687/ data.Population.var())*(data.Population.mean())\nexpected_theta0\n\n```\n\n\n\n\n -3.8957808298478307\n\n\n\n\n```python\ndata.Population.std() * data.Profit.std()\n```\n\n\n\n\n 21.324073135832304\n\n\n\n\n```python\ndata.corr()*(data.Population.std() * data.Profit.std()) #covariance of x and y off-diagonal\n```\n\n\n\n\n\n
\n
\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
PopulationProfit
Population21.32407317.866870
Profit17.86687021.324073
\n
\n \n\n \n\n \n
\n
\n\n\n\n\n#Linear Regression with multiple variables\n\n\"In this part, you will implement linear regression with multiple variables to\npredict the prices of houses. Suppose you are selling your house and you\nwant to know what a good market price would be. One way to do this is to\nfirst collect information on recent houses sold and make a model of housing\nprices.\nThe file ex1data2.txt contains a training set of housing prices in Port-\nland, Oregon. The first column is the size of the house (in square feet), the\nsecond column is the number of bedrooms, and the third column is the price\nof the house.\" (extract from Stanford-ML-ex01- Andrew Ng)\n\n\n```python\npath = '/content/drive/MyDrive/Machine_Learning_DS/Material/ML_Standford/ex1-octave/ex1data2.txt'\ndata = pd.read_csv(path, header=None, names=['Size', 'Bedrooms', 'Price'])\n\nm = len(data['Price']) #number of training values\n\n#make sure to create a matrix \nfeatures = [ 'Size','Bedrooms']\n\nx = np.array( [ data['Size'], data['Bedrooms'] ] ) #capital X will be with x0s included...\ny = np.array(data['Price'])\n\nm = len(data)\n\ndata.head(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
SizeBedroomsPrice
021043399900
116003329900
224003369000
314162232000
430004539900
519854299900
615343314900
\n
\n \n\n \n\n \n
\n
\n\n\n\n\n\n```python\ndata.info()\n```\n\n \n RangeIndex: 47 entries, 0 to 46\n Data columns (total 3 columns):\n # Column Non-Null Count Dtype\n --- ------ -------------- -----\n 0 Size 47 non-null int64\n 1 Bedrooms 47 non-null int64\n 2 Price 47 non-null int64\n dtypes: int64(3)\n memory usage: 1.2 KB\n\n\n\n```python\ndata.describe() #5-point description\n```\n\n\n\n\n\n
\n
\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
SizeBedroomsPrice
count47.00000047.00000047.000000
mean2000.6808513.170213340412.659574
std794.7023540.760982125039.899586
min852.0000001.000000169900.000000
25%1432.0000003.000000249900.000000
50%1888.0000003.000000299900.000000
75%2269.0000004.000000384450.000000
max4478.0000005.000000699900.000000
\n
\n \n\n \n\n \n
\n
\n\n\n\n\n\n```python\n#The examples with 5 bedrooms are scarce and will not give much information\n#that is the same case for those with only 1 bedroom (check)\ndata[data['Bedrooms'] >=5 ]['Bedrooms'].count()\n```\n\n\n\n\n 1\n\n\n\n\n```python\n#The visible linear dependence of price and Size can be seen below\n#note the behaviour of examples with 3 and 4 bedrooms\nsns.pairplot(data, hue= 'Bedrooms' , diag_kind='kde')\n```\n\n\n```python\n#the data size has 2 features , 1 target and 47 examples\nprint(data.shape)\nprint(x.shape)\nprint(y.shape)\n```\n\n (47, 3)\n (2, 47)\n (47,)\n\n\n\n```python\n#but the shapes are not as we want at the moment\nx = x.T #transpose (ONCE!) to make examples along rows\n(m,n) = x.shape\nprint(m,n)\n```\n\n 47 2\n\n\n\n```python\nx[:5]\n```\n\n\n\n\n array([[2104, 3],\n [1600, 3],\n [2400, 3],\n [1416, 2],\n [3000, 4]])\n\n\n\n\n```python\n#Reshape such that we have column vectors and matrices\n#x was corrected with transpose but make sure all formates are fixed as follows\n\nx = x.reshape(m,n)\ny = y.reshape(m,1)\n\nprint(x.shape)\nprint(y.shape)\n```\n\n (47, 2)\n (47, 1)\n\n\n\n```python\nx[1]\n```\n\n\n\n\n array([1600, 3])\n\n\n\n\n```python\n#Look at this plot below. The orders of magnitude of Size are larger than \n#the orders of magnitude in Bedrooms. In fact, Sizes are of order 10^3 and Bedrooms only 10^0.\nfeatures = ['Size','Bedrooms']\ndata[features].plot()\n```\n\n\n```python\n\n```\n\n#Standard deviation and normalization\nBefore we normalize the features, note that Pandas standard deviation is different from Numpy std(). The reason is that Pandas will use the corrected version (Bessel's correction), where the mean value is a data estimation of the true mean value, while Numpy considers the uncorrected standard deviation. That is, Pandas assumes that the mean/expectation_value is calculated from a sample only. Numpy considers it is calculated from a population. These two concepts are different in statistics, because the sample is, generally, data coming from the population, a subset of all the data!\n\nSpecifically, let $N$ be the number of examples observed, these two quantities differ by\n\n$$ \\sigma_{\\textrm{sample}} = \\sqrt{ \\left( \\frac{1}{N-1} \\sum_{i=1}^{N} (x_i - \\bar{x})^2 \\right) },$$\n\n$$ \\sigma_{\\textrm{population}} = \\sqrt{ \\left( \\frac{1}{N} \\sum_{i=1}^{N} (x_i - \\mu)^2 \\right) },$$\nwhere we understand the true mean value as $\\mu$ and the mean value $\\bar{x}$ from the dataset (subset of a population) is a data estimation of the true mean. Note that $\\sigma_{\\textrm{sample}} \\geq \\sigma_{\\textrm{population}}$.\n\nIf we tell Numpy to use \"ddof=1\", it will be equivalent to the Pandas default, namely, the standard deviation of a sample. Conversely, we would set \"ddof=0\" in Pandas to calculate the population standard deviation.\n\nOn a different note, when we peform feature normalization, it is useful to store their values of mean() and std(), because we want to make prediction with unseen data and will need to normalize as well the unseen data.\nFinally, the normalization is given by $ x \\mapsto \\left(\\frac{x - \\mu }{\\sigma} \\right) $, such that the range of the features is defined in terms of how much it deviates from the standard deviation $\\sigma$. In the case of a Gaussian distribution, it is known ($68-95-99.7$ rule) that $95$% of the data lies within the range $(\\mu \\pm 2 \\sigma)$ and $99.7$% within three standard deviations of the mean $(\\mu \\pm 3 \\sigma)$. More generally, the Chebyshev's inequality stats that at least ($1 - \\frac{1}{k^2}) \\times 100$% of the data lies within $k$ standard deviations away from the mean. Hence, at least $75$% of the data is included in the range $\\mu \\pm 2 \\sigma$. These observations can be seen below after we have performed feature normlatization.\n\n\n\n\"Implementation Note: When normalizing the features, it is important\nto store the values used for normalization - the mean value and the stan-\ndard deviation used for the computations. After learning the parameters\nfrom the model, we often want to predict the prices of houses we have not\nseen before. Given a new x value (living room area and number of bed-\nrooms), we must first normalize x using the mean and standard deviation\nthat we had previously computed from the training set.\" (Stanford-ML-ex01- Andrew Ng)\n\n\n```python\nprint( data['Size'].std(), data['Bedrooms'].std())\n#slightly different \nprint(np.std(x, axis=0))\n\n```\n\n 794.7023535338897 0.7609818867800999\n [7.86202619e+02 7.52842809e-01]\n\n\n\n```python\n#More than a matter of visualization, which is important for interpretation,\n#so distinct numbers will not be helpful in the process of convergence required\n#in optimization problems. The so called 'feature normalization' is a way to deal with this problem.\n#Basically, we will normalize the features using mean (expectation value) and standard deviation\n\ndef featureNormalize(x):\n \"\"\"Given the features x, return the features normalized, mean and standard deviation, respectively. \"\"\"\n x_norm = x\n\n mu = np.mean(x, axis=0) #take elements along rows of same column (mean value of each column)\n sigma = x.std(axis=0, ddof=1)\n\n#numpy broadcasting will make it easier to vectorize the code\n x_norm = (x - mu )/sigma #divide is also broadcasted operation\n\n\n return x_norm, mu, sigma\n\n\n\n```\n\n\n```python\nx_norma, mu, sigma = featureNormalize(x) #\n\nx_norma[:3]\n```\n\n\n\n\n array([[ 0.13000987, -0.22367519],\n [-0.50418984, -0.22367519],\n [ 0.50247636, -0.22367519]])\n\n\n\n\n```python\nprint('expectation values are: ', mu)\nprint('standard deviations are: ', sigma)\n```\n\n expectation values are: [2000.68085106 3.17021277]\n standard deviations are: [7.94702354e+02 7.60981887e-01]\n\n\nGradient descent is calculated again \n\n\n```python\n#Now that the features are normalized, we can include the bias by means of considering the extended X \n#with a column of 1's for x0\n\nX = np.append(np.ones((m,1)), x_norma, axis=1 )\nX[:3]\n```\n\n\n\n\n array([[ 1. , 0.13000987, -0.22367519],\n [ 1. , -0.50418984, -0.22367519],\n [ 1. , 0.50247636, -0.22367519]])\n\n\n\n\n```python\nX.shape\n```\n\n\n\n\n (47, 3)\n\n\n\n\n```python\ndef gradientdescentMulti(X, y, theta, alpha, itera):\n \"\"\"Gradient to update weights theta. It returns the thetas and the cost function at each iteration step \"\"\"\n\n m = len(y) #number of training examples\n J_history = np.zeros((itera,1)) \n for i in range(itera):\n theta = theta - (alpha/m) * (X.T @ (np.dot(X,theta) - y )) #vectorized\n J_history[i] = cost_function(X, y, theta) #store J value after updating theta and repeat process\n\n\n return theta, J_history\n\ntheta = np.zeros( (3,1) )\nalpha = 0.01\nitera = 2000 #try 3000 for better value\n\ntheta, J_history = gradientdescentMulti(X, y, theta, alpha, itera)\n\nprint(theta)\nz = pd.DataFrame(J_history, columns=['J values']) \nz.head()\n```\n\n [[340412.65894002]\n [110620.59436465]\n [ -6639.01835663]]\n\n\n\n\n\n\n
\n
\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
J values
06.430075e+10
16.303679e+10
26.179911e+10
36.058714e+10
45.940033e+10
\n
\n \n\n \n\n \n
\n
\n\n\n\n\n\n```python\n#The cost function against the number of iterations below\n#note the quick convergence for about from 0 to 200 iterations\nplt.plot(J_history, label='cost')\nplt.xlabel('number of iterations')\nplt.ylabel('J(theta)')\nplt.title('Cost function decay')\nplt.legend()\n```\n\nAs before, we are in a position to make predictions. What is the\nestimated price of a 1650 ft^2 house with 3 bedrooms ?\n\n\n```python\n#As we normalized the features when fitting the model, we also need to \n#normalize the features used for any prediction.\nX_test = np.array([1, 1650, 3 ])\n\n\nX_test_norma = np.array([1, (X_test[1] -mu[0])/sigma[0] , (X_test[2] - mu[1])/sigma[1] ])\n\n\nprice = np.dot(X_test_norma.T, theta)\n\nprint('The estimated price of a House with 1650 ft^2 and 3 bedrooms is: ' + str(price[0]) + '$')\n```\n\n The estimated price of a House with 1650 ft^2 and 3 bedrooms is: 293083.73888660746$\n\n\n#Exact solution (Normal equation)\nFor linear regression, an exact solution to the problem of finding the minimum of the cost function can be found and it is called the normal equation.\nAs it involves the calculation of inverse matrices, the computational cost of the process grows with $\\mathcal{O}(n^3)$, where $n$ is the number of examples.\nThat means the use of the normal equation shall be restricted to situations where the dataset is not very large, up to $10^3$ number of examples.\nThe solution is obtained by setting $\\frac{\\partial J}{\\partial \\theta} = 0$, as the quadratic function $J$ is convex and will have a global minimum rather than a maximum, which results in \n\\begin{equation}\n\\theta = \\left( X^t X \\right)^{-1} X^t y,\n\\end{equation}\nwhich indeed is a $(n+1) \\times 1$ matrix.\nNote there is no need for using the learning rate $\\alpha$ or iterative steps. The learning rate is a consequence of using approximations to a numerical problem and it is absent in the case of exact solutions.\n\n\n```python\ntheta_min = np.linalg.inv(X.T @ X) @ X.T @ y\n\nprint(f'The weights that solve the problem exactly are \\n {theta_min.flatten()}')\n```\n\n The weights that solve the problem exactly are \n [340412.65957447 110631.05027885 -6649.47427082]\n\n\n#Comparison with Scikit-learn\n\n\n\n```python\n#If we use our initial x without normalization \nfrom sklearn.linear_model import LinearRegression\n\nlr = LinearRegression(fit_intercept=True)\nlr.fit(x, y)\n```\n\n\n\n\n LinearRegression()\n\n\n\n\n```python\nx_test = np.array([[1650, 3]])\nprice_predicted = lr.predict(x_test)\nprice_predicted\n\n#the prediction agress with what we found before\n```\n\n\n\n\n array([[293081.4643349]])\n\n\n\n\n```python\n#But the values of the weights and bias are not the same. that is expected! \nprint('weights are: ',lr.coef_)\nprint('intercept is: ',lr.intercept_)\n```\n\n weights are: [[ 139.21067402 -8738.01911233]]\n intercept is: [89597.9095428]\n\n\n\n```python\n#Now, if we use our normalized features x_norma (before adding the bias)\nlr2 = LinearRegression(fit_intercept=True)\nlr2.fit(x_norma, y)\n\nprint('weights are: ',lr2.coef_)\nprint('intercept is: ',lr2.intercept_)\n\n#same weights and bias we found before\n```\n\n weights are: [[110631.05027885 -6649.47427082]]\n intercept is: [340412.65957447]\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "ee81243aeba556b107d7dd239ebf6459a123ddca", "size": 400927, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Linear Regression/Linear_Regression_model.ipynb", "max_stars_repo_name": "Alexandre-Hefren/Machine-Learning-models", "max_stars_repo_head_hexsha": "588eaaf475ef0c78104861ae42cb78889782ba55", "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": "Linear Regression/Linear_Regression_model.ipynb", "max_issues_repo_name": "Alexandre-Hefren/Machine-Learning-models", "max_issues_repo_head_hexsha": "588eaaf475ef0c78104861ae42cb78889782ba55", "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": "Linear Regression/Linear_Regression_model.ipynb", "max_forks_repo_name": "Alexandre-Hefren/Machine-Learning-models", "max_forks_repo_head_hexsha": "588eaaf475ef0c78104861ae42cb78889782ba55", "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": 133.9101536406, "max_line_length": 52321, "alphanum_fraction": 0.8172585034, "converted": true, "num_tokens": 14866, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067260443809, "lm_q2_score": 0.9124361586911174, "lm_q1q2_score": 0.8599772166524763}} {"text": "# How\n\n## How to create a symbolic numeric value\n\nTo create a symbolic numerical value use `sympy.S`.\n\n````{tip}\n```\nsympy.S(a)\n```\n````\n\nFor example:\n\n\n```python\nimport sympy\n\nvalue = sympy.S(3)\nvalue\n```\n\n\n\n\n$\\displaystyle 3$\n\n\n\n```{attention}\nIf we combine a symbolic value with a non symbolic value it will automatically\ngive a symbolic value:\n```\n\n\n```python\n1 / value\n```\n\n\n\n\n$\\displaystyle \\frac{1}{3}$\n\n\n\n## How to get the numerical value of a symbolic expression\n\nWe can get the numerical value of a symbolic value using `float` or `int`:\n\n- `float` will give the numeric approximation in \\\\(\\mathbb{R}\\\\)\n ````{tip}\n ```\n float(x)\n ```\n ````\n- `int` will give the integer value\n ````{tip}\n ```\n int(x)\n ```\n ````\n\nFor example, let us create a symbolic numeric variable with value\n\\\\(\\frac{1}{5}\\\\):\n\n\n```python\nvalue = 1 / sympy.S(5)\nvalue\n```\n\n\n\n\n$\\displaystyle \\frac{1}{5}$\n\n\n\nTo get the numerical value:\n\n\n```python\nfloat(value)\n```\n\n\n\n\n 0.2\n\n\n\nIf we wanted the integer value:\n\n\n```python\nint(value)\n```\n\n\n\n\n 0\n\n\n\n```{attention}\nThis is not rounding to the nearest integer. It is returning the integer part.\n```\n\n## How to factor an expression\n\nWe use the `sympy.factor` tool to factor expressions.\n\n````{tip}\n```\nsympy.factor(expression)\n```\n````\n\nFor example:\n\n\n```python\nx = sympy.Symbol(\"x\")\nsympy.factor(x ** 2 - 9)\n```\n\n\n\n\n$\\displaystyle \\left(x - 3\\right) \\left(x + 3\\right)$\n\n\n\n## How to expand an expression\n\nWe use the `sympy.expand` tool to expand expressions.\n\n````{tip}\n```\nsympy.expand(expression)\n```\n````\n\nFor example:\n\n\n```python\nsympy.expand((x - 3) * (x + 3))\n```\n\n\n\n\n$\\displaystyle x^{2} - 9$\n\n\n\n## How to simplify an expression\n\nWe use the `sympy.simplify` tool to simplify an expression.\n\n````{tip}\n```\nsympy.simplify(expression)\n```\n````\n\nFor example:\n\n\n```python\nsympy.simplify((x - 3) * (x + 3))\n```\n\n\n\n\n$\\displaystyle x^{2} - 9$\n\n\n\n```{attention}\nThis will not always give the expected (or any) result. At times it could be\nmore beneficial to use `sympy.expand` and/or `sympy.factor`.\n```\n\n## How to solve an equation\n\nWe use the `sympy.solveset` tool to solve an equation. It takes two values as\ninputs. The first is either:\n\n- An expression for which a root is to be found\n- An equation\n\nThe second is the variable we want to solve for.\n\n````{tip}\n```\nsympy.solveset(equation, variable)\n```\n````\n\nHere is how we can use `sympy` to obtain the roots of the general quadratic:\n\n\\\\[\na x ^ 2 + bx + c\n\\\\]\n\n\n```python\na = sympy.Symbol(\"a\")\nb = sympy.Symbol(\"b\")\nc = sympy.Symbol(\"c\")\nquadratic = a * x ** 2 + b * x + c\nsympy.solveset(quadratic, x)\n```\n\n\n\n\n$\\displaystyle \\left\\{- \\frac{b}{2 a} - \\frac{\\sqrt{- 4 a c + b^{2}}}{2 a}, - \\frac{b}{2 a} + \\frac{\\sqrt{- 4 a c + b^{2}}}{2 a}\\right\\}$\n\n\n\nHere is how we would solve the same equation but not for \\\\(x\\\\) but for\n\\\\(b\\\\):\n\n\n```python\nsympy.solveset(quadratic, b)\n```\n\n\n\n\n$\\displaystyle \\left\\{- \\frac{a x^{2} + c}{x}\\right\\}$\n\n\n\nIt is however clearer to specifically write the equation that we want to solve:\n\n\n```python\nequation = sympy.Eq(a * x ** 2 + b * x + c, 0)\nsympy.solveset(equation, x)\n```\n\n\n\n\n$\\displaystyle \\left\\{- \\frac{b}{2 a} - \\frac{\\sqrt{- 4 a c + b^{2}}}{2 a}, - \\frac{b}{2 a} + \\frac{\\sqrt{- 4 a c + b^{2}}}{2 a}\\right\\}$\n\n\n\n## How to substitute a value in to an expression\n\nGiven a `sympy` expression it is possible to substitute values in to it using\nthe `.subs()` tool.\n\n````{tip}\n```\nexpression.subs({variable: value})\n```\n````\n\n```{attention}\nIt is possible to pass multiple variables at a time.\n```\n\nFor example we can substitute the values for \\\\(a, b, c\\\\) in to our quadratic:\n\n\n```python\nquadratic = a * x ** 2 + b * x + c\nquadratic.subs({a: 1, b: sympy.S(7) / 8, c: 0})\n```\n\n\n\n\n$\\displaystyle x^{2} + \\frac{7 x}{8}$\n\n\n", "meta": {"hexsha": "8b2f76668c14164a7b1fe35f4cc8679ef917196c", "size": 10167, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "book/tools-for-mathematics/02-algebra/how/.main.md.bcp.ipynb", "max_stars_repo_name": "11michalis11/pfm", "max_stars_repo_head_hexsha": "c91b1eda70d7cde3fbe065db4667f84853947850", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2020-09-24T21:02:41.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-14T08:37:21.000Z", "max_issues_repo_path": "book/tools-for-mathematics/02-algebra/how/.main.md.bcp.ipynb", "max_issues_repo_name": "11michalis11/pfm", "max_issues_repo_head_hexsha": "c91b1eda70d7cde3fbe065db4667f84853947850", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 87, "max_issues_repo_issues_event_min_datetime": "2020-09-21T15:54:23.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-19T23:26:15.000Z", "max_forks_repo_path": "book/tools-for-mathematics/02-algebra/how/.main.md.bcp.ipynb", "max_forks_repo_name": "11michalis11/pfm", "max_forks_repo_head_hexsha": "c91b1eda70d7cde3fbe065db4667f84853947850", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-10-02T09:21:27.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-08T14:46:27.000Z", "avg_line_length": 20.2529880478, "max_line_length": 157, "alphanum_fraction": 0.4463460214, "converted": true, "num_tokens": 1204, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404096760996, "lm_q2_score": 0.9252299539994747, "lm_q1q2_score": 0.8599461074898707}} {"text": "# 微积分\n\nSymPy支持微分和积分操作,也支持推导极限\n\n\n```python\nfrom sympy import init_printing\ninit_printing(use_unicode=True)\n```\n\n\n```python\nfrom sympy import symbols\nx, y, z = symbols('x y z')\n```\n\n## `diff()`微分(求导)\n\n\n```python\nfrom sympy import diff\n```\n\n\n```python\ndiff(x**3+x**2+x+1)\n```\n\n`diff(exp,var,level)`可以求多阶导数,需要指定变量和阶数\n\n\n```python\ndiff(x**3+x**2+x+1,x,2)\n```\n\n同样的,也可以求偏导\n\n\n```python\ndiff(x**3+x*y**2+x*y+1,x)\n```\n\n要创建未化简的的导数,需要使用导数类.它具有与diff相同的语法,但必须显式的指定是谁的微分\n\n\n```python\nfrom sympy import Derivative\n```\n\n\n```python\nexp = diff(x**3+x**2+x+1)\nexp\n```\n\n\n```python\nDerivative(exp,x)\n```\n\n要推导导数类的实例,可以使用算式的`doit()`方法\n\n\n```python\nDerivative(exp,x).doit()\n```\n\n## `integrate(exp,var)`积分\n\n\n```python\nfrom sympy import integrate\nfrom sympy import cos\n```\n\n### 不定积分\n\n\n```python\nexp = cos(x)\nexp\n```\n\n\n```python\nintegrate(exp, x)\n```\n\n### 定积分\n\n定积分一般会有上下限,可以用元组(integration_variable, lower_limit, upper_limit)替换var,sympy.注意`oo`表示无穷大\n\n\n```python\nfrom sympy import oo,exp\n```\n\n$ \\int _0^\\infty e^{-x} dx$\n\n\n```python\nintegrate(exp(-x), (x, 0, oo))\n```\n\n### 重积分\n\n比如我们想求如下这个二重积分\n\n$\\int _{-\\infty}^\\infty \\int _{-\\infty}^\\infty e^{-x^2-y^2} dx dy$\n\n\n```python\nintegrate(exp(-x**2 - y**2), (x, -oo, oo), (y, -oo, oo))\n```\n\n如果积分无法求得,那么它会返回原来的样子\n\n\n```python\nexpr = integrate(x**x, x)\nexpr\n```\n\n就像微分一样,积分也有对应的类型Integral,定义方式也相似\n\n\n```python\nfrom sympy import Integral,log\n```\n\n\n```python\nexpr = Integral(log(x)**2, x)\nexpr \n```\n\n\n```python\nexpr.doit()\n```\n\n## 极限\n\nSymPy可以使用limit函数计算极限。\n\n\n```python\nfrom sympy import limit,sin\n```\n\n\n```python\nlimit(sin(x)/x, x, 0)\n```\n\n\n```python\nexpr = x**2/exp(x)\nexpr.subs(x, oo)\n```\n\n\n\n\n$\\displaystyle \\text{NaN}$\n\n\n\n\n```python\nlimit(expr, x, oo)\n```\n\n极限也有一个类,也和上面的微分积分差不多\n\n\n```python\nfrom sympy import Limit\n```\n\n\n```python\nexpr = Limit((cos(x) - 1)/x, x, 0)\nexpr\n```\n\n\n```python\nexpr.doit()\n```\n\n## 泰勒展开\n\n泰勒公式是一个用函数在某点的信息描述其附近取值的公式.如果函数足够平滑的话,在已知函数在某一点的各阶导数值的情况之下,泰勒公式可以用这些导数值做系数构建一个多项式来近似函数在这一点的邻域中的值.泰勒公式还给出了这个多项式和实际的函数值之间的偏差.\n\nSymPy可以计算围绕一个点的函数做泰勒级数展开.它使用算式的`.series(x, x0, n)`方法,就像之前在验证欧拉公式时我们做的那样\n\n\n```python\nexpr = exp(sin(x))\nexpr\n```\n\n\n```python\nexpr.series(x, 0, 4)\n```\n\n\n```python\nfrom sympy import symbols\nx0 = symbols(\"x0\")\n```\n\n\n```python\nexpr.series(x, x0, 4)\n```\n\n## 有限差分\n\n到目前为止我们分别用分析导数和原始函数来研究表达式.\n但是如果我们想要一个表达式来估计曲线的导数,如果我们缺少一个闭合形式表示,或者我们还不知道函数值那又怎么办呢?\n一种方法是使用有限差分法.\n\nSymPy中提供了接口`as_finite_difference()`可以在任何微分实例上来生成任意阶导数的近似:\n\n\n```python\nfrom sympy import Function,finite_diff_weights,apply_finite_diff\n```\n\n\n```python\nf = Function('f')\ndfdx = Derivative(f(x))#.diff(x)\ndfdx\n```\n\n\n```python\ndfdx.as_finite_difference()\n```\n\n这里我们使用步长为1,等距离估计的最小点数来近似函数对x的一阶导数.我们可以使用任意的步长\n\n\n```python\nf = Function('f')\nd2fdx2 = Derivative(f(x),x, 2)\nd2fdx2\n```\n\n\n```python\nh = symbols('h')\nd2fdx2.as_finite_difference([-3*h,-h,2*h])\n```\n\n如果要评估权重,你可以手动计算\n\n\n```python\nfinite_diff_weights(2, [-3, -1, 2], 0)[-1][-1]\n```\n\n注意,我们只需要从`finite_diff_weights`返回的最后一个子列表中取最后一个元素.这样做的原因是`finite_diff_weights`产生较低阶导数的权重,并使用较少的点.\n\n如果使用`finite_diff_weights`直接看起来很复杂,并且觉得Derivative实例操作的`as_finite_difference`函数不够灵活,则可以使用`apply_finite_diff`,它接受order,x_list,y_list和x0作为参数\n\n\n```python\nx_list = [-3, 1, 2]\ny_list = symbols('a b c')\napply_finite_diff(1, x_list, y_list, 0)\n```\n", "meta": {"hexsha": "1d044a2a5206fcae0ba2dda264bab9c77c7e9ab8", "size": 61142, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "src/数据分析篇/工具介绍/SymPy/符号计算/.ipynb_checkpoints/微积分-checkpoint.ipynb", "max_stars_repo_name": "hsz1273327/TutorialForDataScience", "max_stars_repo_head_hexsha": "1d8e72c033a264297e80f43612cd44765365b09e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/数据分析篇/工具介绍/SymPy/符号计算/.ipynb_checkpoints/微积分-checkpoint.ipynb", "max_issues_repo_name": "hsz1273327/TutorialForDataScience", "max_issues_repo_head_hexsha": "1d8e72c033a264297e80f43612cd44765365b09e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2020-03-31T03:36:05.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-31T03:36:21.000Z", "max_forks_repo_path": "src/数据分析篇/工具介绍/SymPy/符号计算/.ipynb_checkpoints/微积分-checkpoint.ipynb", "max_forks_repo_name": "hsz1273327/TutorialForDataScience", "max_forks_repo_head_hexsha": "1d8e72c033a264297e80f43612cd44765365b09e", "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": 61.0809190809, "max_line_length": 8060, "alphanum_fraction": 0.7871021556, "converted": true, "num_tokens": 1597, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9658995718336469, "lm_q2_score": 0.8902942217558213, "lm_q1q2_score": 0.8599348075999177}} {"text": "## Fourier methods\n\nThe Fourier transform (FT) for a well-behaved functions $f$ is defined as:\n\n$$f(k) = \\int e^{-ikx} f(x) ~dx$$\n\nThe inverse FT is then \n\n$$f(x) = \\frac{1}{2\\pi} \\int e^{ikx} f(k) ~dk$$\n\n\n\n## Discrete Fourier transforms (DFTs)\n\n\nIf the function is periodic in real space, $f(x+L) = f(x)$, then the Fourier space is discrete with spacing $\\frac{2\\pi}{L}$. Moreover, if the real space is periodic as well as discrete with the spacing $h$, then the Fourier space is discrete as well as bounded. \n\n$$f(x) = \\sum e^{ikx} f(k) ~dk~~~~~~ \\text{where } k = \\Bigg[ -\\frac{\\pi}{h}, \\frac{\\pi}{h}\\Bigg];~~ \\text{with interval} \\frac{2\\pi}{L} $$\n\n\nThis is very much in line with crystallography with $ [ -\\frac{\\pi}{h}, \\frac{\\pi}{h} ]$ being the first Brillouin zone. So we see that there is a concept of the maximum wavenumber $ k_{max}=\\frac{\\pi}{h} $, we will get back to this later in the notes. Usually in computations we need to find FT of discrete function rather than of a well defined analytic function. Since the real space is discrete and periodic, the Fourier space is also discrete and periodic or bounded. Also, the Fourier space is continuous if the real space is unbounded. If the function is defined at $N$ points in real space and one wants to calculate the function at $N$ points in Fourier space, then **DFT** is defined as \n\n$$f_k = \\sum_{n=0}^{N-1} f_n ~ e^{-i\\frac{2\\pi~n~k}{N}}$$\n\nwhile the inverse transform of this is\n\n$$f_n = \\frac1N \\sum_{n=0}^{N-1} f_k ~ e^{~i\\frac{2\\pi~n~k}{N}}$$\n\nTo calculate each $f_n$ one needs $N$ computations and it has to be done $N$ times, i.e, the algorithm is simply $\\mathcal{O}(N^2)$. This can be implemented numerically as a matrix multiplication, $f_k = M\\cdot f_n$, where $M$ is a $N\\times N$ matrix.\n\n\n## Fast fourier tranforms (FFTs)\n\nThe discussion here is based on the Cooley-Tukey algorithm. FFTs improves on DFTs by exploiting their symmetries.\n\n$$ \\begin{align}\nf_k &= \\sum_{n=0}^{N-1} f_n e^{-i~\\frac{2\\pi~k~n}{N}} \\\\\n&= \\sum_{n=0}^{N/2-1} f_{2n} e^{-i~\\frac{2\\pi~k~2n}{N}} &+ \\sum_{n=0}^{N/2-1} f_{2n + 1} e^{-i~\\frac{2\\pi~k~(n+1)}{N}}\\\\\n&= \\sum_{n=0}^{N/2 - 1} f_{2n} e^{-i~\\frac{2\\pi k~n}{N/2}} &+ e^{-i\\frac{2\\pi k}{N}} \\sum_{n=0}^{N/2 - 1} f_{2n + 1} e^{-i~\\frac{2\\pi~k~n~}{N/2}}\\\\\n&=\\vdots &\\vdots\n\\end{align}$$\n\nWe can use the symmetry property, from the definition, $f_{N+k} = f_k$. Notice that, because of the tree structure, there are $\\ln_2 N$ stages of the calculation. By applying the method of splitting the computation in two halves recursively, the complexity of the problem becomes $\\mathcal{O}(N \\ln N)$ while the naive algorithm is $\\mathcal{O}(N^2)$. Below we will look at a simple implementation of FFT. \n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\n```\n\n\n```python\ndef testFFT(x):\n ''' FFT in 1d '''\n N = x.shape[0]\n if N % 2 > 0:\n raise Exception('x must have even size')\n elif N <= 16: \n ''' this is the naive implementation using matrix multiplication'''\n n = np.arange(N)\n k = n.reshape((N, 1))\n M = np.exp(-2j * np.pi * k * n / N)\n return np.dot(M, x)\n else:\n M1 = testFFT(x[::2])\n M2 = testFFT(x[1::2])\n fac = np.exp(-2j*np.pi*np.arange(N)/N)\n return np.concatenate([M1+fac[:N/2]*M2, M1+fac[N/2:]*M2])\n```\n\n\n```python\nx = np.random.random(1024)\n#np.allclose(np.fft.fftn(x), testFFT(x))\n```\n\n\n```python\n# TRANSLATION by e^{ikr}!\nL, N = 64, 128 \nll = np.linspace(0, L, N) \nx, y = np.meshgrid(ll, ll)\n\n# Fourier grid.\nkx = 2 * np.pi / L * np.concatenate((np.arange(0, N/2+1,1),np.arange(-N/2+1, 0, 1))) # k = (2\\pi)/L\nky = 2 * np.pi / L * np.concatenate((np.arange(0, N/2+1,1),np.arange(-N/2+1, 0, 1)))\nkx, ky = np.meshgrid(kx, ky) \n\ndef plotFirst(x, y, sig, n_):\n sp = f.add_subplot(1, 3, n_ )\n plt.pcolormesh(x, y, np.real(sig), cmap=plt.cm.gist_heat_r)\n plt.axis('off');\n \nf = plt.figure(figsize=(20, 5), dpi=80); \nrr = np.sqrt( (x - L/2)*(x - L/2) + (y - L/2)*(y - L/2) )\nsig = np.fft.fftn(np.exp(-0.1*rr))\n\nxx = ([-L/4, L/2, -L/2,])\nyy = ([-L/8, -L/9, L/2])\nfor i in range(3):\n kdotr = kx*xx[i] + ky *yy[i]\n sig = sig*np.exp(-1j*kdotr)\n plotFirst(x, y, np.fft.ifftn(sig), i+1)\n```\n\n## More examples\n### Sampling: Aliasing error\n\nWe saw that because of the smallest length scale, $h$, in the real space there is a corresponding largest wave-vector, $k_{max}$ in the Fourier space. The error is because of this $k_{max}$ and a signal which has $k>k_{max}$ can not be distinguished on this grid. In the given example, below, we see that if the real space has 10 points that one can not distinguish between $sin(2\\pi x/L)$ and $sin(34 \\pi x/L)$. In general, $sin(k_1 x)$ and $sin(k_2 x)$ can not be distinguished if $k_1 -k_2$ is a multiple of $\\frac{2\\pi}{h}$. This is a manifestation of the gem called the sampling theorem which is defined, as on wikipedia:\n\nIf a function x(t) contains no frequencies higher than B hertz, it is completely determined by giving its ordinates at a series of points spaced 1/(2B) seconds apart.\n\n\n```python\nL, N = 1, 16\nx = np.arange(0, L, L/512)\nxx = np.arange(0, L, L/N)\n\ndef ff(k, x):\n return sin(k*x)\n```\n\n\n```python\nf = plt.figure(figsize=(17, 6), dpi=80); pi=np.pi; sin=np.sin; cos=np.cos\n\nplt.plot(x, ff(x, 2*pi), color=\"#A60628\", linewidth=2);\nplt.plot(x, ff(x, 34*pi), color=\"#348ABD\", linewidth=2);\nplt.plot(xx, ff(xx, 2*pi), 'o', color=\"#020e3e\", markersize=8)\nplt.xlabel('x', fontsize=15); plt.ylabel('y(x)', fontsize=15);\nplt.title('Aliasing in sampling of $sin(2\\pi x/L)$ and $sin(34 \\pi x/L)$', fontsize=15);\n```\n\n ### Differentiation\n \n In this section we will use the in-built FFT modules of numpy and then perform differentiation. Differentiation in Fourier space is trivial, $\\mathbf{\\nabla}_{\\alpha}$ gets replaced by $ik_{\\alpha}$. Steps involved are\n \n* FFT the function to be differentiated.\n* multiply by suitable numbers of $ik$\n* IFFT on the resulting thing to get the differentiated function in real space.\n\n\n```python\ndef f1(kk, x):\n return cos(kk*x)\n\n```\n\n\n```python\nf = plt.figure(figsize=(10, 5), dpi=80); \n\nL, N = 1, 32\nkk = 2*pi/L\nx = np.arange(0, N)*(L/N) \nk = np.concatenate(( np.arange(0, N/2+1,1), np.arange(-N/2+1, 0, 1) ))*(2*pi/L)\n\nfk = np.fft.fft(f1(kk, x)) \nf1_kk = -k*k*fk \nf1_xx = np.fft.ifft(f1_kk)\n\n \nplt.plot(x, -f1(kk, x)*kk*kk, color=\"#348ABD\", label = 'analytical', linewidth=2) \nplt.plot(x, f1_xx, 'o', color=\"#A60628\", label = 'numerical', markersize=6) \nplt.legend(loc = 'best')\nplt.xlabel('x', fontsize=15)\nplt.title('derivatives using FFT', fontsize=15)\nplt.xlim([0, max(x)]);\n```\n\nThere are additional symmetry properties for a real function. Wavenumbers corresponding to $j$ and $N-j$ are same and hence we only need to consider wavenumber till N/2!\n\n\n```python\n# since we know that function is real, then we could save some time and memory by using real FFTs.\nf = plt.figure(figsize=(10, 5), dpi=80); \n\nL, N = 1, 64 \nx = np.arange(0, L, L/N) \nkk = 4*pi/L\nk = np.arange(0, N/2 + 1)*(2*pi/L)\n\n# k[2] = 0 # all the pattern is dead at a particular k mode which coooresponds to the signal!!\n\nfk = np.fft.rfft(f1(kk, x)) \nfk = -k*k*fk \nfx = np.fft.irfft(fk)\n\nplt.plot(x, -kk*kk*f1(kk, x), color=\"#348ABD\", label = 'analytical', linewidth=2) \nplt.plot(x, fx, 'o', color=\"#A60628\", label = 'numerical') \nplt.legend(loc = 'best')\nplt.xlabel('x', fontsize=15)\nplt.title('derivatives using FFT', fontsize=15)\nplt.xlim([0, max(x)]);\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "b1d7d5ef1b8d44a2d71db4698ec5f2e5eab63dcc", "size": 241446, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/2014/FourierSeries.ipynb", "max_stars_repo_name": "lzfpljdmt-lzy/compPhy", "max_stars_repo_head_hexsha": "5266fa439adbda8ed6ed13e532cb82ee0eefb18e", "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/2014/FourierSeries.ipynb", "max_issues_repo_name": "lzfpljdmt-lzy/compPhy", "max_issues_repo_head_hexsha": "5266fa439adbda8ed6ed13e532cb82ee0eefb18e", "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/2014/FourierSeries.ipynb", "max_forks_repo_name": "lzfpljdmt-lzy/compPhy", "max_forks_repo_head_hexsha": "5266fa439adbda8ed6ed13e532cb82ee0eefb18e", "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": 685.9261363636, "max_line_length": 118636, "alphanum_fraction": 0.9452962567, "converted": true, "num_tokens": 2592, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122714836208, "lm_q2_score": 0.897695292107347, "lm_q1q2_score": 0.8599133363627013}} {"text": "# Predefined Metrics in Symbolic Module\n\n### Importing some of the predefined tensors. All the metrics are comprehensively listed in EinsteinPy documentation.\n\n\n```python\nfrom einsteinpy.symbolic.predefined import Schwarzschild, DeSitter, AntiDeSitter, Minkowski, find\nfrom einsteinpy.symbolic import RicciTensor, RicciScalar\nimport sympy\nfrom sympy import simplify\n\nsympy.init_printing() # for pretty printing\n```\n\n### Printing the metrics for visualization\nAll the functions return instances of :py:class:`~einsteinpy.symbolic.metric.MetricTensor`\n\n\n```python\nsch = Schwarzschild()\nsch.tensor()\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}1 - \\frac{r_{s}}{r} & 0 & 0 & 0\\\\0 & - \\frac{1}{c^{2} \\left(1 - \\frac{r_{s}}{r}\\right)} & 0 & 0\\\\0 & 0 & - \\frac{r^{2}}{c^{2}} & 0\\\\0 & 0 & 0 & - \\frac{r^{2} \\sin^{2}{\\left(\\theta \\right)}}{c^{2}}\\end{matrix}\\right]$\n\n\n\n\n```python\nMinkowski(c=1).tensor()\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}-1 & 0 & 0 & 0\\\\0 & 1.0 & 0 & 0\\\\0 & 0 & 1.0 & 0\\\\0 & 0 & 0 & 1.0\\end{matrix}\\right]$\n\n\n\n\n```python\nDeSitter().tensor()\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}-1 & 0 & 0 & 0\\\\0 & e^{\\frac{2 x}{\\alpha}} & 0 & 0\\\\0 & 0 & e^{\\frac{2 x}{\\alpha}} & 0\\\\0 & 0 & 0 & e^{\\frac{2 x}{\\alpha}}\\end{matrix}\\right]$\n\n\n\n\n```python\nAntiDeSitter().tensor()\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}-1 & 0 & 0 & 0\\\\0 & \\cos^{2}{\\left(t \\right)} & 0 & 0\\\\0 & 0 & \\cos^{2}{\\left(t \\right)} \\sinh^{2}{\\left(\\chi \\right)} & 0\\\\0 & 0 & 0 & \\sin^{2}{\\left(\\theta \\right)} \\cos^{2}{\\left(t \\right)} \\sinh^{2}{\\left(\\chi \\right)}\\end{matrix}\\right]$\n\n\n\n### Calculating the scalar (Ricci) curavtures\nThey should be constant for De-Sitter and Anti-De-Sitter spacetimes.\n\n\n```python\nscalar_curvature_de_sitter = RicciScalar.from_metric(DeSitter())\nscalar_curvature_anti_de_sitter = RicciScalar.from_metric(AntiDeSitter())\n```\n\n\n```python\nscalar_curvature_de_sitter.expr\n```\n\n\n```python\nscalar_curvature_anti_de_sitter.expr\n```\n\nOn simplifying the expression we got above, we indeed obtain a constant\n\n\n```python\nsimplify(scalar_curvature_anti_de_sitter.expr)\n```\n\n### Searching for a predefined metric\nfind function returns a list of available functions\n\n\n```python\nfind(\"sitter\")\n```\n\n\n\n\n ['AntiDeSitter', 'AntiDeSitterStatic', 'DeSitter']\n\n\n", "meta": {"hexsha": "76322c699f322c567d78f4eb38a105aac919d506", "size": 18165, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "docs/source/examples/Predefined Metrics in Symbolic Module.ipynb", "max_stars_repo_name": "r0cketr1kky/einsteinpy", "max_stars_repo_head_hexsha": "d86f412736a42e2cf688a1e21d7b553868a14bc4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-04-07T04:01:57.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-11T11:59:55.000Z", "max_issues_repo_path": "docs/source/examples/Predefined Metrics in Symbolic Module.ipynb", "max_issues_repo_name": "r0cketr1kky/einsteinpy", "max_issues_repo_head_hexsha": "d86f412736a42e2cf688a1e21d7b553868a14bc4", "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/source/examples/Predefined Metrics in Symbolic Module.ipynb", "max_forks_repo_name": "r0cketr1kky/einsteinpy", "max_forks_repo_head_hexsha": "d86f412736a42e2cf688a1e21d7b553868a14bc4", "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.2697947214, "max_line_length": 6264, "alphanum_fraction": 0.6262042389, "converted": true, "num_tokens": 772, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.930458253565792, "lm_q2_score": 0.924141827813457, "lm_q1q2_score": 0.8598753911544081}} {"text": "#Snippets and Programs from Chapter 4: Algebra and Symbolic Math with SymPy\n\n\n```python\n%matplotlib inline\n```\n\n\n```python\n#P96/97: Basic factorization and expansion\nfrom sympy import Symbol, factor, expand\nx = Symbol('x')\ny = Symbol('y')\nexpr = x**2 - y**2\nf = factor(expr)\nprint(f)\n# Expand\nprint(expand(f))\n```\n\n\n```python\n#P97: Factorizing and expanding a complicated identity\nfrom sympy import Symbol, factor, expand\nx = Symbol('x')\ny = Symbol('y')\nexpr = x**3 + 3*x**2*y + 3*x*y**2 + y**3 \n\nprint('Original expression: {0}'.format(expr))\nfactors = factor(expr)\nprint('Factors: {0}'.format(factors))\n\n\nexpanded = expand(factors)\nprint('Expansion: {0}'.format(expanded))\n\n```\n\n\n```python\n#P97: Pretty printing\nfrom sympy import Symbol, pprint, init_printing\nx = Symbol('x')\nexpr = x*x + 2*x*y + y*y\npprint(expr)\n# Reverse order lexicographical\ninit_printing(order='rev-lex')\nexpr = 1 + 2*x + 2*x**2\npprint(expr)\n```\n\n*Since we have initialized pretty printing above, it will be active for all the output below this.*\n\n\n```python\n#P99: Print a series\n\n'''\nPrint the series:\nx + x**2 + x**3 + ... + x**n\n ____ _____ ____ \n 2 3 n\n'''\nfrom sympy import Symbol, pprint, init_printing\ndef print_series(n):\n # initialize printing system with\n # reverse order\n init_printing(order='rev-lex')\n x = Symbol('x')\n series = x\n for i in range(2, n+1):\n series = series + (x**i)/i\n pprint(series)\n\nif __name__ == '__main__':\n n = input('Enter the number of terms you want in the series: ')\n print_series(int(n))\n```\n\n\n```python\n#P100: Substituting in values\nfrom sympy import Symbol\nx = Symbol('x')\ny = Symbol('y')\nexpr = x*x + x*y + x*y + y*y\nres = expr.subs({x:1, y:2})\nres\n```\n\n\n```python\n#P102: Print a series and also calculate its value at a certain point\n\n'''\nPrint the series:\n\nx + x**2 + x**3 + ... + x**n\n ____ _____ ____ \n 2 3 n\n \nand calculate its value at a certain value of x.\n'''\n\nfrom sympy import Symbol, pprint, init_printing\ndef print_series(n, x_value):\n # initialize printing system with\n # reverse order\n init_printing(order='rev-lex')\n x = Symbol('x')\n series = x\n for i in range(2, n+1):\n series = series + (x**i)/i\n pprint(series)\n # evaluate the series at x_value\n series_value = series.subs({x:x_value})\n print('Value of the series at {0}: {1}'.format(x_value, series_value))\n\nif __name__ == '__main__':\n n = input('Enter the number of terms you want in the series: ')\n x_value = input('Enter the value of x at which you want to evaluate the series: ') \n print_series(int(n), float(x_value))\n```\n\n\n```python\n# P104: Expression multiplier\n\n'''\nProduct of two expressions\n'''\n\nfrom sympy import expand, sympify\nfrom sympy.core.sympify import SympifyError\ndef product(expr1, expr2):\n prod = expand(expr1*expr2)\n print(prod)\n\nif __name__=='__main__':\n expr1 = input('Enter the first expression: ')\n expr2 = input('Enter the second expression: ')\n try:\n expr1 = sympify(expr1)\n expr2 = sympify(expr2)\n except SympifyError:\n print('Invalid input')\n else:\n product(expr1, expr2)\n\n```\n\n\n```python\n#P105: Solving a linear equation\n>>> from sympy import Symbol, solve \n>>> x = Symbol('x')\n>>> expr = x - 5 - 7\n>>> solve(expr)\n```\n\n\n```python\n#P106: Solving a quadratic equation\n>>> from sympy import solve \n>>> x = Symbol('x')\n>>> expr = x**2 + 5*x + 4 \n>>> solve(expr, dict=True)\n```\n\n\n```python\n#P106: Quadratic equation with imaginary roots\n>>> from sympy import Symbol\n>>> x=Symbol('x')\n>>> expr = x**2 + x + 1\n>>> solve(expr, dict=True)\n```\n\n\n```python\n#P106/107: Solving for one variable in terms of others\n>>> from sympy import Symbol, solve\n>>> x = Symbol('x')\n>>> a = Symbol('a') \n>>> b = Symbol('b')\n>>> c = Symbol('c')\n>>> expr = a*x*x + b*x + c\n>>> solve(expr, x, dict=True)\n```\n\n\n```python\n#P107: Express s in terms of u, a, t\n>>> from sympy import Symbol, solve, pprint \n>>> s = Symbol('s')\n>>> u = Symbol('u')\n>>> t = Symbol('t')\n>>> a = Symbol('a')\n>>> expr = u*t + (1/2)*a*t*t - s\n>>> t_expr = solve(expr,t, dict=True) \n>>> t_expr\n```\n\n\n```python\n#P108: Solve a system of Linear equations\n>>> from sympy import Symbol\n>>> x = Symbol('x')\n>>> y = Symbol('y')\n>>> expr1 = 2*x + 3*y - 6 \n>>> expr2 = 3*x + 2*y - 12\n>>> solve((expr1, expr2), dict=True)\n```\n\n\n```python\n#P109: Simple plot with SymPy\n>>> from sympy.plotting import plot\n>>> from sympy import Symbol\n>>> x = Symbol('x')\n>>> plot(2*x+3)\n```\n\n\n```python\n#P110: Plot in SymPy with range of x as well as other attributes specified\n>>> from sympy import plot, Symbol\n>>> x = Symbol('x')\n>>> plot(2*x + 3, (x, -5, 5), title='A Line', xlabel='x', ylabel='2x+3')\n```\n\n\n```python\n#P112: Plot the graph of an input expression\n'''\nPlot the graph of an input expression\n'''\nfrom sympy import Symbol, sympify, solve\nfrom sympy.plotting import plot\n\ndef plot_expression(expr):\n y = Symbol('y')\n solutions = solve(expr, y)\n expr_y = solutions[0]\n plot(expr_y)\n\nif __name__=='__main__':\n expr = input('Enter your expression in terms of x and y: ')\n try:\n expr = sympify(expr)\n except SympifyError:\n print('Invalid input')\n else:\n plot_expression(expr)\n```\n\n\n```python\n#P113: Plotting multiple functions\n>>> from sympy.plotting import plot \n>>> from sympy import Symbol\n>>> x = Symbol('x')\n>>> plot(2*x+3, 3*x+1)\n```\n\n\n```python\n#P114: Plot of the two lines drawn in a different color\n>>> from sympy.plotting import plot \n>>> from sympy import Symbol\n>>> x = Symbol('x')\n>>> p = plot(2*x+3, 3*x+1, legend=True, show=False) \n>>> p[0].line_color = 'b'\n>>> p[1].line_color = 'r'\n>>> p.show()\n```\n\n\n```python\n#P116: Example of summing a series\n>>> from sympy import Symbol, summation, pprint \n>>> x = Symbol('x')\n>>> n = Symbol('n')\n>>> s = summation(x**n/n, (n, 1, 5)) \n>>> s.subs({x:1.2})\n```\n\n\n\n\n 3.51206400000000\n\n\n\n\n```python\n#P117: Example of solving a polynomial inequality\n>>> from sympy import Poly, Symbol, solve_poly_inequality\n>>> x = Symbol('x')\n>>> ineq_obj = -x**2 + 4 < 0 \n>>> lhs = ineq_obj.lhs\n>>> p = Poly(lhs, x)\n>>> rel = ineq_obj.rel_op\n>>> solve_poly_inequality(p, rel)\n```\n\n\n\n\n [(-oo, -2), (2, oo)]\n\n\n\n\n```python\n#P118: Example of solving a rational inequality\n>>> from sympy import Symbol, Poly, solve_rational_inequalities\n>>> x = Symbol('x')\n>>> ineq_obj = ((x-1)/(x+2)) > 0\n>>> lhs = ineq_obj.lhs\n>>> numer, denom = lhs.as_numer_denom()\n>>> p1 = Poly(numer)\n>>> p2 = Poly(denom)\n>>> rel = ineq_obj.rel_op\n>>> solve_rational_inequalities([[((p1, p2), rel)]])\n```\n\n\n\n\n (-oo, -2) U (1, oo)\n\n\n\n\n```python\n#P118: Solve a non-polynomial inequality\n>>> from sympy import Symbol, solve, solve_univariate_inequality, sin \n>>> x = Symbol('x')\n>>> ineq_obj = sin(x) - 0.6 > 0\n>>> solve_univariate_inequality(ineq_obj, x, relational=False)\n```\n\n\n\n\n (0.643501108793284, 2.49809154479651)\n\n\n", "meta": {"hexsha": "6075efe3ee36ffd05522e9f499072db93c58a992", "size": 72623, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "chapter4/Chapter4.ipynb", "max_stars_repo_name": "hexu1985/Doing.Math.With.Python", "max_stars_repo_head_hexsha": "b6a02805cd450325e794a49f55d2d511f9db15a5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 109, "max_stars_repo_stars_event_min_datetime": "2015-08-28T10:23:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-15T01:39:51.000Z", "max_issues_repo_path": "chapter4/Chapter4.ipynb", "max_issues_repo_name": "hexu1985/Doing.Math.With.Python", "max_issues_repo_head_hexsha": "b6a02805cd450325e794a49f55d2d511f9db15a5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2015-12-07T19:35:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-01T07:25:42.000Z", "max_forks_repo_path": "chapter4/Chapter4.ipynb", "max_forks_repo_name": "hexu1985/Doing.Math.With.Python", "max_forks_repo_head_hexsha": "b6a02805cd450325e794a49f55d2d511f9db15a5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 74, "max_forks_repo_forks_event_min_datetime": "2015-10-15T18:09:15.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-30T05:06:21.000Z", "avg_line_length": 115.2746031746, "max_line_length": 14682, "alphanum_fraction": 0.8584470485, "converted": true, "num_tokens": 2128, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632288833652, "lm_q2_score": 0.9032942073547148, "lm_q1q2_score": 0.8598125408442988}} {"text": "```python\nimport os\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"-1\"\n\nimport tensorflow as tf\n```\n\nPart of the training process requires calculating derivatives that involve tensors. So let's learn about TensorFlow's built-in [automatic differentiation](https://www.tensorflow.org/guide/autodiff) engine, using a very simple example. Let's consider the following two tensors:\n\n$$\n\\begin{align}\n U =\n \\begin{bmatrix}\n 1 & 2\n \\end{bmatrix}\n &&\n V =\n \\begin{bmatrix}\n 3 & 4 \\\\\n 5 & 6\n \\end{bmatrix}\n\\end{align}\n$$\n\nNow let's suppose that we want to multiply $U$ by $V$, and then sum all the values in the resulting tensor, such that the result is a scalar. In math notation, we might represent this as the following scalar function $f$:\n\n$$\nf(U, V) = \\mathrm{sum} (U \\, V) = \\sum_j \\sum_i u_i \\, v_{ij}\n$$\n\nOur goal is to calculate the derivative of $f$ with respect to each of its inputs: $\\frac{\\partial f}{\\partial U}$ and $\\frac{\\partial f}{\\partial V}$. We start by creating the two tensors $U$ and $V$. We then create a [tf.GradientTape](https://www.tensorflow.org/guide/autodiff#gradient_tapes), and tell TensorFlow to watch for mathematical operations involving $U$ and $V$, recording those operations onto our \"tape.\" The tape then enables us to calculate the derivatives of the function $f$ with respect to $U$ and $V$.\n\n\n```python\n# Decimal points in tensor values ensure they are floats, which automatic differentiation requires.\nU = tf.constant([[1., 2.]])\nV = tf.constant([[3., 4.], [5., 6.]])\n\nwith tf.GradientTape(persistent=True) as tape:\n tape.watch(U)\n tape.watch(V)\n W = tf.matmul(U, V)\n f = tf.math.reduce_sum(W)\n\nprint(tape.gradient(f, U)) # df/dU\nprint(tape.gradient(f, V)) # df/dV\n```\n\n tf.Tensor([[ 7. 11.]], shape=(1, 2), dtype=float32)\n tf.Tensor(\n [[1. 1.]\n [2. 2.]], shape=(2, 2), dtype=float32)\n\n\nTensorFlow automatically watches tensors that are defined as `Variable` instances. So let's turn `U` and `V` into variables, and remove the `watch` calls:\n\n\n```python\n# Decimal points in tensor values ensure they are floats, which automatic differentiation requires.\nU = tf.Variable(tf.constant([[1., 2.]]))\nV = tf.Variable(tf.constant([[3., 4.], [5., 6.]]))\n\nwith tf.GradientTape(persistent=True) as tape:\n W = tf.matmul(U, V)\n f = tf.math.reduce_sum(W)\n\nprint(tape.gradient(f, U)) # df/dU\nprint(tape.gradient(f, V)) # df/dV\n```\n\n tf.Tensor([[ 7. 11.]], shape=(1, 2), dtype=float32)\n tf.Tensor(\n [[1. 1.]\n [2. 2.]], shape=(2, 2), dtype=float32)\n\n\nAs you will see later, in deep learning, we will need to calculate the derivatives of the loss function with respect to the model parameters. Those parameters are variables because they change during training. Therefore, the fact that variables are automatically watched is handy in our scenario. \n\n## Optional explanation of the math\n\nLet's take a look at the math used to compute the derivatives. You only need to understand matrix multiplication and partial derivatives to follow along, but if the math isn't as interesting to you, feel free to skip to the next notebook.\n\nWe'll start by thinking of $U$ and $V$ as generic 1 × 2 and 2 × 2 matrices:\n\n$$\n\\begin{align}\n U =\n \\begin{bmatrix}\n u_1 & u_2\n \\end{bmatrix}\n &&\n V =\n \\begin{bmatrix}\n v_{11} & v_{12} \\\\\n v_{21} & v_{22}\n \\end{bmatrix}\n\\end{align}\n$$\n\nThen the scalar function $f$ can be written as:\n\n$$\n\\begin{align}\n f(U, V)\n &= \\mathrm{sum}(U \\, V) \\\\\n &= \\mathrm{sum} \n \\left( \n \\begin{bmatrix}\n u_1 & u_2\n \\end{bmatrix}\n \\begin{bmatrix}\n v_{11} & v_{12} \\\\\n v_{21} & v_{22}\n \\end{bmatrix}\n \\right) \\\\\n &= \\mathrm{sum}\n \\left(\n \\begin{bmatrix}\n u_1 v_{11} + u_2 v_{21} & u_1 v_{12} + u_2 v_{22}\n \\end{bmatrix}\n \\right) \\\\\n &= u_1 v_{11} + u_2 v_{21} + u_1 v_{12} + u_2 v_{22}\n\\end{align}\n$$\n\nWe can now calculate the derivatives of $f$ with respect to each of its inputs:\n\n$$\n\\frac{\\partial f}{\\partial U} =\n \\begin{bmatrix}\n \\frac{\\partial f}{\\partial u_1} & \\frac{\\partial f}{\\partial u_2}\n \\end{bmatrix} = \n \\begin{bmatrix}\n v_{11} + v_{12} & v_{21} + v_{22}\n \\end{bmatrix} = \n \\begin{bmatrix}\n 7 & 11\n \\end{bmatrix} \n$$\n\n$$\n\\frac{\\partial f}{\\partial V} =\n \\begin{bmatrix}\n \\frac{\\partial f}{\\partial v_{11}} & \\frac{\\partial f}{\\partial v_{12}} \\\\\n \\frac{\\partial f}{\\partial v_{21}} & \\frac{\\partial f}{\\partial v_{22}} \n \\end{bmatrix} = \n \\begin{bmatrix}\n u_1 & u_1 \\\\\n u_2 & u_2\n \\end{bmatrix} = \n \\begin{bmatrix}\n 1 & 1 \\\\\n 2 & 2\n \\end{bmatrix}\n$$\n\nAs you can see, when we plug in the numerical values of $U$ and $V$, we get the same result as TensorFlow's automatic differentiation.\n\n", "meta": {"hexsha": "0c90eaed02a47b9ce8b839deb0f5b9a5a7439861", "size": 8339, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "intro-tf/3-automatic-differentiation.ipynb", "max_stars_repo_name": "MicrosoftDocs/tensorflowfundamentals", "max_stars_repo_head_hexsha": "ccc0fa119dce1122529c2400d395542fbd7cf3b6", "max_stars_repo_licenses": ["CC-BY-4.0", "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": "intro-tf/3-automatic-differentiation.ipynb", "max_issues_repo_name": "MicrosoftDocs/tensorflowfundamentals", "max_issues_repo_head_hexsha": "ccc0fa119dce1122529c2400d395542fbd7cf3b6", "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": "intro-tf/3-automatic-differentiation.ipynb", "max_forks_repo_name": "MicrosoftDocs/tensorflowfundamentals", "max_forks_repo_head_hexsha": "ccc0fa119dce1122529c2400d395542fbd7cf3b6", "max_forks_repo_licenses": ["CC-BY-4.0", "MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-11-02T13:08:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-14T00:51:45.000Z", "avg_line_length": 35.485106383, "max_line_length": 540, "alphanum_fraction": 0.4709197746, "converted": true, "num_tokens": 1487, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474194456935, "lm_q2_score": 0.9005297834483234, "lm_q1q2_score": 0.8596884339029311}} {"text": "# Lecture 2: Different types of point processes and transformations \n\n## 1. Binomial Point Process\n\n- Fixed number of points\n- Independent and identically distributed points over a given region\n- How to simulate a BPP?\n\n\n```python\n#Numpy library\nimport numpy as np\n#Number of points: N\nx_realization_BPP = 50\n\n#Square side: L\nL = 10\n\n#Random points in axis x\nposition_x_realization_BPP = np.random.uniform(0,L,x_realization_BPP)\n\n#Random points in axis y\nposition_y_realization_BPP = np.random.uniform(0,L,x_realization_BPP)\n\n#Manipulating arrays\nposition_x_realization_BPP_t=np.transpose(position_x_realization_BPP)\nposition_y_realization_BPP_t=np.transpose(position_y_realization_BPP)\n#position_final_BPP = []\n#position_final_BPP = [[position_x_realization_BPP_t[ix], position_y_realization_BPP_t[ix]] for ix in range(0, x_realization_BPP)]\n```\n\n\n```python\n#Ploting libraries\nimport matplotlib.pyplot as plt\n#Plot commands\nplt.figure(figsize=(8,8), dpi=1200)\nplt.plot(position_x_realization_BPP, position_y_realization_BPP, marker='.', color='g',linestyle = '')\nplt.xlabel('x')\nplt.ylabel('y')\nplt.title('BPP')\nplt.show()\n```\n\nWhat can you say about this process?\n\n## 2. Poisson Point Process\n\n- Random number of points: Poisson distribution\n- Independent and identically distributed point over a given region\n- How to simulate a PPP?\n\n\n```python\n#Square side: L\nL = 10\n\n#Average number of points (Poisson)\nx_average_PPP = 50\n\n#Number of points N that is a Poisson random variable \nx_realization_PPP = np.random.poisson(x_average_PPP,1)\n\n#Random points in axis x\nposition_x_realization_PPP = np.random.uniform(0,L,x_realization_PPP)\n\n#Random points in axis y\nposition_y_realization_PPP = np.random.uniform(0,L,x_realization_PPP)\n\n#Manipulating arrays\nposition_x_realization_PPP_t=np.transpose(position_x_realization_PPP)\nposition_y_realization_PPP_t=np.transpose(position_y_realization_PPP)\n#position_final = []\n#position_final = [[position_x_realization_PPP_t[ix], position_y_realization_PPP_t[ix]] for ix in range(0, x_realization_PPP)]\n```\n\n\n```python\n#Number of points in this realization\nprint 'Number of points:', x_realization_PPP\n\n#Ploting libraries\nimport numpy as np\nimport matplotlib.pyplot as plt\n#Plot commands\nplt.figure(figsize=(8,8), dpi=1200)\nplt.plot(position_x_realization_PPP, position_y_realization_PPP, marker='.', color='r',linestyle = '')\nplt.xlabel('x')\nplt.ylabel('y')\nplt.title('PPP')\nplt.axis([0, L, 0, L])\nplt.show()\n```\n\nHow about the statistics?\n- Let's compare the average number of points based on the simulation and the analytic formula of Poisson distribution.\n\n\n```python\n#Sympy library\nfrom sympy import Symbol, symbols, init_printing, oo\nfrom sympy import exp, gamma\n\n# Setting things up\ninit_printing()\n\n#Symbols\nx,k = symbols('x k', real = True, positive = True)\n#Defining Poisson distribution\nf_Poisson = ((x)**k/gamma(k)) * exp(-x)\nf_Poisson\n```\n\n\n```python\n#Simulating Poisson distribution\ns = np.random.poisson(x_realization_PPP, 100000)\n\n#Analytic distribution\nfrom scipy.stats import poisson\n#\nplt.figure(figsize=(10,8), dpi=1200)\nplt.hist(s,normed=True, color=\"#6495ED\")\nk = np.arange(100)\nplt.plot(k, poisson.pmf(k, x_realization_PPP), '-o')\nplt.xlabel('$k$')\nplt.ylabel('Probability that $n = k$')\nplt.title('Poisson distribution')\nplt.show()\n```\n\n## 3. Superposition transformation\n\nWhat is a superposition transformation?\n\n\n```python\nimport matplotlib.pyplot as plt\n#Plot commands\nplt.figure(figsize=(8,8), dpi=100)\nplt.plot(position_x_realization_BPP, position_y_realization_BPP, marker='.', color='b',linestyle = '')\nplt.plot(position_x_realization_PPP, position_y_realization_PPP, marker='.', color='b',linestyle = '')\nplt.xlabel('x')\nplt.ylabel('y')\nplt.title('Superposition: BPP and PPP')\nplt.show()\n```\n\nBy looking this plot, can you say which point process is which?\n\nMarking the process\n\n\n```python\nimport matplotlib.pyplot as plt\n#Plot commands\nplt.figure(figsize=(8,8), dpi=1200)\nplt.plot(position_x_realization_BPP, position_y_realization_BPP, marker='x', color='g',linestyle = '')\nplt.plot(position_x_realization_PPP, position_y_realization_PPP, marker='o', color='r',linestyle = '')\nplt.xlabel('x')\nplt.ylabel('y')\nplt.title('Superposition: BPP and PPP')\nplt.show()\n```\n\n## 4. Mapping transformation\n\nWhat is a mapping transformation?\n\n\n```python\n#Square side: L\nL = 10\n\n#Average number of points (Poisson)\nx_average_PPP = 50\n\n#Number of points N that is a Poisson random variable \nx_realization_PPP = np.random.poisson(x_average_PPP,1)\n\n#Scaling transformation\ns = 2\n\n#Random points in axis x\nposition_x_realization_PPP = s * np.random.uniform(0,L,x_realization_PPP)\n\n#Random points in axis y\nposition_y_realization_PPP = s * np.random.uniform(0,L,x_realization_PPP) \n```\n\n\n```python\n#Number of points in this realization\nprint 'Number of points:', x_realization_PPP\n\n#Ploting libraries\nimport numpy as np\nimport matplotlib.pyplot as plt\n#Plot commands\nplt.figure(figsize=(8,8), dpi=1200)\nplt.plot(position_x_realization_PPP, position_y_realization_PPP, marker='.', color='g',linestyle = '')\nplt.xlabel('x')\nplt.ylabel('y')\nplt.title('PPP with scaling')\nplt.show()\n```\n\n## 5. Thinning transformation\n\nWhat is a thinning transformation?\n\nDelete points\n\n- Independent: e.g. erase with a given probability\n- Dependent: e.g. erase the points within a given range\n\nYou can try to implentent this at home\n\n## 6. Cluster formation\n\nHow to form clusters?\n\n- Think about if every point in the original point process can be the parent of other point process around it\n- Try also to implement this at home\n\n
This work is licensed under a Creative Commons Attribution-NonCommercial 4.0 International License.\n\n\n```python\n\n```\n", "meta": {"hexsha": "378c7c48cb27c29d7e088753287c5db868bf6f08", "size": 97794, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "lecture2.ipynb", "max_stars_repo_name": "pedrohjn/Stochastic-Geometry", "max_stars_repo_head_hexsha": "d9c57169989219e4ff38577130096054a51a78e3", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2019-03-11T10:52:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-24T02:55:49.000Z", "max_issues_repo_path": "lecture2.ipynb", "max_issues_repo_name": "pedrohjn/Stochastic-Geometry", "max_issues_repo_head_hexsha": "d9c57169989219e4ff38577130096054a51a78e3", "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": "lecture2.ipynb", "max_forks_repo_name": "pedrohjn/Stochastic-Geometry", "max_forks_repo_head_hexsha": "d9c57169989219e4ff38577130096054a51a78e3", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2017-12-19T12:08:24.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-30T10:57:52.000Z", "avg_line_length": 152.0902021773, "max_line_length": 28226, "alphanum_fraction": 0.8945129558, "converted": true, "num_tokens": 1570, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.959154281754899, "lm_q2_score": 0.8962513800615313, "lm_q1q2_score": 0.859643348714755}} {"text": "# Euler Equations \n\nThe Euler equations in one-dimension are given by the following set of partial differential equations representing the conservation of mass, momentum, and energy.\n\n$$\n\\begin{align}\n& \\frac{\\partial \\rho}{\\partial t} + \\frac{\\partial \\rho u}{\\partial x} = 0 \\\\\n& \\frac{\\partial \\rho u}{\\partial t} + \\frac{\\partial (\\rho u^2 + p)}{\\partial x} = 0 \\\\\n& \\frac{\\partial \\rho e}{\\partial t} + \\frac{\\partial}{\\partial x}\\Bigg[ \\left(e + p\\right)u \\Bigg] = 0\n\\end{align}\n$$\n\nThe Euler equations can be written in vector form as\n\n$$\n\\frac{\\partial \\mathbf{U} }{\\partial t} + \\frac{\\partial \\mathbf{F}}{\\partial x} = 0\n$$\n\nwhere \n\n$$\n\\mathbf{U} = \\begin{bmatrix}\n\\rho \\\\\n\\rho u \\\\\ne \n\\end{bmatrix}\n$$\n\nand\n\n$$\n\\mathbf{F} = \\begin{bmatrix}\n\\rho u\\\\\n\\rho u^2 + p \\\\\n u (e + p)\n\\end{bmatrix}\n$$\n\nwith \n\n$$\np = (\\gamma - 1)\\left(e - \\rho \\frac{u^2}{2}\\right)\n$$\n\nwhere the vector $\\mathbf{U}$ is a vector of the conservative variables, and the vector $\\mathbf{F}$ is the net flux of those conservative variables in and out of the control volume.\n\nWe want to be able to relate the vector form of the Euler equations to our model hyperbolic PDE; however, for this PDE, we have the partial derivative of $\\mathbf{U}$ with time, but instead of $\\mathbf{U}$, the partial derivative with respect to $x$ is the function, $\\mathbf{F}$. \n\n## Homogeneous of Degree p\n\nConsider $\\mathbf{F} = \\mathbf{F}(\\mathbf{U})$, where $\\mathbf{F}$ is a function of the elements of $\\mathbf{U}$. Let $\\mathbf{U}^{\\prime} = \\alpha \\mathbf{U}$, then the following statement is true, \n\n$$\n\\mathbf{F}(\\mathbf{U}^{\\prime}) = \\alpha^p \\mathbf{F}(\\mathbf{U}),\n$$\n\nif and only if $\\mathbf{F}$ is homogenous of degree $p$ with respect to $\\mathbf{U}$. \n\n## Euler Equations are Homogeneous with p = 1\n\n\nUsing this theorem, we can state that if $\\mathbf{F}$ in the Euler equations, \n\n$$\n\\frac{\\partial \\mathbf{U} }{\\partial t} + \\frac{\\partial \\mathbf{F}}{\\partial x} = 0\n$$\n\nis homogenous of degree $p=1$ with respect to $\\mathbf{U}$, then\n\n$$\n\\frac{\\partial \\mathbf{F}}{\\partial \\mathbf{U}}\\mathbf{U} = \\overline{\\mathbf{A}} \\mathbf{U} = \\mathbf{F}\n$$\n\nwhere the matrix $\\overline{\\mathbf{A}}$ is called the Jacobian is defined as\n\n$$\n\\overline{\\mathbf{A}} = \\frac{\\partial \\mathbf{F}}{\\partial \\mathbf{U}}\n$$\n\nand\n\n$$\n\\frac{\\partial \\mathbf{U} }{\\partial t} + \\overline{\\mathbf{A}} \\frac{\\partial \\mathbf{U}}{\\partial x} = 0\n$$\n\n### Example\n\nConsidering the following system of equations\n\n$$\n\\frac{\\partial \\mathbf{U} }{\\partial t} + \\frac{\\partial \\mathbf{F}}{\\partial x} = 0\n$$\n\nwhere\n\n$$\n\\mathbf{F} = \n\\begin{bmatrix}\n\\rho \\\\\n\\rho u^2 \n\\end{bmatrix}\n$$\n\nand \n\n$$\n\\mathbf{U} = \n\\begin{bmatrix}\n\\rho \\\\\n\\rho u \n\\end{bmatrix}\n$$\n\ncompute the Jacobian matrix \n\n$$\n\\overline{\\mathbf{A}} = \\frac{\\partial \\mathbf{F}}{\\partial \\mathbf{U}}\n$$\n\nand demonstrate that $\\mathbf{F} = \\overline{\\mathbf{A}} \\mathbf{U}$.\n\n### Solution\n\nWriting this in component form, \n\n$$\n\\overline{\\mathbf{A}} = \\begin{bmatrix}\n\\frac{\\partial f_1}{\\partial u_1} \\Big\\rvert_{u_2} & \\frac{\\partial f_1}{\\partial u_2} \\Big\\rvert_{u_1}\\\\\n\\frac{\\partial f_2}{\\partial u_1} \\Big\\rvert_{u_2} & \\frac{\\partial f_2}{\\partial u_2} \\Big\\rvert_{u_1}\n\\end{bmatrix}\n$$\n\nwhere\n\n$$\n\\overline{\\mathbf{A}} = \\begin{bmatrix}\n\\frac{\\partial \\rho}{\\partial \\rho} \\Big\\rvert_{\\rho u} & \\frac{\\partial \\rho}{\\partial (\\rho u)} \\Big\\rvert_{\\rho} \\\\\n\\frac{\\partial \\rho u^2}{\\partial \\rho} \\Big\\rvert_{\\rho u} & \\frac{\\partial \\rho u^2}{\\partial (\\rho u)} \\Big\\rvert_{\\rho}\n\\end{bmatrix} \n= \n\\begin{bmatrix}\n1 & 0 \\\\\n\\frac{\\partial }{\\partial \\rho} \\left[ \\frac{1}{\\rho} (\\rho u)^2 \\right]_{\\rho u} & \\frac{\\partial }{\\partial (\\rho u)} \\left[ \\frac{1}{\\rho} (\\rho u)^2 \\right]_{\\rho}\n\\end{bmatrix} \n$$\n\nSimplifying this results in \n\n$$\n\\overline{\\mathbf{A}} = \n\\begin{bmatrix}\n1 & 0 \\\\\n-\\frac{1}{\\rho^2} (\\rho u)^2 & \\frac{1}{\\rho} \\left(2 \\rho u \\right)\n\\end{bmatrix}\n= \n\\begin{bmatrix}\n1 & 0 \\\\\n-u^2 & 2 u\n\\end{bmatrix} \n$$\n\nand we can show that \n\n$$\n \\begin{bmatrix}\n\\frac{\\partial \\rho }{\\partial t} \\\\\n\\frac{\\partial \\rho u }{\\partial t}\n\\end{bmatrix}\n+ \\begin{bmatrix}\n1 & 0 \\\\\n-\\frac{1}{\\rho^2} (\\rho u)^2 & \\frac{1}{\\rho} \\left(2 \\rho u \\right)\n\\end{bmatrix} \\begin{bmatrix}\n\\frac{\\partial \\rho }{\\partial x} \\\\\n\\frac{\\partial \\rho u }{\\partial x}\n\\end{bmatrix}= 0\n$$\n\n# Euler Equations\n\nTo write the Euler equations in this form would require determining the Jacobian\n\n$$\n\\overline{\\mathbf{A}} = \\begin{bmatrix}\n\\frac{\\partial \\rho u}{\\partial \\rho} \\Big\\rvert_{\\rho u,e} & \n\\frac{\\partial \\rho u}{\\partial (\\rho u)} \\Big\\rvert_{\\rho,e} &\n\\frac{\\partial \\rho u}{\\partial e} \\Big\\rvert_{\\rho,\\rho u} \\\\\n\\frac{\\partial \\rho u^2 + p}{\\partial \\rho} \\Big\\rvert_{\\rho u,e} & \n\\frac{\\partial \\rho u^2 + p}{\\partial (\\rho u)} \\Big\\rvert_{\\rho,e} &\n\\frac{\\partial \\rho u^2 + p}{\\partial e} \\Big\\rvert_{\\rho,\\rho u} \\\\\n\\frac{\\partial (e + p)u}{\\partial \\rho} \\Big\\rvert_{\\rho u,e} & \n\\frac{\\partial (e + p)u}{\\partial (\\rho u)} \\Big\\rvert_{\\rho,e} &\n\\frac{\\partial (e + p)u}{\\partial e} \\Big\\rvert_{\\rho,\\rho u}\n\\end{bmatrix} \n$$\n\nSince evaluating this matrix is not straight-forward, let us apply a transformation of variables and write the Euler equations in primitve form using the vector of primitive variables \n\n$$\n\\mathbf{V} = \n\\begin{bmatrix}\n\\rho \\\\\nu \\\\\np\n\\end{bmatrix}\n\\qquad \\textrm{and} \\qquad\n\\mathbf{U} = \n\\begin{bmatrix}\n\\rho u\\\\\n\\rho u^2 \\\\\ne\n\\end{bmatrix}\n$$\n\nLet the matrix $\\overline{\\mathbf{T}}$ be the transformation Jacobian, which is defined as\n\n$$\n\\overline{\\mathbf{T}} = \\frac{\\partial \\mathbf{U}}{\\partial \\mathbf{V}}\n$$\n\nUsing the transformation Jacobian we can write\n\n$$\n\\frac{\\partial \\mathbf{U}}{\\partial \\mathbf{V}} \\frac{\\partial \\mathbf{V}}{\\partial t} + \\overline{\\mathbf{A}} \\left( \\frac{\\partial \\mathbf{U}}{\\partial \\mathbf{V}} \\frac{\\partial \\mathbf{V}}{\\partial x} \\right) = 0\n$$\n\nMultiply by the inverse of $\\partial \\mathbf{U} / \\partial \\mathbf{V}$, \n\n$$\n\\left( \\frac{\\partial \\mathbf{U}}{\\partial \\mathbf{V}}\\right)^{-1} \\frac{\\partial \\mathbf{U}}{\\partial \\mathbf{V}} \\frac{\\partial \\mathbf{V}}{\\partial t} + \\left( \\frac{\\partial \\mathbf{U}}{\\partial \\mathbf{V}}\\right)^{-1} \\overline{\\mathbf{A}} \\left( \\frac{\\partial \\mathbf{U}}{\\partial \\mathbf{V}} \\frac{\\partial \\mathbf{V}}{\\partial x} \\right) = 0\n$$\n\nsimplifying, \n\n$$\n\\frac{\\partial \\mathbf{V}}{\\partial t} + \\left[ \\left( \\frac{\\partial \\mathbf{U}}{\\partial \\mathbf{V}}\\right)^{-1} \\overline{\\mathbf{A}} \\frac{\\partial \\mathbf{U}}{\\partial \\mathbf{V}} \\right] \\frac{\\partial \\mathbf{V}}{\\partial x} = 0\n$$\n\nwhich gives\n\n$$\n\\frac{\\partial \\mathbf{V}}{\\partial t} + \\overline{\\mathbf{A}^{\\prime}} \\frac{\\partial \\mathbf{V}}{\\partial x} = 0\n$$\n\nwhere \n\n$$\n\\overline{\\mathbf{A}^{\\prime}} = \\overline{\\mathbf{T}}^{-1} \\, \\overline{\\mathbf{A}} \\, \\overline{\\mathbf{T}} \n$$\n\nBy induction, we can then define\n\n$$\n\\overline{\\mathbf{A}^{\\prime}} =\n\\begin{bmatrix}\nu & \\rho & 0 \\\\\n0 & u & \\frac{1}{\\rho} \\\\\n0 & \\gamma p & u \\\\\n\\end{bmatrix}\n$$\n\nwhere\n\n$$\n\\begin{bmatrix}\n\\frac{\\partial \\rho }{\\partial t} \\\\\n\\frac{\\partial u }{\\partial t} \\\\\n\\frac{\\partial p}{\\partial t} \n\\end{bmatrix}\n+\n\\begin{bmatrix}\nu & \\rho & 0 \\\\\n0 & u & \\frac{1}{\\rho} \\\\\n0 & \\gamma p & u \\\\\n\\end{bmatrix}\n\\begin{bmatrix}\n\\frac{\\partial \\rho }{\\partial x} \\\\\n\\frac{\\partial u }{\\partial x} \\\\\n\\frac{\\partial p}{\\partial x} \n\\end{bmatrix}\n = 0\n$$\n\n### Proof\n\n$$\n\\frac{\\partial e }{\\partial t} = \\frac{\\partial}{\\partial t}\\left[ \\frac{p}{\\gamma - 1} + \\rho \\frac{ u^2 }{2} \\right]\n$$\n\n$$\n\\frac{\\partial (e + p)u }{\\partial x} = \\frac{\\partial}{\\partial x}\\left[ u \\frac{p}{\\gamma - 1} + \\rho u \\frac{ u^2 }{2} + p u\\right] = \\frac{\\partial}{\\partial x}\\left[ p u \\left( 1 + \\frac{1}{\\gamma - 1}\\right) + \\rho u \\frac{ u^2 }{2} \\right] = \\frac{\\partial}{\\partial x}\\left[ p u \\frac{\\gamma}{\\gamma - 1} + \\rho u \\frac{ u^2 }{2} \\right]\n$$\n\nCombining the terms\n\n$$\n\\frac{\\partial e }{\\partial t} + \\frac{\\partial (e + p)u }{\\partial x} = \\frac{\\partial}{\\partial t}\\left[ \\frac{p}{\\gamma - 1} + \\rho \\frac{ u^2 }{2} \\right] + \\frac{\\partial}{\\partial x}\\left[ p u \\frac{\\gamma}{\\gamma - 1} + \\rho u \\frac{ u^2 }{2} \\right] = 0\n$$\n\n$$\n\\frac{\\partial e }{\\partial t} + \\frac{\\partial (e + p)u }{\\partial x} = \\frac{\\partial}{\\partial t}\\left[ \\frac{p}{\\gamma - 1} \\right] + \\frac{\\partial}{\\partial x}\\left[ p u \\frac{\\gamma}{\\gamma - 1} \\right] + \\frac{\\partial}{\\partial t}\\left[ \\rho \\frac{ u^2 }{2} \\right] + \\frac{\\partial}{\\partial x}\\left[\\rho u \\frac{ u^2 }{2} \\right] = 0\n$$\n\nUsing the chain rule, we know \n\n$$\n\\frac{\\partial f(x^2)}{\\partial x} = 2 x \\frac{\\partial f(x)}{\\partial x} \n$$\n\nwhich we can use to simplify the equation as follows\n\n$$\n\\frac{\\partial e }{\\partial t} + \\frac{\\partial (e + p)u }{\\partial x} = \\frac{1}{\\gamma - 1} \\left( \\frac{\\partial p}{\\partial t} + \\frac{\\partial \\gamma p u }{\\partial x} \\right) + u \\frac{\\partial (\\rho u)}{\\partial t} + u \\frac{\\partial \\rho u^2 }{\\partial x} = 0\n$$\n\nand factoring\n\n$$\n\\frac{\\partial e }{\\partial t} + \\frac{\\partial (e + p)u }{\\partial x} = \\frac{1}{\\gamma - 1} \\left( \\frac{\\partial p}{\\partial t} + \\frac{\\partial \\gamma p u }{\\partial x} \\right) + u \\left( \\frac{\\partial (\\rho u)}{\\partial t} + \\frac{\\partial \\rho u^2 }{\\partial x} \\right) = 0\n$$\n\nthen using the fact that \n\n$$\n\\frac{\\partial (\\rho u)}{\\partial t} + \\frac{\\partial \\rho u^2 + p}{\\partial x} = 0\n$$\n\nwe can rewrite the equation about adding and subtracting $\\frac{\\partial p }{\\partial x}$ term, \n\n$$\n\\frac{\\partial e }{\\partial t} + \\frac{\\partial (e + p)u }{\\partial x} = \\frac{1}{\\gamma - 1} \\left( \\frac{\\partial p}{\\partial t} + \\frac{\\partial \\gamma p u }{\\partial x} \\right) + u \\left( \\frac{\\partial (\\rho u)}{\\partial t} + \\frac{\\partial (\\rho u^2 + p)}{\\partial x} - \\frac{\\partial p}{\\partial x} \\right) = 0\n$$\n\n\nwe get the conservation of energy in the primitive form as\n\n$$\n\\frac{\\partial p}{\\partial t} + \\frac{\\partial ( \\gamma p u) }{\\partial x} - u (\\gamma - 1) \\frac{\\partial p }{\\partial x} = 0\n$$\n\nexpaning results in \n\n$$\n\\frac{\\partial p}{\\partial t} + u \\gamma \\frac{\\partial p }{\\partial x} + \\gamma p \\frac{\\partial u }{\\partial x} - u \\gamma \\frac{\\partial p }{\\partial x} + u \\frac{\\partial p }{\\partial x} = 0\n$$\n\nFinally,\n\n$$\n\\frac{\\partial p}{\\partial t} + \\gamma p \\frac{\\partial u }{\\partial x} + u \\frac{\\partial p }{\\partial x}= 0\n$$\n\n\n\n\n\n## One-dimensional Euler Equations\n\nIn conservative form, the one-dimensional Euler equations are \n\n$$\n\\frac{\\partial \\mathbf{U}}{\\partial t} + \\frac{\\partial \\mathbf{F}}{\\partial x} = 0\n$$\n\nwhere \n\n$$\n\\mathbf{U} = \\begin{bmatrix}\n\\rho \\\\\n\\rho u \\\\\ne \n\\end{bmatrix}\n$$\n\nand\n\n$$\n\\mathbf{F} = \\begin{bmatrix}\n\\rho u\\\\\n\\rho u^2 + p \\\\\n u (e + p)\n\\end{bmatrix}\n$$\n\nwith \n\n$$\np = (\\gamma - 1)\\left(e - \\rho \\frac{u^2}{2}\\right)\n$$\n\nSince the Euler equations are homogenous to degeree 1, we can write the same set of equations in terms of the Jacobian matrix $\\mathbf{A}$, \n\n$$\n\\frac{\\partial \\mathbf{U}}{\\partial t} + \\overline{\\mathbf{A}} \\frac{\\partial \\mathbf{U}}{\\partial x} = 0\n$$\n\nIt is often more convenient to work with the primitive set of variables $(\\rho, u, p)$ instead of the conservative variables. Using this set of variables, the Euler equations in terms of the primitive variables is written \n\n$$\n\\frac{\\partial \\mathbf{V}}{\\partial t} + \\overline{\\mathbf{A}^{\\prime}} \\frac{\\partial \\mathbf{V}}{\\partial x} = 0\n$$\n\nNote that this form of the equation is also referred to as the non-conservative form of the Euler equations though sometimes the entropy is used as the primitive variable instead of the pressure. The transformed Jacobian matrix is defined as\n\n$$\n\\overline{\\mathbf{A}^{\\prime}} = \\overline{\\mathbf{T}}^{-1} \\, \\overline{\\mathbf{A}} \\, \\overline{\\mathbf{T}} \n$$\n\nwhere\n\n$$\n\\overline{\\mathbf{A}^{\\prime}} =\n\\begin{bmatrix}\nu & \\rho & 0 \\\\\n0 & u & \\frac{1}{\\rho} \\\\\n0 & \\gamma p & u \\\\\n\\end{bmatrix}\n$$\n\n\n\n## Hyperbolic Requirement\n\nThe above equation is hyperbolic if the eigenvalues of the matrix $\\overline{\\mathbf{A}}$ or $\\overline{\\mathbf{A}^{\\prime}}$ are real and have a complete set of eigenvectors (the matrix is diagonalizable). We can determine the eigenvalues by diagonalizing the matrix\n\n$$\n\\Lambda = \\overline{\\mathbf{P}} \\, \\overline{\\mathbf{A}^{\\prime}} \\, \\overline{\\mathbf{P}}^{-1} = \n\\begin{bmatrix}\nu & 0 & 0 \\\\\n0 & u + c& 0 \\\\\n0 & 0& u -c \\\\\n\\end{bmatrix}\n$$\n\nwhere\n\n$$\n\\overline{\\mathbf{P}} =\n\\begin{bmatrix}\n1 & 0 & -\\frac{1}{c^2} \\\\\n0 & \\rho c & 1 \\\\\n0 & -\\rho c& 1 \\\\\n\\end{bmatrix}\n$$\n\nand\n\n$$\n\\overline{\\mathbf{P}}^{-1} =\n\\begin{bmatrix}\n1 & \\frac{1}{c^2} & \\frac{1}{c^2} \\\\\n0 & \\frac{1}{2\\rho c} & -\\frac{1}{2\\rho c} \\\\\n0 & \\frac{1}{2} & \\frac{1}{2} \\\\\n\\end{bmatrix}\n$$\n", "meta": {"hexsha": "f1077e8bf23a015fda2b46062b69d368c23b1c67", "size": 18564, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Notebooks/Euler/2-EulerEquations-HyperbolicPDE-Part2.ipynb", "max_stars_repo_name": "jcschulz/ae269", "max_stars_repo_head_hexsha": "5c467a6e70808bb00e27ffdb8bb0495e0c820ca0", "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/Euler/2-EulerEquations-HyperbolicPDE-Part2.ipynb", "max_issues_repo_name": "jcschulz/ae269", "max_issues_repo_head_hexsha": "5c467a6e70808bb00e27ffdb8bb0495e0c820ca0", "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/Euler/2-EulerEquations-HyperbolicPDE-Part2.ipynb", "max_forks_repo_name": "jcschulz/ae269", "max_forks_repo_head_hexsha": "5c467a6e70808bb00e27ffdb8bb0495e0c820ca0", "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.0466019417, "max_line_length": 395, "alphanum_fraction": 0.4734970911, "converted": true, "num_tokens": 4663, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9591542829224748, "lm_q2_score": 0.8962513627417532, "lm_q1q2_score": 0.8596433331488572}} {"text": "# Regression\n\n## 1.Linear models\n\n***\n\n* 1.1 Formulation\n\n***\n\nAssume instance $ \\mathbf{x} = (x_1, x_2, ... , x_d)^T $, here $T$ means the matrix transpose. Linear model use linear combination of all attributes to do prediction.\n\n\\begin{equation}\nf(\\mathbf{x}) = w_1x_1 + w_2x_2 + ... + w_dx_d + b, \\tag{1}\n\\end{equation}\n\nor\n\n\\begin{equation}\n f(\\mathbf{x}) = \\mathbf{w}^T\\mathbf{x} + b. \\tag{2}\n\\end{equation}\n\n***\n\n* 1.2 Linear regression\n\n***\n\nUse the linear model to obtain the relationship between the dependent variable (test results, $y_i$) and independent variables (selected features, $x_i$). If only one explanatory variable is considered, it is called simple linear regression, for more than one, it is called multiple linear regression. If multiple dependent variables are considered, it is called multivariate linear regression. Let's start with the simple linear regression.\n\nGiven $x_i$ and $y_i$, how to find w and b so that $f(x_i) = wx_i + b \\rightarrow y_i$?\n\nWe may use the least square approach:\n\n$(w^* , b^*) = \\underset{(w , b)}{\\arg\\min} \\sum\\limits_{i=1}^m (f(x_i) - y_i)^2 = \\underset{(w , b)}{\\arg\\min} \\sum\\limits_{i=1}^m (y_i - wx_i - b)^2$, here $m$ means we have $m$ instances.\n\nLet's set\n$E_{(w, b)} = \\sum\\limits_{i=1}^m (y_i - wx_i - b)^2$, here $E_{(w, b)}$ is the cost function. \n\nPerform parameter estimation of least square approach\n\n\\begin{equation}\n \\frac{\\partial E}{\\partial w} = 2 \\left( w \\sum\\limits_{i=1}^m x_i^2 - \\sum\\limits_{i=1}^m (y_i - b)x_i \\right) = 0, \\tag{3}\n\\end{equation}\n\n\\begin{equation}\n \\frac{\\partial E}{\\partial b} = 2 \\left( mb - \\sum\\limits_{i=1}^m (y_i - wx_i) \\right) = 0. \\tag{4}\n\\end{equation}\n\nWe then have\n\n\\begin{equation}\n w = \\frac{ \\sum\\limits_{i=1}^m y_i (x_i - \\frac{1}{m}\\sum\\limits_{i=1}^m x_i )}{\\sum\\limits_{i=1}^m x_i^2 - \\frac{1}{m} \\left( \\sum\\limits_{i=1}^m x_i \\right)^2}, \\tag{5}\n\\end{equation}\n\n\\begin{equation}\n b = \\frac{1}{m}\\sum\\limits_{i=1}^m (y_i - w x_i). \\tag{6}\n\\end{equation}\n\nSimilarly, the cost function for multiple variables (let's say d varaibles) is: $E_{(\\mathbf{w}, b)} = E_{(w_1, w_2, ..., w_d, b)} = \\sum\\limits_{i=1}^m (y_i - \\mathbf{w}^T\\mathbf{x} - b)^2$. Combine coeficients $\\mathbf{w}$ and $b$, we obtain a new vector $\\hat{\\mathbf{w}} = (\\mathbf{w} ; b)$. The dataset $\\mathbf{XX}$ with the size $m \\times (d+1)$ can be read as \n\n\\begin{equation}\n\\mathbf{XX} = \\begin{pmatrix}\nx_{11} & x_{12} & ... & x_{1d}\\\\\nx_{21} & x_{22} & ... & x_{2d}\\\\\n\\vdots & \\vdots & \\ddots & \\vdots \\\\\nx_{m1} & x_{m2} & ... & x_{md}\n\\end{pmatrix} = \\begin{pmatrix}\n\\mathbf{x_{1}^T} & 1 \\\\\n\\mathbf{x_{2}^T} & 1 \\\\\n\\vdots & \\vdots \\\\\n\\mathbf{x_{m}^T} & 1\n\\end{pmatrix}. \\tag{7}\n\\end{equation}\n\nThe label vector is $\\mathbf{y} = (y_1; y_2; ...; y_m)$. Based on least square method, we need obtain the following\n\n\\begin{equation}\n\\mathbf{\\hat{w}}^* = \\underset{\\mathbf{\\hat{w}}}{\\arg\\min} (\\mathbf{y} - \\mathbf{XX\\hat{w}})^T (\\mathbf{y} - \\mathbf{XX\\hat{w}}). \\tag{8}\n\\end{equation}\n\nLet $E_{\\mathbf{\\hat{w}}} = (\\mathbf{y} - \\mathbf{XX\\hat{w}})^T (\\mathbf{y} - \\mathbf{XX\\hat{w}})$, then the derivative w.r.t. $\\mathbf{\\hat{w}}$ is\n\n\\begin{equation}\n\\frac{\\partial E_{\\mathbf{\\hat{w}}}}{\\partial \\mathbf{\\hat{w}}} = 2\\mathbf{XX}^T (\\mathbf{XX}\\mathbf{\\hat{w}} - \\mathbf{y}) . \\tag{9}\n\\end{equation}\n\nWe then use Gradient Descent method to iterativly update the unknown coefficients\n\n\\begin{equation}\n\\mathbf{\\hat{w}}^{(n+1)} = \\mathbf{\\hat{w}}^{(n)} - \\left ( \\alpha \\frac{\\partial E_{\\mathbf{\\hat{w}}}}{\\partial \\mathbf{\\hat{w}}} \\right)^n. \\tag{10}\n\\end{equation}\n\n***\n\n* 1.3 Hand-on example\n\n***\n\n\n```python\nimport numpy as np \nimport pandas as pd \nimport math as m\nimport matplotlib.pyplot as plt \n\ndef train_test_split(X, Y, train_size, shuffle):\n ''' Perform tran/test datasets splitting '''\n if shuffle:\n randomize = np.arange(len(X))\n np.random.shuffle(randomize)\n X = X[randomize]\n Y = Y[randomize]\n s_id = int(len(Y) * train_size)\n X_train, X_test = X[:s_id], X[s_id:]\n Y_train, Y_test = Y[:s_id], Y[s_id:]\n\n return X_train, X_test, Y_train, Y_test \n\n\ndef metric_mse(Y_label, Y_pred):\n ''' Evaluate mean squared error (MSE) '''\n return np.mean(np.power(Y_label - Y_pred, 2))\n\ndef metric_rmse(Y_label, Y_pred):\n ''' Evaluate root mean squared error (RMSE) '''\n return m.sqrt(np.mean(np.power(Y_label - Y_pred, 2)))\n\ndef readin_data(path):\n ''' Evaluate root mean squared error (RMSE) '''\n df = pd.read_csv(path) \n X = df.iloc[:,:-1].values \n Y = df.iloc[:,1].values \n return X, Y\n \ndef generate_dataset_simple(beta, n, std_dev):\n ''' Generate dataset '''\n X = np.random.rand(n)\n e = np.random.randn(n) * std_dev\n Y = X * beta + e\n X = X.reshape((n,1))\n return X, Y \n\nclass LinearRegression() : \n ''' Linear Regression model. \n Used to obtain the relationship between dependent variable and independent variables.'''\n def __init__(self, iterations, learning_rate): \n self.lr = learning_rate \n self.it = iterations \n \n def fit(self, X, Y): \n # m instances, d atrributes \n self.m, self.d = X.shape \n # weight initialization \n self.W = np.zeros(self.d+1) \n self.X = X \n self.XX = np.ones((self.m, self.d+1)) \n self.XX[:,:-1] = self.X\n self.Y = Y \n for i in range(self.it): \n self.update_weights() \n return self\n \n def update_weights(self): \n Y_pred = self.predict(self.XX) \n # calculate gradients \n dW = (self.XX.T).dot(Y_pred - self.Y)/self.m \n # update weights \n self.W = self.W - self.lr * dW \n return self\n \n def predict(self, X): \n return X.dot(self.W)\n \ndef main(): \n # Import data\n X, Y = generate_dataset_simple(10, 200, 0.5)\n # Splitting dataset into train and test set \n X_train, X_test, Y_train, Y_test = train_test_split(X, Y, train_size=.5, shuffle=False)\n # Model Learning\n model = LinearRegression(learning_rate = 0.01, iterations = 15000) \n model.fit(X_train, Y_train) \n # Model Working\n M, D = X_test.shape\n TEST = np.ones((M, D+1)) \n TEST[:,:-1] = X_test\n Y_pred = model.predict(TEST) \n # Statistics\n mse = metric_mse(Y_test, Y_pred)\n rmse = metric_rmse(Y_test, Y_pred)\n print('Coefficients: ', 'W = ', model.W[:-1], ', b = ', model.W[-1]) \n print('MSE = ', mse) \n print('RMSE = ', rmse)\n # Visualization\n plt.scatter( X_test, Y_test, color = 'black', s=8) \n plt.plot( X_test, Y_pred, color = 'red', linewidth=3) \n plt.title( 'X_test v.s. Y_test') \n plt.xlabel( 'X_test') \n plt.ylabel( 'Y_test') \n X_actual = np.array([0, 1])\n Y_actual = X_actual*10\n plt.plot(X_actual, Y_actual, 'c--', linewidth=3) \n plt.legend(('Regression Line', 'Actual Line'),loc='upper left', prop={'size': 15})\n plt.show()\n \nif __name__ == '__main__': \n main()\n```\n\n\n```python\nimport numpy as np \nimport pandas as pd \nimport math as m\nimport matplotlib.pyplot as plt \n\ndef train_test_split_po(X, Y, train_size, shuffle):\n ''' Perform tran/test datasets splitting '''\n if shuffle:\n randomize = np.arange(len(X))\n np.random.shuffle(randomize)\n X = X[randomize]\n Y = Y[randomize]\n s_id = int(len(Y) * train_size)\n X_train, X_test = X[:s_id], X[s_id:]\n Y_train, Y_test = Y[:s_id], Y[s_id:]\n Y_train = Y_train.reshape((-1, 1))\n X_train1 = np.append(X_train, Y_train, axis = 1) \n X_train1 = X_train1[np.argsort(X_train1[:, 0])]\n Y_test = Y_test.reshape((-1, 1))\n X_test1 = np.append(X_test, Y_test, axis = 1) \n X_test1 = X_test1[np.argsort(X_test1[:, 0])]\n X_train, X_test = X_train1[:,:-1], X_test1[:,:-1]\n Y_train, Y_test = X_train1[:,-1], X_test1[:,-1]\n Y_train=np.squeeze(Y_train)\n Y_test=np.squeeze(Y_test)\n return X_train, X_test, Y_train, Y_test \n\n\ndef metric_mse(Y_label, Y_pred):\n ''' Evaluate mean squared error (MSE) '''\n return np.mean(np.power(Y_label - Y_pred, 2))\n\ndef metric_rmse(Y_label, Y_pred):\n ''' Evaluate root mean squared error (RMSE) '''\n return m.sqrt(np.mean(np.power(Y_label - Y_pred, 2)))\n\ndef readin_data(path):\n ''' Evaluate root mean squared error (RMSE) '''\n df = pd.read_csv(path) \n X = df.iloc[:,:-1].values \n Y = df.iloc[:,1].values \n return X, Y\n \ndef generate_dataset_simple(beta, n, std_dev):\n ''' Generate dataset '''\n X = np.random.rand(n)\n e = np.random.randn(n) * std_dev\n Y = X * beta + e\n X = X.reshape((n,1))\n return X, Y \n\ndef generate_dataset_polynomial(beta, n, std_dev):\n ''' Generate polynomial dataset '''\n \n e = np.random.randn(n) * std_dev/n\n X = np.random.random_sample(n)\n X = np.sort(X)\n Y = 1- 6*X +36*X**2 - 53*X**3 + 22*X**5 + e\n X = X.reshape((n,1))\n return X, Y \n\n\ndef standardization(X,degree):\n \"\"\" A scaling technique where the values\n are centered around the mean with \n a unit standard deviation. \n This means that the mean of the attribute \n becomes zero and the resultant distribution \n has a unit standard deviation. \n ----------------------------------------\n degree: polynomial regression degree\n \"\"\"\n X[:, :(degree)] = (X[:, :(degree)] - np.mean(X[:, :(degree)], axis = 0))/ \\\n np.std(X[:, :(degree)], axis = 0)\n return X \n\ndef normalization(X,degree):\n \"\"\" A scaling technique in which values \n are shifted and rescaled so that they \n end up ranging between 0 and 1. \n It is also known as Min-Max scaling \n ----------------------------------------\n degree: polynomial regression degree\n \"\"\"\n X[:, :(degree)] = (X[:, :(degree)] - np.amin(X[:, :(degree)], axis = 0))/ \\\n (np.amax(X[:, :(degree)], axis = 0) - np.amin(X[:, :(degree)], axis = 0))\n return X \n\n\ndef transformation(m, X, degree):\n tmp = np.zeros([m, 1])\n for j in range(degree + 1):\n if j != 0:\n x_pow = np.power(X, j) \n tmp = np.append(tmp, x_pow.reshape(-1, 1), axis = 1) \n tmp = np.append(tmp, np.ones((m, 1)), axis = 1) \n Xt=tmp[:,1:]\n return Xt\n\ndef transformation_predict(m, X, degree):\n tmp = np.zeros([m, 1])\n for j in range(degree + 1):\n if j != 0:\n x_pow = np.power(X, j) \n tmp = np.append(tmp, x_pow.reshape(-1, 1), axis = 1) \n tmp = np.append(tmp, np.ones((m, 1)), axis = 1) \n Xt=tmp[:,1:-1]\n return Xt\n\nclass PolynomialRegression(): \n ''' Univariate Polynomial Regression model. \n Used to obtain the relationship between dependent variable and independent variables.\n -------------------------------------------------------------------------------------\n degree shall be great equal 2\n '''\n \n def __init__(self, iterations, learning_rate, degree): \n self.lr = learning_rate \n self.it = iterations \n self.de = degree \n \n def fit(self, X, Y): \n # m instances, d atrributes \n self.m, self.d = X.shape \n # weight initialization \n self.W = np.zeros(self.de+1) \n self.X = X \n self.Xt = transformation(self.m, self.X, self.de)\n self.Xs = standardization(self.Xt, self.de)\n self.Y = Y \n for i in range(self.it): \n self.update_weights() \n return self\n \n def update_weights(self): \n Y_pred = self.predict(self.X) \n # calculate gradients \n dW = (self.Xs.T).dot(Y_pred - self.Y)/self.m \n # update weights \n self.W = self.W - self.lr * dW \n return self\n \n def predict(self, X):\n self.Xt = transformation(X.shape[0], X, self.de)\n self.Xs = standardization(self.Xt, self.de)\n return self.Xs.dot(self.W)\n \ndef main(): \n # Import data\n X, Y = generate_dataset_polynomial(10, 200, 20)\n # Splitting dataset into train and test set \n X_train, X_test, Y_train, Y_test = train_test_split_po(X, Y, train_size=.5, shuffle=True)\n # Model Learning\n model = PolynomialRegression(learning_rate = 0.2, iterations = 20000, degree=5) \n model.fit(X_train, Y_train) \n print(X_test.shape)\n Y_pred = model.predict(X_test) \n print(Y_test.shape) \n print(Y_pred.shape)\n # Statistics\n mse = metric_mse(Y_test, Y_pred)\n rmse = metric_rmse(Y_test, Y_pred)\n print('Coefficients: ', 'W = ', model.W[-1], model.W[:-1]) \n print('MSE = ', mse) \n print('RMSE = ', rmse)\n # Visualization\n l1=plt.scatter(X_train, Y_train, color = 'black', s=8) \n l2=plt.scatter(X_test, Y_test, color = 'green', s=8) \n l3=plt.plot( X_test, Y_pred, color = 'red', linewidth=3) \n plt.title( 'X v.s. Y') \n plt.xlabel( 'X') \n plt.ylabel( 'Y') \n plt.legend((l1, l2),('Train Points', 'Test Points'),loc='lower left', prop={'size': 20})\n plt.show()\n \nif __name__ == '__main__': \n main()\n```\n\n***\n* 1.4 Additional notes about linear regression\n***\n\n1. When performing **Gradient Descent** approach, all features/attributes must have similar scale, or **feature scaling** is required to increase Gradient Descent convergence. We may import `from sklearn.preprocessing import StandardScaler`, then use `StandardScaler()`. (refer [feature scaling](https://www.analyticsvidhya.com/blog/2020/04/feature-scaling-machine-learning-normalization-standardization/))\n\n2. To avoid local minimum, and to quickly find the global minimum, make sure the cost function is a **convex function** ($\\displaystyle i.e., f(\\frac{a+b}{2}) \\leq \\frac{f(a)+f(b)}{2} $).\n\n3. Linear regression assumptions:\n - Exogeneity weak. Independent variable X is fixed variable, it is not random variable;\n - **Linearity**. $f$ is a linear combination of the parameters/coefficients and the independent variables X. Note that, linearity is a restriction on the parameters, not the independent variables X, e.g., polynomial regression can also be linear regression;\n - **Constant variable(Homoscedasticity)**. The variance of residual is the same for any value of independent variables;\n - **Independence**. Observations are independent of each other. The errors are uncorrelated with each other;\n - **Normality**. For any fixed value of X, Y is normally distributed.\n\n\n", "meta": {"hexsha": "9b6b8c3ca554d90184e0522b94598c5e7c251623", "size": 69570, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Regression/Regression_v2.ipynb", "max_stars_repo_name": "Sunnyfred/Machine-Learning-Models", "max_stars_repo_head_hexsha": "e7caeb84d367b1b941695ac64d94c0cca6345a80", "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": "Regression/Regression_v2.ipynb", "max_issues_repo_name": "Sunnyfred/Machine-Learning-Models", "max_issues_repo_head_hexsha": "e7caeb84d367b1b941695ac64d94c0cca6345a80", "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": "Regression/Regression_v2.ipynb", "max_forks_repo_name": "Sunnyfred/Machine-Learning-Models", "max_forks_repo_head_hexsha": "e7caeb84d367b1b941695ac64d94c0cca6345a80", "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": 127.4175824176, "max_line_length": 26132, "alphanum_fraction": 0.8289923818, "converted": true, "num_tokens": 4347, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9759464436075291, "lm_q2_score": 0.880797081106935, "lm_q1q2_score": 0.8596107788462056}} {"text": "# Zero-based indexing\n\nIn math we use 1-based indexing, but in many programming languages including Python, we use 0-based indexing.\n\nFor example, a three dimensional vector $\\vec{v} \\in \\mathbb{R}^3$ are denoted as $(v_1,v_2,v_3)$ in components form.\n\nIn Python a vector `vec` can be denoted as a list (or a Matrix), and its three components will be `vec[0]`, `vec[1]`, and `vec[2]`. The variable we to index the components is assumed to start at zero, not one.\n\n\n```python\nfrom sympy import Matrix, symbols\na, b, c = symbols('a b c')\n\nvec = Matrix([a,b,c])\nvec\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}a\\\\b\\\\c\\end{matrix}\\right]$\n\n\n\n\n```python\nvec[0]\n```\n\n\n\n\n$\\displaystyle a$\n\n\n\n\n```python\nvec[1]\n```\n\n\n\n\n$\\displaystyle b$\n\n\n\n\n```python\nvec[2]\n```\n\n\n\n\n$\\displaystyle c$\n\n\n\n\n```python\n# trying to access vec[3] leads to an error, \n# since a 3 in 0-based indexing is accessing a fourth component which doesn't exist\nvec[3]\n```\n\n## Ranges\n\n\n```python\n# a list of five numbers\nlist(range(0,5))\n# Note the second argument of the function range specifies\n# the first number not to be included in the range...\n```\n\n\n\n\n [0, 1, 2, 3, 4]\n\n\n\n\n```python\n\n```\n\n## SymPy shorthand for ranges\n\n\n```python\n# consider a 2x3 matrix\nA = Matrix([\n [1,2,3],\n [4,5,6]])\nA\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}1 & 2 & 3\\\\4 & 5 & 6\\end{matrix}\\right]$\n\n\n\n\n```python\n# can access individual entry on row i, col j using A[i-1,j-1]\nprint('top left =', A[0,0], ' top right =', A[0,2])\nprint('bottom left =', A[1,0], ' bottom right =', A[1,2])\n```\n\n top left = 1 top right = 3\n bottom left = 4 bottom right = 6\n\n\n\n```python\n# can access entire colum j using A[:,j-1]\nA[:,0]\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}1\\\\4\\end{matrix}\\right]$\n\n\n\n\n```python\n# can access entire row i using A[i-1,:]\nA[0,:]\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}1 & 2 & 3\\end{matrix}\\right]$\n\n\n\n\n```python\n# can access left 2x2 submatrix using i:j shorhand range notation\nA[0:2,0:2]\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}1 & 2\\\\4 & 5\\end{matrix}\\right]$\n\n\n\n\n```python\n# the above notation is MATLAB-like syntax sugar that translates to\nA[range(0,2),range(0,2)]\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}1 & 2\\\\4 & 5\\end{matrix}\\right]$\n\n\n\n\n```python\n\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "b56fecb50613fa9b44fc572fe764f702cee32cd0", "size": 9704, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "extra/python_basics_zero_based_indexing.ipynb", "max_stars_repo_name": "minireference/noBSLAnotebooks", "max_stars_repo_head_hexsha": "3d6acb134266a5e304cb2d51c5ac4dc3eb3949b4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 116, "max_stars_repo_stars_event_min_datetime": "2016-04-20T13:56:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T08:55:08.000Z", "max_issues_repo_path": "extra/python_basics_zero_based_indexing.ipynb", "max_issues_repo_name": "minireference/noBSLAnotebooks", "max_issues_repo_head_hexsha": "3d6acb134266a5e304cb2d51c5ac4dc3eb3949b4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-07-01T17:00:38.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-01T19:34:09.000Z", "max_forks_repo_path": "extra/python_basics_zero_based_indexing.ipynb", "max_forks_repo_name": "minireference/noBSLAnotebooks", "max_forks_repo_head_hexsha": "3d6acb134266a5e304cb2d51c5ac4dc3eb3949b4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 29, "max_forks_repo_forks_event_min_datetime": "2017-02-04T05:22:23.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-28T00:06:50.000Z", "avg_line_length": 25.8085106383, "max_line_length": 1443, "alphanum_fraction": 0.5155605936, "converted": true, "num_tokens": 743, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896780646392, "lm_q2_score": 0.9334308161220821, "lm_q1q2_score": 0.8594934606726654}} {"text": "## OSY\n\nOsyczka and Kundu used the following six-variable\ntest problem: \n\n**Definition**\n\n\\begin{equation}\n\\newcommand{\\boldx}{\\mathbf{x}}\n\\begin{array}\n\\mbox{Minimize} & f_1(\\boldx) = -\\left[25(x_1-2)^2+(x_2-2)^2 + (x_3-1)^2+(x_4-4)^2 + (x_5-1)^2\\right], \\\\\n\\mbox{Minimize} & f_2(\\boldx) = x_1^2 + x_2^2 + x_3^2 + x_4^2 + x_5^2 + x_6^2, \n\\end{array}\n\\end{equation}\n\n\\begin{equation}\n\\begin{array}\n\\mbox{\\text{subject to}} & C_1(\\boldx) \\equiv x_1 + x_2 - 2 \\geq 0, \\\\\n& C_2(\\boldx) \\equiv 6 - x_1 - x_2 \\geq 0, \\\\\n& C_3(\\boldx) \\equiv 2 - x_2 + x_1 \\geq 0, \\\\\n& C_4(\\boldx) \\equiv 2 - x_1 + 3x_2 \\geq 0, \\\\\n& C_5(\\boldx) \\equiv 4 - (x_3-3)^2 - x_4 \\geq 0, \\\\\n& C_6(\\boldx) \\equiv (x_5-3)^2 + x_6 - 4 \\geq 0, \\\\[2mm]\n& 0 \\leq x_1,x_2,x_6 \\leq 10,\\quad 1 \\leq x_3,x_5 \\leq 5,\\quad 0\\leq x_4 \\leq 6.\n\\end{array}\n\\end{equation}\n\n**Optimum**\n\nThe Pareto-optimal region is a concatenation of\nfive regions. Every region lies on some of the constraints. However, for the\nentire Pareto-optimal region, $x_4^{\\ast} = x_6^{\\ast} = 0$. \nIn table below shows the other variable values in each of the five\nregions and the constraints that are active in each region.\n\n\n\n
\n\n
\n\n**Plot**\n\n\n```python\nfrom pymoo.factory import get_problem\nfrom pymoo.util.plotting import plot\n\nproblem = get_problem(\"osy\")\nplot(problem.pareto_front(), no_fill=True)\n```\n", "meta": {"hexsha": "b5943d71c90c0b395bc0c6271c8432324c0933d1", "size": 39880, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "doc/source/problems/multi/osy.ipynb", "max_stars_repo_name": "gabicavalcante/pymoo", "max_stars_repo_head_hexsha": "1711ce3a96e5ef622d0116d6c7ea4d26cbe2c846", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2018-05-22T17:38:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-28T03:34:33.000Z", "max_issues_repo_path": "doc/source/problems/multi/osy.ipynb", "max_issues_repo_name": "gabicavalcante/pymoo", "max_issues_repo_head_hexsha": "1711ce3a96e5ef622d0116d6c7ea4d26cbe2c846", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 15, "max_issues_repo_issues_event_min_datetime": "2022-01-03T19:36:36.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T03:57:58.000Z", "max_forks_repo_path": "doc/source/problems/multi/osy.ipynb", "max_forks_repo_name": "gabicavalcante/pymoo", "max_forks_repo_head_hexsha": "1711ce3a96e5ef622d0116d6c7ea4d26cbe2c846", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-11-22T08:01:47.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-11T08:53:58.000Z", "avg_line_length": 271.2925170068, "max_line_length": 36440, "alphanum_fraction": 0.9211384152, "converted": true, "num_tokens": 595, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240073565739, "lm_q2_score": 0.9161096204605946, "lm_q1q2_score": 0.859424428324403}} {"text": "# Generating Partitions\n\nPython code for generating all integer partitions of a given integer $n > 0$\nusing different algorithms. Let's define some terminology.\n\n**Integer partition:** An integer partition is a way to write a nonnegative integer $n$\nas sum of positive integers (note that the order of the summand doesn't matter). Therefore,\n3+2 and 2+3 are the same partitions of 5. The number of partition of $n$ is denoted by\n$p(n)$. The function $p(\\cdot)$ is called the _partition function_.\n\nExample: There are 7 partitions of 5. Therefore, $p(5) = 7$.\n\n\\begin{align}\n5 &= 1 + 1 + 1 + 1 + 1 \\\\\n &= 2 + 1 + 1 + 1 \\\\\n &= 2 + 2 + 1 \\\\\n &= 3 + 1 + 1 \\\\\n &= 3 + 2 \\\\\n &= 4 + 1 \\\\\n &= 5.\n\\end{align}\n\n**Ascending/Descending composition:** Partitions are represented as an ordered list of\nsummands. Depending on whether they are ordered as weakly increasing or decreasing, it's\ncalled either an _ascending_ or _descending composition_.\n\nFor example, `[2, 2, 1]` is a descending composition, whereas, `[1, 4]` is an ascending\ncomposition.\n\n**Ordering of the output:** An algorithm to generate all integer partitions may output the partition of the given input $n > 0$ in different order. Most commonly, they output the partitions as _lexicographically increasing_ or _decreasing_ order as list of summands.\nThis is independent of whether partitions are represented as ascending or descending\ncompositions.\n\n\n```python\nimport partition\n```\n\n\n```python\ndir(partition)\n```\n\n\n\n\n ['__builtins__',\n '__doc__',\n '__file__',\n '__name__',\n '__package__',\n 'accel_asc',\n 'accel_desc',\n 'merca1',\n 'merca2',\n 'merca3',\n 'rule_asc',\n 'rule_desc',\n 'zs1',\n 'zs2']\n\n\n\n## ZS Algorithms (1998)\n\nSee [Zoghbi-Stojmenovic-1998] for reference. There are two algorithms, `zs1` and `zs2`.\n\n\n```python\ndef print_partitions(algo_name, n):\n \"\"\"Print all integer partions of n using the given algorithm.\n \n Inputs:\n n A nonnegative integer\n algo_name The algorithm name (a string)\n \"\"\"\n method = getattr(partition, algo_name)\n for p in method(n):\n print p\n \ndef count_partitions(algo_name, n):\n \"\"\"Count the number of all integer partitions of n using the given algorithm.\n\n Inputs:\n n A nonnegative integer\n algo_name The algorithm name (a string)\n \n Returns:\n The count, p(n) (integer or long).\n \"\"\"\n method = getattr(partition, algo_name)\n count = 0\n for p in method(n):\n count += 1\n return count\n\n# We will print partitions of a small number\nn = 5\n```\n\n\n```python\nprint_partitions('zs1', n)\n```\n\n [5]\n [4, 1]\n [3, 2]\n [3, 1, 1]\n [2, 2, 1]\n [2, 1, 1, 1]\n [1, 1, 1, 1, 1]\n\n\nAs we can see, `zs1` outputs partitions as descending compositions in lexicographically decreasing order.\n\n\n```python\nprint_partitions('zs2', n)\n```\n\n [1, 1, 1, 1, 1]\n [2, 1, 1, 1]\n [2, 2, 1]\n [3, 1, 1]\n [3, 2]\n [4, 1]\n [5]\n\n\n`zs2` generates partitions as descending compositions, but in lexicographically increasing order.\n\nNow let's compare the time to generate partiton of a large number (say N = 50). We won't print out the partitions, only count them.\n\nNotice that the pure python implementation is much slower than the C implementation.\n\n**TODO:** Later I will wrap the C program as a python module. Or, try other optimizations.\n\n\n```python\n# Define ans in the global scope:\nans = 0\n\n# Moderately large number to test\nN = 50\n\n# It may take a long time\n%timeit global ans; ans = count_partitions('zs1', N)\nprint ans\n```\n\n 10 loops, best of 3: 124 ms per loop\n 204226\n\n\n\n```python\n%timeit global ans; ans = count_partitions('zs2', N)\nprint ans\n```\n\n 10 loops, best of 3: 161 ms per loop\n 204226\n\n\n## Kelleher's Algorithms (2006)\n\nSee [Kelleher-2006] for reference. There are four algorithms: `rule_desc`, `rule_asc`, `accel_desc` and `accel_desc`.\n\n\n```python\nprint_partitions('rule_desc', n)\n```\n\n [5]\n [4, 1]\n [3, 2]\n [3, 1, 1]\n [2, 2, 1]\n [2, 1, 1, 1]\n [1, 1, 1, 1, 1]\n\n\nThe `rule_desc` algorithm generates partitions as descending compositions, in lexicographically decreasing order.\n\n\n```python\nprint_partitions('rule_asc', n)\n```\n\n [1, 1, 1, 1, 1]\n [1, 1, 1, 2]\n [1, 1, 3]\n [1, 2, 2]\n [1, 4]\n [2, 3]\n [5]\n\n\nThe `rule_asc` algorithm generates partitions as ascending compositions, in lexicographically increasing order.\n\n\n```python\nprint_partitions('accel_desc', n)\n```\n\n [5]\n [4, 1]\n [3, 2]\n [3, 1, 1]\n [2, 2, 1]\n [2, 1, 1, 1]\n [1, 1, 1, 1, 1]\n\n\n\n```python\nprint_partitions('accel_asc', n)\n```\n\n [1, 1, 1, 1, 1]\n [1, 1, 1, 2]\n [1, 1, 3]\n [1, 2, 2]\n [1, 4]\n [2, 3]\n [5]\n\n\nThe algorithms `accel_desc` and `accel_asc` are faster versions of `rule_desc` and `rule_asc` respectively.\n\nNow, let's compare the speed.\n\n\n```python\n%timeit global ans; ans = count_partitions('rule_desc', N)\nprint ans\n```\n\n 1 loop, best of 3: 374 ms per loop\n 204226\n\n\n\n```python\n%timeit global ans; ans = count_partitions('rule_asc', N)\nprint ans\n```\n\n 10 loops, best of 3: 159 ms per loop\n 204226\n\n\n\n```python\n%timeit global ans; ans = count_partitions('accel_desc', N)\nprint ans\n```\n\n 10 loops, best of 3: 126 ms per loop\n 204226\n\n\n\n```python\n%timeit global ans; ans = count_partitions('accel_asc', N)\nprint ans\n```\n\n 10 loops, best of 3: 124 ms per loop\n 204226\n\n\n## Merca's Algorithms\n\nSee [Merca-2012] for reference. There are three algorithms in this family: `merca1`, `merca2` and `merca3` -- all generates partitions as ascending compositions and in lexicographically increasing order.\n\n\n```python\nprint_partitions('merca1', n)\n```\n\n [1, 1, 1, 1, 1]\n [1, 1, 1, 2]\n [1, 1, 3]\n [1, 2, 2]\n [1, 4]\n [2, 3]\n [5]\n\n\n\n```python\nprint_partitions('merca2', n)\n```\n\n [1, 1, 1, 1, 1]\n [1, 1, 1, 2]\n [1, 1, 3]\n [1, 2, 2]\n [1, 4]\n [2, 3]\n [5]\n\n\n\n```python\nprint_partitions('merca3', n)\n```\n\n [1, 1, 1, 1, 1]\n [1, 1, 1, 2]\n [1, 1, 3]\n [1, 2, 2]\n [1, 4]\n [2, 3]\n [5]\n\n\n\n```python\n%timeit global ans; ans = count_partitions('merca1', N)\nprint ans\n```\n\n 1 loop, best of 3: 141 ms per loop\n 204226\n\n\n\n```python\n%timeit global ans; ans = count_partitions('merca2', N)\nprint ans\n```\n\n 10 loops, best of 3: 122 ms per loop\n 204226\n\n\n\n```python\n%timeit global ans; ans = count_partitions('merca3', N)\nprint ans\n```\n\n 10 loops, best of 3: 112 ms per loop\n 204226\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "8e3ea646045a6aca280c68caf92fd6587479eb24", "size": 13880, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "partition-examples.ipynb", "max_stars_repo_name": "deehzee/integer-partitions", "max_stars_repo_head_hexsha": "7b2d1c6261d096fa59dd02d0acb42af8d71f9cd0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2017-01-03T20:51:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-16T06:25:01.000Z", "max_issues_repo_path": "partition-examples.ipynb", "max_issues_repo_name": "deehzee/integer-partitions", "max_issues_repo_head_hexsha": "7b2d1c6261d096fa59dd02d0acb42af8d71f9cd0", "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": "partition-examples.ipynb", "max_forks_repo_name": "deehzee/integer-partitions", "max_forks_repo_head_hexsha": "7b2d1c6261d096fa59dd02d0acb42af8d71f9cd0", "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": 21.3538461538, "max_line_length": 275, "alphanum_fraction": 0.4804034582, "converted": true, "num_tokens": 2152, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096090086367, "lm_q2_score": 0.9381240134113843, "lm_q1q2_score": 0.8594244231279163}} {"text": "# Sympy\n\n## What is Symbolic Computation? \n\nSymbolic computation deals with the computation of mathematical objects\nsymbolically. This means that the mathematical objects are represented\nexactly, not approximately, and mathematical expressions with unevaluated\nvariables are left in symbolic form.\n\nLet’s take an example. Say we wanted to use the built-in Python functions to\ncompute square roots. We might do something like this\n\n\n```\nimport math\nmath.sqrt(9)\n```\n\n\n\n\n 3.0\n\n\n\n9 is a perfect square, so we got the exact answer, 3. But suppose we computed\nthe square root of a number that isn’t a perfect square\n\n\n```\nmath.sqrt(8)\n```\n\n\n\n\n 2.8284271247461903\n\n\n\nHere we got an approximate result. 2.82842712475 is not the exact square root\nof 8 (indeed, the actual square root of 8 cannot be represented by a finite\ndecimal, since it is an irrational number). If all we cared about was the\ndecimal form of the square root of 8, we would be done.\n\nBut suppose we want to go further. Recall that $\\sqrt{8} = \\sqrt{4\\cdot 2} =\n2\\sqrt{2}$. We would have a hard time deducing this from the above result.\nThis is where symbolic computation comes in. With a symbolic computation\nsystem like SymPy, square roots of numbers that are not perfect squares are\nleft unevaluated by default\n\n\n```\nimport sympy\nsympy.sqrt(8)\n```\n\n\n\n\n 2*sqrt(2)\n\n\n\nFurthermore—and this is where we start to see the real power of symbolic\ncomputation—symbolic results can be symbolically simplified\n\n## A more interesting example\n\nThe above example starts to show how we can manipulate irrational numbers\nexactly using SymPy. But it is much more powerful than that. Symbolic\ncomputation systems (which by the way, are also often called computer algebra\nsystems, or just CASs) such as SymPy are capable of computing symbolic\nexpressions with variables.\n\nLet us define a symbolic expression, representing the mathematical expression\n\n\n```\nfrom sympy import symbols\nx, y = symbols('x y')\nexpr = x + 2*y\nexpr\n```\n\n\n\n\n x + 2*y\n\n\n\nNote that we wrote `x + 2*y` just as we would if `x` and `y` were\nordinary Python variables. But in this case, instead of evaluating to\nsomething, the expression remains as just `x + 2*y`. Now let us play around\nwith it:\n\n\n```\nexpr + 1\n```\n\n\n\n\n x + 2*y + 1\n\n\n\n\n```\nexpr - x\n```\n\n\n\n\n 2*y\n\n\n\n\n```\nx*expr\n```\n\n\n\n\n x*(x + 2*y)\n\n\n\nNotice something in the above example. When we typed `expr`, we did not\nget $x + 2 y-x$, but rather just $2y$. The `x` and the `-x`\nautomatically canceled one another. This is similar to how `sqrt(8)`\nautomatically turned into `2*sqrt(2)` above. This isn’t always the case in\nSymPy, however:\n\n\n```\nfrom sympy import expand, factor\nexpanded = expand(x*expr)\nexpanded\n```\n\n\n\n\n x**2 + 2*x*y\n\n\n\n\n```\nfactor(expanded)\n```\n\n\n\n\n x*(x + 2*y)\n\n\n\n# The Power of Symbolic Computation\n\nThe real power of a symbolic computation system such as SymPy is the ability\nto do all sorts of computations symbolically. SymPy can simplify expressions,\ncompute derivatives, integrals, and limits, solve equations, work with\nmatrices, and much, much more, and do it all symbolically. It includes\nmodules for plotting, printing (like 2D pretty printed output of math\nformulas, or $\\mathrm{\\LaTeX}$, code generation, physics, statistics, combinatorics,\nnumber theory, geometry, logic, and more. Here is a small sampling of the sort\nof symbolic power SymPy is capable of, to whet your appetite.\n\n\n```\nfrom sympy import *\nx, t, z, nu = symbols('x t z nu')\n```\n\n\n```\n#This will make things look pretty\ninit_printing(use_unicode=True)\n```\n\n*Take* the derivative of $sin{(x)}e^x$\n\n\n```\ndiff(sin(x)*exp(x), x)\n```\n\nCompute $\\int(e^x\\sin{(x)} + e^x\\cos{(x)})\\,dx$.\n\n\n```\nintegrate(exp(x)*sin(x) + exp(x)*cos(x), x)\n```\n\nCompute $\\int_{-\\infty}^\\infty \\sin{(x^2)}\\,dx$\n\n\n```\nintegrate(sin(x**2), (x, -oo, oo))\n```\n\nFind $\\lim_{x\\to 0}\\frac{\\sin{(x)}}{x}$\n\n\n```\nlimit(sin(x)/x, x, 0)\n```\n\nSolve $x^2 - 2 = 0$\n\n\n```\nsolve(x**2 - 2, x)\n```\n\nSolve the differential equation $y'' - y = e^t$\n\n\n```\ny = Function('y')\ndsolve(Eq(y(t).diff(t, t) - y(t), exp(t)), y(t))\n```\n\n[link text](https://)Print$\\int_{0}^{\\pi} \\cos^{2}{\\left (x \\right )}\\, dx$ in $\\mathrm{\\LaTeX}$\n\n\n```\nlatex(Integral(cos(x)**2, (x, 0, pi)))\n```\n\n\n\n\n '\\\\int_{0}^{\\\\pi} \\\\cos^{2}{\\\\left (x \\\\right )}\\\\, dx'\n\n\n\n# Why Sympy\n\n\n1. It is free and open source, you can even use it as part of something you sell\n2. SymPy is written entirely in Python, and is executed entirely in Python. Thus it is interoperable\n3. It is very lightweight to download and install. Other packages might be Gb in size. \n4. It can be used as a library. There is an Application Programming Interface or API for use with other tools.\n\n\n\n# Series Expansion:\nSymPy can compute asymptotic series expansions of functions around a point. To\ncompute the expansion of $f(x)$ around the point $x = x_0$ terms of order\n$x^n$ use `f(x).series(x,x0,n)`.`x0` and `n` can be omitted, in\nwhich case the defaults `x0=0` and `n=6` will be used.\n\n\n```\nexpr = exp(sin(x))\nexpr.series(x,0,4)\n```\n\nThe $O\\left(x^4\\right)$ term at the end represents the Landau order term at\n`x=0` (not to be confused with big O notation used in computer science, which\ngenerally represents the Landau order term at $x=\\infty$. It means that all\nx terms with power greater than or equal to $x^4$ are omitted. Order terms\ncan be created and manipulated outside of `series`. They automatically\nabsorb higher order terms.\n\n\n```\nx + x**3 + x**6 + O(x**4)\n```\n\n# Lambdafy\n\nThe easiest way to convert a SymPy expression to an expression that can be numerically evaluated is to use the `lambdify` function. `lambdify` acts like a `lambda` function, except it converts the SymPy names to the names of the given numerical library, usually NumPy. For example\n\n`Lambda` functions are just small anonymous functions\n\n\n```\nimport numpy as np\nx = lambda a : a + 10\nprint(x(np.arange(10)))\n```\n\n [10 11 12 13 14 15 16 17 18 19]\n\n\n\n```\nx = lambda a, b : a * b\nprint(x(5,6))\n```\n\n 30\n\n\n\n```\ndef myfunc(n):\n return lambda a : a * n\n\nmytripler = myfunc(3)\n\nprint(mytripler(11))\n```\n\n 33\n\n\n\n```\na = np.arange(10)\nexpr = sin(x)\n\nf = lambdify(x, expr)\n\nf(a)\n\n```\n\n\n\n\n array([ 0. , 0.84147098, 0.90929743, 0.14112001, -0.7568025 ,\n -0.95892427, -0.2794155 , 0.6569866 , 0.98935825, 0.41211849])\n\n\n", "meta": {"hexsha": "9c92294c955db87e977bbd0b7e6ca0067b6728cd", "size": 38707, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "lectures/11_AdvancedSympy/Sympy.ipynb", "max_stars_repo_name": "jagar2/Summer_2020_MAT-395-495_Scientific-Data-Analysis-and-Computing", "max_stars_repo_head_hexsha": "e4b831460bddd34e7ad1d8888327c8d85b80e35e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-11-10T15:34:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-10T15:34:37.000Z", "max_issues_repo_path": "lectures/11_AdvancedSympy/Sympy.ipynb", "max_issues_repo_name": "jagar2/Summer_2020_MAT-395-495_Scientific-Data-Analysis-and-Computing", "max_issues_repo_head_hexsha": "e4b831460bddd34e7ad1d8888327c8d85b80e35e", "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/11_AdvancedSympy/Sympy.ipynb", "max_forks_repo_name": "jagar2/Summer_2020_MAT-395-495_Scientific-Data-Analysis-and-Computing", "max_forks_repo_head_hexsha": "e4b831460bddd34e7ad1d8888327c8d85b80e35e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-08-06T15:11:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-05T20:21:09.000Z", "avg_line_length": 38.210266535, "max_line_length": 2678, "alphanum_fraction": 0.5995814711, "converted": true, "num_tokens": 1881, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009503523291, "lm_q2_score": 0.9390248234010296, "lm_q1q2_score": 0.85911470333403}} {"text": "# The Linear Model II\n\n
\n\n* linear classification | classification error | perceptron learning algorithm, pocket algorithm, ...\n* linear regression | squared error | pseudo-inverse, ...\n* third linear model (logistic regression) | cross-entropy error | gradient descent, ...\n* nonlinear transforms \n\n
\n\n## 1. The Logistic Regression Linear Model\n\n### 1.1 Hypothesis Functions\n\nIn the case of linear models, inputs are combined linearly using weights, and summed into a signal, $s$:\n\n$$s = \\sum\\limits_{i=0}^d w_i x_i$$\n\nNext, the signal passes through a function, given by:\n\n* **Linear classification**: $h\\left(\\mathbf{x}\\right) = \\text{sign}\\left(s\\right)$\n* **Linear regression**: $h\\left(\\mathbf{x}\\right) = s$\n* **Logistic regression**: $h\\left(\\mathbf{x}\\right) = \\theta\\left(s\\right)$\n\nFor logistic regression, we use a \"soft threshold\", by choosing a logistic function, $\\theta$, that has a sigmoidal shape. The sigmoidal function can take on various forms, such as the following:\n\n$$\\theta\\left(s\\right) = \\frac{e^s}{1+e^s}$$\n\nThis model implements a probability that has a genuine probability interpretation.\n\n### 1.2 Likelihood Measure and Probabilistic Connotations\n\nThe likelihood of a dataset, $\\mathcal{D} = \\left(\\mathbf{x_1},y_1\\right), \\dots, \\left(\\mathbf{x_N},y_N\\right)$, that we wish to maximize is given by:\n\n$$\\prod\\limits_{n=1}^N P\\left(y_n | \\mathbf{x_n}\\right) = \\prod\\limits_{n=1}^N \\theta\\left(y_n \\mathbf{w^T x_n}\\right)$$\n\nIt is possible to derive an error measure (that would *maximise* the above likelihood measure), which **has a probabilistic connotation**, and is called the in-sample \"cross-entropy\" error. It is based on assuming the hypothesis (of the logistic regression function) as the target function:\n\n$$E_{in}\\left(\\mathbf{w}\\right) = \\frac{1}{N}\\sum\\limits_{n=1}^N \\ln\\left[1 + \\exp\\left(-y_n \\mathbf{w^T x_n}\\right)\\right]$$\n\n$$E_{in}\\left(\\mathbf{w}\\right) = \\frac{1}{N}\\sum\\limits_{n=1}^N e\\left[ h\\left(\\mathbf{x_n}\\right), y_n \\right]$$\n\nWhile the above does not have a closed form solution, it is a *convex function* and therefore we can find the weights corresponding to the minimum of the above error measure using various techniques. Such techniques include gradient descent (and its variations, such as stochastic gradient descent and batch gradient descent) and there are others which make use of second order derivatives (such as the conjugate gradient method) or [Hessians](https://en.wikipedia.org/wiki/Hessian_matrix).\n\n### 1.3 Libraries Used\n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.optimize import minimize\nfrom numpy.random import permutation\nfrom sympy import var, diff, exp, latex, factor, log, simplify\nfrom IPython.display import display, Math, Latex\n%matplotlib inline\n```\n\n### 1.4 Gradient Descent for Logistic Regression\n\n#### 1.4.1 Gradient of the Cost Function - Derivation (using Sympy)\nThe Python package, `sympy`, can be used to obtain the form for the gradient of the cost function in logistic regression:\n\n\n```python\nvar('x y w')\nlogistic_cost = log(1 + exp(-y*w*x))\ndisplay(Math(latex(logistic_cost)))\n```\n\n\n$$\\log{\\left (1 + e^{- w x y} \\right )}$$\n\n\n\n```python\nlogistic_grad = logistic_cost.diff(w)\ndisplay(Math(latex(logistic_grad)))\ndisplay(Math(latex(simplify(logistic_grad))))\n```\n\n\n$$- \\frac{x y e^{- w x y}}{1 + e^{- w x y}}$$\n\n\n\n$$- \\frac{x y}{e^{w x y} + 1}$$\n\n\n#### 1.4.2 Gradient Descent Algorithm\n\nThe gradient descent algorithm is a means to find the minimum of a function,\nstarting from some initial weight, $\\mathbf{w}()$.\nThe weights are adjusted at each iteration, by moving them in the direction of the **steepest descent** ($\\nabla E_{in}$). A **learning rate**, $\\eta$, is used to scale the gradient, $\\nabla E_{in}$.\n\n$$\\mathbf{w}(t+1) = \\mathbf{w}(t) - \\eta\\nabla E_{in}$$\n\nFor the case of logistic regression, the gradient of the error measure with respect to the weights, is calculated as:\n\n$$\\nabla E_{in}\\left(\\mathbf{w}\\right) = -\\frac{1}{N}\\sum\\limits_{n=1}^N \\frac{y_n\\mathbf{x_N}}{1 + \\exp\\left(y_n \\mathbf{w^T}(t)\\mathbf{x_n}\\right)}$$\n\n## 2. Linear Regression Error with Noisy Targets\n\n### 2.1 Effect of Sample Size on In-Sample Errors \n\nConsider a noisy target, $y=\\mathbf{w^{*T}x} + \\epsilon$ where $\\epsilon$ is a noise term with zero mean and variance, $\\sigma^2$\nThe in-sample error on a training set, $\\mathcal{D}$,\n\n$$\\mathbb{E}_\\mathcal{D}\\left[E_{in}\\left(\\mathbf{w_{lin}}\\right)\\right] = \\sigma^2\\left(1 - \\frac{d+1}{N}\\right)$$\n\n\n```python\ndef in_sample_err(N, sigma = 0.1, d = 8):\n return (sigma**2)*(1 - (d+1)/N)\n```\n\n\n```python\nN_arr = [10, 25, 100, 500, 1000]\nerr = [ in_sample_err(N) for N in N_arr ]\nfor i in range(len(N_arr)):\n print(\"N = {:4}, E_in = {}\".format(N_arr[i],err[i]))\n```\n\n N = 10, E_in = 0.001\n N = 25, E_in = 0.006400000000000001\n N = 100, E_in = 0.009100000000000002\n N = 500, E_in = 0.009820000000000002\n N = 1000, E_in = 0.009910000000000002\n\n\nHere, we can see that, *for a noisy target*, as the number of examples, $N$, increases, the in-sample error also increases.\n\n\n```python\nresult = minimize(lambda x: (0.008-in_sample_err(x))**2, x0=[20.0], tol=1e-11)\nif result.success is True:\n N = result.x[0]\n print(\"N = {}\".format(N))\n print(\"err({}) = {}\".format(int(N),in_sample_err(int(N))))\n print(\"err({}) = {}\".format(int(N+1),in_sample_err(int(N+1))))\n```\n\n N = 44.99981844579476\n err(44) = 0.007954545454545455\n err(45) = 0.008000000000000002\n\n\nIf we desire an in-sample error of not more than 0.008, then the maximum number of examples we should have is 44.\n\n## 3. Non-linear Transforms\n\n### 3.1 Background\n\nConsider the linear transform $z_i = \\phi_i\\left(\\mathbf{x}\\right)$ or $\\mathbf{z} = \\Phi\\left(\\mathbf{x}\\right)$, with the following mapping:\n\n$$\\mathbf{x} = \\left(x_0, x_1, \\dots, x_d\\right) \\rightarrow \\mathbf{z} = \\left(z_0, z_1, \\dots, z_{\\tilde d}\\right)$$\n\nThe final hypothesis, $\\mathcal{X}$ space is:\n\n$$g\\left(\\mathbf{x}\\right) = \\mathbf{\\tilde w^T} \\Phi\\left(\\mathbf{x}\\right)$$\n\n$$g\\left(\\mathbf{x}\\right) = \\left(w_0, w_1, w_2\\right) \\left(\\begin{array}{c}1\\\\x_1^2\\\\x_2^2\\end{array}\\right) = w_0 + w_1 x_1^2 + w_2 x_2^2$$\n\nThe non-linear transforms are implemented in the subroutine `add_nonlinear_features()` below. The contour plots corresponding to the non-linear transforms are implemented in `plot_data_nonlinear()`.\n\n\n```python\ndef add_nonlinear_features(X):\n N = X.shape[0]\n X = np.hstack((X,np.zeros((N,3))))\n X[:,3] = X[:,1]*X[:,2]\n X[:,4] = X[:,1]**2\n X[:,5] = X[:,2]**2\n return(X)\n\ndef plot_data_nonlinear(fig,plot_id,w_arr,w_colors,titles):\n p = 2.0\n x1 = np.linspace(-p,p,100)\n x2 = np.linspace(-p,p,100)\n X1,X2 = np.meshgrid(x1,x2)\n X1X2 = X1*X2\n X1_sq= X1**2\n X2_sq= X2**2\n\n for i,w in enumerate(w_arr):\n Y = w[0] + w[1]*X1 + w[2]*X2 + w[3]*X1X2 + \\\n w[4]*X1_sq + w[5]*X2_sq\n ax = fig.add_subplot(plot_id[i])\n cp0 = ax.contour(X1,X2,Y,1,linewidth=4, levels=[0.0],\n colors=w_colors[i])\n ax.clabel(cp0, inline=True, fontsize=14)\n #cp1 = ax.contour(X1,X2,Y,N=1,linewidth=4, levels=[-1.0, 1.0],\n # linestyles='dashed', colors=w_colors[i], alpha=0.3)\n cp1 = ax.contourf(X1,X2,Y,1,linewidth=4, linestyles='dashed', alpha=0.8)\n ax.clabel(cp1, inline=True, fontsize=14)\n\n plt.colorbar(cp1)\n ax.set_title(titles[i])\n #ax.set_axis_off() #ax.axis('off')\n ax.axes.xaxis.set_ticks([])\n ax.axes.yaxis.set_ticks([])\n```\n\nHere we wish to consider the effects of the sign of the weights $\\tilde w_1, \\tilde w_2$ on the decision boundary. For simplicity, we choose the weights from [-1, 0, 1], as similar shapes would be obtained if the set of weights were scaled to something like [-2, 0, 2].\n\n\n```python\nw1 = np.array([ 1, 0, 0, 0, 0.0, 1.0])\nw2 = np.array([ 1, 0, 0, 0, 1.0, 0.0])\nw3 = np.array([ 1, 0, 0, 0, 1.0, 1.0])\nw4 = np.array([ 1, 0, 0, 0,-1.0, 1.0])\nw5 = np.array([ 1, 0, 0, 0, 1.0,-1.0])\nw_arr = [w1,w2,w3,w4,w5]\nw_colors = ['red','orange','green','blue','black']\ntitles = ['(a) $w_1$ = 0, $w_2$ > 0',\n '(b) $w_1$ > 0, $w_2$ = 0',\n '(c) $w_1$ > 0, $w_2$ > 0',\n '(d) $w_1$ < 0, $w_2$ > 0',\n '(e) $w_1$ > 0, $w_2$ < 0']\nplot_id_arr = [ 231, 232, 233, 234, 235 ]\nfig = plt.figure(figsize=(12,7))\nplot_data_nonlinear(fig,plot_id_arr,w_arr,w_colors,titles)\n```\n\nIn the second last example, $\\tilde w_1 <0, \\tilde w_2 > 0$, (with $x_0 = 1$), we have:\n\n$$\\mathbf{x} = \\left(1, x_1, x_2\\right) \\rightarrow \\mathbf{z} = \\left(1, x_1^2, x_2^2\\right)$$\n\n$$g\\left(\\mathbf{x}\\right) = 1 - x_1^2 + x_2^2$$\n\n## 4. Gradient Descent\n\n### 4.1 Gradient Descent Example Using Sympy\n\nThis example provides a demonstration of how the package `sympy` can be used to find the gradient of an arbitrary function, and perform gradient descent to the minimum of the function.\n\nOur arbitrary function in this case is:\n\n$$E\\left(u,v\\right) = \\left(ue^v -2ve^{-u}\\right)^2$$\n\n\n```python\nvar('u v')\nexpr = (u*exp(v) -2*v*exp(-u))**2\ndisplay(Math(latex(expr)))\n```\n\n\n$$\\left(u e^{v} - 2 v e^{- u}\\right)^{2}$$\n\n\nThe partial derivative of the function, $E$, with respect to $u$ is:\n\n\n```python\nderivative_u = expr.diff(u)\ndisplay(Math(latex(derivative_u)))\ndisplay(Math(latex(factor(derivative_u))))\n```\n\n\n$$\\left(u e^{v} - 2 v e^{- u}\\right) \\left(4 v e^{- u} + 2 e^{v}\\right)$$\n\n\n\n$$2 \\left(2 v + e^{u} e^{v}\\right) \\left(u e^{u} e^{v} - 2 v\\right) e^{- 2 u}$$\n\n\nThe partial derivative of the function, $E$, with respect to $v$ is:\n\n\n```python\nderivative_v = expr.diff(v)\ndisplay(Math(latex(derivative_v)))\ndisplay(Math(latex(factor(derivative_v))))\n```\n\n\n$$\\left(u e^{v} - 2 v e^{- u}\\right) \\left(2 u e^{v} - 4 e^{- u}\\right)$$\n\n\n\n$$2 \\left(u e^{u} e^{v} - 2\\right) \\left(u e^{u} e^{v} - 2 v\\right) e^{- 2 u}$$\n\n\nNext, the functions to implement the gradient descent are implemented as follows. In the first case, `err_gradient()`, the derivatives are specified in the code. In the second case, `err_gradient2()`, the derivatives are calculated using `sympy + evalf`:\n\n\n```python\ndef err(uv):\n u = uv[0]\n v = uv[1]\n ev = np.exp(v)\n e_u= np.exp(-u)\n return (u*ev - 2.0*v*e_u)**2\n\ndef err_gradient(uv):\n u = uv[0]\n v = uv[1]\n ev = np.exp(v)\n e_u= np.exp(-u)\n return np.array([ 2.0*(ev + 2.0*v*e_u)*(u*ev - 2.0*v*e_u),\n 2.0*(u*ev - 2.0*e_u)*(u*ev - 2.0*v*e_u) ])\ndef err_gradient2(uv):\n du = derivative_u.subs(u,uv[0]).subs(v,uv[1]).evalf()\n dv = derivative_v.subs(u,uv[0]).subs(v,uv[1]).evalf()\n return np.array([ du, dv ], dtype=float)\n```\n\nTo follow the gradient to the function minimum, we can either use $\\nabla E$ in the gradient descent approach, or we can alternate between the individual derivatives, $\\frac{\\partial E}{\\partial u}$ and $\\frac{\\partial E}{\\partial v}$ in the coordinate descent approach. \n\n\n```python\ndef gradient_descent(x0, err, d_err, eta=0.1):\n x = x0\n for i in range(20):\n e = err(x)\n de = d_err(x)\n print(\"%2d: x = (%8.5f, %8.5f) | err' = (%8.4f, %8.4f) | err = %.3e\" %\n (i,x[0],x[1],de[0],de[1],e))\n if e < 1e-14:\n break\n x = x - eta*de\n\ndef coordinate_descent(x0, err, d_err, eta=0.1):\n x = x0\n for i in range(15):\n # Step 1: Move along the u-coordinate\n e = err(x)\n de = d_err(x)\n print(\"%2d: x = (%8.5f, %8.5f) | err' = (%8.4f, --------) | err = %.3e\" %\n (i,x[0],x[1],de[0],e))\n x[0] = x[0] - eta*de[0]\n if e < 1e-14: break\n \n # Step 2: Move along the v-coordinate\n e = err(x)\n de = d_err(x)\n print(\"%2d: x = (%8.5f, %8.5f) | err' = (--------, %8.4f) | err = %.3e\" %\n (i,x[0],x[1],de[1],e))\n x[1] = x[1] - eta*de[1]\n if e < 1e-14: break\n```\n\n\n```python\nx0 = np.array([1.0,1.0])\ngradient_descent(x0=x0, err=err, d_err=err_gradient)\n```\n\n 0: x = ( 1.00000, 1.00000) | err' = ( 13.6954, 7.8608) | err = 3.930e+00\n 1: x = (-0.36954, 0.21392) | err' = ( -4.0006, 7.2185) | err = 1.160e+00\n 2: x = ( 0.03052, -0.50793) | err' = ( -0.7700, -3.8572) | err = 1.007e+00\n 3: x = ( 0.10752, -0.12221) | err' = ( 0.4188, -1.0704) | err = 9.901e-02\n 4: x = ( 0.06564, -0.01517) | err' = ( 0.1780, -0.3366) | err = 8.661e-03\n 5: x = ( 0.04784, 0.01849) | err' = ( 0.0284, -0.0501) | err = 1.818e-04\n 6: x = ( 0.04500, 0.02350) | err' = ( 0.0024, -0.0043) | err = 1.297e-06\n 7: x = ( 0.04476, 0.02392) | err' = ( 0.0002, -0.0003) | err = 7.292e-09\n 8: x = ( 0.04474, 0.02396) | err' = ( 0.0000, -0.0000) | err = 4.010e-11\n 9: x = ( 0.04474, 0.02396) | err' = ( 0.0000, -0.0000) | err = 2.202e-13\n 10: x = ( 0.04474, 0.02396) | err' = ( 0.0000, -0.0000) | err = 1.209e-15\n\n\n\n```python\ngradient_descent(x0=x0, err=err, d_err=err_gradient2)\n```\n\n 0: x = ( 1.00000, 1.00000) | err' = ( 13.6954, 7.8608) | err = 3.930e+00\n 1: x = (-0.36954, 0.21392) | err' = ( -4.0006, 7.2185) | err = 1.160e+00\n 2: x = ( 0.03052, -0.50793) | err' = ( -0.7700, -3.8572) | err = 1.007e+00\n 3: x = ( 0.10752, -0.12221) | err' = ( 0.4188, -1.0704) | err = 9.901e-02\n 4: x = ( 0.06564, -0.01517) | err' = ( 0.1780, -0.3366) | err = 8.661e-03\n 5: x = ( 0.04784, 0.01849) | err' = ( 0.0284, -0.0501) | err = 1.818e-04\n 6: x = ( 0.04500, 0.02350) | err' = ( 0.0024, -0.0043) | err = 1.297e-06\n 7: x = ( 0.04476, 0.02392) | err' = ( 0.0002, -0.0003) | err = 7.292e-09\n 8: x = ( 0.04474, 0.02396) | err' = ( 0.0000, -0.0000) | err = 4.010e-11\n 9: x = ( 0.04474, 0.02396) | err' = ( 0.0000, -0.0000) | err = 2.202e-13\n 10: x = ( 0.04474, 0.02396) | err' = ( 0.0000, -0.0000) | err = 1.209e-15\n\n\nHere, we can see that in both approaches of gradient descent above, it takes about 10 iterations to get the error below $10^{-14}$.\n\nFor comparison, an attempt to find the roots of the minimum via [`scipy.optimize.minimize`](https://docs.scipy.org/doc/scipy-0.18.1/reference/generated/scipy.optimize.minimize.html) was made, but it yielded a different result. This could be due to the fact that another method was used (in this case, conjugate gradient). At the moment, `scipy.optimize.minimize`, does not appear to have a gradient descent implementation.\n\n\n```python\nerr_fn = lambda x: (x[0]*np.exp([1]) - 2.0*x[1]*np.exp(-x[0]))**2\nresult = minimize(err_fn, x0=np.array([1.0,1.0]), tol=1e-5, method='CG')\nif result.success is True:\n x = result.x\n print(\"x = {}\".format(x))\n print(\"f = {}\".format(result.fun))\n print(\"evalf = {}\".format(expr.subs(u,x[0]).subs(v,x[1]).evalf()))\n```\n\n x = [ 0.49714221 1.11083931]\n f = 1.7782471701861512e-17\n evalf = 0.0250910775449603\n\n\n### 4.2 Coordinate Descent\n\nUsing the coordinate descent approach, the error minimization takes place more slowly. Even after 15 iterations, the error remains at only ~0.15, regardless of implementation.\n\n\n```python\nx0 = np.array([1.0,1.0])\ncoordinate_descent(x0=x0, err=err, d_err=err_gradient)\n```\n\n 0: x = ( 1.00000, 1.00000) | err' = ( 13.6954, --------) | err = 3.930e+00\n 0: x = (-0.36954, 1.00000) | err' = (--------, 30.3992) | err = 1.520e+01\n 1: x = (-0.36954, -2.03992) | err' = (-67.6202, --------) | err = 3.429e+01\n 1: x = ( 6.39247, -2.03992) | err' = (--------, 1.3878) | err = 7.024e-01\n 2: x = ( 6.39247, -2.17870) | err' = ( 0.1548, --------) | err = 5.341e-01\n 2: x = ( 6.37700, -2.17870) | err' = (--------, 1.0477) | err = 5.318e-01\n 3: x = ( 6.37700, -2.28347) | err' = ( 0.1239, --------) | err = 4.327e-01\n 3: x = ( 6.36461, -2.28347) | err' = (--------, 0.8474) | err = 4.311e-01\n 4: x = ( 6.36461, -2.36821) | err' = ( 0.1033, --------) | err = 3.650e-01\n 4: x = ( 6.35428, -2.36821) | err' = (--------, 0.7138) | err = 3.640e-01\n 5: x = ( 6.35428, -2.43959) | err' = ( 0.0886, --------) | err = 3.165e-01\n 5: x = ( 6.34542, -2.43959) | err' = (--------, 0.6178) | err = 3.157e-01\n 6: x = ( 6.34542, -2.50138) | err' = ( 0.0774, --------) | err = 2.798e-01\n 6: x = ( 6.33768, -2.50138) | err' = (--------, 0.5452) | err = 2.792e-01\n 7: x = ( 6.33768, -2.55590) | err' = ( 0.0687, --------) | err = 2.510e-01\n 7: x = ( 6.33081, -2.55590) | err' = (--------, 0.4884) | err = 2.505e-01\n 8: x = ( 6.33081, -2.60473) | err' = ( 0.0617, --------) | err = 2.278e-01\n 8: x = ( 6.32464, -2.60473) | err' = (--------, 0.4425) | err = 2.274e-01\n 9: x = ( 6.32464, -2.64898) | err' = ( 0.0559, --------) | err = 2.087e-01\n 9: x = ( 6.31904, -2.64898) | err' = (--------, 0.4047) | err = 2.083e-01\n 10: x = ( 6.31904, -2.68945) | err' = ( 0.0511, --------) | err = 1.926e-01\n 10: x = ( 6.31393, -2.68945) | err' = (--------, 0.3730) | err = 1.923e-01\n 11: x = ( 6.31393, -2.72675) | err' = ( 0.0470, --------) | err = 1.789e-01\n 11: x = ( 6.30923, -2.72675) | err' = (--------, 0.3460) | err = 1.787e-01\n 12: x = ( 6.30923, -2.76135) | err' = ( 0.0435, --------) | err = 1.671e-01\n 12: x = ( 6.30488, -2.76135) | err' = (--------, 0.3227) | err = 1.670e-01\n 13: x = ( 6.30488, -2.79361) | err' = ( 0.0404, --------) | err = 1.569e-01\n 13: x = ( 6.30084, -2.79361) | err' = (--------, 0.3024) | err = 1.567e-01\n 14: x = ( 6.30084, -2.82385) | err' = ( 0.0377, --------) | err = 1.478e-01\n 14: x = ( 6.29708, -2.82385) | err' = (--------, 0.2845) | err = 1.477e-01\n\n\n\n```python\nx0 = np.array([1.0,1.0])\ncoordinate_descent(x0=x0, err=err, d_err=err_gradient2)\n```\n\n 0: x = ( 1.00000, 1.00000) | err' = ( 13.6954, --------) | err = 3.930e+00\n 0: x = (-0.36954, 1.00000) | err' = (--------, 30.3992) | err = 1.520e+01\n 1: x = (-0.36954, -2.03992) | err' = (-67.6202, --------) | err = 3.429e+01\n 1: x = ( 6.39247, -2.03992) | err' = (--------, 1.3878) | err = 7.024e-01\n 2: x = ( 6.39247, -2.17870) | err' = ( 0.1548, --------) | err = 5.341e-01\n 2: x = ( 6.37700, -2.17870) | err' = (--------, 1.0477) | err = 5.318e-01\n 3: x = ( 6.37700, -2.28347) | err' = ( 0.1239, --------) | err = 4.327e-01\n 3: x = ( 6.36461, -2.28347) | err' = (--------, 0.8474) | err = 4.311e-01\n 4: x = ( 6.36461, -2.36821) | err' = ( 0.1033, --------) | err = 3.650e-01\n 4: x = ( 6.35428, -2.36821) | err' = (--------, 0.7138) | err = 3.640e-01\n 5: x = ( 6.35428, -2.43959) | err' = ( 0.0886, --------) | err = 3.165e-01\n 5: x = ( 6.34542, -2.43959) | err' = (--------, 0.6178) | err = 3.157e-01\n 6: x = ( 6.34542, -2.50138) | err' = ( 0.0774, --------) | err = 2.798e-01\n 6: x = ( 6.33768, -2.50138) | err' = (--------, 0.5452) | err = 2.792e-01\n 7: x = ( 6.33768, -2.55590) | err' = ( 0.0687, --------) | err = 2.510e-01\n 7: x = ( 6.33081, -2.55590) | err' = (--------, 0.4884) | err = 2.505e-01\n 8: x = ( 6.33081, -2.60473) | err' = ( 0.0617, --------) | err = 2.278e-01\n 8: x = ( 6.32464, -2.60473) | err' = (--------, 0.4425) | err = 2.274e-01\n 9: x = ( 6.32464, -2.64898) | err' = ( 0.0559, --------) | err = 2.087e-01\n 9: x = ( 6.31904, -2.64898) | err' = (--------, 0.4047) | err = 2.083e-01\n 10: x = ( 6.31904, -2.68945) | err' = ( 0.0511, --------) | err = 1.926e-01\n 10: x = ( 6.31393, -2.68945) | err' = (--------, 0.3730) | err = 1.923e-01\n 11: x = ( 6.31393, -2.72675) | err' = ( 0.0470, --------) | err = 1.789e-01\n 11: x = ( 6.30923, -2.72675) | err' = (--------, 0.3460) | err = 1.787e-01\n 12: x = ( 6.30923, -2.76135) | err' = ( 0.0435, --------) | err = 1.671e-01\n 12: x = ( 6.30488, -2.76135) | err' = (--------, 0.3227) | err = 1.670e-01\n 13: x = ( 6.30488, -2.79361) | err' = ( 0.0404, --------) | err = 1.569e-01\n 13: x = ( 6.30084, -2.79361) | err' = (--------, 0.3024) | err = 1.567e-01\n 14: x = ( 6.30084, -2.82385) | err' = ( 0.0377, --------) | err = 1.478e-01\n 14: x = ( 6.29708, -2.82385) | err' = (--------, 0.2845) | err = 1.477e-01\n\n\n## 5. Logistic Regression\n\n### 5.1 Creating a target function\n\nFor simplicity, we choose a target function, $f$, to be a 0/1 probability.\nFor visualization purposes, we choose the domain of interest to be in 2 dimensions, and choose $\\mathbf{x}$ to be picked uniformly from the region $\\mathcal{X}=\\left[-1,1\\right] \\times \\left[-1,1\\right]$,\nwhere $\\times$ denotes the [Cartesian Product](https://en.wikipedia.org/wiki/Cartesian_product).\n\nA random line is created, and to ensure that it falls within the region of interest, it is created from two random points, $(x_0,y_0)$ and $(x_1,y_1)$ which are generated within $\\mathcal{X}$. The equation for this line in *slope-intercept* form and in the *hypothesis / weights* can be shown to be:\n\n**Slope-Intercept Form**\n\n$$m = - \\frac{w_1}{w_2}, c = - \\frac{w_0}{w_2}$$\n\n**Hypothesis Weights Form**\n\n$$\\mathbf{w} = \\left(-c,-m,1\\right)$$\n\n\n```python\ndef generate_data(n,seed=None):\n if seed is not None:\n np.random.seed(seed)\n x0 = np.ones(n)\n x1 = np.random.uniform(low=-1,high=1,size=(2,n))\n return np.vstack((x0,x1)).T\n```\n\n\n```python\ndef get_random_line(seed=None):\n X = generate_data(2,seed=seed)\n x = X[:,1]\n y = X[:,2]\n m = (y[1]-y[0])/(x[1]-x[0])\n c = y[0] - m*x[0]\n return np.array([-c,-m,1])\n\ndef draw_line(ax,w,marker='g--',label=None):\n m = -w[1]/w[2]\n c = -w[0]/w[2]\n x = np.linspace(-1,1,20)\n y = m*x + c\n if label is None:\n ax.plot(x,y,marker)\n else:\n ax.plot(x,y,marker,label=label)\n \ndef get_hypothesis(X,w):\n h=np.dot(X,w)\n return np.sign(h).astype(int)\n```\n\n### 5.2 Plotting the Data\n\n\n```python\ndef plot_data(fig,plot_id,X,y=None,w_arr=None,my_x=None,title=None):\n ax = fig.add_subplot(plot_id)\n if y is None:\n ax.plot(X[:,1],X[:,2],'gx')\n else:\n ax.plot(X[y > 0,1],X[y > 0,2],'b+',label='Positive (+)')\n ax.plot(X[y < 0,1],X[y < 0,2],'ro',label='Negative (-)')\n ax.set_xlim(-1,1)\n ax.set_ylim(-1,1)\n ax.grid(True)\n if w_arr is not None:\n if isinstance(w_arr,list) is not True:\n w_arr=[w_arr]\n for i,w in enumerate(w_arr):\n if i==0:\n draw_line(ax,w,'g-',label='Theoretical')\n else:\n draw_line(ax,w,'g--')\n if my_x is not None:\n ax.plot([my_x[0]],[my_x[1]],'kx',markersize=10)\n if title is not None:\n ax.set_title(title)\n ax.legend(loc='best',frameon=True)\n```\n\n\n```python\ndef create_dataset(N,make_plot=True,seed=None):\n X = generate_data(N,seed=seed)\n w_theoretical = get_random_line()\n y = get_hypothesis(X,w_theoretical)\n if make_plot is True:\n fig = plt.figure(figsize=(7,5))\n plot_data(fig,111,X,y,w_theoretical,title=\"Initial Dataset\")\n return X,y,w_theoretical\n```\n\nWe choose 100 training points at random from $\\mathcal{X}$ and record the outputs, $y_n$, for each of the points, $\\mathbf{x_n}$.\n\n\n```python\nN = 100\nX,y,w_theoretical = create_dataset(N=N,make_plot=True,seed=127)\n```\n\n### 5.3 Gradient Descent\n\nThe gradient descent algorithm adjust the weights in the direction of the 'steepest descent' ($\\nabla E_{in}$), with the adjustment of a learning rate, $\\eta$:\n\n$$\\mathbf{w}(t+1) = \\mathbf{w}(t) - \\eta\\nabla E_{in}$$\n\nWe thus need to know the gradient of the error measure with respect to the weights, i.e.:\n\n$$\\nabla E_{in}\\left(\\mathbf{w}\\right) = -\\frac{1}{N}\\sum\\limits_{n=1}^N \\frac{y_n\\mathbf{x_N}}{1 + \\exp\\left(y_n \\mathbf{w^T}(t)\\mathbf{x_n}\\right)}$$\n\n$$E_{in}\\left(\\mathbf{w}\\right) = \\frac{1}{N}\\sum\\limits_{n=1}^N \\ln\\left[1 + \\exp\\left(-y_n \\mathbf{w^T x_n}\\right)\\right]$$\n\n\n```python\nw = w_theoretical\ndef cross_entropy(y_i,w,x):\n return np.log(1 + np.exp(-y_i*np.dot(x,w)))\ndef gradient(y_i,w,x):\n return -y_i*x/(1+np.exp(y_i*np.dot(x,w)))\nassert np.allclose(cross_entropy(y[0],w,X[0,:]),np.log(1 + np.exp(-y[0]*np.dot(X[0,:],w))))\nassert np.allclose(gradient(y[0],w,X[0,:]),-y[0]*X[0,:]/(1+np.exp(y[0]*np.dot(X[0,:],w))))\n```\n\n\n```python\nnp.mean(cross_entropy(y,w,X))\n```\n\n\n\n\n 0.15242626832575448\n\n\n\n\n```python\nnp.set_printoptions(precision=4)\nassert np.linalg.norm(np.array([1.0, 2.0, 3.0])) == np.sqrt(1**2 + 2**2 + 3**2)\n```\n\n\n```python\ndef run_simulation(N=100,eta=0.01,make_plot=None,w0 = np.array([0,0,0],dtype=float)):\n X = generate_data(N)\n w_theoretical = get_random_line()\n y = get_hypothesis(X,w_theoretical)\n\n w_arr = []\n w_arr2= []\n e_arr = []\n w = w0\n h = get_hypothesis(X,w)\n assert y.dtype == h.dtype\n for t_epoch in range(1000):\n w_epoch = w\n for i,p in enumerate(permutation(N)):\n grad = gradient(y[p],w,X[p,:])\n w = w - eta*grad;\n w_arr2.append(w)\n\n #Estimate out-of-sample error by re-generating data\n X_out = generate_data(N)\n h = get_hypothesis(X_out,w_theoretical)\n misclassified = np.mean(h != y)\n #E_out = np.mean(cross_entropy(y,w,X))\n E_out = np.mean(cross_entropy(h,w,X_out))\n delta_w = np.linalg.norm(w - w_epoch)\n w_arr.append(w)\n e_arr.append(E_out)\n #if t_epoch % 20 == 0:\n # print(\"epoch{:4}: miss={}, delta_w={}, E_out={}, w={}\".format(\n # t_epoch, misclassified, np.round(delta_w,5), E_out, w))\n if delta_w < 0.01: break\n print(\"Epochs = {}, E_out = {}, w = {}\".format(t_epoch, E_out, w))\n if make_plot is not None:\n fig = plt.figure(figsize=(7,5))\n plot_data(fig,111,X,y,[w_theoretical,w],title=\"Converged\")\n return e_arr, np.array(w_arr), X, y, np.array(w_arr2)\n```\n\nDue to the randomness of starting with different target functions each time, we run stochastic gradient descent multiple times and consider the statistics in terms of the average number of epochs and the average out-of-sample errors.\n\n\n```python\nt_arr = []\ne_arr = []\nw_arr = []\nfor n in range(50):\n e, w, _, _, _ = run_simulation()\n t_arr.append(len(e)-1) #Should I subtract 1 here?\n e_arr.append(e[-1])\n w_arr.append(w[-1])\n```\n\n Epochs = 344, E_out = 0.1145102478546653, w = [-4.3349 -6.8128 3.151 ]\n Epochs = 330, E_out = 0.13254923381857528, w = [ 3.9176 7.7578 3.0019]\n Epochs = 338, E_out = 0.12272718416074929, w = [-5.1854 5.7707 -0.0663]\n Epochs = 362, E_out = 0.11358961920713569, w = [-5.1431 1.1128 7.6227]\n Epochs = 355, E_out = 0.08452200240499405, w = [-3.4195 7.4099 4.1785]\n Epochs = 387, E_out = 0.10453583621865964, w = [ 1.4044 -7.1103 6.8903]\n Epochs = 382, E_out = 0.11095706431956907, w = [ 1.2906 -6.6268 7.327 ]\n Epochs = 375, E_out = 0.11401376588425498, w = [ 4.3071 8.4367 1.3905]\n Epochs = 313, E_out = 0.08906826626000988, w = [-4.6285 5.0157 4.3839]\n Epochs = 319, E_out = 0.09907279197577364, w = [ 1.8946 7.248 4.4978]\n Epochs = 331, E_out = 0.11951194996454045, w = [-2.1788 7.0753 5.1223]\n Epochs = 345, E_out = 0.08534027589824467, w = [ 4.5074 2.043 6.8368]\n Epochs = 353, E_out = 0.09919776381452064, w = [ 2.6006 8.8545 2.8099]\n Epochs = 386, E_out = 0.10680017454642046, w = [ 2.3637 -7.6321 6.7116]\n Epochs = 327, E_out = 0.07963332746431315, w = [-1.3705 1.8633 8.9342]\n Epochs = 310, E_out = 0.1004902896810616, w = [-4.8985 2.0773 6.2821]\n Epochs = 352, E_out = 0.09435527830870676, w = [ 3.026 8.6722 2.6698]\n Epochs = 177, E_out = 0.06606451292292667, w = [-4.0843 -2.4275 0.7686]\n Epochs = 312, E_out = 0.08993382351733965, w = [-1.6081 -8.5505 0.3119]\n Epochs = 343, E_out = 0.10269877468148719, w = [ 2.1217 -8.803 2.7701]\n Epochs = 272, E_out = 0.0872375327354725, w = [-4.8057 -2.0756 4.3213]\n Epochs = 405, E_out = 0.1150348727541617, w = [-4.831 -8.8921 0.8516]\n Epochs = 322, E_out = 0.10791883242053275, w = [-4.0173 1.1187 7.0841]\n Epochs = 343, E_out = 0.13927435537954996, w = [ 3.7391 6.7424 4.8557]\n Epochs = 324, E_out = 0.11451497060907402, w = [-4.0974 4.2159 6.4424]\n Epochs = 337, E_out = 0.11013500604859183, w = [-1.6868 -3.1915 8.7905]\n Epochs = 311, E_out = 0.1202390667292876, w = [ 1.2721 -8.2782 3.2557]\n Epochs = 425, E_out = 0.1040334437781984, w = [ 1.1855 -8.1509 6.6445]\n Epochs = 324, E_out = 0.1266759412214779, w = [ 1.769 -1.973 8.6323]\n Epochs = 362, E_out = 0.10454353508849133, w = [ 1.6676 3.9335 8.6676]\n Epochs = 331, E_out = 0.07162336922800794, w = [-1.9393 2.237 8.7294]\n Epochs = 347, E_out = 0.11201459689167029, w = [ 2.7126 -6.0879 6.4069]\n Epochs = 324, E_out = 0.10162245585984317, w = [-4.5788 -6.8037 3.3853]\n Epochs = 376, E_out = 0.07224885673385947, w = [ 4.9275 -1.5392 8.1009]\n Epochs = 344, E_out = 0.09418330137125026, w = [-2.2507 -8.0475 4.707 ]\n Epochs = 409, E_out = 0.07914745644057647, w = [ 1.181 -5.8557 8.8743]\n Epochs = 361, E_out = 0.0781523158521627, w = [-4.0031 6.3655 5.5268]\n Epochs = 354, E_out = 0.11836358806105533, w = [-2.5064 -4.4141 8.1074]\n Epochs = 361, E_out = 0.10094928768153809, w = [-1.5559 -5.7539 7.5764]\n Epochs = 363, E_out = 0.07564746211750291, w = [-1.2404 -4.2471 8.6759]\n Epochs = 401, E_out = 0.10600085255274277, w = [-5.4864 6.9466 0.912 ]\n Epochs = 315, E_out = 0.13348176305348317, w = [ 2.0044 -8.0714 2.6051]\n Epochs = 398, E_out = 0.08309106515191791, w = [-4.8958 0.2701 9.4649]\n Epochs = 259, E_out = 0.16735110442009668, w = [-4.3832 0.5935 5.2335]\n Epochs = 294, E_out = 0.10293018590522714, w = [ 0.0834 -0.3418 8.7189]\n Epochs = 384, E_out = 0.08324299232848924, w = [ 3.9464 6.2222 6.9053]\n Epochs = 345, E_out = 0.12940067224923055, w = [-0.0396 5.4435 7.5821]\n Epochs = 342, E_out = 0.11404890276530884, w = [ 1.3681 9.2648 0.4564]\n Epochs = 327, E_out = 0.10240693589397777, w = [ 2.7934 -8.2483 1.8324]\n Epochs = 312, E_out = 0.07759210390392761, w = [-4.5546 -5.4712 4.6846]\n\n\nThe average out of sample error and the average number of epochs from the multiple runs above are:\n\n\n```python\nprint(\" = {}\".format(np.mean(e_arr)))\nprint(\" = {}\".format(np.mean(t_arr)))\n```\n\n = 0.10325358016261309\n = 342.26\n\n\n### 5.4 Gradient Descent Visualization\n\n\n```python\ndef normalize_weights(w_arr):\n # You can't normalize the weights as this changes the cross entropy.\n w_arr[:,1] = w_arr[:,1] / w_arr[:,0]\n w_arr[:,2] = w_arr[:,2] / w_arr[:,0]\n w_arr[:,0] = 1.0\n return w_arr\n```\n\n\n```python\ndef calculate_J(w0,w1,w2,X,y):\n J = np.zeros((w1.size,w2.size))\n for j in range(w1.size):\n for i in range(w2.size):\n W = np.array([w0, w1[j], w2[i]])\n J[i,j] = np.mean(cross_entropy(y,W,X))\n return J\n\ndef get_WJ(w_arr,X,y,n=100):\n w_arr = np.array(w_arr)\n\n w1_min = np.min(w_arr[:,1])\n w2_min = np.min(w_arr[:,2])\n w1_max = np.max(w_arr[:,1])\n w2_max = np.max(w_arr[:,2])\n sp = 10.0\n\n w0 = w_arr[-1,0] # take a 2D slice through the final value of w_0 in the 3D space [w0,w1,w2]\n w1 = np.linspace(w1_min-sp,w1_max+sp,n)\n w2 = np.linspace(w2_min-sp,w2_max+sp,n)\n W1, W2 = np.meshgrid(w1,w2)\n J = calculate_J(w0,w1,w2,X,y)\n return w_arr,w1,w2,W1,W2,J\n```\n\n\n```python\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom matplotlib import cm\ndef visualise_SGD_3D(e_arr,w_arr,w_arr2,X,y,epoch_interval,elevation=30,azimuth=75):\n w_arr,w1,w2,W1,W2,J = get_WJ(w_arr,X,y)\n w0 = w_arr[-1,0] # take a 2D slice through the final value of w_0 in the 3D space [w0,w1,w2]\n z_arr = [ np.mean(cross_entropy(y,[w0,w_i[1],w_i[2]],X)) for w_i in w_arr ]\n z_arr2 = [ np.mean(cross_entropy(y,[w0,w_i[1],w_i[2]],X)) for w_i in w_arr2 ]\n\n fig = plt.figure(figsize=(14,10))\n ax = fig.gca(projection='3d')\n surf = ax.plot_surface(W1,W2,J, rstride=10, cstride=10, cmap=cm.coolwarm,\n linewidth=0.3, antialiased=True, alpha=0.9) #, zorder=3)\n ax.set_xlabel(r'$w_1$', fontsize=18)\n ax.set_ylabel(r'$w_2$', fontsize=18)\n ax.set_zlabel(r'$E_{in}$', fontsize=18)\n ax.plot(w_arr[:,1],w_arr[:,2],z_arr,'k-',lw=0.8,label=\"Stochastic Gradient Descent (SGD)\")\n ax.plot(w_arr2[:,1],w_arr2[:,2],z_arr2,'k-',lw=1.8,alpha=0.3,label=\"SGD within epochs\")\n ax.plot(w_arr[::epoch_interval,1],w_arr[::epoch_interval,2],z_arr[::epoch_interval],\n 'ko',markersize=7,label=r\"Intervals of $n$ Epochs\")\n ax.scatter([w_arr[-1,1]],[w_arr[-1,2]],[z_arr[-1]], c='r', s=250, marker='x', lw=3);\n #fig.colorbar(surf, shrink=0.5, aspect=12)\n ax.legend(loc='best',frameon=False)\n ax.axes.xaxis.set_ticklabels([])\n ax.axes.yaxis.set_ticklabels([])\n ax.axes.zaxis.set_ticklabels([])\n ax.view_init(elev=elevation, azim=azimuth)\n\ndef visualise_SGD_contour(e_arr,w_arr,w_arr2,X,y,epoch_interval):\n w_arr,w1,w2,W1,W2,J = get_WJ(w_arr,X,y)\n\n fig = plt.figure(figsize=(12,8))\n ax = fig.gca()\n CS = plt.contour(W1,W2,J,20)\n #plt.clabel(CS, inline=1, fontsize=10)\n ax.set_xlabel(r'$w_1$', fontsize=18)\n ax.set_ylabel(r'$w_2$', fontsize=18)\n ax.plot(w_arr[:,1],w_arr[:,2],'k-',lw=0.8,label=\"Stochastic Gradient Descent (SGD)\")\n ax.plot(w_arr2[:,1],w_arr2[:,2],'k-',lw=1.8,alpha=0.3,label=\"SGD within epochs\")\n ax.plot(w_arr[::epoch_interval,1],w_arr[::epoch_interval,2],\n 'ko',markersize=7,label=r\"Intervals of $n$ Epochs\")\n ax.scatter([w_arr[-1,1]],[w_arr[-1,2]], c='r', s=150, marker='x', lw=3);\n ax.legend(loc='best',frameon=False)\n ax.axes.xaxis.set_ticklabels([])\n ax.axes.yaxis.set_ticklabels([])\n plt.title(r'$E_{in}$', fontsize=16);\n```\n\n\n```python\ndef plot_epochs(e_arr,w_arr,X,y,epoch_interval):\n w_arr,w1,w2,W1,W2,J = get_WJ(w_arr,X,y)\n E_in = [ np.mean(cross_entropy(y,w_i,X)) for w_i in w_arr ]\n epoch = np.array(range(len(e_arr)))\n\n fig = plt.figure(figsize=(10,10))\n ax = fig.add_subplot(211)\n ax.set_ylabel(r'Error', fontsize=16)\n ax.plot(epoch,e_arr,c='g',markersize=1,marker='+',lw=1,alpha=0.8,label=r'$E_{out}$')\n #ax.scatter(epoch[::epoch_interval],e_arr[::epoch_interval],c='g',s=20,marker='o',lw=3,alpha=0.8)\n ax.plot(epoch,E_in,c='k',linestyle='--',label=r'$E_{in}$')\n ax.legend(loc='best',frameon=False, fontsize=16)\n ax.set_title('\"Cross Entropy\" Error', fontsize=16);\n ax.axes.xaxis.set_ticklabels([])\n ax.axes.yaxis.set_ticklabels([])\n ax.grid(True)\n\n ax = fig.add_subplot(212)\n ax.set_xlabel(r'Epoch', fontsize=16)\n ax.set_ylabel(r'Error', fontsize=16)\n ax.loglog(epoch,e_arr,c='g',markersize=1,marker='+',lw=1,alpha=0.8,label=r'$E_{out}$')\n ax.loglog(epoch,E_in,c='k',linestyle='--',label=r'$E_{in}$')\n #ax.loglog(epoch[::epoch_interval],e_arr[::epoch_interval],c='g',markersize=8,marker='o',lw=3,alpha=0.8,ls='None')\n ax.legend(loc='best',frameon=False, fontsize=16)\n ax.axes.xaxis.set_ticklabels([])\n ax.axes.yaxis.set_ticklabels([])\n ax.grid(True)\n```\n\n\n```python\nnp.random.seed(12345)\ne_arr, w_arr, X, y, w_arr2 = run_simulation(N=15,eta=0.8,w0=np.array([2.0, 10.0, -20.0]))\n```\n\n Epochs = 751, E_out = 0.00495140131231788, w = [ 4.8336 21.6983 15.9885]\n\n\n\n```python\nvisualise_SGD_3D(e_arr,w_arr,w_arr2,X,y,epoch_interval=100)\n```\n\n\n```python\nvisualise_SGD_contour(e_arr,w_arr,w_arr2,X,y,epoch_interval=100)\n```\n\n\n```python\nplot_epochs(e_arr,w_arr,X,y,epoch_interval=100)\n```\n\n### 5.5 Stochastic Gradient Descent vs Perceptron Learning Algorithm\n\n\"Consider that you are picking a point at random out of the $N$ points. In PLA, you see if it is misclassified then update using the PLA rule if it is and not update if it isn't. In SGD, you take the gradient of the error on that point w.r.t. $\\mathbf{w}$ and update accordingly. Which of the 5 error functions would make these equivalent?\n\n- **(a)**: $e_n\\left(\\mathbf{w}\\right) = \\exp\\left(-y_n \\mathbf{w^T x_n}\\right)$\n- **(b)**: $e_n\\left(\\mathbf{w}\\right) = -y_n \\mathbf{w^T x_n}$\n- **(c)**: $e_n\\left(\\mathbf{w}\\right) = \\left(y_n - \\mathbf{w^T x_n}\\right)^2$\n- **(d)**: $e_n\\left(\\mathbf{w}\\right) = \\ln\\left[1 + \\exp\\left(-y_n \\mathbf{w^T x_n}\\right)\\right]$\n- **(e)**: $e_n\\left(\\mathbf{w}\\right) = -\\min\\left(0, y_n \\mathbf{w^T x_n}\\right)$\n\nAnswer: **(e)**\n\nNotes: an attempt to evaluate the gradients of the above functions using sympy was carried out as follows (the final expression, which contains the function `min` was excluded):\n\n\n```python\nvar('y_n w_i x_n')\nexpr = exp(-y_n * w_i * x_n)\nd_expr = expr.diff(w_i)\ndisplay(Math(latex(d_expr)))\n\nexpr = -y_n * w_i * x_n\nd_expr = expr.diff(w_i)\ndisplay(Math(latex(d_expr)))\n\nexpr = (y_n - w_i * x_n)**2\nd_expr = simplify(expr.diff(w_i))\ndisplay(Math(latex(d_expr)))\n\nexpr = log(1+exp(-y_n * w_i * x_n))\nd_expr = simplify(expr.diff(w_i))\ndisplay(Math(latex(d_expr)))\n```\n\n\n$$- x_{n} y_{n} e^{- w_{i} x_{n} y_{n}}$$\n\n\n\n$$- x_{n} y_{n}$$\n\n\n\n$$2 x_{n} \\left(w_{i} x_{n} - y_{n}\\right)$$\n\n\n\n$$- \\frac{x_{n} y_{n}}{e^{w_{i} x_{n} y_{n}} + 1}$$\n\n\n\n```python\nw_final = np.array(w_arr)[-1,:]\ne_a = np.mean(np.exp(-y*np.dot(X,w_final)))\ne_b = np.mean(-y*np.dot(X,w_final))\ne_c = np.mean((y - np.dot(X,w_final))**2)\ne_d = np.mean(np.log(1 + np.exp(-y*np.dot(X,w_final))))\ne_e = -y*np.dot(X,w_final); e_e[e_e > 0] = 0; e_e = np.mean(e_e)\nprint(\"(a) e_n(w) = {}\".format(e_a))\nprint(\"(b) e_n(w) = {}\".format(e_b))\nprint(\"(c) e_n(w) = {}\".format(e_c))\nprint(\"(d) e_n(w) = {}\".format(e_d))\nprint(\"(e) e_n(w) = {}\".format(e_e))\n```\n\n (a) e_n(w) = 0.006921150896126407\n (b) e_n(w) = -15.160717353544413\n (c) e_n(w) = 314.2802497501979\n (d) e_n(w) = 0.006754859029354315\n (e) e_n(w) = -15.160717353544413\n\n\nAn attempt was also made to visualize the gradient descent algorithm when performed on the various error functions.\n\n\n```python\ndef my_err_fn(y,W,X):\n #e = np.exp(-y*np.dot(X,W)) # e_a\n #e = -y*np.dot(X,W) # e_b\n #e = (y - np.dot(X,W))**2 # e_c\n e = np.log(1 + np.exp(-y*np.dot(X,W))) # e_d\n #e = -y*np.dot(X,W); e[e > 0] = 0 # e_e\n return np.mean(e)\n\ndef calculate_J(w0,w1,w2,X,y,my_err_fn):\n J = np.zeros((w1.size,w2.size))\n for j in range(w1.size):\n for i in range(w2.size):\n W = np.array([w0, w1[j], w2[i]])\n J[i,j] = my_err_fn(y,W,X)\n return J\n\ndef get_WJ(w_arr,X,y,my_err_fn,n=100):\n w_arr = np.array(w_arr)\n w1_min = np.min(w_arr[:,1])\n w2_min = np.min(w_arr[:,2])\n w1_max = np.max(w_arr[:,1])\n w2_max = np.max(w_arr[:,2])\n sp = 10.0\n\n w0 = w_arr[-1,0] # take a 2D slice through the final value of w_0 in the 3D space [w0,w1,w2]\n w1 = np.linspace(w1_min-sp,w1_max+sp,n)\n w2 = np.linspace(w2_min-sp,w2_max+sp,n)\n W1, W2 = np.meshgrid(w1,w2)\n J = calculate_J(w0,w1,w2,X,y,my_err_fn)\n return w_arr,w1,w2,W1,W2,J\n\ndef visualise_SGD_contour2(e_arr,w_arr,X,y,my_err_fn):\n w_arr,w1,w2,W1,W2,J = get_WJ(w_arr,X,y,my_err_fn)\n\n fig = plt.figure(figsize=(10,7))\n ax = fig.gca()\n CS = plt.contour(W1,W2,J,20)\n plt.clabel(CS, inline=1, fontsize=10)\n ax.set_xlabel(r'$w_1$', fontsize=18)\n ax.set_ylabel(r'$w_2$', fontsize=18)\n ax.plot(w_arr[:,1],w_arr[:,2],'k-',label=\"Gradient Descent\")\n ax.plot(w_arr[::100,1],w_arr[::100,2],'ko',markersize=7,label=r\"Intervals of $n$ Epochs\")\n ax.scatter([w_arr[-1,1]],[w_arr[-1,2]], c='r', s=150, marker='x', lw=3);\n ax.legend(loc='best',frameon=False)\n ax.axes.xaxis.set_ticklabels([])\n ax.axes.yaxis.set_ticklabels([])\n plt.title(r'$E_{in}$', fontsize=16)\n```\n\n\n```python\nnp.random.seed(12345)\ne_arr, w_arr, X, y, w_arr2 = run_simulation(N=300,eta=0.15)\nvisualise_SGD_contour2(e_arr,w_arr,X,y,my_err_fn)\n```\n", "meta": {"hexsha": "592e7c86ef065cb2f17a878e9a18539fc6154743", "size": 632837, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "perceptron/logistic-regression.ipynb", "max_stars_repo_name": "nathanielng/machine-learning", "max_stars_repo_head_hexsha": "07ba6b7eb1d09a3d9929fd8390dde356e1d0745d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2016-10-05T05:26:14.000Z", "max_stars_repo_stars_event_max_datetime": "2017-11-24T03:42:04.000Z", "max_issues_repo_path": "perceptron/logistic-regression.ipynb", "max_issues_repo_name": "nathanielng/machine-learning", "max_issues_repo_head_hexsha": "07ba6b7eb1d09a3d9929fd8390dde356e1d0745d", "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": "perceptron/logistic-regression.ipynb", "max_forks_repo_name": "nathanielng/machine-learning", "max_forks_repo_head_hexsha": "07ba6b7eb1d09a3d9929fd8390dde356e1d0745d", "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": 375.7939429929, "max_line_length": 150522, "alphanum_fraction": 0.9125793846, "converted": true, "num_tokens": 15674, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768557238084, "lm_q2_score": 0.9099070109242131, "lm_q1q2_score": 0.8591131405754725}} {"text": "# Pyomo - Getting started\n\nPyomo installation: see http://www.pyomo.org/installation\n\n```\npip install pyomo\n```\n\n\n```python\nfrom pyomo.environ import *\n```\n\n## Ice cream example\n\nThis example is taken from the following book: *Pyomo - Optimization Modeling in Python* by W. E. Hart & al. , Second Edition, Springer (p.19)\n\n$$\n\\begin{align}\n \\max_{x} & \\quad \\sum_{i \\in \\mathcal{A}} h_i (1 - u/d_i^2) x_i \\\\\n \\text{s.t.} & \\quad \\sum_{i \\in \\mathcal{A}} c_i x_i \\leq b \\\\\n & \\quad 0 \\leq x_i \\leq u_i, \\quad i \\in \\mathcal{A}\n\\end{align}\n$$\n\n### Concrete Model\n\n`ConcHLinScript.py` in https://github.com/Pyomo/pyomo/tree/master/examples/doc/pyomobook/optimization-ch\n\n\n```python\ninstance = ConcreteModel(name=\"Linear (H)\")\n\nA = ['I_C_Scoops', 'Peanuts']\nh = {'I_C_Scoops': 1, 'Peanuts': 0.1}\nd = {'I_C_Scoops': 5, 'Peanuts': 27}\nc = {'I_C_Scoops': 3.14, 'Peanuts': 0.2718}\nb = 12\nu = {'I_C_Scoops': 100, 'Peanuts': 40.6}\n\ndef x_bounds(m, i):\n return (0,u[i])\n\ninstance.x = Var(A, bounds=x_bounds)\n\ndef obj_rule(instance):\n return sum(h[i]*(1 - u[i]/d[i]**2) * instance.x[i] for i in A)\n\ninstance.z = Objective(rule=obj_rule, sense=maximize)\n\ninstance.budgetconstr = Constraint(expr = sum(c[i] * instance.x[i] for i in A) <= b)\n\n# @tail:\nopt = SolverFactory('glpk')\n\nresults = opt.solve(instance) # solves and updates instance\n\ninstance.display()\n# @:tail\n```\n\n### Abstract Model\n\n`AbstHLinScript.py` in https://github.com/Pyomo/pyomo/tree/master/examples/doc/pyomobook/optimization-ch\n\n\n```python\nDATA_STR = \"\"\"# Pyomo data file for AbstractH.py\nset A := I_C_Scoops Peanuts ;\nparam h := I_C_Scoops 1 Peanuts 0.1 ;\nparam d := \n I_C_Scoops 5\n Peanuts 27 ;\nparam c := I_C_Scoops 3.14 Peanuts 0.2718 ;\nparam b := 12 ;\nparam u := I_C_Scoops 100 Peanuts 40.6 ;\n\"\"\"\n\nwith open(\"AbstractH.dat\", \"w\") as fd:\n print(DATA_STR, file=fd)\n```\n\n\n```python\n!cat AbstractH.dat\n```\n\n\n```python\nmodel = AbstractModel(name=\"Simple Linear (H)\")\n\nmodel.A = Set()\n\nmodel.h = Param(model.A)\nmodel.d = Param(model.A)\nmodel.c = Param(model.A)\nmodel.b = Param()\nmodel.u = Param(model.A)\n\ndef xbounds_rule(model, i):\n return (0, model.u[i])\nmodel.x = Var(model.A, bounds=xbounds_rule)\n\ndef obj_rule(model):\n return sum(model.h[i] * (1 - model.u[i]/model.d[i]**2) * model.x[i] for i in model.A)\n\nmodel.z = Objective(rule=obj_rule, sense=maximize)\n\ndef budget_rule(model):\n return summation(model.c, model.x) <= model.b\n\nmodel.budgetconstr = Constraint(rule=budget_rule)\n\n# @tail:\nopt = SolverFactory('glpk')\n\ninstance = model.create_instance(\"AbstractH.dat\")\nresults = opt.solve(instance) # solves and updates instance\n\ninstance.display()\n# @:tail\n```\n", "meta": {"hexsha": "149b57447cce8ff87bd116909bcf46ad9bab5072", "size": 5154, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "nb_dev_python/python_pyomo_getting_started_3.ipynb", "max_stars_repo_name": "jdhp-docs/python-notebooks", "max_stars_repo_head_hexsha": "91a97ea5cf374337efa7409e4992ea3f26b99179", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2017-05-03T12:23:36.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-26T17:30:56.000Z", "max_issues_repo_path": "nb_dev_python/python_pyomo_getting_started_3.ipynb", "max_issues_repo_name": "jdhp-docs/python-notebooks", "max_issues_repo_head_hexsha": "91a97ea5cf374337efa7409e4992ea3f26b99179", "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": "nb_dev_python/python_pyomo_getting_started_3.ipynb", "max_forks_repo_name": "jdhp-docs/python-notebooks", "max_forks_repo_head_hexsha": "91a97ea5cf374337efa7409e4992ea3f26b99179", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-10-26T17:30:57.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-26T17:30:57.000Z", "avg_line_length": 24.0841121495, "max_line_length": 148, "alphanum_fraction": 0.5042685293, "converted": true, "num_tokens": 863, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9539660962919971, "lm_q2_score": 0.9005297901222472, "lm_q1q2_score": 0.8590748884775716}} {"text": "### Computing for Mathematics - Mock individual coursework\n\nThis jupyter notebook contains questions that will resemble the questions in your individual coursework.\n\n**Important** Do not delete the cells containing: \n\n```\n### BEGIN SOLUTION\n\n### END SOLUTION\n```\n\nwrite your solution attempts in those cells.\n\n**If you would like to** submit this notebook:\n\n- Change the name of the notebook from `main` to: ``. For example, if your student number is `c1234567` then change the name of the notebook to `c1234567`.\n- Write all your solution attempts in the correct locations;\n- Save the notebook (`File>Save As`);\n- Follow the instructions given in class/email to submit.\n\n#### Question 1\n\nOutput the evaluation of the following expressions exactly.\n\na. \\\\(\\frac{(9a^2bc^4) ^ {\\frac{1}{2}}}{6ab^{\\frac{3}{2}}c}\\\\)\n\n\n```python\n### BEGIN SOLUTION\nimport sympy as sym\na, b, c = sym.Symbol(\"a\"), sym.Symbol(\"b\"), sym.Symbol(\"c\")\n\nsym.expand((9 * a ** 2 * b * c ** 4) ** (sym.S(1) / 2) / (6 * a * b ** (sym.S(3) / 2) * c))\n### END SOLUTION\n```\n\n\n\n\n$\\displaystyle \\frac{\\sqrt{a^{2} b c^{4}}}{2 a b^{\\frac{3}{2}} c}$\n\n\n\n\n```python\nq1_a_answer = _\nfeedback_text = \"\"\"Your output is not a symbolic expression.\n\nYou are expected to use sympy for this question.\n\"\"\"\ntry:\n assert q1_a_answer.expand(), feedback_text\nexcept AttributeError:\n assert False, feedback_text\n```\n\n\n```python\nimport sympy as sym\na, b, c = sym.Symbol(\"a\"), sym.Symbol(\"b\"), sym.Symbol(\"c\")\n\nexpected_answer = (9 * a ** 2 * b * c ** 4) ** (sym.S(1) / 2) / (6 * a * b ** (sym.S(3) / 2) * c)\nfeedback_text = f\"\"\"Your answer is not correct.\n\nThe expected answer is {expected_answer}.\"\"\"\nassert sym.simplify(q1_a_answer - expected_answer) == 0, feedback_text\n```\n\nb. \\\\((2 ^ {\\frac{1}{2}} + 2) ^ 2 - 2 ^ {\\frac{5}{2}}\\\\)\n\n\n```python\n### BEGIN SOLUTION\n(sym.S(2) ** (sym.S(1) / 2) + 2) ** 2 - 2 ** (sym.S(5) / 2)\n### END SOLUTION\n```\n\n\n\n\n$\\displaystyle - 4 \\sqrt{2} + \\left(\\sqrt{2} + 2\\right)^{2}$\n\n\n\n\n```python\nq1_b_answer = _\nfeedback_text = \"\"\"Your output is not a symbolic expression.\n\nYou are expected to use sympy for this question.\n\"\"\"\ntry:\n assert q1_b_answer.expand(), feedback_text\nexcept AttributeError:\n assert False, feedback_text\n```\n\n\n```python\nx = sym.Symbol(\"x\")\nexpected_answer = 6\nfeedback_text = f\"\"\"Your answer is not correct.\n\nThe expected answer is {expected_answer}.\"\"\"\nassert sym.expand(q1_b_answer - expected_answer) == 0, feedback_text\n```\n\n3. \\\\((\\frac{1}{8}) ^ {\\frac{4}{3}}\\\\)\n\n\n```python\n### BEGIN SOLUTION\n(sym.S(1) / 8) ** (sym.S(4) / 3)\n### END SOLUTION\n```\n\n\n\n\n$\\displaystyle \\frac{1}{16}$\n\n\n\n\n```python\nq1_c_answer = _\nfeedback_text = \"\"\"Your output is not a symbolic expression.\n\nYou are expected to use sympy for this question.\n\"\"\"\ntry:\n assert q1_c_answer.expand(), feedback_text\nexcept AttributeError:\n assert False, feedback_text\n```\n\n\n```python\nx = sym.Symbol(\"x\")\nexpected_answer = sym.S(1) / 16\nfeedback_text = f\"\"\"Your answer is not correct.\n\nThe expected answer is {expected_answer}.\"\"\"\nassert q1_c_answer == expected_answer, feedback_text\n```\n\n### Question 2\n\nWrite a function `expand` that takes a given mathematical expression and returns the expanded expression.\n\n\n```python\ndef expand(expression):\n ### BEGIN SOLUTION\n \"\"\"\n Take a symbolic expression and expands it.\n \"\"\"\n return sym.expand(expression)\n ### END SOLUTION\n```\n\n\n```python\nfeedback_text = \"\"\"You did not include a docstring. This is important to help document your code.\n\n\nIt is done using triple quotation marks. For example:\n\ndef get_remainder(m, n):\n \\\"\\\"\\\"\n This function returns the remainder of m when dividing by n\n \\\"\\\"\\\"\n …\n\nUsing that it's possible to access the docstring,\none way to do this is to type: `get_remainder?`\n(which only works in Jupyter) or help(get_remainder).\n\nWe can also comment code using `#` but this is completely\nignored by Python so cannot be accessed in the same way.\n\n\"\"\"\ntry:\n assert expand.__doc__ is not None, feedback_text\nexcept NameError:\n assert False, \"You did not create a function called `expand`\"\n```\n\n\n```python\nexpression = x * (x + 1)\nassert expand(expression) == x ** 2 + x, f\"Your function failed for {expression}\"\nexpression = x * (x + 1) - x ** 2\nassert expand(expression) == x, f\"Your function failed for {expression}\"\nexpression = x ** 2 + 1\nassert expand(expression) == x ** 2 + 1, f\"Your function failed for {expression}\"\n```\n\n### Question 3\n\nThe matrix \\\\(D\\\\) is given by \\\\(D = \\begin{pmatrix} 1& 2 & a\\\\ 3 & 1 & 0\\\\ 1 & 1 & 1\\end{pmatrix}\\\\) where \\\\(a\\ne 2\\\\).\n\na. Create a variable `D` which has value the matrix \\\\(D\\\\).\n\n\n```python\n### BEGIN SOLUTION\na = sym.Symbol(\"a\")\nD = sym.Matrix([[1, 2, a], [3, 1, 0], [1, 1, 1]])\n### END SOLUTION\n```\n\n\n```python\nexpected_D = sym.Matrix([[1, 2, a], [3, 1, 0], [1, 1, 1]])\nfeedback_text = f\"The expected value of `D` is {expected_D}.\"\ntry:\n assert sym.simplify(sym.expand(sym.simplify(D) - expected_D)) == sym.Matrix([[0, 0, 0] for _ in range(3)]), feedback_text\nexcept NameError:\n assert False, \"You did not create a variable `D`\"\n```\n\nb. Create a variable `D_inv` with value the inverse of \\\\(D\\\\).\n\n\n```python\n### BEGIN SOLUTION\nD_inv = D.inv()\n### END SOLUTION\n```\n\n\n```python\nexpected_D_inv = expected_D.inv()\nfeedback_text = f\"The expected value of `D_inv` is {expected_D_inv}.\"\nassert sym.simplify(sym.expand(sym.simplify(D_inv) - expected_D_inv)) == sym.Matrix([[0, 0, 0] for _ in range(3)]), feedback_text\n```\n\nc. Using `D_inv` **output** the solution of the following system of equations:\n\n\\\\[\n\\begin{array}{r}\n x + 2y + 4z = 3\\\\\n 3x + y = 4\\\\\n x + y + z = 1\\\\\n\\end{array}\n\\\\]\n\n\n```python\n### BEGIN SOLUTION\nb = sym.Matrix([[3], [4], [1]])\nsym.simplify(D.inv() @ b).subs({a: 4})\n### END SOLUTION\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}\\frac{7}{3}\\\\-3\\\\\\frac{5}{3}\\end{matrix}\\right]$\n\n\n\n\n```python\nanswer_q3_c = _\nexpected_b = sym.Matrix([[3], [4], [1]])\nexpected_answer = sym.simplify(expected_D_inv @ expected_b).subs({a: 4})\nfeedback_text = f\"The expected solution is {expected_answer}.\"\nassert sym.expand(expected_answer - answer_q3_c) == sym.Matrix([[0], [0], [0]]), feedback_text\n```\n\n### Question 4\n\nDuring a game of frisbee between a handler and their dog the handler chooses to randomly select if they throw using a backhand or a forehand: 25% of the time they will throw a backhand.\n\nBecause of the way their dog chooses to approach a flying frisbee they catch it with the following probabilities:\n\n- 80% of the time when it is thrown using a backhand\n- 90% of the time when it is thrown using a forehand\n\na. Write a function `sample_experiment()` that simulates a given throw and returns the throw type (as a string with value `\"backhand\"` or `\"forehand\"`) and whether it was caught (as a boolean: either `True` or `False`).\n\n\n```python\nimport random\n\n\ndef sample_experiment():\n \"\"\"\n Returns the throw type and whether it was caught\n \"\"\"\n ### BEGIN SOLUTION\n if random.random() < .25:\n throw = \"backhand\"\n probability_of_catch = .8\n else:\n throw = \"forehand\"\n probability_of_catch = .9\n \n caught = random.random() < probability_of_catch\n ### END SOLUTION\n return throw, caught\n```\n\n\n```python\nfeedback_text = \"\"\"You did not include a docstring. This is important to help document your code.\n\n\nIt is done using triple quotation marks. For example:\n\ndef get_remainder(m, n):\n \\\"\\\"\\\"\n This function returns the remainder of m when dividing by n\n \\\"\\\"\\\"\n …\n\nUsing that it's possible to access the docstring,\none way to do this is to type: `get_remainder?`\n(which only works in Jupyter) or help(get_remainder).\n\nWe can also comment code using `#` but this is completely\nignored by Python so cannot be accessed in the same way.\n\n\"\"\"\ntry:\n assert sample_experiment.__doc__ is not None, feedback_text\nexcept NameError:\n assert False, \"You did not create a variable called `sample_experiment`\"\n```\n\n\n```python\ntry:\n random.seed(0)\n throw, caught = sample_experiment()\n assert throw in [\"forehand\", \"backhand\"], \"Your function did not give a throw with seed=0\"\n assert caught in [True, False], \"Your function did not give a valid coin with seed=0\"\n\n random.seed(1)\n throw, caught = sample_experiment()\n assert throw in [\"forehand\", \"backhand\"], \"Your function did not give a valid throw with seed=0\"\n assert caught in [True, False], \"Your function did not give a valid coin with seed=0\"\nexcept NameError:\n assert False, \"You did not create a function called `sample_experiment` or there is an error in your function.\"\n```\n\n\n```python\nrepetitions = 10_000\nrandom.seed(0)\nfeedback_text = f\"\"\"Your function did not give a selection of forehand throws within acceptable error bounds.\n\nOut of {repetitions} repetitions you got less than 5500 or more than 9500 forehand throw.\n\"\"\"\nthrows = [sample_experiment()[0] for _ in range(repetitions)]\nassert 5_500 <= throws.count(\"forehand\") <= 9_500, feedback_text\n```\n\nb. Using 1,000,000 samples create a variable `probability_of_catch` which has value an estimate for the probability of the frisbee being caught.\n\n\n```python\n### BEGIN SOLUTION\nnumber_of_repetitions = 1_000_000\nrandom.seed(0)\nsamples = [sample_experiment() for repetition in range(number_of_repetitions)]\nprobability_of_catch = sum(catch is True for throw, catch in samples) / number_of_repetitions\n### END SOLUTION\n```\n\n\n```python\nassert type(probability_of_catch) is float, \"You did not return a float\"\n```\n\n\n```python\nexpected_answer = sym.S(1) / (4) * sym.S(8) / 10 + sym.S(3) / (4) * sym.S(9) / 10\nfeedback_text = f\"\"\"The expected value is: {expected_answer}\n\nYour value was not within 20% of the expected answer.\n\"\"\"\nassert expected_answer * .8 <= probability_of_catch <= expected_answer * 1.2, feedback_text\n```\n\nc. Using the above, create a variable `probability_of_forehand_given_drop` which has value an estimate for the probability of the frisbee being thrown with a forehand given that it was not caught.\n\n\n```python\n### BEGIN SOLUTION\nsamples_with_drop = [(throw, catch) for throw, catch in samples if catch is False]\nnumber_of_drops = len(samples_with_drop)\nprobability_of_forehand_given_drop = sum(throw == \"forehand\" for throw, catch in samples_with_drop) / number_of_drops\n### END SOLUTION\n```\n\n\n```python\nassert type(probability_of_forehand_given_drop) is float, \"You did not return a float\"\n```\n\n\n```python\nexpected_answer = (sym.S(1) / (10) * sym.S(75) / 100) / (1 - (sym.S(1) / (4) * sym.S(8) / 10 + sym.S(3) / (4) * sym.S(9) / 10))\nfeedback_text = f\"\"\"The expected value is: {expected_answer}\n\nYour value was not within 20% of the expected answer.\n\"\"\"\nassert expected_answer * .8 <= probability_of_forehand_given_drop <= expected_answer * 1.2, feedback_text\n```\n", "meta": {"hexsha": "fd08acd332ffd33ee59b69ebc98707cb6a3a25dd", "size": 19428, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "assets/assessment/mock/main.ipynb", "max_stars_repo_name": "drvinceknight/cfm", "max_stars_repo_head_hexsha": "06977f5c1ba37590b17a8d2a22f57e3575875b3b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2016-08-25T01:05:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-04T16:17:06.000Z", "max_issues_repo_path": "assets/assessment/mock/main.ipynb", "max_issues_repo_name": "drvinceknight/cfm", "max_issues_repo_head_hexsha": "06977f5c1ba37590b17a8d2a22f57e3575875b3b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 88, "max_issues_repo_issues_event_min_datetime": "2016-08-24T20:08:15.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-19T23:26:14.000Z", "max_forks_repo_path": "assets/assessment/mock/main.ipynb", "max_forks_repo_name": "drvinceknight/cfm", "max_forks_repo_head_hexsha": "06977f5c1ba37590b17a8d2a22f57e3575875b3b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2016-09-22T12:36:03.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-13T13:21:30.000Z", "avg_line_length": 25.8695073236, "max_line_length": 229, "alphanum_fraction": 0.5167284332, "converted": true, "num_tokens": 3010, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299632771662, "lm_q2_score": 0.928408800060238, "lm_q1q2_score": 0.858991639985932}} {"text": "```python\n%matplotlib inline\n\nimport numpy as np\nimport scipy as sc\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport sympy as sp\n\nimport functools\nimport itertools\n\nsns.set();\n```\n\n# Taylor expansion\n\n## Taylor series\n\nLet $f$ be a function with all derivatives throughout some interval containing $a$ as an interior point. Then the Taylor series generated by $f$ at $x = a$ is given by the following power series\n\n$$f(x) = \\sum_{k = 0}^{\\infty} \\frac{f^{k}(a)}{k!} (x-a)^{k}$$\n\nwhere $k!$ denotes the factorial of $k$ and $f^{k}(a)$ denotes the nth derivative of $f$ evaluated at the point $a$.\n\nTaking $a = 0$, we have the McLaurin series:\n\n$$f(x) = \\sum_{k = 0}^{\\infty} \\frac{f^{k}(0)}{k!} x^{k}$$\n\n## Taylor polynomial\n\nLet $f$ be a function with derivatives of order $k$ for $k = 1, 2, \\dots, N$ in some interval containing $a$ as an interior point. Then for any integer $n$ from 0 through $N$, the Taylor polynomial of order $n$ generated by $f$ at the point $x = a$ is the polynomial\n\n$$P_{n}(x) = \\sum_{k = 0}^{n} \\frac{f^{k}(a)}{k!} (x-a)^{k}$$\n\nwhere $k!$ denotes the factorial of $k$ and $f^{k}(a)$ denotes the nth derivative of $f$ evaluated at the point $a$.\n\n\n## Taylor's theorem\n\nIf $f$ and its first $n$ derivatives $f', f'', \\dots, f^{n}$ are continuous on the closed interval between $a$ and $b$, and $f^{n}$ is differentiable on the open interval between $a$ and $b$, then there exists a number $c$ between $a$ and $b$ such that\n\n$$f(b) = \\sum_{k = 0}^{n} \\frac{f^{k}(a)}{k!} (x-a)^{k} + R_{n}(x)$$\n\nwhere\n\n$$R_{n}(x) = \\frac{f^{n+1}(c)}{(n+1)!} (x-a)^{n+1}$$\n\nfor some $c$ between $a$ and $x$. The function $R_{n}(x)$ is called the Lagrange remainder.\n\nIn other words,\n\n$$f(x) = P_{n}(x) + R_{n}(x)$$\n\nwhere $P_{n}(x)$ is the Taylor polynomial seen above.\n\nWe can write our own function of Taylor series as below.\n\n\n```python\ndef taylor(f, x, var, max_terms=6, x0=0):\n def taylor_terms():\n for k in range(max_terms):\n term = (sp.diff(f, var, k).subs(var, x0).evalf()/np.math.factorial(k)) * (x - x0)**k\n yield term\n \n serie = 0\n for term in taylor_terms():\n serie += term\n \n return serie\n```\n\n## Example 1\n\nConsider the function $f:\\mathbb{R}\\rightarrow[-1,1]$ defined as $f(x) = \\cos(x)$.\n\nIts Taylor expansion is given by\n\n$$\\cos(x) = \\sum_{n=0}^{\\infty} \\frac{(-1)^{n}}{(2n)!}x^{2n}, \\forall x \\in \\mathbb{R}$$\n\nThe code below show approximates for this function with 3, 10, 15 and 20 terms in the summation (or orders of the Taylor polynomials). The actual value for the function is also computed.\n\n\n```python\nx = sp.symbols(\"x\")\nf = sp.cos(x)\n\nf_series = functools.partial(taylor, var=x)\n\ndf1 = pd.DataFrame({\"x\": np.linspace(-8, 8, num=100)})\n\nmax_terms = [3, 10, 15, 20]\n\nfor max_term in max_terms:\n df1[\"y\" + str(max_term)] = np.array([f_series(f, x, max_terms=max_term) for x in df1[\"x\"]])\n \ndf1[\"y_actual\"] = np.cos(df1[\"x\"])\n\ndf1.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
xy3y10y15y20y_actual
0-8.000000-31.0000000000000191.679365079365-11.1999880425277-0.560661521641142-0.145500
1-7.838384-29.7201305989185158.861412892716-8.01837396936362-0.2618280447515120.015597
2-7.676768-28.4663809815325131.132555123681-5.62223682052865-0.007511654209640060.176288
3-7.515152-27.2387511478421107.799204597122-3.822641877071930.2116985661371030.332384
4-7.353535-26.037241097847288.2471659612040-2.475227853442060.4013100107356650.479817
\n
\n\n\n\nIt is clear from the figure below that the higher the order of polynomial (or the number of terms in the summation) more precise the approximates become, even for distant points from which the series was generated at.\n\n\n```python\nfig, ax = plt.subplots(figsize=(13, 8))\nax.set_ylim(-1.5, 1.5)\n\ncolors = [\"red\", \"purple\", \"blue\", \"green\"]\n\nfor max_term, color in zip(max_terms, colors):\n plt.plot(df1[\"x\"], df1[\"y\"+str(max_term)], color=color)\n \nplt.plot(df1[\"x\"], df1[\"y_actual\"], color='black')\n\nplt.legend(loc='lower left', fancybox=True, framealpha=1, shadow=True, borderpad=1, frameon=True)\nax.set(title=r\"Taylor polynomials for $\\cos(x)$\", xlabel=\"x\", ylabel=\"y\");\n```\n\n## Example 2\n\nConsider the function $f:\\mathbb{R}\\rightarrow[-1,1]$ defined as $f(x) = \\exp(x)$.\n\nIts Taylor expansion is given by\n\n$$\\exp(x) = \\sum_{n=0}^{\\infty} \\frac{x^{n}}{n!}, \\forall x \\in \\mathbb{R}$$\n\nThe code below show approximates for this function with 4, 7, 10 and 12 terms in the summation (or orders of the Taylor polynomials). The actual value for the function is also computed.\n\n\n```python\nx = sp.symbols(\"x\")\nf = sp.exp(x)\n\nf_series = functools.partial(taylor, var=x)\n\ndf2 = pd.DataFrame({\"x\": np.linspace(0, 10, num=100)})\n\nmax_terms = [4, 7, 10, 12]\n\nfor max_term in max_terms:\n df2[\"y\" + str(max_term)] = np.array([f_series(f, x, max_terms=max_term) for x in df2[\"x\"]])\n \ndf2[\"y_actual\"] = np.exp(df2[\"x\"])\n\ndf2.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
xy4y7y10y12y_actual
00.000001.000000000000001.000000000000001.000000000000001.000000000000001.000000
10.101011.106283389621821.106287816309831.106287816331391.106287816331391.106288
20.202021.223800429901851.223872729768111.223872732563251.223872732563281.223873
30.303031.353581730992201.353955444394681.353955492773121.353955492774971.353955
40.404041.496657903045011.497864098300011.497864465478751.497864465511881.497864
\n
\n\n\n\nThe conclusion is the same as for the case shown above, namely, the higher the order of polynomial (or the number of terms in the summation) more precise the approximates become, even for distant points from which the series was generated at.\n\n\n```python\nfig, ax = plt.subplots(figsize=(13, 8))\nax.set_ylim(0, 1000)\n\ncolors = [\"red\", \"purple\", \"blue\", \"green\"]\n\nfor max_term, color in zip(max_terms, colors):\n plt.plot(df2[\"x\"], df2[\"y\"+str(max_term)], color=color)\n \nplt.plot(df2[\"x\"], df2[\"y_actual\"], color='black')\n\nplt.legend(loc='lower left', fancybox=True, framealpha=1, shadow=True, borderpad=1, frameon=True)\nax.set(title=r\"Taylor polynomials for $\\exp(x)$\", xlabel=\"x\", ylabel=\"y\");\n```\n", "meta": {"hexsha": "b3fe4a95f35cb5665865314abe9c664e0a4e4542", "size": 144573, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/math/taylor.ipynb", "max_stars_repo_name": "kmyokoyama/machine-learning", "max_stars_repo_head_hexsha": "05c41cfa1d2c070ce4f476a20f5ad0c5bd6a1fe7", "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/math/taylor.ipynb", "max_issues_repo_name": "kmyokoyama/machine-learning", "max_issues_repo_head_hexsha": "05c41cfa1d2c070ce4f476a20f5ad0c5bd6a1fe7", "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/math/taylor.ipynb", "max_forks_repo_name": "kmyokoyama/machine-learning", "max_forks_repo_head_hexsha": "05c41cfa1d2c070ce4f476a20f5ad0c5bd6a1fe7", "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": 281.2704280156, "max_line_length": 77912, "alphanum_fraction": 0.9019941483, "converted": true, "num_tokens": 2889, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.925229961215457, "lm_q2_score": 0.9284088015458666, "lm_q1q2_score": 0.858991639446371}} {"text": "# Basis for grayscale images\n\n## Introduction\n\nConsider the set of real-valued matrices of size $M\\times N$; we can turn this into a vector space by defining addition and scalar multiplication in the usual way:\n\n\\begin{align}\n\\mathbf{A} + \\mathbf{B} &= \n \\left[ \n \\begin{array}{ccc} \n a_{0,0} & \\dots & a_{0,N-1} \\\\ \n \\vdots & & \\vdots \\\\ \n a_{M-1,0} & \\dots & b_{M-1,N-1} \n \\end{array}\n \\right]\n + \n \\left[ \n \\begin{array}{ccc} \n b_{0,0} & \\dots & b_{0,N-1} \\\\ \n \\vdots & & \\vdots \\\\ \n b_{M-1,0} & \\dots & b_{M-1,N-1} \n \\end{array}\n \\right]\n \\\\\n &=\n \\left[ \n \\begin{array}{ccc} \n a_{0,0}+b_{0,0} & \\dots & a_{0,N-1}+b_{0,N-1} \\\\ \n \\vdots & & \\vdots \\\\ \n a_{M-1,0}+b_{M-1,0} & \\dots & a_{M-1,N-1}+b_{M-1,N-1} \n \\end{array}\n \\right] \n \\\\ \\\\ \\\\\n\\beta\\mathbf{A} &= \n \\left[ \n \\begin{array}{ccc} \n \\beta a_{0,0} & \\dots & \\beta a_{0,N-1} \\\\ \n \\vdots & & \\vdots \\\\ \n \\beta a_{M-1,0} & \\dots & \\beta a_{M-1,N-1}\n \\end{array}\n \\right]\n\\end{align}\n\n\nAs a matter of fact, the space of real-valued $M\\times N$ matrices is completely equivalent to $\\mathbb{R}^{MN}$ and we can always \"unroll\" a matrix into a vector. Assume we proceed column by column; then the matrix becomes\n\n$$\n \\mathbf{a} = \\mathbf{A}[:] = [\n \\begin{array}{ccccccc}\n a_{0,0} & \\dots & a_{M-1,0} & a_{0,1} & \\dots & a_{M-1,1} & \\ldots & a_{0, N-1} & \\dots & a_{M-1,N-1}\n \\end{array}]^T\n$$\n\nAlthough the matrix and vector forms represent exactly the same data, the matrix form allows us to display the data in the form of an image. Assume each value in the matrix is a grayscale intensity, where zero is black and 255 is white; for example we can create a checkerboard pattern of any size with the following function:\n\n\n```python\n# usual pyton bookkeeping...\n%matplotlib inline\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport IPython\nfrom IPython.display import Image\nimport math\n```\n\n\n```python\n# ensure all images will be grayscale\nplt.gray();\n```\n\n\n \n\n\n\n```python\n# let's create a checkerboard pattern\nSIZE = 4\nimg = np.zeros((SIZE, SIZE))\nfor n in range(0, SIZE):\n for m in range(0, SIZE):\n if (n & 0x1) ^ (m & 0x1):\n img[n, m] = 255\n\n# now display the matrix as an image\nplt.matshow(img); \n```\n\nGiven the equivalence between the space of $M\\times N$ matrices and $\\mathbb{R}^{MN}$ we can easily define the inner product between two matrices in the usual way:\n\n$$\n\\langle \\mathbf{A}, \\mathbf{B} \\rangle = \\sum_{m=0}^{M-1} \\sum_{n=0}^{N-1} a_{m,n} b_{m, n}\n$$\n\n(where we have neglected the conjugation since we'll only deal with real-valued matrices); in other words, we can take the inner product between two matrices as the standard inner product of their unrolled versions. The inner product allows us to define orthogonality between images and this is rather useful since we're going to explore a couple of bases for this space.\n\n\n## Actual images\n\nConveniently, using IPython, we can read images from disk in any given format and convert them to numpy arrays; let's load and display for instance a JPEG image:\n\n\n```python\nimg = np.array(plt.imread('cameraman.jpg'), dtype=int)\nplt.matshow(img);\n```\n\nThe image is a $64\\times 64$ low-resolution version of the famous \"cameraman\" test picture. Out of curiosity, we can look at the first column of this image, which is is a $64×1$ vector:\n\n\n```python\nimg[:,0]\n```\n\n\n\n\n array([156, 157, 157, 152, 154, 155, 151, 157, 152, 155, 158, 159, 159,\n 160, 160, 161, 155, 160, 161, 161, 164, 162, 160, 162, 158, 160,\n 158, 157, 160, 160, 159, 158, 163, 162, 162, 157, 160, 114, 114,\n 103, 88, 62, 109, 82, 108, 128, 138, 140, 136, 128, 122, 137,\n 147, 114, 114, 144, 112, 115, 117, 131, 112, 141, 99, 97])\n\n\n\nThe values are integers between zero and 255, meaning that each pixel is encoded over 8 bits (or 256 gray levels).\n\n## The canonical basis\n\nThe canonical basis for any matrix space $\\mathbb{R}^{M\\times N}$ is the set of \"delta\" matrices where only one element equals to one while all the others are 0. Let's call them $\\mathbf{E}_n$ with $0 \\leq n < MN$. Here is a function to create the canonical basis vector given its index:\n\n\n```python\ndef canonical(n, M=5, N=10):\n e = np.zeros((M, N))\n e[(n % M), int(n / M)] = 1\n return e\n```\n\nHere are some basis vectors: look for the position of white pixel, which differentiates them and note that we enumerate pixels column-wise:\n\n\n```python\nplt.matshow(canonical(0));\nplt.matshow(canonical(1));\nplt.matshow(canonical(49));\n```\n\n## Transmitting images\n\nSuppose we want to transmit the \"cameraman\" image over a communication channel. The intuitive way to do so is to send the pixel values one by one, which corresponds to sending the coefficients of the decomposition of the image over the canonical basis. So far, nothing complicated: to send the cameraman image, for instance, we will send $64\\times 64 = 4096$ coefficients in a row. \n\nNow suppose that a communication failure takes place after the first half of the pixels have been sent. The received data will allow us to display an approximation of the original image only. If we replace the missing data with zeros, here is what we would see, which is not very pretty:\n\n\n```python\n# unrolling of the image for transmission (we go column by column, hence \"F\")\ntx_img = np.ravel(img, \"F\")\n\n# oops, we lose half the data\ntx_img[int(len(tx_img)/2):] = 0\n\n# rebuild matrix\nrx_img = np.reshape(tx_img, (64, 64), \"F\")\nplt.matshow(rx_img);\n```\n\nCan we come up with a trasmission scheme that is more robust in the face of channel loss? Interestingly, the answer is yes, and it involves a different, more versatile basis for the space of images. What we will do is the following: \n\n* describe the Haar basis, a new basis for the image space\n* project the image in the new basis\n* transmit the projection coefficients\n* rebuild the image using the basis vectors\n\nWe know a few things: if we choose an orthonormal basis, the analysis and synthesis formulas will be super easy (a simple inner product and a scalar multiplication respectively). The trick is to find a basis that will be robust to the loss of some coefficients. \n\nOne such basis is the **Haar basis**. We cannot go into too many details in this notebook but, for the curious, a good starting point is [here](https://chengtsolin.wordpress.com/2015/04/15/real-time-2d-discrete-wavelet-transform-using-opengl-compute-shader/). Mathematical formulas aside, the Haar basis works by encoding the information in a *hierarchical* way: the first basis vectors encode the broad information and the higher coefficients encode the detail. Let's have a look. \n\nFirst of all, to keep things simple, we will remain in the space of square matrices whose size is a power of two. The code to generate the Haar basis matrices is the following: first we generate a 1D Haar vector and then we obtain the basis matrices by taking the outer product of all possible 1D vectors (don't worry if it's not clear, the results are what's important):\n\n\n```python\ndef haar1D(n, SIZE):\n # check power of two\n if math.floor(math.log(SIZE) / math.log(2)) != math.log(SIZE) / math.log(2):\n print(\"Haar defined only for lengths that are a power of two\")\n return None\n if n >= SIZE or n < 0:\n print(\"invalid Haar index\")\n return None\n \n # zero basis vector\n if n == 0:\n return np.ones(SIZE)\n \n # express n > 1 as 2^p + q with p as large as possible;\n # then k = SIZE/2^p is the length of the support\n # and s = qk is the shift\n p = math.floor(math.log(n) / math.log(2))\n pp = int(pow(2, p))\n k = SIZE / pp\n s = (n - pp) * k\n \n h = np.zeros(SIZE)\n h[int(s):int(s+k/2)] = 1\n h[int(s+k/2):int(s+k)] = -1\n # these are not normalized\n return h\n\n\ndef haar2D(n, SIZE=8):\n # get horizontal and vertical indices\n hr = haar1D(n % SIZE, SIZE)\n hv = haar1D(int(n / SIZE), SIZE)\n # 2D Haar basis matrix is separable, so we can\n # just take the column-row product\n H = np.outer(hr, hv)\n H = H / math.sqrt(np.sum(H * H))\n return H\n```\n\nFirst of all, let's look at a few basis matrices; note that the matrices have positive and negative values, so that the value of zero will be represented as gray:\n\n\n```python\nplt.matshow(haar2D(0));\nplt.matshow(haar2D(1));\nplt.matshow(haar2D(10));\nplt.matshow(haar2D(63));\n```\n\nWe can notice two key properties\n\n* each basis matrix has positive and negative values in some symmetric patter: this means that the basis matrix will implicitly compute the difference between image areas\n* low-index basis matrices take differences between large areas, while high-index ones take differences in smaller **localized** areas of the image\n\nWe can immediately verify that the Haar matrices are orthogonal:\n\n\n```python\n# let's use an 8x8 space; there will be 64 basis vectors\n# compute all possible inner product and only print the nonzero results\nfor m in range(0,64):\n for n in range(0,64):\n r = np.sum(haar2D(m, 8) * haar2D(n, 8))\n if r != 0:\n print(\"[%dx%d -> %f] \" % (m, n, r), end=\"\")\n```\n\n [0x0 -> 1.000000] [1x1 -> 1.000000] [2x2 -> 1.000000] [3x3 -> 1.000000] [4x4 -> 1.000000] [5x5 -> 1.000000] [6x6 -> 1.000000] [7x7 -> 1.000000] [8x8 -> 1.000000] [9x9 -> 1.000000] [10x10 -> 1.000000] [11x11 -> 1.000000] [12x12 -> 1.000000] [13x13 -> 1.000000] [14x14 -> 1.000000] [15x15 -> 1.000000] [16x16 -> 1.000000] [16x17 -> -0.000000] [17x16 -> -0.000000] [17x17 -> 1.000000] [18x18 -> 1.000000] [19x19 -> 1.000000] [20x20 -> 1.000000] [21x21 -> 1.000000] [22x22 -> 1.000000] [23x23 -> 1.000000] [24x24 -> 1.000000] [24x25 -> -0.000000] [25x24 -> -0.000000] [25x25 -> 1.000000] [26x26 -> 1.000000] [27x27 -> 1.000000] [28x28 -> 1.000000] [29x29 -> 1.000000] [30x30 -> 1.000000] [31x31 -> 1.000000] [32x32 -> 1.000000] [33x33 -> 1.000000] [34x34 -> 1.000000] [35x35 -> 1.000000] [36x36 -> 1.000000] [37x37 -> 1.000000] [38x38 -> 1.000000] [39x39 -> 1.000000] [40x40 -> 1.000000] [41x41 -> 1.000000] [42x42 -> 1.000000] [43x43 -> 1.000000] [44x44 -> 1.000000] [45x45 -> 1.000000] [46x46 -> 1.000000] [47x47 -> 1.000000] [48x48 -> 1.000000] [49x49 -> 1.000000] [50x50 -> 1.000000] [51x51 -> 1.000000] [52x52 -> 1.000000] [53x53 -> 1.000000] [54x54 -> 1.000000] [55x55 -> 1.000000] [56x56 -> 1.000000] [57x57 -> 1.000000] [58x58 -> 1.000000] [59x59 -> 1.000000] [60x60 -> 1.000000] [61x61 -> 1.000000] [62x62 -> 1.000000] [63x63 -> 1.000000] \n\nOK! Everything's fine. Now let's transmit the \"cameraman\" image: first, let's verify that it works\n\n\n```python\n# project the image onto the Haar basis, obtaining a vector of 4096 coefficients\n# this is simply the analysis formula for the vector space with an orthogonal basis\ntx_img = np.zeros(64*64)\nfor k in range(0, (64*64)):\n tx_img[k] = np.sum(img * haar2D(k, 64))\n\n# now rebuild the image with the synthesis formula; since the basis is orthonormal\n# we just need to scale the basis matrices by the projection coefficients\nrx_img = np.zeros((64, 64))\nfor k in range(0, (64*64)):\n rx_img += tx_img[k] * haar2D(k, 64)\n\nplt.matshow(rx_img);\n```\n\nCool, it works! Now let's see what happens if we lose the second half of the coefficients:\n\n\n```python\n# oops, we lose half the data\nlossy_img = np.copy(tx_img);\nlossy_img[int(len(tx_img)/2):] = 0\n\n# rebuild matrix\nrx_img = np.zeros((64, 64))\nfor k in range(0, (64*64)):\n rx_img += lossy_img[k] * haar2D(k, 64)\n\nplt.matshow(rx_img);\n```\n\nThat's quite remarkable, no? We've lost the same amount of information as before but the image is still acceptable. This is because we lost the coefficients associated to the fine details of the image but we retained the \"broad strokes\" encoded by the first half. \n\nNote that if we lose the first half of the coefficients the result is markedly different:\n\n\n```python\nlossy_img = np.copy(tx_img);\nlossy_img[0:int(len(tx_img)/2)] = 0\n\nrx_img = np.zeros((64, 64))\nfor k in range(0, (64*64)):\n rx_img += lossy_img[k] * haar2D(k, 64)\n\nplt.matshow(rx_img);\n```\n\nIn fact, schemes like this one are used in *progressive encoding*: send the most important information first and add details if the channel permits it. You may have experienced this while browsing the interned over a slow connection. \n\nAll in all, a great application of a change of basis!\n", "meta": {"hexsha": "41d1b238e748c725cfdb26d3c7efc0d3b73bf40d", "size": 125613, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Digital Signal Processing 1 Basic Concepts and Algorithms/Basis for grayscale images.ipynb", "max_stars_repo_name": "chandlerbing65nm/Digital-Signal-Processing-Coursera", "max_stars_repo_head_hexsha": "77036cf9b3f985b5fe9e7ccc48f03ae0f7365e18", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-09-07T16:27:47.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-08T12:42:27.000Z", "max_issues_repo_path": "Digital Signal Processing 1 Basic Concepts and Algorithms/Basis for grayscale images.ipynb", "max_issues_repo_name": "chandlerbing65nm/Digital-Signal-Processing-Coursera", "max_issues_repo_head_hexsha": "77036cf9b3f985b5fe9e7ccc48f03ae0f7365e18", "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": "Digital Signal Processing 1 Basic Concepts and Algorithms/Basis for grayscale images.ipynb", "max_forks_repo_name": "chandlerbing65nm/Digital-Signal-Processing-Coursera", "max_forks_repo_head_hexsha": "77036cf9b3f985b5fe9e7ccc48f03ae0f7365e18", "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": 202.2753623188, "max_line_length": 17388, "alphanum_fraction": 0.8866677812, "converted": true, "num_tokens": 3996, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338090839606, "lm_q2_score": 0.8933094138654242, "lm_q1q2_score": 0.8589472034045815}} {"text": "# Support Vector Machines\n\n## Motivating Support Vector Machines\n### Developing the Intuition\n\nSupport vector machines (SVM) are a powerful and flexible class of supervised algorithms. Developed in the 1990s, SVM have shown to perform well in a variety of settings which explains their popularity. Though the underlying mathematics can become somewhat complicated, the basic concept of a SVM is easily understood. Therefore, in what follows we develop an intuition, introduce the mathematical basics of SVM and ultimately look into how we can apply SVM with Python.\n\nAs an introductory example, borrowed from VanderPlas (2016), consider the following simplified two-dimensional classification task, where the two classes (indicated by the colors) are well separated. \n\n\n\nA linear discriminant classifier as discussed in chapter 8 would attempt to draw a separating hyperplane (which in two dimensions is nothing but a line) in order to distinguish the two classes. For two-dimensional data, we could even do this by hand. However, one problem arises: there are more than one separating hyperplane between the two classes.\n\n\n\nThere exist an infinite number of possible hyperplanes that perfectly discriminate between the two classes in the training data. In above figure we visualize but three of them. Depending on what hyperplane we choose, a new data point (e.g. the one marked by the red \"X\") will be assigned a different label. Yet, so far we have no decision criteria established to decide which one of the three hyperplanes we should choose. \n\nHow do we decide which line best separates the two classes? The idea of SVM is to add a margin of some width to both sides of each hyperplane - up to the nearest point. This might look something like this:\n\n\n\nIn SVM, the hyperplane that maximizes the margin to the nearest points is the one that is chosen as decision boundary. In other words, the maximum margin estimator is what we are looking for. Below figure shows the optimal solution for a (linear) SVM. Of all possible hyperplanes, the solid line has the largest margins (dashed lines) - measured from the decision boundary (solid line) to the nearest points (circled points). \n\n\n\n### Support Vector\n\nThe three circled sample points in above figure represent the nearest points. All three lie along the (dashed) margin line and in terms of perpendicular distance are equidistant from the decision boundary (solid line). Together they form the so called **support vector**. The support vector \"supports\" the maximal margin hyperplane in the sense that if one of the observations were moved slightly, the maximal margin hyperplane would move as well. In other words, they dictate slope and intercept of the hyperplane. Interestingly, any points further from the margin that are on the correct side do not modify the decision boundary. For example points at $(x_1, x_2) = (2.5, 1)$ or $(1, 4.2)$ have no effect on the decision boundary. Technically, this is because these points do not contribute to the loss function used to fit the model, so their position and number do not matter so long as they do not cross the margin (VanderPlas (2016)) . This is an important and helpful property as it simplifies calculations significantly. It is not surprising that computations are a lot faster if a model has only a few data points (in the support vector) to consider (James et al. (2013)). \n\n## Developing the Mathematical Intuition\n### Hyperplanes\n\nTo start, let us do a brief (and superficial) refresher on hyperplanes. In a $p$-dimensional space, a hyperplane is a flat (affine) subspace of dimension $p - 1$. Affine simply indicates that the subspace need not pass through the origin. As we have seen above, in two dimensions a hyperplane is just a line. In three dimensions it is a plane. For $p > 3$ visualization is hardly possible but the notion applies in similar fashion. Mathematically a $p$-dimensional hyperplane is defined by the expression \n\n\\begin{equation}\n\\beta_0 + \\beta_1 x_1 + \\beta_2 x_2 + \\ldots + \\beta_p x_p = 0\n\\end{equation}\n\n\nIf a point $\\mathbf{x}^* = (x^*_1, x^*_2, \\ldots, x^*_p)^T$ (i.e. a vector of length $p$) satisfies the above equation, then $\\mathbf{x}^*$ lies on the hyperplane. If $\\mathbf{x}^{*}$ does not satisfy above equation but yields a value $>0$, that is\n\n\\begin{equation}\n\\beta_0 + \\beta_1 x^*_1 + \\beta_2 x^*_2 + \\ldots + \\beta_p x^*_p > 0\n\\end{equation}\n\nthen this tells us that $\\mathbf{x}^*$ lies on one side of the hyperplane. Similarly, \n\n\\begin{equation}\n\\beta_0 + \\beta_1 x^*_1 + \\beta_2 x^*_2 + \\ldots + \\beta_p x^*_p < 0\n\\end{equation}\n\ntells us that $\\mathbf{x}^*$ lies on the other side of the plane. \n\n### Separating Hyperplanes\n\nSuppose our training sample is a $n \\times p$ data matrix $\\mathbf{X}$ that consists of $n$ observations in $p$-dimensional space, \n\n\\begin{equation*}\n\\mathbf{x}_1 = \n\\begin{pmatrix}\nx_{11} \\\\\n\\vdots \\\\\nx_{1p}\n\\end{pmatrix}, \\; \\ldots, \\; \\mathbf{x}_n = \n\\begin{pmatrix}\nx_{n1} \\\\\n\\vdots \\\\\nx_{np}\n\\end{pmatrix}\n\\end{equation*}\n\nand each observation falls into one of two classes: $y_1, \\ldots, y_n \\in \\{-1, 1\\}$. Then a separating hyperplane has the helpful property that\n\n\\begin{align}\nf(x) = \\beta_0 + \\beta_1 x_{i1} + \\beta_2 x_{i2} + \\ldots + \\beta_p x_{ip} \\quad \\text{is} \\quad\n\\begin{cases}\n> 0 & \\quad \\text{if } y_i =1 \\\\\n< 0 & \\quad \\text{if } y_i = -1 \n\\end{cases}\n\\end{align}\n\nGiven such a hyperplane exists, it can be used to construct a very intuitive classifier: a test observation is assigned to a class based on the side of the hyperplane it lies. This means we simply calculate $f(x^*)$ and if the result is positive, we assign the test observation to class 1, and to class -1 otherwise.\n\n### Maximal Margin Classifier\n\nIf our data can be perfectly separated, then - as alluded to above - there exist an infinite number of separating hyperplanes. Therefore we seek to maximize the margin to the closest training observations (support vector). The result is what we call the *maximal margin hyperplane*. \n\nLet us consider how such a maximal margin hyperplane is constructed. We follow Raschka (2015) in deriving the objective function as this approach is appealing to the intuition. For a mathematically more sound derivation, see e.g. Friedman et al. (2001, chapter 4.5). As before we assume to have a set of $n$ training observations $\\mathbf{x}_1, \\mathbf{x}_2, \\ldots, \\mathbf{x}_n \\in \\mathbb{R}^p$ with corresponding class labels $y_1, y_2, \\ldots, y_n \\in \\{-1, 1\\}$. The hyperplane as our decision boundary we have introduced above. Here is the same in vector notation, where $\\mathbf{\\beta}$ and $\\mathbf{x}$ are vector of dimension $[p \\times 1]$:\n\n\\begin{equation}\n\\beta_0 + \\mathbf{\\beta}^T \\mathbf{x}_{\\text{hyper}} = 0\n\\end{equation}\n\nThis way of writing is much more concise and therefore we will stick to it moving forward. Let us further define the positive and negative margin hyperplanes, which lie parallel to the decision boundary:\n\\begin{align}\n\\beta_0 + \\mathbf{\\beta}^T \\mathbf{x}_{\\text{pos}} &= 1 &\\text{pos. margin} \\\\\n\\beta_0 + \\mathbf{\\beta}^T \\mathbf{x}_{\\text{neg}} &= -1 &\\text{neg. margin}\n\\end{align}\n\n\nBelow you find a visual representationof the above. Notice that the two margin hyperplanes are parallel and the values for $\\beta_0, \\mathbf{\\beta}$ are identical\n\n\n\nIf we subtract the equation for the negative margin from the positive, we get:\n\n\\begin{equation}\n\\mathbf{\\beta}^T (\\mathbf{x}_{\\text{pos}} - \\mathbf{x}_{\\text{neg}}) = 2\n\\end{equation}\n\nLet us normalize both sides of the equation by the length of the vector $\\mathbf{\\beta}$, that is the norm, which is defined as follows:\n\n\\begin{equation}\n\\Vert \\mathbf{\\beta} \\Vert := \\sqrt{\\sum_{i=1}^p \\beta_i^2} = 1\n\\end{equation}\n\nWith that we arrive at the following expression:\n\n\\begin{equation}\n\\frac{\\mathbf{\\beta}^T (\\mathbf{x}_{\\text{pos}} - \\mathbf{x}_{\\text{neg}})}{\\Vert \\mathbf{\\beta}\\Vert} = \\frac{2}{\\Vert \\mathbf{\\beta} \\Vert}\n\\end{equation}\n\nThe left side of the equation can be interpreted as the normalized distance between the positive (upper) and negative (lower) margin. This distance we aim to maximize. Since maximizing the lefthand side of above expression is similar to maximizing the right hand side, we can summarize this in the following optimization problem:\n\n\\begin{equation}\n\\begin{aligned}\n& \\underset{\\beta_0, \\beta_1, \\ldots, \\beta_p}{\\text{maximize}}\n& & \\frac{2}{\\Vert \\mathbf{\\beta} \\Vert} \\\\\n& \\text{subject to} & & \\beta_0 + \\mathbf{\\beta}^T \\mathbf{x}_{i} \\geq \\;\\; 1 \\quad \\text{if } y_i = 1 \\\\\n&&& \\beta_0 + \\mathbf{\\beta}^T \\mathbf{x}_{i} \\leq -1 \\quad \\text{if } y_i = -1 \\\\\n&&& \\text{for } i = 1, \\ldots, N.\n\\end{aligned}\n\\end{equation}\n\nThe two constraints make sure that all positive samples ($y_i = 1$) fall on or above the positive side of the positive margin hyperplane and all negative samples ($y_i = -1$) are on or below the negative margin hyperplane. A few tweaks allow us to write the two constraints as one. We show this by transforming the second constraint, in which case $y_i = -1$:\n\n\\begin{align}\n \\beta_0 + \\mathbf{\\beta}^T \\mathbf{x}_i &\\leq -1 \\\\\n \\Leftrightarrow \\qquad y_i (\\beta_0 + \\mathbf{\\beta}^T \\mathbf{x}_i) &\\geq (-1)y_i \\\\\n \\Leftrightarrow \\qquad y_i (\\beta_0 + \\mathbf{\\beta}^T \\mathbf{x}_i) &\\geq 1\n\\end{align}\n\nThe same can be done for the first constraint - it will yield the same expression. Therefore, our maximization problem can be restated in a slightly simpler form:\n\n\\begin{equation}\n\\begin{aligned}\n& \\underset{\\beta_0, \\beta_1, \\ldots, \\beta_p}{\\text{maximize}}\n& & \\frac{2}{\\Vert \\mathbf{\\beta} \\Vert} \\\\\n& \\text{subject to} & & y_i(\\beta_0 + \\mathbf{\\beta}^T \\mathbf{x}_{i}) \\geq 1 \\quad \\text{for } i = 1, \\ldots, N.\n\\end{aligned}\n\\end{equation}\n\nThis is a convex optimization problem (quadratic criterion with linear inequality constraints) and can be solved with Lagrange. For details refer to appendix (D1) of the script.\n\nNote that in practice it is easier to minimize the reciprocal term of the squared norm of $\\mathbf{\\beta}$, $\\frac{1}{2} \\Vert\\mathbf{\\beta} \\Vert^2$. Therefore the objective function is often given as\n\n\\begin{equation}\n\\begin{aligned}\n& \\underset{\\beta_0, \\beta}{\\text{minimize}}\n& & \\frac{1}{2}\\Vert \\mathbf{\\beta} \\Vert^2 \\\\\n& \\text{subject to} & & y_i(\\beta_0 + \\mathbf{\\beta}^T \\mathbf{x}_{i}) \\geq 1 \\quad \\text{for } i = 1, \\ldots, N.\n\\end{aligned}\n\\end{equation}\n\nThis transformation does not change the optimization problem yet at the same time is computationally easier to be handled by quadratic programming. A detailed discussion of quadratic programming goes beyond the scope of this course. For details, see e.g. Vapnik (2000) or [Burges (1998)](http://www.cmap.polytechnique.fr/~mallat/papiers/svmtutorial.pdf).**\n\n## Support Vector Classifier\n\n### Non-Separable Data\n\nGiven our data is separable into two classes, the maximal margin classifier from before seems like a natural approach. However, it is easy to see that **when the data is not clearly discriminable, no separable hyperplane exists and therefore such a classifier does not exist**. In that case the above maximization problem has no solution. What makes the situation even more complicated is that the maximal margin classifier is very sensitive to changes in the support vectors. This means that this classifier might suffer from inappropriate sensitivity to individual observations and thus it has a substantial risk of overfitting the training data. That is why we might be willing to consider a classifier on a hyperplane that does not perfectly separate the two classes but allows for greater robustness to individual observations and better classification of most of the training observations. In other words it could be worthwhile to misclassify a few training observations in order to do a better job in classifying the test data (James et al. (2013)). \n\n### Details of the Support Vector Classifier\n\nThis is where the Support Vector Classifier (SVC) comes into play. It allows a certain number of observations to be on the 'wrong' side of the hyperplane while seeking a solution where the majority of data points are still on the 'correct' side of the hyperplane. The following figure visualizes this.\n\n\n\nThe SVC still classifies a test observation based on which side of a hyperplane it lies. However, when we train the model, the margins are now somewhat softened. This means that the model allows for a limited number of training observations to be on the wrong side of the margin and hyperplane, respectively. \n\nLet us briefly discuss in general terms how the support vector classifier reaches its optimal solution. For this we extend the optimization problem from the maximum margin classifier as follows: \n\n\\begin{equation}\n\\begin{aligned}\n& \\underset{\\beta_0, \\beta}{\\text{minimize}}\n& & \\frac{1}{2}\\Vert \\mathbf{\\beta} \\Vert^2 + C \\left(\\sum_{i=1}^n \\epsilon_i \\right) \\\\\n& \\text{subject to} & & \\beta_0 + \\mathbf{\\beta}^T \\mathbf{x}_{i} \\geq (1-\\epsilon_i) \\quad \\text{for } i = 1, \\ldots, N. \\\\\n& & & \\epsilon_i \\geq 0 \\quad \\forall i\n\\end{aligned}\n\\end{equation}\n\nThis, again, can be solved with Lagrange similar to the way it is shown for the maximum margin classifier (see appendix (D1)) and it is left to the reader as an exercise to derive the Lagrange (primal and dual) objective function. For the impatient readers will find a solution draft in Friedman et al. (2001), section 12.2.1.\n\nLet us now focus on the added term $C \\left(\\sum_{i=1}^n \\epsilon_i \\right)$. Here, $\\epsilon_1, \\epsilon_2, \\ldots, \\epsilon_n$ are slack variables that allow the individual observations to be on the wrong side of the margin or the hyperplane. They contain information on where the $i$th observation is located, relative to the hyperplane and relative to the margin. \n\n* If $\\epsilon_i = 0$ then the $i$th observation is on the correct side of the margin, \n* if $1 \\geq \\epsilon_i > 0$ it is on the wrong side of the margin but correct side of the hyperplane, and \n* if $\\epsilon_i > 1$ it is on the wrong side of the hyperplane. \n\nThe tuning parameter $C$ can be interpreted as a penalty factor for misclassification. It is defined by the user. Large values of $C$ correspond to a significant error penalty, whereas small values are used if we are less strict about misclassification errors. By controlling for $C$ we indirectly control for the margin and therefore actively tune the bias-variance trade-off. Decreasing the value of $C$ increases the bias but lowers the variance of the model. \n\nBelow figure shows how $C$ impacts the decision boundary and its corresponding margin.\n\n\n\n### Solving Nonlinear Problems\n\nSo far we worked with data that is linearly separable. What makes SVM so powerful and popular is that it can be kernelized to solve nonlinear classification problems. We start our discussion again with illustrations to build an intuition.\n\n\n\nClearly the data is not linear and the resulting (linear) decision boundary is useless. How, then, do we deal with this? With mapping functions. The basic idea is to project the data via some mapping function $\\phi$ onto a higher dimension such that a linear separator would be sufficient. The idea is similar to using quadratic and cubic terms of the predictor in linear regression in order to address non-linearity $(y = \\beta_0 + \\beta_1 x_i + \\beta_2 x_i^2 + \\beta_3 x_i^3 + \\ldots)$ . For example, for the data in the preceding figure we could use the following mapping function $\\phi: \\mathbb{R}^2 \\rightarrow \\mathbb{R}^3$.\n\n\\begin{equation}\n\\phi(x_1, x_2) = (z_1, z_2, z_3) = \\left(x_1, x_2, x_1^2 + x_2^2 \\right)\n\\end{equation}\n\n\n\nHere we enlarge our feature space from $\\mathbb{R}^2 \\rightarrow \\mathbb{R}^3$ in oder to accommodate a non-linear boundary. The transformed data becomes trivially linearly separable. All we have to do is find a plane in $\\mathbb{R}^3$. If we project this decision boundary back onto the original feature space $\\mathbb{R}^2$ (with $\\phi^{-1}$), we have a nonlinear decision boundary. \n\n\n\nHere's an animated visualization of this concept.\n\n\n```python\nfrom IPython.display import YouTubeVideo\nYouTubeVideo('3liCbRZPrZA')\n```\n\n\n\n\n\n\n\n\n\n\n### The Problem with Mapping Functions\nOne could think that this is the recipe to work with nonlinear data: Transform all training data onto a higher-dimensional feature space via some mapping function $\\phi$ train a linear SVM model and use the same function $\\phi$ to transform new (test) data to classify it. \n\nAs attractive as this idea seems, it is unfortunately unfeasible because it quickly becomes computationally too expensive. Here is a hands-on example why: Consider for example a degree-2 polynomial (kernel) transformation of the form $\\phi(x_1, x_2) = (x_1^2, x_2^2, \\sqrt{2} x_1 x_2, \\sqrt{2c} x_1, \\sqrt{2c} x_2, c)$. This means that for a dataset in $\\mathbb{R}^2$ the transformation adds four additional dimensions ($\\mathbb{R}^2 \\rightarrow \\mathbb{R}^6$). If we generalize this, it means that a $d$-dimensional polynomial (Kernel) transformation maps from $\\mathbb{R}^p$ to an ${p + d}\\choose{d}$-dimensional space [(Balcan (2011))](http://www.cs.cmu.edu/%7Eninamf/ML11/lect1020.pdf). Thus for datasets with $p$ large, naively performing such transformations will force most computers to its knees. \n\n### The Kernel Trick\n\nThankfully, not all is lost. It turns out that one does not need to explicitly work in the higher-dimensional space. One can show that when using Lagrange to solve our optimization problem, the training samples are only used to compute the pair-wise dot products $\\langle x_i, x_{j}\\rangle$ (where $x_i, x_{j} \\in \\mathbb{R}^{p}$). This is significant because there exist functions that, given two vectors $x_i$ and $x_{j}$ in $\\mathbb{R}^p$, implicitly compute the dot product between the two vectors in a higher-dimension $\\mathbb{R}^q$ (with $q > p$) without explicitly transforming $x_i, x_{j}$ onto a higher dimension $\\mathbb{R}^q$. Such functions are called **Kernel** functions, written $K(x_i, x_{j})$ [(Kim (2013))](http://www.eric-kim.net/eric-kim-net/posts/1/kernel_trick_blog_ekim_12_20_2017.pdf). \n\nLet us show an example of such a Kernel function (following [Hofmann (2006)](http://www.cogsys.wiai.uni-bamberg.de/teaching/ss06/hs_svm/slides/SVM_Seminarbericht_Hofmann.pdf)). For ease of reading we use $x = (x_1, x_2)$ and $z=(z_1, z_2)$ instead of $x_i$ and $x_{j}$. Consider the Kernel function $K(x, z) = (x^T z)^2$ and the mapping function $\\phi(x) = (x_1^2, \\sqrt{2}x_1 x_2, x_2^2)$. If we were to solve our optimization problem from above with Lagrange, the mapping function appears in the form $\\phi(x)^T \\phi(z)$.\n\n\\begin{align}\n\\phi(x)^T \\phi(z) &= (x_1^2, \\sqrt{2}x_1 x_2, x_2^2)^T (z_1^2, \\sqrt{2}z_1 z_2, z_2^2) \\\\\n &= x_1^2 z_1^2 + 2x_1 z_1 x_2 z_2 + x_2^2 z_2^2 \\\\\n &= (x_1 z_1 + x_2 z_2)^2 \\\\\n &= (x^T z)^2 \\\\\n &= K(x, z)\n\\end{align}\n\nThe mapping function would have transformed the data from $\\mathbb{R}^2 \\rightarrow \\mathbb{R}^3$ and back. The Kernel function, however, stays in $\\mathbb{R}^2$. This is of course only one (toy) example and far away from a proper proof but it provides the intuition of what can be generalized: that by using a Kernel function, e.g. where $K(x_i, x_j) = (x^T z)^2 = \\phi(x_i)^T \\phi(x_j)$, we implicitly transform our data to a higher-dimension without having to explicitly apply a mapping function $\\phi$. This so called \"Kernel Trick\" allows us to efficiently learn nonlinear decision boundaries for SVM. \n\n### Popular Kernel Functions\nNot every random mapping function is also a Kernel function. For a function to be a Kernel function, it needs to have certain properties (see e.g. [Balcan (2011)](http://www.cogsys.wiai.uni-bamberg.de/teaching/ss06/hs_svm/slides/SVM_Seminarbericht_Hofmann.pdf) or [Hofmann (2006)](http://www.cogsys.wiai.uni-bamberg.de/teaching/ss06/hs_svm/slides/SVM_Seminarbericht_Hofmann.pdf) for a discussion). In SVM literature, the following three Kernel functions have emerged as popular choices (Friedman et al. (2001)):\n\n\\begin{align}\nd\\text{th-Degree polynomial} \\qquad K(x_i, x_j) &= (r + \\gamma \\langle x_i, x_j \\rangle)^d \\\\\n\\text{Radial Basis (RBF)} \\qquad K(x_i, x_j) &= \\exp(-\\gamma \\Vert x_i - x_j \\Vert^2) \\\\\n\\text{Sigmoid} \\qquad K(x_i, x_j) &= \\tanh(\\gamma \\langle x_i, x_j \\rangle + r)\n\\end{align}\n\nIn general there is no \"best choice\". With each Kernel having some degree of variability, one has to find the optimal solution by experimenting with different Kernels and playing with their parameter ($\\gamma, r, d$). \n\n### Optimization with Lagrange\n\nWe have mentioned before that the optimization problem of the maximum margin classifier and support vector classifier can be solved with Lagrange. The details of which are beyond the scope of this notebook. However, the interested reader is encouraged to learn the details in the appendix of the script (and the recommended reference sources) as these are crucial in understanding the mathematics/core of SVM and the application of Kernel functions.\n\n## SVM with Scikit-Learn\n### Preparing the Data\n\nHaving build an intuition of how SVM work, let us now see this algorithm applied in Python. We will again use the Scikit-learn package that has an optimized class implemented. The data we will work with is called \"Polish Companies Bankruptcy Data Set\" and was used in Zieba et al. (2014). The full set comprises five data files. Each file contains 64 features plus a class label. The features are ratios derived from the financial statements of the more than 10'000 manufacturing companies considered during the period of 2000 - 2013 (from EBITDA margin to equity ratio to liquidity ratios (quick ratio) etc.. The five files differ in that the first contains data with companies that defaulted/were still running **five** years down the road ('1year.csv'), the second **four** years down the road ('2year.csv') etc. Details can be found in the original publication (Zikeba et al. (2016)) or in the [description provided on the UCI Machine Learning Repository site](https://archive.ics.uci.edu/ml/datasets/Polish+companies+bankruptcy+data) where the data was downloaded from. For our purposes we will use the '5year.csv' file where we should predict defaults within the next year. \n\n\n```python\n%matplotlib inline\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nplt.style.use('seaborn-whitegrid')\nplt.rcParams['font.size'] = 14\n```\n\n\n```python\n# Load data\ndf = pd.read_csv('Data/5year.csv', sep=',')\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
Attr1Attr2Attr3Attr4Attr5Attr6Attr7Attr8Attr9Attr10...Attr56Attr57Attr58Attr59Attr60Attr61Attr62Attr63Attr64class
00.0882380.554720.011341.0205-66.52000.3420400.1094900.577521.08810.32036...0.0809550.2754300.919050.0020247.27114.7343142.7602.55683.25970
1-0.0062020.484650.232981.59986.18250.000000-0.0062021.063401.27570.51535...-0.028591-0.0120351.004700.1522206.09113.2749111.1403.28413.37000
20.1302400.221420.577513.6082120.04000.1876400.1621203.059001.14150.67731...0.1239600.1922900.876040.0000008.79342.987071.5315.10275.61880
3-0.0899510.887000.269271.5222-55.9920-0.073957-0.0899510.127401.27540.11300...0.418840-0.7960200.590742.8787007.65243.3302147.5602.47355.92990
40.0481790.550410.107651.2437-22.95900.0000000.0592800.816821.51500.44959...0.2404000.1071600.770480.13938010.11804.0950106.4303.42943.36220
\n

5 rows × 65 columns

\n
\n\n\n\n\n```python\n# Check for NA values\ndf.isnull().sum()\n```\n\n\n\n\n Attr1 3\n Attr2 3\n Attr3 3\n Attr4 21\n Attr5 11\n ... \n Attr61 15\n Attr62 0\n Attr63 21\n Attr64 107\n class 0\n Length: 65, dtype: int64\n\n\n\n\n```python\n# Calculate % of missing values for 'Attr37'\ndf['Attr37'].isnull().sum() / (len(df))\n```\n\n\n\n\n 0.4311336717428088\n\n\n\nAttribute 37 sticks out with 2'548 of 5'910 (43.1%) missing values. This attribute considers *\"(current assets - inventories) / long-term liabilities\"*. Due to the many missing values we can not use a fill method so let us drop this feature column. \n\n\n```python\n# Drop column with 'Attr37'. \n# Notice that as of Pandas version 0.21.0 you can simply use df.drop(columns=['Attr37'])\ndf = df.drop('Attr37', axis=1)\ndf.iloc[:, 30:38].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
Attr31Attr32Attr33Attr34Attr35Attr36Attr38Attr39
00.077287155.3302.34980.243770.1352301.44930.321010.095457
10.000778108.0503.37792.70750-0.0364751.27570.59380-0.028591
20.14349081.6534.47010.658780.1458601.16980.677310.129100
3-0.138650253.9101.43750.835670.0140271.27540.438300.010998
40.039129140.1202.65832.133600.3642001.51500.512250.240400
\n
\n\n\n\nAs for the other missing values we are left to decide whether we want to remove the corresponding observations (rows) or apply a filling method. The problem with dropping all rows with missing values is that we might lose a lot of valuable information. Therefore in this case we prefer to use a common interpolation technique and impute `NaN` values with the corresponging feature mean. Alternatively we could use '`median`' or '`most_frequent`' as strategy. A convenient way to achieve this imputation is to use the `Imputer` class from `sklearn`.\n\nNotice that as of `sklearn` version 0.20.2 Scikit-learn has [relabeled function `Imputer` we use below to `SimpleImputer()`](https://scikit-learn.org/stable/modules/impute.html). Furthermore, with version 0.22.1 other imputers were introduced, such as a `KNNImputer` or a (yet still experimental) `IterativeImputer`. It is up to the reader to familiarize her-/himself with the available options for imputing. [See Scikit-learn's guide for details](https://scikit-learn.org/stable/modules/impute.html). To check for the Sklearn version you currently run hit `!pip list` in your shell. \n\n\n```python\nfrom sklearn.impute import SimpleImputer\n\n# Impute missing values by mean (axis=0 --> along columns; \n# Notice that argument 'axis=' has been removed as of version 0.20.2)\nipr = SimpleImputer(missing_values=np.nan, strategy='mean')\nipr = ipr.fit(df.values)\nimputed_data = ipr.transform(df.values)\n\n# Assign imputed values to 'df' and check for 'NaN' values\ndf = pd.DataFrame(imputed_data, columns=df.columns)\ndf.isnull().sum().sum()\n```\n\n\n\n\n 0\n\n\n\nNow let us check if we have some categorical features that we need to transform. For this we compare the number of cells in the dataframe with the sum of numeric values (`np.isreal()`). If the result is 0, we do not need to apply a One-Hot-Encoding or LabelEncoding procedure. \n\n\n```python\ndf.shape[0] * df.shape[1] - df.applymap(np.isreal).sum().sum()\n```\n\n\n\n\n 0\n\n\n\nAs we see, the dataframe only consists of real values. Therefore, we can proceed by assigning columns 1-63 to variable `X` and column 64 to `y`.\n\n\n```python\nX = df.iloc[:, :-1].values\ny = df.iloc[:, -1].values\n```\n\n### Applying SVM\n\nHaving assigned the data to `X` and `y` we are now ready to divide the dataset into separate training and test sets.\n\n\n```python\nfrom sklearn.model_selection import train_test_split\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, \n test_size=0.2, \n random_state=0, \n stratify=y)\n```\n\nUnlike e.g. decision tree algorithms SVM are sensitive to the magnitude the data. Therefore scaling our data is recommended. \n\n\n```python\nfrom sklearn.preprocessing import StandardScaler\n\n# Create StandardScaler object\nsc = StandardScaler()\n\n# Standardize features; equal results as if done in two\n# separate steps (first .fit() and then .transform())\nX_train_std = sc.fit_transform(X_train)\n\n# Transform test set\nX_test_std = sc.transform(X_test)\n```\n\nWith the data standardized, we can finally apply a SVM on the data. We import the `SVC` (for Support Vector Classifier) from the Scikit-learn toolbox and create a `svm_linear` object that represents a linear SVM with `C=1`. Recall that `C` helps us control the penalty for misclassification. Large values of `C` correspond to large error penalties and vice-versa. More parameter can be specified. Details are best explained in the function's [documentation page](http://scikit-learn.org/stable/modules/generated/sklearn.svm.SVC.html).\n\n\n```python\nfrom sklearn.svm import SVC\nfrom sklearn import metrics\nimport matplotlib.pyplot as plt\n\n# Create object\nsvm_linear = SVC(kernel='linear', C=1.0)\nsvm_linear\n```\n\n\n\n\n SVC(C=1.0, break_ties=False, cache_size=200, class_weight=None, coef0=0.0,\n decision_function_shape='ovr', degree=3, gamma='scale', kernel='linear',\n max_iter=-1, probability=False, random_state=None, shrinking=True,\n tol=0.001, verbose=False)\n\n\n\nWith the `svm_linear` object ready we can now fit the object to the training data and check for the model's accuracy.\n\n\n```python\n# Fit linear SVM to standardized training set\nsvm_linear.fit(X_train_std, y_train)\n\n# Print results\nprint(\"Observed probability of non-default: {:.2f}\".format(np.count_nonzero(y_train==0) / len(y_train)))\nprint(\"Train score: {:.2f}\".format(svm_linear.score(X_train_std, y_train)))\nprint(\"Test score: {:.2f}\".format(svm_linear.score(X_test_std, y_test)))\n```\n\n Observed probability of non-default: 0.93\n Train score: 0.93\n Test score: 0.93\n\n\n\n```python\n# Predict classes\ny_pred = svm_linear.predict(X_test_std)\n\n# Manual confusion matrix as pandas DataFrame\nconfm = pd.DataFrame({'Predicted': y_pred,\n 'True': y_test})\nconfm.replace(to_replace={0:'Non-Default', 1:'Default'}, inplace=True)\nprint(confm.groupby(['True','Predicted'], sort=False).size().unstack('Predicted'))\n```\n\n Predicted Non-Default Default\n True \n Non-Default 1096.0 4.0\n Default 82.0 NaN\n\n\nIn the same way we can run a Kernel SVM on the data. We have four Kernel options: one linear as introduced above and three non-linear. All of them have hyperparameter available. If these are not specified, default values are taken. [Check the documentation for details](http://scikit-learn.org/stable/modules/generated/sklearn.svm.SVC.html).\n\n* `linear`: linear SVM as shown above with `C` as hyperparameter\n* `rbf`: Radial basis function Kernel with `C, gamma` as hyperparameter\n* `poly`: Polynomial Kernel with `C, degree, gamma, coef0` as hyperparameter\n* `sigmoid`: Sigmoid Kernel with `C, gamma, coef0` as hyperparameter\n\nLet us apply a polynomial Kernel as example.\n\n\n```python\nsvm_poly = SVC(kernel='poly', random_state=1)\nsvm_poly\n```\n\n\n\n\n SVC(C=1.0, break_ties=False, cache_size=200, class_weight=None, coef0=0.0,\n decision_function_shape='ovr', degree=3, gamma='scale', kernel='poly',\n max_iter=-1, probability=False, random_state=1, shrinking=True, tol=0.001,\n verbose=False)\n\n\n\nNot having specified hyperparameter `C, degree, gamma`, and `coef0` we see that the algorithm has taken default values. For `C` it is equal to 1, default `degree` is 3, `gamma=auto` means that the value will be calculated as $1/n_{\\text{features}}$, and `coef0` is set to 0 as default. \n\n\n```python\n# Fit polynomial SVM to standardized training set\nsvm_poly.fit(X_train_std, y_train)\n\n# Print results\nprint(\"Observed probability of non-default: {:.2f}\".format(np.count_nonzero(y_train==0) / len(y_train)))\nprint(\"Train score: {:.2f}\".format(svm_poly.score(X_train_std, y_train)))\nprint(\"Test score: {:.2f}\".format(svm_poly.score(X_test_std, y_test)))\n```\n\n Observed probability of non-default: 0.93\n Train score: 0.94\n Test score: 0.93\n\n\n\n```python\n# Predict classes\ny_pred = svm_poly.predict(X_test_std)\n\n# Manual confusion matrix as pandas DataFrame\nconfm = pd.DataFrame({'Predicted': y_pred,\n 'True': y_test})\nconfm.replace(to_replace={0:'Non-Default', 1:'Default'}, inplace=True)\nprint(confm.groupby(['True','Predicted'], sort=False).size().unstack('Predicted'))\n```\n\n Predicted Non-Default Default\n True \n Non-Default 1096 4\n Default 81 1\n\n\nAs it looks linear and polynomial SVM yield similar results. What is clearly unsatisfactory is the number of true defaults that the SVM missed to detect. Both linear as well as non linear SVM miss to label $\\geq$ 80 defaults [sic]. From a financial perspective, this is unacceptable and raises questions regarding\n* Class imbalance\n* Hyperparameter fine-tuning through cross validation and grid search\n* Feature selection\n* Noise & dimension reduction\n\nwhich we want to address in the next section.\n\n## Dealing with Class Imbalance\n\nWhen we deal with default data sets we observe that the ratio of non-default to default records is heavily skewed towards non-default. This is a common problem in real-world data set: Samples from one class or multiple classes dominate the data set. For the present data set we are talking 93% non-defaults vs. 7% defaults. Having an algorithm that predicts non-default 100 out of a 100 times is right in 93% of the cases. Therefore, training a model on such a data set that achieves the same 93% test accuracy (as our SVM above) means nothing else than our model hasn't learned anything informative from the features provided in this data set. Thus, when assessing a classifier on an imbalanced data set we have learned that other metrics such as precision, recall, ROC curve etc. might be more informative. \n\nHaving said that, what we have to consider is that a class imbalance might influences a learning algorithm during the model fitting itself. Machine learning algorithms typically optimize a reward or cost function. This means that an algorithm implicitly learns the model that optimizes the predictions based on the most abundant class in the dataset in order to minimize the cost or maximize the reward during the training phase. And this in turn might yield skewed results in case of imbalanced data sets.\n\nThere are several options to deal with class imbalance, we will discuss two of them. The first option is to set the `class_weight` parameter to `class_weight='balanced'`. Most classifier hae this option implemented (of the introduced classifiers, KNN, LDA and QDA lack such a parameter). This will assign a larger penalty to wrong predictions on the minority class.\n\n\n```python\n# Initiate and fit a polynomial SVM to training set\nsvm_poly = SVC(kernel='poly', random_state=1, class_weight='balanced')\nsvm_poly.fit(X_train_std, y_train)\n\n# Predict classes and print results\ny_pred = svm_poly.predict(X_test_std)\nprint(metrics.classification_report(y_test, y_pred))\nprint(metrics.confusion_matrix(y_test, y_pred))\nprint(\"Test score: {:.2f}\".format(svm_poly.score(X_test_std, y_test)))\n```\n\n precision recall f1-score support\n \n 0.0 0.93 0.99 0.96 1100\n 1.0 0.12 0.02 0.04 82\n \n accuracy 0.92 1182\n macro avg 0.53 0.51 0.50 1182\n weighted avg 0.88 0.92 0.89 1182\n \n [[1086 14]\n [ 80 2]]\n Test score: 0.92\n\n\nThe second option we want to discuss is up- & downsampling of the minority/majority class. Both up- and downsampling are implemented in Scikit-learn through the `resample` function and depending on the data and given the task at hand, one might be better suited than the other. For the upsampling, scikit-learn will apply a bootstrapping to draw new samples from the datasets with replacement. This means that the function will repeatedly draw new samples from the minority class until it contains the number of samples we define. Here's a code example:\n\n\n```python\npd.DataFrame(X[y==1]).shape\n```\n\n\n\n\n (410, 63)\n\n\n\n\n```python\nX[y==0].shape\n```\n\n\n\n\n (5500, 63)\n\n\n\n\n```python\nfrom sklearn.utils import resample\n\n# Upsampling: define which rows you want to upsample \n# (i.e. all columns of X where value in corresponding y vector is equal to 1: X[y==1], \n# and similar for y[y==1]. Then define how many samples should be generated through\n# bootstrapping (here: X[y==0].shape[0] = 5'500))\nX_upsampled, y_upsampled = resample(X[y==1], y[y==1],\n replace=True,\n n_samples=X[y==0].shape[0],\n random_state=1)\nprint('No. of default samples BEFORE upsampling: {:.0f}'.format(y.sum()))\nprint('No. of default samples AFTER upsampling: {:.0f}'.format(y_upsampled.sum()))\n```\n\n No. of default samples BEFORE upsampling: 410\n No. of default samples AFTER upsampling: 5500\n\n\nDownsampling works in similar fashion. \n\n\n```python\n# Downsampling\nX_dnsampled, y_dnsampled = resample(X[y==0], y[y==0],\n replace=False,\n n_samples=X[y==1].shape[0],\n random_state=1)\n```\n\nRunning the SVM algorighm on the balanced dataset works now as you would expect:\n\n\n```python\n# Combine datasets\nX_bal = np.vstack((X[y==1], X_dnsampled))\ny_bal = np.hstack((y[y==1], y_dnsampled))\n\n# Train test split\nX_train_bal, X_test_bal, y_train_bal, y_test_bal = \\\n train_test_split(X_bal, y_bal, \n test_size=0.2, \n random_state=0, \n stratify=y_bal)\n \n# Standardize features; equal results as if done in two\n# separate steps (first .fit() and then .transform())\nX_train_bal_std = sc.fit_transform(X_train_bal)\n\n# Transform test set\nX_test_bal_std = sc.transform(X_test_bal)\n\n# Initiate and fit a polynomial SVM to training set\nsvm_poly_bal = SVC(kernel='poly', random_state=1)\nsvm_poly_bal.fit(X_train_bal_std, y_train_bal)\n\n\n# Predict classes and print results\ny_pred_bal = svm_poly_bal.predict(X_test_bal_std)\nprint(metrics.classification_report(y_test_bal, y_pred_bal))\nprint(metrics.confusion_matrix(y_test_bal, y_pred_bal))\nprint(\"Test score: {:.2f}\".format(svm_poly_bal.score(X_test_bal_std, y_test_bal)))\n```\n\n precision recall f1-score support\n \n 0.0 0.51 1.00 0.68 82\n 1.0 1.00 0.05 0.09 82\n \n accuracy 0.52 164\n macro avg 0.76 0.52 0.39 164\n weighted avg 0.76 0.52 0.39 164\n \n [[82 0]\n [78 4]]\n Test score: 0.52\n\n\nBy applying a SVM to a balanced set of data we improve our model slightly. Yet there remains some work to be done. The polynomial SVM still misses out on 95.1% (=78/82) of the default cases. \n\nIt should be said that in general using an upsampled set is to be preferred over a downsampled set. However, here we are talking 11'000 observations times 63 features for the upsampled set and this can easily take quite some time to run models on, especially if we compute a grid search as in the next section. For this reason the downsampled set was used.\n\n## Hyperparameter Fine-Tuning\n### Pipelines\n\nAnother tool that is of help in optimizing our model is the `GridSearchCV` function introduced in the previous chapter that finds the best hyperparameter through a brute-force (cross validation) approach. Yet before we simply copy-past the code from the last chapter we ought to address a subtle yet important difference between the decision tree and SVM (or most other ML) algorithms that has implications on the application: Decision tree algorithms are of the few models where data scaling is not necessary. SVM on the other hand are (as most ML algorithms) fairly sensitive to the magnitude of the data. Now you might say that this is precisely why we standardized the data at the very beginning and with that we are good to go. In principle, this is correct. However, if we are precise, we commit a subtle yet possibly significant thought error. \n\nIf we decide to apply a grid search using cross validation to find the optimal hyperparameter for e.g. a SVM we unfortunately can not just scale the full data set at the very beginning and then be good for the rest of the process. Conceptually it is important to understand why. Assume we have a data set. As we learned in the chapter on feature scaling and cross validation, applying a scaling on the combined data set and splitting the set into training and holdout set after the scaling is wrong. The reason is that information from the test set found its way into the model and distorts the results. The training set is scaled not only based on information from that set but also based on information from the test set. \n\nNow the same is true if we apply a gridsearch process with cross validation on a training set. For each fold in the CV, some part of the training set will be declared as the training part, and some the test part. The test part within this split is used to measure the performance of our model trained on the training part. However, if we simply scale the training set and then apply gridsearch-CV on the scaled training set we would commit the same thought error as if we simply scale the full set at the very beginning. The test fold (of the CV split) would no longer be independent but implicitly already be part of the training set we used to fit the model. This is fundamentally different from how new data looks to the model. The test data within each cross validation split would no longer correctly mirrors how new data would look to the modeling process. Information already leaked from the test data into our modeling process. This would lead to overly optimistic results during cross validation, and possibly the selection of suboptimal parameter (Müller & Guido (2017)).\n\nWe have not addressed this problem in the chapter on cross validation because so far we have not introduced the tool to deal with it. Furthermore, if our data set is homogeneous and of some size, this is less of an issue. Yet as Scikit-learn provides a fantastic tool to deal with this (and many other) issue(s), we want to introduce it here. The tool is called **pipelines** and allows to combine multiple processing steps in a very convenient and proper way. Let us look at how we can use the `Pipeline` class to express the end-to-end workflow. First we build a pipeline object. This object is provided a list of steps. Each step is a tuple containing a name (you define) and an instance of an estimator. \n\n\n```python\nfrom sklearn.pipeline import Pipeline\n\n# Create pipeline object with standard scaler and SVC estimator\npipe = Pipeline([('scaler', StandardScaler()), \n ('svm_poly', SVC(kernel='poly', random_state=0))])\n```\n\nNext we define a parameter grid to search over and construct a `GridSearchCV` from the pipeline and the parameter grid. Notice that we have to specify for each parameter which step of the pipeline it belongs to. This is done by calling the name we gave this step, followed by a double underscore and the parameter name. For the present example, let us compare different degrees, and `C` values.\n\n\n```python\n# Define parameter grid\nparam_grid = {'svm_poly__C': [0.1, 1, 10, 100],\n 'svm_poly__degree': [1, 2, 3, 5, 7]}\n```\n\nWith that we can run a `GridSearchCV` as usual.\n\n\n```python\nfrom sklearn.model_selection import GridSearchCV\n\n# Run grid search\ngrid = GridSearchCV(pipe, param_grid=param_grid, cv=5, n_jobs=-1)\ngrid.fit(X_train_bal, y_train_bal)\n\n# Print results\nprint('Best CV accuracy: {:.2f}'.format(grid.best_score_))\nprint('Test score: {:.2f}'.format(grid.score(X_test_bal, y_test_bal)))\nprint('Best parameters: {}'.format(grid.best_params_))\n```\n\n Best CV accuracy: 0.73\n Test score: 0.78\n Best parameters: {'svm_poly__C': 100, 'svm_poly__degree': 1}\n\n\nNotice that thanks to the pipeline object, now for each split in the cross validation the `StandardScaler` is refit with only the training splits and no information is leaked from the test split into the parameter search. \n\nDepending on the grid you search, computations might take quite some time. One way to improve speed is by reducing the feature space; that is reducing the number of features. We will discuss feature selection and dimension reduction options in the next section but for the moment, let us just apply a method called Principal Component Analysis (PCA). PCA effectively transforms the feature space from $\\mathbb{R}^{p} \\rightarrow \\mathbb{R}^{q}$ with $q$ being a user specified value (but usually $q < < p$). PCA is similar to other preprocessing steps and can be included in pipelines as e.g. `StandardScaler`. \n\nHere we reduce the feature space from $\\mathbb{R}^{63}$ (i.e. $p=63$ features) to $\\mathbb{R}^{2}$. This will make the fitting process faster. However, this comes at a cost: by reducing the feature space we might not only get rid of noise but also lose part of the information available in the full dataset. Our model accuracy might suffer as a consequence. Furthermore, the speed that we gain by fitting a model to a smaller subset can be set off by the additional computations it takes to calculate the PCA. In the example of the upsampled data set we would be talking of an $[11'000 \\cdot 0.8 \\cdot 0.8 \\times 63]$ matrix (0.8 for the train/test-split and each cv fold) for which eigenvector and eigenvalues need to be calculated. This means up to 63 eigenvalues per grid search loop. \n\n\n```python\nfrom sklearn.decomposition import PCA\n\n# Create pipeline object with standard scaler, PCA and SVC estimator\npipe = Pipeline([('scaler', StandardScaler()), \n ('pca', PCA(n_components=2)),\n ('svm_poly', SVC(kernel='poly', random_state=0))])\n\n# Define parameter grid\nparam_grid = {'svm_poly__C': [100],\n 'svm_poly__degree': [1, 2, 3]}\n\n# Run grid search\ngrid = GridSearchCV(pipe, param_grid=param_grid, cv=5, n_jobs=-1)\ngrid.fit(X_train_bal, y_train_bal)\n\n# Print results\nprint('Best CV accuracy: {:.2f}'.format(grid.best_score_))\nprint('Test score: {:.2f}'.format(grid.score(X_test_bal, y_test_bal)))\nprint('Best parameters: {}'.format(grid.best_params_))\n```\n\n Best CV accuracy: 0.62\n Test score: 0.76\n Best parameters: {'svm_poly__C': 100, 'svm_poly__degree': 1}\n\n\nOther so called preprocessing steps can be included in the pipeline too. This shows how seamless such workflows can be steered through pipelines. We can even combine multiple models as we show in the next code snippet. By now you are probably aware that trying all possible solutions is not a viable machine learning strategy. Computational power is certainly going to be an issue. Nevertheless, for the record we provide below an example where we apply logistic regression and a SVM with RBF kernel to find the best solution (details see section on PCA below). \n\n\n```python\nfrom sklearn.linear_model import LogisticRegression\n\n# Create pipeline object with standard scaler, PCA and SVC estimator\npipe = Pipeline([('scaler', StandardScaler()), \n ('classifier', SVC(random_state=0))])\n\n# Define parameter grid\nparam_grid = [{'scaler': [StandardScaler()],\n 'classifier': [SVC(kernel='rbf')],\n 'classifier__gamma': [1, 10],\n 'classifier__C': [10, 100]},\n {'scaler': [StandardScaler(), None],\n 'classifier': [LogisticRegression(max_iter=1000)],\n 'classifier__C': [10, 100]}]\n\n# Run grid search\ngrid = GridSearchCV(pipe, param_grid, cv=5, n_jobs=-1)\ngrid.fit(X_train_bal, y_train_bal)\n\n# Print results\nprint('Best CV accuracy: {:.2f}'.format(grid.best_score_))\nprint('Test score: {:.2f}'.format(grid.score(X_test_bal, y_test_bal)))\nprint('Best parameters: {}'.format(grid.best_params_))\n```\n\n Best CV accuracy: 0.75\n Test score: 0.76\n Best parameters: {'classifier': SVC(C=100, break_ties=False, cache_size=200, class_weight=None, coef0=0.0,\n decision_function_shape='ovr', degree=3, gamma=1, kernel='rbf', max_iter=-1,\n probability=False, random_state=None, shrinking=True, tol=0.001,\n verbose=False), 'classifier__C': 100, 'classifier__gamma': 1, 'scaler': StandardScaler(copy=True, with_mean=True, with_std=True)}\n\n\nFrom the above output we see that the SVC yields the best accuracy.\n\n## Feature Selection and Dimensionality Reduction\n### Complexity and the Curse of Overfitting\n\nIf we observe that a model performs much better on training than on test data, we have an indication that the model suffers from overfitting. The reason for the overfitting is most probably that our model is too complex for the given training data. Common solutions to reduce the generalization error are (Raschka (2015)):\n* Collect more (training) data\n* Introduce a penalty for complexity via regularization\n* Choose a simpler model with fewer parameter\n* Reduce the dimensionality of the data\n\nCollecting more data is self explanatory but often not applicable. Regularization via a complexity penalty term is a technique that is primarily applicable to regression settings (e.g. logistic regression). We will not discuss it here but the interested reader will easily find helpful information in e.g. James et al. (2013) chapter 6 or Raschka (2015) chapter 4. Here we will look at one commonly used solution to reduce overfitting: dimensionality reduction via feature selection. \n\n\n### Feature Selection\n\nA useful approach to select relevant features from a data set is to use information from the random forest algorithm we introduced in the previous chapter. There we elaborated how decision trees rank the feature importance based on a impurity decrease. Conveniently, we can access this feature importance rank directly from the `RandomForestClassifier` object. By executing below code - following the example in Raschka (2015) - we will train a random forest model on the balanced default data set (from before) and rank the features by their respective importance measure.\n\n\n```python\nfrom sklearn.ensemble import RandomForestClassifier\n\n# Extract feature labels\nfeat_labels = df.columns[:-1]\n\n# Create Random Forest object, fit data and\n# extract feature importance attributes\nforest = RandomForestClassifier(random_state=1)\nforest.fit(X_train_bal, y_train_bal)\nimportances = forest.feature_importances_\n```\n\n\n```python\n# Sort output (by relative importance) and \n# print top 15 features\nindices = np.argsort(importances)[::-1]\nn = 15\nfor i in range(n):\n print('{0:2d}) {1:7s} {2:6.4f}'.format(i + 1, \n feat_labels[indices[i]],\n importances[indices[i]]))\n```\n\n 1) Attr27 0.0531\n 2) Attr26 0.0374\n 3) Attr16 0.0369\n 4) Attr21 0.0354\n 5) Attr39 0.0339\n 6) Attr13 0.0336\n 7) Attr35 0.0313\n 8) Attr29 0.0268\n 9) Attr42 0.0261\n 10) Attr41 0.0238\n 11) Attr25 0.0227\n 12) Attr15 0.0220\n 13) Attr7 0.0219\n 14) Attr46 0.0209\n 15) Attr11 0.0207\n\n\nThe value in decimal is the relative importance for the respective feature. We can also plot this result to have a better overview. Below code shows one way of doing it.\n\n\n```python\n# Get cumsum of the n most important features\nfeat_imp = np.sort(importances)[::-1]\nsum_feat_imp = np.cumsum(feat_imp)[:n]\n```\n\n\n```python\n# Plot Feature Importance (both cumul., individual)\nplt.figure(figsize=(12, 8))\nplt.bar(range(n), importances[indices[:n]], align='center')\nplt.xticks(range(n), feat_labels[indices[:n]], rotation=90)\nplt.xlim([-1, n])\nplt.xlabel('Feature')\nplt.ylabel('Rel. Feature Importance')\nplt.step(range(n), sum_feat_imp, where='mid', \n label='Cumulative importance')\nplt.tight_layout();\n```\n\nExecuting the code will rank the different features according to their relative importance. The definition of each `AttrXX` we would have to [look up in the data description](https://archive.ics.uci.edu/ml/datasets/Polish+companies+bankruptcy+data). Note that the feature importance values are normalized such that they sum up to 1.\n\nFeature selection in the way shown in the preceding code snippets will not work in combination with a `pipeline` object. However, Scikit-learn has implemented such a function that could be used in a preprocessing step. Its name is `SelectFromModel` and details can be found [here](http://scikit-learn.org/stable/modules/feature_selection.html#feature-selection-using-selectfrommodel). Instead of selecting the top $n$ features you define a threshold, which selects those features whose combined importance is greater or equal to said threshold (e.g. mean, median etc.). For reference, below it is shown how the function is applied inside a pipeline.\n\n\n```python\nfrom sklearn.feature_selection import SelectFromModel\n\npipe = Pipeline([('feature_selection', SelectFromModel(RandomForestClassifier(), threshold='median')),\n ('scaler', StandardScaler()),\n ('classification', SVC())])\npipe.fit(X_train_bal, y_train_bal).score(X_test_bal, y_test_bal)\n```\n\n\n\n\n 0.8170731707317073\n\n\n\n### Principal Component Analysis\n\nIn the previous section you learned an approach for reducing the dimensionality of a data set through feature selection. An alternative to feature selection is feature extraction, of which Principal Component Analysis (PCA) is the best known and most popular approach. It is an unsupervised method that aims to summarize the information content of a data set by transforming it onto a new feature subspace of lower dimensionality than the original one. With the rise of big data, this is a field that is gaining importance by the day. PCA is widely used in a variety of field - e.g. in finance to de-noise signals in stock market trading, create factor models, for feature selection in bankruptcy prediction, dimensionality reduction of high frequency data etc.. Unfortunately, the scope of this course does not allow us to discuss PCA in great detail. Nevertheless the fundamentals shall be addressed here briefly so that the reader has a good understanding of how PCA helps in reducing dimensionality. \n\nTo build an intuition for PCA we quote the excellent James et al. (2013, p. 375): *\"PCA finds a low-dimensional representation of a dataset that contains as much as possible of the **variation**. The idea is that each of the $n$ observations lives in $p$-dimensional space, but not all of these dimensions are equally interesting. PCA seeks a small number of dimensions that are as interesting as possible, where the concept of interesting is measured by the amount that the observation vary along each dimension. Each of the dimensions found by PCA is a linear combination of the $p$ features.\"* Since each principal component is required to be orthogonal to all other principal components, we basically take correlated original variables (features) and replace them with a small set of principal components that capture their joint variation. \n\nBelow figures aim at visualizing the idea of principal components. In both figures we see the same two-dimensional dataset. PCA searches for the principal axis along which the data varies most. These principal axis measure the variance of the data when projected onto that axis. The two vectors (arrows) in the left plot visualize this. Notice that given an $[n \\times p]$ feature matrix $\\mathbf{X}$ there are at most $\\min(n-1, p)$ principal components. The figure on the right-hand side displays the projection of the data points projected onto the first principal axis. In this way we have reduced the dimensionality from $\\mathbf{R}^2$ to $\\mathbf{R}^1$. In practice, PCA is of course primarily used for datasets with $p$ large and the selected number of principal components $q$ is usually much smaller than the dimension of the original dataset ($q << p)$.\n\n\n\nThe first principal component is the direction in space along which (orthogonal) projections have the largest variance. The second principal component is the direction which maximizes variance among all directions while being orthogonal to the first. The $k^{\\text{th}}$ component is the variance-maximizing direction orthogonal to the previous $k-1$ components. \n\nHow do we express this in mathematical terms? Let $\\mathbf{X}$ be an $n \\times p$ dataset and let it be centered (i.e. each column mean is zero; notice that standardization is very important in PCA). The $p \\times p$ variance-covariance matrix $\\mathbf{C}$ is then equal to $\\mathbf{C} = \\frac{1}{n} \\mathbf{X}^T \\mathbf{X}$. Additionally, let $\\mathbf{\\phi}$ be a unit $p$-dimensional vector, i.e. $\\phi \\in \\mathbb{R}^p$ and let $\\sum_{i=1}^p \\phi_{i1}^2 = \\mathbf{\\phi}^T \\mathbf{\\phi} = 1$.\n\nThe projections of the individual data points onto the principal axis are given by the linear combination of the form \n\n\\begin{equation}\nZ_{i} = \\phi_{1i} X_{1} + \\phi_{2i} X_{2} + \\ldots + \\phi_{pi} X_{p}.\n\\end{equation}\n\nIn matrix notation we write\n\n\\begin{equation}\n\\mathbf{Z} = \\mathbf{X \\phi}\n\\end{equation}\n\nSince each column vector $X_i$ is standardized, i.e. $\\frac{1}{n} \\sum_{i=1}^n x_{ip} = 0$, the average of $Z_i$ (the column vector for feature $i$) will be zero as well. With that, the variance of $\\mathbf{Z}$ is \n\n\\begin{align}\n\\text{Var}(\\mathbf{Z}) &= \\frac{1}{n} (\\mathbf{X \\phi})^T (\\mathbf{X \\phi}) \\\\\n &= \\frac{1}{n} \\mathbf{\\phi}^T \\mathbf{X}^T \\mathbf{X \\phi} \\\\\n &= \\mathbf{\\phi}^T \\frac{\\mathbf{X}^T \\mathbf{X}}{n} \\mathbf{\\phi} \\\\\n &= \\mathbf{\\phi}^T \\mathbf{C} \\mathbf{\\phi}\n\\end{align}\n\nNote that it is common standard to use the population estimation of variance (division by $n$) instead of the sample variance (division by $n-1$). \n\nNow, PCA seeks to solve a sequence of optimization problems:\n\n\\begin{equation}\n\\begin{aligned}\n& \\underset{\\mathbf{\\phi}}{\\text{maximize}} & & \\text{Var}(\\mathbf{Z})\\\\\n& \\text{subject to} & & \\mathbf{\\phi}^T \\mathbf{\\phi}=1, \\quad \\phi \\in \\mathbb{R}^p \\\\\n&&& \\mathbf{Z}^T \\mathbf{Z} = \\mathbf{ZZ}^T = \\mathbf{I}.\n\\end{aligned}\n\\end{equation}\n\nLooking at the above term it should be clear why we haver restricted vector $\\mathbf{\\phi}$ to be a unit vector. If not, we could simply increase $\\mathbf{\\phi}$ - which is not what we want. This problem can be solved with Lagrange and via an eigen decomposition (a standard technique in linear algebra). The details of which are explained in the appendix of the script. \n\nHow we apply PCA within a pipeline workflow we have shown above. A more general setup is shown in below code snippet. We again make use of the polish bankruptcy set introduced above.\n\n\n```python\nfrom sklearn.decomposition import PCA\n\n# Define no. of PC\nq = 10\n\n# Create PCA object and fit to find \n# first q principal components\npca = PCA(n_components=q)\npca.fit(X_train_bal)\npca\n```\n\n\n\n\n PCA(copy=True, iterated_power='auto', n_components=10, random_state=None,\n svd_solver='auto', tol=0.0, whiten=False)\n\n\n\nTo close, one last code snippet is provided. Running it will visualize the cumulative explained variance ratio as a function of the number of components. (Mathematically, the explained variance ratio is the ratio of the eigenvalue of principal component $i$ to the sum of the eigenvalues, $\\frac{\\lambda_i}{\\sum_{i}^p \\lambda_i}$. See the appendix in the script to better understand the meaning of eigenvalues in this context.) In practice, this might be helpful in deciding on the number of principal components $q$ to use.\n\n\n```python\n# Run PCA for all possible PCs\npca = PCA().fit(X_train_bal)\n\n# Define max no. of PC\nq = X_train_bal.shape[1]\n\n# Get cumsum of the PC 1-q\nexpl_var = pca.explained_variance_ratio_\nsum_expl_var = np.cumsum(expl_var)[:q]\n```\n\n\n```python\n# Plot Feature Importance (both cumul., individual)\nplt.figure(figsize=(12, 6))\nplt.bar(range(1, q + 1), expl_var, align='center')\nplt.xticks(range(1, q + 1, 5))\nplt.xlim([0, q + 1])\nplt.xlabel('Principal Components')\nplt.ylabel('Explained Variance Ratio')\nplt.step(range(1, 1 + q), sum_expl_var, where='mid')\nplt.tight_layout();\n```\n\nThis shows us that the first 5 principal components explain basically all variation in the data. Therefore we could focus to work with only these. \n\n# Further Ressources\n\n\nIn writing this notebook, many ressources were consulted. For internet ressources the links are provided within the textflow above and will therefore not be listed again. Beyond these links, the following ressources were consulted and are recommended as further reading on the discussed topics:\n\n* Burges, Christopher J.C., 1998, A tutorial on support vector machines for pattern recognition, Data mining and knowledge discovery 2.2, 121-167.\n* Friedman, Jerome, Trevor Hastie, and Robert Tibshirani, 2001, *The Elements of Statistical Learning* (Springer, New York, NY).\n* James, Gareth, Daniela Witten, Trevor Hastie, and Robert Tibshirani, 2013, *An Introduction to Statistical Learning: With Applications in R* (Springer Science & Business Media, New York, NY).\n* Müller, Andreas C., and Sarah Guido, 2017, *Introduction to Machine Learning with Python* (O’Reilly Media, Sebastopol, CA).\n* Raschka, Sebastian, 2015, *Python Machine Learning* (Packt Publishing Ltd., Birmingham, UK).\n* Shalizi, Cosma Rohilla, 2017, Advanced Data Analysis from an Elementary Point of View from website, http://www.stat.cmu.edu/~cshalizi/ADAfaEPoV/ADAfaEPoV.pdf, 08/24/17.\n* VanderPlas, Jake, 2016, *Python Data Science Handbook* (O'Reilly Media, Sebastopol, CA).\n* Vapnik, Vladimir N., 2013, *The Nature of Statistical Learning* (Springer, New York, NY).\n\n\n", "meta": {"hexsha": "e174a7302edaac21e2c5986f4917fc6180abf6a5", "size": 150297, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "0211_SVM.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": "0211_SVM.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": "0211_SVM.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": 73.7473012758, "max_line_length": 24292, "alphanum_fraction": 0.7414053507, "converted": true, "num_tokens": 17589, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418116217418, "lm_q2_score": 0.9294404008810105, "lm_q1q2_score": 0.858934735864615}} {"text": "# Minimum Trajectories\n\n## Overview\nNotebook and code to derive minimum trajectories. This notebook starts with minimum snap trajectories between 2 points and then explores multi-waypoint minimum snap trajectories. Finally, we finish off with lower derivative minimum trajectories (jerk, acceleration and velocity), which are derivied in a similar fashion but with less coefficients and boundary conditions.\n\n**DISCLAIMER:** I only have a loose understanding of the math involved - please feel free to submit a pull request with a better/accurate explanation.\n\nTo control a quadcopter through a give set of waypoints, we desire a smooth trajectory. The criteria of smoothness can be defined as minimizing the rate of change of the input or minimizing a lower derivative of position.\n\n[Calculus of variations](https://en.wikipedia.org/wiki/Calculus_of_variations) can be used to minimize a lower derivative function to achieve the desired smoothness: \"Functions that maximize or minimize functionals may be found using the [Euler–Lagrange](https://en.wikipedia.org/wiki/Euler%E2%80%93Lagrange_equation) equation of the calculus of variations\". \n\nFor a function $x(t)$, the stationary values of the functional: \n\n$I[x] = \\int_{t=t_s}^{t_e} \\mathcal{L}(t, x, \\dot{x}, \\ddot{x}, \\ldots, x^{(n-1)}, x^{(n)})\\,dt$ \n\ncan be obtained from the Euler–Lagrange equation: \n\n$\\dfrac{\\partial\\mathcal{L}}{\\partial{x}} - \\dfrac{d}{dt}\\dfrac{\\partial\\mathcal{L}}{\\partial{\\dot{x}}} + \\dfrac{d^2}{dt^2}\\dfrac{\\partial\\mathcal{L}}{\\partial{\\ddot{x}}} - \\ldots + (-1)^k\\dfrac{d^n}{dt^n}\\dfrac{\\partial\\mathcal{L}}{\\partial{x^{(n)}}} = 0$\n\nTo find the shortest distance: \n\n$min I[x] = \\int_{t=t_s}^{t_e} \\mathcal{L}(t, x, \\dot{x})\\,dt = \\int_{t=t_s}^{t_e} (\\dot{x})^2\\, dt$ \n\nSatisfying the requirements of the Euler–Lagrange equation: \n\n$\\dfrac{\\partial\\mathcal{L}}{\\partial{x}} - \\dfrac{d}{dt}\\dfrac{\\partial\\mathcal{L}}{\\partial{\\dot{x}}} = 0$ resulting in $\\ddot{x} = 0$\n\nThis means we wish to find a polynomial that has its 2nd time derivative equal to 0, or a polynomial with 2 coefficients:\n\n$x = c_1t + c_0$\n\nand in general ( **TODO:** need a reference/explanation here as to why the functional is $(x^{(n)})^2$ ):\n\n$min I[x] = \\int_{t=t_s}^{t_e} (x^{(n)})^2\\, dt \\\\\nx^{(2n)} = 0$\n\nand we will need a polynomial with degree $2n - 1$ to satisfy the Euler-Lagrange requirement.\n\nSummary of the minimum trajectory types for values of $n$:\n\n| $n$ | Minimum Type | Euler–Lagrange | Poly. Degree | Num. Coeffs. |\n| --- | ------------ | -------------- | ------------ | ------------ |\n| 1 | Velocity | $\\ddot{x} = 0$ | 1 | 2 |\n| 2 | Acceleration | $x^{(4)} = 0$ | 3 | 4 |\n| 3 | Jerk | $x^{(6)} = 0$ | 5 | 6 |\n| 4 | Snap | $x^{(8)} = 0$ | 7 | 8 |\n\n## Minimum Snap Trajectory\nA minimum snap trajectory can be used to create smooth trajectories to control a quadcopter since the control system for a quadcopter is a fourth order system.\n\nWe want a trajectory defining position of the form: \n$x(t) = c_7t^7 + c_6t^6 + c_5t^5 + c_4t^4 + c_3t^3 + c_2t^2 + c_1t + c_0$\n\nOnce we derive the coefficients, we can then differentiate the resulting polynomial to get the desired velocity and acceleration polynomials, and use these to calculate the desired position, velocity, and accelerations at any time $t$ to give us a minimum snap trajectory, that we can then feed into our position controller.\n\n### Generating a Trajectory for 2 Points\nFor a set of 2 points a and b where the time at position a is $t_s$, and the time at position b is $t_e$, we assume that the velocity and all further time deriviates will be zero (i.e. the object following the trajectory starts and ends at rest):\n\n| | Position | Velocity | Acceleration | Jerk |\n| ------------- | ------------- | -------- | ------------ | ---- |\n| $t = t_s$ | $a$ | 0 | 0 | 0 |\n| $t = t_e$ | $b$ | 0 | 0 | 0 |\n\nThis means we will have 8 unknowns and will need 8 equations to determine the coefficients of the polynomial that will give us the minimum snap trajectory over the given time period. We will be able to evaluate the position, velocity, acceleration, and jerk equations at the start and end times to generate the required equations. Note that this will be in 1-dimension, but we can repeat the process for each dimension - e.g. if we want to generate a trajectory in 3D space, the process will be the same for x, y, and z and we can re-use the A matrix for each dimension.\n\nThe equations are as follows: \n$c_{7}t_s^7 + c_{6}t_s^6 + c_{5}t_s^5 + c_{4}t_s^4 + c_{3}t_s^3 + c_{2}t_s^2 + c_{1}t_s + c_{0} = a \\\\\n c_{7}t_e^7 + c_{6}t_e^6 + c_{5}t_e^5 + c_{4}t_e^4 + c_{3}t_e^3 + c_{2}t_e^2 + c_{1}t_e + c_{0} = b \\\\\n 7c_{7}t_s^6 + 6c_{6}t_s^5 + 5c_{5}t_s^4 + 4c_{4}t_s^3 + 3c_{3}t_s^2 + 2c_{2}t_s + c_{1} = 0 \\\\\n 7c_{7}t_e^6 + 6c_{6}t_e^5 + 5c_{5}t_e^4 + 4c_{4}t_e^3 + 3c_{3}t_e^2 + 2c_{2}t_e + c_{1} = 0 \\\\\n 42c_{7}t_s^5 + 30c_{6}t_s^4 + 20c_{5}t_s^3 + 12c_{4}t_s^2 + 6c_{3}t_s + 2c_{2} = 0 \\\\\n 42c_{7}t_e^5 + 30c_{6}t_e^4 + 20c_{5}t_e^3 + 12c_{4}t_e^2 + 6c_{3}t_e + 2c_{2} = 0 \\\\\n 210c_{7}t_s^4 + 120c_{6}t_s^3 + 60c_{5}t_s^2 + 24c_{4}t_s + 6c_{3} = 0 \\\\\n 210c_{7}t_e^4 + 120c_{6}t_e^3 + 60c_{5}t_e^2 + 24c_{4}t_e + 6c_{3} = 0$ \n \nWe can form an 8x8 matrix A using the above equations, and we can let x be a column vector of the coefficients we wish to find, and b will be a column vector of the RHS. We can then form the system $Ax = b$ and then we can solve for $x = A^{-1}b$\n\n$x = \\begin{bmatrix}\nc_0 \\\\\nc_1 \\\\\nc_2 \\\\\nc_3 \\\\\nc_4 \\\\\nc_5 \\\\\nc_6 \\\\\nc_7\n\\end{bmatrix}$ ,    \n$A = \\begin{bmatrix}\n1 & t_s & t_s^2 & t_s^3 & t_s^4 & t_s^5 & t_s^6 & t_s^7 \\\\\n1 & t_e & t_e^2 & t_e^3 & t_e^4 & t_e^5 & t_e^6 & t_e^7 \\\\\n0 & 1 & 2t_s & 3t_s^2 & 4t_s^3 & 5t_s^4 & 6t_s^5 & 7t_s^6 \\\\\n0 & 1 & 2t_e & 3t_e^2 & 4t_e^3 & 5t_e^4 & 6t_e^5 & 7t_e^6 \\\\\n0 & 0 & 2 & 6t_s & 12t_s^2 & 20t_s^3 & 30t_s^4 & 42t_s^5 \\\\\n0 & 0 & 2 & 6t_e & 12t_e^2 & 20t_e^3 & 30t_e^4 & 42t_e^5 \\\\\n0 & 0 & 0 & 6 & 24t_s & 60t_s^2 & 120t_s^3 & 210t_s^4 \\\\\n0 & 0 & 0 & 6 & 24t_e & 60t_e^2 & 120t_e^3 & 210t_e^4\n\\end{bmatrix}$ ,    \n$b = \\begin{bmatrix}\na \\\\\nb \\\\\n0 \\\\\n0 \\\\\n0 \\\\\n0 \\\\\n0 \\\\\n0\n\\end{bmatrix}$\n\n\n```python\nimport sympy as sp\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nsp.init_printing()\n```\n\n\n```python\nt, T = sp.symbols('t, T')\n\n# define our position and time derivatives\npos = t**7 + t**6 + t**5 + t**4 + t**3 + t**2 + t + 1\nvel = pos.diff(t)\nacc = vel.diff(t)\njerk = acc.diff(t)\nsnap = jerk.diff(t)\ncrac = snap.diff(t)\npop = crac.diff(t)\n\n# print all the equations\neqs = [pos, vel, acc, jerk, snap, crac, pop]\nfor eq in eqs:\n display(eq)\n```\n\n\n```python\n# define matrix print function, courtesy of: https://gist.github.com/braingineer/d801735dac07ff3ac4d746e1f218ab75\ndef matprint(mat, fmt=\"g\"):\n col_maxes = [max([len((\"{:\"+fmt+\"}\").format(x)) for x in col]) for col in mat.T]\n for x in mat:\n for i, y in enumerate(x):\n print((\"{:\"+str(col_maxes[i])+fmt+\"}\").format(y), end=\" \")\n print(\"\")\n```\n\n\n```python\n# since we want to find 8 coefficients, we will need 8 equations, so we can evaluate pos, velocity, acceleration and jerk at time = 0 and time = T\n# we will solve the linear system Ax = b - each row of A will be the coefficients of the evaluated polynomials at the boundary conditions, \n# where the lowest index in the row, 0, corresponds to coefficient 0\nnumcoeffs = 8\nA = np.zeros((numcoeffs, numcoeffs))\n\n# our time range for this polynomial\nstartt = 1\nendt = 6\n\n# let's assume we are starting from (1, 2) and moving to (12, 9) with the above time range\nstart = (1, 2)\nend = (12, 9)\n\ndef coeffs_for_time(equations, numcoeffs, time):\n retval = np.zeros((len(equations), numcoeffs))\n \n for ii, eq in enumerate(equations):\n # pull out the coefficients - ordered from highest to lowest poly order, e.g.: t^3, t^2, t^1, t^0\n coeffs = eq.as_poly().all_coeffs()\n \n # apply time\n exp = len(coeffs) - 1\n for idx in range(len(coeffs)):\n coeffs[idx] *= time**exp\n exp -= 1\n\n # pad out with zeros if some of the coefficients are 0\n while len(coeffs) < numcoeffs:\n coeffs.append(0)\n\n # reverse them to match up with our coeffs vector\n retval[ii] = list(reversed(coeffs))\n return retval\n\nhalf = int(numcoeffs/2)\nA[0:half,:] = coeffs_for_time(eqs[0:half], numcoeffs, startt)\nA[half:,:] = coeffs_for_time(eqs[0:half], numcoeffs, endt)\n\n# print our A matrix\nprint('A = [')\nmatprint(A)\nprint(']')\n```\n\n A = [\n 1 1 1 1 1 1 1 1 \n 0 1 2 3 4 5 6 7 \n 0 0 2 6 12 20 30 42 \n 0 0 0 6 24 60 120 210 \n 1 6 36 216 1296 7776 46656 279936 \n 0 1 12 108 864 6480 46656 326592 \n 0 0 2 36 432 4320 38880 326592 \n 0 0 0 6 144 2160 25920 272160 \n ]\n\n\n\n```python\n# so now we can create our b vectors\nbx = np.zeros((numcoeffs, 1))\nby = np.zeros((numcoeffs, 1))\n\nbx[0] = start[0]\nbx[half] = end[0]\nby[0] = start[1]\nby[half] = end[1]\n\n# print out our b vectors\nprint('bx = [')\nmatprint(bx)\nprint(']\\n\\nby = [')\nmatprint(by)\nprint(']')\n```\n\n bx = [\n 1 \n 0 \n 0 \n 0 \n 12 \n 0 \n 0 \n 0 \n ]\n \n by = [\n 2 \n 0 \n 0 \n 0 \n 9 \n 0 \n 0 \n 0 \n ]\n\n\n\n```python\n# now we can solve for the coefficients\nbxc = np.linalg.solve(A, bx)\nbyc = np.linalg.solve(A, by)\nprint('bxc = [')\nmatprint(bxc)\nprint(']\\n\\nbyc = [')\nmatprint(byc)\nprint(']')\n```\n\n bxc = [\n 1.96378 \n -4.25779 \n 7.45114 \n -6.50496 \n 2.93216 \n -0.650496 \n 0.068992 \n -0.002816 \n ]\n \n byc = [\n 2.61331 \n -2.7095 \n 4.74163 \n -4.13952 \n 1.86592 \n -0.413952 \n 0.043904 \n -0.001792 \n ]\n\n\n\n```python\nplot_colors = ['r', 'b', 'g', 'y', 'm', 'c'] * 2\nderivative_labels = ['position', 'velocity', 'acceleration', 'jerk', 'snap', 'crack', 'pop']\n\n# define a plotting function\ndef plot_all(tvals, xpoly, ypoly, numderivatives=3): \n plt.figure(figsize=(20, 8*numderivatives))\n \n numplots = 2*numderivatives\n numcols = 2\n label_idx = 0\n \n for plot_idx in range(1, numderivatives*2+1, 2):\n dlabel = derivative_labels[label_idx]\n \n # plot x\n xvals = [xpoly.eval(tval) for tval in tvals]\n plt.subplot(numplots, numcols, plot_idx)\n plt.plot(tvals, xvals, plot_colors[plot_idx-1])\n plt.ylabel(f'X {dlabel}')\n plt.grid(True)\n \n plot_idx += 1\n \n # plot y\n yvals = [ypoly.eval(tval) for tval in tvals]\n plt.subplot(numplots, numcols, plot_idx)\n plt.plot(tvals, yvals, plot_colors[plot_idx-1])\n plt.ylabel(f'Y {dlabel}')\n plt.grid(True)\n \n # compute next derivative\n xpoly = xpoly.diff(t)\n ypoly = ypoly.diff(t)\n \n label_idx += 1\n \n plt.show()\n```\n\n\n```python\n# create the polynomials so we can differentiate them to get our various commanded position, velocity and accelleration curves\nbxpoly = sp.Poly(reversed(bxc.transpose()[0]), t)\nbypoly = sp.Poly(reversed(byc.transpose()[0]), t)\n\n# create our t values over the specified range\ntvals = np.linspace(startt, endt, 100)\n\n# display the position, velocity and acceleration curves\nplot_all(tvals, bxpoly, bypoly, numderivatives=6)\n```\n\n#### Non-Zero Time Derivative Boundary Conditions\nTrajectories can also be generated by assuming non-zero boundary conditions for velocity, and further time derivatives. One use case could be the desire for the trajectory to smoothly transition to/from a steady-state velocity or even start a some velocity and end at another velocity (in which case the acceleration and jerk would continue to be 0 at the boundaries).\n\nBy assigning these non-zero velocity values in our b vectors, we can generate the minimum snap trajectory that transitions to these velocities.\n\nThis is also tackled in the next section for multi-waypoint trajectories where all that is required are the desired waypoints and times of arrival, and then the intermediate velocities and further time derivative values are calculated automatically.\n\n\n```python\n# init our b vectors\nbx = np.zeros((numcoeffs, 1))\nby = np.zeros((numcoeffs, 1))\n\n# assign the start and end positions and velocities - in this case we start with intial velocities of (0,0) and end with (4,3)\n# NOTE: if you wanted to start with non-zero velocities, then you would assign non-zero values to bx[1] and by[1]\nbx[0] = start[0]\nbx[half] = end[0]\nbx[half+1] = 4 # we want our end velocity in the x direction to be 4 m/s\nby[0] = start[1]\nby[half] = end[1]\nby[half+1] = 3 # we want our end velocity in the y direction to be 3 m/s\n\n# now we can solve for the coefficients\nbxc = np.linalg.solve(A, bx)\nbyc = np.linalg.solve(A, by)\n\n# create the polynomials so we can differentiate them to get our various commanded position, velocity and accelleration curves\nbxpoly = sp.Poly(reversed(bxc.transpose()[0]), t)\nbypoly = sp.Poly(reversed(byc.transpose()[0]), t)\n\n# create our t values over the specified range\ntvals = np.linspace(startt, endt, 100)\n\n# display the position, velocity and acceleration curves\nplot_all(tvals, bxpoly, bypoly)\n```\n\n### Multi-point Trajectories\n\nFor trajectories that contain $n$ points, we will need to generate $n-1$ polynomials. This means we will need to find $8(n-1)$ coefficients - where each set of 8 corresponds to one segment. So we must form $8(n-1)$ equations in order to solve for the coefficients, where coefficients for segment $i$ are: \n$c_{i,7}, c_{i,6}, c_{i,5}, c_{i,4}, c_{i,3}, c_{i,2}, c_{i,1}, c_{i,0}$\n\nThe boundary conditions are slightly different in this case, since we don't want the trajectory to stop at intermediary points but smoothly traverse through them - so we want to ensure that the transitions between polynomials is continuous.\n\nFor a set of points, we will also assume we have a desired time when each point should be reached. For a set of n points, we will also have n times, where the following condition is satisifed: \n$t_{i-1} < t_i < t_{i+1}$\n\nFor all segments, we know that the polynomial must pass through the start and end point for that segment. This gives us $2(n-1)$ equations, so for any segment $i$ with point $a_i$: \n$c_{i,7}t_i^7 + c_{i,6}t_i^6 + c_{i,5}t_i^5 + c_{i,4}t_i^4 + c_{i,3}t_i^3 + c_{i,2}t_i^2 + c_{i,1}t_i + c_{i,0} = a_i \\\\\nc_{i,7}t_{i+1}^7 + c_{i,6}t_{i+1}^6 + c_{i,5}t_{i+1}^5 + c_{i,4}t_{i+1}^4 + c_{i,3}t_{i+1}^3 + c_{i,2}t_{i+1}^2 + c_{i,1}t_{i+1} + c_{i,0} = a_{i+1}$\n\nEach segment, except for the last, will have the condition that at it's end time, the velocity and all its further time derivatives, will equal the velocity, and all its further time derivatives of the following segment's start time. If we use velocity, acceleration, jerk, snap, crackle and pop, we will have a further $6(n-2)$ equations: \n$7c_{i,7}t_{i+1}^6 + 6c_{i,6}t_{i+1}^5 + 5c_{i,5}t_{i+1}^4 + 4c_{i,4}t_{i+1}^3 + 3c_{i,3}t_{i+1}^2 + 2c_{i,2}t_{i+1} + c_{i,1} = 7c_{i+1,7}t_{i+1}^6 + 6c_{i+1,6}t_{i+1}^5 + 5c_{i+1,5}t_{i+1}^4 + 4c_{i+1,4}t_{i+1}^3 + 3c_{i+1,3}t_{i+1}^2 + 2c_{i+1,2}t_{i+1} + c_{+1i,1} \\\\\n42c_{i,7}t_{i+1}^5 + 30c_{i,6}t_{i+1}^4 + 20c_{i,5}t_{i+1}^3 + 12c_{i,4}t_{i+1}^2 + 6c_{i,3}t_{i+1} + 2c_{i,2} = 42c_{i+1,7}t_{i+1}^5 + 30c_{i+1,6}t_{i+1}^4 + 20c_{i+1,5}t_{i+1}^3 + 12c_{i+1,4}t_{i+1}^2 + 3c_{i+1,3}t_{i+1} + 2c_{i+1,2} \\\\\n210c_{i,7}t_{i+1}^4 + 120c_{i,6}t_{i+1}^3 + 60c_{i,5}t_{i+1}^2 + 24c_{i,4}t_{i+1} + 6c_{i,3} = 210c_{i+1,7}t_{i+1}^4 + 120c_{i+1,6}t_{i+1}^3 + 60c_{i+1,5}t_{i+1}^2 + 24c_{i+1,4}t_{i+1} + 6c_{i+1,3} \\\\\n840c_{i,7}t_{i+1}^3 + 360c_{i,6}t_{i+1}^2 + 120c_{i,5}t_{i+1} + 24c_{i,4} = 840c_{i+1,7}t_{i+1}^3 + 360c_{i+1,6}t_{i+1}^2 + 120c_{i+1,5}t_{i+1} + 24c_{i+1,4} \\\\\n2520c_{i,7}t_{i+1}^2 + 720c_{i,6}t_{i+1} + 120c_{i,5} = 2520c_{i+1,7}t_{i+1}^2 + 720c_{i+1,6}t_{i+1} + 120c_{i+1,5} \\\\\n5040c_{i,7}t_{i+1} + 720c_{i,6}t_{i+1} = 5040c_{i+1,7}t_{i+1} + 720c_{i+1,6}$\n\nor, by moving all terms to LHS:\n\n$7c_{i,7}t_{i+1}^6 + 6c_{i,6}t_{i+1}^5 + 5c_{i,5}t_{i+1}^4 + 4c_{i,4}t_{i+1}^3 + 3c_{i,3}t_{i+1}^2 + 2c_{i,2}t_{i+1} + c_{i,1} - 7c_{i+1,7}t_{i+1}^6 - 6c_{i+1,6}t_{i+1}^5 - 5c_{i+1,5}t_{i+1}^4 - 4c_{i+1,4}t_{i+1}^3 - 3c_{i+1,3}t_{i+1}^2 - 2c_{i+1,2}t_{i+1} - c_{i+1,1} = 0 \\\\\n42c_{i,7}t_{i+1}^5 + 30c_{i,6}t_{i+1}^4 + 20c_{i,5}t_{i+1}^3 + 12c_{i,4}t_{i+1}^2 + 6c_{i,3}t_{i+1} + 2c_{i,2} - 42c_{i+1,7}t_{i+1}^5 - 30c_{i+1,6}t_{i+1}^4 - 20c_{i+1,5}t_{i+1}^3 - 12c_{i+1,4}t_{i+1}^2 - 3c_{i+1,3}t_{i+1} - 2c_{i+1,2} = 0 \\\\\n210c_{i,7}t_{i+1}^4 + 120c_{i,6}t_{i+1}^3 + 60c_{i,5}t_{i+1}^2 + 24c_{i,4}t_{i+1} + 6c_{i,3} - 210c_{i+1,7}t_{i+1}^4 - 120c_{i+1,6}t_{i+1}^3 - 60c_{i+1,5}t_{i+1}^2 - 24c_{i+1,4}t_{i+1} - 6c_{i+1,3} = 0 \\\\\n840c_{i,7}t_{i+1}^3 + 360c_{i,6}t_{i+1}^2 + 120c_{i,5}t_{i+1} + 24c_{i,4} - 840c_{i+1,7}t_{i+1}^3 - 360c_{i+1,6}t_{i+1}^2 - 120c_{i+1,5}t_{i+1} - 24c_{i+1,4} = 0 \\\\\n2520c_{i,7}t_{i+1}^2 + 720c_{i,6}t_{i+1} + 120c_{i,5} - 2520c_{i+1,7}t_{i+1}^2 - 720c_{i+1,6}t_{i+1} - 120c_{i+1,5} = 0 \\\\\n5040c_{i,7}t_{i+1} + 720c_{i,6}t_{i+1} - 5040c_{i+1,7}t_{i+1} - 720c_{i+1,6} = 0$\n\nWe now only need 6 more equations which we can get from the first and last segments: \n* the first segment will have zero velocity, acceleration and jerk for its start point - this gives us 3 more equations \n $7c_{0,7}t_0^6 + 6c_{0,6}t_0^5 + 5c_{0,5}t_0^4 + 4c_{0,4}t_0^3 + 3c_{0,3}t_0^2 + 2c_{0,2}t_0 + c_{0,1} = 0 \\\\\n 42c_{0,7}t_0^5 + 30c_{0,6}t_0^4 + 20c_{0,5}t_0^3 + 12c_{0,4}t_0^2 + 6c_{0,3}t_0 + 2c_{0,2} = 0 \\\\\n 210c_{0,7}t_0^4 + 120c_{0,6}t_0^3 + 60c_{0,5}t_0^2 + 24c_{0,4}t_0 + 6c_{0,3} = 0$\n* the last segment will have zero velocity, acceleration and jerk for its its end point. This gives us 3 more equation \n $7c_{n-1,7}t_{n-1}^6 + 6c_{n-1,6}t_{n-1}^5 + 5c_{n-1,5}t_{n-1}^4 + 4c_{n-1,4}t_{n-1}^3 + 3c_{n-1,3}t_{n-1}^2 + 2c_{n-1,2}t_{n-1} + c_{n-1,1} = 0 \\\\\n 42c_{n-1,7}t_{n-1}^5 + 30c_{n-1,6}t_{n-1}^4 + 20c_{n-1,5}t_{n-1}^3 + 12c_{n-1,4}t_{n-1}^2 + 6c_{n-1,3}t_{n-1} + 2c_{n-1,2} = 0 \\\\\n 210c_{n-1,7}t_{n-1}^4 + 120c_{n-1,6}t_{n-1}^3 + 60c_{n-1,5}t_{n-1}^2 + 24c_{n-1,4}t_{n-1} + 6c_{n-1,3} = 0$\n\nOnce we have the above equations evaluated at the correct times, we can again use linear algebra to determine the set of polynomial coefficients to give us a minimum snap trajectory over multiple points, where the intermediary points will transition smoothly.\n\n\n```python\n# setup our desired trajectory points and times of arrival\npoints = [(1, 2), (12, 9), (20, 6), (25, 0)]\ntimes = [1, 6, 11, 16]\n\n# initialize the matrix and vectors\nn = numcoeffs * (len(points) - 1)\nA = np.zeros((n, n))\nbx = np.zeros((n, 1))\nby = np.zeros((n, 1))\n\n# fill in 3 equations for first segment - velocity, acceleration and jerk are all equal to 0 at start time\nnextrow = 0\nA[nextrow:nextrow+3, 0:numcoeffs] = coeffs_for_time([vel, acc, jerk], numcoeffs, times[0])\nnextrow += 3\n\n# fill in 3 equations for last segment - velocity, acceleration and jerk are all equal to 0 at end time\nA[nextrow:nextrow+3, n-numcoeffs:n] = coeffs_for_time([vel, acc, jerk], numcoeffs, times[-1])\nnextrow += 3\n\n# for all segments...\nfor idx, startp in enumerate(points[0:-1]):\n endp = points[idx+1]\n startt = times[idx]\n endt = times[idx+1]\n \n # fill in 2 equations for start and end point passing through the poly\n # start point\n col = idx * numcoeffs\n A[nextrow:nextrow+1, col:col+numcoeffs] = coeffs_for_time([pos], numcoeffs, startt)\n bx[nextrow] = startp[0]\n by[nextrow] = startp[1]\n nextrow += 1\n \n # end point\n A[nextrow:nextrow+1, col:col+numcoeffs] = coeffs_for_time([pos], numcoeffs, endt)\n bx[nextrow] = endp[0]\n by[nextrow] = endp[1]\n \n nextrow += 1\n\n# for all segments, except last...\nfor idx in range(len(points) - 2):\n endt = times[idx+1]\n \n # fill in 6 equations for velocity, acceleration, jerk, snap, crackle and pop to ensure they are the same through the transition point\n # evaluate both poly's at the end point\n col = idx * numcoeffs\n A[nextrow:nextrow+6, col:col+numcoeffs] = coeffs_for_time([vel, acc, jerk, snap, crac, pop], numcoeffs, endt)\n col += numcoeffs\n \n # negate endt coefficients since we move everything to the lhs\n A[nextrow:nextrow+6, col:col+numcoeffs] = -coeffs_for_time([vel, acc, jerk, snap, crac, pop], numcoeffs, endt)\n nextrow += 6\n```\n\n\n```python\n# now we can solve for the coefficients\nbxc = np.linalg.solve(A, bx)\nbyc = np.linalg.solve(A, by)\n```\n\n\n```python\n# create our array of position polys for each segment\nxpolys = []\nypolys = []\nfor segment in range(len(points) - 1):\n offset = segment*numcoeffs\n xpolys.append(sp.Poly(reversed(bxc[offset:offset+numcoeffs].transpose()[0]), t))\n ypolys.append(sp.Poly(reversed(byc[offset:offset+numcoeffs].transpose()[0]), t))\n```\n\n\n```python\n# now we can iterate over each of the found polynomials to get our full trajectory\nsamples = 50\ntvals = np.linspace(times[0], times[-1], samples*(len(points) - 1))\nxpos = []\nypos = []\nxvel = []\nyvel = []\nxacc = []\nyacc = []\nfor idx in range(len(points) - 1):\n # pull out the tvals for this segment\n currtvals = tvals[np.argwhere((tvals >= times[idx]) & (tvals <= times[idx+1]))].transpose()[0]\n \n # get the correct poly for this segment\n xpoly = xpolys[idx]\n ypoly = ypolys[idx]\n \n # evaluate at each tval for position, velocity and acceleration\n xpos += [xpoly.eval(tval) for tval in currtvals]\n ypos += [ypoly.eval(tval) for tval in currtvals]\n xvel += [xpoly.diff(t).eval(tval) for tval in currtvals]\n yvel += [ypoly.diff(t).eval(tval) for tval in currtvals]\n xacc += [xpoly.diff(t).diff(t).eval(tval) for tval in currtvals]\n yacc += [ypoly.diff(t).diff(t).eval(tval) for tval in currtvals]\n\n# plot the results\nplt.figure(figsize=(20, 24))\n\nplt.subplot(6, 2, 1)\nplt.plot(tvals, xpos, 'r')\nplt.ylabel('X position (m)')\nplt.grid(True)\n\nplt.subplot(6, 2, 2)\nplt.plot(tvals, ypos, 'b')\nplt.ylabel('Y position (m)')\nplt.grid(True)\n\nplt.subplot(6, 2, 3)\nplt.plot(tvals, xvel, 'g')\nplt.ylabel('X velocity (m/s)')\nplt.grid(True)\n\nplt.subplot(6, 2, 4)\nplt.plot(tvals, yvel, 'y')\nplt.ylabel('Y velocity (m/s)')\nplt.grid(True)\n\nplt.subplot(6, 2, 5)\nplt.plot(tvals, xacc, 'm')\nplt.xlabel('time (s)')\nplt.ylabel('X acceleration (m/s^2)')\nplt.grid(True)\n\nplt.subplot(6, 2, 6)\nplt.plot(tvals, yacc, 'c')\nplt.xlabel('time (s)')\nplt.ylabel('Y acceleration (m/s^2)')\nplt.grid(True)\n\nplt.show()\n```\n\n## Minimum Jerk Trajectory\n\nWe want a trajectory defining position of the form: \n$x(t) = c_5t^5 + c_4t^4 + c_3t^3 + c_2t^2 + c_1t + c_0$\n\nOnce we derive the coefficients, we can then differentiate the resulting polynomial to get the desired velocity and acceleration polynomials, and use these to calculate the desired position, velocity, and accelerations at any time $t$ to give us a minimum jerk trajectory, that we can then feed into our position controller.\n\nThis is the same process as for minimum snap trajectory, so we will define a new plotting function and rely on the class base trajectory generator included elsewhere in this git repository.\n\n\n```python\n# define a plotting function to process results from the class based generator\ndef plot_all_for_class(tvals, xvalues, yvalues):\n numderivatives = xvalues.shape[0]\n plt.figure(figsize=(20, 8*numderivatives))\n \n numplots = 2*numderivatives\n numcols = 2\n label_idx = 0\n \n currderivative = 0\n \n for plot_idx in range(1, numderivatives*2+1, 2):\n dlabel = derivative_labels[label_idx]\n \n # plot x\n xvals = xvalues[currderivative]\n plt.subplot(numplots, numcols, plot_idx)\n plt.plot(tvals, xvals, plot_colors[plot_idx-1])\n plt.ylabel(f'X {dlabel}')\n plt.grid(True)\n \n plot_idx += 1\n \n # plot y\n yvals = yvalues[currderivative]\n plt.subplot(numplots, numcols, plot_idx)\n plt.plot(tvals, yvals, plot_colors[plot_idx-1])\n plt.ylabel(f'Y {dlabel}')\n plt.grid(True)\n \n label_idx += 1\n currderivative += 1\n \n plt.show()\n```\n\n\n```python\n# add in our class based trajectory generator path so we can use that moving forward\nimport sys\nsys.path.insert(0, '../')\n\nfrom trajectory import MininumTrajectory, TrajectoryType\n\nnumderivatives = 4\n\nminjerk = MininumTrajectory(TrajectoryType.JERK)\nminjerk.generate(points, times, numderivatives=numderivatives)\n\ntvals = np.linspace(times[0], times[-1], samples*(len(points) - 1))\n\nxvalues = np.zeros((numderivatives+1, len(tvals)))\nyvalues = np.zeros((numderivatives+1, len(tvals)))\n\nfor tidx, tval in enumerate(tvals):\n out = minjerk.getvalues(tval)\n xout = out[0]\n yout = out[1]\n \n for idx in range(numderivatives+1):\n xvalues[idx][tidx] = xout[idx]\n yvalues[idx][tidx] = yout[idx]\n\nplot_all_for_class(tvals, xvalues, yvalues)\n```\n\n## Minimum Acceleration Trajectory\n\nWe want a trajectory defining position of the form: \n$x(t) = c_3t^3 + c_2t^2 + c_1t + c_0$\n\n\n```python\nnumderivatives = 2\n\nminacc = MininumTrajectory(TrajectoryType.ACCELERATION)\nminacc.generate(points, times, numderivatives=numderivatives)\n\ntvals = np.linspace(times[0], times[-1], samples*(len(points) - 1))\n\nxvalues = np.zeros((numderivatives+1, len(tvals)))\nyvalues = np.zeros((numderivatives+1, len(tvals)))\n\nfor tidx, tval in enumerate(tvals):\n out = minacc.getvalues(tval)\n xout = out[0]\n yout = out[1]\n \n for idx in range(numderivatives+1):\n xvalues[idx][tidx] = xout[idx]\n yvalues[idx][tidx] = yout[idx]\n\nplot_all_for_class(tvals, xvalues, yvalues)\n```\n\n## Minimum Velocity Trajectory\n\nWe want a trajectory defining position of the form: \n$x(t) = c_1t + c_0$\n\n\n```python\nnumderivatives = 1\n\nminvel = MininumTrajectory(TrajectoryType.VELOCITY)\nminvel.generate(points, times, numderivatives=numderivatives)\n\ntvals = np.linspace(times[0], times[-1], samples*(len(points) - 1))\n\nxvalues = np.zeros((numderivatives+1, len(tvals)))\nyvalues = np.zeros((numderivatives+1, len(tvals)))\n\nfor tidx, tval in enumerate(tvals):\n out = minvel.getvalues(tval)\n xout = out[0]\n yout = out[1]\n \n for idx in range(numderivatives+1):\n xvalues[idx][tidx] = xout[idx]\n yvalues[idx][tidx] = yout[idx]\n\nplot_all_for_class(tvals, xvalues, yvalues)\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "ef649eaae62a18327283d7972d28485397abd2d9", "size": 703780, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/trajector-generator.ipynb", "max_stars_repo_name": "tristeng/control", "max_stars_repo_head_hexsha": "dbf99de467e92d998f4fd078057476cdf98537c7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-11-27T10:49:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-04T03:41:19.000Z", "max_issues_repo_path": "notebooks/trajector-generator.ipynb", "max_issues_repo_name": "tristeng/control", "max_issues_repo_head_hexsha": "dbf99de467e92d998f4fd078057476cdf98537c7", "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/trajector-generator.ipynb", "max_forks_repo_name": "tristeng/control", "max_forks_repo_head_hexsha": "dbf99de467e92d998f4fd078057476cdf98537c7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-09-23T16:07:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-08T04:23:46.000Z", "avg_line_length": 694.0631163708, "max_line_length": 175424, "alphanum_fraction": 0.9416408537, "converted": true, "num_tokens": 9908, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966732132748, "lm_q2_score": 0.907312215721497, "lm_q1q2_score": 0.8588587249677342}} {"text": "## Review Calculus using by Python \n\nConsider a sequence of n numbers $x_0, x_1, \\cdots x_{n-1}$. We will start our index at 0, to remain in accordance with Python/Numpy's index system. $x_0$ is the first number in the sequence, $x_1$ is the second number in the sequence, and so forth, so $x_j$ is the general $j+1$ number in the sequence. We will utilize this $j$ index in our summation notation. Suppose we were to calculate the sum of all $n$ of these numbers in the sequence. We write that this sum is equivalent to \n\n\n\nLet's parse this equation. $\\Sigma$ is the summation sign, indicating that we are summing a sequence. $j$ is the index of summation that is being iterated over; $j$ is being used to subscript $x$. Then, we start our summation at 0 because the lower bound on our sum is set as $j=0$. The upper bound for our sum, or our stopping point is written as $n-1$, which is equivalent to writing $j=n-1$ on top of the $\\Sigma$ symbol. Then, $x_j$ indicates the quantitiy that we are summing. One way to think about this is in terms of a for-loop. This summation concept is equivalent to a for loop for all integers in the range from the lower bound to the upper bound, indexed into the sequence $x$. Then, the code for our previous sum is:\n\n\n```python\n\n```\n\nThen, you can run through a few more examples of summation notation.\n\nExample1:\n\n\n\n\n```python\n\n```\n\nExample2:\n\n\n\n\n```python\n\n```\n\nExample3:\n\n\n\n\n```python\n\n```\n\nThen, we can also sum over several different sequences. Consider the sequences A and B, where A consists of m values $a_0, a_1, \\cdots, a_{m-1}$ and B contains n values $b_0, b_1, \\cdots b_{n-1}$. Then, we can calculate the sum of the product of each value in A with each value in B (a sum over $m\\times n$ products). Because the $i$ index only appears in association with A, and the $j$ index with B, we can group these summations. \n\n\n\n\n```python\nimport numpy as np\n```\n\n\n```python\nA = np.random.rand(5)\n```\n\n\n```python\nB = np.random.rand(7)\n```\n\n\n```python\n\n```\n\nNote that the following does not hold \n\n\n\nbecause this effectively treats the index $i$ in the first term independently from the $i$ in the second term of the product. Notice that in the right side of the equation, we could have interchanged the index $i$ in the second summation with $j$, without changing any of the mathematics. The sum on the left represents the summation of $m$ terms of $a_{i}^2$, whereas the sum on the right represents the summation of $m \\times m$ terms - products between all possible pairs of A's terms.\n\n\n```python\nimport numpy as np\n```\n\n\n```python\nA = np.random.rand(5)\n```\n\n\n```python\n\n```\n\nNote that typically when someone writes $\\sum_{i} x_i$, this is just the sum of all values in the sequence X, and is the same as writing $\\sum_{i=0}^{n-1} x_i$, where you'll usually know the value of n so you can still compute the sum.\n\n\n## Matrices \n\n\nThen suppose we have a m by n matrix that contains all products of the values in both sequence A and sequence B such that the matrix value of $M$ at index $(i,j)$ is $a_i \\cdot b_j$.\n\n\n\nYou can form this matrix in numpy via an \"outer product\": \n\n\n```python\nimport numpy as np\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\nYou can use this matrix to visualize several possible uses of summations. For example, suppose $m=n$. Then, if we express the sequences A and B as column vectors, the dot product of the two vectors would be the sum of the diagonal of M, or $\\sum_{k=0}^{n-1} a_k \\cdot b_k$. Furthermore, we can take the sum of a row using the sum $\\sum_{i=0}^{n-1} a_k \\cdot b_i$ for the $k^{th}$ row of the matrix, and similarly take the sum of a column with $\\sum_{i=0}^{n-1} a_i \\cdot b_k$ for the $k^{th}$ column of the matrix.\n\n\n```python\nk = 2\n```\n\n\n```python\n# sum over the kth column:\n```\n\n\n```python\n# sum over the kth row:\n```\n\n## Kronecker Delta\n\nTo make notation for working with summations (particularly in considering the matrix format) even simpler, we can use the Kronecker delta function, named after Prussian mathematician Leonard Kronecker. We use $\\delta_{i,j}$ to denote the Kronecker delta function, defined as: \\begin{equation} \\begin{cases} \\delta{i, j}= 0 & \\text{if } i \\neq j\\\n\\delta{i,j}=1 & \\text{if } i=j\n\\end{cases} \\end{equation}\n\nSee that a Kronecker-delta can \"collapse\" a sum. Let $j$ be an integer between 0 and $n-1$: \n\n\n\nSee also that the identity matrix, $I$, can be written as $I_{i,j}=\\delta_{i,j}$.\n\n\n\nAs an exercise, write a python function that behaves as a kronecker delta, and include it in a for-loop that is computing a sum. Verify that it does indeed collapse the sum.\n\n## Partial Derivatives\n\nPartial derivatives are used in multivariable functions, in which we essentially derive with respect to one of these variables and treat the remaining variables as constants. For example: \n\n$$ f(x,y) = 6 x^2 y^3 $$ $$ \\frac{\\partial}{\\partial x} f(x,y) = 12x y^3 $$ $$ \\frac{\\partial}{\\partial y} f(x,y) = 18 x^2 y^2 $$\n\nSo, what if we want to take a partial derivative of a sum?\n\nSuppose that we have two vectors containing variables:\n\n\n\n\n\nThen, in our previous section we saw that $\\vec{x} \\cdot \\vec{y} = \\sum_{i=0}^{n-1} x_i \\cdot y_i$. What happens when we take the partial derivative of this sum with respect to the variable $x_{j}$? Let $f = \\vec{x} \\cdot \\vec{y}$, then \n\n\n\nIt is critical to see that, because $x_i$ and $x_j$ are distinct variables (unless $i = j$), \\begin{equation} \\begin{cases} \\frac{\\partial x_i}{\\partial x_j} = 0 & \\text{if } i \\neq j\\\n\\frac{\\partial x_i}{\\partial x_j} = 1 & \\text{if } i=j\n\\end{cases} \\end{equation} and thus $\\frac{\\partial x_i}{\\partial x_j} = \\delta_{i,j}$.\n\nThus we can simplify our sum by collapsing it via the kronecker-delta: \n\n\n\nDefining $\\frac{\\partial f}{\\partial \\vec{x}} = [\\frac{\\partial f}{\\partial x_0}, \\cdots , \\frac{\\partial f}{\\partial x_j}, \\cdots, \\frac{\\partial f}{\\partial x_{n-1}}]$, we can see from our above result that \n\n\n\nTake a little bit of time to think through the above expression, and make sure you understand why it is true, writing out matrices to help your understanding. This is just one example of how we can apply some of the calculus we already know to vectors, leading to vector calculus, a pillar for linear algebra! This is especially important for deriving expressions used in back-propagation in machine learning.\n\nThe end of document\n", "meta": {"hexsha": "cbbbc7299cec9e3770640e58361d751d4d0ad25f", "size": 15992, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "aip2-dgs/other/reference.ipynb", "max_stars_repo_name": "nurseiit/comm-unist", "max_stars_repo_head_hexsha": "e7a122c910bf12eddf5c0ffc2c666995b4989408", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2019-07-03T00:57:01.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-11T23:06:11.000Z", "max_issues_repo_path": "aip2-dgs/other/reference.ipynb", "max_issues_repo_name": "nurseiit/comm-unist", "max_issues_repo_head_hexsha": "e7a122c910bf12eddf5c0ffc2c666995b4989408", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-10-19T17:42:42.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-19T17:42:42.000Z", "max_forks_repo_path": "aip2-dgs/other/reference.ipynb", "max_forks_repo_name": "nurseiit/comm-unist", "max_forks_repo_head_hexsha": "e7a122c910bf12eddf5c0ffc2c666995b4989408", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-11-05T04:14:08.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-05T04:14:08.000Z", "avg_line_length": 32.0480961924, "max_line_length": 737, "alphanum_fraction": 0.6061155578, "converted": true, "num_tokens": 1777, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850075259039, "lm_q2_score": 0.9173026590205305, "lm_q1q2_score": 0.8588567270045692}} {"text": "# Complex numbers and operation on complex numbers\n\n\nFrom _A.G. Sveshnokov, A.N. Tikhonov (1982). The theory of functions of a complex variable. Section 1.1_.\n\n## The concept of a complex number\n\nA complex number $z$ is characterized by a pair of real numbers $(a, b)$. The first number\n$a$ of the pair $(a, b)$ is called the _real part_ of the complex number $z$ and is denoted\nby $a =\\mathrm{Re}\\, z$; the second number $b$ of the pair $(a, b)$ is called the\n_imaginary part_ of the complex number $z$ and is symbolized by $b=\\mathrm{Im}\\, z$.\n\nTwo complex numbers $z_1 = (a_1, b_1)$ and $z_2 = (a_2, b_2)$ are equal only when both the real\nand imaginary parts are equal, that is, $z_1 = z_2$ only when $a_1 = a_2$ and $b_1 = b_2$.\n\n## Operations on complex numbers\n\nLet us now define algebraic operations involving complex numbers.\n\nThe sum of two complex numbers $z_1 = (a_1, b_1)$ and $z_2 = (a_2, b_2)$ is a complex number\n$z = (a, b)$, where $a = a_1 + a_2$, $b = b_1 + b_2$. The commutative and associative laws\nfor addition, $z_1 + z_2 = z_2 + z_1$ and $z_1 + (z_2 + z_3) = (z_1 + z_2) + z_3$, hold true.\nAs in the domain of real numbers, zero is a complex number $0$ such that the sum of it and any\ncomplex number $z$ is equal to $z$, that is, $z + 0 = z$. There is a unique complex number\n$0 = (0, 0)$ that possesses this property.\n\nThe _product_ of the complex numbers $z_1 = (a_1, b_1)$ and $z_2 = (a_2, b_2)$ is a complex\nnumber $z = (a, b)$ such that $a = a_1 a_2 - b_1 b_2$, $b = a_1 b_2 + a_2 b_1$. In this\ndefinition of a product, we find that the commutative $[z_1 z_2 = z_2 z_1]$, associative\n$[z_1 (z_2\\cdot z_3) = (z_1\\cdot z_2) z_3]$ and distributive $[(z_1 + z_2) z_3 = z_1 z_3 + z_2 z_3]$\nlaws hold.\n\nLet us include the real numbers in the set of complex numbers and regard the real number $a$ as the\ncomplex number $a = (a, 0)$. Then, as follows from the definition of the operations of addition\nand miltiplication, the familiar rules involving real numbers hold true for complex numbers as well.\nThus, the set of complex numbers is regarded as an extension of the set of real numbers. Note that\nmultiplication by a real unit $(1, 0)$ does not change a complex number: $z\\cdot 1 = z$.\n\nA complex number of the form of the form $z = (0, b)$ is called a _pure imaginary_ number (or just\nimaginary number) and is symbolized as $z = ib$. The pure imaginary number $(0, b) = ib$ may be\nregarded as the product of the imaginary unit $(0, 1)$ and real number $(b, 0)$. The imaginary\nunit is commonly denoted by the symbol $(0, 1) = i$. By virtue of the definition of a product\nof complex numbers, the following relation holds true: $i\\cdot i = i^2 = -1$. It enables one\nto attribute a direct algebraig meaning to the _real-imaginary form_ of a complex number:\n\n$$ z = (a, b) = a + ib\\, ,$$\n\nand perform operations of addition and multiplication of complex numbers in accordance with the\nusual rules of the algebra of polynomials.\n\nThe complex number $\\bar{z} = a - ib$ is said to be the complex _conjugate_ of $z = a + ib$.\n\nThe operation of substraction of complex numbers is defined as the inverse operation of addition.\nA complex number $z = a + ib$ is termed the _difference_ between the complex numbers $z_1 = a_1 + ib_1$\nand $z_2 = a_2 + ib_2$ if $a = a_1 - a_2$, $b = b_1 - b_2$.\n\nThe operation of dividing complex numbers is defined as the inverse operation of multiplication.\nA complex number $z = a + ib$ is called the quotient of the complex numbers $z_1 = a_1 + ib_1$ and\n$z_2 = a_2 + ib_2 \\neq = 0$ if $z_1 = z\\cdot z_2$, whence it follows that the real part $a$ and the\nimaginary part $b$ of the quotient $z$ are found from the linear system of algebraic equations\n\n\\begin{align}\n &a_2 a - b_2 b = a_1\\\\\n &b_2 a + a_2 b = b_1\n\\end{align}\n\nwith the determinant $a_2^2 + b_2^2$ different from zero. Solving this system, we get\n\n$$z = \\frac{z_1}{z_2} = \\frac{a_1 a_2 + b_1 b_2}{a_2^2 + b_2^2} + i \\frac{b_1 a_2 - a_1 b_2}{a_2^2 + b_2^2}\\, .$$\n\n## Operations on complex numbers using SymPy\n\nLet us repeat the operations described above using SymPy.\n\n\n```python\nfrom sympy import *\ninit_printing()\n```\n\n\n```python\na, a1, a2, a3 = symbols(\"a a1 a2 a3\", real=True)\nb, b1, b2, b3 = symbols(\"b b1 b2 b3\", real=True)\n```\n\nIn SymPy the imaginary unit is represented by ``I``.\n\n\n```python\nI**2\n```\n\n\n```python\nz1 = a1 + b1*I\nz2 = a2 + b2*I\nz3 = a3 + b3*I\ndisplay(z1)\ndisplay(z2)\ndisplay(z3)\n```\n\n### Real and imaginary parts\n\n\n```python\n# Real part\ndisplay(re(z1))\ndisplay(re(z2))\n```\n\n\n```python\n# Imaginary part\ndisplay(im(z1))\ndisplay(im(z2))\n```\n\n### Addition\n\n\n```python\ndisplay(z1 + z2)\ndisplay(re(z1 + z2))\ndisplay(im(z1 + z2))\n```\n\nAddition is commutative\n\n\n```python\ndisplay(z1 + z2)\ndisplay(z2 + z1)\n```\n\nAddition is also associative\n\n\n```python\ndisplay(z1 + (z2 + z3))\ndisplay((z1 + z2) + z3)\n```\n\n### Multiplication\n\n\n```python\ndisplay(z1 * z2)\ndisplay(re(z1 * z2))\ndisplay(im(z1 * z2))\n```\n\nMultiplication is commutative\n\n\n```python\ndisplay(z1 * z2)\ndisplay(z2 * z1)\n```\n\nMultiplication is associative\n\n\n```python\ndisplay(expand(z1 * (z2 * z3)))\ndisplay(expand((z1 * z2) * z3))\n```\n\nMultiplication is distributive over addition\n\n\n```python\ndisplay(expand((z1 + z2) * z3))\ndisplay(expand(z1 * z3 + z2 * z3))\n```\n\n### Complex conjugate\n\n\n```python\ndisplay(z1)\ndisplay(conjugate(z1))\n```\n\n### Difference\n\n\n```python\ndisplay(z1 - z2)\ndisplay(re(z1 - z2))\ndisplay(im(z1 - z2))\n```\n\n### Division\n\n\n```python\ndisplay(z1 / z2)\ndisplay(factor(re(z1 / z2)))\ndisplay(factor(im(z1 / z2)))\n```\n\n## The geometric interpretation of complex numbers\n\nThe study of complex numbers is greatly facilitated by interpretating them geometrically.\nInsofar as a complex number is defined as a pair of real numbers, it is natural to depict\nthe complex number $z = a + ib$ as a point in the $x$, $y$-plane with Cartesian coordinates\n$x = a$ and $y = b$. The number $z=0$ corresponds to the origin of the plane. We shall henceforward\ncall this the _complex plane_; the axis of the abscissas is the _real_ axis, the axis of\nthe ordinates is the _imaginary_ axis of the complex plane. We have thus established a\nreciprocal one-to-one correspondence between the set of all complex numbers and the set of\npoints the complex plane, and also between the set of al complex numbers $z = a + ib$ and the\nset of free vectors, the projections $x$ and $y$ of which on the axis of abscissas and the\naxis of ordinates are, respectively, equal to $a$ and $b$.\n\nThere is another extremely important form of representing complex numbers. It is possible to\ndefine the position of a point in the plane by means of polar coordinates $(\\rho, \\varphi)$, where\n$\\rho$ is the distance of the point from the origin, and $\\varphi$ is the angle between the\nradius vector with the positive direction of the axis of abscissas. The positive direction of the\nvariation of the angle $\\varphi$ is counterclockwise $(-\\infty < \\varphi < \\infty)$. Taking\nadvantage of the relationship between Cartesian and polar coordinates\n\n\\begin{align}\n &x = \\rho \\cos\\varphi\\\\\n &y = \\rho \\sin\\varphi\\, ,\n\\end{align}\n\nwe get the so-called _trigonometric form_ (or polar form) of a complex number:\n\n$$z = \\rho(\\cos\\varphi + i\\sin\\varphi)\\, .$$\n\n\n```python\nAbs(z1)\n```\n\n\n```python\n\n```\n\n\n```python\nfrom IPython.core.display import HTML\ndef css_styling():\n styles = open('./styles/custom_barba.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```python\n\n```\n", "meta": {"hexsha": "6dca2882389e59d88d0dedc7e6bd31f55b6bb8d4", "size": 74951, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/complex numbers.ipynb", "max_stars_repo_name": "nicoguaro/AdvancedMath", "max_stars_repo_head_hexsha": "2749068de442f67b89d3f57827367193ce61a09c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 26, "max_stars_repo_stars_event_min_datetime": "2017-06-29T17:45:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-06T20:14:29.000Z", "max_issues_repo_path": "notebooks/complex numbers.ipynb", "max_issues_repo_name": "nicoguaro/AdvancedMath", "max_issues_repo_head_hexsha": "2749068de442f67b89d3f57827367193ce61a09c", "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/complex numbers.ipynb", "max_forks_repo_name": "nicoguaro/AdvancedMath", "max_forks_repo_head_hexsha": "2749068de442f67b89d3f57827367193ce61a09c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 13, "max_forks_repo_forks_event_min_datetime": "2019-04-22T08:08:56.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-27T08:15:53.000Z", "avg_line_length": 73.5534838077, "max_line_length": 3740, "alphanum_fraction": 0.7984016224, "converted": true, "num_tokens": 2878, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362849986365571, "lm_q2_score": 0.9173026550642018, "lm_q1q2_score": 0.8588567151460964}} {"text": "# Exponential-family belief updating\n\n## Reduction of Bayes' theorem to mean updating\n\n### Mean updating\n\nThe mean $\\bar{x}_n$ of a set $\\{x_1, x_2, \\ldots, x_n\\}$ is\n\n$$\n\\bar{x}_n := \\frac{1}{n} \\sum_{i=1}^{n} x_i\n$$\n\nFor example, $x_i$ could be observations made sequentially. If we now add a new element $x_{n+1}$ to our set, the new mean $\\bar{x}_{n+1}$ is\n\n$$\n\\bar{x}_{n+1} = \\bar{x}_n + \\frac{1}{n+1} \\left( x_{n+1} - \\bar{x}_n \\right)\n$$\n\n*Proof:*\n\n$$\n\\begin{align}\n\\bar{x}_{n+1} &= \\frac{1}{n+1} \\sum_{i=1}^{n+1} x_i \\\\\n&= \\frac{1}{n+1} \\left( x_{n+1} + n \\cdot \\frac{1}{n} \\sum_{i=1}^{n} x_i \\right) \\\\\n&= \\frac{1}{n+1} \\left( x_{n+1} + n \\bar{x}_n \\right) \\\\\n&= \\frac{1}{n+1} \\left( x_{n+1} - \\bar{x}_n + (n+1) \\bar{x}_n \\right) \\\\\n&= \\bar{x}_n + \\frac{1}{n+1} \\left( x_{n+1} - \\bar{x}_n \\right)\n\\end{align}\n$$\n\n### Bayes' theorem\n\nBayes' theorem is an immediate consequence of the product rule of probability and states that the posterior is the likelihood times the prior divided by the model evidence.\n\n$$\np\\left( \\vartheta \\middle| x \\right) = \\frac{p\\left( x \\middle| \\vartheta \\right) p\\left( \\vartheta \\right)}{p\\left( x \\right)}\n= \\frac{p\\left( x \\middle| \\vartheta \\right) p\\left( \\vartheta \\right)}{\\int_\\Omega p\\left( x \\middle| \\vartheta' \\right) p\\left( \\vartheta' \\right) \\mathrm{d}\\vartheta'},\n$$\n\nwhere $\\Omega$ is the support of $p(\\vartheta)$.\n\n### Exponential families of probability distributions\n\nA family of probability distributions is an *exponential family* if and only if it can be written in the following form\n\n$$\np\\left( x \\middle| \\vartheta \\right) = f_x(\\vartheta) := h(x) \\exp\\left( \\eta(\\vartheta) \\cdot T(x) - B(\\vartheta) \\right),\n$$\n\nwhere $x$ is a vector-valued observation, $\\vartheta$ is a parameter vector, $h(x)$ is a normalization constant, $\\eta(\\vartheta)$ is the so-called 'natural' parameter vector, $T(x)$ is the sufficient statistic vector, and $B(\\vartheta)$ is a scalar function.\n\n### Bayes' theorem applied to exponential families\n\nWhen the likelihood belongs to an exponential family, applying Bayes' theorem becomes extremely simple with an appropriate prior. We choose a prior with a natural interpretation, implying that we have made $\\nu \\in \\mathbb{R}$ observations with sufficient statistics $\\xi$:\n\n$$\np\\left( \\vartheta \\middle| \\xi, \\nu \\right) = g_{\\xi, \\nu}(\\vartheta) := z\\left( \\xi, \\nu \\right) \\exp\\left( \\nu\\left( \\eta \\left( \\vartheta \\right) \\cdot \\xi - B(\\vartheta) \\right) \\right),\n$$\n\nwhere $z(\\xi, \\nu)$ is a normalization constant:\n\n$$\nz(\\xi, \\nu) := \\left( \\int_\\Omega \\exp\\left( \\nu\\left( \\eta \\left( \\vartheta \\right) \\cdot \\xi - B(\\vartheta) \\right) \\right) \\mathrm{d}\\vartheta \\right)^{-1}.\n$$\n\nThe *hyperpriors* $\\xi$ and $\\nu$ parameterize the prior $g_{\\xi, \\nu}$ of $\\vartheta$. This prior is *conjugate* to the likelihood; that is, the posterior has the same form $g_{\\xi, \\nu}$. When passing from the prior to the posterior after a new observation $x$, all that needs to be updated are the hyperpriors $\\xi$ and $\\nu$:\n\n$$\n\\begin{align}\n\\nu &\\leftarrow \\nu+1 \\\\\n\\xi &\\leftarrow \\xi + \\frac{1}{\\nu+1} \\left( T(x) - \\xi \\right)\n\\end{align}\n$$\n\n*Proof:*\n\n$$\n\\begin{align}\np\\left( \\vartheta \\middle| x, \\xi, \\nu \\right) &\\propto p\\left( x \\middle| \\vartheta \\right) p\\left( \\vartheta \\middle| \\xi, \\nu \\right) \\\\\\\\\n&= f_x(\\vartheta)g_{\\xi, \\nu}(\\vartheta) \\\\\\\\\n&= h(x) \\exp\\left( \\eta(\\vartheta) \\cdot T(x) - B(\\vartheta) \\right) z\\left( \\xi, \\nu \\right) \\exp\\left( \\nu\\left( \\eta \\left( \\vartheta \\right) \\cdot \\xi - B(\\vartheta) \\right) \\right) \\\\\\\\\n&\\propto \\exp\\left( \\eta(\\vartheta) \\cdot \\left( T(x) + \\nu \\xi \\right) - (\\nu+1) B(\\vartheta) \\right) \\\\\\\\\n&= \\exp\\left( (\\nu+1) \\left( \\eta(\\vartheta) \\cdot \\frac{1}{\\nu+1} \\left( T(x) + \\nu \\xi \\right) - B(\\vartheta) \\right)\\right) \\\\\\\\\n&= \\exp\\left( (\\nu+1) \\left( \\eta(\\vartheta) \\cdot \\left( \\xi + \\frac{1}{\\nu+1} \\left( T(x) - \\xi \\right) \\right) - B(\\vartheta) \\right)\\right) \\\\\\\\\\\\\n\\Longrightarrow p\\left( \\vartheta \\middle| x, \\xi, \\nu \\right) &= g_{\\xi', \\nu'}(\\vartheta) \\qquad \\text{with} \\qquad \\nu' = \\nu+1 \\qquad \\text{and} \\qquad \\xi' = \\xi + \\frac{1}{\\nu+1} \\left( T(x) - \\xi \\right)\n\\end{align}\n$$\n\nSince the prior can \n\n## Gaussian with unknown mean and known precision\n\n### Likelihood\n\nThe likelihood is\n\n$$\n\\begin{aligned}\np\\left( x \\middle| \\vartheta \\right) &= h\\left( x \\right) \\exp\\left( \\eta\\left( \\vartheta \\right) \\cdot T(x) - B(\\vartheta) \\right) \\\\\n&= \\sqrt{\\frac{\\tau}{2\\pi}} \\exp \\left( -\\frac{\\tau}{2}\\left( x -\\mu \\right)^2 \\right) \\\\\n&= \\mathcal{N} \\left( x ; \\mu, \\tau^{-1} \\right)\n\\end{aligned}\n$$\n\nwith\n\n$$\n\\begin{aligned}\nh( x ) &: = \\sqrt{\\frac{\\tau}{2\\pi}} \\exp\\left(-\\frac{\\tau}{2} x^2\\right),\\\\\n\\vartheta &:= \\mu,\\\\\n\\eta (\\vartheta) &: = \\tau\\mu,\\\\\nT(x) &: = x,\\\\\nB(\\vartheta) &:= \\frac{\\tau}{2}\\mu^2.\n\\end{aligned}\n$$\n\n### Prior\n\nThe prior is\n\n\n$$\np\\left( \\vartheta \\middle| \\xi, \\nu \\right) = z\\left( \\xi, \\nu\n\\right) \\exp\\left( \\nu\\left( \\eta \\left( \\vartheta \\right) \\cdot \\xi -\nB(\\vartheta) \\right) \\right),\n$$\n\nwith normalization factor\n\n$$\nz(\\xi, \\nu) := \\left( \\int_\\Omega \\exp\\left( \\nu\\left( \\eta \\left( \\vartheta \\right) \\cdot \\xi -\nB(\\vartheta) \\right) \\right) \\mathrm{d}\\vartheta \\right)^{-1}.\n$$\n\nWith the definitions above, this means\n\n$$\n\\begin{aligned}\nz(\\xi, \\nu)^{-1} &= \\int_{-\\infty}^\\infty \\exp \\left( \\nu \\left( \\tau \\mu \\xi - \\frac{1}{2}\\tau \\mu^2 \\right) \\right) \\mathrm{d}\\mu \\\\\n&= \\int_{-\\infty}^\\infty \\exp \\left( -\\frac{\\nu\\tau}{2} \\left( \\mu^2 - 2 \\mu \\xi \\right) \\right) \\mathrm{d}\\mu \\\\\n&= \\int_{-\\infty}^\\infty \\exp \\left( -\\frac{\\nu\\tau}{2} \\left( \\left( \\mu - \\xi \\right)^2 - \\xi^2 \\right) \\right) \\mathrm{d}\\mu \\\\\n&= \\exp \\left( \\frac{\\nu\\tau}{2} \\xi^2 \\right) \\int_{-\\infty}^\\infty \\exp \\left( -\\frac{\\nu\\tau}{2} \\left( \\mu - \\xi \\right)^2 \\right) \\mathrm{d}\\mu \\\\\n&= \\sqrt{\\frac{2\\pi}{\\nu \\tau}} \\exp \\left( \\frac{\\nu\\tau}{2} \\xi^2 \\right)\n\\end{aligned}\n$$\n\nand\n\n$$\n\\begin{aligned}\np\\left( \\vartheta \\middle| \\xi, \\nu \\right) &= z(\\xi, \\nu) \\exp \\left( \\frac{\\nu\\tau}{2} \\xi^2 \\right) \\exp \\left( -\\frac{\\nu\\tau}{2} \\left( \\mu - \\xi \\right)^2 \\right) \\\\\n&= \\sqrt{\\frac{\\nu \\tau}{2\\pi}} \\exp \\left( -\\frac{\\nu\\tau}{2} \\left( \\mu - \\xi \\right)^2 \\right) \\\\\n&= \\mathcal{N} \\left( \\mu ; \\xi, (\\nu\\tau)^{-1} \\right)\n\\end{aligned}\n$$\n\n### Prior predictive distribution\n\nMarginalizing the joint over the parameter $\\vartheta$ gives us the prior predictive distribution\n\n$$\n\\begin{aligned}\np\\left( x | \\xi, \\nu \\right) &= \\int_\\Omega p(x | \\vartheta) p(\\vartheta | \\xi, \\nu) \\mathrm{d}\\vartheta \\\\\n&= \\int_{-\\infty}^\\infty \\mathcal{N} \\left( x ; \\mu, \\tau^{-1} \\right) \\mathcal{N} \\left( \\mu ; \\xi, (\\nu\\tau)^{-1} \\right) \\mathrm{d}\\mu \\\\\n&= \\mathcal{N} \\left( x ; \\xi, \\tau^{-1} + (\\nu\\tau)^{-1} \\right) \\\\\n&= \\mathcal{N} \\left( x ; \\xi, \\left( \\frac{\\nu\\tau}{\\nu+1} \\right)^{-1} \\right).\n\\end{aligned}\n$$\n\nThe third equality is a consequence of the fact that compounding two Gaussians gives a Gaussian whose variance is the sum of those of the compounded Gaussians. A more tedious derivation gives the same result:\n\n$$\n\\begin{aligned}\np\\left( x | \\xi, \\nu \\right) &= \\int_\\Omega p(x | \\vartheta) p(\\vartheta | \\xi, \\nu) \\mathrm{d}\\vartheta \\\\\n&= \\int_{-\\infty}^\\infty \\mathcal{N} \\left( x ; \\mu, \\tau^{-1} \\right) \\mathcal{N} \\left( \\mu ; \\xi, (\\nu\\tau)^{-1} \\right) \\mathrm{d}\\mu \\\\\n&= \\int_{-\\infty}^\\infty \\sqrt{\\frac{\\tau}{2\\pi}} \\exp \\left( -\\frac{\\tau}{2}\\left( x -\\mu \\right)^2 \\right) \\sqrt{\\frac{\\nu \\tau}{2\\pi}} \\exp \\left( -\\frac{\\nu\\tau}{2} \\left( \\mu - \\xi \\right)^2 \\right) \\mathrm{d}\\mu \\\\\n&= \\frac{\\sqrt{\\nu} \\tau}{2\\pi} \\int_{-\\infty}^\\infty \\exp \\left( -\\frac{\\tau}{2}\\left( x -\\mu \\right)^2 \\right) \\exp \\left( -\\frac{\\nu\\tau}{2} \\left( \\mu - \\xi \\right)^2 \\right) \\mathrm{d}\\mu \\\\\n&= \\frac{\\sqrt{\\nu} \\tau}{2\\pi} \\int_{-\\infty}^\\infty \\exp \\left( -\\frac{\\tau}{2}\\left( (\\nu+1)\\mu^2 -2(x+\\nu\\xi)\\mu + x^2 +\\nu\\xi^2 \\right) \\right) \\mathrm{d}\\mu \\\\\n&= \\frac{\\sqrt{\\nu} \\tau}{2\\pi} \\exp \\left( -\\frac{\\tau}{2}\\left( x^2 +\\nu\\xi^2 \\right) \\right) \\int_{-\\infty}^\\infty \\exp \\left( -\\frac{(\\nu+1) \\tau}{2}\\left( \\left( \\mu - \\frac{x+\\nu\\xi}{\\nu+1} \\right)^2 - \\left( \\frac{x+\\nu\\xi}{\\nu+1} \\right)^2 \\right) \\right) \\mathrm{d}\\mu \\\\\n&= \\frac{\\sqrt{\\nu} \\tau}{2\\pi} \\exp \\left( -\\frac{\\tau}{2}\\left( x^2 +\\nu\\xi^2 - \\frac{(x+\\nu\\xi)^2}{\\nu+1} \\right) \\right) \\int_{-\\infty}^\\infty \\exp \\left( -\\frac{(\\nu+1) \\tau}{2}\\left( \\left( \\mu - \\frac{x+\\nu\\xi}{\\nu+1} \\right)^2 \\right) \\right) \\mathrm{d}\\mu \\\\\n&= \\frac{\\sqrt{\\nu} \\tau}{2\\pi} \\exp \\left( -\\frac{\\tau}{2}\\left( x^2 +\\nu\\xi^2 - \\frac{(x+\\nu\\xi)^2}{\\nu+1} \\right) \\right) \\sqrt{\\frac{2\\pi}{(\\nu+1)\\tau}} \\\\\n&= \\sqrt{\\frac{\\nu\\tau}{2\\pi(\\nu+1)}} \\exp \\left( -\\frac{\\tau}{2}\\left( x^2 +\\nu\\xi^2 - \\frac{(x+\\nu\\xi)^2}{\\nu+1} \\right) \\right) \\\\\n&= \\sqrt{\\frac{\\nu\\tau}{2\\pi(\\nu+1)}} \\exp \\left( -\\frac{\\tau}{2}\\left( x^2 - \\frac{x^2}{\\nu+1} - \\frac{2\\nu\\xi x}{\\nu+1}- \\frac{\\nu^2\\xi^2}{\\nu+1} +\\nu\\xi^2 \\right) \\right) \\\\\n&= \\sqrt{\\frac{\\nu\\tau}{2\\pi(\\nu+1)}} \\exp \\left( -\\frac{\\tau}{2}\\left( x^2 \\left( 1 - \\frac{1}{\\nu+1} \\right) - 2\\frac{\\nu}{\\nu+1}\\xi x - \\frac{\\nu}{\\nu+1} \\left( +\\nu\\xi^2 + (\\nu+1)\\xi^2 \\right) \\right) \\right) \\\\\n&= \\sqrt{\\frac{\\nu\\tau}{2\\pi(\\nu+1)}} \\exp \\left( -\\frac{\\nu\\tau}{2(\\nu+1)}(x - \\xi)^2 \\right) \\\\\n&= \\mathcal{N} \\left( x ; \\xi, \\left( \\frac{\\nu\\tau}{\\nu+1} \\right)^{-1} \\right).\n\\end{aligned}\n$$\n\n## Gaussian with mean and precision unknown\n\n### Likelihood\n\nWhether precision is known or unknown does not affect the likelihood. It still is\n\n$$\n\\begin{aligned}\np\\left( x \\middle| \\vartheta \\right) &= h\\left( x \\right) \\exp\\left( \\eta\\left( \\vartheta \\right) \\cdot T(x) - B(\\vartheta) \\right) \\\\\n&= \\sqrt{\\frac{\\tau}{2\\pi}} \\exp \\left( -\\frac{\\tau}{2}\\left( x -\\mu \\right)^2 \\right) \\\\\n&= \\mathcal{N} \\left( x ; \\mu, \\tau^{-1} \\right),\n\\end{aligned}\n$$\n\nbut this time with\n\n$$\n\\begin{aligned}\nh( x ) &: = \\frac{1}{\\sqrt{2\\pi}},\\\\\n\\vartheta &:= \\left( \\mu, \\tau \\right)^\\intercal \\\\\n\\eta (\\vartheta) &: = \\left( \\tau\\mu, -\\tau/2 \\right)^\\intercal \\\\\nT(x) &: = \\left( x, x^2 \\right)^\\intercal \\\\\nB(\\vartheta) &:= \\frac{1}{2} \\left( \\tau \\mu^2 - \\ln \\tau \\right).\n\\end{aligned}\n$$\n\n### Prior\n\nWith\n\n$$\n\\begin{aligned}\nz(\\xi, \\nu)^{-1} &= \\int_0^\\infty \\int_{-\\infty}^\\infty \\exp \\left( \\nu \\left( \\tau \\mu \\xi_1 - \\frac{1}{2}\\tau \\xi_2 - \\frac{1}{2}\\tau \\mu^2 + \\frac{1}{2} \\ln \\tau \\right) \\right) \\mathrm{d}\\mu \\mathrm{d}\\tau \\\\\n&= \\int_0^\\infty \\tau^\\frac{\\nu}{2} \\int_{-\\infty}^\\infty \\exp \\left( \\frac{\\nu\\tau}{2} \\left( 2\\mu\\xi_1 - \\xi_2 - \\mu^2 \\right) \\right) \\mathrm{d}\\mu \\mathrm{d}\\tau \\\\\n&= \\int_0^\\infty \\tau^\\frac{\\nu}{2} \\exp \\left( -\\frac{\\nu\\tau}{2} \\xi_2 \\right) \\int_{-\\infty}^\\infty \\exp \\left( -\\frac{\\nu\\tau}{2} \\left( \\mu^2 - 2\\mu\\xi_1 \\right) \\right) \\mathrm{d}\\mu \\mathrm{d}\\tau \\\\\n&= \\int_0^\\infty \\tau^\\frac{\\nu}{2} \\exp \\left( -\\frac{\\nu\\tau}{2} \\left( \\xi_2 - \\xi_1^2 \\right) \\right) \\int_{-\\infty}^\\infty \\exp \\left( -\\frac{\\nu\\tau}{2} \\left( \\mu - \\xi_1 \\right)^2 \\right) \\mathrm{d}\\mu \\mathrm{d}\\tau \\\\\n&= \\int_0^\\infty \\tau^\\frac{\\nu}{2} \\exp \\left( -\\frac{\\nu\\tau}{2} \\left( \\xi_2 - \\xi_1^2 \\right) \\right) \\sqrt{\\frac{2\\pi}{\\nu\\tau}} \\mathrm{d}\\tau \\\\\n&= \\sqrt{\\frac{2\\pi}{\\nu}} \\int_0^\\infty \\tau^\\frac{\\nu-1}{2} \\exp \\left( -\\frac{\\nu}{2} \\left( \\xi_2 - \\xi_1^2 \\right) \\tau \\right) \\mathrm{d}\\tau \\\\\n&= \\sqrt{\\frac{2\\pi}{\\nu}} \\frac{\\Gamma \\left( \\frac{\\nu+1}{2} \\right)}{\\left( \\frac{\\nu}{2} \\left( \\xi_2 - \\xi_1^2 \\right) \\right)^\\frac{\\nu+1}{2}} \\\\\n\\end{aligned}\n$$\n\nwe get\n\n$$\n\\begin{aligned}\np\\left( \\vartheta \\middle| \\xi, \\nu \\right) &= z(\\xi, \\nu) \\tau^\\frac{\\nu}{2} \\exp \\left( -\\frac{\\nu}{2} \\left( \\xi_2 - \\xi_1^2 \\right) \\tau \\right) \\exp \\left( -\\frac{\\nu\\tau}{2} \\left( \\mu - \\xi_1 \\right)^2 \\right) \\\\\n&= \\frac{\\left( \\frac{\\nu}{2} \\left( \\xi_2 - \\xi_1^2 \\right) \\right)^\\frac{\\nu+1}{2} }{\\Gamma \\left( \\frac{\\nu+1}{2} \\right)} \\tau^\\frac{\\nu-1}{2} \\exp \\left( -\\frac{\\nu}{2} \\left( \\xi_2 - \\xi_1^2 \\right) \\tau \\right) \\sqrt{\\frac{\\nu\\tau}{2\\pi}} \\exp \\left( -\\frac{\\nu\\tau}{2} \\left( \\mu - \\xi_1 \\right)^2 \\right) \\\\\n&= \\mathcal{N} \\left( \\mu ; \\xi_1, (\\nu\\tau)^{-1} \\right) \\text{Gamma} \\left( \\tau; \\frac{\\nu+1}{2}, \\frac{\\nu}{2} \\left( \\xi_2 - \\xi_1^2 \\right) \\right). \\\\\n\\end{aligned}\n$$\n\n### Prior predictive distribution\n\n$$\n\\begin{aligned}\np\\left( x | \\xi, \\nu \\right) &= \\int_\\Omega p(x | \\vartheta) p(\\vartheta | \\xi, \\nu) \\mathrm{d}\\vartheta \\\\\n&= \\int_0^\\infty \\int_{-\\infty}^\\infty \\mathcal{N} \\left( x ; \\mu, \\tau^{-1} \\right) \\mathcal{N} \\left( \\mu ; \\xi_1, (\\nu\\tau)^{-1} \\right) \\text{Gamma} \\left( \\tau; \\frac{\\nu+1}{2}, \\frac{\\nu}{2} \\left( \\xi_2 - \\xi_1^2 \\right) \\right) \\mathrm{d}\\mu \\mathrm{d}\\tau \\\\\n&= \\int_0^\\infty \\mathcal{N} \\left( x ; \\xi_1, \\left( \\frac{\\nu\\tau}{\\nu+1} \\right)^{-1} \\right) \\text{Gamma} \\left( \\tau; \\frac{\\nu+1}{2}, \\frac{\\nu}{2} \\left( \\xi_2 - \\xi_1^2 \\right) \\right) \\mathrm{d}\\tau \\\\\n&= \\int_0^\\infty \\sqrt{\\frac{\\nu\\tau}{2\\pi(\\nu+1)}} \\exp \\left( -\\frac{\\nu\\tau}{2(\\nu+1)}(x - \\xi_1)^2 \\right) \\frac{\\left( \\frac{\\nu}{2} \\left( \\xi_2 - \\xi_1^2 \\right) \\right)^\\frac{\\nu+1}{2} }{\\Gamma \\left( \\frac{\\nu+1}{2} \\right)} \\tau^\\frac{\\nu-1}{2} \\exp \\left( -\\frac{\\nu}{2} \\left( \\xi_2 - \\xi_1^2 \\right) \\tau \\right) \\mathrm{d}\\tau \\\\\n&= \\sqrt{\\frac{\\nu}{2\\pi(\\nu+1)}} \\frac{\\left( \\frac{\\nu}{2} \\left( \\xi_2 - \\xi_1^2 \\right) \\right)^\\frac{\\nu+1}{2} }{\\Gamma \\left( \\frac{\\nu+1}{2} \\right)} \\int_0^\\infty \\exp \\left( -\\frac{\\nu\\tau}{2(\\nu+1)}(x - \\xi_1)^2 \\right) \\tau^\\frac{\\nu}{2} \\exp \\left( -\\frac{\\nu}{2} \\left( \\xi_2 - \\xi_1^2 \\right) \\tau \\right) \\mathrm{d}\\tau \\\\\n&= \\sqrt{\\frac{\\nu}{2\\pi(\\nu+1)}} \\frac{\\left( \\frac{\\nu}{2} \\left( \\xi_2 - \\xi_1^2 \\right) \\right)^\\frac{\\nu+1}{2} }{\\Gamma \\left( \\frac{\\nu+1}{2} \\right)} \\int_0^\\infty \\tau^\\frac{\\nu}{2} \\exp \\left( -\\frac{\\nu}{2} \\left( \\xi_2 - \\xi_1^2 + \\frac{(x - \\xi_1)^2}{\\nu+1} \\right) \\tau \\right) \\mathrm{d}\\tau \\\\\n&= \\sqrt{\\frac{\\nu}{2\\pi(\\nu+1)}} \\frac{\\left( \\frac{\\nu}{2} \\left( \\xi_2 - \\xi_1^2 \\right) \\right)^\\frac{\\nu+1}{2} }{\\Gamma \\left( \\frac{\\nu+1}{2} \\right)} \\frac{\\Gamma \\left( \\frac{\\nu}{2} + 1\\right)}{\\left( \\frac{\\nu}{2} \\left( \\xi_2 - \\xi_1^2 + \\frac{(x - \\xi_1)^2}{\\nu+1} \\right) \\right)^{\\frac{\\nu}{2} + 1}} \\\\\n&= \\sqrt{\\frac{1}{\\pi(\\nu+1)}} \\frac{\\left( \\xi_2 - \\xi_1^2 \\right)^\\frac{\\nu+1}{2} }{\\Gamma \\left( \\frac{\\nu+1}{2} \\right)} \\frac{\\Gamma \\left( \\frac{\\nu}{2} + 1\\right)}{\\left( \\xi_2 - \\xi_1^2 + \\frac{(x - \\xi_1)^2}{\\nu+1} \\right)^{\\frac{\\nu}{2} + 1}} \\\\\n&= \\sqrt{\\frac{1}{\\pi(\\nu+1)\\left( \\xi_2 - \\xi_1^2 \\right)}} \\frac{\\Gamma \\left( \\frac{\\nu+2}{2} \\right)}{\\Gamma \\left( \\frac{\\nu+1}{2} \\right)} \\left( \\frac{\\xi_2 - \\xi_1^2}{\\xi_2 - \\xi_1^2 + \\frac{(x - \\xi_1)^2}{\\nu+1}} \\right)^{\\frac{\\nu+2}{2}} \\\\\n&= \\sqrt{\\frac{1}{\\pi(\\nu+1)\\left( \\xi_2 - \\xi_1^2 \\right)}} \\frac{\\Gamma \\left( \\frac{\\nu+2}{2} \\right)}{\\Gamma \\left( \\frac{\\nu+1}{2} \\right)} \\left( 1 + \\frac{(x - \\xi_1)^2}{(\\nu+1) \\left( \\xi_2 - \\xi_1^2 \\right)} \\right)^{-\\frac{\\nu+2}{2}} \\\\\n&= \\text{Student's-}t \\left( x; \\nu+1, \\xi_1, \\xi_2 - \\xi_1^2 \\right) \\\\\n\\end{aligned}\n$$\n\nThis motivates the definition of the *normal-predictive* distribution $\\mathcal{NP}$:\n\n$$\n\\mathcal{NP} \\left( x; \\xi_1, \\xi_2, \\nu \\right) := \\sqrt{\\frac{1}{\\pi(\\nu+1)\\left( \\xi_2 - \\xi_1^2 \\right)}} \\frac{\\Gamma \\left( \\frac{\\nu+2}{2} \\right)}{\\Gamma \\left( \\frac{\\nu+1}{2} \\right)} \\left( 1 + \\frac{(x - \\xi_1)^2}{(\\nu+1) \\left( \\xi_2 - \\xi_1^2 \\right)} \\right)^{-\\frac{\\nu+2}{2}}\n$$\n\n## Code and examples\n\n\n```R\ndnp <- function(x, xi1, xi2, nu) {\n # Mean\n mu <- xi1\n # 'Standard deviation'\n sigma <- sqrt(xi2 - xi1^2)\n # Degrees of freedom\n df <- nu + 1\n # Argument\n a <- (x - mu)/sigma\n \n # Density\n d <- 1/sigma*dt(a, df)\n return(d)\n}\n```\n\n\n```R\ndnp(1, 1, 2, 7)\n```\n\n\n0.386699020961393\n\n\n\n```R\ndt(1, 3)\n```\n\n\n0.206748335783172\n\n\n\n```R\nlibrary(ggplot2)\n```\n\n\n```R\noptions(repr.plot.width = 4, repr.plot.height = 3)\nggplot(data.frame(x = c(-4, 4)), aes(x = x)) +\n stat_function(fun = dt, args = list(df = 1)) +\n stat_function(fun = dnp, args = list(xi1 = 1, xi2 = 2, nu = 200), colour = \"red\")\n```\n\n\n```R\n# Define hyperprior update function\nud <- function(xi, nu, x, T = identity) {\n xi <- xi + 1/(1 + nu)*(T(x) - xi)\n return(xi)\n}\n```\n\n\n```R\n# Define sufficient statistics of univariate\n# Gaussian with both parameters unknown\nTnorm <- function(x) {\n T <- c(x, x^2)\n return(T)\n}\n```\n\n\n```R\n# Set parameters of sampling distribution\nmux <- 5\nsdx <- 1/4 # ie pix == 16\n\n# Set hyperpriors to define prior\nxi <- c(0, 1/8)\nnu <- 1\n\n# Sample n observations\nn <- 10001\nxs <- rnorm(n, mux, sdx)\n\n# Hyperprior update loop\nxis <- xi\nnus <- nu\nfor (i in 1:n) {\n xi <- ud(xi, nu, xs[i], Tnorm)\n xis <- rbind(xis, xi)\n nu <- nu + 1\n nus <- append(nus, nu)\n}\n```\n\n\n```R\n# Set up plot\noptions(repr.plot.width = 9, repr.plot.height = 3)\np <- ggplot(data.frame(x = c(-4, 8)), aes(x = x))\n\n# Plot prior predictive\np <- p + stat_function(fun = dnp, args = list(xi1 = xis[1,1], xi2 = xis[1,2], nu = nus[1]), n = 401, colour = \"black\")\n\n\n# Plot every mth posterior predictive\nm <- 200\nfor (i in seq(2, n + 1, m)) {\n p <- p + stat_function(fun = dnp, args = list(xi1 = xis[i,1], xi2 = xis[i,2], nu = nus[i]), n = 401, colour = \"grey\")\n}\n\n# Plot sampling distribution\np <- p + stat_function(fun = dnorm, args = list(mean = mux, sd = sdx), n = 401, colour = \"red\")\n\n# Make the plot\np\n```\n\n\n```R\ngauss_dens <- function(x, mu, la) {\n T <- c(x, x^2)\n h <- 1/sqrt(2*pi)\n eta <- c(la*mu, -la/2)\n B <- (la*mu^2 - log(la))/2\n p <- drop(h*exp(eta %*% T - B))\n\n return(p)\n}\n```\n\n\n```R\ngauss_dens(3,0,1)\n```\n\n\n0.00443184841193801\n\n\n\n```R\ndnorm(3)\n```\n\n\n0.00443184841193801\n\n\n\n```R\n\n```\n", "meta": {"hexsha": "b2a9f7ac4af7ed845b4a03a0a2cb6b7d914f7218", "size": 119978, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/exp-fam.ipynb", "max_stars_repo_name": "AddiH/methods-4-course", "max_stars_repo_head_hexsha": "50cd3d653d6b0eb29768b9a6fbb41cf2108db7f8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2022-01-26T22:33:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-31T11:11:22.000Z", "max_issues_repo_path": "notebooks/exp-fam.ipynb", "max_issues_repo_name": "AddiH/methods-4-course", "max_issues_repo_head_hexsha": "50cd3d653d6b0eb29768b9a6fbb41cf2108db7f8", "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/exp-fam.ipynb", "max_forks_repo_name": "AddiH/methods-4-course", "max_forks_repo_head_hexsha": "50cd3d653d6b0eb29768b9a6fbb41cf2108db7f8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 19, "max_forks_repo_forks_event_min_datetime": "2022-01-26T22:30:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-01T07:56:47.000Z", "avg_line_length": 181.5098335855, "max_line_length": 53806, "alphanum_fraction": 0.844079748, "converted": true, "num_tokens": 7462, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067211996142, "lm_q2_score": 0.9111797148356995, "lm_q1q2_score": 0.8587930054533945}} {"text": "### Analytic Solutions to Variational Bayes\n\nThe general setting for variational Bayesian techniques begins from Bayesian inference, where we wish to infer a posterior.\n\n\\begin{align}\np(z|x) = \\frac{p(x|z)p(z)}{p(x)}\n\\end{align}\n\nOften times the marginal $p(x)$ is too complicated to derive analytically or calcuate computationally. In this case, we call it 'intractable'. When this happens we may wish to approximate the posterior $p(z|x)$. A common technique involves determining a surrogate distribution $q(z|x)$ that is as close as possible to the true posterior. We can measure the closeness between two distributions with the well known Kullback Leibler (KL) divergence. In this case we use the reverse KL divergence.\n\n\\begin{align}\nD_{\\text{KL}}(q(z|x)||p(z|x)) = \\int_z q(z|x) \\log{\\frac{q(z|x)}{p(z|x)}} \\text{d}z\n\\end{align}\n\nHowever, posing the problem this way has not helped us yet as the KL retains the unknown posterior within it. In other words, we need the thing we are trying to approximate, to approximate it. There is a fix. Let us rewrite the KL term as follows...\n\n\\begin{align}\nD_{\\text{KL}}(q(z|x)||p(z|x)) &= \\int_z q(z|x) \\log{\\frac{q(z|x)}{p(z|x)}} \\text{d}z \\\\\n&= \\int_z q(z|x) \\log{\\frac{q(z|x)p(x)}{p(z|x)p(x)}} \\text{d}z \\\\\n&= \\int_z q(z|x) \\log{\\frac{q(z|x)}{p(x,z)}} \\text{d}z + \\int_z q(z|x) \\log{p(x)} \\text{d}z \\\\\n&= \\int_z q(z|x) \\log{\\frac{q(z|x)}{p(x,z)}} \\text{d}z + \\log{p(x)} \\\\\n\\end{align}\n\nWe wish to make the right hand side as small as possible. Recall that the data generating distribution $p(x,z)$ is considered fixed and $x$ is considered given, or observed, therefore $\\log{p(x)}$ is a constant. Minimizing the right hand side then amounts to minimizing the integral where we've replaced the posterior with the joint which is more often available. However, before we move on let us make a quick observation from information theory. As Claude Shannon demonstrated, KL divergence is greater than or equal to zero, therefore we know that \n\n\\begin{align}\n\\int_z q(z|x) \\log{\\frac{q(z|x)}{p(x,z)}} \\text{d}z + \\log{p(x)} &\\ge 0 \\\\\n\\log{p(x)} &\\ge -\\int_z q(z|x) \\log{\\frac{q(z|x)}{p(x,z)}} \\text{d}z \\\\\n\\log{p(x)} &\\ge \\mathcal{L}[q]\n\\end{align}\nWe see that the functional $\\mathcal{L}[q]$ is a lower bound for the marginal likelihood, or model evidence. For this reason $\\mathcal{L}$ is often referred to as the *evidence lower bound* or *ELBO* for short. We will adopt this nomenclature.\n\nOur initial objective was to minimize the reverse KL divergence between the true posterior and our surrogate distribution $q(z|x)$. We have now reformulated that problem to maximizing the ELBO. As posed thus far, the maximum for $\\mathcal{L}$ is when $\\mathcal{L} = \\log{p(x)}$, in which case the KL divergence would be zero and the optimal variational distribution will equal the true posterior $q(z|x) = p(z|x)$. This is rarely possible, so assumptions are made regarding $q(z|x)$ that constrain it to a family of distributions which simplifies the analysis. Under such assumptions, the distribution $q$ is no longer free to take any form and we can not guarantee that our optimal $q^*(z|x)$ equals the posterior. It is in this sense that our technique becomes an approximation. Albeit, there are times when the true posterior lives within the family of our variational distribution $q(z|x)$ and an exact solution is possible. The larger the family, the more likely this is to happen. Though, as the family increases in size, the complexity of the problem often does as well. Therefore, one might consider variational inference as the art of maximizing the expressive power of your model while minimizing the complexity of the resulting analysis. In any case, we often have to settle for a reasonable approximation to the posterior, in the KL sense. \n\n### Mean Field Model\n\nOne simplifying assumption that is made to constrain the variational family is that the distribution $q(z|x)$ factorizes over the latent variables $q(z|x) = q(z_1|x)q(z_2|x)\\cdots q(z_n|x)$. The assumption is often referred to as the *mean field* approximation, inspired by physics. \n\n**(expand on this in the future with your seminar notes)**\n\n### Parametric Families\n\nAnother technique, sometimes used in conjuction with the former, is to assume a parametric family for our variational distribution $q_{\\phi}(z|x)$, parameterized by $\\phi$. The ELBO simplifies to a function of the variational parameters $\\mathcal{L}(\\phi)$. This can sometimes be solved analytically but is most often approached computationally. In this form standard stochastic optimization techniques can be applied.\n\n\\begin{align}\n\\mathcal{L}(\\phi;x) &= -\\int_z q_{\\phi}(z|x) \\log{\\frac{q_{\\phi}(z|x)}{p(x,z)}} \\text{d}z \\\\\n&\\approx \\frac{1}{L} \\sum_i^L \\log{p(x,z_i)} - \\log{q_{\\phi}(z_i|x)}\n\\end{align}\n\nwhere $z_i \\sim q_{\\phi}(z|x)$. From here, one takes the pathwise derivative of the ELBO with respect to the variational parameters $\\phi$ and optimizes with different samples $x \\sim p(x)$.\n\n### Variational Autoencoders\n\nFor variational autoencoders we rewrite the ELBO as follows\n\n\\begin{align}\n\\mathcal{L}[q] &= -\\int_z q(z|x) \\log{\\frac{q(z|x)}{p(x,z)}} \\text{d}z \\\\\n&= \\int_z q(z|x) \\log{\\frac{p(x|z)p(z)}{q(z|x)}} \\text{d}z \\\\\n&= -D_{\\text{KL}}(q(z|x)||p(z)) + \\mathbb{E}_{q(z|x)} \\big[ \\log{p(x|z)} \\big]\\\\\n\\end{align}\n\nBy specifying different assumptions about $q(z|x)$, $p(x|z)$ and $p(z)$ we will arrive at different algorithms. For example if we choose parametric forms amenable to analysis we can derive closed form solutions for the lower bound. These simplifications remove the need for Monte Carlo estimation. Let us examine the most common example. We begin by parameterizing the encoder $q_{\\phi}(z|x)$ as a diagonal covariance Gaussian $\\mathcal{N}(z|x; \\mu,\\sigma^2 \\cdot I)$ where $\\sigma^2 \\in \\mathbb{R}^N$ and assume $p(z)$ is a centered isotropic Gaussian $p(z) = \\mathcal{N}(z; 0,I)$ (i.e. parameterless). \n\n\\begin{align}\nq_{\\phi}(z|x) &= (2\\pi )^{-\\frac{N}{2}} \\big( \\prod_i \\sigma_i^2 \\big )^{-\\frac{1}{2}} \\text{exp}\\big\\{-\\frac{1}{2}(z-\\mu)^T(\\sigma^2 \\cdot I)^{-1}(z-\\mu)\\big\\} \\\\\n\\end{align}\n\\begin{align}\np(z) &= (2\\pi )^{-\\frac{N}{2}} \\text{exp}\\big\\{-\\frac{z^T z}{2}\\} \\\\\n\\log{p(z)} &= -\\frac{N}{2}\\log{2\\pi} -\\frac{z^T z}{2} \\\\\n\\end{align}\n\nWith these definitions we can evaluate the negative KL term as\n\n\\begin{align}\n-D_{\\text{KL}}(q_{\\phi}(z|x)||p(z)) &= \\int_z q_{\\phi}(z|x) \\log{\\frac{p(z)}{q_{\\phi}(z|x)}} \\text{d}z \\\\\n&= \\int_z q_{\\phi}(z|x) \\log{p(z)} \\text{d}z - \\int_z q_{\\phi}(z|x) \\log{q_{\\phi}(z|x)} \\text{d}z \\\\\n&= \\int_z \\bigg((2\\pi )^{-\\frac{N}{2}} \\big( \\prod_i \\sigma_i^2 \\big )^{-\\frac{1}{2}} \\text{exp}\\big\\{-\\frac{1}{2}(z-\\mu)^T(\\sigma^2 \\cdot I)^{-1}(z-\\mu)\\big\\}\\bigg)\\bigg(-\\frac{N}{2}\\log{2\\pi} -\\frac{z^T z}{2}\\bigg)\\text{d}z + H\\big[q_{\\phi}(z|x)\\big]\n\\end{align}\n\nwhere we have identified the term on the right as the entropy $H$ which has a known closed form solution for the multivariate Gaussian case.\n\n\\begin{align}\nH\\big[\\mathcal{N}(x; \\mu,\\Sigma)\\big] &= \\frac{1}{2} \\log{\\text{det}(2 \\pi e \\Sigma)} \\\\\n\\end{align}\n\nTherefore in our case\n\n\\begin{align}\nH\\big[\\mathcal{N}(z|x; \\mu,\\sigma^2 \\cdot I)\\big] &= \\frac{1}{2} \\log\\big(\\text{det}(2 \\pi e \\sigma^2 \\cdot I)\\big) \\\\\n&= \\frac{1}{2} \\log\\big((2 \\pi e)^N \\prod_i \\sigma_i^2\\big) \\\\\n&= \\frac{N}{2} \\log(2 \\pi e) + \\frac{1}{2} \\sum_i \\log(\\sigma_i^2) \\\\\n\\end{align}\n\nNow to address the more daunting integral\n\n\\begin{align}\n& \\int_z q_{\\phi}(z|x) \\log{p(z)} \\text{d}z \\\\\n=& \\int_z \\bigg((2\\pi )^{-\\frac{N}{2}} \\big( \\prod_i \\sigma_i^2 \\big )^{-\\frac{1}{2}} \\text{exp}\\big\\{-\\frac{1}{2}(z-\\mu)^T(\\sigma^2 \\cdot I)^{-1}(z-\\mu)\\big\\}\\bigg)\\bigg(-\\frac{N}{2}\\log{2\\pi} -\\frac{z^T z}{2}\\bigg)\\text{d}z\n\\end{align}\n\nIf we expand the inner term and factor out the constants we see that\n\n\\begin{align}\n& \\int_z \\bigg((2\\pi )^{-\\frac{N}{2}} \\big( \\prod_i \\sigma_i^2 \\big )^{-\\frac{1}{2}} \\text{exp}\\big\\{-\\frac{1}{2}(z-\\mu)^T(\\sigma^2 \\cdot I)^{-1}(z-\\mu)\\big\\}\\bigg)\\bigg(-\\frac{N}{2}\\log{2\\pi} -\\frac{z^T z}{2}\\bigg)\\text{d}z \\\\\n=& -\\frac{N}{2}\\log{2\\pi} \\int_z q_{\\phi}(z|x) \\text{d}z -\\int_z \\frac{z^T z}{2}\\bigg((2\\pi )^{-\\frac{N}{2}} \\big( \\prod_i \\sigma_i^2 \\big )^{-\\frac{1}{2}} \\text{exp}\\big\\{-\\frac{1}{2}(z-\\mu)^T(\\sigma^2 \\cdot I)^{-1}(z-\\mu)\\big\\}\\bigg) \\text{d}z \\\\\n\\end{align}\n\n---\n\nassume we have only $M$ observations from the marginal data generating distribution $p(x)$. In this case we must not only parameterize the variational distribution $q_{\\phi}(z|x)$ but also the true likelihood $p_{\\theta}(x|z)$. Furthermore, we \n\n\n\\begin{align}\n\\nabla_{\\phi} \\mathcal{L}(\\phi;x) &= -\\nabla_{\\phi} \\int_z q_{\\phi}(z|x) \\log{\\frac{q_{\\phi}(z|x)}{p(x,z)}} \\text{d}z \\\\\n&= -\\nabla_{\\phi} \\int_z q_{\\phi}(z|x) \\log{q_{\\phi}(z|x)} \\text{d}z + \\int_z \\nabla_{\\phi} q_{\\phi}(z|x) \\log{p(x,z)} \\text{d}z \\\\\n&= -\\nabla_{\\phi} \\text{H}[q_{\\phi}(z|x)] + \\int_z \\nabla_{\\phi} q_{\\phi}(z|x) \\log{p(x,z)} \\text{d}z\n\\end{align}\n\nwhere we chose to represent the first integral as the entropy $\\text{H}$ because many parametrics models have known closed form solutions for the entropy and this will simplify things to come.\n", "meta": {"hexsha": "f669fa01634ed076c3ba6f405047f4700627a3c0", "size": 11815, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notes/variational_inference.ipynb", "max_stars_repo_name": "mathnathan/notebooks", "max_stars_repo_head_hexsha": "63ae2f17fd8e1cd8d80fef8ee3b0d3d11d45cd28", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-12-04T11:04:45.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-04T11:04:45.000Z", "max_issues_repo_path": "notes/variational_inference.ipynb", "max_issues_repo_name": "mathnathan/notebooks", "max_issues_repo_head_hexsha": "63ae2f17fd8e1cd8d80fef8ee3b0d3d11d45cd28", "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": "notes/variational_inference.ipynb", "max_forks_repo_name": "mathnathan/notebooks", "max_forks_repo_head_hexsha": "63ae2f17fd8e1cd8d80fef8ee3b0d3d11d45cd28", "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.354368932, "max_line_length": 1361, "alphanum_fraction": 0.5834109183, "converted": true, "num_tokens": 3070, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067179697694, "lm_q2_score": 0.91117969855511, "lm_q1q2_score": 0.8587929871658606}} {"text": "# Entropy and Cross-Entropy\n\nCreated by Andres Segura-Tinoco \nCreated on Mar 15, 2021\n\nSource: https://en.wikipedia.org/wiki/Entropy_(information_theory)\n\n\n```\nimport math\n```\n\n**Entropy** is a measure of unpredictability, so its value is inversely related to the compression capacity of a chain of symbols.\n\\begin{align}\n Entropy(X) = H(X) = \\sum_{i=1}^n P(x_i) \\log_{2} \\frac{1}{P(x_i)} \\tag{1}\n\\end{align}\n\nThe **Cross-Entropy** of the distribution $q$ relative to a distribution $p$ over a given set is defined as follows:\n\\begin{align}\n Cross-Entropy(p, q) = H(p, q) = \\sum_{i=1}^n P(x_i) \\log_{2} \\frac{1}{Q(x_i)} \\tag{2}\n\\end{align}\n\n\n```\n# Probability distributions P of x set\np_x = [0.1, 0.2, 0.15, 0.15, 0.4]\nsum(p_x)\n```\n\n\n\n\n 1.0\n\n\n\n\n```\n# Calculate entropy of Px\nh_x = 0\nfor x in p_x:\n h_x -= x * math.log2(x)\nh_x\n```\n\n\n\n\n 2.1464393446710153\n\n\n\n\n```\n# Probability distributions Qgu of x set\nq_x = [0.08, 0.24, 0.13, 0.17, 0.38]\nsum(q_x)\n```\n\n\n\n\n 1.0\n\n\n\n\n```\n# Calculate cross-entropy of Qx relative to Px\nce_x = 0\nfor p, q in zip(p_x, q_x):\n ce_x += p * math.log2(1/q)\nce_x\n```\n\n\n\n\n 2.1595073003443446\n\n\n\n\n```\n# Validation\nh_x < ce_x\n```\n\n\n\n\n True\n\n\n\n
\nYou can contact me on Twitter | GitHub | LinkedIn\n", "meta": {"hexsha": "4dc954b4ebf4c9bbad99b7d2d0be1f8ea55af74c", "size": 4929, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "data-science/DS - Cross-Entropy.ipynb", "max_stars_repo_name": "ansegura7/DS_ML_DL_Examples", "max_stars_repo_head_hexsha": "ccfaa3d84e6d0314f3a826f476cfd20e5e7b73d1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 70, "max_stars_repo_stars_event_min_datetime": "2021-05-17T17:08:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T04:55:40.000Z", "max_issues_repo_path": "data-science/DS - Cross-Entropy.ipynb", "max_issues_repo_name": "ansegura7/DS_ML_DL_Examples", "max_issues_repo_head_hexsha": "ccfaa3d84e6d0314f3a826f476cfd20e5e7b73d1", "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-science/DS - Cross-Entropy.ipynb", "max_forks_repo_name": "ansegura7/DS_ML_DL_Examples", "max_forks_repo_head_hexsha": "ccfaa3d84e6d0314f3a826f476cfd20e5e7b73d1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11, "max_forks_repo_forks_event_min_datetime": "2021-05-17T17:08:06.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-28T03:06:10.000Z", "avg_line_length": 4929.0, "max_line_length": 4929, "alphanum_fraction": 0.6968959221, "converted": true, "num_tokens": 519, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625107731764, "lm_q2_score": 0.9219218423633528, "lm_q1q2_score": 0.8587356340244012}} {"text": "# Solving some system of equations\n\n\n```python\nimport numpy as np\n```\n\n\n```python\n# Solving following system of linear equation\n# 3x + 2y = 7\n# 2x + 3y = 9\n\nx = np.array([[3, 2],[2,3]])\ny = np.array([7, 8])\n\nprint(np.linalg.solve(x,y))\n```\n\n [ 1. 2.]\n\n\n\n```python\n# Solving following system of linear equation\n# 9x - 17y = -20\n# -13x + 7y = -94\n\nx = np.array([[9, -17],[-13,7]])\ny = np.array([-20, -94])\n\nprint(np.linalg.solve(x,y))\n```\n\n [ 11. 7.]\n\n\n\n```python\n# 5x - 2y = -13\n# 4x + 5y = -6\n\nx = np.array([[5, -2],[4,5]])\ny = np.array([-13, -6])\n\nprint(np.linalg.solve(x,y))\n```\n\n [-2.33333333 0.66666667]\n\n\n\n```python\n# 5x + 7y = 11\n# 20x - 18y = 39\n\nx = np.array([[5, 7],[20,-18]])\ny = np.array([11, 39])\n\nprint(np.linalg.solve(x,y))\n```\n\n [ 2.04782609 0.10869565]\n\n\n\n```python\n# 3x - 2y + z = 7\n# x + y + z = 2\n# 3x - 2y - z = 3 \n\nx = np.array([[3, -2, 1],[1, 1, 1],[3, -2, -1]])\ny = np.array([7, 2, 3])\n\nprint(np.linalg.solve(x,y))\n```\n\n [ 1. -1. 2.]\n\n\n\n```python\n# 5x - 2y = -13\n# 4x + 5y = -6\n\nfrom sympy import *\n\nx, y = symbols(['x', 'y'])\nsystem = [Eq(5*x - 2*y, -7),\n Eq(4*x + 5*y, -8)]\n\nsolutions = solve(system, [x, y])\nprint(solutions)\n```\n\n {x: -17/11, y: -4/11}\n\n\n\n```python\n# 3x - 2y + z = 7\n# x + y + z = 2\n# 3x - 2y - z = 3 \n\nfrom sympy import *\n\nx, y, z = symbols(['x', 'y', 'z'])\nsystem = [Eq(3*x - 2*y + z, 7),\n Eq(x + y + z, 2),\n Eq(3*x - 2*y - z, 3)]\n\nsolutions = solve(system, [x, y, z])\nprint(solutions)\n```\n\n {x: 1, y: -1, z: 2}\n\n\n\n```python\nx = np.array([[3, -2, 1],[1, 1, 1],[3, -2, -1]])\ny = np.array([7, 2, 3])\n\n# linalg.solve is the function of NumPy to solve a system of linear scalar equations \nprint(\"Solutions:\\n\", np.linalg.solve(x, y))\n```\n\n Solutions:\n [ 1. -1. 2.]\n\n\n## LU decomposition with SciPy\n\n\n```python\n# LU decomposition with SciPy\nimport scipy.linalg as linalg # Package for LU decomposition\n\nx = np.array([[3, -2, 1],[1, 1, 1],[3, -2, -1]])\ny = np.array([7, 2, 3])\n\n\nLU = linalg.lu_factor(x)\nx = linalg.lu_solve(LU, y) \nprint(\"Solutions:\\n\",x) \n```\n\n Solutions:\n [ 1. -1. 2.]\n\n\n\n```python\nimport scipy\nx = scipy.array([[3, -2, 1],[1, 1, 1],[3, -2, -1]])\nP, L, U = scipy.linalg.lu(x)\n```\n\n\n```python\nprint(\"x:\\n\", x)\nprint(\"-\"*50)\nprint(\"P:\\n\", P)\nprint(\"-\"*50)\nprint(\"L:\\n\", L)\nprint(\"-\"*50)\nprint(\"U:\\n\", U)\n```\n\n x:\n [[ 3 -2 1]\n [ 1 1 1]\n [ 3 -2 -1]]\n --------------------------------------------------\n P:\n [[ 1. 0. 0.]\n [ 0. 1. 0.]\n [ 0. 0. 1.]]\n --------------------------------------------------\n L:\n [[ 1. 0. 0. ]\n [ 0.33333333 1. 0. ]\n [ 1. 0. 1. ]]\n --------------------------------------------------\n U:\n [[ 3. -2. 1. ]\n [ 0. 1.66666667 0.66666667]\n [ 0. 0. -2. ]]\n\n\n## Euclidean \n\n\n```python\nfrom scipy.spatial import distance\na = (1, 2, 3)\nb = (4, 5, 6)\neuc_dist = distance.euclidean(a, b)\n\nprint(\"Euclidean Distance:\", euc_dist)\n```\n\n Euclidean Distance: 5.19615242271\n\n\n## Hadamard Product\n\n\n```python\na = np.array([[1,2],[3,4]])\nb = np.array([[5,6],[7,8]])\nhp = np.multiply(a,b)\n\nprint(\"Hadamard Product:\\n\", hp)\n```\n\n Hadamard Product:\n [[ 5 12]\n [21 32]]\n\n\n\n```python\n# Another method\na * b \n```\n\n\n\n\n array([[ 5, 12],\n [21, 32]])\n\n\n\n\n```python\n# Another method\nnp.multiply(a,b)\n```\n\n\n\n\n array([[ 5, 12],\n [21, 32]])\n\n\n\n## Dot Product\n\n\n```python\nx = np.array([[1,2],[3,4]])\ny = np.array([[5,6],[7,8]])\n\ndp = x @ y\nprint('Dot Product:\\n', dp)\n```\n\n Dot Product:\n [[19 22]\n [43 50]]\n\n\n\n```python\n# Another Method\nnp.dot(x,y)\n```\n\n\n\n\n array([[19, 22],\n [43, 50]])\n\n\n\n## Dot product of vectors\n\nFinding the product of the summation of two vectors and the output will be a single vector.\n\n\n```python\nx = np.array([[1,2],[3,4]])\ny = np.array([[5,6],[7,8]])\ndotproduct = sum(i*j for i,j in zip(x,y))\n\nprint('Dot product is : ' , dotproduct)\n```\n\n Dot product is : [26 44]\n\n\n\n```python\nx = [1,2,3,4]\ny = [5,6,7,8]\ndotproduct = sum(i*j for i,j in zip(x,y))\n\nprint('Dot product is : ' , dotproduct)\n```\n\n Dot product is : 70\n\n\n## Inner Product\n\n\n```python\nx = np.array([[1,2],[3,4]])\ny = np.array([[5,6],[7,8]])\n\nip = np.inner(x,y)\nprint('Inner Product:\\n', ip)\n```\n\n Inner Product:\n [[17 23]\n [39 53]]\n\n", "meta": {"hexsha": "0fa8b2ea21e7033cf9b0a95f5b1e289d183f395c", "size": 14786, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Mathematics_for_Machine_Learning_Linear_Algebra.ipynb", "max_stars_repo_name": "damonclifford/Mathematics_for_Machine_Learning", "max_stars_repo_head_hexsha": "ecdb6b28ce6361dda4e810df829f2d3ed7e7e193", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 28, "max_stars_repo_stars_event_min_datetime": "2019-02-05T04:35:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T19:05:15.000Z", "max_issues_repo_path": "Mathematics_for_Machine_Learning_Linear_Algebra.ipynb", "max_issues_repo_name": "damonclifford/Mathematics_for_Machine_Learning", "max_issues_repo_head_hexsha": "ecdb6b28ce6361dda4e810df829f2d3ed7e7e193", "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_for_Machine_Learning_Linear_Algebra.ipynb", "max_forks_repo_name": "damonclifford/Mathematics_for_Machine_Learning", "max_forks_repo_head_hexsha": "ecdb6b28ce6361dda4e810df829f2d3ed7e7e193", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 19, "max_forks_repo_forks_event_min_datetime": "2019-08-20T14:50:07.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-19T19:24:02.000Z", "avg_line_length": 23.3217665615, "max_line_length": 103, "alphanum_fraction": 0.3551332341, "converted": true, "num_tokens": 1709, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896780646393, "lm_q2_score": 0.9324533130837862, "lm_q1q2_score": 0.8585933859647258}} {"text": "```python\n%pylab inline\nimport seaborn\n```\n\n Populating the interactive namespace from numpy and matplotlib\n\n\n\n```python\nfrom plotting import plot_trajectory\n```\n\n# Joint Space Trajectories\n\n## Point-to-Point Motion\n\n### Cubic Polynomial\n\n\\begin{align}\nq(t) &= a_3 t^3 + a_2 t^2 + a_1 t + a_0 \\\\\n\\dot{q}(t) &= 3 a_3 t^2 + 2 a_2 t + a_1 \\\\\n\\ddot{q}(t) &= 6 a_3 t + 2 a_2\n\\end{align}\n\n\\begin{align}\na_0 &= q_i \\\\\na_1 &= \\dot{q}_i \\\\\na_3 t_f^3 + a_2 t_f^2 + a_1 t_f + a_0 &= q_f \\\\\n3 a_3 t_f^2 + 2 a_2 t_f + a_1 &= \\dot{q}_f\n\\end{align}\n\n\\begin{align}\n\\begin{pmatrix} q_i \\\\ q_f \\\\ \\dot q_i \\\\ \\dot q_f \\end{pmatrix} =\n\\begin{pmatrix} \n 0 & 0 & 0 & 1 \\\\ \n t^3 & t^2 & t & 1 \\\\ \n 0 & 0 & 1 & 0 \\\\ \n 3t^2 & 2t & 1 & 0\n \\end{pmatrix} \n \\begin{pmatrix} a_3 \\\\ a_2 \\\\ a_1 \\\\ a_0 \\end{pmatrix}\n\\end{align}\n\n\n```python\ndef cubic_trajectory(current_position, target_position, \n current_velocity, target_velocity,\n duration_in_seconds):\n trajectories = []\n t = duration_in_seconds\n xs = linspace(0,t)\n for qi, qf, dqi, dqf in zip(current_position, target_position, \n current_velocity, target_velocity):\n A = np.array([[0.0,0.0,0.0,1.0],\n [t**3, t**2, t, 1.],\n [0.0, 0.0, 1.0, 0.0],\n [3.0 * t**2, 2*t, 1.0, 0.0]])\n \n b = np.array([qi, qf, dqi, dqf])\n x = np.linalg.solve(A,b) \n \n qs = np.polyval(x, xs)\n dqs = np.polyval([3. * x[0], 2. * x[1], x[2]], xs)\n ddqs = np.polyval([6. * x[0], 2. * x[1]], xs)\n\n trajectories.append((qs, dqs, ddqs))\n return trajectories\n```\n\n\n```python\nqi = [0,np.pi]\nqf = [np.pi,0]\ndqi = [0,0]\ndqf = [0,0]\ntrajectories = cubic_trajectory(qi, qf, dqi, dqf, 50)\n```\n\n\n```python\nplot_trajectory(trajectories[0], iscubic=True)\n```\n\n### Cubic Polynomial\n\n\n```python\ndef quintic_trajectory(current_position, target_position, current_velocity,\n target_velocity, current_acceleration,\n target_acceleration, duration_in_seconds):\n trajectories = []\n t = duration_in_seconds\n xs = linspace(0, t)\n for qi, qf, dqi, dqf, ddqi, ddqf in zip(current_position, target_position, \n current_velocity, target_velocity,\n current_acceleration, target_acceleration):\n A = np.array(\n [[0.0, 0.0, 0.0, 0.0, 0.0, 1.0], \n [t**5, t**4, t**3, t**2, t, 1.0],\n [0.0, 0.0, 0.0, 0.0, 1.0, 0.0], \n [5. * t**4, 4. * t**3, 3. * t**2, 2. * t, 1., 0.0], \n [0.0, 0.0, 0.0, 2.0, 0.0, 0.0], \n [20. * t**3, 12. * t**2, 6. * t, 2., 0.0, 0.0]])\n\n b = np.array([qi, qf, dqi, dqf, ddqi, ddqf])\n x = np.linalg.solve(A, b)\n\n qs = np.polyval(x, xs)\n dqs = np.polyval([5. * x[0], 4. * x[1], 3. * x[2], 2. * x[3], x[4]], xs)\n ddqs = np.polyval([20. * x[0], 12. * x[1], 6. * x[2], 2. * x[3]], xs)\n\n trajectories.append((qs, dqs, ddqs))\n return trajectories\n```\n\n\n```python\nqi = [0,np.pi]\nqf = [np.pi,0]\ndqi = [0,0]\ndqf = [0,0]\nddqi = [0,0]\nddqf = [0,0]\ntrajectories = quintic_trajectory(qi, qf, dqi, dqf, ddqi, ddqf, 50)\n```\n\n\n```python\nplot_trajectory(trajectories[0], iscubic=False)\n```\n", "meta": {"hexsha": "eb3768c890d144bd7b727f6b74a2a7d6f4b5054d", "size": 149725, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Joint-Space-Trajectories.ipynb", "max_stars_repo_name": "ipk-ntnu/tpk4170", "max_stars_repo_head_hexsha": "2a394841586024d9b81f49a9e8ed2a9b331ddbc4", "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": "Joint-Space-Trajectories.ipynb", "max_issues_repo_name": "ipk-ntnu/tpk4170", "max_issues_repo_head_hexsha": "2a394841586024d9b81f49a9e8ed2a9b331ddbc4", "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": "Joint-Space-Trajectories.ipynb", "max_forks_repo_name": "ipk-ntnu/tpk4170", "max_forks_repo_head_hexsha": "2a394841586024d9b81f49a9e8ed2a9b331ddbc4", "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.537037037, "max_line_length": 75042, "alphanum_fraction": 0.9307330105, "converted": true, "num_tokens": 1258, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109798251322, "lm_q2_score": 0.9032942001955142, "lm_q1q2_score": 0.8585007258781778}} {"text": "## Introduction\n-----\nYou (an electrical engineer) wish to determine the resistance of an electrical component by using Ohm's law. You remember from your high school circuit classes that $$V = RI$$ where $V$ is the voltage in volts, $R$ is resistance in ohms, and $I$ is electrical current in amperes. Using a multimeter, you collect the following data:\n\n| Current (A) | Voltage (V) |\n|-------------|-------------|\n| 0.2 | 1.23 |\n| 0.3 | 1.38 |\n| 0.4 | 2.06 |\n| 0.5 | 2.47 |\n| 0.6 | 3.17 |\n\nYour goal is to \n1. Fit a line through the origin (i.e., determine the parameter $R$ for $y = Rx$) to this data by using the method of least squares. You may assume that all measurements are of equal importance. \n2. Consider what the best estimate of the resistance is, in ohms, for this component.\n\n## Getting Started\n----\n\nFirst we will import the neccesary Python modules and load the current and voltage measurements into numpy arrays:\n\n\n```python\nimport numpy as np\nfrom numpy.linalg import inv\nimport matplotlib.pyplot as plt\n\n# Store the voltage and current data as column vectors.\nI = np.mat([0.2, 0.3, 0.4, 0.5, 0.6]).T\nV = np.mat([1.23, 1.38, 2.06, 2.47, 3.17]).T\n```\n\nNow we can plot the measurements - can you see the linear relationship between current and voltage?\n\n\n```python\nplt.scatter(np.asarray(I), np.asarray(V))\n\nplt.xlabel('Current (A)')\nplt.ylabel('Voltage (V)')\nplt.grid(True)\nplt.show()\n```\n\n\n```python\n\n```\n\n## Estimating the Slope Parameter\n----\nLet's try to estimate the slope parameter $R$ (i.e., the resistance) using the least squares formulation from Module 1, Lesson 1 - \"The Squared Error Criterion and the Method of Least Squares\":\n\n\\begin{align}\n\\hat{R} = \\left(\\mathbf{H}^T\\mathbf{H}\\right)^{-1}\\mathbf{H}^T\\mathbf{y}\n\\end{align}\n\nIf we know that we're looking for the slope parameter $R$, how do we define the matrix $\\mathbf{H}$ and vector $\\mathbf{y}$?\n\n\n```python\n# Define the H matrix, what does it contain?\nH = I\n\nH_transpose = H.transpose()\ninverse = inv(np.dot(H_transpose, H))\n\n# Now estimate the resistance parameter.\n# R = ...\ny = V\nR = inverse * H_transpose * y\n\nprint('The slope parameter (i.e., resistance) for the best-fit line is:')\nprint(R)\nR = R[0, 0]\nprint(R)\n\n```\n\n The slope parameter (i.e., resistance) for the best-fit line is:\n [[5.13444444]]\n 5.134444444444445\n\n\n## Plotting the Results\n----\nNow let's plot our result. How do we relate our linear parameter fit to the resistance value in ohms?\n\n\n```python\nI_line = np.arange(0, 0.8, 0.1)\nV_line = R*I_line\n\nplt.scatter(np.asarray(I), np.asarray(V))\nplt.plot(I_line, V_line)\nplt.xlabel('current (A)')\nplt.ylabel('voltage (V)')\nplt.grid(True)\nplt.show()\n```\n\nIf you have implemented the estimation steps correctly, the slope parameter $\\hat{R}$ should be close to the actual resistance value of $R = 5~\\Omega$. However, the estimated value will not match the true resistance value exactly, since we have only a limited number of noisy measurements.\n", "meta": {"hexsha": "f0f18ebf5eab6bc3cd536fb964081e6708186f03", "size": 31891, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "State Estimation and Localization for Self-Driving Cars/week_1/Programming_excersie/C2M1L1.ipynb", "max_stars_repo_name": "veerkalburgi/Self_Driving_Cars_Specialization", "max_stars_repo_head_hexsha": "42b2bf28104c86b77c49f141b4eead6fc9efe6e1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-08-14T18:27:12.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-14T18:27:12.000Z", "max_issues_repo_path": "State Estimation and Localization for Self-Driving Cars/week_1/Programming_excersie/C2M1L1.ipynb", "max_issues_repo_name": "veerkalburgi/Self_Driving_Cars_Specialization", "max_issues_repo_head_hexsha": "42b2bf28104c86b77c49f141b4eead6fc9efe6e1", "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": "State Estimation and Localization for Self-Driving Cars/week_1/Programming_excersie/C2M1L1.ipynb", "max_forks_repo_name": "veerkalburgi/Self_Driving_Cars_Specialization", "max_forks_repo_head_hexsha": "42b2bf28104c86b77c49f141b4eead6fc9efe6e1", "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": 154.8106796117, "max_line_length": 16028, "alphanum_fraction": 0.8946411213, "converted": true, "num_tokens": 848, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109728022221, "lm_q2_score": 0.9032941969413321, "lm_q1q2_score": 0.8585007164416134}} {"text": "# 15.7. Analyzing a nonlinear differential system — Lotka-Volterra (predator-prey) equations\n\n\n```python\nfrom sympy import *\ninit_printing(pretty_print=True)\n\nvar('x y')\nvar('a b c d', positive=True)\n```\n\n\n```python\nf = x * (a - b * y)\ng = -y * (c - d * x)\n```\n\n\n```python\nsolve([f, g], (x, y))\n```\n\n\n```python\n(x0, y0), (x1, y1) = _\n```\n\n\n```python\nM = Matrix((f, g))\nM\n```\n\n\n```python\nJ = M.jacobian((x, y))\nJ\n```\n\n\n```python\nM0 = J.subs(x, x0).subs(y, y0)\nM0\n```\n\n\n```python\nM0.eigenvals()\n```\n\n\n```python\nM1 = J.subs(x, x1).subs(y, y1)\nM1\n```\n\n\n```python\nM1.eigenvals()\n```\n", "meta": {"hexsha": "b8cd0f37c068ce2526f7764d934ce52d7c983c4e", "size": 39575, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "chapter15_symbolic/07_lotka.ipynb", "max_stars_repo_name": "wgong/cookbook-2nd-code", "max_stars_repo_head_hexsha": "8ca2e5b3c90fee6605f4155e6b9dfb783ce46807", "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": "chapter15_symbolic/07_lotka.ipynb", "max_issues_repo_name": "wgong/cookbook-2nd-code", "max_issues_repo_head_hexsha": "8ca2e5b3c90fee6605f4155e6b9dfb783ce46807", "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": "chapter15_symbolic/07_lotka.ipynb", "max_forks_repo_name": "wgong/cookbook-2nd-code", "max_forks_repo_head_hexsha": "8ca2e5b3c90fee6605f4155e6b9dfb783ce46807", "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.0436507937, "max_line_length": 6428, "alphanum_fraction": 0.9032217309, "converted": true, "num_tokens": 227, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9658995782141546, "lm_q2_score": 0.888758786126321, "lm_q1q2_score": 0.8584517366535375}} {"text": "```python\nimport sympy\n```\n\n\n```python\nx = sympy.symbols(\"x\")\nslope = 3\n\n# Phi-sides\nphi1 = 3*x\nphi2 = 2-3*x\nphi3 = 3*x-1\nphi4 = 3-3*x\n```\n\n\n```python\ninterval1 = sympy.integrate(slope**2, (x, 0, sympy.Rational(1, 3)))\ninterval2 = sympy.integrate(slope**2, (x, sympy.Rational(1, 3), sympy.Rational(2, 3)))\n\ninterval3 = sympy.integrate(phi1**2, (x, 0, sympy.Rational(1, 3)))\ninterval4 = sympy.integrate(phi2**2, (x, sympy.Rational(1, 3), sympy.Rational(2, 3)))\n\nK_11 = interval1 + interval2 + interval3 + interval4\nK_11\n```\n\n\n\n\n$\\displaystyle \\frac{56}{9}$\n\n\n\n\n```python\ninterval1 = sympy.integrate(-slope*slope, (x, sympy.Rational(1, 3), sympy.Rational(2, 3)))\ninterval2 = sympy.integrate(phi2*phi3, (x, sympy.Rational(1, 3), sympy.Rational(2, 3)))\n\nK_12 = interval1 + interval2\nK_12\n```\n\n\n\n\n$\\displaystyle - \\frac{53}{18}$\n\n\n\n\n```python\n# Because of symmetry\n\nsympy.Matrix([[K_11, K_12], [K_12, K_11]])\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}\\frac{56}{9} & - \\frac{53}{18}\\\\- \\frac{53}{18} & \\frac{56}{9}\\end{matrix}\\right]$\n\n\n", "meta": {"hexsha": "10a3d87d5930a7dc83ed71e21e2cb01db0d2f5cc", "size": 3052, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "3.BoundaryValueProblems/Exam2/Exam2.ipynb", "max_stars_repo_name": "nickovchinnikov/Computational-Science-and-Engineering", "max_stars_repo_head_hexsha": "45620e432c97fce68a24e2ade9210d30b341d2e4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2021-01-14T08:00:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-31T14:00:11.000Z", "max_issues_repo_path": "3.BoundaryValueProblems/Exam2/Exam2.ipynb", "max_issues_repo_name": "nickovchinnikov/Computational-Science-and-Engineering", "max_issues_repo_head_hexsha": "45620e432c97fce68a24e2ade9210d30b341d2e4", "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": "3.BoundaryValueProblems/Exam2/Exam2.ipynb", "max_forks_repo_name": "nickovchinnikov/Computational-Science-and-Engineering", "max_forks_repo_head_hexsha": "45620e432c97fce68a24e2ade9210d30b341d2e4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-25T15:21:40.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-25T15:21:40.000Z", "avg_line_length": 22.9473684211, "max_line_length": 150, "alphanum_fraction": 0.5127785059, "converted": true, "num_tokens": 411, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9609517061554854, "lm_q2_score": 0.8933094067644466, "lm_q1q2_score": 0.8584271985550395}} {"text": "Author: Drishika Nadella\n\nDate: 4th March 2021\n\n\n```python\nimport numpy as np\nfrom sympy import *\n```\n\n\n```python\ndef func(x):\n return x*(x-1)\n```\n\n\n```python\ndef derivative(x, delta):\n f_ = (func(x+delta) - func(x))/delta\n return f_\n```\n\n\n```python\n# Analytical derivative\n\nx = Symbol('x')\ny = func(x)\nyprime = y.diff(x)\n\nf = lambdify(x, yprime, 'numpy')\nf(1)\n```\n\n\n\n\n 1\n\n\n\n\n```python\nprint(derivative(1, 10**-2))\n```\n\n 1.010000000000001\n\n\n\n```python\nprint(derivative(1, 10**-4))\n```\n\n 1.0000999999998899\n\n\n\n```python\nprint(derivative(1, 10**-6))\n```\n\n 1.0000009999177333\n\n\n\n```python\nprint(derivative(1, 10**-8))\n```\n\n 1.0000000039225287\n\n\n\n```python\nprint(derivative(1, 10**-10))\n```\n\n 1.000000082840371\n\n\n\n```python\nprint(derivative(1, 10**-12))\n```\n\n 1.0000889005833413\n\n\n\n```python\nprint(derivative(1, 10**-14))\n```\n\n 0.9992007221626509\n\n\nUntil $10^{-8}$, the accuracy got better, and then it got worse again. This is because of the multiplication of very small floating point numbers being multiplied with each other, which increases the round-off error.\n", "meta": {"hexsha": "35813893029e342accb4b028f4437cae4d4d00ca", "size": 3801, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Week 2/HW2_3.ipynb", "max_stars_repo_name": "drkndl/PH354-IISc", "max_stars_repo_head_hexsha": "e1b40a1ed11fb1967cfb5204d81ee237df453d39", "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 2/HW2_3.ipynb", "max_issues_repo_name": "drkndl/PH354-IISc", "max_issues_repo_head_hexsha": "e1b40a1ed11fb1967cfb5204d81ee237df453d39", "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 2/HW2_3.ipynb", "max_forks_repo_name": "drkndl/PH354-IISc", "max_forks_repo_head_hexsha": "e1b40a1ed11fb1967cfb5204d81ee237df453d39", "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": 17.3561643836, "max_line_length": 222, "alphanum_fraction": 0.4706656143, "converted": true, "num_tokens": 375, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308091776495, "lm_q2_score": 0.9196425372343817, "lm_q1q2_score": 0.8584226776848756}} {"text": "```python\n%load_ext autoreload\n%autoreload 2\n\n# Needed imports\nfrom abtest import utils # local utils; see utils.py\nimport pandas as pd\nimport numpy as np\nfrom statsmodels.stats import proportion as ssp\nfrom scipy import stats\n\n%matplotlib inline\nfrom matplotlib import pyplot as plt\nplt.style.use('ggplot')\nimport seaborn as sns\n\n# Some settings for the notebook\n%precision 5\nnp.set_printoptions(precision=4)\npd.set_option('precision',4)\n```\n\nThe focus of this section is on the following case.\nThe experiment consists of two groups: control and variant.\nEach user can either convert or not and the metric of interest is the conversion rate.\nSet the null and alternative hypotheses as follows:\n\n$$\\begin{align}\nH_0:\\quad & p_c = p_v \\\\\nH_a:\\quad & p_c \\neq p_v\n\\end{align}$$\n\nAs before, you can start with a simulation of an experiment.\n\n\n```python\nexp = utils.generate_experiment(seed=43, N=10000, control_cr=0.3, variant_cr=0.3)\nexp\n```\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ConvertedVisitedCR_pct
Control30901000030.90
Variant29521000029.52
\n
\n\n\n\nThe question you will answer in this section is:\n> Is the difference witnessed between the proportions \"real\" or just due to randomness?\n\nThis is the time to introduce the *two-sided $Z$-test*\n\n## Two-sided $Z$-test\n\nRecall that $p_c$ is the conversion rate (or proportion) for the control group and $p_v$ is the one for the variant; both are, in reality, *unknown!*\nNext, $\\hat{p}_c$ and $\\hat{p}_v$ are the rates witnessed in the experiment.\nIn the table above they are given as percentages in the column `CR_pct`.\n\n### By hand\n\nUnder the hood, for each group you obtain a vector $c = (c_1, c_2, \\ldots, c_N)$ and $v = (v_1, v_2, \\ldots, v_N)$ where $c_i, v_i \\in \\{0,1\\}$ and $N$ is the number of visitors in the group (here assumed to be the same).\nFrom this, we have that:\n\n$$\n\\begin{align}\n\\hat{p}_c = \\frac{\\sum c_i}{N} \\\\\n\\hat{p}_v = \\frac{\\sum v_i}{N}\n\\end{align}\n$$\n\nIn other words, the witnessed proportions are means of the values observed.\nTherefore, by the [central limit theorem](https://en.wikipedia.org/wiki/Central_limit_theorem), both are approximately normally distributed.\nThus also their difference $\\hat{p}_c - \\hat{p}_v$.\nIn this case, the following $z$-statistic is to be used [[ref]](https://onlinecourses.science.psu.edu/stat414/node/268)\n\n$$z = \\frac{\\hat{p}_c - \\hat{p}_v}{\\sqrt{\\frac{\\hat{p}(1-\\hat{p})}{c_t} + \\frac{\\hat{p}(1-\\hat{p})}{v_t} }} $$\n\nWhere\n\n$$\\hat{p} = \\frac{c_t \\hat{p}_c + v_t \\hat{p}_v}{c_t + v_t}$$ \n\nis the *pooled* proportion where $c_t$ and $v_t$ are the sample sizes of the control and variant groups, respectively.\nYou can find the above formula implemented in `utils.manual_z_score`; and you can compute the statistic for the data generated for the experiment above.\n\nNote that in this computation the *pooled* version of the variant is used. An un-pooled computation can also be used, but it is less recommended [[ref]](https://stats.stackexchange.com/a/17205/54320).\n\n\n```python\nz_score = utils.manual_z_score(exp)\nz_score\n```\n\n\n\n\n 2.12516\n\n\n\nIt is time to better understand what this score means.\nThe obtained $Z$-score indicates where the results of the experiment lies on the normal distribution:\n\n\n```python\nx = np.arange(-5, 5, step=0.1)\nz_score = utils.manual_z_score(exp)\nx = np.append(x, [-z_score, z_score])\nx = np.sort(x)\ny = stats.norm.pdf(x)\n\nfig, ax = plt.subplots(1, 1)\nax.plot(x , y)\nax.fill_between(x[x <= -abs(z_score)], \n y1=y[x <= -abs(z_score)], alpha=0.5, facecolor='blue');\nax.fill_between(x[x >= abs(z_score)], \n y1=y[x >= abs(z_score)], alpha=0.5, facecolor='blue')\nplt.axvline(z_score, color='gray')\nplt.axvline(-z_score, color='gray')\nplt.text(z_score + 0.1, 0.2, '$|Z|$', rotation=90)\nplt.text(-z_score + 0.1, 0.2, '$-|Z|$', rotation=90)\nplt.title('Normal distribution with $\\mu = 0$ and $\\sigma^2 = 1$');\n```\n\nRecall that the question that has to be answered is:\n> What is the likelihood to witness even more extreme results than those witnessed in the experiment?\n\nThis can be answered by computing the area to the left of $-|Z|$ and to the right of $|Z|$ (shaded in the plot above). \nBy symmetry it is enough to compute the area to the left of $-|Z|$ and multiply the result by $2$.\nThe [cumulative distribution function (cdf)](https://en.wikipedia.org/wiki/Cumulative_distribution_function) of the normal distribution can be used:\n\n\n```python\n2 * stats.norm.cdf(-abs(z_score))\n```\n\n\n\n\n 0.03357\n\n\n\nSay hello to the mighty $p$-value!\nThis value tells you how likely is it to witness even more extreme difference given the null hypothesis holds.\nRecall, that $H_0$ is that the two proportions are the same.\nYou can now convince yourself that this is indeed the meaning of the $p$-value.\nDo so by running a simulation: run $M$ identical experiments and check in how many of them you witness more extreme results.\n\n\n```python\nM = 1000\nN = 10000\nbase_cr_diff = abs((exp.Converted / exp.Visited).diff()[-1])\nnp.random.seed(1492)\nseeds = np.random.randint(0, 2**32-1, size=(M))\ncontrol_cr = 0.3 # 30% \nvariant_cr = 0.3 # 30%\nexperiments = [\n utils.generate_experiment(\n seed=seed, N=N, control_cr=control_cr, variant_cr=variant_cr\n ) for seed in seeds]\ncr_diffs = pd.Series([(exp.Converted / exp.Visited).diff()[-1] for exp in experiments])\n\nprint(\n \"In ~{}% of the simulations the difference between the proportions\\n\"\n \"is at least {:03.3f} (the one in the base experiment)\".format(\n np.round(100 * np.sum(np.abs(cr_diffs) > base_cr_diff) / M, decimals=2),\n base_cr_diff\n ))\n```\n\n In ~3.5% of the simulations the difference between the proportions\n is at least 0.014 (the one in the base experiment)\n\n\n#### Summary\n\nYou obtained the results of a (simulated) experiment (with random seed $43$) where the underlaying proportions are predefined.\nDue to pure randomness you witness a difference between the conversion rates which might be considered big: \n$$\n100 \\cdot \\frac{30.90 - 29.52}{29.52} = 4.675\\%\n$$\n\nBut is it really that big? If you had ran more experiments, what is the likelihood that you would witness an even bigger difference?\nThe $p$-value as computed above, answers this very question.\nIt is now a question of interpretation; can you live peacefully knowing that this extremity is to be expected in $\\sim 3.38\\%$ of the cases?\nIn all other cases the difference is smaller!\nAre you taking a risk by deciding based on this finding?\nLater on you will learn how to better evaluate the validity (or *power*) of the test.\n\n### The Python way\n\nNow, once you hopefully have deeper understanding of the meaning of the $p$-value, you should know how to easily compute it.\nThe easiest way is to use [`statsmodels.stats.proportions.proportions_ztest`](http://www.statsmodels.org/dev/generated/statsmodels.stats.proportion.proportions_ztest.html):\n\n\n```python\n# ssp.proportions_ztest returns a tuple contaiing two values\nres_ztest = ssp.proportions_ztest(exp.Converted, exp.Visited, alternative='two-sided')\nprint(\"z-score = %f\" % res_ztest[0])\nprint(\"p-value = %f\" % res_ztest[1])\n```\n\n z-score = 2.125162\n p-value = 0.033573\n\n\nThe values above are exactly the $Z$-score and the $p$-value as we computed by hand above.\nAt this point it is worthy to mention also the $\\chi^2$-test which is implemented in [`scipy.stats.chi2_contingency`](https://docs.scipy.org/doc/scipy-0.15.1/reference/generated/scipy.stats.chi2_contingency.html).\nFor this to work, the aggregation of the data should be a little altered:\n\n\n```python\n# In this case the function returns also the number of degrees of freedom and \n# the expected frequencies\nres_chi2 = stats.contingency.chi2_contingency(\n pd.concat([exp.Converted, exp.Visited - exp.Converted], axis=1), \n correction=False) # Keeping the default True would yield different resutls\n # due to the Yates’ correction\nprint(\"z-score = %f\" % res_chi2[0])\nprint(\"p-value = %f\" % res_chi2[1])\n```\n\n z-score = 4.516315\n p-value = 0.033573\n\n\nYou should notice that this approach yields the *same* $p$-value but a different score.\nThe math behind this is beyond the scope of this post.\n", "meta": {"hexsha": "66f288fd5f48a093853b10ed18e6066b3b347f43", "size": 32604, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/02-Two sided proportions.ipynb", "max_stars_repo_name": "drorata/abtest", "max_stars_repo_head_hexsha": "e30b05190636ab82c0273b7164adce2852857c4d", "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/02-Two sided proportions.ipynb", "max_issues_repo_name": "drorata/abtest", "max_issues_repo_head_hexsha": "e30b05190636ab82c0273b7164adce2852857c4d", "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/02-Two sided proportions.ipynb", "max_forks_repo_name": "drorata/abtest", "max_forks_repo_head_hexsha": "e30b05190636ab82c0273b7164adce2852857c4d", "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": 78.5638554217, "max_line_length": 18932, "alphanum_fraction": 0.792724819, "converted": true, "num_tokens": 2470, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810481379379, "lm_q2_score": 0.9059898248255075, "lm_q1q2_score": 0.858317589845496}} {"text": "## $$a_0 = \\frac{2}{T}\\int_a^b{f(x)}dx$$\n## $$a_n = \\frac{2}{T}\\int_a^b{f(x)\\;cos(n\\omega x)dx}$$\n## $$b_n = \\frac{2}{T}\\int_a^b{f(x)\\;sin(n\\omega x)dx}$$\n\n\n```python\nfrom sympy import *\nimport sympy as sp\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport handcalcs.render\nplt.style.use('dark_background')\n\nx, t = symbols('x t', real = True)\nn = symbols('n', real = True, positive = True, integer = True)\nT = sp.symbols('T', real = True, positive = True)\na = symbols('a', real = True, positive = True, constant = True)\nnumber_of_terms = 9\n```\n\n# Define function, free variable and range\n\n\n```python\nf = sp.Piecewise((x, x>0), (-x, x<0))\nfree_var = x\nperiod = [-2, 2]\nT = period[1]-period[0]\nT\n```\n\n\n\n\n 4\n\n\n\n# Calculation of coefficients\n\n\n```python\na_0 = (2/T) * integrate(f, (free_var, period[0], period[1]))\na_0 = a_0.simplify()\n\na_n =(2/T) * (integrate(f*cos(n*2*pi*free_var/T), (free_var,period[0], period[1])))\na_n = a_n.simplify()\n\nb_n =(2/T) * integrate(f*sin(n*2*pi/T*free_var), (free_var, period[0], period[1]))\nb_n = b_n.simplify()\n```\n\n\n```python\na_0.factor()\na_0.factor()\n```\n\n\n\n\n$\\displaystyle 2.0$\n\n\n\n\n```python\n%%render\na_0\na_n\nb_n\n```\n\n\n\\[\n\\begin{aligned}\na_{0} &= \\displaystyle 2.0 \\; \n\\\\[10pt]\na_{n} &= \\displaystyle \\frac{4.0 \\left(\\left(-1\\right)^{n} - 1\\right)}{\\pi^{2} n^{2}} \\; \n\\\\[10pt]\nb_{n} &= \\displaystyle 0 \\; \n\\end{aligned}\n\\]\n\n\n# Calculation of whole series upto desired terms\n\n\n```python\na_new = 0\nb_new = 0\na1 = cos(n*free_var) * a_n\nb1 = sin(n*free_var) * b_n\nfor i in range(number_of_terms,0, -1):\n a_new += a1.subs(n, i)\n b_new += b1.subs(n, i)\nser = (a_0/2) + a_new + b_new\n```\n\n# The whole series\n\n\n```python\nser\n```\n\n\n\n\n$\\displaystyle - \\frac{8.0 \\cos{\\left(x \\right)}}{\\pi^{2}} - \\frac{0.888888888888889 \\cos{\\left(3 x \\right)}}{\\pi^{2}} - \\frac{0.32 \\cos{\\left(5 x \\right)}}{\\pi^{2}} - \\frac{0.163265306122449 \\cos{\\left(7 x \\right)}}{\\pi^{2}} - \\frac{0.0987654320987654 \\cos{\\left(9 x \\right)}}{\\pi^{2}} + 1.0$\n\n\n", "meta": {"hexsha": "ea4f6beee2ae99a67f636de0d9264073ed08aef1", "size": 5211, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Fourier series.ipynb", "max_stars_repo_name": "ScientificArchisman/Mathematics", "max_stars_repo_head_hexsha": "2aabf6627d39eb618abb428f1ef2a801b161a066", "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": "Fourier series.ipynb", "max_issues_repo_name": "ScientificArchisman/Mathematics", "max_issues_repo_head_hexsha": "2aabf6627d39eb618abb428f1ef2a801b161a066", "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": "Fourier series.ipynb", "max_forks_repo_name": "ScientificArchisman/Mathematics", "max_forks_repo_head_hexsha": "2aabf6627d39eb618abb428f1ef2a801b161a066", "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": 22.5584415584, "max_line_length": 328, "alphanum_fraction": 0.4709268854, "converted": true, "num_tokens": 773, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810436809827, "lm_q2_score": 0.9059898248255074, "lm_q1q2_score": 0.8583175858075399}} {"text": "# Distribuição Normal\n\nGaussiana, curva de sino\n\n* simétrica\n* média = mediana = moda\n* variáveis contínuas\n\nEx:\n* altura e peso de uma população\n* tamanho do crânio de recém nascidos\n* pressão sanguínea\n\n$$ p(x|\\mu,\\sigma) = \\frac{1}{\\sqrt{2\\pi\\sigma^2}}\\exp\\left[-\\frac{(x-\\mu)^2}{2\\sigma^2}\\right] $$\n\n\n\n```\nimport matplotlib.pyplot as plt\n\nSMALL_SIZE = 12\nMEDIUM_SIZE = 14\nBIGGER_SIZE = 16\n\n# Font Sizes \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.rc('figure', figsize = (8, 6)) # Figure Size\n```\n\n\n```\nimport numpy as np\nfrom scipy.stats import norm\nimport math\n\n\nmu = 0\nvariance = 1\nsigma = np.sqrt(variance)\nx = np.linspace(mu - 3*sigma, mu + 3*sigma, 100)\n\np = 1/np.sqrt(2*math.pi*sigma**2)*np.exp(-(x-mu)**2/(2*sigma**2))\n\nplt.plot(x, norm.pdf(x, mu, sigma), label='scipy')\nplt.plot(x, p, 'k:', lw=5, label='formula')\n\nplt.legend();\n```\n\n\n```\nx = np.linspace(-5, 5, 100)\n\nmu = 0\nsigma = 1\nplt.plot(x,norm.pdf(x, mu, sigma), 'k:', lw=5, \n label=r'$\\mu={}, \\sigma={}$'.format(mu,sigma))\n\nmu = 1\nsigma = 1.5\nplt.plot(x,norm.pdf(x, mu, sigma), 'r-.', lw=2, \n label=r'$\\mu={}, \\sigma={}$'.format(mu,sigma))\n\nmu = -1\nsigma = .75\nplt.plot(x,norm.pdf(x, mu, sigma), 'g', lw=3, \n label=r'$\\mu={}, \\sigma={}$'.format(mu,sigma))\n\n\nplt.legend();\n```\n\nZ_score\n\n$$ z_i = \\frac{x_i-\\bar{x}}{\\sigma} $$\n\n# Distribuição\n\n* Variáveis Contínuas\n * Normal\n * Exponencial\n * Gamma\n\n* Variáveis Discretas\n * Binomial\n * Poisson\n\n# Distribuição binomial\n\n* variáveis discretas\n* dois resultados possíveis de igual chance de ocorrência\n* eventos finitos e independentes\n\nEx.:\n* Dado\n* Moeda\n\n\n$$ p(k|n,p) = \\frac{n!}{k!(n-k)!}p^k(1-p)^{n-k} $$\n\n\n```\nfrom math import factorial\nfrom scipy.stats import binom\n\nn = 50 \np = 0.5\nk_vec = np.arange(1,n+1) # target, starts at 1 goes to n, all possible outcomes\n\ndef compute_binomial_prob(n,k,p):\n return factorial(n)/(factorial(k)*factorial(n-k)) * p**k * (1-p)**(n-k)\n\nP_vec = [compute_binomial_prob(n,k,p) for k in k_vec]\n\nplt.plot(k_vec, binom.pmf(k_vec, n, p), 'r', label='scipy')\nplt.plot(k_vec, P_vec, 'k:', lw=5, label='formula')\n\n\n\n\nplt.legend();\n\n```\n\nEx: https://towardsdatascience.com/fun-with-the-binomial-distribution-96a5ecabf65b\n\n\n```\n# Import libraries\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n# Input variables\n# Number of trials\ntrials = 1000\n# Number of independent experiments in each trial\nn = 10\n# Probability of success for each experiment\np = 0.5\n# Function that runs our coin toss trials (Monte Carlo)\n# heads is a list of the number of successes from each trial of n experiments\ndef run_binom(trials, n, p):\n heads = []\n for i in range(trials):\n tosses = [np.random.random() for i in range(n)]\n heads.append(len([i for i in tosses if i>=0.50]))\n return heads\n# Run the function\nheads = run_binom(trials, n, p)\n# Plot the results as a histogram\nfig, ax = plt.subplots(figsize=(14,7))\nax = sns.distplot(heads, bins=11, label='simulation results')\nax.set_xlabel(\"Number of Heads\",fontsize=16)\nax.set_ylabel(\"Frequency\",fontsize=16);\n```\n\n\n```\n# Plot the actual binomial distribution as a sanity check\nfrom scipy.stats import binom\nx = range(0,11)\nplt.plot(x, binom.pmf(x, n, p), 'ro', label='actual binomial distribution')\nplt.vlines(x, 0, binom.pmf(x, n, p), colors='r', lw=5, alpha=0.5)\nplt.legend()\nplt.show()\n```\n\n\n```\n# Probability of getting 6 heads\nruns = 10000\nprob_6 = sum([1 for i in np.random.binomial(n, p, size=runs) if i==6])/runs\nprint('The probability of 6 heads is: ' + str(prob_6))\n```\n\n The probability of 6 heads is: 0.201\n\n\n\n```\n# Call Center Simulation\n# Number of employees to simulate\nemployees = 100\n# Cost per employee\nwage = 200\n# Number of independent calls per employee\nn = 50\n# Probability of success for each call\np = 0.04\n# Revenue per call\nrevenue = 100\n# Binomial random variables of call center employees\nconversions = np.random.binomial(n, p, size=employees)\n# Print some key metrics of our call center\nprint('Average Conversions per Employee: ' + str(round(np.mean(conversions), 2)))\nprint('Standard Deviation of Conversions per Employee: ' + str(round(np.std(conversions), 2)))\nprint('Total Conversions: ' + str(np.sum(conversions)))\nprint('Total Revenues: ' + str(np.sum(conversions)*revenue))\nprint('Total Expense: ' + str(employees*wage))\nprint('Total Profits: ' + str(np.sum(conversions)*revenue - employees*wage))\n\n# Number of days to simulate\nsims = 1000\nsim_conversions = [np.sum(np.random.binomial(n, p, size=employees)) for i in range(sims)]\nsim_profits = np.array(sim_conversions)*revenue - employees*wage\n```\n\n Average Conversions per Employee: 1.72\n Standard Deviation of Conversions per Employee: 1.28\n Total Conversions: 172\n Total Revenues: 17200\n Total Expense: 20000\n Total Profits: -2800\n\n\n\n```\n# Call Center Simulation (Higher Conversion Rate)\n# Number of employees to simulate\nemployees = 100\n# Cost per employee\nwage = 200\n# Number of independent calls per employee\nn = 55\n# Probability of success for each call\np = 0.05\n# Revenue per call\nrevenue = 100\n# Binomial random variables of call center employees\nconversions_up = np.random.binomial(n, p, size=employees)\n# Simulate 1,000 days for our call center\n# Number of days to simulate\nsims = 1000\n\nsim_conversions_up = [np.sum(np.random.binomial(n, p, size=employees)) for i in range(sims)]\nsim_profits_up = np.array(sim_conversions_up)*revenue - employees*wage\n# Plot and save the results as a histogram\nfig, ax = plt.subplots(figsize=(14,7))\nax = sns.distplot(sim_profits, bins=20, label='original call center simulation results')\nax = sns.distplot(sim_profits_up, bins=20, label='improved call center simulation results', color='red')\nax.set_xlabel(\"Profits\",fontsize=16)\nax.set_ylabel(\"Frequency\",fontsize=16)\nplt.legend();\n```\n\nEx: https://cmdlinetips.com/2018/03/probability-distributions-in-python/\n\n\nhttps://www.probabilisticworld.com/discrete-probability-distributions-overview/\n\n\n```\n# for inline plots in jupyter\n%matplotlib inline\n# import matplotlib\nimport matplotlib.pyplot as plt\n# import seaborn\nimport seaborn as sns\n# settings for seaborn plotting style\nsns.set(color_codes=True)\n# settings for seaborn plot sizes\nsns.set(rc={'figure.figsize':(4.5,3)})\n```\n\n# Uniform distribution\n\n$$ P(x;n) = \\frac{1}{n} $$\n\n\n```\n# import uniform distribution\nfrom scipy.stats import uniform\n\n# random numbers from uniform distribution\n# Generate 10 numbers from 0 to 10\nn = 10000\na = 0\nb = 10\ndata_uniform = uniform.rvs(size=n, loc = a, scale=b) #random variables\n\nax = sns.distplot(data_uniform,\n bins=100,\n kde=False, # density plot\n color='skyblue',\n hist_kws={\"linewidth\": 15,'alpha':1})\nax.set(xlabel='Uniform ', ylabel='Frequency');\n```\n\n# Normal distribution\n\n$$ p(x|\\mu,\\sigma) = \\frac{1}{\\sqrt{2\\pi\\sigma^2}}\\exp\\left[-\\frac{(x-\\mu)^2}{2\\sigma^2}\\right] $$\n\n\n```\nfrom scipy.stats import norm\n\n# generate random numbers from N(0,1)\ndata_normal = norm.rvs(size=10000,loc=0,scale=1) # loc = mean, scale = std\n\nax = sns.distplot(data_normal,\n bins=100,\n kde=False,\n color='skyblue',\n hist_kws={\"linewidth\": 15,'alpha':1})\nax.set(xlabel='Normal', ylabel='Frequency');\n```\n\n# Bernoulli distribution\n\nDiscrete. Outcome: 0 or 1.\n\n\n\\begin{equation}\nP(x;p) = \\begin{cases}\np &\\text{if $x=1$}\\\\\n1-p &\\text{if $x=0$}\n\\end{cases}\n\\end{equation}\n\n\n\n```\n# import bernoulli\nfrom scipy.stats import bernoulli\n\n# generate bernoulli\ndata_bern = bernoulli.rvs(size=10000,p=0.3)\nax= sns.distplot(data_bern,\n kde=False,\n color=\"skyblue\",\n hist_kws={\"linewidth\": 15,'alpha':1})\nax.set(xlabel='Bernoulli', ylabel='Frequency');\n\n\n```\n\n# Binomial distribution\n\nDiscrete.\nObtains the number of successe from N Bernoulli trials.\n\n$$ p(k|n,p) = \\frac{n!}{k!(n-k)!}p^k(1-p)^{n-k} $$\n\n\\begin{equation}\np(x; p,n) = \\binom{n}{x}p^{x}(1-p)^{n-x}\n\\end{equation}\n\n\n```\nfrom scipy.stats import binom\n\nbinom.rvs(n=10,p=0.5) # sucesses from n=10 Bernoulli trials with p=0.5\n\n\ndata_binom = binom.rvs(n=10,p=0.5,size=10000)\nax = sns.distplot(data_binom,\n kde=False,\n color='skyblue',\n hist_kws={\"linewidth\": 15,'alpha':1})\nax.set(xlabel='Binomial', ylabel='Frequency');\n\n```\n\n# Poisson distribution\n\nnumber of times an event happened in a time interval\n\n* rate of ocurrence (mu)\n\n$$ P(x;\\mu)=\\frac{\\mu^x e^{-\\mu}}{x!} $$\n\n\n```\nfrom scipy.stats import poisson\n\ndata_poisson = poisson.rvs(mu=3, size=10000)\nax = sns.distplot(data_poisson,\n kde=False,\n color='green',\n hist_kws={\"linewidth\": 15,'alpha':1})\nax.set(xlabel='Poisson', ylabel='Frequency');\n```\n\n# Beta distribution\n\n* Continuous\n* distribution for probabilities\n\n\n```\nfrom scipy.stats import beta\n\ndata_beta = beta.rvs(1, 1, size=10000) # ~ uniform\nax = sns.distplot(data_beta,\n kde=False,\n bins=100,\n color='skyblue',\n hist_kws={\"linewidth\": 15,'alpha':1})\nax.set(xlabel='Beta(1,1)', ylabel='Frequency');\n```\n\n\n```\ndata_beta_a10b1 = beta.rvs(10, 1, size=10000) #skewed right\nax = sns.distplot(data_beta_a10b1,\n kde=False,\n bins=50,\n color='skyblue',\n hist_kws={\"linewidth\": 15,'alpha':1})\nax.set(xlabel='Beta(10,1)', ylabel='Frequency');\n```\n\n\n```\ndata_beta_a1b10 = beta.rvs(1, 10, size=10000) # skewed leftt\nax = sns.distplot(data_beta_a1b10,\n kde=False,\n bins=100,\n color='skyblue',\n hist_kws={\"linewidth\": 15,'alpha':1})\nax.set(xlabel='Beta(1,10)', ylabel='Frequency');\n```\n\n\n```\ndata_beta_a10b10 = beta.rvs(10, 10, size=10000) # ~ normal\nax = sns.distplot(data_beta_a10b10,\n kde=False,\n bins=100,\n color='skyblue',\n hist_kws={\"linewidth\": 15,'alpha':1})\nax.set(xlabel='Beta(10,10)', ylabel='Frequency');\n```\n\n# Gamma distribution\n\n\n\n\n```\nfrom scipy.stats import gamma\n\ndata_gamma = gamma.rvs(a=5, size=10000)\nax = sns.distplot(data_gamma,\n kde=False,\n bins=100,\n color='skyblue',\n hist_kws={\"linewidth\": 15,'alpha':1})\nax.set(xlabel='Gamma', ylabel='Frequency');\n```\n\n\n```\nhelp(gamma)\n```\n\n Help on gamma_gen in module scipy.stats._continuous_distns object:\n \n class gamma_gen(scipy.stats._distn_infrastructure.rv_continuous)\n | A gamma continuous random variable.\n | \n | %(before_notes)s\n | \n | See Also\n | --------\n | erlang, expon\n | \n | Notes\n | -----\n | The probability density function for `gamma` is:\n | \n | .. math::\n | \n | f(x, a) = \\frac{x^{a-1} \\exp(-x)}{\\Gamma(a)}\n | \n | for :math:`x \\ge 0`, :math:`a > 0`. Here :math:`\\Gamma(a)` refers to the\n | gamma function.\n | \n | `gamma` takes ``a`` as a shape parameter for :math:`a`.\n | \n | When :math:`a` is an integer, `gamma` reduces to the Erlang\n | distribution, and when :math:`a=1` to the exponential distribution.\n | \n | %(after_notes)s\n | \n | %(example)s\n | \n | Method resolution order:\n | gamma_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 | When the location is fixed by using the argument `floc`, this\n | function uses explicit formulas or solves a simpler numerical\n | problem than the full ML optimization problem. So in that case,\n | the `optimizer`, `loc` and `scale` arguments are ignored.\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# Lognormal distribution\n\n\n```\nfrom scipy.stats import lognorm\n\ndata_lognorm = lognorm.rvs(0.2, size=10000)\nax = sns.distplot(data_lognorm,kde=False,\n bins=100,\n color='skyblue',\n hist_kws={\"linewidth\": 15,'alpha':1})\nax.set(xlabel='Log Normal', ylabel='Frequency');\n```\n\n# Negative Binomial distribution\n* discrete\n\n\n```\nfrom scipy.stats import nbinom\n\ndata_nbinom = nbinom.rvs(10, 0.5, size=10000)\nax = sns.distplot(data_nbinom,\n kde=False,\n color='skyblue',\n hist_kws={\"linewidth\": 15,'alpha':1})\nax.set(xlabel='Negative Binomial', ylabel='Frequency');\n```\n\n# PDF e CDF\nPDF: Função Densidade de Probabilidade\n* relativa\n* não negativa\n* integral = 1\n\nCDF: Função Distribuição Acumulada\n* acumulada\n* não negativa\n* integral = 1\n\nSurvivor fuction = 1 - CDF\n\nECDF\n* estimador empírico\n\n\n\n```\n\n```\n", "meta": {"hexsha": "dfa44b0b863d5f6ce1ce4d42f8ec5257baa46ec9", "size": 332728, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "GoogleColab/AceleraDevEstatistica.ipynb", "max_stars_repo_name": "viniciusriosfuck/dscodenation", "max_stars_repo_head_hexsha": "b59fb4417f6b348538f500123fe0ed4d048e2505", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-11-09T18:18:41.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-09T18:18:41.000Z", "max_issues_repo_path": "GoogleColab/AceleraDevEstatistica.ipynb", "max_issues_repo_name": "inaborges/dscodenation", "max_issues_repo_head_hexsha": "710113aeed64f3302fe207201a967cc7cdc9e8e7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2020-07-21T17:28:07.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-05T22:30:35.000Z", "max_forks_repo_path": "GoogleColab/AceleraDevEstatistica.ipynb", "max_forks_repo_name": "inaborges/dscodenation", "max_forks_repo_head_hexsha": "710113aeed64f3302fe207201a967cc7cdc9e8e7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-07-21T22:40:33.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-21T22:40:33.000Z", "avg_line_length": 332728.0, "max_line_length": 332728, "alphanum_fraction": 0.9060283475, "converted": true, "num_tokens": 9913, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810481379379, "lm_q2_score": 0.9059898114992677, "lm_q1q2_score": 0.858317577220469}} {"text": "## Basic sympy setting\n\n\n```python\n%reset -f \nfrom sympy import * # import everything from sympy module\ninit_printing() # for nice math output \n\n## forcing plots inside browser\n%matplotlib inline\n```\n\n### Declare symbolic variables\n\n\n```python\nx = symbols('x')\n```\n\n### Example 1\n\nFind 4-th degree Taylor polynamial of $f(x) = \\sin(x)$ at $a = \\frac{\\pi}{2}$. Plot $f(x)$ and Taylor polynomial on the same window\n\n\n\n```python\n## Finding Taylor polynomial\n\na = pi/2\nf = sin(x)\n\nT = f.subs(x,a) \\\n + diff(f,x,1).subs(x,a)*(x-a) \\\n + diff(f,x,2).subs(x,a)*(x-a)**2/2 \\\n + diff(f,x,3).subs(x,a)*(x-a)**3/factorial(3) \\\n + diff(f,x,4).subs(x,a)*(x-a)**4/factorial(4)\n \nT\n \n```\n\n\n```python\n## plotting f(x) and T(x) in same window\n\n\np = plot(f,T, (x,a - 4, a + 4),show=False, legend=True)\n\np[0].line_color = 'blue'\np[1].line_color = 'green'\n\np[0].label = 'f(x)'\np[1].label = 'T(x)'\n\np.show()\n```\n\n### Example 2\n\nFind 20-th degree Taylor polynamial of $f(x) = \\log(x)$ at $a = 1$. Plot $f(x)$ and Taylor polynomial on the same window\n\n\n\n```python\n## evaluation of T\n\na = 1\nn = 20\nf = log(x)\n\nT = f.subs(x,a)\n\nfor k in range(1,n+1):\n df = diff(f,x,k)\n T = T + df.subs(x,a)*(x-a)**k/factorial(k)\n \nT\n```\n\n\n```python\n## plotting f(x) and T(x) in same window\n\n\np = plot(f,T, (x, 0.5, 2),show=False, legend=True)\n\np[0].line_color = 'blue'\np[1].line_color = 'green'\n\np[0].label = 'f(x)'\np[1].label = 'T(x)'\n\np.show()\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "ab140b59006d559ef67f9f3ad0a42fe244a25cc8", "size": 69126, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "sympy/TaylorPolynomial.ipynb", "max_stars_repo_name": "krajit/krajit.github.io", "max_stars_repo_head_hexsha": "221c8bcdf0612b3ae28c827809aa309ea6a7b0c2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-09-29T07:40:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-28T22:17:04.000Z", "max_issues_repo_path": "sympy/TaylorPolynomial.ipynb", "max_issues_repo_name": "krajit/krajit.github.io", "max_issues_repo_head_hexsha": "221c8bcdf0612b3ae28c827809aa309ea6a7b0c2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2019-08-26T08:42:47.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-26T09:48:21.000Z", "max_forks_repo_path": "sympy/TaylorPolynomial.ipynb", "max_forks_repo_name": "krajit/krajit.github.io", "max_forks_repo_head_hexsha": "221c8bcdf0612b3ae28c827809aa309ea6a7b0c2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2017-09-09T23:32:09.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-28T21:11:39.000Z", "avg_line_length": 270.0234375, "max_line_length": 29342, "alphanum_fraction": 0.9014408471, "converted": true, "num_tokens": 529, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9591542817548989, "lm_q2_score": 0.8947894527758052, "lm_q1q2_score": 0.8582411348990365}} {"text": "## Computing a running variance the smart way\n\nSuppose we compute the running mean of a list of numbers $x_1,\\,x_2,\\,...,x_p,...$ when the $p^{th}$ number $x_p$ arrives the *smart way* (as shown above)\n\n\\begin{equation}\nh_{p}^{\\text{ave}} = \\frac{p-1}{p}h_{p-1}^{\\text{ave}} + \\frac{1}{p}x_p\n\\end{equation}\n\nand then - on top of this - we would like to compute the *running variance* of our ever-increasing list of numbers. If we used the standard formula for variance we would compute\n\n\\begin{equation}\nh_p^{\\text{var}} = \\frac{1}{p}\\sum_{j=1}^p\\left(x_j - h_p^{\\text{ave}}\\right)^2\n\\end{equation}\n\neach time a new point $x_p$ arrived. However computing the running variance this way would be wasteful - both in terms of storage (we would need to store all of the previous input points) and computation (we're repeating the same sorts of computation over and over again) - in complete analogy to the use of the standard formula when computing the running mean (as we saw above). \n\nMultiplying both sides of Equation (2) by $p$ we have \n\n\\begin{equation}\np\\,h_p^{\\text{var}} = \\sum_{j=1}^p\\left(x_j - h_p^{\\text{ave}}\\right)^2\n\\end{equation}\n\nPlugging in $p-1$ in place of $p$ in the Equation above yields\n\n\\begin{equation}\n\\left(p-1\\right)\\,h_{p-1}^{\\text{var}} = \\sum_{j=1}^{p-1}\\left(x_j - h_{p-1}^{\\text{ave}}\\right)^2\n\\end{equation}\n\nSubtracting (4) from (3), and simple re-arrangement of terms gives\n\n\\begin{equation}\n\\begin{split}\np\\,h_p^{\\text{var}} - \\left(p-1\\right)\\,h_{p-1}^{\\text{var}} & = \\sum_{j=1}^p\\left(x_j - h_p^{\\text{ave}}\\right)^2 - \\sum_{j=1}^{p-1}\\left(x_j - h_{p-1}^{\\text{ave}}\\right)^2 \\\\\n& = \\left[\\left(x_p - h_p^{\\text{ave}}\\right)^2 + \\sum_{j=1}^{p-1}\\left(x_j - h_p^{\\text{ave}}\\right)^2 \\right] - \\sum_{j=1}^{p-1}\\left(x_j - h_{p-1}^{\\text{ave}}\\right)^2 \\\\\n& = \\left(x_p - h_p^{\\text{ave}}\\right)^2 + \\left[\\sum_{j=1}^{p-1}\\left(x_j - h_p^{\\text{ave}}\\right)^2 - \\sum_{j=1}^{p-1}\\left(x_j - h_{p-1}^{\\text{ave}}\\right)^2\\right] \\\\\n& = \\left(x_p - h_p^{\\text{ave}}\\right)^2 + \\sum_{j=1}^{p-1}\\left[\\left(x_j - h_p^{\\text{ave}}\\right)^2 - \\left(x_j - h_{p-1}^{\\text{ave}}\\right)^2\\right] \\\\\n\\end{split}\n\\end{equation}\n\nWe now use the identity $a^2 - b^2 = \\left(a-b\\right)\\left(a+b\\right)$ to simplify each summand in Equation (5) as follows\n\n\\begin{equation}\n\\begin{split}\np\\,h_p^{\\text{var}} - \\left(p-1\\right)\\,h_{p-1}^{\\text{var}} & = \\left(x_p - h_p^{\\text{ave}}\\right)^2 + \\sum_{j=1}^{p-1}\\left(h_{p-1}^{\\text{ave}} - h_p^{\\text{ave}}\\right) \\left(2 x_j - h_{p}^{\\text{ave}}-h_{p-1}^{\\text{ave}}\\right) \\\\\n & = \\left(x_p - h_p^{\\text{ave}}\\right)^2 + \\left(h_{p-1}^{\\text{ave}} - h_p^{\\text{ave}}\\right) \\sum_{j=1}^{p-1} \\left(2 x_j - h_{p}^{\\text{ave}}-h_{p-1}^{\\text{ave}}\\right)\\\\\n\\end{split}\n\\end{equation}\n\nNotice, the last summation in Equation above can be written equivalently as\n\n\\begin{equation}\n\\begin{split}\n\\sum_{j=1}^{p-1} \\left(2 x_j - h_{p}^{\\text{ave}}-h_{p-1}^{\\text{ave}}\\right) & = \\left(2\\sum_{j=1}^{p-1} x_j\\right) - \\left(p-1\\right) \\left( h_{p}^{\\text{ave}} + h_{p-1}^{\\text{ave}} \\right)\\\\\n& = 2\\left(p-1\\right)h_{p-1}^{\\text{ave}} - \\left(p-1\\right) \\left( h_{p}^{\\text{ave}} + h_{p-1}^{\\text{ave}} \\right)\\\\\n& = \\left(p-1\\right) h_{p-1}^{\\text{ave}} - \\left(p-1\\right) h_{p}^{\\text{ave}} \\\\ \n& = \\left(p \\,h_{p}^{\\text{ave}} - x_p\\right) - \\left(p-1\\right) h_{p}^{\\text{ave}} \\\\ \n& = h_{p}^{\\text{ave}} - x_p\n\\end{split}\n\\end{equation}\n\nwhere we have made use of the fact that $\\left(p-1\\right) h_{p-1}^{\\text{ave}} = p \\,h_{p}^{\\text{ave}} - x_p$.\n\nSubstituting the result above into (6) we now have\n\n\\begin{equation}\n\\begin{split}\np\\,h_p^{\\text{var}} - \\left(p-1\\right)\\,h_{p-1}^{\\text{var}} & = \\left(x_p - h_p^{\\text{ave}}\\right)^2 + \\left(h_{p-1}^{\\text{ave}} - h_p^{\\text{ave}}\\right) \\left(h_{p}^{\\text{ave}} - x_p\\right)\\\\\n & = \\left(x_p - h_p^{\\text{ave}}\\right)\\left(x_p - h_{p-1}^{\\text{ave}}\\right)\n\\end{split}\n\\end{equation}\n\nA little re-arrangement finally gives \n\n\n\\begin{equation}\nh_{p}^{\\text{var}} = \\frac{p-1}{p}h_{p-1}^{\\text{var}} + \\frac{1}{p}\\left(x_p^{\\,} - h_{p}^{\\text{ave}}\\right)\\left(x_p^{\\,} - h_{p-1}^{\\text{ave}}\\right)\n\\end{equation}\n", "meta": {"hexsha": "e6a84fc9e1b682d74cf15c01f06e80c720033c96", "size": 6317, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "posts/dynamic_systems_limited_memory/running_variance_derivation.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": "posts/dynamic_systems_limited_memory/running_variance_derivation.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": "posts/dynamic_systems_limited_memory/running_variance_derivation.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": 43.8680555556, "max_line_length": 387, "alphanum_fraction": 0.5273072661, "converted": true, "num_tokens": 1750, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037363973295, "lm_q2_score": 0.9263037257164178, "lm_q1q2_score": 0.8580386021698849}} {"text": "```python\nOABC is any quadrilateral in 3D space. \nP is the midpoint of OA, Q is the midpoint of AB, R is the midpoint of BC and S is the midpoint of OC. \nProve that PQ is parallel to SR\n```\n\n\n```python\n#Define a coordinate system\nfrom sympy.vector import CoordSys3D\nSys = CoordSys3D('Sys')\n```\n\n\n```python\n# Define point O to be Sys’ origin. We can do this without loss of generality\nO = Sys.origin\n\n```\n\n\n```python\n#Define point A with respect to O\n\nfrom sympy import symbols\na1, a2, a3 = symbols('a1 a2 a3')\nA = O.locate_new('A', a1*Sys.i + a2*Sys.j + a3*Sys.k)\n```\n\n\n\n\n$\\displaystyle Point\\left(A, (a_{1})\\mathbf{\\hat{i}_{Sys}} + (a_{2})\\mathbf{\\hat{j}_{Sys}} + (a_{3})\\mathbf{\\hat{k}_{Sys}}, Point\\left(Sys.origin, \\mathbf{\\hat{0}}\\right)\\right)$\n\n\n\n\n```python\nA\n```\n\n\n\n\n$\\displaystyle Point\\left(A, (a_{1})\\mathbf{\\hat{i}_{Sys}} + (a_{2})\\mathbf{\\hat{j}_{Sys}} + (a_{3})\\mathbf{\\hat{k}_{Sys}}, Point\\left(Sys.origin, \\mathbf{\\hat{0}}\\right)\\right)$\n\n\n\n\n```python\n# Similarly define points B and C\n\nb1, b2, b3 = symbols('b1 b2 b3')\nB = O.locate_new('B', b1*Sys.i + b2*Sys.j + b3*Sys.k)\nc1, c2, c3 = symbols('c1 c2 c3')\nC = O.locate_new('C', c1*Sys.i + c2*Sys.j + c3*Sys.k)\n```\n\n\n```python\nB\n```\n\n\n\n\n$\\displaystyle Point\\left(B, (b_{1})\\mathbf{\\hat{i}_{Sys}} + (b_{2})\\mathbf{\\hat{j}_{Sys}} + (b_{3})\\mathbf{\\hat{k}_{Sys}}, Point\\left(Sys.origin, \\mathbf{\\hat{0}}\\right)\\right)$\n\n\n\n\n```python\nC\n```\n\n\n\n\n$\\displaystyle Point\\left(C, (c_{1})\\mathbf{\\hat{i}_{Sys}} + (c_{2})\\mathbf{\\hat{j}_{Sys}} + (c_{3})\\mathbf{\\hat{k}_{Sys}}, Point\\left(Sys.origin, \\mathbf{\\hat{0}}\\right)\\right)$\n\n\n\n\n```python\n# P is the midpoint of OA. Lets locate it with respect to O (you could also define it with respect to A).\nP = O.locate_new('P', A.position_wrt(O) + (O.position_wrt(A) / 2))\nP\n```\n\n\n\n\n$\\displaystyle Point\\left(P, (\\frac{a_{1}}{2})\\mathbf{\\hat{i}_{Sys}} + (\\frac{a_{2}}{2})\\mathbf{\\hat{j}_{Sys}} + (\\frac{a_{3}}{2})\\mathbf{\\hat{k}_{Sys}}, Point\\left(Sys.origin, \\mathbf{\\hat{0}}\\right)\\right)$\n\n\n\n\n```python\n# Similarly define points Q, R and S as per the problem definitions.\nQ = A.locate_new('Q', B.position_wrt(A) / 2)\nR = B.locate_new('R', C.position_wrt(B) / 2)\nS = O.locate_new('R', C.position_wrt(O) / 2)\n```\n\n\n```python\nQ\n```\n\n\n\n\n$\\displaystyle Point\\left(Q, (- \\frac{a_{1}}{2} + \\frac{b_{1}}{2})\\mathbf{\\hat{i}_{Sys}} + (- \\frac{a_{2}}{2} + \\frac{b_{2}}{2})\\mathbf{\\hat{j}_{Sys}} + (- \\frac{a_{3}}{2} + \\frac{b_{3}}{2})\\mathbf{\\hat{k}_{Sys}}, Point\\left(A, (a_{1})\\mathbf{\\hat{i}_{Sys}} + (a_{2})\\mathbf{\\hat{j}_{Sys}} + (a_{3})\\mathbf{\\hat{k}_{Sys}}, Point\\left(Sys.origin, \\mathbf{\\hat{0}}\\right)\\right)\\right)$\n\n\n\n\n```python\nR\n```\n\n\n\n\n$\\displaystyle Point\\left(R, (- \\frac{b_{1}}{2} + \\frac{c_{1}}{2})\\mathbf{\\hat{i}_{Sys}} + (- \\frac{b_{2}}{2} + \\frac{c_{2}}{2})\\mathbf{\\hat{j}_{Sys}} + (- \\frac{b_{3}}{2} + \\frac{c_{3}}{2})\\mathbf{\\hat{k}_{Sys}}, Point\\left(B, (b_{1})\\mathbf{\\hat{i}_{Sys}} + (b_{2})\\mathbf{\\hat{j}_{Sys}} + (b_{3})\\mathbf{\\hat{k}_{Sys}}, Point\\left(Sys.origin, \\mathbf{\\hat{0}}\\right)\\right)\\right)$\n\n\n\n\n```python\nS\n```\n\n\n\n\n$\\displaystyle Point\\left(R, (\\frac{c_{1}}{2})\\mathbf{\\hat{i}_{Sys}} + (\\frac{c_{2}}{2})\\mathbf{\\hat{j}_{Sys}} + (\\frac{c_{3}}{2})\\mathbf{\\hat{k}_{Sys}}, Point\\left(Sys.origin, \\mathbf{\\hat{0}}\\right)\\right)$\n\n\n\n\n```python\n# Now compute the vectors in the directions specified by PQ and SR.\nPQ = Q.position_wrt(P)\nSR = R.position_wrt(S)\n```\n\n\n\n\n$\\displaystyle (\\frac{b_{1}}{2})\\mathbf{\\hat{i}_{Sys}} + (\\frac{b_{2}}{2})\\mathbf{\\hat{j}_{Sys}} + (\\frac{b_{3}}{2})\\mathbf{\\hat{k}_{Sys}}$\n\n\n\n\n```python\nPQ\n```\n\n\n\n\n$\\displaystyle (\\frac{b_{1}}{2})\\mathbf{\\hat{i}_{Sys}} + (\\frac{b_{2}}{2})\\mathbf{\\hat{j}_{Sys}} + (\\frac{b_{3}}{2})\\mathbf{\\hat{k}_{Sys}}$\n\n\n\n\n```python\nSR\n```\n\n\n\n\n$\\displaystyle (\\frac{b_{1}}{2})\\mathbf{\\hat{i}_{Sys}} + (\\frac{b_{2}}{2})\\mathbf{\\hat{j}_{Sys}} + (\\frac{b_{3}}{2})\\mathbf{\\hat{k}_{Sys}}$\n\n\n\n\n```python\n# Compute cross product\nPQ.cross(SR)\n```\n\n\n\n\n$\\displaystyle \\mathbf{\\hat{0}}$\n\n\n\n\n```python\n# Since the cross product is a zero vector, the two vectors have to be parallel, thus proving that PQ || SR.\n```\n", "meta": {"hexsha": "c0b747cfd94e3a22218a82100ced3ba43c0be594", "size": 9707, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Personal_Projects/vector math calculus 1.ipynb", "max_stars_repo_name": "NSC9/Sample_of_Work", "max_stars_repo_head_hexsha": "8f8160fbf0aa4fd514d4a5046668a194997aade6", "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": "Personal_Projects/vector math calculus 1.ipynb", "max_issues_repo_name": "NSC9/Sample_of_Work", "max_issues_repo_head_hexsha": "8f8160fbf0aa4fd514d4a5046668a194997aade6", "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": "Personal_Projects/vector math calculus 1.ipynb", "max_forks_repo_name": "NSC9/Sample_of_Work", "max_forks_repo_head_hexsha": "8f8160fbf0aa4fd514d4a5046668a194997aade6", "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.5126262626, "max_line_length": 420, "alphanum_fraction": 0.478932729, "converted": true, "num_tokens": 1583, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9653811591688146, "lm_q2_score": 0.8887587883361618, "lm_q1q2_score": 0.857990989305435}} {"text": "# Exercise 2: Sinusoids and the DFT\n\nDoing this exercise you will get a better understanding of the basics elements and operations that take place in the Discrete Fourier Transform (DFT). There are five parts: 1) Generate a sinusoid, 2) Generate a complex sinusoid, 3) Implement the DFT, 4) Implement the IDFT, and 5) Compute the magnitude spectrum of an input sequence.\n\n### Relevant Concepts\n\nA real sinusoid in discrete time domain can be expressed by:\n\n\\begin{equation}\nx[n] = A\\cos(2 \\pi fnT + \\varphi)\n\\end{equation}\n\nwhere, $x$ is the array of real values of the sinusoid, $n$ is an integer value expressing the time index, $A$ is the amplitude value of the sinusoid, $f$ is the frequency value of the sinusoid in Hz, $T$ is the sampling period equal to $1/fs$, fs is the sampling frequency in Hz, and $\\varphi$ is the initial phase of the sinusoid in radians.\n\nA complex sinusoid in discrete time domain can be expressed by:\n\n\\begin{equation}\n\\bar{x}[n] = Ae^{j(\\omega nT + \\varphi)} = A\\cos(\\omega nT + \\varphi)+ j A\\sin(\\omega nT + \\varphi)\n\\end{equation}\n\nwhere, $\\bar{x}$ is the array of complex values of the sinusoid, $n$ is an integer value expressing the time index, $A$ is the amplitude value of the sinusoid, $e$ is the complex exponential number, $\\omega$ is the frequency of the sinusoid in radians per second (equal to $2 \\pi f$), $T$ is the sampling period equal $1/fs$, fs is the sampling frequency in Hz and $\\varphi$ is the initial phase of the sinusoid in radians.\n\nThe $N$ point DFT of a sequence of real values $x$ (a sound) can be expressed by:\n\n\\begin{equation}\nX[k] = \\sum_{n=0}^{N-1} x[n]e^{-j2 \\pi kn/N} \\hspace{1cm} k=0,...,N-1\n\\end{equation}\n\nwhere $n$ is an integer value expressing the discrete time index, $k$ is an integer value expressing the discrete frequency index, and $N$ is the length of the DFT.\n\nThe IDFT of a spectrum $X$ of length $N$ can be expressed by:\n\n\\begin{equation}\nx[n] = \\frac{1}{N} \\sum_{k=0}^{N-1} X[k]e^{j2 \\pi kn/N} \\hspace{1cm} n=0,...,N-1\n\\end{equation}\n\nwhere, $n$ is an integer value expressing the discrete time index, $k$ is an integer value expressing the discrete frequency index, and $N$ is the length of the spectrum $X$.\n\nThe magnitude of a complex spectrum $X$ is obtained by taking its absolute value: $|X[k]| $\n\n\n## Part 1 - Generate a sinusoid\n\nComplete the function `gen_sine` to generate a real sinusoid (use `np.cos()`) given its amplitude `A`, frequency `f` (Hz), initial phase `phi` (radians), sampling rate `fs` (Hz) and duration `t` (seconds). \n\nAll the input arguments to this function `(A, f, phi, fs and t)` are real numbers such that `A`, `t` and `fs` are positive, and `fs > 2*f` to avoid aliasing. The function should return a numpy array `x` of the generated sinusoid. \n\nUse the function `cos` of the numpy package to compute the sinusoidal values.\n\n\n```python\nimport numpy as np\n```\n\n\n```python\ndef gen_sine(A, f, phi, fs, t):\n \"\"\"\n Inputs:\n A (float) = amplitude of the sinusoid\n f (float) = frequency of the sinusoid in Hz\n phi (float) = initial phase of the sinusoid in radians\n fs (float) = sampling frequency of the sinusoid in Hz\n t (float) = duration of the sinusoid (is second)\n Output:\n x (numpy array) = generated sinusoid\n \"\"\"\n ### your code here\n\n \n```\n\nNow call and test the `gen_sine()` function. If you use `A=1.0, f = 10.0, phi = 1.0, fs = 50` and `t = 0.1`, the output numpy array should be:\n\n```\narray([ 0.54030231, -0.63332387, -0.93171798, 0.05749049, 0.96724906])\n```\n\nTo generate a sinewave that you can hear, it should be longer and with a higher sampling rate. For example you can use `A=1.0, f = 440.0, phi = 1.0, fs = 5000` and `t = 0.5`. To play it import the `Ipython.display` package and use `ipd.display(ipd.Audio(data=x, rate=fs))`.\n\n\n```python\nimport IPython.display as ipd\n\n### your code here\n\n```\n\n## Part 2 - Generate a complex sinusoid \n\nComplete the `gen_complex_sine()` function to generate the complex sinusoid that is used in DFT computation of length `N` (samples), corresponding to the frequency index `k`. Note that the complex sinusoid used in DFT computation has a negative sign in the exponential function.\n\nThe amplitude of such a complex sinusoid is `1`, the length is `N`, and the frequency in radians is `2*pi*k/N`.\n\nThe input arguments to the function are two positive integers, `k` and `N`, such that `k < N-1`. The function should return `c_sine`, a numpy array of the complex sinusoid. Use the function `exp()` of the numpy package to compute the complex sinusoidal values.\n\n\n```python\ndef gen_complex_sine(k, N):\n \"\"\"\n Inputs:\n k (integer) = frequency index of the complex sinusoid of the DFT\n N (integer) = length of complex sinusoid in samples\n Output:\n c_sine (numpy array) = generated complex sinusoid (length N)\n \"\"\"\n ### your code here\n\n```\n\nNow run an test the `gen_complex_sine()` function. If you run it using `k=1` and `N=5`, the function should return the following numpy array:\n\n```\narray([ 1.0 + 0.j, 0.30901699 - 0.95105652j, -0.80901699 - 0.58778525j, -0.80901699 + 0.58778525j, 0.30901699 + 0.95105652j])\n```\n\n\n```python\n# call gen_complex_sine\n### your code here\n\n```\n\n## Part 3 - Implement the discrete Fourier transform (DFT)\n\nComplete the function `dft()` to implement the discrete Fourier transform (DFT) equation given above. Given a sequence `x` of length `N`, the function should return its spectrum of length `N` with the frequency indexes ranging from 0 to `N-1`.\n\nThe input argument to the function is a numpy array `x` and the function should return a numpy array `X`, the DFT of `x`.\n\n\n```python\ndef dft(x):\n \"\"\"\n Input:\n x (numpy array) = input sequence of length N\n Output:\n X (numpy array) = N point DFT of the input sequence x\n \"\"\"\n ## Your code here\n\n```\n\nNow run and test the function `dft()`. If you run it using as input `x = np.array([1, 2, 3, 4])`, the function shoulds return the following numpy array:\n\n```\narray([10.0 + 0.0j, -2. +2.0j, -2.0 - 9.79717439e-16j, -2.0 - 2.0j])\n```\n\nNote that you might not get an exact 0 in the output because of the small numerical errors due to the limited precision of the data in your computer. Usually these errors are of the order 1e-15 depending on your machine.\n\n\n```python\n# call dft\n### your code here\n\n```\n\n## Part 4 - Implement the inverse discrete Fourier transform (IDFT)\n\nComplete the function `idft()` to implement the inverse discrete Fourier transform (IDFT) equation given above. Given a frequency spectrum `X` of length `N`, the function should return its IDFT `x`, also of length `N`. Assume that the frequency index of the input spectrum ranges from 0 to `N-1`.\n\nThe input argument to the function is a numpy array `X` of the frequency spectrum and the function should return a numpy array of the IDFT of `X`.\n\nRemember to scale the output appropriately.\n\n\n```python\ndef idft(X):\n \"\"\"\n Input:\n X (numpy array) = frequency spectrum (length N)\n Output:\n x (numpy array) = N point IDFT of the frequency spectrum X\n \"\"\"\n ### Your code here\n\n```\n\nNow run and test the `idft()` function. If you run it with the input `X = np.array([1 ,1 ,1 ,1])`, the function should return the following numpy array: \n\n```\narray([ 1.00000000e+00 +0.00000000e+00j, -4.59242550e-17 +5.55111512e-17j, 0.00000000e+00 +6.12323400e-17j, 8.22616137e-17 +8.32667268e-17j])\n```\n\nNotice that the output numpy array is essentially `[1, 0, 0, 0]`. Instead of exact 0 we get very small numerical values of the order of 1e-15, which can be ignored. Also, these small numerical errors are machine dependent and might be different in your case.\n\nIn addition, an interesting test of the IDFT function can be done by providing the output of the DFT of a sequence as the input to the IDFT. See if you get back the original time domain sequence.\n\n\n```python\n# call idft\n### your code here\n\n```\n\n## Part 5 - Compute the magnitude spectrum\n\nComplete the function `gen_mag_spectrum()` to compute the magnitude spectrum of an input sequence `x` of length `N`. The function should return an `N` point magnitude spectrum with frequency index ranging from 0 to `N-1`.\n\nThe input argument to the function is a numpy array `x` and the function should return a numpy array of the magnitude spectrum of `x`.\n\n\n```python\ndef gen_mag_spec(x):\n \"\"\"\n Input:\n x (numpy array) = input sequence of length N\n Output:\n magX (numpy array) = magnitude spectrum of the input sequence x (length N)\n \"\"\"\n ### Your code here\n\n```\n\nNow run and test the function `gen_mag_spec()`. If you run `gen_mag_spec()` using as input `x = np.array([1, 2, 3, 4])`, it should return the following numpy array:\n```\narray([10.0, 2.82842712, 2.0, 2.82842712])\n```\nFor a more realistic use of `gen_mag_spec()` use as input a longer signal, such as `x = np.cos(2*np.pi*200.0*np.arange(512)/1000)`, and to get a visual representation of the input and output, import the `matplotlib.pyplot` package and use `plt.plot(x)` and `plt.plot(abs(X))`.\n\n\n```python\nimport IPython.display as ipd\nimport matplotlib.pyplot as plt\n```\n\n\n```python\n# call gen_mag_spec and plot result\n### your code here\n\n\n```\n", "meta": {"hexsha": "7a5bd2850ef299f1eb2c7ff4f878140aac8e4984", "size": 13229, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "stanford/sms-tools/notebooks/E2-Sinusoids-and-DFT.ipynb", "max_stars_repo_name": "phunc20/dsp", "max_stars_repo_head_hexsha": "e7c496eb5fd4b8694eab0fc049cf98a5e3dfd886", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-03-12T18:32:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-12T18:32:06.000Z", "max_issues_repo_path": "stanford/sms-tools/notebooks/E2-Sinusoids-and-DFT.ipynb", "max_issues_repo_name": "phunc20/dsp", "max_issues_repo_head_hexsha": "e7c496eb5fd4b8694eab0fc049cf98a5e3dfd886", "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": "stanford/sms-tools/notebooks/E2-Sinusoids-and-DFT.ipynb", "max_forks_repo_name": "phunc20/dsp", "max_forks_repo_head_hexsha": "e7c496eb5fd4b8694eab0fc049cf98a5e3dfd886", "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.4759206799, "max_line_length": 436, "alphanum_fraction": 0.5853806032, "converted": true, "num_tokens": 2642, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088005554475, "lm_q2_score": 0.9241418178895029, "lm_q1q2_score": 0.8579813966899241}} {"text": "\n\n\n```\nimport numpy as np\nimport matplotlib.pyplot as plt\n```\n\n# Lecture 1: The Geometry of Linear Equations\n\n$$\n\\begin{align}\n2x -y & = 0 \\\\\n-x +2y & = 3\n\\end{align}\n$$\nを行列で表すと\n$$\n\\left[\n \\begin{array}{cc}\n 2 & -1 \\\\\n -1 & 2\n \\end{array}\n\\right]\n\\left[\n \\begin{array}{c}\n x \\\\\n y\n \\end{array}\n\\right] =\n\\left[\n \\begin{array}{r}\n 0\\\\\n 3\n \\end{array}\n\\right]\n$$\n\n## Row Picture\n行ごとに見ていく方法(方程式をそのままプロットするイメージ)\n\n\n```\nxs = np.linspace(-5, 5, 100)\nys1 = [2 * x for x in xs]\nys2 = [(3+x)/2 for x in xs]\nfig, ax = plt.subplots()\nax.plot(xs, ys1, color='blue')\nax.plot(xs, ys2, color='red')\nax.hlines(2, -5, 5, linestyles='dotted')\nax.vlines(1, -5, 5, linestyles='dotted')\nax.annotate('[1, 2]', [1, 2])\nax.axis([-5, 5, -5, 5])\nplt.show()\n```\n\n2本の線の交点が答え→$x=1, y=2$\n\n## Column Picture\n列ごとに見ていく方法(一つの列を一つのベクトルをみなす)\n$$\n\\left[\n \\begin{array}{c}\n 2 \\\\\n -1\n \\end{array}\n\\right]\nx+\n\\left[\n \\begin{array}{c}\n -1\\\\\n 2\n \\end{array}\n\\right]\ny=\n\\left[\n \\begin{array}{r}\n 0\\\\\n 3\n \\end{array}\n\\right]\n$$\n\n\n```\nfig, ax = plt.subplots()\nax.quiver(0, 0, 2, -1, angles='xy', scale_units='xy', scale=1, color='blue')\nax.annotate('[2, -1]', [2, -1], color='blue')\nax.quiver(0, 0, -1, 2, angles='xy', scale_units='xy', scale=1, color='red')\nax.annotate('[-1, 2]', [-1, 2], color='red')\nax.quiver(0, 0, 0, 3, angles='xy', scale_units='xy', scale=1, color='green')\nax.annotate('[0, 3]', [0, 3], color='green')\nax.axis([-4, 4, -4, 4])\nplt.show()\n```\n\n青のベクトル1個分と赤のベクトル2個分を足すと緑のベクトルになる→ $x=1, y=2$\n", "meta": {"hexsha": "f6b1a850e7cb134924970a97f99b3ba271cfb0bd", "size": 29679, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "lecture01.ipynb", "max_stars_repo_name": "tnaka78/mit_ocw_1806_spring_2005", "max_stars_repo_head_hexsha": "10006fa0052c6802dbb522b1bef0a7b9ea3cfa62", "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": "lecture01.ipynb", "max_issues_repo_name": "tnaka78/mit_ocw_1806_spring_2005", "max_issues_repo_head_hexsha": "10006fa0052c6802dbb522b1bef0a7b9ea3cfa62", "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": "lecture01.ipynb", "max_forks_repo_name": "tnaka78/mit_ocw_1806_spring_2005", "max_forks_repo_head_hexsha": "10006fa0052c6802dbb522b1bef0a7b9ea3cfa62", "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": 129.6026200873, "max_line_length": 14948, "alphanum_fraction": 0.8454125813, "converted": true, "num_tokens": 753, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248157222395, "lm_q2_score": 0.91367652400137, "lm_q1q2_score": 0.8579649295801228}} {"text": "# Support Vector Machine\n\n* Formulation\n\nSupport Vector Machine (SVM) is a supervised machine learning model that use classification algorithm for finding decision boundary/hyperplane to separate two-group classification problem.\n\nThe hyperplane in sample space can be described using linear equation\n\n\\begin{equation}\n\\mathbf{w}^T \\mathbf{x} + b = 0, \\tag{1}\n\\end{equation}\n\nhere, $\\mathbf{w} = (w_1, w_2, ..., w_d)$ is the normal vector of the hyperplane. Intercept $b$ denotes the distance between hyperplane and the origin point. The distance between random sample $\\mathbf{x}$ and the hyperplane is\n\n\\begin{equation}\nr = \\frac{\\left\\vert \\mathbf{w}^T \\mathbf{x} + b \\right\\rvert}{\\left\\lVert \\mathbf{w} \\right\\rVert} . \\tag{2}\n\\end{equation}\n\n\n\n\n* Large margin\n\nIf the hyperplane $(\\mathbf{w}, b)$ is capable of properly classifying the samples. then for any samples in data space, we have \n\n\\begin{equation}\n \\begin{cases}\n w_i x_i + b \\geq +1, & y_i = +1\\\\\n w_i x_i + b \\leq -1, & y_i = -1\n \\end{cases} \\tag{3}\n\\end{equation}\n\nSamples that satisfy $\\mathbf{w}^T \\mathbf{x} + b = \\pm 1$ are called support vectors. Note that only support vectors are important to form the SVM model(based on KKT condition, KKT is composed of Lagrangian multiplier condition, support vectors condition and constrains of Lagrangian function).\n\nThe distance between $\\mathbf{w}^T \\mathbf{x} + b = +1$ and $\\mathbf{w}^T \\mathbf{x} + b = -1$, namely $\\displaystyle \\gamma = \\frac{2}{\\left\\lVert \\mathbf{w} \\right\\rVert}$, are called margin.\n\nTo make sure the SVM is robust and is less likely to greatly affected by small local fluctuations, we need find the large margin / maximum margin, i.e.,\n\n\\begin{equation}\n\\underset{(\\mathbf{w}, b)}{\\max} \\frac{2}{\\left\\lVert \\mathbf{w} \\right\\rVert},\\\\\ns.t. y_i(\\mathbf{w}^T \\mathbf{x}_i + b) \\geq 1, i = 1,2, ..., m. \\tag{4}\n\\end{equation}\n\nHere, we have $m$ samples in the data space.\n\nThis is equivalent to the following\n\n\\begin{equation}\n\\underset{(\\mathbf{w}, b)}{\\min} \\frac{1}{2}\\left\\lVert \\mathbf{w} \\right\\rVert^2,\\\\\ns.t. y_i(\\mathbf{w}^T \\mathbf{x}_i + b) \\geq 1, i = 1,2, ..., m. \\tag{5}\n\\end{equation}\n\nThis is the base form of SVM. Obviously, it is a Convex Quadratic Programming (CQP) problem.\n\n* Dual problem\n\nWe need to find solutions of equatin (5) to obtain the hyperplane model $f(\\mathbf{x}) = \\mathbf{w}^T\\mathbf{x} + b$. We use Lagrangian Multiplier theorem to form the Lagrangian Function\n\n\\begin{equation}\nL(\\mathbf{w}, b, \\mathbf{\\alpha}) = \\frac{1}{2}\\left\\lVert \\mathbf{w} \\right\\rVert^2 - \\sum\\limits_{i=1}^m \\alpha_i [y_i(\\mathbf{w}^T \\mathbf{x}_i + b) - 1] . \\tag{6}\n\\end{equation}\n\nHere, we assume $\\mathbf{\\alpha_i} \\geq 0$. Set $\\displaystyle \\frac{\\partial L(\\mathbf{w}, b, \\mathbf{\\alpha})}{\\partial \\mathbf{w}} = 0$ and $\\displaystyle \\frac{\\partial L(\\mathbf{w}, b, \\mathbf{\\alpha})}{\\partial b} = 0$. equation (6) is reorganized as \n\n\\begin{equation}\n\\underset{\\mathbf{\\alpha}}{\\max} \\sum\\limits_{i=1}^m \\alpha_i - \\frac{1}{2} \\sum\\limits_{i=1}^m \\sum\\limits_{j=1}^m \\alpha_i \\alpha_j y_i y_j \\mathbf{x}_i^T \\mathbf{x}_j,\\\\\ns.t. \\sum\\limits_{i=1}^{m} \\alpha_i y_i = 0 \\quad \\text{and} \\quad \\alpha_i \\geq 0, \\quad i = 1,2, ..., m. \\tag{7}\n\\end{equation}\n\nEquation (7) is a dual problem of equation (5).\n\nOnce we found the multiplier $\\alpha$, we can estimate $\\mathbf{w}$ based on $\\displaystyle \\frac{\\partial L(\\mathbf{w}, b, \\mathbf{\\alpha})}{\\partial \\mathbf{w}} = 0$ and calculate $b$ based on large margin.\n\nThe model is then obtained\n\n\\begin{equation}\nf(\\mathbf{x}) = \\mathbf{w}^T \\mathbf{x} + b = \\sum\\limits_{i=1}^{m} \\alpha_i y_i \\mathbf{x}_i^T \\mathbf{x} + b. \\tag{8}\n\\end{equation}\n\n* Kernel trick\n\nSVM allows one to classify data that's linearly separable. If it isn't, one can use kernel trick to make it works.\n\nKernel function mapping original space to a higer dimension so that it is more easy to find a hyperplane. The hyperplane is\n\n\\begin{equation}\nf(\\mathbf{x}) = \\mathbf{w}^T \\phi(\\mathbf{x}) + b . \\tag{9}\n\\end{equation}\n\nHere $\\phi(\\mathbf{x})$ is the kernel function of feature vector.\n\nThen the SVM problem becomes\n\n\\begin{equation}\n\\underset{(\\mathbf{w}, b)}{\\min} \\frac{1}{2}\\left\\lVert \\mathbf{w} \\right\\rVert^2,\\\\\ns.t. y_i(\\mathbf{w}^T \\phi(\\mathbf{x}_i) + b) \\geq 1, i = 1,2, ..., m. \\tag{10}\n\\end{equation}\n\nThe corresponding dual problem is\n\n\\begin{equation}\n\\underset{\\mathbf{\\alpha}}{\\max} \\sum\\limits_{i=1}^m \\alpha_i - \\frac{1}{2} \\sum\\limits_{i=1}^m \\sum\\limits_{j=1}^m \\alpha_i \\alpha_j y_i y_j \\phi(\\mathbf{x}_i)^T \\phi(\\mathbf{x}_j),\\\\\ns.t. \\sum\\limits_{i=1}^{m} \\alpha_i y_i = 0 \\quad \\text{and} \\quad \\alpha_i \\geq 0, \\quad i = 1,2, ..., m. \\tag{11}\n\\end{equation}\n\nIt is expensive to find the inner product $\\phi(\\mathbf{x}_i)^T \\phi(\\mathbf{x}_j)$ directly, we define kernel function $K(\\mathbf{x}_i, \\mathbf{x}_j)$ to avoid high dimensional calculations\n\n\\begin{equation}\n\\underset{\\mathbf{\\alpha}}{\\max} \\sum\\limits_{i=1}^m \\alpha_i - \\frac{1}{2} \\sum\\limits_{i=1}^m \\sum\\limits_{j=1}^m \\alpha_i \\alpha_j y_i y_j K(\\mathbf{x}_i, \\mathbf{x}_j),\\\\\ns.t. \\sum\\limits_{i=1}^{m} \\alpha_i y_i = 0 \\quad \\text{and} \\quad \\alpha_i \\geq 0, \\quad i = 1,2, ..., m. \\tag{12}\n\\end{equation}\n\nThe model is then\n\n\\begin{equation}\nf(\\mathbf{x}) = \\mathbf{w}^T \\phi(\\mathbf{x}) + b = \\sum\\limits_{i=1}^{m}\\alpha_iy_iK(\\mathbf{x}, \\mathbf{x}_i) + b. \\tag{13}\n\\end{equation}\n\n* Soft margin\n\nDifferent from the hard margin, the soft margin allows the existence of some samples that are not satisfied with the constraints $y_i(\\mathbf{w}^T \\mathbf{x}_i + b) \\geq 1$. The optimization purpose of soft margin is to find a large margin and there are fewer samples that are not satisfied with the constraints. Therefore, the constrains of the soft margin, $y_i(\\mathbf{w}^T \\mathbf{x}_i + b) \\geq 1-\\zeta_i$, has a similar constrains but with a slack variable $\\zeta_i \\geq 0$ to represent overlap. Some samples are not satisfied with the constraints, so the loss function $l$ is supposed to consider in the optimization, this introduces the penalty constant $C$.\n\nThe objective of the optimization becomes\n\n\\begin{equation}\n\\underset{(\\mathbf{w}, b)}{\\min} \\frac{1}{2}\\left\\lVert \\mathbf{w} \\right\\rVert^2 + C \\sum\\limits_{i=1}^{m} l(y_i(\\mathbf{w}^T \\mathbf{x}_i + b) - 1),\\\\\ns.t. y_i(\\mathbf{w}^T \\phi(\\mathbf{x}_i) + b) \\geq 1 - \\zeta_i, i = 1,2, ..., m. \\tag{14}\n\\end{equation}\n\nThe corresponding dual problem is\n\n\\begin{equation}\n\\underset{\\mathbf{\\alpha}}{\\max} \\sum\\limits_{i=1}^m \\alpha_i - \\frac{1}{2} \\sum\\limits_{i=1}^m \\sum\\limits_{j=1}^m \\alpha_i \\alpha_j y_i y_j K(\\mathbf{x}_i, \\mathbf{x}_j),\\\\\ns.t. \\sum\\limits_{i=1}^{m} \\alpha_i y_i = 0 \\quad \\text{and} \\quad 0 \\leq \\alpha_i \\leq C, \\quad i = 1,2, ..., m. \\tag{15}\n\\end{equation}\n\n* Tuning parameters \n\n1. Penalty C: how much you want to avoid misclassifying each training sample. Large C (may lead to overfitting) results to a smaller margin even if the model did a better classification job, and vise versa. C is a penalty to the optimization of the margin so that the system pays more attention to loss function. However, as for regularization constant $\\lambda$, it is a penalty to the optimization of the loss function to avoid overfitting. ($\\displaystyle C=\\frac{1}{\\lambda}$)\n\n2. Margin $\\gamma$: how far the influence of a single training reaches. If large $\\gamma$ (small standard deviation $\\sigma$) is used, only samples close to the margin are considered, and vise versa. (\\displaystyle $\\gamma = \\frac{1}{2\\sigma^2}$)\n\n\n* Hand-on examples\n\n\n```python\npip install cvxopt \n```\n\n\n```python\nimport numpy as np\n\ndef linear_kernel(x1, x2):\n return np.dot(x1, x2)\n\ndef polynomial_kernel(x, y, c=1, degree=3):\n '''degree: great equal 1'''\n return (c + np.dot(x, y)) ** degree\n\ndef gaussian_kernel(x, y, sigma=2):\n '''sigma: great than 0'''\n gamma=1/2/(sigma ** 2)\n return np.exp(-np.linalg.norm(x-y)**2 *gamma)\n\ndef laplace_kernel(x, y, sigma):\n '''sigma: great than 0'''\n return np.exp(-np.linalg.norm(x-y) / sigma)\n\ndef sigmoid_kernel(beta, theta):\n '''beta: great than 0\n theta: less than 0'''\n return np.tanh(beta*np.dot(x, y) + theta)\n```\n\n\n```python\nimport cvxopt\nimport cvxopt.solvers\nimport matplotlib.pyplot as plt\nimport math as m \n\ndef train_test_split(X, Y, train_size, shuffle):\n ''' Perform tran/test datasets splitting '''\n if shuffle:\n randomize = np.arange(len(X))\n np.random.shuffle(randomize)\n X = X[randomize]\n Y = Y[randomize]\n s_id = int(len(Y) * train_size)\n X_train, X_test = X[:s_id], X[s_id:]\n Y_train, Y_test = Y[:s_id], Y[s_id:]\n return X_train, X_test, Y_train, Y_test \n \n \ndef generate_dataset_MVND_ls():\n '''generate a dataset that satisfies the multivariate normal distribution\n and the dataset is linearly sperable'''\n np.random.seed(24) # Fixing random state for reproducibility\n num_observations = 200\n X1 = np.random.multivariate_normal([0, 2], [[0.8, 0.6], [0.6, 0.8]], num_observations)\n X2 = np.random.multivariate_normal([2, 0], [[0.8, 0.6], [0.6, 0.8]], num_observations)\n X = np.vstack((X1, X2)).astype(np.float32)\n Y = np.hstack((np.ones(len(X1)),np.ones(len(X2))*-1))\n return X, Y\n\ndef generate_dataset_MVND_nls():\n '''generate a dataset that satisfies the multivariate normal distribution\n and the dataset is NOT linearly sperable'''\n np.random.seed(24) # Fixing random state for reproducibility\n num_observations = 100\n X1 = np.random.multivariate_normal([-1, 2], [[1.0,0.8], [0.8, 1.0]], num_observations)\n X1 = np.vstack((X1, np.random.multivariate_normal([4, -4], [[1.0,0.8], [0.8, 1.0]], num_observations)))\n X2 = np.random.multivariate_normal([1, -1], [[1.0,0.8], [0.8, 1.0]], num_observations)\n X2 = np.vstack((X2, np.random.multivariate_normal([-4, 4], [[1.0,0.8], [0.8, 1.0]], num_observations)))\n X = np.vstack((X1, X2)).astype(np.float32)\n Y = np.hstack((np.ones(len(X1)),np.ones(len(X2))*-1))\n return X, Y\n\ndef generate_dataset_MVND_lso():\n '''generate a dataset that satisfies the multivariate normal distribution\n and the dataset is linearly sperable but overlapping'''\n np.random.seed(24) # Fixing random state for reproducibility\n num_observations = 100\n X1 = np.random.multivariate_normal([0, 2], [[1.5, 1.0], [1.0, 1.5]], num_observations)\n X2 = np.random.multivariate_normal([2, 0], [[1.5, 1.0], [1.0, 1.5]], num_observations)\n X = np.vstack((X1, X2)).astype(np.float32)\n Y = np.hstack((np.ones(len(X1)),np.ones(len(X2))*-1))\n return X, Y\n\ndef generate_dataset_MVND_nlso2():\n '''generate a dataset that satisfies the multivariate normal distribution\n and the dataset is NOT linearly sperable but overlapping'''\n np.random.seed(24) # Fixing random state for reproducibility\n num_observations = 100\n radius1 = np.sqrt(np.array(np.random.uniform(0,1,num_observations))).reshape(-1,1)\n angle1 = 2*m.pi*np.array(np.random.uniform(0,1,num_observations)).reshape(-1,1)\n X1 = np.array(radius1*np.cos(angle1)).reshape(-1,1)\n X2 = np.array(radius1*np.sin(angle1)).reshape(-1,1)\n X_ = np.hstack((X1, X2))\n radius2 = np.sqrt(np.array(3.* np.random.uniform(0,1,num_observations) + .9)).reshape(-1,1)\n X3 = np.array(radius2*np.cos(angle1)).reshape(-1,1)\n X4 = np.array(radius2*np.sin(angle1)).reshape(-1,1)\n X_X = np.hstack((X3, X4))\n X = np.vstack((X_, X_X))\n Y = np.hstack((np.ones(len(X_)),np.ones(len(X_X))*-1))\n return X, Y\n\ndef generate_dataset_MVND_nls2():\n '''generate a dataset that satisfies the multivariate normal distribution\n and the dataset is NOT linearly sperable'''\n np.random.seed(24) # Fixing random state for reproducibility\n num_observations = 100\n radius1 = np.sqrt(np.array(np.random.uniform(0,1,num_observations))).reshape(-1,1)\n angle1 = 2*m.pi*np.array(np.random.uniform(0,1,num_observations)).reshape(-1,1)\n X1 = np.array(radius1*np.cos(angle1)).reshape(-1,1)\n X2 = np.array(radius1*np.sin(angle1)).reshape(-1,1)\n X_ = np.hstack((X1, X2))\n radius2 = np.sqrt(np.array(3.* np.random.uniform(0,1,num_observations) + 1.5)).reshape(-1,1)\n X3 = np.array(radius2*np.cos(angle1)).reshape(-1,1)\n X4 = np.array(radius2*np.sin(angle1)).reshape(-1,1)\n X_X = np.hstack((X3, X4))\n X = np.vstack((X_, X_X))\n Y = np.hstack((np.ones(len(X_)),np.ones(len(X_X))*-1))\n return X, Y\n\ndef metric_accuracy_count(Y_label, Y_pred):\n '''Evaluate the accuracy'''\n correct_amount = 0 \n for i in range(np.size(Y_pred)) : #np.size: Number of elements in the array\n if Y_label[i] == Y_pred[i] : \n correct_amount = correct_amount + 1\n return correct_amount \n\n\n\ndef plot_contour(X1_train, X2_train, model):\n plt.figure(figsize = (12, 8))\n plt.scatter(X1_train[:,0], X1_train[:,1], s=50, c=\"r\", cmap=plt.cm.jet, marker = '+', label = 'Positive ')\n plt.scatter(X2_train[:,0], X2_train[:,1], s=50, c=\"b\", cmap=plt.cm.jet, marker = '_', label = 'Negative ')\n plt.scatter(clf.support_vector[:,0], clf.support_vector[:,1], s=120, facecolors='none', edgecolors='g', label = 'Support Vector')\n\n X1, X2 = np.meshgrid(np.linspace(-6,6,50), np.linspace(-6,6,50))\n X = np.array([[x1, x2] for x1, x2 in zip(np.ravel(X1), np.ravel(X2))])\n Z = clf.predict(X).reshape(X1.shape)\n plt.contour(X1, X2, Z, [0.0], colors='k', linewidths=1, origin='lower')\n plt.contour(X1, X2, Z + 1, [0.0], colors='grey', linestyles = 'dashed', linewidths=1, origin='lower')\n plt.contour(X1, X2, Z - 1, [0.0], colors='grey', linestyles = 'dashed', linewidths=1, origin='lower')\n\n plt.show()\n\n\n\n\n\nclass SVM():\n '''Suppor Vector Machine model. \n Used to find the decision boundary/hyperplane \n to separate the two-group classification problem \n ------------------------------------------------\n kernel: kernel function of kernel trick, \n designed for cases that are not linearly separable\n C: penality constant (inverse of regularization constant, 1/lambda). \n It means how much you want to avoid misclassifying each sample.\n If large C is used, then the model tries to make sure all samples\n satisfy the constrains, namely, a smaller-margin hyperplane is \n obtained even if the samples are all correctly classified, and \n vise versa.'''\n \n def __init__(self, kernel, C=None):\n self.kernel = kernel\n self.C = C\n \n def fit(self, X, y):\n # m instances, d atrributes \n self.m, self.d = X.shape \n # Kernel matrix\n K = np.zeros((self.m, self.m))\n for i in range(self.m):\n for j in range(self.m):\n K[i,j] = self.kernel(X[i], X[j])\n # The Convex Quadratic Programming parameters (https://cvxopt.org/examples/tutorial/qp.html)\n # QP Problem like: min_x 0.5*x^T P x + q^T x, s.t. G x <= h and A x = b. \n # May use list or np.array to create matrix. Note that if use list, \n # matrixs should be defined by columns instead of rows\n P = cvxopt.matrix(np.outer(y,y) * K)\n q = cvxopt.matrix(np.ones(self.m) * -1)\n A = cvxopt.matrix(y, (1, self.m))\n b = cvxopt.matrix(0.0)\n if not self.C:\n G = cvxopt.matrix(np.diag(np.ones(self.m) * -1))\n h = cvxopt.matrix(np.zeros(self.m))\n else:\n G1 = np.diag(np.ones(self.m) * -1)\n G2 = np.identity(self.m)\n G = cvxopt.matrix(np.vstack((G1, G2)))\n h1 = np.zeros(self.m)\n h2 = np.ones(self.m) * self.C\n h = cvxopt.matrix(np.hstack((h1, h2)))\n\n # Construct the QP\n sol = cvxopt.solvers.qp(P, q, G, h, A, b)\n # Lagrange multipliers\n l_m = np.ravel(sol['x'])\n\n # The model, in its formation, is: f(x) = w^T x + b = (sum_i^m l_m_i y_i K(x_i^T, x) + b \n # if l_m_i = 0, it will not exist in the above summation, and will have no influence on f(x),\n # only consider cases that have l_m_i > 0. Based on KKT condition, if l_m_i > 0, y_if(x_i) = 1.\n # That means these samples are right on the large margins and they are support vectors. \n # Only the support vectors are important in training the model f(x).\n support_vector_id = l_m > 1e-6\n new_id = np.arange(len(l_m))[support_vector_id]\n store_id = [i for i in range(len(l_m)) if support_vector_id[i]==True]\n store_id = np.array(store_id)\n self.l_m = l_m[support_vector_id]\n self.support_vector = X[support_vector_id]\n self.support_vector_label = y[support_vector_id]\n \n # Estimate the hyperplane intercept\n self.b = 0\n for i in range(len(self.l_m)):\n self.b += self.support_vector_label[i] / len(self.l_m)\n self.b -= np.sum(self.l_m * self.support_vector_label * K[store_id[i],support_vector_id]) / len(self.l_m)\n \n \n def predict(self, X):\n self.y_pred = np.zeros(len(X))\n for i in range(len(X)):\n tmp = 0\n for j in range(len(self.l_m)):\n tmp = tmp + self.l_m[j] * self.support_vector_label[j] * self.kernel(X[i], self.support_vector[j])\n self.y_pred[i] = tmp + self.b\n return self.y_pred\n \n \n\n\n```\n\n\n```python\ndef main(): \n \n # Import data\n X, Y = generate_dataset_MVND_ls()\n print(X.shape, Y.shape)\n # Splitting dataset into train and test set \n X_train, X_test, Y_train, Y_test = train_test_split(X, Y, train_size=.9, shuffle=False)\n print( X_train.shape, Y_train.shape)\n print( X_test.shape, Y_test.shape)\n # Model Learning\n model = SVM(linear_kernel)\n model.fit(X_train, Y_train) \n # Model Working\n Y_pred = model.predict(X_test) \n Y_pred = np.sign(Y_pred)\n #Statistics\n #print( 'Accuracy count: ', metric_accuracy_count(Y_test, Y_pred), ' out of ', len(Y_test), ' are correct!' ) \n #Visulaization\n plt.figure(figsize = (12, 8))\n c1 = np.ma.masked_where(Y == -1, Y)\n c2 = np.ma.masked_where(Y == 1, Y)\n plt.scatter(X[:,0], X[:,1], s=50, c=c1, cmap=\"RdBu_r\", marker = '+', label = 'Positive ')\n plt.scatter(X[:,0], X[:,1], s=50, c=c2, cmap=\"RdBu_r\", marker = '_', label = 'Negative ')\n plt.scatter(model.support_vector[:,0], model.support_vector[:,1], s=120, facecolors='none', edgecolors='c', label = 'Support Vectors') \n X1, X2 = np.meshgrid(np.linspace(-3,5,10), np.linspace(-3,5,10))\n X = np.array([[x1, x2] for x1, x2 in zip(np.ravel(X1), np.ravel(X2))])\n Y = model.predict(X).reshape(X1.shape)\n plt.contour(X1, X2, Y, [0], colors='k', linewidths=3) # W^t X = 0\n plt.contour(X1, X2, Y - 1, [0], colors='k', linestyles = 'dashed', linewidths=1) # W^t X = 1\n plt.contour(X1, X2, Y + 1, [0], colors='k', linestyles = 'dashed', linewidths=1) # W^t X = -1\n \n plt.legend()\n plt.show()\n \nif __name__ == \"__main__\":\n main()\n```\n\n\n```python\ndef main(): \n \n # Import data\n X, Y = generate_dataset_MVND_lso()\n print(X.shape, Y.shape)\n # Splitting dataset into train and test set \n X_train, X_test, Y_train, Y_test = train_test_split(X, Y, train_size=.9, shuffle=False)\n print( X_train.shape, Y_train.shape)\n print( X_test.shape, Y_test.shape)\n # Model Learning\n model = SVM(linear_kernel, C=1000)\n model.fit(X_train, Y_train) \n # Model Working\n Y_pred = model.predict(X_test) \n Y_pred = np.sign(Y_pred)\n #Statistics\n #print( 'Accuracy count: ', metric_accuracy_count(Y_test, Y_pred), ' out of ', len(Y_test), ' are correct!' ) \n #Visulaization\n plt.figure(figsize = (12, 8))\n c1 = np.ma.masked_where(Y == -1, Y)\n c2 = np.ma.masked_where(Y == 1, Y)\n plt.scatter(X[:,0], X[:,1], s=50, c=c1, cmap=\"RdBu_r\", marker = '+', label = 'Positive ')\n plt.scatter(X[:,0], X[:,1], s=50, c=c2, cmap=\"RdBu_r\", marker = '_', label = 'Negative ')\n plt.scatter(model.support_vector[:,0], model.support_vector[:,1], s=120, facecolors='none', edgecolors='c', label = 'Support Vectors') \n X1, X2 = np.meshgrid(np.linspace(-3,5,10), np.linspace(-3,5,10))\n X = np.array([[x1, x2] for x1, x2 in zip(np.ravel(X1), np.ravel(X2))])\n Y = model.predict(X).reshape(X1.shape)\n plt.contour(X1, X2, Y, [0], colors='k', linewidths=3) # W^t X = 0\n plt.contour(X1, X2, Y - 1, [0], colors='k', linestyles = 'dashed', linewidths=1) # W^t X = 1\n plt.contour(X1, X2, Y + 1, [0], colors='k', linestyles = 'dashed', linewidths=1) # W^t X = -1\n \n plt.legend()\n plt.show()\n \nif __name__ == \"__main__\":\n main()\n\n```\n\n\n```python\ndef main(): \n \n # Import data\n X, Y = generate_dataset_MVND_nls()\n print(X.shape, Y.shape)\n # Splitting dataset into train and test set \n X_train, X_test, Y_train, Y_test = train_test_split(X, Y, train_size=.9, shuffle=False)\n print( X_train.shape, Y_train.shape)\n print( X_test.shape, Y_test.shape)\n # Model Learning\n model = SVM(polynomial_kernel)\n model.fit(X_train, Y_train) \n # Model Working\n Y_pred = model.predict(X_test) \n Y_pred = np.sign(Y_pred)\n #Statistics\n #print( 'Accuracy count: ', metric_accuracy_count(Y_test, Y_pred), ' out of ', len(Y_test), ' are correct!' ) \n #Visulaization\n plt.figure(figsize = (12, 8))\n c1 = np.ma.masked_where(Y == -1, Y)\n c2 = np.ma.masked_where(Y == 1, Y)\n plt.scatter(X[:,0], X[:,1], s=50, c=c1, cmap=\"RdBu_r\", marker = '+', label = 'Positive ')\n plt.scatter(X[:,0], X[:,1], s=50, c=c2, cmap=\"RdBu_r\", marker = '_', label = 'Negative ')\n plt.scatter(model.support_vector[:,0], model.support_vector[:,1], s=120, facecolors='none', edgecolors='c', label = 'Support Vectors') \n X1, X2 = np.meshgrid(np.linspace(-7,7,100), np.linspace(-7,7,100))\n X = np.array([[x1, x2] for x1, x2 in zip(np.ravel(X1), np.ravel(X2))])\n Y = model.predict(X).reshape(X1.shape)\n plt.contour(X1, X2, Y, [0], colors='k', linewidths=3) # W^t X = 0\n plt.contour(X1, X2, Y - 1, [0], colors='k', linestyles = 'dashed', linewidths=1) # W^t X = 1\n plt.contour(X1, X2, Y + 1, [0], colors='k', linestyles = 'dashed', linewidths=1) # W^t X = -1\n \n plt.legend()\n plt.show()\n \nif __name__ == \"__main__\":\n main()\n```\n\n\n```python\ndef main(): \n \n # Import data\n X, Y = generate_dataset_MVND_nls2()\n print(X.shape, Y.shape)\n # Splitting dataset into train and test set \n X_train, X_test, Y_train, Y_test = train_test_split(X, Y, train_size=.9, shuffle=False)\n print( X_train.shape, Y_train.shape)\n print( X_test.shape, Y_test.shape)\n # Model Learning\n model = SVM(gaussian_kernel)\n model.fit(X_train, Y_train) \n # Model Working\n Y_pred = model.predict(X_test) \n Y_pred = np.sign(Y_pred)\n #Statistics\n #print( 'Accuracy count: ', metric_accuracy_count(Y_test, Y_pred), ' out of ', len(Y_test), ' are correct!' ) \n #Visulaization\n plt.figure(figsize = (8, 8))\n c1 = np.ma.masked_where(Y == -1, Y)\n c2 = np.ma.masked_where(Y == 1, Y)\n plt.scatter(X[:,0], X[:,1], s=50, c=c1, cmap=\"RdBu_r\", marker = '+', label = 'Positive ')\n plt.scatter(X[:,0], X[:,1], s=50, c=c2, cmap=\"RdBu_r\", marker = '_', label = 'Negative ')\n plt.scatter(model.support_vector[:,0], model.support_vector[:,1], s=120, facecolors='none', edgecolors='c', label = 'Support Vectors') \n X1, X2 = np.meshgrid(np.linspace(-3,3,100), np.linspace(-3,3,100))\n X = np.array([[x1, x2] for x1, x2 in zip(np.ravel(X1), np.ravel(X2))])\n Y = model.predict(X).reshape(X1.shape)\n plt.contour(X1, X2, Y, [0], colors='k', linewidths=3) # W^t X = 0\n plt.contour(X1, X2, Y - 1, [0], colors='k', linestyles = 'dashed', linewidths=1) # W^t X = 1\n plt.contour(X1, X2, Y + 1, [0], colors='k', linestyles = 'dashed', linewidths=1) # W^t X = -1\n \n plt.legend()\n plt.show()\n \nif __name__ == \"__main__\":\n main()\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "c36fccd796a2016f6794644e2e4d9b6fdd72f738", "size": 250727, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Support Vector Machine/Support Vector Machine.ipynb", "max_stars_repo_name": "Sunnyfred/Machine-Learning-Models", "max_stars_repo_head_hexsha": "e7caeb84d367b1b941695ac64d94c0cca6345a80", "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": "Support Vector Machine/Support Vector Machine.ipynb", "max_issues_repo_name": "Sunnyfred/Machine-Learning-Models", "max_issues_repo_head_hexsha": "e7caeb84d367b1b941695ac64d94c0cca6345a80", "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": "Support Vector Machine/Support Vector Machine.ipynb", "max_forks_repo_name": "Sunnyfred/Machine-Learning-Models", "max_forks_repo_head_hexsha": "e7caeb84d367b1b941695ac64d94c0cca6345a80", "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.7183431953, "max_line_length": 76796, "alphanum_fraction": 0.9043182426, "converted": true, "num_tokens": 7726, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9603611654370414, "lm_q2_score": 0.8933094096048376, "lm_q1q2_score": 0.8578996657039772}} {"text": "# Understanding the FFT Algorithm\n\nhttps://jakevdp.github.io/blog/2013/08/28/understanding-the-fft/\n\nThe Fast Fourier Transform (FFT) is one of the most important algorithms in signal processing and data analysis. I've used it for years, but having no formal computer science background, It occurred to me this week that I've never thought to ask how the FFT computes the discrete Fourier transform so quickly. I dusted off an old algorithms book and looked into it, and enjoyed reading about the deceptively simple computational trick that JW Cooley and John Tukey outlined in their classic 1965 paper introducing the subject.\n\nThe goal of this post is to dive into the Cooley-Tukey FFT algorithm, explaining the symmetries that lead to it, and to show some straightforward Python implementations putting the theory into practice. My hope is that this exploration will give data scientists like myself a more complete picture of what's going on in the background of the algorithms we use.\n\nFor simplicity, we'll concern ourself only with the forward transform, as the inverse transform can be implemented in a very similar manner. Taking a look at the DFT expression above, we see that it is nothing more than a straightforward linear operation: a matrix-vector multiplication of$\\vec{x}$\n\n\n\nForward Discrete Fourier Transform (DFT):\n\n$$X_k = \\sum_{n=0}^{N-1} x_n \\cdot e^{-i~2\\pi~k~n~/~N}$$\n\nInverse Discrete Fourier Transform (IDFT):\n\n$$x_n = \\frac{1}{N}\\sum_{k=0}^{N-1} X_k e^{i~2\\pi~k~n~/~N}$$\n\n\n```python\nimport numpy as np\ndef DFT_slow(x):\n \"\"\"Compute the discrete Fourier Transform of the 1D array x\"\"\"\n x = np.asarray(x, dtype=float)\n N = x.shape[0]\n n = np.arange(N)\n k = n.reshape((N, 1))\n M = np.exp(-2j * np.pi * k * n / N)\n return np.dot(M, x)\n#We can double-check the result by comparing to numpy's built-in FFT function:\nx = np.random.random(1024)\nnp.allclose(DFT_slow(x), np.fft.fft(x))\n```\n\n\n\n\n True\n\n\n\nJust to confirm the sluggishness of our algorithm, we can compare the execution times of these two approaches:\n\n\n```python\n%timeit DFT_slow(x)\n%timeit np.fft.fft(x)\n```\n\n 111 ms ± 19.9 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)\n 3.89 µs ± 59.5 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)\n\n\nWe are over 1000 times slower, which is to be expected for such a simplistic implementation. But that's not the worst of it. For an input vector of length N, the FFT algorithm scales as$ O[NlogN]$, while our slow algorithm scales as $O[N2]$. That means that for $N=10^6$ elements, we'd expect the FFT to complete in somewhere around 50 ms, while our slow algorithm would take nearly 20 hours!\n\nSo how does the FFT accomplish this speedup? The answer lies in exploiting symmetry.\n\n# Symmetries in the Discrete Fourier Transform\n\nOne of the most important tools in the belt of an algorithm-builder is to exploit symmetries of a problem. If you can show analytically that one piece of a problem is simply related to another, you can compute the subresult only once and save that computational cost. Cooley and Tukey used exactly this approach in deriving the FFT.\n\nWe'll start by asking what the value of $X_{N+k}$ is. From our above expression:\n\n$$\\begin{align*}\nX_{N + k} &= \\sum_{n=0}^{N-1} x_n \\cdot e^{-i~2\\pi~(N + k)~n~/~N}\\\\\n &= \\sum_{n=0}^{N-1} x_n \\cdot e^{- i~2\\pi~n} \\cdot e^{-i~2\\pi~k~n~/~N}\\\\\n &= \\sum_{n=0}^{N-1} x_n \\cdot e^{-i~2\\pi~k~n~/~N}\n\\end{align*}$$\n\nwhere we've used the identity $exp[2π i n]=1$ which holds for any integer n.\n\nThe last line shows a nice symmetry property of the DFT:\n\n$$X_{N+k}=X_k$$\n\nBy a simple extension,\n\n$$X_{k + i \\cdot N} = X_k$$\n\nfor any integer i. As we'll see below, this symmetry can be exploited to compute the DFT much more quickly.\n\n# DFT to FFT: Exploiting Symmetry\n\nCooley and Tukey showed that it's possible to divide the DFT computation into two smaller parts. From the definition of the DFT we have:\n\n$$\\begin{align}\nX_k &= \\sum_{n=0}^{N-1} x_n \\cdot e^{-i~2\\pi~k~n~/~N} \\\\\n &= \\sum_{m=0}^{N/2 - 1} x_{2m} \\cdot e^{-i~2\\pi~k~(2m)~/~N} + \\sum_{m=0}^{N/2 - 1} x_{2m + 1} \\cdot e^{-i~2\\pi~k~(2m + 1)~/~N} \\\\\n &= \\sum_{m=0}^{N/2 - 1} x_{2m} \\cdot e^{-i~2\\pi~k~m~/~(N/2)} + e^{-i~2\\pi~k~/~N} \\sum_{m=0}^{N/2 - 1} x_{2m + 1} \\cdot e^{-i~2\\pi~k~m~/~(N/2)}\n\\end{align}$$\n\nWe've split the single Discrete Fourier transform into two terms which themselves look very similar to smaller Discrete Fourier Transforms, one on the odd-numbered values, and one on the even-numbered values. So far, however, we haven't saved any computational cycles. Each term consists of $(N/2)∗N $computations, for a total of $N^2$.\n\nThe trick comes in making use of symmetries in each of these terms. Because the range of $k$ is $0≤k 0:\n raise ValueError(\"size of x must be a power of 2\")\n elif N <= 32: # this cutoff should be optimized\n return DFT_slow(x)\n else:\n X_even = FFT(x[::2])\n X_odd = FFT(x[1::2])\n factor = np.exp(-2j * np.pi * np.arange(N) / N)\n return np.concatenate([X_even + factor[:N / 2] * X_odd,\n X_even + factor[N / 2:] * X_odd]) \n```\n\n\n```python\nx = np.random.random(1024)\nnp.allclose(FFT(x), np.fft.fft(x))\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "6d489446b1c4f127d69c0291491078a5ef663e4e", "size": 19218, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "code/fft/Understanding the FFT.ipynb", "max_stars_repo_name": "xing710/ModSimPy", "max_stars_repo_head_hexsha": "87f0f481926c40855223e2843bd728edb235c516", "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": "code/fft/Understanding the FFT.ipynb", "max_issues_repo_name": "xing710/ModSimPy", "max_issues_repo_head_hexsha": "87f0f481926c40855223e2843bd728edb235c516", "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": "code/fft/Understanding the FFT.ipynb", "max_forks_repo_name": "xing710/ModSimPy", "max_forks_repo_head_hexsha": "87f0f481926c40855223e2843bd728edb235c516", "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": 61.7942122186, "max_line_length": 1714, "alphanum_fraction": 0.6393485274, "converted": true, "num_tokens": 1818, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.930458253565792, "lm_q2_score": 0.9219218311008969, "lm_q1q2_score": 0.8578097768903176}} {"text": "# Automatic differentiation\n\n__Automatic differentiation__ is a method for evaluating the rate of change in the numerical output of a program with respect to the rate of change in its input. The power of the method is the ability of writing a program that computes a differentiable function and having the derivative immediatelly available.\n\nWe start with an example.\n\nConsider the function\n$$\nf(x) = \\cos(x)\\sin(x)\n$$\n\nWhen we want to evaluate the function numerically at a specific $x$, say $x=1$ we can implement a computer program like\n~~~\nx = 1\nf = cos(x)*sin(x)\n~~~\n\nor \n\n~~~\ndef g(x):\n return cos(x)*sin(x)\n \nx = 1\nf = g(x)\n~~~\n\nNow suppose we need the derivative as well, that is how much $f$ changes when we slightly change $x$. For this example, it is a simple exercise to calculate the derivative symbolically as \n$$\nf'(x) = \\cos(x)\\cos(x) -\\sin(x)\\sin(x) = \\cos(x)^2 - \\sin(x)^2\n$$\nand code this explicitely as\n~~~\nx = 1\ndf_dx = cos(x)*cos(x) - sin(x)*sin(x)\n~~~\n\nBut could we have calculated the derivative without coding it up explicitely, that is without symbolically evaluating it a priori by hand? For example, can we code just\n~~~\nx = my.Variable(1)\nf = my.cos(x)*my.sin(x)\ndf_dx = f.derivative()\n~~~\nor \n\n~~~\ndef g(x):\n return my.cos(x)*my.sin(x)\n\nx = my.Variable(1)\nf = g(x)\ndf_dx = f.derivative()\n~~~\n\nto get what we want, perhaps by overloading the appropriate variables, functions and operators? The answer turns out to be yes and it is a quite fascinating subject called __automatic differentiation__. Interestingly, this algorithm, known also as __backpropagation__, is in the core of todays artificial intelligence systems, programs that learn how to program themselves from input and output examples. See https://www.youtube.com/watch?v=aircAruvnKk for an introduction to a particular type of model, known as a __neural network__.\n\n\nTo symbolically evaluate the derivative, we use the chain rule. The chain rule dictates that when\n$$\nf(x) = g(h(x))\n$$\nthe derivative is given as\n$$\nf'(x) = g'(h(x)) h'(x)\n$$\n\nWe could implement this program as \n~~~\nx = 1\nh = H(x)\ng = G(h)\nf = g\n~~~\nwhere we have used capital letters for the functions -- beware that the function and its output is always denoted with the same letter in mathematical notation. To highlight the underlying mechanism of automatic differentiation, we will always assign the output of a function to a variable so we will only think of the rate of change of a variable with respect to another variable, rather than 'derivatives of functions'. To be entirely formal we write \n~~~\nx = 1\nh = H(x)\ng = G(h)\nf = identity(g)\n~~~\nand denote the identity function as $(\\cdot)$. This program can be represented also by the following directed computation graph:\n\n\n\nThe derivative is denoted by\n$$\nf'(x) = \\frac{df}{dx}\n$$\nAs we will later use multiple variables, we will already introduce the partial derivative notation, that is equivalent to the derivative for scalar functions.\n$$\nf'(x) = \\frac{\\partial f}{\\partial x}\n$$\n\nThe chain rule, using the partial derivative notation can be stated as\n\\begin{eqnarray}\n\\frac{\\partial f}{\\partial x} & = & \\frac{\\partial h}{\\partial x} \\frac{\\partial g}{\\partial h} \\frac{\\partial f}{\\partial g} \\\\\n& = & h'(x) g'(h(x)) \\cdot 1\n\\end{eqnarray}\n\nThis quantity is actually just a product of numbers, so we could have evaluated this derivative in the following order\n\\begin{eqnarray}\n\\frac{\\partial f}{\\partial x} & = & \\frac{\\partial h}{\\partial x} \\left(\\frac{\\partial g}{\\partial h} \\left(\\frac{\\partial f}{\\partial g} \\frac{\\partial f}{\\partial f} \\right) \\right) \\\\\n& =& \\frac{\\partial h}{\\partial x} \\left(\\frac{\\partial g}{\\partial h} \\frac{\\partial f}{\\partial g} \\right) \\\\\n& = &\\frac{\\partial h}{\\partial x} \\frac{\\partial f}{\\partial h} \\\\\n& = &\\frac{\\partial f}{\\partial x} \n\\end{eqnarray}\nwhere we have included $\\partial f/\\partial f = 1$ as the boundry case.\n\n\n\nSo, we could imagine calculating the derivative using the following program\n\n~~~\ndf_df = 1\ndf_dg = 1 * df_df\ndf_dh = dG(h) * df_dg \ndf_dx = dH(x) * df_dh \n~~~\n\nIf $g$ and $h$ are elementary functions, their derivatives are known in closed form and can be calculated from their input(s) only.\n\nAs an example, consider\n$$\nf(x) = \\sin(\\cos(x))\n$$\n\nThe derivative is\n$$\n\\frac{\\partial f}{\\partial x} = -\\sin(x) \\cos(\\cos(x)) \n$$\n\n~~~\ndf_df = 1\ndf_dg = 1 * df_df\ndf_dh = cos(h) * df_dg \ndf_dx = -sin(x) * df_dh \n~~~\n\nAs $h=\\cos(x)$, it can be easily verified that the derivative is calculated correctly.\n\n### Functions of two or more variables\nWhen we have functions of two or more variables the notion of a derivative changes slightly. For example, when \n$$\ng(x_1, x_2)\n$$\nwe define the partial derivatives\n\\begin{eqnarray}\n\\frac{\\partial g}{\\partial x_1} & , & \\frac{\\partial g}{\\partial x_2}\n\\end{eqnarray}\n\nThe collection of partial derivatives can be organized as a vector. This object is known as the __gradient__ and is denoted as\n\\begin{eqnarray}\n\\nabla g(x) \\equiv \\left(\\begin{array}{c} \\frac{\\partial g}{\\partial x_1} \\\\ \\frac{\\partial g}{\\partial x_2} \\end{array} \\right) \n\\end{eqnarray}\n\nWhen taking the partial derivative, we assume that all the variables are constant, apart from the one that we are taking the derivative with respect to.\n\nFor example,\n$$\ng(x_1, x_2) = \\cos(x_1)e^{3 x_2}\n$$\nWhen taking the (partial) derivative with respect to $x_1$, we assume that the second factor is a constant\n$$\n\\frac{\\partial g}{\\partial x_1} = -\\sin(x_1) e^{3 x_2}\n$$\nSimilarly, when taking the partial derivative with respect to $x_2$, we assume that the first factor is a constant\n$$\n\\frac{\\partial g}{\\partial x_2} = 3 \\cos(x_1) e^{3 x_2}\n$$\n\n\nThe chain rule for multiple variables is in a way similar to the chain rule for single variable functions but with a caveat: the derivatives over all paths between the two variables need to be added.\n\nAnother example is\n$$\nf(x) = g(h_1(x), h_2(x)) \n$$\nHere, the partial derivative is \n$$\n\\frac{\\partial g}{\\partial x} = \\frac{\\partial g}{\\partial h_1} \\frac{\\partial h_1}{\\partial x} + \\frac{\\partial g}{\\partial h_2} \\frac{\\partial h_2}{\\partial x}\n$$\nThe chain rule has a simple form\n$$\n\\frac{\\partial f}{\\partial x} = \\frac{\\partial f}{\\partial g} \\frac{\\partial g}{\\partial x} \n$$\n\n\nTo see a concrete example of a function of form $f(x) = g(h_1(x), h_2(x)) $, consider \n$$\nf(x) = \\sin(x)\\cos(x)\n$$\n\nWe define \n\\begin{align}\nh_1(x) & = c = \\cos(x) \\\\\nh_2(x) & = s = \\sin(x) \\\\\ng(c,s) & = g = c \\times s \\\\\nf & = g(c,s)\n\\end{align}\n\nthat is equivalent to the following program, written deliberately as a sequence of scalar function evaluations and binary operators only\n~~~\nx = 1\nc = cos(x)\ns = sin(x)\ng = c * s\nf = g\n~~~\n\nThis program can be represented by the following directed computation graph:\n\n\nThe function can be evaluated by traversing the variable nodes of the directed graph from the inputs to the outputs in the topological order. At each variable node, we merely evaluate the incoming function. Topological order guarantees that the inputs for the function are already calculated. \n\nIt is not obvious, but the derivatives can also be calculated easily. By the chain rule, we have \n\\begin{eqnarray}\n\\frac{\\partial f}{\\partial x} &=& \\frac{\\partial f}{\\partial g} \\frac{\\partial g}{\\partial c} \\frac{\\partial c}{\\partial x} + \\frac{\\partial f}{\\partial g} \\frac{\\partial g}{\\partial s} \\frac{\\partial s}{\\partial x} \\\\\n&=& 1 \\cdot s \\cdot (-\\sin(x)) + 1 \\cdot c \\cdot \\cos(x) \\\\\n&=& -\\sin(x) \\cdot \\sin(x) + 1 \\cdot \\cos(x) \\cdot \\cos(x) \\\\\n\\end{eqnarray}\n\nThe derivative could have been calculated numerically by the following program\n\n~~~\ndf_dx = 0, df_ds = 0, df_dc = 0, df_dg = 0 \ndf_df = 1\n\ndf_dg += df_df // df/dg = 1\ndf_dc += s * df_dg // dg/dc = s\ndf_ds += c * df_dg // dg/ds = c\ndf_dx += cos(x) * df_ds // ds/dx = cos(x)\ndf_dx += -sin(x) * df_dc // dc/dx = -sin(x)\n~~~\n\nNote that the total derivative consists of sums of several terms. Each term is the product of the derivatives along the path leading from $f$ to $x$. In the above example, there are only two paths: \n\n- $f,g,c,x$\n- $f,g,s,x$\n\n$$\n\\frac{\\partial f}{\\partial x} = \\frac{\\partial f}{\\partial g} \\frac{\\partial g}{\\partial c} \\frac{\\partial c}{\\partial x} + \\frac{\\partial f}{\\partial g} \\frac{\\partial g}{\\partial s} \\frac{\\partial s}{\\partial x}\n$$\n\nIt is not obvious in this simple example but the fact that we are propagating backwards makes us save computation by storing the intermediate variables.\n\nThis program can be represented by the following directed computation graph:\n\n\nNote that during the backward pass, if we traverse variable nodes in the reverse topological order, we only need the derivatives already computed in previous steps and values of variables that are connected to the function node that are computed during the forward pass. As an example, consider\n\n$$\n\\frac{\\partial f}{\\partial c} = \\frac{\\partial f}{\\partial g} \\frac{\\partial g}{\\partial c}\n$$\nThe first term is already available during the backward pass. The second term needs to be programmed by calculating the partial derivative of $g(s,c) = sc$ with respect to $c$. It has a simple form, namely $s$. More importantly, the numerical value is also immediately available, as it is calculated during the forward pass. For each function type, this calculation will be different but is nevertheless straightforward for all basic functions, including the binary arithmetic operators $+,-,\\times$ and $\\div$.\n\n\n\n\n\nTutorial introductions to Automatic differentiation\n\nRichard D. Neidinger,\nIntroduction to Automatic Differentiation and MATLAB Object-Oriented Programming,\nSIAM REVIEW, 2010 Society for Industrial and Applied Mathematics,\nVol. 52, No. 3, pp. 545–563\n\nBaydin, Atılım Güneş, Barak A. Pearlmutter, Alexey Andreyevich Radul, and Jeffrey Mark Siskind. 2018. “Automatic Differentiation in Machine Learning: a Survey.” Journal of Machine Learning Research (JMLR) \nhttps://arxiv.org/pdf/1502.05767.pdf\n\n\nTwo related blog posts from Ben Recht:\n\nhttp://www.argmin.net/2016/05/18/mates-of-costate/\n\nhttp://www.argmin.net/2016/05/31/mechanics-of-lagrangians/\n\n\nBack-propagation, an introduction, by Sanjeev Arora and Tengyu Ma \nhttp://www.offconvex.org/2016/12/20/backprop/\n\nA nice autodifferentiation package for python\nhttps://github.com/HIPS/autograd\n\nA good tutorial on Backpropagation by Roger Grosse\n\nhttp://www.cs.toronto.edu/~rgrosse/courses/csc321_2017/slides/lec6.pdf\n\nhttp://www.cs.toronto.edu/~rgrosse/courses/csc321_2017/readings/L06%20Backpropagation.pdf\n\n\n```python\nfrom __future__ import absolute_import\nimport autograd.numpy as np\nimport matplotlib.pyplot as plt\nfrom autograd import grad\n\n'''\nMathematically we can only take gradients of scalar-valued functions, but\nautograd's grad function also handles numpy's familiar vectorization of scalar\nfunctions, which is used in this example.\nTo be precise, grad(fun)(x) always returns the value of a vector-Jacobian\nproduct, where the Jacobian of fun is evaluated at x and the the vector is an\nall-ones vector with the same size as the output of fun. When vectorizing a\nscalar-valued function over many arguments, the Jacobian of the overall\nvector-to-vector mapping is diagonal, and so this vector-Jacobian product simply\nreturns the diagonal elements of the Jacobian, which is the gradient of the\nfunction at each input value over which the function is vectorized.\n'''\n\ndef tanh(x):\n return (1.0 - np.exp(-x)) / (1.0 + np.exp(-x))\n\nx = np.linspace(-7, 7, 200)\nplt.plot(x, tanh(x),\n x, grad(tanh)(x), # first derivative\n x, grad(grad(tanh))(x), # second derivative\n x, grad(grad(grad(tanh)))(x), # third derivative\n x, grad(grad(grad(grad(tanh))))(x), # fourth derivative\n x, grad(grad(grad(grad(grad(tanh)))))(x), # fifth derivative\n x, grad(grad(grad(grad(grad(grad(tanh))))))(x)) # sixth derivative\n\nplt.axis('off')\nplt.savefig(\"tanh.png\")\nplt.show()\n```\n", "meta": {"hexsha": "280b3b0ccb9b7d2912238753cc105bc9e5f82402", "size": 41537, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Automatic Differentiation.ipynb", "max_stars_repo_name": "atcemgil/notes", "max_stars_repo_head_hexsha": "380d310a87767d9b1fe88229588dfe00a61d2353", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 191, "max_stars_repo_stars_event_min_datetime": "2016-01-21T19:44:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T20:50:50.000Z", "max_issues_repo_path": "Automatic Differentiation.ipynb", "max_issues_repo_name": "onurboyar/notes", "max_issues_repo_head_hexsha": "2ec14820af044c2cfbc99bc989338346572a5e24", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2018-02-18T03:41:04.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-21T11:08:49.000Z", "max_forks_repo_path": "Automatic Differentiation.ipynb", "max_forks_repo_name": "onurboyar/notes", "max_forks_repo_head_hexsha": "2ec14820af044c2cfbc99bc989338346572a5e24", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 138, "max_forks_repo_forks_event_min_datetime": "2015-10-04T21:57:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-15T19:35:55.000Z", "avg_line_length": 104.8914141414, "max_line_length": 24934, "alphanum_fraction": 0.8055950117, "converted": true, "num_tokens": 3363, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.948154531885212, "lm_q2_score": 0.9046505415276079, "lm_q1q2_score": 0.8577485107218127}} {"text": "# Python - Symbolic Mathematics (`sympy`)\n\n\n```python\n%matplotlib inline\n\nimport sympy as sp\nimport numpy as np\nimport matplotlib.pyplot as plt\n```\n\n\n```python\nsp.init_printing()\n```\n\n### `sympy` treats stuff fundementally different than `numpy`\n\n\n```python\nnp.sqrt(8)\n```\n\n\n```python\nsp.sqrt(8)\n```\n\n\n```python\nnp.pi\n```\n\n\n```python\nsp.pi\n```\n\n#### Adding `.n()` to the end of a sympy expression will `evaluate` expression\n\n\n```python\nsp.pi.n()\n```\n\n\n```python\nsp.pi.n(100)\n```\n\n#### `nsimplify()` will sort-of do the reverse\n\n\n```python\nsp.nsimplify(0.125)\n```\n\n\n```python\nsp.nsimplify(4.242640687119286)\n```\n\n\n```python\nsp.nsimplify(sp.pi, tolerance=1e-2)\n```\n\n\n```python\nsp.nsimplify(sp.pi, tolerance=1e-5)\n```\n\n\n```python\nsp.nsimplify(sp.pi, tolerance=1e-6)\n```\n\n### ... to $\\infty$ and beyond\n\n\n```python\nsp.oo\n```\n\n\n```python\nsp.oo + 3\n```\n\n\n```python\n1e9 < sp.oo\n```\n\n### Primes\n\n\n```python\nlist(sp.primerange(0,100))\n```\n\n\n```python\nsp.nextprime(2018)\n```\n\n\n```python\nsp.factorint(11192018)\n```\n\n# Symbolic\n\n### You have to explicitly tell `SymPy` what symbols you want to use.\n\n\n```python\nx, y, z = sp.symbols('x y z')\na, b, c = sp.symbols('a b c')\nmu, rho = sp.symbols('mu rho')\n```\n\n### Expressions are then able use these symbols\n\n\n```python\nmy_equation = 2*x + y\n\nmy_equation\n```\n\n\n```python\nmy_equation + 3\n```\n\n\n```python\nmy_equation - x\n```\n\n\n```python\nmy_equation / x\n```\n\n\n```python\nmy_greek_equation = mu**2 / rho * (a + b)\n\nmy_greek_equation\n```\n\n### `SymPy` has all sorts of ways to manipulates symbolic equations\n\n\n```python\nsp.simplify(my_equation / x)\n```\n\n\n```python\nanother_equation = (x + 2) * (x - 3)\n\nanother_equation\n```\n\n\n```python\nsp.expand(another_equation)\n```\n\n\n```python\nlong_equation = 2*y*x**3 + 12*x**2 - x + 3 - 8*x**2 + 4*x + x**3 + 5 + 2*y*x**2 + x*y\n\nlong_equation\n```\n\n\n```python\nsp.collect(long_equation,x)\n```\n\n\n```python\nsp.collect(long_equation,y)\n```\n\n### You can evaluate equations for specific values\n\n\n```python\ntrig_equation = a*sp.sin(2*x + y) + b*sp.cos(x + 2*y)\n\ntrig_equation\n```\n\n\n```python\ntrig_equation.subs({a:2, b:3, x:4, y:5})\n```\n\n\n```python\ntrig_equation.subs({a:2, b:3, x:4, y:5}).n()\n```\n\n\n```python\nsp.expand(trig_equation, trig=True)\n```\n\n\n```python\nsp.collect(sp.expand(trig_equation, trig=True),sp.cos(x))\n```\n\n#### You can evaluate/simplify equations sybolically\n\n\n```python\nmy_equation_xyz = sp.sqrt((x * (y - 4*x)) / (z * (y - 3*x)))\n\nmy_equation_xyz\n```\n\n\n```python\nmy_equation_x = (3 * a * y) / (9 * a - y)\n\nmy_equation_x\n```\n\n\n```python\nmy_new_xyz = my_equation_xyz.subs(x, my_equation_x)\n\nmy_new_xyz\n```\n\n\n```python\nsp.simplify(my_new_xyz)\n```\n\n# System of equations\n\n$$\n\\begin{array}{c}\n9x - 2y = 5 \\\\\n-2x + 6y = 10 \\\\\n\\end{array}\n\\hspace{3cm}\n\\left[\n\\begin{array}{cc}\n9 & -2 \\\\\n-2 & 6 \\\\\n\\end{array}\n\\right]\n\\left[\n\\begin{array}{c}\nx\\\\\ny\n\\end{array}\n\\right]\n=\n\\left[\n\\begin{array}{c}\n5\\\\\n10\n\\end{array}\n\\right]\n$$\n\n\n```python\na_matrix = sp.Matrix([[9, -2],\n [-2, 6]])\n\nb_matrix = sp.Matrix([[5],\n [10]])\n```\n\n\n```python\na_matrix, b_matrix\n```\n\n\n```python\na_matrix.inv()\n```\n\n\n```python\na_matrix.inv() * a_matrix\n```\n\n\n```python\na_matrix.inv() * b_matrix\n```\n\n# Solving equations - `solve`\n\n\n```python\nyet_another_equation = x**3 + x + 10\n\nyet_another_equation\n```\n\n\n```python\nsp.solve(yet_another_equation,x)\n```\n\n#### ... complex numbers\n\n\n```python\nsp.I\n```\n\n\n```python\na_complex_number = 2 + 3 * sp.I\n\na_complex_number\n```\n\n\n```python\nsp.re(a_complex_number), sp.im(a_complex_number)\n```\n\n### ... solving more symbolically\n\n\n```python\nsymbolic_equation = a*x**2 + b*x +c\n\nsymbolic_equation\n```\n\n\n```python\nsp.solve(symbolic_equation, x)\n```\n\n## Calculus\n\n\n```python\nsymbolic_equation\n```\n\n\n```python\nsp.diff(symbolic_equation,x)\n```\n\n\n```python\nsp.diff(symbolic_equation,x,2)\n```\n\n\n```python\nsp.integrate(symbolic_equation,x)\n```\n\n\n```python\nsp.integrate(symbolic_equation,(x,0,5)) # limits x = 0 to 5\n```\n\n\n```python\nsp.integrate(symbolic_equation,(x,0,5)).subs({a:2, b:7, c:3}).n()\n```\n\n\n```python\ntrig_equation\n```\n\n\n```python\nsp.diff(trig_equation,x)\n```\n\n\n```python\nsp.integrate(trig_equation,x)\n```\n\n### Ordinary differential equation - `dsolve`\n\n\n```python\nf = sp.Function('f')\n```\n\n\n```python\nf(x)\n```\n\n\n```python\nsp.Derivative(f(x),x,x)\n```\n\n\n```python\nequation_ode = sp.Derivative(f(x), x, x) + 9*f(x)\n\nequation_ode\n```\n\n\n```python\nsp.dsolve(equation_ode, f(x))\n```\n\n### Limits\n\n\n```python\nlimit_equation = (1 + (1 / x)) ** x\n\nlimit_equation\n```\n\n$$\\lim _{x\\to 5 }\\left(1+{\\frac {1}{x}}\\right)^{x}$$\n\n\n```python\nsp.limit(limit_equation, x, 5)\n```\n\n\n```python\nsp.limit(limit_equation, x, 5).n()\n```\n\n$$\\lim _{x\\to \\infty }\\left(1+{\\frac {1}{x}}\\right)^{x}$$\n\n\n```python\nsp.limit(limit_equation, x, sp.oo)\n```\n\n\n```python\nsp.limit(limit_equation, x, sp.oo).n()\n```\n\n### Summation\n\n$$ \\sum{\\frac {x^{a}}{a!}} $$\n\n\n```python\nsum_equation = x**a / sp.factorial(a)\n\nsum_equation\n```\n\n$$ \\sum _{a=0}^{3}{\\frac {x^{a}}{a!}} $$\n\n\n```python\nsp.summation(sum_equation, [a, 0, 3])\n```\n\n\n```python\nsp.summation(sum_equation.subs({x:1}), [a, 0, 3])\n```\n\n\n```python\nsp.summation(sum_equation.subs({x:1}), [a, 0, 3]).n()\n```\n\n$$ \\sum _{a=0}^{10}{\\frac {x^{a}}{a!}} $$\n\n\n```python\nsp.summation(sum_equation.subs({x:1}), [a, 0, 10]).n()\n```\n\n$$ \\sum _{a=0}^{\\infty}{\\frac {x^{a}}{a!}} $$\n\n\n```python\nsp.summation(sum_equation, [a, 0, sp.oo])\n```\n\n## Let's do some graphing stuff ...\n\n$$\n\\large y_1 = \\frac{x^3}{4} - 3x\n$$\n\n\n```python\nmy_np_x = np.linspace(-2*np.pi,2*np.pi,200)\n```\n\n\n```python\nmy_np_y1 = my_np_x ** 3 / 4 - 3 * my_np_x\n```\n\n\n```python\nfig,ax = plt.subplots(1,1)\nfig.set_size_inches(10,4)\n\nfig.tight_layout()\n\nax.set_ylim(-7,7)\nax.set_xlim(-np.pi,np.pi)\n\nax.set_xlabel(\"This is X\")\nax.set_ylabel(\"This is Y\")\n\nax.plot(my_np_x, my_np_y1, color='r', marker='None', linestyle='-', linewidth=4);\n```\n\n### Fourier Series\n\n\n```python\nmy_sp_y1 = x ** 3 / 4 - 3 * x\n\nmy_sp_y1\n```\n\n\n```python\nmy_fourier = sp.fourier_series(my_sp_y1, (x, -sp.pi, sp.pi))\n\nmy_fourier\n```\n\n\n```python\nmy_fourier.truncate(3).n(2)\n```\n\n\n```python\nmy_np_1term = -4.1 * np.sin(my_np_x)\nmy_np_2term = -4.1 * np.sin(my_np_x) + 0.91 * np.sin(2*my_np_x)\nmy_np_3term = -4.1 * np.sin(my_np_x) + 0.91 * np.sin(2*my_np_x) - 0.47 * np.sin(3*my_np_x)\n```\n\n\n```python\nfig,ax = plt.subplots(1,1)\nfig.set_size_inches(10,4)\n\nfig.tight_layout()\n\nax.set_ylim(-7,7)\nax.set_xlim(-np.pi,np.pi)\n\nax.set_xlabel(\"This is X\")\nax.set_ylabel(\"This is Y\")\n\nax.plot(my_np_x, my_np_y1, color='r', marker='None', linestyle='-', linewidth=8)\n\nax.plot(my_np_x, my_np_1term, color='b', marker='None', linestyle='--', label=\"1-term\")\nax.plot(my_np_x, my_np_2term, color='g', marker='None', linestyle='--', label=\"2-term\")\nax.plot(my_np_x, my_np_3term, color='k', marker='None', linestyle='--', label=\"3-term\")\n\nax.legend(loc = 0);\n```\n\n### Another Function\n\n$$\n\\large y_2 = 2\\,\\sin(5x) \\ e^{-x}\n$$\n\n\n```python\nmy_np_y2 = 2 * np.sin(5 * my_np_x) * np.exp(-my_np_x)\n```\n\n\n```python\nfig,ax = plt.subplots(1,1)\nfig.set_size_inches(10,4)\n\nfig.tight_layout()\n\nax.set_ylim(-10,10)\nax.set_xlim(-np.pi,np.pi)\n\nax.set_xlabel(\"This is X\")\nax.set_ylabel(\"This is Y\")\n\nax.plot(my_np_x, my_np_y2, color='r', marker='None', linestyle='-', linewidth=4);\n```\n\n### Taylor Expansions\n\n\n```python\nmy_sp_y2 = 2 * sp.sin(5 * x) * sp.exp(-x)\nmy_sp_y2\n```\n\n\n```python\nmy_taylor = sp.series(my_sp_y2, x, x0 = 0)\n\nmy_taylor\n```\n\n\n```python\nmy_taylor.removeO()\n```\n\n\n```python\nmy_taylor.removeO().n(2)\n```\n\n## General Equation Solving - `nsolve`\n\n$$\n\\large y_1 = \\frac{x^3}{4} - 3x\\\\\n\\large y_2 = 2\\,\\sin(5x) \\ e^{-x}\n$$\n\n### Where do they cross? - The graph\n\n\n```python\nfig,ax = plt.subplots(1,1)\nfig.set_size_inches(10,4)\n\nfig.tight_layout()\n\nax.set_ylim(-5,5)\nax.set_xlim(-np.pi,4)\n\nax.set_xlabel(\"This is X\")\nax.set_ylabel(\"This is Y\")\n\nax.plot(my_np_x, my_np_y1, color='b', marker='None', linestyle='--', linewidth = 4)\nax.plot(my_np_x, my_np_y2, color='r', marker='None', linestyle='-', linewidth = 4);\n```\n\n### Where do they cross? - The `sympy` solution\n\n\n```python\nmy_sp_y1, my_sp_y2\n```\n\n\n```python\nmy_guess = 3.3\n\nsp.nsolve(my_sp_y1 - my_sp_y2, x, my_guess)\n```\n\n\n```python\nall_guesses = (3.3, 0, -0.75)\n\nfor val in all_guesses:\n result = sp.nsolve(my_sp_y1 - my_sp_y2, x, val)\n print(result)\n```\n\n### Your guess has to be (somewhat) close or the solution will not converge:\n\n\n```python\nmy_guess = -40\n\nsp.nsolve(my_sp_y1 - my_sp_y2, x, my_guess)\n```\n\n# `SymPy` can do *so* much more. It really is magic. \n\n## Complete documentation can be found [here](http://docs.sympy.org/latest/index.html)\n", "meta": {"hexsha": "6e6cc23e0bd9acb5a0530935a31ede1834c2b51d", "size": 27470, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Python_SymPy.ipynb", "max_stars_repo_name": "UWashington-Astro300/Astro300-A18", "max_stars_repo_head_hexsha": "f03b1967195aae65f46729aa285948d1e8648a0c", "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_SymPy.ipynb", "max_issues_repo_name": "UWashington-Astro300/Astro300-A18", "max_issues_repo_head_hexsha": "f03b1967195aae65f46729aa285948d1e8648a0c", "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_SymPy.ipynb", "max_forks_repo_name": "UWashington-Astro300/Astro300-A18", "max_forks_repo_head_hexsha": "f03b1967195aae65f46729aa285948d1e8648a0c", "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": 16.5881642512, "max_line_length": 98, "alphanum_fraction": 0.4685475064, "converted": true, "num_tokens": 3053, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9539660956376159, "lm_q2_score": 0.8991213738910259, "lm_q1q2_score": 0.857731306555151}} {"text": "# Final project\nThe Allen–Cahn equation (after John W. Cahn and Sam Allen) is a reaction–diffusion equation of mathematical physics which describes the process of phase separation in multi-component alloy systems, including order-disorder transitions.\n\nThe equation describes the time evolution of a scalar-valued state variable $\\eta$ on a domain $\\Omega=[0,1]$ during a time interval $[0,T]$, and is given (in one dimension) by:\n\n$$\n\\frac{\\partial \\eta}{\\partial t} - \\varepsilon^2 \\eta'' + f'(\\eta) = 0, \\qquad \\eta'(0, t) = \\eta'(1, t) = 0,\\qquad\\eta(x,0) = \\eta_0(x)\n$$\n\nwhere $f$ is a double-well potential, $\\eta_0$ is the initial condition, and $\\varepsilon$ is the characteristic width of the phase transition.\n\nThis equation is the L2 gradient flow of the Ginzburg–Landau free energy functional, and it is closely related to the Cahn–Hilliard equation.\n\nA typical example of double well potential is given by the following function\n\n$$\nf(\\eta) = \\eta^2(\\eta-1)^2\n$$\n\nwhich has two minima in $0$ and $1$ (the two wells, where its value is zero), one local maximum in $0.5$, and it is always greater or equal than zero.\n\nThe two minima above behave like \"attractors\" for the phase $\\eta$. Think of a solid-liquid phase transition (say water+ice) occupying the region $[0,1]$. When $\\eta = 0$, then the material is liquid, while when $\\eta = 1$ the material is solid (or viceversa).\n\nAny other value for $\\eta$ is *unstable*, and the equation will pull that region towards either $0$ or $1$.\n\nDiscretisation of this problem can be done by finite difference in time. For example, a fully explicity discretisation in time would lead to the following algorithm.\n\nWe split the interval $[0,T]$ in `n_steps` intervals, of dimension `dt = T/n_steps`. Given the solution at time `t[k] = k*dt`, it i possible to compute the next solution at time `t[k+1]` as\n\n$$\n\\eta_{k+1} = \\eta_{k} + \\Delta t \\varepsilon^2 \\eta_k'' - \\Delta t f'(\\eta_k)\n$$\n\nSuch a solution will not be stable. A possible remedy that improves the stability of the problem, is to treat the linear term $\\Delta t \\varepsilon^2 \\eta_k''$ implicitly, and keep the term $-f'(\\eta_k)$ explicit, that is:\n\n$$\n\\eta_{k+1} - \\Delta t \\varepsilon^2 \\eta_k'' = \\eta_{k} - \\Delta t f'(\\eta_k)\n$$\n\nGrouping together the terms on the right hand side, this problem is identical to the one we solved in the python notebook number 9, with the exception of the constant $\\Delta t \\varepsilon^2$ in front the stiffness matrix.\n\nIn particular, given a set of basis functions $v_i$, representing $\\eta = \\eta^j v_j$ (sum is implied), we can solve the problem using finite elements by computing\n\n$$\n\\big((v_i, v_j) + \\Delta t \\varepsilon^2 (v_i', v_j')\\big) \\eta^j_{k+1} = \\big((v_i, v_j) \\eta^j_{k} - \\Delta t (v_i, f'(\\eta_k)\\big)\n$$\nwhere a sum is implied over $j$ on both the left hand side and the right hand side. Let us remark that while writing this last version of the equation we moved from a forward Euler scheme to a backward Euler scheme for the second spatial derivative term: that is, we used $\\eta^j_{k+1}$ instead of $\\eta^j_{k}$. \n\nThis results in a linear system\n\n$$\nA x = b\n$$\n\nwhere \n\n$$\nA_{ij} = M_{ij}+ \\Delta t \\varepsilon^2 K_{ij} = \\big((v_i, v_j) + \\Delta t \\varepsilon^2 (v_i', v_j')\\big) \n$$\n\nand \n\n$$\nb_i = M_{ij} \\big(\\eta_k^j - \\Delta t f'(\\eta_k^j)\\big)\n$$\n\nwhere we simplified the integration on the right hand side, by computing the integral of the interpolation of $f'(\\eta)$.\n\n## Step 1\n\nWrite a finite element solver, to solve one step of the problem above, given the solution at the previous time step, using the same techniques used in notebook number 9.\n\nIn particular:\n\n1. Write a function that takes in input a vector representing $\\eta$, an returns a vector containing $f'(\\eta)$. Call this function `F`.\n\n2. Write a function that takes in input a vector of support points of dimension `ndofs` and the degree `degree` of the polynomial basis, and returns a list of basis functions (piecewise polynomial objects of type `PPoly`) of dimension `ndofs`, representing the interpolatory spline basis of degree `degree`\n\n3. Write a function that, given a piecewise polynomial object of type `PPoly` and a number `n_gauss_quadrature_points`, computes the vector of global_quadrature_points and global_quadrature_weights, that contains replicas of a Gauss quadrature formula with `n_gauss_quadrature_points` on each of the intervals defined by `unique(PPoly.x)`\n\n4. Write a function that, given the basis and the quadrature points and weights, returns the two matrices $M$ and $K$ \n\n## Step 2\n\nSolve the Allen-Cahan equation on the interval $[0,1]$, from time $t=0$ and time $t=1$, given a time step `dt`, a number of degrees of freedom `ndofs`, and a polynomial degree `k`.\n\n1. Write a function that takes the initial value of $\\eta_0$ as a function, eps, dt, ndofs, and degree, and returns a matrix of dimension `(int(T/dt), ndofs)` containing all the coefficients $\\eta_k^i$ representing the solution, and the set of basis functions used to compute the solution\n\n2. Write a function that takes all the solutions `eta`, the basis functions, a stride number `s`, and a resolution `res`, and plots on a single plot the solutions $\\eta_0$, $\\eta_s$, $\\eta_{2s}$, computed on `res` equispaced points between zero and one\n\n## Step 3\n\nSolve the problem for all combinations of\n\n1. eps = [01, .001]\n\n2. ndofs = [16, 32, 64, 128]\n\n3. degree = [1, 2, 3]\n\n3. dt = [.25, .125, .0625, .03125, .015625]\n\nwith $\\eta_0 = \\sin(2 \\pi x)+1$.\n\nPlot the final solution at $t=1$ in all cases. What do you observe? What happens when you increase ndofs and keep dt constant? \n\n## Step 4 (Optional)\n\nInstead of solving the problem explicitly, solve it implicitly, by using backward euler method also for the non linear term. This requires the solution of a Nonlinear problem at every step. Use scipy and numpy methods to solve the non linear iteration.\n\n# Project implementation\nFirst we import the needed python libraries\n\n\n```python\n%pylab inline\nimport sympy as sym\nimport scipy\nfrom scipy.interpolate import *\nfrom scipy.integrate import *\n\n%matplotlib inline\nfrom matplotlib import cm\nimport matplotlib.pyplot\nfrom IPython.display import Image\nfrom IPython.display import display, clear_output\nimport time\n```\n\n Populating the interactive namespace from numpy and matplotlib\n\n\n*The Allen–Cahn equation $\n\\frac{\\partial \\eta}{\\partial t} - \\varepsilon^2 \\eta'' + f'(\\eta) = 0\n$ is a reaction–diffusion equation which describes the process of phase separation in multi-component alloy systems, including order-disorder transitions.*\n\n*The equation describes the time evolution of a scalar-valued state variable $\\eta$ on a domain $\\Omega=[0,1]$ during a time interval $[0,T]$. *\n\n*The double well potential is given by the following function*\n$$\nf(\\eta) = \\eta^2(\\eta-1)^2\n$$\nBefore to start, let's represent graphically this function over it's interval of definition\n\n\n```python\ndef f(eta): # This is the double well potential function\n return eta**2*(eta-1)**2\n```\n\nTo represent f over it's whole interval of definition, we split the interval $\\Omega=[0,1]$ in `n_space` intervals, of dimension `dl = T/n_space`.\n\n\n```python\nn_space=500\nOmega=linspace(0,1,n_space)\ndl=1/n_space\n```\n\n\n```python\n_ = plot(Omega,f(Omega))\n_ = plt.ylabel(r\"$f ( \\eta )$\", fontsize = 12)\n_ = plt.xlabel(r\"$\\eta \\in \\Omega$\", fontsize = 12)\n```\n\nAs announced, $f$ \"*has two minima in $0$ and $1$ (the two wells, where its value is zero), one local maximum in $0.5$, and it is always greater or equal than zero.*\"\n\nIn preparation of the exercise to be done, we define and split the interval $[0,T]$ in `n_steps` intervals, of dimension `dt = T/n_steps`. \n\n\n```python\nT=1\nn_steps=100\ndt=T/n_steps\nTime=linspace(0,T,n_steps)\n```\n\n## Step 1\n\n*Write a finite element solver, to solve one step of the problem above, given the solution at the previous time step*\n#### 1.1 Double potential derivative\n*Write a function that takes in input a vector representing $\\eta$, an returns a vector containing $f'(\\eta)$. Call this function `F`.*\n\nGiven the definition of the double well potential $\nf(\\eta) = \\eta^2(\\eta-1)^2\n$, it's derivative is the following function:\n$$\nf'(\\eta) = F(\\eta)= \\frac{d(\\eta^2)} {d \\eta} \\times(\\eta-1)^2+ \\eta^2\\times\\frac{d (\\eta-1)^2}{d\\eta}\\\\\n=2\\eta\\times(\\eta-1)^2 + \\eta^2\\times2(\\eta-1)\n$$\n\n\n```python\ndef F(eta): # derivative of the double well potential function\n return 2*eta*(eta-1)**2+eta**2*2*(eta-1)\n_ = plot(Omega,F(Omega))\n_ = plt.ylabel(r\"$F(\\eta) = f'(\\eta) $\", fontsize = 12)\n_ = plt.xlabel(r\"$\\eta \\in \\Omega$\", fontsize = 12)\n```\n\n#### 1.2. Basis functions\n*Write a function that takes in input a vector of support points of dimension `ndofs` and the degree `degree` of the polynomial basis, and returns a list of basis functions (piecewise polynomial objects of type `PPoly`) of dimension `ndofs`, representing the interpolatory spline basis of degree `degree`.*\n\n\n```python\ndef compute_basis_functions(support_points, degree):\n # Insert here what was in notebook 9\n basis = []\n dbasis = []\n for i in range(len(support_points)):\n c = support_points*0 # c has same shape as support_points but is null\n c[i] = 1 # c is null everywhere except in one of the support_points\n bi = PPoly.from_spline(splrep(support_points,c,k=degree))\n basis.append(bi)# append base basis function to basis matrix\n return basis\n```\n\n*The basis functions are constructed from the spline interpolation by computing the piecewise interpolation of a function that has value one in one of the `support_points` and zero in all other support points.*\n\nThere are as many basis functions as support points, that is, `ndofs`. They define a basis for a piecewise polynomial space of dimension `ndofs`.\n\n\n```python\nndofs=16\ndegree=2\n```\n\nLets visualize this basis functions and use them to plot a piecewise polynomial interpolation of $f$ in $\\Omega$\n\n\n```python\nsupport_points=linspace(0,1,ndofs)\nBasisFunctions=compute_basis_functions(support_points,degree)\nOmegaBasisMat=zeros((n_space,ndofs))\nfor i in range(len(support_points)):\n OmegaBasisMat[:,i]=BasisFunctions[i](Omega)\n \n\nfig, ax = plt.subplots(nrows=1, ncols=2,figsize=(10,4))\n\nylim(-0.01,max(f(Omega)))\nfor i in range(ndofs):\n BasisFunc=BasisFunctions[i]\n ax[0].plot(Omega,BasisFunc(Omega),color=cm.gist_rainbow(i/ndofs)) # plot this basis function\n ax[1].plot(Omega,OmegaBasisMat[:,i:i+1].dot(f(support_points[i:i+1])),color=cm.gist_rainbow(i/ndofs)) # plot this basis function\n ax[1].scatter(support_points[i],f(support_points)[i:i+1],color=cm.gist_rainbow(i/ndofs))\n ax[1].plot(support_points[:i+1],f(support_points)[:i+1],'k',dashes=[2,2,2,2]) \n clear_output() \n display(fig)\n time.sleep(2.0/float(ndofs))\nclear_output() \ndisplay(fig)\ntime.sleep(0.5)\n_ = ax[1].plot(Omega,f(Omega),'k',alpha=0.8)\nclear_output() \ndisplay(fig)\nclear_output() \n```\n\n.\n\n.\n\n.\n\n.\n\n.\n\n.\n\n.\n\n#### 1.3. Global quadrature\n*Write a function that, given a piecewise polynomial object of type `PPoly` and a number `n_gauss_quadrature_points`, computes the vector of global_quadrature_points and global_quadrature_weights, that contains replicas of a Gauss quadrature formula with `n_gauss_quadrature_points` on each of the intervals defined by `unique(PPoly.x)`*\n\n Gauss quadrature uses the function values evaluated at the `n_gauss_quadrature_points` and corresponding weights to approximate the integral by a weighted sum. Gauss quadrature deals with integration for $x \\in [-1,1]$, consequently we have to rescale the points and weights to work from zero to one. \n\n\n```python\n# Step 1.3\n\ndef compute_global_quadrature(basis, n_gauss_quadrature_points):\n # Create a Gauss quadrature formula with n_gauss_quadrature_points, \n # extract the intervals from basis (i.e., unique(basis.x)), and \n # create len(x)-1 shifted \n # and scaled Gauss quadrature formulas \n # that can be used to integrate on each interval. \n # Put all of these \n # together, and return the result\n \n\n # The intervals are stored as `x` (with some repeated entries)\n # in the `PPoly` object. Thats why we use unique() to make sure\n # that every interval border is taken only once\n intervals = unique(basis[0].x) \n\n # and make sure we can integrate exactly the product \n # of two basis functions\n qp, w = numpy.polynomial.legendre.leggauss(n_gauss_quadrature_points)\n \n # Rescale the points and weights to work from zero to one\n qp = (qp+1)/2\n w /= 2\n \n # Now replicate these points and weights in all the intervals\n h = diff(intervals) # 1st order discrete difference \n Q = array([intervals[i]+h[i]*qp for i in range(len(h))]).reshape((-1,))\n W = array([w*h[i] for i in range(len(h))]).reshape((-1,))\n \n # return global_quadrature, global_weights\n return Q,W\n```\n\n\n```python\nQ,W= compute_global_quadrature(BasisFunctions,degree +1)\nplot(Q,W,'k',dashes=[2,2,2,2],alpha=0.3)\nplot(Q,W,'xk')\nxlabel(\"global quadrature points\")\nylabel(\"global weights\")\n```\n\n#### 1.4 Compute M and K\n*Write a function that, given the basis and the quadrature points and weights, returns the two matrices $M$ and $K$ *\n\n\n```python\n# Step 1.4\n\ndef compute_system_matrices(basis, global_quadrature, global_weights):\n # Compute the matrices M_ij = (v_i, v_j) and K_ij = (v_i', v_j') and return them\n \n #compute the 1st derivative of the basis functions\n dbasis = []\n nB=len(basis)\n for i in range(nB):\n dbasis.append( basis[i].derivative(1) )\n\n Bq = array([basis[i](global_quadrature) for i in range(nB)]).T\n dBq = array([dbasis[i](global_quadrature) for i in range(nB)]).T\n M = einsum('qi, q, qj', Bq, global_weights, Bq)\n K = einsum('qi, q, qj', dBq, global_weights, dBq)\n # return M, Kn-th order discrete difference \n return M,K\n```\n\n\n```python\nM,K=compute_system_matrices(BasisFunctions, Q,W)\nshape(support_points)\nfig,ax=plt.subplots(nrows=1,ncols=2,figsize=(10,4))\nax[0].imshow(M,cm.jet,vmin=0,vmax=0.02)\nax[0].set_title(\"M matrix\")\nax[1].imshow(K,cm.jet,vmin=0,vmax=2)\nax[1].set_title(\"K matrix\")\n```\n\n## Step 2\n\nSolve the Allen-Cahan equation on the interval $[0,1]$, from time $t=0$ and time $t=1$, given a time step `dt`, a number of degrees of freedom `ndofs`, and a polynomial degree `k`.\n\n1. Write a function that takes the initial value of $\\eta_0$ as a function, eps, dt, ndofs, and degree, and returns a matrix of dimension `(int(T/dt), ndofs)` containing all the coefficients $\\eta_k^i$ representing the solution, and the set of basis functions used to compute the solution\n\n\n\n```python\n# Step 2.1\n\ndef solve_allen_cahan(eta_0_function, eps, dt, ndofs, degree):\n # put together all the above functions, loop over time, and produce \n # the result matrix eta, containing the solution at all points\n support_points=linspace(0,1,ndofs)\n \n basis=compute_basis_functions(support_points, degree)\n Q,W= compute_global_quadrature(basis,degree +1)\n M,K=compute_system_matrices(basis, Q,W)\n \n #A_{ij} = M_{ij}+ \\Delta t \\varepsilon^2 K_{ij}\n A = M + dt * eps**2 * K\n \n ntime=int(1.0/dt)\n \n eta=zeros((ntime, ndofs),dtype=float)\n # store initial values in eta\n eta[0,:]=eta_0_function(support_points)\n \n for k in range(ntime-1):\n # b_i = M_{ij} (eta_k^j - Delta_t f'(eta_k^j) )\n b = M.dot( eta[k] - dt *F(eta[k]) )\n # A.eta_k+1 = b\n eta[k+1,:]=np.linalg.solve(A,b)\n \n return eta, basis\n```\n\n#### 2.2. plot the solutions $\\eta_0$, $\\eta_s$, $\\eta_{2s}$\nWrite a function that takes all the solutions `eta`, the basis functions, a stride number `s`, and a resolution `res`, and plots on a single plot the solutions $\\eta_0$, $\\eta_s$, $\\eta_{2s}$, computed on `res` equispaced points between zero and one\n\n\n\n```python\n# Step 2.2 \n\ndef plot_solution(eta, basis, stride, resolution):\n x = linspace(0,1,resolution)\n BasisMatrix=np.zeros((resolution,len(basis)))\n for i in range(len(basis)):\n BasisMatrix[:,i]=basis[i](x)\n\n fig,ax=plt.subplots(figsize=(8,4))\n for k in range(0,len(eta)):#,stride):\n label=\"t=\"+str(k/len(eta))\n if( (k/len(eta))%0.1!=0):label=''\n ax.plot(x , eta[k,:].dot(BasisMatrix.T),color=cm.jet(k/len(eta)),label=label)\n ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))\n clear_output() \n display(fig)\n time.sleep(2.0*1.0/float(len(eta)))\n ax.plot(x , eta[-1,:].dot(BasisMatrix.T),color='k',label=\"t=1\",dashes=[2,2,2,2])\n ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))\n display(fig)\n clear_output() \n\n```\n\n\n## Step 3\n\n*Solve the problem for all combinations of*\n\n*1. eps = [01, .001]*\n\n*2. ndofs = [16, 32, 64, 128]*\n\n*3. degree = [1, 2, 3]*\n\n*3. dt = [.25, .125, .0625, .03125, .015625]*\n\n*with $\\eta_0 = \\sin(2 \\pi x)+1$.*\n\n*Plot the final solution at $t=1$ in all cases. What do you observe? What happens when you increase ndofs and keep dt constant? *\n\n\n```python\ndef eta_0(x):\n return sin(2*pi*x)+1\n```\n\n\n```python\neps=.001\ndegree=2\nndofs=64\ndt=0.05\neta,basis=solve_allen_cahan(eta_0, eps, dt, ndofs, degree)\nstride=4\nplot_solution(eta,basis,stride,200)\nplt.title(\"Degree=\"+str(degree)+\" ndofs=\"+str(ndofs)+\" Small eps = \"+str(eps)+\" and small dt= \"+str(dt))\n```\n\n.\n\n.\n\n.\n\n.\n\n.\n\n.\n\n\n```python\neps=.01\ndegree=3\nndofs=128\ndt=0.25\neta,basis=solve_allen_cahan(eta_0, eps, dt, ndofs, degree)\nstride=1\nplot_solution(eta,basis,stride,ndofs)\nplt.title(\"Degree=\"+str(degree)+\" ndofs=\"+str(ndofs)+\" Larger eps = \"+str(eps)+\" and Larger dt = \"+str(dt))\n```\n\n.\n\n.\n\n.\n\n.\n\n.\n\n.\n\nThe plots below show the influence of the different parameters within the ranges requested. We can see the convergence of the approximated solution increases with the increase of the number of degrees of freedom and the reduction of the timestep. \n\nMore precisely :\n\n- the **degree** is represented by the different versions of dashes on the plot below:\n - degree **1** corrisponds to the curves with small hashes, \n - degree **2** to the dong dashes,\n - degree **3** to the continuous lines. \n \n The continuous and dashed lines are almost always superposed, indicating that the degrees used are almost not influent on the result at t=1. A very light effect can be visible only for the smallest numbers of degree of freedom **ndofs** or for large timesteps **dt**.\n \n \n- the largest is the characteristic width of the phase transition **eps**, the smaller is the **dt** required to observe convergence of the approximated solution towards the exact solution . \nIn facts for the smallest values of the phase transition $\\varepsilon$, the convergence of the problem modeled in this exercise requires $dt \\le 0.0625$, while for the largest values of $\\varepsilon$ a timestep $dt\\le 0.125$ is almost sufficient. Choosing too large **dt** the solution experiences oscillations.\n\n\n- increasing the number of degrees of freedom **ndofs** while keeping **dt** constant leads to smoother functions, removing some \"local\" variations of the solution respecto to the converged solution (specially for the smallest values of $\\varepsilon$ that induce a sharper solution). But this doesn't change the global shape of the result, except for very large **dt** but for the largest **dt** the approximation is anyway far to be good.\n\n\n```python\ndef plot_t1(eta, basis, stride, resolution,ax,color,dashes):\n x = linspace(0,1,resolution)\n BasisMatrix=np.zeros((resolution,len(basis)))\n for i in range(len(basis)):\n BasisMatrix[:,i]=basis[i](x)\n if(dashes!=[1,0,1,0]):label=''\n ax.plot(x , eta[-1,:].dot(BasisMatrix.T),color=color,dashes=dashes)\n #ax.legend(loc='lower right')\n #ax.set_title(title)\n ax.set_ylim(-1,1.5)\n \nepslist=[0.1,0.04,0.01,.001]\ndeglist=[1,2,3]\nndofslist=[16, 32, 64, 128]\ndtlist=[.25, .125, .0625, .03125, .015625]\nfig,ax=plt.subplots(nrows=5,ncols=4,figsize=(20,20))\nfor col,ndofs in enumerate(ndofslist):\n for row,dt in enumerate(dtlist):\n ax[row,col].text(.5,.9,\" nodfs=\"+str(ndofs)+\" dt=\"+str(dt),\n horizontalalignment='center',\n transform=ax[row,col].transAxes,fontsize=14)\n for eps,color in zip(epslist,cm.jet([0.1,.30,0.45,0.9])):\n ax[row,col].plot(0,0,color=color,label=\" eps=\"+str(eps))\n ax[row,col].legend(loc='lower right')\n for degree,dash in zip(deglist,([3,3,3,3],[6,4,6,4],[1,0,1,0])):\n eta,basis=solve_allen_cahan(eta_0, eps, dt, ndofs, degree)\n plot_t1(eta,basis,stride,200,ax[row,col],color,dash)\n```\n", "meta": {"hexsha": "671eb7841e12739cda665530fea3c5dc31814eb2", "size": 620219, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "final_project/final_project_2019-2020_claurent.ipynb", "max_stars_repo_name": "CeliaLaurent/P1.4_seed", "max_stars_repo_head_hexsha": "f4180024eb4f355d81f67018dc48dee380002d1e", "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": "final_project/final_project_2019-2020_claurent.ipynb", "max_issues_repo_name": "CeliaLaurent/P1.4_seed", "max_issues_repo_head_hexsha": "f4180024eb4f355d81f67018dc48dee380002d1e", "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": "final_project/final_project_2019-2020_claurent.ipynb", "max_forks_repo_name": "CeliaLaurent/P1.4_seed", "max_forks_repo_head_hexsha": "f4180024eb4f355d81f67018dc48dee380002d1e", "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": 708.0125570776, "max_line_length": 326260, "alphanum_fraction": 0.9474379211, "converted": true, "num_tokens": 5917, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067244294588, "lm_q2_score": 0.9099070121457543, "lm_q1q2_score": 0.8575934775528907}} {"text": "# Finding Roots of Equations\n\n## Calculus review\n\n\n```python\n%matplotlib inline\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport scipy as scipy\nfrom scipy.interpolate import interp1d\n```\n\nLet's review the theory of optimization for multivariate functions. Recall that in the single-variable case, extreme values (local extrema) occur at points where the first derivative is zero, however, the vanishing of the first derivative is not a sufficient condition for a local max or min. Generally, we apply the second derivative test to determine whether a candidate point is a max or min (sometimes it fails - if the second derivative either does not exist or is zero). In the multivariate case, the first and second derivatives are *matrices*. In the case of a scalar-valued function on $\\mathbb{R}^n$, the first derivative is an $n\\times 1$ vector called the *gradient* (denoted $\\nabla f$). The second derivative is an $n\\times n$ matrix called the *Hessian* (denoted $H$)\n\nJust to remind you, the gradient and Hessian are given by:\n\n$$\\nabla f(x) = \\left(\\begin{matrix}\\frac{\\partial f}{\\partial x_1}\\\\ \\vdots \\\\\\frac{\\partial f}{\\partial x_n}\\end{matrix}\\right)$$\n\n\n$$H = \\left(\\begin{matrix}\n \\dfrac{\\partial^2 f}{\\partial x_1^2} & \\dfrac{\\partial^2 f}{\\partial x_1\\,\\partial x_2} & \\cdots & \\dfrac{\\partial^2 f}{\\partial x_1\\,\\partial x_n} \\\\[2.2ex]\n \\dfrac{\\partial^2 f}{\\partial x_2\\,\\partial x_1} & \\dfrac{\\partial^2 f}{\\partial x_2^2} & \\cdots & \\dfrac{\\partial^2 f}{\\partial x_2\\,\\partial x_n} \\\\[2.2ex]\n \\vdots & \\vdots & \\ddots & \\vdots \\\\[2.2ex]\n \\dfrac{\\partial^2 f}{\\partial x_n\\,\\partial x_1} & \\dfrac{\\partial^2 f}{\\partial x_n\\,\\partial x_2} & \\cdots & \\dfrac{\\partial^2 f}{\\partial x_n^2}\n\\end{matrix}\\right)$$\n\nOne of the first things to note about the Hessian - it's symmetric. This structure leads to some useful properties in terms of interpreting critical points.\n\nThe multivariate analog of the test for a local max or min turns out to be a statement about the gradient and the Hessian matrix. Specifically, a function $f:\\mathbb{R}^n\\rightarrow \\mathbb{R}$ has a critical point at $x$ if $\\nabla f(x) = 0$ (where zero is the zero vector!). Furthermore, the second derivative test at a critical point is as follows:\n\n* If $H(x)$ is positive-definite ($\\iff$ it has all positive eigenvalues), $f$ has a local minimum at $x$\n* If $H(x)$ is negative-definite ($\\iff$ it has all negative eigenvalues), $f$ has a local maximum at $x$\n* If $H(x)$ has both positive and negative eigenvalues, $f$ has a saddle point at $x$.\n\nIf you have $m$ equations with $n$ variables, then the $m \\times n$ matrix of first partial derivatives is known as the Jacobian $J(x)$. For example, for two equations $f(x, y)$ and $g(x, y)$, we have\n\n$$\nJ(x) = \\begin{bmatrix}\n\\frac{\\delta f}{\\delta x} & \\frac{\\delta f}{\\delta y} \\\\\n\\frac{\\delta g}{\\delta x} & \\frac{\\delta g}{\\delta y} \n\\end{bmatrix}\n$$\n\nWe can now express the multivariate form of Taylor polynomials in a familiar format.\n\n$$\nf(x + \\delta x) = f(x) + \\delta x \\cdot J(x) + \\frac{1}{2} \\delta x^T H(x) \\delta x + \\mathcal{O}(\\delta x^3)\n$$\n\n## Main Issues in Root Finding in One Dimension\n\n* Separating close roots\n* Numerical Stability\n* Rate of Convergence\n* Continuity and Differentiability\n\n## Bisection Method\n\nThe bisection method is one of the simplest methods for finding zeros of a non-linear function. It is guaranteed to find a root - but it can be slow. The main idea comes from the intermediate value theorem: If $f(a)$ and $f(b)$ have different signs and $f$ is continuous, then $f$ must have a zero between $a$ and $b$. We evaluate the function at the midpoint, $c = \\frac12(a+b)$. $f(c)$ is either zero, has the same sign as $f(a)$ or the same sign as $f(b)$. Suppose $f(c)$ has the same sign as $f(a)$ (as pictured below). We then repeat the process on the interval $[c,b]$. \n\n\n```python\ndef f(x):\n return x**3 + 4*x**2 -3\n\nx = np.linspace(-3.1, 0, 100)\nplt.plot(x, x**3 + 4*x**2 -3)\n\na = -3.0\nb = -0.5\nc = 0.5*(a+b)\n\nplt.text(a,-1,\"a\")\nplt.text(b,-1,\"b\")\nplt.text(c,-1,\"c\")\n\nplt.scatter([a,b,c], [f(a), f(b),f(c)], s=50, facecolors='none')\nplt.scatter([a,b,c], [0,0,0], s=50, c='red')\n\nxaxis = plt.axhline(0)\npass\n```\n\n\n```python\nx = np.linspace(-3.1, 0, 100)\nplt.plot(x, x**3 + 4*x**2 -3)\n\nd = 0.5*(b+c)\n\nplt.text(d,-1,\"d\")\nplt.text(b,-1,\"b\")\nplt.text(c,-1,\"c\")\n\nplt.scatter([d,b,c], [f(d), f(b),f(c)], s=50, facecolors='none')\nplt.scatter([d,b,c], [0,0,0], s=50, c='red')\n\nxaxis = plt.axhline(0)\npass\n```\n\nWe can terminate the process whenever the function evaluated at the new midpoint is 'close enough' to zero. This method is an example of what are known as 'bracketed methods'. This means the root is 'bracketed' by the end-points (it is somewhere in between). Another class of methods are 'open methods' - the root need not be somewhere in between the end-points (but it usually needs to be close!)\n\n## Secant Method\n\nThe secant method also begins with two initial points, but without the constraint that the function values are of opposite signs. We use the secant line to extrapolate the next candidate point.\n\n\n```python\ndef f(x):\n return (x**3-2*x+7)/(x**4+2)\n\nx = np.arange(-3,5, 0.1);\ny = f(x)\n\np1=plt.plot(x, y)\nplt.xlim(-3, 4)\nplt.ylim(-.5, 4)\nplt.xlabel('x')\nplt.axhline(0)\nt = np.arange(-10, 5., 0.1)\n\nx0=-1.2\nx1=-0.5\nxvals = []\nxvals.append(x0)\nxvals.append(x1)\nnotconverge = 1\ncount = 0\ncols=['r--','b--','g--','y--']\nwhile (notconverge==1 and count < 3):\n slope=(f(xvals[count+1])-f(xvals[count]))/(xvals[count+1]-xvals[count])\n intercept=-slope*xvals[count+1]+f(xvals[count+1])\n plt.plot(t, slope*t + intercept, cols[count])\n nextval = -intercept/slope\n if abs(f(nextval)) < 0.001:\n notconverge=0\n else:\n xvals.append(nextval)\n count = count+1\n\nplt.show()\n```\n\nThe secant method has the advantage of fast convergence. While the bisection method has a linear convergence rate (i.e. error goes to zero at the rate that $h(x) = x$ goes to zero, the secant method has a convergence rate that is faster than linear, but not quite quadratic (i.e. $\\sim x^\\alpha$, where $\\alpha = \\frac{1+\\sqrt{5}}2 \\approx 1.6$) however, the trade-off is that the secant method is not guaranteed to find a root in the brackets.\n\nA variant of the secant method is known as the **method of false positions**. Conceptually it is identical to the secant method, except that instead of always using the last two values of $x$ for linear interpolation, it chooses the two most recent values that maintain the bracket property (i.e $f(a) f(b) < 0$). It is slower than the secant, but like the bisection, is safe.\n\n## Newton-Raphson Method\n\nWe want to find the value $\\theta$ so that some (differentiable) function $g(\\theta)=0$. \nIdea: start with a guess, $\\theta_0$. Let $\\tilde{\\theta}$ denote the value of $\\theta$ for which $g(\\theta) = 0$ and define $h = \\tilde{\\theta} - \\theta_0$. Then:\n\n$$\n\\begin{eqnarray*}\ng(\\tilde{\\theta}) &=& 0 \\\\\\\\\n&=&g(\\theta_0 + h) \\\\\\\\\n&\\approx& g(\\theta_0) + hg'(\\theta_0)\n\\end{eqnarray*}\n$$\n\nThis implies that \n\n$$ h\\approx \\frac{g(\\theta_0)}{g'(\\theta_0)}$$\n\nSo that\n\n$$\\tilde{\\theta}\\approx \\theta_0 - \\frac{g(\\theta_0)}{g'(\\theta_0)}$$\n\nThus, we set our next approximation:\n\n$$\\theta_1 = \\theta_0 - \\frac{g(\\theta_0)}{g'(\\theta_0)}$$\n\nand we have developed an iterative procedure with:\n\n$$\\theta_n = \\theta_{n-1} - \\frac{g(\\theta_{n-1})}{g'(\\theta_{n-1})}$$\n\n#### Example\n\nLet $$g(x) = \\frac{x^3-2x+7}{x^4+2}$$\n\n\n```python\nx = np.arange(-5,5, 0.1);\ny = (x**3-2*x+7)/(x**4+2)\n\np1=plt.plot(x, y)\nplt.xlim(-4, 4)\nplt.ylim(-.5, 4)\nplt.xlabel('x')\nplt.axhline(0)\nplt.title('Example Function')\nplt.show()\n```\n\n\n```python\nx = np.arange(-5,5, 0.1);\ny = (x**3-2*x+7)/(x**4+2)\n\np1=plt.plot(x, y)\nplt.xlim(-4, 4)\nplt.ylim(-.5, 4)\nplt.xlabel('x')\nplt.axhline(0)\nplt.title('Good Guess')\nt = np.arange(-5, 5., 0.1)\n\nx0=-1.5\nxvals = []\nxvals.append(x0)\nnotconverge = 1\ncount = 0\ncols=['r--','b--','g--','y--','c--','m--','k--','w--']\nwhile (notconverge==1 and count < 6):\n funval=(xvals[count]**3-2*xvals[count]+7)/(xvals[count]**4+2)\n slope=-((4*xvals[count]**3 *(7 - 2 *xvals[count] + xvals[count]**3))/(2 + xvals[count]**4)**2) + (-2 + 3 *xvals[count]**2)/(2 + xvals[count]**4)\n \n intercept=-slope*xvals[count]+(xvals[count]**3-2*xvals[count]+7)/(xvals[count]**4+2)\n\n plt.plot(t, slope*t + intercept, cols[count])\n nextval = -intercept/slope\n if abs(funval) < 0.01:\n notconverge=0\n else:\n xvals.append(nextval)\n count = count+1\n\n\n```\n\nFrom the graph, we see the zero is near -2. We make an initial guess of $$x=-1.5$$\n\nWe have made an excellent choice for our first guess, and we can see rapid convergence!\n\n\n```python\nfunval\n```\n\n\n\n\n 0.007591996330867034\n\n\n\nIn fact, the Newton-Raphson method converges quadratically. However, NR (and the secant method) have a fatal flaw:\n\n\n```python\nx = np.arange(-5,5, 0.1);\ny = (x**3-2*x+7)/(x**4+2)\n\np1=plt.plot(x, y)\nplt.xlim(-4, 4)\nplt.ylim(-.5, 4)\nplt.xlabel('x')\nplt.axhline(0)\nplt.title('Bad Guess')\nt = np.arange(-5, 5., 0.1)\n\nx0=-0.5\nxvals = []\nxvals.append(x0)\nnotconverge = 1\ncount = 0\ncols=['r--','b--','g--','y--','c--','m--','k--','w--']\nwhile (notconverge==1 and count < 6):\n funval=(xvals[count]**3-2*xvals[count]+7)/(xvals[count]**4+2)\n slope=-((4*xvals[count]**3 *(7 - 2 *xvals[count] + xvals[count]**3))/(2 + xvals[count]**4)**2) + (-2 + 3 *xvals[count]**2)/(2 + xvals[count]**4)\n \n intercept=-slope*xvals[count]+(xvals[count]**3-2*xvals[count]+7)/(xvals[count]**4+2)\n\n plt.plot(t, slope*t + intercept, cols[count])\n nextval = -intercept/slope\n if abs(funval) < 0.01:\n notconverge = 0\n else:\n xvals.append(nextval)\n count = count+1\n```\n\nWe have stumbled on the horizontal asymptote. The algorithm fails to converge. \n\n### Convergence Rate\n\nThe following is a derivation of the convergence rate of the NR method:\n\n\nSuppose $x_k \\; \\rightarrow \\; x^*$ and $g'(x^*) \\neq 0$. Then we may write:\n\n$$x_k = x^* + \\epsilon_k$$.\n\nNow expand $g$ at $x^*$:\n\n$$g(x_k) = g(x^*) + g'(x^*)\\epsilon_k + \\frac12 g''(x^*)\\epsilon_k^2 + ...$$\n$$g'(x_k)=g'(x^*) + g''(x^*)\\epsilon_k$$\n\nWe have that\n\n\n\\begin{eqnarray}\n\\epsilon_{k+1} &=& \\epsilon_k + \\left(x_{k-1}-x_k\\right)\\\\\n&=& \\epsilon_k -\\frac{g(x_k)}{g'(x_k)}\\\\\n&\\approx & \\frac{g'(x^*)\\epsilon_k + \\frac12g''(x^*)\\epsilon_k^2}{g'(x^*)+g''(x^*)\\epsilon_k}\\\\\n&\\approx & \\frac{g''(x^*)}{2g'(x^*)}\\epsilon_k^2\n\\end{eqnarray}\n\n## Gauss-Newton\n\nFor 1D, the Newton method is\n$$\nx_{n+1} = x_n - \\frac{f(x_n)}{f'(x_n)}\n$$\n\nWe can generalize to $k$ dimensions by \n$$\nx_{n+1} = x_n - J^{-1} f(x_n)\n$$\nwhere $x$ and $f(x)$ are now vectors, and $J^{-1}$ is the inverse Jacobian matrix. In general, the Jacobian is not a square matrix, and we use the generalized inverse $(J^TJ)^{-1}J^T$ instead, giving\n$$\nx_{n+1} = x_n - (J^TJ)^{-1}J^T f(x_n)\n$$\n\nIn multivariate nonlinear estimation problems, we can find the vector of parameters $\\beta$ by minimizing the residuals $r(\\beta)$, \n$$\n\\beta_{n+1} = \\beta_n - (J^TJ)^{-1}J^T r(\\beta_n)\n$$\nwhere the entries of the Jacobian matrix $J$ are\n$$\nJ_{ij} = \\frac{\\partial r_i(\\beta)}{\\partial \\beta_j}\n$$\n\n## Inverse Quadratic Interpolation\n\nInverse quadratic interpolation is a type of polynomial interpolation. Polynomial interpolation simply means we find the polynomial of least degree that fits a set of points. In quadratic interpolation, we use three points, and find the quadratic polynomial that passes through those three points. \n\n\n```python\n\ndef f(x):\n return (x - 2) * x * (x + 2)**2\n\n\nx = np.arange(-5,5, 0.1);\nplt.plot(x, f(x))\nplt.xlim(-3.5, 0.5)\nplt.ylim(-5, 16)\nplt.xlabel('x')\nplt.axhline(0)\nplt.title(\"Quadratic Interpolation\")\n\n#First Interpolation\nx0=np.array([-3,-2.5,-1.0])\ny0=f(x0)\nf2 = interp1d(x0, y0,kind='quadratic')\n\n#Plot parabola\nxs = np.linspace(-3, -1, num=10000, endpoint=True)\nplt.plot(xs, f2(xs))\n\n#Plot first triplet\nplt.plot(x0, f(x0),'ro');\nplt.scatter(x0, f(x0), s=50, c='yellow');\n\n#New x value\nxnew=xs[np.where(abs(f2(xs))==min(abs(f2(xs))))]\n\nplt.scatter(np.append(xnew,xnew), np.append(0,f(xnew)), c='black');\n\n#New triplet\nx1=np.append([-3,-2.5],xnew)\ny1=f(x1)\nf2 = interp1d(x1, y1,kind='quadratic')\n\n#New Parabola\nxs = np.linspace(min(x1), max(x1), num=100, endpoint=True)\nplt.plot(xs, f2(xs))\n\nxnew=xs[np.where(abs(f2(xs))==min(abs(f2(xs))))]\nplt.scatter(np.append(xnew,xnew), np.append(0,f(xnew)), c='green');\n\n\n```\n\nSo that's the idea behind quadratic interpolation. Use a quadratic approximation, find the zero of interest, use that as a new point for the next quadratic approximation.\n\n\nInverse quadratic interpolation means we do quadratic interpolation on the *inverse function*. So, if we are looking for a root of $f$, we approximate $f^{-1}(x)$ using quadratic interpolation. This just means fitting $x$ as a function of $y$, so that the quadratic is turned on its side and we are guaranteed that it cuts the x-axis somewhere. Note that the secant method can be viewed as a *linear* interpolation on the inverse of $f$. We can write:\n\n$$f^{-1}(y) = \\frac{(y-f(x_n))(y-f(x_{n-1}))}{(f(x_{n-2})-f(x_{n-1}))(f(x_{n-2})-f(x_{n}))}x_{n-2} + \\frac{(y-f(x_n))(y-f(x_{n-2}))}{(f(x_{n-1})-f(x_{n-2}))(f(x_{n-1})-f(x_{n}))}x_{n-1} + \\frac{(y-f(x_{n-2}))(y-f(x_{n-1}))}{(f(x_{n})-f(x_{n-2}))(f(x_{n})-f(x_{n-1}))}x_{n-1}$$\n\nWe use the above formula to find the next guess $x_{n+1}$ for a zero of $f$ (so $y=0$):\n\n$$x_{n+1} = \\frac{f(x_n)f(x_{n-1})}{(f(x_{n-2})-f(x_{n-1}))(f(x_{n-2})-f(x_{n}))}x_{n-2} + \\frac{f(x_n)f(x_{n-2})}{(f(x_{n-1})-f(x_{n-2}))(f(x_{n-1})-f(x_{n}))}x_{n-1} + \\frac{f(x_{n-2})f(x_{n-1})}{(f(x_{n})-f(x_{n-2}))(f(x_{n})-f(x_{n-1}))}x_{n}$$\n\nWe aren't so much interested in deriving this as we are understanding the procedure:\n\n\n\n\n\n```python\nx = np.arange(-5,5, 0.1);\nplt.plot(x, f(x))\nplt.xlim(-3.5, 0.5)\nplt.ylim(-5, 16)\nplt.xlabel('x')\nplt.axhline(0)\nplt.title(\"Inverse Quadratic Interpolation\")\n\n#First Interpolation\nx0=np.array([-3,-2.5,1])\ny0=f(x0)\nf2 = interp1d(y0, x0,kind='quadratic')\n\n#Plot parabola\nxs = np.linspace(min(f(x0)), max(f(x0)), num=10000, endpoint=True)\nplt.plot(f2(xs), xs)\n\n#Plot first triplet\nplt.plot(x0, f(x0),'ro');\nplt.scatter(x0, f(x0), s=50, c='yellow');\n```\n\nConvergence rate is approximately $1.8$. The advantage of the inverse method is that we will *always* have a real root (the parabola will always cross the x-axis). A serious disadvantage is that the initial points must be very close to the root or the method may not converge.\n\nThat is why it is usually used in conjunction with other methods.\n\n## Brentq Method\n\nBrent's method is a combination of bisection, secant and inverse quadratic interpolation. Like bisection, it is a 'bracketed' method (starts with points $(a,b)$ such that $f(a)f(b)<0$.\n\nRoughly speaking, the method begins by using the secant method to obtain a third point $c$, then uses inverse quadratic interpolation to generate the next possible root. Without going into too much detail, the algorithm attempts to assess when interpolation will go awry, and if so, performs a bisection step. Also, it has certain criteria to reject an iterate. If that happens, the next step will be linear interpolation (secant method). \n\nTo find zeros, use \n\n\n```python\nx = np.arange(-5,5, 0.1);\np1=plt.plot(x, f(x))\nplt.xlim(-4, 4)\nplt.ylim(-10, 20)\nplt.xlabel('x')\nplt.axhline(0)\npass\n```\n\n\n```python\nscipy.optimize.brentq(f,-1,.5)\n```\n\n\n\n\n -7.864845203343107e-19\n\n\n\n\n```python\nscipy.optimize.brentq(f,.5,3)\n```\n\n\n\n\n 2.0\n\n\n\n## Roots of polynomials\n\nOne method for finding roots of polynomials converts the problem into an eigenvalue one by using the **companion matrix** of a polynomial. For a polynomial \n\n$$\np(x) = a_0 + a_1x + a_2 x^2 + \\ldots + a_m x^m\n$$\n\nthe companion matrix is\n\n$$\nA = \\begin{bmatrix}\n-a_{m-1}/a_m & -a_{m-2}/a_m & \\ldots & -a_0/a_m \\\\\n1 & 0 & \\ldots & 0 \\\\\n0 & 1 & \\ldots & 0 \\\\\n\\vdots & \\vdots & \\ldots & \\vdots \\\\\n0 & 0 & \\ldots & 0\n\\end{bmatrix}\n$$\n\nThe characteristic polynomial of the companion matrix is $\\lvert \\lambda I - A \\rvert$ which expands to \n\n$$\na_0 + a_1 \\lambda + a_2 \\lambda^2 + \\ldots + a_m \\lambda^m\n$$\n\nIn other words, the roots we are seeking are the eigenvalues of the companion matrix.\n\nFor example, to find the cube roots of unity, we solve $x^3 - 1 = 0$. The `roots` function uses the companion matrix method to find roots of polynomials.\n\n\n```python\n# Coefficients of $x^3, x^2, x^1, x^0$\n\npoly = np.array([1, 0, 0, -1])\n```\n\n\n```python\nx = np.roots(poly)\nx\n```\n\n\n\n\n array([-0.5+0.8660254j, -0.5-0.8660254j, 1. +0. j])\n\n\n\n\n```python\nplt.scatter([z.real for z in x], [z.imag for z in x])\ntheta = np.linspace(0, 2*np.pi, 100)\nu = np.cos(theta)\nv = np.sin(theta)\nplt.plot(u, v, ':')\nplt.axis('square')\npass\n```\n\n## Using `scipy.optimize`\n\n### Finding roots of univariate equations\n\n\n```python\ndef f(x):\n return x**3-3*x+1\n```\n\n\n```python\nx = np.linspace(-3,3,100)\nplt.axhline(0, c='red')\nplt.plot(x, f(x))\npass\n```\n\n\n```python\nfrom scipy.optimize import brentq, newton\n```\n\n#### `brentq` is the recommended method\n\n\n```python\nbrentq(f, -3, 0), brentq(f, 0, 1), brentq(f, 1,3)\n```\n\n\n\n\n (-1.8793852415718166, 0.3472963553337031, 1.532088886237956)\n\n\n\n#### Secant method\n\n\n```python\nnewton(f, -3), newton(f, 0), newton(f, 3)\n```\n\n\n\n\n (-1.8793852415718169, 0.34729635533385395, 1.5320888862379578)\n\n\n\n#### Newton-Raphson method\n\n\n```python\nfprime = lambda x: 3*x**2 - 3\nnewton(f, -3, fprime), newton(f, 0, fprime), newton(f, 3, fprime)\n```\n\n\n\n\n (-1.8793852415718166, 0.34729635533386066, 1.532088886237956)\n\n\n\n### Finding fixed points\n\nFinding the fixed points of a function $g(x) = x$ is the same as finding the roots of $g(x) - x$. However, specialized algorithms also exist - e.g. using `scipy.optimize.fixedpoint`.\n\n\n```python\nfrom scipy.optimize import fixed_point\n```\n\n\n```python\nx = np.linspace(-3,3,100)\nplt.plot(x, f(x), color='red')\nplt.plot(x, x)\npass\n```\n\n\n```python\nfixed_point(f, 0), fixed_point(f, -3), fixed_point(f, 3)\n```\n\n\n\n\n (array(0.25410169), array(-2.11490754), array(1.86080585))\n\n\n\n### Mutlivariate roots and fixed points\n\nUse `root` to solve polynomial equations. Use `fsolve` for non-polynomial equations.\n\n\n```python\nfrom scipy.optimize import root, fsolve\n```\n\nSuppose we want to solve a sysetm of $m$ equations with $n$ unknowns\n\n\\begin{align}\nf(x_0, x_1) &= x_1 - 3x_0(x_0+1)(x_0-1) \\\\\ng(x_0, x_1) &= 0.25 x_0^2 + x_1^2 - 1\n\\end{align}\n\nNote that the equations are non-linear and there can be multiple solutions. These can be interpreted as fixed points of a system of differential equations.\n\n\n```python\ndef f(x):\n return [x[1] - 3*x[0]*(x[0]+1)*(x[0]-1),\n .25*x[0]**2 + x[1]**2 - 1]\n```\n\n\n```python\nsol = root(f, (0.5, 0.5))\nsol.x\n```\n\n\n\n\n array([1.11694147, 0.82952422])\n\n\n\n\n```python\nfsolve(f, (0.5, 0.5))\n```\n\n\n\n\n array([1.11694147, 0.82952422])\n\n\n\n\n```python\nr0 = root(f,[1,1])\nr1 = root(f,[0,1])\nr2 = root(f,[-1,1.1])\nr3 = root(f,[-1,-1])\nr4 = root(f,[2,-0.5])\n\nroots = np.c_[r0.x, r1.x, r2.x, r3.x, r4.x]\n```\n\n\n```python\nY, X = np.mgrid[-3:3:100j, -3:3:100j]\nU = Y - 3*X*(X + 1)*(X-1)\nV = .25*X**2 + Y**2 - 1\n\nplt.streamplot(X, Y, U, V, color=U, linewidth=2, cmap=plt.cm.autumn)\nplt.scatter(roots[0], roots[1], s=50, c='none', edgecolors='k', linewidth=2)\npass\n```\n\n#### We can also give the Jacobian\n\n\n```python\ndef jac(x):\n return [[-6*x[0], 1], [0.5*x[0], 2*x[1]]]\n```\n\n\n```python\nsol = root(f, (0.5, 0.5), jac=jac)\nsol.x, sol.fun\n```\n\n\n\n\n (array([1.11694147, 0.82952422]), array([-4.23383550e-12, -3.31612515e-12]))\n\n\n\n#### Check that values found are really roots\n\n\n\n```python\nnp.allclose(f(sol.x), 0)\n```\n\n\n\n\n True\n\n\n\n#### Starting from other initial conditions, different roots may be found\n\n\n```python\nsol = root(f, (12,12))\nsol.x\n```\n\n\n\n\n array([ 0.77801314, -0.92123498])\n\n\n\n\n```python\nnp.allclose(f(sol.x), 0)\n```\n\n\n\n\n True\n\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "be4751a3214fdd7a26e84ac9cffe4c7442421ae2", "size": 340669, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/S09A_Root_Finding.ipynb", "max_stars_repo_name": "ZhechangYang/STA663", "max_stars_repo_head_hexsha": "0dcf48e3e7a2d1f698b15e84946e44344b8153f5", "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": "notebooks/S09A_Root_Finding.ipynb", "max_issues_repo_name": "ZhechangYang/STA663", "max_issues_repo_head_hexsha": "0dcf48e3e7a2d1f698b15e84946e44344b8153f5", "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": "notebooks/S09A_Root_Finding.ipynb", "max_forks_repo_name": "ZhechangYang/STA663", "max_forks_repo_head_hexsha": "0dcf48e3e7a2d1f698b15e84946e44344b8153f5", "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": 249.5743589744, "max_line_length": 79964, "alphanum_fraction": 0.9054830349, "converted": true, "num_tokens": 6897, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425355825848, "lm_q2_score": 0.9324533144915912, "lm_q1q2_score": 0.8575237304514323}} {"text": "```python\nfrom sympy import *\ninit_printing()\nx=symbols(\"x\")\na=Integral(cos(x)*exp(x),x)\na\n```\n\n\n```python\nx,y=symbols(\"x y\")\n\nexpr=x+2*y\nexpr\n```\n\n\n```python\ntype(x)\n```\n\n\n\n\n sympy.core.symbol.Symbol\n\n\n\n\n```python\nexpr+1\n```\n\n\n```python\nexpr-x\n```\n\n\n```python\nx*expr\n```\n\n\n```python\nexpanded_expr=expand(_)\nexpanded_expr\n```\n\n\n```python\nfactor_expr=factor(_)\nfactor_expr\n```\n\n\n```python\nx,t,z,nu=symbols(\"x t z nu\")\n```\n\n\n```python\ndiff(cos(x**2)/x,x)\n```\n\n\n```python\nprint(_)\n```\n\n -2*sin(x**2) - cos(x**2)/x**2\n\n\n\n```python\nDerivative(cos(x**2)/x,x)\n```\n\n\n```python\nintegrate(exp(-x**2),(x,-oo,+oo))\n```\n\n\n```python\nlimit((cos(x+t)-cos(x))/t,t,0)\n```\n\n\n```python\nabs(sin(x))/sin(x)\n```\n\n\n```python\nlimit(_,x,0)\n```\n\n\n```python\nlimit(abs(sin(x))/sin(x),x,0,\"+\")\n```\n\n\n```python\nlimit(abs(sin(x))/sin(x),x,0,\"-\")\n```\n\n\n```python\nIntegral(cos(z)*sin(nu),z,nu,t)\n```\n\n\n```python\nr,phi,theta,R=symbols(\"r phi theta R\")\n```\n\n\n```python\nIntegral(r**2*sin(theta),(theta,0,pi),(phi,0,2*pi),(r,0,R))\n```\n\n\n```python\nLimit(exp(cos(t**2)),t,5,\"+\")\n```\n\n\n```python\nsolve(x**2-2,x)\n```\n\n\n```python\nEq(x**2-2,0)\n```\n\n\n```python\nsolve(_,x)\n```\n\n### Ecuacion diferencial!!!\n\n$y''-y=e^t$\n\n\n```python\ny=Function(\"y\")\ny(t)\nn=symbols(\"n\")\n```\n\n\n```python\nDerivative(y(t),t)\n```\n\n\n```python\nDerivative(y(t),(t,n))\n```\n\n\n```python\nEq(Derivative(y(t),(t,2))-y(t),exp(t))\n```\n\n\n```python\ndsolve(_,y(t))\n```\n\n\n```python\nMatrix([[0,-I],[I,0]])\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}0 & - i\\\\i & 0\\end{matrix}\\right]$\n\n\n\n\n```python\n_.eigenvals()\n```\n\n\n```python\nEq(4*t*y(t).diff(t,t)+y(t).diff(t)-y(t),0)\n```\n\n\n```python\ndsolve(_)\n```\n\n\n```python\nprint(latex(_))\n```\n\n y{\\left(t \\right)} = t^{\\frac{3}{8}} \\left(C_{1} J_{\\frac{3}{4}}\\left(i \\sqrt{t}\\right) + C_{2} Y_{\\frac{3}{4}}\\left(i \\sqrt{t}\\right)\\right)\n\n", "meta": {"hexsha": "b98365ebf86f9e6a9fb89c948d29c040935d2144", "size": 65458, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "IntroToSciPy/SymPy/SymPyTutorial/chibolo meppo.ipynb", "max_stars_repo_name": "migueloayza/LearningPython", "max_stars_repo_head_hexsha": "00fe5e0072d16cb5caa10f546d2708b1beb8c30b", "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": "IntroToSciPy/SymPy/SymPyTutorial/chibolo meppo.ipynb", "max_issues_repo_name": "migueloayza/LearningPython", "max_issues_repo_head_hexsha": "00fe5e0072d16cb5caa10f546d2708b1beb8c30b", "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": "IntroToSciPy/SymPy/SymPyTutorial/chibolo meppo.ipynb", "max_forks_repo_name": "migueloayza/LearningPython", "max_forks_repo_head_hexsha": "00fe5e0072d16cb5caa10f546d2708b1beb8c30b", "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.1526980482, "max_line_length": 4452, "alphanum_fraction": 0.8203428152, "converted": true, "num_tokens": 678, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947163538935, "lm_q2_score": 0.9073122201074846, "lm_q1q2_score": 0.8574052540848938}} {"text": "# Rate of Change\nFunctions are often visualized as a line on a graph, and this line shows how the value returned by the function changes based on changes in the input value.\n\n## Linear Rate of Change\n\nFor example, imagine a function that returns the number of meters travelled by a cyclist based on the number of seconds that the cyclist has been cycling.\n\nHere is such a function:\n\n\\begin{equation}q(x) = 2x + 1\\end{equation}\n\nWe can plot the output for this function for a period of 10 seconds like this:\n\n\n```python\n%matplotlib inline\n\ndef q(x):\n return 2*x + 1\n\n# Plot the function\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\n# Create an array of x values from 0 to 10\nx = np.array(range(0, 11))\n\n# Set up the graph\nplt.xlabel('Seconds')\nplt.ylabel('Meters')\nplt.xticks(range(0,11, 1))\nplt.yticks(range(0, 22, 1))\nplt.grid()\n\n# Plot x against q(x)\nplt.plot(x,q(x), color='green')\n\nplt.show()\n```\n\nIt's clear from the graph that ***q*** is a *linear* function that describes a slope in which distance increases at a constant rate over time. In other words, the cyclist is travelling at a constant speed.\n\nBut what speed?\n\nSpeed, or more technically, velocity is a measure of change - it measures how the distance travelled changes over time (which is why we typically express it as a unit of distance per a unit of time, like *miles-per-hour* or *meters-per-second*). So we're looking for a way to measure the change in the line created by the function.\n\nThe change in values along the line define its *slope*, which we know from a previous lesson is represented like this:\n\n\\begin{equation}m = \\frac{\\Delta{y}}{\\Delta{x}} \\end{equation}\n\nWe can calculate the slope of our function like this:\n\n\\begin{equation}m = \\frac{q(x)_{2} - q(x)_{1}}{x_{2} - x_{1}} \\end{equation}\n\nSo we just need two ordered pairs of ***x*** and ***q(x)*** values from our line to apply this equation.\n\n- After 1 second, ***x*** is 1 and ***q***(1) = **3**.\n- After 10 seconds, ***x*** is 10 and ***q***(10) = 21.\n\nSo we can meassure the rate of change like this:\n\n\\begin{equation}m = \\frac{21 - 3}{10 - 1} \\end{equation}\n\nThis is the same as:\n\n\\begin{equation}m = \\frac{18}{9} \\end{equation}\n\nWhich simplifies to:\n\n\\begin{equation}m = \\frac{2}{1} \\end{equation}\n\nSo our rate of change is 2/1 or put another way, the cyclist is travelling at 2 meters-per-second.\n\n## Average Rate of Change\nOK, let's look at another function that calculates distance travelled for a given number of seconds:\n\n\\begin{equation}r(x) = x^{2} + x\\end{equation}\n\nLet's take a look at that using Python:\n\n\n```python\n%matplotlib inline\n\ndef r(x):\n return x**2 + x\n\n# Plot the function\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\n# Create an array of x values from 0 to 10\nx = np.array(range(0, 11))\n\n# Set up the graph\nplt.xlabel('Seconds')\nplt.ylabel('Meters')\nplt.grid()\n\n# Plot x against r(x)\nplt.plot(x,r(x), color='green')\n\nplt.show()\n```\n\nThis time, the function is not linear. It's actually a quadratic function, and the line from 0 seconds to 10 seconds shows an exponential increase; in other words, the cyclist is *accelerating*.\n\nTechnically, acceleration itself is a measure of change in velocity over time; and velocity, as we've already discussed, is a measure of change in distance over time. So measuring accelleration is pretty complex, and requires *differential calculus*, which we're going to cover shortly. In fact, even just measuring the velocity at a single point in time requires differential calculus; but we can use algebraic methods to calculate an *average* rate of velocity for a given period shown in the graph.\n\nFirst, we need to define a *secant* line that joins two points in our exponential arc to create a straight slope. For example, a secant line for the entire 10 second time span would join the following two points:\n\n- 0, ***r***(0)\n- 10, ***r***(10)\n\nRun the following Python code to visualize this line:\n\n\n```python\n%matplotlib inline\n\ndef r(x):\n return (x)**2 + x\n\n# Plot the function\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\n# Create an array of x values from 0 to 10\nx = np.array(range(0, 11))\n\n# Create an array for the secant line\ns = np.array([0,10])\n\n# Set up the graph\nplt.xlabel('Seconds')\nplt.ylabel('Meters')\nplt.grid()\n\n# Plot x against r(x)\nplt.plot(x,r(x), color='green')\n\n# Plot the secant line\nplt.plot(s,r(s), color='magenta')\n\nplt.show()\n```\n\nNow, because the secant line is straight, we can apply the slope formula we used for a linear function to calculate the average velocity for the 10 second period:\n\n- At 0 seconds, ***x*** is 0 and ***r***(0) = **0**.\n- At 10 seconds, ***x*** is 10 and ***r***(10) = 110.\n\nSo we can meassure the rate of change like this:\n\n\\begin{equation}m = \\frac{110 - 0}{10 - 0} \\end{equation}\n\nThis is the same as:\n\n\\begin{equation}m = \\frac{110}{10} \\end{equation}\n\nWhich simplifies to:\n\n\\begin{equation}m = \\frac{11}{1} \\end{equation}\n\nSo our rate of change is 11/1 or put another way, the cyclist is travelling at an average velocity of 11 meters-per-second over the 10-second period.\n\nOf course, we can measure the average velocity between any two points on the exponential line. Use the following Python code to show the secant line for the period between 2 and 7 seconds, and calculate the average velocity for that period\n\n\n```python\n%matplotlib inline\n\ndef r(x):\n return x**2 + x\n\n# Plot the function\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\n# Create an array of x values from 0 to 10\nx = np.array(range(0, 11))\n\n# Create an array for the secant line\ns = np.array([2,7])\n\n# Calculate rate of change\nx1 = s[0]\nx2 = s[-1]\ny1 = r(x1)\ny2 = r(x2)\na = (y2 - y1)/(x2 - x1)\n\n\n# Set up the graph\nplt.xlabel('Seconds')\nplt.ylabel('Meters')\nplt.grid()\n\n# Plot x against r(x)\nplt.plot(x,r(x), color='green')\n\n# Plot the secant line\nplt.plot(s,r(s), color='magenta')\n\nplt.annotate('Average Velocity =' + str(a) + ' m/s',((x2+x1)/2, (y2+y1)/2))\n\nplt.show()\n\n\n```\n", "meta": {"hexsha": "09705d0b4397c0645f18e610dcd7be0382c99a8c", "size": 9026, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Basics of Calculus by Hiren/02-01-Rate of Change.ipynb", "max_stars_repo_name": "awesome-archive/Basic-Mathematics-for-Machine-Learning", "max_stars_repo_head_hexsha": "b6699a9c29ec070a0b1615c46952cb0deeb73b54", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 401, "max_stars_repo_stars_event_min_datetime": "2018-08-29T04:55:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T11:03:39.000Z", "max_issues_repo_path": "Basics of Calculus by Hiren/02-01-Rate of Change.ipynb", "max_issues_repo_name": "aligeekk/Basic-Mathematics-for-Machine-Learning", "max_issues_repo_head_hexsha": "8662076d60e89f58a6e81e4ca1377569472760a2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2018-11-19T23:54:27.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-20T00:15:39.000Z", "max_forks_repo_path": "Basics of Calculus by Hiren/02-01-Rate of Change.ipynb", "max_forks_repo_name": "aligeekk/Basic-Mathematics-for-Machine-Learning", "max_forks_repo_head_hexsha": "8662076d60e89f58a6e81e4ca1377569472760a2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 135, "max_forks_repo_forks_event_min_datetime": "2018-08-29T05:04:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T07:04:25.000Z", "avg_line_length": 31.8939929329, "max_line_length": 510, "alphanum_fraction": 0.5604919123, "converted": true, "num_tokens": 1683, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566342012360932, "lm_q2_score": 0.8962513655129178, "lm_q1q2_score": 0.857384709154208}} {"text": "#### Distribución Bernoulli\n\nLa distribución Bernoulli es una **distribución de probabilidad discreta**.\n\nUn ensayo Bernoulli se define como un experimento aleatorio con sólo dos resultados posibles: éxito o fracaso.\n\nLa probabilidad de éxito es $p$ y la probabilidad de fracaso es $1-p$\n\nDefinimos la variable aleatoria X como la función de mapea el resultado éxito al número 1, y fracaso al número 0. Entonces X tiene distribución Bernoulli con parámetro $p \\in (0,1) \\hspace{0.5cm} X \\sim Be(p)$\n\nLa función de probabilidad es\n\n\\begin{equation}\n f_X(x)=\\begin{cases}\n 1-p, & \\text{si $x = 0$} \\\\\n p, & \\text{si $x = 1$} \\\\\n 0, & \\text{en otro caso}\n \\end{cases}\n\\end{equation}\n\nQue también puede escribirse como\n\n\\begin{equation}\n f_X(x)=\\begin{cases}\n p^{x}(1-p)^{1-x}, & \\text{si $x \\in \\{0, 1\\}$} \\\\ \n 0, & \\text{en otro caso}\n \\end{cases}\n\\end{equation}\n\n**Ejemplos**:\n\n* X: un tratamiento médico es efectivo\n\n* X: al lanzar una moneda sale cara\n\n* X: al lanzar un dado sale 3\n\n---\n\nVamos a ver ahora cómo generar datos con esta distibución de probabilidad.\n\nNecesitamos un generador de números aleatorios, que expone métodos para generar números aleatorios con alguna distribución de probabilidad especificada. Construimos este generador de este modo `np.random.default_rng()`\n\nhttps://docs.scipy.org/doc/numpy/reference/random/generator.html\n\nEstas son las distribuciones de probabilidad disponibles:\nhttps://docs.scipy.org/doc/numpy/reference/random/generator.html#distributions\n\nRecordemos que la distribución de Bernoulli es un caso particular de la distribucón Binomial con una única repetición. Por eso vamos a generar datos con distribución empleando el método `binomial` con `n=1` https://docs.scipy.org/doc/numpy/reference/random/generated/numpy.random.Generator.binomial.html#numpy.random.Generator.binomial\n\n\n\n```python\nimport numpy as np\nrandom_generator = np.random.default_rng()\nsample_size = 1000\nrandom_bernoulli_data = random_generator.binomial(n=1, p = 0.7, size = sample_size)\n```\n\nUsamos la misma función `distribution_plotter` para graficar los datos generados\n\n\n```python\nimport seaborn as sns\ndef distribution_plotter(data, label, bins=None): \n sns.set(rc={\"figure.figsize\": (10, 7)})\n sns.set_style(\"white\") \n dist = sns.distplot(data, bins= bins, hist_kws={'alpha':0.2}, kde_kws={'linewidth':5})\n dist.set_title('Distribucion de ' + label + '\\n', fontsize=16)\n```\n\n\n```python\n#print(random_bernoulli_data)\ndistribution_plotter(random_bernoulli_data, \"bernoulli\", bins=[0,.1,.9,1])\n```\n\n#### Referencias\n\nhttps://www.statisticshowto.datasciencecentral.com/bernoulli-distribution/\n\nGráficos: https://en.wikipedia.org/wiki/List_of_probability_distributions\n", "meta": {"hexsha": "aa9614c9130931069426d4f01e3436ec1018acc4", "size": 4380, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Code/3-numpy/probabilidad/4.2_bernoulli.ipynb", "max_stars_repo_name": "Flor91/Data-Science", "max_stars_repo_head_hexsha": "f67ec537341e8b2d8213a56ef8ee63028e46e1b2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-10-06T12:59:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-08T10:58:14.000Z", "max_issues_repo_path": "Code/3-numpy/probabilidad/4.2_bernoulli.ipynb", "max_issues_repo_name": "Flor91/Data-Science", "max_issues_repo_head_hexsha": "f67ec537341e8b2d8213a56ef8ee63028e46e1b2", "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": "Code/3-numpy/probabilidad/4.2_bernoulli.ipynb", "max_forks_repo_name": "Flor91/Data-Science", "max_forks_repo_head_hexsha": "f67ec537341e8b2d8213a56ef8ee63028e46e1b2", "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": 31.5107913669, "max_line_length": 343, "alphanum_fraction": 0.5897260274, "converted": true, "num_tokens": 780, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308165850443, "lm_q2_score": 0.9184802434674242, "lm_q1q2_score": 0.8573377636770281}} {"text": "# Google Page Rank Algorithm\n\n\n\nIn this notebook, we learn and code up a simplified version of Google's Page Rank Algorithm, which is a direct application of Eigenvectors and Eigenvalues we learnt in Linear Algebra.\n\n\n\nReference to the original paper: $\\href{http://ilpubs.stanford.edu:8090/422/1/1999-66.pdf}{here}$\n\nReference to blog:\n$\\href{https://www.dhruvonmath.com/2019/03/20/pagerank/}{here}$\n\nGoogle Page Rank Algorithm predicts a rank for each webpage on the internet. This rank depends on the number of ingoing and outgoing links to a webpage.\n\nYou can think of rank of a webpage as follows: If a web page gets rank $1$, it means that a random web searcher who clicks links randomly would spend the most amount of time in this web page. If a web page gets rank $2$, it means that a random web searcher who keeps clicking links randomly would spend the second most amount of time in this web page and so on and so forth.\n\nGiven the structure of the web, it is very obvious to model the web as a Graph Data structure. The nodes of the graph are the web pages. Edges of the graph represent links between the web pages.\n\nNote that the graph is a directed graph. There maybe a link from webpage 'A' to webpage 'B', it may not always be the case that there exists a link from webpage 'B' to webpage 'A'.\n\nA graph with $N$ nodes can be represented with a $N \\times N$ matrix. This matrix is known as Adjacency matrix.\n\n$A_{ij}$ represents the weight of the edge connecting the $j^{th}$ node to the $i^{th}$ node. \nWe can think of this adjacency matrix as concatenation of $N$ column vectors. The $i^{th}$ column defines the edges from node $i$ to all other nodes.\n\n**Exercise:**\nCan you draw the graph corresponding to the following adjacency matrix?\n\n\\begin{equation}\nA = \\begin{pmatrix}\n0 & 1/2 & 0 & 0\\\\\n1/3 & 0 & 0 & 1/2\\\\\n1/3 & 0 & 0 & 1/2\\\\\n1/3 & 1/2 & 1 & 0\\\\\n\\end{pmatrix}\n\\end{equation}\n\n**Exercise:**\nCan you write down the adjacency matrix for the following graph?\n\n\nLet us normalize each column of the adjacency matrix so that the entries sum upto $1$. This is because we want to output the rank as a probability value of the amount of time spent on that webpage.\n\nWe start with equiprobable ranks for all webpages. \n\nWe update the ranks($r$) as follows:\n\\begin{equation}\nr(i) = \\underset{j}{\\sum} r(j) * A(i, j)\n\\end{equation}\n\\begin{equation}\nr' = A.r\n\\end{equation}\nThe above is a recursive definition.\n\n\n```python\nimport numpy as np\n```\n\n\n```python\n# Complete the below function to return A after normalizing\n# each of it's columns\n# Normalizing a column means sum of entries in each column adds to 1.\n# PLEASE USE VECTORISED CODE FOR EFFICIENCY\ndef normalize_columns(A):\n sums = A.sum(axis=0)\n return (A/sums)\n \n```\n\n\n```python\nA = np.array([[0, 0, 1, 1], [1, 0, 0, 0], [1, 1, 0, 1], [1, 1, 0, 0]])\nprint(normalize_columns(A))\n```\n\n [[0. 0. 1. 0.5 ]\n [0.33333333 0. 0. 0. ]\n [0.33333333 0.5 0. 0.5 ]\n [0.33333333 0.5 0. 0. ]]\n\n\n**Expected Output:**\n\n[[0. 0. 1. 0.5 ]\n [0.33333333 0. 0. 0. ]\n [0.33333333 0.5 0. 0.5 ]\n [0.33333333 0.5 0. 0. ]]\n\n\n```python\n# Complete the below function to take a matrix A and a vector r.\n# Return the updated rank.\n# PLEASE USE VECTORISED CODE WITHOUT LOOPS\ndef update_rank(A, r):\n r = np.dot(A,r)\n return r\n```\n\n\n```python\n# Complete the below function to check if two vectors a and b are equal\n# Since we are dealing with real numbers, \n# we say two elements(x and y) are equal if abs(x - y) <= epsilon\n\n# PLEASE USE VECTORISED CODE WITHOUT LOOPS\nep = 1e-8\ndef check_equality(a, b):\n val = np.abs(a - b) <= ep\n if(np.any(val[:]== False)):\n return False\n return True\n \n```\n\n\n```python\n# Complete the below function to compute ranks iteratively until \n# ranks stabilise.\n# We say ranks become stabilised when the after updation the ranks\n# do not change.\n# Use the functions defined above.\ndef compute_iteratively(A, initial_rank):\n curr_rank = initial_rank\n prev_rank=np.zeros(initial_rank.shape[0])\n while(check_equality(curr_rank,prev_rank)!=True):\n prev_rank = curr_rank\n curr_rank = update_rank(A,curr_rank)\n return curr_rank\n \n \n```\n\n\n```python\n# Complete the below function to compute final ranks at one shot using\n# eigen values and eigen vectors\n# You may use inbuilt functions to compute eigenvectors and eigenvalues\nimport scipy.linalg as la\ndef compute_using_eig(A, initial_rank):\n eigenvals, eigenvecs = la.eig(A)\n egi = eigenvals.astype(int)\n i = np.where(egi==1)\n i = i[0][0]\n \n \n return normalize_columns(eigenvecs[:,i])\n```\n\n\n```python\nA = np.array([[0, 1, 0, 0], [1, 0, 0, 1], [1, 0, 0, 1], [1, 1, 1, 0]])\nA = normalize_columns(A)\nr = np.array([0.25, 0.25, 0.25, 0.25])\nprint(\"Rank computed iteratively: \\n\", compute_iteratively(A, r))\nprint(\"Rank computed using eigen values and eigen vectors: \\n\", compute_using_eig(A, r))\n```\n\n Rank computed iteratively: \n [0.12 0.24 0.24 0.4 ]\n Rank computed using eigen values and eigen vectors: \n [0.12 0.24 0.24 0.4 ]\n\n\n /usr/lib/python3/dist-packages/ipykernel_launcher.py:7: ComplexWarning: Casting complex values to real discards the imaginary part\n import sys\n\n\n**Expected Output:**\n\nRank computed iteratively: \n [0.12 0.24 0.24 0.39999999]\n\nRank computed using eigen values and eigen vectors: \n [0.12 0.24 0.24 0.4 ]\n\n\n```python\nA = np.array([[0, 0, 1, 1], [1, 0, 0, 0], [1, 1, 0, 1], [1, 1, 0, 0]])\nA = normalize_columns(A)\nr = np.array([0.25, 0.25, 0.25, 0.25])\nprint(\"Rank computed iteratively: \\n\", compute_iteratively(A, r))\nprint(\"Rank computed using eigen values and eigen vectors: \\n\", compute_using_eig(A, r))\n```\n\n Rank computed iteratively: \n [0.38709677 0.12903226 0.29032258 0.19354839]\n Rank computed using eigen values and eigen vectors: \n [0.38709677+0.j 0.12903226+0.j 0.29032258+0.j 0.19354839+0.j]\n\n\n /usr/lib/python3/dist-packages/ipykernel_launcher.py:7: ComplexWarning: Casting complex values to real discards the imaginary part\n import sys\n\n\n**Expected Output:**\n\nRank computed iteratively: \n\n[0.38709677 0.12903226 0.29032258 0.19354839]\n\nRank computed using eigen values and eigen vectors: \n\n[0.38709677 0.12903226 0.29032258 0.19354839]\n", "meta": {"hexsha": "f109cf6edb299e272771fba288461a5b6090e987", "size": 10235, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "day8/morning/Google Page Rank Algorithm Assignment/Page Rank Algorithm.ipynb", "max_stars_repo_name": "avani17101/CVIT-Workshop", "max_stars_repo_head_hexsha": "0339021123b82dfa55c6f6fa4d8c4322ecf7e687", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-06-27T06:38:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-01T15:37:33.000Z", "max_issues_repo_path": "day8/morning/Google Page Rank Algorithm Assignment/Page Rank Algorithm.ipynb", "max_issues_repo_name": "avani17101/CVIT-Workshop", "max_issues_repo_head_hexsha": "0339021123b82dfa55c6f6fa4d8c4322ecf7e687", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-06-08T18:41:11.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-27T10:25:24.000Z", "max_forks_repo_path": "day8/morning/Google Page Rank Algorithm Assignment/Page Rank Algorithm.ipynb", "max_forks_repo_name": "avani17101/CVIT-Workshop", "max_forks_repo_head_hexsha": "0339021123b82dfa55c6f6fa4d8c4322ecf7e687", "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.4613095238, "max_line_length": 383, "alphanum_fraction": 0.5426477772, "converted": true, "num_tokens": 1933, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897492587141, "lm_q2_score": 0.9111797069968974, "lm_q1q2_score": 0.8572285280752396}} {"text": "```python\nfrom sympy import *\n```\n\n\n```python\ndef build_polynomial(matrix, iter):\n x = Symbol('x')\n if iter == -1:\n return 1\n if iter == 0:\n return poly(matrix[1][1] - x)\n return poly(\n (matrix[iter][iter] - x)*build_polynomial(matrix, iter - 1) - \n matrix[iter - 1][iter]*matrix[iter][iter - 1]*build_polynomial(matrix, iter - 2))\n```\n\n\n```python\ndef halleys_method(function, initial, precision):\n x = Symbol('x')\n iters = 0\n \n lfunction = lambdify(x, function, 'numpy')\n \n dfunction = function.diff(x)\n ldfunction = lambdify(x, dfunction, 'numpy')\n \n d2function = dfunction.diff(x)\n ld2function = lambdify(x, d2function, 'numpy')\n \n while abs(lfunction(initial)) > precision:\n t = - lfunction(initial)/ldfunction(initial)\n r = ld2function(initial)*t**2/ldfunction(initial)\n initial = initial + t**2/(t + 0.5*r)\n iters += 1\n \n residual = lfunction(initial)\n return {'root': initial, 'iterations': iters, 'residual': residual}\n```\n\n\n```python\ndef eigenvalues(matrix, initial, precision):\n x = Symbol('x')\n eigenvalues = {'value':[], 'residual':[]}\n n = len(matrix)\n polynomial = build_polynomial(matrix, n-1)\n for _ in range(n):\n root = halleys_method(polynomial.as_expr(), initial, precision)\n eigenvalues['value'].append(root['root'])\n eigenvalues['residual'].append(root['residual'])\n polynomial = pquo(polynomial, poly(x - root['root']))\n return eigenvalues\n```\n\n\n```python\nmatrix = [[1, 2, 0, 0],\n [3, 1, 2, 0],\n [0, 3, 1, 2],\n [0, 0, 3, 2]]\ninitial = 0\nprecision = 0.001\n```\n\n\n```python\n# результат написанного алгоритма с невязкой для каждого значения\neigenvalues(matrix, initial, precision)\n```\n\n\n\n\n {'value': [-0.1881911215025469,\n 2.8998266041121847,\n -2.8518950613854894,\n 5.14025957877585],\n 'residual': [8.34833535634516e-09,\n 1.497466683986204e-08,\n -7.894759500359783e-06,\n 0.0]}\n\n\n\n\n```python\nimport numpy\n# результат встроенной функции\nnumpy.linalg.eigvals(numpy.array(matrix))\n```\n\n\n\n\n array([-2.85189605, -0.18819112, 5.14026057, 2.89982661])\n\n\n", "meta": {"hexsha": "34bed8ba8fb99eb54cf982c98d145cb7eb9e5f45", "size": 4137, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Numerical-Methods/Eigenvalues/eigenvalues.ipynb", "max_stars_repo_name": "cmlimm/uni-projects", "max_stars_repo_head_hexsha": "b63ac71cc0b971c7f035096a6bd15b0cbb5bb9f6", "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": "Numerical-Methods/Eigenvalues/eigenvalues.ipynb", "max_issues_repo_name": "cmlimm/uni-projects", "max_issues_repo_head_hexsha": "b63ac71cc0b971c7f035096a6bd15b0cbb5bb9f6", "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": "Numerical-Methods/Eigenvalues/eigenvalues.ipynb", "max_forks_repo_name": "cmlimm/uni-projects", "max_forks_repo_head_hexsha": "b63ac71cc0b971c7f035096a6bd15b0cbb5bb9f6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-10-29T18:31:32.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-29T18:31:32.000Z", "avg_line_length": 25.3803680982, "max_line_length": 95, "alphanum_fraction": 0.4945612763, "converted": true, "num_tokens": 684, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.950410972802222, "lm_q2_score": 0.9019206758704633, "lm_q1q2_score": 0.8571953069444845}} {"text": "## RIHAD VARIAWA, Data Scientist - Who has fun LEARNING, EXPLORING & GROWING\n## Exponentials, Radicals, and Logs\nUp to this point, all of our equations have included standard arithmetic operations, such as division, multiplication, addition, and subtraction. Many real-world calculations involve exponential values in which numbers are raised by a specific power.\n\n## Exponentials\nA simple case of of using an exponential is squaring a number; in other words, multipying a number by itself. For example, 2 squared is 2 times 2, which is 4. This is written like this:\n\n\\begin{equation}2^{2} = 2 \\cdot 2 = 4\\end{equation}\n\nSimilarly, 2 cubed is 2 times 2 times 2 (which is of course 8):\n\n\\begin{equation}2^{3} = 2 \\cdot 2 \\cdot 2 = 8\\end{equation}\n\nIn Python, you use the ****** operator, like this example in which **x** is assigned the value of 5 raised to the power of 3 (in other words, 5 x 5 x 5, or 5-cubed):\n\n\n```python\nx = 5**3\nprint(x)\n```\n\nMultiplying a number by itself twice or three times to calculate the square or cube of a number is a common operation, but you can raise a number by any exponential power. For example, the following notation shows 4 to the power of 7 (or 4 x 4 x 4 x 4 x 4 x 4 x 4), which has the value:\n\n\\begin{equation}4^{7} = 16384 \\end{equation}\n\nIn mathematical terminology, **4** is the *base*, and **7** is the *power* or *exponent* in this expression.\n\n## Radicals (Roots)\nWhile it's common to need to calculate the solution for a given base and exponential, sometimes you'll need to calculate one or other of the elements themselves. For example, consider the following expression:\n\n\\begin{equation}?^{2} = 9 \\end{equation}\n\nThis expression is asking, given a number (9) and an exponent (2), what's the base? In other words, which number multipled by itself results in 9? This type of operation is referred to as calculating the *root*, and in this particular case it's the *square root* (the base for a specified number given the exponential **2**). In this case, the answer is 3, because 3 x 3 = 9. We show this with a **√** symbol, like this:\n\n\\begin{equation}\\sqrt{9} = 3 \\end{equation}\n\nOther common roots include the *cube root* (the base for a specified number given the exponential **3**). For example, the cube root of 64 is 4 (because 4 x 4 x 4 = 64). To show that this is the cube root, we include the exponent **3** in the **√** symbol, like this:\n\n\\begin{equation}\\sqrt[3]{64} = 4 \\end{equation}\n\nWe can calculate any root of any non-negative number, indicating the exponent in the **√** symbol.\n\nThe **math** package in Python includes a **sqrt** function that calculates the square root of a number. To calculate other roots, you need to reverse the exponential calculation by raising the given number to the power of 1 divided by the given exponent:\n\n\n```python\nimport math\n\n# Calculate square root of 25\nx = math.sqrt(25)\nprint (x)\n\n# Calculate cube root of 64\ncr = round(64 ** (1. / 3))\nprint(cr)\n```\n\nThe code used in Python to calculate roots other than the square root reveals something about the relationship between roots and exponentials. The exponential root of a number is the same as that number raised to the power of 1 divided by the exponential. For example, consider the following statement:\n\n\\begin{equation} 8^{\\frac{1}{3}} = \\sqrt[3]{8} = 2 \\end{equation}\n\nNote that a number to the power of 1/3 is the same as the cube root of that number.\n\nBased on the same arithmetic, a number to the power of 1/2 is the same as the square root of the number:\n\n\\begin{equation} 9^{\\frac{1}{2}} = \\sqrt{9} = 3 \\end{equation}\n\nYou can see this for yourself with the following Python code:\n\n\n```python\nimport math\n\nprint (9**0.5)\nprint (math.sqrt(9))\n```\n\n## Logarithms\nAnother consideration for exponential values is the requirement occassionally to determine the exponent for a given number and base. In other words, how many times do I need to multiply a base number by itself to get the given result. This kind of calculation is known as the *logarithm*.\n\nFor example, consider the following expression:\n\n\\begin{equation}4^{?} = 16 \\end{equation}\n\nIn other words, to what power must you raise 4 to produce the result 16?\n\nThe answer to this is 2, because 4 x 4 (or 4 to the power of 2) = 16. The notation looks like this:\n\n\\begin{equation}log_{4}(16) = 2 \\end{equation}\n\nIn Python, you can calculate the logarithm of a number using the **log** function in the **math** package, indicating the number and the base:\n\n\n```python\nimport math\n\nx = math.log(16, 4)\nprint(x)\n```\n\nThe final thing you need to know about exponentials and logarithms is that there are some special logarithms:\n\nThe *common* logarithm of a number is its exponential for the base **10**. You'll occassionally see this written using the usual *log* notation with the base omitted:\n\n\\begin{equation}log(1000) = 3 \\end{equation}\n\nAnother special logarithm is something called the *natural log*, which is a exponential of a number for base ***e***, where ***e*** is a constant with the approximate value 2.718. This number occurs naturally in a lot of scenarios, and you'll see it often as you work with data in many analytical contexts. For the time being, just be aware that the natural log is sometimes written as ***ln***:\n\n\\begin{equation}log_{e}(64) = ln(64) = 4.1589 \\end{equation}\n\nThe **math.log** function in Python returns the natural log (base ***e***) when no base is specified. Note that this can be confusing, as the mathematical notation *log* with no base usually refers to the common log (base **10**). To return the common log in Python, use the **math.log10** function:\n\n\n```python\nimport math\n\n# Natural log of 29\nprint (math.log(29))\n\n# Common log of 100\nprint(math.log10(100))\n```\n\n## Solving Equations with Exponentials\nOK, so now that you have a basic understanding of exponentials, roots, and logarithms; let's take a look at some equations that involve exponential calculations.\n\nLet's start with what might at first glance look like a complicated example, but don't worry - we'll solve it step-by-step and learn a few tricks along the way:\n\n\\begin{equation}2y = 2x^{4} ( \\frac{x^{2} + 2x^{2}}{x^{3}} ) \\end{equation}\n\nFirst, let's deal with the fraction on the right side. The numerator of this fraction is x2 + 2x2 - so we're adding two exponential terms. When the terms you're adding (or subtracting) have the same exponential, you can simply add (or subtract) the coefficients. In this case, x2 is the same as 1x2, which when added to 2x2 gives us the result 3x2, so our equation now looks like this: \n\n\\begin{equation}2y = 2x^{4} ( \\frac{3x^{2}}{x^{3}} ) \\end{equation}\n\nNow that we've condolidated the numerator, let's simplify the entire fraction by dividing the numerator by the denominator. When you divide exponential terms with the same variable, you simply divide the coefficients as you usually would and subtract the exponential of the denominator from the exponential of the numerator. In this case, we're dividing 3x2 by 1x3: The coefficient 3 divided by 1 is 3, and the exponential 2 minus 3 is -1, so the result is 3x-1, making our equation:\n\n\\begin{equation}2y = 2x^{4} ( 3x^{-1} ) \\end{equation}\n\nSo now we've got rid of the fraction on the right side, let's deal with the remaining multiplication. We need to multiply 3x-1 by 2x4. Multiplication, is the opposite of division, so this time we'll multipy the coefficients and add the exponentials: 3 multiplied by 2 is 6, and -1 + 4 is 3, so the result is 6x3:\n\n\\begin{equation}2y = 6x^{3} \\end{equation}\n\nWe're in the home stretch now, we just need to isolate y on the left side, and we can do that by dividing both sides by 2. Note that we're not dividing by an exponential, we simply need to divide the whole 6x3 term by two; and half of 6 times x3 is just 3 times x3:\n\n\\begin{equation}y = 3x^{3} \\end{equation}\n\nNow we have a solution that defines y in terms of x. We can use Python to plot the line created by this equation for a set of arbitrary *x* and *y* values:\n\n\n```python\nimport pandas as pd\n\n# Create a dataframe with an x column containing values from -10 to 10\ndf = pd.DataFrame ({'x': range(-10, 11)})\n\n# Add a y column by applying the slope-intercept equation to x\ndf['y'] = 3*df['x']**3\n\n#Display the dataframe\nprint(df)\n\n# Plot the line\n%matplotlib inline\nfrom matplotlib import pyplot as plt\n\nplt.plot(df.x, df.y, color=\"magenta\")\nplt.xlabel('x')\nplt.ylabel('y')\nplt.grid()\nplt.axhline()\nplt.axvline()\nplt.show()\n```\n\nNote that the line is curved. This is symptomatic of an exponential equation: as values on one axis increase or decrease, the values on the other axis scale *exponentially* rather than *linearly*.\n\nLet's look at an example in which x is the exponential, not the base:\n\n\\begin{equation}y = 2^{x} \\end{equation}\n\nWe can still plot this as a line:\n\n\n```python\nimport pandas as pd\n\n# Create a dataframe with an x column containing values from -10 to 10\ndf = pd.DataFrame ({'x': range(-10, 11)})\n\n# Add a y column by applying the slope-intercept equation to x\ndf['y'] = 2.0**df['x']\n\n#Display the dataframe\nprint(df)\n\n# Plot the line\n%matplotlib inline\nfrom matplotlib import pyplot as plt\n\nplt.plot(df.x, df.y, color=\"magenta\")\nplt.xlabel('x')\nplt.ylabel('y')\nplt.grid()\nplt.axhline()\nplt.axvline()\nplt.show()\n```\n\nNote that when the exponential is a negative number, Python reports the result as 0. Actually, it's a very small fractional number, but because the base is positive the exponential number will always positive. Also, note the rate at which y increases as x increases - exponential growth can be be pretty dramatic.\n\nSo what's the practical application of this?\n\nWell, let's suppose you deposit $100 in a bank account that earns 5% interest per year. What would the balance of the account be in twenty years, assuming you don't deposit or withdraw any additional funds?\n\nTo work this out, you could calculate the balance for each year:\n\nAfter the first year, the balance will be the initial deposit ($100) plus 5% of that amount:\n\n\\begin{equation}y1 = 100 + (100 \\cdot 0.05) \\end{equation}\n\nAnother way of saying this is:\n\n\\begin{equation}y1 = 100 \\cdot 1.05 \\end{equation}\n\nAt the end of year two, the balance will be the year one balance plus 5%:\n\n\\begin{equation}y2 = 100 \\cdot 1.05 \\cdot 1.05 \\end{equation}\n\nNote that the interest for year two, is the interest for year one multiplied by itself - in other words, squared. So another way of saying this is:\n\n\\begin{equation}y2 = 100 \\cdot 1.05^{2} \\end{equation}\n\nIt turns out, if we just use the year as the exponent, we can easily calculate the growth after twenty years like this:\n\n\\begin{equation}y20 = 100 \\cdot 1.05^{20} \\end{equation}\n\nLet's apply this logic in Python to see how the account balance would grow over twenty years:\n\n\n```python\nimport pandas as pd\n\n# Create a dataframe with 20 years\ndf = pd.DataFrame ({'Year': range(1, 21)})\n\n# Calculate the balance for each year based on the exponential growth from interest\ndf['Balance'] = 100 * (1.05**df['Year'])\n\n#Display the dataframe\nprint(df)\n\n# Plot the line\n%matplotlib inline\nfrom matplotlib import pyplot as plt\n\nplt.plot(df.Year, df.Balance, color=\"green\")\nplt.xlabel('Year')\nplt.ylabel('Balance')\nplt.show()\n```\n", "meta": {"hexsha": "16244c75e66ea7b0529e5aa46d4ef6890b0511c1", "size": 15488, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "AI Professional/2 - Essential Mathematics For Artificial Intelligence/DAT256x/Module01/01-04-Exponentials Radicals and Logarithms.ipynb", "max_stars_repo_name": "2series/DataScience-Courses", "max_stars_repo_head_hexsha": "5ee71305721a61dfc207d8d7de67a9355530535d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-02-23T07:40:39.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-23T07:40:39.000Z", "max_issues_repo_path": "AI Professional/2 - Essential Mathematics For Artificial Intelligence/DAT256x/Module01/01-04-Exponentials Radicals and Logarithms.ipynb", "max_issues_repo_name": "2series/DataScience-Courses", "max_issues_repo_head_hexsha": "5ee71305721a61dfc207d8d7de67a9355530535d", "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": "AI Professional/2 - Essential Mathematics For Artificial Intelligence/DAT256x/Module01/01-04-Exponentials Radicals and Logarithms.ipynb", "max_forks_repo_name": "2series/DataScience-Courses", "max_forks_repo_head_hexsha": "5ee71305721a61dfc207d8d7de67a9355530535d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-12-05T11:04:58.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-26T10:42:08.000Z", "avg_line_length": 41.3013333333, "max_line_length": 525, "alphanum_fraction": 0.616089876, "converted": true, "num_tokens": 3161, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206738932334, "lm_q2_score": 0.9504109735045131, "lm_q1q2_score": 0.8571953056987144}} {"text": "## Ainsley Works on Problem Sets\n\nAinsley sits down on Sunday night to finish S problem sets, where S is a random variable that is equally likely to be 1, 2, 3, or 4. She learns C concepts from the problem sets and drinks D energy drinks to stay awake, where C and D are random and depend on how many problem sets she does. You know that $p_{C|S}(c|s) = 1/(2s+1)$ for $c \\in \\{ 0,1,\\ldots ,2s\\}.$ For each problem set she completes, regardless of concepts learned, she independently decides to have an energy drink with probability $q.$ That is, the number of energy drinks she has is binomial with parameters $q$ and $S:$\n\n$$\\begin{eqnarray}\n p_{D\\mid S}(d\\mid s) &= \\begin{cases} {s \\choose d}\\, q^d\\, (1-q)^{s-d} & d \\in \\{0,\\ldots,s\\} \\\\\n 0 & \\text{otherwise} \\end{cases}\n\\end{eqnarray}$$\n\nwhere ${n \\choose k} = \\frac{n!}{k!\\, (n-k)!}.$\n\n**Question:** Does the conditional entropy $H(C\\mid S=s)$ decrease, stay the same, or increase as $s$ increases from $1$ to $4?$\n\n\n[$\\times $] It decreases.
\n[$\\times $] It stays the same
\n[$\\checkmark$] It increases.\n\n**Solution:** Conditioned on $S=s, C$ is uniform from $0$ to $2s.$\n\n$$\\begin{align} H(C|S=s)&= \\sum _{c=0}^{2s} p_{C|S}(c|s) \\log \\frac{1}{p_{C|S}(c|s)}\\\\\t \t \n&= \\sum _{c=0}^{2s} \\frac{1}{2s+1} \\log \\frac{1}{\\frac{1}{2s+1}}\\\\\t \t \n&= \\log \\frac{1}{\\frac{1}{2s+1}}\\\\\t \t \n&= \\log (2s+1)\t \t \n\\end{align}$$\n\nAs $s$ increases, so does $\\log (2s+1).$\n\nWe can also see this intuitively: as $s$ increases, $c$ is uniform over a broader range of possibilities, which implies a higher entropy.\n\n\n```python\n%matplotlib inline\nfrom numpy import log2, arange\nimport matplotlib.pyplot as plt\n\nf = lambda x: - x * log2(x)\ng = lambda s: (2*s + 1) * f(1/(2*s+1))\n\ns = arange(1, 5, 1)\nplt.plot(s, g(s), '-', s, g(s), 'ro')\nplt.xlabel(\"$s$\")\nplt.ylabel(\"$H(C\\mid S=s)$\")\nplt.show()\n```\n\n**Question:** The next morning, her roommate notices that Ainsley drank $d$ energy drinks. What is the expected number of concepts that she learned?\n\nYou should derive a general expression for this although in the answer boxes below we only ask you to evaluate the expression for specific choices of $d$ and $q.$ If you're general expression is correct, your answers to these should also be correct.\n\n(Please be precise with at least 3 decimal places, unless of course the answer doesn't need that many decimal places. You could also put a fraction.)\n\n1. When $q=0.2, \\mathbb {E}[C | D = 1] =$ {{ans1}}\n2. When $q=0.5, \\mathbb {E}[C | D = 2] =$ {{ans2}}\n3. When $q=0.7, \\mathbb {E}[C | D = 3] =$ {{ans3}}\n\n**Solution:** We are interested in $\\mathbb {E}[C|D=d].$ Since we are given information about $C$ conditioned on $S,$ we will condition on $S$ and use total expectation. We will also use the fact that $C$ and $D$ are conditionally independent given $S:$\n\n$$\\begin{align}\n\\mathbb {E}[C|D=d] &= \\sum _{s=1}^4 \\mathbb {E}[C|D=d, S=s] \\mathbb {P}(S=s | D=d)\\\\ \t \n\\text {(by conditional independence)}\t&= \\sum _{s=1}^4 \\mathbb {E}[C|S=s] p_{S|D}(s|d)\\\\\t \t \n\\text {(by Bayes' rule)} &= \\sum _{s=1}^4 \\mathbb {E}[C|S=s] \\frac{p_{D|S}(d|s) p_ S(s)}{p_ D(d)}\\\\\t \t \n&= \\frac{\\sum _{s=1}^4 \\left(\\sum _{c=0}^{2s} c \\frac{1}{2s+1}\\right) p_{D|S}(d|s) p_ S(s)}{\\sum _{s=1}^4 p_{D|S}(d|s) p_ S(s)}\t\\\\ \t \n&=\\frac{\\sum _{s=1}^4 s \\cdot p_{D|S}(d|s) }{\\sum _{s=1}^4 p_{D|S}(d|s)}\\\\\t \t \n\\text {(since $p_{D|S}(d|s) = 0$ for $s < d$)}&= \\frac{\\sum _{s=d}^4 s \\cdot p_{D|S}(d|s) }{\\sum _{s=d}^4 p_{D|S}(d|s)}\t\\\\ \t \n&=\\frac{\\sum _{s=d}^4 s {s \\choose d} q^ d (1-q)^{s-d}}{\\sum _{s=d}^4 {s \\choose d} q^ d (1-q)^{s-d}}\n\\end{align}$$\nAnother solution that works is to compute $p_{C|D}(\\cdot \\mid d)$ and compute the expectation with respect to this distribution. This leads to a very similar set of steps as above.\n\n\n```python\nfrom scipy.misc import comb\nf = lambda s, d, q : comb(s, d) * (q ** d) * ((1 - q) ** (s - d))\nED = lambda d, q : sum([s * f(s, d, q) for s in range(d, 5)]) / \\\n sum([f(s, d, q) for s in range(d, 5)])\n\nans1 = \"{0:.3f}\".format(ED(1, 0.2))\nans2 = \"{0:.3f}\".format(ED(2, 0.5))\nans3 = \"{0:.3f}\".format(ED(3, 0.7))\n```\n\n**Question:** Is the mutual information $I(C ; D)$ greater than, less than, or equal to zero? You should assume that $q$ lies in the range $0 < q < 1.$\n\n\n[$\\checkmark$] Greater than 0
\n[$\\times $] Less than 0
\n[$\\times $] Equal to 0 \n\n**Solution:** $\\boxed {\\text {Greater than zero}}.$\n\nSince the conditional expectation in the previous part depends on $d,$ we can infer that they are not independent. We can also justify this intuitively: for example, knowing that $D=4$ guarantees that $S=4,$ and therefore changes our belief about $C$ (i.e., $C$ is more likely to take on higher values).\n\n## Consecutive Sixes\n\n**Question:** On average, how many times do you have to roll a fair six-sided die before getting two consecutive sixes?\n\nHint: Use total expectation.\n\n**Solution:** Let $\\mu = \\mathbb {E}[\\# \\text { rolls until we get two consecutive 6's}].$\n\nThe problem can be broken up into two events (that forms a partition of the sample space):\n\n- Event 1: The very first time we roll a 6, the roll right afterward is also a 6.\n\n The probability of this first event is $1/6.$ You can think of it as we will, with probability $1,$ roll a 6 in a finite amount of time, and then it's just the next roll that we are looking at the probability for, and rolling a 6 in this next roll happens with probability $1/6.$ (Note that the probability that we never see a 6 is $\\lim _{n \\rightarrow \\infty } (5/6)^ n = 0.$)\n\n Conditioned on this first event, let's compute the expected number of rolls until we get two consecutive 6's: The expected number of rolls until the first 6 is the expectation of a $\\text {Geo}(1/6)$ random variable, which is $1/(1/6) = 6.$ The event we are conditioning on says that the next roll is a 6, so there the conditional expectation here is just $6 + 1 = 7$ rolls.\n\n- Event 2: The very first time we roll a 6, the roll right afterward is not a 6.\n\n The probability for this second event is $5/6,$ i.e., the roll right after getting the first 6 is not a 6.\n\n Conditioned on this second event, let's compute the expected number of rolls until we get two consecutive 6's: The expected number of rolls until the first 6 is 6 rolls (again, this is the expectation of a $\\text {Geo}(1/6)$ random variable), and then the 7th roll is not a 6. And then we restart the whole process over. So the conditional expectation for this case is $7 + \\mu.$\n\nNow using the law of total expectation,\n\n$$\\begin{align}\n\\mu\t&= 7 \\cdot \\frac16 + (7 + \\mu ) \\frac56 \\\\\t \t \n&= \\frac76 + \\frac{35}6 + \\frac{5}{6}\\mu\\\\ \t \n&= \\frac{42}6 + \\frac{5}{6}\\mu ,\n\\end{align}$$\n\nso\n\n$$\\frac16 \\mu = \\frac{42}6,\\qquad {\\text {i.e.,}}\\qquad \\mu = \\boxed {42}.$$\n\n\n```python\n\n```\n", "meta": {"hexsha": "0015f8de6c6d57b341e26dce75a57c961cf09b16", "size": 29398, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "week04/06 Homework.ipynb", "max_stars_repo_name": "infimath/Computational-Probability-and-Inference", "max_stars_repo_head_hexsha": "e48cd52c45ffd9458383ba0f77468d31f781dc77", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-04-04T03:07:47.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-04T03:07:47.000Z", "max_issues_repo_path": "week04/06 Homework.ipynb", "max_issues_repo_name": "infimath/Computational-Probability-and-Inference", "max_issues_repo_head_hexsha": "e48cd52c45ffd9458383ba0f77468d31f781dc77", "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": "week04/06 Homework.ipynb", "max_forks_repo_name": "infimath/Computational-Probability-and-Inference", "max_forks_repo_head_hexsha": "e48cd52c45ffd9458383ba0f77468d31f781dc77", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-02-27T05:33:49.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-27T05:33:49.000Z", "avg_line_length": 131.2410714286, "max_line_length": 19852, "alphanum_fraction": 0.8251921899, "converted": true, "num_tokens": 2333, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475794701961, "lm_q2_score": 0.9086178938396674, "lm_q1q2_score": 0.8571424908169578}} {"text": "# Ejercicios tema 1 \nBlanca Cano Camarero\n\nANTES DE COMENZAR LAS PRÁCTCAS, LEED LE README \n\n\n\n```python\n# import básicos\nfrom sympy import * \n## declaraciones\nx = symbols(\"x\")\n```\n\n### Ejercicio 1\n1.- Demuestre que la ecuación $x^3+4 x^2=10$ tiene una única raíz en el intervalo $[1,2]$. Aproxime dicha raíz con el método de bisección con al menos 3 cifras decimales exactas. ¿Cuántas iteraciones serán necesarias para conseguir 5 cifras decimales exactas? Aproxime también la raíz con el método de Newton-Raphson partiendo del extremo adecuado hasta que la diferencia en valor absoluto, entre dos aproximaciones consecutivas sea inferior a $10^{-3}$.\n\n\n```python\n# La siguiente función se anula en donde la ecuación tiene solución\nf = x**4 + 4*x**2 - 10\n\nprint(f'en f(2)={f.evalf(subs={x:2})} y f(1)={f.evalf(subs={x:1})}')\n\n# análisis de la derivada\ndf = diff(f,x)\nprint(f'Los puntos donde se anula l aderiva son {solve(df)}')\nprint(f'en df(-1)={df.evalf(subs={x:-1})} y df(1)={df.evalf(subs={x:1})}')\n\n\n```\n\n en f(2)=22.0000000000000 y f(1)=-5.00000000000000\n Los puntos donde se anula l aderiva son [0, -sqrt(2)*I, sqrt(2)*I]\n en df(-1)=-12.0000000000000 y df(1)=12.0000000000000\n\n\nPor ser f un polinomio (clase infinito) y puesto que la derivada solo se anula en 0 y toma valores positivos en adelante; deducimos que la función $f$ es creciente a partir de 0. \n\nAdemás gracias al teorema de Bolzano sabemos que se anulará en un punto por ser $f(1)<0 2.5$ se tiene que $N^7>4 > - cos(N) + 3$ \n\nAdemás la solución estará próxima a 1, un dato ideal para utilzar `nsolve`.\n\n\n```python\n# segunda\nfii = x**7 + cos(x) -3\nplot(fii, xlim=(-2.5,2.5), ylim=(-10, 10) )\n# Por tanto calcula la única solución \nsol = nsolve(fii, 1)\n\nprint(f'La raíz para {fii} es {sol}')\n```\n\n## Ejercicio 6\n 6.- Aplicar los métodos de aceleración de la convergencia de Aitken y Steffensen a las sucesiones obtenidas para los distintos métodos\nprogramados en esta práctica y comparar los resultados. Para aplicar el método de aceleración de Steffensen, recuerde que para transformar cualquier ecuación de la forma $ f(x)=0 $ en un problema de puntos fijos $ g(x)=x $, la forma más simple puede ser definir $g(x)=x \\pm f(x)$.\n\n### Resolución\n\nOJO CUIDADO, algunos resultados no convergen a la solución, y es que el método de aceleración de convergencia no te aseguran de ello, si no que el cocienente de la sucesión de errores se vaya a cero.\n\nTambién influye cómo se haya obtenido $g$, es decir cómo se ha despejado la x para que quede sola y eso lo reflejo en que de una ecuación verá varios despejes distintos. \n\n\n```python\n# cada tupla contiene la función f de cada ejercicio, la semilla inicial \nimport aceleracionConvergencia as ac\n\n#Dejo comentado todos las funciones posibles porque de otra forma esto es muy pesado de meter y yo diría que la idea se entiende.\n#f=[(x**4 + 4*x**2 - 10,1),(x**3 -25,2),(x**3-x-1,1),(exp(x)-x**2 + 3*x -2,0),\n #(x**2 + 10*cos(x) + x,-2),(1,3* x**2 + exp(x)-1), (x**7 - x**4 +2,0),(x**7 + cos(x) -3,-1)]\n \nf =[x**4 + 4*x**2 - 10,exp(x)-x**2 + 3*x -2, x**3 -25, x**3 -25, exp(x)-x**2 + 3*x -2,exp(x)-x**2 + 3*x -2, x**2 + 10*cos(x) + x ]\n\nfor i in range(len(f)):\n gaux=[(10/(x*(x+4)),1),((x**2+2-exp(x))/3,1.4),(x**3+x-25,2.93), (25/x**2, 2.9),\n (exp(x)-x**2 + x+ 3*x -2,0.25), (1/3*(-exp(x)+x**2 + x +2),0.25), (-(x**2 + 10*cos(x)),-3.55), \n ] #(3* x**2 + x+ exp(x)-1 ,0.1)]\n def g(y):\n return gaux[i][0].evalf(subs={x:y})\n print(f'La aceleración de {f[i]} con semilla {gaux[i][1]} en {gaux[i][0]}:')\n ac.tablasAceleracion(g,gaux[i][1])\n\n```\n\n La aceleración de x**4 + 4*x**2 - 10 con semilla 1 en 10/(x*(x + 4)):\n Xn | Aitken |Stepheson \n 1 | | \n 2.00000000000000 | | \n 0.833333333333333 | 1.46153846153846 | \n 2.48275862068966 | 1.51666666666667 | \n 0.621306146572104 | 1.37815034468775 | 1.37815034468775\n 3.48280861316797 | 1.34654507131928 | 1.34654507131928\n 0.383712328149617 | 1.41935299784799 | 1.41935299784799\n 5.94500467589520 | 1.29391242913432 | 1.29391242913432\n 0.169138629713219 | 1.59554139423208 | 1.59554139423208\n 14.1811305766207 | 1.04384454082576 | 1.04384454082576\n 0.0387853985175662 | 2.35352259823629 | 2.35352259823629\n 63.8382487052382 | -0.974754625444874 | -0.974754625444874\n 0.00230910886112447 | 5.88011667047837 | 5.88011667047837\n La aceleración de -x**2 + 3*x + exp(x) - 2 con semilla 1.4 en x**2/3 - exp(x)/3 + 2/3:\n Xn | Aitken |Stepheson \n 1.4 | | \n -0.0317333222815582 | | \n 0.344080702698839 | 0.265943783305879 | \n 0.235899684121873 | 0.260079958147681 | \n 0.263200453939663 | 0.256071638322854 | 0.256071638322854\n 0.256062326008391 | 0.257530717992165 | 0.257530717992165\n 0.257911558186928 | 0.257530268398944 | 0.257530268398944\n 0.257431340610680 | 0.257530285669833 | 0.257530285669833\n 0.257555968396257 | 0.257530285435571 | 0.257530285435571\n 0.257523619331349 | 0.257530285439935 | 0.257530285439935\n 0.257532015678931 | 0.257530285439859 | 0.257530285439859\n 0.257529836344885 | 0.257530285439861 | 0.257530285439861\n 0.257530402005542 | 0.257530285439861 | 0.257530285439861\n La aceleración de x**3 - 25 con semilla 2.93 en x**3 + x - 25:\n Xn | Aitken |Stepheson \n 2.93 | | \n 3.08375700000000 | | \n 7.40892069048313 | 2.92433255570526 | \n 389.100179080503 | 3.03418434042021 | \n 58909722.4089418 | 2.92150143189044 | 2.92150143189044\n 2.04437672938503E+23 | 4.65717060612217 | 4.65717060612217\n 8.54442390811763E+69 | 0 | 0\n 6.23804293586468E+209 | nan | nan\n 2.42742085550551E+629 | nan | nan\n 1.43032667048473E+1888 | nan | nan\n 2.92621148325892E+5664 | nan | nan\n 2.50563109951439E+16993 | nan | nan\n 1.57308211140660E+50980 | nan | nan\n La aceleración de x**3 - 25 con semilla 2.9 en 25/x**2:\n Xn | Aitken |Stepheson \n 2.9 | | \n 2.97265160523187 | | \n 2.82912400000000 | 2.92441611166700 | \n 3.12346067761173 | 2.92560466792560 | \n 2.56252389048675 | 2.92402638779294 | 2.92402638779294\n 3.80718659474958 | 2.92394574212361 | 2.92394574212361\n 1.72477196110407 | 2.92455767849169 | 2.92455767849169\n 8.40381806645469 | 2.91880646378207 | 2.91880646378207\n 0.353986520684614 | 2.95840919148536 | 2.95840919148536\n 199.510868259849 | 2.21686496195687 | 2.21686496195687\n 0.000628068324895442 | 4.62750182697734 | 4.62750182697734\n 63376204.4287542 | -1055.80776950707 | -1055.80776950707\n 6.22425757889018E-15 | 99.8438526019454 | 99.8438526019454\n La aceleración de -x**2 + 3*x + exp(x) - 2 con semilla 0.25 en -x**2 + 4*x + exp(x) - 2:\n Xn | Aitken |Stepheson \n 0.25 | | \n 0.221525416687741 | | \n 0.0850071238216746 | 0.257504387790415 | \n -0.578472893261474 | 0.256892775322289 | \n -4.08776841696098 | 0.257526937369315 | 0.257526937369315\n -35.0441476682879 | 0.257732604822869 | 0.257732604822869\n -1370.26887646992 | 0.287528863010341 | 0.287528863010341\n -1883119.86932801 | 0.247735480396528 | 0.247735480396528\n -3546147974739.43 | -2.62847312700751 | -2.62847312700751\n -1.25751654587628E+25 | -34.0968756675720 | -34.0968756675720\n -1.58134786315260E+50 | 1073741481.68260 | 1073741481.68260\n -2.50066106429729E+100 | 0 | 0\n -6.25330575849244E+200 | nan | nan\n La aceleración de -x**2 + 3*x + exp(x) - 2 con semilla 0.25 en 0.333333333333333*x**2 + 0.333333333333333*x - 0.333333333333333*exp(x) + 0.666666666666667:\n Xn | Aitken |Stepheson \n 0.25 | | \n 0.342824861104086 | | \n 0.350477254406297 | 0.351164790235221 | \n 0.351188864597114 | 0.351261823088331 | \n 0.351255617399848 | 0.351262532505594 | 0.351262532505594\n 0.351261884184793 | 0.351262533522134 | 0.351262533522134\n 0.351262472557723 | 0.351262533522904 | 0.351262533522904\n 0.351262527798990 | 0.351262533522905 | 0.351262533522905\n 0.351262532985496 | 0.351262533522905 | 0.351262533522905\n 0.351262533472448 | 0.351262533522904 | 0.351262533522904\n 0.351262533518167 | 0.351262533522904 | 0.351262533522904\n 0.351262533522460 | 0.351262533522904 | 0.351262533522904\n 0.351262533522863 | 0.351262533522904 | 0.351262533522904\n La aceleración de x**2 + x + 10*cos(x) con semilla -3.55 en -x**2 - 10*cos(x):\n Xn | Aitken |Stepheson \n -3.55 | | \n -3.42495494033724 | | \n -2.12910813554661 | -3.56335517905669 | \n 0.764449677143187 | -4.47597038254420 | \n -7.80201698008086 | -3.77208967876199 | -3.77208967876199\n -61.3908816588683 | -17.7134524671622 | -17.7134524671622\n -3770.13495617214 | -0.308949401778629 | -0.308949401778629\n -14213927.3384249 | 4.40737816363196 | 4.40737816363196\n -202035730382025 | -6.23603888153457 | -6.23603888153457\n -4.08184363509983E+28 | -1899.79022616796 | -1899.79022616796\n -1.66614474614050E+57 | 0 | 0\n -2.77603831509158E+114 | nan | nan\n -7.70638872685652E+228 | nan | nan\n\n\n## Ejercicio 7\n 7.- Programar el método de Newton-Raphson acelerado para el caso de una raíz múltiple de una ecuación y comparar los resultados\ncon los que se obtienen mediante el empleo de los métodos de aceleración anteriores.\n\n### Solución\n\nLo que relentiza el método de convergencia Newton-Raphson para $f(x)$ son sus raíces múltiples, pero la función $\\mu(x) = f(x)/f'(x)$ tiene las misma raíces y ninguna múltiple, así que será tan sencillo como aplicarle Newton-Raphson a esa función. \n\n\n```python\nimport newtonRaphson as nr\n\nf = (x-2)*(x-2)\n\n#método sin acelerar \nraiz,mensaje, iteraciones = nr.newtonRaphson(f,100,max_iter=4)\n\nprint(f'Para el método tradicional la solución es {raiz}, tras {iteraciones} iteraciones')\n\ndf = 2*(x-2)\nm = simplify(f/df)\n\nraiz,mensaje, iteraciones = nr.newtonRaphson(m,100, max_iter=4)\n\nprint(f'Para el método acelerado la solución es {raiz}, tras {iteraciones} iteraciones')\n```\n\n Para el método tradicional la solución es 14.25, tras 4 iteraciones\n Para el método acelerado la solución es 2.0, tras 4 iteraciones\n\n\n## Ejercicio 8 \n\n 8.- Programar el conocido algoritmo de Horner para la evaluación de un polinomio y emplearlo de forma reiterativa para el cálculo del\ndesarrollo de Taylor de orden $ n$ de un polinomio cualquiera. Aprovecharlo también para programar una versión especial del método de Newton-Raphson para polinomios, evaluando tanto $ p(x_k ) $ como $ p'(x_k)$ mediante el citado algoritmo.\n\n### Solución\n\n El algoritmo de Horner se basa en sacar factor común $x$ para ahorrarse multiplicaciones, es decir si nuestro polinomio es de la forma $p = \\sum_{i=0}^n \\alpha_i x^i$ entonces el algoritmo de Horner sería, definimos $H(\\alpha_i) = \\alpha_i + x H(\\alpha_{i+1})$, con $H(\\alpha_n)=\\alpha_n x$ sería $p =H(\\alpha_0)$. \n \n Si ahora queremos calcular la derivada $d$ del polinomio expresado;\n \n \n para todo $i \\geq d$\nDefinimos $H_d(\\alpha_i) = \\frac{i!}{(i-d)!} \\alpha_i + x H_d(\\alpha_{i+1})$, con \n $H_d(\\alpha_n)=\\frac{n!}{(n-d)!}\\alpha_n x$ y sería $p =H_d(\\alpha_d)$. \n\n\n```python\nn=4\na = list(symbols('a0:'+ str(n)))\ndef horner(x,coef, d = 0):\n \n n = len(coef)\n salida = 0\n for i in range(n,d,-1):\n salida = factorial(i-1)/factorial(i-d-1)*coef[i-1] + x*salida\n\n \n return salida\n\nfor i in range(n+1):\n print(f' derivada {i}: {horner(x,a,i)}')\n\n```\n\n derivada 0: a0 + x*(a1 + x*(a2 + a3*x))\n derivada 1: a1 + x*(2*a2 + 3*a3*x)\n derivada 2: 2*a2 + 6*a3*x\n derivada 3: 6*a3\n derivada 4: 0\n\n\n#### Newton con horner\nPuede encontrar la implementación al final del fichero `newtonRaphson.py`\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "9f192668fee0169f83813a221e1ff4362ca7a8ed", "size": 78598, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "practica1-evaluacion_y_raices/EJERCICIOS.ipynb", "max_stars_repo_name": "BlancaCC/metodosNumericosII", "max_stars_repo_head_hexsha": "73fd6d8bc202a34af0d95d9ac17a3b671895314d", "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": "practica1-evaluacion_y_raices/EJERCICIOS.ipynb", "max_issues_repo_name": "BlancaCC/metodosNumericosII", "max_issues_repo_head_hexsha": "73fd6d8bc202a34af0d95d9ac17a3b671895314d", "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": "practica1-evaluacion_y_raices/EJERCICIOS.ipynb", "max_forks_repo_name": "BlancaCC/metodosNumericosII", "max_forks_repo_head_hexsha": "73fd6d8bc202a34af0d95d9ac17a3b671895314d", "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.2360616845, "max_line_length": 19264, "alphanum_fraction": 0.799931296, "converted": true, "num_tokens": 7677, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765187126079, "lm_q2_score": 0.9381240164387895, "lm_q1q2_score": 0.8571418854604825}} {"text": "```python\nimport numpy as np\nimport sympy as sy\nimport matplotlib.pyplot as plt\nfrom simtk import unit\n```\n\n# Harmonic Well Potential\n\nThe harmonic well potential is described by the following expression:\n\n\\begin{equation}\nf(x)=\\frac{1}{2} k \\left(x^2 + y^2 + z^2 \\right)\n\\end{equation}\n\nWhere $k$ is the only parameter and represents the stiffness of the harmonic potential -or the stiffness of the harmonic spring described by the hookes' law-. Notice that the potential for potential dimensions $Y$ and $Z$, has the same shape. In this way we have a three dimensional harmonic well. But let's see here only the proyection over a single dimension $X$ since $Y$ and $Z$ are decorrelated, and there by will behave as $X$.\n\n\n```python\ndef harmonic_well(x,k):\n return 0.5*k*x**2\n```\n\n\n```python\nk=5.0 * unit.kilocalories_per_mole/ unit.nanometers**2 # stiffness of the harmonic potential\n\nx_serie = np.arange(-5., 5., 0.05) * unit.nanometers\n\nplt.plot(x_serie, harmonic_well(x_serie, k), 'r-')\nplt.ylim(-1,5)\nplt.xlim(-2,2)\nplt.grid()\nplt.xlabel(\"X ({})\".format(unit.nanometers))\nplt.ylabel(\"Energy ({})\".format(unit.kilocalories_per_mole))\nplt.title(\"Harmonic Well\")\nplt.show()\n```\n\nDifferent values of $k$ can be tested to graphically see how this parameter accounts for the openness of the well's arms. Or, as it is described below, the period of oscillations of a particle of mass $m$ in a newtonian dynamics.\n\nThe hooks' law describes the force suffered by a mass attached to an ideal spring as:\n\n\\begin{equation}\nF(x) = -k(x-x_{0})\n\\end{equation}\n\nWhere $k$ is the stiffness of the spring and $x_{0}$ is the equilibrium position. Now, since the force is minus the gradient of the potential energy $V(x)$,\n\n\\begin{equation}\nF(x) = -\\frac{d V(x)}{dx},\n\\end{equation}\n\nwe can proof that the spring force is the result of the first harmonic potential derivative:\n\n\\begin{equation}\nV(x) = \\frac{1}{2} k (x-x_{0})^{2}\n\\end{equation}\n\nAnd the angular frequency of oscillations of a spring, or a particle goberned by the former potential, is:\n\n\\begin{equation}\n\\omega = \\sqrt{\\frac{k}{m}}\n\\end{equation}\n\nWhere $m$ is the mass of the particle. This way the potential can also be written as:\n\n\\begin{equation}\nV(x) = \\frac{1}{2} k (x-x_{0})^{2} = \\frac{1}{2} m \\omega^{2} (x-x_{0})^{2}\n\\end{equation}\n\nFinnally, the time period of these oscillations are immediately computed from the mass of the particle, $m$, and the stiffness parameter $k$. Given that by definition:\n\n\\begin{equation}\nT = 2\\pi / \\omega\n\\end{equation}\n\nThen:\n\n\\begin{equation}\nT = 2\\pi \\sqrt{\\frac{m}{k}}\n\\end{equation}\n\n## Working with this test system\n\nThis test system is fully documented in [HarmonicWell class API](../api/_autosummary/uibcdf_test_systems.HarmonicWell.html). Let's see an example of how to interact with it:\n\n\n```python\nfrom openmolecularsystems import HarmonicWell\n\nopen_molecular_system = HarmonicWell(n_particles = 1, mass = 32 * unit.amu,\n k=5.0 * unit.kilocalories_per_mole/unit.nanometers**2)\n```\n\nThe potential expression and the value of the parameters are stored in `potential`:\n\n\n```python\nopen_molecular_system.potential_expression\n```\n\n\n\n\n$\\displaystyle 0.5 k \\left(x^{2} + y^{2} + z^{2}\\right)$\n\n\n\n\n```python\nopen_molecular_system.parameters\n```\n\n\n\n\n {'n_particles': 1,\n 'mass': Quantity(value=32, unit=dalton),\n 'k': Quantity(value=5.0, unit=kilocalorie/(nanometer**2*mole))}\n\n\n\n\n```python\nopen_molecular_system.coordinates\n```\n\n\n\n\n Quantity(value=array([[0., 0., 0.]], dtype=float32), unit=nanometer)\n\n\n\n\n```python\nopen_molecular_system.topology\n```\n\n\n```python\nopen_molecular_system.system\n```\n\n\n\n\n >\n\n\n\nThere is a method to evaluate the potential at a given positions:\n\n\n```python\nopen_molecular_system.evaluate_potential([-1.5, 0.0, 0.0] * unit.nanometers)\n```\n\n\n\n\n Quantity(value=5.625, unit=kilocalorie/mole)\n\n\n\n\n```python\nposition = np.zeros((200,3), dtype=float) * unit.nanometers\nposition[:,0] = np.linspace(-5., 5., 200) * unit.nanometers\n\nplt.plot(position[:,0], open_molecular_system.evaluate_potential(position) , 'r-')\nplt.ylim(-1,5)\nplt.xlim(-2,2)\nplt.grid()\nplt.xlabel(\"X ({})\".format(unit.nanometers))\nplt.ylabel(\"Energy ({})\".format(unit.kilocalories_per_mole))\nplt.title(\"Harmonic Well\")\nplt.show()\n```\n\n\n```python\nopen_molecular_system.get_oscillations_time_period()\n```\n\n\n\n\n Quantity(value=7.770948260727904, unit=picosecond)\n\n\n\n\n```python\nopen_molecular_system.get_standard_deviation(300.0*unit.kelvin)\n```\n\n\n\n\n Quantity(value=0.3453002396733165, unit=nanometer)\n\n\n\n### Newtonian dynamics\n\n\n```python\ninitial_positions = np.zeros([1, 3], np.float32) * unit.nanometers\ninitial_positions[0,0] = 1.0 * unit.nanometers\n\nopen_molecular_system.set_coordinates(initial_positions)\n```\n\n\n```python\nfrom openmolecularsystems.tools.md import newtonian\ntraj_dict = newtonian(open_molecular_system, time=50.0*unit.picoseconds, saving_timestep=0.1*unit.picoseconds,\n integration_timestep=0.02*unit.picoseconds)\n```\n\n 100%|██████████| 2500/2500 [00:00<00:00, 8947.70it/s]\n\n\nWe can now plot the trajectory of the x coordinate:\n\n\n```python\nplt.plot(traj_dict['time'], traj_dict['coordinates'][:,0,0])\nplt.xlabel('time ({})'.format(traj_dict['time'].unit))\nplt.ylabel('X ({})'.format(traj_dict['coordinates'].unit))\nplt.show()\n```\n\nWe can wonder now if the period of these oscillations is in agreement with the value calculated above.\n\n\n```python\nmass = 32 * unit.amu\nT = 2*np.pi*np.sqrt(mass/k)\n\nprint('The period of the small oscillations around the minimum is',T)\n```\n\n The period of the small oscillations around the minimum is 7.770948260727904 ps\n\n\n\n```python\nopen_molecular_system.get_oscillations_time_period()\n```\n\n\n\n\n Quantity(value=7.770948260727904, unit=picosecond)\n\n\n\n\n```python\nplt.plot(traj_dict['time'], traj_dict['coordinates'][:,0,0])\nplt.axvline(T._value, color='gray', linestyle='--') # Period of the harmonic oscillations\nplt.xlabel('time ({})'.format(traj_dict['time'].unit))\nplt.ylabel('X ({})'.format(traj_dict['coordinates'].unit))\nplt.show()\n```\n\nRemember that the integration timestep must be smaller than $\\sim T/10.0$ to guarantee that no artifacts are introduced by the timestep size.\n\nThe newtonian dynamics can also include damping. This way we can simulate damped oscillations around the minimum.\n\n\n```python\ntraj_dict = newtonian(open_molecular_system, time=50.0*unit.picoseconds, saving_timestep=0.1*unit.picoseconds,\n integration_timestep=0.02*unit.picoseconds, friction=0.25/unit.picoseconds)\n```\n\n 100%|██████████| 2500/2500 [00:00<00:00, 8990.40it/s]\n\n\n\n```python\nplt.plot(traj_dict['time'], traj_dict['coordinates'][:,0,0])\nplt.xlabel('time ({})'.format(traj_dict['time'].unit))\nplt.ylabel('X ({})'.format(traj_dict['coordinates'].unit))\nplt.show()\n```\n\nWhat would be the friction value needed to enter in the overdamped regime?\n\n\n```python\ntraj_dict = newtonian(open_molecular_system, time=50.0*unit.picoseconds, saving_timestep=0.1*unit.picoseconds,\n integration_timestep=0.02*unit.picoseconds, friction=5.0/unit.picoseconds)\n```\n\n 100%|██████████| 2500/2500 [00:00<00:00, 8904.40it/s]\n\n\n\n```python\nplt.plot(traj_dict['time'], traj_dict['coordinates'][:,0,0])\nplt.xlabel('time ({})'.format(traj_dict['time'].unit))\nplt.ylabel('X ({})'.format(traj_dict['coordinates'].unit))\nplt.show()\n```\n\n### Stochastic Dynamics\n\n\n```python\nfrom openmolecularsystems.tools.md import langevin_NVT\n\ntraj_dict = langevin_NVT(open_molecular_system, time=0.5*unit.nanoseconds, saving_timestep=0.5*unit.picoseconds,\n integration_timestep=0.02*unit.picoseconds,\n friction=1.0/unit.picoseconds, temperature=300.0*unit.kelvin,\n initial_velocities='boltzmann')\n```\n\n 100%|██████████| 25000/25000 [00:00<00:00, 30010.47it/s]\n\n\nLet us see the time evolution of the coordinate $x$ of our single particle:\n\n\n```python\nplt.plot(traj_dict['time'], traj_dict['coordinates'][:,0,0])\nplt.xlabel('time ({})'.format(traj_dict['time'].unit))\nplt.ylabel('X ({})'.format(traj_dict['coordinates'].unit))\nplt.show()\n```\n\n\n```python\nopen_molecular_system.get_standard_deviation(300.0*unit.kelvin)\n```\n\n\n\n\n Quantity(value=0.3453002396733165, unit=nanometer)\n\n\n\n\n```python\nnp.std(traj_dict['coordinates'][:,0,0])\n```\n\n\n\n\n Quantity(value=0.36140549642467434, unit=nanometer)\n\n\n", "meta": {"hexsha": "fc09801bd70109b203f6196a63f0fb585fef464f", "size": 186692, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "docs/contents/harmonic_well/Harmonic_Well.ipynb", "max_stars_repo_name": "dprada/OpenMolecularSystems", "max_stars_repo_head_hexsha": "5787fc159f87091ec498cf23abd07c1c2aec6138", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-07-02T14:42:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-02T14:42:08.000Z", "max_issues_repo_path": "docs/contents/harmonic_well/Harmonic_Well.ipynb", "max_issues_repo_name": "dprada/OpenMolecularSystems", "max_issues_repo_head_hexsha": "5787fc159f87091ec498cf23abd07c1c2aec6138", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-07-25T02:28:07.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-25T02:28:07.000Z", "max_forks_repo_path": "docs/contents/harmonic_well/Harmonic_Well.ipynb", "max_forks_repo_name": "dprada/OpenMolecularSystems", "max_forks_repo_head_hexsha": "5787fc159f87091ec498cf23abd07c1c2aec6138", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-06-17T18:56:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-17T18:56:55.000Z", "avg_line_length": 258.5761772853, "max_line_length": 41544, "alphanum_fraction": 0.9270831101, "converted": true, "num_tokens": 2412, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026550642019, "lm_q2_score": 0.9343951552333004, "lm_q1q2_score": 0.8571231567746336}} {"text": "# Least Squares Simplification\n\nIn this notebook, we explore the implications of zero-mean distributions on a least squares fit.\n\nFirst, let $L$ be a block luma samples and $C$ the correspoding chroma samples\n\n\n```python\nfrom sympy import diff, Eq, expand, factor, Idx, IndexedBase, symbols, solveset, summation, init_printing \ninit_printing()\n\nN = symbols('N', integer='True')\na, b = symbols('alpha, beta', integer='True')\ni = symbols('i', cls=Idx)\nL = IndexedBase('L', shape=N)\nC = IndexedBase('C', shape=N)\n```\n\nNext, we define $e$ as the squarred prediction error from a linear model using zero-mean luma samples to predict chroma samples.\n\n\n```python\ne = summation((a*L[i] + b - C[i])**2, (i,0,N-1))\ne\n```\n\n## Equation for $\\alpha$\nTo minimize the error, we compute the derivative with respect to $\\alpha$ and expand the result\n\n\n```python\nda = diff(e, a).expand()\nda\n```\n\nSince $L$ is zero-mean, the sum Àof L is 0. As such, we can remove the middle term\n\n\n```python\ndazm = (factor(da.args[0]) + factor(da.args[1]) + factor(da.args[2])).subs(summation(L[i], (i,0,N-1)),0)\ndazm\n```\n\nWe solve for $\\alpha$ with the derivative equal to 0\n\n\n```python\nsolveset(Eq(dazm,0),a)\n```\n\nFrom this equation, we see that when $L$ is zero-mean, the equation of $\\alpha$ is simplified. \n\n\n## Equation for $\\beta$\nTo minimize the error, we compute the derivative with respect to $\\beta$ and expand the result\n\n\n```python\ndb = diff(e, b).expand()\ndb\n```\n\nSince $L$ is zero-mean, the sum of L is 0. As such, we can remove the middle term\n\n\n```python\ndbzm = (factor(db.args[0]) + factor(db.args[1]) + factor(db.args[2])).subs(summation((L[i]), (i,0,N-1)), 0)\ndbzm\n```\n\nWe solve for $\\beta$ with the derivative equal to 0\n\n\n```python\nsolveset(Eq(dbzm,0),b)\n```\n\nFrom this equation, we see that when $L$ is zero-mean, the equation of $\\beta$ is the average.\n", "meta": {"hexsha": "d844374201db81659b45c34a3b6314bff33e553e", "size": 22748, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/exploratory/0.02-luctrudeau-LeastSquaresSimplification.ipynb", "max_stars_repo_name": "luctrudeau/CfL-Analysis", "max_stars_repo_head_hexsha": "678cca209019b7ceafdef2634f49b96ff04831d4", "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": "notebooks/exploratory/0.02-luctrudeau-LeastSquaresSimplification.ipynb", "max_issues_repo_name": "luctrudeau/CfL-Analysis", "max_issues_repo_head_hexsha": "678cca209019b7ceafdef2634f49b96ff04831d4", "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": "notebooks/exploratory/0.02-luctrudeau-LeastSquaresSimplification.ipynb", "max_forks_repo_name": "luctrudeau/CfL-Analysis", "max_forks_repo_head_hexsha": "678cca209019b7ceafdef2634f49b96ff04831d4", "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": 64.2598870056, "max_line_length": 2670, "alphanum_fraction": 0.7139089151, "converted": true, "num_tokens": 556, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750360641185, "lm_q2_score": 0.8991213786215104, "lm_q1q2_score": 0.8571099646314403}} {"text": "# Cauchy-Euler Homogeneus Second Order ODE - Theory\n\nAn Cauchy-Euler second order ODE has the following format:\n \n$$x^2 \\frac{d^2 y}{dx^2} + px \\frac{dy}{dx} + qy(x)=0$$\n\n## The Equation's Solution\n\nThe general solution $y(x)$ for this type of equation is a linear combination of two fundamental solutions $y_1(x)$ and $y_1(x)$:\n\n$$y(x) = c_1y_1(x) + c_2y_2(x)$$\n\nwhere $c_1$ and $c_2$ are constants that must be found by solving de initial value problem.\n\nThe simplest way of solving Cauchy-Euler second order ODE is assuming the trial solution $y(x)=x^m$. For that, we have $y'(x)=mx^{m-1}$ and $y''(x)=m(m-1)x^{m-2}$, where $m$ is a constant that we must find.\n\nSubstituting $y(x)$ and its derivatives in the equation, we have:\n\n$$x^2[m(m-1)x^{m-2}] + px(mx^{m-1}) + qx^m = 0$$\n\nApplying the distributive property, we have:\n\n$$m^2 x^2 x^{m-2} - m x^2 x^{m-2} + px(mx^{m-1}) + qx^m = 0$$\n\nApplying $x^{a-b} = x^a/x^b$, we have:\n\n$$m^2 \\frac{x^2 x^m}{x^2} - m \\frac{x^2 x^m}{x^2} + pmx \\frac{x^m}{x} + qx^m = 0$$\n\nSimplifying:\n\n$$m^2 x^m - m x^m + pm x^m + qx^m = 0$$\n\nPutting $x^m$ in evidence:\n\n$$x^m[m^2 + m(p-1) + q] = 0$$\n\nAssuming that for $x \\neq 0$ there is no $m \\in \\mathbb{C}$ which satisfacts $x^m = 0$, we have:\n\n$$m^2 + m(p-1) + q = 0$$\n\nApplying the quadratic formula, we have $m_1 = \\frac{1 -p + \\sqrt{\\Delta}}{2}$ and $m_2 = \\frac{1 -p - \\sqrt{\\Delta}}{2}$, where $\\Delta = (p-1)^2 - 4q$.\n\n### Fundamental and General Solutions\n\nThe fundamental solutions $y_1(x)$ and $y_2(x)$ need to be linearly independent. This linear independence can be verified by the Wronskian. The characteristc equation can have two real roots, one real root or two complex roots, and there are a pair of fundamentally linearly independent solutions for each of these cases.\n\n#### Case $\\Delta > 0$\n\nIn this case, $m_1, m_2 \\in \\mathbb{R}$ and $m_1 \\neq m_2$.\n\nThe fundamental solutions are $y_1(x)=x^{m_1}$ and, $y_2(x)=x^{m_2}$.\n\nThe general solution is:\n\n$$y(x) = c_1 x^{m_1} + c_2 x^{m_2}$$\n\nwhere $c_1, c_2 \\in \\mathbb{R}$.\n\n#### Case $\\Delta = 0$\n\nIn this case, $m = m_1 = m_2$ and $m \\in \\mathbb{R}$.\n\nThe fundamental solutions are $y_1(x)=x^{m}\\ln(x)$ and, $y_2(x)=x^{m}$.\n\nThe general solution is:\n\n$$y(x) = c_1 x^{m} \\ln(x) + c_2 x^{m}$$\n\nwhere $c_1, c_2 \\in \\mathbb{R}$.\n\n#### Case $\\Delta < 0$\n\nIn this case, $m_1, m_2 \\in \\mathbb{C}$. These roots are $m_1 = \\alpha + \\beta i$ and $m_2 = \\alpha - \\beta i$.\n\nThe fundamental solutions are $y_1(x)=x^{m_1}$ and, $y_2(x)=x^{m_2}$. Applying $x^{a+b} = x^ax^b$, $e^{\\ln x} = x$ and $(x^a)^b = x^{ab}$, we have:\n\n$$y_1(x) = x^{m_1} = x^{\\alpha + \\beta i} = x^{\\alpha}x^{\\beta i} = x^{\\alpha}(e^{\\ln x})^{\\beta i} = x^{\\alpha} e^{i\\beta \\ln x }$$ \n\nand\n\n$$y_2(x) = x^{m_2} = x^{\\alpha - \\beta i} = x^{\\alpha}e^{-i\\beta \\ln x}$$\n\nApplying Euler's indentity ($e^{i\\theta} = \\cos\\theta + i\\sin\\theta$), we have:\n\n$$y_1(x) = x^{\\alpha} [\\cos(\\beta \\ln x) + i\\sin(\\beta \\ln x)]$$ \n\nand \n\n$$y_2(x) = x^{\\alpha}[\\cos(\\beta \\ln x) - i \\sin(\\beta \\ln x)]$$\n\nFinally, the general solution is:\n\n$$y(x) = c_1 x^{m_1} + c_2 x^{m_2} = x^\\alpha [k_1 \\cos(\\beta \\ln x) + k_2 \\sin(\\beta \\ln x)]$$\n\nwhere $c_1, c_2, k_1, k_2$ are constants.\n\n# Practice with Python\n\n## Solving the Cauchy-Euler Homogeneus Second-Order ODE\nIn this practice, we will use the algebraic manipulation of the **SymPy** symbolic math package, numeric features of the **NumPy** package and the plotting from the **MatPlotLib** package. For first, we will import these packages.\n\n\n```python\nfrom sympy import *\nfrom matplotlib import pyplot as plt\nimport numpy as np\n```\n\nNow, we gonna define a function to give the roots of the characteristic equation.\n\n\n```python\ndef get_characteristic_eq_roots(p, q):\n m = Symbol('m') #Defines the unknown m\n\n c_eq = Eq(m**2 + m*(p-1) + q, 0) #Gets SymPy's characteristic equation\n\n c_eq_roots = solve(c_eq, m) #Gets the l roots of the c_eq \n \n return c_eq_roots\n```\n\nThis function returns a list of symbolic roots, that can be two real roots, a single real root or two complex roots. Look that at the following example:\n\n\n```python\nprint('Real roots (p=-3, q=2): ', get_characteristic_eq_roots(-3, 2))\nprint('Complex roots (p=1, q=1): ', get_characteristic_eq_roots(1, 1))\nprint('Single root (p=3, q=1): ', get_characteristic_eq_roots(3, 1))\n```\n\n Real roots (p=-3, q=2): [2 - sqrt(2), sqrt(2) + 2]\n Complex roots (p=1, q=1): [-I, I]\n Single root (p=3, q=1): [-1]\n\n\nNow, we gonna define a function to give the fundamental solutions of the ODE.\n\n\n```python\ndef get_ODE_fundamental_solutions(x, p, q):\n c_eq_roots = get_characteristic_eq_roots(p, q)\n \n if len(c_eq_roots) == 1:# Single real root\n m = c_eq_roots[0] #Root lambda\n \n y1 = x**m #fundamental solution y1(x)\n y2 = ln(x)*(x**m) #fundamental solution y2(x)\n \n return [y1, y2]\n \n elif len(c_eq_roots) == 2: #Two roots\n if c_eq_roots[0].is_real == True and c_eq_roots[1].is_real == True: # Real roots\n m1 = c_eq_roots[1] #Root lambda1\n m2 = c_eq_roots[0] #Root lambda2\n \n y1 = x**m1 #fundamental solution y1(x)\n y2 = x**m2 #fundamental solution y2(x)\n \n return [y1, y2]\n \n elif c_eq_roots[0].is_real == False and c_eq_roots[1].is_real == False: # Complex roots\n m1 = c_eq_roots[1] #Root lambda1\n m2 = c_eq_roots[0] #Root lambda2\n \n alpha = re(m1) #Real part of the roots\n beta = abs(im(m1)) #Absolute imaginary part of the roots\n \n y1 = (x**alpha)*( cos(beta*ln(x)) + I*sin(beta*ln(x))) #fundamental solution y1(x)\n y2 = (x**alpha)*( cos(beta*ln(x)) - I*sin(beta*ln(x))) #fundamental solution y2(x)\n \n return [y1, y2]\n \n else: #Error\n raise Exception('Unexpected answer from the get_characteristic_eq_roots function.')\n \n else: #Error\n raise Exception('Unexpected answer from the get_characteristic_eq_roots function.')\n```\n\nThis function returns a list of symbolic fundamental solutions. Look that at the following examples:\n\n\n```python\nx = Symbol('x')\n\nprint('p=-3, q=2: ', get_ODE_fundamental_solutions(x, -3, 2))\nprint('p=1, q=1: ', get_ODE_fundamental_solutions(x, 1, 1))\nprint('p=3, q=1: ', get_ODE_fundamental_solutions(x, 2, 1))\n```\n\n p=-3, q=2: [x**(sqrt(2) + 2), x**(2 - sqrt(2))]\n p=1, q=1: [I*sin(log(x)) + cos(log(x)), -I*sin(log(x)) + cos(log(x))]\n p=3, q=1: [(I*sin(sqrt(3)*log(x)/2) + cos(sqrt(3)*log(x)/2))/sqrt(x), (-I*sin(sqrt(3)*log(x)/2) + cos(sqrt(3)*log(x)/2))/sqrt(x)]\n\n\nNow, we gonna define a function to give the symbolic general solution.\n\n\n```python\ndef get_ODE_solution(x, p, q, c1, c2):\n fundamental_solutions = get_ODE_fundamental_solutions(x, p, q)\n \n y1 = fundamental_solutions[0] #Fundamental solution y1(x)\n y2 = fundamental_solutions[1] #Fundamental solution y2(x)\n \n y = c1*y1 + c2*y2 #General solution y(x)\n \n return y\n```\n\nTesting...\n\n\n```python\nx, c1, c2 = Symbol('x'), Symbol('c1'), Symbol('c2')\n\nprint('p=-3, q=2: ', get_ODE_solution(x, -3, 2, c1, c2))\nprint('p=1, q=1: ', get_ODE_solution(x, 1, 1, c1, c2))\nprint('p=2, q=1: ', get_ODE_solution(x, 2, 1, c1, c2))\n```\n\n p=-3, q=2: c1*x**(sqrt(2) + 2) + c2*x**(2 - sqrt(2))\n p=1, q=1: c1*(I*sin(log(x)) + cos(log(x))) + c2*(-I*sin(log(x)) + cos(log(x)))\n p=2, q=1: c1*(I*sin(sqrt(3)*log(x)/2) + cos(sqrt(3)*log(x)/2))/sqrt(x) + c2*(-I*sin(sqrt(3)*log(x)/2) + cos(sqrt(3)*log(x)/2))/sqrt(x)\n\n\nFinally, we will define a function to give the $y(x)$ values for any $x$ input in the ODE solution.\n\n\n```python\ndef get_ODE_function(p, q, c1, c2):\n x = Symbol('x')\n \n symbolic_solution = get_ODE_solution(x, p, q, c1, c2)\n \n y_function = lambdify(x, symbolic_solution)\n \n return y_function\n```\n\n## Plotting $y(x)$\nPlotting $y(x)$ from $y''(x) - 3y'(x) + 2y(x) = 0$ with $c_1 = c_2 = 1$: \n\n\n```python\np, q, c1, c2 = (-3, 2, 1, 1)\ny = get_ODE_function(p, q, c1, c2) #y(x) function\nx = np.linspace(0,20,500) #500 dots in [0, 20]\nplt.plot(x,y(x).real) #Plot the real part of y(x)\nplt.show()\n```\n\nPlotting $y(x)$ from $y''(x) + 2y'(x) + 20y(x) = 0$ with $c_1 = c_2 = 1$: \n\n\n```python\np, q, c1, c2 = (2, 20, 1, 1)\ny = get_ODE_function(p, q, c1, c2) #y(x) function\nx = np.linspace(0,20,500) #500 dots in [0, 20]\nplt.plot(x,y(x).real) #Plot the real part of y(x)\nplt.show()\n```\n\nPlotting $y(x)$ from $y''(x) + y'(x) + 10y(x) = 0$ with $c_1 = c_2 = 1$: \n\n\n```python\np, q, c1, c2 = (1, 10, 1, 1)\ny = get_ODE_function(p, q, c1, c2) #y(x) function\nx = np.linspace(0,20,500) #500 dots in [0, 20]\nplt.plot(x,y(x).real) #Plot the real part of y(x)\nplt.show()\n```\n", "meta": {"hexsha": "bff9c16d8aefd7f97cbc8ef36b98008ec8fb2fb2", "size": 61240, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "ODE/second_order/Cauchy-Euler_Homogeneus_SO_ODE.ipynb", "max_stars_repo_name": "FilipeChagasDev/Calculus-for-Programmers", "max_stars_repo_head_hexsha": "97a78eb2f1e6d4aa63b5bed31ff171acf287839e", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-05-24T13:02:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-15T15:00:34.000Z", "max_issues_repo_path": "ODE/second_order/Cauchy-Euler_Homogeneus_SO_ODE.ipynb", "max_issues_repo_name": "FilipeChagasDev/Calculus-for-Programmers", "max_issues_repo_head_hexsha": "97a78eb2f1e6d4aa63b5bed31ff171acf287839e", "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": "ODE/second_order/Cauchy-Euler_Homogeneus_SO_ODE.ipynb", "max_forks_repo_name": "FilipeChagasDev/Calculus-for-Programmers", "max_forks_repo_head_hexsha": "97a78eb2f1e6d4aa63b5bed31ff171acf287839e", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-08-15T15:00:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-15T15:00:35.000Z", "avg_line_length": 128.6554621849, "max_line_length": 20788, "alphanum_fraction": 0.8533148269, "converted": true, "num_tokens": 3256, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037343628703, "lm_q2_score": 0.9252299612154571, "lm_q1q2_score": 0.8570439682182915}} {"text": "# Projection Experiment\nIn the open source implementation of [dehazing with color lines by Tomlk](https://github.com/Tomlk/Dehazing-with-Color-Lines), the distance metric that is used during ransac is different from the metric mentioned in [Fattal paper](https://www.cse.huji.ac.il/~raananf/projects/dehaze_cl/). We will explore the validty of this alternative form. \n\n\n## Fattal's Formula\nFattal paper's defines the similarity metric (distance) between two direction as follows (paraphrased): \n\n$D = I(x_2) - I(x_1)$ - Direction vector of the color line. \n$V = I(x_1)$ - Point on the color line. \n$\\Omega$ - The set of pixels in an image patch\n\nEach line is associted with pixels $x \\in \\Omega$ that support it, i.e., pixels in which $I(x)$ is sufficiently close to the line. **This is measured by projecting $I(x) - V$ onto the plane perpendicular to $D$ and computing the norm of the projected vector.** In our implementation we associate a pixel with the line if the norm falls below $2 \\times 10^{-2}$.\n\nLet $\\hat{D} = I(x) - V$. \nFattal's formula can be written as: \n\n$$Distance = ||\\hat{D}-\\frac{\\hat{D}\\cdot D}{||D||^{2}}D||$$ \nThe projection onto the plane is calculated as $\\hat{D}$ minus its component that is not orthogonal to $D$.\n$$ $$\n\n\n## Tomlk's Formula\nThe formula used in Tomlk's implementation can be written as: \n \n$$||\\frac{D\\times\\hat{D}}{||D||}||$$ \n \nNo further explanation is provided, so we will have to figure it out ourselves. Intuitively, the fraction makes sense as the norm of the cross product will increase when the angle between $D$ and $\\hat{D}$ is larger (the norm of the cross product equals the [area of the parallelogram](https://en.wikipedia.org/wiki/Cross_product)). The denominator $||D||$ may possibly be a scalar that removes any effect the magnitude of $D$ may have (thereby treating it as a unit vector). Before proving the equality of these formulas, we can test them to rule out some obvious counter examples.\n\n\n```python\nimport numpy as np \nnp.random.seed(2)\n\ndef explicit_project(vec1, vec2): \n \"\"\" Returns length of projection of vec2 onto a plane perpendicular to vec1. \n Fattal's Formula.\n \"\"\"\n dot = np.dot(vec2, vec1)\n squared_norm = np.linalg.norm(vec1)**2\n proj_onto_vec1 = (dot / squared_norm) * vec1\n proj_onto_plane = vec2 - proj_onto_vec1\n result = np.linalg.norm(proj_onto_plane)\n result = abs(result)\n return result\n\ndef implicit_project(vec1, vec2):\n \"\"\" Returns the length of the cross project scaled to the lenght of vec1.\n Tomlk's Formula. \n \"\"\"\n cross_product = np.cross(vec1, vec2)\n norm = np.linalg.norm(vec1)\n scaled_cross_product = cross_product / norm \n result = np.linalg.norm(scaled_cross_product)\n result = abs(result)\n return result \n\ndifferences = list()\nfor i in range(1000):\n v1 = np.random.rand(3)\n v2 = np.random.rand(3)\n # Randomly scale random vectors\n v1 = v1 * np.random.randint(1000)\n v2 = v2 * np.random.randint(1000)\n explicit = explicit_project(v1, v2)\n implicit = implicit_project(v1, v2)\n difference = explicit - implicit\n differences.append(difference)\n \ndifferences = np.array(differences)\nprint('The largest difference is equal to : {}'.format(differences.max()))\n# The largest difference is equal to : 2.2737367544323206e-13\n```\n\n The largest difference is equal to : 2.2737367544323206e-13\n\n\nSuch a small difference over so many samples is a good sign. Now let's prove the equality.\n\n## Equality proof\n\n$$||\\hat{D}-\\frac{\\hat{D}\\cdot D}{||D||^{2}}D|| = ||\\frac{D\\times\\hat{D}}{||D||}||$$ \n$$||\\hat{D}-proj_{D}\\hat{D}|| = ||\\frac{D\\times\\hat{D}}{||D||}|| $$\n\nGiven the propetry $||\\frac{\\vec{1}}{x}|| = \\frac{||\\vec{1}||}{x}$\n\n$$ = \\frac{||D \\times \\hat{D}||}{||D||} $$ \n\nGiven the property $||a\\times b|| = ||a||\\hspace{0.1cm}||b||sin(\\theta)$\n\n$$ = \\frac{||D||\\hspace{0.1cm}||\\hat{D}||sin(\\theta)}{||D||}$$ \n\n$$= ||\\hat{D}||sin(\\theta)$$ \n\nNow if we draw $D$, $\\hat{D}$, $P = proj_{D}\\hat{D}$, and $W = \\hat{D}-P$$ we have: \n
\n\n
\n\n\nWe see the vectors draw compose a right triangle : \nWith a hypotenuse of length $||\\hat{D}||$ \nTwo legs of length $||P|| = ||proj_{D}\\hat{D}||$ \nand $||W|| = ||\\hat{D}-proj_{D}\\hat{D}||$ \n\nLet us consider the trigonometric definition of sin. \n \n \n
\n\n
\n\nThis means that \n\\begin{align}\nsin(\\theta) &= \\frac{||W||}{||\\hat{D}||} \\newline \\newline\n&= \\frac{||\\hat{D}-proj_{D}\\hat{D}||}{||\\hat{D}||}\n\\end{align}\n\nNow we all necessary steps to complete the proof: \n\n\\begin{align}\n||\\hat{D}-proj_{D}\\hat{D}|| &= ||\\frac{D\\times\\hat{D}}{||D||}||\\newline \\newline\n &= \\frac{||D \\times \\hat{D}||}{||D||} \\newline \\newline\n &= \\frac{||D||\\hspace{0.1cm}||\\hat{D}||sin(\\theta)}{||D||} \\newline \\newline\n &= ||\\hat{D}||sin(\\theta) \\newline \\newline\n &= ||\\hat{D}|| \\frac{||\\hat{D}-proj_{D}\\hat{D}||}{||\\hat{D}||} \\newline \\newline\n &= ||\\hat{D}-proj_{D}\\hat{D}|| \\newline \\newline\n ||\\hat{D}-proj_{D}\\hat{D}|| &= ||\\hat{D}-proj_{D}\\hat{D}||\n\\end{align}\n \n$$ True $$\n\n", "meta": {"hexsha": "3f9b6cdf4230c111e2d015f6d44bac71a707076a", "size": 8019, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Experiment_notebooks/2_projection_experiment.ipynb", "max_stars_repo_name": "LittleLittleZE/dehazing_using_color_lines", "max_stars_repo_head_hexsha": "86609bee3f1cbe9bb17af915d9a18b83a744044c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2021-01-12T08:44:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T04:56:12.000Z", "max_issues_repo_path": "Experiment_notebooks/2_projection_experiment.ipynb", "max_issues_repo_name": "LittleLittleZE/dehazing_using_color_lines", "max_issues_repo_head_hexsha": "86609bee3f1cbe9bb17af915d9a18b83a744044c", "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": "Experiment_notebooks/2_projection_experiment.ipynb", "max_forks_repo_name": "LittleLittleZE/dehazing_using_color_lines", "max_forks_repo_head_hexsha": "86609bee3f1cbe9bb17af915d9a18b83a744044c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-05-03T08:45:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-01T00:48:23.000Z", "avg_line_length": 33.835443038, "max_line_length": 589, "alphanum_fraction": 0.5328594588, "converted": true, "num_tokens": 1600, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299570920387, "lm_q2_score": 0.9263037343628702, "lm_q1q2_score": 0.8570439643987536}} {"text": "# Probability in Python\n\n# Importing packages\n\nYou can ignore this part for now.\n\n\n```python\nimport numpy as np\n```\n\n# Import statistics module\nWe will use scipy.stats, which has several functions for statistics and probability distributions. \n\n\n```python\nimport scipy.stats as st\n```\n\n# Import pandas, matplotlib\n\n\n```python\nimport pandas as pd\nimport matplotlib.pyplot as plt\n```\n\n# Function for uniform outcome\n\n$n$: number of outcomes in the sample space\n\nOutput: $m$ outcomes selected uniformly at random from 1 to $n$\n\n\n```python\ndef uniform(n, m):\n return np.random.randint(1, n+1, size = m)\n```\n\n# Toss a coin\n\nToss once, 10 times and 100 times\n\n1: Heads and 2: Tails\n\n\n```python\nprint(uniform(2, 1))\nprint(uniform(2, 10))\nprint(uniform(2,100))\n```\n\n [1]\n [2 1 1 1 1 1 2 2 1 2]\n [1 1 2 2 1 1 1 1 1 1 1 2 2 1 1 1 1 2 2 1 1 1 1 2 2 2 1 1 1 2 2 2 1 2 1 1 2\n 1 2 2 1 1 2 1 2 1 1 2 1 2 2 2 2 1 1 2 1 1 1 2 2 1 2 2 1 2 2 1 2 2 2 1 1 2\n 1 2 1 1 2 1 1 2 1 2 1 1 2 1 2 2 1 2 1 2 1 1 1 1 1 2]\n\n\n# Throw a die\n\nThrow once, 10 times and 100 times\n\n\n```python\nprint(uniform(6, 1))\nprint(uniform(6, 10))\nprint(uniform(6,100))\n```\n\n [4]\n [6 2 2 5 3 2 3 1 1 3]\n [3 6 2 3 1 1 3 5 5 3 5 5 2 6 1 4 5 1 6 2 6 5 3 3 1 2 3 3 6 2 6 5 6 5 3 3 1\n 2 3 3 1 6 1 5 6 5 5 2 4 3 4 6 2 5 6 2 2 3 3 5 2 1 1 4 3 2 1 1 4 6 1 4 2 6\n 4 5 4 5 5 2 3 1 2 1 5 1 1 3 5 3 5 3 5 6 1 4 5 1 6 1]\n\n\n# Estimating probability by simulation - Monte Carlo\n\nThe probability of an event $A$ can be estimated as follows. We can simulate the experiment repeatedly and independently, say $N$ times, and count the number of times the event occurred, say $N_A$. \n\nA good estimate of $P(A)$ is the following:\n$$P(A) \\approx \\frac{N_A}{N}$$\nAs $N$ grows larger and larger, the estimate becomes better and better. This method is generally termed as Monte Carlo simulation.\n\nWe will first evaluate probability of coin toss described above using Monte Carlo simulations. There are two steps: generate a large number of tosses and count the number of heads or tails. These two steps can be written in a single loop usually.\n\nYou should run the simulation multiple times to see what probability estimate is obtained each time. You will see that the estimate is close to 0.5.\n\n\n```python\nno_heads = 0 #variable for storing number of heads\nfor i in range(1000): #repeat 1000 times\n if uniform(2, 1) == 1: #check if coin toss is heads\n no_heads = no_heads + 1\nprint(no_heads/1000) #probability estimate by Monte Carlo\n```\n\n 0.492\n\n\n# Probability of die showing a number\n\nWe will modify the Monte Carlo simulation above for finding the probability that a dies shows a number falling in an event $A$. You will see that the estimate is close to $P(A)$. If you change the loop iterations to 10000, the estimate will be much closer to $P(A)$ and more consistent as well. \n\n\n```python\nno = 0 #variable for storing number of event occurence\nfor i in range(10000): #repetitions\n die = uniform(6,1) #experiment\n if die == 1 or die == 3: #Event\n no = no + 1\nprint(no/10000) #probability estimate by Monte Carlo\n```\n\n 0.3361\n\n\n# Birthday problem\n\nIn a group of $n$ persons, what is the chance that some two have the same birthday? Assume birthday of a person is uniformly distributed in $\\{1,2,\\ldots,365\\}$ and is independent of all other birthdays. Most people will think that you need at least 100 persons before you start seeing same birthdays. However, surprisingly perhaps, even with 23 persons there is a 50% chance of two sharing a birthday.\n\nEvent $A$: some two have same birthday\n\nEvent $A^c$: no two have same birthday\n\n$A^c$: (Birthday 1 on any date $B_1$) and (Birthday 2 on any date other than $B_1$) and (Birthday 3 on any date other than $B_1$, $B_2$) and ... and (Birthday $n$ on any day other than $B_1,B_2,\\ldots,B_{n-1}$)\n\n$P(A^c)= 1 \\cdot \\left(1 - \\frac{1}{365}\\right)\\left(1 - \\frac{2}{365}\\right)\\cdots\\left(1 - \\frac{n-1}{365}\\right)$\n\nIf $n=10$, what is the chance? If $n=30$, what is the chance?\n\nWe will do a Monte Carlo simulation to estimate the probability and compare with the calculation above.\n\n\n```python\nno = 0 #variable for storing number of event occurence\nn = 60 #number of persons\nprint(1 - np.prod(1-np.arange(1,n)/365)) #probability from expression\n\nfor i in range(1000):\n B = np.zeros(366) #array to keep track of birthdays seen\n for j in range(n): #generate birthdays for each person\n Bi = uniform(365, 1) #i-th birthday\n if B[Bi] == 0: #if Bi is seen for the first time\n B[Bi] = 1 #make note that Bi has been seen\n else:\n no = no + 1 #if Bi has been seen before, then two birthdays are same \n break #we can stop generating more birthdays and exit loop early\n\nprint(no/1000) #probability estimate by Monte Carlo\n```\n\n 0.994122660865348\n 0.996\n\n\n# Monty Hall problem\n\nHere is the problem taken from the [Wiki page](https://en.wikipedia.org/wiki/Monty_Hall_problem).\n\n> Suppose you're on a game show, and you're given the choice of three doors: Behind one door is a car; behind the others, goats. You pick a door, say No. 1, and the host, who knows what's behind the doors, opens another door, say No. 3, which has a goat. He then says to you, \"Do you want to pick door No. 2?\" Is it to your advantage to switch your choice?\n\nThe assumptions (also taken from [Wiki](https://en.wikipedia.org/wiki/Monty_Hall_problem)) are as follows:\n1. Car and goats are placed at random behind the doors.\n2. Host always picks a door not chosen by contestant.\n3. Host always reveals a goat and not a car.\n4. Host always offers a choice to switch from the original door to the other closed door.\n\nUnder the above assumptions, here are the probabilities of winning.\n\nP(win if contestant chooses to switch) = 2/3\n\nP(win if contestant does not switch) = 1/3\n\nYou can see the Wiki page for the computation. Let us simulate and find the probability of winning under switch by Monte Carlo.\n\n\n```python\nno = 0 #variable for storing number of event occurence\nfor i in range(1000):\n car_loc = uniform(3, 1)\n if car_loc == 1:\n goat1_loc = 2; goat2_loc = 3\n elif car_loc == 2:\n goat1_loc = 1; goat2_loc = 3\n else:\n goat1_loc = 1; goat2_loc = 2\n\n contestant_orig = uniform(3, 1)\n if contestant_orig == goat1_loc:\n host_reveal_loc = goat2_loc; other_closed_door = car_loc\n elif contestant_orig == goat2_loc:\n host_reveal_loc = goat1_loc; other_closed_door = car_loc\n else:\n host_reveal_loc = goat1_loc; other_closed_door = goat2_loc\n if other_closed_door == car_loc:\n no = no + 1\n\nprint(no/1000) #probability estimate by Monte Carlo\n```\n\n 0.663\n\n\n# Polya's urn scheme\n\nSuppose an urn contains $r$ red and $b$ blue balls. The experiment proceeds in multiple steps, where Step $i$ is as follows:\n\nStep $i$: Draw a ball at random, note down its colour and replace it in the urn. Add $c$ more balls of the same colour to the urn.\n\nLet $R_i$ be the event that the $i$-th ball drawn is red. Let $B_i$ be the event that the $i$-th abll drawn is black.\n\nClearly, $P(R_1) = \\frac{r}{r+b}$ and $P(B_1)=\\frac{b}{r+b}$. It is perhaps surprising that, irrespective of $c$, we have, for all $i$,\n$$P(R_i) = \\frac{r}{r+b}, P(B_i) = \\frac{b}{r+b}.$$\nTo prove the above, you can use induction. Assume that the above is true for $i$ and show it is true for $i+1$. Starting with $i=1$, by induction, the statement becomes true.\n\nWe will setup a Monte Carlo simulation for verifying $P(R_i)$ above for a few steps.\n\n\n```python\nno = 0 #variable for storing number of event occurence\nr = 10; b = 5 #assume 1 to r is red and r+1 to r+b is blue\nprint(r/(r+b))\nfor i in range(1000):\n r = 10; b = 5\n c = 3\n for j in range(5): #do 5 steps\n if uniform(r+b, 1) <= r:\n r = r + c\n else:\n b = b + c\n if uniform(r+b, 1) <= r: #in the 6th step, count if red ball drawn\n no = no + 1\nprint(no/1000) #probability estimate by Monte Carlo\n```\n\n 0.6666666666666666\n 0.66\n\n\n# Gambler's ruin (simple random walk)\n\nA gambler starting with $k$ units of money plays the following game at a casino:\n\n* If he has $\\ge 1$ units of money, a coin is tossed. If heads, the casino pays him 1 unit. If tails, he loses 1 unit to the casino.\n* If he loses all money, he goes bankrupt and stops.\n* If he gets $N$ units of money, he wins and stops playing.\n\nIf $p$ is the probability of heads and $q=1-p$, it can be shown that\n$$\\text{Pr}(\\text{Bankruptcy})=\\begin{cases}\n1-k/N,&\\text{ if }p=q=1/2,\\\\\n\\frac{\\left(\\dfrac{q}{p}\\right)^k-\\left(\\dfrac{q}{p}\\right)^N}{1-\\left(\\dfrac{q}{p}\\right)^N}, &\\text{ if }p\\ne q.\n\\end{cases}$$\nYou can see some details of the proof of the above in the [Wiki page](https://en.wikipedia.org/wiki/Gambler%27s_ruin). Suppose $x_k$ denotes the probability of bankruptcy starting with $k$ units. The main idea is to condition on the first toss and derive the following recursive equation:\n$$\\begin{align}\nx_k&=P(\\text{Bankruptcy}\\ |\\ \\text{first toss is head})\\ p\\ +\\ P(\\text{Bankruptcy}\\ |\\ \\text{first toss is tail})\\ q\\\\\n&=x_{k+1}p+x_{k-1}q\n\\end{align}$$\nwith boundary conditions $x_0=1$ and $x_N=0$. Solution of the recursive equation results in the above closed form expression for $x_k$.\n\nWe are interested in Monte Carlo simulation of Gambler's ruin and verification of the formula for $x_k$. First, we consider the case $p=1/2$.\n\n\n```python\nno = 0 #variable for storing number of event occurence\nk = 5; N = 10\nprint(1-k/N)\nfor i in range(1000):\n k = 5\n while k > 0 and k < N:\n if uniform(2, 1) == 1:\n k = k + 1\n else:\n k = k - 1\n if k == 0:\n no = no + 1\nprint(no/1000) #probability estimate by Monte Carlo\n```\n\n 0.5\n 0.505\n\n\n# Toss a biased coin\n\nFor $p\\ne q$, we require a method to toss a biased coin. This is accomplished by the following function that generates $m$ coin tosses with probability of heads equal to $p$. Note that a value of 1 represents heads and 2 represents tails as before.\n\n\n```python\ndef biased(p, m):\n return 2-(np.random.rand(m) < p)\n```\n\n\n```python\nno_heads = 0 #variable for storing number of heads\np = 0.25\nprint(p)\nfor i in range(1000):\n if biased(p, 1) == 1:\n no_heads = no_heads + 1\nprint(no_heads/1000) #probability estimate by Monte Carlo\n```\n\n 0.25\n 0.253\n\n\n# Biased Gambler's ruin\n\nWe now simulate the biased version of Gambler's ruin.\n\n\n```python\nno = 0 #variable for storing number of event occurence\np = 0.35\nqbyp = (1-p)/p\nk = 5; N = 10\nprint((qbyp**k-qbyp**N)/(1-qbyp**N))\nfor i in range(1000):\n k = 5\n while k > 0 and k < N:\n if biased(p, 1) == 1:\n k = k + 1\n else:\n k = k - 1\n if k == 0:\n no = no + 1\nprint(no/1000) #probability estimate by Monte Carlo\n```\n\n 0.9566941509920124\n 0.964\n\n\n# Casino die game\nThrow a pair of die. A player bets $k_1$ units of money on whether the sum of the two numbers is Under 7 or Over 7, and $k_2$ units on Equal to 7. For Under 7 and Over 7, the returns are $a$:1, while, for Equal to 7, the returns are $b$:1, if the player wins the bet. If the bet is lost, the unit of money goes to the casino.\n\nThe strategy for betting will be to independently and randomly select one of the 3 bets. The simulation will track the average return over a large number of trails.\n\n\n```python\na = 1.0; b = 4.0\nk1 = 1; k2 = 1\nprint((((a-1)*5-7)*k1+((b-1)-5)*k2)/6/3) #expected gain\navg_return = 0\nfor i in range(1000):\n bet = uniform(3,1) #1 - Under 7, 2 - Over 7, 3 - Equal to 7\n sum = uniform(6,1) + uniform(6,1)\n if ((bet == 1) and (sum < 7)) or ((bet == 2) and (sum > 7)): #win for Under 7 or Over 7 bet\n avg_return = avg_return + k1*(a-1)/1000\n if (bet == 3) and (sum == 7): #win for Equal to 7 bet\n avg_return = avg_return + k2*(b-1)/1000\n if ((bet == 1) and (sum >= 7)) or ((bet == 2) and (sum <= 7)): #loss for Under 7 or Over 7 bet\n avg_return = avg_return + (-k1)/1000\n if (bet == 3) and (sum != 7): #loss for Equal to 7 bet\n avg_return = avg_return + (-k2)/1000\n \nprint(avg_return) #simulated gain\n```\n\n -0.5\n -0.5080000000000005\n\n\n# Expected value of common distributions\nThe module has functions for generating binomial, geometric, Poisson and other distributions. We will generate a large number of samples and compute the average value and compare with the expected value.\n\n\n```python\n#binomial(20,0.3)\nprint(20*0.3) #expected value\nx = st.binom.rvs(20,0.3,size=1000)\nprint(np.sum(x)/1000) #average value in simulation\n```\n\n 6.0\n 6.062\n\n\n\n```python\n#geometric(0.3)\nprint(1/0.3) #expected value\nx = st.geom.rvs(0.3,size=1000)\nprint(np.sum(x)/1000) #average value in simulation\n```\n\n 3.3333333333333335\n 3.276\n\n\n\n```python\n#Poisson(6)\nprint(6) #expected value\nx = st.poisson.rvs(6,size=1000)\nprint(np.sum(x)/1000) #average value in simulation\n```\n\n 6\n 6.029\n\n\n# Balls and bins\nSuppose $m$ balls are thrown independently and uniformly at random into $n$ bins. We will compute the expected number of empty bins by simulation and compare with the theoretical value of $n(1-1/n)^m\\approx ne^{-m/n}$.\n\n\n```python\nm = 10; n = 3\nprint(n*((1-1/n)**m)) #expected value\navg_empty_bins = 0\nfor i in range(1000):\n no_balls = np.zeros(n, dtype=int) #keep track of balls in bins\n for ball in range(m):\n bin = uniform(n, 1)\n no_balls[bin-1] += 1\n\n no_empty_bins = 0\n for bin in range(n):\n if no_balls[bin] == 0:\n no_empty_bins += 1\n\n avg_empty_bins += no_empty_bins/1000.0\n\nprint(avg_empty_bins) #average value in simulation\n```\n\n 0.0520245897474979\n 0.05600000000000004\n\n\n# Common continuous distributions and histograms\nScipy stats module can be used to generate samples from common continuous distributions. We will generate a number of such samples and plot their histogram to confirm that the samples follow the expected density function.\n\nFor histograms, we will use the hist() function from the matplotlib.pyplot module imported below.\n\n## Uniform distribution\nWe will begin with the uniform distribution.\n\n\n```python\nx = st.uniform.rvs(0,3,size=10000)\nplt.hist(x,bins=50,range=(0,3),density=True) #blue histogram\nplt.plot([-0.2,0,0,3,3,3.2],[0,0,1.0/3,1.0/3,0,0],lw=2) #orange line. uniform[0,3] density\nplt.show()\n```\n\n## From histogram to density\nThe code above generates 10000 samples that are supposed to be independent and uniformly distributed in $[0,3]$. The histogram, created using the plt.hist command, uses 100 bins of equal width in the range $[0,3]$. So, the bins are $[0,0.03),[0.03,0.06),\\ldots,[2.97,3]$. \n\nSuppose the number of samples that fall into the bin $[0,0.03]$ is $N_0$. Then, by Monte Carlo, we have that \n$$P(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 \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
Col1
038.026635
1409.445210
2272.463390
398.674526
487.858008
......
3930321.296880
3931146.966750
3932184.342160
393384.361201
3934218.148090
\n

3935 rows × 1 columns

\n\n\n\n\nWe see that there are 3935 samples of data. To get a sense of the distribution, we should plot a histogram.\n\n\n```python\nplt.hist(df['Col1'],bins=50)\n```\n\n# Fitting a Gamma distribution\nFrom the histogram, the distribution could be modelled as Gamma$(\\alpha,\\beta)$. The next step is to estimate $\\alpha$ and $\\beta$ from the given samples.\n\n## Method of moments\nSuppose $m_1$ and $m_2$ are the first and second moments of the samples. The method of moments estimates are obtained by solving\n$$m_1=\\frac{\\alpha}{\\beta},$$\n$$m_2=\\frac{\\alpha^2}{\\beta^2}+\\frac{\\alpha}{\\beta^2}.$$\nThe solution results in\n$$\\hat{\\alpha}_{MM}=\\frac{m_1^2}{m_2-m_1^2}=\\frac{m_1^2}{s^2},\\hat{\\beta}_{MM}=\\frac{m_1}{m_2-m_1^2}=\\frac{m_1}{s^2}.$$\nWe now compute the values of $m_1$ (sample mean) and $s^2=m_2-m_1^2$ (sample variance) from the data. After that, we can compute the estimates.\n\n\n```python\nx = np.array(df['Col1'])\nm1 = np.average(x)\nss = np.var(x)\nprint(m1)\nprint(ss)\n\n```\n\n 79.93522014279034\n 6311.67624499251\n\n\n\n```python\nalphaMM = m1*m1/ss\nbetaMM = m1/ss\nprint(alphaMM)\nprint(betaMM)\n```\n\n 1.0123522137792949\n 0.012664657856335469\n\n\nWe can plot the density of the Gamma on top of the density histogram to check if the estimate gives a reasonable fit.\n\n\n```python\nfig,ax = plt.subplots(1,1)\nax.hist(x,density=True,bins=50)\nxx = np.linspace(0,300,50)\nax.plot(xx, st.gamma.pdf(xx,alphaMM,scale=1/betaMM),label='gamma fit MM')\nax.legend(loc='best')\nplt.show()\n```\n\n# Bootstrap\nHow do we find the bias and variance of the estimator? Theoretical derivations of the sampling distributions may be too cumbersome and difficult in most cases. Bootstrap is a Monte Carlo simulation method for computing metrics such as bias, variance and confidence intervals for estimators.\n\nIn the above example, we have found $\\hat{\\alpha}_{MM}=1.0123...$ and $\\hat{\\beta}_{MM}=0.01266...$. Using these values, we simulate $n=3935$ *iid* samples from Gamma$(1.0123...,0.0126...)$ and, using the simulated samples, we compute new estimates of $\\alpha$ and $\\beta$ and call them $\\hat{\\alpha}_{MM}(1)$ and $\\hat{\\beta}_{MM}(1)$. Now, repeat the simulation $N$ times to get estimates $\\hat{\\alpha}_{MM}(i)$ and $\\hat{\\beta}_{MM}(i)$, $i=1,2,\\ldots,N$.\n\nThe sample variance of $\\{\\hat{\\alpha}_{MM}(1), \\hat{\\alpha}_{MM}(2),\\ldots,\\hat{\\alpha}_{MM}(N)\\}$ is taken to be the bootstrap estimate for the variance of the estimator.\n\n\n```python\nN = 1000\nn = 3935\nalpha_hat = np.zeros(N)\nbeta_hat = np.zeros(N)\nfor i in np.arange(N):\n xi = st.gamma.rvs(alphaMM,scale=1/betaMM,size=n)\n m1i = np.average(xi); ssi = np.var(xi)\n alpha_hat[i] = m1i*m1i/ssi; beta_hat[i] = m1i/ssi\n```\n\nWe can see the histograms of the estimates to get an idea of the spread of the values.\n\n\n```python\nax1 = plt.subplot(121)\nax1.hist(alpha_hat,density=True)\nax2 = plt.subplot(122)\nax2.hist(beta_hat,density=True)\n```\n\nNotice how the histograms look roughly normal.\n\nThe sample standard deviations of the estimates is a bootstrap estimate for the standard error of the estimator.\n\n\n```python\nprint(np.sqrt(np.var(alpha_hat)))\nprint(np.sqrt(np.var(beta_hat)))\n```\n\n 0.031822357311654136\n 0.000449581400441715\n\n\n## Confidence intervals\nSuppose a parameter $\\theta$ is estimated as $\\hat{\\theta}$, and suppose the distribution of $\\hat{\\theta}-\\theta$ is known. Then, to obtain $(100(1-\\alpha))$% confidence intervals (typical values are $\\alpha=0.1$ for 90% confidence intervals and $\\alpha=0.05$ for 95% confidence intervals), we use the CDF of $\\hat{\\theta}-\\theta$ to obtain $\\delta_1$ and $\\delta_2$ such that\n$$P(\\hat{\\theta}-\\theta\\le\\delta_1)=1-\\frac{\\alpha}{2},$$\n$$P(\\hat{\\theta}-\\theta\\le\\delta_2)=\\frac{\\alpha}{2}.$$\nActually, the inverse of the CDF of $\\hat{\\theta}-\\theta$ is used to find the above $\\delta_1$ and $\\delta_2$. From the above, we see that\n$$P(\\hat{\\theta}-\\theta \\le \\delta_1)-P(\\hat{\\theta}-\\theta \\le \\delta_2)= P(\\delta_2< \\hat{\\theta}-\\theta \\le \\delta_1)=1-\\frac{\\alpha}{2}-\\frac{\\alpha}{2}=1-\\alpha.$$\nThe above is rewritten as\n$$P(\\hat{\\theta}-\\delta_1\\le\\theta<\\hat{\\theta}-\\delta_2)=1-\\alpha,$$\nand $[\\hat{\\theta}-\\delta_1,\\hat{\\theta}-\\delta_2]$ is interpreted as the $100(1-\\alpha)$% confidence interval.\n\n## Bootstrap confidence intervals\nThe CDF of $\\hat{\\theta}-\\theta$ might be difficult to determine in many cases, and the bootstrap method is used often to estimate $\\delta_1$ and $\\delta_2$. We consider the list of numbers $\\{\\hat{\\alpha}_{MM}(1)-1.0123...,\\ldots,\\hat{\\alpha}_{MM}(N)-1.0123...\\}$ and pick the $100(\\alpha/2)$-th percentile and $100(1-\\alpha/2)$-th percentile.\n\n\n```python\ndel1 = np.percentile(alpha_hat - alphaMM, 97.5)\ndel2 = np.percentile(alpha_hat - alphaMM, 2.5)\nprint([del1,del2])\n```\n\n [0.06149537903410332, -0.06043329601919404]\n\n\nThe 95% confidence interval for $\\alpha$ using the method of moments estimator works out to $[1.0123-0.0615,1.0123-(-0.0604)]=[0.9508,1.0727]$.\n\n## Maximum likelihood\nWe now turn to the maximum likelihood estimator for $\\alpha$ and $\\beta$. The likelihood $L(x_1,\\ldots,x_n)$ can be written as\n$$L = \\frac{\\beta^\\alpha}{\\Gamma(\\alpha)}x_1^{\\alpha-1}e^{-\\beta x_1}\\,\\frac{\\beta^\\alpha}{\\Gamma(\\alpha)}x_2^{\\alpha-1}e^{-\\beta x_2}\\cdots \\frac{\\beta^\\alpha}{\\Gamma(\\alpha)}x_n^{\\alpha-1}e^{-\\beta x_n}= \\frac{\\beta^{n\\alpha}}{\\Gamma(\\alpha)^n}(x_1\\cdots x_n)^{\\alpha-1}e^{-\\beta(x_1+\\cdots+x_n)},$$\n$$\\log L = n\\alpha\\log\\beta-n\\log\\Gamma(\\alpha)+(\\alpha-1)\\log(x_1\\cdots x_n)-\\beta(x_1+\\cdots+x_n).$$\nDifferentiating $\\log L$ with respect to $\\beta$ and equating to zero, we get\n$$n\\alpha\\frac{1}{\\beta}-(x_1+\\cdots+x_n)=0,\\text{or }\\alpha=\\beta \\frac{x_1+\\cdots+x_n}{n}.$$\nDifferentiating $\\log L$ with respect to $\\alpha$ and equating to zero, we get\n$$n\\log\\beta-n\\frac{\\Gamma'(\\alpha)}{\\Gamma(\\alpha)}+\\log(x_1\\cdots x_n)=0.$$\nSo, we get two equations in the two variables $\\alpha$ and $\\beta$. However, the equations do not have a closed form solution, and we need to solve them numerically or approximately. From the first equation, we have $\\log\\beta=\\log\\alpha-\\log\\frac{x_1+\\cdots+x_n}{n}$. Using this in the second equation, we get\n$$\\log\\alpha - \\frac{\\Gamma'(\\alpha)}{\\Gamma(\\alpha)}=\\log\\frac{x_1+\\cdots+x_n}{n}-\\frac{1}{n}\\log(x_1\\cdots x_n).$$\nWe will now solve the above equation to find the ML estimate of $\\alpha$. This will be a numerical solution.\n\n\n```python\nlm1 = np.average(np.log(x))\n#Write the equation as a function\n#digamma is the function Gamma'/Gamma\nfrom scipy.special import digamma\nfML = lambda a: (np.log(a) - digamma(a) - np.log(m1)+lm1)\n```\n\nWe can plot the above function to see how it looks.\n\n\n```python\nfig, ax = plt.subplots(1,1)\n\nxx = np.linspace(0.1,2,50)\nax.plot(xx,fML(xx))\nax.grid(True)\nplt.show()\n```\n\n\n```python\n#For solving numerically, we will use scipy.optimize\nimport scipy.optimize as sopt\nsol = sopt.root_scalar(fML, bracket=[0.1,2])\nsol.root\n```\n\n\n\n\n 1.0263317358725452\n\n\n\n\n```python\nalphaML = sol.root\nbetaML = alphaML/m1\nprint([alphaML, betaML])\n```\n\n [1.0263317358725452, 0.012839543495835532]\n\n\nLet us check the fit with the histogram.\n\n\n```python\nfig,ax = plt.subplots(1,1)\nax.hist(x,density=True,bins=50)\nxx = np.linspace(0,300,50)\nax.plot(xx, st.gamma.pdf(xx,alphaMM,scale=1/betaMM),lw='4',alpha=0.7,label='gamma fit MM')\nax.plot(xx, st.gamma.pdf(xx,alphaML,scale=1/betaML),lw='1',label='gamma fit ML')\nax.legend(loc='best')\nplt.show()\n```\n\nBoth the curves are literally on top of each other showing very good fit. Let us use the bootstrap method to find variance and confidence intervals for the ML estimator.\n\n\n```python\nN = 1000\nn = 3935\nalpha_hatML = np.zeros(N)\nbeta_hatML = np.zeros(N)\nfor i in np.arange(N):\n xi = st.gamma.rvs(alphaMM,scale=1/betaMM,size=n)\n m1i = np.average(xi); lm1i = np.average(np.log(xi))\n fMLi = lambda a: (np.log(a) - digamma(a) - np.log(m1i)+lm1i)\n soli = sopt.root_scalar(fMLi, bracket = [0.1,2]) \n alpha_hatML[i] = soli.root; beta_hatML[i] = soli.root / m1i\n```\n\n\n```python\nprint(np.sqrt(np.var(alpha_hatML)))\nprint(np.sqrt(np.var(beta_hatML)))\n```\n\n 0.01988186514427374\n 0.0003157550854393247\n\n\nWe see that the variance of the bootstrap ML estimator is lesser than that of bootstrap MM estimator.\n", "meta": {"hexsha": "8188dcb4d1a510edd1b40f2d0a9de3be87020a28", "size": 437584, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Statistics/stats.ipynb", "max_stars_repo_name": "tanav2202/100-days-python-and-Ml", "max_stars_repo_head_hexsha": "70ac964a98103bc68ebdf1d03bebc625ace93cac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-12-17T19:47:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-13T16:19:54.000Z", "max_issues_repo_path": "Statistics/stats.ipynb", "max_issues_repo_name": "tanav2202/100-days-python-and-Ml", "max_issues_repo_head_hexsha": "70ac964a98103bc68ebdf1d03bebc625ace93cac", "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": "Statistics/stats.ipynb", "max_forks_repo_name": "tanav2202/100-days-python-and-Ml", "max_forks_repo_head_hexsha": "70ac964a98103bc68ebdf1d03bebc625ace93cac", "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": 211.5976789168, "max_line_length": 273604, "alphanum_fraction": 0.8891412849, "converted": true, "num_tokens": 10214, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037262250325, "lm_q2_score": 0.9252299627617389, "lm_q1q2_score": 0.8570439621212468}} {"text": "# 2022-03-28 Gradient Descent\n\n## Last time\n\n* Assumptions of linear models\n* Look at your data!\n* Partial derivatives\n* Loss functions\n\n## Today\n\n* Discuss projects\n* Gradient-based optimization for linear models\n* Nonlinear models\n\n\n```julia\nusing LinearAlgebra\nusing Plots\ndefault(linewidth=4, legendfontsize=12)\n\nfunction vander(x, k=nothing)\n if isnothing(k)\n k = length(x)\n end\n m = length(x)\n V = ones(m, k)\n for j in 2:k\n V[:, j] = V[:, j-1] .* x\n end\n V\nend\n\nfunction vander_chebyshev(x, n=nothing)\n if isnothing(n)\n n = length(x) # Square by default\n end\n m = length(x)\n T = ones(m, n)\n if n > 1\n T[:, 2] = x\n end\n for k in 3:n\n #T[:, k] = x .* T[:, k-1]\n T[:, k] = 2 * x .* T[:,k-1] - T[:, k-2]\n end\n T\nend\n\nfunction chebyshev_regress_eval(x, xx, n)\n V = vander_chebyshev(x, n)\n vander_chebyshev(xx, n) / V\nend\n\nrunge(x) = 1 / (1 + 10*x^2)\nrunge_noisy(x, sigma) = runge.(x) + randn(size(x)) * sigma\n\nCosRange(a, b, n) = (a + b)/2 .+ (b - a)/2 * cos.(LinRange(-pi, 0, n))\n\nvcond(mat, points, nmax) = [cond(mat(points(-1, 1, n))) for n in 2:nmax]\n```\n\n\n\n\n vcond (generic function with 1 method)\n\n\n\n# Workshopping projects today\n\n* Maybe you've started, maybe you're still looking for a good project\n* What have you been thinking about?\n* What do you need help on?\n\n## Each breakout group will report out\n1. One interesting thing about process\n2. One question you have relevant to the projects (specific or general)\n3. One question from content we've covered\n\n# Variational notation for derivatives\n\nIt's convenient to express derivatives in terms of how they act on an infinitessimal perturbation. So we might write\n\n$$ \\delta f = \\frac{\\partial f}{\\partial x} \\delta x .$$\n\n(It's common to use $\\delta x$ or $dx$ for these infinitesimals.) This makes inner products look like a normal product rule\n\n$$ \\delta(\\mathbf x^T \\mathbf y) = \\mathbf y^T (\\delta \\mathbf x) + \\mathbf x^T (\\delta \\mathbf y). $$\n\nA powerful example of variational notation is differentiating a matrix inverse\n\n$$ 0 = \\delta I = \\delta(A^{-1} A) = (\\delta A^{-1}) A + A^{-1} (\\delta A) $$\nand thus\n$$ \\delta A^{-1} = - A^{-1} (\\delta A) A^{-1} $$\n\n# Optimization for linear models\nGiven data $(x,y)$ and loss function $L(c; x,y)$, we wish to find the coefficients $c$ that minimize the loss, thus yielding the \"best predictor\" (in a sense that can be made statistically precise). I.e.,\n$$ \\bar c = \\arg\\min_c L(c; x,y) . $$\n\nIt is usually desirable to design models such that the loss function is differentiable with respect to the coefficients $c$, because this allows the use of more efficient optimization methods. Recall that our forward model is given in terms of the Vandermonde matrix,\n\n$$ f(x, c) = V(x) c $$\n\nand thus\n\n$$ \\frac{\\partial f}{\\partial c} = V(x) . $$\n\n# Derivative of loss function\n\nWe now differentiate our loss function\n$$ L(c; x, y) = \\frac 1 2 \\lVert f(x, c) - y \\rVert^2 $$\nusing a more linear algebraic approach to write the same expression is\n\\begin{align} \\nabla_c L(c; x,y) &= \\big( f(x,c) - y \\big)^T V(x) \\\\\n&= \\big(V(x) c - y \\big)^T V(x) \\\\\n&= V(x)^T \\big( V(x) c - y \\big) .\n\\end{align}\nA necessary condition for the loss function to be minimized is that $\\nabla_c L(c; x,y) = 0$.\n\n* Is the condition sufficient for general $f(x, c)$?\n* Is the condition sufficient for the linear model $f(x,c) = V(x) c$?\n* Have we seen this sort of equation before?\n\n## Gradient descent\n\nInstead of solving the least squares problem using linear algebra (QR factorization), we could solve it using gradient descent. That is, on each iteration, we'll take a step in the direction of the negative gradient.\n\n\n```julia\nfunction grad_descent(loss, grad, c0; gamma=1e-3, tol=1e-5)\n \"\"\"Minimize loss(c) via gradient descent with initial guess c0\n using learning rate gamma. Declares convergence when gradient\n is less than tol or after 500 steps.\n \"\"\"\n c = copy(c0)\n chist = [copy(c)]\n lhist = [loss(c)]\n for it in 1:500\n g = grad(c)\n c -= gamma * g\n push!(chist, copy(c))\n push!(lhist, loss(c))\n if norm(g) < tol\n break\n end\n end\n (c, hcat(chist...), lhist)\nend\n```\n\n\n\n\n grad_descent (generic function with 1 method)\n\n\n\n## Quadratic model\n\n\n```julia\nA = [1 1; 1 8]\n@show cond(A)\nloss(c) = .5 * c' * A * c\ngrad(c) = A * c\n\nc, chist, lhist = grad_descent(loss, grad, [.9, .9],\n gamma=.22)\nplot(lhist, yscale=:log10, xlims=(0, 80))\n```\n\n cond(A) = 9.46578492882319\n\n\n\n\n\n \n\n \n\n\n\n\n```julia\nplot(chist[1, :], chist[2, :], marker=:circle)\nx = LinRange(-1, 1, 30)\ncontour!(x, x, (x,y) -> loss([x, y]))\n```\n\n\n\n\n \n\n \n\n\n\n# Chebyshev regression via optimization\n\n\n\n\n```julia\nx = LinRange(-1, 1, 200)\nsigma = 0.5; n = 8\ny = runge_noisy(x, sigma)\nV = vander(x, n)\nfunction loss(c)\n r = V * c - y\n .5 * r' * r\nend\nfunction grad(c)\n r = V * c - y\n V' * r\nend\nc, _, lhist = grad_descent(loss, grad, ones(n),\n gamma=0.008)\nc\n```\n\n\n\n\n 8-element Vector{Float64}:\n 0.7891712932446856\n 0.007025641791364225\n -1.957064629386119\n -0.36715187386667464\n 0.9229823103908219\n 0.3031710357963882\n 0.4284481908323782\n 0.27267026221101087\n\n\n\n\n```julia\nc0 = V \\ y\nl0 = 0.5 * norm(V * c0 - y)^2\n@show cond(V' * V)\nplot(lhist, yscale=:log10)\nplot!(i -> l0, color=:black)\n```\n\n cond(V' * V) = 52902.52994792479\n\n\n\n\n\n \n\n \n\n\n\n# Why use QR vs gradient-based optimization?\n\n# Nonlinear models\n\nInstead of the linear model\n$$ f(x,c) = V(x) c = c_0 + c_1 \\underbrace{x}_{T_1(x)} + c_2 T_2(x) + \\dotsb $$\nlet's consider a rational model with only three parameters\n$$ f(x,c) = \\frac{1}{c_1 + c_2 x + c_3 x^2} = (c_1 + c_2 x + c_3 x^2)^{-1} . $$\nWe'll use the same loss function\n$$ L(c; x,y) = \\frac 1 2 \\lVert f(x,c) - y \\rVert^2 . $$\n\nWe will also need the gradient\n$$ \\nabla_c L(c; x,y) = \\big( f(x,c) - y \\big)^T \\nabla_c f(x,c) $$\nwhere\n\\begin{align}\n\\frac{\\partial f(x,c)}{\\partial c_1} &= -(c_1 + c_2 x + c_3 x^2)^{-2} = - f(x,c)^2 \\\\\n\\frac{\\partial f(x,c)}{\\partial c_2} &= -(c_1 + c_2 x + c_3 x^2)^{-2} x = - f(x,c)^2 x \\\\\n\\frac{\\partial f(x,c)}{\\partial c_3} &= -(c_1 + c_2 x + c_3 x^2)^{-2} x^2 = - f(x,c)^2 x^2 .\n\\end{align}\n\n# Fitting a rational function\n\n\n```julia\nf(x, c) = 1 ./ (c[1] .+ c[2].*x + c[3].*x.^2)\nfunction gradf(x, c)\n f2 = f(x, c).^2\n [-f2 -f2.*x -f2.*x.^2]\nend\nfunction loss(c)\n r = f(x, c) - y\n 0.5 * r' * r\nend\nfunction gradient(c)\n r = f(x, c) - y\n vec(r' * gradf(x, c))\nend\n```\n\n\n\n\n gradient (generic function with 1 method)\n\n\n\n\n```julia\nc, _, lhist = grad_descent(loss, gradient, ones(3), gamma=8e-2)\nplot(lhist, yscale=:log10)\n```\n\n\n\n\n \n\n \n\n\n\n# Compare fits on noisy data\n\n\n```julia\nscatter(x, y)\nV = vander_chebyshev(x, 7)\nplot!(x -> runge(x), color=:black, label=\"Runge\")\nplot!(x, V * (V \\ y), label=\"Chebyshev fit\")\nplot!(x -> f(x, c), label=\"Rational fit\")\n```\n\n\n\n\n \n\n \n\n\n", "meta": {"hexsha": "4a42def7c54f70b9845f10a7ded5a3cf8cbde95b", "size": 262716, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "slides/2022-03-28-gradient-descent.ipynb", "max_stars_repo_name": "cu-numcomp/spring22", "max_stars_repo_head_hexsha": "f4c1f9287bff2c10645809e65c21829064493a66", "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": "slides/2022-03-28-gradient-descent.ipynb", "max_issues_repo_name": "cu-numcomp/spring22", "max_issues_repo_head_hexsha": "f4c1f9287bff2c10645809e65c21829064493a66", "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": "slides/2022-03-28-gradient-descent.ipynb", "max_forks_repo_name": "cu-numcomp/spring22", "max_forks_repo_head_hexsha": "f4c1f9287bff2c10645809e65c21829064493a66", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2022-02-09T21:05:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-11T20:34:46.000Z", "avg_line_length": 151.8589595376, "max_line_length": 15399, "alphanum_fraction": 0.6501317012, "converted": true, "num_tokens": 2419, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632916317103, "lm_q2_score": 0.9241418278134569, "lm_q1q2_score": 0.8570152073756326}} {"text": "```python\n# Intialization for notebook use\n%pylab inline\n\nimport sympy as sp\nsp.init_printing(use_latex=True)\n\nimport ipywidgets as widgets\n```\n\n Populating the interactive namespace from numpy and matplotlib\n\n\n\n```python\nx_1, x_2 = sp.symbols('x_1 x_2') # indentify these as symbols\nλ = sp.symbols('λ')\n```\n\n# Introduction\n\nConsider the following 2nd order system (Mass-Damper-Spring):\n\n$\\ddot{x} + \\dot{x} = 3x + x^2 = 0 \\Longleftrightarrow \\ddot{x} + c \\dot{x} + f(x) = 0$\n\n$c$ is the dampening force and $f(x)$ is the non-linear spring. \n\nThe system can be placed into the $\\dot{\\underline{x}} = \\underline{f}(\\underline{x})$ form:\n\n$\\begin{cases}\n \\dot{x}_1 = x_2 \\\\\n \\dot{x}_2 = -3x_1 - x_1^2 - x_2\n\\end{cases}$\n\n# Analysis of the system: Manual\n\nAnalysis of the system $\\Rightarrow$ Phase Plane $(x_1, x_2)$:\n\n## Step 1: Find the Equillibrium Points:\n\n$\\begin{cases}\n f_1(x_1, x_2) = 0 \\\\\n f_2(x_2, x_2) = 0\n\\end{cases} \\Rightarrow\n\\begin{cases}\n x_2 && = 0 \\\\\n -3x_1 - x_1^2 - x_2 && = 0 \\, \\Rightarrow \\, -3x_1 - x_1^2 = 0\n\\end{cases}$\n\n$\\begin{cases}\n x_2 = 0 \\\\\n x_1(-3 - x_1) = 0\n\\end{cases} \\Rightarrow$ 2 equillibrium points $\\Rightarrow\n\\begin{cases}\n \\underline{x}_1 = [0, 0]^T \\\\\n \\underline{x}_2 = [-3, 0]^T\n\\end{cases}$\n\n## Step 2: Linearize the System Around the Equillibrium Points:\n\n$\\displaystyle\\dot{\\underline{x}} = \\underline{f}(\\underline{x}) \\Rightarrow \\approx \\underline{f}(\\underline{x}^*) + \\left . \\frac{\\partial \\underline{f}}{\\partial \\underline{x}} \\right |_{\\underline{x}^*} (\\underline{x} - \\underline{x}^*)$\n\n$\\displaystyle A = \\left . \\frac{\\partial\\underline{f}}{\\partial\\underline{x}} \\right |_{\\underline{x}_{1, \\, 2}^*} = \n\\begin{bmatrix}\n 0 && 1 \\\\\n -3 - 2x_1 && -1\n\\end{bmatrix}_{\\underline{x}_1^*, \\, \\underline{x}_2^*}$\n\n### For $\\underline{x} = \\underline{x}_1$ \n\nWe have the following system:\n\n$\\dot{\\underline{x}} = A_1 \\underline{x} \\Rightarrow A_1 = \n\\begin{bmatrix}\n 0 && 1 \\\\\n -3 && -1\n\\end{bmatrix}$\n\nLook for the behavior of the system near $\\underline{x}_1 = \\underline{0}$. e-value analysis:\n\n$\\det (A_1 - \\lambda I) = \n\\begin{vmatrix}\n -\\lambda && 1 \\\\\n -3 && -1 - \\lambda\n\\end{vmatrix}\n= \\lambda \\big(\\lambda + 1\\big) + 3 = 0$\n\n$\\Rightarrow \\lambda^2 + \\lambda + 3 = 0 \\Rightarrow \\lambda_{12} = -\\frac{1}{2} \\left( 1 \\pm \\sqrt{1 - 12}\\right) = -\\frac{1}{2} \\left( 1 \\pm \\sqrt{11} j\\right)$\n\n\n\n### For $\\underline{x} = \\underline{x}_2$\n\nWe have the following system:\n\n$\\dot{\\underline{x}} = A_2 \\underline{x} \\Rightarrow A_2 = \n\\begin{bmatrix}\n 0 && 1 \\\\\n 3 && -1\n\\end{bmatrix}$\n\nLook for the behavior of the system near $\\underline{x}_2 = \\underline{0}$. e-value analysis:\n\n$\\left|(A - \\lambda I ) \\right| = \n\\begin{vmatrix}\n -\\lambda && 1 \\\\\n 3 && -1 - \\lambda\n\\end{vmatrix} = 0$\n\n$\\Rightarrow \\lambda \\left(\\lambda + 1 \\right) - 3 = 0 \\Rightarrow \\, \\lambda^2 + \\lambda - 3 = 0$\n\n$\\lambda = -\\frac{1}{2} \\left ( 1 \\pm \\sqrt{1 + 12} \\right) = - \\frac{1}{2} \\pm \\frac{1}{2} \\sqrt{13}$\n\nNote that both solutions of $\\lambda$ are REAL! Therefore:\n\n$\\begin{matrix}\n \\lambda_1 = -\\frac{1}{2} \\left( 1 - \\sqrt{13} \\right ) > 0 \\\\\n \\lambda_2 = -\\frac{1}{2} \\left( 1 + \\sqrt{13} \\right ) < 0\n\\end{matrix} \\Rightarrow \\text{ Unstable } \\Rightarrow \\underline{\\text{Saddle Point}}$\n\nCompute the e-vectors $\\underline{v}_1,\\, \\underline{v}_2$ to determine the direction of convergence\n\n## Step 3: Put Everything Together:\n\n## !!!!! TODO: Insert Graphic !!!!!\n\n# Analysis of the System: Python\n\nGiven that:\n\n$\\begin{cases}\n \\dot{x}_1 = f_1(x_1, x_2) = x_2 \\\\\n \\dot{x}_2 = f_2(x_2, x_2) = -3x_1 - x_1^2 - x_2\n\\end{cases}$\n\nWe can define two variables to these functions:\n\n\n```python\nf_1 = x_2\nf_2 = -3 * x_1 - x_1 ** 2 - x_2\n```\n\nWe can solve the system of equations using the `solve` function.\n\n\n```python\nslns = sp.solve([f_1, f_2])\nslns\n```\n\nWe get the same solutions that we found previously. \n\nTo linearize the system, we need to take the derivatives of each function with respect to $x_1$ and $x_2$. We'll compile this into a matrix A_1 like so:\n\n\n```python\nA = sp.Matrix([[sp.diff(f_1, x_1), sp.diff(f_1, x_2)], [sp.diff(f_2, x_1), sp.diff(f_2, x_2)]])\nA\n```\n\nNow we let $\\dot{\\underline{x}} = A_1 \\, \\underline{x}$. Therefore `A_1` would be:\n\n\n```python\nA_1 = sp.Matrix([[0, 1], [-3, -1]])\nA_1\n```\n\nNext we find the determinate of $A_1 - \\lambda I$\n\n\n```python\nλ_fun = sp.det(A_1 - λ * sp.eye(2))\nλ_fun\n```\n\n\n```python\nsp.solve(λ_fun)\n```\n\n# Analysis of the System: Numpy Meshgrid\n\n\n```python\nimport numpy as np\nfrom matplotlib import pyplot as plt\nx1, x2 = np.meshgrid(np.linspace(-.5, .5, 10), np.linspace(-.5, .5, 10))\nx1dot = x2\nx2dot = -3 * x1 - x1 ** 2 - x2\n```\n\n\n```python\nplt.figure()\nplt.quiver(x1, x2, x1dot, x2dot)\nplt.show()\n```\n\n\n```python\n@widgets.interact (\n x_start=(-10.0, 10.0, 0.1), \n x_stop=(-10.0, 10.0, 0.1), \n y_start=(-10.0, 10.0, 0.1), \n y_stop=(-10.0, 10.0, 0.1), \n space=(10, 50)\n)\ndef inter_plot(x_start, x_stop, y_start, y_stop, space):\n x1, x2 = np.meshgrid(np.linspace(x_start, x_stop, space), np.linspace(y_start, y_stop, space))\n x1dot = x2\n x2dot = -3 * x1 - x1 ** 2 - x2\n plt.figure()\n plt.quiver(x1, x2, x1dot, x2dot)\n plt.show()\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "0d241ea61d7a446b5889351ff7b929c625904650", "size": 150790, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "01a - Example of Phase-Plane Analysis.ipynb", "max_stars_repo_name": "mertzjames/Linear-Systems-Theory", "max_stars_repo_head_hexsha": "d67c6017e0830e0d04882a3e33a6a4bb5cd0e61f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-05-05T23:48:17.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-05T23:48:17.000Z", "max_issues_repo_path": "01a - Example of Phase-Plane Analysis.ipynb", "max_issues_repo_name": "mertzjames/Linear-Systems-Theory", "max_issues_repo_head_hexsha": "d67c6017e0830e0d04882a3e33a6a4bb5cd0e61f", "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": "01a - Example of Phase-Plane Analysis.ipynb", "max_forks_repo_name": "mertzjames/Linear-Systems-Theory", "max_forks_repo_head_hexsha": "d67c6017e0830e0d04882a3e33a6a4bb5cd0e61f", "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": 290.5394990366, "max_line_length": 97744, "alphanum_fraction": 0.9157769083, "converted": true, "num_tokens": 1972, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632976542184, "lm_q2_score": 0.9241418178895029, "lm_q1q2_score": 0.8570152037381736}} {"text": "# Simplification\n\n\n```python\n# Load sympy module\nfrom sympy import *\n```\n\n\n```python\n# Define variables\nx, y = symbols('x y')\n```\n\n## Simplification of $$\\frac{x^2 + x\\times y}{x + y} = x$$\n\n\n```python\n# Simplification\nsimplify((x**2 + x*y)/(x + y))\n```\n\n\n\n\n$\\displaystyle x$\n\n\n\n## Rational simplification of $$(x^2 + 1)(x + 2) = x^3 + 2x^2 + x + 2$$\n\n\n```python\n# Rational simplification\nexpand((x**2 + 1)*(x+2))\n```\n\n\n\n\n$\\displaystyle x^{3} + 2 x^{2} + x + 2$\n\n\n\n## Factor of $$x^2 + 2x + 1 = (x + 1)^2$$\n\n\n```python\n# Factor\nfactor(x**2 + 2*x + 1)\n```\n\n\n\n\n$\\displaystyle \\left(x + 1\\right)^{2}$\n\n\n", "meta": {"hexsha": "b1553dce9a07fce105cf4e7a561f10a89f9d645c", "size": 3206, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "simplification.ipynb", "max_stars_repo_name": "ricoen/learn-math", "max_stars_repo_head_hexsha": "fc84bc4d0dc353f8ccb3c52e36155069e9ca5af4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-11-30T10:05:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-30T13:39:08.000Z", "max_issues_repo_path": "simplification.ipynb", "max_issues_repo_name": "ricoen/learn-math", "max_issues_repo_head_hexsha": "fc84bc4d0dc353f8ccb3c52e36155069e9ca5af4", "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": "simplification.ipynb", "max_forks_repo_name": "ricoen/learn-math", "max_forks_repo_head_hexsha": "fc84bc4d0dc353f8ccb3c52e36155069e9ca5af4", "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": 17.2365591398, "max_line_length": 77, "alphanum_fraction": 0.45102932, "converted": true, "num_tokens": 231, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9711290955604489, "lm_q2_score": 0.8824278633625322, "lm_q1q2_score": 0.8569513728445953}} {"text": "# Lab Assignment 3\n\n## Sam Dauncey, s2028017\n\nWe consider the system $$\\frac{dx}{dt}=x(y-1),\\quad \\frac{dy}{dt}=4-y^2-x^2.$$\n\n## Task 1 (2 marks)\n\nUse `SymPy` to find the critical points of the system.\n\n\n```python\nimport sympy as sym\nsym.init_printing()\nfrom IPython.display import display_latex\n```\n\n\n```python\n# Define sympy symbols.\nt = sym.symbols(\"t\")\nx = sym.Function(\"x\")\ny = sym.Function(\"y\")\n\n# Use these symbols to define the expressions for x' and y' given above.\nx_prime = x(t)*(y(t) - 1)\ny_prime = 4 - y(t)**2 - x(t)**2\n\ndeq_x = sym.Eq(x(t).diff(t), x_prime)\ndeq_y = sym.Eq(y(t).diff(t), y_prime)\n\n# Symbolically solve for when (x', y') = (0, 0)\ncrit_point_dicts = sym.solve([x_prime, y_prime])\n\n# Extract the critical points from the dictionaries given by sympy.\ncrit_points = [(point[x(t)], point[y(t)]) for point in crit_point_dicts]\ncrit_points\n```\n\n## Task 2 (4 marks)\n\nGive your implementation of the `linearise` function from Lab 3.\n\nUse this to find linear approximations of the system around the critical points with $x \\geq 0$ and $y \\geq 0$. Use the output to classify these critical points (use markdown cells and proper reasoning to explain the type of each critical point).\n\n\n```python\n# Define some variables to use in our linear system.\nu = sym.Function(\"u\")\nv = sym.Function(\"v\")\n\ndef lin_matrix(eqs, crit_point):\n \"\"\"Returns the jacobian F(x, y) = (x', y') evaluated at the given critical point\"\"\"\n # Unpack the expressions for x' and y' and use them to calculate the Jacobian.\n eq1, eq2 = eqs\n FG = sym.Matrix([eq1.rhs, eq2.rhs])\n matJ = FG.jacobian([x(t), y(t)])\n \n # Evaluate the Jacobian at the given critical point.\n x0, y0 = crit_point\n lin_mat = matJ.subs({x(t):x0, y(t):y0})\n return lin_mat\n\ndef linearise(eqs, crit_point):\n \"\"\"Returns a list of equations for the linearised system of eqs evaluated at the given critical point\"\"\"\n # Get the jacobian, J, at our critical point\n lin_mat = lin_matrix(eqs, crit_point)\n \n # Construct the system (u', v') = J (u, v) component-wise and return.\n uv_rhs = lin_mat * sym.Matrix([u(t),v(t)])\n u_eq = sym.Eq(u(t).diff(t), uv_rhs[0])\n v_eq = sym.Eq(v(t).diff(t), uv_rhs[1])\n return [u_eq, v_eq]\n\n\n# Print info about the linear system at each of the critical points.\nfor point in crit_points:\n \n # If the x and y coords are non-negative, print information about the point.\n x0, y0 = point \n if x0 >= 0 and y0 >= 0:\n print(\"critical point:\")\n display_latex((x0, y0))\n \n # Use lin_matrix() to get the matrix and eigenvalues of the linearised system\n linearised_matrix = lin_matrix([deq_x, deq_y], point)\n print(\"linearised matrix, eigenvalues\")\n display_latex(linearised_matrix)\n display_latex(list(linearised_matrix.eigenvals().keys()))\n \n # Use linearise() to get a printable version of the linear system\n print(\"full linearised system:\")\n display_latex(linearise([deq_x, deq_y], point))\n print()\n print()\n```\n\n critical point:\n\n\n\n$\\displaystyle \\left( 0, \\ 2\\right)$\n\n\n linearised matrix, eigenvalues\n\n\n\n$\\displaystyle \\left[\\begin{matrix}1 & 0\\\\0 & -4\\end{matrix}\\right]$\n\n\n\n$\\displaystyle \\left[ 1, \\ -4\\right]$\n\n\n full linearised system:\n\n\n\n$\\displaystyle \\left[ \\frac{d}{d t} u{\\left(t \\right)} = u{\\left(t \\right)}, \\ \\frac{d}{d t} v{\\left(t \\right)} = - 4 v{\\left(t \\right)}\\right]$\n\n\n \n \n critical point:\n\n\n\n$\\displaystyle \\left( \\sqrt{3}, \\ 1\\right)$\n\n\n linearised matrix, eigenvalues\n\n\n\n$\\displaystyle \\left[\\begin{matrix}0 & \\sqrt{3}\\\\- 2 \\sqrt{3} & -2\\end{matrix}\\right]$\n\n\n\n$\\displaystyle \\left[ -1 - \\sqrt{5} i, \\ -1 + \\sqrt{5} i\\right]$\n\n\n full linearised system:\n\n\n\n$\\displaystyle \\left[ \\frac{d}{d t} u{\\left(t \\right)} = \\sqrt{3} v{\\left(t \\right)}, \\ \\frac{d}{d t} v{\\left(t \\right)} = - 2 \\sqrt{3} u{\\left(t \\right)} - 2 v{\\left(t \\right)}\\right]$\n\n\n \n \n\n\nWe can see here that the point $(2, 0)$ will be unstable as the linearised system has a positive eigenvalue (namely $1$). In contrast, the eigenvalues for the linearised system at the critical point $(\\sqrt{3}, 1)$ both have negative real parts so this critical point will be stable.\n\n## Task 3 (4 marks)\n\nProduce a phase portrait of the system, with trajectories showing the behaviour around all the critical points. A few trajectories are enough to show this behaviour. Use properly-sized arrows to diplay the vector field (the RHS of the ODE). There are some marks allocated to the quality of your figure in this part. Try to keep it illustrative yet not too cluttered.\n\n\n```python\n\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom scipy.integrate import odeint\n%matplotlib inline\n\n# Get figure and axes\nfig, ax = plt.subplots(figsize=(12, 9))\n\n\n# Define x and y derivatives (t variable for use with odeint)\ndef vector_field(xy, t):\n X, Y = xy\n return (X*(Y - 1), 4 - Y**2 - X**2)\n\n# Get arrays for all the points with -4 < x < 4, -3 < y < 3\nX, Y = np.mgrid[-4:4:24j, -3:3: 18j]\n\n# Evaluate the vector field and length of each vector at each point\nX_prime, Y_prime = vector_field((X, Y), None)\nMagnitude = np.hypot(X_prime, Y_prime)\n\n# Plot arrows which are faded if they have large magnitute\nax.quiver(X, Y, X_prime, Y_prime, Magnitude,\n scale=200, pivot = 'mid', cmap = plt.cm.bone)\n\n# Pick some initial conditions for phase portraits\nics = [[0.2, 2.2], [-0.2, -1.8], [3, 2], [-1.5, 0.5]]\ndurations = [[0, 10], [0, 8], [0, 5], [0, 5]]\n\nvcolors = plt.cm.autumn_r(np.linspace(0.5, 1., len(ics))) # colors for each trajectory\n\n# plot trajectories\nfor time_span, ic, color in zip(durations, ics, vcolors):\n t = np.linspace(*time_span, 100)\n sol = odeint(vector_field, ic, t)\n x_sol, y_sol = sol.T\n ax.plot(x_sol, y_sol, color=color, label=f\"$(x_0, y_0)$ = {ic}\")\n\n\ndef split_coords(tuple_list):\n \"\"\"Helper function which takes [(a, b), (c, d), (e, f) ... ] and returns [[a, c, e .. ], [b, d, f ...]]\"\"\"\n return np.array(tuple_list).T\n\n# Plot black and blue points for the critical points and initial conditions respectivelyl\nax.scatter(*split_coords(crit_points), color = \"k\", label=\"critical points\")\nax.scatter(*split_coords(ics), color='b', label=\"initial conditions\")\n\nplt.xlabel('x')\nplt.ylabel('y')\nplt.legend()\n\nplt.xlim(-4, 4)\nplt.ylim(-3, 3)\n\nplt.show()\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "8188ec7e5e49f018269af124e1b4669fec2f9d8c", "size": 214330, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": ".ipynb_checkpoints/Lab_3_Assignment-checkpoint.ipynb", "max_stars_repo_name": "SamD770/hons-diff-eqs-notebooks", "max_stars_repo_head_hexsha": "48503988b75f113760b67979713c8dcf5f143fa4", "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": ".ipynb_checkpoints/Lab_3_Assignment-checkpoint.ipynb", "max_issues_repo_name": "SamD770/hons-diff-eqs-notebooks", "max_issues_repo_head_hexsha": "48503988b75f113760b67979713c8dcf5f143fa4", "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": ".ipynb_checkpoints/Lab_3_Assignment-checkpoint.ipynb", "max_forks_repo_name": "SamD770/hons-diff-eqs-notebooks", "max_forks_repo_head_hexsha": "48503988b75f113760b67979713c8dcf5f143fa4", "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": 539.8740554156, "max_line_length": 199640, "alphanum_fraction": 0.9410021929, "converted": true, "num_tokens": 1925, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294403959948494, "lm_q2_score": 0.9219218375365862, "lm_q1q2_score": 0.8568713977563038}} {"text": "# GDA\n\n```{note}\nGaussian Discriminant Analysis(GDA) suppose that observations are presumed to come from one of several multivariate normal distributions.
\nIt is \n```\n\n## Normal Distribution\n\nNormal distribution is parameterized by a mean vector $\\mu \\in \\mathbb{R}^{d}$ and a covariance matrix $\\Sigma \\in \\mathbb{R}^{d \\times d}$, where $\\Sigma >= 0$ is symmetric and positive semi-definite, also written $\\mathcal{N}(\\mu,\\Sigma)$, it's density is given by:\n\n$$p(x;\\mu,\\Sigma)=\\frac{1}{(2\\pi)^{d/2}\\left | \\Sigma \\right |^{1/2} }\\exp\\left ( -\\frac{1}{2}(x-\\mu)^{T}{\\Sigma}^{-1}(x-\\mu)\\right )$$\n\nunsurprisingly, for random variable $X \\sim \\mathcal{N}(\\mu,\\Sigma)$:\n\n$$E[X] = \\int_{x}xp(x;\\mu, \\Sigma)dx = \\mu$$\n$$Cov(X) = E[(X - E(X))(X - E(X))^{T}] = \\Sigma$$\n\n## Model\n\nWhen we have a classification problem in which the input features $x$ are continous, we can use GDA, which model $p(x|y)$ using the multivariant normal distribution:\n\n$$y\\sim Bernoulli(\\phi)$$\n$$x | y=0 \\sim \\mathcal{N}(\\mu_{0},\\Sigma) $$\n$$x | y=1 \\sim \\mathcal{N}(\\mu_{1},\\Sigma) $$\n\ndensity:\n\n$$p(y) = \\phi^{y}(1 - \\phi)^{1 - y}$$\n\n$$p(x| y=0)=\\frac{1}{(2\\pi)^{d/2}\\left | \\Sigma \\right |^{1/2} }\\exp\\left (-\\frac{1}{2}(x-\\mu_{0})^{T}{\\Sigma}^{-1}(x-\\mu_{0})\\right )$$\n\n$$p(x| y=1)=\\frac{1}{(2\\pi)^{d/2}\\left | \\Sigma \\right |^{1/2} }\\exp\\left (-\\frac{1}{2}(x-\\mu_{1})^{T}{\\Sigma}^{-1}(x-\\mu_{1})\\right )$$\n\nThen the log-likelihood of the data is given by:\n\n$$\n\\begin{equation}\n\\begin{split}\nl(\\phi,\\mu_{0},\\mu_{1},\\Sigma) &= \\log\\prod_{i=1}^{n}p(x^{(i)},y^{(i)};\\phi,\\mu_{0},\\mu_{1},\\Sigma) \\\\\n&= \\log\\prod_{i=1}^{n}p(x^{(i)}|y^{(i)};\\mu_{0},\\mu_{1},\\Sigma)p(y^{(i)};\\phi)\n\\end{split}\n\\end{equation}\n$$\n\nMaximum Likelihood Estimate result:\n\n$$\\phi = \\frac{1}{n}\\sum_{i=1}^{n}1\\left \\{ y^{(i)}=1 \\right \\}$$\n\n$$\\mu_{0} = \\frac{\\sum_{i=1}^{n}1\\left \\{ y^{(i)}=0 \\right \\}x^{(i)} }{\\sum_{i=1}^{n}1\\left \\{ y^{(i)}=0 \\right \\}} $$\n\n$$\\mu_{1} = \\frac{\\sum_{i=1}^{n}1\\left \\{ y^{(i)}=1 \\right \\}x^{(i)} }{\\sum_{i=1}^{n}1\\left \\{ y^{(i)}=1 \\right \\}} $$\n\n$$\\Sigma=\\frac{1}{n}\\sum_{i=1}^{n}(x^{(i)} - \\mu_{y^{(i)}})(x^{(i)} - \\mu_{y^{(i)}})^{T}$$\n\n\n```python\n\n```\n", "meta": {"hexsha": "b1b37218d334f0e4598cc7dba54a9c4098e1acd6", "size": 3492, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "machine-learning-book/c3.GDA.ipynb", "max_stars_repo_name": "newfacade/jupyters", "max_stars_repo_head_hexsha": "12d3c8bf1b91a7fc2f84e89b5a55efa176f4da23", "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": "machine-learning-book/c3.GDA.ipynb", "max_issues_repo_name": "newfacade/jupyters", "max_issues_repo_head_hexsha": "12d3c8bf1b91a7fc2f84e89b5a55efa176f4da23", "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-book/c3.GDA.ipynb", "max_forks_repo_name": "newfacade/jupyters", "max_forks_repo_head_hexsha": "12d3c8bf1b91a7fc2f84e89b5a55efa176f4da23", "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.9029126214, "max_line_length": 287, "alphanum_fraction": 0.4664948454, "converted": true, "num_tokens": 921, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9802808759252645, "lm_q2_score": 0.8740772384450967, "lm_q1q2_score": 0.8568412009292956}} {"text": "# Differential Algebraic Equation / Partial Differentiation Equation solvers\n_By Dhruv Jain_\n\n### **Objective: Implementation of fintie differentiation to solve various types of PDE**\n\n\n```python\n# Key libraries: Numpy(for mathematical procedures) and matplotlib(to create plots)\nimport numpy as np\nimport matplotlib.pyplot as plt \nimport copy\n```\n\n## 1D Heat Equation\n$\\frac{\\partial h}{\\partial t} = k\\frac{\\partial^2 h}{\\partial x^2}$; $0 \\leq t < \\infty $, $0 \\leq x \\leq X_{limit}$
\n$h(0,t) = 0$
\n$h(X_{limit},t) = f(t)$
\n$h(x,0) = 0$\n\nWe notice that the DE is a PDE with derivatives with respect to t and x.
\nWe discretize $x$ as $x_i$ where i = 0, 1, ....., $n_x$, $\\Delta x = \\frac{X_{limit} - 0}{n_x}$
\n$t$ as $t_k$ where k = 0,1,...., $n_t$, $\\Delta t = \\frac{max(t) - 0}{n_t}$
\nUsing Finite Forward Differencing of first-order and Central Differencing of second-order accuracy, we approximate the derivative terms as,
\n(This setup is first-order accurate in time and second-order accurate in space)
\n\n\\begin{equation}\n \\frac{\\partial h}{\\partial t} \\approx \\frac{h_{i}^{k+1}-h_{i}^{k}}{\\Delta t} \\notag{}\n\\end{equation}\n\n\\begin{equation}\n \\frac{\\partial^2 h}{\\partial x^2} \\approx \\frac{h_{i+1}^k-2h_i^k+h_{i-1}^k}{\\Delta x^2} \\notag{}\n\\end{equation}\n\nwhere, $h(x_i, t_k) = h_i^k$\nSubsituting and discretizing the other pieces in the given PDE, \n\n\\begin{equation}\n \\frac{h_{i}^{k+1}-h_{i}^{k}}{\\Delta t} = k\\frac{h_{i+1}^k-2h_i^k+h_{i-1}^k}{\\Delta x^2} \\notag{}\n\\end{equation}\n\nRearranging the terms, we get the discretized PDE:\n\n\n\\begin{equation}\n h_{i}^{k+1} = h_{i}^{k} + k\\frac{\\Delta t}{\\Delta x^2}(h_{i+1}^k-2h_i^k+h_{i-1}^k) \\notag{}\n\\end{equation}\n\nWith B.C.:
\n$h_0^k = 0$
\n$h_{X_{limit}}^t = f_k(t)$
\n$h_i^0 = 0$\n\n\n```python\ndef PDE_solve_1Dheat(tmax, xmax, hx, ht, bc0t, funcx, kconst):\n \"\"\"\"Dhruv Jain, 22 Nov 2021\n Obj: Solve 1D heat equation of the from \n h_t = k*h_xx; t ->[0,tmax), x -> [a,b]\n h(a,t) = bc0t\n h(x,0) = funcx\n dh/dx(b,t) = 0\n Args:\n tmax: end value of time interval, float\n xmax: end value of space interval, float\n hx: step size in space, float\n ht: step size in time, float\n bc0t: condition 1, Dirichlet condition, float\n funct: function that defines h(x,0)\n kconst: constant, float\n Output:\n soln: dict, evaluated y values ['y'] and respective time steps ['t'], ndarray\n \"\"\"\n \n xi = np.arange(0, xmax+1e-15, hx) # mesh points in space\n ti = np.arange(0, tmax+1e-12,ht) # time discretization\n Nx = len(xi)-1\n Nt = len(ti)-1\n \n D = kconst*ht/hx**2\n \n yi = np.zeros((Nt+1, Nx+1))\n \n yi[0,:] = funcx(xi) #h(x,0), B.C. bottom\n yi[:,0] = bc0t*np.ones(Nt+1) #h(0,t), B.C. left\n \n for k in range(1,Nt):\n for i in range(1,Nx+1):\n if i == Nx:\n yi[k,i] = yi[k-1,i] + D*(- 2*yi[k-1,i] + 2*yi[k-1,i-1]) # Neuman Condition on B.C. right\n else: \n yi[k,i] = yi[k-1,i] + D*(yi[k-1,i+1] - 2*yi[k-1,i] + yi[k-1,i-1]) # Basic Setup for 1D Heat Equation \n \n fval = {}\n fval['y'] = yi # y(x,t)\n fval['x'] = xi\n fval['t'] = ti\n \n return fval\n```\n\n# #Example 1\n$\\frac{\\partial T}{\\partial t} = c\\frac{\\partial^2 T}{\\partial x^2}$; $0 < x < 4 m$
\n$T(0,t) = 273$
\n$T_x(4,t) = 0$
\n$T(x,0) = 273 + 25sin(3x)$\n\n\n```python\ndef p1_bcx0(xi):\n \"\"\"\"Dhruv Jain, 11 Dec, 2021\n Obj: h(xi,0) expression for 1D Heat Equation\n Args:\n xi: xi's, ndarray, float\n Output:\n hi: ndarray\n \"\"\"\n hi = 273 + 25*np.sin(3*xi)\n return hi\n\ntmax = 31\nxmax = 4\ndelta_x = 0.1 \ndelta_t = 0.025\nkconst = 1/5\nbc0t = 273\n\nfval_p1 = PDE_solve_1Dheat(tmax, xmax,delta_x, delta_t, bc0t, p1_bcx0, kconst)\n\n# Find index of array for the required x values\nxneeded = [0.2, 0.5 ,0.8]\nxindex = []\ntlim = []\nfor i in range(len(xneeded)):\n xindex.append(np.argmin(abs(fval_p1['x']-xneeded[i])))\n\n# T(x,t) computed till 31 sec, get index for t till 4 sec\ntlim = np.argmin(abs(fval_p1['t']-4))\n\nfor i in range(len(xindex)):\n plt.figure(i)\n plt.title('Plot of T(x,t) vs t @ x ='+str(xneeded[i])+' m ')\n plt.plot(fval_p1['t'][:tlim], fval_p1['y'][:tlim,xindex[i]],marker='.')\n plt.ylabel('T(x,t) @ x ='+str(xneeded[i])+' m')\n plt.xlabel('t (s)')\n plt.grid()\n```\n\n## Advect Equation\nFinite Forward Differnce Method
\n$c\\frac{\\partial u}{\\partial t} + k\\frac{\\partial u}{\\partial x} = qx$, $u(x,0) = sin(2\\pi x/L)$, u(0,t) = 0
\n\nDiscretized PDE using first-order accuracy finite forward differencing method in time and backward differencing method in space: \n\n\\begin{equation}\n c\\frac{u_{i}^{k+1}-u_{i}^{k}}{\\Delta t} + k\\frac{u_{i}^{k}-u_{i-1}^{k}}{\\Delta x} = qx_i \\notag{}\n\\end{equation}\n\nwhere, $u(x_i, t_k) = u_i^k$
\n$u(x_i,0) = sin(2\\pi x_i/L)$
\n$u(0,t_k) = 0$
\n\n\n\\begin{equation}\n u_{i}^{k+1} = u_{i}^{k} - \\frac{k\\Delta t}{c\\Delta x}(u_{i}^{k}-u_{i-1}^{k}) + \\frac{qx_i\\Delta t}{c} \\notag{}\n\\end{equation}\n\n\n```python\ndef advect_solve_forwdiff_dir_dir(del_x, del_t, kconst, q, L, xmax, tmax):\n \"\"\"\"Dhruv Jain, 22 Nov, 2021\n Obj: Uses Finite Forward Difference Method of first-order accuracy in time and Backward Difference Method in space to solve BVP\n of Advect form: du/dt + kdu/dx = r\n Dirichlet BC left and bottom\n Args:\n del_x: spatial discrization, float\n del_t: temporal discretization, float\n k: coeffeicient of du/dx, float\n q: coefficient on rhs, float\n L: constant in B.C., float\n xmax: U.L. of x, float\n tmax: U.L. of t, float\n Output:\n soln: dict, evaluated y values ['y'] and respective time steps ['t'], ndarray\n \"\"\"\n xi = np.arange(0,xmax+1e-12,del_x)\n ti = np.arange(0,tmax+1e-12,del_t)\n \n y = np.zeros((len(ti),len(xi))) # B.C. left = 0\n \n y[0,:] = np.sin(2*np.pi*xi/L) # Set B.C. bottom\n\n lam = kconst/5*del_t/del_x\n grhs = del_t*q*xi/5\n for k in range(1,len(ti)): \n for i in range(1,len(xi)):\n y[k,i] = (1-lam)*y[k-1,i] + lam*y[k-1,i-1] + grhs[i]\n \n fval = {}\n fval['y'] = y\n fval['t'] = ti\n fval['xi'] = xi\n return fval\n```\n\n# #Example 2\n\n\n```python\ndelta_x = 0.05\ndelta_t = 0.005\nk = 1 #m/s\nq = 1 #1/m\nL = 1 #m\nxmax = 3 #m\ntmax = 3 #sec\n\nsol_p1 = advect_solve_forwdiff_dir_dir(delta_x, delta_t, k, q, L, xmax, tmax)\n\nxindex = np.argmin(abs(sol_p1['xi']-3))\n\nindex = []\nfor i in range(4):\n index.append(np.argmin(abs(sol_p1['t']-i)))\n \nplt.figure(1)\nplt.title('Plot of u(x,t) ')\nfor i in range(0,len(index)):\n plt.plot(sol_p1['xi'][:-1],sol_p1['y'][index[i],:xindex],marker='.',label='t='+str(i))\nplt.xlabel('x')\nplt.ylabel('u(x,ti)')\nplt.grid()\nplt.legend()\n```\n\n## Wave Equation\n$\\frac{\\partial^2 u}{\\partial t^2} = c^2\\frac{\\partial^2 u}{\\partial x^2}$
\n$u(0,t) = u(l,t) = 0$
\n$u_t(x,0) = g(x)$
\n$u(x,0) = f(x)$\n\n\n```python\ndef wave_solve_dir_neu(c, m, l, tsteps, xsteps, tmax, funcf, funcg):\n \"\"\"\"Dhruv Jain, 7 Dec, 2021\n Obj: Uses Finite Central Difference Method of second-order accuracy to solve BVP\n of wave form: d^2u/dt^2 = c^2 d^2u/dx^2\n Dirichlet BC\n Args:\n c: coeffeicient of d^2u/dx^2, float\n m: constant in B.C., float\n L: constant in B.C. and U.L. of x, float\n tsetps: number of time steps, int\n xsteps: number of spatial steps, int\n tmax: U.L. of t, float\n funcf: function to compute f(x) for u(x,0)\n funcg: function to compute g(x) for u_t(x,0)\n Output:\n soln: dict, evaluated y values ['y'] and respective time steps ['t'], ndarray\n \"\"\"\n xi = np.linspace(0,l,xsteps+1)\n del_x = xi[1]-xi[0]\n ti = np.linspace(0,tmax,tsteps+1)\n del_t = ti[1]-ti[0]\n \n D = (c*del_t/del_x)**2\n \n y = np.zeros((len(ti),len(xi)))\n # B.C. left and right: u(0,ti) = u(l,ti) = 0\n \n y[0,:] = funcf(xi, l)\n \n gi = funcg(xi)\n \n # As u_t(x,0) is known\n for i in range(1,len(xi)-1):\n y[1,i] = y[0,i] + del_t*gi[i] + 1/2 * D*(y[0,i+1] - 2*y[0,i] + y[0,i-1])\n \n #Using u(0,i) and u(1,i) compute u(k,i) for k>1 and i lies between 1 and xi-1\n for k in range(1,len(ti)-1): \n for i in range(1,len(xi)-1):\n y[k+1,i] = 2*y[k,i] - y[k-1,i] + D*(y[k,i+1] - 2*y[k,i] + y[k,i-1])\n \n fval = {}\n fval['y'] = y\n fval['t'] = ti\n fval['xi'] = xi\n return fval\n```\n\n# #Example 3\n\n\n```python\ndef p2_g(xi):\n \"\"\"\"Dhruv Jain, 6 Dec\n Obj: g(x) expression \n Args:\n xi: xi's, ndarray, float\n Output:\n gi: g(xi), ndarray\n \"\"\"\n gi = xi*0\n return gi\n\ndef p2_f(xi, l):\n \"\"\"\"Dhruv Jain, 6 Dec\n Obj: f(x) expression \n Args:\n xi: xi's, ndarray, float\n Output:\n fi: f(xi), ndarray\n \"\"\"\n \n fi = np.zeros((len(xi)))\n\n #Compute B.C. bottom: u(xi,0)\n for i in range(len(xi)):\n if xi[i] <= l/2 and xi[i] >= 0: \n fi[i] = 2*m*xi[i]/l\n elif xi[i] <= l and xi[i] > l/2: \n fi[i] = 2*m*(l-xi[i])/l\n\n return fi\n\ntmax = 10\ntsteps = 500\nxsteps = 500\nl = 10\nc = 1\nm = 1\nsol_p2 = wave_solve_dir_neu(c, m, l, tsteps, xsteps, tmax, p2_f, p2_g)\n\nt_req = [0, 2.5, 5, 7.5, 10]\nindex = []\nfor i in t_req:\n index.append(np.argmin(abs(sol_p2['t']-i)))\n\n```\n\n\n```python\nfor i in range(len(index)):\n plt.figure(i)\n plt.title('Plot of u(x,t) @ t = '+str(t_req[i]))\n plt.plot(sol_p2['xi'], sol_p2['y'][index[i],:],marker='.',label='t='+str(t_req[i]))\n plt.ylabel('u(x,'+str(t_req[i])+')')\n plt.xlabel('x')\n if max(abs(sol_p2['y'][index[i],:])) < 1e-12: # To avoid plotting near machine precision values of u(x,y)\n plt.ylim([-0.1, 0.1])\n plt.grid()\n plt.legend()\n```\n\n## Laplace Equation\n\n\n```python\ndef laplace_solve_neumleft_neubottom(h,xmin,xmax, ymin, ymax, funcf, funcg):\n \"\"\"\"Dhruv Jain, 12 Dec\n Obj: Uses Finite Central Difference Method of second-order accuracy to solve BVP\n of laplace form: d^2u/dy^2 + d^2u/dx^2 = f(x,y)\n Dirichlet BC on top and right = g(x,y)\n Neuman BC on left(=0) and bottom(=0)\n Args:\n h: step size, dx=dy=h, float\n xmin: L.L. of x, float\n xmax: U.L. of x, float\n ymin: L.L. of y, float\n ymax: U.L. of y, float\n funcf: function to compute f(x,y) for u(x,y)\n funcg: function to compute g(x,y) for u(x,y) # B.C. top and right\n Output:\n soln: dict, ndarray\n {u: u(x,y) values\n xi: xi values\n yi: yi values}\n \"\"\"\n xi = np.arange(xmin,xmax+1e-12,h)\n yi = np.arange(ymin,ymax+1e-12,h)\n \n u = np.zeros((len(yi),len(xi)))\n B = np.zeros((len(yi)-1,len(xi)-1))# B should not contain nodes on top and right\n\n u[0,-1] = funcg(-1,0,xi[-1],yi[0]) #u_0,-1\n for i in range(len(yi)-1):\n B[i,-1] = funcg(-1,i,xi[-1],yi[i]) # Add B.C. right to all u_-1,i\n \n u[i+1,-1] = funcg(-1,i+1,xi[-1],yi[i+1]) #u_-1,-1\n \n u[-1,0] += funcg(0,-1,xi[0],yi[-1])#u_-1,0\n for i in range(len(xi)-1): \n B[-1,i] = funcg(i,-1,xi[i],yi[-1]) # Add B.C. top to all u_i,-1\n u[-1,i+1] += funcg(i+1,-1,xi[i+1],yi[-1]) #u_-1,1 -> u_-1,-1\n \n for i in range(len(yi)-1):\n for j in range(len(xi)-1):\n B[i,j] += -h**2*funcf(xi[i],yi[j]) # Add -h^2*fij terms\n \n B = B.flatten()\n A = np.zeros((len(B),len(B))) \n \n D = np.zeros((len(xi)-1,len(xi)-1))\n \n for i in range(len(xi)-1): # Only difference in D from typical Dirichlet setup is -2 on D[1,1] instead of -1 to account for Neumann on left\n D[i,i] = 4\n for j in range(len(xi)-1):\n if j == i+1:\n D[i,j] = -1\n if i == 0:\n D[i,j] = -1*2\n if j == i-1:\n D[i,j] = -1\n\n nx = len(xi)-1\n for i in range(len(yi)-1): # Sim\n A[nx*i:nx*(i+1),nx*i:nx*(i+1)] = D\n for j in range(len(yi)-1):\n if j == i+1 and j == 1:\n A[nx*i:nx*(i+1),nx*j:nx*(j+1)] = -2*np.identity(nx) # -2*I to account for Neumann on bottom \n if j == i+1 and j > 1:\n A[nx*i:nx*(i+1),nx*j:nx*(j+1)] = -np.identity(nx)\n if j == i-1:\n A[nx*i:nx*(i+1),nx*j:nx*(j+1)] = -np.identity(nx)\n \n uij = np.matmul(np.linalg.inv(A),B)\n\n for i in range(len(yi)-1):\n u[i,0:len(xi)-1] = uij[nx*i:nx*(i+1)]\n \n fval = {}\n fval['u'] = u\n fval['yi'] = yi\n fval['xi'] = xi\n return fval\n```\n\n# #Example 4\ndT/dx(-10,y) = 0, dT/dy(x,-10) = 0, T(x,10) = 0, T(10,y) = 0\n\n\n```python\ndef p2_f(xi,yj):\n \"\"\"\"Dhruv Jain, 11 Dec, 2021\n Obj: f(x,y) expression\n Args:\n xi: x value at i, float\n yj: y value at j, float\n Output:\n fi: f(i,j), float\n \"\"\"\n if xi**2 + yj**2 <= 10:\n fij = -25 \n else:\n fij = 0\n return fij\n\ndef p2_g_c(i,j,xi,yj):\n \"\"\"\"Dhruv Jain, 11 Dec, 2021\n Obj: g(x,y) expression\n Args:\n i: x index, int\n j: y index, int\n xi: x value at i, float\n yj: y value at j, float\n Output:\n gi: g(i,j), float\n \"\"\" \n if i == -1 and j != -1: # Right BC\n gi = 0\n elif j == -1:# Top BC\n gi = 0\n return gi\n\n# Setup\nh = 0.5\nxmin = -10\nxmax = 10\nymin = -10\nymax = 10\nsol_p2c = laplace_solve_neumleft_neubottom(h,xmin,xmax, ymin, ymax, p2_f, p2_g_c)\n\n# Pot\nxindex = np.argmin(abs(sol_p2c['xi']-0))\nyindex = np.argmin(abs(sol_p2c['yi']-0))\n\n# Contour Plot\nfig,ax=plt.subplots(1,1)\ncp = ax.contourf(sol_p2c['xi'],sol_p2c['yi'],sol_p2c['u'])\nfig.colorbar(cp) \nax.set_title('Final Exam, P2(c): Contour plot of T(x,y)')\nax.set_xlabel('x (m)')\nax.set_ylabel('y (m)')\nplt.show()\n\n```\n", "meta": {"hexsha": "a656db262d1bab3d04bf8d708ec503a9865a9507", "size": 208985, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "DAE-PDE Solvers.ipynb", "max_stars_repo_name": "DhruvJ22/Numerical-Methods", "max_stars_repo_head_hexsha": "52e0b2d71b054c8e3581cb580e0ab8b1a91b1cb2", "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": "DAE-PDE Solvers.ipynb", "max_issues_repo_name": "DhruvJ22/Numerical-Methods", "max_issues_repo_head_hexsha": "52e0b2d71b054c8e3581cb580e0ab8b1a91b1cb2", "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": "DAE-PDE Solvers.ipynb", "max_forks_repo_name": "DhruvJ22/Numerical-Methods", "max_forks_repo_head_hexsha": "52e0b2d71b054c8e3581cb580e0ab8b1a91b1cb2", "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": 282.7943166441, "max_line_length": 49304, "alphanum_fraction": 0.9119362634, "converted": true, "num_tokens": 5230, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582593509315, "lm_q2_score": 0.9207896829553821, "lm_q1q2_score": 0.8567563656309609}} {"text": "# Cours 3 : Récursivité\n\n## Rappel : la pile d'exécution\n\nAu cours de l'exécution d'un programme les variables sont stockées dans la mémoire sous forme d'une **pile**. A chaque appel de fonction, un espace mémoire est réservé pour les variables de la fonction.\n\n**Exemple** \n\n\n```python\ndef fonction1(a):\n c = a + 1\n return c\n\ndef fonction2(b):\n return fonction1(b+1)\n\na = fonction2(3)\na\n```\n\n\n\n\n 5\n\n\n\nVoici une image simplifiée de l'évolution de la pile lors de l'exécution\n\n\n\nOn va utiliser le petit bout de code suivant pour suivre en direct les appels de fonctions, exécutez la cellule qui définit la fonction `printAppelsFonctions` puis regardons comment on l'applique sur notre petit bout de code.\n\n\n```python\nimport functools\n\ndef printAppelsFonctions(func):\n \"\"\"Print the function signature and return value\"\"\"\n @functools.wraps(func)\n def wrapper_debug(*args, **kwargs):\n args_repr = [repr(a) for a in args] \n kwargs_repr = [f\"{k}={v!r}\" for k, v in kwargs.items()] \n signature = \", \".join(args_repr + kwargs_repr) \n print(f\"Appel de {func.__name__}({signature})\")\n value = func(*args, **kwargs)\n print(f\"valeur de retour {value!r}\")\n print(f\"Fin de {func.__name__}({signature})\") \n return value\n return wrapper_debug\n```\n\n\n```python\n@printAppelsFonctions\ndef fonction1(a):\n c = a + 1\n return c\n\n@printAppelsFonctions\ndef fonction2(b):\n return fonction1(b+1)\n\na = fonction2(3)\na\n```\n\n Appel de fonction2(3)\n Appel de fonction1(4)\n valeur de retour 5\n Fin de fonction1(4)\n valeur de retour 5\n Fin de fonction2(3)\n\n\n\n\n\n 5\n\n\n\n**Exemple**\n\nque se passe-t-il dans le cas suivant ?\n\n\n```python\ndef fonction1(a):\n fonction1(a)\n\nfonction1(3)\n```\n\n\n```python\n@printAppelsFonctions\ndef fonction1(a):\n fonction1(a)\n\nfonction1(3)\n```\n\n## Définition\n\nUn algorithme *récursif* est un algorithme qui fait appel à lui même. Lorsqu'un algorithme n'est pas récursif, on dit qu'il est *itératif*.\n\nPour éviter une boucle infinie, il faudra impérativement définir **une condition d'arrêt**.\n\n**Exemple**\n\nLe calcul de $n! = n \\times (n-1) \\times \\dots \\times 1$. Tout d'abord la version itérative\n\n\n```python\ndef factorielleIterative(n):\n r = 1\n for i in range(1,n+1):\n r = r*i\n return r\n```\n\n\n```python\nfactorielleIterative(3)\n```\n\n\n\n\n 6\n\n\n\n\n```python\nfactorielleIterative(5)\n```\n\n\n\n\n 120\n\n\n\nLa version récursive se base sur le principe suivant :\n\n$n! = \\begin{cases}\n1 & \\text{si } n = 0 \\\\\nn \\times (n-1)! & \\text{sinon}\n\\end{cases}$\n\n\n```python\ndef factorielleRecursive(n):\n if n == 0:\n return 1\n return n * factorielleRecursive(n-1)\n```\n\n\n```python\nfactorielleRecursive(3)\n```\n\n\n\n\n 6\n\n\n\n\n```python\nfactorielleRecursive(5)\n```\n\n\n\n\n 120\n\n\n\nQue se passe-t-il au niveau de la pile ?\n\n\n```python\n@printAppelsFonctions\ndef factorielleRecursive(n):\n if n == 0:\n return 1\n return n * factorielleRecursive(n-1)\n\n```\n\n\n```python\nfactorielleRecursive(3)\n```\n\n Appel de factorielleRecursive(3)\n Appel de factorielleRecursive(2)\n Appel de factorielleRecursive(1)\n Appel de factorielleRecursive(0)\n valeur de retour 1\n Fin de factorielleRecursive(0)\n valeur de retour 1\n Fin de factorielleRecursive(1)\n valeur de retour 2\n Fin de factorielleRecursive(2)\n valeur de retour 6\n Fin de factorielleRecursive(3)\n\n\n\n\n\n 6\n\n\n\nAttention, sur certaines valeurs, on obtient des appels récurisfs à l'infini. Ici, la *fonction termine* sur l'ensemble des entiers positifs mais pas sur les négatifs\n\n\n```python\nfactorielleRecursive(-2)\n```\n\n## Comment définir une fonction récursive ?\n\nLe principe d'une fonction récursive est assez similaire à la notion de **récurrence** mathématique. On ne cherche pas à calculer le problème dans son ensemble mais simplement à le définir en fonction d'un problème de taille plus petite. Tout comme en mathématique le fait de prouver l'état initial et une seule étape permet de prouver la propriété, dans un algorithme, le fait de calculer l'état initial et une étape permet de calculer n'importe quelle valeur. \n\nUn algorithme récursif s'écrira toujours de cette façon :\nInput : des paramètres\nProcessus:\n Si les paramètres correspondent à la condition d'arret (cas simple):\n Actions cas d'arret\n Sinon\n Appel(s) récursifs sur de nouveaux paramètres\nPour être sûr que l'algorithme termine, les nouveaux paramètres doivent se rapprocher de la condition d'arrêt.\n\n## Exercices\n\n### Exercice 1\n\n1. Donner un algorithme récursif qui affiche les entiers de 1 à $n$\n1. Même chose de $n$ à 1\n3. Puis-je modifier ces algorithmes pour qu'ils rajoutent \"fin\" à la fin de la liste\n\n\n```python\n@printAppelsFonctions\ndef affiche1n(n):\n if n == 0:\n print(\"fin\")\n return\n affiche1n(n-1)\n print(n)\n```\n\n\n```python\naffiche1n(10)\n```\n\n Appel de affiche1n(10)\n Appel de affiche1n(9)\n Appel de affiche1n(8)\n Appel de affiche1n(7)\n Appel de affiche1n(6)\n Appel de affiche1n(5)\n Appel de affiche1n(4)\n Appel de affiche1n(3)\n Appel de affiche1n(2)\n Appel de affiche1n(1)\n Appel de affiche1n(0)\n fin\n valeur de retour None\n Fin de affiche1n(0)\n 1\n valeur de retour None\n Fin de affiche1n(1)\n 2\n valeur de retour None\n Fin de affiche1n(2)\n 3\n valeur de retour None\n Fin de affiche1n(3)\n 4\n valeur de retour None\n Fin de affiche1n(4)\n 5\n valeur de retour None\n Fin de affiche1n(5)\n 6\n valeur de retour None\n Fin de affiche1n(6)\n 7\n valeur de retour None\n Fin de affiche1n(7)\n 8\n valeur de retour None\n Fin de affiche1n(8)\n 9\n valeur de retour None\n Fin de affiche1n(9)\n 10\n valeur de retour None\n Fin de affiche1n(10)\n\n\n\n```python\ndef affichen1(n):\n if n == 0:\n print(\"fin\")\n return\n print(n)\n affichen1(n-1)\n \n```\n\n\n```python\naffichen1(10)\n```\n\n 10\n 9\n 8\n 7\n 6\n 5\n 4\n 3\n 2\n 1\n fin\n\n\n\n```python\ndef concat1n(n):\n if n == 0:\n return \"\"\n return concat1n(n-1) + \" \" + str(n) + \" fin \"\n```\n\n\n```python\nconcat1n(10)\n```\n\n\n\n\n ' 1 fin 2 fin 3 fin 4 fin 5 fin 6 fin 7 fin 8 fin 9 fin 10 fin '\n\n\n\n\n```python\ndef concatn1(n):\n if n == 0:\n return \"\"\n return str(n) + \" \" + concatn1(n-1)\n```\n\n\n```python\nconcatn1(10)\n```\n\n\n\n\n '10 9 8 7 6 5 4 3 2 1 '\n\n\n\n\n```python\n\n```\n\n### Exercice 2\n\nPour chacun des algorithmes suivants :\n\n1. Déterminez pour quelles valeurs d'entrée l'algorithme termine (= ne fait pas de boucles infinies)\n2. Calculez un exemple à la main\n3. Expliquez ce que calcule l'algorithme\n\n\n```python\ndef fonction1(n):\n if n == 0:\n return 1\n return fonction1(n+1)\n```\n\nLa fonction va terminer sur les valeurs négatives et renvoie toujours 1\nBoucle infinie sur les strictements positifs\n\n\n\n```python\nfonction1(-6)\n```\n\n\n\n\n 1\n\n\n\n\n```python\ndef fonction2(n):\n if n == 0:\n return 0\n return fonction2(n-1)+n\n```\n\nTermine pour les nombres positifs (boucle infinie sur les strictement négatifs)\nCalcule la somme des nombres de 1 à n\n\n\n```python\nfonction2(5)\n```\n\n\n\n\n 15\n\n\n\n\n```python\ndef fonction3(n):\n if n == 0:\n return 0\n return fonction3(n-1) - n\n```\n\nTermine pour les nombres positifs (boucle infinie sur les strictement négatifs)\nCalcule -(la somme des nombres de 1 à n)\n\n\n```python\nfonction3(5)\n```\n\n\n\n\n -15\n\n\n\n\n```python\ndef fonction4(n):\n if n == 0:\n return 0\n if n < 0:\n return n + fonction4(-n)\n return n + fonction4(-n+1)\n```\n\nTermine pour tous les entiers\nCalcule pour les positifs :\n\nexemple 5\n\n$5 + -4 + 4 + -3 + 3 + -2 + 2 + -1 + 1 + 0 = 5$\n\nPour les négatifs : 0\n\n\n```python\nfonction4(-10)\n```\n\n\n\n\n 0\n\n\n\n\n```python\ndef fonction5(n):\n if n <= 1:\n return 0\n return 1 + fonction5(n-2)\n```\n\nTermine pour tous les entiers \n\nCalcule n//2\n\n\n```python\nfonction5(11)\n```\n\n\n\n\n 5\n\n\n\n### Exercice 3\n\nLa fonction de fibonacci est définie par :\n\n$U_0 = 1$\n\n$U_1 = 1$\n\n$U_n = U_{n-1} + U_{n-2}$ si $n \\geq 2$\n\nCes premières valeurs sont donc : 1, 1, 2, 3, 5, 8, 13, ...\n\nDonner deux algorithmes, un itératif et un récursif, qui calculent la valeur $n$ de la suite.\n\n\n\n```python\ndef fiboIteratif(n):\n u0 = 1\n u1 = 1\n for i in range(2,n+1):\n u0, u1 = u1, u0 + u1\n return u1\n```\n\n\n```python\n[fiboIteratif(i) for i in range(10)]\n```\n\n\n\n\n [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]\n\n\n\n\n```python\ndef fiboRec(n):\n if n <= 1:\n return 1\n return fiboRec(n-1) + fiboRec(n-2)\n```\n\n\n```python\nfiboRec(5)\n```\n\n\n\n\n 8\n\n\n\n\n```python\n[fiboRec(i) for i in range(10)]\n```\n\n\n\n\n [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]\n\n\n\n### Exercice 4\n\nOn rappelle sur un exemple le principe de l'algorithme d'Euclide du calcul du pgcd (plus grand diviseur commun). \n\nCalcul du pgcd de 2145 et 630 : On commence par effectuer la division euclidienne de 2145 par 630\n\n$2145 = 630 * 3 + 255$\n\npuis on effectue la division de 630 par le reste obtenu 255\n\n$630 = 255 * 2 + 120$\n\nOn continue jusqu'à ce que l'on trouve un reste nul.\n\n$\\begin{align*}\n255 &= 120 *2 + 15 \\\\\n120 &= 15 * 8\n\\end{align*}$\n\nLe pgcd est le dernier reste non nul, c'est-à-dire **15**.\n\nDonner un algorithme récursif qui calcule le pgcd de deux nombres.\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n### Exercice 5\n\nReprendre l'algorithme de recherche dichotomique dans un tableau trié vu dans le TD1 et donner une version récursive.\n\n\n```python\nT = [1,2,3,3,4]\nT\n```\n\n\n\n\n [1, 2, 3, 3, 4]\n\n\n\n\n```python\nT[0]\n```\n\n\n\n\n 1\n\n\n\n\n```python\nlen(T)\n```\n\n\n\n\n 5\n\n\n\n\n```python\ndef dicho(T, deb, fin, x):\n if deb == fin:\n return False\n m = (deb + fin)//2\n if x == T[m]:\n return True\n if x < T[m]:\n return dicho(T,deb,m,x)\n return dicho(T,m+1,fin,x)\n```\n\n\n```python\nT = [1,2,3,3,4]\ndicho(T,0,len(T),2)\n```\n\n\n\n\n True\n\n\n\n\n```python\ndicho(T,0,len(T),3.5)\n```\n\n\n\n\n False\n\n\n\n\n```python\ndicho(T,0,len(T),6)\n```\n\n\n\n\n False\n\n\n\n\n```python\ndicho(T,0,len(T),-3)\n```\n\n\n\n\n False\n\n\n\n### Exemple avancé : les Tours de Hanoï\n\n\n\nProblème : on possède trois pics sur lesquels sont empilés des disques de tailles décroissantes (tous sur le premier pic). On souhaite déplacer la pile sur le second pic en suivant les règles suivantes:\n\n* on ne peut déplacer qu'un seul disque à la fois, celui du haut de la pile,\n* on ne peut poser un disque que sur un disque plus grand.\n\n\nOn suppose donc que l'on dispose d'une seule action possible :\nFonction Déplacer\nInput : \n - le pic de départ\n - le pic d'arrivée\nProcessus :\n Si départ n'est pas vide:\n D <- disque retiré au sommet de départ\n Sinon:\n Erreur \"Départ est vide\"\n Si D < disque au sommet d'arrivée:\n Poser D au sommet d'arrivée\n Sinon:\n Erreur \"Action impossible\"\nEn python, on utilisera l'interface suivante :\n\n\n```python\nclass Towers:\n \n def __init__(self,n):\n self.towers = (list(range(n,0,-1)),[],[])\n self.size = n\n \n def move(self,i,j):\n t1,t2 = self.towers[i], self.towers[j]\n if len(t1) == 0 or (len(t2) != 0 and t1[-1]>t2[-1]):\n raise ValueError(\"Invalid action\")\n print(\"Move from Tower \" + str(i) + \" to Tower \" + str(j))\n t2.append(t1.pop())\n \n def __repr__(self):\n res = \"\"\n n = self.size\n for i in range(n):\n line = \"\"\n for t in self.towers:\n if len(t) > i:\n v = t[i]\n else:\n v = 0\n stars = v*\"*\"\n spaces = (n-v)*\" \"\n line+= spaces + stars + \"|\" + stars + spaces + \" \"\n line+=\"\\n\"\n res = line + res\n return res\n```\n\n\n```python\nT = Towers(3)\nT\n```\n\n\n\n\n *|* | | \n **|** | | \n ***|*** | | \n\n\n\n\n```python\nT.move(0,1)\nT\n```\n\n Move from Tower 0 to Tower 1\n\n\n\n\n\n | | | \n **|** | | \n ***|*** *|* | \n\n\n\n\n```python\nT.move(0,2)\nT\n```\n\n Move from Tower 0 to Tower 2\n\n\n\n\n\n | | | \n | | | \n ***|*** *|* **|** \n\n\n\n\n```python\nT.move(1,2)\nT\n```\n\n Move from Tower 1 to Tower 2\n\n\n\n\n\n | | | \n | | *|* \n ***|*** | **|** \n\n\n\n\n```python\nT.move(0,1)\nT\n```\n\n Move from Tower 0 to Tower 1\n\n\n\n\n\n | | | \n | | *|* \n | ***|*** **|** \n\n\n\n\n```python\nT.move(2,0)\nT\n```\n\n Move from Tower 2 to Tower 0\n\n\n\n\n\n | | | \n | | | \n *|* ***|*** **|** \n\n\n\n\n```python\nT.move(2,1)\nT\n```\n\n Move from Tower 2 to Tower 1\n\n\n\n\n\n | | | \n | **|** | \n *|* ***|*** | \n\n\n\n\n```python\nT.move(0,1)\nT\n```\n\n Move from Tower 0 to Tower 1\n\n\n\n\n\n | *|* | \n | **|** | \n | ***|*** | \n\n\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n**Comment résoudre le problème ?**\n\nPour résoudre un problème de façon récursive, il faut répondre à plusieurs questions :\n\n1. Quelle est la taille de mon problème ?\n2. Quelle est la plus petite taille possible ? (condition d'arrêt)\n3. Comment résoudre le problème dans ce cas là ? (action d'arrêt)\n4. Si je suppose que je sais résoudre le problème pour toutes les tailles $k < n$, comment le résoudre pour la taille $n$ ?\n\n\n\n```python\n@compteAppels\ndef hanoi(T,n,dep, arrivee, inter):\n if n == 1:\n T.move(dep,arrivee)\n print(T)\n else:\n hanoi(T,n-1,dep,inter,arrivee)\n T.move(dep,arrivee)\n print(T)\n hanoi(T,n-1,inter,arrivee,dep)\n```\n\n\n```python\nhanoi(Towers(3),3,0,1,2)\n```\n\n Move from Tower 0 to Tower 1\n | | | \n **|** | | \n ***|*** *|* | \n \n Move from Tower 0 to Tower 2\n | | | \n | | | \n ***|*** *|* **|** \n \n Move from Tower 1 to Tower 2\n | | | \n | | *|* \n ***|*** | **|** \n \n Move from Tower 0 to Tower 1\n | | | \n | | *|* \n | ***|*** **|** \n \n Move from Tower 2 to Tower 0\n | | | \n | | | \n *|* ***|*** **|** \n \n Move from Tower 2 to Tower 1\n | | | \n | **|** | \n *|* ***|*** | \n \n Move from Tower 0 to Tower 1\n | *|* | \n | **|** | \n | ***|*** | \n \n 7 appels à la fonction hanoi\n\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n## Complexité d'un algorithme récursif\n\n### méthode de calcul\n\nReprenons le schéma de base d'un algorithme récursif que l'on précise légèrement:\nFonction R\nInput : des paramètres\nProcessus:\n Si les paramètres correspondent à la condition d'arret (cas simple):\n Actions cas d'arret\n Sinon\n Actions itératives et \n k Appel(s) récursifs: R(p1), R(p2), ..., R(pk)\nOn veut compter le nombre d'actions de base. Chaque appel de fonction est une action de base. Soit $f$ la complexité de l'algorithme. Pour simplifier l'écriture, on suppose que les paramètres de l'algorithme correspondent à la taille $n$ du problème. La condition d'arrêt est obtenue quand $n=0$ et correspond à une complexité constante $c_0$. On obtient une définition récursive de $f$\n\n$\\begin{align}\nf(0) &= c_0 \\\\\nf(n) &= g(n) + \\sum_{i=0}^k f(p_i)\n\\end{align}$\n\noù $g$ est la complexité de la partie itérative. La complexité dépend donc du **nombre d'appels récursifs** à chaque étape et de la **taille des paramètres**. Il peut être plus ou moins simple de *développer* la fonction $f$ pour obtenir une formule close (non récursive).\n\n### Cas classiques\n\nOn va regarder quelques cas classiques et compter le nombre d'appels de fonction. Pour cela, on utilise la fonctionnalité suivante (exécuter la cellule)\n\n\n```python\nimport functools\n\nCOMPTEUR = 0\nSTACK = 0\n\ndef compteAppels(func):\n c = 0\n \"\"\"Print the function signature and return value\"\"\"\n @functools.wraps(func)\n def wrapper_debug(*args, **kwargs):\n global COMPTEUR, STACK\n COMPTEUR +=1\n STACK += 1\n value = func(*args, **kwargs)\n STACK -=1\n if STACK == 0:\n print(f\"{COMPTEUR} appels à la fonction {func.__name__}\")\n COMPTEUR = 0\n return value\n return wrapper_debug\n```\n\n**Exemple : cas linéaire**\n\nOn reprend la fonction factorielle vue précédemment.\n\n\n```python\n@compteAppels\ndef factorielle(n):\n if n <= 0:\n return 1\n return n*factorielle(n-1)\n```\n\n\n```python\nfactorielle(10)\n```\n\n 11 appels à la fonction factorielle\n\n\n\n\n\n 3628800\n\n\n\nLorsqu'on appelle `factorielle(n)` on génère $n+1$ appels de fonctions. On est sur le schéma suivant :\nFonction R\nInput : un entier n\nProcessus:\n Si n=0:\n Actions cas d'arret\n Sinon\n Appel de R(n-1)\nDans ce cas, si $f$ est le nombre d'appels, on a \n\n$\\begin{align}\nf(0) &= 1 \\\\\nf(n) &= 1 + f(n-1)\n\\end{align}$\n\nLorsqu'on développe, on obtient\n\n$\\begin{equation}\nf(n) = 1 + 1 + 1 + \\dots + 1 = n+1\n\\end{equation}$\n\n$n+1$ fois.\n\nConclusion : la complexité est en $O(n)$.\n\n**Exemple : cas exponentiel**\n\nReprenons l'exemple des Tours de Hanoï. Combien d'appels de fonctions sont réalisés pour la taille $n$ ?\n\n\n```python\n@compteAppels\ndef Hanoi(n, T, depart, arrivee, inter):\n if n == 0:\n return\n Hanoi(n-1, T, depart, inter, arrivee)\n T.move(depart, arrivee)\n Hanoi(n-1, T, inter, arrivee, depart)\n```\n\n\n```python\nn = 3\nT = Towers(n)\nHanoi(n,T,0,1,2)\nT\n```\n\n Move from Tower 0 to Tower 1\n Move from Tower 0 to Tower 2\n Move from Tower 1 to Tower 2\n Move from Tower 0 to Tower 1\n Move from Tower 2 to Tower 0\n Move from Tower 2 to Tower 1\n Move from Tower 0 to Tower 1\n 15 appels à la fonction Hanoi\n\n\n\n\n\n | *|* | \n | **|** | \n | ***|*** | \n\n\n\nOn est sur le schéma suivant :\nFonction R\nInput : un entier n\nProcessus:\n Si n=0:\n Actions cas d'arret\n Sinon:\n 2 appels de R(n-1)\nDans ce cas, la complexité est donnée par le nombre d'appels $f$ avec\n\n$\\begin{align}\nf(0) &= 1 \\\\\nf(n) &= 1 + 2 \\times f(n-1).\n\\end{align}$\n\nPar exemple, pour $n=3$ :\n\n$\\begin{align}\nf(3) &= 1 + 2f(2) = 1 + 2(1 + 2f(1)) = 1 + 2(1 + 2(1 + 2))\\\\\n &= 15 = 2^4 - 1.\n\\end{align}$\n\nOn prouve facilement par récurrence que\n$\\begin{equation}\nf(n) = 2^{n+1} - 1.\n\\end{equation}$\n\nEn effet, $f(0) = 1 = 2^1 - 1$ et si on suppose la formule vraie pour $n$, on obtient pour $n+1$\n\n$f(n+1) = 1 + 2 f(n) = 1 + 2(2^{n+1} -1) = 1 + 2^{n+2} - 2 = 2^{n+2} - 1$\n\nOn est dans le cas d'une complexité exponentielle en $O(2^n)$.\n\n**Exemple : cas logarithmique**\n\nReprenons l'exemple de la fonction de recherche dichotomique. Combien d'appels sont réalisés ici ?\n\n\n```python\n@compteAppels\ndef rechercheDich(T,v,deb, fin):\n m = (deb+fin)//2\n if deb == fin:\n return False\n if T[m] == v:\n return True\n if v < T[m]:\n return rechercheDich(T,v,deb,m)\n return rechercheDich(T,v,m+1,fin)\n```\n\n\n```python\nn = 10000000\nT = list(range(n))\nv = 0.5\nrechercheDich(T,v,0,n)\n```\n\n 25 appels à la fonction rechercheDich\n\n\n\n\n\n False\n\n\n\nOn est sur le schéma suivant\nFonction R\nInput : un entier n\nProcessus:\n Si n=0:\n Actions cas d'arret\n Sinon:\n Appel de R(n/2)\nDans ce cas, si $f$ est le nombre d'appels, on a\n\n$\\begin{align}\nf(0) &= 1 \\\\\nf(n) &= 1 + f(\\lfloor n/2 \\rfloor).\n\\end{align}$\n\nDéveloppons sur un exemple :\n\n$\\begin{align}\nf(10) &= 1 + f(5) = 2 + f(2) = 3 + f(1) = 5 \\\\\n&= \\log(10) + 2.\n\\end{align}$\n\n(on prend le $\\log$ en base 2)\n\nOn prouve par récurrence\n$\\begin{equation}\nf(n) = \\lfloor \\log(n) \\rfloor + 2.\n\\end{equation}$\n\nEn effet, \n\n$f(1) = 1 + f(0) = 2 = \\log(1) + 2$ \n\nEn supposant la formule correcte pour toute valeur inférieure stricte à $n$, on obtient\n\n$\\begin{align}\nf(n) &= 1 + f(\\lfloor n/2 \\rfloor) \\\\\n&= 1 + \\lfloor \\log(\\lfloor n/2 \\rfloor) \\rfloor + 2\n\\end{align}$\n\nSupposons $n$ pair, si $k = \\lfloor \\log(n/2) \\rfloor$, cela signifie\n\n$2^k \\leq \\frac{n}{2} < 2^{k+1}$, c'est à dire\n\n$2^{k+1} \\leq n < 2^{k+2}$\n\nOn peut obtenir une inégalité similaire dans le cas de $n$ impair. Cela signifie que :\n\n$\\lfloor \\log(\\lfloor n/2 \\rfloor) \\rfloor = \\lfloor \\log(n) \\rfloor - 1$ \n\net donc\n\n$f(n) = 1 + \\lfloor \\log(n) \\rfloor - 1 + 2 = \\lfloor \\log(n) \\rfloor + 2$\n\nOn a donc une complexité en $O(log(n))$.\n\n### Conclusion : calcul de complexité\n\nSi l'on simplifie le problème aux cas où la partie itérative de la fonction est en $O(1)$ (comme dans les exemples précédents). La complexité est donnée entièrement par le nombre d'appels récursifs, $f$ on a 3 cas de figures. ($v \\geq 1$ et $k \\geq 2$ sont des constantes qui ne dépendent pas de $n$)\n\n$f(n) = 1 + f(n-v) \\rightarrow$ complexité linéaire $O(n)$\n\n$f(n) = 1 + k f(n - v) \\rightarrow$ complexité exponentielle $O(k^n)$\n\n$f(n) = 1 + f(n/k) \\rightarrow$ complexité logarithmique $O(\\log(n))$ (la constante $k$ agit sur la base dans laquelle on prend le logarithme, ce qui ne change pas la classe de complexité)\n\n## Exercices\n\n### Exercice 6\n\nDans la fonction suivante du calcul des nombres de Fibonacci, combien d'appels de fonctions sont réalisés pour un $n$ donné ? Quelle est la complexité ?\n\n\n```python\n@compteAppels\ndef fibo(n):\n if n <= 1:\n return 1\n return fibo(n-1) + fibo(n-2)\n```\n\nLe nombre d'appels est donné par\n\n$f(0) = f(1) = 1$\n\n$f(n) = 1 + f(n-1) + f(n-2)$\n\n\n```python\nfibo(20)\n```\n\n 21891 appels à la fonction fibo\n\n\n\n\n\n 10946\n\n\n\n\n```python\ndef fiboIteratif(n):\n u0 = 1\n u1 = 1\n for i in range(2,n+1):\n u0, u1 = u1, u0 + u1\n return u1\n```\n\n\n```python\nfiboIteratif(100)\n```\n\n\n\n\n 573147844013817084101\n\n\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n### Exercice 7\n\nIl existe deux définitions récursives de la fonction puissance :\n\n$\\begin{align*}\na^b &= \\begin{cases}\n1 &\\text{si }b=0 \\\\\na \\times a^{b-1} &\\text{sinon}\n\\end{cases} \\\\\na^b &= \\begin{cases}\n1 &\\text{si }b=0 \\\\\na \\times a^{b-1} &\\text{si }b\\text{ est impair} \\\\\na^{\\frac{b}{2}}a^{\\frac{b}{2}} &\\text{si }b\\text{ est pair}\n\\end{cases}\n\\end{align*}$\n\nPour chacune des définitions, donner l'algorithme récursif correspondant ainsi que sa complexité.\n\n\n```python\n@compteAppels\ndef puissance1(a,b):\n if b == 0:\n return 1\n return a * puissance1(a,b-1)\n```\n\n\n```python\npuissance1(2,100)\n```\n\n 101 appels à la fonction puissance1\n\n\n\n\n\n 1267650600228229401496703205376\n\n\n\n\n```python\n@compteAppels\ndef puissance2(a,b):\n if b == 0:\n return 1\n if b%2 == 1:\n res = puissance2(a,(b-1)//2)\n return a * res * res\n res = puissance2(a,b//2)\n return res * res\n #return puissance2(a,b//2) * puissance2(a,b//2)\n```\n\n\n```python\npuissance2(2,10000)\n```\n\n 15 appels à la fonction puissance2\n\n\n\n\n\n 19950631168807583848837421626835850838234968318861924548520089498529438830221946631919961684036194597899331129423209124271556491349413781117593785932096323957855730046793794526765246551266059895520550086918193311542508608460618104685509074866089624888090489894838009253941633257850621568309473902556912388065225096643874441046759871626985453222868538161694315775629640762836880760732228535091641476183956381458969463899410840960536267821064621427333394036525565649530603142680234969400335934316651459297773279665775606172582031407994198179607378245683762280037302885487251900834464581454650557929601414833921615734588139257095379769119277800826957735674444123062018757836325502728323789270710373802866393031428133241401624195671690574061419654342324638801248856147305207431992259611796250130992860241708340807605932320161268492288496255841312844061536738951487114256315111089745514203313820202931640957596464756010405845841566072044962867016515061920631004186422275908670900574606417856951911456055068251250406007519842261898059237118054444788072906395242548339221982707404473162376760846613033778706039803413197133493654622700563169937455508241780972810983291314403571877524768509857276937926433221599399876886660808368837838027643282775172273657572744784112294389733810861607423253291974813120197604178281965697475898164531258434135959862784130128185406283476649088690521047580882615823961985770122407044330583075869039319604603404973156583208672105913300903752823415539745394397715257455290510212310947321610753474825740775273986348298498340756937955646638621874569499279016572103701364433135817214311791398222983845847334440270964182851005072927748364550578634501100852987812389473928699540834346158807043959118985815145779177143619698728131459483783202081474982171858011389071228250905826817436220577475921417653715687725614904582904992461028630081535583308130101987675856234343538955409175623400844887526162643568648833519463720377293240094456246923254350400678027273837755376406726898636241037491410966718557050759098100246789880178271925953381282421954028302759408448955014676668389697996886241636313376393903373455801407636741877711055384225739499110186468219696581651485130494222369947714763069155468217682876200362777257723781365331611196811280792669481887201298643660768551639860534602297871557517947385246369446923087894265948217008051120322365496288169035739121368338393591756418733850510970271613915439590991598154654417336311656936031122249937969999226781732358023111862644575299135758175008199839236284615249881088960232244362173771618086357015468484058622329792853875623486556440536962622018963571028812361567512543338303270029097668650568557157505516727518899194129711337690149916181315171544007728650573189557450920330185304847113818315407324053319038462084036421763703911550639789000742853672196280903477974533320468368795868580237952218629120080742819551317948157624448298518461509704888027274721574688131594750409732115080498190455803416826949787141316063210686391511681774304792596709376\n\n\n\n## Pour finir : itératif ou récursif ?\n\nEn terme de complexité, la récursivité ne permet pas par défaut d'obtenir des algorithmes plus efficaces. Quand elle est mal utilisée, elle peut même donner des complexité **plus mauvaise** : exemple de Fibonacci. Par ailleurs, on peut prouver qu'il existe **toujours** une version itérative d'un algorithme récursif : il suffit de déplier la pile !\n\n**Qu'en est-il de la complexité mémoire ?** Reprendre l'exemple de la fonction exponentielle en itératif et en récursif. La complexité mémoire de l'algorithme récursif est en $O(n)$ tandis qu'il est en $O(1)$ pour l'itératif.\n\n**Alors pourquoi on fait du récursif ?** Sur de nombreux problèmes, les algorithmes récursifs sont beaucoup plus simples à concevoir que les algorithmes itératifs. C'est le cas de l'algorithme des Tour de Hanoi. Ils donnent des codes plus courts et plus lisibles. Par ailleurs, certaines **structure de données** ont elles-mêmes des **définition récursives** et sont particulièrement adaptés aux algorithmes récursifs : les arbres, les graphes, les listes chaînées. \n\n\n```python\n\n```\n", "meta": {"hexsha": "294ec0a2db4506c0bfdb68332398956870e97f4e", "size": 118791, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Algorithmic_Polytech/3-Recursivite/cours-recursivite.ipynb", "max_stars_repo_name": "VivianePons/courses", "max_stars_repo_head_hexsha": "5f1d6ce80efff97129bf8c723394acec65283563", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2016-09-02T17:31:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-25T12:54:46.000Z", "max_issues_repo_path": "Algorithmic_Polytech/3-Recursivite/cours-recursivite.ipynb", "max_issues_repo_name": "VivianePons/courses", "max_issues_repo_head_hexsha": "5f1d6ce80efff97129bf8c723394acec65283563", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2016-09-07T17:00:10.000Z", "max_issues_repo_issues_event_max_datetime": "2016-09-09T07:23:02.000Z", "max_forks_repo_path": "Algorithmic_Polytech/3-Recursivite/cours-recursivite.ipynb", "max_forks_repo_name": "VivianePons/courses", "max_forks_repo_head_hexsha": "5f1d6ce80efff97129bf8c723394acec65283563", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2018-01-21T19:55:41.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-15T14:08:53.000Z", "avg_line_length": 32.0105092967, "max_line_length": 3020, "alphanum_fraction": 0.5644114453, "converted": true, "num_tokens": 9085, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582632076909, "lm_q2_score": 0.9207896710002323, "lm_q1q2_score": 0.8567563580584573}} {"text": "# Límites de la Precisión\n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport sympy as sym\nsym.init_printing()\nfrom scipy import optimize\n```\n\n\n```python\ndef bisection(f, a, b, n, tol=1e-16):\n fa = f(a)\n fb = f(b)\n x = np.empty(n)\n \n # Just checking if the sign is not negative => not root necessarily \n if np.sign(f(a)*f(b)) >= 0:\n print('f(a)f(b)<0 not satisfied!')\n return None\n i = 0\n while (b-a) / 2 > tol and i < n:\n c = (a + b) / 2.\n x[i] = c\n fc = f(c)\n if fc == 0:\n x = x[:i+1]\n break\n elif np.sign(fa*fc) < 0:\n b = c\n fb = fc\n else:\n a = c\n fa = fc\n i += 1\n \n return x\n```\n\n\n```python\ndef fpi(g, x0, n, tol=1e-10):\n x = np.empty(n+1)\n x[0] = x0\n for i in range(n):\n x[i+1] = g(x[i])\n if np.abs(x[i+1] - x[i]) < tol:\n x = x[:i+2]\n break\n return x\n```\n\n\n```python\ndef secant(f, x0, x1, n, tol=1e-10):\n x = np.zeros(n + 2)\n x[0] = x0\n x[1] = x1\n for i in range(1, n + 1):\n x[i+1] = x[i] - (f(x[i]) * (x[i] - x[i-1])) / (f(x[i]) - f(x[i-1]))\n if np.abs(x[i+1] - x[i]) < tol:\n x = x[:i+1]\n break\n return x\n```\n\n\n```python\ndef newton_raphson(f, fp, x0, n, m=1, tol=1e-10):\n x = np.empty(n + 1)\n x[0] = x0\n for i in range(n):\n x[i+1] = x[i] - f(x[i]) / fp(x[i])\n if np.abs(x[i+1] - x[i]) < tol or f(x[i+1]) == 0:\n x = x[:i+2]\n break\n return x\n```\n\n# Backward y Forward Error \n\nAnalicemos la función\n\\begin{equation}\n f(x) = \\left(x-\\frac{2}{3}\\right)^3 = x^3 - 2x^2 + \\frac{4}{3}x-\\frac{8}{27}\n\\end{equation}\n\ndonde su raíz es $x=2/3$ con multiplicidad $3$.\n\n\n```python\nf = lambda x: (x - 2 / 3) ** 3\nfp = lambda x: 3 * (x - 2 / 3) ** 2\n```\n\n\n```python\nerror = lambda x, r: np.abs(x - r)\n```\n\n\n```python\ndef plotError(f, a, r):\n plt.figure(figsize=(12, 6))\n plt.plot(error(f(a), 0), 'r-o', label='Backward Error')\n plt.plot(error(a, r), 'b-o', label=\"Forward Error\")\n plt.yscale('log')\n plt.xlabel(\"# Iteraciones\")\n plt.ylabel(\"Error\")\n plt.grid(True)\n plt.legend()\n plt.show()\n```\n\n\n```python\nx = np.linspace(-1, 2, 100)\nplt.plot(x, f(x))\nplt.xlabel(r\"$x$\")\nplt.ylabel(r\"$f(x)$\")\nplt.grid(True)\nplt.show()\n```\n\n\n```python\n# Solución\nr = 2/3\n```\n\n### Bisección\n\n\n```python\na, b = .5, .7\nn_b = 50\nx_b = bisection(f, a, b, n_b)\nx_b[-1]\n```\n\n\n```python\nplotError(f, x_b, r)\n```\n\n### Secante\n\n\n```python\nx0 = .6\nx1 = .7\nn = 50\nx_s = secant(f, x0, x1, n)\nx_s[-1]\n```\n\n\n```python\nplotError(f, x_s, r)\n```\n\n### Newton-Raphson\n\n\n```python\nx0 = .6\nn = 50\nx_n = newton_raphson(f, fp, x0, n, 3)\nx_n[-1]\n```\n\n\n```python\nplotError(f, x_n, r)\n```\n\nDe acuerdo a lo revisado en clases y analizando los resultados, el **backward error** $|f(x_a)|$ decae rápidamente pero esto no implica que el **forward error** $|r-x_a|$ lo haga a la misma velocidad. Cuando un problema no está bien condicionado, no podemos asegurar que el comportamiento de ambos errores esté directamente relacionado.\n\n# Wilkinson Polynomial\n\nEste polinomio tiene un comportamiento interesante. Si bien sus raíces son evidentes, al utilizar los métodos revisados no vamos a obtener exactamente sus raíces.\n\n\n```python\n# Construccion de W(x)\nx = sym.symbols('x', reals=True)\nWf = np.prod(x - np.arange(1, 21))\nWf # W(x)\n```\n\n\n```python\n# Expansión del polinomio\nWe = sym.expand(Wf)\nWe\n```\n\n\n```python\n# Derivada version expandida\nWep = sym.diff(We, x)\nWep\n```\n\n\n```python\n# Derivada version factorizada\nWd = sym.diff(Wf, x)\nWd\n```\n\n\n```python\n# Transformar a funcion lambda para podes evaluar con nuestros métodos\n# Version expandida\nP = sym.lambdify(x, We) # def P(x): ... o P = lambda x: ...\nPp = sym.lambdify(x, Wep)\n# Factorizada\nW = sym.lambdify(x, Wf)\nWp = sym.lambdify(x, Wd)\n```\n\nSolo para visualizar...\n\n\n```python\nx1 = np.linspace(0.9, 20.1, 500)\npx = W(x1)\nplt.figure(figsize=(12, 6))\nplt.plot(x1, px)\nplt.xticks(np.arange(1, 21))\nplt.grid(True)\nplt.show()\n```\n\nCon el gráfico $\\log(f(x))$ no se verán los valores negativos pero verificamos que sus raíces sean las que corresponden.\n\n¿Qué pasa con la raíz $x=16$? Notar que ocurre en un vecindario a $x=16$...\n\n\n```python\nP(16 - .1), P(16.0), P(16), P(16 + .1)\n```\n\n\n```python\nW(16 - .1), W(16), W(16.0), W(16 + .1)\n```\n\n¿Por qué la diferencia del polinomio expandido y el factorizado?\n\n## Bisección\n\n\n```python\nr_w = 16\n```\n\n\n```python\na, b = r_w - 0.1, r_w + 0.1\nn_b = 100\nx_b = bisection(P, a, b, n_b, 1e-16)\nx_b[-1]\n```\n\n\n```python\nx_b[-1], P(x_b[-1]), W(x_b[-1])\n```\n\n\n```python\nplotError(P, x_b, r_w)\n```\n\n## Secante\n\n\n```python\nx0 = r_w - .1\nx1 = r_w + .1\nn_s = 1000\nx_s = secant(P, x0, x1, n_s, 1e-16)\nx_s[-1]\n```\n\n\n```python\nplotError(P, x_s, r_w)\n```\n\n\n```python\nx0 = r_w - .1\nn_n = 100\nx_n = newton_raphson(P, Pp, x0, n_n, 1e-16)\nx_n[-1]\n```\n\n\n```python\nplotError(P, x_n, r_w)\n```\n\n\n```python\nx_b[-1]-16\n```\n\n\n```python\nprint(error(x_b[-1], r_w), error(x_s[-1], r_w), error(x_n[-1], r_w))\n```\n\n 0.0033284982507311156 0.004299420643381069 0.017405068783038047\n\n\nEn clases derivamos que $\\Delta r \\approx \\pm 0.0136$ que se acerca más o menos a los resultados experimentales. ¿Podemos concluir con la información del **backward error**?, ¿Es un problema bien o mal condicionado?\n\n---\n\n# Comentario Iteración Punto Fijo!\n\nRecordemos el teorema de Taylor y tomando una idea similar al *Método de Newton-Raphson*, realicemos la siguiente expansión de $f(x)$ en torno a la raíz $r$:\n\n\\begin{equation}\n \\begin{split}\n f(x) & = f(r) + f'(r)(x-r) + O(x^2) \\\\\n f(x) & = 0 + f'(r)(x-r) + O(x^2) \\quad \\frac{1}{f'(r)}, f'(r)\\neq 0 \\\\\n \\frac{f(x)}{f'(r)} & = 0 + (x-r) + O(x^2) \\\\\n r = x - \\frac{f(x)}{f'(r)} + O(x^2).\n \\end{split}\n\\end{equation}\n\nDespreciando los términos $O(x^2)$ construyamos una iteración del tipo:\n\\begin{equation}\n \\begin{split}\n x_{i+1} & = x_i + \\alpha \\, f(x_i) \\\\\n & = g(x_i),\n \\end{split}\n\\end{equation}\n\ndonde $\\alpha = -\\frac{1}{f'(r)}$ es un parámetro conveniente que nos asegure $|g'(r)| < 1$.\n\nSi analizamos la expresión:\n\\begin{equation}\n \\begin{split}\n g(x) & = x + \\alpha f(x) \\\\\n g'(x) & = 1 + \\alpha f'(x),\n \\end{split}\n\\end{equation}\n\nla idea es que $|1 + \\alpha f'(x)| < 1$ cuando $x\\to r$.\n\n\n```python\nG = lambda x, f, a: x + a * f(x)\n```\n\nEjemplos...\n\n\n```python\nf1 = lambda x: 2 - x ** 2\n```\n\nProbemos para distintos $\\alpha$:\n\n\n```python\ng1 = lambda x: G(x, f1, .5)\ng2 = lambda x: G(x, f1, .1)\n```\n\n\n```python\nx0 = 1\nn = 100\n```\n\n\n```python\nx_g_1 = fpi(g1, x0, n)\n```\n\n\n```python\nx_g_1, x_g_1.shape\n```\n\n\n\n\n (array([1. , 1.5 , 1.375 , 1.4296875 , 1.40768433,\n 1.41689675, 1.41309855, 1.41467479, 1.41402241, 1.41429272,\n 1.41418077, 1.41422714, 1.41420794, 1.41421589, 1.4142126 ,\n 1.41421396, 1.4142134 , 1.41421363, 1.41421353, 1.41421357,\n 1.41421356, 1.41421356, 1.41421356, 1.41421356, 1.41421356,\n 1.41421356, 1.41421356]),\n (27,))\n\n\n\n\n```python\nx_g_2 = fpi(g2, x0, n)\n```\n\n\n```python\nx_g_2, x_g_2.shape\n```\n\n\n\n\n (array([1. , 1.1 , 1.179 , 1.2399959 , 1.28623692,\n 1.32079638, 1.34634607, 1.3650813 , 1.3787366 , 1.38864514,\n 1.39581161, 1.4009826 , 1.40470738, 1.4073871 , 1.40931325,\n 1.41069687, 1.4116903 , 1.41240335, 1.41291503, 1.41328214,\n 1.4135455 , 1.41373441, 1.41386991, 1.4139671 , 1.4140368 ,\n 1.4140868 , 1.41412265, 1.41414836, 1.4141668 , 1.41418003,\n 1.41418951, 1.41419632, 1.41420119, 1.41420469, 1.4142072 ,\n 1.414209 , 1.41421029, 1.41421122, 1.41421188, 1.41421236,\n 1.4142127 , 1.41421294, 1.41421312, 1.41421324, 1.41421333,\n 1.4142134 , 1.41421344, 1.41421348, 1.4142135 , 1.41421352,\n 1.41421353, 1.41421354, 1.41421355, 1.41421355, 1.41421355,\n 1.41421356, 1.41421356, 1.41421356, 1.41421356, 1.41421356,\n 1.41421356, 1.41421356, 1.41421356, 1.41421356, 1.41421356,\n 1.41421356]),\n (66,))\n\n\n\n\n```python\nr1 = np.sqrt(2)\nprint(np.abs(x_g_1[-1] - r1), np.abs(x_g_2[-1] - r1))\n```\n\n 2.4623636463161347e-11 2.1262236415964253e-10\n\n\n\n```python\nplt.figure(figsize=(12,6))\nplt.plot(error(x_g_1, r1), 'b.', label=r\"$\\alpha=0.5$\")\nplt.plot(error(x_g_2, r1), 'r.', label=r\"$\\alpha=0.1$\")\nplt.yscale('log')\nplt.xlabel(\"# iteraciones\")\nplt.ylabel(\"Error\")\nplt.legend()\nplt.grid(True)\nplt.show()\n```\n\nSegún el $\\alpha$ que utilicemos podemos asegurar convergencia, incluso mejorar la tasa!\n\nOtro ejemplo!\n\n\n```python\nf2 = lambda x: x ** 2 - x - 1\n```\n\n\n```python\ng3 = lambda x: G(x, f2, -.4) \ng4 = lambda x: G(x, f2, -.8)\n```\n\nRecordar que $\\alpha \\approx -1/f'(r)$, y $f'(x) =2x-1$. Como $f'(x) > 0$ cerca de $r$ entonces $\\alpha < 0$. Esa es la razón de utilizar valores negativos...\n\n\n```python\nx0 = 1\nn = 100\n```\n\n\n```python\nx_g_3 = fpi(g3, x0, n)\n```\n\n\n```python\nx_g_3, x_g_3.shape\n```\n\n\n\n\n (array([1. , 1.4 , 1.576 , 1.6128896 , 1.6174803 ,\n 1.61797541, 1.6180278 , 1.61803334, 1.61803392, 1.61803398,\n 1.61803399, 1.61803399, 1.61803399]),\n (13,))\n\n\n\n\n```python\nx_g_4 = fpi(g4, x0, n)\n```\n\n\n```python\nx_g_4, x_g_4.shape\n```\n\n\n\n\n (array([1. , 1.8 , 1.448 , 1.7290368 , 1.52061164,\n 1.68729315, 1.55956113, 1.6614253 , 1.58229832, 1.6452026 ,\n 1.59601141, 1.6350186 , 1.60440482, 1.62863682, 1.60957997,\n 1.6246458 , 1.61278326, 1.622154 , 1.61477032, 1.62060002,\n 1.61600449, 1.61963167, 1.61677161, 1.61902855, 1.61724863,\n 1.61865303, 1.61754535, 1.61841926, 1.61772995, 1.61827376,\n 1.6178448 , 1.6181832 , 1.61791626, 1.61812685, 1.61796073,\n 1.61809177, 1.6179884 , 1.61806995, 1.61800562, 1.61805637,\n 1.61801634, 1.61804791, 1.618023 , 1.61804265, 1.61802715,\n 1.61803938, 1.61802973, 1.61803734, 1.61803134, 1.61803608,\n 1.61803234, 1.61803529, 1.61803296, 1.6180348 , 1.61803335,\n 1.61803449, 1.61803359, 1.6180343 , 1.61803374, 1.61803418,\n 1.61803384, 1.61803411, 1.61803389, 1.61803406, 1.61803393,\n 1.61803404, 1.61803395, 1.61803402, 1.61803397, 1.61803401,\n 1.61803397, 1.618034 , 1.61803398, 1.618034 , 1.61803398,\n 1.61803399, 1.61803399, 1.61803399, 1.61803399, 1.61803399,\n 1.61803399, 1.61803399, 1.61803399, 1.61803399, 1.61803399,\n 1.61803399, 1.61803399, 1.61803399, 1.61803399, 1.61803399,\n 1.61803399, 1.61803399, 1.61803399, 1.61803399, 1.61803399,\n 1.61803399]),\n (96,))\n\n\n\n\n```python\nr2 = (1 + np.sqrt(5)) / 2\n```\n\n\n```python\nplt.figure(figsize=(12,6))\nplt.plot(error(x_g_3, r2), 'b.', label=r\"$\\alpha=-0.4$\")\nplt.plot(error(x_g_4, r2), 'r.', label=r\"$\\alpha=-0.8$\")\nplt.yscale('log')\nplt.xlabel(\"# iteraciones\")\nplt.ylabel(\"Error\")\nplt.legend()\nplt.grid(True)\nplt.show()\n```\n\nQuizás esta herramienta pueda ser útil para construir iteraciones de punto fijo...\n", "meta": {"hexsha": "726ac7f45ffa2211c4e18298ff5fdf616ea5775e", "size": 528072, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "material/03_raices_1D/precision.ipynb", "max_stars_repo_name": "etra0/INF-285", "max_stars_repo_head_hexsha": "189f8d66cf6997fc87b545378b2c5f1c7b908dbc", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2020-04-24T01:25:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-10T01:08:37.000Z", "max_issues_repo_path": "material/03_raices_1D/precision.ipynb", "max_issues_repo_name": "etra0/INF-285", "max_issues_repo_head_hexsha": "189f8d66cf6997fc87b545378b2c5f1c7b908dbc", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-04-22T00:57:29.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-23T23:59:28.000Z", "max_forks_repo_path": "material/03_raices_1D/precision.ipynb", "max_forks_repo_name": "etra0/INF-285", "max_forks_repo_head_hexsha": "189f8d66cf6997fc87b545378b2c5f1c7b908dbc", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 45, "max_forks_repo_forks_event_min_datetime": "2020-04-20T01:15:09.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-27T22:53:59.000Z", "avg_line_length": 386.8659340659, "max_line_length": 142620, "alphanum_fraction": 0.9228741535, "converted": true, "num_tokens": 4576, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312221360624, "lm_q2_score": 0.9441768639704482, "lm_q1q2_score": 0.856663207806335}} {"text": "# Training the Neural Network\n\n$\\def\\abs#1{\\left\\lvert #1 \\right\\rvert}\n\\def\\Set#1{\\left\\{ #1 \\right\\}}\n\\def\\mc#1{\\mathcal{#1}}\n\\def\\M#1{\\boldsymbol{#1}}\n\\def\\R#1{\\mathsf{#1}}\n\\def\\RM#1{\\boldsymbol{\\mathsf{#1}}}\n\\def\\op#1{\\operatorname{#1}}\n\\def\\E{\\op{E}}\n\\def\\d{\\mathrm{\\mathstrut d}}$\n\n\n```python\n# init\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport tensorboard as tb\nimport torch\nimport torch.optim as optim\nfrom torch import Tensor, nn\nfrom torch.nn import functional as F\nfrom torch.utils.tensorboard import SummaryWriter\n\n%load_ext tensorboard\n%load_ext jdc\n%matplotlib inline\n\nSEED = 0\n\n# create samples\nXY_rng = np.random.default_rng(SEED)\nrho = 1 - 0.19 * XY_rng.random()\nmean, cov, n = [0, 0], [[1, rho], [rho, 1]], 1000\nXY = XY_rng.multivariate_normal(mean, cov, n)\n\nXY_ref_rng = np.random.default_rng(SEED)\ncov_ref, n_ = [[1, 0], [0, 1]], n\nXY_ref = XY_ref_rng.multivariate_normal(mean, cov_ref, n_)\n```\n\n The tensorboard extension is already loaded. To reload it, use:\n %reload_ext tensorboard\n The jdc module is not an IPython extension.\n\n\nWe will train a neural network with `torch` and use GPU if available:\n\n\n```python\nDEVICE = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n\nif DEVICE == \"cuda\": # print current GPU name if available\n print(\"Using GPU:\", torch.cuda.get_device_name(torch.cuda.current_device()))\n```\n\nWhen GPU is available, you can use [GPU dashboards][gpu] on the left to monitor GPU utilizations.\n\n[gpu]: https://github.com/rapidsai/jupyterlab-nvdashboard\n\n\n\n**How to train a neural network by gradient descent?**\n\nWe will first consider a simple implementation followed by a more practical implementation.\n\n## A simple implementation of gradient descent\n\nConsider solving for a given $z\\in \\mathbb{R}$,\n\n$$ \\inf_{w\\in \\mathbb{R}} \\overbrace{e^{w\\cdot z}}^{L(w):=}.$$\n\nWe will train one parameter, namely, $w$, to minimize the loss $L(w)$.\n\n**Exercise** \n\nWhat is the solution for $z=-1$?\n\n**Solution**\n\nWith $z=-1$,\n\n$$\nL(w) = e^{-w} \\geq 0\n$$\n\nwhich is achievable with equality as $w\\to \\infty$.\n\n**How to implement the loss function?**\n\nWe will define the loss function using tensors:\n\n\n```python\nz = Tensor([-1]).to(DEVICE) # default tensor type on a designated device\n\n\ndef L(w):\n return (w * z).exp()\n\n\nL(float(\"inf\"))\n```\n\n\n\n\n tensor([0.])\n\n\n\nThe function `L` is vectorized because `Tensor` operations follow the [broadcasting rules of `numpy`](https://numpy.org/doc/stable/user/basics.broadcasting.html):\n\n\n```python\nww = np.linspace(0, 10, 100)\nax = sns.lineplot(\n x=ww,\n y=L(Tensor(ww).to(DEVICE)).cpu().numpy(), # convert to numpy array for plotting\n)\nax.set(xlabel=r\"$w$\", title=r\"$L(w)=e^{-w}$\")\nax.axhline(L(float(\"inf\")), ls=\"--\", c=\"r\")\nplt.show()\n```\n\n**What is gradient descent?**\n\nA gradient descent algorithm updates the parameter $w$ iteratively starting with some initial $w_0$:\n\n$$w_{i+1} = w_i - s_i \\nabla L(w_i) \\qquad \\text{for }i\\geq 0,$$\n\nwhere $s_i$ is the *learning rate* (*step size*).\n\n**How to compute the gradient?**\n\nWith $w=0$, \n\n$$\\nabla L(0) = \\left.-e^{-w}\\right|_{w=0}=-1,$$ \n\nwhich can be computed using `backward` ([backpropagation][bp]):\n\n[bp]: https://en.wikipedia.org/wiki/Backpropagation\n\n\n```python\nw = Tensor([0]).to(DEVICE).requires_grad_() # requires gradient calculation for w\nL(w).backward() # calculate the gradient by backpropagation\nw.grad\n```\n\n\n\n\n tensor([-1.])\n\n\n\nUnder the hood, the function call `L(w)` \n\n- not only return the loss function evaluated at `w`, but also\n- updates a computational graph for calculating the gradient since `w` `requires_grad_()`.\n\n**How to implement the gradient descent?**\n\nWith a learning rate of `0.001`:\n\n\n```python\nfor i in range(1000):\n w.grad = None # zero the gradient to avoid accumulation\n L(w).backward()\n with torch.no_grad(): # updates the weights in place without gradient calculation\n w -= w.grad * 1e-3\n\nprint(\"w:\", w.item(), \"\\nL(w):\", L(w).item())\n```\n\n w: 0.6933202147483826 \n L(w): 0.4999134838581085\n\n\n**What is `torch.no_grad()`?**\n\nIt sets up a context where the computational graph will not be updated. In particular,\n\n```Python\nw -= w.grad * 1e-3\n```\n\nshould not be differentiated in the subsequent calculations of the gradient.\n\n[no_grad]: https://pytorch.org/docs/stable/generated/torch.no_grad.html\n\n**Exercise** \n\nRepeatedly run the above cell until you get `L(w)` below `0.001`. How large is the value of `w`? What is the limitations of the simple gradient descent algorithm?\n\n\n**Solution** \n\nThe value of `w` needs to be smaller than `6.9`. The convergence can be slow, especially when the learning rate is small. Also, `w` can be far away from its optimal value even if `L(w)` is close to its minimum.\n\n\n## A practical implementation\n\nFor a neural network to approximate a sophisticated function, it should have many parameters (*degrees of freedom*).\n\n**How to define a neural network?**\n\nThe following code [defines a simple neural network][define] with 3 fully-connected (fc) hidden layers:\n\n \n\nwhere \n\n- $\\M{W}_l$ and $\\M{b}_l$ are the weight and bias respectively for the linear transformation $\\M{W}_l \\M{a}_l + \\M{b}_l$ of the $l$-th layer; and\n- $\\sigma$ for the first 2 hidden layers is an activation function called the [*exponential linear unit (ELU)*](https://pytorch.org/docs/stable/generated/torch.nn.ELU.html).\n\n[define]: https://pytorch.org/tutorials/beginner/blitz/neural_networks_tutorial.html#define-the-network\n\n\n```python\nclass Net(nn.Module):\n def __init__(self, input_size=2, hidden_size=100, sigma=0.02):\n super().__init__()\n self.fc1 = nn.Linear(input_size, hidden_size) # fully-connected (fc) layer\n self.fc2 = nn.Linear(hidden_size, hidden_size) # layer 2\n self.fc3 = nn.Linear(hidden_size, 1) # layer 3\n nn.init.normal_(self.fc1.weight, std=sigma) #\n nn.init.constant_(self.fc1.bias, 0)\n nn.init.normal_(self.fc2.weight, std=sigma)\n nn.init.constant_(self.fc2.bias, 0)\n nn.init.normal_(self.fc3.weight, std=sigma)\n nn.init.constant_(self.fc3.bias, 0)\n\n def forward(self, z):\n a1 = F.elu(self.fc1(z))\n a2 = F.elu(self.fc2(a1))\n t = self.fc3(a2)\n return t\n\n\ntorch.manual_seed(SEED) # seed RNG for PyTorch\nnet = Net().to(DEVICE)\nprint(net)\n```\n\n Net(\n (fc1): Linear(in_features=2, out_features=100, bias=True)\n (fc2): Linear(in_features=100, out_features=100, bias=True)\n (fc3): Linear(in_features=100, out_features=1, bias=True)\n )\n\n\nThe neural network is also a vectorized function. E.g., the following call `net` once to plots the density estimate of all $t(\\R{Z}_i)$'s and $t(\\R{Z}'_i)$'s.\n\n\n```python\nZ = Tensor(XY).to(DEVICE)\nZ_ref = Tensor(XY_ref).to(DEVICE)\n\ntZ = (\n net(torch.cat((Z, Z_ref), dim=0)) # compute t(Z_i)'s and t(Z'_i)\n # output needs to be converted back to an array on CPU for plotting\n .cpu() # copy back to CPU\n .detach() # detach from current graph (no gradient calculation)\n .numpy() # convert output back to numpy\n)\n\ntZ_df = pd.DataFrame(data=tZ, columns=[\"t\"])\nsns.kdeplot(data=tZ_df, x=\"t\")\nplt.show()\n```\n\nFor 2D sample $(x,y)\\in \\mc{Z}$, we can plot the neural network $t(x,y)$ as a heatmap. The following code adds a method `plot` to `Net` using [`jdc`](https://alexhagen.github.io/jdc):\n\n\n```python\n%%add_to Net\ndef plot(net, xmin=-5, xmax=5, ymin=-5, ymax=5, xgrids=50, ygrids=50, ax=None):\n \"\"\"Plot a heat map of a neural network net. net can only have two inputs.\"\"\"\n x, y = np.mgrid[xmin : xmax : xgrids * 1j, ymin : ymax : ygrids * 1j]\n xy = np.concatenate((x[:, :, None], y[:, :, None]), axis=2)\n with torch.no_grad():\n z = (\n net(\n torch.cat(\n [\n Tensor(x.reshape(-1, 1)).to(DEVICE),\n Tensor(y.reshape(-1, 1)).to(DEVICE),\n ],\n dim=-1,\n )\n )\n .reshape(x.shape)\n .cpu()\n )\n if ax is None:\n ax = plt.gca()\n im = ax.pcolormesh(x, y, z, cmap=\"RdBu_r\", shading=\"auto\")\n ax.figure.colorbar(im)\n ax.set(xlabel=r\"$x$\", ylabel=r\"$y$\", title=r\"Heatmap of $t(z)$ for $z=(x,y)$\")\n```\n\nTo plot the heatmap:\n\n\n```python\nnet.plot()\n```\n\n**Exercise** \n\nWhy are the values of $t(\\R{Z}_i)$'s and $t(\\R{Z}'_i)$'s concentrated around $0$?\n\n**Solution** \n\nThe neural network parameters are all very close to $0$ as we have set a small variance `sigma=0.02` to initialize them randomly. Hence:\n\n- The linear transformation $\\M{W}_l (\\cdot) + \\M{b}_l$ is close to $0$ for when the weight and bias are close to $0$. \n- The ELU activation function $\\sigma$ is also close to $0$ if its input is close to $0$.\n\n**How to implements the divergence estimate?**\n\nWe decompose the approximate divergence lower bound in {eq}`avg-DV` as follows:\n\n$$\n\\begin{align}\n\\op{DV}(\\R{Z}^n,\\R{Z'}^{n'},\\theta) &:= \\underbrace{\\frac1{n} \\sum_{i\\in [n]} t(\\R{Z}_i)}_{\\text{(a)}} - \\underbrace{\\log \\frac1{n'} \\sum_{i\\in [n']} e^{t(\\R{Z}'_i)}}_{ \\underbrace{\\log \\sum_{i\\in [n']} e^{t(\\R{Z}'_i)}}_{\\text{(b)}} - \\underbrace{\\log n'}_{\\text{(c)}}} \n\\end{align}\n$$\n\nwhere $\\theta$ is a tuple of parameters (weights and biases) of the neural network that computes $t$:\n\n$$\n\\theta := (\\M{W}_l,\\M{b}_l|l\\in [3]).\n$$\n\n\n```python\ndef DV(Z, Z_ref, net):\n avg_tZ = net(Z).mean() # (a)\n log_avg_etZ_ref = net(Z_ref).logsumexp(dim=0) - np.log(Z_ref.shape[0]) # (b) - (c)\n return avg_tZ - log_avg_etZ_ref\n\n\nDV_estimate = DV(Z, Z_ref, net)\n```\n\n**Exercise** \n\nWhy is it preferrable to use `logsumexp(dim=0)` instead of `.exp().sum().log()`? Try running\n\n```Python\nTensor([100]).exp().log(), Tensor([100]).logsumexp(0)\n```\n\nin a separate console.\n\n**Solution** \n\n`logsumexp(dim=0)` is numerically more stable than `.exp().mean().log()` especially when the output of the exponential function is too large to be represented with the default floating point precision.\n\nTo calculate the gradient of the divergence estimate with respect to $\\theta$:\n\n\n```python\nnet.zero_grad() # zero the gradient values of all neural network parameters\nDV(Z, Z_ref, net).backward() # calculate the gradient\na_param = next(net.parameters())\n```\n\n`a_param` is a (module) parameter in $\\theta$ retrieved from the parameter iterator `parameters()`.\n\n**Exercise** \n\nCheck that the value of `a_param.grad` is non-zero. Is `a_param` a weight or a bias?\n\n**Solution** \n\nIt should be the weight matrix $\\M{W}_1$ because the shape is `torch.Size([100, 2])`.\n\n**How to gradient descend?**\n\nWe will use the [*Adam's* gradient descend algorithm][adam] implemented as an optimizer [`optim.Adam`][optimAdam]:\n\n[adam]: https://en.wikipedia.org/wiki/Stochastic_gradient_descent#cite_note-Adam2014-28\n[optimAdam]: https://pytorch.org/docs/stable/generated/torch.optim.Adam.html#torch.optim.Adam\n\n\n```python\nnet = Net().to(DEVICE)\noptimizer = optim.Adam(\n net.parameters(), lr=1e-3\n) # Allow Adam's optimizer to update the neural network parameters\noptimizer.step() # perform one step of the gradient descent\n```\n\nTo alleviate the problem of overfitting, the gradient is often calculated on randomly chosen batches:\n\n$$\n\\begin{align}\n\\R{L}(\\theta) := - \\bigg[\\frac1{\\abs{\\R{B}}} \\sum_{i\\in \\R{B}} t(\\R{Z}_i) - \\log \\frac1{\\abs{\\R{B}'}} \\sum_{i\\in \\R{B}'} e^{t(\\R{Z}'_i)} - \\log \\abs{\\R{B}'} \\bigg],\n\\end{align}\n$$\n\nwhich is the negative lower bound of the VD formula in {eq}`DV` but on the minibatches \n\n$$\\R{Z}_{\\R{B}}:=(\\R{Z}_i\\mid i\\in \\R{B})\\quad \\text{and}\\quad \\R{Z}'_{\\R{B}'}$$\n\nwhere $\\R{B}$ and $\\R{B}'$ are batches of uniformly randomly chosen indices from $[n]$ and $[n']$ respectively.\n\nThe neural network parameter is updated\n\n$$\n\\theta_{j+1} := \\theta_j - s_j \\nabla \\R{L}_j(\\theta_j),\n$$\n\nstarting with a randomly initialized $\\theta_0$ \nwhere $s_j>0$ is the learning rate and $\\R{L}_j$ is the loss evaluated on the $j$-th randomly chosen batches $\\R{B}_j$ and $\\R{B}'_j$.\n\nThe different batches are often obtained by \n- permuting the samples first, and then\n- partitioning the samples into batches.\n\nThis is illustrated by the figure below:\n\n\n\n\n```python\nn_iters_per_epoch = 10 # ideally a divisor of both n and n'\nbatch_size = int((Z.shape[0] + 0.5) / n_iters_per_epoch)\nbatch_size_ref = int((Z_ref.shape[0] + 0.5) / n_iters_per_epoch)\n```\n\nWe will use `tensorboard` to show the training logs. \nRerun the following to start a new log, for instance, after a change of parameters.\n\n\n```python\nif input(\"New log?[Y/n] \").lower() != \"n\":\n n_iter = n_epoch = 0 # keep counts for logging\n writer = SummaryWriter() # create a new folder under runs/ for logging\n```\n\n New log?[Y/n] \n\n\nThe following code carries out Adam's gradient descent on batch loss:\n\n\n```python\nif input(\"Train? [Y/n]\").lower() != \"n\":\n for i in range(10): # loop through entire data multiple times\n n_epoch += 1\n\n # random indices for selecting samples for all batches in one epoch\n idx = torch.randperm(Z.shape[0])\n idx_ref = torch.randperm(Z_ref.shape[0])\n\n for j in range(n_iters_per_epoch): # loop through multiple batches\n n_iter += 1\n optimizer.zero_grad()\n\n # obtain a random batch of samples\n batch_Z = Z[idx[j : Z.shape[0] : n_iters_per_epoch]]\n batch_Z_ref = Z_ref[idx_ref[j : Z_ref.shape[0] : n_iters_per_epoch]]\n\n # define the loss as negative DV divergence lower bound\n loss = -DV(batch_Z, batch_Z_ref, net)\n loss.backward() # calculate gradient\n optimizer.step() # descend\n\n writer.add_scalar(\"Loss/train\", loss.item(), global_step=n_epoch)\n\n # Estimate the divergence using all data\n with torch.no_grad():\n estimate = DV(Z, Z_ref, net).item()\n writer.add_scalar(\"Estimate\", estimate, global_step=n_epoch)\n net.plot()\n print(\"Divergence estimation:\", estimate)\n```\n\nRun the following to show the losses and divergence estimate in `tensorboard`. You can rerun the above cell to train the neural network more.\n\n\n```python\n%tensorboard --logdir=runs\n```\n\n\n\n\n\n\n\n\nThe ground truth is given by\n\n$$D(P_{\\R{Z}}\\|P_{\\R{Z}'}) = \\frac12 \\log(1-\\rho^2) $$\n\nwhere $\\rho$ is the randomly generated correlation in the previous notebook. \n\n**Exercise** \n\nCompute the ground truth using the formula above.\n\n\n```python\n### BEGIN SOLUTION\nground_truth = -0.5 * np.log(1 - rho ** 2)\n### END SOLUTION\nground_truth\n```\n\n\n\n\n 0.7405246745135301\n\n\n\n**Exercise** \n\nSee if you can get an estimate close to this value by training the neural network repeatedly as shown below.\n\n\n\n## Encapsulation\n\nIt is a good idea to encapsulate the training by a class, so multiple configurations can be run without interfering each other:\n\n\n```python\nclass DVTrainer:\n \"\"\"\n Neural estimator for KL divergence based on the sample DV lower bound.\n\n Estimate D(P_Z||P_Z') using samples Z and Z' by training a network t to maximize\n avg(t(Z)) - log avg(e^t(Z'))\n\n Parameters:\n ----------\n\n Z, Z_ref : Tensors with first dimension indicing the samples of Z and Z' respect.\n net : The neural network t that take Z as input and output a real number for each sample.\n n_iters_per_epoch : Number of iterations per epoch.\n writer_params : Parameters to be passed to SummaryWriter for logging.\n \"\"\"\n\n # constructor\n def __init__(self, Z, Z_ref, net, n_iters_per_epoch, writer_params={}, **kwargs):\n self.Z = Z\n self.Z_ref = Z_ref\n self.net = net\n self.n_iters_per_epoch = n_iters_per_epoch # ideally a divisor of both n and n'\n\n # set optimizer\n self.optimizer = optim.Adam(net.parameters(), **kwargs)\n\n # logging\n self.writer = SummaryWriter(\n **writer_params\n ) # create a new folder under runs/ for logging\n self.n_iter = self.n_epoch = 0 # keep counts for logging\n\n def step(self, epochs=1):\n \"\"\"\n Carries out the gradient descend for a number of epochs and returns\n the divergence estimate evaluated over the entire data.\n\n Loss for each epoch is recorded into the log, but only one divergence\n estimate is computed/logged using the entire dataset. Rerun the method,\n using a loop, to continue to train the neural network and log the result.\n\n Parameters:\n ----------\n epochs : number of epochs\n \"\"\"\n for i in range(epochs):\n self.n_epoch += 1\n\n # random indices for selecting samples for all batches in one epoch\n idx = torch.randperm(self.Z.shape[0])\n idx_ref = torch.randperm(self.Z_ref.shape[0])\n\n for j in range(self.n_iters_per_epoch):\n self.n_iter += 1\n self.optimizer.zero_grad()\n\n # obtain a random batch of samples\n batch_Z = self.Z[idx[i : self.Z.shape[0] : self.n_iters_per_epoch]]\n batch_Z_ref = self.Z_ref[\n idx_ref[i : self.Z_ref.shape[0] : self.n_iters_per_epoch]\n ]\n\n # define the loss as negative DV divergence lower bound\n loss = -DV(batch_Z, batch_Z_ref, self.net)\n loss.backward() # calculate gradient\n self.optimizer.step() # descend\n\n self.writer.add_scalar(\n \"Loss/train\", loss.item(), global_step=self.n_iter\n )\n\n with torch.no_grad():\n estimate = DV(Z, Z_ref, self.net).item()\n self.writer.add_scalar(\"Estimate\", estimate, global_step=self.n_epoch)\n return estimate\n```\n\nTo use the above class to train, we first create an instance:\n\n\n```python\ntorch.manual_seed(SEED)\nnet = Net().to(DEVICE)\ntrainer = DVTrainer(Z, Z_ref, net, n_iters_per_epoch=10)\n```\n\nNext, run `step` iteratively to train the neural network:\n\n\n```python\nif input(\"Train? [Y/n]\").lower() != \"n\":\n for i in range(10):\n print(\"Divergence estimate:\", trainer.step(10))\n net.plot()\n```\n\n\n```python\n%tensorboard --logdir=runs\n```\n\n\n Reusing TensorBoard on port 6006 (pid 4485), started 0:14:03 ago. (Use '!kill 4485' to kill it.)\n\n\n\n\n\n\n\n\n\n## Clean-up\n\nIt is important to release the resources if it is no longer used. You can release the memory or GPU memory by `Kernel->Shut Down Kernel`.\n\nTo clear the logs:\n\n\n```python\nif input('Delete logs? [y/N]').lower() == 'y':\n !rm -rf ./runs\n```\n\n Delete logs? [y/N] y\n\n\nTo kill a tensorboard instance without shutting down the notebook kernel:\n\n\n```python\ntb.notebook.list() # list all the running TensorBoard notebooks.\nwhile (pid := input('pid to kill? (press enter to exit)')):\n !kill {pid}\n```\n\n Known TensorBoard instances:\n - port 6006: logdir runs (started 0:00:37 ago; pid 9479)\n\n\n pid to kill? (press enter to exit) 9479\n pid to kill? (press enter to exit) \n\n", "meta": {"hexsha": "7483ced0dab8860829cfb9921e4e9903b117db79", "size": 237519, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "source/part1/Training.ipynb", "max_stars_repo_name": "ccha23/miml", "max_stars_repo_head_hexsha": "6a41de1c0bb41d38e3cdc6e9c27363215b7729b9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-08-17T15:16:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-17T15:16:11.000Z", "max_issues_repo_path": "source/part1/Training.ipynb", "max_issues_repo_name": "ccha23/miml", "max_issues_repo_head_hexsha": "6a41de1c0bb41d38e3cdc6e9c27363215b7729b9", "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": "source/part1/Training.ipynb", "max_forks_repo_name": "ccha23/miml", "max_forks_repo_head_hexsha": "6a41de1c0bb41d38e3cdc6e9c27363215b7729b9", "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.1655384615, "max_line_length": 69604, "alphanum_fraction": 0.8840219098, "converted": true, "num_tokens": 5284, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.944176857294597, "lm_q2_score": 0.9073122119620788, "lm_q1q2_score": 0.8566631928753649}} {"text": "## Problem Sheet Question 7b\n\nThe general form of the population growth differential equation\n$$ y^{'}-y+x=0, \\ \\ (0 \\leq x \\leq 1) $$\nwith the initial condition\n$$y(0)=0$$\nFor h=0.2.\n# Midpoint method Solution\n\\begin{equation}\n\\frac{w_{i+1}-w_i}{h}=f(x_i+\\frac{h}{2},w_i+\\frac{h}{2}f(x_i,w_i))\n\\end{equation}\nRearranging \n\\begin{equation}\nw_{i+1}=w_i+hf(x_i+\\frac{h}{2},w_i+\\frac{h}{2}f(x_i,w_i))\n\\end{equation}\n\\begin{equation}\nw_{i+1}=w_i+h(k_2)\n\\end{equation}\n\\begin{equation}\nk_1=w_i-x_i+2\n\\end{equation}\n\\begin{equation}\nk_2=w_i+\\frac{h}{2}k_1-(x_i+\\frac{h}{2})+2)\n\\end{equation}\n\n\n```python\nimport numpy as np\nimport math \n%matplotlib inline\nimport matplotlib.pyplot as plt # side-stepping mpl backend\nimport matplotlib.gridspec as gridspec # subplots\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n```\n\n\n```python\ndef myfun_xy(x,y):\n return y-x+2\n\n#PLOTS\ndef Midpoint_Question2(N,IC):\n\n x_start=0\n INTITIAL_CONDITION=IC\n h=0.2\n N=N+1\n x=np.zeros(N)\n w=np.zeros(N)\n k_mat=np.zeros((2,N))\n k=0\n w[0]=INTITIAL_CONDITION\n x[0]=x_start\n \n for k in range (0,N-1):\n k_mat[0,k]=myfun_xy(x[k],w[k])\n k_mat[1,k]=myfun_xy(x[k]+h/2,w[k]+h/2*k_mat[0,k])\n w[k+1]=w[k]+h*(k_mat[1,k])\n x[k+1]=x[k]+h\n\n\n fig = plt.figure(figsize=(10,4))\n plt.plot(x,w,'-.o',color='blue')\n plt.title('Numerical Solution h=%s'%(h))\n\n # --- title, explanatory text and save\n fig.suptitle(r\"$y'=y-x+2$\", fontsize=20)\n plt.tight_layout()\n plt.subplots_adjust(top=0.85) \n print('x')\n print(x)\n print('k1')\n print(k_mat[0,:])\n print('k2')\n print(k_mat[1,:])\n print('w')\n print(w)\n```\n\n\n```python\n# Midpoint_Question2(N,IC)\nMidpoint_Question2(5,1)\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "ff431756cecc0023e702787716c82632cd27cd87", "size": 20216, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Chapter 03 - Runge Kutta/Supplementary/.ipynb_checkpoints/02_RK Mid point Example - Review Question 7b-checkpoint.ipynb", "max_stars_repo_name": "jjcrofts77/Numerical-Analysis-Python", "max_stars_repo_head_hexsha": "97e4b9274397f969810581ff95f4026f361a56a2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 69, "max_stars_repo_stars_event_min_datetime": "2019-09-05T21:39:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T14:00:25.000Z", "max_issues_repo_path": "Chapter 03 - Runge Kutta/Supplementary/.ipynb_checkpoints/02_RK Mid point Example - Review Question 7b-checkpoint.ipynb", "max_issues_repo_name": "jjcrofts77/Numerical-Analysis-Python", "max_issues_repo_head_hexsha": "97e4b9274397f969810581ff95f4026f361a56a2", "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": "Chapter 03 - Runge Kutta/Supplementary/.ipynb_checkpoints/02_RK Mid point Example - Review Question 7b-checkpoint.ipynb", "max_forks_repo_name": "jjcrofts77/Numerical-Analysis-Python", "max_forks_repo_head_hexsha": "97e4b9274397f969810581ff95f4026f361a56a2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 13, "max_forks_repo_forks_event_min_datetime": "2021-06-17T15:34:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T14:53:43.000Z", "avg_line_length": 116.183908046, "max_line_length": 16092, "alphanum_fraction": 0.8619410368, "converted": true, "num_tokens": 658, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625069680098, "lm_q2_score": 0.919642529525996, "lm_q1q2_score": 0.8566125360666862}} {"text": "# Exponentials, Radicals, and Logs\nUp to this point, all of our equations have included standard arithmetic operations, such as division, multiplication, addition, and subtraction. Many real-world calculations involve exponential values in which numbers are raised by a specific power.\n\n## Exponentials\nA simple case of using an exponential is squaring a number; in other words, multipying a number by itself. For example, 2 squared is 2 times 2, which is 4. This is written like this:\n\n\\begin{equation}2^{2} = 2 \\cdot 2 = 4\\end{equation}\n\nSimilarly, 2 cubed is 2 times 2 times 2 (which is of course 8):\n\n\\begin{equation}2^{3} = 2 \\cdot 2 \\cdot 2 = 8\\end{equation}\n\nIn Python, you use the ****** operator, like this example in which **x** is assigned the value of 5 raised to the power of 3 (in other words, 5 x 5 x 5, or 5-cubed):\n\n\n```python\nx = 5**3\nprint(x)\n```\n\n 125\n\n\nMultiplying a number by itself twice or three times to calculate the square or cube of a number is a common operation, but you can raise a number by any exponential power. For example, the following notation shows 4 to the power of 7 (or 4 x 4 x 4 x 4 x 4 x 4 x 4), which has the value:\n\n\\begin{equation}4^{7} = 16384 \\end{equation}\n\nIn mathematical terminology, **4** is the *base*, and **7** is the *power* or *exponent* in this expression.\n\n## Radicals (Roots)\nWhile it's common to need to calculate the solution for a given base and exponential, sometimes you'll need to calculate one or other of the elements themselves. For example, consider the following expression:\n\n\\begin{equation}?^{2} = 9 \\end{equation}\n\nThis expression is asking, given a number (9) and an exponent (2), what's the base? In other words, which number multipled by itself results in 9? This type of operation is referred to as calculating the *root*, and in this particular case it's the *square root* (the base for a specified number given the exponential **2**). In this case, the answer is 3, because 3 x 3 = 9. We show this with a **√** symbol, like this:\n\n\\begin{equation}\\sqrt{9} = 3 \\end{equation}\n\nOther common roots include the *cube root* (the base for a specified number given the exponential **3**). For example, the cube root of 64 is 4 (because 4 x 4 x 4 = 64). To show that this is the cube root, we include the exponent **3** in the **√** symbol, like this:\n\n\\begin{equation}\\sqrt[3]{64} = 4 \\end{equation}\n\nWe can calculate any root of any non-negative number, indicating the exponent in the **√** symbol.\n\nThe **math** package in Python includes a **sqrt** function that calculates the square root of a number. To calculate other roots, you need to reverse the exponential calculation by raising the given number to the power of 1 divided by the given exponent:\n\n\n```python\nimport math\n\n# Calculate square root of 25\nx = math.sqrt(25)\nprint (x)\n\n# Calculate cube root of 64\ncr = round(64 ** (1. / 3))\nprint(cr)\n```\n\n 5.0\n 4\n\n\nThe code used in Python to calculate roots other than the square root reveals something about the relationship between roots and exponentials. The exponential root of a number is the same as that number raised to the power of 1 divided by the exponential. For example, consider the following statement:\n\n\\begin{equation} 8^{\\frac{1}{3}} = \\sqrt[3]{8} = 2 \\end{equation}\n\nNote that a number to the power of 1/3 is the same as the cube root of that number.\n\nBased on the same arithmetic, a number to the power of 1/2 is the same as the square root of the number:\n\n\\begin{equation} 9^{\\frac{1}{2}} = \\sqrt{9} = 3 \\end{equation}\n\nYou can see this for yourself with the following Python code:\n\n\n```python\nimport math\n\nprint (9**0.5)\nprint (math.sqrt(9))\n```\n\n## Logarithms\nAnother consideration for exponential values is the requirement occassionally to determine the exponent for a given number and base. In other words, how many times do I need to multiply a base number by itself to get the given result. This kind of calculation is known as the *logarithm*.\n\nFor example, consider the following expression:\n\n\\begin{equation}4^{?} = 16 \\end{equation}\n\nIn other words, to what power must you raise 4 to produce the result 16?\n\nThe answer to this is 2, because 4 x 4 (or 4 to the power of 2) = 16. The notation looks like this:\n\n\\begin{equation}log_{4}(16) = 2 \\end{equation}\n\nIn Python, you can calculate the logarithm of a number using the **log** function in the **math** package, indicating the number and the base:\n\n\n```python\nimport math\n\nx = math.log(16, 4)\nprint(x)\n```\n\nThe final thing you need to know about exponentials and logarithms is that there are some special logarithms:\n\nThe *common* logarithm of a number is its exponential for the base **10**. You'll occassionally see this written using the usual *log* notation with the base omitted:\n\n\\begin{equation}log(1000) = 3 \\end{equation}\n\nAnother special logarithm is something called the *natural log*, which is a exponential of a number for base ***e***, where ***e*** is a constant with the approximate value 2.718. This number occurs naturally in a lot of scenarios, and you'll see it often as you work with data in many analytical contexts. For the time being, just be aware that the natural log is sometimes written as ***ln***:\n\n\\begin{equation}log_{e}(64) = ln(64) = 4.1589 \\end{equation}\n\nThe **math.log** function in Python returns the natural log (base ***e***) when no base is specified. Note that this can be confusing, as the mathematical notation *log* with no base usually refers to the common log (base **10**). To return the common log in Python, use the **math.log10** function:\n\n\n```python\nimport math\n\n# Natural log of 29\nprint (math.log(29))\n\n# Common log of 100\nprint(math.log10(100))\n```\n\n 3.367295829986474\n 2.0\n\n\n## Solving Equations with Exponentials\nOK, so now that you have a basic understanding of exponentials, roots, and logarithms; let's take a look at some equations that involve exponential calculations.\n\nLet's start with what might at first glance look like a complicated example, but don't worry - we'll solve it step-by-step and learn a few tricks along the way:\n\n\\begin{equation}2y = 2x^{4} ( \\frac{x^{2} + 2x^{2}}{x^{3}} ) \\end{equation}\n\nFirst, let's deal with the fraction on the right side. The numerator of this fraction is x2 + 2x2 - so we're adding two exponential terms. When the terms you're adding (or subtracting) have the same exponential, you can simply add (or subtract) the coefficients. In this case, x2 is the same as 1x2, which when added to 2x2 gives us the result 3x2, so our equation now looks like this: \n\n\\begin{equation}2y = 2x^{4} ( \\frac{3x^{2}}{x^{3}} ) \\end{equation}\n\nNow that we've condolidated the numerator, let's simplify the entire fraction by dividing the numerator by the denominator. When you divide exponential terms with the same variable, you simply divide the coefficients as you usually would and subtract the exponential of the denominator from the exponential of the numerator. In this case, we're dividing 3x2 by 1x3: The coefficient 3 divided by 1 is 3, and the exponential 2 minus 3 is -1, so the result is 3x-1, making our equation:\n\n\\begin{equation}2y = 2x^{4} ( 3x^{-1} ) \\end{equation}\n\nSo now we've got rid of the fraction on the right side, let's deal with the remaining multiplication. We need to multiply 3x-1 by 2x4. Multiplication, is the opposite of division, so this time we'll multipy the coefficients and add the exponentials: 3 multiplied by 2 is 6, and -1 + 4 is 3, so the result is 6x3:\n\n\\begin{equation}2y = 6x^{3} \\end{equation}\n\nWe're in the home stretch now, we just need to isolate y on the left side, and we can do that by dividing both sides by 2. Note that we're not dividing by an exponential, we simply need to divide the whole 6x3 term by two; and half of 6 times x3 is just 3 times x3:\n\n\\begin{equation}y = 3x^{3} \\end{equation}\n\nNow we have a solution that defines y in terms of x. We can use Python to plot the line created by this equation for a set of arbitrary *x* and *y* values:\n\n\n```python\nimport pandas as pd\n\n# Create a dataframe with an x column containing values from -10 to 10\ndf = pd.DataFrame ({'x': range(-10, 11)})\n\n# Add a y column by applying the slope-intercept equation to x\ndf['y'] = 3*df['x']**3\n\n#Display the dataframe\nprint(df)\n\n# Plot the line\n%matplotlib inline\nfrom matplotlib import pyplot as plt\n\nplt.plot(df.x, df.y, color=\"magenta\")\nplt.xlabel('x')\nplt.ylabel('y')\nplt.grid()\nplt.axhline()\nplt.axvline()\nplt.show()\n```\n\nNote that the line is curved. This is symptomatic of an exponential equation: as values on one axis increase or decrease, the values on the other axis scale *exponentially* rather than *linearly*.\n\nLet's look at an example in which x is the exponential, not the base:\n\n\\begin{equation}y = 2^{x} \\end{equation}\n\nWe can still plot this as a line:\n\n\n```python\nimport pandas as pd\n\n# Create a dataframe with an x column containing values from -10 to 10\ndf = pd.DataFrame ({'x': range(-10, 11)})\n\n# Add a y column by applying the slope-intercept equation to x\ndf['y'] = 2.0**df['x']\n\n#Display the dataframe\nprint(df)\n\n# Plot the line\n%matplotlib inline\nfrom matplotlib import pyplot as plt\n\nplt.plot(df.x, df.y, color=\"magenta\")\nplt.xlabel('x')\nplt.ylabel('y')\nplt.grid()\nplt.axhline()\nplt.axvline()\nplt.show()\n```\n\nNote that when the exponential is a negative number, Python reports the result as 0. Actually, it's a very small fractional number, but because the base is positive the exponential number will always positive. Also, note the rate at which y increases as x increases - exponential growth can be be pretty dramatic.\n\n**So what's the practical application of this?**\n\nWell, let's suppose you deposit $100 in a bank account that earns 5% interest per year. What would the balance of the account be in twenty years, assuming you don't deposit or withdraw any additional funds?\n\nTo work this out, you could calculate the balance for each year:\n\nAfter the first year, the balance will be the initial deposit ($100) plus 5% of that amount:\n\n\\begin{equation}y_1 = 100 + (100 \\cdot 0.05) \\end{equation}\n\nAnother way of saying this is:\n\n\\begin{equation}y_1 = 100 \\cdot 1.05 \\end{equation}\n\nAt the end of year two, the balance will be the year one balance plus 5%:\n\n\\begin{equation}y_2 = 100 \\cdot 1.05 \\cdot 1.05 \\end{equation}\n\nNote that the interest for year two, is the interest for year one multiplied by itself - in other words, squared. So another way of saying this is:\n\n\\begin{equation}y_2 = 100 \\cdot 1.05^{2} \\end{equation}\n\nIt turns out, if we just use the year as the exponent, we can easily calculate the growth after twenty years like this:\n\n\\begin{equation}y_{20} = 100 \\cdot 1.05^{20} \\end{equation}\n\nLet's apply this logic in Python to see how the account balance would grow over twenty years:\n\n\n```python\nimport pandas as pd\n\n# Create a dataframe with 20 years\ndf = pd.DataFrame ({'Year': range(1, 21)})\n\n# Calculate the balance for each year based on the exponential growth from interest\ndf['Balance'] = 100 * (1.05**df['Year'])\n\n#Display the dataframe\nprint(df)\n\n# Plot the line\n%matplotlib inline\nfrom matplotlib import pyplot as plt\n\nplt.plot(df.Year, df.Balance, color=\"green\")\nplt.xlabel('Year')\nplt.ylabel('Balance')\nplt.show()\n```\n", "meta": {"hexsha": "94f3fea8a6ae424c8d094d8e2a1cc0165080c460", "size": 43036, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "MathsToML/Module01-Equations, Graphs, and Functions/01-04-Exponentials Radicals and Logarithms.ipynb", "max_stars_repo_name": "hpaucar/data-mining-repo", "max_stars_repo_head_hexsha": "d0e48520bc6c01d7cb72e882154cde08020e1d33", "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": "MathsToML/Module01-Equations, Graphs, and Functions/01-04-Exponentials Radicals and Logarithms.ipynb", "max_issues_repo_name": "hpaucar/data-mining-repo", "max_issues_repo_head_hexsha": "d0e48520bc6c01d7cb72e882154cde08020e1d33", "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": "MathsToML/Module01-Equations, Graphs, and Functions/01-04-Exponentials Radicals and Logarithms.ipynb", "max_forks_repo_name": "hpaucar/data-mining-repo", "max_forks_repo_head_hexsha": "d0e48520bc6c01d7cb72e882154cde08020e1d33", "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.1390374332, "max_line_length": 14874, "alphanum_fraction": 0.851008458, "converted": true, "num_tokens": 3172, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.914900950352329, "lm_q2_score": 0.9362850048591, "lm_q1q2_score": 0.8566080407462257}} {"text": "### 적분\n- 부정적분, 정적분\n\n- 부정적분\n - 미분과 반대되는 개념, 반-미분\n - 도함수 미분되기 전의 원래 함수 찾는 과정\n \n\n- 편미분의 부정적분\n - 편미분을 한 도함수에서 원래의 함수를 찾을 수 있다.\n - C(y) 가 y의 함수일 수 있다. 상수일 수도 있다.\n\n- 다차 도함수와 다중적분\n - 변수 순서대로 적분\n\n\n```python\nimport sympy\nx = sympy.symbols('x')\nf = x * sympy.exp(x) + sympy.exp(x)\nf\n```\n\n\n\n\n$\\displaystyle x e^{x} + e^{x}$\n\n\n\n\n```python\nsympy.integrate(f)\n```\n\n\n\n\n$\\displaystyle x e^{x}$\n\n\n\n\n```python\nx, y = sympy.symbols('x y')\nf = 2 * x + y\nf\n```\n\n\n\n\n$\\displaystyle 2 x + y$\n\n\n\n\n```python\nsympy.integrate(f, x)\n```\n\n\n\n\n$\\displaystyle x^{2} + x y$\n\n\n\n\n```python\nx = sympy.symbols('x')\nf = 3 * x ** 2\nsympy.integrate(f)\n```\n\n\n\n\n$\\displaystyle x^{3}$\n\n\n\n\n```python\nx = sympy.symbols('x')\nf = 3 * x ** 2 - 6 * x + 1\nsympy.integrate(f)\n```\n\n\n\n\n$\\displaystyle x^{3} - 3 x^{2} + x$\n\n\n\n\n```python\nx = sympy.symbols('x')\nf = 2 + 6 * x + 4 * sympy.exp(x) + 5 / x\nsympy.integrate(f)\n```\n\n\n\n\n$\\displaystyle 3 x^{2} + 2 x + 4 e^{x} + 5 \\log{\\left(x \\right)}$\n\n\n\n\n```python\nx = sympy.symbols('x')\nf = 2 * x / (x ** 2 - 1)\nsympy.integrate(f)\n```\n\n\n\n\n$\\displaystyle \\log{\\left(x^{2} - 1 \\right)}$\n\n\n\n\n```python\nx, y = sympy.symbols('x y')\nf = 1 + x * y\nsympy.integrate(f, x)\n```\n\n\n\n\n$\\displaystyle \\frac{x^{2} y}{2} + x$\n\n\n\n\n```python\nx, y = sympy.symbols('x y')\nf = x * y * sympy.exp(x ** 2 + y ** 2)\nsympy.simplify(sympy.integrate(f, x))\n```\n\n\n\n\n$\\displaystyle \\frac{y e^{x^{2} + y^{2}}}{2}$\n\n\n\n- 정적분\n - 독립변수 x가 어떤 구간 [a, b] 사이일 때 그 구간에서 함수 f(x)의 값과 수평선(x 축)이 이루는 면적을 구하는 방법\n\n\n```python\nfrom matplotlib.patches import Polygon\n\n\ndef f(x):\n return x ** 3 - 3 * x ** 2 + x + 6\n\n\na, b = 0, 2\nx = np.linspace(a - 0.5, b + 0.5, 50)\ny = f(x)\n\nax = plt.subplot(111)\nplt.title(\"정적분의 예\")\nplt.plot(x, y, 'r', linewidth=2)\nplt.ylim(bottom=0)\nix = np.linspace(a, b)\niy = f(ix)\nverts = [(a, 0)] + list(zip(ix, iy)) + [(b, 0)]\npoly = Polygon(verts, facecolor='0.9', edgecolor='0.5')\nax.add_patch(poly)\nplt.text(0.5 * (a + b), 0.2 * (f(a) + f(b)), r\"$\\int_a^b f(x)dx$\",\n horizontalalignment='center', fontsize=20)\nplt.figtext(0.9, 0.05, '$x$')\nplt.figtext(0.1, 0.9, '$y$')\nax.spines['right'].set_visible(False)\nax.spines['top'].set_visible(False)\nax.xaxis.set_ticks_position('bottom')\nax.set_xticks((a, b))\nax.set_xticklabels(('$a$', '$b$'))\nax.set_yticks([])\nax.set_xlim(-2, 4)\nax.set_ylim(0, 8)\nplt.show()\n```\n\n\n```python\nx, y = sympy.symbols('x y')\nf = x ** 3 - 3 * x ** 2 + x + 6\nf\n```\n\n\n\n\n$\\displaystyle x^{3} - 3 x^{2} + x + 6$\n\n\n\n\n```python\nF = sympy.integrate(f)\nF\n```\n\n\n\n\n$\\displaystyle \\frac{x^{4}}{4} - x^{3} + \\frac{x^{2}}{2} + 6 x$\n\n\n\n\n```python\n(F.subs(x, 2) - F.subs(x, 0)).evalf()\n```\n\n\n\n\n$\\displaystyle 10.0$\n\n\n\n\n```python\ndef f(x):\n return x ** 3 - 3 * x ** 2 + x + 6\n\n\nsp.integrate.quad(f, 0, 2)\n```\n\n\n\n\n (10.0, 1.1102230246251565e-13)\n\n\n\n\n```python\nsympy.symbols('x')\nf = 3 * x ** 2 - 6 * x + 1\nF = sympy.integrate(f)\n(F.subs(x, 1) - F.subs(x, 0))\n```\n\n\n\n\n$\\displaystyle -1$\n\n\n\n\n```python\ndef f(x):\n return 3 * x ** 2 - 6 * x + 1\n\n\nsp.integrate.quad(f, 0, 1)\n```\n\n\n\n\n (-1.0, 1.3085085171449517e-14)\n\n\n\n\n```python\nsympy.symbols('x')\nf = 2 + 6 * x + 4 * sympy.exp(x) + (5 / x)\nF = sympy.integrate(f)\n(F.subs(x, 10) - F.subs(x, 1))\n```\n\n\n\n\n$\\displaystyle - 4 e + 5 \\log{\\left(10 \\right)} + 315 + 4 e^{10}$\n\n\n\n\n```python\ndef f(x):\n return 2 + 6 * x + 4 * sympy.exp(x) + (5 / x)\n\n\nsp.integrate.quad(f, 1, 10)\n```\n\n\n\n\n (88421.50297737827, 1.5276890734473408e-06)\n\n\n\n\n```python\nfig = plt.figure()\nax = fig.add_subplot(111, projection='3d')\n_x = np.arange(12) / 2 + 2\n_y = np.arange(12) / 2\nX, Y = np.meshgrid(_x, _y)\nx, y = X.ravel(), Y.ravel()\nz = x * x - 10 * x + y + 50\nz0 = np.zeros_like(z)\nax.bar3d(x, y, z0, 0.48, 0.48, z)\nax.set_xlim(0, 10)\nax.set_ylim(-2, 10)\nax.set_zlim(0, 50)\nax.set_xlabel(\"x\")\nax.set_ylabel(\"y\")\nplt.title(\"f(x, y)\")\nplt.show()\n```\n\n\n```python\ndef f(x, y):\n return np.exp(-x * y) / y**2\n\nsp.integrate.dblquad(f, 1, np.inf, lambda x: 0, lambda x: np.inf)\n```\n\n\n\n\n (0.4999999999999961, 1.068453874338024e-08)\n\n\n\n\n```python\ndef f(x, y):\n return 1 + x * y\n\nsp.integrate.dblquad(f, -1, 1, lambda x: -1, lambda x: 1)\n```\n\n\n\n\n (4.0, 4.440892098500626e-14)\n\n\n\n- 다차원 함수의 단일 정적분\n - 2차원 함수이지만 단일 정적분을 하는 경우\n", "meta": {"hexsha": "d213c1fbbeaae786044f674ae9caba367fa7dab7", "size": 553459, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "4.3 integral_hyojunahn.ipynb", "max_stars_repo_name": "loveactualry/TIL", "max_stars_repo_head_hexsha": "0b111a1ec01cbbe44245611cb2d26489c2701f39", "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": "4.3 integral_hyojunahn.ipynb", "max_issues_repo_name": "loveactualry/TIL", "max_issues_repo_head_hexsha": "0b111a1ec01cbbe44245611cb2d26489c2701f39", "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": "4.3 integral_hyojunahn.ipynb", "max_forks_repo_name": "loveactualry/TIL", "max_forks_repo_head_hexsha": "0b111a1ec01cbbe44245611cb2d26489c2701f39", "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": 842.403348554, "max_line_length": 466044, "alphanum_fraction": 0.9500107506, "converted": true, "num_tokens": 1862, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741254760638, "lm_q2_score": 0.8991213826762113, "lm_q1q2_score": 0.8564797647996213}} {"text": "# Poisson Distribution - Waiting Time\n\n> This document is written in *R*.\n>\n> ***GitHub***: https://github.com/czs108\n\n## Background\n\n> A certain call centre receives on average **5** calls per minute.\n\n## Question A\n\n> What is the probability of receiving **3** calls in any given minute?\n\n\\begin{equation}\n\\lambda = 5\n\\end{equation}\n\n\\begin{equation}\n\\begin{split}\nP(X = 3) &= \\frac{e^{-5} \\times {5}^{3}}{3!} \\\\\n &= 0.1404\n\\end{split}\n\\end{equation}\n\nUse the `dpois` function.\n\n\n```R\ndpois(x=3, lambda=5)\n```\n\n\n0.140373895814281\n\n\n## Question B\n\n> What is the probability of receiving *no* calls in **2** minutes? \n\n\\begin{equation}\n\\lambda = 5 \\times 2 = 10\n\\end{equation}\n\n\\begin{equation}\n\\begin{split}\nP(X = 0) &= \\frac{e^{-10} \\times {10}^{0}}{0!} \\\\\n &= e^{-10}\n\\end{split}\n\\end{equation}\n\n\n```R\ndpois(x=0, lambda=10)\n```\n\n\n4.53999297624849e-05\n\n\nOr use the `exp` function directly.\n\n\n```R\nexp(-10)\n```\n\n\n4.53999297624849e-05\n\n\n## Question C\n\n> What is the probability of having to wait *less* than **1** minute for a call?\n\n\\begin{equation}\n\\begin{split}\nP(X \\geq 1) &= 1 - P(X = 0) \\\\\n &= 1 - \\frac{e^{-5} \\times {5}^{0}}{0!} \\\\\n &= 1 - e^{-5}\n\\end{split}\n\\end{equation}\n\n\n```R\n1 - exp(-5)\n```\n\n\n0.993262053000915\n\n\n## Question D\n\n> Write down an equation for the time $t$ in which you could be **90%** certain of receiving a call.\n\n\\begin{align}\n1 - P(X = 0) = 0.9 \\\\\nP(X = 0) = 0.1\n\\end{align}\n\n\\begin{equation}\n\\lambda = 5 \\cdot t\n\\end{equation}\n\n\\begin{equation}\n\\begin{split}\nP(X = 0) &= \\frac{e^{-\\lambda} \\times {\\lambda}^{0}}{0!} \\\\\n &= e^{-\\lambda} \\\\\n &= 0.1\n\\end{split}\n\\end{equation}\n\nThen we get\n\n\\begin{align}\n\\ln 0.1 = -2.3 \\\\\n\\lambda = 2.3\n\\end{align}\n\n\n```R\nlog(0.1)\n```\n\n\n-2.30258509299405\n\n\n\\begin{equation}\nt = \\lambda \\div 5 = 0.46\n\\end{equation}\n", "meta": {"hexsha": "7677185439affac6866b106671a709f302261306", "size": 5891, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "exercises/Poisson Distribution - Waiting Time.ipynb", "max_stars_repo_name": "czs108/Probability-Theory-Exercises", "max_stars_repo_head_hexsha": "60c6546db1e7f075b311d1e59b0afc3a13d93229", "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/Poisson Distribution - Waiting Time.ipynb", "max_issues_repo_name": "czs108/Probability-Theory-Exercises", "max_issues_repo_head_hexsha": "60c6546db1e7f075b311d1e59b0afc3a13d93229", "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/Poisson Distribution - Waiting Time.ipynb", "max_forks_repo_name": "czs108/Probability-Theory-Exercises", "max_forks_repo_head_hexsha": "60c6546db1e7f075b311d1e59b0afc3a13d93229", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-03-21T05:04:07.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-21T05:04:07.000Z", "avg_line_length": 18.7611464968, "max_line_length": 106, "alphanum_fraction": 0.429808182, "converted": true, "num_tokens": 687, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545333502203, "lm_q2_score": 0.9032942021480236, "lm_q1q2_score": 0.8564624927156188}} {"text": "# 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\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.00043200502\n 2.01072423406\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')\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')\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')\nplt.hist(d_t, bins=200, normed=True, histtype='step')\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')\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')\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": "51db78bd64a477d877ec790ba6bece8eb8d6fc16", "size": 107833, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Supporting_Notebooks/Computing_and_plotting_PDFs.ipynb", "max_stars_repo_name": "Mayakshanesht/Kalman-and-bayesian-filters", "max_stars_repo_head_hexsha": "967091f1c9640b4b3f96bbf5f422fee1b3e69778", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2017-03-14T23:48:40.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-30T13:53:00.000Z", "max_issues_repo_path": "Supporting_Notebooks/Computing_and_plotting_PDFs.ipynb", "max_issues_repo_name": "vishalmhjn/Kalman-and-Bayesian-Filters-in-Python", "max_issues_repo_head_hexsha": "0cc841f68c186b365bdd25f02cbb7a327f5c1417", "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": "vishalmhjn/Kalman-and-Bayesian-Filters-in-Python", "max_forks_repo_head_hexsha": "0cc841f68c186b365bdd25f02cbb7a327f5c1417", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2016-08-01T04:02:41.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-23T15:20:07.000Z", "avg_line_length": 216.0981963928, "max_line_length": 15082, "alphanum_fraction": 0.9061697254, "converted": true, "num_tokens": 2032, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802462567087, "lm_q2_score": 0.9324533130837862, "lm_q1q2_score": 0.8564399486240798}} {"text": "# Taylor series expansion and error analysis\n\n\n\n## Taylor series expansion\n\nDuring the lecture, we talked several times about the Taylor series as a way to formally determine the differential of a property. As a brief reminder, the Taylor series can be used to approximate the value of a function $f(x)$ at a location $f(x +h)$ with the help of a polynomial series:\n\n$$f(x+h) = \\sum_{i=1}^n \\frac{h^n}{n!} \\frac{d^nf}{dx^n}(h)$$\n\nAs an example in the lecture, we approximated the sine function at several locations. This was pretty easy as the derivatives of $f(x) = \\sin(x)$ can easily be calculated.\n\nHowever, this is not always the case. Think about a tiny bit more complex function: $f(x) = \\sin(x^2)$. Determining higher-order differentials quickly gets quite tricky - try it out, to convince yourself:\n\n$$f(x) = \\sin(x^2)$$\n\n$$\\frac{df}{dx} = 2x \\cos(x^2)$$\n\n$$\\frac{d^2f}{dx^2} = ?$$\n\n$$\\frac{d^3f}{dx^3} = ??$$\n\nCreating more differentials is a very systematic process and maybe not difficult - but requires quickly a lot of bookkeeping and is prone to errors - and it becomes very repetitive if you have to do it very often...\n\nAs soon as you read things in descriptions like: \"requires bookkeeping\", \"not difficult systematic process\" and \"repetitive\", I hope you think by now: **we should do that in Python**! Yes, correct!\n\nSo luckily, someone did the hard work of coding all these things into Python for us before: it is implemented in the sympy package for symbolic computation. \n\nWe'll have a look at some of the basic features in this notebook - and then apply it to determine Taylor Series Expansions, and finally to the accuracy estimation that we did in the last lecture.\n\n\n\n\n\n```python\nimport sympy as sym\nimport numpy as np\nimport matplotlib.pyplot as plt\n%matplotlib inline\n```\n\n\n```python\n# to get LaTeX function rendereing:\nsym.init_printing()\n```\n\n\n```python\nsym.var('x')\n```\n\n### Sine function\n\n\n```python\ndef plot_taylor(x0=0.0, n=1):\n func = sym.sin(x)#/x\n taylor = sym.series(func, x0=x0, n=n+1).removeO()\n\n evalfunc = sym.lambdify(x, func, modules=['numpy'])\n evaltaylor = sym.lambdify(x, taylor, modules=['numpy'])\n\n t = np.linspace(-2*np.pi, 3*np.pi, 100)\n plt.figure(figsize=(10,8))\n plt.plot(t, evalfunc(t), 'b', label='sin(x)')\n plt.plot(t, evaltaylor(t), 'r', label='Taylor')\n plt.plot(x0, evalfunc(x0), 'go', label='x0', markersize = 12)\n plt.legend(loc='upper left')\n plt.xlim([-1*np.pi, 2*np.pi])\n plt.ylim([-3,3])\n plt.show()\n```\n\n\n```python\nfrom ipywidgets import interactive\nfrom IPython.display import Audio, display\n```\n\n\n```python\nplt.figure(figsize=(10,8))\nplt.style.use(\"bmh\")\n```\n\n\n \n\n\n\n```python\nv = interactive(plot_taylor, x0=(0.0,np.pi,np.pi/10.), n=(1,8), r=(2,4))\ndisplay(v)\n```\n\n### Logarithm function\n\n\n```python\ndef plot_taylor_lnx(x0=0.0, n=1):\n \"\"\"Same method, different base function\"\"\"\n func = sym.ln(x)#/x\n taylor = sym.series(func, x0=x0, n=n+1).removeO()\n\n evalfunc = sym.lambdify(x, func, modules=['numpy'])\n evaltaylor = sym.lambdify(x, taylor, modules=['numpy'])\n\n t = np.linspace(0.01, 10, 100)\n plt.figure(figsize=(10,8))\n plt.plot(t, evalfunc(t), 'b', label='ln(x)')\n plt.plot(t, evaltaylor(t), 'r', label='Taylor')\n plt.plot(x0, evalfunc(x0), 'go', label='x0', markersize = 12)\n plt.legend(loc='upper left')\n plt.xlim([-0.2,10])\n plt.ylim([-3,3])\n plt.show()\n```\n\n\n```python\nv = interactive(plot_taylor_lnx, x0=(1,3,0.2), n=(1,8), r=(2,4))\ndisplay(v)\n```\n\n\n interactive(children=(FloatSlider(value=1.0, description='x0', max=3.0, min=1.0, step=0.2), IntSlider(value=1,…\n\n\n## Error analysis\n\nNote that, in previous examples: for higher degrees of approximation, the local solution gets better, but the extrapolation gets worse!\n\nAnalyzing this in a bit more detail:\n\n\n```python\ndef plot_taylor_error(x0=0.0, n=1, s=1):\n func = sym.sin(x)#/x\n taylor = sym.series(func, x0=x0, n=n+1).removeO()\n\n evalfunc = sym.lambdify(x, func, modules=['numpy'])\n evaltaylor = sym.lambdify(x, taylor, modules=['numpy'])\n\n t = np.linspace(-2*np.pi, 3*np.pi, 100)\n fig = plt.figure(figsize=(10,8))\n ax1 = fig.add_subplot(211)\n # plt.plot(t, evalfunc(t), 'b', label='sin(x)')\n ax1.plot(t, evaltaylor(t)-evalfunc(t), 'r', label='Taylor error')\n ax1.plot(x0, 0, 'go', label='x0', markersize = 12)\n plt.legend(loc='upper left')\n ax1.set_xlim([-1*np.pi, 2*np.pi])\n ax1.set_ylim([-s*3,s*3])\n ax2 = fig.add_subplot(212)\n ax2.plot(t, evalfunc(t), 'b', label='sin(x)')\n ax2.plot(t, evaltaylor(t), 'r', label='Taylor')\n ax2.plot(x0, evalfunc(x0), 'go', label='x0', markersize = 12)\n plt.legend(loc='upper left')\n ax2.set_xlim([-1*np.pi, 2*np.pi])\n ax2.set_ylim([-3,3])\n\n\n plt.show()\n```\n\n\n```python\nv = interactive(plot_taylor_error, x0=(0,np.pi,0.1*np.pi), n=(1,8), r=(2,4), s=(1,10))\ndisplay(v)\n```\n\n\n interactive(children=(FloatSlider(value=0.0, description='x0', max=3.141592653589793, step=0.3141592653589793)…\n\n\n\n```python\n\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "b0e49cd53d72f3a84eccff668dd82e15f4f2b68a", "size": 53142, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "quanti_geo/TSE-Error-Analysis.ipynb", "max_stars_repo_name": "cgre-aachen/teaching", "max_stars_repo_head_hexsha": "411bd3df76b7efee4a4ee311e06d1b0cf9aab8a1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2018-02-16T10:24:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-30T13:13:28.000Z", "max_issues_repo_path": "quanti_geo/TSE-Error-Analysis.ipynb", "max_issues_repo_name": "cgre-aachen/teaching", "max_issues_repo_head_hexsha": "411bd3df76b7efee4a4ee311e06d1b0cf9aab8a1", "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": "quanti_geo/TSE-Error-Analysis.ipynb", "max_forks_repo_name": "cgre-aachen/teaching", "max_forks_repo_head_hexsha": "411bd3df76b7efee4a4ee311e06d1b0cf9aab8a1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2018-01-08T08:36:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-29T11:55:08.000Z", "avg_line_length": 152.2693409742, "max_line_length": 43272, "alphanum_fraction": 0.8784388996, "converted": true, "num_tokens": 1570, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.942506726044381, "lm_q2_score": 0.9086179037377831, "lm_q1q2_score": 0.8563784856772064}} {"text": "## Eigen & Singular Value Decomp\n\n**Unsupervised learning: summarizing data, dimensionality reduction**\n\n**Abstract:** Eigendecomposition is an important step in many algorithms: spectral clustering, principal component analysis, ISOMAP etc. When it comes to computing the eigenvalues and eigenvectors, there is more than one way to skin that cat. Besides implementing that code yourself or turning to eigendecomp functions provided by numpy or scipy, one can also use SVD. There's a small tweak needed though. The purpose of this notebook is to show the relation between eigendecomp and SVD. \n\n**Topics covered:** eigenvalue problem, eigendecomposition, eigenvalues, eigenvectors, singular value decomposition (SVD), eigenfaces.\n\n**First things first.** Before showing the formal definitions of eigendecomposition (ED) and singular value decomposition (SVD), let's first provide the definition of the sample covariance matrix and the centered data matrix. This will become very handy later in this demonstration.\n\nGiven $n$ data points with $p$ features, $\\{x_1,x_2,\\dots,x_p\\} \\in \\mathbb{R}^n$, we define the sample covariance matrix, $C \\in \\mathbb{R}^{p \\times p}$, which is symmetrical (i.e. a square matrix), as\n\n$$\nC = \\frac{1}{n} \\sum_{i=1}^{n} (x_i - \\mu)^T(x_i - \\mu),\n$$\n\nor simply\n\n$$\nC = M^TM\n$$\n\nwhere M is the centered data matrix $X - \\mu$.\n\n**The eigenvalue problem**. Given this symmetric matrix $C$ we find a vector $u \\in \\mathbb{R}^p$ such that \n\n$$\nCu = \\lambda u.\n$$\n\nThe vector $u$ is ortho-normal, meaning (1) it's orthogonal to other such vector $u_i^Tu_j = 0$, and (2) has unit length $\\|u\\|=u^Tu=1$ (inner product).\n\nLoosly put, the vector $u$ represents some intrinsic value of $C$. Thus, $u$ is known as an eigenvector of $C$ and $\\lambda$ as its corresponding eigenvalue. The product $\\lambda u$ represents a scaled version of $u$ that doesn't change the direction of $u$ but only its magnitude.\n\nThere will be multiple solutions to this problem; thus, $u_1,u_2,\\dots,u_p$ are all eigenvectors with different $\\lambda_1,\\lambda_2,\\dots,\\lambda_p$ eigenvalues. Note though, that the eigenvalues aren't necessarily unique. So multiple eigenvectors can be associated with the same eigenvalue.\n\n**Eigendecomp.** Thus, the eigendecomposition of $C$ is\n\n$$\nC = U \\Lambda U^T,\n$$\n\nwhere\n\n$U \\in \\mathbb{R}^{p \\times p}$ and $\\Lambda = diag(\\lambda_1,\\lambda_2,\\dots,\\lambda_p)$. Typically, the eigenvalues as sorted in descending order, so $\\lambda_1 \\geq \\lambda_2 \\geq \\dots \\geq \\lambda_p$. Moreover, $U$ is a square matrix and also ortho-normal. Its columns are the eigenvectors of unit length $\\|u_i\\|=1$, and its transpose corresponds to its inverse $U^TU = U^{-1}U = I$.\n\n**Singular value decomp.** Given the real matrix $M \\in \\mathbb{R}^{n \\times p}$ where $n \\geq p$, SVD is the product of three matrices\n\n$$\nM = U \\Sigma V^T\n$$\n\n$$\nM = [u_1 u_2 \\dots u_n]\n\\begin{bmatrix}\n \\sigma_1 & & \\\\\n & \\ddots & \\\\\n & & \\sigma_{p}\n\\end{bmatrix}\n[v_1 v_2 \\dots v_p].\n$$\n\n$U \\in \\mathbb{R}^{n\\times n}$ are the left singular vectors, $V \\in \\mathbb{R}^{p\\times p}$ the right singular vectors and $\\Sigma \\in \\mathbb{R}^{p\\times p}$ is a diagonal matrix with the singular values $\\sigma_1,\\sigma_2,\\dots,\\sigma_p$ where typically $\\sigma_1\\geq\\sigma_2\\geq\\dots\\geq\\sigma_p$.\n\n**Where's the relation?** Say we want to find the eigenpairs $\\{(u_1,\\lambda_1), (u_2,\\lambda_2), \\dots, (u_p,\\lambda_p)\\}$ of the data matrix $X$. We can these with two equivalent approaches, namely\n\n1. computing the eigendecomposition (ED) of the sample covariance matrix, $C$, or \n2. computing the singular value decomposition (SVD) of the centered data matrix, $M$.\n\n#boom\n\nThis fact becomes apparent when looking back at the definition of the sample covariance matrix:\n\n$$\nC=M^TM.\n$$\n\nIf we substitute $M$ by the SVD definition above then\n\n$$\nC = M^TM = (U\\Sigma V^T)^T U\\Sigma V^T.\n$$\n\nSince $(ab)^T = b^T a^T$ (transpose property) we get\n\n$$\nC = V \\Sigma^T U^T U\\Sigma V^T.\n$$\n\nAnd since $U$ is orthogonal, i.e. $U^TU = I$, we end up with\n\n$$\nC = V \\Sigma^T \\Sigma V^T.\n$$\n\nNote that $\\Sigma^T \\Sigma$ corresponds to\n\n$$\n\\begin{equation}\n\\Sigma^T \\Sigma =\n\\begin{bmatrix}\n \\sigma_1 & & \\\\\n & \\ddots & \\\\\n & & \\sigma_{p}\\\\\n\\end{bmatrix}\n\\begin{bmatrix}\n \\sigma_1 & & \\\\\n & \\ddots & \\\\\n & & \\sigma_{p}\n\\end{bmatrix}\n\\end{equation} =\n\\begin{bmatrix}\n \\sigma_1^2 & & \\\\\n & \\ddots & \\\\\n & & \\sigma_{p}^2\n\\end{bmatrix}.\n$$\n\nThus, \n\n* the right singular vectors in the SVD of $M$, $v^T_i$, are equivalent to the eigenvectors of $C$, $u_i$; whereas\n* the squared singular values in the SVD of $M$, $\\sigma_i^2$, correspond to the eigenvalues of $C$, $\\lambda_i$.\n\n$$\nC = V \\Sigma^T \\Sigma V^T = U \\Lambda U^T.\n$$\n\n## Demo: Yale Face data set\n\nLet's demo this using an excerpt of data from the famous Yale Face dataset (Face recognition using eigenfaces, M.A Turk and A.P. Pentland, IEEE computer society conference on computer vision and pattern recognition (1991) 586-587).\n\n\n```python\n# Loads\nimport numpy as np\nimport matplotlib.pyplot as plt\n%matplotlib inline\nfrom scipy.linalg import svd\nfrom scipy.sparse.linalg import eigs\nfrom skimage.measure import block_reduce\nfrom PIL import Image\nfrom matplotlib.pyplot import boxplot\n```\n\nAs part of preprocessing, we will downsample each image by a factor of 4 to turn them into a lower resolution image. Let's build a helper function to help with this routine.\n\n\n```python\n# demo one image\nim_raw = Image.open('data/yalefaces/subject01.glasses.gif')\nim_orig = np.asarray(im_raw)\n# downsample by a factor of 4\nh = int((im_raw.size[0] / 4) + .5)\nw = int((im_raw.size[1] / 4) + .5)\nim_down = block_reduce(im_orig, block_size=4, func=np.mean)\n# vectorize (reshape)\nim_vec = np.asarray(im_down)\n# plot\nfig, a = plt.subplots(1, 2, figsize=(9,4))\na[0].imshow(im_orig, interpolation='nearest', cmap='gray')\na[0].set_title('Original Image ({} x {})'.format(im_raw.size[1], im_raw.size[0]))\na[1].imshow(im_vec, interpolation='nearest', cmap='gray')\na[1].set_title('Downsample ({} x {})'.format(w, h))\n```\n\n\n```python\n# helper function\ndef im2arr(filename):\n # import image\n im_raw = Image.open('data/yalefaces/{}.gif'.format(filename))\n im_orig = np.asarray(im_raw)\n # downsample by a factor of 4\n h = int((im_raw.size[0] / 4) + .5)\n w = int((im_raw.size[1] / 4) + .5)\n im_down = block_reduce(im_orig, block_size=4, func=np.mean)\n # vectorize (reshape)\n return np.asarray(im_down).flatten()\n```\n\n\n```python\n# load the data to ndarrays\ns101 = im2arr('subject01.glasses')\ns102 = im2arr('subject01.happy')\ns103 = im2arr('subject01.leftlight')\ns104 = im2arr('subject01.noglasses')\ns105 = im2arr('subject01.normal')\ns106 = im2arr('subject01.rightlight')\ns107 = im2arr('subject01.sad')\ns108 = im2arr('subject01.sleepy')\ns109 = im2arr('subject01.surprised')\ns110 = im2arr('subject01.wink')\n```\n\n\n```python\n# build data matrix with obs as rows and pixels as cols\nX = np.array([s101, s102, s103, s104, s105, s106, s107, s108, s109, s110])\nX.shape\n```\n\n\n\n\n (10, 4880)\n\n\n\n\n```python\n# center the data\nM = X - np.mean(X, axis=1)[:, np.newaxis]\nM.shape\n```\n\n\n\n\n (10, 4880)\n\n\n\n\n```python\n# compute cov matrix\nC = (M.T @ M) / np.mean(X, axis=0)[np.newaxis, :]\nC.shape\n```\n\n\n\n\n (4880, 4880)\n\n\n\nLet's now compute the eigenvectors with the two equivalent approaches:\n\n\n```python\n# ED\n_, U = eigs(C, k=10)\nU = U.real\nU.shape\n```\n\n\n\n\n (4880, 10)\n\n\n\n\n```python\n# SVD\n_, _, VT = svd(M, full_matrices=False)\nVT.shape\n```\n\n\n\n\n (10, 4880)\n\n\n\nWe can inspect the eigenvectors and see if they match. As we are working with images, we can simply visualize the eigenfaces.\n\n\n```python\n# plot first 6 eigenfaces from ED\nfig, ax = plt.subplots(2, 3, figsize=(12, 6))\nfor i, a in enumerate(ax.flat):\n a.imshow(U[:, i].reshape(w, h), cmap='gray')\n a.set(xticks=[], yticks=[], xlabel=f'eigenface {i+1}')\n```\n\n\n```python\n# plot first 6 eigenfaces from SVD\nfig, ax = plt.subplots(2, 3, figsize=(12, 6))\nfor i, a in enumerate(ax.flat):\n a.imshow(VT[i, :].reshape(w, h), cmap='gray')\n a.set(xticks=[], yticks=[], xlabel=f'eigenface {i+1}')\n```\n\nMinor subtleties aside, like value ranges, these two results are quivalent.\n\n\n```python\n# box plots for U\nfig, ax = plt.subplots(1, 6, figsize=(18, 3))\nfor i, a in enumerate(ax.flat):\n a.boxplot(U[:, i])\n a.set(xlabel=f'U {i+1}')\n```\n\n\n```python\n# box plots for VT\nfig, ax = plt.subplots(1, 6, figsize=(18, 3))\nfor i, a in enumerate(ax.flat):\n a.boxplot(VT[i, :])\n a.set(xlabel=f'VT {i+1}')\n```\n", "meta": {"hexsha": "388fe0b2c2a32ea38c363837cca8004310151093", "size": 407247, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "ed and svd.ipynb", "max_stars_repo_name": "dchosch/mlx", "max_stars_repo_head_hexsha": "2352d032a2ad04e73047ba79bca706e50271959d", "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": "ed and svd.ipynb", "max_issues_repo_name": "dchosch/mlx", "max_issues_repo_head_hexsha": "2352d032a2ad04e73047ba79bca706e50271959d", "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": "ed and svd.ipynb", "max_forks_repo_name": "dchosch/mlx", "max_forks_repo_head_hexsha": "2352d032a2ad04e73047ba79bca706e50271959d", "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": 709.4895470383, "max_line_length": 148912, "alphanum_fraction": 0.9461628938, "converted": true, "num_tokens": 2677, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067228145365, "lm_q2_score": 0.908617906212312, "lm_q1q2_score": 0.8563784850747721}} {"text": "# Gradient Descent Optimizations\n\nMini-batch and stochastic gradient descent is widely used in deep learning, where the large number of parameters and limited memory make the use of more sophisticated optimization methods impractical. Many methods have been proposed to accelerate gradient descent in this context, and here we sketch the ideas behind some of the most popular algorithms.\n\n\n```python\n%matplotlib inline\n```\n\n\n```python\nimport matplotlib.pyplot as plt\nimport numpy as np\n```\n\n## Smoothing with exponentially weighted averages\n\n\n```python\nn = 50\nx = np.arange(n) * np.pi\ny = np.cos(x) * np.exp(x/100) - 10*np.exp(-0.01*x)\n```\n\n### Exponentially weighted average\n\nThe exponentially weighted average adds a fraction $\\beta$ of the current value to a leaky running sum of past values. Effectively, the contribution from the $t-n$th value is scaled by\n\n$$\n\\beta^n(1 - \\beta)\n$$\n\nFor example, here are the contributions to the current value after 5 iterations (iteration 5 is the current iteration)\n\n| iteration | contribution |\n| --- | --- |\n| 1 | $\\beta^4(1 - \\beta)$ |\n| 2 | $\\beta^3(1 - \\beta)$ |\n| 3 | $\\beta^2(1 - \\beta)$ |\n| 4 | $\\beta^1(1 - \\beta)$ |\n| 5 | $(1 - \\beta)$ |\n\nSince $\\beta \\lt 1$, the contribution decreases exponentially with the passage of time. Effectively, this acts as a smoother for a function.\n\n\n```python\ndef ewa(y, beta):\n \"\"\"Exponentially weighted average.\"\"\"\n \n zs = np.zeros(len(y))\n z = 0\n for i in range(n):\n z = beta*z + (1 - beta)*y[i]\n zs[i] = z\n return zs\n```\n\n### Exponentially weighted average with bias correction\n\nSince the EWA starts from 0, there is an initial bias. This can be corrected by scaling with \n\n$$\n\\frac{1}{1 - \\beta^t}\n$$\n\nwhere $t$ is the iteration number.\n\n\n```python\ndef ewabc(y, beta):\n \"\"\"Exponentially weighted average with hias correction.\"\"\"\n \n zs = np.zeros(len(y))\n z = 0\n for i in range(n):\n z = beta*z + (1 - beta)*y[i]\n zc = z/(1 - beta**(i+1))\n zs[i] = zc\n return zs\n```\n\n\n```python\nbeta = 0.9\n\nplt.plot(x, y, 'o-')\nplt.plot(x, ewa(y, beta), c='red', label='EWA')\nplt.plot(x, ewabc(y, beta), c='orange', label='EWA with bias correction')\nplt.legend()\npass\n```\n\n## Momentum in 1D\n\nMomentum comes from physics, where the contribution of the gradient is to the velocity, not the position. Hence we create an accessory variable $v$ and increment it with the gradient. The position is then updated with the velocity in place of the gradient. The analogy is that we can think of the parameter $x$ as a particle in an energy well with potential energy $U = mgh$ where $h$ is given by our objective function $f$. The force generated is a function of the rat of change of potential energy $F \\propto \\nabla U \\propto \\nabla f$, and we use $F = ma$ to get that the acceleration $a \\propto \\nabla f$. Finally, we integrate $a$ over time to get the velocity $v$ and integrate $v$ to get the displacement $x$. Note that we need to damp the velocity otherwise the particle would just oscillate forever.\n\nWe use a version of the update that simply treats the velocity as an exponentially weighted average popularized by Andrew Ng in his Coursera course. This is the same as the momentum scheme motivated by physics with some rescaling of constants.\n\n\n```python\ndef f(x):\n return x**2\n```\n\n\n```python\ndef grad(x):\n return 2*x\n```\n\n\n```python\ndef gd(x, grad, alpha, max_iter=10):\n xs = np.zeros(1 + max_iter)\n xs[0] = x\n for i in range(max_iter):\n x = x - alpha * grad(x)\n xs[i+1] = x\n return xs\n```\n\n\n```python\ndef gd_momentum(x, grad, alpha, beta=0.9, max_iter=10):\n xs = np.zeros(1 + max_iter)\n xs[0] = x\n v = 0\n for i in range(max_iter):\n v = beta*v + (1-beta)*grad(x)\n vc = v/(1+beta**(i+1))\n x = x - alpha * vc\n xs[i+1] = x\n return xs\n```\n\n### Gradient descent with moderate step size\n\n\n```python\nalpha = 0.1\nx0 = 1\nxs = gd(x0, grad, alpha)\nxp = np.linspace(-1.2, 1.2, 100)\nplt.plot(xp, f(xp))\nplt.plot(xs, f(xs), 'o-', c='red')\nfor i, (x, y) in enumerate(zip(xs, f(xs)), 1):\n plt.text(x, y+0.2, i, \n bbox=dict(facecolor='yellow', alpha=0.5), fontsize=14)\npass\n```\n\n### Gradient descent with large step size\n\nWhen the step size is too large, gradient descent can oscillate and even diverge.\n\n\n```python\nalpha = 0.95\nxs = gd(1, grad, alpha)\nxp = np.linspace(-1.2, 1.2, 100)\nplt.plot(xp, f(xp))\nplt.plot(xs, f(xs), 'o-', c='red')\nfor i, (x, y) in enumerate(zip(xs, f(xs)), 1):\n plt.text(x*1.2, y, i,\n bbox=dict(facecolor='yellow', alpha=0.5), fontsize=14)\npass\n```\n\n### Gradient descent with momentum\n\nMomentum results in cancellation of gradient changes in opposite directions, and hence damps out oscillations while amplifying consistent changes in the same direction. This is perhaps clearer in the 2D example below.\n\n\n```python\nalpha = 0.95\nxs = gd_momentum(1, grad, alpha, beta=0.9)\nxp = np.linspace(-1.2, 1.2, 100)\nplt.plot(xp, f(xp))\nplt.plot(xs, f(xs), 'o-', c='red')\nfor i, (x, y) in enumerate(zip(xs, f(xs)), 1):\n plt.text(x, y+0.2, i, \n bbox=dict(facecolor='yellow', alpha=0.5), fontsize=14)\npass\n```\n\n## Momentum and RMSprop in 2D\n\n\n```python\ndef f2(x):\n return x[0]**2 + 100*x[1]**2\n```\n\n\n```python\ndef grad2(x):\n return np.array([2*x[0], 200*x[1]])\n```\n\n\n```python\nx = np.linspace(-1.2, 1.2, 100)\ny = np.linspace(-1.2, 1.2, 100)\nX, Y = np.meshgrid(x, y)\nlevels = [0.1,1,2,4,9, 16, 25, 36, 49, 64, 81, 100]\nZ = x**2 + 100*Y**2\nc = plt.contour(X, Y, Z, levels)\npass\n```\n\n\n```python\ndef gd2(x, grad, alpha, max_iter=10):\n xs = np.zeros((1 + max_iter, x.shape[0]))\n xs[0,:] = x\n for i in range(max_iter):\n x = x - alpha * grad(x)\n xs[i+1,:] = x\n return xs\n```\n\n\n```python\ndef gd2_momentum(x, grad, alpha, beta=0.9, max_iter=10):\n xs = np.zeros((1 + max_iter, x.shape[0]))\n xs[0, :] = x\n v = 0\n for i in range(max_iter):\n v = beta*v + (1-beta)*grad(x)\n vc = v/(1+beta**(i+1))\n x = x - alpha * vc\n xs[i+1, :] = x\n return xs\n```\n\n### Gradient descent with large step size\n\nWe get severe oscillations.\n\n\n```python\nalpha = 0.01\nx0 = np.array([-1,-1])\nxs = gd2(x0, grad2, alpha, max_iter=75)\n```\n\n\n```python\nx = np.linspace(-1.2, 1.2, 100)\ny = np.linspace(-1.2, 1.2, 100)\nX, Y = np.meshgrid(x, y)\nlevels = [0.1,1,2,4,9, 16, 25, 36, 49, 64, 81, 100]\nZ = x**2 + 100*Y**2\nc = plt.contour(X, Y, Z, levels)\nplt.plot(xs[:, 0], xs[:, 1], 'o-', c='red')\nplt.title('Vanilla gradient descent')\npass\n```\n\n### Gradient descent with momentum\n\nThe damping effect is clear.\n\n\n```python\nalpha = 0.01\nx0 = np.array([-1,-1])\nxs = gd2_momentum(x0, grad2, alpha, beta=0.9, max_iter=75)\n```\n\n\n```python\nx = np.linspace(-1.2, 1.2, 100)\ny = np.linspace(-1.2, 1.2, 100)\nX, Y = np.meshgrid(x, y)\nlevels = [0.1,1,2,4,9, 16, 25, 36, 49, 64, 81, 100]\nZ = x**2 + 100*Y**2\nc = plt.contour(X, Y, Z, levels)\nplt.plot(xs[:, 0], xs[:, 1], 'o-', c='red')\nplt.title('Gradieent descent with momentum')\npass\n```\n\n### Gradient descent with RMSprop\n\nRMSprop scales the learning rate in each direction by the square root of the exponentially weighted sum of squared gradients. Near a saddle or any plateau, there are directions where the gradient is very small - RMSporp encourages larger steps in those directions, allowing faster escape.\n\n\n```python\ndef gd2_rmsprop(x, grad, alpha, beta=0.9, eps=1e-8, max_iter=10):\n xs = np.zeros((1 + max_iter, x.shape[0]))\n xs[0, :] = x\n v = 0\n for i in range(max_iter):\n v = beta*v + (1-beta)*grad(x)**2\n x = x - alpha * grad(x) / (eps + np.sqrt(v))\n xs[i+1, :] = x\n return xs\n```\n\n\n```python\nalpha = 0.1\nx0 = np.array([-1,-1])\nxs = gd2_rmsprop(x0, grad2, alpha, beta=0.9, max_iter=10)\n```\n\n\n```python\nx = np.linspace(-1.2, 1.2, 100)\ny = np.linspace(-1.2, 1.2, 100)\nX, Y = np.meshgrid(x, y)\nlevels = [0.1,1,2,4,9, 16, 25, 36, 49, 64, 81, 100]\nZ = x**2 + 100*Y**2\nc = plt.contour(X, Y, Z, levels)\nplt.plot(xs[:, 0], xs[:, 1], 'o-', c='red')\nplt.title('Gradient descent with RMSprop')\npass\n```\n\n### ADAM\n\nADAM (Adaptive Moment Estimation) combines the ideas of momentum, RMSprop and bias correction. It is probably the most popular gradient descent method in current deep learning practice.\n\n\n```python\ndef gd2_adam(x, grad, alpha, beta1=0.9, beta2=0.999, eps=1e-8, max_iter=10):\n xs = np.zeros((1 + max_iter, x.shape[0]))\n xs[0, :] = x\n m = 0\n v = 0\n for i in range(max_iter):\n m = beta1*m + (1-beta1)*grad(x)\n v = beta2*v + (1-beta2)*grad(x)**2\n mc = m/(1+beta1**(i+1))\n vc = v/(1+beta2**(i+1))\n x = x - alpha * m / (eps + np.sqrt(vc))\n xs[i+1, :] = x\n return xs\n```\n\n\n```python\nalpha = 0.1\nx0 = np.array([-1,-1])\nxs = gd2_adam(x0, grad2, alpha, beta1=0.9, beta2=0.9, max_iter=10)\n```\n\n\n```python\nx = np.linspace(-1.2, 1.2, 100)\ny = np.linspace(-1.2, 1.2, 100)\nX, Y = np.meshgrid(x, y)\nlevels = [0.1,1,2,4,9, 16, 25, 36, 49, 64, 81, 100]\nZ = x**2 + 100*Y**2\nc = plt.contour(X, Y, Z, levels)\nplt.plot(xs[:, 0], xs[:, 1], 'o-', c='red')\nplt.title('Gradient descent with RMSprop')\npass\n```\n\n## Implementing a custom optimization routine for `scipy.optimize`\n\nGradient descent is not one of the methods available in `scipy.optimize`. However we can implement our own version by following the API of the `minimize` function.\n\n\n```python\nimport scipy.optimize as opt\nimport scipy.linalg as la\n```\n\n\n```python\ndef custmin(fun, x0, args=(), maxfev=None, alpha=0.0002,\n maxiter=100000, tol=1e-10, callback=None, **options):\n \"\"\"Implements simple gradient descent for the Rosen function.\"\"\"\n bestx = x0\n bestf = fun(x0)\n funcalls = 1\n niter = 0\n improved = True\n stop = False\n\n while improved and not stop and niter < maxiter:\n niter += 1\n # the next 2 lines are gradient descent\n step = alpha * rosen_der(bestx)\n bestx = bestx - step\n\n bestf = fun(bestx)\n funcalls += 1\n \n if la.norm(step) < tol:\n improved = False\n if callback is not None:\n callback(bestx)\n if maxfev is not None and funcalls >= maxfev:\n stop = True\n break\n\n return opt.OptimizeResult(fun=bestf, x=bestx, nit=niter,\n nfev=funcalls, success=(niter > 1))\n```\n\n\n```python\ndef reporter(p):\n \"\"\"Reporter function to capture intermediate states of optimization.\"\"\"\n global ps\n ps.append(p)\n```\n\n### Test on Rosenbrock banana function\n\nWe will use the [Rosenbrock \"banana\" function](http://en.wikipedia.org/wiki/Rosenbrock_function) to illustrate unconstrained multivariate optimization. In 2D, this is\n$$\nf(x, y) = b(y - x^2)^2 + (a - x)^2\n$$\n\nThe function has a global minimum at (1,1) and the standard expression takes $a = 1$ and $b = 100$. \n\n#### Conditioning of optimization problem\n\nWith these values for $a$ and $b$, the problem is ill-conditioned. As we shall see, one of the factors affecting the ease of optimization is the condition number of the curvature (Hessian). When the condition number is high, the gradient may not point in the direction of the minimum, and simple gradient descent methods may be inefficient since they may be forced to take many sharp turns.\n\nFor the 2D version, we have\n\n$$\nf(x) = 100(y - x^2)^2 + (1 - x)^2\n$$\n\nand can calculate the Hessian to be \n\n$$\n\\begin{bmatrix}\n802 & -400 \\\\\n-400 & 200\n\\end{bmatrix}\n$$\n\n\n```python\nH = np.array([\n [802, -400],\n [-400, 200]\n])\n```\n\n\n```python\nnp.linalg.cond(H)\n```\n\n\n\n\n 2508.009601277298\n\n\n\n\n```python\nU, s, Vt = np.linalg.svd(H)\ns[0]/s[1]\n```\n\n\n\n\n 2508.0096012772983\n\n\n\n#### Function to minimize\n\n\n```python\ndef rosen(x):\n \"\"\"Generalized n-dimensional version of the Rosenbrock function\"\"\"\n return sum(100*(x[1:]-x[:-1]**2.0)**2.0 +(1-x[:-1])**2.0)\n```\n\n\n```python\ndef rosen_der(x):\n \"\"\"Derivative of generalized Rosen function.\"\"\"\n xm = x[1:-1]\n xm_m1 = x[:-2]\n xm_p1 = x[2:]\n der = np.zeros_like(x)\n der[1:-1] = 200*(xm-xm_m1**2) - 400*(xm_p1 - xm**2)*xm - 2*(1-xm)\n der[0] = -400*x[0]*(x[1]-x[0]**2) - 2*(1-x[0])\n der[-1] = 200*(x[-1]-x[-2]**2)\n return der\n```\n\n#### Why is the condition number so large?\n\n\n```python\nx = np.linspace(-5, 5, 100)\ny = np.linspace(-5, 5, 100)\nX, Y = np.meshgrid(x, y)\nZ = rosen(np.vstack([X.ravel(), Y.ravel()])).reshape((100,100))\n```\n\n\n```python\n# Note: the global minimum is at (1,1) in a tiny contour island\nplt.contour(X, Y, Z, np.arange(10)**5, cmap='jet')\nplt.text(1, 1, 'x', va='center', ha='center', color='red', fontsize=20)\npass\n```\n\n#### Zooming in to the global minimum at (1,1)\n\n\n```python\nx = np.linspace(0, 2, 100)\ny = np.linspace(0, 2, 100)\nX, Y = np.meshgrid(x, y)\nZ = rosen(np.vstack([X.ravel(), Y.ravel()])).reshape((100,100))\n```\n\n\n```python\nplt.contour(X, Y, Z, [rosen(np.array([k, k])) for k in np.linspace(1, 1.5, 10)], cmap='jet')\nplt.text(1, 1, 'x', va='center', ha='center', color='red', fontsize=20)\npass\n```\n\n#### We will use our custom gradient descent to minimize the banana function\n\n#### Helpful Hint \n\nOne of the most common causes of failure of optimization is because the gradient or Hessian function is specified incorrectly. You can check for this using `check_grad` which compares the analytical gradient with one calculated using finite differences.\n\n\n```python\nfrom scipy.optimize import check_grad\n\nfor x in np.random.uniform(-2,2,(10,2)):\n print(x, check_grad(rosen, rosen_der, x))\n```\n\n [1.52226677 0.65004796] 1.489680875137234e-05\n [ 0.52565945 -0.97450204] 5.561538106652017e-06\n [-1.90395551 -1.40865775] 4.959629801043568e-06\n [1.56241883 0.02916979] 1.1141498255202488e-05\n [1.41686433 0.97694193] 1.2788749325180071e-05\n [ 1.67198246 -1.43445961] 4.925842873021741e-05\n [1.50075383 1.26752343] 1.646225036670931e-05\n [ 0.12793507 -0.8359048 ] 3.0161708019548927e-06\n [0.35530784 0.59406072] 1.7619515805981918e-06\n [-0.01477088 -1.9624893 ] 6.263297131400611e-06\n\n\n\n```python\n# Initial starting position\nx0 = np.array([4,-4.1])\nps = [x0]\nopt.minimize(rosen, x0, method=custmin, callback=reporter)\n```\n\n\n\n\n fun: 1.060466347344834e-08\n nfev: 100001\n nit: 100000\n success: True\n x: array([0.9998971 , 0.99979381])\n\n\n\n\n```python\nx = np.linspace(-5, 5, 100)\ny = np.linspace(-5, 5, 100)\nX, Y = np.meshgrid(x, y)\nZ = rosen(np.vstack([X.ravel(), Y.ravel()])).reshape((100,100))\n```\n\n\n```python\nps = np.array(ps)\nplt.figure(figsize=(12,4))\nplt.subplot(121)\nplt.contour(X, Y, Z, np.arange(10)**5, cmap='jet')\nplt.plot(ps[:, 0], ps[:, 1], '-ro')\nplt.subplot(122)\nplt.semilogy(range(len(ps)), rosen(ps.T))\npass\n```\n\n### Comparison with standard algorithms\n\nNote that all these methods take far fewer function iterations and function evaluations to find the minimum compared with vanilla gradient descent.\n\nMany of these are based on estimating the Newton direction. Recall Newton's method for finding roots of a univariate function\n\n$$\nx_{K+1} = x_k - \\frac{f(x_k)}{f'(x_k)}\n$$\n\nWhen we are looking for a minimum, we are looking for the roots of the *derivative* $f'(x)$, so\n\n$$\nx_{K+1} = x_k - \\frac{f'(x_k}{f''(x_k)}\n$$\n\nNewton's method can also be seen as a Taylor series approximation\n\n$$\nf(x+h) = f(x) + h f'(x) + \\frac{h^2}{2}f''(x)\n$$\n\nAt the function minimum, the derivative is 0, so\n\\begin{align}\n\\frac{f(x+h) - f(x)}{h} &= f'(x) + \\frac{h}{2}f''(x) \\\\\n0 &= f'(x) + \\frac{h}{2}f''(x) \n\\end{align}\n\nand letting $\\Delta x = \\frac{h}{2}$, we get that the Newton step is\n\n$$\n\\Delta x = - \\frac{f'(x)}{f''(x)}\n$$\n\nThe multivariate analog replaces $f'$ with the Jacobian and $f''$ with the Hessian, so the Newton step is\n\n$$\n\\Delta x = -H^{-1}(x) \\nabla f(x)\n$$\n\nSlightly more rigorously, we can optimize the quadratic multivariate Taylor expansion \n\n$$\nf(x + p) = f(x) + p^T\\nabla f(x) + \\frac{1}{2}p^TH(x)p\n$$\n\nDifferentiating with respect to the direction vector $p$ and setting to zero, we get\n\n$$\nH(x)p = -\\nabla f(x)\n$$\n\ngiving\n\n$$\np = -H(x)^{-1}\\nabla f(x)\n$$\n\n\n```python\nfrom scipy.optimize import rosen, rosen_der, rosen_hess\n```\n\n#### Nelder-Mead\n\nThere are some optimization algorithms not based on the Newton method, but on other heuristic search strategies that do not require any derivatives, only function evaluations. One well-known example is the Nelder-Mead simplex algorithm.\n\n\n```python\nps = [x0]\nopt.minimize(rosen, x0, method='nelder-mead', callback=reporter)\n```\n\n\n\n\n final_simplex: (array([[0.99998846, 0.99997494],\n [0.99994401, 0.99989075],\n [1.0000023 , 1.0000149 ]]), array([5.26275688e-10, 3.87529507e-09, 1.06085894e-08]))\n fun: 5.262756878429089e-10\n message: 'Optimization terminated successfully.'\n nfev: 162\n nit: 85\n status: 0\n success: True\n x: array([0.99998846, 0.99997494])\n\n\n\n\n```python\nps = np.array(ps)\nplt.figure(figsize=(12,4))\nplt.subplot(121)\nplt.contour(X, Y, Z, np.arange(10)**5, cmap='jet')\nplt.plot(ps[:, 0], ps[:, 1], '-ro')\nplt.subplot(122)\nplt.semilogy(range(len(ps)), rosen(ps.T));\n```\n\n#### BFGS\n\nAs calculating the Hessian is computationally expensive, sometimes first order methods that only use the first derivatives are preferred. Quasi-Newton methods use functions of the first derivatives to approximate the inverse Hessian. A well know example of the Quasi-Newoton class of algorithjms is BFGS, named after the initials of the creators. As usual, the first derivatives can either be provided via the `jac=` argument or approximated by finite difference methods.\n\n\n```python\nps = [x0]\nopt.minimize(rosen, x0, method='Newton-CG', jac=rosen_der, hess=rosen_hess, callback=reporter)\n```\n\n\n\n\n fun: 1.3642782750354208e-13\n jac: array([ 1.21204353e-04, -6.08502470e-05])\n message: 'Optimization terminated successfully.'\n nfev: 38\n nhev: 26\n nit: 26\n njev: 63\n status: 0\n success: True\n x: array([0.99999963, 0.99999926])\n\n\n\n\n```python\nps = np.array(ps)\nplt.figure(figsize=(12,4))\nplt.subplot(121)\nplt.contour(X, Y, Z, np.arange(10)**5, cmap='jet')\nplt.plot(ps[:, 0], ps[:, 1], '-ro')\nplt.subplot(122)\nplt.semilogy(range(len(ps)), rosen(ps.T))\npass\n```\n\n#### Newton-CG\n\nSecond order methods solve for $H^{-1}$ and so require calculation of the Hessian (either provided or approximated using finite differences). For efficiency reasons, the Hessian is not directly inverted, but solved for using a variety of methods such as conjugate gradient. An example of a second order method in the `optimize` package is `Newton-GC`.\n\n\n```python\nps = [x0]\nopt.minimize(rosen, x0, method='Newton-CG', jac=rosen_der, hess=rosen_hess, callback=reporter)\n```\n\n\n\n\n fun: 1.3642782750354208e-13\n jac: array([ 1.21204353e-04, -6.08502470e-05])\n message: 'Optimization terminated successfully.'\n nfev: 38\n nhev: 26\n nit: 26\n njev: 63\n status: 0\n success: True\n x: array([0.99999963, 0.99999926])\n\n\n\n\n```python\nps = np.array(ps)\nplt.figure(figsize=(12,4))\nplt.subplot(121)\nplt.contour(X, Y, Z, np.arange(10)**5, cmap='jet')\nplt.plot(ps[:, 0], ps[:, 1], '-ro')\nplt.subplot(122)\nplt.semilogy(range(len(ps)), rosen(ps.T))\npass\n```\n", "meta": {"hexsha": "ed9c91bd89d813e68273fa740272e30b4f996c32", "size": 744965, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/S09G_Gradient_Descent_Optimization.ipynb", "max_stars_repo_name": "taotangtt/sta-663-2018", "max_stars_repo_head_hexsha": "67dac909477f81d83ebe61e0753de2328af1be9c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 72, "max_stars_repo_stars_event_min_datetime": "2018-01-20T20:50:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-27T23:24:21.000Z", "max_issues_repo_path": "notebooks/S09G_Gradient_Descent_Optimization.ipynb", "max_issues_repo_name": "taotangtt/sta-663-2018", "max_issues_repo_head_hexsha": "67dac909477f81d83ebe61e0753de2328af1be9c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-02-03T13:43:46.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-03T13:43:46.000Z", "max_forks_repo_path": "notebooks/S09G_Gradient_Descent_Optimization.ipynb", "max_forks_repo_name": "taotangtt/sta-663-2018", "max_forks_repo_head_hexsha": "67dac909477f81d83ebe61e0753de2328af1be9c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 64, "max_forks_repo_forks_event_min_datetime": "2018-01-12T17:13:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-14T20:22:46.000Z", "avg_line_length": 535.5607476636, "max_line_length": 73174, "alphanum_fraction": 0.9323471572, "converted": true, "num_tokens": 6308, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067195846919, "lm_q2_score": 0.908617900644622, "lm_q1q2_score": 0.8563784768924922}} {"text": "# Kernel SVM\n\n```{note}\nIntuition: Transforming the original space to the feature space, solve the problem in the feature space.
\nFor SVM, we can use the kernel trick.\n```\n\nRecall the Linear SVM in the original space:\n\n$$\n\\begin{equation}\n\\begin{split}\n\\underset{\\alpha}{\\max}\\ &\\sum_{i=1}^{n}\\alpha_{i} - \\sum_{i,j=1}^{n}y^{(i)}y^{(j)}\\alpha_{i}\\alpha_{j}\\left \\langle x^{(i)},x^{(j)} \\right \\rangle \\\\\n\\mbox{s.t.}\\ &0 \\le \\alpha_{i}\\le{C},\\ i=1,...,n \\\\\n&\\sum_{i=1}^{n}\\alpha_{i}y^{(i)}=0\n\\end{split}\n\\end{equation}\n$$\n\nLet $\\phi : \\mathbb{R}^{d} \\to \\mathbb{R}^{p}$ be a feature map, $\\left \\langle x^{(i)},x^{(j)} \\right \\rangle$ change to $\\left \\langle \\phi(x^{(i)}),\\phi(x^{(j)}) \\right \\rangle$, so SVM in the feature space:\n\n$$\n\\begin{equation}\n\\begin{split}\n\\underset{\\alpha}{\\max}\\ &\\sum_{i=1}^{n}\\alpha_{i} - \\sum_{i,j=1}^{n}y^{(i)}y^{(j)}\\alpha_{i}\\alpha_{j}\\left \\langle \\phi(x^{(i)}),\\phi(x^{(j)}) \\right \\rangle \\\\\n\\mbox{s.t.}\\ &0 \\le \\alpha_{i}\\le{C},\\ i=1,...,n \\\\\n&\\sum_{i=1}^{n}\\alpha_{i}y^{(i)}=0\n\\end{split}\n\\end{equation}\n$$\n\nWe only need to know kernel of the feature space $K(x, z) = \\left \\langle \\phi(x),\\phi(z) \\right \\rangle$ with out knowing the form of $\\phi$.\n\nWhen predicting:\n\n$$w^{T}\\phi(x) + b = \\left ( \\sum_{i=1}^{n}\\alpha_{i}y^{(i)}\\phi(x^{(i)})\\right )^{T}x + b = \\sum_{i=1}^{n}\\alpha_{i}y^{(i)}\\left \\langle \\phi(x^{(i)}),\\phi(x) \\right \\rangle + b$$\n\n## Kernels\n\nTheorem(mercer): let $ K: \\mathbb{R}^{d} \\times \\mathbb{R}^{d} \\mapsto \\mathbb{R}$. then for K be a valid kernel, it is necessary and sufficient that for any $\\left \\{ x^{(1)},...,x^{(n)} \\right \\} $, the corresponding kernel matrix is symmetric positive semi-definite.\n\nLinear kernel:\n\n$$K(x, z) = x^{T}z$$\n\nPolynomial kernel:\n\n$$K(x, z) = (\\gamma{x^{T}}z + r)^{k}$$\n\nGaussian RBF(Radial Basis Function):\n\n$$K(x, z) = \\exp(-\\gamma\\left \\| x - z \\right \\|^{2} )$$\n\n## Examples\n\n\n```python\nimport numpy as np\n\nX = np.array([[-1, -1], [-2, -1], [1, 1], [2, 1]])\ny = np.array([1, 1, 2, 2])\n```\n\n\n```python\nfrom sklearn.svm import SVC\nfrom sklearn.pipeline import make_pipeline\nfrom sklearn.preprocessing import StandardScaler\n\nclf = make_pipeline(StandardScaler(), SVC(kernel='rbf', gamma='auto'))\nclf.fit(X, y)\n```\n\n\n\n\n Pipeline(steps=[('standardscaler', StandardScaler()),\n ('svc', SVC(gamma='auto'))])\n\n\n\n\n```python\nclf.predict([[-0.8, -1]])\n```\n\n\n\n\n array([1])\n\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "a1932380e7464b012e739dc5c6a2c53d22495f72", "size": 4450, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "machine-learning-book/a5.kernel svm.ipynb", "max_stars_repo_name": "newfacade/jupyters", "max_stars_repo_head_hexsha": "12d3c8bf1b91a7fc2f84e89b5a55efa176f4da23", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-10T16:20:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-10T16:20:34.000Z", "max_issues_repo_path": "machine-learning-book/a5.kernel svm.ipynb", "max_issues_repo_name": "newfacade/jupyters", "max_issues_repo_head_hexsha": "12d3c8bf1b91a7fc2f84e89b5a55efa176f4da23", "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-book/a5.kernel svm.ipynb", "max_forks_repo_name": "newfacade/jupyters", "max_forks_repo_head_hexsha": "12d3c8bf1b91a7fc2f84e89b5a55efa176f4da23", "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": 27.6397515528, "max_line_length": 287, "alphanum_fraction": 0.4743820225, "converted": true, "num_tokens": 910, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.966914018751051, "lm_q2_score": 0.8856314753275017, "lm_q1q2_score": 0.856329488941337}} {"text": "# Determine polynomial functions of degree 2\n\nFrom the graph $y=f(x)$ of a polynomial function $f$ of degree 2 the following three points are known:\n$P(2|4)$, $Q(3|5)$, $R(-1|-3)$\n\nDetermine the equation of this function \n\n- in its normal form, $f(x) = a\\,x^2 + b\\,x + c$, and\n- in its vertex form, $f_s(x) = a_s\\,(x-x_s)^2 + y_s$\n\n\n```python\n# Initialisations\n\nfrom sympy import *\ninit_printing()\n\nimport matplotlib.pyplot as plt\n\n# usually you want this\n%matplotlib inline \n\n# useful for OS X\n%config InlineBackend.figure_format='retina' \n\nimport numpy as np\n\nfrom IPython.display import display, Math\n\nfrom fun_expr import Function_from_Expression as FE\n```\n\n\n```python\n# To define f, we first need a variable x\n# and three coefficients a,b,c\n# with these, f is defined\nx = Symbol('x')\n\na,b,c = symbols('a,b,c')\n\nf = FE(x, a*x**2 + b*x + c)\nMath(\"f(x)=\"+latex(f(x)))\n```\n\n\n\n\n$$f(x)=a x^{2} + b x + c$$\n\n\n\n\n```python\n# define points and determine equations\nx_1,y_1 = 2,4\nx_2,y_2 = 3,5\nx_3,y_3 = -1,-3\n\npts = [(x_1,y_1),(x_2,y_2),(x_3,y_3)]\n\neqns = [Eq(f(x_1),y_1),\n Eq(f(x_2),y_2),\n Eq(f(x_3),y_3)]\n\n# display result\nfor eq in eqns:\n display(eq)\n```\n\n\n```python\n# solve eqnations\nsol = solve(eqns)\n\n# display results\nsol\n```\n\n\n```python\n# substitute result into f\nf = f.subs(sol)\n\n# show result\nMath(\"f(x)=\"+latex(f(x)))\n```\n\n\n\n\n$$f(x)=- \\frac{x^{2}}{3} + \\frac{8 x}{3}$$\n\n\n\nTo find the vertex form $f_s(x) = a_s\\,(x-x_s)^2 + y_s$, a new function is defined\n\n\n```python\n# define f_s\nx = Symbol('x')\na_s, x_s, y_s = symbols('a_s,x_s,y_s')\n\nf_s = FE(x, a_s*(x-x_s)**2 + y_s)\nMath(\"f_s(x)=\"+latex(f_s(x)))\n```\n\n\n\n\n$$f_s(x)=a_{s} \\left(x - x_{s}\\right)^{2} + y_{s}$$\n\n\n\nThe expanded coefficients of $f_s$ must be equal to the coefficients of the known function $f$.\n\nFirst, we create an expression `expr`, to hold the expanded form of $f_s(x)$\n\n\n```python\nexpr = f_s(x).expand()\nexpr\n```\n\nThen the method `expr.coeff` is used to get the coefficients of all powers of `x`:\n\n\n```python\nc_s = [expr.coeff(x,i) for i in range(3)]\nc_s\n```\n\nIn the same way, the list of coefficients of `f(x)` is determined.\n\nHere, `f(x)` is an expression, an we can use the method `f(x).coeff` directly.\n\n\n```python\nc = [f(x).coeff(x,i) for i in range(3)]\nc\n```\n\nThis leads to a system of equations:\n\n\n```python\neqns_s = [Eq(lc,rc) for lc,rc in zip(c_s,c)]\n\nfor eq in eqns_s:\n display(eq)\n```\n\nThis system of equations could also be archieved by\n\n\n```python\neqns_s = [Eq(f_s(x).expand().coeff(x,i),f(x).coeff(x,i)) for i in range(3)]\n\nfor eq in eqns_s:\n display(eq)\n```\n\nThe solution gives the unknown values $a_s$, $x_s$ and $y_s$:\n\n\n```python\nsol_s = solve(eqns_s)\nsol_s\n```\n\nSince the system of equations is not linear, the solution is a list of possible solutions. This list contains only one dict of solutions.\n\n\n```python\n# substitute sol_s into f_s\nf_s = f_s.subs(*sol_s)\nMath(\"f_s(x)=\"+latex(f_s(x)))\n```\n\n\n\n\n$$f_s(x)=- \\frac{1}{3} \\left(x - 4\\right)^{2} + \\frac{16}{3}$$\n\n\n\n\n```python\n# f and f_s define essentially the same function.\n# To see this, we need both of them in expanded form\nf(x) == f_s(x).expand()\n```\n\n\n\n\n True\n\n\n\nDisplay the result:\n\n\n```python\n# init new plot\nfig, ax = plt.subplots()\n\n# redefine x_s\nx_s = x_s.subs(*sol_s)\nd = 6\n\n# the interval along the x-axis\nlx = np.linspace(float(x_s-d),float(x_s+d))\n\n# plot f(x), the given points and the vertex\nax.plot(lx,f.lambdified(lx),label=r\"$y={f}$\".format(f=latex(f(x))))\nax.scatter(*zip(*pts))\nax.scatter(x_s,f(x_s),c='r')\n\n# refine plot\nax.axhline(0)\nax.axvline(0)\nax.grid(True)\nax.legend(loc='best')\nax.set_xlabel('x')\nax.set_ylabel('y')\nax.set_title('A polynomial of degree 2')\n\n# show result\nplt.show()\n```\n", "meta": {"hexsha": "abdb61c9a48d1b8129ea20d1954b4a1824955e65", "size": 71474, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "docs/03-square_functions.ipynb", "max_stars_repo_name": "w-meiners/fun-expr", "max_stars_repo_head_hexsha": "a44f0366f08c8c2d2eb2702176698bfe3f6febed", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2017-12-20T16:16:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-28T11:06:38.000Z", "max_issues_repo_path": "docs/03-square_functions.ipynb", "max_issues_repo_name": "w-meiners/fun-expr", "max_issues_repo_head_hexsha": "a44f0366f08c8c2d2eb2702176698bfe3f6febed", "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/03-square_functions.ipynb", "max_forks_repo_name": "w-meiners/fun-expr", "max_forks_repo_head_hexsha": "a44f0366f08c8c2d2eb2702176698bfe3f6febed", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-01-27T09:50:59.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-27T09:50:59.000Z", "avg_line_length": 115.2806451613, "max_line_length": 44700, "alphanum_fraction": 0.8626773372, "converted": true, "num_tokens": 1238, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107878954105, "lm_q2_score": 0.91367652458901, "lm_q1q2_score": 0.8563074954916065}} {"text": "# Mandatory exercises\n\n1. Consider the ODE\n\\begin{equation}\n \\begin{split}\n y'(t)+1000y(t)=0,\\quad 0\\leq t\\leq2\\\\\n y(0)=0.5,\n \\end{split}\n\\end{equation}\nsolved numerically by a numerical method with a step size $h$.\n\n 1. What is the step size restriction by stability if we use the forward Euler method?\n 2. What is the step size restriction by stability if we use the backward Euler method? What other factors should we consider when choosing the step size?\n \n\n2. The numerical scheme\n\\begin{equation}\n \\begin{split}\n y_{i+1}=y_i-hky_i,\n \\end{split}\n\\end{equation}\nis used to approximate the differential equation $y'(t)=-ky(t)$ with step size $h$. What is the order of accuracy for this approximation? Motivate your answer by the analysis of the local truncation error.\n\n3. Heun’s method can be written as\n\\begin{equation}\n y_{i+1}=y_i+\\frac{h}{2}(f(t_i,y_i)+f(t_{i+1},\\tilde{y}_{i+1})),\n\\end{equation}\nwhere $\\tilde{y}_{i+1}=y_i+hf(t_i,y_i)$. Is Heun’s method an explicit method or an implicit method? Is it unconditionally stable? Motivate your answer by the stability analysis of the test equation\n\\begin{equation}\n \\begin{split}\n y'(t) = -\\lambda y,\\, \\mathcal{R}(\\lambda)>0\\\\\n y(0)=y_0.\n \\end{split}\n\\end{equation}\n\n# Non-mandatory exercises\n\n4. The following is a model for how an infectuous disease spreads in a population:\n\\begin{equation}\n P'=(k+0.1\\sin(t))P(C-P).\n\\end{equation}\nHere, $P(t)$ represents the total number of individuals who have had the infection at time $t$ and $C$ is the total number of individuals in the population. The parameter $k$ represents the risk of becoming infected and the sinus function models seasonal variation in susceptibility to infection.\n\n 1. Let $g(t,P)$ denote the right-hand side in the differential equation above. Then, a family of numerical methods for solving the equation can be expressed as:\\begin{equation}P_{k+1}=P_k+h(c_1g(t_k,P_k)+c_2g(t_{k+1},P_{k+1})).\\end{equation} Each specific choice of values $c_1$ and $c_2$ yields a specific method within this family. For what values of $c_1$ and $c_2$ , respectively, will you get (i) an explicit method; (ii) an implicit method.\n 2. What values of $c_1$ and $c_2$, respectively, will yield a consistent method?\n 3. There is a limit to the order of accuracy that can be obtained within this family of methods. What is the best order of accuracy and what values of $c_1$ and $c_2$ are required to obtain it?\n\n5. Suppose that you are to solve an ODE problem by means of the Explicit Euler method, and that you choose a step size $h = h_0$ that is too large, so that the approximate solution obtained is not sufficiently accurate compared to the tolerance level you have set for this problem. You should now consider the following alternative strategies to improve the accuracy:\n 1. Reduce the step size to $h = ch_0$ , where $0 < c < 1$, so that Explicit Euler will give sufficient accuracy.\n 2. Keep the step size $h = h_0$ but change to Heun’s method, assuming that Heun’s method is sufficiently accurate with that step size.\n \nSince both alternatives will give a solution within the given tolerance,\nyou should use the strategy that results in the shortest execution time.\nWhich alternative will you then choose? (There is no exact answer\nto this question, but you could make a rough analysis to find out\napproximately how small c would have to be in order for the second\nalternative to be preferable.)\n", "meta": {"hexsha": "f81dfec01e3df4373e4fb8aa41a990558c7a9b9b", "size": 6677, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Workouts/Workout3.ipynb", "max_stars_repo_name": "enigne/ScientificComputingBridging", "max_stars_repo_head_hexsha": "920f3c9688ae0e7d17cffce5763289864b9cac80", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-05-04T01:15:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-08T15:08:27.000Z", "max_issues_repo_path": "Workouts/Workout3.ipynb", "max_issues_repo_name": "enigne/ScientificComputingBridging", "max_issues_repo_head_hexsha": "920f3c9688ae0e7d17cffce5763289864b9cac80", "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": "Workouts/Workout3.ipynb", "max_forks_repo_name": "enigne/ScientificComputingBridging", "max_forks_repo_head_hexsha": "920f3c9688ae0e7d17cffce5763289864b9cac80", "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.241025641, "max_line_length": 461, "alphanum_fraction": 0.6101542609, "converted": true, "num_tokens": 951, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.925229959153748, "lm_q2_score": 0.9252299591537478, "lm_q1q2_score": 0.856050477315646}} {"text": "```python\nfrom sympy import *\nfrom collections import defaultdict\nfrom IPython.display import display\nimport numpy as np\nimport matplotlib.pyplot as plt\n%matplotlib inline\ninit_printing()\n```\n\n### Bspline basis\n\n\n```python\nxs = Symbol('x')\nknots = [0,1,2,3,4,5,6]\n\n# Third-order bspline\nsym_basis = bspline_basis_set(3, knots, xs)\n# Form for one basis function\nsym_basis[0]\n```\n\n\n```python\n# Plot some basis functions\nnbasis_to_plot = 3\nnpoints_to_plot = 40\nbasis_y = np.zeros((nbasis_to_plot, npoints_to_plot))\nxvals = np.zeros(npoints_to_plot)\nfor i in range(npoints_to_plot):\n xv = i*.1 + 1.0\n for j in range(3):\n basis_y[j,i] = sym_basis[j].subs(xs,xv)\n xvals[i] = xv\nplt.plot(xvals, basis_y[0,:], xvals, basis_y[1,:], xvals, basis_y[2,:])\n```\n\n### Function approximation\nTo fully represent an interval (say, 0.0 - 5.0, with a knot spacing of 1.0), we need parts of basis functions outside the interval as well. To approximate a function, we evaluate at the M knots (there are 6 knots for this example). There will be M+2 basis functions.\n\n\n```python\n# Need knot values outside the target interval to generate the right set of basis functions.\nknots = [0,1,2,3,4,5]\nall_knots = [-3,-2,-1,0,1,2,3,4,5,6,7,8]\n\n# Third-order bspline\nsym_basis = bspline_basis_set(3, all_knots, xs)\nprint(\"Number of basis functions = \",len(sym_basis))\nsym_basis\n```\n\nTo approximate a function we need coefficients for each basis function \n$$\nf(x) = \\sum_0^{M+2} c_i B_i(x)\n$$\nThe values of the function at the knots provides $M$ constraints. We still need 2 more to fully specify the coefficients. This is where the boundary conditions come into play.\n\n$$\n\\sum_0^{M+2} c_i B_i(x_j) = g(x_j)\n$$\n\n\n```python\n# Fill out the coefficient matrix\nmat = Matrix.eye(len(knots)+2)\nfor i,k in enumerate(knots):\n for j,basis in enumerate(sym_basis):\n bv = basis.subs(xs,k)\n mat[i+1,j] = bv\n\n# Natural boundary conditions - set 2nd derivative at end of range to zero\ndd_spline = [diff(bs, xs, 2) for bs in sym_basis]\n\nrow0 = [dds.subs(xs, 0) for dds in dd_spline]\nrowN = [dds.subs(xs, knots[-1]) for dds in dd_spline]\ndisplay(row0)\ndisplay(rowN)\nfor i in range(len(row0)):\n mat[0,i] = row0[i]\n mat[-1,i] = rowN[i]\nmat\n\n```\n\n\n```python\n# Let us assume a simple quadratic function for interpolation\nfunc_to_approx = [k*k for k in knots]\nfunc_to_approx\n```\n\n### Solve for coefficients\n\n\n```python\nlhs_vals = [0] + func_to_approx + [0] # Zeros are the value of the second derivative\ncoeffs = mat.LUsolve(Matrix(len(lhs_vals), 1, lhs_vals))\ncoeffs.T.tolist()[0]\n```\n\n### Evaluate the spline\n\n\n```python\ndef spline_eval(basis, coeffs, x):\n val = 0.0\n for c,bs in zip(coeffs, basis):\n val += c*bs.subs(xs,x)\n return val\n```\n\n\n```python\n# check that it reproduces the knots\nfor k,v in zip(knots,func_to_approx):\n print(k,spline_eval(sym_basis, coeffs, k),v)\n```\n\n (0, 0, 0)\n (1, 1, 1)\n (2, 4, 4)\n (3, 9, 9)\n (4, 16, 16)\n (5, 25, 25)\n\n\n\n```python\n# Now check elsewhere\nxvals = []\nyvals = []\nfor i in range(50):\n x = .1*i\n val = spline_eval(sym_basis, coeffs, x)\n xvals.append(x)\n yvals.append(val)\nplt.plot(xvals, yvals)\n#plt.plot(xvals, yvals, knots, func_to_approx)\n```\n\n### Matching Einspline\nThe einspline code collects the values of each power of x in each interval. The current form of the basis functions is a piecewise interval on the inside, and multiplication by the coefficients on the outside. We would like to transpose this representation so that the intervals are on the outside, and the constributions from each coefficient are on the inside. This will require some examination of the Sympy representation for intervals.\n\n\n```python\ndef to_interval(ival):\n \"\"\"Convert relational expression to an Interval\"\"\"\n min_val = None\n lower_open = False\n max_val = None\n upper_open = True\n if isinstance(ival, And):\n for rel in ival.args:\n #print('rel ',rel, type(rel), rel.args[1])\n if isinstance(rel, StrictGreaterThan):\n min_val = rel.args[1]\n #lower_open = True\n elif isinstance(rel, GreaterThan):\n min_val = rel.args[1]\n #lower_open = False\n elif isinstance(rel, StrictLessThan):\n max_val = rel.args[1]\n #upper_open = True\n elif isinstance(rel, LessThan):\n max_val = rel.args[1]\n #upper_open = False\n else:\n print('unhandled ',rel)\n\n if min_val == None or max_val == None:\n print('error',ival)\n return Interval(min_val, max_val, lower_open, upper_open)\n```\n\n\n```python\n# Transpose the interval and coefficients\n# Note that interval [0,1) has the polynomial coefficients found in the einspline code\n# The other intervals could be shifted, and they would also have the same polynomials\ndef transpose_interval_and_coefficients(sym_basis):\n cond_map = defaultdict(list)\n\n i1 = Interval(0,5, False, False) # interval for evaluation\n for idx, s0 in enumerate(sym_basis):\n for expr, cond in s0.args:\n if cond != True:\n i2 = to_interval(cond)\n if not i1.is_disjoint(i2):\n cond_map[i2].append( (idx, expr) )\n return cond_map\n\ncond_map = transpose_interval_and_coefficients(sym_basis)\nfor cond, expr in cond_map.items():\n #print(cond, [e.subs(x, x-cond.args[0]) for e in expr])\n print(\"Interval = \",cond)\n # Shift interval to a common start - see that the polynomial coefficients are all the same\n #e2 = [expand(e[1].subs(xs, xs+cond.args[0])) for e in expr]\n e2 = [(idx,expand(e)) for idx, e in expr]\n display(e2)\n```\n\n\n```python\n# Create piecewise expression from the transposed intervals\ndef recreate_piecewise(basis_map, c):\n args = []\n for cond, exprs in basis_map.items():\n e = 0\n for idx, b in exprs:\n e += c[idx] * b\n args.append( (e, cond.as_relational(xs)))\n return Piecewise(*args)\n\nc = IndexedBase('c')\nspline = recreate_piecewise(cond_map, c)\nspline\n```\n\n\n```python\ndef spline_eval2(spline, coeffs, x):\n \"\"\"Evaluate spline using transposed expression\"\"\"\n val = 0.0\n c = IndexedBase('c')\n to_sub = {}\n for i,cf in enumerate(coeffs):\n to_sub[c[i]] = cf\n to_sub[xs] = x\n return spline.subs(to_sub)\n\n```\n\n\n```python\nfor k in knots:\n val = spline_eval2(spline, coeffs, k)\n print(k,val)\n```\n\n (0, 0)\n (1, 1)\n (2, 4)\n (3, 9)\n (4, 16)\n (5, 25)\n\n\n## Bspline for Jastrow\n\nFor the radial part of the Jastrow factor, the derivative at $r=0$ is fixed by the cusp condition. At $r=r_{cut}$, the value and derivatives are zero.\n\nAlso add the grid spacing, $\\Delta$, to the knots.\n\n\n```python\nDelta = Symbol('Delta',positive=True)\n#knots = [0,1*Delta,2*Delta,3*Delta,4*Delta,5*Delta]\nnknots = 6\nknots = [i*Delta for i in range(nknots)]\ndisplay('knots = ',knots)\n#all_knots = [-3*Delta,-2*Delta,-1*Delta,0,1*Delta,2*Delta,3*Delta,4*Delta,5*Delta,6*Delta,7*Delta,8*Delta]\nall_knots = [i*Delta for i in range(-3,nknots+3)]\n#display('all knots',all_knots)\nrcut = (nknots-1)*Delta\n\n# Third-order bspline\njastrow_sym_basis = bspline_basis_set(3, all_knots, xs)\nprint(\"Number of basis functions = \",len(jastrow_sym_basis))\n#jastrow_sym_basis\n```\n\n\n```python\n# Now create the spline from the basis functions\njastrow_cond_map = transpose_interval_and_coefficients(jastrow_sym_basis)\nc = IndexedBase('c',shape=(nknots+3))\n#c = MatrixSymbol('c',nknots+3,1)\njastrow_spline = recreate_piecewise(jastrow_cond_map, c)\njastrow_spline\n```\n\n\n```python\n# Boundary conditions at r = 0 with the cusp (first derivative) condition\n\ncusp_val = Symbol('A')\n# Evaluate spline derivative at 0\ndu = diff(jastrow_spline,xs)\ndu_zero = du.subs(xs, 0)\ndisplay(du_zero)\n\n# Solve following equation\ndisplay(Eq(du_zero-cusp_val,0))\n\n# solve doesn't seem to work with Indexed value, substitute something else\nc0 = Symbol('c0')\nsoln = solve(du_zero.subs(c[0],c0) - cusp_val, c0)\ndisplay(Eq(c0, soln[0]))\n```\n\n\n```python\n# Boundary conditions at r=r_cut. For smoothness the value and derivatives should be 0.\n# Add zero value and derivatives at r_cut\neq_v = jastrow_spline.subs(xs, rcut)\ndisplay(Eq(Symbol('u')(xs),eq_v))\n\neq_dv = diff(jastrow_spline, xs).subs(xs,rcut)\ndisplay(Eq(diff(Symbol('u')(xs),xs),eq_dv))\n\neq_ddv = diff(jastrow_spline, xs, 2).subs(xs,rcut)\ndisplay(Eq(diff(Symbol('u')(xs),xs,2),eq_ddv))\n\n#eq_d3v = diff(jastrow_spline, xs, 3).subs(xs, rcut)\n#display(eq_d3v)\n```\n\n\n```python\n# Solve for all these equal to zero\nc5 = Symbol('c5')\nc6 = Symbol('c6')\nc7 = Symbol('c7')\nsubs_list = {c[5]:c5, c[6]:c6, c[7]:c7}\nlinsolve([v.subs(subs_list) for v in [eq_v, eq_dv, eq_ddv]], [c5, c6, c7])\n# QMCPACK enforces these conditions by setting c5, c6, c7 (the last three coefficients) to 0.\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "e461f946729033b9d366ab80c223333c87411fd4", "size": 294533, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Wavefunctions/Explain_Bspline.ipynb", "max_stars_repo_name": "markdewing/qmc_algorithms", "max_stars_repo_head_hexsha": "0575c8cdbc66eac26f323f26a63dcf6222f31152", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2017-12-30T09:21:01.000Z", "max_stars_repo_stars_event_max_datetime": "2017-12-31T12:31:09.000Z", "max_issues_repo_path": "Wavefunctions/Explain_Bspline.ipynb", "max_issues_repo_name": "markdewing/qmc_algorithms", "max_issues_repo_head_hexsha": "0575c8cdbc66eac26f323f26a63dcf6222f31152", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-03-23T17:17:04.000Z", "max_issues_repo_issues_event_max_datetime": "2017-03-23T17:17:04.000Z", "max_forks_repo_path": "Wavefunctions/Explain_Bspline.ipynb", "max_forks_repo_name": "markdewing/qmc_algorithms", "max_forks_repo_head_hexsha": "0575c8cdbc66eac26f323f26a63dcf6222f31152", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2016-06-30T21:29:32.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-22T16:10:03.000Z", "avg_line_length": 208.2977369165, "max_line_length": 54972, "alphanum_fraction": 0.7998899953, "converted": true, "num_tokens": 2681, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070060380482, "lm_q2_score": 0.9407897513338646, "lm_q1q2_score": 0.8560311859474765}} {"text": "# Constraint Satisfaction Problems Lab\n\n## Introduction\nConstraint Satisfaction is a technique for solving problems by expressing limits on the values of each variable in the solution with mathematical constraints. We've used constraints before -- constraints in the Sudoku project are enforced implicitly by filtering the legal values for each box, and the planning project represents constraints as arcs connecting nodes in the planning graph -- but in this lab exercise we will use a symbolic math library to explicitly construct binary constraints and then use Backtracking to solve the N-queens problem (which is a generalization [8-queens problem](https://en.wikipedia.org/wiki/Eight_queens_puzzle)). Using symbolic constraints should make it easier to visualize and reason about the constraints (especially for debugging), but comes with a performance penalty.\n\n\n\nBriefly, the 8-queens problem asks you to place 8 queens on a standard 8x8 chessboard such that none of the queens are in \"check\" (i.e., no two queens occupy the same row, column, or diagonal). The N-queens problem generalizes the puzzle to to any size square board.\n\n## I. Lab Overview\nStudents should read through the code and the wikipedia page (or other resources) to understand the N-queens problem, then:\n\n0. Complete the warmup exercises in the [Sympy_Intro notebook](Sympy_Intro.ipynb) to become familiar with they sympy library and symbolic representation for constraints\n0. Implement the [NQueensCSP class](#II.-Representing-the-N-Queens-Problem) to develop an efficient encoding of the N-queens problem and explicitly generate the constraints bounding the solution\n0. Write the [search functions](#III.-Backtracking-Search) for recursive backtracking, and use them to solve the N-queens problem\n0. (Optional) Conduct [additional experiments](#IV.-Experiments-%28Optional%29) with CSPs and various modifications to the search order (minimum remaining values, least constraining value, etc.)\n\n\n```python\nimport copy\nimport timeit\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\n\nfrom util import constraint, displayBoard\nfrom sympy import *\nfrom IPython.display import display\ninit_printing()\n%matplotlib inline\n```\n\n## II. Representing the N-Queens Problem\nThere are many acceptable ways to represent the N-queens problem, but one convenient way is to recognize that one of the constraints (either the row or column constraint) can be enforced implicitly by the encoding. If we represent a solution as an array with N elements, then each position in the array can represent a column of the board, and the value at each position can represent which row the queen is placed on.\n\nIn this encoding, we only need a constraint to make sure that no two queens occupy the same row, and one to make sure that no two queens occupy the same diagonal.\n\n### Define Symbolic Expressions for the Problem Constraints\nBefore implementing the board class, we need to construct the symbolic constraints that will be used in the CSP. Declare any symbolic terms required, and then declare two generic constraint generators:\n- `diffRow` - generate constraints that return True if the two arguments do not match\n- `diffDiag` - generate constraints that return True if two arguments are not on the same diagonal (Hint: you can easily test whether queens in two columns are on the same diagonal by testing if the difference in the number of rows and the number of columns match)\n\nBoth generators should produce binary constraints (i.e., each should have two free symbols) once they're bound to specific variables in the CSP. For example, Eq((a + b), (b + c)) is not a binary constraint, but Eq((a + b), (b + c)).subs(b, 1) _is_ a binary constraint because one of the terms has been bound to a constant, so there are only two free variables remaining. \n\n\n```python\n# Declare any required symbolic variables\nr1, r2 = symbols(['r1', 'r2'])\nc1, c2 = symbols(['c1', 'c2'])\n\n# Define diffRow and diffDiag constraints\ndiffRow = constraint('DiffRow', ~Eq(r1, r2))\ndiffDiag = constraint('DiffDiag', ~Eq(abs(r1 - r2), abs(c1 - c2)))\n```\n\n\n```python\n# Test diffRow and diffDiag\n_x = symbols('x:3')\n\n# generate a diffRow instance for testing\ndiffRow_test = diffRow.subs({r1: _x[0], r2: _x[1]})\n\nassert(len(diffRow_test.free_symbols) == 2)\nassert(diffRow_test.subs({_x[0]: 0, _x[1]: 1}) == True)\nassert(diffRow_test.subs({_x[0]: 0, _x[1]: 0}) == False)\nassert(diffRow_test.subs({_x[0]: 0}) != False) # partial assignment is not false\nprint(\"Passed all diffRow tests.\")\n\n# generate a diffDiag instance for testing\ndiffDiag_test = diffDiag.subs({r1: _x[0], r2: _x[2], c1:0, c2:2})\n\nassert(len(diffDiag_test.free_symbols) == 2)\nassert(diffDiag_test.subs({_x[0]: 0, _x[2]: 2}) == False)\nassert(diffDiag_test.subs({_x[0]: 0, _x[2]: 0}) == True)\nassert(diffDiag_test.subs({_x[0]: 0}) != False) # partial assignment is not false\nprint(\"Passed all diffDiag tests.\")\n```\n\n Passed all diffRow tests.\n Passed all diffDiag tests.\n\n\n### The N-Queens CSP Class\nImplement the CSP class as described above, with constraints to make sure each queen is on a different row and different diagonal than every other queen, and a variable for each column defining the row that containing a queen in that column.\n\n\n```python\nclass NQueensCSP:\n \"\"\"CSP representation of the N-queens problem\n \n Parameters\n ----------\n N : Integer\n The side length of a square chess board to use for the problem, and\n the number of queens that must be placed on the board\n \"\"\"\n def __init__(self, N):\n _vars = symbols(f'A0:{N}')\n _domain = set(range(N))\n self.size = N\n self.variables = _vars\n self.domains = {v: _domain for v in _vars}\n self._constraints = {x: set() for x in _vars}\n\n # add constraints - for each pair of variables xi and xj, create\n # a diffRow(xi, xj) and a diffDiag(xi, xj) instance, and add them\n # to the self._constraints dictionary keyed to both xi and xj;\n # (i.e., add them to both self._constraints[xi] and self._constraints[xj])\n for i in range(N):\n for j in range(i + 1, N):\n diffRowConstraint = diffRow.subs({r1: _vars[i], r2: _vars[j]})\n diffDiagConstraint = diffDiag.subs({r1: _vars[i], r2: _vars[j], c1:i, c2:j})\n self._constraints[_vars[i]].add(diffRowConstraint)\n self._constraints[_vars[i]].add(diffDiagConstraint)\n self._constraints[_vars[j]].add(diffRowConstraint)\n self._constraints[_vars[j]].add(diffDiagConstraint)\n \n @property\n def constraints(self):\n \"\"\"Read-only list of constraints -- cannot be used for evaluation \"\"\"\n constraints = set()\n for _cons in self._constraints.values():\n constraints |= _cons\n return list(constraints)\n \n def is_complete(self, assignment):\n \"\"\"An assignment is complete if it is consistent, and all constraints\n are satisfied.\n \n Hint: Backtracking search checks consistency of each assignment, so checking\n for completeness can be done very efficiently\n \n Parameters\n ----------\n assignment : dict(sympy.Symbol: Integer)\n An assignment of values to variables that have previously been checked\n for consistency with the CSP constraints\n \"\"\"\n return len(assignment) == self.size\n \n def is_consistent(self, var, value, assignment):\n \"\"\"Check consistency of a proposed variable assignment\n \n self._constraints[x] returns a set of constraints that involve variable `x`.\n An assignment is consistent unless the assignment it causes a constraint to\n return False (partial assignments are always consistent).\n \n Parameters\n ----------\n var : sympy.Symbol\n One of the symbolic variables in the CSP\n \n value : Numeric\n A valid value (i.e., in the domain of) the variable `var` for assignment\n\n assignment : dict(sympy.Symbol: Integer)\n A dictionary mapping CSP variables to row assignment of each queen\n \n \"\"\"\n assignment[var] = value\n constraints = list(self._constraints[var])\n for constraint in constraints:\n for arg in constraint.args:\n if arg in assignment.keys():\n constraint = constraint.subs({arg: assignment[arg]})\n if not constraint:\n return False\n return True\n \n def inference(self, var, value):\n \"\"\"Perform logical inference based on proposed variable assignment\n \n Returns an empty dictionary by default; function can be overridden to\n check arc-, path-, or k-consistency; returning None signals \"failure\".\n \n Parameters\n ----------\n var : sympy.Symbol\n One of the symbolic variables in the CSP\n \n value : Integer\n A valid value (i.e., in the domain of) the variable `var` for assignment\n \n Returns\n -------\n dict(sympy.Symbol: Integer) or None\n A partial set of values mapped to variables in the CSP based on inferred\n constraints from previous mappings, or None to indicate failure\n \"\"\"\n # TODO (Optional): Implement this function based on AIMA discussion\n return {}\n \n def show(self, assignment):\n \"\"\"Display a chessboard with queens drawn in the locations specified by an\n assignment\n \n Parameters\n ----------\n assignment : dict(sympy.Symbol: Integer)\n A dictionary mapping CSP variables to row assignment of each queen\n \n \"\"\"\n locations = [(i, assignment[j]) for i, j in enumerate(self.variables)\n if assignment.get(j, None) is not None]\n displayBoard(locations, self.size)\n```\n\n## III. Backtracking Search\nImplement the [backtracking search](https://github.com/aimacode/aima-pseudocode/blob/master/md/Backtracking-Search.md) algorithm (required) and helper functions (optional) from the AIMA text. \n\n\n```python\ndef select(csp, assignment):\n \"\"\"Choose an unassigned variable in a constraint satisfaction problem \"\"\"\n # TODO (Optional): Implement a more sophisticated selection routine from AIMA\n for var in csp.variables:\n if var not in assignment:\n return var\n return None\n\ndef order_values(var, assignment, csp):\n \"\"\"Select the order of the values in the domain of a variable for checking during search;\n the default is lexicographically.\n \"\"\"\n # TODO (Optional): Implement a more sophisticated search ordering routine from AIMA\n return csp.domains[var]\n\ndef backtracking_search(csp):\n \"\"\"Helper function used to initiate backtracking search \"\"\"\n return backtrack({}, csp)\n\ndef backtrack(assignment, csp):\n \"\"\"Perform backtracking search for a valid assignment to a CSP\n \n Parameters\n ----------\n assignment : dict(sympy.Symbol: Integer)\n An partial set of values mapped to variables in the CSP\n \n csp : CSP\n A problem encoded as a CSP. Interface should include csp.variables, csp.domains,\n csp.inference(), csp.is_consistent(), and csp.is_complete().\n \n Returns\n -------\n dict(sympy.Symbol: Integer) or None\n A partial set of values mapped to variables in the CSP, or None to indicate failure\n \"\"\"\n if csp.is_complete(assignment):\n return assignment\n var = select(csp, assignment)\n for value in order_values(var, assignment, csp):\n if csp.is_consistent(var, value, assignment):\n assignment[var] = value\n assignment_copy = copy.deepcopy(assignment)\n result = backtrack(assignment_copy, csp)\n if result is not None:\n return result\n```\n\n### Solve the CSP\nWith backtracking implemented, now you can use it to solve instances of the problem. We've started with the classical 8-queen version, but you can try other sizes as well. Boards larger than 12x12 may take some time to solve because sympy is slow in the way its being used here, and because the selection and value ordering methods haven't been implemented. See if you can implement any of the techniques in the AIMA text to speed up the solver!\n\n\n```python\nstart = timeit.default_timer()\nnum_queens = 12\ncsp = NQueensCSP(num_queens)\nvar = csp.variables[0]\nprint(\"CSP problems have variables, each variable has a domain, and the problem has a list of constraints.\")\nprint(\"Showing the variables for the N-Queens CSP:\")\ndisplay(csp.variables)\nprint(\"Showing domain for {}:\".format(var))\ndisplay(csp.domains[var])\nprint(\"And showing the constraints for {}:\".format(var))\ndisplay(csp._constraints[var])\n\nprint(\"Solving N-Queens CSP...\")\nassn = backtracking_search(csp)\nif assn is not None:\n csp.show(assn)\n print(\"Solution found:\\n{!s}\".format(assn))\nelse:\n print(\"No solution found.\")\n \nend = timeit.default_timer() - start\nprint(f'N-Queens size {num_queens} solved in {end} seconds')\n```\n\n## IV. Experiments (Optional)\nFor each optional experiment, discuss the answers to these questions on the forum: Do you expect this change to be more efficient, less efficient, or the same? Why or why not? Is your prediction correct? What metric did you compare (e.g., time, space, nodes visited, etc.)?\n\n- Implement a _bad_ N-queens solver: generate & test candidate solutions one at a time until a valid solution is found. For example, represent the board as an array with $N^2$ elements, and let each element be True if there is a queen in that box, and False if it is empty. Use an $N^2$-bit counter to generate solutions, then write a function to check if each solution is valid. Notice that this solution doesn't require any of the techniques we've applied to other problems -- there is no DFS or backtracking, nor constraint propagation, or even explicitly defined variables.\n- Use more complex constraints -- i.e., generalize the binary constraint RowDiff to an N-ary constraint AllRowsDiff, etc., -- and solve the problem again.\n- Rewrite the CSP class to use forward checking to restrict the domain of each variable as new values are assigned.\n- The sympy library isn't very fast, so this version of the CSP doesn't work well on boards bigger than about 12x12. Write a new representation of the problem class that uses constraint functions (like the Sudoku project) to implicitly track constraint satisfaction through the restricted domain of each variable. How much larger can you solve?\n- Create your own CSP!\n", "meta": {"hexsha": "0f87dbd66b5db991ed5d7b2414283c105101cffb", "size": 96093, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "1_foundations/5_nqueens/constraint_satisfaction.ipynb", "max_stars_repo_name": "madhavajay/nd889", "max_stars_repo_head_hexsha": "7be0d8eade9ede2da217448409305f6ef83efaeb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 32, "max_stars_repo_stars_event_min_datetime": "2017-02-22T20:55:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-24T09:37:31.000Z", "max_issues_repo_path": "1_foundations/5_nqueens/constraint_satisfaction.ipynb", "max_issues_repo_name": "madhavajay/nd889", "max_issues_repo_head_hexsha": "7be0d8eade9ede2da217448409305f6ef83efaeb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2017-02-20T15:08:26.000Z", "max_issues_repo_issues_event_max_datetime": "2017-03-24T10:59:28.000Z", "max_forks_repo_path": "1_foundations/5_nqueens/constraint_satisfaction.ipynb", "max_forks_repo_name": "madhavajay/nd889", "max_forks_repo_head_hexsha": "7be0d8eade9ede2da217448409305f6ef83efaeb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 30, "max_forks_repo_forks_event_min_datetime": "2017-02-20T11:58:33.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-21T08:26:53.000Z", "avg_line_length": 197.3162217659, "max_line_length": 56880, "alphanum_fraction": 0.8677843339, "converted": true, "num_tokens": 3329, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951643678381, "lm_q2_score": 0.9161096084360388, "lm_q1q2_score": 0.8560083881535483}} {"text": "# Interact Exercise 6\n\n## Imports\n\nPut the standard imports for Matplotlib, Numpy and the IPython widgets in the following cell.\n\n\n```python\n%matplotlib inline\nimport matplotlib.pyplot as plt\nimport numpy as np\n```\n\n\n```python\nfrom IPython.display import Image\nfrom IPython.html.widgets import interact, interactive, fixed\n```\n\n## Exploring the Fermi distribution\n\nIn quantum statistics, the [Fermi-Dirac](http://en.wikipedia.org/wiki/Fermi%E2%80%93Dirac_statistics) distribution is related to the probability that a particle will be in a quantum state with energy $\\epsilon$. The equation for the distribution $F(\\epsilon)$ is:\n\n\n```python\nImage('fermidist.png')\n```\n\nIn this equation:\n\n* $\\epsilon$ is the single particle energy.\n* $\\mu$ is the chemical potential, which is related to the total number of particles.\n* $k$ is the Boltzmann constant.\n* $T$ is the temperature in Kelvin.\n\nIn the cell below, typeset this equation using LaTeX:\n\n\\begin{align}\nF(\\epsilon) = \\frac{1}{e^{(\\epsilon-\\mu)/kt} + 1}\n\\end{align}\n\nDefine a function `fermidist(energy, mu, kT)` that computes the distribution function for a given value of `energy`, chemical potential `mu` and temperature `kT`. Note here, `kT` is a single variable with units of energy. Make sure your function works with an array and don't use any `for` or `while` loops in your code.\n\n\n```python\ndef fermidist(energy, mu, kT):\n \"\"\"Compute the Fermi distribution at energy, mu and kT.\"\"\"\n f = 1/(np.exp((energy-mu)/kT)+1)\n return f\n```\n\n\n```python\nassert np.allclose(fermidist(0.5, 1.0, 10.0), 0.51249739648421033)\nassert np.allclose(fermidist(np.linspace(0.0,1.0,10), 1.0, 10.0),\n np.array([ 0.52497919, 0.5222076 , 0.51943465, 0.5166605 , 0.51388532,\n 0.51110928, 0.50833256, 0.50555533, 0.50277775, 0.5 ]))\n```\n\nWrite a function `plot_fermidist(mu, kT)` that plots the Fermi distribution $F(\\epsilon)$ as a function of $\\epsilon$ as a line plot for the parameters `mu` and `kT`.\n\n* Use enegies over the range $[0,10.0]$ and a suitable number of points.\n* Choose an appropriate x and y limit for your visualization.\n* Label your x and y axis and the overall visualization.\n* Customize your plot in 3 other ways to make it effective and beautiful.\n\n\n```python\ndef plot_fermidist(mu, kT):\n plt.figure(figsize=(9,6))\n plt.plot(np.linspace(0.0,10.0,100),fermidist(np.linspace(0.0,10.0,100), mu, kT),'r')\n plt.xlabel('Energy')\n plt.ylabel('Fermi Distribution')\n plt.title('Fermi Distribution as a function of Energy')\n plt.xlim(0.0, 10.0)\n plt.ylim(0.0, 1.0)\n plt.grid(True)\n plt.box(False)\n```\n\n\n```python\nplot_fermidist(4.0, 1.0)\n```\n\n\n```python\nassert True # leave this for grading the plot_fermidist function\n```\n\nUse `interact` with `plot_fermidist` to explore the distribution:\n\n* For `mu` use a floating point slider over the range $[0.0,5.0]$.\n* for `kT` use a floating point slider over the range $[0.1,10.0]$.\n\n\n```python\ninteract(plot_fermidist, mu=(0.0,10.0),kT=(0.1,10.0));\n```\n\nProvide complete sentence answers to the following questions in the cell below:\n\n* What happens when the temperature $kT$ is low?\n* What happens when the temperature $kT$ is high?\n* What is the effect of changing the chemical potential $\\mu$?\n* The number of particles in the system are related to the area under this curve. How does the chemical potential affect the number of particles.\n\nUse LaTeX to typeset any mathematical symbols in your answer.\n\nWhen $kT$ was low, the curve of $F$ became very steep. When $kT$ was high, the curve became much shallower. Changing the chemical potential $\\mu$ shifts the graph to the right with an increase, and to the left with a decrease. A decrease in $\\mu$ decreases the number of particles in the system and vice versa.\n", "meta": {"hexsha": "cd5ad556ddb11c54e7ac5cb13ec9436ca3b20a5e", "size": 49159, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "assignments/midterm/InteractEx06.ipynb", "max_stars_repo_name": "joshnsolomon/Josh-Solomon-PHYS-202-work", "max_stars_repo_head_hexsha": "919bb26416af0e81ca9724d5991e041dbd79d164", "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/midterm/InteractEx06.ipynb", "max_issues_repo_name": "joshnsolomon/Josh-Solomon-PHYS-202-work", "max_issues_repo_head_hexsha": "919bb26416af0e81ca9724d5991e041dbd79d164", "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/midterm/InteractEx06.ipynb", "max_forks_repo_name": "joshnsolomon/Josh-Solomon-PHYS-202-work", "max_forks_repo_head_hexsha": "919bb26416af0e81ca9724d5991e041dbd79d164", "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": 138.0870786517, "max_line_length": 20492, "alphanum_fraction": 0.8862873533, "converted": true, "num_tokens": 1092, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240194661944, "lm_q2_score": 0.9124361569052932, "lm_q1q2_score": 0.8559782750222809}} {"text": "```python\nimport numpy as np\nimport matplotlib.pyplot as plt\n```\n\n# More on Numeric Optimization\n\nRecall that in homework 2, in one problem you were asked to maximize the following function:\n \n\\begin{align}\nf(x) & = -7x^2 + 930x + 30\n\\end{align}\n \nUsing calculus, you found that $x^* = 930/14=66.42857$ maximizes $f$. You also used a brute force method to find $x^*$ that involved computing $f$ over a grid of $x$ values. That approach works but is inefficient.\n\nAn alternative would be to use an optimizaton algorithm that takes an initial guess and proceeds in a deliberate way. The `fmin` function from `scipy.optimize` executes such an algorithm. `fmin` takes as arguments a *function* and an ititial guess. It iterates, computing updates to the initial guess until the function appears to be close to a *minimum*. It's standard for optimization routines to minimize functions. If you want to maximize a function, supply the negative of the desired function to `fmin`.\n\n## Example using `fmin`\n\nLet's use `fmin` to solve the problem from Homework 2. First, import `fmin`.\n\n\n```python\nfrom scipy.optimize import fmin\n```\n\nNext, define a function that returns $-(-7x^2 + 930x + 30)$. We'll talk in class later about how to do this.\n\n\n```python\ndef quadratic(x):\n return -(-7*x**2 + 930*x + 30)\n```\n\nNow call `fmin`. We know that the exact solution, but let's guess something kind of far off. Like $x_0 = 10$.\n\n\n```python\nx_star = fmin(quadratic,x0=10)\n\nprint()\nprint('fmin solution: ',x_star[0])\nprint('exact solution:',930/14)\n```\n\n Optimization terminated successfully.\n Current function value: -30919.285714\n Iterations: 26\n Function evaluations: 52\n \n fmin solution: 66.4285888671875\n exact solution: 66.42857142857143\n\n\n`fmin` iterated 26 times and evaluated the function $f$ only 52 times. The solution is accurate to 4 digits. The same accuracy in the assignment would be obtained by setting the step to 0.00001 in constructing `x`.Wtih min and max values of 0 and 100, `x` would have 10,000,000 elements implying that the funciton $f$ would have to be evaluated that many times. Greater accuracy would imply ever larger numbers of function evaluations.\n\nTo get a sense of the iterative process that `fmin` uses, we can request that the function return the value of $x$ at each iteration using the argument `retall=True`.\n\n\n```python\nx_star, x_values = fmin(quadratic,x0=10,retall=True)\n\nprint()\nprint('fmin solution: ',x_star[0])\nprint('exact solution:',930/14)\n```\n\n Optimization terminated successfully.\n Current function value: -30919.285714\n Iterations: 26\n Function evaluations: 52\n \n fmin solution: 66.4285888671875\n exact solution: 66.42857142857143\n\n\nWe can plot the iterated values to see how the routine converges.\n\n\n```python\nfig = plt.figure()\nax = fig.add_subplot(1,1,1)\nax.set_xlabel('Iteration of fmin')\nax.set_ylabel('x')\nax.plot(x_values,label=\"Computed by fmin\")\nax.plot(np.zeros(len(x_values))+930/14,'--',label=\"True $x^*$\")\nax.legend(loc='center left', bbox_to_anchor=(1, 0.5))\n```\n\nAccuracy of the `fmin` result can be improved by reducing the `xtol` and `ftol` arguments. These arguments specify the required maximum magnitide between iterations of $x$ and $f$ that is acceptable for algorithm convergence. Both default to 0.0001.\n\nLet's try `xtol=1e-7`.\n\n\n```python\nfmin(quadratic,x0=10,xtol=1e-7)\n```\n\n Optimization terminated successfully.\n Current function value: -30919.285714\n Iterations: 36\n Function evaluations: 75\n\n\n\n\n\n array([66.42857122])\n\n\n\nThe result is accurate to an additional decimal place. Greater accuracy will be hard to achieve with `fmin` because the function is large in absolute value at the maximum. We can improve accuracy by scaling the function by 1/30,000.\n\n\n```python\ndef quadratic_2(x):\n return -(-7*(x)**2 + 930*(x) + 30)/30000\n\nx_star = fmin(quadratic_2,x0=930/14,xtol=1e-7)\nprint()\nprint('fmin solution: ',x_star[0])\nprint('exact solution:',930/14)\n```\n\n Optimization terminated successfully.\n Current function value: -1.030643\n Iterations: 26\n Function evaluations: 54\n \n fmin solution: 66.42857142857143\n exact solution: 66.42857142857143\n\n\nNow the computed solution is accurate to 14 decimal places.\n\n## Another example\n\nConsider the polynomial function:\n\n\\begin{align}\nf(x) & = -\\frac{(x-1)(x-2)(x-7)(x-9)}{200}\n\\end{align}\n\nThe function has two local maxima which can be seen by plotting.\n\n\n```python\ndef polynomial(x):\n '''Funciton for computing the NEGATIVE of the polynomial'''\n return (x-1)*(x-2)*(x-7)*(x-9)/200\n\nfig = plt.figure()\nax = fig.add_subplot(1,1,1)\nax.set_xlabel('y')\nax.set_ylabel('x')\nax.set_title('$f(x) = -(x-1)(x-2)(x-7)(x-9)/200$')\n\nx = np.linspace(0,10,1000)\nplt.plot(x,-polynomial(x))\n```\n\nNow, let's use `fmin` to compute the maximum of $f(x)$. Suppose that our initial guess is $x_0=4$.\n\n\n```python\nx_star,x_values = fmin(polynomial,x0=4,retall=True)\n\nprint()\nprint('fmin solution: ',x_star[0])\n```\n\n Optimization terminated successfully.\n Current function value: -0.051881\n Iterations: 18\n Function evaluations: 36\n \n fmin solution: 1.4611328124999978\n\n\nThe routine apparently converges on a value that is only a local maximum because the inital guess was not properly chosen. To see how `fmin` proceeded, plot the steps of the iterations on the curve:\n\n\n```python\n# Redefine x_values because it is a list of one-dimensional Numpy arrays. Not convenient.\nx_values = np.array(x_values).T[0]\n\nfig = plt.figure()\nax = fig.add_subplot(1,1,1)\nax.set_xlabel('y')\nax.set_ylabel('x')\nax.set_title('$f(x) = -(x-1)(x-2)(x-7)(x-9)/200$')\n\nplt.plot(x,-polynomial(x))\nplt.plot(x_values,-polynomial(x_values),'o',alpha=0.5,label='iterated values')\nax.legend(loc='center left', bbox_to_anchor=(1, 0.5))\n```\n\n`fmin` takes the intial guess and climbs the hill to the left. So apparently the ability of the routine to find the maximum depends on the quality of the initial guess. That's why plotting is important. We can see that beyond about 5.5, the function ascends to the global max. So let's guess $x_0 = 6$.\n\n\n```python\nx_star,x_values = fmin(polynomial,x0=6,retall=True)\n\nprint()\nprint('fmin solution: ',x_star[0])\n```\n\n Optimization terminated successfully.\n Current function value: -0.214917\n Iterations: 17\n Function evaluations: 34\n \n fmin solution: 8.147973632812505\n\n\n\n```python\n# Redefine x_values because it is a list of one-dimensional Numpy arrays. Not convenient.\nx_values = np.array(x_values).T[0]\n\nfig = plt.figure()\nax = fig.add_subplot(1,1,1)\nax.set_xlabel('y')\nax.set_ylabel('x')\nax.set_title('$f(x) = -(x-1)(x-2)(x-7)(x-9)/200$')\n\nplt.plot(x,-polynomial(x))\nplt.plot(x_values,-polynomial(x_values),'o',alpha=0.5,label='iterated values')\nax.legend(loc='center left', bbox_to_anchor=(1, 0.5))\n```\n\n`fmin` converges to the global maximum.\n\n\n\n## Solving systems of equations\n\nA related problem to numeric optimization is finding the solutions to systems of equations. Consider the problem of mximizing utility:\n\n\\begin{align}\nU(x,1,x_2) & = x_1^{\\alpha} x_2^{\\beta}\n\\end{align}\n\nsubject to the budget constraint:\n\n\\begin{align}\nM & = p_1x_1 + p_2x_2\n\\end{align}\n\nby choosing $x_1$ and $x_2$. Solve this by constructing the Lagrangian function:\n\n\\begin{align}\n\\mathcal{L}(x_1,x_2,\\lambda) & = x_1^{\\alpha} x_2^{\\beta} + \\lambda \\left(M - p_1x_1 - p_2x_2\\right)\n\\end{align}\n\nwhere $\\lambda$ is the Lagrange multiplier on the constraint. The first-order conditions represent a system of equations to be solved:\n\n\\begin{align}\n\\alpha x1^{\\alpha-1} x2^{\\beta} - \\lambda p_1 & = 0\\\\\n\\beta x1^{\\alpha} x2^{\\beta-1} - \\lambda p_2 & = 0\\\\\nM - p_1x_1 - p_2 x_2 & = 0\\\\\n\\end{align}\n\nSolved by hand, you find:\n\n\\begin{align}\nx_1^* & = \\left(\\frac{\\alpha}{\\alpha+\\beta}\\right)\\frac{M}{p_1}\\\\\nx_1^* & = \\left(\\frac{\\beta}{\\alpha+\\beta}\\right)\\frac{M}{p_2}\\\\\n\\lambda^* & = \\left(\\frac{\\alpha}{p_1}\\right)^{\\alpha}\\left(\\frac{\\beta}{p_2}\\right)^{\\beta}\\left(\\frac{M}{\\alpha+\\beta}\\right)^{\\alpha+\\beta - 1}\n\\end{align}\n\nBut solving this problem by hand was tedious. If we knew values for $\\alpha$, $\\beta$, $p_1$, $p_2$, and $M$, then we could use an equation solver to solve the system. The one we'll use is called `fsolve` from `scipy.optimize`.\n\nFor the rest of the example, assumethe following parameter values:\n\n| $\\alpha$ | $\\beta$ | $p_1$ | $p_2$ | $M$ |\n|----------|---------|-------|-------|-------|\n| 0.25 | 0.75 | 1 | 2 | 100 |\n\nFirst, import `fsolve`.\n\n\n```python\nfrom scipy.optimize import fsolve\n```\n\nDefine variables to store parameter values and compute exact solution\n\n\n```python\n# Parameters\nalpha = 0.25\nbeta = 0.75\np1 = 1\np2 = 2\nm = 100\n\n# Solution\nx1_star = m/p1*alpha/(alpha+beta)\nx2_star = m/p2*beta/(alpha+beta)\nlam_star = x_star = alpha**alpha*beta**beta*p1**-alpha*p2**-beta\n\nexact_soln = np.array([x1_star,x2_star,lam_star])\n```\n\nNext, define a function that returns the system of equations solved for zero. I.e., when the solution is input into the function, it return an array of zeros.\n\n\n```python\ndef system(x):\n \n x1,x2,lam = x\n \n retval = np.zeros(3)\n\n retval[0] = alpha*x1**(alpha-1)*x2**beta - lam*p1\n retval[1] = beta*x1**alpha*x2**(beta-1) - lam*p2\n retval[2] = m - p1*x1 - p2*x2\n \n return retval\n```\n\nSolve the system with `fsolve`. Set initial guess for $x_1$, $x_2$, and $\\lambda$ to 1, 1, and 1.\n\n\n```python\napprox_soln = fsolve(system,x0=[1,1,1])\n\nprint('Approximated solution:',approx_soln)\nprint('Exact solution: ',exact_soln)\n```\n\n Approximated solution: [25. 37.5 0.33885075]\n Exact solution: [25. 37.5 0.33885075]\n\n\nApparently the solution form fsolve is highly accurate. However, we can (and should) verify that original system is in fact equal to zero at the values returned by `fsolve`. Use `np.isclose` to test.\n\n\n```python\nnp.isclose(system(approx_soln),0)\n```\n\n\n\n\n array([ True, True, True])\n\n\n\nNote that like `fmin`, the results of `fsolve` are sensitive to the intial guess. Suppose we guess 1000 for $x_1$ and $x_2$.\n\n\n```python\napprox_soln = fsolve(system,x0=[1000,1000,1])\n\napprox_soln\n```\n\n :7: RuntimeWarning: invalid value encountered in double_scalars\n retval[0] = alpha*x1**(alpha-1)*x2**beta - lam*p1\n :8: RuntimeWarning: invalid value encountered in double_scalars\n retval[1] = beta*x1**alpha*x2**(beta-1) - lam*p2\n /Users/bcjenkin/opt/anaconda3/lib/python3.8/site-packages/scipy/optimize/minpack.py:175: RuntimeWarning: The iteration is not making good progress, as measured by the \n improvement from the last ten iterations.\n warnings.warn(msg, RuntimeWarning)\n\n\n\n\n\n array([1000., 1000., 1.])\n\n\n\nThe routine does not converge on the solution. The lesson is that with numerical routines for optimization and equation solving, you have to use juedgment in setting initial guesses and it helps to think carefully about the problem that you are solving beforehand.\n", "meta": {"hexsha": "6d13eacd3af5ed600a9ba6ca27b3454d77bcda12", "size": 96158, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Examples/Optimization_and_Equation_Solving.ipynb", "max_stars_repo_name": "letsgoexploring/econ126", "max_stars_repo_head_hexsha": "05f50d2392dd1c7c38b14950cb8d7eff7ff775ee", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-12-12T16:28:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-24T12:11:04.000Z", "max_issues_repo_path": "Examples/Optimization_and_Equation_Solving.ipynb", "max_issues_repo_name": "letsgoexploring/econ126", "max_issues_repo_head_hexsha": "05f50d2392dd1c7c38b14950cb8d7eff7ff775ee", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-04-29T08:50:41.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-29T08:51:05.000Z", "max_forks_repo_path": "Examples/.ipynb_checkpoints/Optimization_and_Equation_Solving-checkpoint.ipynb", "max_forks_repo_name": "letsgoexploring/econ126", "max_forks_repo_head_hexsha": "05f50d2392dd1c7c38b14950cb8d7eff7ff775ee", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 19, "max_forks_repo_forks_event_min_datetime": "2019-03-08T18:49:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T23:27:16.000Z", "avg_line_length": 131.7232876712, "max_line_length": 21412, "alphanum_fraction": 0.8757981655, "converted": true, "num_tokens": 3306, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361557147439, "lm_q2_score": 0.938124019033708, "lm_q1q2_score": 0.8559782735107818}} {"text": "\n\n# Ejemplo de simulación numérica\n\n\n```python\nimport numpy as np\nfrom scipy.integrate import odeint\nfrom matplotlib import rc\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\nrc(\"text\", usetex=True)\nrc(\"font\", size=18)\nrc(\"figure\", figsize=(6,4))\nrc(\"axes\", grid=True)\n```\n\n## Problema físico\n\n\n\nDefinimos un SR con el origen en el orificio donde el hilo atravieza el plano, la coordenada $\\hat{z}$ apuntando hacia abajo. Con esto sacamos, de la segunda ley de Newton para las particulas:\n\n$$\n\\begin{align}\n\\text{Masa 1)}\\quad&\\vec{F}_1 = m_1 \\vec{a}_1 \\\\\n&-T \\hat{r} = m_1 \\vec{a}_1 \\\\\n&-T \\hat{r} = m_1 \\left\\{ \\left(\\ddot{r} - r \\dot{\\theta}^2\\right) \\hat{r} + \\left(r\\ddot{\\theta} + 2\\dot{r}\\dot{\\theta}\\right)\\hat{\\theta} \\right\\} \\\\\n&\\begin{cases}\n\\hat{r})\\ - T = m_1\\left( \\ddot{r} - r\\, \\dot{\\theta}^2\\right)\\\\\n\\hat{\\theta})\\ 0 = m_1 \\left(r \\ddot{\\theta} + 2 \\dot{r}\\dot{\\theta}\\right)\\\\\n\\end{cases}\\\\\n\\\\\n\\text{Masa 2)}\\quad&\\vec{F}_2 = m_2 \\vec{a}_2 \\\\\n&-T \\hat{z} + m_2 g \\hat{z} = m_2 \\ddot{z} \\hat{z} \\\\\n\\implies & \\boxed{T = m_2 \\left( g - \\ddot{z} \\right)}\\\\\n\\end{align}\n$$\n\nAhora reemplazando este resultado para la tension (que es igual en ambas expresiones) y entendiendo que $\\ddot{z} = -\\ddot{r}$ pues la soga es ideal y de largo constante, podemos rescribir las ecuaciones obtenidas para la masa 1 como:\n\n$$\n\\begin{cases}\n\\hat{r})\\quad - m_2 \\left( g + \\ddot{r} \\right) = m_1\\left( \\ddot{r} - r\\, \\dot{\\theta}^2\\right)\\\\\n\\\\\n\\hat{\\theta})\\quad 0 = m_1 \\left(r \\ddot{\\theta} + 2 \\dot{r}\\dot{\\theta}\\right)\n\\end{cases}\n\\implies\n\\begin{cases}\n\\hat{r})\\quad \\ddot{r} = \\dfrac{- m_2 g + m_1 r \\dot{\\theta}^2}{m_1 + m_2}\\\\\n\\\\\n\\hat{\\theta})\\quad \\ddot{\\theta} = -2 \\dfrac{\\dot{r}\\dot{\\theta}}{r}\\\\\n\\end{cases}\n$$\n\n\nLa gracia de estos métodos es lograr encontrar una expresión de la forma $y'(x) = f(x,t)$ donde x será la solución buscada, aca como estamos en un sistema de segundo orden en dos variables diferentes ($r$ y $\\theta$) sabemos que nuestra solución va a tener que involucrar 4 componentes. Es como en el oscilador armónico, que uno tiene que definir posicion y velocidad inicial para poder conocer el sistema, solo que aca tenemos dos para $r$ y dos para $\\theta$.\n\nSe puede ver entonces que vamos a necesitar una solucion del tipo:\n$$\\mathbf{X} = \\begin{pmatrix} r \\\\ \\dot{r}\\\\ \\theta \\\\ \\dot{\\theta} \\end{pmatrix} $$\nY entonces\n$$\n\\dot{\\mathbf{X}} = \n\\begin{pmatrix} \\dot{r} \\\\ \\ddot{r}\\\\ \\dot{\\theta} \\\\ \\ddot{\\theta} \\end{pmatrix} =\n\\begin{pmatrix} \\dot{r} \\\\ \\dfrac{-m_2 g + m_1 r \\dot{\\theta}^2}{m_1 + m_2} \\\\ \\dot{\\theta} \\\\ -2 \\dfrac{\\dot{r}\\dot{\\theta}}{r} \\end{pmatrix} =\n\\mathbf{f}(\\mathbf{X}, t)\n$$\n\n---\n\nSi alguno quiere, tambien se puede escribir la evolucion del sistema de una forma piola, que no es otra cosa que una querida expansión de Taylor a orden lineal.\n\n$$\n\\begin{align}\n r(t+dt) &= r(t) + \\dot{r}(t)\\cdot dt \\\\\n \\dot{r}(t+dt) &= \\dot{r}(t) + \\ddot{r}(t)\\cdot dt \\\\\n \\theta(t+dt) &= \\theta(t) + \\dot{\\theta}(t)\\cdot dt \\\\\n \\dot{\\theta}(t+dt) &= \\dot{\\theta}(t) + \\ddot{\\theta}(t)\\cdot dt\n\\end{align}\n\\implies\n\\begin{pmatrix}\n r\\\\\n \\dot{r}\\\\\n \\theta\\\\\n \\ddot{\\theta}\n\\end{pmatrix}(t + dt) = \n\\begin{pmatrix}\n r\\\\\n \\dot{r}\\\\\n \\theta\\\\\n \\ddot{\\theta}\n\\end{pmatrix}(t) + \n\\begin{pmatrix}\n \\dot{r}\\\\\n \\ddot{r}\\\\\n \\dot{\\theta}\\\\\n \\ddot{\\theta}\n\\end{pmatrix}(t) \\cdot dt\n$$\n\nAca tenemos que recordar que la compu no puede hacer cosas continuas, porque son infinitas cuentas, entones si o si hay que discretizar el tiempo y el paso temporal!\n\n$$\n\\begin{pmatrix}\nr\\\\\n\\dot{r}\\\\\n\\theta\\\\\n\\ddot{\\theta}\n\\end{pmatrix}_{i+1} = \n\\begin{pmatrix}\nr\\\\\n\\dot{r}\\\\\n\\theta\\\\\n\\ddot{\\theta}\n\\end{pmatrix}_i + \n\\begin{pmatrix}\n\\dot{r}\\\\\n\\ddot{r}\\\\\n\\dot{\\theta}\\\\\n\\ddot{\\theta}\n\\end{pmatrix}_i \\cdot dt\n$$\n\nSi entonces decido llamar a este vector columna $\\mathbf{X}$, el sistema queda escrito como:\n\n$$\n\\mathbf{X}_{i+1} = \\mathbf{X}_i + \\dot{\\mathbf{X}}_i\\ dt\n$$\n\nDonde sale denuevo que $\\dot{\\mathbf{X}}$ es lo que está escrito arriba.\n\nEs decir que para encontrar cualquier valor, solo hace falta saber el vector anterior y la derivada, pero las derivadas ya las tenemos (es todo el trabajo que hicimos de fisica antes)!!\n\n---\n---\n\n\nDe cualquier forma que lo piensen, ojala hayan entendido que entonces con tener las condiciones iniciales y las ecuaciones diferenciales ya podemos resolver (tambien llamado *integrar*) el sistema.\n\n\n```python\n# Constantes del problema:\nM1 = 3\nM2 = 3\ng = 9.81\n\n# Condiciones iniciales del problema:\nr0 = 2\nr_punto0 = 0\ntita0 = 0\ntita_punto0 = 1\n\nC1 = (M2*g)/(M1+M2) # Defino constantes utiles\nC2 = (M1)/(M1+M2)\ncond_iniciales = [r0, r_punto0, tita0, tita_punto0]\n\ndef derivada(X, t, c1, c2): # esto sería la f del caso { x' = f(x,t) }\n r, r_punto, tita, tita_punto = X\n deriv = [0, 0, 0, 0] # es como el vector columna de arriba pero en filado\n \n deriv[0] = r_punto # derivada de r\n deriv[1] = -c1 + c2*r*(tita_punto)**2 # r dos puntos\n deriv[2] = tita_punto # derivada de tita\n deriv[3] = -2*r_punto*tita_punto/r\n return deriv\n\n\ndef resuelvo_sistema(m1, m2, tmax = 20):\n t0 = 0\n c1 = (m2*g)/(m1+m2) # Defino constantes utiles\n c2 = (m1)/(m1+m2)\n t = np.arange(t0, tmax, 0.001)\n \n # aca podemos definirnos nuestro propio algoritmo de integracion\n # o bien usar el que viene a armado de scipy. \n # Ojo que no es perfecto eh, a veces es mejor escribirlo uno\n out = odeint(derivada, cond_iniciales, t, args = (c1, c2,))\n\n return [t, out.T]\n\nt, (r, rp, tita, titap) = resuelvo_sistema(M1, M2, tmax=10)\n\nplt.figure()\nplt.plot(t, r/r0, 'r')\nplt.ylabel(r\"$r / r_0$\")\nplt.xlabel(r\"tiempo\")\n# plt.savefig(\"directorio/r_vs_t.pdf\", dpi=300)\n\nplt.figure()\nplt.plot(t, tita-tita0, 'b')\nplt.ylabel(r\"$\\theta - \\theta_0$\")\nplt.xlabel(r\"tiempo\")\n# plt.savefig(\"directorio/tita_vs_t.pdf\", dpi=300)\n\n\nplt.figure()\nplt.plot(r*np.cos(tita-tita0)/r0, r*np.sin(tita-tita0)/r0, 'g')\nplt.ylabel(r\"$r/r_0\\ \\sin\\left(\\theta - \\theta_0\\right)$\")\nplt.xlabel(r\"$r/r_0\\ \\cos\\left(\\theta - \\theta_0\\right)$\")\n# plt.savefig(\"directorio/trayectoria.pdf\", dpi=300)\n```\n\nTodo muy lindo!!\n\nCómo podemos verificar si esto está andando ok igual? Porque hasta acá solo sabemos que dio razonable, pero el ojímetro no es una medida cuantitativa.\n\nUna opción para ver que el algoritmo ande bien (y que no hay errores numéricos, y que elegimos un integrador apropiado **ojo con esto eh... te estoy mirando a vos, Runge-Kutta**), es ver si se conserva la energía.\n\nLes recuerdo que la energía cinética del sistema es $K = \\frac{1}{2} m_1 \\left|\\vec{v}_1 \\right|^2 + \\frac{1}{2} m_2 \\left|\\vec{v}_2 \\right|^2$, cuidado con cómo se escribe cada velocidad, y que la energía potencial del sistema únicamente depende de la altura de la pelotita colgante.\nHace falta conocer la longitud $L$ de la cuerda para ver si se conserva la energía mecánica total? (Spoiler: No. Pero piensen por qué)\n\nLes queda como ejercicio a ustedes verificar eso, y también pueden experimentar con distintos metodos de integración a ver qué pasa con cada uno, abajo les dejamos una ayudita para que prueben.\n\n\n```python\nfrom scipy.integrate import solve_ivp\n\ndef resuelvo_sistema(m1, m2, tmax = 20, metodo='RK45'):\n t0 = 0\n c1 = (m2*g)/(m1+m2) # Defino constantes utiles\n c2 = (m1)/(m1+m2)\n t = np.arange(t0, tmax, 0.001)\n \n # acá hago uso de las lambda functions, solamente para usar \n # la misma funcion que definimos antes. Pero como ahora\n # voy a usar otra funcion de integracion (no odeint)\n # que pide otra forma de definir la funcion, en vez de pedir\n # f(x,t) esta te pide f(t, x), entonces nada, hay que dar vuelta\n # parametros y nada mas...\n \n deriv_bis = lambda t, x: derivada(x, t, c1, c2)\n out = solve_ivp(fun=deriv_bis, t_span=(t0, tmax), y0=cond_iniciales,\\\n method=metodo, t_eval=t)\n\n return out\n\n# Aca armo dos arrays con los metodos posibles y otro con colores\nall_metodos = ['RK45', 'RK23', 'Radau', 'BDF', 'LSODA']\nall_colores = ['r', 'b', 'm', 'g', 'c']\n\n# Aca les dejo la forma piola de loopear sobre dos arrays a la par\nfor met, col in zip(all_metodos, all_colores):\n result = resuelvo_sistema(M1, M2, tmax=30, metodo=met)\n t = result.t\n r, rp, tita, titap = result.y\n plt.plot(t, r/r0, col, label=met)\n \nplt.xlabel(\"tiempo\")\nplt.ylabel(r\"$r / r_0$\")\nplt.legend(loc=3)\n```\n\nVen cómo los distintos métodos van modificando más y más la curva de $r(t)$ a medida que van pasando los pasos de integración. Tarea para ustedes es correr el mismo código con la conservación de energía.\n\nCuál es mejor, por qué y cómo saberlo son preguntas que deberán hacerse e investigar si en algún momento trabajan con esto.\n\nPor ejemplo, pueden buscar en Wikipedia \"Symplectic Integrator\" y ver qué onda.\n\n### Les dejamos también abajo la simulación de la trayectoria de la pelotita\n\n\n```python\nfrom matplotlib import animation\n%matplotlib notebook\n\nresult = resuelvo_sistema(M1, M2, tmax=30, metodo='Radau')\nt = result.t\nr, rp, tita, titap = result.y\n\nfig, ax = plt.subplots()\nax.set_xlim([-1, 1])\nax.set_ylim([-1, 1])\nax.plot(r*np.cos(tita)/r0, r*np.sin(tita)/r0, 'm', lw=0.2)\nline, = ax.plot([], [], 'ko', ms=5)\n\nN_SKIP = 50\nN_FRAMES = int(len(r)/N_SKIP)\n\ndef animate(frame_no):\n i = frame_no*N_SKIP\n r_i = r[i]/r0\n tita_i = tita[i]\n line.set_data(r_i*np.cos(tita_i), r_i*np.sin(tita_i))\n return line,\n \nanim = animation.FuncAnimation(fig, animate, frames=N_FRAMES,\n interval=50, blit=False)\n```\n\n\n \n\n\n\n\n\n\nRecuerden que esta animación no va a parar eh, sabemos que verla te deja en una especie de trance místico, pero recuerden pararla cuando haya transcurrido suficiente tiempo\n\n# Animación Interactiva\n\nUsando `ipywidgets` podemos agregar sliders a la animación, para modificar el valor de las masitas\n\n\n```python\nfrom ipywidgets import interactive, interact, FloatProgress\nfrom IPython.display import clear_output, display\n%matplotlib inline\n\n@interact(m1=(0,5,0.5), m2=(0,5,0.5), tmax=(0.01,20,0.5)) #Permite cambiar el parámetro de la ecuación\ndef resuelvo_sistema(m1, m2, tmax = 20):\n t0 = 0\n c1 = (m2*g)/(m1+m2) # Defino constantes utiles\n c2 = (m1)/(m1+m2)\n t = np.arange(t0, tmax, 0.05)\n# out = odeint(derivada, cond_iniciales, t, args = (c1, c2,))\n r, rp, tita, titap = odeint(derivada, cond_iniciales, t, args=(c1, c2,)).T\n plt.xlim((-1,1))\n plt.ylim((-1,1))\n plt.plot(r*np.cos(tita)/r0, r*np.sin(tita)/r0,'b-')\n \n# plt.xlabel(\"tiempo\")\n# plt.ylabel(r\"$r / r_0$\")\n# plt.show()\n\n```\n\n\n interactive(children=(FloatSlider(value=2.0, description='m1', max=5.0, step=0.5), FloatSlider(value=2.0, desc…\n\n", "meta": {"hexsha": "4a483923b75398e649865f22009835c59b8ec171", "size": 248551, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "python/Extras/Fisica1/simulacion.ipynb", "max_stars_repo_name": "LTGiardino/talleresfifabsas", "max_stars_repo_head_hexsha": "a711b4425b0811478f21e6c405eeb4a52e889844", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17, "max_stars_repo_stars_event_min_datetime": "2015-10-23T17:14:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-31T02:18:29.000Z", "max_issues_repo_path": "python/Extras/Fisica1/simulacion.ipynb", "max_issues_repo_name": "LTGiardino/talleresfifabsas", "max_issues_repo_head_hexsha": "a711b4425b0811478f21e6c405eeb4a52e889844", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2016-04-03T23:39:11.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-03T02:09:02.000Z", "max_forks_repo_path": "python/Extras/Fisica1/simulacion.ipynb", "max_forks_repo_name": "LTGiardino/talleresfifabsas", "max_forks_repo_head_hexsha": "a711b4425b0811478f21e6c405eeb4a52e889844", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 29, "max_forks_repo_forks_event_min_datetime": "2015-10-16T04:16:01.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-18T16:55:48.000Z", "avg_line_length": 193.1243201243, "max_line_length": 83416, "alphanum_fraction": 0.8675201468, "converted": true, "num_tokens": 3803, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109798251321, "lm_q2_score": 0.9005297854505006, "lm_q1q2_score": 0.8558733957517263}} {"text": "# sympy [1] - Symbolic Python\n\nhttps://docs.sympy.org/latest/index.html\n\nhttps://github.com/sympy/sympy/wiki\n\n1. Meurer A, Smith CP, Paprocki M, Čertík O, Kirpichev SB, Rocklin M, Kumar A, Ivanov S, Moore JK, Singh S, Rathnayake T, Vig S, Granger BE, Muller RP, Bonazzi F, Gupta H, Vats S, Johansson F, Pedregosa F, Curry MJ, Terrel AR, Roučka Š, Saboo A, Fernando I, Kulal S, Cimrman R, Scopatz A. (2017) sympy: symbolic computing in Python. PeerJ Computer Science 3:e103 https://doi.org/10.7717/peerj-cs.103\n\n\n\n\n```python\nimport sympy\n```\n\n## Number representation\n\n\n```python\nsympy.sqrt(7)\n```\n\n\n```python\nsympy.Float(9/4)\n```\n\n\n```python\nsympy.Integer(9/4) ## drops the fractional part\n```\n\n\n```python\nsympy.Rational(9/4)\n```\n\n## Defining variables (i.e. symbols)\n\n\n```python\nx, y, z, t = sympy.symbols('x y z t')\n```\n\n## Expresssions\n\n- can type them directly into the cell:\n\n\n```python\nx**2+3*x+2\n```\n\n\n```python\ntype(x**2+3*x+2)\n```\n\n- alternatively, `sympify` will converts a string to a sympy function\n\n\n```python\nfunction_string = 'x**2+3*x+2'\nfunction_string\n```\n\n\n```python\n## Equivalent statement\n# function_sympy = sympy.sympify('x**2+3*x+2')\n\nfunction_sympy = sympy.sympify(function_string, evaluate=False)\nfunction_sympy\n```\n\nLet's prove that it took a string and converted it to a sympy object:\n\n\n```python\nprint(type(function_string))\nprint(type(function_sympy))\n```\n\n\n```python\nsympy.sympify(\"2/3 + 1/6\", evaluate=False)\n```\n\n`simpify` also attempts to simplify a provided forumla:\n\n\n```python\nsympy.sympify(\"2/3 + 1/6\", evaluate=True)\n```\n\nAlso does so for equations with variables.\n\n\n```python\nsympy.sympify(\"(1 + x)*(2 + x**2)*(2 + x**2)*(2 + x**2)\", evaluate=False)\n```\n\nLet' go back and see what `Rational` would do with $\\frac{2}{3} + \\frac{1}{6}$:\n\n\n```python\nsympy.Rational(2/3 + 1/6)\n```\n\nThis looks complicated, but it is just the manner tha sympy stores the resulting number:\n\n\n```python\nprint(3752999689475413/4503599627370496)\nprint(5/6)\n```\n\n#### Evaluate an expression or function\n\nConvert a sympy expressions to a float\n\nThe following two are equivalent:\n- `evalf()`\n- `sympy.N()`\n\n\n```python\ntest_func = sympy.sqrt(7)*sympy.pi\ntest_func\n```\n\n\n```python\ntest_func.evalf()\n```\n\n\n```python\nsympy.N(test_func)\n```\n\nReturning to our fraction above, we could get float value via:\n\n\n```python\nsympy.sympify(\"2/3 + 1/6\").evalf()\n```\n\n## Polynomials\n\nsympy can also create and work with polynomials.\n\nRecall: 2nd Degree Polynomial (Three coefficients: [M, N, O] --> $Mx^2 + Nx + O$)\n\nOne can do this using two approaches, which result in two different object types:\n1. A sympy \"expression\"\n1. A sympy Poly\n\n##### Approach 1\n Using a sympy \"expresssion\"\n\n\n```python\npolynomial_simple_expr = -4*x**2 + 1*x -2\npolynomial_simple_expr\n```\n\n\n```python\ntype(polynomial_simple_expr)\n```\n\n##### Approach 2\nUsing sympy's `Poly` function (https://docs.sympy.org/latest/modules/polys/reference.html)\n\n - Efficiently transform an expression into a polynomial\n\n\n```python\npolynomial_simple_poly = sympy.Poly(-4*x**2 + 1*x -2)\npolynomial_simple_poly\n```\n\n\n```python\ntype(polynomial_simple_poly)\n```\n\nOne can also create a polynomial by providing a list of **ALL** of the coefficients (including those that might be zero).\n\n\n```python\npolynomial_simple_poly = sympy.Poly.from_list([-4, 1, -2], x)\npolynomial_simple_poly\n```\n\nPrint the degree:\n\n- of a sympy expression\n\n\n```python\nsympy.degree(polynomial_simple_expr)\n```\n\n- of a sympy `Poly`\n\n\n```python\nsympy.degree(polynomial_simple_poly)\n```\n\n#### Evaluating Polynomials\n\n- Use `subs` to substitute values (https://docs.sympy.org/latest/tutorial/basic_operations.html)\n- `subs` works for both\n - expressions (e.g. sympy.core.add.Add, sympy.core.power.Pow)\n - `Poly` (i.e. sympy.polys.polytools.Poly)\n\n##### Evaluating a Single Variable Polynomial\n\n- expression\n\n\n```python\npolynomial_simple_expr.subs(x, 2)\n```\n\n- Poly\n\n\n```python\npolynomial_simple_poly.subs(x, 2)\n```\n\n##### Evaluating a Multiple Variable Polynomial\n\n- Using `subs` pass a\n - list of tuples\n - dictionary \n\n\n```python\npolynomial_multi_expr = x**2 + x*y + 3\npolynomial_multi_expr\n```\n\n**Approach 1**: Substitute the two variables by providing a list:\n\n\n```python\npolynomial_multi_expr.subs([(x, 3), (y, 2)])\n```\n\n\n```python\ntype(polynomial_multi_expr.subs([(x, 3), (y, 2)]))\n```\n\n**Approach 2**: SSubstitute the two variables by providing a dictionary:\n\n\n```python\npolynomial_multi_expr.subs({x: 3, y: 2})\n```\n\nTo obtain a float, use `evalf` (https://docs.sympy.org/latest/modules/evalf.html)\n\nImportant: the variable values are passed as a dictionary (i.e. lists don't work as they did for `subs`).\n\n\n```python\npolynomial_multi_expr.evalf(subs = {x: 3, y: 2})\n```\n\n\n```python\ntype(polynomial_multi_expr.evalf(subs = {x: 3, y: 2}))\n```\n\n### Expanding a polynomial\n\nNotice: we are not specifying a Poly object.\n\n\n```python\npolynomial_expr = (-4*x**2 + 1*x - 2)**2\npolynomial_expr\n```\n\n\n```python\npolynomial_expr.expand()\n```\n\n\n```python\npolynomial_expr\n```\n\nsympy `Poly` will expand it automatically:\n\n\n```python\npolynomial_poly = sympy.Poly((-4*x**2 + 1*x - 2)**2)\npolynomial_poly\n```\n\n### Factor a polynomial\n\n\n```python\npolynomial_expr = (16*x**4 - 8*x**3 + 17*x**2 - 4*x + 4).factor()\npolynomial_expr\n```\n\n\n```python\ntype(polynomial_expr)\n```\n\nNotice this does not work for sympy Poly:\n\n\n```python\n# sympy.Poly((-4*x**2 + 1*x - 2)**2).fractor()\n\npolynomial_poly.factor()\n```\n\n### Math with Polynomials\n\n#### Multiply two polynomials together\n\nExpression\n\n\n```python\npolynomial_simple_expr\n```\n\n\n```python\npolynomial_simple_expr * polynomial_simple_expr\n```\n\nsympy `Poly`\n\n\n```python\npolynomial_simple_poly\n```\n\n\n```python\npolynomial_simple_poly * polynomial_simple_poly\n```\n\nRecall: `Poly` automatically expands the polynomials.\n\n#### Calculus\n\n#### Taking Derivatives\n -`diff()` (https://docs.sympy.org/latest/modules/core.html?highlight=diff#sympy.core.function.diff)\n\n\n**First derivative** (noted as $f'(x)$ or as $\\frac{df}{dx}$, which is the same as $\\frac{d}{dx}f$)\n\nTaking the first derivative of a function (e.g. f(x)) tells us:\n1. if the function at a given point (ie. x) is increasing or decreasing (i.e. the **direction of change**), and\n1. by how much it is increasing or decreasing (i.e. **a rate**)\n\n##### sympy Expressions\n\n\n```python\npolynomial_expr = 2 * x**3 + 1\npolynomial_expr\n```\n\n**Approach 1**\n\n\n```python\nsympy.diff(polynomial_expr, x, 1)\n```\n\n**Approach 2**\n\n\n```python\npolynomial_expr.diff(x)\n```\n\n\n```python\npolynomial_expr.diff(x, 1)\n```\n\n##### sympy `Poly`\n\n\n```python\npolynomial_poly = sympy.poly(2 * x**3 + 1)\npolynomial_poly\n```\n\n**Approach 1**\n\n\n```python\npolynomial_poly.diff(x)\n```\n\n**Approach 2**\n\n\n```python\nsympy.diff(polynomial_poly, x)\n```\n\n**Note**: that `sympy.diff(polynomial_poly, x, 1)` or `polynomial_poly.diff(x, 1)` does not work for a sympy poly object, as it did using the sympy expression above.\n\nTherefore, it is generally better to have your **functions as sympy expressions** if you plan to preforms some **calculus** on them.\n\n**Second derivative** (noted as $f''(x)$ or as $\\frac{d^2f}{dx}$)\n\nTaking the second derivative of a function (e.g. f(x)) tells us:\n1. the **shape** of the curve at a specified point (i.e. x)\n - **postive** value: the curve is **convex**\n - **negative** value: the curve is **concave**\n\n\n```python\npolynomial_expr.diff(x, x)\n```\n\n\n```python\npolynomial_expr.diff(x, 2)\n```\n\n\n```python\nsympy.diff(polynomial_expr, x, 2)\n```\n\n##### Derivative of Multiple Variable Functions\n\n\n```python\npolynomial_multi_expr\n```\n\n1st derivative with respect to x:\n\n\n```python\nsympy.diff(polynomial_multi_expr, x, 1)\n```\n\n1st derivative with respect to y:\n\n\n```python\nsympy.diff(polynomial_multi_expr, y, 1)\n```\n\n2nd-order mixed derivatives:\n\nDerivative with respect to x **and then** to y:\n- i.e. $\\frac{d}{dy}(\\frac{df}{dx})$\n\n$f(x) = x^2 + xy + 3$\n\n$f'(x) = \\frac{df}{dx} = \\frac{d}{dx}(x^2 + xy + 3) = 2x + y$\n\n$\\frac{df'(x)}{dy} = \\frac{d}{dy}(2x + y) = 1$\n\n\n```python\nsympy.diff(polynomial_multi_expr, x, y)\n```\n\n### Integration\n\nThe integral of a function (e.g. f(x)) tells us:\n\n1. the area that resides under the function (e.g. the amount of water in a curve shaped pool).\n\n#### Indefinite integral (i.e. without limits/bounds)\n\n$\\int (2x^3+1) \\,dx = \\frac{x^4}{2} + 1x$\n\n(recall: if you take the derivative of the result, you will get the input)\n\n**Approaches 1**\n- sympy expression\n- sympy Poly\n\n\n```python\npolynomial_expr\n```\n\n\n```python\nsympy.integrate(polynomial_expr, x)\n```\n\n\n```python\nsympy.integrate(polynomial_poly, x)\n```\n\n**Approaches 2**\n- sympy expression\n- sympy Poly\n\n\n```python\npolynomial_expr.integrate(x)\n```\n\n\n```python\npolynomial_poly.integrate(x)\n```\n\n#### Definate integral (i.e. evaluated between two boundary conditions)\n\n$\\int_1^2 (2x^3+1) \\,dx = \\frac{x^4}{2} + 1x$\n\nNotice: the tuple being passed (i.e. `(x, 1, 2)`)\n\n\n```python\nsympy.integrate(polynomial_expr, (x, 1, 2))\n```\n\n\n```python\npolynomial_expr.integrate((x, 1, 2))\n```\n\nThis is where I personally find some of the logic/consistency breaking down in sympy. It seems like `sympy.integrate` only works with expresssions.\n\n\n```python\nsympy.integrate(polynomial_poly, (x, 1, 2))\n```\n\n## Visualizing functions (i.e. plotting)\n\n- backend: matplotlib\n\nPlot a function (i.e. f(x)) by its single variable\n\n(doing something like f(x,y) would require a 2D plot)\n\n\n```python\nsympy.plot(x**2 + 20)\n```\n\nChange the x-axis range:\n\n\n```python\nsympy.plot(x**2 + 20, (x, -2, 2))\n```\n\n\n```python\nfunction = x**4\nplot_func = sympy.plot(function)\nplot_der1 = sympy.plot(sympy.diff(function, x, 1))\nplot_der2 = sympy.plot(sympy.diff(function, x, 2))\n```\n\n## Solving equations\n\n- Finding the \"roots\" of the equation (i.e. what the variable values are that sets the equation to zero).\n\nEquation:\n\n$x^2 = 4$\n\nRearrange:\n\n$x^2 -4 = 0$\n\nSolve:\n\nSolutions are\n1. x = 2\n1. x = -2\n\n\n```python\nsolutions = sympy.solve(x**2 - 4)\nsolutions\n```\n\n\n```python\nsolutions[0]\n```\n\n### Misc sympy functions\n\nLambdify: https://docs.sympy.org/latest/modules/utilities/lambdify.html\n - transforms a sympy expression to a lambda function that can be used to evaluate (solve) equations\n\n- https://docs.python.org/3/reference/expressions.html#lambda\n\nExamples of lambda functions\n- `lambda x: x+x`\n- `lambda a, b: a+b`\n\nAnd you can directly evaluate a lambda function:\n\n\n```python\n(lambda x: x*2)(12)\n```\n\n\n```python\nfunction = x**2\n\nderivative_function = function.diff(x)\nderivative_function\n```\n\n\n```python\nf1 = sympy.lambdify(x, derivative_function)\n```\n\n\n```python\nf1(3)\n```\n\n\n```python\nmulti_var_func = (x**2 + y**3 + z**4)\n```\n\nList the variables\n\n\n```python\nmulti_var_func.free_symbols\n```\n\nTo evaluate the function for when x=1, y=2 and z=3 and return an regular Python `int` type:\n\n\n```python\nf = sympy.lambdify([x, y, z], multi_var_func)\n\nf(1, 2, 3)\n```\n\n\n```python\ntype(f(1, 2, 3))\n```\n\nYou can also evalute the function to return a `sympy.core.numbers.Integer` type:\n\n\n```python\nmulti_var_func.subs([(x, 1), (y, 2), (z, 3)])\n```\n\n\n```python\ntype(multi_var_func.subs([(x, 1), (y, 2), (z, 3)]))\n```\n\nTo obtain a `sympy.core.numbers.Float`:\n\n\n```python\nmulti_var_func.evalf(subs = {x: 1, y: 2, z: 3})\n```\n\n\n```python\ntype(multi_var_func.evalf(subs = {x: 1, y: 2, z: 3}))\n```\n\n## Unit Conversions with sympy\n\n\n```python\nfrom sympy.physics.units import convert_to\nfrom sympy.physics.units import speed_of_light\nfrom sympy.physics.units import kilometer, meter, centimeter, millimeter \nfrom sympy.physics.units import second, minute, hour\n```\n\n\n```python\nspeed_of_light\n```\n\n\n```python\nspeed_of_light.evalf()\n```\n\nTo obtain a value, you must specify the desired units:\n\n\n```python\nconvert_to(speed_of_light, [meter, minute])\n```\n\n\n```python\nconvert_to(speed_of_light, [millimeter, hour])\n```\n\n\n```python\n#help(sympy.physics.units)\n```\n\n#### Constants built into sympy\n1. A: ampere\n1. Bq: becquerel\n1. C: coulomb\n1. D: dioptre\n1. F: farad\n1. G: gravitational_constant\n1. Gy: gray\n1. H: henry\n1. Hz: hertz\n1. J: joule\n1. K: kelvin\n1. N: newton\n1. Pa: pascal\n1. R: molar_gas_constant\n1. S: siemens\n1. T: tesla\n1. V: volt\n1. W: watt\n1. Wb: weber\n1. Z0: vacuum_impedance\n1. __all__: ['Dimension', 'DimensionSystem', 'UnitSystem', 'convert_to',...\n1. acceleration: Dimension(acceleration)\n1. acceleration_due_to_gravity: acceleration_due_to_gravity\n1. action: Dimension(action, A)\n1. amount: Dimension(amount_of_substance)\n1. amount_of_substance: Dimension(amount_of_substance)\n1. ampere: ampere\n1. amperes: ampere\n1. amu: atomic_mass_constant\n1. amus: atomic_mass_constant\n1. angular_mil: angular_mil\n1. angular_mils: angular_mil\n1. anomalistic_year: anomalistic_year\n1. anomalistic_years: anomalistic_year\n1. astronomical_unit: astronomical_unit\n1. astronomical_units: astronomical_unit\n1. atm: atmosphere\n1. atmosphere: atmosphere\n1. atmospheres: atmosphere\n1. atomic_mass_constant: atomic_mass_constant\n1. atomic_mass_unit: atomic_mass_constant\n1. atto: Prefix('atto', 'a', -18)\n1. au: astronomical_unit\n1. avogadro: avogadro_constant\n1. avogadro_constant: avogadro_constant\n1. avogadro_number: avogadro_number\n1. bar: bar\n1. bars: bar\n1. becquerel: becquerel\n1. bit: bit\n1. bits: bit\n1. boltzmann: boltzmann_constant\n1. boltzmann_constant: boltzmann_constant\n1. byte: byte\n1. c: speed_of_light\n1. candela: candela\n1. candelas: candela\n1. capacitance: Dimension(capacitance)\n1. cd: candela\n1. centi: Prefix('centi', 'c', -2)\n1. centiliter: centiliter\n1. centiliters: centiliter\n1. centimeter: centimeter\n1. centimeters: centimeter\n1. charge: Dimension(charge, Q)\n1. cl: centiliter\n1. cm: centimeter\n1. common_year: common_year\n1. common_years: common_year\n1. conductance: Dimension(conductance, G)\n1. coulomb: coulomb\n1. coulomb_constant: coulomb_constant\n1. coulombs: coulomb\n1. current: Dimension(current, I)\n1. dHg0: 13.5951\n1. day: day\n1. days: day\n1. deca: Prefix('deca', 'da', 1)\n1. deci: Prefix('deci', 'd', -1)\n1. deciliter: deciliter\n1. deciliters: deciliter\n1. decimeter: decimeter\n1. decimeters: decimeter\n1. deg: degree\n1. degree: degree\n1. degrees: degree\n1. dioptre: dioptre\n1. dl: deciliter\n1. dm: decimeter\n1. draconic_year: draconic_year\n1. draconic_years: draconic_year\n1. e0: vacuum_permittivity\n1. eV: electronvolt\n1. electric_constant: vacuum_permittivity\n1. electric_force_constant: coulomb_constant\n1. electronvolt: electronvolt\n1. electronvolts: electronvolt\n1. elementary_charge: elementary_charge\n1. energy: Dimension(energy, E)\n1. exa: Prefix('exa', 'E', 18)\n1. exbi: Prefix('exbi', 'Y', 60, 2)\n1. exbibyte: exbibyte\n1. exbibytes: exbibyte\n1. farad: farad\n1. faraday_constant: faraday_constant\n1. farads: farad\n1. feet: foot\n1. femto: Prefix('femto', 'f', -15)\n1. foot: foot\n1. force: Dimension(force, F)\n1. frequency: Dimension(frequency, f)\n1. ft: foot\n1. full_moon_cycle: full_moon_cycle\n1. full_moon_cycles: full_moon_cycle\n1. g: gram\n1. gaussian_year: gaussian_year\n1. gaussian_years: gaussian_year\n1. gee: acceleration_due_to_gravity\n1. gees: acceleration_due_to_gravity\n1. gibi: Prefix('gibi', 'Y', 30, 2)\n1. gibibyte: gibibyte\n1. gibibytes: gibibyte\n1. giga: Prefix('giga', 'G', 9)\n1. gram: gram\n1. grams: gram\n1. gravitational_constant: gravitational_constant\n1. gray: gray\n1. h: hour\n1. hbar: hbar\n1. hecto: Prefix('hecto', 'h', 2)\n1. henry: henry\n1. henrys: henry\n1. hertz: hertz\n1. hour: hour\n1. hours: hour\n1. hz: hertz\n1. impedance: Dimension(impedance, Z)\n1. inch: inch\n1. inches: inch\n1. inductance: Dimension(inductance)\n1. josephson_constant: josephson_constant\n1. joule: joule\n1. joules: joule\n1. julian_year: julian_year\n1. julian_years: julian_year\n1. kPa: kilopascal\n1. kat: katal\n1. katal: katal\n1. kelvin: kelvin\n1. kelvins: kelvin\n1. kg: kilogram\n1. kibi: Prefix('kibi', 'Y', 10, 2)\n1. kibibyte: kibibyte\n1. kibibytes: kibibyte\n1. kilo: Prefix('kilo', 'k', 3)\n1. kilogram: kilogram\n1. kilograms: kilogram\n1. kilometer: kilometer\n1. kilometers: kilometer\n1. km: kilometer\n1. l: liter\n1. length: Dimension(length, L)\n1. lightyear: lightyear\n1. lightyears: lightyear\n1. liter: liter\n1. liters: liter\n1. luminosity: Dimension(luminous_intensity)\n1. luminous_intensity: Dimension(luminous_intensity)\n1. lux: lux\n1. lx: lux\n1. ly: lightyear\n1. m: meter\n1. magnetic_constant: magnetic_constant\n1. magnetic_density: Dimension(magnetic_density, B)\n1. magnetic_flux: Dimension(magnetic_flux)\n1. magnetic_flux_density: Dimension(magnetic_density, B)\n1. mass: Dimension(mass, M)\n1. mebi: Prefix('mebi', 'Y', 20, 2)\n1. mebibyte: mebibyte\n1. mebibytes: mebibyte\n1. mega: Prefix('mega', 'M', 6)\n1. meter: meter\n1. meters: meter\n1. mg: milligram\n1. mho: siemens\n1. mhos: siemens\n1. mi: mile\n1. micro: Prefix('micro', 'mu', -6)\n1. microgram: microgram\n1. micrograms: microgram\n1. micrometer: micrometer\n1. micrometers: micrometer\n1. micron: micrometer\n1. microns: micrometer\n1. microsecond: microsecond\n1. microseconds: microsecond\n1. mil: angular_mil\n1. mile: mile\n1. miles: mile\n1. milli: Prefix('milli', 'm', -3)\n1. milli_mass_unit: milli_mass_unit\n1. milligram: milligram\n1. milligrams: milligram\n1. milliliter: milliliter\n1. milliliters: milliliter\n1. millimeter: millimeter\n1. millimeters: millimeter\n1. millisecond: millisecond\n1. milliseconds: millisecond\n1. minute: minute\n1. minutes: minute\n1. ml: milliliter\n1. mm: millimeter\n1. mmHg: mmHg\n1. mmu: milli_mass_unit\n1. mmus: milli_mass_unit\n1. mol: mole\n1. molar_gas_constant: molar_gas_constant\n1. mole: mole\n1. moles: mole\n1. momentum: Dimension(momentum)\n1. ms: millisecond\n1. nano: Prefix('nano', 'n', -9)\n1. nanometer: nanometer\n1. nanometers: nanometer\n1. nanosecond: nanosecond\n1. nanoseconds: nanosecond\n1. nautical_mile: nautical_mile\n1. nautical_miles: nautical_mile\n1. newton: newton\n1. newtons: newton\n1. nm: nanometer\n1. nmi: nautical_mile\n1. ns: nanosecond\n1. ohm: ohm\n1. ohms: ohm\n1. optical_power: dioptre\n1. pa: pascal\n1. pascal: pascal\n1. pascals: pascal\n1. pebi: Prefix('pebi', 'Y', 50, 2)\n1. pebibyte: pebibyte\n1. pebibytes: pebibyte\n1. percent: percent\n1. percents: percent\n1. permille: permille\n1. peta: Prefix('peta', 'P', 15)\n1. pico: Prefix('pico', 'p', -12)\n1. picometer: picometer\n1. picometers: picometer\n1. picosecond: picosecond\n1. picoseconds: picosecond\n1. planck: planck\n1. planck_acceleration: planck_acceleration\n1. planck_angular_frequency: planck_angular_frequency\n1. planck_area: planck_area\n1. planck_charge: planck_charge\n1. planck_current: planck_current\n1. planck_density: planck_density\n1. planck_energy: planck_energy\n1. planck_energy_density: planck_energy_density\n1. planck_force: planck_force\n1. planck_impedance: planck_impedance\n1. planck_intensity: planck_intensity\n1. planck_length: planck_length\n1. planck_mass: planck_mass\n1. planck_momentum: planck_momentum\n1. planck_power: planck_power\n1. planck_pressure: planck_pressure\n1. planck_temperature: planck_temperature\n1. planck_time: planck_time\n1. planck_voltage: planck_voltage\n1. planck_volume: planck_volume\n1. pm: picometer\n1. pound: pound\n1. pounds: pound\n1. power: Dimension(power)\n1. pressure: Dimension(pressure)\n1. ps: picosecond\n1. psi: psi\n1. quart: quart\n1. quarts: quart\n1. rad: radian\n1. radian: radian\n1. radians: radian\n1. s: second\n1. second: second\n1. seconds: second\n1. sidereal_year: sidereal_year\n1. sidereal_years: sidereal_year\n1. siemens: siemens\n1. speed: Dimension(velocity)\n1. speed_of_light: speed_of_light\n1. sr: steradian\n1. stefan: stefan_boltzmann_constant\n1. stefan_boltzmann_constant: stefan_boltzmann_constant\n1. steradian: steradian\n1. steradians: steradian\n1. tebi: Prefix('tebi', 'Y', 40, 2)\n1. tebibyte: tebibyte\n1. tebibytes: tebibyte\n1. temperature: Dimension(temperature, T)\n1. tera: Prefix('tera', 'T', 12)\n1. tesla: tesla\n1. teslas: tesla\n1. time: Dimension(time, T)\n1. torr: mmHg\n1. tropical_year: tropical_year\n1. tropical_years: tropical_year\n1. u0: magnetic_constant\n1. ug: microgram\n1. um: micrometer\n1. us: microsecond\n1. v: volt\n1. vacuum_impedance: vacuum_impedance\n1. vacuum_permeability: magnetic_constant\n1. vacuum_permittivity: vacuum_permittivity\n1. velocity: Dimension(velocity)\n1. volt: volt\n1. voltage: Dimension(voltage, U)\n1. volts: volt\n1. volume: Dimension(volume)\n1. von_klitzing_constant: von_klitzing_constant\n1. watt: watt\n1. watts: watt\n1. wb: weber\n1. weber: weber\n1. webers: weber\n1. yard: yard\n1. yards: yard\n1. yd: yard\n1. year: tropical_year\n1. years: tropical_year\n1. yocto: Prefix('yocto', 'y', -24)\n1. yotta: Prefix('yotta', 'Y', 24)\n1. zepto: Prefix('zepto', 'z', -21)\n1. zetta: Prefix('zetta', 'Z', 21)\n\n# Practicle Usage Example\n\nA particle is moving in space with a velocity that can be defined by the following function:\n\n$v(t) = t^2 - 2t - 8$\n\nwhere time `t` is in seconds and the velocity `v` is measured in $\\frac{\\text{meter}}{\\text{second}}$:\n\n1. Plot the function.\n1. At what time(s) is the particle at rest (i.e. $v(t) = 0$)? \n1. What is the acceleration of the particle at a time of 5.3 seconds into its trajectory? (Hint: acceleration is the first derivative of the velocity)\n\nOriginal source: https://www.georgebrown.ca/sites/default/files/2020-05/Applications%20of%20Derivatives.pdf\n\nFirst define what our sympy variable is:\n\n\n```python\nt = sympy.symbols('t')\nvelocity_function = t**2 - 2*t - 8\n```\n\n1. Plot the function\n\n\n```python\nplot_func = sympy.plot(velocity_function)\n```\n\n2. At what time(s) is the particle at rest (i.e. $v(t) = 0$)?\n\n- That means we need to solve the equation an find its **roots**.\n\nAs learned above, we do this using the `solve` function.\n\n\n```python\nsolutions = sympy.solve(velocity_function)\nsolutions\n```\n\nHowever, now it is time to **think** about the solutions. \n\nSince a negative time is not possible in our scenario, the answer to the question can only be 4 seconds.\n\n3. What is the acceleration of the particle at t=3 seconds?\n\n- Recall that acceleration is defined as the first derivative of the velecity with respect to time\n\n$a(t) = \\frac{d}{dt} v(t) = \\frac{d}{dt} (t^2 - 2t - 8)$\n\n\n```python\nfirst_derivative = velocity_function.diff(t, 1)\nfirst_derivative\n```\n\nNow evaluate the first derivative at a time of 5.3 seconds:\n\n\n```python\ntime = 5.3\n```\n\n\n```python\nacceleration = first_derivative.evalf(subs = {t: time})\nacceleration\n```\n\n\n```python\nprint(f'The acceleration of the particle at {time} s into its trajectory is '\n f' {acceleration:0.1f} m/s^2.')\n```\n\n---\nSide note about how the unit was obtained:\n\nDerivative can also be expressed mathematically in a different way (i.e. via Leibniz):\n\n$\\frac{d}{dx} f(x) = \\lim_{x \\to x_0} f(x) = \\lim_{x \\to x_0} \\frac{f(x) - f(x_0)}{x - x_0}$\n\nif `f(x)` has units of $\\frac{\\text{meter}}{\\text{second}}$\n\nand `x` has units of $\\text{second}$, then we have\n\n$\\lim_{x \\to x_0} \\frac{\\frac{\\text{meter}}{\\text{second}} - \\frac{\\text{meter}}{\\text{second}}}{\\text{second} - \\text{seconds}}$\n\n$ = \\frac{\\frac{\\text{meter}}{\\text{second}}}{\\text{second}} = \\frac{\\text{meter}}{\\text{second second}} = \\frac{\\text{meter}}{\\text{second}^2}$\n\n\n```python\n\n```\n", "meta": {"hexsha": "0bd64f89a9889e042eca6c561ae353e7e3b691e9", "size": 49918, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "sympy.ipynb", "max_stars_repo_name": "karlkirschner/2020_Scientific_Programming", "max_stars_repo_head_hexsha": "e7830468194eb2ef7824bc46f6d9ee112c652e35", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-03-30T12:24:57.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-30T13:34:27.000Z", "max_issues_repo_path": "sympy.ipynb", "max_issues_repo_name": "karlkirschner/2020_Scientific_Programming", "max_issues_repo_head_hexsha": "e7830468194eb2ef7824bc46f6d9ee112c652e35", "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": "sympy.ipynb", "max_forks_repo_name": "karlkirschner/2020_Scientific_Programming", "max_forks_repo_head_hexsha": "e7830468194eb2ef7824bc46f6d9ee112c652e35", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-04-18T10:23:47.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-01T10:38:21.000Z", "avg_line_length": 23.4027191749, "max_line_length": 601, "alphanum_fraction": 0.5354381185, "converted": true, "num_tokens": 7951, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896769778074, "lm_q2_score": 0.9294404072330196, "lm_q1q2_score": 0.8558191323462139}} {"text": "# 4.4.1 Fitting Logistic Regression Models\n\nLogistic regression models fit by maximum likelihood, the log-likelihood for N observations is (4.19):\n$$\nl(\\theta)=\\sum_{i=1}^N \\log p_{g_i}(x_i, \\theta),\n$$\n\nWe discuss in detail the two-class case, it is convenient to code the two-class $g_i$ via 0/1 response $y_i$. The log-likelihood can be written (4.20):\n$$\n\\begin{align}\nl(\\beta) &= \\sum_{i=1}^N \\left \\{y_i \\log p(x_i; \\beta) + (1-y_i)log(1 - p(x_i;\\beta)) \\right \\}\\\\\n&= \\sum_{i=1}^N \\left \\{ \n y_i(\\beta^Tx_i - log(1+e^{\\beta^Tx_i})) -\n (1-y_i)log(1+e^{\\beta^Tx_i})\n\\right\\}\\\\\n&= \\sum_{i=1}^N \\left \\{ y_i\\beta^Tx_i - \\log (1+e^{\\beta^Tx_i}) \\right\\}\n\\end{align}\n$$\n\nHere $\\beta = \\{\\beta_{10}, \\beta_1\\}$, and we assume that the vector of inputs $x_i$ includes the constant term 1.\n\nTo maximize the log-likelihood, we set its derivative to zero (4.21):\n$$\n\\begin{align}\n\\cfrac{\\partial l(\\beta)}{\\partial \\beta} &=\\cfrac{\\partial \\left [\n\\sum_{i=1}^N \\left \\{ y_i\\beta^Tx_i - \\log (1+e^{\\beta^Tx_i}) \\right\\}\n\\right]}\n{\\partial \\beta}\\\\\n&= \\sum_{i=1}^N \\left \\{ y_ix_i - \\cfrac{e^{\\beta^Tx_i}}{1+e^{\\beta^Tx_i}} x_i\\right\\}\\\\\n&= \\sum_{i=1}^N x_i(y_i-p(x_i; \\beta))\n\\end{align}\n$$\n\nwhich are p + 1 equations *nonlinear* in $\\beta$. Notice that since the first component of $x_i$ is 1, the first score equation specifies that $\\sum_{i=1}^N y_i = \\sum_{i=1}^N p(x_i;\\beta)$, the *expected* number of class ones matches the observed number (ane hence also class twos).\n\nTo solve the score equation (4.21), we use the Newton-Raphson algorithm, which requires the second-derivatie or Hessian Matrix (4.22):\n$$\n\\begin{align}\n\\cfrac{\\partial^2 l(\\beta)}{\\partial \\beta \\partial \\beta^T} \n&= \\cfrac{\\partial \\left[ \\sum_{i=1}^N x_iy_i - x_i\\cfrac{e^{\\beta^Tx_i}}{1+e^{\\beta^Tx_i}}\\right]}{ \\partial \\beta^T}\\\\\n&= \\cfrac{\\partial \\left[ \\sum_{i=1}^N -x_i\\cfrac{e^{\\beta^Tx_i}}{1+e^{\\beta^Tx_i}}\\right]}{ \\partial \\beta^T}\\\\\n&= \\sum_{i=1}^N -x_i x_i^T \n \\cfrac{ \n e^{\\beta^Tx_i}(1+e^{\\beta^Tx_i}) - e^{2\\beta^Tx_i}\n }{\n (1+e^{\\beta^Tx_i})^2\n }\\\\\n&= \\sum_{i=1}^N -x_i x_i^T \n\\cfrac{ e^{\\beta^Tx_i} }{ 1+e^{\\beta^Tx_i} }\n\\cfrac{ 1 }{ 1+e^{\\beta^Tx_i} }\\\\\n&= -\\sum_{i=1}^N x_ix_i^Tp(x_i;\\beta)(1-p(x_i;\\beta))\n\\end{align}\n$$\n\nA single Newton update is (4.23):\n$$\n\\beta^{new}=\\beta^{old} - \n\\left (\n \\cfrac{\\partial^2 l(\\beta)}{\\partial \\beta \\partial \\beta^T}\n\\right)^{-1}\n\\cfrac{\\partial l(\\beta)}{\\partial \\beta}\n$$\n\nWe can write it as (4.24, 4.25):\n$$\n\\begin{equation}\n\\cfrac{\\partial l(\\beta)}{\\partial \\beta} = \\mathbf{X}^T(\\mathbf{y}-\\mathbf{p})\\\\\n\\cfrac{\\partial^2 l(\\beta)}{\\partial \\beta \\partial \\beta^T} = -\\mathbf{X}^T\\mathbf{W}\\mathbf{X}\n\\end{equation}\n$$\nwhere: \n\n- **X** - the $N \\times (p + 1)$ input matrix,\n\n- **p** - the vector of fitted probabilities.\n\n- **W** - a $N \\times N$ diagonal matrix with ith element $p(x_i, \\beta_{old})(1-p(x_i;\\beta_{old}))$\n\nThe Newton step is thus (4.26):\n$$\n\\begin{align}\n\\beta^{new} \n&= \\beta^{old} + (\\mathbf{X}^T\\mathbf{WX})^{-1}\\mathbf{X}^T(\\mathbf{y}-\\mathbf{p})\\\\\n&= (\\mathbf{X}^T\\mathbf{WX})^{-1}\\mathbf{X}^T\\mathbf{W}\n\\left(\\mathbf{X}\\beta^{old}+\\mathbf{W}^{-1}(\\mathbf{y}-\\mathbf{p})\\right)\\\\\n&= (\\mathbf{X}^T\\mathbf{WX})^{-1}\\mathbf{X}^T\\mathbf{W}\\mathbf{z}\n\\end{align}\n$$\n\nWe re-expressed the Newton step as a weighted least squares step, with the response (4.27):\n$$\n\\mathbf{z}=\\mathbf{X}\\beta^{old}+\\mathbf{W}^{-1}(\\mathbf{y}-\\mathbf{p})\n$$\n\nalso known as the *adjusted response*. These equations get solved repeatedly and referred to as *iteratively least squares* (IRLS), since each iteration solves the weighted least squares problem(4.28): \n$$\n\\beta^{new} \\leftarrow \\underset{\\beta}{argmin} (\\mathbf{z}-\\mathbf{X}\\beta)^T\\mathbf{W}(\\mathbf{z}-\\mathbf{X}\\beta)\n$$\n", "meta": {"hexsha": "6ef5f15efe77029f3ebc4cf0c7a5f5f2a46d6b4e", "size": 5675, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "chapter-04/4.4.1-fitting-logistic-regression-models.ipynb", "max_stars_repo_name": "leduran/ESL", "max_stars_repo_head_hexsha": "fcb6c8268d6a64962c013006d9298c6f5a7104fe", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 360, "max_stars_repo_stars_event_min_datetime": "2019-01-28T14:05:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T00:11:21.000Z", "max_issues_repo_path": "chapter-04/4.4.1-fitting-logistic-regression-models.ipynb", "max_issues_repo_name": "leduran/ESL", "max_issues_repo_head_hexsha": "fcb6c8268d6a64962c013006d9298c6f5a7104fe", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-07-06T16:51:40.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-06T16:51:40.000Z", "max_forks_repo_path": "chapter-04/4.4.1-fitting-logistic-regression-models.ipynb", "max_forks_repo_name": "leduran/ESL", "max_forks_repo_head_hexsha": "fcb6c8268d6a64962c013006d9298c6f5a7104fe", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 79, "max_forks_repo_forks_event_min_datetime": "2019-03-21T23:48:35.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T13:05:10.000Z", "avg_line_length": 36.6129032258, "max_line_length": 293, "alphanum_fraction": 0.5057268722, "converted": true, "num_tokens": 1526, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750413739075, "lm_q2_score": 0.8976952818435994, "lm_q1q2_score": 0.8557505069406187}} {"text": "# Lab Assignment 3\n\n## Sam Dauncey, s2028017\n\nWe consider the system $$\\frac{dx}{dt}=x(y-1),\\quad \\frac{dy}{dt}=4-y^2-x^2.$$\n\n## Task 1 (2 marks)\n\nUse `SymPy` to find the critical points of the system.\n\n\n```python\nimport sympy as sym\nsym.init_printing()\nfrom IPython.display import display_latex\n```\n\n\n```python\n# Define sympy symbols.\nt = sym.symbols(\"t\")\nx = sym.Function(\"x\")\ny = sym.Function(\"y\")\n\n# Use these symbols to define the expressions for x' and y' given above.\nx_prime = x(t)*(y(t) - 1)\ny_prime = 4 - y(t)**2 - x(t)**2\n\ndeq_x = sym.Eq(x(t).diff(t), x_prime)\ndeq_y = sym.Eq(y(t).diff(t), y_prime)\n\n# Symbolically solve for when (x', y') = (0, 0)\ncrit_point_dicts = sym.solve([x_prime, y_prime])\n\n# Extract the critical points from the dictionaries given by sympy.\ncrit_points = [(point[x(t)], point[y(t)]) for point in crit_point_dicts]\ncrit_points\n```\n\n## Task 2 (4 marks)\n\nGive your implementation of the `linearise` function from Lab 3.\n\nUse this to find linear approximations of the system around the critical points with $x \\geq 0$ and $y \\geq 0$. Use the output to classify these critical points (use markdown cells and proper reasoning to explain the type of each critical point).\n\n\n```python\n# Define some variables to use in our linear system.\nu = sym.Function(\"u\")\nv = sym.Function(\"v\")\n\ndef lin_matrix(eqs, crit_point):\n \"\"\"Returns the jacobian F(x, y) = (x', y') evaluated at the given critical point\"\"\"\n # Unpack the expressions for x' and y' and use them to calculate the Jacobian.\n eq1, eq2 = eqs\n FG = sym.Matrix([eq1.rhs, eq2.rhs])\n matJ = FG.jacobian([x(t), y(t)])\n \n # Evaluate the Jacobian at the given critical point.\n x0, y0 = crit_point\n lin_mat = matJ.subs({x(t):x0, y(t):y0})\n return lin_mat\n\ndef linearise(eqs, crit_point):\n \"\"\"Returns a list of equations for the linearised system of eqs evaluated at the given critical point\"\"\"\n # Get the jacobian, J, at our critical point\n lin_mat = lin_matrix(eqs, crit_point)\n \n # Construct the system (u', v') = J (u, v) component-wise and return.\n uv_rhs = lin_mat * sym.Matrix([u(t),v(t)])\n u_eq = sym.Eq(u(t).diff(t), uv_rhs[0])\n v_eq = sym.Eq(v(t).diff(t), uv_rhs[1])\n return [u_eq, v_eq]\n\n\n# Print info about the linear system at each of the critical points.\nfor point in crit_points:\n \n # If the x and y coords are non-negative, print information about the point.\n x0, y0 = point \n if x0 >= 0 and y0 >= 0:\n print(\"critical point:\")\n display_latex((x0, y0))\n \n # Use lin_matrix() to get the matrix and eigenvalues of the linearised system\n linearised_matrix = lin_matrix([deq_x, deq_y], point)\n print(\"linearised matrix, eigenvalues\")\n display_latex(linearised_matrix)\n display_latex(list(linearised_matrix.eigenvals().keys()))\n \n # Use linearise() to get a printable version of the linear system\n print(\"full linearised system:\")\n display_latex(linearise([deq_x, deq_y], point))\n print()\n print()\n```\n\n critical point:\n\n\n\n$\\displaystyle \\left( 0, \\ 2\\right)$\n\n\n linearised matrix, eigenvalues\n\n\n\n$\\displaystyle \\left[\\begin{matrix}1 & 0\\\\0 & -4\\end{matrix}\\right]$\n\n\n\n$\\displaystyle \\left[ 1, \\ -4\\right]$\n\n\n full linearised system:\n\n\n\n$\\displaystyle \\left[ \\frac{d}{d t} u{\\left(t \\right)} = u{\\left(t \\right)}, \\ \\frac{d}{d t} v{\\left(t \\right)} = - 4 v{\\left(t \\right)}\\right]$\n\n\n \n \n critical point:\n\n\n\n$\\displaystyle \\left( \\sqrt{3}, \\ 1\\right)$\n\n\n linearised matrix, eigenvalues\n\n\n\n$\\displaystyle \\left[\\begin{matrix}0 & \\sqrt{3}\\\\- 2 \\sqrt{3} & -2\\end{matrix}\\right]$\n\n\n\n$\\displaystyle \\left[ -1 - \\sqrt{5} i, \\ -1 + \\sqrt{5} i\\right]$\n\n\n full linearised system:\n\n\n\n$\\displaystyle \\left[ \\frac{d}{d t} u{\\left(t \\right)} = \\sqrt{3} v{\\left(t \\right)}, \\ \\frac{d}{d t} v{\\left(t \\right)} = - 2 \\sqrt{3} u{\\left(t \\right)} - 2 v{\\left(t \\right)}\\right]$\n\n\n \n \n\n\nWe can see here that the point $(2, 0)$ will be unstable as the linearised system has a positive eigenvalue (namely $1$). In contrast, the eigenvalues for the linearised system at the critical point $(\\sqrt{3}, 1)$ both have negative real parts so this critical point will be stable.\n\n## Task 3 (4 marks)\n\nProduce a phase portrait of the system, with trajectories showing the behaviour around all the critical points. A few trajectories are enough to show this behaviour. Use properly-sized arrows to diplay the vector field (the RHS of the ODE). There are some marks allocated to the quality of your figure in this part. Try to keep it illustrative yet not too cluttered.\n\n\n```python\n\n```\n\n\n```python\n\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom scipy.integrate import odeint\n%matplotlib inline\n\n# Get figure and axes\nfig, ax = plt.subplots(figsize=(12, 9))\n\n\n# Define x and y derivatives (t variable for use with odeint)\ndef vector_field(xy, t):\n X, Y = xy\n return (X*(Y - 1), 4 - Y**2 - X**2)\n\n# Get arrays for all the points with -4 < x < 4, -3 < y < 3\nX, Y = np.mgrid[-4:4:24j, -3:3: 18j]\n\n# Evaluate the vector field and length of each vector at each point\nX_prime, Y_prime = vector_field((X, Y), None)\nMagnitude = np.hypot(X_prime, Y_prime)\n\n# Plot arrows which are faded if they have large magnitute\nax.quiver(X, Y, X_prime, Y_prime, Magnitude,\n scale=200, pivot = 'mid', cmap = plt.cm.bone)\n\n# Pick some initial conditions for phase portraits\nics = [[0.2, 2.2], [-0.2, -1.8], [3, 2], [-1.5, 0.5]]\ndurations = [[0, 10], [0, 8], [0, 5], [0, 5]]\n\nvcolors = plt.cm.autumn_r(np.linspace(0.5, 1., len(ics))) # colors for each trajectory\n\n# plot trajectories\nfor time_span, ic, color in zip(durations, ics, vcolors):\n t = np.linspace(*time_span, 100)\n sol = odeint(vector_field, ic, t)\n x_sol, y_sol = sol.T\n ax.plot(x_sol, y_sol, color=color, label=f\"$(x_0, y_0)$ = {ic}\")\n\n\ndef split_coords(tuple_list):\n \"\"\"Helper function which takes [(a, b), (c, d), (e, f) ... ] and returns [[a, c, e .. ], [b, d, f ...]]\"\"\"\n return np.array(tuple_list).T\n\n# Plot black and blue points for the critical points and initial conditions respectivelyl\nax.scatter(*split_coords(crit_points), color = \"k\", label=\"critical points\")\nax.scatter(*split_coords(ics), color='b', label=\"initial conditions\")\n\nplt.xlabel('x')\nplt.ylabel('y')\nplt.legend()\n\nplt.xlim(-4, 4)\nplt.ylim(-3, 3)\n\nplt.show()\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "a67fc6b1e53eae8da07465d3a2bf158e36b39e40", "size": 232459, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Lab_3_Assignment.ipynb", "max_stars_repo_name": "SamD770/hons-diff-eqs-notebooks", "max_stars_repo_head_hexsha": "48503988b75f113760b67979713c8dcf5f143fa4", "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": "Lab_3_Assignment.ipynb", "max_issues_repo_name": "SamD770/hons-diff-eqs-notebooks", "max_issues_repo_head_hexsha": "48503988b75f113760b67979713c8dcf5f143fa4", "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": "Lab_3_Assignment.ipynb", "max_forks_repo_name": "SamD770/hons-diff-eqs-notebooks", "max_forks_repo_head_hexsha": "48503988b75f113760b67979713c8dcf5f143fa4", "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": 560.1421686747, "max_line_length": 215736, "alphanum_fraction": 0.9410261595, "converted": true, "num_tokens": 1930, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582497090321, "lm_q2_score": 0.9196425377849806, "lm_q1q2_score": 0.8556889860653855}} {"text": "# Euler angle worksheet\n\nThis is a [jupyter notebook](https://jupyter.org/). Jupyter Notebooks allows you to combine notes, code, and output into a single document. You can even export your document as a presentation or presentation.\n\nIn this worksheet, we will use the python3 SymPy package to derive expressions for converting between euler angles and matrices.\n\nIf you would like more information about jupyter notebook features:\n\n* [Getting started tutorial](https://realpython.com/jupyter-notebook-introduction/#creating-a-notebook)\n* [Reference on markdown text](https://help.github.com/articles/markdown-basics/)\n\nFor this assignment, you do not need to run this notebook. It has been compiled for you and saved as a webpage. However, if you would like to play with it, start by running all the cells (from the menu: goto 'Cell' -> 'Run All'). \n\n\n```python\n# python3 \nfrom sympy import *\ninit_printing(use_latex='mathjax')\nimport math\n```\n\n\n```python\n# Define symbols\ncx,sx = symbols('cx sx')\ncy,sy = symbols('cy sy')\ncz,sz = symbols('cz sz')\n\nRx = Matrix([ \n [1, 0, 0], \n [0, cx,-sx], \n [0, sx, cx]])\n\nRy = Matrix([\n [ cy, 0, sy], \n [ 0, 1, 0], \n [-sy, 0, cy]])\n\nRz = Matrix([ \n [cz, -sz, 0], \n [sz, cz, 0], \n [0, 0, 1]])\n```\n\n# Convert from ZYX euler angles to a matrix\n\nWe can compute the matrix Rzyx by multiplying matrixes corresponding to each consecutive rotation, e.g. \n\n$$\nR_{zyx}(\\theta_x, \\theta_y, \\theta_z) = R_z(\\theta_z) * R_y(\\theta_y) * R_x(\\theta_x)\n$$\n\nIn this file, we will use the [SymPy](https://www.sympy.org/en/index.html) to compute algebraic expressions for euler angle matrices. Using these expressions, we will be able to derive formulas for converting from matrices to euler angles.\n\nIn the following example, let\n\n* cx = $cos(\\theta_x)$\n* sx = $sin(\\theta_x)$\n* cy = $cos(\\theta_y)$\n* sy = $sin(\\theta_y)$\n* cz = $cos(\\theta_z)$\n* sz = $sin(\\theta_z)$\n\n\n\n```python\nRzyx = Rz * Ry * Rx\npprint(Rzyx)\n```\n\n ⎡cy⋅cz -cx⋅sz + cz⋅sx⋅sy cx⋅cz⋅sy + sx⋅sz⎤\n ⎢ ⎥\n ⎢cy⋅sz cx⋅cz + sx⋅sy⋅sz cx⋅sy⋅sz - cz⋅sx⎥\n ⎢ ⎥\n ⎣ -sy cy⋅sx cx⋅cy ⎦\n\n\nNow that we have a matrix expression for the ZYX euler angles, we have formulas which describe how matrices and euler angles relate to each. Specifically, suppose we have a 3x3 rotation matrix R with the following elements\n\n$$\nR = \n\\begin{bmatrix}\nr_{00} & r_{01} & r_{02} \\\\\nr_{10} & r_{11} & r_{12} \\\\\nr_{20} & r_{21} & r_{22} \\\\\n\\end{bmatrix}\n$$\n\nwhere each $r_{ij}$ represents a scalar value in $\\mathbb{R}$. Usually math texts will use indexing at 1, but here let's use 0-based indexing so that it will be easier to use implement these formulas later.\n\nNow suppose we wish to extract the euler angles from this matrix. We can get the Y rotation back from the term $r_{20}$.\n\n$$\nr_{20} = -\\sin(\\theta_y) \\\\\n=> \\theta_y = \\sin(-r_{20})\n$$\n\nWhat about the rotations around X and Z? We can obtain these similarly using the terms from the first column and last row. A robust method involves using the fact that \n\n$$\n\\tan(\\theta) = \\frac{\\sin(\\theta)}{\\cos(\\theta)}\n$$\n\nto form the following expression for obtaining $\\theta_x$\n\n$$\n\\frac{r_{21}}{r_{22}} = \\frac{\\sin(\\theta_x)}{\\cos(\\theta_x)} = \\tan(\\theta_x) \\\\\n=> \\theta_x = \\text{atan2}(r_{21}, r_{22})\n$$\n\nThe expression for $\\theta_z$ can be obtained similarly\n\n$$\n\\frac{r_{10}}{r_{00}} = \\frac{\\sin(\\theta_z)}{\\cos(\\theta_z)} = \\tan(\\theta_z) \\\\\n=> \\theta_z = \\text{atan2}(r_{10}, r_{00})\n$$\n\nUsing atan2 makes it easier to handle the cases when $\\theta$ is near 0, 90, or 180 degrees, which makes sine and cosine close to zero and 1. Be careful when using acos and asin because values even *slightly* out of the range [-1,1] can lead to NaNs. The computer will not tolerate nansense!\n\n## What happens to Rzyx when y is +/- 90 degrees?\n\nWhen the middle euler angle is 90 degrees, we need to look to the non-zero terms to values for the first and last angles. For example, for ZYX euler angles, we need to handle the case when Y is either positive or negative 90 degrees. \n\n\n```python\n# Compute Rzyx when y is +90\nRy90 = Matrix([\n [ 0, 0, 1], \n [ 0, 1, 0], \n [-1, 0, 0]])\n\nRzyx = Rz * Ry90 * Rx\npprint(Rzyx)\n```\n\n ⎡0 -cx⋅sz + cz⋅sx cx⋅cz + sx⋅sz⎤\n ⎢ ⎥\n ⎢0 cx⋅cz + sx⋅sz cx⋅sz - cz⋅sx⎥\n ⎢ ⎥\n ⎣-1 0 0 ⎦\n\n\nSo now we have the above expression. We know that the Y rotation is 90 but what about the X and Z rotations? We need to look at the upper part of the matrix to figure these out.\n\nLet's apply the sine and cosine [addition rules](https://en.wikipedia.org/wiki/List_of_trigonometric_identities)\n\n$$\n\\sin(z + x) = \\sin(z) \\cos(x) + \\cos(z) \\sin(x) \\\\\n\\sin(z - x) = \\sin(z) \\cos(x) - \\cos(z) \\sin(x) \\\\\n\\cos(z + x) = \\cos(z) \\cos(x) - \\sin(z) \\sin(x) \\\\\n\\cos(z - x) = \\cos(z) \\cos(x) + \\sin(z) \\sin(x) \\\\\n$$\n\nAnother useful property of sine and cosine is the following\n\n$$\n\\sin(-\\theta) = -\\sin(\\theta) \\\\\n\\cos(-\\theta) = \\cos(\\theta)\n$$\n\nLet's try to simplify the above matrix using these rules. For example, the term in position $r_{12}$ has two terms containing both sine and cosine, so it corresponds to one of the sine rules. It also has a negative, so its the difference between two angles X and Z.\n\n$$\n\\begin{bmatrix}\n0 & s(x-z) & c(x-z) \\\\\n0 & c(x-z) & s(z-x) \\\\\n-1 & 0 & 0\n\\end{bmatrix}\n$$\nwhich can be rewritten so every term has angle $x-z$\n$$\n\\begin{bmatrix}\n0 & s(x-z) & c(x-z) \\\\\n0 & c(x-z) & -s(x-z) \\\\\n-1 & 0 & 0\n\\end{bmatrix}\n$$\n\nTherefore, we can use atan2($r_{12}$, $r_{13}$) to get the $\\theta$ angle corresponding to the difference between $x-z$. Many values for X and Z could combine to be $\\theta$. Let's choose one of X or Z to be zero and then the other can be $\\theta$. \n\n\n```python\n# Compute Rzyx when y is -90\nRy90_Minus = Ry90.T\n\nRzyx = Rz * Ry90_Minus * Rx\npprint(Rzyx)\n```\n\n ⎡0 -cx⋅sz - cz⋅sx -cx⋅cz + sx⋅sz⎤\n ⎢ ⎥\n ⎢0 cx⋅cz - sx⋅sz -cx⋅sz - cz⋅sx⎥\n ⎢ ⎥\n ⎣1 0 0 ⎦\n\n\n$$\n\\begin{bmatrix}\n0 & -s(x+z) & c(x+z) \\\\\n0 & c(z+x) & -s(x+z) \\\\\n1 & 0 & 0\n\\end{bmatrix}\n$$\n\n\n# Convert from all euler angles to a matrix\n\nThe other five euler angle combinations can be derived similarly. \n\n# XYZ\n\n\n```python\nprint(\"Rxyz\")\npprint(Rx * Ry * Rz)\nprint()\nprint()\n\nprint(\"Y = 90\")\npprint(Rx * Ry90 * Rz)\nprint()\nprint()\n\nprint(\"Y = -90\")\npprint(Rx * Ry90_Minus * Rz)\nprint()\nprint()\n\n```\n\n Rxyz\n ⎡ cy⋅cz -cy⋅sz sy ⎤\n ⎢ ⎥\n ⎢cx⋅sz + cz⋅sx⋅sy cx⋅cz - sx⋅sy⋅sz -cy⋅sx⎥\n ⎢ ⎥\n ⎣-cx⋅cz⋅sy + sx⋅sz cx⋅sy⋅sz + cz⋅sx cx⋅cy ⎦\n \n \n Y = 90\n ⎡ 0 0 1⎤\n ⎢ ⎥\n ⎢cx⋅sz + cz⋅sx cx⋅cz - sx⋅sz 0⎥\n ⎢ ⎥\n ⎣-cx⋅cz + sx⋅sz cx⋅sz + cz⋅sx 0⎦\n \n \n Y = -90\n ⎡ 0 0 -1⎤\n ⎢ ⎥\n ⎢cx⋅sz - cz⋅sx cx⋅cz + sx⋅sz 0 ⎥\n ⎢ ⎥\n ⎣cx⋅cz + sx⋅sz -cx⋅sz + cz⋅sx 0 ⎦\n \n \n\n\nY = 90\n$$\n\\begin{bmatrix}\n0 & 0 & 1 \\\\\ns(x+z) & c(x+z) & 0\\\\\n-c(x+z) & s(x+z) & 0 \\\\\n\\end{bmatrix}\n$$\n\nY = -90\n$$\n\\begin{bmatrix}\n0 & 0 & -1 \\\\\ns(z-x) & c(z-x) & 0 \\\\\nc(z-x) & -s(z-x) & 0 \\\\\n\\end{bmatrix}\n$$\n\n\n# YXZ\n\n\n```python\nprint(\"Ryxz\")\npprint(Ry * Rx * Rz)\nprint()\nprint()\n\nRx90 = Matrix([ \n [1, 0, 0], \n [0, 0,-1], \n [0, 1, 0]])\nprint(\"+90\")\npprint(Ry * Rx90 * Rz)\nprint()\nprint()\n\nRx90_Minus = Rx90.T\nprint(\"-90\")\npprint(Ry * Rx90.T * Rz)\nprint()\nprint()\n\n```\n\n Ryxz\n ⎡cy⋅cz + sx⋅sy⋅sz -cy⋅sz + cz⋅sx⋅sy cx⋅sy⎤\n ⎢ ⎥\n ⎢ cx⋅sz cx⋅cz -sx ⎥\n ⎢ ⎥\n ⎣cy⋅sx⋅sz - cz⋅sy cy⋅cz⋅sx + sy⋅sz cx⋅cy⎦\n \n \n +90\n ⎡cy⋅cz + sy⋅sz -cy⋅sz + cz⋅sy 0 ⎤\n ⎢ ⎥\n ⎢ 0 0 -1⎥\n ⎢ ⎥\n ⎣cy⋅sz - cz⋅sy cy⋅cz + sy⋅sz 0 ⎦\n \n \n -90\n ⎡cy⋅cz - sy⋅sz -cy⋅sz - cz⋅sy 0⎤\n ⎢ ⎥\n ⎢ 0 0 1⎥\n ⎢ ⎥\n ⎣-cy⋅sz - cz⋅sy -cy⋅cz + sy⋅sz 0⎦\n \n \n\n\nX = 90\n$$\n\\begin{bmatrix}\nc(y-z) & s(y-z) & 0\\\\\n0 & 0 & -1 \\\\\n-s(y-z) & c(y-z) & 0 \\\\\n\\end{bmatrix}\n$$\n\nX = -90\n$$\n\\begin{bmatrix}\nc(y+z) & -s(y+z) & 0 \\\\\n0 & 0 & 1 \\\\\n-s(y+z) & -c(y+z) & 0 \\\\\n\\end{bmatrix}\n$$\n\n\n# ZXY\n\n\n```python\nprint(\"Rzxy\")\npprint(Rz * Rx * Ry)\nprint()\nprint()\n\nprint(\"+90\")\npprint(Rz * Rx90 * Ry)\nprint()\nprint()\n\nprint(\"-90\")\npprint(Rz * Rx90.T * Ry)\nprint()\nprint()\n```\n\n Rzxy\n ⎡cy⋅cz - sx⋅sy⋅sz -cx⋅sz cy⋅sx⋅sz + cz⋅sy ⎤\n ⎢ ⎥\n ⎢cy⋅sz + cz⋅sx⋅sy cx⋅cz -cy⋅cz⋅sx + sy⋅sz⎥\n ⎢ ⎥\n ⎣ -cx⋅sy sx cx⋅cy ⎦\n \n \n +90\n ⎡cy⋅cz - sy⋅sz 0 cy⋅sz + cz⋅sy ⎤\n ⎢ ⎥\n ⎢cy⋅sz + cz⋅sy 0 -cy⋅cz + sy⋅sz⎥\n ⎢ ⎥\n ⎣ 0 1 0 ⎦\n \n \n -90\n ⎡cy⋅cz + sy⋅sz 0 -cy⋅sz + cz⋅sy⎤\n ⎢ ⎥\n ⎢cy⋅sz - cz⋅sy 0 cy⋅cz + sy⋅sz ⎥\n ⎢ ⎥\n ⎣ 0 -1 0 ⎦\n \n \n\n\nX = 90\n$$\n\\begin{bmatrix}\nc(y+z) & 0 & s(y+z) \\\\\ns(y+z) & 0 & -c(y+z) \\\\\n0 & 1 & 0 \\\\\n\\end{bmatrix}\n$$\n\nX = -90\n$$\n\\begin{bmatrix}\nc(y-z) & 0 & s(y-z) \\\\\n-s(y-z) & 0 & c(y-z) \\\\\n0 & -1 & 0 \\\\\n\\end{bmatrix}\n$$\n\n\n# XZY\n\n\n```python\nprint(\"Rxzy\")\npprint(Rx * Rz * Ry)\nprint()\nprint()\n\nRz90 = Matrix([ \n [0, -1, 0], \n [1, 0, 0], \n [0, 0, 1]])\n\nprint(\"+90\")\npprint(Rx * Rz90 * Ry)\nprint()\nprint()\n\nprint(\"-90\")\npprint(Rx * Rz90.T * Ry)\nprint()\nprint()\n\n\n```\n\n Rxzy\n ⎡ cy⋅cz -sz cz⋅sy ⎤\n ⎢ ⎥\n ⎢cx⋅cy⋅sz + sx⋅sy cx⋅cz cx⋅sy⋅sz - cy⋅sx⎥\n ⎢ ⎥\n ⎣-cx⋅sy + cy⋅sx⋅sz cz⋅sx cx⋅cy + sx⋅sy⋅sz⎦\n \n \n +90\n ⎡ 0 -1 0 ⎤\n ⎢ ⎥\n ⎢cx⋅cy + sx⋅sy 0 cx⋅sy - cy⋅sx⎥\n ⎢ ⎥\n ⎣-cx⋅sy + cy⋅sx 0 cx⋅cy + sx⋅sy⎦\n \n \n -90\n ⎡ 0 1 0 ⎤\n ⎢ ⎥\n ⎢-cx⋅cy + sx⋅sy 0 -cx⋅sy - cy⋅sx⎥\n ⎢ ⎥\n ⎣-cx⋅sy - cy⋅sx 0 cx⋅cy - sx⋅sy ⎦\n \n \n\n\nZ = 90\n$$\n\\begin{bmatrix}\n0 & -1 & 0 \\\\\nc(x-y) & 0 & -s(x-y) \\\\\ns(x-y) & 0 & c(x-y) \\\\\n\\end{bmatrix}\n$$\n\nZ = -90\n$$\n\\begin{bmatrix}\n0 & 1 & 0 \\\\\n-c(x+y) & 0 & -s(x+y) \\\\\n-s(x+y) & 0 & c(x+y) \\\\\n\\end{bmatrix}\n$$\n\n# YZX\n\n\n```python\nprint(\"Ryzx\")\npprint(Ry * Rz * Rx)\nprint()\nprint()\n\nprint(\"+90\")\npprint(Ry * Rz90 * Rx)\nprint()\nprint()\n\nprint(\"-90\")\npprint(Ry * Rz90.T * Rx)\nprint()\nprint()\n\n```\n\n Ryzx\n ⎡cy⋅cz -cx⋅cy⋅sz + sx⋅sy cx⋅sy + cy⋅sx⋅sz⎤\n ⎢ ⎥\n ⎢ sz cx⋅cz -cz⋅sx ⎥\n ⎢ ⎥\n ⎣-cz⋅sy cx⋅sy⋅sz + cy⋅sx cx⋅cy - sx⋅sy⋅sz⎦\n \n \n +90\n ⎡0 -cx⋅cy + sx⋅sy cx⋅sy + cy⋅sx⎤\n ⎢ ⎥\n ⎢1 0 0 ⎥\n ⎢ ⎥\n ⎣0 cx⋅sy + cy⋅sx cx⋅cy - sx⋅sy⎦\n \n \n -90\n ⎡0 cx⋅cy + sx⋅sy cx⋅sy - cy⋅sx⎤\n ⎢ ⎥\n ⎢-1 0 0 ⎥\n ⎢ ⎥\n ⎣0 -cx⋅sy + cy⋅sx cx⋅cy + sx⋅sy⎦\n \n \n\n\nZ = 90\n$$\n\\begin{bmatrix}\n0 & c(x-y) & -s(x-y) \\\\\n1 & 0 & 0 \\\\\n0 & s(x-y) & c(x-y) \\\\\n\\end{bmatrix}\n$$\n\nZ = -90\n$$\n\\begin{bmatrix}\n0 & c(y-x) & s(y-x) \\\\\n-1 & 0 & 0 \\\\\n0 & -s(y-x) & c(y-x) \\\\\n\\end{bmatrix}\n$$\n", "meta": {"hexsha": "e6851d2a32d1cee8e3520944e094d933b8bfb427", "size": 19607, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Labs/EulerAngles.ipynb", "max_stars_repo_name": "isaacwasserman/website", "max_stars_repo_head_hexsha": "c052e1e8b28b9a600623589768691585eeda774d", "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": "Labs/EulerAngles.ipynb", "max_issues_repo_name": "isaacwasserman/website", "max_issues_repo_head_hexsha": "c052e1e8b28b9a600623589768691585eeda774d", "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": "Labs/EulerAngles.ipynb", "max_forks_repo_name": "isaacwasserman/website", "max_forks_repo_head_hexsha": "c052e1e8b28b9a600623589768691585eeda774d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-09-28T20:41:54.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-28T20:41:54.000Z", "avg_line_length": 26.8957475995, "max_line_length": 298, "alphanum_fraction": 0.38720865, "converted": true, "num_tokens": 4905, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582554941719, "lm_q2_score": 0.9196425278741989, "lm_q1q2_score": 0.8556889821640775}} {"text": "# Shape of loss functions\n\n\n```python\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n%matplotlib inline\n```\n\n\n```python\nt = np.arange(-3,3,0.01)\n```\n\n\n```python\ndef hinge_loss(t):\n \"\"\"Hinge loss is used by the Support Vector Machine\"\"\"\n return np.maximum(0, 1-t)\n```\n\n\n```python\nloss = hinge_loss(t)\nfig = plt.figure(figsize=(6,6))\nax = fig.add_subplot(111)\nax.plot(t, loss)\nax.set_xlabel('$t$')\nax.set_ylabel('max{0, 1-$t$}')\nplt.savefig('hinge_loss.pdf')\n```\n\n# Smoothing\n\nIf we are interested in applying gradient methods such as L-BFGS, and do not want to resort to subgradient methods, we need to smooth the kink in the hinge loss. The approach we take here is to compute the conjugate of the hinge loss, then add a proximal term ($\\ell_2$ penalty), and then compute the conjugate of that to obtain the smooth primal hinge loss.\n\nRecall that the hinge loss is given by\n$$\nL(\\alpha) = \\max\\{0, 1-\\alpha\\}\n$$\nThe convex conjugate of $L(\\alpha)$ is\n\\begin{align}\nL^*(\\beta) &= \\sup_{\\alpha\\in\\mathbb{R}} \\left\\{ \\alpha\\beta - \\max\\{0, 1-\\alpha\\} \\right\\}\\\\\n&=\n \\begin{cases}\n \\beta & \\mathrm{if}\\quad -1\\leqslant \\beta \\leqslant 0,\\\\\n \\infty & \\mathrm{otherwise}\n \\end{cases}\n\\end{align}\nThe smoothed conjugate is\n$$\nL_\\gamma^*(\\beta) = L^*(\\beta) + \\frac{\\gamma}{2} \\beta^2.\n$$\nThe corresponding primal smooth hinge loss is given by\n\\begin{align}\nL_\\gamma(\\alpha) &=\\sup_{-1\\leqslant \\beta\\leqslant 0} \\left\\{ \\alpha\\beta- \\beta - \\frac{\\gamma}{2}\\beta^2 \\right\\}\\\\\n&=\n \\begin{cases}\n 1-\\alpha-\\frac{\\gamma}{2}&\\mathrm{if}\\quad \\alpha < 1-\\gamma,\\\\\n \\frac{(\\alpha-1)^2}{2\\gamma}&\\mathrm{if}\\quad 1-\\gamma \\leqslant \\alpha \\leqslant 1,\\\\\n 0&\\mathrm{if}\\quad \\alpha > 1.\n \\end{cases}\n\\end{align}\n$L_\\gamma(\\alpha)$ is convex and differentiable with the derivative\n$$\nL_\\gamma'(\\alpha) =\n\\begin{cases}\n -1&\\mathrm{if}\\quad \\alpha < 1-\\gamma,\\\\\n \\frac{\\alpha-1}{\\gamma}&\\mathrm{if}\\quad 1-\\gamma\\leqslant \\alpha\\leqslant 1,\\\\\n 0&\\mathrm{if}\\quad \\alpha > 1.\n\\end{cases}\n$$\n\n\n```python\n\n```\n", "meta": {"hexsha": "f9a159a044ff764fde81abc9580b41266e07b296", "size": 19721, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Loss/loss_shape.ipynb", "max_stars_repo_name": "lydiaknuefing/didbits", "max_stars_repo_head_hexsha": "c392fd46167282bcad48a3b05ee915aaa27e4856", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 18, "max_stars_repo_stars_event_min_datetime": "2015-06-24T02:24:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-22T10:47:09.000Z", "max_issues_repo_path": "Loss/loss_shape.ipynb", "max_issues_repo_name": "lydiaknuefing/didbits", "max_issues_repo_head_hexsha": "c392fd46167282bcad48a3b05ee915aaa27e4856", "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": "Loss/loss_shape.ipynb", "max_forks_repo_name": "lydiaknuefing/didbits", "max_forks_repo_head_hexsha": "c392fd46167282bcad48a3b05ee915aaa27e4856", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2015-06-26T06:50:43.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-27T03:58:00.000Z", "avg_line_length": 127.2322580645, "max_line_length": 15640, "alphanum_fraction": 0.8642056691, "converted": true, "num_tokens": 710, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474181553805, "lm_q2_score": 0.8962513682840824, "lm_q1q2_score": 0.8556040547506263}} {"text": "# Finding Roots of Equations\n\n## Calculus review\n\n\n```python\n%matplotlib inline\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport scipy as scipy\nfrom scipy.interpolate import interp1d\n```\n\nLet's review the theory of optimization for multivariate functions. Recall that in the single-variable case, extreme values (local extrema) occur at points where the first derivative is zero, however, the vanishing of the first derivative is not a sufficient condition for a local max or min. Generally, we apply the second derivative test to determine whether a candidate point is a max or min (sometimes it fails - if the second derivative either does not exist or is zero). In the multivariate case, the first and second derivatives are *matrices*. In the case of a scalar-valued function on $\\mathbb{R}^n$, the first derivative is an $n\\times 1$ vector called the *gradient* (denoted $\\nabla f$). The second derivative is an $n\\times n$ matrix called the *Hessian* (denoted $H$)\n\nJust to remind you, the gradient and Hessian are given by:\n\n$$\\nabla f(x) = \\left(\\begin{matrix}\\frac{\\partial f}{\\partial x_1}\\\\ \\vdots \\\\\\frac{\\partial f}{\\partial x_n}\\end{matrix}\\right)$$\n\n\n$$H = \\left(\\begin{matrix}\n \\dfrac{\\partial^2 f}{\\partial x_1^2} & \\dfrac{\\partial^2 f}{\\partial x_1\\,\\partial x_2} & \\cdots & \\dfrac{\\partial^2 f}{\\partial x_1\\,\\partial x_n} \\\\[2.2ex]\n \\dfrac{\\partial^2 f}{\\partial x_2\\,\\partial x_1} & \\dfrac{\\partial^2 f}{\\partial x_2^2} & \\cdots & \\dfrac{\\partial^2 f}{\\partial x_2\\,\\partial x_n} \\\\[2.2ex]\n \\vdots & \\vdots & \\ddots & \\vdots \\\\[2.2ex]\n \\dfrac{\\partial^2 f}{\\partial x_n\\,\\partial x_1} & \\dfrac{\\partial^2 f}{\\partial x_n\\,\\partial x_2} & \\cdots & \\dfrac{\\partial^2 f}{\\partial x_n^2}\n\\end{matrix}\\right)$$\n\nOne of the first things to note about the Hessian - it's symmetric. This structure leads to some useful properties in terms of interpreting critical points.\n\nThe multivariate analog of the test for a local max or min turns out to be a statement about the gradient and the Hessian matrix. Specifically, a function $f:\\mathbb{R}^n\\rightarrow \\mathbb{R}$ has a critical point at $x$ if $\\nabla f(x) = 0$ (where zero is the zero vector!). Furthermore, the second derivative test at a critical point is as follows:\n\n* If $H(x)$ is positive-definite ($\\iff$ it has all positive eigenvalues), $f$ has a local minimum at $x$\n* If $H(x)$ is negative-definite ($\\iff$ it has all negative eigenvalues), $f$ has a local maximum at $x$\n* If $H(x)$ has both positive and negative eigenvalues, $f$ has a saddle point at $x$.\n\nIf you have $m$ equations with $n$ variables, then the $m \\times n$ matrix of first partial derivatives is known as the Jacobian $J(x)$. For example, for two equations $f(x, y)$ and $g(x, y)$, we have\n\n$$\nJ(x) = \\begin{bmatrix}\n\\frac{\\delta f}{\\delta x} & \\frac{\\delta f}{\\delta y} \\\\\n\\frac{\\delta g}{\\delta x} & \\frac{\\delta g}{\\delta y} \n\\end{bmatrix}\n$$\n\nWe can now express the multivariate form of Taylor polynomials in a familiar format.\n\n$$\nf(x + \\delta x) = f(x) + \\delta x \\cdot J(x) + \\frac{1}{2} \\delta x^T H(x) \\delta x + \\mathcal{O}(\\delta x^3)\n$$\n\n## Main Issues in Root Finding in One Dimension\n\n* Separating close roots\n* Numerical Stability\n* Rate of Convergence\n* Continuity and Differentiability\n\n## Bisection Method\n\nThe bisection method is one of the simplest methods for finding zeros of a non-linear function. It is guaranteed to find a root - but it can be slow. The main idea comes from the intermediate value theorem: If $f(a)$ and $f(b)$ have different signs and $f$ is continuous, then $f$ must have a zero between $a$ and $b$. We evaluate the function at the midpoint, $c = \\frac12(a+b)$. $f(c)$ is either zero, has the same sign as $f(a)$ or the same sign as $f(b)$. Suppose $f(c)$ has the same sign as $f(a)$ (as pictured below). We then repeat the process on the interval $[c,b]$. \n\n\n```python\ndef f(x):\n return x**3 + 4*x**2 -3\n\nx = np.linspace(-3.1, 0, 100)\nplt.plot(x, x**3 + 4*x**2 -3)\n\na = -3.0\nb = -0.5\nc = 0.5*(a+b)\n\nplt.text(a,-1,\"a\")\nplt.text(b,-1,\"b\")\nplt.text(c,-1,\"c\")\n\nplt.scatter([a,b,c], [f(a), f(b),f(c)], s=50, facecolors='none')\nplt.scatter([a,b,c], [0,0,0], s=50, c='red')\n\nxaxis = plt.axhline(0)\npass\n```\n\n\n```python\nx = np.linspace(-3.1, 0, 100)\nplt.plot(x, x**3 + 4*x**2 -3)\n\nd = 0.5*(b+c)\n\nplt.text(d,-1,\"d\")\nplt.text(b,-1,\"b\")\nplt.text(c,-1,\"c\")\n\nplt.scatter([d,b,c], [f(d), f(b),f(c)], s=50, facecolors='none')\nplt.scatter([d,b,c], [0,0,0], s=50, c='red')\n\nxaxis = plt.axhline(0)\npass\n```\n\nWe can terminate the process whenever the function evaluated at the new midpoint is 'close enough' to zero. This method is an example of what are known as 'bracketed methods'. This means the root is 'bracketed' by the end-points (it is somewhere in between). Another class of methods are 'open methods' - the root need not be somewhere in between the end-points (but it usually needs to be close!)\n\n## Secant Method\n\nThe secant method also begins with two initial points, but without the constraint that the function values are of opposite signs. We use the secant line to extrapolate the next candidate point.\n\n\n```python\ndef f(x):\n return (x**3-2*x+7)/(x**4+2)\n\nx = np.arange(-3,5, 0.1);\ny = f(x)\n\np1=plt.plot(x, y)\nplt.xlim(-3, 4)\nplt.ylim(-.5, 4)\nplt.xlabel('x')\nplt.axhline(0)\nt = np.arange(-10, 5., 0.1)\n\nx0=-1.2\nx1=-0.5\nxvals = []\nxvals.append(x0)\nxvals.append(x1)\nnotconverge = 1\ncount = 0\ncols=['r--','b--','g--','y--']\nwhile (notconverge==1 and count < 3):\n slope=(f(xvals[count+1])-f(xvals[count]))/(xvals[count+1]-xvals[count])\n intercept=-slope*xvals[count+1]+f(xvals[count+1])\n plt.plot(t, slope*t + intercept, cols[count])\n nextval = -intercept/slope\n if abs(f(nextval)) < 0.001:\n notconverge=0\n else:\n xvals.append(nextval)\n count = count+1\n\nplt.show()\n```\n\nThe secant method has the advantage of fast convergence. While the bisection method has a linear convergence rate (i.e. error goes to zero at the rate that $h(x) = x$ goes to zero, the secant method has a convergence rate that is faster than linear, but not quite quadratic (i.e. $\\sim x^\\alpha$, where $\\alpha = \\frac{1+\\sqrt{5}}2 \\approx 1.6$) however, the trade-off is that the secant method is not guaranteed to find a root in the brackets.\n\nA variant of the secant method is known as the **method of false positions**. Conceptually it is identical to the secant method, except that instead of always using the last two values of $x$ for linear interpolation, it chooses the two most recent values that maintain the bracket property (i.e $f(a) f(b) < 0$). It is slower than the secant, but like the bisection, is safe.\n\n## Newton-Raphson Method\n\nWe want to find the value $\\theta$ so that some (differentiable) function $g(\\theta)=0$. \nIdea: start with a guess, $\\theta_0$. Let $\\tilde{\\theta}$ denote the value of $\\theta$ for which $g(\\theta) = 0$ and define $h = \\tilde{\\theta} - \\theta_0$. Then:\n\n$$\n\\begin{eqnarray*}\ng(\\tilde{\\theta}) &=& 0 \\\\\\\\\n&=&g(\\theta_0 + h) \\\\\\\\\n&\\approx& g(\\theta_0) + hg'(\\theta_0)\n\\end{eqnarray*}\n$$\n\nThis implies that \n\n$$ h\\approx \\frac{g(\\theta_0)}{g'(\\theta_0)}$$\n\nSo that\n\n$$\\tilde{\\theta}\\approx \\theta_0 - \\frac{g(\\theta_0)}{g'(\\theta_0)}$$\n\nThus, we set our next approximation:\n\n$$\\theta_1 = \\theta_0 - \\frac{g(\\theta_0)}{g'(\\theta_0)}$$\n\nand we have developed an iterative procedure with:\n\n$$\\theta_n = \\theta_{n-1} - \\frac{g(\\theta_{n-1})}{g'(\\theta_{n-1})}$$\n\n#### Example\n\nLet $$g(x) = \\frac{x^3-2x+7}{x^4+2}$$\n\n\n```python\nx = np.arange(-5,5, 0.1);\ny = (x**3-2*x+7)/(x**4+2)\n\np1=plt.plot(x, y)\nplt.xlim(-4, 4)\nplt.ylim(-.5, 4)\nplt.xlabel('x')\nplt.axhline(0)\nplt.title('Example Function')\nplt.show()\n```\n\n\n```python\nx = np.arange(-5,5, 0.1);\ny = (x**3-2*x+7)/(x**4+2)\n\np1=plt.plot(x, y)\nplt.xlim(-4, 4)\nplt.ylim(-.5, 4)\nplt.xlabel('x')\nplt.axhline(0)\nplt.title('Good Guess')\nt = np.arange(-5, 5., 0.1)\n\nx0=-1.5\nxvals = []\nxvals.append(x0)\nnotconverge = 1\ncount = 0\ncols=['r--','b--','g--','y--','c--','m--','k--','w--']\nwhile (notconverge==1 and count < 6):\n funval=(xvals[count]**3-2*xvals[count]+7)/(xvals[count]**4+2)\n slope=-((4*xvals[count]**3 *(7 - 2 *xvals[count] + xvals[count]**3))/(2 + xvals[count]**4)**2) + (-2 + 3 *xvals[count]**2)/(2 + xvals[count]**4)\n \n intercept=-slope*xvals[count]+(xvals[count]**3-2*xvals[count]+7)/(xvals[count]**4+2)\n\n plt.plot(t, slope*t + intercept, cols[count])\n nextval = -intercept/slope\n if abs(funval) < 0.01:\n notconverge=0\n else:\n xvals.append(nextval)\n count = count+1\n\n\n```\n\nFrom the graph, we see the zero is near -2. We make an initial guess of $$x=-1.5$$\n\nWe have made an excellent choice for our first guess, and we can see rapid convergence!\n\n\n```python\nfunval\n```\n\n\n\n\n 0.007591996330867034\n\n\n\nIn fact, the Newton-Raphson method converges quadratically. However, NR (and the secant method) have a fatal flaw:\n\n\n```python\nx = np.arange(-5,5, 0.1);\ny = (x**3-2*x+7)/(x**4+2)\n\np1=plt.plot(x, y)\nplt.xlim(-4, 4)\nplt.ylim(-.5, 4)\nplt.xlabel('x')\nplt.axhline(0)\nplt.title('Bad Guess')\nt = np.arange(-5, 5., 0.1)\n\nx0=-0.5\nxvals = []\nxvals.append(x0)\nnotconverge = 1\ncount = 0\ncols=['r--','b--','g--','y--','c--','m--','k--','w--']\nwhile (notconverge==1 and count < 6):\n funval=(xvals[count]**3-2*xvals[count]+7)/(xvals[count]**4+2)\n slope=-((4*xvals[count]**3 *(7 - 2 *xvals[count] + xvals[count]**3))/(2 + xvals[count]**4)**2) + (-2 + 3 *xvals[count]**2)/(2 + xvals[count]**4)\n \n intercept=-slope*xvals[count]+(xvals[count]**3-2*xvals[count]+7)/(xvals[count]**4+2)\n\n plt.plot(t, slope*t + intercept, cols[count])\n nextval = -intercept/slope\n if abs(funval) < 0.01:\n notconverge = 0\n else:\n xvals.append(nextval)\n count = count+1\n```\n\nWe have stumbled on the horizontal asymptote. The algorithm fails to converge. \n\n### Convergence Rate\n\nThe following is a derivation of the convergence rate of the NR method:\n\n\nSuppose $x_k \\; \\rightarrow \\; x^*$ and $g'(x^*) \\neq 0$. Then we may write:\n\n$$x_k = x^* + \\epsilon_k$$.\n\nNow expand $g$ at $x^*$:\n\n$$g(x_k) = g(x^*) + g'(x^*)\\epsilon_k + \\frac12 g''(x^*)\\epsilon_k^2 + ...$$\n$$g'(x_k)=g'(x^*) + g''(x^*)\\epsilon_k$$\n\nWe have that\n\n\n\\begin{eqnarray}\n\\epsilon_{k+1} &=& \\epsilon_k + \\left(x_{k-1}-x_k\\right)\\\\\n&=& \\epsilon_k -\\frac{g(x_k)}{g'(x_k)}\\\\\n&\\approx & \\frac{g'(x^*)\\epsilon_k + \\frac12g''(x^*)\\epsilon_k^2}{g'(x^*)+g''(x^*)\\epsilon_k}\\\\\n&\\approx & \\frac{g''(x^*)}{2g'(x^*)}\\epsilon_k^2\n\\end{eqnarray}\n\n## Gauss-Newton\n\nFor 1D, the Newton method is\n$$\nx_{n+1} = x_n - \\frac{f(x_n)}{f'(x_n)}\n$$\n\nWe can generalize to $k$ dimensions by \n$$\nx_{n+1} = x_n - J^{-1} f(x_n)\n$$\nwhere $x$ and $f(x)$ are now vectors, and $J^{-1}$ is the inverse Jacobian matrix. In general, the Jacobian is not a square matrix, and we use the generalized inverse $(J^TJ)^{-1}J^T$ instead, giving\n$$\nx_{n+1} = x_n - (J^TJ)^{-1}J^T f(x_n)\n$$\n\nIn multivariate nonlinear estimation problems, we can find the vector of parameters $\\beta$ by minimizing the residuals $r(\\beta)$, \n$$\n\\beta_{n+1} = \\beta_n - (J^TJ)^{-1}J^T r(\\beta_n)\n$$\nwhere the entries of the Jacobian matrix $J$ are\n$$\nJ_{ij} = \\frac{\\partial r_i(\\beta)}{\\partial \\beta_j}\n$$\n\n## Inverse Quadratic Interpolation\n\nInverse quadratic interpolation is a type of polynomial interpolation. Polynomial interpolation simply means we find the polynomial of least degree that fits a set of points. In quadratic interpolation, we use three points, and find the quadratic polynomial that passes through those three points. \n\n\n```python\n\ndef f(x):\n return (x - 2) * x * (x + 2)**2\n\n\nx = np.arange(-5,5, 0.1);\nplt.plot(x, f(x))\nplt.xlim(-3.5, 0.5)\nplt.ylim(-5, 16)\nplt.xlabel('x')\nplt.axhline(0)\nplt.title(\"Quadratic Interpolation\")\n\n#First Interpolation\nx0=np.array([-3,-2.5,-1.0])\ny0=f(x0)\nf2 = interp1d(x0, y0,kind='quadratic')\n\n#Plot parabola\nxs = np.linspace(-3, -1, num=10000, endpoint=True)\nplt.plot(xs, f2(xs))\n\n#Plot first triplet\nplt.plot(x0, f(x0),'ro');\nplt.scatter(x0, f(x0), s=50, c='yellow');\n\n#New x value\nxnew=xs[np.where(abs(f2(xs))==min(abs(f2(xs))))]\n\nplt.scatter(np.append(xnew,xnew), np.append(0,f(xnew)), c='black');\n\n#New triplet\nx1=np.append([-3,-2.5],xnew)\ny1=f(x1)\nf2 = interp1d(x1, y1,kind='quadratic')\n\n#New Parabola\nxs = np.linspace(min(x1), max(x1), num=100, endpoint=True)\nplt.plot(xs, f2(xs))\n\nxnew=xs[np.where(abs(f2(xs))==min(abs(f2(xs))))]\nplt.scatter(np.append(xnew,xnew), np.append(0,f(xnew)), c='green');\n\n\n```\n\nSo that's the idea behind quadratic interpolation. Use a quadratic approximation, find the zero of interest, use that as a new point for the next quadratic approximation.\n\n\nInverse quadratic interpolation means we do quadratic interpolation on the *inverse function*. So, if we are looking for a root of $f$, we approximate $f^{-1}(x)$ using quadratic interpolation. This just means fitting $x$ as a function of $y$, so that the quadratic is turned on its side and we are guaranteed that it cuts the x-axis somewhere. Note that the secant method can be viewed as a *linear* interpolation on the inverse of $f$. We can write:\n\n$$f^{-1}(y) = \\frac{(y-f(x_n))(y-f(x_{n-1}))}{(f(x_{n-2})-f(x_{n-1}))(f(x_{n-2})-f(x_{n}))}x_{n-2} + \\frac{(y-f(x_n))(y-f(x_{n-2}))}{(f(x_{n-1})-f(x_{n-2}))(f(x_{n-1})-f(x_{n}))}x_{n-1} + \\frac{(y-f(x_{n-2}))(y-f(x_{n-1}))}{(f(x_{n})-f(x_{n-2}))(f(x_{n})-f(x_{n-1}))}x_{n-1}$$\n\nWe use the above formula to find the next guess $x_{n+1}$ for a zero of $f$ (so $y=0$):\n\n$$x_{n+1} = \\frac{f(x_n)f(x_{n-1})}{(f(x_{n-2})-f(x_{n-1}))(f(x_{n-2})-f(x_{n}))}x_{n-2} + \\frac{f(x_n)f(x_{n-2})}{(f(x_{n-1})-f(x_{n-2}))(f(x_{n-1})-f(x_{n}))}x_{n-1} + \\frac{f(x_{n-2})f(x_{n-1})}{(f(x_{n})-f(x_{n-2}))(f(x_{n})-f(x_{n-1}))}x_{n}$$\n\nWe aren't so much interested in deriving this as we are understanding the procedure:\n\n\n\n\n\n```python\nx = np.arange(-5,5, 0.1);\nplt.plot(x, f(x))\nplt.xlim(-3.5, 0.5)\nplt.ylim(-5, 16)\nplt.xlabel('x')\nplt.axhline(0)\nplt.title(\"Inverse Quadratic Interpolation\")\n\n#First Interpolation\nx0=np.array([-3,-2.5,1])\ny0=f(x0)\nf2 = interp1d(y0, x0,kind='quadratic')\n\n#Plot parabola\nxs = np.linspace(min(f(x0)), max(f(x0)), num=10000, endpoint=True)\nplt.plot(f2(xs), xs)\n\n#Plot first triplet\nplt.plot(x0, f(x0),'ro');\nplt.scatter(x0, f(x0), s=50, c='yellow');\n```\n\nConvergence rate is approximately $1.8$. The advantage of the inverse method is that we will *always* have a real root (the parabola will always cross the x-axis). A serious disadvantage is that the initial points must be very close to the root or the method may not converge.\n\nThat is why it is usually used in conjunction with other methods.\n\n## Brentq Method\n\nBrent's method is a combination of bisection, secant and inverse quadratic interpolation. Like bisection, it is a 'bracketed' method (starts with points $(a,b)$ such that $f(a)f(b)<0$.\n\nRoughly speaking, the method begins by using the secant method to obtain a third point $c$, then uses inverse quadratic interpolation to generate the next possible root. Without going into too much detail, the algorithm attempts to assess when interpolation will go awry, and if so, performs a bisection step. Also, it has certain criteria to reject an iterate. If that happens, the next step will be linear interpolation (secant method). \n\nTo find zeros, use \n\n\n```python\nx = np.arange(-5,5, 0.1);\np1=plt.plot(x, f(x))\nplt.xlim(-4, 4)\nplt.ylim(-10, 20)\nplt.xlabel('x')\nplt.axhline(0)\npass\n```\n\n\n```python\nfrom scipy import optimize\n```\n\n\n```python\nscipy.optimize.brentq(f,-1,.5)\n```\n\n\n\n\n -7.864845203343107e-19\n\n\n\n\n```python\nscipy.optimize.brentq(f,.5,3)\n```\n\n\n\n\n 2.0\n\n\n\n## Roots of polynomials\n\nOne method for finding roots of polynomials converts the problem into an eigenvalue one by using the **companion matrix** of a polynomial. For a polynomial \n\n$$\np(x) = a_0 + a_1x + a_2 x^2 + \\ldots + a_m x^m\n$$\n\nthe companion matrix is\n\n$$\nA = \\begin{bmatrix}\n-a_{m-1}/a_m & -a_{m-2}/a_m & \\ldots & -a_0/a_m \\\\\n1 & 0 & \\ldots & 0 \\\\\n0 & 1 & \\ldots & 0 \\\\\n\\vdots & \\vdots & \\ldots & \\vdots \\\\\n0 & 0 & \\ldots & 0\n\\end{bmatrix}\n$$\n\nThe characteristic polynomial of the companion matrix is $\\lvert \\lambda I - A \\rvert$ which expands to \n\n$$\na_0 + a_1 \\lambda + a_2 \\lambda^2 + \\ldots + a_m \\lambda^m\n$$\n\nIn other words, the roots we are seeking are the eigenvalues of the companion matrix.\n\nFor example, to find the cube roots of unity, we solve $x^3 - 1 = 0$. The `roots` function uses the companion matrix method to find roots of polynomials.\n\n\n```python\n# Coefficients of $x^3, x^2, x^1, x^0$\n\npoly = np.array([1, 0, 0, -1])\n```\n\nManual construction\n\n\n```python\nA = np.array([\n [0,0,1],\n [1,0,0],\n [0,1,0]\n])\n```\n\n\n```python\nscipy.linalg.eigvals(A)\n```\n\n\n\n\n array([-0.5+0.8660254j, -0.5-0.8660254j, 1. +0.j ])\n\n\n\nUsing built-in function\n\n\n```python\nx = np.roots(poly)\nx\n```\n\n\n\n\n array([-0.5+0.8660254j, -0.5-0.8660254j, 1. +0.j ])\n\n\n\n\n```python\nplt.scatter([z.real for z in x], [z.imag for z in x])\ntheta = np.linspace(0, 2*np.pi, 100)\nu = np.cos(theta)\nv = np.sin(theta)\nplt.plot(u, v, ':')\nplt.axis('square')\npass\n```\n\n## Using `scipy.optimize`\n\n### Finding roots of univariate equations\n\n\n```python\ndef f(x):\n return x**3-3*x+1\n```\n\n\n```python\nx = np.linspace(-3,3,100)\nplt.axhline(0, c='red')\nplt.plot(x, f(x))\npass\n```\n\n\n```python\nfrom scipy.optimize import brentq, newton\n```\n\n#### `brentq` is the recommended method\n\n\n```python\nbrentq(f, -3, 0), brentq(f, 0, 1), brentq(f, 1,3)\n```\n\n\n\n\n (-1.8793852415718166, 0.3472963553337031, 1.532088886237956)\n\n\n\n#### Secant method\n\n\n```python\nnewton(f, -3), newton(f, 0), newton(f, 3)\n```\n\n\n\n\n (-1.8793852415718166, 0.34729635533385395, 1.5320888862379578)\n\n\n\n#### Newton-Raphson method\n\n\n```python\nfprime = lambda x: 3*x**2 - 3\nnewton(f, -3, fprime), newton(f, 0, fprime), newton(f, 3, fprime)\n```\n\n\n\n\n (-1.8793852415718166, 0.34729635533386066, 1.532088886237956)\n\n\n\n### Finding fixed points\n\nFinding the fixed points of a function $g(x) = x$ is the same as finding the roots of $g(x) - x$. However, specialized algorithms also exist - e.g. using `scipy.optimize.fixedpoint`.\n\n\n```python\nfrom scipy.optimize import fixed_point\n```\n\n\n```python\nx = np.linspace(-3,3,100)\nplt.plot(x, f(x), color='red')\nplt.plot(x, x)\npass\n```\n\n\n```python\nfixed_point(f, 0), fixed_point(f, -3), fixed_point(f, 3)\n```\n\n\n\n\n (array(0.25410169), array(-2.11490754), array(1.86080585))\n\n\n\n### Mutlivariate roots and fixed points\n\nUse `root` to solve polynomial equations. Use `fsolve` for non-polynomial equations.\n\n\n```python\nfrom scipy.optimize import root, fsolve\n```\n\nSuppose we want to solve a sysetm of $m$ equations with $n$ unknowns\n\n\\begin{align}\nf(x_0, x_1) &= x_1 - 3x_0(x_0+1)(x_0-1) \\\\\ng(x_0, x_1) &= 0.25 x_0^2 + x_1^2 - 1\n\\end{align}\n\nNote that the equations are non-linear and there can be multiple solutions. These can be interpreted as fixed points of a system of differential equations.\n\n\n```python\ndef f(x):\n return [x[1] - 3*x[0]*(x[0]+1)*(x[0]-1),\n .25*x[0]**2 + x[1]**2 - 1]\n```\n\n\n```python\nsol = root(f, (0.5, 0.5))\nsol.x\n```\n\n\n\n\n array([1.11694147, 0.82952422])\n\n\n\n\n```python\nfsolve(f, (0.5, 0.5))\n```\n\n\n\n\n array([1.11694147, 0.82952422])\n\n\n\n\n```python\nr0 = root(f,[1,1])\nr1 = root(f,[0,1])\nr2 = root(f,[-1,1.1])\nr3 = root(f,[-1,-1])\nr4 = root(f,[2,-0.5])\n\nroots = np.c_[r0.x, r1.x, r2.x, r3.x, r4.x]\n```\n\n\n```python\nY, X = np.mgrid[-3:3:100j, -3:3:100j]\nU = Y - 3*X*(X + 1)*(X-1)\nV = .25*X**2 + Y**2 - 1\n\nplt.streamplot(X, Y, U, V, color=U, linewidth=2, cmap=plt.cm.autumn)\nplt.scatter(roots[0], roots[1], s=50, c='none', edgecolors='k', linewidth=2)\npass\n```\n\n#### We can also give the Jacobian\n\n\n```python\ndef jac(x):\n return [[-6*x[0], 1], [0.5*x[0], 2*x[1]]]\n```\n\n\n```python\nsol = root(f, (0.5, 0.5), jac=jac)\nsol.x, sol.fun\n```\n\n\n\n\n (array([1.11694147, 0.82952422]), array([-4.23383550e-12, -3.31612515e-12]))\n\n\n\n#### Check that values found are really roots\n\n\n\n```python\nnp.allclose(f(sol.x), 0)\n```\n\n\n\n\n True\n\n\n\n#### Starting from other initial conditions, different roots may be found\n\n\n```python\nsol = root(f, (12,12))\nsol.x\n```\n\n\n\n\n array([ 0.77801314, -0.92123498])\n\n\n\n\n```python\nnp.allclose(f(sol.x), 0)\n```\n\n\n\n\n True\n\n\n", "meta": {"hexsha": "2e0287644eebd36d254189244326ba7f6ab33da8", "size": 331066, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/copies/lectures/T07B_Root_Finding.ipynb", "max_stars_repo_name": "robkravec/sta-663-2021", "max_stars_repo_head_hexsha": "4dc8018f7b172eaf81da9edc33174768ff157939", "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/copies/lectures/T07B_Root_Finding.ipynb", "max_issues_repo_name": "robkravec/sta-663-2021", "max_issues_repo_head_hexsha": "4dc8018f7b172eaf81da9edc33174768ff157939", "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/copies/lectures/T07B_Root_Finding.ipynb", "max_forks_repo_name": "robkravec/sta-663-2021", "max_forks_repo_head_hexsha": "4dc8018f7b172eaf81da9edc33174768ff157939", "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": 236.8140200286, "max_line_length": 75264, "alphanum_fraction": 0.9139960008, "converted": true, "num_tokens": 6993, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625069680098, "lm_q2_score": 0.9184802362152842, "lm_q1q2_score": 0.8555299034256585}} {"text": "## Reminders\n\n### Conditional Probability\n\n$$\np(x \\mid y) = \\frac{p(x, y)}{p(y)}\n$$\n\n### Bayes' Rule\n\n$\n\\begin{align}\np(x \\mid y) &= \\frac{p(y \\mid x)p(x)}{p(y)} \\\\\n &= \\frac{p(y \\mid x)p(x)}{\\int_x p(y \\mid x)p(x)}\n\\end{align}\n$\n\nPosterior, likelihood and prior:\n\n$\nPosterior = \\frac{Likelihood \\cdot Prior}{Normalizer}\n$\n\n### Frequentist Perspective on Probability\nIf we were to repeat the same experiment many times, in the limit, the frequency of the event would approach the given probability.\n\n### Bayesian Perspective on Probability\nProbability is a reasonable guess based on our degree of belief about the environment.\n\n### Independence\n$$\n\\text{x and y are independent} \\iff p(x, y) = kf(x)g(y)\n$$\n\n### Conditional Independence\n\n$$\nX \\ci Y \\mid Z\n$$\n\ndenotes that random variables $X$ and $Y$ are independent provided that we know the state of $Z$.\n\n$$\nX \\ci Y \\mid Z \\iff p(X, Y \\mid Z) = p(X \\mid Z)p(Y \\mid Z)\n$$\n\n1. If $Z = \\varnothing$, then $X$ and $Y$ are (unconditionally) independent.\n2. It may be the case that $X$ and $Y$ are not independent, but $X$ and $Y$ are conditionally independent given $Z$.\n\nSee https://www.eecs.qmul.ac.uk/~norman/BBNs/Independence_and_conditional_independence.htm for examples on conditional independence.\n", "meta": {"hexsha": "cde211692a89bec79b032c4718a50419a5bfaaf7", "size": 3981, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "BRML/notebooks/chapter1.ipynb", "max_stars_repo_name": "eozd/brml-notes", "max_stars_repo_head_hexsha": "46a14ae7ea22e9786a750b99293bea70c8a11af9", "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": "BRML/notebooks/chapter1.ipynb", "max_issues_repo_name": "eozd/brml-notes", "max_issues_repo_head_hexsha": "46a14ae7ea22e9786a750b99293bea70c8a11af9", "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": "BRML/notebooks/chapter1.ipynb", "max_forks_repo_name": "eozd/brml-notes", "max_forks_repo_head_hexsha": "46a14ae7ea22e9786a750b99293bea70c8a11af9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-03-23T00:44:06.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-23T00:44:06.000Z", "avg_line_length": 22.6193181818, "max_line_length": 138, "alphanum_fraction": 0.5300175835, "converted": true, "num_tokens": 370, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9591542840900507, "lm_q2_score": 0.8918110447190671, "lm_q1q2_score": 0.855384384141117}} {"text": "# Beautiful Mathematics Typesetting\n[Tex](https://en.wikipedia.org/wiki/TeX)\n\n[LaTex](https://www.latex-project.org/)\n\n[Motivating Examples](http://jupyter-notebook.readthedocs.io/en/latest/examples/Notebook/Typesetting%20Equations.html)\n\n### The Lorenz Equations\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\\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### The Cauchy-Schwarz Inequality\n\\begin{equation*}\n\\left( \\sum_{k=1}^n a_k b_k \\right)^2 \\leq \\left( \\sum_{k=1}^n a_k^2 \\right) \\left( \\sum_{k=1}^n b_k^2 \\right)\n\\end{equation*}\n\\begin{equation*}\n\\left( \\sum_{k=1}^n a_k b_k \\right)^2 \\leq \\left( \\sum_{k=1}^n a_k^2 \\right) \\left( \\sum_{k=1}^n b_k^2 \\right)\n\\end{equation*}\n\n### Cross Product Formula\n\\begin{equation*}\n\\mathbf{V}_1 \\times \\mathbf{V}_2 = \\begin{vmatrix}\n\\mathbf{i} & \\mathbf{j} & \\mathbf{k} \\\\\n\\frac{\\partial X}{\\partial u} & \\frac{\\partial Y}{\\partial u} & 0 \\\\\n\\frac{\\partial X}{\\partial v} & \\frac{\\partial Y}{\\partial v} & 0\n\\end{vmatrix}\n\\end{equation*}\n\\begin{equation*}\n\\mathbf{V}_1 \\times \\mathbf{V}_2 = \\begin{vmatrix}\n\\mathbf{i} & \\mathbf{j} & \\mathbf{k} \\\\\n\\frac{\\partial X}{\\partial u} & \\frac{\\partial Y}{\\partial u} & 0 \\\\\n\\frac{\\partial X}{\\partial v} & \\frac{\\partial Y}{\\partial v} & 0\n\\end{vmatrix}\n\\end{equation*}\n\n### Probability of getting (k) heads when flipping (n) coins\n\\begin{equation*}\nP(E) = {n \\choose k} p^k (1-p)^{ n-k}\n\\end{equation*}\n\\begin{equation*}\nP(E) = {n \\choose k} p^k (1-p)^{ n-k}\n\\end{equation*}\n\n### Identity of Ramanujan\n[Srinivasa Ramanujan](https://en.wikipedia.org/wiki/Srinivasa_Ramanujan)\n\nSelf-taught, no formal training in mathematics, made contributions to:\n- mathematical analysis\n- number theory\n- infinite series\n- continued fractions\n\\begin{equation*}\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\\end{equation*}\n\\begin{equation*}\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\\end{equation*}\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\\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\n```\n", "meta": {"hexsha": "b15fa7b94eed4f2da824c49b2ab990b6120e1350", "size": 5839, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "numpy-data-science-essential-training/Ex_Files_NumPy_Data_EssT/Exercise Files/Ch 1/dashboard/Beautiful.ipynb", "max_stars_repo_name": "saint1729/in-learning", "max_stars_repo_head_hexsha": "fe58495846f05e2dcd15d1dbb6ff87535d35d6c5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-01-16T18:21:07.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-16T18:21:07.000Z", "max_issues_repo_path": "numpy-data-science-essential-training/Ex_Files_NumPy_Data_EssT/Exercise Files/Ch 1/dashboard/Beautiful.ipynb", "max_issues_repo_name": "saint1729/in-learning", "max_issues_repo_head_hexsha": "fe58495846f05e2dcd15d1dbb6ff87535d35d6c5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-05-09T07:13:52.000Z", "max_issues_repo_issues_event_max_datetime": "2017-06-12T05:24:08.000Z", "max_forks_repo_path": "numpy-data-science-essential-training/Ex_Files_NumPy_Data_EssT/Exercise Files/Ch 1/dashboard/Beautiful.ipynb", "max_forks_repo_name": "saint1729/in-learning", "max_forks_repo_head_hexsha": "fe58495846f05e2dcd15d1dbb6ff87535d35d6c5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-09-03T14:17:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-03T14:17:00.000Z", "avg_line_length": 26.0669642857, "max_line_length": 211, "alphanum_fraction": 0.4714848433, "converted": true, "num_tokens": 1245, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9711290905469752, "lm_q2_score": 0.8807970873650401, "lm_q1q2_score": 0.8553676744092361}} {"text": "# Knapsack problem\n\n## Definition\n\nWe assume that the there is a knapsack with a volume $b>=0$, and a set of items with which the kanpsack is filled. Every item has it's own volume $a_j>=0$ and value $c_j>=0$.\nThe goal is to fill the most valuable knapsack so that the sum of all items inside is the maximum possible, without going over the knapsack's volume.\n\nThe following definition is given for the **Unbounded Knapsack problem (UKP)** which places no upper bound on the number of copies of each kind of item and can be formulated as below except for that the only restriction is that the number of items in the solution must be non-negative integers.\n\n\n\n\\begin{equation}\nmax\\sum_{j=1}^n c_jx_j\\\\\n\\sum_{j=1}^n a_jx_j \\le b\\\\\nx_1,x_2,...,x_n \\in Z,\\; x_j\\ge0\n\\end{equation}\n\n\nA more common occurence of this problem is in a form of **0-1 Knapsack Problem**, which restricts the number of copies of one kind of item to zero or one $x_j\\in\\{0,1\\}$.\n\n## Applications\n\nThe name \"knapsack problem\" dates back to the early works of the mathematician Tobias Dantzig (1884–1956), and refers to the commonplace problem of packing the most valuable or useful items without overloading the luggage.\n\n\n\nKnapsack problem (KP) has broad applications in different fields such as\nmachine scheduling, space allocation, and asset optimization. Meanwhile, it is a hard\nproblem due to its computational complexity, but numerous solution approaches have\nbeen developed for a variety of KP. \n\nThe problem often arises in resource allocation where the decision makers have to choose from a set of non-divisible projects or tasks under a fixed budget or time constraint, respectively. Problems like these arise in a wide variety of fields, such as finding the least wasteful way to cut raw materials, selection of investments and portfolios, and generating keys for the Merkle–Hellman and other knapsack cryptosystems.\n\n\n\n## Solution\n\n### Recursive solution\n- The problem is solved by dividing it into stages\n- We are introducing a helper function $F$ defined like following which we will solve with the recursive formulas below:\n$F_k=max\\{c_1 x_1 + ... + c_k x_k \\:|\\: a_1 x_1 + ... + a_k x_k \\le y,\\;x_1,...,x_k\\ge0,\\;x_1,...,x_k\\in Z\\}$\n\n#### Backward solution:\nWe need to rememer all the steps of the solution in order to reach the final solution.\n
    \n
  • $F_1(y)=c_1\\lfloor\\frac{y}{a_1}\\rfloor$
  • \n
  • $F_k(y)=max\\{F_{k-1}(y - a_k x_k) + c_k x_k \\:|\\: x_k \\in \\{0,1,...,\\lfloor \\frac{y}{a_k}\\rfloor\\}\\},\\; k\\ge2$
  • \n
\n\n#### Forward solution:\nEeasier to implement in computers and in comparison to the Backward solution only the last two rows of the table are need to be stored in memory.\n
    \n For forming of the k\\y table\n
  • $F_k(y)=-\\infty,\\;y<0$
  • \n
  • $F_1(y)=c_1\\lfloor\\frac{y}{a_1}\\rfloor,\\;y\\ge0$
  • \n
  • $F_k(y)=max\\{F_{k-1}(y), F_{k}(y - a_k) + c_k\\},\\; k\\ge2$
  • \n
\n
    \n
  • \n This will store the highest index $j$ such that the $j$ variable in the optimal solution in F_k(y) is positive. If the optimal solution in $F_k(y)$ is $0$ we define this index $i$ with $0$.\n
    For forming of the i\\y table
    \n $\n i_k(y)=\n \\begin{cases}\n i_{k-1}(y)\\quad &,c_k+F_k(y)\n
  • \n We can reconstruct the optimal solution from the value reached for $i_n(y)$, by using the index and the corresponding values $i_n(b)$ and $i_n(b-a_{i_n(b)})$.\n $\n i_n(y)=\n \\begin{cases}\n k &,x_n=1,n=k\\\\\n \\ne k &,x_n=0,n\\ne k\\\\\n \\end{cases}\\\\\n i_n(b-a_{i_n(b)})=\n \\begin{cases}\n k\\quad &,x_k\\ge a_{i_n(b)}, \\text{testing for}\\; y-a_{i_n(b)}\\\\\n e\\quad &,x_e=1,x_{e+1}=0,x_k=1\\\\\n \\end{cases}\n $\n
  • \n
\n\n\n## Examples\n\n### Example 1\n\\begin{equation}\nmax\\;6x_1+7x_2+10x_3+4x_4+5x_5\\\\\n3x_1+4x_2+5x_3+2x_4+2x_5\\le9\\\\\nx\\in Z\n\\end{equation}\n\n##### Forward solution\nFirst we determine the capacities: $c_1=6, c_2=7, c_3=10, c_4=4, c_5=5, a_1=3, a_2=4 ,a_3=5, a_4=2, a_5=2$ \nNow we can form our tables $F_k(y)$ and $i_k(y)$ using the formulas from above to find $F_{max}$ and our optimum strategy for $x=(0,0,0,0,0)$: \n\n\n\n
\n\n| k\\y | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |\n|:---:|:-:|:-:|:-:|:-:|:--:|:--:|:--:|:--:|:--:|:--:|\n| 1 | 0 | 0 | 0 | 6 | 6 | 6 | 12 | 12 | 12 | 18 |\n| 2 | 0 | 0 | 0 | 6 | 7 | 7 | 12 | 13 | 14 | 18 |\n| 3 | 0 | 0 | 0 | 6 | 7 | 10 | 12 | 13 | 16 | 18 |\n| 3 | 0 | 0 | 4 | 6 | 8 | 10 | 12 | 14 | 16 | 18 |\n| 5 | 0 | 0 | 5 | 6 | 10 | 11 | 15 | 16 | 20 | 21 |\n\n        \n \n| i\\y | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |\n|:---:|:-:|:-:|:-:|:-:|:-:|:-:|:-:|:-:|:-:|:-:|\n| 1 | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 1 |\n| 2 | 0 | 0 | 0 | 1 | 2 | 2 | 1 | 2 | 2 | 1 |\n| 3 | 0 | 0 | 0 | 1 | 2 | 3 | 1 | 2 | 3 | 1 |\n| 3 | 0 | 0 | 4 | 1 | 4 | 3 | 1 | 4 | 3 | 1 |\n| 5 | 0 | 0 | 5 | 1 | 5 | 5 | 5 | 5 | 5 | 5 |\n\n
\nFinally, we can see that the maximum is reached for $F_5(9)=21 \\rightarrow F_{max}=21$
\nNow we need to form the maximum packing strategy.
\nWe look in the $i$ table to see what item (index) corresponds to the maximum in $F_5(9)$
\n$i_5(9)=5$ we add $1$ to the corresponding position in our $x=(0,0,0,0,0) \\rightarrow x=(0,0,0,0,1)$
\n
    \n
  1. $i_5(9-a_5)=i_5(9-2)=i_5(7)=5$, we add $1$ to the corresponding position in our $x=(0,0,0,0,1) \\rightarrow x=(0,0,0,0,2)$

  2. \n
  3. $i_5(7-a_5)=i_5(7-2)=i_5(5)=5$, we add $1$ to the corresponding position in our $x=(0,0,0,0,2) \\rightarrow x=(0,0,0,0,3)$

  4. \n
  5. $i_5(5-a_5)=i_5(5-2)=i_5(3)=1$, we add $1$ to the corresponding position in our $x=(0,0,0,0,3) \\rightarrow x=(1,0,0,0,3)$

  6. \n
  7. $i_5(3-a_5)=i_5(3-2)=i_5(1)=0 \\rightarrow$ we finished filling the solution.

  8. \n
\nMaximum solution: $F_{max}=21,\\;x=(1,0,0,0,3)$\n\n##### Backward solution\nWe form the general formula formula for the maximum possible set:\n
\n\n$$\n\\begin{aligned}\nF_5(9)&=max\\{5x_5+F_4(9-2x_5)|x_5\\in \\{0,1,2,3,4\\}\\} \\\\\n &=max\\{F_4(9), F_4(7)+5, F_4(5)+10, F_4(3)+15, F_4(1)+20\\}\\\\\n &\\qquad\\quad(1)\\qquad\\quad(2)\\qquad\\quad(3)\\quad\\qquad(4)\\quad\\qquad(5)\\\\\n\\end{aligned}\n\\\\\n-----------------------\n\\\\\n\\begin{aligned}\n(1)\\quad F_4(9)&=max\\{4x_4+F_3(9-2x_4)\\;|\\;x_4\\in \\{0,1,2,3,4\\}\\} \\\\\n &=max\\{F_3(9), F_3(7)+4, F_3(5)+8, F_3(3)+12, F_3(1)+16\\} \\\\\n &\\qquad\\quad(1.1)\\qquad(1.2)\\qquad(1.3)\\qquad(1.4)\\qquad(1.5)\\\\\n\\end{aligned}\\\\\n\\begin{aligned}\n(2)\\quad F_4(7)&=max\\{4x_4+F_3(7-2x_4)\\;|\\;x_4\\in \\{0,1,2,3\\}\\} \\\\\n &=max\\{F_3(7), F_3(5)+4, F_3(3)+8, F_3(1)+12\\} \\\\\n &\\qquad\\quad(2.1)\\qquad(2.2)\\qquad(2.3)\\qquad(2.4)\\\\\n\\end{aligned}\\\\\n\\begin{aligned}\n(3)\\quad F_4(5)&=max\\{4x_4+F_3(5-2x_4)\\;|\\;x_4\\in \\{0,1,2\\}\\} \\\\\n &=max\\{F_3(5), F_3(3)+4, F_3(1)+8\\} \\\\\n &\\qquad\\quad(3.1)\\qquad(3.2)\\qquad(3.3)\\\\\n\\end{aligned}\\\\\n\\begin{aligned}\n(4)\\quad F_4(3)&=max\\{4x_4+F_3(3-2x_4)\\;|\\;x_4\\in \\{0,1\\}\\} \\\\\n &=max\\{F_3(3), F_3(1)+4\\} \\\\\n &\\qquad\\quad(4.1)\\qquad(4.2)\\\\\n\\end{aligned}\\\\\n\\begin{aligned}\n(5)\\quad F_4(1)&=max\\{4x_4+F_3(1-2x_4)\\;|\\;x_4\\in \\{0\\}\\} \\\\\n &=max\\{F_3(1)\\} \\\\\n &\\qquad\\quad(5.1)\\\\\n\\end{aligned}\n\\\\\n-----------------------\n\\\\\n\\begin{aligned}\n(1.1)\\quad F_3(9)&=max\\{10x_3+F_2(9-5x_3)\\;|\\;x_3\\in \\{0,1\\}\\} \\\\\n &=max\\{F_2(9), F_2(4)+10\\} \\\\\n &\\qquad\\quad(1.1.1)\\quad(1.1.2)\\\\\n\\end{aligned}\\\\\n\\begin{aligned}\n(1.2)\\quad F_3(7)&=max\\{10x_3+F_2(7-5x_3)\\;|\\;x_3\\in \\{0,1\\}\\} \\\\\n &=max\\{F_2(7), F_2(2)+10\\} \\\\\n &\\qquad\\quad(1.2.1)\\quad(1.2.2)\\\\\n\\end{aligned}\\\\\n\\begin{aligned}\n(1.3)\\quad F_3(5)&=max\\{10x_3+F_2(5-5x_3)\\;|\\;x_3\\in \\{0,1\\}\\} \\\\\n &=max\\{F_2(5), F_2(0)+10\\} \\\\\n &\\qquad\\quad(1.3.1)\\quad(1.3.2)\\\\\n\\end{aligned}\\\\\n\\begin{aligned}\n(1.4)\\quad F_3(3)&=max\\{10x_3+F_2(3-5x_3)\\;|\\;x_3\\in \\{0\\}\\} \\\\\n &=max\\{F_2(3)\\} \\\\\n &\\qquad\\quad(1.4.1)\\\\\n\\end{aligned}\\\\\n\\begin{aligned}\n(1.5)\\quad F_3(1)&=max\\{10x_3+F_2(1-5x_3)\\;|\\;x_3\\in \\{0\\}\\} \\\\\n &=max\\{F_2(1)\\} \\\\\n &\\qquad\\quad(1.5.1)\\\\\n\\end{aligned}\n\\\\\n(1.2) \\Leftrightarrow (2.1)\\\\\n(1.3) \\Leftrightarrow (3.1) \\Leftrightarrow (2.2)\\\\\n(1.4) \\Leftrightarrow (4.1) \\Leftrightarrow (3.2) \\Leftrightarrow (2.3)\\\\\n(1.5) \\Leftrightarrow (5.1) \\Leftrightarrow (4.2) \\Leftrightarrow (3.3) \\Leftrightarrow (2.4)\n\\\\\n-----------------------\n\\\\\n\\begin{aligned}\n(1.1.1)\\quad F_2(9)&=max\\{7x_2+F_1(9-4x_2)\\;|\\;x_2\\in \\{0,1,2\\}\\} \\\\\n &=max\\{F_1(9), F_1(5)+7, F_1(1)+14\\} \\\\\n\\end{aligned}\\\\\n\\begin{aligned}\n(1.1.2)\\quad F_2(4)&=max\\{7x_2+F_1(4-4x_2)\\;|\\;x_2\\in \\{0,1\\}\\} \\\\\n &=max\\{F_1(4), F_1(0)+7\\} \\\\\n\\end{aligned}\\\\\n\\begin{aligned}\n(1.2.1)\\quad F_2(7)&=max\\{7x_2+F_1(7-4x_2)\\;|\\;x_2\\in \\{0,1\\}\\} \\\\\n &=max\\{F_1(7), F_1(3)+7\\} \\\\\n\\end{aligned}\\\\\n\\begin{aligned}\n(1.2.2)\\quad F_2(2)&=max\\{7x_2+F_1(2-4x_2)\\;|\\;x_2\\in \\{0\\}\\} = max\\{F_1(2)\\} \\\\\n\\end{aligned}\\\\\n\\begin{aligned}\n(1.3.1)\\quad F_2(5)&=max\\{7x_2+F_1(5-4x_2)\\;|\\;x_2\\in \\{0,1\\}\\} \\\\\n &= max\\{F_1(5), F_1(1)+7\\} \\\\\n\\end{aligned}\\\\\n\\begin{aligned}\n(1.3.2)\\quad F_2(0)&=max\\{7x_2+F_1(0-4x_2)\\;|\\;x_2\\in \\{0\\}\\} = max\\{F_1(0)\\} \\\\\n\\end{aligned}\\\\\n\\begin{aligned}\n(1.4.1)\\quad F_2(3)&=max\\{7x_2+F_1(3-4x_2)\\;|\\;x_2\\in \\{0\\}\\} = max\\{F_1(3)\\} \\\\\n\\end{aligned}\\\\\n\\begin{aligned}\n(1.5.1)\\quad F_2(1)&=max\\{7x_2+F_1(1-4x_2)\\;|\\;x_2\\in \\{0\\}\\} = max\\{F_1(1)\\} \\\\\n\\end{aligned}\\\\\n\\\\\n-----------------------\n\\\\\n\\begin{aligned}\n&F_1(0) = c1*\\lfloor\\frac{y}{a_1}\\rfloor = 6*\\lfloor\\frac{0}{3}\\rfloor = 0\\\\\n\\dots \\\\\n&F_1(3) = 6*\\lfloor\\frac{3}{3}\\rfloor = 6\\\\\n\\dots \\\\\n&F_1(6) = 6*\\lfloor\\frac{6}{3}\\rfloor = 12\\\\\n\\dots \\\\\n&F_1(9) = 6*\\lfloor\\frac{9}{3}\\rfloor = 18\\\\\n\\end{aligned}\n$$\n\n
\nNow we can start going back through the recursive calls until, finding maximum values for each step. Looking for when the maximum values are hit, because that will tell us what element should be included in the maximum solution.\n
\n\n$$\n\\begin{aligned}\n(1.1.1)\\quad F_2(9)&=max\\{F_1(9), F_1(5)+7, F_1(1)+14\\} \\\\\n &=max\\{18, 6+7, 0+14\\} = 18\\\\\n\\end{aligned}\\\\\n\\begin{aligned}\n(1.1.2)\\quad F_2(4)&=max\\{F_1(4), F_1(0)+7\\} \\\\\n &=max\\{6, 0+7\\} = 7\\\\\n\\end{aligned}\\\\\n\\begin{aligned}\n(1.2.1)\\quad F_2(7)&=max\\{F_1(7), F_1(3)+7\\} \\\\\n &=max\\{12, 6+7\\} = 13 \\\\\n\\end{aligned}\\\\\n\\begin{aligned}\n(1.2.2)\\quad F_2(2)&=max\\{F_1(2)\\} = F_1(2) = 0 \\\\\n\\end{aligned}\\\\\n\\begin{aligned}\n(1.3.1)\\quad F_2(5)&=max\\{F_1(5), F_1(1)+7\\} \\\\\n &=max\\{6, 7\\} = 7 \\\\\n\\end{aligned}\\\\\n\\begin{aligned}\n(1.3.2)\\quad F_2(0)&=max\\{F_1(0)\\} = F_1(0) = 0 \\\\\n\\end{aligned}\\\\\n\\begin{aligned}\n(1.4.1)\\quad F_2(3)&=max\\{F_1(3)\\} = F_1(3) = 6 \\\\\n\\end{aligned}\\\\\n\\begin{aligned}\n(1.5.1)\\quad F_2(1)&=max\\{F_1(1)\\} = F_1(1) = 0 \\\\\n\\end{aligned}\\\\\n\\\\\n-----------------------\n\\\\\n\\begin{aligned}\n(1.1)\\quad F_3(9)&=max\\{F_2(9), F_2(4)+10\\} \\\\\n &=max\\{18, 7+10\\} = 18 \\\\\n\\end{aligned}\\\\\n\\begin{aligned}\n(1.2)\\quad F_3(7)&=max\\{F_2(7), F_2(2)+10\\} \\\\\n &=max\\{13, 0+10\\} = 13\\\\\n\\end{aligned}\\\\\n\\begin{aligned}\n(1.3)\\quad F_3(5)&=max\\{F_2(5), F_2(0)+10\\} \\\\\n &=max\\{7, 0+10\\} = 10 \\\\\n\\end{aligned}\\\\\n\\begin{aligned}\n(1.4)\\quad F_3(3)&=max\\{F_2(3)\\} = F_2(3) = 6 \\\\\n\\end{aligned}\\\\\n\\begin{aligned}\n(1.5)\\quad F_3(1)&=max\\{F_2(1)\\} = F_2(1) = 0\\\\\n\\end{aligned}\n\\\\\n-----------------------\n\\\\\n\\begin{aligned}\n(1)\\quad F_4(9)&=max\\{F_3(9), F_3(7)+4, F_3(5)+8, F_3(3)+12, F_3(1)+16\\} \\\\\n &=max\\{18, 13+4, 10+8, 6+12, 0+16\\} = 18 \\\\\n\\end{aligned}\\\\\n\\begin{aligned}\n(2)\\quad F_4(7)&=max\\{F_3(7), F_3(5)+4, F_3(3)+8, F_3(1)+12\\} \\\\\n &=max\\{13, 10+4, 6+8, 0+12\\} = 14 \\\\\n\\end{aligned}\\\\\n\\begin{aligned}\n(3)\\quad F_4(5)&=max\\{F_3(5), F_3(3)+4, F_3(1)+8\\} \\\\\n &=max\\{10, 6+4, 0+8\\} = 10 \\\\\n\\end{aligned}\\\\\n\\begin{aligned}\n(4)\\quad F_4(3)&=max\\{F_3(3), F_3(1)+4\\} \\\\\n &=max\\{6, 0+4\\} = 6 \\\\\n\\end{aligned}\\\\\n\\begin{aligned}\n(5)\\quad F_4(1)&=max\\{F_3(1)\\} = F_3(1) = 0\\\\\n\\end{aligned}\n\\\\\n-----------------------\n\\\\\n\\text{Finally:}\n\\begin{aligned}\nF_5(9)&=max\\{4x_4+F_3(9-2x_4)\\;|\\;x_4\\in \\{0,1,2,3,4\\}\\} \\\\\n &=max\\{F_4(9), F_4(7)+5, F_4(5)+10, F_4(3)+15, F_4(1)+20\\}\\\\\n &=max\\{18, 14+5, 10+10, 6+15, 0+20\\}\\\\\n &=max\\{18, 19, 20, 21, 20\\}\\\\\n &=21\n\\end{aligned}\n$$\n\n
\nMaximum value reached is in $F_5(9) = 21$ and has been reached for $x_5 = 3$ from $F_4(3)$, which gets its maximum value in $x_4 = 0$ from $F_3(3)$, which gets its maximum value in $x_3 = 0$ from $F_2(3)$, which gets its maximum value in $x_2 = 0$ from $F_1(3)$, which gets its maximum value in $x_1 = 1.$\n
\n$\n\\begin{aligned}\nF_5(9)&=max\\{F_4(9), F_4(7)+5, F_4(5)+10, F_4(3)+15, F_4(1)+20\\}\\\\\n &=max\\{18, 19, 20, 21, 20\\}\\\\\n &=21\n\\end{aligned}\n\\rightarrow\n\\begin{aligned}\nF_4(3)&=max\\{F_3(3), F_3(1)+4\\} \\\\\n &=max\\{6, 0+4\\} = 6 \\\\\n\\end{aligned}\\\\\n\\rightarrow\n\\begin{aligned}\nF_3(3)&=max\\{F_2(3)\\} = F_2(3) = 6\n\\end{aligned}\n\\rightarrow\n\\begin{aligned}\nF_2(3)&=max\\{F_1(3)\\} = F_1(3) = 6\n\\end{aligned}\n\\rightarrow\n\\begin{aligned}\nF_1(3) = 6 \\\\\n\\end{aligned}\n\\\\\n$\n
\nMaximum solution: $F_{max}=21,\\;x=(1,0,0,0,3)$\n\n### Example 2\n\\begin{equation}\nmax\\;10x_1+40x_2+30x_3+50x_4\\\\\n5x_1+4x_2+6x_3+3x_4\\le11\\\\\nx\\in Z\n\\end{equation}\n\n##### Forward solution\nFirst we determine the capacities: $c_1=10, c_2=40,c_3=30,c_4=50,a_1=5,a_2=4,a_3=6,a_4=3$ \nNow we can form our tables $F_k(y)$ and $i_k(y)$ using the formulas from above to find $F_{max}$ and our optimum strategy for $x=(0,0,0,0)$:\n\n\n\n
\n\n| k\\y | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 |\n|:---:|:-:|:-:|:-:|:--:|:--:|:--:|:---:|:---:|:---:|:---:|:---:|:---:|\n| 1 | 0 | 0 | 0 | 0 | 0 | 10 | 10 | 10 | 10 | 10 | 20 | 20 |\n| 2 | 0 | 0 | 0 | 0 | 40 | 40 | 40 | 40 | 80 | 80 | 80 | 80 |\n| 3 | 0 | 0 | 0 | 0 | 40 | 40 | 40 | 40 | 80 | 80 | 80 | 80 |\n| 4 | 0 | 0 | 0 | 50 | 50 | 50 | 100 | 100 | 100 | 150 | 150 | 150 |\n\n        \n\n| i\\y | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 |\n|:---:|:-:|:-:|:-:|:-:|:-:|:-:|:-:|:-:|:-:|:-:|:--:|:--:|\n| 1 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 1 |\n| 2 | 0 | 0 | 0 | 0 | 2 | 2 | 2 | 2 | 2 | 2 | 2 | 2 |\n| 3 | 0 | 0 | 0 | 0 | 2 | 2 | 2 | 2 | 2 | 2 | 2 | 2 |\n| 4 | 0 | 0 | 0 | 4 | 4 | 4 | 4 | 4 | 4 | 4 | 4 | 4 |\n\n
\nFinally, we can see that the maximum is reached for $F_4(9)=150 \\rightarrow F_{max}=150$
\nNow we need to form the maximum packing strategy.
\nWe look in the $i$ table to see what item (index) corresponds to the maximum in $F_4(9)$
\n$i_4(9)=4$ we add $1$ to the corresponding position in our $x=(0,0,0,0) \\rightarrow x=(0,0,0,1)$
\n
    \n
  1. $i_4(9-a_4)=i_4(9-3)=i_4(6)=4$, we add $1$ to the corresponding position in our $x=(0,0,0,1) \\rightarrow x=(0,0,0,2)$

  2. \n
  3. $i_4(6-a_4)=i_4(6-3)=i_4(3)=4$, we add $1$ to the corresponding position in our $x=(0,0,0,2) \\rightarrow x=(0,0,0,3)$

  4. \n
  5. $i_4(3-a_4)=i_4(3-3)=i_4(0)=0 \\rightarrow$ we finished filling the solution.

  6. \n
\nMaximum solution: $F_{max}=150,\\;x=(0,0,0,3)$\n\n##### Backward solution\nWe form the general formula formula for the maximum possible set:\n
\n\n$$\n\\begin{aligned}\nF_4(11)&=max\\{50x_4+F_3(11-3x_3)\\;|\\;x_4\\in \\{0,1,2,3\\}\\} \\\\\n &=max\\{F_3(11), F_3(8)+50, F_3(5)+100, F_3(2)+150\\}\\\\\n &\\qquad\\qquad(1)\\qquad\\quad(2)\\qquad\\quad(3)\\qquad\\qquad(4)\n\\end{aligned}\n\\\\\n-----------------------\n\\\\\n\\begin{aligned}\n(1)\\quad F_3(11)&=max\\{30x_3+F_2(11-6x_3)\\;|\\;x_3\\in \\{0,1\\}\\} \\\\\n &=max\\{F_2(11), F_2(5)+30\\} \\\\\n &\\qquad\\quad(1.1)\\qquad(1.2)\\\\\n\\end{aligned}\\\\\n\\begin{aligned}\n(2)\\quad F_3(8)&=max\\{30x_3+F_2(8-6x_3)\\;|\\;x_3\\in \\{0,1\\}\\} \\\\\n &=max\\{F_2(8), F_2(2)+30\\} \\\\\n &\\qquad\\quad(2.1)\\qquad(2.2)\\\\\n\\end{aligned}\\\\\n\\begin{aligned}\n(3)\\quad F_3(5)&=max\\{30x_3+F_2(5-6x_3)\\;|\\;x_3\\in \\{0\\}\\} \\\\\n &=max\\{F_2(5)\\} \\\\\n &\\qquad\\quad(3.1)\\\\\n\\end{aligned}\\\\\n\\begin{aligned}\n(4)\\quad F_3(2)&=max\\{30x_3+F_2(2-6x_3)\\;|\\;x_3\\in \\{0\\}\\} \\\\\n &=max\\{F_2(2)\\}\\\\\n &\\qquad\\quad(3.1)\\\\\n\\end{aligned}\n\\\\\n-----------------------\n\\\\\n\\begin{aligned}\n(1.1)\\quad \nF_2(11)&=max\\{40x_2+F_1(11-4x_2)\\;|\\;x_2\\in \\{0,1,2\\}\\} \\\\\n &=max\\{F_1(11), F_1(7)+40, F_1(3)+80\\} \\\\\n\\end{aligned}\n\\\\\n\\begin{aligned}\n(1.2)\\quad \nF_2(5)&=max\\{40x_2+F_1(5-4x_2)\\;|\\;x_2\\in \\{0,1\\}\\} \\\\\n &=max\\{F_1(5), F_1(1)+40\\} \\\\\n\\end{aligned}\n\\\\\n\\begin{aligned}\n(2.1)\\quad \nF_2(8)&=max\\{40x_2+F_1(8-4x_2)\\;|\\;x_2\\in \\{0,1,2\\}\\} \\\\\n &=max\\{F_1(8), F_1(4)+40, F_1(0)+80\\} \\\\\n\\end{aligned}\n\\\\\n\\begin{aligned}\n(2.2)\\quad \nF_2(2)&=max\\{40x_2+F_1(2-4x_2)\\;|\\;x_2\\in \\{0\\}\\} \\\\\n &=max\\{F_1(2)\\} \\\\\n\\end{aligned}\n\\\\\n\\begin{aligned}\n(3.1)\\quad \nF_2(5)&=max\\{40x_2+F_1(5-4x_2)\\;|\\;x_2\\in \\{0,1\\}\\} \\\\\n &=max\\{F_1(5), F_1(1)+40\\} \\\\\n\\end{aligned}\n\\\\\n\\begin{aligned}\n(4.1)\\quad \nF_2(2)&=max\\{40x_2+F_1(2-4x_2)\\;|\\;x_2\\in \\{0\\}\\} \\\\\n &=max\\{F_1(2)\\} \\\\\n\\end{aligned}\n\\\\\n-----------------------\n\\\\\n\\begin{aligned}\n&F_1(0) = c1*\\lfloor\\frac{y}{a_1}\\rfloor = 10*\\lfloor\\frac{0}{5}\\rfloor = 0\\\\\n\\dots \\\\\n&F_1(5) = 10*\\lfloor\\frac{5}{5}\\rfloor = 10\\\\\n\\dots \\\\\n&F_1(10) = 10*\\lfloor\\frac{10}{5}\\rfloor = 20\\\\\n&F_1(11) = 20\\\\\n\\end{aligned}\n$$\n\n
\nNow we can start going back through the recursive calls until, finding maximum values for each step. Looking for when the maximum values are hit, because that will tell us what element should be included in the maximum solution.\n
\n\n$$\n\\begin{aligned}\n(1.1)\\quad \nF_2(11)&=max\\{F_1(11), F_1(7)+40, F_1(3)+80\\} \\\\\n &=max\\{20, 10+40, 0+80\\} = 80\\\\\n\\end{aligned}\n\\\\\n\\begin{aligned}\n(1.2)\\quad \nF_2(5)&=max\\{F_1(5), F_1(1)+40\\} \\\\\n &=max\\{10, 40\\} = 40\\\\\n\\end{aligned}\n\\\\\n\\begin{aligned}\n(2.1)\\quad \nF_2(8)&=max\\{F_1(8), F_1(4)+40, F_1(0)+80\\} \\\\\n &=max\\{10, 0+40, 0+80\\} = 80 \\\\\n\\end{aligned}\n\\\\\n\\begin{aligned}\n(2.2)\\quad \nF_2(2)&=max\\{F_1(2)\\} = F_1(2) = 0 \\\\\n\\end{aligned}\n\\\\\n\\begin{aligned}\n(3.1)\\quad \nF_2(5)&= 40\\; \\text{(calculated above)} \\\\\n\\end{aligned}\n\\\\\n\\begin{aligned}\n(4.1)\\quad \nF_2(2)&= 0\\; \\text{(calculated above)}\\\\\n\\end{aligned}\n\\\\\n\\\\\n-----------------------\n\\\\\n\\begin{aligned}\n(1)\\quad F_3(11)&=max\\{F_2(11), F_2(5)+30\\} \\\\\n &=max\\{80, 40+30\\} = 80 \\\\\n\\end{aligned}\\\\\n\\begin{aligned}\n(2)\\quad F_3(8)&=max\\{F_2(8), F_2(2)+30\\} \\\\\n &=max\\{80, 0+30\\} = 80 \\\\\n\\end{aligned}\\\\\n\\begin{aligned}\n(3)\\quad F_3(5)&=max\\{F_2(5)\\} = F_2(5) = 40\\\\\n\\end{aligned}\\\\\n\\begin{aligned}\n(4)\\quad F_3(2)&=max\\{F_2(2)\\} = F_2(2) = 0 \\\\\n\\end{aligned}\n\\\\\n\\\\\n-----------------------\n\\\\\n\\text{Finally:}\n\\begin{aligned}\nF_4(11)&=max\\{50x_4+F_3(11-3x_3)\\;|\\;x_4\\in \\{0,1,2,3\\}\\} \\\\\n &=max\\{F_3(11), F_3(8)+50, F_3(5)+100, F_3(2)+150\\}\\\\\n &=max\\{80, 80+50, 40+100, 0+150\\}\\\\\n &=max\\{80, 130, 140, 150\\}\\\\\n &=150\\\\\n\\end{aligned}\n\\\\\n$$\n
\nMaximum value reached is in $F_4(11) = 150$ and has been reached for $x_4 = 3$ from $F_3(2)$, which gets its maximum value in $x_3 = 0$ from $F_2(2)$, which gets its maximum value in $x_2 = 0$ from $F_1(2)$, which gets its maximum value in $x_3 = 0$ from $F_1(2)$.
\n$\n\\begin{aligned}\nF_4(11)&=max\\{F_3(11), F_3(8)+50, F_3(5)+100, F_3(2)+150\\}\\\\\n &=max\\{80, 130, 140, 150\\} = 150\\\\\n\\end{aligned}\n\\rightarrow\n\\begin{aligned}\nF_3(2)&=max\\{F_2(2)\\} = 0 \\\\\n\\end{aligned}\n\\rightarrow\n\\begin{aligned}\nF_2(2)&=max\\{F_1(2)\\} = 0 \\\\\n\\end{aligned}\n\\rightarrow\n\\begin{aligned}\nF_1(2) = 0 \\\\\n\\end{aligned}\n\\\\\n$\n
\nMaximum solution: $F_{max}=150,\\;x=(0,0,0,3)$\n", "meta": {"hexsha": "c82ec95fcdd63499c71a318dd2f5a314ee056e47", "size": 27961, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "07. Knapsack problem/Seminarski.ipynb", "max_stars_repo_name": "lkora/DS3", "max_stars_repo_head_hexsha": "653115657d8c42f501dcb5dbf25c892a4e0ed3d1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-04-19T12:17:02.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-19T12:17:02.000Z", "max_issues_repo_path": "07. Knapsack problem/Seminarski.ipynb", "max_issues_repo_name": "lkora/MATF-DS3", "max_issues_repo_head_hexsha": "653115657d8c42f501dcb5dbf25c892a4e0ed3d1", "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": "07. Knapsack problem/Seminarski.ipynb", "max_forks_repo_name": "lkora/MATF-DS3", "max_forks_repo_head_hexsha": "653115657d8c42f501dcb5dbf25c892a4e0ed3d1", "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.773826458, "max_line_length": 432, "alphanum_fraction": 0.4301705948, "converted": true, "num_tokens": 9556, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741268224333, "lm_q2_score": 0.8976952968970956, "lm_q1q2_score": 0.8551213135943558}} {"text": "## Introduction\n-----\nYou (an electrical engineer) wish to determine the resistance of an electrical component by using Ohm's law. You remember from your high school circuit classes that $$V = RI$$ where $V$ is the voltage in volts, $R$ is resistance in ohms, and $I$ is electrical current in amperes. Using a multimeter, you collect the following data:\n\n| Current (A) | Voltage (V) |\n|-------------|-------------|\n| 0.2 | 1.23 |\n| 0.3 | 1.38 |\n| 0.4 | 2.06 |\n| 0.5 | 2.47 |\n| 0.6 | 3.17 |\n\nYour goal is to \n1. Fit a line through the origin (i.e., determine the parameter $R$ for $y = Rx$) to this data by using the method of least squares. You may assume that all measurements are of equal importance. \n2. Consider what the best estimate of the resistance is, in ohms, for this component.\n\n## Getting Started\n----\n\nFirst we will import the neccesary Python modules and load the current and voltage measurements into numpy arrays:\n\n\n```python\nimport numpy as np\nfrom numpy.linalg import inv\nimport matplotlib.pyplot as plt\n\n# Store the voltage and current data as column vectors.\nI = np.mat([0.2, 0.3, 0.4, 0.5, 0.6]).T\nV = np.mat([1.23, 1.38, 2.06, 2.47, 3.17]).T\n```\n\nNow we can plot the measurements - can you see the linear relationship between current and voltage?\n\n\n```python\nplt.scatter(np.asarray(I), np.asarray(V))\n\nplt.xlabel('Current (A)')\nplt.ylabel('Voltage (V)')\nplt.grid(True)\nplt.show()\n```\n\n## Estimating the Slope Parameter\n----\nLet's try to estimate the slope parameter $R$ (i.e., the resistance) using the least squares formulation from Module 1, Lesson 1 - \"The Squared Error Criterion and the Method of Least Squares\":\n\n\\begin{align}\n\\hat{R} = \\left(\\mathbf{H}^T\\mathbf{H}\\right)^{-1}\\mathbf{H}^T\\mathbf{y}\n\\end{align}\n\nIf we know that we're looking for the slope parameter $R$, how do we define the matrix $\\mathbf{H}$ and vector $\\mathbf{y}$?\n\n\n```python\n# Define the H matrix, what does it contain?\n# H = ...\nH = I\ny = V\n\n# Now estimate the resistance parameter.\n# R = ... \nR = inv(H.T * H) * H.T * y\nR = R[0, 0]\n\nprint('The slope parameter (i.e., resistance) for the best-fit line is:')\nprint(R)\n\n```\n\n The slope parameter (i.e., resistance) for the best-fit line is:\n 5.13444444444\n\n\n## Plotting the Results\n----\nNow let's plot our result. How do we relate our linear parameter fit to the resistance value in ohms?\n\n\n```python\nI_line = np.arange(0, 0.8, 0.1)\nV_line = R*I_line\n\nplt.scatter(np.asarray(I), np.asarray(V))\nplt.plot(I_line, V_line)\nplt.xlabel('current (A)')\nplt.ylabel('voltage (V)')\nplt.grid(True)\nplt.show()\n```\n\nIf you have implemented the estimation steps correctly, the slope parameter $\\hat{R}$ should be close to the actual resistance value of $R = 5~\\Omega$. However, the estimated value will not match the true resistance value exactly, since we have only a limited number of noisy measurements.\n", "meta": {"hexsha": "2af21e6c7dad6d6bc06dda171addc77746efa045", "size": 31542, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "2_state_estimation_and_localization_for_self_driving_cars/C2M1L1.ipynb", "max_stars_repo_name": "daniel-s-ingram/self_driving_cars_specialization", "max_stars_repo_head_hexsha": "ee400c4caa9170a391da7aba24ae7082151b5b69", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 102, "max_stars_repo_stars_event_min_datetime": "2019-05-28T19:36:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T08:05:34.000Z", "max_issues_repo_path": "2_state_estimation_and_localization_for_self_driving_cars/C2M1L1.ipynb", "max_issues_repo_name": "daniel-s-ingram/self_driving_cars_specialization", "max_issues_repo_head_hexsha": "ee400c4caa9170a391da7aba24ae7082151b5b69", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2019-10-01T16:20:24.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-23T09:36:07.000Z", "max_forks_repo_path": "2_state_estimation_and_localization_for_self_driving_cars/C2M1L1.ipynb", "max_forks_repo_name": "daniel-s-ingram/self_driving_cars_specialization", "max_forks_repo_head_hexsha": "ee400c4caa9170a391da7aba24ae7082151b5b69", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 69, "max_forks_repo_forks_event_min_datetime": "2019-06-06T23:45:53.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-15T12:15:29.000Z", "avg_line_length": 163.4300518135, "max_line_length": 15940, "alphanum_fraction": 0.8984845603, "converted": true, "num_tokens": 822, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.952574129515172, "lm_q2_score": 0.8976952832120991, "lm_q1q2_score": 0.855121302975641}} {"text": "```python\n# import Python libraries\nimport numpy as np\n%matplotlib inline\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport sympy as sym\nfrom sympy.plotting import plot\nimport pandas as pd\nfrom IPython.display import display\nfrom IPython.core.display import Math\nfrom scipy.optimize import minimize\n```\n\n1. Find the extrema in the function $f(x)=x^3-7.5x^2+18x-10$ analytically and determine if they are minimum or maximum.\n\n\n```python\nx = sym.symbols('x')\nf = x**3 - 7.5*x**2 + 18*x - 10\ndisplay(Math(sym.latex('f(x) = ') + sym.latex(f)))\n\nfdiff = sym.expand(sym.diff(f, x))\ndisplay(Math(sym.latex('\\dot f(x) = ') + sym.latex(fdiff)))\n\nroots = sym.solve(fdiff, x)\ndisplay(Math(sym.latex('Roots:') + sym.latex(roots)))\n\nfdiff2 = sym.expand(sym.diff(fdiff, x))\ndisplay(Math(sym.latex('\\ddot f(x) = ') + sym.latex(fdiff2)))\n\nf2 = fdiff2.subs(x,2)\ndisplay(Math(sym.latex('\\ddot f(2) = ') + sym.latex(f2)))\n\nf3 = fdiff2.subs(x,3)\ndisplay(Math(sym.latex('\\ddot f(3) = ') + sym.latex(f3)))\n```\n\n\n$$f(x) = x^{3} - 7.5 x^{2} + 18 x - 10$$\n\n\n\n$$\\dot f(x) = 3 x^{2} - 15.0 x + 18$$\n\n\n\n$$Roots:\\left [ 2.0, \\quad 3.0\\right ]$$\n\n\n\n$$\\ddot f(x) = 6 x - 15.0$$\n\n\n\n$$\\ddot f(2) = -3.0$$\n\n\n\n$$\\ddot f(3) = 3.0$$\n\n\nf(2) is a maximum and f(3) is a minimum\n\n\n```python\nplot(f,(x,1,4),xlabel= 'x',ylabel = 'f(x)')\n```\n\n\n```python\n\n```\n\n2. Find the minimum in the $f(x)=x^3-7.5x^2+18x-10$ using the gradient descent algorithm. \n\n\n```python\ncur_x = 2.001 \ngamma = 0.01 # step size multiplier\nprecision = 0.00001\nstep_size = 1 # initial step size\nmax_iters = 10000 # maximum number of iterations\niters = 0 # iteration counter\n\n\nf = lambda x: x**3 - 7.5*x**2 + 18*x - 10 # lambda function for f(x)\ndf = lambda x: 3*x**2 - 15*x + 18 # lambda function for the gradient of f(x)\n\nwhile (step_size > precision) & (iters < max_iters):\n prev_x = cur_x\n cur_x -= gamma*df(prev_x)\n step_size = abs(cur_x - prev_x)\n iters+=1\n\nprint('True local minimum at {} with function value {}.'.format(3, f(3)))\nprint('Local minimum by gradient descent at {} with function value {}.'.format(cur_x, f(cur_x)))\n```\n\n True local minimum at 3 with function value 3.5.\n Local minimum by gradient descent at 2.9996813387653187 with function value 3.500000152285125.\n\n\n\n```python\n\n```\n\n3. Regarding the distribution problem for the elbow muscles presented in this text: \n a. Test different initial values for the optimization. \n b. Test other values for the elbow angle where the results are likely to change. \n\n\n```python\ndef cf_f1(x):\n \"\"\"Cost function: sum of forces.\"\"\" \n return x[0] + x[1] + x[2]\n\ndef cf_f2(x):\n \"\"\"Cost function: sum of forces squared.\"\"\"\n return x[0]**2 + x[1]**2 + x[2]**2\n\ndef cf_fpcsa2(x, a):\n \"\"\"Cost function: sum of squared muscle stresses.\"\"\"\n return (x[0]/a[0])**2 + (x[1]/a[1])**2 + (x[2]/a[2])**2\n\ndef cf_fmmax3(x, m):\n \"\"\"Cost function: sum of cubic forces normalized by moments.\"\"\"\n return (x[0]/m[0])**3 + (x[1]/m[1])**3 + (x[2]/m[2])**3\ndef cf_f1d(x):\n \"\"\"Derivative of cost function: sum of forces.\"\"\"\n dfdx0 = 1\n dfdx1 = 1\n dfdx2 = 1\n return np.array([dfdx0, dfdx1, dfdx2])\n\ndef cf_f2d(x):\n \"\"\"Derivative of cost function: sum of forces squared.\"\"\"\n dfdx0 = 2*x[0]\n dfdx1 = 2*x[1]\n dfdx2 = 2*x[2]\n return np.array([dfdx0, dfdx1, dfdx2])\n\ndef cf_fpcsa2d(x, a):\n \"\"\"Derivative of cost function: sum of squared muscle stresses.\"\"\"\n dfdx0 = 2*x[0]/a[0]**2\n dfdx1 = 2*x[1]/a[1]**2\n dfdx2 = 2*x[2]/a[2]**2\n return np.array([dfdx0, dfdx1, dfdx2])\n\ndef cf_fmmax3d(x, m):\n \"\"\"Derivative of cost function: sum of cubic forces normalized by moments.\"\"\"\n dfdx0 = 3*x[0]**2/m[0]**3\n dfdx1 = 3*x[1]**2/m[1]**3\n dfdx2 = 3*x[2]**2/m[2]**3\n return np.array([dfdx0, dfdx1, dfdx2])\n```\n\n\n```python\n# time elbow_flexion BIClong BICshort BRA\nr_ef = np.loadtxt('./../../../data/r_elbowflexors.mot', skiprows=7)\nf_ef = np.loadtxt('./../../../data/f_elbowflexors.mot', skiprows=7)\n\nm_ef = r_ef*1\nm_ef[:, 2:] = r_ef[:, 2:]*f_ef[:, 2:]\n\na_ef = np.array([624.3, 435.56, 987.26])/50 # 50 N/cm2\n```\n\n\n```python\nM = 20 # desired torque at the elbow\niang = 69 # which will give the closest value to 90 degrees\n\n\nr = r_ef[iang, 2:]\nf0 = f_ef[iang, 2:]\na = a_ef\nm = m_ef[iang, 2:]\nx0 = f_ef[iang, 2:]/235 # far from the correct answer for the sum of torques\nprint('M =', M)\nprint('x0 =', x0)\nprint('r * x0 =', np.sum(r*x0))\n\nbnds = ((0, f0[0]), (0, f0[1]), (0, f0[2]))\n\n```\n\n M = 20\n x0 = [2.44736654 1.5446698 3.8147662 ]\n r * x0 = 0.28178742323694983\n\n\n\n```python\n# use this in combination with the parameter bounds:\ncons = ({'type': 'eq',\n 'fun' : lambda x, r, f0, M: np.array([r[0]*x[0] + r[1]*x[1] + r[2]*x[2] - M]), \n 'jac' : lambda x, r, f0, M: np.array([r[0], r[1], r[2]]), 'args': (r, f0, M)})\n# to enter everything as constraints:\ncons = ({'type': 'eq',\n 'fun' : lambda x, r, f0, M: np.array([r[0]*x[0] + r[1]*x[1] + r[2]*x[2] - M]), \n 'jac' : lambda x, r, f0, M: np.array([r[0], r[1], r[2]]), 'args': (r, f0, M)},\n {'type': 'ineq', 'fun' : lambda x, r, f0, M: f0[0]-x[0],\n 'jac' : lambda x, r, f0, M: np.array([-1, 0, 0]), 'args': (r, f0, M)},\n {'type': 'ineq', 'fun' : lambda x, r, f0, M: f0[1]-x[1],\n 'jac' : lambda x, r, f0, M: np.array([0, -1, 0]), 'args': (r, f0, M)},\n {'type': 'ineq', 'fun' : lambda x, r, f0, M: f0[2]-x[2],\n 'jac' : lambda x, r, f0, M: np.array([0, 0, -1]), 'args': (r, f0, M)},\n {'type': 'ineq', 'fun' : lambda x, r, f0, M: x[0],\n 'jac' : lambda x, r, f0, M: np.array([1, 0, 0]), 'args': (r, f0, M)},\n {'type': 'ineq', 'fun' : lambda x, r, f0, M: x[1],\n 'jac' : lambda x, r, f0, M: np.array([0, 1, 0]), 'args': (r, f0, M)},\n {'type': 'ineq', 'fun' : lambda x, r, f0, M: x[2],\n 'jac' : lambda x, r, f0, M: np.array([0, 0, 1]), 'args': (r, f0, M)})\n```\n\n\n```python\nf1r = minimize(fun=cf_f1, x0=x0, args=(), jac=cf_f1d,\n constraints=cons, method='SLSQP',\n options={'disp': True})\nf2r = minimize(fun=cf_f2, x0=x0, args=(), jac=cf_f2d,\n constraints=cons, method='SLSQP',\n options={'disp': True})\nfpcsa2r = minimize(fun=cf_fpcsa2, x0=x0, args=(a,), jac=cf_fpcsa2d,\n constraints=cons, method='SLSQP',\n options={'disp': True})\nfmmax3r = minimize(fun=cf_fmmax3, x0=x0, args=(m,), jac=cf_fmmax3d,\n constraints=cons, method='SLSQP',\n options={'disp': True})\n```\n\n Optimization terminated successfully. (Exit mode 0)\n Current function value: 409.59266009952\n Iterations: 7\n Function evaluations: 7\n Gradient evaluations: 7\n Optimization terminated successfully. (Exit mode 0)\n Current function value: 75657.38479127164\n Iterations: 4\n Function evaluations: 6\n Gradient evaluations: 4\n Optimization terminated successfully. (Exit mode 0)\n Current function value: 529.9639777695752\n Iterations: 11\n Function evaluations: 11\n Gradient evaluations: 11\n Optimization terminated successfully. (Exit mode 0)\n Current function value: 1075.1388931095582\n Iterations: 12\n Function evaluations: 13\n Gradient evaluations: 12\n\n\n\n```python\ndat = np.vstack((np.around(r*100,1), np.around(a,1), np.around(f0,0), np.around(m,1)))\nopt = np.around(np.vstack((f1r.x, f2r.x, fpcsa2r.x, fmmax3r.x)), 1)\ner = ['-', '-', '-', '-',\n np.sum(r*f1r.x)-M, np.sum(r*f2r.x)-M, np.sum(r*fpcsa2r.x)-M, np.sum(r*fmmax3r.x)-M]\ndata = np.vstack((np.vstack((dat, opt)).T, er)).T\n\nrows = ['$\\text{Moment arm}\\;[cm]$', '$pcsa\\;[cm^2]$', '$F_{max}\\;[N]$', '$M_{max}\\;[Nm]$',\n '$\\sum F_i$', '$\\sum F_i^2$', '$\\sum(F_i/pcsa_i)^2$', '$\\sum(F_i/M_{max,i})^3$']\ncols = ['Biceps long head', 'Biceps short head', 'Brachialis', 'Error in M']\ndf = pd.DataFrame(data, index=rows, columns=cols)\nprint('\\nComparison of different cost functions for solving the distribution problem')\ndf\n```\n\n \n Comparison of different cost functions for solving the distribution problem\n\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
Biceps long headBiceps short headBrachialisError in M
$\\text{Moment arm}\\;[cm]$4.94.92.3-
$pcsa\\;[cm^2]$12.58.719.7-
$F_{max}\\;[N]$575.0363.0896.0-
$M_{max}\\;[Nm]$28.117.720.4-
$\\sum F_i$205.2204.3-0.00.0
$\\sum F_i^2$184.7184.786.1-3.552713678800501e-15
$\\sum(F_i/pcsa_i)^2$201.798.2235.20.0
$\\sum(F_i/M_{max,i})^3$241.1120.9102.0-3.552713678800501e-15
\n
\n\n\n\n\n```python\nM = 20 # desired torque at the elbow\niang = 35 # which will give the closest value to 90 degrees\n\n\nr = r_ef[iang, 2:]\nf0 = f_ef[iang, 2:]\na = a_ef\nm = m_ef[iang, 2:]\nx0 = f_ef[iang, 2:]/235 # far from the correct answer for the sum of torques\nprint('M =', M)\nprint('x0 =', x0)\nprint('r * x0 =', np.sum(r*x0))\n\nbnds = ((0, f0[0]), (0, f0[1]), (0, f0[2]))\n```\n\n M = 20\n x0 = [2.65687365 1.84300054 4.17723792]\n r * x0 = 0.20841024709802292\n\n\n\n```python\nf1r = minimize(fun=cf_f1, x0=x0, args=(), jac=cf_f1d,\n constraints=cons, method='SLSQP',\n options={'disp': True})\n\nf2r = minimize(fun=cf_f2, x0=x0, args=(), jac=cf_f2d,\n constraints=cons, method='SLSQP',\n options={'disp': True})\n\nfpcsa2r = minimize(fun=cf_fpcsa2, x0=x0, args=(a,), jac=cf_fpcsa2d,\n constraints=cons, method='SLSQP',\n options={'disp': True})\n\nfmmax3r = minimize(fun=cf_fmmax3, x0=x0, args=(m,), jac=cf_fmmax3d,\n constraints=cons, method='SLSQP',\n options={'disp': True})\n```\n\n Optimization terminated successfully. (Exit mode 0)\n Current function value: 409.59266009953393\n Iterations: 7\n Function evaluations: 7\n Gradient evaluations: 7\n Optimization terminated successfully. (Exit mode 0)\n Current function value: 75657.3847912717\n Iterations: 4\n Function evaluations: 6\n Gradient evaluations: 4\n Optimization terminated successfully. (Exit mode 0)\n Current function value: 529.9639777695751\n Iterations: 11\n Function evaluations: 11\n Gradient evaluations: 11\n Optimization terminated successfully. (Exit mode 0)\n Current function value: 2330.3142947977667\n Iterations: 10\n Function evaluations: 10\n Gradient evaluations: 10\n\n\n\n```python\ndat = np.vstack((np.around(r*100,1), np.around(a,1), np.around(f0,0), np.around(m,1)))\nopt = np.around(np.vstack((f1r.x, f2r.x, fpcsa2r.x, fmmax3r.x)), 1)\ner = ['-', '-', '-', '-',\n np.sum(r*f1r.x)-M, np.sum(r*f2r.x)-M, np.sum(r*fpcsa2r.x)-M, np.sum(r*fmmax3r.x)-M]\ndata = np.vstack((np.vstack((dat, opt)).T, er)).T\n\nrows = ['$\\text{Moment arm}\\;[cm]$', '$pcsa\\;[cm^2]$', '$F_{max}\\;[N]$', '$M_{max}\\;[Nm]$',\n '$\\sum F_i$', '$\\sum F_i^2$', '$\\sum(F_i/pcsa_i)^2$', '$\\sum(F_i/M_{max,i})^3$']\ncols = ['Biceps long head', 'Biceps short head', 'Brachialis', 'Error in M']\ndf = pd.DataFrame(data, index=rows, columns=cols)\nprint('\\nComparison of different cost functions for solving the distribution problem')\ndf\n```\n\n \n Comparison of different cost functions for solving the distribution problem\n\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
Biceps long headBiceps short headBrachialisError in M
$\\text{Moment arm}\\;[cm]$3.43.41.3-
$pcsa\\;[cm^2]$12.58.719.7-
$F_{max}\\;[N]$624.0433.0982.0-
$M_{max}\\;[Nm]$21.514.912.5-
$\\sum F_i$205.2204.40.0-5.875094718302668
$\\sum F_i^2$184.7184.786.1-6.162588012268191
$\\sum(F_i/pcsa_i)^2$201.798.2235.2-6.660232419069558
$\\sum(F_i/M_{max,i})^3$238.3137.772.1-6.115622167519737
\n
\n\n\n\n\n```python\n\n```\n\n4. In an experiment to estimate forces of the elbow flexors, through inverse dynamics it was found an elbow flexor moment of 10 Nm. \nConsider the following data for maximum force (F0), moment arm (r), and pcsa (A) of the brachialis, brachioradialis, and biceps brachii muscles: F0 (N): 1000, 250, 700; r (cm): 2, 5, 4; A (cm$^2$): 33, 8, 23, respectively (data from Robertson et al. (2013)). \n a. Use static optimization to estimate the muscle forces. \n b. Test the robustness of the results using different initial values for the muscle forces. \n c. Compare the results for different cost functions.\n\n\n```python\nM = 10 # desired torque at the elbow\n\nf0 = np.array([1000, 250, 700])\nr = np.array([2, 5, 4])\na = np.array([33, 8, 23])\n\nm = r*f0\nx0 = f0*10 # far from the correct answer for the sum of torques\nprint('M =', M)\nprint('x0 =', x0)\nprint('r * x0 =', np.sum(r*x0))\n\nbnds = ((0, f0[0]), (0, f0[1]), (0, f0[2]))\n```\n\n M = 10\n x0 = [10000 2500 7000]\n r * x0 = 60500\n\n\n\n```python\n# use this in combination with the parameter bounds:\ncons = ({'type': 'eq',\n 'fun' : lambda x, r, f0, M: np.array([r[0]*x[0] + r[1]*x[1] + r[2]*x[2] - M]), \n 'jac' : lambda x, r, f0, M: np.array([r[0], r[1], r[2]]), 'args': (r, f0, M)})\n# to enter everything as constraints:\ncons = ({'type': 'eq',\n 'fun' : lambda x, r, f0, M: np.array([r[0]*x[0] + r[1]*x[1] + r[2]*x[2] - M]), \n 'jac' : lambda x, r, f0, M: np.array([r[0], r[1], r[2]]), 'args': (r, f0, M)},\n {'type': 'ineq', 'fun' : lambda x, r, f0, M: f0[0]-x[0],\n 'jac' : lambda x, r, f0, M: np.array([-1, 0, 0]), 'args': (r, f0, M)},\n {'type': 'ineq', 'fun' : lambda x, r, f0, M: f0[1]-x[1],\n 'jac' : lambda x, r, f0, M: np.array([0, -1, 0]), 'args': (r, f0, M)},\n {'type': 'ineq', 'fun' : lambda x, r, f0, M: f0[2]-x[2],\n 'jac' : lambda x, r, f0, M: np.array([0, 0, -1]), 'args': (r, f0, M)},\n {'type': 'ineq', 'fun' : lambda x, r, f0, M: x[0],\n 'jac' : lambda x, r, f0, M: np.array([1, 0, 0]), 'args': (r, f0, M)},\n {'type': 'ineq', 'fun' : lambda x, r, f0, M: x[1],\n 'jac' : lambda x, r, f0, M: np.array([0, 1, 0]), 'args': (r, f0, M)},\n {'type': 'ineq', 'fun' : lambda x, r, f0, M: x[2],\n 'jac' : lambda x, r, f0, M: np.array([0, 0, 1]), 'args': (r, f0, M)})\n```\n\n\n```python\nf1r = minimize(fun=cf_f1, x0=x0, args=(), jac=cf_f1d,\n constraints=cons, method='SLSQP',\n options={'disp': True})\nf2r = minimize(fun=cf_f2, x0=x0, args=(), jac=cf_f2d,\n constraints=cons, method='SLSQP',\n options={'disp': True})\nfpcsa2r = minimize(fun=cf_fpcsa2, x0=x0, args=(a,), jac=cf_fpcsa2d,\n constraints=cons, method='SLSQP',\n options={'disp': True})\nfmmax3r = minimize(fun=cf_fmmax3, x0=x0, args=(m,), jac=cf_fmmax3d,\n constraints=cons, method='SLSQP',\n options={'disp': True})\n```\n\n Optimization terminated successfully. (Exit mode 0)\n Current function value: 1.9999999999999882\n Iterations: 5\n Function evaluations: 5\n Gradient evaluations: 5\n Optimization terminated successfully. (Exit mode 0)\n Current function value: 2.2222222227876145\n Iterations: 6\n Function evaluations: 7\n Gradient evaluations: 6\n Optimization terminated successfully. (Exit mode 0)\n Current function value: 0.006934901666808587\n Iterations: 14\n Function evaluations: 14\n Gradient evaluations: 14\n Optimization terminated successfully. (Exit mode 0)\n Current function value: 1.5623481833790065e-08\n Iterations: 2\n Function evaluations: 3\n Gradient evaluations: 2\n\n\n\n```python\ndat = np.vstack((np.around(r*100,1), np.around(a,1), np.around(f0,0), np.around(m,1)))\nopt = np.around(np.vstack((f1r.x, f2r.x, fpcsa2r.x, fmmax3r.x)), 1)\ner = ['-', '-', '-', '-',\n np.sum(r*f1r.x)-M, np.sum(r*f2r.x)-M, np.sum(r*fpcsa2r.x)-M, np.sum(r*fmmax3r.x)-M]\ndata = np.vstack((np.vstack((dat, opt)).T, er)).T\n\nrows = ['$\\text{Moment arm}\\;[cm]$', '$pcsa\\;[cm^2]$', '$F_{max}\\;[N]$', '$M_{max}\\;[Nm]$',\n '$\\sum F_i$', '$\\sum F_i^2$', '$\\sum(F_i/pcsa_i)^2$', '$\\sum(F_i/M_{max,i})^3$']\ncols = ['Biceps long head', 'Biceps short head', 'Brachialis', 'Error in M']\ndf = pd.DataFrame(data, index=rows, columns=cols)\nprint('\\nComparison of different cost functions for solving the distribution problem')\ndf\n```\n\n \n Comparison of different cost functions for solving the distribution problem\n\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
Biceps long headBiceps short headBrachialisError in M
$\\text{Moment arm}\\;[cm]$200.0500.0400.0-
$pcsa\\;[cm^2]$33.08.023.0-
$F_{max}\\;[N]$1000.0250.0700.0-
$M_{max}\\;[Nm]$2000.01250.02800.0-
$\\sum F_i$-0.02.0-0.0-1.7763568394002505e-15
$\\sum F_i^2$0.41.10.90.0
$\\sum(F_i/pcsa_i)^2$1.50.21.50.0
$\\sum(F_i/M_{max,i})^3$5.00.00.00.0
\n
\n\n\n\n\n```python\nM = 10 # desired torque at the elbow\n\nf0 = np.array([1000, 250, 700])\nr = np.array([2, 5, 4])\na = np.array([33, 8, 23])\n\nm = r*f0\nx0 = f0/235 # far from the correct answer for the sum of torques\nprint('M =', M)\nprint('x0 =', x0)\nprint('r * x0 =', np.sum(r*x0))\n\nbnds = ((0, f0[0]), (0, f0[1]), (0, f0[2]))\n```\n\n M = 10\n x0 = [4.25531915 1.06382979 2.9787234 ]\n r * x0 = 25.744680851063826\n\n\n\n```python\nf1r = minimize(fun=cf_f1, x0=x0, args=(), jac=cf_f1d,\n constraints=cons, method='SLSQP',\n options={'disp': True})\nf2r = minimize(fun=cf_f2, x0=x0, args=(), jac=cf_f2d,\n constraints=cons, method='SLSQP',\n options={'disp': True})\nfpcsa2r = minimize(fun=cf_fpcsa2, x0=x0, args=(a,), jac=cf_fpcsa2d,\n constraints=cons, method='SLSQP',\n options={'disp': True})\nfmmax3r = minimize(fun=cf_fmmax3, x0=x0, args=(m,), jac=cf_fmmax3d,\n constraints=cons, method='SLSQP',\n options={'disp': True})\n```\n\n Optimization terminated successfully. (Exit mode 0)\n Current function value: 2.000000000000004\n Iterations: 6\n Function evaluations: 6\n Gradient evaluations: 6\n Optimization terminated successfully. (Exit mode 0)\n Current function value: 2.222222231479426\n Iterations: 7\n Function evaluations: 7\n Gradient evaluations: 7\n Optimization terminated successfully. (Exit mode 0)\n Current function value: 0.006934812760199668\n Iterations: 11\n Function evaluations: 11\n Gradient evaluations: 11\n Optimization terminated successfully. (Exit mode 0)\n Current function value: 4.177724714444361e-09\n Iterations: 1\n Function evaluations: 2\n Gradient evaluations: 1\n\n\n\n```python\ndat = np.vstack((np.around(r*100,1), np.around(a,1), np.around(f0,0), np.around(m,1)))\nopt = np.around(np.vstack((f1r.x, f2r.x, fpcsa2r.x, fmmax3r.x)), 1)\ner = ['-', '-', '-', '-',\n np.sum(r*f1r.x)-M, np.sum(r*f2r.x)-M, np.sum(r*fpcsa2r.x)-M, np.sum(r*fmmax3r.x)-M]\ndata = np.vstack((np.vstack((dat, opt)).T, er)).T\n\nrows = ['$\\text{Moment arm}\\;[cm]$', '$pcsa\\;[cm^2]$', '$F_{max}\\;[N]$', '$M_{max}\\;[Nm]$',\n '$\\sum F_i$', '$\\sum F_i^2$', '$\\sum(F_i/pcsa_i)^2$', '$\\sum(F_i/M_{max,i})^3$']\ncols = ['Biceps long head', 'Biceps short head', 'Brachialis', 'Error in M']\ndf = pd.DataFrame(data, index=rows, columns=cols)\nprint('\\nComparison of different cost functions for solving the distribution problem')\ndf\n```\n\n \n Comparison of different cost functions for solving the distribution problem\n\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
Biceps long headBiceps short headBrachialisError in M
$\\text{Moment arm}\\;[cm]$200.0500.0400.0-
$pcsa\\;[cm^2]$33.08.023.0-
$F_{max}\\;[N]$1000.0250.0700.0-
$M_{max}\\;[Nm]$2000.01250.02800.0-
$\\sum F_i$0.02.00.00.0
$\\sum F_i^2$0.41.10.90.0
$\\sum(F_i/pcsa_i)^2$1.50.21.53.552713678800501e-15
$\\sum(F_i/M_{max,i})^3$3.20.00.91.0658141036401503e-14
\n
\n\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "d29f4eedeac9e62b02d3d45d8b3e874100fa11bf", "size": 58042, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "courses/modsim2018/pedrosilva/Atividade Aula 20.ipynb", "max_stars_repo_name": "Pedro-henrique-silv/bmc", "max_stars_repo_head_hexsha": "988019c506c0897289a510a262889d1e6c86de13", "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": "courses/modsim2018/pedrosilva/Atividade Aula 20.ipynb", "max_issues_repo_name": "Pedro-henrique-silv/bmc", "max_issues_repo_head_hexsha": "988019c506c0897289a510a262889d1e6c86de13", "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": "courses/modsim2018/pedrosilva/Atividade Aula 20.ipynb", "max_forks_repo_name": "Pedro-henrique-silv/bmc", "max_forks_repo_head_hexsha": "988019c506c0897289a510a262889d1e6c86de13", "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.9937984496, "max_line_length": 13240, "alphanum_fraction": 0.5313049171, "converted": true, "num_tokens": 9020, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418272911436, "lm_q2_score": 0.925229956061184, "lm_q1q2_score": 0.855043702258887}} {"text": "**1**. Making wallpaper with `fromfunction`\n\nAdapted from [Circle Squared](http://igpphome.ucsd.edu/~shearer/COMP233/SciAm_Mandel.pdf)\n\nCreate a $400 \\times 400$ array using the function `lambda i, j: 0.27**2*(i**2 + j**2) % 1.5`. Use `imshow` from `matplotlib.pyplot` with `interpolation='nearest'` and the `YlOrBr` colormap to display the resulting array as an image.\n\n\n```python\n%matplotlib inline\nimport numpy as np\nimport matplotlib.pyplot as plt\n```\n\n\n```python\nxy = np.fromfunction(lambda i, j: 0.27**2*(i**2 + j**2) % 1.5, (400, 400))\nplt.figure(figsize = (8, 8))\nplt.imshow(xy, interpolation = 'nearest', cmap = plt.cm.YlOrBr)\n```\n\n**2**. Find t least squares solution for $\\beta_0, \\beta_1, \\beta_2$ using the normal equations $\\hat{\\beta} = (X^TX)^{-1}x^Ty$.\n\n\\begin{align}\n10 &= \\beta_0 + 3 \\beta_1 + 7 \\beta_2 \\\\\n11 &= \\beta_0 + 2 \\beta_1 + 8 \\beta_2 \\\\\n9 &= \\beta_0 + 3 \\beta_1 + 7 \\beta_2 \\\\\n10 &= \\beta_0 + 1 \\beta_1 + 9 \\beta_2 \\\\\n\\end{align}\n\nYou can find the inverse of a matrix by using `np.linalg.inv` and the transpose with `X.T`\n\n\n```python\nX = np.c_[np.ones(4), [3,2,3,1], [7,8,7,9]]\ny = np.array([10,11,9,10]).reshape(4,1)\n```\n\n\n```python\nb = np.linalg.inv(X.T @ X) @ X.T @ y\nb\n```\n\n\n\n\n array([[-1280.],\n [ 0.],\n [ 29.]])\n\n\n\n\n```python\nb2 = np.linalg.solve(X.T @ X, X.T @ y)\nb2\n```\n\n\n\n\n array([[ 9.10878011],\n [-0.19269619],\n [ 0.17094017]])\n\n\n\n\n```python\nnp.c_[y, X @ b]\n```\n\n\n\n\n array([[ 10., -1077.],\n [ 11., -1048.],\n [ 9., -1077.],\n [ 10., -1019.]])\n\n\n\n\n```python\nnp.c_[y, X @ b2]\n```\n\n\n\n\n array([[10. , 9.72727273],\n [11. , 10.09090909],\n [ 9. , 9.72727273],\n [10. , 10.45454545]])\n\n\n", "meta": {"hexsha": "632249008fe1ff6912ef387469cd955401e4499b", "size": 590498, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebook/T03_Exercises_Answer.ipynb", "max_stars_repo_name": "ywang512/sta663", "max_stars_repo_head_hexsha": "722c73a9b549b3bbbc1ec2ddd8d7ba4750023b92", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-02-18T10:06:51.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-18T10:06:51.000Z", "max_issues_repo_path": "notebook/T03_Exercises_Answer.ipynb", "max_issues_repo_name": "ywang512/sta663", "max_issues_repo_head_hexsha": "722c73a9b549b3bbbc1ec2ddd8d7ba4750023b92", "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": "notebook/T03_Exercises_Answer.ipynb", "max_forks_repo_name": "ywang512/sta663", "max_forks_repo_head_hexsha": "722c73a9b549b3bbbc1ec2ddd8d7ba4750023b92", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-03-15T08:38:14.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-15T08:38:14.000Z", "avg_line_length": 2952.49, "max_line_length": 586060, "alphanum_fraction": 0.9619676951, "converted": true, "num_tokens": 658, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037343628702, "lm_q2_score": 0.923039160069787, "lm_q1q2_score": 0.8550146209358108}} {"text": "# 1. Perceptron\n**Single Layer Perceptron(one Neuron)** \nA Perceptron is a simple model of a biological neuron that classifies the label of the input data based on various activation functions:\n1. Binary Step Function: \n\\begin{equation}\n f(x)=\\begin{cases}\n 0, & \\text{if $x<0$}.\\\\\n 1, & \\text{otherwise}.\n \\end{cases}\n\\end{equation}\n\n\n2. Signum Function:\n\\begin{equation}\n f(x)=\\begin{cases}\n -1, & \\text{if $x<0$}.\\\\\n 0, & \\text{if $x=0$>}\\\\\n 1, & \\text{if $x>0$}.\n \\end{cases}\n\\end{equation}\n\n\n3. Linear Activation Function:\n$$f(x) = x$$\n\n\n4. Sigmoid / Logistic Activation Function:\n$$f(x) = \\frac{1}{1+e^{-x}}$$\n\n\n5. Tanh Function (Hyperbolic Tangent):\n$$f(x) = \\frac{e^{x} - e^{-x}}{e^{x} + e^{-x}}$$\n\n\n6. ReLU Function:\n$$f(x) = max(0, x)$$\n\n\n7. Exponential Linear Units (ELUs) Function:\n\\begin{equation}\n f(x)=\\begin{cases}\n x, & \\text{if $x\\geqslant0$}.\\\\\n \\alpha(e^{x} - 1), & \\text{otherwise}.\n \\end{cases}\n\\end{equation}\n\n\n8. Swish:\n$$f(x) = \\frac{x}{1 + e^{-x}}$$\n\n\n9. Gaussian Error Linear Unit (GELU):\n$$f(x) = 0.5x(1 + tanh[\\sqrt{2/\\pi}(x + 0.044715x^3)])$$\n\n\n\n```python\nfn_list = ['step', 'signum', 'linear', 'relu', 'sigmoid', 'tanh', 'elu', 'gelu', 'swish']\n```\n\n## 1.1. How to use this\n```python\nfrom Perceptron.perceptron import Perceptron\nfrom Perceptron.utils import prepare_data, save_plot, save_model\n\n# get the data, convert it into a DataFrame and then use below commands\nX, y = prepare_data(df)\n\nmodel = Perceptron(eta = eta, epochs = epochs)\nmodel.fit(X, y, fn, alpha=None) # alpha ranges between 0 to 1 if and only if ELU activation function is applied else alpha value remains None for other activation functions\n\nTotal_Error = model.total_loss()\n\nsave_model(model, filename = filename)\n\nsave_plot(df, plotFilename, model)\n```\n\n## 1.2. Reference\n[Python Package Publishing Docs](https://packaging.python.org/tutorials/packaging-projects/)\n\n[GitHub Actions CICD Docs](https://docs.github.com/en/actions/guides/building-and-testing-python#publishing-to-package-registries)\n", "meta": {"hexsha": "d51d582f32f5be82130aee0cd3701bda9a9cfeff", "size": 3927, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Readme.ipynb", "max_stars_repo_name": "rohandhanraj/Perceptron", "max_stars_repo_head_hexsha": "5eea4679b14be3beec4b9e9999e47fef62cf18d8", "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": "Readme.ipynb", "max_issues_repo_name": "rohandhanraj/Perceptron", "max_issues_repo_head_hexsha": "5eea4679b14be3beec4b9e9999e47fef62cf18d8", "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": "Readme.ipynb", "max_forks_repo_name": "rohandhanraj/Perceptron", "max_forks_repo_head_hexsha": "5eea4679b14be3beec4b9e9999e47fef62cf18d8", "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.147826087, "max_line_length": 181, "alphanum_fraction": 0.5586962058, "converted": true, "num_tokens": 679, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947117065459, "lm_q2_score": 0.9046505370289057, "lm_q1q2_score": 0.8548899734348028}} {"text": "```python\nfrom sympy import *\nfrom sympy.solvers.solveset import solveset\ninit_printing()\nx, y, z = symbols('x,y,z')\n```\n\n## Solveset\n\nEquation solving is both a common need also a common building block for more complicated symbolic algorithms. \n\nHere we introduce the `solveset` function.\n\n\n```python\nsolveset(x**2 - 4, x)\n```\n\nSolveset takes two arguments and one optional argument specifying the domain, an equation like $x^2 - 4$ and a variable on which we want to solve, like $x$ and an optional argument domain specifying the region in which we want to solve.\n\nSolveset returns the values of the variable, $x$, for which the equation, $x^2 - 4$ equals 0.\n\n### Exercise\n\nWhat would the following code produce? Are you sure?\n\n\n```python\nsolveset(x**2 - 9 == 0, x)\n```\n\n## Infinite Solutions\n\nOne of the major improvements of `solveset` is that it also supports infinite solution.\n\n\n```python\nsolveset(sin(x), x)\n```\n\n## Domain argument\n\n\n```python\nsolveset(exp(x) -1, x)\n```\n\n`solveset` by default solves everything in the complex domain. In complex domain $exp(x) == cos(x) + i\\ sin(x)$ and solution is basically equal to solution to $cos(x) == 1$. If you want only real solution, you can specify the domain as `S.Reals`.\n\n\n```python\nsolveset(exp(x) -1, x, domain=S.Reals)\n```\n\n## Condition Set\n\n`solveset` isn't always able to solve a given equation, such cases it returns a `ConditionSet` object. `ConditionSet` represents a set satisfying a given condition.\n\n\n```python\nsolveset(exp(x) + cos(x) + 1, x, domain=S.Reals)\n```\n\n`solveset` aims to return all the solutions of the equation. In cases where it able to find some solution but not all it returns a union of the known solutions and `ConditionSet`.\n\n\n```python\nsolveset((x - 1)*(exp(x) + cos(x) + 1), x, domain=S.Reals)\n```\n\n## Symbolic use of `solveset`\n\nResults of `solveset` don't need to be numeric, like `{-2, 2}`. We can use solveset to perform algebraic manipulations. For example if we know a simple equation for the area of a square\n\n area = height * width\n \nwe can solve this equation for any of the variables. For example how would we solve this system for the `height`, given the `area` and `width`?\n\n\n```python\nheight, width, area = symbols('height, width, area')\nsolveset(area - height*width, height)\n```\n\nNote that we would have liked to have written\n\n solveset(area == height * width, height)\n \nBut the `==` gotcha bites us. Instead we remember that `solveset` expects an expression that is equal to zero, so we rewrite the equation\n\n area = height * width\n \ninto the equation\n\n 0 = height * width - area\n \nand that is what we give to solveset.\n\n### Exercise\n\nCompute the radius of a sphere, given the volume. Reminder, the volume of a sphere of radius `r` is given by\n\n$$ V = \\frac{4}{3}\\pi r^3 $$\n\n\n```python\n# Solve for the radius of a sphere, given the volume\n\n```\n\nYou will probably get several solutions, this is fine. The first one is probably the one that you want.\n\n## Substitution\n\nWe often want to substitute in one expression for another. For this we use the subs method\n\n\n```python\nx**2\n```\n\n\n```python\n# Replace x with y\n(x**2).subs({x: y})\n```\n\n### Exercise\n\nSubsitute $x$ for $sin(x)$ in the equation $x^2 + 2\\cdot x + 1$\n\n\n```python\n# Replace x with sin(x)\n\n\n```\n\n## Subs + Solveset\n\nWe can use subs and solve together to plug the solution of one equation into another\n\n\n```python\n# Solve for the height of a rectangle given area and width\n\nsoln = list(solveset(area - height*width, height))[0]\nsoln\n```\n\n\n```python\n# Define perimeter of rectangle in terms of height and width\n\nperimeter = 2*(height + width)\n```\n\n\n```python\n# Substitute the solution for height into the expression for perimeter\n\nperimeter.subs({height: soln})\n```\n\n### Exercise\n\nIn the last section you solved for the radius of a sphere given its volume\n\n\n```python\nV, r = symbols('V,r', real=True)\n4*pi/3 * r**3\n```\n\n\n```python\nlist(solveset(V - 4*pi/3 * r**3, r))[0]\n```\n\nNow lets compute the surface area of a sphere in terms of the volume. Recall that the surface area of a sphere is given by\n\n$$ 4 \\pi r^2 $$\n\n\n```python\n(?).subs(?)\n```\n\nDoes the expression look right? How would you expect the surface area to scale with respect to the volume? What is the exponent on $V$?\n\n## Plotting\n\nSymPy can plot expressions easily using the `plot` function. By default this links against matplotlib.\n\n\n```python\n%matplotlib inline\n```\n\n\n```python\nplot(x**2)\n```\n\n### Exercise\n\nIn the last exercise you derived a relationship between the volume of a sphere and the surface area. Plot this relationship using `plot`.\n\n\n```python\nplot(?)\n```\n\n## Low dependencies\n\nYou may know that SymPy tries to be a very low-dependency project. Our user base is very broad. Some entertaining aspects result. For example, `textplot`.\n\n\n```python\ntextplot(x**2, -3, 3)\n```\n\n### Exercise\n\nPlay with `textplot` and enjoy :)\n", "meta": {"hexsha": "90f413f64fcfbd36f53378b48bfa9ba920c5c446", "size": 10879, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "tutorial_exercises/02-Solveset-Subs-Plot.ipynb", "max_stars_repo_name": "gvvynplaine/scipy-2016-tutorial", "max_stars_repo_head_hexsha": "aa417427a1de2dcab2a9640b631b809d525d7929", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 53, "max_stars_repo_stars_event_min_datetime": "2016-06-21T21:11:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-04T07:51:03.000Z", "max_issues_repo_path": "tutorial_exercises/02-Solveset-Subs-Plot.ipynb", "max_issues_repo_name": "gvvynplaine/scipy-2016-tutorial", "max_issues_repo_head_hexsha": "aa417427a1de2dcab2a9640b631b809d525d7929", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 11, "max_issues_repo_issues_event_min_datetime": "2016-07-02T20:24:06.000Z", "max_issues_repo_issues_event_max_datetime": "2016-07-11T11:31:44.000Z", "max_forks_repo_path": "tutorial_exercises/02-Solveset-Subs-Plot.ipynb", "max_forks_repo_name": "gvvynplaine/scipy-2016-tutorial", "max_forks_repo_head_hexsha": "aa417427a1de2dcab2a9640b631b809d525d7929", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 36, "max_forks_repo_forks_event_min_datetime": "2016-06-25T09:04:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-09T06:46:01.000Z", "avg_line_length": 21.7145708583, "max_line_length": 253, "alphanum_fraction": 0.5362625241, "converted": true, "num_tokens": 1319, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087965937711, "lm_q2_score": 0.9207896829553822, "lm_q1q2_score": 0.8548692414685664}} {"text": "# the $k$-nearest neighbors (kNN) supervised learning algorithm\n\n* can be used for regression or classification\n* non-parametric\n* imposes only mild structural assumptions about the data\n\nlet's explore $k$-nearest neighbor classification.\n\ntraining data examples: $\\{(\\mathbf{x}_1, y_1), (\\mathbf{x}_2, y_2), ..., (\\mathbf{x}_n, y_n)\\}$ where $\\mathbf{x}_i$ is the feature vector and $y_i \\in \\{0, 1\\}$ is the label on data point $i$. This is a binary classification since each data point is labeled with $0$ or $1$.\n\nthe $k$-NN algorithm uses the training data to classify new data points. say we have a new data point $\\mathbf{x}$ but we don't know its label. the $k$-NN algorithm predicts the class of this data point as:\n\\begin{equation}\n \\hat{y}(\\mathbf{x})= \\frac{1}{k} \\displaystyle \\sum_{\\mathbf{x}_i \\in N_k(\\mathbf{x})} y_i\n\\end{equation}\nwhere $N_k(x)$ is the *neighborhood* of $\\mathbf{x}$ defined as the $k$ \"closest\" points in the training data set. For \"closest\" to be mathematically defined, we need a distance metric. One such distance metric is Euclidean distance. In words, the $k$ data points closest to $\\mathbf{x}$ vote on whether we should classify this point as a 0 or 1 with their labels.\n\n\n```julia\nusing CSV\nusing DataFrames\nusing PyPlot\nusing ScikitLearn # machine learning package\nusing StatsBase\nusing Random\nusing LaTeXStrings # for L\"$x$\" to work instead of needing to do \"\\$x\\$\"\nusing Printf\n\n# (optional)change settings for all plots at once, e.g. font size\nrcParams = PyPlot.PyDict(PyPlot.matplotlib.\"rcParams\")\nrcParams[\"font.size\"] = 16\n\n# (optional) change the style. see styles here: https://matplotlib.org/3.1.1/gallery/style_sheets/style_sheets_reference.html\nPyPlot.matplotlib.style.use(\"seaborn-white\") \n```\n\n## classifying breast tumors as malignant or benign\n\nsource: [UCI Machine Learning Repository](https://archive.ics.uci.edu/ml/datasets/Breast+Cancer+Wisconsin+(Diagnostic))\n\n> Features are computed from a digitized image of a fine needle aspirate (FNA) of a breast mass. They describe characteristics of the cell nuclei present in the image.\n\nThe mean radius and smoothness of the cell nuclei (the two features) and the outcome (M = malignant, B = benign) of the tumor are in the `breast_cancer_data.csv`.\n\n\n```julia\ndf = CSV.read(\"breast_cancer_data.csv\")\nfirst(df, 5)\n```\n\n\n\n\n

5 rows × 3 columns

mean_radiusmean_smoothnessoutcome
Float64Float64String
113.851.495B
29.6682.275B
39.2952.388B
419.694.585M
59.7551.243B
\n\n\n\n\n```julia\n\n```\n\nlet's map the outcomes to a number, 0 or 1, to facilitate the NN algo.\n\nbenign (B) : 0
\nmalignant (M) : 1\n\n\n```julia\n\n```\n\nlet's also have a color scheme for the class labels.\n\n\n```julia\n\n```\n\nsince this is a two-dimensional feature space, we have the luxury of visualizing how the classes are distributed in feature space. in practice, we do not have this luxury. I choose a 2D feature space for pedagogical purposes :)\n\n\n```julia\n\n```\n\n### using Scikitlearn for $k$-nearest neighbor classification\n\nscikitlearn documentation for `KNeighborsClassifier` [here](https://scikit-learn.org/stable/modules/generated/sklearn.neighbors.KNeighborsClassifier.html)\n\n\n```julia\n@sk_import neighbors : KNeighborsClassifier\n@sk_import model_selection : train_test_split\n@sk_import metrics : confusion_matrix\n```\n\n ┌ Warning: Module model_selection has been ported to Julia - try `import ScikitLearn: CrossValidation` instead\n └ @ ScikitLearn.Skcore /home/cokes/.julia/packages/ScikitLearn/bo2Pt/src/Skcore.jl:140\n\n\n\n\n\n PyObject \n\n\n\nscikitlearn takes as input:\n* a feature matrix `X`, which must be `n_samples` by `n_features`\n* a target vector `y`, which must be `n_samples` long (of course)\n\n\n```julia\n\n```\n\nconstruct a nearest neighbor object in scikitlearn\n\n\n```julia\n\n```\n\npass the `KNeighborsClassifier` object our training data. this will be used to make predictions on future, unseen data.\n\n\n```julia\n\n```\n\nwe can now make predictions on new, unseen data. that is, if we know the mean radius and mean smoothness of a new tumor, we can make a prediction about whether this tumor is malignant or benign. let's imagine we take measurements on a new tumor and it has the feature vector `x_new` below. we aim to predict whether it is benign or malignant.\n\n\n```julia\n# new tumor. unknown if malignant or benign...\nx_new = [10.0 1.5] # should be B\nx_new = [20.0 5.0] # should be M\n```\n\n\n\n\n 1×2 Array{Float64,2}:\n 20.0 5.0\n\n\n\nfirst, let's plot where it falls in feature space\n\n\n```julia\n\n```\n\npredict whether this new tumor is benign or malignant\n\n\n```julia\n\n```\n\nvisualize the decision boundary\n\n\n```julia\n\n```\n\n\n```julia\nfigure()\nxlabel(\"mean radius\")\nylabel(\"mean smoothness\")\n```\n\nwe can compute the accuracy of the prediction on the training data. but when $k=1$ we get 100% accuracy by construction!\n\n\n```julia\n\n```\n\n### the test/train paradigm\n\nrandomly split your data set into a training and test set. train the $k$-NN algo on the training data, then use the trained model to make predictions on data in the test set. we can compare the predicted label to the true label. the test set error is a quality prediction of generalization error on *unseen* data. we could write our own code for this, but scikitlearn provides `test_train_split` for us.\n\n\n```julia\n\n```\n\nto fully assess the performance of our model, trained on the training set, and tested on the test set, we can plot a so-called confusion matrix. it tells us about false positives, true positives, false negatives, and true negatives.\n\n\n```julia\n# see https://scikit-learn.org/stable/auto_examples/model_selection/plot_confusion_matrix.html#sphx-glr-auto-examples-model-selection-plot-confusion-matrix-py\nfunction plot_confusion_matrix(y_true::Array{Float64}, y_pred::Array{Float64}, classes::Array{String})\n # calculate confusion matrix from scikitlearn\n cm = confusion_matrix(y_true, y_pred)\n \n fig, ax = plt.subplots()\n ax.imshow(cm, interpolation=\"nearest\", cmap=plt.cm.Greens)\n ax.set(\n xlim=[-0.5, 1.5],\n ylim=[-0.5, 1.5],\n xticks=[0, 1],\n yticks=[0, 1],\n xticklabels=classes,\n yticklabels=classes,\n xlabel=\"predicted label\",\n ylabel=\"true label\"\n )\n\n for i = 1:2\n for j = 1:2\n ax.text(j-1, i-1, @sprintf(\"%d\", cm[i, j]), ha=\"center\", va=\"center\")\n end\n end\n tight_layout()\nend\n```\n\n\n\n\n plot_confusion_matrix (generic function with 1 method)\n\n\n\nto find the best $k$, we can scan over all $k$, train the model in the training set, then test the model on the test set (unseen data) to see how it performs. we take the \"best\" $k$ as the one that yields the lowest test set error, as we expect it to have the lowest generalization error on unseen data.\n\n\n```julia\n\n```\n\nthe optimal $k$ is around 8. So we should train our $k$-NN algo with $k=8$, then deploy this model, since it should result in the best accuracy on unseen data.\n\n\n```julia\n\n```\n", "meta": {"hexsha": "001405c8088211b4ab788b4df94b6383b0f578e3", "size": 38507, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "CHE599-IntroDataScience/lectures/knn/kNN_algo_sparse.ipynb", "max_stars_repo_name": "leanth/OSUCoursework", "max_stars_repo_head_hexsha": "ccfbf5f9daa8f6d3818bb5e4cc8df7c5135a5f34", "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": "CHE599-IntroDataScience/lectures/knn/kNN_algo_sparse.ipynb", "max_issues_repo_name": "leanth/OSUCoursework", "max_issues_repo_head_hexsha": "ccfbf5f9daa8f6d3818bb5e4cc8df7c5135a5f34", "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": "CHE599-IntroDataScience/lectures/knn/kNN_algo_sparse.ipynb", "max_forks_repo_name": "leanth/OSUCoursework", "max_forks_repo_head_hexsha": "ccfbf5f9daa8f6d3818bb5e4cc8df7c5135a5f34", "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": 79.5599173554, "max_line_length": 24282, "alphanum_fraction": 0.8154880931, "converted": true, "num_tokens": 2075, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377237352755, "lm_q2_score": 0.8918110540642805, "lm_q1q2_score": 0.8548345377647322}} {"text": "# 3.2.2 The Gauss–Markov Theorem\n\nThe Gauss-Markov theorem states that the least squares estimates of the $\\beta$ have the smallest variance among all linear unbiased estimates. We focus on estimation of any linear combination of the parameters $\\theta=\\alpha^T\\hat{\\beta}$, i.e predictions $f(x_0)={x_0}^T\\beta$ are of this form. \nThe least squares estimate is (3.17):\n\n$$\n\\hat{\\theta}=\\alpha^T\\hat{\\beta} = \\alpha^T(\\mathbf{X}^T\\mathbf{X})^{-1}\\mathbf{X}^T\\mathbf{y}\n$$\n\nand $\\alpha^T\\hat{\\beta}$ is unbiased, since (3.18):\n\n$$\n\\begin{align}\nE(\\alpha^T\\hat{\\beta}) &= E( \\alpha^T(\\mathbf{X}^T\\mathbf{X})^{-1}\\mathbf{X}^T\\mathbf{y})\\\\\n&= \\alpha^T(\\mathbf{X}^T\\mathbf{X})^{-1}\\mathbf{X}^T\\mathbf{X}\\beta\\\\\n&= \\alpha^T\\beta\n\\end{align}\n$$\n\n\nThe *Gauss-Markov* states that if we have any other linear estimator $\\tilde{\\theta}=\\mathbf{c}^T\\mathbf{y}$, that is, $E(\\mathbf{c}^T\\mathbf{y})=\\alpha^T\\beta$, then (3.19):\n\n$$\nVar(\\alpha^T\\hat{\\beta})\\le Var(\\mathbf{c}^T\\mathbf{y})\n$$\n\n*Proof*: \n\nLet's assume that $\\mathbf{c}^T\\mathbf{y}=(\\alpha^T(\\mathbf{X}^T\\mathbf{X})^{-1}\\mathbf{X}^T + \\mathbf{d}^T)\\mathbf{y}$, then:\n\n$$\n\\begin{align}\nE(\\mathbf{c}^T\\mathbf{y})&= E((\\alpha^T(\\mathbf{X}^T\\mathbf{X})^{-1}\\mathbf{X}^T + \\mathbf{d}^T)\\mathbf{y})\\\\\n&= E((\\alpha^T(\\mathbf{X}^T\\mathbf{X})^{-1}\\mathbf{X}^T + \\mathbf{d}^T)(\\mathbf{X}\\beta + \\varepsilon))\\\\\n&= \\alpha^T\\beta + d^T\\mathbf{X}\\beta\n\\end{align}\n$$\n\nSince $E(\\mathbf{c}^T\\mathbf{y})$ is unbiased $d^T\\mathbf{X}=0$.\n\n$$\n\\begin{align}\nVar(\\mathbf{c}^T\\mathbf{y}) &= \\mathbf{c}^{T}Var(\\mathbf{y})\\mathbf{c} = \\sigma^2\\mathbf{c}^T\\mathbf{c}\\\\\n&= \\sigma^2(\\alpha^T(\\mathbf{X}^T\\mathbf{X})^{-1}\\mathbf{X}^T + \\mathbf{d}^T)(\\mathbf{X}(\\mathbf{X}^T\\mathbf{X})^{-1}\\alpha + \\mathbf{d})\\\\\n&= \\sigma^2(\\alpha^T(\\mathbf{X}^T\\mathbf{X})^{-1}\\alpha+\\mathbf{d}^T\\mathbf{d})\\\\\n&= Var(\\alpha^T\\hat{\\beta})+\\sigma^2\\mathbf{d}^T\\mathbf{d}\n\\end{align}\n$$\n\nSince $\\mathbf{d}^T\\mathbf{d}\\ge 0$, the proof is completed.\n\nConsider the MSE of an estimator $\\tilde{\\theta}$ is estimating $\\theta$:\n$$\n\\begin{align}\nMSE(\\tilde{\\theta}) &= E(\\tilde{\\theta} - \\theta)^2\\\\\n&= Var(\\tilde{\\theta})+[E(\\tilde{\\theta}) - \\theta]^2\n\\end{align}\n$$\n\nThe first term is the variance, while the second term is the squared bias. The theorem implies that the least squares estimator has the smallest mean squared error of all linear estimators with no bias. However, there may exist a biased estimator with smaller MSE.\n\nMean squared error is related to prediction accuracy. Consider the prediction of the $x_0$, (3.21):\n\n$$\nY_0 = f(x_0) + \\varepsilon_0\n$$\n\nThen the EPE of an estimate $\\tilde{f}(x_0)={x_0}^T\\tilde{\\beta}$ is (3.22):\n$$\n\\begin{align}\nE(Y_0 - \\tilde{f}(x_0)) &= \\sigma^2 + E({x_0}^T\\tilde{\\beta}-f(x_0))^2\\\\\n&= \\sigma^2 + MSE(\\tilde{f}(x_0))\n\\end{align}\n$$\n\nTherefore, EPE and MSE differ only by the constant $\\sigma^2$.\n", "meta": {"hexsha": "efc8d40af4fc15ffcc8f1eb1166234d4cce36f67", "size": 4399, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "chapter-03/3.2.2-the-gauss-markov-theorem.ipynb", "max_stars_repo_name": "leduran/ESL", "max_stars_repo_head_hexsha": "fcb6c8268d6a64962c013006d9298c6f5a7104fe", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 360, "max_stars_repo_stars_event_min_datetime": "2019-01-28T14:05:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T00:11:21.000Z", "max_issues_repo_path": "chapter-03/3.2.2-the-gauss-markov-theorem.ipynb", "max_issues_repo_name": "leduran/ESL", "max_issues_repo_head_hexsha": "fcb6c8268d6a64962c013006d9298c6f5a7104fe", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-07-06T16:51:40.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-06T16:51:40.000Z", "max_forks_repo_path": "chapter-03/3.2.2-the-gauss-markov-theorem.ipynb", "max_forks_repo_name": "leduran/ESL", "max_forks_repo_head_hexsha": "fcb6c8268d6a64962c013006d9298c6f5a7104fe", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 79, "max_forks_repo_forks_event_min_datetime": "2019-03-21T23:48:35.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T13:05:10.000Z", "avg_line_length": 36.0573770492, "max_line_length": 312, "alphanum_fraction": 0.5160263696, "converted": true, "num_tokens": 1192, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240194661945, "lm_q2_score": 0.9111797045849583, "lm_q1q2_score": 0.8547995669212608}} {"text": "# Solutions\n\n## Question 1\n\n> `1`. Obtain the determinant and the inverses of the following matrices:\n\n> `1`. $A = \\begin{pmatrix} 1 / 5 & 1\\\\1 & 1\\end{pmatrix}$\n\n\n```python\nimport sympy as sym\n\nA = sym.Matrix([[sym.S(1) / 5, 1], [1, 1]])\nA.det()\n```\n\n\n\n\n$\\displaystyle - \\frac{4}{5}$\n\n\n\n\n```python\nA.inv()\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}- \\frac{5}{4} & \\frac{5}{4}\\\\\\frac{5}{4} & - \\frac{1}{4}\\end{matrix}\\right]$\n\n\n\n> `2`. $B = \\begin{pmatrix} 1 / 5 & 1 & 5\\\\3 & 1 & 6 \\\\ 1 & 2 & 1\\end{pmatrix}$\n\n\n```python\nB = sym.Matrix([[sym.S(1) / 5, 1, 5], [3, 1, 6], [1, 2, 1]])\nB.det()\n```\n\n\n\n\n$\\displaystyle \\frac{129}{5}$\n\n\n\n\n```python\nB.inv()\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}- \\frac{55}{129} & \\frac{15}{43} & \\frac{5}{129}\\\\\\frac{5}{43} & - \\frac{8}{43} & \\frac{23}{43}\\\\\\frac{25}{129} & \\frac{1}{43} & - \\frac{14}{129}\\end{matrix}\\right]$\n\n\n\n> `3`. $C = \\begin{pmatrix} 1 / 5 & 5 & 5\\\\3 & 1 & 7 \\\\ a & b & c\\end{pmatrix}$\n\n\n```python\na, b, c = sym.Symbol(\"a\"), sym.Symbol(\"b\"), sym.Symbol(\"c\")\nC = sym.Matrix([[sym.S(1) / 5, 5, 5], [3, 1, 7], [a, b, c]])\nC.det()\n```\n\n\n\n\n$\\displaystyle 30 a + \\frac{68 b}{5} - \\frac{74 c}{5}$\n\n\n\n\n```python\nC.inv()\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}\\frac{- 35 b + 5 c}{150 a + 68 b - 74 c} & \\frac{25 b - 25 c}{150 a + 68 b - 74 c} & - \\frac{444}{25 \\left(- \\frac{444 a}{25} - \\frac{5032 b}{625} + \\frac{5476 c}{625}\\right)}\\\\\\frac{35 a - 15 c}{150 a + 68 b - 74 c} & \\frac{- 25 a + c}{150 a + 68 b - 74 c} & - \\frac{5032}{125 \\left(- \\frac{444 a}{5} - \\frac{5032 b}{125} + \\frac{5476 c}{125}\\right)}\\\\\\frac{- 5 a + 15 b}{150 a + 68 b - 74 c} & \\frac{25 a - b}{150 a + 68 b - 74 c} & - \\frac{74}{25 \\left(6 a + \\frac{68 b}{25} - \\frac{74 c}{25}\\right)}\\end{matrix}\\right]$\n\n\n\n## Question 2\n\n> `2`. Compute the following:\n\n> `1`. $500\\begin{pmatrix} 1 / 5 & 1\\\\1 & 1\\end{pmatrix}$\n\n\n```python\nA = 500 * sym.Matrix([[sym.S(1) / 5, 1], [1, 1]])\nA\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}100 & 500\\\\500 & 500\\end{matrix}\\right]$\n\n\n\n> `2`. $\\pi \\begin{pmatrix} 1 / \\pi & 2\\pi\\\\3/\\pi & 1\\end{pmatrix}$\n\n\n```python\nB = sym.pi * sym.Matrix([[1 / sym.pi, 2 * sym.pi], [3 / sym.pi, 1]])\nB\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}1 & 2 \\pi^{2}\\\\3 & \\pi\\end{matrix}\\right]$\n\n\n\n> `3`. $500\\begin{pmatrix} 1 / 5 & 1\\\\1 & 1\\end{pmatrix} + \\pi \\begin{pmatrix} 1 / \\pi & 2\\pi\\\\3/\\pi & 1\\end{pmatrix}$\n\n\n```python\nA + B\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}101 & 2 \\pi^{2} + 500\\\\503 & \\pi + 500\\end{matrix}\\right]$\n\n\n\n> `4`. $500\\begin{pmatrix} 1 / 5 & 1\\\\1 & 1\\end{pmatrix}\\begin{pmatrix} 1 / \\pi & 2\\pi\\\\3/\\pi & 1\\end{pmatrix}$\n\n\n```python\nC = sym.Matrix([[1 / sym.pi, 2 * sym.pi], [3 / sym.pi, 1]])\nA @ C\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}\\frac{1600}{\\pi} & 500 + 200 \\pi\\\\\\frac{2000}{\\pi} & 500 + 1000 \\pi\\end{matrix}\\right]$\n\n\n\n## Question 3\n\n> `3`. The matrix $A$ is given by $A=\\begin{pmatrix}a & 4 & 2\\\\ 1 & a & 0\\\\ 1 & 2 & 1\\end{pmatrix}$.\n\n> `1`. Find the determinant of $A$\n\n\n```python\nA = sym.Matrix([[a, 4, 2], [1, a, 0], [1, 2, 1]])\ndeterminant = A.det()\ndeterminant\n```\n\n\n\n\n$\\displaystyle a^{2} - 2 a$\n\n\n\n> `2`. Hence find the values of $a$ for which $A$ is singular.\n\n$A$ is singular when the determinant is $0$ so we solve that equation:\n\n\n```python\nsym.solveset(determinant, a)\n```\n\n\n\n\n$\\displaystyle \\left\\{0, 2\\right\\}$\n\n\n\n> `3`. State, giving a brief reason in each case, whether the simultaneous equations\n>\n> $$\n \\begin{array}{l}\n a x + 4y + 2z= 3a\\\\\n x + a y = 1\\\\\n x + 2y + z = 3\\\\\n \\end{array}\n $$\n\n> have any solutions when:\n> `1`. $a = 3$;\n\nWhen $a$ is 3 the determinant is none zero, and so the matrix that represents\nthat linear system can be inverted.\n\n> `2`. $a = 2$\n\nWhen $a$ is 2 the determinant is zero and so the matrix that represents\nthat linear system cannot be inverted.\n\n## Question 4\n\n> `4`. The matrix $D$ is given by $D = \\begin{pmatrix} a & 2 & 0\\\\ 3 & 1 & 2\\\\ 0 & -1 & 1\\end{pmatrix}$ where $a\\ne 2$.\n> `1`. Find $D^{-1}$.\n\n\n```python\nD = sym.Matrix([[a, 2, 0], [3, 1, 2], [0, -1, 1]])\nD_inverse = D.inv()\nD_inverse\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}- \\frac{9}{18 - 9 a} & \\frac{6}{18 - 9 a} & - \\frac{12}{18 - 9 a}\\\\\\frac{3}{6 - 3 a} & - \\frac{a}{6 - 3 a} & \\frac{2 a}{6 - 3 a}\\\\- \\frac{3}{3 a - 6} & \\frac{a}{3 a - 6} & \\frac{a - 6}{3 a - 6}\\end{matrix}\\right]$\n\n\n\n> `2`. Hence of otherwise, solve the equations:\n>\n> $$\n \\begin{array}{l}\n a x + 2y = 3\\\\\n 3x + y + 2z = 4\\\\\n - y + z = 1\\\\\n \\end{array}\n $$\n\nThis corresponds to calculating: $D^{-1} \\begin{pmatrix}3\\\\4\\\\1\\end{pmatrix}$\n\n\n```python\nb = sym.Matrix([[3], [4], [1]])\nD_inverse @ b\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}- \\frac{15}{18 - 9 a}\\\\- \\frac{2 a}{6 - 3 a} + \\frac{9}{6 - 3 a}\\\\\\frac{4 a}{3 a - 6} + \\frac{a - 6}{3 a - 6} - \\frac{9}{3 a - 6}\\end{matrix}\\right]$\n\n\n", "meta": {"hexsha": "9c669d12a9f5f6183fbc8880c4e372860a52d0d7", "size": 12610, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "book/tools-for-mathematics/04-matrices/solutions/.main.md.bcp.ipynb", "max_stars_repo_name": "11michalis11/pfm", "max_stars_repo_head_hexsha": "c91b1eda70d7cde3fbe065db4667f84853947850", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2020-09-24T21:02:41.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-14T08:37:21.000Z", "max_issues_repo_path": "book/tools-for-mathematics/04-matrices/solutions/.main.md.bcp.ipynb", "max_issues_repo_name": "11michalis11/pfm", "max_issues_repo_head_hexsha": "c91b1eda70d7cde3fbe065db4667f84853947850", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 87, "max_issues_repo_issues_event_min_datetime": "2020-09-21T15:54:23.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-19T23:26:15.000Z", "max_forks_repo_path": "book/tools-for-mathematics/04-matrices/solutions/.main.md.bcp.ipynb", "max_forks_repo_name": "11michalis11/pfm", "max_forks_repo_head_hexsha": "c91b1eda70d7cde3fbe065db4667f84853947850", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-10-02T09:21:27.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-08T14:46:27.000Z", "avg_line_length": 24.53307393, "max_line_length": 599, "alphanum_fraction": 0.4201427439, "converted": true, "num_tokens": 2051, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.966914020657881, "lm_q2_score": 0.8840392893839086, "lm_q1q2_score": 0.8547899837177311}} {"text": "# Simple PageRank example\n\nPageRank is a algorithm used by Google to rank the 'importance' of a web page. The concept is that every web page has an importance score, and it 'endows' its importance evenly amongst the pages to which it links. The will lead to a problem where the ranking of all pages is an eigenvalue problem. We will demonstrate the process for the small web of four pages.\n\nConsider a web of four pages, $p_{0}$, $p_{1}$, $p_{2}$ and $p_{3}$. Consider the scenario:\n\n- $p_{0}$ links to: $p_{1}$, $p_{2}$ and $p_{3}$\n- $p_{1}$ links to: $p_{2}$ and $p_{3}$\n- $p_{2}$ links to: $p_{0}$\n- $p_{3}$ links to: $p_{0}$ and $p_{2}$\n\nWe can build a directed graph to describe the connections, and for this we use the package `networkx`. To visualise the graph, the packages `pygraphviz` and `pydot` are required.\n\n\n```\nimport networkx as nx\n\n# Create a directed networkx graph\nG = nx.DiGraph()\n\n# Add web pages (graph nodes)\nfor i in range(4):\n G.add_node(i, label=\"p\" + str(i))\n\n# Add outgoing web links with weights (directed graph edges)\nG.add_edge(0, 1, weight=1.0/3.0, label=\"1/3\")\nG.add_edge(0, 2, weight=1.0/3.0, label=\"1/3\")\nG.add_edge(0, 3, weight=1.0/3.0, label=\"1/3\")\n\nG.add_edge(1, 2, weight=1.0/2.0, label=\"1/2\")\nG.add_edge(1, 3, weight=1.0/2.0, label=\"1/2\")\n\nG.add_edge(2, 0, weight=1.0, label=\"1\")\n\nG.add_edge(3, 0, weight=1.0/2.0, label=\"1/2\")\nG.add_edge(3, 2, weight=1.0/2.0, label=\"1/2\")\n\n# To plot graph, convert to a PyGraphviz graph for drawing\nAg = nx.to_agraph(G)\nAg.layout(prog='dot')\nAg.draw('web.png')\nfrom IPython.display import Image\nImage('web.png')\n```\n\nNote that edges have been given a weight which is $1/n$, where $n$ is the number of outgoing link/edges from a page/node. The is the fraction of page's importance/rank that it can give to the pages to which it links. \n\nIf we denote the rank/importance of page $i$ by $x_{i}$, we can express the importance of each page:\n\n$$\n\\begin{align}\nx_{0} =& x_{2} + \\tfrac{1}{2}x_{2}\n\\\\\nx_{1} =& \\tfrac{1}{3}x_{0} \n\\\\\nx_{2} =& \\tfrac{1}{3}x_{0} + \\tfrac{1}{2}x_{1} + \\tfrac{1}{2}x_{3}\n\\\\\nx_{3} =& \\tfrac{1}{3}x_{0} + \\tfrac{1}{2}x_{1}\n\\end{align}\n$$\n\nWe can express this as a system of equation:\n\n$$\n\\underbrace{\n\\begin{bmatrix}\n0 & 0 & 1 & \\tfrac{1}{2}\n\\\\\n\\tfrac{1}{3} & 0 & 0 & 0\n\\\\\n\\tfrac{1}{3} & \\tfrac{1}{2} & 0 & \\tfrac{1}{2}\n\\\\\n\\tfrac{1}{3} & \\tfrac{1}{2} & 0 & 0\n\\end{bmatrix}}_{\\boldsymbol{A}}\n\\begin{bmatrix}\nx_{0} \\\\ x_{1} \\\\ x_{2} \\\\ x_{3}\n\\end{bmatrix}\n=\n\\begin{bmatrix}\nx_{0} \\\\ x_{1} \\\\ x_{2} \\\\ x_{3}\n\\end{bmatrix}\n$$\n\nThis is an eigenvalue problem with eigenvalue $\\lambda = 1$. To solve the problem we need to find the corresponding eigenvector.\n\nFirst, we can create the matrix $\\boldsymbol{A}$ directly from the graph (note that we added weights to the graph edges when building the graph):\n\n\n```\n# Get the matrix containing the graph weights\nA = (nx.adjacency_matrix(G).T).getA()\nprint A\n```\n\n [[ 0. 0. 1. 0.5 ]\n [ 0.33333333 0. 0. 0. ]\n [ 0.33333333 0.5 0. 0.5 ]\n [ 0.33333333 0.5 0. 0. ]]\n\n\nNote that the columns of $\\boldsymbol{A}$ sum to one. Such a matrix is known as a *stochastic matrix*. In our context, what is important is that the largest eigenvalue (in absolute terms) for such a matrix is one. Therefore, we are looking for the eigenvector associated with the largest eigenvalue.\n\n\n## Direct computation of the PageRank vector\n\nTo find the solution, we can compute the eigenvectors of $\\boldsymbol{A}$, and pick the eigenvectors that corresponds to $\\lambda = 1$:\n\n\n```\n# Compute the eigenvalues and eigenvectors\nimport numpy as np\nevalues, evectors = np.linalg.eig(A)\n\n# Print largest eigenvalue and corresponding eigenvector\nprint(\"The maxiumum eigenvalue is: {}\".format(np.max(evalues)))\nevector = evectors[:, np.argmax(evalues)]\nevector /= np.linalg.norm(evector, 1)\nprint(\"The PageRank vector (eigenvector) is: \\n {}\".format(evector))\n```\n\n The maxiumum eigenvalue is: (1+0j)\n The PageRank vector (eigenvector) is: \n [ 0.38709677+0.j 0.12903226+0.j 0.29032258+0.j 0.19354839+0.j]\n\n\nThe PageRank vector has been normalised using the $l_{1}$ norm such the the entries sum to one.\n\n\n## Approximation of the PageRank vector via matrix multiplication\n\nThe direct computation of all eigenvalues and eigenvectors is an expensive operation, and can only be reasonably performed for small matrices. However, we are interested only in the eigenvector corresponding to the largest eigenvalue. Recall that, in almost all cases, the repeated multiplication of a vector by a matrix $\\boldsymbol{A}$ will yield a vector that tends to the direction of the eigenvector corresponding to the largest eigenvalue. We can use this to approximate the PageRank vector using only matrix-vector multiplication:\n\n\n```\n# Create random starting vector\nx0 = np.random.rand(A.shape[0])\n\n# Perform 5 iterations\nfor i in range(5):\n x0 = A.dot(x0)\nx0 = x0/np.linalg.norm(x0 ,1)\nprint(\"Estimated PageRank after 5 iterations: {}\".format(x0))\n\n# Perform another 5 iterations\nfor i in range(5):\n x0 = A.dot(x0)\nx0 = x0/np.linalg.norm(x0 ,1)\nprint(\"Estimated PageRank after 10 iterations: {}\".format(x0))\n\n```\n\n Estimated PageRank after 5 iterations: [ 0.41444044 0.12356961 0.2825718 0.17941816]\n Estimated PageRank after 10 iterations: [ 0.38821763 0.12815233 0.29052499 0.19310505]\n\n\nIt is clear that the approximate solution is very close to the exact solution with relatively few iterations. The major advantage of this method is that it is computationally inexpensive, which makes it tractable for very large matrices.\n", "meta": {"hexsha": "d068dc6b66ae9a05ac18ff396426a495a5608ffd", "size": 51715, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/pagerank-simple.ipynb", "max_stars_repo_name": "quang-ha/IA-maths-Ipython", "max_stars_repo_head_hexsha": "8ff8533d64a3d8db8e4813a7b6dfee39339fd846", "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": "notebooks/pagerank-simple.ipynb", "max_issues_repo_name": "quang-ha/IA-maths-Ipython", "max_issues_repo_head_hexsha": "8ff8533d64a3d8db8e4813a7b6dfee39339fd846", "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": "notebooks/pagerank-simple.ipynb", "max_forks_repo_name": "quang-ha/IA-maths-Ipython", "max_forks_repo_head_hexsha": "8ff8533d64a3d8db8e4813a7b6dfee39339fd846", "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": 211.0816326531, "max_line_length": 42753, "alphanum_fraction": 0.8845596055, "converted": true, "num_tokens": 1813, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.975946445706356, "lm_q2_score": 0.8757869867849166, "lm_q1q2_score": 0.8547211969486188}} {"text": "```python\nfrom scipy.stats import norm\nfrom scipy.stats import t\nimport numpy as np\nimport pandas as pd\nfrom numpy.random import seed\nimport matplotlib.pyplot as plt\n```\n\n\n```python\n#generates random variates to draw five samples from the standard normal distribution\nsample1 = norm.rvs(size=5)\n```\n\n\n```python\nnp.mean(sample1)\n```\n\n\n\n\n 0.20789409052637584\n\n\n\n\n```python\nseed(47)\nsample2 = norm.rvs(size=5)\nsample2\n```\n\n\n\n\n array([-0.84800948, 1.30590636, 0.92420797, 0.6404118 , -1.05473698])\n\n\n\n\n```python\nnp.mean(sample2)\n```\n\n\n\n\n 0.19355593334131074\n\n\n\n\n```python\n#standard deviation - calculating manually\ndiff_squared = (sample2 - np.mean(sample2))**2\nv = np.sum(diff_squared) / len(sample2)\nprint('Variance: ' + str(v))\nprint('Standard Deviation: ' + str(np.sqrt(v)))\n```\n\n Variance: 0.9227899466393845\n Standard Deviation: 0.9606195639478641\n\n\n\n```python\n#standard deviation - calculating using np.sqrt(np.var())\nprint('Variance: ' + str(np.sqrt(np.var(sample2))))\n```\n\n Variance: 0.9606195639478641\n\n\n\n```python\n#standard deviation - calculating using np.std()\nprint('Standard Deviation: ' + str(np.std(sample2)))\n```\n\n Standard Deviation: 0.9606195639478641\n\n\n\n```python\n#standard deviation for sample\nvar_b = np.sum(diff_squared) / (len(sample2)-1)\nnp.sqrt(var_b)\n```\n\n\n\n\n 1.0740053227518152\n\n\n\n\n```python\n#with np.std() we get population standard deviation\nnp.std(sample2)\n```\n\n\n\n\n 0.9606195639478641\n\n\n\n\n```python\n#adding ddof=1 to np.std() will return the sample standard deviation\nnp.std(sample2, ddof=1)\n```\n\n\n\n\n 1.0740053227518152\n\n\n\nFor the sampling distribution of the mean, the standard deviation of this distribution is given by\n\n\\begin{equation}\n\\sigma_{mean} = \\frac{\\sigma}{\\sqrt n}\n\\end{equation}\n\nwhere $\\sigma_{mean}$ is the standard deviation of the sampling distribution of the mean and $\\sigma$ is the standard deviation of the population (the population parameter).\n\nLet us imagine we live in a town of 50000 people and we know the height of everyone in this town. We will have 50000 numbers that tell us everything about our population. We'll simulate these numbers now and put ourselves in one particular town, called 'town 47', where the **population mean** height is **172** cm and **population standard deviation** is **5** cm.\n\n\n```python\n#Generate 50000 samples from the population heights using 172 population mean and 5 population std\nseed(47)\npop_heights = norm.rvs(172, 5, size=50000)\npop_heights.min(), pop_heights.max(), np.mean(pop_heights), np.std(pop_heights)\n```\n\n\n\n\n (150.86806415764312, 193.22214997313296, 172.0192602425845, 4.990839139566387)\n\n\n\n\n```python\n#Using histogram to show the distribution of heights in the population\n_ = plt.hist(pop_heights, bins=30)\n_ = plt.xlabel('height (cm)')\n_ = plt.ylabel('number of people')\n_ = plt.title('Distribution of heights in entire town population')\n_ = plt.axvline(172, color='r')\n_ = plt.axvline(172+5, color='r', linestyle='--')\n_ = plt.axvline(172-5, color='r', linestyle='--')\n_ = plt.axvline(172+10, color='r', linestyle='-.')\n_ = plt.axvline(172-10, color='r', linestyle='-.')\n```\n\nNow, 50000 people is rather a lot to chase after with a tape measure. If all you want to know is the average height of the townsfolk, then can you just go out and measure a sample to get a pretty good estimate of the average height?\n\n\n```python\n#creating a function to create a sample size(n) from our population heights\ndef townsfolk_sampler(n):\n return np.random.choice(pop_heights, n)\n```\n\nLet's say you go out one day and randomly sample 10 people to measure.\n\n\n```python\nseed(47)\ndaily_sample1 = townsfolk_sampler(10)\n```\n\n\n```python\n_ = plt.hist(daily_sample1, bins=10)\n_ = plt.xlabel('height (cm)')\n_ = plt.ylabel('number of people')\n_ = plt.title('Distribution of heights in sample size 10')\n```\n\nThe sample distribution doesn't look much like what we know (but wouldn't know in real-life) the population distribution looks like. What do we get for the mean?\n\n\n```python\nnp.mean(daily_sample1)\n```\n\n\n\n\n 173.47911444163503\n\n\n\nAnd if we went out and repeated this experiment?\n\n\n```python\ndaily_sample2 = townsfolk_sampler(10)\n```\n\n\n```python\nnp.mean(daily_sample2)\n```\n\n\n\n\n 173.7317666636263\n\n\n\nSimulate performing this random trial every day for a year, calculating the mean of each daily sample of 10, and plot the resultant sampling distribution of the mean.\n\n\n```python\n# Using a foor loop to perform this sampling of 10 for each day of a year\n#[np.mean(townsfolk_sampler(10)) for x in range(365)]\ntrial_10 = []\nfor x in range(365):\n trial_10.append(np.mean(townsfolk_sampler(10)))\n```\n\n\n```python\nseed(47)\n# plotting the sampling distribution of the mean\n_ = plt.hist(trial_10, bins = 10)\n_ = plt.xlabel('height (cm)')\n_ = plt.ylabel('number of people')\n_ = plt.title('Distribution of heights of daily sample of 10 for a year')\n_ = plt.axvline(172, color='r')\n_ = plt.axvline(172+5, color='r', linestyle='--')\n_ = plt.axvline(172-5, color='r', linestyle='--')\n_ = plt.axvline(172+10, color='r', linestyle='-.')\n_ = plt.axvline(172-10, color='r', linestyle='-.')\n\nprint(len(trial_10))\nprint(np.mean(trial_10))\nprint(np.median(trial_10))\n```\n\nThe above is the distribution of the means of samples of size 10 taken from our population. The Central Limit Theorem tells us the expected mean of this distribution will be equal to the population mean, and standard deviation will be 𝜎/𝑛⎯⎯√ , which, in this case, should be approximately 1.58.\n\nQ: Verify the above results from the CLT.\n\n\n```python\nnp.std(trial_10, ddof=1)\n```\n\n\n\n\n 1.578160835870796\n\n\n\nRemember, in this instance, we knew our population parameters, that the average height really is 172 cm and the standard deviation is 5 cm, and we see some of our daily estimates of the population mean were as low as around 168 and some as high as 176.\n\nQ: Repeat the above year's worth of samples but for a sample size of 50 (perhaps you had a bigger budget for conducting surveys that year!) Would you expect your distribution of sample means to be wider (more variable) or narrower (more consistent)? Compare your resultant summary statistics to those predicted by the CLT.\n\n\n```python\nseed(47)\ntrial_50 = []\nfor x in range(365):\n trial_50.append(np.mean(townsfolk_sampler(50)))\n```\n\n\n```python\n_ = plt.hist(trial_50, bins = 50, histtype='stepfilled', alpha=0.8)\n_ = plt.xlabel('height (cm)')\n_ = plt.ylabel('number of people')\n_ = plt.title('Distribution of heights of daily sample of 50 for a year')\n_ = plt.axvline(172, color='r')\n_ = plt.axvline(172+5, color='r', linestyle='--')\n_ = plt.axvline(172-5, color='r', linestyle='--')\n_ = plt.axvline(172+10, color='r', linestyle='-.')\n_ = plt.axvline(172-10, color='r', linestyle='-.')\n\nprint(len(trial_50))\nprint(np.mean(trial_50))\nprint(np.median(trial_50))\nprint(np.std(trial_50,ddof = 1))\n```\n\nWhat we've seen so far, then, is that we can estimate population parameters from a sample from the population, and that samples have their own distributions. Furthermore, the larger the sample size, the narrower are those sampling distributions.\n\n### Let's now start from the position of knowing nothing about the heights of people in our town.\n* Use our favorite random seed of 47, to randomly sample the heights of 50 townsfolk\n* Estimate the population mean using np.mean\n* Estimate the population standard deviation using np.std (remember which denominator to use!)\n* Calculate the (95%) [margin of error](https://www.statisticshowto.datasciencecentral.com/probability-and-statistics/hypothesis-testing/margin-of-error/#WhatMofE) (use the exact critial z value to 2 decimal places - [look this up](https://www.statisticshowto.datasciencecentral.com/probability-and-statistics/find-critical-values/) or use norm.ppf())\n* Calculate the 95% Confidence Interval of the mean\n* Does this interval include the true population mean?\n\n\n```python\nseed(47)\nsecond_trial_50 = townsfolk_sampler(50)\n```\n\n\n```python\nnp.mean(second_trial_50)\n```\n\n\n\n\n 172.7815108576788\n\n\n\n\n```python\n# Using ddof = 1 because this is a sample not population\nnp.std(second_trial_50, ddof=1)\n```\n\n\n\n\n 4.195424364433547\n\n\n\n\n```python\ncritical_val = (norm.ppf(0.95))\n# Standard Error of the Mean (a.k.a. the standard deviation of the sampling distribution of the sample mean!\nse = (np.std(second_trial_50, ddof=1)) / (np.sqrt(50))\nmoe = critical_val * se # Margin of Error\nprint(moe)\n```\n\n 0.9759288364989565\n\n\n\n```python\nlower=np.mean(second_trial_50) - moe\nupper=np.mean(second_trial_50) + moe\nprint('lower: ' + str(lower) + '\\n' + 'Upper: ' + str(upper))\n```\n\n lower: 171.80558202117984\n Upper: 173.75743969417775\n\n\n__Q:__ Above we calculated the confidence interval using the critical z value. What is the problem with this? What requirement, or requirements, are we (strictly) failing?\n\n__A:__ Because we don't know anything about our population, the dataset has an unknown population standard deviation. I think using a t-score instead of z-score would be better.\n\n__Q__: Calculate the 95% confidence interval for the mean using the _t_ distribution. Is this wider or narrower than that based on the normal distribution above? If you're unsure, you may find this [resource](https://www.statisticshowto.datasciencecentral.com/probability-and-statistics/confidence-interval/) useful. For calculating the critical value, remember how you could calculate this for the normal distribution using norm.ppf().\n\n\n```python\n#Subtract 1 from your sample size to find the degrees of freedom (df).\ndof = 50 - 1\nt = t.ppf(0.95, (dof))\nt\n```\n\n\n\n\n 1.6765508919142629\n\n\n\n\n```python\n# Margin of error for t-score\nmoe_t = t * se \n```\n\n\n```python\nlower=np.mean(second_trial_50) - moe_t\nupper=np.mean(second_trial_50) + moe_t\nprint('lower: ' + str(lower) + '\\n' + 'Upper: ' + str(upper))\n```\n\n lower: 171.78677531740482\n Upper: 173.77624639795278\n\n\n__A:__ Wider than the normal distribution since t-distribution curves are wider and bigger at the tails compared to normal distribution curves\n\n\n```python\n\n```\n", "meta": {"hexsha": "af2cf8bc2cee3e158885eef1139fb2192b81c0ec", "size": 76699, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Python Statistics/Mini Projects/inferential_statistics_frequentist_mini-projects6.28.19/Mini Projects - Simplified.ipynb", "max_stars_repo_name": "atalebizadeh/DS-Career-Track", "max_stars_repo_head_hexsha": "8bf78ef11041aef94810a392022cd51b94462d9c", "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 Statistics/Mini Projects/inferential_statistics_frequentist_mini-projects6.28.19/Mini Projects - Simplified.ipynb", "max_issues_repo_name": "atalebizadeh/DS-Career-Track", "max_issues_repo_head_hexsha": "8bf78ef11041aef94810a392022cd51b94462d9c", "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 Statistics/Mini Projects/inferential_statistics_frequentist_mini-projects6.28.19/Mini Projects - Simplified.ipynb", "max_forks_repo_name": "atalebizadeh/DS-Career-Track", "max_forks_repo_head_hexsha": "8bf78ef11041aef94810a392022cd51b94462d9c", "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.4767295597, "max_line_length": 15176, "alphanum_fraction": 0.8601807064, "converted": true, "num_tokens": 2746, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475699138558, "lm_q2_score": 0.9059898279984214, "lm_q1q2_score": 0.854663302608983}} {"text": "# Basis for grayscale images\n\n## Introduction\n\nConsider the set of real-valued matrices of size $M\\times N$; we can turn this into a vector space by defining addition and scalar multiplication in the usual way:\n\n\\begin{align}\n\\mathbf{A} + \\mathbf{B} &= \n \\left[ \n \\begin{array}{ccc} \n a_{0,0} & \\dots & a_{0,N-1} \\\\ \n \\vdots & & \\vdots \\\\ \n a_{M-1,0} & \\dots & b_{M-1,N-1} \n \\end{array}\n \\right]\n + \n \\left[ \n \\begin{array}{ccc} \n b_{0,0} & \\dots & b_{0,N-1} \\\\ \n \\vdots & & \\vdots \\\\ \n b_{M-1,0} & \\dots & b_{M-1,N-1} \n \\end{array}\n \\right]\n \\\\\n &=\n \\left[ \n \\begin{array}{ccc} \n a_{0,0}+b_{0,0} & \\dots & a_{0,N-1}+b_{0,N-1} \\\\ \n \\vdots & & \\vdots \\\\ \n a_{M-1,0}+b_{M-1,0} & \\dots & a_{M-1,N-1}+b_{M-1,N-1} \n \\end{array}\n \\right] \n \\\\ \\\\ \\\\\n\\beta\\mathbf{A} &= \n \\left[ \n \\begin{array}{ccc} \n \\beta a_{0,0} & \\dots & \\beta a_{0,N-1} \\\\ \n \\vdots & & \\vdots \\\\ \n \\beta a_{M-1,0} & \\dots & \\beta a_{M-1,N-1}\n \\end{array}\n \\right]\n\\end{align}\n\n\nAs a matter of fact, the space of real-valued $M\\times N$ matrices is completely equivalent to $\\mathbb{R}^{MN}$ and we can always \"unroll\" a matrix into a vector. Assume we proceed column by column; then the matrix becomes\n\n$$\n \\mathbf{a} = \\mathbf{A}[:] = [\n \\begin{array}{ccccccc}\n a_{0,0} & \\dots & a_{M-1,0} & a_{0,1} & \\dots & a_{M-1,1} & \\ldots & a_{0, N-1} & \\dots & a_{M-1,N-1}\n \\end{array}]^T\n$$\n\nAlthough the matrix and vector forms represent exactly the same data, the matrix form allows us to display the data in the form of an image. Assume each value in the matrix is a grayscale intensity, where zero is black and 255 is white; for example we can create a checkerboard pattern of any size with the following function:\n\n\n```python\n# usual python bookkeeping...\n%pylab inline\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport IPython\nfrom IPython.display import Image\nimport math\nfrom __future__ import print_function\n\n# ensure all images will be grayscale\ngray();\n```\n\n Populating the interactive namespace from numpy and matplotlib\n\n\n\n
\n\n\n#### (?1) `gray() # ensure all images will be grayscale`? What?\n\n#### (R1)\n\n\n```python\ngray.__module__\n```\n\n\n\n\n 'matplotlib.pyplot'\n\n\n\n\n```python\nhelp(gray)\n```\n\n Help on function gray in module matplotlib.pyplot:\n \n gray()\n Set the colormap to \"gray\".\n \n This changes the default colormap as well as the colormap of the current\n image if there is one. See ``help(colormaps)`` for more information.\n \n\n\n#### (!1) Worth digging deep: `colormaps`\n\n\n```python\nhelp(colormaps)\n```\n\n Help on function colormaps in module matplotlib.pyplot:\n \n colormaps()\n Matplotlib provides a number of colormaps, and others can be added using\n :func:`~matplotlib.cm.register_cmap`. This function documents the built-in\n colormaps, and will also return a list of all registered colormaps if\n called.\n \n You can set the colormap for an image, pcolor, scatter, etc,\n using a keyword argument::\n \n imshow(X, cmap=cm.hot)\n \n or using the :func:`set_cmap` function::\n \n imshow(X)\n pyplot.set_cmap('hot')\n pyplot.set_cmap('jet')\n \n In interactive mode, :func:`set_cmap` will update the colormap post-hoc,\n allowing you to see which one works best for your data.\n \n All built-in colormaps can be reversed by appending ``_r``: For instance,\n ``gray_r`` is the reverse of ``gray``.\n \n There are several common color schemes used in visualization:\n \n Sequential schemes\n for unipolar data that progresses from low to high\n Diverging schemes\n for bipolar data that emphasizes positive or negative deviations from a\n central value\n Cyclic schemes\n for plotting values that wrap around at the endpoints, such as phase\n angle, wind direction, or time of day\n Qualitative schemes\n for nominal data that has no inherent ordering, where color is used\n only to distinguish categories\n \n Matplotlib ships with 4 perceptually uniform color maps which are\n the recommended color maps for sequential data:\n \n ========= ===================================================\n Colormap Description\n ========= ===================================================\n inferno perceptually uniform shades of black-red-yellow\n magma perceptually uniform shades of black-red-white\n plasma perceptually uniform shades of blue-red-yellow\n viridis perceptually uniform shades of blue-green-yellow\n ========= ===================================================\n \n The following colormaps are based on the `ColorBrewer\n `_ color specifications and designs developed by\n Cynthia Brewer:\n \n ColorBrewer Diverging (luminance is highest at the midpoint, and\n decreases towards differently-colored endpoints):\n \n ======== ===================================\n Colormap Description\n ======== ===================================\n BrBG brown, white, blue-green\n PiYG pink, white, yellow-green\n PRGn purple, white, green\n PuOr orange, white, purple\n RdBu red, white, blue\n RdGy red, white, gray\n RdYlBu red, yellow, blue\n RdYlGn red, yellow, green\n Spectral red, orange, yellow, green, blue\n ======== ===================================\n \n ColorBrewer Sequential (luminance decreases monotonically):\n \n ======== ====================================\n Colormap Description\n ======== ====================================\n Blues white to dark blue\n BuGn white, light blue, dark green\n BuPu white, light blue, dark purple\n GnBu white, light green, dark blue\n Greens white to dark green\n Greys white to black (not linear)\n Oranges white, orange, dark brown\n OrRd white, orange, dark red\n PuBu white, light purple, dark blue\n PuBuGn white, light purple, dark green\n PuRd white, light purple, dark red\n Purples white to dark purple\n RdPu white, pink, dark purple\n Reds white to dark red\n YlGn light yellow, dark green\n YlGnBu light yellow, light green, dark blue\n YlOrBr light yellow, orange, dark brown\n YlOrRd light yellow, orange, dark red\n ======== ====================================\n \n ColorBrewer Qualitative:\n \n (For plotting nominal data, `.ListedColormap` is used,\n not `.LinearSegmentedColormap`. Different sets of colors are\n recommended for different numbers of categories.)\n \n * Accent\n * Dark2\n * Paired\n * Pastel1\n * Pastel2\n * Set1\n * Set2\n * Set3\n \n A set of colormaps derived from those of the same name provided\n with Matlab are also included:\n \n ========= =======================================================\n Colormap Description\n ========= =======================================================\n autumn sequential linearly-increasing shades of red-orange-yellow\n bone sequential increasing black-white color map with\n a tinge of blue, to emulate X-ray film\n cool linearly-decreasing shades of cyan-magenta\n copper sequential increasing shades of black-copper\n flag repetitive red-white-blue-black pattern (not cyclic at\n endpoints)\n gray sequential linearly-increasing black-to-white\n grayscale\n hot sequential black-red-yellow-white, to emulate blackbody\n radiation from an object at increasing temperatures\n jet a spectral map with dark endpoints, blue-cyan-yellow-red;\n based on a fluid-jet simulation by NCSA [#]_\n pink sequential increasing pastel black-pink-white, meant\n for sepia tone colorization of photographs\n prism repetitive red-yellow-green-blue-purple-...-green pattern\n (not cyclic at endpoints)\n spring linearly-increasing shades of magenta-yellow\n summer sequential linearly-increasing shades of green-yellow\n winter linearly-increasing shades of blue-green\n ========= =======================================================\n \n A set of palettes from the `Yorick scientific visualisation\n package `_, an evolution of\n the GIST package, both by David H. Munro are included:\n \n ============ =======================================================\n Colormap Description\n ============ =======================================================\n gist_earth mapmaker's colors from dark blue deep ocean to green\n lowlands to brown highlands to white mountains\n gist_heat sequential increasing black-red-orange-white, to emulate\n blackbody radiation from an iron bar as it grows hotter\n gist_ncar pseudo-spectral black-blue-green-yellow-red-purple-white\n colormap from National Center for Atmospheric\n Research [#]_\n gist_rainbow runs through the colors in spectral order from red to\n violet at full saturation (like *hsv* but not cyclic)\n gist_stern \"Stern special\" color table from Interactive Data\n Language software\n ============ =======================================================\n \n A set of cyclic color maps:\n \n ================ =================================================\n Colormap Description\n ================ =================================================\n hsv red-yellow-green-cyan-blue-magenta-red, formed by\n changing the hue component in the HSV color space\n twilight perceptually uniform shades of\n white-blue-black-red-white\n twilight_shifted perceptually uniform shades of\n black-blue-white-red-black\n ================ =================================================\n \n Other miscellaneous schemes:\n \n ============= =======================================================\n Colormap Description\n ============= =======================================================\n afmhot sequential black-orange-yellow-white blackbody\n spectrum, commonly used in atomic force microscopy\n brg blue-red-green\n bwr diverging blue-white-red\n coolwarm diverging blue-gray-red, meant to avoid issues with 3D\n shading, color blindness, and ordering of colors [#]_\n CMRmap \"Default colormaps on color images often reproduce to\n confusing grayscale images. The proposed colormap\n maintains an aesthetically pleasing color image that\n automatically reproduces to a monotonic grayscale with\n discrete, quantifiable saturation levels.\" [#]_\n cubehelix Unlike most other color schemes cubehelix was designed\n by D.A. Green to be monotonically increasing in terms\n of perceived brightness. Also, when printed on a black\n and white postscript printer, the scheme results in a\n greyscale with monotonically increasing brightness.\n This color scheme is named cubehelix because the (r, g, b)\n values produced can be visualised as a squashed helix\n around the diagonal in the (r, g, b) color cube.\n gnuplot gnuplot's traditional pm3d scheme\n (black-blue-red-yellow)\n gnuplot2 sequential color printable as gray\n (black-blue-violet-yellow-white)\n ocean green-blue-white\n rainbow spectral purple-blue-green-yellow-orange-red colormap\n with diverging luminance\n seismic diverging blue-white-red\n nipy_spectral black-purple-blue-green-yellow-red-white spectrum,\n originally from the Neuroimaging in Python project\n terrain mapmaker's colors, blue-green-yellow-brown-white,\n originally from IGOR Pro\n turbo Spectral map (purple-blue-green-yellow-orange-red) with\n a bright center and darker endpoints. A smoother\n alternative to jet.\n ============= =======================================================\n \n The following colormaps are redundant and may be removed in future\n versions. It's recommended to use the names in the descriptions\n instead, which produce identical output:\n \n ========= =======================================================\n Colormap Description\n ========= =======================================================\n gist_gray identical to *gray*\n gist_yarg identical to *gray_r*\n binary identical to *gray_r*\n ========= =======================================================\n \n .. rubric:: Footnotes\n \n .. [#] Rainbow colormaps, ``jet`` in particular, are considered a poor\n choice for scientific visualization by many researchers: `Rainbow Color\n Map (Still) Considered Harmful\n `_\n \n .. [#] Resembles \"BkBlAqGrYeOrReViWh200\" from NCAR Command\n Language. See `Color Table Gallery\n `_\n \n .. [#] See `Diverging Color Maps for Scientific Visualization\n `_ by Kenneth Moreland.\n \n .. [#] See `A Color Map for Effective Black-and-White Rendering of\n Color-Scale Images\n `_\n by Carey Rappaport\n \n\n\n\n```python\n# let's create a checkerboard pattern\nSIZE = 4\nimg = np.zeros((SIZE, SIZE))\nfor n in range(0, SIZE):\n for m in range(0, SIZE):\n if (n & 0x1) ^ (m & 0x1):\n ## recall that ^ is the exclusive or\n #img[n, m] = 255\n img[m, n] = 255\n\n# now display the matrix as an image\nplt.matshow(img); \n```\n\n\n```python\nSIZE = 4\nimg = np.zeros((SIZE, SIZE))\nimg.dtype # float64, better uint8 for images\n```\n\n\n\n\n dtype('float64')\n\n\n\n\n```python\nnp.uint8\n```\n\n\n\n\n numpy.uint8\n\n\n\n`m & 0x1` and `n & 0x1` tests the parity: if `m` is odd, then `m & 0x1` outputs `1` (or `True`); if `m` even,\noutput `0`. Using XOR after that guarantees that only when exactly one of `m` and `n` is odd will the case\nbe colored white. This implies that every time one crosses from one case to any of its neighboring cases,\nthe color changes\n\n\nNote how the axes of `plt.matshow()` are arranged diff from that of `plt.imshow()`\nhelp(plt.matshow)\n\n```python\nplt.imshow(img);\n```\n\nGiven the equivalence between the space of $M\\times N$ matrices and $\\mathbb{R}^{MN}$ we can easily define the inner product between two matrices in the usual way:\n\n$$\n\\langle \\mathbf{A}, \\mathbf{B} \\rangle = \\sum_{m=0}^{M-1} \\sum_{n=0}^{N-1} a_{m,n} b_{m, n}\n$$\n\n(where we have neglected the conjugation since we'll only deal with real-valued matrices); in other words, we can take the inner product between two matrices as the standard inner product of their unrolled versions. The inner product allows us to define orthogonality between images and this is rather useful since we're going to explore a couple of bases for this space.\n\n## Actual images\n\nConveniently, using IPython, we can read images from disk in any given format and convert them to numpy arrays; let's load and display for instance a JPEG image:\nimg = np.array(plt.imread('cameraman.jpg'), dtype=int)\nplt.matshow(img);---------------------------------------------------------------------------\nValueError Traceback (most recent call last)\n in ()\n----> 1 img = np.array(plt.imread('cameraman.jpg'), dtype=int)\n 2 plt.matshow(img);\n\n/home/phunc20/.virtualenvs/dsp-py2.7/lib/python2.7/site-packages/matplotlib/pyplot.pyc in imread(*args, **kwargs)\n 2371 @docstring.copy_dedent(_imread)\n 2372 def imread(*args, **kwargs):\n-> 2373 return _imread(*args, **kwargs)\n 2374 \n 2375 \n\n/home/phunc20/.virtualenvs/dsp-py2.7/lib/python2.7/site-packages/matplotlib/image.pyc in imread(fname, format)\n 1351 raise ValueError('Only know how to handle extensions: %s; '\n 1352 'with Pillow installed matplotlib can handle '\n-> 1353 'more images' % list(handlers))\n 1354 return im\n 1355 \n\nValueError: Only know how to handle extensions: [u'png']; with Pillow installed matplotlib can handle more images!pip install pillow\n\n```python\nimg = np.array(plt.imread('cameraman.jpg'), dtype=int)\nplt.matshow(img);\n```\n\nThe image is a $64\\times 64$ low-resolution version of the famous \"cameraman\" test picture. Out of curiosity, we can look at the first column of this image, which is is a $64×1$ vector:\n\n\n```python\nimg[:,0]\n```\n\n\n\n\n array([156, 157, 157, 152, 154, 155, 151, 157, 152, 155, 158, 159, 159,\n 160, 160, 161, 155, 160, 161, 161, 164, 162, 160, 162, 158, 160,\n 158, 157, 160, 160, 159, 158, 163, 162, 162, 157, 160, 114, 114,\n 103, 88, 62, 109, 82, 108, 128, 138, 140, 136, 128, 122, 137,\n 147, 114, 114, 144, 112, 115, 117, 131, 112, 141, 99, 97])\n\n\n\nThe values are integers between zero and 255, meaning that each pixel is encoded over 8 bits (or 256 gray levels).\n\n## The canonical basis\n\nThe canonical basis for any matrix space $\\mathbb{R}^{M\\times N}$ is the set of \"delta\" matrices where only one element equals to one while all the others are 0. Let's call them $\\mathbf{E}_n$ with $0 \\leq n < MN$. Here is a function to create the canonical basis vector given its index:\n\n\n```python\ndef canonical(n, M=5, N=10):\n e = np.zeros((M, N))\n #e[(n % M), int(n / M)] = 1\n e[n % M, n // M] = 1\n return e\n```\n\n\n```python\n!python --version\n```\n\n Python 3.8.2\r\n\n\n\n```python\n10 / 3, 10 // 3, int(10/3)\n```\n\n\n\n\n (3.3333333333333335, 3, 3)\n\n\n\nHere are some basis vectors: look for the position of white pixel, which differentiates them and note that we enumerate pixels column-wise:\n\n\n```python\nplt.matshow(canonical(0));\nplt.matshow(canonical(1));\nplt.matshow(canonical(49));\n```\n\nNote how diff `matshow()` is from `imshow()`:\n> In a jupyter cell, successive `matshow()`'s can draw any number of images, while `imshow()` will only do it for the last one\n\n\n```python\nplt.imshow(canonical(0));\nplt.imshow(canonical(1));\nplt.imshow(canonical(49));\n```\n\n##### Stopped here (2020/11/19 12h25)\n\n## Transmitting images\n\nSuppose we want to transmit the \"cameraman\" image over a communication channel. The intuitive way to do so is to send the pixel values one by one, which corresponds to sending the coefficients of the decomposition of the image over the canonical basis. So far, nothing complicated: to send the cameraman image, for instance, we will send $64\\times 64 = 4096$ coefficients in a row. \n\nNow suppose that a communication failure takes place after the first half of the pixels have been sent. The received data will allow us to display an approximation of the original image only. If we replace the missing data with zeros, here is what we would see, which is not very pretty:\n\n\n```python\n# unrolling of the image for transmission (we go column by column, hence \"F\")\ntx_img = np.ravel(img, \"F\")\n\n# oops, we lose half the data\ntx_img[int(len(tx_img)/2):] = 0\n\n# rebuild matrix\nrx_img = np.reshape(tx_img, (64, 64), \"F\")\nplt.matshow(rx_img);\n```\nhelp(np.ravel)\nCan we come up with a trasmission scheme that is more robust in the face of channel loss? Interestingly, the answer is yes, and it involves a different, more versatile basis for the space of images. What we will do is the following: \n\n* describe the Haar basis, a new basis for the image space\n* project the image in the new basis\n* transmit the projection coefficients\n* rebuild the image using the basis vectors\n\nWe know a few things: if we choose an orthonormal basis, the analysis and synthesis formulas will be super easy (a simple inner product and a scalar multiplication respectively). The trick is to find a basis that will be robust to the loss of some coefficients. \n\nOne such basis is the **Haar basis**. We cannot go into too many details in this notebook but, for the curious, a good starting point is [here](https://chengtsolin.wordpress.com/2015/04/15/real-time-2d-discrete-wavelet-transform-using-opengl-compute-shader/). (An even better starting point is [these two papers](http://grail.cs.washington.edu/projects/wavelets/article/).) Mathematical formulas aside, the Haar basis works by encoding the information in a *hierarchical* way: the first basis vectors encode the broad information and the higher coefficients encode the detail. Let's have a look. \n\nFirst of all, to keep things simple, we will remain in the space of square matrices whose size is a power of two. The code to generate the Haar basis matrices is the following: first we generate a 1D Haar vector and then we obtain the basis matrices by taking the outer product of all possible 1D vectors (don't worry if it's not clear, the results are what's important):\n\n\n```python\ndef haar1D(n, SIZE):\n # check power of two\n if math.floor(math.log(SIZE) / math.log(2)) != math.log(SIZE) / math.log(2):\n print(\"Haar defined only for lengths that are a power of two\")\n return None\n if n >= SIZE or n < 0:\n print(\"invalid Haar index\")\n return None\n \n # zero basis vector\n if n == 0:\n return np.ones(SIZE)\n \n # express n >= 1 as 2^p + q with p as large as possible;\n # then k = SIZE/2^p is the length of the support\n # and s = qk is the shift\n p = math.floor(math.log(n) / math.log(2))\n pp = int(pow(2, p))\n k = SIZE / pp\n s = (n - pp) * k\n \n h = np.zeros(SIZE)\n h[int(s):int(s+k/2)] = 1\n h[int(s+k/2):int(s+k)] = -1\n # these are not normalized\n return h\n\n\ndef haar2D(n, SIZE=8):\n # get horizontal and vertical indices\n hr = haar1D(n % SIZE, SIZE)\n hv = haar1D(int(n / SIZE), SIZE)\n # 2D Haar basis matrix is separable, so we can\n # just take the column-row product\n H = np.outer(hr, hv)\n # np.outer() is just column vector times row vector,\n # the 1st arg being the col vec, the 2nd the row vec.\n H = H / math.sqrt(np.sum(H * H))\n # the previous line just divides H by its Frobenius norm\n # so that the returned value of haar2D() has norm 1.\n return H\n```\nhelp(np.outer)\nFirst of all, let's look at a few basis matrices; note that the matrices have **both positive and negative values**, so that the value of **zero** will be represented as **gray**:\n\n\n```python\nplt.matshow?\n```\n\n\n```python\nplt.matshow(haar2D(0));\nplt.matshow(haar2D(1));\nplt.matshow(haar2D(10));\nplt.matshow(haar2D(63));\n```\n\n\n```python\nnp.unique(haar2D(0))\n```\n\n\n\n\n array([0.125])\n\n\n\n\n```python\nnp.unique(haar2D(1))\n```\n\n\n\n\n array([-0.125, 0.125])\n\n\n\n\n```python\nnp.unique(haar2D(63))\n```\n\n\n\n\n array([-0.5, 0. , 0.5])\n\n\n\n\n```python\nwhite = np.unique(haar2D(0))[0]\nblack = -white\nplt.matshow(haar2D(0), vmax=white, vmin=black);\n```\n\nWe can notice two key properties\n\n* each basis matrix has positive and negative values in some symmetric pattern: this means that the basis matrix will implicitly compute the difference between image areas\n* low-index basis matrices take differences between large areas, while high-index ones take differences in smaller **localized** areas of the image\n\nWe can immediately verify that the Haar matrices are orthogonal:\n\n\n```python\n# let's use an 8x8 space; there will be 64 basis vectors\n# compute all possible inner product and only print the nonzero results\nfor m in range(0,64):\n for n in range(0,64):\n r = np.sum(haar2D(m, 8) * haar2D(n, 8))\n if r != 0:\n print(\"[%dx%d -> %f] \" % (m, n, r), end=\"\")\n```\n\n [0x0 -> 1.000000] [1x1 -> 1.000000] [2x2 -> 1.000000] [3x3 -> 1.000000] [4x4 -> 1.000000] [5x5 -> 1.000000] [6x6 -> 1.000000] [7x7 -> 1.000000] [8x8 -> 1.000000] [9x9 -> 1.000000] [10x10 -> 1.000000] [11x11 -> 1.000000] [12x12 -> 1.000000] [13x13 -> 1.000000] [14x14 -> 1.000000] [15x15 -> 1.000000] [16x16 -> 1.000000] [16x17 -> -0.000000] [17x16 -> -0.000000] [17x17 -> 1.000000] [18x18 -> 1.000000] [19x19 -> 1.000000] [20x20 -> 1.000000] [21x21 -> 1.000000] [22x22 -> 1.000000] [23x23 -> 1.000000] [24x24 -> 1.000000] [24x25 -> -0.000000] [25x24 -> -0.000000] [25x25 -> 1.000000] [26x26 -> 1.000000] [27x27 -> 1.000000] [28x28 -> 1.000000] [29x29 -> 1.000000] [30x30 -> 1.000000] [31x31 -> 1.000000] [32x32 -> 1.000000] [33x33 -> 1.000000] [34x34 -> 1.000000] [35x35 -> 1.000000] [36x36 -> 1.000000] [37x37 -> 1.000000] [38x38 -> 1.000000] [39x39 -> 1.000000] [40x40 -> 1.000000] [41x41 -> 1.000000] [42x42 -> 1.000000] [43x43 -> 1.000000] [44x44 -> 1.000000] [45x45 -> 1.000000] [46x46 -> 1.000000] [47x47 -> 1.000000] [48x48 -> 1.000000] [49x49 -> 1.000000] [50x50 -> 1.000000] [51x51 -> 1.000000] [52x52 -> 1.000000] [53x53 -> 1.000000] [54x54 -> 1.000000] [55x55 -> 1.000000] [56x56 -> 1.000000] [57x57 -> 1.000000] [58x58 -> 1.000000] [59x59 -> 1.000000] [60x60 -> 1.000000] [61x61 -> 1.000000] [62x62 -> 1.000000] [63x63 -> 1.000000] \n\nOK! Everything's fine. Now let's transmit the \"cameraman\" image: first, let's verify that it works\n\n\n```python\n# project the image onto the Haar basis, obtaining a vector of 4096 coefficients\n# this is simply the analysis formula for the vector space with an orthogonal basis\ntx_img = np.zeros(64*64)\nfor k in range(0, (64*64)):\n tx_img[k] = np.sum(img * haar2D(k, 64))\n\n# now rebuild the image with the synthesis formula; since the basis is orthonormal\n# we just need to scale the basis matrices by the projection coefficients\nrx_img = np.zeros((64, 64))\nfor k in range(0, (64*64)):\n rx_img += tx_img[k] * haar2D(k, 64)\n\nplt.matshow(rx_img);\n```\n\n\n```python\nnp.linalg.norm(img - rx_img, inf)\n```\n\n\n\n\n 2.112088282046898e-12\n\n\nhelp(np.linalg.norm)\nCool, it works! Now let's see what happens if we lose the second half of the coefficients:\n\n\n```python\n# oops, we lose half the data\nlossy_img = np.copy(tx_img);\nlossy_img[int(len(tx_img)/2):] = 0\n\n# rebuild matrix\nrx_img = np.zeros((64, 64))\nfor k in range(0, (64*64)):\n rx_img += lossy_img[k] * haar2D(k, 64)\n\nplt.matshow(rx_img);\n```\n\nThat's quite remarkable, no? We've lost the same amount of information as before but the image is still acceptable. This is because we lost the coefficients associated to the fine details of the image but we retained the \"broad strokes\" encoded by the first half. \n\nNote that if we lose the first half of the coefficients, the result would look remarkably different:\n\n\n```python\nlossy_img = np.copy(tx_img);\nlossy_img[0:int(len(tx_img)/2)] = 0\n\nrx_img = np.zeros((64, 64))\nfor k in range(0, (64*64)):\n rx_img += lossy_img[k] * haar2D(k, 64)\n\nplt.matshow(rx_img);\n```\n\nIn fact, schemes like this one are used in *progressive encoding*: send the most important information first and add details if the channel permits it. You may have experienced this while browsing the internet over a slow connection. \n\nAll in all, a great application of a change of basis!\n\n## A few of my own questions\n\n**(?)** About `# check power of two` of `haar1D()`\n\n\n```python\nhelp(math.log)\n```\n\n Help on built-in function log in module math:\n \n log(...)\n log(x[, base])\n \n Return the logarithm of x to the given base.\n If the base not specified, returns the natural logarithm (base e) of x.\n \n\n\n\n```python\nmath.log(2)\n```\n\n\n\n\n 0.6931471805599453\n\n\n\n\n```python\nmath.log(2, 2)\n```\n\n\n\n\n 1.0\n\n\n\n\n```python\nmath.log(2, 10)\n```\n\n\n\n\n 0.30102999566398114\n\n\n\nThe author is just checking whether\n$\n\\log_{2} \\texttt{SIZE} = \\frac{\\ln \\texttt{SIZE}}{\\ln 2}\n$\nis an integer.\n\n**N.B.** Unlike `math.log`, numpy has\n- `np.log`: Natural logarithm\n- `np.log2`: base 2\n- `np.log10`: base 10\n- `np.log1p`: log(1+p)\n\n**(?)** What is `n` in `haar2D()`?\nMust `n` be bounded?\n\n**(R)**\nFrom reading the code, it seems that if `SIZE = k`, then `n = 0, 1, 2, ..., k**2 -1`, like the above examples\n- when `SIZE=8`, `n = 0, 1, ..., 63`\n- when `SIZE=64`, `n = 0, 1, ..., 64**2 - 1`\n\nThe `n` in `haar2D()` has to do with the `n` in `haar1D()`. To better understand how the function is written that way, readers would better have read [one of the papers](http://grail.cs.washington.edu/projects/wavelets/article/wavelet1.pdf) mentioned above. Briefly speaking, `Haar1D(n , SIZE)` will return a basis for the vector space $V^j$, where with `SIZE`$ = 2^j$. For example, with the box basis and the Haar wavelets described in the paper,\n\n$$\n\\forall\\, f \\in V^3,\\; \\text{we have}\\\\\nf = \nc_{0}^{0} \\phi_{0}^{0}\n+ d_{0}^{0} \\psi_{0}^{0}\n+ \\left(d_{0}^{1} \\psi_{0}^{1} + d_{1}^{1} \\psi_{1}^{1}\\right)\n+ \\left(d_{0}^{2} \\psi_{0}^{2} + d_{1}^{2} \\psi_{1}^{2} + d_{2}^{2} \\psi_{2}^{2} + d_{3}^{2} \\psi_{3}^{2}\\right).\n$$\n
\nWhat `haar1D(n, SIZE)` does is that it returns those $\\phi_{s}^{t}$ and $\\psi_{s}^{t}$.
As you can see from the $V^3$ example, there should be $2^3$ such basis vectors/functions; in general, there will be `SIZE`$= 2^j$ basis vectors and that's why the subscript (here in the `haar1D` function `n`) runs from `0` to `SIZE-1`.\n\n**(?)** Is it correct for `haar2D` to normalize by Frobenius norm?\n\n**(R)**\n\n\n## Ref.\n- [http://grail.cs.washington.edu/projects/wavelets/](http://grail.cs.washington.edu/projects/wavelets/)\n - [http://grail.cs.washington.edu/Research/](http://grail.cs.washington.edu/Research/)\n- **exercise3.4 p.57** of the textbook written by the same authors of the course also talks about Haar basis. \n\n\n```python\ntype(pow(2,3)), type(pow(2,3.0))\n```\n\n\n\n\n (int, float)\n\n\n\n\n```python\npow(2,3), pow(2,3.0)\n```\n\n\n\n\n (8, 8.0)\n\n\n\n\n```python\n2**3, 2**3.0\n```\n\n\n\n\n (8, 8.0)\n\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "069c785a4dedfd845f1cebf03b3abe4464474103", "size": 164646, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "epfl/2020/hw-ipynb/HaarBasis/hb.ipynb", "max_stars_repo_name": "phunc20/dsp", "max_stars_repo_head_hexsha": "e7c496eb5fd4b8694eab0fc049cf98a5e3dfd886", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-03-12T18:32:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-12T18:32:06.000Z", "max_issues_repo_path": "epfl/2020/hw-ipynb/HaarBasis/hb.ipynb", "max_issues_repo_name": "phunc20/dsp", "max_issues_repo_head_hexsha": "e7c496eb5fd4b8694eab0fc049cf98a5e3dfd886", "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": "epfl/2020/hw-ipynb/HaarBasis/hb.ipynb", "max_forks_repo_name": "phunc20/dsp", "max_forks_repo_head_hexsha": "e7c496eb5fd4b8694eab0fc049cf98a5e3dfd886", "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": 106.1547388781, "max_line_length": 17060, "alphanum_fraction": 0.8275573048, "converted": true, "num_tokens": 8332, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475699138558, "lm_q2_score": 0.9059898140375993, "lm_q1q2_score": 0.8546632894390754}} {"text": "# Lotka-Volterra Introduction\n\nThe Lotka-Volterra model is a basic dynamic model named after two biomathematicians, Alfred Lotka and Vito Volterra,\nwho developed the system of equations independent of each other in the first half of the twentieth century.\nLotka had developed the model to explain the dynamics of predator and prey populations, expanding on his previous model\nof autocatalytic chemical reactions. Volterra had developed the system of equations to model the population of predator\nfish in the Adriatic Sea.\n\nThe basic system consists of two linear ordinary differential equations (ode). One equation represents the change in population of\nthe prey over time and is dependent on the population of the predator. The other equation represents the same but\nfor the predator population.\n\nAs an example, we let the prey be sheep and the predators be wolves.\nIf sheep were to exist without a predator and without a limitation of resources, the population would grow\nexponentially:\n\n> $ \\frac{dx}{dt}=\\alpha*x , $\n\nwhere $\\alpha$ is a constant rate of growth and $x$ is the number of sheep.\n\nIf wolves were added to the environment, then the sheep population would depend on how\noften they met with the wolves. If there are more wolves, then there is more likelihood that they would meet sheep and\neat one. If there are more sheep, then they would have more likelihood of meeting wolves. If a wolf eats a sheep anytime\nit finds one, then the death of the sheep is proportional to how many wolves there are. This relationship is the same\nas the law of mass action, the rate of the chemical reaction is proportional to the concentration of the reactants.\nIn this case, the death of the sheep is then represented by a constant multiplied by the population of the sheep and the\npopulation of the wolves. The sheep population equation is represented as:\n\n> $ \\frac{dx}{dt}=\\alpha*x-\\beta*x*y $\n\nThe equation for the population of the wolves is given as:\n\n> $ \\frac{dy}{dt} = \\delta x y - \\gamma y, $\n\nwhere $y$ is the wolf population, $\\delta$ is the growth rate of the wolves that is proportional to number of sheep and\nwolves and $\\gamma$ is the mortality rate of the wolves.\n\nThere are many assumptions with this model and some are stated here:\n- The sheep population grows exponentially without the presence of wolves.\n- The wolves will always eat a sheep when it meets one.\n- The wolves only eat sheep.\n\nTo see the interaction between the wolf and sheep populations, let $\\alpha= 1.1, \\beta = 0.4, \\delta = 0.1, and \\gamma = 0.4$.\nIf we then solve this system, assuming time is in weeks, with initial population of 10 (thousands) sheep\nand 1 (thousand) wolf, the following plot shows the solutions on the interval [0,100] (100 weeks or a little under 2 years).\n\n\n```python\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport random\nfrom scipy.integrate import odeint as ode\nimport tabulate\n```\n\n\n```python\ninit_pop = [10,1] # initial population levels [prey, predator]\n\nt_steps = 1000 # time steps\nt_end = 100 # end of time interval\ntime = np.linspace(0, t_end, num=t_steps) # array to store time\n\nalpha = 1.1 # prey birthrate\nbeta = 0.4 # prey death rate\ndelta = 0.1 # predator birthrate\ngamma = 0.4 # predator death rate\n\nk = 150 # prey carrying capacity\nk_y = 100 # predator carrying capacity\n# Array to track coefficients\ncoef = [alpha, beta, delta, gamma]\n```\n\n\n```python\n# Define the simulation function\ndef run_simu(tmp_pop, tmp_time, tmp_coef):\n\n tmp_x = tmp_pop[0] # Prey population value\n tmp_y = tmp_pop[1] # Predator population value\n\n tmp_alpha = tmp_coef[0]\n tmp_beta = tmp_coef[1]\n tmp_delta = tmp_coef[2]\n tmp_gamma = tmp_coef[3]\n\n dxdt = tmp_alpha * tmp_x - tmp_beta * tmp_x * tmp_y\n dydt = tmp_delta * tmp_x * tmp_y - tmp_gamma * tmp_y\n\n return[dxdt, dydt]\n\n# Call the ode solver function\noutput = ode(run_simu, init_pop, time, args = (coef,))\n\nplt.plot(time, output[:,0], color = \"green\", label = \"Prey Population\") # Prey output\nplt.plot(time, output[:,1], color = \"red\", label = \"Predator Population\") # Prey output\n\nplt.xlabel(\"Time\")\nplt.ylabel(\"Population Level\")\n\nplt.title(\"Predator / Prey Dynamics\")\nplt.legend()\nplt.grid()\n\nplt.show()\n```\n\nIt makes sense that we see oscillations in the populations as seen in the plot because we have negative\nfeedback. As the predator population approaches its maximum, the prey population decreases rapidly. Then\nafter the predator population has decreased, the prey population begins to increase and eventually the predator population\nwill begin to increase again.\n\nThe steady state of the model is when there is equilibrium between the populations.\n\nTo find the steady state we need to find the equilibrium points.\nIn other words, we want to know when the rate of change (derivative) is equal to zero.\n\nThe not-so-meaningful solution is when the prey and the predator populations are zero.\n\nThe more meaningful populations can be solved:\n\n> $ \\begin{align}\n>0 &= \\alpha x - \\beta x y \\\\\n>0 &= x ( \\alpha - \\beta y ) \\\\\n> y &= \\frac{\\alpha}{\\beta} \\text{ or }x = 0\n> \\end{align} $\n\n> $ \\begin{align}\n>0 &= \\delta x y - \\gamma y \\\\\n>0 &= y ( \\delta x - \\gamma ) \\\\\n> x &= \\frac{\\gamma}{\\delta} \\text{ or }y = 0\n> \\end{align} $\n\nThe non-zero equilibrium point for this system is $ (\\frac{\\gamma}{\\delta}, \\frac{\\alpha}{\\beta}) $\n\nIf we change our birth and death rate parameters to visualize this, we see that it is in fact an equilibrium state.\n\n\n```python\nalpha_eq = 1.1 # prey birthrate\nbeta_eq = 1.1 # prey death rate\ndelta_eq = 0.4 # predator birthrate\ngamma_eq = 4 # predator death rate\n\n# Array to track coefficients\ncoef_eq = [alpha_eq, beta_eq, delta_eq, gamma_eq]\n\n# Call the ode solver function\noutput_eq = ode(run_simu, init_pop, time, args = (coef_eq,))\n\nplt.plot(time, output_eq[:,0], color = \"green\", label = \"Prey Population\") # Prey output\nplt.plot(time, output_eq[:,1], color = \"red\", label = \"Predator Population\") # Prey output\n\nplt.xlabel(\"Time\")\nplt.ylabel(\"Population Level\")\n\nplt.title(\"Predator / Prey Dynamics\")\nplt.legend()\nplt.grid()\n\nplt.show()\n\n```\n\nIt would be interesting to see how the change in the parameters will change the dynamics of the populations.\nTo visualize this, we can make a phase space plot with varying parameter values.\n\n\n```python\ndef run_range_ode(lrange, urange, tmp_run_simu, tmp_init_pop, tmp_time, coef_base):\n\n output_range = [np.zeros((t_steps,2)), np.zeros((t_steps,2)),\n np.zeros((t_steps,2)), np.zeros((t_steps,2)),\n np.zeros((t_steps,2)), np.zeros((t_steps,2)),\n np.zeros((t_steps,2)), np.zeros((t_steps,2))]\n\n idx = 0 # index to track output array storage\n\n for num in [0,1,2,3]:\n # for i in range(len(coef_base)):\n coef_new = coef_base[:]\n for j in [lrange,urange]:\n coef_new[num] = round(coef_base[num] + j, 2)\n output_temp = ode(tmp_run_simu, tmp_init_pop, tmp_time, args = (coef_new,))\n output_range[idx] = output_temp\n idx = idx + 1\n\n return output_range\n\noutput_vary = run_range_ode(-0.2, 0.2, run_simu, init_pop, time, coef)\n```\n\n\n```python\n# original parameters\nplt.plot(output[:,0], output[:,1], color = \"black\", label = \"a: 1.1, b: 0.4, d:0.1, g: 0.4\")\n\n# alpha changes\nplt.plot(output_vary[0][:,0], output_vary[0][:,1], color = \"mediumvioletred\", label = \"alpha: 0.9\")\nplt.plot(output_vary[1][:,0], output_vary[1][:,1], color = \"hotpink\", label = \"alpha: 1.3\")\n\n# beta changes\n#plt.plot(output_vary[2][:,0], output_vary[2][:,1], color = \"gold\", label = \"beta: 0.2\")\n#plt.plot(output_vary[3][:,0], output_vary[3][:,1], color = \"goldenrod\", label = \"beta: 0.8\")\n\n# delta changes\n#plt.plot(output_vary[4][:,0], output_vary[4][:,1], color = \"springgreen\", label = \"delta: 0.05\")\n#plt.plot(output_vary[5][:,0], output_vary[5][:,1], color = \"green\", label = \"delta: 0.2\")\n\n# gamma changes\nplt.plot(output_vary[6][:,0], output_vary[6][:,1], color = \"aqua\", label = \"gamma: 0.2\")\nplt.plot(output_vary[7][:,0], output_vary[7][:,1], color = \"darkcyan\", label = \"gamma: 0.8\")\n\n#plt.plot(output)\nplt.xlabel(\"Prey Population\")\nplt.ylabel(\"Predator Population\")\n\nplt.title(\"Predator / Prey Phase Space Plot\")\nplt.legend()\nplt.grid()\n\nplt.show()\n```\n\nThe black line is the phase plot with the original parameters. It is a closed orbit that oscillates around the\nfixed point $ (\\frac{\\gamma}{\\delta}, \\frac{\\alpha}{\\beta}) = (4, 2.75) $ (one of the equilibrium points).\n\nWhen keeping all other parameters constant and changing only $\\alpha$, the ellipse would stretch or shrink vertically.\nAdjusting the values of only $\\gamma$, the ellipse would stretch or shrink horizontally. This is because the closed\norbit oscillates around the fixed point and when we change $\\gamma$, we change the x-value of the fixed point and when\nwe change $\\alpha$ we change the y value.\n\nThese dynamics can be proven algebraically using concepts from linear algebra (calculating the eigenvalue and\neigenvector of the Jacobian matrix).\n\n\nThe assumption that the prey grow exponentially in the absence of predators is not realistic.\nA more realistic approach is to assume there is a carrying capacity. When the sheep population is below the environmental\ncarrying capacity, the growth rate is large. When the sheep population is equal to it's carrying capacity, there is no\ngrowth and when the sheep population is above the carrying capacity, there is negative growth.\n\nIncorporating the carrying capacity into the model would alter the sheep population ode:\n\n> $ \\frac{dx}{dt} = \\alpha x (1-\\frac{x}{K}), $\n\nwhere $K$ is carrying capacity.\n\nNow we need to add the predators to the environment:\n\n> $ \\frac{dx}{dt} = \\alpha x (1-\\frac{x}{K}) - \\beta x y $\n\nAnd the predator equation remains the same:\n\n>$ \\frac{dy}{dt} = \\delta x y - \\gamma y $\n>\n\nUsing these updated ODEs, we can rerun our system and visualize the dynamics.\n\n\n```python\n# Define the simulation function\ndef run_simu_carry_cap(tmp_pop, tmp_time, tmp_coef):\n\n tmp_x = tmp_pop[0] # Prey population value\n tmp_y = tmp_pop[1] # Predator population value\n\n tmp_alpha = tmp_coef[0]\n tmp_beta = tmp_coef[1]\n tmp_delta = tmp_coef[2]\n tmp_gamma = tmp_coef[3]\n\n dxdt = tmp_alpha * tmp_x * (1 - (tmp_x/k)) - tmp_beta * tmp_x * tmp_y\n dydt = tmp_delta * tmp_x * tmp_y - tmp_gamma * tmp_y\n #dxdt = tmp_alpha * x * (1 - ((x+tmp_beta*y)/k))\n #dydt = tmp_delta * x * y - tmp_gamma * y\n\n return[dxdt, dydt]\n\n# Call the ode solver function\noutput_carry_cap = ode(run_simu_carry_cap, init_pop, time, args = (coef,))\n\nplt.plot(time, output_carry_cap[:,0], color = \"green\", label = \"Prey Population\") # Prey output\nplt.plot(time, output_carry_cap[:,1], color = \"red\", label = \"Predator Population\") # Prey output\n\nplt.xlabel(\"Time\")\nplt.ylabel(\"Population Level\")\n\nplt.title(\"Predator / Prey Dynamics with Prey Carrying Capacity\")\nplt.legend()\nplt.grid()\n\nplt.show()\n```\n\nThere is still an oscillation between the predator and prey populations, but the difference between the maximum and\nminimum values is decreasing. The non-zero steady state of this system has changed. Previously, it was\n$ (\\frac{\\gamma}{\\delta}, \\frac{\\alpha}{\\beta}) $, but now that has changed.\n\n> $ \\begin{align}\n> 0 &= \\alpha x (1-\\frac{x}{k}) - \\beta x y\n>\\end{align} $\n\nsubstitute $x =\\frac{\\gamma}{\\delta}$ and solve for $y$\n> $ \\begin{align}\n> 0 &= \\alpha \\frac{\\gamma}{\\delta} (1-\\frac{\\frac{\\gamma}{\\delta}}{k}) - \\beta\\frac{\\gamma}{\\delta} y \\\\\n> 0 &= \\alpha (1-\\frac{\\gamma}{\\delta k}) - \\beta y \\\\\n> y &= \\frac{\\alpha}{\\beta}(1-\\frac{\\gamma}{\\delta k}) \\\\\n> \\end{align} $\n\nThe non-zero new steady state is $(\\frac{\\gamma}{\\delta}, \\frac{\\alpha}{\\beta}(1-\\frac{\\gamma}{\\delta k}))$\n\nWith the narrowing of the prey and predator population, we know that our phase plot will spiral instead of have an\nellipse.\n\n\n```python\n# original parameters\nplt.plot(output_carry_cap[:,0], output_carry_cap[:,1], color = \"black\", label = \"original\")\n\n#plt.plot(output)\nplt.xlabel(\"Prey Population\")\nplt.ylabel(\"Predator Population\")\n\nplt.title(\"Predator / Prey with Carrying Capacity Phase Plot\")\nplt.legend()\nplt.grid()\n\nplt.show()\n\n```\n\nTo add stochastic behavior to our system, we can use an algorithm to randomly choose events\nand event times from probability distributions.\nWe can use the Gillespie algorithm to do this.\n\nWe keep track of the population of the predator and prey. An event occurs when birth or death\noccurs in either the prey or predator population. The propensity for each event to occur at a given\ntime is shown in the table below.\n\n\n```python\ndata = [['Prey + 1', 'alpha * x * (1 - x/k)'],\n['Prey - 1', 'beta * x * y'],\n['Predator + 1', 'delta * x * y'],\n['Predator - 1','gamma * y']]\n\nprint(tabulate(data, headers=[\"Events\", \"Propensity\"]))\n\n```\n\n\n```python\n# Initial conditions\n# Original init_pop = [10,1]. Too likely for prey/predator to die out with 10 and 1\nx = [10] # track prey\ny = [1] # track predator\nt = [0] # to keep track of time\nend = 100\n\nx_all = [] # track results of prey from all model runs\ny_all = [] # track results of predator from all model runs\nt_all = []\n# Keep same rates of coefficients as above\n#alpha = 10 # prey birthrate\n#beta = 0.1 # prey death rate\n#delta = 0.3 # predator birthrate\n#gamma = 30 # predator death rate\n\n#k = 150\n#k_y = 100\n#r = 0.05\n#K = 100\nfor i in range(0,5): # simulate the model 100 times\n t = [0] # reset time to rerun\n x = [10] # reset time to rerun\n y = [1] # reset time to rerun\n i = i+1\n while t[-1] < end: # keep running until last item in t is after end\n #current_x = x[-1]\n props = [alpha * x[-1] * (1- x[-1]/k),\n beta*x[-1]*y[-1],\n delta*x[-1]*y[-1],\n gamma * y[-1]]\n prop_sum = sum(props)\n #print(\"x: \", x[-1], \"; y: \", y[-1])\n if prop_sum == 0: # can not divide by zero so break out of while loop\n break\n\n # choose next time increment randomly from exponential distribution with mean = 1/prop_sum\n #tau = np.random.exponential(scale=1/prop_sum)\n tau = np.random.uniform(0.5, 4.5)\n\n # add the randomly chosen tau to the current time\n t.append(t[-1]+tau)\n\n # randomly choose number to later weight with probability of events\n # to randomly choose which event that will occur at the next time point\n rand = random.uniform(0,1)\n\n if rand * prop_sum <= props[0]: # growth of prey\n x.append(x[-1] + 1)\n y.append(y[-1])\n elif rand * prop_sum > props[0] and rand * prop_sum <= props[0] + props[1]: # death of prey\n x.append(x[-1] - 1)\n y.append(y[-1])\n elif rand * prop_sum > props[0] and rand * prop_sum <= props[0] + props[1] + props[2]: # death of predator\n x.append(x[-1])\n y.append(y[-1] + 1)\n else:\n x.append(x[-1])\n y.append(y[-1] - 1)\n\n x_all.append(x)\n y_all.append(y)\n t_all.append(t)\n\n# plot results\nfor i in range(len(x_all)):\n plt.plot(t_all[i],x_all[i], color = \"green\")\n plt.plot(t_all[i],y_all[i], color = \"red\")\n\nplt.legend(['Prey', 'Predator'])\nplt.xlabel(\"Time\")\nplt.ylabel(\"Population\")\nplt.show()\n```\n\nIn the stochastic model, there are several simulations in which the predator and/or prey population becomes extinct.\nThis could be a more realistic situation, especially given that the original models showed the populations had fallen\nto very low numbers and could likely become extinct.\n\nIf we change the predator-prey model dynamics such that the two species are competing for the same resource(s), then we\ncan use the competitive Lotka-Volterra Equations which are slightly different:\n\n> $ \\frac{dx}{dt} = \\alpha x (1-\\frac{x+\\beta y}{K_x}) $\n> $ \\frac{dy}{dt} = \\delta y (1-\\frac{y+\\gamma x}{K_y}) $\n>\nSame as before, $\\alpha$ and $\\delta$ represent the growth of x and y populations, respectively. $\\beta$ and $\\gamma$\nare the effect that y has on x and x has on y, respectively. In this situation, both x and y populations have carrying\ncapacities.\n\nThis system (as with the others) is not restricted to two populations, it can be generalized to many more populations\ninteracting in the form:\n\n> $ \\frac{dx_i}{dt}=r_ix_i(1-\\frac{\\sum_{j=1}^{N} a_{ij}x_j}{K_i}) $,\n>\n\nwhere $r_i$ is the growth rate of $x_i$, N is the number of populations that interact with $x_i$ and $K_i$ is the\ncarrying capacity for $x_i$.\n", "meta": {"hexsha": "b9e4141f9e2892e1192092602b4c0bcc34d4dca6", "size": 276295, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "_build/jupyter_execute/_sources/lotka-volterra.ipynb", "max_stars_repo_name": "kmoriarty123/lotka-volterra", "max_stars_repo_head_hexsha": "76788e0e534ce934882089ad8eb21a8118d623ef", "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": "_build/jupyter_execute/_sources/lotka-volterra.ipynb", "max_issues_repo_name": "kmoriarty123/lotka-volterra", "max_issues_repo_head_hexsha": "76788e0e534ce934882089ad8eb21a8118d623ef", "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": "_build/jupyter_execute/_sources/lotka-volterra.ipynb", "max_forks_repo_name": "kmoriarty123/lotka-volterra", "max_forks_repo_head_hexsha": "76788e0e534ce934882089ad8eb21a8118d623ef", "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": 365.4695767196, "max_line_length": 67049, "alphanum_fraction": 0.9217322065, "converted": true, "num_tokens": 4493, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475715065793, "lm_q2_score": 0.9059898108646849, "lm_q1q2_score": 0.8546632878889056}} {"text": "# Functions\nWe've the next function:\n\\begin{equation}f(x) = x^{3} - 6x^{2} - 15x + 40 \\end{equation}\n\n## Important Elements \n- f' and f'' \n- \\begin{equation}f'(x) = 3x^{2} - 12x - 15 \\end{equation}\n- \\begin{equation}f''(x) = 6x - 12 \\end{equation}\n- Critical Points $(x_1=-1:max ; x_2=5:min)$\n- increasing and decreasing $(↗↘)$\n- Infection Points $x_1=2$\n- $Concave ⋂ and ⋃$\n- Principal Points ${(-1,48);(2,-6);(5,-60)}$\n\n\n# Critical Points and Optimization\nWe've explored various techniques that we can use to calculate the derivative of a function at a specific *x* value; in other words, we can determine the *slope* of the line created by the function at any point on the line.\n\nThis ability to calculate the slope means that we can use derivatives to determine some interesting properties of the function.\n\n## Function Direction at a Point\nConsider the following function, which represents the trajectory of a ball that has been kicked on a football field:\n\n\\begin{equation}k(x) = -10x^{2} + 100x + 3 \\end{equation}\n\nRun the Python code below to graph this function and see the trajectory of the ball over a period of 10 seconds.\n\n\n```python\n%matplotlib inline\n\n# Create function k\ndef k(x):\n return -10*(x**2) + (100*x) + 3\n\nfrom matplotlib import pyplot as plt\n\n# Create an array of x values to plot\nx = list(range(0, 11))\n\n# Use the function to get the y values\ny = [k(i) for i in x]\n\n# Set up the graph\nplt.xlabel('x (time in seconds)')\nplt.ylabel('k(x) (height in feet)')\nplt.xticks(range(0,15, 1))\nplt.yticks(range(-200, 500, 20))\nplt.grid()\n\n# Plot the function\nplt.plot(x,y, color='green')\n\nplt.show()\n```\n\nBy looking at the graph of this function, you can see that it describes a parabola in which the ball rose in height before falling back to the ground. On the graph, it's fairly easy to see when the ball was rising and when it was falling.\n\nOf course, we can also use derivative to determine the slope of the function at any point. We can apply some of the rules we've discussed previously to determine the derivative function:\n\n- We can add together the derivatives of the individual terms (***-10x2***, ***100x***, and ***3***) to find the derivative of the entire function.\n- The *power* rule tells us that the derivative of ***-10x2*** is ***-10 • 2x***, which is ***-20x***.\n- The *power* rule also tells us that the derivative of ***100x*** is ***100***.\n- The derivative of any constant, such as ***3*** is ***0***.\n\nSo:\n\n\\begin{equation}k'(x) = -20x + 100 + 0 \\end{equation}\n\nWhich of course simplifies to:\n\n\\begin{equation}k'(x) = -20x + 100 \\end{equation}\n\nNow we can use this derivative function to find the slope for any value of ***x***.\n\nRun the cell below to see a graph of the function and its derivative function:\n\n\n```python\n%matplotlib inline\n\n# Create function k\ndef k(x):\n return -10*(x**2) + (100*x) + 3\n\ndef kd(x):\n return -20*x + 100\n\nfrom matplotlib import pyplot as plt\n\n# Create an array of x values to plot\nx = list(range(0, 11))\n\n# Use the function to get the y values\ny = [k(i) for i in x]\n\n# Use the derivative function to get the derivative values\nyd = [kd(i) for i in x]\n\n# Set up the graph\nplt.xlabel('x (time in seconds)')\nplt.ylabel('k(x) (height in feet)')\nplt.xticks(range(0,15, 1))\nplt.yticks(range(-200, 500, 20))\nplt.grid()\n\n# Plot the function\nplt.plot(x,y, color='green')\n\n# Plot the derivative\nplt.plot(x,yd, color='purple')\n\nplt.show()\n```\n\nLook closely at the purple line representing the derivative function, and note that it is a constant decreasing value - in other words, the slope of the function is reducing linearly as x increases. Even though the function value itself is increasing for the first half of the parabola (while the ball is rising), the slope is becoming less steep (the ball is not rising at such a high rate), until finally the ball reaches its apogee and the slope becomes negative (the ball begins falling).\n\nNote also that the point where the derivative line crosses 0 on the y-axis is also the point where the function value stops increasing and starts decreasing. When the slope has a positive value, the function is increasing; and when the slope has a negative value, the function is decreasing.\n\nThe fact that the derivative line crosses 0 at the highest point of the function makes sense if you think about it logically. If you were to draw the tangent line representing the slope at each point, it would be rotating clockwise throughout the graph, initially pointing up and to the right as the ball rises, and turning until it is pointing down and right as the ball falls. At the highest point, the tangent line would be perfectly horizontal, representing a slope of 0.\n\nRun the following code to visualize this:\n\n\n```python\n%matplotlib inline\n\n# Create function k\ndef k(x):\n return -10*(x**2) + (100*x) + 3\n\ndef kd(x):\n return -20*x + 100\n\nfrom matplotlib import pyplot as plt\n\n# Create an array of x values to plot\nx = list(range(0, 11))\n\n# Use the function to get the y values\ny = [k(i) for i in x]\n\n# Use the derivative function to get the derivative values\nyd = [kd(i) for i in x]\n\n# Set up the graph\nplt.xlabel('x (time in seconds)')\nplt.ylabel('k(x) (height in feet)')\nplt.xticks(range(0,15, 1))\nplt.yticks(range(-200, 500, 20))\nplt.grid()\n\n# Plot the function\nplt.plot(x,y, color='green')\n\n# Plot the derivative\nplt.plot(x,yd, color='purple')\n\n# Plot tangent slopes for x = 2, 5, and 8\nx1 = 2\nx2 = 5\nx3 = 8\nplt.plot([x1-1,x1+1],[k(x1)-(kd(x1)),k(x1)+(kd(x1))], color='red')\nplt.plot([x2-1,x2+1],[k(x2)-(kd(x2)),k(x2)+(kd(x2))], color='red')\nplt.plot([x3-1,x3+1],[k(x3)-(kd(x3)),k(x3)+(kd(x3))], color='red')\n\nplt.show()\n```\n\nNow consider the following function, which represents the number of flowers growing in a flower bed before and after the spraying of a fertilizer:\n\n\\begin{equation}w(x) = x^{2} + 2x + 7 \\end{equation}\n\n\n```python\n%matplotlib inline\n\n# Create function w\ndef w(x):\n return (x**2) + (2*x) + 7\n\ndef wd(x):\n return 2*x + 2\n\nfrom matplotlib import pyplot as plt\n\n# Create an array of x values to plot\nx = list(range(-10, 11))\n\n# Use the function to get the y values\ny = [w(i) for i in x]\n\n# Use the derivative function to get the derivative values\nyd = [wd(i) for i in x]\n\n# Set up the graph\nplt.xlabel('x (time in days)')\nplt.ylabel('w(x) (flowers)')\nplt.xticks(range(-10,15, 1))\nplt.yticks(range(-200, 500, 20))\nplt.grid()\n\n# Plot the function\nplt.plot(x,y, color='green')\n\n# Plot the derivative\nplt.plot(x,yd, color='purple')\n\nplt.show()\n```\n\nNote that the green line represents the function, showing the number of flowers for 10 days before and after the fertilizer treatment. Before treatment, the number of flowers was in decline, and after treatment the flower bed started to recover.\n\nThe derivative function is shown in purple, and once again shows a linear change in slope. This time, the slope is increasing at a constant rate; and once again, the derivative function line crosses 0 at the lowest point in the function line (in other words, the slope changed from negative to positive when the flowers started to recover).\n\n## Critical Points\nFrom what we've seen so far, it seems that there is a relationship between a function reaching an extreme value (a maximum or a minimum), and a derivative value of 0. This makes intuitive sense; the derivative represents the slope of the line, so when a function changes from a negative slope to a positive slope, or vice-versa, the derivative must pass through 0.\n\nHowever, you need to be careful not to assume that just because the derivative is 0 at a given point, that this point represents the minimum or maximum of the function. For example, consider the following function:\n\n\\begin{equation}v(x) = x^{3} - 2x + 100 \\end{equation}\n\nRun the following Python code to visualize this function and its corresponding derivative function:\n\n\n```python\n%matplotlib inline\n\n# Create function v\ndef v(x):\n return (x**3) - (2*x) + 100\n\ndef vd(x):\n return 3*(x**2) - 2\n\nfrom matplotlib import pyplot as plt\n\n# Create an array of x values to plot\nx = list(range(-10, 11))\n\n# Use the function to get the y values\ny = [v(i) for i in x]\n\n# Use the derivative function to get the derivative values\nyd = [vd(i) for i in x]\n\n# Set up the graph\nplt.xlabel('x')\nplt.ylabel('v(x)')\nplt.xticks(range(-10,15, 1))\nplt.yticks(range(-1000, 2000, 100))\nplt.grid()\n\n# Plot the function\nplt.plot(x,y, color='green')\n\n# Plot the derivative\nplt.plot(x,yd, color='purple')\n\nplt.show()\n```\n\nNote that in this case, the purple derivative function line passes through 0 as the green function line transitions from a *concave downwards* slope (a slope that is decreasing) to a *concave upwards* slope (a slope that is increasing). The slope flattens out to 0, forming a \"saddle\" before the it starts increasing.\n\nWhat we can learn from this is that interesting things seem to happen to the function when the derivative is 0. We call points where the derivative crosses 0 *critical points*, because they indicate that the function is changing direction. When a function changes direction from positive to negative, it forms a peak (or a *local maximum*), when the function changes direction from negative to positive it forms a trough (or *local minimum*), and when it maintains the same overall direction but changes the concavity of the slope it creates an *inflexion point*.\n\n## Finding Minima and Maxima\nA common use of calculus is to find minimum and maximum points in a function. For example, we might want to find out how many seconds it took for the kicked football to reach its maximum height, or how long it took for our fertilizer to be effective in reversing the decline of flower growth.\n\nWe've seen that when a function changes direction to create a maximum peak or a minimum trough, the derivative of the function is 0, so a step towards finding these extreme points might be to simply find all of the points in the function where the derivative is 0. For example, here's our function for the kicked football:\n\n\\begin{equation}k(x) = -10x^{2} + 100x + 3 \\end{equation}\n\nFrom this, we've calculated the function for the derivative as:\n\n\\begin{equation}k'(x) = -20x + 100 \\end{equation}\n\nWe can then solve the derivative equation for an f'(x) value of 0:\n\n\\begin{equation}-20x + 100 = 0 \\end{equation}\n\nWe can remove the constant by subtracting 100 to both sides:\n\n\\begin{equation}-20x = -100 \\end{equation}\n\nMultiplying both sides by -1 gets rid of the negative values (this isn't strictly necessary, but makes the equation a little less confusing)\n\n\\begin{equation}20x = 100 \\end{equation}\n\nSo:\n\n\\begin{equation}x = 5 \\end{equation}\n\nSo we know that the derivative will be 0 when *x* is 5, but is this a minimum, a maximum, or neither? It could just be an inflexion point, or the entire function could be a constant value with a slope of 0) Without looking at the graph, it's difficult to tell.\n\n## Second Order Derivatives\nThe solution to our problem is to find the derivative of the derivative! Until now, we've found the derivative of a function, and indicated it as ***f'(x)***. Technically, this is known as the *prime* derivative; and it describes the slope of the function. Since the derivative function is itself a function, we can find its derivative, which we call the *second order* (or sometimes just *second*) derivative. This is indicated like this: ***f''(x)***.\n\nSo, here's our function for the kicked football:\n\n\\begin{equation}k(x) = -10x^{2} + 100x + 3 \\end{equation}\n\nHere's the function for the prime derivative:\n\n\\begin{equation}k'(x) = -20x + 100 \\end{equation}\n\nAnd using a combination of the power rule and the constant rule, here's the function for the second derivative:\n\n\\begin{equation}k''(x) = -20 \\end{equation}\n\nNow, without even drawing the graph, we can see that the second derivative has a constant value; so we know that the slope of the prime derivative is linear; and because it's a negative value, we know that it is decreasing. So when the prime derivative crosses 0, it we know that the slope of the function is decreasing linearly; so the point at *x=0* must be a maximum point.\n\nRun the following code to plot the function, the prime derivative, and the second derivative for the kicked ball:\n\n\n```python\n%matplotlib inline\n\n# Create function k\ndef k(x):\n return -10*(x**2) + (100*x) + 3\n\ndef kd(x):\n return -20*x + 100\n\ndef k2d(x):\n return -20\n\nfrom matplotlib import pyplot as plt\n\n# Create an array of x values to plot\nx = list(range(0, 11))\n\n# Use the function to get the y values\ny = [k(i) for i in x]\n\n# Use the derivative function to get the k'(x) values\nyd = [kd(i) for i in x]\n\n# Use the 2-derivative function to get the k''(x)\ny2d = [k2d(i) for i in x]\n\n# Set up the graph\nplt.xlabel('x (time in seconds)')\nplt.ylabel('k(x) (height in feet)')\nplt.xticks(range(0,15, 1))\nplt.yticks(range(-200, 500, 20))\nplt.grid()\n\n# Plot the function\nplt.plot(x,y, color='green')\n\n# Plot k'(x)\nplt.plot(x,yd, color='purple')\n\n# Plot k''(x)\nplt.plot(x,y2d, color='magenta')\n\nplt.show()\n```\n\nLet's take the same approach for the flower bed problem. Here's the function:\n\n\\begin{equation}w(x) = x^{2} + 2x + 7 \\end{equation}\n\nUsing the power rule and constant rule, gives us the prime derivative function:\n\n\\begin{equation}w'(x) = 2x + 2 \\end{equation}\n\nApplying the power rule and constant rule to the prime derivative function gives us the second derivative function:\n\n\\begin{equation}w''(x) = 2 \\end{equation}\n\nNote that this time, the second derivative is a positive constant, so the prime derivative (which is the slope of the function) is increasing linearly. The point where the prime derivative crosses 0 must therefore be a minimum. Let's run the code below to check:\n\n\n```python\n%matplotlib inline\n\n# Create function w\ndef w(x):\n return (x**2) + (2*x) + 7\n\ndef wd(x):\n return 2*x + 2\n\ndef w2d(x):\n return 2\n\nfrom matplotlib import pyplot as plt\n\n# Create an array of x values to plot\nx = list(range(-10, 11))\n\n# Use the function to get the y values\ny = [w(i) for i in x]\n\n# Use the derivative function to get the w'(x) values\nyd = [wd(i) for i in x]\n\n# Use the 2-derivative function to get the w''(x) values\ny2d = [w2d(i) for i in x]\n\n# Set up the graph\nplt.xlabel('x (time in days)')\nplt.ylabel('w(x) (flowers)')\nplt.xticks(range(-10,15, 1))\nplt.yticks(range(-200, 500, 20))\nplt.grid()\n\n# Plot the function\nplt.plot(x,y, color='green')\n\n# Plot w'(x)\nplt.plot(x,yd, color='purple')\n\n# Plot w''(x)\nplt.plot(x,y2d, color='magenta')\n\nplt.show()\n```\n\n## Critical Points that are *Not* Maxima or Minima\nOf course, it's possible for a function to form a \"saddle\" where the prime derivative is zero at a point that is not a minimum or maximum. Here's an example of a function like this:\n \n\\begin{equation}v(x) = x^{3} - 6x^{2} + 12x + 2 \\end{equation}\n\nAnd here's its prime derivative:\n \n\\begin{equation}v'(x) = 3x^{2} - 12x + 12 \\end{equation}\n \nLet's find a critical point where v'(x) = 0\n \n\\begin{equation}3x^{2} - 12x + 12 = 0 \\end{equation}\n\nFactor the x-terms\n \n\\begin{equation}3x(x - 4) = 12 \\end{equation}\n\nDivide both sides by 3:\n\n\\begin{equation}x(x - 4) = 4 \\end{equation}\n\nFactor the x terms back again\n\n\\begin{equation}x^{2} - 4x = 4 \\end{equation}\n\nComplete the square, step 1\n\n\\begin{equation}x^{2} - 4x + 4 = 0 \\end{equation}\n\nComplete the square, step 2\n\n\\begin{equation}(x - 2)^{2} = 0 \\end{equation}\n\nFind the square root:\n\n\\begin{equation}x - 2 = \\pm\\sqrt{0}\\end{equation}\n\n\\begin{equation}x - 2 = +\\sqrt{0} = 0, -\\sqrt{0} = 0\\end{equation}\n\nv'(2) = 0 (only touches 0 once)\n\nIs it a maximum or minimum? Let's find the second derivative:\n\n\\begin{equation}v''(x) = 6x - 12\\end{equation}\n\nSo\n\n\\begin{equation}v''(2) = 0\\end{equation}\n\nSo it's neither negative or positive, so it's not a maximum or minimum.\n\n\n```python\n%matplotlib inline\n\n# Create function v\ndef v(x):\n return (x**3) - (6*(x**2)) + (12*x) + 2\n\ndef vd(x):\n return (3*(x**2)) - (12*x) + 12\n\ndef v2d(x):\n return (3*(2*x)) - 12\n\nfrom matplotlib import pyplot as plt\n\n# Create an array of x values to plot\nx = list(range(-5, 11))\n\n# Use the function to get the y values\ny = [v(i) for i in x]\n\n# Use the derivative function to get the derivative values\nyd = [vd(i) for i in x]\n\n# Use the derivative function to get the derivative values\ny2d = [v2d(i) for i in x]\n\n# Set up the graph\nplt.xlabel('x')\nplt.ylabel('v(x)')\nplt.xticks(range(-10,15, 1))\nplt.yticks(range(-2000, 2000, 50))\nplt.grid()\n\n# Plot the function\nplt.plot(x,y, color='green')\n\n# Plot the derivative\nplt.plot(x,yd, color='purple')\n\n# Plot the derivative\nplt.plot(x,y2d, color='magenta')\n\nplt.show()\n\nprint (\"v(2) = \" + str(v(2)))\n\nprint (\"v'(2) = \" + str(vd(2)))\n\nprint (\"v''(2) = \" + str(v2d(2)))\n\n```\n\n## Optimization\nThe ability to use derivatives to find minima and maxima of a function makes it a useful tool for scenarios where you need to optimize a function for a specific variable.\n\n### Defining Functions to be Optimized\nFor example, suppose you have decided to build an online video service that is based on a subscription model. You plan to charge a monthly subscription fee, and you want to make the most revenue possible. The problem is that customers are price-sensitive, so if you set the monthly fee too high, you'll deter some customers from signing up. Conversely, if you set the fee too low, you may get more customers, but at the cost of reduced revenue.\n\nWhat you need is some kind of function that will tell you how many subscriptions you might expect to get based on a given fee. So you've done some research, and found a formula to indicate that the expected subscription volume (in thousands) can be calculated as 5-times the monthly fee subtracted from 100; or expressed as a function:\n\n\\begin{equation}s(x) = -5x + 100\\end{equation}\n\nWhat you actually want to optimize is monthly revenue, which is simply the number of subscribers multiplied by the fee:\n\n\\begin{equation}r(x) = s(x) \\cdot x\\end{equation}\n\nWe can combine ***s(x)*** into ***r(x)*** like this:\n\n\\begin{equation}r(x) = -5x^{2} + 100x\\end{equation}\n\n### Finding the Prime Derivative\nThe function ***r(x)*** will return the expected monthly revenue (in thousands) for any proposed fee (*x*). What we need to do now is to find the fee that yields the maximum revenue. Fortunately, we can use a derivative to do that.\n\nFirst, we need to determine the prime derivative of ***r(x)***, and we can do that easily using the power rule:\n\n\\begin{equation}r'(x) = 2 \\cdot -5x + 100\\end{equation}\n\nWhich is:\n\n\\begin{equation}r'(x) = -10x + 100\\end{equation}\n\n### Find Critical Points\nNow we need to find any critical points where the derivative is 0, as this could indicate a maximum:\n\n\\begin{equation}-10x + 100 = 0\\end{equation}\n\nLet's isolate the *x* term:\n\n\\begin{equation}-10x = -100\\end{equation}\n\nBoth sides are negative, so we can mulitply both by -1 to make them positive without affecting the equation:\n\n\\begin{equation}10x = 100\\end{equation}\n\nNow we can divide both sides by 10 to isolate *x*:\n\n\\begin{equation}x = \\frac{100}{10}\\end{equation}\n\nSo:\n\n\\begin{equation}x = 10\\end{equation}\n\n#### Check for a Maximum\nWe now know that with an *x* value of of **10**, the derivative is 0; or put another way, when the fee is 10, the slope indicating the change in subscription volume is flat. This could potentially be a point where the change in subscription volume has peaked (in other words, a maximum); but it could also be a minimum or just an inflexion point where the rate of change transitions from negative to positive.\n\nTo be sure, we can check the second order derivative. We can calculate this by applying the power rule to the prime derivative:\n\n\\begin{equation}r''(x) = -10\\end{equation}\n\nNote that the second derivative is a constant with a negative value. It will be the same for any point, including our critical point at *x=10*:\n\n\\begin{equation}r''(10) = -10\\end{equation}\n\nA negative value for the second derivative tells us that the derivative slope is moving in a negative direction at the point where it is 0, so the function value must be at a maximum.\n\nIn other words, the optimal monthly fee for our online video service is 10 - this will generate the maximum monthly revenue.\n\nRun the code below to show the function ***r(x)*** as a graph, and verify that the maximum point is at x = 10.\n\n\n```python\n%matplotlib inline\n\n# Create function s\ndef s(x):\n return (-5*x) + 100\n\n# Create function r\ndef r(x):\n return s(x) * x\n\nfrom matplotlib import pyplot as plt\n\n# Create an array of x values to plot\nx = list(range(0, 21))\n\n# Use the function to get the y values\ny = [r(i) for i in x]\n\n# Set up the graph\nplt.xlabel('x (monthly fee)')\nplt.ylabel('r(x) (revenue in $,000)')\nplt.xticks(range(0,22, 1))\nplt.yticks(range(0, 600, 50))\nplt.grid()\n\n# Plot the function\nplt.plot(x,y, color='green')\n\nplt.show()\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "093a90fe6e4ce23cc5063c4b15f4ae704fdf729f", "size": 245735, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "MathsToML/Module02-Derivatives and Optimization/02-04-Critical Points and Optimization.ipynb", "max_stars_repo_name": "hpaucar/data-mining-repo", "max_stars_repo_head_hexsha": "d0e48520bc6c01d7cb72e882154cde08020e1d33", "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": "MathsToML/Module02-Derivatives and Optimization/02-04-Critical Points and Optimization.ipynb", "max_issues_repo_name": "hpaucar/data-mining-repo", "max_issues_repo_head_hexsha": "d0e48520bc6c01d7cb72e882154cde08020e1d33", "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": "MathsToML/Module02-Derivatives and Optimization/02-04-Critical Points and Optimization.ipynb", "max_forks_repo_name": "hpaucar/data-mining-repo", "max_forks_repo_head_hexsha": "d0e48520bc6c01d7cb72e882154cde08020e1d33", "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": 775.1892744479, "max_line_length": 29210, "alphanum_fraction": 0.9304860927, "converted": true, "num_tokens": 5864, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582593509315, "lm_q2_score": 0.9184802484881361, "lm_q1q2_score": 0.8546075332564822}} {"text": "```python\nimport numpy as np\nimport pandas as pd\nimport scipy as sp\nimport sklearn as sl\nimport seaborn as sns; sns.set()\nimport matplotlib as mpl\nimport sympy as spy\nimport matplotlib.pyplot as plt\nimport scipy.fftpack\nfrom matplotlib import pyplot as plt\nfrom mpl_toolkits.mplot3d import axes3d\nfrom matplotlib import cm\nfrom scipy.fftpack import fft\nx = spy.Symbol('x')\n%matplotlib inline\n```\n\n# Tarea 4\n\nCon base a los métodos vistos en clase resuelva las siguientes dos preguntas\n\n## (A) Integrales\n\n* $\\int_{0}^{1}x^{-1/2}\\,\\text{d}x$ = 1.9936755351040816\n* $\\int_{0}^{\\infty}e^{-x}\\ln{x}\\,\\text{d}x$ = −𝛾 = -0.57721566490153286061\n* $\\int_{0}^{\\infty}\\frac{\\sin{x}}{x}\\,\\text{d}x$ = 𝜋/2 = 1.5707963267948966\n\n\n```python\ndef f1(x):\n if x >= 0:\n return x**(-1/2)\n return 0\nf1_v = np.vectorize(f1)\n```\n\n\n```python\nN = 1000000\nX1 = np.linspace(0.000001,1,N)\nY1 = f1_v(X1)\n#plt.scatter(X,Y)\n```\n\n\n```python\nsp.integrate.simpson(y=Y1, x=X1)\n```\n\n\n\n\n 1.9980152377229565\n\n\n\n\n```python\nresult2 = spy.integrate(spy.exp(-x)*spy.log(x),(x,0,np.inf))\nprint(result2,\" = \",float(result2))\n```\n\n -EulerGamma = -0.5772156649015329\n\n\n\n```python\nresult3 = spy.integrate(spy.sin(x)/x,(x,0,np.inf))\nprint(result3,\" = \",float(result3))\n```\n\n pi/2 = 1.5707963267948966\n\n\n## (B) Fourier\n\nCalcule la transformada rápida de Fourier para la función de la **Tarea 3 (D)** en el intervalo $[0,4]$ ($k$ máximo $2\\pi n/L$ para $n=25$). Ajuste la transformada de Fourier para los datos de la **Tarea 3** usando el método de regresión exacto de la **Tarea 3 (C)** y compare con el anterior resultado. Para ambos ejercicios haga una interpolación y grafique para comparar.\n\n\n```python\ndf = pd.read_pickle('ex1.gz')\nN = 25\nT = 2*np.pi*N / 100\nx = df.iloc[:,0].values\ny = df.iloc[:,1].values\ny_f = sp.fft.fft(y)\nx_f = np.linspace(0.0, 1.0/(2.0*T), N//2)\n\nplt.plot(x_f, 2.0/N * np.abs(y_f[:N//2]))\nplt.show()\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "95a53572e1cad37350d9783b30b2d57cd0995593", "size": 12179, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "soluciones/s.martinez13/tarea4/solucion.ipynb", "max_stars_repo_name": "japeinado/FISI2028-202120", "max_stars_repo_head_hexsha": "6b16a779f3e34bcbf35d8b5e0ea345cf50ffdadd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-08-17T19:19:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-08T12:26:41.000Z", "max_issues_repo_path": "soluciones/s.martinez13/tarea4/solucion.ipynb", "max_issues_repo_name": "japeinado/FISI2028-202120", "max_issues_repo_head_hexsha": "6b16a779f3e34bcbf35d8b5e0ea345cf50ffdadd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12, "max_issues_repo_issues_event_min_datetime": "2021-09-18T01:33:58.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-16T00:11:45.000Z", "max_forks_repo_path": "soluciones/s.martinez13/tarea4/solucion.ipynb", "max_forks_repo_name": "japeinado/FISI2028-202120", "max_forks_repo_head_hexsha": "6b16a779f3e34bcbf35d8b5e0ea345cf50ffdadd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 28, "max_forks_repo_forks_event_min_datetime": "2021-09-17T22:38:23.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-02T19:59:49.000Z", "avg_line_length": 54.3705357143, "max_line_length": 1595, "alphanum_fraction": 0.6312505132, "converted": true, "num_tokens": 696, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.935346511643776, "lm_q2_score": 0.913676530465412, "lm_q1q2_score": 0.8546041555416113}} {"text": "# How to Draw Ellipse of Covariance Matrix\nGiven a 2x2 covariance matrix, how to draw the ellipse representing it. The following function explains the method to visualize multivariate normal distributions and correlation matrices. Formulae for radii & rotation are provided for covariance matrix shown below\n\\begin{align}\n\\Sigma = \\begin{bmatrix} a & b \\\\ c & d \\end{bmatrix}\n\\end{align}\n\n## Radii and Rotation\n\n\\begin{align}\n\\lambda_{1,2} &= \\frac{a+c}{2} \\pm \\sqrt{\\left( \\frac{a-c}{2} \\right)^{2} + b^{2}} \\\\\n\\theta &= \\begin{cases} 0 & \\text{ if } b = 0 \\text{ and } a \\geq c \\\\\n \\frac{\\pi}{2} & \\text{ if } b = 0 \\text{ and } a < c \\\\\n \\text{atan2}(\\lambda_{1} - a, b) & \\text{ if } b \\neq 0 \n\\end{cases}\n\\end{align}\nHere, $\\theta$ is the angle in radians from positive x-axis to the ellipse's major axis in the counterclockwise direction. $\\sqrt{\\lambda_{1}}$ is the radius of the major axis (the longer radius) and $\\sqrt{\\lambda_{2}}$ is the radius of the minor axis (shorter radius). In $atan2(\\cdot, \\cdot)$, the first parameter is $y$ and second is $x$.\n\n\n```python\nimport random\nimport math\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport time\nfrom scipy.linalg import block_diag\nfrom scipy.special import erfinv\nfrom scipy.stats import t as tdist\nfrom numpy.linalg import inv\nfrom numpy import linalg as LA\nfrom matplotlib.patches import Ellipse\n```\n\n\n```python\ndef GetAngleAndRadii(covar):\n \"\"\"\n Given a covariance matrix, the function GetAngleAndRadii() calculates \n the major axis and minor axis radii and the orientation of the ellipse.\n \n Inputs:\n covar: 2x2 matrix\n \n Output:\n major_radius: Radius of the major axis of ellipse\n minor_radius: Radius of the minor axis of ellipse\n theta : Orientation angle in radians from positive x-axis\n to the ellipse's major axis in the counterclockwise direction\n \"\"\"\n \n # Infer the a,b,c values\n a = covar[0,0]\n b = covar[0,1]\n c = covar[1,1]\n \n if b > a:\n raise Exception(\"Sorry, covariance matrix is invalid - Cov[0,1] should be < Cov[0,0] \")\n \n lambda_1 = (a+c)/2 + math.sqrt(((a-c)/2)**2 + b**2)\n lambda_2 = (a+c)/2 - math.sqrt(((a-c)/2)**2 + b**2)\n \n # Infer the radii\n major_radius = math.sqrt(lambda_1)\n minor_radius = math.sqrt(lambda_2)\n \n # Infer the rotation\n if b == 0:\n if a >= c:\n theta = 0\n else:\n theta = pi/2\n else:\n theta = math.atan2(lambda_1-a, b)\n \n return major_radius, minor_radius, theta\n \n```\n\n\n```python\n# Check the above code\ncovar_check = np.array([[9,5],[5,4]])\nmajor_radius_check, minor_radius_check, theta_check = GetAngleAndRadii(covar_check)\nprint('major axis radius = ', round(major_radius_check,2), \n 'minor axis radius = ', round(minor_radius_check,2), \n 'orientation = ', round(theta_check,2), 'rad')\n```\n\n major axis radius = 3.48 minor axis radius = 0.95 orientation = 0.55 rad\n\n\n\n```python\ndef plot_ellipse(center, cov = None):\n\n # Get the center of ellipse\n x_cent, y_cent = center\n \n print('center x at: ', x_cent)\n print('center y at: ', y_cent)\n \n # Get Ellipse Properties from cov matrix\n if cov is not None:\n major_radius, minor_radius, theta_orient = GetAngleAndRadii(cov)\n print('major axis radius = ', round(major_radius,2), \n 'minor axis radius = ', round(minor_radius,2), \n 'orientation = ', round(theta_orient,2), 'rad')\n eig_vec,eig_val,u = np.linalg.svd(cov)\n\n # Generate data for ellipse structure\n t = np.linspace(0,2*np.pi,1000)\n x = major_radius*np.cos(t)\n y = minor_radius*np.sin(t)\n data = np.array([x,y])\n R = np.array([[np.cos(theta_orient),-np.sin(theta_orient)],\n [np.sin(theta_orient),np.cos(theta_orient)]])\n T = np.dot(R,eig_vec)\n data = np.dot(T,data)\n \n # Center the ellipse at given center\n data[0] += x_cent\n data[1] += y_cent\n\n # Plot the ellipse\n fig,ax = plt.subplots()\n ax.plot(data[0],data[1],color='b',linestyle='-')\n ax.fill(data[0],data[1])\n```\n\n\n```python\ncovar_check = np.array([[9,4],[4,3]])\nplot_ellipse(center = (1,2), cov=covar_check, plot_way = 2)\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "67ca447a2021197c2e43b576d78e932ba3c6ce26", "size": 21086, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": ".ipynb_checkpoints/Draw_Covariance_Ellipse-checkpoint.ipynb", "max_stars_repo_name": "venkatramanrenganathan/Demonstrations", "max_stars_repo_head_hexsha": "6d25f6b6b208b6c74aecb6c1482ad54d44ad8038", "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": ".ipynb_checkpoints/Draw_Covariance_Ellipse-checkpoint.ipynb", "max_issues_repo_name": "venkatramanrenganathan/Demonstrations", "max_issues_repo_head_hexsha": "6d25f6b6b208b6c74aecb6c1482ad54d44ad8038", "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": ".ipynb_checkpoints/Draw_Covariance_Ellipse-checkpoint.ipynb", "max_forks_repo_name": "venkatramanrenganathan/Demonstrations", "max_forks_repo_head_hexsha": "6d25f6b6b208b6c74aecb6c1482ad54d44ad8038", "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": 92.0786026201, "max_line_length": 9232, "alphanum_fraction": 0.8170349995, "converted": true, "num_tokens": 1235, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465080392797, "lm_q2_score": 0.9136765234137297, "lm_q1q2_score": 0.8546041456525012}} {"text": "```python\nimport sympy as sp\nimport numpy as np\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nsp.init_printing()\n%matplotlib inline\n```\n\n\n```python\ndef plot_RS(a, b, n, N, f, method):\n x = np.linspace(a, b, N + 1)\n y = f(x)\n X = np.linspace(a, b, n * N + 1)\n Y = f(X)\n plt.plot(X, Y, 'b')\n x_test = x\n y_test = y\n align = 'edge'\n width = (b - a) / N\n if method == \"left\":\n x_test = x[:-1]\n y_test = y[:-1]\n elif method == \"mid\":\n x_test = (x[:-1] + x[1:]) / 2\n y_test = f(x_test)\n align = 'center'\n elif method == \"right\":\n x_test = x[1:]\n y_test = y[1:]\n width = -width\n plt.plot(x_test, y_test, 'b.', markersize=10)\n plt.bar(x_test, y_test, width=width, alpha=0.3, align=align, edgecolor='b')\n return sum(y_test * (b - a) / N)\n\nn = 10; N = 2\nf = lambda x : x + 1\nplt.figure(figsize=(35, 10))\nplt.subplot(2, 3, 1)\ns = plot_RS(0, 2, n, N, f, \"left\")\nplt.title(f\"Left Riemann Sum, N = {N}\")\nplt.subplot(2, 3, 2)\ns = plot_RS(0, 2, n, N, f, \"mid\")\nplt.title(f\"Midpoint Riemann Sum, N = {N}\")\nplt.subplot(2, 3, 3)\ns = plot_RS(0, 2, n, N, f, \"right\")\nplt.title(f\"Right Riemann Sum, N = {N}\")\nN = 10\nplt.subplot(2, 3, 4)\ns = plot_RS(0, 2, n, N, f, \"left\")\nplt.title(f\"Left Riemann Sum, N = {N}\")\nplt.subplot(2, 3, 5)\ns = plot_RS(0, 2, n, N, f, \"mid\")\nplt.title(f\"Midpoint Riemann Sum, N = {N}\")\nplt.subplot(2, 3, 6)\ns = plot_RS(0, 2, n, N, f, \"right\")\nplt.title(f\"Right Riemann Sum, N = {N}\")\n\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "6df3ac18d1773af77dec7ea8bd0e28aaeb6054ad", "size": 78281, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Integrals.ipynb", "max_stars_repo_name": "urkud/calculus-notebooks", "max_stars_repo_head_hexsha": "27a5a79b1cd89f0ef71ebdff16a4027f28f9fe3d", "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": "Integrals.ipynb", "max_issues_repo_name": "urkud/calculus-notebooks", "max_issues_repo_head_hexsha": "27a5a79b1cd89f0ef71ebdff16a4027f28f9fe3d", "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": "Integrals.ipynb", "max_forks_repo_name": "urkud/calculus-notebooks", "max_forks_repo_head_hexsha": "27a5a79b1cd89f0ef71ebdff16a4027f28f9fe3d", "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": 626.248, "max_line_length": 75104, "alphanum_fraction": 0.9441882449, "converted": true, "num_tokens": 598, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465080392795, "lm_q2_score": 0.9136765204755286, "lm_q1q2_score": 0.854604142904265}} {"text": "Find the volume of the following \"stadium\". The inner wall is part of a sphere of radius 2 and the outer wall is a cylinder of radius 4.\n\n \n\n$$ \\int_{\\pi/2}^{2\\pi} \\int_{\\pi/4}^{\\pi/2} \\int_2^{4/\\sin\\phi} \\rho^2 \\sin\\phi \\,d\\rho\\,d\\phi\\,d\\theta $$\n\n\n```python\nfrom sympy import *\n```\n\n\n```python\nrh,ph,th = var(\"rho phi theta\")\n```\n\n\n```python\nvol = integrate(rh**2*sin(ph),(rh,2,4/sin(ph)),(ph,pi/4,pi/2),(th,pi/2,2*pi))\nsimplify(vol)\n```\n\n\n\n\n$\\displaystyle 2 \\pi \\left(16 - \\sqrt{2}\\right)$\n\n\n\n\n```python\nvol.evalf()\n```\n\n\n\n\n$\\displaystyle 91.6451990385567$\n\n\n\n\n```python\nimport numpy as np\nfrom scipy.integrate import tplquad\n```\n\n\n```python\ntplquad(lambda r,p,t: r**2*np.sin(p),np.pi/2,2*np.pi,np.pi/4,np.pi/2,2,lambda t,p: 4/np.sin(p))\n```\n\n\n\n\n (91.64519903855667, 1.0174661006896088e-12)\n\n\n", "meta": {"hexsha": "4112db9978eb05594220d579d9e467c0020c2f05", "size": 2717, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "extras/stadium-solution.ipynb", "max_stars_repo_name": "drewyoungren/mvc", "max_stars_repo_head_hexsha": "f5217ae7888050d722c66de95756586f662841d2", "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": "extras/stadium-solution.ipynb", "max_issues_repo_name": "drewyoungren/mvc", "max_issues_repo_head_hexsha": "f5217ae7888050d722c66de95756586f662841d2", "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": "extras/stadium-solution.ipynb", "max_forks_repo_name": "drewyoungren/mvc", "max_forks_repo_head_hexsha": "f5217ae7888050d722c66de95756586f662841d2", "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": 19.8321167883, "max_line_length": 147, "alphanum_fraction": 0.4854619065, "converted": true, "num_tokens": 306, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9648551556203815, "lm_q2_score": 0.8856314798554445, "lm_q1q2_score": 0.8545060993182337}} {"text": "# Modeling and Simulation in Python\n\nChapter 7: Thermal systems\n\nCopyright 2017 Allen Downey\n\nLicense: [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0)\n\n\n### Mixing liquids\n\nWe can figure out the final temperature of a mixture by setting the total heat flow to zero and then solving for $T$.\n\n\n```python\nfrom sympy import *\n\ninit_printing() \n```\n\n\n```python\nC1, C2, T1, T2, T = symbols('C1 C2 T1 T2 T')\n\neq = Eq(C1 * (T - T1) + C2 * (T - T2), 0)\neq\n```\n\n\n```python\nsolve(eq, T)\n```\n\n### Analysis\n\nWe can use SymPy to solve the cooling differential equation.\n\n\n```python\nT_init, T_env, r, t = symbols('T_init T_env r t')\nT = Function('T')\n\neqn = Eq(diff(T(t), t), -r * (T(t) - T_env))\neqn\n```\nHere's the general solution:\n\n```python\nsolution_eq = dsolve(eqn)\nsolution_eq\n```\n\n\n```python\ngeneral = solution_eq.rhs\ngeneral\n```\n\nWe can use the initial condition to solve for $C_1$. First we evaluate the general solution at $t=0$\n\n\n```python\nat0 = general.subs(t, 0)\nat0\n```\n\nNow we set $T(0) = T_{init}$ and solve for $C_1$\n\n\n```python\nsolutions = solve(Eq(at0, T_init), C1)\nvalue_of_C1 = solutions[0]\nvalue_of_C1\n```\n\nThen we plug the result into the general solution to get the particular solution:\n\n\n```python\nparticular = general.subs(C1, value_of_C1)\nparticular\n```\n\nWe use a similar process to estimate $r$ based on the observation $T(t_{end}) = T_{end}$\n\n\n```python\nt_end, T_end = symbols('t_end T_end')\n```\n\nHere's the particular solution evaluated at $t_{end}$\n\n\n```python\nat_end = particular.subs(t, t_end)\nat_end\n```\n\nNow we set $T(t_{end}) = T_{end}$ and solve for $r$\n\n\n```python\nsolutions = solve(Eq(at_end, T_end), r)\nvalue_of_r = solutions[0]\nvalue_of_r\n```\n\nWe can use `evalf` to plug in numbers for the symbols. The result is a SymPy float, which we have to convert to a Python float.\n\n\n```python\nsubs = dict(t_end=30, T_end=70, T_init=90, T_env=22)\nr_coffee2 = value_of_r.evalf(subs=subs)\ntype(r_coffee2)\n```\n\n\n\n\n sympy.core.numbers.Float\n\n\n\n\n```python\nr_coffee2 = float(r_coffee2)\nr_coffee2\n```\n", "meta": {"hexsha": "1114249cd503f721bc667568daeb40f6bbfa6b25", "size": 23319, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "code/old_notebooks/chap07sympy.ipynb", "max_stars_repo_name": "leilamerz/ModSimPy", "max_stars_repo_head_hexsha": "b877b6053a461c179643f55d0f1c1d929af0aef8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-04-13T01:09:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-13T01:09:39.000Z", "max_issues_repo_path": "code/old_notebooks/chap07sympy.ipynb", "max_issues_repo_name": "leilamerz/ModSimPy", "max_issues_repo_head_hexsha": "b877b6053a461c179643f55d0f1c1d929af0aef8", "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": "code/old_notebooks/chap07sympy.ipynb", "max_forks_repo_name": "leilamerz/ModSimPy", "max_forks_repo_head_hexsha": "b877b6053a461c179643f55d0f1c1d929af0aef8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-04-13T01:10:41.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-13T01:10:41.000Z", "avg_line_length": 50.6934782609, "max_line_length": 2150, "alphanum_fraction": 0.7566791029, "converted": true, "num_tokens": 643, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314624993576759, "lm_q2_score": 0.917302665802808, "lm_q1q2_score": 0.8544330337561423}} {"text": "## z* visualization\n\nVisualize the work of _Adcroft and Campin (2004)_. They incorporated a z* depth in the MITgcm which is defined as\n\n$$z=\\eta + s^* z^*$$ \nwhere $s^* = 1 + \\eta/H$ and $z=-H$ at the bottom of the ocean and $\\eta$ is at the top of the ocean.\n\n\n```python\nfrom numpy import linspace\n```\n\n\n```python\nH=3000.0 # meters (m)\neta=30.0 # meters (m)\nnumPts=50\nwaterColumn=linspace(0,0,num=numPts)\nz=linspace(eta, -H, num=numPts)\n```\n\n\n```python\nsStar=1+eta/H\nzStar= (z-eta) / sStar\n```\n\n#### Plotting z* next to z to show the difference\n\n\n```python\nimport matplotlib.pyplot as plt\n%matplotlib inline\n```\n\n\n```python\nplt.figure(figsize=(2,20))\nplt.plot(waterColumn, z,\n 'k_', ms=40, label='z')\nplt.plot(waterColumn, zStar,\n 'co', ms=10, alpha=0.6, label='z*')\nplt.legend()\nplt.show()\n\nplt.figure(figsize=(10,2.5))\nplt.plot(abs(z-zStar))\nplt.show()\n```\n\n### Math proof\n\nLet $z \\in [-H, \\eta]$, we want to show that $z^*$ contains only non-positive numbers. We do so by rearranging the relation\n$$z=\\eta + s^* z^*$$ \nto \n$$z^*=\\frac{z-\\eta}{s^*}.$$ \n\nAt $z=-H$\n\n\\begin{align}\n z^* &= \\frac{-H-\\eta}{s^*} \\\\\n &= \\frac{-H-\\eta}{1+\\frac{\\eta}{H}}\\\\\n (1+\\frac{\\eta}{H})z^* &= -H-\\eta \\\\\n (H+\\eta)z^* &= -H(H+\\eta)\\\\\n z^* &= -H.\n\\end{align}\n\nAt $z=\\eta$\n\\begin{align}\n z^* &= \\frac{\\eta-\\eta}{s^*} \\\\\n z^* &= 0.\n\\end{align}\n\nTherefore, $z^* \\in [-H, 0]$, which is a non-positive range for all values of $H$ and $\\eta$.\n\n\n```python\n\n```\n", "meta": {"hexsha": "6386154a337de88f80f159cf2a305b54dad74507", "size": 27963, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "sandbox/gcm-methods/zStarTutorial.ipynb", "max_stars_repo_name": "IvanaEscobar/sandbox", "max_stars_repo_head_hexsha": "71d62af2c112686c5ce26def35593247cf6a0ccc", "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": "sandbox/gcm-methods/zStarTutorial.ipynb", "max_issues_repo_name": "IvanaEscobar/sandbox", "max_issues_repo_head_hexsha": "71d62af2c112686c5ce26def35593247cf6a0ccc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2022-02-15T23:32:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T21:35:12.000Z", "max_forks_repo_path": "sandbox/gcm-methods/zStarTutorial.ipynb", "max_forks_repo_name": "IvanaEscobar/sandbox", "max_forks_repo_head_hexsha": "71d62af2c112686c5ce26def35593247cf6a0ccc", "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": 166.4464285714, "max_line_length": 14100, "alphanum_fraction": 0.9054107213, "converted": true, "num_tokens": 542, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541659378681, "lm_q2_score": 0.907312213841788, "lm_q1q2_score": 0.8543743259704295}} {"text": "Für $q \\neq 1$ kann die n-te Partialsumme der geometrischen Reihe wie folgt berechnet werden:\n \n$$\n\\sum_{k=0}^{n}{q^{k}} = \\frac{1-q^{n+1}}{1-q}\n$$\n\nZeigen Sie dies empirisch, indem Sie mithilfe von `sympy` die linke und rechte Seite in einer for-Schleife für $n = 1, \\ldots, 5$ berechnen und deren faktorisierte Formen mit einem logischen Operator vergleichen. Geben Sie dies für jedes $n$ aus. Anschließend berechnen Sie die 5-te Partialsumme an der Stelle $q = 3$ (indem Sie mittels einer `sympy` Routine für $q$ den konkreten Wert übergeben) und geben diese aus.\n\n\n```python\nfrom sympy.abc import k, n, q\nfrom sympy import Sum\n\nfor ni in range(1, 6):\n geom_series = Sum(q**k, (k, 0, ni))\n geom_formula = (1 - q**(ni + 1))/(1 - q)\n print(f'n = {ni}, Same factorized form: {geom_series.doit().factor() == geom_formula.factor()}')\n```\n\n n = 1, Same factorized form: True\n n = 2, Same factorized form: True\n n = 3, Same factorized form: True\n n = 4, Same factorized form: True\n n = 5, Same factorized form: True\n\n\n\n```python\ngeom_series = Sum(q**k, (k, 0, n))\ngeom_formula = (1 - q**(n + 1))/(1 - q)\n\nsubs_dict = {k: v for k, v in zip('nq', [5, 3])}\nfor function, label in zip(\n [geom_series, geom_formula],\n ['Series', 'Formula']\n):\n print(f'{label}: {function.evalf(subs = subs_dict)}, n = 5, q = 3')\n```\n\n Series: 364.000000000000, n = 5, q = 3\n Formula: 364.000000000000, n = 5, q = 3\n\n", "meta": {"hexsha": "f2723826f8953fc9e0704fd52ed34fb1c5abd1c2", "size": 2724, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Daniel_Malzl_Aufgabe3.ipynb", "max_stars_repo_name": "dmalzl/mathcode", "max_stars_repo_head_hexsha": "6a22ad0b2f193e0b7fa3926a65a6a0791f2e2366", "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": "Daniel_Malzl_Aufgabe3.ipynb", "max_issues_repo_name": "dmalzl/mathcode", "max_issues_repo_head_hexsha": "6a22ad0b2f193e0b7fa3926a65a6a0791f2e2366", "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": "Daniel_Malzl_Aufgabe3.ipynb", "max_forks_repo_name": "dmalzl/mathcode", "max_forks_repo_head_hexsha": "6a22ad0b2f193e0b7fa3926a65a6a0791f2e2366", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.6736842105, "max_line_length": 424, "alphanum_fraction": 0.5403817915, "converted": true, "num_tokens": 511, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850093037731, "lm_q2_score": 0.9124361616674908, "lm_q1q2_score": 0.8543003001159456}} {"text": "# Coinflips\n\n*Coinflips until you die.*\n\nHere are some things that I like:\n\n1. Reminding myself that probability theory is rooted in sets. (Blitzstein & Hwang's \"Introduction to Probability\" does a great job driving this point home. I claim that applied probability curricula normally fail to do so -- a couple of Venn Diagrams is not enough.)\n2. Indicator variables that convert set theory expressions into random variables (c.f. Matching Problem).\n3. Indicator variables that convert expected value calculations to probabilities.\n4. Independent events.\n\nI claim:\n\n- Problems typically become confusing when random variables have complicated interdependencies, but often they are made up of \"atoms\" of independent events. For difficult problems, deconstructing a problem in terms of independent events can be half the battle.\n- Recursion. Typically emerges most naturally from applying the law of total expectation.\n- Expected values for complicated problems are much simpler creatures than full probability distributions, and can often be found using symmetry tricks. This provides fertile ground for the type of dumb probability puzzles that quant interviewers apparently *salivate* over.\n\n\n## Expected Flips until $n$ Heads in a Row: Recursion and Law of Total Expectation\nA coin is flipped until there is a sequence of $n$ subsequent heads. What is the exected number of flips $\\mathbb{E}[N]$? \n\nCondition on the outcome of the first flip:\n\\begin{equation}\n\\begin{array}{rl}\n\\mathbb{E}[N] &= \\sum_{j=\\{H,T\\}}\\mathbb{E}[N|f_1 = j]p(f_1=j)\\\\\n&=\\frac{1}{2}\\underbrace{\\mathbb{E}[N|f_1=T]}_{\\mathbb{E}[N+1]=\\mathbb{E}[N]+1} + \\frac{1}{2}\\mathbb{E}[N|f_1=H]\n\\end{array}\n\\end{equation}\n\nIf you the first flip is tails, you're back to where you started, except that you'e already done one flip. Hence $\\mathbb{E}[N|f_1=T] = \\mathbb{E}[N]+1$. If the first throw is heads, then we should find ourselves slightly closer to $k$ flips. Repeating the procedure by conditioning on the outcome of the second throw:\n\n\\begin{equation}\n\\begin{array}{rl}\n\\mathbb{E}[N|f_1=H] &= \\sum_{j=\\{H,T\\}}\\mathbb{E}[N|f_1 = H|f_2=j]p(f_2=j)\\\\\n&=\\frac{1}{2}\\underbrace{\\mathbb{E}[N|f_1=H,f_2=T]}_{\\mathbb{E}[N+2]=\\mathbb{E}[N]+2} + \\frac{1}{2}\\mathbb{E}[N|f_1=H,f_2=H]\n\\end{array}\n\\end{equation}\n\nUnsurprisingly, this looks like a pattern where either you start over because you flipped tails, or you are dealing with the conditional probability of already having flipped some consecutive heads. Let $M_k = \\mathbb{E}[N|f_1=H,f_2=H,...,f_k=H]$, so that $M_0 = \\mathbb{E}[N]$ is the expected number of flips conditioned on no previous outcomes. Then:\n\n\\begin{equation}\nM_k = \\frac{1}{2}(k+1+M_0)+\\frac{1}{2}M_{k+1}\n\\end{equation}\n\nCool. So far this is a linear system that goes on forever. Fortunately the agreement was that the game was going to be over if we throw $n$ heads in a row. That means that $\\mathbb{E}[N|f_1=H,f_2=H,...,f_n=H] = M_n = n$ because here I am explicitly conditioning on throwing $n$ heads in a row. \n\n\nTake $n=3$, for example. Then:\n\\begin{equation}\n\\begin{array}{rl}\nM_0 &= \\frac{1}{2}(0+1+M_0)+\\frac{1}{2}\\underbrace{\\left[\\frac{1}{2}(1+1+M_0)+\\frac{1}{2}\\underbrace{\\left[\\frac{1}{2}(2+1+M_0)+\\frac{1}{2}\\underbrace{\\left[n\\right]}_{M_3}\\right]}_{M_2}\\right]}_{M_1}\\\\\n&=\\sum^{n-1}_{k=0}\\frac{1}{2^{k+1}}(1+k+M_0) + \\frac{1}{2^n}n\\\\\nM_0\\left[1-\\sum_{k=0}^{n-1} \\frac{1}{2^{k+1}}\\right]&=\\sum^{n-1}_{k=0}\\frac{1+k}{2^{k+1}} + \\frac{1}{2^n}n\\\\\nM_0 &= \\left[\\sum^{n-1}_{k=0}\\frac{1+k}{2^{k+1}} + \\frac{1}{2^n}n\\right]\\left[1-\\sum_{k=0}^{n-1} \\frac{1}{2^{k+1}}\\right]^{-1}\n\\end{array}\n\\end{equation}\n\nTo the dismay of my friends and family, I will not simplify this further because dinner is almost ready. (Even though it is easily possible using the finite geometric series)\n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef M_0(n):\n \"\"\"\n Expected number of flips until there are n consecutive heads\n \"\"\"\n numerator = np.sum([(1+k)/2**(k+1) for k in range(n)])+n/2**n\n denominator = 1-np.sum([1/2**(k+1) for k in range(n)])\n \n return numerator/denominator\n\n\ndef get_sequence(n):\n \"\"\"\n generates a sequence of flips and stops the moment there are n consecutive heads, then returns the length of the sequence.\n might run for a long time.\n \"\"\"\n sq = ''\n while sq[-n:] != n*'H':\n sq+=np.random.choice(['H','T'])\n return len(sq)\n \ndef M_0_simulated(n,n_trials=100):\n return np.mean([get_sequence(n) for i in range(n_trials)])\n\n# look at distribution, because it's interesting\nplt.figure(figsize=(12,8))\nnn = [2,4,6,8]\nfor n in nn:\n data = [get_sequence(n) for i in range(5000)]\n _ = plt.hist(data,bins=list(range(200)),density=True)\n \nplt.legend(['n=%i' % i for i in nn])\nplt.xlabel('flips')\n_ = plt.title('flips until n-consecutive heads')\n```\n\n\n```python\nnn = list(range(10))\n\nplt.figure(figsize=(12,8))\nplt.plot(nn,[M_0(n) for n in nn],'d-',linewidth=2.5,markersize=10)\nplt.plot(nn,[M_0_simulated(n,n_trials=1000) for n in nn],'o',linewidth=2.5,markersize=10)\n\nplt.legend(['analytical','simulated'])\nplt.title('Expected Numer of Flips until n Consecutive Heads')\nplt.xlabel('n',fontsize=15)\n_= plt.ylabel('Flips',fontsize=15)\n```\n\n## Why This Doesn't Generalize To Arbitrary Sequences\n\nSo what if instead of looking for a sequence of $n$ heads, I am looking for some arbitrary $n$-flip sequence, such as \"HHTHHH\" or whatever. \n\nThe formula does not work anymore, because it assumed that you start over the moment that you flip tails. For an arbirary sequence, flipping the wrong thing does not necessarily mean that you start over. \n\nLet's say $S=\\{s_1=H,s_2=H,s_3=T,s_4=H,s_5=H,s_6=H\\}$. \n\n*Previously*, for a sequence of all heads: \n\n\\begin{equation}\n\\mathbb{E}[N|f_1=H,...,f_k\\neq H] = \\mathbb{E}[N]\n\\end{equation}.\n\nNow, \n\n\\begin{equation}\n\\mathbb{E}[N|f_1=s_1,f_2=s_2,f_3=s_3,f_4=s_4,f_5=s_5,f_6\\neq s_6] = \\mathbb{E}[N|f_1=s_1,f_2=s_2,f_3=s_3]\n\\end{equation}. \n\nIf you get only the last flip of the sequence wrong, then it puts you back to where you had the first three flips of the sequence right. Because of this, the expected number of flips until you see some sequence S is smaller.\n\nEven though the result doesn't generalize, it is interesting because it provides an upper bound on the expected value. Any repeat of the first few items within the sequence at some point during the sequence will lower the expected number of flips.\n\nAn approach toward studying this might be by modeling the process as a Markov Chain. If $S$ has length $n$, then let the state space be all possible sequences of length $n$. Then the transition matrix acts in a way so the states are modified corresponding to dropping the first entry and tagging on a \"T\" or an \"H\" with equation probability. I.e., state \"THH\" --> \"HHH\" with p=0.5 and \"THH\" --> \"HHT\" with p=0.5. This is except for the state that corresponds to the sought after Sequence, $S$, which is absorbing. Denote the set of states where the last $r$ entries are equal to the first $k$ elements of $S$ as $\\{x_r\\}$ (these have size $2^{n-r}$ because you can assign $n-r$ arbitrarily and $r$ must match up with S). When $S$ consists of only heads, then the states $\\{x_r\\}$ only communiate with $\\{x_0\\}$ or $\\{x_{r+1}\\}$. For arbitrary sequences, you will see communication of the form $\\{x_r\\} \\rightarrow \\{x_{r-m}\\}$. A setback, but not all the way to 0.\n\n\n```python\ndef get_sequence_S(S):\n \"\"\"\n generates a sequence of flips and stops the moment that sequence S is flipped.\n \"\"\"\n sq = ''\n while sq[-len(S):] != S:\n sq+=np.random.choice(['H','T'])\n return len(sq)\n \ndef M_0_simulated_S(S,n_trials=100):\n return np.mean([get_sequence_S(S) for i in range(n_trials)])\n\n\nSS = 'HHTHHH'\nnn = list(range(len(SS)))\n\nplt.figure(figsize=(12,8))\nfor n in nn:\n S = SS[:n]\n \n plt.plot(n,M_0(n),'d',color='blue',markersize=10)\n plt.plot(n,M_0_simulated_S(S,n_trials=1000),'o',color='orange',markersize=10)\n \n\nplt.legend(np.hstack([['%i heads' % n,'sequence %s' % S[:n]] for n in nn]))\nplt.title('Expected Numer of Flips until S')\nplt.xlabel('n',fontsize=15)\n_= plt.ylabel('Flips',fontsize=15)\n```\n", "meta": {"hexsha": "8e539bf8feab968c6cd310f1717b008d87519d2f", "size": 85155, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Probability - Coinflips, Expected Flips until Sequence of n Heads.ipynb", "max_stars_repo_name": "jpbm/probabilism", "max_stars_repo_head_hexsha": "a2f5c1595aed616236b2b889195604f365175899", "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": "Probability - Coinflips, Expected Flips until Sequence of n Heads.ipynb", "max_issues_repo_name": "jpbm/probabilism", "max_issues_repo_head_hexsha": "a2f5c1595aed616236b2b889195604f365175899", "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": "Probability - Coinflips, Expected Flips until Sequence of n Heads.ipynb", "max_forks_repo_name": "jpbm/probabilism", "max_forks_repo_head_hexsha": "a2f5c1595aed616236b2b889195604f365175899", "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": 330.0581395349, "max_line_length": 29488, "alphanum_fraction": 0.9142035112, "converted": true, "num_tokens": 2549, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850075259038, "lm_q2_score": 0.9124361545241945, "lm_q1q2_score": 0.8543002918055922}} {"text": "# Estimation with sensor offset and drift\n\n_This is based on a problem presented in EE 263 Linear Dynamical Systems at Stanford University_\n\n### Background: Least Squares\n\nSuppose that we are trying to estimate a vector $p\\in\\mathbf{R}^{n}$. We take $m$ scalar measurements, each a linear combination of elements of $p$. Each measurement, $y_i$, is modeled as\n\n\\begin{align}\ny_i = a_i^T p + v_i,\\quad\\quad i=1,\\ldots,m,\n\\end{align}\n\nwhere\n\n- $y_i\\in\\mathbf{R}$ is the $i^{\\text{th}}$ measurement\n- $p\\in\\mathbf{R}^n$ is vector we wish to measure\n- $v_i$ is the sensor or measurement error of the ith measurement.\n\nWe assume that the $a_i$'s are given, i.e. we know the calibration values of the sensor for each measurement. Additionally, we assume that we have at least as many measurements as values we need to estimate $\\left(m\\geq n\\right)$ and that the matrix A given by\n\n\\begin{align}\nA = \\left[\\begin{matrix}\na_1^T \\\\ a_2^T \\\\ \\vdots \\\\ a_m^T\n\\end{matrix}\\right]\n\\end{align}\n\nis full rank. For standard linear regression, the vector $x$ would be in $\\mathbf{R}^2$ and would represent the slope and intercept parameters. In this context, the matrix $A$ would have the given values for the independent variable in the first column and all ones in the second column, and the vector $y\\in\\mathbf{R}^m$ would contain the values for the dependent variable. If the error terms, $v_i$, were small, random, and centered around zero (Gaussian white noise), then least squares gives the optimal estimation of x (i.e., minimizes the RMSE):\n\n\\begin{align}\n\\hat{p} = \\left(A^TA\\right)^{-1}A^T y = \\underset{p}{\\text{argmin}}\\left\\lVert y - Ap \\right\\rVert_2^2\n\\end{align}\n\nLet's illustrate this with a quick example.\n\n\n```python\nimport numpy as np\nfrom numpy.linalg import inv\nimport matplotlib.pyplot as plt\n%matplotlib inline\nimport seaborn as sns\nsns.set(context='talk', style='darkgrid', palette='colorblind')\n```\n\n\n```python\nm = 2\nb = -1\nxs = np.random.uniform(0, 1, 10)\nys = m * xs + b + np.random.normal(0, .2, size=len(xs))\nfig = plt.figure(figsize=(8,6))\nplt.scatter(xs, ys)\nplt.xlabel('x'); plt.ylabel('y')\nplt.show()\n```\n\nConstruct the matrix $A$.\n\n\n```python\nA = np.c_[xs, np.ones_like(xs)]\nprint A\n```\n\n [[0.12997784 1. ]\n [0.10977849 1. ]\n [0.60488689 1. ]\n [0.38266506 1. ]\n [0.60065919 1. ]\n [0.44154635 1. ]\n [0.23412023 1. ]\n [0.8084878 1. ]\n [0.22136882 1. ]\n [0.23757838 1. ]]\n\n\nSolve the least squares problem.\n\n\n```python\np_hat = inv(A.T.dot(A)).dot(A.T).dot(ys)\n```\n\nCompared the estimated parameters to the real parameters.\n\n\n```python\nfig = plt.figure(figsize=(8,6))\nplt.scatter(xs, ys, label='measured')\nx2 = np.linspace(0, 1)\nplt.plot(x2, m*x2 + b, linewidth=1, ls='--', label='actual')\nplt.plot(x2, p_hat[0]*x2 + p_hat[1], linewidth=1, ls='--', label='estimated')\nplt.xlabel('x'); plt.ylabel('y')\nplt.xlim(0, 1); plt.ylim(-1, 1)\nplt.legend(loc=4)\nplt.show()\n```\n\n### Adding bias and drift to the error\n\nFor this problem, let us assume that the error contains some predictable terms in addition to white noise: a common offset term that is the same for all measurements and a drift term that grows linearly with each subsequent measurement. We model this situation as:\n\n\\begin{align}\nv_i = \\alpha + \\beta i + w_i\n\\end{align}\n\nWe will use least squares to simultaneously the desired vector $x\\in\\mathbf{R}^n$, the bias term $\\alpha\\in\\mathbf{R}$, and the drift term $\\beta\\in\\mathbf{R}$. We begin by substituting our error model into the measurement model:\n\n\\begin{align}\ny_i = a_i^T x + \\alpha + \\beta i + w_i,\\quad\\quad i=1,\\ldots,m,\n\\end{align}\n\nThis induces the matrix equation:\n\n\\begin{align}\n\\left[\\begin{matrix}\ny_1 \\\\ y_2 \\\\ \\vdots \\\\ y_m\n\\end{matrix}\\right] &= \n\\left[\\begin{matrix}\na_1^T & 1 & 1 \\\\\na_2^T & 1 & 2 \\\\\n\\vdots & \\vdots & \\vdots \\\\\na_m^T & 1 & m\n\\end{matrix}\\right]\n\\left[\\begin{matrix}\nx \\\\ \\alpha \\\\ \\beta\n\\end{matrix}\\right] + \n\\left[\\begin{matrix}\nw_1 \\\\ w_2 \\\\ \\vdots \\\\ w_m\n\\end{matrix}\\right] \\\\ \\\\\ny &= \\tilde{A}\\tilde{x} + w\n\\end{align}\n\nWe can now use least squares to find all parameters:\n\n\\begin{align}\n\\hat{\\tilde{x}} = \\left[\\begin{matrix}\n\\hat{x} \\\\ \\hat{\\alpha} \\\\ \\hat{\\beta}\n\\end{matrix}\\right] = \\left(\\tilde{A}^T\\tilde{A}\\right)^{-1}\\tilde{A}^T y\n\\end{align}\n\nAlright! We have a closed-form expression to estimate $x$, $\\alpha$, and $\\beta$. A couple caveats: for this to work, the following much be true:\n\n- $m\\geq n +2$. We must have enough measurement to recover $n+2$ parameters.\n- $\\tilde{A}$ must be full rank. Note, even if $A$ is full rank (which is given), $\\tilde{A}$ might not be. If some linear combination of the sensor signals looks like some linear combination of the offset and drift, then it is impossible to separate the offset and drift parameters from $x$. \n\nImmediately, we see a potential problem! If we are using this to derive the parameters of a statistical model (as in the previous example), that model can't contain an offset term! If it does, then the second condition is violated.\n\nAlright, that's enough theory. Now let's look at an application of this technique. Again, suppose we have some noisy measurements of a function. This time we'll make the function a bit more interesting: a cubic function with no offset. We'll start by again looking at the simpler case where the noise terms are i.i.d. Gaussian white noise, and then we'll add the offset and drift terms.\n\n\n```python\ndef our_func(x, p1=1, p2=3, p3=-0.2):\n output = p1 * x + p2 * np.power(x, 2) + p3 * np.power(x, 3)\n return output\n```\n\n\n```python\nnp.random.seed(42)\n```\n\n\n```python\nfig = plt.figure(figsize=(10, 8))\nxs_ideal = np.linspace(-5, 15, 30)\nxs_samples = np.random.uniform(-5, 15, 15)\nys_samples = our_func(xs_samples) + np.random.normal(0, 5, size=len(xs_samples))\nplt.plot(xs_ideal, our_func(xs_ideal), linewidth=1, ls='--')\nplt.scatter(xs_samples, ys_samples)\nplt.legend(['Actual Function', 'Noisy Measurements'], loc=4)\nplt.xlabel('x'); plt.ylabel('y')\n_ = plt.title('Noisy Samples of a Cubic Function')\n```\n\nA cubic function with no offset is fully defined by three scalar coefficients:\n\n\\begin{align}\ny = \\mathcal{P}_3(x) &= p_1 x + p_2 x^2 + p_3 x^3 \\\\\n&= \\left[\\begin{matrix} x & x^2 & x^3 \\end{matrix}\\right] \\left[\\begin{matrix} p_1 \\\\ p_2 \\\\ p_3 \\end{matrix}\\right]\n\\end{align}\n\nSo, given a set of noisy measurement, $\\left\\{\\left(x_1, y_1\\right),\\left(x_2, y_2\\right),\\ldots, \\left(x_m, y_m\\right)\\right\\}$, we find $p=\\left[\\begin{matrix}p_1 & p_2 & p_3\\end{matrix}\\right]^T$ as follows. First, construct the following matrix:\n\n\\begin{align}\nA &= \\left[\\begin{matrix}\nx_1 & x_1^2 & x_1^3 \\\\\nx_2 & x_2^2 & x_2^3 \\\\\n\\vdots & \\vdots & \\vdots \\\\\nx_m & x_m^2 & x_m^3 \\\\\n\\end{matrix}\\right]\n\\end{align}\n\nThen, find $\\hat{p}$ as before:\n\n\\begin{align}\n\\hat{p} = \\left(A^TA\\right)^{-1}A^T y = \\underset{p}{\\text{argmin}}\\left\\lVert y - Ap \\right\\rVert_2^2\n\\end{align}\n\nLet's try it out on this cubic-fitting problem! As before, start by constructing matrix $A$.\n\n\n```python\nA = np.c_[xs_samples, np.power(xs_samples, 2), np.power(xs_samples, 3)]\nnp.set_printoptions(precision=2)\nprint A\n```\n\n [[ 2.49e+00 6.20e+00 1.55e+01]\n [ 1.40e+01 1.96e+02 2.75e+03]\n [ 9.64e+00 9.29e+01 8.96e+02]\n [ 6.97e+00 4.86e+01 3.39e+02]\n [-1.88e+00 3.53e+00 -6.64e+00]\n [-1.88e+00 3.53e+00 -6.65e+00]\n [-3.84e+00 1.47e+01 -5.65e+01]\n [ 1.23e+01 1.52e+02 1.87e+03]\n [ 7.02e+00 4.93e+01 3.46e+02]\n [ 9.16e+00 8.39e+01 7.69e+02]\n [-4.59e+00 2.11e+01 -9.66e+01]\n [ 1.44e+01 2.07e+02 2.98e+03]\n [ 1.16e+01 1.36e+02 1.58e+03]\n [-7.53e-01 5.67e-01 -4.27e-01]\n [-1.36e+00 1.86e+00 -2.53e+00]]\n\n\nThen, solve the least squares problem.\n\n\n```python\np_hat = inv(A.T.dot(A)).dot(A.T).dot(ys_samples)\nprint p_hat\n```\n\n [ 0.96 2.88 -0.19]\n\n\nRecall, that the actual parameters were $\\left[1, 3, -0.2\\right]$. Let's compare the results.\n\n\n```python\nfig = plt.figure(figsize=(10, 8))\nplt.plot(xs_ideal, our_func(xs_ideal), linewidth=1, ls='--', label='Actual Function')\nplt.plot(xs_ideal, our_func(xs_ideal, p1=p_hat[0], p2=p_hat[1], p3=p_hat[2]),\n linewidth=1, ls='--', label='Estimated Function')\nplt.scatter(xs_samples, ys_samples, label='Noisy Measurements')\nplt.legend(loc=4)\nplt.xlabel('x'); plt.ylabel('y')\n_ = plt.title('Noisy Samples of a Cubic Function')\n```\n\nThat's pretty good! Now let's make things interesting and include the offset and drift terms. The existing formulation already includes Gaussian white noise, so there's no need to add that again.\n\n\n```python\nalpha = -3\nbeta = 5\n```\n\n\n```python\nys_od = ys_samples + alpha + beta * np.arange(1, 1 + A.shape[0])\n```\n\nAs a sanity check, here's what the measurements look like now, as compared to the actual function:\n\n\n```python\nfig = plt.figure(figsize=(10, 8))\nplt.plot(xs_ideal, our_func(xs_ideal), linewidth=1, ls='--', label='Actual Function')\nplt.scatter(xs_samples, ys_od, label='Noisy Measurements')\nplt.legend(loc=4)\nplt.xlabel('x'); plt.ylabel('y')\n_ = plt.title('Noisy Samples of a Cubic Function')\n```\n\nYikes! That looks like a mess. We might not think we would have any chance of recovering the original function from these measurements, but we'll see that correctly modeling the error saves the day.\n\nFirst, we construct the augmented matrix $\\tilde{A}$.\n\n\n```python\nA_tilde = np.concatenate([\n A,\n np.ones(A.shape[0])[:, None],\n np.arange(1, 1 + A.shape[0])[:, None]\n], axis = 1)\nprint A_tilde\n```\n\n [[ 2.49e+00 6.20e+00 1.55e+01 1.00e+00 1.00e+00]\n [ 1.40e+01 1.96e+02 2.75e+03 1.00e+00 2.00e+00]\n [ 9.64e+00 9.29e+01 8.96e+02 1.00e+00 3.00e+00]\n [ 6.97e+00 4.86e+01 3.39e+02 1.00e+00 4.00e+00]\n [-1.88e+00 3.53e+00 -6.64e+00 1.00e+00 5.00e+00]\n [-1.88e+00 3.53e+00 -6.65e+00 1.00e+00 6.00e+00]\n [-3.84e+00 1.47e+01 -5.65e+01 1.00e+00 7.00e+00]\n [ 1.23e+01 1.52e+02 1.87e+03 1.00e+00 8.00e+00]\n [ 7.02e+00 4.93e+01 3.46e+02 1.00e+00 9.00e+00]\n [ 9.16e+00 8.39e+01 7.69e+02 1.00e+00 1.00e+01]\n [-4.59e+00 2.11e+01 -9.66e+01 1.00e+00 1.10e+01]\n [ 1.44e+01 2.07e+02 2.98e+03 1.00e+00 1.20e+01]\n [ 1.16e+01 1.36e+02 1.58e+03 1.00e+00 1.30e+01]\n [-7.53e-01 5.67e-01 -4.27e-01 1.00e+00 1.40e+01]\n [-1.36e+00 1.86e+00 -2.53e+00 1.00e+00 1.50e+01]]\n\n\nThe standard least squared estimate:\n\n\n```python\np_ls = inv(A.T.dot(A)).dot(A.T).dot(ys_od)\nprint p_ls\n```\n\n [-3.5 4.51 -0.27]\n\n\nThe least squared estimate using the noise model:\n\n\n```python\np_ls_plus_noise = inv(A_tilde.T.dot(A_tilde)).dot(A_tilde.T).dot(ys_od)\nprint p_ls_plus_noise[:3]\n```\n\n [ 1.16 2.86 -0.19]\n\n\nAnd we also recover the estimates of $\\alpha$ and $\\beta$.\n\n\n```python\np_ls_plus_noise[3:]\n```\n\n\n\n\n array([-7.56, 5.57])\n\n\n\nSo, we can see that the LS estimate that utilizes the noise model does a much better job of estimating the desired parameters. What about the error? Recall the quantity we are trying to minimize is\n\n\\begin{align}\n\\left\\lVert y- Ap\\right\\rVert_2^2\n\\end{align}\n\nSo, there are really two errors to consider:\n\n- The value of the cost function we are minimizing via the least squares method. In a real application, this is the only error we could consider\n- The root-mean-square error between the estimated functions and the actual functions, evaluated at the sample points. We are only able to this because we know the function that generated the data\n\nLet's begin by evaluating the cost function we've minimized. \n\n\n```python\nJ_ls = np.sum(np.power(ys_od - A.dot(p_ls), 2))\nJ_ls_plus_noise = np.sum(np.power(ys_od - A_tilde.dot(p_ls_plus_noise), 2))\nprint 'Basic LS Error: {:.3f}'.format(J_ls)\nprint 'Noise model LS Error: {:.3f}'.format(J_ls_plus_noise)\n```\n\n Basic LS Error: 13403.986\n Noise model LS Error: 469.325\n\n\nThat's great! By accounting for the error, we drive the cost down by an additional 32%. That certainly seems promising. Now, let's compare to the oracle (the actual function that generated the data).\n\n\n```python\nx = our_func(xs_samples)\nx_ls = our_func(xs_samples, p1=p_ls[0], p2=p_ls[1], p3=p_ls[2])\nx_ls_plus_noise = our_func(xs_samples, p1=p_ls_plus_noise[0], p2=p_ls_plus_noise[1], p3=p_ls_plus_noise[2])\nerr_ls = np.linalg.norm(x - x_ls)\nerr_ls_plus_noise = np.linalg.norm(x - x_ls_plus_noise)\n```\n\n\n```python\nprint 'Basic LS Error: {:.3f}'.format(err_ls)\nprint 'Noise model LS Error: {:.3f}'.format(err_ls_plus_noise)\n```\n\n Basic LS Error: 120.583\n Noise model LS Error: 8.427\n\n\nAs expected, the method that correctly models the error gets much closer to the oracle.\n\nAnd finally, visualize the results with another plot:\n\n\n```python\nfig = plt.figure(figsize=(10, 8))\nplt.plot(xs_ideal, our_func(xs_ideal), linewidth=1, ls='--', label='Actual function')\nplt.plot(xs_ideal, our_func(xs_ideal, p1=p_ls[0], p2=p_ls[1], p3=p_ls[2]), linewidth=1, ls='--', label='LS estimate')\nplt.plot(xs_ideal, our_func(xs_ideal, p1=p_ls_plus_noise[0], p2=p_ls_plus_noise[1], p3=p_ls_plus_noise[2]),\n linewidth=1, ls='--', label='LS with error model estimate')\nplt.scatter(xs_samples, ys_od, label='Noisy Measurements')\nplt.legend(loc=4)\nplt.xlabel('x'); plt.ylabel('y')\n_ = plt.title('Noisy Samples of a Cubic Function')\n```\n\nAs a final note, I implemented$\\left(A^TA\\right)^{-1}A^T$ directly to emphasize the underlying equation, but this is known as the pseudoinverse of $A$ and is implemented in the NumPy linear algebra package as [pinv](https://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.pinv.html).\n\n\n```python\nfrom numpy.linalg import pinv\n```\n\n\n```python\nnp.allclose(pinv(A), inv(A.T.dot(A)).dot(A.T))\n```\n\n\n\n\n True\n\n\n", "meta": {"hexsha": "e846c363a560c671128f30a4ea104ab424df6f7a", "size": 230942, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/LS_offet_and_drift.ipynb", "max_stars_repo_name": "drfilipp/drfilipp.github.io", "max_stars_repo_head_hexsha": "1c90433746550a33bd6a4e674347ee59c2935904", "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/LS_offet_and_drift.ipynb", "max_issues_repo_name": "drfilipp/drfilipp.github.io", "max_issues_repo_head_hexsha": "1c90433746550a33bd6a4e674347ee59c2935904", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-04-18T05:43:55.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-18T05:43:55.000Z", "max_forks_repo_path": "notebooks/LS_offet_and_drift.ipynb", "max_forks_repo_name": "drfilipp/drfilipp.github.io", "max_forks_repo_head_hexsha": "1c90433746550a33bd6a4e674347ee59c2935904", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2018-02-14T18:26:11.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-09T12:33:33.000Z", "avg_line_length": 301.4908616188, "max_line_length": 51700, "alphanum_fraction": 0.9156151761, "converted": true, "num_tokens": 4739, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533069832973, "lm_q2_score": 0.9161096198879968, "lm_q1q2_score": 0.854229444623774}} {"text": "# Mathematics for Machine Learning: Linear Algebra\n## Week3\n## Module 3:\n\n### Matrices, vectors, and solving simultaneous equation problems\n\n#### Motivations for linear algebra\n\n\n```python\nfrom sympy import solve, Poly, Eq, Function, exp\n\nfrom sympy.abc import x, y, z, a, b\n```\n\n$2a + 3b = 8$\n\n$10a +1b = 13$\n\n\n```python\nsolve((2 * a + 3* b- 8, 10 * a + b - 13), a, b)\n```\n\n\n\n\n {a: 31/28, b: 27/14}\n\n\n\n$\\begin{pmatrix} 2 & 3 \\\\ 10 & 1 \\end{pmatrix} \\begin{bmatrix} a \\\\ b \\end{bmatrix} = \\begin{bmatrix} 8 \\\\ 13 \\end{bmatrix}$ \n\n## How matrices transform space\n\n\n```python\nimport numpy as np\nm = np.array([[2 ,3],[10,1]])\nv = np.array([[31/28], [27/14]])\n```\n\n\n```python\nm@v\n```\n\n\n\n\n array([[ 8.],\n [13.]])\n\n\n\n\n```python\nv.T\n```\n\n\n\n\n array([1.10714286, 1.92857143])\n\n\n\n\n```python\nm = np.array([[7 ,-6],[12,8]])\n```\n\n\n```python\nv1 = np.array([7, 12]); v2 = np.array([-6,8])\n```\n\n\n```python\n5*v1 + 6 * v2\n```\n\n\n\n\n array([ -1, 108])\n\n\n\n\n```python\nm @ [5,6]\n```\n\n\n\n\n array([ -1, 108])\n\n\n\n# Type of Matrix Transformation\n\n\n```python\nI = np.eye(2);I # Identity matrix\n```\n\n\n\n\n array([[1., 0.],\n [0., 1.]])\n\n\n\n\n```python\nScale = np.diag([3,2]); Scale # scale matrix\n```\n\n\n\n\n array([[3, 0],\n [0, 2]])\n\n\n\n\n```python\nScale2 = np.diag([-1,2]); Scale2 # scale matrix\n```\n\n\n\n\n array([[-1, 0],\n [ 0, 2]])\n\n\n\n### rotation matrix\n\n\n```python\ntheta = np.pi/6\nc, s = np.cos(theta), np.sin(theta)\nR = np.array([[c, -s], [s, c]]);R\n```\n\n\n\n\n array([[ 0.8660254, -0.5 ],\n [ 0.5 , 0.8660254]])\n\n\n\n### Composition or combination of matrix transformations\n\n\n```python\nA1 = R\n```\n\n\n```python\nA2 = np.array([[-1, 0.0], [0.0, 1]]) #vertical mirror\n```\n\n\n```python\nA21=A2@A1\nnp.where(abs(A21)>1e-15,A21,0).round()\n```\n\n\n\n\n array([[ 0., -1.],\n [-1., 0.]])\n\n\n\n\n```python\nA12 = A1@A2\nnp.where(abs(A12)>1e-15,A12,0).round()\n```\n\n\n\n\n array([[0., 1.],\n [1., 0.]])\n\n\n\n#### Matrix multipication is not commutative\n\n#### but Matrix multipication is associative \n\n# Using matrices to make transformations\n### Practice Quiz\n\n\n```python\nA = np.array([[1/2, -1], [0, 3/4]]); A\n```\n\n\n\n\n array([[ 0.5 , -1. ],\n [ 0. , 0.75]])\n\n\n\n\n```python\nA@[-2, 4]\n```\n\n\n\n\n array([-5., 3.])\n\n\n\n\n```python\nM= np.array([[1, 0], [0, 8]])@ np.array([[1, 0], [-0.5, 1]]);M\n```\n\n\n\n\n array([[ 1., 0.],\n [-4., 8.]])\n\n\n\n# Solving the apples and bananas problem: Gaussian elimination\n\n\n```python\nM = np.array([[1,1,3],[1, 2, 4],[1, 1, 2]]); M\n```\n\n\n\n\n array([[1, 1, 3],\n [1, 2, 4],\n [1, 1, 2]])\n\n\n\n\n```python\nfrom scipy.linalg import lu\npl, u = lu(M, permute_l=True); u\n```\n\n\n\n\n array([[ 1., 1., 3.],\n [ 0., 1., 1.],\n [ 0., 0., -1.]])\n\n\n\n\n```python\npl@u\n```\n\n\n\n\n array([[1., 1., 3.],\n [1., 2., 4.],\n [1., 1., 2.]])\n\n\n\n\n```python\nb = np.array([15, 21, 13])\nx = np.linalg.solve(M, b);x\n```\n\n\n\n\n array([5., 4., 2.])\n\n\n\n\n```python\nI1 = np.array([1, 0, 0])\nb1 = np.linalg.solve(M, I1);b1\n```\n\n\n\n\n array([ 0., -2., 1.])\n\n\n\n\n```python\nI2 = np.array([0, 1, 0])\nb2 = np.linalg.solve(M, I2);b2\n```\n\n\n\n\n array([-1., 1., -0.])\n\n\n\n\n```python\nI3 = np.array([0, 0, 1])\nb3 = np.linalg.solve(M, I3);b3\n```\n\n\n\n\n array([ 2., 1., -1.])\n\n\n\n\n```python\nMinv = np.array([b1,b2,b3]).T;Minv\n```\n\n\n\n\n array([[ 0., -1., 2.],\n [-2., 1., 1.],\n [ 1., -0., -1.]])\n\n\n\n\n```python\nM@Minv\n```\n\n\n\n\n array([[1., 0., 0.],\n [0., 1., 0.],\n [0., 0., 1.]])\n\n\n\n\n```python\nnp.linalg.inv(M) == Minv\n```\n\n\n\n\n array([[ True, True, True],\n [ True, True, True],\n [ True, True, True]])\n\n\n\n### Practice Quiz\n\n\n```python\nM = np.array([[4,6,2],[3, 4, 1],[2, 8, 13]]); M\n```\n\n\n\n\n array([[ 4, 6, 2],\n [ 3, 4, 1],\n [ 2, 8, 13]])\n\n\n\n\n```python\nb = np.array([9, 7, 2])\nx = np.linalg.solve(M, b);x.round(1)\n```\n\n\n\n\n array([ 3. , -0.5, -0. ])\n\n\n\n5)\n\n\n```python\nA = np.array([[1, 1, 1],\n [3, 2, 1],\n [2, 1, 2]])\ns = np.array([15, 28, 23])\np = np.linalg.solve(A, s);p.round(1)\n```\n\n\n\n\n array([3., 7., 5.])\n\n\n\n\n```python\nnp.linalg.inv(A).round(2)\n```\n\n\n\n\n array([[-1.5, 0.5, 0.5],\n [ 2. , 0. , -1. ],\n [ 0.5, -0.5, 0.5]])\n\n\n\n# LAB\n\n# Identifying special matrices\n## Instructions\nIn this assignment, you shall write a function that will test if a 4×4 matrix is singular, i.e. to determine if an inverse exists, before calculating it.\n\nYou shall use the method of converting a matrix to echelon form, and testing if this fails by leaving zeros that can’t be removed on the leading diagonal.\n\nDon't worry if you've not coded before, a framework for the function has already been written.\nLook through the code, and you'll be instructed where to make changes.\nWe'll do the first two rows, and you can use this as a guide to do the last two.\n\n### Matrices in Python\nIn the *numpy* package in Python, matrices are indexed using zero for the top-most column and left-most row.\nI.e., the matrix structure looks like this:\n```python\nA[0, 0] A[0, 1] A[0, 2] A[0, 3]\nA[1, 0] A[1, 1] A[1, 2] A[1, 3]\nA[2, 0] A[2, 1] A[2, 2] A[2, 3]\nA[3, 0] A[3, 1] A[3, 2] A[3, 3]\n```\nYou can access the value of each element individually using,\n```python\nA[n, m]\n```\nwhich will give the n'th row and m'th column (starting with zero).\nYou can also access a whole row at a time using,\n```python\nA[n]\n```\nWhich you will see will be useful when calculating linear combinations of rows.\n\nA final note - Python is sensitive to indentation.\nAll the code you should complete will be at the same level of indentation as the instruction comment.\n\n### How to submit\nEdit the code in the cell below to complete the assignment.\nOnce you are finished and happy with it, press the *Submit Assignment* button at the top of this notebook.\n\nPlease don't change any of the function names, as these will be checked by the grading script.\n\nIf you have further questions about submissions or programming assignments, here is a [list](https://www.coursera.org/learn/linear-algebra-machine-learning/discussions/weeks/1/threads/jB4klkn5EeibtBIQyzFmQg) of Q&A. You can also raise an issue on the discussion forum. Good luck!\n\n\n```python\n# GRADED FUNCTION\nimport numpy as np\n\n# Our function will go through the matrix replacing each row in order turning it into echelon form.\n# If at any point it fails because it can't put a 1 in the leading diagonal,\n# we will return the value True, otherwise, we will return False.\n# There is no need to edit this function.\ndef isSingular(A) :\n B = np.array(A, dtype=np.float_) # Make B as a copy of A, since we're going to alter it's values.\n try:\n fixRowZero(B)\n fixRowOne(B)\n fixRowTwo(B)\n fixRowThree(B)\n except MatrixIsSingular:\n return True\n return False\n\n# This next line defines our error flag. For when things go wrong if the matrix is singular.\n# There is no need to edit this line.\nclass MatrixIsSingular(Exception): pass\n\n# For Row Zero, all we require is the first element is equal to 1.\n# We'll divide the row by the value of A[0, 0].\n# This will get us in trouble though if A[0, 0] equals 0, so first we'll test for that,\n# and if this is true, we'll add one of the lower rows to the first one before the division.\n# We'll repeat the test going down each lower row until we can do the division.\n# There is no need to edit this function.\ndef fixRowZero(A) :\n if A[0,0] == 0 :\n A[0] = A[0] + A[1]\n if A[0,0] == 0 :\n A[0] = A[0] + A[2]\n if A[0,0] == 0 :\n A[0] = A[0] + A[3]\n if A[0,0] == 0 :\n raise MatrixIsSingular()\n A[0] = A[0] / A[0,0]\n return A\n\n# First we'll set the sub-diagonal elements to zero, i.e. A[1,0].\n# Next we want the diagonal element to be equal to one.\n# We'll divide the row by the value of A[1, 1].\n# Again, we need to test if this is zero.\n# If so, we'll add a lower row and repeat setting the sub-diagonal elements to zero.\n# There is no need to edit this function.\ndef fixRowOne(A) :\n A[1] = A[1] - A[1,0] * A[0]\n if A[1,1] == 0 :\n A[1] = A[1] + A[2]\n A[1] = A[1] - A[1,0] * A[0]\n if A[1,1] == 0 :\n A[1] = A[1] + A[3]\n A[1] = A[1] - A[1,0] * A[0]\n if A[1,1] == 0 :\n raise MatrixIsSingular()\n A[1] = A[1] / A[1,1]\n return A\n\n# This is the first function that you should complete.\n# Follow the instructions inside the function at each comment.\ndef fixRowTwo(A) :\n # Insert code below to set the sub-diagonal elements of row two to zero (there are two of them).\n A[2] = A[2] - A[2,0] * A[0]\n A[2] = A[2] - A[2,1] * A[1]\n # Next we'll test that the diagonal element is not zero.\n if A[2,2] == 0 :\n # Insert code below that adds a lower row to row 2.\n A[2] = A[2] + A[3]\n # Now repeat your code which sets the sub-diagonal elements to zero.\n A[2] = A[2] - A[2,0] * A[0]\n A[2] = A[2] - A[2,1] * A[1] \n \n if A[2,2] == 0 :\n raise MatrixIsSingular()\n # Finally set the diagonal element to one by dividing the whole row by that element.\n A[2] = A[2] / A[2,2]\n return A\n\n# You should also complete this function\n# Follow the instructions inside the function at each comment.\ndef fixRowThree(A) :\n # Insert code below to set the sub-diagonal elements of row three to zero.\n A[3] = A[3] - A[3,0] * A[0]\n A[3] = A[3] - A[3,1] * A[1]\n A[3] = A[3] - A[3,2] * A[2]\n \n # Complete the if statement to test if the diagonal element is zero.\n if A[3,3] == 0 :\n raise MatrixIsSingular()\n # Transform the row to set the diagonal element to one.\n A[3] = A[3] / A[3,3]\n return A\n```\n\n## Test your code before submission\nTo test the code you've written above, run the cell (select the cell above, then press the play button [ ▶| ] or press shift-enter).\nYou can then use the code below to test out your function.\nYou don't need to submit this cell; you can edit and run it as much as you like.\n\nTry out your code on tricky test cases!\n\n\n```python\nA = np.array([\n [2, 0, 0, 0],\n [0, 3, 0, 0],\n [0, 0, 4, 4],\n [0, 0, 5, 5]\n ], dtype=np.float_)\nisSingular(A)\n```\n\n\n\n\n True\n\n\n\n\n```python\nA = np.array([\n [0, 7, -5, 3],\n [2, 8, 0, 4],\n [3, 12, 0, 5],\n [1, 3, 1, 3]\n ], dtype=np.float_)\nfixRowZero(A)\n```\n\n\n\n\n array([[ 1. , 7.5, -2.5, 3.5],\n [ 2. , 8. , 0. , 4. ],\n [ 3. , 12. , 0. , 5. ],\n [ 1. , 3. , 1. , 3. ]])\n\n\n\n\n```python\nfixRowOne(A)\n```\n\n\n\n\n array([[ 1. , 7.5 , -2.5 , 3.5 ],\n [-0. , 1. , -0.71428571, 0.42857143],\n [ 3. , 12. , 0. , 5. ],\n [ 1. , 3. , 1. , 3. ]])\n\n\n\n\n```python\nfixRowTwo(A)\n```\n\n\n\n\n array([[ 1. , 7.5 , -2.5 , 3.5 ],\n [-0. , 1. , -0.71428571, 0.42857143],\n [ 0. , 0. , 1. , 1.5 ],\n [ 1. , 3. , 1. , 3. ]])\n\n\n\n\n```python\nfixRowThree(A)\n```\n\n\n\n\n array([[ 1. , 7.5 , -2.5 , 3.5 ],\n [-0. , 1. , -0.71428571, 0.42857143],\n [ 0. , 0. , 1. , 1.5 ],\n [ 0. , 0. , 0. , 1. ]])\n\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "35887ca66bf987eb945e49416758b3c556a138d4", "size": 26066, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "week3/Module_3.ipynb", "max_stars_repo_name": "FarhadManiCodes/Math_for_ML_Coursera", "max_stars_repo_head_hexsha": "68f06d7be417d625f60a7257e81242084c0cc7d9", "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": "week3/Module_3.ipynb", "max_issues_repo_name": "FarhadManiCodes/Math_for_ML_Coursera", "max_issues_repo_head_hexsha": "68f06d7be417d625f60a7257e81242084c0cc7d9", "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": "week3/Module_3.ipynb", "max_forks_repo_name": "FarhadManiCodes/Math_for_ML_Coursera", "max_forks_repo_head_hexsha": "68f06d7be417d625f60a7257e81242084c0cc7d9", "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": 22.8048993876, "max_line_length": 285, "alphanum_fraction": 0.4495511394, "converted": true, "num_tokens": 4076, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474200908501, "lm_q2_score": 0.894789454880027, "lm_q1q2_score": 0.854208444625716}} {"text": "# Logistic Regression\n\n```{note}\nLogistic Regression = Logistic model + binary cross entropy loss.
\nFor multi-class classification problem, we can use softmax regression.\n```\n\n## Model\n\nFor binary classification problem where $x \\in \\mathbb{R}^{d}$, $y \\in \\left\\{0, 1\\right\\}$, we could approach the classification problem using linear regression ignoring the fact that $y$ is discrete. Howerver, it is easy to construct examples that performs poorly, it doesn't make sense for $h(x)$ outside $\\left[0, 1\\right]$.\n\nTo fix this, we used the logistic function(sigmoid) to force the result in $\\left[0, 1\\right]$ after the affine transformation:\n\n$$h(x) = \\frac{1}{1 + \\mbox{exp}(\\theta^{T}x)} = \\sigma(\\theta^{T}x)$$\n\n## Entropy\n\nSelf information $I(x)$ indicates the amount of information an event $x$ to happen that satisfies:\n\n1. $I(x) \\ge 0$\n2. $\\text{if }p(x_{1}) > p(x_{2}) \\text{, then } I(x_{1}) < I(x_{2})$\n3. $I(x_{1}, x_{2}) = I(x_{1}) + I(x_{2}) \\text{ for independent }x_{1},x_{2}$\n\nThis leads to $I(x) = -\\log_{r}p(x)$, for convenient $I(x) := -\\log{p(x)}$.\n\nWhile self-information measures the information of a event, entropy measures the information of a random variable:\n\n$$\nH(X) = E(I(x)) = E(-\\log{p(x)}) = -\\sum_{x \\in \\mathcal{X}}\\log{p(x)}\n$$\n\nIt is exactly the optimal encoding length of $X$.\n\nCross entropy $H(p, q)$ is the encoding length of $p$ by optimal encoding of $q$:\n\n$$H(p,q)=E_{p}\\left[-\\log{q(x)}\\right] = -\\sum_{x}p(x)\\log{q(x)}$$\n\nFix $p$, the closer $q$ is to $p$, the less is $H(p,q)$. We can use $H(p,q)$ to define the distance from $q$ to $p$.\n\n## Loss\n\nUsing the definition of cross entropy above, we interpret label $y^{(i)}$ as the distribution $p(y^{(i)}|x^{(i)}) = 1, p(1 - y^{(i)}|x^{(i)})=0$.\n\nIn the same manner, interpret the hypothesis as $q(y=1|x^{(i)}) = h(x^{(i)}), q(y=0|x^{(i)}) = 1 - h(x^{(i)})$.\n\nCross Entropy Loss from $q$ to $p$ measures the distance from hypothesis to label:\n\n$$l_{\\theta}(x^{(i)}) = -y^{(i)}\\log(h(x^{(i)})) - (1 - y^{(i)})\\log(1 - h(x^{(i)}))$$\n\nSum them up derive the cross entropy loss logistic regression uses:\n\n$$J(\\theta) = \\sum_{i=1}^{n}\\left[-y^{(i)}\\log(h(x^{(i)})) - (1 - y^{(i)})\\log(1 - h(x^{(i)}))\\right]$$\n\n## Probabilistic Interpretation\n\nAs we supposes:\n\n$$p(y|x) = h(x)^{y}\\cdot(1 - h(x))^{1 - y} $$\n\nLog likelihood of the dataset:\n\n$$\n\\begin{equation}\n\\begin{split}\nL(\\theta) &= \\log\\prod_{i=1}^{n} h(x^{(i)})^{y^{(i)}}\\cdot(1 - h(x^{(i)}))^{1 - y^{(i)}} \\\\\n&= \\sum_{i=1}^{n}y^{(i)}\\log(h(x^{(i)})) + (1 - y^{(i)})\\log(1 - h(x^{(i)}))\n\\end{split}\n\\end{equation}\n$$\n\nSo logistic regression $\\Leftrightarrow$ MLE if we see $h(x)$ as $p(y=1|x)$.\n\n## Update Rule\n\nGradient of logistic regression:\n\n\n$$\n\\begin{equation}\n\\begin{split}\n\\frac{\\partial }{\\partial \\theta_{j}}J(\\theta ) \n&= \\sum_{i=1}^{n} \\left (-y^{(i)}\\frac{1}{\\sigma(\\theta^{T}x^{(i)})} + (1 - y^{(i)})\\frac{1}{1 - \\sigma(\\theta^{T}x^{(i)})} \\right )\\frac{\\partial }{\\partial \\theta_{j}}\\sigma(\\theta^{T}x^{(i)})\\\\\n&=\\sum_{i=1}^{n} \\left (-y^{(i)}\\frac{1}{\\sigma(\\theta^{T}x^{(i)})} + (1 - y^{(i)})\\frac{1}{1 - \\sigma(\\theta^{T}x^{(i)})} \\right )\\sigma(\\theta^{T}x^{(i)})(1-\\sigma(\\theta^{T}x^{(i)}))\\frac{\\partial }{\\partial \\theta_{j}}\\theta^{T}x^{(i)} \\\\\n&=\\sum_{i=1}^{n}(h_{\\theta}(x^{(i)}) - y^{(i)})x_{j}^{(i)}\n\\end{split}\n\\end{equation}\n$$\n\nCombine all dimensions:\n\n$$\\theta \\to \\theta - \\alpha\\sum_{i=1}^{n}(h(x^{(i)}) - y^{(i)})\\cdot{x}^{(i)} $$\n\nWrite in matrix form:\n\n$$\\theta \\to \\theta - \\alpha{X}^{T}(\\sigma({X}{\\theta})-{y}) $$\n\nwhere ${X} \\in \\mathbb{R}^{n\\times{d}}, {y} \\in \\mathbb{R}^{n}$.\n\n## Examples\n\n\n```python\nfrom sklearn.datasets import load_breast_cancer\n\nX, y = load_breast_cancer(return_X_y=True)\n```\n\n\n```python\nfrom sklearn.linear_model import LogisticRegression\n\nclf = LogisticRegression(random_state=0, max_iter=5000)\nclf.fit(X, y)\nclf.predict(X[:2, :])\n```\n\n\n\n\n array([0, 0])\n\n\n\n\n```python\n# score return the mean accuracy on the given test data and labels.\nclf.predict_proba(X[:2, :]), clf.score(X, y)\n```\n\n\n\n\n (array([[1.00000000e+00, 3.16211740e-14],\n [9.99996140e-01, 3.86002382e-06]]),\n 0.9578207381370826)\n\n\n\n## Softmax Regression\n\nFor multi-class classification, we start off with a simple image classification problem, each input consists of a $2\\times{2}$ grayscale image, represent each pixel with a scalar, giving us features $\\left\\{x_{1},x_{2},x_{3}, x_{4}\\right\\}$. assume each image belong to one among the categories \"cat\", \"chiken\" and \"dog\".\n\nWe have a nice way to represent categorical data: the one-hot encoding, for our problem, \"cat\" represents by $(1,0,0)$, \"chicken\" by $(0, 1, 0)$, \"dog\" by $(0, 0, 1)$.\n\nTo estimate the conditional probabilities of all classes, we need a model with multiple outputs, one per class:\n\n$$o_{1} = x_{1}w_{11} + x_{2}w_{12} + x_{3}w_{13} + x_{4}w_{14}$$\n$$o_{2} = x_{1}w_{21} + x_{2}w_{22} + x_{3}w_{23} + x_{4}w_{24}$$\n$$o_{3} = x_{1}w_{31} + x_{2}w_{32} + x_{3}w_{33} + x_{4}w_{34}$$\n\ndepict as:\n\n\n\nWe would like $\\hat{y}_{j}$ to be interpreted as probability that a given item belong to class $j$, to transform our current outputs $\\left\\{o_{1},o_{2},o_{3},o_{4}\\right\\}$ to probability distribution $\\left\\{\\hat{y}_{1},\\hat{y}_{2},\\hat{y}_{3},\\hat{y}_{4}\\right\\}$, just use the softmax operation:\n\n$$\\hat{y}_{j} = \\frac{\\exp(o_{j})}{\\sum_{k}\\exp(o_{k})}$$\n\nAs logistic regression, we use the cross entropy loss:\n\n$$H(y,\\hat{y}) = -\\sum_{k}y_{j}\\log\\hat{y}_{j} = -\\log\\hat{y}_{\\text{category of y}}$$\n\nNow complete the construction of softmax regression.\n\n\n```python\n\"\"\"multi-class classification problem\"\"\"\nfrom sklearn.datasets import load_iris\n\nX, y = load_iris(return_X_y=True)\ny\n```\n\n\n\n\n array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,\n 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,\n 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2])\n\n\n\n\n```python\n\"\"\"\nSet multi_class='multinomial' in LogisticRegression\n\"\"\"\nsoftmax_reg = LogisticRegression(multi_class=\"multinomial\", solver=\"lbfgs\", C=10, max_iter=1000)\nsoftmax_reg.fit(X, y)\nsoftmax_reg.predict(X[:3, :])\n```\n\n\n\n\n array([0, 0, 0])\n\n\n", "meta": {"hexsha": "ca8c466562810225d11b40b6cb50fd72a631c3e1", "size": 10088, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "chapter1/3.logistic regression.ipynb", "max_stars_repo_name": "newfacade/machine-learning-handbook", "max_stars_repo_head_hexsha": "2784702b3fd24fce8f00ca7c88cb060fa23798ea", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-10T16:20:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-10T16:20:34.000Z", "max_issues_repo_path": "chapter1/3.logistic regression.ipynb", "max_issues_repo_name": "newfacade/machine-learning-handbook", "max_issues_repo_head_hexsha": "2784702b3fd24fce8f00ca7c88cb060fa23798ea", "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/3.logistic regression.ipynb", "max_forks_repo_name": "newfacade/machine-learning-handbook", "max_forks_repo_head_hexsha": "2784702b3fd24fce8f00ca7c88cb060fa23798ea", "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.0754098361, "max_line_length": 346, "alphanum_fraction": 0.4881046788, "converted": true, "num_tokens": 2617, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813463747181, "lm_q2_score": 0.8933094103149354, "lm_q1q2_score": 0.8539871328020774}} {"text": "# Numerical Recipes Workshop 4\nFor the week of 14-18 October, 2019\n\nThis notebook will cover some basics of ODE solving and advanced plotting techniques.\n\n\n```python\nfrom matplotlib import pyplot as plt\n%matplotlib inline\nimport numpy as np\n```\n\n\n```python\nplt.rcParams['figure.figsize'] = (10, 6)\nplt.rcParams['font.size'] = 14\n```\n\n## Solving ODEs\nIn this activity, you will implement and experiment with some ODE integration methods for initial value problems. You will then learn to use SciPy's [solve_ivp](https://docs.scipy.org/doc/scipy/reference/generated/scipy.integrate.solve_ivp.html#scipy.integrate.solve_ivp) function for doing this more generally.\n\nIn each case, you will solve an ODE of the form:\n\n$\n\\begin{align}\n\\frac{dy}{dt} = f(t, y)\n\\end{align}\n$\n\nA straightforward way to code this is to implement a Python function for $f(t, y)$. We will do this below for \n\n$\n\\begin{align}\n\\frac{dy}{dt} = cos(t)\n\\end{align}\n$\n\n### Define the function\nFor reasons that will be clear later, the order of arguments should be $t$ first and $y$ second.\n\n\n```python\ndef dy_dt(t, y):\n return np.cos(t)\n```\n\n### Define a step size\nWe will use $h$ to denote the step size. We will integrate from $t$ = 0 to 20. The `ts` and `ys` arrays will store the values of $t$ and the solution.\n\n\n```python\nh = 0.25\nts = np.arange(0, 20+h, h)\nys = np.empty(ts.size)\n```\n\n### Direct Euler\n\n$\n\\begin{align}\ny(t+h) = y(t) + h f(t, y)\n\\end{align}\n$\n\nThis becomes:\n\n$\n\\begin{align}\ny_{n+1} = y_{n} + h f(t_{n}, y_{n})\n\\end{align}\n$\n\n\n\n```python\n# Set the inital value\nys[0] = 0.5\n\n# Now integrate\nfor i in range(1, ts.size):\n tn = ts[i-1]\n yn = ys[i-1]\n ys[i] = yn + h * dy_dt(tn, yn)\n```\n\n\n```python\nplt.plot(ts, ys)\nplt.xlabel('t')\nplt.ylabel('y')\n```\n\n### Calculate the error\nThe above problem has the analytic solution\n\n$\n\\begin{align}\ny(t) = sin(t) + 0.5\n\\end{align}\n$\n\nWe will compare to that to measure the error.\n\n\n```python\nyexact = np.sin(ts) + 0.5\n```\n\n\n```python\nplt.plot(ts, yexact, label='exact')\nplt.plot(ts, ys, label=f'h = {h}')\nplt.legend(loc='best')\n```\n\n\n```python\nerr = np.abs(yexact - ys)\nerr_max = np.amax(err)\nplt.plot(ts, err)\nplt.xlabel('t')\nplt.ylabel('error')\nprint(err_max)\n```\n\n\n```python\nhs = np.arange(0.01, 1.0, 0.01)\nerr_array = np.array([])\n\nfor h in hs:\n ts = np.arange(0, 20+h, h)\n ys = np.empty(ts.size)\n \n # Set the inital value\n ys[0] = 0.5\n \n for i in range(1, ts.size):\n tn = ts[i-1]\n yn = ys[i-1]\n ys[i] = yn + h * dy_dt(tn, yn)\n \n yexact = np.sin(ts) + 0.5\n \n err = np.abs(yexact - ys)\n \n err_array = np.append(err_array, np.amax(err))\n\nplt.plot(hs, err_array)\nplt.xlabel('h')\nplt.ylabel('error')\n```\n\nRecord $h$ and the maximum value of the error and make a plot of error vs. step size. How does the error change with step size for the Direct Euler method?\n\n### 2nd Order Runga-Kutta\n\n$\n\\begin{align}\nk_{1} = h f(t, y),\\\\\n\\end{align}\n$\n\n$\n\\begin{align}\nk_{2} = h f(t + \\frac{h}{2}, y + \\frac{k_{1}}{2})\n\\end{align}\n$\n\n$\n\\begin{align}\ny(t+h) = y(t) + k_{2}\n\\end{align}\n$\n\n\n\n```python\nhs = np.arange(0.01, 1.0, 0.01)\nerr_array_RK2 = np.array([])\n\nfor h in hs:\n ts = np.arange(0, 20+h, h)\n ys = np.empty(ts.size)\n \n # Set the inital value\n ys[0] = 0.5\n \n # Now integrate\n for i in range(1, ts.size):\n tn = ts[i-1]\n yn = ys[i-1]\n k1 = h * dy_dt(tn, yn)\n k2 = h * dy_dt(tn + h/2, yn + k1/2)\n ys[i] = yn + k2\n \n yexact = np.sin(ts) + 0.5\n \n err = np.abs(yexact - ys)\n \n err_array_RK2 = np.append(err_array_RK2, np.amax(err))\n\nplt.plot(ts, yexact, label='exact')\nplt.plot(ts, ys, label=f'h = {h}')\nplt.legend(loc='best')\n```\n\n\n```python\nplt.plot(hs, err_array_RK2)\nplt.xlabel('h')\nplt.ylabel('error - RK2')\n```\n\nPlot the integrated and analytic solutions and calculate the error as a function of $h$. Compare this with the Direct Euler method.\n\n### 4th Order Rung-Kutta\n$\n\\begin{align}\nk_{1} = h f(t, y),\\\\\n\\end{align}\n$\n\n$\n\\begin{align}\nk_{2} = h f(t + \\frac{h}{2}, y + \\frac{k_{1}}{2})\n\\end{align}\n$\n\n$\n\\begin{align}\nk_{3} = h f(t + \\frac{h}{2}, y + \\frac{k_{2}}{2})\n\\end{align}\n$\n\n$\n\\begin{align}\nk_{4} = h f(t + h, y + k_{3})\n\\end{align}\n$\n\n$\n\\begin{align}\ny(t+h) = y(t) + \\frac{k_{1}}{6} + \\frac{k_{2}}{3} + \\frac{k_{3}}{3} + \\frac{k_{4}}{6}\n\\end{align}\n$\n\nImplement this method yourself for the same initial value problem. Make the same plots and compare the error with the DE and RK23 methods.\n\n\n```python\nhs = np.arange(0.01, 1.0, 0.01)\nerr_array_RK4 = np.array([])\n\nfor h in hs:\n ts = np.arange(0, 20+h, h)\n ys = np.empty(ts.size)\n \n # Set the inital value\n ys[0] = 0.5\n \n # Now integrate\n for i in range(1, ts.size):\n tn = ts[i-1]\n yn = ys[i-1]\n k1 = h * dy_dt(tn, yn)\n k2 = h * dy_dt(tn + h/2, yn + k1/2)\n k3 = h * dy_dt(tn + h/2, yn + k2/2)\n k4 = h * dy_dt(tn + h, yn + k3)\n \n ys[i] = yn + k1/6 + k2/3 + k3/3 + k4/6\n \n yexact = np.sin(ts) + 0.5\n \n err = np.abs(yexact - ys)\n \n err_array_RK4 = np.append(err_array_RK4, np.amax(err))\n```\n\n\n```python\nplt.plot(hs, err_array, label = 'Euler')\nplt.plot(hs, err_array_RK2, label = 'RK2')\nplt.plot(hs, err_array_RK4, label = 'RK4')\nplt.legend()\nplt.grid()\nplt.xlabel('h')\nplt.ylabel('error - RK4')\n```\n\n### The SciPy `solve_ivp` function\nSciPy's [solve_ivp](https://docs.scipy.org/doc/scipy/reference/generated/scipy.integrate.solve_ivp.html#scipy.integrate.solve_ivp) can solve IVPs using a variety of methods. The user must provide a function that accepts $t, y$ in that order as well an initial value, and range over which to solve.\n\n\n```python\nfrom scipy.integrate import solve_ivp\n```\n\n\n```python\nh = 0.05\nts = np.arange(0, 50+h, h)\nsol_range = (ts[0], ts[-1])\ny0 = 1\n```\n\n\n```python\nsol = solve_ivp(dy_dt, sol_range, [y0], t_eval=ts, method='RK45')\n```\n\n\n```python\nplt.plot(sol.t, sol.y[0])\nplt.xlabel('t')\nplt.ylabel('y')\n```\n\nNow solve the following IVP:\n\n$\n\\begin{align}\n\\large\n\\frac{dy}{dt} = y\\ cos(t),\\\\\n\\end{align}\n$\n\n$\n\\begin{align}\n\\large\ny(0) = 1\n\\end{align}\n$\n\n\nThis has the analytic solution:\n\n$\n\\begin{align}\n\\large\ny(t) = e^{sin(t)}\n\\end{align}\n$\n\nTry a few different methods using the `method` and `max_step` keywords to experiment with different solvers and step sizes.\n\n\n```python\ndef dy_dt_2(t,y):\n return y*np.cos(t)\nh = 0.05\nts = np.arange(0, 50+h, h)\nsol_range = (ts[0], ts[-1])\ny0 = 1\nyexact = np.exp(np.sin(ts))\n\nsol = solve_ivp(dy_dt_2, sol_range, [y0], t_eval=ts, method='RK45')\n\nplt.plot(sol.t, sol.y[0])\nplt.xlabel('t')\nplt.ylabel('y - solution to dy_dt_2')\n\n```\n\n## Solving a sytem of equations\nThe `solve_ivp` function can solve a system of ODEs just as easily as a single ODE. This is done by creating a function for `dy/dt` that returns multiple values.\n\nConsider the problem of parabolic motion, i.e., a projectile launched into the air with an initial velocity, feeling only the force of gravity (no air resistance). We can define the follow system of equations:\n\n$\n\\begin{align}\n\\large\n\\frac{dx}{dt} = v_{x}\n\\end{align}\n$\n\n$\n\\begin{align}\n\\large\n\\frac{dy}{dt} = v_{y}\n\\end{align}\n$\n\n$\n\\begin{align}\n\\large\n\\frac{dv_{x}}{dt} = 0\n\\end{align}\n$\n\n$\n\\begin{align}\n\\large\n\\frac{dv_{y}}{dt} = -g\n\\end{align}\n$\n\nWe can then create a function to give to `solve_ivp` as follows:\n\n\n```python\ng = 9.80665 # m/s^2\ndef projectile_motion(t, f):\n \"\"\"\n f0 = dx/dt = vx\n f1 = dy/dt = vy\n f2 = dvx/dt = 0\n f3 = dvy/dt = - g / m\n \"\"\"\n \n vals = np.zeros(4)\n vals[0] = f[2]\n vals[1] = f[3]\n vals[2] = 0\n vals[3] = - g\n\n return vals\n```\n\nWe must provide an initial value for each of the equations. Assume a starting position of (0, 0) with some initial velocity, $v_{i}$, with an angle, $\\theta$, with the ground.\n\n\n```python\nvi = 100 # m/s\ntheta = 30 * np.pi / 180 # 30 degrees\nvx = vi * np.cos(theta)\nvy = vi * np.sin(theta)\nfi = np.array([0, 0, vx, vy])\n```\n\nAdditionally, we can provide a function to determine when the projectile hits the ground. The function below returns the value of the $y$ coordinate. A root-finding method will then determine the time when this function returns 0, i.e., the ball is on the ground.\n\nThe `terminal` attribute will instruct the solver to end there, even if the full time interval has not been evaluated. The `direction` attribute can be used to filter out solutions we don't want, i.e., the initial value.\n\n\n```python\ndef object_lands(t, f):\n return f[1]\nobject_lands.terminal = True\nobject_lands.direction = -1\n```\n\n\n```python\n# Set t values\nts = np.linspace(0, 20, 401)\ntrange = (ts[0], ts[-1])\n```\n\n\n```python\n# Solve!\nsol = solve_ivp(projectile_motion, trange, fi, events=(object_lands), t_eval=ts, dense_output=True)\n```\n\nNow, plot x position vs. y position. We could also plot $v_{x}$, $v_{y}$, or $t$.\n\n\n```python\nplt.plot(sol.y[0], sol.y[1])\nplt.xlabel('x [m]')\nplt.ylabel('y [m]')\n```\n\n\n```python\n\n```\n\n## 3D and Advanced Plotting\nLines and points are great, but often insufficient for visualizing multi-dimensional data. Matplotlib provides a [3D plotting toolkit](https://matplotlib.org/3.1.1/tutorials/toolkits/mplot3d.html) for a variety of 3D plots.\n\nLet's return to the dust temperature example from Workshop 3. If you are not familiar with this, go back to the Workshop 3 notebook and read the short text on computing the temperature of interstellar dust grains.\n\nThe functions for calculating the dust temperature are given below. Previously, you solved for $T_{dust}$ for a range of densities ($n_{H}$) and a single gas temperature ($T_{gas}$). Now, let's do the same exercise for a range of gas temperatures as well. The code is given below.\n\n\n```python\nmh = 1.673735e-24 # g\n# Stefan-Boltzmann constant\nsigma_b = 5.670373e-5 # erg cm^−2 s^−1 K^−4\n\ndef gas_grain(Tgas):\n \"\"\"\n Return gas/grain heat transfer rate coefficient.\n \"\"\"\n\n grain_coef = 1.2e-31 * 1.0e3**-0.5 / mh\n gasgra = grain_coef * Tgas**0.5 * \\\n (1.0 - (0.8 * np.exp(-75.0 / Tgas)))\n return gasgra\n\ndef kappa_grain(Tdust):\n \"\"\"\n Return grain mean opacity.\n \"\"\"\n\n kgr1 = 4.0e-4\n kgr200 = 16.0\n T_subl = 1500.\n\n Tdust = np.asarray(Tdust)\n kgr = np.zeros(Tdust.size)\n\n f1 = Tdust < 200\n if f1.any():\n kgr[f1] = kgr1 * Tdust[f1]**2\n\n kgr[(Tdust >= 200) & (Tdust < T_subl)] = kgr200\n\n f2 = Tdust >= T_subl\n if f2.any():\n kgr[f2] = kgr200 * (Tdust[f2] / T_subl)**-12\n \n return kgr\n\ndef gamma_isrf():\n \"\"\"\n Interstellar radiation field heating rate coefficient.\n \"\"\"\n\n return 4.154682e-22 / mh\n\ndef gamma_grain(Tdust, Tgas, nh, isrf=1.7, z=0):\n \"\"\"\n Return the grain heating rate.\n \n Parameters\n ----------\n \n Tdust : float\n dust temperature in K\n Tgas : float\n gas temperature in K\n nh : float\n Hydrogen number density in cm^-3\n isrf : float, optional\n interstellar radiation field strengh in Habing units\n default: 1.7 (typical for local interstellar medium)\n z : float, optional\n current redshift, used to set the temperature of the\n Cosmic Microwave Background.\n default: 0\n \"\"\"\n\n TCMB = 2.73 * (1 + z)\n my_isrf = isrf * gamma_isrf()\n\n return my_isrf + \\\n 4 * sigma_b * kappa_grain(Tdust) * (TCMB**4 - Tdust**4) + \\\n (gas_grain(Tgas) * nh * (Tgas - Tdust))\n```\n\n\n```python\nimport scipy.optimize as opt\n```\n\n\n```python\n# Create arrays of Tgas and nH\nTgas = np.logspace(1, 3.5, 61)\nnH = np.logspace(0, 13, 131)\n```\n\nNow, calculate the dust temperature for all values of $n_{H}$ and $T_{dust}$. This will take a minute.\n\n\n```python\nTdust = np.empty((nH.size, Tgas.size))\nfor i in range(nH.size):\n for j in range(Tgas.size):\n Tdust[i,j] = opt.brentq(gamma_grain, 1, 1e4, args=(Tgas[j], nH[i]))\n```\n\n### Plotting $T_{dust}$ as a surface\n\nThe dust temperature can be visualized in 3D as a surface in the space ($n_{H}$, $T_{gas}$). In order to give the surface some texture for a more intuitive appearance, we can also apply a colormap to color the surface according to the heigh in the z axis.\n\n\n```python\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom matplotlib import cm\n```\n\n\n```python\nfig = plt.figure(figsize=(16, 10))\nax = fig.gca(projection='3d')\n\n# Make data.\n# Put data in log-space to view the large dynamic range.\nX, Y = np.meshgrid(np.log10(nH), np.log10(Tgas))\n\n# Note, we transpose the Tdust array.\nZ = np.log10(Tdust.T)\n\n# Plot the surface.\nsurf = ax.plot_surface(X, Y, Z, cmap=cm.coolwarm,\n linewidth=0, antialiased=False)\n\n# Customize the z axis.\n# ax.set_zlim(-1.01, 1.01)\n#ax.zaxis.set_major_locator(LinearLocator(10))\n#ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))\nax.xaxis.set_label_text('log ($n_{H} / cm^{-3}$)')\nax.xaxis.labelpad = 10\nax.yaxis.set_label_text('log ($T_{gas} / K$)')\nax.yaxis.labelpad = 10\nax.zaxis.set_label_text('log ($T_{dust} / K$)')\nax.zaxis.labelpad = 10\n\n# Add a color bar which maps values to colors.\ncb = fig.colorbar(surf, shrink=0.5, aspect=5, label='log ($T_{dust}$ / K)')\nplt.show()\n```\n\n### Plotting $T_{dust}$ as a color mesh\nThere are obvious disadvantages to plotting $T_{dust}$ as a surface, i.e., not all points can be seen or apparent values can depend somewhat on perspective. Since the z height and the color are showing the same information, we can eliminate the height component and view the above plot from the top down using the [pcolormesh](https://matplotlib.org/api/_as_gen/matplotlib.pyplot.pcolormesh.html#matplotlib.pyplot.pcolormesh) from matplotlib.\n\n\n```python\nplt.pcolormesh(X, Y, Z, cmap=cm.viridis) # change to cmap=cm.coolwarm to see same colormap as above\nplt.colorbar(label='log ($T_{dust} / K$)')\nplt.xlabel('log ($n_{H} / cm^{-3}$)')\nplt.ylabel('log ($T_{gas} / K$)')\n```\n\n## Baseball: the objectively most interesting spectator sport\nBaseball is undergoing a \"launch angle revolution.\" Players have been traditionally coached to hit the ball low to the ground in order to get \"line-drive\" hits and to avoid hitting the ball into the air where it can be easily caught for an out. However, with the advent of technology to measure the speed of the batted ball off the bat (known as \"exit-velocity\"), analysis showed that many players hit the ball with enough power to be hitting home runs (the ball is hit out of the park) regularly. Thus, players are now adjusting their swings to hit the ball with a more upward trajectory.\n\nBatted baseballs experience enough air resistance to alter their paths from a simple parabola. To compute the distance traveled by a baseball, we must consider the drag force, which is defined as\n\n$\n\\begin{align}\nF_{D} = \\frac{1}{2} C_{D} A \\rho v^{2},\n\\end{align}\n$\n\nwhere $C_{D}$ is the drag coefficient, $A$ is the cross-sectional area of the ball, $\\rho$ is the density of air, and $v$ is the velocity of the ball.\n\nAdd the drag force to the projectile motion problem to compute the travel distance a batted ball for a given exit velocity and launch angle. The relevant constants are given below.\n\n\n```python\n# baseballs\nm = 0.145 # kg\nc = 23.2 # cm\nr = c / 2 / np.pi\nA = np.pi * (r)**2 / 10000 # m^2\nCd = 0.346\n```\n\n\n```python\n# Earth-related constants\nrhoE = 1.19657921 # kg/m^3\ng = 9.80665 # m/s^s\n```\n\n\n```python\ndef baseball_flight(t, f):\n \"\"\"\n f0 = dx/dt = vx\n f1 = dy/dt = vy\n f2 = dvx/dt = F_x / m\n f3 = dvy/dt = F_y / m - g \n \"\"\"\n v_mag = np.sqrt(np.power(f[2],2)*np.power(f[3],2))\n Fx_hat = (-1/v_mag) * (f[2])\n Fy_hat = (-1/v_mag) * (f[3])\n F_x = .5 * Cd * A * rhoE * v_mag *Fx_hat\n F_y = .5 * Cd * A * rhoE * v_mag *Fy_hat\n \n vals = np.zeros(4)\n vals[0] = f[2]\n vals[1] = f[3]\n vals[2] = F_x / m\n vals[3] = F_y / m - g\n \n return vals\n```\n\n### Initial values\nThe average well-hit ball has an exit velocity of about 100 miles/hour, or about 45 m/s. Assume a launch angle of 30 degrees and that the ball is hit by the batter from a height of 1 m.\n\n\n```python\nvi = 45 # m/s\ntheta = 30 * np.pi / 180 # 30 degrees\nvx = vi * np.cos(theta)\nvy = vi * np.sin(theta)\nfi = np.array([0, 1, vx, vy])\n```\n\n### Is it a home run?\nThe average outfield wall is about 100 m from the batter and about 2 m high. A ball must reach at least this point to be considered a homerun.\n\nBaseballs will have a total flight time of less than 10 seconds.\n\nImplement an event function to determine when the ball has returned to a height of 2 m.\n\n\n```python\ndef ball_lands(t, f):\n return f[1]\n \nball_lands.terminal = True\nball_lands.direction = -1\n```\n\n\n```python\nts = np.linspace(0, 10, 201)\nsol = solve_ivp(baseball_flight, (0, 10), fi, events=(ball_lands), t_eval=ts, dense_output=True)\n```\n\nPlot the trajectory of the batted ball. An outfield wall has been provided for you.\n\n\n```python\nplt.plot(sol.y[0], sol.y[1], label='baseball')\n# Outfield wall\nplt.plot([100, 100, 110], [0, 2, 2], label='outfield wall', color='red')\nplt.legend(loc='best')\n```\n\n### Was it a homerun?\nThe `ball_lands` event will record the time for the ball to return to a height of 2 m. The `sol.sol` command can then be used to determine the values for each of the equations in the series at the given time.\n\n\n```python\nprint (f'Flight time: {sol.t_events[0][0]} s.')\nvalue = sol.sol(sol.t_events[0])\nprint (f'Distance: {value[0][0]} m.')\n```\n\n### Optimal launch angle\nPlot the distance traveled in the x direction as a function of exit velocity and launch angle for exit velocities from 90 to 115 mph (make sure to convert to m/s). What is the optimal launch angle? What is the minimum exit velocity needed to hit a home run?\n\n\n```python\n\n```\n\n### Chicago: the windy city\nWrigley Field, home of the Chicago Cubs, is well-known for fluctuating significantly between being friendly to hitters or pitchers, depending on the direction of the wind. Experiment with adding a 15 mph wind heading either in (against the direction of the batted ball) or out to see how this changes things for the problem above.\n\n\n```python\n\n```\n", "meta": {"hexsha": "6b090f245e398e1669bc189de05e0411726215ac", "size": 553123, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "c2/workshop_4.ipynb", "max_stars_repo_name": "c-abbott/num-rep", "max_stars_repo_head_hexsha": "fb548007b84f96d46527b8ea3ba0461b32a34452", "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": "c2/workshop_4.ipynb", "max_issues_repo_name": "c-abbott/num-rep", "max_issues_repo_head_hexsha": "fb548007b84f96d46527b8ea3ba0461b32a34452", "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": "c2/workshop_4.ipynb", "max_forks_repo_name": "c-abbott/num-rep", "max_forks_repo_head_hexsha": "fb548007b84f96d46527b8ea3ba0461b32a34452", "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": 320.6510144928, "max_line_length": 123320, "alphanum_fraction": 0.9309936488, "converted": true, "num_tokens": 5723, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797027760038, "lm_q2_score": 0.9372107870185259, "lm_q1q2_score": 0.853967446354005}} {"text": "# Path Planning for a Simple Car\n\n## Required Installations\n\nIf run on Google Colab, it is necessary to install any needed solvers for each Colab session. The following cell tests if the notebook is run on Google Colab, then installs Pyomo and Ipopt if not already installed.\n\n\n```python\ntry:\n import google.colab\n try:\n from pyomo.environ import *\n except:\n !pip install -q pyomo\n if not 'ipopt_executable' in vars():\n !wget -N -q \"https://ampl.com/dl/open/ipopt/ipopt-linux64.zip\"\n !unzip -o -q ipopt-linux64\n ipopt_executable = '/content/ipopt'\nexcept:\n pass\n```\n\n## Kinematic Model\n\n\nThe following equations describe a simple model of a car\n\n\\begin{align}\n\\frac{dx}{dt} & = v \\cos(\\theta) \\\\\n\\frac{dy}{dt} & = v \\sin(\\theta) \\\\\n\\frac{d\\theta}{dt} & = \\frac{v}{L}\\tan(\\phi) \\\\\n\\end{align}\n\nwhere $x$ and $y$ denote the position of the center of the rear axle, $\\theta$ is the angle of the car axis to the horizontal, $v$ is velocity, and $\\phi$ is the angle of the front steering wheels to the car axis. The length $L$ is the distance from the center of the rear axle to the center of the front axle.\n\nThe velocity $v$ is controlled by acceleration of the car, the position of the wheels is controlled by the rate limited steering input $v$.\n\n\\begin{align}\n\\frac{dv}{dt} & = a \\\\\n\\frac{d\\phi}{dt} & = u\n\\end{align}\n\nThe state of the car is determined by the value of the five state variables $x$, $y$, $\\theta$, $v$, and $\\phi$.\n\nThe path planning problem is to find find values of the manipulable variables $a(t)$ and $u(t)$ on a time interval $0 \\leq t \\leq t_f$ to drive the car from an initial condition $\\left[x(0), y(0), \\theta(0), v(0), \\phi(0)\\right]$ to a specified final condition $\\left[x(t_f), y(t_f), \\theta(t_f), v(t_f), \\phi(t_f)\\right]$ that minimizes an objective function:\n\n\\begin{align}\nJ = \\min \\int_0^{t_f} \\left( \\phi(t)^2 + \\alpha a(t)^2 + \\beta u(t)^2\\right)\\,dt\n\\end{align}\n\nand which satisfy operational constraints\n\n\\begin{align*}\n| u | & \\leq u_{max}\n\\end{align*}\n\n\n## Pyomo Model\n\n\n```python\nfrom pyomo.environ import *\nfrom pyomo.dae import *\n\nL = 2\ntf = 50\n\n# create a model object\nm = ConcreteModel()\n\n# define the independent variable\nm.t = ContinuousSet(bounds=(0, tf))\n\n# define control inputs\nm.a = Var(m.t)\nm.u = Var(m.t, domain=Reals, bounds=(-0.1,0.1))\n\n# define the dependent variables\nm.x = Var(m.t)\nm.y = Var(m.t)\nm.theta = Var(m.t)\nm.v = Var(m.t)\nm.phi = Var(m.t, domain=Reals, bounds=(-0.5,0.5))\n\nm.xdot = DerivativeVar(m.x)\nm.ydot = DerivativeVar(m.y)\nm.thetadot = DerivativeVar(m.theta)\nm.vdot = DerivativeVar(m.v)\nm.phidot = DerivativeVar(m.phi)\n\n# define the differential equation as a constraint\nm.ode_x = Constraint(m.t, rule=lambda m, t: m.xdot[t] == m.v[t]*cos(m.theta[t]))\nm.ode_y = Constraint(m.t, rule=lambda m, t: m.ydot[t] == m.v[t]*sin(m.theta[t]))\nm.ode_t = Constraint(m.t, rule=lambda m, t: m.thetadot[t] == m.v[t]*tan(m.phi[t])/L)\nm.ode_u = Constraint(m.t, rule=lambda m, t: m.vdot[t] == m.a[t])\nm.ode_p = Constraint(m.t, rule=lambda m, t: m.phidot[t] == m.u[t])\n\n# path constraints\nm.path_x1 = Constraint(m.t, rule=lambda m, t: m.x[t] >= 0)\nm.path_y1 = Constraint(m.t, rule=lambda m, t: m.y[t] >= 0)\n\n# initial conditions\nm.ic = ConstraintList()\nm.ic.add(m.x[0]==0)\nm.ic.add(m.y[0]==0)\nm.ic.add(m.theta[0]==0)\nm.ic.add(m.v[0]==0)\nm.ic.add(m.phi[0]==0)\n\n# final conditions\nm.fc = ConstraintList()\nm.fc.add(m.x[tf]==0)\nm.fc.add(m.y[tf]==20)\nm.fc.add(m.theta[tf]==0)\nm.fc.add(m.v[tf]==0)\nm.fc.add(m.phi[tf]==0)\n\n# define the optimization objective\nm.integral = Integral(m.t, wrt=m.t, rule=lambda m, t: 0.2*m.phi[t]**2 + m.a[t]**2 + m.u[t]**2)\nm.obj = Objective(expr=m.integral)\n\n# transform and solve\nTransformationFactory('dae.collocation').apply_to(m, wrt=m.t, nfe=3, ncp=12, method='BACKWARD')\nSolverFactory('ipopt', executable=ipopt_executable).solve(m).write()\n```\n\n## Accessing Solution Data\n\n\n```python\n# access the results\nt= [t for t in m.t]\n\na = [m.a[t]() for t in m.t]\nu = [m.u[t]() for t in m.t]\n\nx = [m.x[t]() for t in m.t]\ny = [m.y[t]() for t in m.t]\ntheta = [m.theta[t]() for t in m.t]\nv = [m.v[t]() for t in m.t]\nphi = [m.phi[t]() for t in m.t]\n```\n\n## Visualizing Car Path\n\n\n```python\n% matplotlib inline\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nsns.set()\n\nscl=0.3\n\ndef draw_car(x=0, y=0, theta=0, phi=0):\n R = np.array([[np.cos(theta), -np.sin(theta)], [np.sin(theta), np.cos(theta)]])\n car = np.array([[0.2, 0.5], [-0.2, 0.5], [0, 0.5], [0, -0.5],\n [0.2, -0.5], [-0.2, -0.5], [0, -0.5], [0, 0], [L, 0], [L, 0.5],\n [L + 0.2*np.cos(phi), 0.5 + 0.2*np.sin(phi)],\n [L - 0.2*np.cos(phi), 0.5 - 0.2*np.sin(phi)], [L, 0.5],[L, -0.5],\n [L + 0.2*np.cos(phi), -0.5 + 0.2*np.sin(phi)],\n [L - 0.2*np.cos(phi), -0.5 - 0.2*np.sin(phi)]])\n carz= scl*R.dot(car.T)\n plt.plot(x + carz[0], y + carz[1], 'k', lw=2)\n plt.plot(x, y, 'k.', ms=10)\n \nplt.figure(figsize=(10,10))\nfor xs,ys,ts,ps in zip(x,y,theta,phi): \n draw_car(xs, ys, ts, scl*ps)\nplt.plot(x, y, 'r--', lw=0.8)\nplt.axis('square')\n```\n\n UsageError: Line magic function `%` not found.\n\n\n\n```python\nplt.figure(figsize=(10,8))\nplt.subplot(311)\nplt.plot(t, a, t, u)\nplt.legend(['Acceleration','Steering Input'])\n\nplt.subplot(312)\nplt.plot(t, phi, t, theta)\nplt.legend(['Wheel Position','Car Direction'])\n\nplt.subplot(313)\nplt.plot(t, v)\nplt.legend(['Velocity'])\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "2ec5c1c94d233c6848acdb99eadf80fb4f23cf57", "size": 19314, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Mathematics/Mathematical Modeling/07.06-Path-Planning-for-a-Simple-Car.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/07.06-Path-Planning-for-a-Simple-Car.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/07.06-Path-Planning-for-a-Simple-Car.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.9927007299, "max_line_length": 1558, "alphanum_fraction": 0.5921093507, "converted": true, "num_tokens": 1856, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067147399245, "lm_q2_score": 0.9059898197488448, "lm_q1q2_score": 0.8539014885993002}} {"text": "# 初始化环境\n\n\n```python\nfrom IPython.display import display, Math\nfrom sympy import *\ninit_printing()\n\nfrom helper import comparator_factory, comparator_eval_factory, comparator_method_factory\n\nx,y,z = symbols('x y z')\n\ncomparator = comparator_factory('使用{}前:','使用后:')\nmethod_comparator = comparator_method_factory('调用{}前:','调用后:')\neval_comparator = comparator_eval_factory('计算前:','计算后:')\n```\n\n# 微积分\n\n这部分设计如何进行基本的微积分操作,比如微分,积分,求极限,级数展开。\n\n## 微分\n用```diff()```求微分\n\n### 基本的微分\n传入表达式和应用微分的符号变量。\n\n\n```python\nexpr = sin(x)\n\nexpr_diff = diff(expr,x)\n\ncomparator(expr, diff, x)\n```\n\n也可以用方法调用的方式计算微分\n\n\n```python\nexpr = sin(x)\n\nmethod_comparator(expr, 'diff', x)\n```\n\n如果要创建一个未执行计算的微分, 可以使用```Derivative```类。 初始化的语法和```diff()```是一样的。\n\n\n```python\nexpr = sin(x)\n\ndiff_expr = Derivative(expr,x)\n\nprint('Before evaluation:')\ndisplay(diff_expr)\n```\n\n然后调用```doit()```方法执行计算。\n\n\n```python\nprint('After evaluation:')\ndisplay(diff_expr.doit())\n```\n\n为了避免冗余代码, 后面的笔记我们使用```eval_comparator```来进行比较。\n\n### 高阶微分\n如果要计算n次高阶微分, 传入符号n次或者在符号后面传入n。\n\n\n```python\nexpr = Derivative(x**4,x,x,x)\n\neval_comparator(expr)\n```\n\n用第二种方式达到同样的效果。\n\n\n```python\nexpr = Derivative(x**4,x,3)\n\neval_comparator(expr)\n```\n\n### 高阶偏微分\n\n只要按照顺序传入符号就可以, 语法和一阶微分一样。\n\n\n```python\nexpr = Derivative(exp(x*y*z),x, y, y, z, z, z, z)\n\neval_comparator(expr)\n```\n\n或者通过数字控制每个符号的微分阶数\n\n\n```python\nexpr = Derivative(exp(x*y*z),x, y, 2, z, 4)\n\neval_comparator(expr)\n```\n\n# 积分\n\n## 不定积分\n和微分类似,积分可以通过```integral()```函数或者方法来实现。 如果要创建未计算的积分表达式,初始化一个```Integral```类然后调用```doit()```进行计算。\n\n\n```python\nexpr = Integral(cos(x),x)\n\neval_comparator(expr)\n```\n\n### 定积分\n\n传入一个包含符号,积分下限, 积分上线的tuple去进行定积分。\n\n\n```python\nexpr = Integral(exp(-x),(x,0,oo))\n\neval_comparator(expr)\n```\n\n注意,在Sympy中$\\infty$用oo表示(两个小写的'O')\n\n### 多重积分\n传入多个包含符号和积分限的tuple进行多重积分。\n\n\n```python\nexpr = Integral(exp(-x**2 - y**2), (x, -oo, oo), (y, -oo, oo))\n\neval_comparator(expr)\n```\n\n如果Sympy无法计算一个表达式的积分,机会返回未计算的积分式。\n\n\n```python\nexpr = Integral(x**x)\n\neval_comparator(expr)\n```\n\n# 极限\n\n和微分一样, 极限可以用过```limit()```函数或者方法进行微分计算。 如果要创建未计算的表达式,初始化一个```Limit```类, 然后通过调用```doit()```方法完成计算。\n\n默认情况下, ```dir = '+'```, 极限从右侧计算。\n\n\n```python\nexpr = Limit(sin(x)/x, x, 0)\n\neval_comparator(expr)\n```\n\n如果要计算左侧极限, 可以传入```dir='-'```\n\n\n```python\nexpr = Limit(sin(x)/x, x, 0, dir = '-')\n\neval_comparator(expr)\n```\n\n# 级数展开\n\n通过调用```series()```方法, Sympy可以计算误差关于$O(x-x_0)^n$, 在点$x_0$处的渐进级数展开。\n\n\n```python\nexpr = sin(x)\n\nmethod_comparator(expr, 'series', x,0,6)\n```\n\n如果要去掉误差项,可以调用```removeO()```方法。\n\n\n```python\nprint('Expanded expression without order term:')\nexpr.series(x,0,6).removeO()\n```\n\n# 参考资料\n[Sympy Documentation](http://docs.sympy.org/latest/index.html)\n\n# 相关文章\n* [Sympy笔记I]({filename}0026_sympy_intro_1_ch.ipynb)\n* [Sympy笔记II]({filename}0027_sympy_intro_2_ch.ipynb)\n* [Sympy笔记III]({filename}0028_sympy_intro_3_ch.ipynb)\n* [Sympy笔记IV]({filename}0029_sympy_intro_4_ch.ipynb)\n", "meta": {"hexsha": "31d82313ec6398e16b7022a7918cc627c103ea94", "size": 62632, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "0011_sympy/0027_sympy_intro_2_ch.ipynb", "max_stars_repo_name": "junjiecai/jupyter_demos", "max_stars_repo_head_hexsha": "8aa8a0320545c0ea09e05e94aea82bc8aa537750", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2019-09-16T10:44:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-04T18:55:52.000Z", "max_issues_repo_path": "0011_sympy/0027_sympy_intro_2_ch.ipynb", "max_issues_repo_name": "junjiecai/jupyter_demos", "max_issues_repo_head_hexsha": "8aa8a0320545c0ea09e05e94aea82bc8aa537750", "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": "0011_sympy/0027_sympy_intro_2_ch.ipynb", "max_forks_repo_name": "junjiecai/jupyter_demos", "max_forks_repo_head_hexsha": "8aa8a0320545c0ea09e05e94aea82bc8aa537750", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-10-24T16:19:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-04T18:55:57.000Z", "avg_line_length": 56.2226211849, "max_line_length": 3890, "alphanum_fraction": 0.7749712607, "converted": true, "num_tokens": 1286, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.951142217223021, "lm_q2_score": 0.8976952907388474, "lm_q1q2_score": 0.8538358892240117}} {"text": "```python\nfrom IPython.display import Image\nfrom IPython.core.display import HTML \nfrom sympy import *\nImage(url= \"https://i.imgur.com/4HeGIe7.png\")\n```\n\n\n\n\n\n\n\n\n\n```python\nt = symbols(\"t\")\nIntegral(sqrt(4*t+9))\n```\n\n\n\n\n$\\displaystyle \\int \\sqrt{4 t + 9}\\, dt$\n\n\n\n\n```python\nsimplify(Integral(sqrt(4*t+9)).doit())\n\n```\n\n\n\n\n$\\displaystyle \\frac{\\left(4 t + 9\\right)^{\\frac{3}{2}}}{6}$\n\n\n\n\n```python\nImage(url= \"https://i.imgur.com/tAO2Ij3.png\")\n\n```\n\n\n\n\n\n\n\n\n\n```python\nImage(url= \"https://i.imgur.com/kXlWcEb.png\")\n```\n\n\n\n\n\n\n\n\n\n```python\nx = symbols(\"x\")\nIntegral(x**5*sin(x**6))\n```\n\n\n\n\n$\\displaystyle \\int x^{5} \\sin{\\left(x^{6} \\right)}\\, dx$\n\n\n\n\n```python\nprint(Integral(x**5*sin(x**6)).doit())\n```\n\n -cos(x**6)/6\n\n\n\n```python\nImage(url= \"https://i.imgur.com/Mr3KaY2.png\")\n```\n\n\n\n\n\n\n\n\n\n```python\nImage(url= \"https://i.imgur.com/RpUQmc0.png\")\n```\n\n\n\n\n\n\n\n\n\n```python\nfrom sympy import pi\nIntegral(cos(pi/x)/x**2)\n```\n\n\n\n\n$\\displaystyle \\int \\frac{\\cos{\\left(\\frac{\\pi}{x} \\right)}}{x^{2}}\\, dx$\n\n\n\n\n```python\nprint(Integral(cos(pi/x)/x**2).doit())\n```\n\n -sin(pi/x)/pi\n\n\n\n```python\nImage(url= \"https://i.imgur.com/Nj4pFIO.png\")\n```\n\n\n\n\n\n\n\n\n\n```python\nImage(url= \"https://i.imgur.com/u7LsgcI.png\")\n```\n\n\n\n\n\n\n\n\n\n```python\nIntegral(sin(x)**4*cos(x))\n```\n\n\n\n\n$\\displaystyle \\int \\sin^{4}{\\left(x \\right)} \\cos{\\left(x \\right)}\\, dx$\n\n\n\n\n```python\nprint(Integral(sin(x)**4*cos(x)).doit())\n```\n\n sin(x)**5/5\n\n\n\n```python\nImage(url= \"https://i.imgur.com/Bytu7tM.png\")\n```\n\n\n\n\n\n\n\n\n\n```python\nImage(url= \"https://i.imgur.com/ZTp8zyi.png\")\n```\n\n\n\n\n\n\n\n\n\n```python\nIntegral(x*cos(1-x**2))\n```\n\n\n\n\n$\\displaystyle \\int x \\cos{\\left(x^{2} - 1 \\right)}\\, dx$\n\n\n\n\n```python\nprint(Integral(x*cos(1-x**2)).doit())\n```\n\n sin(x**2 - 1)/2\n\n\n\n```python\nImage(url= \"https://i.imgur.com/D72UOm8.png\")\n```\n\n\n\n\n\n\n\n\n\n```python\nImage(url= \"https://i.imgur.com/Tt4wiJA.png\")\n```\n\n\n\n\n\n\n\n\n\n```python\n(Integral(cos(4*t)**15*sin(4*t)))\n```\n\n\n\n\n$\\displaystyle \\int \\sin{\\left(4 t \\right)} \\cos^{15}{\\left(4 t \\right)}\\, dt$\n\n\n\n\n```python\nprint(Integral(cos(4*t)**15*sin(4*t)).doit())\n```\n\n -cos(4*t)**16/64\n\n\n\n```python\nImage(url= \"https://i.imgur.com/fp90pIZ.png\")\n```\n\n\n\n\n\n\n\n\n\n```python\nImage(url= \"https://i.imgur.com/87ipBxf.png\")\n```\n\n\n\n\n\n\n\n\n\n```python\nIntegral(sec(5*x)*tan(5*x))\n```\n\n\n\n\n$\\displaystyle \\int \\tan{\\left(5 x \\right)} \\sec{\\left(5 x \\right)}\\, dx$\n\n\n\n\n```python\nprint(Integral(sec(5*x)*tan(5*x)).doit())\n```\n\n 1/(5*cos(5*x))\n\n\n\n```python\nImage(url= \"https://i.imgur.com/p3TV8lD.png\")\n```\n\n\n\n\n\n\n\n\n\n```python\nImage(url= \"https://i.imgur.com/VOZPhlq.png\")\n```\n\n\n\n\n\n\n\n\n\n```python\nIntegral((2*x-5)**5,(x,3,5))\n```\n\n\n\n\n$\\displaystyle \\int\\limits_{3}^{5} \\left(2 x - 5\\right)^{5}\\, dx$\n\n\n\n\n```python\nprint(Integral((2*x-5)**5,(x,3,5)).doit())\n```\n\n 1302\n\n\n\n```python\nImage(url= \"https://i.imgur.com/IEjf5cG.png\")\n```\n\n\n\n\n\n\n\n\n\n```python\nImage(url= \"https://i.imgur.com/SSN6ZNW.png\")\n```\n\n\n\n\n\n\n\n\n\n```python\nIntegral(4/(sqrt(9-4*x)),(x,-4,-10))\n```\n\n\n\n\n$\\displaystyle \\int\\limits_{-4}^{-10} \\frac{4}{\\sqrt{9 - 4 x}}\\, dx$\n\n\n\n\n```python\nprint(Integral(4/(sqrt(9-4*x)),(x,-4,-10)).doit())\n```\n\n -4\n\n\n\n```python\nImage(url= \"https://i.imgur.com/GpwBaxw.png\")\n```\n\n\n\n\n\n\n\n\n\n```python\nImage(url= \"https://i.imgur.com/McCH6Kx.png\")\n```\n\n\n\n\n\n\n\n\n\n```python\nIntegral(8*x**9 + 8*x**4)\n```\n\n\n\n\n$\\displaystyle \\int \\left(8 x^{9} + 8 x^{4}\\right)\\, dx$\n\n\n\n\n```python\nprint(Integral(8*x**9 + 8*x**4).doit())\n```\n\n 4*x**10/5 + 8*x**5/5\n\n\n\n```python\nImage(url= \"https://i.imgur.com/Hziq0U9.png\")\n```\n\n\n\n\n\n\n\n\n\n```python\nImage(url= \"https://i.imgur.com/cMQDWXn.png\")\n```\n\n\n\n\n\n\n\n\n\n```python\nfrom sympy import Function\nf = Function('f')\ndef f(x):\n return x\nEq(Integral(f(x),(x,0,4)),8)\n```\n\n\n\n\n$\\displaystyle \\int\\limits_{0}^{4} x\\, dx = 8$\n\n\n\n\n```python\nIntegral(f(2*x),(x,0,2)).doit()\n```\n\n\n\n\n$\\displaystyle 4$\n\n\n\n\n```python\nImage(url= \"https://i.imgur.com/Ir5yAmw.png\")\n```\n\n\n\n\n\n\n\n\n\n```python\nImage(url= \"https://i.imgur.com/hIFtNsa.png\")\n```\n\n\n\n\n\n\n\n\n\n```python\nIntegral(sqrt(5-2*x),(x,-4,2))\n```\n\n\n\n\n$\\displaystyle \\int\\limits_{-4}^{2} \\sqrt{5 - 2 x}\\, dx$\n\n\n\n\n```python\nprint(Integral(sqrt(5-2*x),(x,-4,2)).doit())\n```\n\n -1/3 + 13*sqrt(13)/3\n\n\n\n```python\nImage(url= \"https://i.imgur.com/RXi96fW.png\")\n```\n\n\n\n\n\n\n\n\n\n```python\nImage(url= \"https://i.imgur.com/Kg571fy.png\")\n```\n\n\n\n\n\n\n\n\n\n```python\ne5 = sin(x**(Rational(1,4)))/x**(Rational(3,4))\ne5\n```\n\n\n\n\n$\\displaystyle \\frac{\\sin{\\left(\\sqrt[4]{x} \\right)}}{x^{\\frac{3}{4}}}$\n\n\n\n\n```python\ne6 = Integral(e5,(x,1,16)).doit()\ne6\n```\n\n\n\n\n$\\displaystyle - 4 \\cos{\\left(2 \\right)} + 4 \\cos{\\left(1 \\right)}$\n\n\n\n\n```python\nprint(e6)\n```\n\n -4*cos(2) + 4*cos(1)\n\n\n\n```python\nImage(url= \"https://i.imgur.com/IZerZus.png\")\n```\n\n\n\n\n\n\n\n\n\n```python\nImage(url= \"https://i.imgur.com/0JLEO9z.png\")\n```\n\n\n\n\n\n\n\n\n\n```python\ne7 = 3*sin(x)/cos(x)**2\ne7\n```\n\n\n\n\n$\\displaystyle \\frac{3 \\sin{\\left(x \\right)}}{\\cos^{2}{\\left(x \\right)}}$\n\n\n\n\n```python\nIntegral(e7,(x,0,pi/3))\n```\n\n\n\n\n$\\displaystyle \\int\\limits_{0}^{\\frac{\\pi}{3}} \\frac{3 \\sin{\\left(x \\right)}}{\\cos^{2}{\\left(x \\right)}}\\, dx$\n\n\n\n\n```python\nIntegral(e7,(x,0,pi/3)).doit()\n```\n\n\n\n\n$\\displaystyle 3$\n\n\n\n\n```python\nImage(url= \"https://i.imgur.com/ZN10AB4.png\")\n```\n\n\n\n\n\n\n\n\n\n```python\nImage(url= \"https://i.imgur.com/mb5y8z8.png\")\n```\n\n\n\n\n\n\n\n\n\n```python\nIntegral(cos(8*x)*sqrt(14-sin(8*x)))\n```\n\n\n\n\n$\\displaystyle \\int \\sqrt{14 - \\sin{\\left(8 x \\right)}} \\cos{\\left(8 x \\right)}\\, dx$\n\n\n\n\n```python\nprint(Integral(cos(8*x)*sqrt(14-sin(8*x))).doit())\n```\n\n sqrt(14 - sin(8*x))*sin(8*x)/12 - 7*sqrt(14 - sin(8*x))/6\n\n\n\n```python\nImage(url= \"https://i.imgur.com/E2evsbD.png\")\n```\n\n\n\n\n\n\n\n\n\n```python\nImage(url= \"https://i.imgur.com/iFHeHfX.png\")\n```\n\n\n\n\n\n\n\n\n\n```python\nIntegral(1/x**5*sqrt(1+(1/x**4)),(x,1,4))\n```\n\n\n\n\n$\\displaystyle \\int\\limits_{1}^{4} \\frac{\\sqrt{1 + \\frac{1}{x^{4}}}}{x^{5}}\\, dx$\n\n\n\n\n```python\nprint(Integral(1/x**5*sqrt(1+(1/x**4)),(x,1,4)).doit())\n```\n\n -257*sqrt(257)/24576 + sqrt(2)/3\n\n\n\n```python\nImage(url= \"https://i.imgur.com/nceIFbp.png\")\n```\n\n\n\n\n\n\n\n\n\n```python\nImage(url= \"https://i.imgur.com/NxrFbm7.png\")\n```\n\n\n\n\n\n\n\n\n\n```python\nIntegral(x**2*(1+3*x**3)**5,(x,0,1))\n```\n\n\n\n\n$\\displaystyle \\int\\limits_{0}^{1} x^{2} \\left(3 x^{3} + 1\\right)^{5}\\, dx$\n\n\n\n\n```python\nprint(Integral(x**2*(1+3*x**3)**5,(x,0,1)).doit())\n```\n\n 455/6\n\n\n\n```python\nImage(url= \"https://i.imgur.com/RXX2ruO.png\")\n```\n\n\n\n\n\n\n\n\n\n```python\nImage(url= \"https://i.imgur.com/8u9zXhU.png\")\n```\n\n\n\n\n\n\n\n\n\n```python\nIntegral((4*x**3)/(x**4+1)**2,(x,2,4))\n```\n\n\n\n\n$\\displaystyle \\int\\limits_{2}^{4} \\frac{4 x^{3}}{\\left(x^{4} + 1\\right)^{2}}\\, dx$\n\n\n\n\n```python\nprint(Integral((4*x**3)/(x**4+1)**2,(x,2,4)).doit())\n\n```\n\n 240/4369\n\n\n\n```python\nImage(url= \"https://i.imgur.com/pqFk6Hu.png\")\n```\n\n\n\n\n\n\n\n\n\n```python\nImage(url= \"https://i.imgur.com/vFmjBoG.png\")\n```\n\n\n\n\n\n\n\n\n\n```python\ny = symbols('y')\nIntegral(y*sqrt(y+8))\n```\n\n\n\n\n$\\displaystyle \\int y \\sqrt{y + 8}\\, dy$\n\n\n\n\n```python\nprint(Integral(y*sqrt(y+8)).doit())\n```\n\n 2*y**2*sqrt(y + 8)/5 + 16*y*sqrt(y + 8)/15 - 256*sqrt(y + 8)/15\n\n\n\n```python\nImage(url= \"https://i.imgur.com/Ef9IGex.png\")\n```\n\n\n\n\n\n\n\n\n\n```python\nImage(url= \"https://i.imgur.com/iniy2ix.png\")\n```\n\n\n\n\n\n\n\n\n\n```python\nf = 12/(4*x-7)**2\nf\n```\n\n\n\n\n$\\displaystyle \\frac{12}{\\left(4 x - 7\\right)^{2}}$\n\n\n\n\n```python\ng = Integral(f)\nc = symbols('c')\nEq(g.subs(x,2)+c,-6)\n```\n\n\n\n\n$\\displaystyle c + \\int\\limits^{2} \\frac{12}{\\left(4 x - 7\\right)^{2}}\\, dx = -6$\n\n\n\n\n```python\nsolve(Eq(g.subs(x,2)+c,-6),c)\n```\n\n\n\n\n [-3]\n\n\n\n\n```python\nprint(g.doit()-3)\n```\n\n -3 - 12/(16*x - 28)\n\n\n\n```python\nImage(url= \"https://i.imgur.com/K2tpqzf.png\")\n```\n\n\n\n\n\n\n\n", "meta": {"hexsha": "c272efbd920eb26a6875730a95c4a68d1c64559e", "size": 37999, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Calculus_Homework/WWB20.ipynb", "max_stars_repo_name": "NSC9/Sample_of_Work", "max_stars_repo_head_hexsha": "8f8160fbf0aa4fd514d4a5046668a194997aade6", "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": "Calculus_Homework/WWB20.ipynb", "max_issues_repo_name": "NSC9/Sample_of_Work", "max_issues_repo_head_hexsha": "8f8160fbf0aa4fd514d4a5046668a194997aade6", "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": "Calculus_Homework/WWB20.ipynb", "max_forks_repo_name": "NSC9/Sample_of_Work", "max_forks_repo_head_hexsha": "8f8160fbf0aa4fd514d4a5046668a194997aade6", "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": 19.4467758444, "max_line_length": 132, "alphanum_fraction": 0.4485644359, "converted": true, "num_tokens": 2805, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966762263737, "lm_q2_score": 0.901920685097536, "lm_q1q2_score": 0.8537551227331414}} {"text": "# Occupational Therapy — Notebook\n\nFor many practising engineers, their notebook plays a key role in helping them keep their thoughts on track when working through a problem.\n\nComputational notebooks can play a similar role, with several additional benefits.\n\nFirstly, as digital documents, they can be easily searched. Secondly, as *computational* notebooks, they can can be used to record, *and execute*, mathematical and computational models.\n\nIn this notebook, we'll provide a complement to Danny Nowlan's \"Occupational Therapy\" *Chassis Simulation* column from the July, 2020, edition of *Racecar Engineering* magazine to show how to explore some of the models described using mathematical equations in that article interactively using computational notebooks.\n\nElsewhere, we'll show how you can explore actual data sets, using data rather than an mathematical models, using the computational notebook approach.\n\n## Evaluating a Simple Equation\n\nOver the years, the Pyhton programming language has been extended by many thousands of community generated \"packages\" that perform a wide variety of computational tasks, from data analysis and chart plotting, to finite element analysis to symbolic computation.\n\n*Symbolic computaion*? What's that then...?\n\nMaths... Programmes that do maths. If you've ever used Mathcad or Mathematica, that's symbolic computation.\n\nIn this notebook, I'll introduce a Python programming package called `sympy`, and show you how you can use it to \"do maths\" in a computational notebook.\n\nOne reason I'm doing it this way, in a *Jupyter* notebook, rather than Mathcad or Mathematica, is that Jupyter notebooks, the Python programming language, and the `sympy` package are all free, open source software. Another reason is that Jupyter notebooks are increasingly widely used in academic teaching and research, as well as industry. This means they provide a good basis for being able to share your work with others, as well allowing you to directly benefit from code other people have put out there that you can learn from and crib from too..\n\nSo let's get started...\n\nDanny Nowlan's article starts of with a simple equation that describes the traction circle radius ($TC_{RAD}$) as a function of tyre load ($F_z$) given a particular coefficient of friction ($k_a$) and coefficient drop off with load ($k_b$).\n\nThe basic equation takes the form:\n\n$$TC_{RAD}=k_a(1-k_b.F_z)F_z$$\n\n\nWe can calculate this expression of a range of values for $F_z$, for example zero to one thousand.\n\n*You may notice that equations in the notebook are presented in a stylised way. You can display all manner of mathematical equations in a notebook, and render the appropriately, by writing them using the LateX markup language.*\n\nTo start with, we declare that we want some symbolic variables: \n\n\n```python\nfrom sympy import symbols\n\nTC_RAD, F_z, k_a, k_b = symbols('TC_RAD F_z k_a k_b')\n```\n\nWe can assign particular values to symbolic quantities:\n\n\n```python\nk_a = 2\nk_b = 5e-5\n```\n\nWe can also write symbolic equations:\n\n\n```python\nTC_RAD = k_a *(1-k_b * F_z) * F_z\nTC_RAD\n```\n\n\n\n\n$\\displaystyle F_{z} \\left(2 - 0.0001 F_{z}\\right)$\n\n\n\nGiven a symbolic equation, we can plot it:\n\n\n```python\nfrom sympy.plotting import plot\n\n# We aren't going to do symbolic sums using the min/max values\n# so we don't need to define them as symbols in this case\n# We can just declare normal Python variables\nF_z_min = 0\nF_z_max = 10000\n\nplot(TC_RAD, (F_z, F_z_min, F_z_max), xlabel='$F_z$', ylabel='$TC_{RAD}$');\n```\n\nWe can also make a interactive plot that allows us to explore the effect of changing the $k_a$ and $k_b$ parameter values:\n\n\n```python\nfrom ipywidgets import interact\n\n# Unfortunately, the default slider widget does not show small numbers...\n@interact(k_a=(0, 5, 0.1),\n k_b=(1e-5,1e-4, 5e-6))\ndef charter(k_a=2, k_b=5e-5):\n TC_RAD = k_a *(1-k_b * F_z) * F_z\n plot(TC_RAD, (F_z, F_z_min, F_z_max), xlabel='$F_z$', ylabel='$TC_{RAD}$',\n title=f'$k_b$={k_b}');\n\n```\n\n\n interactive(children=(FloatSlider(value=2.0, description='k_a', max=5.0), FloatSlider(value=5e-05, description…\n\n\nWe can expliclty define a log slider plot that is a bit more sensitve in its display; note that by defining the plot, we can also control the label that is displayed:\n\n\n```python\nimport ipywidgets as widgets\n\nk_b_slider = widgets.FloatLogSlider(\n value=-5, # This is the power of the initial value\n base=10,\n min=-5, max=-4, # limits are powers\n step=0.01,\n description='$k_b$:'\n)\n\n\ninteract(charter, k_b=k_b_slider);\n```\n\n\n interactive(children=(IntSlider(value=2, description='k_a', max=6, min=-2), FloatLogSlider(value=1e-05, descri…\n\n\nThe article suggests differentiating the equation for $TC_{RAD}$ and then solving by setting the result to zero.\n\nWe can differentiate expression by asking *sympy* to differentiate the equation for us:\n\n\n```python\nfrom sympy import diff\n\n# Redefine the symbols\nTC_RAD, F_z, k_a, k_b = symbols('TC_RAD F_z k_a k_b')\n\n# Redefine the equation\nTC_RAD = k_a *(1 - k_b * F_z) * F_z\n\n# Differentiate with respect to load, F_z\ndiff(TC_RAD, F_z)\n```\n\n\n\n\n$\\displaystyle - F_{z} k_{a} k_{b} + k_{a} \\left(- F_{z} k_{b} + 1\\right)$\n\n\n\nAnd then we can solve it automatically as well:\n\n\n```python\nfrom sympy import solve\n\nsolve(diff(TC_RAD, F_z))\n```\n\n\n\n\n [{F_z: 1/(2*k_b)}, {k_a: 0}]\n\n\n\nThe result is a list of possible solutions (in Pyhton, a list represented by comma separated values in square brackets, `[...]`).\n\nWe can extract the first solution (list index `0`) and display it:\n\n\n```python\nL_P = symbols('L_P')\n\nL_P = solve(diff(TC_RAD, F_z))[0][F_z]\nL_P\n```\n\n\n\n\n$\\displaystyle \\frac{1}{2 k_{b}}$\n\n\n\nwhich is the same as the expression for Equation 2 in the article:\n\n$L_p=\\frac{1}{2.k_b}$\n\nThe article then identifies the maximum traction circle radius as:\n\n$TC_{RAD\\_MAX}=\\frac{k_a.L_P}{2}$\n\nWe can computationally derive this by substituting in our value of `L_P` into the equation for `TC_RAD`:\n\n\n```python\nTC_RAD_MAX = k_a *(1 - k_b * L_P) * L_P\nTC_RAD_MAX\n```\n\n\n\n\n$\\displaystyle \\frac{k_{a}}{4 k_{b}}$\n\n\n\nFor $L_p=\\frac{1}{2.k_b}$, this gives us the result of equation 3 in the article.\n\nOne of the major problems with maths notation used in Racecar Engineering magazine articles is that the symbols are often used inconsistently; for example, is $L_P$ of equation 3 intended to be the same as the previously derived $L_p$ from equation 2? As another example of notational ambiguity, in table 1, the value of $k_b$ is given as `5.0e-5 (1/N)`; the `(1/N)` component is presumably referring to the units rather than an unexplained part of the equation referring to some undeclared quantity `N`? (Many articles are all but impossible to follow without a lot of mental gymnastics trying to make sense of the garbled notation...)\n\nMoving on in the article, equation 4 provides expressions for determining front and rear cornering speeds using quantities:\n\n- $F_{xf}$: deduced front lateral force derived from equation 1;\n- $F_{yr}$: deduced rear lateral force derived from equation 1;\n- $wdf$: front weight distribution (per cent / 100);\n- $m_t$: total car mass (kg);\n- $iR$: peak corner curvature (1/m);\n- $V_x$: cornering speed (m/s).\n\n\n\n\n```python\nF_xf, F_yr, wdf, m_t, iR, V_x = symbols('F_xf F_yr wdf m_t iR V_x')\n\nF_xf = wdf * m_t * iR * V_x**2\nF_yr = (1 - wdf) * m_t * iR * V_x**2\n```\n\nThe article then gives a view of a whole host of other settings in an Excel worksheet but no formulas to show how they gerneate the claimed results also show in the worksheet.\n\nIn all the years I've read Racecar Engineer, I'm not sure I can recall a single article with a mathematical basis that I could replicate all the various elements myself... And this one is no different!\n", "meta": {"hexsha": "9575fe59574361eaa14fcad753b230a5506cab66", "size": 28880, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Occupational Therapy.ipynb", "max_stars_repo_name": "f1datajunkie/coding_for_racecar_engineers", "max_stars_repo_head_hexsha": "a778f234fad0d516f71ae855c6f02f7703b50f1c", "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": "Occupational Therapy.ipynb", "max_issues_repo_name": "f1datajunkie/coding_for_racecar_engineers", "max_issues_repo_head_hexsha": "a778f234fad0d516f71ae855c6f02f7703b50f1c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-06-29T07:30:48.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-29T07:53:55.000Z", "max_forks_repo_path": "Occupational Therapy.ipynb", "max_forks_repo_name": "f1datajunkie/coding_for_racecar_engineers", "max_forks_repo_head_hexsha": "a778f234fad0d516f71ae855c6f02f7703b50f1c", "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": 61.974248927, "max_line_length": 15264, "alphanum_fraction": 0.7841759003, "converted": true, "num_tokens": 2040, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9539660949832346, "lm_q2_score": 0.894789457685656, "lm_q1q2_score": 0.8535988047805515}} {"text": "### Common Activation Functions\n\n\n```python\nimport numpy as np\nfrom math import tanh\nfrom matplotlib import pyplot as plt\ni = np.arange(-10, 10, .1)\n\ndef softplus(x):\n return np.log(1 + np.exp(x))\n\nplt.plot(i, softplus(i))\nplt.ylabel('softplus(x)')\nplt.show()\n\ndef logistic_sigmoid(x):\n return 1 / (1 + np.exp(-x))\n\nplt.plot(i, logistic_sigmoid(i))\nplt.ylabel('logistic_sigmoid(x)')\nplt.show()\n\ndef softmax(x):\n e_x = np.exp(x - np.max(x))\n return e_x / e_x.sum()\n\nplt.plot(i, softmax(i))\nplt.ylabel('softmax(x)')\nplt.show()\n\ndef rectified_linear_activation_function(z):\n return max([0, z])\n\nplt.plot(i, list(map(rectified_linear_activation_function, i)))\nplt.ylabel('rectified_linear_activation_function(x)')\nplt.show()\n\nplt.plot(i, list(map(tanh, i)))\nplt.ylabel('tanh(x)')\nplt.show()\n\n\n```\n\n### XOR as a Neural Network in Numpy, Keras (TensorFlow), TensorFlow, and PyTorch\n\nXOR with Numpy\n\n\n```python\nimport numpy as np\n\nX = np.matrix([[0, 0],\n [0, 1],\n [1, 0],\n [1, 1]])\nW = np.matrix([[1, 1],\n [1, 1]])\nc = np.array([0, -1])\nw = np.matrix([[1],\n [-2]])\n\nA_in = (X * W + c)\nA_out = np.matrix([list(rectified_linear_activation_function(y) for y in x) for x in A_in.tolist()])\nA_out * w\n```\n\n\n\n\n matrix([[0],\n [1],\n [1],\n [0]])\n\n\n\nXOR with Keras\n\n\n```python\nimport keras\n\nmodel = keras.models.Sequential()\nmodel.add(keras.layers.core.Dense(2, activation='relu', input_shape=(2,)))\nmodel.add(keras.layers.core.Dense(1)) # linear is the default activation (https://keras.io/activations/)\nmodel.set_weights([\n np.array([[1 , 1], [1, 1]]),\n np.array([ 0, -1]),\n np.array([[1], [-2]]),\n np.array([ 0])\n])\nmodel.predict_classes(X)\n```\n\n 4/4 [==============================] - 0s\n\n\n\n\n\n array([[0],\n [1],\n [1],\n [0]], dtype=int32)\n\n\n\nXOR with TensorFlow\n\n\n```python\nimport tensorflow as tf\n\ntfX = tf.constant(X, dtype='float64')\ntfW = tf.Variable(W, dtype='float64')\ntfc = tf.Variable(c, dtype='float64')\ntfw = tf.Variable(w, dtype='float64')\n\nnode1 = tf.matmul(tfX, tfW)\nnode2 = tf.add(node1, tfc)\nnode3 = tf.nn.relu(node2)\nnode4 = tf.matmul(node3, tfw)\n\ninit = tf.global_variables_initializer()\nsess = tf.Session()\nsess.run(init)\nsess.run(node4)\n```\n\n\n\n\n array([[ 0.],\n [ 1.],\n [ 1.],\n [ 0.]])\n\n\n\nXOR with PyTorch\n\n\n```python\nfrom torch import Tensor\nfrom torch.autograd import Variable\nfrom torch.nn import Module, Linear, Parameter \nfrom torch.nn.functional import relu\n\nclass Net(Module):\n def __init__(self):\n super(Net, self).__init__()\n self.fc1 = Linear(2, 2)\n self.fc2 = Linear(2, 1)\n def forward(self, x):\n x = relu(self.fc1(x))\n x = self.fc2(x)\n return x\n\nnet = Net()\n\nnet.fc1.weight = Parameter(Tensor([[1, 1],\n [1, 1]]))\nnet.fc1.bias = Parameter(Tensor([[0, -1]]))\nnet.fc2.weight = Parameter(Tensor([[1, -2]]))\nnet.fc2.bias = Parameter(Tensor([[0]]))\n\ninput = Variable(Tensor([[0, 0],\n [0, 1],\n [1, 0],\n [1, 1]]))\nout = net(input)\nout\n```\n\n\n\n\n Variable containing:\n 0\n 1\n 1\n 0\n [torch.FloatTensor of size 4x1]\n\n\n\n## Neural Network w/ Loss Function, Gradient, and Optimization defined with Sympy\n\n\n```python\nimport numpy as np\nimport sympy\n\nx_data = np.array([1, 2, 3])\ny_data = np.array([2, 4, 6])\n\nx, y, w, y_pred = sympy.symbols('x y w y_pred')\ny_pred = x * w\nprint('forward:', y_pred)\nloss = (y_pred - y)**2\nprint('loss:', loss)\ngradient = sympy.diff(loss, w)\nprint('gradient:', gradient)\n\nw_in = np.random.randint(0,3)\nprint('w:', w_in)\nlearning_rate = 0.01\nprint('learning_rate:', learning_rate, '\\n')\nfor epoch in range(10):\n for x_in, y_in in zip(x_data, y_data):\n print('x:', x_in, 'y:', y_in, 'w:', w_in)\n grad = gradient.evalf(subs={x: x_in, y: y_in, w: w_in})\n print('gradient:', grad)\n w_in = w_in - learning_rate * grad\n l = loss.evalf(subs={x: x_in, y: y_in, w: w_in})\n print('loss:', l, '\\n')\n```\n\n forward: w*x\n loss: (w*x - y)**2\n gradient: 2*x*(w*x - y)\n w: 2\n learning_rate: 0.01 \n \n x: 1 y: 2 w: 2\n gradient: 0.e-141\n x: 2 y: 4 w: 2.00000000000000\n gradient: 0.e-140\n x: 3 y: 6 w: 2.00000000000000\n gradient: 0.e-140\n loss: 4.62129760221396e-274 \n \n x: 1 y: 2 w: 2.00000000000000\n gradient: 0.e-141\n x: 2 y: 4 w: 2.00000000000000\n gradient: 0.e-140\n x: 3 y: 6 w: 2.00000000000000\n gradient: 0.e-140\n loss: 4.62129760221396e-274 \n \n x: 1 y: 2 w: 2.00000000000000\n gradient: 0.e-141\n x: 2 y: 4 w: 2.00000000000000\n gradient: 0.e-140\n x: 3 y: 6 w: 2.00000000000000\n gradient: 0.e-140\n loss: 4.62129760221396e-274 \n \n x: 1 y: 2 w: 2.00000000000000\n gradient: 0.e-141\n x: 2 y: 4 w: 2.00000000000000\n gradient: 0.e-140\n x: 3 y: 6 w: 2.00000000000000\n gradient: 0.e-140\n loss: 4.62129760221396e-274 \n \n x: 1 y: 2 w: 2.00000000000000\n gradient: 0.e-141\n x: 2 y: 4 w: 2.00000000000000\n gradient: 0.e-140\n x: 3 y: 6 w: 2.00000000000000\n gradient: 0.e-140\n loss: 4.62129760221396e-274 \n \n x: 1 y: 2 w: 2.00000000000000\n gradient: 0.e-141\n x: 2 y: 4 w: 2.00000000000000\n gradient: 0.e-140\n x: 3 y: 6 w: 2.00000000000000\n gradient: 0.e-140\n loss: 4.62129760221396e-274 \n \n x: 1 y: 2 w: 2.00000000000000\n gradient: 0.e-141\n x: 2 y: 4 w: 2.00000000000000\n gradient: 0.e-140\n x: 3 y: 6 w: 2.00000000000000\n gradient: 0.e-140\n loss: 4.62129760221396e-274 \n \n x: 1 y: 2 w: 2.00000000000000\n gradient: 0.e-141\n x: 2 y: 4 w: 2.00000000000000\n gradient: 0.e-140\n x: 3 y: 6 w: 2.00000000000000\n gradient: 0.e-140\n loss: 4.62129760221396e-274 \n \n x: 1 y: 2 w: 2.00000000000000\n gradient: 0.e-141\n x: 2 y: 4 w: 2.00000000000000\n gradient: 0.e-140\n x: 3 y: 6 w: 2.00000000000000\n gradient: 0.e-140\n loss: 4.62129760221396e-274 \n \n x: 1 y: 2 w: 2.00000000000000\n gradient: 0.e-141\n x: 2 y: 4 w: 2.00000000000000\n gradient: 0.e-140\n x: 3 y: 6 w: 2.00000000000000\n gradient: 0.e-140\n loss: 4.62129760221396e-274 \n \n\n\n\n```python\n\n```\n", "meta": {"hexsha": "f111e66eb422cb6afc134726dae3e9fe4c733d5a", "size": 83306, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "py/neuralnetworks.ipynb", "max_stars_repo_name": "davidbailey/etc", "max_stars_repo_head_hexsha": "9239a5e90a72e7d11d213ea5e7cc41176d066780", "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": "py/neuralnetworks.ipynb", "max_issues_repo_name": "davidbailey/etc", "max_issues_repo_head_hexsha": "9239a5e90a72e7d11d213ea5e7cc41176d066780", "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": "py/neuralnetworks.ipynb", "max_forks_repo_name": "davidbailey/etc", "max_forks_repo_head_hexsha": "9239a5e90a72e7d11d213ea5e7cc41176d066780", "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": 173.9164926931, "max_line_length": 16850, "alphanum_fraction": 0.8881713202, "converted": true, "num_tokens": 2292, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582554941718, "lm_q2_score": 0.9173026595857203, "lm_q1q2_score": 0.8535118323982935}} {"text": "# Lab 3\n## Introduction\nIn this lab we will analyse population dynamics under the logisitic model with managed harvesting.\n\nFirst import the modules we need.\n\n\n```python\nfrom plotly.figure_factory import create_quiver\nfrom plotly import graph_objs as go\nfrom numpy import meshgrid, arange, sqrt, linspace\nfrom scipy.integrate import odeint\n```\n\n## Harvesting of fish\nA population of fish in a lake, left to its own devices, is modelled by the logistic differential equation\n\\begin{align}\n\\frac{\\mathrm{d}y}{\\mathrm{d}{t}} = 4y(1-y),\n\\end{align}\nwhere the population $y$ is in units of thousands of fish and time $t$ is measured in years.\n\nFirst define a function for $\\mathrm{d}y/\\mathrm{d}x$ in terms of $y$ and $x$.\n\n\n```python\ndef diff_eq(y, x):\n return 4 * y * (1 - y)\n```\n\nNext define a function that creates a Plotly Figure object that contains a slope field and, optionally, a few solutions to initial value problems.\n\nIt automates a few things we did in the last lab.\n\n- `diff_eq` is the differential equation to be plotted\n- `x` and `y` should be outputs from `meshgrid`. \n- `args` is any additional arguments to `diff_eq` (we will use that below).\n- `initial_values` is a list (or array) of starting $y$ values from which approximate solutions will start. The corresponding $x$ value is the minimum element of `x`.\n\nNote that the numerical solutions will plotted for the whole range of $x$ values in `x`, so if they blow up you will probably get a warning and less-than-useful plot.\n\n\n```python\ndef create_slope_field(diff_eq, x, y, args=(), initial_values=()): \n S = diff_eq(y, x, *args)\n L = sqrt(1 + S**2)\n scale = 0.9*min(x[0][1]-x[0][0], y[1][0]-y[0][0]) # assume a regular grid\n fig = create_quiver(x, y, 1/L, S/L, scale=scale, arrow_scale=1e-16)\n fig.layout.update(yaxis=dict(scaleanchor='x',\n scaleratio=1,\n range=[y.min()-scale, y.max()+scale]),\n xaxis=dict(range=[x.min()-scale, x.max()+scale]),\n showlegend=False, width=500,\n height=0.8*(y.max()-y.min())/(x.max()-x.min())*500)\n x = linspace(x.min(), x.max())\n for y0 in initial_values:\n y = odeint(diff_eq, y0, x, args).flatten()\n fig.add_trace(go.Scatter(x=x, y=y))\n return fig\n```\n\nThe slope field below should hopefully give you some idea for the fish population dynamics.\n\nNote that we use `arange` rather than `linspace` this week so that we can carefully control the increments between our grid points. `arange(0, 1.1, 0.25)` returns an array that starts with 0 and increments by 0.25 until it exceeds 1.1.\n\nThe plot also contains the solution curves for \n$y(0) = 1$ and $y(0) = 0.4$. Edit the cell to also include the solution curve for $y(0)=1.4$.\n\n\n```python\nx, y = meshgrid(arange(0, 1.1, 0.1), arange(-0.4, 1.41, 0.1))\nfig = create_slope_field(diff_eq, x, y, initial_values=(0.4, 1))\nfig.show('png')\n```\n\n### Equilibrium solutions\nLooking back to our differential equation, $\\mathrm{d}y/\\mathrm{d}t = 0$ when $y(t) = 0$ or $y(t) = 1$. Looking at the slope field, we see that the equilibrium solution $y(t) = 1$ is stable (this is the carrying capacity here, corresponding to 1000 fish), whereas the equilibrium solution $y(t) = 0$ is unstable. Any non-zero initial population will eventually stabilise at 1000 fish.\n\n### What will happen if harvesting is now commenced at a steady rate?\nFor the simplest harvesting model, assume that $H$ units (thousands) of fish are taken\ncontinuously (smoothly) over the year, rather than at one instant each year.\nNote that the units of $H$ are the same as those of $\\mathrm{d}y/\\mathrm{d}t$, thousands of fish per year, so we simply subtract $H$ from the RHS of our existing equation to give the DE with harvesting as\n\\begin{align}\n\\frac{\\mathrm{d}y}{\\mathrm{d}{t}} = 4y(1-y) - H.\n\\end{align}\nAgain, the (constant) equilibrium solutions are found by setting $\\mathrm{d}y/\\mathrm{d}t = 0$, giving from the quadratic formula (check this),\n\\begin{align}\ny(t) = \\frac{4\\pm\\sqrt{16-16H}}{8} = \\frac{1\\pm\\sqrt{1-H}}{2}.\n\\end{align}\nWhat happens after harvesting starts will depend on the equilibrium solutions, their\nstability and the initial number of fish $y(0)$.\n\nStart by redefining `diff_eq` to include the `H` parameter. Note that defining `diff_eq` again overides our original definition.\n\n\n```python\ndef diff_eq(y, x, H=0):\n return 4 * y * (1 - y) - H\n```\n\nNow set $H = 0.6$ and plot the slope field. This is done by setting `args=(0.6,)` when we call `create_slope_field`. This is exactly how you would pass additional arguments like this one to `odeint` if you were calling it directly.\n\n\n```python\nx, y = meshgrid(arange(0, 1.1, 0.1), arange(-0.4, 1.41, 0.1))\nfig = create_slope_field(diff_eq, x, y, args=(0.6,))\nfig.show('png')\n```\n\nFrom the solutions to the quadratic equation above, the equilibrium solutions of the DE are found to be $y(t) \\approx 0.184$ and $y(t) \\approx 0.816$. The previous equilibrium solution with no harvesting at $y(t) = 0$ has moved up to $y(t) \\approx 0.184$, while the previous equilibrium solution with no harvesting at $y(t) = 1$ has moved down to $y(t) \\approx 0.816$.\n\nFrom the slope field, we see that the equilibrium solution $y(t) \\approx 0.184$ is unstable, whereas the equilibrium solution $y(t) \\approx 0.816$ is stable. If the population ever falls below about 0.184, or 184 fish, it will then drop to 0. This is a new feature, introduced by harvesting.\n\nIn the cell below, use `create_slope_field` to experiment by plotting the solutions to the initial value problems $y(0)=0.183$ and $y(0)=0.25$. Extend the $x$ range of your slope field until the top line is close to equlibrium. Note that if you extend it too far you will break `odeint` (why?). You may also like to increase the increments in `arange` to make the plot clearer.\n\n\n```python\nx, y = meshgrid(arange(0, 2.1, 0.1), arange(-0.4, 1.41, 0.1))\nfig = create_slope_field(diff_eq, x, y, args=(0.6,), initial_values=(0.183, 0.25))\nfig.show('png')\n```\n\n## Exercises\n\nIn this lab you will experiment with the population dynamics given by the logistic equation with harvesting that we started analysing in the lab.\n\nThis week the questions will be a combination of plots and written answers.\n\n1. Assume that the harvest is 600 fish per year. **On the same figure,** \n a. plot the slope field, \n b. plot the equilibrium solutions that we found in above, and \n c. plot the solution curves for $y(0)=1$, $y(0)=0.3$, and $y(0)=0.15$.\n\n\n```python\nx, y = meshgrid(arange(0, 1.2, 0.1), arange(-0.4, 1.3, 0.1))\nfig = create_slope_field(diff_eq, x, y, args=(0.6,), initial_values=(1, 0.3, 0.15))\nfig.show('png')\n```\n\n1. d. In the cell below, describe the behaviour of the fish population for each of these five initial numbers of fish.\n\nIf the initial value is y(0) = 1, the popuplation falls towards the stable equilirium at approx 0.8.\nIf the initial value is y(0) = 0.3, then the population tends out of the unstable equilibrium at approximately 0.2 and towards a stable equilibrium f If our initial value is at y(0) = 0.15, at after 0.6 years the population will be about 0. It zooms off to negative infinity as time goes on.\n\n2. a. i. Assume that $H=0.8$. Plot the slope field and five solutions, one for each equilibrium solution and one for each region between, above, or below them. You can use the equation from the lab to calculate the equilibrium solutions.\n\n\n```python\nx, y = meshgrid(arange(0, 1.1, 0.05), arange(-0.4, 1.3, 0.05))\nfig = create_slope_field(diff_eq, x, y, args=(0.8,), initial_values=(1, 0.45, 0.2, 0.7236, 0.2764))\nfig.show('png')\n```\n\n2. a. ii. In the cell below, describe the limiting behaviour of each line.\n\nWe can see limiting behaviours for lines with initial values (1, 0.45 and 0.7236) is towards the stable equilibrium found at approx 0.7236 in infinity time. \n\nThe limiting behaviour of the line at point 0.2764 stays at this point.\n\nThe bottom line (initial value of 0.2) tends to negative infinity.\n\n2. b. i. Assume that $H=1$. Plot the slope field and three solutions for the equilibrium solution and the regions above and below it.\n\n\n```python\nx, y = meshgrid(arange(0, 1.1, 0.05), arange(-0.4, 1.41, 0.05))\nfig = create_slope_field(diff_eq, x, y, args=(1,), initial_values=(1, 0.46, 0.2764))\nfig.show('png')\n```\n\n2. b. ii. Describe the limiting behaviour of each line.\n\nInitial value of 1 declines and tends towards the equilibrium at approx. 0.46.\n\nFor any value below the equilibrium, it hits 0 and continues declining so it tends towards negative infinity.\n\n2. c. i. Assume that 𝐻=1.2. Plot the slope field and two or three solutions.\n\n\n```python\nx, y = meshgrid(arange(0, 1.1, 0.05), arange(-0.4, 1.41, 0.05))\nfig = create_slope_field(diff_eq, x, y, args=(1.2,), initial_values=(1, 0.4,))\nfig.show()\n```\n\n2. c. iii. Describe the limiting behaviour of the lines.\n\nThis situation demonstrates no critical points, the bottom line (initial value 0.4) will have a limiting behaviour that tends off to negative infinity.\n\nY will never become 0.\n\nThe fish population will always be declining. The species will inevitably die out.\n\n3. Summarize what happens to the equilibrium solutions and their stability as $H$\nis increased from 0 to beyond 1. Refer to your plots to support your answers.\n\nThe higher the H value the less equilibrium points exist. Beyond 1 there exists critical points so the populaiton will inevitably decline and remain declining to negative infinity. \n\n4. What is a reasonable strategy for sustainable fishing in this case?\nDon’t forget to allow qualitatively for minor catastrophes, such as disease or temporary overfishing.\n\nA sustainable amount of fish to remove from the environment would be around 500. \n\nWe have a margin of error of around 500 fish, and by taking 500 from the population we are approximately half way through this margin of error (so as to incorporate catastrophes/disease/temporary overfishing)\n", "meta": {"hexsha": "d1b07d3cf8c6086ed7027ee4081d38491d05ce1e", "size": 974745, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/lab-03.ipynb", "max_stars_repo_name": "JoshE117/mm-labs", "max_stars_repo_head_hexsha": "07558ee8dff76952a8afd6410419aaae2fffb893", "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": "notebooks/lab-03.ipynb", "max_issues_repo_name": "JoshE117/mm-labs", "max_issues_repo_head_hexsha": "07558ee8dff76952a8afd6410419aaae2fffb893", "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": "notebooks/lab-03.ipynb", "max_forks_repo_name": "JoshE117/mm-labs", "max_forks_repo_head_hexsha": "07558ee8dff76952a8afd6410419aaae2fffb893", "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": 74.2153951576, "max_line_length": 180678, "alphanum_fraction": 0.7715638449, "converted": true, "num_tokens": 2845, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096204605946, "lm_q2_score": 0.9314625041141347, "lm_q1q2_score": 0.853321761117275}} {"text": "# Linear Programming: Introduction\n\n## Definition\n\nFormally, a linear program is an optimzation problem of the form:\n\n\\begin{equation}\n\\min \\vec{c}^\\mathsf{T}\\vec x\\\\\n\\textrm{subject to} \\begin{cases}\n\\mathbf{A}\\vec x=\\vec b\\\\\n\\vec x\\ge\\vec 0\n\\end{cases}\n\\end{equation}\n\nwhere $\\vec c\\in\\mathbb R^n$, $\\vec b\\in\\mathbb R^m$ and $\\mathbf A \\in \\mathbb R^{m\\times n}$. The vector inequality $\\vec x\\ge\\vec 0$ means that each component of $\\vec x$ is nonnegative. Several variations of this problem are possible; eg. instead of minimizing, we can maximize, or the constraints may be in the form of inequalities, such as $\\mathbf A\\vec x\\ge \\vec b$ or $\\mathbf A\\vec x\\le\\vec b$. We shall see later, these variations can all be rewritten into the standard form. \n\n## Example\n\nA manufacturer produces four different products $X_1$, $X_2$, $X_3$ and $X_4$. There are three inputs to this production process:\n\n- labor in man weeks, \n- kilograms of raw material A, and \n- boxes of raw material B.\n\nEach product has different input requirements. In determining each week's production schedule, the manufacturer cannot use more than the available amounts of manpower and the two raw materials:\n\n|Inputs|$X_1$|$X_2$|$X_3$|$X_4$|Availabilities|\n|------|-----|-----|-----|-----|--------------|\n|Person-weeks|1|2|1|2|20|\n|Kilograms of material A|6|5|3|2|100|\n|Boxes of material B|3|4|9|12|75|\n|Production level|$x_1$|$x_2$|$x_3$|$x_4$| |\n\nThese constraints can be written in mathematical form\n\n\\begin{align}\nx_1+2x_2+x_3+2x_4\\le&20\\\\\n6x_1+5x_2+3x_3+2x_4\\le&100\\\\\n3x_1+4x_2+9x_3+12x_4\\le&75\n\\end{align}\n\nBecause negative production levels are not meaningful, we must impose the following nonnegativity constraints on the production levels:\n\n\\begin{equation}\nx_i\\ge0,\\qquad i=1,2,3,4\n\\end{equation}\n\nNow suppose that one unit of product $X_1$ sells for €6 and $X_2$, $X_3$ and $X_4$ sell for €4, €7 and €5, respectively. Then, the total revenue for any production decision $\\left(x_1,x_2,x_3,x_4\\right)$ is\n\n\\begin{equation}\nf\\left(x_1,x_2,x_3,x_4\\right)=6x_1+4x_2+7x_3+5x_4\n\\end{equation}\n\nThe problem is then to maximize $f$ subject to the given constraints.\n\n## Vector Notation\n\nUsing vector notation with\n\n\\begin{equation}\n\\vec x = \\begin{pmatrix}\nx_1\\\\x_2\\\\x_3\\\\x_4\n\\end{pmatrix}\n\\end{equation}\n\nthe problem can be written in the compact form\n\\begin{equation}\n\\max \n\\begin{pmatrix}6&4&7&5\\end{pmatrix}\n\\begin{pmatrix}\nx_1\\\\x_2\\\\x_3\\\\x_4\n\\end{pmatrix}\\\\\n\\textrm{subject to}\n\\begin{cases}\n\\begin{pmatrix}\n1&2&1&2\\\\\n6&5&3&2\\\\\n3&4&9&12\n\\end{pmatrix}\n\\begin{pmatrix}\nx_1\\\\x_2\\\\x_3\\\\x_4\n\\end{pmatrix}\\le\n\\begin{pmatrix}\n20\\\\100\\\\75\n\\end{pmatrix}\\\\\n\\begin{pmatrix}\nx_1\\\\x_2\\\\x_3\\\\x_4\n\\end{pmatrix}\\ge\n\\begin{pmatrix}\n0\\\\0\\\\0\\\\0\n\\end{pmatrix}\n\\end{cases}\n\\end{equation}\n\n## Two-dimensional Linear Program\n\nMany fundamental concepts of linear programming are easily illustrated in two-dimensional space.\n\nConsider the following linear program:\n\n\\begin{equation}\n\\max\n\\begin{pmatrix}\n1&5\n\\end{pmatrix}\n\\begin{pmatrix}\nx_1\\\\\nx_2\n\\end{pmatrix}\\\\\n\\textrm{subject to}\n\\begin{cases}\n\\begin{pmatrix}\n5&6\\\\\n3&2\n\\end{pmatrix}\n\\begin{pmatrix}\nx_1\\\\\nx_2\n\\end{pmatrix}\\le\n\\begin{pmatrix}\n30\\\\\n12\n\\end{pmatrix}\\\\\n\\begin{pmatrix}\nx_1\\\\\nx_2\n\\end{pmatrix}\\ge\n\\begin{pmatrix}\n0\\\\\n0\n\\end{pmatrix}\n\\end{cases}\n\\end{equation}\n\n\n```julia\n#using Pkg\n#pkg\"add LaTeXStrings\"\n\nusing Plots\nusing LaTeXStrings\n\nx = -2:6\nplot(x, (30 .- 5 .* x) ./ 6, linestyle=:dash, label=L\"5x_1+6x_2=30\")\nplot!(x, (12 .- 3 .* x) ./ 2, linestyle=:dash, label=L\"3x_1+2x_2=12\")\nplot!([0,4,1.5,0,0],[0,0,3.75,5,0], linewidth=2, label=\"constraints\")\nplot!(x, -x ./ 5, label=L\"f\\left(x_1,x_2\\right)=x_1+5x_2=0\")\nplot!(x, (25 .- x) ./ 5, label=L\"f\\left(x_1,x_2\\right)=x_1+5x_2=25\")\n```\n\n## Slack Variables\n\nTheorems and solution techniques are usually stated for problems in standard form. other forms of linear programs can be converted as the standard form. If a linear program is in the form\n\n\\begin{equation}\n\\min \\vec{c}^\\mathsf{T}\\vec x\\\\\n\\textrm{subject to} \\begin{cases}\n\\mathbf{A}\\vec x\\ge \\vec b\\\\\n\\vec x\\ge\\vec 0\n\\end{cases}\n\\end{equation}\n\nthen by introducing _surplus variables_, we can convert the orginal problem into the standard form\n\n\\begin{equation}\n\\min \\vec{c}^\\mathsf{T}\\vec x\\\\\n\\textrm{subject to} \\begin{cases}\n\\mathbf{A}\\vec x-\\mathbf I\\vec y = \\vec b\\\\\n\\vec x\\ge\\vec 0\\\\\n\\vec y\\ge\\vec 0\n\\end{cases}\n\\end{equation}\n\nwhere $\\mathbf I$ is the $m\\times m$ identity matrix.\n\nIf, on the other hand, the constraints have the form\n\\begin{equation}\n\\begin{cases}\n\\mathbf{A}\\vec x\\le b\\\\\n\\vec x\\ge\\vec 0\n\\end{cases}\n\\end{equation}\n\nthen we introduce the _slack variables_ to convert the constraints into the form\n\n\\begin{equation}\n\\begin{cases}\n\\mathbf{A}\\vec x+\\mathbf I\\vec y = \\vec b\\\\\n\\vec x\\ge\\vec 0\\\\\n\\vec y\\ge\\vec 0\n\\end{cases}\n\\end{equation}\n\nConsider the following optimization problem\n\n\\begin{equation}\n\\max x_2-x_1\\\\\n\\textrm{subject to}\n\\begin{cases}\n3x_1=x_2-5\\\\\n\\left|x_2\\right|\\le2\\\\\nx_1\\le0\n\\end{cases}\n\\end{equation}\n\nTo convert the problem into a standard form, we perform the following steps:\n\n1. Change the objective function to:\n\n\\begin{equation}\n\\min x_1 - x_2\n\\end{equation}\n\n2. Substitute $x_1=-x_1^\\prime$.\n\n3. Write $\\left|x_2\\right|\\le2$ as $x_2\\le 2$ and $-x_2\\le 2$.\n\n4. Introduce slack variables $y_1$ and $y_2$, and convert the inequalities above to\n\n\\begin{cases}\n\\hphantom{-}x_2 + y_1 =2\\\\\n-x_2+y_2 =2\n\\end{cases}\n\n5. Write $x_2=u-v$ with $u,v\\ge0$.\n\nHence, we obtain\n\n\\begin{equation}\n\\min -x_1^\\prime-u+v\\\\\n\\textrm{subject to}\n\\begin{cases}\n3x_1^\\prime+u-v=5\\\\\nu-v+y_1=2\\\\\nv-u+y_2=2\\\\\nx_1^\\prime,u,v,y_1,y_2\\ge0\n\\end{cases}\n\\end{equation}\n\n## Fundamental Theorem of Linear Programming\n\nWe consider the system of equalities\n\n\\begin{equation}\n\\mathbf{A}\\vec x=\\vec b\n\\end{equation}\n\nwhere $\\mathrm{rank}\\,\\mathbf A=m$.\n\nLet $\\mathbf B$ a square matrix whose columns are $m$ linearly independent columns of $\\mathbf A$. If necessary, we reorder the columns of $\\mathbf A$ so that the columns in $\\mathbf B$ appear first: $\\mathbf A$ has the form $\\left(\\mathbf B |\\mathbf N\\right)$.\n\nThe matrix is nonsingular, and thus we can solve the equation\n\n\\begin{equation}\n\\mathbf B\\vec x_\\mathbf B = \\vec b\n\\end{equation}\n\nThe solution is $\\vec x_\\mathbf B = \\mathbf B^{-1}\\vec b$.\n\nLet $\\vec x$ be the vector whose first $m$ components are equal to $\\vec x_\\mathbf B$ and the remaining components are equal to zero. Then $\\vec x$ is a solution to $\\mathbf A\\vec x=\\vec b$. We call $\\vec x$ a _basic solution_. Its components refering to the the components of $\\vec x_\\mathbf B$ are called _basic variables_.\n\n- If some of the basic variables are zero, then the basic solution is _degenerate_.\n- A vector $\\vec x$ satisfying $\\mathbf A\\vec x=\\vec b$, $\\vec x \\ge \\vec 0$, is said to be a _feasible solution_.\n- A feasible solution that is also basic is called a _basic feasible solution_.\n\nThe fundamental theorem of linear programming states that when solving a linear programming problem, we need only consider basic feasible solutions. This is because the optimal value (if it exists) is always achieved at a basic solution.\n", "meta": {"hexsha": "162d7466e9ef9f19b55cae7e80719ed031028d97", "size": 10683, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Lectures_old/Lecture 5.ipynb", "max_stars_repo_name": "BenLauwens/ES313.jl", "max_stars_repo_head_hexsha": "5a7553e53c288834f768d26e0d5aa22f9062b6af", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2018-12-17T16:00:26.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-18T04:09:25.000Z", "max_issues_repo_path": "Lectures_old/Lecture 5.ipynb", "max_issues_repo_name": "BenLauwens/ES313", "max_issues_repo_head_hexsha": "5a7553e53c288834f768d26e0d5aa22f9062b6af", "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_old/Lecture 5.ipynb", "max_forks_repo_name": "BenLauwens/ES313", "max_forks_repo_head_hexsha": "5a7553e53c288834f768d26e0d5aa22f9062b6af", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-08-27T13:41:05.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T11:00:53.000Z", "avg_line_length": 32.7699386503, "max_line_length": 516, "alphanum_fraction": 0.5363661893, "converted": true, "num_tokens": 2543, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850039701653, "lm_q2_score": 0.9111797033789887, "lm_q1q2_score": 0.8531238921957305}} {"text": "# Fun with continued fractions and Taylor approximations\n\nA Taylor series of a function is kind of like a decimal representation of a real number, where instead of base 10 we use \"base x\" to represent functions of x.\n\nWhat happens if we replace \"decimal representation\" with \"[continued fraction](https://en.wikipedia.org/wiki/Continued_fraction) representation\"?\n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\n%matplotlib inline\n```\n\nSay we want to approximate y = log(1 + x) near x = 0. Here's a graph of this function:\n\n\n```python\nx = np.linspace(-0.5, 0.5)\ny = np.log1p(x)\n\nplt.plot(x, y)\nplt.axhline(0, color='black')\nplt.axvline(0, color='black')\n```\n\nOur first order approximation is y = x. This matches the slope and intercept at x = 0:\n\n\n```python\nplt.plot(x, y)\nplt.plot(x, x)\nplt.axhline(0, color='black')\nplt.axvline(0, color='black')\n```\n\nSuppose now we want more terms in the Taylor approximation. We could take derivatives and plug it into the general formula but here's a more heuristic approach (which we will modify later).\n\nIf $ y \\approx x $, then $ y/x \\approx 1 $. Define $z_1 = y/x$ and plot it as a function of x. We find that we can get a better approximation for $z_1$ by matching *its* slope at x = 0:\n\n\n```python\nplt.plot(x, y/x)\nplt.plot(x, 1 - x/2)\nplt.axvline(0, color='black')\n```\n\nWorking backward this gives us a second order Taylor approximation.\n\n$$ \\begin{align}\ny/x &= z_1 \\approx 1 - x/2 \\\\\ny &= xz_1 \\\\\ny &\\approx x(1 - x/2) \\\\\n&\\approx x - x^2/2\n\\end{align} $$\n\n\n```python\nplt.plot(x, y)\nplt.plot(x, x - x*x/2)\nplt.axhline(0, color='black')\nplt.axvline(0, color='black')\n```\n\nWe can keep going to get the third term.\n\n$$ \\begin{align}\ny &\\approx x + x^2(-1/2) \\\\\ny &= x + x^2 z_2 \\\\\ny/x &= 1 + xz_2 \\\\\ny/x - 1 &= xz_2 \\\\\n(y/x - 1)/x &= z_2\n\\end{align} $$\n\nso we plot (y/x - 1)/x and once again match its slope\n\n\n```python\nplt.plot(x, (y/x-1)/x)\nplt.plot(x, -1/2 + x/3)\nplt.axvline(0, color='black')\n```\n\nand plug it back in to get the third order Taylor expansion\n\n$$ \\begin{align}\ny &= x + x^2 z_2 \\\\\ny &\\approx x + x^2 (-1/2 + x/3) \\\\\n&= x - x^2/2 + x^3/3\n\\end{align} $$\n\n\n```python\nplt.plot(x, y)\nplt.plot(x, x - x*x/2 + x*x*x/3)\nplt.axhline(0, color='black')\nplt.axvline(0, color='black')\n```\n\nAnd we can keep going like this to get more and more terms in the Taylor series.\n\nTo summarize what we've been doing so far:\n\n* Approximate a function as constant + linear in x\n* Subtract out the constant and divide what's left by x, to get something approximately constant\n* Replace \"constant\" with \"constant + linear\" and repeat\n\n## Enter continued fractions\n\nNow to this basic procedure we're going to make one change:\n\n* Approximate a function as constant + linear in x\n* Subtract out the constant and **divide x by what's left**, to get something approximately constant\n* Replace \"constant\" with \"constant + linear\" and repeat\n\nThis is inspired by continued fractions as it's analogous to how you would generate a continued fraction expansion for a real number.\n\nLet's see what happens when we apply the modified procedure to our function from before. In the first step we have $y \\approx x$. Last time we went from this to $y = xz_1$, now let's do $y = x/z_1$ and plot $z_1 = x/y$:\n\n\n```python\nplt.plot(x, x/y)\nplt.plot(x, 1 + x/2)\nplt.axvline(0, color='black')\n```\n\nWe can approximate $z_1$ better with 1 + x/2. So\n\n$$ \\begin{align}\ny &= x/z_1 \\\\\ny &\\approx x/(1 + x/2)\n\\end{align} $$\n\nAnd that's our second order continued fraction approximation!\n\n\n```python\nplt.plot(x, y)\nplt.plot(x, x/(1 + x/2))\nplt.axhline(0, color='black')\nplt.axvline(0, color='black')\n```\n\nContinuing,\n\n$$ \\begin{align}\ny &\\approx x/(1 + x/2) \\\\\ny &= x/(1 + x/z_2) \\\\\nx/y &= 1 + x/z_2 \\\\\nx/y - 1 &= x/z_2 \\\\\nx/(x/y - 1) &= z_2\n\\end{align} $$\n\nso we plot and approximate x/(x/y - 1)\n\n\n```python\nplt.plot(x, x/(x/y - 1))\nplt.plot(x, 2 + x/3)\nplt.axvline(0, color='black')\n```\n\nand plug it back in to get the third order continued fraction approximation\n\n$$ \\begin{align}\ny &= x/(1 + x/z_2) \\\\\ny &\\approx x/(1 + x/(2 + x/3))\n\\end{align} $$\n\n\n```python\nplt.plot(x, y)\nplt.plot(x, x/(1 + x/(2 + x/3)))\nplt.axhline(0, color='black')\nplt.axvline(0, color='black')\n```\n\nIt seems to work pretty well! I don't have a proof of convergence or anything, but for this example, it seems to produce better approximations than the same order Taylor series.\n\nHere's a bigger plot of the second order Taylor and continued fraction approximations, together:\n\n\n```python\nplt.figure(figsize=(15, 10))\nplt.plot(x, x - x*x/2, color='#ff7f00', label=\"2nd order Taylor approximation\")\nplt.plot(x, x/(1 + x/2), color='#00cc00', label=\"2nd order continued fraction approximation\")\nplt.plot(x, y, label=\"y = ln(1 + x)\")\nplt.axhline(0, color='black')\nplt.axvline(0, color='black')\nplt.legend()\n```\n\nAnd the relative error of the second order and third order approximations. In both cases, continued fraction (green) beats Taylor expansion (orange).\n\n\n```python\nx = np.linspace(-0.5, 0.5, 200)\ny = np.log1p(x)\n\nplt.figure(figsize=(15, 10))\nplt.plot(x, np.abs((x - x*x/2)/y-1), color='#ff7f00', label=\"2nd order Taylor approximation\")\nplt.plot(x, np.abs((x/(1 + x/2))/y-1), color='#00cc00', label=\"2nd order continued fraction approximation\")\nplt.ylabel('relative error')\nplt.yscale('log')\nplt.axhline(0, color='black')\nplt.axvline(0, color='black')\nplt.legend()\n\nplt.figure(figsize=(15, 10))\nplt.plot(x, np.abs((x - x*x/2 + x*x*x/3)/y-1), color='#ff7f00', label=\"3rd order Taylor approximation\")\nplt.plot(x, np.abs((x/(1 + x/(2 + x/3)))/y-1), color='#00cc00', label=\"3rd order continued fraction approximation\")\nplt.ylabel('relative error')\nplt.yscale('log')\nplt.axhline(0, color='black')\nplt.axvline(0, color='black')\nplt.legend()\n```\n\nWe can do this for other functions too! Here's y = e^x\n\n\n```python\nx = np.linspace(-1, 1)\ny = np.exp(x)\nplt.figure(figsize=(15, 10))\nplt.plot(x, y, label=\"y = e^x\")\nplt.plot(x, 1 + x/(1 - x/2), label=\"2nd order continued fraction approximation\")\nplt.plot(x, 1 + x/(1 - x/(2 + x/3)), label=\"3rd order continued fraction approximation\")\nplt.axvline(0, color='black')\nplt.legend()\n```\n\nAnd y = sin(x)\n\n\n```python\nx = np.linspace(-2, 2)\ny = np.sin(x)\nplt.figure(figsize=(15, 10))\nplt.plot(x, y, label=\"y = sin(x)\")\nplt.plot(x, x, label=\"1st order Taylor (or continued fraction) approximation\")\nplt.plot(x, x/(1 + x*x/6), label=\"3rd order continued fraction approximation\")\nplt.axvline(0, color='black')\nplt.legend()\n```\n\nIn the case of y = sin(x), this seems to be worse than the same order Taylor approximation. Is there a theory for when this method does well?\n\nI searched for information about this and I came across [Padé approximant](https://en.wikipedia.org/wiki/Pad%C3%A9_approximant). Does the procedure I've described compute a Padé approximant?\n", "meta": {"hexsha": "7c6e467e9afbbac38d80c78e3bae46e885092e28", "size": 403917, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "2018-06-28 continued rational function approximations.ipynb", "max_stars_repo_name": "luanthe/notebooks", "max_stars_repo_head_hexsha": "7653f7c6310ac994596945e70dc36ff26066f74e", "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": "2018-06-28 continued rational function approximations.ipynb", "max_issues_repo_name": "luanthe/notebooks", "max_issues_repo_head_hexsha": "7653f7c6310ac994596945e70dc36ff26066f74e", "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": "2018-06-28 continued rational function approximations.ipynb", "max_forks_repo_name": "luanthe/notebooks", "max_forks_repo_head_hexsha": "7653f7c6310ac994596945e70dc36ff26066f74e", "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.0699588477, "max_line_length": 55216, "alphanum_fraction": 0.9459790006, "converted": true, "num_tokens": 2116, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850057480346, "lm_q2_score": 0.9111797003640646, "lm_q1q2_score": 0.8531238909928607}} {"text": "## The vanilla RBM.\n\n * weights $W_{ji}$ means the weight between the j-th hidden unit and the i-th visible unit.\n * $W_{0i}$ is \"bias\" into the i-th visible unit. \n * $W_{j0}$ is \"bias\" into the j-th hidden unit. \nThe joint probability under the RBM factorisation is:\n$$ P^\\star(h,v) = \\prod_i \\prod_j e^{h_j W_{ji} v_i} \\;\\; \\times \\;\\; \\prod_{i^\\prime} e^{W_{0i^\\prime} v_{i^\\prime}} \\;\\; \\times \\;\\; \\prod_{j^\\prime} e^{W_{j^\\prime 0} h_{j^\\prime}} $$\nand its logarithm is\n$$ \\log P^\\star(h,v) = \\sum_i \\sum_j h_j W_{ji} v_i \\;\\; + \\;\\; \\sum_i W_{0i} v_i \\;\\; + \\;\\; \\sum_j W_{j0} h_j $$\n\n## Gibbs in vanilla RBM\nTo sample from this distribution we can figure out the Gibbs update step. \n\nThe probability $p(h_j=1|v)$ that the j-th hidden unit generates a 1 can be written as $ \\sigma(\\psi_j) $ with $\\sigma(x)=1/(1+e^{-x})$ and $\\psi_j = \\log P^*(h,v | h_j =1 ) - \\log P^*(h,v | h_j = 0)$. \nAnd from the $\\log P^\\star(h,v)$ given above, this is easily seen to be\n$ \\psi_j(v) = \\sum_i W_{ji} v_i + W_{j0}$\n\nSimilarly, for the visible units the probability $p(v_i=1|h)$ that the i-th visible generates a 1 can be written as \n$\\sigma(\\phi_i(h)) $ with $\\phi_i(h) = \\log P^*(h,v | v_i =1 ) - \\log P^*(h,v | v_i = 0)$. \nAnd similarly this can be seen to be\n$ \\phi_i(h) = \\sum_j W_{ji} h_j + W_{0i}$ for the i-th visible unit.\n\n\nFor convenience we will sometimes write $\\sigma(\\phi_i(h))$ as just $\\sigma_i(h)$.\n\n## Gibbs in an equivalent network\n\nNote this is equivalent to a 3 layer network in which the top 2 layers form an RBM and the lower one is a sigmoid belief network. \nSampling from the latter model involves drawing Bernoulli variables repeatedly (eg. via alternating Gibbs sampling) from the RBM until equilibrium and then sampling $v$ from the visibles given the hiddens $h$, ie. \"ancestral sampling\" in the belief net, but from an $h$ generated by an RBM. \n\nWe know (from above) how to generate the $h$ sample: Gibbs sampling from the RBM will do it. Then, the conditional probability of $v$ under a sigmoid belief net is (by definition) $p(v_i=1|h) = \\sigma_i(h)$. \nThus _Gibbs sampling from a simple RBM ending in a sample for $v$ is the same as sampling $h$ from the same RBM and then using a sigmoid belief net for the last step_. \n\nHowever, there's another way to draw such samples. Write (product rule) $\\log P^\\star(h,v) = \\log P^\\star(h) + \\log P(v|h)$. We have the second term already:\n$$ \\log P(v|h) = \\sum_i v_i \\log \\sigma_i(h) + (1-v_i) \\log (1 - \\sigma_i(h)$$\n\nTo find $P^\\star(h)$ we need to marginalise that joint over all $\\mathbf{v}$ configurations:\n$$\\begin{align} P^\\star(h) &= \\sum_{v_1=0}^1 \\cdots \\sum_{v_n=0}^1 \\exp \\bigg[ \\log P^{\\star}(h,v) \\bigg] \\\\\n&= \\sum_{v_1=0}^1 \\cdots \\sum_{v_n=0}^1 \\exp \\bigg[ \\sum_i \\sum_j h_j W_{ji} v_i \\;\\; + \\;\\; \\sum_i W_{0i} v_i \\;\\; + \\;\\; \\sum_j W_{j0} h_j \\bigg] \\\\\n&= \\sum_{v_1=0}^1 \\cdots \\sum_{v_n=0}^1 \\exp \\bigg[ \\sum_i v_i \\phi_i(h) \\;\\; + \\;\\; \\sum_j W_{j0} h_j \\bigg] \\\\\n\\text{where } \\phi_i(h) &= \\sum_j W_{ji} h_j + W_{0i} \\\\\n&= \\exp\\left[ \\sum_j h_j W_{j0} \\right] \\;\\; \\times \\sum_{v_1=0}^1 \\cdots \\sum_{v_n=0}^1 \\prod_i \\exp\\bigg[ v_i \\phi_i(h) \\bigg] \\\\\n&= \\exp\\left[\\sum_j h_j W_{j0}\\right] \\;\\; \\times \\prod_i \\bigg( 1 + e^{\\phi_i(h) } \\bigg) \\\\\n\\text{and so}\n\\log P^\\star(h) &= \\sum_j h_j W_{j0} \\;\\; + \\sum_i \\log \\bigg( 1 + e^{\\phi_i(h) } \\bigg)\n\\\\\n&= \\sum_j h_j W_{j0} \\;\\; + \\; \\sum_i \\phi_i(h) \\; - \\; \\sum_i \\log \\sigma_i(h) \n\\end{align} $$\n\nSo far we've figured out $\\log P^\\star(h)$ for the RBM that is the \"top layer\".\n\nTherefore another way to write $\\log P^\\star(h,v)$ is\n$$ \n\\log P^\\star(h,v) = \\underbrace{\\sum_j h_j W_{j0} \\;\\; + \\; \\sum_i \\phi_i(h) \\; - \\; \\sum_i \\log \\sigma_i(h)}_{\\log P^\\star(h)} \\;\\;+\\;\\; \\underbrace{\\sum_i v_i \\log \\sigma_i(h) + (1-v_i) \\log (1 - \\sigma_i(h))}_{\\log P(v \\mid h)} \n$$\nBy collecting terms and simplifying one can readily those that this matches the earlier form.\n\n# a model of two causes\n\nNow we'd like to change this slightly, so that 2 RBMs that are independent are used to model two causes, which are then combined at the last moment via a sigmoid belief net to form $v$.\nSuppose that at a given moment the 2nd RBM is in a state which contributes an extra activation $\\epsilon_i$ respectively to each of the visible units. We're interested in how this will affect the Gibbs updates to the hidden units $h$ in the first RBM.\n\nNote: $\\epsilon_i$ is in general going to be a weighted sum of inputs from the second RBM's hidden layer, _plus a new bias_ arising from the second RBM. Although the two biases both going into the visible units seems (and might be) redundant, in the generative model it seems sensible that visible activations under the two \"causes\" would have different background rates if taken separately (ie. different biases). So for now I think we should leave them in, but maybe hope to eliminate / merge if possible in future, if it helps anything...\n\nBefore going on to the Gibbs Sampler version in which visible units are clampled, consider \"ancestral\" sampling from the model: each RBM independently does alternating Gibbs Sampling for a (longish) period, and then both combine to generate a sample $v$ vector, by adding both their weighted sums ($\\phi$) _and adding in both their visible biases too_ . That's a much more efficient way to do the \"sleep\" phase than doing what follows (which is mandatory for the \"wake\" phase samples however).\n\nThe Gibbs update step is given by $p_j = \\sigma(\\phi_j) $ with \n$ \\psi_j = \\log P^*(h,v ; h_j =1 ) - \\log P^*(h,v ; h_j = 0)$.\nHowever this time we don't have exact correspondence with an RBM because only the final step involves $\\epsilon$, not the reverberations in the RBM above it that generates $h$. So it's not enough to consider just the RBM alone, with it's joint being just the product of factors in the first line of math above. We need to incorporate the last step explicitly, with its slight difference in the form of $\\epsilon$. We know the joint decomposes into this:\n$$ \\log P^* (h,v) = \\log P^*(h) + \\log P(v|h)$$\nwhere the first term is the vanilla RBM probability but the second is the final layer's probability, now given by\n$$ \\log P(v|h,\\epsilon) = \\sum_i v_i \\log \\sigma (\\phi_i(h) + \\epsilon_i) + (1-v_i) \\log (1 - \\sigma(\\phi_i(h) + \\epsilon_i)$$ \n\nTo carry out Gibbs sampling in the hidden layer of this architecture we need to calculate $\\psi_j = \\log P^*(h,v ; h_j =1 ) - \\log P^*(h,v ; h_j = 0)$. Using the fact that $\\phi_i(h ; h_j=1) = \\phi_i(h ; h_j=0) + W_{ji}$, and abbreviating $\\phi_i(h ; h_j=0)$ to $\\phi_i^0$, we obtain\n\n$$\\psi_j = \\sum_i v_i \\log \\left( \\frac{1+ e^{-\\phi_i^0 - \\epsilon_i}}{1+e^{-\\phi_i^0 - W_{ji} -\\epsilon_i}} \\frac{1+ e^{\\phi_i^0 + W_{ji} + \\epsilon}}{1+e^{\\phi_i^0 + \\epsilon_i}}\\right) \\;\\;+ \\;\\;\\sum_i \\log \\left(\\frac{1+e^{\\phi_i^0 + W_{ji}}}{1+ e^{\\phi_i^0}}\n\\frac{1+e^{\\phi_i^0 + \\epsilon_i}}{1+ e^{\\phi_i^0 + W_{ji} + \\epsilon_i}} \\right)$$\n\nNow $\\phi = \\log \\frac{1+e^{\\phi}}{1+e^{-\\phi}}$ (Marcus' magic identity), which is$ = \\log \\frac{\\sigma(\\phi)}{\\sigma(-\\phi)}$.\nSo the first term simplifies to\n$ \\sum_i v_i W_{ji}$, which is the same as that in a \"vanilla RBM\".\n\nThe second term can also be simplified, using the identity $\\log(1-\\sigma(\\phi)) = \\phi - \\log(1+e^\\phi)$.\n\nThis leads to the following Gibbs Sampler probability of the j-th hidden unit being 1: $p_j = \\sigma(\\psi_j)$ with\n\n$$\\psi_j = \\sum_i (W_{ji} v_i + C_{ji}) $$\nwhere\n$$C_{ji} \\; = \\;\\log \\bigg[ \\frac{\\sigma (\\phi_i^0)}{\\sigma (\\phi_i^0 + W_{ji})} . \\frac{\\sigma (\\phi_i^0 + W_{ji} + \\epsilon_i) }{\\sigma (\\phi_i^0 + \\epsilon_i)} \\bigg] $$\n\nNote that $\\sum_i C_{ji}$ can be thought of as correction to vanilla RBM Gibbs \"input\" to the hidden node. Weirdly, $v$ plays no role in the $C$ term!\n\nWritten another way this is\n$$C_{ji} = \\log \\sigma(\\phi_i^0) \\; +\\log \\sigma (\\phi_i^0 + W_{ji} + \\epsilon_i) \\;- \\log \\sigma (\\phi_i^0 + W_{ji}) \\;- \\log \\sigma ( \\phi_i^0 + \\epsilon _i) $$\n\nIt is clear that adding the single $\\epsilon$ has introduced a dependency between the whole of $h$, which is a worry.\n\n1) What happens if $\\epsilon$ feeds into $u$ as well?\n2) How coupled is it really?\n3) Can we just hack it?\n a) Conditionals on the size of $\\phi$, $\\epsilon$\n b) Truncated Markov chain\n4) Linear RBM\n5) Is any hidden node coupling bad?\n6) How to interpret as Blind Source Separation\n\n## What does the correction to standard RBM $\\psi$ look like?\n\nThought: the \"correction\" is all hinge functions and should have an approximation as \"if../else..\" piecewise linear regimes, and this ought to have an intuitive hand-wave type explanation that makes sense.\n\nSo let's plot the correction contours on axes $\\epsilon_i$ versus $\\phi_i$, for (say) a positive $w_{ij}$.\nWe'll need two plots for the two cases $h_i=0,1$\n\n\n```python\n%matplotlib inline \nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.cm as cm\nimport numpy.random as rng\nnp.set_printoptions(precision = 2)\nplt.rcParams['figure.figsize'] = (10.0, 8.0)\nplt.rcParams['image.interpolation'] = 'nearest'\nplt.rcParams['image.cmap'] = 'gray'\n\ndef sigmoid(x):\n return 1.0/(1.0 + np.exp(-x))\n\ndef calc_psi_correction(phi, eps, w,h):\n # note here the Phi is the full weighted sum into the visible node. We're explicitly taking care of the hidden activation too. \n correction = np.log(sigmoid(phi+w+eps-h*w)) + np.log( sigmoid(phi-h*w)) - np.log( sigmoid(phi+w-h*w)) - np.log( sigmoid(phi+eps-h*w)) \n return correction\n\ndef calc_psi0_correction(phi0, eps, w):\n # note here the phi0 is what the weighted sum into the visible node WOULD be IF h=0. \n correction = np.log(sigmoid(phi0+w+eps)) + np.log( sigmoid(phi0)) - np.log( sigmoid(phi0+w)) - np.log( sigmoid(phi0+eps)) \n return correction\n\nreach = 40\nphi, eps = np.mgrid[-reach:reach:100j, -reach:reach:100j]\nwgt = 3.0\nlevels = np.arange(-abs(wgt)-0.5, abs(wgt)+0.5, abs(wgt)/10.)\ncmap = cm.RdYlGn\n\nplt.subplot(121)\npsi_correction_h0 = calc_psi_correction(phi, eps, wgt, 0)\nC = plt.contourf(phi, eps, psi_correction_h0, levels, origin='lower', cmap=cm.get_cmap(cmap, len(levels)-1))\n#plt.colorbar()\n#plt.title('$h_j=0$')\nplt.xlabel('$\\phi_i$ (left network)')\nplt.ylabel('$\\phi_i$ (right network)')\nplt.plot([0,0], [-reach, reach],'-k', [-reach, reach], [0,0], '-k', [-reach, reach], [reach,-reach], '-k')\nplt.axis([-reach, reach, -reach, reach])\nplt.axis('off')\nplt.axis('equal')\nplt.xticks([-reach/2,reach/2])\nplt.yticks([-reach/2,reach/2])\n\nplt.subplot(122)\npsi_correction_h0 = calc_psi_correction(phi, eps, wgt, 1)\n#plt.title('$h_j=1$')\nC = plt.contourf(phi, eps, psi_correction_h0, levels, origin='lower', cmap=cm.get_cmap(cmap, len(levels)-1))\nplt.plot([0,0], [-reach, reach],'-k', [-reach, reach], [0,0], '-k', [-reach, reach], [reach,-reach], '-k')\nplt.axis('off')\nplt.axis('equal')\nplt.xticks([-reach/2,reach/2])\nplt.yticks([-reach/2,reach/2])\n\nplt.savefig('correction.png', dpi=200)\n```\n\n\n```python\ndef calc_APPROX_psi_correction(phi, eps, w, h):\n # note here the Phi is the full weighted sum into the visible node. We're explicitly taking care of the hidden activation too. \n correction = np.log(sigmoid(phi+w+eps-h*w)) + np.log( sigmoid(phi-h*w)) - np.log( sigmoid(phi+w-h*w)) - np.log( sigmoid(phi+eps-h*w)) \n return correction\n\nplt.subplot(121)\npsi_correction_h0 = calc_APPROX_psi_correction(phi, eps, wgt, 0)\nC = plt.contourf(phi, eps, psi_correction_h0, levels, origin='lower', cmap=cm.get_cmap(cmap, len(levels)-1))\n#plt.colorbar()\n#plt.title('$h_j=0$')\nplt.xlabel('$\\phi_i$ (left network)')\nplt.ylabel('$\\phi_i$ (right network)')\nplt.plot([0,0], [-reach, reach],'-k', [-reach, reach], [0,0], '-k', [-reach, reach], [reach,-reach], '-k')\nplt.axis([-reach, reach, -reach, reach])\nplt.axis('off')\nplt.axis('equal')\nplt.xticks([-reach/2,reach/2])\nplt.yticks([-reach/2,reach/2])\n\nplt.subplot(122)\npsi_correction_h0 = calc_psi_correction(phi, eps, wgt, 1)\n#plt.title('$h_j=1$')\nC = plt.contourf(phi, eps, psi_correction_h0, levels, origin='lower', cmap=cm.get_cmap(cmap, len(levels)-1))\nplt.plot([0,0], [-reach, reach],'-k', [-reach, reach], [0,0], '-k', [-reach, reach], [reach,-reach], '-k')\nplt.axis('off')\nplt.axis('equal')\nplt.xticks([-reach/2,reach/2])\nplt.yticks([-reach/2,reach/2])\n\nplt.savefig('correction.png', dpi=200)\n```\n\n# Approximations (trying to find a simple one)\nWithin its \"wedges\" the correction is pretty much flat, so an approximation is just to compute true/false on the appropriate condition. The red section is where v is ON under full input from both nets, but would be OFF if it were the first alone. It's fairly closely approximated by $\\sigma(\\phi+\\epsilon) (1-\\sigma(\\phi))$. And under this condition we SUBTRACT the weight from $\\psi$. Similarly the green section is where it's very likely that v is OFF under full input, but would be ON if it were the first alone. Close approx to this is $(1-\\sigma(\\phi+\\epsilon)) \\sigma(\\phi)$. And in this case we'd ADD in the weight to $\\psi$.\n\nPutting the green and red bits together, maybe a good approximation to the correction is just going to be something like\n$$ C_{ji} = -W_{ji} \\bigg[\\sigma_{\\phi+\\epsilon} (1-\\sigma_{\\phi}) - (1-\\sigma_{\\phi+\\epsilon}) \\sigma_{\\phi} \\bigg] $$\nwhere hopefully the notation is obvious. But it gets better: that's actually just\n$$ C_{ji} = W_{ji} \\bigg[\\sigma_{\\phi}- \\sigma_{\\phi+\\epsilon} \\bigg]$$\n\nAnd a nice feature of this is that it's just a multiplication by $W$, just like the vanilla part was, which means our correction can be thought of as equivalently a correction to $v_i$, the activity of the visible unit.\n\n## A better approximation\nThe true correction is composed of the sum of two terms of form $\\log(\\sigma(\\phi)/\\sigma(\\phi+W))$.\n\nThe first term is exactly $\\log(\\sigma(\\phi)/\\sigma(\\phi+W))$, which goes from being $-W$ at $\\phi=-\\infty$ to $0$ at $\\phi=+\\infty$. The second term is $\\log(\\sigma(\\phi+\\epsilon+W)/\\sigma(\\phi+\\epsilon))$, which goes from being $W$ at $\\phi=-\\infty$ to $0$ at $\\phi=+\\infty$.\n\nEach of these is \"roughly sigmoid\", so my approximation is going to use a sigmoid in its place.\nFocussing on the 1st term, the best sigmoid has it's \"switching point\" at $\\phi = -W/2$.\nIt should also have a \"gain\" of $\\alpha = (4/W)*(2\\sigma(W/2)-1)$ if you want its slope at the switching point to match that of the true correction.\n\nThe 2nd term has switching point at $\\phi^A = -\\phi^B - W/2$, and so the whole approximation is \n$$\n\\tilde{C} = W \\bigg[ \\sigma(\\phi^{A0} + W/2) \\;\\; - \\;\\; \\sigma(\\phi^{A0} + W/2 + \\phi^B) \\bigg]\n$$\n\nAnd again, the fact that it's got a multiplication by $W$ means our correction can be thought of as equivalently a correction to $v_i$, the activity of the visible unit. So, filling in all the tedious super and subscripts...\n\nThe Gibbs update for this hopefully improved approximation is:\n$$\n\\begin{align}\n\\psi_j &= \\sum_i W_{ji} \\bigg( v_i - \\sigma_i^{AB} \\;\\;+\\;\\; \\sigma_i^A \\bigg) \\\\\n\\text{where}\\;\\; \\sigma_i^{AB} &= \\sigma(\\alpha \\times (\\phi_i^{A0} + W_{ji}/2 +\\phi_i^B)) & \\text{ie. both nets}\n\\\\\n\\sigma_i^A &= \\sigma(\\alpha \\times (\\phi_i^{A0} + W_{ji}/2) & \\text{ie. one net}\n\\end{align}\n$$\nThis seems very intuitive to me - it's almost literally \"explaining away\". If it works, that's a really nice story to tell.\n\n\"Ideally\" by some measure the sigmoids here should also use the suggested \"gain\" of $\\alpha$. But that's probably not completely crucial...?\n\n\n```python\n# testing the improved approximation\nW = -10.0\nalpha = 4*(2*sigmoid(W/2)-1)/W # this is the scaler that would match the slope at the 'midpoint'\nphi = np.linspace(-30, 30, 1001)\nplt.plot(phi, np.log(sigmoid(phi)/sigmoid(phi+W)),'k')\nplt.plot(phi, -W*sigmoid(-alpha*(phi+W/2)),'b')\nprint(alpha)\n```\n\n## ELEPHANT IN THE ROOM\n\nwhat a pain it is that, in order to update $h_j^A$, we need to find the input to each visible unit _in the case that $h_j^A = 0$. That really sucks. It'd be way way cooler if we could somehow just use the existing input to the visible unit, and perhaps account for the fact that $h_j^A \\neq 0$ somehow..._\n\nTHIS IS A BIG FAT TODO.\n\n## this looks like a pig, but perhaps can be found locally...\n\nBuilding in the effect of the ACTUAL hidden unit activity $h_j^A$, we have that\n$$\n\\begin{align}\n\\psi_j &= \\psi_j^\\text{RBM} \\;\\; + \\;\\; \\sum_i W^A_{ji} \\bigg[ \\sigma(\\phi^A_i - \\hat{h}^A_j W^A_{ji}) - \\sigma(\\phi^{AB}_i - \\hat{h}^A_j W^A_{ji}) \\bigg] \n\\end{align}\n$$\nwhere\n * $\\phi^{A}_i $ is the actual input to visible unit $v_i$ arising from the $A$ net alone\n * $\\phi^{AB}_i = \\phi^{A}_i + \\phi^{B}_i $ is the total input from both nets\n * $\\hat{h}^A_j = h^A_j - 1/2$\n\nThe above was ignoring the \"optimal gain\" mentioned earlier. \nLet's denote the optimal gain as \n$\\omega = 8\\,(\\sigma(W/2)-0.5)/W$:\n\n$$\n\\begin{align}\\psi_j &= \\psi_j^\\text{RBM} \\;\\; + \\;\\; \\sum_i W^A_{ji} \\bigg[ \\sigma\\bigg(\\phi^A_i \\omega^A_{ji} \\, - \\, \\hat{h}^A_j \\omega^A_{ji} W^A_{ji}\\bigg) \\; - \\; \\sigma\\bigg(\\phi^{AB}_i \\omega^A_{ji} \\, - \\, \\hat{h}^A_j \\omega^A_{ji} W^A_{ji} \\bigg) \\bigg] \n\\end{align}\n$$\n\n\n```python\n# testing \nphi = np.linspace(-3, 3, 1001)\nplt.plot(phi, sigmoid(phi),'k')\nplt.plot(phi, phi/4.+.5,'r')\n#plt.axis('equal')\n```\n\n\n```python\n# Now to put the \"eps\" term in too, to see the entire approximation\neps = 10.0\ntruth = np.log(sigmoid(phi)/sigmoid(phi+W)) - np.log(sigmoid(phi+eps)/sigmoid(phi+W+eps))\napprox = -W*(sigmoid(-alpha*(phi+W/2)) - sigmoid(-alpha*(phi+eps+W/2)) )\nplt.plot(phi, truth,'k', phi, approx,'b')\n```\n\n# The learning algorithm\nStochastic ascent of the log likelihood.\n\nSWITCHING NOTATION HERE IS A PAIN, BUT IT BECOMES MORE STRAIGHT-UP TO DITCH EPSILON AND INSTEAD PUT A/B SUPERSCIPTS ON PHI AND H, TO DENOTE THE TWO NETWORKS. NEED TO MAKE A DECISION ON WHICH IS BETTER AND USE IT EVERYWHERE I GUESS.\n\nHandy shorthands:\n * $\\phi_i^A = \\sum_j h_j^A W_{ji}$, and similarly for $B$\n * $\\phi_i^\\text{AB} = \\phi_i^A + \\phi_i^B$\n\nWe have that \n$$\n\\log P^\\star(h^A, h^B, v) = \\log P^\\star(h^A) + \\log P^\\star(h^B) + \\log P^\\star(v \\mid h^A, h^B)\n$$\n\nThe first term is: \n$ \\log P^\\star(h^A) = \\sum_i \\log (1 + e^{\\phi^A_i}) = -\\sum_i \\log (\\sigma(\\phi^A_i))$\n\nSecond is the same...\n\nThird is \n$\\sum_i v_i\\log \\sigma(\\phi_i^\\text{AB}) \\; + \\; (1-v_i) \\log \\sigma(- \\phi_i^\\text{AB}) $\n\nSo now we differentiate it w.r.t. some particular weight $W_{ml}^A$ like this:\n\nFirst term:\n$\\frac{\\partial}{\\partial W_{ml}^A} \\log P^\\star(h^A) = \\sigma(\\phi^A_l) h_m^A$ is the first term, which is just the average of the usual RBM Hebbian change.\n\nThe second term: is zero.\n\nThird term: \n\n$\\frac{\\partial}{\\partial W_{ml}^A} \\log P^\\star(v \\mid h^A, h^B) = (v_l-\\sigma(\\phi_l^\\text{AB})) h_m^A$\nwhich is \"just the perceptron rool\".\n\n## so the learning algorithm is...\n\n### WAKE PHASE\n\nuse our Gibbs chain to get samples from $h$ for each $v \\in \\mathcal{D}$, and do\n\n$\\Delta W_{ji}^A \\;\\;\\; \\propto \\;\\;\\; \\underbrace{\\sigma(\\phi^A_i) h_j^A}_\\text{mean field Hebbian} \\; + \\; \\underbrace{(v_i - \\sigma(\\phi_i^\\text{AB})) h_j^A}_\\text{Perceptron learning rule}$\n\nand similarly for the other RBM. Note that the $\\phi$'s are not the same in the two terms: the first only sums input from the A side, but the second sums from both hidden layers.\n\nAnother way to say the same thing would be\n\n$\\Delta W_{ji}^A \\;\\;\\; \\propto \\;\\;\\; \\big[ v_i \\, + \\, \\sigma(\\phi^A_i) \\, - \\,\\sigma(\\phi_i^\\text{AB}) \\big] h_j^A$\n\nwhich is like a Hebbian update but with a modified visible activation, in effect.\n\n_Q: What do we make of the resemblance between this and the approximation, below?_\n\n\n### SLEEP PHASE \nuse \"regular\" Gibbs sampling _in each model separately_ to sample independently from the two RBMs, and do\n\n$\\Delta W_{ji}^A \\;\\;\\; \\propto \\;\\;\\; - \\sigma( \\phi^{A}_i) \\; h_j^A$\n\nand similarly for the other RBM.\n\n### notice the free phase is free\nIn the FREE PHASE the expected $\\psi$ is simply:\n$$\\bar{\\psi}_j = \\sum_i W_{ji} \\sigma_{\\phi}$$\nDoes that mean that the free phase in this model corresponds to what it would be if the two RBMs were not even connected?\nLooks like it (although this is just an approximation, isn't it?).\nBUT OF COURSE IT DOES! In the \"unrolled\" version of the net, the visibles are not clamped in the free phase and hence there's no explaining away going on between the two RBMs: they're independent RBMs doing their own thing, in the free phase. It's *only the wake phase that needs any update to the vanilla Gibbs* $\\psi$.\n\nThought: maybe even the wake phase could be implemented via samples instead of having to calculate and propogate those sigmoid floats? THINK ABOUT THIS SOME MORE.\n\n\n```python\nimport sympy as sp\nx,y,z = sp.symbols('x y z')\nsp.simplify(sp.log( (1+sp.exp(-x-y)) * (1+sp.exp(x+y+z)) / (1+sp.exp(-x-y-z)) / (1+sp.exp(x+y))) )\nsp.simplify(sp.log( (1+sp.exp(x)) * (1+sp.exp(x+y+z)) / (1+sp.exp(x+y)) / (1+sp.exp(x+z)) )) \n```\n", "meta": {"hexsha": "441e20f28fb9030bd374ac7c77a4014970949a9e", "size": 113110, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Words/old_oRBM_thinking.ipynb", "max_stars_repo_name": "garibaldu/multicauseRBM", "max_stars_repo_head_hexsha": "f64f54435f23d04682ac7c15f895a1cf470c51e8", "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": "Words/old_oRBM_thinking.ipynb", "max_issues_repo_name": "garibaldu/multicauseRBM", "max_issues_repo_head_hexsha": "f64f54435f23d04682ac7c15f895a1cf470c51e8", "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": "Words/old_oRBM_thinking.ipynb", "max_forks_repo_name": "garibaldu/multicauseRBM", "max_forks_repo_head_hexsha": "f64f54435f23d04682ac7c15f895a1cf470c51e8", "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": 178.125984252, "max_line_length": 28008, "alphanum_fraction": 0.8505525595, "converted": true, "num_tokens": 6833, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.951863227517834, "lm_q2_score": 0.8962513793687401, "lm_q1q2_score": 0.8531087306332397}} {"text": "# Fourier Transform\n\n## Polynomials\n- How to multiply two polynomials\n- Brute force algorithm (multiplying all terms together): O(n * m) for polynomials with degrees n-1 and m-1\n\n## Representation\n- Coefficient representation vs. point-value representation\n- Multiplying polynomials in point-value representation is much easier:\n - (fg)(x) = f(x)g(x)\n\n# Discrete Fourier Transform\nConvert from coefficient representation to point-value representation\n- $\\mathcal{O}(n \\lg n)$ runtime\n- Evaluate a polynomial of degree n - 1 at n points to find its point-value representation\n- Choose these points carefully\n\n# Definitions\nLet $\\mathbf{a} = [a_0, a_1, ..., a_{n-1}]$ be the sequence of coefficients of a polynomial $P$ with degree $n-1$ and $\\mathbf{w} = [w_0, w_1, ..., w_{n-1}]$, $w_j \\in \\mathbb{C}$. Then the discrete Fourier transform of $P$ gives the set of point-values $[b_0, b_1, ..., b_{n-1}]$, where each $b_j$ is given by\n\\begin{align}\nb_j = P(w_j) = \\sum_{k=0}^{n-1} a_k w_j^k\n\\end{align}\n\nWritten in matrix form, we have\n\\begin{align}\n\\begin{bmatrix}\n1 & w_0 & w_0^2 & ... & w_0^{n-1} \\\\\n1 & w_1 & w_1^2 & ... & w_1^{n-1} \\\\\n1 & w_2 & w_2^2 & ... & w_2^{n-1} \\\\\n\\vdots & \\vdots & \\vdots & \\ddots & \\vdots \\\\\n1 & w_{n-1} & w_{n-1}^2 & ... & w_{n-1}^{n-1} \\\\\n\\end{bmatrix}\n\\begin{bmatrix}\na_0 \\\\\na_1 \\\\\na_2 \\\\\n\\vdots \\\\\na_{n-1} \\\\\n\\end{bmatrix}\n = & \n\\begin{bmatrix}\nb_0 \\\\\nb_1 \\\\\nb_2 \\\\\n\\vdots \\\\\nb_{n-1} \\\\\n\\end{bmatrix}\n\\end{align}\n\nThe fast Fourier transform algorithm calculates each $b_j$. We will show that this algorithm runs in $\\mathcal{O} (n \\log{} n)$ when $n$ is a power of 2. To do so requires a selecting a special set of points $\\mathbf{w}$ called the $N^{th}$ roots of unity.\n\n# $N^{th}$ Roots of Unity\n## Definition\nThe $N^{th}$ roots of unity are the set of complex numbers \n\\begin{align}\n\\{ \\; e^{2\\pi i \\frac{j}{N}} \\; \\mid \\; j = 0, 1, \\dots, N-1 \\}\n\\end{align}\nFor example, the $5^{th}$ roots of unity:\n\n\n## Notation\nWhen $\\mathbf{w}$ is the $n^{th}$ roots of unity, we will refer to $\\mathbf{w}$ as $w_n$. The $j^{th}$ element (previously $w_j$) is indicated using the array index notation, $w_n[j]$.\n\n## Properties\nLet $w_n[j] = e^{2\\pi i j/n}$. Then $w_n[j]$ is said to be an $n^{th}$ root of unity and has the following properties:\n1. $w_n[j]^k = w_n[jk]$ \n2. $w_n[j] w_n[k] = w_n[j + k]$\n3. $w_n[j]^n = 1$\n4. If $n = 2^r$, then $w_n[2j] = w_{\\frac{n}{2}}[j]$\n\n*Proof of 4:*\n\n\\begin{align}\nw_n[2j] & = (e^{2 \\pi i (2j)/2^r}) \\\\\n& = e^{2 \\pi i j/2^{r-1}} \\\\\n& = w_{\\frac{n}{2}}[j] \\\\\n\\end{align}\n\n# Fast Fourier Transform\nWe are now ready to derive a recursive algorithm for the DFT. \n\n\\begin{align}\nF(a, w_n[j]) = \\sum_{k=0}^{n-1} a[k] w_n[j]^k\n\\end{align}\n\nIf we split the righthand side into two summations, one over even indices of $a$, the other over the odd, we get\n\n\\begin{align}\n\\sum_{k=0}^{n-1} a[k] w_n[j]^k & = \\sum_{m=0}^{\\frac{n}{2}-1} a[2m] w_n[j]^{2m} + \\sum_{m=0}^{\\frac{n}{2}-1} a[2m+1] w_n[j]^{2m+1}\n\\end{align}\n\n\n\nFrom properties 1. and 4., we can clearly see that the lefthand summation is $F(a_{even}, w_{\\frac{n}{2}}[j])$. The righthand side requires a bit more manipulation:\n\n\\begin{align}\n\\sum_{m=0}^{\\frac{n}{2}-1} a[2m + 1] w_n[j]^{2m+1} & = \\sum_{m=0}^{\\frac{n}{2}-1} a[2m + 1] w_n[j(2m+1)]\\\\\n& = \\sum_{m=0}^{\\frac{n}{2}-1} a[2m + 1] w_n[j2m] w_n[j] \\\\\n& = w_n[j] \\biggl( \\sum_{m=0}^{\\frac{n}{2}-1} a[2m + 1] w_n[2j]^m \\biggr) \\\\\n& = w_n[j] \\cdot F(a_{odd}, w_{\\frac{n}{2}}[j]) \\\\\n\\end{align}\n\n\nTherefore, our function $F$ can be written as\n\n\\begin{align}\nF(a, w_n[j]) & = F(a_{even}, w_{\\frac{n}{2}}[j]) + w_n[j] \\cdot F(a_{odd}, w_{\\frac{n}{2}}[j]) \\\\\n\\end{align}\nfor $j = (0, 1, \\dots, n-1)$\n\nThis recurrence returns a single value for a particular $j$, however we can modify it to instead return the Fourier transform for all values of $j$, giving us\n\n\\begin{align}\nF(a, w_n) & = F(a_{even}, w_{\\frac{n}{2}}) + w_n \\cdot F(a_{odd}, w_{\\frac{n}{2}}) \\\\\n\\end{align}\n\nWritten in Julia, the algorithm is as follows:\n\n\n```julia\nfunction FFT(n::Integer, x̄::Array{<:Number})\n \"\"\"\n Calculate the fast Fourier transform of n numbers in x̄.\n (Note that n must be a power of 2 (n = 2ᵏ))\n Returns:\n ȳ - A complex array of size n \n \"\"\"\n # Julia is 1-indexed\n if n == 1\n return [x̄[1]]\n end\n \n evens = [x̄[Int(2i)] for i = 1:n/2]\n odds = [x̄[Int(2i-1)] for i = 1:n/2]\n # Since Julia is 1-indexed, we flip the odds and evens at the recursive step\n ū = FFT(Int(n/2), odds)\n v̄ = FFT(Int(n/2), evens)\n ȳ = zeros(Complex, n)\n for j = 1:n\n τ = exp(2π*im*(j-1)/n) \n ȳ[j] = ū[(j-1)%Int(n/2)+1] + τ * v̄[(j-1)%Int(n/2)+1]\n end\n return ȳ\nend\n```\n\n\n\n\n FFT (generic function with 1 method)\n\n\n\n# Time Complexity\nLet $N = n$, and $T(N) = F(\\mathbf{a}, w_n[j])$,\n\\begin{align}\nT(N) = 2 \\cdot T(\\frac{N}{2}) + N,\n\\end{align}\nwhere the $+N$ comes from the loop after the recursive step.\n\nThis algorithm runs in $\\mathcal{O}(N \\lg N)$ when $N$ is a power of 2.\n\n*Proof:*\n\\begin{align}\nT(N) & = 2 \\cdot T(\\frac{N}{2}) + N \\\\\n\\end{align}\nLet $N = 2^k$, and $t_k = T(2^k)$\n\\begin{align}\nt_k & = 2t_{k-1} + 2^k \\\\\nt_k - 2t_{k-1} & = 2^k \\\\\n\\end{align}\n\nWe can use the characteristic equation to solve this inhomogeneous system.\n\\begin{align}\n(x - 2)^2 & = 0 \\\\\n\\end{align}\nSo we end up with\n\\begin{align}\nt_k & = c_1 2^k + c_2 k 2^k; k = \\lg N\\\\\nT(N) & = c_1 N + c_2 N \\lg N \\\\\nT(N) & = \\mathcal{O}(N \\lg N) \\\\\n\\end{align}\n\n# Example\nSay you want to perform the following multiplication:\n\\begin{align}\n(1 + x)(1 + x + x^2).\n\\end{align}\nWe can use the FFT algorithm to find the point-value representation of each polynomial, then multiply those two together:\n\n\n```julia\nn = 4\nx̄₁ = [1 1 0im 2]\nȳ₁ = FFT(n, x̄₁)\ndisplay(ȳ₁)\n```\n\n\n 4-element Array{Complex,1}:\n 4.0+0.0im \n 1.0-1.0im \n -2.0+3.67394e-16im\n 1.0+1.0im \n\n\nCalculating the FFT of each,\n\\begin{align}\nFFT(1 + x) & = [2, 1+i, 0, 1-i] \\\\\nFFT(1 + x + x^2) & = [3, i, 1, -i], \\\\\n\\end{align}\nwhich leads to the point-value representation of their product: $[6, -1 + i, 0, -1-i]$.\n", "meta": {"hexsha": "1e3d82e9a53cde9fa7d04f2f0dd69b73bc0567a8", "size": 11094, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "FourierTransform.ipynb", "max_stars_repo_name": "dillondaudert/JuliaFFT", "max_stars_repo_head_hexsha": "eeb80cd0b2208cba70bf024c092228cb898ea015", "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": "FourierTransform.ipynb", "max_issues_repo_name": "dillondaudert/JuliaFFT", "max_issues_repo_head_hexsha": "eeb80cd0b2208cba70bf024c092228cb898ea015", "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": "FourierTransform.ipynb", "max_forks_repo_name": "dillondaudert/JuliaFFT", "max_forks_repo_head_hexsha": "eeb80cd0b2208cba70bf024c092228cb898ea015", "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.9927007299, "max_line_length": 323, "alphanum_fraction": 0.4751216874, "converted": true, "num_tokens": 2424, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.951863227517834, "lm_q2_score": 0.8962513689768735, "lm_q1q2_score": 0.8531087207416039}} {"text": "# Lecture 2: second-order ordinary differential equations\n\nWe now look at solving second-order ordinary differential equations using a computer algebra system.\n\nTo use SymPy, we first need to import it and call `init_printing()` to get nicely typeset equations:\n\n\n```python\nfrom sympy import *\n\n# This initialises pretty printing\ninit_printing()\nfrom IPython.display import display\n\n# This command makes plots appear inside the browser window\n%matplotlib inline\n```\n\n# Mass-spring-damper system\n\nThe differential equation that governs an unforced, single degree-of-freedom mass-spring-damper system is\n\n$$\nm \\frac{d^{2}y}{dt^{2}} + \\lambda \\frac{dy}{dt} + ky = 0\n$$\n\nTo solve this problem using SymPy, we first define the symbols $t$ (time), $m$ (mass), $\\lambda$ (damper coefficient) and $k$ (spring stiffness), and the function $y$ (displacement): \n\n\n```python\nt, m, lmbda, k = symbols(\"t m lambda k\")\ny = Function(\"y\")\n```\n\nNote that we mis-spell $\\lambda$ as `lmbda` because `lambda` is a protected keyword in Python.\n\nNext, we define the differential equation, and print it to the screen:\n\n\n```python\neqn = Eq(m*Derivative(y(t), t, t) + lmbda*Derivative(y(t), t) + k*y(t), 0)\ndisplay(eqn)\n```\n\nChecking the order of the ODE:\n\n\n```python\nprint(\"This order of the ODE is: {}\".format(ode_order(eqn, y(t))))\n```\n\n This order of the ODE is: 2\n\n\nand now classifying the ODE:\n\n\n```python\nprint(\"Properties of the ODE are: {}\".format(classify_ode(eqn)))\n```\n\n Properties of the ODE are: ('nth_linear_constant_coeff_homogeneous', '2nd_power_series_ordinary')\n\n\nwe see as expected that the equation is linear, constant coefficient, homogeneous and second order.\n\nThe `dsolve` function solves the differential equation:\n\n\n```python\ny = dsolve(eqn, y(t))\ndisplay(y)\n```\n\nThe solution looks very complicated because we have not specified values for the constants $m$, $\\lambda$ and $k$. The nature of the solution depends heavily on the relative values of the coefficients, as we will see later. We have four constants because the most general case the solution is complex, with two complex constants having four real coefficients.\n\nNote that the solution is make up of expoential functions and sinusoidal functions. This is typical of second-order ODEs.\n\n# Second order, constant coefficient equation\n\nWe'll now solve \n\n$$\n\\frac{d^{2}y}{dx^{2}} + 2 \\frac{dy}{dx} - 3 y = 0\n$$\n\nThe solution for this problem will appear simpler because we have concrete values for the coefficients.\n\nEntering the differential equation:\n\n\n```python\ny = Function(\"y\")\nx = symbols(\"x\")\neqn = Eq(Derivative(y(x), x, x) + 2*Derivative(y(x), x) - 3*y(x), 0)\ndisplay(eqn)\n```\n\nSolving this equation,\n\n\n```python\ny1 = dsolve(eqn)\ndisplay(y1)\n```\n\nwhich is the general solution. As expected for a second-order equation, there are two constants.\n\nNote that the general solution is of the form\n\n$$\ny = C_{1} e^{\\lambda_{1} x} + C_{2} e^{\\lambda_{2} x}\n$$\n\nThe constants $\\lambda_{1}$ and $\\lambda_{2}$ are roots of the \\emph{characteristic} equation\n\n$$\n\\lambda^{2} + 2\\lambda - 3 = 0\n$$\n\nThis quadratic equation is trivial to solve, but for completeness we'll look at how to solve it using SymPy. We first define the quadratic equation:\n\n\n```python\neqn = Eq(lmbda**2 + 2*lmbda -3, 0)\ndisplay(eqn)\n```\n\nand then compute the roots:\n\n\n```python\nsolve(eqn)\n```\n\nwhich as expected are the two exponents in the solution to the differential equattion.\n", "meta": {"hexsha": "2809aef25cb1c1cc24d792e89c737b84853a66c5", "size": 24675, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Lecture02.ipynb", "max_stars_repo_name": "garth-wells/IA-maths-Ipython", "max_stars_repo_head_hexsha": "7497ee12f2a36d6ec6025ccdb3d2ce6387dc7c9a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 27, "max_stars_repo_stars_event_min_datetime": "2017-05-21T16:30:35.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-14T00:23:51.000Z", "max_issues_repo_path": "Lecture02.ipynb", "max_issues_repo_name": "garth-wells/IA-maths-Ipython", "max_issues_repo_head_hexsha": "7497ee12f2a36d6ec6025ccdb3d2ce6387dc7c9a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2016-10-10T09:06:41.000Z", "max_issues_repo_issues_event_max_datetime": "2016-11-04T11:05:32.000Z", "max_forks_repo_path": "Lecture02.ipynb", "max_forks_repo_name": "garth-wells/IA-maths-Jupyter", "max_forks_repo_head_hexsha": "7497ee12f2a36d6ec6025ccdb3d2ce6387dc7c9a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 13, "max_forks_repo_forks_event_min_datetime": "2017-05-15T08:22:51.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-02T05:27:59.000Z", "avg_line_length": 63.5953608247, "max_line_length": 4210, "alphanum_fraction": 0.7618237082, "converted": true, "num_tokens": 919, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338112885303, "lm_q2_score": 0.8872046049010911, "lm_q1q2_score": 0.8530772251432809}} {"text": "# Numerical Recipes Workshop 6\nFor the week of 28 October to 1 November, 2019.\n\nThis notebook will cover some boundary value problem solving and minimization.\n\n\n```python\nfrom matplotlib import pyplot as plt\n%matplotlib inline\nimport numpy as np\n```\n\n\n```python\nplt.rcParams['figure.figsize'] = (10, 6)\nplt.rcParams['font.size'] = 14\n```\n\n## Solving Boundary Value Problems\n\nSciPy's [solve_bvp](https://docs.scipy.org/doc/scipy/reference/generated/scipy.integrate.solve_bvp.html) function will solve a boundary value problem given a system of ordinary differential equations (ODEs). We will consider an example from the function's documentation.\n\n### The Bratu Problem\nThis is defined as:\n\n$\n\\begin{align}\n\\large\n\\frac{d^{2}y}{dx^{2}} + e^{y} = 0\n\\end{align}\n$\n\n$\n\\begin{align}\n\\large\ny(0) = y(1) = 0\n\\end{align}\n$\n\nThe setup is similar to that of [solve_ivp](https://docs.scipy.org/doc/scipy/reference/generated/scipy.integrate.solve_ivp.html#scipy.integrate.solve_ivp) for initial value problems. We need to define a function that returns the derivative of the system of equations. As with the parabolic motion example, we can decompse the nth order ODE into a system of n 1st order ODEs.\n\n$\n\\begin{align}\n\\large\n\\frac{dy}{dx} = v(x)\n\\end{align}\n$\n\n$\n\\begin{align}\n\\large\n\\frac{dv}{dx} = -e^{y(x)}\n\\end{align}\n$\n\nThe difference here is that both $y$ and $v$ will be arrays instead of single values.\n\n\n```python\ndef derivatives(x, y):\n \"\"\"\n y0 = f(x) => dy0/dx = y1\n y1 = df/dx => dy1/dx = -e^y0\n \"\"\"\n return np.vstack((y[1], -np.exp(y[0])))\n```\n\nIt may be helpful to look up the documentation on `np.vstack` and to stick a print statement into the `derivatives` to understand what the arguments look like.\n\nWe also need to create a function to return the relevant boundary conditions. Similar to the events functions for `solve_ivp`, the `solve_bvp` function will look for solutions where the boundary conditions function returns 0s. For a systen of n ODEs, the boundary conditions function must n values, but they can be related to any one of the equations and be for either the left or right side.\n\nThe arguments of the boundary conditions function are `ya` and `yb`, the values of the system of equations on the left side ($x = a$) and the right side ($x = b$). For the Bratu problem, the relevant boundary conditions are $y(a) = 0$ and $y(b) = 0$, where $a = 0$ and $b = 1$.\n\n\n```python\ndef bc(ya, yb):\n \"\"\"\n ya is [f(x), df/dx] on the left (x = 0)\n yb is [f(x), df/dx] on the right (x = 1)\n \n For this problem, we want y(0) = 0 and y(1) = 0\n \"\"\"\n return np.array([ya[0], # f(x) on left side\n yb[0]]) # f(x) on right side\n\n```\n\nNow define the initial x-space over which to solve the problem.\n\n\n```python\nx = np.linspace(0, 1, 5)\n```\n\nCreate an initial guess for the solution. The array must have the shape ($N_{equations}$, $N_x$).\n\n\n```python\n# start with all zeroes\ny = np.zeros((2, x.size))\n```\n\nNow solve the BVP. The `verbose` keyword gives some additional output. Remove or set it to 0 to get rid of the output.\n\n\n```python\nfrom scipy.integrate import solve_bvp\n\nsol = solve_bvp(derivatives, bc, x, y, verbose = 2)\n```\n\n Iteration Max residual Max BC residual Total nodes Nodes added \n 1 1.05e-04 0.00e+00 5 0 \n Solved in 1 iterations, number of nodes 5. \n Maximum relative residual: 1.05e-04 \n Maximum boundary residual: 0.00e+00\n\n\n### What `solve_bvp` returns\n\nPrinting the return value of `solve_bvp` (in this case `sol`) shows a complicate object with multiple components.\n\n\n```python\nprint(sol)\n```\n\n message: 'The algorithm converged to the desired accuracy.'\n niter: 1\n p: None\n rms_residuals: array([9.86500717e-05, 1.05360602e-04, 1.05360602e-04, 9.86500717e-05])\n sol: \n status: 0\n success: True\n x: array([0. , 0.25, 0.5 , 0.75, 1. ])\n y: array([[ 0.00000000e+00, 1.04784145e-01, 1.40534773e-01,\n 1.04784145e-01, 0.00000000e+00],\n [ 5.49349275e-01, 2.84320977e-01, -1.02436237e-17,\n -2.84320977e-01, -5.49349275e-01]])\n yp: array([[ 5.49349275e-01, 2.84320977e-01, -1.02436237e-17,\n -2.84320977e-01, -5.49349275e-01],\n [-1.00000000e+00, -1.11047088e+00, -1.15088910e+00,\n -1.11047088e+00, -1.00000000e+00]])\n\n\nThe most important thing returned is the `sol` attribute of the return value (in this case `sol.sol`). This is a function that will return the value of the solution for given $x$ values.\n\nNote, a similar object is returned for `solve_ivp` when the `dense_output=True` keyword is given.\n\n\n```python\nx_sol = np.linspace(0, 1, 100)\ny_sol = sol.sol(x_sol)\n# sol.sol return values for the whole system [f(x), df/dx]\nplt.plot(x_sol, y_sol[0])\n```\n\nThe Bratu problem has two solutions. The second can be found by changing the initial guess slightly.\n\n\n```python\n# start with all zeroes\ny = np.zeros((2, x.size))\n# small change in initial guess\ny[0] = 3\n```\n\nNow, solve the BVP again, compare the output and plot the two solutions.\n\n\n```python\nx = np.linspace(0, 1, 10)\n# start with all zeroes\ny = np.zeros((2, x.size))\nfrom scipy.integrate import solve_bvp\n\nsol = solve_bvp(derivatives, bc, x, y,)\n```\n\n\n```python\nx_sol = np.linspace(0, 1, 100)\ny_sol = sol.sol(x_sol)\n# sol.sol return values for the whole system [f(x), df/dx]\nplt.plot(x_sol, y_sol[0])\n```\n\n### Heat Exchanger Problem\n(from the old bvp_solver tutorial)\n\nConsider a device where heat is exchanged between two fluids. The hot fluid (with temperature $T_1$) enters from the left, moving to the right. The cold fluid (with temperature $T_2$) enters from the right, moving to the left. They exchange heat through a metal plate in between them. The cold fluid has twice the specific heat of the hot fluid. This system can be expressed as\n\n$\n\\begin{align}\n\\large\nq = U * (T_1 - T_2)\n\\end{align}\n$\n\n$\n\\begin{align}\n\\large\n\\frac{dT_1}{dx} = -q\n\\end{align}\n$\n\n$\n\\begin{align}\n\\large\n\\frac{dT_2}{dx} = \\frac{-q}{2}\n\\end{align}\n$\n\nwhere $U$ is a coefficient of heat transfer.\n\nThe temperatures of the hot and cold fluids when they enter the device are known.\n\n$\n\\begin{align}\n\\large\nT_1(x = 0) = 200\n\\end{align}\n$\n\n$\n\\begin{align}\n\\large\nT_2(x = L) = 50\n\\end{align}\n$\n\nRelevant constants are given below.\n\n\n```python\nT1_0 = 200\nT2_L = 50\nL = 5\nU = 1\n```\n\nImplement the derivatives and bounary conditions functions that describe this system.\n\n\n```python\ndef derivatives(x , y):\n \"\"\"\n y[0] is T_1\n y[1] is T_2\n \"\"\"\n q = U * (y[0] - y[1])\n return np.vstack((- q, - q / 2))\n \n \ndef bc(ya, yb):\n \"\"\"\n ya is [T1, T2] on the left\n yb is [T1, T2] on the right\n \"\"\"\n return np.array([ya[0]-200, yb[0]-50])\n \n```\n\n\n```python\nderivatives(x, y).shape\n```\n\n\n\n\n (2, 10)\n\n\n\nSet an initial guess for the solution. Try $T_1(x) = T_1(0)$ and $T_2(x) = T_2(L)$.\n\n\n```python\nx = np.linspace(0, L, 10)\ny = np.empty([2, x.size])\ny[0] = T1_0\ny[1] = T2_L\n```\n\nNow find the solution and plot $T_1(x)$ and $T_2(x)$.\n\n\n```python\nsol = solve_bvp(derivatives, bc, x, y,)\nx_sol = np.linspace(0, L, 100)\ny_sol = sol.sol(x_sol)\nplt.plot(x_sol, y_sol[0])\nplt.plot(x_sol, y_sol[1])\n```\n\n## Minimization\n\nThe [scipy.optimize](https://docs.scipy.org/doc/scipy/reference/optimize.html) module provides a number of options for finding function minima and maxima. The most relevant to our purposes is [minimize_scalar](https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.minimize_scalar.html#scipy.optimize.minimize_scalar).\n\nStudy the documentation of `minimize_scalar` and use it to find all local minima of the function below in the range [-10, 10]. Plot $f(x)$ to gain some intuition. Is there a more informative way to plot $f(x)$?\n\n\n```python\ndef f(x):\n return (x - 4*np.euler_gamma) * 0.5 * x * (x + np.e)**2 - 5*np.sin(3*x) + 11\n```\n\n\n```python\nfrom scipy.optimize import minimize_scalar\n```\n\n\n```python\nx = np.arange(-10, 10, 0.1)\ny = f(x)\n#plt.ylim(0,100)\nplt.semilogy(x,y)\n#plt.plot(x,y)\n```\n\n\n```python\nres = minimize_scalar(f, method = 'Brent', bracket = (-10, 0, 10))\nsol_1 = res.x\nres = minimize_scalar(f, method = 'Brent', bracket = (-5, -3, -2.5))\nsol_2 = res.x\nres = minimize_scalar(f, method = 'Brent', bracket = (0, 1, 2.5))\nsol_3 = res.x\nsol = np.array([sol_1, sol_2, sol_3])\nprint(sol)\n```\n\n [-1.65627449 -3.3207098 0.73763619]\n\n\n\n```python\n\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "9ae302330e5f03fd3d6ec41c73b5ec089a275561", "size": 117545, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "c2/workshop_6.ipynb", "max_stars_repo_name": "c-abbott/num-rep", "max_stars_repo_head_hexsha": "fb548007b84f96d46527b8ea3ba0461b32a34452", "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": "c2/workshop_6.ipynb", "max_issues_repo_name": "c-abbott/num-rep", "max_issues_repo_head_hexsha": "fb548007b84f96d46527b8ea3ba0461b32a34452", "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": "c2/workshop_6.ipynb", "max_forks_repo_name": "c-abbott/num-rep", "max_forks_repo_head_hexsha": "fb548007b84f96d46527b8ea3ba0461b32a34452", "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.6204819277, "max_line_length": 25336, "alphanum_fraction": 0.8904674805, "converted": true, "num_tokens": 2719, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218284193597, "lm_q2_score": 0.9252299509069106, "lm_q1q2_score": 0.8529896880484534}} {"text": "# Solving Ordinary Differential Equations using Numerical Methods\n\n### The following shows different numerical methods in solving ODEs\n\n## Euler Method (1st Order)\n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\n```\n\n\n```python\ndef Euler(f, x0, y, x, deltax):\n \n X = []\n Y = []\n X.append(x0)\n Y.append(y)\n \n while x0 < x:\n deltax = min(deltax, x - x0)\n y = y + deltax*f(x,y)\n x0 = x0 + deltax\n X.append(x0)\n Y.append(y)\n \n return np.array(X), np.array(Y)\n```\n\n### Exponential Decay\n\nLet $N_u$ be the number of $U^{235}$ nuclei present in the sample at a time $t$:\n\\begin{equation}\n\\frac{dN_U}{dt} = - \\frac{N_U}{\\tau}\n\\end{equation}\nInitial condition: $N_U = N_{U,0}$ at $t = 0$ with an exact solution $N_U(t) = N_{U,0} e^{-t/\\tau}$\n\n\n```python\nN = lambda t,y: -y*tau\n\ntau = 1\nN0 = 100\nt0, tf = 0, 5\n\ndeltat1 = Euler(N, x0=t0, y=N0, x=tf, deltax=0.5)\ndeltat2 = Euler(N, x0=t0, y=N0, x=tf, deltax=0.1)\ndeltat3 = Euler(N, x0=t0, y=N0, x=tf, deltax=0.05)\n\nt1, N1 = deltat1[0], deltat1[1]\nt2, N2 = deltat2[0], deltat2[1]\nt3, N3 = deltat3[0], deltat3[1]\n\nt_exact = np.linspace(0,5)\nN_exact = N0*np.exp(-t_exact/tau)\n\nplt.plot(t1,N1, 'b.', label = r'$\\Delta t = 0.5$')\nplt.plot(t2,N2, 'bx', label = r'$\\Delta t = 0.1$')\nplt.plot(t3,N3, 'b+', label = r'$\\Delta t = 0.05$')\nplt.plot(t_exact, N_exact, 'r', label = 'Exact')\nplt.legend()\nplt.xlabel('time')\nplt.ylabel(r'$N_u$')\nplt.title('Number of nuclei of $U^{235}$')\nplt.show()\n```\n\n### Linear Motion with Air Drag\n\nIt is often the case that the frictional force on an object will increase as the object moves faster. An example is the motion of a falling parachutist; the role of the parachute is to produce a frictional force due to air drag, which is larger than would normally be the case without the parachute. Assume that the velocity of the parachutist is described by the equation:\n\\begin{equation}\n\\frac{dv}{dt} = g - Cv\n\\end{equation}\nwhere $g$ and $C$ are constants. The constant $g$ is the acceleration due to gravity while $C$ is a drag coefficient. Provide a way of estimating $v$ using the Euler method.\n\nUsing Euler method, we could estimate the $v$ as:\n\\begin{equation}\nv_{n+1} = v_n + (g - Cv_n)\\Delta t\n\\end{equation}\nwhere $\\Delta t$ is small increments of time $t$\n\nLet $C=1$, $g=9.8$, $v_0=100$, at $t=0$ to $t=5$ and $\\Delta t=0.05$\n\n\n```python\nC = 1\ng = 9.8\nv0 = 100\nt0, tf = 0, 5\ndeltat = 0.05\n\nv = lambda t, y: g - C*y\n\nv_deltat = Euler(v, x0=t0, y=v0, x=tf, deltax=deltat)\nt, v = v_deltat[0], v_deltat[1]\n\nvexact = np.exp(-C*t)*(v0*C-g+g*np.exp(C*t))/C\n\nplt.plot(t, v, 'b.', label = r'$\\Delta t = 0.05$')\nplt.plot(t, vexact, 'r', label = 'Exact')\nplt.legend()\nplt.xlabel('time')\nplt.ylabel('$v$')\nplt.title('Velocity of the parachutist through time')\nplt.show()\n```\n\n## Euler Method (2nd Order)\n\n\n```python\ndef Euler2nd(f, t0, tf, y0, v0, dt, Cromer= 'False'):\n \n t = np.arange(t0, tf+dt, dt)\n n = len(t)\n \n y = np.zeros(n)\n v = np.zeros(n)\n \n y[0] = y0\n v[0] = v0\n \n for i in range(n-1):\n if Cromer == 'False':\n v[i+1] = v[i] + f(y[i],v[i],t)*dt\n y[i+1] = y[i] + v[i]*dt\n else:\n v[i+1] = v[i] + f(y[i],v[i],t[i])*dt\n y[i+1] = y[i] + v[i+1]*dt\n \n return t, y\n```\n\n### Simple Harmonic Motion\n\n\\begin{equation}\n\\frac{d^2y}{dt^2} = -ky\n\\end{equation}\nwhere, $y_0 = 0.2$, $v_0 = 0$, $k = 1$, and $\\Delta t = 0.01$\n\n\n```python\ny0 = 0.2\nv0 = 0\nk = 1\ndt = 0.01\ntf = 20.\n\nf = lambda y,v,t: -k*y\n\nsol = Euler2nd(f, t0=0, tf=tf, y0=y0, v0=v0, dt=dt, Cromer= 'False')\nt, y = sol[0], sol[1]\n\nyexact = y0*np.cos(t*np.sqrt(k))\n\nplt.plot(t, y, 'b.', label = 'Euler')\nplt.plot(t, yexact, 'r', label = 'Exact')\nplt.title('Simple Harmonic Oscillator')\nplt.legend()\nplt.xlabel('time')\nplt.ylabel('y')\nplt.show()\n```\n\n## Euler-Cromer (2nd Order)\n\n### Simple Harmonic Motion\n\n\\begin{equation}\n\\frac{d^2y}{dt^2} = -ky\n\\end{equation}\nwhere, $y_0 = 0.2$, $v_0 = 0$, $k = 1$, and $\\Delta t = 0.01$\n\n\n```python\ny0 = 0.2\nv0 = 0\nk = 1\ndt = 0.01\ntf = 20.\n\nf = lambda y,v,t: -k*y\n\nsol = Euler2nd(f, t0=0, tf=tf, y0=y0, v0=v0, dt=dt, Cromer= 'True')\nt, y = sol[0], sol[1]\n\nyexact = y0*np.cos(t*np.sqrt(k))\n\nplt.plot(t, y, 'b.', label = 'Euler-Cromer')\nplt.plot(t, yexact, 'r', label = 'Exact')\nplt.title('Simple Harmonic Oscillator')\nplt.legend()\nplt.xlabel('time')\nplt.ylabel('y')\nplt.show()\n```\n\n### Idealized Projectile Motion\n\nConsider a projectile such as a shell shot from a cannon. The equations of motion of the cannon shell are obtained from Newton’s 2nd law:\n\n\n\\begin{equation}\n\\frac{d^2x}{dt^2} = 0, \\frac{d^2y}{dt^2} = -g\n\\end{equation}\n\nExpress each of these 2nd-order ODEs as 1st-order ODEs and write down the equations for the Euler method that will approximate the motion of the cannon shell.\n\n\\begin{equation}\n\\frac{dx}{dt} = v, \\frac{dy}{dt} = -gt + v\n\\end{equation}\n\n\\begin{equation}\nx = x_0 + vt, y = y_0 + vt - \\frac{gt^2}{2}\n\\end{equation}\n\n\\begin{equation}\nv_{i+1} = v_i \\\\\nx_{i+1} = x_i + v_{i+1}\\Delta t\n\\end{equation}\n\n\\begin{equation}\nv_{i+1} = v_i - g\\Delta t \\\\\ny_{i+1} = y_i + v_{i+1}\\Delta t\n\\end{equation}\n\nLet $g=9.8$, $v_{0x}=0.1$, $v_{0y}=10$, at $t=0$ to $t=2$ and $\\Delta t=0.01$\n\n\n```python\ng = 9.8\nv0x, v0y = 0.1, 10\nx0, y0 = 0, 0\nt0, tf = 0, 2\ndt = 0.01\n\nfx = lambda y,v,t: 0\nfy = lambda y,v,t: -g\n\nsolx = Euler2nd(f=fx, t0=t0, tf=tf, y0=x0, v0=v0x, dt=dt, Cromer= 'True')\nsoly = Euler2nd(f=fy, t0=t0, tf=tf, y0=y0, v0=v0y, dt=dt, Cromer= 'True')\nx, y = solx[1], soly[1]\nt = solx[0]\n\nxexact = v0x*t\nyexact = y0 + v0y*t - 0.5*g*(t**2.)\n\nplt.plot(x, y, 'b.', label = 'Euler-Cromer')\nplt.plot(xexact, yexact, 'r', label = 'Exact')\nplt.title('Idealized Projectile Motion')\nplt.legend()\nplt.xlabel('x')\nplt.ylabel('y')\nplt.show()\n```\n\n### Damped Harmonic Oscillator\n\nThe motion of a damped harmonic oscillator can be described using Newton’s 2nd Law:\n\n\n\\begin{equation}\nm\\frac{d^2x}{dt^2} + C\\frac{dx}{dt} + kx = 0\n\\end{equation}\n\nwhere $m$ is the mass of the oscillator, $C$ is the drag coefficient that damps the motion, and $k$ is a constant that determines the restoring force. Provide a numerical scheme that will approximate the motion of the oscillator.\n\nLet $m=1$, $C=1$, $k=10$, $v_0=0$, $x_0=1$, at $t=0$ to $t=20$ and $\\Delta t=0.01$\n\n\n```python\nm = 1\nC = 1\nk = 10\nv0 = 0\nx0 = 1\nt0, tf = 0, 20\ndt = 0.01\n\nf = lambda y,v,t: -((C/m)*v + (k/m)*y)\n\nsol = Euler2nd(f, t0=t0, tf=tf, y0=x0, v0=v0, dt=dt, Cromer= 'True')\nt, x = sol[0], sol[1]\n\nxexact = (1./39.)*np.exp(-t/2.)*(39*np.cos(0.5*t*np.sqrt(39)) + \\\n np.sqrt(39)*np.sin(0.5*t*np.sqrt(39))) \n\nplt.plot(t, x, 'b.', label = 'Euler-Cromer')\nplt.plot(t, xexact, 'r', label = 'Exact')\nplt.title('Damped Harmonic Oscillator')\nplt.legend()\nplt.xlabel('time')\nplt.ylabel('x')\nplt.show()\n```\n\n### Pendulum\n\nConsider a pendulum of length $L$ and mass $m$ which is acted upon by a frictional force and an external driving force. Let the driving force be a sinusoidally varying force with constant amplitude $F_D$ and driving frequency $\\Omega_D$. Assume that the frictional force is proportional to the pendulum’s velocity with a constant damping factor $q$. (1) Write down the differential equation that describes the motion of the damped, driven pendulum. From the differential equation, write down the equations that approximate the solution using (2) Euler-Cromer, (3) 2nd-order Runge-Kutta, and (4) Verlet algorithms.\n\n\\begin{equation}\n\\frac{d^2y}{dt^2} + q\\frac{dy}{dt} + \\frac{g}{l}\\sin{y} = F_D\\cos{\\Omega_D}\n\\end{equation}\n\n\\begin{equation}\nv_{i+1} = v_i + (- qv - \\frac{g}{l}\\sin{y} + F_D\\cos{\\Omega_Dt})\\Delta t \\\\\ny_{i+1} = y_i + (v_i + (- qv - \\frac{g}{l}\\sin{y} + F_D\\cos{\\Omega_Dt})\\Delta t)\\Delta t\n\\end{equation}\n\nLet $L=1$, $Fd=0.5$, $\\Omega_D=10$, $g=9.8$, $q=0.1$, $v_0=0$, $y_0=10$, at $t=0$ to $t=20$ and $\\Delta t=0.005$\n\n\n```python\nL = 1\nFd = 0.5\nomegaD = 10\ng = 9.8\nq = 0.1\nv0, y0 = 0, 10\nt0, tf = 0, 20\ndt = 0.005\n\nf = lambda y,v,t: -q*v-(g/L)*np.sin(y)+Fd*np.cos(omegaD*t)\n\nsolEu = Euler2nd(f=f, t0=t0, tf=tf, y0=y0, v0=v0, dt=dt, Cromer= 'True')\nt, y = solEu[0], solEu[1]\n\nplt.plot(t, y, 'b.', label = 'Euler-Cromer')\nplt.title('Pendulum')\nplt.legend()\nplt.xlabel('time')\nplt.ylabel('y')\nplt.show()\n```\n\n## 2nd - Order Runge Kutta \n\n\n```python\ndef RK2(f, t0, tf, y0, v0, dt):\n \n t = np.arange(t0, tf+dt, dt)\n n = len(t)\n \n y = np.zeros(n)\n v = np.zeros(n)\n \n y[0] = y0\n v[0] = v0\n \n for i in range(n-1):\n v[i+1] = v[i] + f(y[i],v[i],t[i])*dt\n y[i+1] = y[i] + v[i+1]*dt\n \n return t, v, y\n```\n\n### Linear Motion with Air Drag \n\nUse RK2 to approximate the motion of the falling parachutist:\n\n\\begin{equation}\n\\frac{dv}{dt} = g - Cv\n\\end{equation}\n\nThe constants are the same with the Linear Motion problem stated previously under the Euler Method section\n\n\n```python\nC = 1\ng = 9.8\ny0, v0 = 0, 100\nt0, tf = 0, 5\ndt = 0.05\n\nf = lambda y,v,t: g-C*(v + (dt/2.)*(g-C*v))\n\nsol = RK2(f, t0, tf, y0, v0, dt)\nt, v = sol[0], sol[1]\n\nvexact = np.exp(-C*t)*(v0*C-g+g*np.exp(C*t))/C\n\nplt.plot(t, v, 'b.', label = 'RK2')\nplt.plot(t, vexact, 'r', label = 'Exact')\nplt.title('Linear Motion with Air Drag')\nplt.legend()\nplt.xlabel('time')\nplt.ylabel('v')\nplt.show()\n```\n\n### Damped Harmonic Oscillator\n\nUse the RK2 method to estimate the position of the damped harmonic oscillator at any time t.\n\n\\begin{equation}\nm\\frac{d^2x}{dt^2} + C\\frac{dx}{dt} + kx = 0\n\\end{equation}\n\nThe constants used are the same with the problem on the Euler-Cromer section\n\n\n```python\nm = 1\nC = 1\nk = 10\nv0 = 0\nx0 = 1\nt0, tf = 0, 20\ndt = 0.01\n\nf = lambda y,v,t: -((C/m)*(v - (dt/2.)*((C/m)*v + (k/m)*y)) + (k/m)*y)\n\nsol = RK2(f=f, t0=t0, tf=tf, y0=x0, v0=v0, dt=dt)\nt, x = sol[0], sol[2]\n\nxexact = (1./39.)*np.exp(-t/2.)*(39*np.cos(0.5*t*np.sqrt(39)) + \\\n np.sqrt(39)*np.sin(0.5*t*np.sqrt(39))) \n\nplt.plot(t, x, 'b.', label = 'RK2')\nplt.plot(t, xexact, 'r', label = 'Exact')\nplt.title('Damped Harmonic Oscillator')\nplt.legend()\nplt.xlabel('time')\nplt.ylabel('x')\nplt.show()\n```\n\n### Pendulum\n\nConsider a pendulum of length $L$ and mass $m$ which is acted upon by a frictional force and an external driving force. Let the driving force be a sinusoidally varying force with constant amplitude $F_D$ and driving frequency $\\Omega_D$. Assume that the frictional force is proportional to the pendulum’s velocity with a constant damping factor $q$. (1) Write down the differential equation that describes the motion of the damped, driven pendulum. From the differential equation, write down the equations that approximate the solution using (2) Euler-Cromer, (3) 2nd-order Runge-Kutta, and (4) Verlet algorithms.\n\n\\begin{equation}\n\\frac{d^2y}{dt^2} + q\\frac{dy}{dt} + \\frac{g}{l}\\sin{y} = F_D\\cos{\\Omega_D}\n\\end{equation}\n\n\\begin{equation}\nv_{i+1} = v_i + (- q(v_i + \\frac{\\Delta t}{2}(- qv - \\frac{g}{l}\\sin{y} + F_D\\cos{\\Omega_Dt}) ) - \\frac{g}{l}\\sin{y} + F_D\\cos{\\Omega_D(t + \\frac{dt}{2}}))\\Delta t \\\\\ny_{i+1} = y_i + (v_i + (- q(v_i + \\frac{\\Delta t}{2}(- qv - \\frac{g}{l}\\sin{y} + F_D\\cos{\\Omega_Dt}) ) - \\frac{g}{l}\\sin{y} + F_D\\cos{\\Omega_D(t + \\frac{dt}{2}}))\\Delta t)\\Delta t\n\\end{equation}\n\nThe constants used are the same as that of the Pendulum problem under the Euler-Cromer section\n\n\n```python\nL = 1\nFd = 0.5\nomegaD = 10\ng = 9.8\nq = 0.1\nv0, y0 = 0, 10\nt0, tf = 0, 20\ndt = 0.005\n\nf = lambda y,v,t: -q*(v + (dt/2.)*(-q*v - (g/L)*np.sin(y) + Fd*np.cos(omegaD*t))) - \\\n (g/L)*np.sin(y) + Fd*np.cos(omegaD*(t+dt/2.))\n\nsolRK = RK2(f=f, t0=t0, tf=tf, y0=y0, v0=v0, dt=dt)\nt, y = solRK[0], solRK[2]\n\nplt.plot(t, y, 'b.', label = 'RK2')\nplt.title('Pendulum')\nplt.legend()\nplt.xlabel('time')\nplt.ylabel('y')\nplt.show()\n```\n\n## Verlet Method\n\n### Pendulum\n\nConsider a pendulum of length $L$ and mass $m$ which is acted upon by a frictional force and an external driving force. Let the driving force be a sinusoidally varying force with constant amplitude $F_D$ and driving frequency $\\Omega_D$. Assume that the frictional force is proportional to the pendulum’s velocity with a constant damping factor $q$. (1) Write down the differential equation that describes the motion of the damped, driven pendulum. From the differential equation, write down the equations that approximate the solution using (2) Euler-Cromer, (3) 2nd-order Runge-Kutta, and (4) Verlet algorithms.\n\n\\begin{equation}\n\\frac{d^2y}{dt^2} + q\\frac{dy}{dt} + \\frac{g}{l}\\sin{y} = F_D\\cos{\\Omega_D}\n\\end{equation}\n\n\\begin{equation}\ny_{i+1} = (2y_i - y_{i-1} + \\frac{q}{2}y_{i-1}\\Delta t + (-\\frac{g}{l}\\sin{y} + F_D\\cos{\\Omega_Dt})\\Delta t^2)(1 - \\frac{q}{2}\\Delta t)\n\\end{equation}\n\nThe constants used are the same with the Pendulum problem under the Euler Cromer section\n\n\n```python\ndef Verlet(f1, f2, f3, t0, tf, y0, v0, dt):\n \n t = np.arange(t0, tf+dt, dt)\n n = len(t)\n \n y = np.zeros(n)\n v = np.zeros(n)\n \n v1 = v0 + f1*dt\n y1 = y0 + v0*dt\n \n y[0], y[1] = y0, y1\n v[0], v[1] = v0, v1\n \n \n for i in range(1,n-1):\n y[i+1] = (2.*y[i] - y[i-1] + f3*y[i-1]*dt + (f2(y[i],t[i]))*(dt**2))*(1. - f3*dt)\n \n return t, y\n```\n\n\n```python\nL = 1\nFd = 0.5\nomegaD = 10\ng = 9.8\nq = 0.1\nv0, y0 = 0, 10\nt0, tf = 0, 20\ndt = 0.005\n\nf1 = (-q*v0-(g/L)*np.sin(y0)+Fd*np.cos(omegaD*t0))\nf2 = lambda y, t: (-(g/L)*np.sin(y) + Fd*np.cos(omegaD*t))\nf3 = q/2.\n\nsolVer = Verlet(f1, f2, f3, t0, tf, y0, v0, dt)\nt, y = solVer[0], solVer[1]\n\nplt.plot(t, y, 'b.', label = 'Verlet')\nplt.title('Pendulum')\nplt.legend()\nplt.xlabel('time')\nplt.ylabel('y')\nplt.show()\n```\n\n\n```python\nt1, y1 = solEu[0], solEu[1]\nt2, y2 = solRK[0], solRK[2]\nt3, y3 = solVer[0], solVer[1]\n\nplt.plot(t1, y1, 'b', label = 'Euler-Cromer')\nplt.plot(t2, y2, 'r--', label = 'RK2')\nplt.plot(t3, y3, 'g:', label = 'Verlet')\nplt.title('Pendulum')\nplt.legend()\nplt.xlabel('time')\nplt.ylabel('y')\nplt.show()\n```\n", "meta": {"hexsha": "c157f5ab9678c9c47885639f98d5b48b7db27626", "size": 303501, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Numerical Method Codes/ODEs.ipynb", "max_stars_repo_name": "lindleezy/Numerical-Methods", "max_stars_repo_head_hexsha": "1cb8f65d09f9ae7b00e6530a6960055dcc6c1174", "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": "Numerical Method Codes/ODEs.ipynb", "max_issues_repo_name": "lindleezy/Numerical-Methods", "max_issues_repo_head_hexsha": "1cb8f65d09f9ae7b00e6530a6960055dcc6c1174", "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": "Numerical Method Codes/ODEs.ipynb", "max_forks_repo_name": "lindleezy/Numerical-Methods", "max_forks_repo_head_hexsha": "1cb8f65d09f9ae7b00e6530a6960055dcc6c1174", "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": 291.8278846154, "max_line_length": 41304, "alphanum_fraction": 0.9258684485, "converted": true, "num_tokens": 5386, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9702399094961359, "lm_q2_score": 0.8791467627598856, "lm_q1q2_score": 0.8529832755339722}} {"text": "# Contitional probability\n\nLet us assume that we have two random variables $X$ and $Y$. Both are generated by rolling fair six-sided dice, so the possible outcomes are:\n\n\\begin{align}\nPr(X=1) & = \\frac{1}{6} & Pr(Y=1) & = \\frac{1}{6} \\\\\nPr(X=2) & = \\frac{1}{6} & Pr(Y=2) & = \\frac{1}{6} \\\\\nPr(X=3) & = \\frac{1}{6} & Pr(Y=3) & = \\frac{1}{6} \\\\\nPr(X=4) & = \\frac{1}{6} & Pr(Y=4) & = \\frac{1}{6} \\\\\nPr(X=5) & = \\frac{1}{6} & Pr(Y=5) & = \\frac{1}{6} \\\\\nPr(X=6) & = \\frac{1}{6} & Pr(Y=6) & = \\frac{1}{6} \n\\end{align}\n\nFurther, we assume that $X$ and $Y$ are independent. \n\nSo, if one defines notation $Pr(X=x \\cap Y=y)$ to mean the probability that $X=x$ and $Y=y$\nthen $X$ and $Y$ being independent means that $Pr(X=x \\cap Y=y) = Pr(X=x)Pr(Y=y)$.\n\nFor example, $Pr(X=1 \\cap Y=2) = Pr(X=1)Pr(Y=2) = \\frac{1}{6} \\frac{1}{6} = \\frac{1}{36}$.\n\n\nWith this notation in mind, we define the conditional probality of $X=x$ given $Y=y$, denoted by $Pr(X=x | Y=y)$, as:\n\n$$\nPr(X=x | Y=y) = \\frac{Pr(X=x \\cap Y=y)}{Pr(Y=y)}\n$$\n\nIf $X$ and $Y$ are independent then the conditional probability is \n\n$$\nPr(X=x | Y=y) = \\frac{Pr(X=x \\cap Y=y)}{Pr(Y=y)} = \\frac{Pr(X=x) Pr(Y=y)}{Pr(Y=y)} = Pr(X=x). \n$$\n\nIn other words, knowing $Y=y$ does not provide any information about $Pr(X=x)$.\n\nNote, since\n\n$$\nPr(X=x | Y=y) = \\frac{Pr(X=x \\cap Y=y)}{Pr(Y=y)}\n$$\n\nwe also have that\n\n$$\nPr(X=x | Y=y)Pr(Y=y) = Pr(X=x \\cap Y=y).\n$$\n\nSo, we have the following identity\n\n$$\nPr(X=x | Y=y)Pr(Y=y) = Pr(X=x \\cap Y=y) = Pr(Y=y \\cap X=x) = Pr(Y=y | X=x)Pr(X=x).\n$$\n\n\n\n# Example\n\nThings get more interesting when you have dependent random variables so let us define the random variables $Z$ by setting $Z=X+Y$. All of the possible values for $Z$ as a function of $Y$ and $Z$ can be seen in the following table.\n\nx\\Y | 1 | 2 | 3 | 4 | 5 | 6 \n-----|:---|:--|:--|:--|:--|:--\n1 | 2 | 3 | 4 | 5 | 6 | 7 \n2 | 3 | 4 | 5 | 6 | 7 | 8 \n3 | 4 | 5 | 6 | 7 | 8 | 9 \n4 | 5 | 6 | 7 | 8 | 9 | 10 \n5 | 6 | 7 | 8 | 9 | 10| 11 \n6 | 7 | 8 | 9 | 10| 11| 12 \n\nLet us compute the\n\n$$\nPr(Z=5 \\cap X=2).\n$$\n\nNote there are two ways to proceed since\n\n$$\nPr(Z=5 \\cap X=2) = Pr(Z=5 | X=2) Pr(X=2) = Pr(X=2 | Z=5) Pr(Z=5)\n$$\n\nDoing it the first way we have that\n\n\\begin{align}\nPr(Z=5 \\cap X=2) &= Pr(Z=5 | X=2) Pr(X=2) \\\\\n &= Pr(Y=3) Pr(X=2) \\\\\n &= \\frac{1}{6} \\frac{1}{6} \\\\\n &= \\frac{1}{36} \n\\end{align}\n\nWe use the face that $Pr(Z=5 | X=2) = Pr(Y=3)$ since, given that $X=2$, $Z=5$ if, and only if, $Y=3$.\n\nDoing it the second way we have that\n\n\\begin{align}\nPr(X=2 \\cap Z=5) &= Pr(X=2 | Z=5) Pr(Z=5) \\\\\n &= \\frac{1}{4} \\frac{4}{36} \\\\\n &= \\frac{1}{36} \n\\end{align}\n\nWe use the face that $Pr(Z=5)$ in 4 of the 36 entries in the table above giving us that\n$Pr(Z=5) = \\frac{4}{36}$. We also know that the four places where $Z=5$ occur when\n\n\\begin{align}\nX=1 ,\\;& Y = 4 \\\\\nX=2 ,\\;& Y = 3 \\\\\nX=3 ,\\;& Y = 2 \\\\\nX=4 ,\\;& Y = 1 \n\\end{align}\n\nand $X=2$ in exactly one of those places, so $Pr(X=2 | Z=5) = \\frac{1}{4}$.\n\nThe two ways match!\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "516962c6b036565d05b2817e07a3f3d00817e995", "size": 5279, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "lectures/05 Basic Statistics, Probability, and Linear Algebra/ConditionalProbabilty.ipynb", "max_stars_repo_name": "thomasmeagher/DS-501", "max_stars_repo_head_hexsha": "b5c697c3bc4f44903af16219f242b5728c9a82d1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2017-07-27T02:52:06.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-01T09:25:14.000Z", "max_issues_repo_path": "lectures/05 Basic Statistics, Probability, and Linear Algebra/ConditionalProbabilty.ipynb", "max_issues_repo_name": "thomasmeagher/DS-501", "max_issues_repo_head_hexsha": "b5c697c3bc4f44903af16219f242b5728c9a82d1", "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/05 Basic Statistics, Probability, and Linear Algebra/ConditionalProbabilty.ipynb", "max_forks_repo_name": "thomasmeagher/DS-501", "max_forks_repo_head_hexsha": "b5c697c3bc4f44903af16219f242b5728c9a82d1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2017-07-18T21:50:17.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-01T09:25:18.000Z", "avg_line_length": 28.3817204301, "max_line_length": 240, "alphanum_fraction": 0.4328471301, "converted": true, "num_tokens": 1311, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750440288019, "lm_q2_score": 0.8947894639983209, "lm_q1q2_score": 0.8529804656895075}} {"text": "# 2.9 Model Selection and the Bias-Variance Tradeoff\n\nAll the models described have a *smoothing* or *complexity* parameter that has to be determined:\n\n- the multiplier of the penalty term;\n\n- the width of the kernel\n\n- or the number of basis functions\n\nWe cannont use RSS on the training data to determine these parameters, since we would always pick those that gave interpolating fits and have zero residuals.\n\nThe kNN regression fit $\\hat{f_k}(x_0)$ illustrates the competing forces that effect the predictive ability of such approximations. Suppose the data arise from a model $Y = f(X) + \\varepsilon$ with $E(\\varepsilon)=0$ and $Var(\\varepsilon) = \\sigma^2$. We assume that the values of $x_i$ in the sample are fixed. The EPE at $x_0$:\n\n$$\n\\begin{align}\nEPE_k(x_0) &= E[(Y - \\hat{f_k}(x_0))^2|X=x_0]\\\\\n&=\\sigma^2 + [Bias^2(\\hat{f_k}(x_0)) + Var_\\tau(\\hat{f_k}(x_0))]\\\\\n&=\\sigma^2 + \\left[f(x_0) - \\frac{1}{k}\\sum_{l=1}^k{f(x_{(l)})} \\right]^2 + \\frac{\\sigma^2}{k}\n\\end{align}\n$$\n\nThe subscripts in parentheses ($l$) indicates the sequence of nearest neighbors to $x_0$. There are three terms in this expression:\n\n1. $\\sigma^2$ is the *irreducible* error - is beyond our control, even if we know the true $f(x_0)$.\n\n2. The bias term and the expected value of the estimate - $[E_\\tau(\\hat{f_k}(x_0))-f(x_0)]^2$ - where the expected averages the randomness in the training data. This term increases with $k$ if the function is smooth.\n\n3. The variance term and it decreases as the inverse of k. The expected value of the variance is: \n\n$$\n\\begin{align}\nVar_\\tau(\\hat{f_k}(x_0)) &= E_\\tau\\left[\\hat{f_k}(x_0) - E_\\tau(\\hat{f_k}(x_0))\\right]^2\\\\\n&= E_\\tau\\left[\\frac{1}{k}\\sum_{l=1}^k (f(x_{(l)}) + \\varepsilon_l) - \\frac{1}{k}\\sum_{l=1}^k{f(x_{(l)})}\\right]^2\\\\\n&= E_\\tau\\left[\\frac{1}{k}\\sum_{l=1}^k \\varepsilon_l\\right]^2\\\\\n&= \\frac{1}{k^2}E_\\tau\\left[\\sum_{l=1}^k \\varepsilon_l\\right]^2\\\\\n&= \\frac{1}{k^2}E_\\tau\\left[\\sum_{l=1}^k \\varepsilon_l^2\\right]\\\\\n&= \\frac{\\sigma^2}{k}\n\\end{align}\n$$\n\nAs the *model complexity* of our procedure is increased, the variance tends to increase and the squared bias tends to decrease. The opposite behavior occurs as the model complexity is decreased.\n", "meta": {"hexsha": "ee234c4cf8d92ea490c874357a3f6bffac416d94", "size": 3224, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "chapter-02/2.9-model-selection-and-the-bias-variance-tradeoff.ipynb", "max_stars_repo_name": "leduran/ESL", "max_stars_repo_head_hexsha": "fcb6c8268d6a64962c013006d9298c6f5a7104fe", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 360, "max_stars_repo_stars_event_min_datetime": "2019-01-28T14:05:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T00:11:21.000Z", "max_issues_repo_path": "chapter-02/2.9-model-selection-and-the-bias-variance-tradeoff.ipynb", "max_issues_repo_name": "leduran/ESL", "max_issues_repo_head_hexsha": "fcb6c8268d6a64962c013006d9298c6f5a7104fe", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-07-06T16:51:40.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-06T16:51:40.000Z", "max_forks_repo_path": "chapter-02/2.9-model-selection-and-the-bias-variance-tradeoff.ipynb", "max_forks_repo_name": "leduran/ESL", "max_forks_repo_head_hexsha": "fcb6c8268d6a64962c013006d9298c6f5a7104fe", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 79, "max_forks_repo_forks_event_min_datetime": "2019-03-21T23:48:35.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T13:05:10.000Z", "avg_line_length": 40.8101265823, "max_line_length": 343, "alphanum_fraction": 0.5790942928, "converted": true, "num_tokens": 747, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037363973295, "lm_q2_score": 0.9207896704568164, "lm_q1q2_score": 0.8529309121802148}} {"text": "# Frequency folding\n## The relationship between the Fourier transform of a function and the Fourier transform of its sampled function\nConsider the function $f(t)$. The function is sampled with the sampling period $h$ (correspoding to sampling frequency $\\omega_s = \\frac{2\\pi}{h}$) to obtain the sequence $f(kh)$. \nIf $F(\\omega)$ is the Fourier transform of the function $f(t)$ and $F_s(\\omega)$ is the Fourier transform of the sampled signal $f(kh)$, then\n\\begin{equation}\nF_s(\\omega) = \\frac{1}{h} \\sum_{k=-\\infty}^{\\infty} F(\\omega + k\\omega_s)\n\\end{equation}\n\nFrom this we see that the spectrum of a sampled signal is periodic, since the function $F_s(\\omega)$ is periodic with period $\\omega_s$, i.e.\n\\begin{equation}\nF_s(\\omega + m\\omega_s) = \\frac{1}{h} \\sum_{k=-\\infty}^{\\infty} F(\\omega + k\\omega_s + m\\omega_s) = \\frac{1}{h} \\sum_{k=-\\infty}^{\\infty} F(\\omega + (k+m)\\omega_s) = F_s(\\omega)\n\\end{equation}\n\nWe also see that the power of the signal $f(kh)$ at a frequency $\\omega_1$, $0 \\le \\omega \\le \\omega_N$ contains contributions from all frequencies of the original signal at the frequencies \n\\begin{equation}\n\\omega = \\omega_1 + k\\omega_s, \\; k=-\\infty, \\ldots, 0, \\ldots, \\infty \n\\end{equation}\nand\n\\begin{equation}\n\\omega = -\\omega_1 + k\\omega_s, \\; k=-\\infty, \\ldots, 0, \\ldots, \\infty \n\\end{equation}\nWe say that $\\omega_1$ is the alias of all these frequencies. The lowest such alias frequency is the frequency\n\\begin{equation}\n\\omega = -\\omega_1 + \\omega_s,\n\\end{equation}\nwhich can be written\n\\begin{equation}\n\\omega = |\\omega_1 - \\omega_s| = | \\omega_1 + \\omega_N - \\omega_N - \\omega_s | = | (\\omega_a + \\omega_N) - \\omega_s - \\omega_N| = | (\\omega_1 + \\omega_N)\\, \\mathrm{mod}\\, \\omega_s - \\omega_N|.\n\\end{equation}\n\n\n```python\n%matplotlib notebook\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef spectrum(x,h):\n \"\"\" Computes spectrum using np.fft.fft Returns frequency in rad/s from -\\omega_N to \\omega_N\"\"\"\n wN = np.pi/h # The Nyquist frequency\n N = len(x)\n X = np.fft.fft(x) # Computes the Fourier transform\n Xpos = X[:N/2] # Positive part of the spectrum\n Xneg = X[N/2:] # Negative part. Obs: for frequencies wN up to ws\n wpos = np.linspace(0, wN, N/2) # Positive frequencies, goes from 0 to wN\n\n W = np.hstack((-wpos[::-1], wpos))\n XX = np.hstack((Xneg, Xpos))\n \n return (XX, W)\n\n# Assume too slow sampling of signal consisting of two high-frequency sinusoids\nws = 16 # Sampling frequency in rad/s\nwN = ws/2\nh = np.pi/wN\n\nw1 = 10 # rad/s\nw2 = w1+1*ws # rad/s\n\nw1Alias = np.abs( (w1+wN) % ws - wN )\nw2Alias = np.abs( (w1+wN) % ws - wN )\n\nM = 4000 # Number of samples in the over-sampled (\"continuous\") signal \nt = np.linspace(0, 60*2*np.pi/w1, M) # 60 periods of the slowest sinusoid\ny = np.sin(w1*t) + np.sin(w2*t) # Continuous time (sort of) signal\n\n\nN = 400 # Number of samples to take \nts = np.arange(N)*h\nys = np.sin(w1*ts) + np.sin(w2*ts) # Sampled signal\n\n(Y,W) = spectrum(y,t[1]-t[0]) # get spectrum (from FFT) of the \"continuous\" signal\n(Ys, Ws) = spectrum(ys, h) # Spectrum of discrete signal\n\nplt.figure(figsize=(10,7))\nplt.subplot(2,1,1)\nplt.plot(W, np.real(Y))\nplt.plot(Ws, np.real(Ys))\nplt.plot([wN, wN], [-50, 150], 'k--')\nplt.plot([-wN, -wN], [-50, 150], 'k--')\nplt.xlim((-1.2*w2, 1.2*w2))\nplt.xticks((-w2, -w1, -wN, -w1Alias, w1Alias, wN, w1, w2))\nplt.ylim((-500, 500))\nplt.ylabel('Real part')\nplt.subplot(2,1,2)\nplt.plot(W, np.imag(Y))\nplt.plot(Ws, np.imag(Ys))\nplt.plot([wN, wN], [-1500, 1500], 'k--')\nplt.plot([-wN, -wN], [-1500, 1500], 'k--')\nplt.xlim((-1.2*w2, 1.2*w2))\nplt.xticks((-w2, -w1, -wN, -w1Alias, w1Alias, wN, w1, w2))\n\nplt.ylim((-400, 400))\n#plt.xticks((-10, -5, -1, 0, 1, 5, 10))\nplt.ylabel('Imaginary part')\nplt.xlabel(r'$\\omega$ [rad/s]')\n\nplt.legend(('Continuous', 'Sampled', 'Nyquist frequency'), loc=1, borderaxespad=0.)\n\n```\n\n\n \n\n\n\n\n\n\n\n\n\n \n\n\n\n\n```python\nplt.figure(figsize=(10,5))\nplt.plot(t,y, color=(0.7,0.7,1))\nplt.stem(ts[:20], ys[:20],linefmt='r--', markerfmt='ro', basefmt = 'r-')\nplt.xlim((0,7.8))\nplt.xlabel('t [s]')\n```\n\n\n \n\n\n\n\n\n\n\n\n\n \n\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "42e937bb76d2f7a5fa717f40b847688ad0bf7644", "size": 229600, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "sampling-and-aliasing/notebooks/Frequency-folding.ipynb", "max_stars_repo_name": "kjartan-at-tec/mr2007-computerized-control", "max_stars_repo_head_hexsha": "16e35f5007f53870eaf344eea1165507505ab4aa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-11-07T05:20:37.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-22T09:46:13.000Z", "max_issues_repo_path": "sampling-and-aliasing/notebooks/Frequency-folding.ipynb", "max_issues_repo_name": "alfkjartan/control-computarizado", "max_issues_repo_head_hexsha": "5b9a3ae67602d131adf0b306f3ffce7a4914bf8e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-06-12T20:44:41.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-12T20:49:00.000Z", "max_forks_repo_path": "sampling-and-aliasing/notebooks/Frequency-folding.ipynb", "max_forks_repo_name": "kjartan-at-tec/mr2007-computerized-control", "max_forks_repo_head_hexsha": "16e35f5007f53870eaf344eea1165507505ab4aa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-03-14T03:55:27.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-14T03:55:27.000Z", "avg_line_length": 132.4106113033, "max_line_length": 93913, "alphanum_fraction": 0.8094555749, "converted": true, "num_tokens": 1494, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768635777511, "lm_q2_score": 0.9032942158155877, "lm_q1q2_score": 0.8528694995766858}} {"text": "# Truncation Error Analysis via sympy\n\nCopyright (C) 2020 Andreas Kloeckner\n\n
\nMIT License\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n
\n\n\n```python\nimport sympy as s\ns.init_printing()\n```\n\nEstablish some variables that we'll need:\n\n\n```python\nu = s.Function(\"u\")\na, x, t, h_x, h_t = s.symbols(\"a, x, t, h_x, h_t\")\nxi_1, xi_2, tau = s.symbols(\"xi1, xi2, tau\")\n```\n\n`taylor` is a utility function that spits out a taylor expansion for $f(x+h)$, optionally including a remainder term, with all variables under our control.\n\n\n```python\ndef taylor(f, x, h, n, remainder_variable=None):\n result = sum(f.diff(x, i)*h**i/s.factorial(i) for i in range(n))\n if remainder_variable:\n result += f.diff(x, n).subs(x, remainder_variable)*h**n/s.factorial(n)\n return result\n```\n\n- Try it out by expanding $u(x+h_x,t)$\n- Vary the order\n- Expand $u(x,t+h_t)$ instead\n\n\n```python\n#clear\ntaylor(u(x,t), x, h_x, 3, xi)\n```\n\nAssign the PDE we're solving to `pde`:\n\n\n```python\n#clear\npde = u(x, t).diff(t) + a * u(x, t).diff(x)\npde\n```\n\nWrite out the scheme we're analyzing, in this case ETCS:\n\n\n```python\netcs = (\n (u(x, t+h_t) - u(x, t))/h_t\n +\n a*(u(x+h_x, t) - u(x-h_x, t))/(2*h_x))\netcs\n```\n\nFollow this general pattern:\n```\netcs\n.subs(u(x, t+h_t), taylor(u(x,t), t, h_t, 2, tau))\n```\nto arrive at the truncation error.\n\n⚠️ Make sure to keep the two $x$ remainder terms separate.\n\n\n```python\n#clear\netcs_taylor = (\n etcs\n .subs(u(x, t+h_t), taylor(u(x,t), t, h_t, 2, tau))\n .subs(u(x+h_x, t), taylor(u(x,t), x, h_x, 3, xi_1))\n .subs(u(x-h_x, t), taylor(u(x,t), x, -h_x, 3, xi_2))\n)\nsp.simplify(etcs_taylor - pde)\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "82e53fc65399eadc6633e7869403c69e1769a097", "size": 32284, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "demos/fd-tdep/Truncation Error Analysis via sympy.ipynb", "max_stars_repo_name": "inducer/numpde-notes", "max_stars_repo_head_hexsha": "80952b692fc16f185042a64d91312b0e53fafe17", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2020-05-31T23:00:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-25T15:08:14.000Z", "max_issues_repo_path": "demos/fd-tdep/Truncation Error Analysis via sympy.ipynb", "max_issues_repo_name": "inducer/numpde-notes", "max_issues_repo_head_hexsha": "80952b692fc16f185042a64d91312b0e53fafe17", "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": "demos/fd-tdep/Truncation Error Analysis via sympy.ipynb", "max_forks_repo_name": "inducer/numpde-notes", "max_forks_repo_head_hexsha": "80952b692fc16f185042a64d91312b0e53fafe17", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2020-08-14T22:49:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-25T15:08:34.000Z", "avg_line_length": 117.8248175182, "max_line_length": 8524, "alphanum_fraction": 0.8360488168, "converted": true, "num_tokens": 789, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.933430805473952, "lm_q2_score": 0.9136765263519308, "lm_q1q2_score": 0.8528538159353252}} {"text": "# Lesson 01 - From Machine Learning to Deep Learning\n\n## Training Logistic classifier\n- Is a Linear Classifier\n\n```\nW X + b = Y\n```\n- W, X are matrices\n- X is input\n- W (Weights) and b (bias) are found by training the model\n- Y vector \n - contains output prediction score for each possible output\n - also known as Logits for Logistic Regression\n - turned into probabilities (by using SoftMax function)\n\n\n```python\nscores = [3.0, 1.0, 0.2]\n```\n\n\n```python\nimport numpy as np\n\ndef softmax(x):\n return np.exp(x) / np.sum(np.exp(x), axis=0)\n```\n\n\n```python\nimport matplotlib.pyplot as plt\n\nx = np.arange(-2.0, 6.0, 0.1)\nscores = np.vstack([x, np.ones_like(x), 0.2 * np.ones_like(x)])\nscores.shape\n```\n\n\n\n\n (3, 80)\n\n\n\n\n```python\nplt.plot(x, softmax(scores).T, linewidth = 2)\nplt.legend(['x', '1', '0.2'])\nplt.show()\n```\n\nIf we increase the magnitude of scores then classifier becomes more confident but if we decrease the size of the outputs then the classifier becomes less confident\n\n\n\n## One Hot encoding\n- Each label would be represented by a vector which is as long as the number of labels and has value 1.0 for the label and 0 for other labels\n- Works not well when we have tens of thousands of labels or more. We have lots of zeros at that time\n- We can find how well we are doing by simply comparing 2 vectors\n\n\nPutting all pieces together we have the following Multinomial Logistic Classification\n\n\n```\nD(S(W * X + b), L)\n```\n\n## Minimizing Cross Entropy\n- Now how do we find the W and b so that our classifier works i.e. D(A, a) is less but D(A, b) is high\n- We can try and minimize the loss when summed over all training data\n\\begin{align}\nL = (1/ N) * \\sum_{i} D(S(WX_{i} + b), L_{i})\n\\end{align}\n\n- We need to calculate the derivative w.r.t to parameters and follow derivative to solution. This is called gradient descent\n\n## Numerical stability\n- You have to worry abut calculating values that are too big or too small whenever doing numerical computation\n\n\n\n```python\na = 10 ** 9\nfor i in range(10 ** 6):\n a += 10 ** (-6)\n \na - 10 ** 9\n```\n\n\n\n\n 0.95367431640625\n\n\n\n- For numerical stability the values involved in our Loss function L should not get too big or too small.\n- A good principle is\n - 0 mean\n - equal variance\n\n\n- For images it is simple to normalize it by \n\\begin{align}\n(R/G/B - 128) / 128\n\\end{align}\n\n- The weights and bias should also be good enough for gradient descent to proceed\n- Many many but a simple way is to take from gaussian distribution with mean 0 and small variance. Higher variance would mean that the our model is opinioninated in the beginning which we don't want. Our model should be uncertain in the beginning and learn from data\n\n- Validation sets are needed because as we iterate we are exposing the test set to classifier through our decisions\n- Using 30000 examples as validation set is good. But if that is a lot of data then we could possibly use cross validation\n\n- Logistic Regression's biggest problem is that it is very difficult to scale\n - Depends on all of data\n - Usually computing the gradient uses 3 times the compute of Loss function\n - In gradient descent we iterate\n - So instead of using all of data we use a small random sample and iterate more. This is called Stochastic Gradient Descent (SGD)\n - SGD is important because it scales well with big data and big models\n \n\n## Helping SGD\n- Momentum\n - Instead of using the current direction we use the knowledge of the general direction in which we are going to decide the current direction in which we want to go\n - \n- Learning Rate average\n - Learing rate should be decreased over time\n", "meta": {"hexsha": "3385f20f9669fbdd8c0487942f3b2b1f2f1eb8a6", "size": 39447, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "udacity_machine_learning_notes/deep_learning/lesson_01/lesson_01.ipynb", "max_stars_repo_name": "anshbansal/anshbansal.github.io", "max_stars_repo_head_hexsha": "9ce6be13b81053e7640ef5b5952e7ed1ee6f2e4f", "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": "udacity_machine_learning_notes/deep_learning/lesson_01/lesson_01.ipynb", "max_issues_repo_name": "anshbansal/anshbansal.github.io", "max_issues_repo_head_hexsha": "9ce6be13b81053e7640ef5b5952e7ed1ee6f2e4f", "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": "udacity_machine_learning_notes/deep_learning/lesson_01/lesson_01.ipynb", "max_forks_repo_name": "anshbansal/anshbansal.github.io", "max_forks_repo_head_hexsha": "9ce6be13b81053e7640ef5b5952e7ed1ee6f2e4f", "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": 166.4430379747, "max_line_length": 32778, "alphanum_fraction": 0.8868101503, "converted": true, "num_tokens": 925, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632876167045, "lm_q2_score": 0.9196425317283918, "lm_q1q2_score": 0.8528427216557909}} {"text": "# Alice's Rose\n\n## Dependencies\n\nThe `import` statement is special... it imports programmer's wisdom!\nThe common usage is to acquire access to python packages.\n\n\n```python\nimport sympy\nimport math\n```\n\n## A Romantic Introduction to Matematical Optimization and to Python\n\nNote: this story was originally told in the book [Optimization](https://press.princeton.edu/books/hardcover/9780691102870/optimization) and the protagonist there is called Samantha, but we stick to the alphabetical order...\n\nAs the story goes, Alice receives a beautiful rose. She has nothing but a lemonade glass to hold the rose and becomes very distressed when the ensemble falls down. \n\nAdding a bit of water helps! Not only that helps the rose, but it also helps the stability: glass, with some water, and rose stands!\n\nAlice thinks: if a bit of water helps, the let us fill the glass! \n\nHowever, it tilts and falls, as in the beginning, just much more wet. \n\nAlice has a problem to solve: what is the _optimal_ level of water for her rose on a lemonade glass?\n\nShe learns from [Archimedes]( https://en.wikipedia.org/wiki/Archimedes) how to compute the _center of gravity_ of the glass with water, which has height\n$h = \\frac{m_w}{m_w+m_g} h_w + \\frac{m_g}{m_w+m_g} h_g$ with:\n\n* $m_w$ the mass of water \n* $m_g$ the mass of glass\n* $h_w$ the height of the center of gravity of the water in the glass\n* $h_g$ the height of the center of gravity of the glass without water \n\nSince Alice's glass is $20$ cm tall, $4$ cm wide and weighs $100$ gram, Alice may fill the glass with water up to height $x$ cm, provided that $0 \\leq x \\leq 20$ since the water must fit in the glass.\n\nThe volume of water is $\\pi r^2 x$ with $r$ the radius of the base, i.e. $r=2$. \nThe volume is therefore $4\\pi x$ cubic centimetres. \n\nSince the density of water can be [taken](https://en.wikipedia.org/wiki/Gram_per_cubic_centimetre) as being $1$ gram per cubic centimeter we have:\n\n* $m_w = 4\\pi x$\n* $m_g = 100$\n* $h_w = \\frac{x}{2}$\n* $h_g = \\frac{20}{2} = 10$ \n\nAnd from here we finally obtain the following formula for the height of the center of gravity of the glass with water:\n\n$$\nh = \\frac{4\\pi x}{4\\pi x + 100} \\frac{x}{2} + \\frac{100}{4\\pi x + 100} 10 = \\frac{4\\pi x^2 + 2000}{8\\pi x + 200}\n$$\n\nAlice's problem is therefore:\n\n$$\n\\begin{array}{rl}\n\\min & \\frac{4\\pi x^2 + 2000}{8\\pi x + 200} \\\\\ns.t. & x \\geq 0 \\\\\n & x \\leq 20 \\\\\n\\end{array}\n$$\n\n## Analytical solution\n\nAlice learns from [Fermat]( https://en.wikipedia.org/wiki/Pierre_de_Fermat) that for a function to reach its highest and lowest points inside its domain the derivative must vanish. \n\nThis is a good moment to play with symbolic mathematics in python, we will use [sympy](https://www.sympy.org/en/index.html).\n\n### With $\\pi$ as a number\n\n\n```python\n# x is a symbol and pi is a number\nx = sympy.Symbol('x')\npi = math.pi\n\n# h is a function of x, and hprime its derivative \nh = (4*pi*x**2 + 2000)/(8*pi*x+200)\nhprime = sympy.diff(h, x)\n\n# sol is(are) the value(s) of x that solve hprime(x) == 0\nsol = sympy.solveset(hprime, x)\nsol\n```\n\n\n\n\n$\\displaystyle \\left\\{-22.8735335189926, -7.95774715459477, 6.95803920980307\\right\\}$\n\n\n\nAbove we see that the equation $h^\\prime(x) = 0$ has two solutions: one negative and one positive. \nObviously, only the positive may be feasible for Alice. \nAnd, since its value is between $0$ and $20$, it is indeed feasible. \n\nYou may recall that the sign of the second derivative tells you whether the root of the first derivative is a *maximum*, a *minimum* or a *saddle point*.\n\n\n```python\nopt = max(sol)\nsympy.diff(hprime, x).subs(x,opt).evalf()\n```\n\n\n\n\n$\\displaystyle 0.0670430626699561$\n\n\n\nSince $h^{\\prime\\prime}(\\text{opt}) > 0$ it is indeed a (local) **minimum**.\n\n### With $\\pi$ as a symbol\n\n\n```python\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 = (4*pi*x**2 + 2000)/(8*pi*x + 200)\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### From a symbolic $\\pi$ to a numeric $\\pi$\n\n\n```python\ns = max(solution.subs(pi, math.pi).evalf())\nprint(s)\n```\n\n 6.95803920980307\n\n\n### A picture says more than thousand words\n\n\n```python\nimport matplotlib.pyplot as plt\nimport numpy as np\n \ndef plot_alice(h, s, start, stop, width=18, height=8):\n\n plt.rcParams[\"figure.figsize\"] = (18,8)\n\n x = sympy.Symbol('x')\n f = sympy.lambdify(x, h.subs( pi, math.pi))\n\n x = np.linspace(start=start,stop=stop,num=100) \n y = f(x)\n\n plt.plot(x,y,label='$'+sympy.latex(h)+'$',linewidth=3)\n plt.plot(s,f(s), 'ro', label='optimum', markersize=12)\n\n plt.legend()\n plt.show() \n```\n\n\n```python\nplot_alice( h, s, 0, 20 )\n```\n\n## What if we only care about the numerical solution?\n\n### Introducing `pyomo`\n\nThis is the moment to meet:\n * mathematical models expressed in `python`, using `pyomo`,\n * powerful numerical optimization algorithms and how to use them. \n\nWe will see that `pyomo` completely separates modeling from solving, which allows us to switch solver without recoding! \n\n### Notebook dependencies requiring installation on `colab`\n\nNote that [this notebook](https://nbviewer.jupyter.org/github/jckantor/ND-Pyomo-Cookbook/blob/master/notebooks/01.02-Running-Pyomo-on-Google-Colab.ipynb) explains how to run `Pyomo` on Google Colab. \nFor a complete overview please check the [cookbook](https://jckantor.github.io/ND-Pyomo-Cookbook/).\n\n\n```python\nimport shutil\nif not shutil.which('pyomo'):\n !pip install -q pyomo\n assert(shutil.which('pyomo'))\n```\n\n\n```python\nimport pyomo.environ as pyo\n\nalice = pyo.ConcreteModel('Alice')\nalice.h = pyo.Var(bounds=(0,20))\n\n@alice.Objective(sense=pyo.minimize)\ndef cog(m):\n return (4*math.pi*alice.h**2 + 2000)/(8*math.pi*alice.h + 200)\n\nalice.pprint()\n```\n\n 1 Var Declarations\n h : Size=1, Index=None\n Key : Lower : Value : Upper : Fixed : Stale : Domain\n None : 0 : None : 20 : False : True : Reals\n \n 1 Objective Declarations\n cog : Size=1, Index=None, Active=True\n Key : Active : Sense : Expression\n None : True : minimize : (12.566370614359172*h**2 + 2000)/(25.132741228718345*h + 200)\n \n 2 Declarations: h cog\n\n\nWe will use `ipopt`. We refer again to [this notebook](https://nbviewer.jupyter.org/github/jckantor/ND-Pyomo-Cookbook/blob/master/notebooks/01.02-Running-Pyomo-on-Google-Colab.ipynb) explains how to run `Pyomo` **and how to install solvers** on Google Colab. For a complete overview please check the [cookbook](https://jckantor.github.io/ND-Pyomo-Cookbook/).\n\n\n```python\nimport sys\nif 'google.colab' in sys.modules:\n !wget -N -q 'https://ampl.com/dl/open/ipopt/ipopt-linux64.zip'\n !unzip -o -q ipopt-linux64\n```\n\n\n```python\nresults = pyo.SolverFactory('ipopt').solve(alice)\nprint(results.solver.status, results.solver.termination_condition )\nalice.display()\n```\n\n ok optimal\n Model Alice\n \n Variables:\n h : Size=1, Index=None\n Key : Lower : Value : Upper : Fixed : Stale : Domain\n None : 0 : 6.95803921230998 : 20 : False : False : Reals\n \n Objectives:\n cog : Size=1, Index=None, Active=True\n Key : Active : Value\n None : True : 6.95803920980307\n \n Constraints:\n None\n\n\n## Conclusion\n\nThis notebook shows how to solve Alice's problem: finding the most stable amount of water in a vase. \n\nThe notebook shows how to solve the problem analytically with `sympy`, how to use `matplotlib` to visualize the function and the optimum. And how to model Alice's problem on `pyomo` and solve it with `ipopt` both at [neos](https://neos-server.org/neos/solvers/index.html) and \"locally\" at your own Colab session.\n\n\n## Last remarks\n\nThis notebook deferred installation of the packages needed to the moment that we needed them. This was deliberate, but subsequent notebooks will normally list all dependencies on their top part, which we often call the _preamble_. Furthermore, the `colab' dependencies will be streamlined in future notebooks. \n\n\n```python\n\n```\n", "meta": {"hexsha": "da9a0b62db926cd1f52bae0ec1d6e609700379c0", "size": 55255, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "_build/html/_sources/notebooks/01/alice-rose.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": "_build/html/_sources/notebooks/01/alice-rose.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": "_build/html/_sources/notebooks/01/alice-rose.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": 96.0956521739, "max_line_length": 39248, "alphanum_fraction": 0.8459324948, "converted": true, "num_tokens": 2436, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474194456936, "lm_q2_score": 0.8933093946927837, "lm_q1q2_score": 0.8527955084100606}} {"text": "# Solving Linear Systems: Direct Methods\n
This notebook by Xiaozhou Li is licensed under a Creative Commons Attribution 4.0 International License. \nAll code examples are also licensed under the [MIT license](http://opensource.org/licenses/MIT).\n\n\n```python\n%matplotlib inline\nimport numpy as np\nfrom scipy.linalg import lu\n```\n\n## Gaussian Elimination\n\nThe simplest version of Gaussian Elimination only involves two operations as follows:\n* Add or substrct a muliple of one equation from another.\n* Multiply an equation by a nonzero constant.\n\n### Solving a linear system by Gaussian elimination\nThe general form of a linear system for $n$ equations in $n$ unknown can be wriiten as\n\\begin{equation}\n\\begin{pmatrix}{a_{11}} & {a_{12}} & {\\cdots} & {a_{1 n}} \\\\ {a_{21}} & {a_{22}} & {\\cdots} & {a_{2 n}} \\\\ {\\vdots} & {\\vdots} & {} & {\\vdots} \\\\ {a_{n 1}} & {a_{n 2}} & {\\cdots} & {a_{n n}}\\end{pmatrix}\\begin{pmatrix}{x_{1}} \\\\ {x_{2}} \\\\ {\\vdots} \\\\ {x_{n}}\\end{pmatrix}=\\begin{pmatrix}{b_{1}} \\\\ {b_{2}} \\\\ {\\vdots} \\\\ {b_{n}}\\end{pmatrix}\n\\end{equation}\n \nTo solve this linear system by Gaussian elimination \n1. Using the allowed row operations to eliminate the system to an upper triangular system\n\\begin{equation}\n\\begin{pmatrix}{a_{11}} & {a_{12}} & {\\cdots} & {a_{1 n}} & {b_{1}} \\\\ {} & {a_{22}^{(1)}} & {\\cdots} & {a_{2 n}^{(1)}} & {b_{2}^{(1)}} \\\\ {} & {} & {\\ddots} & {\\vdots} & {\\vdots} \\\\ {} & {} & {} & {a_{n n}^{(n-1)}} & {b_{n}^{(n-1)}}\\end{pmatrix}\n\\end{equation}\n2. Using the back substituion (backsolving) to solve the upper triangular system, \n\\begin{align}\nx_{n}=& \\frac{b_{n}^{(n-1)}}{a_{n-1}^{(n-1)}} \\\\ x_{k}=& \\frac{b_{k}^{(k-1)}-\\sum_{j=k+1}^{n} a_{k j}^{(k-1)} x_{j} }{a_{k k}^{(k-1)}}, \\quad k=n-1, \\ldots, 1. \n\\end{align}\nHere, assuming $a^{(k-1)}_{kk} \\neq 0,\\,\\, k = 1,\\ldots,n$\n\n**Example**\n\nUsing Gaussian elimination to solve the following linear system\n\\begin{align}\n 10^{-20}x_1 + x_2 & = 1 \\\\\n x_1 + 2x_2 & = 4\n\\end{align}\nThe argumented matrix reads\n\\begin{pmatrix}\n10^{-20} & 1 & 1 \\\\\n1 & 2 & 4\n\\end{pmatrix}\n\n1. Elimination: $\\text{Row}_2 = \\text{Row}_2 - 10^{20}\\times\\text{Row}_1$ \n\n\n```python\nA = np.array([[1e-20, 1, 1], [1, 2, 4]])\nA[1] = A[1] - 10**20*A[0]\nprint (A[1])\n```\n\n [ 0.e+00 -1.e+20 -1.e+20]\n\n\n2. The echelon form of the argumented matrix reads\n\\begin{pmatrix}\n10^{-20} & 1 & 1 \\\\\n0 & -10^{20} & -10^{20}\n\\end{pmatrix}\n3. Using the back substituion, the solution is \n$$ x_2 = 1,\\qquad x_1 = 0.$$\n\n## The $PA = LU$ factorization\n### Partial pivoting\nAt the start of classical Gaussian elimination of $n$ equations in $n$ unknowns, the first step is to use the diagonal element $a_{11}$ as a pivot to eliminate the first column. The partial pivoting protocol consists of comparing numbers before carrying out each elimination step. The largest entry of the first column is located, and its row is swapped with the pivot row, in this case the top row.\n\n**Example**\n\nSolve the following linear system\n\\begin{align}\n 10^{-20}x_1 + x_2 & = 1 \\\\\n x_1 + 2x_2 & = 4\n\\end{align}\n\nThe argumented matrix reads\n\\begin{pmatrix}\n10^{-20} & 1 & 1 \\\\\n1 & 2 & 4\n\\end{pmatrix}\n\n1. Interchange $\\text{Row}_1$ with $\\text{Row}_2$\n\\begin{pmatrix}\n1 & 2 & 4 \\\\\n10^{-20} & 1 & 1 \n\\end{pmatrix}\n2. Elimination: $\\text{Row}_2 = \\text{Row}_2 - 10^{-20}\\times\\text{Row}_1$ \n\n\n```python\nA = np.array([[1, 2, 4], [1e-20, 1, 1]])\nA[1] = A[1] - 10**(-20)*A[0]\nprint (A[1])\n```\n\n [0. 1. 1.]\n\n\n3. The echelon form of the argumented matrix reads\n\\begin{pmatrix}\n1 & 2 & 4 \\\\\n0 & 1 & 1\n\\end{pmatrix}\n4. Using the back substituion, the solution is \n$$ x_2 = 1,\\qquad x_1 = 2.$$\n\n* Solving this equation by the build-in linear solver in numpy:\n\n\n```python\nA = np.array([[1e-20, 1], [1, 2]])\nb = np.array([1, 4])\n\nx = np.linalg.solve(A, b)\nprint (x)\n```\n\n [2. 1.]\n\n\n### Implementation\n#### The $LU$ factorization\n\n\n```python\ndef LU_factor(A):\n A = A.astype(np.float)\n print (A)\n n = len(A)\n for j in range(0,n-1):\n if A[j,j] != 0:\n for i in range(j+1,n):\n lam = A[i,j]/A[j,j]\n A[i,j+1:n] = A[i,j+1:n] - lam*A[j,j+1:n]\n A[i,j] = lam\n return A\n```\n\n**Example**\nFind the LU factorization of matrix\n$$\nA=\\begin{pmatrix}{2} & {4} & {4} & {2} \\\\ {3} & {3} & {12} & {6} \\\\ {2} & {4} & {-1} & {2} \\\\ {4} & {2} & {1} & {1}\\end{pmatrix}\n$$\nand \n$$\nA=\\begin{pmatrix}{1} & {1} & {3} & {4} \\\\ {2} & {4} & {1} & {3} \\\\ {3} & {2} & {1} & {1} \\\\ {2} & {1} & {2} & {1}\\end{pmatrix}\n$$\n\n\n```python\nA = np.array([[2, 4, 4, 2], [3, 3, 12, 6], [2, 4, -1, 2], [4, 2, 1, 1]])\nprint (LU_factor(A))\n```\n\n [[ 2. 4. 4. 2.]\n [ 3. 3. 12. 6.]\n [ 2. 4. -1. 2.]\n [ 4. 2. 1. 1.]]\n [[ 2. 4. 4. 2. ]\n [ 1.5 -3. 6. 3. ]\n [ 1. -0. -5. 0. ]\n [ 2. 2. 3.8 -9. ]]\n\n\n\n```python\nA = np.array([[1, 1, 3, 4], [2, 4, 1, 3], [3, 2, 1, 1], [2, 1, 2, 1]])\nprint (LU_factor(A))\n```\n\n [[1. 1. 3. 4.]\n [2. 4. 1. 3.]\n [3. 2. 1. 1.]\n [2. 1. 2. 1.]]\n [[ 1. 1. 3. 4. ]\n [ 2. 2. -5. -5. ]\n [ 3. -0.5 -10.5 -13.5 ]\n [ 2. -0.5 0.61904762 -1.14285714]]\n\n\n#### The $PA = LU$ factorization\n\nAll of the techniques described so far are implemented in Python (Scipy). The most sophisticated form of Gaussian elimination we have discussed is the $PA=LU$ (or $A = PLU$) factorization. Scipy package has the command accepts a square coefficient matrix $A$ and returns $P$ , $L$, and $U$, such that $A = PLU$.\n\n\n```python\nfrom scipy.linalg import lu\nA = np.array([[2, 1, 5], [4, 4, -4], [1, 3, 1]])\nP, L, U = lu(A)\nprint (P)\nprint (L)\nprint (U)\n```\n\n [[0. 0. 1.]\n [1. 0. 0.]\n [0. 1. 0.]]\n [[ 1. 0. 0. ]\n [ 0.25 1. 0. ]\n [ 0.5 -0.5 1. ]]\n [[ 4. 4. -4.]\n [ 0. 2. 2.]\n [ 0. 0. 8.]]\n\n\n\n```python\nA = np.array([[2, 4, 4, 2], [3, 3, 12, 6], [2, 4, -1, 2], [4, 2, 1, 1]])\nP, L, U = lu(A)\nprint (P)\nprint (L)\nprint (U)\n```\n\n [[0. 0. 0. 1.]\n [0. 0. 1. 0.]\n [0. 1. 0. 0.]\n [1. 0. 0. 0.]]\n [[1. 0. 0. 0. ]\n [0.5 1. 0. 0. ]\n [0.75 0.5 1. 0. ]\n [0.5 1. 0.41666667 1. ]]\n [[ 4. 2. 1. 1. ]\n [ 0. 3. -1.5 1.5 ]\n [ 0. 0. 12. 4.5 ]\n [ 0. 0. 0. -1.875]]\n\n\n\n```python\nprint (np.dot(P, np.dot(L, U)) - A)\n```\n\n [[0. 0. 0. 0.]\n [0. 0. 0. 0.]\n [0. 0. 0. 0.]\n [0. 0. 0. 0.]]\n\n\n## Erros, Conditions Number\n\n**Example** (Hilbert Matrix)\n\nThe $n\\times n$ Hilbert Matrix $H_n$ is defined as follows:\n$$\nH_n = \\begin{pmatrix}{1} & {1 / 2} & {1 / 3} & {\\cdots} & {1 / n} \\\\ {1 / 2} & {1 / 3} & {1 / 4} & {\\cdots} & {1 /(n+1)} \\\\ {1 / 3} & {1 / 4} & {1 / 5} & {\\cdots} & {1 /(n+2)} \\\\ {\\cdots} & {\\cdots} & {\\cdots} & {\\cdots} & {\\cdots} \\\\ {1 / n} & {1 /(n+1)} & {1 /(n+2)} & {\\cdots} & {1 /(2 n-1)}\\end{pmatrix}\n$$\n\nSolving the linear system \n$$ H_n x = b$$\nwith \n$$ b = H_n \\cdot\\begin{pmatrix}1 \\\\ 1 \\\\ \\vdots \\\\ 1\\end{pmatrix} $$\nfor $n = 5, 10, 20$\n* The exact solution is $x = \\begin{pmatrix}1 \\\\ 1 \\\\ \\vdots \\\\ 1\\end{pmatrix} $\n\n\n```python\ndef hil(n):\n A = np.empty([n, n])\n for i in range(n):\n for j in range(n):\n A[i,j] = 1/(i+j+1)\n return A\n\ndef hil_example(n):\n A = hil(n)\n x_exact = np.zeros(n) + 1.\n b = np.dot(A, x_exact)\n x = np.linalg.solve(A, b)\n \n print (\"The Hilbert Example\")\n print (\"Exact Solution: \", x_exact)\n print (\"Numerical Solution: \", x)\n print (\"Max Norm Error: \", np.max(x_exact - x))\n```\n\n\n```python\nn = 30\n#A = hil(n)\n#print (A, '\\n')\n\nhil_example(n)\n```\n\n The Hilbert Example\n Exact Solution: [1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.\n 1. 1. 1. 1. 1. 1.]\n Numerical Solution: [ 0.99999999 1.00000549 0.9995934 1.01063208 0.86492543\n 1.95654753 -2.98980522 10.66985353 -10.64549422 1.40496892\n 15.91216488 -9.67086839 -3.19672645 5.14709635 -5.92419006\n 16.63359268 3.83136369 -13.36494379 -3.48351104 -2.37205148\n 14.37850702 22.52283623 -37.62581185 20.90624367 -8.37575394\n 1.62476071 10.16821532 -4.99742976 1.20141018 1.41386896]\n Max Norm Error: 38.62581184885538\n\n\n\n```python\n#n = 5\nA = hil(n)\nprint (np.linalg.cond(A, np.inf))\n```\n\n 6.598338740631285e+18\n\n\n**Example**\n\nSolve the following linear system\n\\begin{align}\n (1 + 10^{-20})x_1 + x_2 & = 2 + 10^{-20} \\\\\n x_1 + x_2 & = 2\n\\end{align}\n\n\n```python\nA = np.array([[1e-20, 1], [1, 1]])\nb = np.array([2+1e-20, 2])\n\nx = np.linalg.solve(A, b)\nprint (x)\n```\n\n [0. 2.]\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "6e42003939665170c37eeff30f984ab972f5bbec", "size": 15274, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "LinearSys_DirectMethod.ipynb", "max_stars_repo_name": "xiaozhouli/numerical_analysis", "max_stars_repo_head_hexsha": "68600ca56f8fdec6a2d22c65ec02ec2871546ea2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-11-06T02:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-06T02:11:33.000Z", "max_issues_repo_path": "LinearSys_DirectMethod.ipynb", "max_issues_repo_name": "xiaozhouli/numerical_analysis", "max_issues_repo_head_hexsha": "68600ca56f8fdec6a2d22c65ec02ec2871546ea2", "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": "LinearSys_DirectMethod.ipynb", "max_forks_repo_name": "xiaozhouli/numerical_analysis", "max_forks_repo_head_hexsha": "68600ca56f8fdec6a2d22c65ec02ec2871546ea2", "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": 27.3727598566, "max_line_length": 406, "alphanum_fraction": 0.436362446, "converted": true, "num_tokens": 3777, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361604769413, "lm_q2_score": 0.9343951698485603, "lm_q1q2_score": 0.8525759411448198}} {"text": "# Tensor Manipulation: Psi4 and NumPy manipulation routines\nContracting tensors together forms the core of the Psi4Julia project. First let us consider the popluar [Einstein Summation Notation](https://en.wikipedia.org/wiki/Einstein_notation) which allows for very succinct descriptions of a given tensor contraction.\n\nFor example, let us consider a [inner (dot) product](https://en.wikipedia.org/wiki/Dot_product):\n$$c = \\sum_{ij} A_{ij} * B_{ij}$$\n\nWith the Einstein convention, all indices that are repeated are considered summed over, and the explicit summation symbol is dropped:\n$$c = A_{ij} * B_{ij}$$\n\nThis can be extended to [matrix multiplication](https://en.wikipedia.org/wiki/Matrix_multiplication):\n\\begin{align}\n\\rm{Conventional}\\;\\;\\; C_{ik} &= \\sum_{j} A_{ij} * B_{jk} \\\\\n\\rm{Einstein}\\;\\;\\; C &= A_{ij} * B_{jk} \\\\\n\\end{align}\n\nWhere the $C$ matrix has *implied* indices of $C_{ik}$ as the only repeated index is $j$.\n\nHowever, there are many cases where this notation fails. Thus we often use the generalized Einstein convention. To demonstrate let us examine a [Hadamard product](https://en.wikipedia.org/wiki/Hadamard_product_(matrices)):\n$$C_{ij} = \\sum_{ij} A_{ij} * B_{ij}$$\n\n\nThis operation is nearly identical to the dot product above, and is not able to be written in pure Einstein convention. The generalized convention allows for the use of indices on the left hand side of the equation:\n$$C_{ij} = A_{ij} * B_{ij}$$\n\nUsually it should be apparent within the context the exact meaning of a given expression.\n\nFinally we also make use of Matrix notation:\n\\begin{align}\n{\\rm Matrix}\\;\\;\\; \\bf{D} &= \\bf{A B C} \\\\\n{\\rm Einstein}\\;\\;\\; D_{il} &= A_{ij} B_{jk} C_{kl}\n\\end{align}\n\nNote that this notation is signified by the use of bold characters to denote matrices and consecutive matrices next to each other imply a chain of matrix multiplications! \n\n## Tensor Operations\n\nTo perform most operations we turn to tensor packages (here we use [TensorOperations.jl](https://github.com/Jutho/TensorOperations.jl)). Those allow Einstein convention as an input. In addition to being much easier to read, manipulate, and change, it has (usually) optimal performance.\nFirst let us import our normal suite of modules:\n\n\n```julia\nusing PyCall: pyimport\npsi4 = pyimport(\"psi4\")\nnp = pyimport(\"numpy\")\nusing TensorOperations: @tensor\n```\n\nWe can then use conventional Julia loops or `@tensor` to perform the same task. \n\n\n```julia\nusing BenchmarkTools: @btime, @belapsed\n```\n\nWith `@btime`/`@belapsed` we average time over several executions to have more reliable timings than `@time`/`@elapsed` (single execution).\n\n**WARNING: We are using Julia's global variables, and those are known to be less efficient than local variables. It is better to wrap code inside function.**\n\nTo begin let us consider the construction of the following tensor (which you may recognize):\n$$G_{pq} = 2.0 * I_{pqrs} D_{rs} - 1.0 * I_{prqs} D_{rs}$$ \n\nKeep size relatively small as these 4-index tensors grow very quickly in size.\n\n\n```julia\ndims = 20\n\n@assert dims <= 30 \"Size must be smaller than 30.\"\nD = rand(dims, dims)\nI = rand(dims, dims, dims, dims)\n\n# Build the Fock matrix using loops, while keeping track of time\nprintln(\"Time for loop G build:\")\nGloop = @btime begin\n Gloop = np.zeros((dims, dims))\n @inbounds for ind in CartesianIndices(I)\n p, q, r, s = Tuple(ind)\n Gloop[p, q] += 2I[p, q, r, s] * D[r, s]\n Gloop[p, q] -= I[p, r, q, s] * D[r, s]\n end\n Gloop\nend\n\n# Build the Fock matrix using einsum, while keeping track of time\nprintln(\"Time for @tensor G build:\")\nG = @btime @tensor G[p,q] := 2I[p,q,r,s] * D[r,s] - I[p,r,q,s] * D[r,s]\n\n# Make sure the correct answer is obtained\nprintln(\"Loop and einsum builds of the Fock matrix match? \", np.allclose(G, Gloop))\nprintln()\n# Print out relative times for explicit loop vs einsum Fock builds\n#println(\"G builds with einsum are $(g_loop_time/einsum_time) times faster than Julia loops!\")\n```\n\n Time for loop G build:\n 81.372 ms (2400038 allocations: 61.04 MiB)\n Time for @tensor G build:\n 264.983 μs (46 allocations: 5.75 KiB)\n Loop and einsum builds of the Fock matrix match? true\n \n\n\nAs you can see, the `@tensor` macro can be considerably faster than plain Julia loops.\n\n## Matrix multiplication chain/train\n\nNow let us turn our attention to a more canonical matrix multiplication example such as:\n$$D_{il} = A_{ij} B_{jk} C_{kl}$$\n\nMatrix multiplication is an extremely common operation in all branches of linear algebra. Thus, these functions have been optimized to be extremely efficient. `@tensor` uses it. The matrix product will explicitly compute the following operation:\n$$C_{ij} = A_{ij} * B_{ij}$$\n\n\nThis is Julia's matrix multiplication method `*` for matrices.\n\n\n```julia\ndims = 200\nA = rand(dims, dims)\nB = rand(dims, dims)\nC = rand(dims, dims)\n\n# First compute the pair product\ntmp_dot = A * B\n@tensor tmp_tensor[i,k] := A[i,j] * B[j,k]\nprintln(\"Pair product allclose? \", np.allclose(tmp_dot, tmp_tensor))\n```\n\n Pair product allclose? true\n\n\nNow that we have proved exactly what `*` product does, let us consider the full chain and do a timing comparison:\n\n\n```julia\nD_dot = A * B * C\n@tensor D_tensor[i,l] := A[i,j] * B[j,k] * C[k,l]\nprintln(\"Chain multiplication allclose? \", np.allclose(D_dot, D_tensor))\n```\n\n Chain multiplication allclose? true\n\n\n\n```julia\nprintln()\nprintln(\"* time:\")\n@btime A * B * C\n\nprintln()\nprintln(\"@tensor time:\")\n@btime @tensor D_tensor[i,l] := A[i,j] * B[j,k] * C[k,l];\n```\n\n \n * time:\n 467.984 μs (4 allocations: 625.16 KiB)\n \n @tensor time:\n 471.215 μs (34 allocations: 314.20 KiB)\n\n\nBoth have similar timings, and both call [Basic Linear Algebra Subprograms (BLAS)](https://en.wikipedia.org/wiki/Basic_Linear_Algebra_Subprograms). The BLAS routines are highly optimized and threaded versions of the code.\n - The `@tensor` code will factorize the operation by default; Thus, the overall cost is not ${\\cal O}(N^4)$ (as there are four indices) rather it is the factored $(\\bf{A B}) \\bf{C}$ which runs ${\\cal O}(N^3)$.\n \nTherefore you do not need to factorize the expression yourself (sometimes you might need):\n\n\n```julia\nprintln(\"@tensor factorized time:\")\n@btime @tensor begin\n tmp[i,k] := A[i,j] * B[j,k]\n tmp2[i,l] := tmp[i,k] * C[k,l]\nend\nnothing\n```\n\n @tensor factorized time:\n 474.136 μs (8 allocations: 625.25 KiB)\n\n\nOn most machines the three have similar timings. The BLAS usage is usually recommended. Thankfully, in Julia its syntax is very clear. The Psi4Julia project tends to lean toward usage of tensor packages but if Julia's built-in matrix multiplication is significantly cleaner/faster we would use it. The real value of tensor packages will become tangible for more complicated expressions.\n\n## Complicated tensor manipulations\nLet us consider a popular index transformation example:\n$$M_{pqrs} = C_{pi} C_{qj} I_{ijkl} C_{rk} C_{sl}$$\n\nHere, a naive loop implementation would scale like $\\mathcal{O}(N^8)$ which translates to an extremely costly computation for all but the smallest $N$. A smarter implementation (factorizing the whole expression) would scale\nlike $\\mathcal{O}(N^5)$.\n\n**WARNING: First execution is slow because of compilation time. Successive are more honest to the running time.**\n\n\n```julia\n# Grab orbitals\ndims = 15\n@assert dims <= 15 || \"Size must be smaller than 15.\"\n \nC = rand(dims, dims)\nI = rand(dims, dims, dims, dims)\n\n# @tensor full transformation.\nprint(\"\\nStarting @tensor full transformation...\")\nn8_time = @elapsed @tensor MO_n8[I,J,K,L] := C[p,I] * C[q,J] * I[p,q,r,s] * C[r,K] * C[s,L]\nprint(\"complete in $n8_time s\\n\")\n\n# @tensor factorized N^5 transformation.\nprint(\"\\nStarting @tensor factorized N^5 transformation with einsum ... \")\nn5_time = @elapsed @tensor begin\n MO_n5[A,q,r,s] := C[p,A] * I[p,q,r,s]\n MO_n5[A,B,r,s] := C[q,B] * MO_n5[A,q,r,s]\n MO_n5[A,B,C,s] := C[r,C] * MO_n5[A,B,r,s]\n MO_n5[A,B,C,D] := C[s,D] * MO_n5[A,B,C,s]\nend\nprint(\"complete in $n5_time s \\n\")\nprintln(\" @tensor factorized is $(n8_time/n5_time) faster than full @tensor algorithm!\")\nprintln(\" Allclose? \", np.allclose(MO_n8, MO_n5))\n\n# Julia's GEMM N^5 transformation.\n# Try to figure this one out!\nprint(\"\\nStarting Julia's factorized transformation with * ... \")\ndgemm_time = @elapsed begin\n MO = C' * reshape(I, dims, :)\n MO = reshape(MO, :, dims) * C\n MO = permutedims(reshape(MO, dims, dims, dims, dims), (2, 1, 4, 3))\n\n MO = C' * reshape(MO, dims, :)\n MO = reshape(MO, :, dims) * C\n MO = permutedims(reshape(MO, dims, dims, dims, dims),(2, 1, 4, 3))\nend\nprint(\"complete in $dgemm_time s \\n\")\nprintln(\" * factorized is $(n8_time/dgemm_time) faster than full @tensor algorithm!\")\nprintln(\" Allclose? \", np.allclose(MO_n8, MO))\n\n# There are still several possibilities to explore:\n# @inbounds, @simd, LinearAlgebra.LAPACK calls, Einsum.jl, Tullio.jl, ...\n```\n\n \n Starting @tensor full transformation...complete in 0.008222635 s\n \n Starting @tensor factorized N^5 transformation with einsum ... complete in 0.000705554 s \n @tensor factorized is 11.65415404065458 faster than full @tensor algorithm!\n Allclose? true\n \n Starting Julia's factorized transformation with * ... complete in 0.001960656 s \n * factorized is 4.193818293469126 faster than full @tensor algorithm!\n Allclose? true\n\n\nNone of the above algorithms is $\\mathcal{O}(N^8)$. `@tensor` factorizes the expression to achieve better performance. There is a small edge in doing the factorization manually. Factorized algorithms have similar timings, although it is clear that with `@tensor` is easier than with Julia's built-in `*`. To use the usual matrix multiplication with tensors we have to reshape and permute their dimensions, subtracting appeal to the simple `*` syntax.\n", "meta": {"hexsha": "1c98ce2e226de9cc08db9a6f1e5bb43c365a096a", "size": 14453, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Tutorials/01_Psi4Julia-Basics/1f_tensor-manipulation.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/01_Psi4Julia-Basics/1f_tensor-manipulation.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/01_Psi4Julia-Basics/1f_tensor-manipulation.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": 35.0800970874, "max_line_length": 457, "alphanum_fraction": 0.5800871791, "converted": true, "num_tokens": 2775, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951607140232, "lm_q2_score": 0.9124361545241945, "lm_q1q2_score": 0.85257592724792}} {"text": "# First Post\n> Gotta start somewhere\n\n\nA big part of the workflow students in my python-based mathematics classes is to create clear, beautiful documents with Jupyter. For that reason, I'll use Jupyter to generate all the content in PythonMathClassroom. \n\nThe decision to host the blog from githup fastpages came down to the ease with which Jupyter content can go up on that platform without any intermediate fuss.\n\nThe first post ought to have some python mathematics, so here we go:\n\nLet's use the sympy library to compute and plot some functions related to $x^2e^{-x}$\n\n\n```python\nfrom sympy import *\nx, y = symbols(\"x y\")\n\nii=integrate(x**2*exp(-x),x)\nii\n\n```\n\n\n\n\n$\\displaystyle \\left(- x^{2} - 2 x - 2\\right) e^{- x}$\n\n\n\n\n```python\ndiff(ii,x)\n```\n\n\n\n\n$\\displaystyle \\left(- 2 x - 2\\right) e^{- x} - \\left(- x^{2} - 2 x - 2\\right) e^{- x}$\n\n\n\n\n```python\nexpand(_)\n```\n\n\n\n\n$\\displaystyle x^{2} e^{- x}$\n\n\n\n\n```python\nsolve(x**2*exp(-x)- 3/10 ,x)\n```\n\n\n\n\n [-0.439637356954377, 0.829068989148422, 3.95284287457532]\n\n\n\n\n```python\nplot(x**2*exp(-x),3/10,(x,-.6,10))\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "dce6b98ef3ec69f677ba4b4c6d8c22f52053138e", "size": 22859, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "_notebooks/2022-02-18-FirstPost.ipynb", "max_stars_repo_name": "ejbarth/PythonMathClassroom", "max_stars_repo_head_hexsha": "493e314678f629b80ced1af361dc9a5d7ebb25ae", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-23T03:17:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-23T03:17:44.000Z", "max_issues_repo_path": "_notebooks/2022-02-18-FirstPost.ipynb", "max_issues_repo_name": "ejbarth/PythonMathClassroom", "max_issues_repo_head_hexsha": "493e314678f629b80ced1af361dc9a5d7ebb25ae", "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/2022-02-18-FirstPost.ipynb", "max_forks_repo_name": "ejbarth/PythonMathClassroom", "max_forks_repo_head_hexsha": "493e314678f629b80ced1af361dc9a5d7ebb25ae", "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": 122.2406417112, "max_line_length": 18996, "alphanum_fraction": 0.8877466206, "converted": true, "num_tokens": 338, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9626731126558705, "lm_q2_score": 0.885631470799559, "lm_q1q2_score": 0.8525736046606082}} {"text": "```\nimport numpy as np\nimport scipy as sp\nimport scipy.signal\nimport matplotlib\nimport matplotlib.pyplot as plt\n%matplotlib inline\n```\n\nThe linear interpolation is a convolution of the samples with a triangular pulse $h_l(t)$. The triangular pulse is the convolution of two rectangular pulses $ h_l(t) = (p_{\\tau} \\ast p_{\\tau}) (t) $. The frequency response $ H_l(f) $ is therefore \n\\begin{equation}\nH_l(f) = (\\tau \\cdot \\text{sinc}(f \\tau))^2.\n\\end{equation}\n\nFor the linear interpolator $ \\tau = T_S $ where $ T_S $ is the sampling time of the input discrete signal.\n\n\n```\n# sampling period & frequency ofthe input discrete signal\nTs = 1\nFs = 1/Ts\n\n# analytic frequency response of the interpolating filter\nN = 40\nres = 100\nf = np.linspace(-N*Fs,N*Fs, 2*N*res)\ntau = Ts\nH_l = tau**2 * np.sinc(f * tau)**2\n```\n\n\n```\nfig, ax = plt.subplots(1, 1, figsize=(13,4))\nax.plot(f, 20 * np.log10( np.abs(H_l) ))\nax.set_ylabel('Amplitude [dB]', fontsize=12)\nax.set_xlabel('Frequency [Hz]', fontsize=12)\n\nn = np.arange(0,9,1)\nax.set_xticks(Fs * n)\nlabels = [\"$%d F_S$\" % y for y in n[1:]]\nlabels.insert(0,\"0\")\nax.set_xticklabels(labels, fontsize=12)\nax.grid()\n\nax.axis('tight');\nax.set_ylim([-100, 10]); # semicolon suppresses the output\nax.set_xlim([0, n[-1]*Fs]);\n```\n\nWith this operation I get a continuous signal from a discrete one. If I want to output a discrete signal, I must sample the output. This is the same as both:\n - sampling the impulse response of the linear interpolation filter, \n - interpolating zeros to the input signal\n\nwith sampling time \n\\begin{equation} T_{S1} = L \\cdot T_S \\qquad L \\in \\mathbb{N}. \\end{equation}\n\nThis produces spectral copies of the original frequency response, at $ n F_{S1} $\n\n\n\n```\nL = 6 # Fs1 is L times Fs\nFs1 = L * Fs\n\n# view\nf_min = 0\nf_max = 8*Fs\n\nfig, ax = plt.subplots(1, 1, figsize=(12,6))\n\n# plot some spectral copies\nf = np.linspace(f_min, f_max, ((f_max-f_min)/Fs)*res)\ntau = Ts\nH_l_tot = np.zeros((len(f),))\nfor i in range(-10,10):\n H_l = tau**2 * np.sinc((f + i*Fs1) * tau)**2\n ax.plot(f, 20 * np.log10( np.abs(H_l) ), '--b', alpha=0.4)\n H_l_tot = H_l_tot + H_l\n\n# plot the sum of all the spectral copies\nax.plot(f, 20 * np.log10( np.abs(H_l_tot)), 'b')\n\nax.set_ylabel('Amplitude [dB]', fontsize=12)\nax.set_xlabel('Frequency [Hz]', fontsize=12)\n\nn = np.arange(0,9,1)\nax.set_xticks(Fs * n)\nlabels = [\"$%d F_S$\" % y for y in n[1:]]\nlabels.insert(0,\"0\")\nax.set_xticklabels(labels, fontsize=12)\nax.grid()\n\nax.axis('tight');\nax.set_ylim([-100, 10]); # semicolon suppresses the output\nax.set_xlim([f_min, f_max]);\n```\n\nWe show that by fourier transforming the impulse response of the linear interpolator, sampled at $F_{S1}$, we obtain the same result.\n\n\n```\nnfft = 1024\nh_l_sampled = np.hstack((np.linspace(0,1-1/L,L), np.linspace(1,0+1/L,L)))\nH_l_sampled = np.fft.rfft(h_l_sampled, nfft, axis=-1)\nf_sampled = Fs1 * np.linspace(0,0.5,(nfft/2)+1)\n```\n\n\n```\nfig, ax = plt.subplots(1, 1, figsize=(6,4))\n\n#plt.title('Digital filter frequency response')\n\n# highest frequency (pi) corresponds to M * Fs/2\nax.plot(f_sampled, 20 * np.log10(abs(H_l_sampled)), 'b', label=r\"$ALIAS_{10}$\")\nax.set_ylabel('Amplitude [dB]', fontsize=12)\nax.set_xlabel('Frequency [Hz]', fontsize=12)\nax.grid()\n\nn = np.arange(0,9,1)\nax.set_xticks(Fs * n)\nlabels = [\"$%d F_S$\" % y for y in n[1:]]\nlabels.insert(0,\"0\")\nax.set_xticklabels(labels, fontsize=12)\nax.set_xlim([0, L*Fs/2]);\n```\n\nLets normalize them to compare the frequency response of the sampled version with respect to the continuous version\n\n\n```\n# frequency response of the sampled (at L*Fs) interpolator \nL = 6\nFs1 = L * Fs\n\n# fft computation\nnfft = 1024\nh_l_sampled = np.hstack((np.linspace(0,1-1/L,L), np.linspace(1,0+1/L,L)))\nH_l_sampled = np.fft.rfft(h_l_sampled, nfft, axis=-1)\nf_sampled = Fs1 * np.linspace(0,0.5,(nfft/2)+1) # [0, .5 Fs1]\n\n#Normalization\nH_l_sampled = H_l_sampled/np.max(np.abs(H_l_sampled))\n\n# frequency response of the continuous-time interpolator\nf = np.linspace(0*Fs,(L/2)*Fs, (L/2)*100) # we care only up to (L/2)*Fs\ntau = Ts\nH_l = tau**2 * np.sinc(f * tau)**2\n\n#Normalization\nH_l = H_l / np.max(H_l)\n```\n\n\n```\nfig, ax = plt.subplots(1, 1, figsize=(12,4))\n\n# highest frequency (pi) corresponds to M * Fs/2\nax.plot(f_sampled, 20 * np.log10(abs(H_l_sampled)), 'b', label=r\"$ALIAS_{%d}$\" % L)\nax.plot(f, 20 * np.log10(abs(H_l)), 'g', label=r\"$sinc$\")\nax.set_ylabel('Amplitude [dB]', fontsize=12)\nax.set_xlabel('Frequency [Hz]', fontsize=12)\nax.grid()\nax.legend(loc=0)\n\nn = np.arange(0,9,1)\nax.set_xticks(Fs * n)\nlabels = [\"$%d F_S$\" % y for y in n[1:]]\nlabels.insert(0,\"0\")\nax.set_xticklabels(labels, fontsize=12)\nax.set_xlim([0, L*Fs/2]);\nax.set_ylim([-100, 10]);\n```\n", "meta": {"hexsha": "096ab30778f022e72905d7c191d8dec9b899a329", "size": 230875, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "audio/LinearInterpolation.ipynb", "max_stars_repo_name": "brunodigiorgi/ipn-notes", "max_stars_repo_head_hexsha": "c8840a45989f25442c1d800ef8acdf8c630cdafc", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-03-07T13:46:17.000Z", "max_stars_repo_stars_event_max_datetime": "2018-03-07T13:46:17.000Z", "max_issues_repo_path": "audio/LinearInterpolation.ipynb", "max_issues_repo_name": "brunodigiorgi/ipn-notes", "max_issues_repo_head_hexsha": "c8840a45989f25442c1d800ef8acdf8c630cdafc", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "audio/LinearInterpolation.ipynb", "max_forks_repo_name": "brunodigiorgi/ipn-notes", "max_forks_repo_head_hexsha": "c8840a45989f25442c1d800ef8acdf8c630cdafc", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 712.5771604938, "max_line_length": 135737, "alphanum_fraction": 0.9357314564, "converted": true, "num_tokens": 1570, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545318852121, "lm_q2_score": 0.899121388082479, "lm_q1q2_score": 0.8525060188253251}} {"text": "# Parameter Learning\n\n## 1. Gradient Descent\n\nWe may summarize our steps in the solution of our housing prices regression problem as follows:\n\n- We proposed a hypothesis function:\n $$h_{\\theta}(x) = \\theta_0 + \\theta_1 x.$$\n \n- Whose parameters are:\n $$\\theta_0, \\theta_1.$$\n \n- Then, we had the cost function:\n $$J(\\theta_0, \\theta_1) = \\frac{1}{2m}\\sum_{i=1}^{m}(h_{\\theta}(x^{(i)}) - y^{(i)})^2,$$\n which accounts for the square of the vertical distance between the hypothesis function and the training examples.\n \n- Our goal is to find the parameters $\\theta_0$ and $\\theta_1$ that solve the following optimization problem:\n $$\\min_{\\theta_0, \\theta_1} J(\\theta_0, \\theta_1)$$\n\n### How do we do this?:\n\n- Start with some $\\theta_0, \\theta_1.$\n- Keep changing $\\theta_0, \\theta_1$ to reduce $J(\\theta_0, \\theta_1)$ until we hopefully end up at a minimum.\n\nThe **gradient descent** algorithm, which we will explore in a moment, actually applies to cost functions with an arbitrary number of parameters:\n\n$$J(\\theta_0, \\theta_1, \\dots, \\theta_n),$$\n\nwith $n\\in\\mathbb{N}$.\n\n### Gradient descent algorithm\n\nThe gradient descent algorithm can be described as follows:\n\n- Initialize $\\theta_j$, for $j\\in\\{0, 1,\\dots, n\\}$.\n\n- repeat until convergence {\n $$\\theta_j := \\theta_j - \\alpha \\frac{\\partial}{\\partial \\theta_j} J(\\theta_0, \\theta_1, \\dots, \\theta_n); \\qquad \\text{ for } j\\in\\{0, 1,\\dots, n\\}$$\n }\n\nOr, in a vector form, with $\\boldsymbol{\\theta} = \\left[\\theta_0, \\theta_1, \\dots, \\theta_n\\right]^T\\in\\mathbb{R}^{n+1}$:\n\n- Initialize $\\boldsymbol{\\theta}$.\n\n- repeat until convergence {\n $$\\boldsymbol{\\theta} := \\boldsymbol{\\theta} - \\alpha \\frac{\\partial}{\\partial \\boldsymbol{\\theta}} J(\\boldsymbol{\\theta})$$\n }\n \nwhere $\\frac{\\partial}{\\partial \\boldsymbol{\\theta}} J(\\boldsymbol{\\theta})$ is the gradient of the function $J$.\n\n> The *hyperparameter* $\\alpha>0$ is called the **learning rate**. It basically controls how big/small is the step to be taken in the direction of the gradient $\\frac{\\partial}{\\partial \\boldsymbol{\\theta}} J(\\boldsymbol{\\theta})$.\n\nTo gain some intuition with this algorithm, let's consider the function (of only one parameter)\n\n$$J(\\theta) = (\\theta - 3)^2 + 1,$$\n\nand its derivative\n\n$$\\frac{d}{d \\theta} J(\\theta) = 2(\\theta - 3).$$\n\n\n```python\n# Import libraries\nfrom matplotlib import pyplot as plt\nimport numpy as np\n%matplotlib inline\n```\n\n\n```python\n# Cost function\ndef J(t):\n return (t - 3)**2 + 1\n# Derivative of the cost function\ndef dJ(t):\n return 2 * (t - 3)\n```\n\n\n```python\nt = np.linspace(0, 6, 101)\n```\n\n\n```python\nplt.figure(figsize=(6, 4))\nplt.plot(t, J(t), 'b--', lw=2, label=r'$J(\\theta)$')\nplt.axhline(y=0, c='k', lw=2)\nplt.axvline(x=0, c='k', lw=2)\n```\n\nNow, let's suppose that our initialization for the parameter is $\\theta=5$. In this case, one iteration of the gradient descent algorithm, with $\\alpha = 0.1$ would produce:\n\n\\begin{align}\n \\theta & := \\theta - 2\\alpha (\\theta - 3) \\\\\n & = 5 - 0.1 \\times 2 \\times 2\n\\end{align}\n\n\n```python\nplt.figure(figsize=(6, 4))\nplt.plot(t, J(t), 'b--', lw=2, label=r'$J(\\theta)$')\nplt.plot(5, J(5), 'or', ms=10, label='$(5, J(5))$')\nplt.arrow(x=5, y=J(5), dx=(5 - 0.1 * 2 * 2 - 5), dy=(J(5 - 0.1 * 2 * 2) - J(5)), width=0.1)\nplt.legend(loc='best')\nplt.axhline(y=0, c='k', lw=2)\nplt.axvline(x=0, c='k', lw=2)\n```\n\nThe update of $\\theta=4.6$ is in the direction of the minimum.\n\nLet's look at the behavior of the gradient descent algorithm until its convergence:\n\n\n```python\nfrom grad_desc import grad_desc\n```\n\n\n```python\nsteps = grad_desc(grad=dJ, x0=5, alpha=0.1, grad_tol=1e-3)\n```\n\n\n```python\nplt.figure(figsize=(6, 4))\nplt.plot(t, J(t), 'b--', lw=2, label=r'$J(\\theta)$')\nplt.plot(steps, J(steps), 'or', ms=5, label='Gradient descent iterations')\nplt.plot(steps[-1], J(steps[-1]), 'ok', ms=5, label='Iteration at convergence')\nplt.legend(loc='best')\nplt.axhline(y=0, c='k', lw=2)\nplt.axvline(x=0, c='k', lw=2)\n```\n\nNow, let's try initializing $\\theta=0$:\n\n\n```python\nsteps = grad_desc(grad=dJ, x0=0, alpha=0.1, grad_tol=1e-3)\n```\n\n\n```python\nsteps\n```\n\n\n\n\n array([0. , 0.6 , 1.08 , 1.464 , 1.7712 ,\n 2.01696 , 2.213568 , 2.3708544 , 2.49668352, 2.59734682,\n 2.67787745, 2.74230196, 2.79384157, 2.83507326, 2.8680586 ,\n 2.89444688, 2.91555751, 2.93244601, 2.9459568 , 2.95676544,\n 2.96541235, 2.97232988, 2.97786391, 2.98229113, 2.9858329 ,\n 2.98866632, 2.99093306, 2.99274645, 2.99419716, 2.99535772,\n 2.99628618, 2.99702894, 2.99762316, 2.99809852, 2.99847882,\n 2.99878306, 2.99902644, 2.99922116, 2.99937692, 2.99950154])\n\n\n\n\n```python\nplt.figure(figsize=(6, 4))\nplt.plot(t, J(t), 'b--', lw=2, label=r'$J(\\theta)$')\nplt.plot(steps, J(steps), 'or', ms=5, label='Gradient descent iterations')\nplt.plot(steps[-1], J(steps[-1]), 'ok', ms=5, label='Iteration at convergence')\nplt.legend(loc='best')\nplt.axhline(y=0, c='k', lw=2)\nplt.axvline(x=0, c='k', lw=2)\n```\n\n### What about $\\alpha$?\n\nIf $\\alpha$ is too small, gradient descent can be slow:\n\n\n```python\nsteps = grad_desc(grad=dJ, x0=0, alpha=1e-4, grad_tol=1e-3)\n```\n\n\n```python\nlen(steps)\n```\n\n\n\n\n 43495\n\n\n\n\n```python\nplt.figure(figsize=(6, 4))\nplt.plot(t, J(t), 'b--', lw=2, label=r'$J(\\theta)$')\nplt.plot(steps, J(steps), 'or', ms=5, label='Gradient descent iterations')\nplt.plot(steps[-1], J(steps[-1]), 'ok', ms=5, label='Iteration at convergence')\nplt.legend(loc='best')\nplt.axhline(y=0, c='k', lw=2)\nplt.axvline(x=0, c='k', lw=2)\n```\n\nIf $\\alpha$ is too large, gradient descent can fail to converge, or even diverge:\n\n\n```python\nsteps = grad_desc(grad=dJ, x0=2.5, alpha=1.5, grad_tol=1e-3, max_iter=10)\n```\n\n\n```python\nplt.figure(figsize=(6, 4))\nplt.plot(t, J(t), 'b--', lw=2, label=r'$J(\\theta)$')\nplt.plot(steps, J(steps), 'or', ms=5, label='Gradient descent iterations')\ndsteps = np.diff(steps)\nplt.arrow(steps[0], J(steps[0]), dsteps[0], J(steps[1]) - J(steps[0]), width=0.1)\nplt.arrow(steps[1], J(steps[1]), dsteps[1], J(steps[2]) - J(steps[1]), width=0.1)\nplt.arrow(steps[2], J(steps[2]), dsteps[2], J(steps[3]) - J(steps[2]), width=0.1)\nplt.legend(loc='best')\nplt.axhline(y=0, c='k', lw=2)\nplt.axvline(x=0, c='k', lw=2)\nplt.axis([-1, 7, -1, 10])\n```\n\n### If we initialize already at a local optimum, the gradient descent will stuck at that point\n\n\n```python\nsteps = grad_desc(grad=dJ, x0=3, alpha=0.1, grad_tol=1e-3, max_iter=10)\n```\n\n\n```python\nlen(steps)\n```\n\n\n\n\n 1\n\n\n\n\n```python\nplt.figure(figsize=(6, 4))\nplt.plot(t, J(t), 'b--', lw=2, label=r'$J(\\theta)$')\nplt.plot(steps, J(steps), 'or', ms=5, label='Gradient descent iterations')\nplt.plot(steps[-1], J(steps[-1]), 'ok', ms=5, label='Iteration at convergence')\nplt.legend(loc='best')\nplt.axhline(y=0, c='k', lw=2)\nplt.axvline(x=0, c='k', lw=2)\n```\n\n## 2. Gradient descent for linear regression\n\nGiven that we proposed the hypothesis function:\n $$h_{\\theta}(x) = \\theta_0 + \\theta_1 x,$$\n \nwith the cost function:\n $$J(\\theta_0, \\theta_1) = \\frac{1}{2m}\\sum_{i=1}^{m}(h_{\\theta}(x^{(i)}) - y^{(i)})^2,$$\n\nwhat are the partial derivatives of $J$?\n\n\\begin{align}\n\\frac{\\partial}{\\partial \\theta_j} J(\\theta_0, \\theta_1) & = \\frac{\\partial}{\\partial \\theta_j}\\frac{1}{2m}\\sum_{i=1}^{m}(h_{\\theta}(x^{(i)}) - y^{(i)})^2 \\\\\n& = \\frac{\\partial}{\\partial \\theta_j}\\frac{1}{2m}\\sum_{i=1}^{m}(\\theta_0 + \\theta_1 x^{(i)} - y^{(i)})^2, \\qquad \\text{ for } j=0,1\n\\end{align}\n\nThus, for $j=0$:\n\n$$\n\\frac{\\partial}{\\partial \\theta_0} J(\\theta_0, \\theta_1) = \\frac{1}{m}\\sum_{i=1}^{m}(h_{\\theta}(x^{(i)}) - y^{(i)}),\n$$\n\nand, for $j=1$:\n\n$$\n\\frac{\\partial}{\\partial \\theta_1} J(\\theta_0, \\theta_1) = \\frac{1}{m}\\sum_{i=1}^{m}(h_{\\theta}(x^{(i)}) - y^{(i)})x^{(i)}.\n$$\n\nEquivalently, the gradient of $J$ is:\n\n$$\n\\frac{\\partial}{\\partial \\boldsymbol{\\theta}} J(\\theta_0, \\theta_1) = \\frac{1}{m}\\left[\n\\begin{array}{c}\n\\sum_{i=1}^{m}(h_{\\theta}(x^{(i)}) - y^{(i)}) \\\\\n\\sum_{i=1}^{m}(h_{\\theta}(x^{(i)}) - y^{(i)})x^{(i)}\n\\end{array}\n\\right].\n$$\n\nAs we saw in the previous notebook, this is a (strictly) convex function. Thus, it has at most one local/global minimum. Under this conditions, the gradient descent algorithm is guaranteed to converge to that point.\n\nIn our housing prices example:\n\n\n```python\nimport pandas as pd\n```\n\n\n```python\n# Read the data\ndata = pd.read_csv(\"house_pricing.csv\", low_memory=False)\n```\n\n\n```python\n# Data (scaled)\nx = data['size'].values / 1000\ny = data['price'].values / 100000\nm = len(x)\n```\n\n\n```python\n# Hypothesis function (as a function of the params)\ndef h(t):\n return t[0] + t[1] * x\n# Cost function\ndef J(t):\n return ((h(t) - y)**2).sum() / (2 * m)\n# Gradient of the cost function\ndef dJ(t):\n return np.array([(h(t) - y).sum(), ((h(t) - y) * x).sum()]) / m\n```\n\n\n```python\n# Generate theta0, theta1 grid\nt0 = np.linspace(-10, 30, 100)\nt1 = np.linspace(-10, 10, 1000)\nT0, T1 = np.meshgrid(t0, t1)\n```\n\n\n```python\n# Compute cost function in the theta0, theta1 grid\n# TODO: find a more efficient way to evaluate this function\ncost_fcn = np.zeros(T0.shape)\nfor i in range(T0.shape[0]):\n for j in range(T0.shape[1]):\n cost_fcn[i, j] = J([T0[i, j], T1[i, j]])\n```\n\n\n```python\nsteps = grad_desc(grad=dJ, x0=np.array([30., 10.]), alpha=0.1, grad_tol=1e-3)\n```\n\n\n```python\n# Import libraries\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom matplotlib import cm\n```\n\n\n```python\n# 3D plot and gradient descent steps\nfig = plt.figure()\nax = fig.add_subplot(111, projection='3d')\nax.plot_surface(T0, T1, cost_fcn, rstride=8, cstride=8, alpha=0.5)\nax.scatter(steps[::50, 0], steps[::50, 1], [J(step) for step in steps[::50]], c='r', s=5,\n label='Gradient descent iterations')\nax.scatter(steps[-1, 0], steps[-1, 1], J(steps[-1]), c='k',\n label=r'Convergence: $\\theta_0=${}, $\\theta_1=${}'.format(np.round(steps[-1, 0], 2), \n np.round(steps[-1, 1],2)))\nax.set_xlabel(r'$\\theta_0$')\nax.set_ylabel(r'$\\theta_1$')\nax.set_zlabel(r'$J(\\theta_0, \\theta_1)$')\nax.legend()\n```\n\n\n```python\n# Plot the corresponding lines\nplt.figure(figsize=(6, 4))\nplt.plot(data['size'], data['price'], 'xr', ms=5, label='Housing prices data')\nx = np.linspace(500, 5000)\ny = 100000 * (steps[-1, 0] + steps[-1, 1] * x / 1000)\nplt.plot(x, y, 'g', lw=3,\n label=r'$\\theta_0=${}, $\\theta_1=${}'.format(np.round(steps[-1, 0], 2),\n np.round(steps[-1, 1], 2)))\nplt.axhline(y=0, c='k', lw=2)\nplt.axvline(x=0, c='k', lw=2)\nplt.xlabel('Size in $ft^2$')\nplt.ylabel('Price ($USD)')\nplt.legend(loc='best')\n```\n\nThis version of the *gradient descent algorithm* is often called **batch gradient descent algorithm**, beacuse is uses all the training examples at each step of the process.\n\n\n\n
\nCreated with Jupyter by Esteban Jiménez Rodríguez. Based on the content of the Machine Learning course offered through coursera by Prof. Andrew Ng.\n
\n", "meta": {"hexsha": "55bb917b97b235399016a82623d457aa3831257b", "size": 236137, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Week1/3ParameterLearning.ipynb", "max_stars_repo_name": "esjimenezro/ml_course", "max_stars_repo_head_hexsha": "5967489aeda57451228014df13c30ca356c79b84", "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": "Week1/3ParameterLearning.ipynb", "max_issues_repo_name": "esjimenezro/ml_course", "max_issues_repo_head_hexsha": "5967489aeda57451228014df13c30ca356c79b84", "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": "Week1/3ParameterLearning.ipynb", "max_forks_repo_name": "esjimenezro/ml_course", "max_forks_repo_head_hexsha": "5967489aeda57451228014df13c30ca356c79b84", "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": 262.0832408435, "max_line_length": 72972, "alphanum_fraction": 0.9195594083, "converted": true, "num_tokens": 3890, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.964321452198369, "lm_q2_score": 0.8840392741081574, "lm_q1q2_score": 0.8524980366083703}} {"text": "## Ackley\n\nThe Ackley function is widely used for testing optimization algorithms. In its two-dimensional form, as shown in the plot above, it is characterized by a nearly flat outer region, and a large hole at the centre. The function poses a risk for optimization algorithms, particularly hillclimbing algorithms, to be trapped in one of its many local minima. \n\n**Definition**\n\n\\begin{align}\n\\begin{split}\nf(x) &=& \\,-a \\exp{ \\Bigg[ -b \\, \\sqrt{ \\frac{1}{n} \\sum_{i=1}^{n}{x_i}^2 } \\Bigg]} - \\exp{ \\Bigg[ \\frac{1}{n}\\sum_{i=1}^{n}{cos(c x_i)} \\Bigg] } + a + e, \\\\[2mm]\n&& a = \\;20, \\quad b = \\; \\frac{1}{5}, \\quad c = \\;2 \\pi \\\\[2mm]\n&&-32.768 \\leq x_i \\leq 32.768, \\quad i=1 \\ldots,n \\\\[4mm]\n\\end{split}\n\\end{align}\n\n**Optimum**\n\n$$f(x^*) = 0 \\; \\text{at} \\; x^* = (0,\\ldots,0) $$\n\n**Contour**\n\n\n```python\nimport numpy as np\nfrom pymoo.factory import get_problem, get_visualization\n\nproblem = get_problem(\"ackley\", n_var=2, a=20, b=1/5, c=2 * np.pi)\nget_visualization(\"fitness-landscape\", problem, angle=(45, 45), _type=\"surface\").show()\nget_visualization(\"fitness-landscape\", problem, _type=\"contour\", colorbar=True).show()\n```\n", "meta": {"hexsha": "be5e8236a5fbeb9660bc74b9e1374b3513193659", "size": 994965, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "source/problems/single/ackley.ipynb", "max_stars_repo_name": "SunTzunami/pymoo-doc", "max_stars_repo_head_hexsha": "f82d8908fe60792d49a7684c4bfba4a6c1339daf", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-09-11T06:43:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-10T13:36:09.000Z", "max_issues_repo_path": "source/problems/single/ackley.ipynb", "max_issues_repo_name": "SunTzunami/pymoo-doc", "max_issues_repo_head_hexsha": "f82d8908fe60792d49a7684c4bfba4a6c1339daf", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2021-09-21T14:04:47.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-07T13:46:09.000Z", "max_forks_repo_path": "source/problems/single/ackley.ipynb", "max_forks_repo_name": "SunTzunami/pymoo-doc", "max_forks_repo_head_hexsha": "f82d8908fe60792d49a7684c4bfba4a6c1339daf", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-10-09T02:47:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-10T07:02:37.000Z", "avg_line_length": 7370.1111111111, "max_line_length": 991664, "alphanum_fraction": 0.9647384581, "converted": true, "num_tokens": 396, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422241476943, "lm_q2_score": 0.8962513786759491, "lm_q1q2_score": 0.8524625297092796}} {"text": "# 6. Similarity Functions\n\n- **Created by Andrés Segura Tinoco**\n- **Created on May 20, 2019**\n- **Updated on Mar 19, 2021**\n\nIn statistics and related fields, a **similarity measure** or similarity function is a real-valued function that quantifies the similarity between two objects. In short, a similarity function quantifies how much alike two data objects are [1].\n\n## 6.1. Common similarity functions\n\n\n```python\n# Load the Python libraries\nfrom math import *\nfrom decimal import Decimal\nfrom scipy import stats as ss\nimport sklearn.metrics.pairwise as sm\nimport math\n```\n\n\\begin{align}\n similarity(X, Y) = d(X, Y) = \\sqrt{\\sum_{i=1}^n (X_i - Y_i)^2} \\tag{1}\n\\end{align}\n\n\n```python\n# (1) Euclidean distance function\ndef euclidean_distance(x, y):\n return sqrt(sum(pow(a-b,2) for a, b in zip(x, y)))\n```\n\n\\begin{align}\n similarity(X, Y) = d(X, Y) = \\sum_{i=1}^n |X_i - Y_i| \\tag{2}\n\\end{align}\n\n\n```python\n# (2) manhattan distance function\ndef manhattan_distance(x, y):\n return sum(abs(a-b) for a,b in zip(x,y))\n```\n\n\\begin{align}\n similarity(X, Y) = d(X, Y) = (\\sum_{i=1}^n |X_i - Y_i|^p)^\\frac{1}{p} \\tag{3}\n\\end{align}\n\n\n```python\n# (3) Minkowski distance function\ndef _nth_root(value, n_root):\n root_value = 1/float(n_root)\n return round(Decimal(value) ** Decimal(root_value),3)\n\ndef minkowski_distance(x, y, p = 3):\n return float(_nth_root(sum(pow(abs(a-b), p) for a,b in zip(x, y)), p))\n```\n\n\\begin{align}\n similarity(X, Y) = cos(\\theta) = \\frac{\\vec{X}.\\vec{Y}}{\\|\\vec{X}\\|.\\|\\vec{Y}\\|} = \\frac{\\sum_{i=1}^n X_i.Y_i}{\\sqrt{\\sum_{i=1}^n X_i^2}.\\sqrt{\\sum_{i=1}^n Y_i^2}} \\tag{4}\n\\end{align}\n\n\n```python\n# (4) Cosine similarity function\ndef _square_rooted(x):\n return round(sqrt(sum([a*a for a in x])),3)\n\ndef cosine_similarity(x, y):\n numerator = sum(a*b for a,b in zip(x,y))\n denominator = _square_rooted(x) * _square_rooted(y)\n return round(numerator/float(denominator),3)\n```\n\n\\begin{align}\n similarity(X, Y) = \\frac{cov(X, Y)}{\\sigma_X . \\sigma_Y} = \\frac{\\sum_{i=1}^n (X_i - \\bar{X}).(Y_i - \\bar{Y})}{\\sqrt{\\sum_{i=1}^n (X_i - \\bar{X})^2 . (Y_i - \\bar{Y})^2}} \\tag{5}\n\\end{align}\n\n\n```python\n# (5) Pearson similarity function\ndef _avg(x):\n assert len(x) > 0\n return float(sum(x)) / len(x)\n\ndef pearson_similarity(x, y):\n assert len(x) == len(y)\n n = len(x)\n assert n > 0\n avg_x = _avg(x)\n avg_y = _avg(y)\n diffprod = 0\n xdiff2 = 0\n ydiff2 = 0\n for idx in range(n):\n xdiff = x[idx] - avg_x\n ydiff = y[idx] - avg_y\n diffprod += xdiff * ydiff\n xdiff2 += xdiff * xdiff\n ydiff2 += ydiff * ydiff\n\n return diffprod / math.sqrt(xdiff2 * ydiff2)\n```\n\n\\begin{align}\n similarity(X, Y) = J(X, Y) = \\frac{|X \\cap Y|}{|X \\cup Y|} = \\frac{|X \\cap Y|}{|X| + |Y| - |X \\cap Y|} \\tag{6}\n\\end{align}\n\n\n```python\n# (6) Jaccard similarity function\ndef jaccard_similarity(x, y):\n intersection_cardinality = len(set.intersection(*[set(x), set(y)]))\n union_cardinality = len(set.union(*[set(x), set(y)]))\n return intersection_cardinality / float(union_cardinality)\n```\n\n## 6.2. Manual examples\n\n\n```python\n# Vectors\nx = [-4.593481, -5.478033, 1.127111, 1.252885, -2.286953] # Messi\ny = [-4.080334, -3.406618, 4.334073, -0.485612, -2.817897] # CR\nz = [-4.048185, -5.546171, 0.505673, 0.616553, -1.730906] # Neymar\n```\n\n### Euclidean distance\n\n\n```python\neuclidean_distance(x, y)\n```\n\n\n\n\n 4.259455195846412\n\n\n\n\n```python\neuclidean_distance(x, z)\n```\n\n\n\n\n 1.1841800466723797\n\n\n\n### Manhattan distance\n\n\n```python\nmanhattan_distance(x, y)\n```\n\n\n\n\n 8.060965\n\n\n\n\n```python\nmanhattan_distance(x, z)\n```\n\n\n\n\n 2.4272509999999996\n\n\n\n### Minkowski distance\n\n\n```python\nminkowski_distance(x, y)\n```\n\n\n\n\n 3.619\n\n\n\n\n```python\nminkowski_distance(x, z)\n```\n\n\n\n\n 0.941\n\n\n\n### Cosine similarity\n\n\n```python\ncosine_similarity(x, y)\n```\n\n\n\n\n 0.842\n\n\n\n\n```python\ncosine_similarity(x, z)\n```\n\n\n\n\n 0.99\n\n\n\n### Pearson similarity\n\n\n```python\npearson_similarity(x, y)\n```\n\n\n\n\n 0.8214001476231276\n\n\n\n\n```python\npearson_similarity(x, z)\n```\n\n\n\n\n 0.9888645775446726\n\n\n\n### Jaccard similarity\n\n\n```python\na = [0, 1, 2, 3, 4, 5]\nb = [-1, 1, 2, 0, 3, 5]\n```\n\n\n```python\njaccard_similarity(a, b)\n```\n\n\n\n\n 0.7142857142857143\n\n\n\n## 6.3. Sklearn examples\n\n\n```python\ncorr = sm.euclidean_distances([x], [y])\nfloat(corr[0])\n```\n\n\n\n\n 4.259455195846413\n\n\n\n\n```python\ncorr = sm.manhattan_distances([x], [y])\nfloat(corr[0])\n```\n\n\n\n\n 8.060965\n\n\n\n\n```python\ncorr = sm.cosine_similarity([x], [y])\nfloat(corr[0])\n```\n\n\n\n\n 0.841904969009294\n\n\n\n\n```python\ncorr, p_value = ss.pearsonr(x, y)\ncorr\n```\n\n\n\n\n 0.8214001476231275\n\n\n\n## Reference\n\n[1] Wikipedia - Similarity measure. \n\n---\n« Home\n", "meta": {"hexsha": "e79592db92a45d90d69613d9b86840e28894a12f", "size": 13165, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "similarity-functions/SimilarityFunctions.ipynb", "max_stars_repo_name": "ansegura7/Algorithms", "max_stars_repo_head_hexsha": "4788c183ff42964dacc2bb51d7715f120d79c447", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 112, "max_stars_repo_stars_event_min_datetime": "2020-01-08T17:10:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-20T07:34:25.000Z", "max_issues_repo_path": "similarity-functions/SimilarityFunctions.ipynb", "max_issues_repo_name": "suanhwee1234/Algorithms", "max_issues_repo_head_hexsha": "7ac304fac42a8dec50580c78e623b0f5c021373b", "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": "similarity-functions/SimilarityFunctions.ipynb", "max_forks_repo_name": "suanhwee1234/Algorithms", "max_forks_repo_head_hexsha": "7ac304fac42a8dec50580c78e623b0f5c021373b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 19, "max_forks_repo_forks_event_min_datetime": "2019-07-15T20:14:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-28T03:06:38.000Z", "avg_line_length": 20.1607963247, "max_line_length": 275, "alphanum_fraction": 0.4781617926, "converted": true, "num_tokens": 1708, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422158380861, "lm_q2_score": 0.8962513634345444, "lm_q1q2_score": 0.8524625077650384}} {"text": "# Importance Sampling \n\n\nThe expectation value of a function $H({\\bf x})$ is defined as\n\n$$\n\\begin{align}\n \\langle H({\\bf x})\\rangle_{f} = \\int d{\\bf x} H({\\bf x}) f({\\bf x; u}),\n\\end{align}\n$$\n\nwhere $f({\\bf x})$ is the probability distribution. The unbiased estimator of this expectation value is\n\n$$\n\\begin{align}\n\\langle H({\\bf x})\\rangle_{f} \\approx \\frac{1}{N}\\sum_{i=1} H({\\bf X_i}),\n\\end{align}\n$$\nwhere the sample points $X_i$ are drawn from the distribution $f$. This method may be a computationally inneficient estimate of the expectation value of $H$. We would like to modify our previous estimator to the form \n$$\n\\begin{align}\n\\langle H({\\bf x})\\rangle_{g} \\approx \\frac{1}{N}\\sum_{i=1} w(X_i)H({\\bf X_i}),\n\\end{align}\n$$\nwhere $w(X_i)$ is an unknown weight factor and $X_i$ are drawn from a new probability distribution $g({\\bf x})$ that samples $H(x)$ more effectively. \n\n\nWe would like to relate how the weight functions $w(x)$ relate to the new distribution $g(x)$. This relation is very simple\n$$\n\\begin{align}\n \\langle H({\\bf x})\\rangle_{f} &= \\int d{\\bf x} H({\\bf x}) f({\\bf x; u}),\\\\\n &= \\int d{\\bf x} H({\\bf x}) \\frac{f({\\bf x; u})}{g({\\bf x})} g({\\bf x}) \\\\\n &= \\int d{\\bf x} H({\\bf x}) w({\\bf x; u}) g({\\bf x}) \\\\\n &\\equiv \\langle H({\\bf x})\\rangle_{g}.\n\\end{align}\n$$\n\n\nNow we would like to choose the best distribution function $g^*({\\bf x})$ to sample $H({\\bf x})$. This can be done by choosing the $g({\\bf x})$ function that minimizes the variance of the estimate $\\langle H({\\bf x})\\rangle_g$ \n\nThe variance of this estimate is given by the integral\n$$\n\\begin{align}\n\\sigma^2 = \\int d{\\bf x} \\left( w({\\bf x})H({\\bf x})-\\mu \\right)^2 g({\\bf x}),\n\\end{align}\n$$\nwhere $\\mu$ is the expectation value of the function $H({\\bf x})$. Minimizing the variance of this expression with respect to $w({\\bf x})$, we get\n\n$$\n\\begin{align}\n\\frac{d\\sigma^2}{dw} = 0 &= \\int d{\\bf x} \\left( w({\\bf x})H({\\bf x})-\\mu \\right)H(x)\\delta({\\bf x-y}) g({\\bf x}) \\\\\n&\\Rightarrow \\\\\nw({\\bf y}) &= \\frac{\\mu}{H({\\bf y})}\n\\end{align}\n$$\n\nRe-writing $w({\\bf y})$ in terms of $f$ and $g$ gives,\n\n$$\n\\begin{align}\ng^*({\\bf y}) = \\frac{H({\\bf y})f({\\bf y; u})}{\\mu}.\n\\end{align}\n$$\n\nThis last expression for $g^*$ represents the optimal choice of the importance sampling function $g$. If we want to find the best function $g({\\bf y})$ to carry out importance sampling, we must choose $g=g^*$ given above.\n\n\n# Cross Entropy Estimation\n\n\nLet us return to the problem of estimating the expectation value\n$$\n\\begin{align}\n\\langle H({\\bf x})\\rangle_{f} = \\int d{\\bf x} H({\\bf x}) f({\\bf x; u}).\n\\end{align}\n$$\nThe best importance sampling function to estimate this integral is\n$$\n\\begin{align}\ng^*({\\bf x}) = \\frac{H({\\bf x})f({\\bf x;u})}{\\mu}.\n\\end{align}\n$$\n\nInstead of using this function directly with the unknown parameter $\\mu$, we approximate the function $g^*(x)$ using our parametrized function $f({\\bf x;v})$. This approximation can be carried out using the Kullback-Leibler divergence\n\n$$\n\\begin{align}\nD(g^*,f({\\bf x;v})) = \\int dx \\ g^*({\\bf x}) {\\rm ln}(g^*({\\bf x})) - \\int dx \\ g^*({\\bf x}) {\\rm ln}(f({\\bf x;v})).\n\\end{align}\n$$\n\nThe above expression vanishes when the two functions $g^*$ and $f$ are equal. To minimize the above expression in terms of the parameter ${\\bf v}$, we must maximize the expression\n$$\n\\begin{align}\nD({\\bf v}) &= \\int dx \\ g^*({\\bf x}) {\\rm ln}(f({\\bf x; v})),\\\\\n &= \\frac{1}{\\mu}\\int dx \\ H({\\bf x}) f({\\bf x; u}) {\\rm ln}(f({\\bf x; v})),\\\\\n &= \\frac{1}{\\mu}\\int dx \\ H({\\bf x}) \\frac{f({\\bf x; u})}{f({\\bf x,w})} {\\rm ln}(f({\\bf x; v})) f({\\bf x,w}),\\\\\n &= \\frac{1}{\\mu}\\int dx \\ H({\\bf x}) w({\\bf x;u,w}) {\\rm ln}(f({\\bf x; v})) f({\\bf x,w}).\n\\end{align}\n$$\nTherefore, The optimal choice of ${\\bf v}$ is given by solving the expression\n$$\n\\begin{align}\n\\nabla_{\\bf v}D({\\bf v}) &= 0 \\\\\n\\int dx \\ H({\\bf x}) w({\\bf x;u,w}) {\\bf \\nabla}_{\\bf v}{\\rm ln}(f({\\bf x; v})) f({\\bf x,w})&=0.\n\\end{align}\n$$\nWhen sampling this integral, this last expression will be\n\n$$\n\\begin{align}\n\\frac{1}{N}\\sum_i H({\\bf X_i})w({\\bf X_i;u,w}) \\nabla_{\\bf v}{\\rm ln}(f({\\bf X_i;v})) = 0\n\\end{align}\n$$\nwhere \n$$\nX_i \\sim f({\\bf x,w}).\n$$\n\n\n## Using Cross Entropy for Optimization\n\nTo optimize the function $H({\\bf x})$ using cross entropy optimization we will consider the integral that represents that the function $H({\\bf x})$ is greater or equal to the maximum of the function $H({\\bf x^*})=\\gamma^*$.\n\n$$\nP(H >= \\gamma^*) = \\int d{\\bf x} \\ I_{ \\lbrace H({\\bf x}) >= \\gamma^* \\rbrace }(x) f({\\bf x; u})\n$$\n\nNote that we dont know ahead of time what $x^*$ and $\\gamma^*$ are yet. These will be updated iteratively.\n\n\n\nUsing the ideas of importance sampling and minimizing the KL-divergence from the previous section, \n$$\n\\begin{align}\n\\frac{1}{N}\\sum_i H({\\bf X_i})\\nabla_{\\bf v}{\\rm ln}(f({\\bf X_i;v})) = 0\n\\end{align}\n$$\nwhere $X_i \\sim f({\\bf x,u})$. The algorithm to do this iteratively is below\n\n\n#### Algorithm\n\n* Choose $\\rho$ \n* Choose $N$ \n* Initilize ${\\bf u}$\n\n\n\n1. Sample $N$ points, $X_i \\sim f({\\bf x,u})$, compute $H(X_i)$\n2. Order $(X_i,H(X_i))$ in decending order according to the values $H(X_i)$ \n3. Using the $N_\\rho = N\\rho$ elite samples determine the solution ${\\bf v}$ to \n\n\n$$ \n\\frac{1}{N_\\rho}\\sum\\limits_{i=1}^{N_\\rho} H({\\bf X_i})\\nabla_{\\bf v}{\\rm ln}(f({\\bf X_i;v})) = 0 \n$$\n\nlet this new solution replace the previous result, ${\\bf v} \\rightarrow {\\bf u}$\n\n4. Go to step 1, repeat until convergence criteria is met\n\n\n#### References \n\n[ [1] ](http://web.mit.edu/6.454/www/www_fall_2003/gew/CEtutorial.pdf) **A Tutorial on the Cross-Entropy Method** Pieter-Tjerk de Boer \n\n[[2]](https://link.springer.com/article/10.1007/s11009-006-9753-0) D. P. Kroese, S. Porotsky and R. Y. Rubinstein, **The Cross-Entropy Method for Continuous\nMulti-Extremal Optimization**, Methodol. Comput. Appl. Probab. 8 (2006).\n\n[[3]](https://www.sciencedirect.com/science/article/pii/S0968090X1100088X?via%3Dihub) M. Maher, R. Liu, D. Ngoduy, **Signal optimization using the cross entropy method**, Transportation Research C. 27, (2013). \n\n\n[[4]](https://www.sciencedirect.com/science/article/pii/B9780444538598000035) Zdravko I. Botev, Dirk P. Kroese, Reuven Y. Rubinstein, Pierre L’Ecuyer, **Chapter 3 - The Cross-Entropy Method for Optimization**, Handbook of Statistics, Elsevier, 31, 35-59, (2013).\n\n# Let us now implement the above algorithm as a simple example\n\n\n```python\n# Simple Implementation\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n```\n\n\n```python\ndef H(x):\n '''\n This function has a global maximum at x=10\n and local maximum at x=-2\n '''\n return np.exp(-(x-10)**2)+0.8*np.exp(-(x+2)**2)\n\nx = np.linspace(-20,20,num=1000)\n\nplt.plot(x,H(x))\nplt.show()\n```\n\n\n```python\n\nN = 1000\nrho = 0.1\nmu, sigma = -20.0,1000.0\nN_rho = int(N*rho)\n\nsteps =200\n\n\nfor k in range(0,steps):\n x_samples = np.random.normal(loc=mu,scale=sigma,size=N)\n H_samples = H(x_samples) \n data = np.array((x_samples,H_samples)).T\n\n # Now sort these tuples according to H(x_i) values\n sorted_data = np.array(sorted(data,key= lambda x: x[1],reverse=True))\n x_elite_samples = sorted_data[0:N_rho,0]\n \n # Update the Gaussian distribution parameters with the elite samples\n mu = np.mean(x_elite_samples)\n sigma = np.std(x_elite_samples)\n \n\n\nprint('Result from cross-entropy optimization: {0:0=.2f}'.format(mu))\nprint('Global maximum: {}'.format(10.0))\n```\n\n Result from cross-entropy optimization: 10.00\n Global maximum: 10.0\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "a908a400503bc36f9718ea59f441556dcc48995e", "size": 23837, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Cross_Entropy_Optimization.ipynb", "max_stars_repo_name": "OscarJHernandez/qc_portfolio_optimization", "max_stars_repo_head_hexsha": "30f0e27689ad6bf37fb87880c2813a5b9858608d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 15, "max_stars_repo_stars_event_min_datetime": "2020-06-29T08:33:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-12T00:28:51.000Z", "max_issues_repo_path": "Cross_Entropy_Optimization.ipynb", "max_issues_repo_name": "OscarJHernandez/qc_mentorship_project", "max_issues_repo_head_hexsha": "30f0e27689ad6bf37fb87880c2813a5b9858608d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-11-27T09:34:13.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-30T21:13:41.000Z", "max_forks_repo_path": "Cross_Entropy_Optimization.ipynb", "max_forks_repo_name": "OscarJHernandez/qc_mentorship_project", "max_forks_repo_head_hexsha": "30f0e27689ad6bf37fb87880c2813a5b9858608d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 11, "max_forks_repo_forks_event_min_datetime": "2020-06-29T08:40:24.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-24T17:39:16.000Z", "avg_line_length": 75.673015873, "max_line_length": 12716, "alphanum_fraction": 0.753870034, "converted": true, "num_tokens": 2612, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741322079104, "lm_q2_score": 0.8947894717137996, "lm_q1q2_score": 0.8523533045265473}} {"text": "$\\newcommand{\\ind}[1]{\\left[#1\\right]}$\n\n# Model\n\n- Data set\n$$ {\\cal D} = \\{ x_1, \\dots x_N \\} $$\n- Model with parameter $\\theta$\n$$ p(\\cal D | \\theta) $$\n\n\n\n\n## Maximum Likelihood\n\n- Maximum Likelihood (ML)\n$$ \\theta^{\\text{ML}} = \\arg\\max_{\\theta} \\log p({\\cal D} | \\theta) $$\n- Predictive distribution\n$$ p(x_{N+1} | {\\cal D} ) \\approx p(x_{N+1} | \\theta^{\\text{ML}}) $$\n\n## Maximum Aposteriori\n\n- Prior\n$$ p(\\theta) $$\n\n- Maximum a-posteriori (MAP) : Regularised Maximum Likelihood\n$$\n\\theta^{\\text{MAP}} = \\arg\\max_{\\theta} \\log p({\\cal D} | \\theta) p(\\theta)\n$$\n\n- Predictive distribution\n$$ p(x_{N+1} | {\\cal D} ) \\approx p(x_{N+1} | \\theta^{\\text{MAP}}) $$\n\n## Bayesian Learning\n\n- We treat parameters on the same footing as all other variables\n- We integrate over unknown parameters rather than using point estimates (remember the many-dice example)\n - Self-regularisation, avoids overfitting\n - Natural setup for online adaptation\n - Model selection\n\n\n- Predictive distribution\n\\begin{eqnarray}\np(x_{N+1} , {\\cal D} ) &=& \\int d\\theta \\;\\; p(x_{N+1} | \\theta) p( {\\cal D}| \\theta) p(\\theta) \\\\\n &=& \\int d\\theta \\;\\; p(x_{N+1}| \\theta) p( {\\cal D}, \\theta) \\\\\n &=& \\int d\\theta \\;\\; p(x_{N+1}| \\theta) p( \\theta| {\\cal D}) p({\\cal D}) \\\\\n &=& p({\\cal D}) \\int d\\theta \\;\\; p(x_{N+1}| \\theta) p( \\theta| {\\cal D}) \\\\\np(x_{N+1} | {\\cal D} ) &=& \\int d\\theta \\;\\; p(x_{N+1} | \\theta) p(\\theta | {\\cal D}) \n\\end{eqnarray}\n\nThe interpretation is that past data provides an 'update' to the recent prior to be used for the current prediction.\n\n- Bayesian learning is just inference ...\n\n\n\n\n# Learning the parameter of a (possibly fake) coin\n\nSuppose we have a coin, flipped several times independently. A vague question one can ask is if one can predict the outcome of the next flip.\n\nIt depends. If we already know that the coin is fair, there is nothing that we can learn from past data and indeed the future flips are independent of the previous flips. However, if we don't know the probability of the coin, we could estimate the parameter from past data to create a better prediction. Mathematically, the model is identical to \n\n\n\nHere, $\\theta$ is the parameter of the coin.\n\n## Maximum Likelihood Estimation\n\nWe observe the outcome of $N$ coin flips $\\{x^{(n)}\\}_{n=1\\dots N}$ where $x^{(n)} \\in \\left\\{0,1\\right\\}$. The model is a Bernoulli distribution with parameter $\\pi = (\\pi_0, \\pi_1)$. We have $\\pi_0 = 1 - \\pi_1$ where $0 \\leq \\pi_1 \\leq 1$. \n\n\\begin{eqnarray}\nx^{(n)} & \\sim & p(x|\\pi) = (1-\\pi_1)^{1-x^{(n)} } \\pi_1^{x^{(n)} }\n\\end{eqnarray}\n\nThe loglikelihood is \n\n\\begin{eqnarray}\n{\\cal L}(\\pi_1) & = & \\sum_{n=1}^N (1- x^{(n)}) \\log (1 - \\pi_1) + \\sum_{n=1}^N x^{(n)} \\log (\\pi_1) \\\\\n& = & \\log (1 - \\pi_1) \\sum_{n=1}^N (1- x^{(n)}) + \\log (\\pi_1) \\sum_{n=1}^N x^{(n)} \n\\end{eqnarray}\n\nWe define the number of $0$'s \n\\begin{eqnarray}\nc_0 = \\sum_{n=1}^N (1- x^{(n)})\n\\end{eqnarray}\nand $1$'s as\n\\begin{eqnarray}\nc_1 = \\sum_{n=1}^N x^{(n)}\n\\end{eqnarray}\n\n\\begin{eqnarray}\n{\\cal L}(\\pi_1) & = & \\log (1 - \\pi_1) c_0 + \\log (\\pi_1) c_1 \n\\end{eqnarray}\n\nWe compute the gradient \n\\begin{eqnarray}\n\\frac{\\partial}{\\partial \\pi_1} {\\cal L}(\\pi_1) & = & - \\frac{c_0}{1 - \\pi_1} + \\frac{c_1}{\\pi_1} = 0 \n\\end{eqnarray}\n\nThe solution is quite predictable\n\\begin{eqnarray}\n\\pi_1 & = &\\frac{c_1}{c_0 + c_1} = \\frac{c_1}{N} \n\\end{eqnarray}\n\n## Maximum A-posteriori estimation\n\nWe need a prior over the probability parameter. One choice is the beta distribution\n\n\\begin{eqnarray}\np(\\pi_1) & = & \\mathcal{B}(\\pi_1; \\alpha, \\beta) = \\frac{\\Gamma(\\alpha + \\beta)}{\\Gamma(\\alpha) \\Gamma(\\beta) } \\pi_1^{\\alpha-1} (1-\\pi_1)^{\\beta-1}\n\\end{eqnarray}\n\nThe log joint ditribution of data is\n\\begin{eqnarray}\n\\log p(X, \\pi_1) & = & \\log p(\\pi_1) + \\sum_{n=1}^N \\log p(x^{(n)}|\\pi_1) \\\\\n& = & \\log \\Gamma(\\alpha + \\beta) -\\log \\Gamma(\\alpha) - \\log \\Gamma(\\beta) \\\\\n& & + (\\alpha-1) \\log \\pi_1 + (\\beta-1) \\log(1-\\pi_1) \\\\\n& & + c_1 \\log (\\pi_1) + c_0 \\log (1 - \\pi_1) \\\\\n& = & \\log \\Gamma(\\alpha + \\beta) -\\log \\Gamma(\\alpha) - \\log \\Gamma(\\beta) \\\\\n& & + (\\alpha + c_1 -1) \\log \\pi_1 + (\\beta + c_0 -1) \\log(1-\\pi_1) \n\\end{eqnarray}\n\nThe gradient is \n\n\\begin{eqnarray}\n\\frac{\\partial}{\\partial \\pi_1} \\log p(X, \\pi_1) & = & - \\frac{\\beta + c_0 -1}{1 - \\pi_1} + \\frac{\\alpha + c_1 -1}{\\pi_1} = 0 \n\\end{eqnarray}\n\nWe can solve for the parameter.\n\\begin{eqnarray}\n\\pi_1 (\\beta + c_0 -1) & = & (1 - \\pi_1) (\\alpha + c_1 -1) \\\\ \n\\pi_1 \\beta + \\pi_1 c_0 - \\pi_1 & = & \\alpha + c_1 - 1 - \\pi_1 \\alpha - \\pi_1 c_1 + \\pi_1 \\\\ \n\\pi_1 & = & \\frac{\\alpha - 1 + c_1}{\\alpha + \\beta - 2 + c_0 + c_1} \\\\ \n\\end{eqnarray}\n\nWhen the prior is flat, i.e., when $\\alpha = \\beta = 1$, MAP and ML solutions coincide.\n\n## Full Bayesian inference\n\nWe infer the posterior\n\n\\begin{eqnarray}\np(\\pi_1| X) & = & \\frac{p(\\pi_1, X)}{p(X)} \n\\end{eqnarray}\n\n\nThe log joint density is \n\\begin{eqnarray}\n\\log p(X, \\pi_1) & = & \\log \\Gamma(\\alpha + \\beta) -\\log \\Gamma(\\alpha) - \\log \\Gamma(\\beta) \\\\\n& & + (\\alpha + c_1 -1) \\log \\pi_1 + (\\beta + c_0 -1) \\log(1-\\pi_1) \n\\end{eqnarray}\n\nAt this stage, we may try to evaluate the integral \n$$\np(X) = \\int d\\pi_1 p(X, \\pi_1) \n$$\n\nRather than trying to evaluate this integral directly, a simple approach is known as 'completing the square': we add an substract terms to obtain an expression that corresponds to a known, normalized density. This typically involves adding and substracting an expression that will make us identify a normalized density. \n\n\\begin{eqnarray}\n\\log p(X, \\pi_1) & = & \\log \\Gamma(\\alpha + \\beta) -\\log \\Gamma(\\alpha) - \\log \\Gamma(\\beta) \\\\\n& & - \\log \\Gamma(\\alpha + \\beta + c_0 + c_1) + \\log \\Gamma(\\alpha + c_1) + \\log \\Gamma(\\beta + c_0) \\\\\n& & + \\log \\Gamma(\\alpha + \\beta + c_0 + c_1) - \\log \\Gamma(\\alpha + c_1) - \\log \\Gamma(\\beta + c_0) \\\\\n& & + (\\alpha + c_1 -1) \\log \\pi_1 + (\\beta + c_0 -1) \\log(1-\\pi_1) \\\\\n& = & \\log \\Gamma(\\alpha + \\beta) -\\log \\Gamma(\\alpha) - \\log \\Gamma(\\beta) \\\\\n& & - \\log \\Gamma(\\alpha + \\beta + c_0 + c_1) + \\log \\Gamma(\\alpha + c_1) + \\log \\Gamma(\\beta + c_0) \\\\\n& & + \\log \\mathcal{B}(\\alpha + c_1, \\beta + c_0) \\\\\n& = & \\log p(X) + \\log p(\\pi_1| X)\n\\end{eqnarray}\n\nFrom the resulting expression, taking the exponent on both sides we see that \n\\begin{eqnarray}\np(\\pi_1| X) & = & \\mathcal{B}(\\alpha + c_1, \\beta + c_0) \\\\\np(X) & = & \\frac{\\Gamma(\\alpha + \\beta)}{\\Gamma(\\alpha)\\Gamma(\\beta)} \\frac{\\Gamma(\\alpha + c_1)\\Gamma(\\beta + c_0)}{\\Gamma(\\alpha + \\beta + c_0 + c_1)}\n\\end{eqnarray}\n\nPredictive distribution: Let $a=\\alpha + c_1$ and $b=\\beta+c_0$\n\n\\begin{eqnarray}\n\\int d\\pi_1 p(x|\\pi_1) p(\\pi_1| X) & = & \\int d\\pi_1 \\mathcal{BE}(x; \\pi_1) \\mathcal{B}(\\pi_1; a, b) \\\\\n & = & \\int d\\pi_1 \\pi_1^{\\ind{x=1}}(1-\\pi_1)^{\\ind{x=0}}\\mathcal{B}(a, b) \\\\\n\\end{eqnarray}\n\n\\begin{eqnarray}\np(x) & = & \\frac{\\Gamma(a + b)}{\\Gamma(a)\\Gamma(b)} \\frac{\\Gamma(a + \\ind{x=1})\\Gamma(b + \\ind{x=0})}{\\Gamma(b + a + 1)}\n\\end{eqnarray}\n\n\\begin{eqnarray}\np(x=1) & = & \\frac{\\Gamma(a + b)}{\\Gamma(a)\\Gamma(b)} \\frac{\\Gamma(a + 1)\\Gamma(b)}{\\Gamma(b + a + 1)} \\\\\n& = & \\frac{\\Gamma(a + b)}{\\Gamma(a)\\Gamma(b)} \\frac{a\\Gamma(a)\\Gamma(b)}{(b+a)\\Gamma(b + a)} \\\\\n& = & \\frac{a}{a+b}\n\\end{eqnarray}\n\n\n## Alternative Derivation\nAlternatively, we may directly write\n\\begin{eqnarray}\np(X, \\pi_1) & = & \\frac{\\Gamma(\\alpha + \\beta)}{\\Gamma(\\alpha)\\Gamma(\\beta)} \\pi_1^{(\\alpha + c_1 -1)} (1-\\pi_1)^{(\\beta + c_0 -1)} \n\\end{eqnarray}\n\n\\begin{eqnarray}\np(X) &=& \\int d\\pi_1 p(X, \\pi_1) = \\frac{\\Gamma(\\alpha + \\beta)}{\\Gamma(\\alpha)\\Gamma(\\beta)} \\int d\\pi_1 \\pi_1^{(\\alpha + c_1 -1)} (1-\\pi_1)^{(\\beta + c_0 -1)} \n\\end{eqnarray}\n\n\nFrom the definition of the beta distribution, we can arrive at the 'formula' for the integral \n\\begin{eqnarray}\n1 &=& \\int d\\pi \\mathcal{B}(\\pi; a, b) \\\\\n& = & \\int d\\pi \\frac{\\Gamma(a + b)}{\\Gamma(a)\\Gamma(b)} \\pi^{(a -1)} (1-\\pi)^{(b -1)} \\\\\n\\frac{\\Gamma(a)\\Gamma(b)}{\\Gamma(a + b)} & = & \\int d\\pi \\pi^{(a -1)} (1-\\pi)^{(b -1)}\n\\end{eqnarray}\nJust substitute $a = \\alpha + c_1$ and $b = \\beta + c_0$\n\n## An Approximation\nFor large $x$, we have the following approximation\n\\begin{eqnarray}\n\\log \\Gamma(x + a) - \\log \\Gamma(x) & \\approx & a \\log(x) \\\\\n\\Gamma(x + a) & \\approx & \\Gamma(x) x^a \\\\\n\\end{eqnarray}\n\nWhen $c_0$ and $c_1$ are large, we obtain:\n\n\\begin{eqnarray}\np(X) & \\approx & \\frac{\\Gamma(\\alpha + \\beta)}{\\Gamma(\\alpha)\\Gamma(\\beta)} \\frac{\\Gamma(c_1)\\Gamma(c_0)c_0^{\\beta}c_1^{\\alpha}}{\\Gamma(c_0 + c_1)(c_0+c_1)^{\\alpha + \\beta}}\n\\end{eqnarray}\n\nLet $\\hat{\\pi}_1 = c_1/(c_0+c_1)$ and $N = c_0 + c_1$, we have\n\\begin{eqnarray}\np(X) & \\approx & \\frac{\\Gamma(c_1)\\Gamma(c_0)}{\\Gamma(c_0 + c_1)} (1-\\hat{\\pi}_1) \\hat{\\pi}_1 \\frac{\\Gamma(\\alpha + \\beta)}{\\Gamma(\\alpha)\\Gamma(\\beta)} (1-\\hat{\\pi}_1)^{\\beta-1}\\hat{\\pi}_1^{\\alpha-1}\n\\end{eqnarray}\n\n### Illustration: Bayesian update of a Beta Distribution \n\n\n```python\n%matplotlib inline\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom scipy.special import gammaln\n\ndef log_beta_pdf(x, a, b):\n return - gammaln(a) - gammaln(b) + gammaln(a+b) + np.log(x)*(a-1) + np.log(1-x)*(b-1) \n\nx = np.arange(0.01,1,0.01)\n\na = 1\nb = 1\nc_0 = 1\nc_1 = 1\nN = c_0 + c_1\n\npi_ML = c_1/N\n\nplt.figure(figsize=(8,4))\nplt.plot(x, np.exp(log_beta_pdf(x, a, b)), 'b')\nplt.plot(x, np.exp(log_beta_pdf(x, a+c_1, b+c_0)), 'r')\nyl = plt.gca().get_ylim()\nplt.plot([pi_ML, pi_ML], yl , 'k:')\nplt.legend([\"Prior $\\cal B$ $(a={}, b={})$\".format(a,b), \"Posterior $\\cal B$ $(a={}, b={})$\".format(a+c_1, b+c_0)], loc=\"best\")\nplt.show()\n```\n\n### Illustration: Learning from a sequence of coin flips\n\n\n```python\n%matplotlib inline\nimport matplotlib.pyplot as plt\nfrom scipy.special import gammaln\nimport numpy as np\nimport scipy.special as sps\n\n#savefigs = \n\ndef log_beta_pdf(x, a, b):\n \n y = - gammaln(a) - gammaln(b) + gammaln(a+b) + np.log(x)*(a-1) + np.log(1-x)*(b-1) \n idx = np.where(x == 0)\n if a==1:\n y[idx] = - gammaln(a) - gammaln(b) + gammaln(a+b)\n elif a<1:\n y[idx] = np.Inf\n else:\n y[idx] = - np.Inf\n \n idx = np.where(x == 1)\n if b==1:\n y[idx] = - gammaln(a) - gammaln(b) + gammaln(a+b)\n elif b<1:\n y[idx] = np.Inf\n else:\n y[idx] = - np.Inf\n return y\n\na = 1\nb = 1\n\nxx = [1,1,1,1,1,0,1,1, 1,0,1,0,1,1,1,1,0, 1,1,1,1,1,1,1]\n\np = np.arange(0.0,1.01,0.01)\n\nc = [0,0]\nN = 0\nplt.figure(figsize=(5,3))\nplt.plot(p, np.exp(log_beta_pdf(p, a+c[1], b+c[0])), 'r')\nplt.xticks([0,1])\nplt.yticks([])\nplt.xlim([-0.1,1.1])\nplt.ylim([0,6])\npi_ML = (a+c[1])/(a+b+N)\nyl = plt.gca().get_ylim()\nplt.plot([pi_ML, pi_ML], yl , 'k:')\n\nplt.xlabel('$\\lambda$')\n#plt.savefig('/Users/cemgil/Dropbox/tex/cam/talks/cmpe547/beta{n}.eps'.format(n=N), bbox_inches='tight')\nplt.show()\n\nfor x in xx:\n c[x] += 1\n N += 1\n plt.figure(figsize=(5,3))\n plt.plot(p, np.exp(log_beta_pdf(p, a+c[1], b+c[0])), 'r')\n\n \n pi_ML = (a+c[1])/(a+b+N)\n pi_mode = (a+c[1]-1)/float(a+b+N-2)\n tmp = str(int(a+c[1]-1))+'/'+str(a+b+N-2)\n plt.xticks([0,pi_mode],('0',tmp))\n #plt.xticks([0,pi_mode])\n plt.yticks([])\n plt.xlim([-0.1,1.1])\n plt.ylim([0,6])\n \n yl = plt.gca().get_ylim()\n plt.plot([pi_ML, pi_ML], yl , 'k:')\n plt.plot([pi_mode, pi_mode], yl , 'b:')\n \n plt.xlabel('$\\lambda$')\n #plt.savefig('/Users/cemgil/Dropbox/tex/cam/talks/cmpe547/beta{n}.eps'.format(n=N), bbox_inches='tight')\n plt.show()\n\n```\n\n# Finding if a Coin is Fair or Fake \n\nWe consider the folowing problem: Given a sequence of coin tosses $X = \\{x^{(n)}\\}_{n=1\\dots N}$, determine if the coin is fair or fake.\n\nThis can be cast as a model selection problem:\n\n\\begin{eqnarray}\n\\pi_1|m & \\sim & \\left\\{ \\begin{array}{cc} \\delta(\\pi_1 - 0.5) & m = 0\\\\ \\mathcal{B}(\\pi; a, b) & m = 1 \\end{array} \\right.\n\\end{eqnarray}\nFor $n = 1\\dots N$\n\\begin{eqnarray}\nx^{(n)}| \\pi_1 & \\sim & \\mathcal{BE}(x; \\pi_1)\n\\end{eqnarray}\n\nThis model defines the following:\n- The indicator $m$, that denotes if the coin is fake,\n- What a fake coin is: a fake coin is one that has an arbitrary probability $\\pi_1$ between $0$ and $1$. \n- What a fair coin is: a fair coin has $\\pi_1 = 0.5$\n\nWe need to calculate the marginal likelihoods for $m=0$ and $m=1$\n\\begin{eqnarray}\np(X| m) & = & \\int d\\pi_1 p(X | \\pi_1) p(\\pi_1|m)\n\\end{eqnarray}\n\n###### Not Fake\n\\begin{eqnarray}\np(X| m) & = & \\int d\\pi_1 p(X| \\pi_1) \\delta(\\pi_1 - 0.5) \\\\\n& = & \\prod_{n=1}^N \\left(\\frac{1}{2}\\right)^{x^{(n)}} \\left(\\frac{1}{2}\\right)^{1-x^{(n)}} = \\frac{1}{2^N}\n\\end{eqnarray}\n\n###### Fake\n\n\\begin{eqnarray}\np(X| m) & = & \\int d\\pi_1 p(\\pi_1; a, b) \\prod_{n=1}^{N} p(x^{(n)}| \\pi_1) \\\\\n& = & \\int d\\pi_1 \\left(\\prod_{n=1}^N \\left(1-\\pi_1\\right)^{1-x^{(n)}} \\pi_1^{x^{(n)}} \\right) \\mathcal{B}(\\pi; a, b) \\\\\n& = & \\frac{\\Gamma(a + b)}{\\Gamma(a)\\Gamma(b)} \\int d\\pi_1 \\left(1-\\pi_1\\right)^{c_0+a-1} \\pi_1^{c_1+b-1} \\\\\n& = & \\frac{\\Gamma(a + b)}{\\Gamma(a)\\Gamma(b)} \\frac{\\Gamma(c_0+a)\\Gamma(c_1+b)}{\\Gamma(c_0 + c_1 +a + b)}\n\\end{eqnarray}\n\nThe log-odds is the ratio of marginal likelihoods\n\n$$\nl(X) = \\log\\left( \\frac{p(X|m = \\text{Fair})}{p(X|m = \\text{Fake})} \\right)\n$$\n\nIf $l(X)>0$, we may conclude that the coin is fair and biased when $l<0$.\n\n\n```python\nimport numpy as np\nimport scipy.special as sps\n\ndef log_odds(c_0, c_1, a, b):\n # Total number of tosses\n N = c_0 + c_1\n \n M_fair = N*np.log(0.5)\n M_fake = sps.gammaln(a+b) - sps.gammaln(a) - sps.gammaln(b) + sps.gammaln(c_0+a) + sps.gammaln(c_1+b) - sps.gammaln(N+a + b) \n return M_fair - M_fake\n\n# Number of Zeros observed\nc_0 = 6\n# Number of Ones\nc_1 = 1\n\n# Prior\na = 1\nb = 1\n\n\nprint('log_odds = ', log_odds(c_0, c_1, a, b) )\n\n```\n\n log_odds = -0.826678573184\n\n\n\n```python\na = 1\nb = 1\nN = 10\n\nl = np.zeros(N+1)\n\nfor c in range(0,N+1):\n l[c] = log_odds(N-c, c, a, b)\n\nplt.plot(range(0,N+1), l, 'o')\nplt.plot(range(0,N+1), np.zeros(N+1), 'k:')\nax = plt.gca()\nax.set_xlabel('Number of ones $c_1$')\nax.set_ylabel('log-odds $l(X)$')\nplt.show()\n```\n\nWe can visualize the region where we would decide that the coin is fake by plotting the points where the log-odds is negative.\n\n\n```python\na = 1\nb = 1\n\nfor N in range(1, 25):\n\n l = np.zeros(N+1)\n\n for c in range(0,N+1):\n l[c] = log_odds(N-c, c, a, b)\n \n \n idx = np.where( np.array(l)<0 )\n p = np.arange(0,N+1)/N\n plt.plot(N*np.ones_like(p), p, '.k',markersize=4) \n plt.plot(N*np.ones_like(p[idx]), p[idx], '.r',markersize=20)\n \n\nax = plt.gca()\nax.set_ylim((0,1))\nax.set_xlabel('$N$')\nax.set_ylabel('$c_1/N$')\nplt.show()\n```\n\n# Estimation of a Categorical distribution\n\n## Maximum Likelihood Estimation\n\nWe observe a dataset $\\{x^{(n)}\\}_{n=1\\dots N}$. The model for a single observation is a categorical distribution with parameter $\\pi = (\\pi_1, \\dots, \\pi_S)$ where \n\n\\begin{eqnarray}\nx^{(n)} & \\sim & p(x|\\pi) = \\prod_{s=1}^{S} \\pi_s^{\\ind{s = x^{(n)}}}\n\\end{eqnarray}\nwhere $\\sum_s \\pi_s = 1$.\n\nThe loglikelihood of the entire dataset is\n\n\\begin{eqnarray}\n{\\cal L}(\\pi_1,\\dots,\\pi_S) & = & \\sum_{n=1}^N\\sum_{s=1}^S \\ind{s = x^{(n)}} \\log \\pi_s\n\\end{eqnarray}\nThis is a constrained optimisation problem.\nForm the Lagrangian\n\\begin{eqnarray}\n\\Lambda(\\pi, \\lambda) & = & \\sum_{n=1}^N\\sum_{s'=1}^S \\ind{s' = x^{(n)}} \\log \\pi_{s'} + \\lambda \\left( 1 - \\sum_{s'} \\pi_{s'} \\right ) \\\\\n\\frac{\\partial \\Lambda(\\pi, \\lambda)}{\\partial \\pi_s} & = & \\sum_{n=1}^N \\ind{s = x^{(n)}} \\frac{1}{\\pi_s} - \\lambda = 0 \\\\\n\\pi_s & = & \\frac{\\sum_{n=1}^N \\ind{s = x^{(n)}}}{\\lambda}\n\\end{eqnarray}\n\nWe solve for $\\lambda$\n\\begin{eqnarray}\n1 & = & \\sum_s \\pi_s = \\frac{\\sum_{s=1}^S \\sum_{n=1}^N \\ind{s = x^{(n)}}}{\\lambda} \\\\\n\\lambda & = & \\sum_{s=1}^S \\sum_{n=1}^N \\ind{s = x^{(n)}} = \\sum_{n=1}^N 1 = N\n\\end{eqnarray}\n\nHence\n\\begin{eqnarray}\n\\pi_s & = & \\frac{\\sum_{n=1}^N \\ind{s = x^{(n)}}}{N}\n\\end{eqnarray}\n\n\n```python\n# %load template_equations.py\nfrom IPython.display import display, Math, Latex, HTML\nimport notes_utilities as nut\nfrom importlib import reload\nreload(nut)\nLatex('$\\DeclareMathOperator{\\trace}{Tr}$')\n\nL = nut.pdf2latex_dirichlet(x=r'\\pi', a=r'a',N=r'S', i='s')\n\ndisplay(HTML(nut.eqs2html_table(L)))\n```\n\n\n
\\begin{eqnarray}\\mathcal{D}(\\pi_{1:S}; a_{1:S} )\\end{eqnarray}\\mathcal{D}(\\pi_{1:S}; a_{1:S} )
\\begin{eqnarray}\\frac{\\Gamma(\\sum_{s} a_{s})}{\\prod_{s} \\Gamma(a_{s})} \\prod_{{s}=1}^{S} {\\pi}_{s}^{a_{s} - 1} \\end{eqnarray}\\frac{\\Gamma(\\sum_{s} a_{s})}{\\prod_{s} \\Gamma(a_{s})} \\prod_{{s}=1}^{S} {\\pi}_{s}^{a_{s} - 1}
\\begin{eqnarray}\\exp\\left(\\log{\\Gamma(\\sum_{s} a_{s})} - {\\sum_{s} \\log \\Gamma(a_{s})} + \\sum_{{s}=1}^{S} (a_{s} - 1) \\log{\\pi}_{s} \\right)\\end{eqnarray}\\exp\\left(\\log{\\Gamma(\\sum_{s} a_{s})} - {\\sum_{s} \\log \\Gamma(a_{s})} + \\sum_{{s}=1}^{S} (a_{s} - 1) \\log{\\pi}_{s} \\right)
\\begin{eqnarray}\\log{\\Gamma(\\sum_{s} a_{s})} - {\\sum_{s} \\log \\Gamma(a_{s})} + \\sum_{{s}=1}^{S} (a_{s} - 1) \\log{\\pi}_{s} \\end{eqnarray}\\log{\\Gamma(\\sum_{s} a_{s})} - {\\sum_{s} \\log \\Gamma(a_{s})} + \\sum_{{s}=1}^{S} (a_{s} - 1) \\log{\\pi}_{s}
\n\n\n#### Maximum A-Posteriori Estimation\n\n$$\n\\pi \\sim \\mathcal{D}(\\pi_{1:S}; a_{1:S} )\n$$\nwhere $\\sum_s \\pi_s = 1$. For $n = 1\\dots N$\n\\begin{eqnarray}\nx^{(n)} & \\sim & p(x|\\pi) = \\prod_{s=1}^{S} \\pi_s^{\\ind{s = x^{(n)}}}\n\\end{eqnarray}\n$X = \\{x^{(1)},\\dots,x^{(N)} \\}$\n\nThe posterior is \n\\begin{eqnarray}\n\\log p(\\pi_{1:S}| X) & =^+ & \\log p(\\pi_{1:S}, X) \\\\\n& = & +\\log{\\Gamma(\\sum_{s} a_{s})} - {\\sum_{s} \\log \\Gamma(a_{s})} + \\sum_{{s}=1}^{S} (a_{s} - 1) \\log{\\pi}_{s} + \\sum_{s=1}^S\\sum_{n=1}^N \\ind{s = x^{(n)}} \\log \\pi_s \\\\\n & =^+ & \\sum_{s=1}^S \\left(a_s - 1 + \\sum_{n=1}^N \\ind{s = x^{(n)}}\\right) \\log \\pi_s \n\\end{eqnarray}\nFinding the parameter vector $\\pi_{1:S}$ that maximizes the posterior density is a constrained optimisation problem. After omitting constant terms that do not depend on $\\pi$, we form the Lagrangian\n\\begin{eqnarray}\n\\Lambda(\\pi, \\lambda) & = & \\sum_{s=1}^S \\left(a_s - 1 + \\sum_{n=1}^N \\ind{s = x^{(n)}}\\right) \\log \\pi_s + \\lambda \\left( 1 - \\sum_{s'} \\pi_{s'} \\right ) \\\\\n\\frac{\\partial \\Lambda(\\pi, \\lambda)}{\\partial \\pi_s} & = & \\left(a_s - 1 + \\sum_{n=1}^N \\ind{s = x^{(n)}}\\right) \\frac{1}{\\pi_s} - \\lambda = 0 \\\\\n\\pi_s & = & \\frac{a_s - 1 + \\sum_{n=1}^N \\ind{s = x^{(n)}}}{\\lambda}\n\\end{eqnarray}\n\n\nWe solve for $\\lambda$\n\\begin{eqnarray}\n1 & = & \\sum_s \\pi_s = \\frac{- S + \\sum_{s=1}^S \\left( a_s + \\sum_{n=1}^N \\ind{s = x^{(n)} \\right) }}{\\lambda} \\\\\n\\lambda & = & N - S + \\sum_{s=1}^S a_s\n\\end{eqnarray}\n\nSetting the count of observations equal to $s$ as $C_s \\equiv \\sum_{n=1}^N \\ind{s = x^{(n)}}$, we obtain \n\nHence\n\\begin{eqnarray}\n\\pi_s & = & \\frac{C_s + a_s - 1}{N + \\sum_{s=1}^S a_s - S}\n\\end{eqnarray}\n\n\n\n#### Full Bayesian Inference\n\nSetting the count of observations equal to $s$ as $C_s \\equiv \\sum_{n=1}^N \\ind{s = x^{(n)}}$, we obtain \n\n\nThe posterior is \n\\begin{eqnarray}\n\\log p(\\pi_{1:S}, X) & = & \\log{\\Gamma(\\sum_{s} a_{s})} - {\\sum_{s} \\log \\Gamma(a_{s})} + \\sum_{s=1}^S \\left(\\left(a_s + \\sum_{n=1}^N \\ind{s = x^{(n)}}\\right) - 1 \\right) \\log \\pi_s \\\\\n& = & \\log{\\Gamma(\\sum_{s} a_{s})} - {\\sum_{s} \\log \\Gamma(a_{s})}\\\\\n& & + \\sum_{s=1}^S (a_s + C_s - 1) \\log \\pi_s \\\\\n & & + \\log{\\Gamma(\\sum_{s} (a_{s} + C_s) )} - {\\sum_{s} \\log \\Gamma(a_{s} + C_s)} \\\\\n & & - \\log{\\Gamma(\\sum_{s} (a_{s} + C_s) )} + {\\sum_{s} \\log \\Gamma(a_{s} + C_s)} \\\\\n & = & \\log \\mathcal{D}(\\pi_{1:S}, \\alpha_{1:S} ) + \\log p(X) \n\\end{eqnarray}\n\n\\begin{eqnarray}\n\\log p(X) & = & \\log{\\Gamma(\\sum_{s} a_{s})} - {\\sum_{s} \\log \\Gamma(a_{s})} - \\log{\\Gamma(\\sum_{s} (a_{s} + C_s) )} + {\\sum_{s} \\log \\Gamma(a_{s} + C_s)}\n\\end{eqnarray}\n\n\n\n\n```python\nfrom IPython.display import display, Math, Latex, HTML\nimport html_utils as htm\nwd = '65px'\nL = [[htm.TableCell('', width=wd), htm.TableCell('$x_2=1$', width=wd), htm.TableCell('$x_2=j$', width=wd), htm.TableCell('$x_2=S_2$', width='80px')],\n [r'$x_1=1$',r'$C(1,1)$',r'',r'$C(1,S_2)$'],\n [r'$x_1=i$',r'',r'$C(i,j)$',r''],\n [r'$x_1=S_1$',r'$C(S_1,1)$',r'',r'$C(S_1,S_2)$']]\n\nt = htm.make_htmlTable(L)\n#display(HTML(str(t)))\nprint(str(t))\n```\n\n## Are $x_1$ and $x_2$ independent?\nSuppose we observe a dataset of $(x_1, x_2)$ pairs where\n$x_1 \\in \\{1,\\dots,S_1\\}$ and\n$x_2 \\in \\{1,\\dots,S_2\\}$.\n\n\n| $x_1^{(1)}$ | $x_2^{(1)}$ | \n| --- | --- |\n| $\\vdots$ | $\\vdots$ | \n| $x_1^{(n)}$ | $x_2^{(n)}$ | \n| $\\vdots$ | $\\vdots$ | \n| $x_1^{(N)}$ | $x_2^{(N)}$ | \n\n\nWe are given the counts of observations where $x_1 = i$ while $x_2 = j$. These counts can be stored as an array, that is known as a contingency table\n$\nC(i,j) = \\sum_{n=1}^N \\ind{x_1^{(n)} = i}\\ind{x_2^{(n)} = j}\n$\n\n\n \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=1$$x_2=j$$x_2=S_2$
$x_1=1$$C(1,1)$ $C(1,S_2)$
$x_1=i$ $C(i,j)$ 
$x_1=S_1$$C(S_1,1)$ $C(S_1,S_2)$
\n\nThe goal is deciding if the random variables are independent or dependent.\n\n||$x_2$||\n|-|-|-|-|\n|$x_1$ |$3$|$5$|$9$|\n| |$7$|$9$|$17$|\n\n### Independent model $M_1$\n\n\\begin{equation}\np(x_1, x_2) = p(x_1) p(x_2) \n\\end{equation}\n\n\\begin{eqnarray}\n\\pi_1 & \\sim & \\mathcal{D}(\\pi_1; a_1) \\\\\n\\pi_2 & \\sim & \\mathcal{D}(\\pi_2; a_2) \\\\\nx_1^{(n)} & \\sim & \\mathcal{C}(x_1; \\pi_1) \\\\\nx_2^{(n)} & \\sim & \\mathcal{C}(x_2; \\pi_2) \n\\end{eqnarray}\n\nWe let \n\n* $C_1(i) = \\sum_j C(i,j)$ \n* $C_2(j) = \\sum_i C(i,j)$\n* $A_1 = \\sum_i a_{1}(i)$ \n* $A_2 = \\sum_j a_{2}(j)$\n\nThe marginal likelihood can be found as \n\\begin{eqnarray}\n\\log p(X|M_1) & = & \\log{\\Gamma(\\sum_{i} a_{1}(i))} - {\\sum_{i} \\log \\Gamma(a_{1}(i)} - \\log{\\Gamma(\\sum_{i} (a_{1}(i) + \\sum_{j} C(i,j)) )} + {\\sum_{i} \\log \\Gamma(a_{1}(i) + \\sum_{j} C(i,j))} \\\\\n& & +\\log{\\Gamma(\\sum_{j} a_{2}(j)} - {\\sum_{j} \\log \\Gamma(a_{2}(j))} - \\log{\\Gamma(\\sum_{j} (a_{2}(j) + \\sum_{i} C(i,j)) )} + {\\sum_{j} \\log \\Gamma(a_{2}(j) + \\sum_{i} C(i,j))} \\\\\n& = & \\log{\\Gamma(A_1)} - \\sum_{i} \\log \\Gamma(a_{1}(i)) - \\log{\\Gamma(A_1+ N)} + {\\sum_{i} \\log \\Gamma(a_{1}(i) + C_1(i))} \\\\\n& & + \\log{\\Gamma(A_2)} - {\\sum_{j} \\log \\Gamma(a_{2}(j))} - \\log{\\Gamma(A_2 + N )} + {\\sum_{j} \\log \\Gamma(a_{2}(j) + C_2(j))} \\\\\n\\end{eqnarray}\n\n### Dependent model $M_2$\n\\begin{equation}\np(x_1, x_2)\n\\end{equation}\n\n$\\pi_{1,2}$ is a $S_1 \\times S_2$ matrix where the joint distribution of entries is Dirichlet $\\mathcal{D}(\\pi_{1,2}; a_{1,2})$ with $S_1 \\times S_2$ parameter matrix $a_{1,2}$. Then, the probability that $p(x_1 = i, x_2 = j|\\pi_{1,2}) = \\pi_{1,2}(i,j)$.\n\n\\begin{eqnarray}\n\\pi_{1,2} & \\sim & \\mathcal{D}(\\pi_{1,2}; a_{1,2}) \\\\\n(x_1, x_2)^{(n)} & \\sim & \\mathcal{C}((x_1,x_2); \\pi_{1,2}) \\\\\n\\end{eqnarray}\n\n\\begin{eqnarray}\n\\log p(X|M_2) & = & \\log{\\Gamma(A_{1,2})} - {\\sum_{i,j} \\log \\Gamma(a_{1,2}(i,j))} - \\log{\\Gamma(A_{1,2}+ N)} + {\\sum_{i,j} \\log \\Gamma(a_{1,2}(i,j) + C(i,j))} \n\\end{eqnarray}\n\n\n\n### Dependent model $M_3$\n\\begin{equation}\np(x_1, x_2) = p(x_1) p(x_2|x_1) \n\\end{equation}\n\n\\begin{eqnarray}\n\\pi_1 & \\sim & \\mathcal{D}(\\pi_1; a_1) \\\\\n\\pi_{2,1} & \\sim & \\mathcal{D}(\\pi_2; a_2) \\\\\n\\vdots \\\\\n\\pi_{2,S_1} & \\sim & \\mathcal{D}(\\pi_2; a_2) \\\\\nx_1^{(n)} & \\sim & \\mathcal{C}(x_1; \\pi_1) \\\\\nx_2^{(n)} & \\sim & \\mathcal{C}(x_2; \\pi_{2}(x_1^{(n)},:)) \n\\end{eqnarray}\n\n\\begin{eqnarray}\n\\log p(x_1^{(1:N)}|\\pi_1) & = & \\sum_n \\sum_i \\sum_j \\ind{x_1^{(n)} = i} \\ind{x_2^{(n)} = j} \\log \\pi_{1}(i) = \\sum_i \\sum_j C(i,j) \\log \\pi_{1}(i)\n\\end{eqnarray}\n\\begin{eqnarray}\n\\log p(x_2^{(1:N)}|\\pi_2, x_1^{(1:N)} ) & = & \\sum_n \\sum_i \\sum_j \\ind{x_1^{(n)} = i} \\ind{x_2^{(n)} = j} \\log \\pi_{2}(i,j) = \\sum_i \\sum_j C(i,j) \\log \\pi_{2}(i,j)\n\\end{eqnarray}\n\n\n\n\\begin{eqnarray}\n\\log p(\\pi_1) & = & \\log{\\Gamma(\\sum_{i} a_{1}(i))} - {\\sum_{i} \\log \\Gamma(a_{1}(i))} + \\sum_{{i}=1}^{S_1} (a_{1}(i) - 1) \\log{\\pi_1}(i) \n\\end{eqnarray}\n\\begin{eqnarray}\n\\log p(\\pi_2) & = & \\sum_i \\left(\\log{\\Gamma(\\sum_{j} a_{2}(i,j))} - {\\sum_{j} \\log \\Gamma(a_{2}(i,j))} + \\sum_{{j}=1}^{S_2} (a_{2}(i,j) - 1) \\log{\\pi_2}(i,j) \\right)\n\\end{eqnarray}\n\nThe joint distribution is\n\\begin{eqnarray}\n\\log p(X, \\pi| M_2)&= & \\log{\\Gamma(\\sum_{i} a_{1}(i))} - {\\sum_{i} \\log \\Gamma(a_{1}(i))} + \\sum_{{i}=1}^{S_1} (a_{1}(i) + C_1(i) - 1) \\log{\\pi_1}(i) \\\\\n& & + \\sum_i \\left(\\log{\\Gamma(\\sum_{j} a_{2}(i,j))} - {\\sum_{j} \\log \\Gamma(a_{2}(i,j))} + \\sum_{{j}=1}^{S_2} (a_{2}(i,j) + C(i,j) - 1) \\log{\\pi_2}(i,j) \\right) \n\\end{eqnarray}\n\nWe will assume $a_2(i,j) = a_2(i',j)$ for all $i$ and $i'$.\n\\begin{eqnarray}\n\\log p(X| M_2)&= & \\log{\\Gamma(\\sum_{i} a_{1}(i))} - {\\sum_{i} \\log \\Gamma(a_{1}(i))} - \\log{\\Gamma(\\sum_{{i}} a_{1}(i) + C_1(i) )} + \\sum_{{i}} \\log \\Gamma(a_{1}(i) + C_1(i)) \\\\\n& & + \\sum_i \\left( \\log\\Gamma(\\sum_{j} a_{2}(i,j)) - \\sum_{j} \\log \\Gamma(a_{2}(i,j)) - \\log\\Gamma( \\sum_{j} a_{2}(i,j) + C(i,j)) + \\sum_j \\log\\Gamma( a_{2}(i,j) + C(i,j) ) \\right) \\\\\n& = & \\log{\\Gamma(A_1)} - {\\sum_{i} \\log \\Gamma(a_{1}(i))} - \\log{\\Gamma(A_1+ N)} + {\\sum_{i} \\log \\Gamma(a_{1}(i) + C_1(i))} \\\\\n& & + \\sum_i \\left( \\log{\\Gamma(A_2)} - {\\sum_{j} \\log \\Gamma(a_{2}(j))} - \\log{\\Gamma(A_2 + C_1(i) )} + {\\sum_{j} \\log \\Gamma(a_{2}(j) + C(i,j))} \\right) \\\\\n\\end{eqnarray}\n\n\n\n### Dependent model $M_3b$\nThe derivation is similar and corresponds to the factorization:\n\n\\begin{equation}\np(x_1, x_2) = p(x_2) p(x_1|x_2) \n\\end{equation}\n\n\n\n\n\n```python\nimport numpy as np\nfrom notes_utilities import randgen, log_sum_exp, normalize_exp, normalize\n\nimport scipy as sc\nfrom scipy.special import gammaln\n\n#C = np.array([[3,5,9],[7,9,17]])\nC = 1*np.array([[1,1,3],[1,1,7]])\n\n#C = np.array([[0,1,1],[1,0,2]])\n\nC_i = np.sum(C, axis=1)\nC_j = np.sum(C, axis=0)\n\nN = np.sum(C)\nS_1 = C.shape[0]\nS_2 = C.shape[1]\n\n#M1 Parameter\nM1 = {'a_1': np.ones(S_1), 'a_2': np.ones(S_2), 'A_1': None, 'A_2': None}\nM1['A_1'] = np.sum(M1['a_1'])\nM1['A_2'] = np.sum(M1['a_2'])\n#p(x_1) p(x_2)\nlog_marglik_M1 = gammaln(M1['A_1']) - np.sum(gammaln(M1['a_1'])) - gammaln(M1['A_1'] + N) + np.sum(gammaln(M1['a_1'] + C_i)) \\\n + gammaln(M1['A_2']) - np.sum(gammaln(M1['a_2'])) - gammaln(M1['A_2'] + N) + np.sum(gammaln(M1['a_2'] + C_j))\n\n# p(x_1, x_2)\nM2 = {'a_12': np.ones((S_1,S_2)), 'A_12':None}\nM2['A_12'] = np.sum(M2['a_12'])\nlog_marglik_M2 = gammaln(M2['A_12']) - np.sum(gammaln(M2['a_12'])) - gammaln(M2['A_12'] + N) + np.sum(gammaln(M2['a_12'] + C)) \n\n \n \nM3 = {'a_1': S_2*np.ones(S_1), 'a_2': np.ones(S_2), 'A_1': None, 'A_2': None}\nM3['A_1'] = np.sum(M3['a_1'])\nM3['A_2'] = np.sum(M3['a_2'])\n\n#p(x_1) p(x_2|x_1)\nlog_marglik_M3 = gammaln(M3['A_1']) - np.sum(gammaln(M3['a_1'])) - gammaln(M3['A_1'] + N) + np.sum(gammaln(M3['a_1'] + C_i)) \nfor i in range(S_1):\n log_marglik_M3 += gammaln(M3['A_2']) - np.sum(gammaln(M3['a_2'])) - gammaln(M3['A_2'] + C_i[i]) + np.sum(gammaln(M3['a_2'] + C[i,:]))\n\n# Beware the prior parameters\nM3b = {'a_1': np.ones(S_1), 'a_2': S_1*np.ones(S_2), 'A_1': None, 'A_2': None}\nM3b['A_1'] = np.sum(M3b['a_1'])\nM3b['A_2'] = np.sum(M3b['a_2'])\n\n#p(x_2) p(x_1|x_2)\nlog_marglik_M3b = gammaln(M3b['A_2']) - np.sum(gammaln(M3b['a_2'])) - gammaln(M3b['A_2'] + N) + np.sum(gammaln(M3b['a_2'] + C_j)) \nfor j in range(S_2):\n log_marglik_M3b += gammaln(M3b['A_1']) - np.sum(gammaln(M3b['a_1'])) - gammaln(M3b['A_1'] + C_j[j]) + np.sum(gammaln(M3b['a_1'] + C[:,j]))\n\n\nprint('M1:', log_marglik_M1)\nprint('M2:', log_marglik_M2)\nprint('M3:', log_marglik_M3)\nprint('M3b:', log_marglik_M3b)\n\nprint('Log Odds, M1-M2')\nprint(log_marglik_M1 - log_marglik_M2)\nprint(normalize_exp([log_marglik_M1, log_marglik_M2]))\n\nprint('Log Odds, M1-M3')\nprint(log_marglik_M1 - log_marglik_M3)\nprint(normalize_exp([log_marglik_M1, log_marglik_M3]))\n\nprint('Log Odds, M1-M3b')\nprint(log_marglik_M1 - log_marglik_M3b)\nprint(normalize_exp([log_marglik_M1, log_marglik_M3b]))\n\n```\n\n M1: -23.7979581523\n M2: -24.2354716141\n M3: -24.2354716141\n M3b: -24.2354716141\n Log Odds, M1-M2\n 0.437513461821\n [ 0.60766638 0.39233362]\n Log Odds, M1-M3\n 0.437513461821\n [ 0.60766638 0.39233362]\n Log Odds, M1-M3b\n 0.437513461821\n [ 0.60766638 0.39233362]\n\n\nConceptually $M_2$, $M_3$ and $M_3b$ should have the same marginal likelihood score, as the dependence should not depend on how we parametrize the conditional probability tables. However, this is dependent on the choice of the prior parameters. \n\nHow should the prior parameters of $M_2$, $M_3$ and $M_3b$ be chosen such that we get the same evidence score?\n\nThe models \n$M_2$, $M_3$ and $M_3b$ are all equivlent, if the prior parameters are chosen appropriately. For $M_2$ and $M_3$, we need to take $a_1(i) = \\sum_j a_{1,2}(i,j)$.\n\nFor example, if in $M_2$, the prior parameters $a_{1,2}$ are chosen as\n\\begin{eqnarray}\na_{1,2} & = & \\left(\\begin{array}{ccc} 1 & 1 & 1\\\\ 1 & 1 & 1 \\end{array} \\right)\n\\end{eqnarray}\n\nwe need to choose in model $M_3$\n\\begin{eqnarray}\na_{1} & = & \\left(\\begin{array}{c} 3 \\\\ 3 \\end{array} \\right)\n\\end{eqnarray}\n\\begin{eqnarray}\na_{2} & = & \\left(\\begin{array}{ccc} 1 & 1 & 1\\\\ 1 & 1 & 1 \\end{array} \\right)\n\\end{eqnarray}\n\nand in model $M_3b$\n\\begin{eqnarray}\na_{2} & = & \\left(\\begin{array}{ccc} 2 & 2 & 2 \\end{array} \\right)\n\\end{eqnarray}\n\\begin{eqnarray}\na_{1} & = & \\left(\\begin{array}{ccc} 1 & 1 & 1\\\\ 1 & 1 & 1 \\end{array} \\right)\n\\end{eqnarray}\n\nThis is due to fact that the marginals of a Dirichlet distribution are also Dirichlet. In particular,\nif a probability vector $x$ and corresponding parameter vector $a$ are partitioned as $x = (x_\\iota, x_{-\\iota})$ \nand $a = (a_\\iota, a_{-\\iota})$, the Dirichlet distribution\n$$\n\\mathcal{D}(x_\\iota, x_{-\\iota}; a_\\iota, a_{-\\iota})\n$$\nhas marginals \n$$\n\\mathcal{D}(X_{\\iota}, X_{-\\iota}; A_{\\iota}, A_{-\\iota})\n$$\nwhere $X_\\iota = \\sum_{i \\in \\iota} x_i$ and $X_{-\\iota} = \\sum_{i \\in -\\iota} x_i$, where $A_\\iota = \\sum_{i \\in \\iota} a_i$ and $A_{-\\iota} = \\sum_{i \\in -\\iota} a_i$. The script below verifies that the marginals are indeed distributed according to this formula.\n\n\n\n```python\nS_1 = 2\nS_2 = 10\nM = S_1*S_2\n\na = np.ones(M)\n\nN = 100\nP = np.random.dirichlet(a, size=N)\nA = np.zeros((N,S_1))\nB = np.zeros((N*S_1,S_2))\n\nfor n in range(N):\n temp = P[n,:].reshape((S_1,S_2))\n A[n,:] = np.sum(temp, axis=1)\n for i in range(S_1):\n B[(n*S_1+i),:] = temp[i,:]/A[n,i]\n\nimport pylab as plt\n\nplt.hist(A[:,0],bins=20)\nplt.gca().set_xlim([0,1])\n#plt.plot(B[:,0],B[:,1],'.')\nplt.show()\n\nP2 = np.random.dirichlet(S_2*np.ones(S_1), size=N)\nplt.hist(P2[:,0],bins=20)\nplt.gca().set_xlim([0,1])\nplt.show()\n```\n\nAre two given histograms drawn from the same distribution?\n\n$[3,5,12,4]$\n\n$[8, 14, 31, 14]$\n\n## Visualizing the Dirichlet Distribution\n\n[http://blog.bogatron.net/blog/2014/02/02/visualizing-dirichlet-distributions/]\n\n\n```python\n%matplotlib inline\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.tri as tri\nfrom functools import reduce\nfrom scipy.special import gammaln\n\ncorners = np.array([[0, 0], [1, 0], [0.5, 0.75**0.5]])\ntriangle = tri.Triangulation(corners[:, 0], corners[:, 1])\n\nrefiner = tri.UniformTriRefiner(triangle)\ntrimesh = refiner.refine_triangulation(subdiv=4)\n\n\n# Mid-points of triangle sides opposite of each corner\nmidpoints = [(corners[(i + 1) % 3] + corners[(i + 2) % 3]) / 2.0 \\\n for i in range(3)]\n\ndef xy2bc(xy, tol=1.e-3):\n '''Converts 2D Cartesian coordinates to barycentric.'''\n s = [(corners[i] - midpoints[i]).dot(xy - midpoints[i]) / 0.75 \\\n for i in range(3)]\n return np.clip(s, tol, 1.0 - tol)\n\nclass Dirichlet(object):\n def __init__(self, alpha):\n self._alpha = np.array(alpha)\n self._coef = gammaln(np.sum(self._alpha)) - np.sum(gammaln(self._alpha))\n def log_pdf(self, x):\n return self._coef + np.sum(np.log(x)*(self._alpha - 1)) \n def pdf(self, x):\n '''Returns pdf value for `x`.'''\n return np.exp(self.log_pdf(x))\n \ndef draw_pdf_contours(dist, nlevels=200, subdiv=8, **kwargs):\n\n refiner = tri.UniformTriRefiner(triangle)\n trimesh = refiner.refine_triangulation(subdiv=subdiv)\n pvals = [dist.pdf(xy2bc(xy)) for xy in zip(trimesh.x, trimesh.y)]\n\n plt.tricontourf(trimesh, pvals, nlevels, **kwargs)\n plt.axis('equal')\n plt.xlim(0, 1)\n plt.ylim(0, 0.75**0.5)\n plt.axis('off')\n```\n\n\n```python\ndraw_pdf_contours(Dirichlet([1, 3, 1]))\n```\n\n\n```python\ndraw_pdf_contours(Dirichlet([1.99, 3.99, 10.99]))\n```\n\n# 6-faced die with repeated labels\n\nConsider a die where the numbers on each face are labeled, possibly with repetitions, from the set $1\\dots 6$. \nA 'normal' die has labels $1,2,3,4,5,6$ but we allow other labelings, for example as $1,1,3,5,5,5$ or $1,1,1,1,1,6$.\n\nCan we construct a method to find how the die has been labeled from a sequence of outcomes? \n\n\n\n# Does my data have a single cluster or are there two clusters?\n\nWe observe a dataset of $N$ points and want to decide if there are one or two clusters. For example, the below dataset, when visualized seems to suggest two clusters; however the separation is not very clear; perhaps a single component might have been also sufficient. How can we derive a procedure that leads to a resonable answer in this ambigious situation?\n\n\n\nOne principled approach is based on Bayesian model selection. Our approach will be describing two alternative generative models for data. Each generative model will reflect our assumption what it means to have clusters. In other words, we should describe two different procedures: how to generate a dataset with a single cluster, or a datset that has two clusters. Once we have a description of each generative procedure, we may hope to convert our qualitative question (how many clusters?) into a well defined computational procedure. \n\nEach generative procedure will be a different probability model and we will compute the marginal posterior distribution conditioned on an observed dataset.\n\nThe single cluster model will have a single cluster center, denoed as $\\mu$. Once $\\mu$ is generated, each observation is generated by a Gaussian distribution with variance $R$, centered around $\\mu$.\n\nModel $M =1$: Single Cluster\n\\begin{eqnarray}\n\\mu & \\sim & {\\mathcal N}(\\mu; 0, P) \\\\\nx_i | \\mu & \\sim & {\\mathcal N}(x; \\mu, R)\n\\end{eqnarray}\n\nThe parameter $P$ denotes a natural range for the mean, $R$ denotes the variance of data, the amount of spread around the mean. To start simple, we will assume that these parameters are known; we will able to relax this assumption later easily.\n\nBelow, we show an example where each data point is a scalar.\n\n\n```python\n# Parameters\nP = 100\nR = 10\n\n# Number of datapoints\nN = 5\n\nmu = np.random.normal(0, np.sqrt(P))\nx = np.random.normal(mu, np.sqrt(R), size=(N))\n\nplt.figure(figsize=(10,1))\nplt.plot(mu, 0, 'r.')\nplt.plot(x, np.zeros_like(x), 'x')\nax = plt.gca()\nax.set_xlim(3*np.sqrt(P)*np.array([-1,1]))\nax.set_ylim([-0.1,0.1])\nax.axis('off')\nplt.show()\n```\n\nModel $M = 2$: Two Clusters\n\\begin{eqnarray}\n\\mu_0 & \\sim & {\\mathcal{N}}(\\mu; 0, P) \\\\\n\\mu_1 & \\sim & {\\mathcal{N}}(\\mu; 0, P) \\\\\nc_i & \\sim & {\\mathcal{BE}}(r; 0.5) \\\\\nx_i | \\mu_0, \\mu_1, c_i & \\sim & {\\mathcal N}(x; \\mu_0, R)^{1-c_i} {\\mathcal N}(x; \\mu_1, R)^{c_i}\n\\end{eqnarray}\n\nThe parameter $P$ denotes a natural range for both means, $R$ denotes the variance of data in each cluster. The variables $r_i$ are the indicators that show the assignment of each datapoint to one of the clusters.\n\n\n```python\n# Parameters\nP = 100\nR = 2\n\n# Number of datapoints\nN = 10\n\n# Number of clusters\nM = 2\n\nmu = np.random.normal(0, np.sqrt(P), size=(M))\nc = np.random.binomial(1, 0.5, size=N)\nx = np.zeros(N)\nfor i in range(N):\n x[i] = np.random.normal(mu[c[i]], np.sqrt(R))\n\nplt.figure(figsize=(10,1))\n#plt.plot(mu, np.zeros_like(mu), 'r.')\nplt.plot(x, np.zeros_like(x), 'x')\nax = plt.gca()\nax.set_xlim(3*np.sqrt(P)*np.array([-1,1]))\nax.set_ylim([-0.1,0.1])\nax.axis('off')\nplt.show()\n```\n\n#### Extension\nWe dont know the component variances\n\n\n#### Combining into a single model\n\nCapture\n\nRecapture\n\n### Change point\nCoin switch\n\nCoal Mining Data\n Single Change Point\n Multiple Change Point\n\n# Bivariate Gaussian model selection\n\n\nSuppose we are given a dataset $X = \\{x_1, x_2, \\dots, x_N \\}$ where $x_n \\in \\mathbb{R}^K$ for $n=1 \\dots N$ and consider two competing models:\n\n- ### Model $m=1$:\n$\\newcommand{\\diag}{\\text{diag}}$\n\n- Observation\n\\begin{eqnarray}\n\\text{for}\\; n=1\\dots N&& \\\\\nx_n| s_{1:K} & \\sim & \\mathcal{N}\\left(x; 0, \\diag\\{s_1, \\dots, s_K\\}\\right) = \\mathcal{N}\\left(x; 0, \\left(\\begin{array}{ccc} s_1 & 0 & 0\\\\0 & \\ddots & 0 \\\\ 0 & \\dots & s_K \\end{array} \\right) \\right)\n\\end{eqnarray}\n\n$$\np(x_n| s_{1:K}) = \n\\prod_{k=1}^K \\mathcal{N}(x_{k,n}; 0, s_k) \n$$\n\n$$\np(X|s_{1:K} ) = \\prod_{n=1}^N p(x_n| s_{1:K}) = \n\\prod_{n=1}^N \\prod_{k=1}^K \\mathcal{N}(x_{k,n}; 0, s_k) \n$$\n\n\n- Prior\n\\begin{eqnarray}\n\\text{for}\\; k=1\\dots K&& \\\\\ns_k & \\sim & \\mathcal{IG}(s_k; \\alpha, \\beta) \n\\end{eqnarray}\n\n\n\n- ### Model $m=2$:\n\n-- Observation\n\n\\begin{eqnarray}\nx_n \\sim \\mathcal{N}(x_n; 0, \\Sigma)=\\left|{ 2\\pi \\Sigma } \\right|^{-1/2} \\exp\\left(-\\frac12 {x_n}^\\top {\\Sigma}^{-1} {x_n} \\right)=\\exp\\left( -\\frac{1}{2}\\trace {\\Sigma}^{-1} {x_n}{x_n}^\\top -\\frac{1}{2}\\log \\left|2{\\pi}\\Sigma\\right|\\right)\n\\end{eqnarray}\n\n$$\n{\\cal IW}(\\Sigma; 2a, 2B) = \\exp( - (a + (k+1)/2) \\log |\\Sigma| - \\trace B\\Sigma^{-1} - \\log\\Gamma_k(a) + a\\log |B|) \\\\\n$$\n\n\n```python\n# %load template_equations.py\nfrom IPython.display import display, Math, Latex, HTML\nimport notes_utilities as nut\nfrom importlib import reload\nreload(nut)\nLatex('$\\DeclareMathOperator{\\trace}{Tr}$')\n\n#L = nut.pdf2latex_gauss(x=r's', m=r'\\mu',v=r'v')\n#L = nut.pdf2latex_mvnormal(x=r's', m=r'\\mu',v=r'\\Sigma')\nL = nut.pdf2latex_mvnormal(x=r'x_n', m=0,v=r'\\Sigma')\n#L = nut.pdf2latex_gamma(x=r'x', a=r'a',b=r'b')\n#L = nut.pdf2latex_invgamma(x=r'x', a=r'a',b=r'b')\n#L = nut.pdf2latex_beta(x=r'\\pi', a=r'\\alpha',b=r'\\beta')\n\neq = L[0]+'='+L[1]+'='+L[2]\ndisplay(Math(eq))\ndisplay(Latex(eq))\ndisplay(HTML(nut.eqs2html_table(L)))\n```\n\n\n$$\\mathcal{N}(x_n; 0, \\Sigma)=\\left|{ 2\\pi \\Sigma } \\right|^{-1/2} \\exp\\left(-\\frac12 {x_n}^\\top {\\Sigma}^{-1} {x_n} \\right)=\\exp\\left( -\\frac{1}{2}\\trace {\\Sigma}^{-1} {x_n}{x_n}^\\top -\\frac{1}{2}\\log \\left|2{\\pi}\\Sigma\\right|\\right)$$\n\n\n\n\\mathcal{N}(x_n; 0, \\Sigma)=\\left|{ 2\\pi \\Sigma } \\right|^{-1/2} \\exp\\left(-\\frac12 {x_n}^\\top {\\Sigma}^{-1} {x_n} \\right)=\\exp\\left( -\\frac{1}{2}\\trace {\\Sigma}^{-1} {x_n}{x_n}^\\top -\\frac{1}{2}\\log \\left|2{\\pi}\\Sigma\\right|\\right)\n\n\n\n
\\begin{eqnarray}\\mathcal{N}(x_n; 0, \\Sigma)\\end{eqnarray}\\mathcal{N}(x_n; 0, \\Sigma)
\\begin{eqnarray}\\left|{ 2\\pi \\Sigma } \\right|^{-1/2} \\exp\\left(-\\frac12 {x_n}^\\top {\\Sigma}^{-1} {x_n} \\right)\\end{eqnarray}\\left|{ 2\\pi \\Sigma } \\right|^{-1/2} \\exp\\left(-\\frac12 {x_n}^\\top {\\Sigma}^{-1} {x_n} \\right)
\\begin{eqnarray}\\exp\\left( -\\frac{1}{2}\\trace {\\Sigma}^{-1} {x_n}{x_n}^\\top -\\frac{1}{2}\\log \\left|2{\\pi}\\Sigma\\right|\\right)\\end{eqnarray}\\exp\\left( -\\frac{1}{2}\\trace {\\Sigma}^{-1} {x_n}{x_n}^\\top -\\frac{1}{2}\\log \\left|2{\\pi}\\Sigma\\right|\\right)
\\begin{eqnarray} -\\frac{1}{2}\\trace {\\Sigma}^{-1} {x_n}{x_n}^\\top -\\frac{1}{2}\\log \\left|2{\\pi}\\Sigma\\right|\\end{eqnarray} -\\frac{1}{2}\\trace {\\Sigma}^{-1} {x_n}{x_n}^\\top -\\frac{1}{2}\\log \\left|2{\\pi}\\Sigma\\right|
\n\n\nComputing the marginal likelihood\n\n* #### Model 1\n\n\\begin{eqnarray}\np(X| m=1) & = & \\int d{s_{1:K}} p(X|s_{1:K}) p(s_{1:K}) = \n\\end{eqnarray}\n\n\n\n```python\n# %load template_equations.py\nfrom IPython.display import display, Math, Latex, HTML\nimport notes_utilities as nut\nfrom importlib import reload\nreload(nut)\nLatex('$\\DeclareMathOperator{\\trace}{Tr}$')\n\n#L = nut.pdf2latex_gauss(x=r's', m=r'\\mu',v=r'v')\nL = nut.pdf2latex_mvnormal(x=r'x_t', m=r'(Ax_{t-1})',v=r'Q')\n#L = nut.pdf2latex_mvnormal(x=r's', m=0,v=r'I')\n#L = nut.pdf2latex_gamma(x=r'x', a=r'a',b=r'b')\n#L = nut.pdf2latex_invgamma(x=r'x', a=r'a',b=r'b')\n#L = nut.pdf2latex_beta(x=r'\\pi', a=r'\\alpha',b=r'\\beta')\n\neq = L[0]+'='+L[1]+'='+L[2]\ndisplay(Math(eq))\n\nL = nut.pdf2latex_mvnormal(x=r'y_t', m=r'(Cx_{t})',v=r'R')\neq = L[0]+'='+L[1]+'='+L[2]\ndisplay(Math(eq))\n\n```\n\n\n$$\\mathcal{N}(x_t; (Ax_{t-1}), Q)=\\left|{ 2\\pi Q } \\right|^{-1/2} \\exp\\left(-\\frac12 ({x_t} - {(Ax_{t-1})} )^\\top {Q}^{-1} ({x_t} - {(Ax_{t-1})} ) \\right)=\\exp\\left( -\\frac{1}{2}\\trace {Q}^{-1} {x_t}{x_t}^\\top + \\trace {Q}^{-1} {x_t}{(Ax_{t-1})}^\\top -\\frac{1}{2}\\trace {Q}^{-1} {(Ax_{t-1})}{(Ax_{t-1})}^\\top -\\frac{1}{2}\\log \\left|2{\\pi}Q\\right|\\right)$$\n\n\n\n$$\\mathcal{N}(y_t; (Cx_{t}), R)=\\left|{ 2\\pi R } \\right|^{-1/2} \\exp\\left(-\\frac12 ({y_t} - {(Cx_{t})} )^\\top {R}^{-1} ({y_t} - {(Cx_{t})} ) \\right)=\\exp\\left( -\\frac{1}{2}\\trace {R}^{-1} {y_t}{y_t}^\\top + \\trace {R}^{-1} {y_t}{(Cx_{t})}^\\top -\\frac{1}{2}\\trace {R}^{-1} {(Cx_{t})}{(Cx_{t})}^\\top -\\frac{1}{2}\\log \\left|2{\\pi}R\\right|\\right)$$\n\n\n\n```python\n%connect_info\n```\n\n {\n \"key\": \"5fe2a052-2599-465d-96fa-793a58b02ea2\",\n \"transport\": \"tcp\",\n \"signature_scheme\": \"hmac-sha256\",\n \"shell_port\": 65197,\n \"stdin_port\": 65199,\n \"ip\": \"127.0.0.1\",\n \"hb_port\": 65201,\n \"control_port\": 65200,\n \"iopub_port\": 65198\n }\n \n Paste the above JSON into a file, and connect with:\n $> ipython --existing \n or, if you are local, you can connect with just:\n $> ipython --existing kernel-457030b1-3d25-4222-9094-06fb4bbdbefe.json \n or even just:\n $> ipython --existing \n if this is the most recent IPython session you have started.\n\n", "meta": {"hexsha": "3d45602fb55ac0abffcb32ff2fb2b2683fe82a4e", "size": 474877, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "ModelingExamples.ipynb", "max_stars_repo_name": "bkoyuncu/notes", "max_stars_repo_head_hexsha": "0e660f46b7d17fdfddc2cad1bb60dcf847f5d1e4", "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": "ModelingExamples.ipynb", "max_issues_repo_name": "bkoyuncu/notes", "max_issues_repo_head_hexsha": "0e660f46b7d17fdfddc2cad1bb60dcf847f5d1e4", "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": "ModelingExamples.ipynb", "max_forks_repo_name": "bkoyuncu/notes", "max_forks_repo_head_hexsha": "0e660f46b7d17fdfddc2cad1bb60dcf847f5d1e4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-09-11T11:46:36.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-11T11:46:36.000Z", "avg_line_length": 251.924137931, "max_line_length": 32130, "alphanum_fraction": 0.8863874224, "converted": true, "num_tokens": 17284, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9539661028358093, "lm_q2_score": 0.8933093961129794, "lm_q1q2_score": 0.8521868832365093}} {"text": "# Solution {-}\n\nConsider a random variable $X$ with an exponential probability function given as:\n\\begin{equation*}\n f_X(x)=\n \\begin{cases}\n e^{-x}, &x \\geq 0 \\\\\n 0, &x < 0 \\\\\n \\end{cases}\n\\end{equation*}\n\na) Compute $P(X \\geq 2)$:\n\n\n```python\nfrom sympy import exp, integrate, symbols, oo\n\nx = symbols('x')\n\nPX2 = integrate(exp(-x), (x, 2, oo))\nPX2\n```\n\n\n\n\n$\\displaystyle e^{-2}$\n\n\n\nb) Compute $P(1 \\leq X \\leq 2)$:\n\n\n```python\nP1X2 = integrate(exp(-x), (x, 1, 2))\nP1X2\n```\n\n\n\n\n$\\displaystyle - \\frac{1}{e^{2}} + e^{-1}$\n\n\n\nc) Compute $E(X)$, $E(X^2)$ and $Var(X)$:\n\n\n```python\nEX = integrate(x*exp(-x), (x, 0, oo))\nEX\n```\n\n\n\n\n$\\displaystyle 1$\n\n\n\n\n```python\nEX2 = integrate(x**2*exp(-x), (x, 0, oo))\nEX2\n```\n\n\n\n\n$\\displaystyle 2$\n\n\n\n\n```python\nVarX = EX2 - EX**2\nVarX\n```\n\n\n\n\n$\\displaystyle 1$\n\n\n", "meta": {"hexsha": "057f1fb33b8e46dcf1cbae3829118aa6adfc7c10", "size": 3252, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Problem 1.22.ipynb", "max_stars_repo_name": "mfkiwl/GMPE340", "max_stars_repo_head_hexsha": "3602b8ba859a2c7db2cab96862472597dc1ac793", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-09-07T09:36:36.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-07T09:36:36.000Z", "max_issues_repo_path": "Problem 1.22.ipynb", "max_issues_repo_name": "mfkiwl/GMPE340", "max_issues_repo_head_hexsha": "3602b8ba859a2c7db2cab96862472597dc1ac793", "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": "Problem 1.22.ipynb", "max_forks_repo_name": "mfkiwl/GMPE340", "max_forks_repo_head_hexsha": "3602b8ba859a2c7db2cab96862472597dc1ac793", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-09-20T18:48:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-20T18:48:20.000Z", "avg_line_length": 17.6739130435, "max_line_length": 90, "alphanum_fraction": 0.426199262, "converted": true, "num_tokens": 314, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9637799451753696, "lm_q2_score": 0.8840392725805822, "lm_q1q2_score": 0.8520193216605871}} {"text": "```\n%pylab inline\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport time\n```\n\nIn this problem we'll study the efficiency of various approaches to solving the initial value problem \n$$\\begin{align} u_1'(t) & = -K_1 u_1 \\\\\\\\ \nu_2'(t) & = K_1 u_1 -K_2 u_2 \\\\\\\\\nu_3'(t) & = K_2 u_2\\end{align}$$ \n$$u(0) = [1,0,0].$$ \nThis corresponds to the decay process \n$$A\\to^{K_1} B \\to^{K_2} C $$ \nTo begin, we define a Python function that evaluates the right-hand-side of this system. \n\n\n```\ndef f(t,u):\n K1=1\n K2=2\n du=np.zeros([3])\n du[0]=-K1*u[0]\n du[1]= K1*u[0] - K2*u[1]\n du[2]= K2*u[1]\n return du\n```\n\nThe scipy.integrate.ode package contains interfaces to various numerical ODE solvers, similar to those available in MATLAB. Take a moment to read the help on this package. The scipy.integrate.odeint package contains similar functionality. \n\n\n```\nfrom scipy.integrate import ode\n```\n\nWe'll use the 'dopri5' integrator, which is an embedded Runge-Kutta pair (the same one used by MATLAB's ode45 command). The code below sets up and solves the problem. Note that the parameter dt_output below, does not determine the step size used by the integrator; it is merely the interval between outputs that we'll use for plotting. The step size is chosen to achieve specified error tolerances; in this case, we have specified $10^{-10}$ for both absolute and relative errors. \n\n\n```\nt0 = 0. # Initial time\nu0 = np.array([1.,0.,0.])# Initial values\ntfinal = 4. # Final time\nr = ode(f).set_integrator('dopri5',atol=1.e-10,rtol=1.e-10) # Dormand-Prince RK4(5) method\nr.set_initial_value(u0, t0)\ndt_output=0.02 # Interval between output for plotting\nN=tfinal/dt_output # Number of output times\ntt=np.zeros(N+1); tt[0]=t0 # Output times\nuu=np.zeros([3,N+1]); # Output values\nuu[:,0]=u0\ni=0\nwhile r.successful() and r.tHint: in order to get useful timing figures, set dt_output=tfinal. That way no time will be spent copying the output and you will measure just the time to compute the solution.\n\n\n```\n\n```\n\n#Exercise 2\n\n(continuation of exercise 1) \n(a) Plot the computed solution from part (c) of the previous exercise, using the tolerances $10^{-2}$ and $10^{-4}$, and comment on what you observe. \n(b) Now set the tolerances to $10^{-6}$ and vary $K_3$ from 500 up to 2000. You should observe that the time to compute the solution grows linearly with $K_3$. Explain why you would expect this to be true (rather than being roughly constant, or growing at some other rate, such as quadratically in $K_3$). How long would it take to compute a solution for $K_3=10^7$? \n(c) Repeat part (b) but use the scipy.integrate.odeint function, which has an adaptive BDF integrator, in place of dopri5. Explain why the computational time is much smaller and now roughly constant for large $K_3$. Also try $K_3=10^7$.\n\n\n```\n\n```\n", "meta": {"hexsha": "4b00e501d3ba6dfee1ad8c4e937eb3d0b7f488ad", "size": 7424, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "ipython/HW_4_part_1.ipynb", "max_stars_repo_name": "bfdeandrade/Finite-Difference", "max_stars_repo_head_hexsha": "97e93f394051a70b6aa2c26fa266952ae821deb2", "max_stars_repo_licenses": ["CC-BY-2.0"], "max_stars_count": 28, "max_stars_repo_stars_event_min_datetime": "2015-02-05T23:13:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-05T03:09:04.000Z", "max_issues_repo_path": "ipython/HW_4_part_1.ipynb", "max_issues_repo_name": "MuriloHMoreira/finite-difference-course", "max_issues_repo_head_hexsha": "97e93f394051a70b6aa2c26fa266952ae821deb2", "max_issues_repo_licenses": ["CC-BY-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/HW_4_part_1.ipynb", "max_forks_repo_name": "MuriloHMoreira/finite-difference-course", "max_forks_repo_head_hexsha": "97e93f394051a70b6aa2c26fa266952ae821deb2", "max_forks_repo_licenses": ["CC-BY-2.0"], "max_forks_count": 13, "max_forks_repo_forks_event_min_datetime": "2015-02-16T17:36:38.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-11T07:13:03.000Z", "avg_line_length": 38.4663212435, "max_line_length": 846, "alphanum_fraction": 0.5697737069, "converted": true, "num_tokens": 1365, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122163480667, "lm_q2_score": 0.9390248251074271, "lm_q1q2_score": 0.8519886952740754}} {"text": "# One Degree-of-Freedom (DoF) Hamiltonian Bifurcation of Equilibria\n\n(ADD INTRODUCTORY LANGUAGE ABOUT PROBLEM DEVELOPMENT)\nWe will now consider two examples of bifurcation of equilibria in two dimensional Hamiltonian system; in particular, the Hamiltonian saddle-node and Hamiltonian pitchfork bifurcations. \n\n## Hamiltonian saddle-node bifurcation\n\nWe consider the Hamiltonian:\n\n\\begin{equation}\nH (q, p) = \\frac{p^2}{2} - \\lambda q + \\frac{q^3}{3}, \\quad (q, p) \\in \\mathbb{R}^2.\n\\label{eq:hamApp13}\n\\end{equation}\n\n\nwhere $\\lambda$ is considered to be a parameter that can be varied. From this Hamiltonian, we derive Hamilton's equations:\n\n\\begin{eqnarray}\n\\dot{q} & = & \\frac{\\partial H}{\\partial p} = p, \\nonumber \\\\\n\\dot{p} & = & -\\frac{\\partial H}{\\partial q} =\\lambda - q^2.\n\\label{eq:hamApp14}\n\\end{eqnarray}\n\n### Revealing the Phase Space Structures and their implications for Reaction Dynamics\n\nThe fixed points for \\eqref{eq:hamApp14} are:\n\n\\begin{equation}\n(q, p) = (\\pm\\sqrt{\\lambda}, 0),\n\\end{equation}\n\n\nfrom which it follows that there are no fixed points for $\\lambda <0$, one fixed point for $\\lambda =0$, and two fixed points for $\\lambda >0$. This is the scenario for a saddle-node bifurcation. \n\nNext we examine the stability of the fixed points. The Jacobian of \\eqref{eq:hamApp14} is given by:\n\n\\begin{equation}\nJ =\\left(\n\\begin{array}{cc} \n0 & 1\\\\\n-2 q & 0\n\\end{array}\n\\right).\n\\label{eq:hamApp15}\n\\end{equation}\n\n\nThe eigenvalues of this matrix are:\n\n\\begin{equation}\n\\Lambda_{1, 2} = \\pm \\sqrt{-2q}.\n\\end{equation}\n\n\nHence $(q, p) = (-\\sqrt{\\lambda}, 0)$ is a saddle, $(q, p) = (\\sqrt{\\lambda}, 0)$ is a center, and $(q, p) = (0, 0)$ has two zero eigenvalues. The phase portraits are shown in Fig. [fig:1](#fig:appC_fig3).\n\n\n\n\n
fig:1 The phase portraits for the Hamiltonian saddle-node bifurcation.

\n\n## Hamiltonian pitchfork bifurcation\n\nWe consider the Hamiltonian:\n\n\\begin{equation}\nH (q, p) = \\frac{p^2}{2} - \\lambda \\frac{q^2}{2} + \\frac{q^4}{4},\n\\label{eq:hamApp16}\n\\end{equation}\n\n\nwhere $\\lambda$ is considered to be a parameter that can be varied. From this Hamiltonian, we derive Hamilton's equations:\n\n\\begin{eqnarray}\n\\dot{q} & = & \\frac{\\partial H}{\\partial p} = p, \\nonumber \\\\\n\\dot{p} & = & -\\frac{\\partial H}{\\partial q} =\\lambda q - q^3.\n\\label{eq:hamApp17}\n\\end{eqnarray}\n\n### Revealing the Phase Space Structures and their implications for Reaction Dynamics\n\nThe fixed points for \\eqref{eq:hamApp17} are:\n\n\\begin{equation}\n(q, p) = (0, 0), \\, (\\pm\\sqrt{\\lambda}, 0),\n\\end{equation}\n\n\nfrom which it follows that there is one fixed point for $\\lambda \\leq 0$, and three fixed points for $\\lambda >0$. This is the scenario for a pitchfork bifurcation.\n\nNext we examine the stability of the fixed points. The Jacobian of \\eqref{eq:hamApp17} is given by:\n\n\\begin{equation}\nJ = \\left(\n\\begin{array}{cc} \n0 & 1\\\\\n\\lambda-3q^2 & 0\n\\end{array}\n\\right).\n\\label{eq:hamApp18}\n\\end{equation}\n\n\nThe eigenvalues of this matrix are:\n\n\\begin{equation}\n\\Lambda_{1, 2} = \\pm \\sqrt{\\lambda - 3q^2 }.\n\\end{equation}\n\n\nHence $(q, p) = (0, 0)$ is a center for $\\lambda <0$, a saddle for $\\lambda >0$ and has two zero eigenvalues for $\\lambda =0$. The fixed points $(q, p) = (\\sqrt{\\lambda}, 0)$ are centers for $\\lambda >0$. The phase portraits are shown in Fig. [fig:2](#fig:appC_fig4).\n\n\n\n\n
fig:2 The phase portraits for the Hamiltonian pitchfork bifurcation.

\n", "meta": {"hexsha": "e7b83a3d5c707a8dfe5353f910354b802e027fb0", "size": 6945, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "content/act1/hamiltonian_bifurcation/ham_bif-jekyll.ipynb", "max_stars_repo_name": "champsproject/chem_react_dyn", "max_stars_repo_head_hexsha": "53ee9b30fbcfa4316eb08fd3ca69cba82cf7b598", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2019-12-09T11:23:13.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-16T09:49:55.000Z", "max_issues_repo_path": "content/act1/hamiltonian_bifurcation/ham_bif-jekyll.ipynb", "max_issues_repo_name": "champsproject/chem_react_dyn", "max_issues_repo_head_hexsha": "53ee9b30fbcfa4316eb08fd3ca69cba82cf7b598", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 40, "max_issues_repo_issues_event_min_datetime": "2019-12-09T14:52:38.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-26T06:10:08.000Z", "max_forks_repo_path": "content/act1/hamiltonian_bifurcation/ham_bif-jekyll.ipynb", "max_forks_repo_name": "champsproject/chem_react_dyn", "max_forks_repo_head_hexsha": "53ee9b30fbcfa4316eb08fd3ca69cba82cf7b598", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-05-12T06:27:20.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-08T05:29:56.000Z", "avg_line_length": 29.6794871795, "max_line_length": 280, "alphanum_fraction": 0.551187905, "converted": true, "num_tokens": 1181, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070084811307, "lm_q2_score": 0.9362850048591, "lm_q1q2_score": 0.8519322878570846}} {"text": "# Convex Optimization Project Proposal\nThis notebook describes a convex optimization problem to be studied in a one-week project as part of the course Convex Optimization.\n\nGroup: Mads Holst Aagaard Madsen, Emilie Knudsen Brun, and Oliver Lylloff\n\n\nThe optimization problem could be characterized as *covariance matrix fitting* where measured data, given by a covariance matrix, is used to estimate a source covariance matrix through a propagation model.\n\nConsider a measured (hermitian) covariance matrix $P\\in\\mathbb{C}^{M\\times M}$ and a sound propagation model defined by transfer functions \n\n$$g_{m,n} = \\frac{r_{m,n}}{r_{0,n}}e^{i\\omega r_{m,n}/c}\\quad m=1,...,M,\\;n=1,...,N, $$\n\nwhere $\\omega = 2\\pi f$ is the angular frequency, $c = 343 m/s$ is the speed of sound, $r_{0,n}$ is the distance from the center of the microphone array to the $n$'th source point, and $r_{m,n}$ is the distance between the $m$'th microphone and $n$'th source point. The transfer functions take into account the propagation of sound from the sources to the microphones. These are arranged in a transfer matrix $G\\in\\mathbb{C}^{N\\times M}$. The model can be decribed by\n\n$$P = GXG^H$$\n\nwhere $X\\in \\mathbb{C}^{N\\times N}$ is a covariance matrix at the source plane which is to be estimated.\n\nThe optimization problem can be stated as a SDP:\n\n$$\\begin{align} \n\\begin{aligned} \n\\underset{X}{\\mathrm{minimize}}\\quad & \\|P-GXG^H\\|_F^2\\\\ \n\\mathrm{subject \\ to} \\quad & X\\succeq 0\\\\ \n\\end{aligned} \n\\end{align}\n$$\n\nSeveral options for the solution can be persued:\n* $X$ is diagonal and sparse. In this case the number of variables can be reduced greatly. Additionally a penalty function with regularization parameter $\\lambda$ can be added to the objective function, e.g.,\n\n$$\\begin{align} \n\\begin{aligned} \n\\underset{X}{\\mathrm{minimize}}\\quad & \\|P-GXG^H\\|_F^2+\\lambda\\;\\text{tr(diag}(X))\\\\ \n\\mathrm{subject \\ to} \\quad & X\\succeq 0\\\\ \n\\end{aligned} \n\\end{align}\n$$\n\n* Reducing the number of variables by introducing a matrix $M$ of same dimensions as $P$ and writing $X = G^HMG+D$, i.e.,\n\n$$\\begin{align} \n\\begin{aligned} \n\\underset{X}{\\mathrm{minimize}}\\quad & \\|P-G(G^HMG+D)G^H\\|_F^2+\\lambda\\sum_{i=1}^n(D_{ii}+e_i^TG^HMGe_i)\\\\ \n\\mathrm{subject \\ to} \\quad & M\\succeq 0\\\\\n\\quad & D_{ii}\\geq0\n\\end{aligned} \n\\end{align}\n$$\n\nand using $e_i^TG^HMGe_i = \\sum_i tr(MGe_ie_iG^H)$, where $e_i$ is a unit-vector. Use resulting $M$ to obtain $X$.\n\n* First-order methods and warmstart. The optimization problem should be solved multiple times for different $\\omega$'s. Exploit warmstart capability of first-order methods and the assumption that covariance matrices does not change much between subsequent $\\omega$'s.\n\n\n### Data analysis and modelling\nThe visualization of noise using a microphone array is produced by a beamforming algorithm. One such example is given below:\n\n\n```julia\nfunction beamformer(Ns,X,Y,z0,f,rn,CSM)\n const M = size(rn,1) # Number of microphones\n const omega = 2pi*f # Angular frequency\n const c = 343 # Speed of sound\n \n r0 = sqrt(X.^2 + Y.^2 .+ z0^2)\n \n # Allocation of arrays\n rmn = Array(Float64,Ns,Ns,M);\n gj = Array(Complex128,Ns,Ns,M);\n b = Array(Complex128,Ns,Ns);\n \n # Compute transfer functions\n for i in 1:Ns\n for j in 1:Ns\n for m in 1:M\n rmn[i,j,m] = sqrt((X[i,j]-rn[m,1])^2+(Y[i,j]-rn[m,2])^2 + z0^2);\n gj[i,j,m] = (rmn[i,j,m]/r0[i,j])*exp(im*omega*rmn[i,j,m]/c);\n end\n end\n end\n\n CSM[eye(Bool,M)] = 0; # Diagonal removal\n\n for i = 1:Ns\n for j = 1:Ns\n b[i,j] = (dot(vec(gj[i,j,:]),CSM*vec(gj[i,j,:])))/(M^2-M);\n end\n end\n return b,gj\nend\n```\n\n\n\n\n beamformer (generic function with 1 method)\n\n\n\nThe experimental data used for this project is obtained from the Python package [Acoular](www.acoular.org). Time sampling of 56 microphones arranged in a microphone array can be found on the [Acoular Github page (a 6 MB download stored in HDF5 format)](https://github.com/acoular/acoular/blob/master/examples/example_data.h5?raw=true). The data is averaged and tranformed into the frequecy domain to obtain a covariance matrix. \n\nBelow is an example of the covariance matrix and a beamforming map. Solving the optimization problem results in a matrix $X$ with a diagonal that can be used to visualize the noise distribution in the source plane with a much higher resolution than that of the beamforming map.\n\n\n```julia\nusing MAT, GR\ninline()\n\nfile = matopen(\"CSM_TE.mat\")\nCSM_TE = read(file, \"CSM\")\nclose(file)\n\nfile = matopen(\"micgeom.mat\")\nrn = read(file, \"micgeom\")\nclose(file)\n\nNs = 50 # i.e. N = Ns^2\n\nid = 80\ndf = 47\nf = id*df\nrx = linspace(-0.6,0,Ns)\nry = linspace(-0.3,0.3,Ns)\nX,Y = (Float64[i for i in rx, j in ry],Float64[j for i in rx, j in ry])\n\nb,gj = beamformer(Ns,X,Y,0.68,f,rn,CSM_TE[:,:,id])\n\n# Plot example\n\nGR.figure(size=(750,300))\nGR.subplot(1,2,1)\nGR.heatmap(abs(flipdim(CSM_TE[:,:,id],1)),title=\"CSM matrix, rank = $(rank(CSM_TE[:,:,id]))\")\nGR.subplot(1,2,2)\nGR.contourf(rx,ry,real(b)./maximum(real(b)),xlabel=\"x\",ylabel=\"y\",title=\"Beamforming at $f Hz\")\n```\n\n\n\n\n \n\n \n\n\n\n## Background\n\nThe generation of electricity from renewable energy sources is more important than ever following the global agreement signed by 195 countries at the COP21 climate conference in Paris, December 2015. The long term goal, to limit the global average temperature increase to 2$^{\\circ}$C, requires governments around the world to limit their dependence on fossil fuels and adapt renewable energy sources.\n\nThis goal requires development and installation of more wind turbines (onshore and offshore) in the following years. Noise regulations on wind turbines near urban areas can restrict the installation of new wind turbines and limit the potential energy production. The main noise from wind turbines is aerodynamic and arises from turbulence caused by the air flow around the wind turbine blades in motion. The aerodynamic noise increases with the size of the wind turbine and with a demand for more productive, and thus larger wind turbines, there is an increased interest in quantifying the aerodynamic noise from wind turbine blades. In the design stage, wind turbine blades undergo a wealth of tests and simulations to ensure that the specific design is efficient. A wind tunnel is used to test the aerodynamic properties by applying a controlled airflow to a section of the blade. The wind tunnel can also be used to localize and quantify the noise sources with a microphone array, however, this requires specially designed wind tunnels.\n\nIn typical experimental setups, a wind turbine wing section, i.e., airfoil, is placed in such a wind tunnel and a controlled air flow is applied. The aerodynamic noise generated on the airfoil can be measured with a microphone array.\n\n## References\n[Hoeltgen, L., Breuß, M., Herold, G., & Sarradj, E. (2016). Sparse l1 Regularisation of Matrix Valued Models for Acoustic Source Characterisation. arXiv preprint arXiv:1607.00171.](https://arxiv.org/abs/1607.00171)\n\n[Herold, G., Sarradj, E., & Geyer, T. (2013). Covariance Matrix Fitting for Aeroacoustic Application.](http://www-docs.tu-cottbus.de/aeroakustik/public/veroeffentlichungen/herold_cmf_daga2013.pdf)\n\n[Yardibi, T., Li, J., Stoica, P., & Cattafesta, L. N. (2008). Sparsity constrained deconvolution approaches for acoustic source mapping. Journal of the Acoustical Society of America, 123(5), 2631–2642.](http://dx.doi.org.proxy.findit.dtu.dk/10.1121/1.2896754)\n\n\n```julia\n\n```\n", "meta": {"hexsha": "1e988418365ebdb7789cae5cadb6851ae7df7857", "size": 70092, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "ConvexOpt project proposal.ipynb", "max_stars_repo_name": "1oly/Convex-Optimization2017", "max_stars_repo_head_hexsha": "df0e967cc044fc1b8c5698fb0a98cf32fc6a63ac", "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": "ConvexOpt project proposal.ipynb", "max_issues_repo_name": "1oly/Convex-Optimization2017", "max_issues_repo_head_hexsha": "df0e967cc044fc1b8c5698fb0a98cf32fc6a63ac", "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": "ConvexOpt project proposal.ipynb", "max_forks_repo_name": "1oly/Convex-Optimization2017", "max_forks_repo_head_hexsha": "df0e967cc044fc1b8c5698fb0a98cf32fc6a63ac", "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": 75.0449678801, "max_line_length": 1048, "alphanum_fraction": 0.7108514524, "converted": true, "num_tokens": 2169, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9653811591688145, "lm_q2_score": 0.8824278772763471, "lm_q1q2_score": 0.8518792470479163}} {"text": "# Guide to Linear Regression in Python\n\nThis notebook is designed to guide you in learning how to do a basic linear regression using Python. The notebook will be divided into two parts. In the first, we will create data with some known function. Then, we will add some random fluctuations to the data and see if we can recover the function. In the second part, we will use a public dataset to test this schema and perform the linear regression.\n\nThis notebook will use a variety of packages.\n\n* [Numpy](https://numpy.org/doc/stable/reference/index.html) for array handling and basic numerical functions.\n* [SciKit-Learn](https://scikit-learn.org/stable/modules/classes.html) to perform the [linear regression](https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LinearRegression.html#sklearn.linear_model.LinearRegression) and provide [some data](https://scikit-learn.org/stable/modules/classes.html#module-sklearn.datasets)\n* [Matplotlib](https://matplotlib.org/stable/contents.html) for plotting and its simplified plotting module [Pyplot](https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.html?highlight=pyplot#module-matplotlib.pyplot)\n\n## Imports\n\nWe will begin by *importing* the necessary packages below.\n\n\n```python\n# Import Numpy\nimport numpy as np # For arrays and basic numerical computation\n\n# Import Packages from SciKit-Learn (sklearn)\n# sklearn is such a large project that objects must be imported directly\nfrom sklearn import datasets\nfrom sklearn.linear_model import LinearRegression\n\n# Import Matplotlib\nfrom matplotlib import pyplot as plt\n```\n\n## Part 1 - Known Functions\n\n### Example - Velocity as a Function of Position\n\nSuppose we have a particle traveling along the $x$ axis and get the following data.\n\n| x (m) | v (m/s) |\n| ----- | ------- |\n| 0.00 | 3.04 |\n| 1.00 | 4.96 |\n| 2.00 | 7.19 |\n| 3.00 | 9.03 |\n| 4.00 | 10.84 |\n| 5.00 | 13.11 |\n| 6.00 | 15.39 |\n| 7.00 | 17.28 |\n| 8.00 | 18.79 |\n| 9.00 | 20.62 |\n| 10.00 | 22.81 |\n\nAs it turns out, this data was simply generated by the equation\n\n\\begin{equation}\n v(x) = 2 x + 3\n\\end{equation}\n\nwith some additional random, gaussian noise. Therefore, when we do linear regression on this data, we *should* recover a slope of 2 and an offset of 3.\n\nNormally, your data might be entered on a spreadsheet which could be ported with either [pandas](https://pandas.pydata.org/) or Google's gsheet plugin, but we will enter the data manually below.\n\nSciKit-Learn requires that data be entered as 2D arrays where the \"observations\" appear on each row and the \"features\" on each column. Therefore, we will cast our data into just such an array.\n\n\n```python\n# Store the Positions\n# We will store this a 2D row vector first the transpose it to a column vector\n# A 1D array is created with one set of brackets whereas a 2D row vector is\n# stored with two brackets\n# Note the `T` operator at the end of the parentheses. This is what is performing\n# the transposition\n# Although this is not incredibly relevant now, python/numpy assumes numerical data\n# without decimals is integer data. Therefore, my dtype statement is telling\n# numpy that the data should be treated as a float (number with decimals)\nX = np.array([[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]], dtype='float64').T\n\n# Store the Velocities\n# This procedure matches the statement above\n# Note that statements in parentheses can be broken over multiple lines\n# This is called implicit line breaking\nY = np.array([[\n 3.04, 4.96, 7.19, 9.03, 10.84, 13.11, 15.39, 17.28, 18.79, 20.62, 22.81\n]]).T\n```\n\nNow that we have stored our data in the variables `X` and `Y`, we can plot the scatter data before the regression to get a sense for what the data look like. Since this is a simple plot, we will use the pyplot [scatter](scatter) function. I'll also plot the function from which the data were generated with a simple [line plot](https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.plot.html#matplotlib.pyplot.plot).\n\n\n```python\n# Plot the Sample Data as a scatter plot\n# The scatter function takes the independent variable first and the dependent second\n# The label keyword is for displaying the legend later\n_ = plt.scatter(X, Y, label='Sample Data')\n\n# Plot the Function\n# I'll generate another set of variables to make this plot\nxLine = np.arange(-2., 12) # Generates data from -2 to 11 with stepsize 1\nyLine = 2*xLine + 3 # Create y from the x data and known function\n_ = plt.plot(xLine, yLine, ':k', label='v(x)')\n\n# Set the Limits for the axis\nplt.xlim(-2, 11)\nplt.ylim( 0, 25)\n\n# Label Everything!\nplt.xlabel('Position (m)')\nplt.ylabel('Velocity (m/s)')\nplt.title(\"Measuring a Particle's Velocity\")\n\n# Add the grid if wanted\n# Uncomment the next line if you want the plot to be gridded\n# plt.grid()\n\n# Create the Legend\n_ = plt.legend()\n```\n\nNow that we are comfortable with plotting, let's move on the the linear regression.\n\n\n```python\n# Create/Fit the Model\n# sklearn is built around a framework of fitting data to models. Here, we are trying\n# to fit our data to a linear model with linear regression.\n# Below, we are creating a linear regression model, fitting the model to our data\n# then we are storing that information in the variable named model\nmodel = LinearRegression().fit(X, Y)\n\n# Print out the fit\n# Note that the slope parameter is stored as the model.coef_ and the\n# intercept is stored as model.intercept_\n# We store the equation in a string for future use\neqStr = 'v(x) = {:.2f} x + {:.2f}'.format(model.coef_.item(), model.intercept_.item())\nprint('Model Fit')\nprint('v(x) = m x + b')\nprint(eqStr)\n```\n\n Model Fit\n v(x) = m x + b\n v(x) = 1.98 x + 3.13\n\n\nAs can be seen above, we were able to approximate the generating function based on the given data. Although the \"random\" fluctuations created a slight error in our coeficient and intercept, we got close to the predicted value.\n\nNow, let's recreate the plot above with our regression too.\n\n\n```python\n# Plot the Sample Data as a scatter plot\n_ = plt.scatter(X, Y, label='Sample Data')\n\n# Plot the Regression Model\n# For this, we need an xLine that is a 2D column vector like above\n# We will calculate the y values by predicting with our model\nxLine = np.arange(-2., 12)[:, np.newaxis] # Generates data from -2 to 11 with stepsize 1\nyLine = model.predict(xLine) # Create y from the x data and known function\n_ = plt.plot(xLine, yLine, 'C1', label='Trendline')\n\n# Add the equation string we printed above on the graph\n_ = plt.text(-1, 15, eqStr)\n\n# Plot the Function\nyLine = 2*xLine + 3 # Create y from the x data and known function\n_ = plt.plot(xLine, yLine, ':k', label='v(x)')\n\n# Set the Limits for the axis\nplt.xlim(-2, 11)\nplt.ylim( 0, 25)\n\n# Label Everything!\nplt.xlabel('Position (m)')\nplt.ylabel('Velocity (m/s)')\nplt.title(\"Measuring a Particle's Velocity\")\n\n# Add the grid if wanted\n# Uncomment the next line if you want the plot to be gridded\n# plt.grid()\n\n# Create the Legend\n_ = plt.legend()\n```\n\nAs you can see, the model fits the data well and almost perfectly recovers the generating function.\n\n### Your Turn\n\nNow it's your turn, input the following data into the variables below and let my code from above take care of the rest.\n\n| x (m) | v (m/s) |\n| ----- | ------- |\n| 0.00 | 2.09 |\n| 2.00 | 7.91 |\n| 4.00 | 14.45 |\n| 6.00 | 20.07 |\n| 8.00 | 25.63 |\n| 10.00 | 32.25 |\n| 12.00 | 38.91 |\n| 14.00 | 44.66 |\n| 16.00 | 49.51 |\n| 18.00 | 55.11 |\n| 20.00 | 61.56 |\n\n\n\n```python\n# Store the Positions\nX = np.array([[]], dtype='float64').T\n\n# Store the Velocities\nY = np.array([[\n \n]]).T\n\n# Create/Fit the Model\nmodel = LinearRegression().fit(X, Y)\n\n# Print out the fit\neqStr = 'v(x) = {:.2f} x + {:.2f}'.format(model.coef_.item(), model.intercept_.item())\nprint('Model Fit')\nprint('v(x) = m x + b')\nprint(eqStr)\n\n# Plot the Sample Data as a scatter plot\n_ = plt.scatter(X, Y, label='Sample Data')\n\n# Plot the Regression Model\nxLine = np.arange(-2., 22)[:, np.newaxis] # Generates data from -2 to 11 with stepsize 1\nyLine = model.predict(xLine) # Create y from the x data and known function\n_ = plt.plot(xLine, yLine, 'C1', label='Trendline')\n\n# Add the equation string we printed above on the graph\n_ = plt.text(-1, 40, eqStr)\n\n# Plot the Function\nyLine = 3*xLine + 2 # Create y from the x data and known function\n_ = plt.plot(xLine, yLine, ':k', label='v(x)')\n\n# Set the Limits for the axis\nplt.xlim(-2, 21)\nplt.ylim( 0, 65)\n\n# Label Everything!\nplt.xlabel('Position (m)')\nplt.ylabel('Velocity (m/s)')\nplt.title(\"Measuring a Particle's Velocity\")\n\n# Add the grid if wanted\n# Uncomment the next line if you want the plot to be gridded\n# plt.grid()\n\n# Create the Legend\n_ = plt.legend()\n```\n", "meta": {"hexsha": "b6af721be786cd4502667618e64c1ae0150fa8dc", "size": 54035, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "04-ElementaryStatistics/LinearRegression.ipynb", "max_stars_repo_name": "wwaldron/NumericalPythonGuide", "max_stars_repo_head_hexsha": "8e0c2947251b9639cbc66d6462dd495c180e3faa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-09-22T02:29:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-22T02:29:11.000Z", "max_issues_repo_path": "04-ElementaryStatistics/LinearRegression.ipynb", "max_issues_repo_name": "wwaldron/NumericalPythonGuide", "max_issues_repo_head_hexsha": "8e0c2947251b9639cbc66d6462dd495c180e3faa", "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": "04-ElementaryStatistics/LinearRegression.ipynb", "max_forks_repo_name": "wwaldron/NumericalPythonGuide", "max_forks_repo_head_hexsha": "8e0c2947251b9639cbc66d6462dd495c180e3faa", "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": 144.4786096257, "max_line_length": 22304, "alphanum_fraction": 0.8678264088, "converted": true, "num_tokens": 2486, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037302939515, "lm_q2_score": 0.9196425322789908, "lm_q1q2_score": 0.851868308187005}} {"text": "## Homework\n\n### Ice Cream Sales in Inferenceville\n\nYou have been hired to investigate a disturbing connection between ice cream sales and crime in Inferenceville. You are given a report that describes the joint distribution over random variable $S$, representing ice cream sales, and random variable $C$, representing crime. Each variable takes on a value of “low\" or “high\", which we'll represent with $0$ and $1$ respectively. The joint distribution (estimated from data) is as follows:\n\n\n\n(a) Are random variables $S$ and $C$ independent?\n\n\n[$\\times $] Yes
\n[$\\checkmark$] No\n\n\n```python\ndef is_independent(p_X_Y):\n \"\"\"\n Returns true if the given join prbability distribution is independet.\n \n >>> import numpy as np\n >>> p_X_Y = np.array([[0.4, 0.1], [0.25, 0.25]])\n >>> is_independent(p_X_Y)\n False\n \n >>> p_X_Y = np.array([[0.72, 0.08], [0.18, 0.02]])\n >>> is_independent(p_X_Y)\n True\n \"\"\"\n\n import numpy as np\n p_X = p_X_Y.sum(axis=1)\n p_Y = p_X_Y.sum(axis=0)\n Δ = np.outer(p_X, p_Y) - p_X_Y\n return (np.linalg.norm(Δ, np.inf) - 0.00001) < 0\n\nif __name__ == \"__main__\":\n import doctest\n doctest.testmod()\n```\n\n\n```python\nfrom sympy import init_printing\ninit_printing()\n```\n\n\n```python\nimport numpy as np\np_S_C = np.array([[0.4, 0.1], [0.25, 0.25]])\nis_independent(p_S_C)\n```\n\n\n\n\n False\n\n\n\n(b) After further investigation, you discover information about the temperature, represented by $T$. This random variable also takes on values $0$ or $1$ corresponding again to “low\" and “high\". You are able to obtain the conditional distribution $p_{S,C \\mid T}(s,c \\mid t)$, shown below.\n\n\n\nAre random variables $S$ and $C$ conditionally independent given $T$?\n\n\n[$\\checkmark$] Yes
\n[$\\times $] No\n\n\n```python\nimport numpy as np\np_T_1 = np.array([[0.72, 0.08], [0.18, 0.02]])\np_T_2 = np.array([[0.08, 0.12], [0.32, 0.48]])\nis_independent(p_T_1) and is_independent(p_T_2)\n```\n\n\n\n\n True\n\n\n\n(c) Determine the distribution $p_T$ from the tables above. Express your answer as a Python dictionary. The keys should be the Python integers $0$ and $1$.\n\nAssuming $p_T(0) = p$ then $p_T(1) = (1-p)$. Now by the law of total probability, \n\n$$\\begin{align}\np_{S,C}(0,0) &= p_{S,C\\mid T}(0,0 | 0)p_T(0) + p_{S,C\\mid T}(0,0 | 1)p_T(1) \\\\\n 0.4 &= 0.72p + 0.08(1-p)\\\\ \n\\end{align}$$\n\n\n```python\nfrom sympy.solvers import solve\nfrom sympy import Symbol\np = Symbol('p')\np = solve(0.08*(1-p) + 0.72*p - 0.4, p)[0]; p\n```\n\n\n```python\np_T = {0: p, 1: 1-p}; p_T\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "9c6fbea1bcef8eaa6605c857fb4f6ea610bd2393", "size": 8485, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "week03/04 Homework.ipynb", "max_stars_repo_name": "infimath/Computational-Probability-and-Inference", "max_stars_repo_head_hexsha": "e48cd52c45ffd9458383ba0f77468d31f781dc77", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-04-04T03:07:47.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-04T03:07:47.000Z", "max_issues_repo_path": "week03/04 Homework.ipynb", "max_issues_repo_name": "infimath/Computational-Probability-and-Inference", "max_issues_repo_head_hexsha": "e48cd52c45ffd9458383ba0f77468d31f781dc77", "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": "week03/04 Homework.ipynb", "max_forks_repo_name": "infimath/Computational-Probability-and-Inference", "max_forks_repo_head_hexsha": "e48cd52c45ffd9458383ba0f77468d31f781dc77", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-02-27T05:33:49.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-27T05:33:49.000Z", "avg_line_length": 30.8545454545, "max_line_length": 1358, "alphanum_fraction": 0.6044784915, "converted": true, "num_tokens": 832, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172644875642, "lm_q2_score": 0.8976952934758465, "lm_q1q2_score": 0.8518385622284614}} {"text": "# Ridge Regression with Gradient Descent\n\n### Author: Juan Solorio\n\n-----\n\n# Overview\nIn this exercise, I will implement a first version of my own gradient descent algorithm to\nsolve the ridge regression problem. I will keep improving and extending this gradient descent optimization algorithm. In this notebook, I will implement a basic version of the algorithm.\n\n## Objectives\n- Mathematically define _Objective Function_ for Ridge Regression ($F\\beta$)\n - Compute gradiant $\\nabla F$\n- Create functions for algorithm:\n - Objective function\n - Gradient function\n - Gradient Descent funtion\n- Observe (plot) the convergence in terms of the function values and the gradients \n and tune for the optimal hyperparameters for step-size ($\\eta$) and normalization ($\\lambda$)\n- Compare to _sklearn_\n\n\n## Environment Setup - *Importing Libraries*\n\n\n```python\n# needed libraries\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom sklearn.model_selection import train_test_split\nfrom sklearn import preprocessing\nfrom sklearn.linear_model import Ridge\nimport time\n\n%matplotlib inline\nplt.style.use('ggplot')\n```\n\n# Background and Theory\n\nWe start by defining the ___Linear Regression___ as a supervised learning algorithm and we write the mathematical algorithm as:\n$$\ny = b_0*x + b_1\n$$\n> y - target value \n$b_0$ - slope \nx - predictor variable \n$b_1$ - intercept\n\nwhere $m$ and $b$ are the variables the algorithm will try to predict from the data.\n\nWe can generalize this equation for multiple variables and write our _cost function_ to optimize our algorithm as:\n\n$$\nF(\\beta) = \\frac{1}n\\sum_{i=1}^n(y_i - h(x_i))^2 \\\\\n\\\\\n\\\\\nh(x_i) = x_1\\beta_1 + x_2\\beta_2 + ... + x_{i,j}\\beta_j\n$$\n\nWhere $h(x_i)$ is the predicted value for the function, $\\beta$ are the weights for the individual variables, and $y_i$ is the target value of the data.\n\nWe can finalize this by writing the equation in the expanded form:\n$$\nF(\\beta) = \\frac{1}n\\sum_{i=1}^n(y_i - \\sum_{j=1}^dx_{ij}\\beta_j)^2\n$$\n\n## Lasso Regression\n\nLinear Regression treats all the features equally and finds unbiased weights to minimizes the cost function.\nIn _Ridge Regression_ , there is an addition of l2 penalty ( square of the magnitude of weights ) in the cost function of Linear Regression:\n\n\n$$\n\\lambda\\|\\beta\\|^2_2\n\n$$\n\nWhere $\\lambda$ is a hyperparameter to be tuned and this is done so that the model does not overfit the data. \n\nWe can write the final objective equation as:\n\n\n$$\nF(\\beta) = \\frac{1}n\\sum_{i=1}^n(y_i - \\sum_{j=1}^dx_{ij}\\beta_j)^2 + \\lambda\\sum_{j=1}^d\\beta_j^2\n$$\n\n\n## Gradient Descent\nGradient descent is an optimization algorithm used to minimize some function by iteratively moving in the direction of steepest descent as defined by the negative of the gradient. In machine learning, we use gradient descent to update the parameters or weights ($\\beta$) of our model.\n\nIn order to minimize with respect to $\\beta$, we want to take the derivative of $F(\\beta)$ and set it equal to zero. \n\nThe derivative for $n=1$ and $d=1$ yields:\n\\begin{equation}\n\\frac{dF}{d\\beta} = \\frac{2}n(y - x\\beta) + 2\\lambda\\beta\n\\end{equation}\n\nand for $n>1$ and $d>1$\n\n\n$$\n\\frac{\\partial F}{\\partial \\beta_j} = \\frac{\\partial}{\\partial \\beta_j} (\\frac{1}n\\sum_{i=1}^n(y_i - x^T_{i}\\beta_j)^2 + \\lambda\\|\\beta\\|^2_2)\n$$\n$$\n= \\frac{1}n(\\sum_{i=1}^n \\frac{\\partial}{\\partial \\beta_j} (y_i - x^T_{i}\\beta_j)^2 + \\frac{\\partial}{\\partial \\beta_j} \\lambda\\|\\beta\\|^2_2)\n$$\n$$\n= -\\frac{2}n(\\sum_{i=1}^n x_{ij} (y_i - x^T_{i}\\beta_j)) + 2\\lambda\\sum_{j=1}^d\\beta_j\n$$\n\n\n\nIn Matrix terms, $F(\\beta)$ can be interpreted as:\n\n\n$$\nF(\\beta) = \\frac{1}{n} + \\lambda\\|\\beta\\|^2_2\n$$\n\n\nTaking the derivative of the matrix form of $F(\\beta)$ leads us to the following:\n\n\n$$\n\\nabla F = \\frac{\\partial}{\\partial\\beta} F= - \\frac{2}{n}X^T(y + X\\beta) + 2\\lambda\\beta\n$$\n\n\nWhich is also known as the _gradient_ of the _objective function_ $F$.\n\n\n# Algorithm Functions Definitions\n\n* Objective function for Ridge Regression $F(\\beta)$:\n\n>$$\nF(\\beta) = \\frac{1}n\\sum_{i=1}^n(y_i - X^T_{ij} \\cdot \\beta_j)^2 + \\lambda\\|\\beta_j\\|^2_2\n$$\n\n\n```python\ndef obj_fx(beta,lamda,X,y):\n \"\"\"\n Linear regression with Ridge penalty L1:\n F(b) = 1/n sum((y - x dotproduct b)^2) + lamda*norm(b)^2\n \n Parameters\n ----------\n beta : arr\n array of values for weights\n lamda : int\n interger value for normalization parameter\n X : arr\n array of features from data\n y : arr\n array of target values from data\n\n Returns\n -------\n int\n computation of the objective function\n\n \"\"\"\n \n # dot product can be accomplish by 'numpy_arrayA @ numpy_arrayB' or 'numpy_arrayA.dot(numpy_arrayB)'\n return 1/len(y) * sum((y - X @ beta)**2) + lamda*np.linalg.norm(beta)**2\n```\n\n* Gradient of objective funtion - $\\nabla F$:\n>$$\n\\nabla F = \\frac{\\partial}{\\partial\\beta} F= - \\frac{2}{n}X^T(y + X\\beta) + 2\\lambda\\beta\n$$\n\n\n```python\ndef gradient_fx(beta,lamda,X,y):\n \"\"\"\n Computes gradient of the Linear regression with Ridge penalty L1 function:\n grad F(b) = -2/n (x.T dotproduct (y - x dotproduct b)) + 2*lamda*b\n \n Parameters\n ----------\n beta : arr\n array of values for weights\n lamda : int\n interger value for normalization parameter\n X : arr\n array of features from data\n y : arr\n array of target values from data\n\n Returns\n -------\n int\n computation of the gradient of Ridge regression objective function\n\n \"\"\"\n return (-2/len(y)) * X.T @ (y - X @ beta) + 2*lamda*beta \n```\n\n* Gradient Descent Algorith:\n>`Gradient Descent algorithm with fixed constant step-size \n__input__ step-size $\\eta$ \n__initialization__ $\\beta_0 = 0$ \n__repeat for__ t = 0, 1, 2, . . . \n $\\beta_{t+1} = \\beta_t − \\eta \\nabla F(\\beta_t)$ \n__until__ the stopping criterion $\\|\\nabla F\\| \\leq \\epsilon$ is satisfied.\n\n\n\n```python\ndef gradient_descent(beta_init, eta ,lamda,X,y,epsilon=0.005):\n \"\"\"\n Computes gradient descent with a fixed step size eta and stopping condition norm gradient F < epislon\n \n Parameters\n ----------\n beta_init : arr\n array of values for weights as starting point\n eta : int\n interger value for step size parameter\n lamda : int\n interger value for normalization parameter\n X : arr\n array of features from data\n y : arr\n array of target values from data\n epsilon : int\n interger value for stopping parameter condition, defaul = 0.005\n\n Returns\n -------\n beta_vals: Matrix \n Estimated betas at each iteration, with the most recent values in the last row\n \"\"\"\n # setting initial value of betas\n beta = beta_init\n # gradient calculation for starting values\n gradient = gradient_fx(beta,lamda,X,y)\n # list to save beta values \n beta_vals = [beta_init]\n # loop for stopping criterion epsilon\n while np.linalg.norm(gradient) > epsilon:\n # updating values for beta and gradient\n beta = beta - eta*gradient\n gradient = gradient_fx(beta,lamda,X,y)\n \n # appending values\n beta_vals.append(beta)\n return np.array(beta_vals)\n```\n\n# Implementation\nFor our data, we'll use the ***Hitters*** dataset from `'https://raw.githubusercontent.com/selva86/datasets/master/Hitters.csv'`, and we'll drop any rows with `NA` values.\n\n\n```python\n# Load the data\nhitters = pd.read_csv('https://raw.githubusercontent.com/selva86/datasets/master/Hitters.csv',\n sep=',', header=0)\nhitters = hitters.dropna()\nhitters.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
AtBatHitsHmRunRunsRBIWalksYearsCAtBatCHitsCHmRunCRunsCRBICWalksLeagueDivisionPutOutsAssistsErrorsSalaryNewLeague
131581724383914344983569321414375NW6324310475.0N
2479130186672763162445763224266263AW8808214480.0A
3496141206578371156281575225828838354NE200113500.0N
43218710394230239610112484633NE80540491.5N
55941694745135114408113319501336194AW28242125750.0A
\n
\n\n\n\nWe are going to attempt to use our Ridge Regression algorithm to try and predict the _Salary_ of a player based on all the other features in the dataset. We want to create our _Features_ (X) and _Target_ (y) datasets.\n\n\n```python\n# Creating matrix X with the predictors and \n# and vector y with the response \nX = hitters.drop('Salary', axis=1)\n# need to transform our labels for 'League','Division','NewLeague' to bool or {1,0} values\nX = pd.get_dummies(X, drop_first=True) \ny = hitters.Salary\n\nX.head(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 \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
AtBatHitsHmRunRunsRBIWalksYearsCAtBatCHitsCHmRunCRunsCRBICWalksPutOutsAssistsErrorsLeague_NDivision_WNewLeague_N
1315817243839143449835693214143756324310111
24791301866727631624457632242662638808214010
3496141206578371156281575225828838354200113101
\n
\n\n\n\nWe now need to split our data into _train_ and _test_ sets for both the features and target variables. Given the values in our _Features_ vary in size or magnitude, we need to standardize our features by using the sklearn function `preprocessing.StandardScaler()`.\n\n\n```python\n# Dividing the data into train and test sets.\n# By default, it is a 75-25 split between train-test\nX_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)\n\n# Standarizing the data\nscaler = preprocessing.StandardScaler().fit(X_train)\nX_train = scaler.transform(X_train)\nX_test = scaler.transform(X_test)\nscaler = preprocessing.StandardScaler().fit(y_train.values.reshape(-1, 1))\ny_train = scaler.transform(y_train.values.reshape(-1, 1)).reshape((-1))\ny_test = scaler.transform(y_test.values.reshape(-1, 1)).reshape((-1))\n```\n\n\n```python\ndef convergence_plots(x_vals, lambduh, X,y,title):\n \"\"\"\n Plot the convergence in terms of the function values and the gradients\n Input:\n - x_vals: Values the gradient descent algorithm stepped to\n \"\"\"\n n, d = x_vals.shape\n fs = np.zeros(n)\n grads = np.zeros((n, d))\n for i in range(n):\n fs[i] = obj_fx(x_vals[i], lambduh,X,y)\n grads[i, :] = gradient_fx(x_vals[i], lambduh,X,y)\n grad_norms = np.linalg.norm(grads, axis=1)\n \n fig_dims = (15, 3)\n fig, (ax1, ax2) = plt.subplots(1, 2, figsize=fig_dims)\n\n ax1.plot(fs)\n ax1.set_xlabel('Iteration')\n ax1.set_ylabel('Objective value')\n \n ax2.plot(grad_norms)\n ax2.set_xlabel('Iteration')\n ax2.set_ylabel('Norm of gradient')\n plt.suptitle(title,fontsize=16)\n plt.subplots_adjust(left=0.2, wspace=0.8, top=0.8)\n plt.show()\n\n```\n\n\n```python\neta = 0.05\nlambdas = [-0.1, 0.005,0.001,0.01,0.05,1]\nd = X_train.shape[1]\nbeta_init = np.zeros(d)\nfor lambduh in lambdas:\n # store starting time \n begin = time.time() \n betas = gradient_descent(beta_init=beta_init, eta=eta, lamda=lambduh,X=X_train,y=y_train)\n title=r'Function Value and Norm of Gradient Convergence $\\lambda =$ {:.3f}'.format(lambduh)\n convergence_plots(betas, lambduh,X_train, y_train, title)\n\n time.sleep(1) \n # store end time \n end = time.time() \n \n # total time taken \n print(f\"Total runtime of the program is {end - begin}\") \n```\n\nWe see that the _Objective value_ of the function diverges when the normalization parameter $\\lambda$ is negative and that it converges to about _0.5_ when tha values of $\\lambda=[0.001,0.05]$. The best run time occured for $\\lambda=0.01$, so we'll use this as our _Optimal_ normalization parameter value.\n\n# Comparing to _Scikit-Learn_\n\nWe can compute the ridge regression model from sklearn by using the `Ridge` function from **sklearn.linear_model** and compare how our model performed. \n\n_Note that the scikit-learn [objective function](http://scikit-learn.org/stable/modules/linear_model.html#ridge-regression) is_ :\n\n$$\nF^*(\\beta) = \\min_{\\beta \\in \\mathbb{R}^d} \\sum_{i=1}^n(y_i - \\sum_{j=1}^dx_{ij}\\beta_j)^2 + \\alpha\\sum_{j=1}^d\\beta_j^2\n$$\n\nwhen comparing sklearn's objective function $F^*(\\beta)$ to our objective function $F(\\beta)$, we get that:\n> $\\lambda = \\frac{\\alpha}{n} \\Longrightarrow \\alpha = n * \\lambda$\n\n\n```python\n# number of samples n\nn = len(y_train)\nlambduh = 0.01\nbetas = gradient_descent(beta_init=beta_init, eta=eta, lamda=lambduh,X=X_train,y=y_train)\n# setting alpha for sklearn ridge \nalpha = n*lambduh\nridge = Ridge(alpha=alpha, fit_intercept=False) # initializing ridge\nridge.fit(X_train, y_train) # training ridge model\n# printing beta values\nprint(\"Sklearn Final weights (betas): \", ridge.coef_)\nprint(\"Our Final weights (betas): \", betas[-1])\n\n```\n\n Sklearn Final weights (betas): [-0.49683318 0.53848371 0.14026802 -0.09125083 0.01367849 0.28982753\n -0.10561524 -0.22109841 0.49775465 -0.05474063 0.53958547 0.06559602\n -0.37105594 0.14704651 0.09250802 -0.09098076 0.04637135 -0.12793725\n -0.01498699]\n Our Final weights (betas): [-0.48507163 0.51545023 0.1336241 -0.07385865 0.01975817 0.28526168\n -0.11787016 -0.12322043 0.4547416 -0.05871632 0.49069089 0.06869243\n -0.36495034 0.14618957 0.08881195 -0.09213196 0.04644374 -0.12970797\n -0.0157561 ]\n\n\n\n```python\nprint(\"Objective value from Sklearn F*(beta): \", obj_fx(ridge.coef_, lambduh,X_train,y_train))\nprint(\"Objective value from our F(beta): \", obj_fx(betas[-1], lambduh,X_train,y_train))\n\n```\n\n Objective value from Sklearn F*(beta): 0.5261102696078659\n Objective value from our F(beta): 0.5263969771608789\n\n\nThe values for our final _feature weights_ ($\\beta$ 's) and _objective function_ from our algorithms match pretty well with those produced by _Sklearn_ functions.\n\nWe can now predict values for our _tests_ datasets and see how well our model's predictions compare to the expected values. Sklearn has the built in function `.predict` for all it's supervised learning models, we can recreate the function by computing the _dot product_ of the features and the weights.\n\n\n```python\ndef predict_values(betas, X):\n \"\"\"\n Function calculates the predicted target values for dot product for given betas and features (X)\n \n Parameters\n ----------\n beta_init : arr\n array of values for weights \n X : arr\n array of features from data\n\n Returns\n -------\n Calculated predicted values for target variable, from dot product of features and weights\n \"\"\"\n return X.dot(betas)\n```\n\n\n```python\n# getting a dataframe of the predicted values for both my own algorithm and sklearn\n# for the test dataset\npredicted_data = pd.DataFrame(np.array([ridge.predict(X_test), predict_values(betas[-1],X_test), y_test]).T, \n columns=['Sklearn Ridge','Own Ridge','Expected Values']).melt(id_vars=['Expected Values']).rename(\n columns={'variable':'ML algorithm','value':'Predicted Values'})\npredicted_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
Expected ValuesML algorithmPredicted Values
00.289100Sklearn Ridge0.030257
1-0.079887Sklearn Ridge1.323443
2-0.811811Sklearn Ridge-1.026751
31.402108Sklearn Ridge0.250032
4-0.769468Sklearn Ridge0.114917
\n
\n\n\n\n\n```python\n# plot comparing both how well do my algorithm compares to sklean's predictions\n# and comparing how well the predictions are compared to the actual expected values (diagonal scatter)\nsns.color_palette(\"colorblind\")\ng = sns.FacetGrid(predicted_data,hue='ML algorithm', height = 7,aspect=1)\ng = g.map(sns.scatterplot, \"Expected Values\", \"Predicted Values\", edgecolor=\"w\",s=100,alpha=.8)\nplt.plot(predicted_data['Expected Values'],predicted_data['Expected Values'],'k.',linewidth=1.5,\n alpha=.4,label='If Perfect Prediction')\nplt.legend()\nplt.show()\n```\n\nWe can again see that the values from our model compared very well to those from the sklearn model, and both models aline with the expected values' overall trend, but do appear to have greater error or diverge from the expected values the higher the \"Salary\". \n\nLet's finally just check the distribution of the percent difference for the predicted from expected values, we'll first rescale the predicted values back to the original sample values.\n\n\n```python\n# scaling back to the actual salary values\nsalary_sklearn = np.round(scaler.inverse_transform(ridge.predict(X_test)))\nsalary_own = np.round(scaler.inverse_transform(predict_values(betas[-1],X_test)))\nsalary = scaler.inverse_transform(y_test)\n```\n\n\n```python\n# checking the error distribution\nprint(\"Percent of values with less than 50%% error: %2d %%\"%(100*np.mean(abs(salary-salary_own)/salary <= 0.5)))\nsns.histplot(((salary-salary_own)/salary))\n```\n\nWe can see that about 57% of our values have less than or equal to \"50%\" difference from the expected values, and from the scatter plot again we can see how at smaller salaries we have some higher predicted salaries and we tend to under predict values as the salaries increase.\n", "meta": {"hexsha": "eb21e98f18e0a933609a97b6afd88397af80754d", "size": 248158, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "1-Python/1 - Ridge Regression w Gradient Descent.ipynb", "max_stars_repo_name": "JUAN-SOLORIO/UW-MachineLearning", "max_stars_repo_head_hexsha": "60cf1474bce45dd541d3fb60eb3b2a2eeaa9ca3c", "max_stars_repo_licenses": ["RSA-MD"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "1-Python/1 - Ridge Regression w Gradient Descent.ipynb", "max_issues_repo_name": "JUAN-SOLORIO/UW-MachineLearning", "max_issues_repo_head_hexsha": "60cf1474bce45dd541d3fb60eb3b2a2eeaa9ca3c", "max_issues_repo_licenses": ["RSA-MD"], "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-Python/1 - Ridge Regression w Gradient Descent.ipynb", "max_forks_repo_name": "JUAN-SOLORIO/UW-MachineLearning", "max_forks_repo_head_hexsha": "60cf1474bce45dd541d3fb60eb3b2a2eeaa9ca3c", "max_forks_repo_licenses": ["RSA-MD"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 212.1008547009, "max_line_length": 39216, "alphanum_fraction": 0.8908114991, "converted": true, "num_tokens": 6769, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.933430812881347, "lm_q2_score": 0.9124361527383703, "lm_q1q2_score": 0.8516960197529059}} {"text": "# Horner's Method\n\nwhich also call as QinJiuSao's Method in China, because QinJiuSao pubulished the method in 1247 while Horner pubilshed in 1819.\n\nHorner's Method is an algorithm for calculating polynomials in a computational efficient way.\n\n$$p(x) = \\sum_{i=0}^{n}a_i * x^{n-i}$$\n\nIntuitively, it seams we need $\\frac{n(n+1)}{2}$ times Multiplies and $n$ times Additons. But things chanegd if it is transformed to the follow expression.\n$$p(x) = (...(a_0x+a_1)x + a_2)...+a_{n-1})x+a_n$$\n\nObviously, it is just a recursion defination of the previous polynomial which can be present as below.\n\n$$\n\\begin{equation}\n\\left\\{\n \\begin{array}{lr}\n b_0=a_0, & \\\\\n b_i = b_{i-1} * x^* + a_i, & i = 1,2,...,n \n \\end{array}\n\\right.\n\\end{equation}\n$$\n\nEvidently, it just takes $n$ times Multiplies and $n$ times Additions.\n\n# 秦九韶算法\n\n用于计算多项式,将原来的需要$n^2$的运算复杂度降低到了$n$。算法的迭代表达式如上公式。\n", "meta": {"hexsha": "b3638af68e3e04800e3f6358fe062e3372818993", "size": 1706, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Numerical Analysis/Horner method/.ipynb_checkpoints/README-checkpoint.ipynb", "max_stars_repo_name": "Sean16SYSU/Algorithms4N", "max_stars_repo_head_hexsha": "24f06c29d476c4bd9c90bcc89dac90ba3a448c27", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-09-30T01:26:41.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-02T01:36:34.000Z", "max_issues_repo_path": "Numerical Analysis/Horner method/.ipynb_checkpoints/README-checkpoint.ipynb", "max_issues_repo_name": "Sean16SYSU/Algorithms4N", "max_issues_repo_head_hexsha": "24f06c29d476c4bd9c90bcc89dac90ba3a448c27", "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": "Numerical Analysis/Horner method/.ipynb_checkpoints/README-checkpoint.ipynb", "max_forks_repo_name": "Sean16SYSU/Algorithms4N", "max_forks_repo_head_hexsha": "24f06c29d476c4bd9c90bcc89dac90ba3a448c27", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-05-18T15:09:01.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-21T10:14:51.000Z", "avg_line_length": 27.9672131148, "max_line_length": 165, "alphanum_fraction": 0.52989449, "converted": true, "num_tokens": 340, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566341999997378, "lm_q2_score": 0.8902942319436397, "lm_q1q2_score": 0.8516859103397847}} {"text": "# Optimizing Stiffness Constants\n\nSuppose we have $n$ blocks, each of width $w$, at positions $x\\in\\mathbb{R}^n$.\nThe blocks are positioned between two walls at $0$ and $l$.\nThe leftmost block is connected to the left wall via a spring with stiffness coefficient $k_1$,\nthe rightmost block is connected to the right wall via a spring with stiffness coefficient $k_{n+1}$,\nand the $i$th block is connected to the $(i+1)$th block via a spring with stiffness coefficient $k_{i+1}$.\nThe equilibrium position of all the blocks can be found by solving the optimization problem\n\\begin{equation}\n\\begin{array}{ll}\n\\mbox{minimize} & \\frac{1}{2}k_1x_1^2 + \\frac{1}{2}k_2(x_2-x_1)^2 + \\ldots + \\frac{1}{2}k_{n+1}(l-x_n)^2\\\\[.2cm]\n\\mbox{subject to} & x_1 \\geq w/2, \\quad x_n \\leq l - w/2, \\\\\n& x_i - x_{i-1} \\geq w, \\quad i=2,\\ldots,n-1,\n\\end{array}\n\\label{eq:prob}\n\\end{equation}\nwith variable $x$ and solution denoted $x^\\star$.\nThe objective is the potential energy of the system, and the constraints express\nthe fact that the blocks have a width, and cannot penetrate each other or the walls.\n\n\n```python\n# NOTE: this notebook requires ffmpeg, which can be installed on ubuntu with \"sudo apt install ffmpeg\"\n# and on mac with \"brew install ffmpeg\"\nimport cvxpy as cp\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nfrom cvxpylayers.tensorflow import CvxpyLayer\nimport matplotlib.patches as patches\nfrom matplotlib import animation, rc\nrc('animation', html='html5')\n```\n\nWe can easily set up this problem as a CVXPY problem, with parameter $k$ and variable $x$:\n\n\n```python\nn = 5\nl = 1\nw = .05\n\nk = cp.Parameter(n + 1, nonneg=True)\nx = cp.Variable(n + 2)\nobjective = cp.sum(cp.multiply(k, .5 * cp.square(cp.diff(x))))\nconstraints = [x[0] == 0, x[-1] == l] + [x[i] - x[i-1] >= w for i in range(1, n+2)]\nprob = cp.Problem(cp.Minimize(objective), constraints)\n```\n\nWe can easily convert this problem to a `tensorflow` `CvxpyLayer` in one line.\nThe layer maps stiffness coefficients to block positions, or $x^\\star(k)$.\n\n\n```python\nprob_tf = CvxpyLayer(prob, [k], [x])\n```\n\nOur goal is to tune the stiffness coefficients such that the block positions are close to target positions,\nor solve the problem\n\\begin{equation}\n\\begin{array}{ll}\n\\mbox{minimize} & \\|x^\\star(k) - x^\\mathrm{targ}\\|_2^2,\n\\end{array}\n\\end{equation}\nwith variable $k\\in\\mathbb{R}^{n+1}$.\n\n\n```python\ntf.random.set_seed(1)\nk = tf.constant(tf.ones([n + 1], dtype=tf.float64))\nx_targ = tf.sort(tf.random.uniform([n], dtype=tf.float64))\nx_targ\n```\n\n\n\n\n \n\n\n\nWe can (approximately) solve this problem via gradient descent:\n\n\n```python\nx, = prob_tf(k)\nx_np = x.numpy()\n\nfig, ax = plt.subplots()\nax.set_xlim((0, 1))\nax.set_ylim((0, w*4))\nrects = []\nfor i in range(n):\n plt.axvline(x_targ[i].numpy(), c='k')\n rect = patches.Rectangle((x_np[i + 1] - w/2, 0), w, w, linewidth=1, edgecolor='k', facecolor='none')\n ax.add_patch(rect)\n rects.append(rect)\n\ndef animate(i):\n global k\n with tf.GradientTape() as tape:\n tape.watch(k)\n x, = prob_tf(k)\n loss = tf.reduce_sum((x[1:-1] - x_targ)**2)\n grad, = tape.gradient(loss, [k])\n k = k - .1 * grad\n k = tf.maximum(k, 0.0)\n for i in range(n):\n rects[i].xy = (x.numpy()[i + 1] - w/2, 0)\n return rects\n\nanim = animation.FuncAnimation(fig, animate,\n frames=300, interval=50, blit=True)\nanim\n```\n", "meta": {"hexsha": "b72bf624d82a5f616dfa431214a9a6be4b59b398", "size": 64658, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "examples/tf/optimizing_stiffness_constants.ipynb", "max_stars_repo_name": "RanganThaya/cvxpylayers", "max_stars_repo_head_hexsha": "483e9220ff34a8eea31d80f83a5cdc930925925d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1287, "max_stars_repo_stars_event_min_datetime": "2019-10-25T21:19:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T16:35:11.000Z", "max_issues_repo_path": "examples/tf/optimizing_stiffness_constants.ipynb", "max_issues_repo_name": "RanganThaya/cvxpylayers", "max_issues_repo_head_hexsha": "483e9220ff34a8eea31d80f83a5cdc930925925d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 100, "max_issues_repo_issues_event_min_datetime": "2019-10-28T15:38:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-18T14:23:16.000Z", "max_forks_repo_path": "examples/tf/optimizing_stiffness_constants.ipynb", "max_forks_repo_name": "RanganThaya/cvxpylayers", "max_forks_repo_head_hexsha": "483e9220ff34a8eea31d80f83a5cdc930925925d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 115, "max_forks_repo_forks_event_min_datetime": "2019-10-28T16:57:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T18:20:48.000Z", "avg_line_length": 81.7420986094, "max_line_length": 7700, "alphanum_fraction": 0.823270129, "converted": true, "num_tokens": 1123, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.956634196290671, "lm_q2_score": 0.8902942348544447, "lm_q1q2_score": 0.8516859098221996}} {"text": "# Lecture 5\n\nThis lecture covered linear difference equations (recurrence equations). Below one of the examples from the lecture is solved using SymPy.\n\n\n## Student grant example\n\nThe difference equation for the student grant example from the lecture notes has the form\n\n$$\ny_{n} - 2.95 y_{n-1} + 2 y_{n-2} = −(63.685)(1.07^{n})\n$$\n\nWe investigate and solve this equation using SymPy. As before, we first need to import SymPy. We will also import a `Fraction` object to represent fractions without Python evaluating fraction numerically.\n\n\n```\nfrom sympy import *\ninit_printing()\nfrom IPython.display import display\n\nfrom fractions import Fraction\n```\n\nWe now define $n$ as an integer symbol and $y$ as a function:\n\n\n```\nn = Symbol(\"n\", integer=True)\ny = Function(\"y\")\n```\n\nNow, we define the RHS of the difference equation:\n\n\n```\nf = y(n) - Fraction(295, 100)*y(n - 1) + 2*y(n - 2)\ndisplay(f)\n```\n\nWe'll now solve the homogeneous version of the equation using `rsolve`. To compare to the solution in the lecture notes, we'll also evaluate the the solution in floating point: \n\n\n```\neqn = Eq(f, 0)\nsoln = rsolve(eqn, y(n))\ndisplay(soln)\nsoln.evalf()\n```\n\nThe solution is the same as in the lecture notes.\n\nWe now consider the non-homogeneous case:\n\n\n```\n# Create non-homogeneous equation\neqn = Eq(f, -63.685*(1.07**n))\ndisplay(eqn)\n```\n\nWe now solve the non-homogeneous equation, on this occasion providing the initial conditions $y(0) = 2000$ and $y(1) = 2200$:\n\n\n```\nsoln = rsolve(eqn, y(n), init={y(0) : 2000, y(1) : 2200})\ndisplay(soln)\nsoln.evalf()\n```\n\n\n```\n# Plot\n%matplotlib inline\nplot(soln, (n, 0, 12), xlabel=\"year (n)\", ylabel=\"fee\")\n\n# Evaluate fee at 10 years\nprint(\"Fee after 10 years (n=10): {}\".format(soln.subs(n, 10).evalf()))\n```\n", "meta": {"hexsha": "2d5a2f05fa5023a5e611a4eb38946c2c01d29405", "size": 40545, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/Lecture5.ipynb", "max_stars_repo_name": "quang-ha/IA-maths-Ipython", "max_stars_repo_head_hexsha": "8ff8533d64a3d8db8e4813a7b6dfee39339fd846", "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": "notebooks/Lecture5.ipynb", "max_issues_repo_name": "quang-ha/IA-maths-Ipython", "max_issues_repo_head_hexsha": "8ff8533d64a3d8db8e4813a7b6dfee39339fd846", "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": "notebooks/Lecture5.ipynb", "max_forks_repo_name": "quang-ha/IA-maths-Ipython", "max_forks_repo_head_hexsha": "8ff8533d64a3d8db8e4813a7b6dfee39339fd846", "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": 145.845323741, "max_line_length": 13127, "alphanum_fraction": 0.8517449747, "converted": true, "num_tokens": 515, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088025362857, "lm_q2_score": 0.9173026550642019, "lm_q1q2_score": 0.8516318595515112}} {"text": "# Conditioning of evaluating tan()\n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as pt\n```\n\nLet us estimate the sensitivity of evaluating the $\\tan$ function:\n\n\n```python\nx = np.linspace(-5, 5, 1000)\npt.ylim([-10, 10])\npt.plot(x, np.tan(x))\n```\n\n\n```python\nx = np.pi/2 - 0.0001\n#x = 0.1\nx\n```\n\n\n```python\nnp.tan(x)\n```\n\n\n```python\ndx = 0.00005\nnp.tan(x+dx)\n```\n\n## Condition number estimates\n\n### From evaluation data\n\n\n\n```python\n\n```\n\n### Using the derivative estimate\n\n\n```python\nimport sympy as sp\n\nxsym = sp.Symbol(\"x\")\n\nf = sp.tan(xsym)\ndf = f.diff(xsym)\ndf\n```\n\nEvaluate the derivative estimate. Use `.subs(xsym, x)` to substitute in the value of `x`.\n\n\n```python\n\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "b22522da1a6e761f47883d4e0ea162e927a6af92", "size": 3404, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "cleared-demos/error_and_fp/Conditioning of Evaluating tan.ipynb", "max_stars_repo_name": "xywei/numerics-notes", "max_stars_repo_head_hexsha": "70e67e17d855b7bb06a0de7e3570d40ad50f941b", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 20, "max_stars_repo_stars_event_min_datetime": "2021-01-24T21:12:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-02T19:58:25.000Z", "max_issues_repo_path": "cleared-demos/error_and_fp/Conditioning of Evaluating tan.ipynb", "max_issues_repo_name": "xywei/numerics-notes", "max_issues_repo_head_hexsha": "70e67e17d855b7bb06a0de7e3570d40ad50f941b", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2021-08-24T17:48:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-14T21:22:02.000Z", "max_forks_repo_path": "cleared-demos/error_and_fp/Conditioning of Evaluating tan.ipynb", "max_forks_repo_name": "xywei/numerics-notes", "max_forks_repo_head_hexsha": "70e67e17d855b7bb06a0de7e3570d40ad50f941b", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2020-11-23T09:56:26.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-24T17:30:26.000Z", "avg_line_length": 19.7906976744, "max_line_length": 99, "alphanum_fraction": 0.4124559342, "converted": true, "num_tokens": 219, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768588653856, "lm_q2_score": 0.9019206745523101, "lm_q1q2_score": 0.8515726294445498}} {"text": "## Recap Matrix Multiplication\nProduces a matrix from two matrices\n\n\nThe number of columns in the first matrix (m) must be equal to the number of rows in the second matrix. The result matrix has the number of rows of the first (l) and the number of columns of the second matrix (n). \n\n\nIf $\\mathbf{A}$ is an $m \\times n$ matrix and $\\mathbf{B}$ is an $n \\times p$ matrix\n$$\n\\mathbf{A}=\\begin{pmatrix}\n a_{11} & a_{12} & \\cdots & a_{1n} \\\\\n a_{21} & a_{22} & \\cdots & a_{2n} \\\\\n\\vdots & \\vdots & \\ddots & \\vdots \\\\\n a_{m1} & a_{m2} & \\cdots & a_{mn} \\\\\n\\end{pmatrix},\\quad\\mathbf{B}=\\begin{pmatrix}\n b_{11} & b_{12} & \\cdots & b_{1p} \\\\\n b_{21} & b_{22} & \\cdots & b_{2p} \\\\\n\\vdots & \\vdots & \\ddots & \\vdots \\\\\n b_{n1} & b_{n2} & \\cdots & b_{np} \\\\\n\\end{pmatrix}\n$$\n\nthe matrix product $\\mathbf{C} = \\mathbf{AB}$ is defined to be the $m \\times p$\n\n$\\mathbf{C}=\\begin{pmatrix}\n c_{11} & c_{12} & \\cdots & c_{1p} \\\\\n c_{21} & c_{22} & \\cdots & c_{2p} \\\\\n\\vdots & \\vdots & \\ddots & \\vdots \\\\\n c_{m1} & c_{m2} & \\cdots & c_{mp} \\\\\n\\end{pmatrix}$\n\nsuch that \n$$c_{ij} = a_{i1}b_{1j} + a_{i2}b_{2j} +\\cdots + a_{in}b_{nj}= \\sum_{k=1}^n a_{ik}b_{kj} \\;\\;\\; \\text{for}\\ i = 1, ..., m\\ \\text{and}\\ j = 1, ..., p.$$\n\n\n\nThe corresponding operation on vectors is referred to as dot product or scalar product. If two vectors $\\mathbf{\\color{red}a} = \\left[\\color{red}a_\\color{red}1, \\color{red}a_\\color{red}2, ..., \\color{red}a_\\color{red}n\\right]$ and $\\mathbf{\\color{blue}b} = \\left[\\color{blue}b_\\color{blue}1, \\color{blue}b_\\color{blue}2, ..., \\color{blue}b_\\color{blue}n\\right]$\n\nare identified as row matrices:\n\n$$\\begin{align}\n\\mathbf{\\color{red}a} \\cdot \\mathbf{\\color{blue}b} &= \\mathbf{\\color{red}a}\\mathbf{\\color{blue}b}^\\top\\\\\n&=\\sum_{i=1}^n {\\color{red}a}_i{\\color{blue}b}_i\\\\\n&={\\color{red}a}_1{\\color{blue}b}_1+{\\color{red}a}_2{\\color{blue}b}_2+\\cdots+{\\color{red}a}_n{\\color{blue}b}_n \\\\\n\\end{align}$$\n\nSource: https://en.wikipedia.org/wiki/Matrix_multiplication and https://en.wikipedia.org/wiki/Dot_product\n\n\n```python\n\n```\n", "meta": {"hexsha": "08bec08f7a67a2ffdd5e4017d81ea6b37c010db5", "size": 3246, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "basic_math/mat_mult.ipynb", "max_stars_repo_name": "phonosync/fromscratch", "max_stars_repo_head_hexsha": "ab637c50caabca253cee7474c532511d33879cfd", "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": "basic_math/mat_mult.ipynb", "max_issues_repo_name": "phonosync/fromscratch", "max_issues_repo_head_hexsha": "ab637c50caabca253cee7474c532511d33879cfd", "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": "basic_math/mat_mult.ipynb", "max_forks_repo_name": "phonosync/fromscratch", "max_forks_repo_head_hexsha": "ab637c50caabca253cee7474c532511d33879cfd", "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.7441860465, "max_line_length": 390, "alphanum_fraction": 0.5166358595, "converted": true, "num_tokens": 814, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9702399069145609, "lm_q2_score": 0.8774767842777551, "lm_q1q2_score": 0.8513629934973374}} {"text": "# Lab 3\n## Introduction\nIn this lab we will analyse population dynamics under the logisitic model with managed harvesting.\n\nFirst import the modules we need.\n\n\n```python\nfrom plotly.figure_factory import create_quiver\nfrom plotly import graph_objs as go\nfrom numpy import meshgrid, arange, sqrt, linspace\nfrom scipy.integrate import odeint\n```\n\n## Harvesting of fish\nA population of fish in a lake, left to its own devices, is modelled by the logistic differential equation\n\\begin{align}\n\\frac{\\mathrm{d}y}{\\mathrm{d}{t}} = 4y(1-y),\n\\end{align}\nwhere the population $y$ is in units of thousands of fish and time $t$ is measured in years.\n\nFirst define a function for $\\mathrm{d}y/\\mathrm{d}x$ in terms of $y$ and $x$.\n\n\n```python\ndef diff_eq(y, x):\n return 4 * y * (1 - y)\n```\n\nNext define a function that creates a Plotly Figure object that contains a slope field and, optionally, a few solutions to initial value problems.\n\nIt automates a few things we did in the last lab.\n\n- `diff_eq` is the differential equation to be plotted\n- `x` and `y` should be outputs from `meshgrid`. \n- `args` is any additional arguments to `diff_eq` (we will use that below).\n- `initial_values` is a list (or array) of starting $y$ values from which approximate solutions will start. The corresponding $x$ value is the minimum element of `x`.\n\nNote that the numerical solutions will plotted for the whole range of $x$ values in `x`, so if they blow up you will probably get a warning and less-than-useful plot.\n\n\n```python\ndef create_slope_field(diff_eq, x, y, args=(), initial_values=()): \n S = diff_eq(y, x, *args)\n L = sqrt(1 + S**2)\n scale = 0.9*min(x[0][1]-x[0][0], y[1][0]-y[0][0]) # assume a regular grid\n fig = create_quiver(x, y, 1/L, S/L, scale=scale, arrow_scale=1e-16)\n fig.layout.update(yaxis=dict(scaleanchor='x',\n scaleratio=1,\n range=[y.min()-scale, y.max()+scale]),\n xaxis=dict(range=[x.min()-scale, x.max()+scale]),\n showlegend=False, width=500,\n height=0.8*(y.max()-y.min())/(x.max()-x.min())*500)\n x = linspace(x.min(), x.max())\n for y0 in initial_values:\n y = odeint(diff_eq, y0, x, args).flatten()\n fig.add_trace(go.Scatter(x=x, y=y))\n return fig\n```\n\nThe slope field below should hopefully give you some idea for the fish population dynamics.\n\nNote that we use `arange` rather than `linspace` this week so that we can carefully control the increments between our grid points. `arange(0, 1.1, 0.25)` returns an array that starts with 0 and increments by 0.25 until it exceeds 1.1.\n\nThe plot also contains the solution curves for \n$y(0) = 1$ and $y(0) = 0.4$. Edit the cell to also include the solution curve for $y(0)=1.4$.\n\n\n```python\nx, y = meshgrid(arange(0, 1.1, 0.1), arange(-0.4, 1.41, 0.05))\nfig = create_slope_field(diff_eq, x, y, initial_values=(0.4, 1, 1.4))\nfig.show('png')\n```\n\n### Equilibrium solutions\nLooking back to our differential equation, $\\mathrm{d}y/\\mathrm{d}t = 0$ when $y(t) = 0$ or $y(t) = 1$. Looking at the slope field, we see that the equilibrium solution $y(t) = 1$ is stable (this is the carrying capacity here, corresponding to 1000 fish), whereas the equilibrium solution $y(t) = 0$ is unstable. Any non-zero initial population will eventually stabilise at 1000 fish.\n\n### What will happen if harvesting is now commenced at a steady rate?\nFor the simplest harvesting model, assume that $H$ units (thousands) of fish are taken\ncontinuously (smoothly) over the year, rather than at one instant each year.\nNote that the units of $H$ are the same as those of $\\mathrm{d}y/\\mathrm{d}t$, thousands of fish per year, so we simply subtract $H$ from the RHS of our existing equation to give the DE with harvesting as\n\\begin{align}\n\\frac{\\mathrm{d}y}{\\mathrm{d}{t}} = 4y(1-y) - H.\n\\end{align}\nAgain, the (constant) equilibrium solutions are found by setting $\\mathrm{d}y/\\mathrm{d}t = 0$, giving from the quadratic formula (check this),\n\\begin{align}\ny(t) = \\frac{4\\pm\\sqrt{16-16H}}{8} = \\frac{1\\pm\\sqrt{1-H}}{2}.\n\\end{align}\nWhat happens after harvesting starts will depend on the equilibrium solutions, their\nstability and the initial number of fish $y(0)$.\n\nStart by redefining `diff_eq` to include the `H` parameter. Note that defining `diff_eq` again overides our original definition.\n\n\n```python\ndef diff_eq(y, x, H=0):\n return 4 * y * (1 - y) - H\n```\n\nNow set $H = 0.6$ and plot the slope field. This is done by setting `args=(0.6,)` when we call `create_slope_field`. This is exactly how you would pass additional arguments like this one to `odeint` if you were calling it directly.\n\n\n```python\nx, y = meshgrid(arange(0, 1.1, 0.1), arange(-0.4, 1.41, 0.1))\nfig = create_slope_field(diff_eq, x, y, args=(0.6,))\nfig.show('png')\n```\n\nFrom the solutions to the quadratic equation above, the equilibrium solutions of the DE are found to be $y(t) \\approx 0.184$ and $y(t) \\approx 0.816$. The previous equilibrium solution with no harvesting at $y(t) = 0$ has moved up to $y(t) \\approx 0.184$, while the previous equilibrium solution with no harvesting at $y(t) = 1$ has moved down to $y(t) \\approx 0.816$.\n\nFrom the slope field, we see that the equilibrium solution $y(t) \\approx 0.184$ is unstable, whereas the equilibrium solution $y(t) \\approx 0.816$ is stable. If the population ever falls below about 0.184, or 184 fish, it will then drop to 0. This is a new feature, introduced by harvesting.\n\nIn the cell below, use `create_slope_field` to experiment by plotting the solutions to the initial value problems $y(0)=0.183$ and $y(0)=0.25$. Extend the $x$ range of your slope field until the top line is close to equlibrium. Note that if you extend it too far you will break `odeint` (why?). You may also like to increase the increments in `arange` to make the plot clearer.\n\n\n```python\nx, y = meshgrid(arange(0, 1.1, 0.1), arange(-0.4, 1.41, 0.1))\nfig = create_slope_field(diff_eq, x, y, args=(0.6,), initial_values=(0.183, 0.25))\nfig.show('png')\n```\n\n## Exercises\n\nIn this lab you will experiment with the population dynamics given by the logistic equation with harvesting that we started analysing in the lab.\n\nThis week the questions will be a combination of plots and written answers.\n\n1. Assume that the harvest is 600 fish per year. **On the same figure,** \n a. plot the slope field, \n b. plot the equilibrium solutions that we found in above, and \n c. plot the solution curves for $y(0)=1$, $y(0)=0.3$, and $y(0)=0.15$.\n\n\n```python\nx, y = meshgrid(arange(0, 1.1, 0.1), arange(-0.4, 1.41, 0.1))\nfig = create_slope_field(diff_eq, x, y, args=(0.6,), initial_values=(0.183, 0.816, 1, 0.3, 0.15))\nfig.show('png')\n```\n\n1. d. In the cell below, describe the behaviour of the fish population for each of these five initial numbers of fish.\n\nAt the equilibrium points the fish population will stagnate and remain constant. At the starting point of 1 it will decline towards 0.816 and at 0.3 it will increase towards it. For 0.15 it will continue to decline until there are no fish left.\n\n2. a. i. Assume that $H=0.8$. Plot the slope field and five solutions, one for each equilibrium solution and one for each region between, above, or below them. You can use the equation from the lab to calculate the equilibrium solutions.\n\n\n```python\nx, y = meshgrid(arange(0, 1.1, 0.1), arange(-0.4, 1.41, 0.1))\nfig = create_slope_field(diff_eq, x, y, args=(0.8,), initial_values=(0.276, 0.724, 1, 0.4, 0.2))\nfig.show('png')\n```\n\n2. a. ii. In the cell below, describe the limiting behaviour of each line.\n\nAt the equilibrium points the fish population will stagnate and remain constant. At the starting point of 1 it will decline towards 0.724 and at 0.1 it will increase towards it. For 0.2 it will continue to decline until there are no fish left.\n\n2. b. i. Assume that $H=1$. Plot the slope field and three solutions for the equilibrium solution and the regions above and below it.\n\n\n```python\nx, y = meshgrid(arange(0, 1.1, 0.1), arange(-0.4, 1.41, 0.1))\nfig = create_slope_field(diff_eq, x, y, args=(1,), initial_values=(0.5, 0.8, 0.3))\nfig.show('png')\n```\n\n2. b. ii. Describe the limiting behaviour of each line.\n\nall values trend towards 0.5.\n\n2. c. i. Assume that 𝐻=1.2. Plot the slope field and two or three solutions.\n\n\n```python\nx, y = meshgrid(arange(0, 1.1, 0.1), arange(-0.4, 1.41, 0.1))\nfig = create_slope_field(diff_eq, x, y, args=(1.2,), initial_values=(0.5,))\nfig.show('png')\n```\n\n2. c. iii. Describe the limiting behaviour of the lines.\n\nregardless of input fish population tends towards extinction\n\n3. Summarize what happens to the equilibrium solutions and their stability as $H$\nis increased from 0 to beyond 1. Refer to your plots to support your answers.\n\nthe stable soultion, or the stable population number decreases and the unstable number increases until 1 where there is a single semi-stable soultion.\n\n4. What is a reasonable strategy for sustainable fishing in this case?\nDon’t forget to allow qualitatively for minor catastrophes, such as disease or temporary overfishing.\n\ndont allow for fishing above 1000 fish to keep the population at a stable rate, assuming it stated above 500 fish.\n\n\n```python\n\n```\n", "meta": {"hexsha": "d328bfdd936b2482ccf02130372f59140d4de7f6", "size": 296525, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/lab-03.ipynb", "max_stars_repo_name": "AF641/mm-labs", "max_stars_repo_head_hexsha": "6d92f89e6ac4009b5a531dbe3c449c776feb4dab", "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": "notebooks/lab-03.ipynb", "max_issues_repo_name": "AF641/mm-labs", "max_issues_repo_head_hexsha": "6d92f89e6ac4009b5a531dbe3c449c776feb4dab", "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": "notebooks/lab-03.ipynb", "max_forks_repo_name": "AF641/mm-labs", "max_forks_repo_head_hexsha": "6d92f89e6ac4009b5a531dbe3c449c776feb4dab", "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": 475.963081862, "max_line_length": 46721, "alphanum_fraction": 0.9459876908, "converted": true, "num_tokens": 2680, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009480320036, "lm_q2_score": 0.9304582574225517, "lm_q1q2_score": 0.8512771418200986}} {"text": "# Problem 3.6 Conditional Distribution\n\nShow that \n$$P_{C\\mid E=2}\\sim\\mathcal{N}\\left(\\frac{8}{17},\\frac{1}{17}\\right)$$\nfor the SCM\n\\begin{align}\nC:=&\\mathcal{N}(0,1)\\\\\nE:=&4C+\\mathcal{N}(0,1)\n\\end{align}\n\n## Proof\n\nThe SCM can be seen as a [multivariate normal distribution](https://en.wikipedia.org/wiki/Multivariate_normal_distribution)\n$$\nP\\left(\\begin{matrix}C\\\\E\\end{matrix}\\right)=\n\\mathcal{N}\\left(\\begin{bmatrix}\\mu_C\\\\\\mu_E\\end{bmatrix},\\Sigma\\right)\n$$\nwhere $\\mu_C=\\mu_E=0$ because both distributions have an expecation of zero and $\\Sigma$ is the covariance matrix which is\n\\begin{align}\n\\Sigma:=&\\begin{bmatrix}\\sigma^2_C&\\rho\\sigma_C\\sigma_E\\\\\\rho\\sigma_C\\sigma_E&\\sigma_C^2\\end{bmatrix}\\\\\n=&\\begin{bmatrix}1&14\\\\14&4^2+1\\end{bmatrix}\n\\end{align}\n\nFor the bivariate case the conditional distribution is defined as \n$${\\displaystyle X_{1}\\mid X_{2}=a\\ \\sim \\ {\\mathcal {N}}\\left(\\mu _{1}+{\\frac {\\sigma _{1}}{\\sigma _{2}}}\\rho (a-\\mu _{2}),\\,(1-\\rho ^{2})\\sigma _{1}^{2}\\right).}$$\n\nApplied to $C\\mid E=2$ that yields $$\\mathcal{N}\\left(\\frac{8}{17},\\frac{1}{17}\\right)$$\n", "meta": {"hexsha": "5327e3790928dccfd1dfd8bff782c8494d03cadf", "size": 2236, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "causal-inference/problems/problem-3.6-conditional-distribution.ipynb", "max_stars_repo_name": "Simsso/Machine-Learning-Tinkering", "max_stars_repo_head_hexsha": "0a024aab0bb1ac5fbdd2f77380ab36d192278701", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-02-19T16:30:04.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-13T02:22:29.000Z", "max_issues_repo_path": "causal-inference/problems/problem-3.6-conditional-distribution.ipynb", "max_issues_repo_name": "Simsso/Machine-Learning-Tinkering", "max_issues_repo_head_hexsha": "0a024aab0bb1ac5fbdd2f77380ab36d192278701", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2021-02-17T14:00:33.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-10T03:05:35.000Z", "max_forks_repo_path": "causal-inference/problems/problem-3.6-conditional-distribution.ipynb", "max_forks_repo_name": "Simsso/Machine-Learning-Tinkering", "max_forks_repo_head_hexsha": "0a024aab0bb1ac5fbdd2f77380ab36d192278701", "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.619047619, "max_line_length": 188, "alphanum_fraction": 0.5295169946, "converted": true, "num_tokens": 412, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9719924810166349, "lm_q2_score": 0.8757869997529962, "lm_q1q2_score": 0.8512583787320298}} {"text": "```\n%pylab inline\nimport numpy as np\n```\n\n# Using finite differences to approximate derivatives\n\nThe material in this notebook is a supplement to chapter 1 of the text.\n\nSuppose that you're given a table of values of some \"secret\" function $f(x)$, but you are not given the function itself. For example:\n\n\n```\nx_values = (0,1,2,3,4)\ny_values = (0,1,8,27,64)\n```\n\nIn order to understand the function that generated these values, we could plot them:\n\n\n```\nplt.plot(x_values,y_values,'-o')\n```\n\nIn the plot, the points have been connected by a line, and you might use the slope of this line if you wanted to estimate the derivative of the function. For instance, to estimate the slope at $x=2$, you could use the slope of the line between $x=2$ and $x=3$:\n\n\n```\nplt.plot(x_values,y_values,'-o')\nplt.hold(True)\nplt.plot(x_values[2:4],y_values[2:4],'-r',linewidth=5)\n```\n\n$$\\left. f'(x) \\right|_{x=2} \\approx \\frac{f(3)-f(2)}{3-2} = 19.$$\n\nAlternatively, you might use the slope of the line between $x=1$ and $x=2$:\n\n\n```\nplt.plot(x_values,y_values,'-o')\nplt.hold(True)\nplt.plot(x_values[1:3],y_values[1:3],'-r',linewidth=5)\n```\n\n$$\\left. f'(x) \\right|_{x=2} \\approx \\frac{f(2)-f(1)}{2-1} = 7.$$\n\nRemember that the derivative is defined as the limit of a formula rather like our first approximation above (referred to as a *forward difference*):\n\n$$ f'(x) = \\lim_{h\\to 0} \\frac{f(x+h)-f(x)}{(x+h)-x} = \\lim_{h\\to 0} \\frac{f(x+h)-f(x)}{h}.$$\n\nNotice that the fraction in the definition is just the slope of the line connecting the values of $f$ at $x$ and $x+h$. We could equally well define the derivative in terms of a *backward difference*, similar to our second formula above:\n\n$$ f'(x) = \\lim_{h\\to 0} \\frac{f(x)-f(x-h)}{x-(x-h)} = \\lim_{h\\to 0} \\frac{f(x)-f(x-h)}{h}.$$\n\nYet another way of defining the derivative would be to use the slope of the line connecting points $x+h$ and $x-h$, leading to\n\n$$ f'(x) = \\lim_{h \\to 0} \\frac{f(x+h) - f(x-h)}{2h}.$$\n\nHere the factor $2h$ in the denominator is just the length of the interval $(x-h,x+h)$. Using this formula with our values gives\n\n\n```\nplt.plot(x_values,y_values,'-ok')\nplt.hold(True)\nplt.plot((x_values[1],x_values[3]),(y_values[1],y_values[3]),'-r',linewidth=5)\n```\n\n$$\\left. f'(x) \\right|_{x=2} \\approx \\frac{f(3)-f(1)}{3-1} = 13.$$\n\nWhen we only know the values of a function at a finite set of points, we can't compute these limits, so it makes sense to use a finite value of $h$ in order to approximate the derivative. This approach is known as the *finite difference method*. Soon we will use it to solve differential equations, but first let's examine its effectiveness in approximating derivatives.\n\nYou may have guessed that the \"secret\" function that generated these values is $f(x)=x^3$. Let's compare our three estimates of the derivative with the true derivative: $f'(2) = 3\\cdot 2^2 = 12$. Clearly the third formula (known as a *centered difference*) is the best approximation. We can also see this by plotting the approximations and the tangent line (whose slope is that of the true derivative):\n\n\n```\ndef f(x):\n return x**3\n\nx = np.linspace(0,4)\ntangent = 8 + 12*(x-2)\nplot(x,f(x),'k',linewidth=2)\nplt.plot(x_values[2:4],y_values[2:4],'-g',linewidth=3)\nplt.plot(x_values[1:3],y_values[1:3],'-b',linewidth=3)\nplt.plot((x_values[1],x_values[3]),(y_values[1],y_values[3]),'-r',linewidth=3)\nplt.plot(x,tangent,'--k',linewidth=3)\nplt.legend(['f(x)','Forward','Backward','Centered','Tangent'],loc='best')\nplt.axis((0.5,3.5,0,40))\n```\n\nIt's clear that the centered difference approximation (slope of the red line) is closest to the derivative (slope of the dotted line). Would this be true if we picked another function $f(x)$, or if we used function values at different points? Let's answer the second question with an experiment.\n\n\n```\nx = 2.\ndf = 12.\n\nfor h in (0.1, 0.05, 0.025):\n forward = (f(x+h)-f(x))/h\n forward_error = forward - df\n print forward_error\n```\n\nIt seems clear from the results that reducing $h$ by a factor of two also reduces the error in the forward difference approximation by a factor of two.\n\n**Now add backward and centered difference approximations to the code above and try to figure out what happens to their errors as $h$ decreases. Make a table like Table 1.1 on page 5 of the textbook.** Is the centered difference always the most accurate? Do you think it will still be the most accurate if we continue reducing $h$?\n\n**Now redefine the function $f(x)$ to be $x^2$ and generate the same table. Do you see anything surprising? Can you explain it?** If not, make a guess.\n\n## Estimating truncation errors\n\nThe error made by a finite difference approximation is called *truncation error*. Why? Well, we can estimate the error by expanding each function value in a *Taylor series*:\n\n$$f(x+h) = f(x) + h f'(x) + \\frac{1}{2}h^2 f''(x) + \\frac{1}{6} h^3 f'''(x) + {\\mathcal O}(h^4)$$\n\nHere ${\\mathcal O}(h^4)$ indicates that the rest of the terms in the series vanish at least as quickly as $h^4$ when $h\\to 0$ (see Appendix A of the text).\nSubstituting this series in our forward difference formula gives\n\\begin{align}\n\\frac{f(x+h) - f(x)}{h} & = \\frac{f(x) + h f'(x) + \\frac{1}{2}h^2 f''(x) + \\frac{1}{6} h^3 f'''(x) + {\\mathcal O}(h^4) - f(x)}{h} \\\\\n& = f'(x) + \\frac{1}{2}h f''(x) + \\frac{1}{6} h^2 f'''(x) + {\\mathcal O}(h^3) \\\\\n& = f'(x) + \\frac{1}{2}h f''(x) + {\\mathcal O}(h^2).\n\\end{align}\n\nThis analysis confirms our intuition that the forward difference approximates $f'(x)$, but it tells us much more. Most importantly, it shows that the largest term in the error in this approximation is proportional to $h$. That's why we saw that decreasing $h$ by a factor of two caused the error to decrease by the same amount.\n\nNotice that if we truncated the Taylor series after the first term, we would get the forward difference formula exactly. That is why the error is referred to as *truncation error* -- it's the error we get from truncating an infinite series. The term $\\frac{1}{2} h f''(x)$ is referred to as the *leading truncation error* because when $h$ is very small we expect that term to be much bigger than all the ones that come after it.\n\nSince in our simple example we know the function $f(x)$, we could evaluate error terms in the series above to get a better approximation of the error. But typically we won't know what the function is (if we did, why would we need finite differences?), so we'll be most interested in knowing what power of $h$ multiplies the leading error term.\n\n**Write down the Taylor series for $f(x-h)$ about $x$. Use that (and the series above) to work out the leading truncation error terms for the backward and centered difference formulas.** Does your result for the centered formula allow you to explain the results you found before when applying it to $f(x)=x^2$?\n\n## Polynomial interpolation and finite difference formulas\n\nIn sections 1.2-1.5 of the text, a method for finding finite difference formulas is given, based on Taylor series. Here we will approach the same topic from a different route, using polynomial interpolation. The idea is this: to approximate the derivative of a function whose point values are known, we first find a polynomial that interpolates those values, then evaluate the derivative of that polynomial.\n\nTo begin, suppose we are given three function values: $f(x_0-h), f(x_0), f(x_0+h)$, which we'll denote by $(f_1,f_2,f_3)$. We wish to find a polynomial that passes through these three points. As you may know, a set of $n$ values uniquely defines a polynomial of degree $n-1$, so we will look for a quadratic polynomial. To make the computation simpler, we'll write it this way: $p(x) = a + b (x-x_0) + c (x-x_0)^2$. We know that $p$ and $f$ must agree at the three given points, which means\n\\begin{align}\na + b(-h) + c (-h)^2 & = f_1 \\\\\na + b(0) + c(0)^2 & = f_2 \\\\\na + b (h) + c (h)^2 & = f_3 \\\\\n\\end{align}\n\nor simply\n\n\\begin{align}\na - hb + h^2c & = f_1 \\\\\na & = f_2 \\\\\na + hb + h^2c & = f_3 \\\\\n\\end{align}\n\nWe can rewrite this system of equations in matrix form:\n\n\\begin{align}\n\\begin{pmatrix}\n1 & -h & h^2 \\\\\n1 & 0 & 0 \\\\\n1 & h & h^2 \\\\\n\\end{pmatrix}\n\\begin{pmatrix} a \\\\ b \\\\ c \\end{pmatrix}\n& = \\begin{pmatrix} f_1 \\\\ f_2 \\\\ f_3 \\end{pmatrix}\n\\end{align}\n\nThis is a linear system that we can solve for the coefficients $a,b,c$ in terms of $h$, and the values of $f$. The result is\n\n\\begin{align}\na & = f_2, & b & = \\frac{f_3-f_1}{2h}, & c & = \\frac{f_1 -2 f_2 + f_3}{2h^2}.\n\\end{align}\n\nThus\n\n\\begin{align}\np(x) = f_2 + \\frac{x-x_0}{2h}(f_3-f_1) + \\frac{(x-x_0)^2}{2h^2}(f_1-2f_2+f_3).\n\\end{align}\n\nNow suppose we wish to approximate the derivative of $f$. We have an easy approach: use the derivative of $p$:\n\n\\begin{align}\np'(x) = \\frac{f_3-f_1}{2h} + \\frac{x-x_0}{h^2}(f_1 -2 f_2 + f_3).\n\\end{align}\n\nIn particular, if want to approximate the derivative at $x=x_0$, we get simply\n\n$$f'(x) \\approx p'(x_0) = \\frac{f_3-f_1}{2h} = \\frac{f(x_0+h) - f(x_0-h)}{2h}.$$\n\n**Do you recognize this approximation? Now use $p(x)$ to get an approximation for the second derivative of $f(x)$. Write down the resulting formula.**\n\n\nDerive a formula for $f''(x)$ based on the values $f(x), f(x-h), f(x-3h)$ by determining the interpolating polynomial and differentiating it. How accurate is your formula?\n\n\n**Can you think of a similar approach that would allow you to derive rules for numerical quadrature (integration)?**\n\n\n```\n\n```\n", "meta": {"hexsha": "a43c1de8e9988eb630540e7a355f560a782afd23", "size": 14298, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "ipython/Week_1_Finite_differences.ipynb", "max_stars_repo_name": "bfdeandrade/Finite-Difference", "max_stars_repo_head_hexsha": "97e93f394051a70b6aa2c26fa266952ae821deb2", "max_stars_repo_licenses": ["CC-BY-2.0"], "max_stars_count": 28, "max_stars_repo_stars_event_min_datetime": "2015-02-05T23:13:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-05T03:09:04.000Z", "max_issues_repo_path": "ipython/Week_1_Finite_differences.ipynb", "max_issues_repo_name": "MuriloHMoreira/finite-difference-course", "max_issues_repo_head_hexsha": "97e93f394051a70b6aa2c26fa266952ae821deb2", "max_issues_repo_licenses": ["CC-BY-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/Week_1_Finite_differences.ipynb", "max_forks_repo_name": "MuriloHMoreira/finite-difference-course", "max_forks_repo_head_hexsha": "97e93f394051a70b6aa2c26fa266952ae821deb2", "max_forks_repo_licenses": ["CC-BY-2.0"], "max_forks_count": 13, "max_forks_repo_forks_event_min_datetime": "2015-02-16T17:36:38.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-11T07:13:03.000Z", "avg_line_length": 39.8272980501, "max_line_length": 505, "alphanum_fraction": 0.5542033851, "converted": true, "num_tokens": 2936, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122113355091, "lm_q2_score": 0.9381240090865197, "lm_q1q2_score": 0.8511713691912234}} {"text": "## Higher Order Integration Schemes\n\nThe composite trapezoidal rule is functional, but not all that accurate. At this point, the only method we have to improve accuracy is to divide the interval into smaller segments. We can, however, use results for different step sizes $h$ to improve both results by eliminating the lowest order error. To illustrate, consider the trapezoidal rule for a step $h_1=(b-a)$ and then $h_2=(b-a)/2$, \n\n$$\n\\begin{align}\nI_1 &=\\int_a^b f(x) dx = \\frac{h_1}{2}\\left[f(a)+f(b)\\right] - (b-a)\\frac{h_1^2}{12} f''(\\eta_1),\\\\\nI_2 &=\\int_a^b f(x) dx = \\frac{h_2}{2}\\left[f(a)+2f(a+h)+f(b)\\right] - (b-a)\\frac{h_2^2}{12} f''(\\eta_2).\n\\end{align}\n$$\n\nThe problem with attempting to use these two equations to eliminate the error term lies in the fact that $\\eta_1$ and $\\eta_2$ are not likely to be the same. However, it is possible to show that, for a suitably smooth function, the error term can be replaced by a power series om even powers of $h$, namely\n\n$$\nE(h) = - (b-a)\\frac{h^2}{12} f''(\\eta_1) = \\sum_{j=1}^n K_j h^{2j} + \\mathcal{O}(h^{2n+2}),\n$$\n\nwhere the $K_j$ are constants, independent of the division $h$. Using this, and $h_2=h_1/2$ we can rewrite the two trapezoidal methods above as\n\n$$\n\\begin{align}\nI_1 &= \\frac{h_1}{2}\\left[f(a)+f(b)\\right] + K_1 h_1^2 + K_2 h_1^4+ \\mathcal{O}(h_1^6),\\\\\nI_2 &= \\frac{h_2}{2}\\left[f(a)+2f(a+h_2)+f(b)\\right] + K_1 h_2^2 + K_2 h_2^4 + \\mathcal{O}(h_2^6),\\\\\n&= \\frac{h_1}{4}\\left[f(a)+2f(a+h_2)+f(b)\\right] + K_1 \\frac{h_1^2}{4} + K_2 h_2^4+\\mathcal{O}(h_1^6).\n\\end{align}\n$$\n\nNow note that\n\n$$\n\\int_a^b f(x) dx=\\frac{4 I_2 - I_1}{3} = \\frac{h_2}{3}\\left[f(a) + 4 f(a+h_2) + f(b) \\right] - \\frac{12}{3} K_2 h_2^4 + \\mathcal{O}(h_2^6).\n$$\n\nThe resulting numerical integration scheme is known as *Simpson's Rule* and the error is now $\\mathcal{O}(h^4)$ rather than the $\\mathcal{O}(h^2)$ for the (composite) trapezoidal rule.\n\nThis technique of eliminating error terms using results from two step sizes is generally referred to as Richardson's extrapolation. We can also use this method to get rid of higher order error terms as well which brings us to *Romberg's Method*.\n\n## Romberg's Method\n\nWe start by using the composite trapezoidal rule for $m_1=1,\\, m_2=2,\\, m_3=4,\\,\\cdots m_n=2^{n-1}$ subintervals with regularly spaced points $h_k=\\frac{b-a}{m_k}$ apart. In particular, when we do this we don't want to recompute $f(x)$ any more than necessary so we need to write the trapezoidal rule for the different intervals in such a way that we use our previous work:\n\n$$\n\\begin{align}\nR_{1,1} &= \\frac{h_1}{2}\\left[f(a)+f(b)\\right],\\\\\nR_{2,1} &= \\frac{h_2}{2}\\left[f(a)+f(b) + 2 f(a+h_2)\\right],\\\\\n&= \\frac{1}{2}\\left[ \\frac{h_1}{2}\\left\\{ f(a)+f(b)\\right\\} + 2h_2 f(a+h_2)\\right],\\\\\n&= \\frac{1}{2}\\left[ R_{1,1} + h_1 f(a+h_2)\\right],\\\\\nR_{3,1} &= \\frac{h_3}{2}\\left[f(a)+f(b) + 2\\left\\{f(a+h_3)+f(a+2 h_3) + f(a+3 h_r)\\right\\}\\right],\\\\\n&= \\frac{1}{2}\\left[ R_{2,1} + h_2 \\left\\{ f(a+h_3)+ f(a+3 h_r)\\right\\}\\right],\\\\\n&\\vdots \\\\\nR_{k,1} &= \\frac{1}{2}\\left[ R_{k-1,1}+h_{k-1} \\sum_{i=1}^{2^{k-2}} f(a+(2i-1)h_k) \\right].\n\\end{align}\n$$\n\nWe now apply the extrapolation technique to refine our results using\n\n$$\nR_{k,2}=\\frac{4 R_{k,1}-R_{k-1,1}}{3},\n$$\n\non each successive pair of our previous results.\n\nWe then apply the extrapolation technique to successivly higher orders using\n\n$$\nR_{i,j} = \\frac{4^{j-1}R_{i,j-1}-R_{i-1,j-1}}{4^{j-1}-1},\\qquad j=2,3,\\cdots,n.\n$$\n\n\n**Example** Suppose we want to compute $\\int_0^\\pi \\sin x\\, dx$ (which in this case we know is $2$). We construct the following tableau: \n\n$$\n\\begin{align}\n{\\begin{array}{ccccccc}\n R_{1,1} & & & & & &\\\\\n \\downarrow & \\rangle & R_{2,2} & & & &\\\\\n R_{2,1} & & & \\rangle & R_{3,3} & &\\\\\n \\downarrow & \\rangle & R_{3,2} & & & \\rangle & R_{4,4}\\\\\n R_{3,1} & & & \\rangle & R_{4,3} & &\\\\\n \\downarrow & \\rangle & R_{4,2} & & & &\\\\\n R_{4,1} & & & & &\\\\\n \\end{array} } \n\\end{align}\n$$\n\nWith actual numbers, this translates to\n\n\n$$\n\\begin{align}\n{\\begin{array}{ccccccc}\n 0 & & & & & &\\\\\n \\downarrow & \\rangle & 2.094... & & & &\\\\\n 1.57079... & & & \\rangle & 1.9985... & &\\\\\n \\downarrow & \\rangle & 2.0045... & & & \\rangle & 2.0000055...\\\\\n 1.896... & & & \\rangle & 1.999983... & &\\\\\n \\downarrow & \\rangle & 2.00026... & & & &\\\\\n 1.974... & & & & &\\\\\n \\end{array} } \n\\end{align}\n$$\n\nWe see that even though the underlying composite trapezoidal rule results in the first column are not all that accurate, extrapolation of those results to the fourth column gives six digits of accuracy. It should also be clear that we can get an estimate for our (forward) error by comparing the difference between our best two results, in this case $R_{4,4}$ and $R_{4,3}$ where $|R_{4,4}-R_{4,3}|\\sim 2\\times 10^{-5}$. Here, this is the error in $R_{4,3}$ and so an overestimate of the error for $R_{4,4}$. \n\nWhile these are fairly easy to code up yourself, there are also scipy versions of all of these integration routines as illustrated below where we use the various schemes to integrate $\\frac{1}{\\sqrt{\\pi}}e^{-x^2}$ from $0$ to $2$. We start with the results of the cumulative trapezoidal and cumulative Simpson's rule with our interval divided into eight segments:\n\n\n```python\nimport numpy as np\n\ndef f(x):\n return 1/np.sqrt(np.pi) * np.exp(-x**2)\n\nx = np.linspace(0, 2, num=9, endpoint=True)\nprint(\"sample points: \",x)\n\ny = f(x)\nfrom scipy import integrate\nI1 = integrate.trapezoid(y, x)\nI2 = integrate.simpson(y, x)\nprint(\"trapezoidal = \",I1, \", Simpsons = \",I2)\n```\n\n sample points: [0. 0.25 0.5 0.75 1. 1.25 1.5 1.75 2. ]\n trapezoidal = 0.49744809484415425 , Simpsons = 0.4976521729751664\n\n\nThe accuracy of these results is difficult to judge, other than by comparing them which gives us an estimate for the trapezoidal rule. In contrast, the Romberg integration keeps adding a row to the tableau until the results converge:\n\n\n```python\nfrom scipy import integrate\n\nnormaldist = lambda x: 1/np.sqrt(np.pi) * np.exp(-x**2)\nresult = integrate.romberg(normaldist, 0, 2, show=True)\n```\n\n Romberg integration of .vfunc at 0x0000020286FC9AF0> from [0, 2]\n \n Steps StepSize Results\n 1 2.000000 0.574523 \n 2 1.000000 0.494815 0.468246 \n 4 0.500000 0.496836 0.497509 0.499460 \n 8 0.250000 0.497448 0.497652 0.497662 0.497633 \n 16 0.125000 0.497607 0.497661 0.497661 0.497661 0.497661 \n 32 0.062500 0.497648 0.497661 0.497661 0.497661 0.497661 0.497661 \n 64 0.031250 0.497658 0.497661 0.497661 0.497661 0.497661 0.497661 0.497661 \n \n The final result is 0.4976611325094085 after 65 function evaluations.\n\n\nOur previous results from the trapezoidal and Simpson's rule correspond to the first two results in the fourth row. \n\n\n```python\n\n```\n", "meta": {"hexsha": "a9c268f9cf7ec3b3d1bd1cab42a467e4655c5ee3", "size": 10012, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "class/NDiffInt/HigherOrderInt.ipynb", "max_stars_repo_name": "CDenniston/NumericalAnalysis", "max_stars_repo_head_hexsha": "8f4ccaa864461c36e269824a0e9038bc14ef10b1", "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": "class/NDiffInt/HigherOrderInt.ipynb", "max_issues_repo_name": "CDenniston/NumericalAnalysis", "max_issues_repo_head_hexsha": "8f4ccaa864461c36e269824a0e9038bc14ef10b1", "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": "class/NDiffInt/HigherOrderInt.ipynb", "max_forks_repo_name": "CDenniston/NumericalAnalysis", "max_forks_repo_head_hexsha": "8f4ccaa864461c36e269824a0e9038bc14ef10b1", "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.4977777778, "max_line_length": 524, "alphanum_fraction": 0.5316620056, "converted": true, "num_tokens": 2642, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976953003183443, "lm_q2_score": 0.9481545364633622, "lm_q1q2_score": 0.8511538713586785}} {"text": "dS/dt=-bSI+gI, dI/dt=bSI-gI (uso b para beta y g para gamma)\n\n\n```python\nfrom sympy import *\nfrom sympy.abc import S,I,t,b,g\n```\n\n\n```python\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom scipy.integrate import odeint\nimport pylab as pl\n```\n\n\n```python\n#puntos criticos\nP=-b*S*I+g*I\nQ=b*S*I-g*I\n#establecer P(S,I)=0 y Q(S,I)=0\nPeqn=Eq(P,0)\nQeqn=Eq(Q,0)\nprint(solve((Peqn,Qeqn),S,I))\n#matriz Jacobiana\nJ11=diff(P,S)\nJ12=diff(P,I)\nJ21=diff(Q,S)\nJ22=diff(Q,I)\nJ=Matrix([[J11,J12],[J21,J22]])\npprint(J)\n```\n\n [(S, 0), (g/b, I)]\n ⎡-I⋅b -S⋅b + g⎤\n ⎢ ⎥\n ⎣I⋅b S⋅b - g ⎦\n\n\n\n```python\n#J en el punto critico\nJc1=J.subs([(S,S),(I,0)])\npprint(Jc1)\npprint(Jc1.eigenvals())\npprint(Jc1.eigenvects())\nJc2=J.subs([(S,g/b),(I,I)])\npprint(Jc2)\npprint(Jc2.eigenvals())\npprint(Jc2.eigenvects())\n```\n\n ⎡0 -S⋅b + g⎤\n ⎢ ⎥\n ⎣0 S⋅b - g ⎦\n {0: 1, S⋅b - g: 1}\n ⎡⎛ ⎡⎡1⎤⎤⎞ ⎛ ⎡⎡-1⎤⎤⎞⎤\n ⎢⎜0, 1, ⎢⎢ ⎥⎥⎟, ⎜S⋅b - g, 1, ⎢⎢ ⎥⎥⎟⎥\n ⎣⎝ ⎣⎣0⎦⎦⎠ ⎝ ⎣⎣1 ⎦⎦⎠⎦\n ⎡-I⋅b 0⎤\n ⎢ ⎥\n ⎣I⋅b 0⎦\n {0: 1, -I⋅b: 1}\n ⎡⎛ ⎡⎡0⎤⎤⎞ ⎛ ⎡⎡-1⎤⎤⎞⎤\n ⎢⎜0, 1, ⎢⎢ ⎥⎥⎟, ⎜-I⋅b, 1, ⎢⎢ ⎥⎥⎟⎥\n ⎣⎝ ⎣⎣1⎦⎦⎠ ⎝ ⎣⎣1 ⎦⎦⎠⎦\n\n\nLos puntos criticos son no hiperbolicos, por lo que no cumplen el teorema de Hartmann.\n\n\n```python\nb=1\ng=1\ndef dx_dt(x,t):\n return [ -b*x[0]*x[1]+g*x[1] , b*x[0]*x[1]-g*x[1] ]\n#trayectorias en tiempo hacia adelante\nts=np.linspace(0,10,500)\nic=np.linspace(20000,100000,3)\nfor r in ic:\n for s in ic:\n x0=[r,s]\n xs=odeint(dx_dt,x0,ts)\n plt.plot(xs[:,0],xs[:,1],\"-\", color=\"orangered\", lw=1.5)\n#trayectorias en tiempo hacia atras\nts=np.linspace(0,-10,500)\nic=np.linspace(20000,100000,3)\nfor r in ic:\n for s in ic:\n x0=[r,s]\n xs=odeint(dx_dt,x0,ts)\n plt.plot(xs[:,0],xs[:,1],\"-\", color=\"orangered\", lw=1.5)\n#etiquetas de ejes y estilo de letra\nplt.xlabel('S',fontsize=20)\nplt.ylabel('I',fontsize=20)\nplt.tick_params(labelsize=12)\nplt.ticklabel_format(style=\"sci\", scilimits=(0,0))\nplt.xlim(0,100000)\nplt.ylim(0,100000)\n#campo vectorial\nX,Y=np.mgrid[0:100000:15j,0:100000:15j]\nu=-b*X*Y+g*Y\nv=b*X*Y-g*Y\npl.quiver(X,Y,u,v,color='dimgray')\nplt.savefig(\"SISinf.pdf\",bbox_inches='tight')\nplt.show()\n```\n\nAnalsis de Bifurcaciones\n\nEl sistema tiene dos puntos criticos, (S,0) y (gamma/beta,I), el primer punto no depende de gamma ni beta, por lo que no cambia. \n", "meta": {"hexsha": "7b8e4df39365f42abffa4d26fc6285acd72ca5c8", "size": 138843, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "ModeloSIS(infeccioso).ipynb", "max_stars_repo_name": "deleonja/dynamical-sys", "max_stars_repo_head_hexsha": "024acc61a4e36d46b1502ce0391707e4afbc58e2", "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": "ModeloSIS(infeccioso).ipynb", "max_issues_repo_name": "deleonja/dynamical-sys", "max_issues_repo_head_hexsha": "024acc61a4e36d46b1502ce0391707e4afbc58e2", "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": "ModeloSIS(infeccioso).ipynb", "max_forks_repo_name": "deleonja/dynamical-sys", "max_forks_repo_head_hexsha": "024acc61a4e36d46b1502ce0391707e4afbc58e2", "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": 687.3415841584, "max_line_length": 83734, "alphanum_fraction": 0.7797296227, "converted": true, "num_tokens": 1253, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545362802363, "lm_q2_score": 0.8976952818435994, "lm_q1q2_score": 0.851153853677374}} {"text": "I assume Spong angles are $\\theta_1$ and $\\theta_2$.\n\n\n```python\nfrom __future__ import print_function, division\nfrom sympy import *\ninit_printing(use_unicode=True)\n```\n\n\n```python\nm1, l1, lc1, I1, theta1, theta1dot = symbols('m1 l1 l_{c1} I1 theta1 thetadot1')\nm2, lc2, I2, theta2, theta2dot = symbols('m2 l_{c2} I2 theta2 thetadot2')\n```\n\n\n```python\nM = Matrix([[m2*l1*(l1+2*lc2*cos(theta2))+I1+I2,\n m2*l1*lc2*cos(theta2)+I2],\n [m2*l1*lc2*cos(theta2)+I2,\n I2]])\n```\n\n\n```python\nM\n```\n\n\n```python\nC = Matrix([[-2*m2*l1*lc2*sin(theta2)*theta2dot,\n -m2*l1*lc2*sin(theta2)*theta2dot],\n [m2*l1*lc2*sin(theta2)*theta1dot,\n 0]])\n```\n\n\n```python\nC\n```\n\n\n```python\ng = symbols('g')\nG = g*Matrix([[-m1*lc1*sin(theta1)-m2*(l1*sin(theta1)+lc2*sin(theta1+theta2))],\n [-m2*lc2*sin(theta1+theta2)]])\n```\n\n\n```python\nG\n```\n\nNow, let's change the notations to the one that Russ used [here](http://underactuated.csail.mit.edu/underactuated.html?chapter=acrobot) by having ${}^{\\texttt{Russ}}I={}^{\\texttt{Spong}}I+ml_c^2$ and ${}^{\\texttt{Russ}}\\theta_1={}^{\\texttt{Spong}}\\theta_1+\\pi/2$\n\n\n```python\nq1, q1dot = symbols('q1 q1dot')\nq2, q2dot = symbols('q2 q2dot')\n```\n\n\n```python\nM.subs([(I1,I1+m1*lc1**2), (I2,I2+m2*lc2**2), \n (theta1,q1+pi/2), (theta2,q2)])\n```\n\n\n```python\nC.subs([(I1,I1+m1*lc1**2), (I2,I2+m2*lc2**2),\n (theta1,q1+pi/2), (theta2,q2)])\n```\n\n\n```python\nG.subs([(I1,I1+m1*lc1**2), (I2,I2+m2*lc2**2),\n (theta1,q1+pi/2), (theta2,q2)])\n```\n", "meta": {"hexsha": "ea8bcf62fb5badb9e105f924415fa803be9fe695", "size": 3587, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "src/2.1_LQR/Spong-Russ-equivalence.ipynb", "max_stars_repo_name": "atabakd/MuJoCo-Tutorials", "max_stars_repo_head_hexsha": "d6b86726ca9f01e682a45c4de7c11761ec326d38", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 25, "max_stars_repo_stars_event_min_datetime": "2018-09-27T14:04:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T21:58:54.000Z", "max_issues_repo_path": "src/2.1_LQR/Spong-Russ-equivalence.ipynb", "max_issues_repo_name": "atabakd/MuJoCo-Tutorials", "max_issues_repo_head_hexsha": "d6b86726ca9f01e682a45c4de7c11761ec326d38", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2019-02-18T03:26:38.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-22T20:23:16.000Z", "max_forks_repo_path": "src/2.1_LQR/Spong-Russ-equivalence.ipynb", "max_forks_repo_name": "atabakd/MuJoCo-Tutorials", "max_forks_repo_head_hexsha": "d6b86726ca9f01e682a45c4de7c11761ec326d38", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2018-10-03T14:20:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-24T08:32:30.000Z", "avg_line_length": 22.0061349693, "max_line_length": 275, "alphanum_fraction": 0.4959576248, "converted": true, "num_tokens": 624, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693702514737, "lm_q2_score": 0.8962513752119936, "lm_q1q2_score": 0.8511424790845912}} {"text": "# 3.2 Linear Regression Models and Least Squares\n\nWe have an input vector $X^T=(X_1,...,X_p)$ and want to predict a real-valued output $Y$.The linear regression model has the form:\n\n$$f(X) = B_0 + \\sum_{j=1}^p {X_j\\beta_j}$$\n\n Typically we have a set of training data $(x_1, y_1)...(x_N, y_n)$ from which to estimate the parameters $\\beta$. The most popular estimation method is *least squares*, in which we pick $\\beta$ to minimize the residual sum of squares, (3.2):\n$$ \n\\begin{align}\nRSS(\\beta)&=\\sum_{i=1}^N(y_i-f(x_i))\\\\\n&=\\sum_{i=1}^N(y_i-\\beta_0-\\sum_{j=1}^p{x_{ij}\\beta_j})^2\n\\end{align}\n$$\n\nHow do we minimize (3.2)? We can write the (3.2) using matrix, (3.3):\n$$RSS(\\beta)=(\\mathbf{y}-\\mathbf{X}\\beta)^T(\\mathbf{y}-\\mathbf{X}\\beta)$$\n\nDifferentiating with respect to $\\beta$ we obtain:\n$$\n\\begin{align}\n\\frac{\\partial{RSS}}{\\partial\\beta} = -2\\mathbf{X}^T(\\mathbf{y}-\\mathbf{X}\\beta)\n\\end{align}\n$$\n\nAssuming that **X** has full column rank, and hence the second derivative is positive definite:\n$$\\mathbf{X}^T(\\mathbf{y}-\\mathbf{X}\\beta)=0$$\n\nand the unique solution is:\n$$\\hat{\\beta}=(\\mathbf{X}^T\\mathbf{X})^{-1}\\mathbf{X}^T\\mathbf{y}$$\n\nThe predicted value at an input vector $x_0$ are given by $\\hat{f}(x_0)=(1:x_0)^T\\hat{\\beta}$:\n\n$$\\hat{y}=\\mathbf{X}\\hat{\\beta}=\\mathbf{X}(\\mathbf{X}^T\\mathbf{X})^{-1}\\mathbf{X}^T\\mathbf{y}$$\n\nThe matrix $\\mathbf{H}=\\mathbf{X}(\\mathbf{X}^T\\mathbf{X})^{-1}\\mathbf{X}^T$ is sometimes called the \"hat\" matrix.\n\n**Geometrical representation of the least squares:** We denote the column vectors of **X** by $x_0, x_1, ..., x_p$. These vectors span a subspace of $\\mathcal{R}^N$, also referred as the column space of **X**. We minimize $RSS(\\beta)=||\\mathbf{y}-\\mathbf{X}\\beta||^2$ by choosing $\\hat{\\beta}$ so that the residual vector $\\mathbf{y} - \\hat{\\mathbf{y}}$ is orthogonal to this subspace and the orthogonality is expressed by $\\mathbf{X}^T(\\mathbf{y}-\\mathbf{X}\\beta)=0$. The hat matrix **H** is the projection matrix.\n\n\n\n**Sampling properties of $\\hat{\\beta}$**: In order to pin down the sampling properties of $\\hat{\\beta}$, we assume that the observations $y_i$ are uncorrelated and have constant variance $\\sigma^2$, and that the $x_i$ are fixed. The variance-covariance matrix is given by (3.8):\n\n$$\n\\begin{align}\nVar(\\hat{\\beta}) &= E\\left[(\\hat{\\beta}-E(\\hat{\\beta}))(\\hat{\\beta}-E(\\hat{\\beta})^T)\\right]\\\\\n&= E\\left[(\\mathbf{X}^T\\mathbf{X})^{-1}\\mathbf{X}^T\\mathbf{\\varepsilon}\\mathbf{\\varepsilon}^T\\mathbf{X}(\\mathbf{X}^T\\mathbf{X})^{-1}\\right]\\\\\n&= \\sigma^2(\\mathbf{X}^T\\mathbf{X})^{-1}\n\\end{align}\n$$\n\nOne estimates the variance $\\sigma^2$ by:\n$$\n\\hat{\\sigma}^2 = \\frac{1}{N-p-1} \\sum_{i=1}^N(y_i-\\hat{y_i})^2\n$$\n\nThe N-p-1 rather than N in the denominator makes $\\hat{\\sigma}^2$ an unbiased estimate of $\\sigma^2$: $E(\\hat{\\sigma}^2)=\\sigma^2$.\n\n*Proof*:\n$$\n\\begin{align}\n\\hat{\\varepsilon} &= \\mathbf{y} - \\mathbf{\\hat{y}}\\\\\n&= \\mathbf{X}\\beta + \\varepsilon - \\mathbf{X}\\hat{\\beta}\\\\\n&= \\mathbf{X}\\beta + \\varepsilon - \\mathbf{X}(\\mathbf{X}^T\\mathbf{X})^{-1}\\mathbf{X}^T(\\mathbf{X}\\beta + \\varepsilon)\\\\\n&= \\varepsilon - \\mathbf{X}(\\mathbf{X}^T\\mathbf{X})^{-1}\\mathbf{X}^T\\varepsilon\\\\\n&= (\\mathbf{I}_n - \\mathbf{X}(\\mathbf{X}^T\\mathbf{X})^{-1}\\mathbf{X}^T)\\varepsilon\\\\\n&= (\\mathbf{I}_n - \\mathbf{H})\\varepsilon\n\\end{align}\n$$\n\nand we would like to find $Var(\\hat{\\varepsilon})=E(\\hat{\\varepsilon}^T\\hat{\\varepsilon})$:\n\n$$\n\\begin{align}\nE[\\hat{\\varepsilon}^T\\hat{\\varepsilon}] \n&= E\\left[\\varepsilon^T(\\mathbf{I}_n - \\mathbf{H})^T(\\mathbf{I}_n - \\mathbf{H})\\varepsilon\\right]\\\\\n&= E\\left[tr(\\varepsilon^T(\\mathbf{I}_n - \\mathbf{H})^T(\\mathbf{I}_n - \\mathbf{H})\\varepsilon)\\right]\\\\\n&= E\\left[tr(\\varepsilon\\varepsilon^T(\\mathbf{I}_n - \\mathbf{H})^T(\\mathbf{I}_n - \\mathbf{H}))\\right]\\\\\n&= \\sigma^2E\\left[tr((\\mathbf{I}_n - \\mathbf{H})^T(\\mathbf{I}_n - \\mathbf{H}))\\right]\\\\\n&= \\sigma^2E\\left[tr(\\mathbf{I}_n - \\mathbf{H})\\right]\\\\\n&= \\sigma^2E\\left[tr(\\mathbf{I}_n) - tr(\\mathbf{I}_{p+1})\\right]\\\\\n&= \\sigma^2(n-p-1)\n\\end{align}\n$$\n\nNote that, both $\\mathbf{H}$ and $\\mathbf{I_n}-\\mathbf{H}$ are:\n\n- Symmetry matrix, i.e $\\mathbf{H}^T=\\mathbf{H}$\n\n- Idempotent matrix, i.e $\\mathbf{H}^2=\\mathbf{H}$ \n\n\n**Inferences about the parameters and the model:** We now assume that deviations of Y around its expectations and Gaussian. Hence (3.9):\n\n$$\n\\begin{align}\nY &=E(Y|X_1,...,X_p)+\\varepsilon\\\\\n&= \\beta_0 + \\sum_{j=1}^P{X_j\\beta_j} + \\varepsilon\n\\end{align}\n$$\n\nwhere $\\varepsilon \\sim N(0, \\sigma^2) $\n\nUnder (3.9), it is easy to show that (3.10):\n$$\n\\hat{\\beta} \\sim N(\\beta, (\\mathbf{X}^T\\mathbf{X})^{-1}\\sigma^2)\n$$\n\nAlso (3.11):\n$$(N-p-1)\\hat{\\sigma}^2 \\sim \\sigma^2\\chi_{N-p-1}^2$$\n\na chi-squared distribution with N-p-1 degrees of freedom and $\\hat{\\beta}$ and $\\hat{\\sigma}$ are statistically independent.\n\n\n**Hypothesis test:** To test $H_0: \\beta_j = 0$ we form the standardized coefficient or *Z-score*:\n$$\nz_j=\\frac{\\hat{B}_j}{\\hat{\\sigma}\\sqrt{v_j}}\n$$\n\nwhere $v_j$ is the jth diagonal element of $(\\mathbf{X}^T\\mathbf{X})^{-1}$. Under the null hypothesis $z_j$ is distributed as $t_{N-p-1}$, and hence a large value of $z_j$ will lead to rejection. If $\\hat{\\sigma}$ is replaced by $\\sigma$ then $z_j$ is a standard normal distribution. The difference between tail quantiles of a t-distribution and a standard normal become negligible as the sample size increases, see the Figure (3.3) below:\n\n\n```python\n# Figure 3.3\n%matplotlib inline\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom scipy.stats import norm, t\n \nfig = plt.figure(figsize = (12, 8))\naxes = fig.add_subplot(1, 1, 1)\n\nz = np.linspace(1.9, 3, 500)\n\nnormal_probabilities = 1 - norm.cdf(z) + norm.cdf(-z)\nt_30_probabilities = 1 - t.cdf(z, 30) + t.cdf(-z, 30) \nt_100_probabilities = 1 - t.cdf(z, 100) + t.cdf(-z, 100) \n\naxes.plot(z, normal_probabilities, color='C0', label = 'normal')\naxes.plot(z, t_30_probabilities, color='C1', label = '$t_{30}$')\naxes.plot(z, t_100_probabilities, color='C2', label = '$t_{100}$')\n\nxlim = axes.get_xlim()\n\nfor y in [0.01, 0.05]:\n axes.plot(xlim, [y, y], '--', color = 'gray', \n scalex = False, scaley = False)\n\n for index, probs in enumerate([normal_probabilities, t_30_probabilities,\n t_100_probabilities]):\n x = z[np.abs(probs - y).argmin()]\n axes.plot([x, x], [0, y], '--', color = f\"C{index}\",\n scalex = False, scaley = False)\n \naxes.legend()\naxes.set_xlabel('Z')\naxes.set_ylabel('Tail Probabilities')\nplt.show()\n```\n\n**Test for the significance of groups of coefficients simultaneously**: We use the F-statistics (3.13):\n\n$$F=\\frac{(RSS_0-RSS_1) / (p_1 - p_0)}{RSS_1/(N-p_1-1)}$$\n\nWhere $RSS_1$ is for the bigger model with $p_1+1$ parameters and $RSS_0$ for the nested smaller model with $p_0+1$ parameters. Under the null hypothesis that the smaller model is correct, the F statistic will have a $F_{p_1-p_0,N-p_1-1}$ distribution. The $z_j$ in (3.13) is equivalent to the F statistic for dropping the single coefficient $\\beta_j$ from the model.\n\nSimilarly, we can isolate $\\beta_j$ in (3.10) to obtain $1-2\\alpha$ confidence interval (3.14)\n$$(\\hat{\\beta_j} - z^{(1-\\alpha)}v_j^{\\frac{1}{2}}\\hat{\\sigma}, \\hat{\\beta_j} + z^{(1-\\alpha)}v_j^{\\frac{1}{2}}\\hat{\\sigma})$$\n\nIn a similar fashion we can obtain an approximate confidence set for the entire parameter vector $\\beta$ (3.15):\n$$ C_{\\beta} = \\{{\\beta|(\\hat{\\beta}-\\beta)^T\\mathbf{X}^T\\mathbf{X}(\\hat{\\beta}-\\beta)} \\le \\hat{\\sigma}^2{\\chi_{p+1}^2}^{(1-\\alpha)} \\}$$\n\nwhere ${\\chi_{l}^2}^{(1-\\alpha)}$ is the $1-\\alpha$ percentile of the chi-squared distribution of $l$ degrees of freedom.\n\n", "meta": {"hexsha": "1e40b4c9e33c6109a44146ee7153b837a0273ca5", "size": 65137, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "chapter-03/3.2-linear-regression-models-and-least-squares.ipynb", "max_stars_repo_name": "debajitd/the-elements-of-statistical-learning", "max_stars_repo_head_hexsha": "67fae7a4f938b5375dd0d5b52dc159b01add7803", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 360, "max_stars_repo_stars_event_min_datetime": "2019-01-28T14:05:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T00:11:21.000Z", "max_issues_repo_path": "chapter-03/3.2-linear-regression-models-and-least-squares.ipynb", "max_issues_repo_name": "debajitd/the-elements-of-statistical-learning", "max_issues_repo_head_hexsha": "67fae7a4f938b5375dd0d5b52dc159b01add7803", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-07-06T16:51:40.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-06T16:51:40.000Z", "max_forks_repo_path": "chapter-03/3.2-linear-regression-models-and-least-squares.ipynb", "max_forks_repo_name": "debajitd/the-elements-of-statistical-learning", "max_forks_repo_head_hexsha": "67fae7a4f938b5375dd0d5b52dc159b01add7803", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 79, "max_forks_repo_forks_event_min_datetime": "2019-03-21T23:48:35.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T13:05:10.000Z", "avg_line_length": 265.8653061224, "max_line_length": 54556, "alphanum_fraction": 0.8970324086, "converted": true, "num_tokens": 2847, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897442783526, "lm_q2_score": 0.9046505428129514, "lm_q1q2_score": 0.8510859528342695}} {"text": "## Regresión lineal\n\n**Temas Selectos de Modelación Numérica**
\nFacultad de Ciencias, UNAM
\nSemestre 2021-2\n\nEn este notebook aprenderemos como hacer una regresión lineal por el método de mínimos cuadrados y por el método matricial. \n\nNo olvides resolver los ejercicios de tarea al final del notebook. Entrega tu solución en un notebook en la carpeta de Classroom con el nombre `apellido_nombre_tarea05.ipynb`.\n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\n%matplotlib inline\n```\n\n## 1. Mínimos cuadrados \n\nAjuste de rectas de la forma $y=mx+b$ por mínimos cuadrados. La idea detrás de este método es que queremos encontrar la pendiente $m$ y la ordenada al origen $b$ que nos dan la recta que minimiza la suma de los cuadrados de las distancias entre los puntos (digamos, datos) y la recta ajustada:\n\n\n\nEs decir, que cuando sumemos el cuadrado de todas las distancias de los puntos a la recta (líneas azules) el valor que obtengamos sea el más pequeño posible (este tipo de problemas se llaman problemas de optimización). \n\nSe pueden ajustar todo tipo de funciones por este método, no sólo rectas, pero para el caso particular de la recta, se obtiene que la pendiente y la ordenada al origen de la recta que minimiza el cuadrado de las distancias se calcula como:\n\n\\begin{align}\n\\tag{1}\nm =\\frac{N \\sum(x_iy_i) − \\sum x_i\\sum y_i}{N \\sum(x_i^2) − (\\sum x_i)^2} \\label{eq1}\\\\\n\\end{align}\n\n\\begin{align}\nb = \\frac{\\sum y_i − m \\sum x_i}{N} \\tag{2}\n\\end{align}\n\nen donde $N$ es el número de mediciones o puntos, $x_i$, $y_i$ son las mediciones y las sumas ($\\sum$) son sobre todas las mediciones.\n\n**OJO**: Debido a que no es necesario graficar los datos para realizar un ajuste por mínimos cuadrados, se puede caer en errores graves como tratar de ajustar una recta a un conjunto de mediciones cuya relación no es lineal. Por eso **es muy importante graficar** los datos y asegurarse de que la relación entre las variables es lineal antes de aplicar el método de mínimos cuadrados. \n\nSiguiendo las ecuaciones anteriores definamos una función `reg_lineal` que calcule a pendiente y ordenada al origen de la recta que mejor se ajusta a los \"datos\" usando el método de mínimos cuadrados:\n\n\n```python\ndef reg_lineal(X,Y):\n '''Esta función calcula la pendiente y la ordenada al origen de la recta y=mx+b por mínimos \n cuadrados a partir de los vectores de mediciones X y Y.\n Input: \n X - arreglo de numpy 1D\n Y - arreglo de numpy 1D del mismo tamaño que X.\n Output:\n m, b : Escalares, la pendiente y ordenada al origen.\n '''\n N = len(X) # numero de valores del vector X\n sum_xy = np.sum(X*Y) # suma de todos los Xi*Yi\n sum_x = np.sum(X) # suma de todas las X\n sum_y = np.sum(Y) # suma de todas las Y\n sum_x2 = np.sum(X**2) # suma de todas las Xˆ2\n\n m = ((N*sum_xy) - (sum_x*sum_y)) / ((N*sum_x2) - (sum_x**2))\n b = (sum_y - (m*sum_x)) / N\n return(m, b)\n```\n\nProbemos nuestra función que calcula la regresión lineal. Para ello generamos un vector X y un vector f(X)=Y de la siguiente manera:\n\n\n```python\nX = np.linspace(1,10,10)\nY = 1 + 2*X + 1*np.random.randn(1) # f(x)=y=1+2x+d \n\nplt.plot(X,Y,'o')\nplt.xlabel('x')\nplt.ylabel('y=f(x)')\nplt.show()\n```\n\nAhora podemos probar la función `reg_lineal` usando X y Y:\n\n\n```python\nm, b = reg_lineal(X,Y)\nprint('La pendiente m es %f y la ordenada b es %f' %(m,b))\nY2 = m*X+b\n\nplt.plot(X,Y,'o', label='Y')\nplt.plot(X,Y2,'-',label='regresión' )\nplt.xlabel('x')\nplt.ylabel('y=f(x)')\nplt.legend()\nplt.show()\n```\n\n## 2. Método matricial\n(Nota: El material de esta sección fue tomado del blog [cmdlinetips](https://cmdlinetips.com/2020/03/linear-regression-using-matrix-multiplication-in-python-using-numpy/)) \n\nTambién podemos hacer regresiones lineales usando el método matricial. Recordemos que en una regresión lineal queremos ajustar nuestros datos, observaciones, etc. usando el modelo lineal $$y=\\beta_0+\\beta_1X+\\epsilon$$ y estimar los parámetros del modelo $\\beta_0$ y $\\beta_1$ que son la ordenada al origen y la pendiente, respectivamente.\n\nPodemos combinar las \"variables predictivas\", en este caso X, en una matriz que tiene un vector columna lleno de unos (lo que multiplica a $\\beta_0$) y X (lo que multiplica a $\\beta_1$):\n\n\n```python\nX_mat = np.vstack((np.ones(len(X)), X)).T # en este caso usamos la función vstack \n # y el método T (transponer) para obtener las dimensiones \n # adecuadas\n```\n\nCon un poco de álgebra lineal y el objetivo de minimizar el error cuadrático medio del sistema de ecuaciones lineales llegamos a que podemos calcular el valor de los parámetros $\\hat{\\beta}=(\\beta_0, \\beta_1)$ de la forma:\n\n$$\\hat{\\beta}=(X^T. X)^{-1}. X^T. Y$$\n\nPodemos implementar esta ecuación usando las funciones para la inversa de una matriz y multiplicación matricial del módulo de álgebra lineal de numpy `linalg`:\n\n\n```python\nbeta = np.linalg.inv(X_mat.T.dot(X_mat)).dot(X_mat.T).dot(Y)\n\nprint('La pendiente beta_1 es %f y la ordenada beta_0 es %f' %(beta[1], beta[0]))\n```\n\n La pendiente beta_1 es 2.000000 y la ordenada beta_0 es 2.756253\n\n\nque son los mismos valores para la pendiente y ordenada al origen que encontramos usando la función `reg_lineal`. Ahora usemos estos parámetros para estimar los valores de Y:\n\n\n```python\nY_mat = X_mat.dot(beta)\n\nplt.plot(X,Y,'o', label='Y')\nplt.plot(X,Y_mat,'-',label='regresión método matricial' )\nplt.xlabel('x')\nplt.ylabel('y=f(x)')\nplt.legend()\nplt.show()\n```\n\n## 3. Ejemplo usando ambos métodos\n\n\n```python\nX = np.linspace(1,10)\nY = 1 + 2*X + 3*X**2 + 20*np.random.randn(1)\n\n# Método matricial - ahora tenemos otro término, Xˆ2\nX_mat = np.vstack((np.ones(len(X)), X, X**2)).T\nbeta = np.linalg.inv(X_mat.T.dot(X_mat)).dot(X_mat.T).dot(Y)\nY_mat = X_mat.dot(beta)\n\n# Función reg_lineal\nm, b = reg_lineal(X,Y)\nY2 = m*X+b\n\nplt.plot(X,Y,'o',label='datos')\nplt.plot(X,Y_mat, label='Método matricial')\nplt.plot(X,Y2, label='Mínimos cuadrados - recta')\nplt.xlabel('X')\nplt.ylabel('Y')\nplt.legend()\nplt.show()\n```\n\nUps, claramente ajustar los datos a una recta no era una buena idea. Por eso es importante hacer una inspección gráfica de lo que queremos ajustar.\n\n### Ejercicios de tarea:\n \n1. Desarrollar las expresiones para la ordenada al origen y la pendiente en una recta usando el método de mínimos cuadrados. (Entregar el desarrollo en un archivo aparte).\n\n2. Programar una función que calcule la regresión de un polinomio de grado 3. En un notebook define la función y puébala usando el polinomio de grado 3 $y = 2x^3+5x^2-11x+7$.\n\n\n```python\n\n```\n", "meta": {"hexsha": "e7a5435527ade2806fd6056b81b2ce36af7b6aa1", "size": 73843, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "otros/06_reg_lineal.ipynb", "max_stars_repo_name": "anakarinarm/TallerModNum", "max_stars_repo_head_hexsha": "36e54897f23b5ac70f125eba5e1ad7055871df4a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2022-02-14T20:30:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-14T21:23:11.000Z", "max_issues_repo_path": "otros/06_reg_lineal.ipynb", "max_issues_repo_name": "anakarinarm/TallerModNum", "max_issues_repo_head_hexsha": "36e54897f23b5ac70f125eba5e1ad7055871df4a", "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": "otros/06_reg_lineal.ipynb", "max_forks_repo_name": "anakarinarm/TallerModNum", "max_forks_repo_head_hexsha": "36e54897f23b5ac70f125eba5e1ad7055871df4a", "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": 208.5960451977, "max_line_length": 23368, "alphanum_fraction": 0.9103503379, "converted": true, "num_tokens": 2012, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897459384732, "lm_q2_score": 0.9046505402422645, "lm_q1q2_score": 0.8510859519176226}} {"text": "# Part 1: Linear Regression\n\n\n```python\n# Execute this code block to install dependencies when running on colab\ntry:\n import torch\nexcept:\n from os.path import exists\n from wheel.pep425tags import get_abbr_impl, get_impl_ver, get_abi_tag\n platform = '{}{}-{}'.format(get_abbr_impl(), get_impl_ver(), get_abi_tag())\n cuda_output = !ldconfig -p|grep cudart.so|sed -e 's/.*\\.\\([0-9]*\\)\\.\\([0-9]*\\)$/cu\\1\\2/'\n accelerator = cuda_output[0] if exists('/dev/nvidia0') else 'cpu'\n\n !pip install -q http://download.pytorch.org/whl/{accelerator}/torch-1.0.0-{platform}-linux_x86_64.whl torchvision\n```\n\n## Getting started \n\nAt its heart, PyTorch is just a library for manipulating tensors. We're going to start learning how to use \nPyTorch by looking at how we can implement simple linear regression. \n\nCode speaks better than words, so lets start by looking at a bit of pytorch code to generate some 2d data to regress:\n\n\n```python\nimport torch\n\n# Generate some data points on a straight line perturbed with Gaussian noise\nN = 1000 # number of points\ntheta_true = torch.Tensor([[1.5], [2.0]]) # true parameters of the line\n\nX = torch.rand(N, 2) \nX[:, 1] = 1.0\ny = X @ theta_true + 0.1 * torch.randn(N, 1) # Note that just like in numpy '@' represents matrix multiplication and A@B is equivalent to torch.mm(A, B) \n```\n\nThe above code generates $(x,y)$ data according to $y = 1.5x + 2$, with the $x$'s chosen from a uniform distribution. The $y$'s are additionally purturbed by adding an amount $0.1z$, where $z\\sim \\mathcal{N}(0,1)$ is a sample from a standard normal distribution. \n\nNote that we represent our $x$'s as a two-dimensional (row) vector with a 1 in the second element so that the offset can be rolled into the matrix multiplication for efficiency:\n\n\\begin{align}\n y &= \\mathbf{X}\\begin{bmatrix}\n 1.5 \\\\\n 2\n \\end{bmatrix}\n \\end{align}\n\nLet's use `matplotlib` to draw a scatter so we can be sure of what our data looks like:\n\n\n```python\n%matplotlib inline\nimport matplotlib.pyplot as plt\n\nplt.scatter(X[:,0].numpy(), y.numpy())\nplt.show()\n```\n\n__Make sure you understand how the code above is generating data; feel free to change the parameters to see what effect they have.__\n\nNow, lets consider the situation where we have been given the tensors $X$ and $y$ and wish to compute the regression parameters. Our model looks like $\\mathbf{y} = \\mathbf{X\\theta}$, and we wish to recover the parameters $\\theta$. \n\nAs the problem is both overcomplete (only two data pairs are required to find $\\theta$), and the data is noisy, we can use the Moore-Penrose Pseudoinverse to find the least-squares solution to $\\theta$: $\\theta = \\mathbf{X^+y}$. PyTorch has a built-in pseudoinverse method (`pinverse`) that can do all the work for us:\n\n\n```python\n# direct solution using moore-penrose pseudo inverse\nX_inv = torch.pinverse(X)\ntheta_pinv = torch.mm(X_inv, y)\nprint(theta_pinv)\n```\n\nRunning the above code should give you a solution vector for $\\theta$ that is very similar to the true parameter vector (`theta_true`). \n\n## Exercise: computing the pseudoinverse from the Singular Value Decomposition.\n\nThe standard way of computing the pseudoinverse is by using the Singular Value Decomposition (SVD). The SVD is defined as: $\\mathbf{X} = \\mathbf{U}\\Sigma\\mathbf{V}^\\top$. The pseudoinverse is thus $\\mathbf{X}^+ = \\mathbf{V}\\Sigma^{-1}\\mathbf{U}^\\top$ where $\\Sigma^{-1}$ is a diagonal matrix in which the reciprocal of the corresponding non-zero elements in $\\Sigma$ has been taken.\n\n__Use the code block below to compute the parameter vector using the SVD directly rather than the through the `pinverse` method.__ You need to store your manually computed pseudoinverse in `X_inv_svd`. Useful methods will be `torch.svd()` to compute the SVD, `[Tensor].t()` to transpose a matrix and `torch.diag()` to form a diagonal matrix from a vector.\n\n\n```python\n# YOUR CODE HERE\nraise NotImplementedError()\n\ntheta_pinv_svd = torch.mm(X_inv_svd, y)\nprint(theta_pinv_svd)\n```\n\n\n```python\nassert(torch.all(torch.lt(torch.abs(torch.add(theta_pinv, -theta_pinv_svd)), 1e-6)))\n```\n\n## Gradient based Linear Regression\n\nFundamentally, with linear regression we are trying to find a solution vector, $theta$ that minimises $f(\\theta) = 0.5\\|\\mathbf{X}\\theta - \\mathbf{y}\\|_2^2$. \n\nWe've already seen how this can be minimised directly using the pseudoinverse, but it could also be minimised by using gradient descent: $\\theta \\gets \\theta - \\alpha f'(\\theta)$. (_Interesting aside_: SVD (and thus the pseudoinverse) can also be solved using gradient methods - in fact this becomes the only practical way for really large matrices.).\n\n__Use the following block to derive and write down the gradient, $f'(\\theta)$, of $f(\\theta)$__. Note that you can insert latex code by wrapping expressions in dollar symbols.\n\n__Now complete the following code block to implement your gradient as pytorch code:__\n\n\n```python\ndef linear_regression_loss_grad(theta, X, y):\n # theta, X and y have the same shape as used previously\n # YOUR CODE HERE\n raise NotImplementedError()\n return grad\n```\n\n\n```python\nassert(linear_regression_loss_grad(torch.zeros(2,1), X, y).shape == (2,1))\n\n```\n\nNow we can plug that gradient function into a basic gradient descent solver and check that the solution is close to what we get with the pseudoinverse:\n\n\n```python\nalpha = 0.001\ntheta = torch.Tensor([[0], [0]])\nfor e in range(0, 200):\n gr = linear_regression_loss_grad(theta, X, y)\n theta -= alpha * gr\n\nprint(theta)\n```\n\n## Real data\n\nDoing linear regression on synthetic data is a great way to understand how PyTorch works, but it isn't quite as satisfying as working with a real dataset. Let's now apply or understanding of computing linear regression parameters to a dataset of house prices in Boston.\n\nWe'll load the dataset using scikit-learn and perform some manipulations in the following code block:\n\n\n```python\nfrom sklearn.datasets import load_boston\n\nX, y = tuple(torch.Tensor(z) for z in load_boston(True)) #convert to pytorch Tensors\nX = X[:, [2,5]] # We're just going to use features 2 and 5, rather than using all of of them\nX = torch.cat((X, torch.ones((X.shape[0], 1))), 1) # append a column of 1's to the X's\ny = y.reshape(-1, 1) # reshape y into a column vector\nprint('X:', X.shape)\nprint('y:', y.shape)\n\n# We're also going to break the data into a training set for computing the regression parameters\n# and a test set to evaluate the predictive ability of those parameters\nperm = torch.randperm(y.shape[0])\nX_train = X[perm[0:253], :]\ny_train = y[perm[0:253]]\nX_test = X[perm[253:], :]\ny_test = y[perm[253:]]\n```\n\n__Use the following code block to compute the regression parameters using the training data in the variable `theta` by solving using the pseudoinverse directly:__\n\n\n```python\n# compute the regression parameters in variable theta\n# YOUR CODE HERE\nraise NotImplementedError()\n```\n\nWe can now print out the error achieved on the test set, as well as the parameter vector:\n\n\n```python\nassert(theta.shape == (3,1))\n\nprint(\"Theta: \", theta.t())\nprint(\"MSE of test data: \", torch.nn.functional.mse_loss(X_test @ theta, y_test))\n```\n\nNow let's try using gradient descent:\n\n\n```python\nalpha = 0.00001\ntheta_gd = torch.rand((X_train.shape[1], 1))\nfor e in range(0, 10000):\n gr = linear_regression_loss_grad(theta_gd, X_train, y_train)\n theta_gd -= alpha * gr\n\nprint(\"Gradient Descent Theta: \", theta_gd.t())\nprint(\"MSE of test data: \", torch.nn.functional.mse_loss(X_test @ theta_gd, y_test))\n```\n\n__Use the following block to note down any observations you can make about the choice of learning rate and number of iterations in the above code. What factors do you think influence the choice?__\n\n\n```python\n# YOUR CODE HERE\nraise NotImplementedError()\n```\n\nFinally, just so we can visualise what our model has learned, we can plot the predicted house prices (from both the direct solution and from gradient descent) along with the true value for each of the houses in the test set (ordered by increasing true value):\n\n\n```python\nperm = torch.argsort(y_test, dim=0)\nplt.plot(y_test[perm[:,0]].numpy(), '.', label='True Prices')\nplt.plot((X_test[perm[:,0]] @ theta).numpy(), '.', label='Predicted (pinv)')\nplt.plot((X_test[perm[:,0]] @ theta_gd).numpy(), '.', label='Predicted (G.D.)')\nplt.xlabel('House Number')\nplt.ylabel('House Price ($,000s)')\nplt.legend()\nplt.show()\n```\n", "meta": {"hexsha": "bacaa26c0f3aa8e61f302b9b5a5d4f722213facb", "size": 22703, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Pytorch Practical Tasks/1_1_linear_regression.ipynb", "max_stars_repo_name": "VladimirsHisamutdinovs/deep-learning-pytorch", "max_stars_repo_head_hexsha": "252a2d9e496c444fad1cb77a9e200afca9590aef", "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": "Pytorch Practical Tasks/1_1_linear_regression.ipynb", "max_issues_repo_name": "VladimirsHisamutdinovs/deep-learning-pytorch", "max_issues_repo_head_hexsha": "252a2d9e496c444fad1cb77a9e200afca9590aef", "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": "Pytorch Practical Tasks/1_1_linear_regression.ipynb", "max_forks_repo_name": "VladimirsHisamutdinovs/deep-learning-pytorch", "max_forks_repo_head_hexsha": "252a2d9e496c444fad1cb77a9e200afca9590aef", "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": 32.9985465116, "max_line_length": 407, "alphanum_fraction": 0.5228824384, "converted": true, "num_tokens": 2211, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070060380481, "lm_q2_score": 0.9353465147977104, "lm_q1q2_score": 0.8510783468877074}} {"text": "# Scientific Computing: Introduction to Python\n\n\nDr. Ilian Iliev\n\n\nLet's start with some examples of simple printing. Note that in Python 3 the brackets are required (not the case in Python 2). Quotes can be single or double.\n\n\n```python\nprint('hello')\n```\n\n hello\n\n\n\n```python\nprint(\"hello\")\n```\n\n hello\n\n\n## Using Python as a (quite powerful) calculator\nYou can print arithmetic expressions directly at the Python prompt and it will evaluate them and give you the result, just as a calculator will do. (Note: The pound sign (#) denotes the beginning of a comment – all characters between # and the end of the line are ignored \nby the Python interpreter.). For example:\n\n```python\n5+9\n```\n\n\n\n\n 14\n\n\n\n\n```python\n3**50\n```\n\n\n\n\n 717897987691852588770249L\n\n\n\n\n```python\n2000/25 #division\n```\n\n\n\n\n 80\n\n\n\n\n```python\n2000//25 #integer division\n```\n\n\n\n\n 80\n\n\n\n\n```python\n2345677*25\n```\n\n\n\n\n 58641925\n\n\n\n\n```python\n36**0.5 #square root (Note: sqrt() is not in core Python!)\n```\n\n\n\n\n 6.0\n\n\nNote that (unlike many other programming languages) Python can do arbitrary-length arithmetic (Note: When the number has more digits than normal arithmetic Python 2 appends 'L' at the end of the result, for 'Long'; Python 3 does not do that.).\n\n\n```python\n45%7 # modulus (remainder)\n```\n\n\n\n\n 3\n\n\n\n# Note: Beware of integer division in Python 2! \nMany people have been tripped by it. Try for example:\n\n```python\nprint(3/2, 3/2.0, 3.0/2.0, float(3)/2, 3/float(2))\n```\n\n (1, 1.5, 1.5, 1.5, 1.5)\n\nThe best solution is to make sure you always divide real numbers (floats). That is not an issue for Python 3, however.\n# Exercise: Evaluate some more arithmetic expressions on your own. \nCore Python supports only a few mathematical functions, shown with some examples below\n\n```python\na=-7\n```\n\n\n```python\nb={3,9,2,55}\n```\n\n\n```python\nc=3.1415\n```\n\n\n```python\nabs(a) #absolute value\n```\n\n\n\n\n 7\n\n\n\n\n```python\nmax(b) # Largest element in a sequence \n```\n\n\n\n\n 55\n\n\n\n\n```python\nmin(b) # Smallest element in a sequence\n```\n\n\n\n\n 2\n\n\nWhat about other mathematical functions like e.g. square root, logarithms, trigonometric functions, etc.? Those are not built into the core Python, but are available by loading the math module (we will also discuss other modules later). \n\nThere are three ways of accessing the functions available in a module: \n\n```python\nimport math # make the 'math' module available. This is the \n # RECOMMENDED method because it is economical on resources\n # and a good programming practice. This is the method used\n # by most programmers.\n```\n\n\n```python\nprint(math.log(math.sin(0.5))) # Then this is how you use it - each \n # function gets 'math' prefix telling\n # Python where to get this function from.\n```\n\n -0.735166686385\n\nYou can also 'rename' modules when importing them, for brevity or other reasons:\n\n```python\nimport math as m # From now on module math has also this other name 'm'\n```\n\n\n```python\nm.cosh(3)\n```\n\n\n\n\n 10.067661995777765\n\n\nYou can also import a module like this:\n\n```python\nfrom math import * # import ALL math module functions\n```\nFor small modules this could be OK, but for big ones with many functions like 'math' this is wasteful, and also a bad idea for other reasons. \n\nFinally, you can also just import specific functions that you need, in which case you can use the functions without a module prefix:\n\n```python\nfrom math import log, sin\n```\n\n\n```python\nprint(log(sin(0.5)))\n```\n\n -0.735166686385\n\nThe contents of a module could be printed as follows (for example to check if a certain function is available). This type of inquiry is usually called 'introspection':\n\n```python\ndir(math)\n```\n\n\n\n\n ['__doc__',\n '__file__',\n '__name__',\n '__package__',\n 'acos',\n 'acosh',\n 'asin',\n 'asinh',\n 'atan',\n 'atan2',\n 'atanh',\n 'ceil',\n 'copysign',\n 'cos',\n 'cosh',\n 'degrees',\n 'e',\n 'erf',\n 'erfc',\n 'exp',\n 'expm1',\n 'fabs',\n 'factorial',\n 'floor',\n 'fmod',\n 'frexp',\n 'fsum',\n 'gamma',\n 'hypot',\n 'isinf',\n 'isnan',\n 'ldexp',\n 'lgamma',\n 'log',\n 'log10',\n 'log1p',\n 'modf',\n 'pi',\n 'pow',\n 'radians',\n 'sin',\n 'sinh',\n 'sqrt',\n 'tan',\n 'tanh',\n 'trunc']\n\n\nMany of the above functions should be familiar to you. If you are not sure what a given function do or how to call it, you can invoke the Python help system, as follows:\n\n```python\nhelp(modf)\n```\n\n Help on built-in function modf in module math:\n \n modf(...)\n modf(x)\n \n Return the fractional and integer parts of x. Both results carry the sign\n of x and are floats.\n \n\n\nExercises:\n\n1) The Universe is 13.6 billion years old, how many seconds old is it?\n\n2) Compute 2 to the 266th power. This is (roughly) the number of atoms \nin the Universe.\n\n3) Import the math module and calculate: \n\n\\begin{equation}\n\\cos(\\pi/4)\n\\\\ \n\\pi-4 atan(1)\n\\end{equation}\n\nDo results conform with your expectations?\n\n# Variables and important data types\nIn Python, all numbers (and everything else, including functions) are \nOBJECTS (i.e. Python, like C++ is an object-oriented language). A variable can be used to store a certain value or object. There are several basic types of variables that we will need: integers, floats (real numbers), complex numbers, strings and combinations of these (lists, tuples and arrays). \n\nVariables are typed dynamically, i.e. their type (which can be checked with 'type(var)') is set whenever the variable is assigned a value and can be changed by assigning another value: \n\n```python\na=1 #integer\n```\n\n\n```python\ntype(a)\n```\n\n\n\n\n int\n\n\n\n\n```python\nb=1.0 #float=real\n```\n\n\n```python\ntype(b)\n```\n\n\n\n\n float\n\n\n\n\n```python\nc='1.0' #string\n```\n\n\n```python\ntype(c)\n```\n\n\n\n\n str\n\n\n\n\n```python\nd=2+3.0j #complex number\n```\n\n\n```python\ntype(d)\n```\n\n\n\n\n complex\n\n\nA string is a sequence of characters enclosed in single or double quotes. Long strings continuing on several lines are defined using triple quotes. \n\nStrings are concatenated with the plus (+) operator, whereas slicing (:) is used to extract a portion of the string:\n\n```python\nstring1 = 'Press return to exit'\n```\n\n\n```python\nstring2 = 'the program'\n```\n\n\n```python\nprint(string1 + ' ' + string2) # Concatenation\n```\n\n Press return to exit the program\n\n\n\n```python\nprint(string1[0:12]) # Slicing\n```\n\n Press return\n\nStrings are immutable objects (i.e. its individual characters cannot be modified with an assignment statement; the whole string CAN be assigned a different value) with a fixed length. \n\nAn attempt to violate immutability will result in TypeError, as shown here:\n\n```python\ns='Press return to exit'\n```\n\n\n```python\ns[0] # Individual characters can be accessed\n```\n\n\n\n\n 'P'\n\n\n\n\n```python\ns[0]='T' # ... but they cannot be modified\n```\n\n\n```python\nb=2; c=4 # b and c are of an integer type\n```\n\n\n```python\nb=b*1.0; c=float(c) # two ways to convert them back into floats \n```\n\n\n```python\nprint(b,c) # Both b and c are floats now, the original values were destroyed\n```\n\n (2.0, 4.0)\n\n\n\n```python\nd=int(b); print(d) # 'int' converts a number into an integer\n```\n\n 2\n\nThe function 'round' with a single argument rounds up a number to the nearest integer (up or down). You can also round a number with certain number of significant digits after the decimal point.\n\nStrings also can be converted into numbers if they are made of numbers: \n\n```python\na=5.78666; print(round(a)); print(round(a,3))\n```\n\n 6.0\n 5.787\n\n\n\n```python\ns='357'; type(int(s))\n```\n\n\n\n\n int\n\n\n\n\n```python\nprint(int(s))\n```\n\n 357\n\n\n# Exercises: \n\n1) Create a string variable 'myname' that is initialised to \nyour full name - first, middle and last.\n\n2) Using a slice operator, print your first name only.\n\n3) Using a slice operator, print your last name only.\n\n4) Using the slice and concatenation operators, print \nyour name in the form 'Last name, First name'.\n\n5) Create a new string where your middle name is replaced by\nyour middle initial.\n\n6) Use Python to check how long the 'myname' string is and \nif it contains the letter 'a'.\n\n7) What happens if you multiply a string and a number?\n\n# Tuples and lists\nA tuple is a sequence of arbitrary objects separated by commas and enclosed in parentheses. If the tuple contains a single object, a final comma is required; for example, 'x = (2,)'. Tuples support the same operations as strings and are also immutable. Here is an example where the tuple 'rec' contains another tuple '(6,23,68)':\n\n```python\nrec = ('Smith','John',(24,7,1988)) # This is a tuple\n```\n\n\n```python\nlastName,firstName,birthdate = rec # Unpacking the tuple into its parts\n```\n\n\n```python\nprint(firstName)\n```\n\n John\n\n\n\n```python\nbirthYear=birthdate[2]; print(birthYear)\n```\n\n 1988\n\n\n\n```python\nname = rec[1] + ' ' + rec[0] # combine the two name strings\n```\n\n\n```python\nprint(name)\n```\n\n John Smith\n\n\n\n```python\nprint(rec[0:2]) # Slice the first 2 elements of the tuple 'rec'\n```\n\n ('Smith', 'John')\n\n\n### Important note: In Python sequences have zero offset, so that a[0] represents the first element of a, a[1] the second one, and so forth. Similarly, indices in Python always start from 0, so e.g. 2 is the third element, etc. \nLists are ordered sets of objects similar to tuples, but they are mutable, i.e. their elements and length can be changed. A list is identified by enclosing its elements in square brackets, [,]. The objects in a list could be of any type, e.g. real or integer numbers, strings, even other lists.\n\nBelow is a sampling of operations that can be performed on lists: \n\n```python\na = [1.0,'two',3] # Define a list\n```\n\n\n```python\na[0] # First element of the list\n```\n\n\n\n\n 1.0\n\n\n\n\n```python\na[1] # Second element of the list\n```\n\n\n\n\n 'two'\n\n\n\n\n```python\na[3] # There is no such element, so this gives an error.\n```\n\n\n```python\na.append(33.0) # Append another element (33.0) to the list\n```\n\n\n```python\nprint(a)\n```\n\n [1.0, 'two', 3, 33.0]\n\n\n\n```python\na.insert(0,22) # Insert another element (22) at position 0\n```\n\n\n```python\nprint(a)\n```\n\n [22, 1.0, 'two', 3, 33.0]\n\nQuestion: What does a[-1] give? What about a[-3]?If a is a mutable object, such as a list, the assignment statement b=a \ndoes not result in a new object b, but simply creates a new reference to a (i.e. now the same object has 2 names - a and b). Thus any changes made to b will be reflected in a (but not vice-versa). To create an independent copy of a list a, use the statement 'c = a[:]', as shown below:\n\n```python\nb=a # 'b' becomes an alias of a\n```\n\n\n```python\nb[0]=5 # change an element of b\n```\n\n\n```python\nprint(a) # a has changed \n```\n\n [5, 1.0, 'two', 3, 33.0]\n\n\n\n```python\nc=a[:] # 'c' is an independent copy of a\n```\n\n\n```python\nc[0]=4 # change an element of c\n```\n\n\n```python\nprint(a) # a remains the same\n```\n\n [5, 1.0, 'two', 3, 33.0]\n\nThere are various oprations that can be performed on sequences like lists. Some examples: \n\n```python\nprint(a[1:3]) # slices a part of a (here the second and third elements)\n```\n\n [1.0, 'two']\n\n\n\n```python\nlen(a) # how many elements does 'a' have?\n```\n\n\n\n\n 5\n\n\n\n\n```python\n'two' in a # checks if a certain element can be found in the list\n```\n\n\n\n\n True\n\n\n\n\n```python\na[2]=7 # lets make the list wholly of numbers (strings cannot be compared to numbers!)\n```\n\n\n```python\nmax(a) # what is the largest element of the sequence?\n```\n\n\n\n\n 33.0\n\n\n\n\n```python\nmin(a) # what is the smallest element in the sequence?\n```\n\n\n\n\n 1.0\n\n\n\n\n```python\nd=a+c # concatenates the two sequences\n```\n\n\n```python\nprint(d)\n```\n\n [5, 1.0, 7, 3, 33.0, 4, 1.0, 'two', 3, 33.0]\n\n\n# Comparison operators\nThe comparison operators are: \n< (less than), \n> (greater than), \n<= (less than or equal to), \n>= (greater than or equal to), \n== (equal to) \n!= (not equal to). \n\nThey are quite useful for programming, as we shall see. The result is a logical expression ('True' or 'False'). These can be used to construct more complicated logical statements using also 'or' and 'and'. \n\nNumbers of different type (integer, floating point, etc.) are converted to a common type before the comparison is made. Otherwise, objects of different type are considered to be unequal (e.g. 2 does not equal 2.0). Here are a few examples:\n\n```python\na=5.7\n```\n\n\n```python\nb=4.3\n```\n\n\n```python\nprint(a>b)\n```\n\n True\n\n\n\n```python\nprint(a==b)\n```\n\n False\n\n\n\n```python\nc=3\n```\n\n\n```python\na>b and c5'?\n\n2) What is the result of the Boolean expression 'not(True and False)'? Is this what you expected?\n\n3) Write a compound Boolean expression that returns True if the value of the variable 'count' is between 1 and 10 inclusive. \n\n# Conditionals\nConditionals are quite useful in construction of algorithms and are \nan important program control structure. The 'if' construct\n\nif condition:\n block\n \nexecutes a block of statements (which MUST be indented since that \nis how Python knows what is inside the 'if' and what is not!) if the \ncondition returns true. If the condition returns false, the block \nis skipped. The if conditional can be followed by any number of \n'elif' (short for “else if”) constructs\n\nif condition:\n block1\nelif condition:\n block2\n\nwhich work in the same manner. The 'else' clause\n\nelse:\n block\n\ncan be used to define the block of statements that are to be executed if none of the if-elif clauses is true. The function below illustrates the use of the conditionals:\n\n```python\ndef sign_of_a(a):\n if a < 0.0:\n sign = 'negative'\n elif a > 0.0:\n sign = 'positive'\n else:\n sign = 'zero'\n return sign\n\na = 1.5\nprint('a is ' + sign_of_a(a))\n```\n\n a is positive\n\nHere 'def' defines a function, to be discussed below (similar to Matlab \nfunctions).\n# Exercises: \n\n1) If you have several nested 'if/else' constructs, how does Python \nknow to which 'if' an 'else' belongs? Try to check your answer \nusing an example.\n\n2) Write a construct that sets the value of a variable called \n'grade' to the value 4 if a variable named 'score' is greater \nthan 70, 3 if 'score' is between 60 and 69, 2 if 'score' is \nbetween 50 and 59, 1 if 'score' is between 40 and 49, and 0 otherwise. \nThis statement (roughly) converts British-style grades to American-style ones.\n\n# Loops \nOne of the most typical tasks we use a computer for is to do a certain task multiple times (e.g. for different input values). Such repetitive tasks (at which computers are really good, since unlike people they do not get bored) are performed by loops. There are two basic types of loops - a 'while' loop and a 'for' loop. \n## 'While' loops\nThe 'while' construct:\n\nwhile condition:\n block\n\nexecutes a block of (again, indented) statements if the condition is true. After execution of the block, the condition is evaluated again. If it is still true, the block is executed again. This process is continued until the condition becomes false. The 'else' clause\n\nelse: \n block\n\ncan be used to define the block of statements that are to be executed if the condition is false. \n\nHere is an example that creates the list [1, 1/2, 1/3, . . .]:\n\n```python\nnMax=5\n```\n\n\n```python\nn=1\n```\n\n\n```python\na=[] # Create empty list\n```\n\n\n```python\nwhile n < nMax:\n a.append(1.0/n) # Append element to list\n n = n + 1\n print(a)\n```\n\n [1.0]\n [1.0, 0.5]\n [1.0, 0.5, 0.3333333333333333]\n [1.0, 0.5, 0.3333333333333333, 0.25]\n\nNote the indentations above - they indicate what does or does not belong to the loop (since there is no explicit loop end) and are thus absolutely necessary. The IPython shell will do the indentations for you automatically (you indicate the end the loop by pressing 'Return' twice), but an external editor might not do it for you, in which case you have to do it yourself. \n## The range() command\n\nA special type of list is frequently required (often together with \nfor-loops, see below) and therefore a command exists to generate that \nlist: the 'range(stop)' command generates a list of integers starting \nfrom 0 and going up to but NOT INCLUDING n. You can also specify \nboth the start and stop points, as well as (optionally) the step\n\nrange(start,stop[,step])\n\n(see help for further details). Here are a few examples:\n\n\n```python\nfor a in range(5):\n print(a) # print a\n```\n\n 0\n 1\n 2\n 3\n 4\n\n\n\n```python\nfor a in range(3,10,2): \n print(a) \n```\n\n 3\n 5\n 7\n 9\n\n\n# For loops\nThe 'for' loops are explicit in terms of how many times the loop statements will be executed, rather than conditional as the 'while' loops we discussed above:\n\nfor target in sequence:\n block of instructions\n \nand repeat the operations in 'block' for all values in 'sequence'. Unlike many other programming languages (e.g. C, Fortran), the loops in Python need not be over an integer index (as were the 'range' examples above), but can be performed directly over the sequence elements, which need not even be numbers. Here is an example where we iterate over a list of strings and within it over the letters in each string: \n\n```python\nfruits = ['apple','banana','orange']\n```\n\n\n```python\nfor fruit in fruits:\n for letter in fruit:\n print(letter)\n```\n\n a\n p\n p\n l\n e\n b\n a\n n\n a\n n\n a\n o\n r\n a\n n\n g\n e\n\nPython provides further statements for controlling the flow of a program: break, continue and else. \n\nThe 'break' command issued inside a loop immediately ends the loop and moves execution to the statements immediately following that loop. \n\n```python\nx=0\n```\n\n\n```python\nwhile True: # this will go on forever unless stopped\n x += 1 # add 1 to x and put the result back in x\n if not (x % 15 or x % 25):\n break\nprint(x, 'is divisible by both 15 and 25')\n```\n\n (75, 'is divisible by both 15 and 25')\n\nThe 'continue' statement allows us to skip a portion of the statements in an iterative loop. If the interpreter encounters the continue statement, it immediately returns to the beginning of the loop to start the next iteration without executing the statements below 'continue'. \n\nThe following example compiles a list of all numbers between 1 and 99 that are divisible by 7:\n\n```python\nx = [] # Create an empty list\nfor i in range(1,100):\n if i%7!= 0: continue # If not divisible by 7, skip rest of loop\n x.append(i) # Append i to the list\nprint(x)\n```\n\n [7, 14, 21, 28, 35, 42, 49, 56, 63, 70, 77, 84, 91, 98]\n\nFinally, a 'for' or 'while' loop may be followed by an 'else' block of statements, which is executed only if the loop finished 'normally', i.e. without using 'break'.\n# Exercises:\n\n1) Write a for loop which calculates the first 10 terms of the Madhava series:\n\n\\begin{equation}\n\\sqrt{12}\\left(1-\\frac1{3\\times3}+\\frac1{5\\times3^2}-\\frac1{7\\times3^3}+...\\right)\n\\end{equation}\n\n(this is one way to calculate $\\pi$ using series).\n\n2) Use a 'while' loop to calculate\n\n\\begin{equation}\nx_{k+1}=\\frac12\\left(x_k+\\frac2{x_k}\\right)\n\\end{equation} \n\nwith x(0)=1, until $abs(x(k+1)-\\sqrt(2)) < 0.0001$. (As we will discuss later in the term, this is a way to calculate square roots using just addition and division). \n \n3) The double factorial function, n!!, is the product of the positive odd integers up to and including n (which must itself be odd):\n\n\\begin{equation}\n n!!=\\prod\\limits_{i=1}^{(n+1)/2}(2i-1)=1\\cdot3\\cdot5\\dots(n-2)\\cdot n\n\\end{equation}\n\nWrite a routine to calculate n!! in Python. \n\n4) A very elegant way to calculate the greatest common denominator of two numbers is the ver elegant Euclid agorithm:\n\nIn [7]: a,b=1071,462\n\nIn [8]: while b:\n\n a,b=b,a%b\n \n\nIn [9]: print a\n\n21\n\nExplain how it works.\n\n# Reading input and writing output\nThe intrinsic Python 2.x function for accepting user input is\n\nraw_input(prompt)\n\nNote: In Python 3.x this function is renamed 'input()'. In the Python 3.x version of our textbook (Kyusalaas) this is incorrect and 'raw_input' is still being used.\n\nThe 'raw_input' function displays the prompt and then reads a line of input that is converted into a string. To convert the string back into a numerical value (if it is a number), you can use the function\n\neval(string)\n\n```python\na = raw_input(\"Input a: \") # Ask for input\n```\n\n Input a: 34\n\n\n\n```python\nprint(a,type(a)) # Print a and its type\n```\n\n ('34', )\n\n\n\n```python\nb=eval(a) # b is a number\n```\n\n\n```python\nprint(b,type(b)) # 'b' is a number (integer)\n```\n\n (34, )\n\nAs we saw earlier, output can be displayed with the print statement:\n\nprint(object1, object2, . . .)\n\nwhich converts object1, object2, and so on to strings and prints them on the same line, separated by spaces. The newline character '\\n' can be used to force a new line. For example,\n\n```python\na=1234.56789\n```\n\n\n```python\nb=[2,4,6,8]\n```\n\n\n```python\nprint(a,b)\n```\n\n (1234.56789, [2, 4, 6, 8])\n\n\n\n```python\nprint 'a=',a,'\\nb=',b\n```\n\n a= 1234.56789 \n b= [2, 4, 6, 8]\n\nThe modulo operator '%' can be used to format a tuple. The form of the conversion statement is\n\n'%format1 %format2 ... ' % tuple\n\nwhere format1, format2 ... are the format specifications for each object in the tuple. Typically used format specifications are:\n\nwd Integer\nw.df Floating point notation\nw.de Exponential notation\n\nwhere 'w' is the width of the field and d is the number of digits after the decimal point. The output is right-justified in the specified field and padded with blank spaces (there are provisions for changing the justification and padding). A few examples:\n\n```python\nn=9876\n```\n\n\n```python\nprint('%7.2f'%a)\n```\n\n 1234.57\n\n\n\n```python\nprint('n=%6d'%n) # Pad with spaces\n```\n\n n= 9876\n\n\n\n```python\nprint('n=%06d'%n) # Pad with zeroes\n```\n\n n=009876\n\n\n\n```python\nprint('%12.4e %6d' %(a,n))\n```\n\n 1.2346e+03 9876\n\n\n# Exercise:\nCalculate and print on the screen a temperature conversion table from Fahrenheit to Celsius scales. The table should include temperatures from -300 to 210 degrees Fahrenheit (in steps of 5 \ndegrees) and their Celsius equivalents, presented in 2 columns \nwith appropriate headings. Each column should be 10 characters wide, and each temperature should have 3 digits to the right of the decimal point. The conversion formula is:\n\nC=(F-32)(5/9)\n# Reading from and writing to a file\nUp to this point, all data we have used has been either hard-coded into the program or has been obtained from or written to the screen. However, often we need to read from an external file, or write it to such a file. This is done through Python 'file' objects.\n\nA file object is created by opening a file with a given filename and mode. The filename could be given as an absolute path (from the root directory/folder up) or relative one (i.e. from the current working directory). 'Mode' is a string with one of the values given below, which indicates what the file will be used for (reading, writing, or both) and what type of data is being read/written (text, binary).\n\nmode meaning\nr text, read-only (the default)\nw text, write (an existing file with the same name will be overwritten)\na text, append to an existing file\nr+ text, reading and writing\nrb binary, read-only\nwb binary, write (an existing file with the same name will be overwritten)\nab binary, append to an existing file\nrb+ binary, reading and writing\n\nFor example:\n\n```python\nf=open('my_file.txt','w') # open a text file for writing\n```\nfile objects are closed with the 'close' method:\n\n```python\nf.close()\n```\nNote: Python automatically closes any open files when a program terminates.The 'write' method of a file object writes a string to the file (in Python3 it also returns the number of characters being written): \n\n```python\nf=open('my_file.txt','w') # open a text file for writing\n```\n\n\n```python\nf.write('Hello')\n```\n\n\n```python\nf.close()\n```\nTo read n bytes from a file we use the 'read' method, f.read(n). If n is omitted , the entire file is read in (it is your problem if the file is too large, as stated in the official documentation).\n\n'readline()' reads a single line from a file, up to nd including the newline ('\\n') character. Each subsequent call to 'readline' reads another line from the file. Both 'read' and 'readline' return an empty string when they reach the end of the file. To read all of the lines into a list of strings in one go, use 'f.readlines()'. \n\nA better method in practice is to use Numpy to read and write data to files (to be discussed later).\n# Functions\nWe have already encountered many internal Python functions. One can also define new, custom functions which behave the same way as the internal ones. The structure of a Python function is\n\ndef func_name(param1,param2,...):\n statements\n return return_values\n \n(again, note the indentations!), where 'param1, param2, ...' are the parameters. A parameter can be any Python object, including another function. Parameters may be given default values, in which case the parameter in the function call is optional. If the return statement or return values are omitted, the function returns the null object (i.e. nothing).\n\nThe following example computes numerically the first two derivatives of arctan(x) using finite differences (we will discuss this method later in the course, for now focus on the Python constructs only):\n\n```python\nfrom math import atan\ndef finite_diff(f,x,h=0.0001): # h has a default value\n df =(f(x+h) - f(x-h))/(2.0*h)\n ddf =(f(x+h) - 2.0*f(x) + f(x-h))/h**2\n return df,ddf\n\nx = 0.5\ndf,ddf = finite_diff(atan,x) # Uses default value of h\nprint 'First derivative =',df\nprint 'Second derivative =',ddf\n```\n\n First derivative = 0.799999999573\n Second derivative = -0.639999991892\n\n\nNote that the function atan (arctan) was passed to the function finite_diff as a parameter.\n\nThe number of input parameters in a function definition may be left arbitrary. For example, in the function definition\n\ndef func(x1,x2,*x3)\n\n'x1' and 'x2' are the usual parameters, also called positional parameters, whereas 'x3' is a tuple of arbitrary length containing the excess parameters (indicated by the star in front of x3). Calling this function with e.g.\n\nfunc(a,b,c,d,e)\n\nresults in the following correspondence between the parameters:\n\n\\begin{equation}\na \\leftrightarrow x1, b \\leftrightarrow x2, (c,d,e) \\leftrightarrow x3\n\\end{equation}\n\nThe positional parameters must always be listed before the excess parameters!\nIf a mutable object, such as a list, is passed to a function where it is then modified, the changes will also appear in the calling program. Here is an example:\n\n```python\ndef squares(a):\n for i in range(len(a)):\n a[i] = a[i]**2\n\na = [1, 2, 3, 4]\nsquares(a)\nprint(a) # the list a is now modified\n```\n\n [1, 4, 9, 16]\n\n\n# * syntax\nSometimes we want to call a function with arguments taken from a list \nor other sequence. The * syntax, used in a function call unpacks such a sequence into positional arguments to the function. \n\nHere is an example, using the function 'math.hypot(a,b)' (this is a function, in the 'math' package, which for given 'a' and 'b' returns sqrt{a^2+b^2}. If the two arguments are in a list or tuple, the following call will fail:\n\n```python\nimport math\n\nt=[3,4]\n\nmath.hypot(t)\n```\nThis is because we tried to call the function with a single (list) argument 't', while it requires two arguments. One can just index the list explicitly:\n\n```python\nmath.hypot(t[0],t[1])\n```\n\n\n\n\n 5.0\n\n\nwhich works fine, but a more elegant method is to unpack the object:\n\n```python\nmath.hypot(*t)\n```\n\n\n\n\n 5.0\n\n\n\n# Lambda Statement\nIf a function has the form of an expression, it can be defined with the \n'lambda' statement:\n\nfunc name = lambda param1, param2,...: expression\n\nThis is called an anonymous function (function literal) and useful for \ndefining small helper function that will be used only once. Here is an example:\n\n```python\nc = lambda x,y : x**2 + y**2\nprint c(3,4)\n```\n\n 25\n\n\n# Exercises:\n1) A year is a leap year if it is divisible by 4, unless it is a century that is not divisible by 400. Write a function that takes a year as a parameter and returns 'True' if the year is a leap one and 'False' otherwise.\n\n2) Write a function that takes two parameters - a pay rate and the number of hours worked -- and returns the total pay. Any hours over 40 paid at 1.5 times higher rate. ", "meta": {"hexsha": "492f0da340e06b8a3c6525b43e4cc56dcaf7dc4e", "size": 182042, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "ExamPrep/01 Intro to Python/__EXAMPLES 01 - Intro to Python.ipynb", "max_stars_repo_name": "FHomewood/ScientificComputing", "max_stars_repo_head_hexsha": "bc3477b4607b25a700f2d89ca4f01cb3ea0998c4", "max_stars_repo_licenses": ["IJG"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ExamPrep/01 Intro to Python/__EXAMPLES 01 - Intro to Python.ipynb", "max_issues_repo_name": "FHomewood/ScientificComputing", "max_issues_repo_head_hexsha": "bc3477b4607b25a700f2d89ca4f01cb3ea0998c4", "max_issues_repo_licenses": ["IJG"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ExamPrep/01 Intro to Python/__EXAMPLES 01 - Intro to Python.ipynb", "max_forks_repo_name": "FHomewood/ScientificComputing", "max_forks_repo_head_hexsha": "bc3477b4607b25a700f2d89ca4f01cb3ea0998c4", "max_forks_repo_licenses": ["IJG"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.6069207894, "max_line_length": 585, "alphanum_fraction": 0.5092835719, "converted": true, "num_tokens": 7780, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099069987088003, "lm_q2_score": 0.9353465147977104, "lm_q1q2_score": 0.8510783400323211}} {"text": "# Resolviendo sistemas de ecuaciones lineales\n\nEn su forma más general un sistema de ecuaciones lineales se ve como\n\n$$\n\\begin{align}\nA_{11} x_{1} + A_{12} x_{2} + \\ldots + A_{1M} x_M &= b_1 \\nonumber \\\\\nA_{21} x_{1} + A_{22} x_{2} + \\ldots + A_{2M} x_M &= b_2 \\nonumber \\\\\n&\\vdots \\nonumber \\\\\nA_{N1} x_{1} + A_{N2} x_{2} + \\ldots + A_{NM} x_M &= b_N \\nonumber \\\\\n\\end{align}\n$$\n\ndonde \n\n- $A_{ij}$ y $b_i$ son los coeficientes del sistema\n- $N$ es la cantidad de ecuaciones del sistema\n- $M$ es la cantidad de incógnitas del sistema\n\nEl sistema anterior puede escribirse de forma matricial como\n\n$$\nA x = b\n$$\n\ndonde $A \\in \\mathbb{R}^{N \\times M}$ y $b \\in \\mathbb{R}^N$ \n\nRevisemos a continuación como se resuelven problemas de este tipo utilizando `scipy.linalg` \n\n\n\n\n```python\n%matplotlib inline\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport numpy as np\nimport scipy.linalg\n```\n\n## Solución de un sistema cuadrado \n\n\nEste es un caso particular donde la matriz $A$ tiene igual número de filas y columnas ($N=M$)\n\nAsumiendo que la inversa de $A$ existe podemos resolver este sistema como\n\n$$\n\\begin{align}\nA x &= b \\nonumber \\\\\nA^{-1} A x &= A^{-1} b \\nonumber \\\\\nx &= A^{-1} b \\nonumber \n\\end{align}\n$$\n\ndonde $A A^{-1} = I$\n\nA continuación veremos como calcular la inversa de una matriz y resolver el sistema de ecuaciones cuadrado\n\n**Ejemplo** Sea el sistema de tres ecuaciones y tres incognitas\n\n$$\n\\begin{align}\nx_1 - 2x_2 + 3x_3 &= 4 \\\\\n2x_1 - 5x2 + 12x_3 &= 15 \\\\\n2x_2 - 10x_3 &= -10 \n\\end{align}\n$$\n\nque podemos reescribir como\n\n$$\n\\begin{pmatrix}\n1 & -2 & 3 \\\\\n2 & -5 & 12 \\\\\n0 & 2 & -10\n\\end{pmatrix} \\cdot\n\\begin{pmatrix}\nx_1 \\\\ x_2 \\\\ x_3\n\\end{pmatrix} =\n\\begin{pmatrix}\n4 \\\\\n15 \\\\\n-10\n\\end{pmatrix} \n$$\n\nde donde es directo identificar $A$ y $b$\n\n\n```python\nA = np.array([[1, -2, 3], [2, -5, 12], [0, 2, -10]])\nb = np.array([4, 15, -10])\n```\n\nDado que $A$ es una matriz cuadrada podemos intentar invertla la función [`inv`](https://docs.scipy.org/doc/scipy/reference/generated/scipy.linalg.inv.html#scipy.linalg.inv)\n\n\n```python\nAinv = scipy.linalg.inv(A)\nAinv\n```\n\n\n\n\n array([[-13. , 7. , 4.5],\n [-10. , 5. , 3. ],\n [ -2. , 1. , 0.5]])\n\n\n\nCon la inversa podemos resolver el problema con\n\n\n```python\nnp.dot(Ainv, b)\n```\n\n\n\n\n array([8., 5., 2.])\n\n\n\n:::{note}\n\nSi $A$ hubiera sido singular, es decir no invertible, la función `inv` hubiera retornado un `LinAlgError`\n\n:::\n\nPodemos verificar la invertibilidad de la matriz comprobando que su determinante sea distinto de cero\n\n\n```python\nscipy.linalg.det(A)\n```\n\n\n\n\n -1.9999999999999976\n\n\n\nOtra forma de verificar si una matriz es invertible es comprobar que todas sus columnas sean linealmente independientes (LI)\n\nEsto es equivalente a que su rango sea igual al número de columnas, lo cual se puede verificar con la función de `NumPy`\n\n\n```python\nnp.linalg.matrix_rank(A) == A.shape[1]\n```\n\n\n\n\n True\n\n\n\n**Resolviendo sistemas cuadrados eficientemente**\n\nEn general si sólo nos interesa $x$, podemos no realizar el cálculo explícito de $A^{-1}$. Si un sistema de ecuaciones es grande es preferible no calcular la inversa de $A$ debido al alto costo computacional necesario\n\nPodemos encontrar $x$ directamente en un sistema cuadrado usando la función [`solve`](https://docs.scipy.org/doc/scipy/reference/generated/scipy.linalg.solve.html#scipy.linalg.solve)\n\n\n```python\nscipy.linalg.solve(A, b)\n```\n\n\n\n\n array([8., 5., 2.])\n\n\n\nEl resultado es idéntico al anterior\n\nVeamos ahora la diferencia en eficiencia utilizando un sistema más grande\n\n\n```python\nN = 2000\nA_big = np.random.rand(N, N) # Matriz cuadrada\nb_big = np.random.rand(N, 1) # Vector\n%timeit -r5 -n5 np.dot(scipy.linalg.inv(A_big), b_big)\n%timeit -r5 -n5 scipy.linalg.solve(A_big, b_big)\n```\n\n 297 ms ± 15.7 ms per loop (mean ± std. dev. of 5 runs, 5 loops each)\n 193 ms ± 11.6 ms per loop (mean ± std. dev. of 5 runs, 5 loops each)\n\n\n\n```python\nnp.allclose(scipy.linalg.solve(A_big, b_big), np.dot(scipy.linalg.inv(A_big), b_big))\n```\n\n\n\n\n True\n\n\n\nUsar `solve` toma un poco más de la mitad del tiempo de utilizar `inv`+`dot`\n\n¿Cómo puede ser posible esto? \n\nLa respuesta es que `solve` realiza internamente una factorización del tipo\n\n$$\n\\begin{align}\nA x &= b \\nonumber \\\\\nLU x &= b \\nonumber \\\\\nL z &= b \\nonumber\n\\end{align}\n$$\n\nDonde $L$ es una matriz triangular inferior (lower) y $U$ es una matriz triangular superior (upper)\n\n$$\nL = \\begin{pmatrix} \nl_{11} & 0 & 0 & \\ldots & 0 & 0 \\\\ \nl_{21} & l_{22} & 0 &\\ldots & 0 & 0 \\\\ \n\\vdots & \\vdots & \\vdots & \\ddots & \\vdots & \\vdots \\\\\nl_{N1} & l_{N2} & l_{N3} & \\ldots & l_{N(N-1)} & l_{NN} \\\\ \n\\end{pmatrix} \\quad\nU = \\begin{pmatrix} \nu_{11} & u_{11} & u_{13} & \\ldots & u_{1(N-1)} & u_{1N} \\\\ \nu_{21} & u_{22} & u_{32} &\\ldots & u_{2(N-1)} & 0 \\\\ \n\\vdots & \\vdots & \\vdots &\\ldots & \\ddots & \\vdots \\\\\nu_{N1} & 0 & 0 & \\ldots & 0 & 0\\\\ \n\\end{pmatrix}\n$$\n\nLuego $z$ se puede obtener recursivamente\n\n$$\nz_1 = \\frac{b_1}{l_{11}}\n$$\n$$\nz_2 = \\frac{b_2 - l_{21} z_1}{l_{22}}\n$$\n$$\nz_i = \\frac{b_i - \\sum_{j=1}^{i-1} l_{ij} z_j}{l_{ii}}\n$$\n\ny $x$ se puede obtener recursivamente de $z$\n\nEn caso de necesitar los factores LU podemos realizar la factorización en `scipy` con [`linalg.lu`](https://docs.scipy.org/doc/scipy/reference/generated/scipy.linalg.lu.html#scipy.linalg.lu)\n\n\n```python\nP, L, U = scipy.linalg.lu(A)\nL, U\n```\n\n\n\n\n (array([[1. , 0. , 0. ],\n [0. , 1. , 0. ],\n [0.5 , 0.25, 1. ]]),\n array([[ 2. , -5. , 12. ],\n [ 0. , 2. , -10. ],\n [ 0. , 0. , -0.5]]))\n\n\n\n## Solución de un sistema rectangular \n\n\nConsideremos que\n\n- Las incógnitas de un sistema representan sus grados de libertad\n- Las ecuaciones de un sistema representan sus restricciones\n\nSi tenemos un sistema \n\n- con más ecuaciones que incógnitas ($N>M$): el sistema está sobredeterminado \n- con más incógnitas que ecuaciones ($M>N$): el sistema está infradeterminado\n\n:::{warning}\n\nEn ambos casos la matriz $A$ ya no es cuadrada, es decir ya no podemos calcular la inversa\n\n:::\n\nSin embargo podemos utilizar otros métodos, como mostraremos a continuación\n\n**Caso N>M**\n\nSea el vector de error $e = Ax - b$ de un sistema con más ecuaciones que incognitas. \n\nPodemos encontrar una solución aproximada minimizando la norma euclidiana del error\n\n$$\n\\begin{align}\n\\hat x &= \\min_x \\|e\\|_2^2 \\nonumber \\\\\n& = \\min_x e^T e \\nonumber \\\\\n& = \\min_x (Ax -b)^T (Ax -b) \\nonumber \\\\\n\\end{align}\n$$\n\nLo cual se conoce como el **Problema de mínimos cuadrados**\n\nPara continuar tomamos la última expresión y derivamos con respecto a $x$\n\n$$\n\\begin{align}\n\\frac{d}{dx} (A x - b)^T (A x -b) &= 2 A^T (A x -b) \\nonumber \\\\\n&= 2A^T A x - 2A^T b = 0 \\nonumber \\\\\n\\rightarrow \\hat x &= (A^T A)^{-1} A^T b \\nonumber \\\\\n&= A^{\\dagger} b \\nonumber \\\\\n\\end{align}\n$$\n\ndonde $A^{\\dagger} = (A^T A)^{-1} A^T$ se conoce como la pseudo-inversa de [Moore-Penrose](https://en.wikipedia.org/wiki/Moore%E2%80%93Penrose_inverse)\n\n**Caso M>N**\n\nLa consecuencia de que el sistema sea infradeterminado es que $A^T A$ no es invertible. \n\nPara resolver el problema infradeterminado se debe agregar una restricción adicional. La más típica es que el vector solución tenga norma mínima, por ejemplo\n\n$$\n\\min_\\theta \\| x \\|_2^2 ~\\text{s.a.}~ Ax =b\n$$\n\nque se resuelve usando $M$ [multiplicadores de Lagrange](https://es.wikipedia.org/wiki/Multiplicadores_de_Lagrange) $\\lambda$ como sigue\n\n$$\n\\begin{align}\n\\frac{d}{dx} \\| x\\|_2^2 + \\lambda^T (b - Ax) &= 2x - \\lambda^T A \\nonumber \\\\\n&= 2Ax - A A^T \\lambda \\nonumber \\\\\n&= 2b - A A^T \\lambda = 0 \n\\end{align}\n$$\n\nDe donde obtenemos que \n\n$$\n\\lambda = 2(AA^T)^{-1}b\n$$ \n\ny por lo tanto \n\n$$\n\\hat x = \\frac{1}{2} A^T \\lambda = A^T (A A^T)^{-1} b,\n$$\n\ndonde $A^T (A A^T)^{-1}$ se conoce como la pseudo-inversa \"por la derecha\"\n\n**Resolviendo el sistema rectangular con Python**\n\nSea un sistema de ecuaciones lineales con $N\\neq M$. Podemos usar scipy para\n\n- Calcular la matriz pseudo inversa: [`scipy.linalg.pinv`](https://docs.scipy.org/doc/scipy/reference/generated/scipy.linalg.pinv.html)\n- Obtener la solución del sistema directamente: [`scipy.linalg.lstsq`](https://docs.scipy.org/doc/scipy/reference/generated/scipy.linalg.lstsq.html)\n\nSi $N>M$ se utiliza la pseudoinversa por la izquierda y la solución de mínimos cuadrados. En cambio si $M>N$ se utiliza la pseudoinversa para la derecha y la solución de multiplicadores de Lagrange\n\n**Ejemplo:** Sea el siguiente set de datos de un estudio realizado en los años 50\n\nReferencia: [A handbook of small datasets](https://www.routledge.com/A-Handbook-of-Small-Data-Sets/Hand-Daly-McConway-Lunn-Ostrowski/p/book/9780367449667)\n\n\n```python\ndf = pd.read_csv('data/helados.csv', index_col=0)\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
consincomepricetemp
10.386780.27041
20.374790.28256
30.393810.27763
40.425800.28068
50.406760.27269
\n
\n\n\n\ndonde cada fila corresponde a un día las columnas corresponde a \n\n- consumo de helados promedio ([pintas](https://en.wikipedia.org/wiki/Pint) per capita)\n- ingreso familiar promedio (dolares)\n- temperatura promedio (grados Fahrenheit)\n- precio promedio de los helados (dolares)\n\nAhora consideremos la siguiente pregunta\n\n> ¿Está el consumo de helados influenciado por la temperatura?\n\nIntentemos responder esta pregunta en base al siguiente modelo\n\n$$\n\\text{cons} = \\theta_0 + \\theta_1 \\cdot \\text{temp}\n$$\n\nque corresponde a un sistema de ecuaciones lineales de dos incognitas y \n\n\n```python\nf\"{len(df)} ecuaciones\"\n```\n\n\n\n\n '30 ecuaciones'\n\n\n\nEs decir que es un sistema sobredeterminado\n\n$$\n\\begin{pmatrix}\ncons[0] \\\\ cons[1] \\\\ \\vdots \\\\ cons[{29}]\n\\end{pmatrix} = \n\\begin{pmatrix}\n1&temp[0] \\\\ 1&temp[1] \\\\ \\vdots & \\vdots \\\\ 1 & temp[29]\n\\end{pmatrix} \n\\begin{pmatrix}\n\\theta_0 \\\\ \\theta_1\n\\end{pmatrix} \n$$\n\nque podemos resolver utilizando `lstsq`\n\n\n```python\nA = np.ones(shape=(len(df), 2))\nA[:, 1] = df[\"temp\"].values\nb = df[\"cons\"].values\n\ntheta, residuals, rank, s = scipy.linalg.lstsq(A, b)\ntheta\n```\n\n\n\n\n array([0.20686215, 0.00310736])\n\n\n\nLa tupla retornada contiene\n\n- `theta`: El resultado buscado\n- `residuals`: La norma del error al cuadrado\n- `rank`: El rango de $A$\n- `s`: Los valores singulares de $A$\n\nAnalicemos gráficamente la solución obtenida\n\n\n```python\nfig, ax = plt.subplots(tight_layout=True)\nax.scatter(df[\"temp\"], df[\"cons\"], s=5, c='k', label='observaciones')\nax.set_xlabel('Temperatura [F]')\nax.set_ylabel('Consumo promedio')\ntemp_modelo = np.linspace(df[\"temp\"].min(), df[\"temp\"].max(), num=200)\ncons_modelo = temp_modelo*theta[1] + theta[0]\nax.plot(temp_modelo, cons_modelo, label='modelo')\nax.legend();\n```\n\nDe donde podemos observar que el consumo promedio tiende al alza con la temperatura promedio\n\n:::{note}\n\nLo que acabamos de resolver es un problema conocido como **regresión lineal**. Más adelante veremos una forma más general de este problema\n\n:::\n\n## Análisis de errores y *condition number*\n\nIncluso aunque una matriz sea matemáticamente invertible (determinante distinto de cero), podríamos no ser capaces de resolver el problema numéricamente\n\nImaginemos una pequeña variación en $b$ denominada $\\delta b$. Esta variación provoca a su vez una pequeña variación en $x$ denominada $\\delta x$\n\nSe puede encontrar una cota que compara el error relativo de $b$ y $x$ como\n\n$$\n\\frac{\\| \\delta x \\|}{\\|x\\|} \\leq \\frac{\\| A^{-1} \\| \\|\\delta b\\|}{\\|x\\|} = \\|A^{-1}\\| \\|A\\| \\frac{\\| \\delta b \\|}{\\|b\\|} \n$$\n\ndonde se usó que $A \\delta x = \\delta b$ (propiedad de linealidad)\n\n:::{note}\n\nEsto significa que un pequeño error relativo en $b$ puede causar un gran error en $x$ \n\n:::\n\nEl estimador de $\\|A^{-1}\\| \\|A\\|$ es lo que se conoce como *condition number*\n\nUn sistema se dice \"bien condicionado\" si este valor es cercano a $1$ y \"mal condicionado\" si es mucho mayor que $1$.\n\nPodemos calcular el *condition number* con la función de NumPy `cond` como se muestra a continuación\n\n```python\nnp.linalg.cond(x, # Arreglo multidimensional\n p # El orden de la norma: 1, 2, 'fro',...\n )\n```\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "87e2d632ab5acf8cbfcf67321b364d8e0e925ea3", "size": 39137, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "contents/linalg/linalg1.ipynb", "max_stars_repo_name": "phuijse/PythonBook", "max_stars_repo_head_hexsha": "16792e9cc3717ebb7f3603cd8bb39613dd66521b", "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": "contents/linalg/linalg1.ipynb", "max_issues_repo_name": "phuijse/PythonBook", "max_issues_repo_head_hexsha": "16792e9cc3717ebb7f3603cd8bb39613dd66521b", "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": "contents/linalg/linalg1.ipynb", "max_forks_repo_name": "phuijse/PythonBook", "max_forks_repo_head_hexsha": "16792e9cc3717ebb7f3603cd8bb39613dd66521b", "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": 45.4552845528, "max_line_length": 15748, "alphanum_fraction": 0.6850806143, "converted": true, "num_tokens": 4418, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625107731764, "lm_q2_score": 0.91367652458901, "lm_q1q2_score": 0.8510554296281891}} {"text": "# Special Series Solutions\n\n\n```python\n%matplotlib inline\nfrom sympy import *\ninit_printing()\n```\n\n\n```python\nx, t = symbols('x, t')\n```\n\nSymPy can compute special series like formal power series and fourier series. This is a new feature released in SymPy 1.0\n\nLet's try computing formal power series of some basic functions.\n\n\n```python\nexp_series = fps(exp(x), x)\nexp_series\n```\n\nThis looks very similar to what ``series`` has to offer, but unlike series a formal power series object returns an infinite expansion.\n\n\n```python\nexp_series.infinite # Infinite representation\n```\n\n\n\n\n$$\\sum_{k=1}^{\\infty} \\begin{cases} \\frac{x^{k}}{k!} & \\text{for}\\: \\operatorname{Mod}{\\left (k,1 \\right )} = 0 \\\\0 & \\text{otherwise} \\end{cases} + 1$$\n\n\n\nWe can easily find out any term of the expansion (no need to recompute the expansion).\n\n\n```python\nexp_series.term(51) # equivalent to exp_series[51]\n```\n\n\n```python\nexp_series.truncate(10) # return a truncated series expansion\n```\n\n# Exercise\n\nTry computing the formal power series of $\\log(1 + x)$. Try to look at the infinite representation. What is the 51st term in this case? Compute the expansion about 1.\n\n\n```python\nlog_series = fps(log(1 + x), x)\nlog_series\n```\n\n\n```python\n# infinite representation\nlog_series.infinite\n```\n\n\n```python\n# 51st term\nlog_series.term(51)\n```\n\n\n```python\n# expansion about 1\nfps(log(1 + x), x, x0=1)\n```\n\n# Fourier Series\n\nFourier series for functions can be computed using ``fourier_series`` function.\n\nA sawtooth wave is defined as:\n 1. $$ s(x) = x/\\pi \\in (-\\pi, \\pi) $$\n 2. $$ s(x + 2k\\pi) = s(x) \\in (-\\infty, \\infty) $$\n \nLet's compute the fourier series of the above defined wave.\n\n\n```python\nsawtooth_series = fourier_series(x / pi, (x, -pi, pi))\nsawtooth_series\n```\n\n\n```python\nplot(sawtooth_series.truncate(50)) \n```\n\nSee https://en.wikipedia.org/wiki/Gibbs_phenomenon for why the fourier series has peculiar behavior near jump discontinuties.\n\nJust like formal power series we can index fourier series as well.\n\n\n```python\nsawtooth_series[51]\n```\n\nIt is easy to shift and scale the series using ``shift`` and ``scale`` methods.\n\n\n```python\nsawtooth_series.shift(10).truncate(5)\n```\n\n\n```python\nsawtooth_series.scale(10).truncate(5)\n```\n\n# Exercise\n\nConsider a square wave defined over the range of (0, 1) as:\n 1. $$ f(t) = 1 \\in (0, 1/2] $$\n 2. $$ f(t) = -1 \\in (1/2, 1) $$\n 3. $$ f(t + 1) = f(t) \\in (-\\infty, \\infty) $$\n \nTry computing the fourier series of the above defined function. Also, plot the computed fourier series.\n\n\n```python\nsquare_wave = Piecewise((1, t <= Rational(1, 2)), (-1, t > Rational(1, 2)))\n```\n\n\n```python\nsquare_series = fourier_series(square_wave, (t, 0, 1))\nsquare_series\n```\n\n\n```python\nplot(square_series.truncate(50))\n```\n\n# What next?\n\nTry some basic operations like addition, subtraction, etc on formal power series, fourier series and see what happens. \n", "meta": {"hexsha": "a96f09a95847608df9ebd5d8f64a126d3b9847ed", "size": 98722, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "tutorial_exercises/Advanced - Special Series Solutions.ipynb", "max_stars_repo_name": "gvvynplaine/scipy-2016-tutorial", "max_stars_repo_head_hexsha": "aa417427a1de2dcab2a9640b631b809d525d7929", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 53, "max_stars_repo_stars_event_min_datetime": "2016-06-21T21:11:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-04T07:51:03.000Z", "max_issues_repo_path": "tutorial_exercises/Advanced - Special Series Solutions.ipynb", "max_issues_repo_name": "gvvynplaine/scipy-2016-tutorial", "max_issues_repo_head_hexsha": "aa417427a1de2dcab2a9640b631b809d525d7929", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 11, "max_issues_repo_issues_event_min_datetime": "2016-07-02T20:24:06.000Z", "max_issues_repo_issues_event_max_datetime": "2016-07-11T11:31:44.000Z", "max_forks_repo_path": "tutorial_exercises/Advanced - Special Series Solutions.ipynb", "max_forks_repo_name": "gvvynplaine/scipy-2016-tutorial", "max_forks_repo_head_hexsha": "aa417427a1de2dcab2a9640b631b809d525d7929", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 36, "max_forks_repo_forks_event_min_datetime": "2016-06-25T09:04:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-09T06:46:01.000Z", "avg_line_length": 153.7725856698, "max_line_length": 22746, "alphanum_fraction": 0.8672636292, "converted": true, "num_tokens": 858, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625012602594, "lm_q2_score": 0.9136765263519308, "lm_q1q2_score": 0.8510554225785547}} {"text": "## 1. Basic Design of the Model\n1. Output of the model: 0 or 1 (Binary Classification)\n2. Hypothesis to be tested: $Z = W \\cdot X + b$\n3. Activation Function: $\\frac{1}{1 + e^{-x}} $ (Signmoid Function)\n\n## 2. Import Packages\n\n1. numpy\n2. matplotlib\n3. seaborn\n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n%matplotlib inline\n\n# Next Libraries are unimportant, they just make everyhting look better\n\nimport matplotlib.style as style\nimport seaborn as sns\n\nstyle.use('seaborn-poster') #sets the size of the charts\nstyle.use('ggplot')\n```\n\n## 3. Loading the dataset\n\n\n\n```python\ndataset = np.load('dataset.npz', encoding='ASCII')\n## Get the numpy arrays from the dictionary\nX_train = dataset['X_train']\nY_train = dataset['Y_train']\nX_test = dataset['X_test']\nY_test = dataset['Y_test']\n```\n\n\n```python\nprint(X_train.shape)\nprint(Y_train.shape)\nprint(X_test.shape)\nprint(Y_test.shape)\n```\n\n (784, 8000)\n (1, 8000)\n (784, 2000)\n (1, 2000)\n\n\n\n```python\nidx = np.random.randint(X_train.shape[1])\n\nplt.imshow(X_train[:, idx].reshape(28, 28))\n\nlabel = \"cat\" if Y_train[:, idx][0] else \"bat\"\nprint(f\"Label: {label}\")\n```\n\n## 4. Normalizing the data\n\nNormalizing the data with the following equation:\n\n$$ X_{norm} = \\frac {X - X_{min}}{X_{max} - X_{min}} $$\n\nFor this pixel data, $X_{max} = 255$ and $X_{min} = 0$\n\n> After running the next cell, go back and view the raw array again\n\n\n```python\n## Normalizing the training and testing data\nX_min = 0\nX_max = 255\nX_train = X_train / X_max\nX_test = X_test / X_max\n```\n\n## 5. Helper functions for the Model:\n\n### Sigmoid Function and Initialize Parameters function \n\n\n```python\ndef sigmoid(z):\n \"\"\"\n Computes the element sigmoid of scalar or numpy array(element wise)\n \n Arguments:\n z: Scalar or numpy array\n \n Returns:\n s: Sigmoid of z (element wise in case of Numpy Array)\n \"\"\"\n s = 1/(1+np.exp(-z))\n \n return s\n```\n\n\n```python\ndef initialize_parameters(n_x):\n \"\"\"\n Initializes w to a zero vector, and b to a 0 with datatype float \n \n Arguments:\n n_x: Number of features in each sample of X\n \n Returns:\n w: Initialized Numpy array of shape (1, n_x) (Weight)\n b: Initialized Scalar (bias)\n \"\"\"\n\n w = np.full((1,X_train.shape[0]),0)\n b = 0\n \n return w, b\n\n```\n\nHere is a summary of the equations for Forward Propagation and Backward Propagation we have used so far:\n\nFor m training examples $ X_{train} $ and $ Y_{train} $:\n\n### 5.1 Forward Propagation\n\n$$ Z^{(i)} = w \\cdot X_{train}^{(i)} + b $$\n\n$$ \\hat Y^{(i)} = A^{(i)} = \\sigma(Z^{(i)}) = sigmoid(Z^{(i)}) $$\n\n$$ \\mathcal{L}(\\hat Y^{(i)}, Y_{train}^{(i)}) = \\mathcal{L}(A^{(i)}, Y_{train}^{(i)}) = -[Y_{train}^{(i)} \\log(A^{(i)}) + (1 - Y_{train}^{(i)}) \\log(1 - A^{(i)})] $$\n\n$$ J = \\frac{1}{m} \\sum_1^m \\mathcal{L} (A^{(i)}, Y_{train}^{(i)}) $$\n\n\n### 5.2 Backward Propagation - Batch Gradient Descent\n\n$$ \\frac{\\partial J}{\\partial w} = \\frac{1}{m} (A - Y) \\cdot X^T $$\n\n$$ \\frac{\\partial J}{\\partial b} = \\frac{1}{m} \\sum_1^m (A - Y) $$\n\n\n> Note: $ \\frac{\\partial J}{\\partial w} $ is represented as dw, and $ \\frac{\\partial J}{\\partial b}$ is represented as db\n\n\n\n```python\ndef compute_cost(A, Y, m):\n \"\"\"\n Calculates the Cost using the Cross Entropy Loss\n \n Arguments:\n A: Computer Probabilities, numpy array\n Y: Known Labels, numpy array\n \n Returns:\n cost: The computed Cost\n \"\"\"\n cost = np.sum(((- np.log(A))*Y + (-np.log(1-A))*(1-Y)))/m\n \n return np.squeeze(cost)\n```\n\n\n```python\ndef propagate(w, b, X, Y):\n \"\"\"\n Performs forward and backward propagation for the Logistic Regression model\n \n Arguments:\n w: The Weight Matrix of dimension (1, n_x)\n b: Bias\n X: Input Matrix, with shape (n_x, m)\n Y: Label Matrix of shape (1, m)\n \n Returns:\n dw: Gradient of the weight matrix\n db: Gradient of the bias\n cost: Cost computed on Calculated Probability, and output Label\n \"\"\"\n m = X.shape[1]\n \n A = sigmoid((w @ X)+b)\n cost = compute_cost(A, Y, m)\n dw = (np.dot(X,(A-Y).T).T)/m\n db = (np.sum(A-Y))/m\n\n assert(dw.shape == w.shape)\n assert(db.dtype == float)\n return dw, db, cost\n \n```\n\n### 5.3 Optimization\n\nFor a parameter $ \\theta $, the gradient descent update rule is given by:\n$$ \\theta := \\theta - \\alpha \\frac{\\partial J}{\\partial \\theta} $$\n\nwhere $\\alpha$ is the learning rate\n\n\n```python\ndef fit(w, b, X, Y, num_iterations, learning_rate, print_freq=100):\n \"\"\"\n Given the parameters of the model, fits the model corresponding to the given Input Matrix aand output labels, by performing batch gradient descent for given number of iterations.\n \n Arguments:\n w: The Weight Matrix of dimension (1, n_x)\n b: Bias\n X: Input Matrix, with shape (n_x, m)\n Y: Label Matrix of shape (1, m)\n num_iterations: The number of iteratios of bgd to be performed\n print_freq: Frequency of recording the cost\n Returns:\n w: Optimized weight matrix\n b: optimized bias\n costs: print the cost at frequency given by print_freq, no prints if freq is 0\n \"\"\"\n \n costs = []\n for i in range(num_iterations):\n ## 1. Calculate Gradients and cost\n dw, db, cost = propagate(w, b, X, Y)\n \n costs.append(cost)\n \n if print_freq and i % print_freq == 0:\n print(f\"Cost after iteration {i}: {cost}\")\n \n ## 2. Update parameters\n w = w - (learning_rate*dw)\n b = b - (learning_rate*db)\n\n \n return w, b, costs\n \n```\n\n### 5.4 Prediction\nUsing the following equation to determine the class that a given sample belongs to:\n\n$$\n\\begin{equation}\n Y_{prediction}^{(i)} =\n \\begin{cases} \n 1 \\text{, if } \\hat Y^{(i)} \\ge 0.5\\\\\n 0 \\text{, if } \\hat Y^{(i)} \\lt 0.5\\\\\n \\end{cases}\n\\end{equation}\n$$\n\n\n\n```python\ndef predict(w, b, X):\n \"\"\"\n Predicts the class which the given feature vector belongs to given Weights and Bias of the model\n \n Arguments:\n w: The Weight Matrix of dimension (1, n_x)\n b: Bias\n X: Input Matrix, with X.shape[0] = n_X\n Returns:\n Y_prediction: Predicted labels\n \"\"\"\n \n m = X.shape[1]\n Y_prediction = np.full((1,m),0)\n A = sigmoid((w @ X) + b)\n Y_prediction = (A >= 0.5) * 1.0\n \n return Y_prediction\n```\n\n## 6. Building the Model\n\nNow we have assembled all the individual pieces required to create the Logistic Regression model.\nNext function is creating the model and calculating its train and test accuracy. \n\n\n\n\n```python\ndef model(X_train, Y_train, X_test, Y_test, num_iterations, learning_rate, print_freq):\n \"\"\"\n Creates a model and fit it to the train and test data. Use this model to compute the train and test accuracy after 2500 iterations\n \n Arguments:\n X_train: Training Data X\n Y_train: Training Data Y\n X_test: Testing Data X\n Y_test: Testing data Y\n num_iterations: Number of iterations of bgd to perform\n learning_rate: Learning Rate of the model\n print_freq: Frequency of recording the cost\n Returns:\n -None-\n \"\"\"\n \n w, b = initialize_parameters(X_train.shape[0])\n w, b, costs = fit(w, b, X_train, Y_train, num_iterations, learning_rate, print_freq)\n \n Y_prediction_train = predict(w, b, X_train)\n Y_prediction_test = predict(w, b, X_test)\n \n costs = np.squeeze(costs)\n \n\n print(f\"train accuracy: {100 - np.mean(np.abs(Y_prediction_train - Y_train)) * 100} %\")\n print(f\"test accuracy: {100 - np.mean(np.abs(Y_prediction_test - Y_test)) * 100} %\")\n \n plt.plot(costs)\n \n plt.ylabel('cost')\n plt.xlabel('iterations (per hundreds)')\n plt.title(f\"Learning rate = {learning_rate}\")\n plt.show()\n \n```\n\n\n```python\nmodel(X_train, Y_train, X_test, Y_test, num_iterations=2000, learning_rate=0.1, print_freq=100)\n```\n", "meta": {"hexsha": "8193b0bddc60c95cc3480313ddcaef57f183ba10", "size": 43847, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Cat Classification.ipynb", "max_stars_repo_name": "DeepC004/Cat-Classification", "max_stars_repo_head_hexsha": "beaba641189d5e6960f4ee9d4104ba4f63ce2795", "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": "Cat Classification.ipynb", "max_issues_repo_name": "DeepC004/Cat-Classification", "max_issues_repo_head_hexsha": "beaba641189d5e6960f4ee9d4104ba4f63ce2795", "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": "Cat Classification.ipynb", "max_forks_repo_name": "DeepC004/Cat-Classification", "max_forks_repo_head_hexsha": "beaba641189d5e6960f4ee9d4104ba4f63ce2795", "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": 76.1232638889, "max_line_length": 15982, "alphanum_fraction": 0.749903072, "converted": true, "num_tokens": 2276, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947070591976, "lm_q2_score": 0.9005297807787537, "lm_q1q2_score": 0.8509958763851018}} {"text": "# ODE\n\nWe will solve the following linear Cauchy model\n\n\\begin{align}\ny^{\\prime}(t) &= \\lambda y(t)\\\\\ny(0) & = 1\n\\end{align}\n\nwhose exact solution is\n\n$$\ny(t) = e^{\\lambda t}\n$$\n\n\n\n```python\n%matplotlib inline\nfrom numpy import *\nfrom matplotlib.pyplot import *\nimport scipy.linalg\nimport numpy.linalg\n```\n\n\n```python\nl = -5. # lamba (see formula above)\nt0 = 0. # initial time\ntf = 10. # final time\ny0 = 1. # boundary condition\n\ns = linspace(t0,tf,5000)\nexact = lambda x: exp(l*x) # exact solution\n```\n\n### Forward Euler\n\n$$\n\\frac{y_{n}-y_{n-1}}{h} = f(y_{n-1}, t_{n-1})\n$$\n\n\n```python\ndef fe(l,y0,t0,tf,h):\n timesteps = arange(t0,tf+1e-10, h)\n sol = zeros_like(timesteps)\n sol[0] = y0\n for i in range(1,len(sol)):\n sol[i] = sol[i-1]*(1+l*h)\n \n return sol, timesteps\n\ny, t = fe(l,y0,t0,tf,0.1)\n_ = plot(t,y, 'o-')\n_ = plot(s,exact(s))\n\nerror = numpy.linalg.norm(exact(t) - y, 2)\nprint(error)\n```\n\n### Backward Euler\n\n$$\n\\frac{y_{n}-y_{n-1}}{h} = f(y_{n}, t_{n})\n$$\n\n\n```python\ndef be(l,y0,t0,tf,h):\n timesteps = arange(t0, tf+1e-10, h)\n sol = zeros_like(timesteps)\n sol[0] = y0\n for i in range(1, len(sol)):\n sol[i] = sol[i-1]/(1-l*h)\n\n return sol, timesteps\n\ny,t = be(l, y0, t0, tf, 0.1)\n_ = plot(t, y, 'o-')\n_ = plot(s, exact(s))\n\nerror = numpy.linalg.norm(exact(t)-y, infty)\nprint(error)\n```\n\n### $\\theta$-method\n\n$$\n\\frac{y_{n}-y_{n-1}}{h} = \\theta\\, f(y_{n}, t_{n}) + (1-\\theta)\\,f(y_{n-1}, t_{n-1})\n$$\n\n\n```python\ndef tm(theta,l,y0,t0,tf,h):\n timesteps = arange(t0, tf+1e-10, h)\n sol = zeros_like(timesteps)\n sol[0] = y0\n for i in range(1, len(sol)):\n sol[i] = theta*sol[i-1]/(1-l*h) + (1. - theta)*sol[i-1]*(1+l*h)\n\n return sol, timesteps\n\ny,t = tm(0.5, l, y0, t0, tf, 0.1)\n_ = plot(t, y, 'o-')\n_ = plot(s, exact(s))\n\nerror = numpy.linalg.norm(exact(t) - y, infty)\nprint(error)\n```\n\n### Simple adaptive time stepper\n\nFor each time step:\n- Compute solution with CN\n- Compute solution with BE\n- Check the difference\n- If the difference satisfy a given tolerance:\n - keep the solution of higher order\n - double the step size\n - go to the next step\n- Else:\n - half the step size and repeat the time step\n\n\n```python\ndef adaptive(l,y0,t0,tf,h0, hmax=0.9,tol=1e-3):\n sol = []\n sol.append(y0)\n t = []\n t.append(t0)\n h = h0\n while t[-1] < tf:\n #print 'current t =', t[-1], ' h=', h\n current_sol = sol[-1]\n current_t = t[-1]\n sol_cn, _ = tm(0.5,l,current_sol,current_t, current_t + h, h)\n sol_be, _ = tm(1.,l,current_sol,current_t, current_t + h, h)\n \n if (abs(sol_cn[-1] - sol_be[-1]) < tol): #accept\n sol.append(sol_cn[-1])\n t.append(current_t+h)\n h *= 2.\n if h > hmax:\n h=hmax\n else:\n h /= 2.\n \n return sol, t\n\ny,t = adaptive(l,y0,t0,tf,0.9)\n_ = plot(t,y, 'o-')\n_ = plot(s,exact(array(s)))\n\nerror = numpy.linalg.norm(exact(array(t)) - y, infty)\nprint(error, len(y))\n```\n", "meta": {"hexsha": "40ee35fda98d92afd1479d68c4221de22a8c4e31", "size": 46648, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/GR_lab06a_ODEs_1.ipynb", "max_stars_repo_name": "mapenzo-ph/numerical-analysis-2021-2022", "max_stars_repo_head_hexsha": "952808d7fa7a9e718274592104be24882acef3ec", "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": "notebooks/GR_lab06a_ODEs_1.ipynb", "max_issues_repo_name": "mapenzo-ph/numerical-analysis-2021-2022", "max_issues_repo_head_hexsha": "952808d7fa7a9e718274592104be24882acef3ec", "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": "notebooks/GR_lab06a_ODEs_1.ipynb", "max_forks_repo_name": "mapenzo-ph/numerical-analysis-2021-2022", "max_forks_repo_head_hexsha": "952808d7fa7a9e718274592104be24882acef3ec", "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": 129.938718663, "max_line_length": 10310, "alphanum_fraction": 0.8523623735, "converted": true, "num_tokens": 1094, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391643039738, "lm_q2_score": 0.9219218428996602, "lm_q1q2_score": 0.8509699674236818}} {"text": "# 逆行列を求める方法\n\n- `np.linalg` に `inv` という関数がある\n\n\n```python\nimport numpy as np\n```\n\n\n```python\na = np.array([[3, 1, 1], [1, 2, 1], [0, -1, 1]])\n```\n\n\n```python\nnp.linalg.inv(a)\n```\n\n\n\n\n array([[ 0.42857143, -0.28571429, -0.14285714],\n [-0.14285714, 0.42857143, -0.28571429],\n [-0.14285714, 0.42857143, 0.71428571]])\n\n\n\n# ひとつの連立方程式を解く方法\n\n下記の連立方程式を解くには逆行列を求めるよりも `solve` 関数を使うほうが良い。(高速かつ数値安定的なアルゴリズムを背後で利用しているため)\n\n\\begin{equation}\n\\begin{pmatrix}\n3& 1& 1\\\\\n1& 2& 1\\\\\n0& -1& 1\n\\end{pmatrix}\n\\begin{pmatrix}\nx \\\\ y\\\\ z\n\\end{pmatrix}\n=\n\\begin{pmatrix}\n1 \\\\ 2 \\\\ 3\n\\end{pmatrix}\n\\end{equation}\n\n\n```python\nb = np.array([[3, 1, 1], [1, 2, 1], [0, -1, 1]])\n```\n\n\n```python\nc = np.array([1, 2, 3])\n```\n\n\n```python\nnp.linalg.solve(b, c)\n```\n\n\n\n\n array([-0.57142857, -0.14285714, 2.85714286])\n\n\n\n# 同じ係数行列からなく複数の連立方程式を解く方法\n\n\\begin{equation}\nAx=b_1, Ax=b_2, \\dots, Ax=b_m\n\\end{equation}\nとなる連立方程式があったときは、 $A^{-1}$ を計算することで、\n\n\\begin{equation}\nA^{-1}b_1, A^{-1}b_2, \\dots, A^{-1}b_m\n\\end{equation}\n\nと解が計算できる。しかし、もっと良い方法がある。\n\n## LU分解\n\n$A=PLU$ の形に分解することで連立方程式を高速かつ数値安定的に解くことができる。\n\nここで $L$ は下三角行列で対角成分が $1$ となるもの、 $U$ は上三角行列、 $P$ は各行に $1$ となる成分がただひとつだけある行列でそのほかの成分は $0$(置換行列)\n\n\\begin{equation}\nPLUx = b\n\\end{equation}\n\nという連立方程式は次の3つの方程式を逐次的に解くことで解 $x$ を求めることができる。\n\n\\begin{align}\nUz &= b \\\\\nLy &= z \\\\\nPx &= y\n\\end{align}\n\n\n```python\n# scipy を利用\nfrom scipy import linalg\n```\n\n\n```python\na = np.array([[3, 1, 1], [1, 2, 1], [0, -1, 1]])\nb = np.array([1, 2, 3])\n```\n\n\n```python\nlu, p = linalg.lu_factor(a)\nlinalg.lu_solve((lu, p), b)\n```\n\n\n\n\n array([-0.57142857, -0.14285714, 2.85714286])\n\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "3c7d876a06b6931b103f45efa16f6673a3092cdc", "size": 4575, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/linear_equations.ipynb", "max_stars_repo_name": "515hikaru/essence-of-machine-learning", "max_stars_repo_head_hexsha": "7f46be9316d227626f27a06deac64b43191cb4d7", "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/linear_equations.ipynb", "max_issues_repo_name": "515hikaru/essence-of-machine-learning", "max_issues_repo_head_hexsha": "7f46be9316d227626f27a06deac64b43191cb4d7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11, "max_issues_repo_issues_event_min_datetime": "2018-10-04T14:33:15.000Z", "max_issues_repo_issues_event_max_datetime": "2018-10-09T13:40:35.000Z", "max_forks_repo_path": "notebooks/linear_equations.ipynb", "max_forks_repo_name": "515hikaru/essence-of-machine-learning", "max_forks_repo_head_hexsha": "7f46be9316d227626f27a06deac64b43191cb4d7", "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": 18.9834024896, "max_line_length": 99, "alphanum_fraction": 0.4601092896, "converted": true, "num_tokens": 913, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.959154281754899, "lm_q2_score": 0.8872045952083047, "lm_q1q2_score": 0.8509660862866675}} {"text": "# Mixed Integer Linear Programming (MILP)\n\n## Introduction\n\n* Some variables are restricted to be integers\n* NP-complete\n* Applications\n * Production planning\n * Scheduling\n * Many more...\n\n## The standard form\n\n\\begin{align}\n\\text{maximize}\\ & \\mathbf{c}^T\\mathbf{x} + \\mathbf{k}^T\\mathbf{y} \\\\\n\\text{subject to } & \\\\\n& A\\mathbf{x} &&\\leq \\mathbf{b} \\\\\n& D\\mathbf{y} &&\\leq \\mathbf{e} \\\\\n& \\mathbf{x},\\mathbf{y} &&\\geq 0 \\\\\n& \\mathbf{x} \\in \\mathbb{Z}^n\n\\end{align}\nwhere $A, D \\in \\mathbb{R}^{m\\times n}$ are matrices, $\\mathbf{b}, \\mathbf{e}\\in\\mathbb{R}^{m}$ are constants, $\\mathbf{c}, \\mathbf{k} \\in \\mathbb{R}^{n}$ objective function coefficients, and $\\mathbf{x}, \\mathbf{y} \\in\\mathbb{R}^{n}$ are the decision variables.\n\n\n## CPLEX basics: Mixed Integer Programming Model\n## Mathematical Model\n\\begin{align}\n\\text{maximize}\\ & 2x + y + 3z \\\\\n\\text{subject to } & \\\\\n& x+2y+z &&\\leq 4 \\\\\n& 2z + y &&\\leq 5 \\\\\n& x + y &&\\geq 1 \\\\\n& x &&\\in \\{0,1\\} \\\\\n& y, z \\geq 0 \\\\\n& z \\in \\mathbb{Z}\n\\end{align}\n\n# Code in Python using docplex\n## Step 1: Importing Model from docplex package\n\n\n```python\nfrom docplex.mp.model import Model\n```\n\n## Step 2: Create an optimization model\n\n\n```python\nmilp_model = Model(name = \"MILP\")\n```\n\n## Step 3: Add decision variables\n\n\n```python\nx = milp_model.binary_var(name = 'x')\ny = milp_model.continuous_var(name = 'y', lb = 0)\nz = milp_model.integer_var(name=\"z\", lb=0)\n```\n\n## Step 4: Add the constraints\n\n\n```python\n# Add constraint: x + 2 y + z <= 4\nc1 = milp_model.add_constraint(x + 2 * y + z <= 4, ctname = \"c1\")\n\n# Add constraint: 2 z + y <= 5 \\\\\nc2 = milp_model.add_constraint(2 * z + y <= 5, ctname = \"c2\")\n\n# Add constraint x + y >= 1\nc3 = milp_model.add_constraint(x + y >= 1, ctname = \"c3\")\n```\n\n## Step 5: Define the objective function\n\n\n```python\nobj_fn = 2 * x + y + 3 * z\nmilp_model.set_objective('max', obj_fn)\n\nmilp_model.print_information()\n```\n\n## Step 6: Solve the model\n\n\n```python\nmilp_model.solve()\n```\n\n## Step 7: Output the result\n\n\n```python\nmilp_model.print_solution()\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "a2573da47dda73fcef7f83bbf17f1e829b159d78", "size": 4538, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "mathematicalProgramming/Video08/Video08.ipynb", "max_stars_repo_name": "codingperspective/videoMaterials", "max_stars_repo_head_hexsha": "8c9665466d8912c6f0c701c25ad9eb4802fb73a3", "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": "mathematicalProgramming/Video08/Video08.ipynb", "max_issues_repo_name": "codingperspective/videoMaterials", "max_issues_repo_head_hexsha": "8c9665466d8912c6f0c701c25ad9eb4802fb73a3", "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": "mathematicalProgramming/Video08/Video08.ipynb", "max_forks_repo_name": "codingperspective/videoMaterials", "max_forks_repo_head_hexsha": "8c9665466d8912c6f0c701c25ad9eb4802fb73a3", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2021-11-21T05:02:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-17T04:44:57.000Z", "avg_line_length": 22.5771144279, "max_line_length": 286, "alphanum_fraction": 0.4852357867, "converted": true, "num_tokens": 736, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9697854120593483, "lm_q2_score": 0.8774767794716264, "lm_q1q2_score": 0.8509641801524012}} {"text": "# Lab 3\n## Introduction\nIn this lab we will analyse population dynamics under the logisitic model with managed harvesting.\n\nFirst import the modules we need.\n\n\n```python\nfrom plotly.figure_factory import create_quiver\nfrom plotly import graph_objs as go\nfrom numpy import meshgrid, arange, sqrt, linspace\nfrom scipy.integrate import odeint\n```\n\n## Harvesting of fish\nA population of fish in a lake, left to its own devices, is modelled by the logistic differential equation\n\\begin{align}\n\\frac{\\mathrm{d}y}{\\mathrm{d}{t}} = 4y(1-y),\n\\end{align}\nwhere the population $y$ is in units of thousands of fish and time $t$ is measured in years.\n\nFirst define a function for $\\mathrm{d}y/\\mathrm{d}x$ in terms of $y$ and $x$.\n\n\n```python\ndef diff_eq(y, x):\n return 4 * y * (1 - y) \n```\n\nNext define a function that creates a Plotly Figure object that contains a slope field and, optionally, a few solutions to initial value problems.\n\nIt automates a few things we did in the last lab.\n\n- `diff_eq` is the differential equation to be plotted\n- `x` and `y` should be outputs from `meshgrid`. \n- `args` is any additional arguments to `diff_eq` (we will use that below).\n- `initial_values` is a list (or array) of starting $y$ values from which approximate solutions will start. The corresponding $x$ value is the minimum element of `x`.\n\nNote that the numerical solutions will plotted for the whole range of $x$ values in `x`, so if they blow up you will probably get a warning and less-than-useful plot.\n\n\n```python\ndef create_slope_field(diff_eq, x, y, args=(), initial_values=()): \n S = diff_eq(y, x, *args)\n L = sqrt(1 + S**2)\n scale = 0.8*min(x[0][1]-x[0][0], y[1][0]-y[0][0]) # assume a regular grid\n fig = create_quiver(x, y, 1/L, S/L, scale=scale, arrow_scale=1e-16)\n fig.layout.update(yaxis=dict(scaleanchor='x',\n scaleratio=1,\n range=[y.min()-scale, y.max()+scale]),\n xaxis=dict(range=[x.min()-scale, x.max()+scale]),\n showlegend=True, width=500,\n height=0.8*(y.max()-y.min())/(x.max()-x.min())*500)\n x = linspace(x.min(), x.max())\n for y0 in initial_values:\n y = odeint(diff_eq, y0, x, args).flatten()\n fig.add_trace(go.Scatter(x=x, y=y))\n return fig\n```\n\nThe slope field below should hopefully give you some idea for the fish population dynamics.\n\nNote that we use `arange` rather than `linspace` this week so that we can carefully control the increments between our grid points. `arange(0, 1.1, 0.25)` returns an array that starts with 0 and increments by 0.25 until it exceeds 1.1.\n\nThe plot also contains the solution curves for \n$y(0) = 1$ and $y(0) = 0.4$. Edit the cell to also include the solution curve for $y(0)=1.4$.\n\n\n```python\nx, y = meshgrid(arange(0, 1.1, 0.05), arange(-0.4, 1.41, 0.05))\nfig = create_slope_field(diff_eq, x, y, initial_values=(0.4, 1))\nfig.show('png')\n```\n\n### Equilibrium solutions\nLooking back to our differential equation, $\\mathrm{d}y/\\mathrm{d}t = 0$ when $y(t) = 0$ or $y(t) = 1$. Looking at the slope field, we see that the equilibrium solution $y(t) = 1$ is stable (this is the carrying capacity here, corresponding to 1000 fish), whereas the equilibrium solution $y(t) = 0$ is unstable. Any non-zero initial population will eventually stabilise at 1000 fish.\n\n### What will happen if harvesting is now commenced at a steady rate?\nFor the simplest harvesting model, assume that $H$ units (thousands) of fish are taken\ncontinuously (smoothly) over the year, rather than at one instant each year.\nNote that the units of $H$ are the same as those of $\\mathrm{d}y/\\mathrm{d}t$, thousands of fish per year, so we simply subtract $H$ from the RHS of our existing equation to give the DE with harvesting as\n\\begin{align}\n\\frac{\\mathrm{d}y}{\\mathrm{d}{t}} = 4y(1-y) - H.\n\\end{align}\nAgain, the (constant) equilibrium solutions are found by setting $\\mathrm{d}y/\\mathrm{d}t = 0$, giving from the quadratic formula (check this),\n\\begin{align}\ny(t) = \\frac{4\\pm\\sqrt{16-16H}}{8} = \\frac{1\\pm\\sqrt{1-H}}{2}.\n\\end{align}\nWhat happens after harvesting starts will depend on the equilibrium solutions, their\nstability and the initial number of fish $y(0)$.\n\nStart by redefining `diff_eq` to include the `H` parameter. Note that defining `diff_eq` again overides our original definition.\n\n\n```python\ndef diff_eq(y, x, H=0):\n return 4 * y * (1 - y) - H\n```\n\nNow set $H = 0.6$ and plot the slope field. This is done by setting `args=(0.6,)` when we call `create_slope_field`. This is exactly how you would pass additional arguments like this one to `odeint` if you were calling it directly.\n\n\n```python\nx, y = meshgrid(arange(0, 1.1, 0.05), arange(-0.4, 1.41, 0.05))\nfig = create_slope_field(diff_eq, x, y, args=(0.6,))\nfig.show('png')\n```\n\nFrom the solutions to the quadratic equation above, the equilibrium solutions of the DE are found to be $y(t) \\approx 0.184$ and $y(t) \\approx 0.816$. The previous equilibrium solution with no harvesting at $y(t) = 0$ has moved up to $y(t) \\approx 0.184$, while the previous equilibrium solution with no harvesting at $y(t) = 1$ has moved down to $y(t) \\approx 0.816$.\n\nFrom the slope field, we see that the equilibrium solution $y(t) \\approx 0.184$ is unstable, whereas the equilibrium solution $y(t) \\approx 0.816$ is stable. If the population ever falls below about 0.184, or 184 fish, it will then drop to 0. This is a new feature, introduced by harvesting.\n\nIn the cell below, use `create_slope_field` to experiment by plotting the solutions to the initial value problems $y(0)=0.183$ and $y(0)=0.25$. Extend the $x$ range of your slope field until the top line is close to equlibrium. Note that if you extend it too far you will break `odeint` (why?). You may also like to increase the increments in `arange` to make the plot clearer.\n\n\n```python\ndef diff_eq(y, x, H=0):\n return 4 * y * (1 - y) - H\ndef create_slope_field(diff_eq, x, y, args=(), initial_values=()): \n S = diff_eq(y, x, *args)\n L = sqrt(1 + S**2)\n scale = 0.9*min(x[0][1]-x[0][0], y[1][0]-y[0][0]) \n fig = create_quiver(x, y, 1/L, S/L, scale=scale, arrow_scale=1e-16)\n fig.layout.update(yaxis=dict(scaleanchor='x',\n scaleratio=1,\n range=[y.min()-scale, y.max()+scale]),\n xaxis=dict(range=[x.min()-scale, x.max()+scale]),\n showlegend=False, width=500,\n height=0.8*(y.max()-y.min())/(x.max()-x.min())*500)\n x = linspace(x.min(), x.max())\n for y0 in initial_values:\n y = odeint(diff_eq, y0, x, args).flatten()\n fig.add_trace(go.Scatter(x=x, y=y))\n return fig\nx, y = meshgrid(arange(0, 2.0, 0.1), arange(-0.4, 1.41, 0.1))\nfig = create_slope_field(diff_eq, x, y, args=(0.6,), initial_values=(0.183, 0.25))\nfig.show('png')\n```\n\n## Exercises\n\nIn this lab you will experiment with the population dynamics given by the logistic equation with harvesting that we started analysing in the lab.\n\nThis week the questions will be a combination of plots and written answers.\n\n1. Assume that the harvest is 600 fish per year. **On the same figure,** \n a. plot the slope field, \n b. plot the equilibrium solutions that we found in above, and \n c. plot the solution curves for $y(0)=1$, $y(0)=0.3$, and $y(0)=0.15$.\n\n\n```python\ndef diff_eq(y, x, H=0):\n return 4 * y * (1 - y) - H\ndef create_slope_field(diff_eq, x, y, args=(), initial_values=()): \n S = diff_eq(y, x, *args)\n L = sqrt(1 + S**2)\n scale = 0.9*min(x[0][1]-x[0][0], y[1][0]-y[0][0]) \n fig = create_quiver(x, y, 1/L, S/L, scale=scale, arrow_scale=1e-16)\n fig.layout.update(yaxis=dict(scaleanchor='x',\n scaleratio=1,\n range=[y.min()-scale, y.max()+scale]),\n xaxis=dict(range=[x.min()-scale, x.max()+scale]),\n showlegend=False, width=500,\n height=0.8*(y.max()-y.min())/(x.max()-x.min())*500)\n x = linspace(x.min(), x.max())\n for y0 in initial_values:\n y = odeint(diff_eq, y0, x, args).flatten()\n fig.add_trace(go.Scatter(x=x, y=y))\n return fig\nx, y = meshgrid(arange(0, 0.9, 0.05), arange(-0.05, 1.41, 0.05))\nfig = create_slope_field(diff_eq, x, y, args=(0.6,), initial_values=(1, 0.3, 0.15))\nfig.show()\n```\n\n1. d. In the cell below, describe the behaviour of the fish population for each of these five initial numbers of fish.\n\nWhen y(0)=0.15, the curve tends to diverge.\n\n2. a. i. Assume that $H=0.8$. Plot the slope field and five solutions, one for each equilibrium solution and one for each region between, above, or below them. You can use the equation from the lab to calculate the equilibrium solutions.\n\n\n```python\ndef create_slope_field(diff_eq, x, y, args=(), initial_values=()): \n S = diff_eq(y, x, *args)\n L = sqrt(1 + S**2)\n scale = 0.8*min(x[0][1]-x[0][0], y[1][0]-y[0][0]) # assume a regular grid\n fig = create_quiver(x, y, 1/L, S/L, scale=scale, arrow_scale=1e-16)\n fig.layout.update(yaxis=dict(scaleanchor='x',\n scaleratio=1,\n range=[y.min()-scale, y.max()+scale]),\n xaxis=dict(range=[x.min()-scale, x.max()+scale]),\n showlegend=False, width=400,\n height=0.8*(y.max()-y.min())/(x.max()-x.min())*500)\n x = linspace(x.min(), x.max())\n for y0 in initial_values:\n y = odeint(diff_eq, y0, x, args).flatten()\n fig.add_trace(go.Scatter(x=x, y=y))\n return fig\nx, y = meshgrid(arange(0, 1.1, 0.05), arange(-0.4, 1.41, 0.05))\nfig = create_slope_field(diff_eq, x, y, args=(0.5,), initial_values=(0.6,))\nfig.show('png')\n```\n\n2. a. ii. In the cell below, describe the limiting behaviour of each line.\n\n\n\n2. b. i. Assume that $H=1$. Plot the slope field and three solutions for the equilibrium solution and the regions above and below it.\n\n\n```python\nx, y = meshgrid(arange(0, 0.8, 0.1), arange(-0.4, 1.41, 0.05))\nfig = create_slope_field(diff_eq, x, y, args=(1.0,), initial_values=(1, 0.3, 0.15,0.183, 0.25))\nfig.show('png')\n```\n\n2. b. ii. Describe the limiting behaviour of each line.\n\n\n\n2. c. i. Assume that 𝐻=1.2. Plot the slope field and two or three solutions.\n\n\n```python\nx, y = meshgrid(arange(0.0, 0.7, 0.1), arange(-0.4, 1.41, 0.05))\nfig = create_slope_field(diff_eq, x, y, args=(1.2,), initial_values=(1, 0.3, 0.15,0.183, 0.25))\nfig.show()\n```\n\n2. c. iii. Describe the limiting behaviour of the lines.\n\n\n\n3. Summarize what happens to the equilibrium solutions and their stability as $H$\nis increased from 0 to beyond 1. Refer to your plots to support your answers.\n\nAs H value increases, the lower the initial value of y it requires to diverge as seen on the plot. \n\n4. What is a reasonable strategy for sustainable fishing in this case?\nDon’t forget to allow qualitatively for minor catastrophes, such as disease or temporary overfishing.\n\nTHe best way to sustain fishing is to set a certain threshold on harvesting fish yearly. If we harvest too many on a yearly rate, then there's a strong likelihood that the population will plummet.\n", "meta": {"hexsha": "840c08bd46e6792b88952d011024726f4d823fe1", "size": 318240, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/lab-03.ipynb", "max_stars_repo_name": "18lejoh/mm-labs", "max_stars_repo_head_hexsha": "9cc81a388034c661a1de18921110146424cf41e2", "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": "notebooks/lab-03.ipynb", "max_issues_repo_name": "18lejoh/mm-labs", "max_issues_repo_head_hexsha": "9cc81a388034c661a1de18921110146424cf41e2", "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": "notebooks/lab-03.ipynb", "max_forks_repo_name": "18lejoh/mm-labs", "max_forks_repo_head_hexsha": "9cc81a388034c661a1de18921110146424cf41e2", "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": 477.8378378378, "max_line_length": 56509, "alphanum_fraction": 0.9394387883, "converted": true, "num_tokens": 3320, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425311777929, "lm_q2_score": 0.9252299514223379, "lm_q1q2_score": 0.8508808144475452}} {"text": "## FowardDiff.jl\n\n[The JuliaDiff website](http://www.juliadiff.org/) describes the advantages (and some of the implementation) of autodifferentiation. The basic idea is as follows. For normal derivative approximations, you do calculations like:\n\n```julia\nDf = (f(x+ϵ) - f(x)) / ϵ\n```\n\nwith ϵ sufficiently small. However, when ϵ is small [catestrophic cancellation](https://en.wikipedia.org/wiki/Loss_of_significance) occurs which causes numerical error. This puts numerical differentiation methods in a bind: a small epsilon is required to not have derivative error (since it's defined as the limit), but small epsilon results in floating point errors due to cancelation. The result is that numerical derivative approximations are very error prone.\n\nSymbolic differentiation isn't always possible since the length of the expressions grows exponentially. But a newer technique, called autodifferentiation, can do this. The central idea is that you can directly define the derivatives of basic expressions (like `sin`), and then use the chain rule to know how to propagate derivatives. This allows you to efficiently calculate derivatives through entire codes without using small epsilon values, meaning it doesn't result in the high numerical errors that plague numerical differentiation. The result is fast and accurate derivatives.\n\nForwardDiff.jl is an implementation of autodifferentiation which uses [dual numbers](https://en.wikipedia.org/wiki/Dual_number). The idea is you have a two dimensional number, and you define operators like `+` so that way the first part is the value and the second part is the derivative. For example, `sin(Ax) = sin(Ax) + cos(A)ϵ`, and then you can use the chain rule to define how the epsilon gets passed down. The resulting derivative at the end of the calculation is then simply the coefficient on the epsilon part. Here, ϵ is part of a number type, and this is all done by multiple dispatch and defining new dispatches on basic mathematical functions for Dual numbers which also compute the derivative.\n\n### Problem\n\nThe ForwardDiff.jl documentation can be found here: http://www.juliadiff.org/ForwardDiff.jl/stable/user/api.html\n\n1. Use the `ForwardDiff.derivative` function to take the derivative of `x^5 + 3x^2`. Compare the result to the analytical solution by plotting both with Plots.jl, overlaying one on top of the other (hint: `plot!` can be helpful!).\n\n2. The transformation from spherical to cartesian coordinates is given by:\n\n$$\n\\begin{align}\nx &= r\\sin(\\theta)\\cos(\\phi) \\\\\ny &= r\\sin(\\theta)\\sin(\\phi) \\\\\nz &= r\\cos(\\theta)\n\\end{align}\n$$\n\nUse ForwardDiff.jl to calculate the Jacobian of the transformation. Compare the determinant of the Jacobian against the analytical solution $r^2 \\sin(\\theta)$.\n", "meta": {"hexsha": "99bf50819d8ed8a7991dc6684a5f37434f88cb16", "size": 3435, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Notebooks/ForwardDiff.ipynb", "max_stars_repo_name": "jla524/IntroToJulia", "max_stars_repo_head_hexsha": "2301ed94f1459893dcc67f67fc9b65df8d45d0ee", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 251, "max_stars_repo_stars_event_min_datetime": "2016-05-17T06:47:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-30T16:07:03.000Z", "max_issues_repo_path": "Notebooks/ForwardDiff.ipynb", "max_issues_repo_name": "jla524/IntroToJulia", "max_issues_repo_head_hexsha": "2301ed94f1459893dcc67f67fc9b65df8d45d0ee", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 50, "max_issues_repo_issues_event_min_datetime": "2016-10-25T16:11:42.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-02T12:08:06.000Z", "max_forks_repo_path": "Notebooks/ForwardDiff.ipynb", "max_forks_repo_name": "jla524/IntroToJulia", "max_forks_repo_head_hexsha": "2301ed94f1459893dcc67f67fc9b65df8d45d0ee", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 98, "max_forks_repo_forks_event_min_datetime": "2016-05-24T16:44:39.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-19T18:13:08.000Z", "avg_line_length": 60.2631578947, "max_line_length": 717, "alphanum_fraction": 0.69286754, "converted": true, "num_tokens": 623, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533032291501, "lm_q2_score": 0.9124361563100185, "lm_q1q2_score": 0.8508041079369859}} {"text": "# ODE boundary value problems\n\nLet's have a look at how the DifferentialEquations.jl package handles boundary value problems. Let's solve the simple harmonic equation \n$$\nu'' + 3 u = 0\n$$\non the interval $t \\in [0,2\\pi]$ where $u(0)=7$ and $u(2 \\pi)=0$. The exact solution is given by \n$$\n\\begin{align}\nu(t) = 7 \\cos \\left(\\sqrt{3}t \\right) - 7 \\cot \\left(2\\sqrt{3}\\pi \\right) \\sin \\left(\\sqrt{3}t \\right).\n\\end{align}\n$$\n\nThe second order equation can be rewritten as the first order system\n$$\n\\begin{align}\n\\left( u \\right)' =& u', \\\\\n\\left( u' \\right)' =& - 3 u.\n\\end{align}\n$$\nSo let's solve this two point boundary value problem numerically using Julia.\n\n\n```julia\n#using Pkg\n#Pkg.add( \"BoundaryValueDiffEq\" )\n```\n\n\n```julia\nusing DifferentialEquations, BoundaryValueDiffEq, Plots\nusing BenchmarkTools\n```\n\n\n```julia\nfunction harmonic!(du,u,p,t)\n du[1] = u[2]\n du[2] = - 3 * u[1]\nend\n```\n\n\n\n\n harmonic! (generic function with 1 method)\n\n\n\n\n```julia\nfunction boundary_conditions!(residual, u, p, t)\n residual[1] = u[1][1] - 7\n residual[2] = u[end][1]\nend\n```\n\n\n\n\n boundary_conditions! (generic function with 1 method)\n\n\n\n\n```julia\ntspan = (0.0,2*pi)\ntstep = 0.05\ninitial_guess = [7.0,-1.0]\nbvp = TwoPointBVProblem( harmonic!, boundary_conditions!, initial_guess, tspan )\nsol = solve( bvp, MIRK4(), dt=tstep);\n```\n\n\n```julia\nplot( sol, vars=(1), lw=2, label=\"Numerical solution\" )\n\nfunction exact( t )\n return 7*( cos(sqrt(3)*t) - cot(2*sqrt(3)*pi) * sin(sqrt(3)*t) )\nend\n\nplot!( sol.t, t->exact(t), lw=2,ls=:dash, label=\"Exact solution\" )\n```\n\n\n\n\n \n\n \n\n\n\n\n```julia\nerror = map( exact, sol.t )\nfor i in 1:length(sol.t)\n error[i] = error[i] - sol.u[i][1]\nend\nplot( sol.t, error, label=\"Error\", lw=2 )\n```\n\n\n\n\n \n\n \n\n\n\nLet's try a slightly more difficult example such as the Blasius equation\n$$\nf''' + f f'' = 0,\n$$\nwith the conditions $f(0)=f'(0)=0$ and $f'(\\infty)=1$. We can rewrite the Blasius equation as the first order system\n$$\n\\begin{align}\n\\left( f \\right)' =& f', \\\\\n\\left( f' \\right)' =& f'', \\\\\n\\left( f'' \\right)' =& -f f''.\n\\end{align}\n$$\n\n\n```julia\nfunction Blasius!(du,u,p,t)\n du[1] = u[2]\n du[2] = u[3]\n du[3] = -u[1] * u[3]\nend\n```\n\n\n\n\n Blasius! (generic function with 1 method)\n\n\n\n\n```julia\nfunction Blasius_bcs!(residual, u, p, t)\n residual[1] = u[1][1] \n residual[2] = u[1][2]\n residual[3] = u[end][2] - 1\nend\n```\n\n\n\n\n Blasius_bcs! (generic function with 1 method)\n\n\n\n\n```julia\ntinf = 20\nN = 200\ntspan = (0.0,20.0)\ntstep = (tspan[2] - tspan[1])/N\n# Make an initial guess\nt = tspan[1]:tstep:tspan[2]\nfunction f_guess( t )\n return t * ( 1.0 - exp( -t ) )\nend\nfunction f_d_guess( t )\n return ( 1.0 - exp( -t ) ) + t * exp( -t )\nend\nfunction f_dd_guess( t )\n return 2 * exp( -t ) - t * exp( -t )\nend\nf = map( f_guess, t )\nf_d = map( f_d_guess, t )\nf_dd = map( f_dd_guess, t )\n#initial_guess = [f,f_d,f_dd]\ninitial_guess = [1.0,1.0,0.0]\nbvp_Blasius = TwoPointBVProblem( Blasius!, Blasius_bcs!, initial_guess, tspan )\n@btime sol_Blasius = solve( bvp_Blasius, MIRK4(), dt=tstep );\n```\n\n 2.528 s (40327661 allocations: 3.56 GiB)\n\n\n\n```julia\nplot( sol_Blasius, xlims=(0,10), ylims=(0,2), label=[\"f\" \"f'\" \"f''\"] )\n```\n\n\n\n\n \n\n \n\n\n\nAdding the initial guesses doesn't seem to help much with speed or the memory allocation. How can the performance be improved?\n\n\n```julia\n\n```\n", "meta": {"hexsha": "40aff6389cb506b54c13bcf290f9b97cfae8860f", "size": 60029, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "ODE_BVP.ipynb", "max_stars_repo_name": "anthonyoneill/jupyter-notebooks", "max_stars_repo_head_hexsha": "9e1b0a6e1af51d38447adda01ac35060d1097c4e", "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": "ODE_BVP.ipynb", "max_issues_repo_name": "anthonyoneill/jupyter-notebooks", "max_issues_repo_head_hexsha": "9e1b0a6e1af51d38447adda01ac35060d1097c4e", "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": "ODE_BVP.ipynb", "max_forks_repo_name": "anthonyoneill/jupyter-notebooks", "max_forks_repo_head_hexsha": "9e1b0a6e1af51d38447adda01ac35060d1097c4e", "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.5509977827, "max_line_length": 241, "alphanum_fraction": 0.5911642706, "converted": true, "num_tokens": 1211, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037363973295, "lm_q2_score": 0.9184802367731411, "lm_q1q2_score": 0.8507916751300645}} {"text": "# Lucas_task 19 - Motor Control\n### Introduction to modeling and simulation of human movement\nhttps://github.com/BMClab/bmc/blob/master/courses/ModSim2018.md\n\n### 1) Find the extrema in the function f(x)=x3−7.5x2+18x−10 analytically and determine if they are minimum or maximum.\n\nImport Python libraries\n\n\n```python\nimport numpy as np\n%matplotlib inline\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport sympy as sym\nfrom sympy.plotting import plot\nimport pandas as pd\nfrom IPython.display import display\nfrom IPython.core.display import Math\n```\n\nFinding the roots\n\n\n```python\nx = sym.symbols('x')\nF = x**3 - 7.5*x**2 + 18*x - 10\nFdiff = sym.expand(sym.diff(F, x))\nroots = sym.solve(Fdiff, x)\ndisplay(Math(sym.latex('Roots:') + sym.latex(roots)))\n```\n\n\n$$Roots:\\left [ 2.0, \\quad 3.0\\right ]$$\n\n\nFinding the minimum and maximum\n\n\n```python\nx1 = 2\nx2 = 3\nF1 = x1**3 - 7.5*x1**2 + 18*x1 - 10\nF2 = x2**3 - 7.5*x2**2 + 18*x2 - 10\n\nprint(\"F(x1): \", F1)\nprint(\"\\nF(x2): \", F2)\n\n\n```\n\n F(x1): 4.0\n \n F(x2): 3.5\n\n\n\n```python\nprint(\"Minimim:\", x2,\"\\nMaximum:\", x1)\n\n```\n\n Minimim: 3 \n Maximum: 2\n\n\n### 2) Find the minimum in the f(x)=x3−7.5x2+18x−10 using the gradient descent algorithm.\n\n\n```python\ncur_x = 6 # The algorithm starts at x=6\ngamma = 0.01 # step size multiplier\nprecision = 0.00001\nstep_size = 1 # initial step size\nmax_iters = 10000 # maximum number of iterations\niters = 0 # iteration counter\n\nf = lambda x: x**3 - 7.5*x**2 + 18*x - 10 # lambda function for f(x)\ndf = lambda x: 3*x**2 - 15*x + 18 # lambda function for the gradient of f(x)\n\nwhile (step_size > precision) & (iters < max_iters):\n prev_x = cur_x\n cur_x -= gamma*df(prev_x)\n step_size = abs(cur_x - prev_x)\n iters+=1\n\nprint('True local minimum at {} with function value {}.'.format(9/4, f(9/4)))\nprint('Local minimum by gradient descent at {} with function value {}.'.format(cur_x, f(cur_x)))\n```\n\n True local minimum at 2.25 with function value 3.921875.\n Local minimum by gradient descent at 3.000323195755751 with function value 3.5000001567170003.\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "6ff82daa7871fb4b8aa286ee302113eecaf49f9b", "size": 4569, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "courses/modsim2018/tasks/Lucas_task19.ipynb", "max_stars_repo_name": "regifukuchi/bmc-1", "max_stars_repo_head_hexsha": "f4418212664758511bb3f4d4ca2318ac48a55e88", "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": "courses/modsim2018/tasks/Lucas_task19.ipynb", "max_issues_repo_name": "regifukuchi/bmc-1", "max_issues_repo_head_hexsha": "f4418212664758511bb3f4d4ca2318ac48a55e88", "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": "courses/modsim2018/tasks/Lucas_task19.ipynb", "max_forks_repo_name": "regifukuchi/bmc-1", "max_forks_repo_head_hexsha": "f4418212664758511bb3f4d4ca2318ac48a55e88", "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": 22.959798995, "max_line_length": 125, "alphanum_fraction": 0.5049244911, "converted": true, "num_tokens": 698, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.926303724190573, "lm_q2_score": 0.9184802373309982, "lm_q1q2_score": 0.850791664435145}} {"text": "```python\nimport numpy as np\n```\n\n\n```python\n# matrix multiplication\na = np.array([[0,6],[2,8],[4,10]])\nb = np.array([[1,3,5],[7,9,11]])\nprint(a)\nprint(b)\nprint(np.dot(a,b))\n```\n\n [[ 0 6]\n [ 2 8]\n [ 4 10]]\n [[ 1 3 5]\n [ 7 9 11]]\n [[ 42 54 66]\n [ 58 78 98]\n [ 74 102 130]]\n\n\n\n```python\nprint(np.matmul(a,b))\n```\n\n [[ 42 54 66]\n [ 58 78 98]\n [ 74 102 130]]\n\n\n\n```python\n# sigmoid activation function\ndef sigmoid(x):\n return 1 / (1 + np.exp(-x))\n```\n\n\n```python\nx1=1\nx2=1\nscore = 4*x1 + 5*x2 - 9\n```\n\n\n```python\nsigmoid(score)\n```\n\n\n\n\n 0.5\n\n\n\n\n```python\nw1=3\nw2=5\nb=-2.2\n\nsigmoid(w1*0.4 + w2*0.6 + b)\n```\n\n\n\n\n 0.8807970779778823\n\n\n\n\n```python\n# eigenvector and eigenvalues\nA = np.array([[3, 0],[-9, 6]])\nx = np.array([1, 3])\n\nnp.dot(A, x)\n```\n\n\n\n\n array([3, 9])\n\n\n\n\n```python\n# picture size calculation\n# W = input volume\n# K = Kernel size\n# P = padding\n# S = stride\n\nnp.int_(((130-3+0)/1)+1)\n```\n\n\n\n\n 128\n\n\n\n$[(W−K+2*P)/S]+1$\n\n\n```python\n# calculating padding that has kernel_size of 7 for CNN that is the same x-y size as an input array\n# see above equation; using P = 3\nx = (-7 + 2*3/1) + 1 # results in zero; W - 0 = W\nprint(np.int_(x))\n```\n\n 0\n\n\n\n```python\nfrom sympy import Symbol\n\nSymbol('w') + x == Symbol('w') # W = W; CNN has same x-y size as input array\n```\n\n\n\n\n True\n\n\n\n\n```python\n# nlp: Subsampling equation\n# text with 1 million words in it\n# word \"learn\" appears 700 times in this text\n# threshold is 0.0001\n```\n\n$p = 1 - \\sqrt{\\frac{t}{f(x_[i])}}$\n\n\n```python\n# -> calculate probability that we will discard the word \"learn\"\nf = 700\nw_i = 1e6\nt = 1e-4\n```\n\n\n```python\np = 1 - np.sqrt(t/(f/w_i))\nprint(p)\n```\n\n 0.6220355269907727\n\n\n\n```python\n# For an input [23, 702, 89, 15, 99] and R=2, what will the returned context be if we pass in the token at idx=1 (702)?\ndef get_target(words, idx, R):\n start = idx - R if (idx - R) > 0 else 0\n stop = idx + R\n target_words = words[start:idx] + words[idx+1:stop+1]\n \n return list(target_words)\n```\n\n\n```python\nprint(get_target(words=[23, 702, 89, 15, 99], idx=1, R=2))\n```\n\n [23, 89, 15]\n\n", "meta": {"hexsha": "030884b458bc821f1105ab04f5f87aa476e75fa6", "size": 6518, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notes.ipynb", "max_stars_repo_name": "d-kleine/Udacity_DLND", "max_stars_repo_head_hexsha": "36ae9dd851c2e460139d3faf0a5967807c94b85f", "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": "notes.ipynb", "max_issues_repo_name": "d-kleine/Udacity_DLND", "max_issues_repo_head_hexsha": "36ae9dd851c2e460139d3faf0a5967807c94b85f", "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": "notes.ipynb", "max_forks_repo_name": "d-kleine/Udacity_DLND", "max_forks_repo_head_hexsha": "36ae9dd851c2e460139d3faf0a5967807c94b85f", "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": 18.7838616715, "max_line_length": 128, "alphanum_fraction": 0.4444614913, "converted": true, "num_tokens": 833, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850004144266, "lm_q2_score": 0.9086179055936797, "lm_q1q2_score": 0.8507253161153339}} {"text": "# sympy\n\nSince we want to work interactively with `sympy`, we will import the complete module. Note that this polutes the namespace, and is not recommended in general.\n\n\n```python\nfrom sympy import *\n```\n\nEnable pretty printing in this notebook.\n\n\n```python\ninit_printing()\n```\n\n## Expression manipulation\n\nDefine a number of symbols to work with, as well as an example expression.\n\n\n```python\nx, y, a, b, c = symbols('x y a b c')\n```\n\n\n```python\nexpr = (a*x**2 - b*y**2 + 5)/(c*x + y)\n```\n\nCheck the expression's type.\n\n\n```python\nexpr.func\n```\n\n\n\n\n sympy.core.mul.Mul\n\n\n\nAlthough the expression was defined as a divisino, it is represented as a multiplicatino by `sympy`. The `args` attribute of an expressions stores the operands of the top-level operator.\n\n\n```python\nexpr.args\n```\n\nAlthough the first factor appears to be a division, it is in fact a power. The denominator of this expression would be given by:\n\n\n```python\nexpr.args[0].func\n```\n\n\n\n\n sympy.core.power.Pow\n\n\n\n\n```python\nexpr.args[0].args[0]\n```\n\nThe expression $\\frac{1}{a x + b}$ can alternatively be defined as follows, which highlights the internal representation of expressions.\n\n\n```python\nexpr = Pow(Add(Mul(a, x), b), -1)\n```\n\n\n```python\npprint(expr)\n```\n\n 1 \n ───────\n a⋅x + b\n\n\n\n```python\nexpr.args\n```\n\n\n```python\nexpr.args[0].args[0]\n```\n\nThis may be a bit surprising when you look at the mathematical representation of the expression, but the order of the terms is different from its rendering on the screen.\n\n\n```python\nexpr.args[0].args\n```\n\nSince the addition operation is commutative, this makes no difference mathematically.\n\n\n```python\nexpr.args[0].args[1].args\n```\n\n\n```python\nexpr = x**2 + 2*a*x + y**2\n```\n\n\n```python\nexpr2 = expr.subs(y, a)\nexpr2\n```\n\nMost expression manipulation algorithms can be called as functions, or as methods on expressions.\n\n\n```python\nfactor(expr2)\n```\n\n\n```python\nexpr2.factor()\n```\n\n\n```python\nx, y = symbols('x y', positive=True)\n```\n\n\n```python\n(log(x) + log(y)).simplify()\n```\n\n## Calculus\n\n### Series expansion\n\n\n```python\nx, a = symbols('x a')\n```\n\n\n```python\nexpr = sin(a*x)/x\n```\n\n\n```python\nexpr2 = series(expr, x, 0, n=7)\n```\n\n\n```python\nexpr2\n```\n\nA term of a specific order in a given variable can be selected easily.\n\n\n```python\nexpr2.taylor_term(2, x)\n```\n\nWhen the order is unimportant, or when the expression should be used to define a function, the order term can be removed.\n\n\n```python\nexpr2.removeO()\n```\n\nAdding two series deals with the order correctly.\n\n\n```python\ns1 = series(sin(x), x, 0, n=7)\n```\n\n\n```python\ns2 = series(cos(x), x, 0, n=4)\n```\n\n\n```python\ns1 + s2\n```\n\n### Derivatives and integrals\n\n\n```python\nexpr = a*x**2 + b*x + c\n```\n\n\n```python\nexpr.diff(x)\n```\n\n\n```python\nexpr.integrate(x)\n```\n", "meta": {"hexsha": "636c1cc737cf7039e87d6460d0a84abdfe279b01", "size": 44016, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "source-code/sympy/sympy.ipynb", "max_stars_repo_name": "gjbex/Scientific-Python", "max_stars_repo_head_hexsha": "b4b7ca06fdedf1de37a0ad537d69c128e24c747c", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2021-03-24T08:05:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-06T13:45:23.000Z", "max_issues_repo_path": "source-code/sympy/sympy.ipynb", "max_issues_repo_name": "gjbex/Scientific-Python", "max_issues_repo_head_hexsha": "b4b7ca06fdedf1de37a0ad537d69c128e24c747c", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-01-15T07:17:50.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-15T07:17:50.000Z", "max_forks_repo_path": "source-code/sympy/sympy.ipynb", "max_forks_repo_name": "gjbex/Scientific-Python", "max_forks_repo_head_hexsha": "b4b7ca06fdedf1de37a0ad537d69c128e24c747c", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 10, "max_forks_repo_forks_event_min_datetime": "2020-12-07T08:06:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-25T13:00:48.000Z", "avg_line_length": 50.9444444444, "max_line_length": 4034, "alphanum_fraction": 0.7739231189, "converted": true, "num_tokens": 781, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632996617212, "lm_q2_score": 0.9173026488471135, "lm_q1q2_score": 0.8506728112232963}} {"text": "# SymPy\nThe SymPy package is useful for symbolic algebra, much like the commercial software Mathematica.\n\nWe won't make much use of SymPy during the boot camp, but it is definitely useful to know about\nfor mathematics courses.\n\n\n```python\nimport sympy as sp\nsp.init_printing()\n```\n\n# Symbols and Expressions\nWe'll define `x` and `y` to be `sympy` symbols, then do some symbolic algebra.\n\n\n```python\nx, y = sp.symbols(\"x y\")\n```\n\n\n```python\nexpression = (x+y)**4\n```\n\n\n```python\nexpression\n```\n\n\n```python\nsp.expand(expression)\n```\n\n\n```python\nexpression = 8*x**2 + 26*x*y + 15*y**2\n```\n\n\n```python\nexpression\n```\n\n\n```python\nsp.factor(expression)\n```\n\n\n```python\nexpression - 20 *x*y - 14*y**2\n```\n\n\n```python\nsp.factor(expression - 20*x*y - 14*y**2)\n```\n\n# Lambdify: Making python functions from sympy expressions\n\n\n```python\nexpression\n```\n\n\n```python\nf = sp.lambdify((x,y), expression, 'numpy')\n```\n\n\n```python\nf(3,4)\n```\n\n\n```python\n8 * 3**2 + 26 * 3 * 4 + 15 * 4**2\n```\n\n# Calculus\nYou can use `sympy` to perform symbolic integration or differentiation.\n\n\n```python\nexpression = 5*x**2 * sp.sin(3*x**3)\n```\n\n\n```python\nexpression\n```\n\n\n```python\nexpression.diff(x)\n```\n\n\n```python\nexpression = sp.cos(x)\n```\n\n\n```python\nexpression.integrate(x)\n```\n\n\n```python\nexpression.integrate((x, 0, sp.pi / 2))\n```\n\nYou can also create unevalated integrals or derivatives. These can later be evaluated with their `doit` methods.\n\n\n```python\nderiv = sp.Derivative(expression)\n```\n\n\n```python\nderiv\n```\n\n\n```python\nderiv.doit()\n```\n\n\n```python\ninte = sp.Integral(expression, (x, 0, sp.pi / 2))\n```\n\n\n```python\ninte\n```\n\n\n```python\ninte.doit()\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "5b213d87f48f5062442b0930d5479d8a5e5f7ef2", "size": 26716, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "SymPyExample.ipynb", "max_stars_repo_name": "shumway/srt_bootcamp", "max_stars_repo_head_hexsha": "c0b1cdc5f4fd57ac4f120e975842ea6bab2fa64b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2015-07-12T23:21:25.000Z", "max_stars_repo_stars_event_max_datetime": "2015-07-15T04:51:37.000Z", "max_issues_repo_path": "SymPyExample.ipynb", "max_issues_repo_name": "shumway/srt_bootcamp", "max_issues_repo_head_hexsha": "c0b1cdc5f4fd57ac4f120e975842ea6bab2fa64b", "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": "SymPyExample.ipynb", "max_forks_repo_name": "shumway/srt_bootcamp", "max_forks_repo_head_hexsha": "c0b1cdc5f4fd57ac4f120e975842ea6bab2fa64b", "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.205371248, "max_line_length": 1900, "alphanum_fraction": 0.7319209462, "converted": true, "num_tokens": 497, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541626630937, "lm_q2_score": 0.9032942001955142, "lm_q1q2_score": 0.8505907437235358}} {"text": "# Activity: Logistic Functions\n\n\n```python\nfrom cyllene import *\nfrom sympy import solve,log\nfrom f_special import logistic_function, logistic_plot_L, second_derivative\n```\n\n\n```python\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.optimize import curve_fit\n%matplotlib inline\n\nfrom ipywidgets import interact, interactive\nfrom IPython.display import Image\n\n```\n\n## The definition of a logistic function\n\nA *logistic function* is a function of the form\n\n$f(x) = \\dfrac{L}{1+C \\, e^{-kx}},$\n\nwhere $L, C, k$ are *parameters*.\n\nLogistic functions *initially* exhibit growth that is similar to *exponential*, but after a while the growth begins to slow down as a saturation property takes hold of the growth process.\n\n\n```python\nf = function('1/(1+10*exp(-x))')\n```\n\n\n```python\ngraph(f(x))\n```\n\n### The parameter $L$\n\nLet us take a look at the paramater $L$. Use the slider below to change the value of $L$.\nWhat effect does this have on the graph of a logistic function?\n\n\n```python\ninteractive_plot = interactive(logistic_plot_L, L=(1, 8, 0.5))\noutput = interactive_plot.children[-1]\noutput.layout.height = '300px'\ninteractive_plot\n```\n\n\n interactive(children=(FloatSlider(value=4.0, description='L', max=8.0, min=1.0, step=0.5), Output(layout=Layou…\n\n\nWe see that $L$ determines the **height of the graph**. It is the **limiting value** of the logistic function. The values of $f$ will approach $L$ as $x$ goes to infinity. The parameter $L$ is also called the **carrying capacity**.\n\n## The inflection point\n\nLet us again consider a simple logistic function:\n\n\n```python\nf = function('8/(1+10*exp(-2*x))')\n```\n\nTo find possible inflection points, we need to compute the second derivative:\n\n\n```python\nf2 = second_derivative(f(x))\nf2\n```\n\n\n\n\n$\\displaystyle - \\frac{320 e^{- 2 x}}{\\left(1 + 10 e^{- 2 x}\\right)^{2}} + \\frac{6400 e^{- 4 x}}{\\left(1 + 10 e^{- 2 x}\\right)^{3}}$\n\n\n\nTry to find the zeros for this expression.\n\nYou can check your answer by running the code below:\n\n\n```python\np = solve(f2,x)[0]\nsolve(f2,x)[0]\n```\n\n\n\n\n$\\displaystyle \\log{\\left(\\sqrt{10} \\right)}$\n\n\n\nNow plug the solution into the original function: \n\n\n```python\nf(p)\n```\n\n\n\n\n$\\displaystyle 4$\n\n\n\nRepeat this with different values for the parameters $L, C, k$. Do you observe a relation between $L$ and the location of the inflection point?\n\n### **FACT**: The inflection point of a logistic function occurs where $f(x) = L/2$. \n\n\n```python\nImage(filename='logistic_function.png', width=600) \n```\n\n---\n\n## Logistic modeling of COVID-19 data\n\nIn the following cell, we read the current Coronavirus data from CSSE at Johns Hopkins University. We extract a time series for the US, giving us for each day since January 22 the total number of infected persons.\n\n\n```python\nurl = \"https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv\"\ndf = pd.read_csv(url)\n# country = df[df[\"Country/Region\"] == \"Italy\"]\n# country = df[df[\"Country/Region\"] == \"Sweden\"]\n# country = df[df[\"Country/Region\"] == \"Germany\"]\ncountry = df[df[\"Country/Region\"] == \"US\"]\n\ninterval_len = 200\n\nx_data = list(range(interval_len))\ny_data = list(country.iloc[int(0),int(4):int(interval_len+4)])\n```\n\nWe run a logistic regression for our data and the logistic model.\n\n\n```python\nfit = curve_fit(logistic_function, x_data, y_data)\n```\n\n\n```python\nk = round(fit[0][0],3)\nC = round(fit[0][1],3)\nL = int(fit[0][2])\n\nprint(\"We estimated the following parameters:\")\nprint(\"k = \", k)\nprint(\"C = \", C)\nprint(\"L = \", L)\n```\n\n We estimated the following parameters:\n k = 0.025\n C = 106.736\n L = 8580027\n\n\n### Question: What does the parameter $L$ reflect in this case?\n\n#### Plotting the data\n\n\n```python\nplt.figure(figsize=(10,8))\n\nplt.scatter(list(range(interval_len)),y_data,label=\"Real data\",color=\"red\")\n\n# Predicted logistic curve\nt = np.arange(0, interval_len, 1) \ns = L/(1+C*np.exp(-k*t))\nplt.plot(t,s)\n\nplt.xlabel(\"Days since January 22\")\nplt.ylabel(\"Total number of infected people\")\n\nplt.show()\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "108c343e2d7c3591ac991f9df33df082a93d5ae5", "size": 180914, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "logistic.ipynb", "max_stars_repo_name": "28left/psumathnotebooks", "max_stars_repo_head_hexsha": "ec948216304e5f234a2f4d0f6bdcfaa1a10c435d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-05-04T14:09:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-04T14:09:51.000Z", "max_issues_repo_path": "logistic.ipynb", "max_issues_repo_name": "28left/psumathnotebooks", "max_issues_repo_head_hexsha": "ec948216304e5f234a2f4d0f6bdcfaa1a10c435d", "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": "logistic.ipynb", "max_forks_repo_name": "28left/psumathnotebooks", "max_forks_repo_head_hexsha": "ec948216304e5f234a2f4d0f6bdcfaa1a10c435d", "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": 384.9234042553, "max_line_length": 128476, "alphanum_fraction": 0.9430502891, "converted": true, "num_tokens": 1136, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.933430812881347, "lm_q2_score": 0.9111797045849583, "lm_q1q2_score": 0.8505232123317232}} {"text": "## Ejercicios Big O()\n### 1. Calcule el costo T(n) para la siguiente función.\n A. Grafique la función junto con otros O() clásicos.\n B. Analice los cambios a medida que el n aumenta.\n C. T(n) esta incluido en la familia de O(n)? Justifique utilizando definición de O().\n D. El costo obtenido es aceptable?\n \nA continuación un ayuda memoria de $O()$ en operaciones sobre Python:\n\n\n```python\nfrom IPython.display import IFrame\nIFrame('https://wiki.python.org/moin/TimeComplexity', width=900, height=350)\n\n\n```\n\n\n\n\n\n\n\n\n\n\n\n```python\ndef dummy_func(lst, n):\n print(\"primer elemento\", lst[0]) \n \n midpoint = int(n / 2)\n \n for val in lst[:midpoint]:\n print(val)\n \n for x in range(10):\n print('o_O')\n```\n\n\n```python\ndummy_func([1, 2, 3, 4], 4)\n```\n\n primer elemento 1\n 1\n 2\n o_O\n o_O\n o_O\n o_O\n o_O\n o_O\n o_O\n o_O\n o_O\n o_O\n\n\n1.A)\nAnalizando las lineas de la función dada podemos ver que:\n- En linea 2 tenemos $O(1)$\n- En linea 4 tenemos $O(1)$\n- En linea 6 y 7 tenemos $O(n/2)$\n- En linea 9 y 10 tenemos $O(10)$\n\nPor lo que nuestro $O(n/2 + 12)$\n\n\n\n1.B) Ahora graficaremos $O(n/2 + 12)$ junto con $O(n)$, $O(n \\log n)$, $O(n^2)$, $O(2^n)$\n\n\n```python\nfrom math import log\nimport numpy as np\nimport matplotlib.pyplot as plt\n%matplotlib inline\nplt.style.use('default')\n\n# Set up runtime comparisons\n\nn = np.linspace(1, 100, 1000)\nlabels = ['Lineal', 'Lineal Log', 'Cuadrática','Exponencial', 'Mi T(n)']\nbig_o = [n, n* np.log(n), n**2, 2**n, n/2 + 12]\n\n# Plot setup\nplt.figure(figsize=(12,10))\nplt.ylim(0, 700)\nplt.xlim(1, 100)\n\nfor i in range(len(big_o)):\n plt.plot(n,big_o[i],label = labels[i])\n\n\nplt.legend(loc=0)\nplt.ylabel('Tiempo relativo de ejecución')\nplt.xlabel('n')\n```\n\n 1.C) Podemos observar que nuestra función con $n_0 = 24, c=1$ $ \\rightarrow T(n) \\in O(n)\\; \\forall\\; n \\geq 24$:\n \n \\begin{equation}\n n/2 + 12 \\leq c.n \\; \\forall\\; n \\geq 24 \\\\\n n/2 + 12 \\leq n \\; \\forall\\; n \\geq 24 \\\\ \n \\end{equation}\n\n1.D)\n\n\nImagen de http://bigocheatsheet.com/\n\n### 2. Desarrolle dos funciones en Python para encontrar el número más chico en una lista. La primer función debería comparar cada número entre si ($O(n^2)$). La segunda función debería ser lineal ($O(n)$).\n A. Grafique ambas funciones.\n B. Con que implementación se quedaría?\n C. Hay correspondencia entre el benchmarking y $O()$. \n\n\n```python\ndef min_value_n2(lst):\n min_value = lst[0] # O(1)\n for i in lst: # O(n)\n for j in lst: # O(n)\n if i < j: # O(1)\n min_value = i # O(1)\n elif j < i: # O(1)\n min_value = j # O(1) \n return min_value # O(1)\n\nmin_value_n2([3, 2, 6, 1])\n# O(4*n^2 + 2)\n```\n\n\n\n\n 1\n\n\n\n\n```python\ndef min_value_n(lst):\n min_value = lst[0] # O(1)\n for i in lst: # O(n)\n if i < min_value: # O(1)\n min_value = i # O(1)\n return min_value # O(1)\n\nmin_value_n([3, 2, 6, 1])\n# O(2*n + 2)\n```\n\n\n\n\n 1\n\n\n\n2.A)\n\n\n```python\nfrom math import log\nimport numpy as np\nimport matplotlib.pyplot as plt\n%matplotlib inline\nplt.style.use('default')\n\n# Set up runtime comparisons\n\nn = np.linspace(1, 100, 1000)\nlabels = ['min_value_n', 'min_value_n2']\nbig_o = [2*n + 2, 4*n**2 + 2]\n\n# Plot setup\nplt.figure(figsize=(12,10))\nplt.ylim(0, 700)\nplt.xlim(1, 100)\n\nfor i in range(len(big_o)):\n plt.plot(n,big_o[i],label = labels[i])\n\n\nplt.legend(loc=0)\nplt.ylabel('Tiempo relativo de ejecución')\nplt.xlabel('n')\n```\n\n2.C)\n\n\n```python\nassert(min_value_n([3, 2, 6, 1]) == min_value_n2([3, 2, 6, 1]))\n```\n\n\n```python\n%timeit min_value_n(range(10000))\n```\n\n 1000 loops, best of 3: 362 µs per loop\n\n\n\n```python\n%timeit min_value_n2(range(10000))\n```\n\n 1 loop, best of 3: 5.51 s per loop\n\n", "meta": {"hexsha": "dd14c07efb73195815ce52f7a5882558ece5f5ac", "size": 139796, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Ejercicios_big_o.ipynb", "max_stars_repo_name": "celiacintas/FTI", "max_stars_repo_head_hexsha": "2c52681e3ed2d5a284aaaaca83e21bb9bb742620", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-07-31T00:41:12.000Z", "max_stars_repo_stars_event_max_datetime": "2017-07-31T00:41:12.000Z", "max_issues_repo_path": "Ejercicios_big_o.ipynb", "max_issues_repo_name": "celiacintas/FTI", "max_issues_repo_head_hexsha": "2c52681e3ed2d5a284aaaaca83e21bb9bb742620", "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": "Ejercicios_big_o.ipynb", "max_forks_repo_name": "celiacintas/FTI", "max_forks_repo_head_hexsha": "2c52681e3ed2d5a284aaaaca83e21bb9bb742620", "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": 307.9207048458, "max_line_length": 80446, "alphanum_fraction": 0.9131734814, "converted": true, "num_tokens": 1304, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513620489619, "lm_q2_score": 0.9489172603342912, "lm_q1q2_score": 0.850468387046378}} {"text": "## RIHAD VARIAWA, Data Scientist - Who has fun LEARNING, EXPLORING & GROWING\n## Linear Equations\nThe equations in the previous lab included one variable, for which you solved the equation to find its value. Now let's look at equations with multiple variables. For reasons that will become apparent, equations with two variables are known as linear equations.\n\n## Solving a Linear Equation\nConsider the following equation:\n\n\\begin{equation}2y + 3 = 3x - 1 \\end{equation}\n\nThis equation includes two different variables, **x** and **y**. These variables depend on one another; the value of x is determined in part by the value of y and vice-versa; so we can't solve the equation and find absolute values for both x and y. However, we *can* solve the equation for one of the variables and obtain a result that describes a relative relationship between the variables.\n\nFor example, let's solve this equation for y. First, we'll get rid of the constant on the right by adding 1 to both sides:\n\n\\begin{equation}2y + 4 = 3x \\end{equation}\n\nThen we'll use the same technique to move the constant on the left to the right to isolate the y term by subtracting 4 from both sides:\n\n\\begin{equation}2y = 3x - 4 \\end{equation}\n\nNow we can deal with the coefficient for y by dividing both sides by 2:\n\n\\begin{equation}y = \\frac{3x - 4}{2} \\end{equation}\n\nOur equation is now solved. We've isolated **y** and defined it as 3x-4/2\n\nWhile we can't express **y** as a particular value, we can calculate it for any value of **x**. For example, if **x** has a value of 6, then **y** can be calculated as:\n\n\\begin{equation}y = \\frac{3\\cdot6 - 4}{2} \\end{equation}\n\nThis gives the result 14/2 which can be simplified to 7.\n\nYou can view the values of **y** for a range of **x** values by applying the equation to them using the following Python code:\n\n\n```python\nimport pandas as pd\n\n# Create a dataframe with an x column containing values from -10 to 10\ndf = pd.DataFrame ({'x': range(-10, 11)})\n\n# Add a y column by applying the solved equation to x\ndf['y'] = (3*df['x'] - 4) / 2\n\n#Display the dataframe\ndf\n```\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
xy
0-10-17.0
1-9-15.5
2-8-14.0
3-7-12.5
4-6-11.0
5-5-9.5
6-4-8.0
7-3-6.5
8-2-5.0
9-1-3.5
100-2.0
111-0.5
1221.0
1332.5
1444.0
1555.5
1667.0
1778.5
18810.0
19911.5
201013.0
\n
\n\n\n\nWe can also plot these values to visualize the relationship between x and y as a line. For this reason, equations that describe a relative relationship between two variables are known as *linear equations*:\n\n\n```python\n%matplotlib inline\nfrom matplotlib import pyplot as plt\n\nplt.plot(df.x, df.y, color=\"grey\", marker = \"o\")\nplt.xlabel('x')\nplt.ylabel('y')\nplt.grid()\nplt.show()\n```\n\nIn a linear equation, a valid solution is described by an ordered pair of x and y values. For example, valid solutions to the linear equation above include:\n- (-10, -17)\n- (0, -2)\n- (9, 11.5)\n\nThe cool thing about linear equations is that we can plot the points for some specific ordered pair solutions to create the line, and then interpolate the x value for any y value (or vice-versa) along the line.\n\n## Intercepts\nWhen we use a linear equation to plot a line, we can easily see where the line intersects the X and Y axes of the plot. These points are known as *intercepts*. The *x-intercept* is where the line intersects the X (horizontal) axis, and the *y-intercept* is where the line intersects the Y (horizontal) axis.\n\nLet's take a look at the line from our linear equation with the X and Y axis shown through the origin (0,0).\n\n\n```python\nplt.plot(df.x, df.y, color=\"grey\")\nplt.xlabel('x')\nplt.ylabel('y')\nplt.grid()\n\n## add axis lines for 0,0\nplt.axhline()\nplt.axvline()\nplt.show()\n```\n\nThe x-intercept is the point where the line crosses the X axis, and at this point, the **y** value is always 0. Similarly, the y-intercept is where the line crosses the Y axis, at which point the **x** value is 0. So to find the intercepts, we need to solve the equation for **x** when **y** is 0.\n\nFor the x-intercept, our equation looks like this:\n\n\\begin{equation}0 = \\frac{3x - 4}{2} \\end{equation}\n\nWhich can be reversed to make it look more familar with the x expression on the left:\n\n\\begin{equation}\\frac{3x - 4}{2} = 0 \\end{equation}\n\nWe can multiply both sides by 2 to get rid of the fraction:\n\n\\begin{equation}3x - 4 = 0 \\end{equation}\n\nThen we can add 4 to both sides to get rid of the constant on the left:\n\n\\begin{equation}3x = 4 \\end{equation}\n\nAnd finally we can divide both sides by 3 to get the value for x:\n\n\\begin{equation}x = \\frac{4}{3} \\end{equation}\n\nWhich simplifies to:\n\n\\begin{equation}x = 1\\frac{1}{3} \\end{equation}\n\nSo the x-intercept is 11/3 (approximately 1.333).\n\nTo get the y-intercept, we solve the equation for y when x is 0:\n\n\\begin{equation}y = \\frac{3\\cdot0 - 4}{2} \\end{equation}\n\nSince 3 x 0 is 0, this can be simplified to:\n\n\\begin{equation}y = \\frac{-4}{2} \\end{equation}\n\n-4 divided by 2 is -2, so:\n\n\\begin{equation}y = -2 \\end{equation}\n\nThis gives us our y-intercept, so we can plot both intercepts on the graph:\n\n\n```python\nplt.plot(df.x, df.y, color=\"grey\")\nplt.xlabel('x')\nplt.ylabel('y')\nplt.grid()\n\n## add axis lines for 0,0\nplt.axhline()\nplt.axvline()\nplt.annotate('x-intercept',(1.333, 0))\nplt.annotate('y-intercept',(0,-2))\nplt.show()\n```\n\nThe ability to calculate the intercepts for a linear equation is useful, because you can calculate only these two points and then draw a straight line through them to create the entire line for the equation.\n\n## Slope\nIt's clear from the graph that the line from our linear equation describes a slope in which values increase as we travel up and to the right along the line. It can be useful to quantify the slope in terms of how much **x** increases (or decreases) for a given change in **y**. In the notation for this, we use the greek letter Δ (*delta*) to represent change:\n\n\\begin{equation}slope = \\frac{\\Delta{y}}{\\Delta{x}} \\end{equation}\n\nSometimes slope is represented by the variable ***m***, and the equation is written as:\n\n\\begin{equation}m = \\frac{y_{2} - y_{1}}{x_{2} - x_{1}} \\end{equation}\n\nAlthough this form of the equation is a little more verbose, it gives us a clue as to how we calculate slope. What we need is any two ordered pairs of x,y values for the line - for example, we know that our line passes through the following two points:\n- (0,-2)\n- (6,7)\n\nWe can take the x and y values from the first pair, and label them x1 and y1; and then take the x and y values from the second point and label them x2 and y2. Then we can plug those into our slope equation:\n\n\\begin{equation}m = \\frac{7 - -2}{6 - 0} \\end{equation}\n\nThis is the same as:\n\n\\begin{equation}m = \\frac{7 + 2}{6 - 0} \\end{equation}\n\nThat gives us the result 9/6 which is 11/2 or 1.5 .\n\nSo what does that actually mean? Well, it tells us that for every change of **1** in x, **y** changes by 11/2 or 1.5. So if we start from any point on the line and move one unit to the right (along the X axis), we'll need to move 1.5 units up (along the Y axis) to get back to the line.\n\nYou can plot the slope onto the original line with the following Python code to verify it fits:\n\n\n```python\nplt.plot(df.x, df.y, color=\"grey\")\nplt.xlabel('x')\nplt.ylabel('y')\nplt.grid()\nplt.axhline()\nplt.axvline()\n\n# set the slope\nm = 1.5\n\n# get the y-intercept\nyInt = -2\n\n# plot the slope from the y-intercept for 1x\nmx = [0, 1]\nmy = [yInt, yInt + m]\nplt.plot(mx,my, color='red', lw=5)\n\nplt.show()\n```\n\n### Slope-Intercept Form\nOne of the great things about algebraic expressions is that you can write the same equation in multiple ways, or *forms*. The *slope-intercept form* is a specific way of writing a 2-variable linear equation so that the equation definition includes the slope and y-intercept. The generalised slope-intercept form looks like this:\n\n\\begin{equation}y = mx + b \\end{equation}\n\nIn this notation, ***m*** is the slope and ***b*** is the y-intercept.\n\nFor example, let's look at the solved linear equation we've been working with so far in this section:\n\n\\begin{equation}y = \\frac{3x - 4}{2} \\end{equation}\n\nNow that we know the slope and y-intercept for the line that this equation defines, we can rewrite the equation as:\n\n\\begin{equation}y = 1\\frac{1}{2}x + -2 \\end{equation}\n\nYou can see intuitively that this is true. In our original form of the equation, to find y we multiply x by three, subtract 4, and divide by two - in other words, x is half of 3x - 4; which is 1.5x - 2. So these equations are equivalent, but the slope-intercept form has the advantages of being simpler, and including two key pieces of information we need to plot the line represented by the equation. We know the y-intecept that the line passes through (0, -2), and we know the slope of the line (for every x, we add 1.5 to y.\n\nLet's recreate our set of test x and y values using the slope-intercept form of the equation, and plot them to prove that this describes the same line:\n\n\n```python\n%matplotlib inline\n\nimport pandas as pd\nfrom matplotlib import pyplot as plt\n\n# Create a dataframe with an x column containing values from -10 to 10\ndf = pd.DataFrame ({'x': range(-10, 11)})\n\n# Define slope and y-intercept\nm = 1.5\nyInt = -2\n\n# Add a y column by applying the slope-intercept equation to x\ndf['y'] = m*df['x'] + yInt\n\n# Plot the line\nfrom matplotlib import pyplot as plt\n\nplt.plot(df.x, df.y, color=\"grey\")\nplt.xlabel('x')\nplt.ylabel('y')\nplt.grid()\nplt.axhline()\nplt.axvline()\n\n# label the y-intercept\nplt.annotate('y-intercept',(0,yInt))\n\n# plot the slope from the y-intercept for 1x\nmx = [0, 1]\nmy = [yInt, yInt + m]\nplt.plot(mx,my, color='red', lw=5)\n\nplt.show()\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "416f4582abb734369e193b87f9b4a4192b601085", "size": 85791, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "AI Professional/2 - Essential Mathematics For Artificial Intelligence/DAT256x/Module01/01-02-Linear Equations.ipynb", "max_stars_repo_name": "2series/DataScience-Courses", "max_stars_repo_head_hexsha": "5ee71305721a61dfc207d8d7de67a9355530535d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-02-23T07:40:39.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-23T07:40:39.000Z", "max_issues_repo_path": "AI Professional/2 - Essential Mathematics For Artificial Intelligence/DAT256x/Module01/01-02-Linear Equations.ipynb", "max_issues_repo_name": "2series/DataScience-Courses", "max_issues_repo_head_hexsha": "5ee71305721a61dfc207d8d7de67a9355530535d", "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": "AI Professional/2 - Essential Mathematics For Artificial Intelligence/DAT256x/Module01/01-02-Linear Equations.ipynb", "max_forks_repo_name": "2series/DataScience-Courses", "max_forks_repo_head_hexsha": "5ee71305721a61dfc207d8d7de67a9355530535d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-12-05T11:04:58.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-26T10:42:08.000Z", "avg_line_length": 150.2469352014, "max_line_length": 14568, "alphanum_fraction": 0.8562320057, "converted": true, "num_tokens": 3598, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109742068041, "lm_q2_score": 0.894789468908171, "lm_q1q2_score": 0.8504177308550036}} {"text": "```python\nfrom sympy import *\nx, y, z, t = symbols('x y z t')\n```\n\n## Linear algebra\n\nA matrix $A \\in \\mathbb{R}^{m\\times n}$ is a rectangular array of real numbers with $m$ rows and $n$ columns.\nTo specify a matrix $A$, we specify the values for its $mn$ components $a_{11}, a_{12}, \\ldots, a_{mn}$\nas a list of lists:\n\n\n```python\nA = Matrix( [[ 2,-3,-8, 7],\n [-2,-1, 2,-7],\n [ 1, 0,-3, 6]] )\n```\n\nUse the square brackets to access the matrix elements or to obtain a submatrix:\n\n\n```python\nA[0,1] # row 0, col 1 of A\n```\n\n\n\n\n$\\displaystyle -3$\n\n\n\n\n```python\nA[0:2,0:3] # top-left 2x3 submatrix of A\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}2 & -3 & -8\\\\-2 & -1 & 2\\end{matrix}\\right]$\n\n\n\nSome commonly used matrices can be created with shortcut methods:\n\n\n```python\neye(2) # 2x2 identity matrix\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}1 & 0\\\\0 & 1\\end{matrix}\\right]$\n\n\n\n\n```python\nzeros(2, 3)\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}0 & 0 & 0\\\\0 & 0 & 0\\end{matrix}\\right]$\n\n\n\nStandard algebraic operations like \naddition `+`, subtraction `-`, multiplication `*`,\nand exponentiation `**` work as expected for `Matrix` objects.\nThe `transpose` operation flips the matrix through its diagonal:\n\n\n```python\nA.transpose() # the same as A.T\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}2 & -2 & 1\\\\-3 & -1 & 0\\\\-8 & 2 & -3\\\\7 & -7 & 6\\end{matrix}\\right]$\n\n\n\nRecall that the transpose is also used to convert row vectors into column vectors and vice versa.\n\n### Row operations\n\n\n```python\nM = eye(3)\nM[1,:] = M[1,:] + 3*M[0,:]\nM\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}1 & 0 & 0\\\\3 & 1 & 0\\\\0 & 0 & 1\\end{matrix}\\right]$\n\n\n\nThe notation `M[i,:]` refers to entire rows of the matrix.\nThe first argument specifies the $0$-based row index,\nfor example the first row of~`M` is `M[0,:]`.\nThe code example above implements the row operation $R_2 \\gets R_2 + 3R_1$.\n\nTo scale a row `i` by constant `c`, use the command `M[i,:] = c*M[i,:]`.\n\nTo swap rows `i` and `j`, use can use the `Python` tuple-assignment syntax `M[i,:], M[j,:] = M[j,:], M[i,:]`.\n\n### Reduced row echelon form\n\nThe Gauss—Jordan elimination procedure is a sequence of row operations you can perform\non any matrix to bring it to its *reduced row echelon form* (RREF).\nIn `SymPy`, matrices have a `rref` method that computes their RREF:\n\n\n```python\nA = Matrix( [[2,-3,-8, 7],\n [-2,-1,2,-7],\n [1, 0,-3, 6]])\nA.rref() # RREF of A, location of pivots\n```\n\n\n\n\n (Matrix([\n [1, 0, 0, 0],\n [0, 1, 0, 3],\n [0, 0, 1, -2]]),\n (0, 1, 2))\n\n\n\nNote the `rref` method returns a tuple of values:\nthe first value is the RREF of $A$,\nwhile the second tells you the indices of the leading ones (also known as pivots) in the RREF of $A$.\nTo get just the RREF of $A$, select the $0^\\mathrm{th}$ entry form the tuple: `A.rref()[0]`.\n\n### Matrix fundamental spaces\n\nConsider the matrix $A \\in \\mathbb{R}^{m\\times n}$.\nThe fundamental spaces of a matrix are its column space $\\mathcal{C}(A)$, \nits null space $\\mathcal{N}(A)$,\nand its row space $\\mathcal{R}(A)$.\nThese vector spaces are important when you consider the matrix product\n$A\\vec{x}=\\vec{y}$ as “applying” the linear transformation $T_A:\\mathbb{R}^n \\to \\mathbb{R}^m$\nto an input vector $\\vec{x} \\in \\mathbb{R}^n$ to produce the output vector $\\vec{y} \\in \\mathbb{R}^m$.\n\n**Linear transformations** $T_A:\\mathbb{R}^n \\to \\mathbb{R}^m$ (vector functions)\n**are equivalent to $m\\times n$ matrices**.\nThis is one of the fundamental ideas in linear algebra.\nYou can think of $T_A$ as the abstract description of the transformation \nand $A \\in \\mathbb{R}^{m\\times n}$ as a concrete implementation of $T_A$.\nBy this equivalence, \nthe fundamental spaces of a matrix $A$\ntell us facts about the domain and image of the linear transformation $T_A$.\nThe columns space $\\mathcal{C}(A)$ is the same as the image space space $\\textrm{Im}(T_A)$ (the set of all possible outputs).\nThe null space $\\mathcal{N}(A)$ is the same as the kernel $\\textrm{Ker}(T_A)$ (the set of inputs that $T_A$ maps to the zero vector).\nThe row space $\\mathcal{R}(A)$ is the orthogonal complement of the null space.\nInput vectors in the row space of $A$ are in one-to-one correspondence with the output vectors in the column space of $A$.\n\nOkay, enough theory! Let's see how to compute the fundamental spaces of the matrix $A$ defined above.\nThe non-zero rows in the reduced row echelon form of $A$ are a basis for its row space:\n\n\n```python\n[ A.rref()[0][r,:] for r in A.rref()[1] ] # R(A)\n```\n\n\n\n\n [Matrix([[1, 0, 0, 0]]), Matrix([[0, 1, 0, 3]]), Matrix([[0, 0, 1, -2]])]\n\n\n\nThe column space of $A$ is the span of the columns of $A$ that contain the pivots\nin the reduced row echelon form of $A$:\n\n\n```python\n[ A[:,c] for c in A.rref()[1] ] # C(A)\n```\n\n\n\n\n [Matrix([\n [ 2],\n [-2],\n [ 1]]),\n Matrix([\n [-3],\n [-1],\n [ 0]]),\n Matrix([\n [-8],\n [ 2],\n [-3]])]\n\n\n\nNote we took columns from the original matrix $A$ and not its RREF.\n\nTo find the null space of $A$, call its `nullspace` method:\n\n\n```python\nA.nullspace() # N(A)\n```\n\n\n\n\n [Matrix([\n [ 0],\n [-3],\n [ 2],\n [ 1]])]\n\n\n\n### Determinants\n\nThe determinant of a matrix, \ndenoted $\\det(A)$ or $|A|$, \nis a particular way to multiply the entries of the matrix to produce a single number.\n\n\n```python\nM = Matrix( [[1, 2, 3], \n [2,-2, 4],\n [2, 2, 5]] )\nM.det()\n```\n\n\n\n\n$\\displaystyle 2$\n\n\n\nDeterminants are used for all kinds of tasks:\nto compute areas and volumes,\nto solve systems of equations, \nand to check whether a matrix is invertible or not.\n\n### Matrix inverse\n\nFor every invertible matrix $A$,\nthere exists an inverse matrix $A^{-1}$ which *undoes* the effect of $A$.\nThe cumulative effect of the product of $A$ and $A^{-1}$ (in any order)\nis the identity matrix: $AA^{-1}= A^{-1}A=\\mathbb{1}$.\n\n\n```python\nA = Matrix( [[1,2], \n [3,9]] ) \nA.inv()\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}3 & - \\frac{2}{3}\\\\-1 & \\frac{1}{3}\\end{matrix}\\right]$\n\n\n\n\n```python\nA.inv()*A\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}1 & 0\\\\0 & 1\\end{matrix}\\right]$\n\n\n\n\n```python\nA*A.inv()\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}1 & 0\\\\0 & 1\\end{matrix}\\right]$\n\n\n\nThe matrix inverse $A^{-1}$ plays the role of division by $A$.\n\n### Eigenvectors and eigenvalues\n\nWhen a matrix is multiplied by one of its eigenvectors the output\nis the same eigenvector multiplied by a constant $A\\vec{e}_\\lambda =\\lambda\\vec{e}_\\lambda$.\nThe constant $\\lambda$ (the Greek letter *lambda*) is called an *eigenvalue* of $A$.\n\nTo find the eigenvalues of a matrix, start from the definition $A\\vec{e}_\\lambda =\\lambda\\vec{e}_\\lambda$,\ninsert the identity $\\mathbb{1}$, \nand rewrite it as a null-space problem:\n\n$$\nA\\vec{e}_\\lambda =\\lambda\\mathbb{1}\\vec{e}_\\lambda\n\\qquad\n\\Rightarrow\n\\qquad\n\\left(A - \\lambda\\mathbb{1}\\right)\\vec{e}_\\lambda = \\vec{0}.\n$$\n\nThis equation will have a solution whenever $|A - \\lambda\\mathbb{1}|=0$.(The invertible matrix theorem states\nthat a matrix has a non-empty null space if and only if its determinant is zero.)\nThe eigenvalues of $A \\in \\mathbb{R}^{n \\times n}$, \ndenoted $\\{ \\lambda_1, \\lambda_2, \\ldots, \\lambda_n \\}$,\\\nare the roots of the *characteristic polynomial* $p(\\lambda)=|A - \\lambda \\mathbb{1}|$.\n\n\n```python\nA = Matrix( [[ 9, -2],\n [-2, 6]] )\nA.eigenvals() # same as solve(det(A-eye(2)*x), x)\n # return eigenvalues with their multiplicity\n```\n\n\n\n\n {10: 1, 5: 1}\n\n\n\n\n```python\nA.eigenvects()\n```\n\n\n\n\n [(5,\n 1,\n [Matrix([\n [1/2],\n [ 1]])]),\n (10,\n 1,\n [Matrix([\n [-2],\n [ 1]])])]\n\n\n\nCertain matrices can be written entirely in terms of their eigenvectors and their eigenvalues.\nConsider the matrix $\\Lambda$ (capital Greek *L*) that has the eigenvalues of the matrix $A$ on the diagonal, \nand the matrix $Q$ constructed from the eigenvectors of $A$ as columns:\n\n$$\n\\Lambda = \n\\begin{bmatrix}\n\\lambda_1\t& \\cdots & 0 \\\\\n\\vdots \t& \\ddots & 0 \\\\\n0 \t& 0 & \\lambda_n\n\\end{bmatrix}\\!,\n\\ \\ \nQ \\: = \n\\begin{bmatrix}\n| & & | \\\\\n\\vec{e}_{\\lambda_1} & \\! \\cdots \\! & \\large\\vec{e}_{\\lambda_n} \\\\\n| & & | \n\\end{bmatrix}\\!,\n\\ \\ \n\\textrm{then}\n\\ \\ \nA = Q \\Lambda Q^{-1}.\n$$\n\nMatrices that can be written this way are called *diagonalizable*.\nTo *diagonalize* a matrix $A$ is to find its $Q$ and $\\Lambda$ matrices:\n\n\n```python\nQ, L = A.diagonalize()\nQ # the matrix of eigenvectors as columns \n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}1 & -2\\\\2 & 1\\end{matrix}\\right]$\n\n\n\n\n```python\nQ.inv()\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}\\frac{1}{5} & \\frac{2}{5}\\\\- \\frac{2}{5} & \\frac{1}{5}\\end{matrix}\\right]$\n\n\n\n\n```python\nL # the matrix of eigenvalues\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}5 & 0\\\\0 & 10\\end{matrix}\\right]$\n\n\n\n\n```python\nQ*L*Q.inv() # eigendecomposition of A\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}9 & -2\\\\-2 & 6\\end{matrix}\\right]$\n\n\n\n\n```python\nQ.inv()*A*Q # obtain L from A and Q\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}5 & 0\\\\0 & 10\\end{matrix}\\right]$\n\n\n\nNot all matrices are diagonalizable.\nYou can check if a matrix is diagonalizable by calling its `is_diagonalizable` method:\n\n\n```python\nA.is_diagonalizable()\n```\n\n\n\n\n True\n\n\n\n\n```python\nB = Matrix( [[1, 3],\n [0, 1]] )\nB.is_diagonalizable()\n```\n\n\n\n\n False\n\n\n\n\n```python\nB.eigenvals() # eigenvalue 1 with multiplicity 2\n```\n\n\n\n\n {1: 2}\n\n\n\n\n```python\nB.eigenvects()\n```\n\n\n\n\n [(1,\n 2,\n [Matrix([\n [1],\n [0]])])]\n\n\n\nThe matrix $B$ is not diagonalizable because it doesn't have a full set of eigenvectors.\nTo diagonalize a $2\\times 2$ matrix, we need two orthogonal eigenvectors but $B$ has only a single eigenvector.\nTherefore, we can't construct the matrix of eigenvectors $Q$ (we're missing a column!) \nand so $B$ is not diagonalizable.\n\nNon-square matrices don't have eigenvectors and therefore don't have an eigendecomposition.\nInstead, we can use the *singular value decomposition* to break up a non-square matrix $A$ into \nleft singular vectors,\nright singular vectors, \nand a diagonal matrix of singular values.\nUse the `singular_values` method on any matrix to find its singular values.\n", "meta": {"hexsha": "a941f038580db7c17814359d722b910b1888f2b7", "size": 24722, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/Linear-algebra.ipynb", "max_stars_repo_name": "minireference/sympytut_notebooks", "max_stars_repo_head_hexsha": "6669e7bfccef9e70ae029ac5cbb54cb6cbc31652", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2016-08-29T12:04:19.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-23T05:14:52.000Z", "max_issues_repo_path": "notebooks/Linear-algebra.ipynb", "max_issues_repo_name": "minireference/sympytut_notebooks", "max_issues_repo_head_hexsha": "6669e7bfccef9e70ae029ac5cbb54cb6cbc31652", "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": "notebooks/Linear-algebra.ipynb", "max_forks_repo_name": "minireference/sympytut_notebooks", "max_forks_repo_head_hexsha": "6669e7bfccef9e70ae029ac5cbb54cb6cbc31652", "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": 22.7433302668, "max_line_length": 144, "alphanum_fraction": 0.4759728177, "converted": true, "num_tokens": 3306, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012686491107, "lm_q2_score": 0.8991213684847575, "lm_q1q2_score": 0.8503901309824082}} {"text": "```python\nimport numpy as np\np = np.poly1d([1,0,0,0,0,0])\nprint (p)\nprint (p.integ())\np.integ()(1.0) - p.integ()(-1.0)\n```\n\n 5\n 1 x\n 6\n 0.1667 x\n\n\n\n\n\n 0.0\n\n\n\n\n```python\nfrom sympy import integrate, symbols\nx, y = symbols('x y', real=True)\nintegrate(x**5, x)\n```\n\n\n\n\n x**6/6\n\n\n\n\n```python\nintegrate(x**5, (x, -1, 1))\n```\n\n\n\n\n 0\n\n\n\n\n```python\nfrom sympy import N, exp as Exp, sin as Sin\nintegrate(Exp(-x) * Sin(x), x)\n```\n\n\n\n\n -exp(-x)*sin(x)/2 - exp(-x)*cos(x)/2\n\n\n\n\n```python\nintegrate(Exp(-x) * Sin(x), (x, 0, 1))\n```\n\n\n\n\n -exp(-1)*sin(1)/2 - exp(-1)*cos(1)/2 + 1/2\n\n\n\n\n```python\nN(_)\n```\n\n\n\n\n 0.245837007000237\n\n\n\n\n```python\nintegrate(Sin(x) / x, x)\n```\n\n\n\n\n Si(x)\n\n\n\n\n```python\nintegrate(Sin(x) / x, (x, 0, 1))\n```\n\n\n\n\n Si(1)\n\n\n\n\n```python\nN(_)\n```\n\n\n\n\n 0.946083070367183\n\n\n\n\n```python\nintegrate(x**1, (x, 0, 1))\n```\n\n\n\n\n 1/2\n\n\n\n\n```python\nfrom sympy import oo\nintegrate(Exp(-x**2), (x,0,+oo))\n```\n\n\n\n\n sqrt(pi)/2\n\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "530a2c1dc42fcbbab6385379deaba88eaf12c531", "size": 4924, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Chapter08/Integration.ipynb", "max_stars_repo_name": "PacktPublishing/SciPy-Recipes", "max_stars_repo_head_hexsha": "fdea8e3bd6b161402ed824624819aa788e544eed", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2017-12-28T05:01:19.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-08T13:10:39.000Z", "max_issues_repo_path": "Chapter08/Integration.ipynb", "max_issues_repo_name": "PacktPublishing/SciPy-Recipes", "max_issues_repo_head_hexsha": "fdea8e3bd6b161402ed824624819aa788e544eed", "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": "Chapter08/Integration.ipynb", "max_forks_repo_name": "PacktPublishing/SciPy-Recipes", "max_forks_repo_head_hexsha": "fdea8e3bd6b161402ed824624819aa788e544eed", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10, "max_forks_repo_forks_event_min_datetime": "2017-12-24T09:25:55.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-17T22:57:17.000Z", "avg_line_length": 16.6351351351, "max_line_length": 52, "alphanum_fraction": 0.4384646629, "converted": true, "num_tokens": 400, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768604361741, "lm_q2_score": 0.9005297901222472, "lm_q1q2_score": 0.8502593899668701}} {"text": "# The Gaussian (Normal) Distribution\n\n## Probability Distribution Function\n\nThe Normal (Gaussian) distribution probability distribution function is\n\n\\begin{equation}\nf\\left(x; \\mu, \\sigma\\right) = \\frac{1}{\\sqrt{2\\pi}\\sigma}\\,e^{-\\left(x-\\mu\\right)^2/2\\sigma^2},\n\\end{equation}\n\nnormalized to unity,\n$$\n\\int\\limits_{-\\infty}^{\\infty} f\\left(x; \\mu,\\sigma\\right)\\,dx = 1,\n$$\nis symmetrically distributed about its mean, $\\mu$, with width $\\sigma$.\n\n## Full Width at Half Maximum (FWHM)\n\nThe full width at half maximum (FWHM) is the distance between points on a curve at which the function reaches half its maximum value. The FWHM is often used to describe the \"width\" of a distribution.\n\nFor a 1-dimensional Gaussian, it is seen that as the maximum value occurs as $x = \\mu$ (by definition), half of the maximum value is\n\n\\begin{align*}\n\\left.\\frac{1}{\\sqrt{2\\pi}\\sigma}\\,e^{-\\left(x-\\mu\\right)^2/2\\sigma^2}\\right|_{x = x \\text{ of (max/2)}} &= \\frac{1}{2} f\\left(x_{\\text{max}}\\right)\\\\\n &= \\frac{1}{2} f\\left(\\mu\\right) = \\frac{1}{2} \\frac{1}{\\sqrt{2\\pi}\\sigma},\n\\end{align*}\n\nresulting in the equality\n\n\\begin{equation*}\ne^{-\\left(x-\\mu\\right)^2/2\\sigma^2} = \\frac{1}{2},\n\\end{equation*}\n\nwhich is (taking the log)\n\n\\begin{equation*}\n-\\frac{\\left(x-\\mu\\right)^2}{2\\sigma^2} = -\\ln2.\n\\end{equation*}\n\nThus, solving the equality,\n$$\n\\left(x-\\mu\\right)^2 = 2\\sigma^2 \\ln2,\n$$\nyields\n$$\nx_{\\pm} = \\pm \\sigma \\sqrt{2 \\ln 2} + \\mu.\n$$\n\nThus, the FWHM is\n\n\\begin{align*}\n\\text{FWHM} &= x_{+} - x_{-}\\\\\n &= \\left(\\sigma \\sqrt{2 \\ln 2} + \\mu\\right) - \\left(-\\sigma \\sqrt{2 \\ln 2} + \\mu\\right)\\\\\n &= \\boxed{2\\sqrt{2\\ln2}\\sigma}\\,.\n\\end{align*}\n\n**N.B.:** It is seen that the FWHM for a Gaussian is _independent_ of both the normalization constant and the mean, and is only dependent on the standard devaiation of the Gaussian.\n\n## Probability and the Error Function\n\nThe probability that a Normally distributed random variable will lie in a range of values symmetrically integrated over is given by\n\n\\begin{align*}\n\\text{Pr}\\left(\\mu - y \\leq x \\leq \\mu + y\\right) &= \\int\\limits_{\\mu - y}^{\\mu + y}\\frac{1}{\\sqrt{2\\pi}\\sigma}\\,e^{-\\left(x-\\mu\\right)^2/2\\sigma^2}\\,dx\\\\\n &= \\int\\limits_{\\mu}^{\\mu + y}\\frac{2}{\\sqrt{2\\pi}\\sigma}\\,e^{-\\left(x-\\mu\\right)^2/2\\sigma^2}\\,dx.\n\\end{align*}\n\nMaking the substitution\n$$\nt = \\frac{\\left(x-\\mu\\right)}{\\sqrt{2}\\sigma},\n$$\nthen\n\n\\begin{align*}\n\\text{Pr}\\left(\\mu - y \\leq x \\leq \\mu + y\\right) &= \\int\\limits_{\\mu}^{\\mu + y}\\frac{2}{\\sqrt{2\\pi}\\sigma}\\,e^{-\\left(x-\\mu\\right)^2/2\\sigma^2}\\,dx\\\\\n &= \\boxed{\\frac{2}{\\sqrt{\\pi}} \\int\\limits_{0}^{y/\\sqrt{2}\\sigma}e^{-t^2}\\,dt \\equiv \\text{erf}\\left(\\frac{y}{\\sqrt{2}\\sigma}\\right)}\\,.\n\\end{align*}\n\n## Cumulative Distribution Function (cdf)\n\nFor the cumulative distribution function (cdf),\n$$\n\\Phi\\left(x\\right) = \\int\\limits_{-\\infty}^{x}f\\left(t;\\mu,\\sigma\\right)\\,dt,\n$$\nit is seen, noting from the form of the error function, that\n\n\\begin{equation*}\n\\frac{2}{\\sqrt{\\pi}} \\int\\limits_{0}^{y/\\sqrt{2}\\sigma}e^{-t^2}\\,dt = \\frac{2}{\\sqrt{2 \\pi}} \\int\\limits_{0}^{y/\\sigma}e^{-t^2/2}\\,dt = \\text{erf}\\left(\\frac{y}{\\sqrt{2}\\sigma}\\right),\n\\end{equation*}\n\n\n```python\nimport sympy as sym\nsym.init_printing(use_unicode=True, wrap_line=False, no_global=True)\nfrom sympy.abc import sigma\n```\n\n\n```python\nt, y, = sym.symbols('t y')\nsym.integrate((2/sym.sqrt(sym.pi)) * sym.exp(-t**2), (t, 0, y/(sym.sqrt(2) * sigma)))\n```\n\n\n```python\nsym.integrate((2/sym.sqrt(2 * sym.pi)) * sym.exp(-t**2/2), (t, 0, y/sigma))\n```\n\nthen for the standard Gaussian ($\\mu = 0$, $\\sigma=1$)\n\n\\begin{align*}\n\\Phi\\left(x\\right) &= \\frac{1}{\\sqrt{2\\pi}}\\int\\limits_{-\\infty}^{x} e^{-t^2/2}\\,dt\\\\\n &= \\frac{1}{\\sqrt{2\\pi}}\\int\\limits_{-\\infty}^{0} e^{-t^2/2}\\,dt + \\frac{1}{\\sqrt{2\\pi}}\\int\\limits_{0}^{x} e^{-t^2/2}\\,dt\\\\\n &= \\frac{1}{2} + \\frac{1}{2} \\text{erf}\\left(\\frac{x}{\\sqrt{2}}\\right)\\\\\n &= \\frac{1}{2} \\left(1 + \\text{erf}\\left(\\frac{x}{\\sqrt{2}}\\right)\\right)\n\\end{align*}\n\nso it is likewise seen that\n\n\\begin{align*}\n\\text{Pr}\\left(\\mu - n \\sigma \\leq x \\leq \\mu + n\\sigma\\right) &= \\Phi(n) - \\Phi(-n)\\\\\n &= \\Phi(n) - \\left(1-\\Phi(n)\\right)\\\\\n &= \\frac{1}{2} \\left(1 + \\text{erf}\\left(\\frac{n}{\\sqrt{2}}\\right)\\right) - \\left[1-\\frac{1}{2} \\left(1 + \\text{erf}\\left(\\frac{n}{\\sqrt{2}}\\right)\\right)\\right]\\\\\n &= \\text{erf}\\left(\\frac{n}{\\sqrt{2}}\\right).\n\\end{align*}\n\n**Show this for:** generic normal distribution $f$ with mean $\\mu$ and std $\\sigma$\n\nIt is noted that in the case that $\\left|y\\right|=n\\sigma$,\n$$\n\\text{Pr}\\left(\\mu - y \\leq x \\leq \\mu + y\\right) = \\text{Pr}\\left(\\mu - n\\sigma \\leq x \\leq \\mu + n\\sigma\\right) = \\text{erf}\\left(\\frac{n}{\\sqrt{2}}\\right).\n$$\n\nSo, for $n=1$,\n$$\n\\text{Pr}\\left(\\mu - \\sigma \\leq x \\leq \\mu + \\sigma\\right) = \\text{erf}\\left(\\frac{1}{\\sqrt{2}}\\right)\n$$\n\nHowever, at this point we are at an impass analytically, as the integral of a Gaussian function over a finite range has no analytical solution, and must be evaluated numerically.\n\n\n```python\nimport math\nfrom scipy import special as special\n```\n\n\n```python\ndef prob_n_sigma(n):\n return special.erf(n/math.sqrt(2.))\n```\n\n\n```python\nprob_n_sigma(1)\n```\n\n## $p$-values\n\n### Two-Tailed $p$-value\n\n### One-Tailed $p$-value\n", "meta": {"hexsha": "cfeb51b1efd8837aae6439a25fcf4d96338f9c79", "size": 15516, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Notebooks/Introductory/Gaussian-Distribution.ipynb", "max_stars_repo_name": "fizisist/Statistics-Notes", "max_stars_repo_head_hexsha": "9399bca77abc36ee342f8af2fadddffd79390bed", "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/Introductory/Gaussian-Distribution.ipynb", "max_issues_repo_name": "fizisist/Statistics-Notes", "max_issues_repo_head_hexsha": "9399bca77abc36ee342f8af2fadddffd79390bed", "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/Introductory/Gaussian-Distribution.ipynb", "max_forks_repo_name": "fizisist/Statistics-Notes", "max_forks_repo_head_hexsha": "9399bca77abc36ee342f8af2fadddffd79390bed", "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.7892376682, "max_line_length": 1578, "alphanum_fraction": 0.6137535447, "converted": true, "num_tokens": 1987, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768604361741, "lm_q2_score": 0.900529781446146, "lm_q1q2_score": 0.8502593817750962}} {"text": "$$f(x) = x^2$$\n\n### The probability of getting (k) heads when flipping (n) coins is\n\\begin{equation*}\nP(E) = {n \\choose k} p^k (1-p)^{ n-k}\n\\end{equation*}\n\n\\begin{equation}\n\\int y\\, \\mathrm{d}x\n\\end{equation}\n\n## Mean, Median, Mode\n\nMean, median, and mode are different measures of center in a numerical data set. They each try to summarize a dataset with a single number to represent a \"typical\" data point from the dataset.\n\n__Mean:__ The \"average\" number; found by adding all data points and dividing by the number of data points.\n\n\n\\begin{equation}\n\\bar{y} = \\frac{\\sum y}{N}\n\\end{equation}\n\n- $\\sum y$ Take all the values and add them up\n- divide by the total number of observations you have\n\n__Median__ The middle number found by ordering all data points and picking out the one in the middle (or if there are two middle numbers, taking the mean of those two numbers).\n\n\nTo get the median\n\n\\begin{equation}\ny = \\tilde{x}\n\\end{equation}\n\n$ y = [1,2,3,4,4,3,2,1] $\n\n$ y = 4 $\n\n\nThe __mode__ is the most commonly occurring data point in a dataset. The mode is useful when there are a lot of repeated values in a dataset. There can be no mode, one mode, or multiple modes in a dataset.\n\n## Standard Deviation\n\n__Standard deviation__ is a number used to tell how measurements for a group are spread out from the average (mean), or expected value. A low standard deviation means that most of the numbers are close to the average. A high standard deviation means that the numbers are more spread out.\n\n$$s = \\sqrt{\\frac{1}{N-1} \\sum_{i=1}^N (x_i - \\overline{x})^2}$$\n\n## Variance\n\nThe __Variance__ is defined as: The average of the squared differences from the Mean. To calculate the variance follow these steps: Find the __Mean__, Then for each number: subtract the __Mean__ and square the result (the squared difference).\n\n$$\\sigma^2 = \\frac{\\displaystyle\\sum_{i=1}^{n}(x_i - \\mu)^2} {n}$$\n\n## What is RMSE\n\n $RMSE = \\sqrt{\\frac{1}{n}\\sum_{i=1}^{n}{\\Big(\\frac{d_i -f_i}{\\sum_i}\\Big)^2}}$\n \n \n ## Root mean squared error (RMSE)\nRMSE is a quadratic scoring rule that also measures the average magnitude of the error. It’s the square root of the average squared differences between prediction and actual observation. \n\n $RMSE = \\sqrt{\\frac{1}{n}\\Sigma_{i=1}^{n}{\\Big(\\frac{d_i -f_i}{\\Sigma_i}\\Big)^2}}$\n \n we can do this simply from sklearn:\n\n```python\nfrom sklearn.metrics import mean_squared_error\nfrom math import sqrt\nrmse = sqrt(mean_squared_error(y_actual, y_predicted))\nprint(rmse)\n\n# another way\nn = len(predictions)\nrmse = np.linalg.norm(predictions - targets) / np.sqrt(n)\n\n# and another way\nfrom sklearn.metrics import mean_squared_error\nfrom math import sqrt\nexpected = [0.0, 0.5, 0.0, 0.5, 0.0]\npredictions = [0.2, 0.4, 0.1, 0.6, 0.2]\nmse = mean_squared_error(expected, predictions)\nrmse = sqrt(mse)\nprint('RMSE: %f' % rmse)\n\n```\nThe mean square root and square root of it will be useful.\n\n\n\n```python\n#pip install sklearn\n```\n\n\n```python\nfrom sklearn.metrics import mean_squared_error\nfrom math import sqrt\nexpected = [0.0, 0.5, 0.0, 0.5, 0.0]\npredictions = [0.2, 0.4, 0.1, 0.6, 0.2]\nmse = mean_squared_error(expected, predictions)\nrmse = sqrt(mse)\nprint('RMSE: %f' % rmse)\n```\n\n RMSE: 0.148324\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "8c439924029e755a257e54b9864909f1adbe929d", "size": 5773, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Data Science and Machine Learning/Machine-Learning-In-Python-THOROUGH/RECAP_DS/01_BASIC_STATISTICS/01_Math_Basics.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": "Data Science and Machine Learning/Machine-Learning-In-Python-THOROUGH/RECAP_DS/01_BASIC_STATISTICS/01_Math_Basics.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": "Data Science and Machine Learning/Machine-Learning-In-Python-THOROUGH/RECAP_DS/01_BASIC_STATISTICS/01_Math_Basics.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": 28.1609756098, "max_line_length": 296, "alphanum_fraction": 0.5579421445, "converted": true, "num_tokens": 975, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951698485602, "lm_q2_score": 0.9099070109242131, "lm_q1q2_score": 0.8502127160189258}} {"text": "# Generating Functions\n\nGenerating functions are functions that encode sequences of numbers as the coefficients of power series. \n\nConsider a set $S$ with $n$ elements. \n\nPretend there is a picture function' $P(s)\\ \\forall s\\in S$. \n\nThe picture function enables one, for example, to write the multiset $\\{1,1,2\\}$ as an expression $P(1)^2P(2)$.\n\nThe enumerating function $E_p(s)\\ :s\\in S$ is used to list combinations subject to restraints. For example, the enumerating function for all multisets that include either one or two times some element $a$ and between zero and two times some element $b$ is written:\n\n\\begin{equation}\n\\begin{array}{rl}\nE_P(s) &= P(a)+ P(a)^2 + P(a)P(b) + P(a)^2P(b) + + P(a)P(b)^2 + P(a)^2P(b)^2\\\\\n&\\left(P(a) + P(a)^2\\right)\\left(1 + P(b) + P(b)^2\\right)\n\\end{array}\n\\end{equation}\n\nThis hints at how generating functions can make it easier to keep track of combinations.\n\n\n## Example: Binomial Coefficients\n\nConsider the case of a collection of $n$ indistinguishable objects $s$, and write $P(s) = x$. Then the enumerator for selecting any subset of those $n$ objects is given by: \n\n\\begin{equation}\nE_P(s) = \\prod_i^n (x^0+x^1) = (1+x)^n = \\sum_i^n {n \\choose i}x^i\n\\end{equation}\n\nWhere $(x^0 + x^1)$ corresponds to including an element zero or one times. The exponent encodes how many objects were included into a particular subset. This is one way of \"proving\" the binomial theorem, and one can says $(1_x)^n$ is the generating function for the binomial coefficients ${n \\choose i}$. \n\n\n\n## Example: Basket of Goods\n\nAn apple costs $20c$, a pear costs $25c$ and a banana costs $30c$. How many different fruit baskets can be bought for $100c$?\n\nBy replacing the picture function $P(s)$ with $x$, it was possible to identify subsets of $n$ objects by looking at the exponent of $x^n$ in the enumerating function. In this case, the exponent is supposed to show the price. This can be done by writing $P(apple) = x^{20}, P(pear) = x^{25}$ and $P(banana) = x^{30}$. \n\n\\begin{equation}\nE_P(s) = \\left( \\sum_{i=0}^5 x^{20} \\right)\\left( \\sum_{i=0}^4 x^{25} \\right)\\left( \\sum_{i=0}^3 x^{30} \\right)\n\\end{equation}\n\nWhich results in some power series of the form:\n\n\\begin{equation}\nE_P(s) = 1x^0 + 1x^{20} + 1x^{25} + 1x^{30} + 1x^{40} +... + 2x^{60} + ... + 1x^{290}\n\\end{equation}\n\nTo obtain the number of combinations that correspond to a cost of exactly $100c$, one can apply the operator $\\frac{1}{n!}\\frac{d^n}{dx^n}$ and set $x=0$ to obtain the desired term. This is what is done with moment generating functions in statistics. \n\nBut actually it is easier to think through what the coefficients will be so that:\n\n\\begin{equation}\n\\sum_{l=0}^{n+m+h}d_l x^l = \\left(\\sum_{i=0}^n a_i x^i\\right)\\left(\\sum_{j=0}^m b_j x^j\\right)\\left(\\sum_{k=0}^h c_k x^k\\right)\n\\end{equation}\n\n\\begin{equation}\nd_l = \\sum_{\\begin{array}{c}i,j,k\\\\i+j+k=l\\end{array}} a_i b_j c_k\n\\end{equation}\n\nIf the coefficients are all '1', which is the case for these combinations, then:\n\n\\begin{equation}\nd_l = \\sum_{\\begin{array}{c}i,j,k\\\\i+j+k=l\\end{array}} 1 = {l + 3 - 1 \\choose l}\n\\end{equation}\n\nWhich is the number of all multisets of size $l$ and 3 classes. In this case the coefficients are equal to 1 for i=20, j=25, and k=30, and zero otherwise, so that there are 4 ways of summing to 100. Hence, $d_{100} = 4$ for the basket of goods above.\n\nThe sum can also be rewritten:\n\n\\begin{equation}\nd_l = \\sum^l_{i=0}\\sum^{l-i}_{j=0}\\sum^{l-i-j}_{k= l-i-j} a_i b_j c_k\n\\end{equation}\n\nWhere the last sum is actually just over a single term.\n\nOf course, this is the discrete version of a convolution. So, it is no surprise that the addition of random variables winds up being a convolution.\n\n## Example: Dice \n\nHow many ways are there for $n$ dice with $k$ faces to show $s$ eyes?\n\n\\begin{equation}\nE_P = \\left(\\sum_{i=0}^\\infty a_i x^i\\right)^n = \\sum_{i=0}^{\\infty}d_i x^i\n\\end{equation}\n\nWhere $a_i = 1\\ \\forall i\\in(1,k)$ and $a_i = 0$ otherwise. \n\n\\begin{equation}\nE_P = \\left(\\sum_{i=1}^k x^i\\right)^n = \\left(x(1-x^k)\\sum_{i=0}^\\infty x^i\\right)^n = x^n\\left(\\frac{1-x^k}{1-x}\\right)^n = x^n \\left(\\sum_{i=0}^n (-1)^i {n \\choose i} x^{ik}\\right)\\left(\\sum_{j=0}^{\\infty} (-1)^j {-n \\choose j} x^j\\right)\n\\end{equation}\n\nThe coefficient for $x^s$ is given the sum:\n\n\\begin{equation}\nd_s = \\sum_{ki+j=s-n} (-1)^{i+j}{n \\choose i}{-n \\choose j}\\\\\ni \\in [0,n] \\\\\nj \\in [0,\\infty]\n\\end{equation}\n\nWhere the indices $i$ and $j$ satisfy $ki+j = s-n$. For example, for $s=7$, $n=2$ and $k=6$:\n\n\\begin{equation}\n6i+j = 7-2 = 5\n\\end{equation}\n\nHolds for $i=0, j=5$:\n\n\\begin{equation}\nd_s = (-1)^5 {2 \\choose 0}{-2 \\choose 5} = (-1)^{10} 1 {2+5-1 \\choose 5} = {6 \\choose 5} = \\frac{6!}{5!1!} = 6 \n\\end{equation}\n\nIndeed, there are 6 ways for two d6 to add to 7:\n\n\\begin{equation}\n[6,1],[5,2],[4,3],[3,4],[2,5],[1,6]\n\\end{equation}\n\n\n```python\nimport warnings\n\ndef memoize(func):\n \"\"\"\n memoizing wrapper to speed up recursion by keeping track of previously calculated values.\n \"\"\"\n S = {}\n def wrappingfunction(*args):\n if args not in S:\n S[args] = func(*args)\n return S[args]\n return wrappingfunction\n\n@memoize\ndef factorial(x):\n if x == 0:\n return 1\n else:\n res = 1\n for i in range(1,x+1):\n res *= i\n return res\n\n@memoize\ndef binomial(n,k):\n if n > 40 or k > 40:\n warnings.warn('careful with large n or k - unresolved numerical stability issues.')\n \n \n if n >= k and k>= 0:\n return int(factorial(n)/(factorial(n-k)*factorial(k)))\n elif n < 0 and k >= 0:\n return int((-1)**k * binomial(-n+k-1,k))\n elif n < 0 and k <= n:\n return int((-1)**(n-k) * binomial(-k-1,n-k))\n else:\n return 0\n \n \nf = lambda x: str(x) if x != 0 else '-'\nN = 5\n\nprint('\\t'.join([' ']+['k=%i' % k for k in range(-N,N+1)]))\nfor n in range(-N,N+1)[::-1]:\n print('\\t'.join(['n=%i' % n]+[f(binomial(n,k)) for k in range(-N,N+1)]))\n```\n\n \tk=-5\tk=-4\tk=-3\tk=-2\tk=-1\tk=0\tk=1\tk=2\tk=3\tk=4\tk=5\n n=5\t-\t-\t-\t-\t-\t1\t5\t10\t10\t5\t1\n n=4\t-\t-\t-\t-\t-\t1\t4\t6\t4\t1\t-\n n=3\t-\t-\t-\t-\t-\t1\t3\t3\t1\t-\t-\n n=2\t-\t-\t-\t-\t-\t1\t2\t1\t-\t-\t-\n n=1\t-\t-\t-\t-\t-\t1\t1\t-\t-\t-\t-\n n=0\t-\t-\t-\t-\t-\t1\t-\t-\t-\t-\t-\n n=-1\t1\t-1\t1\t-1\t1\t1\t-1\t1\t-1\t1\t-1\n n=-2\t-4\t3\t-2\t1\t-\t1\t-2\t3\t-4\t5\t-6\n n=-3\t6\t-3\t1\t-\t-\t1\t-3\t6\t-10\t15\t-21\n n=-4\t-4\t1\t-\t-\t-\t1\t-4\t10\t-20\t35\t-56\n n=-5\t1\t-\t-\t-\t-\t1\t-5\t15\t-35\t70\t-126\n\n\n\n```python\ndef d_s(s,n=2,k=6):\n \"\"\"\n Number of Dice Combinations\n \n n = number of dice\n k = number of dice faces (faces: 1,2,3,4,5,...,k)\n s = sum of dice throw\n \n Beware of numerical stability issues for N >~ 45\n \"\"\"\n res = 0 \n for i in range(0,int((s-n)/k)+1):\n j = s-n-k*i\n res += (-1)**(i+j) * binomial(n,i) * binomial(-n,j)\n return res\n \nprint('2 d6')\nfor s in range(1,14):\n print('s = %i\\t' % s, 'd = %i' % d_s(s,n=2,k=6))\n```\n\n 2 d6\n s = 1\t d = 0\n s = 2\t d = 1\n s = 3\t d = 2\n s = 4\t d = 3\n s = 5\t d = 4\n s = 6\t d = 5\n s = 7\t d = 6\n s = 8\t d = 5\n s = 9\t d = 4\n s = 10\t d = 3\n s = 11\t d = 2\n s = 12\t d = 1\n s = 13\t d = 0\n\n\n\n```python\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nk = 6 \n\nN = 31\nss = list(range(1,N*(k-2)))\nnn = list(range(1,N))\n\n\nplt.figure(figsize=(12,5))\nfor n in nn: \n d = [d_s(s,n=n,k=k) for s in ss]\n d = np.array(d)/np.sum(d)\n \n plt.plot(ss,d,'.-',linewidth=2,markersize=8)\n plt.text(x=3.5*n+0.2,y=max(d)+0.0025,s='%i' % n)\n \nplt.xlabel('s')\nplt.ylabel('p(s)')\nplt.title('Probability of d6 Throw')\nplt.savefig('./img/d6throw.png')\n\nxlim = plt.xlim()\n\n\nk = 20 \n\nN = 31\nss = list(range(1,N*(k-2)))\nnn = list(range(1,N))\n\n\nplt.figure(figsize=(12,5))\nfor n in nn: \n d = [d_s(s,n=n,k=k) for s in ss]\n d = np.array(d)/np.sum(d)\n \n plt.plot(ss,d,'.-',linewidth=2,markersize=8)\n if 10.5*n <= max(xlim):\n plt.text(x=10.5*n+0.2,y=max(d)+0.00075,s='%i' % n)\n \nplt.xlim(*xlim)\nplt.xlabel('s')\nplt.ylabel('p(s)')\nplt.title('Probability of d20 Throw')\nplt.savefig('./img/d20throw.png')\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "72b31a8f79ce5452c0c8f85cda868faae37e325e", "size": 235977, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Combinatorics - Generating Functions.ipynb", "max_stars_repo_name": "jpbm/probabilism", "max_stars_repo_head_hexsha": "a2f5c1595aed616236b2b889195604f365175899", "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": "Combinatorics - Generating Functions.ipynb", "max_issues_repo_name": "jpbm/probabilism", "max_issues_repo_head_hexsha": "a2f5c1595aed616236b2b889195604f365175899", "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": "Combinatorics - Generating Functions.ipynb", "max_forks_repo_name": "jpbm/probabilism", "max_forks_repo_head_hexsha": "a2f5c1595aed616236b2b889195604f365175899", "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": 655.4916666667, "max_line_length": 127972, "alphanum_fraction": 0.9398161685, "converted": true, "num_tokens": 3084, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067179697694, "lm_q2_score": 0.9019206831203063, "lm_q1q2_score": 0.8500663029167722}} {"text": "# Basic Naive Bayes\n\n## Theory\n\nNaive Bayes classifiers attempt to divine the probability of each class given a data set. If we represent the predicted class as a random variable $Y$ and the set of features as a random variable $X$, then naive Bayes predicts a class from data $x_i$ by selecting the class $y_i$ that have the highest value of $P(Y=y_i|X=x_i)$. In statistical nomenclature, the class with the highest posterior probability. So training consists of figuring out how we can estimate these posterior probabilities from a set of training data.\n\nTo begin, let us assume that we are trying to predict the chance of borrower default given some historical data:\n\n| married | diet | defaulted |\n| --- | ---| ---|\n| yes | conventional | no |\n| no | conventional | yes |\n| no | vegan | yes |\n| yes | vegetarian | no |\n| no | gluten-free | no |\n| yes | West Coast | yes |\n\n\nGiven this data, what is the probability that a married vegan will default? \n\nWe can attempt to solve this with the standard conditional probability definition, $$P(default | (married \\cap vegan)) = \\frac{P(default \\cap married \\cap vegan)}{P(married \\cap vegan)} $$ but find that this leaves us trying to approximate the joint probability of our features. We likely didn't gather data with this estimation in mind (we are attempting to correlate attributes with our predicted class, not other attributes). If we assume indepedence of attributes, our denominator is always 0. Instead, we would like to estimate $P(default | (married \\cap vegan))$ based on the relationships between our attributes and our predicted class. We can accomplish this using Bayes' formula, which is the consequence of the following equalities:\n$$ P(Y|X) = \\frac{P(Y \\cap X)}{P(X)} $$\n$$ P(X|Y) = \\frac{P(X \\cap Y)}{P(Y)} $$\n$$P(X \\cap Y) = P(Y \\cap X)$$\n\nSolving the first two for their joint probabilities, equating them, and then dividing by $P(X)$ yields Bayes formula:\n\n$$ P(Y | X) = \\frac{P(X|Y)P(Y)}{P(X)} $$\n\nAs noted above, we can make classify data $x_i$ by selecting the class $y_i$ that has the highest value of $P(Y=y_i|X=x_i)$. Since $P(X)$ is constant across classes, we can ignore it when searching for the highest posterior. Estimating $P(Y=y_i)$ from the training data is easy as it is just the proportion of labels that belong to a particular class. Estimating $P(X | Y)$ is more difficult, since X is a vector of attributes and therefore $P(X=x_i)$ is shorthand for $P(x_0 = x_{i0} \\cap x_1 = x_{i1} \\cap ... \\cap x_m = x_{im})$. With __naive bayes__, this calculation is greatly simplified by assuming that the attributes are conditionally independent. This assumption yields:\n\n$$P((x_0 = x_{i0} \\cap x_1 = x_{i1} \\cap ... \\cap x_m = x_{im}) | Y=y) = \\prod_{j=0}^{m}{P(x_j=x_{ij} | Y=y)}$$\n\nConsequently, we can estimate our posterior (dropping the class constant denominator) as:\n\n$$P(Y=y | X=x_i) \\sim = \\prod_{j=0}^{m}{P(x_j=x_{ij} | Y=y)}*P(Y=y)$$\n\n### Training\n\nThe learned 'model' is a set of prior probabilities (i.e. $P(Y=y)$ for all classes $y$) and a set of conditional probabilities (i.e. $P(x_j=x_{ij} | Y=y$). We learn the priors based on class proportion in the training set and calculate the conditional probabilities based on the training data.\n\n### Classifying\n\nTo classify, we calculate the posterior (i.e. $P(Y=y | X=x_i)$) for every class y using our learned priors and conditional probabilities. Our label is the class with the highest posterior.\n\n### Misc\n\nArguably the most useful characteristic of a naive bayes classifier is that it returns a probability for each class, which can be used to guage classification confidence.\n\n### Exercise\n\nGiven our borrower default data, calculate the naive bayes 'model' and use it to predict if a married vegan will default on their loan.\n\n---\nOur model:\n\n| model param | value |\n|---|---|\n| $P(defaulted=yes)$ | 0.5|\n| $P(defaulted=no)$ | 0.5|\n| $P(married=yes | defaulted=yes)$ | 0.333|\n| $P(married=no | defaulted=yes)$ | 0.666|\n| $P(married=yes | defaulted=no)$ | 0.666|\n| $P(married=no | defaulted=no)$ | 0.333|\n| $P(diet=conventional | defaulted=yes)$ | 0.333|\n| $P(diet=conventional | defaulted=no)$ | 0.333|\n| ... | ... |\n| $P(diet=West Coast | defaulted=yes)$ | 0.333|\n| $P(diet=West Coast | defaulted=no)$ | 0|\n\nOur posteriors:\n\n\n$\\begin{align}\n P(default=yes|(married=yes \\cap diet=vegan)) &= \\\\\n & = P(married=yes | defaulted = yes) * P(diet=vegan | defaulted = yes) * P(defaulted=yes)\\\\\n & = 0.333 * 0.333 * 0.5 \\\\\n & = 0.055\n\\end{align}$\n\n$\\begin{align}\n P(default=no|(married=yes \\cap diet=vegan)) &= \\\\\n & = P(married=yes | defaulted = no) * P(diet=vegan | defaulted = no) * P(defaulted=no)\\\\\n & = 0.666 * \\rho * 0.5 \\\\\n & = 0.166\\rho\n\\end{align}$\n\nWe see how to actually deal with 0 conditional probabilities later but for now lets just say that $\\rho=0.333$, so we have the posterior for default=yes is 0.055 and for default=no is 0.0833. Therefore, our model would predict that a married vegan would not default.\n\n\n### Edge cases\n\n#### Conditionals of zero\nAs we saw in our example above, a zero conditional can occur when there is too little data (esp. with regard to a single attribute). Since a zero conditional will zero out the product of conditionals, it is important to come up with a heuristic for dealing with them. A common approach is to use the m-estimate:\n\n$$P(x_i|y_i)=\\frac{n_c+mp}{n+m}$$\n\nwhere $m$ (equivalent sample size) and $p$ are parameters, $n_c$ is the number of records with attribute value $x_i$ and class $y_i$, and n is the number of records with class $y_i$. We note that if there is no training set then $P(x_i|y_i)=p$, so $p$ can be conceived of as the prior probability of attribute value $x_i$ given class $y_i$. \n\n#### Estimating conditionals for continuous attributes\nThe astute student might notice that directly calculating conditionals for continuous variables would be impossible since any single point is unlikely to occur multiple times in our training set. The simplest way to deal with this issue is discretization; divide up the range of values into regions, map the values to regions, and treat the region 'labels' as categorical variables. The problem with this approach is that the analyst must select the regions and this is prone to error.\n\nAlternatively, we can assume that the data fits a specific distribution (e.g. Gaussian) and use the class conditional probability of that distribution as our conditional. Assuming a Gaussian distribution, we have:\n\n$$P(X_i=x|Y=y_j)=\\frac{1}{\\sqrt{2\\pi}\\sigma_{ij}}e^{-\\frac{(x-\\mu_{ij})^2}{2\\sigma^2_{ij}}}$$\n\nConsequently, during the training phase we calculate the sample mean and sample variance of the attribute $X_i$'s values for records with class $y_j$ and use those values to estimate $\\mu_{ij}$ and $\\sigma_{ij}$ respectively. At that point, we have a function for determining the conditional for a particular attribute value and class.\n\n## Implementation\n\n\n```python\n#Assumptions : Only string (nominal values) or numeric fields\nimport pandas as pd\nimport math\n\nclass naive_bayes:\n \n def __init__(self, equivalent_sample_size=1, default_attr_prior=0.1):\n self._prior = default_attr_prior\n self._eq_sample_size = equivalent_sample_size\n \n \n def _m_cond(self, class_cnt, class_attr_cnt):\n return (class_attr_cnt + (self._eq_sample_size*self._prior)) / (class_cnt + self._eq_sample_size)\n\n\n def _calc_priors(self, labels):\n return labels.value_counts() / len(labels)\n\n \n def _categorical_conditionals(self, df):\n \"Assumes 2 columns, attribute and label, and the attribute values are categorical\"\n attr_col = df.columns[0]\n class_col = df.columns[1]\n\n conds = []\n for y, df in data.groupby(class_col):\n class_count = len(df)\n conds += [[val,self._m_cond(class_count, cnt),y] for val,cnt in df[attr_col].value_counts().items()]\n\n return pd.DataFrame(conds,columns=['Value','Probability','Class'])\n \n \n def _continuous_conditionals(self, df):\n \"Assumes 2 columns, attribute and label, and the attribute values are numeric\"\n attr_col = df.columns[0]\n class_col = df.columns[1]\n\n stats = []\n for y, df in data.groupby(class_col):\n stats += [[df[attr_col].mean(),df[attr_col].std(),y]]\n\n return pd.DataFrame(stats,columns=['Mean','Std','Class'])\n \n\n def fit(self, data,class_column):\n result = {}\n\n for col,is_numeric in ((data.dtypes == 'float64') | (data.dtypes == 'int64')).items():\n if col != class_column:\n result[col] = {'type' : 'continuous', 'conditionals' : self._continuous_conditionals(data[[col,class_column]])} if is_numeric else {'type' : 'categorical', 'conditionals' : self._categorical_conditionals(data[[col,class_column]])}\n\n self._model = result\n self._priors = self._calc_priors(data[class_column])\n\n\n def _gaussian(self, val, params):\n std = params['Std']\n return (1.0/(math.sqrt(2*math.pi) * std)) * math.exp(-((val-params['Mean'])**2)/(2*(std**2)))\n\n def _calc_posterior(self, record, col):\n model_params = self._model[col]\n x = record[col]\n conds = model_params['conditionals']\n\n if model_params['type'] == 'categorical':\n return conds[conds['Value'] == x][['Probability','Class']]\n\n #else continuous\n gauss = lambda stats : pd.Series([self._gaussian(x,stats), stats['Class']])\n tmp = conds.apply(gauss,axis=1)\n return tmp.rename(columns={0 : 'Probability', 1 : 'Class'})\n\n\n def predict(self, record):\n if not hasattr(self, '_model'):\n raise Exception('The model has not been fitted, prediction is impossible')\n \n tmp_df = pd.DataFrame()\n for col in record.index:\n tmp_df = tmp_df.append(self._calc_posterior(record,col),ignore_index=True)\n\n posteriors = tmp_df.groupby('Class').prod()['Probability']*self._priors\n print(posteriors)\n \n return posteriors.idxmax()\n \n\n```\n\n\n```python\ndata = pd.DataFrame({'Diet' : ['conventional','conventional','vegan','vegetarian','gluten-free','west-coast'],\n 'Married' : ['yes','no','no','yes','no','yes'],\n 'Salary' : [120000.0,34000.0,54000.0,75000.0,90000.0,65000.0],\n 'Default' : ['no','yes','yes','no','no','yes']})\n\nnb = naive_bayes()\n\nnb.fit(data,'Default')\n\nnew_record = pd.Series(['east-coast','no',50000.00],index=['Diet','Married','Salary'])\n\nnb.predict(data.iloc[0,:-1])\nnb.predict(data.iloc[1,:-1])\nnb.predict(new_record)\n\n```\n\n no 6.930807e-07\n yes 6.260629e-11\n dtype: float64\n no 1.902869e-08\n yes 1.020828e-06\n dtype: float64\n no 3.479887e-07\n yes 6.649849e-06\n dtype: float64\n\n\n\n\n\n 'yes'\n\n\n", "meta": {"hexsha": "1c5459d1b8b530b6333ded4fb55770cc05f39317", "size": 14781, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "DataSci/from_scratch/Naive Bayes.ipynb", "max_stars_repo_name": "Tshort76/reference", "max_stars_repo_head_hexsha": "ad47f9e33e72b451e0d26bfeaf96b6ddfd0cd4a5", "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": "DataSci/from_scratch/Naive Bayes.ipynb", "max_issues_repo_name": "Tshort76/reference", "max_issues_repo_head_hexsha": "ad47f9e33e72b451e0d26bfeaf96b6ddfd0cd4a5", "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": "DataSci/from_scratch/Naive Bayes.ipynb", "max_forks_repo_name": "Tshort76/reference", "max_forks_repo_head_hexsha": "ad47f9e33e72b451e0d26bfeaf96b6ddfd0cd4a5", "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.8605341246, "max_line_length": 761, "alphanum_fraction": 0.5793924633, "converted": true, "num_tokens": 2906, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338046748207, "lm_q2_score": 0.8840392878563336, "lm_q1q2_score": 0.8500336599345195}}