-
Notifications
You must be signed in to change notification settings - Fork 2
/
circularFigure.ts
1433 lines (1321 loc) · 44.1 KB
/
circularFigure.ts
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
import * as fs from "fs";
import * as readline from "readline";
import {UniquelyAddressable} from "../uniquelyAddressable";
import {Plasmid} from "../ngplasmid/lib/plasmid";
import {TrackMarker} from "../ngplasmid/lib/trackMarker";
import * as html from "./../ngplasmid/lib/html";
import * as pbDirectives from "./../ngplasmid/lib/pb/node";
import {plasmidToPB} from "./../ngplasmid/lib/directiveToPB";
import {getReadableAndWritable} from "./../getAppPath";
import * as fastaContigLoader from "./../fastaContigLoader";
import * as plasmidTrack from "./circularGenome/plasmidTrack";
import * as trackLabel from "./circularGenome/trackLabel";
import * as trackMarker from "./circularGenome/trackMarker";
import * as markerLabel from "./circularGenome/markerLabel";
import * as trackScale from "./circularGenome/trackScale";
import * as plasmid from "./circularGenome/plasmid";
import {AlignData,getSNPsJSON} from "./../alignData";
import {VCF2JSONRow} from "./../varScanMPileup2SNPVCF2JSON";
import {parseCSS} from "./../parseCSS";
const mkdirp = require("mkdirp");
const uuidv4 : () => string = require("uuid/v4");
const jsonFile = require("jsonfile");
/**
* Represents a single contig in a circular figure
*
* @export
* @class Contig
* @extends {fastaContigLoader.Contig}
*/
export class Contig extends fastaContigLoader.Contig
{
public color? : string = "";
public opacity? : number = 1.0;
public fontSize? : string = "";
public fontWeight? : string = "";
public fontFill? : string = "";
public allowPositionChange? : boolean = false;
public start? : number;
public end? : number;
public vAdjust? : number;
}
/**
* Hydrates contig with the appropriate properties for display
*
* @export
* @param {Contig} contig
* @param {boolean} [allowPositionChange=false]
*/
export function initContigForDisplay(contig : Contig,allowPositionChange = false) : void
{
contig.color = getRandColor(1);
contig.opacity = 1.0;
contig.fontFill = "rgb(0,0,0)";
contig.allowPositionChange = allowPositionChange;
contig.vAdjust = 0;
}
/**
* Returns a random RGB value of the form rgb(r,g,b)
*
* @param {number} brightness
* @returns
*/
function getRandColor(brightness : number)
{
//adapted from answer by letronje and edited by Peter Mortensen
//http://stackoverflow.com/questions/1484506/random-color-generator-in-javascript
// Six levels of brightness from 0 to 5, 0 being the darkest
let rgb = [Math.random() * 256, Math.random() * 256, Math.random() * 256];
let mix = [brightness*51, brightness*51, brightness*51]; //51 => 255/5
let mixedrgb = [rgb[0] + mix[0], rgb[1] + mix[1], rgb[2] + mix[2]].map(function(x)
{
return Math.round(x/2.0);
});
return "rgb(" + mixedrgb.join(",") + ")";
}
/**
* Specifies options options for a figure's interval track
*
* @export
* @class CircularFigureBPTrackOptions
*/
export class CircularFigureBPTrackOptions
{
public interval : number;
public vAdjust : number;
public showLabels : 0 | 1;
public direction : "in" | "out";
constructor()
{
this.interval = 500;
this.vAdjust = 5;
this.showLabels = 0;
this.direction = "out";
}
}
/**
* Contains a record to retrieve/manipulate a data track which has been rendered
*
* @export
* @class RenderedTrackRecord
*/
export class RenderedTrackRecord implements UniquelyAddressable
{
public uuid : string;
public uuidAlign : string;
public uuidContig : string;
public uuidFigure : string;
public checked : boolean;
public colour : string;
public constructor(
uuidAlign : string,
uuidContig : string,
uuidFigure : string,
colour : string)
{
this.uuid = uuidv4();
this.uuidAlign = uuidAlign;
this.uuidContig = uuidContig;
this.uuidFigure = uuidFigure;
this.checked = false;
this.colour = colour;
}
}
/**
* Contains a record to retrieve/manipulate a coverage track which has been built
*
* @export
* @class RenderedCoverageTrackRecord
* @extends {RenderedTrackRecord}
*/
export class RenderedCoverageTrackRecord extends RenderedTrackRecord
{
public scaleFactor : number;
public log10Scaled : boolean;
public constructor(
uuidAlign : string,
uuidContig : string,
uuidFigure : string,
colour : string,
scaleFactor : number,
log10Scaled : boolean)
{
super(uuidAlign,uuidContig,uuidFigure,colour);
this.scaleFactor = scaleFactor;
this.log10Scaled = log10Scaled;
}
}
/**
* Contains a record to retrieve/manipulate a SNP track which has been built
*
* @export
* @class RenderedSNPTrackRecord
* @extends {RenderedTrackRecord}
*/
export class RenderedSNPTrackRecord extends RenderedTrackRecord
{
public constructor(
uuidAlign : string,
uuidContig : string,
uuidFigure : string,
colour : string)
{
super(uuidAlign,uuidContig,uuidFigure,colour);
}
}
/**
* Properties used by sequence selector to display selection arms
*
* @export
* @class SeqSelectionDisplayArm
*/
export class SeqSelectionDisplayArm
{
public armWidth : number;
public armTrackStyle : string;
public armRadius : number;
public armStart : number;
public armWadjust : number;
public armMarkerClick : string;
public armLineClass : string;
public armLineStyle : string;
public armShowLine : 0 | 1;
public armVadjust : number;
public armLabelClick : string;
public constructor(side : "left" | "right",radius : number,armStart : number)
{
this.armWidth = 20;
this.armTrackStyle = "fill-opacity:0.0;";
this.armRadius = radius;
this.armStart = armStart;
this.armWadjust = 12;
this.armMarkerClick = `seqSelectionArmOnClick($event,$handler,'${side}')`;
this.armLineClass = "seqSelectionArm";
this.armLineStyle = "stroke:rgb(0,0,0);stroke-dasharray:5,10;stroke-width:2px;animation: moveSeqSelectionArm 3s infinite;";
this.armShowLine = 1;
this.armVadjust = 1200;
this.armLabelClick = this.armMarkerClick;
}
}
/**
* Properties used by sequence selector to display selection arrow
*
* @export
* @class SeqSelectionDisplayArrow
*/
export class SeqSelectionDisplayArrow
{
public arrowTrackStyle : string;
public arrowTrackRadius : number;
public arrowStart : number;
public arrowEnd : number;
public arrowMarkerStyle : string;
public arrowEndLength : number;
public arrowEndWidth : number;
public arrowType : string;
public arrowClass : string;
public arrowText : string | undefined;
public constructor(start : number,end : number,radius : number)
{
this.arrowTrackStyle = "fill-opacity:0.0;";
this.arrowTrackRadius = radius;
this.arrowStart = start;
this.arrowEnd = end;
this.arrowMarkerStyle = "fill:rgba(0,0,0)";
this.arrowEndLength = 10;
this.arrowEndWidth = 5;
this.arrowType = "path";
this.arrowClass = "";
this.updateText();
}
public updateText()
{
this.arrowText = `${this.arrowStart}-${this.arrowEnd}`;
}
}
export interface MapScope
{
genome : CircularFigure | undefined;
seqSelectionLeftArm : SeqSelectionDisplayArm | undefined;
seqSelectionRightArm : SeqSelectionDisplayArm | undefined;
seqSelectionArrow : SeqSelectionDisplayArrow | undefined;
}
export function makeMapScope(cf : CircularFigure, seqSelectOptions? : {
start : number,
end : number
}) : MapScope
{
return <MapScope>{
genome : cf,
seqSelectionLeftArm : new SeqSelectionDisplayArm(
"left",
cf.radius,
seqSelectOptions ? seqSelectOptions.start : 1
),
seqSelectionRightArm : new SeqSelectionDisplayArm(
"right",
cf.radius,
seqSelectOptions ? seqSelectOptions.end : 100
),
seqSelectionArrow : new SeqSelectionDisplayArrow(
seqSelectOptions ? seqSelectOptions.start : 1,
seqSelectOptions ? seqSelectOptions.end : 100,
cf.radius
)
};
}
export class TrackMap extends Plasmid
{
public $scope : MapScope | undefined;
public constructor()
{
super();
}
}
export class CoverageTrackMap extends TrackMap
{
public constructor()
{
super();
}
}
export class SNPTrackMap extends TrackMap
{
public constructor()
{
super();
}
}
/**
* Contains all structures needed to manipulate a circular figure
*
* @export
* @class CircularFigure
*/
export class CircularFigure implements UniquelyAddressable
{
public uuid : string;
public uuidFasta : string;
public name : string;
public contigs : Array<Contig>;
public customContigs : Array<Contig>;
public radius : number;
public height : number;
public width : number;
public zoomFactor : number;
public isInteractive : boolean;
public showContigNames : boolean;
public circularFigureBPTrackOptions : CircularFigureBPTrackOptions;
public renderedCoverageTracks : Array<RenderedCoverageTrackRecord>;
public renderedSNPTracks : Array<RenderedSNPTrackRecord>;
constructor(name : string,uuid : string,contigs : Array<Contig>)
{
this.uuidFasta = uuid;
this.uuid = uuidv4();
this.name = name;
this.contigs = contigs;
this.radius = 120;
this.height = this.radius*10;
this.width = this.radius*10;
this.zoomFactor = 1;
this.circularFigureBPTrackOptions = new CircularFigureBPTrackOptions();
this.renderedCoverageTracks = new Array<RenderedCoverageTrackRecord>();
this.renderedSNPTracks = new Array<RenderedSNPTrackRecord>();
for(let i = 0; i != this.contigs.length; ++i)
{
initContigForDisplay(this.contigs[i]);
}
//Add filler contig at the end of the reference so the figure displays correctly
if(this.contigs.length == 1)
{
this.contigs.push(new Contig());
this.contigs[1].color = this.contigs[0].color;
this.contigs[1].uuid = "filler";
this.contigs[1].bp = 1;
this.contigs[1].loaded = true;
}
this.customContigs = new Array<Contig>();
this.isInteractive = true;
this.showContigNames = true;
let totalBP = 0;
for(let i = 0; i != this.contigs.length; ++i)
{
totalBP += this.contigs[i].bp;
}
if(this.contigs.length >= 50 || totalBP >= 1000000)
{
this.isInteractive = false;
this.showContigNames = false;
}
cacheBaseFigureTemplate(this);
}
}
/**
* Minimum amount of props/methods expected by figures at runtime
*
* @export
* @abstract
* @class FigureCanvas
*/
export abstract class FigureCanvas implements MapScope
{
public abstract genome : CircularFigure | undefined;
public abstract seqSelectionLeftArm : SeqSelectionDisplayArm | undefined;
public abstract seqSelectionRightArm : SeqSelectionDisplayArm | undefined;
public abstract seqSelectionArrow : SeqSelectionDisplayArrow | undefined;
public abstract showSeqSelector : boolean;
public abstract scope : FigureCanvas;
public abstract markerOnClick($event : any,$marker : any,uuid : string) : void;
public abstract figureNameOnClick() : void;
public abstract updateScope(scope? : FigureCanvas) : void;
public abstract loadFigure(figure : CircularFigure) : void;
}
/**
* Returns the templates for contig
*
* @export
* @param {Contig} contig
* @param {number} [start=-1]
* @param {number} [end=-1]
* @returns {string}
*/
export function buildContigTemplate(figure : CircularFigure,contig : Contig,start : number = -1,end : number = -1) : string
{
if(start == -1)
start = contig.start!;
if(end == -1)
end = contig.end!;
let res = "";
res += `
${trackMarker.add(
{
start : start.toString(),
end : end.toString(),
vAdjust : contig.vAdjust,
markerStyle : `fill:${contig.color};opacity:${contig.opacity};`,
uuid : contig.uuid,
onClick : "markerOnClick",
isInteractive : figure.isInteractive
})}
${markerLabel.add(
{
type : "path",
text : figure.showContigNames ? contig.alias : "",
labelStyle : `fill:${contig.fontFill};opacity:${contig.opacity};`
})}
${markerLabel.end()}
${trackMarker.end()}
`;
return res;
}
/**
* Returns the templates for the base figure of figure
*
* @export
* @param {CircularFigure} figure
* @returns {string}
*/
export function buildBaseFigureTemplate(figure : CircularFigure) : string
{
return `
${plasmidTrack.add(
{
trackStyle : "fill:#f0f0f0;stroke:#ccc",
radius : "{{genome.radius}}"
})}
${trackLabel.add(
{
text : figure.name,
labelStyle : "font-size:20px;font-weight:400",
onClick : "figureNameOnClick",
isInteractive : figure.isInteractive
})}
${trackLabel.end()}
${(()=>
{
let res = "";
let lastLocation = 0;
for(let i = 0; i != figure.contigs.length; ++i)
{
res += buildContigTemplate(figure,figure.contigs[i],lastLocation,lastLocation+figure.contigs[i].bp);
lastLocation = lastLocation + figure.contigs[i].bp;
}
for(let i = 0; i != figure.customContigs.length; ++i)
{
res += buildContigTemplate(figure,figure.customContigs[i],figure.customContigs[i].start,figure.customContigs[i].end);
}
return res;
})()}
${trackScale.add(
{
interval : "{{genome.circularFigureBPTrackOptions.interval}}",
vAdjust : "{{genome.circularFigureBPTrackOptions.vAdjust}}",
showLabels : "{{genome.circularFigureBPTrackOptions.showLabels}}",
direction : "{{genome.circularFigureBPTrackOptions.direction}}"
}
)}
${trackScale.end()}
${plasmidTrack.end()}
`;
}
export function buildSequenceSelectorTemplate(figure : CircularFigure,
seqSelectionLeftArm : SeqSelectionDisplayArm,
seqSelectionRightArm : SeqSelectionDisplayArm,
seqSelectionArrow : SeqSelectionDisplayArrow
) : string
{
let template = `
<plasmidtrack width="{{seqSelectionLeftArm.armWidth}}" trackstyle="{{seqSelectionLeftArm.armTrackStyle}}" radius="{{seqSelectionLeftArm.armRadius}}">
<trackmarker start="{{seqSelectionLeftArm.armStart}}" wadjust="{{seqSelectionLeftArm.armWadjust}}" markerclick="${seqSelectionLeftArm.armMarkerClick}">
<markerlabel lineclass="{{seqSelectionLeftArm.armLineClass}}" linestyle="${seqSelectionLeftArm.armLineStyle}" showline="{{seqSelectionLeftArm.armShowLine}}" text="" vadjust="{{seqSelectionLeftArm.armVadjust}}" labelclick="${seqSelectionLeftArm .armLabelClick}"></markerlabel>
</trackmarker>
</plasmidtrack>
`;
template += `
<plasmidtrack width="{{seqSelectionRightArm.armWidth}}" trackstyle="{{seqSelectionRightArm.armTrackStyle}}" radius="{{seqSelectionRightArm.armRadius}}">
<trackmarker start="{{seqSelectionRightArm.armStart}}" wadjust="{{seqSelectionRightArm.armWadjust}}" markerclick="${seqSelectionRightArm.armMarkerClick}">
<markerlabel lineclass="{{seqSelectionRightArm.armLineClass}}" linestyle="${seqSelectionRightArm.armLineStyle}" showline="{{seqSelectionRightArm.armShowLine}}" text="" vadjust="{{seqSelectionRightArm.armVadjust}}" labelclick="${seqSelectionRightArm .armLabelClick}"></markerlabel>
</trackmarker>
</plasmidtrack>
`;
template += `
<plasmidtrack trackstyle="{{seqSelectionArrow.arrowTrackStyle}}" radius="{{seqSelectionArrow.arrowTrackRadius}}">
<trackmarker start="{{seqSelectionArrow.arrowStart}}" end="{{seqSelectionArrow.arrowEnd}}" markerstyle="{{seqSelectionArrow.arrowMarkerStyle}}" arrowendlength="${seqSelectionArrow.arrowEndLength}" arrowendwidth="${seqSelectionArrow.arrowEndWidth}">
<markerlabel type="path" class="seqSelectionArrowText" text="{{seqSelectionArrow.arrowText}}"></markerlabel>
</trackmarker>
</plasmidtrack>
`;
return template;
}
/**
* Overwrites the current disk template cache for the base figure of figure
*
* @export
* @param {CircularFigure} figure
*/
export function cacheBaseFigureTemplate(figure : CircularFigure) : void
{
try
{
fs.mkdirSync(getReadableAndWritable(`rt/circularFigures/${figure.uuid}`));
}
catch(err)
{}
fs.writeFileSync(getReadableAndWritable(`rt/circularFigures/${figure.uuid}/baseFigure`),buildBaseFigureTemplate(figure));
}
/**
* Overwrites the current disk SVG cache for the base figure of figure
*
* @export
* @param {CircularFigure} figure
* @param {string} svg
*/
export function cacheBaseFigureSVG(figure : CircularFigure,svg : string) : void
{
fs.writeFileSync(getReadableAndWritable(`rt/circularFigures/${figure.uuid}/baseFigure.svg`),svg);
}
/**
* Returns the current disk template cache contents for the base figure of figure
*
* @export
* @param {CircularFigure} figure
* @returns {string}
*/
export function getBaseFigureTemplateFromCache(figure : CircularFigure) : string
{
return fs.readFileSync(getReadableAndWritable(`rt/circularFigures/${figure.uuid}/baseFigure`)).toString();
}
/**
* Returns the current disk SVG cache for the base figure of figure
*
* @export
* @param {CircularFigure} figure
* @returns {string}
*/
export function getBaseFigureSVGFromCache(figure : CircularFigure) : string
{
return fs.readFileSync(getReadableAndWritable(`rt/circularFigures/${figure.uuid}/baseFigure.svg`)).toString();
}
/**
* Deletes the contents of the current disk SVG cache for the base figure of figure
*
* @export
* @param {CircularFigure} figure
*/
export function deleteBaseFigureSVGFromCache(figure : CircularFigure) : void
{
try
{
fs.unlinkSync(getReadableAndWritable(`rt/circularFigures/${figure.uuid}/baseFigure.svg`));
}
catch(err)
{}
}
/**
* Compile base figure. Returns the resulting SVG
*
* @export
* @param {CircularFigure} figure
* @returns {Promise<string>}
*/
export function compileBaseFigureSVG(figure : CircularFigure) : Promise<string>
{
return new Promise<string>(async (resolve,reject) =>
{
let nodes : Array<html.Node> = await html.loadFromString(
assembleCompilableBaseFigureTemplates(figure)
);
let plasmid : Plasmid = new Plasmid();
plasmid.$scope = makeMapScope(figure);
for(let i = 0; i != nodes.length; ++i)
{
if(nodes[i].name == "div")
{
for(let k = 0; k != nodes[i].children.length; ++k)
{
if(nodes[i].children[k].name == "plasmid")
{
plasmid.fromNode<html.Node>(nodes[i].children[k]);
break;
}
}
}
}
resolve(plasmid.renderStart()+plasmid.renderEnd());
});
}
/**
* Returns the distance from the begginning of the figure to the begginning of the contig specified by contiguuid
*
* @param {CircularFigure} figure
* @param {string} contiguuid
* @returns {number}
*/
function getBaseBP(figure : CircularFigure,contiguuid : string) : number
{
//Walk the figures contigs clockwise and return the offset of the beginning of contig specified
//by contiguuid from the start of the figure
let base = 0;
for(let i = 0; i != figure.contigs.length; ++i)
{
if(figure.contigs[i].uuid == contiguuid)
return base;
base += figure.contigs[i].bp;
}
return -1;
}
/**
* Group coverage depths by nucleotide position
*
* @interface PositionsWithDepths
*/
interface PositionsWithDepths
{
depth : number;
positions : Array<number>;
}
/**
* Returns the templates for a coverage track of align for the contig specified by contiguuid on figure in the specified colour
*
* @export
* @param {CircularFigure} figure
* @param {string} contiguuid
* @param {AlignData} align
* @param {string} [colour="rgb(64,64,64)"]
* @param {number} [scaleFactor=1]
* @returns {Promise<string>}
*/
export async function buildCoverageTrackTemplate(
figure : CircularFigure,
contiguuid : string,
align : AlignData,
colour : string = "rgb(64,64,64)",
scaleFactor : number = 1,
log10Scale : boolean = false
) : Promise<string>
{
return new Promise<string>((resolve,reject) =>
{
let coverageTracks : string = "";
//Stream the distilled samtools depth data from the specified alignment for the specified contig
let rl : readline.ReadLine = readline.createInterface(<readline.ReadLineOptions>{
input : fs.createReadStream(getReadableAndWritable(`rt/AlignmentArtifacts/${align.uuid}/contigCoverage/${contiguuid}`))
});
let baseBP = getBaseBP(figure,contiguuid);
if(baseBP == -1)
throw new Error("Could not get base position of "+figure.name+" for reference");
/*
Anular Plasmid tracks are declared in terms of y position. We want to group all positions with the same depth
together so we can create one track for each depth and then render every position with the same depth onto
the same track.
*/
let depths : Array<PositionsWithDepths> = new Array<PositionsWithDepths>();
rl.on("line",function(line : string)
{
let tokens = line.split(/\s/g);
let depth = parseInt(tokens[1]);
if(log10Scale)
depth = Math.log10(depth);
let found = false;
for(let i = 0; i != depths.length; ++i)
{
if(depths[i].depth == depth)
{
depths[i].positions.push(parseInt(tokens[0]));
found = true;
break;
}
}
if(!found)
{
depths.push(<PositionsWithDepths>{
depth : depth,
positions : <Array<number>>[parseInt(tokens[0])]
});
}
});
rl.on("close",function()
{
//sort depths
depths.sort(function(a : PositionsWithDepths,b : PositionsWithDepths)
{
return a.depth - b.depth;
});
/*
Instead of rendering one marker for every single position, we stretch a single marker to cover sequential positions which are all at the same
depth.
*/
for(let i = 0; i != depths.length; ++i)
{
//sort positions within each depth position we're looking at
depths[i].positions.sort(function(a : number,b : number)
{
return a - b;
});
let res = "";
//render the start of the current track
res += `<plasmidtrack trackstyle="fill-opacity:0.0;fill:${colour}" width="10" radius="{{genome.radius+${100+(depths[i].depth*scaleFactor)}}}" >`;
//try to find a group of sequential positions
for(let k = 0; k != depths[i].positions.length; ++k)
{
let offset = 1;
let initial = k;
while(depths[i].positions[k + offset] == depths[i].positions[initial] + offset)
{
if(k + offset == depths[i].positions.length)
break;
offset++;
}
//in case we didn't find any sequential positions, this will render singles fine
k = k + (offset - 1);
res += `<trackmarker start="${baseBP+depths[i].positions[initial]}" end="${baseBP+depths[i].positions[initial]+offset}" markerstyle="fill:${colour};stroke-width:1px;" wadjust="-8"></trackmarker>`;
}
res += "</plasmidtrack>";
coverageTracks += res;
}
resolve(coverageTracks);
});
});
}
/**
* Returns the templates for a coverage track of align for the contig specified by contiguuid on figure in the specified colour. Creates and saves a trackrecord
* on figure with the results
*
* @export
* @param {CircularFigure} figure
* @param {string} contiguuid
* @param {AlignData} align
* @param {string} [colour="rgb(64,64,64)"]
* @param {number} [scaleFactor=1]
* @returns {Promise<string>}
*/
export async function cacheCoverageTrackTemplate(
figure : CircularFigure,
contiguuid : string,
align : AlignData,
colour : string = "rgb(64,64,64)",
scaleFactor : number = 1,
log10Scale : boolean = false
) : Promise<void>
{
return new Promise<void>(async (resolve,reject) =>
{
try
{
mkdirp.sync(getReadableAndWritable(`rt/circularFigures/${figure.uuid}/coverage/${align.uuid}/${contiguuid}`));
}
catch(err)
{}
let coverageTracks = await buildCoverageTrackTemplate(figure,contiguuid,align,colour,scaleFactor,log10Scale);
let trackRecord = new RenderedCoverageTrackRecord(align.uuid,contiguuid,figure.uuid,colour,scaleFactor,log10Scale);
fs.writeFileSync(getCachedCoverageTrackTemplatePath(trackRecord),coverageTracks);
figure.renderedCoverageTracks.push(trackRecord);
resolve();
});
}
/**
* Returns the path to the template cache for the specified coverage track
*
* @export
* @param {RenderedCoverageTrackRecord} trackRecord
* @returns {string}
*/
export function getCachedCoverageTrackTemplatePath(trackRecord : RenderedCoverageTrackRecord) : string
{
return getReadableAndWritable(`rt/circularFigures/${trackRecord.uuidFigure}/coverage/${trackRecord.uuidAlign}/${trackRecord.uuidContig}/${trackRecord.uuid}`);
}
/**
* Returns the path to the SVG cache for the specified coverage track
*
* @export
* @param {RenderedCoverageTrackRecord} trackRecord
* @returns {string}
*/
export function getCachedCoverageTrackSVGPath(trackRecord : RenderedCoverageTrackRecord) : string
{
return getReadableAndWritable(`rt/circularFigures/${trackRecord.uuidFigure}/coverage/${trackRecord.uuidAlign}/${trackRecord.uuidContig}/${trackRecord.uuid}.svg`);
}
/**
* Overwrites the disk SVG cache for the specified coverage track
*
* @export
* @param {RenderedCoverageTrackRecord} trackRecord
* @param {string} svg
*/
export function cacheCoverageTrackSVG(trackRecord : RenderedCoverageTrackRecord,svg : string) : void
{
fs.writeFileSync(getCachedCoverageTrackSVGPath(trackRecord),svg);
}
/**
* Returns the current SVG of the specified coverage track
*
* @export
* @param {RenderedCoverageTrackRecord} trackRecord
* @returns {string}
*/
export function getCoverageTrackSVGFromCache(trackRecord : RenderedCoverageTrackRecord) : string
{
return fs.readFileSync(getCachedCoverageTrackSVGPath(trackRecord)).toString();
}
/**
* Returns the path to the protocol buffer cache for the specified coverage track
*
* @export
* @param {RenderedCoverageTrackRecord} trackRecord
* @returns {string}
*/
export function getCoverageTrackPBPath(trackRecord : RenderedCoverageTrackRecord) : string
{
return getReadableAndWritable(`rt/circularFigures/${trackRecord.uuidFigure}/coverage/${trackRecord.uuidAlign}/${trackRecord.uuidContig}/${trackRecord.uuid}.pb`);
}
/**
* Returns the disk protocol buffer cache for the specified coverage track
*
* @export
* @param {RenderedCoverageTrackRecord} trackRecord
* @returns {Buffer}
*/
export function getCoverageTrackPBFromCache(trackRecord : RenderedCoverageTrackRecord) : Buffer
{
return fs.readFileSync(getCoverageTrackPBPath(trackRecord));
}
/**
* Overwrites the disk protocol buffer cache for the specified coverage track
*
* @export
* @param {RenderedCoverageTrackRecord} trackRecord
* @param {Plasmid} plasmid
*/
export function cacheCoverageTrackPB(trackRecord : RenderedCoverageTrackRecord,plasmid : Plasmid) : void
{
let pb = pbDirectives.Node.create(plasmidToPB(plasmid));
fs.writeFileSync(getCoverageTrackPBPath(trackRecord),pbDirectives.Node.encode(pb).finish());
}
/**
* Holds information relevant to display for a given SNP
*
* @interface SNPPosition
*/
interface SNPPosition
{
position : number;
relativePosition : number;
from : string;
to : string;
colour : string
adjust : number;
}
/**
* Returns the templates for a SNP track of align for the contig specified by contiguuid on figure in the specified colour
*
* @export
* @param {CircularFigure} figure
* @param {string} contiguuid
* @param {AlignData} align
* @param {string} [colour="rgb(64,64,64)"]
* @returns {Promise<string>}
*/
export function buildSNPTrackTemplate(
figure : CircularFigure,
contiguuid : string,
align : AlignData,
colour : string = "rgb(64,64,64)"
) : Promise<string>
{
return new Promise<string>((resolve,reject) =>
{
let SNPTracks : string = "";
let baseBP = getBaseBP(figure,contiguuid);
if(baseBP == -1)
throw new Error("Could not get base position of "+figure.name+" for reference");
let SNPPositions : Array<SNPPosition> = new Array<SNPPosition>();
let SNPs : Array<VCF2JSONRow>;
SNPs = jsonFile.readFileSync(getSNPsJSON(align));
let contigName = "";
for(let i = 0; i != figure.contigs.length; ++i)
{
if(figure.contigs[i].uuid == contiguuid)
{
contigName = figure.contigs[i].name;
break;
}
}
for(let i = 0; i != SNPs.length; ++i)
{
if(SNPs[i].chrom == (contigName.split(/\s/g))[0])
{
SNPPositions.push(<SNPPosition>{
position : baseBP + parseInt(SNPs[i].position),
relativePosition : parseInt(SNPs[i].position),
from : SNPs[i].ref,
to : SNPs[i].var,
adjust : 20,
colour : colour
});
}
}
SNPPositions.sort(function(a : SNPPosition,b : SNPPosition)
{
return a.position - b.position;
});
for(let i = 0; i != SNPPositions.length; ++i)
{
for(let k = 0; k != SNPPositions.length; ++k)
{
if(i != k && i < k)
{
if((SNPPositions[k].position - SNPPositions[i].position) <= 85)
{
SNPPositions[k].adjust += 85;
}
}
}
}
for(let i = 0; i != SNPPositions.length; ++i)
{
SNPTracks += `
<plasmidtrack width="20" trackstyle="fill-opacity:0.0" radius="{{genome.radius}}">
<trackmarker start="${SNPPositions[i].position}" markerstyle="stroke:${SNPPositions[i].colour};stroke-dasharray:2,2;stroke-width:2px;" wadjust="{{genome.radius+${SNPPositions[i].adjust}}}">
<markerlabel style="font-size:20px;fill:${SNPPositions[i].colour}" text="${SNPPositions[i].from}${SNPPositions[i].relativePosition}${SNPPositions[i].to}" vadjust="{{genome.radius+${SNPPositions[i].adjust}}}"></markerlabel>
</trackmarker>
</plasmidtrack>
`;
}
resolve(SNPTracks);
});
}
/**
* Returns the templates for a SNP track of align for the contig specified by contiguuid on figure in the specified colour. Creates and saves a trackrecord
* on figure with the results
*
* @export
* @param {CircularFigure} figure