-
Notifications
You must be signed in to change notification settings - Fork 1
/
pastrami.py
executable file
·2101 lines (1788 loc) · 99.8 KB
/
pastrami.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/env python3
"""Pastrami - Population scale haplotype copying script"""
__author__ = "Andrew Conley, Lavanya Rishishwar"
__copyright__ = "Copyright 2021, Andrew Conley, Lavanya Rishishwar"
__credits__ = ["Andrew Conely", "Lavanya Rishishwar", "Shivam Sharma", "Emily Norris"]
__license__ = "GPL"
__version__ = "0.4"
__maintainer__ = "Andrew Conley, Lavanya Rishishwar"
__status__ = "Development"
__title__ = "pastrami.py"
# Standard modules
import logging
import math
import os
import pickle
import random
import re
import shlex
import shutil
import statistics
import string
import subprocess
import sys
from argparse import ArgumentParser, HelpFormatter
py_version = sys.version_info
if py_version[0] < 3 or py_version[1] < 4:
sys.exit(f"Error: {__title__} requires Python version 3.4+ to work. Please install a newer version of Python.")
# Additional installs
try:
import numpy as np
except ModuleNotFoundError as err:
sys.exit(f"Error: Numpy not found. Please install numpy prior to running {__title__}")
try:
from scipy.optimize import minimize
except ModuleNotFoundError as err:
sys.exit(f"Error: Scipy not found. Please install scipy prior to running {__title__}")
try:
import pandas as pd
except ModuleNotFoundError as err:
sys.exit(f"Error: Pandas not found. Please install pandas prior to running {__title__}")
try:
import pathos.multiprocessing as mp
except ModuleNotFoundError as err:
sys.exit(f"Error: Pathos not found. Please install pathos prior to running {__title__}")
VERSION = __version__
PROGRAM_NAME = __title__
class Colors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
class Support:
@staticmethod
def error_out(message: str = None):
if message is not None:
sys.exit(Colors.FAIL + f"Error: {message}" + Colors.ENDC)
else:
sys.exit(Colors.FAIL + "The program encountered an error and has to exit." + Colors.ENDC)
@staticmethod
def validate_file(the_file: str):
return os.path.isfile(the_file)
@staticmethod
def validate_file_size(the_file: str, fake_run: str = False):
if fake_run:
return True
else:
return os.stat(the_file).st_size > 0
@staticmethod
def validate_file_and_size_or_error(the_file: str, error_prefix: str = 'The file',
presence_suffix: str = 'doesn\'t exist',
size_suffix: str = 'is size 0', fake_run: bool = False):
if not Support.validate_file(the_file=the_file) and not fake_run:
error_message = ' '.join([error_prefix, the_file, presence_suffix])
Support.error_out(message=error_message)
if not Support.validate_file_size(the_file=the_file) and not fake_run:
error_message = ' '.join([error_prefix, the_file, size_suffix])
Support.error_out(message=error_message)
@staticmethod
def validate_dir(the_dir: str):
return os.path.isdir(the_dir)
# TODO: This is a hastily written method, needs error fixing
@staticmethod
def validate_dir_or_error(the_dir: str, error_prefix: str = "The dir", presence_suffix: str = "doesn't exist",
fake_run: bool = False):
if not Support.validate_dir(the_dir=the_dir) and not fake_run:
error_message = ' '.join([error_prefix, the_dir, presence_suffix])
Support.error_out(message=error_message)
# TODO: Implement checks for dependency progams
@staticmethod
def check_dependencies(program_list: list = None) -> list:
errors = []
for program in program_list:
if shutil.which(program) is None:
errors.append(program)
return errors
@staticmethod
def find_plink_binary():
if shutil.which("plink") is not None:
return "plink"
elif shutil.which("plink2") is not None:
return "plink2"
else:
return None
@staticmethod
def run_command(command_str: str = None, command_list: list = None, shell=False):
if command_str is None and command_list is None:
raise ValueError("Support.run_command() was called without any command to execute.")
try:
if command_str is not None:
logging.info(f"Attempting to run: {command_str}")
output = subprocess.check_output(shlex.split(command_str), encoding="utf-8", shell=shell)
else:
logging.info(f"Attempting to run: " + " ".join([str(x) for x in command_list]))
output = subprocess.check_output(command_list, encoding="utf-8", shell=shell)
except subprocess.CalledProcessError as e:
logging.error(f"Encountered an error executing the command: ")
if command_str is not None:
logging.error(command_str)
else:
logging.error(command_list)
logging.error(f"Error details:")
logging.error(f"Exit code={e.returncode}")
logging.error(f"Error message={e.output}")
sys.exit(1)
# logging.info(f"Command output = {output}")
logging.info("Command executed without raising any exceptions")
return output
@staticmethod
def validate_filename(filename: str):
if re.match(r"^[a-zA-Z0-9_.-]+$", filename):
return True
else:
return False
@staticmethod
def validate_output_prefix(out_prefix: str):
parent, prefix = os.path.split(out_prefix)
if parent != "":
if not Support.validate_dir(parent):
Support.safe_dir_create(parent)
return Support.validate_filename(prefix)
@staticmethod
def safe_dir_create(this_dir: str):
try:
os.makedirs(this_dir)
except IOError:
print(f"I don't seem to have access to output prefix directory. Are the permissions correct?")
sys.exit(1)
@staticmethod
def safe_dir_rm(this_dir: str):
try:
os.rmdir(this_dir)
except IOError:
print(f"I don't seem to have access to output prefix directory. Are the permissions correct?")
sys.exit(1)
@staticmethod
def merge_fam_files(infile1: str, infile2: str, outputfile: str):
"""Merged two TFAM files into a single one (for aggregate function)
Parameters
----------
infile1 : str
Input TFAM file #1 (e.g., reference TFAM file)
infile2: str
Input TFAM file #2 (e.g., query TFAM file)
outputfile: str
Output TFAM file
Returns
-------
None
"""
with open(outputfile, "w") as out_handle:
with open(infile1, "r") as infile1_handle:
for line in infile1_handle:
out_handle.write(line)
with open(infile2, "r") as infile2_handle:
for line in infile2_handle:
out_handle.write(line)
@staticmethod
def create_pop_group_from_tfam(tfam_in_file: str, tsv_out_file: str):
"""Takes unique population names from the input file and make them as group
Parameters
----------
tfam_in_file : str
Input TFAM file
tsv_out_file: str
Output TSV file
Returns
-------
None
"""
unique_populations = {}
with open(tfam_in_file, "r") as f_in:
for line in f_in:
pop = line.strip().split()[0]
unique_populations[pop] = True
unique_populations = sorted(unique_populations.keys())
with open(tsv_out_file, "r") as f_out:
f_out.write("#Population\tGroup\n")
for this_pop in unique_populations:
f_out.write(f"{this_pop}\t{this_pop}\n")
@staticmethod
def init_logger(log_file, verbosity):
"""Configures the logging for printing
Returns
-------
None
Logger behavior is set based on the Inputs variable
"""
try:
logging.basicConfig(filename=log_file, filemode="w", level=logging.DEBUG,
format=f"[%(asctime)s] %(message)s",
datefmt="%m-%d-%Y %I:%M:%S %p")
except FileNotFoundError:
print(f"The supplied location for the log file '{log_file}'" +
f"doesn't exist. Please check if the location exists.")
sys.exit(1)
except IOError:
print(f"I don't seem to have access to make the log file." +
f"Are the permissions correct or is there a directory with the same name?")
sys.exit(1)
if verbosity:
console = logging.StreamHandler()
console.setLevel(logging.INFO)
formatter = logging.Formatter(fmt=f"[%(asctime)s] %(message)s", datefmt="%m-%d-%Y %I:%M:%S %p")
console.setFormatter(formatter)
logging.getLogger().addHandler(console)
class Analysis:
chromosomes = list(range(1, 23))
fake_run = False
debug = True
min_haplotype_occurences = 0
optim_step_size = 0.0001
error_threshold = 1e-8
optim_iterations = 10
tolerance = 1e-8
optimizer_script = os.path.join(os.path.dirname(os.path.realpath(__file__)), "outsourcedOptimizer.R")
ancestry_fraction_postfix = "_fractions.Q"
ancestry_painting_postfix = "_paintings.Q"
pop_estimates_postfix = "_estimates.Q"
outsourced_optimizer_pop_estimates_postfix = "_outsourcedOptimizer_estimates.Q"
finegrain_estimates_postfix = "_fine_grain_estimates.Q"
program_list = {'required': ["plink"]}
def __init__(self, opts):
# General attributes
self.threads = opts.threads
self.log_file = opts.log_file
self.verbosity = opts.verbosity
self.pool = None
# Any errors we encounter
self.errors = []
# The actual queue for the analysis
self.analysis = []
# Verbosity levels and colors
self.error_color = Colors.FAIL
self.main_process_verbosity = 1
self.warning_color = Colors.WARNING
self.warning_verbosity = 1
self.main_process_color = Colors.OKGREEN
self.sub_process_verbosity = 2
self.sub_process_color = Colors.OKBLUE
self.command_verbosity = 3
# Sub-commands
self.sub_command = opts.sub_command
self.plink_command = None
self.ancestry_infile = None
self.combined_copying_fractions = None
self.combined_output_file = None
self.fam_infile = None
self.haplotype_file = None
self.haplotypes = None
self.map_dir = None
self.max_rate = None
self.max_snps = None
self.min_snps = None
self.out_prefix = None
self.pop_group_file = None
self.query_combined_file = None
self.query_copying_fractions = None
self.query_output_file = None
self.query_prefix = None
self.query_tfam = None
self.query_tfam_file = None
self.query_tped_file = None
self.reference_copying_fractions = None
self.reference_haplotype_counts = None
self.reference_haplotype_fractions = None
self.reference_individual_populations = None
self.reference_individuals = None
self.reference_output_file = None
self.reference_pickle_output_file = None
self.reference_population_counts = None
self.reference_populations = None
self.reference_prefix = None
self.reference_tfam = None
self.reference_tfam_file = None
self.reference_tped_file = None
# All sub-command options
if self.sub_command == 'all':
# TODO: Test all subcommand
# Required options
self.reference_prefix = opts.reference_prefix
self.query_prefix = opts.query_prefix
self.out_prefix = opts.out_prefix
self.map_dir = opts.map_dir
self.haplotype_file = opts.haplotypes
self.pop_group_file = opts.pop_group_file
self.debug_mode = opts.debug_mode
# Outputs to be made
self.reference_pickle_output_file = None
self.reference_output_file = None
self.reference_pickle_file = None
self.query_output_file = None
self.combined_output_file = None
self.ancestry_infile = None
self.fam_infile = None
# Hapmake
self.min_snps = opts.min_snps
self.max_snps = opts.max_snps
self.max_rate = opts.max_rate
# Build options
self.reference_tpeds = pd.Series([], dtype=pd.StringDtype())
self.reference_background = pd.Series([], dtype=pd.StringDtype())
# Query options
self.query_tpeds = pd.Series([], dtype=pd.StringDtype())
self.query_individuals = None
# aggregate options
self.ref_pop_group_map = {}
self.ind_pop_map = {}
self.pop_ind_map = {} # reverse map of ind_pop_map, sacrificing memory for speed later on
self.reference_individual_dict = {}
self.reference_pops = {}
self.ancestry_fractions = {}
self.af_header = []
self.painting_vectors = {}
self.painting_vectors_keys = []
self.fine_grain_estimates = {}
# Hapmake sub-command options
if self.sub_command == 'hapmake':
self.min_snps = opts.min_snps
self.max_snps = opts.max_snps
self.max_rate = opts.max_rate
self.map_dir = opts.map_dir
self.haplotype_file = opts.haplotypes
# Build sub-command options
if self.sub_command == 'build':
self.reference_pickle_output_file = opts.reference_pickle_out
self.reference_prefix = opts.reference_prefix
self.haplotype_file = opts.haplotypes
self.reference_output_file = opts.reference_out
self.reference_tpeds = pd.Series([], dtype=pd.StringDtype())
self.reference_background = pd.Series([], dtype=pd.StringDtype())
# Query sub-command options
if self.sub_command == 'query':
self.reference_pickle_file = opts.reference_pickle
self.query_prefix = opts.query_prefix
self.query_output_file = opts.query_out
self.combined_output_file = opts.combined_out
self.query_tpeds = pd.Series([], dtype=pd.StringDtype())
self.query_individuals = None
# Co-ancestry sub-command options
if self.sub_command == 'coanc':
self.haplotype_file = opts.haplotypes
self.reference_prefix = opts.reference_prefix
self.query_prefix = opts.query_prefix
self.reference_output_file = opts.reference_out
self.query_output_file = opts.query_out
self.query_combined_file = opts.combined_out
# Aggregate sub-command options
if self.sub_command == 'aggregate':
self.ancestry_infile = opts.ancestry_infile
self.pop_group_file = opts.pop_group_file
self.out_prefix = opts.out_prefix
self.fam_infile = opts.fam_infile
self.ref_pop_group_map = {}
self.ind_pop_map = {}
self.pop_ind_map = {} # reverse map of ind_pop_map, sacrificing memory for speed later on
self.reference_individual_dict = {}
self.reference_pops = {}
self.ancestry_fractions = {}
self.af_header = []
self.painting_vectors = {}
self.painting_vectors_keys = []
self.fine_grain_estimates = {}
Support.init_logger(log_file=self.log_file, verbosity=self.verbosity)
"""
[Class section] Run control
"""
def validate_options(self):
plink_command = Support.find_plink_binary()
if plink_command is None:
self.errors += ["Can't find plink or plink2. Please make sure the binary exists as one of those two names"]
else:
self.plink_command = plink_command
if self.sub_command == "all":
self.validate_and_set_all_subcommand_options()
# self.analysis += ['build_reference_set', 'query_reference_set', 'build_coanc', 'post_pastrami']
self.analysis += ['build_reference_set', 'query_reference_set', 'post_pastrami']
if self.sub_command == 'hapmake':
self.validate_map_dir()
self.analysis += ['make_haplotypes']
if self.sub_command == 'build':
self.validate_reference_prefix()
self.validate_haplotypes()
self.analysis += ['build_reference_set']
if self.sub_command == 'query':
self.validate_reference_pickle()
self.validate_query_prefix()
self.analysis += ['query_reference_set']
if self.sub_command == 'coanc':
self.validate_reference_prefix()
if self.query_prefix is not None:
self.validate_query_prefix()
self.validate_haplotypes()
self.analysis += ['build_coanc']
if self.sub_command == 'aggregate':
self.validate_ancestry_infile()
self.validate_pop_group_file()
self.validate_fam_infile()
self.analysis += ['post_pastrami']
if len(self.analysis) == 0:
self.errors = self.errors + ['Nothing to do!']
def __str__(self):
long_string = f"""
Class constants:
chromosomes = {Analysis.chromosomes}
fake_run = {Analysis.fake_run}
debug = {Analysis.debug}
min_haplotype_occurences = {Analysis.min_haplotype_occurences}
optim_step_size = {Analysis.optim_step_size}
error_threshold = {Analysis.error_threshold}
optim_iterations = {Analysis.optim_iterations}
tolerance = {Analysis.tolerance}
ancestry_fraction_postfix = {Analysis.ancestry_fraction_postfix}
ancestry_painting_postfix = {Analysis.ancestry_painting_postfix}
pop_estimates_postfix = {Analysis.pop_estimates_postfix}
finegrain_estimates_postfix = {Analysis.finegrain_estimates_postfix}
Instance variables:
* General program parameters
log_file = {self.log_file}
threads = {self.threads}
verbosity = {self.verbosity}
* Verbosity options
command_verbosity = {self.command_verbosity}
main_process_verbosity = {self.main_process_verbosity}
sub_process_verbosity = {self.sub_process_verbosity}
warning_verbosity = {self.warning_verbosity}
* Subcommand to be executed
sub_command = {self.sub_command}
* Hapmake-specific parameter options
max_rate = {self.max_rate}
max_snps = {self.max_snps}
min_snps = {self.min_snps}
* Hapmake-specific input/output options
out_prefix = {self.out_prefix}
map_dir = {self.map_dir}
haplotype_file = {self.haplotype_file}
* Query files input/output options
query_prefix = {self.query_prefix}
query_tfam_file = {self.query_tfam_file}
query_tped_file = {self.query_tped_file}
query_output_file = {self.query_output_file}
query_combined_file = {self.query_combined_file}
* Reference files input/output options
reference_prefix = {self.reference_prefix}
reference_tfam_file = {self.reference_tfam_file}
reference_tped_file = {self.reference_tped_file}
reference_output_file = {self.reference_output_file}
reference_pickle_output_file = {self.reference_pickle_output_file}
* Combined query-reference file location
combined_output_file = {self.combined_output_file}
* Aggregate-specific options
pop_group_file = {self.pop_group_file}
ancestry_infile = {self.ancestry_infile}
fam_infile = {self.fam_infile}
optimizer_location = {self.optimizer_script}
"""
return long_string
# TODO: Print a summary of what parameters were provided, what needs to be performed
def summarize_run(self):
logging.info(self.main_process_color + str(self) + Colors.ENDC)
logging.info(self.main_process_color + f"Analysis to perform: " + ", ".join(self.analysis) + Colors.ENDC)
def go(self):
self.summarize_run()
# self.pool = mp.Pool(processes=self.threads)
self.pool = mp.ProcessingPool(nodes=self.threads)
while True:
step = self.analysis[0]
self.analysis = self.analysis[1:]
function = getattr(self, step)
function()
if len(self.analysis) == 0:
break
if not self.debug:
self.cleanup()
# self.pool.terminate()
"""
[Class section] Functions for validating file
"""
def validate_and_set_all_subcommand_options(self):
self.validate_reference_prefix()
self.validate_query_prefix()
Support.validate_output_prefix(self.out_prefix)
if self.haplotype_file is None:
if self.map_dir is None:
self.errors += [self.sub_command + ' requires --haplotypes or --map-dir']
return
else:
self.validate_map_dir()
self.haplotype_file = self.out_prefix + ".hap"
if self.pop_group_file is None:
self.pop_group_file = self.out_prefix + ".pop_group.tsv"
Support.create_pop_group_from_tfam(tfam_in_file=self.reference_tfam_file, tsv_out_file=self.pop_group_file)
else:
self.validate_pop_group_file()
self.reference_pickle_output_file = self.out_prefix + ".pickle"
self.reference_output_file = self.out_prefix + ".hap"
self.reference_pickle_file = self.reference_pickle_output_file
self.query_output_file = self.out_prefix + "_query.tsv"
self.combined_output_file = self.out_prefix + ".tsv"
self.ancestry_infile = self.combined_output_file
self.fam_infile = self.out_prefix + ".fam"
Support.merge_fam_files(infile1=self.query_tfam_file,
infile2=self.reference_tfam_file,
outputfile=self.fam_infile)
def validate_haplotypes(self):
if self.haplotype_file is None:
self.errors += [self.sub_command + ' requires --haplotypes']
return
Support.validate_file_and_size_or_error(the_file=self.haplotype_file, error_prefix='Haplotype file',
fake_run=self.fake_run)
def validate_reference_prefix(self):
if self.reference_prefix is None:
self.errors += [self.sub_command + ' requires --reference-prefix']
return
self.reference_tped_file = self.reference_prefix + '.tped'
self.reference_tfam_file = self.reference_prefix + '.tfam'
for i in [self.reference_tped_file, self.reference_tfam_file]:
Support.validate_file_and_size_or_error(the_file=i, fake_run=self.fake_run)
def validate_query_prefix(self):
if self.query_prefix is None:
self.errors += [self.sub_command + ' requires --query-prefix']
return
self.query_tped_file = self.query_prefix + '.tped'
self.query_tfam_file = self.query_prefix + '.tfam'
for i in [self.query_tped_file, self.query_tfam_file]:
Support.validate_file_and_size_or_error(the_file=i, fake_run=self.fake_run)
def validate_reference_pickle(self):
if self.reference_pickle_file is None:
self.errors += [self.sub_command + ' requires --query-prefix']
return
Support.validate_file_and_size_or_error(the_file=self.reference_pickle_file,
error_prefix='Reference pickle', fake_run=self.fake_run)
def validate_map_dir(self):
if self.map_dir is None:
self.errors += [self.sub_command + ' requires --map-dir']
return
Support.validate_dir_or_error(the_dir=self.map_dir, error_prefix='Map directory', fake_run=self.fake_run)
def validate_ancestry_infile(self):
if self.ancestry_infile is None:
self.errors += [self.sub_command + ' requires --pastrami-output']
return
Support.validate_file_and_size_or_error(the_file=self.ancestry_infile,
error_prefix='Pastrami\' query output',
fake_run=self.fake_run)
# TODO: If user doesn't supply pop-group file, create one based on the TFAM file
def validate_pop_group_file(self):
if self.pop_group_file is None:
self.errors += [self.sub_command + ' requires --pop-group']
return
Support.validate_file_and_size_or_error(the_file=self.pop_group_file,
error_prefix='Population group mapping file',
fake_run=self.fake_run)
def validate_fam_infile(self):
if self.fam_infile is None:
self.errors += [self.sub_command + ' requires --pastrami-fam']
return
Support.validate_file_and_size_or_error(the_file=self.fam_infile,
error_prefix='FAM input',
fake_run=self.fake_run)
"""
[Class section] Haplotype maker
"""
def process_hapmap_file(self, chrom: int):
logging.info(f"[hapmake|chr{chrom}] Started processing")
haplotypes = ""
map_data = []
with open(os.path.join(self.map_dir, f"chr{chrom}.map"), "r") as f:
for line in f:
(position, cmorgan, snp) = line.rstrip().split("\t")
map_data.append([int(position), float(cmorgan), snp])
logging.info(f"[hapmake|chr{chrom}] File read")
left_snp = 0
right_snp = 0
snps = False
for row in range(len(map_data)):
right_snp += 1
if right_snp >= len(map_data):
break
# If the two SNPs have a recombination rate great than the max rate
if map_data[right_snp][1] - map_data[left_snp][1] >= self.max_rate:
if right_snp - left_snp >= self.min_snps:
snps = True
else:
left_snp = right_snp
right_snp += 1
# If the haplotype is long enough
if right_snp - left_snp >= self.max_snps:
snps = True
# If snps isn't False, then save the range of the window
if snps is True:
haplotypes += f"{chrom}\t{left_snp}\t{right_snp}\t{map_data[right_snp - 2][1] - map_data[left_snp][1]}\n"
snps = False
left_snp = right_snp
logging.info(f"[hapmake|chr{chrom}] All haplotypes discovered")
return haplotypes
def make_haplotypes(self):
logging.info(f"[hapmake|chrAll] Starting pool for processing")
# pool = mp.Pool(processes=self.threads)
# self.pool.restart()
results = self.pool.map(self.process_hapmap_file, range(1, 23))
# results.wait()
# results = results.get()
with open(self.haplotype_file, "w") as f:
f.write("".join(results) + "\n")
logging.info(f"[hapmake|chrAll] Files written")
# self.pool.close()
# self.pool.join()
# self.pool.terminate()
"""
[Class section] Core Pastrami code - to be fragmented further in future
"""
def load_reference_pickle(self):
logging.info('Loading reference pickle ' + self.reference_pickle_file)
pickle_file_handle = open(self.reference_pickle_file, 'rb')
old_pickle = pickle.load(pickle_file_handle)
self.reference_tfam = old_pickle.reference_tfam
# self.reference_haplotype_counts = old_pickle.reference_haplotype_counts
self.reference_haplotype_fractions = old_pickle.reference_haplotype_fractions
self.reference_populations = old_pickle.reference_populations
self.reference_background = old_pickle.reference_background
self.haplotypes = old_pickle.haplotypes
self.reference_copying_fractions = old_pickle.reference_copying_fractions
del old_pickle
logging.info('Reference pickle file loaded!')
def load_reference_tfam(self):
self.reference_tfam = pd.read_table(self.reference_tfam_file, index_col=None, header=None, sep=' ')
self.reference_tfam.index = self.reference_tfam.iloc[:, 1]
self.reference_tfam.columns = ['population', 'id', 'x1', 'x2', 'x3', 'x4']
self.reference_individuals = pd.Series(self.reference_tfam.index.values)
logging.info(f"Found {self.reference_tfam.shape[0]} reference individuals")
# Figure out the reference populations
self.reference_populations = self.reference_tfam.iloc[:, 0].unique()
logging.info(f"Found {len(self.reference_populations)} refeerence populations")
self.reference_individual_populations = self.reference_tfam.iloc[:, 0]
self.reference_population_counts = self.reference_tfam.iloc[:, 0].value_counts()
self.reference_population_counts = self.reference_population_counts[self.reference_populations]
def load_haplotypes(self):
self.haplotypes = pd.read_table(self.haplotype_file, index_col=None, header=None)
self.haplotypes.columns = ['chromosome', 'left', 'right', 'cM']
self.haplotypes = self.haplotypes.loc[self.haplotypes['chromosome'].apply(lambda x: x in self.chromosomes), :]
logging.info(f"Found {self.haplotypes.shape[0]} haplotypes")
def load_query_tfam(self):
self.query_tfam = pd.read_table(self.query_tfam_file, index_col=None, header=None, sep=' ')
self.query_tfam.index = self.query_tfam.iloc[:, 1]
self.query_tfam.columns = ['population', 'id', 'x1', 'x2', 'x3', 'x4']
self.query_individuals = self.query_tfam.index.values
logging.info(f"Found {self.query_tfam.shape[0]} query individuals")
def pull_chromosome_tped(self, prefix, chromosome, temp_dir):
# Pull the genotypes for a given chromosome from a given prefix
chromosome_file_prefix = os.path.join(temp_dir, str(chromosome) + '.tmp')
logging.info(f"Loading SNPs from chr{chromosome}")
command = [self.plink_command, '--tfile', prefix,
'--recode transpose',
'--chr', str(chromosome),
'--out', chromosome_file_prefix,
'--keep-allele-order']
# TODO: Move the command to Support.run_command
# Support.run_command(command_str=" ".join(command), shell=True)
# Support.run_command(command_list=command)
subprocess.check_output(" ".join(command), shell=True)
if not os.path.isfile(chromosome_file_prefix + ".tped"):
print(f"Failed to create {chromosome_file_prefix}.tped")
sys.exit(1)
# Read the thing and remove the temporary files
chromosome_tped_file = chromosome_file_prefix + '.tped'
# logging.info(f"Reading in {chromosome_tped_file}")
chromosome_tped = pd.read_table(chromosome_tped_file, index_col=None, header=None, sep='\t').iloc[:, 4::2]
# TODO: Move this to Python's rm command?
command = ['rm'] + [chromosome_file_prefix + '.' + i for i in ['tped', 'tfam', 'log']]
# TODO: Move the command to Support.run_command
# Support.run_command(command_list=command)
subprocess.check_output(" ".join(command), shell=True)
logging.info(f"Finished loading SNPs from chr{chromosome}")
return chromosome_tped
def load_reference_tpeds(self):
# Read in all of the reference TPEDs
# print(self.chromosomes)
temp_name = "pastrami_" + ''.join(random.choice(string.ascii_letters) for _ in range(10))
Support.safe_dir_create(temp_name)
logging.info(f"Loading reference TPEDs with {self.threads} threads")
# pool = mp.Pool(processes=self.threads)
# self.pool.restart()
results = self.pool.map(
lambda x: self.pull_chromosome_tped(prefix=self.reference_prefix, chromosome=x, temp_dir=temp_name),
self.chromosomes)
# results.wait()
# results = results.get()
# self.pool.close()
# self.pool.join()
# self.pool.terminate()
Support.safe_dir_rm(temp_name)
# import pdb; pdb.set_trace()
for i in range(len(self.chromosomes)):
self.reference_tpeds[str(self.chromosomes[i])] = results[i]
self.reference_tpeds[str(self.chromosomes[i])].columns = self.reference_individuals
logging.info(f"Loaded {len(self.reference_tpeds)} referenece TPEDs")
def load_query_tpeds(self):
# Read in all of the reference TPEDs
logging.info("Chromosomes to process: ")
logging.info(self.chromosomes)
temp_name = "pastrami_" + ''.join(random.choice(string.ascii_letters) for _ in range(10))
Support.safe_dir_create(temp_name)
logging.info(f"Loading query TPEDs with {self.threads} threads")
# pool = mp.Pool(processes=self.threads)
# self.pool.restart()
results = self.pool.map(
lambda x: self.pull_chromosome_tped(prefix=self.query_prefix, chromosome=x, temp_dir=temp_name),
self.chromosomes)
# results.wait()
# results = results.get()
# self.pool.close()
# self.pool.join()
# self.pool.terminate()
Support.safe_dir_rm(temp_name)
for i in range(len(self.chromosomes)):
self.query_tpeds[str(self.chromosomes[i])] = results[i]
self.query_tpeds[str(self.chromosomes[i])].columns = self.query_individuals
logging.info(f"Loaded {len(self.query_tpeds)} query TPEDs")
def build_reference_set(self):
# Load up the reference data
logging.info("Building reference set")
self.load_haplotypes()
self.load_reference_tfam()
self.load_reference_tpeds()
# self.haplotypes = self.haplotypes.iloc[self.haplotypes.iloc[:,0].values in self.chromosomes, :]
# Parallelize across equal-sized chunks of haplotypes for good speed
chunk_size = min([30, math.ceil(self.haplotypes.shape[0] / self.threads)])
logging.info(f"Splitting haplotypes into chunks of {chunk_size}")
chunk_indices = list(range(0, math.ceil(self.haplotypes.shape[0] / chunk_size) * chunk_size + 1, chunk_size))
# chunks = len(chunk_indices) - 1
chunk_indices[-1] = self.haplotypes.shape[0]
chunk_indices = [chunk_indices[i:i + 2] for i in range(len(chunk_indices) - 1)]
# Find the haplotypes and corresponding genotypes for each chunk
chunk_haplotypes = []
chunk_genotypes = []
for this_chunk in chunk_indices:
chunk_haplotypes += [self.haplotypes.iloc[this_chunk[0]:this_chunk[1], :]]
this_chunk_genotypes = []
for this_haplotype in range(this_chunk[0], this_chunk[1]):
this_chromosome, left_snp, right_snp, cM = self.haplotypes.iloc[this_haplotype, :]
this_chromosome, left_snp, right_snp = [int(i) for i in [this_chromosome, left_snp, right_snp]]
this_chunk_genotypes += [self.reference_tpeds[str(this_chromosome)].iloc[left_snp:right_snp, :]]
chunk_genotypes += [this_chunk_genotypes]
# noinspection PyTypeChecker
chunk_data = [[chunk_indices[i]] + [chunk_haplotypes[i]] + [chunk_genotypes[i]] + [i] for i in
range(len(chunk_indices))]
del self.reference_tpeds
# Gives us back a list of lists
# Dim 1 - Chunk
# Dim 2 - Results of a chunk
# self.pool.restart()
results = self.pool.map(self.chunk_build_reference_copying_fractions, chunk_data)
# results.wait()
# results = results.get()
# self.pool.close()
# self.pool.join()
# self.pool.terminate()
# Find the population counts for each reference haplotype
self.reference_haplotype_counts = results[0][0]
for i in range(1, len(results)):
self.reference_haplotype_counts = pd.concat([self.reference_haplotype_counts, results[i][0]], axis=0)
logging.info(self.reference_haplotype_counts.shape)
# Find the population fractions for each reference haplotype
self.reference_haplotype_fractions = results[0][1]
for i in range(1, len(results)):
self.reference_haplotype_fractions = pd.concat([self.reference_haplotype_fractions, results[i][1]], axis=0)
# Find the reference indvidiual-reference population copying rates
# Here the copying fraction across all of the haplotypes but scaled 0-1
self.reference_copying_fractions = results[0][2]
for i in range(1, len(results)):
self.reference_copying_fractions += results[i][2]
self.reference_copying_fractions = self.reference_copying_fractions.T.apply(lambda x: x / x.sum()).T
# Find the background individual-reference copying rates.
# We define the background as the lowest copying rate seen for any reference individual for any reference population.
# Here the min of reach columin in the copying fractions
self.reference_background = self.reference_copying_fractions.min(axis=0)
# Adjust the reference individual v. population copying fractions by the backgroud and save
self.reference_copying_fractions -= self.reference_background
self.reference_copying_fractions = self.reference_copying_fractions.T.apply(lambda x: x / x.sum()).T
self.reference_copying_fractions.to_csv(self.reference_output_file, sep='\t')
# Pickle this reference set
pickle_file = open(self.reference_pickle_output_file, 'wb')
pickle.dump(self, pickle_file)
pickle_file.close()
def chunk_build_reference_copying_fractions(self, chunk_data):
chunk_indices, chunk_haplotypes, chunk_genotypes, chunk_number = chunk_data
logging.info('Starting chunk ' + str(chunk_number))
chunk_haplotype_counts = pd.Series([], dtype=pd.StringDtype())
chunk_haplotype_fractions = pd.Series([], dtype=pd.StringDtype())
chunk_reference_individual_counts = pd.DataFrame(0,
index=self.reference_individuals,
columns=self.reference_populations,
dtype=float)
# print('Found', chunk_haplotypes.shape[0], 'haplotypes for this chunk')
# print('Found', len(chunk_haplotypes), 'corresponding genotype sets')
for haplotype in range(len(chunk_haplotypes)):
chromosome, left_snp, right_snp, cM = chunk_haplotypes.iloc[haplotype, :]
chromosome, left_snp, right_snp = [int(i) for i in [chromosome, left_snp, right_snp]]
haplotype_index = str(chromosome) + ':' + str(left_snp) + "-" + str(right_snp)
# print(haplotype_index)
haplotype_genotypes = chunk_genotypes[haplotype]
# Find haplotypes from those individuals with no missingness
have_missing = haplotype_genotypes.apply(lambda x: (x != 0).all())
haplotype_genotypes = haplotype_genotypes.iloc[:, have_missing.values]
haplotype_strings = haplotype_genotypes.apply(lambda x: ''.join(x.astype(str)))
# Count the number of times each haplotype is seen in each population
haplotype_counts = pd.DataFrame(
{'population': self.reference_tfam.loc[haplotype_strings.index, 'population'],
'haplotype': haplotype_strings})
haplotype_counts = haplotype_counts.groupby(['population', 'haplotype']).size().reset_index()
haplotype_counts = haplotype_counts.pivot(index='haplotype', columns='population').fillna(0)
haplotype_counts.columns = haplotype_counts.columns.droplevel()
# Find the counts of each haplotype in each population
distinct_haplotypes = haplotype_strings.unique()
haplotype_counts_with_zeroes = pd.DataFrame(0, index=distinct_haplotypes,
columns=self.reference_populations,
dtype=int)
haplotype_counts_with_zeroes.loc[haplotype_counts.index, haplotype_counts.columns] += haplotype_counts
haplotype_counts = haplotype_counts_with_zeroes
# print(haplotype_counts.shape)
# Keep track of the counts for each haplotype on this chromosome
chunk_haplotype_counts[haplotype_index] = haplotype_counts
chunk_haplotype_fractions[haplotype_index] = haplotype_counts.T.apply(lambda x: x / x.sum()).T * cM
# Look for where the reference individuals fall and tally up their copying counts
for individual in self.reference_individuals:
if individual not in haplotype_strings.index:
continue
individual_haplotype = haplotype_strings[individual]
individual_population = self.reference_tfam.loc[individual, 'population']
# print(individual)
# Figure out if we need to remove this asshole individual from the reference set,
# i.e., don't allow a haplotype to copy from itself
if individual_haplotype in haplotype_counts.index:
# Don't try to count this if the reference individual was the only instance of the haplotype
if haplotype_counts.loc[individual_haplotype, :].sum() == 1: