#ogranicen nosac - gama jezgro
x<-rexp(100)
n<-length(x)
h<-0.9*min(IQR(x)/1.34,sd(x))*n^(-1/5)
H<-seq(0.05*h,1.5*h,(1.5*h-0.05*h)/100)
fh<-matrix(0,length(H),n)
#ocene se odredjuju u svakoj tacki x_i
for (j in 1:n){
  for (i in 1:n){
    if(i!=j){
      f<-dgamma(x[i],x[j]/H+1,1/H) #jezgro u tacki
      fh[,j]<-fh[,j]+f/(n) #ukupna gustina
    }
  }
}
#funkcija koja se maksimizuje: CV(h)=sum(log(f_{-i}(X_i)))/n
suma<-rep(0,length(H))
for(i in 1:length(H)){
  suma[i]<-sum(log(fh[i,]))/n
}
plot(H, suma, type = "l")
h1<-H[which.max(suma)]

y<-seq(-1,4,0.01)
f<-c()
for(j in 1:length(y)){
  suma<-0
  for(i in 1:n){
    suma<-suma+dgamma(x[i],y[j]/h1+1,1/h1)
  }
  f[j]<-suma
}
fh<-f/n #ocena gustine jezgrom
fh2<-c()
for(i in 1:length(y)){
  if(y[i]<0)
    fh2[i]<-0
  else
    fh2[i]<-fh[i]
}
plot(y, fh2, type = 'l', xlim = c(-1,5))
lines(sort(x),dexp(sort(x)), col='red')
Kn<-function(t){
  return(exp(-t^2/2)/sqrt(2*pi))
}
f1<-c()
for(j in 1:length(y)){
  suma<-0
  for(i in 1:n){
    suma<-suma+Kn((y[j]-x[i])/h)
  }
  f1[j]<-suma
}
fh1<-f1/(h*n)
lines(y,fh1, col='blue')
