In [2]:
%load_ext Cython

In [9]:
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
def initialize(size):
    x, y = np.meshgrid(np.linspace(-2, 1, size),
                       np.linspace(-1.5, 1.5, size))
    c = x + 1j*y
    z = c.copy()
    m = np.zeros((size, size))
    return c, z, m
size = 200
iterations = 100
        
def mandelbrot_numpy(c, z, m, iterations):
    for n in range(iterations):
        indices = np.abs(z) <= 10
        z[indices] = z[indices]**2 + c[indices]
        m[indices] = n

In [4]:
%%timeit -n1 -r10 c, z, m = initialize(size)
mandelbrot_numpy(c, z, m, iterations)


1 loops, best of 10: 67.7 ms per loop

In [11]:
%%cython
import numpy as np
def mandelbrot_cython(m,size, iterations):
    for i in range(size):
            for j in range(size):
                c = -2 + 3./size*j + 1j*(1.5-3./size*i)
                z = 0
                for n in range(iterations):
                    if np.abs(z) <= 10:
                        z = z*z + c
                        m[i, j] = n
                    else:
                        break

In [20]:
%%cython -a
import numpy as np
def fast_mandelbrot_cython(int[:,::1] m,
                      int size,
                      int iterations):
    cdef int i, j, n
    cdef complex z, c
    for i in range(size):
        for j in range(size):
            c = -2 + 3./size*j + 1j*(1.5-3./size*i)
            z = 0
            for n in range(iterations):
                if z.real**2 + z.imag**2 <= 100:
                   z = z*z + c
                   m[i, j] = n
                else:
                    break


Out[20]:
Cython: _cython_magic_47ad813afb342fe6360927ea406cd857.pyx

Generated by Cython 0.23.1

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: import numpy as np
  __pyx_t_1 = __Pyx_Import(__pyx_n_s_numpy, 0, -1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
  __Pyx_GOTREF(__pyx_t_1);
  if (PyDict_SetItem(__pyx_d, __pyx_n_s_np, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
  __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
/* … */
  __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
  __Pyx_GOTREF(__pyx_t_1);
  if (PyDict_SetItem(__pyx_d, __pyx_n_s_test, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
  __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
+02: def fast_mandelbrot_cython(int[:,::1] m,
/* Python wrapper */
static PyObject *__pyx_pw_46_cython_magic_47ad813afb342fe6360927ea406cd857_1fast_mandelbrot_cython(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/
static PyMethodDef __pyx_mdef_46_cython_magic_47ad813afb342fe6360927ea406cd857_1fast_mandelbrot_cython = {"fast_mandelbrot_cython", (PyCFunction)__pyx_pw_46_cython_magic_47ad813afb342fe6360927ea406cd857_1fast_mandelbrot_cython, METH_VARARGS|METH_KEYWORDS, 0};
static PyObject *__pyx_pw_46_cython_magic_47ad813afb342fe6360927ea406cd857_1fast_mandelbrot_cython(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) {
  __Pyx_memviewslice __pyx_v_m = { 0, 0, { 0 }, { 0 }, { 0 } };
  int __pyx_v_size;
  int __pyx_v_iterations;
  PyObject *__pyx_r = 0;
  __Pyx_RefNannyDeclarations
  __Pyx_RefNannySetupContext("fast_mandelbrot_cython (wrapper)", 0);
  {
    static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_m,&__pyx_n_s_size,&__pyx_n_s_iterations,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_m)) != 0)) kw_args--;
        else goto __pyx_L5_argtuple_error;
        case  1:
        if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_size)) != 0)) kw_args--;
        else {
          __Pyx_RaiseArgtupleInvalid("fast_mandelbrot_cython", 1, 3, 3, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2; __pyx_clineno = __LINE__; goto __pyx_L3_error;}
        }
        case  2:
        if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_iterations)) != 0)) kw_args--;
        else {
          __Pyx_RaiseArgtupleInvalid("fast_mandelbrot_cython", 1, 3, 3, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2; __pyx_clineno = __LINE__; goto __pyx_L3_error;}
        }
      }
      if (unlikely(kw_args > 0)) {
        if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "fast_mandelbrot_cython") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2; __pyx_clineno = __LINE__; goto __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_m = __Pyx_PyObject_to_MemoryviewSlice_d_dc_int(values[0]); if (unlikely(!__pyx_v_m.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2; __pyx_clineno = __LINE__; goto __pyx_L3_error;}
    __pyx_v_size = __Pyx_PyInt_As_int(values[1]); if (unlikely((__pyx_v_size == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3; __pyx_clineno = __LINE__; goto __pyx_L3_error;}
    __pyx_v_iterations = __Pyx_PyInt_As_int(values[2]); if (unlikely((__pyx_v_iterations == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4; __pyx_clineno = __LINE__; goto __pyx_L3_error;}
  }
  goto __pyx_L4_argument_unpacking_done;
  __pyx_L5_argtuple_error:;
  __Pyx_RaiseArgtupleInvalid("fast_mandelbrot_cython", 1, 3, 3, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2; __pyx_clineno = __LINE__; goto __pyx_L3_error;}
  __pyx_L3_error:;
  __Pyx_AddTraceback("_cython_magic_47ad813afb342fe6360927ea406cd857.fast_mandelbrot_cython", __pyx_clineno, __pyx_lineno, __pyx_filename);
  __Pyx_RefNannyFinishContext();
  return NULL;
  __pyx_L4_argument_unpacking_done:;
  __pyx_r = __pyx_pf_46_cython_magic_47ad813afb342fe6360927ea406cd857_fast_mandelbrot_cython(__pyx_self, __pyx_v_m, __pyx_v_size, __pyx_v_iterations);
  int __pyx_lineno = 0;
  const char *__pyx_filename = NULL;
  int __pyx_clineno = 0;

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

static PyObject *__pyx_pf_46_cython_magic_47ad813afb342fe6360927ea406cd857_fast_mandelbrot_cython(CYTHON_UNUSED PyObject *__pyx_self, __Pyx_memviewslice __pyx_v_m, int __pyx_v_size, int __pyx_v_iterations) {
  int __pyx_v_i;
  int __pyx_v_j;
  int __pyx_v_n;
  __pyx_t_double_complex __pyx_v_z;
  __pyx_t_double_complex __pyx_v_c;
  PyObject *__pyx_r = NULL;
  __Pyx_RefNannyDeclarations
  __Pyx_RefNannySetupContext("fast_mandelbrot_cython", 0);
/* … */
  /* function exit code */
  __pyx_r = Py_None; __Pyx_INCREF(Py_None);
  goto __pyx_L0;
  __pyx_L1_error:;
  __Pyx_AddTraceback("_cython_magic_47ad813afb342fe6360927ea406cd857.fast_mandelbrot_cython", __pyx_clineno, __pyx_lineno, __pyx_filename);
  __pyx_r = NULL;
  __pyx_L0:;
  __PYX_XDEC_MEMVIEW(&__pyx_v_m, 1);
  __Pyx_XGIVEREF(__pyx_r);
  __Pyx_RefNannyFinishContext();
  return __pyx_r;
}
/* … */
  __pyx_tuple__14 = PyTuple_Pack(8, __pyx_n_s_m, __pyx_n_s_size, __pyx_n_s_iterations, __pyx_n_s_i, __pyx_n_s_j, __pyx_n_s_n, __pyx_n_s_z, __pyx_n_s_c); if (unlikely(!__pyx_tuple__14)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
  __Pyx_GOTREF(__pyx_tuple__14);
  __Pyx_GIVEREF(__pyx_tuple__14);
/* … */
  __pyx_t_1 = PyCFunction_NewEx(&__pyx_mdef_46_cython_magic_47ad813afb342fe6360927ea406cd857_1fast_mandelbrot_cython, NULL, __pyx_n_s_cython_magic_47ad813afb342fe636); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
  __Pyx_GOTREF(__pyx_t_1);
  if (PyDict_SetItem(__pyx_d, __pyx_n_s_fast_mandelbrot_cython, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
  __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
  __pyx_codeobj__15 = (PyObject*)__Pyx_PyCode_New(3, 0, 8, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__14, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_home_stephan_cache_ipython_cyth, __pyx_n_s_fast_mandelbrot_cython, 2, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__15)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
 03:                       int size,
 04:                       int iterations):
 05:     cdef int i, j, n
 06:     cdef complex z, c
+07:     for i in range(size):
  __pyx_t_1 = __pyx_v_size;
  for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) {
    __pyx_v_i = __pyx_t_2;
+08:         for j in range(size):
    __pyx_t_3 = __pyx_v_size;
    for (__pyx_t_4 = 0; __pyx_t_4 < __pyx_t_3; __pyx_t_4+=1) {
      __pyx_v_j = __pyx_t_4;
+09:             c = -2 + 3./size*j + 1j*(1.5-3./size*i)
      if (unlikely(__pyx_v_size == 0)) {
        PyErr_SetString(PyExc_ZeroDivisionError, "float division");
        {__pyx_filename = __pyx_f[0]; __pyx_lineno = 9; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
      }
      if (unlikely(__pyx_v_size == 0)) {
        PyErr_SetString(PyExc_ZeroDivisionError, "float division");
        {__pyx_filename = __pyx_f[0]; __pyx_lineno = 9; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
      }
      __pyx_v_c = __Pyx_c_sum(__pyx_t_double_complex_from_parts((-2.0 + ((3. / __pyx_v_size) * __pyx_v_j)), 0), __Pyx_c_prod(__pyx_t_double_complex_from_parts(0, 1.0), __pyx_t_double_complex_from_parts((1.5 - ((3. / __pyx_v_size) * __pyx_v_i)), 0)));
+10:             z = 0
      __pyx_v_z = __pyx_t_double_complex_from_parts(0, 0);
+11:             for n in range(iterations):
      __pyx_t_5 = __pyx_v_iterations;
      for (__pyx_t_6 = 0; __pyx_t_6 < __pyx_t_5; __pyx_t_6+=1) {
        __pyx_v_n = __pyx_t_6;
+12:                 if z.real**2 + z.imag**2 <= 100:
        __pyx_t_7 = (((pow(__Pyx_CREAL(__pyx_v_z), 2.0) + pow(__Pyx_CIMAG(__pyx_v_z), 2.0)) <= 100.0) != 0);
        if (__pyx_t_7) {
/* … */
          goto __pyx_L9;
        }
+13:                    z = z*z + c
          __pyx_v_z = __Pyx_c_sum(__Pyx_c_prod(__pyx_v_z, __pyx_v_z), __pyx_v_c);
+14:                    m[i, j] = n
          __pyx_t_8 = __pyx_v_i;
          __pyx_t_9 = __pyx_v_j;
          __pyx_t_10 = -1;
          if (__pyx_t_8 < 0) {
            __pyx_t_8 += __pyx_v_m.shape[0];
            if (unlikely(__pyx_t_8 < 0)) __pyx_t_10 = 0;
          } else if (unlikely(__pyx_t_8 >= __pyx_v_m.shape[0])) __pyx_t_10 = 0;
          if (__pyx_t_9 < 0) {
            __pyx_t_9 += __pyx_v_m.shape[1];
            if (unlikely(__pyx_t_9 < 0)) __pyx_t_10 = 1;
          } else if (unlikely(__pyx_t_9 >= __pyx_v_m.shape[1])) __pyx_t_10 = 1;
          if (unlikely(__pyx_t_10 != -1)) {
            __Pyx_RaiseBufferIndexError(__pyx_t_10);
            {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
          }
          *((int *) ( /* dim=1 */ ((char *) (((int *) ( /* dim=0 */ (__pyx_v_m.data + __pyx_t_8 * __pyx_v_m.strides[0]) )) + __pyx_t_9)) )) = __pyx_v_n;
 15:                 else:
+16:                     break
        /*else*/ {
          goto __pyx_L8_break;
        }
        __pyx_L9:;
      }
      __pyx_L8_break:;
    }
  }

In [16]:
%%timeit
size = 200
iterations = 100
m = np.zeros((size, size))
mandelbrot_cython(m, size, iterations)


1 loops, best of 3: 1.29 s per loop

In [19]:
%%timeit -n1 -r1 m = np.zeros((size, size),dtype=np.int32)
fast_mandelbrot_cython(m, size, iterations)


1 loops, best of 1: 6.37 ms per loop

In [15]:
import matplotlib.pyplot as plt
%matplotlib inline
plt.imshow(np.log(m), cmap=plt.cm.hot)
plt.xticks([]); plt.yticks([])


Out[15]:
([], <a list of 0 Text yticklabel objects>)

In [21]:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
%matplotlib inline

In [22]:
np.random.seed(12)
for i in range(8):
    x = np.arange(1000)
    y = np.random.randn(1000).cumsum()
    plt.plot(x, y, label=str(i))
    plt.legend()



In [24]:
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline

In [25]:
x1 = np.random.randn(80)
x2 = np.random.randn(80)
x3 = x1 * x2
y1 = .5 + 2 * x1 - x2 + 2.5 * x3 + \
      3 * np.random.randn(80)
y2 = .5 + 2 * x1 - x2 + 2.5 * np.random.randn(80)
y3 = y2 + np.random.randn(80)

In [29]:
sns.violinplot([x1,y2, y3])


Out[29]:
<matplotlib.axes._subplots.AxesSubplot at 0x7f143592ced0>

In [27]:
sns.regplot(x2, y2)


Out[27]:
<matplotlib.axes._subplots.AxesSubplot at 0x7f142783a1d0>

In [34]:
import pandas as pd
df = pd.DataFrame(dict(x1=x1, x2=x2, x3=x3, 
                        y1=y1, y2=y2, y3=y3))
sns.corrplot(df)


Out[34]:
<matplotlib.axes._subplots.AxesSubplot at 0x7f142704c190>

In [ ]: