Index: trunk/tests_python/sampleDistro1DWithWeight_test.py =================================================================== --- trunk/tests_python/sampleDistro1DWithWeight_test.py (revision 0) +++ trunk/tests_python/sampleDistro1DWithWeight_test.py (revision 784) @@ -0,0 +1,76 @@ +import unittest +import npstat as ns +import numpy as np +from npstat_utils import HistoND +import matplotlib.pyplot as plt + +class TestWeightedSampler(unittest.TestCase): + def test_sampleDistro1DWithWeight(self): + showHisto = False + sampleSize = 10000 + nbins = 50 + xmin = 0.0 + xmax = 2.0 + sizeType = ns.SIZE_IS_KISH + + distro = ns.Uniform1D(xmin, xmax-xmin) + dip = ns.GaussianDip(1.0, 0.2, 10.0) + rng = ns.MersenneTwister() + sample, status = ns.sampleDistro1DWithWeight( + distro, dip, rng, sampleSize, sizeType) + if (sizeType == ns.SIZE_IS_N_GENERATED): + self.assertEqual(sampleSize, len(sample)) + wSum, effSize, efficiency = status + if (sizeType == ns.SIZE_IS_N_TRIES): + self.assertEqual(round(sampleSize*efficiency), len(sample)) + if (sizeType == ns.SIZE_IS_KISH): + self.assertTrue(effSize >= sampleSize) + print("\nwsum = %6g, Kish's size = %6g, efficiency = %6g" % status) + + h1 = HistoND("double", ns.HistoAxis(nbins, xmin, xmax, "X"), + "Sample Histogram", "Weight") + h1.fill(sample) + + h2 = HistoND("int", ns.HistoAxis(nbins, xmin, xmax, "X"), + "Unweighted Histogram", "Counts") + h2.fill([s[0] for s in sample], 1) + + if showHisto: + xh, yh = ns.histoOutline1D(h1) + plt.plot(xh, yh, 'k') + xh, yh = ns.histoOutline1D(h2) + plt.plot(xh, yh, 'r') + plt.xlabel(h1.axis(0).label()) + plt.ylabel(h1.accumulatedDataLabel()) + plt.title("Weighted and Unweighted Histograms") + plt.show() + + def test_sampleDistro1DWithWeightSize(self): + showHisto = False + nSamples = 100 + sampleSize = 5.5 + nbins = 11 + xmin = -0.5 + xmax = 10.5 + sizeType = ns.SIZE_IS_N_GENERATED + distro = ns.Uniform1D(xmin, xmax-xmin) + rng = ns.MersenneTwister() + + h2 = HistoND("int", ns.HistoAxis(nbins, xmin, xmax, "Sample Size"), + "Test of sampleDistro1DWithWeight", "Number of Samples") + + for itry in range(nSamples): + sample, status = ns.sampleDistro1DWithWeight( + distro, 1.0, rng, sampleSize, sizeType) + h2.fill(len(sample), 1) + + if showHisto: + xh, yh = ns.histoOutline1D(h2) + plt.plot(xh, yh, 'k') + plt.xlabel(h2.axis(0).label()) + plt.ylabel(h2.accumulatedDataLabel()) + plt.title(h2.title()) + plt.show() + +suite = unittest.TestLoader().loadTestsFromTestCase(TestWeightedSampler) +unittest.TextTestRunner(verbosity=2).run(suite)