This lecture consists of several self study sessions!
In these sections you are supposed to work on the given topics on your own and in your own time. We will try to provide helpful references for books and online material that can help you but you are not limited to these materials.
In order to get an idea on how much you understand of the material we provide exercises.
In this section we are mainly concerned with the basics of Python, nevertheless you are expected to use git and pdm to solve the problems at hand.
6.1 Topics
For each topic we list various materials and what is the basic idea behind it.
If, and only if, you are taking the class at MCI and are not reading these notes on your own, you are expected to hand in the exercises below as a git repository, you can use the old one if you like.
Exercise 6.1 (UML fact checker)
classDiagram
Student "*" --* University : Composition
class University{
- name: string
- address: Address
}
class Student{
- name: string
- fee: float
}
Which of the following can be answered with Yes and which with No:
No two universities can have the same name?
A university and a student can not have the same name?
No student studies at more than one university?
Each student studies at at least one university?
Two students with the same name can not study at the same university?
Two students with the same name can not study at different universities?
Two universities can have the same address?
Is there a way to specify a attribute in UML as unique?
Exercise 6.2 (From text to UML) Convert the following description into an appropriate UML diagram, with multiplicities and associations.
Every person has a name, a phone number and an e-mail address.
Every address is only occupied by one person, some addresses might have no inhabitant.
Each address is associated with a street, a city, an area code, and a country.
Addresses can be verified as a home address for a person and printed for post service.
There are two types of persons:
Students that can enlist for a class
Professors that can receive a salary
A student has a study ID and an average grade.
Exercise 6.3 (From UML to Python) Convert the UML diagram from Exercise 6.2 into Python code and test your classes.
Exercise 6.4 (Interface) Consider the following UML diagram and implement it in Python with interfaces. Set lives for a Cat to the appropriate 7, feed some cat food generated with random integers uniformly distributed between \(-10\) and \(10\) and look how much food it can eat until it dies. Plot this for different initial values of currentFood.
classDiagram
Cat --|> Animal
Cat ..|> FourLegged
Cat ..|> OxygenBreather
class FourLegged{
<<interface>>
+ run(destination)
}
class OxygenBreather{
<<interface>>
+ breath()
}
class Animal{
- lives: int
- currentFood: int
+ eat(food: int)
}
class Cat{
+ getLivesLeft()
+ getCurrentAmountofFood()
- decreaseLives()
}
Exercise 6.5 (Indexing in numpy or slicing) There exists a multitude of different ways to index numpy arrays. Create an appropriate (or multiple appropriate arrays) and provide the answer to the following questions with slicing:
For a vector:
return the last 5 elements
return every second element
reverse the vector
return element 1, 4 and 11
return all elements bigger than the mean
For a matrix:
flip the second and third row
add the second column to the entire matrix
extract the sub matrix that only consists of odd rows and even columns
return the rows 1, 4, and 11
Exercise 6.6 (Reshape numpy) We can reshape, i.e. change row and column dimensions, of arrays. The important part here is the way the array is viewed by its dimensions. Hint: use np.arange(x) for the following exercise so you know the positions of the numbers.
Reshape a 8 element vector into a \(4 \times 2\) matrix.
Reshape a 8 element vector into a \(4 \times 2\) matrix and directly into a \(2 \times 4\) without storing the intermediate result (in one line).
Reshape a 16 element vector into a \(2 \times x\) vector where numpy infers the second dimension from the data.
Use the shape property of a matrix to reshape a vector.
Does reshape create a copy of the original data?
How do you reverse back to a flat vector?
Exercise 6.7 (Monte Carlo simulations in numpy) Recall Exercise 5.5 and implement a version of in_unit_circle that uses numpy arrays, you should take the code from Exercise 5.7 as basis and add a new function in_unit_circle_np.
To write this in Python follow these steps:
With numpy.random.uniform() create a \(2\times N\) matrix with random numbers.
Use element wise computation to get \(M\). Hint:True is interpreted as 1 and False as 0 when you try to add boolean values.
Once you have the second implementation test it and compare it with the other version.
Is the accuracy the same?
Have a look at timeit and see which of your two code versions is faster for which N
Plot your results, i.e. for different values of \(N\) the different execution times for the two versions, maybe use a logarithmic axis.
Are there other plots that might give you an insight for this example.
Exercise 6.8 (Predator Prey simulation) The Lotka-Volterra Equations \[
\begin{array}{c}
\dot{x} = \alpha x - \beta x y\\
\dot{y} = \delta x y - \gamma y
\end{array}
\tag{6.1}\] can be used to describe a predator-prey system. In this case we can interpret the variables as:
\(x\) prey population
\(y\) predator population
\(\dot{x}\) growth rate of prey population
\(\dot{y}\) growth rate of predator population
\(\alpha\) natural growth rate of prey
\(\beta\) death rate of prey due to predators
\(\delta\) natural death rate of predators
\(\gamma\) growth rate of predators per consumed prey
We assume that the prey has unlimited food and the change rate is proportional to the size. The predators only eat the specific prey and they are always hungry.
Create first an UML diagram and later Python code that follows these guidelines:
Create a predator class with the parameters \(x, \alpha, \beta\) where only the first is public
Create a prey class with the parameters \(y, \delta, \gamma\) where only the first is public
Create a class to propagate your model:
the constructor takes a prey and a predator object
create a private method to compute the two derivatives
create a second method to propagate a single time step \(\Delta t\), as time integrator we suggest to implement a Forward Euler but you can also use something from scipy.integrate if you prefer.
use the classes to store the current population in the appropriate variable.
create a public method where you provide the final time \(t_1\) and \(\Delta t\) and returns \(x, y\) in each time step (you need to compute the amount of steps).
Plot the results
Test your method with the following parameters:
\(\alpha = 1\)
\(\beta = 0.1\)
\(\gamma = 0.5\)
\(\delta = 0.02\)
\(x = 100\) (initial population)
\(y = 20\) (initial population)
Create getter/setter methods for the parameters that are private where you check that the signs and types are appropriate if they get set.
Exercise 6.9 (Use pandas to redo Section 2 of MECH-M-DUAL-I-DBM) In MECH-M-DUAL-I-DBM Section 2 we worked with the mieten3.asc dataset and did some computations on it.
Use pandas to load the dataset and compute the same properties and create similar plots, where it is appropriate.
Hint: Data loading and some examples are done in Chapter 9.
Exercise 6.10 (Advanced pandas)
The method apply() can apply a function along an axis of a DataFrame and can be used in various ways.
Transform the PST column into a DataTime object (various possibilities)
Create a new DataFrame that consists of the temperature columns where they are converted from °F to °C
Merge the two DataFrames
Repeat the same operation directly with .apply
Let us assume, for some reason, the entries from January where off for \(1\%\). Use the .update function to change them - i.e. correct them by the error.
Use the .pipe function to apply a series of functions to your data.
Compute the Mean Humidity per month and scale this data with this value
Update the WindDirDegree such that the values in in \([-180, 180]\) instead of \([0, 360)\)
Update the PST column to only contain month and day
Exercise 6.11 (Decorators) In Python we can use decorators to modify the functionality of a function by wrapping it in another function, you can find an introductions in the following links
Write a decorator @positive that checks arguments to be positive and raise an Exception (with raise Exception("Sorry, not positive")). Test this implementation with Exercise 6.7. We will look at exception handling later.
Can you modify the decorator such that you can give an optional argument specifying the location to check for positivity?
@positiv(1)def testfun(a, b, c)# error fortestfun(-1, -1, -1)# but not fortestfun(-1, 1, -1)
Matthes, Eric. 2023. Python Crash Course - a Hands-on, Project-Based Introduction to Programming. 3rd ed. No Starch Press. https://ehmatthes.github.io/pcc_3e/.
McKinney, Wes. 2022. Python for Data Analysis 3e. 3rd ed. Sebastopol, CA: O’Reilly Media. https://wesmckinney.com/book/.
Vasiliev, Yuli. 2022. Python for Data Science - a Hands-on Introduction. München: No Starch Press.