1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282
|
#! /usr/bin/env python
import openturns as ot
import openturns.testing as ott
import math as m
class UniformNdPy(ot.PythonDistribution):
def __init__(self, a=[0.0], b=[1.0]):
super(UniformNdPy, self).__init__(len(a))
if len(a) != len(b):
raise ValueError("Invalid bounds")
for i in range(len(a)):
if a[i] > b[i]:
raise ValueError("Invalid bounds")
self.a = a
self.b = b
self.factor = 1.0
for i in range(len(a)):
self.factor *= b[i] - a[i]
def getRange(self):
return ot.Interval(self.a, self.b, [True] * len(self.a), [True] * len(self.a))
def getRealization(self):
X = []
for i in range(len(self.a)):
X.append(
self.a[i] + (self.b[i] - self.a[i]) * ot.RandomGenerator.Generate()
)
return X
def getSample(self, size):
X = []
for i in range(size):
X.append(self.getRealization())
return X
def computeCDF(self, X):
prod = 1.0
for i in range(len(self.a)):
if X[i] < self.a[i]:
return 0.0
prod *= min(self.b[i], X[i]) - self.a[i]
return prod / self.factor
def computePDF(self, X):
for i in range(len(self.a)):
if X[i] < self.a[i]:
return 0.0
if X[i] > self.b[i]:
return 0.0
return 1.0 / self.factor
def getRoughness(self):
return 42.0
def getMean(self):
mu = []
for i in range(len(self.a)):
mu.append(0.5 * (self.a[i] + self.b[i]))
return mu
def getStandardDeviation(self):
stdev = []
for i in range(len(self.a)):
stdev.append((self.b[i] - self.a[i]) / m.sqrt(12.0))
return stdev
def getSkewness(self):
return [0.0] * len(self.a)
def getKurtosis(self):
return [1.8] * len(self.a)
def getMoment(self, n):
return [-0.1 * n] * len(self.a)
# def getCentralMoment(self, n):
# return [0.0] * len(self.a)
def computeCharacteristicFunction(self, x):
if len(self.a) > 1:
raise ValueError("dim>1")
ax = self.a[0] * x
bx = self.b[0] * x
return (m.sin(bx) - m.sin(ax) + 1j * (m.cos(ax) - m.cos(bx))) / (bx - ax)
def isElliptical(self):
return (len(self.a) == 1) and (self.a[0] == -self.b[0])
def isCopula(self):
for i in range(len(self.a)):
if self.a[i] != 0.0:
return False
if self.b[i] != 1.0:
return False
return True
def getMarginal(self, indices):
subA = []
subB = []
for i in indices:
subA.append(self.a[i])
subB.append(self.b[i])
py_dist = UniformNdPy(subA, subB)
return ot.Distribution(py_dist)
def computeQuantile(self, prob, tail=False):
p = 1.0 - prob if tail else prob
quantile = list(self.a)
for i in range(len(self.a)):
quantile[i] += p * (self.b[i] - self.a[i])
return quantile
def getParameter(self):
return list(self.a) + list(self.b)
def getParameterDescription(self):
paramDesc = ["a_" + str(i) for i in range(len(self.a))]
paramDesc.extend(["b_" + str(i) for i in range(len(self.a))])
return paramDesc
def setParameter(self, parameter):
dim = len(self.a)
for i in range(dim):
self.a[i] = parameter[i]
self.b[i] = parameter[dim + i]
for pyDist in [UniformNdPy(), UniformNdPy([0.0] * 2, [1.0] * 2)]:
print("pyDist=", pyDist)
# Instance creation
myDist = ot.Distribution(pyDist)
print("myDist=", repr(myDist))
# Copy constructor
newRV = ot.Distribution(myDist)
# Dimension
dim = myDist.getDimension()
print("dimension=", dim)
# Realization
X = myDist.getRealization()
print("realization=", X)
# Sample
X = myDist.getSample(5)
print("sample=", X)
# PDF
point = [0.2] * dim
pdf = myDist.computePDF(point)
print("pdf=", pdf)
# CDF
cdf = myDist.computeCDF(point)
print("cdf= %.12g" % cdf)
# roughness
roughness = myDist.getRoughness()
print("roughness=", roughness)
# Mean
mean = myDist.getMean()
print("mean=", mean)
# Standard deviation
standardDeviation = myDist.getStandardDeviation()
print("standard deviation=", standardDeviation)
# Skewness
skewness = myDist.getSkewness()
print("skewness=", skewness)
# Kurtosis
kurtosis = myDist.getKurtosis()
print("kurtosis=", kurtosis)
# Moment
moment = myDist.getMoment(3)
print("moment=", moment)
# Centered moment
centeredMoment = myDist.getCentralMoment(3)
print("centered moment=", centeredMoment)
if dim == 1:
CF = myDist.computeCharacteristicFunction(point[0])
print("characteristic function= (%.12g%+.12gj)" % (CF.real, CF.imag))
isElliptical = myDist.isElliptical()
print("isElliptical=", isElliptical)
isCopula = myDist.isCopula()
print("isCopula=", isCopula)
# Range
range_ = myDist.getRange()
print("range=", range_)
# marginal
marginal = myDist.getMarginal(0)
print("marginal=", marginal)
# quantile
quantile = myDist.computeQuantile(0.5)
print("quantile=", quantile)
ot.Log.Show(ot.Log.TRACE)
validation = ott.DistributionValidation(myDist)
validation.skipEntropy() # slow
validation.skipMinimumVolumeLevelSet() # slow
validation.skipCharacteristicFunction() # undefined
validation.run()
param = myDist.getParameter()
print("parameter=", param)
param[0] = 0.4
myDist.setParameter(param)
print("parameter=", myDist.getParameter())
print("parameterDesc=", myDist.getParameterDescription())
print("Cloning distribution")
newDist = ot.Distribution(myDist)
param[0] = 0.5
newDist.setParameter(param)
print("dist parameter=", myDist.getParameter())
print("copy dist parameter=", newDist.getParameter())
# Use the distribution as a copula
myDist = ot.Distribution(UniformNdPy([0.0] * 2, [1.0] * 2))
print(ot.JointDistribution([ot.Normal(), ot.Normal()], myDist))
try:
print("try with another Python distribution")
myDist = ot.Distribution(UniformNdPy([0.0] * 2, [2.0] * 2))
print(ot.JointDistribution([ot.Normal(), ot.Normal()], myDist))
except Exception:
print("The construction failed on purpose as", myDist, "is not a copula")
# Extract the copula
myDist = ot.Distribution(UniformNdPy([0.0] * 2, [2.0] * 2))
copula = myDist.getCopula()
# Test computePDF over a sample (ticket #899)
res = copula.computePDF([[0.5] * 2] * 10)
# Test a discrete distribution
class PoissonPy(ot.PythonDistribution):
def __init__(self, lamb):
super(PoissonPy, self).__init__(1)
if lamb <= 0.0:
raise ValueError("Expected a positive lambda")
self.poisson_ = ot.Poisson(lamb)
def getRange(self):
return self.poisson_.getRange()
def computeCDF(self, X):
return self.poisson_.computeCDF(X)
def computePDF(self, X):
return self.poisson_.computeCDF(X)
def isDiscrete(self):
return True
def getSupport(self, interval):
return self.poisson_.getSupport(interval)
def isIntegral(self):
return True
dist = ot.Distribution(PoissonPy(2.5))
print("Is discrete?", dist.isDiscrete())
print("Is integral?", dist.isIntegral())
print("pdf graph=", dist.drawPDF())
|