#!/usr/local/bin/pythonw
# coding: iso-8859-1
# Copyright © 2009 by Amos Newcombe
# 
# This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License along with this program.  If not, see <http://www.gnu.org/licenses/>.

'''the Gaussian distribution, in standard and general form
'''

from math import exp, pi, sqrt
from random import gauss
from mathlib.Gamma import IGamma, InverseIGamma
from Probability import Probability, Affine

class StdGaussian(Probability):

	def	Distribution(self, xX):
		if xX == 0.0: return 0.5
		p = (IGamma(0.5, xX*xX/2.0) + 1.0) / 2.0
		if xX < 0.0: p = 1.0 - p
		return p

	def Density(self, xX):
		return 1/sqrt(2.0*pi) * exp(-xX*xX/2.0)

	def InverseDistribution(self, xY, xEpsilon=1e-7):
# 		print '%s.InverseDistribution(%g)' % (self.__class__.__name__, xY)
		if xY < 0. or 1. < xY:
			raise ValueError, 'y = %s is outside of [0,1]' % xY
		if xY == 0.5: return 0.0
		xX = sqrt(2. * InverseIGamma(0.5, abs(2.*xY-1), xEpsilon))
		if xY < 0.5: xX = -xX
		return xX
	
	def Sample(self): return gauss(0., 1.)
	
	def getMean(self): return 0.
	def getVariance(self): return 1.

class Gaussian(Affine):
	
	def __init__(self, xMu=0., xSigma=1.):
		Affine.__init__(self, StdGaussian(), xMu, xSigma)
	
	def __repr__(self):
		return '%s(%s,%s)' % (self.__class__.__name__, self.xM, self.xS)

if __name__ == '__main__':
	
# 	from ProbTester import ProbTester
	prob = StdGaussian()
	print prob.Distribution(0.5) - prob.Distribution(-0.5)
	
