import numpy as np
import scipy.stats as st
import matplotlib.pyplot as plt
from tools import cdf

# defines the cdf F and pdf f
F = lambda u: (u < 2) * (u >= 0) * (1 - 2 * np.exp(-u / 2.) / 3.) + (u >= 2) * (u <= 3)
f = lambda u: (u >= 0) * (u <= 2) * np.exp(- u / 2.) / 3.

#creates a vector of x and evaluates the cdf F
x = np.linspace(-1, 3, 1000)
y = F(x)

#defines the inverse cdf
intervalPoint = 1-2/3*np.exp(-1)
invF = lambda u: (u < intervalPoint) * (u > 1./3.) * ( - 2 * np.log(3*(1 - u)/2.)) + 2 * (u > intervalPoint)

# generates plots
n = [10, 100, 1000]
fig = plt.figure(figsize = (12, 4))

for i in range(3):
	U = st.uniform.rvs(size = (n[i],))
	X = invF(U)

	[xx, Nxx] = cdf(X, [-1, 3])
	ax1 = fig.add_subplot(1,3,i+1)
	ax1.plot(x,y, linewidth = 1.)
	ax1.plot(xx, Nxx, linewidth = 1.)
	ax1.set_title('n = ' + str(n[i]))

plt.show()
