-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathQCPlotHelperBase.js
More file actions
1029 lines (887 loc) · 45.8 KB
/
QCPlotHelperBase.js
File metadata and controls
1029 lines (887 loc) · 45.8 KB
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
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2016-2019 LabKey Corporation
*
* Licensed under the Apache License, Version 2.0: http://www.apache.org/licenses/LICENSE-2.0
*/
Ext4.define("LABKEY.targetedms.QCPlotHelperBase", {
statics: {
qcPlotTypes : ['Metric Value', 'Moving Range', 'CUSUMm', 'CUSUMv', 'Trailing CV', 'Trailing Mean'],
maxPointsPerSeries : 300,
shapeDomain: ['Include', 'Exclude', 'Include-Outlier', 'Exclude-Outlier']
},
showMetricValuePlot: function() {
return this.isPlotTypeSelected('Metric Value');
},
showMovingRangePlot: function() {
return this.isPlotTypeSelected('Moving Range');
},
showMeanCUSUMPlot: function() {
return this.isPlotTypeSelected('CUSUMm');
},
showVariableCUSUMPlot: function() {
return this.isPlotTypeSelected('CUSUMv');
},
isPlotTypeSelected: function(plotType) {
return this.plotTypes.indexOf(plotType) > -1;
},
showTrailingMeanPlot: function() {
return this.isPlotTypeSelected('Trailing Mean');
},
showTrailingCVPlot: function() {
return this.isPlotTypeSelected('Trailing CV');
},
getGuideSetDataObj : function(row) {
return {
ReferenceEnd: row['ReferenceEnd'],
TrainingEnd: row['TrainingEnd'],
TrainingStart: row['TrainingStart'],
Comment: row['Comment'],
Series: {}
};
},
processRawGuideSetData: function (plotDataRows) {
if (!this.guideSetDataMap)
this.guideSetDataMap = {};
Ext4.each(plotDataRows, function (plotDataRow) {
Ext4.each(plotDataRow.GuideSetStats, function (guideSetStat) {
const guideSetId = guideSetStat['GuideSetId'];
const metricId = guideSetStat['MetricId'];
const seriesLabel = plotDataRow['SeriesLabel'];
if (!this.guideSetDataMap[guideSetId]) {
this.guideSetDataMap[guideSetId] = this.getGuideSetDataObj(guideSetStat);
}
if (!this.guideSetDataMap[guideSetId].Series[seriesLabel]) {
this.guideSetDataMap[guideSetId].Series[seriesLabel] = {};
}
if (!this.guideSetDataMap[guideSetId].Series[seriesLabel][metricId]) {
this.guideSetDataMap[guideSetId].Series[seriesLabel][metricId] = {}
}
this.guideSetDataMap[guideSetId].Series[seriesLabel][metricId].MeanMR = guideSetStat['MeanMR'];
this.guideSetDataMap[guideSetId].Series[seriesLabel][metricId].StdDevMR = guideSetStat['StdDevMR'];
this.guideSetDataMap[guideSetId].Series[seriesLabel][metricId].MeanTrailingMean = guideSetStat['MeanTrailingMean'];
this.guideSetDataMap[guideSetId].Series[seriesLabel][metricId].StdDevTrailingMean = guideSetStat['StdDevTrailingMean'];
this.guideSetDataMap[guideSetId].Series[seriesLabel][metricId].MeanTrailingCV = guideSetStat['MeanTrailingCV'];
this.guideSetDataMap[guideSetId].Series[seriesLabel][metricId].StdDevTrailingCV = guideSetStat['StdDevTrailingCV'];
}, this);
}, this);
},
getPlotsData: function() {
// get input number N
// pass includeTrailingCV or includeTrailingMean in plotsConfig
const plotsConfig = {};
plotsConfig.metricId = this.metric;
plotsConfig.metricId2 = this.metric2;
plotsConfig.includeLJ = this.showMetricValuePlot();
plotsConfig.includeMR = this.showMovingRangePlot();
plotsConfig.includeMeanCusum = this.showMeanCUSUMPlot();
plotsConfig.includeVariableCusum = this.showVariableCUSUMPlot();
plotsConfig.showExcluded = this.showExcluded;
// show reference guide set for custom date range
plotsConfig.showReferenceGS = this.showReferenceGS && this.dateRangeOffset !== 0;
plotsConfig.showExcludedPrecursors = this.showExcludedPrecursors;
plotsConfig.trailingRuns = this.trailingRuns;
plotsConfig.includeTrailingMeanPlot = this.showTrailingMeanPlot();
plotsConfig.includeTrailingCVPlot = this.showTrailingCVPlot();
let urlParams = LABKEY.ActionURL.getParameters();
if (parseInt(urlParams['replicateId']) > 0) {
plotsConfig.replicateId = parseInt(urlParams['replicateId']);
}
const config = this.getReportConfig()
if (this.selectedAnnotations) {
plotsConfig.selectedAnnotations = [];
Ext4.Object.each(this.selectedAnnotations, function (name, values) {
plotsConfig.selectedAnnotations.push({
name: name,
values: values
})
}, this);
}
if (config) {
plotsConfig.startDate = config.StartDate;
plotsConfig.endDate = config.EndDate;
}
// Track and cancel in-flight request; ensure only latest response is processed
this._qcRequestSeq = (this._qcRequestSeq || 0) + 1;
const requestSeq = this._qcRequestSeq;
// Abort any previous in-flight request if possible
if (this._qcActiveRequest && typeof this._qcActiveRequest.abort === 'function') {
try { this._qcActiveRequest.abort(); } catch (e) { /* no-op */ }
}
const failureCb = LABKEY.Utils.getCallbackWrapper(this.failureHandler, this);
this._qcActiveRequest = LABKEY.Ajax.request({
url: LABKEY.ActionURL.buildURL('targetedms', 'GetQCPlotsData.api'),
success: function(response) {
// Ignore if not the most recent request
if (requestSeq !== this._qcRequestSeq)
return;
try {
this.lastParsedResponse = JSON.parse(response.responseText);
this.processPlotData();
}
finally {
// Clear active request handle
if (requestSeq === this._qcRequestSeq)
this._qcActiveRequest = null;
}
},
failure: function(response) {
// Ignore failures from stale/aborted requests
if (requestSeq !== this._qcRequestSeq)
return;
try { failureCb(response); } finally {
if (requestSeq === this._qcRequestSeq)
this._qcActiveRequest = null;
}
},
scope: this,
jsonData: plotsConfig
});
},
processPlotData: function() {
var parsed = this.lastParsedResponse;
if (!parsed)
return;
var plotDataRows = parsed.plotDataRows;
const metricProps = {};
for (let x = 0; x < parsed.metricProps.length; x++) {
metricProps[parsed.metricProps[x].id] = parsed.metricProps[x];
}
var sampleFiles = parsed.sampleFiles;
this.filterQCPoints = parsed.filterQCPoints;
var allPlotDateValues = [];
this.setPrecursorsForPage(plotDataRows);
// process the data to shape it for the JS LeveyJenningsPlot API call
this.fragmentPlotData = {};
if (this.showMetricValuePlot()) {
this.processLJGuideSetData(plotDataRows);
}
if (this.showMovingRangePlot() || this.showMeanCUSUMPlot() || this.showVariableCUSUMPlot() || this.showTrailingMeanPlot() || this.showTrailingCVPlot()) {
this.processRawGuideSetData(plotDataRows);
}
let sampleFilesById = {};
Ext4.iterate(sampleFiles, function (sampleFile) {
sampleFilesById[sampleFile['SampleId']] = sampleFile;
}, this);
let tempData; // temp variable to store data for setting the date
let foundTrue = false
let trainingSeqIdx = 1; // this index is used for displaying the average number of runs in tooltip (QCPlotHoverPanel.js L110)
for (let i = this.pagingStartIndex; i < this.pagingEndIndex; i++) {
const plotDataRow = plotDataRows[i];
tempData = plotDataRow;
const fragment = plotDataRow.SeriesLabel;
Ext4.iterate(plotDataRow.data, function (plotData) {
// Flatten the sample file data into each row
let sampleFile = sampleFilesById[plotData['SampleFileId']];
plotData['FilePath'] = sampleFile['FilePath'];
plotData['ReplicateId'] = sampleFile['ReplicateId'];
plotData['AcquiredTime'] = sampleFile['AcquiredTime'];
plotData['GuideSetId'] = sampleFile['GuideSetId'];
plotData['ReplicateName'] = sampleFile['ReplicateName'];
plotData['InGuideSetTrainingRange'] = sampleFile['InGuideSetTrainingRange'];
const gs = this.guideSetDataMap[plotData['GuideSetId']];
if (Ext4.isDefined(gs) && gs.Series[fragment]) {
if (plotData['InsideGuideSet']) {
if (!foundTrue) {
foundTrue = true;
trainingSeqIdx = 1;
}
} else {
foundTrue = false;
}
plotData['TrainingSeqIdx'] = trainingSeqIdx;
trainingSeqIdx++
}
var data = this.processPlotDataRow(plotData, plotDataRow, fragment, metricProps);
this.fragmentPlotData[fragment].data.push(data);
this.fragmentPlotData[fragment].precursorScoped = metricProps[data.MetricId].precursorScoped;
this.setSeriesMinMax(this.fragmentPlotData[fragment], data);
allPlotDateValues.push(data.fullDate);
}, this);
}
// Issue 31678: get the full set of dates values from the precursor data and from the annotations
for (var j = 0; j < this.annotationData.length; j++) {
allPlotDateValues.push(this.formatDate(new Date(this.annotationData[j].Date), true));
}
allPlotDateValues = Ext4.Array.unique(allPlotDateValues).sort();
this.legendHelper = LABKEY.targetedms.QCPlotLegendHelper;
this.legendHelper.setupLegendPrefixes(this.fragmentPlotData, 3);
// merge in the annotation data to make room on the y axis
for (var i = 0; i < this.precursors.length; i++) {
let frag = this.precursors[i];
var precursorInfo = this.fragmentPlotData[frag];
// We don't necessarily have info for all possible precursors, depending on the filters and plot type
if (precursorInfo) {
// if the min and max are the same, or very close, increase the range
if (precursorInfo.max == null && precursorInfo.min == null) {
precursorInfo.max = 1;
precursorInfo.min = 0;
}
else if (precursorInfo.max - precursorInfo.min < 0.0001) {
var factor = precursorInfo.max < 0.1 ? 0.1 : 1;
precursorInfo.max += factor;
precursorInfo.min -= factor;
}
// Issue 31678: add any missing dates from the other plots or from the annotations
var dateProp = this.groupedX ? "date" : "fullDate";
var precursorDates = Ext4.Array.pluck(precursorInfo.data, dateProp);
var datesToAdd = [];
for (var j = 0; j < allPlotDateValues.length; j++) {
var dateVal = this.formatDate(allPlotDateValues[j], !this.groupedX);
var dataIsMissingDate = precursorDates.indexOf(dateVal) === -1 && Ext4.Array.pluck(datesToAdd, dateProp).indexOf(dateVal) === -1;
if (dataIsMissingDate) {
datesToAdd.push({
type: 'missing',
fullDate: this.formatDate(allPlotDateValues[j], true),
date: this.formatDate(allPlotDateValues[j]),
groupedXTick: dateVal
});
}
}
if (datesToAdd.length > 0) {
var index = 0;
for (var k = 0; k < datesToAdd.length; k++) {
var added = false;
for (var l = index; l < precursorInfo.data.length; l++) {
if ((this.groupedX && precursorInfo.data[l].date > datesToAdd[k].date)
|| (!this.groupedX && precursorInfo.data[l].fullDate > datesToAdd[k].fullDate)) {
precursorInfo.data.splice(l, 0, datesToAdd[k]);
added = true;
index = l;
break;
}
}
// tack on any remaining dates to the end
if (!added) {
precursorInfo.data.push(datesToAdd[k]);
}
}
}
// this.filterPoints - object to store left and right indices to truncate for a series for custom date range
// when showing reference guide set
if (this.filterQCPoints) {
if (!this.filterPoints) {
this.filterPoints = {};
}
if (!this.filterPoints[frag]) {
this.filterPoints[frag] = {};
}
for (let j = 0; j < precursorInfo.data.length; j++) {
let plotData = precursorInfo.data[j];
if (!this.filterPoints[frag][plotData.MetricId]) {
this.filterPoints[frag][plotData.MetricId] = {}
}
if (plotData.type === "missing") {
continue;
}
Ext4.Object.each(this.guideSetDataMap, function(guideSetId, guideSetData) {
// for truncating out of range guideset data find first index of plotDate ending at guideset.trainingEnd
if (plotData.guideSetId === guideSetId && plotData.inGuideSetTrainingRange && guideSetData.TrainingEnd <= this.startDate) {
this.filterPoints[frag][plotData.MetricId]['filterPointsFirstIndex'] = j + 1;
// ReferenceRangeSeries is used to separate series
plotData['ReferenceRangeSeries'] = "GuideSet";
}
else {
plotData['ReferenceRangeSeries'] = "InRange";
}
}, this);
// for truncating out of range guideset data find last index of plotData starting from this.startDate
if (plotData.fullDate >= this.startDate) {
if (!this.filterPoints[frag][plotData.MetricId]['filterPointsLastIndex']) {
this.filterPoints[frag][plotData.MetricId]['filterPointsLastIndex'] = j;
}
}
}
}
}
}
var maxPointsPerSeries = 0;
for (var i = 0; i < this.precursors.length; i++) {
if (this.fragmentPlotData[this.precursors[i]]) {
maxPointsPerSeries = Math.max(this.fragmentPlotData[this.precursors[i]].data.length, maxPointsPerSeries);
}
}
this.showDataPoints = maxPointsPerSeries <= LABKEY.targetedms.QCPlotHelperBase.maxPointsPerSeries;
if (this.showExpRunRange && this.filterPoints) {
for (let i = 0; i < plotDataRows.length; i++) {
Ext4.Object.each(this.filterPoints[plotDataRows[i].SeriesLabel], function (metricId, filterPointsData) {
// no need to filter if less than 6 data points are present between reference end of guideset and startdate
if (filterPointsData['filterPointsFirstIndex'] && filterPointsData['filterPointsLastIndex']) {
if (filterPointsData['filterPointsLastIndex'] - filterPointsData['filterPointsFirstIndex'] < 6) {
this.filterQCPoints = false;
// set the startDate field = acquired time of the 1st point of 5 points before the experiment run range
this.getStartDateField().setValue(this.formatDate(plotDataRows[i].data[filterPointsData['filterPointsFirstIndex']].AcquiredTime));
}
else { // skip 5 points
filterPointsData['filterPointsLastIndex'] = filterPointsData['filterPointsLastIndex'] - 6;
// set the startDate field = acquired time of the 1st point of 5 points before the experiment run range
// adding 1 as the point is right after filter last index
this.getStartDateField().setValue(this.formatDate(plotDataRows[i].data[filterPointsData['filterPointsLastIndex'] + 1].AcquiredTime));
}
}
}, this);
}
}
this.renderPlots();
},
renderPlots: function() {
if (this.filterQCPoints) {
this.truncateOutOfRangeQCPoints();
}
// do not persist plot options in qc folder if changed after coming through experimental folder link
if (!this.showExpRunRange) {
this.persistSelectedFormOptions();
}
if (this.precursors.length === 0) {
this.failureHandler({message: "There were no records found. The date filter applied may be too restrictive."});
return;
}
Ext4.get(this.plotDivId).update("");
this.setBrushingEnabled(false);
this.setPlotWidth(this.plotDivId);
let addedPlot;
const metricProps = {};
metricProps[this.metric] = this.getMetricPropsById(this.metric);
if (this.isMultiSeries()) {
metricProps[this.metric2] = this.getMetricPropsById(this.metric2);
}
if (this.singlePlot && this.getMetricPropsById(this.metric).precursorScoped) {
addedPlot = this.addCombinedPeptideSinglePlot(metricProps);
}
else {
addedPlot = this.addIndividualPrecursorPlots(metricProps);
}
if (!addedPlot) {
Ext4.get(this.plotDivId).insertHtml('beforeEnd', '<div>No data to plot</div>');
}
Ext4.get(this.plotDivId).unmask();
},
truncateOutOfRangeQCPoints: function() {
Ext4.Object.each(this.fragmentPlotData, function(label, fragmentData) {
// traverse plotData backwards from firstIndex to lastIndex and
// remove them from the array
if (this.filterQCPoints && this.filterPoints) {
// when we're plotting two different metrics at the same time, then we
// have repeated dates (from oldest to newest for metric 1, and then oldest to newest for metric 2, all in the same array).
// so, removing the array elements from the back
const filterPointsReversed = Object.keys(this.filterPoints[label]).reverse();
const lab = label;
filterPointsReversed.forEach(metricId => {
let firstIndex = this.filterPoints[lab][metricId]['filterPointsFirstIndex'];
let lastIndex = this.filterPoints[lab][metricId]['filterPointsLastIndex'];
for (let i = lastIndex; i >= firstIndex; i--) {
fragmentData.data.splice(i, 1);
}
});
}
}, this);
},
getBasePlotConfig : function(id, data, legenddata) {
return {
rendererType : 'd3',
renderTo : id,
clipRect: true, // set this to true to prevent lines from running outside of the plot region
data : Ext4.Array.clone(data),
width : this.getPlotWidth(),
height : this.singlePlot ? 500 : 300,
gridLineColor : 'white',
legendData : Ext4.Array.clone(legenddata),
legendNoWrap: true
};
},
getPlotWidth: function() {
return this.plotWidth - 30;
},
calculatePlotIndicesBetweenDates: function (precursorInfo) {
var startDate = new Date(this.expRunDetails.startDate);
var endDate = new Date(this.expRunDetails.endDate);
var startIndex;
var endIndex;
if (precursorInfo) {
// fragmentPlotData has plot data separated by series labels
const data = precursorInfo.data;
for (let index = 0; index < data.length; index++) {
const pointDate = new Date(data[index].fullDate)
if (pointDate >= startDate && pointDate < endDate) {
if (startIndex === undefined) {
startIndex = data[index].seqValue;
}
}
if (pointDate >= endDate) {
if (!endIndex) {
endIndex = data[index].seqValue;
}
}
// this happens for custom date range shorter than exp date range
else if (index === data.length - 1 && endIndex === undefined && startIndex !== undefined) {
endIndex = data[data.length - 1].seqValue;
}
const foundIndices = startIndex !== undefined && endIndex !== undefined;
if (foundIndices) {
this.expRunDetails['startIndex'] = startIndex;
this.expRunDetails['endIndex'] = endIndex;
break;
}
}
}
},
// TODO: Move this to tests
testVals: {
a: {fragment:'', dataType: 'Peptide', result: ''},
b: {fragment:'A', dataType: 'Peptide', result: 'A'},
c: {fragment:'A', dataType: 'Peptide', result: 'A'}, // duplicate
d: {fragment:'AB', dataType: 'Peptide', result: 'AB'},
e: {fragment:'ABC', dataType: 'Peptide', result: 'ABC'},
f: {fragment:'ABCD', dataType: 'Peptide', result: 'ABCD'},
g: {fragment:'ABCDE', dataType: 'Peptide', result: 'ABCDE'},
h: {fragment:'ABCDEF', dataType: 'Peptide', result: 'ABCDEF'},
i: {fragment:'ABCDEFG', dataType: 'Peptide', result: 'ABCDEFG'},
j: {fragment:'ABCDEFGH', dataType: 'Peptide', result: 'ABC…FGH'},
k: {fragment:'ABCDEFGHI', dataType: 'Peptide', result: 'ABC…GHI'},
l: {fragment:'ABCE', dataType: 'Peptide', result: 'ABCE'},
m: {fragment:'ABDEFGHI', dataType: 'Peptide', result: 'ABD…'},
n: {fragment:'ABEFGHI', dataType: 'Peptide', result: 'ABEFGHI'},
o: {fragment:'ABEFGHIJ', dataType: 'Peptide', result: 'ABE…HIJ'},
p: {fragment:'ABEFHI', dataType: 'Peptide', result: 'ABEFHI'},
q: {fragment:'ABFFFGHI', dataType: 'Peptide', result: 'ABF(5)'},
r: {fragment:'ABFFFFGHI', dataType: 'Peptide', result: 'ABF(6)'},
s: {fragment:'ABFFFFAFGHI', dataType: 'Peptide', result: 'ABF…FA…'},
t: {fragment:'ABFFFAFFGHI', dataType: 'Peptide', result: 'ABF…A…'},
u: {fragment:'ABGAABAABAGHI', dataType: 'Peptide', result: 'ABG…B…B…'},
v: {fragment:'ABGAAbAABAGHI', dataType: 'Peptide', result: 'ABG…b…B…'},
w: {fragment:'ABGAABAAbAGHI', dataType: 'Peptide', result: 'ABG…B…b…'},
x: {fragment:'ABGAAB[80]AAB[99]AGHI', dataType: 'Peptide', result: 'ABG…b…b…'},
y: {fragment:'C32:0', dataType: 'ion', result: 'C32:0'},
z: {fragment:'C32:1', dataType: 'ion', result: 'C32:1'},
aa: {fragment:'C32:2', dataType: 'ion', result: 'C32:2'},
bb: {fragment:'C32:2', dataType: 'ion', result: 'C32:2'},
cc: {fragment:'C30:0', dataType: 'ion', result: 'C30:0'},
dd: {fragment:'C[30]:0', dataType: 'ion', result: 'C[30]:0'},
ee: {fragment:'C[400]:0', dataType: 'ion', result: 'C[4…'},
ff: {fragment:'C12:0 fish breath', dataType: 'ion', result: 'C12…'},
gg: {fragment:'C15:0 fish breath', dataType: 'ion', result: 'C15(14)'},
hh: {fragment:'C15:0 doggy breath', dataType: 'ion', result: 'C15(15)'},
ii: {fragment:'C16:0 fishy breath', dataType: 'ion', result: 'C16…f…'},
jj: {fragment:'C16:0 doggy breath', dataType: 'ion', result: 'C16…d…'},
kk: {fragment:'C14', dataType: 'ion', result: 'C14'},
ll: {fragment:'C14:1', dataType: 'ion', result: 'C14:1'},
mm: {fragment:'C14:1-OH', dataType: 'ion', result: 'C14:1…'},
nn: {fragment:'C14:2', dataType: 'ion', result: 'C14:2'},
oo: {fragment:'C14:2-OH', dataType: 'ion', result: 'C14:2…'},
},
testLegends: function() {
var legendHelper = LABKEY.targetedms.QCPlotLegendHelper;
legendHelper.setupLegendPrefixes(this.testVals, 3);
for (let key in this.testVals) {
if (this.testVals.hasOwnProperty(key)) {
const val = legendHelper.getUniquePrefix(this.testVals[key].fragment, (this.testVals[key].dataType === 'Peptide'));
if (val !== this.testVals[key].result)
console.log("Incorrect result for " + this.testVals[key].fragment + ". Expected: " + this.testVals[key].result + ", Actual: " + val);
}
}
},
getCombinedPlotLegendData: function(metricProps, groupColors, yAxisCount, plotType, isCUSUMMean) {
let newLegendData = Ext4.Array.clone(this.legendData),
proteomicsLegend = [{ //Temp holder for proteomics legend labels
text: 'Peptides',
separator: true
}],
ionLegend = [{ //Temp holder for small molecule legend labels
text: 'Ions',
separator: true
}],
precursorInfo;
//Add series1 separator to Legend sections
if (this.isMultiSeries()) {
proteomicsLegend.push({
text: metricProps[this.metric].name,
separator: true
});
ionLegend.push({
text: metricProps[this.metric].name,
separator: true
});
}
const legendSeries = this.getCombinedPlotLegendSeries(plotType, isCUSUMMean);
// traverse the precursor list for: calculating the longest legend string and combine the plot data
for (var i = 0; i < this.precursors.length; i++)
{
precursorInfo = this.fragmentPlotData[this.precursors[i]];
// We may not have a match if it's been filtered out - see issue 38720
if (precursorInfo) {
const series1Legend = precursorInfo.dataType === 'Peptide' ? proteomicsLegend : ionLegend;
series1Legend.push({
name: precursorInfo.fragment + (this.isMultiSeries() ? '|' + legendSeries[0] : ''),
text: this.legendHelper.getLegendItemText(precursorInfo),
hoverText: precursorInfo.fragment,
color: groupColors[i % groupColors.length]
});
}
}
// add the fragment name for each group to the legend again for the series2 axis metric series
if (this.isMultiSeries()) {
proteomicsLegend.push({
text: metricProps[this.metric2].name,
separator: true
});
ionLegend.push({
text: metricProps[this.metric2].name,
separator: true
});
for (let i = 0; i < this.precursors.length; i++)
{
const series2Legend = precursorInfo.dataType === 'Peptide' ? proteomicsLegend : ionLegend;
precursorInfo = this.fragmentPlotData[this.precursors[i]];
series2Legend.push({
name: precursorInfo.fragment + '|' + legendSeries[1],
text: this.legendHelper.getLegendItemText(precursorInfo),
hoverText: precursorInfo.fragment,
color: groupColors[(this.precursors.length + i) % groupColors.length]
});
}
}
//Add legends if there is at least one non-separator label
if (proteomicsLegend.length > yAxisCount + 1) {
newLegendData = newLegendData.concat(proteomicsLegend);
}
if (ionLegend.length > yAxisCount + 1) {
newLegendData = newLegendData.concat(ionLegend);
}
var extraPlotLegendData = this.getAdditionalPlotLegend(plotType);
newLegendData = newLegendData.concat(extraPlotLegendData);
return newLegendData;
},
getYScaleLabel: function(plotType, conversion, metricProp) {
const label = metricProp.yAxisLabel;
let yScaleLabel;
let conversionLabel = null;
if (plotType !== LABKEY.vis.TrendingLinePlotType.MovingRange && plotType !== LABKEY.vis.TrendingLinePlotType.LeveyJennings) {
yScaleLabel = 'Sum of Deviations'
}
if (plotType === LABKEY.vis.TrendingLinePlotType.TrailingMean) {
yScaleLabel = label;
}
if (plotType === LABKEY.vis.TrendingLinePlotType.TrailingCV) {
yScaleLabel = 'CV (%)';
}
else if (conversion) {
var options = this.getYAxisOptions();
for (var i = 0; i < options.data.length; i++) {
if (options.data[i][0] === conversion)
conversionLabel = options.data[i][1];
}
}
if (!yScaleLabel) {
yScaleLabel = label;
if (conversionLabel) {
yScaleLabel = yScaleLabel ? (yScaleLabel + ' (' + conversionLabel + ')') : conversionLabel;
}
}
if (this.isMultiSeries()) {
yScaleLabel = metricProp.name + (yScaleLabel ? (' - ' + yScaleLabel) : '');
}
return yScaleLabel;
},
getSubtitle: function(precursor) {
if (!this.isMultiSeries()) {
return (precursor ? (precursor + ' - ') : '') + this.getMetricPropsById(this.metric).name;
}
return precursor;
},
addEachCombinedPrecursorPlot: function(plotIndex, id, combinePlotData, groupColors, yAxisCount, metricProps, showLogInvalid, legendMargin, plotType, isCUSUMMean, scope) {
let plotLegendData = this.getCombinedPlotLegendData(metricProps, groupColors, yAxisCount, plotType, isCUSUMMean);
if (plotType !== LABKEY.vis.TrendingLinePlotType.CUSUM) {
this.showInvalidLogMsg(id, showLogInvalid);
}
let showRange = false;
if (plotType === LABKEY.vis.TrendingLinePlotType.CUSUM && !this.metric2) {
showRange = true;
}
else if (this.yAxisScale === 'standardDeviation' && plotType === LABKEY.vis.TrendingLinePlotType.LeveyJennings) {
showRange = true;
}
else if (plotType === LABKEY.vis.TrendingLinePlotType.LeveyJennings && (metricProps[this.metric].upperBound !== undefined || metricProps[this.metric].lowerBound !== undefined)) {
showRange = true;
}
let shapeProp = 'IgnoreInQC';
let shapeDomain = [undefined, true];
if (plotType === 'Levey-Jennings') {
shapeProp = 'LJShape';
shapeDomain = this.statics().shapeDomain;
}
if (plotType === 'MovingRange') {
shapeProp = 'MRShape';
shapeDomain = this.statics().shapeDomain;
}
var trendLineProps = {
disableRangeDisplay: !showRange,
xTick: this.groupedX ? 'groupedXTick' : 'fullDate',
xTickLabel: 'date',
shape: shapeProp,
combined: true,
yAxisScale: (showLogInvalid ? 'linear' : (this.yAxisScale !== 'log' ? 'linear' : 'log')),
valueConversion: (this.yAxisScale === LABKEY.vis.PlotProperties.ValueConversion.PercentDeviation ||
this.yAxisScale === LABKEY.vis.PlotProperties.ValueConversion.StandardDeviation ||
this.yAxisScale === LABKEY.vis.PlotProperties.ValueConversion.DeltaFromMean ? this.yAxisScale : undefined),
groupBy: 'fragment',
color: 'fragment',
defaultGuideSetLabel: 'fragment',
pointSize: 2,
pointIdAttr: function(row) { return row['fullDate'] + row['fragment']; },
shapeRange: [LABKEY.vis.Scale.Shape()[0] /* circle */, LABKEY.vis.Scale.DataspaceShape()[0] /* open circle */, LABKEY.vis.Scale.Shape()[1], LABKEY.vis.Scale.Shape()[2]],
shapeDomain: shapeDomain,
showTrendLine: true,
showDataPoints: this.showDataPoints,
mouseOverFn: this.plotPointMouseOver,
mouseOverFnScope: this,
mouseOutFn: this.plotPointMouseOut,
mouseOutFnScope: this,
position: this.groupedX ? 'sequential' : undefined,
legendMouseOverFn: this.legendMouseOver,
legendMouseOverFnScope: this,
legendMouseOutFn: this.plotPointMouseOut,
legendMouseOutFnScope: this,
pathMouseOverFn: this.pathMouseOver,
pathMouseOverFnScope: this,
pathMouseOutFn: this.plotPointMouseOut,
pathMouseOutFnScope: this,
hoverTextFn: !this.showDataPoints ? function(pathData) {
return Ext4.htmlEncode(pathData.group) + '\nNarrow the date range to show individual data points.'
} : undefined,
hideSDLines: true
};
if (plotType === 'Levey-Jennings') {
trendLineProps.showBoundLines = false;
}
Ext4.apply(trendLineProps, this.getPlotTypeProperties(combinePlotData, plotType, isCUSUMMean, metricProps));
// Suppress the mean line for multi-series plots
trendLineProps.mean = undefined;
const mainTitle = LABKEY.targetedms.QCPlotHelperWrapper.getQCPlotTypeLabel(plotType, isCUSUMMean);
const basePlotConfig = this.getBasePlotConfig(id, combinePlotData.data, plotLegendData);
const plotConfig = Ext4.apply(basePlotConfig, {
margins : {
top: 65 + this.getMaxStackedAnnotations() * 12,
right: (this.showInPlotLegends() ? legendMargin : 30 ) + (this.isMultiSeries() ? 60 : 10),
left: 75,
bottom: 75
},
labels : {
main: {
value: mainTitle
},
subtitle: {
value: this.getSubtitle(''),
visibility: 'hidden', // Set as hidden so it doesn't clutter the web UI. It'll get set to visible during export, where it's useful context.
color: '#555555'
},
yLeft: {
value: this.getYScaleLabel(plotType, trendLineProps.valueConversion, metricProps[this.metric])
},
yRight: {
value: this.isMultiSeries() ? this.getYScaleLabel(plotType, trendLineProps.valueConversion, metricProps[this.metric2]) : undefined,
visibility: this.isMultiSeries() ? undefined : 'hidden'
}
},
brushing: !this.allowGuideSetBrushing() ? undefined : {
dimension: 'x',
fillOpacity: 0.4,
fillColor: 'rgba(20, 204, 201, 1)',
strokeColor: 'rgba(20, 204, 201, 1)',
brushstart: function(event, data, extent, plot, layerSelections) {
scope.plotBrushStartEvent(plot);
},
brush: function(event, data, extent, plot, layerSelections) {
scope.plotBrushEvent(extent, plot, layerSelections);
},
brushend: function(event, data, extent, plot, layerSelections) {
scope.plotBrushEndEvent(data[data.length - 1], extent, plot);
},
brushclear: function(event, data, plot, layerSelections) {
scope.plotBrushClearEvent(data[data.length - 1], plot);
}
},
properties: trendLineProps
});
plotConfig.qcPlotType = plotType;
const plot = LABKEY.vis.TrendingLinePlot(plotConfig);
plot.render();
this.addAnnotationsToPlot(plot, combinePlotData);
this.addGuideSetTrainingRangeToPlot(plot, combinePlotData);
let urlParams = LABKEY.ActionURL.getParameters();
if (parseInt(urlParams['replicateId']) > 0) {
this.highlightOutliersForClickedReplicate(plot, combinePlotData, parseInt(urlParams['replicateId']));
}
this.attachPlotExportIcons(id, mainTitle + '- All Series', plotIndex, this.getPlotWidth(), this.showInPlotLegends() ? 0 : legendMargin);
},
addEachIndividualPrecursorPlot: function(plotIndex, id, precursorIndex, precursorInfo, metricProps, plotType, isCUSUMMean, scope) {
let trailingMeanOrCVPlot = plotType === LABKEY.vis.TrendingLinePlotType.TrailingMean ||
plotType === LABKEY.vis.TrendingLinePlotType.TrailingCV;
if (trailingMeanOrCVPlot) {
if (this.trailingRuns >= this.runs) {
Ext4.get(id).update("<span class='labkey-error'> " + plotType + " - The number you entered is larger than the number of available runs. Only " + this.runs + " runs are used for calculation</span>");
return;
}
else if (this.trailingRuns <= 2) {
Ext4.get(id).update("<span class='labkey-error'> " + plotType + " - Please enter a positive integer (>2) that is less than or equal to the total number of available runs - " + this.runs + " </span>");
return;
}
}
else if (this.yAxisScale === 'log' && plotType !== LABKEY.vis.TrendingLinePlotType.LeveyJennings && plotType !== LABKEY.vis.TrendingLinePlotType.CUSUM) {
Ext4.get(id).update("<span style='font-style: italic;'>Values that are 0 have been replaced with 0.0000001 for log scale plot.</span>");
}
else if (precursorInfo.showLogInvalid && plotType !== LABKEY.vis.TrendingLinePlotType.CUSUM) {
this.showInvalidLogMsg(id, true);
}
else if (precursorInfo.showLogWarning && plotType !== LABKEY.vis.TrendingLinePlotType.CUSUM) {
Ext4.get(id).update("<span style='font-style: italic;'>For log scale, standard deviations below "
+ "the mean with negative values have been omitted.</span>");
}
var showDataPoints = precursorInfo.data ? precursorInfo.data.length <= LABKEY.targetedms.QCPlotHelperBase.maxPointsPerSeries : true;
let shapeProp = 'IgnoreInQC';
let shapeDomain = [undefined, true];
if (plotType === 'Levey-Jennings') {
shapeProp = 'LJShape';
shapeDomain = this.statics().shapeDomain;
}
if (plotType === 'MovingRange') {
shapeProp = 'MRShape';
shapeDomain = this.statics().shapeDomain;
}
var trendLineProps = {
xTick: this.groupedX ? 'groupedXTick' : 'fullDate',
xTickLabel: 'date',
yAxisScale: (precursorInfo.showLogInvalid ? 'linear' : (this.yAxisScale !== 'log' ? 'linear' : 'log')),
valueConversion: (this.yAxisScale === LABKEY.vis.PlotProperties.ValueConversion.PercentDeviation ||
this.yAxisScale === LABKEY.vis.PlotProperties.ValueConversion.StandardDeviation ||
this.yAxisScale === LABKEY.vis.PlotProperties.ValueConversion.DeltaFromMean ? this.yAxisScale : undefined),
shape: shapeProp,
combined: false,
pointSize: 2,
pointIdAttr: function(row) { return row['fullDate']; },
shapeRange: [LABKEY.vis.Scale.Shape()[0] /* circle */, LABKEY.vis.Scale.DataspaceShape()[0] /* open circle */, LABKEY.vis.Scale.Shape()[1], LABKEY.vis.Scale.Shape()[2]],
shapeDomain: shapeDomain,
showTrendLine: true,
showDataPoints: showDataPoints,
defaultGuideSetLabel: 'fragment',
defaultGuideSets: this.defaultGuideSet,
mouseOverFn: this.plotPointMouseOver,
mouseOverFnScope: this,
position: this.groupedX ? 'sequential' : undefined,
disableRangeDisplay: this.isMultiSeries(),
hoverTextFn: !showDataPoints ? function() { return 'Narrow the date range to show individual data points.' } : undefined,
hideSDLines: true,
showBoundLines: metricProps.metricStatus !== LABKEY.targetedms.MetricStatus.PlotOnly
};
// lines are not separated when indices are not present
if (this.filterQCPoints && this.filterPoints) {
trendLineProps.lineColor = '#000000';
trendLineProps.groupBy = "ReferenceRangeSeries";
}
Ext4.apply(trendLineProps, this.getPlotTypeProperties(precursorInfo, plotType, isCUSUMMean, metricProps));
var plotLegendData = this.getAdditionalPlotLegend(plotType);
if (Ext4.isArray(this.legendData)) {
plotLegendData = plotLegendData.concat(this.legendData);
}
if (plotLegendData && plotLegendData.length > 0) {
Ext4.each(plotLegendData, function(legend) {
if (legend.text && legend.text.length > 0) {
if ( !this.longestLegendText || (this.longestLegendText && legend.text.length > this.longestLegendText))
this.longestLegendText = legend.text.length;
}
}, this);
}
const mainTitle = LABKEY.targetedms.QCPlotHelperWrapper.getQCPlotTypeLabel(plotType, isCUSUMMean);
const leftMargin = 75;
const leftMarginOffset = this.getYAxisLeftMarginOffset(precursorInfo) + leftMargin;
const labels = {
main: {
value: mainTitle
},
subtitle: {
value: this.getSubtitle(this.precursors[precursorIndex]),
visibility: 'hidden', // Set as hidden so it doesn't clutter the web UI. It'll get set to visible during export, where it's useful context.
color: '#555555'
},
yLeft: {
value: this.getYScaleLabel(plotType, trendLineProps.valueConversion, metricProps[this.metric]),
position: leftMarginOffset > 0 ? leftMarginOffset - 15 : undefined
}
};
if (this.isMultiSeries()) {
const defaultColors = LABKEY.vis.Scale.ColorDiscrete();
labels.yLeft.color = defaultColors[0];
labels.yRight = {
value: this.getYScaleLabel(plotType, trendLineProps.valueConversion, metricProps[this.metric2]),
color: defaultColors[1]
}
}
const basePlotConfig = this.getBasePlotConfig(id, precursorInfo.data, plotLegendData);
const plotConfig = Ext4.apply(basePlotConfig, {
margins : {
top: 65 + this.getMaxStackedAnnotations() * 12,
left: leftMarginOffset,
bottom: 75,
right: (this.showInPlotLegends() ? 0 : 30) // if in plot, set to 0 to auto calculate margin; otherwise, set to small value to cut off legend
},
labels: labels,
properties: trendLineProps,
brushing: !this.allowGuideSetBrushing() ? undefined : {
dimension: 'x',
fillOpacity: 0.4,
fillColor: 'rgba(20, 204, 201, 1)',
strokeColor: 'rgba(20, 204, 201, 1)',
brushstart: function(event, data, extent, plot, layerSelections) {
scope.plotBrushStartEvent(plot);
},
brush: function(event, data, extent, plot, layerSelections) {
scope.plotBrushEvent(extent, plot, layerSelections);
},
brushend: function(event, data, extent, plot, layerSelections) {
scope.plotBrushEndEvent(data[data.length - 1], extent, plot);
},
brushclear: function(event, data, plot, layerSelections) {
scope.plotBrushClearEvent(data[data.length - 1], plot);
}
}
});
// create plot using the JS Vis API
plotConfig.qcPlotType = plotType;
const plot = LABKEY.vis.TrendingLinePlot(plotConfig);
plot.render();
this.addAnnotationsToPlot(plot, precursorInfo);
this.addGuideSetTrainingRangeToPlot(plot, precursorInfo);
let urlParams = LABKEY.ActionURL.getParameters();
if (parseInt(urlParams['replicateId']) > 0) {
this.highlightOutliersForClickedReplicate(plot, precursorInfo, parseInt(urlParams['replicateId']));
}
const extraMargin = this.showInPlotLegends() ? 0 : 10 * this.longestLegendText;
this.attachPlotExportIcons(id, mainTitle + '-' + this.precursors[precursorIndex] + '-' + this.getMetricPropsById(this.metric).name, plotIndex, this.getPlotWidth(), extraMargin);
},
getYAxisLeftMarginOffset: function(precursorInfo) {
if (precursorInfo.min === undefined || precursorInfo.max === undefined) {
return 0;
}