forked from qiskit-community/qiskit-js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
350 lines (276 loc) · 8.45 KB
/
index.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
/**
* @license
*
* Copyright (c) 2017, IBM.
*
* This source code is licensed under the Apache License, Version 2.0 found in
* the LICENSE.txt file in the root directory of this source tree.
*/
'use strict';
const { version } = require('./package');
const utils = require('./lib/utils');
const request = require('./lib/request');
const massageJob = require('./lib/massageJob');
const parser = require('./lib/parser');
const cfg = require('./cfg.json');
const dbg = utils.dbg(__filename);
// To avoid requests that are going to fail to the API.
const errLoginBefore = 'Please use "login" before';
class Cloud {
constructor(opts = {}) {
dbg('Starting', opts);
this.version = version;
this.uri = process.env.QE_URI || cfg.defaults.uri;
// Both are also set after a successful login.
if (opts.token) {
this.token = opts.token;
}
if (opts.userId) {
this.userId = opts.userId;
}
}
// Token not needed.
async calibration(name = cfg.defaults.backend.reads) {
dbg('Getting the calibration info', { name });
const backName = parser.string(name);
return request(`${this.uri}/Backends/${backName}/calibration`);
}
async parameters(name = cfg.defaults.backend.reads) {
dbg('Getting the parameters info', { name });
const backName = parser.string(name);
return request(`${this.uri}/Backends/${backName}/parameters`);
}
async queues(name = cfg.defaults.backend.reads) {
dbg('Getting the status of the queue for', { name });
const backName = parser.string(name);
// TODO: The API returns undefined if the backend doesn´t exists.
// Using empty object to be consistent with parameters and calibration.
// return request(`${this.uri}/Backends/${name}/queue/status`);
const res = await request(`${this.uri}/Backends/${backName}/queue/status`);
// The message is redundant with the status.
if (res && res.message) {
delete res.message;
}
return res || {};
}
async login(tokenPersonal) {
dbg('Getting a long term token');
const t = parser.string(tokenPersonal);
const res = await request(`${this.uri}/users/loginWithToken`, {
body: { apiToken: t },
});
this.token = res.id;
this.userId = res.userId;
dbg('Massaging the response', res);
res.token = res.id;
delete res.id;
return res;
}
// Token needed.
async credits() {
dbg('Getting user credits info');
if (!this.token || !this.userId) {
throw new Error(errLoginBefore);
}
const res = await request(`${this.uri}/users/${this.userId}`, {
token: this.token,
});
const creditInfo = res.credit;
delete creditInfo.promotionalCodesUsed;
delete creditInfo.lastRefill;
delete creditInfo.promotional;
return creditInfo;
}
async backend(name = cfg.defaults.backend.reads) {
dbg('Getting info for a backend', { name });
if (!this.token) {
throw new Error(errLoginBefore);
}
// TODO: The API returns undefined if the backend doesn´t exists.
// Using empty object to be consistent with parameters and calibration.
// return request(`${this.uri}/Backends/${parser.string(name)}`, { token: this.token });
const res = await request(`${this.uri}/Backends/${parser.string(name)}`, {
token: this.token,
});
return res || {};
}
async backends(onlySims = false) {
dbg('Getting the available backends', { onlySims });
if (!this.token) {
throw new Error(errLoginBefore);
}
if (onlySims) {
parser.bool(onlySims);
}
let res = await request(`${this.uri}/Backends`, { token: this.token });
// TODO: This endpoint doesn´t allow the filter param.
res = utils.filter(res, el => el.status === 'on');
if (onlySims) {
dbg('Returning only the simulators');
return utils.filter(
res,
el => el.status === 'on' && el.simulator === true,
);
}
return res;
}
async run(circuit, opts = {}) {
dbg('Running experiment ...');
if (!this.token || !this.userId) {
throw new Error(errLoginBefore);
}
dbg('Parsing mandatory params ...', { circuit });
let qasm = parser.string(circuit);
// TODO: Dirty trick because the API adds this line again.
qasm = qasm.replace('IBMQASM 2.0;', '').replace('OPENQASM 2.0;', '');
dbg('Parsing optional params ...', opts);
let backend;
if (opts.backend) {
backend = parser.string(opts.backend);
} else {
backend = cfg.defaults.backend.run;
}
const reqOpts = {
token: this.token,
body: {
qasms: [{ qasm }],
backend: { name: backend },
},
};
if (opts.shots) {
reqOpts.body.shots = parser.number(
opts.shots,
cfg.limits.shots[0],
cfg.limits.shots[1],
);
} else {
reqOpts.body.shots = cfg.defaults.shots;
}
if (opts.seed) {
reqOpts.body.seed = parser.string(opts.seed);
}
if (opts.maxCredits) {
reqOpts.body.maxCredits = parser.number(opts.maxCredits, 0);
}
if (opts.name) {
reqOpts.body.qasms[0].name = parser.string(opts.name);
}
dbg('Making the request ...', reqOpts);
const res = await request(`${this.uri}/Jobs`, reqOpts);
dbg('Massaging the result ...', res);
// TODO: Add info about the status of the job in the queue.
const resMassaged = { id: res.id, status: res.status };
// To avoid a break if any API error or something.
if (res.qasms && res.qasms[0] && res.qasms[0]) {
resMassaged.name = res.qasms[0].name;
}
dbg('Massaged ...', resMassaged);
return resMassaged;
}
async runBatch(circuits, opts = {}) {
dbg('Running batch of experiment ...', { circuits, opts });
if (!this.token || !this.userId) {
throw new Error(errLoginBefore);
}
dbg('Parsing mandatory params ...', { circuits });
let qasms;
if (!circuits || !utils.isArray(circuits) || utils.isEmpty(circuits)) {
throw new Error(`Array format expected, found: ${circuits}`);
} else {
qasms = utils.map(circuits, el => {
// TODO: Dirty trick because the API adds this line again.
if (!utils.isObject(el)) {
throw new Error(`Object format expected: ${el}`);
}
const parsed = {
qasm: parser
.string(el.qasm)
.replace('IBMQASM 2.0;', '')
.replace('OPENQASM 2.0;', ''),
};
if (el.shots) {
parsed.shots = parser.number(
el.shots,
cfg.limits.shots[0],
cfg.limits.shots[1],
);
}
if (el.seed) {
parsed.seed = parser.string(el.seed);
}
if (el.name) {
parsed.name = parser.string(el.name);
}
return parsed;
});
}
dbg('Parsing optional params ...', opts);
let backend;
if (opts.backend) {
backend = parser.string(opts.backend);
} else {
backend = cfg.defaults.backend.run;
}
let shots;
if (opts.shots) {
shots = parser.number(
opts.shots,
cfg.limits.shots[0],
cfg.limits.shots[1],
);
} else {
// eslint-disable-next-line prefer-destructuring
shots = cfg.defaults.shots;
}
const reqOpts = {
token: this.token,
body: {
qasms,
shots,
backend: { name: backend },
},
};
if (opts.seed) {
reqOpts.body.seed = parser.string(opts.seed);
}
if (opts.maxCredits) {
reqOpts.body.maxCredits = parser.number(opts.maxCredits, 0);
}
dbg('Making the request ...', reqOpts);
const res = await request(`${this.uri}/Jobs`, reqOpts);
dbg('Massaging the result ...', res);
return {
id: res.id,
status: res.status,
};
}
async job(id) {
dbg('Getting info for a job', { id });
if (!this.token) {
throw new Error(errLoginBefore);
}
const res = await request(`${this.uri}/Jobs/${parser.string(id)}`, {
token: this.token,
});
return massageJob(res);
}
async jobs(limit = 50, skip) {
dbg('Getting the jobs');
if (!this.token) {
throw new Error(errLoginBefore);
}
const reqOpts = {
token: this.token,
filter: { order: 'creationDate DESC' },
};
if (limit) {
reqOpts.filter.limit = parser.number(limit, 0);
}
if (skip) {
reqOpts.filter.skip = parser.number(skip, 0);
}
const res = await request(`${this.uri}/Jobs`, reqOpts);
return res.map(massageJob);
}
}
module.exports = Cloud;