Contents and Objective

Cell Types

There are two types of cells:

  • Text cells (called 'Markdown'): containing text, allowing use of LaTeX
  • Math/code cells: where code is being executed

As long as you are just reading the simulations, there is no need to be concerned about this fact.

Data Structures

  • In the following sections the basic data structures used in upcoming simulations will be introduced.
  • Basic types as int, float, string are supposed to be well-known.

Lists

  • Container-type structure for collecting entities (which may even be of different type)
  • Defined by key word list( ) or by square brackets with entities being separated by comma
  • Referenced by index in square brackets; Note: indexing starting at 0
  • Entries may be changed, appended, sliced,...

In [1]:
# defining lists
sport_list = [ 'cycling', 'football', 'fitness' ]
first_prime_numbers = [ 2, 3, 5, 7, 11, 13, 17, 19 ]

# getting contents
sport = sport_list[ 2 ]
third_prime = first_prime_numbers[ 2 ]

# printing
print( 'All sports:', sport_list )
print( 'Sport to be done:', sport )

print( '\nFirst primes:', first_prime_numbers )
print( 'Third prime number:', third_prime )


All sports: ['cycling', 'football', 'fitness']
Sport to be done: fitness

First primes: [2, 3, 5, 7, 11, 13, 17, 19]
Third prime number: 5

In [2]:
# adapt entries and append new entries
sport_list[ 1 ] = 'swimming'
sport_list.append( 'running' )
first_prime_numbers.append( 23 ) 

# printing
print( 'All sports:', sport_list )
print( 'First primes:', first_prime_numbers )


All sports: ['cycling', 'swimming', 'fitness', 'running']
First primes: [2, 3, 5, 7, 11, 13, 17, 19, 23]

Tuples

  • Similar to lists but "immutable", i.e., entries can be appended, but not be changed
  • Defined by tuple( ) or by brackets with entities being separated by comma
  • Referenced by index in square brackets; Note: indexing starting at 0

In [3]:
# defining tuple
sport_tuple = ( 'cycling', 'football', 'fitness' )

# getting contents
sport = sport_tuple[ 2 ]

# printing
print( 'All sports:', sport_tuple )
print( 'Sport to be done:', sport )


All sports: ('cycling', 'football', 'fitness')
Sport to be done: fitness

In [4]:
# append new entries
sport_tuple += ( 'running', )

# printing
print( 'All sports:', sport_tuple )
print()

# changing entries will fail
# --> ERROR is being generated on purpose
# --> NOTE: Error is handled by 'try: ... except: ...' statement
try:
    sport_tuple[ 1 ] = 'swimming'
except:
    print('ERROR: Entries within tuples cannot be adapted!')


All sports: ('cycling', 'football', 'fitness', 'running')

ERROR: Entries within tuples cannot be adapted!

Dictionaries

  • Container in which entries are of type: ( key : value )
  • Defined by key word dict or by curly brackets with entities of shape "key : value" being separated by comma
  • Referenced by key in square brackets --> Note: Indexing by keys instead of indices might be a major advantage (at least sometimes)

In [5]:
# defining dictionaries
sports_days = { 'Monday': 'pause', 'Tuesday': 'fitness', 'Wednesday' : 'running', 
            'Thursday' : 'fitness', 'Friday' : 'swimming', 'Saturday' : 'cycling', 
            'Sunday' : 'cycling' }

print( 'Sport by day:', sports_days )
print( '\nOn Tuesday:', sports_days[ 'Tuesday' ])


Sport by day: {'Monday': 'pause', 'Tuesday': 'fitness', 'Wednesday': 'running', 'Thursday': 'fitness', 'Friday': 'swimming', 'Saturday': 'cycling', 'Sunday': 'cycling'}

On Tuesday: fitness

In [6]:
# Changes are made by using the key as identifier
sports_days[ 'Tuesday' ] = 'running'
print( 'Sport by day:', sports_days )


Sport by day: {'Monday': 'pause', 'Tuesday': 'running', 'Wednesday': 'running', 'Thursday': 'fitness', 'Friday': 'swimming', 'Saturday': 'cycling', 'Sunday': 'cycling'}

Sets

  • As characterized by the naming, sets are representing mathematical sets; no double occurences of elements
  • Defined by keyword set of by curly braces with entities being separated by comma
  • Note: As in maths, sets don't possess ordering, so there is no indexing of sets!

In [7]:
# defining sets
sports_set = { 'fitness', 'running', 'swimming', 'cycling'}
print( sports_set )
print()

# indexing will fail
# --> ERROR is being generated on purpose
try:
    print( sports_set[0] )
except:
    print('ERROR: No indexing of sets!')


{'running', 'fitness', 'swimming', 'cycling'}

ERROR: No indexing of sets!

In [8]:
# adding elements (or not)
sports_set.add( 'pause' )
print(sports_set)

sports_set.add( 'fitness' )
print(sports_set)


{'fitness', 'pause', 'running', 'cycling', 'swimming'}
{'fitness', 'pause', 'running', 'cycling', 'swimming'}

In [9]:
# union of sets (also: intersection, complement, ...)
all_stuff_set = set( sports_set )
union_of_sets = all_stuff_set.union( first_prime_numbers)

print( union_of_sets )


{2, 3, 5, 7, 11, 13, 'pause', 17, 19, 23, 'cycling', 'swimming', 'fitness', 'running'}

Flow Control

  • Standards commands as for, while, ...
  • Functions for specific purposes
  • Note: Since commands and their concept are quite self-explaining, only short description of syntax is provided

For Loops

  • for loops in Python allow looping along every so-called iterable as, e.g., list, tuple, dicts.... Note: Not necessarily int
  • Syntax: for i in iterable:
  • Note: Blocks are structured by indentation; sub-command (as, e.g., in a loop) are indented

In [10]:
# looping in lists simply parsing along the list
for s in sport_list:
    print( s )

print()

# looping in dictionaries happens along keys
for s in sports_days:
    print( '{}: \t{}'.format( s, sports_days[ s ] ) )


cycling
swimming
fitness
running

Monday: 	pause
Tuesday: 	running
Wednesday: 	running
Thursday: 	fitness
Friday: 	swimming
Saturday: 	cycling
Sunday: 	cycling

While Loops

  • while loops in Python are (as usual) constructed by checking condition and exiting loop if condition becomes False
  • Note: Blocks are structured by indentation; sub-command (as, e.g., in a loop) are indented

In [11]:
# initialize variables
sum_primes = 0
_n = 0

# sum primes up to sum-value of 20
while sum_primes < 20:
    
    # add prime of according index
    sum_primes += first_prime_numbers[ _n ]
    
    # increase index
    _n += 1
    
print( 'Sum of first {} primes is {}.'.format( _n, sum_primes ) )


Sum of first 5 primes is 28.

Functions

  • Defined by key-word def followed by list of arguments in brackets
  • Doc string defined directly after def by ''' TEXT '''
  • Values returned by key word return; Note: return "value" can be scalar, list, dict, vector, maxtrix,...

In [12]:
def get_n_th_prime( n, first_prime_numbers ):
    '''
    DOC String
    
    IN: index of prime number, list of prime numbers
    OUT: n-th prime number
    '''
    
    # do something smart as, e.g., checking that according index really exists
    # "assert" does the job by checking first arg and--if not being TRUE--providing text given as second arg
    try: 
        val = first_prime_numbers[ n - 1 ]
    except:
        return '"ERROR: Index not feasible!"'
    
    # NOTE: since counting starts at 0, (n-1)st number is returned
    # Furthermore, there is no need for a function here; a simple reference would have done the job!
    
    return first_prime_numbers[ n - 1 ]


# show doc string
print( help( get_n_th_prime ) )

# apply functions
N = 3
print( '{}. prime number is {}.'.format( N, get_n_th_prime( N, first_prime_numbers ) ) )

print()

N = 30
print( '{}. prime number is {}.'.format( N, get_n_th_prime( N, first_prime_numbers ) ) )


Help on function get_n_th_prime in module __main__:

get_n_th_prime(n, first_prime_numbers)
    DOC String
    
    IN: index of prime number, list of prime numbers
    OUT: n-th prime number

None
3. prime number is 5.

30. prime number is "ERROR: Index not feasible!".

Several Useful Commands and Wording

  • import: importing modules to be used as, e.g., modules for
    • plotting (matplotlib),
    • numerical calculations (numpy),
      • np.linalg: linear algebra
      • np.random: everything dealing with randomness, as, e.g., realization of different distributions
    • scientific math (scipy),
    • iterating along an iterable (itertools, ...)
  • break: quitting current loop
  • continue: processing to next iteration of current loop
  • enumerate( x ): generates enumeration tuples of shape ( index, value ) parsing all entries of iterable x
  • len( x ): length of list/tuple x
  • range( N ): generates iterable with integers $0,\ldots N-1$
  • iterable: something that can be iterated, i.e., " walked through"', as, e.g., lists, tuples, dicts

Module Numpy

  • In simulations imported as import numpy as np such that all functions or submodules within the module are being used as np.sub_func_mod
  • Optimized for vector operations
  • np.arange( a, b, step ): generating a numpy array starting at a (included) up to b (not included) with step size 'step' (optional)
  • np.argmax( a ): returns first index at which a attains its maximum value
  • np.array( ): standard data type of numpy, essentially correponding to a vector as used in maths
  • np.average( x ): determines average value of list/array x
  • np.concatenate( x, y ): generates new vector/tuple ( x, y )
  • x.copy( ): creates a copy of x
  • np.corrcoeff( x, y ): determines correlation coefficient of x and y
  • np.correlate( x, y, 'full'): determines correlation function (!) of vectors (signals) x and y
  • np.cumsum( x ): cumulative sum of x
  • np.histogram( values, bins ): generates histogram (relative frequency) of 'values' with respect to classes listed in 'bins'
  • np.isclose( a, b ): returns Boolean describing if $a \approx b$ 'within tolerance'
  • np.linspace( a, b, num_points ): generates vector of 'num_points' equidistant points in $[a, b)$
  • np.ones( shape ): generates array of ones of shape 'shape'
  • np.ones_like( x ): generates array of ones of same shape and type as x
  • np.prod( x ): multiplying all elements of x
  • np.random.choice( A, size = S ): sampling S entities out of A; replacing elements and probability may be characterized as parameters
  • np.random.rand( size ): generates 'size' random values being uniformly distributed in $[0,1)$
  • np.random.randint( a, b, size ): generates 'size' random integers between a (included) and b (not included)
  • np.random.randn( size ): generates a vector of standard gaussian ($E(X)=0, D^2(X)=1$) random variables of size 'size'
  • np.sum( x ): summing up all elements of x
  • np.zeros( shape ): generates array of zeros of shape 'shape'
  • np.zeros_like( x ): generates array of zeros of same shape and type as x

Module Scipy

  • Contains several usefull scientific modules
  • contains elements for digital signal processing, e.g., filter design, filters, fast Fourier transforms,...
  • special: several special functions, e.g., Bessel, binomial coefficients,...