From 104717cfe74abd7e5f61159e2d00e8de8149e528 Mon Sep 17 00:00:00 2001 From: Jan Benda Date: Tue, 12 Jun 2018 10:17:53 +0200 Subject: [PATCH] added Fabians python tutorial scripts --- resources/python/loaddat.py | 46 +++++++++++ resources/python/synchronization.py | 46 +++++++++++ resources/python/test.dat | 22 ++++++ resources/python/tutorial/01FirstProgram.py | 4 + resources/python/tutorial/02DataStructure.py | 79 +++++++++++++++++++ resources/python/tutorial/03numpy.py | 72 +++++++++++++++++ resources/python/tutorial/04plotting.py | 20 +++++ resources/python/tutorial/05plotting2.py | 28 +++++++ resources/python/tutorial/06functions.py | 34 ++++++++ .../python/tutorial/07controlStructure.py | 55 +++++++++++++ 10 files changed, 406 insertions(+) create mode 100644 resources/python/loaddat.py create mode 100644 resources/python/synchronization.py create mode 100644 resources/python/test.dat create mode 100644 resources/python/tutorial/01FirstProgram.py create mode 100644 resources/python/tutorial/02DataStructure.py create mode 100644 resources/python/tutorial/03numpy.py create mode 100644 resources/python/tutorial/04plotting.py create mode 100644 resources/python/tutorial/05plotting2.py create mode 100644 resources/python/tutorial/06functions.py create mode 100644 resources/python/tutorial/07controlStructure.py diff --git a/resources/python/loaddat.py b/resources/python/loaddat.py new file mode 100644 index 0000000..3850ca1 --- /dev/null +++ b/resources/python/loaddat.py @@ -0,0 +1,46 @@ +import numpy as np + +def is_float( s ): + try: + float(s) + return True + except ValueError: + return False + +def loaddat( filename ): + """ Load ascii data files into a numpy array + """ + mdata = {} + tdata = [] + for l in open( filename ) : + if l.startswith( "#" ) : + if ":" in l : + tmp = [e.strip() for e in l[1:].partition(':')] + mdata[tmp[0]] = tmp[2] + elif l and not l.isspace() : + vals = [ float( i ) for i in l.split() if is_float( i ) ] + if len( vals ) > 0 : + tdata.append( vals[0] ) + elif len( tdata ) > 0 : + break + return tdata, mdata + +d,m = loaddat('../Pholidoptera_litoralis/Time_stamps/Chang/sychronization_2013-07-31-102053h_5-msec.dat') + +# the dictionary of meta data: +print m +print +# use the value of a specific metadata item: +print 'The animal number was: ', m['Animal'] +print + +# the data array: +print d +print + +# the fifth value of the data array: +print 'The sixth data value: ', d[0] +print + + + diff --git a/resources/python/synchronization.py b/resources/python/synchronization.py new file mode 100644 index 0000000..3850ca1 --- /dev/null +++ b/resources/python/synchronization.py @@ -0,0 +1,46 @@ +import numpy as np + +def is_float( s ): + try: + float(s) + return True + except ValueError: + return False + +def loaddat( filename ): + """ Load ascii data files into a numpy array + """ + mdata = {} + tdata = [] + for l in open( filename ) : + if l.startswith( "#" ) : + if ":" in l : + tmp = [e.strip() for e in l[1:].partition(':')] + mdata[tmp[0]] = tmp[2] + elif l and not l.isspace() : + vals = [ float( i ) for i in l.split() if is_float( i ) ] + if len( vals ) > 0 : + tdata.append( vals[0] ) + elif len( tdata ) > 0 : + break + return tdata, mdata + +d,m = loaddat('../Pholidoptera_litoralis/Time_stamps/Chang/sychronization_2013-07-31-102053h_5-msec.dat') + +# the dictionary of meta data: +print m +print +# use the value of a specific metadata item: +print 'The animal number was: ', m['Animal'] +print + +# the data array: +print d +print + +# the fifth value of the data array: +print 'The sixth data value: ', d[0] +print + + + diff --git a/resources/python/test.dat b/resources/python/test.dat new file mode 100644 index 0000000..3485c06 --- /dev/null +++ b/resources/python/test.dat @@ -0,0 +1,22 @@ +# Description : Times of song onsets and offsets since midnight +# Species : synchronization +# Animal : 5 +# Experimenter: Chang +# Temperature : +# Comment : +# Date : 2013-08-02 +# Time : 22:12:24 + +#Key +# onset index +# ms 1 + 79991439 1 + 79993821 2 + 79996020 3 + 79998296 4 + 80000457 5 + 80002639 6 + 80004818 7 + 80006942 8 + 80008997 9 + 80011121 10 diff --git a/resources/python/tutorial/01FirstProgram.py b/resources/python/tutorial/01FirstProgram.py new file mode 100644 index 0000000..1b8fbca --- /dev/null +++ b/resources/python/tutorial/01FirstProgram.py @@ -0,0 +1,4 @@ +print "Hello World" + +# for the advanced +print "%i times hello, %s and %s" % (2, "Jan", "Fabian") diff --git a/resources/python/tutorial/02DataStructure.py b/resources/python/tutorial/02DataStructure.py new file mode 100644 index 0000000..4b40d3e --- /dev/null +++ b/resources/python/tutorial/02DataStructure.py @@ -0,0 +1,79 @@ + +################## Lists ############################ +# lists are simple data structures that can hold different data types + +a = [1,2,'hallo'] +print a + +# lists are accessed by indices, starting with 0 +print a[0] + +a[0] = 5 + +print a + +# lists can be indexed with slices, first index is included, the last is not +print a[0:2] + +# if the index is ommitted, then the maximal or minimal index is taken +print a[1:] +print a[:1] + +# negative indices count downwards from the maximal index +print a[:-1] + +# one can also specify steps in slices (start:stop:step) +print a[0:3:2] +print a[1::2] + +# if new variables are assigned to an existing list, the list is NOT copied +b = a +b[2] = 0 +print a + +# if you want to copy lists, use +b = list(a) +b[2] = 'new stuff' +print a +print b +# lists of lists +b = [1,2,3, [4,3,5]] +print b[3][1:] + +################### Tuples ##################################### +# tuples are constant lists. They behave basically like lists but don't allow elements to be set +b = (1,2,'hello') +print b +print b[::2] +# b[2] = "test" # error! + +################### Dictionaries ############################### +# Dictionaries are like lists that can be accessed with arbitraty +# keys. They are initialized with curly brackets and key:value pairs +c = {'key1':2, 3.4:'something else', 5:6} +print c.keys() +print c.values() +print c.items() +print c +print c['key1'] +c[3.4] = 'again something else' +print c + +# again, dictionaries are not copied +d = c +d[5] = 8 +print c + + +############## Numerical types ################################## +# mostly, python determines the numerical type of a number. However, +# sometimes one needs to pay attention when dealing with integers + +a = 1 +b = 5 +print a/b + +# initialization as float or the function float(a) help +a = 1. +b = 5. +print a/b diff --git a/resources/python/tutorial/03numpy.py b/resources/python/tutorial/03numpy.py new file mode 100644 index 0000000..3893935 --- /dev/null +++ b/resources/python/tutorial/03numpy.py @@ -0,0 +1,72 @@ +# first step: import numpy +# there are different ways to do so + +# import numpy --> everything has to be access via e.g. numpy.cos(x) +# import numpy as np --> name numpy np, which means that everything can be accessed via e.g. np.cos(x) +# from numpy import cos, sin --> only import cosine and sine +# from numpy import cos as cosine --> only import cos and name it cosine +# from numpy import * --> import everything. + +# for the moment, we use option 5 +from numpy import * + +# numpy uses arrays which can be though of as lists with a single datatype +# they can be initialized form a list +a = array([1.,2.,3.]) +b = array([[1,2],[4,5.]]) +print a + +# in numpy many commands have the same name as in matlab. For example +# for creating base points for plotting, you can use + +x = linspace(-2.,2.,9) # creates an array with 1000 points between -2 and 2 + +# arithmetic operation are elementwise, double asterics is power +y = 2*x + 2 +y = x+x +y = x**2. - 1. + + +# matplotlib implements many functions, such as matlab +y = cos(x) +y = exp(x) +print y + +# just like matlab, numpy arrays support logical indexing +xp = x[x > 0] +yp = log(xp) # example + +xp = x[x > 0] +inx=where(x>0) +print inx +print x[inx] + +# arrays can also be two dimensional +x = zeros( (3,2) ) # zeros takes a tuple +print x +x[2,1] = 1. +print x +print x > 0 +print x[x > 0] + +# other useful functions to generate arrays +x = random.randn(4,3) # unfortunately, the size specification is implemented inconsistently +x = ones( (3,3) ) + + +# another very useful feature is this +x = random.randn(3,1) # column vector +y = random.randn(1,4) # row vector +print x +print y +print x+y # result is a matrix +print x/y + +# works also with 2d arrays and vectors +x = random.randn(3,1) # column vector +z = random.randn(1,4) # row vector +y = random.randn(3,4) # 2d array + +print y-x # columnwise subtraction +print y-z # rowwise subtraction + diff --git a/resources/python/tutorial/04plotting.py b/resources/python/tutorial/04plotting.py new file mode 100644 index 0000000..ea3b050 --- /dev/null +++ b/resources/python/tutorial/04plotting.py @@ -0,0 +1,20 @@ +from numpy import * +from matplotlib.pyplot import * + +# google matplotlib gallery + +# create basepoints and function values +x = linspace(-2., 2., 100) +y = (x + 2.)**2 - 5. +fig = figure() # create figure +ax = fig.add_subplot(1,1,1) # subplot with 1 row, 1 column, and get axes of first plot +ax.plot(x,y) + +ax.set_xlabel('x values') +ax.set_ylabel('y values') +ax.set_title('quadratic function') + +show() # show plot + +fig.savefig( "test.pdf" ) # saves plot into file + diff --git a/resources/python/tutorial/05plotting2.py b/resources/python/tutorial/05plotting2.py new file mode 100644 index 0000000..dda3306 --- /dev/null +++ b/resources/python/tutorial/05plotting2.py @@ -0,0 +1,28 @@ +from numpy import * +from matplotlib.pyplot import * + +# create basepoints and function values +x = linspace(-2., 2., 100) +y = (x + 2.)**2 - 5. +y2 = (x + 1.)**2 + 2.3 + +fig = figure() +ax = fig.add_subplot(1,1,1) + +# 1) additional parameters can either be specified in the correct +# order or via named parameters +# +# 2) If an r preceeds a string, the result is rendered from latex +# +# 3) Specifying the names argument "label" sets the label for a legend +# +ax.plot(x, y, color='r', linewidth=2, label=r'$(x+2)^2 - 5$') +ax.plot(x, y2, color='b', linewidth=2, label=r'$(x+1)^2 + 2.3$') + +ax.set_xlabel('x values') +ax.set_ylabel(r'$f(x)$') +ax.set_title('quadratic function') +leg = ax.legend() + +show() # show plot + diff --git a/resources/python/tutorial/06functions.py b/resources/python/tutorial/06functions.py new file mode 100644 index 0000000..262a161 --- /dev/null +++ b/resources/python/tutorial/06functions.py @@ -0,0 +1,34 @@ +from numpy import * +from matplotlib.pyplot import * + + +# functions are defined via def (don't forget the :) +# return is defined via the return keyword +def myfunc(x): + tmp = 2*x**3. + 5 + return tmp + +# when using more parameters one can give them default values +def myfunc2(x, a=1., b=5.): + return (x - a)**2. + b + + +############# main program below (old stuff) ############## + +x = linspace(-2., 2., 100) + +fig = figure() +ax = fig.add_subplot(1,1,1) + +ax.plot(x, myfunc(x), color='r', linewidth=2, label='myfunc') +ax.plot(x, myfunc2(x, 2., 4.), color='b', linewidth=2, label=r'myfunc2 a=2, b=4') +ax.plot(x, myfunc2(x, 2.), color='g', linewidth=2, label=r'myfunc2 a=2, b=default') +ax.plot(x, myfunc2(x, b=2.), color='y', linewidth=2, label=r'myfunc2 a=default, b=2') + +ax.set_xlabel('x values') +ax.set_ylabel(r'$f(x)$') +ax.set_title('functions') +leg = ax.legend() + +show() # show plot + diff --git a/resources/python/tutorial/07controlStructure.py b/resources/python/tutorial/07controlStructure.py new file mode 100644 index 0000000..ad4c2c4 --- /dev/null +++ b/resources/python/tutorial/07controlStructure.py @@ -0,0 +1,55 @@ +from numpy import * + +# if statments are fairly straightforward +if True: + print "True" + +if False: + print "False" + +a = 2 +if a == 2: + print "a equals 2" +else: + print "a does not equal 2" + +# different conditions are combined via "and" and "or" +b = 5 + +if a == 2 and b > 4: + print "a equals 2 and b is greater than 4" +elif b > 3: + print "at least b is greater 3" + +# for loops start with general structure "for element in list:" +for elem in [1,2,3,4,8]: + print elem + +# in many +for j in xrange(10): + print j + +print 80*'-' +# this works e.g. with arrays +x = random.randn(10) +for rv in x: + print rv + +print 80*'-' +# for loops also take iterators which can be thought of as lists +for i,rx in enumerate(x): + print i + print x + +print 80*'-' +y = random.randn(10) +for xy in zip(x,y): + print xy + +print 80*'-' + +f = lambda z: z**2 + 3. +print [f(elem) for elem in x if elem < 1] + +def quicksort(x): + return x if len(x)<=1 else quicksort([e for e in x if e < x[0]]) + [x[0]] + quicksort([e for e in x if e > x[0]])