/
model.js
565 lines (513 loc) · 16.7 KB
/
model.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
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
define([
'jquery',
'underscore',
'util'
],
function($, _, util) {
var naturalSort = util.naturalSort;
/**
*
* @class Plottable
*
* Represents a sample and the associated metadata in the ordination space.
*
* @param {string} name A string indicating the name of the sample.
* @param {string[]} metadata An Array of strings with the metadata values.
* @param {float[]} coordinates An Array of floats indicating the position in
* space where this sample is located.
* @param {integer} [idx = -1] An integer representing the index where the
* object is located in a DecompositionModel.
* @param {float[]} [ci = []] An array of floats indicating the confidence
* intervals in each dimension.
*
* @return {Plottable}
* @constructs Plottable
*
**/
function Plottable(name, metadata, coordinates, idx, ci) {
/**
* Sample name.
* @type {string}
*/
this.name = name;
/**
* Metadata values for the sample.
* @type {string[]}
*/
this.metadata = metadata;
/**
* Position of the sample in the N-dimensional space.
* @type {float[]}
*/
this.coordinates = coordinates;
/**
* The index of the sample in the array of meshes.
* @type {integer}
*/
this.idx = idx === undefined ? -1 : idx;
/**
* Confidence intervals.
* @type {float[]}
*/
this.ci = ci === undefined ? [] : ci;
if (this.ci.length !== 0) {
if (this.ci.length !== this.coordinates.length) {
throw new Error("The number of confidence intervals doesn't match " +
'with the number of dimensions in the coordinates ' +
'attribute. coords: ' + this.coordinates.length +
' ci: ' + this.ci.length);
}
}
};
/**
*
* Helper method to convert a Plottable into a string.
*
* @return {string} A string describing the Plottable object.
*
*/
Plottable.prototype.toString = function() {
var ret = 'Sample: ' + this.name + ' located at: (' +
this.coordinates.join(', ') + ') metadata: [' +
this.metadata.join(', ') + ']';
if (this.idx === -1) {
ret = ret + ' without index';
}
else {
ret = ret + ' at index: ' + this.idx;
}
if (this.ci.length === 0) {
ret = ret + ' and without confidence intervals.';
}
else {
ret = ret + ' and with confidence intervals at (' + this.ci.join(', ') +
').';
}
return ret;
};
/**
* @class DecompositionModel
*
* Models all the ordination data to be plotted.
*
* @param {object} data An object with the following attributes (keys):
* - `name` A string containing the abbreviated name of the
* ordination method.
* - `ids` An array of strings where each string is a sample
* identifier
* - `coords` A 2D Array of floats where each row contains the
* coordinates of a sample. The rows are in ids order.
* - `names` A 1D Array of strings where each element is the name of one of
* the dimensions in the model.
* - `pct_var` An Array of floats where each position contains
* the percentage explained by that axis
* - `low` A 1D Array of floats where each row contains the
* coordinates of a sample. The rows are in ids order.
* - `high` A 1D Array of floats where each row contains the
* coordinates of a sample. The rows are in ids order.
* @param {float[]} md_headers An Array of string where each string is a
* metadata column header
* @param {string[]} metadata A 2D Array of strings where each row contains
* the metadata values for a given sample. The rows are in ids order. The
* columns are in `md_headers` order.
*
* @throws {Error} In any of the following cases:
* - The number of coordinates does not match the number of samples.
* - If there's a coordinate in `coords` that doesn't have the same length as
* the rest.
* - The number of samples is different than the rows provided as metadata.
* - Not all metadata rows have the same number of fields.
*
* @return {DecompositionModel}
* @constructs DecompositionModel
*
*/
function DecompositionModel(data, md_headers, metadata, type) {
var coords = data.coordinates, ci = data.ci || [];
/**
*
* Model's type of the data, can be either 'scatter' or 'arrow'
* @type {string}
*
*/
this.type = type || 'scatter';
var num_coords;
/**
* Abbreviated name of the ordination method used to create the data.
* @type {string}
*/
this.abbreviatedName = data.name || '';
/**
* List of sample name identifiers.
* @type {string[]}
*/
this.ids = data.sample_ids;
/**
* Percentage explained by each of the axes in the ordination.
* @type {float[]}
*/
this.percExpl = data.percents_explained;
/**
* Column names for the metadata in the samples.
* @type {string[]}
*/
this.md_headers = md_headers;
if (coords === undefined) {
throw new Error('Coordinates are required to initialize this object.');
}
/*
Check that the number of coordinates set provided are the same as the
number of samples
*/
if (this.ids.length !== coords.length) {
throw new Error('The number of coordinates differs from the number of ' +
'samples. Coords: ' + coords.length + ' samples: ' +
this.ids.length);
}
/*
Check that all the coords set have the same number of coordinates
*/
num_coords = coords[0].length;
var res = _.find(coords, function(c) {return c.length !== num_coords;});
if (res !== undefined) {
throw new Error('Not all samples have the same number of coordinates');
}
/*
Check that we have the percentage explained values for all coordinates
*/
if (this.percExpl.length !== num_coords) {
throw new Error('The number of percentage explained values does not ' +
'match the number of coordinates. Perc expl: ' +
this.percExpl.length + ' Num coord: ' + num_coords);
}
/*
Check that we have the metadata for all samples
*/
if (this.ids.length !== metadata.length) {
throw new Error('The number of metadata rows and the the number of ' +
'samples do not match. Samples: ' + this.ids.length +
' Metadata rows: ' + metadata.length);
}
/*
Check that we have all the metadata categories in all rows
*/
res = _.find(metadata, function(m) {
return m.length !== md_headers.length;
});
if (res !== undefined) {
throw new Error('Not all metadata rows have the same number of values');
}
this.plottable = new Array(this.ids.length);
for (i = 0; i < this.ids.length; i++) {
// note that ci[i] can be empty
this.plottable[i] = new Plottable(this.ids[i], metadata[i], coords[i], i,
ci[i]);
}
// use slice to make a copy of the array so we can modify it
/**
* Minimum and maximum values for each axis in the ordination. More
* concretely this object has a `min` and a `max` attributes, each with a
* list of floating point arrays that describe the minimum and maximum for
* each axis.
* @type {Object}
*/
this.dimensionRanges = {'min': coords[0].slice(),
'max': coords[0].slice()};
this.dimensionRanges = _.reduce(this.plottable,
DecompositionModel._minMaxReduce,
this.dimensionRanges);
/**
* Number of plottables in this decomposition model
* @type {integer}
*/
this.length = this.plottable.length;
/**
* Number of dimensions in this decomposition model
* @type {integer}
*/
this.dimensions = this.dimensionRanges.min.length;
/**
* Names of the axes in the ordination
* @type {string[]}
*/
this.axesNames = data.axes_names === undefined ? [] : data.axes_names;
// We call this after all the other attributes have been initialized so we
// can use that information safely. Fixes a problem with the ordination
// file format, see https://github.com/biocore/emperor/issues/562
this._fixAxesNames();
/**
* Array of pairs of Plottable objects.
* @type {Array[]}
*/
this.edges = this._processEdgeList(data.edges || []);
}
/**
*
* Whether or not the plottables have confidence intervals
*
* @return {Boolean} `true` if the plottables have confidence intervals,
* `false` otherwise.
*
*/
DecompositionModel.prototype.hasConfidenceIntervals = function() {
if (this.plottable.length <= 0) {
return false;
}
else if (this.plottable[0].ci.length > 0) {
return true;
}
return false;
};
/**
*
* Retrieve the plottable object with the given id.
*
* @param {string} id A string with the plottable.
*
* @return {Plottable} The plottable object for the given id.
*
*/
DecompositionModel.prototype.getPlottableByID = function(id) {
idx = this.ids.indexOf(id);
if (idx === -1) {
throw new Error(id + ' is not found in the Decomposition Model ids');
}
return this.plottable[idx];
};
/**
*
* Retrieve all the plottable objects with the given ids.
*
* @param {integer[]} idArray an Array of strings where each string is a
* plottable id.
*
* @return {Plottable[]} An Array of plottable objects for the given ids.
*
*/
DecompositionModel.prototype.getPlottableByIDs = function(idArray) {
dm = this;
return _.map(idArray, function(id) {return dm.getPlottableByID(id);});
};
/**
*
* Helper function that returns the index of a given metadata category.
*
* @param {string} category A string with the metadata header.
*
* @return {integer} An integer representing the index of the metadata
* category in the `md_headers` array.
*
*/
DecompositionModel.prototype._getMetadataIndex = function(category) {
var md_idx = this.md_headers.indexOf(category);
if (md_idx === -1) {
throw new Error('The header ' + category +
' is not found in the metadata categories');
}
return md_idx;
};
/**
*
* Retrieve all the plottable objects under the metadata header value.
*
* @param {string} category A string with the metadata header.
* @param {string} value A string with the value under the metadata category.
*
* @return {Plottable[]} An Array of plottable objects for the given category
* value pair.
*
*/
DecompositionModel.prototype.getPlottablesByMetadataCategoryValue = function(
category, value) {
var md_idx = this._getMetadataIndex(category);
var res = _.filter(this.plottable, function(pl) {
return pl.metadata[md_idx] === value;
});
if (res.length === 0) {
throw new Error('The value ' + value +
' is not found in the metadata category ' + category);
}
return res;
};
/**
*
* Retrieve the available values for a given metadata category
*
* @param {string} category A string with the metadata header.
*
* @return {string[]} An array of the available values for the given metadata
* header sorted first alphabetically and then numerically.
*
*/
DecompositionModel.prototype.getUniqueValuesByCategory = function(category) {
var md_idx = this._getMetadataIndex(category);
var values = _.map(this.plottable, function(pl) {
return pl.metadata[md_idx];
});
return naturalSort(_.uniq(values));
};
/**
*
* Method to determine if this is an arrow decomposition
*
*/
DecompositionModel.prototype.isArrowType = function() {
return this.type === 'arrow';
};
/**
*
* Method to determine if this is a scatter decomposition
*
*/
DecompositionModel.prototype.isScatterType = function() {
return this.type === 'scatter';
};
/**
*
* Executes the provided `func` passing all the plottables as parameters.
*
* @param {function} func The function to call for each plottable. It should
* accept a single parameter which will be the plottable.
*
* @return {Object[]} An array with the results of executing func over all
* plottables.
*
*/
DecompositionModel.prototype.apply = function(func) {
return _.map(this.plottable, func);
};
/**
*
* Transform observation names into plottable objects.
*
* @return {Array[]} An array of plottable pairs.
* @private
*
*/
DecompositionModel.prototype._processEdgeList = function(edges) {
if (edges.length === 0) {
return edges;
}
var u, v, scope = this;
edges = edges.map(function(edge) {
if (edge[0] === edge[1]) {
throw new Error('Cannot create edge between two identical nodes (' +
edge[0] + ' and ' + edge[1] + ')');
}
u = scope.getPlottableByID(edge[0]);
v = scope.getPlottableByID(edge[1]);
return [u, v];
});
return edges;
};
/**
*
* Helper function used to find the minimum and maximum values every
* dimension in the plottable objects. This function is used with
* underscore.js' reduce function (_.reduce).
*
* @param {Object} accumulator An object with a "min" and "max" arrays that
* store the minimum and maximum values over all the plottables.
* @param {Plottable} plottable A plottable object to compare with.
*
* @return {Object} An updated version of accumulator, integrating the ranges
* of the newly seen plottable object.
* @private
*
*/
DecompositionModel._minMaxReduce = function(accumulator, plottable) {
// iterate over every dimension
_.each(plottable.coordinates, function(value, index) {
if (value > accumulator.max[index]) {
accumulator.max[index] = value;
}
else if (value < accumulator.min[index]) {
accumulator.min[index] = value;
}
});
return accumulator;
};
/**
*
* Fix the names of the axes.
*
* Account for missing axes names, and for uninformative names produced by
* scikit-bio. In both cases, if we have an abbreviated name, we will use
* that string as a prefix for the axes names.
*
* @private
*
*/
DecompositionModel.prototype._fixAxesNames = function() {
var expected = [], replacement = [], prefix, names, cast, i;
if (this.abbreviatedName === '') {
prefix = 'Axis ';
}
else {
prefix = this.abbreviatedName + ' ';
}
if (this.axesNames.length === 0) {
for (i = 0; i < this.dimensions; i++) {
replacement.push(prefix + (i + 1));
}
this.axesNames = replacement;
}
else {
names = util.splitNumericValues(this.axesNames);
for (i = 0; i < names.numeric.length; i++) {
expected.push(i);
// don't zero-index, doesn't make sense for displaying purposes
replacement.push(prefix + (i + 1));
}
// to truly match scikit-bio's format, all the numeric names should come
// after the non-numeric names, and the numeric names should match the
// array of expected values.
if (_.isEqual(expected, names.numeric) &&
_.isEqual(this.axesNames, names.nonNumeric.concat(names.numeric))) {
this.axesNames = names.nonNumeric.concat(replacement);
}
}
this._buildAxesLabels();
};
/**
*
* Helper method to build labels for all axes
*
*/
DecompositionModel.prototype._buildAxesLabels = function() {
var axesLabels = [], index, text;
for (index = 0; index < this.axesNames.length; index++) {
// when the labels get too long, it's a bit hard to look at
if (this.axesNames[index].length > 25) {
text = this.axesNames[index].slice(0, 20) + '...';
}
else {
text = this.axesNames[index];
}
// account for custom axes (their percentage explained will be -1 to
// indicate that this attribute is not meaningful).
if (this.percExpl[index] >= 0) {
text += ' (' + this.percExpl[index].toPrecision(4) + ' %)';
}
axesLabels.push(text);
}
this.axesLabels = axesLabels;
};
/**
*
* Helper method to convert a DecompositionModel into a string.
*
* @return {string} String representation describing the Decomposition
* object.
*
*/
DecompositionModel.prototype.toString = function() {
return 'name: ' + this.abbreviatedName + '\n' +
'Metadata headers: [' + this.md_headers.join(', ') + ']\n' +
'Plottables:\n' + _.map(this.plottable, function(plt) {
return plt.toString();
}).join('\n');
};
return { 'DecompositionModel': DecompositionModel,
'Plottable': Plottable};
});