-
Notifications
You must be signed in to change notification settings - Fork 2
/
bn.go
342 lines (287 loc) · 8.14 KB
/
bn.go
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
// A DAG (Directed Acyclic Graph) implementation of a Bayesian Network enabling Ancestral Sampling and Gibbs Sampling on Binary Discrete Variables
package BayesianNetwork
import (
"bytes"
"fmt"
// "math"
"math/rand"
// "sort"
// "time"
)
type BayesianNetwork struct {
// nodesName -> node-pointer map
nodes map[string]*Node
// connections between nodes
edges map[string][]string
// index of nodes sorted on id
// - root-ids > child nodes etc..
// [1;len(nodes)]
nodeIndex BayNodes
}
// Creates a directed bayesian network from each node
func NewBayesianNetwork(nodes ...*Node) *BayesianNetwork {
bn := &BayesianNetwork{
nodes: make(map[string]*Node, len(nodes)),
nodeIndex: make([]*Node, 0, len(nodes)),
edges: make(map[string][]string),
}
// add nodes to network
for _, node := range nodes {
if err := bn.addNode(node); err != nil {
panic(err)
}
}
// generate connections
for _, node := range nodes {
bn.addConnections(node.GetParentNames(), node.Name())
}
// validate that CPT has the correct dimensions
// wrt. number of parents
if err := bn.validateCPTs(); err != nil {
panic(err)
}
// index nodes in a breath first fashion
bn.indexNetwork()
return bn
}
// takes the node argument of interest (X5) and the truth-value
// mapping for the surrounding markov blanket
// it returns the map containing the frequencies of each of the inferred values:
// if X5 sample == false:
func (bn *BayesianNetwork) GibbsSampling(observations map[string]string, n, m int) StatMap {
// only sample from the variables that
// are not defined
nodes_of_interest := make(BayNodes, 0, len(bn.nodeIndex)-len(observations))
// just to be sure
bn.Reset()
// make sure no node is not assigned
// either using the mapping or using a default of "F"
if len(observations) == 0 {
// no observations => sample from entire network
nodes_of_interest = bn.nodeIndex[0:len(bn.nodeIndex)]
// reset entire graph to false
bn.ResetWithAssignment("F")
} else {
// update the graph with all the observed values
err := bn.UpdateGraphValues(observations)
if err != nil {
panic(err)
}
// gather all the nodes of interest
// and initialize them
for _, node := range bn.nodeIndex {
if node.GetAssignment() == "" {
node.SetAssignment("F")
nodes_of_interest = append(nodes_of_interest, node)
}
}
}
// initialize stat gathering
ns := NewNetworkStat(bn)
// run n times before we start registering statistics
for i := 0; i < n; i++ {
for _, xi := range nodes_of_interest {
sample := bn.MarkovBlanketSample(xi)
xi.SetAssignment(sample)
}
}
// run m times while gathering stats
for i := 0; i < m; i++ {
for _, xi := range nodes_of_interest {
sample := bn.MarkovBlanketSample(xi)
xi.SetAssignment(sample)
}
// update stats
ns.Update()
}
// clean up
bn.Reset()
return ns.GetStats()
}
func (bn *BayesianNetwork) MarkovBlanketSample(node *Node) string {
// ******* numerator *******
numerator := node.P()
// now sample the children given the sampled node of interest
for _, childNode := range node.GetChildren() {
numerator *= childNode.P()
}
// ******* normalization *******
Z := 0.0
// set the value of node of interest to each value
for _, cond := range []string{"T", "F"} {
// assign truth value
node.SetAssignment(cond)
// sample the probability given the assignment
sampleProb := node.SampleOnCondition(cond)
// now sample the children given the sampled node of interest
for _, childNode := range node.GetChildren() {
sampleProb *= childNode.P()
}
Z += sampleProb
}
markovProb := numerator / Z
random := rand.Float64()
if random > markovProb {
return "F"
}
return "T"
}
// Given a truth-assignment for a markov blanket,
// this method updates the nodes to reflect those values.
// mapping example: map[string]string{ "X1":"F", X3:"T"}
// - reports an error if just one of the nodes does not exist
func (bn *BayesianNetwork) UpdateGraphValues(mapping map[string]string) error {
for nodeName, value := range mapping {
node := bn.nodes[nodeName]
if node == nil {
return fmt.Errorf("Node '%s' does not exist in network\n\tmapping: %v\n\tnetwork: %v\n", nodeName, mapping, bn.nodeIndex)
}
node.SetAssignment(value)
}
return nil
}
// does a complete ancestral sampling of the network
func (bn *BayesianNetwork) AncestralSampling(n int) StatMap {
// initialize stats gathering
stat := NewNetworkStat(bn)
for i := 0; i < n; i++ {
for _, node := range bn.nodeIndex {
// fmt.Printf("%s = %s\n", node.Name(), node.AssignmentValue())
node.SetAssignment(node.Sample())
}
// upate stats
stat.Update()
}
// cleanup
bn.Reset()
return stat.GetStats()
}
// Reset network after running a destructive method
func (bn *BayesianNetwork) Reset() {
for _, node := range bn.nodeIndex {
node.Reset()
}
}
func (bn *BayesianNetwork) ResetWithAssignment(assignment string) {
if assignment != "F" && assignment != "T" {
panic(fmt.Sprintf("Invalid assignment: '%s' should be T or F", assignment))
}
for _, node := range bn.nodeIndex {
node.SetAssignment(assignment)
}
}
// prints every node in the system seperately
// - also, print assignment value, if it has been
// set. meant for DEABUG
func (bn *BayesianNetwork) PrintNetwork() string {
if len(bn.nodeIndex) == 0 {
return "[]"
}
var buffer bytes.Buffer
buffer.WriteString(" ")
for _, node := range bn.nodeIndex {
buffer.WriteString(node.String())
buffer.WriteString(" ")
}
return fmt.Sprintf("[%v]", buffer.String())
}
// joint probability of the network
func (bn *BayesianNetwork) JointProbability() float64 {
p := 1.0
bn.ResetWithAssignment("T")
for _, node := range bn.nodeIndex {
p *= node.P()
}
return p
}
// validate every node in the system for invalid
// conditional probability tables
func (bn *BayesianNetwork) validateCPTs() error {
for _, node := range bn.nodes {
if err := node.ValidateCPT(); err != nil {
return err
}
}
return nil
}
// index the graph in a breath-first fashion
// - guarantees that every parent has an index
// that is larger than every one of their children
func (bn *BayesianNetwork) indexNetwork() {
roots := make(BayNodes, 0, 5)
for _, node := range bn.nodes {
if node.NumParents() != 0 {
continue
// children := append(children, node.GetChildren()...)
}
roots = append(roots, node)
}
id := 1
for len(roots) > 0 {
children := make(BayNodes, 0, 10)
for _, node := range roots {
if node.Id() != 0 {
continue
}
node.setId(id)
bn.nodeIndex = append(bn.nodeIndex, node)
id++
ch := node.GetChildren()
children = append(children, ch...)
}
// swap childnodes for parentNodes
roots = children
}
}
func (bn *BayesianNetwork) addNode(node *Node) error {
if _, ok := bn.nodes[node.Name()]; ok == true {
return fmt.Errorf("Duplicate nodeName: %s", node.Name())
}
// add parent to child and visa versa
bn.nodes[node.Name()] = node
bn.edges[node.Name()] = make([]string, 0, 5)
return nil
}
// returns the BayesianNode probided a valid name
func (bn *BayesianNetwork) GetNode(name string) *Node {
return bn.nodes[name]
}
func (bn *BayesianNetwork) addConnections(parentNames []string, childName string) error {
child, ok := bn.nodes[childName]
if !ok {
return fmt.Errorf("Child '%s' does not exist \n", childName)
}
for _, parentName := range parentNames {
parent, ok := bn.nodes[parentName]
if !ok {
return fmt.Errorf("Parent '%s' does not exist \n", parentName)
}
parent.AddChild(child)
child.AddParent(parent)
for _, v := range bn.edges[parentName] {
if child.Name() == v {
return nil
}
}
bn.edges[parent.Name()] = append(bn.edges[parent.Name()],
child.Name())
}
return nil
}
func (bn *BayesianNetwork) NodeCount() int {
return len(bn.nodeIndex)
}
// returns all the nodes in the graph
func (bn *BayesianNetwork) GetNodes() BayNodes {
return bn.nodeIndex
}
func (bn *BayesianNetwork) String() string {
var buffer bytes.Buffer
// buffer.WriteString(fmt.Sprintf("nodes: %d\n", bn.nodeCount))
// buffer.WriteString(fmt.Sprintf("nodeIndex: %d\n", bn.nodeIndex))
for _, node := range bn.nodeIndex {
buffer.WriteString(fmt.Sprintf("%s ", node.AssignmentString()))
}
buffer.WriteString("\n")
return buffer.String()
}