{"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\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\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:
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# BA - 1x2\npd.DataFrame(np.matmul(B, A))\n```\n\n\n\n\n
\n\n
\n \n
\n
\n
0
\n
1
\n
\n \n \n
\n
0
\n
44
\n
56
\n
\n \n
\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
0
\n
1
\n
2
\n
3
\n
4
\n
\n \n \n
\n
0
\n
20
\n
16
\n
12
\n
8
\n
4
\n
\n
\n
1
\n
19
\n
15
\n
11
\n
7
\n
3
\n
\n
\n
2
\n
19
\n
14
\n
10
\n
6
\n
2
\n
\n
\n
3
\n
17
\n
13
\n
9
\n
5
\n
1
\n
\n \n
\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## 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```\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
p-hat
\n
\n \n \n
\n
0
\n
0.18
\n
\n
\n
1
\n
0.22
\n
\n
\n
2
\n
0.17
\n
\n
\n
3
\n
0.19
\n
\n
\n
4
\n
0.23
\n
\n
\n
...
\n
...
\n
\n
\n
9995
\n
0.19
\n
\n
\n
9996
\n
0.24
\n
\n
\n
9997
\n
0.22
\n
\n
\n
9998
\n
0.27
\n
\n
\n
9999
\n
0.27
\n
\n \n
\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 **μx̄**) 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
x
y
\n\n\t
-10
-17.0
\n\t
-9
-15.5
\n\t
-8
-14.0
\n\t
-7
-12.5
\n\t
-6
-11.0
\n\t
-5
-9.5
\n\t
-4
-8.0
\n\t
-3
-6.5
\n\t
-2
-5.0
\n\t
-1
-3.5
\n\t
0
-2.0
\n\t
1
-0.5
\n\t
2
1.0
\n\t
3
2.5
\n\t
4
4.0
\n\t
5
5.5
\n\t
6
7.0
\n\t
7
8.5
\n\t
8
10.0
\n\t
9
11.5
\n\t
10
13.0
\n\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```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
**Number of Points**
**Points** $x_i$
**Weights** $A_i$
\n
\n
\n
1
0
2.000000
\n
\n
\n
2
$-\\sqrt{\\frac{1}{3}}=-0.577350$
1.000000
\n
\n
\n
$+\\sqrt{\\frac{1}{3}}=+0.577350$
1.000000
\n
\n
\n
3
$-\\sqrt{\\frac{3}{5}}=-0.774597$
$\\frac{5}{9}=0.555556$
\n
\n
\n
$0$
$\\frac{8}{9}=0.888889$
\n
\n
\n
$+\\sqrt{\\frac{3}{5}}=+0.774597$
$\\frac{5}{9}=0.555555$
\n
\n
\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
t_student
\n
p_value
\n
accept_H0_critical_value
\n
accept_H0_p_value
\n
\n \n \n
\n
0
\n
5.641207
\n
0.000782
\n
0.0
\n
0.0
\n
\n
\n
1
\n
7.306917
\n
0.000162
\n
0.0
\n
0.0
\n
\n
\n
2
\n
-3.873954
\n
0.006100
\n
0.0
\n
0.0
\n
\n \n
\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\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
Attr1
\n
Attr2
\n
Attr3
\n
Attr4
\n
Attr5
\n
Attr6
\n
Attr7
\n
Attr8
\n
Attr9
\n
Attr10
\n
...
\n
Attr56
\n
Attr57
\n
Attr58
\n
Attr59
\n
Attr60
\n
Attr61
\n
Attr62
\n
Attr63
\n
Attr64
\n
class
\n
\n \n \n
\n
0
\n
0.088238
\n
0.55472
\n
0.01134
\n
1.0205
\n
-66.5200
\n
0.342040
\n
0.109490
\n
0.57752
\n
1.0881
\n
0.32036
\n
...
\n
0.080955
\n
0.275430
\n
0.91905
\n
0.002024
\n
7.2711
\n
4.7343
\n
142.760
\n
2.5568
\n
3.2597
\n
0
\n
\n
\n
1
\n
-0.006202
\n
0.48465
\n
0.23298
\n
1.5998
\n
6.1825
\n
0.000000
\n
-0.006202
\n
1.06340
\n
1.2757
\n
0.51535
\n
...
\n
-0.028591
\n
-0.012035
\n
1.00470
\n
0.152220
\n
6.0911
\n
3.2749
\n
111.140
\n
3.2841
\n
3.3700
\n
0
\n
\n
\n
2
\n
0.130240
\n
0.22142
\n
0.57751
\n
3.6082
\n
120.0400
\n
0.187640
\n
0.162120
\n
3.05900
\n
1.1415
\n
0.67731
\n
...
\n
0.123960
\n
0.192290
\n
0.87604
\n
0.000000
\n
8.7934
\n
2.9870
\n
71.531
\n
5.1027
\n
5.6188
\n
0
\n
\n
\n
3
\n
-0.089951
\n
0.88700
\n
0.26927
\n
1.5222
\n
-55.9920
\n
-0.073957
\n
-0.089951
\n
0.12740
\n
1.2754
\n
0.11300
\n
...
\n
0.418840
\n
-0.796020
\n
0.59074
\n
2.878700
\n
7.6524
\n
3.3302
\n
147.560
\n
2.4735
\n
5.9299
\n
0
\n
\n
\n
4
\n
0.048179
\n
0.55041
\n
0.10765
\n
1.2437
\n
-22.9590
\n
0.000000
\n
0.059280
\n
0.81682
\n
1.5150
\n
0.44959
\n
...
\n
0.240400
\n
0.107160
\n
0.77048
\n
0.139380
\n
10.1180
\n
4.0950
\n
106.430
\n
3.4294
\n
3.3622
\n
0
\n
\n \n
\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
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
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
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
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:
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:
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
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.
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$:
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", "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
Exact value
\n
-0.223143551314210
\n
\n
\n
Estimated
\n
-0.223143564849920
\n
\n
\n
Error
\n
1.35357104968925e-8
\n
\n \n
\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
\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
\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
\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\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
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 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
\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.
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
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.
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
When only real solution is present:
\n
\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
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", "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
\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
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\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
Age
\n
Sex
\n
RestingBP
\n
Cholesterol
\n
FastingBS
\n
MaxHR
\n
ExerciseAngina
\n
Oldpeak
\n
HeartDisease
\n
ATA
\n
NAP
\n
TA
\n
Normal
\n
ST
\n
Flat
\n
Up
\n
\n \n \n
\n
0
\n
-1.433140
\n
1
\n
0.410909
\n
0.825070
\n
0
\n
1.382928
\n
0
\n
0.0
\n
0
\n
1
\n
0
\n
0
\n
1
\n
0
\n
0
\n
1
\n
\n
\n
1
\n
-0.478484
\n
0
\n
1.491752
\n
-0.171961
\n
0
\n
0.754157
\n
0
\n
1.0
\n
1
\n
0
\n
1
\n
0
\n
1
\n
0
\n
1
\n
0
\n
\n
\n
2
\n
-1.751359
\n
1
\n
-0.129513
\n
0.770188
\n
0
\n
-1.525138
\n
0
\n
0.0
\n
0
\n
1
\n
0
\n
0
\n
0
\n
1
\n
0
\n
1
\n
\n
\n
3
\n
-0.584556
\n
0
\n
0.302825
\n
0.139040
\n
0
\n
-1.132156
\n
1
\n
1.5
\n
1
\n
0
\n
0
\n
0
\n
1
\n
0
\n
1
\n
0
\n
\n
\n
4
\n
0.051881
\n
1
\n
0.951331
\n
-0.034755
\n
0
\n
-0.581981
\n
0
\n
0.0
\n
0
\n
0
\n
1
\n
0
\n
1
\n
0
\n
0
\n
1
\n
\n \n
\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
volume(cm3)
\n
pressure(gm/cm2)
\n
\n \n \n
\n
0
\n
54.3
\n
61.2
\n
\n
\n
1
\n
61.8
\n
49.2
\n
\n
\n
2
\n
72.4
\n
37.6
\n
\n
\n
3
\n
88.7
\n
28.4
\n
\n
\n
4
\n
118.6
\n
19.2
\n
\n
\n
5
\n
194.0
\n
10.1
\n
\n \n
\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
theta(degree)
\n
f(theta)
\n
\n \n \n
\n
0
\n
30
\n
11
\n
\n
\n
1
\n
45
\n
13
\n
\n
\n
2
\n
90
\n
16
\n
\n
\n
3
\n
120
\n
17
\n
\n
\n
4
\n
150
\n
14
\n
\n \n
\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
t [s]
\n
N [s-1]
\n
\n \n \n
\n
0
\n
0
\n
32
\n
\n
\n
1
\n
5
\n
28
\n
\n
\n
2
\n
10
\n
29
\n
\n
\n
3
\n
15
\n
28
\n
\n
\n
4
\n
20
\n
25
\n
\n
\n
...
\n
...
\n
...
\n
\n
\n
78
\n
390
\n
1
\n
\n
\n
79
\n
395
\n
1
\n
\n
\n
80
\n
400
\n
2
\n
\n
\n
81
\n
405
\n
2
\n
\n
\n
82
\n
410
\n
1
\n
\n \n
\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 [s-1]
\n
\n \n \n
\n
0
\n
0
\n
8.0
\n
\n
\n
1
\n
1
\n
6.0
\n
\n
\n
2
\n
2
\n
5.0
\n
\n
\n
3
\n
3
\n
4.0
\n
\n
\n
4
\n
4
\n
3.0
\n
\n
\n
5
\n
5
\n
2.0
\n
\n
\n
6
\n
6
\n
2.0
\n
\n
\n
7
\n
7
\n
2.0
\n
\n
\n
8
\n
8
\n
2.0
\n
\n
\n
9
\n
9
\n
1.0
\n
\n
\n
10
\n
10
\n
1.0
\n
\n
\n
11
\n
11
\n
1.0
\n
\n
\n
12
\n
12
\n
0.5
\n
\n
\n
13
\n
13
\n
0.5
\n
\n
\n
14
\n
14
\n
0.5
\n
\n
\n
15
\n
15
\n
0.5
\n
\n
\n
16
\n
16
\n
1.0
\n
\n
\n
17
\n
17
\n
0.5
\n
\n
\n
18
\n
18
\n
0.4
\n
\n
\n
19
\n
19
\n
0.3
\n
\n
\n
20
\n
20
\n
0.1
\n
\n \n
\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
NYC
\n
Paris
\n
Cairo
\n
Seoul
\n
\n \n \n
\n
NYC
\n
0.25
\n
0.25
\n
0.25
\n
0.25
\n
\n
\n
Paris
\n
0.00
\n
0.25
\n
0.25
\n
0.50
\n
\n
\n
Cairo
\n
0.75
\n
0.00
\n
0.25
\n
0.00
\n
\n
\n
Seoul
\n
1.00
\n
0.00
\n
0.00
\n
0.00
\n
\n \n
\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:
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:
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):
(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:
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
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:
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:
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\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:
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:
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):
(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
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:
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:
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:
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.Polyor the import_from function, as in import_from(sympy, :Poly). The latter has some attempt to avoid naming collisions.
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,
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:
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:
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:
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)$:
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 JuliaSet:
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:
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:
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:
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$:
(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
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].
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.
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="-".
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$:
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:
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:
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:
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:
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:
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:
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$:
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.
\"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.\"
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:
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:
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$:
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:
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
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:
(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.)
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:
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:
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:
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.
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$.
(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(