def test_findTruncNormalRoots(self): """Tests whether our root finder for a truncated normal works in the case of a standard normal truncated at 0""" from numpy import sqrt from math import pi # These are the analytic values of mean and variance of a standard normal # truncated on the left at 0. truncMean = 2.0 / sqrt(2*pi) truncVarnce = 1.0 - 4.0/(2.0*pi) muInit = truncMean sigmaInit = sqrt(truncVarnce) minThreshRefl = 0 mu, sigma = findTruncNormalRoots(truncMean,truncVarnce, muInit,sigmaInit, minThreshRefl) self.assertAlmostEqual(mu, 0, places=10) self.assertAlmostEqual(sigma, 1, places=10)
plt.xlabel('Time [' + time_offset_radar_refl.units + ']') plt.ylabel('Altitude [m]') plt.figure() radar_refl_nc.close() # Compute mean and variance of truncated time series truncMean = mean( reflCompressed ) truncVarnce = var( reflCompressed ) print "truncMean = %s" %truncMean print "sqrt(truncVarnce) = %s" %sqrt(truncVarnce) # Compute parameters of truncated normal distribution muInit = 2*truncMean sigmaInit = 2*sqrt(truncVarnce) mu, sigma = findTruncNormalRoots(truncMean,truncVarnce,muInit,sigmaInit,minThreshRefl) print "mu = %s" %mu print "sigma = %s" %sigma # Compute empirical distribution function of data reflCompressedSorted = sort(reflCompressed) reflEdf = (rankdata(reflCompressedSorted) - 1)/lenReflCompressed normCdf = norm.cdf( reflCompressedSorted, loc=truncMean, scale=sqrt(truncVarnce) ) truncNormCdf = ( norm.cdf(reflCompressedSorted,mu,sigma) \ - norm.cdf((minRefl-mu)/sigma) ) \ /(1.0-norm.cdf((minRefl-mu)/sigma)) minRefl = amin(reflCompressedSorted) expMuLogN = (truncMean-minRefl)/sqrt(1+truncVarnce/((truncMean-minRefl)**2)) sigma2LogN = log(1+truncVarnce/((truncMean-minRefl)**2)) lognormCdf = lognorm.cdf( reflCompressedSorted - minRefl, sqrt(sigma2LogN), loc=0, scale=expMuLogN )