1
2
3
4
5
6
7
8
9
10
11
12
13
14 __docformat__ = "restructuredtext en"
15
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 parms = tuple([float(k) for k in parms])
79 perc = numpy.arange(0.,1.,1./n)
80 numpy.random.shuffle(perc)
81 smp = [stats.uniform(i,1./n).rvs() for i in perc]
82 v = dist(*parms).ppf(smp)
83
84 if isinstance(siz,(tuple,list)):
85 v.shape = siz
86 return v
87
88 if __name__=='__main__':
89 dist = stats.norm
90
91 pars = (50,1)
92
93 c=lhs(dist, pars,20)
94
95 n = dist(*pars).rvs(size=20)
96
97
98
99
100
101
102
103
104