1
2
3
4
5
6
7
8
9
10
11
12
13
14 __docformat__ = "restructuredtext en"
15 from pylab import plot, figure,hist,show, savefig, legend
16 import scipy.stats as stats
17 import numpy
18
20 """
21 Latin Hypercube Sample from a set of values
22
23 :Parameters:
24 - `sample`: list, tuple of array
25 - `siz`: Number or shape tuple for the output sample
26 """
27 if not isinstance(sample, (list,tuple,numpy.ndarray)):
28 raise TypeError('sample is not a list, tuple or numpy vector')
29 n = siz
30 if isinstance(siz,(tuple,list)):
31 n=numpy.product(siz)
32 perc = numpy.arange(0,100.,100./n)
33 numpy.random.shuffle(perc)
34 smp = [stats.uniform(i,100./n).rvs() for i in perc]
35 v = numpy.array([stats.scoreatpercentile(sample,p) for p in smp])
36 if isinstance(siz,(tuple,list)):
37 v.shape = siz
38 return v
39
41 '''
42 LHS sampling from a variables Kernel density estimate.
43
44 :Parameters:
45 - `kde`: scipy.stats.kde.gaussian_kde object
46 - `siz`: Number or shape tuple for the output sample
47 '''
48 if not isinstance(kde,scipy.stats.kde.gaussian_kde):
49 raise TypeError("kde is not a density object")
50 if isinstance(siz,(tuple,list)):
51 n=numpy.product(siz)
52 s = kde.resample(n)
53 v = lhsFromSample(s,n)
54 if isinstance(siz,(tuple,list)):
55 v.shape = siz
56 return v
57
58
59 -def lhs(dist, parms, siz=100):
60 '''
61 Latin Hypercube sampling of any distrbution.
62 dist is is a scipy.stats random number generator
63 such as stats.norm, stats.beta, etc
64 parms is a tuple with the parameters needed for
65 the specified distribution.
66
67 :Parameters:
68 - `dist`: random number generator from scipy.stats module.
69 - `parms`: tuple of parameters as required for dist.
70 - `siz` :number or shape tuple for the output sample
71 '''
72 if not isinstance(dist, (stats.rv_discrete,stats.rv_continuous)):
73 raise TypeError('dist is not a scipy.stats distribution object')
74 n=siz
75 if isinstance(siz,(tuple,list)):
76 n=numpy.product(siz)
77
78 perc = numpy.arange(0,1.,1./n)
79 numpy.random.shuffle(perc)
80 smp = [stats.uniform(i,1./n).rvs() for i in perc]
81 v = dist(*parms).ppf(smp)
82
83 if isinstance(siz,(tuple,list)):
84 v.shape = siz
85 return v
86
87 if __name__=='__main__':
88 dist = stats.norm
89
90 pars = (50,1)
91
92 c=lhs(dist, pars,20)
93 hist(c,normed=1, label='LHS sample')
94 n = dist(*pars).rvs(size=20)
95 hist(n.ravel(),facecolor='r',alpha =0.3,normed=1, label='Regular sample')
96 plot(numpy.arange(min(min(c),min(n)),max(max(c),max(n)),.1),dist(*pars).pdf(numpy.arange(min(min(c),min(n)),max(max(c),max(n)),.1)),label='PDF')
97 legend()
98
99 show()
100
101
102
103
104