/
vis_defines.py
1775 lines (1637 loc) · 82.7 KB
/
vis_defines.py
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
from pyramid.response import Response
from pyramid.view import view_config
from pyramid.compat import bytes_
from snovault import Item
from collections import OrderedDict
from copy import deepcopy
import json
import os
from urllib.parse import (
parse_qs,
urlencode,
)
from snovault.elasticsearch.interfaces import ELASTIC_SEARCH
import time
from pkg_resources import resource_filename
from .vis_igv import file_igv_viewable
import logging
log = logging.getLogger(__name__)
#log.setLevel(logging.DEBUG)
log.setLevel(logging.INFO)
IHEC_DEEP_DIG = True # ihec requires pipeline and aligner information which is not easy to get
IHEC_LIB_STRATEGY = {
'ATAC-seq': 'ATAC-seq',
'ChIP-seq': 'ChIP-Seq',
'DNase-seq': 'DNase-Hypersensitivity',
'MeDIP-seq': 'MeDIP-Seq',
'microRNA-seq': 'miRNA-Seq',
'microRNA counts': 'miRNA-Seq',
'MRE-seq': 'MRE-Seq',
'RNA-seq': 'RNA-Seq',
'RRBS': 'Bisulfite-Seq',
'whole-genome shotgun bisulfite sequencing': 'Bisulfite-Seq'
}
ASSEMBLY_DETAILS = {
'GRCh38': { 'species': 'Homo sapiens', 'assembly_reference': 'GRCh38',
'common_name': 'human',
'ucsc_assembly': 'hg38',
'ensembl_host': 'www.ensembl.org',
'quickview': True,
'hic': True,
'comment': 'Ensembl works'
},
'GRCh38-minimal': { 'species': 'Homo sapiens', 'assembly_reference': 'GRCh38',
'common_name': 'human',
'ucsc_assembly': 'hg38',
'ensembl_host': 'www.ensembl.org',
},
'hg19': { 'species': 'Homo sapiens', 'assembly_reference': 'GRCh37',
'common_name': 'human',
'ucsc_assembly': 'hg19',
'NA_ensembl_host': 'grch37.ensembl.org',
'quickview': True,
'hic': True,
'comment': 'Ensembl DOES NOT WORK'
},
'mm10': { 'species': 'Mus musculus', 'assembly_reference': 'GRCm38',
'common_name': 'mouse',
'ucsc_assembly': 'mm10',
'ensembl_host': 'www.ensembl.org',
'quickview': True,
'comment': 'Ensembl works'
},
'mm10-minimal': { 'species': 'Mus musculus', 'assembly_reference': 'GRCm38',
'common_name': 'mouse',
'ucsc_assembly': 'mm10',
'ensembl_host': 'www.ensembl.org',
'quickview': True,
'comment': 'Should this be removed?'
},
'mm9': { 'species': 'Mus musculus', 'assembly_reference': 'NCBI37',
'common_name': 'mouse',
'ucsc_assembly': 'mm9',
'NA_ensembl_host': 'may2012.archive.ensembl.org',
'quickview': True,
'comment': 'Ensembl DOES NOT WORK'
},
'dm6': { 'species': 'Drosophila melanogaster', 'assembly_reference': 'BDGP6',
'common_name': 'fruit fly',
'ucsc_assembly': 'dm6',
'NA_ensembl_host': 'www.ensembl.org',
'quickview': True,
'comment': 'Ensembl DOES NOT WORK'
},
'dm3': { 'species': 'Drosophila melanogaster', 'assembly_reference': 'BDGP5',
'common_name': 'fruit fly',
'ucsc_assembly': 'dm3',
'NA_ensembl_host': 'dec2014.archive.ensembl.org',
'quickview': True,
'comment': 'Ensembl DOES NOT WORK'
},
'ce11': { 'species': 'Caenorhabditis elegans', 'assembly_reference': 'WBcel235',
'common_name': 'worm',
'ucsc_assembly': 'ce11',
'NA_ensembl_host': 'www.ensembl.org',
'quickview': True,
'comment': 'Ensembl DOES NOT WORK'
},
'ce10': { 'species': 'Caenorhabditis elegans', 'assembly_reference': 'WS220',
'common_name': 'worm',
'ucsc_assembly': 'ce10',
'quickview': True,
'comment': 'Never Ensembl'
},
'ce6': { 'species': 'Caenorhabditis elegans', 'assembly_reference': 'WS190',
'common_name': 'worm',
'ucsc_assembly': 'ce6',
'comment': 'Never Ensembl, not found in encoded'
},
'J02459.1': { 'species': 'Escherichia virus Lambda', 'assembly_reference': 'J02459.1',
'common_name': 'lambda phage',
'comment': 'Never visualized'
},
}
BROWSER_FILE_TYPES = {
'ucsc': {'bigWig', 'bigBed'},
'ensembl': {'bigWig', 'bigBed'},
'quickview': {'bigWig', 'bigBed'},
'hic': {'hic'},
}
# Distinct from ASSEMBLY_DETAILS['ucsc_assembly'] as that defines allowed mappings
ASSEMBLY_TO_UCSC_ID = {
'GRCh38-minimal': 'hg38',
'GRCh38': 'hg38',
'GRCh37': 'hg19',
'mm10-minimal': 'mm10',
'GRCm38': 'mm10',
'NCBI37': 'mm9',
'BDGP6': 'dm6',
'BDGP5': 'dm3',
'WBcel235': 'ce11'
}
QUICKVIEW_STATUSES_BLOCKED = ["deleted", "revoked", "replaced"]
VISIBLE_DATASET_STATUSES = ["released"]
VISIBLE_FILE_STATUSES = ["released"]
BIGWIG_FILE_TYPES = ['bigWig']
BIGBED_FILE_TYPES = ['bigBed']
HIC_FILE_TYPES = ['hic']
VISIBLE_FILE_FORMATS = BIGBED_FILE_TYPES + BIGWIG_FILE_TYPES + HIC_FILE_TYPES
VISIBLE_DATASET_TYPES = ["Experiment", "Annotation"]
VISIBLE_DATASET_TYPES_LC = ["experiment", "annotation"]
# Supported tokens are the only tokens the code currently knows how to look up.
SUPPORTED_MASK_TOKENS = [
"{replicate}", # replicate that that will be displayed: ("rep1", "combined")
"{rep_tech}", # The rep_tech if desired ("rep1_1", "combined")
"{replicate_number}", # The replicate number displayed for visualized track: ("1", "0")
"{biological_replicate_number}",
"{technical_replicate_number}",
"{assay_title}",
"{assay_term_name}", # dataset.assay_term_name
"{annotation_type}", # some datasets have annotation type and not assay
"{output_type}", # files.output_type
"{accession}", "{experiment.accession}", # "{accession}" is assumed to be experiment.accession
"{file.accession}",
"{@id}", "{@type}", # dataset only
"{target}", "{target.label}", # Either is acceptible
"{target.title}",
"{target.name}", # Used in metadata URLs
"{target.investigated_as}",
"{biosample_term_name}", "{biosample_term_name|multiple}", # "|multiple": none means multiple
"{output_type_short_label}", # hard-coded translation from output_type to very
# short version
"{replicates.library.biosample.summary}", # Idan, Forrest and Cricket are conspiring to move
# to dataset.biosample_summary & make it shorter
"{replicates.library.biosample.summary|multiple}", # "|multiple": none means multiple
"{assembly}", # you don't need this in titles, but it is crucial
# variable and seems to not be being applied
# # correctly in the html generation
"{lab.title}", # In metadata
"{award.rfa}", # To distinguish vis_defs based upon award
# TODO "{software? or pipeline?}", # Cricket: "I am stumbling over the fact that we
# # can't distinguish tophat and star produced files"
# TODO "{phase}", # Cricket: "If we get to the point of being fancy
# # in the replication timing, then we need this,
# # otherwise it bundles up in the biosample summary now"
]
# Simple tokens are a straight lookup, no questions asked
SIMPLE_DATASET_TOKENS = ["{accession}", "{assay_title}",
"{assay_term_name}", "{annotation_type}", "{@id}", "{@type}"]
# static group defs are keyed by group title (or special token) and consist of
# tag: (optional) unique terse key for referencing group
# groups: (optional) { subgroups keyed by subgroup title }
# group_order: (optional) [ ordered list of subgroup titles ]
# other definitions
# live group defs are keyed by tag and are the transformed in memory version of static defs
# title: (required) same as the static group's key
# groups: (if appropriate) { subgroups keyed by subgroup tag }
# group_order: (if appropriate) [ ordered list of subgroup tags ]
VIS_DEFS_FOLDER = "static/vis_defs/"
VIS_DEFS_BY_TYPE = {}
VIS_DEFS_DEFAULT = {}
# vis_defs may not have the default experiment group defined
EXP_GROUP = "Experiment"
DEFAULT_EXPERIMENT_GROUP = {"tag": "EXP", "groups": {"one": {"title_mask": "{accession}",
"url_mask": "experiments/{accession}"}}}
# Pennants are flags that display at UCSC next to composite definitions
PENNANTS = {
"NHGRI": ("https://www.encodeproject.org/static/img/pennant-nhgri.png "
"https://www.encodeproject.org/ "
"\"This trackhub was automatically generated from the files and metadata found "
"at the ENCODE portal\""),
"ENCODE": ("https://www.encodeproject.org/static/img/pennant-encode.png "
"https://www.encodeproject.org/ "
"\"This trackhub was automatically generated from the ENCODE files and metadata "
"found at the ENCODE portal\""),
"modENCODE": ("https://www.encodeproject.org/static/img/pennant-encode.png "
"https://www.encodeproject.org/ "
"\"This trackhub was automatically generated from the modENCODE files and "
"metadata found at the ENCODE portal\""),
"GGR": ("https://www.encodeproject.org/static/img/pennant-ggr.png "
"https://www.encodeproject.org/ "
"\"This trackhub was automatically generated from the Genomics of "
"Gene Regulation files files and metadata found at the "
"ENCODE portal\""),
"REMC": ("https://www.encodeproject.org/static/img/pennant-remc.png "
"https://www.encodeproject.org/ "
"\"This trackhub was automatically generated from the Roadmap Epigentics files "
"and metadata found at the ENCODE portal\"")
# "Roadmap": "encodeThumbnail.jpg "
# "https://www.encodeproject.org/ "
# "\"This trackhub was automatically generated from the Roadmap files and "
# "metadata found at https://www.encodeproject.org/\"",
# "modERN": "encodeThumbnail.jpg "
# "https://www.encodeproject.org/ "
# "\"This trackhub was automatically generated from the modERN files and "
# "metadata found at https://www.encodeproject.org/\"",
}
# supported groups for arranging/sorting files in a visualization
SUPPORTED_SUBGROUPS = ["Biosample", "Targets", "Assay", "Replicates", "Views", EXP_GROUP]
# UCSC trackDb settings that are supported
SUPPORTED_TRACK_SETTINGS = [
"type", "visibility", "longLabel", "shortLabel", "color", "altColor", "allButtonPair", "html",
"scoreFilter", "spectrum", "minGrayLevel", "itemRgb", "viewLimits",
"autoScale", "negateValues", "maxHeightPixels", "windowingFunction", "transformFunc",
"signalFilter", "signalFilterLimits", "pValueFilter", "pValueFilterLimits",
"qValueFilter", "qValueFilterLimits" ]
VIEW_SETTINGS = SUPPORTED_TRACK_SETTINGS
# UCSC trackDb settings that are supported
COMPOSITE_SETTINGS = ["longLabel", "shortLabel", "visibility", "pennantIcon", "allButtonPair",
"html"]
# UCSC settings for individual files (tracks)
TRACK_SETTINGS = ["bigDataUrl", "longLabel", "shortLabel", "type", "color", "altColor"]
# This dataset terms (among others) are needed in vis_dataset formatting
ENCODED_DATASET_TERMS = ['biosample_ontology.term_name',
'biosample_ontology.term_id', 'biosample_summary',
'biosample_ontology.classification', 'assay_term_id',
'assay_term_name']
# This dataset terms (among others) are needed in vis_dataset formatting
ENCODED_DATASET_EMBEDDED_TERMS = {
'biosample_accession': 'replicates.library.biosample.accession',
'sex': 'replicates.library.biosample.sex',
'taxon_id': 'replicates.library.biosample.organism.taxon_id'
}
# Abbeviations for output_type to fit in UCSC shortLabel
OUTPUT_TYPE_8CHARS = {
# "idat green channel": "idat gr", # raw data
# "idat red channel": "idat rd", # raw data
# "reads":"reads", # raw data
# "intensity values": "intnsty", # raw data
# "reporter code counts": "rcc", # raw data
# "alignments":"aln", # our plan is not to visualize alignments for now
# "unfiltered alignments":"unflt aln", # our plan is not to visualize alignments for now
# "transcriptome alignments":"tr aln", # our plan is not to visualize alignments for now
"minus strand signal of all reads": "all -",
"plus strand signal of all reads": "all +",
"signal of all reads": "all sig",
"normalized signal of all reads": "normsig",
# "raw minus strand signal":"raw -", # these are all now minus signal of all reads
# "raw plus strand signal":"raw +", # these are all now plus signal of all reads
"raw signal": "raw sig",
"raw normalized signal": "nraw",
"read-depth normalized signal": "rdnorm",
"control normalized signal": "ctlnorm",
"minus strand signal of unique reads": "unq -",
"plus strand signal of unique reads": "unq +",
"signal of unique reads": "unq sig",
"signal p-value": "pval sig",
"fold change over control": "foldchg",
"exon quantifications": "exon qt",
"gene quantifications": "gene qt",
"microRNA quantifications": "miRNA qt",
"transcript quantifications": "trsct qt",
"library fraction": "lib frac",
"methylation state at CpG": "mth CpG",
"methylation state at CHG": "mth CHG",
"methylation state at CHH": "mth CHH",
"enrichment": "enrich",
"replication timing profile": "repli tm",
"variant calls": "vars",
"filtered SNPs": "f SNPs",
"filtered indels": "f indel",
"hotspots": "hotspt",
"long range chromatin interactions": "lrci",
"chromatin interactions": "ch int",
"topologically associated domains": "tads",
"genome compartments": "compart",
"open chromatin regions": "open ch",
"filtered peaks": "filt pk",
"filtered regions": "filt reg",
"DHS peaks": "DHS pk",
"peaks": "peaks",
"replicated peaks": "rep pk",
"RNA-binding protein associated mRNAs": "RBP RNA",
"splice junctions": "splice",
"transcription start sites": "tss",
"predicted enhancers": "pr enh",
"candidate enhancers": "can enh",
"candidate promoters": "can pro",
"predicted forebrain enhancers": "fb enh", # plan to fix these
"predicted heart enhancers": "hrt enh", # plan to fix these
"predicted whole brain enhancers": "wb enh", # plan to fix these
"candidate Cis-Regulatory Elements": "cCRE",
# "genome reference":"ref", # references not to be viewed
# "transcriptome reference":"tr ref", # references not to be viewed
# "transcriptome index":"tr rix", # references not to be viewed
# "tRNA reference":"tRNA", # references not to be viewed
# "miRNA reference":"miRNA", # references not to be viewed
# "snRNA reference":"snRNA", # references not to be viewed
# "rRNA reference":"rRNA", # references not to be viewed
# "TSS reference":"TSS", # references not to be viewed
# "reference variants":"var", # references not to be viewed
# "genome index":"ref ix", # references not to be viewed
# "female genome reference":"XX ref", # references not to be viewed
# "female genome index":"XX rix", # references not to be viewed
# "male genome reference":"XY ref", # references not to be viewed
# "male genome index":"XY rix", # references not to be viewed
# "spike-in sequence":"spike", # references not to be viewed
"IDR thresholded peaks": "IDRt pk",
"optimal IDR thresholded peaks": "oIDR pk",
"conservative IDR thresholded peaks": "cIDR pk",
"enhancer validation": "enh val",
"semi-automated genome annotation": "saga"
}
# Track coloring is defined by biosample
BIOSAMPLE_COLOR = {
"GM12878": {"color": "153,38,0", "altColor": "115,31,0"}, # Dark Orange-Red
"H1-hESC": {"color": "0,107,27", "altColor": "0,77,20"}, # Dark Green
"K562": {"color": "46,0,184", "altColor": "38,0,141"}, # Dark Blue
"keratinocyte": {"color": "179,0,134", "altColor": "154,0,113"}, # Darker Pink-Purple
"HepG2": {"color": "189,0,157", "altColor": "189,76,172"}, # Pink-Purple
"HeLa-S3": {"color": "0,119,158", "altColor": "0,94,128"}, # Greenish-Blue
"HeLa": {"color": "0,119,158", "altColor": "0,94,128"}, # Greenish-Blue
"A549": {"color": "204,163,0", "altColor": "218,205,22"}, # Dark Yellow
"endothelial cell of umbilical vein": {"color": "224,75,0",
"altColor": "179,60,0"}, # Pink
"MCF-7": {"color": "22,219,206", "altColor": "18,179,168"}, # Cyan
"SK-N-SH": {"color": "255,115,7", "altColor": "218,98,7"}, # Orange
"IMR-90": {"color": "6,62,218", "altColor": "5,52,179"}, # Blue
"CH12.LX": {"color": "86,180,233", "altColor": "76,157,205"}, # Dark Orange-Red
"MEL cell line": {"color": "46,0,184", "altColor": "38,0,141"}, # Dark Blue
"brain": {"color": "105,105,105", "altColor": "77,77,77"}, # Grey
"eye": {"color": "105,105,105", "altColor": "77,77,77"}, # Grey
"spinal cord": {"color": "105,105,105", "altColor": "77,77,77"}, # Grey
"olfactory organ": {"color": "105,105,105", "altColor": "77,77,77"}, # Grey
"esophagus": {"color": "230,159,0", "altColor": "179,125,0"}, # Mustard
"stomach": {"color": "230,159,0", "altColor": "179,125,0"}, # Mustard
"liver": {"color": "230,159,0", "altColor": "179,125,0"}, # Mustard
"pancreas": {"color": "230,159,0", "altColor": "179,125,0"}, # Mustard
"large intestine": {"color": "230,159,0", "altColor": "179,125,0"}, # Mustard
"small intestine": {"color": "230,159,0", "altColor": "179,125,0"}, # Mustard
"gonad": {"color": "0.0,158,115", "altColor": "0.0,125,92"}, # Darker Aquamarine
"mammary gland": {"color": "0.0,158,115", "altColor": "0.0,125,92"}, # Darker Aquamarine
"prostate gland": {"color": "0.0,158,115", "altColor": "0.0,125,92"}, # Darker Aquamarine
"ureter": {"color": "204,121,167", "altColor": "166,98,132"}, # Grey-Pink
"urinary bladder": {"color": "204,121,167", "altColor": "166,98,132"}, # Grey-Pink
"kidney": {"color": "204,121,167", "altColor": "166,98,132"}, # Grey-Pink
"muscle organ": {"color": "102,50,200 ", "altColor": "81,38,154"}, # Violet
"tongue": {"color": "102,50,200", "altColor": "81,38,154"}, # Violet
"adrenal gland": {"color": "189,0,157", "altColor": "154,0,128"}, # Pink-Purple
"thyroid gland": {"color": "189,0,157", "altColor": "154,0,128"}, # Pink-Purple
"lung": {"color": "145,235,43", "altColor": "119,192,35"}, # Mossy green
"bronchus": {"color": "145,235,43", "altColor": "119,192,35"}, # Mossy green
"trachea": {"color": "145,235,43", "altColor": "119,192,35"}, # Mossy green
"nose": {"color": "145,235,43", "altColor": "119,192,35"}, # Mossy green
"placenta": {"color": "153,38,0", "altColor": "102,27,0"}, # Orange-Brown
"extraembryonic structure": {"color": "153,38,0",
"altColor": "102,27,0"}, # Orange-Brown
"thymus": {"color": "86,180,233", "altColor": "71,148,192"}, # Baby Blue
"spleen": {"color": "86,180,233", "altColor": "71,148,192"}, # Baby Blue
"bone element": {"color": "86,180,233", "altColor": "71,148,192"}, # Baby Blue
"blood": {"color": "86,180,233", "altColor": "71,148,192"}, # Baby Blue (red?)
"blood vessel": {"color": "214,0,0", "altColor": "214,79,79"}, # Red
"heart": {"color": "214,0,0", "altColor": "214,79,79"}, # Red
"lymphatic vessel": {"color": "214,0,0", "altColor": "214,79,79"}, # Red
"skin of body": {"color": "74,74,21", "altColor": "102,102,44"}, # Brown
}
VIS_CACHE_INDEX = "vis_cache"
class Sanitize(object):
# Tools for sanitizing labels
def escape_char(self, c, exceptions=['_'], htmlize=False, numeralize=False):
'''Pass through for 0-9,A-Z.a-z,_, but then either html encodes, numeralizes or removes special
characters.'''
n = ord(c)
if n >= 47 and n <= 57: # 0-9
return c
if n >= 65 and n <= 90: # A-Z
return c
if n >= 97 and n <= 122: # a-z
return c
if c in exceptions:
return c
if n == 32: # space
return '_'
if htmlize:
return "&#%d;" % n
if numeralize:
return "%d" % n
return ""
def label(self, s):
'''Encodes the string to swap special characters and leaves spaces alone.'''
new_s = "" # longLabel and shorLabel can have spaces and some special characters
for c in s:
new_s += self.escape_char(c, [' ', '_', '.', '-', '(', ')', '+'], htmlize=False)
return new_s
def title(self, s):
'''Encodes the string to swap special characters and replace spaces with '_'.'''
new_s = "" # Titles appear in tag=title pairs and cannot have spaces
for c in s:
new_s += self.escape_char(c, ['_', '.', '-', '(', ')', '+'], htmlize=True)
return new_s
def tag(self, s):
'''Encodes the string to swap special characters and remove spaces.'''
new_s = ""
first = True
for c in s:
new_s += self.escape_char(c, numeralize=True)
if first:
if new_s.isdigit(): # tags cannot start with digit.
new_s = 'z' + new_s
first = False
return new_s
def name(self, s):
'''Encodes the string to remove special characters swap spaces for underscores.'''
new_s = ""
for c in s:
new_s += self.escape_char(c)
return new_s
sanitize = Sanitize()
class VisDefines(object):
# Loads vis_def static files and other defines for vis formatting
# This class is also a swiss army knife of vis formatting conversions
def __init__(self, request, dataset=None):
# Make these global so that the same files are not continually reloaded
self._request = request
global VIS_DEFS_BY_TYPE
global VIS_DEFS_DEFAULT
self.vis_defs = VIS_DEFS_BY_TYPE
self.vis_def_default = VIS_DEFS_DEFAULT
self.vis_type = "opaque"
self.dataset = dataset
if not self.vis_defs:
self.load_vis_defs()
def load_vis_defs(self):
'''Loads 'vis_defs' (visualization definitions by assay type) from a static files.'''
#global VIS_DEFS_FOLDER
global VIS_DEFS_BY_TYPE
global VIS_DEFS_DEFAULT
folder = resource_filename(__name__, VIS_DEFS_FOLDER)
files = os.listdir(folder)
for filename in files:
if filename.endswith('.json'):
with open(folder + filename) as fh:
log.debug('Preparing to load %s' % (filename))
vis_def = json.load(fh)
# Could alter vis_defs here if desired.
if vis_def:
VIS_DEFS_BY_TYPE.update(vis_def)
self.vis_defs = VIS_DEFS_BY_TYPE
VIS_DEFS_DEFAULT = self.vis_defs.get("opaque",{})
self.vis_def_default = VIS_DEFS_DEFAULT
def get_vis_type(self):
'''returns the best visualization definition type, based upon dataset.'''
assert(self.dataset is not None)
assay = self.dataset.get("assay_term_name", 'none')
if isinstance(assay, list):
if len(assay) == 1:
assay = assay[0]
else:
log.debug("assay_term_name for %s is unexpectedly a list %s" %
(self.dataset['accession'], str(assay)))
return "opaque"
# simple rule defined in most vis_defs
for vis_type in sorted(self.vis_defs.keys(), reverse=True): # Reverse pushes anno to bottom
if "rule" in self.vis_defs[vis_type]:
rule = self.vis_defs[vis_type]["rule"].replace('{assay_term_name}', assay)
if rule.find('{') != -1:
rule = self.convert_mask(rule)
if eval(rule):
self.vis_type = vis_type
return self.vis_type
# Ugly rules:
vis_type = None
if assay in ["RNA-seq", "PAS-seq", "microRNA-seq", \
"shRNA knockdown followed by RNA-seq", \
"CRISPR genome editing followed by RNA-seq", \
"CRISPRi followed by RNA-seq", \
"single cell isolation followed by RNA-seq", \
"siRNA knockdown followed by RNA-seq"]:
reps = self.dataset.get("replicates", []) # NOTE: overly cautious
if len(reps) < 1:
log.debug("Could not distinguish between long and short RNA for %s because there are "
"no replicates. Defaulting to short." % (self.dataset.get("accession")))
vis_type = "SRNA" # this will be more noticed if there is a mistake
else:
size_range = reps[0].get("library", {}).get("size_range", "")
if size_range.startswith('>'):
try:
min_size = int(size_range[1:])
max_size = min_size
except:
log.debug("Could not distinguish between long and short RNA for %s. "
"Defaulting to short." % (self.dataset.get("accession")))
vis_type = "SRNA" # this will be more noticed if there is a mistake
elif size_range.startswith('<'):
try:
max_size = int(size_range[1:]) - 1
min_size = 0
except:
log.debug("Could not distinguish between long and short RNA for %s. "
"Defaulting to short." % (self.dataset.get("accession")))
self.vis_type = "SRNA" # this will be more noticed if there is a mistake
return self.vis_type
else:
try:
sizes = size_range.split('-')
min_size = int(sizes[0])
max_size = int(sizes[1])
except:
log.debug("Could not distinguish between long and short RNA for %s. "
"Defaulting to short." % (self.dataset.get("accession")))
vis_type = "SRNA" # this will be more noticed if there is a mistake
if vis_type is None:
if min_size == 120 and max_size == 200: # Another ugly exception!
vis_type = "LRNA"
elif max_size <= 200 and max_size != min_size:
vis_type = "SRNA"
elif min_size >= 150:
vis_type = "LRNA"
elif (min_size + max_size)/2 >= 235: # This is some wicked voodoo (SRNA:108-347=227; LRNA:155-315=235)
vis_type = "SRNA"
if vis_type is None:
log.debug("%s (assay:'%s') has undefined vis_type" % (self.dataset['accession'], assay))
vis_type = "opaque" # This becomes a dict key later so None is not okay
self.vis_type = vis_type
return self.vis_type
def get_vis_def(self, vis_type=None):
'''returns the visualization definition set, based upon dataset.'''
if vis_type is None:
vis_type = self.vis_type
vis_def = self.vis_defs.get(vis_type, self.vis_def_default)
if "other_groups" in vis_def and EXP_GROUP not in vis_def["other_groups"]["groups"]:
vis_def["other_groups"]["groups"][EXP_GROUP] = DEFAULT_EXPERIMENT_GROUP
if "sortOrder" in vis_def and EXP_GROUP not in vis_def["sortOrder"]:
vis_def["sortOrder"].append(EXP_GROUP)
return vis_def
def visible_file_statuses(self):
return VISIBLE_FILE_STATUSES
def supported_subgroups(self):
return SUPPORTED_SUBGROUPS
def encoded_dataset_terms(self):
return list(ENCODED_DATASET_EMBEDDED_TERMS.keys()) + ENCODED_DATASET_TERMS
def pennants(self, project):
return PENNANTS.get(project, PENNANTS['NHGRI'])
def find_pennent(self):
'''Returns an appropriate pennantIcon given dataset's award'''
assert(self.dataset is not None)
project = self.dataset.get("award", {}).get("project", "NHGRI")
return self.pennants(project)
def lookup_colors(self):
'''Using the mask, determine which color table to use.'''
assert(self.dataset is not None)
color = None
altColor = None
coloring = {}
ontology = self.dataset.get('biosample_ontology')
term = "unknown" # really only seen in test data!
if ontology is not None:
if not isinstance(ontology, list):
ontology = [ontology]
if len(ontology) == 1:
if isinstance(ontology[0], dict):
term = ontology[0]['term_name']
else:
log.debug("%s has biosample_ontology %s that is unexpectedly a list",
self.dataset['accession'],
str([bo['@id'] for bo in ontology]))
coloring = BIOSAMPLE_COLOR.get(term, {})
if not coloring:
for organ_slim in (os for bo in ontology
for os in bo['organ_slims']):
coloring = BIOSAMPLE_COLOR.get(organ_slim, {})
if coloring:
break
if coloring:
assert("color" in coloring)
if "altColor" not in coloring:
color = coloring["color"]
shades = color.split(',')
red = int(shades[0]) / 2
green = int(shades[1]) / 2
blue = int(shades[2]) / 2
altColor = "%d,%d,%d" % (red, green, blue)
coloring["altColor"] = altColor
return coloring
def add_living_color(self, live_format):
'''Adds color and altColor. Note that altColor is only added if color is found.'''
colors = self.lookup_colors()
if colors and "color" in colors:
live_format["color"] = colors["color"]
if "altColor" in colors:
live_format["altColor"] = colors["altColor"]
def rep_for_file(self, a_file):
'''Determines best rep_tech or rep for a file.'''
# Starting with a little cheat for rare cases where techreps are compared instead of bioreps
if a_file.get("file_format_type", "none") in ["idr_peak"]:
return "combined"
if a_file['output_type'].endswith("IDR thresholded peaks"):
return "combined"
bio_rep = 0
tech_rep = 0
if "replicate" in a_file:
bio_rep = a_file["replicate"]["biological_replicate_number"]
tech_rep = a_file["replicate"]["technical_replicate_number"]
elif "tech_replicates" in a_file:
# Do we want to make rep1_1.2.3 ? Not doing it now
tech_reps = a_file["tech_replicates"]
if len(tech_reps) == 1:
bio_rep = int(tech_reps[0].split('_')[0])
tech_reps = tech_reps[0][2:]
if len(tech_reps) == 1:
tech_rep = int(tech_reps)
elif len(tech_reps) > 1:
bio = 0
for tech in tech_reps:
if bio == 0:
bio = int(tech.split('_')[0])
elif bio != int(tech.split('_')[0]):
bio = 0
break
if bio > 0:
bio_rep = bio
elif "biological_replicates" in a_file:
bio_reps = a_file["biological_replicates"]
if len(bio_reps) == 1:
bio_rep = bio_reps[0]
if bio_rep == 0:
return "combined"
rep = "rep%d" % bio_rep
if tech_rep > 0:
rep += "_%d" % tech_rep
return rep
def lookup_embedded_token(self, name, obj):
'''Encodes the string to swap special characters and remove spaces.'''
token = ENCODED_DATASET_EMBEDDED_TERMS.get(name, name)
if token[0] == '{' and token[-1] == '}':
token = token[1:-1]
terms = token.split('.')
cur_obj = obj
while len(terms) > 0:
term = terms.pop(0)
cur_obj = cur_obj.get(term)
if len(terms) == 0 or cur_obj is None:
return cur_obj
if isinstance(cur_obj,list):
if len(cur_obj) == 0:
return None
cur_obj = cur_obj[0] # Can't presume to use any but first
return None
def lookup_token(self, token, dataset, a_file=None):
'''Encodes the string to swap special characters and remove spaces.'''
# dataset might not be self.dataset
if token not in SUPPORTED_MASK_TOKENS:
log.warn("Attempting to look up unexpected token: '%s'" % token)
return "unknown token"
if token in SIMPLE_DATASET_TOKENS:
term = dataset.get(token[1:-1])
if term is None:
return "Unknown " + token[1:-1].split('_')[0].capitalize()
elif isinstance(term,list) and len(term) > 3:
return "Collection of %d %ss" % (len(term),token[1:-1].split('_')[0].capitalize())
return term
elif token == "{experiment.accession}":
return dataset['accession']
elif token in ["{target}", "{target.label}", "{target.name}", "{target.title}", "{target.investigated_as}"]:
if token == '{target}':
token = '{target.label}'
term = self.lookup_embedded_token(token, dataset)
if term is None and token == '{target.name}':
term = self.lookup_embedded_token('{target.label}', dataset)
if term is not None:
if isinstance(term, list) and len(term) > 0:
return term[0]
return term
return "Unknown Target"
elif token in ["{replicates.library.biosample.summary}",
"{replicates.library.biosample.summary|multiple}"]:
term = self.lookup_embedded_token('{replicates.library.biosample.summary}', dataset)
if term is None:
term = dataset.get("{biosample_term_name}")
if term is not None:
return term
if token.endswith("|multiple}"):
return "multiple biosamples"
return "Unknown Biosample"
elif token == "{biosample_term_name}":
biosample_ontology = dataset.get('biosample_ontology')
if biosample_ontology is None:
return "Unknown Biosample"
if isinstance(biosample_ontology, dict):
return biosample_ontology['term_name']
if isinstance(biosample_ontology, list) and len(biosample_ontology) > 3:
return "Collection of %d Biosamples" % (len(biosample_ontology))
# The following got complicated because general Dataset objects
# cannot have biosample_ontology embedded properly. As a base class,
# some of the children, PublicationData, Project and 8 Series
# objects, have biosample_ontology embedded as array of objects,
# while experiment and annotation have it embedded as one single
# object. This becomes a problem when File object linkTo Dataset in
# general rather than one specific type. Current embedding system
# don't know how to map a property with type = ["array", "string"]
# in elasticsearch. Therefore, it is possible the
# "biosample_ontology" we got here is @id which should be embedded
# with the following code.
if not isinstance(biosample_ontology, list):
biosample_ontology = [biosample_ontology]
term_names = []
for type_obj in biosample_ontology:
if isinstance(type_obj, str):
term_names.append(
self._request.embed(type_obj, '@@object')['term_name']
)
elif 'term_name' in type_obj:
term_names.append(type_obj['term_name'])
if len(term_names) == 1:
return term_names[0]
else:
return term_names
elif token == "{biosample_term_name|multiple}":
biosample_ontology = dataset.get('biosample_ontology')
if biosample_ontology is None:
return "multiple biosamples"
return biosample_ontology.get('term_name')
# TODO: rna_species
# elif token == "{rna_species}":
# if replicates.library.nucleic_acid = polyadenylated mRNA
# rna_species = "polyA RNA"
# elif replicates.library.nucleic_acid == "RNA":
# if "polyadenylated mRNA" in replicates.library.depleted_in_term_name
# rna_species = "polyA depleted RNA"
# else
# rna_species = "total RNA"
elif a_file is not None:
if token == "{file.accession}":
return a_file['accession']
#elif token == "{output_type}":
# return a_file['output_type']
elif token == "{output_type_short_label}":
output_type = a_file['output_type']
return OUTPUT_TYPE_8CHARS.get(output_type, output_type)
elif token == "{replicate}":
rep_tag = a_file.get("rep_tag")
if rep_tag is not None:
while len(rep_tag) > 4:
if rep_tag[3] != '0':
break
rep_tag = rep_tag[0:3] + rep_tag[4:]
return rep_tag
rep_tech = a_file.get("rep_tech")
if rep_tech is not None:
return rep_tech.split('_')[0] # Should truncate tech_rep
rep_tech = self.rep_for_file(a_file)
return rep_tech.split('_')[0] # Should truncate tech_rep
elif token == "{replicate_number}":
rep_tag = a_file.get("rep_tag", a_file.get("rep_tech", self.rep_for_file(a_file)))
if not rep_tag.startswith("rep"):
return "0"
return rep_tag[3:].split('_')[0]
elif token == "{biological_replicate_number}":
rep_tech = a_file.get("rep_tech", self.rep_for_file(a_file))
if not rep_tech.startswith("rep"):
return "0"
return rep_tech[3:].split('_')[0]
elif token == "{technical_replicate_number}":
rep_tech = a_file.get("rep_tech", self.rep_for_file(a_file))
if not rep_tech.startswith("rep"):
return "0"
return rep_tech.split('_')[1]
elif token == "{rep_tech}":
return a_file.get("rep_tech", self.rep_for_file(a_file))
else:
val = self.lookup_embedded_token(token, a_file)
if val is not None and isinstance(val, str):
return val
return ""
else:
val = self.lookup_embedded_token(token, dataset)
if val is not None and isinstance(val, str):
return val
log.debug('Untranslated token: "%s"' % token)
return "unknown"
def convert_mask(self, mask, dataset=None, a_file=None):
'''Given a mask with one or more known {term_name}s, replaces with values.'''
working_on = mask
# dataset might not be self.dataset
if dataset is None:
dataset = self.dataset
chars = len(working_on)
while chars > 0:
beg_ix = working_on.find('{')
if beg_ix == -1:
break
end_ix = working_on.find('}')
if end_ix == -1:
break
term = self.lookup_token(working_on[beg_ix:end_ix+1], dataset, a_file=a_file)
new_mask = []
if beg_ix > 0:
new_mask = working_on[0:beg_ix]
new_mask += "%s%s" % (term, working_on[end_ix+1:])
chars = len(working_on[end_ix+1:])
working_on = ''.join(new_mask)
return working_on
def ucsc_single_composite_trackDb(self, vis_format, title):
'''Given a single vis_format (vis_dataset or vis_by_type dict, returns single UCSC trackDb composite text'''
if vis_format is None or len(vis_format) == 0:
return "# Empty composite for %s. It cannot be visualized at this time.\n" % title
blob = ""
# First the composite structure
blob += "track %s\n" % vis_format["name"]
blob += "compositeTrack on\n"
blob += "type bed 3\n"
for var in COMPOSITE_SETTINGS:
val = vis_format.get(var)
if val:
blob += "%s %s\n" % (var, val)
views = vis_format.get("view", [])
if len(views) > 0:
blob += "subGroup1 view %s" % views["title"]
for view_tag in views["group_order"]:
view_title = views["groups"][view_tag]["title"]
blob += " %s=%s" % (view_tag, sanitize.title(view_title))
blob += '\n'
dimA_checked = vis_format.get("dimensionAchecked", "all")
dimA_tag = ""
if dimA_checked == "first": # All will leave dimA_tag & dimA_checked empty, default to all on
dimA_tag = vis_format.get("dimensions", {}).get("dimA", "")
dimA_checked = None
subgroup_ix = 2
for group_tag in vis_format["group_order"]:
group = vis_format["groups"][group_tag]
blob += "subGroup%d %s %s" % (subgroup_ix, group_tag, sanitize.title(group["title"]))
subgroup_ix += 1
subgroup_order = None # group.get("group_order")
if subgroup_order is None or not isinstance(subgroup_order, list):
subgroup_order = sorted(group["groups"].keys())
for subgroup_tag in subgroup_order:
subgroup_title = group["groups"][subgroup_tag]["title"]
blob += " %s=%s" % (subgroup_tag, sanitize.title(subgroup_title))
if group_tag == dimA_tag and dimA_checked is None:
dimA_checked = subgroup_tag
blob += '\n'
# sortOrder
sort_order = vis_format.get("sortOrder")
if sort_order:
blob += "sortOrder"
for sort_tag in sort_order:
if title.startswith("ENCSR") and sort_tag == "EXP":
continue # Single exp composites do not need to sort on EMP
blob += " %s=+" % sort_tag
blob += '\n'
# dimensions
actual_group_tags = ["view"] # Not all groups will be used in composite, depending upon content
dimensions = vis_format.get("dimensions", {})
if dimensions:
pairs = ""
XY_skipped = []
XY_added = []
for dim_tag in sorted(dimensions.keys()):
group = vis_format["groups"].get(dimensions[dim_tag])
if group is None: # e.g. "Targets" may not exist
continue
if dimensions[dim_tag] != "REP":
if len(group.get("groups", {})) <= 1:
if dim_tag[-1] in ['X', 'Y']:
XY_skipped.append(dim_tag)
continue
elif dim_tag[-1] in ['X', 'Y']:
XY_added.append(dim_tag)
pairs += " %s=%s" % (dim_tag, dimensions[dim_tag])
actual_group_tags.append(dimensions[dim_tag])
# Getting too fancy for our own good:
# If one XY dimension has more than one member then we must add both X and Y
if len(XY_skipped) > 0 and len(XY_added) > 0:
for dim_tag in XY_skipped:
pairs += " %s=%s" % (dim_tag, dimensions[dim_tag])
actual_group_tags.append(dimensions[dim_tag])
if len(pairs) > 0:
blob += "dimensions%s\n" % pairs
# filterComposite
filter_composite = vis_format.get("filterComposite")
if filter_composite:
filterfish = ""
for filter_tag in sorted(filter_composite.keys()):
group = vis_format["groups"].get(filter_composite[filter_tag])
if group is None or len(group.get("groups", {})) <= 1: # e.g. "Targets" may not exist
continue
filterfish += " %s" % filter_tag
if filter_composite[filter_tag] == "one":
filterfish += "=one"
if len(filterfish) > 0:
blob += 'filterComposite%s\n' % filterfish
elif dimA_checked is not None:
blob += 'dimensionAchecked %s\n' % dimA_checked
blob += '\n'
# Now cycle through views
for view_tag in views["group_order"]:
view = views["groups"][view_tag]
tracks = view.get("tracks", [])
if len(tracks) == 0:
continue
blob += " track %s_%s_view\n" % (vis_format["name"], view["tag"])
blob += " parent %s on\n" % vis_format["name"]
blob += " view %s\n" % view["tag"]
for var in VIEW_SETTINGS: