-
-
Notifications
You must be signed in to change notification settings - Fork 7
/
jsbayes-ww.js
125 lines (109 loc) · 2.61 KB
/
jsbayes-ww.js
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
function toGraph(obj) {
var nodes = obj.nodes;
var parents = obj.parents;
var arrNodes = [];
for(var name in parents) {
var node = nodes[name];
var pas = parents[name];
for(var i=0; i < pas.length; i++) {
var pa = nodes[pas[i]];
node.parents.push(pa);
}
arrNodes.push(node);
node.initSampleLw = function() {
this.sampledLw = undefined;
};
node.sampleLw = function() {
if(this.wasSampled) {
return 1;
}
var fa = 1;
for(var h=0; h < this.parents.length; h++) {
var pa = this.parents[h];
var pSampleLw = pa.sampleLw();
fa *= pSampleLw;
}
this.wasSampled = true;
var dh = this.cpt;
for(var h=0; h < this.parents.length; h++) {
var p = this.parents[h];
var v = p.value;
dh = dh[v];
}
if(this.value != -1) {
var v = dh[this.value];
fa *= v;
} else {
var fv = Math.random();
for(var h=0; h < dh.length; h++) {
var v = dh[h];
fv -= v;
if(fv < 0) {
this.value = h;
break;
}
}
}
return fa;
};
node.saveSampleLw = function(f) {
if(!this.sampledLw) {
this.sampledLw = new Array(this.values.length);
for(var h=this.values.length-1; h >= 0; h--) {
this.sampledLw[h] = 0;
}
}
this.sampledLw[this.value] += f;
};
}
var g = {
nodes: arrNodes,
sample: function(samples) {
var g = this;
for(var h=g.nodes.length-1; h >= 0; h--) {
g.nodes[h].initSampleLw();
}
var lwSum = 0;
for(var count=0; count < samples; count++) {
for(var h=g.nodes.length-1; h >= 0; h--) {
var n = g.nodes[h];
if(!n.isObserved) {
n.value = -1;
}
n.wasSampled = false;
}
var fa = 1;
for(var h=g.nodes.length-1; h >= 0; h--) {
var n = g.nodes[h];
fa *= n.sampleLw();
}
lwSum += fa;
for(var h=g.nodes.length-1; h >= 0; h--) {
var n = g.nodes[h];
n.saveSampleLw(fa);
}
}
return lwSum;
}
}
return g;
}
function sample(msg) {
var obj= JSON.parse(msg);
var samples = obj.samples;
var g = toGraph(obj);
g.sample(samples);
var nodes = {};
for(var i=0; i < g.nodes.length; i++) {
var node = g.nodes[i];
nodes[node.name] = node;
}
var response = {
success: true,
nodes: nodes
};
self.postMessage(JSON.stringify(response));
}
self.onmessage = function(e) {
sample(e.data);
}