Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
63217cba01 | ||
|
|
535d4a0bd1 | ||
|
|
a3731fc280 | ||
|
|
4811c2c8e7 | ||
|
|
37ead0063c | ||
|
|
f6eb4d7b7c | ||
|
|
37133059bf | ||
|
|
8d6a025b3f | ||
|
|
2f1e0d1e63 | ||
|
|
d4d993b3c9 | ||
|
|
94c1ede797 |
@@ -1,5 +1,5 @@
|
||||
|
||||
<!--#set var="rb_section" value="home" -->
|
||||
<!--#set var="rb_section" value="cv" -->
|
||||
<!--#include virtual="header_include.shtml" -->
|
||||
<!--#set var="title_de" value="Lebenslauf von F. Spanier" -->
|
||||
<!--#set var="title_en" value="Curriculum Vitae of F. Spanier" -->
|
||||
@@ -28,10 +28,10 @@
|
||||
<tr><td>2003-2005</td><td>Doktorand am <a href="http://www.tp4.rub.de">Lehrstuhl für Theoretische Physik IV (RUB)</a></td></tr>
|
||||
<tr><td>2005</td><td>Dissertation zu "Plasmawellenheizung im interstellaren " betreut von Reinhard Schlickeiser</td></tr>
|
||||
<tr><td>2006-2013</td><td>Juniorforschungsgruppenleiter am <a href="http://www.astro.uni-wuerzburg.de">Lehrstuhl Astronomie, Universität Würzburg</a></td></tr>
|
||||
<tr><td>2007-2009</td><td>Gastwissenschatler in der <a href="https://blogs.helsinki.fi/spacephysics">Space physics Gruppe University Helsinki</a> in the group of Rami Vainio</td></tr>
|
||||
<tr><td>2007-2009</td><td>Gastwissenschatler in der <a href="https://blogs.helsinki.fi/spacephysics">Space physics Gruppe University Helsinki</a> in der Gruppe von Rami Vainio</td></tr>
|
||||
<tr><td>2013-2017</td><td>Professor am <a href="http://natural-sciences.nwu.ac.za/space-research">Centre for Space Research, North-West University</a> </td></tr>
|
||||
<tr><td>2018-2019</td><td>Projektwissenschaftler in der <a href="http://www.katrin.kit.edu/">KATRIN Kollaboration</td></td></tr>
|
||||
<tr><td>2018-2019</td><td>DFG Wissenschaftler am <a href="https://www.zah.uni-heidelberg.de">ZAH Heidelberg</td></td></tr>
|
||||
<tr><td>2019-</td><td>DFG Wissenschaftler am <a href="https://www.zah.uni-heidelberg.de">ZAH Heidelberg</td></td></tr>
|
||||
</table>
|
||||
</p>
|
||||
|
||||
@@ -47,7 +47,7 @@
|
||||
<tr><td>2007-2009</td><td>Guest scientist at the <a href="https://blogs.helsinki.fi/spacephysics">Space physics group University Helsinki</a> in the group of Rami Vainio</td></tr>
|
||||
<tr><td>2013-2017</td><td>Professor at the <a href="http://natural-sciences.nwu.ac.za/space-research">Centre for Space Research, North-West University</a> </td></tr>
|
||||
<tr><td>2018-2019</td><td>Project scientist for the <a href="http://www.katrin.kit.edu/">KATRIN collaboration</td></td></tr>
|
||||
<tr><td>2018-2019</td><td>DFG fellow at the <a href="https://www.zah.uni-heidelberg.de">ZAH Heidelberg</td></td></tr>
|
||||
<tr><td>2019-</td><td>DFG fellow at the <a href="https://www.zah.uni-heidelberg.de">ZAH Heidelberg</td></td></tr>
|
||||
</table>
|
||||
</p>
|
||||
<!--#endif -->
|
||||
|
||||
|
After Width: | Height: | Size: 27 KiB |
@@ -1,7 +1,7 @@
|
||||
<!--#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="title_de" value="Webseite von Felix Spanier" -->
|
||||
<!--#set var="title_en" value="Felix Spanier's Homepage" -->
|
||||
<!--#set var="autolocation" value="on" -->
|
||||
<!--#set var="location_de" value="fspanier" -->
|
||||
<!--#set var="location_en" value="fspanier" -->
|
||||
@@ -9,7 +9,7 @@
|
||||
|
||||
<!-- Test -->
|
||||
|
||||
<h1>Dr. Felix Spanier</h1>
|
||||
<h1>PD Dr. Felix Spanier</h1>
|
||||
|
||||
|
||||
|
||||
@@ -62,14 +62,13 @@ ORCID: orcid.org/0000-0001-6802-4744
|
||||
<!--#if expr="$language = de" -->
|
||||
<h3 style="color: red">Aktuell</h3>
|
||||
|
||||
<p style=" border:3px; border-style:solid; border-color:#FF0000; padding: 1em;">Im Wintersemester 2020/2021 halte ich das Pflichtseminar "Astrophysik der Kosmischen Strahlung". Weiter Informationen
|
||||
befinden sich bei den <a href="lectures/cosmicray_2020ws/index.shtml">Vorlesungen</a>
|
||||
<p style=" border:3px; border-style:solid; border-color:#FF0000; padding: 1em;">Im Wintersemester 2023/2024 halte ich die Master-Vorlesung "Numerische Methoden der Plasmaastrophysik". Weiter Informationen
|
||||
befinden sich bei den <a href="lectures/numericalplasmaastro_2023ws/index.shtml">Vorlesungen</a>
|
||||
</p>
|
||||
|
||||
<!--#else -->
|
||||
|
||||
I will host the Bachelor's seminar "Cosmic Ray Astrophysics". Weiter Informationen
|
||||
befinden sich bei den <a href="lectures/cosmicray_2020ws/index.shtml">Vorlesungen</a>
|
||||
I will host the lecture "Numerical Methods of Plasmaastrophysiscs". Please see <a href="lectures/numericalplasmaastro_2023ws/index.shtml">Lectures</a> for further details.
|
||||
|
||||
<!--#endif -->
|
||||
|
||||
@@ -96,6 +95,15 @@ numerischen Methoden erläutere ich <a href="codes.shtml">hier.</a>
|
||||
<img src="images/katrin_logo.png" alt="Der KATRIN-Papagei" height="100">
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td width="500">
|
||||
Seit neuestem arbeite ich auch beim <a href="https://www.project8.org/">Project 8-Konsortium</a> mit. Auch dort befasse ich mit Plasmasimulationen</a>.
|
||||
</td>
|
||||
|
||||
<td width="100">
|
||||
<img src="images/P8Logo.png" alt="Project 8-Logo" height="100">
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
</p>
|
||||
@@ -122,6 +130,15 @@ numerischen Methoden erläutere ich <a href="codes.shtml">hier.</a>
|
||||
<img src="images/katrin_logo.png" alt="Der KATRIN-Papagei" height="100">
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td width="500">
|
||||
I have joined the <a href="https://www.project8.org/">Project 8 consortium</a> recently. There I am also tasked with plasma simulations.</a>.
|
||||
</td>
|
||||
|
||||
<td width="100">
|
||||
<img src="images/P8Logo.png" alt="Project 8-Logo" height="100">
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
</p>
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
<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>Kosmische Neutrinos</h1>
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
<p>
|
||||
<h3>Sommersemester 2023</h3>
|
||||
<h4>F. Spanier</h4>
|
||||
</p>
|
||||
<hr>
|
||||
<p>
|
||||
<table>
|
||||
<tr>
|
||||
<td>Ort</td>
|
||||
<td>Philosophenweg 12 / Raum 056</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Zeit</td>
|
||||
<td> Do. 14:00 bis 15:30</td>
|
||||
</tr>
|
||||
</table>
|
||||
</p>
|
||||
<p>
|
||||
Hier handelt es sich um ein <b>Bachelor-Pflichtseminar</b>. <br>
|
||||
|
||||
Das Seminar wird wie folgt verlaufen:
|
||||
<ul>
|
||||
<li>Zu Beginn des Semesters verteilen wir die Themen (s. dazu auch meine erste Ankündigung zur technischen
|
||||
Durchführung)</li>
|
||||
<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> 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
|
||||
gestellt, stelle ich Fragen an die Zuhörer</li>
|
||||
</ul>
|
||||
</p>
|
||||
<p>
|
||||
Bitte registrieren Sie sich bei
|
||||
<!--<a href="https://moodle.uni-heidelberg.de/course/view.php?id=631">Moodle</a> -->
|
||||
<a href="https://moodle.uni-heidelberg.de/course/view.php?id=16915"> Moodle</a>
|
||||
und der <a href="https://uebungen.physik.uni-heidelberg.de/v/1679">Übungsgruppenverwaltung</a>
|
||||
</p>
|
||||
|
||||
<p>
|
||||
<h3>Themen des Seminars sind Neutrinos in verschiedenen Bereichen des Universum. Das sind unter anderem:</h3>
|
||||
<ul>
|
||||
<li>Eigenschaften von Neutrinos</li>
|
||||
<li>Detektion von Neutrinos</li>
|
||||
<li>Quellen von Neutrinos</li>
|
||||
<li>Neutrinos und Dunkle Materie</li>
|
||||
</ul>
|
||||
</p>
|
||||
|
||||
<!--#else -->
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<div id="ueberschrift">
|
||||
<h1>Cosmic Neutrinos </h1>
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
<p>
|
||||
<h3>Summer semester 2023</h3>
|
||||
<h4>F. Spanier</h4>
|
||||
</p>
|
||||
<hr>
|
||||
<p>
|
||||
<table>
|
||||
<tr>
|
||||
<td>Place</td>
|
||||
<td>Philosophenweg 12 / Room 056</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Time</td>
|
||||
<td> Thu 14:00 bis 15:30</td>
|
||||
</tr>
|
||||
</table>
|
||||
</p>
|
||||
|
||||
<p>
|
||||
This is a compulsory bachelor's seminar. <br>
|
||||
The seminar will proceed as follows:
|
||||
<ul>
|
||||
<li>At the beginning of the semester we distribute the topics </li>
|
||||
|
||||
<li>At the first appointment after the topic has been assigned, I explain some research techniques and discuss the horizon of expectations for the presentation.</li>
|
||||
|
||||
<li>You will receive some scientific articles on which the presentation should be based. </li>
|
||||
|
||||
<li>One week before the presentation, you can give a test presentation.</li>
|
||||
|
||||
<li>Your presentation will be accompanied by a handout</li>
|
||||
|
||||
<li>The presentation, the question and answer session and the paper will be assessed.</li>
|
||||
|
||||
<li>You are also expected to participate as an audience member by asking questions about the presentation - if no questions are asked, I will ask questions of the audience.</li>
|
||||
|
||||
</ul>
|
||||
</p>
|
||||
|
||||
<p>
|
||||
Please register with
|
||||
<!--<a href="https://moodle.uni-heidelberg.de/course/view.php?id=631">Moodle</a> -->
|
||||
<a href="https://moodle.uni-heidelberg.de/course/view.php?id=16915"> Moodle</a>
|
||||
and the <a href="https://uebungen.physik.uni-heidelberg.de/v/1679">tutorial group administratiom</a>
|
||||
</p>
|
||||
|
||||
|
||||
|
||||
<p>
|
||||
<h3>The seminar's topic are neutrinos in various parts of the universe:</h3>
|
||||
<ul>
|
||||
<li>Neutrino properties</li>
|
||||
<li>Detection of neutrinos</li>
|
||||
<li>Sources of neutrinos</li>
|
||||
<li>Neutrinos and dark matter</li>
|
||||
</ul>
|
||||
</p>
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<!--#endif -->
|
||||
|
||||
|
||||
<!--#include virtual="/share/after_include.shtml" -->
|
||||
@@ -0,0 +1,94 @@
|
||||
<head>
|
||||
<!--#set var="rb_section" value="home" -->
|
||||
<!--#include virtual="../../header_include.shtml" -->
|
||||
<!--#set var="title_de" value="Webseite von Felix Spanier" -->
|
||||
<!--#set var="title_en" value="Felix Spanier's Homepage" -->
|
||||
<!--#set var="autolocation" value="on" -->
|
||||
<!--#set var="location_de" value="fspanier" -->
|
||||
<!--#set var="location_en" value="fspanier" -->
|
||||
</head>
|
||||
|
||||
|
||||
<div id="ueberschrift">
|
||||
<h1>Die höchsten Energien im Universum - die kosmische Strahlung (PSem)</h1>
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
<p>
|
||||
<h3>Sommersemester 2024</h3>
|
||||
<h4>F. Spanier</h4>
|
||||
</p>
|
||||
<hr>
|
||||
<p>
|
||||
<table>
|
||||
<tr>
|
||||
<td>Ort</td>
|
||||
<td> Phil 12 R 105</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Zeit</td>
|
||||
<td> Di. 14:15 bis 15:45</td>
|
||||
</tr>
|
||||
</table>
|
||||
</p>
|
||||
<p>
|
||||
Hier handelt es sich um ein <b>Bachelor-Pflichtseminar</b>. <br>
|
||||
|
||||
Das Seminar wird wie folgt verlaufen:
|
||||
<ul>
|
||||
<li>Zu Beginn des Semesters verteilen wir die Themen (s. dazu auch meine erste Ankündigung zur technischen
|
||||
Durchführung)</li>
|
||||
<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 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
|
||||
gestellt, stelle ich Fragen an die Zuhörer</li>
|
||||
</ul>
|
||||
</p>
|
||||
<p>
|
||||
Bitte registrieren Sie sich bei
|
||||
<!--<a href="https://moodle.uni-heidelberg.de/course/view.php?id=631">Moodle</a> -->
|
||||
<a href="https://moodle.uni-heidelberg.de/course/view.php?id=xxx"> Moodle</a>
|
||||
und der <a href="https://uebungen.physik.uni-heidelberg.de/v/1771">Übungsgruppenverwaltung</a>
|
||||
</p>
|
||||
|
||||
<p>
|
||||
<h3>Themen des Seminars:</h3>
|
||||
<ul>
|
||||
<li>Methoden: Bodengebundene CR-Beobachtung</li>
|
||||
<li>Methoden: Satelliten CR-Beobachtung</li>
|
||||
<li>Methoden: Das IceCUBE-Teleskop</li>
|
||||
|
||||
|
||||
|
||||
<li>Quellen: Die Sonne</li>
|
||||
<li>Quellen: Supernova Überreste</li>
|
||||
<li>Quellen: Pulsare</li>
|
||||
<li>Quellen: Aktive Galaxienkerne</li>
|
||||
|
||||
|
||||
<li>Beobachtung: Spektrum der kosmischen Strahlung</li>
|
||||
<li>Beobachtung: Cosmic ray clocks</li>
|
||||
<li>Beobachtung: Greisen-Zatsepin-Kuzmin Cutoff</li>
|
||||
<li>Beobachtung: Solare Modulation</li>
|
||||
<li>Beobachtung: Neutrinospektrum</li>
|
||||
<li>Beobachtung: Kosmische Strahlung und Magnetfeld</li>
|
||||
|
||||
<li>Theorie: Fokker-Planck-Gleichung</li>
|
||||
<li>Theorie: Fermi-Beschleunigung</li>
|
||||
<li>Theorie: Rekonnektion</li>
|
||||
<li>Exotik: Dunkle Materie Annihilation</li>
|
||||
<li>Exotik: Positron-Anomalie</li>
|
||||
|
||||
|
||||
|
||||
|
||||
</ul>
|
||||
</p>
|
||||
|
||||
|
||||
<!--#include virtual="/share/after_include.shtml" -->
|
||||
@@ -0,0 +1,108 @@
|
||||
<head>
|
||||
<!--#set var="rb_section" value="home" -->
|
||||
<!--#include virtual="../../header_include.shtml" -->
|
||||
<!--#set var="title_de" value="Webseite von fspanier" -->
|
||||
<!--#set var="title_en" value="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>Numerische Methoden der Plasmaastrophysik </h1>
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
<p>
|
||||
<h3>Wintersemester 2022/2023</h3>
|
||||
<h4>F. Spanier</h4>
|
||||
</p>
|
||||
<hr>
|
||||
<p>Die Vorlesung beschäftigt sich mit gängigen numerischen Methoden, die für aktuelle plasmaphysikalische
|
||||
Probleme in der Astrophysik verwendet werden. Dazu zählen u.a.
|
||||
<ul>
|
||||
<li>Finite Volumenmethoden</li>
|
||||
<li>N-Body-Codes</li>
|
||||
<li>Tree-Codes</li>
|
||||
<li>Particle-in-Cell Codes</li>
|
||||
<li>Vlasov-Methoden</li>
|
||||
<li>Lattice-Boltzmann-Methoden</li>
|
||||
</ul>
|
||||
In den Übungen sollen diese Methoden numerisch umgesetzt werden. Das Beherrschen einer Programmiersprache
|
||||
ist daher verpflichtend. Kenntnisse in Elektrodynamik oder Plasmaphysik sind hilfreich aber nicht
|
||||
notwendig.
|
||||
</p>
|
||||
|
||||
<p>
|
||||
<table>
|
||||
<tr>
|
||||
<td>Ort</td>
|
||||
<td> Philos.-weg 12 / kHS</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Zeit</td>
|
||||
<td> Vorlesung: Do 16:15 - 18:00<br>Übung: Mo 16:15 - 18:00</td>
|
||||
</tr>
|
||||
</table>
|
||||
</p>
|
||||
|
||||
<p>
|
||||
Bitte registrieren Sie sich bei
|
||||
<!--<a href="https://moodle.uni-heidelberg.de/course/view.php?id=631">Moodle</a> -->
|
||||
<a href="https://uebungen.physik.uni-heidelberg.de/v/1612">Übungsgruppenverwaltung</a>
|
||||
</p>
|
||||
|
||||
<!--#else -->
|
||||
|
||||
<div id="ueberschrift">
|
||||
<h1>Numerical methods in plasma-astrophysics</h1>
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
<p>
|
||||
<h3>Winter 2022/2023</h3>
|
||||
<h4>F. Spanier</h4>
|
||||
</p>
|
||||
<hr>
|
||||
<p>In this lecture numerical methods for current plasma problems in astrophysics are
|
||||
discussed. This includes
|
||||
<ul>
|
||||
<li>Finite Volume methods</li>
|
||||
<li>N-Body-Codes</li>
|
||||
<li>Tree-Codes</li>
|
||||
<li>Particle-in-Cell Codes</li>
|
||||
<li>Vlasov-Methods</li>
|
||||
<li>Lattice-Boltzmann-Methods</li>
|
||||
</ul>
|
||||
During the exercises the numerical methods shall be coded - knowledge of at least one
|
||||
programming language is a must. Experience in electrodynamics or plasmaphysics is a plus.
|
||||
|
||||
</p>
|
||||
|
||||
<p>
|
||||
<table>
|
||||
<tr>
|
||||
<td>Place</td>
|
||||
<td> Philos.-weg 12 / kHS</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Tine</td>
|
||||
<td> Lecture: Thu 16:15 - 18:00<br>Exercise: Mon 16:15 - 18:00</td>
|
||||
</tr>
|
||||
</table>
|
||||
</p>
|
||||
|
||||
<p>
|
||||
Please register yourself in the
|
||||
<!--<a href="https://moodle.uni-heidelberg.de/course/view.php?id=631">Moodle</a> -->
|
||||
<a href="https://uebungen.physik.uni-heidelberg.de/v/1612">Exercise Group Administration</a>
|
||||
</p>
|
||||
|
||||
|
||||
<!--#endif -->
|
||||
|
||||
|
||||
<!--#include virtual="/share/after_include.shtml" -->
|
||||
@@ -0,0 +1,108 @@
|
||||
<head>
|
||||
<!--#set var="rb_section" value="home" -->
|
||||
<!--#include virtual="../../header_include.shtml" -->
|
||||
<!--#set var="title_de" value="Webseite von fspanier" -->
|
||||
<!--#set var="title_en" value="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>Numerische Methoden der Plasmaastrophysik </h1>
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
<p>
|
||||
<h3>Wintersemester 2023/2024</h3>
|
||||
<h4>F. Spanier</h4>
|
||||
</p>
|
||||
<hr>
|
||||
<p>Die Vorlesung beschäftigt sich mit gängigen numerischen Methoden, die für aktuelle plasmaphysikalische
|
||||
Probleme in der Astrophysik verwendet werden. Dazu zählen u.a.
|
||||
<ul>
|
||||
<li>Finite Volumenmethoden</li>
|
||||
<li>N-Body-Codes</li>
|
||||
<li>Tree-Codes</li>
|
||||
<li>Particle-in-Cell Codes</li>
|
||||
<li>Vlasov-Methoden</li>
|
||||
<li>Lattice-Boltzmann-Methoden</li>
|
||||
</ul>
|
||||
In den Übungen sollen diese Methoden numerisch umgesetzt werden. Das Beherrschen einer Programmiersprache
|
||||
ist daher verpflichtend. Kenntnisse in Elektrodynamik oder Plasmaphysik sind hilfreich aber nicht
|
||||
notwendig.
|
||||
</p>
|
||||
|
||||
<p>
|
||||
<table>
|
||||
<tr>
|
||||
<td>Ort</td>
|
||||
<td> Philos.-weg 12 / kHS</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Zeit</td>
|
||||
<td> Vorlesung: Do 16:15 - 18:00<br>Übung: Mo 16:15 - 18:00</td>
|
||||
</tr>
|
||||
</table>
|
||||
</p>
|
||||
|
||||
<p>
|
||||
Bitte registrieren Sie sich bei
|
||||
<a href="https://moodle.uni-heidelberg.de/course/view.php?id=19057">Moodle</a> und
|
||||
<a href="https://uebungen.physik.uni-heidelberg.de/v/1761">Übungsgruppenverwaltung</a>
|
||||
</p>
|
||||
|
||||
<!--#else -->
|
||||
|
||||
<div id="ueberschrift">
|
||||
<h1>Numerical methods in plasma-astrophysics</h1>
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
<p>
|
||||
<h3>Winter 2023/2024</h3>
|
||||
<h4>F. Spanier</h4>
|
||||
</p>
|
||||
<hr>
|
||||
<p>In this lecture numerical methods for current plasma problems in astrophysics are
|
||||
discussed. This includes
|
||||
<ul>
|
||||
<li>Finite Volume methods</li>
|
||||
<li>N-Body-Codes</li>
|
||||
<li>Tree-Codes</li>
|
||||
<li>Particle-in-Cell Codes</li>
|
||||
<li>Vlasov-Methods</li>
|
||||
<li>Lattice-Boltzmann-Methods</li>
|
||||
</ul>
|
||||
During the exercises the numerical methods shall be coded - knowledge of at least one
|
||||
programming language is a must. Experience in electrodynamics or plasmaphysics is a plus.
|
||||
|
||||
</p>
|
||||
|
||||
<p>
|
||||
<table>
|
||||
<tr>
|
||||
<td>Place</td>
|
||||
<td> Philos.-weg 12 / kHS</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Tine</td>
|
||||
<td> Lecture: Thu 16:15 - 18:00<br>Exercise: Mon 16:15 - 18:00</td>
|
||||
</tr>
|
||||
</table>
|
||||
</p>
|
||||
|
||||
<p>
|
||||
Please register yourself in the
|
||||
<a href="https://moodle.uni-heidelberg.de/course/view.php?id=19057">Moodle</a> and
|
||||
<a href="https://uebungen.physik.uni-heidelberg.de/v/1761">Exercise Group Administration</a>
|
||||
</p>
|
||||
|
||||
|
||||
<!--#endif -->
|
||||
|
||||
|
||||
<!--#include virtual="/share/after_include.shtml" -->
|
||||
@@ -0,0 +1,46 @@
|
||||
<head>
|
||||
<!--#set var="rb_section" value="home" -->
|
||||
<!--#include virtual="../../header_include.shtml" -->
|
||||
<!--#set var="title_de" value="Webseite von fspanier" -->
|
||||
<!--#set var="title_en" value="fspanier's Homepage" -->
|
||||
<!--#set var="autolocation" value="on" -->
|
||||
<!--#set var="location_de" value="fspanier" -->
|
||||
<!--#set var="location_en" value="fspanier" -->
|
||||
</head>
|
||||
|
||||
|
||||
<div id="ueberschrift">
|
||||
<h1>Plasmaastrophysik</h1>
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
<p>
|
||||
<h3>Sommersemester 2021</h3>
|
||||
<h4>F. Spanier</h4>
|
||||
</p>
|
||||
<hr>
|
||||
<p>
|
||||
<table>
|
||||
<tr>
|
||||
<td>Ort</td>
|
||||
<td> Das Internet!</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Zeit</td>
|
||||
<td> Fr. 14:15 bis 15:45</td>
|
||||
</tr>
|
||||
</table>
|
||||
</p>
|
||||
|
||||
<p>
|
||||
Bitte registrieren Sie sich bei
|
||||
<!--<a href="https://moodle.uni-heidelberg.de/course/view.php?id=631">Moodle</a> -->
|
||||
<a href="https://moodle.uni-heidelberg.de/course/view.php?id=7469"> Moodle</a>
|
||||
und der <a href="https://uebungen.physik.uni-heidelberg.de/v/1343">Übungsgruppenverwaltung</a>
|
||||
</p>
|
||||
|
||||
|
||||
|
||||
|
||||
<!--#include virtual="/share/after_include.shtml" -->
|
||||
@@ -0,0 +1,149 @@
|
||||
<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>Das Plasma-Universum </h1>
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
<p>
|
||||
<h3>Wintersemester 2021/2022</h3>
|
||||
<h4>F. Spanier</h4>
|
||||
</p>
|
||||
<hr>
|
||||
<p>
|
||||
<table>
|
||||
<tr>
|
||||
<td>Ort</td>
|
||||
<td>Philosophenweg 12 / Raum 056</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Zeit</td>
|
||||
<td> Do. 14:00 bis 15:30</td>
|
||||
</tr>
|
||||
</table>
|
||||
</p>
|
||||
<p>
|
||||
Hier handelt es sich um ein <b>Master-Pflichtseminar</b>. <br>
|
||||
|
||||
Das Seminar wird wie folgt verlaufen:
|
||||
<ul>
|
||||
<li>Zu Beginn des Semesters verteilen wir die Themen </li>
|
||||
<li>Am ersten Termin nach der Themenvergabe erläutere ich einige Recherche-Techniken und bespreche den Erwartungshorizont für Vortrag und schriftliche Zusammenfassung</li>
|
||||
<li>Sie erhalten einen mehr oder minder aktuellen wissenschaftlichen Artikel, an dem sich der Vortrag orientieren soll </li>
|
||||
<li> Eine Woche vor dem Vortrag können Sie einen Probevortrag halten</li>
|
||||
<li> Zu Ihrem Vortrag gehört eine schriftliche Ausarbeitung</li>
|
||||
<li> Bewertet werden der Vortrag, die Fragerunde und die Ausarbeitung</li>
|
||||
<li> Es wird erwartet, dass Sie sich auch als Zuhörer mit Fragen zum Vortrag beteiligen - werden keine Fragen
|
||||
gestellt, stelle ich Fragen an die Zuhörer</li>
|
||||
</ul>
|
||||
</p>
|
||||
<p>
|
||||
Bitte registrieren Sie sich bei
|
||||
<!--<a href="https://moodle.uni-heidelberg.de/course/view.php?id=631">Moodle</a> -->
|
||||
<a href="https://moodle.uni-heidelberg.de/course/view.php?id=9342"> Moodle</a>
|
||||
und der <a href="https://uebungen.physik.uni-heidelberg.de/v/1415">Übungsgruppenverwaltung</a>
|
||||
</p>
|
||||
|
||||
<p>
|
||||
<h3>Themen des Seminars sind Plasmen in verschiedenen Bereichen des Universum. Das sind unter anderem:</h3>
|
||||
<ul>
|
||||
<li>Kosmische Magnetfelder und deren Herkunft</li>
|
||||
<li>Interstellare Plasmen</li>
|
||||
<li>Sonnen- und Sternwinde</li>
|
||||
<li>Akkretionsscheiben</li>
|
||||
<li>Jets in Aktiven Galaxienkernen</li>
|
||||
<li>Pulsare und Pulsarwindnebel</li>
|
||||
<li>(relativistische) Stoßfronten</li>
|
||||
</ul>
|
||||
</p>
|
||||
|
||||
<!--#else -->
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<div id="ueberschrift">
|
||||
<h1>The plasma universe </h1>
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
<p>
|
||||
<h3>Winter semester 2021/2022</h3>
|
||||
<h4>F. Spanier</h4>
|
||||
</p>
|
||||
<hr>
|
||||
<p>
|
||||
<table>
|
||||
<tr>
|
||||
<td>Place</td>
|
||||
<td>Philosophenweg 12 / Room 056</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Time</td>
|
||||
<td> Thu 14:00 bis 15:30</td>
|
||||
</tr>
|
||||
</table>
|
||||
</p>
|
||||
<p>
|
||||
This is a compulsory Master's seminar (<b>MVSem</b>) <br>
|
||||
|
||||
The seminar will proceed as follows:
|
||||
<ul>
|
||||
<li>At the beginning of the semester we distribute the topics </li>
|
||||
|
||||
<li>At the first appointment after the topic has been assigned, I explain some research techniques and discuss the horizon of expectations for the presentation and written summary.</li>
|
||||
|
||||
<li>You will receive a more or less current scientific article on which the presentation should be based. </li>
|
||||
|
||||
<li>One week before the presentation, you can give a test presentation.</li>
|
||||
|
||||
<li>Your presentation will be accompanied by a written summary</li>
|
||||
|
||||
<li>The presentation, the question and answer session and the paper will be assessed.</li>
|
||||
|
||||
<li>You are also expected to participate as an audience member by asking questions about the presentation - if no questions are asked, I will ask questions of the audience.</li>
|
||||
|
||||
</ul>
|
||||
</p>
|
||||
<p>
|
||||
Please register at
|
||||
<!--<a href="https://moodle.uni-heidelberg.de/course/view.php?id=631">Moodle</a> -->
|
||||
<a href="https://moodle.uni-heidelberg.de/course/view.php?id=9342"> Moodle</a>
|
||||
and <a href="https://uebungen.physik.uni-heidelberg.de/v/1415">Übungsgruppenverwaltung</a>
|
||||
</p>
|
||||
|
||||
<p>
|
||||
<h3>The seminar will cover plasma topics from various places of the universe. This includes for example:</h3>
|
||||
<ul>
|
||||
<li>Cosmic magnetic fields and their origin </li>
|
||||
<li>Interstellar plasmas</li>
|
||||
<li>Solar- and stellar winds</li>
|
||||
<li>Accretion disks</li>
|
||||
<li>Jets in Active Galactic nuclei</li>
|
||||
<li>Pulsars and pulsar wind nebulae</li>
|
||||
<li>(relativistic) shock fronts</li>
|
||||
</ul>
|
||||
</p>
|
||||
|
||||
|
||||
|
||||
|
||||
<!--#endif -->
|
||||
|
||||
|
||||
<!--#include virtual="/share/after_include.shtml" -->
|
||||
@@ -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
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"# What is Python?"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"slideshow": {
|
||||
"slide_type": "notes"
|
||||
}
|
||||
},
|
||||
"source": [
|
||||
""
|
||||
]
|
||||
},
|
||||
{
|
||||
"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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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",
|
||||
""
|
||||
]
|
||||
},
|
||||
{
|
||||
"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",
|
||||
""
|
||||
]
|
||||
},
|
||||
{
|
||||
"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",
|
||||
""
|
||||
]
|
||||
},
|
||||
{
|
||||
"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",
|
||||
""
|
||||
]
|
||||
},
|
||||
{
|
||||
"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",
|
||||
""
|
||||
]
|
||||
},
|
||||
{
|
||||
"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",
|
||||
"\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",
|
||||
""
|
||||
]
|
||||
},
|
||||
{
|
||||
"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
|
||||
}
|
||||
@@ -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",
|
||||
"\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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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" -->
|
||||
@@ -1,4 +1,5 @@
|
||||
<div id="leftColumnVariabel">
|
||||
|
||||
<!--#if expr="$language = de" -->
|
||||
<div class="institutslogo"><a href="http://www.zah.uni-hd.de/index.php.de"><img src="/share/zah-text.png"
|
||||
alt="Zentrum für Astronomie" width="204" /></a></div>
|
||||
@@ -41,25 +42,38 @@
|
||||
|
||||
<li>
|
||||
<!--#if expr="$language = de" -->
|
||||
<a href="/~fspanier/index.shtml?lang=de" <!--#if expr="$rb_section = home" -->class="current"
|
||||
<!--#endif --> >
|
||||
<a href="/~fspanier/index.shtml?lang=de" <!--#if expr="$rb_section = home" --> class="current" <!--#endif -->>
|
||||
|
||||
<img src="/share/home1.gif" border="0">
|
||||
Startseite
|
||||
</a>
|
||||
<!--#else -->
|
||||
<a href="/~fspanier/index.shtml?lang=en" <!--#if expr="$rb_section = home" -->class="current"
|
||||
<!--#endif --> >
|
||||
<a href="/~fspanier/index.shtml?lang=en" <!--#if expr="$rb_section = home" -->class="current" <!--#endif -->>
|
||||
<img src="/share/home1.gif" border="0">
|
||||
Home page
|
||||
</a>
|
||||
<!--#endif -->
|
||||
</li>
|
||||
|
||||
|
||||
<li>
|
||||
<!--#if expr="$language = de" -->
|
||||
<a href="/~fspanier/research.shtml?lang=de" <!--#if expr="$rb_section = research" -->class="current"
|
||||
<!--#endif --> >
|
||||
<a href="/~fspanier/cv.shtml?lang=de" <!--#if expr="$rb_section = cv" --> class="current" <!--#endif -->>
|
||||
<img src="/share/home1.gif" border="0">
|
||||
Lebenslauf
|
||||
</a>
|
||||
<!--#else -->
|
||||
<a href="/~fspanier/cv.shtml?lang=en"<!--#if expr="$rb_section = cv" --> class="current" <!--#endif -->>
|
||||
<img src="/share/home1.gif" border="0">
|
||||
CV
|
||||
</a>
|
||||
<!--#endif -->
|
||||
</li>
|
||||
|
||||
<li>
|
||||
<!--#if expr="$language = de" -->
|
||||
<a href="/~fspanier/research.shtml?lang=de" <!--#if expr="$rb_section = research" -->class="current"<!--#endif -->>
|
||||
<img src="/share/research_icon.png" border="0">
|
||||
Forschung
|
||||
</a>
|
||||
|
||||
@@ -72,9 +86,8 @@
|
||||
</ul>
|
||||
|
||||
<!--#else -->
|
||||
<a href="/~fspanier/research.shtml?lang=en" <!--#if expr="$rb_section = research" -->class="current"
|
||||
<!--#endif --> >
|
||||
<img src="/share/home1.gif" border="0">
|
||||
<a href="/~fspanier/research.shtml?lang=en" <!--#if expr="$rb_section = research" -->class="current"<!--#endif -->>
|
||||
<img src="/share/research_icon.png" border="0">
|
||||
Research
|
||||
</a>
|
||||
|
||||
@@ -174,6 +187,7 @@
|
||||
<!--#if expr="$language = de" -->
|
||||
<a href="/~fspanier/fspanier_ads.shtml?lang=de" <!--#if expr="$rb_section = publications" -->class="current"
|
||||
<!--#endif --> >
|
||||
|
||||
<img src="/share/pub_icon.gif" border="0">
|
||||
Veröffentlichungen
|
||||
</a>
|
||||
@@ -190,10 +204,10 @@
|
||||
|
||||
<li>
|
||||
<!--#if expr="$language = de" -->
|
||||
<a href="http://www.zah.uni-hd.de/index.php.de" class="lastNav"><img src="/share/back_icon.png" />
|
||||
<a href="http://www.zah.uni-hd.de/index.php" class="lastNav"><img src="/share/back_icon.png" />
|
||||
Zentrum für Astronomie
|
||||
<!--#else -->
|
||||
<a href="http://www.zah.uni-hd.de/index.php.en" class="lastNav"><img src="/share/back_icon.png" />
|
||||
<a href="http://www.zah.uni-hd.de/index.php" class="lastNav"><img src="/share/back_icon.png" />
|
||||
Center for Astronomy
|
||||
<!--#endif -->
|
||||
</a>
|
||||
|
||||
@@ -52,7 +52,7 @@
|
||||
<p>Ziel der Forschung ist, die verschiedenen Beobachtungen (Photonen, Neutrinos, evtl. sogar Protonen und
|
||||
Gravitationswellen) miteinander zu verknüpfen (sog. Multi-Messenger Astronomie).
|
||||
Dabei sollen insbesondere selbstkonsistent aus der Teilchenverteilung das elektromagnetische Spektrum
|
||||
und dessen Variabilität oder gar die Struktur des Jets folgen. <a href="research/agn.shtml">Mehr</a></p>
|
||||
und dessen Variabilität oder gar die Struktur des Jets folgen. /p>
|
||||
</td>
|
||||
|
||||
<td><img width="300" src="research/m87-jet.jpg">
|
||||
@@ -61,6 +61,7 @@
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
<p><a href="research/agn.shtml">Mehr</a></p>
|
||||
|
||||
<h3>Kinetische Plasmaphysik</h3>
|
||||
<table>
|
||||
@@ -76,26 +77,32 @@
|
||||
vorliegen.
|
||||
</p>
|
||||
<p>
|
||||
Die mathematisch-physikalische Beschreibung von Plasmen ist dabei äußerst vielfältig. Von nicht-magnetisierten
|
||||
Die mathematisch-physikalische Beschreibung von Plasmen ist dabei äußerst vielfältig. Von
|
||||
nicht-magnetisierten
|
||||
Fluidplasmen bis zu kinetischen Plasmen in starken Magnetfeldern gibt es viele Arten und Beschreibungen
|
||||
von Plasmen, die in verschiedenen Bereichen eine Anwendung finden.
|
||||
</p>
|
||||
<p>
|
||||
Ich beschäftige mich vornehmlich mit der sogenannten kinetischen Plasmen - also Plasmen, bei denen die
|
||||
Ich beschäftige mich vornehmlich mit der sogenannten kinetischen Plasmen - also Plasmen, bei denen die
|
||||
Verteilungsfunktion der Teilchen nicht Maxwell-Boltzmann ist, sondern ein Überschuß an Teilchen bei
|
||||
höheren Energien existiert. Viele astronomische Objekte (die Sonne, Planeten, Pulsare, Aktive Galaxienkerne etc.)
|
||||
beschleunigen Teilchen und produzieren damit kinetische Plasmen.
|
||||
höheren Energien existiert. Viele astronomische Objekte (die Sonne, Planeten, Pulsare, Aktive
|
||||
Galaxienkerne etc.)
|
||||
beschleunigen Teilchen und produzieren damit kinetische Plasmen.
|
||||
</p>
|
||||
<p>
|
||||
Mit Hilfe numerischer Methoden (z.B. <a href="software/acronym.shtml">Particle-in-Cell</a>) untersuche ich,
|
||||
wie sich solche Plasmen verhalten und welchen Einfluß nichtthermische Teilchen auf das Plasma haben. <a href="research/plasma.shtml">Mehr</a>
|
||||
Mit Hilfe numerischer Methoden (z.B. <a href="software/acronym.shtml">Particle-in-Cell</a>) untersuche
|
||||
ich,
|
||||
wie sich solche Plasmen verhalten und welchen Einfluß nichtthermische Teilchen auf das Plasma haben.
|
||||
</p>
|
||||
</td>
|
||||
<td><img width="300" src="research/filamentation.png">
|
||||
<p>Darstellung von magnetischen Flußröhren, die durch eine Filamentierungsinstabilität hervorgerufen werden.<br> <i>Image credit: T. Burkart, O. Elbracht, F. Spanier</i></p></td>
|
||||
<p>Darstellung von magnetischen Flußröhren, die durch eine Filamentierungsinstabilität hervorgerufen
|
||||
werden.<br> <i>Image credit: T. Burkart, O. Elbracht, F. Spanier</i></p>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
<p><a href="research/plasma.shtml">Mehr</a></p>
|
||||
|
||||
|
||||
|
||||
@@ -128,7 +135,7 @@
|
||||
href="https://ui.adsabs.harvard.edu/abs/2008arXiv0810.5059S">Three-wave interactions of dispersive
|
||||
plasma waves propagating parallel to the magnetic field (Spanier and Vainio 2008 arXiv e-prints
|
||||
)</A>.
|
||||
<a href="research/turbulence.shtml">Mehr</a>
|
||||
|
||||
</p>
|
||||
</td>
|
||||
<td><img width="300" src="research/feldlinien.jpg">
|
||||
@@ -138,7 +145,7 @@
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
<p><a href="research/turbulence.shtml">Mehr</a></p>
|
||||
|
||||
<h3>Transport kosmischer Strahlung</h3>
|
||||
|
||||
@@ -182,7 +189,8 @@
|
||||
<i>Image credit: <A href="https://ui.adsabs.harvard.edu/abs/2018JPlPh..84a9004S">Analytical treatment of
|
||||
particle motion in circularly polarized slab-mode wave fields (Schreiner, Vainio, and Spanier
|
||||
2018 Journal of Plasma Physics )</A>
|
||||
</A></i></p>
|
||||
</A></i>
|
||||
</p>
|
||||
</td>
|
||||
|
||||
</tr>
|
||||
@@ -214,7 +222,8 @@
|
||||
wichtige Rolle (
|
||||
<A href="https://ui.adsabs.harvard.edu/abs/2018JCoPh.353..258K">Simulating the injection of magnetized
|
||||
plasma without electromagnetic precursor wave (Kilian and Spanier 2018 Journal of Computational
|
||||
Physics )</A>)</p>
|
||||
Physics )</A>)
|
||||
</p>
|
||||
|
||||
</td>
|
||||
<td><img width="300" src="research/particle_tracks.png">
|
||||
@@ -222,15 +231,53 @@
|
||||
<i>Image credit: Teilchenbeschleunigung an kollisionsfreien Schockfronten, Dissertation, P. Kilian, Uni
|
||||
Würzburg 2015 <a
|
||||
href="https://nbn-resolving.org/urn:nbn:de:bvb:20-opus-119023">urn:nbn:de:bvb:20-opus-119023</a>
|
||||
</i></p>
|
||||
|
||||
<p><a href="research/acceleration.shtml">Mehr</a>
|
||||
</i>
|
||||
</p>
|
||||
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
<p><a href="research/acceleration.shtml">Mehr</a>
|
||||
</p>
|
||||
|
||||
<h3>Plasmapyhsik in Neutrinoexperimenten</h3>
|
||||
<table>
|
||||
<tr>
|
||||
<td>
|
||||
<p>Die Messung der Neutrinomasse ist nicht direkt möglich, verschiedene Experimente versuchen aber diese
|
||||
indirekt zu bestimmen. Ein Weg diese zu bestimmen, ist die Bestimmung des Elektronenspektrums aus
|
||||
Betazerfällen. Fermi konnte schon den Einfluß der Neutrinomasse auf das Spektrum zeigen.
|
||||
</p>
|
||||
<p>
|
||||
Im KATRIN-Experiment zum Beispiel wird eine große Tritiumquelle verwendet, die eine sehr große Zahl an
|
||||
Tritiumzerfällen liefert. Damit ist es möglich, das Spektrum im Detail zu vermessen. Dabei gibt es aber
|
||||
einen Haken: Die hochenergetischen Elektronen aus dem Betazerfall ionisieren das Tritiumgas. Dadurch
|
||||
entsteht ein Plasma, das ein elektrostatisches Potential hat. Dieses Potential ändert die
|
||||
Energiedifferenz zwischen Zerfallselektronen und dem Detektor.
|
||||
</p>
|
||||
|
||||
<p>
|
||||
Für eine Neutrinomassenmessung mit höchstmöglicher Präzision ist es notwendig, dieses elektrostatische
|
||||
Potential zu bestimmen. Dazu müssen sowohl die molekularen und atomaren Prozesse, die zur Ionisation und
|
||||
Rekombination führen simuliert werden als auch das Plasma selber simuliert werden.
|
||||
</p>
|
||||
|
||||
</td>
|
||||
<td><img width="300" src="research/katrin_potential.png">
|
||||
<p>Elektrostatischs Potential in der WGTS. PiC-Simulation<br>
|
||||
<i>Image credit: Simulation of the KATRIN Source Plasma using Monte Carlo and Particle in Cell Methods,
|
||||
Dissertation, J. Kellerer, KIT Karlsruhe 2022 <a
|
||||
href="https://nbn-resolving.org/urn:nbn:de:101:1-2022033004594613326610">urn:nbn:de:101:1-2022033004594613326610</a>
|
||||
</i>
|
||||
</p>
|
||||
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
|
||||
<p><a href="research/neutrino.shtml">Mehr</a> </p>
|
||||
<!--#else -->
|
||||
|
||||
|
||||
@@ -261,7 +308,7 @@
|
||||
they emit electromagnetic emission over a wide energy range (from radio to gamma
|
||||
rays), their variability ranges from seconds to years and they are considered
|
||||
potential sources of high-energy protons and neutrinos.</p>
|
||||
|
||||
|
||||
<p>From the astronomical observations it is known that the central element of active
|
||||
galactic nuclei is a super massiveblack hole that serves as an engine for extremely
|
||||
fast plasma jets. In these plasma jets shock fronts can form in which particles are
|
||||
@@ -279,50 +326,66 @@
|
||||
Morphologies and Their Radio Emission (Richter and Spanier 2016 The Astrophysical Journal )</A>
|
||||
that allow for a morphological study of AGN.
|
||||
</p>
|
||||
<p>The aim of the research is to link the different observations (photons, neutrinos, possibly even protons and
|
||||
gravitational waves) with one another (so-called multi-messenger astronomy). In particular, the electromagnetic
|
||||
spectrum and its variability or even the structure of the jet should follow from the particle distribution in a
|
||||
self-consistent manner. <a href="research/agn.shtml">More</a></p>
|
||||
<p>The aim of the research is to link the different observations (photons, neutrinos, possibly even protons
|
||||
and
|
||||
gravitational waves) with one another (so-called multi-messenger astronomy). In particular, the
|
||||
electromagnetic
|
||||
spectrum and its variability or even the structure of the jet should follow from the particle
|
||||
distribution in a
|
||||
self-consistent manner. </p>
|
||||
</td>
|
||||
|
||||
<td><img width="300" src="research/m87-jet.jpg">
|
||||
<p>The active galactic nucleus M87 with its 10 kpc long jet.<br> <i>Image credit: NASA and the Hubble Heritage
|
||||
<p>The active galactic nucleus M87 with its 10 kpc long jet.<br> <i>Image credit: NASA and the Hubble
|
||||
Heritage
|
||||
Team (STScI/AURA)</i></p>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
<p><a href="research/agn.shtml">More</a></p>
|
||||
|
||||
<h3>Kinetic plasma physics</h3>
|
||||
<table>
|
||||
<tr>
|
||||
<td>
|
||||
<p>Plasma describes the state of an ionized gas in which there is a collective interaction. In the literature, plasma is
|
||||
also referred to as the fourth state of matter - even if this represents an extreme simplification. While plasmas
|
||||
<p>Plasma describes the state of an ionized gas in which there is a collective interaction. In the
|
||||
literature, plasma is
|
||||
also referred to as the fourth state of matter - even if this represents an extreme simplification.
|
||||
While plasmas
|
||||
occur on earth (lightning, fluorescent light bulbs, coating reactors, etc.), matter in a
|
||||
non-ionized state ultimately dominates. The situation is different in the rest of the universe: almost everywhere,
|
||||
non-ionized state ultimately dominates. The situation is different in the rest of the universe: almost
|
||||
everywhere,
|
||||
matter is in a plasma state. It is often read that 99% of all matter is in the form of plasma.
|
||||
</p>
|
||||
<p>
|
||||
The mathematical-physical description of plasmas is extremely diverse. From non-magnetized fluid plasmas to kinetic
|
||||
plasmas in strong magnetic fields, there are many types and descriptions of plasmas that are used in different
|
||||
The mathematical-physical description of plasmas is extremely diverse. From non-magnetized fluid plasmas
|
||||
to kinetic
|
||||
plasmas in strong magnetic fields, there are many types and descriptions of plasmas that are used in
|
||||
different
|
||||
areas.
|
||||
</p>
|
||||
<p>
|
||||
I mainly deal with the so-called kinetic plasmas - plasmas in which the distribution function of the particles is not
|
||||
Maxwell-Boltzmann, but an excess of particles exists at higher energies. Many astronomical objects (the sun, planets,
|
||||
I mainly deal with the so-called kinetic plasmas - plasmas in which the distribution function of the
|
||||
particles is not
|
||||
Maxwell-Boltzmann, but an excess of particles exists at higher energies. Many astronomical objects (the
|
||||
sun, planets,
|
||||
pulsars, active galaxy nuclei etc.) accelerate particles and thus produce kinetic plasmas.
|
||||
</p>
|
||||
<p>
|
||||
Using numerical methods (e.g. <a href="software/acronym.shtml">Particle-in-Cell</a>) I study how plasmas behave
|
||||
especially in the presence of nonthermal particle distributions. <a href="research/plasma.shtml">More</a>
|
||||
Using numerical methods (e.g. <a href="software/acronym.shtml">Particle-in-Cell</a>) I study how plasmas
|
||||
behave
|
||||
especially in the presence of nonthermal particle distributions.
|
||||
</p>
|
||||
</td>
|
||||
<td><img width="300" src="research/filamentation.png">
|
||||
<p>Magnetic flux tubes as they are produced by the filamentation instability.<br> <i>Image credit: T. Burkart, O. Elbracht, F. Spanier</i></p></td>
|
||||
<p>Magnetic flux tubes as they are produced by the filamentation instability.<br> <i>Image credit: T.
|
||||
Burkart, O. Elbracht, F. Spanier</i></p>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
|
||||
<p><a href="research/plasma.shtml">More</a></p>
|
||||
|
||||
|
||||
<h3>Turbulene</h3>
|
||||
@@ -330,25 +393,32 @@
|
||||
<table>
|
||||
<tr>
|
||||
<td>
|
||||
<p>Turbulence is known from the everyday life of liquids and gases. Although the equations behind (hydrodynamic)
|
||||
turbulence are simple, the theoretical description of turbulence is still not completely clear. In plasma physics,
|
||||
<p>Turbulence is known from the everyday life of liquids and gases. Although the equations behind
|
||||
(hydrodynamic)
|
||||
turbulence are simple, the theoretical description of turbulence is still not completely clear. In
|
||||
plasma physics,
|
||||
the equations become more complicated and those in plasmas all the more complex.
|
||||
</p>
|
||||
<p>
|
||||
The areas that I deal with include the investigation of turbulence in magnetized fluid plasma (magnetohydrodynamics,
|
||||
The areas that I deal with include the investigation of turbulence in magnetized fluid plasma
|
||||
(magnetohydrodynamics,
|
||||
cf. s. <A href="https://ui.adsabs.harvard.edu/abs/2012A&A...546A..51L">Evolution of
|
||||
plasma turbulence excited with particle beams (Lange and Spanier 2012 Astronomy and Astrophysics )</A>)) and
|
||||
the turbulence in the area of kinetic plasmas. The questions are: how the energy is distributed, how energy is
|
||||
transported across scales and what anisotropies look like (or in the case of kinetic turbulence, which wave modes
|
||||
plasma turbulence excited with particle beams (Lange and Spanier 2012 Astronomy and Astrophysics
|
||||
)</A>)) and
|
||||
the turbulence in the area of kinetic plasmas. The questions are: how the energy is distributed, how
|
||||
energy is
|
||||
transported across scales and what anisotropies look like (or in the case of kinetic turbulence, which
|
||||
wave modes
|
||||
play a
|
||||
role in turbulence).
|
||||
</p>
|
||||
<p> As in many other project I mainly employ numerical methods like the pseudospectral MHD solber <a
|
||||
href="software/gismo.shtml">GISMO</a> or particle-in-cell codes <a href="software/acronym.shtml">ACRONYM</a> aber auch analytische Methoden <A
|
||||
href="software/gismo.shtml">GISMO</a> or particle-in-cell codes <a
|
||||
href="software/acronym.shtml">ACRONYM</a> aber auch analytische Methoden <A
|
||||
href="https://ui.adsabs.harvard.edu/abs/2008arXiv0810.5059S">Three-wave interactions of dispersive
|
||||
plasma waves propagating parallel to the magnetic field (Spanier and Vainio 2008 arXiv e-prints
|
||||
)</A>.
|
||||
<a href="research/turbulence.shtml">More</a>
|
||||
|
||||
</p>
|
||||
</td>
|
||||
<td><img width="300" src="research/feldlinien.jpg">
|
||||
@@ -358,54 +428,63 @@
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
<p><a href="research/turbulence.shtml">More</a></p>
|
||||
|
||||
<h3>Cosmic ray transport</h3>
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<td>
|
||||
<p>Closely connected to turbulence research is the study of cosmic ray transport: Charged high energy particles
|
||||
in the heliosphere and the interstellar medium are interacting with turbulent magnetic fields. This interaction
|
||||
governs the transport parameters of particles. It is often assumed that the turbulent perturbations can be
|
||||
<p>Closely connected to turbulence research is the study of cosmic ray transport: Charged high energy
|
||||
particles
|
||||
in the heliosphere and the interstellar medium are interacting with turbulent magnetic fields. This
|
||||
interaction
|
||||
governs the transport parameters of particles. It is often assumed that the turbulent perturbations can
|
||||
be
|
||||
described as plasma waves.</p>
|
||||
<p>Already the simplest case of interaction (one particle with one wave) yields a very complicated analytical solution (<A
|
||||
href="https://ui.adsabs.harvard.edu/abs/2018JPlPh..84a9004S">Analytical treatment of particle motion
|
||||
<p>Already the simplest case of interaction (one particle with one wave) yields a very complicated
|
||||
analytical solution (<A href="https://ui.adsabs.harvard.edu/abs/2018JPlPh..84a9004S">Analytical
|
||||
treatment of particle motion
|
||||
in circularly polarized slab-mode wave fields (Schreiner, Vainio, and Spanier 2018 Journal of Plasma
|
||||
Physics )</A>). For this reason I use again numerical models to calculate transport parameters in different
|
||||
turbulence realisations.
|
||||
Physics )</A>). For this reason I use again numerical models to calculate transport parameters in
|
||||
different
|
||||
turbulence realisations.
|
||||
</p>
|
||||
<p>The incompressible MHD code <a href="software/gismo.shtml">GISMO</a> allows for the calculation of test particle
|
||||
tracks (<A
|
||||
href="https://ui.adsabs.harvard.edu/abs/2013A&A...553A.129L">Particle scattering in turbulent
|
||||
<p>The incompressible MHD code <a href="software/gismo.shtml">GISMO</a> allows for the calculation of test
|
||||
particle
|
||||
tracks (<A href="https://ui.adsabs.harvard.edu/abs/2013A&A...553A.129L">Particle scattering in
|
||||
turbulent
|
||||
plasmas with amplified wave modes (Lange, Spanier et al. 2013 Astronomy and Astrophysics )</A>).
|
||||
For dispersive wave modes simulations with <a href="software/acronym.shtml">ACRONYM</a>
|
||||
For dispersive wave modes simulations with <a href="software/acronym.shtml">ACRONYM</a>
|
||||
an (<A href="https://ui.adsabs.harvard.edu/abs/2014CoPhC.185.1981S">Wave-particle-interaction in kinetic
|
||||
plasmas (Schreiner and Spanier 2014 Computer Physics Communications )</A>
|
||||
, <A href="https://ui.adsabs.harvard.edu/abs/2017ApJ...834..161S">Particle Scattering off of
|
||||
Right-Handed Dispersive Waves (Schreiner, Kilian, and Spanier 2017 The Astrophysical Journal )</A>
|
||||
) can be performed. A major problem in analysing such test particle simulations is the derivation
|
||||
of transport parameters. A new method to derive quasi-linear parameters from nonlinear simulations
|
||||
has been developed. <A
|
||||
href="https://ui.adsabs.harvard.edu/abs/2016ApJ...833..223I">Determining Pitch-angle Diffusion
|
||||
has been developed. <A href="https://ui.adsabs.harvard.edu/abs/2016ApJ...833..223I">Determining
|
||||
Pitch-angle Diffusion
|
||||
Coefficients from Test Particle Simulations (Ivascenko, Lange, Spanier, and Vainio 2016 The
|
||||
Astrophysical Journal )</A>
|
||||
.
|
||||
</p>
|
||||
<p><a href="research/transport.shtml">Mehr</a>
|
||||
</p>
|
||||
|
||||
</td>
|
||||
<td><img width="300" src="research/rami.png">
|
||||
<p>Phase space diagram for wave-particle interaction<br>
|
||||
<i>Image credit: <A href="https://ui.adsabs.harvard.edu/abs/2018JPlPh..84a9004S">Analytical treatment of
|
||||
particle motion in circularly polarized slab-mode wave fields (Schreiner, Vainio, and Spanier
|
||||
2018 Journal of Plasma Physics )</A>
|
||||
</A></i></p>
|
||||
</A></i>
|
||||
</p>
|
||||
</td>
|
||||
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
<p><a href="research/transport.shtml">More</a>
|
||||
</p>
|
||||
|
||||
<h3>Shocks and particle acceleration</h3>
|
||||
<table>
|
||||
<tr>
|
||||
@@ -418,17 +497,19 @@
|
||||
href="https://ui.adsabs.harvard.edu/abs/2018ASSL..448..201B">Kinetic Simulations of Electron
|
||||
Acceleration at Mercury (Büchner, Kilian et al.} , 2018, Magnetic Fields in the Solar System )</A>
|
||||
) In active galactic nuclei shock fronts may be assumed, but in situ observation is impossible.
|
||||
Only through radiation modeling
|
||||
Only through radiation modeling
|
||||
(<A href="https://ui.adsabs.harvard.edu/abs/2016ApJ...829...56R">A Numerical Model of Parsec-scale SSC
|
||||
Morphologies and Their Radio Emission (Richter and Spanier 2016 The Astrophysical Journal )</A>
|
||||
) is it possible to verify certain acceleration models.
|
||||
</p>
|
||||
<p>I study shock acceleration scenario on a microphysical level <a href="software/acronym.shtml">Particle-in-Cell codes</a> aber
|
||||
<p>I study shock acceleration scenario on a microphysical level <a
|
||||
href="software/acronym.shtml">Particle-in-Cell codes</a> aber
|
||||
as well as on macrophysical level through <a href="software/unicorn.shtml">AGN modeling</a>.
|
||||
This is only possible using numerical models, in which new methods are also developed. (
|
||||
<A href="https://ui.adsabs.harvard.edu/abs/2018JCoPh.353..258K">Simulating the injection of magnetized
|
||||
plasma without electromagnetic precursor wave (Kilian and Spanier 2018 Journal of Computational
|
||||
Physics )</A>)</p>
|
||||
Physics )</A>)
|
||||
</p>
|
||||
|
||||
</td>
|
||||
<td><img width="300" src="research/particle_tracks.png">
|
||||
@@ -436,19 +517,56 @@
|
||||
<i>Image credit: Teilchenbeschleunigung an kollisionsfreien Schockfronten, Dissertation, P. Kilian, Uni
|
||||
Würzburg 2015 <a
|
||||
href="https://nbn-resolving.org/urn:nbn:de:bvb:20-opus-119023">urn:nbn:de:bvb:20-opus-119023</a>
|
||||
</i></p>
|
||||
|
||||
<p><a href="research/acceleration.shtml">Mehr</a>
|
||||
</i>
|
||||
</p>
|
||||
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
<p><a href="research/acceleration.shtml">More</a>
|
||||
</p>
|
||||
|
||||
|
||||
|
||||
<h3>Plasmapyhsics in neutrino experiments</h3>.
|
||||
<table>
|
||||
<tr>
|
||||
<td>
|
||||
<p>The measurement of neutrino mass is not possible directly, but various experiments attempt to determine it
|
||||
to determine it indirectly. One way to determine it is to determine the electron spectrum from
|
||||
beta decays. Fermi could already show the influence of the neutrino mass on the spectrum.
|
||||
</p>
|
||||
<p>
|
||||
In the KATRIN experiment, for example, a large tritium source is used, which yields a very large number of
|
||||
Tritium decays. This makes it possible to measure the spectrum in detail. But there is
|
||||
one catch: The high-energy electrons from the beta decay ionize the tritium gas. This
|
||||
creates a plasma that has an electrostatic potential. This potential changes the
|
||||
energy difference between decay electrons and the detector.
|
||||
</p>
|
||||
|
||||
<p>
|
||||
For a neutrino mass measurement with the highest possible precision, it is necessary to determine this electrostatic
|
||||
Potential to be determined. Dazu müssen sowohl die molekularen und atomaren Prozesse, die zur Ionisation und
|
||||
Rekombination führen simuliert werden als auch das Plasma selber simuliert werden.
|
||||
</p>
|
||||
|
||||
</td>
|
||||
<td><img width="300" src="research/katrin_potential.png">
|
||||
<p>Elektrostatischs Potential in der WGTS. PiC-Simulation<br>
|
||||
<i>Image credit: Simulation of the KATRIN Source Plasma using Monte Carlo and Particle in Cell Methods,
|
||||
Dissertation, J. Kellerer, KIT Karlsruhe 2022 <a
|
||||
href="https://nbn-resolving.org/urn:nbn:de:101:1-2022033004594613326610">urn:nbn:de:101:1-2022033004594613326610</a>
|
||||
</i>
|
||||
</p>
|
||||
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
<p><a href="research/neutrino.shtml">More</a> </p>
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -1,35 +1,109 @@
|
||||
|
||||
<!--#set var="rb_section" value="software" -->
|
||||
<!--#include virtual="../header_include.shtml" -->
|
||||
<!--#set var="title_de" value="Forschung - Beschleunigung" -->
|
||||
<!--#set var="title_en" value="Research - Acceleration" -->
|
||||
<!--#set var="autolocation" value="on" -->
|
||||
<!--#set var="location_de" value="fspanier" -->
|
||||
<!--#set var="location_en" value="fspanier" -->
|
||||
<!--#set var="rb_section" value="software" -->
|
||||
<!--#include virtual="../header_include.shtml" -->
|
||||
<!--#set var="title_de" value="Forschung - Beschleunigung" -->
|
||||
<!--#set var="title_en" value="Research - Acceleration" -->
|
||||
<!--#set var="autolocation" value="on" -->
|
||||
<!--#set var="location_de" value="fspanier" -->
|
||||
<!--#set var="location_en" value="fspanier" -->
|
||||
|
||||
|
||||
|
||||
<div id="ueberschrift">
|
||||
<!--#if expr="$language = de" -->
|
||||
<!--#if expr="$language = de" -->
|
||||
<h1>Forschung - Teilchenbeschleunigung</h1>
|
||||
<p>
|
||||
Die Beschleunigung kosmischer Strahlung ist ein komplexes Thema: Eine Vielzahl von Objekten im Universum
|
||||
beschleunigt
|
||||
Teilchen zu nichtthermischen Energien. Das geht von der Beschleunigung an Schocks im interstellaren Medium über die
|
||||
Beschleunigung an kompakten Objekten wie Pulsaren bis hin zu ausgedehnten Objekten wie Jets von Aktiven
|
||||
Galaxienkernen. Daher gibt es auch eine Vielzahl von Beschleunigungmechanismen
|
||||
</p>
|
||||
|
||||
<p>
|
||||
Einer der wichtigsten Mechanismen der in der Astrophysik diskutiert wird, ist die Fermibechleunigung an
|
||||
Schockfronten. Auch wenn der Mechanismus grundsätzlich seit Jahren bekannt ist, wird weiterhin an vielen Details
|
||||
geforscht. Z.B. an der Frage, wie Teilchen vorbeschleunigt werden oder wie sich die Schockfront durch die
|
||||
hochenergetischen Teilchen, die dort beschleunigt werden, verändert wird.
|
||||
</p>
|
||||
|
||||
<p>
|
||||
Mit <a href="../software/acronym.shtml">Particle-in-Cell</a> Simulationen versuchen wir z.B. herauszufinden, wie
|
||||
Teilchen an Schockfronten im Sonnenwind (<A href="https://ui.adsabs.harvard.edu/abs/2018ASSL..448..201B">Kinetic
|
||||
Simulations of Electron Acceleration at
|
||||
Mercury (Büchner, Kilian \emph{et al.} , 2018, Magnetic Fields in the Solar System )</A>) beschleunigt werden.
|
||||
Oder aber auch, wie sich überholende Schockfronten in Aktiven Galaxienkernen sich auf die Teilchenbeschleunigung
|
||||
auswirken (<A href="https://ui.adsabs.harvard.edu/abs/2018JCoPh.353..258K">Simulating the injection of magnetized
|
||||
plasma
|
||||
without
|
||||
electromagnetic precursor wave (Kilian and Spanier 2018 Journal of Computational Physics )</A>)
|
||||
</p>
|
||||
|
||||
<p>
|
||||
Ein anderer Ansatz ist die parametrisierte Betrachtung von Fermi-Beschleunigung in AGN-Strahlungsmodellen (<A
|
||||
href="https://ui.adsabs.harvard.edu/abs/2016ApJ...829...56R">A Numerical Model of Parsec-scale SSC Morphologies
|
||||
and
|
||||
Their Radio Emission (Richter and Spanier 2016 The Astrophysical Journal )</A>). Damit lässt sich zwar nicht
|
||||
klären, wie Beschleunigungsmechanismen funktionieren, allerdings kann man so herausfinden, wie die
|
||||
Strahlungssignaturen verschiedener Mechanismen aussehen.
|
||||
|
||||
</p>
|
||||
|
||||
|
||||
|
||||
<A href="https://ui.adsabs.harvard.edu/abs/2016ApJ...829...56R">A Numerical Model of Parsec-scale SSC Morphologies and Their Radio Emission (Richter and Spanier 2016 The Astrophysical Journal )</A>
|
||||
|
||||
<A href="https://ui.adsabs.harvard.edu/abs/2010ApJ...720.1318B">The Influence of the Mass Ratio on the Acceleration of Particles by Filamentation Instabilities (Burkart, Elbracht, Ganse, and Spanier 2010 The Astrophysical Journal )</A>
|
||||
|
||||
<A href="https://ui.adsabs.harvard.edu/abs/2018JPlPh..84a9004S">Analytical treatment of particle motion in circularly polarized slab-mode wave fields (Schreiner, Vainio, and Spanier 2018 Journal of Plasma Physics )</A>
|
||||
|
||||
<A href="https://ui.adsabs.harvard.edu/abs/2018JCoPh.353..258K">Simulating the injection of magnetized plasma without electromagnetic precursor wave (Kilian and Spanier 2018 Journal of Computational Physics )</A>
|
||||
|
||||
<A href="https://ui.adsabs.harvard.edu/abs/2018ASSL..448..201B">Kinetic Simulations of Electron Acceleration at Mercury (Büchner, Kilian \emph{et al.} , 2018, Magnetic Fields in the Solar System )</A>
|
||||
<p>
|
||||
Völlig andersartige Beschleunigungsmechanismen wie durch die Filamentierungsinstabilität (<A
|
||||
href="https://ui.adsabs.harvard.edu/abs/2010ApJ...720.1318B">The Influence of the Mass Ratio on the Acceleration
|
||||
of
|
||||
Particles by Filamentation Instabilities (Burkart, Elbracht, Ganse, and Spanier 2010 The Astrophysical Journal
|
||||
)</A>) lassen sich mittlerweile durch numerische Methoden ebenfalls gut erschließen.
|
||||
</p>
|
||||
|
||||
|
||||
|
||||
<!--#else -->
|
||||
<!--#else -->
|
||||
<h1>Research - Particle Acceleration</h1>
|
||||
<!--#endif -->
|
||||
|
||||
|
||||
|
||||
<p>
|
||||
The acceleration of cosmic rays is a complex topic: A large number of objects in the universe accelerate particles
|
||||
to non-thermal energies. This ranges from acceleration at shocks in the interstellar medium, to acceleration at
|
||||
compact objects such as pulsars, to extended objects such as jets from active galactic nuclei. Therefore, there is
|
||||
also a wide range of acceleration mechanisms
|
||||
</p>
|
||||
|
||||
<p>
|
||||
One of the most important mechanisms discussed in astrophysics is Fermi acceleration at shock fronts. Even though
|
||||
the mechanism has been known in principle for years, many details are still being are still being researched. For
|
||||
example, the question of how particles are pre-accelerated, or how the shock front is affected by the the shock
|
||||
front is changed by the high-energy particles that are accelerated there.
|
||||
</p>
|
||||
|
||||
<p>
|
||||
With <a href="../software/acronym.shtml">particle-in-cell</a> simulations, we try to find out, for example, how
|
||||
particles arrive at shock fronts in the solar wind (<A
|
||||
href="https://ui.adsabs.harvard.edu/abs/2018ASSL..448..201B">Kinetic
|
||||
Simulations of Electron Acceleration at
|
||||
Mercury (Büchner, Kilian \emph{et al.} , 2018, Magnetic Fields in the Solar System )</A>) are accelerated.
|
||||
Or how overtaking shock fronts in active galactic nuclei affect particle acceleration.
|
||||
(<A href="https://ui.adsabs.harvard.edu/abs/2018JCoPh.353..258K">Simulating the injection of magnetized plasma
|
||||
without electromagnetic precursor wave (Kilian and Spanier 2018 Journal of Computational Physics )</A>).
|
||||
</p>
|
||||
|
||||
<p>
|
||||
Another approach is the parameterised consideration of Fermi acceleration in AGN radiation models (<A
|
||||
href="https://ui.adsabs.harvard.edu/abs/2016ApJ...829...56R">A Numerical Model of Parsec-scale SSC Morphologies
|
||||
and Their Radio Emission (Richter and Spanier 2016 The Astrophysical Journal )</A>). While this does not clarify
|
||||
how acceleration mechanisms work, it does allow us to find out what the radiation signatures of different mechanisms
|
||||
look like.
|
||||
|
||||
</p>
|
||||
|
||||
|
||||
<p>
|
||||
Completely different acceleration mechanisms, such as those caused by filamentation instability (<A
|
||||
href="https://ui.adsabs.harvard.edu/abs/2010ApJ...720.1318B">The Influence of the Mass Ratio on the Acceleration
|
||||
of Particles by Filamentation Instabilities (Burkart, Elbracht, Ganse, and Spanier 2010 The Astrophysical Journal
|
||||
)</A>) can now also be readily inferred by numerical methods. </p>
|
||||
<!--#endif -->
|
||||
</div>
|
||||
|
||||
|
||||
@@ -43,4 +117,4 @@
|
||||
|
||||
|
||||
|
||||
<!--#include virtual="/share/after_include.shtml" -->
|
||||
<!--#include virtual="/share/after_include.shtml" -->
|
||||
|
After Width: | Height: | Size: 479 KiB |
|
After Width: | Height: | Size: 34 KiB |
|
After Width: | Height: | Size: 30 KiB |
|
After Width: | Height: | Size: 30 KiB |
@@ -0,0 +1,272 @@
|
||||
<!--#set var="rb_section" value="software" -->
|
||||
<!--#include virtual="../header_include.shtml" -->
|
||||
<!--#set var="title_de" value="Forschung - Beschleunigung" -->
|
||||
<!--#set var="title_en" value="Research - Acceleration" -->
|
||||
<!--#set var="autolocation" value="on" -->
|
||||
<!--#set var="location_de" value="fspanier" -->
|
||||
<!--#set var="location_en" value="fspanier" -->
|
||||
|
||||
|
||||
|
||||
<div id="ueberschrift">
|
||||
<!--#if expr="$language = de" -->
|
||||
<h1>Forschung - Neutrinos</h1>
|
||||
|
||||
|
||||
<p>
|
||||
Seit der Postulierung des Neutrinos im Jahr 1930 durch Pauli steht das Neutrino im Mittelpunkt der
|
||||
Untersuchungen in vielen Experimenten der Teilchen- und Astroteilchenphysik. Bislang werden Neutrinos am besten
|
||||
durch das Standardmodell beschrieben beschrieben, in dem sie als ladungsneutrale, masselose Fermionen
|
||||
beschrieben werden, die durch schwache Wechselwirkung in einem der drei verschiedenen leptonischen Eigenzustände
|
||||
entstehen. Allerdings haben die Experimente des Sudbury Neutrino Observatoriums und Super-Kamiokande zeigten
|
||||
jedoch, dass sich der leptonische Neutrino-Flavor während der Ausbreitung ändert. Dieser Effekt deutet darauf
|
||||
hin, dass Neutrinos mindestens drei zusätzliche Masseneigenzustände mit Massequadratunterschieden ungleich Null
|
||||
haben. Unterschieden haben. Damit haben die Experimente bewiesen, dass Neutrinos eine Masse ungleich Null haben,
|
||||
was dem Standardmodell widerspricht. Bis heute ist die absolute Masse noch unbestimmt und wird in verschiedenen
|
||||
Experimenten gesucht.
|
||||
</p>
|
||||
|
||||
<p>
|
||||
Neutrinomassenexperimente lassen sich in zwei konzeptionell unterschiedliche Kategorien einteilen: indirekte und
|
||||
direkte Ansätze. Bei der indirekten Suche wird die Neutrinomasse aus einem Modell abgeleitet, wobei das Modell
|
||||
selbst nicht vollständig bewiesen ist. Zu den indirekten Ansätzen gehören kosmologische Studien,
|
||||
Supernova-Neutrinomessungen und Messungen des neutrinolosen doppelten Betazerfalls. Bei der direkten Suche wird
|
||||
die Neutrinomasse direkt aus gut getesteten Modellen bestimmt. Zu den direkten Ansätzen gehört die Spektroskopie
|
||||
von Betazerfallselektronen.
|
||||
</p>
|
||||
|
||||
<p>
|
||||
Betazerfallsexperimente untersuchen die fehlende Energie, die vom Neutrino weggetragen wird, entweder beim
|
||||
Elektroneneinfangprozess oder dem Betazerfallsprozess. Die Berechnungen beruhen auf der Energie- und
|
||||
Impulserhaltung
|
||||
erhaltung. Es werden keine Annahmen über die spezifische Natur der Neutrinos gemacht. Daher können diese
|
||||
Methoden als
|
||||
als modellunabhängig betrachtet werden. Im Folgenden wird nur das Messprinzip des Betazerfalls beschrieben, da
|
||||
beide
|
||||
Methoden so grundlegend ähnlich sind.
|
||||
</p>
|
||||
|
||||
<figure>
|
||||
<img src="tritium_beta_decay.png" width=80% height=auto alt="Tritium beta decay spectrum" class="center">
|
||||
<figcaption>Skizze des Tritium-Zerfallsspektrum. Auf der linken Seite sieht man das volle Spektrum bis zum
|
||||
Endpunkt E<sub>0</sub>.Auf der rechten Seite wird die Endpunktsregion für verschiedene Neutrinomassen
|
||||
gezeigt. Abbildung nach C. Reiling</figcaption>
|
||||
</figure>
|
||||
|
||||
<p>
|
||||
Sowohl die Verzerrung als auch die Endpunktverschiebung können nachgewiesen werden, wenn die Ereignisrate im
|
||||
Endpunktbereich hoch genug ist und die Energieauflösung des Experiments hoch genug ist. Die Wahl der
|
||||
betazerfallenden Isotope hängt also von einer niedrigen Halbwertszeit und einer niedrigen Endpunktenergie ab.
|
||||
Die niedrige Halbwertszeit garantiert, dass bei einer vergleichsweise geringen Menge an Ausgangsmaterial
|
||||
genügend Statistik im Endpunktbereich vorhanden ist. Die niedrige Endpunktenergie sorgt dafür, dass der Einfluss
|
||||
auf das Spektrum vergleichsweise groß ist.
|
||||
</p>
|
||||
|
||||
<p>Tritium ist ein idealer Kandidat für Neutrinomassenexperimente. Es hat eine kurze Halbwertszeit von
|
||||
T<sub>1/2</sub>= 12.3
|
||||
Jahren und eine niedrige Endpunktenergie E<sub>0</sub>= 18.6 keV. Aufgrund dieser Eigenschaften wird Tritium in
|
||||
vielen Betazerfallsexperimenten und zuletzt im KATRIN-Experiment verwendet. Die KATRIN-Kollaboration konnte
|
||||
zeigen, dass die Elektronen-Antineutrino-Masse unter 1,1 eV liegt (Konfidenzniveau 90\%). Ziel des
|
||||
KATRIN-Experiments ist es jedoch, die Elektronen-Antineutrinomasse mit einer Empfindlichkeit von bis zu 0,2 eV
|
||||
zu messen. Dieses anspruchsvolle Ziel kann nur durch eine genaue Untersuchung aller systematischen Effekte des
|
||||
Experiments erreicht werden. Einer dieser Effekte wird durch ein Plasma in der leuchtstarken, fensterlosen,
|
||||
gasförmigen Tritiumquelle verursacht. Das Plasma wird durch Betazerfall, anschließende Ionisierung und
|
||||
Kollisionen mit dem umgebenden Tritiumgas erzeugt. Das Plasma erzeugt ein ab initio inhomogenes Potential in der
|
||||
gesamten Quelle, das die Form des gemessenen Elektronenspektrums verändern kann.
|
||||
</p>
|
||||
|
||||
<p>Das Plasma innerhalb der WGTS des KATRIN-Experiments ist in mehr als einer Hinsicht komplex:
|
||||
<ul>
|
||||
<li>Das Plasma hat einen starken Dichtegradienten</li>
|
||||
<li>Das Plasma ist im Zentrum stoßbestimmt und stoßfrei an den Rändern.</li>
|
||||
<li>Die Elektronenverteilung setzt sich aus einer thermischen und mehreren nicht-thermischen Komponenten
|
||||
zusammen</li>
|
||||
<li>Eine große Zahl verschiedener Spezies ist im Plasma vorhanden</li>
|
||||
<li>Die Plasmawandwechselwirkung ist nicht vollständig verstanden</li>
|
||||
</ul>
|
||||
</p>
|
||||
|
||||
<p>
|
||||
In meiner Gruppe wurde ein zweiteiliger Simulationsansatz entwickelt. Zunächst wird das Elektronenspektrum in
|
||||
Abhängigkeit von der Position in der Quelle durch ein neues Monte-Carlo-Simulationswerkzeug namens KARL neu
|
||||
bewertet. Damit werden die Wechselwirkungen von Elektronen und Ionen mit dem neutralen Gas bei einem gegebenen
|
||||
neutralen Gasstrom und statischen elektromagnetischen Feldern erfasst. Anschließend werden die Ergebnisse von
|
||||
KARL in Teilchen-in-Zellen-Simulationen mit einer modifizierten Version des <a
|
||||
href="../software/acronym.shtml">ACRONYM</a>-Simulationstools einbezogen. Dieses Tool berechnet
|
||||
elektrodynamische Felder aus gegebenen Eingaben, unter der Annahme, dass es keine direkten Kollisionen zwischen
|
||||
geladenen Teilchen gibt. Die Ergebnisse der ACRONYM-Simulationen können dann als Input für neue
|
||||
KARL-Simulationen verwendet werden. Es wird davon ausgegangen, dass die Iteration zwischen beiden
|
||||
Simulationswerkzeugen einen Gleichgewichtszustand erreicht.
|
||||
</p>
|
||||
|
||||
<p>Der KARL-Code umfasst verschiedene Prozesse der Ionisation, Rekombination und elastischen Streuung. Um die Dichte
|
||||
und Spektrum an verschiedenen Positionen in der Quelle zu messen, werden die Pertikel an verschiedenen
|
||||
Kontrollpunkten verfolgt. </p>
|
||||
|
||||
<figure>
|
||||
<img src="katrin_spectrum.png" width=80% height=auto alt="Particle densities as a function of position"
|
||||
class="center">
|
||||
<figcaption>Die Dichte der Elektronen und Ionen in der KATRIN-Quelle, berechnet mit dem KARL-Code. Die
|
||||
Simulationen wurden mit verschiedenen Einstellungen für das Rückwandpotential durchgeführt.</figcaption>
|
||||
</figure>
|
||||
|
||||
<p> Das Spektrum im Inneren der Quelle zeigt ein komplexes Verhalten: Die Elektronen werden entsprechend dem
|
||||
Fermi-Spektrum emittiert. Durch Wechselwirkungen mit dem umgebenden Tritiumgas und Ionen verlieren die
|
||||
Elektronen Energie, was zu einem nichtthermischen Leistungsgesetz führt. Nach einer großen Anzahl von
|
||||
elastischen Streuungen - hauptsächlich im Zentrum, wo die Gasdichte hoch ist - kühlen die Elektronen auf eine
|
||||
Maxwell-Verteilung ab.</p>
|
||||
|
||||
<figure>
|
||||
<img src="comparison_potential_regions.png" width=50% height=auto alt="Electrostatic potential in KATRIN"
|
||||
class="center">
|
||||
<figcaption>Elektrostatisches Potenzial über die gesamte KATRIN-Quelle aus ACRONYM-Simulationen.
|
||||
KARL-Simulationen der der Teilchenspektren werden als Input für die Plasmasimulationen verwendet.
|
||||
</figcaption>
|
||||
</figure>
|
||||
|
||||
<p>Teilchenspektren werden als Input für Plasmasimulationen mit dem <a
|
||||
href="../software/acronym.shtml">ACRONYM-Code</a> verwendet. Mit geeigneten Randbedingungen kann das
|
||||
Verhalten auf großen Skalen simuliert werden. Mit dem derzeitigen Aufbau sind numerische Experimente sehr
|
||||
rechenintensiv. We are currently working on making simulations more feasible using various approaches from
|
||||
pseudo-2D PiC simulations to 1D electrostatic Vlasov simulations.</p>
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<!--#else -->
|
||||
<h1>Research - Neutrinos</h1>
|
||||
|
||||
<p>
|
||||
Since the postulation of neutrinos in 1930 by Pauli the neutrino has been at the center of the investigation in
|
||||
many particle and astroparticle physics experiments. So far, neutrinos are best described by the standard model
|
||||
of particles, where they are specified as charge neutral, massless fermions, which are created by weak
|
||||
interaction in one of the three different leptonic eigenstates. However, the experiments of the Sudbury Neutrino
|
||||
Observatory and Super-Kamiokande showed that the leptonic neutrino flavor changes during propagation. This
|
||||
effect indicates that neutrinos have at least three additional mass eigenstates with non-zero mass-squared
|
||||
differences. Thus, the experiments proved that neutrinos have non-zero masses, contradicting the standard model.
|
||||
Until now, the absolute mass is still undetermined, and searched for in various experiments.
|
||||
</p>
|
||||
|
||||
<p>
|
||||
Neutrino mass experiments can be classified into two conceptually different categories: indirect and direct
|
||||
approaches. In the indirect search, the neutrino mass is inferred from a model, where the model itself is not
|
||||
fully proven. The indirect approaches include cosmological studies, supernova neutrino measurements and
|
||||
measurements of the neutrinoless double beta decay. In the direct search, the neutrino mass is determined
|
||||
directly from well tested models. The direct approaches includes the spectroscopy of beta decay electrons.
|
||||
</p>
|
||||
|
||||
<p>
|
||||
Beta decay experiments investigate the missing energy, which will be carried away by the neutrino, in either the
|
||||
electron capture process or the beta decay process. The calculations are based on energy and momentum
|
||||
conservation. No assumption is made on the specific nature of neutrinos. Thus, these methods can be considered
|
||||
as model independent. In the following, only the beta decay measurement principle will be described because both
|
||||
methods are so fundamentally similar.
|
||||
</p>
|
||||
|
||||
<figure>
|
||||
<img src="tritium_beta_decay.png" width=80% height=auto alt="Tritium beta decay spectrum" class="center">
|
||||
<figcaption>Sketch of Tritium beta decay spectrum. The left side shows the full spectrum up to the endpoint
|
||||
energy E<sub>0</sub>. The right side shows a close up of the endpoint region for two different neutrino mass
|
||||
cases. Figure adapted from C. Reiling</figcaption>
|
||||
</figure>
|
||||
|
||||
<p>
|
||||
The distortion as well as the endpoint shift can be detected, given a high enough event rate in the endpoint
|
||||
region as well as a high enough energy resolution of the experiment. Thus, the choice of beta decaying isotopes
|
||||
relies on a low half-life and a low endpoint energy. The low half-life guarantees that there is enough
|
||||
statistics in the endpoint region with a comparably small amount of source material. The low endpoint energy
|
||||
ensures that the influence on the spectrum is comparably large.
|
||||
</p>
|
||||
|
||||
<p>Tritium is an ideal candidate for neutrino mass measurements. It has a short half-life of T<sub>1/2</sub>= 12.3
|
||||
years and has a low endpoint energy of E<sub>0</sub>= 18.6 keV. Because of these properties, tritium is used in
|
||||
many beta decay experiments and most recently at the KATRIN experiment. The KATRIN collaboration could show that
|
||||
the electron antineutrino mass is below 1.1 eV (90\% confidence level). However, the KATRIN experiment aims to
|
||||
measure the electron antineutrino mass with a sensitivity down to 0.2 eV. This challenging goal can only be
|
||||
reached through a precise examination of all systematic effects of the experiment. One of these effects is
|
||||
caused by a plasma in the high luminous windowless gaseous tritium source. The plasma is generated by beta
|
||||
decay, subsequent ionization and collisions with surrounding tritium gas. The plasma produces an ab initio
|
||||
inhomogeneous potential throughout the source, which can change the shape of the measured electron spectrum.
|
||||
</p>
|
||||
|
||||
<p>The plasma inside the WGTS source of the KATRIN experiment is very intricate in many aspects
|
||||
<ul>
|
||||
<li>The plasma has a very strong density gradient</li>
|
||||
<li>The plasma is collisional in the center and collisionless at the edges</li>
|
||||
<li>The electron distribution has a Maxwellian part and several nonthermal components</li>
|
||||
<li>A large number of different species is present</li>
|
||||
<li>The interaction of the plasma with the walls </li>
|
||||
</ul>
|
||||
</p>
|
||||
|
||||
<p>
|
||||
In my group a two-part simulation approach was developed. First, the electron spectrum is reevaluated, dependent
|
||||
on the position in the source by a new Monte-Carlo simulation tool, named KARL. It will cover the interactions
|
||||
of electrons and ions with the neutral gas by a given neutral gas flow and static electromagnetic fields.
|
||||
Second, the results of KARL are then incorporated in particle-in-cell simulations with a modified version of the
|
||||
<a href="../software/acronym.shtml">ACRONYM</a> simulation tool. This tool will calculate electrodynamic fields
|
||||
from given input, assuming that there are no direct collisions between charged particles. Results of the
|
||||
ACRONYM simulations can then be used as an input for new KARL simulations. It is hypothesized that the
|
||||
iteration between both simulations tools will reach an equilibrium state.
|
||||
</p>
|
||||
|
||||
<p>The KARL code includes various processes from ionization, recombination and elastic scattering. In order to
|
||||
measure density and spectrum at different positions in the source perticles are tracked at different
|
||||
checkpoints. </p>
|
||||
|
||||
<figure>
|
||||
<img src="katrin_spectrum.png" width=80% height=auto alt="Particle densities as a function of position"
|
||||
class="center">
|
||||
<figcaption>The density of electrons and ions in the KATRIN source as calculated by the KARL code. Simulations
|
||||
have been performed with different settings for the rear wall potential.</figcaption>
|
||||
</figure>
|
||||
|
||||
<p> The spectrum inside the source shows a complex behaviour: Electrons are emitted according to the Fermi spectrum.
|
||||
Through interactions with the ambient tritium gas and ions the electrons lose energy leading to a nonthermal
|
||||
power-law. After a large number of elastic scattering events - mainly in the center where the gas density is
|
||||
high - electrons cool down to a Maxwell distribution.</p>
|
||||
|
||||
<figure>
|
||||
<img src="comparison_potential_regions.png" width=50% height=auto alt="Electrostatic potential in KATRIN"
|
||||
class="center">
|
||||
<figcaption>Electrostatic potential over the whole KATRIN source from ACRONYM simulations. KARL simulations of
|
||||
the particle spectra are used as input for the plasma simulations.</figcaption>
|
||||
</figure>
|
||||
|
||||
<p>Particle spectra are used as input for plasma simulations with the <a href="../software/acronym.shtml">ACRONYM
|
||||
code</a>. Using appropriate boundary conditions the behaviour on large scales can be simulated. With the
|
||||
current setup numerical experiments are computationally expensive. We are currently working on making
|
||||
simulations more feasible using various approaches from pseudo-2D PiC simulations to 1D electrostatic Vlasov
|
||||
simulations.</p>
|
||||
|
||||
|
||||
|
||||
|
||||
<!--#endif -->
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
<!--#if expr="$language = de" -->
|
||||
|
||||
<!--#else -->
|
||||
|
||||
|
||||
<!--#endif -->
|
||||
|
||||
|
||||
|
||||
<!--#include virtual="/share/after_include.shtml" -->
|
||||
@@ -1,20 +1,231 @@
|
||||
|
||||
<!--#set var="rb_section" value="research" -->
|
||||
<!--#include virtual="../header_include.shtml" -->
|
||||
<!--#set var="title_de" value="Forschung - Transport" -->
|
||||
<!--#set var="title_en" value="Research - Transport" -->
|
||||
<!--#set var="autolocation" value="on" -->
|
||||
<!--#set var="location_de" value="fspanier" -->
|
||||
<!--#set var="location_en" value="fspanier" -->
|
||||
<!--#set var="rb_section" value="research" -->
|
||||
<!--#include virtual="../header_include.shtml" -->
|
||||
<!--#set var="title_de" value="Forschung - Transport" -->
|
||||
<!--#set var="title_en" value="Research - Transport" -->
|
||||
<!--#set var="autolocation" value="on" -->
|
||||
<!--#set var="location_de" value="fspanier" -->
|
||||
<!--#set var="location_en" value="fspanier" -->
|
||||
|
||||
|
||||
|
||||
<div id="ueberschrift">
|
||||
<!--#if expr="$language = de" -->
|
||||
<h1>Forschung - Transport</h1>
|
||||
<!--#else -->
|
||||
<h1>Research - Transport</h1>
|
||||
<!--#endif -->
|
||||
<!--#if expr="$language = de" -->
|
||||
<h1>Forschung - Transport</h1>
|
||||
|
||||
<p>Kosmische Strahlung besteht aus geladenen Teilchen, die von verschiedenen Quellen im Universum emittiert werden -
|
||||
von der Sonne bis zu weit entfernten Aktiven Galaxienkernen. Dabei die Teilchen, meist Elektronen oder Protonen,
|
||||
Energien von etlichen keV im solaren Bereich bis zu 10<sup>20</sup> eV für extragalaktische Strahlung. Auf Grund
|
||||
der hohen Energie und der geringen Dichte des Hintergrunds interagieren diese Teilchen praktisch nicht durch
|
||||
Stöße, sondern nur durch Wechselwirkung mit magnetischen Störungen. Diese Störungen werden meist durch eine <a
|
||||
href="turbulence.shtml">Turbulenztheorie</a> beschrieben. Die Wechselwirkung der Teilchen selber wird durch
|
||||
die Transporttheorie beschrieben. </p>
|
||||
|
||||
<p>Eine analytische Beschreibung der Transporttheorie ist durch die nichtlineare Wechselwirkung extrem kompliziert
|
||||
und ist nur in bestimmten Grenzfällen erfolgreich. Eine sehr umfangreiche Darstellung findet sich im Buch
|
||||
"Cosmic Ray Astrophysics" von Reinhard Schlickeiser.<br>
|
||||
Ich habe analytische Theorien z.B. verwendet, um die Verteilung kosmischer Strahlung in elliptischen Galaxien zu
|
||||
beschreiben. (
|
||||
<A href="https://ui.adsabs.harvard.edu/abs/2008A&A...481....1H">Analytical view of diffusive and convective
|
||||
cosmic ray transport in elliptical galaxies (Hein and Spanier 2008 Astronomy and Astrophysics )</A>).
|
||||
Wie kompliziert die Interaktion von Plasmawellen mit kosmischer Strahlung tatsächlich ist, lässt sich sehr schön
|
||||
am Paper
|
||||
<A href="https://ui.adsabs.harvard.edu/abs/2018JPlPh..84a9004S">Analytical treatment of particle motion in
|
||||
circularly polarized slab-mode wave fields (Schreiner, Vainio, and Spanier 2018 Journal of Plasma Physics
|
||||
)</A> illustrieren: Alleine der Beweis, dass die Interaktion einer einzelnen Welle mit einem einzigen
|
||||
Teilchen integrabel ist, füllt mehrere Seiten.
|
||||
|
||||
</p>
|
||||
|
||||
|
||||
<p>Ein numerischer Ansatz, Teilchentransport zu beschreiben ist der Testteilchenansatz: Der turbulente Hintergrund
|
||||
des interplanetaren oder interstellaren Mediums wird simuliert und in die resultierenden Magnetfelder werden
|
||||
Testteilchen gesetzt, deren Bewegung verfolgt wird. In frühen Arbeiten habe ich dazu kompressible
|
||||
MHD-Simulationen verwendet (<A href="https://ui.adsabs.harvard.edu/abs/2011ASTRA...7...21S">Simulation of
|
||||
Charged Particle Diffusion in MHD
|
||||
plasmas (Spanier and Wisniewski 2011 Astrophysics and Space Sciences Transactions )</A>,
|
||||
<A href="https://ui.adsabs.harvard.edu/abs/2012ApJ...750..150W">Diffusion of Energetic Particles in Turbulent
|
||||
Magnetohydrodynamic Plasmas (Wisniewski, Spanier, and Kissmann 2012 The Astrophysical Journal )</A>).
|
||||
Allerdings ist es hier auf Grund der hohen numerischen Dissipation nicht möglich breite Wellenzahlbereich des
|
||||
Inertialbereichs der Turbulenz abzubilden.
|
||||
</p>
|
||||
|
||||
|
||||
<p>
|
||||
<table style="width:100%">
|
||||
<tr>
|
||||
<td>
|
||||
Daher wurde später der <a href="../software/gismo.shtml">GISMO</a>-Code verwendet. Dort wird die Physik
|
||||
von
|
||||
Alfven-Wellen abgebildet, was in großen Teilen des interstellaren Mediums eine realistische Darstellung
|
||||
ist. Ein
|
||||
wichtiger Aspekt der Forschung dabei ist die Frage, wie sich der Transport von Teilchen ändert durch die
|
||||
von
|
||||
Teilchen selbstgenerierte Turbulenz ( <A
|
||||
href="https://ui.adsabs.harvard.edu/abs/2012A&A...546A..51L">Evolution of plasma turbulence
|
||||
excited with
|
||||
particle beams (Lange and Spanier 2012 Astronomy and Astrophysics )</A>,
|
||||
<A href="https://ui.adsabs.harvard.edu/abs/2013A&A...553A.129L">Particle scattering in turbulent
|
||||
plasmas
|
||||
with amplified wave modes (Lange, Spanier \emph{et al.} 2013 Astronomy and Astrophysics )</A>).
|
||||
Unter <a href="turbulence.shtml">Turbulenz</a> wird darauf eingegangen. Für den Teilchentransport hat
|
||||
sich
|
||||
insbesondere gezeigt, dass der Transport durch Pseudo-Alfven-Wellen die Diffusion von Teilchen, die sich
|
||||
senkrecht zum Magnetfeld bewegen, deutlich verändert.
|
||||
|
||||
</td>
|
||||
<td style="width:30%">
|
||||
<img src="v35-small8-decay-Daa.jpg" width="100%"><br>
|
||||
<p style="font-style: italic; text-align:center"> <i>Diffusionskoeffizient für Streuung an
|
||||
selbstgenerierter Turbulenz. Auffällig ist die Starke Streuung für senkrecht laufende Teilchen.
|
||||
Quelle:<A href="https://ui.adsabs.harvard.edu/abs/2013A&A...553A.129L">Particle scattering
|
||||
in turbulent plasmas
|
||||
with amplified wave modes (Lange, Spanier \emph{et al.} 2013 Astronomy and Astrophysics
|
||||
)</A></i></p>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
</p>
|
||||
|
||||
|
||||
<p>Neuere Forschung schließen den Transport an dispersiven Moden (hier Whistler-Moden) ein. Dies lässt sich mit
|
||||
einem MHD-Modell nicht mehr darstellen, deswegen wird ein <a
|
||||
href="../software/acronym.shtml">Particle-in-Cell</a> Code verwendet (<A
|
||||
href="https://ui.adsabs.harvard.edu/abs/2017ApJ...834..161S">Particle Scattering off of Right-Handed
|
||||
Dispersive Waves (Schreiner, Kilian, and Spanier 2017 The Astrophysical Journal )</A>). Dies ist eine
|
||||
wichtige Vorarbeit, um den Teilchentransport in kinetischer Turbulenz zu simulieren (<A
|
||||
href="https://ui.adsabs.harvard.edu/abs/2014CoPhC.185.1981S">Wave-particle-interaction in kinetic plasmas
|
||||
(Schreiner and Spanier 2014 Computer Physics Communications )</A>).
|
||||
</p>
|
||||
|
||||
|
||||
|
||||
<p> Ein zentrales Problem bei der Analyse von Testteilchemodellen ist, dass Streukoeffizienten eigentlich nur für
|
||||
die quasilineare Theorie wohldefiniert sind. In Testteilchen-Simulationen ändert sich aber Richtung und Impuls
|
||||
von Teilchen. Damit schwindet die Aussagekraft von Simulationen mit zunehmender Laufzeit. Gleichzeitig benötigt
|
||||
man lange Laufzeiten um konvergente Ergebnisse zu erzielen. Wir haben einen neuen Ansatz zur Analyse von
|
||||
Testteilchensimulationen entwickelt, der nicht mehr auf der Betrachtung von Einzelteilchen, sondern auf der
|
||||
zeitlichen Entwicklung von Verteilungsfunktionen fusst. (<A
|
||||
href="https://ui.adsabs.harvard.edu/abs/2016ApJ...833..223I">Determining Pitch-angle Diffusion Coefficients
|
||||
from Test Particle Simulations (Ivascenko, Lange, Spanier, and Vainio 2016 The Astrophysical Journal )</A>)
|
||||
|
||||
</p>
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<!--#else -->
|
||||
<h1>Research - Transport</h1>
|
||||
|
||||
|
||||
<p>Cosmic radiation consists of charged particles emitted from various sources in the universe - from the sun to
|
||||
distant active galactic nuclei. from the Sun to distant active galactic nuclei. In the process, the particles,
|
||||
mostly electrons or protons, have energies ranging from several keV in the solar range to 10<sup>20</sup> eV for
|
||||
extragalactic radiation. Due to the high energy and low density of the background, these particles do not
|
||||
interact by collisions but only by collisions, but only by interacting with magnetic perturbations. These
|
||||
disturbances are usually caused by a <a href="turbulence.shtml">turbulence theory</a>. The interaction of the
|
||||
particles themselves is described by transport theory. </p>
|
||||
|
||||
<p>An analytical description of the transport theory is extremely complicated due to the non-linear interaction and
|
||||
is only successful in certain limiting cases. A very comprehensive account can be found in the book. "Cosmic Ray
|
||||
Astrophysics" by Reinhard Schlickeiser.<br>
|
||||
I have used analytical theories, for example, to describe the distribution of cosmic rays in elliptical
|
||||
galaxies. ( <A href="https://ui.adsabs.harvard.edu/abs/2008A&A...481....1H">Analytical view of diffusive and
|
||||
convective cosmic ray transport in elliptical galaxies (Hein and Spanier 2008 Astronomy and Astrophysics
|
||||
)</A>). The complexity of the interaction of plasma waves with cosmic rays is nicely illustrated by the
|
||||
paper <A href="https://ui.adsabs.harvard.edu/abs/2018JPlPh..84a9004S">Analytical treatment of particle motion in
|
||||
circularly polarised slab-mode wave fields (Schreiner, Vainio, and Spanier 2018 Journal of Plasma Physics
|
||||
)</A>: The proof alone that the interaction of a single wave with a single particle is integrable fills
|
||||
several pages.
|
||||
|
||||
</p>
|
||||
|
||||
|
||||
|
||||
<p>A numerical approach to describe particle transport is the test particle approach: The turbulent background of
|
||||
the interplanetary or interstellar medium is simulated and test particles are placed in the resulting magnetic
|
||||
fields and their motion is tracked. In early work, I used compressible MHD simulations for this purpose (<A
|
||||
href="https://ui.adsabs.harvard.edu/abs/2011ASTRA...7...21S">Simulation of
|
||||
Charged Particle Diffusion in MHD
|
||||
plasmas (Spanier and Wisniewski 2011 Astrophysics and Space Sciences Transactions )</A>,
|
||||
<A href="https://ui.adsabs.harvard.edu/abs/2012ApJ...750..150W">Diffusion of Energetic Particles in Turbulent
|
||||
Magnetohydrodynamic Plasmas (Wisniewski, Spanier, and Kissmann 2012 The Astrophysical Journal )</A>).
|
||||
However, due to the high numerical dissipation, it is not possible here to obtain a wide wavenumber range of the
|
||||
inertial range of the turbulence.
|
||||
inertial range of the turbulence.
|
||||
</p>
|
||||
|
||||
|
||||
<p>
|
||||
<table style="width:100%">
|
||||
<tr>
|
||||
<td>
|
||||
Therefore, the <a href="../software/gismo.shtml">GISMO</a> code was used later. There the physics
|
||||
of
|
||||
Alfven waves, which is a realistic representation in large parts of the interstellar medium.
|
||||
in large parts of the interstellar medium. One
|
||||
important aspect of the research here is the question of how the transport of particles is changed by
|
||||
the
|
||||
of
|
||||
particles' self-generated turbulence ( <A
|
||||
href="https://ui.adsabs.harvard.edu/abs/2012A&A...546A..51L">evolution of plasma turbulence
|
||||
excited with
|
||||
particle beams (Lange and Spanier 2012 Astronomy and Astrophysics )</A>,
|
||||
<A href="https://ui.adsabs.harvard.edu/abs/2013A&A...553A.129L">Particle scattering in turbulent
|
||||
plasmas
|
||||
with amplified wave modes (Lange, Spanier \emph{et al.} 2013 Astronomy and Astrophysics )</A>).
|
||||
See <a href="turbulence.shtml">Turbulence</a> for a discussion of this. For particle transport, in
|
||||
particular, it has been shown that transport by pseudo-Alfven waves significantly alters the diffusion
|
||||
of particles moving perpendicular to the magnetic field.
|
||||
|
||||
</td>
|
||||
<td style="width:30%">
|
||||
<img src="v35-small8-decay-Daa.jpg" width="100%"><br>
|
||||
<p style="font-style: italic; text-align:centre"> <i>Diffusion coefficient for scattering from
|
||||
self-generated turbulence. The strong scattering for vertically moving particles is striking.
|
||||
Source:<A href="https://ui.adsabs.harvard.edu/abs/2013A&A...553A.129L">Particle scattering
|
||||
in turbulent plasmas with amplified wave modes (Lange, Spanier \emph{et al.} 2013 Astronomy
|
||||
and Astrophysics
|
||||
)</A></i></p>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
</p>
|
||||
|
||||
|
||||
<p>Newer research includes transport at dispersive modes (here Whistler modes). This can no longer be MHD model, so
|
||||
a <a href="../software/acronym.shtml">particle-in-cell</a> code is used (<A
|
||||
href="https://ui.adsabs.harvard.edu/abs/2017ApJ...834..161S">Particle Scattering off of Right-Handed
|
||||
Dispersive Waves (Schreiner, Kilian, and Spanier 2017 The Astrophysical Journal )</A>). This is an important
|
||||
preliminary work to simulate particle transport in kinetic turbulence (<A
|
||||
href="https://ui.adsabs.harvard.edu/abs/2014CoPhC.185.1981S">Wave-particle-interaction in kinetic plasmas
|
||||
(Schreiner and Spanier 2014 Computer Physics Communications )</A>).
|
||||
</p>
|
||||
|
||||
|
||||
|
||||
<p>A central problem in the analysis of test-particle models is that scattering coefficients are actually
|
||||
well-defined only for quasilinear theory. In test particle simulations, however, the direction and momentum of
|
||||
particles changes. This means that the validity of simulations diminishes with increasing runtime. At the same
|
||||
time, long runtimes are needed to obtain convergent results. We have developed a new approach to the analysis of
|
||||
test particle simulations that is no longer based on the consideration of individual particles but on the
|
||||
temporal evolution of distribution functions. (<A
|
||||
href="https://ui.adsabs.harvard.edu/abs/2016ApJ...833..223I">Determining Pitch-angle Diffusion Coefficients
|
||||
from Test Particle Simulations (Ivascenko, Lange, Spanier, and Vainio 2016 The Astrophysical Journal )</A>)
|
||||
|
||||
</p>
|
||||
|
||||
|
||||
|
||||
|
||||
<!--#endif -->
|
||||
</div>
|
||||
|
||||
|
||||
@@ -23,39 +234,6 @@
|
||||
|
||||
|
||||
|
||||
<A href="https://ui.adsabs.harvard.edu/abs/2012A&A...546A..51L">Evolution of plasma turbulence excited with particle beams (Lange and Spanier 2012 Astronomy and Astrophysics )</A>
|
||||
|
||||
<A href="https://ui.adsabs.harvard.edu/abs/2011ASTRA...7...21S">Simulation of Charged Particle Diffusion in MHD plasmas (Spanier and Wisniewski 2011 Astrophysics and Space Sciences Transactions )</A>
|
||||
|
||||
<A href="https://ui.adsabs.harvard.edu/abs/2008A&A...481....1H">Analytical view of diffusive and convective cosmic ray transport in elliptical galaxies (Hein and Spanier 2008 Astronomy and Astrophysics )</A>
|
||||
|
||||
<A href="https://ui.adsabs.harvard.edu/abs/2012ApJ...750..150W">Diffusion of Energetic Particles in Turbulent Magnetohydrodynamic Plasmas (Wisniewski, Spanier, and Kissmann 2012 The Astrophysical Journal )</A>
|
||||
|
||||
<A href="https://ui.adsabs.harvard.edu/abs/2013A&A...553A.129L">Particle scattering in turbulent plasmas with amplified wave modes (Lange, Spanier \emph{et al.} 2013 Astronomy and Astrophysics )</A>
|
||||
|
||||
<A href="https://ui.adsabs.harvard.edu/abs/2017ApJ...834..161S">Particle Scattering off of Right-Handed Dispersive Waves (Schreiner, Kilian, and Spanier 2017 The Astrophysical Journal )</A>
|
||||
|
||||
<A href="https://ui.adsabs.harvard.edu/abs/2014CoPhC.185.1981S">Wave-particle-interaction in kinetic plasmas (Schreiner and Spanier 2014 Computer Physics Communications )</A>
|
||||
|
||||
<A href="https://ui.adsabs.harvard.edu/abs/2014A&A...564A..15G">Fundamental and harmonic plasma emission in different plasma environments (Ganse, Kilian, Spanier, and Vainio 2014 Astronomy and Astrophysics )</A>
|
||||
|
||||
<A href="https://ui.adsabs.harvard.edu/abs/2013JPlPh..79..597W">Turbulence evolution in MHD plasmas (Wisniewski, Kissmann, Spanier, and Spanier 2013 Journal of Plasma Physics )</A>
|
||||
|
||||
<A href="https://ui.adsabs.harvard.edu/abs/2018AN....339..331G">Decomposing blazar spectra into lepto-hadronic emission components (Gokus, Richter \emph{et al.} 2018 Astronomische Nachrichten )</A>
|
||||
|
||||
<A href="https://ui.adsabs.harvard.edu/abs/2016ApJ...833..223I">Determining Pitch-angle Diffusion Coefficients from Test Particle Simulations (Ivascenko, Lange, Spanier, and Vainio 2016 The Astrophysical Journal )</A>
|
||||
|
||||
<A href="https://ui.adsabs.harvard.edu/abs/2015APh....61..102R">Multi-band implications of external-IC flares (Richter and Spanier 2015 Astroparticle Physics )</A>
|
||||
|
||||
<A href="https://ui.adsabs.harvard.edu/abs/2010ApJ...720.1318B">The Influence of the Mass Ratio on the Acceleration of Particles by Filamentation Instabilities (Burkart, Elbracht, Ganse, and Spanier 2010 The Astrophysical Journal )</A>
|
||||
|
||||
<A href="https://ui.adsabs.harvard.edu/abs/2008arXiv0810.5059S">Three-wave interactions of dispersive plasma waves propagating parallel to the magnetic field (Spanier and Vainio 2008 arXiv e-prints )</A>
|
||||
|
||||
<A href="https://ui.adsabs.harvard.edu/abs/2018JPlPh..84a9004S">Analytical treatment of particle motion in circularly polarized slab-mode wave fields (Schreiner, Vainio, and Spanier 2018 Journal of Plasma Physics )</A>
|
||||
|
||||
|
||||
|
||||
|
||||
<!--#if expr="$language = de" -->
|
||||
|
||||
<!--#else -->
|
||||
@@ -65,4 +243,4 @@
|
||||
|
||||
|
||||
|
||||
<!--#include virtual="/share/after_include.shtml" -->
|
||||
<!--#include virtual="/share/after_include.shtml" -->
|
||||
|
After Width: | Height: | Size: 16 KiB |
@@ -21,17 +21,14 @@
|
||||
<!--#if expr="$language = de" -->
|
||||
|
||||
<p>Turbulenz spielt in vielen Bereichen der Astro- und Weltraumphysik eine wichtige Rolle. Auf großen Skalen ist
|
||||
Turbulenz
|
||||
wichtig für die Sternentstehung, auf kleineren Skalen trägt Turbulenz zur Strukturbildung und Heizung bei. Auch beim
|
||||
Transport kosmischer Strahlung ist Turbulenz eine zentrale Komponente.</p>
|
||||
Turbulenz wichtig für die Sternentstehung, auf kleineren Skalen trägt Turbulenz zur Strukturbildung und Heizung bei.
|
||||
Auch beim Transport kosmischer Strahlung ist Turbulenz eine zentrale Komponente.</p>
|
||||
|
||||
<p>In der Hydrodynamik ist Turbulenz auch nach sehr langer Zeit in weiten Teilen unverstanden, zumindest existiert dort
|
||||
aber mit der Kolmogorov-Theorie eine Beschreibung, die zumindest die Energiespektren der Turbulenz gut erklärt. In
|
||||
der
|
||||
Astrophysik geht es allerdings um Plasmaturbulenz auf Längenskalen, die mehrere Größenordnungen umfassen. Dabei
|
||||
kommen
|
||||
verschiedene Plasmabeschreibungen von der Magnetohydrodynamik über Hybridmodelle bis zu kinetischen Modellen zum
|
||||
Tragen.</p>
|
||||
der Astrophysik geht es allerdings um Plasmaturbulenz auf Längenskalen, die mehrere Größenordnungen umfassen. Dabei
|
||||
kommen verschiedene Plasmabeschreibungen von der Magnetohydrodynamik über Hybridmodelle bis zu kinetischen Modellen
|
||||
zum Tragen.</p>
|
||||
|
||||
<p>Für inkompressible magnetohydrodynamische Plasmen gibt es die Theorie von Goldreich&Sridhar, die vorhersagt, dass
|
||||
die Energiespektren einen ähnlichen Index haben wie in der Kolmogorov-Theorie (also 5/3), aber der Energietransport
|
||||
@@ -107,74 +104,71 @@
|
||||
star formation, on smaller scales turbulence contributes to structure formation and plasma heating. Especially for
|
||||
the transport of cosmic rays turbulence plays a vital role.</p>
|
||||
|
||||
<p>In der Hydrodynamik ist Turbulenz auch nach sehr langer Zeit in weiten Teilen unverstanden, zumindest existiert dort
|
||||
aber mit der Kolmogorov-Theorie eine Beschreibung, die zumindest die Energiespektren der Turbulenz gut erklärt. In
|
||||
der
|
||||
Astrophysik geht es allerdings um Plasmaturbulenz auf Längenskalen, die mehrere Größenordnungen umfassen. Dabei
|
||||
kommen
|
||||
verschiedene Plasmabeschreibungen von der Magnetohydrodynamik über Hybridmodelle bis zu kinetischen Modellen zum
|
||||
Tragen.</p>
|
||||
<p> Turbulence in the context of hydrodynamics is still not well understood after very long time, but at least the
|
||||
Kolmogorov theory exists which allows to understand energy spectra of turbulence. Turbulence in the context of
|
||||
astrophyics however is plasma turbulence on lengt scales spanning many orders of magnitude. This means that various
|
||||
plasma descriptions from magnetohydrodynamics and hybrid models to kinetic models have to be used.</p>
|
||||
|
||||
<p>Für inkompressible magnetohydrodynamische Plasmen gibt es die Theorie von Goldreich&Sridhar, die vorhersagt, dass
|
||||
die Energiespektren einen ähnlichen Index haben wie in der Kolmogorov-Theorie (also 5/3), aber der Energietransport
|
||||
senkrecht zu den Magnetfeldlinien stattfindet - bis es zu einer kritischen Balance kommt.</p>
|
||||
<p> For incompressible nagnetohydrodynamic plasmas, there is the theory of Goldreich&Sridhar, which predicts that
|
||||
the energy spectra have a similar index as in Kolmogorov theory (i.e. 5/3), but the energy transport takes place
|
||||
perpendicular to the magnetic field lines - until a critical balance occurs.</p>
|
||||
|
||||
<p>Wie sich die Goldreich-Sridhar-Theorie auf Plasmen auswirkt, in denen Energie durch Teilchen injiziert wird, wurde in
|
||||
<p>How the Goldreich-Sridhar theory affects plasmas in which energy is injected by particles was discussed in
|
||||
<A href="https://ui.adsabs.harvard.edu/abs/2012A&A...546A..51L">Evolution of plasma turbulence excited with
|
||||
particle
|
||||
beams (Lange and Spanier 2012 Astronomy and Astrophysics )</A> untersucht. Dazu wurde der <a
|
||||
href="../software/gismo.shtml">GISMO-Code</a> verwendet, es wurde also die Entwicklung im Bereich der
|
||||
Magnetohydrodynamik untersucht. Dabei zeigt sich, dass
|
||||
hochenergetische Protonen Wellen in Plasmen anregen, die Energie sich aber tatsächlich so ausbreitet, wie von
|
||||
Goldreich und Sridhar vorhergesagt wurde - senkrecht zur Magnetfeldlinie zuerst.
|
||||
beams (Lange and Spanier 2012 Astronomy and Astrophysics )</A>. For this purpose, the <a
|
||||
href="../software/gismo.shtml">GISMO code</a> was used , i.e. the evolution in the field of magnetohydrodynamics
|
||||
was investigated. This shows that
|
||||
high-energy protons excite waves in plasmas, but the energy actually propagates as predicted by Goldreich and
|
||||
Sridhar - perpendicular to the magnetic field line first.
|
||||
</p>
|
||||
|
||||
<p>
|
||||
<img width="500" src="lange-goldreichsridhar.png"><br>
|
||||
Energietransport in inkompressiblen Plasmen: Bei k=24 wird Energie durch strömende Protonen injiziert. Die Energie
|
||||
wird senkrecht zum Magnetfeld transportiert und später - nach Erreichen der kritischen Balance - auch parallel.
|
||||
<i>Aus: <A href="https://ui.adsabs.harvard.edu/abs/2012A&A...546A..51L">Evolution of plasma turbulence excited
|
||||
Energy transport in incompressible plasmas: At k=24, energy is injected by flowing protons. The energy is
|
||||
transported perpendicular to the magnetic field and later - after reaching the critical balance - also parallel.
|
||||
<i>From: <A href="https://ui.adsabs.harvard.edu/abs/2012A&A...546A..51L">Evolution of plasma turbulence excited
|
||||
with
|
||||
particle
|
||||
beams (Lange and Spanier 2012 Astronomy and Astrophysics )</A></i>
|
||||
</p>
|
||||
|
||||
<p>Wenn man statt inkompressiblen MHD-Plasmen den kompressiblen Fall betrachtet, stellt man fest, dass sowohl der
|
||||
Energietransport als auch die Spektren fundamental anders aussehen. In
|
||||
<p>If one considers the compressible case instead of incompressible MHD plasmas, one finds that both the energy
|
||||
transport as well as the spectra look fundamentally different. In
|
||||
<A href="https://ui.adsabs.harvard.edu/abs/2013JPlPh..79..597W">Turbulence evolution in MHD plasmas (Wisniewski,
|
||||
Kissmann, Spanier, and Spanier 2013 Journal of Plasma Physics )</A>
|
||||
wurde dies im Detail untersucht. Es ist dabei nicht unerwartet, dass tatsächlich eine mehr oder minder isotrope
|
||||
Energieausbreitung stattfindet. Allerdings zeigt sich auch, dass die Kompressibilität eine weitaus größere
|
||||
Abhängigkeit von den Parametern darstellt.
|
||||
this has been studied in detail. It is not unexpected that there is indeed a more or less isotropic energy
|
||||
energy propagation takes place. However, it also shows that the compressibility is a much greater
|
||||
dependence on the parameters.
|
||||
</p>
|
||||
|
||||
|
||||
<p>
|
||||
Meine aktuelle Forschung beschäftigt sich sehr stark mit Turbulenz im kinetischen Bereich - also auf Längenskalen,
|
||||
bei denen die Stöße zwischen Teilchen des Plasmas keine Rolle mehr spielen. In diesen Bereichen spielt die
|
||||
Wechselwirkung einzelner Plasmawellen eine wichtige Rolle. Wie in
|
||||
My current research is very much concerned with turbulence in the kinetic range - that is, on length scales,
|
||||
where the collisions between particles in the plasma no longer play a role. In these areas, the
|
||||
interaction of individual plasma waves plays an important role. As shown in
|
||||
<A href="https://ui.adsabs.harvard.edu/abs/2008arXiv0810.5059S">Three-wave interactions of dispersive plasma waves
|
||||
propagating parallel to the magnetic field (Spanier and Vainio 2008 arXiv e-prints )</A>
|
||||
beschrieben, wird diese Interaktion für dispersive Wellen, wie man sie jenseits der Protonengyrofrequenz findet,
|
||||
sehr kompliziert. Auch die Wellendämpfung (
|
||||
this interaction becomes very complicated for dispersive waves such as those found beyond the proton gyrofrequency,
|
||||
very complicated. Also, the wave damping (
|
||||
<A href="https://ui.adsabs.harvard.edu/abs/2017CCoPh..21..947S">Recovering the Damping Rates of Cyclotron Damped
|
||||
Plasma
|
||||
Waves from Simulation Data (Schreiner, Kilian, and Spanier 2017 Communications in Computational Physics )</A>
|
||||
) ist erheblich komplizierter.
|
||||
) is considerably more complicated.
|
||||
</p>
|
||||
|
||||
|
||||
<p>Mit <a href="../software/acronym.shtml">Particle-in-Cell Codes</a> ist es möglich, die Turbulenz im kinetischen
|
||||
Bereich im Detail zu untersuchen. Auch wenn die Technik relativ einfach verständlich ist, ist der numerische Aufwand
|
||||
dennoch extrem groß: Turbulenz ist ein Phänomen, dass auf vielen Größenskalen stattfindet, PiC-Codes erfordern aber
|
||||
gleichzeitig eine Auflösung der kleinsten Skalen. Entsprechend groß ist der numerische Aufwand.</p>
|
||||
<p> With <a href="../software/acronym.shtml">Particle-in-Cell Codes</a> it is possible to investigate turbulence in the
|
||||
kinetic range in detail. Even though the technique is relatively easy to understand, the numerical effort is
|
||||
nevertheless extremely large: turbulence is a phenomenon that takes place on many size scales, but PiC codes require
|
||||
a resolution of the smallest scales at the same time. The numerical effort is correspondingly large.</p>
|
||||
|
||||
|
||||
<p>
|
||||
<img width="500" src="cschreiner-gary.png"><br>
|
||||
Kinetische Simulation von Turbulenz: Energie wird bei kleinsten Skalen injiziert und breitet sich auch hier
|
||||
senkrecht aus. Der Unteschied zum oben gezeigten Bild ist dies eine kinetische Simulation. Dementsprechend werden
|
||||
hier auch dispersive Wellenmoden berücksichtigt.
|
||||
Kinetic simulation of turbulence: Energy is injected at the smallest scales and also spreads out vertically here.
|
||||
The difference to the image shown above is that this is a kinetic simulation. Accordingly, dispersive wave modes are
|
||||
also considered here.
|
||||
</p>
|
||||
|
||||
|
||||
|
||||
|
After Width: | Height: | Size: 66 KiB |
@@ -21,33 +21,137 @@
|
||||
|
||||
<!--#if expr="$language = de" -->
|
||||
<h3>Vorlesungen:</h3>
|
||||
<p>Wintersemester 2020/2021 (wahrscheinlich per online Videokonferenz):<br>
|
||||
<a href="lectures/cosmicray_2020ws/index.shtml">Astrophysik der Kosmischen Strahlung (WS 20/21)</a>
|
||||
<p>Sommersemester 2024:<br>
|
||||
<a href="lectures/pycourse/index.shtml">Python for scientists</a>
|
||||
</p>
|
||||
<!--#else -->
|
||||
<h3>Lectures:</h3>
|
||||
<p>Winter semester 2020/2021 (likely by online webconference):<br>
|
||||
<a href="lectures/cosmicray_2020ws/index.shtml">Cosmic ray astrophysics (WS 20/21)</a>
|
||||
<p>Summer semester 2024<br>
|
||||
<a href="lectures/pycourse/index.shtml">Python for scientists</a>
|
||||
</p>
|
||||
<!--#endif -->
|
||||
|
||||
<!--#if expr="$language = de" -->
|
||||
Vorherige Semester:
|
||||
|
||||
|
||||
|
||||
|
||||
<ul>
|
||||
<li>Sommersemester 2020 (wahrscheinlich per online Videokonferenz):</li>
|
||||
</li> <li>Sommersemester 204
|
||||
<ul>
|
||||
<li>
|
||||
<a href="lectures/highestenergies_2024ss/index.shtml">Die höchsten Energien im Universum - die kosmische Strahlung (PSem)</a>
|
||||
</li>
|
||||
</ul>
|
||||
</li>
|
||||
<li>Wintersemester 2023/2024
|
||||
<ul>
|
||||
<li>
|
||||
<a href="lectures/numericalplasmaastro_2023ws/index.shtml">Numerische Methoden der Plasmaastrophysik</a>
|
||||
</li>
|
||||
</ul>
|
||||
</li> <li>Sommersemester 2023
|
||||
<ul>
|
||||
<li>
|
||||
<a href="lectures/cosmicneutrinos_2023ss/index.shtml">Kosmische Neutrinos</a>
|
||||
</li>
|
||||
</ul>
|
||||
</li>
|
||||
<li>Wintersemester 2022/2023
|
||||
<ul>
|
||||
<li>
|
||||
<a href="lectures/numericalplasmaastro_2022ws/index.shtml">Numerische Methoden der Plasmaastrophysik</a>
|
||||
</li>
|
||||
</ul>
|
||||
</li>
|
||||
<li>Sommersemester 2022:
|
||||
<ul>
|
||||
<li><a href="https://muesli.mathi.uni-heidelberg.de/lecture/view/1487">Programmierkurs IKP</a>
|
||||
</li>
|
||||
</ul>
|
||||
</li>
|
||||
<li>Wintersemester 2021/2022
|
||||
<ul>
|
||||
<li><a href="lectures/plasmauniverse_2021ws/index.shtml">Das Plasmauniversum (Masterseminar / MVSem)</a>
|
||||
</li>
|
||||
</ul>
|
||||
</li>
|
||||
<li>Sommersemester 2021 (per online Videokonferenz):
|
||||
<ul>
|
||||
<li><a href="lectures/plasmaastro_2021ss/index.shtml">Einführung in die Plasmaastrophysik</a>
|
||||
</li>
|
||||
</ul>
|
||||
</li>
|
||||
<li>Wintersemester 2020/2021 (per online Videokonferenz):
|
||||
<ul>
|
||||
<li><a href="lectures/cosmicray_2020ws/index.shtml">Astrophysik der Kosmischen Strahlung (WS 20/21)</a></li>
|
||||
</ul>
|
||||
</li>
|
||||
|
||||
<li>Sommersemester 2020 (per online Videokonferenz):
|
||||
<ul>
|
||||
<li><a href="lectures/nonthermal_2020ss/index.shtml">Astronomie des nichtthermischen Universums (SS 20)</a></li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
<!--#else -->
|
||||
Previous semester:
|
||||
|
||||
<ul>
|
||||
<li>Summer semester 2020 (likely by online webconference):</li>
|
||||
<li>Summer semester 2024<br>
|
||||
<ul>
|
||||
<a href="lectures/highestenergies_2024ss/index.shtml">Highest energies in the universe - cosmic rays (PSem)</a>
|
||||
</ul>
|
||||
</li>
|
||||
<li>Winter semester 2023/2024
|
||||
<ul>
|
||||
<li>
|
||||
<a href="lectures/numericalplasmaastro_2023ws/index.shtml">Numerische Methoden der Plasmaastrophysik</a>
|
||||
</li>
|
||||
</ul>
|
||||
</li>
|
||||
<li>Summer semester 2023<br>
|
||||
<ul>
|
||||
<a href="lectures/cosmicray_2020ws/index.shtml">Cosmic Neutrinos</a>
|
||||
</ul>
|
||||
</li>
|
||||
<li>Winter semester 2022/2023
|
||||
<ul>
|
||||
<li>
|
||||
<a href="lectures/numericalplasmaastro_2022ws/index.shtml">Numerical methods of plasma astrophysics</a>
|
||||
</li>
|
||||
</ul>
|
||||
</li>
|
||||
<li>Summer semester 2022:
|
||||
<ul>
|
||||
<li><a href="https://muesli.mathi.uni-heidelberg.de/lecture/view/1487">Programming course IKP</a>
|
||||
</li>
|
||||
</ul>
|
||||
</li>
|
||||
<li>Winter semester 2021/2022
|
||||
<ul>
|
||||
<li><a href="lectures/plasmauniverse_2021ws/index.shtml">The plasma universe (Master's seminar / MVSem)</a>
|
||||
</li>
|
||||
</ul>
|
||||
</li>
|
||||
<li>Summer semester 2021 (by online webconference)
|
||||
<ul>
|
||||
<li>
|
||||
<a href="lectures/plasmaastro_2021ss/index.shtml">Introduction to Plasmaastrophysics</a>
|
||||
</li>
|
||||
</ul>
|
||||
<li>Winter semester 2020/2021 (by online webconference):
|
||||
<ul>
|
||||
<a href="lectures/cosmicray_2020ws/index.shtml">Cosmic ray astrophysics (WS 20/21)</a>
|
||||
</ul>
|
||||
</li>
|
||||
|
||||
<li>Summer semester 2020 (by online webconference):
|
||||
<ul>
|
||||
<li><a href="lectures/nonthermal_2020ss/index.shtml">Astronomie des nichtthermischen Universums (SS 20)</a></li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
<!--#endif -->
|
||||
|
||||
|
||||