Winpython Default checker

In [1]:
%matplotlib inline

Compilers: Numba and Cython

Numba (a JIT Compiler)

Windows 7 and 8 users may have to install "Microsoft Visual C++ 2015 Redistributable" at https://www.visualstudio.com/downloads/download-visual-studio-vs#d-visual-c

In [2]:
# checking Numba JIT toolchain
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
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()
Mandelbrot created by numba in 3.516329 s
Cython (a compiler for writing C extensions for the Python language)

WinPython 3.5 users may not have mingwpy available, and so need "VisualStudio C++ Community Edition 2015" https://www.visualstudio.com/downloads/download-visual-studio-vs#d-visual-c

In [3]:
# Cython + Mingwpy compiler toolchain test
%load_ext Cython
In [4]:
%%cython -a
# with %%cython -a , full C-speed lines are shown in white, slowest python-speed lines are shown in dark yellow lines 
# ==> put your cython rewrite effort on dark yellow lines
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
Out[4]:
Cython: _cython_magic_e73dd6dd78c429b832522f398af62efb.pyx

Generated by Cython 0.24

Yellow lines hint at Python interaction.
Click on a line that starts with a "+" to see the C code that Cython generated for it.

 01: # with %%cython -a , full C-speed lines are shown in white, slowest python-speed lines are shown in dark yellow lines 
 02: # ==> put your cython rewrite effort on dark yellow lines
+03: def mandel_cython(x, y, max_iters):
/* Python wrapper */
static PyObject *__pyx_pw_46_cython_magic_e73dd6dd78c429b832522f398af62efb_1mandel_cython(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/
static PyMethodDef __pyx_mdef_46_cython_magic_e73dd6dd78c429b832522f398af62efb_1mandel_cython = {"mandel_cython", (PyCFunction)__pyx_pw_46_cython_magic_e73dd6dd78c429b832522f398af62efb_1mandel_cython, METH_VARARGS|METH_KEYWORDS, 0};
static PyObject *__pyx_pw_46_cython_magic_e73dd6dd78c429b832522f398af62efb_1mandel_cython(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) {
  PyObject *__pyx_v_x = 0;
  PyObject *__pyx_v_y = 0;
  PyObject *__pyx_v_max_iters = 0;
  PyObject *__pyx_r = 0;
  __Pyx_RefNannyDeclarations
  __Pyx_RefNannySetupContext("mandel_cython (wrapper)", 0);
  {
    static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_x,&__pyx_n_s_y,&__pyx_n_s_max_iters,0};
    PyObject* values[3] = {0,0,0};
    if (unlikely(__pyx_kwds)) {
      Py_ssize_t kw_args;
      const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args);
      switch (pos_args) {
        case  3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2);
        case  2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1);
        case  1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0);
        case  0: break;
        default: goto __pyx_L5_argtuple_error;
      }
      kw_args = PyDict_Size(__pyx_kwds);
      switch (pos_args) {
        case  0:
        if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_x)) != 0)) kw_args--;
        else goto __pyx_L5_argtuple_error;
        case  1:
        if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_y)) != 0)) kw_args--;
        else {
          __Pyx_RaiseArgtupleInvalid("mandel_cython", 1, 3, 3, 1); __PYX_ERR(0, 3, __pyx_L3_error)
        }
        case  2:
        if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_max_iters)) != 0)) kw_args--;
        else {
          __Pyx_RaiseArgtupleInvalid("mandel_cython", 1, 3, 3, 2); __PYX_ERR(0, 3, __pyx_L3_error)
        }
      }
      if (unlikely(kw_args > 0)) {
        if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "mandel_cython") < 0)) __PYX_ERR(0, 3, __pyx_L3_error)
      }
    } else if (PyTuple_GET_SIZE(__pyx_args) != 3) {
      goto __pyx_L5_argtuple_error;
    } else {
      values[0] = PyTuple_GET_ITEM(__pyx_args, 0);
      values[1] = PyTuple_GET_ITEM(__pyx_args, 1);
      values[2] = PyTuple_GET_ITEM(__pyx_args, 2);
    }
    __pyx_v_x = values[0];
    __pyx_v_y = values[1];
    __pyx_v_max_iters = values[2];
  }
  goto __pyx_L4_argument_unpacking_done;
  __pyx_L5_argtuple_error:;
  __Pyx_RaiseArgtupleInvalid("mandel_cython", 1, 3, 3, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 3, __pyx_L3_error)
  __pyx_L3_error:;
  __Pyx_AddTraceback("_cython_magic_e73dd6dd78c429b832522f398af62efb.mandel_cython", __pyx_clineno, __pyx_lineno, __pyx_filename);
  __Pyx_RefNannyFinishContext();
  return NULL;
  __pyx_L4_argument_unpacking_done:;
  __pyx_r = __pyx_pf_46_cython_magic_e73dd6dd78c429b832522f398af62efb_mandel_cython(__pyx_self, __pyx_v_x, __pyx_v_y, __pyx_v_max_iters);

  /* function exit code */
  __Pyx_RefNannyFinishContext();
  return __pyx_r;
}

static PyObject *__pyx_pf_46_cython_magic_e73dd6dd78c429b832522f398af62efb_mandel_cython(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_x, PyObject *__pyx_v_y, PyObject *__pyx_v_max_iters) {
  int __pyx_v_i;
  double __pyx_v_cx;
  double __pyx_v_cy;
  double __pyx_v_zx;
  double __pyx_v_zy;
  PyObject *__pyx_r = NULL;
  __Pyx_RefNannyDeclarations
  __Pyx_RefNannySetupContext("mandel_cython", 0);
/* … */
  /* function exit code */
  __pyx_L1_error:;
  __Pyx_XDECREF(__pyx_t_6);
  __Pyx_AddTraceback("_cython_magic_e73dd6dd78c429b832522f398af62efb.mandel_cython", __pyx_clineno, __pyx_lineno, __pyx_filename);
  __pyx_r = NULL;
  __pyx_L0:;
  __Pyx_XGIVEREF(__pyx_r);
  __Pyx_RefNannyFinishContext();
  return __pyx_r;
}
/* … */
  __pyx_tuple_ = PyTuple_Pack(8, __pyx_n_s_x, __pyx_n_s_y, __pyx_n_s_max_iters, __pyx_n_s_i, __pyx_n_s_cx, __pyx_n_s_cy, __pyx_n_s_zx, __pyx_n_s_zy); if (unlikely(!__pyx_tuple_)) __PYX_ERR(0, 3, __pyx_L1_error)
  __Pyx_GOTREF(__pyx_tuple_);
  __Pyx_GIVEREF(__pyx_tuple_);
/* … */
  __pyx_t_1 = PyCFunction_NewEx(&__pyx_mdef_46_cython_magic_e73dd6dd78c429b832522f398af62efb_1mandel_cython, NULL, __pyx_n_s_cython_magic_e73dd6dd78c429b832); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 3, __pyx_L1_error)
  __Pyx_GOTREF(__pyx_t_1);
  if (PyDict_SetItem(__pyx_d, __pyx_n_s_mandel_cython, __pyx_t_1) < 0) __PYX_ERR(0, 3, __pyx_L1_error)
  __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
 04:   cdef int   i
 05:   cdef double   cx, cy , zx, zy
+06:   cx , cy = x, y
  __pyx_t_1 = __pyx_PyFloat_AsDouble(__pyx_v_x); if (unlikely((__pyx_t_1 == (double)-1) && PyErr_Occurred())) __PYX_ERR(0, 6, __pyx_L1_error)
  __pyx_t_2 = __pyx_PyFloat_AsDouble(__pyx_v_y); if (unlikely((__pyx_t_2 == (double)-1) && PyErr_Occurred())) __PYX_ERR(0, 6, __pyx_L1_error)
  __pyx_v_cx = __pyx_t_1;
  __pyx_v_cy = __pyx_t_2;
+07:   zx , zy =0 ,0
  __pyx_t_2 = 0.0;
  __pyx_t_1 = 0.0;
  __pyx_v_zx = __pyx_t_2;
  __pyx_v_zy = __pyx_t_1;
+08:   for i in range(max_iters):
  __pyx_t_3 = __Pyx_PyInt_As_long(__pyx_v_max_iters); if (unlikely((__pyx_t_3 == (long)-1) && PyErr_Occurred())) __PYX_ERR(0, 8, __pyx_L1_error)
  for (__pyx_t_4 = 0; __pyx_t_4 < __pyx_t_3; __pyx_t_4+=1) {
    __pyx_v_i = __pyx_t_4;
+09:     zx , zy = zx*zx - zy*zy + cx , zx*zy*2 + cy
    __pyx_t_1 = (((__pyx_v_zx * __pyx_v_zx) - (__pyx_v_zy * __pyx_v_zy)) + __pyx_v_cx);
    __pyx_t_2 = (((__pyx_v_zx * __pyx_v_zy) * 2.0) + __pyx_v_cy);
    __pyx_v_zx = __pyx_t_1;
    __pyx_v_zy = __pyx_t_2;
+10:     if (zx*zx + zy*zy) >= 4:
    __pyx_t_5 = ((((__pyx_v_zx * __pyx_v_zx) + (__pyx_v_zy * __pyx_v_zy)) >= 4.0) != 0);
    if (__pyx_t_5) {
/* … */
    }
  }
+11:       return i
      __Pyx_XDECREF(__pyx_r);
      __pyx_t_6 = __Pyx_PyInt_From_int(__pyx_v_i); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 11, __pyx_L1_error)
      __Pyx_GOTREF(__pyx_t_6);
      __pyx_r = __pyx_t_6;
      __pyx_t_6 = 0;
      goto __pyx_L0;
+12:   return max_iters
  __Pyx_XDECREF(__pyx_r);
  __Pyx_INCREF(__pyx_v_max_iters);
  __pyx_r = __pyx_v_max_iters;
  goto __pyx_L0;
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()
Mandelbrot created by cython in 1.351458 s

Graphics: Matplotlib, Pandas, Seaborn, bqplot, Bokeh, Holoviews

In [6]:
# Matplotlib
# for more examples, see: http://matplotlib.org/gallery.html
from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
from matplotlib import cm

fig = plt.figure()
ax = fig.gca(projection='3d')
X, Y, Z = axes3d.get_test_data(0.05)
ax.plot_surface(X, Y, Z, rstride=8, cstride=8, alpha=0.3)
cset = ax.contourf(X, Y, Z, zdir='z', offset=-100, cmap=cm.coolwarm)
cset = ax.contourf(X, Y, Z, zdir='x', offset=-40, cmap=cm.coolwarm)
cset = ax.contourf(X, Y, Z, zdir='y', offset=40, cmap=cm.coolwarm)

ax.set_xlabel('X')
ax.set_xlim(-40, 40)
ax.set_ylabel('Y')
ax.set_ylim(-40, 40)
ax.set_zlabel('Z')
ax.set_zlim(-100, 100)

plt.show()
In [7]:
%matplotlib inline
# Pandas interactive
import pandas as pd
import numpy as np
import seaborn as sns

# create a df with random datas
np.random.seed(24)
df = pd.DataFrame({'A': np.linspace(1, 10, 10)})
df = pd.concat([df, pd.DataFrame(np.random.randn(10, 4), columns=list('BCDE'))],
               axis=1)
df.iloc[0, 2] = np.nan

# interactive
from IPython.html import widgets
@widgets.interact
def f(h_neg=(0, 359, 1), h_pos=(0, 359), s=(0., 99.9), l=(0., 99.9)):
    return (df
             .style
             .background_gradient(
                cmap=sns.palettes.diverging_palette(
                     h_neg=h_neg, h_pos=h_pos, s=s, l=l, as_cmap=True)
             ).highlight_null()
           )
A B C D E
0 1 1.32921 nan -0.31628 -0.99081
1 2 -1.07082 -1.43871 0.564417 0.295722
2 3 -1.6264 0.219565 0.678805 1.88927
3 4 0.961538 0.104011 -0.481165 0.850229
4 5 1.45342 1.05774 0.165562 0.515018
5 6 -1.33694 0.562861 1.39285 -0.063328
6 7 0.121668 1.2076 -0.00204021 1.6278
7 8 0.354493 1.03753 -0.385684 0.519818
8 9 1.68658 -1.32596 1.42898 -2.08935
9 10 -0.12982 0.631523 -0.586538 0.29072
In [8]:
# Seaborn
# for more examples, see http://stanford.edu/~mwaskom/software/seaborn/examples/index.html
import seaborn as sns
sns.set()
df = sns.load_dataset("iris")
sns.pairplot(df, hue="species", size=1.5)
Out[8]:
<seaborn.axisgrid.PairGrid at 0xbb6e470>
In [9]:
#bqplot
from IPython.display import display
from bqplot import (Figure, Map, Mercator, Orthographic, ColorScale, ColorAxis,
                    AlbersUSA, topo_load, Tooltip)
def_tt = Tooltip(fields=['id', 'name'])
map_mark = Map(scales={'projection': Mercator()}, tooltip=def_tt)
map_mark.interactions = {'click': 'select', 'hover': 'tooltip'}
fig = Figure(marks=[map_mark], title='Interactions Example')
display(fig)
In [10]:
# ipyleaflet (javascript library usage)
from ipyleaflet import (
    Map, Marker, TileLayer, ImageOverlay, Polyline, Polygon,
    Rectangle, Circle, CircleMarker, GeoJSON, DrawControl
)
from traitlets import link
center = [34.6252978589571, -77.34580993652344]
m = Map(center=[34.6252978589571, -77.34580993652344], zoom=10)
dc = DrawControl()

def handle_draw(self, action, geo_json):
    print(action)
    print(geo_json)
m
m
In [11]:
dc.on_draw(handle_draw)
m.add_control(dc)
In [12]:
# Bokeh 0.11.0
# for more examples, see http://nbviewer.jupyter.org/github/bokeh/bokeh-notebooks/blob/master/index.ipynb
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import os
from bokeh import mpl
from bokeh.plotting import output_notebook, show
import matplotlib as mplc
# Generate the pandas dataframe
data = np.random.multivariate_normal([0, 0], [[1, 2], [2, 20]], size=100)
data = pd.DataFrame(data, columns=["X", "Y"])
mplc.rc("figure", figsize=(6, 6))

# Just plot seaborn kde
import seaborn as sns
sns.kdeplot(data, cmap="BuGn_d")

plt.title("Seaborn kdeplot in bokeh.")

from bokeh.resources import INLINE
# default solution output_notebook() relies on pydata.org (but spare 2Mo of inline jsscript in your notebook)
# other method to get internal bokeh script can be
#    os.environ['BOKEH_RESOURCES'] = 'inline'
output_notebook(resources=INLINE)

show(mpl.to_bokeh())
Loading BokehJS ...