-
Notifications
You must be signed in to change notification settings - Fork 13
/
fig.py
1062 lines (784 loc) · 46.3 KB
/
fig.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
import sys
import plotly.graph_objs as go
import numpy as np
import pandas as pd
import maths
import colors
import copy
from Complex import Complex
from config import json_config, coord_config
import io
import base64
#from dash_dict import *
# input_json_path = sys.argv[1]
def merge_dict(basedict, *extradict):
'''
this function updates basedict with extradict values, will apply to any nested values
e.g:
extradict = {'font': {'color': 'yellow'}}
basedict = {'font': {'color': 'black', size: 16}}
merge_dict(extradict, basedict):
{'font': {'color': 'yellow', size: 16}}
'''
for i in range(len(extradict)):
for key in extradict[i].keys():
if key not in basedict.keys():
basedict[key] = extradict[i][key]
else:
if not isinstance(basedict[key], dict):
basedict[key] = extradict[i][key]
else:
merge_dict(basedict[key], extradict[i][key])
return basedict
class Figure(Complex):
def __init__(self, *args, **kwargs):
# not able to read dash_dict twice for some reason
if 'dash_dict' in kwargs:
self.dash_dict = kwargs['dash_dict'].copy()
#print(self.dash_dict)
## a switch
self.config_dict = json_config.json2dict(self.dash_dict)
#print(self.config_dict)
#except Exception:
else:
self.config_dict = json_config.json2dict(kwargs['input_json_path'])
########################################################################
# try replacing all self.get_chr_info() with self.chr_info
self.chr_info = coord_config.chr_info(self.config_dict['Category']['ideogram']['patch']['file']['path'],
sep=self.config_dict['Category']['ideogram']['patch']['file']['sep'],
custom_label=self.config_dict['Category']['ideogram']['patch']['customoptions']['customlabel'],
custom_spacing=self.config_dict['Category']['ideogram']['patch']['customoptions']['customspacing'],
custom_color=self.config_dict['Category']['ideogram']['patch']['customoptions']['customcolor'],
)
########################################################################
self.ideogram_coord_config = self.get_ideogram_coord_config()
self.layout_general = self.config_dict['General']
categories = self.config_dict['Category']
keyList = []
for key in categories:
if key in ['cytoband', 'highlight', 'annotation']:
if 'file' not in categories[key]:
keyList.append(key)
for key in keyList:
categories.pop(key)
# if cytoband is used, ideogram patch fill is automatically disabled!
if 'cytoband' in categories:
categories['ideogram']['patch']['showfillcolor'] = False
###### for some reason annotation file path is not converted to io.StringIO format
self.categories = categories
#print('self.categories')
#print(self.categories)
#print('self.categories.keys()')
#print(self.categories.keys())
self.ideogram = self.categories['ideogram']
self.ideogram_patch = self.ideogram['patch']
#print(self.ideogram_patch)
self.ideogram_majortick = self.ideogram['majortick']
self.ideogram_minortick = self.ideogram['minortick']
self.ideogram_ticklabel = self.ideogram['ticklabel']
self.ideogram_radius_dict = self.ideogram_patch['radius']
self.show_chr_annotation = self.ideogram_patch['chrannotation']['show']
self.major_tick_radius_dict = self.ideogram_majortick['radius']
self.minor_tick_radius_dict = self.ideogram_minortick['radius']
self.tick_label_radius_dict = self.ideogram_ticklabel['radius']
self.SUM = self.get_ideogram_coord_config()['SUM']
self.degreerange = self.ideogram_patch['degreerange']
self.chr_color_dict = self.chr_info['chr_color_dict']
self.chr_label_dict = self.chr_info['chr_label_dict']
############################################################
#replace self.get_data_array_dict() & self.read_data() with ONE self.get_data attribute!!
get_data_array_dict_ = {}
get_read_data_ = {}
for key in self.categories:
if key == 'ideogram':
pass
else:
try:
get_data_array_dict_[key] = self.get_data_array_dict(key)
except Exception:
pass
self.get_data = get_data_array_dict_
#print('test self.get_data')
#print(self.get_data)
#print('done testing')
#print('test self.get_data_array_dict_')
#print(self.get_data_array_dict_)
#print('self.get_data_array_dict_ scatter')
#print(self.get_data_array_dict_['scatter'])
#print('end')
def generate_dash_dict(self):
return self.config_dict
def np_list_concat(self, x):
if isinstance(x, list):
try:
return np.concatenate(x)
except ValueError:
return np.array(x)
elif isinstance(x, np.ndarray):
return x
else:
raise ValueError('input must be an ndarray or a list')
def get_read_data(self, key):
items = self.categories[key]
sortindices = self.get_data_array_sortindex(key)
def get_single_data(item, key, sortindex=None):
assert isinstance(item, dict)
if item['file']['header'] in ['None', None, 'none']:
unsorted_data = coord_config.read_data(item['file']['path'],
key,
#self.get_chr_info(),
self.chr_info,
sep=item['file']['sep'],
header=None
)
else:
unsorted_data = coord_config.read_data(item['file']['path'],
key,
#self.get_chr_info(),
self.chr_info,
sep=item['file']['sep']
)
if item['sortbycolor']:
## ONGOING
assert sortindex is not None
return unsorted_data[sortindex]
else:
return unsorted_data
if isinstance(items, dict):
return get_single_data(items, key, sortindex=sortindices)
elif isinstance(items, list):
return [*map(lambda x, y: get_single_data(x, key, sortindex=y), items, sortindices)]
def get_chr_info(self):
#chr_info_file = self.config_dict['Category']['ideogram']['patch']['file']
#custom_options = self.config_dict['Category']['ideogram']['patch']['customoptions']
chr_info_dict = coord_config.chr_info(self.config_dict['Category']['ideogram']['patch']['file']['path'],
sep=self.config_dict['Category']['ideogram']['patch']['file']['sep'],
custom_label=self.config_dict['Category']['ideogram']['patch']['customoptions']['customlabel'],
custom_spacing=self.config_dict['Category']['ideogram']['patch']['customoptions']['customspacing'],
custom_color=self.config_dict['Category']['ideogram']['patch']['customoptions']['customcolor'],
)
return chr_info_dict
def get_ideogram_coord_config(self):
ideogram_coord_config = coord_config.ideogram_coord_config(
#self.get_chr_info(),
self.chr_info,
npoints=self.config_dict['Category']['ideogram']['patch']['npoints'],
show_major_tick=self.config_dict['Category']['ideogram']['majortick']['show'],
major_tick_spacing=self.config_dict['Category']['ideogram']['majortick']['spacing'],
show_minor_tick=self.config_dict['Category']['ideogram']['minortick']['show'],
minor_tick_spacing=self.config_dict['Category']['ideogram']['minortick']['spacing'],
show_tick_label=self.config_dict['Category']['ideogram']['ticklabel']['show'],
tick_label_spacing=self.config_dict['Category']['ideogram']['ticklabel']['spacing']
)
return ideogram_coord_config
## self.ideogram_complex() and self.ring_complex() is inherited
def get_ideogram_theta(self):
return self.ideogram_theta_list(self.ideogram_coord_config, self.SUM, degreerange=self.degreerange)
def get_ideogram_complex(self):
return self.ideogram_complex(self.ideogram_coord_config, self.SUM, self.degreerange, ideogram_radius_dict=self.ideogram_radius_dict)
#def get_ideogram_shapes(self):
#return self.ideogram_path(self.get_ideogram_complex())
def get_ring_complex(self):
if isinstance(self.categories['ring'], dict):
return self.ideogram_complex(self.ideogram_coord_config, self.SUM, degreerange=self.degreerange, ideogram_radius_dict=self.categories['ring']['radius'])
elif isinstance(self.categories['ring'], list):
return [*map(lambda x: self.ideogram_complex(self.ideogram_coord_config, self.SUM, degreerange=self.degreerange, ideogram_radius_dict=x['radius']), self.categories['ring'])]
def get_ring_paths_dict(self):
def single_ring_dict(path, ring_dict):
# ring data can only have one background color! therefore I join them
# item = self.categories['ring']
if isinstance(path, list):
path = self.pathjoin(path)
path_dict=dict(path=path)
path_dict.update(ring_dict['layout'])
return path_dict
if isinstance(self.categories['ring'], dict):
path = self.ideogram_path(self.get_ring_complex())
path_dict =[single_ring_dict(path, self.categories['ring'])]
elif isinstance(self.categories['ring'], list):
path = [*map(lambda x: self.ideogram_path(x), self.get_ring_complex())]
path_dict = [*map(lambda x, y: single_ring_dict(x, y), path, self.categories['ring'])]
return path_dict
def get_major_tick_path(self):
major_tick_accum_coord_list = self.ideogram_coord_config['major_tick_accum_coord_list']
major_tick_theta = self.ideogram_tick_theta_list(self.ideogram_coord_config, major_tick_accum_coord_list, SUM=self.SUM, degreerange=self.degreerange)
major_tick_complex = self.tick_complex(major_tick_theta, tick_radius_dict=self.major_tick_radius_dict)
return self.tick_path(major_tick_complex)
def get_minor_tick_path(self):
minor_tick_accum_coord_list = self.ideogram_coord_config['minor_tick_accum_coord_list']
minor_tick_theta = self.ideogram_tick_theta_list(self.ideogram_coord_config, minor_tick_accum_coord_list, SUM=self.SUM, degreerange=self.degreerange)
minor_tick_complex = self.tick_complex(minor_tick_theta, tick_radius_dict=self.minor_tick_radius_dict)
return self.tick_path(minor_tick_complex)
def get_ideogram_chrannot_theta(self):
return self.ideogram_chrannot_theta(self.ideogram_coord_config, self.SUM, degreerange=self.degreerange)
def get_ideogram_chrannot_complex(self):
return self.ideogram_chrannot_complex(self.SUM,
degreerange=self.degreerange,
chr_annotation_radius_dict=self.ideogram_patch['chrannotation']['radius']
)
def get_tick_label_complex(self):
tick_label_theta = self.ideogram_tick_label_theta_list(self.ideogram_coord_config, self.SUM, degreerange=self.degreerange)
return self.tick_label_complex(tick_label_theta, tick_label_radius_dict=self.tick_label_radius_dict)
def pathjoin(self, path_list):
'''this function will join any path_string_list into a single path_string, useful when fillcolor is the same'''
return " ".join(path_list)
def get_data_array_dict(self, key):
assert key in self.categories
items = self.categories[key]
#print('key is {}'.format(key))
#print(items)
if key == 'ideogram':
raise ValueError('ideogram information should not be parsed in get_data_array()')
else:
def single_data_array(key, item):
if 'colorcolumn' not in item.keys():
item['colorcolumn'] = None
if 'sortbycolor' not in item.keys():
item['sortbycolor'] = False
if item['file']['header'] in ['None', None, 'none']:
return coord_config.data_array(item['file']['path'], key,
#self.get_chr_info(),
self.chr_info,
sep=item['file']['sep'],
header=None,
colorcolumn=item['colorcolumn'],
sortbycolor=item['sortbycolor']
)
else:
return coord_config.data_array(item['file']['path'], key,
#self.get_chr_info(),
self.chr_info,
sep=item['file']['sep'],
colorcolumn=item['colorcolumn'],
sortbycolor=item['sortbycolor']
)
if isinstance(items, dict):
return single_data_array(key, items)
elif isinstance(items, list):
try:
return [*map(lambda x: single_data_array(key, x), items)]
except Exception:
print(key)
def get_data_array(self, key):
#if self.get_data_array_dict(key) is None:
if self.get_data[key] is None:
pass
else:
#if not isinstance(self.get_data_array_dict(key), list):
if not isinstance(self.get_data[key], list):
#return self.get_data_array_dict(key)['data_array']
return self.get_data[key]['data_array']
else:
#return [*map(lambda x: x['data_array'], self.get_data_array_dict(key))]
return [*map(lambda x: x['data_array'], self.get_data[key])]
def get_data_array_sortindex(self, key):
# only used when sortbycolor is True! in other cases its just range(len(data_array))
#if not isinstance(self.get_data_array_dict(key), list):
if not isinstance(self.get_data[key], list):
#return self.get_data_array_dict(key)['sortindex']
return self.get_data[key]['sortindex']
else:
#return [*map(lambda x: x['sortindex'], self.get_data_array_dict(key))]
return [*map(lambda x:x['sortindex'], self.get_data[key])]
def get_data_complexes(self, key, return_path=True):
assert key in self.categories
data_array = self.get_data_array(key)
items = self.categories[key]
#print('key is {}'.format(key))
#print(key)
#print(data_array)
def single_data_complex(data_array, key, item):
if key != 'highlight':
if key == 'cytoband':
item['radius'] = self.ideogram_radius_dict
elif key == 'annotation' and item['customradius']:
try:
assert isinstance(item['radiuscolumn'], int)
except AssertionError:
print ('Please enter a valid radiuscolumn under annotation')
try:
radiuscolumn = item['radiuscolumn']
except IndexError:
print ('the column you entered is out of bound, notice that column starts with 0, not 1 ')
try:
data_array[:,radiuscolumn].astype('float')
## DEBUG, the below should be ValueError, changing to Exception temporarily
except Exception:
print (radiuscolumn)
print (data_array[:,radiuscolumn])
print ('Please make sure to enter numeric value for radius column')
item['radius'] = {"R": data_array[:,radiuscolumn]}
radius_dict = item['radius']
else:
radius_dict = {"R0": data_array[:,item['R0column']], "R1": data_array[:,item['R1column']]}
if key == 'annotation':
data_complex = self.data_complex(self.ideogram_coord_config,
data_array, key, radius_dict, self.SUM,
degreerange=self.degreerange,
custom_offset_degree=item['customoffsetdegree']
)
else:
data_complex = self.data_complex(self.ideogram_coord_config,
data_array, key, radius_dict, self.SUM,
degreerange=self.degreerange,
return_path=return_path
)
return data_complex
if isinstance(items, dict):
return single_data_complex(data_array, key, items)
elif isinstance(items, list):
#print('single_data_complex data array')
#print(data_array)
#print('single_data_complex items')
#print(items)
try:
return [*map(lambda x, y: single_data_complex(x, key, y), data_array, items)]
except Exception:
print('debugging data_array')
print(data_array) # got empty
print('debugging items')
print(items)
def get_hovertext(self, key):
assert key in ['histogram', 'line', 'area','scatter', 'tile', 'heatmap', 'link', 'ribbon', 'twistedribbon']
if not isinstance(self.get_data[key], list):
hovertextformat = self.categories[key]['hovertextformat']
#a = self.get_read_data(key)
a = self.get_data[key]['read_data']
hvtext = []
if key not in ['link', 'ribbon', 'twistedribbon']:
assert a.shape[1] >= 3
if key in ['histogram', 'tile', 'heatmap']:
list_count = [*map(lambda x: len(x), self.get_data_complexes(key))]
for i in range(len(a)):
k = 0
while k < list_count[i]:
k += 1
hvtext.append(eval(hovertextformat))
else:
for i in range(len(a)):
hvtext.append(eval(hovertextformat))
else:
# for link, ribbon and twistedribbon hovertext is a list of two elememnt
assert a.shape[1] >= 6
for i in range(len(a)):
hvtext.append(eval(hovertextformat[0]))
hvtext.append(eval(hovertextformat[0]))
hvtext.append(eval(hovertextformat[1]))
hvtext.append(eval(hovertextformat[1]))
else:
hvtext = []
try:
data_array_list = [*map(lambda t:t['read_data'], self.get_data[key])]
except Exception:
print('debugging...')
#print(self.get_data[key])
print('end of debugging...')
for j in range(len(data_array_list)):
hovertextformat = self.categories[key][j]['hovertextformat']
hvtext.append([])
a = data_array_list[j]
if key not in ['link', 'ribbon', 'twistedribbon']:
assert a.shape[1] >= 3
if key in ['histogram', 'tile', 'heatmap']:
list_count = [*map(lambda x: len(x), self.get_data_complexes(key)[j])]
for i in range(len(a)):
k = 0
while k < list_count[i]:
k += 1
hvtext[j].append(eval(hovertextformat))
else:
for i in range(len(a)):
hvtext[j].append(eval(hovertextformat))
else:
assert a.shape[1] >= 6
for i in range(len(a)):
hvtext[j].append(eval(hovertextformat[0]))
hvtext[j].append(eval(hovertextformat[0]))
hvtext[j].append(eval(hovertextformat[1]))
hvtext[j].append(eval(hovertextformat[1]))
return hvtext
def get_traces(self, key):
## always return a list, this makes concatenation easier
# for line plot, there shouldn't be sortbycolor
items = self.categories[key]
complexes = self.get_data_complexes(key, return_path=False)
data_arrays = self.get_data_array(key)
hovertexts = self.get_hovertext(key)
def single_trace(key, Complex, item, data_array, hovertext):
assert key not in ['cytoband', 'ideogram', 'ring', 'annotation', 'highlight', 'connector']
# For scatter plot the complex is an ndarray, for lines it would be a list of ndarray separated by chromosomes
# for other nonvisible plots, they can be concatenated into one ndarray
assert isinstance(item, dict)
# DEBUGGING
if key != 'line':
if isinstance(Complex, list):
Complex = np.concatenate(Complex)
if key == 'line':
# the only time when Complex is a list of ndarray
trace = []
index = np.cumsum([0]+[*map(lambda x: len(x), Complex)])
def divide(l, index):
#this function creates a generator object for hovertext so I know how many hovertext element to take for each chromosome
for n in range(len(index)-1):
yield l[index[n]:index[n+1]]
hovertext_generator = divide(hovertext, index)
if item['colorcolumn'] in [None, 'None']:
for i in range(len(Complex)):
trace.append(go.Scatter(x=Complex[i].real,
y=Complex[i].imag,
text=next(hovertext_generator),
)
)
trace[-1].update(item['trace'])
elif item['colorcolumn'] == 'ideogram':
chr_label = data_array[:,0]
#color = self.get_chr_info()['chr_fillcolor']
color = self.chr_info['chr_fillcolor']
tmp_trace = item['trace'].copy()
for i in range(len(Complex)):
trace.append(go.Scatter(x=Complex[i].real,
y=Complex[i].imag,
text=next(hovertext_generator),
)
)
tmp_trace['line']['color'] = color[i]
tmp_trace['marker']['color'] = color[i]
trace[-1].update(tmp_trace)
else:
if Complex.ndim != 1:
Complex = Complex.ravel()
if key in ['link', 'ribbon', 'twistedribbon']:
index = []
for i in range(len(Complex)):
if i%6 in [0,1,4,5]:
index.append(i)
Complex = Complex[index]
trace = go.Scatter(x=Complex.real,
y=Complex.imag,
text=hovertext
)
trace.update(item['trace'])
if key == 'scatter':
#if 'color' not in item['trace']['marker']:
chr_label = data_array[:,0]
if item['colorcolumn'] == 'ideogram':
# follows ideogram color
color = [*map(lambda x: self.chr_color_dict[x], chr_label)]
elif isinstance(item['colorcolumn'], int):
n = item['colorcolumn']
assert isinstance(n, int)
color = colors.to_rgb(data_array[:,n])
else:
### ONGOING
#assert item['colorcolumn'] in [None, 'None']
color = item['trace']['marker']['color']
trace['marker'].update(color=color)
return trace
if isinstance(items, dict):
trace = single_trace(key, complexes, items, data_arrays, hovertexts)
if not isinstance(trace, list):
trace = [trace]
return trace
elif isinstance(items, list):
return [*map(lambda w, x, y, z: single_trace(key, w, x, y, z), complexes, items, data_arrays, hovertexts)]
def trace(self):
# aggregate all get_traces element into one trace, list variable
trace = []
for key in self.categories.keys():
if key not in ['cytoband', 'ideogram', 'ring', 'annotation', 'highlight', 'connector']:
trace += self.get_traces(key)
return trace
def get_paths_dict(self, key):
# will join path_list into a path string if sortbycolor
### deal with:
# histogram, ribbon, twistedribbon, if fillcolor is true, then linecolor==fillcolor!
# cytoband, heatmap (sortbycolor=True)
# tile, link (no fillcolor), color indicates to linecolor
assert key not in ['scatter', 'annotation', 'line']
items = self.categories[key]
data_arrays = self.get_data_array(key)
data_complexes = self.get_data_complexes(key)
def single_path(key, data_array, data_complex, item):
if key in ['ribbon', 'twistedribbon']:
interval_theta_array_0 = maths.to_theta(data_array[:,1:3], self.SUM, degreerange=self.degreerange)
interval_theta_array_1 = maths.to_theta(data_array[:,4:6], self.SUM, degreerange=self.degreerange)
else:
interval_theta_array_0, interval_theta_array_1 = None, None
if key == 'highlight':
path_list = self.data_path(self.ideogram_coord_config,
key, data_complex, self.SUM, degreerange=self.degreerange,
radius_dict={"R0": item['R0column'], "R1": item['R1column']},
interval_theta_array_0=interval_theta_array_0,
interval_theta_array_1=interval_theta_array_1)
else:
if key == 'cytoband':
item['radius'] = self.ideogram_radius_dict
path_list = self.data_path(self.ideogram_coord_config,
key, data_complex, self.SUM, degreerange=self.degreerange,
radius_dict=item['radius'],
interval_theta_array_0=interval_theta_array_0,
interval_theta_array_1=interval_theta_array_1)
if item['colorcolumn'] in [None, 'None']:
path = " ".join(path_list)
paths_dict = dict(path=path)
paths_dict.update(item['layout'])
#elif isinstance(item['colorcolumn'], int):
else:
# custom line color only, and no fill color: link, tile
# custom fill color only: all others
paths_dict = []
if item['colorcolumn'] == 'ideogram':
if not key == 'area':
color = [*map(lambda x: self.chr_color_dict[x], data_array[:,0])]
else:
#color = self.get_chr_info()['chr_fillcolor']
color = self.chr_info['chr_fillcolor']
elif isinstance(item['colorcolumn'], int):
n = item['colorcolumn']
color = data_array[:,n]
if key == 'heatmap':
color = maths.val2heatmap(color, palatte_dict=item['palatte'])
if key == 'highlight':
o = item['opacitycolumn']
opacity = data_array[:,o]
for i in range(len(color)):
paths_dict.append(dict(path=path_list[i],
fillcolor=color[i],
opacity=opacity[i]
)
)
paths_dict[i].update(item['layout'])
elif key in ['heatmap', 'cytoband', 'ribbon', 'twistedribbon', 'tile', 'link', 'area', 'histogram']:
for i in range(len(path_list)):
paths_dict.append(dict(path=path_list[i]))
paths_dict[i].update(copy.deepcopy(item['layout']))
if key in ['tile', 'link']:
paths_dict[i]['line']['color'] = color[i]
else:
paths_dict[i]['line']['color'] = color[i]
paths_dict[i]['fillcolor'] = color[i]
return paths_dict
if isinstance(items, dict):
if isinstance(single_path(key, data_arrays, data_complexes, items), dict):
return [single_path(key, data_arrays, data_complexes, items)]
else:
return single_path(key, data_arrays, data_complexes, items)
elif isinstance(items, list):
## ONGOING
rtrn = [*map(lambda x, y, z: single_path(key, x, y, z), data_arrays, data_complexes, items)]
return [*map(lambda a: a if isinstance(a,list) else [a], rtrn)]
#return [*map(lambda x, y, z: single_path(key, x, y, z), data_arrays, data_complexes, items)]
else:
raise KeyError('{} file does not exist!'.format(key))
def get_annotations_dict(self):
'''layout['annotations'] can only append one text annotation at a time!! be careful'''
# please make sure you only have one annotation file!
assert 'annotation' in self.categories.keys()
try:
assert isinstance(self.categories['annotation'], dict)
except AssertionError:
print ('Please use one and only one annotation file')
text_complex = self.get_data_complexes('annotation')
text_array = self.get_data_array('annotation')[:,2]
text_theta = maths.to_theta(self.get_data_array('annotation')[:,1], self.SUM, degreerange=self.degreerange)
textangle=self.angleconvert(text_theta, angleoffset=self.categories['annotation']['textangle']['angleoffset'],
anglelimit=self.categories['annotation']['textangle']['anglelimit'])
if self.categories['annotation']['customoffsetdegree']:
textangle += self.get_data_array('annotation')[:,3]
if self.categories['annotation']['fonttype'] == 'bold':
if len(text_array) == 1:
text = '<b>{}</b>'.format(text_array)
else:
text = [*map(lambda x: '<b>{}</b>'.format(x), text_array)]
elif self.categories['annotation']['fonttype'] == 'italic':
if len(text_array) == 1:
text = '<i>{}</i>'.format(text_array)
else:
text = [*map(lambda x: '<i>{}</i>'.format(x), text_array)]
elif self.categories['annotation']['fonttype'] in ['bold+italic', 'italic+bold']:
if len(text_array) == 1:
text = '<b><i>{}</i></b>'.format(text_array)
else:
text = [*map(lambda x: '<b><i>{}</i></b>'.format(x), text_array)]
else:
if len(text_array) == 1:
text = '{}'.format(text_array)
else:
text = [*map(lambda x: '{}'.format(x), text_array)]
if len(text_array) == 1:
annotation_dict = dict(x=text_complex.real, y=text_complex.imag,
text=text, textangle=textangle)
annotation_dict.update(copy.deepcopy(self.categories['annotation']['layout']))
return [annotation_dict]
else:
if not self.categories['annotation']['customcolor']:
annotation_dict_list = [*map(lambda a,b,c: merge_dict(dict(x=a.real, y=a.imag, text=b, textangle=c),
copy.deepcopy(self.categories['annotation']['layout'])),
text_complex, text, textangle)]
else:
assert isinstance(self.categories['annotation']['colorcolumn'], int)
n = self.categories['annotation']['colorcolumn']
assert n <= self.get_data_array('annotation').shape[1]-1
colors = self.get_data_array('annotation')[:,n].tolist()
annotation_dict_list = [*map(lambda a,b,c,d: merge_dict(dict(x=a.real, y=a.imag, text=b, textangle=c),
copy.deepcopy(self.categories['annotation']['layout']),
dict(font=dict(color=d))
),
text_complex, text, textangle, colors)]
return annotation_dict_list
def angleconvert(self, theta, angleoffset=-90, anglelimit=360, custom_offset_degree=0):
# theta could be an ndarray or a list of ndarray
# returns a processed degree data based on anglelimit
# anglelimit is the degree limit before applying angleoffset and custom_offset!
# custom_offset_degree is a 1D ndarray of the same shape as theta
constant = 180/np.pi
assert isinstance(angleoffset, (int, float))
assert isinstance(anglelimit, (int, float))
if not isinstance(theta, list):
degree = theta*constant
for i in range(len(degree)):
while degree[i] >= anglelimit:
degree[i] -= anglelimit
degree += angleoffset + custom_offset_degree
return degree
else:
assert isinstance(custom_offset_degree, list)
assert len(theta) == len(custom_offset_degree)
degree = [*map(lambda x: x*constant), theta]
for i in range(len(degree)):
for j in range(len(degree[i])):
while degree[i][j] >= anglelimit:
degree[i][j] -= anglelimit
degree[i] += angleoffset + custom_offset_degree[i]
return degree
def layout(self):
## new version of plotly says layout['shapes'], ['annotations'] is a tuple, can't be used with list append
## I'm trying to add a temporary layout_shapes list variable collecting everything before assigning to layout['shapes']
layout = go.Layout(self.layout_general)
layout_shapes = []
layout_annotations = []
if self.ideogram_patch['show']:
if not self.ideogram_patch['showfillcolor']:
# if no show fillcolor, there is no need to separate pathstring into list, hense the join
# seems like for dictionary update, the dict variable needs to be defined first
ideogram_pathstring = self.pathjoin(self.ideogram_path(self.get_ideogram_complex()))
layout_dict = self.ideogram_patch['layout']
layout_dict.update(dict(path=ideogram_pathstring))
layout_shapes.append(layout_dict)
else:
ideogram_path_list = self.ideogram_path(self.get_ideogram_complex())
for i in range(len(ideogram_path_list)):
layout_shapes.append(dict(path=ideogram_path_list[i],
#fillcolor=self.get_chr_info()['chr_fillcolor'][i]
fillcolor=self.chr_info['chr_fillcolor'][i]
))
layout_shapes[i].update(self.ideogram_patch['layout'])
if self.ideogram_patch['chrannotation']['show']:
chrannot_theta = self.get_ideogram_chrannot_theta()
chrannot_theta = self.np_list_concat(chrannot_theta)
chrannot_complex = maths.to_complex(chrannot_theta, self.ideogram_patch['chrannotation']['radius']['R'])
chrannot_complex = self.np_list_concat(chrannot_complex)
chrannot_angleoffset = self.ideogram_patch['chrannotation']['textangle']['angleoffset']
chrannot_anglelimit = self.ideogram_patch['chrannotation']['textangle']['anglelimit']
if self.ideogram_patch['chrannotation']['fonttype'] == 'bold':
chrannot_text = [*map(lambda x: '<b>{}</b>'.format(x),
#self.get_chr_info()['chr_label']
self.chr_info['chr_label']
)]
elif self.ideogram_patch['chrannotation']['fonttype'] == 'italic':
chrannot_text = [*map(lambda x: '<i>{}</i>'.format(x),
#self.get_chr_info()['chr_label']
self.chr_info['chr_label']
)]
elif self.ideogram_patch['chrannotation']['fonttype'] in ['bold+italic', 'italic+bold']:
chrannot_text = [*map(lambda x: '<b><i>{}</i></b>'.format(x),
#self.get_chr_info()['chr_label']
self.chr_info['chr_label']
)]
else:
chrannot_text = [*map(lambda x: '{}'.format(x),
#self.get_chr_info()['chr_label']
self.chr_info['chr_label']
)]
textangle = self.angleconvert(chrannot_theta, angleoffset=chrannot_angleoffset, anglelimit=chrannot_anglelimit)
for i in range(len(chrannot_complex)):
layout_annotations.append(dict(x=chrannot_complex[i].real,
y=chrannot_complex[i].imag,
text=chrannot_text[i],
textangle=textangle[i]
)
)
layout_annotations[i].update(self.ideogram_patch['chrannotation']['layout'])
if self.ideogram_majortick['show']:
layout_shapes.append(dict(path=self.get_major_tick_path()))
layout_shapes[-1].update(self.ideogram_majortick['layout'])
if self.ideogram_minortick['show']:
layout_shapes.append(dict(path=self.get_minor_tick_path()))
layout_shapes[-1].update(self.ideogram_minortick['layout'])
if self.ideogram_ticklabel['show']:
ticklabel_text = self.get_ideogram_coord_config()['tick_label_non_accum_list']
if isinstance(ticklabel_text, list):
ticklabel_text = np.concatenate(ticklabel_text)
ticklabel_coord = self.np_list_concat(self.get_ideogram_coord_config()['tick_label_accum_coord_list'])
ticklabel_theta = maths.to_theta(ticklabel_coord, self.SUM, degreerange=self.degreerange)
ticklabel_angle = self.angleconvert(ticklabel_theta, angleoffset=self.ideogram_ticklabel['textangle']['angleoffset'], anglelimit=self.ideogram_ticklabel['textangle']['anglelimit'])
ticklabel_complex = np.concatenate(self.get_tick_label_complex())
if self.ideogram_ticklabel['textformat'] == 'Kb':
ticklabel_text = [*map(lambda x: '{} Kb'.format(x//1000), ticklabel_text)]
elif self.ideogram_ticklabel['textformat'] == 'Mb':
ticklabel_text = [*map(lambda x: '{} Mb'.format(x//1000000), ticklabel_text)]
elif self.ideogram_ticklabel['textformat'] == 'Gb':
ticklabel_text = [*map(lambda x: '{} Gb'.format(x//1000000000), ticklabel_text)]
else:
raise ValueError('acceptable ideogram ticklabel textformats are: Kb & Mb & Gb')
for i in range(len(ticklabel_complex)):
layout_annotations.append(dict(x=ticklabel_complex[i].real,
y=ticklabel_complex[i].imag,
text=ticklabel_text[i],
textangle=ticklabel_angle[i]
)
)
layout_annotations[-1].update(self.ideogram_ticklabel['layout'])