2208 lines
62 KiB
Plaintext
2208 lines
62 KiB
Plaintext
{
|
|
"cells": [
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"# Space, Time, Motion, Reference Frames and Reminder on vectors and other mathematical quantities\n",
|
|
"\n",
|
|
"Our studies will start with the motion of different types of objects\n",
|
|
"such as a falling ball, a runner, a bicycle etc etc. It means that an\n",
|
|
"object's position in space varies with time.\n",
|
|
"In order to study such systems we need to define\n",
|
|
"* choice of origin\n",
|
|
"\n",
|
|
"* choice of the direction of the axes\n",
|
|
"\n",
|
|
"* choice of positive direction (left-handed or right-handed system of reference)\n",
|
|
"\n",
|
|
"* choice of units and dimensions\n",
|
|
"\n",
|
|
"These choices lead to some important questions such as\n",
|
|
"\n",
|
|
"* is the physics of a system independent of the origin of the axes?\n",
|
|
"\n",
|
|
"* is the physics independent of the directions of the axes, that is are there privileged axes?\n",
|
|
"\n",
|
|
"* is the physics independent of the orientation of system?\n",
|
|
"\n",
|
|
"* is the physics independent of the scale of the length?\n",
|
|
"\n",
|
|
"### Dimension, units and labels\n",
|
|
"\n",
|
|
"Throughout this course we will use the standardized SI units. The standard unit for length is thus one meter 1m, for mass\n",
|
|
"one kilogram 1kg, for time one second 1s, for force one Newton 1kgm/s$^2$ and for energy 1 Joule 1kgm$^2$s$^{-2}$.\n",
|
|
"\n",
|
|
"We will use the following notations for various variables (vectors are always boldfaced in these lecture notes):\n",
|
|
"* position $\\boldsymbol{r}$, in one dimention we will normally just use $x$,\n",
|
|
"\n",
|
|
"* mass $m$,\n",
|
|
"\n",
|
|
"* time $t$,\n",
|
|
"\n",
|
|
"* velocity $\\boldsymbol{v}$ or just $v$ in one dimension,\n",
|
|
"\n",
|
|
"* acceleration $\\boldsymbol{a}$ or just $a$ in one dimension,\n",
|
|
"\n",
|
|
"* momentum $\\boldsymbol{p}$ or just $p$ in one dimension,\n",
|
|
"\n",
|
|
"* kinetic energy $K$,\n",
|
|
"\n",
|
|
"* potential energy $V$ and\n",
|
|
"\n",
|
|
"* frequency $\\omega$.\n",
|
|
"\n",
|
|
"More variables will be defined as we need them.\n",
|
|
"\n",
|
|
"It is also important to keep track of dimensionalities. Don't mix this up with a chosen unit for a given variable. We mark the dimensionality in these lectures as $[a]$, where $a$ is the quantity we are interested in. Thus\n",
|
|
"\n",
|
|
"* $[\\boldsymbol{r}]=$ length\n",
|
|
"\n",
|
|
"* $[m]=$ mass\n",
|
|
"\n",
|
|
"* $[K]=$ energy\n",
|
|
"\n",
|
|
"* $[t]=$ time\n",
|
|
"\n",
|
|
"* $[\\boldsymbol{v}]=$ length over time\n",
|
|
"\n",
|
|
"* $[\\boldsymbol{a}]=$ length over time squared\n",
|
|
"\n",
|
|
"* $[\\boldsymbol{p}]=$ mass times length over time\n",
|
|
"\n",
|
|
"* $[\\omega]=$ 1/time\n",
|
|
"\n",
|
|
"## Elements of Vector Algebra\n",
|
|
"\n",
|
|
"**Note**: This section is under revision\n",
|
|
"\n",
|
|
"In these lectures we will use boldfaced lower-case letters to label a vector. A vector $\\boldsymbol{a}$ in three dimensions is thus defined as"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"$$\n",
|
|
"\\boldsymbol{a} =(a_x,a_y, a_z),\n",
|
|
"$$"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"and using the unit vectors in a cartesian system we have"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"$$\n",
|
|
"\\boldsymbol{a} = a_x\\boldsymbol{e}_x+a_y\\boldsymbol{e}_y+a_z\\boldsymbol{e}_z,\n",
|
|
"$$"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"where the unit vectors have magnitude $\\vert\\boldsymbol{e}_i\\vert = 1$ with $i=x,y,z$.\n",
|
|
"\n",
|
|
"Using the fact that multiplication of reals is distributive we can show that"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"$$\n",
|
|
"\\boldsymbol{a}(\\boldsymbol{b}+\\boldsymbol{c})=\\boldsymbol{a}\\boldsymbol{b}+\\boldsymbol{a}\\boldsymbol{c},\n",
|
|
"$$"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"Similarly we can also show that (using product rule for differentiating reals)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"$$\n",
|
|
"\\frac{d}{dt}(\\boldsymbol{a}\\boldsymbol{b})=\\boldsymbol{a}\\frac{d\\boldsymbol{b}}{dt}+\\boldsymbol{b}\\frac{d\\boldsymbol{a}}{dt}.\n",
|
|
"$$"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"We can repeat these operations for the cross products and show that they are distribuitive"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"$$\n",
|
|
"\\boldsymbol{a}\\times(\\boldsymbol{b}+\\boldsymbol{c})=\\boldsymbol{a}\\times\\boldsymbol{b}+\\boldsymbol{a}\\times\\boldsymbol{c}.\n",
|
|
"$$"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"We have also that"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"$$\n",
|
|
"\\frac{d}{dt}(\\boldsymbol{a}\\times\\boldsymbol{b})=\\boldsymbol{a}\\times\\frac{d\\boldsymbol{b}}{dt}+\\boldsymbol{b}\\times\\frac{d\\boldsymbol{a}}{dt}.\n",
|
|
"$$"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"The rotation of a three-dimensional vector $\\boldsymbol{a}=(a_x,a_y,a_z)$ in the $xy$ plane around an angle $\\phi$ results in a new vector $\\boldsymbol{b}=(b_x,b_y,b_z)$. This operation can be expressed in terms of linear algebra as a matrix (the rotation matrix) multiplied with a vector. We can write this as"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"$$\n",
|
|
"\\begin{bmatrix} b_x \\\\ b_y \\\\ b_z \\end{bmatrix} = \\begin{bmatrix} \\cos{\\phi} & \\sin{\\phi} & 0 \\\\ -\\sin{\\phi} & \\cos{\\phi} & 0 \\\\ 0 & 0 & 1\\end{bmatrix}\\begin{bmatrix} a_x \\\\ a_y \\\\ a_z \\end{bmatrix}.\n",
|
|
"$$"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"We can write this in a more compact form as $\\boldsymbol{b} = \\boldsymbol{R}\\boldsymbol{a}$, where the rotation matrix is defined as"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"$$\n",
|
|
"\\boldsymbol{R} = \\begin{bmatrix} \\cos{\\phi} & \\sin{\\phi} & 0 \\\\ -\\sin{\\phi} & \\cos{\\phi} & 0 \\\\ 0 & 0 & 1\\end{bmatrix}.\n",
|
|
"$$"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"## Falling baseball in one dimension\n",
|
|
"\n",
|
|
"We anticipate the mathematical model to come and assume that we have a\n",
|
|
"model for the motion of a falling baseball without air resistance.\n",
|
|
"Our system (the baseball) is at an initial height $y_0$ (which we will\n",
|
|
"specify in the program below) at the initial time $t_0=0$. In our program example here we will plot the position in steps of $\\Delta t$ up to a final time $t_f$. \n",
|
|
"The mathematical formula for the position $y(t)$ as function of time $t$ is"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"$$\n",
|
|
"y(t) = y_0-\\frac{1}{2}gt^2,\n",
|
|
"$$"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"where $g=9.80665=0.980655\\times 10^1$m/s$^2$ is a constant representing the standard acceleration due to gravity.\n",
|
|
"We have here adopted the conventional standard value. This does not take into account other effects, such as buoyancy or drag.\n",
|
|
"Furthermore, we stop when the ball hits the ground, which takes place at"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"$$\n",
|
|
"y(t) = 0= y_0-\\frac{1}{2}gt^2,\n",
|
|
"$$"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"which gives us a final time $t_f=\\sqrt{2y_0/g}$. \n",
|
|
"\n",
|
|
"As of now we simply assume that we know the formula for the falling object. Afterwards, we will derive it.\n",
|
|
"\n",
|
|
"\n",
|
|
"## Our Python Encounter\n",
|
|
"\n",
|
|
"We start with preparing folders for storing our calculations, figures and if needed, specific data files we use as input or output files."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 1,
|
|
"metadata": {
|
|
"collapsed": false
|
|
},
|
|
"outputs": [],
|
|
"source": [
|
|
"%matplotlib inline\n",
|
|
"\n",
|
|
"# Common imports\n",
|
|
"import numpy as np\n",
|
|
"import pandas as pd\n",
|
|
"import matplotlib.pyplot as plt\n",
|
|
"import os\n",
|
|
"\n",
|
|
"# Where to save the figures and data files\n",
|
|
"PROJECT_ROOT_DIR = \"Results\"\n",
|
|
"FIGURE_ID = \"Results/FigureFiles\"\n",
|
|
"DATA_ID = \"DataFiles/\"\n",
|
|
"\n",
|
|
"if not os.path.exists(PROJECT_ROOT_DIR):\n",
|
|
" os.mkdir(PROJECT_ROOT_DIR)\n",
|
|
"\n",
|
|
"if not os.path.exists(FIGURE_ID):\n",
|
|
" os.makedirs(FIGURE_ID)\n",
|
|
"\n",
|
|
"if not os.path.exists(DATA_ID):\n",
|
|
" os.makedirs(DATA_ID)\n",
|
|
"\n",
|
|
"def image_path(fig_id):\n",
|
|
" return os.path.join(FIGURE_ID, fig_id)\n",
|
|
"\n",
|
|
"def data_path(dat_id):\n",
|
|
" return os.path.join(DATA_ID, dat_id)\n",
|
|
"\n",
|
|
"def save_fig(fig_id):\n",
|
|
" plt.savefig(image_path(fig_id) + \".png\", format='png')\n",
|
|
"\n",
|
|
"#in case we have an input file we wish to read in\n",
|
|
"#infile = open(data_path(\"MassEval2016.dat\"),'r')"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"You could also define a function for making our plots. You\n",
|
|
"can obviously avoid this and simply set up various **matplotlib**\n",
|
|
"commands every time you need them. You may however find it convenient\n",
|
|
"to collect all such commands in one function and simply call this\n",
|
|
"function."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 2,
|
|
"metadata": {
|
|
"collapsed": false
|
|
},
|
|
"outputs": [],
|
|
"source": [
|
|
"from pylab import plt, mpl\n",
|
|
"plt.style.use('seaborn')\n",
|
|
"mpl.rcParams['font.family'] = 'serif'\n",
|
|
"\n",
|
|
"def MakePlot(x,y, styles, labels, axlabels):\n",
|
|
" plt.figure(figsize=(10,6))\n",
|
|
" for i in range(len(x)):\n",
|
|
" plt.plot(x[i], y[i], styles[i], label = labels[i])\n",
|
|
" plt.xlabel(axlabels[0])\n",
|
|
" plt.ylabel(axlabels[1])\n",
|
|
" plt.legend(loc=0)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"Thereafter we start setting up the code for the falling object."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 3,
|
|
"metadata": {
|
|
"collapsed": false
|
|
},
|
|
"outputs": [],
|
|
"source": [
|
|
"%matplotlib inline\n",
|
|
"import matplotlib.patches as mpatches\n",
|
|
"\n",
|
|
"g = 9.80655 #m/s^2\n",
|
|
"y_0 = 10.0 # initial position in meters\n",
|
|
"DeltaT = 0.1 # time step\n",
|
|
"# final time when y = 0, t = sqrt(2*10/g)\n",
|
|
"tfinal = np.sqrt(2.0*y_0/g)\n",
|
|
"#set up arrays \n",
|
|
"t = np.arange(0,tfinal,DeltaT)\n",
|
|
"y =y_0 -g*.5*t**2\n",
|
|
"# Then make a nice printout in table form using Pandas\n",
|
|
"import pandas as pd\n",
|
|
"from IPython.display import display\n",
|
|
"data = {'t[s]': t,\n",
|
|
" 'y[m]': y\n",
|
|
" }\n",
|
|
"RawData = pd.DataFrame(data)\n",
|
|
"display(RawData)\n",
|
|
"plt.style.use('ggplot')\n",
|
|
"plt.figure(figsize=(8,8))\n",
|
|
"plt.scatter(t, y, color = 'b')\n",
|
|
"blue_patch = mpatches.Patch(color = 'b', label = 'Height y as function of time t')\n",
|
|
"plt.legend(handles=[blue_patch])\n",
|
|
"plt.xlabel(\"t[s]\")\n",
|
|
"plt.ylabel(\"y[m]\")\n",
|
|
"save_fig(\"FallingBaseball\")\n",
|
|
"plt.show()"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"Here we used **pandas** (see below) to systemize the output of the position as function of time.\n",
|
|
"\n",
|
|
"\n",
|
|
"\n",
|
|
"## Average quantities\n",
|
|
"We define now the average velocity as"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"$$\n",
|
|
"\\overline{v}(t) = \\frac{y(t+\\Delta t)-y(t)}{\\Delta t}.\n",
|
|
"$$"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"In the code we have set the time step $\\Delta t$ to a given value. We could define it in terms of the number of points $n$ as"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"$$\n",
|
|
"\\Delta t = \\frac{t_{\\mathrm{final}-}t_{\\mathrm{initial}}}{n+1}.\n",
|
|
"$$"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"Since we have discretized the variables, we introduce the counter $i$ and let $y(t)\\rightarrow y(t_i)=y_i$ and $t\\rightarrow t_i$\n",
|
|
"with $i=0,1,\\dots, n$. This gives us the following shorthand notations that we will use for the rest of this course. We define"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"$$\n",
|
|
"y_i = y(t_i),\\hspace{0.2cm} i=0,1,2,\\dots,n.\n",
|
|
"$$"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"This applies to other variables which depend on say time. Examples are the velocities, accelerations, momenta etc.\n",
|
|
"Furthermore we use the shorthand"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"$$\n",
|
|
"y_{i\\pm 1} = y(t_i\\pm \\Delta t),\\hspace{0.12cm} i=0,1,2,\\dots,n.\n",
|
|
"$$"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"## Compact equations\n",
|
|
"We can then rewrite in a more compact form the average velocity as"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"$$\n",
|
|
"\\overline{v}_i = \\frac{y_{i+1}-y_{i}}{\\Delta t}.\n",
|
|
"$$"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"The velocity is defined as the change in position per unit time.\n",
|
|
"In the limit $\\Delta t \\rightarrow 0$ this defines the instantaneous velocity, which is nothing but the slope of the position at a time $t$.\n",
|
|
"We have thus"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"$$\n",
|
|
"v(t) = \\frac{dy}{dt}=\\lim_{\\Delta t \\rightarrow 0}\\frac{y(t+\\Delta t)-y(t)}{\\Delta t}.\n",
|
|
"$$"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"Similarly, we can define the average acceleration as the change in velocity per unit time as"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"$$\n",
|
|
"\\overline{a}_i = \\frac{v_{i+1}-v_{i}}{\\Delta t},\n",
|
|
"$$"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"resulting in the instantaneous acceleration"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"$$\n",
|
|
"a(t) = \\frac{dv}{dt}=\\lim_{\\Delta t\\rightarrow 0}\\frac{v(t+\\Delta t)-v(t)}{\\Delta t}.\n",
|
|
"$$"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"**A note on notations**: When writing for example the velocity as $v(t)$ we are then referring to the continuous and instantaneous value. A subscript like\n",
|
|
"$v_i$ refers always to the discretized values.\n",
|
|
"\n",
|
|
"\n",
|
|
"## A differential equation\n",
|
|
"\n",
|
|
"We can rewrite the instantaneous acceleration as"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"$$\n",
|
|
"a(t) = \\frac{dv}{dt}=\\frac{d}{dt}\\frac{dy}{dt}=\\frac{d^2y}{dt^2}.\n",
|
|
"$$"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"This forms the starting point for our definition of forces later. It is a famous second-order differential equation. If the acceleration is constant we can now recover the formula for the falling ball we started with.\n",
|
|
"The acceleration can depend on the position and the velocity. To be more formal we should then write the above differential equation as"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"$$\n",
|
|
"\\frac{d^2y}{dt^2}=a(t,y(t),\\frac{dy}{dt}).\n",
|
|
"$$"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"With given initial conditions for $y(t_0)$ and $v(t_0)$ we can then\n",
|
|
"integrate the above equation and find the velocities and positions at\n",
|
|
"a given time $t$.\n",
|
|
"\n",
|
|
"If we multiply with mass, we have one of the famous expressions for Newton's second law,"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"$$\n",
|
|
"F(y,v,t)=m\\frac{d^2y}{dt^2}=ma(t,y(t),\\frac{dy}{dt}),\n",
|
|
"$$"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"where $F$ is the force acting on an object with mass $m$. We see that it also has the right dimension, mass times length divided by time squared.\n",
|
|
"We will come back to this soon.\n",
|
|
"\n",
|
|
"\n",
|
|
"## Integrating our equations\n",
|
|
"\n",
|
|
"Formally we can then, starting with the acceleration (suppose we have measured it, how could we do that?)\n",
|
|
"compute say the height of a building. To see this we perform the following integrations from an initial time $t_0$ to a given time $t$"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"$$\n",
|
|
"\\int_{t_0}^t dt a(t) = \\int_{t_0}^t dt \\frac{dv}{dt} = v(t)-v(t_0),\n",
|
|
"$$"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"or as"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"$$\n",
|
|
"v(t)=v(t_0)+\\int_{t_0}^t dt a(t).\n",
|
|
"$$"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"When we know the velocity as function of time, we can find the position as function of time starting from the defintion of velocity as the derivative with respect to time, that is we have"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"$$\n",
|
|
"\\int_{t_0}^t dt v(t) = \\int_{t_0}^t dt \\frac{dy}{dt} = y(t)-y(t_0),\n",
|
|
"$$"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"or as"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"$$\n",
|
|
"y(t)=y(t_0)+\\int_{t_0}^t dt v(t).\n",
|
|
"$$"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"These equations define what is called the integration method for\n",
|
|
"finding the position and the velocity as functions of time. There is\n",
|
|
"no loss of generality if we extend these equations to more than one\n",
|
|
"spatial dimension.\n",
|
|
"\n",
|
|
"\n",
|
|
"## Constant acceleration case, the velocity\n",
|
|
"\n",
|
|
"Let us compute the velocity using the constant value for the acceleration given by $-g$. We have"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"$$\n",
|
|
"v(t)=v(t_0)+\\int_{t_0}^t dt a(t)=v(t_0)+\\int_{t_0}^t dt (-g).\n",
|
|
"$$"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"Using our initial time as $t_0=0$s and setting the initial velocity $v(t_0)=v_0=0$m/s we get when integrating"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"$$\n",
|
|
"v(t)=-gt.\n",
|
|
"$$"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"The more general case is"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"$$\n",
|
|
"v(t)=v_0-g(t-t_0).\n",
|
|
"$$"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"We can then integrate the velocity and obtain the final formula for the position as function of time through"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"$$\n",
|
|
"y(t)=y(t_0)+\\int_{t_0}^t dt v(t)=y_0+\\int_{t_0}^t dt v(t)=y_0+\\int_{t_0}^t dt (-gt),\n",
|
|
"$$"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"With $y_0=10$m and $t_0=0$s, we obtain the equation we started with"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"$$\n",
|
|
"y(t)=10-\\frac{1}{2}gt^2.\n",
|
|
"$$"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"## Computing the averages\n",
|
|
"\n",
|
|
"After this mathematical background we are now ready to compute the mean velocity using our data."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 4,
|
|
"metadata": {
|
|
"collapsed": false
|
|
},
|
|
"outputs": [],
|
|
"source": [
|
|
"# Now we can compute the mean velocity using our data\n",
|
|
"# We define first an array Vaverage\n",
|
|
"n = np.size(t)\n",
|
|
"Vaverage = np.zeros(n)\n",
|
|
"for i in range(1,n-1):\n",
|
|
" Vaverage[i] = (y[i+1]-y[i])/DeltaT\n",
|
|
"# Now we can compute the mean accelearatio using our data\n",
|
|
"# We define first an array Aaverage\n",
|
|
"n = np.size(t)\n",
|
|
"Aaverage = np.zeros(n)\n",
|
|
"Aaverage[0] = -g\n",
|
|
"for i in range(1,n-1):\n",
|
|
" Aaverage[i] = (Vaverage[i+1]-Vaverage[i])/DeltaT\n",
|
|
"data = {'t[s]': t,\n",
|
|
" 'y[m]': y,\n",
|
|
" 'v[m/s]': Vaverage,\n",
|
|
" 'a[m/s^2]': Aaverage\n",
|
|
" }\n",
|
|
"NewData = pd.DataFrame(data)\n",
|
|
"display(NewData[0:n-2])"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"Note that we don't print the last values! \n",
|
|
"\n",
|
|
"\n",
|
|
"\n",
|
|
"\n",
|
|
"## Including Air Resistance in our model\n",
|
|
"\n",
|
|
"In our discussions till now of the falling baseball, we have ignored\n",
|
|
"air resistance and simply assumed that our system is only influenced\n",
|
|
"by the gravitational force. We will postpone the derivation of air\n",
|
|
"resistance till later, after our discussion of Newton's laws and\n",
|
|
"forces.\n",
|
|
"\n",
|
|
"For our discussions here it suffices to state that the accelerations is now modified to"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"$$\n",
|
|
"\\boldsymbol{a}(t) = -g +D\\boldsymbol{v}(t)\\vert v(t)\\vert,\n",
|
|
"$$"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"where $\\vert v(t)\\vert$ is the absolute value of the velocity and $D$ is a constant which pertains to the specific object we are studying.\n",
|
|
"Since we are dealing with motion in one dimension, we can simplify the above to"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"$$\n",
|
|
"a(t) = -g +Dv^2(t).\n",
|
|
"$$"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"We can rewrite this as a differential equation"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"$$\n",
|
|
"a(t) = \\frac{dv}{dt}=\\frac{d^2y}{dt^2}= -g +Dv^2(t).\n",
|
|
"$$"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"Using the integral equations discussed above we can integrate twice\n",
|
|
"and obtain first the velocity as function of time and thereafter the\n",
|
|
"position as function of time.\n",
|
|
"\n",
|
|
"For this particular case, we can actually obtain an analytical\n",
|
|
"solution for the velocity and for the position. Here we will first\n",
|
|
"compute the solutions analytically, thereafter we will derive Euler's\n",
|
|
"method for solving these differential equations numerically.\n",
|
|
"\n",
|
|
"\n",
|
|
"## Analytical solutions\n",
|
|
"\n",
|
|
"For simplicity let us just write $v(t)$ as $v$. We have"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"$$\n",
|
|
"\\frac{dv}{dt}= -g +Dv^2(t).\n",
|
|
"$$"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"We can solve this using the technique of separation of variables. We\n",
|
|
"isolate on the left all terms that involve $v$ and on the right all\n",
|
|
"terms that involve time. We get then"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"$$\n",
|
|
"\\frac{dv}{g -Dv^2(t) }= -dt,\n",
|
|
"$$"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"We scale now the equation to the left by introducing a constant\n",
|
|
"$v_T=\\sqrt{g/D}$. This constant has dimension length/time. Can you\n",
|
|
"show this?\n",
|
|
"\n",
|
|
"Next we integrate the left-hand side (lhs) from $v_0=0$ m/s to $v$ and\n",
|
|
"the right-hand side (rhs) from $t_0=0$ to $t$ and obtain"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"$$\n",
|
|
"\\int_{0}^v\\frac{dv}{g -Dv^2(t) }= \\frac{v_T}{g}\\mathrm{arctanh}(\\frac{v}{v_T}) =-\\int_0^tdt = -t.\n",
|
|
"$$"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"We can reorganize these equations as"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"$$\n",
|
|
"v_T\\mathrm{arctanh}(\\frac{v}{v_T}) =-gt,\n",
|
|
"$$"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"which gives us $v$ as function of time"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"$$\n",
|
|
"v(t)=v_T\\tanh{-(\\frac{gt}{v_T})}.\n",
|
|
"$$"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"## Finding the final height\n",
|
|
"\n",
|
|
"With the velocity we can then find the height $y(t)$ by integrating yet another time, that is"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"$$\n",
|
|
"y(t)=y(t_0)+\\int_{t_0}^t dt v(t)=\\int_{0}^t dt[v_T\\tanh{-(\\frac{gt}{v_T})}].\n",
|
|
"$$"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"This integral is a little bit trickier but we can look it up in a table over \n",
|
|
"known integrals and we get"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"$$\n",
|
|
"y(t)=y(t_0)-\\frac{v_T^2}{g}\\log{[\\cosh{(\\frac{gt}{v_T})}]}.\n",
|
|
"$$"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"Alternatively we could have used the symbolic Python package **Sympy** (example will be inserted later). \n",
|
|
"\n",
|
|
"In most cases however, we need to revert to numerical solutions. \n",
|
|
"\n",
|
|
"\n",
|
|
"\n",
|
|
"## Our first attempt at solving differential equations\n",
|
|
"\n",
|
|
"Here we will try the simplest possible approach to solving the second-order differential \n",
|
|
"equation"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"$$\n",
|
|
"a(t) =\\frac{d^2y}{dt^2}= -g +Dv^2(t).\n",
|
|
"$$"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"We rewrite it as two coupled first-order equations (this is a standard approach)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"$$\n",
|
|
"\\frac{dy}{dt} = v(t),\n",
|
|
"$$"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"with initial condition $y(t_0)=y_0$ and"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"$$\n",
|
|
"a(t) =\\frac{dv}{dt}= -g +Dv^2(t),\n",
|
|
"$$"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"with initial condition $v(t_0)=v_0$.\n",
|
|
"\n",
|
|
"Many of the algorithms for solving differential equations start with simple Taylor equations.\n",
|
|
"If we now Taylor expand $y$ and $v$ around a value $t+\\Delta t$ we have"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"$$\n",
|
|
"y(t+\\Delta t) = y(t)+\\Delta t \\frac{dy}{dt}+\\frac{\\Delta t^2}{2!} \\frac{d^2y}{dt^2}+O(\\Delta t^3),\n",
|
|
"$$"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"and"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"$$\n",
|
|
"v(t+\\Delta t) = v(t)+\\Delta t \\frac{dv}{dt}+\\frac{\\Delta t^2}{2!} \\frac{d^2v}{dt^2}+O(\\Delta t^3).\n",
|
|
"$$"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"Using the fact that $dy/dt = v$ and $dv/dt=a$ and keeping only terms up to $\\Delta t$ we have"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"$$\n",
|
|
"y(t+\\Delta t) = y(t)+\\Delta t v(t)+O(\\Delta t^2),\n",
|
|
"$$"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"and"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"$$\n",
|
|
"v(t+\\Delta t) = v(t)+\\Delta t a(t)+O(\\Delta t^2).\n",
|
|
"$$"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"## Discretizing our equations\n",
|
|
"\n",
|
|
"Using our discretized versions of the equations with for example\n",
|
|
"$y_{i}=y(t_i)$ and $y_{i\\pm 1}=y(t_i+\\Delta t)$, we can rewrite the\n",
|
|
"above equations as (and truncating at $\\Delta t$)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"$$\n",
|
|
"y_{i+1} = y_i+\\Delta t v_i,\n",
|
|
"$$"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"and"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"$$\n",
|
|
"v_{i+1} = v_i+\\Delta t a_i.\n",
|
|
"$$"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"These are the famous Euler equations (forward Euler).\n",
|
|
"\n",
|
|
"To solve these equations numerically we start at a time $t_0$ and simply integrate up these equations to a final time $t_f$,\n",
|
|
"The step size $\\Delta t$ is an input parameter in our code.\n",
|
|
"You can define it directly in the code below as"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 5,
|
|
"metadata": {
|
|
"collapsed": false
|
|
},
|
|
"outputs": [],
|
|
"source": [
|
|
"DeltaT = 0.1"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"With a given final time **tfinal** we can then find the number of integration points via the **ceil** function included in the **math** package of Python\n",
|
|
"as"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 6,
|
|
"metadata": {
|
|
"collapsed": false
|
|
},
|
|
"outputs": [],
|
|
"source": [
|
|
"#define final time, assuming that initial time is zero\n",
|
|
"from math import ceil\n",
|
|
"tfinal = 0.5\n",
|
|
"n = ceil(tfinal/DeltaT)\n",
|
|
"print(n)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"The **ceil** function returns the smallest integer not less than the input in say"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 7,
|
|
"metadata": {
|
|
"collapsed": false
|
|
},
|
|
"outputs": [],
|
|
"source": [
|
|
"x = 21.15\n",
|
|
"print(ceil(x))"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"which in the case here is 22."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 8,
|
|
"metadata": {
|
|
"collapsed": false
|
|
},
|
|
"outputs": [],
|
|
"source": [
|
|
"x = 21.75\n",
|
|
"print(ceil(x))"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"which also yields 22. The **floor** function in the **math** package\n",
|
|
"is used to return the closest integer value which is less than or equal to the specified expression or value.\n",
|
|
"Compare the previous result to the usage of **floor**"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 9,
|
|
"metadata": {
|
|
"collapsed": false
|
|
},
|
|
"outputs": [],
|
|
"source": [
|
|
"from math import floor\n",
|
|
"x = 21.75\n",
|
|
"print(floor(x))"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"Alternatively, we can define ourselves the number of integration(mesh) points. In this case we could have"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 10,
|
|
"metadata": {
|
|
"collapsed": false
|
|
},
|
|
"outputs": [],
|
|
"source": [
|
|
"n = 10\n",
|
|
"tinitial = 0.0\n",
|
|
"tfinal = 0.5\n",
|
|
"DeltaT = (tfinal-tinitial)/(n)\n",
|
|
"print(DeltaT)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"Since we will set up one-dimensional arrays that contain the values of\n",
|
|
"various variables like time, position, velocity, acceleration etc, we\n",
|
|
"need to know the value of $n$, the number of data points (or\n",
|
|
"integration or mesh points). With $n$ we can initialize a given array\n",
|
|
"by setting all elelements to zero, as done here"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 11,
|
|
"metadata": {
|
|
"collapsed": false
|
|
},
|
|
"outputs": [],
|
|
"source": [
|
|
"# define array a\n",
|
|
"a = np.zeros(n)\n",
|
|
"print(a)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"## Code for implementing Euler's method\n",
|
|
"In the code here we implement this simple Eurler scheme choosing a value for $D=0.0245$ m/s."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 12,
|
|
"metadata": {
|
|
"collapsed": false
|
|
},
|
|
"outputs": [],
|
|
"source": [
|
|
"# Common imports\n",
|
|
"import numpy as np\n",
|
|
"import pandas as pd\n",
|
|
"from math import *\n",
|
|
"import matplotlib.pyplot as plt\n",
|
|
"import os\n",
|
|
"\n",
|
|
"# Where to save the figures and data files\n",
|
|
"PROJECT_ROOT_DIR = \"Results\"\n",
|
|
"FIGURE_ID = \"Results/FigureFiles\"\n",
|
|
"DATA_ID = \"DataFiles/\"\n",
|
|
"\n",
|
|
"if not os.path.exists(PROJECT_ROOT_DIR):\n",
|
|
" os.mkdir(PROJECT_ROOT_DIR)\n",
|
|
"\n",
|
|
"if not os.path.exists(FIGURE_ID):\n",
|
|
" os.makedirs(FIGURE_ID)\n",
|
|
"\n",
|
|
"if not os.path.exists(DATA_ID):\n",
|
|
" os.makedirs(DATA_ID)\n",
|
|
"\n",
|
|
"def image_path(fig_id):\n",
|
|
" return os.path.join(FIGURE_ID, fig_id)\n",
|
|
"\n",
|
|
"def data_path(dat_id):\n",
|
|
" return os.path.join(DATA_ID, dat_id)\n",
|
|
"\n",
|
|
"def save_fig(fig_id):\n",
|
|
" plt.savefig(image_path(fig_id) + \".png\", format='png')\n",
|
|
"\n",
|
|
"\n",
|
|
"g = 9.80655 #m/s^2\n",
|
|
"D = 0.00245 #m/s\n",
|
|
"DeltaT = 0.1\n",
|
|
"#set up arrays \n",
|
|
"tfinal = 0.5\n",
|
|
"n = ceil(tfinal/DeltaT)\n",
|
|
"# define scaling constant vT\n",
|
|
"vT = sqrt(g/D)\n",
|
|
"# set up arrays for t, a, v, and y and we can compare our results with analytical ones\n",
|
|
"t = np.zeros(n)\n",
|
|
"a = np.zeros(n)\n",
|
|
"v = np.zeros(n)\n",
|
|
"y = np.zeros(n)\n",
|
|
"yanalytic = np.zeros(n)\n",
|
|
"# Initial conditions\n",
|
|
"v[0] = 0.0 #m/s\n",
|
|
"y[0] = 10.0 #m\n",
|
|
"yanalytic[0] = y[0]\n",
|
|
"# Start integrating using Euler's method\n",
|
|
"for i in range(n-1):\n",
|
|
" # expression for acceleration\n",
|
|
" a[i] = -g + D*v[i]*v[i]\n",
|
|
" # update velocity and position\n",
|
|
" y[i+1] = y[i] + DeltaT*v[i]\n",
|
|
" v[i+1] = v[i] + DeltaT*a[i]\n",
|
|
" # update time to next time step and compute analytical answer\n",
|
|
" t[i+1] = t[i] + DeltaT\n",
|
|
" yanalytic[i+1] = y[0]-(vT*vT/g)*log(cosh(g*t[i+1]/vT))\n",
|
|
" if ( y[i+1] < 0.0):\n",
|
|
" break\n",
|
|
"a[n-1] = -g + D*v[n-1]*v[n-1]\n",
|
|
"data = {'t[s]': t,\n",
|
|
" 'y[m]': y-yanalytic,\n",
|
|
" 'v[m/s]': v,\n",
|
|
" 'a[m/s^2]': a\n",
|
|
" }\n",
|
|
"NewData = pd.DataFrame(data)\n",
|
|
"display(NewData)\n",
|
|
"#finally we plot the data\n",
|
|
"fig, axs = plt.subplots(3, 1)\n",
|
|
"axs[0].plot(t, y, t, yanalytic)\n",
|
|
"axs[0].set_xlim(0, tfinal)\n",
|
|
"axs[0].set_ylabel('y and exact')\n",
|
|
"axs[1].plot(t, v)\n",
|
|
"axs[1].set_ylabel('v[m/s]')\n",
|
|
"axs[2].plot(t, a)\n",
|
|
"axs[2].set_xlabel('time[s]')\n",
|
|
"axs[2].set_ylabel('a[m/s^2]')\n",
|
|
"fig.tight_layout()\n",
|
|
"save_fig(\"EulerIntegration\")\n",
|
|
"plt.show()"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"Try different values for $\\Delta t$ and study the difference between the exact solution and the numerical solution.\n",
|
|
"\n",
|
|
"\n",
|
|
"## Simple extension, the Euler-Cromer method\n",
|
|
"\n",
|
|
"The Euler-Cromer method is a simple variant of the standard Euler\n",
|
|
"method. We use the newly updated velocity $v_{i+1}$ as an input to the\n",
|
|
"new position, that is, instead of"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"$$\n",
|
|
"y_{i+1} = y_i+\\Delta t v_i,\n",
|
|
"$$"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"and"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"$$\n",
|
|
"v_{i+1} = v_i+\\Delta t a_i,\n",
|
|
"$$"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"we use now the newly calculate for $v_{i+1}$ as input to $y_{i+1}$, that is \n",
|
|
"we compute first"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"$$\n",
|
|
"v_{i+1} = v_i+\\Delta t a_i,\n",
|
|
"$$"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"and then"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"$$\n",
|
|
"y_{i+1} = y_i+\\Delta t v_{i+1},\n",
|
|
"$$"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"Implementing the Euler-Cromer method yields a simple change to the previous code. We only need to change the following line in the loop over time\n",
|
|
"steps"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 13,
|
|
"metadata": {
|
|
"collapsed": false
|
|
},
|
|
"outputs": [],
|
|
"source": [
|
|
"for i in range(n-1):\n",
|
|
" # more codes in between here\n",
|
|
" v[i+1] = v[i] + DeltaT*a[i]\n",
|
|
" y[i+1] = y[i] + DeltaT*v[i+1]\n",
|
|
" # more code"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"## Python practicalities, Software and needed installations\n",
|
|
"\n",
|
|
"We will make extensive use of Python as programming language and its\n",
|
|
"myriad of available libraries. You will find\n",
|
|
"Jupyter notebooks invaluable in your work. \n",
|
|
"\n",
|
|
"If you have Python installed (we strongly recommend Python3) and you feel\n",
|
|
"pretty familiar with installing different packages, we recommend that\n",
|
|
"you install the following Python packages via **pip** as \n",
|
|
"\n",
|
|
"1. pip install numpy scipy matplotlib ipython scikit-learn mglearn sympy pandas pillow \n",
|
|
"\n",
|
|
"For Python3, replace **pip** with **pip3**.\n",
|
|
"\n",
|
|
"For OSX users we recommend, after having installed Xcode, to\n",
|
|
"install **brew**. Brew allows for a seamless installation of additional\n",
|
|
"software via for example \n",
|
|
"\n",
|
|
"1. brew install python3\n",
|
|
"\n",
|
|
"For Linux users, with its variety of distributions like for example the widely popular Ubuntu distribution,\n",
|
|
"you can use **pip** as well and simply install Python as \n",
|
|
"\n",
|
|
"1. sudo apt-get install python3 (or python for pyhton2.7)\n",
|
|
"\n",
|
|
"etc etc. \n",
|
|
"\n",
|
|
"\n",
|
|
"\n",
|
|
"## Python installers\n",
|
|
"\n",
|
|
"If you don't want to perform these operations separately and venture\n",
|
|
"into the hassle of exploring how to set up dependencies and paths, we\n",
|
|
"recommend two widely used distrubutions which set up all relevant\n",
|
|
"dependencies for Python, namely \n",
|
|
"\n",
|
|
"* [Anaconda](https://docs.anaconda.com/), \n",
|
|
"\n",
|
|
"which is an open source\n",
|
|
"distribution of the Python and R programming languages for large-scale\n",
|
|
"data processing, predictive analytics, and scientific computing, that\n",
|
|
"aims to simplify package management and deployment. Package versions\n",
|
|
"are managed by the package management system **conda**. \n",
|
|
"\n",
|
|
"* [Enthought canopy](https://www.enthought.com/product/canopy/) \n",
|
|
"\n",
|
|
"is a Python\n",
|
|
"distribution for scientific and analytic computing distribution and\n",
|
|
"analysis environment, available for free and under a commercial\n",
|
|
"license.\n",
|
|
"\n",
|
|
"Furthermore, [Google's Colab](https://colab.research.google.com/notebooks/welcome.ipynb) is a free Jupyter notebook environment that requires \n",
|
|
"no setup and runs entirely in the cloud. Try it out!\n",
|
|
"\n",
|
|
"## Useful Python libraries\n",
|
|
"Here we list several useful Python libraries we strongly recommend (if you use anaconda many of these are already there)\n",
|
|
"\n",
|
|
"* [NumPy](https://www.numpy.org/) is a highly popular library for large, multi-dimensional arrays and matrices, along with a large collection of high-level mathematical functions to operate on these arrays\n",
|
|
"\n",
|
|
"* [The pandas](https://pandas.pydata.org/) library provides high-performance, easy-to-use data structures and data analysis tools \n",
|
|
"\n",
|
|
"* [Xarray](http://xarray.pydata.org/en/stable/) is a Python package that makes working with labelled multi-dimensional arrays simple, efficient, and fun!\n",
|
|
"\n",
|
|
"* [Scipy](https://www.scipy.org/) (pronounced “Sigh Pie”) is a Python-based ecosystem of open-source software for mathematics, science, and engineering. \n",
|
|
"\n",
|
|
"* [Matplotlib](https://matplotlib.org/) is a Python 2D plotting library which produces publication quality figures in a variety of hardcopy formats and interactive environments across platforms.\n",
|
|
"\n",
|
|
"* [Autograd](https://github.com/HIPS/autograd) can automatically differentiate native Python and Numpy code. It can handle a large subset of Python's features, including loops, ifs, recursion and closures, and it can even take derivatives of derivatives of derivatives\n",
|
|
"\n",
|
|
"* [SymPy](https://www.sympy.org/en/index.html) is a Python library for symbolic mathematics. \n",
|
|
"\n",
|
|
"* [scikit-learn](https://scikit-learn.org/stable/) has simple and efficient tools for machine learning, data mining and data analysis\n",
|
|
"\n",
|
|
"* [TensorFlow](https://www.tensorflow.org/) is a Python library for fast numerical computing created and released by Google\n",
|
|
"\n",
|
|
"* [Keras](https://keras.io/) is a high-level neural networks API, written in Python and capable of running on top of TensorFlow, CNTK, or Theano\n",
|
|
"\n",
|
|
"* And many more such as [pytorch](https://pytorch.org/), [Theano](https://pypi.org/project/Theano/) etc \n",
|
|
"\n",
|
|
"Your jupyter notebook can easily be\n",
|
|
"converted into a nicely rendered **PDF** file or a Latex file for\n",
|
|
"further processing. For example, convert to latex as"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
" pycod jupyter nbconvert filename.ipynb --to latex \n"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"And to add more versatility, the Python package [SymPy](http://www.sympy.org/en/index.html) is a Python library for symbolic mathematics. It aims to become a full-featured computer algebra system (CAS) and is entirely written in Python. \n",
|
|
"\n",
|
|
"\n",
|
|
"\n",
|
|
"## Numpy examples and Important Matrix and vector handling packages\n",
|
|
"\n",
|
|
"There are several central software libraries for linear algebra and eigenvalue problems. Several of the more\n",
|
|
"popular ones have been wrapped into ofter software packages like those from the widely used text **Numerical Recipes**. The original source codes in many of the available packages are often taken from the widely used\n",
|
|
"software package LAPACK, which follows two other popular packages\n",
|
|
"developed in the 1970s, namely EISPACK and LINPACK. We describe them shortly here.\n",
|
|
"\n",
|
|
" * LINPACK: package for linear equations and least square problems.\n",
|
|
"\n",
|
|
" * LAPACK:package for solving symmetric, unsymmetric and generalized eigenvalue problems. From LAPACK's website <http://www.netlib.org> it is possible to download for free all source codes from this library. Both C/C++ and Fortran versions are available.\n",
|
|
"\n",
|
|
" * BLAS (I, II and III): (Basic Linear Algebra Subprograms) are routines that provide standard building blocks for performing basic vector and matrix operations. Blas I is vector operations, II vector-matrix operations and III matrix-matrix operations. Highly parallelized and efficient codes, all available for download from <http://www.netlib.org>.\n",
|
|
"\n",
|
|
"## Basic Matrix Features\n",
|
|
"\n",
|
|
"**Matrix properties reminder.**"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"$$\n",
|
|
"\\mathbf{A} =\n",
|
|
" \\begin{bmatrix} a_{11} & a_{12} & a_{13} & a_{14} \\\\\n",
|
|
" a_{21} & a_{22} & a_{23} & a_{24} \\\\\n",
|
|
" a_{31} & a_{32} & a_{33} & a_{34} \\\\\n",
|
|
" a_{41} & a_{42} & a_{43} & a_{44}\n",
|
|
" \\end{bmatrix}\\qquad\n",
|
|
"\\mathbf{I} =\n",
|
|
" \\begin{bmatrix} 1 & 0 & 0 & 0 \\\\\n",
|
|
" 0 & 1 & 0 & 0 \\\\\n",
|
|
" 0 & 0 & 1 & 0 \\\\\n",
|
|
" 0 & 0 & 0 & 1\n",
|
|
" \\end{bmatrix}\n",
|
|
"$$"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"The inverse of a matrix is defined by"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"$$\n",
|
|
"\\mathbf{A}^{-1} \\cdot \\mathbf{A} = I\n",
|
|
"$$"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"<table border=\"1\">\n",
|
|
"<thead>\n",
|
|
"<tr><th align=\"center\"> Relations </th> <th align=\"center\"> Name </th> <th align=\"center\"> matrix elements </th> </tr>\n",
|
|
"</thead>\n",
|
|
"<tbody>\n",
|
|
"<tr><td align=\"center\"> $A = A^{T}$ </td> <td align=\"center\"> symmetric </td> <td align=\"center\"> $a_{ij} = a_{ji}$ </td> </tr>\n",
|
|
"<tr><td align=\"center\"> $A = \\left (A^{T} \\right )^{-1}$ </td> <td align=\"center\"> real orthogonal </td> <td align=\"center\"> $\\sum_k a_{ik} a_{jk} = \\sum_k a_{ki} a_{kj} = \\delta_{ij}$ </td> </tr>\n",
|
|
"<tr><td align=\"center\"> $A = A^{ * }$ </td> <td align=\"center\"> real matrix </td> <td align=\"center\"> $a_{ij} = a_{ij}^{ * }$ </td> </tr>\n",
|
|
"<tr><td align=\"center\"> $A = A^{\\dagger}$ </td> <td align=\"center\"> hermitian </td> <td align=\"center\"> $a_{ij} = a_{ji}^{ * }$ </td> </tr>\n",
|
|
"<tr><td align=\"center\"> $A = \\left (A^{\\dagger} \\right )^{-1}$ </td> <td align=\"center\"> unitary </td> <td align=\"center\"> $\\sum_k a_{ik} a_{jk}^{ * } = \\sum_k a_{ki}^{ * } a_{kj} = \\delta_{ij}$ </td> </tr>\n",
|
|
"</tbody>\n",
|
|
"</table>\n",
|
|
"\n",
|
|
"\n",
|
|
"\n",
|
|
"\n",
|
|
"### Some famous Matrices\n",
|
|
"\n",
|
|
" * Diagonal if $a_{ij}=0$ for $i\\ne j$\n",
|
|
"\n",
|
|
" * Upper triangular if $a_{ij}=0$ for $i > j$\n",
|
|
"\n",
|
|
" * Lower triangular if $a_{ij}=0$ for $i < j$\n",
|
|
"\n",
|
|
" * Upper Hessenberg if $a_{ij}=0$ for $i > j+1$\n",
|
|
"\n",
|
|
" * Lower Hessenberg if $a_{ij}=0$ for $i < j+1$\n",
|
|
"\n",
|
|
" * Tridiagonal if $a_{ij}=0$ for $|i -j| > 1$\n",
|
|
"\n",
|
|
" * Lower banded with bandwidth $p$: $a_{ij}=0$ for $i > j+p$\n",
|
|
"\n",
|
|
" * Upper banded with bandwidth $p$: $a_{ij}=0$ for $i < j+p$\n",
|
|
"\n",
|
|
" * Banded, block upper triangular, block lower triangular....\n",
|
|
"\n",
|
|
"### More Basic Matrix Features\n",
|
|
"\n",
|
|
"**Some Equivalent Statements.**\n",
|
|
"\n",
|
|
"For an $N\\times N$ matrix $\\mathbf{A}$ the following properties are all equivalent\n",
|
|
"\n",
|
|
" * If the inverse of $\\mathbf{A}$ exists, $\\mathbf{A}$ is nonsingular.\n",
|
|
"\n",
|
|
" * The equation $\\mathbf{Ax}=0$ implies $\\mathbf{x}=0$.\n",
|
|
"\n",
|
|
" * The rows of $\\mathbf{A}$ form a basis of $R^N$.\n",
|
|
"\n",
|
|
" * The columns of $\\mathbf{A}$ form a basis of $R^N$.\n",
|
|
"\n",
|
|
" * $\\mathbf{A}$ is a product of elementary matrices.\n",
|
|
"\n",
|
|
" * $0$ is not eigenvalue of $\\mathbf{A}$.\n",
|
|
"\n",
|
|
"\n",
|
|
"\n",
|
|
"\n",
|
|
"## Numpy and arrays\n",
|
|
"[Numpy](http://www.numpy.org/) provides an easy way to handle arrays in Python. The standard way to import this library is as"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 14,
|
|
"metadata": {
|
|
"collapsed": false
|
|
},
|
|
"outputs": [],
|
|
"source": [
|
|
"import numpy as np"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"Here follows a simple example where we set up an array of ten elements, all determined by random numbers drawn according to the normal distribution,"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 15,
|
|
"metadata": {
|
|
"collapsed": false
|
|
},
|
|
"outputs": [],
|
|
"source": [
|
|
"n = 10\n",
|
|
"x = np.random.normal(size=n)\n",
|
|
"print(x)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"We defined a vector $x$ with $n=10$ elements with its values given by the Normal distribution $N(0,1)$.\n",
|
|
"Another alternative is to declare a vector as follows"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 16,
|
|
"metadata": {
|
|
"collapsed": false
|
|
},
|
|
"outputs": [],
|
|
"source": [
|
|
"import numpy as np\n",
|
|
"x = np.array([1, 2, 3])\n",
|
|
"print(x)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"Here we have defined a vector with three elements, with $x_0=1$, $x_1=2$ and $x_2=3$. Note that both Python and C++\n",
|
|
"start numbering array elements from $0$ and on. This means that a vector with $n$ elements has a sequence of entities $x_0, x_1, x_2, \\dots, x_{n-1}$. We could also let (recommended) Numpy to compute the logarithms of a specific array as"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 17,
|
|
"metadata": {
|
|
"collapsed": false
|
|
},
|
|
"outputs": [],
|
|
"source": [
|
|
"import numpy as np\n",
|
|
"x = np.log(np.array([4, 7, 8]))\n",
|
|
"print(x)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"In the last example we used Numpy's unary function $np.log$. This function is\n",
|
|
"highly tuned to compute array elements since the code is vectorized\n",
|
|
"and does not require looping. We normaly recommend that you use the\n",
|
|
"Numpy intrinsic functions instead of the corresponding **log** function\n",
|
|
"from Python's **math** module. The looping is done explicitely by the\n",
|
|
"**np.log** function. The alternative, and slower way to compute the\n",
|
|
"logarithms of a vector would be to write"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 18,
|
|
"metadata": {
|
|
"collapsed": false
|
|
},
|
|
"outputs": [],
|
|
"source": [
|
|
"import numpy as np\n",
|
|
"from math import log\n",
|
|
"x = np.array([4, 7, 8])\n",
|
|
"for i in range(0, len(x)):\n",
|
|
" x[i] = log(x[i])\n",
|
|
"print(x)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"We note that our code is much longer already and we need to import the **log** function from the **math** module. \n",
|
|
"The attentive reader will also notice that the output is $[1, 1, 2]$. Python interprets automagically our numbers as integers (like the **automatic** keyword in C++). To change this we could define our array elements to be double precision numbers as"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 19,
|
|
"metadata": {
|
|
"collapsed": false
|
|
},
|
|
"outputs": [],
|
|
"source": [
|
|
"import numpy as np\n",
|
|
"x = np.log(np.array([4, 7, 8], dtype = np.float64))\n",
|
|
"print(x)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"or simply write them as double precision numbers (Python uses 64 bits as default for floating point type variables), that is"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 20,
|
|
"metadata": {
|
|
"collapsed": false
|
|
},
|
|
"outputs": [],
|
|
"source": [
|
|
"import numpy as np\n",
|
|
"x = np.log(np.array([4.0, 7.0, 8.0])\n",
|
|
"print(x)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"To check the number of bytes (remember that one byte contains eight bits for double precision variables), you can use simple use the **itemsize** functionality (the array $x$ is actually an object which inherits the functionalities defined in Numpy) as"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 21,
|
|
"metadata": {
|
|
"collapsed": false
|
|
},
|
|
"outputs": [],
|
|
"source": [
|
|
"import numpy as np\n",
|
|
"x = np.log(np.array([4.0, 7.0, 8.0])\n",
|
|
"print(x.itemsize)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"## Matrices in Python\n",
|
|
"\n",
|
|
"Having defined vectors, we are now ready to try out matrices. We can\n",
|
|
"define a $3 \\times 3 $ real matrix $\\hat{A}$ as (recall that we user\n",
|
|
"lowercase letters for vectors and uppercase letters for matrices)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 22,
|
|
"metadata": {
|
|
"collapsed": false
|
|
},
|
|
"outputs": [],
|
|
"source": [
|
|
"import numpy as np\n",
|
|
"A = np.log(np.array([ [4.0, 7.0, 8.0], [3.0, 10.0, 11.0], [4.0, 5.0, 7.0] ]))\n",
|
|
"print(A)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"If we use the **shape** function we would get $(3, 3)$ as output, that is verifying that our matrix is a $3\\times 3$ matrix. We can slice the matrix and print for example the first column (Python organized matrix elements in a row-major order, see below) as"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 23,
|
|
"metadata": {
|
|
"collapsed": false
|
|
},
|
|
"outputs": [],
|
|
"source": [
|
|
"import numpy as np\n",
|
|
"A = np.log(np.array([ [4.0, 7.0, 8.0], [3.0, 10.0, 11.0], [4.0, 5.0, 7.0] ]))\n",
|
|
"# print the first column, row-major order and elements start with 0\n",
|
|
"print(A[:,0])"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"We can continue this was by printing out other columns or rows. The example here prints out the second column"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 24,
|
|
"metadata": {
|
|
"collapsed": false
|
|
},
|
|
"outputs": [],
|
|
"source": [
|
|
"import numpy as np\n",
|
|
"A = np.log(np.array([ [4.0, 7.0, 8.0], [3.0, 10.0, 11.0], [4.0, 5.0, 7.0] ]))\n",
|
|
"# print the first column, row-major order and elements start with 0\n",
|
|
"print(A[1,:])"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"Numpy contains many other functionalities that allow us to slice, subdivide etc etc arrays. We strongly recommend that you look up the [Numpy website for more details](http://www.numpy.org/). Useful functions when defining a matrix are the **np.zeros** function which declares a matrix of a given dimension and sets all elements to zero"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 25,
|
|
"metadata": {
|
|
"collapsed": false
|
|
},
|
|
"outputs": [],
|
|
"source": [
|
|
"import numpy as np\n",
|
|
"n = 10\n",
|
|
"# define a matrix of dimension 10 x 10 and set all elements to zero\n",
|
|
"A = np.zeros( (n, n) )\n",
|
|
"print(A)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"or initializing all elements to"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 26,
|
|
"metadata": {
|
|
"collapsed": false
|
|
},
|
|
"outputs": [],
|
|
"source": [
|
|
"import numpy as np\n",
|
|
"n = 10\n",
|
|
"# define a matrix of dimension 10 x 10 and set all elements to one\n",
|
|
"A = np.ones( (n, n) )\n",
|
|
"print(A)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"or as unitarily distributed random numbers (see the material on random number generators in the statistics part)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 27,
|
|
"metadata": {
|
|
"collapsed": false
|
|
},
|
|
"outputs": [],
|
|
"source": [
|
|
"import numpy as np\n",
|
|
"n = 10\n",
|
|
"# define a matrix of dimension 10 x 10 and set all elements to random numbers with x \\in [0, 1]\n",
|
|
"A = np.random.rand(n, n)\n",
|
|
"print(A)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"## Meet the Pandas\n",
|
|
"\n",
|
|
"\n",
|
|
"<!-- dom:FIGURE: [fig/pandas.jpg, width=600 frac=0.8] -->\n",
|
|
"<!-- begin figure -->\n",
|
|
"\n",
|
|
"<p></p>\n",
|
|
"<img src=\"fig/pandas.jpg\" width=600>\n",
|
|
"\n",
|
|
"<!-- end figure -->\n",
|
|
"\n",
|
|
"\n",
|
|
"Another useful Python package is\n",
|
|
"[pandas](https://pandas.pydata.org/), which is an open source library\n",
|
|
"providing high-performance, easy-to-use data structures and data\n",
|
|
"analysis tools for Python. **pandas** stands for panel data, a term borrowed from econometrics and is an efficient library for data analysis with an emphasis on tabular data.\n",
|
|
"**pandas** has two major classes, the **DataFrame** class with two-dimensional data objects and tabular data organized in columns and the class **Series** with a focus on one-dimensional data objects. Both classes allow you to index data easily as we will see in the examples below. \n",
|
|
"**pandas** allows you also to perform mathematical operations on the data, spanning from simple reshapings of vectors and matrices to statistical operations. \n",
|
|
"\n",
|
|
"The following simple example shows how we can, in an easy way make tables of our data. Here we define a data set which includes names, place of birth and date of birth, and displays the data in an easy to read way. We will see repeated use of **pandas**, in particular in connection with classification of data."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 28,
|
|
"metadata": {
|
|
"collapsed": false
|
|
},
|
|
"outputs": [],
|
|
"source": [
|
|
"import pandas as pd\n",
|
|
"from IPython.display import display\n",
|
|
"data = {'First Name': [\"Frodo\", \"Bilbo\", \"Aragorn II\", \"Samwise\"],\n",
|
|
" 'Last Name': [\"Baggins\", \"Baggins\",\"Elessar\",\"Gamgee\"],\n",
|
|
" 'Place of birth': [\"Shire\", \"Shire\", \"Eriador\", \"Shire\"],\n",
|
|
" 'Date of Birth T.A.': [2968, 2890, 2931, 2980]\n",
|
|
" }\n",
|
|
"data_pandas = pd.DataFrame(data)\n",
|
|
"display(data_pandas)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"In the above we have imported **pandas** with the shorthand **pd**, the latter has become the standard way we import **pandas**. We make then a list of various variables\n",
|
|
"and reorganize the above lists into a **DataFrame** and then print out a neat table with specific column labels as *Name*, *place of birth* and *date of birth*.\n",
|
|
"Displaying these results, we see that the indices are given by the default numbers from zero to three.\n",
|
|
"**pandas** is extremely flexible and we can easily change the above indices by defining a new type of indexing as"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 29,
|
|
"metadata": {
|
|
"collapsed": false
|
|
},
|
|
"outputs": [],
|
|
"source": [
|
|
"data_pandas = pd.DataFrame(data,index=['Frodo','Bilbo','Aragorn','Sam'])\n",
|
|
"display(data_pandas)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"Thereafter we display the content of the row which begins with the index **Aragorn**"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 30,
|
|
"metadata": {
|
|
"collapsed": false
|
|
},
|
|
"outputs": [],
|
|
"source": [
|
|
"display(data_pandas.loc['Aragorn'])"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"We can easily append data to this, for example"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 31,
|
|
"metadata": {
|
|
"collapsed": false
|
|
},
|
|
"outputs": [],
|
|
"source": [
|
|
"new_hobbit = {'First Name': [\"Peregrin\"],\n",
|
|
" 'Last Name': [\"Took\"],\n",
|
|
" 'Place of birth': [\"Shire\"],\n",
|
|
" 'Date of Birth T.A.': [2990]\n",
|
|
" }\n",
|
|
"data_pandas=data_pandas.append(pd.DataFrame(new_hobbit, index=['Pippin']))\n",
|
|
"display(data_pandas)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"Here are other examples where we use the **DataFrame** functionality to handle arrays, now with more interesting features for us, namely numbers. We set up a matrix \n",
|
|
"of dimensionality $10\\times 5$ and compute the mean value and standard deviation of each column. Similarly, we can perform mathematial operations like squaring the matrix elements and many other operations."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 32,
|
|
"metadata": {
|
|
"collapsed": false
|
|
},
|
|
"outputs": [],
|
|
"source": [
|
|
"import numpy as np\n",
|
|
"import pandas as pd\n",
|
|
"from IPython.display import display\n",
|
|
"np.random.seed(100)\n",
|
|
"# setting up a 10 x 5 matrix\n",
|
|
"rows = 10\n",
|
|
"cols = 5\n",
|
|
"a = np.random.randn(rows,cols)\n",
|
|
"df = pd.DataFrame(a)\n",
|
|
"display(df)\n",
|
|
"print(df.mean())\n",
|
|
"print(df.std())\n",
|
|
"display(df**2)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"Thereafter we can select specific columns only and plot final results"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 33,
|
|
"metadata": {
|
|
"collapsed": false
|
|
},
|
|
"outputs": [],
|
|
"source": [
|
|
"df.columns = ['First', 'Second', 'Third', 'Fourth', 'Fifth']\n",
|
|
"df.index = np.arange(10)\n",
|
|
"\n",
|
|
"display(df)\n",
|
|
"print(df['Second'].mean() )\n",
|
|
"print(df.info())\n",
|
|
"print(df.describe())\n",
|
|
"\n",
|
|
"from pylab import plt, mpl\n",
|
|
"plt.style.use('seaborn')\n",
|
|
"mpl.rcParams['font.family'] = 'serif'\n",
|
|
"\n",
|
|
"df.cumsum().plot(lw=2.0, figsize=(10,6))\n",
|
|
"plt.show()\n",
|
|
"\n",
|
|
"\n",
|
|
"df.plot.bar(figsize=(10,6), rot=15)\n",
|
|
"plt.show()"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"We can produce a $4\\times 4$ matrix"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 34,
|
|
"metadata": {
|
|
"collapsed": false
|
|
},
|
|
"outputs": [],
|
|
"source": [
|
|
"b = np.arange(16).reshape((4,4))\n",
|
|
"print(b)\n",
|
|
"df1 = pd.DataFrame(b)\n",
|
|
"print(df1)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"and many other operations. \n",
|
|
"\n",
|
|
"The **Series** class is another important class included in\n",
|
|
"**pandas**. You can view it as a specialization of **DataFrame** but where\n",
|
|
"we have just a single column of data. It shares many of the same features as _DataFrame. As with **DataFrame**,\n",
|
|
"most operations are vectorized, achieving thereby a high performance when dealing with computations of arrays, in particular labeled arrays.\n",
|
|
"As we will see below it leads also to a very concice code close to the mathematical operations we may be interested in.\n",
|
|
"For multidimensional arrays, we recommend strongly [xarray](http://xarray.pydata.org/en/stable/). **xarray** has much of the same flexibility as **pandas**, but allows for the extension to higher dimensions than two."
|
|
]
|
|
}
|
|
],
|
|
"metadata": {},
|
|
"nbformat": 4,
|
|
"nbformat_minor": 4
|
|
}
|