-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathtubemap.js
4800 lines (4443 loc) · 148 KB
/
tubemap.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
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
/* eslint no-param-reassign: "off" */
/* eslint no-lonely-if: "off" */
/* eslint no-prototype-builtins: "off" */
/* eslint no-console: "off" */
/* eslint no-continue: "off" */
/* eslint max-len: "off" */
/* eslint no-loop-func: "off" */
/* eslint no-unused-vars: "off" */
/* eslint no-return-assign: "off" */
import * as d3 from "d3";
import "d3-selection-multi";
import "../config-client.js";
import externalConfig from "../config-global.mjs";
import { defaultTrackColors } from "../common.mjs";
const deepEqual = require("deep-equal");
const DEBUG = false;
const greys = [
"#d9d9d9",
"#bdbdbd",
"#969696",
"#737373",
"#525252",
"#252525",
"#000000",
];
// Greys but with a special color for the first thing.
const ygreys = [
"#9467bd",
"#d9d9d9",
"#bdbdbd",
"#969696",
"#737373",
"#525252",
"#252525",
"#000000",
];
const blues = [
"#c6dbef",
"#9ecae1",
"#6baed6",
"#4292c6",
"#2171b5",
"#08519c",
"#08306b",
];
const reds = [
"#fcbba1",
"#fc9272",
"#fb6a4a",
"#ef3b2c",
"#cb181d",
"#a50f15",
"#67000d",
];
// d3 category10
const plainColors = [
"#1f77b4",
"#ff7f0e",
"#2ca02c",
"#d62728",
"#9467bd",
"#8c564b",
"#e377c2",
"#7f7f7f",
"#bcbd22",
"#17becf",
];
// d3 category10
const lightColors = [
"#ABCCE3",
"#FFCFA5",
"#B0DBB0",
"#F0AEAE",
"#D7C6E6",
"#C6ABA5",
"#F4CCE8",
"#CFCFCF",
"#E6E6AC",
"#A8E7ED",
];
// Font stack we will use in the SVG
// We start with Courier New because it exists a lot more places than
// "Courier", and because tools like Inkscape can't interpret the text properly
// if they don't have the first font named here.
const fonts = '"Courier New", "Courier", "Lucida Console", monospace';
let svgID; // the (html-tag) ID of the svg
let svg; // the svg
export let zoom; // eslint-disable-line import/no-mutable-exports
let inputNodes = [];
let inputTracks = [];
let inputReads = [];
let inputRegion = [];
let nodes;
// Each track has a `path`, which is an array of objects describing pieces of the path that need to be drawn, in order along the path. The objects in the path are Segment objects and have fields:
//
// * order: horizontal order number at which this piece of the track's path should be drawn.
// * lane: vertical lane that this piece of the track's path should be drawn at, or null if not yet assigned.
// * isForward: true if the track is running left to right here, false if it is running right to left.
// * node: the node being visited, or null if this piece of the track is outside nodes.
let tracks;
// Each read also has a `path` list of objects (here Elements) with `order`, `isForward`, and `node` fields, but there is no `lane` field; reads are organized vertically using a completely different system than non-read tracks.
let reads;
let numberOfNodes;
let numberOfTracks;
let nodeMap; // maps node names to node indices
let nodesPerOrder;
// Contains info about lane assignments for tracks, in one list for each horizontal "order" slot.
// Each entry is an Assignment, which is a list of NodeAssignment objects.
// A NodeAssignment object is:
//
// * type: can be "single" (if only one track visits the node) or "multiple" (if multiple tracks visit the node)
// * node: the node index in nodes that the Assignment belongs to, or null if the Assignment is for a region outside of any node.
// * tracks: a list of SegmentAssignment objects
//
// A SegmentAssignment object contains:
//
// * trackID: the number of the track that the SegmentAssignment represents a piece of.
// * segmentID: the number along all that track's Segments in the track's `path` that is assigned here.
// * compareToFromSame: any earlier SegmentAssignment for this track in this order slot, or null. TODO: This is never used.
//
// This is all duplicative with the tracks' `path` lists, but is organized by order slot instead of by track.
// This is NOT used for reads! Reads use their own system.
let assignments = [];
let extraLeft = []; // info whether nodes have to be moved further apart because of multiple 180° directional changes at the same horizontal order
let extraRight = []; // info whether nodes have to be moved further apart because of multiple 180° directional changes at the same horizontal order
let maxOrder; // horizontal order of the rightmost node
const config = {
mergeNodesFlag: true,
transparentNodesFlag: false,
clickableNodesFlag: false,
showExonsFlag: false,
// Options for the width of sequence nodes:
// 0...scale node width linear with number of bases within node
// 1...scale node width with log2 of number of bases within node
// 2...scale node width with log10 of number of bases within node
nodeWidthOption: 0,
showReads: true,
showSoftClips: true,
colorSchemes: {},
// colors corresponds with tracks(input files), [haplotype, read1, read2, ...]
exonColors: "lightColors",
hideLegendFlag: false,
mappingQualityCutoff: 0,
showInfoCallback: function (info) {
alert(info);
},
};
// variables for storing info which can be directly translated into drawing instructions
let trackRectangles = [];
let trackCurves = [];
let trackCorners = [];
let trackVerticalRectangles = []; // stored separately from horizontal rectangles. This allows drawing them in a separate step -> avoids issues with wrong overlapping
let trackRectanglesStep3 = [];
let maxYCoordinate = 0;
let minYCoordinate = 0;
let maxXCoordinate = 0;
let trackForRuler;
let bed;
// main function to call from outside
// which starts the process of creating a tube map visualization
export function create(params) {
// mandatory parameters: svgID (really a selector, but must be an ID selector), nodes, tracks
// optional parameters: bed, clickableNodes, reads, showLegend
svgID = params.svgID;
svg = d3.select(params.svgID);
inputNodes = deepCopy(params.nodes); // deep copy
// Nodes are referenced in inputs by internal `name` attribute and not by index.
// Internally in e.g. a path's indexSequence we need to reference nodes by *signed* index.
// Which means that index 0 can never be allowed to be used, so we need to make sure it is not there.
// So budge everything down
inputNodes.unshift(undefined);
// And then leave a hole in the array at 0 which we won't iterate over.
delete inputNodes[0];
inputTracks = deepCopy(params.tracks); // deep copy
inputReads = params.reads || null;
inputRegion = params.region;
bed = params.bed || null;
config.clickableNodesFlag = params.clickableNodes || false;
config.hideLegendFlag = params.hideLegend || false;
const tr = createTubeMap();
if (!config.hideLegendFlag) drawLegend(tr);
}
// Deep copy something, but preserve array holes at the top level
function deepCopy(val) {
let newVal = JSON.parse(JSON.stringify(val));
for (let prop of Object.keys(newVal)) {
if (!Object.hasOwn(val, prop)) {
// This should be a hole, so punch it
delete newVal[prop];
}
}
return newVal;
}
// Return true if the given name names a reverse strand node, and false otherwise.
function isReverse(nodeName) {
const s = String(nodeName);
return s.length >= 1 && s.charAt(0) === "-";
}
// Get the forward version of a node name, which may be either forward or backward (negative)
function forward(nodeName) {
if (isReverse(nodeName)) {
// It looks like a negative value.
// Make sure it's a string and cut off the -.
return String(nodeName).substr(1);
} else {
// It's forward.
return nodeName;
}
}
// Get the reverse version of a node name, which may be either forward or backward (negative)
function reverse(nodeName) {
if (isReverse(nodeName)) {
return nodeName;
} else {
return `-${nodeName}`;
}
}
// Get the opposite orientation node name for the given node.
function flip(nodeName) {
if (isReverse(nodeName)) {
return forward(nodeName);
} else {
return reverse(nodeName);
}
}
// moves a specific track to the top
function moveTrackToFirstPosition(index) {
inputTracks.unshift(inputTracks[index]); // add element to beginning
inputTracks.splice(index + 1, 1); // remove 1 element from the middle
straightenTrack(0);
}
// straighten track given by index by inverting inverted nodes
// only keep them inverted if this single track runs thrugh them in both directions
// TODO: This operates on `inputNodes`, etc. when it probably ought to operate on `nodes`
function straightenTrack(index) {
let i;
let j;
const nodesToInvert = [];
let currentSequence;
let nodeName;
// find out which nodes should be inverted
currentSequence = inputTracks[index].sequence;
for (i = 0; i < currentSequence.length; i += 1) {
if (isReverse(currentSequence[i])) {
nodeName = forward(currentSequence[i]);
if (
currentSequence.indexOf(nodeName) === -1 ||
currentSequence.indexOf(nodeName) > i
) {
// only if this inverted node is no repeat
nodesToInvert.push(nodeName);
}
}
}
// invert nodes in the tracks' sequence
for (i = 0; i < inputTracks.length; i += 1) {
currentSequence = inputTracks[i].sequence;
for (j = 0; j < currentSequence.length; j += 1) {
if (!isReverse(currentSequence[j])) {
if (nodesToInvert.indexOf(currentSequence[j]) !== -1) {
currentSequence[j] = reverse(currentSequence[j]);
}
} else if (nodesToInvert.indexOf(forward(currentSequence[j])) !== -1) {
currentSequence[j] = forward(currentSequence[j]);
}
}
}
// invert the sequence within the nodes
inputNodes.forEach((node) => {
if (nodesToInvert.indexOf(node.name) !== -1) {
node.seq = node.seq.split("").reverse().join("");
}
});
}
export function changeTrackVisibility(trackID) {
let i = 0;
while (i < inputTracks.length && inputTracks[i].id !== trackID) i += 1;
if (i < inputTracks.length) {
if (inputTracks[i].hasOwnProperty("hidden")) {
inputTracks[i].hidden = !inputTracks[i].hidden;
} else {
inputTracks[i].hidden = true;
}
}
createTubeMap();
}
// to select/deselect all
export function changeAllTracksVisibility(value) {
let i = 0;
while (i < inputTracks.length) {
inputTracks[i].hidden = !value;
var checkbox = document.getElementById(`showTrack${i}`);
checkbox.checked = value;
i += 1;
}
createTubeMap();
}
export function changeExonVisibility() {
config.showExonsFlag = !config.showExonsFlag;
createTubeMap();
}
// sets the flag for whether redundant nodes should be automatically removed or not
export function setMergeNodesFlag(value) {
if (config.mergeNodesFlag !== value) {
config.mergeNodesFlag = value;
svg = d3.select(svgID);
createTubeMap();
}
}
// sets the flag for whether nodes should be fully transparent or not
export function setTransparentNodesFlag(value) {
if (config.transparentNodesFlag !== value) {
config.transparentNodesFlag = value;
svg = d3.select(svgID);
createTubeMap();
}
}
// sets the flag for whether read soft clips should be displayed or not
export function setSoftClipsFlag(value) {
if (config.showSoftClips !== value) {
config.showSoftClips = value;
svg = d3.select(svgID);
createTubeMap();
}
}
// sets the flag for whether reads should be displayed or not
export function setShowReadsFlag(value) {
if (config.showReads !== value) {
config.showReads = value;
svg = d3.select(svgID);
createTubeMap();
}
}
export function setColorSet(fileID, newColor) {
const currColor = config.colorSchemes[fileID];
// update if any coloring parameter is different
if (!currColor || !deepEqual(currColor, newColor)) {
config.colorSchemes[fileID] = newColor;
const tr = createTubeMap();
if (!config.hideLegendFlag && tracks) drawLegend(tr);
}
}
// sets which option should be used for calculating the node width from its sequence length
export function setNodeWidthOption(value) {
if (value === 0 || value === 1 || value === 2) {
if (config.nodeWidthOption !== value) {
config.nodeWidthOption = value;
if (svg !== undefined) {
svg = d3.select(svgID);
createTubeMap();
}
}
}
}
export function setColoredNodes(value) {
config.coloredNodes = value;
}
// sets callback function that would generate React popup of track information. The callback would
// accept an array argument of track attribute pairs containing attribute name as a string and attribute value
// as a string or number, to be displayed.
export function setInfoCallback(newCallback) {
config.showInfoCallback = newCallback;
}
export function setMappingQualityCutoff(value) {
if (config.mappingQualityCutoff !== value) {
config.mappingQualityCutoff = value;
if (svg !== undefined) {
svg = d3.select(svgID);
createTubeMap();
}
}
}
// main
function createTubeMap() {
console.log("Recreating tube map in", svgID);
trackRectangles = [];
trackCurves = [];
trackCorners = [];
trackVerticalRectangles = [];
trackRectanglesStep3 = [];
assignments = [];
extraLeft = [];
extraRight = [];
maxYCoordinate = 0;
minYCoordinate = 0;
maxXCoordinate = 0;
trackForRuler = undefined;
svg = d3.select(svgID);
svg.selectAll("*").remove(); // clear svg for (re-)drawing
// early exit is necessary when visualization options such as colors are
// changed before any graph has been rendered
if (inputNodes.length === 0 || inputTracks.length === 0) return;
straightenTrack(0);
nodes = deepCopy(inputNodes); // deep copy (can add stuff to copy and leave original unchanged)
tracks = deepCopy(inputTracks);
reads = deepCopy(inputReads);
reads = filterReads(reads);
for (let i = tracks.length - 1; i >= 0; i -= 1) {
if (!tracks[i].hasOwnProperty("type")) {
// TODO: maybe remove "haplo"-property?
tracks[i].type = "haplo";
}
if (tracks[i].hasOwnProperty("hidden")) {
if (tracks[i].hidden === true) {
tracks.splice(i, 1);
}
}
if (tracks[i] && tracks[i].hasOwnProperty("indexOfFirstBase")) {
trackForRuler = tracks[i].name;
}
}
if (tracks.length === 0) return;
nodeMap = generateNodeMap(nodes);
generateTrackIndexSequences(tracks);
if (reads && config.showReads) generateTrackIndexSequences(reads);
generateNodeWidth();
if (config.mergeNodesFlag) {
generateNodeSuccessors(); // requires indexSequence
generateNodeOrder(); // requires successors
if (reads && config.showReads) reverseReversedReads();
mergeNodes();
nodeMap = generateNodeMap(nodes);
generateNodeWidth();
generateTrackIndexSequences(tracks);
if (reads && config.showReads) generateTrackIndexSequences(reads);
}
numberOfNodes = nodes.length;
numberOfTracks = tracks.length;
generateNodeSuccessors();
generateNodeDegree();
if (DEBUG) console.log(`${numberOfNodes} nodes.`);
generateNodeOrder();
maxOrder = getMaxOrder();
// can cause problems when there is a reversed single track node
// OTOH, can solve problems with complex inversion patterns
switchNodeOrientation();
generateNodeOrder(nodes, tracks);
maxOrder = getMaxOrder();
calculateTrackWidth(tracks);
generateLaneAssignment();
if (config.showExonsFlag === true && bed !== null) addTrackFeatures();
generateNodeXCoords();
if (reads && config.showReads) {
generateReadOnlyNodeAttributes();
reverseReversedReads();
generateTrackIndexSequences(reads);
placeReads();
tracks = tracks.concat(reads);
// we do not have any reads to display
} else {
nodes.forEach((node) => {
node.incomingReads = [];
node.outgoingReads = [];
node.internalReads = [];
});
}
generateSVGShapesFromPath(nodes, tracks);
if (DEBUG) {
console.log("Tracks:");
console.log(tracks);
console.log("Nodes:");
console.log(nodes);
console.log("Lane assignment:");
console.log(assignments);
}
getImageDimensions();
alignSVG(nodes, tracks);
defineSVGPatterns();
// all drawn tracks are grouped
let trackGroup = svg.append("g").attr("class", "track");
drawTrackRectangles(trackRectangles, "haplo", trackGroup);
drawTrackCurves("haplo", trackGroup);
drawReversalsByColor(
trackCorners,
trackVerticalRectangles,
"haplo",
trackGroup
);
drawTrackRectangles(trackRectanglesStep3, "haplo", trackGroup);
drawTrackRectangles(trackRectangles, "read", trackGroup);
drawTrackCurves("read", trackGroup);
// draw only those nodes which have coords assigned to them
const dNodes = removeUnusedNodes(nodes);
drawReversalsByColor(
trackCorners,
trackVerticalRectangles,
"read",
trackGroup
);
// all drawn nodes are grouped
let nodeGroup = svg.append("g").attr("class", "node");
drawNodes(dNodes, nodeGroup);
if (config.nodeWidthOption === 0) drawLabels(dNodes);
if (trackForRuler !== undefined) drawRuler();
if (config.nodeWidthOption === 0) drawMismatches(); // TODO: call this before drawLabels and fix d3 data/append/enter stuff
if (DEBUG) {
console.log(`number of tracks: ${numberOfTracks}`);
console.log(`number of nodes: ${numberOfNodes}`);
}
return tracks;
}
// generates attributes (node.y, node.contentHeight) for nodes without tracks, only reads
function generateReadOnlyNodeAttributes() {
nodesPerOrder = [];
for (let i = 0; i <= maxOrder; i += 1) {
nodesPerOrder[i] = [];
}
const orderY = new Map();
nodes.forEach((node) => {
if (node.hasOwnProperty("order") && node.hasOwnProperty("y")) {
setMapToMax(orderY, node.order, node.y + node.contentHeight);
}
});
// for order values where there is no node with haplotypes, orderY is calculated via tracks
tracks.forEach((track) => {
if (track.type === "haplo") {
track.path.forEach((step) => {
setMapToMax(orderY, step.order, step.y + track.width);
});
}
});
nodes.forEach((node, i) => {
if (node.hasOwnProperty("order") && !node.hasOwnProperty("y")) {
node.y = orderY.get(node.order) + 25;
node.contentHeight = 0;
nodesPerOrder[node.order].push(i);
}
});
}
function setMapToMax(map, key, value) {
if (map.has(key)) {
map.set(key, Math.max(map.get(key), value));
} else {
map.set(key, value);
}
}
const READ_WIDTH = 7;
// add info about reads to nodes (incoming, outgoing and internal reads)
function assignReadsToNodes() {
nodes.forEach((node) => {
node.incomingReads = [];
node.outgoingReads = [];
node.internalReads = [];
});
reads.forEach((read, idx) => {
read.width = READ_WIDTH;
if (read.path.length === 1) {
nodes[read.path[0].node].internalReads.push(idx);
} else {
read.path.forEach((element, pathIdx) => {
if (pathIdx === 0) {
nodes[read.path[0].node].outgoingReads.push([idx, pathIdx]);
} else if (read.path[pathIdx].node !== null) {
nodes[read.path[pathIdx].node].incomingReads.push([idx, pathIdx]);
}
});
}
});
}
function removeNonPathNodesFromReads() {
reads.forEach((read) => {
for (let i = read.sequence.length - 1; i >= 0; i -= 1) {
let nodeName = forward(read.sequence[i]);
if (!nodeMap.has(nodeName) || nodes[nodeMap.get(nodeName)].degree === 0) {
read.sequence.splice(i, 1);
}
}
});
}
// calculate paths (incl. correct y coordinate) for all reads
function placeReads() {
generateBasicPathsForReads();
assignReadsToNodes();
// sort nodes by order, then by y-coordinate
const sortedNodes = nodes.slice();
sortedNodes.sort(compareNodesByOrder);
// Organize read IDs by source track
let readsBySource = {};
for (let i = 0; i < reads.length; i++) {
let source = reads[i].sourceTrackID;
if (readsBySource[source] === undefined) {
// First read from this source
readsBySource[source] = [i];
} else {
// Put it with the others from this source
readsBySource[source].push(i);
}
}
let allSources = Object.keys(readsBySource);
allSources.sort((a, b) => Number(a) - Number(b));
console.log("All sources: ", allSources);
// Space out read tracks if multiple exist
let topMargin = allSources.length > 1 ? READ_WIDTH : 0;
for (let source of allSources) {
// Go through all source tracks in order
sortedNodes.forEach((node) => {
// And for each node, place these reads in it.
// Use a margin to separate multiple read tracks if we have them.
placeReadSet(readsBySource[source], node, topMargin);
});
}
// place read segments which are without node
const bottomY = calculateBottomY();
const elementsWithoutNode = [];
reads.forEach((read, idx) => {
read.path.forEach((element, pathIdx) => {
if (!element.hasOwnProperty("y")) {
// previous y value from pathIdx - 1 might not exist yet if that segment is also without node
// use previous y value from last segment with node instead
let previousValidY = null;
let lastIndex = pathIdx - 1;
while (previousValidY === null && lastIndex >= 0) {
previousValidY = reads[idx].path[lastIndex].y;
lastIndex = lastIndex - 1;
}
elementsWithoutNode.push({
readIndex: idx,
pathIndex: pathIdx,
previousY: previousValidY,
});
}
});
});
elementsWithoutNode.sort(compareNoNodeReadsByPreviousY);
elementsWithoutNode.forEach((element) => {
const segment = reads[element.readIndex].path[element.pathIndex];
segment.y = bottomY[segment.order];
bottomY[segment.order] += reads[element.readIndex].width;
});
if (DEBUG) {
console.log("Reads:");
console.log(reads);
}
}
// Place a particular collection of reads, identified by a list of read
// numbers, into the given node at the right Y coordinates. All reads in all
// nodes above it, and no reads in any nodes below it, are already placed.
// Makes the given node bigger if needed and moves other nodes down if needed.
// If topMargin is set, applies that amount of spacing down from whatever is above the reads.
function placeReadSet(readIDs, node, topMargin) {
// Parse arguments
if (!topMargin) {
topMargin = 0;
}
// Turn the read IDs into a set
let toPlace = new Set(readIDs);
// Get arrays of the read entry/exit/internal-ness records we want to work on
let incomingReads = node.incomingReads.filter(([readID, pathIndex]) =>
toPlace.has(readID)
);
let outgoingReads = node.outgoingReads.filter(([readID, pathIndex]) =>
toPlace.has(readID)
);
let internalReads = node.internalReads.filter((readID) =>
toPlace.has(readID)
);
// Only actually use the top margin if we have any reads on the node.
if (
incomingReads.length === 0 &&
outgoingReads.length === 0 &&
internalReads.length === 0
) {
topMargin = 0;
}
// Determine where we start vertically in the node.
// TODO: Why do we have to double this to keep reads out of adjacent lanes???
let startY = node.y + node.contentHeight + topMargin * 2;
// sort incoming reads
incomingReads.sort(compareReadIncomingSegmentsByComingFrom);
// place incoming reads
let currentY = startY;
const occupiedUntil = new Map();
incomingReads.forEach((readElement) => {
reads[readElement[0]].path[readElement[1]].y = currentY;
setOccupiedUntil(
occupiedUntil,
reads[readElement[0]],
readElement[1],
currentY,
node
);
currentY += READ_WIDTH;
});
let maxY = currentY;
// sort outgoing reads
outgoingReads.sort(compareReadOutgoingSegmentsByGoingTo);
// place outgoing reads
const occupiedFrom = new Map();
currentY = startY;
outgoingReads.forEach((readElement) => {
// place in next lane
reads[readElement[0]].path[readElement[1]].y = currentY;
occupiedFrom.set(currentY, reads[readElement[0]].firstNodeOffset);
// if no conflicts
if (
!occupiedUntil.has(currentY) ||
occupiedUntil.get(currentY) + 1 < reads[readElement[0]].firstNodeOffset
) {
currentY += READ_WIDTH;
maxY = Math.max(maxY, currentY);
} else {
// otherwise push down incoming reads to make place for outgoing Read
occupiedUntil.set(currentY, 0);
incomingReads.forEach((incReadElementIndices) => {
const incRead = reads[incReadElementIndices[0]];
const incReadPathElement = incRead.path[incReadElementIndices[1]];
if (incReadPathElement.y >= currentY) {
incReadPathElement.y += READ_WIDTH;
setOccupiedUntil(
occupiedUntil,
incRead,
incReadElementIndices[1],
incReadPathElement.y,
node
);
}
});
currentY += READ_WIDTH;
maxY += READ_WIDTH;
}
});
// sort internal reads
internalReads.sort(compareInternalReads);
// place internal reads
internalReads.forEach((readIdx) => {
const currentRead = reads[readIdx];
currentY = startY;
while (
currentRead.firstNodeOffset < occupiedUntil.get(currentY) + 2 ||
currentRead.finalNodeCoverLength > occupiedFrom.get(currentY) - 3
) {
currentY += READ_WIDTH;
}
currentRead.path[0].y = currentY;
occupiedUntil.set(currentY, currentRead.finalNodeCoverLength);
maxY = Math.max(maxY, currentY);
});
// adjust node height and move other nodes vertically down
const heightIncrease = maxY - node.y - node.contentHeight;
node.contentHeight += heightIncrease;
adjustVertically3(node, heightIncrease);
}
// keeps track of where reads end within nodes
function setOccupiedUntil(map, read, pathIndex, y, node) {
if (pathIndex === read.path.length - 1) {
// last node of current read
map.set(y, read.finalNodeCoverLength);
} else {
// read covers the whole node
map.set(y, node.sequenceLength);
}
}
// compare read segments which are outside of nodes
// by the y-coord of where they are coming from
function compareNoNodeReadsByPreviousY(a, b) {
const segmentA = reads[a.readIndex].path[a.pathIndex];
const segmentB = reads[b.readIndex].path[b.pathIndex];
if (segmentA.order === segmentB.order) {
return a.previousY - b.previousY;
}
return segmentA.order - segmentB.order;
}
// compare read segments by where they are going to
function compareReadOutgoingSegmentsByGoingTo(a, b) {
let pathIndexA = a[1];
let pathIndexB = b[1];
// let readA = reads[a[0]]
// let nodeIndexA = readA.path[pathIndexA].node;
let nodeA = nodes[reads[a[0]].path[pathIndexA].node];
let nodeB = nodes[reads[b[0]].path[pathIndexB].node];
while (nodeA !== null && nodeB !== null && nodeA === nodeB) {
if (pathIndexA < reads[a[0]].path.length - 1) {
pathIndexA += 1;
while (reads[a[0]].path[pathIndexA].node === null) pathIndexA += 1; // skip null nodes in path
nodeA = nodes[reads[a[0]].path[pathIndexA].node];
} else {
nodeA = null;
}
if (pathIndexB < reads[b[0]].path.length - 1) {
pathIndexB += 1;
while (reads[b[0]].path[pathIndexB].node === null) pathIndexB += 1; // skip null nodes in path
nodeB = nodes[reads[b[0]].path[pathIndexB].node];
} else {
nodeB = null;
}
}
if (nodeA !== null) {
if (nodeB !== null) return compareNodesByOrder(nodeA, nodeB);
return 1; // nodeB is null, nodeA not null
}
if (nodeB !== null) return -1; // nodeB not null, nodeA null
// both nodes are null -> both end in the same node
const beginDiff = reads[a[0]].firstNodeOffset - reads[b[0]].firstNodeOffset;
if (beginDiff !== 0) return beginDiff;
// break tie: both reads cover the same nodes and begin at the same position -> compare by endPosition
return reads[a[0]].finalNodeCoverLength - reads[b[0]].finalNodeCoverLength;
}
// compare read segments by (y-coord of) where they are coming from
function compareReadIncomingSegmentsByComingFrom(a, b) {
// these boundary conditions avoid errors for incoming reads
// from inverted nodes (u-turns)
if (a[1] === 0) return -1;
if (b[1] === 0) return 1;
const pathA = reads[a[0]].path[a[1] - 1];
const pathB = reads[b[0]].path[b[1] - 1];
if (pathA.hasOwnProperty("y")) {
if (pathB.hasOwnProperty("y")) {
return pathA.y - pathB.y; // a and b have y-property
}
return -1; // only a has y-property
}
if (pathB.hasOwnProperty("y")) {
return 1; // only b has y-property
}
return compareReadIncomingSegmentsByComingFrom(
[a[0], a[1] - 1],
[b[0], b[1] - 1]
); // neither has y-property
}
// compare 2 reads which are completely within a single node
function compareInternalReads(idxA, idxB) {
const a = reads[idxA];
const b = reads[idxB];
// compare by first base within first node
if (a.firstNodeOffset < b.firstNodeOffset) return -1;
else if (a.firstNodeOffset > b.firstNodeOffset) return 1;
// compare by last base within last node
if (a.finalNodeCoverLength < b.finalNodeCoverLength) return -1;
else if (a.finalNodeCoverLength > b.finalNodeCoverLength) return 1;
return 0;
}
// determine biggest y-coordinate for each order-value
function calculateBottomY() {
const bottomY = [];
for (let i = 0; i <= maxOrder; i += 1) {
bottomY.push(0);
}
nodes.forEach((node) => {
bottomY[node.order] = Math.max(
bottomY[node.order],
node.y + node.contentHeight + 20
);
});
tracks.forEach((track) => {
track.path.forEach((element) => {
bottomY[element.order] = Math.max(
bottomY[element.order],
element.y + track.width
);
});
});
return bottomY;
}
// generate path-info for each read
// containing order, node and orientation, but no concrete coordinates
// TODO: Duplicates a lot of the same work as generateLaneAssignment() does for non-read tracks.
function generateBasicPathsForReads() {
let currentNodeIndex;
let currentNodeIsForward;
let currentNode;
let previousNode;
let previousNodeIsForward;
const isPositive = (n) => ((n = +n) || 1 / n) >= 0;
reads.forEach((read) => {
// add info for start of track
currentNodeIndex = Math.abs(read.indexSequence[0]);
currentNodeIsForward = isPositive(read.indexSequence[0]);
currentNode = nodes[currentNodeIndex];
read.path = [];
read.path.push({
order: currentNode.order,
isForward: currentNodeIsForward,
node: currentNodeIndex,
});
for (let i = 1; i < read.sequence.length; i += 1) {
previousNode = currentNode;
previousNodeIsForward = currentNodeIsForward;
currentNodeIndex = Math.abs(read.indexSequence[i]);
currentNodeIsForward = isPositive(read.indexSequence[i]);
currentNode = nodes[currentNodeIndex];
if (currentNode.order > previousNode.order) {
if (!previousNodeIsForward) {
// backward to forward at previous node
read.path.push({
order: previousNode.order,
isForward: true,
node: null,
});
}
for (let j = previousNode.order + 1; j < currentNode.order; j += 1) {
// forward without nodes
read.path.push({ order: j, isForward: true, node: null });
}
if (!currentNodeIsForward) {
// forward to backward at current node
read.path.push({
order: currentNode.order,
isForward: true,
node: null,
});