Roberto Di Remigio, Luca Frediani
During the course we will use Python to solve some of the exercises and explore concepts in quantum mechanics. Instead of just using the command line, we will exploit Jupyter notebooks. You will be able to look at the exercises and run them on your browser. We recommend you install Python on your machine anyway: we think you will find knowledge of Python useful also in the future. The easiest way to get a reasonably complete Python distribution working is via Anaconda, detailed instructions for Windows, Max OS X and Linux are here.
Python is an interpreted scripting language that has become more and more popular in the past years. It can be used (and it is used) to do pretty much anything. It can be your pocket calculator, you can use it to plot data, calculate derivatives and integrals, perform tasks in linear algebra and much, much more!
There are a lot of resources out there to learn Python. Mark Bakker's collection of Jupyter notebooks is really great. It covers a lot of ground, plus you have screencasts for the notebooks covering the basics of Python. We also recommend the book Learning IPython for Interactive Computing and Data Visualization by Cyrille Roussant. The ebook is available from the University's library. You will have to be on campus to access it via this link, click the Fulltekst tilgjengelig på: ebrary Academic Complete Non-US link to go to the ebook. Finally, to learn more about how to fully exploit a Jupyter notebook we recommend you read the tutorials in this page
Let's start off by using Python as a calculator. There are different types of cells in Jupyter notebooks. We will be mostly using code cells to write and execute code and Markdown cells to write comments to the code. A Markdown cell is just text. You can add images and also equations, using $\LaTeX$:
\begin{equation} f(x) = ax^2 + bx + c \end{equation}Code cells contain Python code. Each code cell has an input and an output section. The input section contains code you write, the ouput section contains the results of executing your code. Move your cursor to the code cell right below this Markdown cell and press [shift][Enter]. This triggers evaluation of the cell and you will see the output of the computation right below.
In [1]:
6 * 2
Out[1]:
When programming, you can (and should) use variables to hold values, so that you can reference them later in your code. Pressing [shift][Enter] will always trigger evaluation of a code cell and print out the results.
In [2]:
a = 6
b = 2
a * b
Out[2]:
Python provides the print
function to write output to the screen.
In [3]:
a = 6
b = 2
c = a * b
print(a)
print(b)
print(c)
Of course, we can add more information to a print statement! A line starting with #
is a comment, the intepreter will just ignore it. It is useful to add comments, to remind both yourself and others what you were trying to do when writing the code ;)
In [2]:
a = 6 # Assign value to a
b = 2 # Assign value to b
c = a * b # Perform operation
# Now print everything out!
print('a =', a)
print('b =', b)
print('c =', c)
matplotlib
When you first install Python and launch an instance of the interpreter (the program running the commands) you cannot do very much. Luckily, Python was designed to be highly extensible using independent packages called modules. Much of the functionality that makes Python appealing is provided via modules. A module is a collection of functions designed to perform a very specific set of tasks.
For example, the matplotlib
module provides the functions needed to perform plotting in Python.
To use it we need to import it. There are many different ways to import a module, for the moment we import only the plottig part of matplotlib
and call it plt
. The second command ensures that the plots are generated in this Notebook and not in a separate window.
In [13]:
import matplotlib.pyplot as plt
# make sure we see it on this notebook
%matplotlib inline
Modules only have to be imported once in a Jupyter session. After the import, any plotting function may be called from any code cell as plt.function
. In the following we are plotting the data table:
x | y |
---|---|
0 | 1 |
1 | 2 |
2 | 3 |
3 | 5 |
4 | 2 |
5 | 6 |
In [15]:
import matplotlib.pyplot as plt
# make sure we see it on this notebook
%matplotlib inline
plt.plot([1, 2, 3, 5, 2, 6])
plt.show()
numpy
OK, let's plot something more interesting than just a bunch of points.
The function we want to plot is:
\begin{equation}
f(x) = 10x^3\mathrm{e}^{-x^2} + \frac{\sin(x^5)}{\cos(x^3)}
\end{equation}
How do we do it? We could of course create a table of $x$,$y$ pairs and feed it to the plt.plot
function as in the example above, but that's too tedious.
The module numpy
comes to the rescue. First of all, we import numpy
and give it the name np
:
In [16]:
import numpy as np
Next, we create an array of, for example, 10 equally spaced points between -4 and +4 with the linspace
command. This array will contain the values of the x
variables where we will evaluate the function $f(x)$.
In [52]:
x = np.linspace(-4, 4, 10)
print(x)
The next step is to evaluate the function at all the $x$ points listed in the x
array and save the results in another array, which we call y
:
In [53]:
y = 10 * x**3 * np.exp(-x**2) + np.sin(x**5) / np.cos(x**3)
print(y)
Notice that:
x**3
and not x^3
numpy
and you have to invoke them as np.exp
, np.sin
and np.cos
since you are giving numpy
arrays as arguments.
We are now ready to plot!
In [22]:
import matplotlib.pyplot as plt
# make sure we see it on this notebook
%matplotlib inline
plt.plot(x, y)
Out[22]:
Done! OK, it doesn't look that great. That's because we are using only 10 sampling points. Try changing the number of points generated by np.linspace
from 10 to another, higher value. Re-run all the cells and see what changes.
We can also apply other changes. First of all, we can define a Python function to calculate $f(x)$. We can then reuse this function wherever we want instead of typing it down everytime! A Python function:
def
statementnumpy
array with the $x$ points.y
array, then returns the array.
In [32]:
def my_first_function(x):
import numpy as np
y = 10 * x**3 * np.exp(-x**2) + np.sin(x**5) / np.cos(x**3)
return y
In [33]:
function = my_first_function(x)
print(function)
As you can see, calling the function gives the same results as calculated above.
As further improvements we will add a legend to the plot, labels to the $x$ and $y$ axes and a title. Python functions in matplotlib
and numpy
take many arguments. Pressing [shift][Tab] when typing in a code cell will open an help box with a lot of useful information on the function arguments.
In [54]:
plt.plot(x, my_first_function(x), 'r--')
# Write label on x axis
plt.xlabel('x-axis')
# Write label on y axis
plt.ylabel('y-axis')
# Write title
plt.title('First Python Figure')
# Add legend
plt.legend('f')
Out[54]: