#!/usr/bin/python3.6

from math import *
import sys

'''
program normalizedKDE.py
	- from the user provided data and the number of bins, this program determines the (Gaussina) kernel density 
	estimation of probability density and store it in file with
	extension .kde  that can be 
	visualized using, e.g., xmgrace or gnuplot

        - example of usage:

        python3 normalizedKDE.py mc.dat 0.05 100

        in this case, data are read from the file mc.dat (one item per line assumed),
	Gaussian kernel functions with standard deviation of 0.05 are used and the result
	is projected onto a regular grid (covering interval between minimal and maximal 
	value found in mc.dat) with 100 points. The result is written into file mc.dat.kde

'''

def gauss_pot(x, x0, w):
    en = e**(-(x-x0)**2/2.0/w**2)
    return en


f = sys.argv[1]
w = float(sys.argv[2])
num = int(sys.argv[3])

ff = f+'.kde'

f = open(f, 'r')

x = []

for line in f.readlines():
    line = line.split()
    x.append(float(line[0]))
f.close()

a0 = min(x)
a1 = max(x)

# c compute norm
norm = len(x) * w * (2*pi)**0.5


step = (a1-a0)/(num-1)
x_write = []
en_write = []
for i in range(num):
    en = 0.0
    x_ = a0 + i * step
    for j in range(len(x)):
        en += gauss_pot(x_, x[j], w)
    x_write.append(x_)
    en_write.append(en)


ff = open(ff, 'w')
for i in range(len(x_write)):
    en = en_write[i] / norm
    ff.write(repr(x_write[i])+ '\t' +repr(en)+ '\n')
ff.close()
