-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
412 lines (335 loc) · 9.73 KB
/
main.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
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
406
407
408
409
410
411
412
"use strict";
/**
* Simple Q-learning library for JavaScript ninja
* @author StarColon Projects
*/
var ql = {}
var fs = require('fs');
var Promise = require('bluebird');
var _ = require('underscore');
var colors = require('colors');
var State = require('./state.js');
var Generalizer = require('./generaliz.js');
var config = require('./package.json');
ql.isVerbose = true;
Promise.longStackTraces = true;
/**
* Create a new agent with given predefined actionset
* @param {String} name of the agent file to save or load
* @param {Array} list of actions (string)
* @param {Number} learning rate
*/
ql.newAgent = function(name,actionset,alpha){
var agent = {}
agent.name = name;
agent.actionset = actionset;
agent.func = {};
agent.policy = {};
agent.alpha = alpha || 0.5;
agent.history = [];
return Promise.resolve(agent)
}
// stateGenerator takes a state and an action
// to create a new subsequent state
ql.bindStateGenerator = function(stateGenerator){
return function(agent){
agent.func.stateGenerator = stateGenerator;
return agent;
}
}
ql.bindRewardMeasure = function(rewardOfState){
return function (agent){
agent.func.rewardOfState = rewardOfState;
return agent;
}
}
ql.bindActionCostMeasure = function(actionCost){
return function(agent){
agent.func.actionCost = actionCost;
return agent;
}
}
ql.bindStatePrinter = function(p){
return function(agent){
agent.func.statePrint = p;
return agent;
}
}
ql.clearHistory = function(agent){
agent.history.length = 0;
return Promise.resolve(agent);
}
/**
* Save the learned policy to a physical file
* the name of the agent is used as the file name
*/
ql.save = function(path){
return function(agent){
fs.writeFileSync(`${path}/${agent.name}.agent`,JSON.stringify(agent.policy));
return Promise.resolve(agent).error((e) => {
console.error('Unable to save agent state'.red);
console.error(e);
});
}
}
/**
* As the learned policy as a specified file
*/
ql.saveAs = function(fullpath){
return function(agent){
fs.writeFileSync(`${fullpath}.agent`,JSON.stringify(agent.policy));
return Promise.resolve(agent);
}
}
/**
* Load the policy from a physical file
*/
ql.load = function(path){
return function(agent){
return new Promise((done,reject) => {
fs.readFile(`${path}/${agent.name}.agent`,function(err,policy){
if (err) {
console.error('Unable to load agent'.red);
console.error(err);
return done(agent);
}
policy = JSON.parse(policy);
agent.policy = policy;
ql.isVerbose && console.log('AGENT LOADED'.cyan);
ql.isVerbose && console.log(agent.policy)
done(agent)
})
})
}
}
/**
* Illustrate the policy it learned
*/
ql.revealBrain = function(agent){
if (Object.keys(agent.policy).length==0)
return agent;
console.log('[BRAIN SCAN]'.green)
Object.keys(agent.policy).forEach(function(state){
console.log(state);
console.log(` most probable action: ${agent.policy[state][0].action} (${agent.policy[state][0].reward})`)
})
return agent;
}
/**
* Update the policy from the observation
* @param {State} state
* @param {String} action
* @param {Number} reward value to add
*/
ql.__updatePolicy = function(state,action,rewardAddUp){
return function(agent){
// Register a new state if haven't
if (!agent.policy.hasOwnProperty(state.hash)){
agent.policy[state.hash] = {}
agent.policy[state.hash] = agent.actionset.map(function(a){
return {action: a, reward: a==action ? rewardAddUp : 0}
})
}
else{
// State exists, update the action reward
agent.policy[state.hash] = agent.policy[state.hash].map(function(a){
if (a.action==action)
return {action: action, reward: rewardAddUp};
else return {action:a.action, reward: a.reward}
})
}
// Resort the policy (higher reward comes first)
agent.policy[state.hash] = _.sortBy(agent.policy[state.hash],(s)=>-s.reward);
return Promise.resolve(agent)
}
}
/**
* Explore the reward of the next state after applying an action
* @param {State} current state
*/
ql.__rewardOf = function(state){
return function(agent){
return agent.func['rewardOfState'](state.hash);
}
}
/**
* Determine (predict) the reward we would get
* when perform a particular action on a state
*/
ql.__q = function(state,action){
return function(agent){
var cost = agent.func.actionCost(state,action);
if (cost<0)
return cost;
// Do we have the state and action registered in the policy?
if (agent.policy.hasOwnProperty(state.hash)){
// Yes, we have the state memorised
var _act = (agent.policy[state.hash].filter((a) => a.action==action));
if (_act.length==0)
return agent.funcactionCost(state,a);
else
return _act[0].reward;
}
else{
// Estimate cost from generalised model
if (agent.ϴ){
console.log('Recall policy from generalisation'.cyan);
var actionIndex = agent.actionset.indexOf(action);
var _state = [1].concat(state.state)
var _cost = agent.ϴ[actionIndex].reduce((_c,θi,i) =>
_c + θi*_state[i]
,0)
return _cost;
}
// We don't know anything about the current state
// Guess it based on uniform distribution then
return cost;
}
}
}
/**
* Explore the subsequent states by trying some actions on it
*/
ql.__exploreNext = function(state){
return function(agent){
// List all actions and try
var rewards = agent.actionset.map(function(a){
// Predict the reward we would get
var q = ql.__q(state,a)(agent);
// If the predicted reward remains zero,
// apply some uncertainty noise
if (q==0) q += Math.random();
return {action: a, reward: q}
})
// Sort the actions by rewards (higher first)
return _.sortBy(rewards,(r) => -r.reward);
}
}
/**
* Start a new learning course of the agent
* @param {State} initial state
*/
ql.start = function(initState){
return function(agent){
ql.isVerbose && console.log('Starting...'.cyan);
// Clear the history then start
return ql.clearHistory(agent)
.then(ql.setState(initState))
.then(ql.step);
}
}
/**
* Perceive and store its own state in the history tree
*/
ql.perceiveState = function(agent){
agent.history.push({action: null, state: agent.state});
return agent;
}
/**
* Set the current state
*/
ql.setState = function(state){
return function(agent){
agent.state = state;
// Push the state to the history list too
agent.history.push({action: null, state: state})
return agent;
}
}
ql.getState = function(agent){
return agent.state
}
/**
* Learn from the recent step which introduces a new state
* This should be called after `ql.step`
* and then `ql.setState` strictly
*/
ql.learn = function(agent){
// NOTE:
// Last history = perceived environmental state after a move
// Preceeding of last = A move the agent took
// History primary validations
if (agent.history.length<2){
return Promise.reject('Agent has not yet made any steps.');
}
var L = agent.history.length;
var lastMove = agent.history[L-2];
var currentState = agent.history[L-1];
if (currentState.action!=null){
return Promise.reject('Agent needs to update the current state after a move.');
}
if (lastMove.action == null){
return Promise.reject('Agent should perceive the current state after its recent move.')
}
var reward0 = agent.func.rewardOfState(lastMove.state);
var reward1 = agent.func.rewardOfState(currentState.state);
var delta = agent.alpha * (reward1 - reward0);
// Learn from mistake, update the policy
ql.isVerbose && console.log(agent.name + ' learning new policy ...'.cyan + delta.toFixed(2));
ql.__updatePolicy(lastMove.state, lastMove.action, delta)(agent);
return agent;
}
/**
* Let the agent choose the next best action
*/
ql.step = function(agent){
ql.isVerbose && console.log('STEP BEGINS'.green);
if (!agent.state){
return Promise.reject('Assign the current state first with `ql.setState`');
}
// Explore the next states
var nexts = ql.__exploreNext(agent.state)(agent);
ql.isVerbose && console.log('generated actions:'.yellow);
ql.isVerbose && console.log(nexts);
// Greedily pick the best action
var chosen = nexts[0];
var currentReward = agent.func.rewardOfState(agent.state);
// Register the chosen action
agent.history.push({action: chosen.action, state: agent.state});
ql.isVerbose && console.log(agent.name + ' chose action :'.green + chosen.action);
// Generate the state after an action is taken
agent.state = agent.func.stateGenerator(agent.state, chosen.action);
// Print the state
ql.isVerbose && agent.func.statePrint && agent.func.statePrint(agent.state);
return agent;
}
/**
* Generalise the J* space
* based on the learned state-reward terrain
* @param {String} method of generalisation to exploit
*/
ql.generalize = function(method){
const maxIters = 100;
const alpha = 0.0001; // Keep it tiny for finest adjustment
method = method || 'GD'; // Gradient descent by default
return function(agent){
// Prepare mapping #action --> #reward
var Qa = agent.actionset.map(function(a){
return {states:[], rewards:[]}
});
// Step through policy and collect
// rewards of each action
Object.keys(agent.policy).forEach((hash) => {
var state = State.fromHash(hash);
// Iterate through each action and fill the space
agent.policy[hash].forEach((a,i) => {
// `a` = {action: .... , reward: .....}
Qa[i].states.push(state);
Qa[i].rewards.push(a.reward);
})
})
// By each action space, fit the parameterised ϴ
var ϴspace = []
Qa.forEach((action,i) => {
var states = action.states;
var rewards = action.rewards;
var ϴi = Generalizer.fit(states,rewards,maxIters,alpha,method);
ϴspace[i] = ϴi;
})
// Now we have learned the entire J* space
// Let the agent memorised it for use
agent.ϴ = ϴspace;
return Promise.resolve(agent)
}
}
module.exports = ql;