{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "## Basics of Python language\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Variables and type\n", "\n", "### Symbol names\n", "\n", "There are a number of Python keywords that cannot be used as variable names. These keywords are:\n", " \n", " and, as, assert, break, class, continue, def, del, elif, else, except, exec, finally, for, from, global, if, import, in, is, lambda, not, or, pass, print, raise, return, try, while, with, yield\n", " \n", "Note: Be aware of the keyword `lambda`, which could easily be a natural variable name in a scientific program. But being a keyword, it cannot be used as a variable name. " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Fundamental types / lists / touples" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "\n", "\n", "\n", " 9\n", "\n", "\n", "[, , , ] [, , , ]\n" ] } ], "source": [ "x=1\n", "print (type(x))\n", "x=1.0\n", "print (type(x))\n", "x=True\n", "print (type(x))\n", "x=1.0+1.j\n", "print (type(x))\n", "x = 'my string'\n", "\n", "print (type(x), len(x))\n", "x = [1,2,3.0,2.+3j]\n", "y = (1,2,3.0,2.+3j)\n", "print(type(x))\n", "print(type(y))\n", "\n", "x[2]='ss'\n", "print([type(i) for i in x], [type(i) for i in y])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Formating strings and print statement" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "This is old type 3.141592653589793 1\n" ] } ], "source": [ "from math import *\n", "print('This is old '+'type', pi, 1)" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "This is old type 3.1415926536 3\n" ] } ], "source": [ "# formatting string\n", "print('This is old %10s %12.10f %5d' % ('type',pi, pi))" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1.0 str1 str2 str3str4\n" ] } ], "source": [ "print(1.0, 'str1', 'str2', 'str3'+'str4')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Python2 type of printing, still very useful**" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "value of pi is 3.14159 and integer part 3\n" ] } ], "source": [ "from math import *\n", "print( 'value of pi is %20.5f and integer part %d' % (pi, pi) )" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "value of pi is 3.141 and integer part 3\n" ] } ], "source": [ "print( 'value of pi is %20.5s and integer part %d' % (pi, pi) )" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'3.141592653589793'" ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "str(pi)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**More Python3 oriented printing**" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "value of pi is 3.141592653589793 and integer part 3\n" ] } ], "source": [ "print('value of pi is {} and integer part {}'.format(pi, int(pi)))" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "value of pi is 3.1416 and integer part 3\n" ] } ], "source": [ "print('value of pi is {0:6.4f} and integer part {1:d}'.format(pi, int(pi)))" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "value of pi is 3.1416 and integer part 3\n" ] } ], "source": [ "print('value of pi is {1:6.4f} and integer part {0:d}'.format(int(pi),pi))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can also skip default values, like position argument or types" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "value of pi is 3.1416 and integer part 3\n" ] } ], "source": [ "print('value of pi is {:6.4f} and integer part {:}'.format(pi,int(pi)))" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "value of pi is 3.141592653589793 and integer part 3\n" ] } ], "source": [ "print('value of pi is {:} and integer part {:}'.format(pi,int(pi)))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Lists" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The syntax for creating list is [..,..,]\n", "\n", "The index starts with 0, like in C (not like in Fortran). Negative indices allowed.\n", "\n", "List can contain different types, and can be nested\n", "\n", "Slicing works just as with strings or arrays. Notation **[start:end:step]**, defaults can be omitted" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1 -1.1\n", "['a', -1.1]\n", "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n", "[1, 3, 5, 7, 9]\n" ] } ], "source": [ "l1=[1,'a',1.0,-1.1]\n", "print(l1[0], l1[-1])\n", "l2=[1,[1,[2,3]]] # nested list\n", "print(l1[1::2] ) # start with 1st, and take every second till the end\n", "print(list(range(10))) # range used in loops\n", "print(list(range(1,10,2))) # similar sintax: start,end,step" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[1, 3, 5, 7, 9]" ] }, "execution_count": 14, "metadata": {}, "output_type": "execute_result" } ], "source": [ "list(range(1,10,2))" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['a']" ] }, "execution_count": 15, "metadata": {}, "output_type": "execute_result" } ], "source": [ "l1[1:-1:2]" ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[1, 3, 5, 7, 9]" ] }, "execution_count": 16, "metadata": {}, "output_type": "execute_result" } ], "source": [ "list(range(1,10,2))" ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "array([[0.+1.j, 2.+0.j],\n", " [3.+0.j, 4.+0.j]])" ] }, "execution_count": 17, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from numpy import *\n", "array([[1j,2],[3,4]])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Modifying a list: \n", "* append\n", "* insert\n", "* remove\n", "* del\n" ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['A', 'd', 'f']\n", "['A', 'e', 'f']\n", "['A', 'k', 'e', 'f']\n", "['A', 'k', 'e']\n", "['A', 'e']\n" ] } ], "source": [ "l=[] # empty list\n", "l.append('A') # add at the end\n", "l.append('d')\n", "l.append('f')\n", "print(l)\n", "l[1]='e' # modify\n", "print(l)\n", "l.insert(1,'k') # insert at specific location to extent the list\n", "print(l)\n", "l.remove('f') # remove specific element, which must exist\n", "print(l)\n", "del l[1] # remove an element at specific location\n", "print(l)" ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "True\n", "[3, 4, 7, 8, 9, 10]\n" ] } ], "source": [ "a=[3,4,7,8,9,10]\n", "\n", "print(3 in a)\n", "\n", "if 10 in a:\n", " print(a)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Tuples\n", "\n", "Are like lists, except non-modifiable. \n", "\n", "Most important use in returning from a function, and use in print statement." ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "30\n", "1 20\n", "I want nice printout 3.14159\n", "a b c\n" ] } ], "source": [ "point=(10,20,30)\n", "#point[2]=2\n", "print(point[2])\n", "# point[0]=1 # can not be done\n", "point=(1,20,30) # modifying the entire tuple is allowed, i.e., it is not a constant\n", "#unpack it\n", "x,y,z = point\n", "print(x,y)\n", "\n", "\n", "print('I want nice printout %10.5f' % (pi,))\n", "\n", "def Simple():\n", " # need to return several things\n", " return ('a','b','c')\n", "\n", "x,y,z = Simple()\n", "print(x,y,z)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Dictionaries\n", "\n", "Dictionaries are like lists, but their keys are not integers, rather key can be any scalar type or tuple of scalar types\n", "\n", "Dictionary is constructed by {...}" ] }, { "cell_type": "code", "execution_count": 21, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{0: 'a', 1: 'b', 2: 'c'}\n", "a b c\n", "{300: 'c', 600: 'd', 'cde': 1, (1, 2): 5}\n", "5\n", "{300: 'c', 600: 'd', 'cde': 1, (1, 2): 5, (3, 4): 'something'}\n", "300 c\n", "600 d\n", "cde 1\n", "(1, 2) 5\n", "\n", "300 c\n", "600 d\n", "cde 1\n", "(1, 2) 5\n" ] } ], "source": [ "# This acts just like list\n", "di={}\n", "di[0]='a'\n", "di[1]='b'\n", "di[2]='c'\n", "print(di) \n", "print(di[0], di[1], di[2])\n", "\n", "# Generic keys\n", "dj={}\n", "dj[300]='c'\n", "dj[600]='d'\n", "dj['cde']=1\n", "dj[(1,2)]=5\n", "print(dj)\n", "\n", "print(dj[(1,2)])\n", "\n", "## Python2 : if dj.has_key((3,4)): \n", "if (3,4) in dj:\n", " print(dj[(3,4)])\n", "else:\n", " dj[(3,4)]='something'\n", "\n", "print(dj)\n", "\n", "\n", "\n", "# can also construct all at once\n", "dk={300:'c', 600:'d', 'cde':1, (1,2):5}\n", "\n", "\n", "# print it out by iterating over keys\n", "for k in dk.keys():\n", " print(k, dk[k])\n", "print() \n", "\n", "\n", "# print by iterating over (key,value) pairs\n", "for k,v in dk.items():\n", " print(k,v)" ] }, { "cell_type": "code", "execution_count": 22, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[300, 600, 'cde', (1, 2)]" ] }, "execution_count": 22, "metadata": {}, "output_type": "execute_result" } ], "source": [ "list(dk.keys())" ] }, { "cell_type": "code", "execution_count": 23, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[(300, 'c'), (600, 'd'), ('cde', 1), ((1, 2), 5)]" ] }, "execution_count": 23, "metadata": {}, "output_type": "execute_result" } ], "source": [ "list(dk.items())" ] }, { "cell_type": "code", "execution_count": 24, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{(100, 100): 3.141592653589793, (100, 300): 6.283185307179586}\n" ] } ], "source": [ "from math import *\n", "\n", "di={(100,100):pi,(100,300):2*pi}\n", "print(di)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Control flow\n", "\n", "* if, else, elif\n", "\n", "* loops using for & while\n", "\n", "* List comprehensions: inline for statement\n", " \n", " [ < do something with i > for i in data]" ] }, { "cell_type": "code", "execution_count": 25, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "statement2 is wrong but statement3 is true\n" ] } ], "source": [ "statement1=statement2=statement3=True\n", "statement2=False\n", "\n", "if (statement1):\n", " if (statement2):\n", " print ('both statements are true')\n", " elif (statement3):\n", " print ('statement2 is wrong but statement3 is true')\n" ] }, { "cell_type": "code", "execution_count": 26, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[4] [3]\n" ] } ], "source": [ "c=d=f=[3]\n", "d[0]=4\n", "d=[3]\n", "print(c,d)" ] }, { "cell_type": "code", "execution_count": 27, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 27, "metadata": {}, "output_type": "execute_result" } ], "source": [ "bool(100)" ] }, { "cell_type": "code", "execution_count": 28, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "-3\n", "-2\n", "-1\n", "0\n", "1\n", "2\n", "scientific\n", "computing\n", "in\n", "Python\n", "At index 0 we have string scientific\n", "At index 1 we have string computing\n", "At index 2 we have string in\n", "At index 3 we have string Python\n", "At index 0 we have string scientific\n", "At index 1 we have string computing\n", "At index 2 we have string in\n", "At index 3 we have string Python\n" ] } ], "source": [ "for x in range(-3,3,1):\n", " print(x)\n", " \n", "ls=['scientific','computing','in','Python']\n", "for word in ls:\n", " print(word)\n", " \n", "for i,word in enumerate(ls):\n", " print('At index',i, 'we have string',word)\n", " \n", "for i in range(len(ls)):\n", " word = ls[i]\n", " print('At index',i, 'we have string',word) " ] }, { "cell_type": "code", "execution_count": 29, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[(0, 'scientific'), (1, 'computing'), (2, 'in'), (3, 'Python')]" ] }, "execution_count": 29, "metadata": {}, "output_type": "execute_result" } ], "source": [ "list(enumerate(ls))" ] }, { "cell_type": "code", "execution_count": 30, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1\n", "2\n", "3\n", "4\n", "5\n" ] } ], "source": [ "i=0\n", "while i<5:\n", " i+=1\n", " print(i)" ] }, { "cell_type": "code", "execution_count": 31, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0\n", "1\n", "2\n", "3\n", "4\n" ] } ], "source": [ "for i in range(10000):\n", " if i>=5: break\n", " print(i)" ] }, { "cell_type": "code", "execution_count": 32, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[0, 1, 4, 9, 16]\n" ] } ], "source": [ "l1=[]\n", "for x in range(5):\n", " l1.append(x**2)\n", "print(l1)" ] }, { "cell_type": "code", "execution_count": 33, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[0, 1, 4, 9, 16]\n" ] } ], "source": [ "l1=[x**2 for x in range(5)]\n", "print(l1)" ] }, { "cell_type": "code", "execution_count": 34, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[(0, 0),\n", " (0, 1),\n", " (0, 2),\n", " (0, 3),\n", " (0, 4),\n", " (1, 0),\n", " (1, 1),\n", " (1, 2),\n", " (1, 3),\n", " (1, 4),\n", " (2, 0),\n", " (2, 1),\n", " (2, 2),\n", " (2, 3),\n", " (2, 4),\n", " (3, 0),\n", " (3, 1),\n", " (3, 2),\n", " (3, 3),\n", " (3, 4),\n", " (4, 0),\n", " (4, 1),\n", " (4, 2),\n", " (4, 3),\n", " (4, 4)]" ] }, "execution_count": 34, "metadata": {}, "output_type": "execute_result" } ], "source": [ "[(j,i) for j in range(5) for i in range(5)]" ] }, { "cell_type": "code", "execution_count": 35, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0 0\n", "0 1\n", "0 2\n", "0 3\n", "0 4\n", "1 0\n", "1 1\n", "1 2\n", "1 3\n", "1 4\n", "2 0\n", "2 1\n", "2 2\n", "2 3\n", "2 4\n", "3 0\n", "3 1\n", "3 2\n", "3 3\n", "3 4\n", "4 0\n", "4 1\n", "4 2\n", "4 3\n", "4 4\n" ] } ], "source": [ "for i in range(5):\n", " for j in range(5):\n", " print (i,j)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Functions\n", "\n", "* A functions starts with keyword `def`\n", "* Very useful is the `docstring`, i.e., a string at the begining, which explains what the function does\n", "* Multiple things (classes or values) can be returned by tuples\n", "* function can have default and keyword arguments" ] }, { "cell_type": "code", "execution_count": 36, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "something has 9 characters\n", "This string has 11 characters\n", "(11, 'This string')\n", "Help on function funca in module __main__:\n", "\n", "funca(s)\n", " Print a string and tell how many characters it has.\n", " Returns the length\n", "\n" ] } ], "source": [ "def funca(s):\n", " \"\"\"Print a string and tell how many characters it has.\n", " Returns the length\n", " \"\"\"\n", " \n", " print(s,'has',len(s),'characters')\n", " return (len(s),s)\n", " \n", "l,s = funca('something')\n", "\n", "print(funca('This string'))\n", "help(funca)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If we explicitly list the name of the arguments in the function calls, they do not need to come in the same order as in the function definition. This is called keyword arguments, and is often very useful in functions that takes a lot of optional arguments." ] }, { "cell_type": "code", "execution_count": 37, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'This strq'" ] }, "execution_count": 37, "metadata": {}, "output_type": "execute_result" } ], "source": [ "def funca(s,prnt=False,extra='p'):\n", " \"\"\"Print a string with extra attached, \n", " and returns new string.\n", " \"\"\"\n", " sn = s+extra\n", " if prnt:\n", " print(sn,'has',len(sn),'characters')\n", " return sn\n", "\n", "funca('This str',extra='q')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Unnamed functions (lambda function)\n", "\n", "In Python we can also create unnamed functions, using the lambda keyword:" ] }, { "cell_type": "code", "execution_count": 38, "metadata": {}, "outputs": [], "source": [ "def f2(x):\n", " return x**2\n", "\n", "# is equivalent to\n", "\n", "f1 = lambda x: x**2" ] }, { "cell_type": "code", "execution_count": 39, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(9, 9)" ] }, "execution_count": 39, "metadata": {}, "output_type": "execute_result" } ], "source": [ "f1(3), f2(3)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This technique is useful for example when we want to pass a simple function as an argument to another function, like this:" ] }, { "cell_type": "code", "execution_count": 40, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Help on function quad in module scipy.integrate._quadpack_py:\n", "\n", "quad(func, a, b, args=(), full_output=0, epsabs=1.49e-08, epsrel=1.49e-08, limit=50, points=None, weight=None, wvar=None, wopts=None, maxp1=50, limlst=50)\n", " Compute a definite integral.\n", " \n", " Integrate func from `a` to `b` (possibly infinite interval) using a\n", " technique from the Fortran library QUADPACK.\n", " \n", " Parameters\n", " ----------\n", " func : {function, scipy.LowLevelCallable}\n", " A Python function or method to integrate. If `func` takes many\n", " arguments, it is integrated along the axis corresponding to the\n", " first argument.\n", " \n", " If the user desires improved integration performance, then `f` may\n", " be a `scipy.LowLevelCallable` with one of the signatures::\n", " \n", " double func(double x)\n", " double func(double x, void *user_data)\n", " double func(int n, double *xx)\n", " double func(int n, double *xx, void *user_data)\n", " \n", " The ``user_data`` is the data contained in the `scipy.LowLevelCallable`.\n", " In the call forms with ``xx``, ``n`` is the length of the ``xx``\n", " array which contains ``xx[0] == x`` and the rest of the items are\n", " numbers contained in the ``args`` argument of quad.\n", " \n", " In addition, certain ctypes call signatures are supported for\n", " backward compatibility, but those should not be used in new code.\n", " a : float\n", " Lower limit of integration (use -numpy.inf for -infinity).\n", " b : float\n", " Upper limit of integration (use numpy.inf for +infinity).\n", " args : tuple, optional\n", " Extra arguments to pass to `func`.\n", " full_output : int, optional\n", " Non-zero to return a dictionary of integration information.\n", " If non-zero, warning messages are also suppressed and the\n", " message is appended to the output tuple.\n", " \n", " Returns\n", " -------\n", " y : float\n", " The integral of func from `a` to `b`.\n", " abserr : float\n", " An estimate of the absolute error in the result.\n", " infodict : dict\n", " A dictionary containing additional information.\n", " message\n", " A convergence message.\n", " explain\n", " Appended only with 'cos' or 'sin' weighting and infinite\n", " integration limits, it contains an explanation of the codes in\n", " infodict['ierlst']\n", " \n", " Other Parameters\n", " ----------------\n", " epsabs : float or int, optional\n", " Absolute error tolerance. Default is 1.49e-8. `quad` tries to obtain\n", " an accuracy of ``abs(i-result) <= max(epsabs, epsrel*abs(i))``\n", " where ``i`` = integral of `func` from `a` to `b`, and ``result`` is the\n", " numerical approximation. See `epsrel` below.\n", " epsrel : float or int, optional\n", " Relative error tolerance. Default is 1.49e-8.\n", " If ``epsabs <= 0``, `epsrel` must be greater than both 5e-29\n", " and ``50 * (machine epsilon)``. See `epsabs` above.\n", " limit : float or int, optional\n", " An upper bound on the number of subintervals used in the adaptive\n", " algorithm.\n", " points : (sequence of floats,ints), optional\n", " A sequence of break points in the bounded integration interval\n", " where local difficulties of the integrand may occur (e.g.,\n", " singularities, discontinuities). The sequence does not have\n", " to be sorted. Note that this option cannot be used in conjunction\n", " with ``weight``.\n", " weight : float or int, optional\n", " String indicating weighting function. Full explanation for this\n", " and the remaining arguments can be found below.\n", " wvar : optional\n", " Variables for use with weighting functions.\n", " wopts : optional\n", " Optional input for reusing Chebyshev moments.\n", " maxp1 : float or int, optional\n", " An upper bound on the number of Chebyshev moments.\n", " limlst : int, optional\n", " Upper bound on the number of cycles (>=3) for use with a sinusoidal\n", " weighting and an infinite end-point.\n", " \n", " See Also\n", " --------\n", " dblquad : double integral\n", " tplquad : triple integral\n", " nquad : n-dimensional integrals (uses `quad` recursively)\n", " fixed_quad : fixed-order Gaussian quadrature\n", " quadrature : adaptive Gaussian quadrature\n", " odeint : ODE integrator\n", " ode : ODE integrator\n", " simpson : integrator for sampled data\n", " romb : integrator for sampled data\n", " scipy.special : for coefficients and roots of orthogonal polynomials\n", " \n", " Notes\n", " -----\n", " \n", " **Extra information for quad() inputs and outputs**\n", " \n", " If full_output is non-zero, then the third output argument\n", " (infodict) is a dictionary with entries as tabulated below. For\n", " infinite limits, the range is transformed to (0,1) and the\n", " optional outputs are given with respect to this transformed range.\n", " Let M be the input argument limit and let K be infodict['last'].\n", " The entries are:\n", " \n", " 'neval'\n", " The number of function evaluations.\n", " 'last'\n", " The number, K, of subintervals produced in the subdivision process.\n", " 'alist'\n", " A rank-1 array of length M, the first K elements of which are the\n", " left end points of the subintervals in the partition of the\n", " integration range.\n", " 'blist'\n", " A rank-1 array of length M, the first K elements of which are the\n", " right end points of the subintervals.\n", " 'rlist'\n", " A rank-1 array of length M, the first K elements of which are the\n", " integral approximations on the subintervals.\n", " 'elist'\n", " A rank-1 array of length M, the first K elements of which are the\n", " moduli of the absolute error estimates on the subintervals.\n", " 'iord'\n", " A rank-1 integer array of length M, the first L elements of\n", " which are pointers to the error estimates over the subintervals\n", " with ``L=K`` if ``K<=M/2+2`` or ``L=M+1-K`` otherwise. Let I be the\n", " sequence ``infodict['iord']`` and let E be the sequence\n", " ``infodict['elist']``. Then ``E[I[1]], ..., E[I[L]]`` forms a\n", " decreasing sequence.\n", " \n", " If the input argument points is provided (i.e., it is not None),\n", " the following additional outputs are placed in the output\n", " dictionary. Assume the points sequence is of length P.\n", " \n", " 'pts'\n", " A rank-1 array of length P+2 containing the integration limits\n", " and the break points of the intervals in ascending order.\n", " This is an array giving the subintervals over which integration\n", " will occur.\n", " 'level'\n", " A rank-1 integer array of length M (=limit), containing the\n", " subdivision levels of the subintervals, i.e., if (aa,bb) is a\n", " subinterval of ``(pts[1], pts[2])`` where ``pts[0]`` and ``pts[2]``\n", " are adjacent elements of ``infodict['pts']``, then (aa,bb) has level l\n", " if ``|bb-aa| = |pts[2]-pts[1]| * 2**(-l)``.\n", " 'ndin'\n", " A rank-1 integer array of length P+2. After the first integration\n", " over the intervals (pts[1], pts[2]), the error estimates over some\n", " of the intervals may have been increased artificially in order to\n", " put their subdivision forward. This array has ones in slots\n", " corresponding to the subintervals for which this happens.\n", " \n", " **Weighting the integrand**\n", " \n", " The input variables, *weight* and *wvar*, are used to weight the\n", " integrand by a select list of functions. Different integration\n", " methods are used to compute the integral with these weighting\n", " functions, and these do not support specifying break points. The\n", " possible values of weight and the corresponding weighting functions are.\n", " \n", " ========== =================================== =====================\n", " ``weight`` Weight function used ``wvar``\n", " ========== =================================== =====================\n", " 'cos' cos(w*x) wvar = w\n", " 'sin' sin(w*x) wvar = w\n", " 'alg' g(x) = ((x-a)**alpha)*((b-x)**beta) wvar = (alpha, beta)\n", " 'alg-loga' g(x)*log(x-a) wvar = (alpha, beta)\n", " 'alg-logb' g(x)*log(b-x) wvar = (alpha, beta)\n", " 'alg-log' g(x)*log(x-a)*log(b-x) wvar = (alpha, beta)\n", " 'cauchy' 1/(x-c) wvar = c\n", " ========== =================================== =====================\n", " \n", " wvar holds the parameter w, (alpha, beta), or c depending on the weight\n", " selected. In these expressions, a and b are the integration limits.\n", " \n", " For the 'cos' and 'sin' weighting, additional inputs and outputs are\n", " available.\n", " \n", " For finite integration limits, the integration is performed using a\n", " Clenshaw-Curtis method which uses Chebyshev moments. For repeated\n", " calculations, these moments are saved in the output dictionary:\n", " \n", " 'momcom'\n", " The maximum level of Chebyshev moments that have been computed,\n", " i.e., if ``M_c`` is ``infodict['momcom']`` then the moments have been\n", " computed for intervals of length ``|b-a| * 2**(-l)``,\n", " ``l=0,1,...,M_c``.\n", " 'nnlog'\n", " A rank-1 integer array of length M(=limit), containing the\n", " subdivision levels of the subintervals, i.e., an element of this\n", " array is equal to l if the corresponding subinterval is\n", " ``|b-a|* 2**(-l)``.\n", " 'chebmo'\n", " A rank-2 array of shape (25, maxp1) containing the computed\n", " Chebyshev moments. These can be passed on to an integration\n", " over the same interval by passing this array as the second\n", " element of the sequence wopts and passing infodict['momcom'] as\n", " the first element.\n", " \n", " If one of the integration limits is infinite, then a Fourier integral is\n", " computed (assuming w neq 0). If full_output is 1 and a numerical error\n", " is encountered, besides the error message attached to the output tuple,\n", " a dictionary is also appended to the output tuple which translates the\n", " error codes in the array ``info['ierlst']`` to English messages. The\n", " output information dictionary contains the following entries instead of\n", " 'last', 'alist', 'blist', 'rlist', and 'elist':\n", " \n", " 'lst'\n", " The number of subintervals needed for the integration (call it ``K_f``).\n", " 'rslst'\n", " A rank-1 array of length M_f=limlst, whose first ``K_f`` elements\n", " contain the integral contribution over the interval\n", " ``(a+(k-1)c, a+kc)`` where ``c = (2*floor(|w|) + 1) * pi / |w|``\n", " and ``k=1,2,...,K_f``.\n", " 'erlst'\n", " A rank-1 array of length ``M_f`` containing the error estimate\n", " corresponding to the interval in the same position in\n", " ``infodict['rslist']``.\n", " 'ierlst'\n", " A rank-1 integer array of length ``M_f`` containing an error flag\n", " corresponding to the interval in the same position in\n", " ``infodict['rslist']``. See the explanation dictionary (last entry\n", " in the output tuple) for the meaning of the codes.\n", " \n", " \n", " **Details of QUADPACK level routines**\n", " \n", " `quad` calls routines from the FORTRAN library QUADPACK. This section\n", " provides details on the conditions for each routine to be called and a\n", " short description of each routine. The routine called depends on\n", " `weight`, `points` and the integration limits `a` and `b`.\n", " \n", " ================ ============== ========== =====================\n", " QUADPACK routine `weight` `points` infinite bounds\n", " ================ ============== ========== =====================\n", " qagse None No No\n", " qagie None No Yes\n", " qagpe None Yes No\n", " qawoe 'sin', 'cos' No No\n", " qawfe 'sin', 'cos' No either `a` or `b`\n", " qawse 'alg*' No No\n", " qawce 'cauchy' No No\n", " ================ ============== ========== =====================\n", " \n", " The following provides a short desciption from [1]_ for each\n", " routine.\n", " \n", " qagse\n", " is an integrator based on globally adaptive interval\n", " subdivision in connection with extrapolation, which will\n", " eliminate the effects of integrand singularities of\n", " several types.\n", " qagie\n", " handles integration over infinite intervals. The infinite range is\n", " mapped onto a finite interval and subsequently the same strategy as\n", " in ``QAGS`` is applied.\n", " qagpe\n", " serves the same purposes as QAGS, but also allows the\n", " user to provide explicit information about the location\n", " and type of trouble-spots i.e. the abscissae of internal\n", " singularities, discontinuities and other difficulties of\n", " the integrand function.\n", " qawoe\n", " is an integrator for the evaluation of\n", " :math:`\\int^b_a \\cos(\\omega x)f(x)dx` or\n", " :math:`\\int^b_a \\sin(\\omega x)f(x)dx`\n", " over a finite interval [a,b], where :math:`\\omega` and :math:`f`\n", " are specified by the user. The rule evaluation component is based\n", " on the modified Clenshaw-Curtis technique\n", " \n", " An adaptive subdivision scheme is used in connection\n", " with an extrapolation procedure, which is a modification\n", " of that in ``QAGS`` and allows the algorithm to deal with\n", " singularities in :math:`f(x)`.\n", " qawfe\n", " calculates the Fourier transform\n", " :math:`\\int^\\infty_a \\cos(\\omega x)f(x)dx` or\n", " :math:`\\int^\\infty_a \\sin(\\omega x)f(x)dx`\n", " for user-provided :math:`\\omega` and :math:`f`. The procedure of\n", " ``QAWO`` is applied on successive finite intervals, and convergence\n", " acceleration by means of the :math:`\\varepsilon`-algorithm is applied\n", " to the series of integral approximations.\n", " qawse\n", " approximate :math:`\\int^b_a w(x)f(x)dx`, with :math:`a < b` where\n", " :math:`w(x) = (x-a)^{\\alpha}(b-x)^{\\beta}v(x)` with\n", " :math:`\\alpha,\\beta > -1`, where :math:`v(x)` may be one of the\n", " following functions: :math:`1`, :math:`\\log(x-a)`, :math:`\\log(b-x)`,\n", " :math:`\\log(x-a)\\log(b-x)`.\n", " \n", " The user specifies :math:`\\alpha`, :math:`\\beta` and the type of the\n", " function :math:`v`. A globally adaptive subdivision strategy is\n", " applied, with modified Clenshaw-Curtis integration on those\n", " subintervals which contain `a` or `b`.\n", " qawce\n", " compute :math:`\\int^b_a f(x) / (x-c)dx` where the integral must be\n", " interpreted as a Cauchy principal value integral, for user specified\n", " :math:`c` and :math:`f`. The strategy is globally adaptive. Modified\n", " Clenshaw-Curtis integration is used on those intervals containing the\n", " point :math:`x = c`.\n", " \n", " References\n", " ----------\n", " \n", " .. [1] Piessens, Robert; de Doncker-Kapenga, Elise;\n", " Überhuber, Christoph W.; Kahaner, David (1983).\n", " QUADPACK: A subroutine package for automatic integration.\n", " Springer-Verlag.\n", " ISBN 978-3-540-12553-2.\n", " \n", " Examples\n", " --------\n", " Calculate :math:`\\int^4_0 x^2 dx` and compare with an analytic result\n", " \n", " >>> from scipy import integrate\n", " >>> x2 = lambda x: x**2\n", " >>> integrate.quad(x2, 0, 4)\n", " (21.333333333333332, 2.3684757858670003e-13)\n", " >>> print(4**3 / 3.) # analytical result\n", " 21.3333333333\n", " \n", " Calculate :math:`\\int^\\infty_0 e^{-x} dx`\n", " \n", " >>> invexp = lambda x: np.exp(-x)\n", " >>> integrate.quad(invexp, 0, np.inf)\n", " (1.0, 5.842605999138044e-11)\n", " \n", " Calculate :math:`\\int^1_0 a x \\,dx` for :math:`a = 1, 3`\n", " \n", " >>> f = lambda x, a: a*x\n", " >>> y, err = integrate.quad(f, 0, 1, args=(1,))\n", " >>> y\n", " 0.5\n", " >>> y, err = integrate.quad(f, 0, 1, args=(3,))\n", " >>> y\n", " 1.5\n", " \n", " Calculate :math:`\\int^1_0 x^2 + y^2 dx` with ctypes, holding\n", " y parameter as 1::\n", " \n", " testlib.c =>\n", " double func(int n, double args[n]){\n", " return args[0]*args[0] + args[1]*args[1];}\n", " compile to library testlib.*\n", " \n", " ::\n", " \n", " from scipy import integrate\n", " import ctypes\n", " lib = ctypes.CDLL('/home/.../testlib.*') #use absolute path\n", " lib.func.restype = ctypes.c_double\n", " lib.func.argtypes = (ctypes.c_int,ctypes.c_double)\n", " integrate.quad(lib.func,0,1,(1))\n", " #(1.3333333333333333, 1.4802973661668752e-14)\n", " print((1.0**3/3.0 + 1.0) - (0.0**3/3.0 + 0.0)) #Analytic result\n", " # 1.3333333333333333\n", " \n", " Be aware that pulse shapes and other sharp features as compared to the\n", " size of the integration interval may not be integrated correctly using\n", " this method. A simplified example of this limitation is integrating a\n", " y-axis reflected step function with many zero values within the integrals\n", " bounds.\n", " \n", " >>> y = lambda x: 1 if x<=0 else 0\n", " >>> integrate.quad(y, -1, 1)\n", " (1.0, 1.1102230246251565e-14)\n", " >>> integrate.quad(y, -1, 100)\n", " (1.0000000002199108, 1.0189464580163188e-08)\n", " >>> integrate.quad(y, -1, 10000)\n", " (0.0, 0.0)\n", "\n" ] } ], "source": [ "from scipy import integrate\n", "help(integrate.quad)" ] }, { "cell_type": "code", "execution_count": 41, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(0.33333333333333337, 3.700743415417189e-15)" ] }, "execution_count": 41, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from scipy import integrate\n", "from numpy import *\n", "\n", "def square(x):\n", " return x**2\n", "\n", "\n", "integrate.quad(lambda x: sin(x)/x,0,1)\n", "integrate.quad(square, 0,1,)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Classes\n", "\n", "A class can contain attributes (variables) and methods (functions).\n", "\n", "A class is defined by `class` keyword, and the class can contains a number of class method definitions (a function in a class).\n", "\n", "* Each class method should have an argument self as its first argument. This object is a self-reference.\n", "* Some class method names have special meaning, for example:\n", " * `__init__` : Constructor, i.e., the name of the method that is invoked when the object is first created.\n", " * `__str__` : A method that is invoked when a simple string representation of the class is needed, as for example when printed.\n", " * `__repr__` : Representation of the class when printed\n", " * `__call__` : Functor, i.e, called when the instance is “called” as a function\n", " * There are many more, see http://docs.python.org/2/reference/datamodel.html#special-method-names\n", " * Note: each class member starting with __ is private. If it does not start with __, it is public." ] }, { "cell_type": "code", "execution_count": 42, "metadata": {}, "outputs": [], "source": [ "class Point:\n", " \"\"\"\n", " Simple class for representing a point in a Cartesian coordinate system.\n", " \"\"\"\n", " def __init__(self, x, y):\n", " \"\"\"\n", " Create a new Point at x, y.\n", " \"\"\"\n", " self.x = x\n", " self.y = y\n", " #print('you gave me x and y=', x, y)\n", " def translate(self, dx, dy):\n", " \"\"\"\n", " Translate the point by dx and dy in the x and y direction.\n", " \"\"\"\n", " self.x += dx\n", " self.y += dy\n", " self.t = 1.0\n", " \n", " def __str__(self): \n", " return(\"Point at [%f, %f]\" % (self.x, self.y))\n", " def __call__(self,z):\n", " return self.x,self.y,z" ] }, { "cell_type": "code", "execution_count": 43, "metadata": { "scrolled": true }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "3.0 4.0 1.0\n", "Point at [3.000000, 4.000000]\n" ] }, { "data": { "text/plain": [ "(3.0, 4.0, 4.5)" ] }, "execution_count": 43, "metadata": {}, "output_type": "execute_result" } ], "source": [ "q = Point(2., 3.0)\n", "\n", "q.translate(1,1)\n", "\n", "print(q.x, q.y, q.t)\n", "print(q)\n", "q(4.5)" ] }, { "cell_type": "code", "execution_count": 44, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Point at [1.000000, 2.000000]\n", "Point at [2.000000, 3.000000]\n", "(2.0, 3.0, 1.0)\n", "2.0 3.0\n" ] } ], "source": [ "p = Point(1.,2.)\n", "\n", "print( p )\n", "\n", "p.translate(1,1)\n", "\n", "print(p)\n", "\n", "print(p(1.0))\n", "\n", "print(p.x,p.y)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Modules\n", "\n", "For additional modularity, modules are provided in Python.\n", "\n", "The modularity in Python is:\n", "* variables, functions\n", "* classes, which combine variables and functions\n", "* modules, which combine classes, variables and functions into a unit, usually a file\n", "\n", "Module is a python file (`*.py`) or a module created by compiler (`*.so`)\n", "\n", "Outside jupyter (in regular python) we just create a file with the code, and call it a module.\n", "\n", "Within jupyter, we need to write code into a file, and than load the module (file)." ] }, { "cell_type": "code", "execution_count": 45, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Overwriting mymodule.py\n" ] } ], "source": [ "%%file mymodule.py \n", "# This will write the following content into a file\n", "\"\"\"\n", "Example of a python module. Contains a variable called my_variable,\n", "a function called my_function, and a class called MyClass.\n", "\"\"\"\n", "\n", "my_variable = 0\n", "\n", "def my_function():\n", " \"\"\"\n", " Example function\n", " \"\"\"\n", " return my_variable\n", " \n", "class MyClass:\n", " \"\"\"\n", " Example class.\n", " \"\"\"\n", "\n", " def __init__(self):\n", " self.variable = my_variable\n", " \n", " def set_variable(self, new_value):\n", " \"\"\"\n", " Set self.variable to a new value\n", " \"\"\"\n", " self.variable = new_value\n", " \n", " def get_variable(self):\n", " return self.variable\n", " \n", "print(__name__)\n", "\n", "if __name__ == '__main__':\n", " \"test the module\"\n", " m = MyClass()\n", " m.set_variable(1.)\n", " print(m.get_variable())" ] }, { "cell_type": "code", "execution_count": 46, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "# This will write the following content into a file\r\n", "\"\"\"\r\n", "Example of a python module. Contains a variable called my_variable,\r\n", "a function called my_function, and a class called MyClass.\r\n", "\"\"\"\r\n", "\r\n", "my_variable = 0\r\n", "\r\n", "def my_function():\r\n", " \"\"\"\r\n", " Example function\r\n", " \"\"\"\r\n", " return my_variable\r\n", " \r\n", "class MyClass:\r\n", " \"\"\"\r\n", " Example class.\r\n", " \"\"\"\r\n", "\r\n", " def __init__(self):\r\n", " self.variable = my_variable\r\n", " \r\n", " def set_variable(self, new_value):\r\n", " \"\"\"\r\n", " Set self.variable to a new value\r\n", " \"\"\"\r\n", " self.variable = new_value\r\n", " \r\n", " def get_variable(self):\r\n", " return self.variable\r\n", " \r\n", "print(__name__)\r\n", "\r\n", "if __name__ == '__main__':\r\n", " \"test the module\"\r\n", " m = MyClass()\r\n", " m.set_variable(1.)\r\n", " print(m.get_variable())\r\n" ] } ], "source": [ "!cat mymodule.py" ] }, { "cell_type": "code", "execution_count": 47, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "mymodule\n" ] } ], "source": [ "import mymodule as my\n", "import scipy as sy\n", "#help(mymodule)" ] }, { "cell_type": "code", "execution_count": 48, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "10" ] }, "execution_count": 48, "metadata": {}, "output_type": "execute_result" } ], "source": [ "m = my.MyClass()\n", "m.set_variable(10)\n", "m.get_variable()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "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.8.18" } }, "nbformat": 4, "nbformat_minor": 4 }