{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Lecture 5"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"%run set_env.py\n",
"%matplotlib inline"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Universal Functions (UFuncs)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"A universal function (ufunc) is:\n",
"* a function which operates on an ndarray object in an element-by-element fashion\n",
"* an instance of the numpy.ufunc class\n",
"* a function of which many are implemented in compiled C code\n",
"* to which broadcasting rules are applied. \n",
"\n",
"The concept is similar to the map function in standard Python."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Some ufuncs within NumPy: "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"* Math operations:\n",
" * add(x1,x2) (called when invoked a+b)\n",
" * power(x1,x2) (same as '**')\n",
" * mod(x1,x2)\n",
" * exp(x)\n",
" * sqrt(x)\n",
" * log(x) (Napierian/natural logarithm)\n",
" * ...\n",
"* Trig operations:\n",
" * sin(x)\n",
" * sinh(x)\n",
" * arcsinh(x)\n",
" * deg2rad(x)\n",
" * rad2deg(x)\n",
" * ..\n",
"* Bit-twiddling operations:\n",
" * bitwise_and(x1,x2)\n",
" * ...\n",
"* Comparison functions:\n",
" * greater(x1,x2) (called when x1>x2 is invoked)\n",
" * not_equal(x1,x2) (called when x1!=x2 is invoked)\n",
" * maximum(x1,x2) (el.-wise max.)\n",
" * isfinite(x) (el. test for finiteness i.e. neither Infinity nor Not a Number)\n",
" * isinf(x)\n",
" * isnan(x)\n",
" * ...\n",
" \n",
"To see all the available ufuncs, see:
\n",
"https://docs.scipy.org/doc/numpy-1.13.0/reference/ufuncs.html#available-ufuncs"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Note:\n",
"* One can write its own UFunc -> C-API"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Examples/Applications of UFuncs:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Example 1: no BC\n",
"np.set_printoptions(precision=5)\n",
"import numpy as np\n",
"x = np.random.random((2,3,7))\n",
"y = np.exp(x)\n",
"print(f\" x:\\n{x}\\n\")\n",
"print(f\" y:\\n{y}\\n\")\n",
"import math\n",
"z=0.5\n",
"print(np.exp(z))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Example 2: with BC\n",
"x=np.arange(90,103,dtype=int)\n",
"y=np.arange(2,7,dtype=int).reshape((5,1))\n",
"print(f\" x:{x.shape}\\n{x}\\n\")\n",
"print(f\" y:{y.shape}\\n{y}\\n\")\n",
"z=np.mod(x,y)\n",
"print(f\" z:{z.shape}\\n{z}\\n\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Reductions on ndarrays"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"* Besides Numpy functions which operate on ndarrays element-wise (UFuncs, vide supra),
\n",
" there are also Numpy functions which perform reductions on ndarrays. \n",
"\n",
"* By default, the reductions operate on the whole ndarray.\n",
" \n",
"* However, we can specify a particular axis/dimension on which to perform the reduction. \n",
"\n",
"* The functions all have a similar syntax:
\n",
" numpy.func_name(a,[axis=None],[dtype=None],[out=None])
\n",
" The function func_name can be called in 2 different ways:\n",
" * a.func_name() # Object-Oriented way i.e. method associated to an object\n",
" * np.func_name(a) # Procedural way i.e. array is an argument of the function"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Mathematical Operations:\n",
"* numpy.sum(), numpy.cumsum() : sum vs. cumulative sum\n",
"* numpy.prod(), numpy.cumprod() : prod vs. cumulative product\n",
"* numpy.min(), numpy.max() : min, max of a vector\n",
"* numpy.argmin(), numpy.argmax() : return indices of the min./max. values"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Statistical Operations:\n",
"* numpy.mean, numpy.median : average, median\n",
"* numpy.std, numpy.var : standard deviation, variance"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Logical Operations:\n",
"* numpy.any(): Test whether ANY el. along a given axis evaluates to True\n",
"* numpy.all(): Test whether ALL el. along a given axis evaluate to True"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Examples"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"###### Example 1:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Example 1: \n",
"# Invoke sum over the complete ndarray\n",
"a = np.arange(1,25).reshape((2,3,4))\n",
"print(f\" a:\\n{a}\\n\")\n",
"print(f\" a.shape:{a.shape}\\n\")\n",
"print(f\" a.sum() (Object-oriented syntax): {a.sum()}\\n\")\n",
"print(f\" np.sum(a) (Procedural syntax) : {np.sum(a)}\\n\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Invoke sums over certain axes\n",
"a = np.arange(1,25).reshape((2,3,4))\n",
"red0 = a.sum(axis=0)\n",
"print(f\" a.sum(axis=0) shape:{red0.shape}:\\n{red0}\\n\")\n",
"red1 = a.sum(axis=1)\n",
"print(f\" a.sum(axis=1) shape:{red1.shape}:\\n{red1}\\n\")\n",
"red2 = a.sum(axis=2)\n",
"print(f\" a.sum(axis=2) shape:{red2.shape}:\\n{red2}\\n\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"###### Example 2:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"np.set_printoptions(precision=4)\n",
"b = rnd.random((3,7))\n",
"print(f\" b:\\n{b}\\n\")\n",
"print(f\" b.shape:{b.shape}\\n\")\n",
"\n",
"av = b.mean(axis=0)\n",
"print(f\" b.mean(axis=0):\\n{av}\\n\")\n",
"\n",
"bool_matrix = b < 0.05\n",
"print(f\" bool_matrix:\\n{bool_matrix}\\n\")\n",
"print(f\" Are they any values < 0.01? {bool_matrix.any()}\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Exercises:"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"* Generate the following vector [ 1, 3, 9, 27, ... , 729] using a UFunc.\n",
" \n",
"* Generate a 5x10 array A with random numbers $x$ $\\in$ $[0,1[$.\n",
" * What is the maximum value for all $x$ in A?\n",
" * What is the minimum value in each column?\n",
" * What is the minimum value in the fourth row?\n",
" * Are there any random numbers $x<\\alpha$ or $x>\\beta$?
You can set $\\alpha:=0.02$ and $\\beta:=0.98$\n",
" \n",
"* Write the function *calc_sn(n)* (**without the use of for loops!**): \n",
" * The function *calc_sn(n)* returns an array of partial sums $S_n$ ($n>0$) given by:
\n",
" $\\begin{equation*}\n",
" S_n := \\sum_{k=1}^{k=n} \\frac{sin(k)}{k^2} \n",
" \\end{equation*}\n",
" $ \n",
" * Generate the plot $S_n$ where $n$ $\\in$ $\\{1,\\ldots,100\\}$ to visualize the absolute convergency of the series.
\n",
" You can use the following code to create the matplotlib plot:
\n",
" *import matplotlib.pyplot as plt*
\n",
" *plt.plot(calc_sn(100))*
\n",
" *plt.show()*
\n",
" \n",
" \n",
"\n",
" "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Solutions:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# %load ../solutions/ex5.py"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.7"
},
"latex_envs": {
"LaTeX_envs_menu_present": true,
"autoclose": false,
"autocomplete": true,
"bibliofile": "biblio.bib",
"cite_by": "apalike",
"current_citInitial": 1,
"eqLabelWithNumbers": true,
"eqNumInitial": 1,
"hotkeys": {
"equation": "Ctrl-E",
"itemize": "Ctrl-I"
},
"labels_anchors": false,
"latex_user_defs": false,
"report_style_numbering": false,
"user_envs_cfg": false
},
"toc": {
"base_numbering": 1,
"nav_menu": {},
"number_sections": true,
"sideBar": true,
"skip_h1_title": false,
"title_cell": "Table of Contents",
"title_sidebar": "Contents",
"toc_cell": false,
"toc_position": {},
"toc_section_display": true,
"toc_window_display": false
}
},
"nbformat": 4,
"nbformat_minor": 4
}