import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import matplotlib.ticker as ticker
from plotstyle import *

# normal distribution:
rng = np.random.RandomState(6281)
x = np.arange(-4.0, 4.0, 0.01)
g = np.exp(-0.5*x*x)/np.sqrt(2.0*np.pi)
r = rng.randn(100)

def kerneldensity(data, xmin, xmax, sigma=1.0) :
    dx = 0.05*sigma
    xg = np.arange(-4.0*sigma, 4.0*sigma + 0.5*dx, dx)
    gauss = np.exp(-0.5*xg*xg/sigma/sigma)/np.sqrt(2.0*np.pi)/sigma
    ng = len(gauss)//2
    x = np.arange(xmin, xmax+0.5*dx, dx)
    kd = np.zeros(len(x))
    for xd in data:
        inx = int((xd-xmin)/dx)
        k0 = inx-ng
        k1 = inx+ng+1
        g0 = 0
        g1 = len(gauss)
        if inx < ng:
            k0 = 0
            g0 = ng-inx
        if inx >= len(kd)-ng:
            k1 = len(kd)
            g1 = len(gauss)-(inx+ng-len(kd)+1)
        kd[k0:k1] += gauss[g0:g1]
    kd /= len(data)
    return kd, x

fig = plt.figure()
spec = gridspec.GridSpec(nrows=2, ncols=2, wspace=0.35, hspace=0.3,
                         **adjust_fs(fig, left=5.5, top=0.2, bottom=2.7))

ax = fig.add_subplot(spec[0, 0])
ax.set_xlim(-3.2, 3.2)
ax.xaxis.set_major_locator(ticker.MultipleLocator(1.0))
ax.xaxis.set_major_formatter(ticker.NullFormatter())
ax.set_ylabel('p(x)')
ax.set_ylim(0.0, 0.49)
ax.yaxis.set_major_locator(ticker.MultipleLocator(0.2))
if mpl_major > 1:
    ax.hist(r, np.arange(-4.1, 4, 0.4), density=True, zorder=-5, **fsC)
else:
    ax.hist(r, np.arange(-4.1, 4, 0.4), normed=True, zorder=-5, **fsC)

ax = fig.add_subplot(spec[1, 0])
ax.set_xlabel('x')
ax.set_xlim(-3.2, 3.2)
ax.xaxis.set_major_locator(ticker.MultipleLocator(1.0))
ax.set_ylabel('p(x)')
ax.set_ylim(0.0, 0.49)
ax.yaxis.set_major_locator(ticker.MultipleLocator(0.2))
if mpl_major > 1:
    ax.hist(r, np.arange(-4.3, 4, 0.4), density=True, zorder=-5, **fsC)
else:
    ax.hist(r, np.arange(-4.3, 4, 0.4), normed=True, zorder=-5, **fsC)

ax = fig.add_subplot(spec[:, 1])
ax.set_xlabel('x')
ax.set_xlim(-3.2, 3.2)
ax.xaxis.set_major_locator(ticker.MultipleLocator(1.0))
ax.set_ylabel('Prob. density p(x)')
ax.set_ylim(0.0, 0.49)
ax.set_yticks(np.arange(0.0, 0.41, 0.1))
kd, xx = kerneldensity(r, -3.2, 3.2, 0.2)
ax.fill_between(xx, 0.0, kd, zorder=-5, **fsDs)
ax.plot(xx, kd, '-', zorder=-1, **lsB)

fig.savefig('kerneldensity.pdf')