Webpage for python course

This commit is contained in:
2024-09-19 18:08:56 +02:00
parent 535d4a0bd1
commit 63217cba01
30 changed files with 12436 additions and 5 deletions
+1 -1
View File
@@ -42,7 +42,7 @@
<li>Am ersten Termin nach der Themenvergabe gebe ich eine Einführung in das Thema "Vorträge halten"</li>
<li>Vier Wochen vor Ihrem Vortrag versorge ich Sie mit Material</li>
<li> Eine Woche vor dem Vortrag gibt es eine Vorbesprechung (per Email oder Videokonferenz)</li>
<li> Der Vortrag wird dann per Videokonferenz mit allen gehalten</li>
<li> Der Vortrag wird dann in Präsenz gehalten</li>
<li> Zu Ihrem Vortrag gehört ein zweiseitiges Handout, dass an die Zuhörer verteilt wird</li>
<li> Bewertet werden der Vortrag, die Fragerunde und das Handout</li>
<li> Es wird erwartet, dass Sie sich auch als Zuhörer mit Fragen zum Vortrag beteiligen - werden keine Fragen
@@ -0,0 +1,262 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# About the course"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This course was originally written by [Thomas Robitaille](http://www.thomasrobitaille.com/teaching.html), and was carefully adapted by Markus Demleitner and myself.\n",
"\n",
"**The web page for this course is\n",
"[https://www.ita.uni-heidelberg.de/~fspanier/lecture/pycourse/].**\n",
"\n",
"The lecturer is Felix Spanier.\n",
"You can contact me during the course and at [felix.spanier@uni-heidelberg.de](mailto:felix.spanier@uni-heidelberg.de)\n",
"\n",
"The tutorium is held by Christian Sendlinger"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"Topics\n",
"------\n",
"\n",
"- Using the IPython Notebook\n",
"- Introduction to Python\n",
"- Modules and Functions\n",
"- Introduction to Numpy and Matplotlib\n",
"- Reading/writing data from files\n",
"- Introduction to Scipy (interpolation, integration, fitting)\n",
"- Applying Python to scientific problems\n",
"- Object-oriented programming"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "notes"
}
},
"source": [
"Structure\n",
"---------\n",
"\n",
"The block course lasts five days, and each day will follow this schedule:\n",
"\n",
"* 9:00-10:30 - lecture/exercises\n",
"* 10:30-11:00 - break\n",
"* 11:00-12:30 - lecture/exercises\n",
"* 12:30-13:30 - break for lunch\n",
"* 13:30-15:00 - lecture/exercises\n",
"* 15:00-17:00 - computer pool available to finish homework\n",
"\n",
"The lectures will be mixed with exercise sessions - from time to time I will give you 5 or 10 minutes to complete a given task/exercise. There will be **problem sets** during the week, and you will be required to hand these in a deadline indicated on the problem sheet. An average of 60% [=54 points] in the problem sets will be required to obtain 2 credits points at the end of the course.\n",
"\n",
"The course will be in English or German as convenient."
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"I am happy to review or talk about your code/solutions to exercises."
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"Solutions to problem sheets\n",
"---------------------------"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"All solutions should be submitted as IPython (/Jupyter) notebooks or python programs (one notebook/program per problem set). \n",
"\n",
"* Please use a **filename that contains the name of the problem sheet and your name**.\n",
"\n",
"* Only submit the program (.py or .ipynb), **do not submit data downloaded from the course web page**.\n",
"\n",
"Submissions have to be entered in the **uebungen** system."
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"The following criteria are taken into account for grading problem sets - the notebook/program should:\n",
"\n",
"- run with no errors *under python3*\n",
"- produce the correct results\n",
"- be clearly readable, and include text to explain what you are doing and why\n",
"- not include any unused code! (-> readability)\n",
"\n",
"\n",
"Please make use of the ability to add comments and text around your code. Make it so that someone not familiar with the problem could read it and understand your solution."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**There is never a unique solution to a problem**, so it does not matter if your programs do not look the same as somebody else's! What matters most is that you get a chance to make mistakes and learn from them."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Policy on handing in solutions\n",
"------------------------------\n",
"\n",
"**Problem set submissions need to be handed in separately for each participant.**\n",
"\n",
"The deadlines for the Problem Sets are:\n",
"\n",
"Problem Set 1 Thursday, Ocotber 3rd 2024, 7pm CEST\n",
"\n",
"Problem Set 2 Thursday, October 10th 2024, 7pm CEST\n",
"\n",
"Problem Set 3 Thursday, October 17th 2024, 7pm CEST\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"Your own python installation on your Laptop\n",
"-------\n",
"\n",
"The default is to use the jupyter server (see below), but\n",
"if you would like to use Python on your laptop, you have several possibilities:\n",
"\n",
"- If you have a linux laptop and are familiar with package managers, most major scientific Python packages are available through these\n",
"- Otherwise, try and install the [Anaconda Python distribution](https://www.anaconda.com/download)\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Getting set up"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### CIP Pool, the jupyter server and the Lecture Notes"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The default is to use the server **https://jupyter.kip.uni-heidelberg.de** for this course (there is also jupyter2 in case of overcrowding). Please login there.\n",
"\n",
"You can download the notebooks I'm showing, the problem sets and the ancillary data files from [here](https://www.ita.uni-heidelberg.de/~fspanier/lecture/pycourse/)\n",
"\n",
"The simplest way to upload the files to the jupyter server is the following:\n",
"\n",
"* copy link location (using the \"right\" mouse button)\n",
"* then open a terminal on the jupyter server using \"New\" -> \"Terminal\" (top right next to \"Upload\")\n",
"* type: wget [paste link location here]\n",
"* using the browser, go back to the tab with the jupyter Home directory (\"Home\")\n",
"\n",
"The file should now be visible in the Home directory.\n",
"\n",
"In the same directory you also find the 'data' directory. The contains material that will be used in this course. In case you used your account before, this may also be called 'data2'. You can ask me if you want to rename this."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Using ipython on the CIP pool computer directly"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This option is now *deprecated* due to the antiquated python installation on these systems, so we do not recommend to do this.\n",
"\n",
"For backwards compatibility I still keep the instructions here:\n",
"\n",
"You will need to start up a command-line Terminal application. In the CIP pool this is located in the Anwendungen -> Zubehör -> Terminal menu.\n",
"\n",
"To ensure a common environment, in the CIP pool we'll be using an updated version of ipython over what is installed on the machines themselves. To use that, you have to manipulate your path. Here is one way to do that:\n",
"\n",
" echo \"export PATH=/local/py4sci/anaconda3/bin:$PATH\" >> ~/.bashrc\n",
" exec bash\n",
"\n",
"You only need to do that once.\n",
"\n",
"Then fetch the notebooks and execute the notebook player (optionally in a subdirectory):\n",
"\n",
" ipython notebook\n",
"\n",
"A web browser should open and you should be ready to go.\n"
]
}
],
"metadata": {
"anaconda-cloud": {},
"kernelspec": {
"display_name": "Python 3",
"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.10"
}
},
"nbformat": 4,
"nbformat_minor": 1
}
+157
View File
@@ -0,0 +1,157 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# What is Python?"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "notes"
}
},
"source": [
"![Python Logo](https://www.python.org/static/community_logos/python-logo-master-v3-TM.png)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# First, what is 'Programming'?"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"Being good at programming is about:\n",
"\n",
"* understanding a problem conceptually and being able to translate it into code\n",
"* thinking of new ways to tackle (for example) a scientific problem, and knowing what tools to use\n",
"* knowing how to fix your program when it does not work\n",
"* writing a program that is fast **enough**, **not** the fastest possible\n",
"* writing a program that can be understood by other people (or by yourself after some time has passed)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "notes"
}
},
"source": [
"The last point is important, because **reproducible research** and **open science** is becoming the norm in certain fields of research. This means that others have to be able to read your code, and understand what you are doing, and be able to run it themselves. For this course, we are not just interested in whether your solutions are correct, but also whether it is possible to understand how you are solving the problem. You should always write code assuming that someone else may read it."
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"This course focuses on aspects of programming that would be useful to you in scientific research, but Python is a very popular language, and what you will learn will also be applicable if you decide to pursue a different career."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## How does Python compare to other languages?"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"Python is an **interpreted** language, which means that the code is not compiled in advance. This makes it slower than programming languages like C/C++ or Fortran. Why therefore would we want to learn/use it?\n",
"\n",
"* It has a clean and simple syntax which emphasises readability\n",
"* It can be much faster to write programs in python than other languages\n",
"* It gives detailed errors by default which makes it easier to fix bugs\n",
"* It is easy to use for interactive analysis\n",
"* It has a large \"ecosystem\" of packages available for everything from numerical analysis, databases, graphical interfaces, web scraping...\n",
"* It is straightforward to interface with C/Fortran code\n",
"* It can interact with command-line programs, and other languages\n",
"* Some Packages (e.g. Numpy for arrays) are written in C, which means that we get the convenience of Python and the speed of C\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Why is it called 'Python'?"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"Even though the Python logo has snakes in it, Python originally comes from the [Monty Python](http://en.wikipedia.org/wiki/Monty_Python) comedy group [\"Monty Python's Flying Circus\", \"Monty Python's Life of Brian\", \"Monty Python and the Holy Grail\"]\n",
"\n",
".. a lot of Python documentation includes jokes related to Monty Python."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## A note on Python 2 vs 3"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"The latest version of Python is currently 3.7.\n",
"\n",
"Sometimes one still encounters python version 2.7 (the latest 2.x release). But this is not recommended anymore, we'll only use Python 3 here."
]
}
],
"metadata": {
"anaconda-cloud": {},
"kernelspec": {
"display_name": "Python 3",
"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.5"
}
},
"nbformat": 4,
"nbformat_minor": 1
}
@@ -0,0 +1,251 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Using the jupyter notebook on the jupyter server"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The jupyter *notebook* is a feature that allows you to write your code in the framework of \"notebooks\" similar to, e.g., Mathematica or Matlab.\n",
"\n",
"An advantage of doing this is that you can include text, code, and plots in the same document. This makes it suitable for example to write up a report about a project that uses mostly Python code, in order to share with others. In fact, the notes for this course are written using the jupyter notebook.\n",
"\n",
"Note: If you are more comfortable, to simply write programs and execute them with python or ipython, that is OK! There is no obligation to use notebooks. Make sure your problem sets run/finish with python3/ipython3 and that they create all the necessary output."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Starting up"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"On the jupyter server you simply log in.\n",
"\n",
"Alternatively, using a set installation (e.g., on your laptop), the normal way to start up the IPython notebook is to open a shell, go to the directory containing your notebooks and say:\n",
"\n",
" jupyter notebook\n",
" \n",
"Once you do this, your web browser should open and go to a page showing a list of folders and notebooks.\n",
"We use here the jupyter server, which runs the JupyterLab. There may be differences here and there.\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## First steps"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In the launcher under Notebook click on ``python 3 ``, which will start a new document. You can change the name of the document by right-clicking on the **Untitled** name at the top and entering a new name. Make sure you then save the document (make sure that you save regularly as you might lose content if you close the browser window!).\n",
"\n",
"At first glance, a notebook looks like a fairly typical application - it has a menubar (File, Edit, View, etc.) and a tool bar with icons. Below this, you will see an empty cell, in which you can type any Python code. You can write several lines of code, and once it is ready to run, you can press _shift-enter_ and it will get executed:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"a = 2.718\n",
"print(a)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can then click on that cell, change the Python code, and press shift-enter again to re-execute the code. Once you have executed a cell once, a new cell will appear below. You can again enter some code, then press shift-enter to execute it."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Text"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"It is likely that you will want to enter actual text (non-code) in the notebook. To do this, click on a cell, and in the drop-down menu in the toolbar, select 'Markdown'. This is a specific type of syntax for writing text. You can just write text normally and press shift-enter to *render* it:\n",
"\n",
" This is some plain text\n",
"\n",
"To edit it, double click on the cell. You can also enter section headings using the following syntax:\n",
"\n",
" This is a title\n",
" ===============\n",
"\n",
" This is a sub-title\n",
" -------------------\n",
"\n",
"which will look like:\n",
"\n",
"This is a title\n",
"===============\n",
"\n",
"This is a sub-title\n",
"-------------------\n",
"\n",
"Finally, if you are familiar with LaTeX, you can enter equations using:\n",
"\n",
" $$E = m c^2$$\n",
"\n",
"on a separate line, or:\n",
"\n",
" Louis likes the equation $p=h/\\lambda$ **very much**.\n",
"\n",
"to include it in a sentence. This will look like:\n",
"\n",
"$$E = m c^2$$\n",
"\n",
"Louis likes the equation $p=h/\\lambda$ **very much**.\n",
"\n",
"For more information about using LaTeX for equations, see [this guide](http://en.wikibooks.org/wiki/LaTeX/Mathematics)."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Splitting/deleting/moving cells"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can split, delete, and move cells by going to 'Edit' and selecting the appropriate command. Some of the commands are also available in the toolbar - put your mouse over the icon and wait for a second, and it will tell you what it does."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Sharing your notebook"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"IPython notebooks are plain text files – you can view them with a text editor, and other people can dump them into their own folders to re-run them.\n",
"\n",
"Find the files under the name you gave the notebook, with an ipynb extension.\n",
"\n",
"If you know how to use version control, the notebooks can be used with diff and merge. If you are already using subversion or github: try it with your notebooks."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Important notes"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"A few important notes about using the notebook:\n",
"\n",
"* Save often! There is an auto-save in the notebook, but better to also save explicitly from time to time.\n",
"\n",
"* Code *can* be executed in an order different from top to bottom, but note that if you do this variables will not be reset. So for example if you type:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"a = 1"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"then go higher up and type:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"print(a)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"it will give the value you previously set. To make sure that your code works from top to bottom, go to the 'Edit' menu item and go to **Clear All Outputs** then in the **Run** menu, select **Run All**.\n",
"\n",
"In addition, even if you remove a cell, then variables set in that cell still exist unless you restart the notebook. If you want to restart a notebook, you can select **Kernel** -> **Restart**. This removes any variables from memory, and you have to start running the notebook from the start.\n",
"\n",
"**Please try out your notebooks after a fresh kernel restart before you submit your solutions.**\n",
"------------------------------------------------------------------------------------------------\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Another word of warning"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"ipython notebooks contain executable code. Executing a notebook of unknown origin is dangerous. From within such a notebook, people can do\n",
"anything you can do, e.g., delete files, create backdoors to your system, etc.\n",
"\n",
"The notebook runner will not execute untrusted code *without your command*. If you see code you don't understand (in particular if it contains calls into modules like os, subprocess, sys, and such): Do not execute!"
]
}
],
"metadata": {
"anaconda-cloud": {},
"kernelspec": {
"display_name": "Python 3",
"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.5"
}
},
"nbformat": 4,
"nbformat_minor": 1
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,575 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Booleans, Tuples, and Dictionaries"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Booleans"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"A ``boolean`` is one of the simplest Python types, and it can have two values: ``True`` and ``False`` (with uppercase ``T`` and ``F``):"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"a = True\n",
"b = False"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"Booleans can be combined with logical operators to give other booleans:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"True and False"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"True or False"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"(False and (True or False)) or (False and True)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"Standard comparison operators can also produce booleans:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"1 == 3"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"1 != 3"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"3 > 2"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"3 <= 3.4"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Exercise 1"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Write an expression that returns ``True`` if ``x`` is strictly greater than 3.4 and smaller or equal to 6.6, or if it is 2, and try changing ``x`` to see if it works:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"x = 3.7\n",
"\n",
"# your solution here\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Tuples"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"Tuples are, like lists, a type of sequence, but they use round parentheses rather than square brackets:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"t = (1, 2, 3)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"They can contain heterogeneous types like lists:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"t = (1, 2.3, 'roof')"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"and also support item access and slicing like lists:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"t[1]"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"t[:2]"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"The main difference is that they are **immutable**, like strings:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"t[1] = 2"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We will not go into the details right now of why this is useful, but you should know that these exist as you may encounter them in examples."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Dictionaries"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"One of the data types that we have not talked about yet is called *dictionaries* (``dict``). If you think about what a 'real' dictionary is, it is a list of words, and for each word is a definition. Similarly, in Python, we can assign definitions (or 'values'), to words (or 'keywords')."
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"Dictionaries are defined using curly brackets ``{}``:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"d = {'a':1, 'b':2, 'c':3}"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"Items are accessed using square brackets and the 'key':"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"d['a']"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"d['c']"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"Values can also be set this way:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"d['r'] = 2.2"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"print(d)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"The keywords don't have to be strings, they can be many (but not all) Python objects:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "-"
}
},
"outputs": [],
"source": [
"e = {}\n",
"e['a_string'] = 3.3\n",
"e[3445] = 2.2\n",
"e[complex(2,1)] = 'value'"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"print(e)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"e[3445]"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"If you try and access an element that does not exist, you will get a ``KeyError``:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"e[4]"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"Also, note that dictionaries do *not* know about order, so there is no 'first' or 'last' element."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"It is easy to check if a specific key is in a dictionary, using the ``in`` operator:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"\"a\" in d"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"\"t\" in d"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"\"t\" not in d"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Note that this also works for lists:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"3 in [1,2,3]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Exercise 2"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Try making a dictionary to translate a few English words into German and try using it!"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"\n",
"# your solution here\n"
]
}
],
"metadata": {
"anaconda-cloud": {},
"kernelspec": {
"display_name": "Python [Root]",
"language": "python",
"name": "Python [Root]"
},
"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.5.2"
}
},
"nbformat": 4,
"nbformat_minor": 0
}
+542
View File
@@ -0,0 +1,542 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Control Flow"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"We now know how to set variables of various types:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"a = 1\n",
"b = 2.718\n",
"c = 'hello'\n",
"d = [a, b, c]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"but this doesn't get us very far. One essential part of programming is **control flow** which is the ability to control how the program will proceed based on for example some conditions, or making parts of the program run multiple times."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## ``if`` statements"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"The simplest form of control flow is the ``if`` statement, which executes a block of code only if a certain condition is true (and optionally executes code if it is *not* true. The basic syntax for an if-statement is the following:\n",
"\n",
" if condition:\n",
" # do something\n",
" elif condition:\n",
" # do something else\n",
" else:\n",
" # do yet something else\n",
"\n",
"Notice that there is no statement to end the if statement, and the\n",
"presence of a colon (``:``) after each control flow statement. Python relies\n",
"on **indentation and colons** to determine whether it is in a specific block of\n",
"code."
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"For example, in the following code:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"a = 1"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"if a == 1:\n",
" print(\"a is 1, changing to 2\")\n",
" a = 2\n",
"\n",
"print(\"finished\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"source": [
"The first print statement, and the ``a = 2`` statement only get executed if\n",
"``a`` is 1. On the other hand, ``print \"finished\"`` gets executed regardless,\n",
"once Python exits the if statement."
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"**Indentation is very important in Python, and the convention is to use four spaces (not tabs) for each level of indent.**"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"Back to the if-statements, the conditions in the statements can be anything that returns a boolean value. For example, ``a == 1``, ``b != 4``, and ``c <= 5`` are valid conditions because they return either ``True`` or ``False`` depending on whether the statements are true or not."
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"Standard comparisons can be used (``==`` for equal, ``!=`` for not equal, ``<=`` for less or equal, ``>=`` for greater or equal, ``<`` for less than, and ``>`` for greater than), as well as logical operators (``and``, ``or``, ``not``). Parentheses can be used to isolate different parts of conditions, to make clear in what order the comparisons should be executed, for example:\n",
"\n",
" if (a == 1 and b <= 3) or c > 3:\n",
" # do something\n",
"\n",
"More generally, any function or expression that ultimately returns ``True`` or ``False`` can be used.\n",
"\n",
"In particular, you can use booleans themselves:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"a = 8\n",
"cond = a==1 or a>7\n",
"if cond:\n",
" print (\"hit\")\n",
"else:\n",
" print (\"miss\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## ``for`` loops"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"Another common structure that is important for controling the flow of execution are loops. Loops can be used to execute a block of code multiple times. The most common type of loop is the ``for`` loop. In its most basic form, it\n",
"is straightforward:\n",
"\n",
" for value in iterable:\n",
" # do things\n",
"\n",
"The ``iterable`` can be any Python object that can be iterated over. This\n",
"includes lists or strings."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"outputs": [],
"source": [
"for x in [3, 1.2, 'a']:\n",
" print(x)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"for letter in 'hello':\n",
" print(letter)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"A common type of for loop is one where the value should go between two integers with a specific set size. To do this, we can use the ``range`` function. If given a single value, it will allow you to iterate from 0 to the value minus 1:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"for i in range(5):\n",
" print(i)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"for i in range(3, 12):\n",
" print(i)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"for i in range(2, 20, 2): # the third entry specifies the \"step size\"\n",
" print(i)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"If you try iterating over a dictionary, it will iterate over the **keys** (not the values), in no specific order:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"d = {'a':1, 'b':2, 'c':3}\n",
"for key in d:\n",
" print(key)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"But you can easily get the value with:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"for key in d:\n",
" print(key, d[key])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Building programs"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"These different control flow structures can be combined to form programs. For example, the following program will print out a different message depending on whether the current number in the loop is less, equal to, or greater than 10:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"for value in [2, 55, 4, 5, 12, 8, 9, 22]:\n",
" if value > 10:\n",
" print(\"Value is greater than 10 (\" + str(value) + \")\")\n",
" elif value == 10:\n",
" print(\"Value is exactly 10\")\n",
" else:\n",
" print(\"Value is less than 10 (\" + str(value) + \")\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Exercise 1"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Write a program that will print out all the prime numbers (numbers divisible only by one and themselves) below 1000.\n",
"\n",
"Hint: the ``%`` operator can be used to find the remainder of the division of an integer by another:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Experiment\n",
"20 % 3"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"\n",
"# enter your solution here\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Exiting or continuing a loop"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"There are two useful statements that can be called in a loop - ``break`` and ``continue``. When called, ``break`` will exit the loop it is currently in:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"for i in range(10):\n",
" print(i)\n",
" if i == 3:\n",
" break"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"The other is ``continue``, which will ignore the rest of the loop and go straight to the next iteration:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"for i in range(10):\n",
" if i == 2 or i == 8:\n",
" continue\n",
" print(i)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Exercise 2"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"When checking if a value is prime, as soon as you have found that the value is divisble by a single value, the value is therefore not prime and there is no need to continue checking whether it is divisible by other values. Copy your solution from above and modify it to break out of the loop once this is the case."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"\n",
"# enter your solution here\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## ``while`` loops"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"Similarly to other programming languages, Python also provides a ``while`` loop which is similar to a ``for`` loop, but where the number of iterations is defined by a condition rather than an iterator:\n",
"\n",
" while condition:\n",
" # do something"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"For example, in the following example:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"a = 1\n",
"while a < 10:\n",
" print(a)\n",
" a = a * 1.5\n",
"print(\"Once the while loop has completed, a has the value\", a)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"the loop is executed until ``a`` is equal to or exceeds 10."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Exercise 3"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Write a program (using a ``while`` loop) that will find the Fibonacci sequence up to (and excluding) 100000. The two first numbers are 0 and 1, and every subsequent number is the sum of the two previous ones, so the sequence starts ``[0, 1, 1, 2, 3, 5, ...]``.\n",
"\n",
"Additional question: Store the sequence inside a Python list, and only print out the whole list to the screen once all the numbers are available. Then, check whether any of the numbers in the sequence are a square (e.g. ``0*0``, ``1*1``, ``2*2``, ``3*3``, ``4*4``) and print out those that are."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"\n",
"# enter your solution here\n"
]
}
],
"metadata": {
"anaconda-cloud": {},
"kernelspec": {
"display_name": "Python 3",
"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.10"
}
},
"nbformat": 4,
"nbformat_minor": 1
}
+459
View File
@@ -0,0 +1,459 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Functions"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Syntax"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "skip"
}
},
"source": [
"You now know how to run Python code, assign variables, and write control flow statements, which allows us to write programs that can do calculations. In fact, this is all you *really* need to write programs (except for being able to read in and write out data which we will talk about later). However, with only this, programs will quickly become very long and unreadable. So one very important rule in programming is to **avoid repetition**."
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"The syntax for a **function** is:\n",
" \n",
" def function_name(arguments):\n",
" # code here\n",
" return values"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"Functions are the **building blocks** of programs - think of them as basic units that are given a certain input an accomplish a certain task. Over time, you can build up more complex programs while preserving readability."
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"Similarly to ``if`` statements and ``for`` and ``while`` loops, indentation is very important because it shows where the function starts and ends.\n",
"\n",
"**Note**: it is a common convention to always use lowercase names for functions."
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"A function can take multiple arguments..."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def add(a, b):\n",
" return a + b\n",
"\n",
"print(add('1','3'))\n",
"print(add(1.,3.2))\n",
"print(add(4,3.))"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"... and can also return multiple values:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def double_and_halve(value):\n",
" return value * 2., value / 2.\n",
"\n",
"print(double_and_halve(5.))"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"If multiple values are returned, you can store them in separate variables."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"d, h = double_and_halve(5.)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"print(d)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"print(h)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"Functions can call other functions:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def do_a_and_b():\n",
" do_a()\n",
" do_b()\n",
"\n",
"def do_a():\n",
" print(\"doing A\")\n",
" \n",
"def do_b():\n",
" print(\"doing B\")\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"outputs": [],
"source": [
"do_a_and_b()"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"**Figuring out the right functions is half the trick behind a good program**. A good function has a clear purpose that can, ideally, be described in one sentence of natural language.\n",
"\n",
"Beginners typically err on the side of defining too few functions and writing monsters spanning a couple of screen pages. That's a clear indication that you're doing it wrong. A good function can be taken in (albeit perhaps not understood) at a glance."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Exercise 1"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Copy your code that finds prime numbers here and modify it so as to make it a function that given a number will return ``True`` or ``False`` depending on whether it is prime."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"\n",
"# enter your solution here\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Exercise 2"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Write a function that will return the digit sum of a number (e.g. for 1989 it is ``1+9+8+9=27``)."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"\n",
"# enter your solutions here\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Optional Arguments"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In addition to normal arguments, functions can take **optional** arguments that can default to a certain value. For example, in the following case:"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"def say_hello(first_name, middle_name='', last_name=''):\n",
" print(\"First name: \" + first_name)\n",
" if middle_name != '':\n",
" print(\"Middle name: \" + middle_name)\n",
" if last_name != '':\n",
" print(\"Last name: \" + last_name)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"we can call the function either with one argument:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"say_hello(\"Douglas\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"and we can also give one or both optional arguments (and the optional arguments can be given in any order):"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"First name: Douglas\n",
"Last name: Adams\n"
]
}
],
"source": [
"say_hello(\"Douglas\", last_name=\"Adams\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"say_hello(\"Douglas\", middle_name=\"Noel\", last_name=\"Adams\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"say_hello(\"Douglas\", last_name=\"Adams\", middle_name=\"Noel\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Built-in functions"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"You may have already noticed that there are functions that are defined by default in Python:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"x = [1,3,6,8,3]"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"len(x)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"outputs": [],
"source": [
"sum(x)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"int(1.7)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"A [full list of built-in functions](http://docs.python.org/3/library/functions.html) is available from http://docs.python.org. Note that there are not *that* many - these are only the most common functions. Most functions are in fact kept inside **modules**, which we will cover later."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Exercise 3"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Write a function that takes a list, and returns the mean and the standard deviation of the values in the list. Test it with the following list:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"l = [1, 9, 4, 5, 16, 7]\n",
"\n",
"# enter your solution here"
]
}
],
"metadata": {
"anaconda-cloud": {},
"kernelspec": {
"display_name": "Python 3",
"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.5"
}
},
"nbformat": 4,
"nbformat_minor": 1
}
@@ -0,0 +1,715 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Reading and Writing files"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"We have already talked about built-in Python types, but there are more types that we did not speak about. One of these is the ``file()`` object which can be used to read or write files."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Reading files"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"Let's try and get the contents of the file into IPython. We start off by creating a file object:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"f = open('data/data.txt', 'r')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The ``open`` function is taking the [data/data.txt](data/data.txt) file, opening it, and returning an object (which we call ``f``) that can then be used to access the data."
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"Note that ``f`` is not the data in the file, it is what is called a *file handle*, which points to the file:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"type(f)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"Now, simply type:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"f.read()"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "-"
}
},
"source": [
"The ``read()`` function basically just read the whole file and put the contents inside a string."
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"Let's try this again:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"f.read()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"What's happened? We read the file, and the file 'pointer' is now sitting at the end of the file, and there is nothing left to read."
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"To close the file handle, you can do:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"f.close()"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"Let's now try and do something more useful, and capture the contents of the file in a string:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"f = open('data/data.txt', 'r')\n",
"data = f.read()"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"Now ``data`` should contain a string with the contents of the file:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"data"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"But what we'd really like to do is read the file line by line. There are several ways to do this, the simplest of which is to use a ``for`` loop in the following way:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"f = open('data/data.txt', 'r')\n",
"for line in f:\n",
" print(repr(line))"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "skip"
}
},
"source": [
"Note that we are using ``repr()`` to show any invisible characters (this will be useful in a minute). Also note that we are now looping over a file rather than a list, and this automatically reads in the next line at each iteration. Each line is being returned as a string. Notice the ``\\n`` at the end of each line - this is a line return character, which indicates the end of a line."
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"Now we're reading in a file line by line, what would be nice would be to get some values out of it. Let's examine the last line in detail. If we just type ``line`` we should see the last line that was printed in the loop:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"line"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"We can first get rid of the ``\\n`` character with:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"line = line.strip()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"line"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"Next, we can use what we learned about strings and lists to do:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"columns = line.split()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"columns"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"Finally, let's say we care about the object name (the 2MASS column), and the J band magnitude (the Jmag) column:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"name = columns[2]\n",
"jmag = columns[3]"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"name"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"jmag"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"Note that ``jmag`` is a string, but if we want a floating point number, we can instead do:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"jmag = float(columns[3])"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"jmag"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"One last piece of information we need about files is how we can read a single line. This is done using:\n",
"\n",
" line = f.readline()"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"We can put all this together to write a little script to read the data from the file and display the columns we care about to the screen! Here it is:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Open file\n",
"f = open('data/data.txt', 'r')\n",
"\n",
"# Read and ignore header lines\n",
"header1 = f.readline()\n",
"header2 = f.readline()\n",
"header3 = f.readline()\n",
"\n",
"# Loop over lines and extract variables of interest\n",
"for line in f:\n",
" line = line.strip()\n",
" columns = line.split()\n",
" name = columns[2]\n",
" jmag = float(columns[3])\n",
" print(name, jmag)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Exercise 1"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Here is a copy of the above code to read in the file. Modify this code so as to create a dictionary which gives ``Jmag`` for a given ``2MASS`` name, i.e.\n",
"\n",
" >>> jmag['00424455+4116103']\n",
" 10.773\n",
" \n",
"Then loop over the items in the dictionary and print out for each the source name and the ``Jmag`` value."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# EDIT THE CODE BELOW\n",
"\n",
"# Open file\n",
"f = open('data/data.txt', 'r')\n",
"\n",
"# Read and ignore header lines\n",
"header1 = f.readline()\n",
"header2 = f.readline()\n",
"header3 = f.readline()\n",
"\n",
"# Loop over lines and extract variables of interest\n",
"for line in f:\n",
" line = line.strip()\n",
" columns = line.split()\n",
" name = columns[2]\n",
" jmag = float(columns[3])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Bonus:** can you figure out a way to make sure that you loop over the source names in alphabetical order?"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Writing files"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"To open a file for writing, use:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"f = open('data_new.txt', 'w')"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"type(f) # checking type again"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"Then simply use ``f.write()`` to write any content to the file, for example:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"f.write(\"Hello, World!\\n\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"If you want to write multiple lines, you can either give a list of strings to the ``writelines()`` method:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"f.writelines(['roof\\n', 'tile\\n', 'roof\\n'])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"or you can write them as a single string:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"f.write('roof\\ntile\\nroof\\n')"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"Once you have finished writing data to a file, you need to close it:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"f.close()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"(this also applies to reading files)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Check your file output:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"f = open('data_new.txt', 'r')\n",
"for line in f:\n",
" print(repr(line))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## The with-statement"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"As we have seen above, files must not just be opened but should be properly closed afterwards to make sure they are actually written before using them somewhere else. Sometimes writes to files get cached by Python to minimize actual writing to disk, which is comparably slow. Closing a file ensures that these changes are actually written.\n",
"\n",
"To avoid forgetting to close a file there is the with-statement."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"with open('data_new.txt', 'w') as f:\n",
" f.write('roof roof roof\\n')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This opens the specified file and holds the file-object within ``f``, as well as closing the file when the with-codeblock ends. Afterwards, the file is properly closed and not available anymore."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"What's behind the ``with`` is called a “context manager”. This is a far more general concept, which tends to be useful whenever you need to maintain “external invariants” – which is jargon for “cleaning up after yourself”. For instance, you can use context managers to reliably remove temporary files, log out from services that have some session management, stop background jobs started, and even reset things within your program. If you come back here later, you'll understand the next piece of language: Check out the contextlib module."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Exercise 2"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Work with the file data/autofahrt.txt\n",
"\n",
"Continuing from the example in the 'Reading files' section, read in columns one (=time $t$) and another of columns two to four (=acceleration $\\ddot x(t)$, $\\ddot y(t)$, $\\ddot z(t)$). Note there are two descriptive (\"header\") lines at the start.\n",
"\n",
"Then, write out the two columns to new file."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# enter your solution here"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Note"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "skip"
}
},
"source": [
"The above shows you how you can read and write any data file. Of course, there are also functions that exist to help you read in data in certain formats (for example ``numpy`` contains a function ``numpy.loadtxt`` to read in arrays from files) but the key is that with the above, you can read in any file."
]
}
],
"metadata": {
"anaconda-cloud": {},
"kernelspec": {
"display_name": "Python 3",
"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.5"
}
},
"nbformat": 4,
"nbformat_minor": 1
}
@@ -0,0 +1,661 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Modules and Variable Scope"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Modules"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "skip"
}
},
"source": [
"One of the strengths of Python is that there are many built-in add-ons - or\n",
"*modules* - which contain existing functions, classes, and variables which allow you to do complex tasks in only a few lines of code. In addition, there are many other third-party modules (e.g. Numpy, Scipy, Matplotlib) that can be installed, and you can also develop your own modules that include functionalities you commonly use."
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"The built-in modules are referred to as the *Standard Library*, and you can\n",
"find a full list of the available functionality in the [Python Documentation](http://docs.python.org/3/library/index.html)."
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"To use modules in your Python session or script, you need to **import** them. The\n",
"following example shows how to import the built-in ``math`` module, which\n",
"contains a number of useful mathematical functions:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import math"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"You can then access functions and other objects in the module with ``math.<function>``, for example:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"math.sin(2.3)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"math.factorial(10)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"math.pi"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"Because these modules exist, it means that if what you want to do is very common, it means it probably already exists, and you won't need to write it (making your code easier to read)."
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"For example, the ``numpy`` module, which we will talk about tomorrow, contains useful functions for finding e.g. the mean, median, and standard deviation of a sequence of numbers:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import numpy as np"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"li = [1,2,7,3,1,3]\n",
"np.mean(li)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"outputs": [],
"source": [
"np.median(li)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"np.std(li)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"np.std? # check the definition, read the manual."
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"Notice that in the above case, we used:\n",
"\n",
" import numpy as np\n",
" \n",
"instead of:\n",
"\n",
" import numpy\n",
" \n",
"which shows that we can rename the module so that it's not as long to type in the program."
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"Finally, it's also possible to simply import the functions needed directly:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from math import sin, cos\n",
"sin(3.4)\n",
"cos(3.4)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"You may find examples on the internet that use e.g.\n",
"\n",
" from module import *\n",
" \n",
"but this is **not** recommended, because it will make it difficult to debug programs, since common debugging tools that rely on just looking at the programs will not know all the functions that are being imported."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Where to find modules and functions"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "skip"
}
},
"source": [
"How do you know which modules exist in the first place? The Python documentation contains a [list of modules in the Standard Library](http://docs.python.org/3/library), but you can also simply search the web. Once you have a module that you think should contain the right kind of function, you can either look at the documentation for that module, or you can use the tab-completion in IPython:\n",
" \n",
" In [2]: math.<TAB>\n",
" math.acos math.degrees math.fsum math.pi\n",
" math.acosh math.e math.gamma math.pow\n",
" math.asin math.erf math.hypot math.radians\n",
" math.asinh math.erfc math.isinf math.sin\n",
" math.atan math.exp math.isnan math.sinh\n",
" math.atan2 math.expm1 math.ldexp math.sqrt\n",
" math.atanh math.fabs math.lgamma math.tan\n",
" math.ceil math.factorial math.log math.tanh\n",
" math.copysign math.floor math.log10 math.trunc\n",
" math.cos math.fmod math.log1p \n",
" math.cosh math.frexp math.modf "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Exercise 1"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"* Does the ``math.cos`` funtion take radians or degrees?\n",
"\n",
"* Serch for functions that can convert between radians and degrees.\n",
"\n",
"* Use these to find the cosine of 60 degrees, and the sine of $\\pi/6$ radians."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# enter your solutions here\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Variable scope"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Local scope"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In the following example, the variables defined in the function are not available outside the function:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def do_something():\n",
" a = 1\n",
"print(a)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The variable ``a`` is defined in the **local scope** of the function."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Global scope"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"Consider the following example:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def show_var():\n",
" print(a, b)\n",
"\n",
"a = 1 \n",
"b = 2\n",
"show_var()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In this case, the function knows about the variables defined outside the function. The variables are in the **global scope**. This is very useful because it means that modules don't have to be imported inside functions, you can import them at the top level:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import numpy as np\n",
"\n",
"def normalize(x):\n",
" return x / np.mean(x)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"a=[5,3,5,7,8,3]\n",
"normalize(a)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This works because modules are objects in the same sense as any other variable. In practice, this does **not** mean that you should ever use:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def show_var():\n",
" print(a)\n",
"\n",
"a = 1 \n",
"show_var()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"because it makes the code harder to read. The exception to this are modules, and variables that remain constant during the execution of the program (such as pi, or physical constants). See the PEP8 section below for more details."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Local scope has precedence over global scope"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Consider the following example:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def show_var():\n",
" print(a)\n",
" a = 2\n",
"\n",
"a = 1 \n",
"show_var()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"What happened? Variables defined anywhere inside a function are part of the **local scope** of the function. Any variable in the local scope takes precedence over any other variable, **even before it is actually used**:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def show_var():\n",
" print(a)\n",
" a = 2"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In this case, ``a`` is defined inside the function and so it doesn't matter if a is used anywhere else in the Python code. The above function will therefore not work because ``a`` is used before it is defined."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Exercise 2"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"What will the following code print? (think about it, don't run it!):\n",
"\n",
" def double(x):\n",
" x = x * 2\n",
" print(x)\n",
"\n",
" x = 1\n",
" double(x)\n",
" print(x)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"and what about this code?:\n",
"\n",
" def append_3(x):\n",
" x.append(3)\n",
" print(x)\n",
"\n",
" x = [1,2]\n",
" append_3(x)\n",
" print(x)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Ok, you can try them out now!"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## PEP8 style"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"[=Python Enhancement Proposal 8]\n",
"\n",
"We just touched on the idea of constants being used in functions - but Python does not *really* have constants, so how do we recognize these? We now need to speak about coding style."
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"There is a set of style guidelines referred to as PEP8, which you can find [here](http://www.python.org/dev/peps/pep-0008/). These guidelines are not compulsory, but you should follow them as much as possible, especially when you have to work with other people or need other people to read your code."
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"You don't need to read the guidelines now, but I will first give a couple of examples, then I will show you a tool that can help you follow the guidelines. The following example does not follow the style guidelines:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"alpha = 1/137.036\n",
"def CalculateValues(x):\n",
" return(x*alpha)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Constants should be made uppercase, and function names should be lower case separated by underscores (the so called *camel-case* used above is reserved for classes)."
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"This is the correct way to write the code:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"ALPHA = 1/137.036\n",
"\n",
"def calculate_values(x):\n",
" return(x * ALPHA)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"Other examples include that indentation should always be 4 spaces, etc. In practice, you can check your code with [this script](https://github.com/PyCQA/pycodestyle) although this does not work in the notebook. Download the script to the folder where you are writing code, and do:\n",
"\n",
" python pycodestyle.py my_script.py\n",
" \n",
"where ``my_script.py`` is the script you want to check. For example, you might see:\n",
"\n",
" my_script.py:2:1: W191 indentation contains tabs\n",
" \n",
"The errors include the line number."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"One additional point from PEP 8 can be raised here:\n",
"\n",
"Make sure your code is never wider than 79 characters (with 72 characters a desirable limit).\n",
"\n",
"Why?\n",
"\n",
"1. 80 characters is about what the average human can largely take in “at a glance”, without having to visually follow lines and such. That's why books are printed the way they are. And why xterms and such should be 80 columns wide.\n",
"2. When using version control, lines of that size still make useful diffs (i.e., changes from one version to another). Have longer lines, and you have lots of spurious material people have to scan to find what's actually changed.\n",
"\n",
"This is true not only for python source code. Make it a habit for TeX, markdown, whatever."
]
}
],
"metadata": {
"anaconda-cloud": {},
"kernelspec": {
"display_name": "Python 3",
"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.10"
}
},
"nbformat": 4,
"nbformat_minor": 1
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,722 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Introduction to Matplotlib\n",
"=="
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "skip"
}
},
"source": [
"Now that we can start doing serious numerical analysis with Numpy arrays, we also reach the stage where we can no longer print out hundreds or thousands of values, so we need to be able to make plots to show the results."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The **Matplotlib** package can be used to make scientific-grade plots. You can import it with:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import matplotlib.pyplot as plt"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"In a jupyter notebook, it is often helpful to add a cell containing:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"%matplotlib inline"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"(``%matplotlib`` is a so-called \"magic function\") so that the plots will appear inside the notebook.\n",
"\n",
"In more recent versions of matplotlib there is also ``%matplotlib notebook`` which is an interactive output."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Basic plotting"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"The main plotting function is called ``plot``:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"plt.plot([1,2,3,6,4,2,3,4])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In the above example, we only gave a single list, so it will assume the x values are the indices of the list/array."
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"However, we can instead specify the x values:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"plt.plot([3.3, 4.4, 4.5, 6.5], [3., 5., 6., 7.])"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"Matplotlib can take Numpy arrays, so we can do for example:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import numpy as np\n",
"x = np.linspace(0., 10., 50)\n",
"y = np.sin(x)\n",
"plt.plot(x, y)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"The ``plt.plot()`` function is actually quite complex, and for example can take arguments specifying the type of point, the color of the line, and the width of the line:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"plt.plot(x, y, marker='o', color='green', linewidth=2)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"The line can be hidden with:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"plt.plot(x, y, marker='o', color='green', linewidth=0)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"If you are interested, you can specify some of these attributes with a special syntax, which you can read up more about in the Matplotlib documentation:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"plt.plot(x, y, 'go') # means green and circles"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Exercise 1"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We start off by loading the ``data/munich_temperatures_average_with_bad_data.txt`` file which we encountered in the introduction to Numpy (section 10):"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# The following code reads in the file and removes bad values\n",
"import numpy as np\n",
"date, temperature = np.loadtxt('data/munich_temperatures_average_with_bad_data.txt', unpack=True)\n",
"keep = np.abs(temperature) < 90\n",
"date = date[keep]\n",
"temperature = temperature[keep]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now that the data has been read in, plot the temperature against time:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# your solution here"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Next, plot the data against the fraction of the year (all years on top of each other).\n",
"For this, the ``%`` (modulo) operator is useful to find the fractional part of the dates:\n",
" 1982.2762%1 = 0.2762"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# your solution here"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Other types of plots"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Scatter plots"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"While the ``plt.plot()`` function can be used to show scatter plots, it is mainly used for line plots, and the ``plt.scatter()`` function is more often used for scatter plots, because it allows more fine control of the markers:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"x = np.random.random(100)\n",
"y = np.random.random(100)\n",
"plt.scatter(x, y)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Histograms"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"Histograms are easy to plot using the ``plt.hist()`` function:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"v = np.random.uniform(0., 10., 100)\n",
"h = plt.hist(v,bins=[0,2,4,6,8,10],density=True) # we do h= to capture the output of the function, but we don't use it (here)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In older version of python, the option to normalize the histogram was called ``normed=True``, but this now often puts out warnings or does not work anymore."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Images"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"You can also show two-dimensional arrays with the ``plt.imshow()`` function:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"array = np.random.random((64, 64))\n",
"plt.imshow(array)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"And the colormap can be changed:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"plt.imshow(array, cmap=plt.cm.gist_heat)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Contours"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Often, countour plots are useful to illustrate 3D data. This can be done using ``plt.contour()``:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"x = np.arange(-2.0, 2.0, 0.005)\n",
"y = np.arange(-2.0, 2.0, 0.005)\n",
"xx, yy = np.meshgrid(x, y)\n",
"zz = np.exp(-xx**2 - yy**2)*(xx-yy)**2\n",
"\n",
"plt.axes().set_aspect('equal') # equal aspect ratio\n",
"\n",
"contour_set = plt.contour(xx, yy, zz) # returns a set of contour lines for plt.clabel\n",
"plt.clabel(contour_set) # creates labels with gaps in the contours"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In the above, we used the ``np.meshgrid()`` function which is useful when the plotting functions (and also other functions in general) require the ``X`` and ``Y`` coordinates in a special format. To understand the ``np.meshgrid()`` function better, consider the following example:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# For example:\n",
"x = [1,2,3]\n",
"y = [1,2]\n",
"a, b = np.meshgrid(x, y)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"print(np.shape(a), np.shape(b))\n",
"print(a)\n",
"print(b)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"So for each of the chosen ``x`` and ``y`` points, ``a`` and ``b`` contain the values of ``x`` and ``y``, respectively."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# at coordinate (0|1), we have (note: the first index determines y, the second x)\n",
"print(x[0], y[1], a[1][0], b[1][0])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Field lines"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"For a **vector field**, you can plot a depiction of the field lines with **plt.streamplot()**\n",
"\n",
"Here this is done in the x-y plane for the field\n",
" $$\\vec{K}(\\vec{r})=\\vec{K}(x,y,z) = (-y,x,0) = \\vec{e}_z \\times \\vec{r}$$\n",
" \n",
"We again use **np.meshgrid()** :"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"x=np.arange(-10,10,0.1)\n",
"y=np.arange(-10,10,0.1)\n",
"\n",
"xx,yy=np.meshgrid(x,y) # define meshgrid of all coordinates\n",
" # (can also work out radii etc)\n",
"kx =-yy\n",
"ky = xx\n",
"\n",
"plt.streamplot(x,y,kx,ky,color='k')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Customizing plots"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"You can also customize plots. For example, the following code adds axis labels, and sets the x and y ranges explicitly:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"x = np.random.random(100)\n",
"y = np.random.random(100)\n",
"plt.scatter(x, y)\n",
"plt.xlabel('x values')\n",
"plt.ylabel('y values')\n",
"plt.xlim(0., 1.)\n",
"plt.ylim(0., 1.)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Saving plots to files"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"To save a plot to a file, you can do for example:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"x = np.random.random(100)\n",
"y = np.random.random(100)\n",
"plt.scatter(x, y)\n",
"plt.xlabel('x values')\n",
"plt.ylabel('y values')\n",
"plt.xlim(0., 1.)\n",
"plt.ylim(0., 1.)\n",
"\n",
"plt.savefig('my_plot.png')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"and you can then view the resulting file like you would view a normal image (check the current folder)."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Interactive plotting"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"One of the features of Matplotlib is the ability to make interactive plots. When using IPython, you can do:\n",
"\n",
" %matplotlib qt\n",
" \n",
"or\n",
"\n",
" %matplotlib notebook\n",
" \n",
"(somwhat dependent on the version) to change the backend to be interactive, after which plots that you make will be interactive."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Learning more"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "skip"
}
},
"source": [
"The easiest way to find out more about a function and available options is to use the ``?`` help in IPython:\n",
"\n",
" In [11]: plt.hist?\n",
"\n",
" Definition: plt.hist(x, bins=10, range=None, normed=False, weights=None, cumulative=False, bottom=None, histtype='bar', align='mid', orientation='vertical', rwidth=None, log=False, color=None, label=None, stacked=False, hold=None, **kwargs)\n",
" Docstring:\n",
" Plot a histogram.\n",
"\n",
" Call signature::\n",
"\n",
" hist(x, bins=10, range=None, normed=False, weights=None,\n",
" cumulative=False, bottom=None, histtype='bar', align='mid',\n",
" orientation='vertical', rwidth=None, log=False,\n",
" color=None, label=None, stacked=False,\n",
" **kwargs)\n",
"\n",
" Compute and draw the histogram of *x*. The return value is a\n",
" tuple (*n*, *bins*, *patches*) or ([*n0*, *n1*, ...], *bins*,\n",
" [*patches0*, *patches1*,...]) if the input contains multiple\n",
" data.\n",
"\n",
" etc.\n",
"\n",
"But sometimes you don't even know how to make a specific type of plot, in which case you can look at the [Matplotlib Gallery](http://matplotlib.org/gallery.html) for example plots and scripts.\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Exercise 2"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"1. Use Numpy to generate 10000 random values following a Gaussian/Normal distribution using ``np.random.normal()``, and make a histogram. Adjust the number of bins to properly see the Gaussian. Over-plot a Gaussian function using a colored line, and adjust the normalization so that the histogram and the line are aligned.\n",
"\n",
"2. Do the same for a Poisson distribution. Compare the Poisson distribution for expectation values $\\lambda <15$ with the appropriate Gaussian."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# your solution here"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Exercise 3 [Bonus]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Work out the magnetic field lines of two equal but infinite line currents along the z-axis that are separated by a distance $a$ along the y-axis.\n",
"\n",
"Since the stream lines are scaled, one can drop constants.\n",
"\n",
"The $\\vec{B}$-Field of a single line current $I$ is\n",
"$$\\vec{B} (\\vec{r})= \\frac{\\mu_0 I}{2 \\pi} \\frac{1}{|\\vec{r}|} \\vec{e}_{\\varphi}$$\n",
" \n",
"**Only** with time left: Can you plot the fieldlines in the x-y plane for a circular coil with radius a in the x-z plane?\n",
"The Biot-Savart law for a wire element is\n",
"\n",
"$$d\\vec{B} (\\vec{r})= \\frac{\\mu_0 I}{4 \\pi} \\frac{d \\vec{l} \\times \\vec{r}}{|\\vec{r}|^3}$$\n",
"\n",
"where $\\vec{r}$ is the vector from the current element to the place of measurement.\n",
"\n",
"You can even code the problem in a way that you can add an aribitrary number of coils, e.g. for a long coil or a ring coil (torus)."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# your solution here"
]
}
],
"metadata": {
"anaconda-cloud": {},
"kernelspec": {
"display_name": "Python 3",
"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.10"
}
},
"nbformat": 4,
"nbformat_minor": 1
}
@@ -0,0 +1,237 @@
{
"cells": [
{
"cell_type": "markdown",
"id": "3411da4f",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"# Files and paths"
]
},
{
"cell_type": "markdown",
"id": "79899374",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"At the start of the course, we learned how to manipulate strings, and how to read/write files. In this lecture, we go over a few useful features of Python that make it easier to deal with lists of files, as well as formatting data into strings (which can be useful for e.g. constructing filenames or writing data)"
]
},
{
"cell_type": "markdown",
"id": "b1d6b7c5",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"## The ``glob`` module"
]
},
{
"cell_type": "markdown",
"id": "0bfef1a1",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"In the Linux command-line, it is possible to list multiple files matching a pattern with e.g.:\n",
"\n",
" $ ls *.py\n",
"\n",
"This means list all files ending in ``.py``."
]
},
{
"cell_type": "markdown",
"id": "791f6ec1",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"The built-in [glob](http://docs.python.org/3/library/glob.html) module allows you to do something similar from Python. The only important function here in the ``glob`` module is also called ``glob``."
]
},
{
"cell_type": "markdown",
"id": "29d4e1a5",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"This function can be given a pattern (such as ``*.py``) and will return a list of filenames that match:"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "5fcdf6ae",
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "-"
}
},
"outputs": [],
"source": [
"import glob\n",
"glob.glob('*.ipynb')"
]
},
{
"cell_type": "markdown",
"id": "2f79ab0e",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"## The ``os`` module"
]
},
{
"cell_type": "markdown",
"id": "3a8350a9",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"The [os](http://docs.python.org/3/library/os.html) module allows you to interact with the system, and also contains utilities to construct or analyse file paths. The ``os.path`` sub-module is particularly useful for accessing files - for example,"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "1d30916a",
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import os\n",
"os.path.exists('test.py')"
]
},
{
"cell_type": "markdown",
"id": "400cce00",
"metadata": {},
"source": [
"can be used to find out if a file exists."
]
},
{
"cell_type": "markdown",
"id": "990df34a",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"When constructing the path to a file, for example ``data/file.txt``, one normally has to worry about whether this file is a Linux/Mac or a Windows file path (since Linux/Mac use ``/`` and Windows uses ``\\``). However, the ``os`` module allows you to construct file paths without worrying about this:"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "f1cf772d",
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"os.path.join('data', 'file.txt')"
]
},
{
"cell_type": "markdown",
"id": "cb3cf242",
"metadata": {},
"source": [
"This can be combined with glob, for example:\n",
"\n",
" glob.glob(os.path.join('data', '*.txt'))"
]
},
{
"cell_type": "markdown",
"id": "1ab36e6d",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"The ``os`` module also has other useful functions which you can find about from the [documentation](http://docs.python.org/3/library/os.html)."
]
},
{
"cell_type": "markdown",
"id": "ce9eaaec",
"metadata": {},
"source": [
"## Exercise"
]
},
{
"cell_type": "markdown",
"id": "46cf3c86",
"metadata": {},
"source": [
"The ``os.path.getsize`` function can be used to find the size of a file in bytes. Do a loop over all the files in the current directory using ``glob`` and for each one, print out the filename and the size in kilobytes (1024 bytes):"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "daf7e0fc",
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"# your solution here"
]
}
],
"metadata": {
"anaconda-cloud": {},
"kernelspec": {
"display_name": "Python [Root]",
"language": "python",
"name": "Python [Root]"
},
"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.5.2"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
@@ -0,0 +1,325 @@
{
"cells": [
{
"cell_type": "markdown",
"id": "5ec829a7",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"# String formatting"
]
},
{
"cell_type": "markdown",
"id": "130cc097",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"We have talked about strings before, and you know that it is possible to construct strings containing values, e.g."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "51d2701f",
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"'x=' + str(43.2) + ', y=' + str(1./3.)"
]
},
{
"cell_type": "markdown",
"id": "bf0f4231",
"metadata": {},
"source": [
"However, one may want to format the values in more detail, for example forcing values to be a certain length, or have a certain number of decimal places. This is called *string formatting*."
]
},
{
"cell_type": "markdown",
"id": "8a6a1b0e",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"The syntax for formatting strings looks like this:"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "462c1d03",
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "-"
}
},
"outputs": [],
"source": [
"\"{0} {1} {2}\".format(1./3., 2./7., 2.)"
]
},
{
"cell_type": "markdown",
"id": "e2522672",
"metadata": {
"slideshow": {
"slide_type": "-"
}
},
"source": [
"In the above example, the ``0``, ``1``, and ``2`` refer to the position of the argument in the parentheses, so one could also do:"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "131d89ab",
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "-"
}
},
"outputs": [],
"source": [
"\"The quantity {0} that could also be called {0} {1}\".format(1./3., 2./7.)"
]
},
{
"cell_type": "markdown",
"id": "8b98fc21",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"By default, the value looks the same as if one had used ``str()``, but you can also specify the format and number of decimal places:"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "c417f3b5",
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "-"
}
},
"outputs": [],
"source": [
"\"{0:10.3f}\".format(1./3.)"
]
},
{
"cell_type": "markdown",
"id": "c5257ae2",
"metadata": {},
"source": [
"The ``f`` stands for floating-point, the 10 is the total length of the string, and the 3 is the nuber of decimal places."
]
},
{
"cell_type": "markdown",
"id": "a9fe4cd2",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"We can do something similar for integers (without the number of decimal places):"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "3c7f537f",
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"\"{0:10d}\".format(4)"
]
},
{
"cell_type": "markdown",
"id": "787175da",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"There are a number of options for string formatting - for instance, one can add leading zeros:"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "14c4d480",
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [],
"source": [
"\"{0:010d}\".format(4)"
]
},
{
"cell_type": "markdown",
"id": "f3895f73",
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"source": [
"or align to the left:"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "63d1da2d",
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [],
"source": [
"\"{0:<10d}\".format(4)"
]
},
{
"cell_type": "markdown",
"id": "c0ca021a",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"Instead of using ``0``, ``1``, etc. it is also possible to pass the values by name:"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "8867ffb4",
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [],
"source": [
"\"{day:02d}\".format(day=3)"
]
},
{
"cell_type": "markdown",
"id": "84803075",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"Here is an example of string formatting for a date:"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "dcf4ee9c",
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"\"{year:04d}{month:02d}{day:02d}\".format(year=2013, month=7, day=8)"
]
},
{
"cell_type": "markdown",
"id": "99bf270d",
"metadata": {},
"source": [
"## Exercise 1"
]
},
{
"cell_type": "markdown",
"id": "c05ba888",
"metadata": {},
"source": [
"Write a function that takes year, month, day, hour, minutes, and seconds and converts them to a string with format ``2006-03-22 13:12:55``:"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "67999f6a",
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"# your solution here"
]
},
{
"cell_type": "markdown",
"id": "1a7cfc85",
"metadata": {},
"source": [
"## Exercise 2"
]
},
{
"cell_type": "markdown",
"id": "c80325a6",
"metadata": {},
"source": [
"Write a function that takes a string like ``2006-03-22 13:12:55`` and return the year, month, day, hour, minutes, and seconds as integers:"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "77fc6ff6",
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"# your solution here"
]
}
],
"metadata": {},
"nbformat": 4,
"nbformat_minor": 5
}
@@ -0,0 +1,931 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"# Python variables - behind the scenes"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"We will now examine how Python stores objects in memory, and the link between variables and memory location. You might be wondering why you need to worry about this, but it is actually essential to understand this in order to make best use of Python's capabilities and avoid mistakes/bugs."
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"## Assignment and modification"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"Consider the following two examples. First:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"a = 2\n",
"b = a\n",
"print(a, b)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"a = 4\n",
"print(a, b)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This should hopefully make sense so far."
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"Now consider the following example: "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"a = [2, 3, 4]\n",
"b = a\n",
"a.append(5)\n",
"print(a, b)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In this case, modifying ``a`` modified ``b`` too! This is not as intutitive... But if we do:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"a = 9\n",
"print(a, b)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This time, changing ``a`` did not change ``b`` - what is happening?"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"The key is to understand that doing:\n",
" \n",
" variable = something\n",
" \n",
"will change which object ``variable`` is pointing to in memory (**assignment**). On the other hand, when calling a method with:\n",
"\n",
" variable.method()\n",
"\n",
"some (but not all) methods will modify the variable **in-place** (more information below)."
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"Let's go over the examples above but this time with a graphical representation, where the yellow circles show the **variables**, and the blue rectangles show the **objects in memory**. If we do:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"a = 2\n",
"b = a\n",
"a = 4"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"then what is happening is the following."
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"First, when doing ``a = 2`` we create space in memory for the value ``2`` and we assign that location in memory to the variable ``a``:\n",
"\n",
"![ex1_1](http://wwwstaff.ari.uni-heidelberg.de/rschmidt/pycourse/graphics/ex1_1.png)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"By doing ``b = a``, we are now assigning the variable ``b`` to point at the same object as ``a``:\n",
"\n",
"![ex1_2](http://wwwstaff.ari.uni-heidelberg.de/rschmidt/pycourse/graphics/ex1_2.png)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"And finally by doing ``a = 4`` we re-assign ``a`` to point at a different place in memory (containing ``4``) but ``b`` still points at the same object (``2``):\n",
"\n",
"![ex1_3](http://wwwstaff.ari.uni-heidelberg.de/rschmidt/pycourse/graphics/ex1_3.png)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"Now if we follow the same logic for the second example:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"a = [2, 3, 4]\n",
"b = a\n",
"a.append(5)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"we again start off by creating space in memory for the list ``[2, 3, 4]``, then we point the variable ``a`` to that location.\n",
"\n",
"![ex2_1](http://wwwstaff.ari.uni-heidelberg.de/rschmidt/pycourse/graphics/ex2_1.png)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"By doing ``b = a``, we then point ``b`` to the same location as ``a``, so **the list exists only once in memory** (this is very important):\n",
"\n",
"![ex2_2](http://wwwstaff.ari.uni-heidelberg.de/rschmidt/pycourse/graphics/ex2_2.png)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"We now **modify, in-place,** the object that ``a`` is pointing to with ``a.append(5)`` - the concept of modifying the object is very important - we are not creating a new list, it is still in the same place in memory, even if it has one extra element now:\n",
"\n",
"![ex2_3](http://wwwstaff.ari.uni-heidelberg.de/rschmidt/pycourse/graphics/ex2_3.png)\n",
"\n",
"This means that since ``b`` is pointing to the same place in memory, it will also see a list with (now) four elements!"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"Then, if one does ``a = 9``, then one is not modifying the list, but instead assigning ``a`` to point to a region in memory with the value ``9``:\n",
"\n",
"![ex2_4](http://wwwstaff.ari.uni-heidelberg.de/rschmidt/pycourse/graphics/ex2_4.png)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In order to talk about this behavior, we use the terms **copying** and **referencing**. When we do:\n",
"\n",
" variable = something\n",
"\n",
"then the **value** is actually created when writing ``something``. The assignment merely creates a pointer (“reference” is just a fancy name for that) from a name to that value, and you could have more such names pointing to the same something."
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"Another important point is that what is on the right hand side will get evaluated first, and will (conceptually) result in the creation of a new object unless the ``something`` is a reference already (in which case ``variable`` and ``something`` will just refer to the same value. In the following cases, ``something`` is a “literal” (i.e., the representation of a value in the source code), and a new value will be created:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"a = 2\n",
"b = a + 1\n",
"c = b * 2\n",
"print(a, b, c)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In the second assignment in the following, ``something`` is a reference, and hence no new object is being created:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"a = [2,3,4]\n",
"b = a # b points to the same object than a"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Python's built-in ``id()`` function will tell you the identity of its argument:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"id(a), id(b), id(c)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"## Copying"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In some cases, the behavior described above is not desirable, and we want to make a true copy, not just a reference, *because we want to change* ``b`` *without changing* ``a``:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from copy import deepcopy\n",
"a = [2,3,4]\n",
"b = deepcopy(a)\n",
"a.append(5)\n",
"print(a, b)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"id(a),id(b)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The ``copy`` module contains a function ``copy``, too. If you want to really understand what's going on, it will probably help to create a nested list (as in ``[range(2), range(3)]``), copy that and manipulate the inner lists.\n",
"\n",
"Note that slicing (usually) creates a copy, too (but be careful with numpy arrays), which is why in quite a bit of source code you see slices when a copy is desired:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"a = range(4)\n",
"b = a[:]\n",
"id(a),id(b)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"## Methods"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"As mentioned above, some *methods* modify object **in-place**:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"a = [1,2,3]\n",
"a.append(5) # modifies ``a``"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"and some will return a copy rather than modifying the object."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"s = 'hello'\n",
"s2=s.upper() # returns a copy of the string in uppercase without modifying s\n",
"id(s),id(s2)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"It should be clear from the documentation (e.g. ``s.upper?``) how a particular method behaves."
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"## Mutable vs immutable objects"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"Some objects are **immutable**, which means that they cannot be modified - examples include ``float``, ``int``, ``str``. For instance, when doing:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"a = 1.\n",
"print (id(a))\n",
"a = 2. \n",
"print (id(a))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In the second line, a new location in memory is created for ``2.``, and ``a`` points at that object, not at ``1.`` (in other words, the float is not being changed, it is ``a`` that is pointing to a different object)."
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"On the other hand, ``list``, ``dict``, and Numpy arrays are **mutable**, which means the object can be modified:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"a = [1,2,3]\n",
"a.append(5)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"After the second line, ``a`` still points at the same list, but the list has now been modified."
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"## Functions"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"A final but important point is that when passing variables to functions, variables are passed as references, so:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"def do(x):\n",
" x.append(1)\n",
" \n",
"a = [1,2]\n",
"do(a)\n",
"print(a)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"The following, however, just changes the value ``x`` in ``do`` references and thus has no effect outside of ``do``:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"def do(x):\n",
" x = 0 # re-assigns x to 0, but only in the function\n",
"\n",
"a = [1,2]\n",
"do(a)\n",
"print(a)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"## Copying and Referencing Numpy arrays"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"With Numpy arrays, one has to be particularly careful with the copying/referencing distinction. With a few exceptions (and superficially contrary to the behaviour of almost all other python objects), most slicing/masking operations in Numpy indicate **references**, not copies, to the data:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"import numpy as np"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"x = np.arange(10)\n",
"y = x\n",
"y[3] = 1"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"x"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"This is similar to lists, but now consider the following:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"x = np.arange(10)\n",
"y = x[::2]\n",
"y[3] = 1"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"x"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"Even though we took a slice with a given start, end, and slice, the resulting array was still just a reference, or **view**, of the array in the original array! (note that for lists, ``x[::2]`` returns a copy!). This can be very handy when combined with masking:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"x = np.arange(10)\n",
"x[x < 5] = 0.\n",
"x"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"There is one exception to the referencing, which is:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"x = np.arange(10)\n",
"y = x[[1,3,2,2]] # returns a new array, not a view\n",
"y[0] = 9\n",
"x"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"As before, you can explore this further to understand in what cases references or copies are made. However, be aware that using ``id()`` on a view *will* be different from the original array, even though the view is actually pointing to a subset of the original array."
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"In the case of Numpy arrays, one can force a copy by doing:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"x = np.arange(10)\n",
"y = x.copy()\n",
"y[0] = -1"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"x"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"y"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Before you start cursing the numpy authors because it might seem they were out to confuse you: They did this because very common operations become very fast in this way, and in practice that's much less of a trap than you may suspect."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Exercise"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The following questions are just to test your understanding of the variable assignment - you don't need to write any code - just try and think of what the output will be, then you can try it out to check if you got it right:\n",
"\n",
"What will ``a`` be after the following?\n",
"\n",
" a = [1, 3., [1, 2, 3], 'hello']\n",
" b = a[0]\n",
" b = 4."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"What will ``c`` be after the following?\n",
"\n",
" c = [1, 3., [1, 2, 3], 'hello']\n",
" d = c[2]\n",
" d.append(8)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"What will ``e`` be after the following?\n",
"\n",
" e = [1, 3., [1, 2, 3], 'hello']\n",
" f = e[2]\n",
" f = [1, 2]"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"What will ``g`` be after the following?\n",
"\n",
" g = [1, 2, 3, 4]\n",
" h = g[::2]\n",
" h[0] = 9\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"What will ``i`` be after the following?\n",
"\n",
" import numpy as np\n",
" i = np.array([1, 2, 3, 4])\n",
" j = i[::2]\n",
" j[0] = 9"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# You can try it here."
]
}
],
"metadata": {
"anaconda-cloud": {},
"kernelspec": {
"display_name": "Python 3",
"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.10"
}
},
"nbformat": 4,
"nbformat_minor": 1
}
@@ -0,0 +1,434 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"# Introduction to Scipy: Fitting data"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"We have talked about the Numpy and Matplotlib libraries, but there is a third library that is invaluable for Scientific Analysis: [Scipy](http://www.scipy.org). Scipy is basically a very large library of functions that you can use for scientific analysis. A good place to start to find out about the top-level scientific functionality in Scipy is the [Documentation](http://docs.scipy.org/doc/scipy/reference/)."
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"Examples of the functionality include:\n",
"\n",
"* Integration (scipy.integrate)\n",
"* Optimization/Fitting (scipy.optimize)\n",
"* Interpolation (scipy.interpolate)\n",
"* Fourier Transforms (scipy.fftpack)\n",
"* Signal Processing (scipy.signal)\n",
"* Linear Algebra (scipy.linalg) **[contains e.g. scipy.linalg.inv() as used in chapter 9 with np.linalg.inv()\n",
"for systems of linear equation]**\n",
"* Spatial data structures and algorithms (scipy.spatial)\n",
"* Statistics (scipy.stats)\n",
"* Multi-dimensional image processing (scipy.ndimage)\n",
"\n",
"and so on."
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"In this section, we will take a look at how to fit models to data. When analyzing scientific data, fitting models to data allows us to determine the parameters of a physical system (assuming the model is correct)."
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"There are a number of routines in Scipy to help with fitting, but we will use the simplest one, ``curve_fit()``, which is imported as follows:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import numpy as np\n",
"from scipy.optimize import curve_fit"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The full documentation for the ``curve_fit()`` is available [here](http://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.curve_fit.html#scipy.optimize.curve_fit), and we will look at a simple example here, which involves fitting a straight line to a dataset."
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"We first create a fake/mock dataset with some random noise:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import matplotlib.pyplot as plt\n",
"%matplotlib inline"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"x = np.random.uniform(0., 100., 100)\n",
"y = 3. * x + 2. + np.random.normal(0., 10., 100)\n",
"plt.plot(x, y, '.')"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"Let's now imagine that this is real data, and we want to determine the slope and intercept of the best-fit line to the data. We start off by definining a function representing the model:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def line(x, a, b):\n",
" return a * x + b"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"The arguments to the function should be ``x``, followed by the parameters. We can now call ``curve_fit()`` to find the best-fit parameters using a least-squares fit:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"popt, pcov = curve_fit(line, x, y)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"The ``curve_fit()`` function returns two items, which we call ``popt`` and ``pcov``. The ``popt`` argument are the best-fit paramters for ``a`` and ``b``:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"popt"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"which is close to the initial values of ``3`` and ``2`` used in the definition of ``y``.\n",
"\n",
"The reason the values are not exact is because there are only a limited number of random samples, so the best-fit slope is not going to be exactly those used in the definition of ``y``. The ``pcov`` variable contains the *covariance* matrix, which indicates the uncertainties and correlations between parameters. This is mostly useful when the data has uncertainties."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Important Note:** ``curve_fit()`` by default uses sigma just as weights, i.e., as hints how important a point should be in the least-squares computation. To compute the covariance matrix, it then estimates the actual error essentially from the scatter in the data. If, however, your data points come with (reliable) error estimates, that actually throws away a lot of information, and the covariance matrix is less expressive than it could be. To make ``curve_fit()`` treat its sigma argument as actual error estimates and use their absolute (rather than relative, as with weights) values in pcov calculation, one needs to pass ``absolute_sigma=True``. This is done here."
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"Let's now try and fit the data assuming each point has a vertical error (standard deviation) of +/-10:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"e = np.repeat(10., 100)\n",
"plt.errorbar(x, y, yerr=e, fmt=\"none\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"outputs": [],
"source": [
"popt, pcov = curve_fit(line, x, y, sigma=e, absolute_sigma=True)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"popt"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"Now ``pcov`` will contain the true variance and covariance of the parameters, so that the best-fit parameters are:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"print(\"a =\", popt[0], \"+/-\", pcov[0,0]**0.5)\n",
"print(\"b =\", popt[1], \"+/-\", pcov[1,1]**0.5)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"We can now plot the best-fit line:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"plt.errorbar(x, y, yerr=e, fmt=\"none\")\n",
"xfine = np.linspace(0., 100., 100) # define values to plot the function for\n",
"plt.plot(xfine, line(xfine, popt[0], popt[1]), 'r-')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You should now be able to fit simple models to datasets! Note that for more complex models, more sophisticated techniques may be required for fitting, but ``curve_fit()`` will be good enough for most simple cases."
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"Note that there is a way to simplify the call to the function with the best-fit parameters, which is:\n",
"\n",
" line(x, *popt)\n",
"\n",
"The * notation will expand a list of values into the arguments of the function. This is useful if your function has more than one or two parameters. Hence, you can do:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"plt.errorbar(x, y, yerr=e, fmt=\"none\")\n",
"plt.plot(xfine, line(xfine, *popt), 'r-')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Exercise 1"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In the following code, we generate some random data points:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"x = np.random.uniform(0., 10., 100)\n",
"y = np.polyval([1, 2, -3], x) + np.random.normal(0., 10., 100)\n",
"e = np.random.uniform(5, 10, 100)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Fit a line and a parabola to it and overplot the two models on top of the data:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# your solution here"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Exercise 2"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"As before, we use the [data/munich_temperatures_average_with_bad_data.txt](data/munich_temperatures_average_with_bad_data.txt) file, which gives the temperature in Munich every day for several years:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# The following code reads in the file and removes bad values\n",
"import numpy as np\n",
"date, temperature = np.loadtxt('data/munich_temperatures_average_with_bad_data.txt', unpack=True)\n",
"keep = np.abs(temperature) < 90\n",
"date = date[keep]\n",
"temperature = temperature[keep]\n",
"plt.plot(date,temperature)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Fit the following function to the data:\n",
"\n",
"$$f(t) = a~\\cos{(2\\pi t + b)} + c$$\n",
"\n",
"where $t$ is the time in years.\n",
"\n",
"Make a plot of the data and the best-fit model in the range 2008 to 2012.\n",
"\n",
"What are the best-fit values of the parameters? What is the overall average temperature in Munich, and what are the typical daily average values predicted by the model for the coldest and hottest time of year?\n",
"\n",
"What is the meaning of the ``b`` parameter, and does its value make sense?"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# your solution here"
]
}
],
"metadata": {
"anaconda-cloud": {},
"kernelspec": {
"display_name": "Python 3",
"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.5"
}
},
"nbformat": 4,
"nbformat_minor": 1
}
@@ -0,0 +1,724 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"# Introduction to Scipy: Interpolation and Integration"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"In this section, we will look at two other common sub-packages of Scipy: [scipy.interpolate](http://docs.scipy.org/doc/scipy/reference/interpolate.html) and [scipy.integrate](http://docs.scipy.org/doc/scipy/reference/integrate.html)."
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"## Interpolation"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"The simplest interpolation routine in [scipy.interpolate](http://docs.scipy.org/doc/scipy/reference/interpolate.html) is [interp1d()](http://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.interp1d.html#scipy.interpolate.interp1d):"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from scipy.interpolate import interp1d"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"If we create a fake dataset:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import numpy as np\n",
"x = np.array([0., 1., 3., 4.])\n",
"y = np.array([0., 4., 2.7, 2.08])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"we can interpolate linearly by first creating an interpolating function:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"f = interp1d(x,y)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"type(f)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"and we can then interpolate to any value of x within the original bounds:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"f(0.5)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"f(3.3)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"It is also possible to interpolate to several values at the same time:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"f(np.array([0.5, 1.5, 2.5, 3.5]))"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"If the interpolating function is called outside the original range, an error is raised:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"f(-1.)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"You can change this behavior by telling ``interp1d()`` to not give an error in this case, but to use a set value:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [],
"source": [
"f = interp1d(x, y, bounds_error=False, fill_value=-10.)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [],
"source": [
"f(-1.0)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [],
"source": [
"f(np.array([-1., 1., 3., 6.]))"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"By default, ``interp1d`` uses linear interpolation, but it is also possible to use e.g. cubic **spline** interpolation:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"f = interp1d(x, y, kind='cubic')\n",
"f(0.5)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Let's compare a few ways to interpolate:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import matplotlib.pyplot as plt\n",
"%matplotlib inline"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"xp=np.arange(0,4,0.1)\n",
"\n",
"f = interp1d(x,y)\n",
"g = interp1d(x,y,kind=2) # equivalent to 'quadratic'\n",
"h = interp1d(x,y,kind=3) # equivalen to 'cubic'\n",
"\n",
"plt.plot(xp,f(xp),xp,g(xp),xp,h(xp))\n",
"plt.xlim(0,6)\n",
"plt.legend(['linear','quadratic spline','cubic spline'])"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def orig(x):\n",
" return 3.11-3.11*(x-1)*(x-1)+0.5*x+0.39*x*x*x\n",
"\n",
"xp=np.arange(0,4,0.5)\n",
"print (xp)\n",
"print (orig(xp))\n",
"print (h(xp))"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"For more information, see the documentation for [interp1d()](http://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.interp1d.html#scipy.interpolate.interp1d). There are also other interpolation functions available (for example for spline interpolation), which you can read up about at [scipy.interpolate](http://docs.scipy.org/doc/scipy/reference/interpolate.html). \n",
"\n",
"[Wikipedia](https://en.wikipedia.org/wiki/Spline_%28mathematics%29) also has some information on splines."
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"## Integration"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"The available integration functions are listed at [scipy.integrate](http://docs.scipy.org/doc/scipy/reference/integrate.html#module-scipy.integrate). See also the tutorial [here](http://docs.scipy.org/doc/scipy/tutorial/integrate.html). You will notice there are two kinds of functions - those that integrate actual Python functions, and those that integrate numerical functions defined by Numpy arrays."
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"First, we can take a look at one of the functions that can integrate actual Python functions. If we define a function:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def simple_function(x):\n",
" return 3. * x**2 + 2. * x + 1."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"we can integrate it between limits using:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from scipy.integrate import quad\n",
"print(quad(simple_function, 1., 2.))"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "-"
}
},
"source": [
"As described in the documentation for [quad()](http://docs.scipy.org/doc/scipy/reference/generated/scipy.integrate.quad.html#scipy.integrate.quad), the first value returned is the integral, and the second is the error on the integral. If we had solved the integral analytically, we would expect 11, so the result is correct. The names comes from quadrature for working out the area under curve by splitting it up into know sub-areas."
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"We can also define functions as Numpy arrays:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"x = np.linspace(1., 2., 1000)\n",
"y = 3. * x**2 + 2. * x + 1."
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "-"
}
},
"source": [
"And in this case we can use for example the [simpson()](http://docs.scipy.org/doc/scipy/reference/generated/scipy.integrate.simpson.html#scipy.integrate.simpson) function to integrate using Simpson's rule (stepwise parabolic approximation):"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from scipy.integrate import simpson\n",
"print(simpson(y, x=x))"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"This can be very useful in cases where one wants to integrate actual data that cannot be represented as a simple function or when the function is only available numerically."
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"Finally there is also the ``trapz()`` function which works similarly to ``simpson()`` but does trapezium integration (stepwise linear approximation):"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from scipy.integrate import trapz\n",
"print(trapz(y, x=x))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Exercise 1"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"a) Write a function that takes ``x``, and the parameters for a Gaussian (amplitude, displacement, width) and returns the value of the Gaussian at ``x``:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# your solution .."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"b) Use ``quad()`` to compute the integral and compare to what you would expect."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# your solution here\n",
"\n",
"\n",
"\n",
"# Note the following EXAMPLE\n",
"# for the 'args' argument (tuple) to be passed to the function to be integrated\n",
"#\n",
"# if only one argument is passed, it should be done like this: (1,) so that it still is a tuple\n",
"def func(x,a,b):\n",
" return result\n",
"\n",
"quad(func,0,1,args=(1,1))\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"c) Now create two arrays ``x`` and ``y`` that contain the Gaussian for fixed values ``x``, and try and compute the integral using ``simps()``."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# your solution here"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Compare this to what you found with ``quad()`` and analytically."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Differential equations"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"An important task in scientific computing is to solve differential equations.\n",
"\n",
"*scipy.integrate* also has *odeint* which we use here to solve the damped oscillation\n",
"\n",
"$$\\ddot{x} + 2 \\gamma \\dot{x} + k x = 0$$\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import numpy as np\n",
"import matplotlib.pyplot as plt\n",
"%matplotlib inline\n",
"\n",
"from scipy.integrate import odeint"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"For the *odeint* solver, the differential equation needs to be split up into a system of first-order equations:\n",
"\n",
"(1) $\\dot{x} = v$\n",
"\n",
"(2) $\\dot{v} = -k x - 2 g v$"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def diffeq(x, t,k,g):\n",
"\n",
" #define/clear derivative\n",
" dxdt = np.zeros(2)\n",
"\n",
" \"\"\" differential equation for damped oscillation\n",
" split into first-order equation \n",
" x. = v\n",
" v. = - k x - 2 gamma v\n",
" \"\"\"\n",
" dxdt[0] = x[1]\n",
" dxdt[1] = -k * x[0] - 2 * g * x[1]\n",
"\n",
" return dxdt\n",
"\n",
"\"\"\" constants \"\"\"\n",
"k=0.1\n",
"g=0.1\n",
"\n",
"x = np.array([2.0,-0.8]) # initial position\n",
"time = np.linspace(0.0,100.0,100) # evaluation times\n",
"\n",
"\"\"\" calling the solver \"\"\"\n",
"solution = odeint(diffeq, x, time, args=(k,g))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This is the corresponding analytical solution:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def damped_oscillation(t,x,k,g):\n",
" om=np.sqrt(k-g**2)\n",
" \n",
" A=(x[1]+g*x[0])/om\n",
" B=x[0]\n",
" \n",
" return (A*np.sin(om*t)+B*np.cos(om*t))*np.exp(-g*t)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"plt.plot(time,solution[:,0],time,damped_oscillation(time,x,k,g))\n",
"plt.legend(['Numerical','Analytical'])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Exercise 2"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"a) Plot the motion of a critically damped oscillator $\\gamma$ = $\\sqrt{k}$ "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# solution here"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"b) Extend the differential equation by a forcing $f(x)=A_0 \\cos (\\omega_0 t)$ [choose $A_0$ and $\\omega_0$].\n",
"Consider the initial behaviour of the system."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# solution here"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"c) **only [Bonus]** Solve the time-independent Schrödinger equation\n",
"\n",
"$\\frac{\\hbar^2}{2 m} \\frac{d^2 \\psi}{d x^2} = ( E - V(x) ) \\psi$\n",
"\n",
"for the [quantum harmonical oscillator](https://en.wikipedia.org/wiki/Quantum_harmonic_oscillator) $V(x) = \\frac{1}{2} m \\omega_0^2 x^2$ for the first few states.\n",
"Plot also the probability $|\\psi^* \\psi|$.\n",
"\n",
"**Simplification**: The parameterization $z=ax$ with $a^2=\\frac{\\omega_0 m}{\\hbar}$ with the energy parameter\n",
"$\\lambda = \\frac{2 E}{\\hbar \\omega_0}$ leads to the equation\n",
"\n",
"$\\psi'' - z^2 \\psi(z) + \\lambda \\psi(z) = 0$\n",
"\n",
"**Note**: The first few states can be found using $E = (n+\\frac{1}{2}) \\hbar \\omega_0$ with $n=0, 1, 2, ...$ or $\\lambda = 1, 3, 5, ...$ The states alternate between even and odd functions $\\psi(z)$.\n",
"\n",
"Due to the symmetry, it is enough to consider $z \\geq 0$.\n",
"\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# solution here"
]
}
],
"metadata": {
"anaconda-cloud": {},
"kernelspec": {
"display_name": "Python 3",
"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.10"
}
},
"nbformat": 4,
"nbformat_minor": 1
}
@@ -0,0 +1,341 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Understanding Python Errors"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Reading errors"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"By now, you have likely encountered Python errors very often. Here is an example of an error:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"s = 'hello'\n",
"s[0] = 'a'"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This is called an **exception traceback**. The **exception** is the error itself, and the **traceback** is the information that shows where it occured. The above traceback is quite simple (because the code producing the error is quite simple). The most important thing you should look at in an error is the last line, in this case:\n",
"\n",
" 'str' object does not support item assignment\n",
" \n",
"Now let's look at a slightly more complex error:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import numpy as np\n",
"\n",
"def subtract_smooth(x, y):\n",
" y_new = y - median_filter(x, y, 2.5)\n",
" return y_new\n",
"\n",
"def median_filter(x, y, width):\n",
" y_new = np.zeros(y.shape)\n",
" for i in range(len(x)):\n",
" y_new[i] = np.median(y[np.abs(x - x[i]) < width * 0.5])\n",
" return y_new"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"subtract_smooth(np.array([1,2,3,4,5]),np.array([4,5,6,8]))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The error is now more complex. The first line shows what top-level code was executed when the error occured - in this case the call to ``subtract_smooth``:\n",
"\n",
" IndexError Traceback (most recent call last)\n",
" <ipython-input-3-d9260f0fd73b> in <module>\n",
" ----> 1 subtract_smooth(np.array([1,2,3,4,5]),np.array([4,5,6,8]))\n",
" \n",
"The next chunk shows where the error occured inside ``subtract_smooth``:\n",
"\n",
" <ipython-input-2-149558127e8f> in subtract_smooth(x, y)\n",
" 2 \n",
" 3 def subtract_smooth(x, y):\n",
" ----> 4 y_new = y - median_filter(x, y, 2.5)\n",
" 5 return y_new\n",
"\n",
" \n",
"you can see it happened when calling ``median_filter``. Finally, we can see where the error occured inside ``median_filter``:\n",
"\n",
" <ipython-input-2-149558127e8f> in median_filter(x, y, width)\n",
" 8 y_new = np.zeros(y.shape)\n",
" 9 for i in range(len(x)):\n",
" ---> 10 y_new[i] = np.median(y[np.abs(x - x[i]) < width * 0.5])\n",
" 11 return y_new\n",
" \n",
"So tracebacks show you the full history of the error!\n",
"\n",
"Now in the above case, the final error is:\n",
"\n",
" IndexError: boolean index did not match indexed array along dimension 0; dimension is 4 but corresponding \n",
" boolean dimension is 5\n",
" \n",
"Why is this occuring? The only place that boolean indices are used here is when doing:\n",
"\n",
" np.abs(x - x[i]) < width * 0.5\n",
" \n",
"The issue is that if we look back at the original function call, there are more values for ``x`` than for ``y``!"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Using the debugger"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In the above example, the code was still simple enough that we could guess the solution, but sometimes things are not so simple. One way to diagnose the issue would have been to print out the content of the variables in ``median_filter`` and run it again to see what was going on.\n",
"\n",
"However, Python includes a *debugger*, which allows you to jump right in to where the error happened, and look at the variables. In the IPython notebook or in IPython, once an error has happened, you can run ``%debug``, and you will see a ``ipdb>`` prompt (IPython debugger). You can then print out variables to see what they are set to. Let's try the above example again:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"subtract_smooth(np.array([1,2,3,4,5]),np.array([4,5,6,8]))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"%debug"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can see that the boolean array that is being used as indices to ``y`` is too big. Much simpler! Type ``exit`` to exit the debugger."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Catching exceptions"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In some cases, we know that errors might happen, and we don't want them to crash the code. For example, if we have to read in 1000 files, a few might be corrupt, and we just want to skip over them. Or we want to try something, and if it doesn't work, do something else. To do this, we can **catch** exceptions:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"s = 'hello'"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"s[1] = 'a'"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"try:\n",
" s[1] = 'a'\n",
"except:\n",
" print(\"Can't set s[1]\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The ``try...except`` contruct above catches *all* exceptions, but in some cases we want to be a bit more specific. The error that occurs above is a ``TypeError``, which is just one kind of error (others include ``ValueError``, ``SystemError``, etc.). To catch just ``TypeError``, you can do:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"try:\n",
" s[1] = 'a'\n",
"except TypeError:\n",
" print(\"Can't set s[1]; TypeError\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"If you catch other errors, TypeError will pass"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"try:\n",
" s[1] = 'a'\n",
"except ValueError: \n",
" print(\"Can't set s[1]\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Catching exceptions is tricky business, however, because it can hide important hints for debugging."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Raising Errors"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"If something goes wrong in your code, rather than just printing some warning and going on, it's usually much better to raise an exception yourself. You'll make sure execution halts where an error has occurred, rather than having confusing junk results much later, when it is hard to figure out what went wrong where."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Raising exceptions is not hard:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"raise ValueError(\"But writing good, descriptive error messages is.\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"``raise`` is another reserved word in Python. What's behind it is an exception class; you can define these yourself once you know how to deal with objects and inheritance, but there's nothing wrong with re-using exceptions you know from the standard library: ``ValueError`` if some value doesn't meet your expectation, ``IOError`` if something is wrong with a file, ``KeyError`` if a lookup of something failed... You can always use ``Exception`` (which is a “base class” of all these exceptions) if unsure."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Note, however, that it's almost always a bad idea to catch an exception and re-raise one of your design. You'll most likely be hiding the root cause of the problem, making analysis of the problem much harder."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Also, don't claim more than you know in your error message (and don't execute the following code if you're running your notebook as root (which of course one should not do anyway!)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# THIS IS HOW *NOT* TO DO IT!\n",
"try:\n",
" with open(\"/etc/passwd\", \"a\") as f:\n",
" pass\n",
"except IOError: \n",
" # don't do this anyway: Catch and raise something else\n",
" # And in particular don't claim more than you know.\n",
" raise Exception(\"/etc/passwd does not exist\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"At least on unix systems, the existence claim is patently untrue, as you can verify with ls. What's failed is that you're not allowed to write to that file. By claiming more than you actually know in your error message, you will confuse users."
]
}
],
"metadata": {
"anaconda-cloud": {},
"kernelspec": {
"display_name": "Python 3",
"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.5"
}
},
"nbformat": 4,
"nbformat_minor": 1
}
@@ -0,0 +1,501 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Accessing Remote Resources\n",
"==========================\n",
"\n",
"Web pages and data\n",
"------------------\n",
"\n",
"I have mentioned before how one can access data files on your hard drive, but Python also allows you to access remote data, for example on the internet. The easiest way to do this is to use the [requests](https://pypi.python.org/pypi/requests) module. To start off, you just can get the URL:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import requests\n",
"\n",
"response = requests.get('http://xkcd.com/353/')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"``response`` holds the response now. You can access the content as text via the text-property:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"print(response.text[:300]) # only print the first 300 characters"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can either just use this information directly, or in some cases you might want to write it to a file. Let's download one of the full resolution files for the Ice coverage data from Problem Set 2:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"r2 = requests.get('http://wwwstaff.ari.uni-heidelberg.de/rschmidt/pycourse/ice_data/20060315.npy')"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"r2.headers"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"scrolled": true
},
"outputs": [],
"source": [
"r2.text[:200]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"However, this doesn't seem to be actual <i>text</i>. Instead, its a binary format. The binary data of the response can be accessed via"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"r2.content[:200]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Note the little ``b`` at the beginning indicating a binary byte-string."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now we can open a new (binary) file and download the data to the file."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"with open('20060315.npy', 'wb') as f:\n",
" f.write(r2.content)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Let's now load and plot the data:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import numpy as np\n",
"data = np.load('20060315.npy')"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import matplotlib.pyplot as plt\n",
"%matplotlib inline\n",
"\n",
"plt.figure(figsize=(12,12))\n",
"plt.imshow(data, origin='lower')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"APIs\n",
"----\n",
"\n",
"Imagine that you want to access some data online. \n",
"A number of websites now offer an \"Application programming interface\" (or API) which is basically a way of accessing data is a machine-readable way. \n",
"An example for weather data is http://openweathermap.org/API "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"Let's however take an example from theoretical Astrophysics, which is the\n",
"[Illustris simulation](http://www.illustris-project.org). *The routines we use below are presented and described on their web page.*\n",
"\n",
"Illustris is a cosmological simulation. It traces the positions and the formation of components such as dark matter, gas and stars across cosmic time from high-redshift to today. Extracting data at various cosmic times (=redshifts $z$), one can study, for instance, the gravitational collapse and merging history of clusters of galaxies and galaxies.\n",
"\n",
"We show here how to extract the dark matter particles inside haloes you can pick from the\n",
"[illustris explorer](http://www.illustris-project.org/explorer) tool.\n",
"\n",
"Once we have picked a halo ID, we can download the data. For the access, we need the access key.\n",
"This was generated for the use by this course (normally, every user has their own key.)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"headers={\"api-key\":\"2566d8dd2bcf9aefbb3d8b01080a877b\"} # 2566... = key for Uni HD python course"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import requests\n",
"r = requests.get('http://www.illustris-project.org/api/', headers=headers)\n",
"print (r.text[:400])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This is much shorter, but still not ideal for reading into Python in this form. The output details the available simulations and the number of snapshots in a format called **JSON (\"JavaScript Object Notation\")**. Python includes a library to easily read in this data:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"import json\n",
"data = json.loads(r.text)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"data"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In fact, such a dictionary can be obtained at every level in the data tree (try, e.g., the next one http://www.illustris-project.org/api/Illustris-1/ )"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now we pick a halo to study. Try finding halo 75 or 1030 in the Explorer for a first visualization.\n",
"\n",
"Specifications of data fields can be found [here](http://www.illustris-project.org/data/docs/specifications/)."
]
},
{
"cell_type": "code",
"execution_count": 30,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"id = 75 # choose your ID of the halo 75 or 1030 are defaults\n",
"redshift = 0.0 # choose a redshift, will be converted to snapshot automatically.\n",
"params = {'dm':'Coordinates'}\n",
"\n",
"url = \"http://www.illustris-project.org/api/Illustris-1/snapshots/z=\" + str(redshift) + \"/subhalos/\" + str(id)\n",
"\n",
"# read the parameters of the subhalo in the json format\n",
"subhalo = requests.get(url, headers=headers).json()\n",
"\n",
"# read the cutout of the subhalo into memory\n",
"cutout = requests.get(url+\"/cutout.hdf5\", headers=headers, params=params)\n",
"\n",
"# extract the filename from the header information and build the output name\n",
"filename= cutout.headers['content-disposition'].split(\"filename=\")[1]\n",
"outname=filename.split(\".hdf5\")[0]+\"_z=\"+str(redshift)+\".hdf5\"\n",
"\n",
"# save the cutout to disk, use 'outname'\n",
"with open(outname, 'wb') as f:\n",
" f.write(cutout.content)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The variable subhalo is a dictionary:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"for key in sorted(subhalo):\n",
" print (key,subhalo[key])"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"subhalo['len']"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The illustris data are in the [hdf5](https://support.hdfgroup.org/HDF5/) format. We need to write them to disk and\n",
"reload them. For this, we need to import the h5py package and read the file using *h5py.File*\n",
"\n",
"The result is again a dictionary. We are here interested in the PartType1 key (dark matter), in particular the Coordinates."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import matplotlib.pyplot as plt\n",
"%matplotlib inline\n",
"import numpy as np\n",
"print (outname)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import h5py\n",
"\n",
"with h5py.File(outname) as f:\n",
" # we subtract the centre of the halo (extracted from the dictionary information in subhalo)\n",
" # from the particle coordinates\n",
" dx = f['PartType1']['Coordinates'][:,0] - subhalo['pos_x']\n",
" dy = f['PartType1']['Coordinates'][:,1] - subhalo['pos_y']\n",
" dz = f['PartType1']['Coordinates'][:,2] - subhalo['pos_z']\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Exercise\n",
"\n",
"Consider subhalo 75 or 1030 (choose) at the three redshifts z=0 (snapshot 135), z=0.5 (snapshot 103) and z=1 (snapshot 85). Note the mass of individual particl is $6.3 \\times 10^6 M_\\odot$ ($M_\\odot$ = solar mass).\n",
"\n",
"1. Look at the distribution of the mass particles.\n",
" Determine the total dark matter mass inside R=10 kpc (ignore here the redshift and Hubble constant scaling of these units).\n",
"\n",
"2. Determine the \n",
" density profiles $\\rho = \\frac{d N}{dV}$ for the halo at these three redshifts.\n",
" $dN$ is the number of objects in the Volume $dV$.\n",
"\n",
" Can you find a redshift dependence?\n",
"\n",
" Remember: *plt.hist* can be used to build histograms.\n",
"\n",
" \n",
"3. (bonus, with time) Fit the functional form\n",
"\n",
" $\\rho(r)=\\frac{A}{\\frac{r}{r_s} (1+\\frac{r}{r_s})^n}$\n",
"\n",
" with n=3 or n=4 to the density profiles. Choose \"sensible\" fitting intervals.\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
" \n",
"\n",
"\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Note:** To simplify things, the following function was provided by the illustris project.\n",
"\n",
"It takes a url as above and returns either the header information, or downloads binary data and returns the file name.\n",
"\n",
"(from the illustris documentation [here](http://www.illustris-project.org/data/docs/api/) )"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"def get(url, params=None):\n",
" # make HTTP GET request to path\n",
" headers = {\"api-key\":\"2566d8dd2bcf9aefbb3d8b01080a877b\"}\n",
" r = requests.get(url, params=params, headers=headers)\n",
"\n",
" # raise exception if response code is not HTTP SUCCESS (200)\n",
" r.raise_for_status()\n",
"\n",
" if r.headers['content-type'] == 'application/json':\n",
" return r.json() # parse json responses automatically\n",
"\n",
" if 'content-disposition' in r.headers:\n",
" filename = r.headers['content-disposition'].split(\"filename=\")[1]\n",
" with open(filename, 'wb') as f:\n",
" f.write(r.content)\n",
" return filename # return the filename string\n",
"\n",
" return r"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
" "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Here is an **example** how the function **get(path)** can be used:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"id = 75\n",
"snapshot = 135\n",
"params = {'dm':'Coordinates'}\n",
"\n",
"url = \"http://www.illustris-project.org/api/Illustris-1/snapshots/\" + str(snapshot) + \"/subhalos/\" + str(id)\n",
"sub = get(url) # get json response of subhalo properties\n",
"saved_filename = get(url + \"/cutout.hdf5\",params) # get and save HDF5 cutout file\n",
"\n",
"with h5py.File(saved_filename) as f: # read coordinates\n",
" dx = f['PartType1']['Coordinates'][:,0] - sub['pos_x']\n",
" dy = f['PartType1']['Coordinates'][:,1] - sub['pos_y']\n",
" dz = f['PartType1']['Coordinates'][:,2] - sub['pos_z']"
]
}
],
"metadata": {
"anaconda-cloud": {},
"kernelspec": {
"display_name": "Python [Root]",
"language": "python",
"name": "Python [Root]"
},
"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.5.2"
}
},
"nbformat": 4,
"nbformat_minor": 0
}
@@ -0,0 +1,697 @@
{
"cells": [
{
"cell_type": "markdown",
"id": "ca47eaf9",
"metadata": {},
"source": [
"# Object-oriented programming"
]
},
{
"cell_type": "markdown",
"id": "67aefeba",
"metadata": {},
"source": [
"## Introduction"
]
},
{
"cell_type": "markdown",
"id": "fdfaf214",
"metadata": {},
"source": [
"Object-oriented programming is a way of programming that groups together related data and functions into **objects**, and makes it easier to design more complex programs. In traditional (procedural) programming, you can typically think of a program as an set of instructions that is read from top to bottom, with the exception of functions, which allow you to avoid repetitive code. In object-oriented programming, one instead thinks of a program mainly as setting up a number of 'types' of objects, and doing operations on them.\n",
"\n",
"Note that you have already been using objects! Every Python object is an object:"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "295461f7",
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"s = 'hello'\n",
"s.upper()"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "599d10fb",
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"l = [4,2,1]\n",
"l.sort()\n",
"l"
]
},
{
"cell_type": "markdown",
"id": "42448c92",
"metadata": {},
"source": [
"In these cases, ``upper`` and ``sort`` are both **methods**, and ``s`` and ``l`` are **instances** of the ``str`` and ``list`` **class** respectively (we will discuss these terms below)."
]
},
{
"cell_type": "markdown",
"id": "69060d63",
"metadata": {},
"source": [
"## Classes, instances, and methods"
]
},
{
"cell_type": "markdown",
"id": "4e87a869",
"metadata": {},
"source": [
"Classes are most easily explained by example, so let's dive right in and look at a **class**, which is used to define an **object**:"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "b2474f2e",
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"class Person(object):\n",
" \n",
" def __init__(self, name):\n",
" self.name = name\n",
" \n",
" def say_hello(self):\n",
" print(\"Hello, my name is \" + self.name)"
]
},
{
"cell_type": "markdown",
"id": "cf4db442",
"metadata": {},
"source": [
"and let's try and use it:"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "6c601095",
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"tom = Person('Tom')\n",
"tom.say_hello()"
]
},
{
"cell_type": "markdown",
"id": "9ee8302a",
"metadata": {},
"source": [
"There is a lot of new syntax here which you won't have likely seen before, but also some syntax which will look more familiar. First, let's have a look at the class definition. The class is defined using the following syntax:\n",
"\n",
" class Person(object):\n",
" ...\n",
"\n",
"This looks similar to the definition for a function, except that it doesn't directly contain code, but it then contains a series of functions:\n",
"\n",
" class Person(object):\n",
" \n",
" def __init__(self, ...):\n",
" ...\n",
"\n",
" def say_hello(self, ...):\n",
" ...\n",
"\n",
"So in effect, a class is a collection of functions. What is special about these functions? If you look at the full class definition above, you will see that the first argument to all the functions is ``self``, which is the object itself. Why is this useful?\n",
"\n",
"At this point, we need to clarify some more terminology: an **instance** of a class is a particular object represented by the **class** - that is, while ``Person`` is the class (i.e. the general definition of the idea of a 'person'), an instance is a *particular* person, e.g. Tom:"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "a7bbcf6f",
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"tom = Person('Tom')"
]
},
{
"cell_type": "markdown",
"id": "7e26bc6e",
"metadata": {},
"source": [
"Here ``tom`` is an instance of the ``Person`` class. Now let's look at the first defined **method**, called ``__init__``:\n",
"\n",
" def __init__(self, name):\n",
" self.name = name\n",
"\n",
"The term **method** is basically used for a function that is attached to a class. The ``__init__`` method is a method that is automatically called when creating an instance of the class (for those familiar with the terminology, it is equivalent to a constructor). What is basically happening here is that ``self`` is the actual instance that is being created, and the method then takes the name of the person and assigns it to the ``name`` **attribute** of the instance:"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "1ce2b8ea",
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"tom = Person('Tom')\n",
"print(tom.name)"
]
},
{
"cell_type": "markdown",
"id": "96c8c800",
"metadata": {},
"source": [
"As you can see, the ``tom`` instance has an attribute ``name`` that has been set to the name that was passed. Now let's look at the second method:\n",
"\n",
" def say_hello(self):\n",
" print \"Hello, my name is \" + self.name\n",
"\n",
"This looks more like a normal function, but takes the same ``self`` argument. It then prints out a string containing the value of the ``name`` attribute *of this instance*. Note that while all methods should take the ``self`` argument, this argument doesn't need to be passed because when calling a method, this is automatically done:"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "b85f0c77",
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"tom.say_hello()"
]
},
{
"cell_type": "markdown",
"id": "f08485e3",
"metadata": {},
"source": [
"is equivalent to:"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "2ab1d3dc",
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"Person.say_hello(tom)"
]
},
{
"cell_type": "markdown",
"id": "a35b6f3a",
"metadata": {},
"source": [
"In the last example, we passed the instance explicitly to the function, but the first notation is much cleaner and simpler. Now let's look at the following example:"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "d12001b3",
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"alice = Person(\"Alice\")\n",
"bob = Person(\"Bob\")\n",
"alice.say_hello()\n",
"bob.say_hello()"
]
},
{
"cell_type": "markdown",
"id": "d82daef2",
"metadata": {},
"source": [
"as you can see, when calling ``say_hello``, the result will depend to the actual object that the method is attached to.\n",
"\n",
"Since they are essentially functions, methods can of course take arguments, which can be any Python object(s). For example, we can make a new ``say_hello_to`` method that will take another ``Person`` instance and say hello to them:"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "b975cd88",
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"alice = Person(\"Alice\")\n",
"print (str(alice))\n",
"alice"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "1262e921",
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"class Person(object):\n",
" \n",
" def __init__(self, name):\n",
" self.name = name\n",
" \n",
" def __str__(self):\n",
" return \"The Person {}\".format(self.name)\n",
" \n",
" def __repr__(self):\n",
" return \"{}({})\".format(self.__class__.__name__,\n",
" repr(self.name))\n",
" \n",
" def say_hello(self):\n",
" print(\"Hello, my name is \" + self.name)\n",
" \n",
" def say_hello_to(self, other):\n",
" print(\"Hello \" + other.name + \", my name is \" + self.name)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "5342be00",
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"alice = Person(\"Alice\")\n",
"bob = Person(\"Bob\")\n",
"alice.say_hello_to(bob)"
]
},
{
"cell_type": "markdown",
"id": "a4665988",
"metadata": {},
"source": [
"As we will see below, you can actually pass any object to ``say_hello_to`` as long as it has a ``name`` attribute."
]
},
{
"cell_type": "markdown",
"id": "70c7b663",
"metadata": {},
"source": [
"Note:\n",
"* the 'str' definition serves to allow str to act on an instance of the Person class.\n",
"* the 'repr' definition serves to allows python to say what kind of object this is. If str does not exist, python will use repr."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "45d8beec",
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"bob # using the repr functionality"
]
},
{
"cell_type": "markdown",
"id": "aefceefd",
"metadata": {},
"source": [
"## Inheritance"
]
},
{
"cell_type": "markdown",
"id": "af704a1c",
"metadata": {},
"source": [
"One of the powerful features of object-oriented programming is **inheritance**, which means that it is possible to define classes based on other classes. For example, we can define:"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "12154cbe",
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"from scipy.integrate import simps\n",
"\n",
"class Scientist(Person):\n",
" \n",
" def integrate(self, x, y):\n",
" return simps(y, x=x)"
]
},
{
"cell_type": "markdown",
"id": "62793b8e",
"metadata": {},
"source": [
"This looks similar to before, but this time when defining the class, we've used ``Person`` instead of ``object``. This means that by default, ``Scientist`` will behave like a ``Person`` instance, but it then has some additional methods defined:"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "fb13b302",
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"alice = Scientist(\"Alice\")\n",
"alice.integrate([1,2,3], [4,5,6])"
]
},
{
"cell_type": "markdown",
"id": "d290d781",
"metadata": {},
"source": [
"The ``say_hello_to`` method takes any object that has a ``name`` attribute, so it can say hello to another person:"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "996cccfc",
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"alice"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "f194c275",
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"bob = Person(\"Bob\")\n",
"alice.say_hello_to(bob)"
]
},
{
"cell_type": "markdown",
"id": "c2d51b3f",
"metadata": {},
"source": [
"or scientist:"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "f5d44022",
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"eve = Scientist(\"Eve\")\n",
"alice.say_hello_to(eve)"
]
},
{
"cell_type": "markdown",
"id": "9f7eeacd",
"metadata": {},
"source": [
"## Attributes"
]
},
{
"cell_type": "markdown",
"id": "a2e1e83d",
"metadata": {},
"source": [
"As mentioned above, attributes are variables attached to the object. It is worth mentioning that attributes are *not* static, so they can be changed from outside the class:"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "9190a139",
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"p = Person('Tom')\n",
"p.say_hello()"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "60683c8d",
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"p.name = 'Alice'\n",
"p.say_hello()"
]
},
{
"cell_type": "markdown",
"id": "7c595a94",
"metadata": {},
"source": [
"and it is also possible to create new attributes from the outside:"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "8933ab29",
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"p.age = 97\n",
"p.name\n",
"p.age"
]
},
{
"cell_type": "markdown",
"id": "ebd960bf",
"metadata": {},
"source": [
"This last practice (creating attributes in an object) is typically a bad idea, because you're essentially violating the object's “namespace”, the names the object manages, and it's not hard to break things in this way.\n",
"\n",
"Then again, python does not keep you from doing such things because that would keep you from doing smart things."
]
},
{
"cell_type": "markdown",
"id": "21c8e1dc",
"metadata": {},
"source": [
"A good way to think about objects is to say:\n",
"\n",
"* attributes = state\n",
"* methods = behaviour"
]
},
{
"cell_type": "markdown",
"id": "ea3a811a",
"metadata": {},
"source": [
"## Why use objects?"
]
},
{
"cell_type": "markdown",
"id": "6a7a9252",
"metadata": {},
"source": [
"So far, the programs you have needed to write have not been very complex, but as you write more and more complex analysis, classes may come in useful in some situations. For example, if you are doing particle physics, you might want to use a class to represent a ``Particle``, which then has common operations and calculations you might want to do with a particle. If you are doing Astronomy, you could use a ``Star`` or ``Galaxy`` class that would be used to represent these objects. You can even use objects without defining actual methods, but just as a convenience to contain several variables - if you need to always handle cartesian point in your code, you could define:"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "a41a42da",
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"class Point(object):\n",
" def __init__(self, x, y, z):\n",
" self.x = x\n",
" self.y = y\n",
" self.z = z"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "373365ed",
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"pt = Point(1, 2, 3)\n",
"pt.y"
]
},
{
"cell_type": "markdown",
"id": "513657e7",
"metadata": {},
"source": [
"After which if you want to pass a point to a function, you can pass it in a single variable instead of three:"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "d34cb465",
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"def find_separation(p1, p2):\n",
" return np.sqrt((p1.x - p2.x)**2 + (p1.y - p2.y)**2 + (p1.z - p2.z)**2)"
]
},
{
"cell_type": "markdown",
"id": "c5981ca6",
"metadata": {},
"source": [
"as opposed to:"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "bb46e764",
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"def find_separation(x1, y1, z1, x2, y2, z2):\n",
" return np.sqrt((x1 - x2)**2 + (y1 - y2)**2 + (z1 - z2)**2)"
]
},
{
"cell_type": "markdown",
"id": "387b256a",
"metadata": {},
"source": [
"This might not look like a big difference, but now imagine that you also wanted to pass 3-d velocities, then you would need to call the function with 12 arguments!\n",
"\n",
"This is not to say that you should *always* use objects, but if you start to think of your program instead of what objects and basic operations are being represented, you may be able to write it more simply than if you were using only functions and procedural code. You may also be able to re-use classes for different projects if they are general enough!"
]
},
{
"cell_type": "markdown",
"id": "5338239b",
"metadata": {},
"source": [
"## Exercise"
]
},
{
"cell_type": "markdown",
"id": "c321cd01",
"metadata": {},
"source": [
"1. Write a ``Particle`` class that can be used to represent a particle with a mass, a 3-d position, and a 3-d velocity.\n",
"\n",
"2. Write a method that can be used to compute the kinetic energy of the particle\n",
"\n",
"3. Write a method that takes another particle as an argument and finds the distance between the two particles\n",
"\n",
"4. Write a method that given a time interval ``dt`` will update the position of the particle to the new position based on the current position and velocity.\n",
"\n",
"5. Write a ``ChargedParticle`` class that inherits from the ``Particle`` class, but also has an attribute for the charge of the particle.\n",
"\n",
"6. Write examples of using these classes to test that the methods are working correctly."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "339d785c",
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"# your solution here"
]
}
],
"metadata": {
"anaconda-cloud": {},
"kernelspec": {
"display_name": "Python [Root]",
"language": "python",
"name": "Python [Root]"
},
"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.5.2"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
@@ -0,0 +1,134 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"List comprehension\n",
"------------------\n",
"\n",
"Python offers a compact method called \"list comprehension\" to create lists from lists.\n",
"Consider the following case of a list that is processed to create another list:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"iterable=range(5)\n",
"my_list=[]\n",
"\n",
"for x in iterable:\n",
" if x<=3:\n",
" my_list.append(x**2)\n",
"\n",
"print (my_list)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Using list comprehension this can be done using the following line:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"my_list=[x**2 for x in iterable if x<=3]\n",
"\n",
"print (my_list)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can see that a loop such as\n",
"\n",
" for item in iterable:\n",
" if conditional:\n",
" expression\n",
"\n",
"is equivalent to\n",
"\n",
" [expression for item in iterable if conditional]\n",
" \n",
" \n",
"You are always creating a list with list comprehension. If you don't necessarily want a list, a loop can be the simpler option.\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Exercise 1:\n",
"-----------\n",
"\n",
"Use list comprehension to translate the sentence list\n",
"\n",
" diogenes=['Cede','paulum','e','sole']\n",
"\n",
"using the dictionary\n",
"\n",
" dic={'Cede':'Go','paulum':'a little','e':'out of','sole':'the sun'}\n",
" \n",
"into an answer sentence list. "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# your solution here"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Exercise 2:\n",
"-----------\n",
"\n",
"Use list comprehension to determine a list with all numbers between 1 and 1000 for which the digit sum is equal to 7."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# your solution here"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"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.5"
}
},
"nbformat": 4,
"nbformat_minor": 1
}
@@ -0,0 +1,70 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Practice Problem - Cryptography"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Cryptography is the study of how to make messages secret or how to read secret messages. A very simple encryption technique is called the *Caesar cipher* -- more information on it can be found [here](http://en.wikipedia.org/wiki/Caesar_cipher). The basic idea is that each letter is replaced by a letter that is a certain number of letters away, so for example if the shift was 2, then A would become C, B would become D, etc. (and Z will become B).\n",
"\n",
"Write a piece of code that given a string and a shift, will produce the encrypted string for that shift. Note that the same routine can be used to decrypt a message, by passing it a negative shift. \n",
"\n",
"The rules are: you should only accept and return lowercase letters, and spaces should not be changed.\n",
"\n",
"Then, decrypt the following message, which was encrypted with a shift of 13:\n",
" \n",
" pbatenghyngvbaf lbh unir fhpprrqrq va qrpelcgvat gur fgevat \n",
" \n",
"Now if you are up for a challenge, try and decrypt this **and** find the shift:\n",
" \n",
" wxkxmh ngynlcb cqn byjwrbq rwzdrbrcrxw\n",
" \n",
"**Note**: there are several ways you can convert between letters and numbers. One is to use the built-in functions ``chr`` and ``ord`` (and remember you can find out more about a function by using ``?`` in IPython). Another is to set up the alphabet in a string and use item access (``[3]``) to convert from numbers to letters, and the ``index`` method to convert from letters to numbers."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Solution"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"\n",
"# your solution here\n"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"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.5"
}
},
"nbformat": 4,
"nbformat_minor": 1
}
@@ -0,0 +1,146 @@
{
"cells": [
{
"cell_type": "markdown",
"id": "3635637b",
"metadata": {},
"source": [
"# Practice Problem - Monte-Carlo Error Propagation"
]
},
{
"cell_type": "markdown",
"id": "1e41e304",
"metadata": {},
"source": [
"## Part 1"
]
},
{
"cell_type": "markdown",
"id": "895e84c4",
"metadata": {},
"source": [
"You have likely encountered the concept of propagation of uncertainty before (see [the usual rules here](http://en.wikipedia.org/wiki/Propagation_of_uncertainty#Example_formulas)). The idea is that given measurements with uncertainties, we can find the uncertainty on the final result of an equation.\n",
"\n",
"For example, let us consider the following equation:\n",
"\n",
"$$F = \\frac{G~M_1~M_2}{r^2}$$\n",
"\n",
"which gives the gravitational force between two masses $M_1$ and $M_2$ separated by a distance $r$.\n",
"\n",
"Let us now imagine that we have two masses:\n",
"\n",
"$$M_1=40\\times10^4\\pm0.05\\times10^4\\rm{kg}$$\n",
"\n",
"and\n",
"\n",
"$$M_2=30\\times10^4\\pm0.1\\times10^4\\rm{kg}$$\n",
"\n",
"separated by a distance:\n",
"\n",
"$$r=3.2\\pm0.01~\\rm{m}$$\n",
"\n",
"where the uncertaintes are the standard deviations of Gaussian distributions which could be e.g. measurement errors.\n",
"\n",
"We also know:\n",
"\n",
"$$G = 6.67384\\times10^{-11}~\\rm{m}^3~\\rm{kg}^{-1}~\\rm{s}^{-2}$$\n",
"\n",
"(exact value, no uncertainty)\n",
"\n",
"Use the [standard error propagation rules](http://en.wikipedia.org/wiki/Propagation_of_uncertainty#Example_formulas) to determine the resulting force and uncertainty in your script (you can just derive the equation by hand and implement it in a single line in your code).\n",
"\n",
"Now, we can try using a **Monte-Carlo** technique instead. The idea behind Monte-Carlo techniques is to generate many possible solutions using random numbers and using these to look at the overall results. In the above case, you can propagate uncertainties with a Monte-Carlo method by doing the following:\n",
"\n",
"* randomly sample values of $M_1$, $M_2$, and $r$, 1000000 times, using the means and standard deviations given above\n",
"\n",
"* compute the gravitational force for each set of values\n",
"\n",
"You should do this with Numpy arrays, and **without any loops**. You should then get an array of 1000000 different values for the forces.\n",
"\n",
"Make a plot of the normalized histogram of these values of the force, and then overplot a Gaussian function with the mean and standard deviation derived with the standard error propagation rules. Make sure that you pick the range of x values in the plot wisely, so that the two distributions can be seen. Make sure there are also a sensible number of bins in the histogram so that you can compare the shape of the histogram and the Gaussian function. The two distributions should agree pretty well."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "6ed585ea",
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"\n",
"# Your solution here\n"
]
},
{
"cell_type": "markdown",
"id": "0334e752",
"metadata": {},
"source": [
"## Part 2"
]
},
{
"cell_type": "markdown",
"id": "117bedb7",
"metadata": {},
"source": [
"Now repeat the experiment above with the following values:\n",
"\n",
"$$M_1=40\\times10^4\\pm2\\times10^4\\rm{kg}$$\n",
"$$M_2=30\\times10^4\\pm10\\times10^4\\rm{kg}$$\n",
"$$r=3.2\\pm1.0~\\rm{m}$$\n",
"\n",
"and as above, produce a plot.\n",
"\n",
"In this case, which method do you think is more accurate? Why? What do you think are the advantages of using a Monte-Carlo technique?"
]
},
{
"cell_type": "markdown",
"id": "7eaa28f9",
"metadata": {},
"source": [
"## Solution"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "eb657c11",
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"\n",
"# your solution here\n"
]
}
],
"metadata": {
"anaconda-cloud": {},
"kernelspec": {
"display_name": "Python [Root]",
"language": "python",
"name": "Python [Root]"
},
"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.5.2"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
@@ -0,0 +1,161 @@
{
"cells": [
{
"cell_type": "markdown",
"id": "690fcfd6",
"metadata": {},
"source": [
"# Practice Problem - Radioactive Decay"
]
},
{
"cell_type": "markdown",
"id": "6c2ea68a",
"metadata": {},
"source": [
"Radioactive decay (or radioactivity) is the process by which a nucleus of an unstable atom loses energy by emitting particles such as alpha particles (Helium nucleii) or beta particles (electrons). You can read up more about radioactive decay [here](https://en.wikipedia.org/wiki/Radioactive_decay).\n",
"\n",
"In this exercise, we look at a (fake) dataset showing the rate of detection of alpha particles close to a radioactive sample, which we will call element X. The dataset used is the [data/new_decay_data.txt](data/new_decay_data.txt) file. The rate of detection of alpha particles is measured at 100 different times (given by the first column, in days since the start of the experiment), and for each of these times, both the rate of detection and the uncertainty in the rate of detection are given (in the second and third columns, in detections per second).\n",
"\n",
"1 - Plot the rate of detection versus time, including error bars (see the lecture notes for an example of how to do this). Include labels on the x and y axis.\n",
"\n",
"2 - The rate of decay of a radioactive element is given by:\n",
"\n",
"$$R(t) = R_0~e^{-t/\\tau}$$\n",
"\n",
"where $R_0$ is the rate of decay at time $t=0$, and $\\tau$ is the *mean lifetime* of the element. Define this function (which has two free parameters in addition to the time) as a Python function in your script, and fit it to the data using ``curve_fit``, and overplot the resulting best-fit function over the data using a line. Is the fit good? If not, what do you think is causing the fit to be bad? Print out the best-fit parameters and uncertainties as shown in the lecture notes.\n",
"\n",
"3 - While one would ideally be able to measure the rate of decay in a completely isolated environment, some of the alpha detections are in fact from background radioactive decay, so we need to take this into account by considering a decay rate function that includes a constant background level term:\n",
"\n",
"$$R(t) = R_0~e^{-t/\\tau} + R_{\\rm bkg}$$\n",
"\n",
"Define this function in your script and fit it to the data using ``curve_fit``, overplotting the best-fit function over the data in a new plot. Also draw a horizontal line to show the constant background level. Does this fit look better? Print out the best-fit parameters and uncertainties.\n",
"\n",
"4 - One way to quantify the *goodness* of a fit is to consider the reduced $\\chi^2$ value of the fit, defined as:\n",
"\n",
"$$\\chi_{\\rm red}^2 = \\frac{1}{N - p}\\sum_{i=1}^{N}~\\left(\\frac{y_i - m_i}{\\sigma_i}\\right)^2$$\n",
"\n",
"where $N$ is the number of datapoints, $p$ is the number of parameters for the model, $y_i$ are the data values, $m_i$ are the model values at the same positions, and $\\sigma_i$ are the uncertainties on the data $y_i$.\n",
"\n",
"Conventional wisdom has it, that a fit is usually considered to be good if $\\chi_{\\rm red}^2 \\approx 1$, and this is a decent guide. \n",
"\n",
"Compute $\\chi_{\\rm red}^2$ for both models above, and comment on the values. Do they agree with what you would have concluded from looking at the plots?"
]
},
{
"cell_type": "markdown",
"id": "94b031df",
"metadata": {},
"source": [
"## Your solution here"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "ef386c00",
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import numpy as np\n",
"import matplotlib.pyplot as plt\n",
"%matplotlib inline\n",
"# your solution here\n"
]
},
{
"cell_type": "markdown",
"id": "e679e9e0",
"metadata": {},
"source": [
"**A note on the $\\chi^2$ distribution**: One can and should look at this more precisely: given the $\\chi^2$ value\n",
"\n",
"$$\\chi^2 = \\sum_{i=1}^{N}~\\left(\\frac{y_i - m_i}{\\sigma_i}\\right)^2$$\n",
"\n",
"and the number of degrees of freedom df (here df=N-p), one can calculate the probability that a chisquare $\\chi'^2$ greater than the one found could have been obtained:"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "46fc591f",
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"# example using the cumulative chisquare distribution implemented in scipy.stats\n",
"from scipy.stats import chi2\n",
"\n",
"chisquare=20.0 # enter chisquare value\n",
"df=10 # enter dof\n",
"print (1-chi2.cdf(chisquare,df=df))"
]
},
{
"cell_type": "markdown",
"id": "c786f73a",
"metadata": {},
"source": [
"You can indeed look at the chisquare probability function with matplotlib, for which the expectation value\n",
"is $<\\chi^2> =$ df."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "16fd5172",
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"import matplotlib.pyplot as plt\n",
"%matplotlib inline\n",
"import numpy as np"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "9c0516ad",
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"df=20\n",
"x=np.arange(0,2*df,0.1)\n",
"\n",
"plt.plot(x,chi2.pdf(x,df=df))\n",
"plt.xlabel('$\\chi^2$')\n",
"plt.ylabel('chi2.pdf')\n",
"plt.title('df='+str(df))"
]
}
],
"metadata": {
"anaconda-cloud": {},
"kernelspec": {
"display_name": "Python [Root]",
"language": "python",
"name": "Python [Root]"
},
"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.5.2"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
@@ -0,0 +1,67 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Practice Problem - Temperatures"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Use the [data/munich_temperatures_average.txt](data/munich_temperatures_average.txt) data file, which gives the temperature in Munich every day for several years. Read in the data, and print out the minimum, average maximum temperature for each year, e.g:\n",
"\n",
" 1995: -3C 10C 35C\n",
" 1996: ...\n",
"\n",
"**Note:** A convenient way to do this, is using dictionaries.\n",
"\n",
"When you are done with this, print out the same values, but for each month (averaged over years), e.g.:\n",
"\n",
" January: -15C 0C 3C\n",
" February: ..."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Solution"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"\n",
"# your solution here\n"
]
}
],
"metadata": {
"anaconda-cloud": {},
"kernelspec": {
"display_name": "Python 3",
"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.5"
}
},
"nbformat": 4,
"nbformat_minor": 1
}
+236
View File
@@ -0,0 +1,236 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Problem Set 1 - DNA"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Total points:** 30\n",
"\n",
"**Due:** Thursday October 3rd, 2024, 7pm CEST\n",
"\n",
"**Format:** jupyter notebook or python program\n",
"\n",
"*The number of points in this problem sheet is *not* directly proportional to the difficulty. In fact, Part 3 is more difficult than Part 1 and 2, but is worth fewer points in terms of the amount of work/code, and are there for people who enjoy challenges. So you can choose to not complete Part 3, and you should still be able to get more than 60% of points from the previous questions if you answer them correctly.*"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Background"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This problem set is about DNA data and methods typically applied to this kind of data. As a reminder, [DNA](http://en.wikipedia.org/wiki/DNA) is a molecule that encodes genetic instructions for living organisms. DNA is typically found as a double-stranded helix, in which each strand corresponds to a sequence of *nucleotides*. Each nucleotide consists of a nucleobase (guanine, adenine, thymine, or cytosine) attached to sugars, which are in turn separated from each other by phosphate groups:\n",
"\n",
"![DNA](http://upload.wikimedia.org/wikipedia/commons/thumb/4/4c/DNA_Structure%2BKey%2BLabelled.pn_NoBB.png/492px-DNA_Structure%2BKey%2BLabelled.pn_NoBB.png)\n",
"\n",
"(image from Wikipedia)\n",
"\n",
"The nucleobases are commonly referred to with the letters G (guanine), A (adenine), T (thymine), and C (cytosine). The nucleobases form pairs between the two strands: G pairs with C, and T pairs with A.\n",
"\n",
"DNA is therefore most commonly represented as a sequence of nucleobases, such as ``GATTACACCTCATTATAAA``.\n",
"\n",
"For more information about DNA, see the wikipedia page in [German](http://de.wikipedia.org/wiki/Desoxyribonukleinsäure) or [English](http://en.wikipedia.org/wiki/DNA).\n",
"\n",
"In this problem set, we will be working with fake genetic data, since real-life data often has added complications, but the functions and techniques uses here are the same or very similar to techniques used on real data."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Part 1 (10 points)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Question 1 (6 points)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The **reverse complement** of DNA is found by reversing the DNA sequence, then replacing each base by its complement (A is replaced by T, T is replaced by A, G is replaced by C, and C is replaced by G). For example, the reverse complement of ``ATGCGGC`` is ``GCCGCAT``\n",
"\n",
"Write a Python function ``reverse_complement`` that takes a DNA sequence as a string, and returns the reverse complement. Test your function by ensuring that ``reverse_complement('ATGCGGC')`` is ``'GCCGCAT'``, then find the reverse complement of the following sequence:\n",
"\n",
" ATGCGCGGATCGTACCTAATCGATGGCATTAGCCGAGCCCGATTACGC\n",
" \n",
"Print the result out using ``print``.\n",
"\n",
"Note that this function is **NOT** needed for the remaining questions below."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Question 2 (4 points)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"[Ribonucleic acid (RNA)](http://en.wikipedia.org/wiki/RNA) is a family of large biological molecules that is *transcribed* from DNA by the [RNA Polymerase](http://en.wikipedia.org/wiki/RNA_polymerase) enzyme. It consists of a single strand of nucleotides that are identical to the ones found in DNA, with the exception of uracil (U), which replaces thymine (T).\n",
"\n",
"[Messenger RNA](http://en.wikipedia.org/wiki/Messenger_RNA) molecules (or mRNA) are a subset of RNA molecules that are used to pass information from DNA to [ribosomes](http://en.wikipedia.org/wiki/Ribosome), which then translates the mRNA to protein sequences.\n",
"\n",
"Write a Python function ``dna_to_mrna`` that takes a DNA sequence and returns the corresponding mRNA sequence. For example, the DNA sequence ``ATCGCGAT`` should produce the mRNA sequence ``AUCGCGAU`` (note that you do **not** need to find the reverse complement of the DNA here)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Part 2 (15 points)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Question 3 (8 points)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"When the mRNA is translated to a protein sequence, each set of three nucleotides, called a **codon**, is translated into a single amino acid. For example, the codon ``UUC`` translates to the amino acid *Phenylalanine*. Each amino acid can be represented by a single letter - for example Phenylalanine is represented by the letter ``F``. A protein, which is formed from a sequence of amino acids, can therefore be written as a sequence of letters in the same way as DNA or mRNA, but using more of the letters of the alphabet since there are more than four amino acids.\n",
"\n",
"The [data/problem_1_codons.txt](data/problem_1_codons.txt) ([this file on the jupyter server](data/PS01-data/problem_1_codons.txt)) file contains two columns. The first column gives a list of codons, and the second column gives the corresponding amino acid (represented by a single letter). Certain codons do not correspond to an amino acid, but instead indicate that the amino acid sequence is finished. These are indicated by ``Stop``.\n",
"\n",
"Write a function ``mrna_to_protein`` that takes an mRNA sequence (as a string) and returns the sequence of amino acids (as a string), stopping the first time a ``Stop`` codon is encountered. Make sure that the file is only read once when running the script (and not every time you want to translate a codon). You will likely need to use a Python dictionary to help.\n",
"\n",
"Finally, write a function ``dna_to_protein`` that takes a DNA sequence (as a string) and returns the sequence of amino acids (as a string), making use of the functions that you wrote previously.\n",
"\n",
"Print out the amino acid sequence for the following DNA sequence:\n",
"\n",
" AATCTCTACGGAAGTAGGTCAGTACTGATCGATCAGTCGATCGGGCGGCGATTTCGATCTGATTGTACGGCGGGCTAG\n",
" "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Question 4 (7 points)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In the previous questions, we have been specifying the DNA sequence by hand, but DNA sequences are usually long and are stored in files. A common file format is the [FASTA format](http://en.wikipedia.org/wiki/FASTA_format) which looks similar to this:\n",
"\n",
" >label1\n",
" ACTGTATCGATGCTAGCTACGTAGCTAGCTAGCTAGCTGACGTA\n",
" ACGATGTGCGAGGGTCATGGGACGCGAGCGAGTCTAGCACGATC\n",
" >label2\n",
" ACTGGGCTTGACTACGGCGGTATCTGACGGGCGAGCTGTACGAG\n",
" ACGGACTAGGGCGCGGCGGGGCGGATTTTCGAGTCGAGCGTTAT\n",
" \n",
"The first line starts with a ``>`` which is immediately followed by a label (which might be the name of the gene for example). The sequence then starts on the second line, and may continue on several lines. It is common to limit the length of each line to 80, but this may vary from file to file. The sequence stops once either the file ends, or a line starts with ``>``, which indicates that a new sequence is being given. There may be any number of sequences in a file.\n",
"\n",
"Write a function ``read_fasta``, that takes the name of a file (as a string) and returns a Python dictionary containing all the sequences from the file, with the keys in the dictionary corresponding to the label. If a sequence is given over several lines, you should remove any line returns and spaces. You should then be able to access the DNA for ``label1`` with ``d['label1']`` for example (if ``d`` is the name of the dictionary).\n",
"\n",
"Use this function and the functions you have written above to read in the [data/problem_1_question_4_new.fasta](data/problem_1_question_4_new.fasta) [(this file on the jupyter server)](data/PS01-data/problem_1_question_4_new.fasta) file and print out, for each sequence, the label, followed by the **amino acid** sequence (not the DNA sequence!)."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Part 3 (5 points)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Question 5 (3 points)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Given several sequences with the same length, but which may include point mutations (i.e. individual nucleotides are changed), we want to try and find the most likely original sequence. For example, if we have the following sequences:\n",
"\n",
" sequence 1: A C T C T\n",
" sequence 2: A C T C G\n",
" sequence 3: G C C C T\n",
" sequence 2: A C T C T\n",
" sequence 4: A T G C T\n",
" \n",
"we can go through each position and find the most common nucleotide. To do this, we can first construct a matrix that looks like:\n",
" \n",
" A: 4 0 0 0 0\n",
" C: 0 4 1 5 0\n",
" G: 1 0 1 0 1\n",
" T: 0 1 3 0 4\n",
" \n",
"which indicates how many nucleotides of each type are found at each position, and from this we can see that the most common first base is A, the most common second base is C, and so on. The most common sequence is then ``ACTCT``. This is the [**consensus sequence**](http://en.wikipedia.org/wiki/Consensus_sequence).\n",
"\n",
"Write a function ``consensus_sequence`` that takes a dictionary of sequences (such as the one returned by ``read_fasta``), and then returns the consensus sequence. Read the [data/problem_1_question_5.fasta](data/problem_1_question_5.fasta) [(this file on the jupyter server)](data/PS01-data/problem_1_question_5.fasta) file using the function you wrote previsouly, and print out the corresponding consensus sequence. All the sequences in this file are the same length.\n",
"\n",
"Note that the selection is based on the **nucleotides**!"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Question 6 (2 points)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In some cases, it is useful to be able to identify the longest common sub-sequence between two sequences. For example, in the sequences ``ACTGCT`` and ``TGCCCT``, the longest common sub-sequence is ``TGC`` (AC**TGC**T and **TGC**CCT). Note that these do not have to be at the same positon in each sequence.\n",
"\n",
"Write a function, ``longest_common_sequence``, that takes a dictionary of sequences (such as the one returned by ``read_fasta``) and returns the longest common sub-sequence found in all the sequences.\n",
"\n",
"Read the [data/problem_1_question_6.fasta](data/problem_1_question_6.fasta) [(this file on the jupyter server)](data/PS01-data/problem_1_question_6.fasta) file, and print out the longest common sequence between all the sequences."
]
}
],
"metadata": {
"anaconda-cloud": {},
"kernelspec": {
"display_name": "Python 3",
"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.10"
}
},
"nbformat": 4,
"nbformat_minor": 1
}
+181
View File
@@ -0,0 +1,181 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Problem Set 2 - Arctic ice maps"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Total points:** 30\n",
"\n",
"**Due:** Thursday October 10th, 2024, 7pm CEST\n",
"\n",
"**Format:** jupyter notebook or python program"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The purpose of this problem set is to become familiar with working with image data, plotting it, and combining it in various ways for analysis.\n",
"\n",
"The data used in this problem set were collected by the AMSR-E and AMSR2 instruments on the [Aqua](http://en.wikipedia.org/wiki/Aqua_%28satellite%29) satellite and [GCOM-W1 satellites](https://en.wikipedia.org/wiki/Global_Change_Observation_Mission). The data consists of maps of the concentration of ice in the Arctic collected between 2002 and 2023(=now). The concentration is defined the percentage of a given area covered with sea ice. The data were downloaded and extracted from [here](http://seaice.uni-bremen.de/data/) and converted into a format that can be more easily used.\n",
"\n",
"The data you should use are situated in the data/ice_data_2022/ directory on the jupyter server.\n",
"\n",
"If you are using your own laptop, you can dowload the data [here](http://wwwstaff.ari.uni-heidelberg.de/rschmidt/pycourse/ice_data.zip). The archive size is 73MB.\n",
"\n",
"The data is in 'Numpy' format, which means that you can read it as a Numpy array using:\n",
"\n",
" >>> import numpy as np\n",
" >>> data = np.load('data/ice_data_2022/20080415.npy')\n",
"\n",
"which will give you a 2-d array. Just for information, this was created with:\n",
"\n",
" >>> np.save('data/ice_data_2022/20080415.npy', data)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Part 1 - examining a single map (6 points)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Start off by reading in one of the maps as shown above, and plot it with Matplotlib**. Note that to get the correct orientation, you will need to call the ``imshow`` command with the ``origin='lower'`` option, which ensures that the (0,0) pixels is on the bottom left, not the top left. You can try and use different colormaps if you like (set by the ``cmap`` option) - see [here](https://matplotlib.org/stable/tutorials/colors/colormaps.html) for information on the available colormaps. You can specify a colormap to use with e.g. ``cmap=plt.cm.jet`` (i.e. ``cmap=plt.cm.`` followed by the name of the colormap). Note that you can make figures larger by specifying before the plot command for example\n",
"\n",
" >>> plt.figure(figsize=(8,8))\n",
"\n",
"where the size is given in inches. Try and find a way to plot a colorbar on the side, to show what color corresponds to what value. Examples can be found in the [Matplotlib Gallery](https://matplotlib.org/stable/gallery/). You may also want to try to remove the tick labels (``100``, ``200``, etc.) since they are not useful."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Part 2 - reading in multiple maps (10 points)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**2.1** We want to make a plot of the ice concentration over time. Reading in a single map is easy, but since we have 455 maps, we do not want to read them all in individually by hand. **Write a loop over all the available files, and inside the loop, read in the data to a variable (e.g. ``data``), and also extract the year, month, and day as integer values (e.g. ``year``, ``month``, and ``day``)**. Then, also inside the loop, **compute a variable ``time``** which is essentially the fractional time in years (so 1st July 2012 is 2012.5). You can assume for simplicity that each month has 30 days - this will not affect the results later. Finally, also **compute for each file the total number of pixels that have a value above 50%**. After the loop, **make a plot of the number of pixels with a concentration above 50% against time**.\n",
"\n",
"**Describe what you see in the plot**.\n",
"\n",
"\n",
"In some version of jupyter, the ticks are in a strange format. In this case you can change this with the following code:\n",
"\n",
" >>> from matplotlib.ticker import ScalarFormatter\n",
" >>> plt.gca().xaxis.set_major_formatter(ScalarFormatter(useOffset=False))\n",
" \n",
" \n",
"In all other cases, you can ignore these lines.\n",
"\n",
"\n",
"**2.2** To deal with a little more than just the number of pixels, so we will compute the area where the ice concentration is above a given threshold. However, we first need to know the effective area of the pixels in the image, as each pixel has a different area. The areas (in km^2) are contained inside the file named ``ice_data_2019_area.npy`` (which remains the correct file despite the name). This file was downladed [here](https://seaice.uni-bremen.de/data/grid_coordinates/GridCellArea/) (PolStereo_GridCellArea_n12.5km_Arctic.nc) and then converted.\n",
"\n",
"**Read in the areas and make a plot (with colorbar) to see how the pixel area is changing over the image.**\n",
"\n",
"Now, loop over the files again as before, but this time, for each file, **compute the total area where the concentration of ice is 15% or above. Make a new plot showing the area of >15% ice concentration against time.**\n",
"\n",
"**Describe what you see - how does the minimum change over time?**"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Part 3 - visualizing changes over time (10 points)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Find the date at which the area of the region where the ice concentration is above 15% is the smallest**. What is the value of the minimum area?\n",
"\n",
"Next, **read in the map for this minimum, and the map for the same day and month but from 2006**. **Make a side-by-side plot showing both data sets**.\n",
"\n",
"Note: You can group together plots using the *add_subplot()* functionality of the matplotlib figure object, which\n",
"creates *Axes* objects to plot in:\n",
"\n",
" >>> fig = plt.figure(figsize=(10,5))\n",
" >>> ax1 = fig.add_subplot(1,2,1)\n",
" >>> ax2 = fig.add_subplot(1,2,2)\n",
" >>> im1 = ax1.imshow( ... )\n",
" >>> im2 = ax2.imshow( ... )\n",
" \n",
"**Compute the difference between the two maps** so that a loss in ice over time will correspond to a negative value, and a gain in ice will correspond to a positive value. **Make a plot** of the difference, and use the ``RdBu`` colormap to highlight the changes (include a colorbar).\n",
"\n",
"Note 2: Sometimes ones needs to add a colour bar to a subplot-figure such as above.\n",
"This can be done by creating an additional *Axes* object to the figure with the apropriate size and location:\n",
"\n",
" >>> cax = fig.add_axes([0.95, 0.15, 0.025, 0.7])\n",
" >>> plt.colorbar(im1,cax=cax)\n",
" \n",
"(then the colour mapping should be chosen identical for the two images)."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Part 4 - yearly averages (4 points)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Compute average ice concentration maps for 2006 and 2012, and plot them side by side.**"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Epilogue"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The data that we have here cover ~21 years, so we cannot easily extract information about long term trends. However, it is worth noting that the minimum ice coverage you find here is a record minimum - never before (in recorded history) had the size of the ice shelf been so small. This is part of a long term trend due to global warming. Most scientists believe that by ~2050, the Arctic will be completely ice-free for at least part of the summer."
]
}
],
"metadata": {
"anaconda-cloud": {},
"kernelspec": {
"display_name": "Python 3",
"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.10"
}
},
"nbformat": 4,
"nbformat_minor": 4
}
File diff suppressed because one or more lines are too long
+130
View File
@@ -0,0 +1,130 @@
<head>
<!--#set var="rb_section" value="home" -->
<!--#include virtual="../../header_include.shtml" -->
<!--#set var="title_de" value="Webseite von Cornelis fspanier" -->
<!--#set var="title_en" value="Cornelis fspanier's Homepage" -->
<!--#set var="autolocation" value="on" -->
<!--#set var="location_de" value="fspanier" -->
<!--#set var="location_en" value="fspanier" -->
</head>
<!--#if expr="$language = de" -->
<div id="ueberschrift">
<h1>Python for scientists</h1>
</div>
<p>
<h3>Sommersemester 2024</h3>
<h4>F. Spanier</h4>
</p>
<hr>
<p>
<table>
<tr>
<td>Ort</td>
<td>INF 226, PC-Pool</td>
</tr>
<tr>
<td>Zeit</td>
<td> 23.-27.09., 09:00 - 13:00</td>
</tr>
</table>
</p>
<p>
<ul>
<li><a href="00. About the course.ipynb">About the course</a></li>
<li><a href="01. What is Python.ipynb">What is Python</a></li>
<li><a href="02. Using the IPython notebook.ipynb">Using the IPython notebook</a></li>
<li><a href="03. Numbers, String, and Lists.ipynb">Numbers, String, and Lists</a></li>
<li><a href="04. Booleans, Tuples, and, Dictionaries.ipynb">Booleans, Tuples, and, Dictionaries</a></li>
<li><a href="05. Control Flow.ipynb">Control Flow</a></li>
<li><a href="Practice Problem - Cryptography.ipynb">Practice Problem - Cryptography.ipynb</a></li>
<li><a href="06. Functions.ipynb">Functions</a></li>
<li><a href="07. Reading and writing files.ipynb">Reading and writing files</a></li>
<li><a href="08. Modules and Variable Scope.ipynb">Modules and Variable Scope</a></li>
<li><a href="Practice Problem - Temperatures.ipynb">Practice Problem - Temperatures</a></li>
<li><a href="Problem Set 1.ipynb">Problem Set 1</a></li>
<li><a href="09. Introduction to Numpy.ipynb">Introduction to Numpy</a></li>
<li><a href="10. Introduction to Matplotlib.ipynb">Introduction to Matplotlib</a></li>
<li><a href="11. Files and paths.nbconvert.ipynb">Files and paths.nbconvert</a></li>
<li><a href="12. String Formatting.nbconvert.ipynb">String Formatting</a></li>
<li><a href="Practice Problem - Monte-Carlo Error Propagation.nbconvert.ipynb">Practice Problem - Monte-Carlo Error Propagation</a></li>
<li><a href="Problem Set 2.ipynb">Problem Set 2</a></li>
<li><a href="13. Python variables - behind the scenes.ipynb">13. Python variables - behind the scenes</a></li>
<li><a href="14. Fitting models to data.ipynb">14. Fitting models to data</a></li>
<li><a href="15. Interpolation and Integration.ipynb">15. Interpolation and Integration</a></li>
<li><a href="16. Understanding Python errors.ipynb">16. Understanding Python errors</a></li>
<li><a href="Practice Problem - Radioactive Decay.nbconvert.ipynb">Practice Problem - Radioactive Decay</a></li>
<li><a href="Problem Set 3.ipynb">Problem Set 3</a></li>
<li><a href="17. Accessing remote resources.ipynb">17. Accessing remote resources</a></li>
<li><a href="18. Object-oriented programming.nbconvert.ipynb">18. Object-oriented programming</a></li>
<li><a href="19. List comprehension.ipynb">19. List comprehension</a></li>
</ul>
</p>
<!--#else -->
<div id="ueberschrift">
<h1>Python for scientists</h1>
</div>
<p>
<h3>Sommersemester 2024</h3>
<h4>F. Spanier</h4>
</p>
<hr>
<p>
<table>
<tr>
<td>Place</td>
<td>INF 226, PC-Pool</td>
</tr>
<tr>
<td>Time</td>
<td> 23.-27.09., 09:00 - 13:00</td>
</tr>
</table>
</p>
<p>
<ul>
<li><a href="00. About the course.ipynb">About the course</a></li>
<li><a href="01. What is Python.ipynb">What is Python</a></li>
<li><a href="02. Using the IPython notebook.ipynb">Using the IPython notebook</a></li>
<li><a href="03. Numbers, String, and Lists.ipynb">Numbers, String, and Lists</a></li>
<li><a href="04. Booleans, Tuples, and, Dictionaries.ipynb">Booleans, Tuples, and, Dictionaries</a></li>
<li><a href="05. Control Flow.ipynb">Control Flow</a></li>
<li><a href="Practice Problem - Cryptography.ipynb">Practice Problem - Cryptography.ipynb</a></li>
<li><a href="06. Functions.ipynb">Functions</a></li>
<li><a href="07. Reading and writing files.ipynb">Reading and writing files</a></li>
<li><a href="08. Modules and Variable Scope.ipynb">Modules and Variable Scope</a></li>
<li><a href="Practice Problem - Temperatures.ipynb">Practice Problem - Temperatures</a></li>
<li><a href="Problem Set 1.ipynb">Problem Set 1</a></li>
<li><a href="09. Introduction to Numpy.ipynb">Introduction to Numpy</a></li>
<li><a href="10. Introduction to Matplotlib.ipynb">Introduction to Matplotlib</a></li>
<li><a href="11. Files and paths.nbconvert.ipynb">Files and paths.nbconvert</a></li>
<li><a href="12. String Formatting.nbconvert.ipynb">String Formatting</a></li>
<li><a href="Practice Problem - Monte-Carlo Error Propagation.nbconvert.ipynb">Practice Problem - Monte-Carlo Error Propagation</a></li>
<li><a href="Problem Set 2.ipynb">Problem Set 2</a></li>
<li><a href="13. Python variables - behind the scenes.ipynb">13. Python variables - behind the scenes</a></li>
<li><a href="14. Fitting models to data.ipynb">14. Fitting models to data</a></li>
<li><a href="15. Interpolation and Integration.ipynb">15. Interpolation and Integration</a></li>
<li><a href="16. Understanding Python errors.ipynb">16. Understanding Python errors</a></li>
<li><a href="Practice Problem - Radioactive Decay.nbconvert.ipynb">Practice Problem - Radioactive Decay</a></li>
<li><a href="Problem Set 3.ipynb">Problem Set 3</a></li>
<li><a href="17. Accessing remote resources.ipynb">17. Accessing remote resources</a></li>
<li><a href="18. Object-oriented programming.nbconvert.ipynb">18. Object-oriented programming</a></li>
<li><a href="19. List comprehension.ipynb">19. List comprehension</a></li>
</ul>
</p>
<!--#endif -->
<!--#include virtual="/share/after_include.shtml" -->