In [1]:
# numpy+ pandas+ ggplot test
from ggplot import *
import pandas as pd
meat_lng = pd.melt(meat[['date', 'beef', 'pork', 'broilers']], id_vars='date')
ggplot(aes(x='date', y='value', colour='variable'), data=meat_lng) + \
geom_point() + \
stat_smooth(color='red')
Out[1]:
In [2]:
# numba and Mingw test
import numpy as np
image = np.zeros((1024, 1536), dtype = np.uint8)
from pylab import imshow, show
from timeit import default_timer as timer
from numba import autojit
@autojit
def mandel(x, y, max_iters):
c = complex(x, y)
z = 0.0j
for i in range(max_iters):
z = z*z + c
if (z.real*z.real + z.imag*z.imag) >= 4:
return i
return max_iters
def create_fractal(min_x, max_x, min_y, max_y, image, iters , mandelx):
height = image.shape[0]
width = image.shape[1]
pixel_size_x = (max_x - min_x) / width
pixel_size_y = (max_y - min_y) / height
for x in range(width):
real = min_x + x * pixel_size_x
for y in range(height):
imag = min_y + y * pixel_size_y
color = mandelx(real, imag, iters)
image[y, x] = color
# NOTA : under Python 3.x, there is a "UserWarning" at first compilation, but Numba did compile anyway.
start = timer()
create_fractal(-2.0, 1.0, -1.0, 1.0, image, 20 , mandel)
dt = timer() - start
print ("Mandelbrot created by numba in %f s" % dt)
imshow(image)
show()
In [3]:
# cython
%load_ext cythonmagic
In [4]:
%%cython
def mandel_cython(x, y, max_iters):
cdef int i
cdef double cx, cy , zx, zy
cx , cy = x, y
zx , zy =0 ,0
for i in range(max_iters):
zx , zy = zx*zx - zy*zy + cx , zx*zy*2 + cy
if (zx*zx + zy*zy) >= 4:
return i
return max_iters
In [5]:
start = timer()
create_fractal(-2.0, 1.0, -1.0, 1.0, image, 20 , mandel_cython)
dt = timer() - start
print ("Mandelbrot created by cython in %f s" % dt)
imshow(image)
show()
In [6]:
# statsmodel
import numpy as np
import matplotlib.pyplot as plt
import statsmodels.api as sm
data = sm.datasets.anes96.load_pandas()
party_ID = np.arange(7)
labels = ["Strong Democrat", "Weak Democrat", "Independent-Democrat",
"Independent-Independent", "Independent-Republican",
"Weak Republican", "Strong Republican"]
plt.rcParams['figure.subplot.bottom'] = 0.23 # keep labels visible
plt.rcParams['figure.figsize'] = (10.0, 8.0) # make plot larger in notebook
age = [data.exog['age'][data.endog == id] for id in party_ID]
fig = plt.figure()
ax = fig.add_subplot(111)
plot_opts={'cutoff_val':5, 'cutoff_type':'abs',
'label_fontsize':'small',
'label_rotation':30}
sm.graphics.beanplot(age, ax=ax, labels=labels,
plot_opts=plot_opts)
ax.set_xlabel("Party identification of respondent")
ax.set_ylabel("Age")
Out[6]:
In [7]:
# checking mahotas
import pylab as p
import numpy as np
import mahotas
f = np.ones((256,256), bool)
f[200:,240:] = False
f[128:144,32:48] = False
# f is basically True with the exception of two islands: one in the lower-right
# corner, another, middle-left
dmap = mahotas.distance(f)
p.imshow(dmap)
p.show()
In [8]:
# sympy
import sympy
a=sympy.Symbol('a')
b=sympy.Symbol('b')
e=(a+b)**5
print (e.expand())
In [9]:
# Scipy and Scikit-learn
import numpy as np
X = np.random.random((1000, 3))
from scipy.spatial.distance import cdist
%timeit cdist(X, X)
from sklearn.metrics import euclidean_distances
%timeit euclidean_distances(X, X)
In [10]:
# checking Ipython-sql, sqlparse, SQLalchemy
%load_ext sql
In [11]:
%%sql sqlite://
DROP TABLE IF EXISTS writer;
CREATE TABLE writer (first_name, last_name, year_of_death);
INSERT INTO writer VALUES ('William', 'Shakespeare', 1616);
INSERT INTO writer VALUES ('Bertold', 'Brecht', 1956);
SELECT * , sqlite_version() as sqlite_version from Writer order by Year_of_death
Out[11]:
In [12]:
# lmfit test (from http://nbviewer.ipython.org/github/lmfit/lmfit-py/blob/master/examples/lmfit-model.ipynb)
def decay(t, N, tau):
return N*np.exp(-t/tau)
t = np.linspace(0, 5, num=1000)
data = decay(t, 7, 3) + np.random.randn(*t.shape)
from lmfit import Model
model = Model(decay, independent_vars=['t'])
result = model.fit(data, t=t, N=10, tau=1)
p.plot(t, data) # data
p.plot(t, decay(t=t, **result.values), color='orange', linewidth=5) # best-fit model
Out[12]:
In [33]:
# checking beautifulsoup and requests
import requests # pip install requests
from bs4 import BeautifulSoup # pip install BeautifulSoup
# XXX: Any URL containing a geo microformat...
URL = 'http://en.wikipedia.org/wiki/Franklin,_Tennessee'
# In the case of extracting content from Wikipedia, be sure to
# review its "Bot Policy," which is defined at
# http://meta.wikimedia.org/wiki/Bot_policy#Unacceptable_usage
req = requests.get(URL, headers={'User-Agent' : "Mining the Social Web"})
soup = BeautifulSoup(req.text)
geoTag = soup.find(True, 'geo')
if geoTag and len(geoTag) > 1:
lat = geoTag.find(True, 'latitude').string
lon = geoTag.find(True, 'longitude').string
print ('Location is at', lat, lon)
elif geoTag and len(geoTag) == 1:
(lat, lon) = geoTag.string.split(';')
(lat, lon) = (lat.strip(), lon.strip())
print ('Location is at', lat, lon)
else:
print ('No location found')
In [ ]: