-
Notifications
You must be signed in to change notification settings - Fork 15
/
labcontrol.js
778 lines (731 loc) · 20.8 KB
/
labcontrol.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
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
// This variable is needed to control the bootstrap alert correctly
var timeoutHandleForBoostrapAlert = null;
// Disable all inputs from a page
function disableAll() {
$("input").prop("disabled", true);
$("select").prop("disabled", true);
$("button").prop("disabled", true);
}
/**
*
* Auxiliary function to set up a Plate Name input
*
* @param $targetDiv Element The target DIV to append the input
* @param plateId integer The plate id to uniquely identify the elements
* @param checksCallback function Callback to execute when the input changes
* @param label string Input label
* @param defaultValue string The input default value
*
**/
function createPlateNameInputDOM(
$targetDiv,
plateId,
checksCallback,
label,
defaultValue
) {
var $rowDiv = $("<div>")
.addClass("form-group")
.appendTo($targetDiv);
$("<label>")
.attr("for", "plate-name-" + plateId)
.addClass("col-sm-5 control-label")
.append(label)
.appendTo($rowDiv);
var $colDiv = $("<div>")
.attr("id", "div-plate-name-" + plateId)
.addClass("col-sm-7 has-feedback")
.appendTo($rowDiv);
$("<span>")
.addClass("glyphicon glyphicon-remove form-control-feedback")
.appendTo($colDiv);
var $inElem = $("<input>")
.attr("type", "text")
.addClass("form-control")
.attr("id", "plate-name-" + plateId)
.val(defaultValue)
.appendTo($colDiv);
$inElem.keyup(function(e) {
onKeyUpPlateName(e, "plate-name-" + plateId, checksCallback);
});
$inElem.ready(function() {
var e = $.Event("keyup");
$("#plate-name-" + plateId).trigger(e);
});
return $rowDiv;
}
function createNumberInputDOM(
$targetDiv,
plateId,
checksCallback,
label,
defaultValue,
idPrefix,
step,
minVal
) {
var $rowDiv = $("<div>")
.addClass("form-group")
.appendTo($targetDiv);
$("<label>")
.attr("for", idPrefix + plateId)
.addClass("col-sm-5 control-label")
.append(label)
.appendTo($rowDiv);
var $colDiv = $("<div>")
.addClass("col-sm-7")
.appendTo($rowDiv);
var $inElem = $("<input>")
.attr("type", "number")
.addClass("form-control")
.attr("id", idPrefix + plateId)
.val(defaultValue)
.appendTo($colDiv)
.on("change", checksCallback)
.attr("step", step)
.attr("min", minVal);
return $rowDiv;
}
function createTextInputDOM(
$targetDiv,
plateId,
checksCallback,
label,
defaultValue,
idPrefix
) {
var $rowDiv = $("<div>")
.addClass("form-group")
.appendTo($targetDiv);
$("<label>")
.attr("for", idPrefix + plateId)
.addClass("col-sm-5 control-label")
.append(label)
.appendTo($rowDiv);
var $colDiv = $("<div>")
.addClass("col-sm-7")
.appendTo($rowDiv);
var $inElem = $("<input>")
.attr("type", "text")
.addClass("form-control")
.attr("id", idPrefix + plateId)
.val(defaultValue)
.appendTo($colDiv)
.on("change", checksCallback);
return $rowDiv;
}
function createSelectDOM(
$targetDiv,
plateId,
checksCallback,
label,
options,
idPrefix,
placeholder,
idKey
) {
if (idKey === undefined) {
idKey = "equipment_id";
}
var $rowDiv = $("<div>")
.addClass("form-group")
.appendTo($targetDiv);
$("<label>")
.attr("for", idPrefix + plateId)
.addClass("col-sm-5 control-label")
.append(label)
.appendTo($rowDiv);
var $colDiv = $("<div>")
.addClass("col-sm-7")
.appendTo($rowDiv);
var $selElem = $("<select>")
.addClass("form-control")
.attr("plate-id", plateId)
.attr("id", idPrefix + plateId)
.appendTo($colDiv)
.on("change", checksCallback);
$("<option>")
.prop("selected", true)
.prop("disabled", true)
.append(placeholder)
.appendTo($selElem);
$.each(options, function(idx, elem) {
$("<option>")
.attr("value", elem[idKey])
.append(elem.external_id)
.appendTo($selElem);
});
}
function createCheckboxEnabledSpinner(
$targetDiv,
plateId,
checksCallback,
label,
defaultValue,
idPrefix,
step,
minVal
) {
var $rowDiv = $("<div>")
.addClass("form-group")
.appendTo($targetDiv);
$("<label>")
.addClass("col-sm-5 control-label")
.append(label)
.appendTo($rowDiv);
var $container = $("<div>")
.addClass("input-group col-sm-2")
.appendTo($rowDiv);
// align this input-group with the rest of the form-groups
$container.css("padding-left", "15px");
var $addon = $("<span>")
.addClass("input-group-addon")
.appendTo($container);
var $checkbox = $("<input>")
.attr("type", "checkbox")
.appendTo($addon);
var $input = $("<input>")
.attr("type", "number")
.addClass("form-control")
.appendTo($container)
.on("change", checksCallback);
$input.attr("step", step).attr("min", minVal);
$input.attr("id", idPrefix + plateId).val(defaultValue);
$input.prop("disabled", defaultValue === "");
$checkbox.prop("checked", defaultValue !== "");
// enable the input when the checkbox is checked
$checkbox.on("change", function(element, event) {
$input.prop("disabled", !$checkbox.prop("checked"));
if (!$checkbox.prop("checked")) {
$input.val(null);
}
checksCallback();
});
}
function createReagentDOM(
$targetDiv,
plateId,
checksCallback,
label,
idPrefix,
vueTarget,
reagentType
) {
var $rowDiv = $("<div>")
.addClass("form-group")
.appendTo($targetDiv);
$("<label>")
.attr("for", idPrefix + plateId)
.addClass("col-sm-5 control-label")
.append(label)
.appendTo($rowDiv);
var $colDiv = $("<div>")
.addClass("col-sm-7")
.appendTo($rowDiv);
var $inElem = $("<input>")
.attr("type", "text")
.addClass("form-control")
.attr("id", idPrefix + plateId)
.appendTo($colDiv);
// Add the Vue element to the extraction kit once it has been loaded into the DOM.
// This is needed otherwise Vue will not find the input element
$inElem.ready(function() {
var vueContainer = $("<div>")
.attr("id", "vue-elem-" + idPrefix + plateId)
.appendTo(vueTarget);
var vueComponentCtr = Vue.extend(ReagentModalComponent);
var vueElem = new vueComponentCtr({
propsData: {
idPrefix: idPrefix + plateId,
reagentType: reagentType,
inputTarget: idPrefix + plateId,
checksCallback: checksCallback
}
});
vueElem.$mount("#vue-elem-" + idPrefix + plateId);
});
}
function createCheckboxDOM(
$targetDiv,
plateId,
checksCallback,
label,
checked,
idPrefix
) {
var $rowDiv = $("<div>")
.addClass("form-group")
.appendTo($targetDiv);
$("<label>")
.attr("for", idPrefix + plateId)
.addClass("col-sm-2 control-label")
.append(label)
.appendTo($rowDiv);
var $colDiv = $("<div>")
.addClass("col-sm-10")
.appendTo($rowDiv);
var $inElem = $("<input>")
.attr("type", "checkbox")
.attr("id", idPrefix + plateId)
.prop("checked", checked)
.appendTo($colDiv)
.on("change", checksCallback);
}
/**
*
* Auxiliary function to check the availability of a plate name as the
* user types it
*
* @param e event The event object from the key up function
* @param input str The name of the input element
* @param checksCallback function Callback function to change the rest of the interface
* @param successCallback function Callback function to execute when the user hits enter and the name doesn't exist
*
* Notes: for this function to work properly, the input should be contained
* in a structure like the one below. The div can contain an optional label.
*
* <div class='form-group has-error has-feedback'>
* **** <label for='newNameInput'>New name:</label> <---- This label is optional
* <input type='text' class='form-control' id='<>INPUT ID'>
* <span class='glyphicon glyphicon-remove form-control-feedback'></span>
* </div>
*
**/
function onKeyUpPlateName(e, input, checksCallback, successCallback) {
// Check if the new value is the empty string
var value = $("#" + input)
.val()
.trim();
var $div = $("#" + input).closest("div");
if (value === "") {
$div
.removeClass("has-success")
.addClass("has-error")
.find("span")
.removeClass("glyphicon-ok")
.addClass("glyphicon-remove");
$("#newNameDivMessage").text("No name specified");
}
if (value !== "") {
$.get("/platename?new-name=" + value, function(data) {
// If we get here it means that the name already exists
$div
.removeClass("has-success")
.addClass("has-error")
.find("span")
.removeClass("glyphicon-ok")
.addClass("glyphicon-remove");
$("#newNameDivMessage").text("Name is already used");
// $('#updateNameBtn').prop('disabled', true);
checksCallback();
}).fail(function(jqXHR, textStatus, errorThrown) {
// We need to check the status of the response
if (jqXHR.status === 404) {
// The plate name doesn't exist - it is ok to change to this name
$div
.removeClass("has-error")
.addClass("has-success")
.find("span")
.removeClass("glyphicon-remove")
.addClass("glyphicon-ok");
$("#newNameDivMessage").text("Name is available");
// $('#updateNameBtn').prop('disabled', false);
checksCallback();
if (e.which == 13 && successCallback !== undefined) {
// This means that the user pressed the enter key
// so we will just call the success callback
successCallback();
}
} else {
bootstrapAlert(jqXHR.responseText, "danger");
checksCallback();
}
});
} else {
$div
.removeClass("has-success")
.addClass("has-error")
.find("span")
.removeClass("glyphicon-ok")
.addClass("glyphicon-remove");
// $('#updateNameBtn').prop('disabled', true);
checksCallback();
}
}
/**
* Adds a Bootstrap alert message to the body of the current page.
*
* @param {string} message Message to display
* @param {string} severity OPTIONAL. One of 'danger' (default), 'info', 'warning' or 'success'.
* @param {integer} timeout OPTIONAL. When given, seconds before alert fades out
*
**/
function bootstrapAlert(message, severity, timeout) {
$(".modal").modal("hide");
// make timeout an optional parameter
timeout = timeout || -1;
// make severity an optinal parameter
severity = typeof severity !== "undefined" ? severity : "danger";
// Remove any previous alert message
$("#alert-message").remove();
// Crate the div that contains the message and append the alert message
var alertDiv = $("<div>", {
class: "alert fade in alert-" + severity,
role: "alert",
id: "alert-message"
})
.append('<a href="#" class="close" data-dismiss="alert">×</a>')
.append(
'<span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span>'
)
.append(message);
// Add the alert div just under the navbar
$("#template-content").prepend(alertDiv);
// Set a timeout for the alert div if needed
if (timeout > 0) {
if (timeoutHandleForBoostrapAlert != null) {
// This is needed in case that a new alert is generated while
// an alert is already shown
window.clearTimeout(timeoutHandleForBoostrapAlert);
}
timeoutHandleForBoostrapAlert = window.setTimeout(function() {
$("#alert-message").remove();
timeoutHandleForBoostrapAlert = null;
}, timeout * 1000); // * 1000 to transform from seconds to miliseconds
}
}
/**
*
* Get's the next row id
* Adapted from: https://stackoverflow.com/a/34483399
*
* @param {char} row The current row id
*
* @return {string}
*
**/
function getNextRowId(row) {
var u = row.toUpperCase();
if (sameStrChar(u, "Z")) {
var txt = "";
var i = u.length;
while (i--) {
txt += "A";
}
return txt + "A";
} else {
var p = "";
var q = "";
if (u.length > 1) {
p = u.substring(0, u.length - 1);
q = String.fromCharCode(p.slice(-1).charCodeAt(0));
}
var l = u.slice(-1).charCodeAt(0);
var z = nextLetter(l);
if (z === "A") {
return p.slice(0, -1) + nextLetter(q.slice(-1).charCodeAt(0)) + z;
} else {
return p + z;
}
}
}
/**
*
* Aux function for getNextRowId
* Returns the letter after the given one
*
* @param {char} l The current letter
*
* @return {char} The next letter
*
**/
function nextLetter(l) {
if (l < 90) {
return String.fromCharCode(l + 1);
} else {
return "A";
}
}
/**
*
* Aux function for getNextRowId
* Returns if str and char are the same
*
* @param {str} str The string to compare
* @param {char} char The char to compare
*
* @return {char} The next letter
*
**/
function sameStrChar(str, char) {
var i = str.length;
while (i--) {
if (str[i] !== char) {
return false;
}
}
return true;
}
/**
*
**/
function addIfNotPresent(array, elem) {
var idx = array.indexOf(elem);
if (idx === -1) {
array.push(elem);
}
}
function safeArrayDelete(array, elem) {
var idx = array.indexOf(elem);
if (idx !== -1) {
array.splice(idx, 1);
}
}
/**
* Determine an appropriate clipping value for the heatmap's maximum value.
*
* @param {Float} plateType String describing the plate type.
* @returns A maximum expected value for the colorscale of a heatmap.
*
*/
function clippingForPlateType(plateType) {
if (plateType == "16S library prep") {
return 100;
} else if (plateType == "shotgun library prep") {
return 30;
} else if (plateType == "gDNA" || plateType == "compressed gDNA plates") {
return 20;
}
// should never get here but if it does, then the range is permissive
return 10000;
}
/**
* Create a heatmap with well compositions and a histogram of the DNA
* concentrations.
*
* The array parameters are all matched one-to-one i.e. element (2, 3) in
* every array represents the same well in the plate.
*
* @param {String} plateId Element identifier for a given plate.
* @param {Array} concentrations A 2D array of floating point values
* representing the concentrations of a plate.
* @param {Array} blanks A 2D array of well names.
* @param {Float} defaultClipping A number representing the default clipping
* value for the heatmap. Depends on the processing stage and the type of
* data being processed.
* @param {Object[]} options Optional parameters
* @param {string} options[].colormap Optional colormap name for the heatmap,
# if not provided then "YlGnBu" is used. For more information see:
* https://matplotlib.org/users/colormaps.html
* @param {string} options[].amounts The descriptor of the value being
* displayed to use for annotation. If not provided, defaults to "Value"
*
*/
function createHeatmap(
plateId,
concentrations,
blanks,
names,
defaultClipping,
options
) {
var colormap = options.colormap || "YlGnBu";
var amounts = options.amounts || "Value";
var $container = $("#pool-results-" + plateId);
// existing plot containers need to be removed
$container.children().remove();
var $heatmap = $('<div id="heatmap-' + plateId + '"></div>');
var $histogram = $('<div id="histogram-' + plateId + '"></div>');
$heatmap.css({ position: "relative" });
var $spinnerContainer = $('<div name="slider-container"></div>');
var $spinner = $('<input name="clipping-spinner" type="number">');
var $label = $("<label>Clip values greater than</label>");
var $resetButton = $("<button>reset</button>");
$label.append($spinner);
$spinnerContainer.append($label);
$spinnerContainer.append("<br>");
$spinnerContainer.append($resetButton);
$spinnerContainer.css({
width: "200px",
height: "100px",
position: "absolute",
top: "0",
left: "20px",
"z-index": "10"
});
$heatmap.append($spinnerContainer);
$container.append($heatmap);
$container.append($histogram);
// the arrays are reversed to have element (0, 0) at the top of the
// heatmap, which matches the location of the wells in a physical plate
blanks = blanks.reverse();
concentrations = concentrations.reverse();
names = names.reverse();
var letters = "ABCDEFGHIJKLMPNOPQRSTUVWXYZ".split(""),
yLabels;
yLabels = letters.slice(0, concentrations.length);
yLabels = yLabels.reverse();
var minConcentration = 0;
var hoverlabels = [],
annotations = [],
result;
var flattenedBlanks = [],
flattenedNonBlanks = [];
// this double loop will construct the arrays necessary for the histogram
// and the heatmap (including annotations, and legends)
for (var i = 0; i < names.length; i++) {
hoverlabels[i] = [];
for (var j = 0; j < names[0].length; j++) {
// per-well annotations on the cells, indicate with a special character
// when the well represents a blank sample
result = {
x: j + 1,
y: yLabels[i],
text: blanks[i][j] ? "🔳" : "",
showarrow: false
};
annotations.push(result);
// per-well labels
hoverlabels[i].push(
"Row : " +
yLabels[i] +
" Column : " +
(j + 1) +
" <br>" +
amounts +
" : " +
concentrations[i][j] +
" <br> Sample Name : " +
(names[i][j] == null ? "Not Available" : names[i][j])
);
// split the concentrations to show different colors in the histogram
if (blanks[i][j] === true) {
flattenedBlanks.push(concentrations[i][j]);
} else {
flattenedNonBlanks.push(concentrations[i][j]);
}
}
}
minConcentration = Math.min.apply(
null,
flattenedBlanks.concat(flattenedNonBlanks)
);
// setup the plotly definitions
var heatmapData = [
{
x: [1],
y: yLabels,
z: concentrations,
text: hoverlabels,
hoverinfo: "text",
type: "heatmap",
colorscale: colormap,
colorbar: {
title: amounts,
titleside: "top"
},
xgap: 1,
ygap: 1,
zmin: 0,
zmax: defaultClipping
}
];
// make each cell a square
var heatwidth = (600 / yLabels.length) * names[0].length;
var heatmapLayout = {
autosize: false,
height: 600,
width: heatwidth,
xaxis: {
autotick: false,
side: "top"
},
annotations: annotations,
title: "Per-well " + amounts
};
var nonBlankData = {
name: "Non-Blank",
x: flattenedNonBlanks,
type: "histogram",
marker: {
color: "rgba(27, 158, 119, 1)",
line: {
color: "rgba(27, 158, 119, 1)",
width: 5
}
}
};
var blankData = {
name: "Blank",
x: flattenedBlanks,
type: "histogram",
marker: {
color: "rgba(217, 95, 2, 1)",
line: {
color: "rgba(217, 95, 2, 1)",
width: 5
}
}
};
var histogramLayout = {
autosize: false,
width: heatwidth,
xaxis: { title: amounts },
yaxis: { title: "Number Samples" },
title: amounts + " Distribution"
};
var histogramData = [nonBlankData, blankData];
// if a plot exists with this id it should be removed
Plotly.purge($heatmap.attr("id"));
Plotly.purge($histogram.attr("id"));
Plotly.plot($heatmap.attr("id"), heatmapData, heatmapLayout);
Plotly.plot($histogram.attr("id"), histogramData, histogramLayout);
// setup some interactivity to clip the values in the histogram
$(function() {
var text = "Clip values greater than ";
// pad the minimum so the colorscale doesn't error
$spinner.val(defaultClipping);
$spinner.attr("min", minConcentration + 1);
$spinner.on("input", function(a, b) {
var clipping = parseFloat($spinner.val());
Plotly.update($heatmap.attr("id"), { zmax: clipping }, 0);
});
$resetButton.on("click", function() {
$spinner.val(defaultClipping);
Plotly.update($heatmap.attr("id"), { zmax: defaultClipping }, 0);
});
});
}
/**
*
* Given a query string and an array of strings to search through, returns a
* subset of the array containing only strings that contain the query string
* (or an empty array, if no such matches are found).
*
* This search is case insensitive, so "abc" will match with "ABCDEF".
*
* Note that if queryString is empty (i.e. "") then this won't return any
* matches, even if "" is present in stringArray for some reason (since
* stringArray should be a list of sample IDs, this should never be the case).
*
* This function is loosely based on textFilterFeatures() in Qurro:
* https://github.com/biocore/qurro/blob/3f4650fb677753e978d971b06794d4790b051d30/qurro/support_files/js/feature_computation.js#L29
*
* @param {string} queryString The string that will be searched for
* @param {array} stringArray Collection of strings to check against the query
* @returns {array} Collection of strings in stringArray that include the query
*
*/
function getSubstringMatches(queryString, stringArray) {
if (queryString.length === 0 || stringArray.length === []) {
return [];
}
var queryStringLowerCase = queryString.toLowerCase();
var matchingStrings = [];
for (var i = 0; i < stringArray.length; i++) {
if (stringArray[i].toLowerCase().includes(queryStringLowerCase)) {
matchingStrings.push(stringArray[i]);
}
}
return matchingStrings;
}