The right imports in a notebook

Following this post http://carreau.github.io/posts/10-No-PyLab-Thanks.ipynb.html, here is ---all in one single cell--- the bits necessary to import most useful libraries in an ipython notebook:

In [1]:
# import numpy and set the printed precision to something humans can read
import numpy as np
np.set_printoptions(precision=2, suppress=True)
# set some prefs for matplotlib
import matplotlib.pyplot as plt
import matplotlib
matplotlib.rcParams.update({'text.usetex': True})
fig_width_pt = 700.  # Get this from LaTeX using \showthe\columnwidth
inches_per_pt = 1.0/72.27               # Convert pt to inches
fig_width = fig_width_pt*inches_per_pt  # width in inches
FORMATS = ['pdf', 'eps']
phi = .5*np.sqrt(5) + .5 # useful ratio for figures
# define plots to be inserted interactively
%matplotlib inline
#%config InlineBackend.figure_format='retina' # high-def PNGs, quite bad when using file versioning
%config InlineBackend.figure_format='svg'

Below, I detail some thoughts on why it is a perfect preamble for most ipython notebooks.

import numpy

In [1]:
# import numpy and set the printed precision to something humans can read
import numpy as np
np.set_printoptions(precision=2, suppress=True)

The golden section ($\phi \approx 1.618033$) gives a nice ratio between the width and height of a figure, it is also close to your display (imacs and many recent displays have a ratio of 16/10) or your phone / tablet / ...

In [2]:
phi = .5*np.sqrt(5) + .5
print r'\phi = ', phi
\phi =  1.61803398875

$\LaTeX$

If you aim at pinting nicely formatted fgures to include into some $\LaTeX$ code, you maywish to include:

In [3]:
import matplotlib
matplotlib.rcParams.update({'text.usetex': True})
fig_width_pt = 700.  # Get this from LaTeX using \showthe\columnwidth
inches_per_pt = 1.0/72.27               # Convert pt to inches
fig_width = fig_width_pt*inches_per_pt  # width in inches

if you export your files to different formats, you may create a list for that:

In [4]:
FORMATS = ['pdf', 'eps']

import interactive pylab

In [5]:
%matplotlib inline
%config InlineBackend.figure_format='retina'
import matplotlib.pyplot as plt

More options can be obtained using ipython's functions:

In [6]:
from IPython.core.pylabtools import figsize, getfigs

such as :

In [7]:
figsize(fig_width, fig_width/phi)

sample

install the LogGabor package

In [8]:
!pip install SLIP
!pip install LogGabor
!pip install NeuroTools
Requirement already satisfied (use --upgrade to upgrade): SLIP in /usr/local/lib/python2.7/site-packages
Cleaning up...
Requirement already satisfied (use --upgrade to upgrade): LogGabor in /usr/local/lib/python2.7/site-packages
Cleaning up...

retrive lena

In [9]:
!curl http://upload.wikimedia.org/wikipedia/en/2/24/Lenna.png -o /tmp/lena.png
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100  462k  100  462k    0     0  1114k      0 --:--:-- --:--:-- --:--:-- 1117k
In [10]:
from SLIP import Image
from LogGabor import LogGabor
from NeuroTools.parameters import ParameterSet
In [11]:
image = plt.imread('/tmp/lena.png').mean(axis=-1)
## alternatively, you may use :
# from scipy.misc import lena
# image = lena()
opts= {'vmin':0., 'vmax':1., 'interpolation':'nearest', 'origin':'upper'}
N_X, N_Y = image.shape
#pe = ParameterSet('default_param.py')
im = Image(ParameterSet({'N_X':N_X, 'N_Y': N_Y}))
lg = LogGabor(im)

fig = plt.figure(figsize=(fig_width, fig_width/phi))
xmin, ymin, size = 0, 0, 1.
for i_level in range(8):
    a = fig.add_axes((xmin/phi, ymin, size/phi, size), axisbg='w')
    a.axis(c='b', lw=0)
    plt.setp(a, xticks=[])
    plt.setp(a, yticks=[])
    im_RGB = np.zeros((N_X, N_Y, 3))
    for theta in np.linspace(0, np.pi, 8, endpoint=False):
        params = {'sf_0':1./(2**i_level), 'B_sf':.4, 'theta':theta, 'B_theta':3.14159/18.}
        # loggabor takes as args: u, v, sf_0, B_sf, theta, B_theta)
        FT_lg = lg.loggabor(0, 0, **params)
        im_abs = np.absolute(im.FTfilter(image, FT_lg, full=True))
        RGB = np.array([.5*np.sin(2*theta + 2*i*np.pi/3)+.5 for i in range(3)])
        im_RGB += im_abs[:,:, np.newaxis] * RGB[np.newaxis, np.newaxis, :]

    im_RGB /= im_RGB.max()
    a.imshow(1. - im_RGB, **opts)
    a.grid(False)
    i_orientation = np.mod(i_level, 4)
    if i_orientation==0:
        xmin += size
        ymin += size/phi**2
    elif i_orientation==1:
        xmin += size/phi**2
        ymin += -size/phi
    elif i_orientation==2:
        xmin += -size/phi
    elif i_orientation==3:
        ymin += size
    size /= phi 
    #print i_orientation, xmin, ymin, size

for ext in FORMATS: fig.savefig('/tmp/fig_log_gabor_filters.' + ext, dpi=450)
No description has been provided for this image
In [13]:
getfigs()
Out[13]:
[]