介绍ipython notebook

1.简单介绍ipython notebook的安装和使用,在ubuntu上:
sudo apt-get install ipython
但是并不是所有的版本都支持notebook功能,本人的系统安装的是0.13的版本有
notebook,但是有个重要的功能没有,什么功能等会再说,所以本人手动安装的
ipython 1.1.0版本,你可以“ipython -V”查看版本号。
http://ipython.org/ 此网址可以下载最新的ipython版本

2.使用python的你也许对ipython有所耳闻或者使用过,简单的介绍ipython:
ipython是一个强大而交互式运算架构:

(1).强大的交互式shell(终端运行);
(2).一个基于浏览器的notbook,支持代码、文本、数学运算、内嵌plots等;
(3).支持交互式的数据可视化和GUI工具包的使用;
(4).灵活、内嵌的解释器加载到自己的项目;
(5).支持并行运算.

3.运行ipython notebook,在终端输入:

ipython notebook
如果你使用matplotlib内嵌进网页中,那么需要运行:
ipython notebook --matplotlib inline
OK,程序会自动在浏览器上新建一个标签窗口。
所以ipython notebook就是一个后端服务和一个前端表现,服务默认端口8888,
前端也就是你在浏览器中看到的,如下图:

In [5]:
from IPython.display import Image
Image(filename='/home/chaofan/Desktop/firstpage.png') #press shift+enter 
Out[5]:

上图即是控制窗口,我们可以按"New Notebook"新建一个,本人已经见了5个。
你现在所读的页面即是上图 Advence打开后本人编辑 成现在的效果。

基本的操作

1.每次运行按shift-enter

In [7]:
i=0
print i #按shift+enter
0

可以看到输出了0,我们可以直接对上面的程序做修改,再运行。

2.ipython提供个很多魔数,以%或者%%开始

In [1]:
%matplotlib inline

%matplotlib就是一个魔数,如果你在命令行加入--matplotlib inline
运行此命令一样可以达到内嵌的效果。

下面是获得连接信息

In [30]:
%connect_info
{
  "stdin_port": 41438, 
  "ip": "127.0.0.1", 
  "control_port": 42233, 
  "hb_port": 49904, 
  "signature_scheme": "hmac-sha256", 
  "key": "b6324ba0-f75a-4aec-98cc-42893b4ef790", 
  "shell_port": 52144, 
  "transport": "tcp", 
  "iopub_port": 59393
}

Paste the above JSON into a file, and connect with:
    $> ipython <app> --existing <file>
or, if you are local, you can connect with just:
    $> ipython <app> --existing kernel-96015ef4-abc1-40db-b408-acb9f47900f1.json 
or even just:
    $> ipython <app> --existing 
if this is the most recent IPython session you have started.

3.可以直接运行bash

In [13]:
ls -l
total 904
-rw-r--r-- 1 chaofan chaofan 892046 12月  9 22:04 Advance.ipynb
-rw-r--r-- 1 chaofan chaofan   6883 11月 24 13:13 python11-24.ipynb
-rw-r--r-- 1 chaofan chaofan   9928 11月 27 00:28 test.ipynb
-rw-r--r-- 1 chaofan chaofan    493 11月 27 20:54 tiny.ipynb
-rw-r--r-- 1 chaofan chaofan    290 11月 30 21:19 tmp.ipynb

In [14]:
pwd
Out[14]:
u'/home/chaofan/notebook'
In [16]:
%%bash
echo 'Hello'
date
Hello
2013年 12月 09日 星期一 22:21:41 CST

如果一个程序无线循环或者循环的时间太长想中断可以
ctr-m i,如下:

In [27]:
import time
i=0
while True:
    time.sleep(1)
    print i
    i+=1
0
1
2
3
4
5
---------------------------------------------------------------------------
KeyboardInterrupt                         Traceback (most recent call last)
<ipython-input-27-cada1146ea44> in <module>()
      2 i=0
      3 while True:
----> 4     time.sleep(1)
      5     print i
      6     i+=1

KeyboardInterrupt: 


4.载入图片

上面已经使用过了载入图片,下面载入notebook快捷键的图片,
ctr-m h也会弹出帮助窗口。

In [19]:
Image(filename='/home/chaofan/Desktop/help.png')
Out[19]:

载入url图片:

In [22]:
Image(url='http://ww1.sinaimg.cn/mw600/6a77a719jw1dyx581xf1cj.jpg')
Out[22]:

高级处理

1.matplotlib使用

In [8]:
import numpy as np
In [9]:
import matplotlib.pyplot as plt
In [10]:
x = np.linspace(0, 3*np.pi, 500)
plt.plot(x, np.sin(x**2))
plt.title('A simple chirp');
plt.show()

url载入代码:

In [28]:
%load http://matplotlib.sourceforge.net/mpl_examples/pylab_examples/integral_demo.py
In [29]:
#!/usr/bin/env python

# implement the example graphs/integral from pyx
from pylab import *
from matplotlib.patches import Polygon

def func(x):
    return (x-3)*(x-5)*(x-7)+85

ax = subplot(111)

a, b = 2, 9 # integral area
x = arange(0, 10, 0.01)
y = func(x)
plot(x, y, linewidth=1)

# make the shaded region
ix = arange(a, b, 0.01)
iy = func(ix)
verts = [(a,0)] + list(zip(ix,iy)) + [(b,0)]
poly = Polygon(verts, facecolor='0.8', edgecolor='k')
ax.add_patch(poly)

text(0.5 * (a + b), 30,
     r"$\int_a^b f(x)\mathrm{d}x$", horizontalalignment='center',
     fontsize=20)

axis([0,10, 0, 180])
figtext(0.9, 0.05, 'x')
figtext(0.1, 0.9, 'y')
ax.set_xticks((a,b))
ax.set_xticklabels(('a','b'))
ax.set_yticks([])
show()

2.来点科学计算的,看看酷不酷!

In [17]:
from sympy.interactive import printing
In [18]:
from IPython.display import display
In [19]:
printing.init_printing()

from __future__ import division
import sympy as sym
from sympy import *
x, y, z = symbols("x y z")
k, m, n = symbols("k m n", integer=True)
f, g, h = map(Function, 'fgh')
In [20]:
Rational(3,2)*pi + exp(I*x) / (x**2 + y)
Out[20]:
$$\frac{3}{2} \pi + \frac{e^{\mathbf{\imath} x}}{x^{2} + y}$$
In [21]:
exp(I*x).subs(x,pi).evalf()
Out[21]:
$$-1.0$$
In [22]:
eq = ((x+y)**2 * (x+1))
eq
Out[22]:
$$\left(x + 1\right) \left(x + y\right)^{2}$$
In [23]:
expand(eq)
Out[23]:
$$x^{3} + 2 x^{2} y + x^{2} + x y^{2} + 2 x y + y^{2}$$
In [24]:
a = 1/x + (x*sin(x) - 1)/x
a
Out[24]:
$$\frac{x \sin{\left (x \right )} -1}{x} + \frac{1}{x}$$
In [25]:
simplify(a)
Out[25]:
$$\sin{\left (x \right )}$$
In [26]:
a, b = symbols('a b')
Sum(6*n**2 + 2**n, (n, a, b))
Out[26]:
$$\sum_{n=a}^{b} \left(2^{n} + 6 n^{2}\right)$$
In [27]:
(1/cos(x)).series(x, 0, 6)
Out[27]:
$$1 + \frac{1}{2} x^{2} + \frac{5}{24} x^{4} + \mathcal{O}\left(x^{6}\right)$$
In [28]:
diff(cos(x**2)**2 / (1+x), x)
Out[28]:
$$- 4 \frac{x \sin{\left (x^{2} \right )} \cos{\left (x^{2} \right )}}{x + 1} - \frac{\cos^{2}{\left (x^{2} \right )}}{\left(x + 1\right)^{2}}$$
In [29]:
eqn = Eq(Derivative(f(x),x,x) + 9*f(x), 1)
display(eqn)
dsolve(eqn, f(x))
$$9 \operatorname{f}{\left (x \right )} + \frac{\partial^{2}}{\partial^{2} x} \operatorname{f}{\left (x \right )} = 1$$
Out[29]:
$$\operatorname{f}{\left (x \right )} = C_{1} \sin{\left (3 x \right )} + C_{2} \cos{\left (3 x \right )} + \frac{1}{9}$$

3.在来些matplotlib的例子

In [1]:
from pylab import *
In [2]:
x = linspace(0, 5, 10)
y = x ** 2
In [3]:
figure()
plot(x, y, 'r')
xlabel('x')
ylabel('y')
title('title')
show()
In [4]:
subplot(1,2,1)
plot(x, y, 'r--')
subplot(1,2,2)
plot(y, x, 'g*-');
In [5]:
fig = plt.figure()

axes1 = fig.add_axes([0.1, 0.1, 0.8, 0.8]) # main axes
axes2 = fig.add_axes([0.2, 0.5, 0.4, 0.3]) # inset axes

# main figure
axes1.plot(x, y, 'r')
axes1.set_xlabel('x')
axes1.set_ylabel('y')
axes1.set_title('title')

# insert
axes2.plot(y, x, 'g')
axes2.set_xlabel('y')
axes2.set_ylabel('x')
axes2.set_title('insert title');
In [6]:
fig, ax = plt.subplots()

ax.plot(x, x**2, label=r"$y = \alpha^2$")
ax.plot(x, x**3, label=r"$y = \alpha^3$")
ax.set_xlabel(r'$\alpha$', fontsize=18)
ax.set_ylabel(r'$y$', fontsize=18)
ax.set_title('title')
ax.legend(loc=2); # upper left corner
Out[6]:
<matplotlib.legend.Legend at 0xacff72c>
In [7]:
fig, ax = plt.subplots(figsize=(12,6))

ax.plot(x, x+1, color="blue", linewidth=0.25)
ax.plot(x, x+2, color="blue", linewidth=0.50)
ax.plot(x, x+3, color="blue", linewidth=1.00)
ax.plot(x, x+4, color="blue", linewidth=2.00)

# possible linestype options ‘-‘, ‘–’, ‘-.’, ‘:’, ‘steps’
ax.plot(x, x+5, color="red", lw=2, linestyle='-')
ax.plot(x, x+6, color="red", lw=2, ls='-.')
ax.plot(x, x+7, color="red", lw=2, ls=':')

# custom dash
line, = ax.plot(x, x+8, color="black", lw=1.50)
line.set_dashes([5, 10, 15, 10]) # format: line length, space length, ...

# possible marker symbols: marker = '+', 'o', '*', 's', ',', '.', '1', '2', '3', '4', ...
ax.plot(x, x+ 9, color="green", lw=2, ls='*', marker='+')
ax.plot(x, x+10, color="green", lw=2, ls='*', marker='o')
ax.plot(x, x+11, color="green", lw=2, ls='*', marker='s')
ax.plot(x, x+12, color="green", lw=2, ls='*', marker='1')

# marker size and color
ax.plot(x, x+13, color="purple", lw=1, ls='-', marker='o', markersize=2)
ax.plot(x, x+14, color="purple", lw=1, ls='-', marker='o', markersize=4)
ax.plot(x, x+15, color="purple", lw=1, ls='-', marker='o', markersize=8, markerfacecolor="red")
ax.plot(x, x+16, color="purple", lw=1, ls='-', marker='s', markersize=8, 
        markerfacecolor="yellow", markeredgewidth=2, markeredgecolor="blue");
In [8]:
fig, ax1 = plt.subplots()

ax1.plot(x, x**2, lw=2, color="blue")
ax1.set_ylabel(r"area $(m^2)$", fontsize=18, color="blue")
for label in ax1.get_yticklabels():
    label.set_color("blue")
    
ax2 = ax1.twinx()
ax2.plot(x, x**3, lw=2, color="red")
ax2.set_ylabel(r"volume $(m^3)$", fontsize=18, color="red")
for label in ax2.get_yticklabels():
    label.set_color("red")
In [11]:
n = array([0,1,2,3,4,5])
xx = np.linspace(-0.75, 1., 100)
In [12]:
fig, axes = plt.subplots(1, 4, figsize=(12,3))

axes[0].scatter(xx, xx + 0.25*randn(len(xx)))

axes[1].step(n, n**2, lw=2)

axes[2].bar(n, n**2, align="center", width=0.5, alpha=0.5)

axes[3].fill_between(x, x**2, x**3, color="green", alpha=0.5);
In [13]:
fig = plt.figure()
ax = fig.add_axes([0.0, 0.0, .6, .6], polar=True)
t = linspace(0, 2 * pi, 100)
ax.plot(t, t, color='blue', lw=3);
In [31]:
import matplotlib.gridspec as gridspec
In [32]:
fig = plt.figure()

gs = gridspec.GridSpec(2, 3, height_ratios=[2,1], width_ratios=[1,2,1])
for g in gs:
    ax = fig.add_subplot(g)
    
fig.tight_layout()
In [33]:
alpha = 0.7
phi_ext = 2 * pi * 0.5

def flux_qubit_potential(phi_m, phi_p):
    return 2 + alpha - 2 * cos(phi_p)*cos(phi_m) \
- alpha * cos(phi_ext - 2*phi_p)
In [34]:
phi_m = linspace(0, 2*pi, 100)
phi_p = linspace(0, 2*pi, 100)
X,Y = meshgrid(phi_p, phi_m)
Z = flux_qubit_potential(X, Y).T
In [35]:
fig, ax = plt.subplots()

p = ax.pcolor(X/(2*pi), Y/(2*pi), Z, cmap=cm.RdBu,\
              vmin=abs(Z).min(), vmax=abs(Z).max())
cb = fig.colorbar(p, ax=ax)
In [36]:
fig, ax = plt.subplots()

im = imshow(Z, cmap=cm.RdBu, vmin=abs(Z).min(),\
            vmax=abs(Z).max(), extent=[0, 1, 0, 1])
im.set_interpolation('bilinear')

cb = fig.colorbar(im, ax=ax)
In [37]:
fig, ax = plt.subplots()

cnt = contour(Z, cmap=cm.RdBu, vmin=abs(Z).min(),\
              vmax=abs(Z).max(), extent=[0, 1, 0, 1])

4.matplotlib 3D效果

In [38]:
from mpl_toolkits.mplot3d.axes3d import Axes3D
In [39]:
fig = plt.figure(figsize=(14,6))

# `ax` is a 3D-aware axis instance, because of the projection='3d' keyword argument to add_subplot
ax = fig.add_subplot(1, 2, 1, projection='3d')

p = ax.plot_surface(X, Y, Z, rstride=4, cstride=4, linewidth=0)

# surface_plot with color grading and color bar
ax = fig.add_subplot(1, 2, 2, projection='3d')
p = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, \
                    cmap=cm.coolwarm, linewidth=0, antialiased=False)
cb = fig.colorbar(p, shrink=0.5)
In [23]:
fig = plt.figure(figsize=(8,6))

ax = fig.add_subplot(1, 1, 1, projection='3d')

p = ax.plot_wireframe(X, Y, Z, rstride=4, cstride=4)
In [24]:
fig = plt.figure(figsize=(8,6))

ax = fig.add_subplot(1,1,1, projection='3d')

ax.plot_surface(X, Y, Z, rstride=4, cstride=4, alpha=0.25)
cset = ax.contour(X, Y, Z, zdir='z', offset=-pi, cmap=cm.coolwarm)
cset = ax.contour(X, Y, Z, zdir='x', offset=-pi, cmap=cm.coolwarm)
cset = ax.contour(X, Y, Z, zdir='y', offset=3*pi, cmap=cm.coolwarm)

ax.set_xlim3d(-pi, 2*pi);
ax.set_ylim3d(0, 3*pi);
ax.set_zlim3d(-pi, 2*pi);

  就演示这么多吧,可以看出对于教育、科研、开发具有很强的运算处理,同时很好的记录
也可以很好的演示给他人。写代码时也在写博客。ipython已经非常流行了,再此介绍给
热爱python的伙伴们.今年8月微软捐赠10万美元给ipython为支持其开发,足见其能量。

最后说一下为何ipython版本要高,因为在1.0+版本后有一个nbconvert功能,由于我们看到的
这个网页本身并不是html的,默认是ipynb格式的文件,存储的也都是json格式的内容,我们需要
把它转成html页面。
ipython nbconvert --to html Advance.ipynb

回首页

1.介绍ipython-notebook

2.基本的操作

3.高级处理

   1.matplotlib使用
   2.科学计算的表现
   3.matplotlib更多的例子
   4.matplotlib 3D效果