/
model.js
442 lines (405 loc) · 13.5 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
define([
'jquery',
'underscore',
'util'
],
function($, _, util) {
/**
*
* @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 {string} name A string containing the abbreviated name of the
* ordination method.
* @param {string[]} ids An array of strings where each string is a sample
* identifier
* @param {float[]} coords A 2D Array of floats where each row contains the
* coordinates of a sample. The rows are in ids order.
* @param {float[]} pct_var An Array of floats where each position contains
* the percentage explained by that axis
* @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(name, ids, coords, pct_var, md_headers,
metadata, axesNames) {
var num_coords;
/**
* Abbreviated name of the ordination method used to create the data.
* @type {string}
*/
this.abbreviatedName = name;
/**
* List of sample name identifiers.
* @type {string[]}
*/
this.ids = ids;
/**
* Percentage explained by each of the axes in the ordination.
* @type {float[]}
*/
this.percExpl = pct_var;
/**
* Column names for the metadata in the samples.
* @type {string[]}
*/
this.md_headers = md_headers;
/*
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 (pct_var.length !== num_coords) {
throw new Error('The number of percentage explained values does not ' +
'match the number of coordinates. Perc expl: ' +
pct_var.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(ids.length);
for (var i = 0; i < ids.length; i++) {
this.plottable[i] = new Plottable(ids[i], metadata[i], coords[i], 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 = axesNames === undefined ? [] : axesNames;
// 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();
// TODO:
// this.edges = [];
// this.plotEdge = false;
// this.serialComparison = 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.
*
*/
DecompositionModel.prototype.getUniqueValuesByCategory = function(category) {
var md_idx = this._getMetadataIndex(category);
return _.uniq(
_.map(this.plottable, function(pl) {return pl.metadata[md_idx];}));
};
/**
*
* 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);
};
/**
*
* 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.
*
**/
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);
}
}
};
/**
*
* 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};
});