-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
1965 lines (1783 loc) · 90.3 KB
/
main.py
File metadata and controls
1965 lines (1783 loc) · 90.3 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
# FILE : main.py
# WRITER : Elal Gilboa , elal.gilboa , 323083188
# EXERCISE : intro2cs final project 2025
# DESCRIPTION: This program execute the biosequence final project
# STUDENTS I DISCUSSED THE EXERCISE WITH: None
# WEB PAGES I USED: https://www.w3schools.com/python/ref_string_split.asp
# https://docs.python.org/3/library/argparse.html
# https://www.youtube.com/watch?v=6Q56r_fVqgw
# https://en.wikipedia.org/wiki/FASTQ_format
# https://docs.pytest.org/en/stable/how-to/monkeypatch.html
# NOTES: None
# Bio_sequence_project version 3.0
# changes:
# 1. validate_flag_combinations has been refactored into 4 simpler functions
# 2. ALN file format has been changed - to contain an Alignment object and not reads dict
# 3. __determine_status func in Alignment has been changed - to count the mapped
# reads statuses in class self.__variables and also to set genome sources
# for each read using read class variable "sources" which is used in dumpalign
# 4. load_fasta and load_fastq turned into generators functions
# !/usr/bin/env python3
############################### Imports #####################################
import argparse
import gzip, pickle
from typing import *
from collections import Counter
import os
import json
from functools import reduce
#############################################################################
class Kmer:
"""This class creates an K-mer object which is represented by a np array
of strings. each cell in the array contain one of the following letters:
A,T,C,G which represent the nucleotide bases in the DNA.
parms:
data = contain the np array of letters in length K
length = the K length of this K-MER object
specific = set to be True/False if the K-mer exist in many genomes on it is
unique to only onr genome.
id = a unique reference to identify this K-mer
locations = a list of locations in which this Kmer appear in a Read
sources_refs = list of identifiers of the K-mer source/s"""
__id_counter: int = 0
def __init__(self, sequence: str, locations: List[int]):
self.__data: str = sequence
self.__length: int = len(sequence)
self.__specific: bool = False # default data
self.__id: int = Kmer.__id_counter
Kmer.__id_counter += 1
self.__loc_in_read: List[int] = locations
self.__sources_refs: List[str] = []
def __eq__(self, other: object) -> bool:
"""This function compare 2 K-mers object by their data values and length
their id and location may be different"""
if type(other) != Kmer:
return False
elif self.__length != cast(Kmer, other).__length:
return False
else:
for i in range(self.__length):
if self.__data[i] != cast(Kmer, other).__data[i]:
return False
return True
def __str__(self):
"""This func return a string to print a Kmer object"""
return (f"K-mer id: {self.__id},"
f" data: {self.__data}," +
f" locations in read: {self.__loc_in_read}," +
f" matching reference sources: {self.__sources_refs}," +
f" specific K-mer: {self.__specific}")
def __repr__(self):
return (f"K-mer id: {self.__id},"
f" data: {self.__data}," +
f" locations in read: {self.__loc_in_read}," +
f" matching reference sources: {self.__sources_refs}," +
f" specific K-mer: {self.__specific}")
def __len__(self) -> int:
return self.__length
def get_data(self) -> str:
return self.__data
def get_location(self):
return self.__loc_in_read
def get_id(self):
return self.__id
def get_specific_status(self):
return self.__specific
def set_specific(self, status: bool):
"""Func set specific status of Kmer - if it appears in more than one
it is not specific and if it only appears in one than it's specific"""
self.__specific = status
def get_sources(self):
return self.__sources_refs
def add_source(self, sources: List[str]):
"""This func adds another sources to the reference sources list"""
for source in sources:
self.__sources_refs.append(source)
def reverse_data(self) -> str:
"""this func return the reverse complement form of its sequence data"""
new_data: List[str] = []
for char in self.__data[::-1]:
if char == "A":
new_data.append("T")
elif char == "T":
new_data.append("A")
elif char == 'C':
new_data.append('G')
elif char == 'G':
new_data.append('C')
return ''.join(new_data)
class Read:
"""This class represent a DNA read from an NGS machine, a read contain
samples of valid and un valid sequences of A,T,C,G nucleotide bases in the
DNA of an unknown object.
parms:
data = is a string of all A,T,C,G data received from the NGS machine
quality = a string describing the quality of each nucleotide bases in data.
the quality is represented by a chat in ASCII and the quality score is the
ASCII VALUE-30 for each character
status = could be unmapped / ambiguously_mapped / uniquely_mapped
id = a unique identifier for the data file for each sample
"""
def __init__(self, header: str, sequence: str, quality: str):
self.__data: str = sequence
self.__quality: str = quality
self.__status: str = ""
self.__header: str = header
self.__sources: List[str] = []
self.__orientation: str = "Forward"
self.__reversed_data: str = self.__reverse_data(self.__data)
def __str__(self):
"""This func return a string to print a Read object"""
if self.__status == "":
status = "NOT DEFINED"
return (f"Read id: {self.__header} \n"
f"data: {self.__data} \n" +
f"quality: {self.__quality} \n" +
f"read mapping status: {status}")
else:
return (f"Read id: {self.__header} \n"
f"data: {self.__data} \n" +
f"quality: {self.__quality} \n" +
f"read mapping status: {self.__status}")
def __eq__(self, other: object):
if type(other) != Read:
return False
elif len(self.__data) != len(cast(Read, other).__data):
return False
elif self.__data != cast(Read, other).__data:
return False
else:
return True
def get_data(self) -> str:
return self.__data
def get_status(self) -> str:
return self.__status
def get_quality(self) -> str:
return self.__quality
def add_sources(self, sources: List[str]):
for source in sources:
self.__sources.append(source)
def get_read_sources(self):
return self.__sources
def get_header(self):
return self.__header
def get_orient(self):
return self.__orientation
def set_orient(self, orient: str):
self.__orientation = orient
def __reverse_data(self, sequence: str) -> str:
"""this func return the reverse complement form of sequence data"""
new_data: List[str] = []
for char in sequence[::-1]:
if char == "A":
new_data.append("T")
elif char == "T":
new_data.append("A")
elif char == 'C':
new_data.append('G')
elif char == 'G':
new_data.append('C')
return ''.join(new_data)
def set_status(self, status: str) -> bool:
"""This func set Read status to be as received from the mapping process
and could only be one of 3 valid statuses"""
VALID_STATUSES = ["Unmapped", "Ambiguous", "Unique"]
if status not in VALID_STATUSES:
return False
else:
self.__status = status
return True
def extract_kmers(self, k):
"""This func return a dictionary of all k-mers in length K from this read
as Keys and their location/s in data as Value"""
data = self.__data
k_mers_dict: Dict[str, List[int]] = {}
if k > len(data):
raise ValueError(
f"K size is smaller than read's length {self.__header}")
for i in range(len(data) - k + 1):
kmer: str = data[i:i + k]
if 'N' in kmer:
continue
if kmer not in k_mers_dict:
k_mers_dict[kmer] = [i]
else:
k_mers_dict[kmer].append(i)
return k_mers_dict
class Reference:
"""This class represent a genome reference from a FASTA file. Each genome
has a unique header and the content of the reference made of A,T,C,G.
parms:
genome = a string representing the reference data
header = a strig representing the reference identifier"""
__id_counter: int = 0
def __init__(self, header: str, sequence: str):
self.__genome: str = sequence
self.__header: str = header
self.__kmers: Dict[str, List[int]] = {}
self.__id: int = Reference.__id_counter
Reference.__id_counter += 1
def __str__(self):
"""This func return a string to print a Reference object"""
return (f"reference header:{self.__header}, \n"
f"genome data:{self.__genome}")
def __len__(self) -> int:
return len(self.__genome)
def get_header(self):
return self.__header
def get_genome(self):
return self.__genome
def get_kmers(self):
return self.__kmers
def get_id(self):
return self.__id
def extract_kmers(self, k):
"""This func return a dictionary of all k-mers in length K from this
reference as Keys and their location/s in data as Value"""
data = self.__genome
k_mers_dict: Dict[str, List[int]] = {}
if k > len(data):
raise ValueError(
f"K size is smaller than genome's length {self.__header}")
for i in range(len(data) - k + 1):
kmer = data[i:i + k]
if 'N' in kmer:
continue
if kmer not in k_mers_dict:
k_mers_dict[kmer] = [i]
else:
k_mers_dict[kmer].append(i)
self.__kmers = k_mers_dict
return k_mers_dict
class KmersDB:
"""K-mers DB is built as a dictionary in which contain as keys all Kmers
string content (from all references together) and as values a dictionary
which contain a ref_header as key and a list of location in which this
K-mer appear in it as value.
parms:
refs_kmers = the main database, the reason the kmers string are the keys
it because string are hashable so the search in this major database should
be more efficient
"""
def __init__(self):
self.__refs_kmers: Dict[str, Dict[str, List[int]]] = {}
# {k_mers_str_from_all_refs: {ref_head: List[k_mer_loc_in_ref]}
self.__similarity: Dict[str, Dict[str, Any]] = {}
def __str__(self):
"""This func return a printable string of the DB"""
result = ""
DB = self.__refs_kmers
for kmer_key, locs_in_refs_dict in DB.items():
result += f"K-mer: {kmer_key} \n"
for ref_header, lst_of_locs in locs_in_refs_dict.items():
result += (
f"appear in reference header: {ref_header}" +
f" in locations: {lst_of_locs} \n")
return result
def inset_ref_data(self, ref_header: str,
kmers_dict: Dict[str, List[int]]) -> bool:
"""This func receive a reference_header and all k_mers extracted from
this reference and insert them to DB"""
for kmer_data, locs_in_ref in kmers_dict.items():
if kmer_data not in self.__refs_kmers:
self.__refs_kmers[kmer_data] = {}
self.__refs_kmers[kmer_data][ref_header] = locs_in_ref
else:
if ref_header in self.__refs_kmers[kmer_data]:
raise ValueError(
f"Duplicate ref_header '{ref_header}' for K-mer '{kmer_data}'")
self.__refs_kmers[kmer_data][ref_header] = locs_in_ref
return True
def get_ref_db(self) -> Dict[str, Dict[str, List[int]]]:
"""This func return the build DB of reference Kmers"""
return self.__refs_kmers
def get_kmer_size(self) -> int:
"""This func return the size of each Kmer key in DB"""
for key, value in self.__refs_kmers.items():
return len(key)
return 0
def remove_ref_from_inner_dict(self, ref_header: str) -> None:
"""This func receive a ref_header and remove it from all the inner dicts
in DB. Func return True if action is successful and False otherwise"""
for kmer in list(self.__refs_kmers.keys()):
if ref_header in self.__refs_kmers[kmer]:
del self.__refs_kmers[kmer][ref_header]
# if no ref_headers remain for this kmer, delete the k-mer key
# from outer Dict
if not self.__refs_kmers[kmer]:
del self.__refs_kmers[kmer]
def get_value(self, key: str):
"""This func receive a Key and return the value from DB for this Key.
If key does not exist raise a KeyError"""
if key in self.__refs_kmers:
return self.__refs_kmers[key]
else:
raise KeyError(f"key {key} does not exist in Ref Kmers DB")
def __repr__(self):
"""This func return a printable string of the DB"""
result = ""
DB = self.__refs_kmers
for kmer_key, locs_in_refs_dict in DB.items():
result += f"K-mer: {kmer_key} \n"
for ref_header, lst_of_locs in locs_in_refs_dict.items():
result += (
f"appear in reference header: {ref_header}" +
f" in locations: {lst_of_locs} \n")
return result
def set_similarity(self, similarity) -> None:
"""This func recieve a similarity dictionary and save it in DB. it is
used when used choose reference command and do not print results"""
self.__similarity = similarity
def get_similarity(self):
"""This func return a similarity dictionary - to be printed in dumpref"""
return self.__similarity
class Alignment:
"""This class represent an alignment file between a DB of references genomes
and Reads of DNA samples from an unknown organism and applying the Pseudo
Alignment algorithm.
parms:
references = a dictionary of Reference objects {ref_header, Reference Object}
Kmers_DB = a Kmer_DB object of all kmers extracted from References
{kmers_data_from_all_refs: {ref_header: List[kmers_locs_in_ref}}
reads = a dictionary of Read object received in a FASTAQ file
{read_header: Read object}
reads_kmers_db = a dictionary of {read_header: Kmers_for_each_read} a list
of all Kmers extracted from a read.
total_unmapped = a counter for all Kmers in reads_kmers_db which received a
status unmapped.
total_ambiguous = same as unmapped
total_unique = same as unmapped"""
def __init__(self):
self.__references: List[str] = []
self.__refs_kmers_db: KmersDB = KmersDB()
self.__reads: Dict[str, Read] = {}
self.__reads_kmers_db: Dict[str, List[Kmer]] = {}
self.__total_unmapped: int = 0
self.__total_ambiguous: int = 0
self.__total_unique: int = 0
self.__coverage_sum: Dict[str, Dict[str, Any]] = {}
self.__quality_stats: List[int] = []
def set_references(self, references: List[str]) -> None:
"""Func receive a list of genomes' ref headers and set it to as
self.__references."""
self.__references = references
def set_reads(self, reads: Dict[str, Read]) -> None:
"""func receive a dict or reads from FASTAQ file and set it to reads.
Dict in format {read_header, Read object}"""
self.__reads = reads
def set_ref_kmers_db(self, ref_kmers_db: KmersDB):
self.__refs_kmers_db = ref_kmers_db
def get_reads(self):
return self.__reads
def get_references(self):
return self.__references
def get_ref_kmers_DB(self):
return self.__refs_kmers_db
def get_reads_kmers_db(self):
return self.__reads_kmers_db
def set_quality_stats(self, quality_stats: List[int]):
self.__quality_stats = quality_stats
def get_quality_stats(self):
return self.__quality_stats
def set_coverage_sum(self, coverage: Dict[str, Dict[str, Any]]):
self.__coverage_sum = coverage
def get_coverage_sum(self):
return self.__coverage_sum
def get_reads_stats(self) -> Dict[str, int]:
"""This func return the reads statistics data in a dictionary with each
data and it's value"""
UNIQUE, AMBIG, UNMAPPED = "unique_mapped_reads", "ambiguous_mapped_reads", "unmapped_reads"
reads_stats: Dict[str, int] = {UNIQUE: self.__total_unique,
AMBIG: self.__total_ambiguous,
UNMAPPED: self.__total_unmapped}
return reads_stats
def __calc_mean_quality(self, sequence: str):
"""This func receive a read and calculates it's mean quality. Func return
a float which is the mean quality score of this read"""
sum_ascii_score = lambda total, char: total + (ord(char) - 33)
result = reduce(sum_ascii_score, sequence, 0) / len(sequence)
return result
def build_reads_kmers_db(self, k_size: int, mkq: int) -> int:
"""This func receive a K int and crete a DB of all Kmers in length K
from all reads in self.__reads. Func create a Dict[str, List[Kmer]] a
dictionary of kmer objects matching to each read header as key. Func
filter out of DB low quality reads in case mkq is not None and return
the number of filtered out Kmers"""
reads_kmers_db: Dict[str, List[Kmer]] = {}
filtered_out: int = 0
for read_header, read in self.__reads.items():
read_kmers_dict: Dict[str, List[int]] = read.extract_kmers(k_size)
list_of_kmers: List[Kmer] = []
quality: str = read.get_quality()
for kmer_data, locs_in_read in read_kmers_dict.items():
if mkq is not None:
first_appearance_index: int = locs_in_read[0]
kmer_quality: str = quality[
first_appearance_index: first_appearance_index + k_size]
mean_quality: float = self.__calc_mean_quality(
kmer_quality)
if mean_quality >= mkq:
new_kmer = Kmer(kmer_data, locs_in_read)
list_of_kmers.append(new_kmer)
else:
filtered_out += 1
else:
new_kmer = Kmer(kmer_data, locs_in_read)
list_of_kmers.append(new_kmer)
if read_header not in reads_kmers_db:
reads_kmers_db[read_header] = list_of_kmers
else:
raise KeyError(
f"read Header {read_header} already exist in reads_kmers_db")
self.__reads_kmers_db = reads_kmers_db
return filtered_out
def __find_matching_ref(self, sequence: str) -> Dict[str, List[int]]:
"""Func receive a Kmer data sequence and check the ref_kmers_db for
matches. func return the inner dictionary if there's a match (one or many)
and return {} in there's No match. The search in ref_kmers_db is O(1)
because sequence is the key of this DB and it's hashable"""
try:
return self.__refs_kmers_db.get_value(sequence)
except KeyError:
return {}
def __count_sources(self, kmers_list: List[Kmer]) -> Counter:
"""This func receive a list of Kmers and return a Counter object which
contains Kmer sources as Keys and their count from kmer_list"""
kmers_sources_count: Counter = Counter()
for kmer in kmers_list:
for source in kmer.get_sources():
if source in kmers_sources_count:
kmers_sources_count[source] += 1
else:
kmers_sources_count[source] = 1
return kmers_sources_count
def __validate_unique_status(self, map_count: int,
combined_counts: Counter,
p: int) -> str:
"""This func is called after mapping process determined a read as
Unique and validate it using the unspecific Kmers. Func receive the
assumed source reference header, the number of Kmers pointing to it,
a combined Counter object of all Kmers results"""
AMBIGUOUS, UNIQUE = "Ambiguous", "Unique"
combined_max_source: str = max(combined_counts,
key=lambda k: combined_counts[k])
combined_max_count: int = combined_counts[combined_max_source]
if combined_max_count - map_count > p:
return AMBIGUOUS
else:
return UNIQUE
def __extract_ambiguous_sources(self, combined_count: Counter,
map_count: int, original_source: str) -> \
List[str]:
"""
This func receive a Counter of specific and unspecific Kmers for cases
in which mapping process resulted Unique status and then validated and
turned into ambiguous. In these cases the read's sources are the original
mapped genome and all the other genomes received higher count of combined
Kmers. Func return a list of read's sources"""
ambiguous_sources = [
genome for genome, count in combined_count.items()
if count > map_count]
if original_source not in ambiguous_sources:
ambiguous_sources.append(original_source)
return ambiguous_sources
def __determine_status(self, specific_kmers: List[Kmer],
unspecific_kmers: List[Kmer], m: int,
p: int) -> Tuple[str, List[str]]:
"""Func receive a list of Kmers specific and unspecific received from
a read and determine the read's mapping status. m and p are thresholds
for minimum difference between highest and second highest mapped genomes.
Func return the determined status and a list of read's sources for later
use in dumpalign"""
UNMAPPED, AMBIGUOUS, UNIQUE = "Unmapped", "Ambiguous", "Unique"
REF_HEADER_LOC, MATCHES_COUNT = 0, 1
FIRST, SECOND = 0, 1
status: str = ""
combined_count: Counter = Counter()
ambiguous_sources: List[str] = []
read_sources: List[str] = []
if len(specific_kmers) == 0 and len(unspecific_kmers) == 0:
# none of the K-mers in read match any of the genomes in DB.
self.__total_unmapped += 1
return UNMAPPED, read_sources
specific_source_count: Counter = self.__count_sources(specific_kmers)
unspecific_source_count: Counter = self.__count_sources(
unspecific_kmers)
# {source_ref_header, num_kmers_pointing_ref}
if len(specific_source_count) == 0:
# all specific Kmers are unmapped to any genome - so read is unmapped
self.__total_unmapped += 1
return UNMAPPED, read_sources
elif len(specific_source_count) == 1:
# all specific Kmers point to the same genome
unique_genome: str = list(specific_source_count.keys())[0]
if p >= 1:
# mapping process determined unique, yet needs to be validated
map_count1: int = max(specific_source_count.values())
status = self.__validate_unique_status(map_count1,
specific_source_count + unspecific_source_count,
p)
if status == UNIQUE:
read_sources.append(unique_genome)
self.__total_unique += 1
return UNIQUE, read_sources
else:
# Extract ambiguous sources
combined_count = specific_source_count + unspecific_source_count
ambiguous_sources = self.__extract_ambiguous_sources(
combined_count, map_count1, unique_genome)
for source in ambiguous_sources:
read_sources.append(source)
self.__total_ambiguous += 1
return AMBIGUOUS, read_sources
else:
read_sources.append(unique_genome)
self.__total_unique += 1
return UNIQUE, read_sources
else:
# specific genomes point to more than one genome
top_two: List[
Tuple[str, int]] = specific_source_count.most_common(2)
most_common: Tuple[str, int] = top_two[FIRST]
sec_most_common: Tuple[str, int] = top_two[SECOND]
if cast(int, most_common[MATCHES_COUNT]) - cast(int,
sec_most_common[
MATCHES_COUNT]) >= m:
if p >= 1:
# mapping process determined unique, yet needs to be validated
map_count: int = cast(int, most_common[MATCHES_COUNT])
max_map_source: str = cast(str,
most_common[REF_HEADER_LOC])
status = self.__validate_unique_status(
map_count,
specific_source_count + unspecific_source_count, p)
if status == UNIQUE:
read_sources.append(max_map_source)
self.__total_unique += 1
return UNIQUE, read_sources
else:
# Extract ambiguous sources
combined_count = specific_source_count + unspecific_source_count
ambiguous_sources = self.__extract_ambiguous_sources(
combined_count, map_count, max_map_source)
for source in ambiguous_sources:
read_sources.append(source)
self.__total_ambiguous += 1
return AMBIGUOUS, read_sources
else:
read_source: str = cast(str, most_common[REF_HEADER_LOC])
read_sources.append(read_source)
self.__total_unique += 1
return UNIQUE, read_sources
else:
# the difference between most and second common is less than
# m which is a threshold for minimum difference, by default it's 1
ambiguous_sources = list(specific_source_count.keys())
# in this case all genomes which this read was partially mapped
# to are countable and added to read's source list
for source in ambiguous_sources:
read_sources.append(source)
self.__total_ambiguous += 1
return AMBIGUOUS, read_sources
def __reverse_lst_of_kmers(self, lst_of_kmers: List[Kmer]) -> List[Kmer]:
"""This func receive a list of Kmer objects and return a reversed list
of Kmers with reversed data sequence. Func created new reversed Kmer from
each original Kmer. Notice - the locations in reversed Kmer are not accurate
they match the original and not the new Kmer."""
reversed_lst: List[Kmer] = []
for kmer in lst_of_kmers:
data: str = kmer.reverse_data()
locations: List[int] = kmer.get_location()
rev_kmer = Kmer(data, locations)
reversed_lst.append(rev_kmer)
return reversed_lst
def __sort_specific_kmers(self, lst_of_kmers: List[Kmer], mg: int) -> \
Tuple[List[Kmer], List[Kmer], int]:
"""This func receive a list of Kmers and sort them into specific and
unspecific based on their match to a genome using __find_matching_ref().
func also receive a threshold mg, if it's not none func remove kmers
which are highly redundant from mapping process. Func return the specific
and unspecific Kmers list and the num of removed Kmers"""
SPECIFIC_KMER = True
UNSPECIFIC_KMER = False
filtered_hq_kmers: int = 0
specific_kmers: List[Kmer] = []
unspecific_kmers: List[Kmer] = []
sources: List[str] = []
for kmer in lst_of_kmers:
matches: Dict[str, List[int]] = self.__find_matching_ref(
kmer.get_data())
if len(matches) > 1: # more than one genome match this k-mer
sources = list(matches.keys())
if mg is not None:
if len(sources) <= mg:
kmer.add_source(sources)
kmer.set_specific(UNSPECIFIC_KMER)
unspecific_kmers.append(kmer)
else:
filtered_hq_kmers += 1
else:
kmer.add_source(sources)
kmer.set_specific(UNSPECIFIC_KMER)
unspecific_kmers.append(kmer)
elif len(matches) == 1:
# there is only one genome matching
sources = list(matches.keys())
kmer.add_source(sources)
kmer.set_specific(SPECIFIC_KMER)
specific_kmers.append(kmer)
return specific_kmers, unspecific_kmers, filtered_hq_kmers
def __determine_orientation(self, status_f: str, status_r: str,
specific_kmers: List[Kmer],
unspecific_kmers: List[Kmer],
rev_specific_kmers: List[Kmer],
rev_unspecific_kmers: List[Kmer]) -> bool:
"""This func receive a determined orientation for forward and reversed
read sequence, Func return True if read should be handled reversed and
False if it should remain Forward"""
UNIQUE, AMBIG = "Unique", "Ambiguous"
if status_f == UNIQUE and status_r != UNIQUE:
# continue with forward
return False
elif status_r == UNIQUE and status_f != UNIQUE:
# continue with reverse
return True
elif status_f == UNIQUE and status_r == UNIQUE:
# chose the one with more unique Kmers, choose forward if tied
return len(rev_specific_kmers) > len(specific_kmers)
elif status_f == AMBIG and status_r == AMBIG:
# chose the orientation with more total matched Kmers
# sum the unique and ambig kmers for each orientation (if kmer is
# unmapped it will not be on either lists)
total_kmers_f = len(specific_kmers) + len(unspecific_kmers)
total_kmers_r = len(rev_specific_kmers) + len(rev_unspecific_kmers)
return total_kmers_r > total_kmers_f
elif status_r == AMBIG:
# forward is unmapped so reverse is chosen
return True
else:
# choose forward - both orientations unmapped - choose forward
return False
def map_reads(self, m: int, p: int, mg: int, rev_comp: bool) -> int:
"""Func execute the pseudo alignment algorithm, and map all reads in
self.__reads. func set the status of each read to be the result of the
mapping process. For each read func check for matches in ref_kmers_db,
and if there is a match updates the Kmer sources and the read status
parms: p - unique-threshold, m - ambiguous-threshold.
mg - maximus genomes (for quality ext), rev_comp - flag (for reverse ext)
Func return the number of highly redundant kmers, filtered out and updates
the read sources for each read.
"""
REV: str = "Reverse"
filtered_hr_kmers: int = 0
rev_filtered_hr_kmers: int = 0
sum_filtered_hr_kmers: int = 0
status: str = ""
for read_header, lst_of_kmers in self.__reads_kmers_db.items():
if not rev_comp:
specific_kmers, unspecific_kmers, filtered_hr_kmers = self.__sort_specific_kmers(
lst_of_kmers, mg)
sum_filtered_hr_kmers += filtered_hr_kmers
status, read_sources = self.__determine_status(
specific_kmers, unspecific_kmers, m, p)
read = self.__reads[read_header]
read.set_status(status)
read.add_sources(read_sources)
else:
# sort Kmers in forward orientation:
specific_kmers, unspecific_kmers, filtered_hr_kmers = self.__sort_specific_kmers(
lst_of_kmers, mg)
# sort Kmers in reverse orientation:
rev_lst_of_kmers = self.__reverse_lst_of_kmers(lst_of_kmers)
rev_specific_kmers, rev_unspecific_kmers, rev_filtered_hr_kmers = self.__sort_specific_kmers(
rev_lst_of_kmers, mg)
# determine status for both orientations:
status_f, read_sources_f = self.__determine_status(
specific_kmers, unspecific_kmers, m, p)
status_r, read_sources_r = self.__determine_status(
rev_specific_kmers, rev_unspecific_kmers, m, p)
if self.__determine_orientation(status_f, status_r,
specific_kmers,
unspecific_kmers,
rev_specific_kmers,
rev_unspecific_kmers):
# continue with reverse
sum_filtered_hr_kmers += rev_filtered_hr_kmers
read = self.__reads[read_header]
read.set_status(status_r)
read.set_orient(REV)
read.add_sources(read_sources_r)
else:
# continue with forward
sum_filtered_hr_kmers += filtered_hr_kmers
read = self.__reads[read_header]
read.set_status(status_f)
read.add_sources(read_sources_f)
return sum_filtered_hr_kmers
###################################################################
def gen_read_from_fastq(filename) -> Generator:
"""This func is a generator of necessary data: header, sequence and quality
in order to create a read object. Func yield this data from FASTQ file and
return a Tuple of """
with open(filename, 'r') as file:
while True:
read_header: str = file.readline().strip()
if not read_header:
# generator reached EOF
break
if not read_header.startswith('@'):
file.close()
raise ValueError(
f"Received file {filename} format is invalid. This header: {read_header} does not start with '@'")
sequence: str = file.readline().strip()
sep: str = file.readline().strip()
if not sep.startswith('+'):
file.close()
raise ValueError(
f"Received file {filename} format is invalid. This seperator line: {sep} does not start with '+'")
quality = file.readline().strip()
if len(sequence) != len(quality):
file.close()
raise ValueError(
f"The lengths of sequence and quality don't match in this read: {read_header[1:]}\n"
f"Sequence: {sequence}\nQuality: {quality}")
yield read_header[1:], sequence, quality
def generate_reads_dict(filename: str) -> Dict[str, Read]:
"""Func receive a filename and load the FASTQ file reads Data. Func creates
Read objects from each read in file and return a dictionary of Read objects
{read_header, Read_obj}. Func is using a generator for receiving the next:
reade_header, sequence and quality from FASTQ file"""
reads: Dict[str, Read] = {}
read_generator: Generator = gen_read_from_fastq(filename)
for read_header, sequence, quality in read_generator:
new_read: Read = Read(read_header, sequence, quality)
if read_header not in reads:
reads[read_header] = new_read
else:
raise KeyError(
f"There are two Reads with the same header in FASTQ file {filename}")
return reads
def generate_ref_dict(filename: str) -> Dict[str, Reference]:
"""Func receive a filename and load the FASTA file of Genomes references.
Func creates Reference objects from each genome in file and return a dictionary
of Reference objects {ref_header, Reference_obj}"""
references: Dict[str, Reference] = {}
refs_generator: Generator = gen_ref_from_fasta(filename)
for ref_header, sequence in refs_generator:
new_ref: Reference = Reference(ref_header, sequence)
if ref_header not in references:
references[ref_header] = new_ref
else:
raise KeyError(
f"There are two Genomes with the same header in FASTA file {filename}")
return references
def gen_ref_from_fasta(filename) -> Generator:
"""func creates a generator for Reference object, for each yield func return
a ref_header and a sequence. If FASTA format is invalid func raise Exception"""
with open(filename, 'r') as file:
ref_header = None
sequence: List[str] = []
for line in file:
# file object is iterable and yield the next line
if not line:
continue
new_line: str = line.strip()
if new_line.startswith('>'):
# mark the start of a new ref_header
if ref_header:
if not sequence:
raise ValueError(
f"Invalid FASTA format: Missing description or identifier after '>'"
)
yield ref_header, ''.join(sequence)
ref_header = new_line[1:]
if not ref_header:
raise ValueError(
f"Invalid FASTA format: Header line is empty")
sequence = []
else:
# this line is part of the ref_data_sequence
sequence.append(new_line)
if ref_header:
if not sequence:
raise ValueError(
f"Invalid FASTA format: Missing description or identifier after '>'"
)
yield ref_header, "".join(sequence)
else:
raise ValueError("Invalid FASTA format: Header line is empty")
def dump_alignment_results(aln: Alignment, filename: str) -> None:
"""Func receive an Alignment object and dump it into an ALN file using
pickle and gzip to compress to bytestream"""
with gzip.open(filename, "wb") as file:
pickle.dump(aln, file)
def load_aln_file(aln_file_path: str) -> Alignment:
"""This func receive an aln_file_path and return Alignment object"""
with gzip.open(aln_file_path, "rb") as file:
aln: Alignment = pickle.load(file)
return aln
def dump_ref_kmers_db(ref_kmers_db: KmersDB, genome_bases: Dict[str, int],
filename: str) -> None:
"""Func receive a Kmers_db object and serializes this object into bytes.
Then func save this serialized bytestream as a compressed pickle file
"""
with gzip.open(filename, "wb") as file:
pickle.dump(ref_kmers_db, file)
pickle.dump(genome_bases, file)
def load_kdb_file(filename) -> Tuple[KmersDB, Dict[str, int]]:
"""Func receive a path to a KDB file and return a KmersDB object and genome
bases dictionary. using unpickling method
"""
with gzip.open(filename, "rb") as file:
ref_kmers_db: KmersDB = pickle.load(file)
genome_bases: Dict[str, int] = pickle.load(file)
return ref_kmers_db, genome_bases
def dump_aln_file(reads_mapping_results: Dict[str, Read],
filename: str) -> None:
"""Func receive a dictionary of reads results from the mapping process and
save them into an aln file using pickle and gzip modules.
"""
with gzip.open(filename, "wb") as file:
pickle.dump(reads_mapping_results, file)
def load_mapping_results(filename: str) -> Dict[str, Read]:
"""Func receive a dictionary of reads results from the mapping process and
save them into an aln file using pickle and gzip modules.
"""
with gzip.open(filename, "rb") as file:
reads_mapping_results: Dict[str, Read] = pickle.load(file)
return reads_mapping_results
def readargs(args=None) -> argparse.Namespace:
"""This function return a ParserArgs object which contain all the received
required and optional arguments from command line"""
parser = argparse.ArgumentParser(prog='Biosequence project', )
# General arguments
parser.add_argument('-t', '--task', help="task", required=True)
parser.add_argument('-g', '--genomefile',
help="Genome fasta file (multiple records)", )
parser.add_argument('-r', '--referencefile',
help="kdb file. Can be either input or name for output file", )
parser.add_argument('-k', '--kmer-size', type=int,
help="length of kmers", )
# Task specific arguments
# align
parser.add_argument('-a', '--alignfile',
help="aln file. Can be either input or name for output file", )
parser.add_argument('--reads', help="fastq reads file", )
parser.add_argument('-m', '--unique-threshold',
help="unique k-mer threshold", default=1, type=int)
parser.add_argument('-p', '--ambiguous-threhold',
help="ambiguous k-mer threshold", default=1, type=int)
# align+rc
parser.add_argument('--reverse-complement', action='store_true', )
# align+quality
parser.add_argument('--min-read-quality', type=int, )
parser.add_argument('--min-kmer-quality', type=int, )
parser.add_argument('--max-genomes', type=int, )
# coverage
parser.add_argument('--genomes', type=str)
parser.add_argument('--coverage', action='store_true')
parser.add_argument('--window-size', type=int, default=100, )
parser.add_argument('--min-coverage', type=int, default=1, )
parser.add_argument('--full-coverage', action='store_true', )
# similarity
parser.add_argument('--filter-similar', action='store_true', )
parser.add_argument('--similarity-threshold', type=float, default=0.95, )
return parser.parse_args(args)
def calc_mean_quality(sequence: str) -> float:
"""This func receive a read and calculates it's mean quality. Func return
a float which is the mean quality score of this read"""
sum_ascii_score = lambda total, char: total + (ord(char) - 33)
result = reduce(sum_ascii_score, sequence, 0) / len(sequence)
return result
def filter_lq_reads(reads: Dict[str, Read], mrq: int) -> Tuple[