forked from PelechanoLab/TIFseq2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdedup.py
executable file
·1824 lines (1445 loc) · 65 KB
/
dedup.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'''
Modified based on UMI-tools source codes
Compatible in python 2.7
'''
import os
import sys
import pysam
import collections
import itertools
import random
import logging
import re
from functools import partial
import numpy as np
import optparse
import textwrap
import copy
import time
import gzip
import inspect
import uuid
import tempfile
#import Utilities as U
global_id = uuid.uuid4()
global_benchmark = collections.defaultdict(int)
def hamming_distance(s1, s2):
assert len(s1) == len(s2)
return sum(ch1 != ch2 for ch1, ch2 in zip(s1, s2))
def breadth_first_search(node, adj_list):
searched = set()
queue = set()
queue.update((node,))
searched.update((node,))
while len(queue) > 0:
node = queue.pop()
for next_node in adj_list[node]:
if next_node not in searched:
queue.update((next_node,))
searched.update((next_node,))
return searched
def get_substr_slices(umi_length, idx_size):
'''
Create slices to split a UMI into approximately equal size substrings
Returns a list of tuples that can be passed to slice function
'''
cs, r = divmod(umi_length, idx_size)
sub_sizes = [cs + 1] * r + [cs] * (idx_size - r)
offset = 0
slices = []
for s in sub_sizes:
slices.append((offset, offset + s))
offset += s
return slices
def build_substr_idx(umis, umi_length, min_edit):
'''
Build a dictionary of nearest neighbours using substrings, can be used
to reduce the number of pairwise comparisons.
'''
substr_idx = collections.defaultdict(
lambda: collections.defaultdict(set))
slices = get_substr_slices(umi_length, min_edit + 1)
for idx in slices:
for u in umis:
u_sub = u[slice(*idx)]
substr_idx[idx][u_sub].add(u)
return substr_idx
def iter_nearest_neighbours(umis, substr_idx):
'''
Added by Matt 06/05/17
use substring dict to get (approximately) all the nearest neighbours to
each in a set of umis.
'''
for u in umis:
neighbours = set()
for idx, substr_map in substr_idx.items():
u_sub = u[slice(*idx)]
neighbours = neighbours.union(substr_map[u_sub])
neighbours.remove(u)
for nbr in neighbours:
yield u, nbr
def find_splice(cigar):
'''Takes a cigar string and finds the first splice position as
an offset from the start. To find the 5' end (read coords) of
the junction for a reverse read, pass in the reversed cigar tuple'''
offset = 0
# a soft clip at the end of the read is taken as splicing
# where as a soft clip at the start is not.
if cigar[0][0] == 4:
offset = cigar[0][1]
cigar = cigar[1:]
for op, bases in cigar:
if op in (3, 4):
# N or S: found the splice
return offset
elif op in (0, 2, 7, 8):
# M, D, = or X: reference consuming
offset += bases
elif op in (1, 5, 6):
# I, H, P: non-reference consuming
continue
else:
raise ValueError("Bad Cigar operation: %i" % op)
return False
def get_read_position(read, soft_clip_threshold):
''' get the read position (taking account of clipping) '''
is_spliced = False
if read.is_reverse:
pos = read.aend
if read.cigar[-1][0] == 4:
pos = pos + read.cigar[-1][1]
start = read.pos
if ('N' in read.cigarstring or
(read.cigar[0][0] == 4 and
read.cigar[0][1] > soft_clip_threshold)):
cigar = read.cigar[::-1]
is_spliced = find_splice(cigar)
else:
pos = read.pos
if read.cigar[0][0] == 4:
pos = pos - read.cigar[0][1]
start = pos
if ('N' in read.cigarstring or
(read.cigar[-1][0] == 4 and
read.cigar[-1][1] > soft_clip_threshold)):
is_spliced = find_splice(read.cigar)
return start, pos, is_spliced
def get_barcode_read_id(read, cell_barcode=False, sep="_"):
''' extract the umi +/- cell barcode from the read id using the
specified separator '''
try:
if cell_barcode:
umi = read.qname.split(sep)[-1].encode('utf-8')
cell = read.qname.split(sep)[-2].encode('utf-8')
else:
umi = read.qname.split(sep)[-1].encode('utf-8')
cell = None
return umi, cell
except:
raise ValueError(
"Could not extract UMI +/- cell barcode from the read"
"ID, please check UMI is encoded in the read name")
def remove_umis(adj_list, cluster, nodes):
'''removes the specified nodes from the cluster and returns
the remaining nodes '''
# list incomprehension: for x in nodes: for node in adj_list[x]: yield node
nodes_to_remove = set([node
for x in nodes
for node in adj_list[x]] + nodes)
return cluster - nodes_to_remove
def get_average_umi_distance(umis):
if len(umis) == 1:
return -1
dists = [hamming_distance(x, y) for
x, y in itertools.combinations(umis, 2)]
return float(sum(dists))/(len(dists))
def detect_bam_features(bamfile, n_entries=1000):
''' read the first n entries in the bam file and identify the tags
available detecting multimapping '''
inbam = pysam.Samfile(bamfile)
inbam = inbam.fetch(until_eof=True)
tags = ["NH", "X0", "XT"]
available_tags = {x: 1 for x in tags}
for n, read in enumerate(inbam):
if n > n_entries:
break
if read.is_unmapped:
continue
else:
for tag in tags:
if not read.has_tag(tag):
available_tags[tag] = 0
return available_tags
class UMIClusterer:
'''A functor that clusters a dictionary of UMIs and their counts.
The primary return value is either a list of representative UMIs
or a list of lists where each inner list represents the contents of
one cluster.
Optionally:
- identify the parent UMIs and return:
- selected reads
- umis
- counts
The initiation of the functor defines the methods:
** get_adj_list ** - returns the edges connecting the UMIs
** get_connected_components ** - returns clusters of connected components
using the edges in the adjacency list
** get_groups ** - returns the groups of umis,
with the parent umi at position 0
Note: The get_adj_list and connected_components methods are not required by
all custering methods. Where there are not required, the methods return
None or the input parameters.
'''
# "get_best" methods #
def _get_best_min_account(self, cluster, adj_list, counts):
''' return the min UMI(s) need to account for cluster'''
if len(cluster) == 1:
return list(cluster)
sorted_nodes = sorted(cluster, key=lambda x: counts[x],
reverse=True)
for i in range(len(sorted_nodes) - 1):
if len(remove_umis(adj_list, cluster, sorted_nodes[:i+1])) == 0:
return sorted_nodes[:i+1]
def _get_best_percentile(self, cluster, counts):
''' return all UMIs with counts >1% of the
median counts in the cluster '''
if len(cluster) == 1:
return list(cluster)
else:
threshold = np.median(list(counts.values()))/100
return [read for read in cluster if counts[read] > threshold]
# "get_adj_list" methods #
def _get_adj_list_adjacency(self, umis, counts, threshold):
''' identify all umis within hamming distance threshold'''
adj_list = {umi: [] for umi in umis}
if len(umis) > 25:
umi_length = len(umis[0])
substr_idx = build_substr_idx(umis, umi_length, threshold)
iter_umi_pairs = iter_nearest_neighbours(umis, substr_idx)
else:
iter_umi_pairs = itertools.combinations(umis, 2)
for umi1, umi2 in iter_umi_pairs:
if hamming_distance(umi1, umi2) <= threshold:
adj_list[umi1].append(umi2)
adj_list[umi2].append(umi1)
return adj_list
def _get_adj_list_directional(self, umis, counts, threshold=1):
''' identify all umis within the hamming distance threshold
and where the counts of the first umi is > (2 * second umi counts)-1'''
adj_list = {umi: [] for umi in umis}
if len(umis) > 25:
umi_length = len(umis[0])
substr_idx = build_substr_idx(umis, umi_length, threshold)
iter_umi_pairs = iter_nearest_neighbours(umis, substr_idx)
else:
iter_umi_pairs = itertools.combinations(umis, 2)
for umi1, umi2 in iter_umi_pairs:
if hamming_distance(umi1, umi2) <= threshold:
if counts[umi1] >= (counts[umi2]*2)-1:
adj_list[umi1].append(umi2)
if counts[umi2] >= (counts[umi1]*2)-1:
adj_list[umi2].append(umi1)
return adj_list
def _get_adj_list_null(self, umis, counts, threshold):
''' for methods which don't use a adjacency dictionary'''
return None
# "get_connected_components" methods #
def _get_connected_components_adjacency(self, umis, graph, counts):
''' find the connected UMIs within an adjacency dictionary'''
# TS: TO DO: Work out why recursive function doesn't lead to same
# final output. Then uncomment below
# if len(graph) < 10000:
# self.search = breadth_first_search_recursive
# else:
# self.search = breadth_first_search
found = set()
components = list()
for node in sorted(graph, key=lambda x: counts[x], reverse=True):
if node not in found:
# component = self.search(node, graph)
component = breadth_first_search(node, graph)
found.update(component)
components.append(component)
return components
def _get_connected_components_null(self, umis, adj_list, counts):
''' for methods which don't use a adjacency dictionary'''
return umis
# "group" methods #
def _group_unique(self, clusters, adj_list, counts):
''' return groups for unique method'''
if len(clusters) == 1:
groups = [clusters]
else:
groups = [[x] for x in clusters]
return groups
def _group_directional(self, clusters, adj_list, counts):
''' return groups for directional method'''
observed = set()
groups = []
for cluster in clusters:
if len(cluster) == 1:
groups.append(list(cluster))
observed.update(cluster)
else:
cluster = sorted(cluster, key=lambda x: counts[x],
reverse=True)
# need to remove any node which has already been observed
temp_cluster = []
for node in cluster:
if node not in observed:
temp_cluster.append(node)
observed.add(node)
groups.append(temp_cluster)
return groups
def _group_adjacency(self, clusters, adj_list, counts):
''' return groups for adjacency method'''
groups = []
for cluster in clusters:
if len(cluster) == 1:
groups.append(list(cluster))
else:
observed = set()
lead_umis = self._get_best_min_account(cluster,
adj_list, counts)
observed.update(lead_umis)
for lead_umi in lead_umis:
connected_nodes = set(adj_list[lead_umi])
groups.append([lead_umi] +
list(connected_nodes - observed))
observed.update(connected_nodes)
return groups
def _group_cluster(self, clusters, adj_list, counts):
''' return groups for cluster or directional methods'''
groups = []
for cluster in clusters:
groups.append(sorted(cluster, key=lambda x: counts[x],
reverse=True))
return groups
def _group_percentile(self, clusters, adj_list, counts):
''' Return "groups" for the the percentile method. Note
that grouping isn't really compatible with the percentile
method. This just returns the retained UMIs in a structure similar
to other methods '''
retained_umis = self._get_best_percentile(clusters, counts)
groups = [[x] for x in retained_umis]
return groups
def __init__(self, cluster_method="directional"):
''' select the required class methods for the cluster_method'''
self.max_umis_per_position = 0
self.total_umis_per_position = 0
self.positions = 0
if cluster_method == "adjacency":
self.get_adj_list = self._get_adj_list_adjacency
self.get_connected_components = self._get_connected_components_adjacency
self.get_groups = self._group_adjacency
elif cluster_method == "directional":
self.get_adj_list = self._get_adj_list_directional
self.get_connected_components = self._get_connected_components_adjacency
self.get_groups = self._group_directional
elif cluster_method == "cluster":
self.get_adj_list = self._get_adj_list_adjacency
self.get_connected_components = self._get_connected_components_adjacency
self.get_groups = self._group_cluster
elif cluster_method == "percentile":
self.get_adj_list = self._get_adj_list_null
self.get_connected_components = self._get_connected_components_null
# percentile method incompatible with defining UMI groups
self.get_groups = self._group_percentile
elif cluster_method == "unique":
self.get_adj_list = self._get_adj_list_null
self.get_connected_components = self._get_connected_components_null
self.get_groups = self._group_unique
def __call__(self, umis, counts, threshold):
'''Counts is a directionary that maps UMIs to their counts'''
umis = list(umis)
self.positions += 1
number_of_umis = len(umis)
self.total_umis_per_position += number_of_umis
if number_of_umis > self.max_umis_per_position:
self.max_umis_per_position = number_of_umis
len_umis = [len(x) for x in umis]
assert max(len_umis) == min(len_umis), (
"not all umis are the same length(!): %d - %d" % (
min(len_umis), max(len_umis)))
adj_list = self.get_adj_list(umis, counts, threshold)
clusters = self.get_connected_components(umis, adj_list, counts)
final_umis = [list(x) for x in
self.get_groups(clusters, adj_list, counts)]
return final_umis
class ReadDeduplicator:
'''This is a wrapper for applying the UMI methods to bundles of BAM reads.
It is currently a pretty transparent wrapper on UMIClusterer. Basically
taking a read bundle, extracting the UMIs and Counts, running UMIClusterer
and returning the results along with annotated reads'''
def __init__(self, cluster_method="directional"):
self.UMIClusterer = UMIClusterer(cluster_method=cluster_method)
def __call__(self, bundle, threshold):
'''Process the the bundled reads according to the method specified
in the constructor. Return signature is:
reads, final_umis, umi_counts, topologies, nodes
reads: predicted best reads for deduplicated position
final_umis: list of predicted parent UMIs
umi_counts: Sum of read counts for reads represented by the
corresponding UMI
'''
umis = bundle.keys()
counts = {umi: bundle[umi]["count"] for umi in umis}
clusters = self.UMIClusterer(umis, counts, threshold)
final_umis = [cluster[0] for cluster in clusters]
umi_counts = [sum(counts[umi] for umi in cluster)
for cluster in clusters]
reads = [bundle[umi]["read"] for umi in final_umis]
return (reads, final_umis, umi_counts)
class TwoPassPairWriter:
'''This class makes a note of reads that need their pair outputting
before outputting. When the chromosome changes, the reads on that
chromosome are read again, and any mates of reads already output
are written and removed from the list of mates to output. When
close is called, this is performed for the last chormosome, and
then an algorithm identicate to pysam's mate() function is used to
retrieve any remaining mates.
This means that if close() is not called, at least as contigs
worth of mates will be missing. '''
def __init__(self, infile, outfile, tags=False):
self.infile = infile
self.outfile = outfile
self.read1s = set()
self.chrom = None
def write(self, read, unique_id=None, umi=None, unmapped=False):
'''Check if chromosome has changed since last time. If it has, scan
for mates. Write the read to outfile and save the identity for paired
end retrieval'''
if unmapped or read.mate_is_unmapped:
self.outfile.write(read)
return
if not self.chrom == read.reference_name:
self.write_mates()
self.chrom = read.reference_name
key = read.query_name, read.next_reference_name, read.next_reference_start
self.read1s.add(key)
self.outfile.write(read)
def write_mates(self):
'''Scan the current chromosome for matches to any of the reads stored
in the read1s buffer'''
if self.chrom is not None:
logging.debug("Dumping %i mates for contig %s" % (
len(self.read1s), self.chrom))
for read in self.infile.fetch(reference=self.chrom, multiple_iterators=True):
if any((read.is_unmapped, read.mate_is_unmapped, read.is_read1)):
continue
key = read.query_name, read.reference_name, read.reference_start
if key in self.read1s:
self.outfile.write(read)
self.read1s.remove(key)
logging.debug("%i mates remaining" % len(self.read1s))
def close(self):
'''Write mates for remaining chromsome. Search for matches to any
unmatched reads'''
self.write_mates()
logging.info("Searching for mates for %i unmatched alignments" %
len(self.read1s))
found = 0
for read in self.infile.fetch(until_eof=True, multiple_iterators=True):
if read.is_unmapped:
continue
key = read.query_name, read.reference_name, read.reference_start
if key in self.read1s:
self.outfile.write(read)
self.read1s.remove(key)
found += 1
continue
logging.info("%i mates never found" % len(self.read1s))
self.outfile.close()
class get_bundles:
''' A functor - When called returns a dictionary of dictionaries,
representing the unique reads at a position/spliced/strand
combination. The key to the top level dictionary is a umi. Each
dictionary contains a "read" entry with the best read, and a count
entry with the number of reads with that
position/spliced/strand/umi combination
initiation arguments:
options: script options
all_reads: if true, return all reads in the dictionary. Else,
return the 'best' read (using MAPQ +/- multimapping) for each key
return_read2: Return read2s immediately as a single read
metacontig_contig: Maps metacontigs to the consistuent contigs
'''
def __init__(self,
options,
only_count_reads=False,
all_reads=False,
return_unmapped=False,
return_read2=False,
metacontig_contig=None):
self.options = options
self.only_count_reads = only_count_reads
self.all_reads = all_reads
self.return_unmapped = return_unmapped
self.return_read2 = return_read2
self.metacontig_contig = metacontig_contig
self.contig_metacontig = {}
if self.metacontig_contig:
for metacontig in metacontig_contig:
for contig in metacontig_contig[metacontig]:
self.contig_metacontig[contig] = metacontig
# set the method with which to extract umis from reads
if self.options.get_umi_method == "read_id":
self.barcode_getter = partial(
get_barcode_read_id,
cell_barcode=self.options.per_cell,
sep=self.options.umi_sep)
else:
raise ValueError("Unknown UMI extraction method")
self.read_events = collections.Counter()
self.observed_contigs = collections.defaultdict(set)
self.last_pos = 0
self.last_chr = None
self.start = 0
self.current_chr = None
self.last_umiStart=0
self.reads_dict = collections.defaultdict(
lambda: collections.defaultdict(
lambda: collections.defaultdict(dict)))
self.read_counts = collections.defaultdict(
lambda: collections.defaultdict(dict))
def update_dicts(self, read, pos, key, umi):
# The content of the reads_dict depends on whether all reads
# are being retained
if self.all_reads:
# retain all reads per key
try:
self.reads_dict[pos][key][umi]["count"] += 1
except KeyError:
self.reads_dict[pos][key][umi]["read"] = [read]
self.reads_dict[pos][key][umi]["count"] = 1
else:
self.reads_dict[pos][key][umi]["read"].append(read)
elif self.only_count_reads:
# retain all reads per key
try:
self.reads_dict[pos][key][umi]["count"] += 1
except KeyError:
self.reads_dict[pos][key][umi]["count"] = 1
else:
# retain just a single read per key
try:
self.reads_dict[pos][key][umi]["count"] += 1
except KeyError:
self.reads_dict[pos][key][umi]["read"] = read
self.reads_dict[pos][key][umi]["count"] = 1
self.read_counts[pos][key][umi] = 0
else:
old_read=self.reads_dict[pos][key][umi]["read"]
if read.get_tag("NM")<=old_read.get_tag("NM"):
self.reads_dict[pos][key][umi]["read"] = read
self.read_counts[pos][key][umi] = 0
return
# TS: implemented different checks for multimapping here
if self.options.detection_method in ["NH", "X0"]:
tag = self.options.detection_method
if (self.reads_dict[pos][key][umi]["read"].opt(tag) <
read.opt(tag)):
return
elif (self.reads_dict[pos][key][umi]["read"].opt(tag) >
read.opt(tag)):
self.reads_dict[pos][key][umi]["read"] = read
self.read_counts[pos][key][umi] = 0
elif self.options.detection_method == "XT":
if self.reads_dict[pos][key][umi]["read"].opt("XT") == "U":
return
elif read.opt("XT") == "U":
self.reads_dict[pos][key][umi]["read"] = read
self.read_counts[pos][key][umi] = 0
self.read_counts[pos][key][umi] += 1
prob = 1.0/self.read_counts[pos][key][umi]
#if random.random() < prob:
# self.reads_dict[pos][key][umi]["read"] = read
def check_output(self):
do_output = False
out_keys = None
if self.options.per_gene:
if self.metacontig_contig:
if (self.current_chr != self.last_chr and
(self.observed_contigs[self.last_pos] ==
self.metacontig_contig[self.last_pos])):
do_output = True
out_keys = [self.last_pos]
else:
if self.current_chr != self.last_chr:
do_output = True
out_keys = sorted(self.reads_dict.keys())
elif self.options.whole_contig:
if self.current_chr != self.last_chr:
do_output = True
out_keys = sorted(self.reads_dict.keys())
else:
if (self.start > (self.last_pos+1000) or
self.current_chr != self.last_chr):
self.shift_umis(1)
do_output = True
out_keys = sorted(self.reads_dict.keys())
if self.current_chr == self.last_chr:
out_keys = [x for x in out_keys if x <= self.start-1000]
return do_output, out_keys
def compare_umis(self,p,k,p_near,k_near):
umi=self.reads_dict[p][k].keys()
umi_near=self.reads_dict[p_near][k_near].keys()
umi_overlap = set(umi).intersection(set(umi_near))
if len(umi_overlap)>0:
for u in umi_overlap:
near_count=self.reads_dict[p_near][k_near][u]["count"]
p_count=self.reads_dict[p][k][u]["count"]
near_read=self.reads_dict[p_near][k_near][u]["read"]
p_read=self.reads_dict[p][k][u]["read"]
if near_count > p_count:
self.reads_dict[p_near][k_near][u]["count"]+=p_count
del self.reads_dict[p][k][u]
elif near_count < p_count:
self.reads_dict[p][k][u]["count"]+=near_count
del self.reads_dict[p_near][k_near][u]
else:
if p_read.get_tag("NM") < near_read.get_tag("NM"):
self.reads_dict[p][k][u]["count"]+=near_count
del self.reads_dict[p_near][k_near][u]
elif p_read.get_tag("NM") > near_read.get_tag("NM"):
self.reads_dict[p_near][k_near][u]["count"]+=p_count
del self.reads_dict[p][k][u]
else:
if k[0][0]:
self.reads_dict[p_near][k_near][u]["count"]+=p_count
del self.reads_dict[p][k][u]
else:
self.reads_dict[p][k][u]["count"]+=near_count
del self.reads_dict[p_near][k_near][u]
def shift_umis(self, shift_bp):
for p in sorted(self.reads_dict.keys()):
#umi_collector=lambda: collections.defaultdict(dict)
p_near=p+shift_bp
p_keys=self.reads_dict[p].keys()
for k in sorted(p_keys,key=lambda x:x[0][2]):
if self.options.paired == False:
if p_near in self.reads_dict.keys():
self.compare_umis(p,k,p_near,k)
else:
k_near=((k[0][0],k[0][1],k[0][2]+shift_bp,k[0][3]),None)
if k_near in self.reads_dict[p].keys():
self.compare_umis(p,k_near,p,k)
if p_near in self.reads_dict.keys():
k_near=((k[0][0],k[0][1],k[0][2]-shift_bp,k[0][3]),None)
if k_near in self.reads_dict[p_near].keys():
self.compare_umis(p,k,p_near,k_near)
if k in self.reads_dict[p_near].keys():
self.compare_umis(p,k,p_near,k)
def __call__(self, inreads):
for read in inreads:
if read.is_read2:
if self.return_read2:
if not read.is_unmapped or (
read.is_unmapped and self.return_unmapped):
yield read, None, "single_read"
continue
else:
self.read_events['Input Reads'] += 1
if read.is_unmapped:
if self.options.paired:
if read.mate_is_unmapped:
self.read_events['Both unmapped'] += 1
else:
self.read_events['Read 1 unmapped'] += 1
else:
self.read_events['Single end unmapped'] += 1
if self.return_unmapped:
self.read_events['Input Reads'] += 1
yield read, None, "single_read"
continue
if read.mate_is_unmapped and self.options.paired:
if not read.is_unmapped:
self.read_events['Read 2 unmapped'] += 1
if self.return_unmapped:
yield read, None, "single_read"
continue
if self.options.paired:
self.read_events['Paired Reads'] += 1
if self.options.subset:
if random.random() >= self.options.subset:
self.read_events['Randomly excluded'] += 1
continue
if self.options.mapping_quality:
if read.mapq < self.options.mapping_quality:
self.read_events['< MAPQ threshold'] += 1
continue
self.current_chr = read.reference_name
if self.options.per_gene:
if self.options.per_contig:
if self.metacontig_contig:
transcript = read.reference_name
gene = self.contig_metacontig[transcript]
else:
gene = read.reference_name
elif self.options.gene_tag:
try:
gene = read.get_tag(self.options.gene_tag)
except KeyError:
self.read_events['Read skipped, no tag'] += 1
continue
if re.search(self.options.skip_regex, gene):
self.read_events['Gene skipped - matches regex'] += 1
continue
pos = gene
key = pos
if self.last_chr:
do_output, out_keys = self.check_output()
else:
do_output = False
if do_output:
for p in out_keys:
for k in sorted(self.reads_dict[p].keys()):
yield self.reads_dict[p][k], k, "bundle"
del self.reads_dict[p]
self.last_chr = self.current_chr
self.last_pos = pos
else:
start, pos, is_spliced = get_read_position(
read, self.options.soft_clip_threshold)
do_output, out_keys = self.check_output()
if do_output:
for p in out_keys:
for k in sorted(self.reads_dict[p].keys()):
if len(self.reads_dict[p][k].keys())>0:
yield self.reads_dict[p][k], k, "bundle"
del self.reads_dict[p]
if p in self.read_counts:
del self.read_counts[p]
self.last_pos = self.start
self.last_chr = self.current_chr
if self.options.read_length:
r_length = read.query_length
else:
r_length = 0
key = (read.is_reverse, self.options.spliced & is_spliced,
self.options.paired*read.tlen, r_length)
# get the umi +/- cell barcode and update dictionaries
if self.options.ignore_umi:
if self.options.per_cell:
umi, cell = self.barcode_getter(read)
umi = ""
else:
umi, cell = "", ""
else:
umi, cell = self.barcode_getter(read)
key = (key, cell)
self.update_dicts(read, pos, key, umi)
if self.metacontig_contig:
# keep track of observed contigs for each gene
self.observed_contigs[gene].add(transcript)
# yield remaining bundles
self.shift_umis(1)
for p in sorted(self.reads_dict.keys()):
for k in sorted(self.reads_dict[p].keys()):
if len(self.reads_dict[p][k].keys())>0:
yield self.reads_dict[p][k], k, "bundle"
class BetterFormatter(optparse.IndentedHelpFormatter):
"""A formatter for :class:`OptionParser` outputting indented
help text.
"""
def __init__(self, *args, **kwargs):
optparse.IndentedHelpFormatter.__init__(self, *args, **kwargs)
self.wrapper = textwrap.TextWrapper(width=self.width)
def _formatter(self, text):
return '\n'.join(['\n'.join(p) for p in
map(self.wrapper.wrap,
self.parser.expand_prog_name(text).split('\n'))])
def format_description(self, description):
if description:
return self._formatter(description) + '\n'
else:
return ''
def format_epilog(self, epilog):
if epilog:
return '\n' + self._formatter(epilog) + '\n'
else:
return ''
def format_usage(self, usage):
return self._formatter(optparse._("Usage: %s\n") % usage)
def format_option(self, option):
# Ripped and modified from Python 2.6's optparse's HelpFormatter
result = []
opts = self.option_strings[option]
opt_width = self.help_position - self.current_indent - 2
if len(opts) > opt_width:
opts = "%*s%s\n" % (self.current_indent, "", opts)
indent_first = self.help_position
else: # start help on same line as opts
opts = "%*s%-*s " % (self.current_indent, "", opt_width, opts)
indent_first = 0
result.append(opts)
if option.help:
help_text = self.expand_default(option)
# Added expand program name
help_text = self.parser.expand_prog_name(help_text)
# Modified the generation of help_line
help_lines = []
wrapper = textwrap.TextWrapper(width=self.help_width)
for p in map(wrapper.wrap, help_text.split('\n')):
if p:
help_lines.extend(p)
else:
help_lines.append('')