Dr. Joshua Vaughan
joshua.vaughan@louisiana.edu
http://www.ucs.louisiana.edu/~jev9637/
For most of our work, we will leverage the great set of tools available for scientific Python. The main of these tools is NumPy. We'll also use parts of the SciPy. Of course, we'll spend most of our time working in IPython Notebooks like this one.
A great tutorial on using these tools is availabe at http://scipy-lectures.github.io
# The "#' is a comment in Python - USE COMMENTS!
# more comments
# We have to import the modules we want to use
import numpy as np # numpy is the heart of what we'll use, we import it with the "nickname" np
# Simple math works as you'd expect
x = 2 + 2
y = 10 * 5
z = 3**2 # Exponentials are with ** not ^
# Let's format x and y for pretty printing
# You can just add strings together to create longer ones
string = 'x = ' + str(x) + ', y = ' + str(y) + ', z = ' + str(z)
print(string)
x = 4, y = 50, z = 9
You can change the "cell" type to be Markdown, a shorthand way of formatting plain text, often with the intentions of later converting to HTML. Many text editors and blogging engines will take it as input as well.
We can make simple, unordered lists:
Item
Item
Item
We can also do numbered lists:
Item 1
a. Subpoint a
b. Subpoint b
Item 2
a. Subpoint a
b. Subpoint b
c. Subpoint c
Item 3
To italicize an item wrap it with astericks and to bold, wrap it with double-astericks.
We can also dislay figures or pictures inline. It can be helpful to include images of the models you are simulating.
We can also generate plots inline. To do this we issue the command:
We will use the matplotlib library for all our plotting. It's a powerful package and with a few tweaks to the defaults, we can generate nice-looking, easily-readable figures.
Some great tutorials on the features of matplotlib can be found at:
# We want to show the figures inline
%matplotlib inline
# Import the plotting functions
import matplotlib.pyplot as plt
Now, let's try a simple plot.
t = np.linspace(0, 5, 1000) # Define the time vector (start,end,number of points)
y = np.sin(2 * np.pi * t)
y2 = np.sin(4 * np.pi * t)
# To plot, we need to preface our plotting commands with plt (the namespace we imported matplotlib under)
# This effectively says "use the matplotlib version of this command"
plt.plot(t, y)
plt.plot(t, y2)
plt.xlabel(r'Time (s)', fontsize=22, labelpad=5)
plt.ylabel(r'$\sin(2\pi t)$',fontsize=22, labelpad=8)
<matplotlib.text.Text at 0x1109d25c0>
That plot isn't very easy to read at all. In fact, it's terrible. We can also issue commands to better format the plot and make the plot a little bit easier to read.
# Set the plot size - 3x2 aspect ratio is best
fig = plt.figure(figsize=(6,4))
ax = plt.gca()
plt.subplots_adjust(bottom=0.17,left=0.17,top=0.96,right=0.96)
# Change the axis units to serif
plt.setp(ax.get_ymajorticklabels(),family='serif',fontsize=18)
plt.setp(ax.get_xmajorticklabels(),family='serif',fontsize=18)
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
# Turn on the plot grid and set appropriate linestyle and color
ax.grid(True,linestyle=':',color='0.75')
ax.set_axisbelow(True)
# Define the X and Y axis labels
plt.xlabel('Time (s)',family='serif',fontsize=22,weight='bold',labelpad=5)
plt.ylabel('Y (units)',family='serif',fontsize=22,weight='bold',labelpad=10)
plt.plot(t, y,linewidth=2,linestyle='-', label=r'$y_1$')
plt.plot(t,y2,linewidth=2,linestyle='--', label=r'$y_2$')
# uncomment below and set limits if needed
plt.xlim(0,5)
plt.ylim(-1.1,1.5)
# Create the legend, then fix the fontsize
leg = plt.legend(loc='upper right', ncol = 2, fancybox=True)
ltext = leg.get_texts()
plt.setp(ltext,family='serif',fontsize=20)
# Adjust the page layout filling the page using the new tight_layout command
plt.tight_layout(pad=0.5)
# Save the figure as a high-res pdf in the current folder
# It's saved at the original 6x4 size
# plt.savefig('plot_filename.pdf')
fig.set_size_inches(9,6) # Resize the figure for better display in the notebook
Code is licensed under a 3-clause BSD style license. See the licenses/LICENSE.md file.
Other content is provided under a Creative Commons Attribution-NonCommercial 4.0 International License, CC-BY-NC 4.0.
# This cell will just improve the styling of the notebook
# You can ignore it, if you are okay with the default sytling
from IPython.core.display import HTML
import urllib.request
response = urllib.request.urlopen("https://cl.ly/1B1y452Z1d35")
HTML(response.read().decode("utf-8"))