-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoscar.js
110 lines (101 loc) · 2.52 KB
/
oscar.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
'use strict';
let request = require('request');
let querystring = require('querystring');
const _API_VERSION = '1';
const _DOMAIN_URL = 'https://' + _API_VERSION + '-dot-sensout-oscar.appspot.com';
class Oscar {
constructor (token) {
this._token = token;
this._trialIds = {};
this._trialKeys = {};
}
/**
* Generic GET API call.
* @private
*/
_request (url, params, callback) {
request.get(
{
url: _DOMAIN_URL + url + '?' + querystring.stringify(params),
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Bearer ' + this._token
}
},
function (err, res, body) {
if (err) {
callback(err);
} else {
// TODO handle JSON parsing error
var data = null;
try {
data = JSON.parse(body);
} catch (e) {
callback(e);
}
if (data) {
if (data.redirect) {
callback(new Error('Your are not authenticated. You should try updating your access token.'));
} else {
callback(null, data);
}
}
}
}).on('error', function (e) {
callback(e);
});
}
/**
* Compute hash for a given job.
* @private
*/
_getJobHash (job) {
return JSON.stringify(job);
}
/**
* Return job id for a given job.
* @private
*/
_getJobId (job) {
return this._trialsIds[this._getJobHash(job)];
}
/**
* Suggest new hyper parameters to try.
*/
suggest (experiment, callback) {
var that = this;
this._request(
'/suggest',
{ 'experiment': JSON.stringify(experiment) },
function (err, result) {
if (err) {
callback(err);
} else {
if (result.job && result.trial_key && result.trial_id !== null) {
var hash = that._getJobHash(result.job);
that._trialIds[hash] = result.trial_id;
that._trialKeys[hash] = result.trial_key;
callback(null, result.job);
} else {
callback(new Error('No job returned. Check your parameters and quotas ' + JSON.stringify(result)));
}
}
}
);
}
/**
* Update result for an experiment.
*/
update (job, result, callback) {
this._request(
'/update',
{
'trial_key': this._trialKeys[this._getJobHash(job)],
'result': JSON.stringify(result)
},
callback
);
}
}
module.exports = Oscar;