-
Notifications
You must be signed in to change notification settings - Fork 4
/
make_hub.py
executable file
·2356 lines (2116 loc) · 117 KB
/
make_hub.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
# WARNINGS:
#
# 1) Display of hints has been adapted to BRAKER hints format
# 2) This script retrieves the binaries for linux and os x64 bit systems. It
# will not work on other architectures and systems unless the required
# UCSC tool binaries are already present.
import os
import errno
import os.path
import argparse
import re
import shutil
import platform
import urllib.request
import subprocess
from difflib import SequenceMatcher
from inspect import currentframe, getframeinfo
try:
from Bio.Seq import Seq
from Bio import SeqIO
from Bio.SeqRecord import SeqRecord
except ImportError:
frameinfo = getframeinfo(currentframe())
raise ImportError('In file ' + frameinfo.filename + ' at line ' +
str(frameinfo.lineno) + ': ' +
'Failed to import biophython modules. ' +
'Try installing with \"pip3 install biopython\"')
__author__ = "Kathairna J. Hoff"
__copyright__ = "Copyright 2019-2022. All rights reserved."
__credits__ = "Mario Stanke"
__license__ = "Artistic Licsense"
__version__ = "1.0.8"
__email__ = "[email protected]"
__status__ = "production"
ucsc_tools = {'bedToBigBed': '', 'genePredCheck': '', 'faToTwoBit': '',
'gtfToGenePred': '', 'hgGcPercent': '', 'ixIxx': '',
'twoBitInfo': '', 'wigToBigWig': '', 'genePredToBed': '',
'genePredToBigGenePred': ''}
ucsc_as_files = {'bigGenePred.as': None, 'cytoBand.as': None}
augustus_tools = {'bam2wig': ''}
parser = argparse.ArgumentParser(
description='Generate UCSC assembly hub (e.g. from BRAKER or MAKER output).')
parser.add_argument('-p', '--printUsageExamples', action='store_true',
help="Print usage examples for make_hub.py")
parser.add_argument('-e', '--email', required=False, type=str,
help='Contact e-mail adress for assembly hub')
parser.add_argument('-g', '--genome', required=False, type=str,
help='Genome fasta file (possibly softmasked)')
parser.add_argument('-L', '--long_label', required=False, type=str,
help='Long label for hub, e.g. species name in english ' +
'and latin, pass in single quotation marks, e.g. ' +
'--long_label \'Dorosphila melanogster (fruit fly)\'')
parser.add_argument('-l', '--short_label', required=False, type=str,
help='Short label for hub, will also be used as ' +
'directory name for hub, should not contain spaces or ' +
'special characters, e.g. --short_label fly')
parser.add_argument('-b', '--bam', required=False, type=str, nargs="+",
help='BAM file(s) - space separated - with RNA-Seq ' +
'information, by default will be displayed as bigWig')
parser.add_argument('-c', '--threads', required=False, type=int, default=1,
help='Number of threads for samtools sort processes')
parser.add_argument('-d', '--display_bam_as_bam', action='store_true',
help="Display BAM file(s) as bam tracks")
parser.add_argument('-E', '--gemoma_filtered_predictions', required=False, type=str,
help="GFF3 output file of Gemoma")
parser.add_argument('-X', '--braker_out_dir', required=False, type=str,
help="BRAKER output directory with GTF files; works also " +
"for GALBA, warnings are expected in case of GALBA as input.")
parser.add_argument('-M', '--maker_gff', required=False, type=str,
help='MAKER2 output file in GFF3 format')
parser.add_argument('-I', '--glimmer_gff', required= False, type=str,
help="GFF3 output file of GlimmerHMM")
parser.add_argument('-S', '--snap_gff', required=False, type = str,
help='SNAP output file in GFF3 format')
parser.add_argument('-a', '--annot', required=False, type=str,
help='GTF file with reference annotation')
parser.add_argument('-G', '--gene_track', required=False, nargs='+',
help="Gene track with user specified label, argument " +
"must be formatted as follows: --gene_track file.gtf tracklabel")
# The following argument is for adding a track to an existing hub, i.e.
# producing the files required for the track and writing into existing
# configuration files; requires the directory tmp to be present
parser.add_argument('-A', '--add_track', action='store_true',
help="Add track(s) to existing hub")
parser.add_argument('-o', '--outdir', required=False, type=str, default='.',
help="output directory to write hub to")
parser.add_argument('-n', '--no_repeats', action='store_true',
help="Disable repeat track generation from softmasked " +
"genome sequence (saves time)")
parser.add_argument('-s', '--SAMTOOLS_PATH', required=False, type=str,
help="Path to samtools executable")
parser.add_argument('-B', '--BAM2WIG_PATH', required=False, type=str,
help="Path to bam2wig executable")
parser.add_argument('-i', '--hints', required=False, type=str,
help='GFF file with AUGUSTUS hints')
parser.add_argument('-t', '--traingenes', required=False, type=str,
help='GTF file with training genes')
parser.add_argument('-m', '--genemark', required=False, type=str,
help='GTF file with GeneMark predictions')
parser.add_argument('-w', '--aug_ab_initio', required=False, type=str,
help='GTF file with ab initio AUGUSTUS predictions')
parser.add_argument('-x', '--aug_hints', required=False, type=str,
help='GTF file with AUGUSTUS predictions with hints')
parser.add_argument('-y', '--aug_ab_initio_utr', required=False, type=str,
help='GTF file with ab initio AUGUSTUS predictions with ' +
'UTRs')
parser.add_argument('-z', '--aug_hints_utr', required=False, type=str,
help='GTF file with AUGUSTUS predictions with hints with ' +
'UTRs')
parser.add_argument('-U', '--braker_genes', required=False, type=str,
help='GTF file with BRAKER genes (generated by TSEBRA).')
parser.add_argument('-N', '--latin_name', required=False, type=str,
help="Latin species name, e.g. \"Drosophila melanogaster\". This " +
"argument must be provided if the hub is supposed to be added to the " +
"public UCSC list.")
parser.add_argument('-V', '--assembly_version', required=False, type=str,
help="Assembly version, e.g. \"BDGP R4/dm3\". This " +
"argument must be provided if the hub is supposed to be added to the " +
"public UCSC list.")
parser.add_argument('-r', '--no_tmp_rm', action='store_true',
help="Do not delete temporary files ")
parser.add_argument('-P', '--no_genePredToBigGenePred', action='store_true',
help='Option for the special case in which the precompiled' +
' UCSC binaries are not working on your system, and you installed ' +
'kentutils from the older ENCODE github repository; if activated, ' +
'gene prediction tracks will be output to bigBed instead of bigGenePred ' +
'format and amino acid display will not be possible in gene tracks.')
parser.add_argument('-u', '--verbosity', required=False, type=int, default=0,
help="If INT>0 verbose output log is produced")
parser.add_argument('-v', '--version', action='version',
version='%(prog)s ' + __version__)
args = parser.parse_args()
if args.verbosity > 3:
print(args)
''' Print usage examples if that is desired '''
if args.printUsageExamples:
print("\nUsage example for generating a novel hub:\n")
print("make_hub.py -l hmi2 -L \"Rodent tapeworm\" -g data/genome.fa -e " +
"[email protected] -a data/annot.gtf -b data/rnaseq.bam -d\n\n")
print("Usage example for adding a gene prediction track to an existing " +
"hub (hub resides in the directory where this command is executed):\n")
print("make_hub.py -l hmi2 -e [email protected] -i data/hintsfile.gff " +
"-A -M data/maker.gff -X data\n")
exit(1)
else:
if args.email is None or args.short_label is None:
print("Error: the following arguments are required: -e/--email, -l/--short_label")
exit(1)
''' Check whether sufficient options have been provided '''
if (args.long_label is None) and (args.short_label is not None) and (args.add_track is False):
print("Warning: no long label specified for creating novel track hub, " +
"will use short label \"" + args.short_label + "\" as long label!")
args.long_label = args.short_label
if ((args.email is None) or (args.genome is None) or (args.short_label is None)) and (args.add_track is False) and (args.printUsageExamples is False):
frameinfo = getframeinfo(currentframe())
print('Usage error in file ' + frameinfo.filename + ' at line ' + str(frameinfo.lineno) + ': '
+ 'If a novel track is created, the following arguments are ' +
'required: -e/--email, -g/--genome, -l/--short_label')
exit(1)
''' Set args in case args.braker_out_dir is specified and they are otherwise unset '''
if args.braker_out_dir:
if re.search(r'[^/]$', args.braker_out_dir):
args.braker_out_dir = args.braker_out_dir + "/"
if os.path.isdir(args.braker_out_dir):
# set args.hints
if (args.hints is None) and os.path.isfile(args.braker_out_dir + "hintsfile.gff"):
args.hints = args.braker_out_dir + "hintsfile.gff"
# set args.traingenes
if args.traingenes is None:
if os.path.isfile(args.braker_out_dir + "GeneMark-ES/genemark.d.gtf"):
args.traingenes = args.braker_out_dir + "GeneMark-ES/genemark.d.gtf"
elif os.path.isfile(args.braker_out_dir + "GeneMark-ES/genemark.f.good.gtf"):
args.traingenes = args.braker_out_dir + "GeneMark-ES/genemark.f.good.gtf"
elif os.path.isfile(args.braker_out_dir + "GeneMark-ET/genemark.d.gtf"):
args.traingenes = args.braker_out_dir + "GeneMark-ET/genemark.d.gtf"
elif os.path.isfile(args.braker_out_dir + "GeneMark-ET/genemark.f.good.gtf"):
args.traingenes = args.braker_out_dir + "GeneMark-ET/genemark.f.good.gtf"
elif os.path.isfile(args.braker_out_dir + "GeneMark-EP/genemark.d.gtf"):
args.traingenes = args.braker_out_dir + "GeneMark-EP/genemark.d.gtf"
elif os.path.isfile(args.braker_out_dir + "GeneMark-EP/genemark.f.good.gtf"):
args.traingenes = args.braker_out_dir + "GeneMark-EP/genemark.f.good.gtf"
elif os.path.isfile(args.braker_out_dir + "GeneMark-ETP/genemark.d.gtf"):
args.traingenes = args.braker_out_dir + "GeneMark-ETP/genemark.d.gtf"
elif os.path.isfile(args.braker_out_dir + "GeneMark-ETP/genemark.f.good.gtf"):
args.traingenes = args.braker_out_dir + "GeneMark-ETP/genemark.f.good.gtf"
else:
print("Warning: did not set args.traingenes because none of the " +
"expected training gene structure files exists in " +
args.braker_out_dir)
# set args.genemark
if args.genemark is None:
if os.path.isfile(args.braker_out_dir + "GeneMark-ES/genemark.gtf"):
args.genemark = args.braker_out_dir + "GeneMark-ES/genemark.gtf"
elif os.path.isfile(args.braker_out_dir + "GeneMark-ET/genemark.gtf"):
args.genemark = args.braker_out_dir + "GeneMark-ET/genemark.gtf"
elif os.path.isfile(args.braker_out_dir + "GeneMark-EP/genemark.gtf"):
args.genemark = args.braker_out_dir + "GeneMark-EP/genemark.gtf"
elif os.path.isfile(args.braker_out_dir + "GeneMark-ETP/genemark.gtf"):
args.genemark = args.braker_out_dir + "GeneMark-ETP/genemark.gtf"
else:
print("Warning: did not set args.genemark because none of the " +
"expected genemark.gtf files exists in " +
args.braker_out_dir)
# set args.aug_ab_initio
if args.aug_ab_initio is None:
if os.path.isfile(args.braker_out_dir + "Augustus/augustus.ab_initio.gtf"):
args.aug_ab_initio = args.braker_out_dir + "Augustus/augustus.ab_initio.gtf"
elif os.path.isfile(args.braker_out_dir + "augustus.ab_initio.gtf"):
args.aug_ab_initio = args.braker_out_dir + "augustus.ab_initio.gtf"
else:
print("Warning: did not set args.aug_ab_initio because the " +
"file augustus.ab_initio.gtf does not exist in " +
args.braker_out_dir)
# set args.aug_hints
if args.aug_hints is None:
if os.path.isfile(args.braker_out_dir + "Augustus/augustus.hints.gtf"):
args.aug_hints = args.braker_out_dir + "Augustus/augustus.hints.gtf"
elif os.path.isfile(args.braker_out_dir + "augustus.hints.gtf"):
args.aug_hints = args.braker_out_dir + "augustus.hints.gtf"
else:
print("Warning: did not set args.aug_hints because the " +
"file augustus.hints.gtf does not exist in " +
args.braker_out_dir)
# set args.aug_ab_initio_utr
if args.aug_ab_initio_utr is None:
if os.path.isfile(args.braker_out_dir + "Augustus/augustus.ab_initio_utr.gtf"):
args.aug_ab_initio_utr = args.braker_out_dir + "Augustus/augustus.ab_initio_utr.gtf"
elif os.path.isfile(args.braker_out_dir + "augustus.ab_initio_utr.gtf"):
args.aug_ab_initio_utr = args.braker_out_dir + "augustus.ab_initio_utr.gtf"
else:
print("Warning: did not set args.aug_ab_initio_utr because the " +
"file augustus.ab_initio_utr.gtf does not exist in " +
args.braker_out_dir)
# set args.aug_hints_utr
if args.aug_hints_utr is None:
if os.path.isfile(args.braker_out_dir + "Augustus/augustus.hints_utr.gtf"):
args.aug_hints_utr = args.braker_out_dir + "Augustus/augustus.hints_utr.gtf"
elif os.path.isfile(args.braker_out_dir + "augustus.hints_utr.gtf"):
args.aug_hints_utr = args.braker_out_dir + "augustus.hints_utr.gtf"
else:
print("Warning: did not set args.aug_hints_utr because the " +
"file augustus.hints_utr.gtf does not exist in " +
args.braker_out_dir)
# set args.braker_genes
if args.braker_genes is None:
if os.path.isfile(args.braker_out_dir + "braker.gtf"):
args.braker_genes = args.braker_out_dir + "braker.gtf"
else:
print("Warning: did not set args.braker_genes because the " +
"file augustus.hints_utr.gtf does not exist in " +
args.braker_out_dir)
''' Check whether args.outdir exists and is writable '''
if not os.path.isdir(args.outdir):
frameinfo = getframeinfo(currentframe())
print('Error in file ' + frameinfo.filename + ' at line ' +
str(frameinfo.lineno) + ': specified argument for --outdir ' +
"(" + args.outdir + ") is not a directory!")
exit(1)
elif not os.access(args.outdir, os.W_OK):
frameinfo = getframeinfo(currentframe())
print('Error in file ' + frameinfo.filename + ' at line ' +
str(frameinfo.lineno) + ': specified argument for --outdir ' +
"(" + args.outdir + ") is not writable!")
exit(1)
tmp_dir = args.outdir + "/tmp-" + args.short_label + "/"
hub_dir = args.outdir + "/" + args.short_label + \
"/" + args.short_label + "/"
''' Find samtools (if bam file provided) '''
samtools = ""
if args.bam:
if args.verbosity > 0:
print("Searching for samtools:")
if args.bam and args.SAMTOOLS_PATH:
samtools = args.SAMTOOLS_PATH + "/samtools"
if not(os.access(samtools, os.X_OK)):
frameinfo = getframeinfo(currentframe())
print('Error in file ' + frameinfo.filename + ' at line ' +
str(frameinfo.lineno) + ': ' + samtools + " is not executable!")
exit(1)
else:
if args.verbosity > 0:
print("Will use " + samtools)
elif args.bam:
if shutil.which("samtools") is not None:
samtools = shutil.which("samtools")
if args.verbosity > 0:
print("Will use " + samtools)
else:
frameinfo = getframeinfo(currentframe())
print('Error in file ' + frameinfo.filename + ' at line ' +
str(frameinfo.lineno) + ': '
+ "Unable to locate samtools binary!")
print("samtools is available as package in many Linux distributions.")
print("For example, on Ubuntu, try installing with:")
print("\"sudo apt install samtools\"")
print("If samtools is unavailable as a package, you can obtain it " +
"from github at:")
print("https://github.com/samtools/samtools")
exit(1)
''' Find either Augustus auxprog bam2wig (optional dependency) '''
bam2wig_aug = False
if args.bam:
if args.verbosity > 0:
print("Searching for bam2wig from AUGUSTUS auxprogs:")
if args.BAM2WIG_PATH is not None:
if os.access(args.BAM2WIG_PATH + "/bam2wig", os.X_OK):
augustus_tools['bam2wig'] = args.BAM2WIG_PATH + "/bam2wig"
bam2wig_aug = True
elif shutil.which("bam2wig") is not None:
augustus_tools['bam2wig'] = shutil.which("bam2wig")
bam2wig_aug = True
else:
frameinfo = getframeinfo(currentframe())
print('Was unable to locate bam2wig from ' +
'AUGUSTUS auxprogs (available at ' +
'https://github.com/Gaius-Augustus/Augustus). ' +
'Will convert bam to wig using samtools pileup ' +
'and line-by-line processing, instead.')
''' Find gzip '''
gzip_tool = ""
if (not args.add_track) or args.bam:
gzip_tool = shutil.which('gzip')
if gzip_tool is None:
frameinfo = getframeinfo(currentframe())
print('Error in file ' + frameinfo.filename + ' at line ' +
str(frameinfo.lineno) + ': ' +
"Unable to locate gzip")
print("gzip is available as package in many Linux distributions.")
print("For example, pn Ubuntu, try installing with:")
print("\"sudo apt install gzip\"")
print("If gzip is unavailable as a package, you can obtain it " +
"from:")
print("https://ftp.gnu.org/gnu/gzip/")
quit(1)
''' Find bash sort '''
sort_tool = shutil.which('sort')
if sort_tool is None:
frameinfo = getframeinfo(currentframe())
print('Error in file ' + frameinfo.filename + ' at line ' +
str(frameinfo.lineno) + ': ' + "Unable to locate bash tool 'sort'")
print('sort is part of most Linux distributions. On Ubuntu, it is ' +
'part of the package coreutils. Try re-installing your bash if sort' +
' is missing on your system.')
quit(1)
''' Find or obtain UCSC tools '''
# the URLs of UCSC tool download are hardcoded for linux.x84_64
arch = platform.machine()
plat_sys = platform.system()
if args.verbosity > 0:
print("Searching for required UCSC tools:")
for key, val in ucsc_tools.items():
# genePredToBigBed is optional because some users might not have easy access
if key == 'genePredToBigBed' and no_genePredToBigBed:
continue
if shutil.which(key) is not None:
ucsc_tools[key] = shutil.which(key)
elif os.path.isfile(os.getcwd() + "/" + key):
ucsc_tools[key] = os.getcwd() + "/" + key
if not(os.access(ucsc_tools[key], os.X_OK)):
os.chmod(ucsc_tools[key], 0o777)
else:
if not(arch == 'x86_64'):
frameinfo = getframeinfo(currentframe())
print('Error in file ' + frameinfo.filename + ' at line ' +
str(frameinfo.lineno) + ': '
+ "This script depends on binaries that are available for " +
"x86_64 architecture for linux and MacOX. " +
"We have determined that your system architecture is " +
arch + "." +
" Please try downloading " + key +
" for your architecture from: " +
"http://hgdownload.soe.ucsc.edu/admin/exe")
exit(1)
elif not(plat_sys == 'Linux') and not(plat_sys == 'Darwin'):
frameinfo = getframeinfo(currentframe())
print('Error in file ' + frameinfo.filename + ' at line ' +
str(frameinfo.lineno) + ': '
+ "This script depends on binaries that are available for " +
"x86_64 architecture for linux and MacOX. " +
"We have determined that your system is " +
plat_sys + "." +
" Please try downloading " + key +
" for your operating system from: " +
"http://hgdownload.soe.ucsc.edu/admin/exe")
exit(1)
else:
if plat_sys == 'Linux':
tool_url = "http://hgdownload.soe.ucsc.edu/admin/exe/linux.x86_64/" + key
elif plat_sys == 'Darwin':
tool_url = "http://hgdownload.soe.ucsc.edu/admin/exe/macOSX.x86_64/" + key
print("Was unable to locate " + key +
" on your system, will try to download it from " + tool_url + "...")
with urllib.request.urlopen(tool_url) as response, open(key, 'wb') as out_file:
shutil.copyfileobj(response, out_file)
ucsc_tools[key] = os.getcwd() + "/" + key
os.chmod(ucsc_tools[key], 0o777)
if args.verbosity > 0:
print("Will use " + ucsc_tools[key])
''' track color defintion '''
col_idx = 0
rgb_cols = ['0,0,0', '255,0,0', '0,255,0', '0,0,255', '176,196,222',
'0,255,255', '255,0,255', '192,192,192', '128,128,128', '128,0,0',
'128,128,0', '0,128,0', '128,0,128', '0,128,128', '0,0,128',
'139,0,0', '220,20,60', '233,150,122', '255,140,0', '218,165,32',
'154,205,50', '34,139,34', '152,251,152', '72,209,203', '176,224,230',
'138,43,226'] # 0 - 25, number: 26
''' Create hub directory structure '''
try:
os.makedirs(hub_dir)
except OSError as e:
if e.errno != errno.EEXIST:
raise
try:
os.makedirs(tmp_dir)
except OSError as e:
if e.errno != errno.EEXIST:
raise
''' When UCSC tools are present, also check for the *.as files or obtain them;
store the as files either make_hub.py directory if it is writable, otherwise
store in temporary hub directory '''
as_url = 'http://genome.ucsc.edu/goldenPath/help/examples/'
for key, val in ucsc_as_files.items():
if ((not args.no_genePredToBigGenePred) and (key == 'BigGenePred.as')) or (key != 'BigGenePred.as'):
as_dir = os.path.dirname(os.path.realpath(__file__))
if os.path.isfile(as_dir + '/' + key):
ucsc_as_files[key] = as_dir + '/' + key
elif os.path.isfile(tmp_dir + '/' + key):
ucsc_as_files[key] = tmp_dir + '/' + key
else:
print("Was unable to locate file " + key + " in " + as_dir + " and " +
tmp_dir + ", will try to download it from " + as_url + "...")
if (not os.access(as_dir, os.W_OK)) and os.access(tmp_dir, os.W_OK):
as_dir = tmp_dir
elif (not os.access(as_dir, os.W_OK)) and (not os.access(tmp_dir, os.W_OK)):
print('Error: neither ' + as_dir + " nor " +
tmp_dir + " are writable directories.")
exit(1)
ucsc_as_files[key] = as_dir + '/' + key
print("Trying to download " + as_url + key +
" and store into " + ucsc_as_files[key])
try:
with urllib.request.urlopen(as_url + key) as response, open(ucsc_as_files[key], 'wb') as out_file:
shutil.copyfileobj(response, out_file)
print("Stored file at " + ucsc_as_files[key] + ".")
except:
frameinfo = getframeinfo(currentframe())
print('Error in file ' + frameinfo.filename + ' at line ' +
str(frameinfo.lineno) + ": Downloading file " + key +
" failed. If your " +
"machine does not have internet access, you may " +
"manually download the file from " + as_url + key +
" and store it in the directory where make_hub.py " +
"resides.")
''' ******************* BEGIN FUNCTIONS *************************************'''
def set_color(c, col_lst):
if c <= len(col_lst)-2:
c = c+1
else:
c = 0
return c, col_lst[c]
def set_visibility(v):
if v < 10:
print_vis = "dense"
v = v + 1
else:
print_vis = "hide"
return v, print_vis
''' Function that runs a subprocess with arguments '''
def run_simple_process(args_lst):
try:
# bed files need sorting with LC_COLLATE=C
myenv = os.environ.copy()
myenv['LC_COLLATE'] = 'C'
if args.verbosity > 0:
print("Trying to execute the following command:")
print(" ".join(args_lst))
result = subprocess.run(
args_lst, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=myenv)
if args.verbosity > 0:
print("Suceeded in executing command.")
if(result.returncode == 0):
return(result)
else:
frameinfo = getframeinfo(currentframe())
print('Error in file ' + frameinfo.filename + ' at line ' +
str(frameinfo.lineno) + ': ' + "Return code of subprocess was " +
str(result.returncode) + str(result.args))
quit(1)
except subprocess.CalledProcessError as grepexc:
frameinfo = getframeinfo(currentframe())
print('Error in file ' + frameinfo.filename + ' at line ' +
str(frameinfo.lineno) + ': ' + "Failed executing: ",
" ".join(grepexec.args))
print("Error code: ", grepexc.returncode, grepexc.output)
quit(1)
''' Function that runs a subprocess with input from STDIN '''
def run_process_stdinput(args_lst, byte_obj):
try:
# bed files need sorting with LC_COLLATE=C
myenv = os.environ.copy()
myenv['LC_COLLATE'] = 'C'
if args.verbosity > 0:
print("Trying to execute the following command with input from " +
"STDIN:")
print(" ".join(args_lst))
result = subprocess.run(args_lst, input=byte_obj,
stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=myenv)
if args.verbosity > 0:
print("Suceeded in executing command.")
if(result.returncode == 0):
return(result)
else:
frameinfo = getframeinfo(currentframe())
print('Error in file ' + frameinfo.filename + ' at line ' +
str(frameinfo.lineno) + ': '
+ "run_process_stdinput: return code of subprocess was "
+ str(result.returncode))
quit(1)
except subprocess.CalledProcessError as grepexc:
frameinfo = getframeinfo(currentframe())
print('Error in file ' + frameinfo.filename + ' at line ' +
str(frameinfo.lineno) + ': ' +
"Failed executing: ", " ".join(grepexec.args))
print("Error code: ", grepexc.returncode, grepexc.output)
quit(1)
''' Function that sanity checks and fixes a gtf file, e.g. for strand problems '''
def make_gtf_sane(annot_file, ucsc_file):
try:
with open(annot_file, "r") as annot_handle:
txs = {}
for line in annot_handle:
if ('transcript_id' in line):
if(re.search(
r'(\S+)(\t[^\t]+\t\S+\t\d+\t\d+\t\S+\t)(\S+)(\t\S+\t).*transcript_id\s\"(\S*)\"', line)):
seq, first_part, strand, second_part, txid = re.search(
r'(\S+)(\t[^\t]+\t\S+\t\d+\t\d+\t\S+\t)(\S+)(\t\S+\t).*transcript_id\s\"(\S*)\"', line).groups()
if len(txid) != 0:
if txid not in txs:
txs[txid] = {'strand': strand,
'lines': [], 'sane': True}
else:
if not(strand == txs[txid]['strand']):
txs[txid]['sane'] = False
txs[txid]['lines'].append(line)
else:
print(line)
except IOError:
frameinfo = getframeinfo(currentframe())
print('Error in file ' + frameinfo.filename + ' at line ' +
str(frameinfo.lineno) + ': ' + "Failed to open file " +
annot_file + " for reading!")
quit(1)
try:
with open(ucsc_file, "w") as ucsc_handle:
for key, value in txs.items():
if value['sane'] == True:
for line in value['lines']:
ucsc_handle.write(line)
else:
for line in value['lines']:
seq, first_part, strand, second_part, txid = re.search(
r'^(\S+)(\t\S+\t\S+\t\d+\t\d+\t\S+\t)(\S+)(\t\S+\t).*transcript_id\s\"(\S+)\"', line).groups()
new_gid = txid + "_" + seq + "_" + strand
new_txid = new_gid + ".t1"
ucsc_handle.write(seq + first_part + strand + second_part +
"gene_id \"" + new_gid + "\"; transcript_id \"" + new_txid + "\";\n")
except IOError:
frameinfo = getframeinfo(currentframe())
print('Error in file ' + frameinfo.filename + ' at line ' +
str(frameinfo.lineno) + ': ' + "Failed to open file " +
ucsc_file + " for writing!")
quit(1)
''' Function that converts Gemoma filtered predictions in GFF3 format
to GTF format that is similar to AUGUSTUS GTF format '''
def gemoma2aug_gtf(gemoma_file, aug_like_file):
try:
with open(aug_like_file, "w") as aug_handle:
try:
with open(gemoma_file, "r") as gemoma_handle:
for line in gemoma_handle:
line = line.strip()
if re.search(r'\tCDS\t', line) or re.search(r'\tfive_prime_UTR\t', line) or re.search(r'\tthree_prime_UTR\t', line):
f0, f1, f2, f3, f4, f5, f6, f7, f8 = line.split()
if re.match(r"ID=", f8):
gff3_part = f8.split(";")
tid_part = gff3_part[1].split("=")
gid = tid = tid_part[1]
else:
thismatch = re.search(r'Parent=([^;]+);?', f8)
gid = tid = thismatch.group(1)
if re.search(r'_R\d+', gid):
gid_groups = re.search(
r'(^\S+)_R\d+', gid).groups()
gid = gid_groups[0]
if f2 == 'five_prime_UTR':
f2 = '5\'-UTR'
elif f2 == 'three_prime_UTR':
f2 = '3\'-UTR'
aug_handle.write(f0 + "\t" + f1 + "\t" + f2 + "\t" +
f3 + "\t" + f4 + "\t" + f5 + "\t" +
f6 + "\t" + f7 + "\t" +
"gene_id \"" + gid + "\"; " +
"transcript_id \"" + tid +
"\";\n")
except IOError:
frameinfo = getframeinfo(currentframe())
print('Error in file ' + frameinfo.filename + ' at line ' +
str(frameinfo.lineno) + ': ' + "Failed to open file " + gemoma_file +
" for reading!")
quit(1)
except IOError:
frameinfo = getframeinfo(currentframe())
print('Error in file ' + frameinfo.filename + ' at line ' +
str(frameinfo.lineno) + ': ' + "Failed to open file " + aug_like_file +
" for writing!")
quit(1)
''' Function that converts GlimmerHMM predictions in GFF3 format to GTF format
that is similar to AUGUSTUS GTF format '''
def glimmer2aug_gtf(glimmer_file, aug_like_file):
try:
with open(aug_like_file, "w") as aug_handle:
try:
with open(glimmer_file, "r") as glimmer_handle:
txid = None
for line in glimmer_handle:
line = line.strip()
if re.search(r'\tCDS\t', line):
f0, f1, f2, f3, f4, f5, f6, f7, f8 = line.split()
gff3_part = f8.split(";")
tid_part = gff3_part[1].split("=")
gid = tid_part[1]
aug_handle.write(f0 + "\t" + f1 + "\t" + f2 + "\t" +
f3 + "\t" + f4 + "\t" + f5 + "\t" +
f6 + "\t" + f7 + "\t" +
"gene_id \"" + gid + ".1\"; " +
"transcript_id \"" + gid +
"\";\n")
except IOError:
frameinfo = getframeinfo(currentframe())
print('Error in file ' + frameinfo.filename + ' at line ' +
str(frameinfo.lineno) + ': ' + "Failed to open file " + glimmer_file +
" for reading!")
quit(1)
except IOError:
frameinfo = getframeinfo(currentframe())
print('Error in file ' + frameinfo.filename + ' at line ' +
str(frameinfo.lineno) + ': ' + "Failed to open file " + aug_like_file +
" for writing!")
quit(1)
''' Function that converts SNAP predictions in GFF3 format to GTF format
that is similar to AUGUSTUS GTF format '''
def snap2aug_gtf(snap_file, aug_like_file):
try:
with open(aug_like_file, "w") as aug_handle:
try:
with open(snap_file, "r") as snap_handle:
txid = None
for line in snap_handle:
line = line.strip()
if re.search(r'\tCDS\t', line):
f0, f1, f2, f3, f4, f5, f6, f7 = line.split()
tid_part = f7.split("=")
gid = tid_part[1]
aug_handle.write(f0 + "\t" + f1 + "\t" + f2 + "\t" +
f3 + "\t" + f4 + "\t" + f5 + "\t" +
f6 + "\t.\t" +
"gene_id \"" + gid + ".1\"; " +
"transcript_id \"" + gid +
"\";\n")
except IOError:
frameinfo = getframeinfo(currentframe())
print('Error in file ' + frameinfo.filename + ' at line ' +
str(frameinfo.lineno) + ': ' + "Failed to open file " + snap_file +
" for reading!")
quit(1)
except IOError:
frameinfo = getframeinfo(currentframe())
print('Error in file ' + frameinfo.filename + ' at line ' +
str(frameinfo.lineno) + ': ' + "Failed to open file " + aug_like_file +
" for writing!")
quit(1)
''' Function that reformats AUGUSTUS gtf format to UCSC gtf format '''
def aug2ucsc_gtf(augustus_file, ucsc_file):
try:
with open(augustus_file, "r") as aug_handle:
try:
with open(ucsc_file, "w") as ucsc_handle:
for line in aug_handle:
if re.search(r'\t\S+\tCDS\t', line) or re.search(r'\t\S+\texon\t', line) or re.search(r'\t\S+\tstart_codon\t', line) or re.search(r'\t\S+\t\d+\'-UTR\t', line):
if re.search(r'\S+\t\S+\t\S+\t\d+\t\d+\t\S+\t\S+\t\S+\ttranscript_id\s\"\S+\";\sgene_id\s\"\S+\";', line):
first_part, feature, second_part, gid, txid = re.search(
r'(\S+\t\S+\t)(\S+)(\t\d+\t\d+\t\S+\t\S+\t\S+\t)(transcript_id\s\"\S+\";)\s(gene_id\s\"\S+\";)', line).groups()
elif re.search(r'\S+\t\S+\t\S+\t\d+\t\d+\t\S+\t\S+\t\S+\tgene_id\s\"\S+\";\stranscript_id\s\"\S+\";', line):
first_part, feature, second_part, txid, gid = re.search(
r'(\S+\t\S+\t)(\S+)(\t\d+\t\d+\t\S+\t\S+\t\S+\t)(gene_id\s\"\S+\";)\s(transcript_id\s\"\S+\";)', line).groups()
if re.search(r'5\'-UTR', feature):
feature = "5UTR"
elif re.search(r'3\'-UTR', feature):
feature = "3UTR"
ucsc_handle.write(
first_part + feature + second_part + gid + " " +
txid + "\n")
except IOError:
frameinfo = getframeinfo(currentframe())
print('Error in file ' + frameinfo.filename + ' at line ' +
str(frameinfo.lineno) + ': ' + "Failed to open file " +
ucsc_file + " for writing!")
quit(1)
except IOError:
frameinfo = getframeinfo(currentframe())
print('Error in file ' + frameinfo.filename + ' at line ' +
str(frameinfo.lineno) + ': ' + "Failed to open file " + augustus_file +
" for reading!")
quit(1)
''' Function that writes subprocess byte object to flat file '''
def write_byteobj(byte_obj, outfile):
try:
with open(outfile, 'w') as byteobj_handle:
byteobj_handle.write(byte_obj.decode('utf-8'))
except IOError:
frameinfo = getframeinfo(currentframe())
print('Error in file ' + frameinfo.filename + ' at line ' +
str(frameinfo.lineno) + ': ' + "Failed to open file " + outfile +
" for writing!")
quit(1)
''' Function that determines which regions in genome are softmasked '''
def find_masked_intervals(genome_file, bed3_file):
try:
masked_intervals = []
with open(genome_file, "r") as genome_handle:
for record in SeqIO.parse(genome_handle, "fasta"):
masked_seq = str(record.seq)
inMasked = False
mmEnd = 0
for x in range(0, len(masked_seq)):
if masked_seq[x].islower() and inMasked == False:
mmStart = x + 1
inMasked = True
elif not(masked_seq[x].islower()) and inMasked == True:
mmEnd = x
inMasked = False
if x > 0 and mmEnd > 0:
masked_intervals.append(
{'id': record.id, 'start': mmStart, 'end': mmEnd})
if inMasked == True:
masked_intervals.append(
{'id': record.id, 'start': mmStart, 'end': len(masked_seq)})
except IOError:
frameinfo = getframeinfo(currentframe())
print('Error in file ' + frameinfo.filename + ' at line ' +
str(frameinfo.lineno) + ': ' + "Failed to open file " + genome_file +
" for reading!")
quit(1)
try:
with open(bed3_file, "w+") as bed2_handle:
for x in masked_intervals:
bed2_handle.write(
x['id'] + '\t' + str(x['start']) + '\t' + str(x['end']) +
'\n')
except IOError:
frameinfo = getframeinfo(currentframe())
print('Error in file ' + frameinfo.filename + ' at line ' +
str(frameinfo.lineno) + ': ' + "Failed to open file " + bed3_file +
" for writing!")
quit(1)
''' Function that sorts a bed3 file with LC_COLLATE=C via custom subprocess function'''
def sort_bed3(bed3_file, bed3_sorted_file):
subprcs_args = [sort_tool, '-k1,1', '-k2,2n', bed3_file]
result = run_simple_process(subprcs_args)
write_byteobj(result.stdout, bed3_sorted_file)
''' Function that converts bed to bigBed '''
def bed2bigBed(btype, bed_file, chrom_size_file, bigBedFile, as_file):
print('Generating bigBed file for ' + bed_file + '...')
if as_file is None:
subprcs_args = [ucsc_tools['bedToBigBed'], '-type=bed' +
str(btype), bed_file, chrom_size_file, bigBedFile]
else:
subprcs_args = [ucsc_tools['bedToBigBed'], '-type=bed' +
str(btype), bed_file, '-as=' + as_file, chrom_size_file, bigBedFile]
run_simple_process(subprcs_args)
''' Function that converts bigGenePred bed-format to special bigBed fromat
for gene predictions '''
def bigGenePredToBigBed(as_file, bigGenePred_file, chrom_size_file, bb_file):
print('Generating bigBed file from bigGenePred format for ' +
bigGenePred_file + '...')
subprcs_args = [ucsc_tools['bedToBigBed'], '-as=' + as_file,
'-type=bed12+8', bigGenePred_file, chrom_size_file,
bb_file]
run_simple_process(subprcs_args)
''' Function that converts gtf to genePred format, used in gtf2bb and gtf2bgpbb '''
def gtf2genePred(gtf_file, gp_file, info_out_file, frameGiven):
if frameGiven is True:
subprcs_args = [ucsc_tools['gtfToGenePred'], '-infoOut=' +
info_out_file, '-genePredExt', gtf_file, gp_file]
else:
subprcs_args = [ucsc_tools['gtfToGenePred'], '-infoOut=' +
info_out_file, gtf_file, gp_file]
run_simple_process(subprcs_args)
subprcs_args = [ucsc_tools['genePredCheck'], gp_file]
result = run_simple_process(subprcs_args)
# parse result for failed annotations
annotation_validation_result = result.stderr.decode('utf-8')
if args.verbosity > 0:
print(annotation_validation_result)
regex_result = re.match(
r'checked: \d+ failed: (\d+)', annotation_validation_result)
if int(regex_result.group(1)) > 0:
print("Warning: " + regex_result.group(1) +
" annotations did not pass validation!")
''' Function that converts gtf to bb format '''
def gtf2bb(gtf_file, gp_file, bed_file, bb_file, info_out_file, chrom_size_file,
sort_tool, frameGiven):
gtf2genePred(gtf_file, gp_file, info_out_file, frameGiven)
subprcs_args = [ucsc_tools['genePredToBed'], gp_file, 'stdout']
result = run_simple_process(subprcs_args)
subprcs_args = [sort_tool, '-k1,1', '-k2,2n']
result = run_process_stdinput(subprcs_args, result.stdout)
write_byteobj(result.stdout, bed_file)
bed2bigBed(12, bed_file, chrom_size_file, bb_file, None)
''' Function that converts gtf to bigGenePred bb format (allows display of
amino acids in browser), alternative to gtf2bb '''
def gtf2bgpbb(gtf_file, gp_file, bigGenePred_file, info_out_file, chrom_size_file,
as_file, sort_tool, bb_file, short_label):
gtf2genePred(gtf_file, gp_file, info_out_file, True)
subprcs_args = [ucsc_tools['genePredToBigGenePred'], gp_file, 'stdout']
result = run_simple_process(subprcs_args)
subprcs_args = [sort_tool, '-k1,1', '-k2,2n']
result = run_process_stdinput(subprcs_args, result.stdout)
write_byteobj(result.stdout, bigGenePred_file)
# type and geneType field are empty in resulting file, fix it:
bigGenePredFixed_file = tmp_dir + short_label + ".fixed.bed"
try:
with open(bigGenePred_file, "r") as bigGenePred_handle:
try:
with open(bigGenePredFixed_file, "w") as fixed_handle:
for line in bigGenePred_handle:
line_items = re.split(r'\t+', line)
for i in range(0, 16):
fixed_handle.write(line_items[i] + '\t')
fixed_handle.write(
'none\t' + line_items[16] + '\tnone\t' + line_items[17] + '\n')
except IOError:
frameinfo = getframeinfo(currentframe())
print('Error in file ' + frameinfo.filename + ' at line ' +
str(frameinfo.lineno) + ': ' + "Failed to open file " +
bigGenePredFixed_file + " for writing!")
quit(1)
except IOError:
frameinfo = getframeinfo(currentframe())
print('Error in file ' + frameinfo.filename + ' at line ' +
str(frameinfo.lineno) + ': ' + "Failed to open file " +
bigGenePred_file + " for reading!")
quit(1)
bigGenePredToBigBed(as_file, bigGenePredFixed_file,
chrom_size_file, bb_file)
''' Function that writes info about gene pred or hints to trackDb file '''
def info_to_trackDB(trackDb_file, short_label, long_label, rgb_color, group,
bed_no, visibility, ttype):
# if maker track, use separate name for label...
track_name = short_label
if(re.search(r'_maker', track_name)):
track_name = re.sub(r'_maker', r'', track_name)
try:
with open(trackDb_file, "a") as trackDb_handle:
trackDb_handle.write("track " + short_label + "\n" +
"longLabel " + long_label + "\n" +
"shortLabel " + track_name + "\n" +
"group " + group + "\ntype " + ttype)
if bed_no is not None:
trackDb_handle.write(" " + str(bed_no) + " .")
trackDb_handle.write("\n" +
"bigDataUrl " + short_label + ".bb\n" +
"color " + rgb_color + "\n" +
"visibility " + visibility +
"\nhtml " + short_label + ".html\n\n" +
"group " + group + "\ntype " + ttype)
if bed_no is not None:
trackDb_handle.write(" " + str(bed_no) + " .")
trackDb_handle.write("\n" +