In [1]:
# Shell commands -- start with !
!ls
!pwd


LICENSE                          Python_Tutorial--2014Sep26.ipynb README.md                        whatever.py
/Users/dg/Astronomy/Astro_Tutorials/Intro/python-tutorial-2014sep26

In [2]:
# Here's a .py file I made earlier...
!cat whatever.py


import numpy as np

print "Hey!"
print

In [3]:
# I can also load the .py file as code...
# Loading magic
%load whatever.py

In [ ]:
import numpy as np

print "Hey!"
print

In [4]:
import numpy as np

print "Hey!"
print


Hey!


In [5]:
# List Range
a = range(10)
print a
print type(a)
print a*2  # Lists don't multiply like arrays do!


[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
<type 'list'>
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

In [6]:
# Numpy Version
a = np.arange(10)
print a
print type(a)
print a*2


[0 1 2 3 4 5 6 7 8 9]
<type 'numpy.ndarray'>
[ 0  2  4  6  8 10 12 14 16 18]

In [7]:
# Lists
list1 = [1,2,'banana']
list2 = list((1,2,'banana'))
empty_list = []
empty_list.append('strawberry')
print list1 == list2
print empty_list


True
['strawberry']

In [8]:
# Tuple
tuple1 = (1,2,'banana')
tuple2 = tuple((1,2,'banana'))
print tuple2[-1]


banana

In [9]:
# Dictionary
empty_dict = {}
print empty_dict
dict1 = {"""one""":1, '2':'two', "banana":'strawberry'}
print dict1


{}
{'2': 'two', 'banana': 'strawberry', 'one': 1}

In [10]:
# Another way of doing dictionary
dict2 = {}
dict2["""one"""] = 1
print dict2


{'one': 1}

In [11]:
# Putting arrays in dictionaries
dict3 = {}
dict3['arr1'] = np.arange(0,1,0.1)
print '\nBefore: ', dict3
dict3['arr1'] *= 2
print '\nAfter: ', dict3
dict3['arr1'] = dict3['arr1'] * 2
print '\nAfter: ', dict3


Before:  {'arr1': array([ 0. ,  0.1,  0.2,  0.3,  0.4,  0.5,  0.6,  0.7,  0.8,  0.9])}

After:  {'arr1': array([ 0. ,  0.2,  0.4,  0.6,  0.8,  1. ,  1.2,  1.4,  1.6,  1.8])}

After:  {'arr1': array([ 0. ,  0.4,  0.8,  1.2,  1.6,  2. ,  2.4,  2.8,  3.2,  3.6])}

In [12]:
# Timing
# Which way of multiplying is faster?
%timeit dict3['arr1'] *= 1
%timeit dict3['arr1'] = dict3['arr1'] * 1


100000 loops, best of 3: 4.58 µs per loop
100000 loops, best of 3: 7.27 µs per loop

In [13]:
print 'List'
z_list = [0.]*11
print z_list

# Numpy version of 'zeros'
print '\nNumpy'
z = np.zeros(11)
print z

# Setting the value of a list element -- Same [] syntax as Numpy arrays
print '\nAfter value change'
z[3] = 1
print z


List
[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]

Numpy
[ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]

After value change
[ 0.  0.  0.  1.  0.  0.  0.  0.  0.  0.  0.]

In [14]:
# Memory Stuff
# -------------
# Make an array
arr1 = np.arange(11)
print arr1
print '\nID of arr1: ', id(arr1)  # Python's unique ID-number for this array object

# Numpy is VERY conservative on memory
arr2 = arr1  # This doesn't copy
print 'ID of arr2: ', id(arr2)   # It's the same as id(arr1) !!

print 'Comparing arrays'
print id(arr1) == id(arr2)
print arr1 is arr2

# Forcing copy
arr3 = np.copy(arr1)
arr4 = arr1.copy()
print '\nComparing arrays after copy'
print id(arr3), id(arr4)
print 'arr3 is arr4?'
print arr3 is arr4


# Putting an array into a Python dict --> DOES NOT COPY!
dict4 = {}
dict4['arr2'] = arr2
print '\nArrays inside dictionaries:'
print dict4['arr2']
print 'id(arr2) =', id(arr2)
print """id(dict4['arr2']) =""", id(dict4['arr2']) # Same array!

print """arr2 is dict4['arr2'] : """, 
print arr2 is dict4['arr2'] # Same array!


[ 0  1  2  3  4  5  6  7  8  9 10]

ID of arr1:  4345631808
ID of arr2:  4345631808
Comparing arrays
True
True

Comparing arrays after copy
4345628592 4345629248
arr3 is arr4?
False

Arrays inside dictionaries:
[ 0  1  2  3  4  5  6  7  8  9 10]
id(arr2) = 4345631808
id(dict4['arr2']) = 4345631808
arr2 is dict4['arr2'] :  True

In [15]:
# Plotting Stuff
import matplotlib as mpl
from matplotlib import pyplot as plt

# Starting from scratch, with just a Figure object
fig2 = plt.figure(figsize=(10,10))

# Make some fake data
xdata = np.random.rand(20)
ydata = np.random.rand(20)

# We can add axes manually by specifying their size & location
# -----
# This will be the "data" subplot
rect1 = [0.1, 0.1, 0.5, 0.5]  # Left, Bottom, Width, Height (normalized, from 0 to 1)
ax1 = fig2.add_axes(rect1)
ax1.plot(xdata, ydata, lw=0, marker='s', markerfacecolor='none', ms=10, mew='0.5', mec='#346824')

# This can be a "residuals" subplot
rect2 = [0.1, 0.6, 0.5, 0.1]  # Left, Bottom, Width, Height (normalized, from 0 to 1)
ax2 = fig2.add_axes(rect2)
#ax2.xaxis.set_visible(False) # Hide the ENTIRE x-axis
plt.setp(ax2.get_yticklabels(), visible=False)  # Hide just y-axis tick labels

# Let's make the "residuals" subplot a 1-dimensional marginalized density
binsize = 0.1
low, high = 0, 1
nbins = int((high-low) / binsize) + 1
bins = np.linspace(low, high, num=nbins, endpoint=True)

x_density = np.histogram(xdata, bins=bins)[0]
x_density = x_density / float(len(xdata))

plot_bins = (bins[:-1] + bins[1:]) / 2.0
ax2.plot(plot_bins, x_density, marker='x', drawstyle='steps-mid')
#ax2.plot(
ax2.set_ylim(0, x_density.max()*1.1)
ax2.set_xlim(0,1)

plt.show()



In [16]:
# MISC: Demonstrating the creation of AxesSubplot objects
# Axes interface
fig, axes = plt.subplots(nrows=2, ncols=3, figsize=(6,6))
print axes.shape
axes.reshape(-1)


(2, 3)
Out[16]:
array([<matplotlib.axes.AxesSubplot object at 0x104c8ef10>,
       <matplotlib.axes.AxesSubplot object at 0x1051c5f90>,
       <matplotlib.axes.AxesSubplot object at 0x10534ae10>,
       <matplotlib.axes.AxesSubplot object at 0x1053accd0>,
       <matplotlib.axes.AxesSubplot object at 0x10542ea90>,
       <matplotlib.axes.AxesSubplot object at 0x105492790>], dtype=object)

In [16]: