-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmapkob.js
301 lines (267 loc) · 7.29 KB
/
mapkob.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
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
mapkob = Object.create(null);
/**
* Generic function to prepare input for consumption
*
* Type can be one of:
* - "plain text": A regular text, sentences are delimited by periods
* - "newline delim": Take a string where sentences are delimited by newlines
* - "sentence array": Takes an array of sentences.
*
* @param {Object} data The input data
* @param {String} type The type of input
* @return {Array} An array of strings, sentences delimited by undefined
*/
mapkob.prepareInput = function(data, type) {
function splitSentenceArray(a) {
var delimited = [];
a.map(function(sentence, i) {
delimited.push(sentence.trim());
if (i < sentences.length - 1) {
delimited.push(undefined);
}
});
return delimited;
}
function flattenSentenceArray(a) {
var wordSplitRe = new RegExp("[ .]+");
return a.map(function(sentence) {
return sentence === undefined ? [undefined] : sentence.split(wordSplitRe);
}).reduce(function(x,y) {return x.concat(y);});
}
// plain text
var plainTextSplitter = new RegExp("([\.!?]+)", "gm")
//var plainTextSplitter = new RegExp("(\.)")
if (type === "plain text") {
data = data.replace(plainTextSplitter, "\n")
type = "newline delim"
}
// newline delim
var splitRe = new RegExp("[\n\r]+", "gm");
if (type === "newline delim") {
var sentences = data.split(splitRe);
var delimited = splitSentenceArray(sentences);
return flattenSentenceArray(delimited);
}
// sentence array
if (type === "sentence array") {
var delimited = splitSentenceArray(sentences);
return flattenSentenceArray(delimited);
}
return;
};
/**
* Creates and empty Transition matrix
*
* @param {Number} n An integer specifying which type of n-gram to use
* @return {Object} A Transition Matrix object
*/
mapkob.TransitionMatrix = function(n) {
if (n % 1 !== 0 || n < 2) {throw "n needs to be an integer >= 2";}
var uniqueWords = [];
var matrix = {};
var starts = {};
this.stateSpace = [];
this.matrix = {};
this.initialStates = new mapkob.Row();
this.n = n;
return this;
};
/**
* functional wrapper around constructor
* Can train supplied data implicitly or load a JSONified Transition matrix.
*
* @param {Number} n An integer specifying which type of n-gram to use
* @param {Object} input transition matrix input or a JSONified Matrix
* @return {Object} A Transition Matrix
*/
mapkob.transitionMatrix = function(n, input) {
n = n || 2;
var output = new mapkob.TransitionMatrix(n);
try {
data = JSON.parse(input);
if (data.hasOwnProperty("type") && data.type === "mapkob Transition Matrix") {
output.statceSpace = data.initialStates;
output.matrix = data.matrix;
output.initialStates = new mapkob.Row(data.initialStates.row);
}
} catch(err) {
if (input !== undefined) {
output.train(input);
}
}
return output;
};
/**
* Adds training data to an existing model
*
* @param {Array} words An array of consecutive words. delimited by undefined
* @return {this} The trained model
*/
mapkob.TransitionMatrix.prototype.train = function(words) {
function wordJoin(words, i, n) {
var output = [];
var offset = 1;
while (n >= offset) {
output.push(words[i + offset]);
offset += 1;
}
return output
.reduce(function(x,y) {return x + " " + y;}, "")
.replace(/undefined[\w, ]+/, "undefined");
}
// State space
words.map(function(word, i) {
if (this.stateSpace.indexOf(word) === -1) {
this.stateSpace.push(word);
}
// Initial states
if (words[i - 1] === undefined &&
this.initialStates.row[word] === undefined) {
this.initialStates.row[word] = 1;
this.initialStates.stateSpace.push(word);
} else if (words[i - 1] === undefined){
this.initialStates.row[word] += 1;
}
// Rows
if (this.matrix[word] === undefined) {
this.matrix[word] = {};
}
var nextWord = wordJoin(words, i, this.n - 1);
// Columns
if (this.matrix[word][nextWord] === undefined) {
this.matrix[word][nextWord] = 1;
} else {
this.matrix[word][nextWord] += 1;
}
}, this);
return this;
};
/**
* return the row of a matrix
*
* @param {String} row The row by name to look up
* @return {Object} The row of the matrix
*/
mapkob.TransitionMatrix.prototype.getRow = function(row) {
var output = new mapkob.Row(this.matrix[row]);
return output;
};
/**
* Generates a Markov chain
*
* @return {String} A Computer generated string
*/
mapkob.TransitionMatrix.prototype.generateChain = function() {
var currentState = this.
initialStates.
probabilities().
cumSum().
pickState(Math.random());
var output = [];
console.log(currentState)
while (currentState !== "undefined") {
console.log("Current output:" +output + " current state: " + currentState)
output.push(currentState.replace(/ ?undefined\w*/, ""));
currentNGram = currentState.split(" ");
currentState = currentNGram[currentNGram.length - 1];
if (currentState === "undefined" || currentState === undefined) {break;}
currentState = this.
getRow(currentState).
probabilities().
cumSum().
pickState(Math.random());
}
return output.join(" ") + ".";
};
/**
* Transforms a Transitionmatrix into an identifiable object
*
* @return {Object} A JSON file
*/
mapkob.TransitionMatrix.prototype.toJSON = function() {
return JSON.stringify({
type: "mapkob Transition Matrix",
matrix: this.matrix,
stateSpace: this.stateSpace,
initialStates: this.initialStates
});
};
/**
* A Row mapkob row constructor
*
* @param {Object} input A simple object
* @return {Object} A maokob row
*/
mapkob.Row = function(input) {
if (input === undefined) {
this.row = {};
this.stateSpace = [];
} else {
this.row = input;
this.stateSpace = Object.keys(input);
}
return this;
};
/**
* Calculates the sum of the rows
*
* @return {Number} The sum of the values
*/
mapkob.Row.prototype.sum = function() {
return this.stateSpace.map(function(state) {
return this.row[state];
}, this).reduce(function(x, y) {
return x + y;
}, 0);
};
/**
* Calculates relative frequencies of a row
*
* @return {Object} A row
*/
mapkob.Row.prototype.probabilities = function() {
var sum = this.sum();
var probs = {};
this.stateSpace.map(function(state) {
probs[state] = this.row[state] / sum;
}, this);
return new mapkob.Row(probs);
};
/**
* A row with the cumulative sums
*
* @return {Object} A row
*/
mapkob.Row.prototype.cumSum = function() {
var sums = {};
var sum = 0;
this.stateSpace.map(function(state) {
sum += this.row[state];
sums[state] = sum;
}, this);
return new mapkob.Row(sums);
};
/**
* return an array with the row's values
*
* @return {Array} The rows values
*/
mapkob.Row.prototype.values = function() {
return this.stateSpace.map(function(state) {
return this.row[state];
}, this);
};
/**
* Picks the state with the largest CDF that is smaller or equal to p
* Technically the first one where the next is larger or the array ends
*
* @return {String} A state string
*/
mapkob.Row.prototype.pickState = function(p) {
cdf = this.values();
for (var col in cdf) {
if (p <= cdf[col] && (cdf[col + 1] == undefined || cdf[col + 1] > p)) {
return this.stateSpace[col];
}
}
};