-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathphase-Extender2.py
executable file
·1833 lines (1365 loc) · 85.5 KB
/
phase-Extender2.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
#!/usr/bin/python3
## Checking required modules
print("\nChecking and importing required modules: ")
import argparse
import collections
import csv
import io
import time
import itertools
import os
import resource
import shutil
from decimal import Decimal
from functools import reduce
from io import StringIO
from itertools import islice, product
from multiprocessing import Pool
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
def main():
print()
''' printing authorship '''
print("#######################################################################")
print(" Welcome to phase-extender version %i " % 1.0)
print(" Author: kiranNbishwa ([email protected], [email protected]) ")
print("#######################################################################")
print()
print("Loading the argument variables ....")
''' Define required argument for interactive mode program. '''
parser = argparse.ArgumentParser()
parser.add_argument("--nt",
help="number of process to run -> "
"the maximum number of processes that can be run at once is the number "
"of different chromosomes (contigs) in the input haplotype file.",
default=1, required=False)
parser.add_argument("--input",
help="name of the input haplotype file -> "
"This haplotype file should contain unique index represented by 'PI' and "
"phased genotype represented by 'PG_al' for several samples. ",
required=True)
parser.add_argument("--SOI",
help="sample of interest -> "
"Name of the sample intended for haplotype extension.",
required=True)
parser.add_argument("--output",
help="Name of the output directory. default: 'SOI_extended' ",
default='', required=False)
parser.add_argument("--refHap",
help="reference haplotype panel -> "
"This file should also contain 'PI' and 'PG_al' values for each "
"sample in that haplotype reference panel."
"default: empty ",
default='', required=False)
parser.add_argument("--useSample",
help="list of samples -> "
"Use phase state information only from these samples while running. "
"This is intended to provide control over phase-extension by "
"allowing select samples from the pool of samples (refHap and/or input). "
"This is useful for comparing the results when different individuals, "
"populations are used in phase extension process."
"Options: 'all','refHap','input','comma separated name of samples'. "
"default: 'all' - i.e all the samples in (refHap + input) will be used, "
"if refHap is given else all samples only from input file is used.",
default='all', required=False)
parser.add_argument("--bed",
help=" bed file -> "
"Process the haplotype extension only in this bed regions. "
"This is useful to limit haplotype extension only within certain "
"regions, like - within genes, exons, introns, QTL, etc. "
"default: empty ",
default= '', required=False)
parser.add_argument("--snpTh",
help="snp threshold -> "
"Minimum number of SNPs required in both haplotype blocks before starting "
"phase extension. "
"Option: an integer value. "
"Default: snpTh = 3 ",
default=3, required=False)
parser.add_argument("--numHets",
help="number of heterozygote SNPs -> "
"Maximum number of heterozygote SNPs used in consecutive haplotype blocks "
"for computing likelyhood of the phase states. "
"Option: an integer value. "
"Default: numHets = 40 ",
default=40, required=False)
parser.add_argument("--lods",
help="log2 of Odds cut off -> "
"Cutoff threshold to assign the phase states between consecutive haplotype blocks. "
"Option: an integer value "
"Default: 5 for parallel configuration (i.e 2^5 = 32 times more likely). ",
default=5, required=False)
#**Note: positive score above the cutoff values joins two consecutive block in "
#"parallel configuration, negative score below the cutoff joins two consecutive block in "
#"alternate configuration.
parser.add_argument("--culLH",
help="Cumulative likelhood estimates -> "
"The likelhoods for two possible configuration can either be max-sum vs. max-product. "
"Default: maxPd i.e max-product. "
"Options: 'maxPd' or 'maxSum'. ",
default='maxPd', required=False)
parser.add_argument("--writeLOD",
help="write log2 of Odds to the output file-> "
"writes the calculated LODs between two consecutive haplotype blocks in the output file. "
"Option: 'yes', 'no'. "
"Default: no. "
"**Note: the 'lods-score' are printed regardless if the "
"consecutive blocks are joined or not.",
default='no', required=False) # ** to do - add this feature
parser.add_argument("--hapStats",
help="Computes the descriptive statistics and plots histogram of the haplotype for "
"input and extended haplotype. "
"Default: 'no'."
"Option: 'yes', 'no' .",
default='no', required=False)
parser.add_argument("--addMissingSites",
help=" write the lines that have data missing for SOI on the output file. "
"Option: yes, no ",
default='no', required=False) # ** to do - add this
''' create a global argument variable and declare values of the global variables.
The values for the global variable are assigned using arguments (args.()) passed by user.'''
# this is necessary if arguments are declared at several functions using "args.variable" parameter.
global args;
args = parser.parse_args() # .. but keep it as it is.
global output # ** now used with "outputdir" - may change in future to control filename in output
global outputdir
global use_bed
global soi
global snp_threshold
global num_of_hets
global lods_cut_off
global use_sample # used in coherence with "sample_list"
global maxed_as
global writelod
global time01 # set a start time (used to time computational run for each chromosome vs. all processes)
global addmissingsites
print("Assigning values to the global variables ....")
# advantage of this method (assignment of global variable values at the beginning) ...
# ... is that we can change the program to non-interactive mode easily and
# point to specific values/files on this top part. This becomes helpful while debugging.
time01 = time.time()
soi = args.SOI
print(' - sample of interest: "%s" ' %(soi))
# Assign the output directory
if args.output == '':
outputdir = soi + '_extended'
elif args.output != '':
outputdir = args.output
if os.path.exists(outputdir):
shutil.rmtree(outputdir, ignore_errors=False, onerror=None)
os.makedirs(outputdir, exist_ok=True)
# assign number of process to be used
nt = int(args.nt) # default, nt = 1
print(' - using "%s" processes ' % (nt))
input_file = args.input # the input haplotype file
# input_file = 'allele_table_for_phase_extender.txt'
print(' - using haplotype file "%s" ' % (input_file))
lods_cut_off = float(args.lods) # log_of_odds_cut_off, default = 5
print(' - using log2 odds cut off of "%s" ' % (lods_cut_off))
# minimum number of SNPs in a haplotype block before it can be phase-extended
snp_threshold = args.snpTh # default, snp_threshold = 3
print(' - each consecutive haplotype block should have minimum of "%s" SNPs ' % (snp_threshold))
# controls the max number of hetVars to include in likelyhood calculation
num_of_hets = int(args.numHets) # default, num_of_hets = 40
print(' - using maximum of "%s" heterozygote sites in each consecutive blocks to compute '
'transition probabilities' % (num_of_hets))
# add argument for max sum vs. max product of likelyhood estimates before calculating the LOD-score
maxed_as = args.culLH # default, maxed_as = "*"
if maxed_as == 'maxSum':
max_is = 'max sum'
maxed_as = '+'
elif maxed_as == 'maxPd':
max_is = 'max product'
maxed_as = '*'
print(' - using "%s" to estimate the cumulative maximum likelyhood of each haplotype configuration '
'between two consecutive blocks ' % (max_is))
##set the required variables related to bed file if bed file is given.
# use provided bed file to limit phase extension on bed regions/boundries
if args.bed != "": # default, use_bed = "no"
use_bed = 'yes'
bed_file = args.bed
print(' - using the bed file "%s" to limit phase extension at the bed boundries '%(bed_file))
else:
use_bed = 'no'
print(' - no bed file is given.')
# if a haplotype panel is provided then the reference panel can be used as backbone or ..
# .. meaningful data to aid in phase extension
if args.refHap != "": # default, use_refHap = "no"
use_refhap = 'yes'
refhap = args.refHap
print(' - using the reference haplotype panel "%s" ' %(refhap))
else:
use_refhap = 'no'
print(' - no reference haplotype panel is provided ')
# which samples to use while running phase-extension, default is all (hapRef + input)
# this variable is updated, later in the pipeline when all sample names are collected
use_sample = args.useSample # default, use_sample = "all"
# print the hapstats to file and also plot histogram
if args.hapStats == 'yes': # default, hapstats = 'no' ** ??
hapstats = 'yes'
print(' - statistics of the haplotype before and after extension will '
'be prepared for the sample of interest i.e "%s" ' %(soi))
else:
hapstats = 'no'
print(' - statistics of the haplotype before and after extension will not '
'be prepared for the sample of interest i.e "%s". '
' Only extendent haplotype block will be prepared.' % (soi))
# write calculated LOD (log2 of odds) of the possible phase state between two consecutive blocks
# default, writeLOD = "no"
if args.writeLOD == 'yes':
writelod = 'yes'
print(' - LOD (log 2 of odds) for consecutive block will be written to the output file ')
elif args.writeLOD != 'yes':
writelod = 'no'
print(' - LOD (log 2 of odds) for consecutive block will not be written to the output file ')
# if missing sites are to be added to phase extended file.
# this will output a new file instead of writing on top of phase extended file.
if args.addMissingSites == 'yes':
addmissingsites = 'yes'
elif args.addMissingSites != 'yes':
addmissingsites = 'no'
'''Assign the number of process - this is the optimal position to start multiprocessing !
**note: number of process should be declared after all the global variables are declared,
because each pool will need to copy the variable/value of global variables. '''
pool = Pool(processes=nt) # number of pool to run at once; default at 1
#### completed assignment of values to argument variables
''' Step 01: Read the input file and and prepare two files as output '''
# a) One output file contains extended phase-states for the sample of interest (soi)
# b) another output file contains the lines that have missing data for sample of interest
''' Step 01 - A: read the input haplotype file and prepare output files '''
with open(input_file) as input_data, \
open(outputdir + '/' +"missingdata_" + soi + ".txt", 'w') as missing_data:
print()
print()
print('# Reading the input haplotype file "%s" '%input_data.name)
print(' - Lines that have data missing for sample "%s" is written in the file "%s" '
%(soi, missing_data.name))
#print('extended haplotype data for sample "%s" will be written in the file "%s" '
#%(soi, update_data.name))
''' Step 01 - B: check if "bed file" and "haplotype reference" file are given.
- then read the "bed file" and "haplotype file" into the memory.
- these data will be used downstream after reading the haplotype file as "good_data" '''
# check and load bed file
if use_bed == 'yes':
''' we want to extend phase state only within bed boundries.
- so, we merge the "input haplotype-file" with "bed-file". '''
print()
print('Reading the bed file "%s" ' % (bed_file))
print('Phase extension will be limited to regions declared in the bed file')
my_bed = pd.read_csv(bed_file, sep='\t', names=['CHROM', 'start', 'end'])
my_bed['CHROM'] = my_bed['CHROM'].astype(str) # setting CHROM column as string type ..
# this is necessary because there has been problem with groupby operations downstream
else:
print()
print('# Genomic bed file is not provided ... ')
print(' - So, phase extension will run throughout the genome.')
# check and load "haplotype reference panel"
if use_refhap == 'yes':
hap_panel = pd.read_csv(refhap, sep='\t').drop(['REF', 'ALT'], axis=1)
hap_panel['CHROM'] = hap_panel['CHROM'].astype(str) # setting CHROM as string type data
# also find the sample in refHap panel
hap_panel_samples = find_samples(list(hap_panel.keys()))
else:
print()
hap_panel_samples = []
print('# Haplotype reference panel is not provided ... ')
print(' So, phase extension will run using the samples available in the input haplotype file. ')
''' Step 01 - C: from the input file
1) For the soi, remove/store the lines that have PI and allele value as empty (.) as "missing_data"
2) Rest of the data should have meaningful data for soi, and we store it as "good_data".
- also prepare the list of samples that will be used in phase extension.
3) Prepare a list of samples to use while computing transition matrix.
4) ** move this else where: write the first K1 block - after this we will only need to update K2 block values,
when reading k1,v1 and k2,v2 consecutive blocks as pairs. '''
''' store the good (meaningful) portion of the input_data as variable (Good_Data).
But, write the missing data as file (** but can also be stored in a variable) '''
good_data = '' # empty string
for lines in input_data:
if lines.startswith('CHROM'):
head = lines.rstrip('\n').split('\t')
# find the index positions of sample-of-interest's PI and PG_allele
soi_PI_index = head.index(soi + ':PI')
soi_PG_index = head.index(soi + ':PG_al')
# update the heading for good_data and missing_data
good_data += '\t'.join(head) + '\n'
missing_data.write('\t'.join(head) + '\n')
continue
''' Now, for the soi if PI and PG are missing (i.e, represented by '.') write it into
"missing_file.txt", else store it as "good_data" '''
lines = lines.rstrip('\n').split('\t')
if len(lines) <= 1: # to control for the last ('\n') line if present
break
# separate the lines with missing data (no "PI" or has "PI" but ambiguous SNP like "*")
if lines[soi_PI_index] == '.' or '.' in lines[soi_PG_index]:
missing_data.write('\t'.join(lines) + '\n')
# write the good part of the RB-phased VCF
elif lines[soi_PI_index] != '.':
good_data += '\t'.join(lines) + '\n'
# ** for future: this above code can be modified to include non-phased SNP variants.
# - just remove "lines[soi:PG_index]" to put SNPs with no PI index inside "good_data"
print()
print('# Filtered the lines that have data missing for sample "%s"; check the file "%s" '
%(soi, missing_data.name))
print(' - Loaded read-backphased variants onto the memory')
''' Step 01 - D: Prepare the samples to use the data from. '''
''' Prepare a list of tuples of samples (PI, PG_al) from the input data and update it as needed.
- **Note: the sample list should always include the soi (sample of interest)
- this is done to include observation from soi rather than introducing a pseudo count
when transition is missing from some observation (n to m). '''
samples = head.copy()
sample_list = find_samples(samples) # returns data from "input haplotype file"
# update the names in "sample_list" if other samples are requested by the user:
if use_sample == "" or use_sample == 'input':
sample_list = sample_list
# use all the samples from hapRefPanel and input samples
elif use_sample == 'all':
sample_list = sample_list + hap_panel_samples
elif use_sample == 'refHap':
sample_list = hap_panel_samples + [(soi + ":PI", soi +":PG_al")] # add the self sample name to account ..
# .. for missing observations instead of using pseudo count
# if specific select samples are of interest, split the sample names and then prepare ..
# .. the list of tuples of sample "PI" and "PG_al"
else:
sample_list = use_sample.split(',')
sample_list = [((x + ':PI'), (x + ':PG_al')) for x in sample_list] + \
[(soi + ":PI", soi +":PG_al")]
# print()
#print('sample listing to use')
#print(sample_list)
''' Step 02: pipe the data into "pandas", then:
A) group the data by "contig" which helps in multiprocessing/threading.
A - optional: if "bed regions" are given add the bed_regions boundries as "start_end"
B) within each group, group again by "PI keys" of soi and then sort by
minimum "POS" value for each "PI key"
C) then pipe the data within each "PI key" for phase-extension computation.'''
''' Step 02 - A : read good part of the data into "pandas" as dataframe.'''
good_data = pd.read_table(StringIO(good_data), delimiter='\t')
good_data['CHROM'] = good_data['CHROM'].astype(str) # setting CHROM as string type data # this is necessary
# to maintain proper groupby downstream
# ** only if "good_data" is desired as text output
#pd.DataFrame.to_csv(good_data, 'good_data_test.txt', sep='\t', header=True, index=False)
''' Step 02 - A (add on - i) ** merge reference haplotype if provided '''
print()
if use_refhap == "yes":
# update the "good_data" (i.e, haplotype data)
print('Merging input haplotype data with data from the hap-reference panel')
good_data = pd.merge(good_data, hap_panel, on=['CHROM', 'POS'],
how='left').fillna('.')
good_data.sort_values(by=['CHROM', 'POS'], inplace=True)
# if haplotype and reference panel merged lines are desired
#pd.DataFrame.to_csv(good_data, 'hap_and_refPanel_merged.txt', sep='\t',
#header=True, index=False)
del hap_panel
else:
print('# Haplotype reference panel is not provided....\n'
' - Only using the samples in the input ("%s") data.' %(input_data.name))
''' Step 02 - A (add on - ii) ** merge bed-regions if provided to limit phase extension
and group the data by "contig". '''
print()
if use_bed == 'no':
# group data only at "contig" level, keep the sort as it is
print('# No bed file is given ... ')
print(' - So, grouping the haplotype file only by chromosome (contig)')
good_data_by_group = good_data.groupby('CHROM', sort=False)
elif use_bed == 'yes':
print('# Merging the bed boundries from "%s" with the input haplotype file ... "%s" '
% (bed_file, input_data.name))
# merge/intersect the "bed regions" and "haplotype file"
# then groupy "contig" and "bed regions" by passing it to function "merge_hap_with_bed()"
good_data_by_group = merge_hap_with_bed(my_bed, good_data)
# ** for future: we can also run multiprocessing while merging "hap file" with "bed regions"
del my_bed
''' Step 02 - A (**add on - iii):
- Write the initial haplotype data.
- Compute the statistics of the initial phased file for SOI if required '''
print()
print('# Writing initial haplotype for sample "%s" in the file "%s" '
%(soi, 'initial_haplotype_' + soi + '.txt'))
# select the colums of interest
initial_haplotype = good_data[['CHROM', 'POS', 'REF', 'all-alleles', soi + ':PI', soi + ':PG_al']]. \
sort_values(by=['CHROM', 'POS'])
# write this initial haplotype to a file
pd.DataFrame.to_csv(initial_haplotype, outputdir + '/' + 'initial_haplotype_' + soi + '.txt',
sep='\t', header=True, index=False)
if hapstats == 'yes':
print(' - Computing the descriptive statistics of the haplotype data before phase extension')
# pipe the data to a function to compute haplotype statistics
compute_haplotype_stats(initial_haplotype, soi, prefix='initial')
else:
print(' - Proceeding to phase-extension without preparing descriptive statistics of initial haplotype state.')
''' Step 02 - B: - Split the data (grouped by chromosome (contig) values.
- Store data in disk or memory.
- Multiprocess each chunks separately '''
print()
print('# Starting multiprocessing using "%i" processes ' %(nt))
# ** new method: create a folder to store the data to disk (rather than memory)
# ** (see old method for comparison)
if os.path.exists('chunked_Data_' + soi):
shutil.rmtree('chunked_Data_' + soi, ignore_errors=False, onerror=None)
os.makedirs('chunked_Data_' + soi + '/', exist_ok=True)
''' Step 02 - B (i)'''
################### old method - ** if possible reuse this method in future.
# take the large dataframe that is grouped by contig and ..
# .. keep chunks of dataframes as as OrderedDict(list of (keys, Dataframe object))
#df_list = collections.OrderedDict()
########################################
# new method - storing data to disk
for chr_, data_by_chr in good_data_by_group:
pd.DataFrame.to_csv(data_by_chr, 'chunked_Data_' + soi + '/' + soi + ':' + str(chr_),
sep='\t', index=False, header=True)
# clear memory - does it do it's job ** ??
initial_haplotype = None; good_data = None; input_file = None
good_data_by_group = None; samples = None; input_data = None
data_by_chr = None
del initial_haplotype, good_data, input_file, good_data_by_group, samples, input_data, data_by_chr
''' Now, pipe the procedure to next function for multiprocessing (i.e Step 02 - C) '''
multiproc(sample_list, pool, hapstats)
# remove the chunked data folder ** (this can be retained if need be)
#shutil.rmtree('chunked_Data_' + soi, ignore_errors=False, onerror=None)
print('End :)')
def multiproc(sample_list, pool, hapstats):
print()
''' Step 02 - C: Start, multiprocessing/threading - process each contig separately. '''
''' Step 02 - C (ii) : create a pool of process and then feed the list of dataframes to another
function "groupby_and_read()" to run phase extension.
- After the data is passed into that function; the steps (02-C to 9) are covered there'''
path='chunked_Data_' + soi # create a temp folder
file_path = [(item, sample_list) for item in list(os.path.join(path, part) for part in os.listdir(path))]
## ** to do: Add "sort" method in "file_path" to read data in order. This way we can save ..
# time/memory while doing sorting within pandas dataframe.
# This sort method is available in "phase-Stitcher"
result = pool.imap(groupby_and_read, file_path)
pool.close()
pool.join()
pool.terminate()
#############################################
# old method of pooling - directly from memory
#p = Pool(processes=nt) # number of pool to run at once; default at 1
# #result = pool.imap(groupby_and_read, list(df_list.items()))
#result = pool .imap(groupby_and_read, [it + (sample_list, ) for it in list(df_list.items())])
# ** for future: use iterator, yield or generators to reduce memory burden while multiprocessing.
###########################
print()
print("Completed haplotype extension for all the chromosomes."
"time elapsed: '%s' " %(time.time() - time01))
print('Global maximum memory usage: %.2f (mb)' % current_mem_usage())
print("Merging dataframes together ....." )
print()
''' Step 10: merge the returned result (extended haplotype block by each contigs)
together and write it to an output file. '''
result_merged = pd.concat(result).sort_values(by=['CHROM', 'POS'], ascending=[True,True])
#result_merged = pd.DataFrame(result_merged).sort_values(by=['contig', 'pos'], ascending=[1,1])
# write data to the final output file
pd.DataFrame.to_csv(result_merged, outputdir + '/' + 'extended_haplotype_'+ soi +'.txt',
sep='\t', index=False)
print('Extended haplotype data for sample "%s" is written in the file "%s". '
%(soi, 'extended_haplotype_'+ soi + '.txt'))
''' Step 11: now, compute the descriptive stats of haplotype after phase extension. '''
if hapstats == 'yes':
print()
print('Computing the descriptive statistics of the extended haplotype file.')
compute_haplotype_stats(result_merged, soi, prefix='final')
else:
print('Skipping the preparation of descriptive statistics of extended haplotype.')
print()
print('Run is complete for all the chromosomes (contigs)')
''' Step 12: if phase extended data is to be merged with non phased SNPs and missing sites.
- we can use this data to run another round of phase extension of singletons (SNP and Indels).
- it also helps to control recursive phase extension. '''
print()
print('writing singletons and missing sites to extended haplotype')
if addmissingsites == 'yes':
missed_data_toadd = pd.read_csv(outputdir + '/' + "missingdata_" + soi + ".txt", sep='\t',
usecols=['CHROM', 'POS', 'REF', 'all-alleles',
soi + ':PI', soi + ':PG_al'])
missed_data_toadd['CHROM'] = missed_data_toadd['CHROM'].astype(str)
# "result_merged" only contains RBphased data for SOI
new_df = pd.concat([result_merged, missed_data_toadd]).sort_values(by=['CHROM', 'POS'], ascending=[True, True])
new_df = new_df[['CHROM', 'POS', 'REF', 'all-alleles', soi + ':PI', soi + ':PG_al']]
# write data to the final output file
pd.DataFrame.to_csv(new_df, outputdir + '/' + 'extended_haplotype_' + soi + '_allsites.txt',
sep='\t', index=False, na_rep='.')
del new_df
del result_merged
def groupby_and_read(file_path):
print()
good_data_by_contig = open(file_path[0], 'r')
chr_ = good_data_by_contig.name.split(':')[-1]
sample_list = file_path[1]
contigs_group = pd.read_csv(StringIO(good_data_by_contig.read()), sep='\t')
''' After doing groupby (by chromosome) we pipe in data, for each chromosome '''
time_chr = time.time() # to time the process in each chromosome
print('## Extending haplotype blocks in chromosome (contig) %s' %(chr_))
del good_data_by_contig
# if phase extension is to be limited to provided bed-regions
if use_bed == 'yes':
# start another level of grouping of the data by bed interval key
# (start-end of the bed is used as unique key for grouping)
print('Splitting the contig by bed regions')
good_data_by_bed = contigs_group.groupby('start_end', sort=False)
# clear memory
contigs_group = None
del contigs_group
''' store the dataframes split by "start_end" key in "df_list_by_bed".
Then pass this to phase-extension process. '''
# store dataframe/s outside bed region
# ** - for future (convert this into collection.OrderedDict of ..
# .. dataframes if data needs to be stored by multiple void blocks)
data_by_bed_void = pd.DataFrame()
# to store dataframes that are split by bed-regions but are within boundry of interest
df_list_by_bed = []
for bed_id, data_by_bed in good_data_by_bed:
if 'void' in bed_id:
# write data from these columns/row as a variable
data_by_bed_void = data_by_bed[
['CHROM', 'POS', 'REF', 'all-alleles', soi + ':PI', soi + ':PG_al']]
# ** write void lines separately (if needed) - optimize in the future.
#pd.DataFrame.to_csv(data_by_bed_void, 'haplotype_file_excluded_regions.txt',
#sep='\t', header=None, index=False)
else:
# now pass this dataframe to a function "process_consecutive_blocks()"
# i.e, Step 02-D - that reads two consecutive keys at once
# see **1, for future - there is possibility to multiprocess (phase-extension) this method
phase_extended_by_bed = process_consecutive_blocks(
data_by_bed, soi, chr_, snp_threshold,
sample_list, num_of_hets, lods_cut_off)
# append the dataframes that are returned as "phase_extended" haplotype block
# .. thus creating a list of dataframes
df_list_by_bed.append(phase_extended_by_bed)
# append the regions of the dataframe that was restricted by bed-file
df_list_by_bed.append(data_by_bed_void)
# concat all the dataframes in the list into one big dataframe
# this merges all the datraframe by bed-file within each chromosome/contig together
phase_extended_by_chr = pd.concat(df_list_by_bed)
# clear memory
data_by_bed_void = None; df_list_by_bed = None; phase_extended_by_bed=None
print(' - Phase-extension completed for contig "%s" in %s seconds' % (chr_, time.time() - time_chr))
print(' - Worker maximum memory usage: %.2f (mb)' % (current_mem_usage()))
print()
return phase_extended_by_chr.sort_values(by=['POS'])
#################################### **********************
# **1 for future - multiprocess phase extension for each bed-regions separately.
# use pool.map() or starmap
# create another pools of process for each chunks of dataframes
#p2 = Pool(1) # processing one dataframe at a time; but multiple possible
# pass it to phase extension
#result_by_bed = p2.map(process_consecutive_blocks, list(df_list_by_bed.values()))
#p2.close()
# "result_by_bed" has stored extended haplotype block for each bedregions as list.
# so, merge those list of dataframe
# result_by_bed_for_each_chr = pd.concat(result_by_bed)
# merge this again to the dataframe that were excluded due to bed-regions restriction
#result_by_bed_for_each_chr
#return result_by_bed_for_each_chr
##################################### ******************************
# if haplotype are extended at chromosome/contig level ..
# ..just pass whole contig/chromosome at once
else:
phase_extended_by_chr = process_consecutive_blocks(
contigs_group, soi, chr_, snp_threshold,
sample_list, num_of_hets, lods_cut_off)
# clear memory
contigs_group = None;
del contigs_group
print(' - Phase-extension completed for contig "%s" in %s seconds' %(chr_, time.time()-time_chr))
print(' - Worker maximum memory usage: %.2f (mb)' % (current_mem_usage()))
print()
# return the phase-extended haplotype back to the pool-process ..
# .. which will be pd.concatenated after all pools are complete
return phase_extended_by_chr.sort_values(by=['POS'])
''' now, read the two consecutive blocks to do phase extension. '''
def process_consecutive_blocks(contigs_group, soi, chr_, snp_threshold,
sample_list, num_of_hets, lods_cut_off):
#print()
print(' - Grouping the dataframe using unique "PI - phased index" values. ')
''' Step 02 - D: group dataframe again by "PI keys" of soi and then
sort by minimum "POS" value for each "PI key".
- This sorting is necessary because sometimes "haplotype blocks" are like 3-3-3-3 5-5-5 3-3-3-3
- i.e there are small RBphased blocks within the boundry of larger RBphased block.
- Not, sure what is causing this (prolly sampling difference of large vs. small chunks in PE reads)
- This problem should go away in first round of haplotype-extension'''
contigs_group = contigs_group. \
assign(New=contigs_group.groupby([soi + ':PI']).
POS.transform('min')).sort_values(['New', 'POS'])
''' Step 03: Now, start reading the "contigs_group" for haplotype-extension.
A) Store the data as dictionary with 'header' values as keys. Some keys are: CHROM, POS, sample (PI, PG within sample),
etc ... Then group the dictionary using unique "PI" values as 'keys' for grouping.
Note: This dict-data should contain information about two adjacent haplotype blocks that needs extending.
In this example I want to extend the haplotypes for "sample ms02g" which has two blocks 6 and 4.
So, I read the PI and PG value for this sample. Also, data should store with some unique keys.
B) Iterate over two consecutive Haplotype-Blocks at once.
Note: While iterating over two blocks, initially we write the very first block of the "contig". With this
method, now when we iterate over two consecutive blocks we can only update and write the second block.
'''
# covert pandas dataframe back to text like file before converting it into dictionary.
contigs_group = pd.DataFrame.to_csv(contigs_group, sep='\t', index=False, header=True)
''' Step 03 - A : read the data with header as keys and groupby using that "keys" '''
phased_dict = csv.DictReader(StringIO(contigs_group), delimiter='\t')
phased_grouped = itertools.groupby(phased_dict, key=lambda x: x[soi + ':PI'])
''' Since the dictionary isn't ordered, we return the order using OrderedDictionary '''
# ** for future: there is room for improvement in here (memory and speed)
grouped_data = collections.OrderedDict()
for key, grp in phased_grouped:
grouped_data[key] = accumulate(grp)
''' Clear memory '''
del phased_dict
del phased_grouped
del contigs_group
#print()
print(' - Starting MarkovChains for contig %s' % chr_)
''' Step 03 - B : now pipe the data for phase extension '''
''' Step 03 - B : And, iterate over two consecutive Haplotype-Blocks at once. This is done to obtain all
possible Haplotype configurations between two blocks. The (keys,values) for first block is represented as
k1,v2 and for the later block as k2,v2. '''
''' Step 03 - B (i): Before running consecutive blocks, we write data from the very first block to the file.
Reason : Before we start computing and solving the haplotype phase state, we plan to write the
data for very first block (k1, v1). So, after that, we can solve the relation between two consecutive..
.. blocks but only write data from 2nd block each time - based on what relation comes out. '''
very_first_block = [list(grouped_data.items())[0]]
if len(list(grouped_data.items())) == 1:
print('there is only one block, so skipping phase extension')
# write header of the extended phase-block
extended_haplotype = '\t'.join(['CHROM', 'POS', 'REF', 'all-alleles', soi +':PI', soi +':PG_al']) + '\n'
if writelod == 'yes': # add extra field if desired by user
extended_haplotype = extended_haplotype.rstrip('\n') + '\tlog2odds\n'
log2odds = ''
# write data/values from very first block.
for k1, v1 in very_first_block:
for r1, vals in enumerate(v1[soi + ':PI']):
new_line = '\t'.join([v1['CHROM'][r1], v1['POS'][r1], v1['REF'][r1], v1['all-alleles'][r1],
v1[soi + ':PI'][r1], v1[soi + ':PG_al'][r1]]) + '\n'
if writelod == 'yes':
new_line = new_line.rstrip('\n') + '\t.\n'
extended_haplotype += new_line
#print('very first block end\n\n') # marker for debugging
''' Step 03 - B (ii): Starting MarkovChains.
Now, read data from two consecutive blocks at a time.
Note: At the end of computation write the data only from each k2 block. No need to write the data
from k1 block of each iteration because it was written in earlier loop.'''
''' Step 03 - B (ii - 1) Create empty "checker variables".
Note: This checker variables (actually multi-level boolean logic) help to carryover information from
ealier iteration of a for-loop - i.e identify if the values from later block i.e k2, v2 were phased to
to earlier block (k1, v1) in "parallel" vs. "alternate configuration".
- If two consecutive blocks are phased, k2_new is now assigned k1 from earlier block; else (if not phased)
k2_new stays empty ('').
- So, the role of flipped variable is to keep information if k2,v2 were phased straight vs. alternate
compared to k1, v1 in the earlier run. These checker-variables are crucial to keep the proper phase-state
in the output file.'''
# start checker variables
k2_new = '' # updates the index of k2 for each k1,v1 ; k2,v2 run
flipped = '' # boolean logic to check and store if the phase state flipped during extension
''' Step 03 - B (ii - 2): Now, read two consecutive blocks at a time'''
for (k1, v1), (k2, v2) in zip(grouped_data.items(), islice(grouped_data.items(), 1, None)):
''' Step 03 - B (ii - 2-A): iterate over the first Haplotype Block, i.e the k1 block.
The nucleotides in the left of the phased SNPs are called Block01-haplotype-A,
and similarly on the right as Block01-haplotype-B. '''
# iterate over the first Haplotype Block, i.e the k1 block and v1 values
hap_block1a = [x.split('|')[0] for x in v1[soi + ':PG_al']] # the left haplotype of block01
hap_block1b = [x.split('|')[1] for x in v1[soi + ':PG_al']]
# iterate over the second Haplotype Block, i.e the k2 block and v2 values
hap_block2a = [x.split('|')[0] for x in v2[soi + ':PG_al']]
hap_block2b = [x.split('|')[1] for x in v2[soi + ':PG_al']]
''' Step 03 - B (ii - 2-B) : Create possible haplotype configurations for "forward markov chain".
Possible haplotype Configurations will be, Either :
1) Block01-haplotype-A phased with Block02-haplotype-A,
creating -> hapb1a-hapb2a, hapb1b-hapb2b '''
''' First possible configuration '''
hapb1a_hapb2a = [hap_block1a, hap_block2a]
hapb1b_hapb2b = [hap_block1b, hap_block2b]
''' Or, Second Possible Configuration
2) block01-haplotype-A phased with Block02-haplotype-B
creating -> hapb1a-hapb2b, hapb1b-hapb2a '''
hapb1a_hapb2b = [hap_block1a, hap_block2b]
hapb1b_hapb2a = [hap_block1b, hap_block2a]
''' Step 03 - B (ii - 2-C) :
Create possible haplotype configurations for "reverse markov chain"
- reverse markov chain are added to increase the confidence in likelyhood estimation. '''
# switch the keys values for reverse markov chain
k1_r = k2
k2_r = k1
v1_r = v2
v2_r = v1
# switch the haplotype positions for preparing the reverse markov chains
hapb1a_hapb2a_r = [hapb1a_hapb2a[1], hapb1a_hapb2a[0]]
hapb1b_hapb2b_r = [hapb1b_hapb2b[1], hapb1b_hapb2b[0]]
hapb1a_hapb2b_r = [hapb1a_hapb2b[1], hapb1a_hapb2b[0]]
hapb1b_hapb2a_r = [hapb1b_hapb2a[1], hapb1b_hapb2a[0]]
################################# - inactive for now- can be used for adding SNP phasing later on.
''' skip if one of the keys has no values - this is redundant ?? - keep it for just in case situation
** can also be used in the future if we want to phase the SNPs that have no assigned 'PI' values,
i.e the "PI" will be "." '''
if k1 == '.' or k2 == '.':
for xi in range(len(v2[soi + ':PI'])):
new_line = '\t'.join([v2['CHROM'][xi], v2['POS'][xi], v2['REF'][xi], v2['all-alleles'][xi],
k2, hapb1a_hapb2a[1][xi] + '|' + hapb1b_hapb2b[1][xi]]) + '\n'
if writelod == 'yes':
new_line = new_line.rstrip('\n') + '\t.\n'
extended_haplotype += new_line
# update the values of checker variables
k2_new = ''
flipped = ''
continue # to next consecutive blocks
######################################################
''' Step 03 - C : Set the threshold for the minimum number of SNPs required in haplotype block
before continuing phase extension. '''
''' If all the data in soi, in either v1 or v2 are SNPs below a certain threshold we just write
the data and continue. i.e say if a Haplotype-Block is composed of only 2 SNPs it will be less
reliable to extend the phase-state.
- So, this step can also be used to control the minimum number/size of the haplotypes that is required
before it can be phase-extended.
- by default the minimum number of SNPs (exclusive) in the soi haplotype is set to 3.
- If minimum requirement isn't met just skip extending the phase and write it to a file and continue. '''
number_of_snp_in_soi_v1 = len([x for x in v1[soi + ':PG_al'] if len(x) == 3])
number_of_snp_in_soi_v2 = len([x for x in v2[soi + ':PG_al'] if len(x) == 3])
# print('number of SNPs: ', NumSNPsInsoi_v1, NumSNPsInsoi_v2)
if number_of_snp_in_soi_v1 < snp_threshold \
or number_of_snp_in_soi_v2 < snp_threshold:
for xth, vals in enumerate(v2[soi + ':PI']):
new_line = '\t'.join([v2['CHROM'][xth], v2['POS'][xth], v2['REF'][xth], v2['all-alleles'][xth],
k2, hapb1a_hapb2a[1][xth] + '|' + hapb1b_hapb2b[1][xth]]) + '\n'
if writelod == 'yes':
new_line = new_line.rstrip('\n') + '\t.\n'
extended_haplotype += new_line
# update values of the checker variables
# this is important, so previous k2 and flip state doesn't get carried over without purpose
k2_new = ''
flipped = ''
continue # to next consecutive blocks
''' Step 04: For the consecutive blocks that pass the thresholds (SNP number, have PI != '.', etc.,
pipe the data (k1, v1 ; k2, v2) to a defined function for computation of forward and reverse
markov chain transition probabilities for these two consecutive blocks (k1, v1; k2, v2) '''
#### for forward chain ########
# ** set "orientation=reversed" to compute transition ..
# .. from the lower tip of former block with upper tip of later block
# .. this helps in using the closest genomic position between consecutive blocks thus ..
# .. downsizing the effects created by recombination.
lhfc_f, lhsc_f = \
compute_maxLh_score(soi, sample_list, k1, k2, v1, v2, num_of_hets,
hapb1a_hapb2a, hapb1b_hapb2b,
hapb1a_hapb2b, hapb1b_hapb2a, orientation=reversed)
#### for reverse chain ########
# set "orientation=lambda..." just passes a null value keeping orientation as it is.
lhfc_r, lhsc_r = compute_maxLh_score \
(soi, sample_list, k1_r, k2_r, v1_r, v2_r, num_of_hets,
hapb1a_hapb2a_r, hapb1b_hapb2b_r,
hapb1a_hapb2b_r, hapb1b_hapb2a_r, orientation=lambda x: x)
''' Step 05-06 are inside the function "compute_maxLh_score()". The values