-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgraph.py
405 lines (314 loc) · 10.3 KB
/
graph.py
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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
import numpy as np
import math
from scipy.special import gammaln
import scipy.stats
class Graph:
def __init__(self, connections, nodes):
self.connections = connections
self.nodes = nodes
self.node_dict = {}
for node in self.nodes:
node._graph = self
self.node_dict[node.name] = node
self.inv_connections = {}
for node, children in self.connections.items():
for child in children:
self.inv_connections[child] = self.inv_connections.setdefault(child, []) + [node]
@property
def hidden_nodes(self):
result = []
for node in self.nodes:
if not node.observed:
result.append(node)
return result
class Node:
def __init__(self, name, graph=None, val=1, observed=False, hyper=False):
self.name = name
self._graph = graph
self._val = val
self.observed = observed
self.hyper = hyper
self._parents = None
self._children = None
def __str__(self):
return self.name
def __repr__(self):
return "(" + self.name + "=" + self.value + ")"
def lookup_probability(self):
return 0
@property
def parents(self):
if self._parents is None:
p = self._graph.inv_connections.get(self.name, [])
self._parents = [self._graph.node_dict[n] for n in p]
return self._parents
@property
def children(self):
if self._children is None:
c = self._graph.connections.get(self.name, [])
self._children = [self._graph.node_dict[n] for n in c]
return self._children
@property
def value(self):
return str(self._val)
class BinaryNode(Node):
def __init__(self, name, probs, **kwargs):
super().__init__(name, **kwargs)
if isinstance(probs, BernoulliParam):
self._probs = probs
else:
self._probs = BernoulliTable(probs, self)
def lookup_probability(self):
given = self._parent_values()
prob = self._probs[given]
if self._val == 1:
return np.log(prob)
else:
return np.log(1.0 - prob)
def _parent_values(self):
l = [p._val for p in self.parents if not p.hyper]
return tuple(l)
def sample(self):
self._val = 1
pos = self.lookup_probability()
for child in self.children:
pos += child.lookup_probability()
self._val = 0
neg = self.lookup_probability()
for child in self.children:
neg += child.lookup_probability()
p = pos - np.logaddexp(pos, neg)
out = np.random.binomial(1, np.exp(p))
self._val = out
return out
@property
def value(self):
if self._val == 1:
return 't'
else:
return 'f'
class BernoulliTable:
def __init__(self, probs, node):
self.probs = probs
self.node = node
def __getitem__(self, item):
x = self.probs[item]
if isinstance(x, Node):
return x._val
if isinstance(x, str):
node = self.node._graph.node_dict[x]
self.probs[item] = node
return node._val
else:
return x
class BernoulliParam:
def __getitem__(self, item):
return item[0]
class Param:
def __init__(self, func, *args):
self._func = func
self._args = args
def __call__(self, graph):
nodes = [graph.node_dict[name] for name in self._args]
return self._func(*nodes)
class BernoulliNode(Node):
def __init__(self, name, prob, **kwargs):
super().__init__(name, **kwargs)
self._prob = prob
def lookup_probability(self):
prob = self.parameter(self._prob)
if self._val == 1:
return prob
else:
return 1 - prob
def parameter(self, param):
if isinstance(param, Node):
return param._val
elif isinstance(param, str):
return self._graph.node_dict[param]._val
elif isinstance(param, Param):
return param(self._graph)
else:
return param
def sample(self):
self._val = 1
pos = self.lookup_probability()
for child in self.children:
pos *= child.lookup_probability()
self._val = 0
neg = self.lookup_probability()
for child in self.children:
neg *= child.lookup_probability()
p = pos / (pos + neg)
out = np.random.binomial(1, p)
self._val = out
return out
class MetropolisNode(Node):
def __init__(self, name, cand_var=None, **kwargs):
super().__init__(name, **kwargs)
if cand_var is None:
cand_var = 1.
self.cd_var = cand_var
def get_candidate_value(self):
mu = self._val
sigma = math.sqrt(self.cd_var)
return np.random.normal(mu, sigma)
def sample(self, cand=None):
if cand is None:
cand = self.get_candidate_value()
last = self._val
fxt = self.lookup_probability()
for child in self.children:
fxt += child.lookup_probability()
self._val = cand
fxs = self.lookup_probability()
for child in self.children:
fxs += child.lookup_probability()
u = np.log(np.random.uniform())
if u < fxs - fxt:
self._val = cand
else:
self._val = last
return self._val
def parameter(self, param):
if isinstance(param, Node):
return param._val
elif isinstance(param, str):
return self._graph.node_dict[param]._val
elif isinstance(param, Param):
return param(self._graph)
else:
return param
class NormalNode(MetropolisNode):
def __init__(self, name, mean, var, **kwargs):
super().__init__(name, **kwargs)
self._mean = mean
self._var = var
@property
def mean(self):
return self.parameter(self._mean)
@property
def var(self):
return self.parameter(self._var)
def lookup_probability(self):
x = self._val
return -1/2 * (np.log(self.var) + 1/self.var * (x - self.mean)**2)
class InverseGammaNode(MetropolisNode):
def __init__(self, name, alpha, beta, **kwargs):
super().__init__(name, **kwargs)
self._alpha = alpha
self._beta = beta
@property
def alpha(self):
return self.parameter(self._alpha)
@property
def beta(self):
return self.parameter(self._beta)
def sample(self, cand=None):
cand = self.get_candidate_value()
if cand <= 0:
return self._val
return super().sample(cand)
def lookup_probability(self):
x = self._val
return self.alpha * np.log(self.beta) - gammaln(self.alpha) - ((self.alpha+1) * np.log(x)) - (self.beta/x)
class GammaNode(MetropolisNode):
def __init__(self, name, alpha, beta, **kwargs):
super().__init__(name, **kwargs)
self._alpha = alpha
self._beta = beta
@property
def alpha(self):
return self.parameter(self._alpha)
@property
def beta(self):
return self.parameter(self._beta)
def sample(self, cand=None):
cand = self.get_candidate_value()
if cand <= 0:
return self._val
return super().sample(cand)
def lookup_probability(self):
x = self._val
return self.alpha * np.log(self.beta) - gammaln(self.alpha) + ((self.alpha - 1) * np.log(x)) - (self.beta * x)
class BetaNode(MetropolisNode):
def __init__(self, name, alpha, beta, **kwargs):
super().__init__(name, **kwargs)
self._alpha = alpha
self._beta = beta
def get_candidate_value(self):
return scipy.stats.beta.rvs(1, 1)
@property
def alpha(self):
return self.parameter(self._alpha)
@property
def beta(self):
return self.parameter(self._beta)
def sample(self, cand=None):
cand = self.get_candidate_value()
if cand <= 0 or cand > 1:
return self._val
return super().sample(cand)
def lookup_probability(self):
x = self._val
alpha = self.alpha
beta = self.beta
return gammaln(alpha+beta) - gammaln(alpha) - gammaln(beta) + (alpha-1)*np.log(x) + (beta-1)*np.log(1-x)
class UniformNode(MetropolisNode):
def __init__(self, name, theta, discrete=False, **kwargs):
super().__init__(name, **kwargs)
self._theta = theta
self.discrete = discrete
def get_candidate_value(self):
r = np.random.uniform(0, self.theta)
if self.discrete:
r = round(r)
return r
@property
def theta(self):
return self.parameter(self._theta)
def lookup_probability(self):
if self._val > self.theta:
return 0
result = -1 * np.log(self.theta)
return result
class ParetoNode(MetropolisNode):
def __init__(self, name, alpha, x_0, **kwargs):
super().__init__(name, **kwargs)
self._alpha = alpha
self._x_0 = x_0
@property
def alpha(self):
return self.parameter(self._alpha)
@property
def x_0(self):
return self.parameter(self._x_0)
def sample(self, cand=None):
cand = self.get_candidate_value()
if cand < self.x_0:
return self._val
return super().sample(cand)
def lookup_probability(self):
x = self._val
if x < self.x_0:
return 0
return np.log(self.alpha) + self.alpha*np.log(self.x_0) - (self.alpha+1)*np.log(x)
class PoissonNode(MetropolisNode):
def __init__(self, name, theta, **kwargs):
super().__init__(name, **kwargs)
self._theta = theta
@property
def theta(self):
return self.parameter(self._theta)
def sample(self, cand=None):
cand = self.get_candidate_value()
if cand <= 0:
return self._val
return super().sample(cand)
def get_candidate_value(self):
mu = self._val
sigma = math.sqrt(self.cd_var)
return round(np.random.normal(mu, sigma))
def lookup_probability(self):
x = float(self._val)
return x*np.log(self.theta) - gammaln(x+1.) - self.theta