├── .gitignore ├── 0-Intro.ipynb ├── 1-GaussQuadrature.ipynb ├── 2-ShapeFuns.ipynb ├── 3-PoissonEquation.ipynb ├── 4-LinearElasticity.ipynb ├── 5-Diffusion.ipynb ├── 6-NewtonRaphson.ipynb ├── 7-TransientNR.ipynb ├── Clean.py ├── Demo-Rank2Tensor.ipynb ├── Demo-Vector.ipynb ├── FEToy ├── __init__.py ├── fe │ ├── __init__.py │ ├── gaussrule.py │ └── shapefun.py ├── mathutils │ ├── __init__.py │ ├── tensor.py │ └── vector.py ├── mesh │ ├── __init__.py │ ├── lagrange1dmesh.py │ └── lagrange2dmesh.py └── postprocess │ ├── PlotResult.py │ ├── Result.py │ └── __init__.py ├── LICENSE ├── README.md └── result.jpg /.gitignore: -------------------------------------------------------------------------------- 1 | .ipynb_checkpoints/ 2 | 3 | __pycache__/ 4 | -------------------------------------------------------------------------------- /5-Diffusion.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "id": "caf83a53-b6e5-4d2c-9d2f-a9e92f688daf", 6 | "metadata": {}, 7 | "source": [ 8 | "# Your first transient solver- diffusion equation\n", 9 | "\n", 10 | "- [x] time stepping\n", 11 | "- [x] time integration\n", 12 | "- [x] initial condition\n", 13 | "- [x] flux/surface integration\n", 14 | "- [x] 1d/2d diffusion\n", 15 | "\n", 16 | "Author: Yang Bai @ M3 Group\n", 17 | "\n", 18 | "Date : 2022.04.15\n", 19 | "\n", 20 | "QQ group: 628204857" 21 | ] 22 | }, 23 | { 24 | "cell_type": "markdown", 25 | "id": "bb41194c-1b90-42d9-80a0-d0a78c47aa22", 26 | "metadata": {}, 27 | "source": [ 28 | "# Governing equation\n", 29 | "\n", 30 | "$\\frac{\\partial c}{\\partial t}=-\\nabla\\cdot\\mathbf{j}$, with $\\mathbf{j}=-D\\nabla c$\n", 31 | "\n", 32 | "$\\dot{c}=\\nabla\\cdot(D\\nabla c)+\\dot{r}(c,\\nabla c,...)=D\\nabla\\cdot(\\nabla c)=D\\Delta c=f(c)$\n", 33 | "\n", 34 | "$c$: concentration of species or normalized concentration(molar fraction)\n", 35 | "\n", 36 | "$D$: diffusion coefficient" 37 | ] 38 | }, 39 | { 40 | "cell_type": "markdown", 41 | "id": "af56e62b-fc7a-4af2-8c62-138acb573d98", 42 | "metadata": {}, 43 | "source": [ 44 | "# Time integration\n", 45 | "\n", 46 | "$c^{n}$: solution of current time step (unknown)\n", 47 | "\n", 48 | "$c^{n-1}$: solution of previous time step (known)\n", 49 | "\n", 50 | "$\\dot{c}=f(c)$ with $\\dot{c}=\\frac{c^{n}-c^{n-1}}{\\Delta t}$\n", 51 | "\n", 52 | "===> $\\dot{c}^{n}=f(c^{n})(\\mathrm{implicit, backward-euler~method~(BE)})$\n", 53 | "\n", 54 | "===> $\\dot{c}^{n}=f(c^{n-1})(\\mathrm{explicit, forward-euler~method, CFL~condition})$\n", 55 | "\n", 56 | "## weighted integration\n", 57 | "$\\int_{\\Omega}\\dot{c}\\delta c dV=\\int_{\\partial\\Omega}D\\nabla c\\cdot\\vec{n}\\delta cdS-\\int_{\\Omega}D\\nabla c\\nabla\\delta c dV$\n", 58 | "\n", 59 | "## time discretization\n", 60 | "### use BE\n", 61 | "$\\int_{\\Omega}\\frac{c^{n}-c^{n-1}}{\\Delta t}\\delta c dV=\\int_{\\partial\\Omega}D\\nabla c^{n}\\cdot\\vec{n}\\delta cdS-\\int_{\\Omega}D\\nabla c^{n}\\nabla\\delta c dV$, $-D\\nabla c^{n}\\cdot\\vec{n}=j_{0}$\n", 62 | "\n", 63 | "### use FE\n", 64 | "$\\int_{\\Omega}\\frac{c^{n}-c^{n-1}}{\\Delta t}\\delta c dV=\\int_{\\partial\\Omega}D\\nabla c^{n-1}\\cdot\\vec{n}\\delta cdS-\\int_{\\Omega}D\\nabla c^{n-1}\\nabla\\delta c dV$, $-D\\nabla c^{n-1}\\cdot\\vec{n}=j_{0}$\n", 65 | "\n", 66 | "## K matrix and right hand side F (BE)\n", 67 | "$K=\\int_{\\Omega}\\frac{1}{\\Delta t}N^{J}N^{I}dV+\\int_{\\Omega}D\\nabla N^{J}\\nabla N^{I}dV$\n", 68 | "\n", 69 | "$F=\\int_{\\Omega}\\frac{c^{n-1}}{\\Delta t}N^{I}dV-\\int_{\\partial\\Omega}j_{0}N^{I}dS$" 70 | ] 71 | }, 72 | { 73 | "cell_type": "markdown", 74 | "id": "d1414a01-2b70-44fb-8562-ee02451bd31e", 75 | "metadata": {}, 76 | "source": [ 77 | "# Diffusion in 1d case" 78 | ] 79 | }, 80 | { 81 | "cell_type": "code", 82 | "execution_count": 1, 83 | "id": "6e409032-9d4b-4f57-a6fc-5aeb617fbac7", 84 | "metadata": {}, 85 | "outputs": [ 86 | { 87 | "data": { 88 | "image/png": "iVBORw0KGgoAAAANSUhEUgAAAZQAAAEKCAYAAAA1qaOTAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjUuMSwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy/YYfK9AAAACXBIWXMAAAsTAAALEwEAmpwYAAAfBklEQVR4nO3dfXhU9Z338fc3BBCKPAgkRh4SdBEhgIABY3chWpooaqu9a1vxiUq9EbzFWguI1VXr9lqt1VXbWl1rrbZ3r7q2PtGKN2tRwV4VDWwFRIogooaAoICwQcjDfO8/ZsgOkzOTQX55Kp/Xdc1Fzjnf+Z3fb35zzmfmzCSYuyMiInK4ctq6AyIi8vdBgSIiIkEoUEREJAgFioiIBKFAERGRIHLbugNtqV+/fl5UVNTW3RAR6VBWrFjxkbv3T11/RAdKUVERy5cvb+tuiIh0KGb2XtR6XfISEZEgFCgiIhKEAkVERIJQoIiISBAKFBERCUKBIiIiQShQREQkCAWKiIgEoUAREZEgFCgiIhKEAkVERIJQoIiISBAKFBERCUKBIiIiQShQREQkCAWKiIgEoUAREZEgFCgiIhKEAkVERIJQoIiISBAKFBERCUKBIiIiQShQREQkCAWKiIgEoUAREZEg2lWgmNlZZrbOzDaY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jObmdj+ILAQOBvYAOwFLk/c/R+BS4HVZvZGYt333H1hKw5BROSIZu6pH1McOUpKSnz58uVt3Q0RkQ7FzFa4e0nq+vZ0yUtERDowBYqIiAShQBERkSAUKCIiEoQCRUREglCgiIhIEAoUEREJQoEiIiJBKFBERCQIBYqIiAShQBERkSAUKCIiEoQCRUREglCgiIhIEAoUEREJQoEiIiJBKFBERCQIBYqIiAShQBERkSAUKCIiEoQCRUREglCgiIhIEAoUEREJQoEiIiJBKFBERCQIBYqIiAShQBERkSAUKIdh+vTp5OXlMXLkyIx1H3zwAWeccQbDhw+nuLiY++67L7Ju3759TJgwgZNPPpni4mJuueWWjO02NDQwduxYzj333Ix1RUVFjBo1ijFjxlBSUpK2bteuXVxwwQWcdNJJDB8+nFdffbVJzbp16xgzZkzjrWfPntx7772R7d1zzz0UFxczcuRIpk6dyr59+yLr7rvvPkaOHElxcXHatiD68d6xYwfl5eUMHTqU8vJydu7cGVn3u9/9juLiYnJycli+fHna9ubOnctJJ53E6NGj+cpXvsKuXbsi6/75n/+Z0aNHM2bMGCoqKqiurs74fLjrrrswMz766KPIultvvZUBAwY0Pq4LFy5M295PfvIThg0bRnFxMfPmzUs7lm984xuN7RUVFTFmzJjIujfeeIPS0tLG58frr78eWbdy5UpOO+00Ro0axZe+9CV2796d9rmdOi+rV6+OrEudl3Ttpc7Lm2++GVmXOi+VlZUZj70D87Jy5crIuqh5yXQ8J8/NzJkzI+tS52XEiBGRdanz8oc//CGyLnVetm3bFnkeSZ2TLVu2RNZFHStZc/cj9nbKKaf44ViyZImvWLHCi4uLM9ZVV1f7ihUr3N199+7dPnToUF+zZk2Tulgs5nv27HF399raWp8wYYK/+uqradu9++67ferUqX7OOedk3H9hYaFv3769ueH4ZZdd5j//+c/d3X3//v2+c+fOjPX19fWen5/vmzZtarKtqqrKi4qKfO/eve7u/rWvfc1/+ctfNqlbvXq1FxcXe01NjdfV1fnkyZP97bffjtxf1OM9d+5cv/32293d/fbbb/d58+ZF1r311lv+t7/9zcvKyryysjJte4sWLfK6ujp3d583b17a9j755JPGn++77z6/8sor0z4f3n//fa+oqPDBgwf79u3bI+tuueUW/9GPftTseF988UWfPHmy79u3z93dP/zww7S1ya677jr//ve/H1lXXl7uCxcudHf35557zsvKyiLrSkpK/OWXX3Z391/84hd+0003pX1up87LVVddFVmXOi/p2kudl3Ttpc7LJZdckvbYS56X1atXR9ZFzUu6PqbOzapVq5o97q+77jqfM2dOZF3qvJSWlkbWpc7LjTfeGHkeSZ2TuXPnRtZFHSupgOUecU7VO5TDMGnSJI455phm6woKChg3bhwARx99NMOHD2fz5s1N6syMHj16AFBXV0ddXR1mFtlmVVUVzz33HFdcccVhjOB/7N69m6VLl/Ktb30LgC5dutC7d++M91m8eDEnnHAChYWFkdvr6+v59NNPqa+vZ+/evRx33HFNatauXUtpaSndu3cnNzeXsrIynn766cj2oh7vZ599lmnTpgEwbdo0nnnmmci64cOHM2zYsGbbq6ioIDc3F4DS0lKqqqoi63r27Nn4c01NDWaW9vnwne98hzvvvLNxLrN93kTVPfDAA8yfP5+uXbsCkJeX12yb7s4TTzzB1KlTI+vMjN27dwPwySefcNxxx0XWrVu3jkmTJgFQXl7Ok08+mfa5nTovf/rTnyLrUuclXXup87Jr167IutR56dGjR9pjL3lejj322KyO0Ux9TJ2bUaNGZWzzwLzMmDEjsi51XoYMGRJZlzovTz31VOR5JHVOnn322ci6qGMlWwqUVrZp0yb++te/cuqpp0Zub2hoYMyYMeTl5VFeXp627tprr+XOO+8kJ6f5KTQzKioqOOWUU3jooYciazZu3Ej//v25/PLLGTt2LFdccQU1NTUZ23388ceZOnVq5LYBAwYwZ84cBg8eTEFBAb169aKioqJJ3ciRI1m6dCkff/wxe/fubbykkK0PP/yQgoICIH6gb9u2Lev7NueRRx5hypQpabffeOONDBo0iN/85jfcdtttkTULFixgwIABnHzyyc3u76c//SmjR49m+vTp7Ny5M7Lm7bff5pVXXuHUU0+lrKyMysrKZtt95ZVXyM/PZ+jQoZHb7733XubOncugQ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P+RyJFBgSLSDpjZJOBF4Ivu/nLKtieIf5ZS6u71bdA9kawoUEREJAh9hiIiIkEoUEREJAgFioiIBKFAERGRIBQoIiIShAJFRESCUKCIiEgQChQREQni/wMlRPyp3f5BiwAAAABJRU5ErkJggg==\n", 89 | "text/plain": [ 90 | "
" 91 | ] 92 | }, 93 | "metadata": { 94 | "needs_background": "light" 95 | }, 96 | "output_type": "display_data" 97 | } 98 | ], 99 | "source": [ 100 | "from FEToy.mesh.lagrange1dmesh import mesh1d\n", 101 | "from FEToy.fe.shapefun import shape1d\n", 102 | "from FEToy.fe.gaussrule import gausspoint1d\n", 103 | "from FEToy.postprocess.Result import ResultIO # to csv file\n", 104 | "import numpy as np\n", 105 | "\n", 106 | "# define your mesh\n", 107 | "my1dmesh=mesh1d(nx=10,xmax=1.0,meshtype='edge4')\n", 108 | "my1dmesh.createmesh()\n", 109 | "my1dmesh.plotmesh(withnode=True,withnodeid=True)\n", 110 | "\n", 111 | "#define your shape fun and gauss points\n", 112 | "shp=shape1d(meshtype='edge4')\n", 113 | "shp.update()\n", 114 | "\n", 115 | "qpoints=gausspoint1d(ngp=3)\n", 116 | "qpoints.creategausspoint()" 117 | ] 118 | }, 119 | { 120 | "cell_type": "markdown", 121 | "id": "653a4d02-cdff-4011-9e84-9705d1b208a3", 122 | "metadata": {}, 123 | "source": [ 124 | "$$K=\\int_{\\Omega}\\frac{1}{\\Delta t}N^{J}N^{I}dV+\\int_{\\Omega}D\\nabla N^{J}\\nabla N^{I}dV$$\n", 125 | "$$F=\\int_{\\Omega}\\frac{c^{n-1}}{\\Delta t}N^{I}dV-\\int_{\\partial\\Omega}j_{0}N^{I}dS$$" 126 | ] 127 | }, 128 | { 129 | "cell_type": "code", 130 | "execution_count": 2, 131 | "id": "a75b79a0-af5d-4890-a098-7bc39847eba2", 132 | "metadata": {}, 133 | "outputs": [ 134 | { 135 | "name": "stdout", 136 | "output_type": "stream", 137 | "text": [ 138 | "write result to diff1d-000000.csv\n", 139 | "step= 1 finished!\n", 140 | "step= 2 finished!\n", 141 | "step= 3 finished!\n", 142 | "step= 4 finished!\n", 143 | "step= 5 finished!\n", 144 | "step= 6 finished!\n", 145 | "step= 7 finished!\n", 146 | "step= 8 finished!\n", 147 | "step= 9 finished!\n", 148 | "step= 10 finished!\n", 149 | "step= 11 finished!\n", 150 | "step= 12 finished!\n", 151 | "step= 13 finished!\n", 152 | "step= 14 finished!\n", 153 | "step= 15 finished!\n", 154 | "step= 16 finished!\n", 155 | "step= 17 finished!\n", 156 | "step= 18 finished!\n", 157 | "step= 19 finished!\n", 158 | "step= 20 finished!\n" 159 | ] 160 | } 161 | ], 162 | "source": [ 163 | "# define your parameters\n", 164 | "D=0.5 # diffusion coefficient\n", 165 | "dt=1.0e-3 # time step size\n", 166 | "totalstep=20 # the total time step\n", 167 | "j0=0.005 # flux\n", 168 | "\n", 169 | "nDofs=my1dmesh.nodes*1\n", 170 | "K=np.zeros((nDofs,nDofs))\n", 171 | "F=np.zeros(nDofs)\n", 172 | "cold=np.zeros(nDofs) # solution in previous step\n", 173 | "c=np.zeros(nDofs) # solution in current step\n", 174 | "\n", 175 | "# apply initial condition\n", 176 | "cold[:]=0.001\n", 177 | "\n", 178 | "# define a csv output\n", 179 | "result=ResultIO('diff1d')\n", 180 | "result.save2csv(mesh=my1dmesh,solution=cold,varnamelist=['c'],step=0) # to csv file\n", 181 | "\n", 182 | "for step in range(totalstep):\n", 183 | " # init your k and rhs\n", 184 | " K[:,:]=0.0;F[:]=0.0\n", 185 | " for e in range(my1dmesh.elements):\n", 186 | " elconn=my1dmesh.elementconn[e,:] # local element connectivity\n", 187 | " nodes=my1dmesh.nodecoords[elconn] # node coordinates of local element\n", 188 | " # now we can do the integration\n", 189 | " for gp in range(qpoints.ngp):\n", 190 | " xi=qpoints.gpcoords[gp,1] # 1->xi, 2->eta\n", 191 | " w =qpoints.gpcoords[gp,0] # weight\n", 192 | " \n", 193 | " shp_val,shp_grad,j=shp.calc(xi,nodes) # j->mapping from x->xi\n", 194 | " JxW=j*w # the weight times the determinate of jacobian transformation\n", 195 | " # gradc=0.0\n", 196 | " # for i in range(my1dmesh.nodesperelement):\n", 197 | " # iInd=elconn[i]\n", 198 | " # gradc+=shp_grad[i]*c[iInd]\n", 199 | " # now we can calculate the F term\n", 200 | " for i in range(my1dmesh.nodesperelement):\n", 201 | " iInd=elconn[i]\n", 202 | " # assemble to global F\n", 203 | " F[iInd]+=(cold[iInd]/dt)*shp_val[i]*JxW\n", 204 | " # now we can calculate the K matrix\n", 205 | " for j in range(my1dmesh.nodesperelement):\n", 206 | " jInd=elconn[j]\n", 207 | " K[iInd,jInd]+=(1.0/dt)*shp_val[j]*shp_val[i]*JxW\\\n", 208 | " +D*shp_grad[j]*shp_grad[i]*JxW\n", 209 | " # apply the flux, in 1d case(bc elemt is 0-d), you don't need surface integration\n", 210 | " iInd=my1dmesh.bcnodeids['right']\n", 211 | " F[iInd]+=j0\n", 212 | " \n", 213 | " # solve the equation\n", 214 | " c=np.linalg.solve(K,F) # current solution\n", 215 | " cold[:]=c[:] # update solution\n", 216 | " # result.save2csv(mesh=my1dmesh,solution=cold,varnamelist=['c'],step=step+1)\n", 217 | " # result.save2vtu(mesh=my1dmesh,solution=cold,varnamelist=['c'],step=step+1)\n", 218 | " print('step=%5d finished!'%(step+1))" 219 | ] 220 | }, 221 | { 222 | "cell_type": "markdown", 223 | "id": "f4cc5e11-7706-418f-aa49-15e0d9a6a4d9", 224 | "metadata": {}, 225 | "source": [ 226 | "# Diffusion in 2d case" 227 | ] 228 | }, 229 | { 230 | "cell_type": "code", 231 | "execution_count": 3, 232 | "id": "c3d44691-691e-42e7-aa62-c5bc4b2992ed", 233 | "metadata": {}, 234 | "outputs": [ 235 | { 236 | "name": "stdout", 237 | "output_type": "stream", 238 | "text": [ 239 | "write result to diff2d-000000.vtu\n", 240 | "write result to diff2d-000001.vtu\n", 241 | "step= 1 finished!\n", 242 | "write result to diff2d-000002.vtu\n", 243 | "step= 2 finished!\n", 244 | "write result to diff2d-000003.vtu\n", 245 | "step= 3 finished!\n", 246 | "write result to diff2d-000004.vtu\n", 247 | "step= 4 finished!\n", 248 | "write result to diff2d-000005.vtu\n", 249 | "step= 5 finished!\n", 250 | "write result to diff2d-000006.vtu\n", 251 | "step= 6 finished!\n", 252 | "write result to diff2d-000007.vtu\n", 253 | "step= 7 finished!\n", 254 | "write result to diff2d-000008.vtu\n", 255 | "step= 8 finished!\n", 256 | "write result to diff2d-000009.vtu\n", 257 | "step= 9 finished!\n", 258 | "write result to diff2d-000010.vtu\n", 259 | "step= 10 finished!\n", 260 | "write result to diff2d-000011.vtu\n", 261 | "step= 11 finished!\n", 262 | "write result to diff2d-000012.vtu\n", 263 | "step= 12 finished!\n", 264 | "write result to diff2d-000013.vtu\n", 265 | "step= 13 finished!\n", 266 | "write result to diff2d-000014.vtu\n", 267 | "step= 14 finished!\n", 268 | "write result to diff2d-000015.vtu\n", 269 | "step= 15 finished!\n", 270 | "write result to diff2d-000016.vtu\n", 271 | "step= 16 finished!\n", 272 | "write result to diff2d-000017.vtu\n", 273 | "step= 17 finished!\n", 274 | "write result to diff2d-000018.vtu\n", 275 | "step= 18 finished!\n", 276 | "write result to diff2d-000019.vtu\n", 277 | "step= 19 finished!\n", 278 | "write result to diff2d-000020.vtu\n", 279 | "step= 20 finished!\n", 280 | "write result to diff2d-000021.vtu\n", 281 | "step= 21 finished!\n", 282 | "write result to diff2d-000022.vtu\n", 283 | "step= 22 finished!\n", 284 | "write result to diff2d-000023.vtu\n", 285 | "step= 23 finished!\n", 286 | "write result to diff2d-000024.vtu\n", 287 | "step= 24 finished!\n", 288 | "write result to diff2d-000025.vtu\n", 289 | "step= 25 finished!\n", 290 | "write result to diff2d-000026.vtu\n", 291 | "step= 26 finished!\n", 292 | "write result to diff2d-000027.vtu\n", 293 | "step= 27 finished!\n", 294 | "write result to diff2d-000028.vtu\n", 295 | "step= 28 finished!\n", 296 | "write result to diff2d-000029.vtu\n", 297 | "step= 29 finished!\n", 298 | "write result to diff2d-000030.vtu\n", 299 | "step= 30 finished!\n", 300 | "write result to diff2d-000031.vtu\n", 301 | "step= 31 finished!\n", 302 | "write result to diff2d-000032.vtu\n", 303 | "step= 32 finished!\n", 304 | "write result to diff2d-000033.vtu\n", 305 | "step= 33 finished!\n", 306 | "write result to diff2d-000034.vtu\n", 307 | "step= 34 finished!\n", 308 | "write result to diff2d-000035.vtu\n", 309 | "step= 35 finished!\n", 310 | "write result to diff2d-000036.vtu\n", 311 | "step= 36 finished!\n", 312 | "write result to diff2d-000037.vtu\n", 313 | "step= 37 finished!\n", 314 | "write result to diff2d-000038.vtu\n", 315 | "step= 38 finished!\n", 316 | "write result to diff2d-000039.vtu\n", 317 | "step= 39 finished!\n", 318 | "write result to diff2d-000040.vtu\n", 319 | "step= 40 finished!\n", 320 | "write result to diff2d-000041.vtu\n", 321 | "step= 41 finished!\n", 322 | "write result to diff2d-000042.vtu\n", 323 | "step= 42 finished!\n", 324 | "write result to diff2d-000043.vtu\n", 325 | "step= 43 finished!\n", 326 | "write result to diff2d-000044.vtu\n", 327 | "step= 44 finished!\n", 328 | "write result to diff2d-000045.vtu\n", 329 | "step= 45 finished!\n", 330 | "write result to diff2d-000046.vtu\n", 331 | "step= 46 finished!\n", 332 | "write result to diff2d-000047.vtu\n", 333 | "step= 47 finished!\n", 334 | "write result to diff2d-000048.vtu\n", 335 | "step= 48 finished!\n", 336 | "write result to diff2d-000049.vtu\n", 337 | "step= 49 finished!\n", 338 | "write result to diff2d-000050.vtu\n", 339 | "step= 50 finished!\n", 340 | "write result to diff2d-000051.vtu\n", 341 | "step= 51 finished!\n", 342 | "write result to diff2d-000052.vtu\n", 343 | "step= 52 finished!\n", 344 | "write result to diff2d-000053.vtu\n", 345 | "step= 53 finished!\n", 346 | "write result to diff2d-000054.vtu\n", 347 | "step= 54 finished!\n", 348 | "write result to diff2d-000055.vtu\n", 349 | "step= 55 finished!\n", 350 | "write result to diff2d-000056.vtu\n", 351 | "step= 56 finished!\n", 352 | "write result to diff2d-000057.vtu\n", 353 | "step= 57 finished!\n", 354 | "write result to diff2d-000058.vtu\n", 355 | "step= 58 finished!\n", 356 | "write result to diff2d-000059.vtu\n", 357 | "step= 59 finished!\n", 358 | "write result to diff2d-000060.vtu\n", 359 | "step= 60 finished!\n", 360 | "write result to diff2d-000061.vtu\n", 361 | "step= 61 finished!\n", 362 | "write result to diff2d-000062.vtu\n", 363 | "step= 62 finished!\n", 364 | "write result to diff2d-000063.vtu\n", 365 | "step= 63 finished!\n", 366 | "write result to diff2d-000064.vtu\n", 367 | "step= 64 finished!\n", 368 | "write result to diff2d-000065.vtu\n", 369 | "step= 65 finished!\n", 370 | "write result to diff2d-000066.vtu\n", 371 | "step= 66 finished!\n", 372 | "write result to diff2d-000067.vtu\n", 373 | "step= 67 finished!\n", 374 | "write result to diff2d-000068.vtu\n", 375 | "step= 68 finished!\n", 376 | "write result to diff2d-000069.vtu\n", 377 | "step= 69 finished!\n", 378 | "write result to diff2d-000070.vtu\n", 379 | "step= 70 finished!\n", 380 | "write result to diff2d-000071.vtu\n", 381 | "step= 71 finished!\n", 382 | "write result to diff2d-000072.vtu\n", 383 | "step= 72 finished!\n", 384 | "write result to diff2d-000073.vtu\n", 385 | "step= 73 finished!\n", 386 | "write result to diff2d-000074.vtu\n", 387 | "step= 74 finished!\n", 388 | "write result to diff2d-000075.vtu\n", 389 | "step= 75 finished!\n", 390 | "write result to diff2d-000076.vtu\n", 391 | "step= 76 finished!\n", 392 | "write result to diff2d-000077.vtu\n", 393 | "step= 77 finished!\n", 394 | "write result to diff2d-000078.vtu\n", 395 | "step= 78 finished!\n", 396 | "write result to diff2d-000079.vtu\n", 397 | "step= 79 finished!\n", 398 | "write result to diff2d-000080.vtu\n", 399 | "step= 80 finished!\n", 400 | "write result to diff2d-000081.vtu\n", 401 | "step= 81 finished!\n", 402 | "write result to diff2d-000082.vtu\n", 403 | "step= 82 finished!\n", 404 | "write result to diff2d-000083.vtu\n", 405 | "step= 83 finished!\n", 406 | "write result to diff2d-000084.vtu\n", 407 | "step= 84 finished!\n", 408 | "write result to diff2d-000085.vtu\n", 409 | "step= 85 finished!\n", 410 | "write result to diff2d-000086.vtu\n", 411 | "step= 86 finished!\n", 412 | "write result to diff2d-000087.vtu\n", 413 | "step= 87 finished!\n", 414 | "write result to diff2d-000088.vtu\n", 415 | "step= 88 finished!\n", 416 | "write result to diff2d-000089.vtu\n", 417 | "step= 89 finished!\n", 418 | "write result to diff2d-000090.vtu\n", 419 | "step= 90 finished!\n", 420 | "write result to diff2d-000091.vtu\n", 421 | "step= 91 finished!\n", 422 | "write result to diff2d-000092.vtu\n", 423 | "step= 92 finished!\n", 424 | "write result to diff2d-000093.vtu\n", 425 | "step= 93 finished!\n", 426 | "write result to diff2d-000094.vtu\n", 427 | "step= 94 finished!\n", 428 | "write result to diff2d-000095.vtu\n", 429 | "step= 95 finished!\n", 430 | "write result to diff2d-000096.vtu\n", 431 | "step= 96 finished!\n", 432 | "write result to diff2d-000097.vtu\n", 433 | "step= 97 finished!\n", 434 | "write result to diff2d-000098.vtu\n", 435 | "step= 98 finished!\n", 436 | "write result to diff2d-000099.vtu\n", 437 | "step= 99 finished!\n", 438 | "write result to diff2d-000100.vtu\n", 439 | "step= 100 finished!\n" 440 | ] 441 | }, 442 | { 443 | "data": { 444 | "image/png": "iVBORw0KGgoAAAANSUhEUgAAAZIAAAEKCAYAAAA4t9PUAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjUuMSwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy/YYfK9AAAACXBIWXMAAAsTAAALEwEAmpwYAAAZ7UlEQVR4nO3df4zc9X3n8eerm1h3+cGtCYFYtjm7e3vhrBZcOjWo6XU3pWltI2WDVCRDz7hA5LgXN0FXdLj5o43O9wdFpJzQEa82iVWQSnzoAseetIlrud3lIiDndbo1tqnLxiV4sWNvoLtkyx2nxe/7Y76bfDV8dz2zn5nvsOzrIY1mvp/35/OZ92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iRmZpbEhcTMzJK4kJiZWRIXEjMzS+JCYmZmSVxIzMwsiQuJmZkl+f8MQDwpn4afMwAAAABJRU5ErkJggg==\n", 445 | "text/plain": [ 446 | "
" 447 | ] 448 | }, 449 | "metadata": { 450 | "needs_background": "light" 451 | }, 452 | "output_type": "display_data" 453 | } 454 | ], 455 | "source": [ 456 | "from FEToy.mesh.lagrange2dmesh import mesh2d\n", 457 | "from FEToy.fe.shapefun import shape1d\n", 458 | "from FEToy.fe.shapefun import shape2d\n", 459 | "from FEToy.fe.gaussrule import gausspoint1d\n", 460 | "from FEToy.fe.gaussrule import gausspoint2d\n", 461 | "from FEToy.postprocess.Result import ResultIO\n", 462 | "import numpy as np\n", 463 | "\n", 464 | "# define your mesh\n", 465 | "my2dmesh=mesh2d(nx=40,ny=8,xmax=1.0,ymax=0.2,meshtype='quad9')\n", 466 | "my2dmesh.createmesh()\n", 467 | "my2dmesh.plotmesh()\n", 468 | "\n", 469 | "#define your shape fun and gauss points\n", 470 | "shp1d=shape1d(meshtype='edge2')\n", 471 | "shp1d.update()\n", 472 | "\n", 473 | "# 4--7--3\n", 474 | "# | | |\n", 475 | "# 8--9--6 \n", 476 | "# | | |\n", 477 | "# 1--5--2\n", 478 | "shp2d=shape2d(meshtype='quad9')\n", 479 | "shp2d.update()\n", 480 | "\n", 481 | "qpoints1d=gausspoint1d(ngp=2)\n", 482 | "qpoints1d.creategausspoint()\n", 483 | "\n", 484 | "qpoints2d=gausspoint2d(ngp=2) # for quad9, you need ngp>=3!\n", 485 | "qpoints2d.creategausspoint()\n", 486 | "\n", 487 | "############################################\n", 488 | "# define your parameters\n", 489 | "D=0.5 # diffusion coefficient\n", 490 | "dt=1.0e-2 # time step size\n", 491 | "totalstep=100 # the total time step\n", 492 | "j0=0.005 # flux\n", 493 | "\n", 494 | "nDofs=my2dmesh.nodes*1\n", 495 | "K=np.zeros((nDofs,nDofs))\n", 496 | "F=np.zeros(nDofs)\n", 497 | "cold=np.zeros(nDofs) # solution in previous step\n", 498 | "c=np.zeros(nDofs) # solution in current step\n", 499 | "\n", 500 | "# apply initial condition\n", 501 | "cold[:]=0.001\n", 502 | "# cold= np.random.normal(0.5, 0.02, nDofs)\n", 503 | "\n", 504 | "# define a csv output\n", 505 | "result=ResultIO('diff2d')\n", 506 | "# result.save2csv(mesh=my2dmesh,solution=cold,varnamelist=['c'],step=0)\n", 507 | "result.save2vtu(mesh=my2dmesh,solution=cold,varnamelist=['c'],step=0)\n", 508 | "for step in range(totalstep):\n", 509 | " # init your k and F\n", 510 | " K[:,:]=0.0;F[:]=0.0\n", 511 | " for e in range(my2dmesh.elements):\n", 512 | " elconn=my2dmesh.elementconn[e,:]\n", 513 | " nodes=my2dmesh.nodecoords[elconn,:]\n", 514 | " # now we can do the integration\n", 515 | " for gp in range(qpoints2d.ngp2):\n", 516 | " xi =qpoints2d.gpcoords[gp,1] # 1->xi, 2->eta\n", 517 | " eta=qpoints2d.gpcoords[gp,2] # 1->xi, 2->eta\n", 518 | " w =qpoints2d.gpcoords[gp,0] # weight\n", 519 | " \n", 520 | " shp_val,shp_grad,j=shp2d.calc(xi,eta,nodes[:,0],nodes[:,1]) # xi,eta,x,y\n", 521 | " JxW=j*w # the weight times the determinate of jacobian transformation\n", 522 | " # now we can calculate the F term\n", 523 | " for i in range(my2dmesh.nodesperelement):\n", 524 | " iInd=elconn[i]\n", 525 | " # assemble to global F\n", 526 | " F[iInd]+=(cold[iInd]/dt)*shp_val[i]*JxW\n", 527 | " # now we can calculate the K matrix\n", 528 | " for j in range(my2dmesh.nodesperelement):\n", 529 | " jInd=elconn[j]\n", 530 | " K[iInd,jInd]+=(1.0/dt)*shp_val[j]*shp_val[i]*JxW\\\n", 531 | " +D*(shp_grad[j,0]*shp_grad[i,0]\\\n", 532 | " +shp_grad[j,1]*shp_grad[i,1])*JxW\n", 533 | "# # apply the flux, now you need the surface integration\n", 534 | "# bcelmt=my2dmesh.bcconn['right'] # we want to apply the flux on the right side\n", 535 | "# for e in range(np.shape(bcelmt)[0]):\n", 536 | "# elconn=bcelmt[e,:]\n", 537 | "# nodes=my2dmesh.nodecoords[elconn,:]\n", 538 | "# for gp in range(qpoints1d.ngp):\n", 539 | "# xi =qpoints1d.gpcoords[gp,1] # 1->xi, 2->eta\n", 540 | "# w =qpoints1d.gpcoords[gp,0] # weight\n", 541 | " \n", 542 | "# shp_val,shp_grad,j=shp1d.calc(xi,nodes[:,1]) # for left side, you need 'y'\n", 543 | "# JxW=j*w # the weight times the determinate of jacobian transformation\n", 544 | "# # now we can calculate the F term\n", 545 | "# for i in range(len(elconn)):\n", 546 | "# iInd=elconn[i]\n", 547 | "# # assemble to global F\n", 548 | "# F[iInd]+=j0*shp_val[i]*JxW\n", 549 | " ####\n", 550 | " # Appyl boundary conditions\n", 551 | " y2=5.0\n", 552 | " iInd=my2dmesh.bcnodeids['left']\n", 553 | " K[iInd,iInd]+=1.0e16\n", 554 | " F[iInd]+=y2*1.0e16\n", 555 | "\n", 556 | " iInd=my2dmesh.bcnodeids['right']\n", 557 | " K[iInd,iInd]+=1.0e16\n", 558 | " F[iInd]+=y2*1.0e16\n", 559 | "\n", 560 | " iInd=my2dmesh.bcnodeids['bottom']\n", 561 | " K[iInd,iInd]+=1.0e16\n", 562 | " F[iInd]+=y2*1.0e16\n", 563 | "\n", 564 | " iInd=my2dmesh.bcnodeids['top']\n", 565 | " K[iInd,iInd]+=1.0e16\n", 566 | " F[iInd]+=y2*1.0e16\n", 567 | " \n", 568 | " \n", 569 | " # solve the equation\n", 570 | " c=np.linalg.solve(K,F)\n", 571 | " cold[:]=c[:] # update solution\n", 572 | " # result.save2csv(mesh=my2dmesh,solution=cold,varnamelist=['c'],step=step+1)\n", 573 | " result.save2vtu(mesh=my2dmesh,solution=cold,varnamelist=['c'],step=step+1)\n", 574 | " print('step=%5d finished!'%(step+1))" 575 | ] 576 | } 577 | ], 578 | "metadata": { 579 | "kernelspec": { 580 | "display_name": "Python 3 (ipykernel)", 581 | "language": "python", 582 | "name": "python3" 583 | }, 584 | "language_info": { 585 | "codemirror_mode": { 586 | "name": "ipython", 587 | "version": 3 588 | }, 589 | "file_extension": ".py", 590 | "mimetype": "text/x-python", 591 | "name": "python", 592 | "nbconvert_exporter": "python", 593 | "pygments_lexer": "ipython3", 594 | "version": "3.9.12" 595 | } 596 | }, 597 | "nbformat": 4, 598 | "nbformat_minor": 5 599 | } 600 | -------------------------------------------------------------------------------- /6-NewtonRaphson.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "id": "21cf672e-ba27-480c-a1e0-39c6dddd09f8", 6 | "metadata": {}, 7 | "source": [ 8 | "# Your first nonlinear solver- newton-raphson iteration\n", 9 | "\n", 10 | "- [x] newton-raphson method\n", 11 | "- [x] weak form\n", 12 | "- [x] residual and jacobian\n", 13 | "- [x] nonlinear iteration\n", 14 | "- [x] convergence criterion\n", 15 | "- [x] nonlinear poisson equation\n", 16 | "\n", 17 | "Author: Yang Bai @ M3 Group\n", 18 | "\n", 19 | "Date : 2022.04.17\n", 20 | "\n", 21 | "QQ group: 628204857" 22 | ] 23 | }, 24 | { 25 | "cell_type": "markdown", 26 | "id": "279b0813-25ab-4118-b26b-f08ef9a516e0", 27 | "metadata": {}, 28 | "source": [ 29 | "# Newton-raphson method\n", 30 | "\n", 31 | "How to find the root of $f(x)=0$?\n", 32 | "\n", 33 | "Find $x_{0}$ which s.a. $f(x_{0})=0$.\n", 34 | "\n", 35 | "## Taylor expansion\n", 36 | "$f(x^{})=f(x^{k})+\\frac{\\partial f(x^{k})}{\\partial x}(x^{}-x^{k})+\\frac{\\partial^{2} f(x^{k})}{\\partial x^{2}}\\frac{1}{2!}(x^{}-x^{k})^{2}+\\dots$\n", 37 | "\n", 38 | "$f(x_{0})=f(x^{k})+\\frac{\\partial f(x^{k})}{\\partial x}(x_{0}-x^{k})=0$\n", 39 | "\n", 40 | "$x_{0}=x^{k}-\\frac{f(x^{k})}{\\frac{\\partial f(x^{k})}{\\partial x}}$\n", 41 | "\n", 42 | "$f(x^{k})=-\\frac{\\partial f(x^{k})}{\\partial x}(x_{0}-x^{k})=K\\Delta x$, with $K=-\\frac{\\partial f(x^{k})}{\\partial x}$, $\\Delta x=x_{0}-x^{k}$\n", 43 | "\n", 44 | "## Example\n", 45 | "\n", 46 | "### Ex. 1 \n", 47 | "$f(x)=x-1=0$\n", 48 | "\n", 49 | "$K=-\\frac{\\partial f}{\\partial x}=-1$\n", 50 | "\n", 51 | "1st iteration: set x=0, f(x)=-1 ===> dx=K\\f=1\n", 52 | "\n", 53 | "--- update x=x+dx=1 check f(x)=0, done!\n", 54 | "\n", 55 | "### Ex 2\n", 56 | "$f(x)=1.0+sin(x)-x$\n", 57 | "\n", 58 | "$K=-\\frac{\\partial f}{\\partial x}=-cos(x)+1$" 59 | ] 60 | }, 61 | { 62 | "cell_type": "code", 63 | "execution_count": 1, 64 | "id": "9fb9ad30-27e4-4371-afe9-9d4ba81c3323", 65 | "metadata": {}, 66 | "outputs": [ 67 | { 68 | "name": "stdout", 69 | "output_type": "stream", 70 | "text": [ 71 | "iters= 1, |R|= 9.794255e-01, |dx|= 8.000703e+00\n", 72 | "iters= 2, |R|= 6.702639e+00, |dx|= 4.182424e+00\n", 73 | "iters= 3, |R|= 4.241618e+00, |dx|= 3.064783e+00\n", 74 | "iters= 4, |R|= 6.965849e-01, |dx|= 1.012482e+00\n", 75 | "iters= 5, |R|= 4.980408e-01, |dx|= 3.035862e-01\n", 76 | "iters= 6, |R|= 3.809059e-02, |dx|= 2.756864e-02\n", 77 | "iters= 7, |R|= 3.525588e-04, |dx|= 2.599914e-04\n", 78 | "iters= 8, |R|= 3.158407e-08, |dx|= 2.329557e-08\n", 79 | "iters= 9, |R|= 4.440892e-16, |dx|= 3.275484e-16\n", 80 | "the converged solution is: x= 1.934563e+00, f(x)=-2.22044605e-16\n" 81 | ] 82 | } 83 | ], 84 | "source": [ 85 | "import numpy as np\n", 86 | "def f(x):\n", 87 | " return 1.0+np.sin(x)-x\n", 88 | "def df(x):\n", 89 | " return np.cos(x)-1\n", 90 | "\n", 91 | "x=0.5;rnorm=1.0;iters=0;tolerance=1.0e-10\n", 92 | "while iters<200 and rnorm>tolerance:\n", 93 | " R=f(x);K=-df(x)\n", 94 | " dx=R/K\n", 95 | " x+=dx\n", 96 | " rnorm=np.abs(R)\n", 97 | " iters+=1\n", 98 | " print('iters=%3d, |R|=%14.6e, |dx|=%14.6e'%(iters,rnorm,np.abs(dx)))\n", 99 | "if(not rnorm>tolerance):\n", 100 | " print('the converged solution is: x=%14.6e, f(x)=%15.8e'%(x,f(x)))\n", 101 | "else:\n", 102 | " print('oops, your newton-raphson failed!')" 103 | ] 104 | }, 105 | { 106 | "cell_type": "markdown", 107 | "id": "f86fd16b-92e3-4fa0-84c9-2dea6eaabb84", 108 | "metadata": {}, 109 | "source": [ 110 | "# Newton-raphson in FEM\n", 111 | "\n", 112 | "For a FEM problem $\\Pi\\sim\\Pi(u,\\nabla u,\\dot{u},\\dots)$, one need to find $u$ s.a. $\\delta\\Pi=R(u,\\nabla u,\\dot{u},\\dots)\\delta u=0$ with $R=[K(u,\\nabla u,\\dot{u})]\\{u\\}-f(u,\\nabla u,\\dot{u})$\n", 113 | "\n", 114 | "## Nonlinear poisson equation\n", 115 | "\n", 116 | "$\\nabla\\cdot(\\sigma\\nabla\\phi)=f$ with $\\sigma\\sim\\sigma(\\phi)$ and $f\\sim f(\\phi)$, $-\\sigma\\nabla\\phi\\cdot\\vec{n}=0$\n", 117 | "\n", 118 | "### weak form\n", 119 | "$\\int_{\\partial\\Omega}\\sigma\\nabla\\phi\\cdot\\vec{n}\\delta\\phi dS-\\int_{\\Omega}\\sigma\\nabla\\phi\\nabla\\delta\\phi dV=\\int_{\\Omega}f\\delta\\phi dV$\n", 120 | "\n", 121 | "then the residual and jacobian matrix can be read as follows:\n", 122 | "\n", 123 | "$R^{I}=\\int_{\\Omega}\\sigma\\nabla\\phi\\nabla N^{I}dV+\\int_{\\Omega}fN^{I}dV$\n", 124 | "\n", 125 | "$K^{IJ}=-\\frac{\\partial R^{I}}{\\partial\\phi^{J}}=-\\int_{\\Omega}\\frac{\\partial\\sigma}{\\partial\\phi}N^{J}\\nabla\\phi\\nabla N^{I}dV-\\int_{\\Omega}\\sigma\\nabla N^{J}\\nabla N^{I}dV-\\int_{\\Omega}\\frac{\\partial f}{\\partial\\phi}N^{J}N^{I}dV$" 126 | ] 127 | }, 128 | { 129 | "cell_type": "code", 130 | "execution_count": 2, 131 | "id": "f94144e7-81f3-4fc6-b65f-21395e167413", 132 | "metadata": {}, 133 | "outputs": [ 134 | { 135 | "name": "stdout", 136 | "output_type": "stream", 137 | "text": [ 138 | "iters= 1, |R0 |= 1.93746e-01, |R |= 1.93746e-01\n", 139 | " |dU0|= 1.05849e+01, |dU|= 1.05849e+01\n", 140 | " |E0 |= 2.05079e+00, |E |= 2.05079e+00\n", 141 | "iters= 2, |R0 |= 1.93746e-01, |R |= 4.72237e-02\n", 142 | " |dU0|= 1.05849e+01, |dU|= 1.55848e+00\n", 143 | " |E0 |= 2.05079e+00, |E |= 7.35972e-02\n", 144 | "iters= 3, |R0 |= 1.93746e-01, |R |= 9.57083e-04\n", 145 | " |dU0|= 1.05849e+01, |dU|= 2.46349e-02\n", 146 | " |E0 |= 2.05079e+00, |E |= 2.35776e-05\n", 147 | "iters= 4, |R0 |= 1.93746e-01, |R |= 4.03722e-07\n", 148 | " |dU0|= 1.05849e+01, |dU|= 6.51174e-06\n", 149 | " |E0 |= 2.05079e+00, |E |= 2.62893e-12\n", 150 | "iters= 5, |R0 |= 1.93746e-01, |R |= 5.72883e-14\n", 151 | " |dU0|= 1.05849e+01, |dU|= 5.33811e-13\n", 152 | " |E0 |= 2.05079e+00, |E |= 3.05811e-26\n", 153 | "write result to nlpoisson-000000.vtu\n" 154 | ] 155 | } 156 | ], 157 | "source": [ 158 | "from FEToy.mesh.lagrange2dmesh import mesh2d\n", 159 | "from FEToy.fe.shapefun import shape2d\n", 160 | "from FEToy.fe.gaussrule import gausspoint2d\n", 161 | "from FEToy.postprocess.Result import ResultIO\n", 162 | "\n", 163 | "# define your mesh\n", 164 | "mymesh=mesh2d(xmax=2.0,ymax=2.0,nx=20,ny=20,meshtype='quad4')\n", 165 | "mymesh.createmesh()\n", 166 | "\n", 167 | "# define your shape function\n", 168 | "shp=shape2d(meshtype='quad4')\n", 169 | "shp.update()\n", 170 | "\n", 171 | "# define your gauss points\n", 172 | "qpoints=gausspoint2d(ngp=3)\n", 173 | "qpoints.creategausspoint()\n", 174 | "\n", 175 | "\n", 176 | "### defines your physical parameters here\n", 177 | "# since sigma and f both are nonlinear, we can offer functions for them\n", 178 | "def sigma(x):\n", 179 | " return 1+np.exp(x)\n", 180 | " # return 1.0+x*x\n", 181 | "def dsigma(x):\n", 182 | " return np.exp(x)\n", 183 | " # return 2*x\n", 184 | "### for f\n", 185 | "def f(x):\n", 186 | " return 1.0+0.1*x\n", 187 | "def df(x):\n", 188 | " return 0.1\n", 189 | "\n", 190 | "# define your K and rhs, and other vectors\n", 191 | "nDofs=mymesh.nodes*1\n", 192 | "K=np.zeros((nDofs,nDofs))\n", 193 | "R=np.zeros(nDofs)\n", 194 | "U=np.zeros(nDofs)\n", 195 | "penalty=1.0e16 # for dirichlet bc\n", 196 | "\n", 197 | "# for parameters used in NR iteration\n", 198 | "tolerance=1.0e-10;reltol=1.0e-15 # absolute tolerenace and relative tolerance\n", 199 | "maxiters=50\n", 200 | "rnorm=1.0;rnorm0=1.0;iters=0 # init\n", 201 | "dunorm=1.0;dunorm0=1.0\n", 202 | "enorm=1.0;enorm0=1.0\n", 203 | "converged=False\n", 204 | "\n", 205 | "gradphi=np.zeros(2)\n", 206 | "# now we can do the newton-raphson iteration\n", 207 | "while iters" 287 | ] 288 | }, 289 | "metadata": { 290 | "needs_background": "light" 291 | }, 292 | "output_type": "display_data" 293 | } 294 | ], 295 | "source": [ 296 | "from FEToy.mesh.lagrange2dmesh import mesh2d\n", 297 | "from FEToy.fe.shapefun import shape2d\n", 298 | "from FEToy.fe.gaussrule import gausspoint2d\n", 299 | "### for surface integration\n", 300 | "from FEToy.mesh.lagrange1dmesh import mesh1d\n", 301 | "from FEToy.fe.shapefun import shape1d\n", 302 | "from FEToy.fe.gaussrule import gausspoint1d\n", 303 | "### for result output\n", 304 | "from FEToy.postprocess.Result import ResultIO\n", 305 | "import numpy as np\n", 306 | "\n", 307 | "# define your mesh\n", 308 | "mymesh=mesh2d(xmax=3.0,ymax=1.0,nx=45,ny=15,meshtype='quad4')\n", 309 | "mymesh.createmesh()\n", 310 | "mymesh.plotmesh()\n", 311 | "\n", 312 | "# define your shape function\n", 313 | "shp=shape2d(meshtype='quad4')\n", 314 | "shp.update()\n", 315 | "# for surface integration\n", 316 | "shp1d=shape1d(meshtype='edge2')\n", 317 | "shp1d.update()\n", 318 | "\n", 319 | "# define your gauss points\n", 320 | "qpoints=gausspoint2d(ngp=2)\n", 321 | "qpoints.creategausspoint()\n", 322 | "# for surface integration\n", 323 | "qpoints1d=gausspoint1d(ngp=2)\n", 324 | "qpoints1d.creategausspoint()\n", 325 | "\n", 326 | "#################################################\n", 327 | "### defines your physical parameters here\n", 328 | "#################################################\n", 329 | "D0=1.0e0\n", 330 | "j0=-0.02\n", 331 | "def D(x):\n", 332 | " return D0*(1.0+0.8*np.sin(x*np.pi))\n", 333 | "def dD(x):\n", 334 | " return D0*0.8*np.cos(x*np.pi)*np.pi\n", 335 | " # return 2*x\n", 336 | "### for f\n", 337 | "def f(x):\n", 338 | " return 1.0+10.0*x*x\n", 339 | "def df(x):\n", 340 | " return 20.0*x\n", 341 | "\n", 342 | "# define your K and rhs, and other vectors\n", 343 | "nDofs=mymesh.nodes*1\n", 344 | "K =np.zeros((nDofs,nDofs))\n", 345 | "R =np.zeros(nDofs)\n", 346 | "C =np.zeros(nDofs) # solution of current step\n", 347 | "Cold=np.zeros(nDofs) # solution of previous step\n", 348 | "penalty=1.0e16 # for dirichlet bc\n", 349 | "\n", 350 | "#################################################\n", 351 | "### for time stepping and NR iteration\n", 352 | "#################################################\n", 353 | "### for time stepping\n", 354 | "dt=2.0e-3 # time step size\n", 355 | "totalstep=50 # total time step\n", 356 | "### for NR iteration\n", 357 | "tolerance=1.0e-10;reltol=1.0e-15 # absolute tolerenace and relative tolerance\n", 358 | "maxiters=50\n", 359 | "rnorm=1.0;rnorm0=1.0;iters=0 # init\n", 360 | "converged=False\n", 361 | "\n", 362 | "### for result output\n", 363 | "result=ResultIO('nldiff')\n", 364 | "result.save2vtu(mesh=mymesh,solution=C,varnamelist=['c'],step=0) # for initial configuration\n", 365 | "interval=5 # output per 5-steps\n", 366 | "\n", 367 | "gradc=np.zeros(2)\n", 368 | "for step in range(1,totalstep):\n", 369 | " C[:]=Cold[:]\n", 370 | " iters=0;converged=False\n", 371 | " # now we can do the newton-raphson iteration\n", 372 | " print('step=%6d, dt=%14.5e, total time=%14.5e'%(step,dt,dt*step))\n", 373 | " while itersxi, 2->eta\n", 438 | "# w =qpoints1d.gpcoords[gp,0] # weight\n", 439 | " \n", 440 | "# shp_val,shp_grad,j=shp1d.calc(xi,nodes[:,1]) # for left side, you need 'y'\n", 441 | "# JxW=j*w # the weight times the determinate of jacobian transformation\n", 442 | "# # now we can calculate the surface flux\n", 443 | "# y=0.0\n", 444 | "# for i in range(len(elconn)):\n", 445 | "# y+=shp_val[i]*nodes[i,1]\n", 446 | "# for i in range(len(elconn)):\n", 447 | "# iInd=elconn[i]\n", 448 | "# # R_{c}^{I}=\\int_{\\Omega}\\dot{c}N^{I}dV\n", 449 | "# # +\\int_{\\Omega}D(c)\\nabla c\\nabla N^{I}dV\n", 450 | "# # -\\int_{\\Omega}f(c)N^{I}dV\n", 451 | "# # +\\int_{\\partial\\Omega}j_{0}N^{I}dS\n", 452 | "# # assemble to global residual\n", 453 | "# # R[iInd]+=j0*shp_val[i]*JxW\n", 454 | "# R[iInd]+=j0*np.sin(y)*shp_val[i]*JxW\n", 455 | " # ### here we apply the flux to 'right' edge\n", 456 | " bcelmt=mymesh.bcconn['top'] # we want to apply the flux on the right side\n", 457 | " for e in range(np.shape(bcelmt)[0]):\n", 458 | " elconn=bcelmt[e,:]\n", 459 | " nodes=mymesh.nodecoords[elconn,:]\n", 460 | " for gp in range(qpoints1d.ngp):\n", 461 | " xi =qpoints1d.gpcoords[gp,1] # 1->xi, 2->eta\n", 462 | " w =qpoints1d.gpcoords[gp,0] # weight\n", 463 | " \n", 464 | " shp_val,shp_grad,j=shp1d.calc(xi,nodes[:,0]) # for left side, you need 'x'\n", 465 | " JxW=j*w # the weight times the determinate of jacobian transformation\n", 466 | " # now we can calculate the surface flux\n", 467 | " x=0.0\n", 468 | " for i in range(len(elconn)):\n", 469 | " x+=shp_val[i]*nodes[i,0]\n", 470 | " for i in range(len(elconn)):\n", 471 | " iInd=elconn[i]\n", 472 | " # R_{c}^{I}=\\int_{\\Omega}\\dot{c}N^{I}dV\n", 473 | " # +\\int_{\\Omega}D(c)\\nabla c\\nabla N^{I}dV\n", 474 | " # -\\int_{\\Omega}f(c)N^{I}dV\n", 475 | " # +\\int_{\\partial\\Omega}j_{0}N^{I}dS\n", 476 | " # assemble to global residual\n", 477 | " # R[iInd]+=j0*shp_val[i]*JxW\n", 478 | " R[iInd]+=j0*np.sin(x*np.pi*2.0)*shp_val[i]*JxW\n", 479 | " # end-of-bc-element-loop\n", 480 | " ###################################################\n", 481 | " ### now your K and R are ready, we can solve Ax=b\n", 482 | " ###################################################\n", 483 | " dC=np.linalg.solve(K,R)\n", 484 | " # update iteration info\n", 485 | " iters+=1\n", 486 | " C[:]+=dC[:]\n", 487 | " rnorm=np.linalg.norm(R)\n", 488 | " dunorm=np.linalg.norm(dC)\n", 489 | " enorm=rnorm*dunorm\n", 490 | " if iters==1:\n", 491 | " rnorm0=rnorm\n", 492 | " dunorm0=dunorm\n", 493 | " enorm0=enorm\n", 494 | " print(' iters=%3d, |R0 |=%14.5e, |R |=%14.5e'%(iters,rnorm0,rnorm))\n", 495 | " # print(' |dU0|=%14.5e, |dU|=%14.5e'%(dunorm0,dunorm))\n", 496 | " # print(' |E0 |=%14.5e, |E |=%14.5e'%(enorm0,enorm))\n", 497 | " ##########################################\n", 498 | " # convergence check\n", 499 | " ##########################################\n", 500 | " if rnorm>> clean files 22 | for file in files: 23 | if ('.csv' in file): 24 | try: 25 | csvfile+=1 26 | removepath=subdir+'/'+file 27 | os.remove(removepath) 28 | except: 29 | print('%s is not here'%(file)) 30 | elif '.swp' in file: 31 | name=str(file) 32 | if '.swp' in name[-4:]: 33 | try: 34 | swp+=1 35 | removepath=subdir+'/'+file 36 | os.remove(removepath) 37 | except: 38 | print('%s is not here'%(file)) 39 | elif ('.i' in file) or ('.cpp' in file) or ('.C' in file) or ('.c' in file and 'cmake_install.cmake' not in file) or ('.h' in file) or ('.hpp' in file) or ('.msh' in file) or ('.geo' in file) or ('.gmsh2' in file) or ('.inp' in file) or ('.py' in file) or ('.C' in file) or ('.txt' in file and 'CMakeCache.txt' not in file) or ('.tex' in file) or ('.jpg' in file) or ('.jpeg' in file) or ('.png' in file) or ('.gif' in file) or ('.pdf' in file) or ('.doc' in file) or ('.docx' in file) or ('.f03' in file) or ('.f08' in file) or ('.f90' in file) or ('.f' in file) or ('.xlsx' in file) or ('Doxyfile' in file): 40 | continue 41 | elif ('ASFEM' in file) or ('asfem' in file): 42 | try: 43 | ASFEM+=1 44 | removepath=subdir+'/'+file 45 | os.remove(removepath) 46 | except: 47 | print('%s is not here'%(file)) 48 | elif 'vgcore.' in file: 49 | try: 50 | valgrind+=1 51 | removepath=subdir+'/'+file 52 | os.remove(removepath) 53 | except: 54 | print('%s is not here'%(file)) 55 | elif 'compile_commands.json' in file: 56 | try: 57 | cmake+=1 58 | removepath=subdir+'/'+file 59 | os.remove(removepath) 60 | except: 61 | print('%s is not here'%(file)) 62 | elif '.o' in file: 63 | try: 64 | o+=1 65 | removepath=subdir+'/'+file 66 | os.remove(removepath) 67 | except: 68 | print('%s is not here'%(file)) 69 | elif ('CMakeCache.txt' in file) or ('cmake_install.cmake' in file) or ('Makefile' in file): 70 | try: 71 | cmake+=1 72 | removepath=subdir+'/'+file 73 | os.remove(removepath) 74 | except: 75 | print('%s is not here'%(file)) 76 | elif ('.vtu' in file) or ('.vtk' in file) or ('.pvd' in file): 77 | try: 78 | vtu+=1 79 | removepath=subdir+'/'+file 80 | os.remove(removepath) 81 | except: 82 | print('%s is not here'%(file)) 83 | elif ('.avi' in file) or ('.gif' in file): 84 | try: 85 | metafile+=1 86 | removepath=subdir+'/'+file 87 | os.remove(removepath) 88 | except: 89 | print('%s is not here'%(file)) 90 | #>> clean folder 91 | for dir in dirs: 92 | if '.idea' in dir: 93 | try: 94 | ideafolder+=1 95 | removepath=subdir+'/'+dir 96 | print('remove folder: ',dir) 97 | shutil.rmtree(removepath) 98 | IdeaRemove=True 99 | except: 100 | if(not IdeaRemove): 101 | print('%s is not here'%(dir)) 102 | elif '.cache' in dir: 103 | try: 104 | cache+=1 105 | removepath=subdir+'/'+dir 106 | print('remove folder: ',dir) 107 | shutil.rmtree(removepath) 108 | CacheRemove=True 109 | except: 110 | if(not CacheRemove): 111 | print('%s is not here'%(dir)) 112 | elif '.ipynb_checkpoints' in dir: 113 | try: 114 | cache+=1 115 | removepath=subdir+'/'+dir 116 | print('remove folder: ',dir) 117 | shutil.rmtree(removepath) 118 | CacheRemove=True 119 | except: 120 | if(not CacheRemove): 121 | print('%s is not here'%(dir)) 122 | elif '__pycache__' in dir: 123 | try: 124 | cache+=1 125 | removepath=subdir+'/'+dir 126 | print('remove folder: ',dir) 127 | shutil.rmtree(removepath) 128 | CacheRemove=True 129 | except: 130 | if(not CacheRemove): 131 | print('%s is not here'%(dir)) 132 | elif '.clangd' in dir: 133 | try: 134 | ideafolder+=1 135 | removepath=subdir+'/'+dir 136 | print('remove folder: ',dir) 137 | shutil.rmtree(removepath) 138 | ClangRemove=True 139 | except: 140 | if(not ClangRemove): 141 | print('%s is not here'%(dir)) 142 | elif 'document' in dir: 143 | try: 144 | cmakefolder+=1 145 | removepath=subdir+'/'+dir 146 | print('remove document folder:',dir) 147 | shutil.rmtree(removepath) 148 | DocumentRemove=True 149 | except: 150 | if(not DocumentRemove): 151 | print('%s is not here'%(dir)) 152 | elif ('cmake-build-debug' in dir) or ('build' in dir) or ('CMakeFiles' in dir): 153 | try: 154 | cmakefolder+=1 155 | removepath=subdir+'/'+dir 156 | print('remove folder: ',dir) 157 | shutil.rmtree(removepath) 158 | IdeaRemove=True 159 | except: 160 | if(not IdeaRemove): 161 | print('%s is not here'%(dir)) 162 | 163 | print('Remove %4d ASFEM files!'%(ASFEM)) 164 | print('Remove %4d vtu files!'%(vtu)) 165 | print('Remove %4d csv files!'%(csvfile)) 166 | print('Remove %4d .o files!'%(o)) 167 | print('Remove %4d .swp files!'%(swp)) 168 | print('Remove %4d valgrind file!'%(valgrind)) 169 | print('Remove %4d meta files!'%(metafile)) 170 | print('Remove %4d .idea folder!'%(ideafolder)) 171 | print('Remove %4d cache files!'%(cache)) 172 | print('Remove %4d cmake file!'%(cmake)) 173 | print('Remove %4d cmake folder!'%(cmakefolder)) 174 | -------------------------------------------------------------------------------- /Demo-Rank2Tensor.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "id": "d4d0e451-bf79-4b09-a28c-ee03b20665e8", 6 | "metadata": {}, 7 | "source": [ 8 | "# Demo notebook for tensor manipulation\n", 9 | "\n", 10 | "- [x] standard operators between tensor/vector and tensor/scalar\n", 11 | "\n", 12 | "\n", 13 | "Author: Yang Bai @ M3 Group\n", 14 | "\n", 15 | "Date : 2022.07.30\n", 16 | "\n", 17 | "QQ group: 628204857" 18 | ] 19 | }, 20 | { 21 | "cell_type": "code", 22 | "execution_count": 1, 23 | "id": "1cc93fce-f73f-40c6-9958-245c60a33e04", 24 | "metadata": {}, 25 | "outputs": [], 26 | "source": [ 27 | "# before we start, we need to import the vector/tensor class\n", 28 | "from FEToy.mathutils.vector import vector\n", 29 | "from FEToy.mathutils.tensor import rank2tensor" 30 | ] 31 | }, 32 | { 33 | "cell_type": "markdown", 34 | "id": "33c45150-9e5a-45a8-8326-10d7772d5e2a", 35 | "metadata": {}, 36 | "source": [ 37 | "## $+$ operator\n", 38 | "\n", 39 | "$+$ operator can be used for the calculation in $\\mathbf{A}+\\mathbf{B}$ and $\\mathbf{A}+b$\n", 40 | "\n", 41 | "where\n", 42 | "\n", 43 | "$\\mathbf{A}+\\mathbf{B}=\\mathbf{C},\\mathrm{with}~C_{ij}=A_{ij}+B_{ij}$\n", 44 | "\n", 45 | "and\n", 46 | "\n", 47 | "$\\mathbf{A}+b=\\mathbf{C},\\mathrm{with}~C_{ij}=A_{ij}+b$" 48 | ] 49 | }, 50 | { 51 | "cell_type": "code", 52 | "execution_count": 7, 53 | "id": "fc8be95c-7e12-466b-a594-47bcb6830334", 54 | "metadata": {}, 55 | "outputs": [ 56 | { 57 | "name": "stdout", 58 | "output_type": "stream", 59 | "text": [ 60 | "tensor a, tensor components are: \n", 61 | " | 0.00000e+00, 0.00000e+00 0.00000e+00|\n", 62 | " | 0.00000e+00, 0.00000e+00 0.00000e+00|\n", 63 | " | 0.00000e+00, 0.00000e+00 0.00000e+00|\n", 64 | "tensor a set to random, tensor components are: \n", 65 | " | 8.21661e-01, 1.45697e-01 8.61283e-01|\n", 66 | " | 7.26508e-01, 6.99656e-01 3.80291e-01|\n", 67 | " | 9.32837e-01, 7.22606e-01 3.63220e-01|\n", 68 | "tensor b, tensor components are: \n", 69 | " | 1.00000e+00, 0.00000e+00 0.00000e+00|\n", 70 | " | 0.00000e+00, 1.00000e+00 0.00000e+00|\n", 71 | " | 0.00000e+00, 0.00000e+00 1.00000e+00|\n", 72 | "( 1.82166e+00, 1.45697e-01, 8.61283e-01)\n", 73 | "( 7.26508e-01, 1.69966e+00, 3.80291e-01)\n", 74 | "( 9.32837e-01, 7.22606e-01, 1.36322e+00)\n", 75 | "1.8216613759021827\n", 76 | "0.7226058715106245\n", 77 | "tensor a(2d), tensor components are: \n", 78 | " | 9.92847e-01, 5.50016e-01|\n", 79 | " | 3.31175e-01, 1.71914e-01|\n", 80 | "tensor b(2d), tensor components are: \n", 81 | " | 1.00000e+00, 0.00000e+00|\n", 82 | " | 0.00000e+00, 1.00000e+00|\n", 83 | "tensor a+b(2d), tensor components are: \n", 84 | " | 1.99285e+00, 5.50016e-01|\n", 85 | " | 3.31175e-01, 1.17191e+00|\n" 86 | ] 87 | } 88 | ], 89 | "source": [ 90 | "tensor_a = rank2tensor(dim=3)\n", 91 | "tensor_a.print('tensor a')\n", 92 | "tensor_a.setToRandom()\n", 93 | "tensor_a.print('tensor a set to random')\n", 94 | "\n", 95 | "tensor_b = rank2tensor(dim=3,value=0.0)\n", 96 | "tensor_b.setToIdentity()\n", 97 | "tensor_b.print('tensor b')\n", 98 | "\n", 99 | "\n", 100 | "tensor_c = tensor_a+tensor_b\n", 101 | "print(tensor_c)\n", 102 | "print(tensor_c[0,0])\n", 103 | "print(tensor_c[2,1])\n", 104 | "\n", 105 | "tensor_a_2d =rank2tensor(dim=2)\n", 106 | "tensor_a_2d.setToRandom()\n", 107 | "tensor_a_2d.print('tensor a(2d)')\n", 108 | "\n", 109 | "tensor_b_2d=rank2tensor(dim=2)\n", 110 | "tensor_b_2d.setToIdentity()\n", 111 | "tensor_b_2d.print('tensor b(2d)')\n", 112 | "\n", 113 | "(tensor_a_2d+tensor_b_2d).print('tensor a+b(2d)')\n" 114 | ] 115 | }, 116 | { 117 | "cell_type": "markdown", 118 | "id": "4fbaa859-8ff2-44a5-8c2b-a24ec8fbe8ea", 119 | "metadata": {}, 120 | "source": [ 121 | "## $-$ operator\n", 122 | "\n", 123 | "$-$ operator can be used for the calculation in $\\mathbf{A}-\\mathbf{B}$ and $\\mathbf{A}-b$\n", 124 | "\n", 125 | "where\n", 126 | "\n", 127 | "$\\mathbf{A}-\\mathbf{B}=\\mathbf{C},\\mathrm{with}~C_{ij}=A_{ij}-B_{ij}$\n", 128 | "\n", 129 | "and\n", 130 | "\n", 131 | "$\\mathbf{A}-b=\\mathbf{C},\\mathrm{with}~C_{ij}=A_{ij}-b$" 132 | ] 133 | }, 134 | { 135 | "cell_type": "code", 136 | "execution_count": 3, 137 | "id": "398f1f27-552a-4f02-b326-1a9cedbe193d", 138 | "metadata": {}, 139 | "outputs": [ 140 | { 141 | "name": "stdout", 142 | "output_type": "stream", 143 | "text": [ 144 | "( 8.38167e-01, 8.71844e-01, 8.41737e-01)\n", 145 | "( 1.26277e-01, 3.50664e-01, 4.43467e-02)\n", 146 | "( 8.00416e-01, 2.62125e-01, 5.91497e-01)\n", 147 | "-------------------------------------\n", 148 | "( 1.00000e+00, 0.00000e+00, 0.00000e+00)\n", 149 | "( 0.00000e+00, 1.00000e+00, 0.00000e+00)\n", 150 | "( 0.00000e+00, 0.00000e+00, 1.00000e+00)\n", 151 | "-------------------------------------\n", 152 | "( -1.61833e-01, 8.71844e-01, 8.41737e-01)\n", 153 | "( 1.26277e-01, -6.49336e-01, 4.43467e-02)\n", 154 | "( 8.00416e-01, 2.62125e-01, -4.08503e-01)\n", 155 | "-------------------------------------\n", 156 | "( -2.16183e+00, -1.12816e+00, -1.15826e+00)\n", 157 | "( -1.87372e+00, -2.64934e+00, -1.95565e+00)\n", 158 | "( -1.19958e+00, -1.73788e+00, -2.40850e+00)\n", 159 | "-------------------------------------\n" 160 | ] 161 | } 162 | ], 163 | "source": [ 164 | "tensor_c = tensor_a-tensor_b\n", 165 | "\n", 166 | "print(tensor_a)\n", 167 | "print('-------------------------------------')\n", 168 | "\n", 169 | "print(tensor_b)\n", 170 | "print('-------------------------------------')\n", 171 | "\n", 172 | "print(tensor_c)\n", 173 | "print('-------------------------------------')\n", 174 | "\n", 175 | "tensor_d = tensor_c-2.0\n", 176 | "print(tensor_d)\n", 177 | "print('-------------------------------------')" 178 | ] 179 | }, 180 | { 181 | "cell_type": "markdown", 182 | "id": "95a5b74f-7f30-4e74-9fe1-46739aafb389", 183 | "metadata": {}, 184 | "source": [ 185 | "## $*$ operator\n", 186 | "\n", 187 | "$*$ operator can be used for the calculation in $\\mathbf{A}*\\vec{b}$ and $\\mathbf{A}*b$\n", 188 | "\n", 189 | "where\n", 190 | "\n", 191 | "$\\mathbf{A}\\cdot\\vec{b}=\\vec{c},\\mathrm{with}~c_{i}=\\sum_{j}a_{ij}b_{j}$\n", 192 | "\n", 193 | "and\n", 194 | "\n", 195 | "$\\mathbf{A}\\cdot b=\\mathbf{C},\\mathrm{with}~C_{ij}=A_{ij}*b$" 196 | ] 197 | }, 198 | { 199 | "cell_type": "code", 200 | "execution_count": 4, 201 | "id": "6d372727-c4b9-4e63-ad43-980b9de40264", 202 | "metadata": {}, 203 | "outputs": [ 204 | { 205 | "name": "stdout", 206 | "output_type": "stream", 207 | "text": [ 208 | "Vector a is:\n", 209 | "( 1.00000e+00, 1.00000e+00, 1.00000e+00)\n", 210 | "-------------------------------------\n", 211 | "Tensor D is:\n", 212 | "( -2.16183e+00, -1.12816e+00, -1.15826e+00)\n", 213 | "( -1.87372e+00, -2.64934e+00, -1.95565e+00)\n", 214 | "( -1.19958e+00, -1.73788e+00, -2.40850e+00)\n", 215 | "-------------------------------------\n", 216 | "Tensor D* Vector b result:\n", 217 | "( -4.44825e+00, -6.47871e+00, -5.34596e+00)\n", 218 | "-------------------------------------\n", 219 | "Tensor D* 5.0 result:\n", 220 | "( -1.08092e+01, -5.64078e+00, -5.79132e+00)\n", 221 | "( -9.36862e+00, -1.32467e+01, -9.77827e+00)\n", 222 | "( -5.99792e+00, -8.68938e+00, -1.20425e+01)\n", 223 | "-------------------------------------\n" 224 | ] 225 | } 226 | ], 227 | "source": [ 228 | "vec_a = vector(3,1.0)\n", 229 | "\n", 230 | "print('Vector a is:')\n", 231 | "print(vec_a)\n", 232 | "print('-------------------------------------')\n", 233 | "\n", 234 | "print('Tensor D is:')\n", 235 | "print(tensor_d)\n", 236 | "print('-------------------------------------')\n", 237 | "\n", 238 | "\n", 239 | "print('Tensor D* Vector b result:')\n", 240 | "vec_b = tensor_d*vec_a\n", 241 | "print(vec_b)\n", 242 | "print('-------------------------------------')\n", 243 | "\n", 244 | "\n", 245 | "print('Tensor D* 5.0 result:')\n", 246 | "print(tensor_d*5.0)\n", 247 | "print('-------------------------------------')" 248 | ] 249 | }, 250 | { 251 | "cell_type": "markdown", 252 | "id": "c887bd7a-2efa-4c51-9f1e-0c822f41e4e4", 253 | "metadata": {}, 254 | "source": [ 255 | "## $/$ operator\n", 256 | "\n", 257 | "$/$ operator can only be used for the calculation in $\\mathbf{a}/b$\n", 258 | "\n", 259 | "where\n", 260 | "\n", 261 | "\n", 262 | "$\\mathbf{A}/ b=\\mathbf{C},\\mathrm{with}~C_{ij}=A_{ij}/b$" 263 | ] 264 | }, 265 | { 266 | "cell_type": "code", 267 | "execution_count": 5, 268 | "id": "b0f61a66-276b-4d84-8221-b42b412ae049", 269 | "metadata": {}, 270 | "outputs": [ 271 | { 272 | "name": "stdout", 273 | "output_type": "stream", 274 | "text": [ 275 | "tensor e is:\n", 276 | "( -1.16183e+00, -1.28156e-01, -1.58263e-01)\n", 277 | "( -8.73723e-01, -1.64934e+00, -9.55653e-01)\n", 278 | "( -1.99584e-01, -7.37875e-01, -1.40850e+00)\n", 279 | "-------------------------------------\n", 280 | "tensor e/10.0 is\n", 281 | "( -1.16183e-01, -1.28156e-02, -1.58263e-02)\n", 282 | "( -8.73723e-02, -1.64934e-01, -9.55653e-02)\n", 283 | "( -1.99584e-02, -7.37875e-02, -1.40850e-01)\n" 284 | ] 285 | } 286 | ], 287 | "source": [ 288 | "tensor_e= tensor_d+1.0\n", 289 | "\n", 290 | "print('tensor e is:')\n", 291 | "print(tensor_e)\n", 292 | "print('-------------------------------------')\n", 293 | "\n", 294 | "print('tensor e/10.0 is')\n", 295 | "print(tensor_e/10.0)" 296 | ] 297 | }, 298 | { 299 | "cell_type": "markdown", 300 | "id": "7e07329b-8038-4352-b1e3-435eba189431", 301 | "metadata": {}, 302 | "source": [ 303 | "## Other operators\n", 304 | "\n", 305 | "dev, trace, det, and double contraction" 306 | ] 307 | }, 308 | { 309 | "cell_type": "code", 310 | "execution_count": 6, 311 | "id": "32da3d68-e3bd-4a02-be70-9bd3c0b73a7b", 312 | "metadata": {}, 313 | "outputs": [ 314 | { 315 | "name": "stdout", 316 | "output_type": "stream", 317 | "text": [ 318 | "tensor e is:\n", 319 | "( -1.16183e+00, -1.28156e-01, -1.58263e-01)\n", 320 | "( -8.73723e-01, -1.64934e+00, -9.55653e-01)\n", 321 | "( -1.99584e-01, -7.37875e-01, -1.40850e+00)\n", 322 | "-------------------------------------\n", 323 | "trace of tensor e is:\n", 324 | "-4.219671348881736\n", 325 | "-------------------------------------\n", 326 | "det of tensor e is:\n", 327 | "-1.7964415859486575\n", 328 | "-------------------------------------\n", 329 | "dev of tensor e is:\n", 330 | "( 2.44724e-01, -1.28156e-01, -1.58263e-01)\n", 331 | "( -8.73723e-01, -2.42779e-01, -9.55653e-01)\n", 332 | "( -1.99584e-01, -7.37875e-01, -1.94581e-03)\n", 333 | "-------------------------------------\n", 334 | "1st col of tensor e is:\n", 335 | "( -1.16183e+00, -8.73723e-01, -1.99584e-01)\n", 336 | "-------------------------------------\n", 337 | "2nd row of tensor e is:\n", 338 | "( -8.73723e-01, -1.64934e+00, -9.55653e-01)\n", 339 | "-------------------------------------\n", 340 | "double contraction between tensor e and its dev part:\n", 341 | "2.421265723034666\n" 342 | ] 343 | } 344 | ], 345 | "source": [ 346 | "print('tensor e is:')\n", 347 | "print(tensor_e)\n", 348 | "print('-------------------------------------')\n", 349 | "\n", 350 | "print('trace of tensor e is:')\n", 351 | "print(tensor_e.trace())\n", 352 | "print('-------------------------------------')\n", 353 | "\n", 354 | "print('det of tensor e is:')\n", 355 | "print(tensor_e.det())\n", 356 | "print('-------------------------------------')\n", 357 | "\n", 358 | "print('dev of tensor e is:')\n", 359 | "tensor_e_dev = tensor_e.dev()\n", 360 | "print(tensor_e_dev)\n", 361 | "print('-------------------------------------')\n", 362 | "\n", 363 | "print('1st col of tensor e is:')\n", 364 | "print(tensor_e.ithCol(0))\n", 365 | "print('-------------------------------------')\n", 366 | "\n", 367 | "print('2nd row of tensor e is:')\n", 368 | "print(tensor_e.ithRow(1))\n", 369 | "print('-------------------------------------')\n", 370 | "\n", 371 | "print('double contraction between tensor e and its dev part:')\n", 372 | "print(tensor_e.doublecontraction(tensor_e_dev))" 373 | ] 374 | } 375 | ], 376 | "metadata": { 377 | "kernelspec": { 378 | "display_name": "Python 3 (ipykernel)", 379 | "language": "python", 380 | "name": "python3" 381 | }, 382 | "language_info": { 383 | "codemirror_mode": { 384 | "name": "ipython", 385 | "version": 3 386 | }, 387 | "file_extension": ".py", 388 | "mimetype": "text/x-python", 389 | "name": "python", 390 | "nbconvert_exporter": "python", 391 | "pygments_lexer": "ipython3", 392 | "version": "3.10.4" 393 | } 394 | }, 395 | "nbformat": 4, 396 | "nbformat_minor": 5 397 | } 398 | -------------------------------------------------------------------------------- /Demo-Vector.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "id": "d4d0e451-bf79-4b09-a28c-ee03b20665e8", 6 | "metadata": {}, 7 | "source": [ 8 | "# Demo notebook for vector manipulation\n", 9 | "\n", 10 | "- [x] standard operators between vector/vector and vector/scalar\n", 11 | "\n", 12 | "\n", 13 | "Author: Yang Bai @ M3 Group\n", 14 | "\n", 15 | "Date : 2022.06.30\n", 16 | "\n", 17 | "QQ group: 628204857" 18 | ] 19 | }, 20 | { 21 | "cell_type": "code", 22 | "execution_count": 1, 23 | "id": "1cc93fce-f73f-40c6-9958-245c60a33e04", 24 | "metadata": {}, 25 | "outputs": [], 26 | "source": [ 27 | "# before we start, we need to import the vector class\n", 28 | "from FEToy.mathutils.vector import vector" 29 | ] 30 | }, 31 | { 32 | "cell_type": "markdown", 33 | "id": "33c45150-9e5a-45a8-8326-10d7772d5e2a", 34 | "metadata": {}, 35 | "source": [ 36 | "## $+$ operator\n", 37 | "\n", 38 | "$+$ operator can be used for the calculation in $\\vec{a}+\\vec{b}$ and $\\vec{a}+b$\n", 39 | "\n", 40 | "where\n", 41 | "\n", 42 | "$\\vec{a}+\\vec{b}=\\vec{c},\\mathrm{with}~c_{i}=a_{i}+b_{i}$\n", 43 | "\n", 44 | "and\n", 45 | "\n", 46 | "$\\vec{a}+b=\\vec{c},\\mathrm{with}~c_{i}=a_{i}+b$" 47 | ] 48 | }, 49 | { 50 | "cell_type": "code", 51 | "execution_count": 2, 52 | "id": "fc8be95c-7e12-466b-a594-47bcb6830334", 53 | "metadata": {}, 54 | "outputs": [ 55 | { 56 | "name": "stdout", 57 | "output_type": "stream", 58 | "text": [ 59 | "vector a,vector components are: 0.00000e+00, 0.00000e+00 0.00000e+00\n", 60 | "vector b,vector components are: 1.00000e+00, 1.00000e+00 1.00000e+00\n", 61 | "-------------------------------------\n", 62 | "( 1.00000e+00, 1.00000e+00, 1.00000e+00)\n", 63 | "-------------------------------------\n", 64 | "( 2.00000e+00, 2.00000e+00, 2.00000e+00)\n", 65 | "( 3.00000e+00, 3.00000e+00, 3.00000e+00)\n", 66 | "( 9.59581e-01, 9.90323e-02, 6.48479e-01)\n", 67 | "-------------------------------------\n", 68 | "( 9.59581e-01, 2.00000e+00, 6.48479e-01)\n", 69 | "( 9.59581e-01, 2.00000e+00, 5.00000e+00)\n" 70 | ] 71 | } 72 | ], 73 | "source": [ 74 | "vec_a = vector(dim=3)\n", 75 | "vec_a.print('vector a')\n", 76 | "\n", 77 | "vec_b = vector(dim=3,value=1.0)\n", 78 | "vec_b.print('vector b')\n", 79 | "\n", 80 | "print('-------------------------------------')\n", 81 | "\n", 82 | "vec_c = vec_a+vec_b\n", 83 | "print(vec_c)\n", 84 | "\n", 85 | "print('-------------------------------------')\n", 86 | "\n", 87 | "vec_d = vec_c + 1.0\n", 88 | "print(vec_d)\n", 89 | "vec_e = vector(3,0.0)\n", 90 | "vec_e[:] = vec_d[:]\n", 91 | "vec_e.setToRandom()\n", 92 | "print(vec_d+1.0)\n", 93 | "print(vec_e)\n", 94 | "\n", 95 | "print('-------------------------------------')\n", 96 | "\n", 97 | "# for element access\n", 98 | "vec_e [1]=2.0\n", 99 | "print(vec_e)\n", 100 | "\n", 101 | "vec_e [2]=5.0\n", 102 | "print(vec_e)" 103 | ] 104 | }, 105 | { 106 | "cell_type": "markdown", 107 | "id": "4fbaa859-8ff2-44a5-8c2b-a24ec8fbe8ea", 108 | "metadata": {}, 109 | "source": [ 110 | "## $-$ operator\n", 111 | "\n", 112 | "$-$ operator can be used for the calculation in $\\vec{a}-\\vec{b}$ and $\\vec{a}-b$\n", 113 | "\n", 114 | "where\n", 115 | "\n", 116 | "$\\vec{a}-\\vec{b}=\\vec{c},\\mathrm{with}~c_{i}=a_{i}-b_{i}$\n", 117 | "\n", 118 | "and\n", 119 | "\n", 120 | "$\\vec{a}-b=\\vec{c},\\mathrm{with}~c_{i}=a_{i}-b$" 121 | ] 122 | }, 123 | { 124 | "cell_type": "code", 125 | "execution_count": 3, 126 | "id": "398f1f27-552a-4f02-b326-1a9cedbe193d", 127 | "metadata": {}, 128 | "outputs": [ 129 | { 130 | "name": "stdout", 131 | "output_type": "stream", 132 | "text": [ 133 | "( 0.00000e+00, 0.00000e+00, 0.00000e+00)\n", 134 | "( 1.00000e+00, 1.00000e+00, 1.00000e+00)\n", 135 | "( -1.00000e+00, -1.00000e+00, -1.00000e+00)\n", 136 | "-------------------------------------\n", 137 | "vector c,vector components are: -1.00000e+00, 2.00000e+00 -1.00000e+00\n", 138 | "( -2.00000e+00, 1.00000e+00, -2.00000e+00)\n", 139 | "-------------------------------------\n", 140 | "( -6.00000e+00, -3.00000e+00, -6.00000e+00)\n" 141 | ] 142 | } 143 | ], 144 | "source": [ 145 | "vec_c = vec_a-vec_b\n", 146 | "\n", 147 | "print(vec_a)\n", 148 | "print(vec_b)\n", 149 | "print(vec_c)\n", 150 | "\n", 151 | "print('-------------------------------------')\n", 152 | "\n", 153 | "vec_c[1]=2.0\n", 154 | "vec_c.print('vector c')\n", 155 | "print(vec_c-1.0)\n", 156 | "\n", 157 | "print('-------------------------------------')\n", 158 | "\n", 159 | "vec_d = vec_c-5.0\n", 160 | "print(vec_d)" 161 | ] 162 | }, 163 | { 164 | "cell_type": "markdown", 165 | "id": "95a5b74f-7f30-4e74-9fe1-46739aafb389", 166 | "metadata": {}, 167 | "source": [ 168 | "## $*$ operator\n", 169 | "\n", 170 | "$*$ operator can be used for the calculation in $\\vec{a}*\\vec{b}$ and $\\vec{a}*b$\n", 171 | "\n", 172 | "where\n", 173 | "\n", 174 | "$\\vec{a}\\cdot\\vec{b}=\\sum_{i}a_{i}b_{i}$\n", 175 | "\n", 176 | "and\n", 177 | "\n", 178 | "$\\vec{a}\\cdot b=\\vec{c},\\mathrm{with}~c_{i}=a_{i}*b$" 179 | ] 180 | }, 181 | { 182 | "cell_type": "code", 183 | "execution_count": 4, 184 | "id": "6d372727-c4b9-4e63-ad43-980b9de40264", 185 | "metadata": {}, 186 | "outputs": [ 187 | { 188 | "name": "stdout", 189 | "output_type": "stream", 190 | "text": [ 191 | "( 1.00000e+00, 1.00000e+00, 1.00000e+00)\n", 192 | "( 2.00000e+00, 2.00000e+00, 2.00000e+00)\n", 193 | "-------------------------------------\n", 194 | "6.0\n", 195 | "( 2.00000e+00, 2.00000e+00, 2.00000e+00)\n", 196 | "6.0\n", 197 | "-------------------------------------\n", 198 | "vector c, vector components are: 1.51993e-02, 5.58038e-01\n", 199 | "vector d, vector components are: 5.68158e-01, 1.60769e-01\n", 200 | "vector c*2.0, vector components are: 3.03986e-02, 1.11608e+00\n", 201 | "vector-c X vector-d is 0.0983510915112724\n", 202 | "vector-c X vector-d(manul) is 0.0983510915112724\n" 203 | ] 204 | } 205 | ], 206 | "source": [ 207 | "vec_a[:] = 1.0\n", 208 | "vec_b[:] = 2.0\n", 209 | "\n", 210 | "print(vec_a)\n", 211 | "print(vec_b)\n", 212 | "\n", 213 | "print('-------------------------------------')\n", 214 | "\n", 215 | "scalar = vec_a*vec_b\n", 216 | "print(scalar)\n", 217 | "print(vec_a*2.0)\n", 218 | "print(vec_a*vec_b)\n", 219 | "\n", 220 | "print('-------------------------------------')\n", 221 | "\n", 222 | "vec_c = vector() # default dim=2\n", 223 | "vec_d = vector() # default dim=2, value=0\n", 224 | "\n", 225 | "vec_c.setToRandom()\n", 226 | "vec_d.setToRandom()\n", 227 | "\n", 228 | "vec_c.print('vector c')\n", 229 | "vec_d.print('vector d')\n", 230 | "(vec_c*2.0).print('vector c*2.0')\n", 231 | "print('vector-c X vector-d is',vec_c*vec_d)\n", 232 | "print('vector-c X vector-d(manul) is',vec_c[0]*vec_d[0]+vec_c[1]*vec_d[1])" 233 | ] 234 | }, 235 | { 236 | "cell_type": "markdown", 237 | "id": "c887bd7a-2efa-4c51-9f1e-0c822f41e4e4", 238 | "metadata": {}, 239 | "source": [ 240 | "## $/$ operator\n", 241 | "\n", 242 | "$/$ operator can only be used for the calculation in $\\vec{a}/b$\n", 243 | "\n", 244 | "where\n", 245 | "\n", 246 | "\n", 247 | "$\\vec{a}/ b=\\vec{c},\\mathrm{with}~c_{i}=a_{i}/b$" 248 | ] 249 | }, 250 | { 251 | "cell_type": "code", 252 | "execution_count": 5, 253 | "id": "b0f61a66-276b-4d84-8221-b42b412ae049", 254 | "metadata": {}, 255 | "outputs": [ 256 | { 257 | "name": "stdout", 258 | "output_type": "stream", 259 | "text": [ 260 | "vector c, vector components are: 5.00000e+00, 5.00000e+00\n", 261 | "( 1.00000e+00, 1.00000e+00)\n" 262 | ] 263 | } 264 | ], 265 | "source": [ 266 | "vec_c[:]=5.0 # slice operator\n", 267 | "\n", 268 | "vec_c.print('vector c')\n", 269 | "print(vec_c/5.0)" 270 | ] 271 | } 272 | ], 273 | "metadata": { 274 | "kernelspec": { 275 | "display_name": "Python 3 (ipykernel)", 276 | "language": "python", 277 | "name": "python3" 278 | }, 279 | "language_info": { 280 | "codemirror_mode": { 281 | "name": "ipython", 282 | "version": 3 283 | }, 284 | "file_extension": ".py", 285 | "mimetype": "text/x-python", 286 | "name": "python", 287 | "nbconvert_exporter": "python", 288 | "pygments_lexer": "ipython3", 289 | "version": "3.10.4" 290 | } 291 | }, 292 | "nbformat": 4, 293 | "nbformat_minor": 5 294 | } 295 | -------------------------------------------------------------------------------- /FEToy/__init__.py: -------------------------------------------------------------------------------- 1 | __copyright__= "Copyright (C) 2021-present by Yang Bai" 2 | 3 | __license__ = """ 4 | Permission is hereby granted, free of charge, to any person obtaining a copy 5 | of this software and associated documentation files (the "Software"), to deal 6 | in the Software without restriction, including without limitation the rights 7 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | copies of the Software, and to permit persons to whom the Software is 9 | furnished to do so, subject to the following conditions: 10 | The above copyright notice and this permission notice shall be included in 11 | all copies or substantial portions of the Software. 12 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 13 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 14 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 15 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 16 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 17 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 18 | THE SOFTWARE. 19 | """ 20 | 21 | 22 | __all__=["mesh","fe","math","postprocess"] 23 | -------------------------------------------------------------------------------- /FEToy/fe/__init__.py: -------------------------------------------------------------------------------- 1 | __author__="Yang Bai" 2 | __copyright__= "Copyright (C) 2021-present by M3 Group" 3 | __version__ = "1.0" 4 | __maintainer__ = "Yang Bai" 5 | __email__ = "yangbai90@outlook.com" 6 | __status__ = "development" 7 | __date__ = "Dec 19, 2021" 8 | 9 | __all__=["gaussrule","shapefun"] 10 | -------------------------------------------------------------------------------- /FEToy/fe/gaussrule.py: -------------------------------------------------------------------------------- 1 | __author__="Yang Bai" 2 | __copyright__= "Copyright (C) 2021-present by M3 Group" 3 | __version__ = "1.0" 4 | __maintainer__ = "Yang Bai" 5 | __email__ = "yangbai90@outlook.com" 6 | __status__ = "development" 7 | __date__ = "Dec 21, 2021" 8 | 9 | 10 | import numpy as np 11 | import matplotlib.pyplot as plt 12 | import sys 13 | 14 | class gausspoint1d: 15 | def __init__(self,ngp=1): 16 | """ 17 | Initialize the gauss point class 18 | 19 | Parameters 20 | ---------- 21 | ngp : int 22 | the number of gauss points 23 | """ 24 | self.ngp=ngp 25 | self.gpcoords=np.zeros((ngp,2)) # 0-> weight, 1-> xi 26 | 27 | def setnum(self,num): 28 | """ 29 | Set up the gauss point number 30 | 31 | Parameters 32 | ---------- 33 | num : int 34 | the number of gauss point one want to generate 35 | """ 36 | self.ngp=num 37 | def getgausspointsnumber(self): 38 | """ 39 | Get the number of gauss points 40 | """ 41 | return self.ngp 42 | def creategausspoint(self): 43 | """ 44 | Generate the gauss points 45 | """ 46 | self.gpcoords=np.zeros((self.ngp,2)) 47 | if self.ngp==1: 48 | self.gpcoords[0,0]=2.0 49 | self.gpcoords[0,1]=0.0 50 | elif self.ngp==2: 51 | self.gpcoords[0,0]=1.0 52 | self.gpcoords[0,1]=-np.sqrt(1.0/3.0) 53 | 54 | self.gpcoords[1,0]=1.0 55 | self.gpcoords[1,1]= np.sqrt(1.0/3.0) 56 | elif self.ngp==3: 57 | self.gpcoords[0,0]=5.0/9.0 58 | self.gpcoords[0,1]=-np.sqrt(3.0/5.0) 59 | 60 | self.gpcoords[1,0]=8.0/9.0 61 | self.gpcoords[1,1]= 0.0 62 | 63 | self.gpcoords[2,0]=5.0/9.0 64 | self.gpcoords[2,1]= np.sqrt(3.0/5.0) 65 | elif self.ngp==4: 66 | t=np.sqrt(4.8) 67 | w=1.0/3.0/t 68 | 69 | self.gpcoords[0,1]=-np.sqrt((3.0+t)/7.0) 70 | self.gpcoords[1,1]=-np.sqrt((3.0-t)/7.0) 71 | self.gpcoords[2,1]= np.sqrt((3.0-t)/7.0) 72 | self.gpcoords[3,1]= np.sqrt((3.0+t)/7.0) 73 | 74 | self.gpcoords[0,0]=0.5-w 75 | self.gpcoords[1,0]=0.5+w 76 | self.gpcoords[2,0]=0.5+w 77 | self.gpcoords[3,0]=0.5-w 78 | elif self.ngp==5: 79 | t=np.sqrt(1120.0) 80 | self.gpcoords[1-1, 1] = -np.sqrt((70.0 + t) / 126.0) 81 | self.gpcoords[2-1, 1] = -np.sqrt((70.0 - t) / 126.0) 82 | self.gpcoords[3-1, 1] = 0.0 83 | self.gpcoords[4-1, 1] = np.sqrt((70.0 - t) / 126.0) 84 | self.gpcoords[5-1, 1] = np.sqrt((70.0 + t) / 126.0) 85 | 86 | self.gpcoords[1-1, 0] = (21.0 * t + 117.60) / (t * (70.0 + t)) 87 | self.gpcoords[2-1, 0] = (21.0 * t - 117.60) / (t * (70.0 - t)) 88 | self.gpcoords[3-1, 0] = 2.0 * (1.0 - self.gpcoords[1-1, 0] -self.gpcoords[2-1, 0]) 89 | self.gpcoords[4-1, 0] = self.gpcoords[2-1, 0] 90 | self.gpcoords[5-1, 0] = self.gpcoords[1-1, 0] 91 | else: 92 | sys.exit("unsuported gauss point number in 1d case") 93 | def update(self): 94 | """ 95 | Update/re-generate the gauss point number 96 | """ 97 | self.creategausspoint() 98 | def print(self): 99 | for i in range(self.ngp): 100 | str='%d-th gauss point: xi=%14.5e, weight=%14.5e'%(i+1,self.gpcoords[i,1],self.gpcoords[i,0]) 101 | print(str) 102 | def getIthweight(self,i): 103 | """ 104 | Get the i-th gauss point's weight 105 | 106 | Parameters 107 | ---------- 108 | i : int 109 | the i-th gauss point 110 | """ 111 | if i>self.ngp: 112 | sys.exit('%d is out of 1d gauss points range !'%(i)) 113 | return self.gpcoords[i,0] 114 | def getIthcoord(self,i): 115 | """ 116 | Get the i-th gauss point's coordinate 117 | """ 118 | if i>self.ngp: 119 | sys.exit('%d is out of 1d gauss points range !'%(i)) 120 | return self.gpcoords[i,1] 121 | def plot(self): 122 | plt.figure() 123 | plt.plot(self.gpcoords[:,1],self.gpcoords[:,0],'k*') 124 | plt.xlabel(r'$\xi$',fontsize=16) 125 | plt.ylabel(r'$w$',fontsize=16) 126 | plt.xticks(fontsize=12) 127 | plt.yticks(fontsize=12) 128 | ########################################################################### 129 | class gausspoint2d: 130 | def __init__(self,ngp): 131 | """ 132 | Initialize the 2d gauss points 133 | """ 134 | self.ngp=ngp 135 | self.ngp2=ngp*ngp 136 | self.gpcoords=np.zeros((self.ngp2,3)) # 0->weight,1->xi,2->eta 137 | def setnum(self,ngp): 138 | """ 139 | Get the i-th gauss point's weight 140 | 141 | Parameters 142 | ---------- 143 | ngp : int 144 | the number of gauss point in each direction 145 | """ 146 | self.ngp=ngp 147 | self.ngp2=ngp*ngp 148 | if ngp>5: 149 | sys.exit("unsupported gauss points number in 2d case!") 150 | def creategausspoint(self): 151 | """ 152 | Generate the 2d gauss points 153 | """ 154 | if self.ngp>5: 155 | sys.exit('can not generate 2d gauss point, unsupported gauss point number (must <=5) !!!') 156 | self.gpcoords=np.zeros((self.ngp2,3)) 157 | gp1d=gausspoint1d(self.ngp) 158 | gp1d.creategausspoint() 159 | k=0 160 | for i in range(self.ngp): 161 | for j in range(self.ngp): 162 | self.gpcoords[k,0]=gp1d.gpcoords[i,0]*gp1d.gpcoords[j,0] 163 | self.gpcoords[k,1]=gp1d.gpcoords[i,1] 164 | self.gpcoords[k,2]=gp1d.gpcoords[j,1] 165 | k+=1 166 | def print(self): 167 | for i in range(self.ngp2): 168 | str='%d-th gauss point: xi=%14.5e, eta=%14.5e, weight=%14.5e'%(i+1,self.gpcoords[i,1],self.gpcoords[i,2],self.gpcoords[i,0]) 169 | print(str) 170 | def update(self): 171 | """ 172 | Update the gauss points 173 | """ 174 | self.creategausspoint() 175 | def getgausspointsnumber(self): 176 | return self.ngp2 177 | def getIthcoords(self,i): 178 | """ 179 | get the i-th gauss point's coordinate 180 | 181 | Parameters 182 | ---------- 183 | i : int 184 | the node index 185 | """ 186 | if i>self.ngp2: 187 | sys.exit('i=%d is out of 2d gauss point range'%(i)) 188 | return self.gpcoords[i,1],self.gpcoords[i,2] 189 | def getIthweight(self,i): 190 | """ 191 | get the i-th gauss point's weight 192 | 193 | Parameters 194 | ---------- 195 | i : int 196 | the node index 197 | """ 198 | if i>self.ngp: 199 | sys.exit('i=%d is out of 2d gauss point range'%(i)) 200 | return self.gpcoords[i,0] 201 | def plot(self): 202 | fig=plt.figure() 203 | plt.clf() 204 | ax=fig.add_subplot(projection='3d') 205 | ax.scatter(self.gpcoords[:,1],self.gpcoords[:,2],self.gpcoords[:,0]) 206 | ax.set_xlabel(r'$\xi$',fontsize=14) 207 | ax.set_ylabel(r'$\eta$',fontsize=14) 208 | ax.set_zlabel(r'$w$',fontsize=14) 209 | -------------------------------------------------------------------------------- /FEToy/fe/shapefun.py: -------------------------------------------------------------------------------- 1 | __author__="Yang Bai" 2 | __copyright__= "Copyright (C) 2021-present by M3 Group" 3 | __version__ = "1.0" 4 | __maintainer__ = "Yang Bai" 5 | __email__ = "yangbai90@outlook.com" 6 | __status__ = "development" 7 | __date__ = "Dec 25, 2021" 8 | 9 | import numpy as np 10 | import matplotlib.pyplot as plt 11 | import sys 12 | 13 | 14 | class shape1d: 15 | def __init__(self,meshtype='edge2'): 16 | """ 17 | Parameters 18 | ---------- 19 | meshtype : string 20 | the type of mesh, the default one is 'edge2' 21 | """ 22 | self.nNodes=2 23 | self.shape_val=np.zeros(self.nNodes) 24 | self.shape_grad=np.zeros(self.nNodes) 25 | self.jacdet=1.0 26 | self.meshtype=meshtype 27 | self.setmeshtype(meshtype) 28 | self.update() 29 | def setmeshtype(self,meshtype): 30 | """ 31 | set up the mesh type for shape1d class 32 | 33 | Parameters 34 | ---------- 35 | meshtype : string 36 | the type of mesh you plan to use, it could be edge2, edge3, edge4 37 | """ 38 | if 'edge2' in meshtype: 39 | self.nNodes=2 40 | self.meshtype='edge2' 41 | elif 'edge3' in meshtype: 42 | self.nNodes=3 43 | self.meshtype='edge3' 44 | elif 'edge4' in meshtype: 45 | self.nNodes=4 46 | self.meshtype='edge4' 47 | else: 48 | sys.exit('unsupported mesh type in shape1d->setmeshtype') 49 | def update(self): 50 | """ 51 | update the shape function 52 | """ 53 | self.shape_val=np.zeros(self.nNodes) 54 | self.shape_grad=np.zeros(self.nNodes) 55 | self.jacdet=1.0 56 | def getshpnumber(self): 57 | return self.nNodes 58 | ########################################################### 59 | def calc(self,xi,x,flag=True): 60 | """ 61 | calculate the shape function value and its derivative w.r.t xi(local) or x(global) 62 | 63 | Parameters 64 | ---------- 65 | xi : scalar 66 | the local cooridinate 67 | x : vector 68 | the global coordinate 69 | flag : boolean 70 | True for the calculation based on global coordinate, otherwise, it use the local one 71 | """ 72 | if self.nNodes==2: 73 | self.shape_val[1-1] = 0.5*(1.0-xi) 74 | self.shape_grad[1-1]=-0.5 75 | 76 | self.shape_val[2-1] = 0.5*(1.0+xi) 77 | self.shape_grad[2-1]= 0.5 78 | elif self.nNodes==3: 79 | self.shape_val[1-1] =0.5*xi*(xi-1.0) 80 | self.shape_grad[1-1]=0.5*(2*xi-1) 81 | 82 | self.shape_val[2-1] =-(xi+1.0)*(xi-1.0) 83 | self.shape_grad[2-1]=-2.0*xi 84 | 85 | self.shape_val[3-1] =0.5*xi*(xi+1.0) 86 | self.shape_grad[3-1]=0.5*(2.0*xi+1.0) 87 | elif self.nNodes==4: 88 | self.shape_val[1-1]=-(3.0*xi+1.0)*(3.0*xi-1.0)*( xi-1.0)/16.0 89 | self.shape_grad[1-1]=-27.0*xi*xi/16.0+9.0*xi/8.0+ 1.0/16.0 90 | 91 | self.shape_val[2-1]=(3.0*xi+3.0)*(3.0*xi-1.0)*(3.0*xi-3.0)/16.0 92 | self.shape_grad[2-1]= 81.0*xi*xi/16.0-9.0*xi/8.0-27.0/16.0 93 | 94 | self.shape_val[3-1]=-(3.0*xi+3.0)*(3.0*xi+1.0)*(3.0*xi-3.0)/16.0 95 | self.shape_grad[3-1]=-81.0*xi*xi/16.0-9.0*xi/8.0+27.0/16.0 96 | 97 | self.shape_val[4-1]=( xi+1.0)*(3.0*xi+1.0)*(3.0*xi-1.0)/16.0 98 | self.shape_grad[4-1]=27.0*xi*xi/16.0+9.0*xi/8.0- 1.0/16.0 99 | else: 100 | sys.exit('unsupported shape function calculation in shape1d') 101 | 102 | dxdxi=0.0 103 | for i in range(self.nNodes): 104 | dxdxi+=self.shape_grad[i]*x[i] 105 | 106 | self.jacdet=np.abs(dxdxi) 107 | if self.jacdet<1.0e-16: 108 | sys.exit('error: you have one singular 1d mesh !!!') 109 | if flag==True: 110 | for i in range(self.nNodes): 111 | self.shape_grad[i]=self.shape_grad[i]/self.jacdet 112 | 113 | return self.shape_val,self.shape_grad,self.jacdet 114 | def plot(self): 115 | """ 116 | plot the 1d shape function 117 | """ 118 | n=50 119 | xivec=np.linspace(-1.0,1.0,n) 120 | x=np.linspace(0.0,1.0,self.nNodes) 121 | shp=np.zeros((self.nNodes,n)) 122 | for i in range(n): 123 | xi=xivec[i] 124 | shp[:,i],shpgrad,jac=self.calc(xi,x) 125 | plt.figure() 126 | for i in range(self.nNodes): 127 | plt.plot(xivec,shp[i,:],label=r'$N_{%d}$'%(i+1)) 128 | plt.legend(fontsize=13) 129 | plt.xlabel(r'$\xi$',fontsize=15) 130 | plt.ylabel('shape function value',fontsize=15) 131 | ################################################################################# 132 | class shape2d: 133 | def __init__(self,meshtype='quad4'): 134 | """ 135 | Initialize the 2d shape function class 136 | """ 137 | self.nNodes=4 138 | self.shape_val=np.zeros(self.nNodes) 139 | self.shape_grad=np.zeros((self.nNodes,2)) 140 | self.jacdet=1.0 141 | self.meshtype=meshtype 142 | self.setmeshtype(meshtype) 143 | self.update() 144 | def setmeshtype(self,meshtype): 145 | """ 146 | set up the mesh type for shape2d class 147 | 148 | Parameters 149 | ---------- 150 | meshtype: string 151 | the type of mesh, it should be quad4,quad9 152 | """ 153 | if 'quad4' in meshtype: 154 | self.nNodes=4 155 | self.meshtype='quad4' 156 | elif 'quad9' in meshtype: 157 | self.nNodes=9 158 | self.meshtype='quad9' 159 | else: 160 | sys.exit('unsupported mesh type in shape2d->setmeshtype') 161 | def update(self): 162 | """ 163 | update the shape function vector 164 | """ 165 | self.shape_val=np.zeros(self.nNodes) 166 | self.shape_grad=np.zeros((self.nNodes,2)) 167 | self.jacdet=1.0 168 | def getshpnumber(self): 169 | """ 170 | return the number of shape function 171 | """ 172 | return self.nNodes 173 | ########################################################### 174 | def calc(self,xi,eta,x,y,flag=True): 175 | """ 176 | calculate the shape function value and its derivative w.r.t xi(local) or x(global) 177 | 178 | Parameters 179 | ---------- 180 | xi : double 181 | the local cooridinate 182 | eta : double 183 | the local cooridinate 184 | x : double 185 | the global coordinate 186 | y : double 187 | the global coordinate 188 | flag : boolean 189 | True for the calculation based on global coordinate, otherwise, it use the local one 190 | """ 191 | if self.nNodes==4: 192 | self.shape_val[0]=(1.0-xi)*(1.0-eta)/4.0 193 | self.shape_val[1]=(1.0+xi)*(1.0-eta)/4.0 194 | self.shape_val[2]=(1.0+xi)*(1.0+eta)/4.0 195 | self.shape_val[3]=(1.0-xi)*(1.0+eta)/4.0 196 | 197 | self.shape_grad[0,1-1]= (eta-1.0)/4.0 198 | self.shape_grad[0,2-1]= (xi -1.0)/4.0 199 | 200 | self.shape_grad[1,1-1]= (1.0-eta)/4.0 201 | self.shape_grad[1,2-1]=-(1.0+xi )/4.0 202 | 203 | self.shape_grad[2,1-1]= (1.0+eta)/4.0 204 | self.shape_grad[2,2-1]= (1.0+xi )/4.0 205 | 206 | self.shape_grad[3,1-1]=-(1.0+eta)/4.0 207 | self.shape_grad[3,2-1]= (1.0-xi )/4.0 208 | elif self.nNodes==9: 209 | self.shape_val[0]=(xi*xi-xi )*(eta*eta-eta)/4.0 210 | self.shape_val[1]=(xi*xi+xi )*(eta*eta-eta)/4.0 211 | self.shape_val[2]=(xi*xi+xi )*(eta*eta+eta)/4.0 212 | self.shape_val[3]=(xi*xi-xi )*(eta*eta+eta)/4.0 213 | self.shape_val[4]=(1.0-xi*xi)*(eta*eta-eta)/2.0 214 | self.shape_val[5]=(xi*xi+xi )*(1.0-eta*eta)/2.0 215 | self.shape_val[6]=(1.0-xi*xi)*(eta*eta+eta)/2.0 216 | self.shape_val[7]=(xi*xi-xi )*(1.0-eta*eta)/2.0 217 | self.shape_val[8]=(1.0-xi*xi)*(1.0-eta*eta) 218 | 219 | self.shape_grad[0,1-1]=(2.0*xi-1.0)*(eta*eta-eta)/4.0 220 | self.shape_grad[0,2-1]=(xi*xi-xi )*(2.0*eta-1.0)/4.0 221 | 222 | self.shape_grad[1,1-1]=(2.0*xi+1.0)*(eta*eta-eta)/4.0 223 | self.shape_grad[1,2-1]=(xi*xi+xi )*(2.0*eta-1.0)/4.0 224 | 225 | self.shape_grad[2,1-1]=(2.0*xi+1.0)*(eta*eta+eta)/4.0 226 | self.shape_grad[2,2-1]=(xi*xi+xi )*(2.0*eta+1.0)/4.0 227 | 228 | self.shape_grad[3,1-1]=(2.0*xi-1.0)*(eta*eta+eta)/4.0 229 | self.shape_grad[3,2-1]=(xi*xi-xi )*(2.0*eta+1.0)/4.0 230 | 231 | self.shape_grad[4,1-1]=-xi*(eta*eta-eta) 232 | self.shape_grad[4,2-1]=(1.0-xi*xi )*(2.0*eta-1.0)/2.0 233 | 234 | self.shape_grad[5,1-1]=(2.0*xi+1.0)*(1.0-eta*eta)/2.0 235 | self.shape_grad[5,2-1]=-(xi*xi+xi )*eta 236 | 237 | self.shape_grad[6,1-1]=-xi*(eta*eta+eta) 238 | self.shape_grad[6,2-1]=(1.0-xi*xi )*(2.0*eta+1.0)/2.0 239 | 240 | self.shape_grad[7,1-1]=(2.0*xi-1.0)*(1.0-eta*eta)/2.0 241 | self.shape_grad[7,2-1]=-(xi*xi-xi )*eta 242 | 243 | self.shape_grad[8,1-1]=-2.0*xi*(1.0-eta*eta) 244 | self.shape_grad[8,2-1]=-2.0*eta*(1.0-xi*xi) 245 | else: 246 | sys.exit('unsupported shape function calculation in shape1d') 247 | 248 | dxdxi=0.0;dxdeta=0.0 249 | dydxi=0.0;dydeta=0.0 250 | for i in range(self.nNodes): 251 | dxdxi +=self.shape_grad[i,0]*x[i] 252 | dxdeta+=self.shape_grad[i,1]*x[i] 253 | 254 | dydxi +=self.shape_grad[i,0]*y[i] 255 | dydeta+=self.shape_grad[i,1]*y[i] 256 | 257 | jac=np.array([[dxdxi,dydxi],[dxdeta,dydeta]]) 258 | self.jacdet=np.linalg.det(jac) 259 | xjac=np.linalg.inv(jac) 260 | if self.jacdet<1.0e-16: 261 | sys.exit('error: you have one singular 1d mesh !!!') 262 | if flag==True: 263 | for i in range(self.nNodes): 264 | temp1=self.shape_grad[i,1-1]*xjac[0,0]+self.shape_grad[i,2-1]*xjac[0,1] 265 | temp2=self.shape_grad[i,1-1]*xjac[1,0]+self.shape_grad[i,2-1]*xjac[1,1] 266 | self.shape_grad[i,1-1]=temp1 267 | self.shape_grad[i,2-1]=temp2 268 | 269 | return self.shape_val,self.shape_grad,self.jacdet 270 | def plot(self): 271 | """ 272 | plot the 2d shape function 273 | """ 274 | n=20 275 | xivec=np.linspace(-1.0,1.0,n) 276 | etavec=np.linspace(-1.0,1.0,n) 277 | x=np.array([0.0,1.0,1.0,0.0, 0.5,1.0,0.5,0.0,0.5]) 278 | y=np.array([0.0,0.0,1.0,1.0, 0.0,0.5,1.0,0.5,0.5]) 279 | shp=np.zeros((self.nNodes,n,n)) 280 | X,Y=np.meshgrid(xivec,etavec) 281 | for i in range(n): 282 | for j in range(n): 283 | xi=xivec[i];eta=etavec[j] 284 | shp[:,i,j],shpgrad,jac=self.calc(xi,eta,x,y) 285 | fig=plt.figure() 286 | ax = fig.add_subplot(111, projection="3d") 287 | for i in range(self.nNodes): 288 | Z=shp[i,:,:] 289 | ax.plot_surface(X,Y,Z,label=r'$N_{%d}$'%(i+1)) 290 | #ax.contour(X, Y, Z, 10, lw=3, cmap="autumn_r", linestyles="solid", offset=-1) 291 | #ax.contour(X, Y, Z, 10, lw=3, colors="k", linestyles="solid") 292 | ax.set_xlabel(r'$\xi$',fontsize=15) 293 | ax.set_ylabel(r'$\eta$',fontsize=15) 294 | 295 | -------------------------------------------------------------------------------- /FEToy/mathutils/__init__.py: -------------------------------------------------------------------------------- 1 | __copyright__= "Copyright (C) 2021-present by Yang Bai" 2 | 3 | __license__ = """ 4 | Permission is hereby granted, free of charge, to any person obtaining a copy 5 | of this software and associated documentation files (the "Software"), to deal 6 | in the Software without restriction, including without limitation the rights 7 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | copies of the Software, and to permit persons to whom the Software is 9 | furnished to do so, subject to the following conditions: 10 | The above copyright notice and this permission notice shall be included in 11 | all copies or substantial portions of the Software. 12 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 13 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 14 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 15 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 16 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 17 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 18 | THE SOFTWARE. 19 | """ 20 | 21 | 22 | __all__=["vector","tensor"] 23 | -------------------------------------------------------------------------------- /FEToy/mathutils/tensor.py: -------------------------------------------------------------------------------- 1 | __author__="Yang Bai" 2 | __copyright__= "Copyright (C) 2022-present by M3 Group" 3 | __version__ = "1.0" 4 | __maintainer__ = "Yang Bai" 5 | __email__ = "yangbai90@outlook.com" 6 | __status__ = "development" 7 | __date__ = "July 30, 2022" 8 | 9 | import imp 10 | import numpy as np 11 | import matplotlib.pyplot as plt 12 | import sys 13 | # from vector import vector 14 | from FEToy.mathutils.vector import vector 15 | 16 | class rank2tensor: 17 | def __init__(self,dim=2,value=0.0): 18 | """ 19 | Initialize the tensor 20 | 21 | Parameters 22 | ---------- 23 | dim : int 24 | the dimension or size of current tensor 25 | value : double 26 | default value for current tensor 27 | """ 28 | self.dim=dim 29 | if dim>3: 30 | sys.exit('error: dim=%d is invalid for a rank-2 tensor'%(dim)) 31 | self.vals=np.zeros((self.dim,self.dim)) 32 | self.vals[:,:]=1.0*value 33 | def setToRandom(self): 34 | """ 35 | Set current rank-2 tensor to random value 36 | 37 | Parameters 38 | ---------- 39 | """ 40 | for i in range(self.dim): 41 | for j in range(self.dim): 42 | self.vals[i,j]=np.random.rand() 43 | def setToIdentity(self): 44 | """ 45 | Set current rank-2 tensor to identity tensor 46 | 47 | Parameters 48 | ---------- 49 | """ 50 | for i in range(self.dim): 51 | for j in range(self.dim): 52 | self.vals[i,j]=1.0*(i==j) 53 | def det(self): 54 | """ 55 | get the determinte of current tensor 56 | 57 | Parameters 58 | ---------- 59 | """ 60 | return np.linalg.det(self.vals) 61 | def trace(self): 62 | """ 63 | get the trace of current tensor 64 | 65 | Parameters 66 | ---------- 67 | """ 68 | if self.dim==2: 69 | return self.vals[0,0]+self.vals[1,1] 70 | else: 71 | return self.vals[0,0]+self.vals[1,1]+self.vals[2,2] 72 | def dev(self): 73 | """ 74 | get the deviatoric part of current tensor 75 | 76 | Parameters 77 | ---------- 78 | """ 79 | temp=rank2tensor(self.dim) 80 | tr=self.trace() 81 | for i in range(self.dim): 82 | for j in range(self.dim): 83 | temp.vals[i,j]=self.vals[i,j]-(1.0/3.0)*tr*(i==j) 84 | return temp 85 | def doublecontraction(self,a): 86 | """ 87 | get the double contraction result between two tensor 88 | 89 | Parameters 90 | ---------- 91 | a : rank2 tensor 92 | right hand side tensor 93 | """ 94 | if isinstance(a,rank2tensor): 95 | if self.dim==a.dim: 96 | sum=0.0 97 | for i in range(self.dim): 98 | for j in range(self.dim): 99 | sum+=self.vals[i,j]*a.vals[i,j] 100 | return sum 101 | else: 102 | sys.exit('error: the right hand side value should be either a tensor or a scalar for \'-\' operator') 103 | else: 104 | sys.exit('error: double contraction should be used for two tensors !!!') 105 | def ithRow(self,i): 106 | """ 107 | get i-th row of current tensor 108 | 109 | Parameters 110 | ---------- 111 | i : integer 112 | row index 113 | """ 114 | temp=vector(self.dim) 115 | for j in range(self.dim): 116 | temp.vals[j]=self.vals[i,j] 117 | return temp 118 | def ithCol(self,i): 119 | """ 120 | get i-th column of current tensor 121 | 122 | Parameters 123 | ---------- 124 | i : integer 125 | col index 126 | """ 127 | temp=vector(self.dim) 128 | for j in range(self.dim): 129 | temp.vals[j]=self.vals[j,i] 130 | return temp 131 | def print(self,str=None): 132 | """ 133 | Print the rank-2 tensor 134 | 135 | Parameters 136 | ---------- 137 | str : string 138 | the content to be printed 139 | """ 140 | if self.dim==2: 141 | if str is None: 142 | print('tensor components are: |%14.5e, %14.5e|'%(self.vals[0,0],self.vals[0,1])) 143 | print(' |%14.5e, %14.5e|'%(self.vals[1,0],self.vals[1,1])) 144 | else: 145 | print(str+', tensor components are: ') 146 | print(' |%14.5e, %14.5e|'%(self.vals[0,0],self.vals[0,1])) 147 | print(' |%14.5e, %14.5e|'%(self.vals[1,0],self.vals[1,1])) 148 | else: 149 | if str is None: 150 | print('tensor components are: |%14.5e, %14.5e %14.5e|'%(self.vals[0,0],self.vals[0,1],self.vals[0,2])) 151 | print(' |%14.5e, %14.5e %14.5e|'%(self.vals[1,0],self.vals[1,1],self.vals[1,2])) 152 | print(' |%14.5e, %14.5e %14.5e|'%(self.vals[2,0],self.vals[2,1],self.vals[2,2])) 153 | else: 154 | print(str+', tensor components are: ') 155 | print(' |%14.5e, %14.5e %14.5e|'%(self.vals[0,0],self.vals[0,1],self.vals[0,2])) 156 | print(' |%14.5e, %14.5e %14.5e|'%(self.vals[1,0],self.vals[1,1],self.vals[1,2])) 157 | print(' |%14.5e, %14.5e %14.5e|'%(self.vals[2,0],self.vals[2,1],self.vals[2,2])) 158 | ################################################# 159 | ### for operators 160 | ################################################# 161 | def __getitem__(self,pos): 162 | """ 163 | Get the i,j-th element of current vector 164 | 165 | Parameters 166 | ---------- 167 | pos : int 168 | the integer index pair 169 | """ 170 | i,j=pos 171 | if isinstance(i,int) and isinstance(j,int): 172 | if i<0 or i>self.dim-1: 173 | sys.exit('i=%d is out of range for a tensor element access !!!'%(i)) 174 | if j<0 or j>self.dim-1: 175 | sys.exit('j=%d is out of range for a tensor element access !!!'%(j)) 176 | return self.vals[i,j] 177 | def __setitem__(self,pos,val): 178 | """ 179 | Set the i,j-th element of current tensor 180 | 181 | Parameters 182 | ---------- 183 | pos : int pair 184 | the integer index pair 185 | val : float 186 | the float scalar 187 | """ 188 | i,j=pos 189 | if isinstance(i,int) and isinstance(j,int): 190 | if i<0 or i>self.dim-1: 191 | sys.exit('i=%d is out of range for a tensor element access !!!'%(i)) 192 | if j<0 or j>self.dim-1: 193 | sys.exit('j=%d is out of range for a tensor element access !!!'%(i)) 194 | self.vals[i,j]=val 195 | def __str__(self): 196 | """ 197 | Print() method overload 198 | ---------- 199 | """ 200 | if self.dim==2: 201 | return "(%14.5e, %14.5e)\n(%14.5e, %14.5e)"%(self.vals[0,0],self.vals[0,1], 202 | self.vals[1,0],self.vals[1,1]) 203 | else: 204 | return "(%14.5e, %14.5e, %14.5e)\n(%14.5e, %14.5e, %14.5e)\n(%14.5e, %14.5e, %14.5e)"%(self.vals[0,0],self.vals[0,1],self.vals[0,2], 205 | self.vals[1,0],self.vals[1,1],self.vals[1,2], 206 | self.vals[2,0],self.vals[2,1],self.vals[2,2]) 207 | # for '+' 208 | def __add__(self,a): 209 | """ 210 | + operator overload 211 | 212 | Parameters 213 | ---------- 214 | a : tensor or scalar 215 | right hand side value 216 | """ 217 | if isinstance(a,rank2tensor): 218 | if self.dim==a.dim: 219 | temp=rank2tensor(self.dim,0.0) 220 | for i in range(self.dim): 221 | for j in range(self.dim): 222 | temp.vals[i,j]=self.vals[i,j]+a.vals[i,j] 223 | return temp 224 | else: 225 | sys.exit('error: \'+\' operator must be applied to two tensors with the same size !!!') 226 | else: 227 | if isinstance(a,int) or isinstance(a,float): 228 | # for scalar 229 | temp=rank2tensor(self.dim,0.0) 230 | for i in range(self.dim): 231 | for j in range(self.dim): 232 | temp.vals[i,j]=self.vals[i,j]+a 233 | return temp 234 | else: 235 | sys.exit('error: the right hand side value should be either a tensor or a scalar for \'+\' operator') 236 | # for '-' 237 | def __sub__(self,a): 238 | """ 239 | - operator overload 240 | 241 | Parameters 242 | ---------- 243 | a : temspr or scalar 244 | right hand side value 245 | """ 246 | if isinstance(a,rank2tensor): 247 | if self.dim==a.dim: 248 | temp=rank2tensor(self.dim,0.0) 249 | for i in range(self.dim): 250 | for j in range(self.dim): 251 | temp.vals[i,j]=self.vals[i,j]-a.vals[i,j] 252 | return temp 253 | else: 254 | sys.exit('error: \'-\' operator must be applied to two tensors with the same size !!!') 255 | else: 256 | if isinstance(a,int) or isinstance(a,float): 257 | # for scalar 258 | temp=rank2tensor(self.dim,0.0) 259 | for i in range(self.dim): 260 | for j in range(self.dim): 261 | temp.vals[i,j]=self.vals[i,j]-a 262 | return temp 263 | else: 264 | sys.exit('error: the right hand side value should be either a tensor or a scalar for \'-\' operator') 265 | # for '*' 266 | def __mul__(self,a): 267 | """ 268 | * operator overload 269 | 270 | Parameters 271 | ---------- 272 | a : tensor or scalar 273 | right hand side value 274 | """ 275 | if isinstance(a,rank2tensor): 276 | if self.dim==a.dim: 277 | temp=rank2tensor(self.dim,0.0) 278 | for i in range(self.dim): 279 | for j in range(self.dim): 280 | for k in range(self.dim): 281 | temp.vals[i,j]+=self.vals[i,k]*a.vals[k,j] 282 | return temp 283 | else: 284 | sys.exit('error: \'*\' operator must be applied to two tensors with the same size !!!') 285 | elif isinstance(a,vector): 286 | if self.dim==a.dim: 287 | temp=vector(self.dim,0.0) 288 | for i in range(self.dim): 289 | for j in range(self.dim): 290 | temp.vals[i]+=self.vals[i,j]*a.vals[j] 291 | return temp 292 | else: 293 | sys.exit('error: \'*\' operator must be applied to tensor/vector with the same size !!!') 294 | else: 295 | if isinstance(a,int) or isinstance(a,float): 296 | # for scalar 297 | temp=rank2tensor(self.dim,0.0) 298 | for i in range(self.dim): 299 | for j in range(self.dim): 300 | temp.vals[i,j]=self.vals[i,j]*a 301 | return temp 302 | else: 303 | sys.exit('error: the right hand side value should be either a tensor or a scalar for \'*\' operator') 304 | # for '/' 305 | def __truediv__(self,a): 306 | """ 307 | / operator overload 308 | 309 | Parameters 310 | ---------- 311 | a : scalar 312 | right hand side value 313 | """ 314 | if isinstance(a,rank2tensor): 315 | sys.exit('error: \'/\' operator can only be applied to a scalar !!!') 316 | else: 317 | if isinstance(a,int) or isinstance(a,float): 318 | # for scalar 319 | if np.abs(a)<1.0e-15: 320 | sys.exit('error: \'/\' operator can only be applied to a non-singular scalar !!!') 321 | temp=rank2tensor(self.dim,0.0) 322 | for i in range(self.dim): 323 | for j in range(self.dim): 324 | temp.vals[i,j]=self.vals[i,j]/a 325 | return temp 326 | else: 327 | sys.exit('error: the right hand side value should be either a tensor or a scalar for \'/\' operator') 328 | 329 | -------------------------------------------------------------------------------- /FEToy/mathutils/vector.py: -------------------------------------------------------------------------------- 1 | __author__="Yang Bai" 2 | __copyright__= "Copyright (C) 2022-present by M3 Group" 3 | __version__ = "1.0" 4 | __maintainer__ = "Yang Bai" 5 | __email__ = "yangbai90@outlook.com" 6 | __status__ = "development" 7 | __date__ = "June 30, 2022" 8 | 9 | import numpy as np 10 | import matplotlib.pyplot as plt 11 | import sys 12 | 13 | 14 | class vector: 15 | def __init__(self,dim=2,value=0.0): 16 | """ 17 | Initialize the vector 18 | 19 | Parameters 20 | ---------- 21 | dim : int 22 | the dimension or size of current vector 23 | value : double 24 | default value for current vector 25 | """ 26 | self.dim=dim 27 | if dim>3: 28 | sys.exit('error: dim=%d is invalid for a vector'%(dim)) 29 | self.vals=np.zeros(self.dim) 30 | self.vals[:]=1.0*value 31 | def setToRandom(self): 32 | """ 33 | Set current vector to random value 34 | 35 | Parameters 36 | ---------- 37 | """ 38 | for i in range(self.dim): 39 | self.vals[i]=np.random.rand() 40 | def print(self,str=None): 41 | """ 42 | Print the vector 43 | 44 | Parameters 45 | ---------- 46 | str : string 47 | the content to be printed 48 | """ 49 | if self.dim==2: 50 | if str is None: 51 | print('vector components are: %14.5e, %14.5e'%(self.vals[0],self.vals[1])) 52 | else: 53 | print(str+', vector components are: %14.5e, %14.5e'%(self.vals[0],self.vals[1])) 54 | else: 55 | if str is None: 56 | print('vector components are: %14.5e, %14.5e %14.5e'%(self.vals[0],self.vals[1],self.vals[2])) 57 | else: 58 | print(str+',vector components are: %14.5e, %14.5e %14.5e'%(self.vals[0],self.vals[1],self.vals[2])) 59 | ################################################# 60 | ### for operators 61 | ################################################# 62 | def __getitem__(self,i): 63 | """ 64 | Get the i-th element of current vector 65 | 66 | Parameters 67 | ---------- 68 | i : int 69 | the integer index 70 | """ 71 | if isinstance(i,int): 72 | if i<0 or i>self.dim-1: 73 | sys.exit('i=%d is out of range for a vector element access !!!'%(i)) 74 | return self.vals[i] 75 | elif isinstance(i,slice): 76 | if i.start is not None and i.stop is not None: 77 | m = max(i.start, i.stop) 78 | return [self[ii] for ii in xrange(*i.indices(m+1))] 79 | else: 80 | return self.vals[:] 81 | # if np.min(i)<1 or np.max(i)>self.dim: 82 | # sys.exit(i+' is out of range for a vector element access !!!') 83 | # return self.vals[i-1] 84 | def __setitem__(self,i,val): 85 | """ 86 | Set the i-th element of current vector 87 | 88 | Parameters 89 | ---------- 90 | i : int 91 | the integer index 92 | val : float 93 | the float scalar 94 | """ 95 | if isinstance(i,int): 96 | if i<0 or i>self.dim-1: 97 | sys.exit('i=%d is out of range for a vector element access !!!'%(i)) 98 | self.vals[i]=val 99 | elif isinstance(i,slice): 100 | if i.start is not None and i.stop is not None: 101 | m = max(i.start, i.stop) 102 | for ii in xrange(*i.indices(m+1)): 103 | self.vals[ii]=val 104 | else: 105 | self.vals[:]=val 106 | def __str__(self): 107 | """ 108 | Print() method overload 109 | ---------- 110 | """ 111 | if self.dim==2: 112 | return "(%14.5e, %14.5e)"%(self.vals[0],self.vals[1]) 113 | else: 114 | return "(%14.5e, %14.5e, %14.5e)"%(self.vals[0],self.vals[1],self.vals[2]) 115 | # for '+' 116 | def __add__(self,a): 117 | """ 118 | + operator overload 119 | 120 | Parameters 121 | ---------- 122 | a : vector or scalar 123 | right hand side value 124 | """ 125 | if isinstance(a,vector): 126 | if self.dim==a.dim: 127 | temp=vector(self.dim,0.0) 128 | temp.vals[:]=self.vals[:]+a.vals[:] 129 | return temp 130 | else: 131 | sys.exit('error: \'+\' operator must be applied to two vector with the same size !!!') 132 | else: 133 | if isinstance(a,int) or isinstance(a,float): 134 | # for scalar 135 | temp=vector(self.dim,0.0) 136 | temp.vals[:]=self.vals[:]+a 137 | return temp 138 | else: 139 | sys.exit('error: the right hand side value should be either a vector or a scalar for \'+\' operator') 140 | # for '-' 141 | def __sub__(self,a): 142 | """ 143 | - operator overload 144 | 145 | Parameters 146 | ---------- 147 | a : vector or scalar 148 | right hand side value 149 | """ 150 | if isinstance(a,vector): 151 | if self.dim==a.dim: 152 | temp=vector(self.dim,0.0) 153 | temp.vals[:]=self.vals[:]-a.vals[:] 154 | return temp 155 | else: 156 | sys.exit('error: \'-\' operator must be applied to two vector with the same size !!!') 157 | else: 158 | if isinstance(a,int) or isinstance(a,float): 159 | # for scalar 160 | temp=vector(self.dim,0.0) 161 | temp.vals[:]=self.vals[:]-a 162 | return temp 163 | else: 164 | sys.exit('error: the right hand side value should be either a vector or a scalar for \'-\' operator') 165 | # for '*' 166 | def __mul__(self,a): 167 | """ 168 | * operator overload 169 | 170 | Parameters 171 | ---------- 172 | a : vector or scalar 173 | right hand side value 174 | """ 175 | if isinstance(a,vector): 176 | if self.dim==a.dim: 177 | if self.dim==2: 178 | sum=self.vals[0]*a.vals[0]\ 179 | +self.vals[1]*a.vals[1] 180 | else: 181 | sum=self.vals[0]*a.vals[0]\ 182 | +self.vals[1]*a.vals[1]\ 183 | +self.vals[2]*a.vals[2] 184 | return sum 185 | else: 186 | sys.exit('error: \'*\' operator must be applied to two vector with the same size !!!') 187 | else: 188 | if isinstance(a,int) or isinstance(a,float): 189 | # for scalar 190 | temp=vector(self.dim,0.0) 191 | temp.vals[:]=self.vals[:]*a 192 | return temp 193 | else: 194 | sys.exit('error: the right hand side value should be either a vector or a scalar for \'*\' operator') 195 | # for '/' 196 | def __truediv__(self,a): 197 | """ 198 | / operator overload 199 | 200 | Parameters 201 | ---------- 202 | a : scalar 203 | right hand side value 204 | """ 205 | if isinstance(a,vector): 206 | sys.exit('error: \'/\' operator can only be applied to a scalar !!!') 207 | else: 208 | if isinstance(a,int) or isinstance(a,float): 209 | # for scalar 210 | if np.abs(a)<1.0e-15: 211 | sys.exit('error: \'/\' operator can only be applied to a non-singular scalar !!!') 212 | temp=vector(self.dim,0.0) 213 | temp.vals[:]=self.vals[:]/a 214 | return temp 215 | else: 216 | sys.exit('error: the right hand side value should be either a vector or a scalar for \'/\' operator') 217 | 218 | -------------------------------------------------------------------------------- /FEToy/mesh/__init__.py: -------------------------------------------------------------------------------- 1 | __copyright__= "Copyright (C) 2021-present by Yang Bai" 2 | 3 | __license__ = """ 4 | Permission is hereby granted, free of charge, to any person obtaining a copy 5 | of this software and associated documentation files (the "Software"), to deal 6 | in the Software without restriction, including without limitation the rights 7 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | copies of the Software, and to permit persons to whom the Software is 9 | furnished to do so, subject to the following conditions: 10 | The above copyright notice and this permission notice shall be included in 11 | all copies or substantial portions of the Software. 12 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 13 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 14 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 15 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 16 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 17 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 18 | THE SOFTWARE. 19 | """ 20 | 21 | 22 | __all__=["lagrange1dmesh","lagrange2dmesh"] 23 | -------------------------------------------------------------------------------- /FEToy/mesh/lagrange1dmesh.py: -------------------------------------------------------------------------------- 1 | __author__="Yang Bai" 2 | __copyright__= "Copyright (C) 2021-present by M3 Group" 3 | __version__ = "1.0" 4 | __maintainer__ = "Yang Bai" 5 | __email__ = "yangbai90@outlook.com" 6 | __status__ = "development" 7 | __date__ = "Dec 19, 2021" 8 | 9 | import numpy as np 10 | import matplotlib.pyplot as plt 11 | import sys 12 | 13 | class mesh1d: 14 | def __init__(self,xmin=0.0,xmax=1.0,nx=5,meshtype='edge2'): 15 | """ 16 | Initialize the mesh class 17 | 18 | Parameters 19 | ---------- 20 | xmin : double 21 | the left point along x-axis 22 | xmax : double 23 | the right point along x-axis 24 | nx : int 25 | the number of element 26 | meshtype : string 27 | the type of mesh you want to generated, it should be edge2, edge3, edge4 28 | """ 29 | self.meshtype=meshtype 30 | self.dim=1 31 | self.xmin=xmin 32 | self.xmax=xmax 33 | self.nx=nx 34 | self.order=1 35 | self.nodes=0 36 | self.nodesperelement=2 37 | self.elements=0 38 | self.meshtype=meshtype 39 | self.vtkcelltype=3 40 | self.setmeshtype(meshtype) 41 | def setnx(self,nx): 42 | """ 43 | set up the number of element we want to generate 44 | 45 | Parameters 46 | ---------- 47 | nx : int 48 | the number of element 49 | """ 50 | self.nx=nx 51 | def setmeshtype(self,meshtype): 52 | """ 53 | set up the type of mesh we want to use 54 | 55 | Parameters 56 | ---------- 57 | meshtype : string 58 | the type name should be edge2,edge3,edge4 59 | """ 60 | if 'edge2' in meshtype: 61 | self.order=1 62 | self.nodesperelement=2 63 | self.vtkcelltype=3 64 | elif 'edge3' in meshtype: 65 | self.order=2 66 | self.nodesperelement=3 67 | self.vtkcelltype=4 68 | elif 'edge4' in meshtype: 69 | self.order=3 70 | self.nodesperelement=4 71 | self.vtkcelltype=4 72 | else: 73 | sys.exit('sorry, unsuported 1d mesh type in FEToy!') 74 | def setdomainsize(self,xmin,xmax): 75 | """ 76 | set up the domain size 77 | 78 | Parameters 79 | ---------- 80 | xmin : double 81 | the left point of x-axis 82 | xmax : double 83 | the right point of x-axis 84 | """ 85 | self.xmin=xmin 86 | self.xmax=xmax 87 | def update(self): 88 | self.createmesh() 89 | def createmesh(self): 90 | """ 91 | generate the lagrange mesh in 1d case 92 | """ 93 | self.elements=self.nx 94 | self.nodes=self.elements*self.order+1 95 | dx=(self.xmax-self.xmin)/(self.nodes-1) 96 | self.nodecoords=np.zeros(self.nodes) 97 | for i in range(self.nodes): 98 | self.nodecoords[i]=self.xmin+i*dx 99 | 100 | self.elementconn=np.zeros((self.elements,self.nodesperelement),dtype=np.int16) 101 | for e in range(self.elements): 102 | for j in range(self.nodesperelement): 103 | self.elementconn[e,j]=e*self.order+j 104 | 105 | # for the boundary elements, in 1d case, it is just simple point 106 | self.bcelements={'left':1-1,'right':self.nodes-1} 107 | self.bcnodeids={'left':1-1,'right':self.nodes-1} 108 | ##################################################### 109 | def printnodes(self): 110 | """ 111 | print the node's coordinates 112 | """ 113 | print('*** node coordinates of the mesh (total nodes=%d, nodes per element=%d)'%(self.nodes,self.nodesperelement)) 114 | for i in range(self.nodes): 115 | str='%6d-th node: x=%14.6e'%(i+1,self.nodecoords[i]) 116 | print(str) 117 | def printelements(self): 118 | """ 119 | print the element connectivity info 120 | """ 121 | print('*** element connectivity information(bulk elements=%d)'%(self.elements)) 122 | for e in range(self.elements): 123 | str='%6d-th element'%(e+1) 124 | for i in range(self.nodesperelement): 125 | str+='%5d '%(self.elementconn[e,i]) 126 | print(str) 127 | ###################################################### 128 | def plotmesh(self,withnode=False,withnodeid=False): 129 | """ 130 | plot the 1d mesh 131 | 132 | Parameters 133 | ---------- 134 | withnode : boolean 135 | True to show the node 136 | withnodeid : boolean 137 | True to show the node id 138 | """ 139 | y=np.zeros(self.nodes) 140 | plt.figure() 141 | plt.plot(self.nodecoords,y,'k') 142 | if withnode: 143 | plt.plot(self.nodecoords,y,'r*') 144 | if withnodeid: 145 | for i in range(self.nodes): 146 | x=self.nodecoords[i] 147 | plt.text(x,0.0,'%d'%(i+1)) 148 | plt.xlabel('X',fontsize=14) 149 | plt.ylabel('Y',fontsize=14) 150 | -------------------------------------------------------------------------------- /FEToy/mesh/lagrange2dmesh.py: -------------------------------------------------------------------------------- 1 | __author__="Yang Bai" 2 | __copyright__= "Copyright (C) 2021-present by M3 Group" 3 | __version__ = "1.0" 4 | __maintainer__ = "Yang Bai" 5 | __email__ = "yangbai90@outlook.com" 6 | __status__ = "development" 7 | __date__ = "Dec 19, 2021" 8 | 9 | import numpy as np 10 | import matplotlib.pyplot as plt 11 | import sys 12 | 13 | class mesh2d: 14 | def __init__(self,xmin=0.0,xmax=1.0,ymin=0.0,ymax=1.0,nx=5,ny=5,meshtype='quad4'): 15 | """ 16 | Initialize the mesh class 17 | 18 | Parameters 19 | ---------- 20 | xmin : double 21 | the left point along x-axis 22 | xmax : double 23 | the right point along x-axis 24 | ymin : double 25 | the bottom point along y-axis 26 | ymax : double 27 | the top point along y-axis 28 | nx : int 29 | the number of element in x direction 30 | ny : int 31 | the number of element in y direction 32 | meshtype : string 33 | the type of mesh you want to generated, it should be quad4, edge8, edge9 34 | """ 35 | self.meshtype=meshtype 36 | self.dim=2 37 | self.xmin=xmin 38 | self.xmax=xmax 39 | self.ymin=ymin 40 | self.ymax=ymax 41 | self.nx=nx 42 | self.ny=ny 43 | self.order=1 44 | self.nodes=0 45 | self.nodesperelement=4 46 | self.elements=0 47 | self.meshtype=meshtype 48 | self.vtkcelltype=9 49 | self.setmeshtype(meshtype) 50 | def setnx(self,nx): 51 | """ 52 | set up the number of element we want to generate along x direction 53 | 54 | Parameters 55 | ---------- 56 | nx : int 57 | nx: the number of element 58 | """ 59 | self.nx=nx 60 | def setny(self,ny): 61 | """ 62 | set up the number of element we want to generate along y direction 63 | 64 | Parameters 65 | ---------- 66 | ny : int 67 | the number of element 68 | """ 69 | self.ny=ny 70 | def setmeshtype(self,meshtype): 71 | """ 72 | set up the type of mesh we want to use 73 | 74 | Parameters 75 | ---------- 76 | meshtype : string 77 | the type name should be qud4,quad8,quad9 78 | """ 79 | if 'quad4' in meshtype: 80 | self.order=1 81 | self.nodesperelement=4 82 | self.meshtype='quad4' 83 | self.vtkcelltype=9 84 | elif 'quad9' in meshtype: 85 | self.order=2 86 | self.nodesperelement=9 87 | self.meshtype='quad9' 88 | self.vtkcelltype=28 89 | else: 90 | sys.exit('sorry, unsuported 2d mesh type in FEToy!') 91 | def setdomainsize(self,xmin,xmax,ymin,ymax): 92 | """ 93 | set up the domain size 94 | 95 | Parameters 96 | ---------- 97 | xmin : double 98 | the left point of x-axis 99 | xmax : double 100 | the right point of x-axis 101 | ymin : double 102 | the bottom point of y-axis 103 | ymax: double 104 | the top point of y-axis 105 | """ 106 | self.xmin=xmin 107 | self.xmax=xmax 108 | self.ymin=ymin 109 | self.ymax=ymax 110 | def update(self): 111 | self.createmesh() 112 | def createmesh(self): 113 | """ 114 | generate the lagrange mesh in 2d case 115 | """ 116 | if 'quad4' in self.meshtype: 117 | self.elements=self.nx*self.ny 118 | self.nodes=(self.nx+1)*(self.ny+1) 119 | dx=(self.xmax-self.xmin)/(self.nx) 120 | dy=(self.ymax-self.ymin)/(self.ny) 121 | self.nodecoords=np.zeros((self.nodes,2)) 122 | 123 | # for bc nodes 124 | leftnodes=np.zeros(self.ny+1,dtype=np.int16) 125 | rightnodes=np.zeros(self.ny+1,dtype=np.int16) 126 | bottomnodes=np.zeros(self.nx+1,dtype=np.int16) 127 | topnodes=np.zeros(self.nx+1,dtype=np.int16) 128 | for j in range(self.ny+1): 129 | for i in range(self.nx+1): 130 | k=j*(self.nx+1)+i 131 | self.nodecoords[k,0]=self.xmin+i*dx 132 | self.nodecoords[k,1]=self.ymin+j*dx 133 | if i==0: 134 | # for left nodes 135 | leftnodes[j]=k 136 | if i==self.nx: 137 | # for right nodes 138 | rightnodes[j]=k 139 | if j==0: 140 | # for bottom nodes 141 | bottomnodes[i]=k 142 | if j==self.ny: 143 | # for top nodes 144 | topnodes[i]=k 145 | self.bcnodeids={'left':leftnodes,'right':rightnodes,'bottom':bottomnodes,'top':topnodes} 146 | ########################################### 147 | self.elementconn=np.zeros((self.elements,self.nodesperelement),dtype=np.int16) 148 | # for bc elements 149 | leftconn=np.zeros((self.ny,2),dtype=np.int16) 150 | rightconn=np.zeros((self.ny,2),dtype=np.int16) 151 | bottomconn=np.zeros((self.nx,2),dtype=np.int16) 152 | topconn=np.zeros((self.nx,2),dtype=np.int16) 153 | for j in range(1,self.ny+1): 154 | for i in range(1,self.nx+1): 155 | e=(j-1)*self.nx+i-1 156 | i1=(j-1)*(self.nx+1)+i 157 | i2=i1+1 158 | i3=i2+self.nx+1 159 | i4=i3-1 160 | self.elementconn[e,0]=i1-1 161 | self.elementconn[e,1]=i2-1 162 | self.elementconn[e,2]=i3-1 163 | self.elementconn[e,3]=i4-1 164 | # 4 +-----+ 3 165 | # | | 166 | # | | 167 | # 1 +-----+ 2 168 | if i==1: 169 | # for left side 170 | leftconn[j-1,0]=i4-1 171 | leftconn[j-1,1]=i1-1 172 | if i==self.nx: 173 | # for right side 174 | rightconn[j-1,0]=i2-1 175 | rightconn[j-1,1]=i3-1 176 | if j==1: 177 | # for bottom side 178 | bottomconn[i-1,0]=i1-1 179 | bottomconn[i-1,1]=i2-1 180 | if j==self.ny: 181 | # for top side 182 | topconn[i-1,0]=i3-1 183 | topconn[i-1,1]=i4-1 184 | self.bcconn={'left':leftconn,'right':rightconn,'bottom':bottomconn,'top':topconn} 185 | elif 'quad9' in self.meshtype: 186 | self.elements=self.nx*self.ny 187 | self.nodes=(2*self.nx+1)*(2*self.ny+1) 188 | dx=(self.xmax-self.xmin)/(2*self.nx) 189 | dy=(self.ymax-self.ymin)/(2*self.ny) 190 | self.nodecoords=np.zeros((self.nodes,2)) 191 | # for bc nodes 192 | leftnodes=np.zeros(2*self.ny+1,dtype=np.int16) 193 | rightnodes=np.zeros(2*self.ny+1,dtype=np.int16) 194 | bottomnodes=np.zeros(2*self.nx+1,dtype=np.int16) 195 | topnodes=np.zeros(2*self.nx+1,dtype=np.int16) 196 | for j in range(2*self.ny+1): 197 | for i in range(2*self.nx+1): 198 | k=j*(2*self.nx+1)+i 199 | self.nodecoords[k,0]=self.xmin+i*dx 200 | self.nodecoords[k,1]=self.ymin+j*dy 201 | if i==0: 202 | # for left nodes 203 | leftnodes[j]=k 204 | if i==2*self.nx: 205 | # for right nodes 206 | rightnodes[j]=k 207 | if j==0: 208 | # for bottom nodes 209 | bottomnodes[i]=k 210 | if j==2*self.ny: 211 | # for top nodes 212 | topnodes[i]=k 213 | self.bcnodeids={'left':leftnodes,'right':rightnodes,'bottom':bottomnodes,'top':topnodes} 214 | ####################################### 215 | self.elementconn=np.zeros((self.elements,self.nodesperelement),dtype=np.int16) 216 | # for bc elements 217 | leftconn=np.zeros((self.ny,3),dtype=np.int16) 218 | rightconn=np.zeros((self.ny,3),dtype=np.int16) 219 | bottomconn=np.zeros((self.nx,3),dtype=np.int16) 220 | topconn=np.zeros((self.nx,3),dtype=np.int16) 221 | for j in range(1,self.ny+1): 222 | for i in range(1,self.nx+1): 223 | e=(j-1)*self.nx+i-1 224 | i1=(j-1)*2*(2*self.nx+1)+2*i-1 225 | i2=i1+2 226 | i3=i2+2*(2*self.nx+1) 227 | i4=i3-2 228 | i5=i1+1 229 | i6=i2+(2*self.nx+1) 230 | i7=i3-1 231 | i8=i1+(2*self.nx+1) 232 | i9=i8+1 233 | self.elementconn[e,1-1]=i1-1 234 | self.elementconn[e,2-1]=i2-1 235 | self.elementconn[e,3-1]=i3-1 236 | self.elementconn[e,4-1]=i4-1 237 | self.elementconn[e,5-1]=i5-1 238 | self.elementconn[e,6-1]=i6-1 239 | self.elementconn[e,7-1]=i7-1 240 | self.elementconn[e,8-1]=i8-1 241 | self.elementconn[e,9-1]=i9-1 242 | ## 243 | # 4 +---7---+ 3 244 | # | | 245 | # 8 + 9 + 6 246 | # | | 247 | # 1 +---5---+ 2 248 | if i==1: 249 | # for left side 250 | leftconn[j-1,0]=i4-1 251 | leftconn[j-1,1]=i8-1 252 | leftconn[j-1,2]=i1-1 253 | if i==self.nx: 254 | # for right side 255 | rightconn[j-1,0]=i2-1 256 | rightconn[j-1,1]=i6-1 257 | rightconn[j-1,2]=i3-1 258 | if j==1: 259 | # for bottom side 260 | bottomconn[i-1,0]=i1-1 261 | bottomconn[i-1,1]=i5-1 262 | bottomconn[i-1,2]=i2-1 263 | if j==self.ny: 264 | # for top side 265 | topconn[i-1,0]=i3-1 266 | topconn[i-1,1]=i7-1 267 | topconn[i-1,2]=i4-1 268 | self.bcconn={'left':leftconn,'right':rightconn,'bottom':bottomconn,'top':topconn} 269 | ##################################################### 270 | def printnodes(self): 271 | """ 272 | print the node's coordinates 273 | """ 274 | print('*** node coordinates of the mesh (total nodes=%d, nodes per element=%d)'%(self.nodes,self.nodesperelement)) 275 | for i in range(self.nodes): 276 | str='%6d-th node: x=%14.6e,y=%14.6e'%(i+1,self.nodecoords[i,0],self.nodecoords[i,1]) 277 | print(str) 278 | def printelements(self): 279 | """ 280 | print the element connectivity info 281 | """ 282 | print('*** element connectivity information(bulk elements=%d)'%(self.elements)) 283 | for e in range(self.elements): 284 | str='%6d-th element :'%(e+1) 285 | for i in range(self.nodesperelement): 286 | str+='%5d '%(self.elementconn[e,i]) 287 | print(str) 288 | ###################################################### 289 | def plotmesh(self,withnode=False,withnodeid=False): 290 | """ 291 | plot the 2d mesh 292 | 293 | Parameters 294 | ---------- 295 | withnode : boolean 296 | True to show the node 297 | withnodeid : boolean 298 | True to show the node id 299 | """ 300 | plt.plot() 301 | for e in range(self.elements): 302 | conn=self.elementconn[e,:] 303 | if 'quad4' in self.meshtype: 304 | conn=np.append(conn,conn[0]) 305 | elif 'quad9' in self.meshtype: 306 | conn=np.array([conn[1-1],conn[5-1],conn[2-1],conn[6-1],conn[3-1],conn[7-1],conn[4-1],conn[8-1],conn[1-1]]) 307 | x=self.nodecoords[conn,0] 308 | y=self.nodecoords[conn,1] 309 | plt.plot(x,y,'k') 310 | if withnode: 311 | plt.plot(self.nodecoords[:,0],self.nodecoords[:,1],'r*') 312 | if withnodeid: 313 | for i in range(self.nodes): 314 | x=self.nodecoords[i,0];y=self.nodecoords[i,1] 315 | str='%d'%(i+1) 316 | plt.text(x,y,str) 317 | plt.xlabel('X',fontsize=14) 318 | plt.ylabel('Y',fontsize=14) 319 | -------------------------------------------------------------------------------- /FEToy/postprocess/PlotResult.py: -------------------------------------------------------------------------------- 1 | __author__="Yang Bai" 2 | __copyright__= "Copyright (C) 2021-present by M3 Group" 3 | __version__ = "1.0" 4 | __maintainer__ = "Yang Bai" 5 | __email__ = "yangbai90@outlook.com" 6 | __status__ = "development" 7 | __date__ = "Jan 23, 2022" 8 | 9 | 10 | import numpy as np 11 | import matplotlib.pyplot as plt 12 | from scipy.interpolate import griddata 13 | #from matplotlib.mlab import griddata 14 | 15 | class Plot2D: 16 | def Contour2D(mesh,sol,savefig=False,figname=''): 17 | fig, ax = plt.subplots(constrained_layout=True) 18 | x,y=mesh.nodecoords[:,0],mesh.nodecoords[:,1] 19 | X,Y=np.meshgrid(x,y) 20 | Z=griddata((x,y),sol,(X,Y),method='linear') 21 | #cs=plt.contourf(X,Y,Z,cmap=plt.cm.hsv,levels=200) 22 | #cs=plt.contourf(X,Y,Z,cmap=plt.cm.viridis,levels=200,antialiased=True,extend='both') 23 | cs=plt.tricontourf(x,y,sol,levels=20) 24 | fig.colorbar(cs) 25 | ax.axis('equal') 26 | 27 | if savefig: 28 | if len(figname)>4: 29 | fig.savefig(figname,dpi=300,bbox_inches='tight') 30 | print('save results to ',figname) 31 | else: 32 | fig.savefig('result.jpg',dpi=300,bbox_inches='tight') 33 | print('save result to result.jpg') 34 | def Contour2DDeform(mesh,disp,sol,savefig=False,figname=''): 35 | fig, ax = plt.subplots(constrained_layout=True) 36 | x=np.zeros(mesh.nodes) 37 | y=np.zeros(mesh.nodes) 38 | for i in range(mesh.nodes): 39 | x[i]=mesh.nodecoords[i,0]+disp[2*i] 40 | y[i]=mesh.nodecoords[i,1]+disp[2*i+1] 41 | #cs=plt.contourf(X,Y,Z,cmap=plt.cm.hsv,levels=200) 42 | #cs=plt.contourf(X,Y,Z,cmap=plt.cm.viridis,levels=200,antialiased=True,extend='both') 43 | X,Y=np.meshgrid(x,y) 44 | Z=griddata((x,y),sol,(X,Y),method='linear') 45 | #cs=plt.contourf(X,Y,Z,cmap=plt.cm.viridis,levels=200,antialiased=True,extend='both') 46 | cs=plt.tricontourf(x,y,sol,levels=20) 47 | #cs=plt.contourf(x,y,sol,200) 48 | fig.colorbar(cs) 49 | ax.axis('equal') 50 | 51 | if savefig: 52 | if len(figname)>4: 53 | fig.savefig(figname,dpi=300,bbox_inches='tight') 54 | print('save results to ',figname) 55 | else: 56 | fig.savefig('result.jpg',dpi=300,bbox_inches='tight') 57 | print('save result to result.jpg') 58 | -------------------------------------------------------------------------------- /FEToy/postprocess/Result.py: -------------------------------------------------------------------------------- 1 | __author__="Yang Bai" 2 | __copyright__= "Copyright (C) 2021-present by M3 Group" 3 | __version__ = "1.0" 4 | __maintainer__ = "Yang Bai" 5 | __email__ = "yangbai90@outlook.com" 6 | __status__ = "development" 7 | __date__ = "April 15, 2022" 8 | 9 | 10 | import numpy as np 11 | import sys 12 | 13 | class ResultIO: 14 | def __init__(self,prefixname=''): 15 | """ 16 | Initialize the ResultIO class 17 | 18 | Parameters 19 | ---------- 20 | prefixname : string 21 | the name of the output file(only prefix) 22 | """ 23 | self.prefixname=prefixname 24 | self.filename='' 25 | if len(prefixname)<1: 26 | self.prefixname='myresult' 27 | def save2csv(self,mesh,solution,varnamelist,step): 28 | """ 29 | Save results to csv file 30 | 31 | Parameters 32 | ---------- 33 | mesh : mesh class 34 | the mesh class 35 | solution : numpy array 36 | the solution of each node 37 | varnamelist : list 38 | the name list of your dofs 39 | step : int 40 | the current time step 41 | """ 42 | if not mesh.nodes*len(varnamelist)==len(solution): 43 | sys.exit('your varnamelist length*nodes does not match with your solution!') 44 | filename='%06d.csv'%(step) 45 | self.filename=self.prefixname+'-'+filename 46 | inp=open(self.filename,'w+') 47 | str='' 48 | if mesh.dim==1: 49 | str='x' 50 | elif mesh.dim==2: 51 | str='x,y' 52 | for i in varnamelist: 53 | str+=','+i 54 | str+='\n' 55 | inp.write(str) 56 | nodedofs=len(varnamelist) 57 | for i in range(mesh.nodes): 58 | if mesh.dim==1: 59 | x=mesh.nodecoords[i] 60 | str='%14.5e'%(x) 61 | elif mesh.dim==2: 62 | x=mesh.nodecoords[i,0] 63 | y=mesh.nodecoords[i,1] 64 | str='%14.5e,%14.5e'%(x,y) 65 | for j in range(nodedofs): 66 | iInd=i*nodedofs+j 67 | str+=',%14.5e'%(solution[iInd]) 68 | str+='\n' 69 | inp.write(str) 70 | 71 | inp.close() 72 | print('write result to %s'%(self.filename)) 73 | 74 | def save2vtu(self,mesh,solution,varnamelist,step): 75 | """ 76 | Save results to vtu file 77 | 78 | Parameters 79 | ---------- 80 | mesh : mesh class 81 | the mesh class 82 | solution : numpy array 83 | the solution of each node 84 | varnamelist : list 85 | the name list of your dofs 86 | step : int 87 | the current time step 88 | """ 89 | if not mesh.nodes*len(varnamelist)==len(solution): 90 | sys.exit('your varnamelist length*nodes dose not match with your solution!') 91 | filename='%06d.vtu'%(step) 92 | self.filename=self.prefixname+'-'+filename 93 | inp=open(self.filename,'w+') 94 | vtkcelltype=mesh.vtkcelltype 95 | 96 | inp.write("\n") 97 | inp.write("\n") 98 | inp.write("\n") 99 | 100 | str="\n"%(mesh.nodes,mesh.elements) 101 | inp.write(str) 102 | inp.write("\n") 103 | inp.write("\n") 104 | 105 | # write out nodal coordinates 106 | for i in range(mesh.nodes): 107 | x=0.0;y=0.0 108 | if mesh.dim==1: 109 | x=mesh.nodecoords[i] 110 | elif mesh.dim==2: 111 | x=mesh.nodecoords[i,0] 112 | y=mesh.nodecoords[i,1] 113 | str='%14.6e %14.6e 0.0\n'%(x,y) 114 | inp.write(str) 115 | inp.write("\n") 116 | inp.write("\n") 117 | 118 | # write out cell info 119 | inp.write("\n") 120 | inp.write("\n") 121 | for e in range(mesh.elements): 122 | str='' 123 | for i in range(mesh.nodesperelement): 124 | str+='%6d '%(mesh.elementconn[e,i]) 125 | str+='\n' 126 | inp.write(str) 127 | inp.write("\n") 128 | 129 | inp.write("\n") 130 | offset=0 131 | for e in range(mesh.elements): 132 | offset+=mesh.nodesperelement 133 | str='%6d\n'%(offset) 134 | inp.write(str) 135 | inp.write("\n") 136 | 137 | # for cell type 138 | inp.write("\n") 139 | for e in range(mesh.elements): 140 | str='%6d\n'%(vtkcelltype) 141 | inp.write(str) 142 | inp.write("\n") 143 | inp.write("\n") 144 | 145 | str="\n" 150 | inp.write(str) 151 | 152 | for j in range(len(varnamelist)): 153 | dofname=varnamelist[j] 154 | str="\n" 155 | inp.write(str) 156 | for i in range(mesh.nodes): 157 | iInd=i*len(varnamelist)+j 158 | str='%14.6e\n'%(solution[iInd]) 159 | inp.write(str) 160 | inp.write("\n\n") 161 | inp.write("\n") 162 | 163 | inp.write("\n") 164 | inp.write("\n") 165 | inp.write("") 166 | 167 | inp.close() 168 | 169 | print('write result to %s'%(self.filename)) -------------------------------------------------------------------------------- /FEToy/postprocess/__init__.py: -------------------------------------------------------------------------------- 1 | __copyright__= "Copyright (C) 2021-present by Yang Bai" 2 | 3 | __license__ = """ 4 | Permission is hereby granted, free of charge, to any person obtaining a copy 5 | of this software and associated documentation files (the "Software"), to deal 6 | in the Software without restriction, including without limitation the rights 7 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | copies of the Software, and to permit persons to whom the Software is 9 | furnished to do so, subject to the following conditions: 10 | The above copyright notice and this permission notice shall be included in 11 | all copies or substantial portions of the Software. 12 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 13 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 14 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 15 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 16 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 17 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 18 | THE SOFTWARE. 19 | """ 20 | 21 | 22 | __all__=["PlotResult","Result"] 23 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | This repository offers several Jupyter notebooks for basic finite element programming. 2 | 3 | 4 | # Installation 5 | Before we start, make sure you have installed: 6 | 7 | - [x] numpy 8 | - [x] matplotlib 9 | - [x] jupyter-lab 10 | 11 | the you can download or git clone the repository via: 12 | ``` 13 | https://github.com/M3Group/FEMLecture.git 14 | ``` 15 | afterwards, set up your `PATHONPATH` as follows: 16 | ``` 17 | export FEToy=*your-path-to-FEMLecture/FEToy 18 | export $PATHONPATH=$PATHONPATH:$FEToy 19 | ``` 20 | then everything is done, open your jupyter notebook and enjoy :-) : 21 | ``` 22 | jupyter-lab 23 | ``` 24 | 25 | # Lecture 26 | The video lecture in chinese can be found here [FEM-Lecture](https://space.bilibili.com/100272198/channel/detail?cid=201531) 27 | 28 | # Discussion 29 | The discussion can be done in the following QQ group: 30 | ``` 31 | 628204857 32 | ``` 33 | -------------------------------------------------------------------------------- /result.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MatMechLab/FEMLecture/6fd9965cc9522fc98d5bde59dadd4d46f709c9ba/result.jpg --------------------------------------------------------------------------------