0% found this document useful (0 votes)
31 views

Python Tutorial

This document provides a step-by-step tutorial for coding problems 1 and 3 from Ge 1 set 2 using Python. It introduces Python and the key packages needed for numerical calculations and plotting. It explains how to define variables, write conditional statements, define functions using lambda notation, construct grids of values, calculate derivatives on the grid, and plot contour maps. The tutorial is intended to explain the necessary Python syntax while leaving the scientific details of solving the problems for the user to determine.

Uploaded by

barack orama
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views

Python Tutorial

This document provides a step-by-step tutorial for coding problems 1 and 3 from Ge 1 set 2 using Python. It introduces Python and the key packages needed for numerical calculations and plotting. It explains how to define variables, write conditional statements, define functions using lambda notation, construct grids of values, calculate derivatives on the grid, and plot contour maps. The tutorial is intended to explain the necessary Python syntax while leaving the scientific details of solving the problems for the user to determine.

Uploaded by

barack orama
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

Ge 1, Spring 2015 Python Introduction Peter Buhler (04/20/2015)

This is a step-by-step guide to coding Ge 1 set 2 problems 1 and 3 using Python. It is meant to explain all
the syntax you will need, but you will still have to figure out the science!

Python is a versatile scientific programming language; it is also free! There are several interfaces available
for Python that increase its ease of use. I suggest the program Canopy by Enthought
(https://store.enthought.com/downloads/). It can be used for Windows, Mac, or Linux. The free version
bundles many of the most used scientific Python packages in one directory so that they will all work
together smoothly and you don’t need to worry about downloading them yourself. Nb. Make sure that
you download the correct version (32- or 64-bit) for your computer; it makes a difference!

As you follow through this tutorial, note that there are other ways of coding and other syntaxes that could
be used. However, I will try to use a syntax that is as transparent as possible so that new users can get a
good understanding of what we’re trying to do!

1. First things first! Open your favorite python editor (e.g. Canopy) and open a new file to begin editing.
In Canopy (and most Graphical User Interfaces [GUIs] for programming), there will be two panels into
which you type. You will be writing your program into the upper panel, which you can think of basically as
a text editor (e.g. you can save your file, copy/paste within the panel, etc.). Once you are done typing your
program you will run it (in Canopy you will press a big green triangle in the top bar) and the output will be
displayed in the lower panel.

2. Before we can start coding, we have to tell Python which packages we will need and then import them.
For this set we will need to do some numerical calculations and we will need to plot contours. Let’s go
ahead and import these packages; here is the syntax:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib
When we ‘import as’ it means that whenever I want to use a function that comes from a particular
package I will write (e.g. for an exponent using the numpy package) np.exp(), where the argument will
go inside the parentheses. So if I want to take e10 then I write np.exp(10). If I just wrote exp(10),
then Python won’t know what to do, because it does not know where to look for the function ‘exp’.
Another reason to write ‘import as’ is so that we have less to write as we code (i.e. ‘plt’ is much
faster to type than ‘matplotlib.pyplot’).

3. Next, we will have variables to work with. It is a very good idea to import values as variables, not plug
in values throughout the code. So think about which variables you will need to import. The syntax for
defining variables follows. Since we need to define sigma for this problem, I’ll use it as an example.
sigma = 5.67e-8

Alternatively, I could write:


sigma = 5.67*10**-8 #The Stefan-Boltzmann constant

As you can see, we can write powers of ten either as e-8 or *10**-8. In Python * is multiplication and
** indicates a power. Also note that you can write yourself notes (usually called ‘comments’) by inserting
a hash-tag before the text (like my comment #The Stefan-Boltzmann constant). These are
Ge 1, Spring 2015 Python Introduction Peter Buhler (04/20/2015)

useful in order to remind yourself what you are doing! Go ahead and define all of the variables that you
will need. Make sure that your units are consistent! You can even make variables that take other variables
as input, like [hint]:
C = Cp*P/g

4. Next we want to make our code versatile, so that we can answer both question 1 and question 3 without
having to rewrite all our code. We will do this by setting two switches iceOn (problem 1) and waterOn
(problem 3):
iceOn = True #Use for problem 1
waterOn = False #Use for problem 3

Here we have set the truth values for each of the variables, which will allow us to toggle between the
problems that we want to solve. Make sure that True and False are capitalized. Capitalization makes
a difference in Python!

5. Now that we can toggle between the two problems at will, we need to tell prompt Python to do the
calculations for problem 1 or problem 3, respectively. We can do that using an ‘if statement,’ which tells
Python to do one thing if the statement is fulfilled, and another if the statement is not fulfilled. For
example:
if iceOn:
x = 5
else:
x = 0

For this example, if we had set the truth value of iceOn to be True, then x will equal 5. If the truth value
were False, then x would equal 0. Also, make sure to use TABs (not spaces) to indent under the if
statement. Every line that is indented under the if statement will apply if that statement is met (e.g. note
how x = 5 is indented); the if statement ends when the text is un-indented (e.g. the else statement has
been un-indented).

6. Now that Python can tell which problem we want to solve, we can tell it what to do. For each of
problems 1 and 3 we have different assumptions. I will let you figure out how to program those exactly
(with the correct functions and values), but the form will be identical to this example…

Say we want to solve Problem X, where we heat a box of water under the conditions of either (i) where
salt water is slowly being mixed in, exponentially faster (part a) or (ii) the water remains fresh (part b)
AND the box is either (i) assumed to have a constant volume (part a) or (ii) have a sinusoidally changing
volume as a function of time (part b).
PartA = True
PartB = False
if PartA:
Rho = lambda t: 1.0 + 1.025*np.exp(0.01t) #Density for part a
Ge 1, Spring 2015 Python Introduction Peter Buhler (04/20/2015)

else:
Rho = lambda t: 1.0 #Density assumption for part b
if PartB:
V = lambda t: 300. #Volume assumption for part a
else:
V = lambda t: 300.+ 5*np.cos(0.01*t) #Volume assumption for part b

You should recognize setting the truth values (whether we are solving part a or part b) and also the if
statements (telling Python whether we want to use the assumptions for part a or part b). Now what does
the rest mean? To define functions of t (a dummy variable which relates time and either volume or rho),
we are going to use ‘lambda notation’. This is a fancy way of saying we are going to define (in this example)
Rho as a function of time or Volume as a function of time. By saying lambda t, we are telling Python
that we want t to be the input, which will go through a particular function (after the colon) and give the
corresponding output value of Rho or V (i.e. the variable on the left hand side of the equals sign).

When writing equations that are meant to handle non-integers, make sure to include a decimal point
because Python treats integer values differently (e.g. use V = lambda t: 300. not V = lambda
t: 300).

To solve the problems on the set, think about which assumptions we make for each part [hint: we change
our assumptions about two variables]. Then, write out the assumptions using the lambda syntax, as
demonstrated in the example. Hint: for exponents use the np.exp() function and for hyperbolic tangent
use the np.tanh() function.

7. Now we want to construct the contour plot for the lefthand side (LHS) of equation (3 or 6) in the set,
that is, the derivative of the surface temperature with respect to time. To this we must first construct a
grid that we can populate with values. Since this part is not very informative in terms of science, let’s walk
through it explicitly.

First we need to define the boundaries of our grid:


if iceOn:
Tmin, Tmax = 220, 320
if waterOn:
Tmin, Tmax = 260, 360

These boundaries are suggested from the problem set.

Now we are going to construct a grid of paired TS and T0 values so that we can numerically calculate the
derivative (LHS of equation 3 or 6) at each point on the grid. First we will construct vectors of surface
temperatures and equilibrium temperatures using the np.arange() function, which takes a minimum
value, a maximum value, and a spacing between values. Then we will have Python mesh them together
to form a Cartesian grid of values using the np.meshgrid() function.
Ge 1, Spring 2015 Python Introduction Peter Buhler (04/20/2015)

Ts = np.arange(Tmin,Tmax,0.1)

T0 = np.arange(220,320,0.1) #220-320 suggested from the set

X,Y = np.meshgrid(T0,Ts)
8. The X and the Y values (from part 7) relate to the T0 and the TS values at each point on the grid,
respectively. These are the values that we want to plug in to solve our dT/dt equation.
𝑑𝑇 𝑇4
For example, if we wanted to solve for = 𝜎(𝐴(𝑇𝑆 ) + 𝑇04 ) , where A(TS) is the albedo that
𝑑𝑡 𝑠
depends on TS, [hint: not the correct equation] then we would code:
A = lambda T: 1.0-T/500. #Defining A (recall part 6)
dTdt = sigma*((Y**4/A(Y))+X**4)
Here X is the value of T0 at a particular grid point and Y is the value of TS paired with X at that
particular grid point. In our fake equation the albedo depends on the value of T S, and thus the
value of Y, which is the value drawn from the TS vector we defined in part 7. Note the syntax A(Y)
and that this is not the correct expression for A…
Now code out the correct equation for dTdt. Make sure it has the correct units!
9. Finally we want to plot out the contours and make them look nice. This is also not scientifically
interesting, so we can spell it out explicitly. Python is well documented and if you run into trouble
while plotting, here is a good resource to look at: http://matplotlib.org/api/pyplot_api.html.
matplotlib.rc('xtick',labelsize = 18)
matplotlib.rc('ytick',labelsize = 18)
matplotlib.rc('axes',linewidth = 2)

These commands tell the matplotlib package how to format the plot area. rc is a routine
within matplotlib, just like pyplot is a routine within matplotlib (recall, in step 2, that
we imported both matplotlib and matplotlib.pyplot; the reason was so that we could
reach into matplotlib and not just the pyplot extension, in order to change the formatting).
Next we have:
plt.figure()
This tells Python that we are about to create a figure. Recall that we imported matplotlib.pyplot
as plt in step 2.

Next:

hc = plt.contour(X,Y,dTdt,10,colors = 'k')
Contour is the contour plotting routine in matplotlib.pyplot. We are defining the contour plot
of dTdt as an object, which we will bring into the plotting area soon. We are telling Python which data to
Ge 1, Spring 2015 Python Introduction Peter Buhler (04/20/2015)

put into the contour plot, the function from which we want to generate the contours, the number of
contours (10), and the color scheme (black = ‘k’).

plt.clabel(hc,fontsize=10,inline=1,fmt='%4.2f')
plt.xlabel('$T_0 \quad (K)$', fontsize = 15)
plt.ylabel('$T_S \quad (K)$', fontsize = 15)

Now we are telling the pyplot extension some additional formatting information. With
plt.clabel (‘contour label’) we are importing our contour plot (which we defined as the
object ‘hc’) and telling it that we want the contour labels to have a font size of 10, that we want
the labels to be in line with contours. The last entry ‘%4.2f’, tells Python that we want the
labels to have four characters, with two decimal points and to be floating point (f) numbers.
Similarly, in formatting the x- and y-labels, we are telling Python to use LaTeX math string format
(prompted by the $ character); the underscore indicates that the next character should be a
subscript, and the \quad inserts a space [blank] character.
10. Finally, you want to plot the value of the current T0, TS pair for equilibrium Earth. Calculate
the T0, TS pair. When you have done so, you can plug them into:
plt.plot([220,320],[288,288],'r',linewidth=2) #TS = 288 K
plt.plot([T0,T0],[Tmin,Tmax],'b',linewidth=2) # plug in for T0
This will plot a crossing pair of lines on your plot (one red, ‘r’, and one blue, ‘b’).
The very last step is to tell Python to display the plot. The command to do this is:
plt.show()
Remember to run your program now! If you’re using Canopy, it will be the big green triangle
button on the top of the interface.
11. Good luck! If you get an error message, try copy/pasting the message into google and you will
likely find an answer to your problem from a site like http://stackoverflow.com/. An extra hint:
never define variables starting with a number (i.e. Rho1 is okay but not 1Rho).

You might also like