Repository navigation
Expand file tree
/
Copy pathmutation_scatter_plot.py
More file actions
executable file
·1737 lines (1518 loc) · 118 KB
/
Copy pathmutation_scatter_plot.py
File metadata and controls
executable file
·1737 lines (1518 loc) · 118 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#! /usr/bin/env python3
# This work © 2025 by Jiří Zahradník and Martin Mokrejš
# (First Medical Faculty - Charles University in Prague) is licensed under
# Creative Commons Attribution 4.0 International. To view a copy of this
# license, visit https://creativecommons.org/licenses/by/4.0/
"""This program can be used to render figures from input TSV files using
Matplotlib and Bokeh. The figures show all amino acid residues or their
underlying codons in a protein-coding region per each position. It counts
naturally from 1, not from zero like python does internally.
Matplotlib provides PNG, JPG, PDF and interactive outputs whereas Bokeh
provides JSON and HTML+javascript outputs providing similar interactivity
upon mouse hover().
If the running python instance and its Matplotlib has access to an X11 or
Wayland screen or other renderer it runs an interactive window with the
figure and one can use computer mouse to hover() above the circles in the
scatter plot. It shows a bubble-like pop-up legend of the particular data
item but also, the script prints out on STDOUT of the command line terminal
the underlying Pandas dataframe lines for the amino acid residue and its
codon.
It can be run either in codon mode or in amino acid mode, default display
thresholds differ for these.
To respect reading frame calculate_codon_frequencies.py follows reference
sequence and parses always 3 nucleotides at once from the ALN input file.
If there was a gap (padding) character '-' if picks an extra character from
the input until it has 3 nucleotides. Then it calculates frequencies for
all possible codons. The results are stored in a TAB-separated TSV file for
easy post-processing by mutation_scatter_plot.py which on-the-fly discards
codons containing unknown (N) nucleotides using python Pandas library and
finally draws interactive figures using Matplotlib and Bokeh graphical
libraries.
To color the figures mutation_scatter_plot.py uses the widely used BLOSUM62
matrix from
https://www.ncbi.nlm.nih.gov/IEB/ToolBox/C_DOC/lxr/source/data/BLOSUM62 to
discern evolutionarily conservative amino acid changes from those more
drastic. For each amino acid replacement pair there is a value in the matrix.
Notably, the values are not centered around zero. Here is an overview:
BLOSUM45: [-5, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12] Range spans 18 values but we need 25 for centering.
BLOSUM50: [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 13] Range spans 19 values but we need 27 for centering.
BLOSUM62: [-4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9] Range spans 14 values but we need 19 for centering.
BLOSUM80: [-6, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9] Range spans 16 values but we need 19 for centering.
BLOSUM90: [-6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 5, 6, 7, 8, 9] Range spans 16 values but we need 19 for centering.
Colormaps
We prefer either discerning colormaps of two colors separated by some narrow
band of a color in the middle (for example represented by gray color in the
"coolwarm_r" color palette).
The color palette "coolwarm_r" visible at https://i.sstatic.net/cmk1J.png is
used for drawing ranges from red to blue (in dark red should be rather
pronounced change while in dark blue should be functionally similar amino
acid change).
Users can discriminate about 3 colors only. That is not much but the figures
are easy to interpret.
Red to Blue color palettes (practically 3 to 2 colors discernible):
cool_r (practically almost 3 colors discernible) > cet_CET_C4 > coolwarm_r (practically 2 to 3 colors discernible) > cet_diverging_bwr_20_95_c54_r > seismic_r > cet_CET_D1A_r
Red to Green but diverging around zero:
Carbone42_r = SCook18_r (practically 5 colors discernible) > Carbone17_r > cet_rainbow_bgyr_10_90_c83_r ~= cet_rainbow4_r ~= cet_CET_R4_r > cet_rainbow_r
Red via narrow Green to Blue (practically 3 colors discernible):
LangRainbow12_r >> cmc.roma > cet_isoluminant_cgo_70_c39_r > cet_isoluminant_cgo_80_c38_r ~ cet_isolum_r
Red via Orange to Green:
Wild25_r (practically 4 to 5 colors discernible) > turbo_r > cet_rainbow_bgyr_35_85_c72_r > cet_rainbow_bgyr_35_85_c73_r
Blue to Orange (practically 3 colors discernible):
cet_rainbow_bgyrm_35_85_c71 ~ cet_rainbow_bgyr_35_85_c72 ~= cet_rainbow_bgyr_35_85_c73 ~= cet_rainbow
Violet to Green (practically 3 colors discernible):
cet_gouldian ~ cet_CET_L20 > cet_linear_kbgoy_20_95_c57 > cet_linear_kbgyw_10_98_c63 > cet_linear_bgyw_15_100_c68 > cet_linear_bgyw_15_100_c67 > cet_kbgyw > cet_linear_bgy_10_95_c74 > cet_CET_L9 ~ cet_CET_L16
Blue to Green (practically 3 to 2 colors discernible):
cet_linear_bgyw_20_98_c66 > cet_bgy > cmc.bukavu (is a bit yellow or brown) > cet_isoluminant_cgo_70_c39 > cet_isoluminant_cgo_80_c38 > cmc.bamako (practically 2 colors discernible)
Color Vision Deficiency:
Somewhat warm Violet to Blue (practically 3 to 4 colors discernible):
cet_linear_tritanopic_krjcw_5_95_c24
Somewhat colder Violet to Blue BUT values around zero have too intense color, almost like when at the right end:
cet_linear_tritanopic_kcw_5_95_c22 > cet_linear_protanopic_deuteranopic_kbw_5_98_c40 > cet_linear_protanopic_deuteranopic_kbw_5_95_c34
Somewhat warm Blue to Orange, better than cet_linear_protanopic_deuteranopic_kbjyw_5_95_c25 and cet_linear_protanopic_deuteranopic_kyw_5_95_c49 but suffers similar problem around zero value:
cmc.batlow
Somewhat warm Violet to Brown BUT values around zero have too intense color, almost like when at the right end:
cet_linear_protanopic_deuteranopic_kbjyw_5_95_c25 > cet_linear_protanopic_deuteranopic_kyw_5_95_c49
Blue to Brown (practically 2 colors discernible):
cet_diverging_linear_bjy_30_90_c45 > cet_diverging_linear_protanopic_deuteranopic_bjy_57_89_c34
Blue to Yellow (practically 3 colors discernible):
cet_CET_R4 > HomeyerRainbow
Single-color (practically 2 colors discernible):
cet_linear_blue_5_95_c73
Green (practically 2 colors discernible):
cet_linear_kgy_5_95_c69 ~ cet_linear_green_5_95_c69
Getting out the most from the figures
If one is after discrimination of different colorings in the figure, then several
colormaps performed well and allowed 5 or even 7 colors to be identified from the
datapoints in our suboptimal testcases (having probably just 7 different data values
with narrow spacing while rest of the space unoccupied).
cet_glasbey_Hv (practically 7 colors discernible) > cet_glasbey_dark_r (practically 6 colors discernible, somewhat light) ~ cet_glasbey_bw_minc_20_maxl_70_r (practically 6 colors discernible) > cet_glasbey_bw_minc_20_r (practically 5 colors discernible)
In default (codon) mode pale green is used to show synonymous changes.
Unfortunately, colors for values around zero are somewhat light blue and
they might appear to some readers as almost gray. Moreover, for some amino
acid changes defined in the BLOSUM62 matrix, the worst (drastic change)
value is e.g. -2 for T change to either of G, H, F, W or Y while for some
other it is -4 (W change to N, D, F or V).
Therefore, one cannot directly compare intensity of the (red) color of
multiple changes because their lowest possible minimum is just different
for each original amino acid. Still we find the color-coding of changes
helpful though not ideal.
The program mutation_scatter_plot.py developed to render the figures can
display either amino acid changes or codon changes in a single run, no both.
To omit less abundant changes from rendering there is a minimal threshold
option available.
Please cite our article if you use our data or software in your work:
Shoshany A., Tian R., Padilla-Blanco M., Hruška A., Baxova K., Zoler E., Mokrejš M., Schreiber G., Zahradník J. (submitted) In Vitro and Viral Evolution Convergence Reveal the Selective Pressures Driving Omicron Emergence. [bioRxiv](https://www.biorxiv.org/content/10.1101/2025.04.23.650148v1)
Other approaches
A completely different approach to display a few mutations is taken by:
Mutplot: An easy-to-use online tool for plotting complex mutation data with flexibility
https://doi.org/10.1371%2Fjournal.pone.0215838
Lollipops in the Clinic: Information Dense Mutation Plots for Precision Medicine
https://doi.org/10.1371%2Fjournal.pone.0160519
https://github.com/pbnjay/lollipops
Mutations Needle Plot
https://github.com/bbglab/muts-needle-plot
DOI:10.5281/zenodo.14561
Plot protein: visualization of mutations
https://doi.org/10.1186%2F2043-9113-3-14
https://sites.google.com/site/plotprotein/home
"""
import os
import sys
import re
from decimal import Decimal, ExtendedContext, setcontext, getcontext
from optparse import OptionParser
import pandas as pd
# https://colorcet.com/index.html
# https://github.com/holoviz/colorcet
# import colorcet
# https://arm-doe.github.io/pyart/examples/plotting/plot_choose_a_colormap.html
# JJ Helmus and SM Collis, JORS 2016, doi: 10.5334/jors.119
# import pyart
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import numpy as np
from Bio.Seq import translate
import mplcursors
# https://pypi.org/project/blosum/
import blosum
# https://docs.bokeh.org/en/latest/docs/user_guide/interaction/tools.html#ug-interaction-tools-hover-tool
import bokeh.plotting
import bokeh.models
setcontext(ExtendedContext)
c = getcontext()
c.prec = 99
VERSION = 202603091645
myparser = OptionParser(version="%s version %s" % ('%prog', VERSION))
myparser.add_option("--tsv", action="store", type="string", dest="tsv_file_path", default='',
help="Path to a TAB separated file with 5-columns: ['position', 'original_aa', 'mutant_aa', 'frequency', 'original_codon', 'mutant_codon', 'coverage_per_codon'] or more up to 11-columns ['padded_position', 'position', 'original_aa', 'mutant_aa', 'frequency', 'original_codon', 'mutant_codon', 'observed_codon_count', 'total_codons_per_site', 'frequency_parent', 'frequency_selected'] as we kept extending the file format")
myparser.add_option("--column", action="store", type="string", dest="column_with_frequencies", default='frequency',
help="Name of a column in input TSV to be used for rendering frequencies [frequency]")
myparser.add_option("--outfile-prefix", action="store", type="string", dest="outfile_prefix", default='',
help="Output file prefix, eventually also with path. Output files will be PNG, JPG or PDF, HTML")
myparser.add_option("--offset", action="store", type="int", dest="offset", default=0,
help="Define offset value to be added to every amino acid position in the first column of the TSV input file at runtime. This is to obtain real amino acid position within the protein. Normally protein starts at position 1. Check the first aa in TSV file and provide whatever number to be added to it to get the desired amino acid position in the full-length protein.")
myparser.add_option("--xmin", action="store", type="int", dest="xmin", default=0,
help="Define minimum X-axis value")
myparser.add_option("--xmax", action="store", type="int", dest="xmax", default=0,
help="Define maximum X-axis value")
myparser.add_option("--x-axis-bins", action="store", type="int", dest="xaxis_bins", default=0,
help="Set number of bins (labels) on the X-axis. Could be used to override the amount of major ticks in a different way. Use 20 for example. [default is 0]")
myparser.add_option("--x-axis-major-ticks-spacing", action="store", type="int", dest="xaxis_major_ticks_spacing", default=10,
help="Set distance between the major ticks on X-axis")
myparser.add_option("--x-axis-minor-ticks-spacing", action="store", type="int", dest="xaxis_minor_ticks_spacing", default=5,
help="Set distance between the minor ticks on X-axis")
myparser.add_option("--x-axis-label-start", action="store", type="int", dest="xaxis_label_start", default=0,
help="Set first label value on the X-axis")
myparser.add_option("--aminoacids", action="store_true", dest="aminoacids", default=False,
help="Draw chart with amino acid residues on Y-axis instead of codons. [default is False]")
myparser.add_option("--show-STOP", action="store_true", dest="showstop", default=False,
help="Include STOP codons or '*' in charts on Y-axis. [default is False]")
myparser.add_option("--show-INS", action="store_true", dest="showins", default=False,
help="Include INS in charts on Y-axis. [default is False]")
myparser.add_option("--show-DEL", action="store_true", dest="showdel", default=False,
help="Include DEL in charts on Y-axis. [default is False]")
myparser.add_option("--show-X", action="store_true", dest="showx", default=False,
help="Include X in charts on Y-axis in --aminoacids mode. [default is False]")
myparser.add_option("--enable-colorbar", action="store_true", dest="colorbar", default=False,
help="Enable colorbar [is Disabled by default]")
myparser.add_option("--disable-short-legend", action="store_false", dest="shortlegend", default=True,
help="Disable short legend in charts on X-axis. [is Enabled by default]")
myparser.add_option("--include-synonymous", action="store_true", dest="include_synonymous", default=False,
help="Include synonymous changes in --aminoacids output as green diamonds. In codon output they are always shown. [default is False]")
myparser.add_option("--threshold", action="store", type="float", dest="threshold", default=0.001,
help="Define minimum frequency threshold to display a pictogram in the output. For codon mode use 0.001 and for aa mode use 0.01. [default: 0.001]")
myparser.add_option("--title", action="store", type="string", dest="title", default='',
help="Set title for the figures, by default trailing '.frequencies.tsv' is stripped from the end of the input filename")
myparser.add_option("--disable-2nd-Y-axis", action="store_true", dest="disable_2nd_Y_axis", default=False,
help="Disable rendering of the 2nd Y-axis showing sequencing coverage")
myparser.add_option("--legend", action="store_true", dest="legend", default=False,
help="Draw legend chart. [default is False]")
myparser.add_option("--matrix", action="store", type="str", dest="matrix", default="BLOSUM80",
help="BLOSUM matrix: BLOSUM45,BLOSUM50,BLOSUM62,BLOSUM80,BLOSUM90 [default is BLOSUM80]")
myparser.add_option("--matrix-file", action="store", type="string", dest="matrix_file", default=None,
help="Matrix file compatible with BLOSUM matrices, e.g. prot26050-sup-0004-Supinfo03.sm from https://www.ncbi.nlm.nih.gov/pmc/articles/PMC8641535/bin/NIHMS1664401-supplement-supinfo.rar if you do not like default BLOSUM62")
myparser.add_option("--colormap", action="store", type="string", dest="colormap", default='amino_acid_changes',
help="Pick a colormap recognized by matplotlib. See https://i.sstatic.net/cmk1J.png [default is coolwarm_r but seismic_r and coolwarm_r are great too]")
myparser.add_option("--dpi", action="store", type="int", dest="dpi", default=600,
help="DPI resolution for images")
myparser.add_option("--backend", action="store", type="string", dest="backend", default='',
help="Matplotlibg backend to render resulting figures: agg, wxpython, pyqt5, pyqt6, pycairo, cairocffi [default: unset]\nTo disable Matplolib interactive window being raised up you can set MPLBACKEND=agg env variable.")
myparser.add_option("--debug", action="store", type="int", dest="debug", default=0,
help="Set debug to some real number")
(myoptions, myargs) = myparser.parse_args()
def alt_translate(seq):
"""Biopython cannot sometimes translate a sequence but one can get around by
splitting it into codons and merging later back
https://github.com/biopython/biopython/pull/4992
https://github.com/biopython/biopython/pull/4992#issuecomment-2865429105
"""
_codons = (seq[i:i+3] for i in range(0, len(seq), 3))
_codons = ("NNN" if "-" in _codon and _codon != "---" else _codon for _codon in _codons)
return "".join(translate(_codon, gap='-') for _codon in _codons)
def get_colormap(colormapname):
_colors = None
try:
_cmap = matplotlib.colormaps.get_cmap(colormapname) # LinearSegmentedColormap object
# tab20b = mpl.colormaps['tab20b'].resampled(27)
# _colors = [matplotlib.colors.to_hex(mpl.colormaps['tab20b'](i), keep_alpha=True) for i in np.linspace(0, 1, 27)]
# https://matplotlib.org/stable/api/_as_gen/matplotlib.colors.to_hex.html
# [matplotlib.colors.to_hex(cmap(i), keep_alpha=True) for i in np.linspace(0, 1, _number_of_colors_needed)] # use #rrggbbaa instead of #rrggbb
# ['#393b79ff', '#393b79ff', '#5254a3ff', '#6b6ecfff', '#9c9edeff', '#9c9edeff', '#637939ff', '#8ca252ff', '#b5cf6bff', '#b5cf6bff', '#cedb9cff', '#8c6d31ff', '#bd9e39ff', '#e7ba52ff', '#e7ba52ff', '#e7cb94ff', '#843c39ff', '#ad494aff', '#ad494aff', '#d6616bff', '#e7969cff', '#7b4173ff', '#7b4173ff', '#a55194ff', '#ce6dbdff', '#de9ed6ff', '#de9ed6ff']
except:
try:
_cmap = plt.get_cmap(colormapname) # matplotlib.colors.ListedColormap object
except:
try:
# https://github.com/akvas/nclcmaps
# is not in conda-forge nor PyPi, you have to install it manually from the source directory using 'python -m pip install .'
import nclcmaps
# Use nclcmaps.cm.colormaps() to list all available colormaps
_cmap = nclcmaps.cm.get_cmap(colormapname) # matplotlib.colors.ListedColormap object
except:
try:
# https://jiffyclub.github.io/palettable/
import palettable
_wished_cmapname_prefix, _wished_cmapname_num = '_'.join(myoptions.colormap.split('_')[:-1]), int(myoptions.colormap.split('_')[-1])
print(f"Debug: _wished_cmapname_prefix={_wished_cmapname_prefix}, _wished_cmapname_num={_wished_cmapname_num}")
_cmap_from_palettable = palettable.colorbrewer.get_map(_wished_cmapname_prefix, 'diverging', _wished_cmapname_num)
_cmap = matplotlib.colors.ListedColormap(_cmap_from_palettable.mpl_colors)
except:
try:
# https://jiffyclub.github.io/palettable/
import palettable
_cmap_from_palettable = palettable.colorbrewer.get_map(_wished_cmapname_prefix, 'sequential', _wished_cmapname_num)
_cmap = matplotlib.colors.ListedColormap(_cmap_from_palettable.mpl_colors)
except:
try:
# https://jiffyclub.github.io/palettable/
import palettable
_cmap_from_palettable = palettable.scientific.get_map(_wished_cmapname_prefix, 'diverging', _wished_cmapname_num)
_cmap = matplotlib.colors.ListedColormap(_cmap_from_palettable.mpl_colors)
except:
try:
# https://jiffyclub.github.io/palettable/
import palettable
_cmap_from_palettable = palettable.scientific.get_map(_wished_cmapname_prefix, 'sequential', _wished_cmapname_num)
_cmap = matplotlib.colors.ListedColormap(_cmap_from_palettable.mpl_colors)
except:
try:
# https://jiffyclub.github.io/palettable/
import palettable
_cmap_from_palettable = palettable.tableau.get_map(myoptions.colormap)
_cmap = matplotlib.colors.ListedColormap(_cmap_from_palettable.mpl_colors)
except:
# #EFB6D6 pink
# #CC79A7 darker pink
# #ff9900 orange
# #F09163 salmon
# #9D654C brown
# #ffcc00 yellow
# #cccc00 yellow to green
# #A3E4D7 light blue
# #7DCCFF light blue
# #43BA8F green to blue
# #DDFFA0 light green
# #97CE2F green with yellow
#
# https://github.com/KarstensLab/microshades
_micro_cvd_gray = ("#F5F5F5", "#D6D6D6", "#B7B7B7", "#8B8B8B","#616161")
_micro_cvd_green = ("#DDFFA0", "#BDEC6F", "#97CE2F", "#6D9F06","#4E7705")
_micro_cvd_orange = ("#FFD5AF", "#FCB076","#F09163", "#C17754", "#9D654C")
_micro_cvd_blue = ("#E7F4FF", "#BCE1FF", "#7DCCFF", "#56B4E9","#098BD9")
_micro_cvd_turquoise = ("#A3E4D7", "#48C9B0", "#43BA8F", "#009E73", "#148F77")
_micro_cvd_purple = ("#EFB6D6", "#E794C1", "#CC79A7", "#A1527F", "#7D3560")
_micro_cvd_gray_r = _micro_cvd_gray[::-1]
_micro_cvd_green_r = _micro_cvd_green[::-1]
_micro_cvd_orange_r = _micro_cvd_orange[::-1]
_micro_cvd_blue_r = _micro_cvd_blue[::-1]
_micro_cvd_turquoise_r = _micro_cvd_turquoise[::-1]
_micro_cvd_purple_r = _micro_cvd_purple[::-1]
if myoptions.colormap == 'microshades_cvd_palettes':
_colors = list(_micro_cvd_orange) + list(_micro_cvd_turquoise) + list(_micro_cvd_blue) + list(_micro_cvd_purple) + list(_micro_cvd_green) + list(_micro_cvd_gray)
_cmap = matplotlib.colors.ListedColormap(_colors, 'microshades_cvd_palettes')
elif myoptions.colormap == 'microshades_cvd_palettes_r':
_colors = list(_micro_cvd_orange_r) + list(_micro_cvd_turquoise_r) + list(_micro_cvd_blue_r) + list(_micro_cvd_purple_r) + list(_micro_cvd_green_r) + list(_micro_cvd_gray_r)
_cmap = matplotlib.colors.ListedColormap(_colors, 'microshades_cvd_palettes_r')
elif myoptions.colormap == 'merged':
# https://stackoverflow.com/questions/31051488/combining-two-matplotlib-colormaps
# sample the colormaps that you want to use. Use 128 from each so we get 256
# colors in total
_colors1 = plt.cm.gist_heat(np.linspace(0.2, 0.8, 9)) # standard matplotlib.cm colormap
_colors2 = plt.cm.cividis_r(np.linspace(0.2, 0.8, 9)) # standard matplotlib.cm colormap
_colors3 = plt.cm.GnBu_r(np.linspace(0.2, 0.8, 9)) # standard matplotlib.cm colormap
# combine them and build a new colormap
_colors = np.vstack((_colors1, _colors2, _colors3))
_cmap = matplotlib.colors.LinearSegmentedColormap.from_list('merged', _colors)
elif myoptions.colormap == 'merged1':
# https://stackoverflow.com/questions/31051488/combining-two-matplotlib-colormaps
# sample the colormaps that you want to use. Use 128 from each so we get 256
# colors in total
_colors1 = plt.cm.viridis(np.linspace(0.2, 0.8, 9)) # standard matplotlib.cm colormap
_colors2 = plt.cm.coolwarm_r(np.linspace(0., 1, 9)) # standard matplotlib.cm colormap
_colors3 = plt.cm.GnBu_r(np.linspace(0.2, 0.8, 9)) # standard matplotlib.cm colormap
# combine them and build a new colormap
_colors = np.vstack((_colors1, _colors2, _colors3))
_cmap = matplotlib.colors.LinearSegmentedColormap.from_list('merged', _colors)
elif myoptions.colormap == 'dkeenan_26cols':
# https://graphicdesign.stackexchange.com/questions/3682/where-can-i-find-a-large-palette-set-of-contrasting-colors-for-coloring-many-d
# https://dkeenan.com/Colour/
# added "#000000" into the middle
_colors = ["#00B7FF", "#004DFF", "#00FFFF", "#826400", "#580041", "#FF00FF", "#00FF00", "#C500FF", "#B4FFD7", "#FFCA00", "#969600", "#B4A2FF", "#C20078", "#000000", "#0000C1", "#FF8B00", "#FFC8FF", "#666666", "#FF0000", "#CCCCCC", "#009E8F", "#D7A870", "#8200FF", "#960000", "#BBFF00", "#FFFF00", "#006F00"]
_cmap = matplotlib.colors.ListedColormap(_colors, "dkeenan_26cols") # 26 colors
myoptions.colormap = 'dkeenan_26cols'
_norm = matplotlib.colors.BoundaryNorm(np.arange(-13, 13, 1), _cmap.N)
else:
# _amino_acid_changes_cmap = ["#F5F5F5", "#D6D6D6", "#B7B7B7", "#8B8B8B", "#ff0000", "#f16264", "#ffc8ff", "#EFB6D6", "#CC79A7", "#ff9900", "#F09163", "#9c644b", "#ffcc00", "#cccc00", "#A3E4D7", "#7DCCFF", "#0042ff", "#DDFFA0", "#97CE2F", "#219f11", "#00ff04", "#c20078", "#ff00fd", "#c500ff", "#8200ff", "#960000", "#580041"]
# with yellow "#ffff00" in the middle _colors[20]
_colors = ["#930000", "#930000", "#930000", "#930000", "#930000", "#930000", "#960000", "#580041", "#8200ff", "#c500ff", "#ff00fd", "#CC79A7", "#eea1d0", "#cc0000", "#ff0000", "#ff4f00", "#ff7c7c", "#ff9999", "#c58a24", "#9c644b", "#ffff00", "#ffcc00", "#ffa200", "#7DCCFF", "#0042ff", "#0000ff", "#D6D6D6", "#B7B7B7", "#8B8B8B", "#bbff00", "#00ff04", "#97CE2F", "#219f11", "#930000", "#930000", "#930000", "#930000", "#930000", "#930000"]
_cmap = matplotlib.colors.ListedColormap(_colors, "amino_acid_changes", len(_colors)) # 39 colors
#plt.cm.register_cmap(name='amino_acid_changes', cmap=_cmap)
myoptions.colormap = 'amino_acid_changes'
_norm = matplotlib.colors.BoundaryNorm(np.arange(-19, 19, 1), _cmap.N) # this will create an asymetric range -19 to 18
return _norm, _cmap, _colors
return _norm, _cmap, _colors
def resolve_codon_or_aa(old_codon_or_aa, new_codon_or_aa):
# define color palette, use 'coolwarm nr. 90' from https://i.sstatic.net/cmk1J.png or 'rainbow nr. 138' or 'seismic_r 141' or 'RdYIBu_r 51'
# https://datascientyst.com/full-list-named-colors-pandas-python-matplotlib/
_len_new_codon_or_aa = len(new_codon_or_aa)
if myoptions.aminoacids:
# in aa mode we always pass to this routine a codon instead of the original amino acid, dunno why but at least when rendering a static figure legend we pass down 'NNN'
_old_codon_or_aa = alt_translate(old_codon_or_aa)
if new_codon_or_aa == 'NNN':
_new_codon_or_aa = 'X'
_len_new_codon_or_aa = len(_new_codon_or_aa)
elif _len_new_codon_or_aa > 1 and new_codon_or_aa not in ('---', 'DEL', 'INS'):
print(f"Info: Weird, the new_codon_or_aa={new_codon_or_aa}")
_new_codon_or_aa = new_codon_or_aa.upper()
else:
_new_codon_or_aa = new_codon_or_aa.upper()
else:
_old_codon_or_aa = old_codon_or_aa.upper()
_new_codon_or_aa = new_codon_or_aa.upper()
# do not get confused by the 3-letter DEL and INS values
if len(_old_codon_or_aa) > 1 and old_codon_or_aa not in ('---', 'DEL', 'INS'):
_codon_on_input = True
elif len(_new_codon_or_aa) > 1 and new_codon_or_aa not in ('---', 'DEL', 'INS'):
_codon_on_input = True
else:
_codon_on_input = False
return _codon_on_input, _old_codon_or_aa, _new_codon_or_aa
def get_score(matrix, codon_on_input, old_codon_or_aa, new_codon_or_aa):
try:
if codon_on_input:
_score = int(matrix[alt_translate(old_codon_or_aa)][alt_translate(new_codon_or_aa)])
else:
_score = int(matrix[old_codon_or_aa][new_codon_or_aa])
except OverflowError:
_score = -11
except:
raise ValueError("Cannot get a score for myoptions.matrix='%s', old_codon_or_aa='%s', new_codon_or_aa='%s'" % (myoptions.matrix, old_codon_or_aa, new_codon_or_aa))
return _score
def adjust_size_and_color(frequency, codon_on_input, old_codon_or_aa, new_codon_or_aa, _old_codon_or_aa, _new_codon_or_aa, matrix, norm, colors):
"""Define colors for basic type of scatterplot figures. The circles have variable diameter
in a range from 0 to 100%, each. The total sum of amino acid residues in a particular position
in a protein is 100%. Provided there can be multiple aa residues encoded by even more codons,
the diameter is not always a 100% (not a full-size).
The checks need to anticipate these scenarios:
old_codon_or_aa = 'NNN'
new_codon_or_aa = 'N' # incomplete new codon
old_codon_or_aa = 'NNN'
new_codon_or_aa = 'DEL'
old_codon_or_aa = '--'
new_codon_or_aa = 'NNN'
https://stackoverflow.com/questions/25408393/getting-individual-colors-from-a-color-map-in-matplotlib
https://stackoverflow.com/questions/34314356/how-to-view-all-colormaps-available-in-matplotlib/68317686#68317686
https://i.sstatic.net/cmk1J.png
https://matplotlib.org/stable/gallery/color/named_colors.html
https://www.ncbi.nlm.nih.gov/IEB/ToolBox/C_DOC/lxr/source/data/BLOSUM45
https://www.ncbi.nlm.nih.gov/IEB/ToolBox/C_DOC/lxr/source/data/BLOSUM50
https://www.ncbi.nlm.nih.gov/IEB/ToolBox/C_DOC/lxr/source/data/BLOSUM62
https://www.ncbi.nlm.nih.gov/IEB/ToolBox/C_DOC/lxr/source/data/BLOSUM80
https://www.ncbi.nlm.nih.gov/IEB/ToolBox/C_DOC/lxr/source/data/BLOSUM90
"""
if codon_on_input:
if str(_old_codon_or_aa)[0].upper() != str(_new_codon_or_aa)[0].upper(): # the 1st nucleotide in a codon is different
_significant_change = True
elif str(_old_codon_or_aa)[1].upper() != str(_new_codon_or_aa)[1].upper(): # the 2nd nucleotide in a codon is different
_significant_change = True
else:
_significant_change = False
elif not _old_codon_or_aa:
raise ValueError("Aieee, old_codon_or_aa='%s' is empty" % str(old_codon_or_aa))
elif not _new_codon_or_aa:
raise ValueError("Aieee, new_codon_or_aa='%s' is empty" % str(new_codon_or_aa))
else:
if new_codon_or_aa in ('---', 'DEL', 'INS', '*'):
_significant_change = True
elif _old_codon_or_aa in ('---', 'DEL', 'INS', '*'):
_significant_change = True
else:
# some single-letter amino acid residue or '*' or 'DEL' or 'INS'
if myoptions.debug:
print("Info: some single-letter but neither asterisk nor dash amino acid residue: _old_codon_or_aa=%s, new_codon_or_aa='%s'" % (str(_old_codon_or_aa), str(new_codon_or_aa)))
_significant_change = False
# make sure the BLOSUM matrix contains the AA pair otherwise blosum module returns -inf (infinity) triggering OverflowError
if _new_codon_or_aa in ('---', 'DEL', 'INS'):
_score = -11
else:
_score = get_score(matrix, codon_on_input, _old_codon_or_aa, _new_codon_or_aa)
_colorindex = norm(_score) # this only affects figures rendered by Bokeh, not by Matplotlib
# if one rewrites _score with a new value it:
# 1. makes the data point in green in Matplotlib images
# 2. the fake score 12 is shown in Bokeh images during hover()
# 3. the original score is shown in Matplotlib images during hover() and mplcursors
# In summary, we need this enabled if we want to emphasize synonymous mutations to make image more readable.
if old_codon_or_aa.upper() == new_codon_or_aa.upper():
_color = '#00ff04' # use palegreen for synonymous changes
_score = 12 # enter fake score because matplotlib.scatter ignores the colors passed to it when cmap and norm are passed to it as well
elif _old_codon_or_aa.upper() == _new_codon_or_aa.upper():
_color = '#00ff04' # use palegreen for synonymous changes
_score = 12 # enter fake score because matplotlib.scatter ignores the colors passed to it when cmap and norm are passed to it as well
elif old_codon_or_aa in ('---', 'DEL', 'INS', '*') or new_codon_or_aa in ('---', 'DEL', 'INS', '*', 'TGA', 'TAA', 'TAG'):
_color = 'red'
_score = -6 # enter fake score because matplotlib.scatter ignores the colors passed to it when cmap and norm are passed to it as well
elif _old_codon_or_aa in ('X', 'NNN') or new_codon_or_aa in ('X', 'NNN'):
_color = 'gray'
elif codon_on_input:
if alt_translate(_old_codon_or_aa) == alt_translate(_new_codon_or_aa):
_color = '#00ff04' # palegreen
_score = 12 # enter fake score because matplotlib.scatter ignores the colors passed to it when cmap and norm are passed to it as well
elif alt_translate(_new_codon_or_aa) == 'X':
_color = 'gray'
else:
if myoptions.debug:
sys.stdout.write("Info: Translating %s to %s to fetch color from _colors," % (_old_codon_or_aa, _new_codon_or_aa))
_color = colors[_colorindex] # get the color by its index position in the ListedColormap
if myoptions.debug:
sys.stdout.write(" which has yielded %s and %s%s" % (_colorindex, str(_color), os.linesep))
else:
if myoptions.debug:
sys.stdout.write("Info: Fetching color for %s to %s directly from _colors," % (_old_codon_or_aa, _new_codon_or_aa))
_color = colors[_colorindex]
if myoptions.debug:
sys.stdout.write(" which has yielded %s and %s%s" % (_colorindex, str(_color), os.linesep))
return _score, frequency, _color
def adjust_size_and_color_neutralized_escape(neutralized_parent_difference, codon_on_input):
"Used only for neutralized_parent_difference and escape_parent_difference figure types."
if neutralized_parent_difference < -0.001:
_size = abs(neutralized_parent_difference)
_color = 'red'
elif neutralized_parent_difference > 0.001:
if not codon_on_input:
_size, _color = 0, '#00ff04' # do not draw circles for unchanged amino acids
else:
_size = neutralized_parent_difference
_color = '#00ff04'
else: # Values close to zero (between -0.001 and 0.001) non-visible; use size 5 to retain a controlling handle
_size = 0
_color = 'black'
return _size, _color
def adjust_size_and_color_weighted(weighted_diff_escape_neutralized, generic_circle_size=5000, weighted_diff_escape_neutralized_size1=3000, weighted_diff_escape_neutralized_size2=2000): # use for 'weighted_diff_escape_neutralized'
"Used only for weighted_diff_escape_neutralized figure type."
if weighted_diff_escape_neutralized > 1:
# Values above 1 will be scaled more prominently and colored dark blue
_size = (weighted_diff_escape_neutralized) * generic_circle_size
_color = 'black'
elif weighted_diff_escape_neutralized > 0.1:
# Values between 0.001 and 1 will be scaled and colored skyblue
_size = (weighted_diff_escape_neutralized) * weighted_diff_escape_neutralized_size1
_color = 'darkblue'
elif weighted_diff_escape_neutralized > 0.01:
# Values between 0.001 and 1 will be scaled and colored skyblue
_size = (weighted_diff_escape_neutralized) * weighted_diff_escape_neutralized_size2
_color = 'skyblue'
else:
_size = abs(weighted_diff_escape_neutralized) * 0
_color = 'black'
return _size, _color
def load_matrix():
"""Load BLOSUM or custom substitution matrix and set up the output file prefix."""
if myoptions.matrix_file and os.path.exists(myoptions.matrix_file):
print(myoptions.matrix)
if not myoptions.matrix:
myoptions.matrix = re.sub(r'.*/', '', myoptions.matrix_file)
print(myoptions.matrix)
_matrix_type, _matrix_num = re.sub(r'\d+', '', myoptions.matrix), int(re.sub(r'[a-zA-Z]+', '', myoptions.matrix))
_matrix = blosum.BLOSUM(myoptions.matrix_file) # if compatible with BLOSUM, import the custom file
_matrix_name = myoptions.matrix_file.split(os.path.sep)[-1]
# _commonly_used_matrix = False
myoptions.matrix = _matrix_name
else:
_matrix_type, _matrix_num = re.sub(r'\d+', '', myoptions.matrix), int(re.sub(r'[a-zA-Z]+', '', myoptions.matrix))
if _matrix_type == 'BLOSUM':
_matrix = blosum.BLOSUM(_matrix_num) # 45,50,62,80,90
_matrix_name = "BLOSUM%d" % (_matrix_num)
else:
sys.stderr.write("Warning: Unexpected matrix type %s, falling back to BLOSUM\n" % str(_matrix_type))
_matrix = blosum.BLOSUM(_matrix_num) # 45,50,62,80,90
_matrix_name = "BLOSUM%d" % (_matrix_num)
myoptions.matrix = _matrix_name
# _commonly_used_matrix = True
if not myoptions.outfile_prefix:
raise RuntimeError("Please provide output filename prefix via --outfile-prefix")
else:
_outfile_prefix = myoptions.outfile_prefix + '.' + _matrix_name + '.' + myoptions.colormap
print(f"Info: _outfile_prefix={_outfile_prefix}")
_theoretical_scores = set()
for _aa in _matrix.keys():
for _score in _matrix[_aa].values():
_theoretical_scores.add(_score)
print(f"Info: Using {_matrix_name} matrix now. Theoretical minimum score is {min(_theoretical_scores)}, theoretical maximum score is {max(_theoretical_scores)}, values are {str(_theoretical_scores)}")
_min_theoretical_score, _max_theoretical_score = int(min(_theoretical_scores)), int(max(_theoretical_scores)) # also convert from float to int
return _matrix, _matrix_name, _min_theoretical_score, _max_theoretical_score, _outfile_prefix
def load_and_clean_dataframe(outfile_prefix):
"Load the input TSV, normalise column names for legacy formats, and filter noisy rows."
print(f"Info: Parsing input file {myoptions.tsv_file_path}")
if not myoptions.tsv_file_path:
raise RuntimeError("Please provide an input TSV file via --tsv")
df = pd.read_csv(myoptions.tsv_file_path, sep='\t', header='infer', na_filter=False, na_values=[None])#, nrows=500)
if 'position' not in df.columns:
del(df)
print("Info: Autodetected old TSV file format without a header in %s, assigning default column names" % myoptions.tsv_file_path)
df = pd.read_csv(myoptions.tsv_file_path, sep='\t', header=0, na_filter=False, na_values=[None])#, nrows=500)
# Assign column names
# released results on Zenodo: 430 T K 0.000386 ACA AAA
print(f"Info: The file {myoptions.tsv_file_path} contained initially these columns: {str(df.columns)}")
_count_columns = len(df.columns.values)
if _count_columns == 9:
# 340 340 E E 0.012149 GAA GAG 97849 8054365
df.columns = ['padded_position', 'position', 'original_aa', 'mutant_aa', 'frequency', 'original_codon', 'mutant_codon', 'observed_codon_count', 'total_codons_per_site']
elif _count_columns == 11:
df.columns = ['padded_position', 'position', 'original_aa', 'mutant_aa', 'frequency', 'original_codon', 'mutant_codon', 'observed_codon_count', 'total_codons_per_site', 'frequency_parent', 'frequency_selected']
elif _count_columns == 10:
df.columns = ['position', 'original_aa', 'mutant_aa', 'frequency', 'original_codon', 'mutant_codon', 'observed_codon_count', 'total_codons_per_site', 'frequency_parent', 'frequency_selected']
elif _count_columns == 8:
df.columns = ['position', 'original_aa', 'mutant_aa', 'frequency', 'original_codon', 'mutant_codon', 'observed_codon_count', 'total_codons_per_site']
elif _count_columns == 6:
df.columns = ['position', 'original_aa', 'mutant_aa', 'frequency', 'original_codon', 'mutant_codon']
else:
raise RuntimeError("Unexpected number of columns in the %s file" % myoptions.tsv_file_path)
else:
print(f"Info: Autodetected new TSV file format with a header in {myoptions.tsv_file_path}")
print(f"Info: The file {myoptions.tsv_file_path} contains now these columns: {str(df.columns)}")
#print(f"Info: df={str(df)}")
# sanitize input aa positions and add myoptions.offset to each value
df['position'] = df['position'] + int(myoptions.offset)
_before = len(df['mutant_codon'])
try:
df = df.loc[df['mutant_codon'].str.match('[ATGCatgc-][ATGCatgc-][ATGCatgc-]')] # discard [nN] but keep '-', beware GISAID also contains other IUPAC codes
except Exception as _exc:
raise ValueError("Cannot parse column df['mutant_codon']=%s containing %d values" % (str(df['mutant_codon']), len(df['mutant_codon'])))
if not myoptions.showstop:
# discard sequencing errors appearing as STOPs
df = df.loc[~df['mutant_aa'].isin(['*'])]
if not myoptions.showdel:
# discard sequencing errors appearing as DEL
df = df.loc[~df['mutant_aa'].isin(['DEL'])]
if not myoptions.showins:
df = df.loc[~df['mutant_aa'].isin(['INS'])]
df = df.loc[~df['mutant_aa'].isin(['X'])] # discard frame-breaking changes (codons contain one or two dashes), TODO: maybe we should check if any dash was in the reference_sequence ?
_after = len(df['mutant_codon'])
if myoptions.showstop:
if myoptions.showdel:
print("Info: Originally there were %d rows but after discarding codons with [N n] there are only %d left" % (_before, _after))
else:
print("Info: Originally there were %d rows but after discarding codons with [N n DEL] there are only %d left" % (_before, _after))
elif myoptions.showdel:
print("Info: Originally there were %d rows but after discarding codons with [N n *] there are only %d left" % (_before, _after))
else:
print("Info: Originally there were %d rows but after discarding codons with [N n DEL] there are only %d left" % (_before, _after))
# print(df)
print(f"Info: Writing into {outfile_prefix}.actually_rendered.tsv")
df.to_csv(f"{outfile_prefix}.actually_rendered.tsv", sep='\t', header=None, index=False, float_format='{:7.6f}'.format) # dump back the edited dataframe for eventual checks and disable scientific notation of float numbers
if '.frequencies.tsv' in myoptions.tsv_file_path:
_count_filename = outfile_prefix + '.count'
if os.path.exists(_count_filename):
try:
_aln_handle = open(_count_filename)
except:
_aln_rows = '0'
_aln_handle = None
else:
_aln_rows = '0'
_aln_handle = None
else:
_aln_rows = '0'
_aln_handle = None
if not myoptions.title:
title_data = myoptions.tsv_file_path.replace('.frequencies.tsv', '')
else:
title_data = myoptions.title
if _aln_handle:
_aln_rows = _aln_handle.readline()
_aln_handle.close()
print(f"Info: Title will be {title_data}")
return df, title_data, _aln_rows
def build_frequency_tables(df):
"Build amino-acid and codon frequency tables from the cleaned dataframe."
# create an empty table pre-filled with zeroes, without ['B', 'Z']
#_amino_acids = ['A', 'R', 'N', 'D', 'C', 'Q', 'E', 'G', 'H', 'I', 'L', 'K', 'M', 'F', 'P', 'S', 'T', 'W', 'Y', 'V', '*']
_amino_acids = ['C', 'R', 'K', 'E', 'Q', 'D', 'N', 'T', 'S', 'H', 'M', 'P', 'W', 'Y', 'F', 'V', 'L', 'I', 'A', 'G'] # 'INS', 'X', 'DEL'] #, None] # sorted by physicochemical properties
if myoptions.showins:
_amino_acids.append('INS')
if myoptions.showx:
_amino_acids.append('X')
if myoptions.showstop:
_amino_acids.append('*')
if myoptions.showdel:
_amino_acids.append('DEL')
_unique_aa_positions = [x for x in df['position'].unique()]
_min_aa_pos = min(_unique_aa_positions)
_max_aa_pos = max(_unique_aa_positions)
#_number_of_insertions = _padded_reference_sequence.count('-') # count number of insertions based on the number of dashes in a padded reference sequence
_number_of_insertions = 0
_unique_aa_positions = [x for x in range(_min_aa_pos, _max_aa_pos + 1 + _number_of_insertions)] # ensure we have a continuous range, eventually inject INS positions, add +1 to accommodate for the pandas dataframe index column
if myoptions.debug:
print(f"Debug: len(_unique_aa_positions)={len(_unique_aa_positions)}, _unique_aa_positions: {str(_unique_aa_positions)}")
_unique_codon_positions = list(_unique_aa_positions)
if myoptions.debug:
print(f"Debug: len(_unique_codon_positions)={len(_unique_codon_positions)}, _unique_codon_positions: {str(_unique_codon_positions)}")
# these are all theoretically appearing codons in a sample
_codons_whitelist = ['TTT', 'TTC', 'TTA', 'TTG', 'CTT', 'CTC', 'CTA', 'CTG', 'ATT', 'ATC', 'ATA', 'ATG', 'GTT', 'GTC', 'GTA', 'GTG', 'TCT', 'TCC', 'TCA', 'TCG', 'CCT', 'CCC', 'CCA', 'CCG', 'ACT', 'ACC', 'ACA', 'ACG', 'GCT', 'GCC', 'GCA', 'GCG', 'TAT', 'TAC', 'TAA', 'TAG', 'CAT', 'CAC', 'CAA', 'CAG', 'AAT', 'AAC', 'AAA', 'AAG', 'GAT', 'GAC', 'GAA', 'GAG', 'TGT', 'TGC', 'TGA', 'TGG', 'CGT', 'CGC', 'CGA', 'CGG', 'AGT', 'AGC', 'AGA', 'AGG', 'GGT', 'GGC', 'GGA', 'GGG']
if not myoptions.showstop:
for _stopcodon in ('TGA', 'TAA', 'TAG'):
_codons_whitelist.remove(_stopcodon)
if myoptions.debug:
print("Debug: Translating pre-made all possible codons")
_codons_whitelist_aa = [alt_translate(_codon) for _codon in _codons_whitelist]
# ensure the resulting _codons_whitelist2 will have same length as the codons later parsed from TSV file into _table.index
if 'DEL' in _amino_acids:
_codons_whitelist.append('---')
_codons_whitelist_aa.append('DEL')
if len(_codons_whitelist) != len(_codons_whitelist_aa):
raise ValueError("Length of _codons_whitelist is %d which is not equal to _codons_whitelist_aa with %d" % (len(_codons_whitelist), len(_codons_whitelist_aa)))
_sorted_whitelist = sorted(zip(_codons_whitelist, _codons_whitelist_aa), key=lambda x: x[1])
if myoptions.debug:
print(f"Debug: _sorted_whitelist={str(_sorted_whitelist)}")
# Info: _sorted_whitelist=[('TAA', '*'), ('TAG', '*'), ('TGA', '*'), ('GCT', 'A'), ('GCC', 'A'), ('GCA', 'A'), ('GCG', 'A'), ('TGT', 'C'), ('TGC', 'C'), ('GAT', 'D'), ('GAC', 'D'), ('GAA', 'E'), ('GAG', 'E'), ('TTT', 'F'), ('TTC', 'F'), ('GGT', 'G'), ('GGC', 'G'), ('GGA', 'G'), ('GGG', 'G'), ('CAT', 'H'), ('CAC', 'H'), ('ATT', 'I'), ('ATC', 'I'), ('ATA', 'I'), ('AAA', 'K'), ('AAG', 'K'), ('TTA', 'L'), ('TTG', 'L'), ('CTT', 'L'), ('CTC', 'L'), ('CTA', 'L'), ('CTG', 'L'), ('ATG', 'M'), ('AAT', 'N'), ('AAC', 'N'), ('CCT', 'P'), ('CCC', 'P'), ('CCA', 'P'), ('CCG', 'P'), ('CAA', 'Q'), ('CAG', 'Q'), ('CGT', 'R'), ('CGC', 'R'), ('CGA', 'R'), ('CGG', 'R'), ('AGA', 'R'), ('AGG', 'R'), ('TCT', 'S'), ('TCC', 'S'), ('TCA', 'S'), ('TCG', 'S'), ('AGT', 'S'), ('AGC', 'S'), ('ACT', 'T'), ('ACC', 'T'), ('ACA', 'T'), ('ACG', 'T'), ('GTT', 'V'), ('GTC', 'V'), ('GTA', 'V'), ('GTG', 'V'), ('TGG', 'W'), ('TAT', 'Y'), ('TAC', 'Y')]
# >>> [pairs[0] + ' (' + pairs[1] + ')' for pairs in _sorted_whitelist]
# ['TAA (*)', 'TAG (*)', 'TGA (*)', 'GCT (A)', 'GCC (A)', 'GCA (A)', 'GCG (A)', 'TGT (C)', 'TGC (C)', 'GAT (D)', 'GAC (D)', 'GAA (E)', 'GAG (E)', 'TTT (F)', 'TTC (F)', 'GGT (G)', 'GGC (G)', 'GGA (G)', 'GGG (G)', 'CAT (H)', 'CAC (H)', 'ATT (I)', 'ATC (I)', 'ATA (I)', 'AAA (K)', 'AAG (K)', 'TTA (L)', 'TTG (L)', 'CTT (L)', 'CTC (L)', 'CTA (L)', 'CTG (L)', 'ATG (M)', 'AAT (N)', 'AAC (N)', 'CCT (P)', 'CCC (P)', 'CCA (P)', 'CCG (P)', 'CAA (Q)', 'CAG (Q)', 'CGT (R)', 'CGC (R)', 'CGA (R)', 'CGG (R)', 'AGA (R)', 'AGG (R)', 'TCT (S)', 'TCC (S)', 'TCA (S)', 'TCG (S)', 'AGT (S)', 'AGC (S)', 'ACT (T)', 'ACC (T)', 'ACA (T)', 'ACG (T)', 'GTT (V)', 'GTC (V)', 'GTA (V)', 'GTG (V)', 'TGG (W)', 'TAT (Y)', 'TAC (Y)']
# sort the pairs according to physicochemical properties in _amino_acids
_final_sorted_whitelist = [_tuple for x in _amino_acids for _tuple in _sorted_whitelist if _tuple[1] == x]
if myoptions.debug:
print(f"Debug: _final_sorted_whitelist={str(_final_sorted_whitelist)}")
# >>> [_tuple for x in _amino_acids for _tuple in _sorted_whitelist if _tuple[1] == x]
# [('TGT', 'C'), ('TGC', 'C'), ('CGT', 'R'), ('CGC', 'R'), ('CGA', 'R'), ('CGG', 'R'), ('AGA', 'R'), ('AGG', 'R'), ('AAA', 'K'), ('AAG', 'K'), ('GAA', 'E'), ('GAG', 'E'), ('CAA', 'Q'), ('CAG', 'Q'), ('GAT', 'D'), ('GAC', 'D'), ('AAT', 'N'), ('AAC', 'N'), ('ACT', 'T'), ('ACC', 'T'), ('ACA', 'T'), ('ACG', 'T'), ('TCT', 'S'), ('TCC', 'S'), ('TCA', 'S'), ('TCG', 'S'), ('AGT', 'S'), ('AGC', 'S'), ('CAT', 'H'), ('CAC', 'H'), ('ATG', 'M'), ('CCT', 'P'), ('CCC', 'P'), ('CCA', 'P'), ('CCG', 'P'), ('TGG', 'W'), ('TAT', 'Y'), ('TAC', 'Y'), ('TTT', 'F'), ('TTC', 'F'), ('GTT', 'V'), ('GTC', 'V'), ('GTA', 'V'), ('GTG', 'V'), ('TTA', 'L'), ('TTG', 'L'), ('CTT', 'L'), ('CTC', 'L'), ('CTA', 'L'), ('CTG', 'L'), ('ATT', 'I'), ('ATC', 'I'), ('ATA', 'I'), ('GCT', 'A'), ('GCC', 'A'), ('GCA', 'A'), ('GCG', 'A'), ('GGT', 'G'), ('GGC', 'G'), ('GGA', 'G'), ('GGG', 'G'), ('TAA', '*'), ('TAG', '*'), ('TGA', '*')]
# >>>
_codons_whitelist2 = [x[0] for x in _final_sorted_whitelist] # get back the list of codons in the order used in _final_sorted_whitelist but also in sync with the order on Y-axis further down
if myoptions.debug:
print(f"Debug: _codons_whitelist2={str(_codons_whitelist2)}")
# Define the genetic code and codons with an additional parameter (1 to 65)
#_genetic_code = {
# "TTT": ("F", 1), "TTC": ("F", 2), "TTA": ("L", 3), "TTG": ("L", 4),
# "CTT": ("L", 5), "CTC": ("L", 6), "CTA": ("L", 7), "CTG": ("L", 8),
# "ATT": ("I", 9), "ATC": ("I", 10), "ATA": ("I", 11), "ATG": ("M", 12),
# "GTT": ("V", 13), "GTC": ("V", 14), "GTA": ("V", 15), "GTG": ("V", 16),
# "TCT": ("S", 17), "TCC": ("S", 18), "TCA": ("S", 19), "TCG": ("S", 20),
# "CCT": ("P", 21), "CCC": ("P", 22), "CCA": ("P", 23), "CCG": ("P", 24),
# "ACT": ("T", 25), "ACC": ("T", 26), "ACA": ("T", 27), "ACG": ("T", 28),
# "GCT": ("A", 29), "GCC": ("A", 30), "GCA": ("A", 31), "GCG": ("A", 32),
# "TAT": ("Y", 33), "TAC": ("Y", 34), "TAA": ("Stop", 35), "TAG": ("Stop", 36),
# "CAT": ("H", 37), "CAC": ("H", 38), "CAA": ("Q", 39), "CAG": ("Q", 40),
# "AAT": ("N", 41), "AAC": ("N", 42), "AAA": ("K", 43), "AAG": ("K", 44),
# "GAT": ("D", 45), "GAC": ("D", 46), "GAA": ("E", 47), "GAG": ("E", 48),
# "TGT": ("C", 49), "TGC": ("C", 50), "TGA": ("Stop", 51), "TGG": ("W", 52),
# "CGT": ("R", 53), "CGC": ("R", 54), "CGA": ("R", 55), "CGG": ("R", 56),
# "AGT": ("S", 57), "AGC": ("S", 58), "AGA": ("R", 59), "AGG": ("R", 60),
# "GGT": ("G", 61), "GGC": ("G", 62), "GGA": ("G", 63), "GGG": ("G", 64),
# "NNN": ("Other", 65), # Placeholder for anything else
#}
_old_aa_table = pd.DataFrame(Decimal(0), index=_amino_acids, columns=_unique_aa_positions)
_new_aa_table = pd.DataFrame(Decimal(0), index=_amino_acids, columns=_unique_aa_positions)
_old_codon_table = pd.DataFrame(Decimal(0), index=_codons_whitelist2, columns=_unique_codon_positions)
_new_codon_table = pd.DataFrame(Decimal(0), index=_codons_whitelist2, columns=_unique_codon_positions)
_very_leftmost_aa_pos = None
_calculated_aa_offset = 0
# make tables with yet another number of rows summing up eventually the frequencies
for df_index, row in df.iterrows():
# 1 G DEL 0.012625 GGA ---
#print(f"Row: {str(row)}")
# It is not necessary to skip N-containing codons as we anyway draw just those
# in codons list. Skipping some rows would make _new_aa_table and _new_codon_table
# have a different amount of rows, breaking slicing
_position = row['position'] # real position_in_protein
if _very_leftmost_aa_pos is None:
_very_leftmost_aa_pos = int(_position)
_calculated_aa_offset = _very_leftmost_aa_pos - myoptions.offset + 1 # if AA positions in the input file do NOT start from the first-one the numbering of sites gets shifted, so calculate the offset
if myoptions.debug:
print(f"Debug: calculated offset is {_calculated_aa_offset}")
_old_amino_acid = row['original_aa']
_new_amino_acid = row['mutant_aa']
frequency = Decimal(row[myoptions.column_with_frequencies])
_old_codon = row['original_codon'].upper()
_new_codon = row['mutant_codon'].upper()
if (not myoptions.aminoacids or _old_amino_acid != _new_amino_acid or myoptions.include_synonymous) and not np.abs(frequency) < myoptions.threshold: # discard sequencing noise by zapping the values instead of deleting altogether
_old_value = Decimal(0)
try:
_old_value = _new_aa_table.at[_new_amino_acid, _position]
except KeyError:
_new_aa_table.at[_new_amino_acid, _position] = Decimal(frequency)
except TypeError:
raise TypeError("Weird value %s" % _new_aa_table.at[_new_amino_acid, _position])
else:
_new_aa_table.at[_new_amino_acid, _position] = Decimal(_old_value) + Decimal(frequency) # the _position with the new amino acid may appear multiple times so sum up the values
_old_value = Decimal( 0)
try:
_old_value = _old_aa_table.at[_old_amino_acid, _position]
except KeyError:
_old_aa_table.at[_old_amino_acid, _position] = Decimal(frequency)
except TypeError:
raise TypeError("Weird value %s" % _old_aa_table.at[_old_amino_acid, _position])
else:
_old_aa_table.at[_old_amino_acid, _position] = Decimal(_old_value) + Decimal(frequency) # the _position with the original amino acid will appear multiple times so sum up the values
_old_value = Decimal(0)
try:
_old_value = Decimal(_old_codon_table.at[_old_codon, _position])
except KeyError:
_old_codon_table.at[_old_codon, _position] = Decimal(frequency) # the _position with the original codon will appear multiple times so sum up the values
except TypeError:
raise TypeError("Weird value %s" % _old_codon_table.at[_old_codon, _position])
else:
_old_codon_table.at[_old_codon, _position] = Decimal(_old_codon_table.at[_old_codon, _position]) + Decimal(frequency) # rewrite np.float64 into Decimal
_old_value = Decimal(0)
# try:
# _new_codon_table.at[_new_codon, _position] = Decimal(_new_codon_table.at[_new_codon, _position]) + Decimal(frequency)
# except KeyError:
_new_codon_table.at[_new_codon, _position] = Decimal(frequency) # the _position and a codon should appear just once so no reason to sum up new value with previous
# except TypeError:
# # sanitize nan values in the table
# raise TypeError("Weird value %s" % _new_codon_table.at[_new_codon, _position])
if myoptions.debug:
print(f"Debug: OriginalDataFrameRowNumber: {df_index}, Old: {_old_amino_acid}, New: {_new_amino_acid}, Frequency: {frequency}")
if myoptions.debug:
# print tables with summed up frequencies, notably each has different amount of rows which differ from the original TSV row number as well
for t in (_old_aa_table, _new_aa_table, _old_codon_table, _new_codon_table):
print(f"Debug: len({t})={len(t)}")
if myoptions.debug:
if myoptions.aminoacids:
print(_old_aa_table)
print(_new_aa_table)
else:
print(_old_codon_table)
print(_new_codon_table)
return (
_amino_acids, _codons_whitelist, _codons_whitelist2, _final_sorted_whitelist,
_unique_aa_positions, _unique_codon_positions,
_old_aa_table, _new_aa_table, _old_codon_table, _new_codon_table,
_calculated_aa_offset,
)
def setup_matplotlib_figure(
title_data, aln_rows, matrix_name, amino_acids, codons_whitelist,
final_sorted_whitelist, unique_aa_positions, unique_codon_positions,
new_aa_table, new_codon_table,
):
"""Configure matplotlib figure, axes, labels, ticks, and the frequency bar chart."""
#print(plt.rcParams["font.sans-serif"][0])
#print(plt.rcParams["font.monospace"][0])
matplotlib.rcParams['font.family'] = 'monospace'
#matplotlib.rcParams["font.monospace"] = ["DejavuSans"]
# trigger core fonts for PDF backend
plt.rcParams["pdf.use14corefonts"] = True
# trigger core fonts for PS backend
plt.rcParams["ps.useafm"] = True
#plt.text(2, 0.65, 'Version %s' % VERSION)
print(f"Info: matplotlib.get_backend={matplotlib.get_backend()}")
_figure, (_ax1, _ax3, _ax4) = plt.subplots(1, 3, figsize=(16, 9), width_ratios=[55, 1, 6]) # default was 6.4 x 4.8 in and 100dpi
# aln_rows contain number of rows in the ALN file typically each read is counted so roughly divide it by two to get at about number of amplicons sequenced
if myoptions.aminoacids:
if myoptions.shortlegend:
_xlabel = 'Amino acid position'
else:
_xlabel = 'Amino acid position%sbased on %s ALN rows, matrix %s, colormap %s, mutation_scatter_plot.py %s' % (os.linesep, aln_rows.strip(os.linesep), matrix_name, myoptions.colormap, VERSION)
else:
if myoptions.shortlegend:
_xlabel = 'Codon position'
else:
_xlabel = 'Codon position%sbased on %s ALN rows, matrix %s, colormap %s, mutation_scatter_plot.py %s' % (os.linesep, aln_rows.strip(os.linesep), matrix_name, myoptions.colormap, VERSION)
_ax1.set_xlabel(_xlabel, fontsize=14)
if myoptions.aminoacids:
_ax1.set_ylabel('Introduced amino acid changes', fontsize=14)
_ax1.set_title(title_data, fontsize=18)
if myoptions.xmin:
# --offset 299 --xmin 305 --xmax 485 ## respect xmin and do not make the figure wider spanning into primer region
_xmin = myoptions.xmin
else:
_xmin = min(unique_aa_positions) - 1
if myoptions.xmax:
_xmax = myoptions.xmax
else:
_xmax = max(unique_aa_positions) + 1
else:
_ax1.set_ylabel('Introduced codon changes', fontsize=14)
_ax1.set_title(title_data, fontsize=14)
if myoptions.xmin:
# --offset 299 --xmin 305 --xmax 485 ## respect xmin and do not make the figure wider spanning into primer region
_xmin = myoptions.xmin
else:
_xmin = min(unique_codon_positions) - 1
if myoptions.xmax:
_xmax = myoptions.xmax
else:
_xmax = max(unique_codon_positions) + 1
_ax1.set_xlim(myoptions.xaxis_label_start or _xmin, _xmax) # start X-axis from 1, not zero
_ax1.xaxis.set_major_locator(ticker.MultipleLocator(myoptions.xaxis_major_ticks_spacing))
_ax1.xaxis.set_minor_locator(ticker.MultipleLocator(myoptions.xaxis_minor_ticks_spacing))
if myoptions.debug:
print(f"Debug: X-axis1: {_xmin}-{_xmax}")
# add a barchart with relative changes
#print(str(unique_aa_positions)) # these are one-based positions
#print(f"Length of unique_aa_positions is {len(unique_aa_positions)}")
if myoptions.aminoacids:
_total_frequencies = np.sum(np.abs(new_aa_table), axis=0)
else:
_total_frequencies = np.sum(np.abs(new_codon_table), axis=0)
if myoptions.debug:
print(f"Debug: len(_total_frequencies)={len(_total_frequencies)}, _total_frequencies={str(_total_frequencies.to_list())}")
# BUG: we cannot change X-axis xticks on one X-axis without resetting xmin and xmax for the twinx plot
# It makes no differenceif we use "ax2 = ax.twinx()" or if we use "fig, (ax, ax2) = plt.subplots(1, 2, sharex=True)"
# https://github.com/matplotlib/matplotlib/issues/6860
# https://github.com/matplotlib/matplotlib/pull/7904
# https://github.com/matplotlib/matplotlib/pull/7528
# https://github.com/chartjs/Chart.js/issues/3484
if myoptions.aminoacids:
# ax.set_xticks(np.arange(0, max(unique_aa_positions), round(round(max(unique_aa_positions)/20)/10.0)*10)) # this breaks syncing of ax and ax2 axes to be out-of-sync, worked around via plt.locator_params()
#ax.set_xticklabels(np.arange(0, max(unique_aa_positions)), rotation=90, ha='right') # rotate X-axis legend
# https://stackoverflow.com/questions/53747298/how-to-format-axis-tick-labels-from-number-to-thousands-or-millions-125-436-to#53747693
#ax.xaxis.set_major_formatter(ticker.FuncFormatter(lambda x, pos: '{:,.0f}'.format(x/1))) # get rid of non-real numbers on the X-axis,like 2.5
_ax1.xaxis.set_tick_params(labelsize=14)
_ax1.tick_params(axis='x', which='both', labelsize=14)
_y_ticks = np.arange(len(amino_acids))
_ax1.set_yticks(_y_ticks)
_ax1.set_yticklabels(amino_acids, fontsize=14)
else:
# ax.set_xticks(np.arange(0, max(unique_codon_positions), round(round(max(unique_aa_positions)/20)/10.0)*10)) # this breaks syncing of ax and ax2 axes to be out-of-sync, worked around via plt.locator_params()
#ax.set_xticklabels(np.arange(0, max(unique_codon_positions)), rotation=90, ha='right') # rotate X-axis legend
# https://stackoverflow.com/questions/53747298/how-to-format-axis-tick-labels-from-number-to-thousands-or-millions-125-436-to#53747693
#ax.xaxis.set_major_formatter(ticker.FuncFormatter(lambda x, pos: '{:,.0f}'.format(x/1))) # get rid of non-real numbers on the X-axis,like 2.5
_ax1.xaxis.set_tick_params(labelsize=14)
_ax1.tick_params(axis='x', which='both', labelsize=14)
_y_ticks = np.arange(len(codons_whitelist))
_ax1.set_yticks(_y_ticks)
_ax1.set_yticklabels([_pairs[0] + ' (' + _pairs[1] + ') ' if _pairs[1] not in ('INS', 'DEL') else _pairs[0] + ' (' + _pairs[1] + ')' for _pairs in final_sorted_whitelist], fontsize=8) # sorted by amino acids