-
Notifications
You must be signed in to change notification settings - Fork 1
/
pipeline.py
2692 lines (2385 loc) · 92.4 KB
/
pipeline.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
"""
File: pipeline.py of HLA_collections
Author: linnil1
Description: Build, running HLA tools and read parsing are all written in this script.
Design Pattern:
* `folder = createFolder("", "xxx") ` Folder creation
* `folder = xxxDownload(folder) ` Download data that required to be used no matter the index is
* `folder = checkAndBuildImage(folder) ` Build docker image
* `index = xxxBuild(folder, db_hla) ` Build HLA index from db_hla (The path of IMGT'DB)
* `samples = xxxPreprocess(samples) ` Preprocess of the tools. They are not related to IMGT version.
* `samples = xxxRun(samples, index) ` Run the tool by giving index
* `samples = xxxReadResult(samples) ` Read the result from the tool's output and save as tsv
* `samples = renameResult(samples, samples_fq)` Rename the hla result file for more organized
Something, the tools types each HLA gene individually and takes long time.
So I split it in `xxxPreRun`, and treat them as different task (`xxxRun`).
* `samples = xxxPreRun(samples_fq, index) ` Prepare the sample for typing each gene (Create scripts or json)
* `samples = globAndRun(xxxRun, samples) ` Select all the genes in the sample and run them
If you want to update the version of tool but not have differnet version tool at the same time,
just change the image name, folder name and xxx.dockerfile,
Mostly it will work.
"""
from glob import glob
from typing import Iterable, Callable
from pathlib import Path
from itertools import chain
from collections import defaultdict
import re
import gzip
import json
import argparse
import subprocess
import pandas as pd
from resources import *
# utility function
def name2Single(name: str) -> str:
"""Trun everything special character ('./') into '_'"""
return name.replace("/", "_").replace(".", "_")
def relink(src: str, dst: str) -> None:
"""
Solve ln when src is not absolute
e.g. ln -s data/1/2 data/1/3 will fail
"""
if Path(src).is_absolute():
runShell(f"ln -fs {src} {dst}")
elif Path(dst).is_absolute():
raise NotImplementedError
else:
parent_folder = "../" * (len(Path(dst).parents) - 1)
runShell(f"ln -fs {parent_folder}{src} {dst}")
def isVersionLarger(version_cur: str, version_max: str) -> bool:
"""Check version in version_cur is larger than version_max"""
if version_cur == "origin":
return False
version_cur_tuple = tuple(map(int, version_cur.split(".")))
version_max_tuple = tuple(map(int, version_max.split(".")))
return version_cur_tuple > version_max_tuple
def globAndRun(func: Callable[[str], str], input_name: str) -> str:
"""This is a temporary solution if not using my pipelilne"""
for i in glob(input_name.replace("{}", "*") + ".json"):
func(i[:-5])
for i in glob(input_name.replace("{}", "*") + ".sh"):
func(i[:-3])
return input_name
def removeMsaNucTail(nuc_ori: str, nuc_new: str) -> None:
"""
Remove the tailing in alignments/xx_nuc.txt
i.e. remove this
```
cDNA 1098
AA codon 342
|
A*03:437Q GACAG CTGCC TTGTG TGGGA CTGA
```
A proper way to do this is read it from pyHLAMSA and
export the same txt format.
"""
with open(nuc_ori) as f_ori:
txt = f_ori.read()
txt_arr = txt.split(" cDNA")
txt_new = txt_arr[0]
num_line = txt_arr[0].count("\n")
for i in txt_arr[1:]:
if i.count("\n") < num_line - 10:
print("Remove")
print(i)
txt_new += (
"Please see http://hla.alleles.org/terms.html for terms of use.\n\n"
)
break
num_line = i.count("\n")
txt_new += " cDNA" + i
# because nuc_ori and nuc_new can be the same file
# so open the read first and then write
with open(nuc_new, "w") as f_new:
f_new.write(txt_new)
# utility pipeline
def createFolder(base_folder: str = "", name: str = "") -> str:
"""Create folder at parent/base_folder"""
output_name = base_folder + folders[name]
Path(output_name).mkdir(exist_ok=True)
return output_name
def addSuffix(input_name: str, suffix: str) -> str:
"""Just add the suffix after input_name"""
return input_name + suffix
def bamSort(input_name: str, sam: bool = False) -> str:
"""sort the bamfile. If sam=True, remove samfile"""
if sam:
output_name = input_name
else:
output_name = input_name + ".sort"
if Path(output_name + ".bam").exists():
return output_name
if sam:
input_bam = input_name + ".sam"
else:
input_bam = input_name + ".bam"
if not Path(input_bam).exists():
raise ValueError(f"Not found {input_bam}")
runDocker(
"samtools", f"samtools sort -@{getThreads()} {input_bam} -o {output_name}.bam"
)
runDocker("samtools", f"samtools index {output_name}.bam")
if sam:
runShell(f"rm {input_bam}")
return output_name
def bam2Fastq(input_name: str) -> str:
"""Extract paired fastq from bamfile"""
output_name = input_name
if Path(f"{output_name}.read.2.fq.gz").exists():
return output_name
runDocker(
"samtools",
f"samtools sort -@{getThreads()}"
f" -n {input_name}.bam -o {output_name}.sortn.bam",
)
runDocker(
"samtools",
f"samtools fastq -@{getThreads()}"
f" -1 {output_name}.read.1.fq.gz -2 {output_name}.read.2.fq.gz "
f" -0 /dev/null -s /dev/null -n {output_name}.sortn.bam",
)
return output_name
def bwaIndex(input_name: str) -> str:
"""bwa index"""
if Path(f"{input_name}.bwt").exists():
return input_name
runDocker("bwa", f"bwa index {input_name}")
return input_name
def bwaRun(input_name: str, index: str) -> str:
"""bwa mem"""
output_name = input_name + ".bwa_" + name2Single(index)
if Path(f"{output_name}.bam").exists():
return output_name
runDocker(
"bwa",
f"bwa mem -t {getThreads()} {index}"
f" {input_name}.read.1.fq.gz {input_name}.read.2.fq.gz -o {output_name}.sam",
)
output_name = bamSort(output_name, sam=True)
return output_name
def addUnmap(input_name: str) -> str:
"""
HLA-LA has the step for extracting unmapped read
and it require at least one unmapped reads.
So I add this step to ensure HLA-LA doesn't fail.
"""
output_name = input_name + ".addunmap"
if Path(f"{output_name}.bam").exists():
return output_name
view = runDocker(
"samtools", f"samtools view -h {input_name}.bam -o {output_name}.sam"
)
with open(output_name + ".sam", "a") as f:
fields = ["ggggg", 77, "*", 0, 0, "*", "*", 0, 0, "A", "A", "AS:i:0 XS:i:0"]
f.write("\t".join(map(str, fields)) + "\n")
fields[1] = 141
f.write("\t".join(map(str, fields)) + "\n")
bamSort(output_name, sam=True)
return output_name
def unzipFastq(input_name: str) -> str:
"""unzip xxx.fq.gz to xx"""
if not Path(input_name + ".read.1.fq").exists():
runShell(f"gunzip -f --keep {input_name}.read.1.fq.gz")
if not Path(input_name + ".read.2.fq").exists():
runShell(f"gunzip -f --keep {input_name}.read.2.fq.gz")
return input_name
def mergeFastq(input_name: str) -> str:
"""Unzip fastq and merge them"""
output_name = input_name + ".read_merge"
if Path(output_name + ".fq").exists():
return output_name
runShell(f"zcat {input_name}.read.*.fq.gz > {output_name}.fq")
return output_name
def downloadRef(folder: str = "bwakit", name: str = "hs38DH") -> str:
"""https://github.com/lh3/bwa/tree/master/bwakit"""
if Path(f"{folder}/{name}.fa").exists():
return f"{folder}/{name}.fa"
runDocker("bwakit", f"run-gen-ref {name}")
runShell(f"mv {name}.* {folder}")
return f"{folder}/{name}.fa"
def downloadSample(folder: str = "data") -> str:
"""Download NA12878 example from HLA-LA"""
name = folder + "/NA12878"
if Path(f"{name}.read.2.fq.gz").exists():
return name
runShell("mkdir -p data")
runShell(
"wget 'https://www.dropbox.com/s/xr99u3vqaimk4vo/NA12878.mini.cram?dl=0'"
f" -O {name}.download.cram"
)
runDocker(
"samtools",
f"samtools view -@{getThreads()} {name}.download.cram -o {name}.bam",
)
output_name = bam2Fastq(name)
runShell(f"rm {name}.bam")
return output_name
def downloadHLA(folder: str = "", version: str = "3.49.0") -> str:
"""download database from https://github.com/ANHIG/IMGTHLA"""
version_name = version.replace(".", "")
if folder:
folder = folder + "/hla_" + version_name
else:
folder = "hla_" + version_name
if Path(folder).exists():
return folder
runShell(
f"wget https://github.com/ANHIG/IMGTHLA/archive/refs/tags/v{version}-alpha.zip"
)
runShell(f"unzip v{version}-alpha.zip")
runShell(f"rm v{version}-alpha.zip")
runShell(f"mv IMGTHLA-{version}-alpha {folder}")
# The downloaded hla.dat is still in git-lfs format
if version.startswith("3.44"):
runShell(
f"wget https://github.com/ANHIG/IMGTHLA/raw/{version}/hla.dat -O {folder}/hla.dat"
)
return folder
# Tool pipeline
def bwakitRun(input_name: str, index: str) -> str:
"""https://github.com/lh3/bwa/tree/master/bwakit"""
output_name = input_name + ".bwakit_" + name2Single(index)
if Path(output_name + ".hla.top").exists():
return output_name
runDocker(
"bwakit",
f"run-bwamem -t {getThreads()} -H -o {output_name}"
f" -R '@RG\\tID:{input_name}\\tSM:{input_name}'"
f" {index} {input_name}.read.1.fq.gz {input_name}.read.2.fq.gz"
f" > {output_name}.sh",
)
# BUG: dos format to linux format
runShell(f"sed -i 's/\\r$//g' {output_name}.sh")
runDocker("bwakit", f"bash {output_name}.sh")
return output_name
def bwakitReadResult(input_name: str) -> str:
"""
Turn bwakit HLA result format into our hla_result format
bwakit HLA format:
data/MMI001.bwakit_bwakit_hs38DH_fa.hla HLA-A*02:07:01 HLA-A*11:01:01...
"""
output_name = input_name + ".hla.top.hla_result"
if Path(output_name + ".tsv").exists():
return output_name
df = pd.read_csv(
input_name + ".hla.top",
sep="\t",
names=["name", "1", "2", "unknown1", "unknown2", "unknown3"],
)
df = df[["name", "1", "2"]]
df["1"] = df["1"].str.replace("HLA-", "")
df["2"] = df["2"].str.replace("HLA-", "")
df1 = allelesToTable(list(df["1"]) + list(df["2"]))
df1["name"] = input_name
df1.to_csv(output_name + ".tsv", index=False, sep="\t")
return output_name
def kouramiDownload(folder: str = "kourami") -> str:
"""https://github.com/Kingsford-Group/kourami"""
if Path(folder + "/resources/hs38NoAltDH.fa").exists():
return folder
runShell(
f"wget https://github.com/Kingsford-Group/kourami/releases/download/v0.9.6/kourami-0.9.6_bin.zip -P {folder}"
)
runShell(f"unzip {folder}/kourami-0.9.6_bin.zip -d {folder}")
runShell(f"mv {folder}/kourami-0.9.6/* {folder}")
runDocker("bwa", f"bash {folder}/scripts/download_grch38.sh hs38NoAltDH")
bwaIndex(folder + "/resources/hs38NoAltDH.fa")
return folder
def kouramiBuild(folder: str, db_hla: str = "origin") -> str:
"""
see https://github.com/Kingsford-Group/kourami/blob/master/preprocessing.md
and formatIMGT.sh
"""
# this line download v3.24 and save the db in {folder}/db
if db_hla == "origin":
output_name = f"{folder}/hla_3240"
else:
output_name = f"{folder}/{Path(db_hla).name}"
if Path(f"{output_name}/All_FINAL_with_Decoy.fa.gz").exists():
return output_name
if db_hla == "origin":
# scripts/download_panel.sh
# runDocker("bwa", f"bash {folder}/scripts/download_panel.sh")
runShell(
f"wget https://github.com/Kingsford-Group/kourami/releases/download/v0.9/kouramiDB_3.24.0.tar.gz -P {folder}"
)
runShell(f"tar -vxf {folder}/kouramiDB_3.24.0.tar.gz -C {folder}")
runShell(f"mv {folder}/db {output_name}")
else:
# Kourami's bug?
# runDocker("kourami", f"java -cp {folder}/build/Kourami.jar FormatIMGT {db_hla}/alignments/ . {output_name}")
runShell(f"cp -r {db_hla}/alignments {folder}/tmp_alignments")
runShell(
f"wget https://raw.githubusercontent.com/ANHIG/IMGTHLA/3240/alignments/Y_nuc.txt -O {folder}/tmp_alignments/Y_nuc.txt"
)
runShell(
f"wget https://raw.githubusercontent.com/ANHIG/IMGTHLA/3240/alignments/Y_gen.txt -O {folder}/tmp_alignments/Y_gen.txt"
)
runDocker(
"java",
f"java -cp {folder}/build/Kourami.jar FormatIMGT"
f" {folder}/tmp_alignments/ . {output_name}",
)
# runShell(f"rm -r {folder}/tmp_alignments")
runShell(
f"cat {output_name}/*.merged.fa {folder}/resources/HLA_decoys.fa"
f" | gzip > {output_name}/All_FINAL_with_Decoy.fa.gz"
)
runShell(f"cp {db_hla}/wmda/hla_nom_g.txt {output_name}")
bwaIndex(output_name + "/All_FINAL_with_Decoy.fa.gz")
return output_name
def kouramiPreprocess(input_name: str, index: str, kourami_folder: str = "") -> str:
"""https://github.com/Kingsford-Group/kourami"""
output_name = input_name + ".kourami_preprocess"
if Path(f"{output_name}._extract_2.fq.gz").exists():
return output_name
if not kourami_folder:
kourami_folder = index + "/.."
runDocker(
"kourami_preprocess",
f"bash {kourami_folder}/scripts/alignAndExtract_hs38DH.sh"
f" -d {index} -r {kourami_folder}/resources/hs38NoAltDH.fa"
f" {output_name}. {input_name}.bam ",
)
return output_name
def kouramiRun(input_name: str, index: str, kourami_folder: str = "") -> str:
"""https://github.com/Kingsford-Group/kourami"""
panel_name = input_name + ".panel_" + name2Single(index)
output_name = panel_name + ".call"
if Path(f"{output_name}.result").exists():
return output_name
# Because we use same preprocessed file
# the last step of alignAndExtract_hs38DH generate extracted fastq
if not kourami_folder:
kourami_folder = index + "/.."
runDocker(
"kourami_preprocess",
f"bwa mem -t {getThreads()} {index}/All_FINAL_with_Decoy.fa.gz"
f" {input_name}._extract_1.fq.gz {input_name}._extract_2.fq.gz"
f" -o {panel_name}.sam",
)
bamSort(panel_name, sam=True)
runDocker(
"java",
f"java -jar {kourami_folder}/build/Kourami.jar -d {index}"
f" {panel_name}.bam -o {output_name}",
)
return output_name
def kouramiReadResult(input_name: str) -> str:
"""
Turn Kourami HLA result into our hla_result.
It's Format:
A*11:01:01G 546 1.0 546 546 29.0 8.0 14.0
"""
output_name = input_name + ".result.hla_result"
if Path(f"{output_name}.tsv").exists():
return output_name
df = pd.read_csv(
input_name + ".result",
sep="\t",
names=[
"allele",
"matched_bases",
"identity",
"assembled_length",
"matched_length",
"bottleneck_sum",
"bottleneck_1",
"bottleneck_2",
],
)
df = allelesToTable(df["allele"], default_gene=["A", "B", "C"])
df["name"] = input_name
df.to_csv(output_name + ".tsv", index=False, sep="\t")
return output_name
def hisatDownload(folder: str = "hisat") -> str:
"""Download genome databse. See hisatgenotype/set.sh"""
if Path(f"{folder}/genome.fa.fai").exists():
return folder
# download_genotype_genome in hisatgenotype_modules/hisatgenotype_typing_common.py
runShell(
f"wget ftp://ftp.ccb.jhu.edu/pub/infphilo/hisat-genotype/data/genotype_genome_20180128.tar.gz -P {folder}"
)
runShell(f"tar -vxf {folder}/genotype_genome_20180128.tar.gz -C {folder}")
# download_genome_and_index in hisatgenotype_modules/hisatgenotype_typing_common.py
runShell(
f"wget ftp://ftp.ccb.jhu.edu/pub/infphilo/hisat2/data/grch38.tar.gz -P {folder}"
)
runShell(f"tar -xvzf {folder}/grch38.tar.gz -C {folder}")
runDocker(
"hisat2", f"sh -c 'hisat2-inspect {folder}/grch38/genome > {folder}/genome.fa'"
)
runDocker("samtools", f"samtools faidx {folder}/genome.fa")
return folder
def hisatBuild(folder: str, db_hla: str = "origin") -> str:
"""
HISAT2 cannot read the IMGT-HLA higher than version 3.43.0.
Which the A's exon length is not the same as A's nuc length
(They have different number of gap insertions)
"""
if db_hla == "origin":
output_name = folder + "/hla_3260"
else:
output_name = folder + "/" + Path(db_hla).name
if Path(f"{output_name}/hla.graph.8.ht2").exists():
return output_name
# link basic things
runShell(f"mkdir -p {output_name}")
files_genome = glob(folder + "/genotype_genome*")
for file_genome in files_genome:
runShell(f"ln -s ../{Path(file_genome).name} {output_name}/")
runShell(f" ln -s ../grch38 {output_name}/")
runShell(f" ln -s ../genome.fa {output_name}/")
runShell(f" ln -s ../genome.fa.fai {output_name}/")
# download HLA related things
if db_hla == "origin":
runShell(
"git clone https://github.com/DaehwanKimLab/hisatgenotype_db"
f" {output_name}/hisatgenotype_db"
)
runShell(f"cd {output_name}/hisatgenotype_db && git checkout d5d9b80")
else:
runShell(f"mkdir -p {output_name}/hisatgenotype_db/HLA")
# Don't use all genes, risky to fail
# runShell(f"cp -r {db_hla}/fasta {output_name}/hisatgenotype_db/HLA/")
# runShell(f"cp -r {db_hla}/msf {output_name}/hisatgenotype_db/HLA/")
runShell(f"mkdir -p {output_name}/hisatgenotype_db/HLA/fasta")
runShell(f"mkdir -p {output_name}/hisatgenotype_db/HLA/msf")
genes = [
"A",
"B",
"C",
"DMA",
"DMB",
"DOA",
"DOB",
"DPA1",
"DPB1",
"DPB2",
"DQA1",
"DQB1",
"DRA",
"DRB",
"E",
"F",
"G",
"H",
"HFE",
"J",
"K",
"L",
"MICA",
"MICB",
"P",
"TAP1",
"TAP2",
"V",
]
runShell(f"cp {db_hla}/hla.dat {output_name}/hisatgenotype_db/HLA")
for gene in genes:
runShell(
f"cp -r {db_hla}/fasta/{gene}*"
f" {output_name}/hisatgenotype_db/HLA/fasta/"
)
runShell(
f"cp -r {db_hla}/msf/{gene}*"
f" {output_name}/hisatgenotype_db/HLA/msf/"
)
# Build the index by running one example
json.dump({"sanity_check": False}, open(f"{folder}/settings.json", "w"))
with open(f"{folder}/read.fq", "w") as f:
f.write(
"""
@B*82:02:01:02-746
ACCCACCCGGACTCAGAGTCTCCTCAGACGCCGAGATGCGGGTCACGGCACCCCGAACCCTCCTCCTGCTGCTCTGGGGGGCCCTGGCCCTGACCGAGACCTGGGCTGGTGAGTGCGGGGTCGGGAGGGAAATGGCCTCTGTGGGGAGGA
+
CCCGGGGGGGGGGJJJJJGCGJJ1G=GJJJJJGJCJGGJGGJ=JGJJJGJJGJJGJJGGGGJGGJGG=GCGGGGGC=G8CCGGGGCGGGGGGGGCGCGG1JCGGGGGGCGCCGG1GCGGCGGGGGGCGGCGCCGG=GGGGG1GCGGGCGC
@B*82:02:01:02-744
CCCTCACCCTGAGATGGGGTAAGGAGGGGGATGAGGGGTCATATCTCTTCTCAGGGAAAGCAGGAGCCCTTCTGGAGCCCTTCAGCAGGGTCAGGGCCCCTCATCTTCCCCTCCTTTCCCAGAGCCATCTTCCCAGTCCACCATCCCCAT
+
CC1CGGGGGGGGGGJGJJJJJJJGGJJGJGGJGGJGCJJJJGJJJJJJGGGGJ=GJJCGJGGGGJ=G=GGG==GGGCGGGC=GGCCGGGCGGG8GG=CGGJCGGCGGGGG1GGGGGGGGCGC1GCG=GGGCGGGCGGG8=C=GGGCGGGG
""".strip()
)
runDocker(
"hisat",
f"hisatgenotype -z {output_name} --threads {getThreads()} "
f"--base hla --out-dir /tmp -v -U {folder}/read.fq",
mounts=[(f"{folder}/settings.json", "/opt/hisat-genotype/devel/settings.json")],
)
return output_name
def hisatRun(input_name: str, index: str) -> str:
"""https://daehwankimlab.github.io/hisat-genotype/manual/"""
output_name = input_name + ".hisat_" + name2Single(index)
if len(glob(f"{output_name}/*.report")) > 0:
return output_name
runDocker(
"hisat",
f"hisatgenotype --threads {getThreads()} --keep-alignment -v --keep-extract"
f" -z {index} --base hla"
f" --out-dir {output_name}"
f" -1 {input_name}.read.1.fq.gz"
f" -2 {input_name}.read.2.fq.gz",
)
# The folder has these three file
# assembly_graph-hla.MMI001_read_1_fq_gz-hla-extracted-1_fq.report
# MMI001.read.1.fq.gz-hla-extracted-1.fq.gz
# MMI001.read.1.fq.gz-hla-extracted-2.fq.gz
# and the current dir has these files
# MMI001_read_1_fq_gz-hla-extracted-1_fq.bam*
name = Path(f"{input_name}.read.1.fq.gz").name
runShell(f"mv {name.replace('.', '_')}* {output_name}/")
relink(f"{output_name}/{name}-hla-extracted-1.fq.gz", f"{output_name}.read.1.fq.gz")
relink(f"{output_name}/{name}-hla-extracted-2.fq.gz", f"{output_name}.read.2.fq.gz")
return output_name
def hisatReadResult(input_name: str) -> str:
"""
Turn hisat HLA report into our hla_result format:
It's format:
```
1 ranked A*02:07:01 (abundance: 50.61%)
2 ranked A*11:01:01:01 (abundance: 49.39%)
```
"""
output_name = input_name + ".hla_result"
if Path(f"{output_name}.tsv").exists():
return output_name
report_file = glob(f"{input_name}/*.report")[0]
f = open(report_file)
line_ranked = filter(lambda i: "ranked" in i, f)
allele_abundance = map(
lambda i: re.findall(r"ranked (.*) \(abundance: (.*)%\)", i)[0], # type:ignore
line_ranked,
)
df = pd.DataFrame(allele_abundance, columns=["allele", "abundance"])
df["gene"] = df["allele"].str.split("*", expand=True)[0]
df = (
df.sort_values(["gene", "abundance"], ascending=[True, False])
.groupby("gene")
.head(2)
)
# print(df)
df1 = allelesToTable(df["allele"], default_gene=["A", "B", "C"])
df1["name"] = input_name
df1.to_csv(output_name + ".tsv", index=False, sep="\t")
return output_name
def hlascanBuild(folder: str = "hlascan", db_hla: str = "origin") -> str:
"""https://github.com/SyntekabioTools/HLAscan"""
output_name = f"{folder}/origin"
if Path(output_name + ".IMGT").exists():
return output_name
runShell(
f"wget https://github.com/SyntekabioTools/HLAscan/releases/download/v2.0.0/dataset.zip -P {folder}"
)
runShell(f"unzip {folder}/dataset.zip -d {folder}")
runShell(f"mv {folder}/db/HLA-ALL.IMGT {output_name}.IMGT")
return output_name
def hlascanPreRun(input_name: str, index: str) -> str:
"""Split the gene before hlascanRun"""
output_name = input_name + ".hlascan_" + name2Single(index) + ".gene.{}"
if Path(f"{output_name.format('TAP2')}.sh").exists():
return output_name
genes = [
"HLA-A",
"HLA-B",
"HLA-C",
"HLA-E",
"HLA-F",
"HLA-G",
"MICA",
"MICB",
"HLA-DMA",
"HLA-DMB",
"HLA-DOA",
"HLA-DOB",
"HLA-DPA1",
"HLA-DPB1",
"HLA-DQA1",
"HLA-DQB1",
"HLA-DRA",
"HLA-DRB1",
"HLA-DRB5",
"TAP1",
"TAP2",
]
for gene in genes:
with open(f"{output_name.format(gene)}.sh", "w") as f:
if Path(input_name + ".bam").exists():
f.write("set -ex\n")
if "hs37" in input_name:
version = "37"
elif "hs38" in input_name:
version = "38"
else:
raise ValueError("reference version cannot determine")
f.write(
f"hlascan -g {gene} -t {getThreads()} -d {index}.IMGT"
f" -b {input_name}.bam -v {version}"
f" > {output_name.format(gene)}.txt"
)
else:
f.write(
f"hlascan -g {gene} -t {getThreads()} -d {index}.IMGT"
f" -l {input_name}.read.1.fq.gz"
f" -r {input_name}.read.2.fq.gz"
f" > {output_name.format(gene)}.txt"
)
return output_name
def hlascanRun(input_name: str) -> str:
"""
https://github.com/SyntekabioTools/HLAscan
I'm not sure what input should given for hlascan:
* selected Fastq
* hs38 with alt (hs38DH)?
* hs37 or hs37d5
"""
output_name = input_name
if Path(f"{output_name}.txt").exists():
return output_name
try:
runDocker("hlascan", f"bash {input_name}.sh")
except subprocess.CalledProcessError as e:
pass
return output_name
def hlascanReadResult(input_name: str) -> str:
"""
Turn hlascan's HLA txt into our hla_result format.
Note that the txt files is splitted by hla gene
It's format:
```
HLA gene : HLA-DPA1
# of considered types : 40
----------- HLA-Types ----------
[Type 1] 02:02:06 EX2_2.85366_53.3333 EX3_0_0 EX4_0_0
[Type 2] 02:02:06 EX2_2.85366_53.3333 EX3_0_0 EX4_0_0
```
"""
output_name = input_name.replace(".{}", "_merge") + ".hla_result"
if Path(f"{output_name}.tsv").exists():
return output_name
alleles = []
for gene in ["HLA-A", "HLA-B", "HLA-C"]:
gene_name = gene.split("-")[1]
for i in open(input_name.replace("{}", f"{gene}.txt")):
if "[Type" in i:
alleles.append(f"{gene_name}*{i.split()[2]}")
df = allelesToTable(alleles, default_gene=["A", "B", "C"])
df["name"] = input_name
df.to_csv(output_name + ".tsv", index=False, sep="\t")
return output_name
def vbseqBuild(folder: str, db_hla: str = "origin") -> str:
"""The document said it's able to use newest IMGT-HLA databse"""
if db_hla == "origin":
output_name = folder + "/hla_3310"
else:
output_name = folder + "/" + Path(db_hla).name
if Path(f"{output_name}.all.fa").exists():
return output_name
# default version
if db_hla == "origin":
runShell(
"wget https://nagasakilab.csml.org/hla/Allelelist_v2.txt"
f" -O {output_name}.allelelist.txt"
)
runShell(
"wget https://nagasakilab.csml.org/hla/hla_all_v2.fasta"
f" -O {output_name}.all.fa"
)
else:
# csv -> special txt
df = pd.read_csv(open(f"{db_hla}/Allelelist.txt"), comment="#")
df.to_csv(f"{output_name}.allelelist.txt", index=False, header=False, sep=" ")
runShell(f"cp {db_hla}/hla_gen.fasta {output_name}.all.fa")
bwaIndex(output_name + ".all.fa")
return output_name
def vbseqPreprocess(input_name: str) -> str:
output_name = input_name + ".vbseq_extract"
if Path(f"{output_name}.bam").exists():
return output_name
runDocker(
"samtools",
f"""\
samtools view {input_name}.bam \
6:29907037-29915661 6:31319649-31326989 6:31234526-31241863 \
6:32914391-32922899 6:32900406-32910847 6:32969960-32979389 \
6:32778540-32786825 6:33030346-33050555 6:33041703-33059473 \
6:32603183-32613429 6:32707163-32716664 6:32625241-32636466 \
6:32721875-32733330 6:32405619-32414826 6:32544547-32559613 \
6:32518778-32554154 6:32483154-32559613 6:30455183-30463982 \
6:29689117-29699106 6:29792756-29800899 6:29793613-29978954 \
6:29855105-29979733 6:29892236-29899009 6:30225339-30236728 \
6:31369356-31385092 6:31460658-31480901 6:29766192-29772202 \
6:32810986-32823755 6:32779544-32808599 6:29756731-29767588 \
-o {output_name}.bam
""",
)
return bam2Fastq(output_name)
def vbseqRun(input_name: str, index: str) -> str:
"""https://nagasakilab.csml.org/hla/"""
output_name = input_name + ".vbseq_" + name2Single(index)
output_name1 = output_name + ".est"
output_name2 = output_name1 + ".call"
if Path(f"{output_name2}.txt").exists():
return output_name2
runDocker(
"bwa",
f"bwa mem -t {getThreads()} -P -L 10000 -a {index}.all.fa"
f" {input_name}.read.1.fq.gz {input_name}.read.2.fq.gz -o {output_name}.sam",
)
runDocker(
"vbseq",
f"java -jar /opt/HLAVBSeq.jar {index}.all.fa"
f" {output_name}.sam {output_name1}.txt "
" --alpha_zero 0.01 --is_paired",
)
runDocker(
"vbseq",
f"perl /opt/parse_result.pl {index}.allelelist.txt"
f" {output_name1}.txt > {output_name2}.txt",
)
return output_name2
def vbseqReadResult(input_name: str) -> str:
"""
Read vbseq hla and coverage result into our hla_result format.
It's format:
```
A*02:03:01 0
A*02:03:03 0
A*02:03:04 0.996701649175412
A*02:04 0
```
"""
output_name = input_name + ".hla_result"
if Path(f"{output_name}.tsv").exists():
return output_name
df = pd.read_csv(input_name + ".txt", sep="\t", names=["allele", "coverage"])
if not len(df):
df1 = allelesToTable([], default_gene=["A", "B", "C"])
df1["name"] = input_name
df1.to_csv(output_name + ".tsv", index=False, sep="\t")
return output_name
df["gene"] = df["allele"].str.split("*", expand=True)[0]
df = df[df["coverage"] > 5]
df = (
df.sort_values(["gene", "coverage"], ascending=[True, False])
.groupby("gene")
.head(2)
)
df1 = allelesToTable(df["allele"], default_gene=["A", "B", "C"])
df1["name"] = input_name
df1.to_csv(output_name + ".tsv", index=False, sep="\t")
return output_name
def hlalaBuild(folder: str = "hlala", db_hla: str = "origin") -> str:
"""https://github.com/DiltheyLab/HLA-LA"""
output_name = f"{folder}/origin"
if Path(f"{output_name}/serializedGRAPH").exists():
return output_name
runShell(
"wget http://www.well.ox.ac.uk/downloads/PRG_MHC_GRCh38_withIMGT.tar.gz"
f" -P {folder}"
)
runShell(f"tar -vxf {folder}/PRG_MHC_GRCh38_withIMGT.tar.gz -C {folder}")
runShell(f"mv {folder}/PRG_MHC_GRCh38_withIMGT {output_name}")
runDocker(
"hlala",
"sh -c 'export PATH=/usr/local/opt/hla-la/bin:$PATH && "
f"HLA-LA --workingDir ./ --action prepareGraph --PRG_graph_dir {output_name}'",
)
return output_name
def hlalaRun(input_name: str, index: str) -> str:
"""https://github.com/DiltheyLab/HLA-LA"""
input_name = addUnmap(input_name)
output_name = input_name + ".hlala_" + name2Single(index)
if Path(f"{output_name}/data/hla/R1_bestguess_G.txt").exists():
return output_name
runShell(f"mkdir -p {output_name}")
runDocker(
"hlala",
f"HLA-LA.pl --graph . --maxThreads {getThreads()}"
f" --workingDir {output_name} --BAM {input_name}.bam --sampleID data",
mounts=[(index, "/usr/local/opt/hla-la/graphs/")],
)
return output_name
def hlalaReadResult(input_name: str) -> str:
"""
Read HLA-LA guess into our hla_result format
It's format:
```
Locus Chromosome Allele Q1 ...
A 1 A*11:01:01G 1 -70 ...
A 2 A*01:01:01G 1 -70 ...
```
"""
output_name = input_name + ".hla_result"
if Path(f"{output_name}.tsv").exists():
return output_name
df = pd.read_csv(f"{input_name}/data/hla/R1_bestguess_G.txt", sep="\t")
df = df[df["AverageCoverage"] > 5]
df1 = allelesToTable(df["Allele"], default_gene=["A", "B", "C"])
# print(df1)
df1["name"] = input_name
df1.to_csv(output_name + ".tsv", index=False, sep="\t")
return output_name
def xhlaBuild(folder: str, db_hla: str = "origin") -> str:
"""
The HLA data is saved in image.
If you want to update the HLA index,
you should build it by script proived in github,
and wait for 7 hours to built.
"""
if db_hla == "origin":
output_name = folder + "/origin"
else:
output_name = f"{folder}/{Path(db_hla).name}"
if Path(output_name).exists():
return output_name
if db_hla == "origin":
runDocker("xhla", f"cp -r /opt/data {output_name}")
else:
output_name1 = output_name + "_tmp"
runShell(f"git clone https://github.com/humanlongevity/HLA {output_name1}")
runShell(f"cd {output_name1} && git checkout 34221ea")
runShell(f"mkdir -p {output_name1}/raw")
runShell(f"cp -r {db_hla}/alignments {output_name1}/raw")
for i in ["nuc", "exon", "dna", "temp", "align"]:
runShell(f"mkdir -p {output_name1}/data/{i}")
runDocker("xhla", f"bash script/batch.sh", chdir=f"{output_name1}/data")
runDocker(
"xhla",
"diamond makedb --in hla.faa --db hla.dmnd",
chdir=f"{output_name1}/data/",
)
runShell(f"mv {output_name1}/data {output_name}")
# runShell(f"rm -rf {output_name1}")
return output_name
return output_name
def xhlaRun(input_name: str, index: str) -> str:
"""
https://github.com/humanlongevity/HLA
Don't input hg19 or hs38DH bam file
"""
output_name = input_name + ".xhla_" + name2Single(index)
if Path(f"{output_name}.json").exists():
return output_name
# Full typing result is not in output_path. It's in hla-{id}.
# see bin/run.py and bin/typer.sh
id = Path(output_name).name
runDocker(
"xhla", f"typer.sh {input_name}.bam {id} full", mounts=[(index, "/opt/data")]
)
runShell(f"mv hla-{id}/{id}* {Path(output_name).parent}")
runShell(f"rm hla-{id} -r")
return output_name
def xhlaReadResult(input_name: str) -> str:
"""
Read xhla json into our hla_result format
Its format:
```
{
"sample_id": "NA12878.bwa_bwakit_hs38_fa.xhla_xhla_origin",
"hla": {
"alleles": [