-
Notifications
You must be signed in to change notification settings - Fork 51
Expand file tree
/
Copy path__init__.py
More file actions
3364 lines (2925 loc) · 153 KB
/
__init__.py
File metadata and controls
3364 lines (2925 loc) · 153 KB
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
"""
Comparative Annotation Toolkit.
"""
import string
import random
import datetime
import collections
import logging
import os
import shutil
import json
import subprocess
from collections import OrderedDict
from frozendict import frozendict
from configobj import ConfigObj
import luigi
import luigi.contrib.sqla
from luigi.util import requires
from toil.job import Job
import pandas as pd
from bx.intervals.cluster import ClusterTree
from toil.lib.memoize import memoize
import tools.bio
import tools.fileOps
import tools.intervals
import tools.hal
import tools.misc
import tools.nameConversions
import tools.procOps
import tools.mathOps
import tools.psl
import tools.sqlInterface
import tools.sqlite
import tools.hintsDatabaseInterface
import tools.transcripts
import tools.gff3
from tools.luigiAddons import multiple_requires, IndexTarget
from .align_transcripts import align_transcripts
from .augustus import augustus
from .augustus_cgp import augustus_cgp
from .augustus_pb import augustus_pb
from .chaining import chaining
from .classify import classify
from .consensus import generate_consensus, load_alt_names, load_hgm_vectors
from .filter_transmap import filter_transmap
from .hgm import hgm, parse_hgm_gtf
from .transmap_classify import transmap_classify
from .plots import generate_plots
from .hints_db import hints_db
from .parent_gene_assignment import assign_parents
from .exceptions import *
logger = logging.getLogger('cat')
###
# Base tasks shared by pipeline tasks
###
class PipelineTask(luigi.Task):
"""
Base class for all tasks in this pipeline. Has Parameters for all input parameters that will be inherited
by all downstream tools.
Provides useful methods for handling parameters being passed between modules.
Note: significant here is not the same as significant in get_pipeline_args. Significant here is for the luigi
scheduler to know which parameters define a unique task ID. This would come into play if multiple instances of this
pipeline are being run on the same scheduler at once.
"""
hal = luigi.Parameter()
ref_genome = luigi.Parameter()
config = luigi.Parameter()
out_dir = luigi.Parameter(default='./cat_output')
work_dir = luigi.Parameter(default='./cat_work')
target_genomes = luigi.TupleParameter(default=None)
annotate_ancestors = luigi.BoolParameter(default=False)
binary_mode = luigi.ChoiceParameter(choices=["docker", "local", "singularity"], default='docker',
significant=False)
# AugustusTM(R) parameters
augustus = luigi.BoolParameter(default=False)
augustus_species = luigi.Parameter(default='human', significant=False)
tm_cfg = luigi.Parameter(default='augustus_cfgs/extrinsic.ETM1.cfg', significant=False)
tmr_cfg = luigi.Parameter(default='augustus_cfgs/extrinsic.ETM2.cfg', significant=False)
augustus_utr_off = luigi.BoolParameter(default=False, significant=False)
# AugustusCGP parameters
augustus_cgp = luigi.BoolParameter(default=False)
cgp_param = luigi.Parameter(default=None, significant=False)
augustus_cgp_cfg_template = luigi.Parameter(default='augustus_cfgs/cgp_extrinsic_template.cfg', significant=False)
maf_chunksize = luigi.IntParameter(default=2500000, significant=False)
maf_overlap = luigi.IntParameter(default=500000, significant=False)
cgp_train_num_exons = luigi.IntParameter(default=5000, significant=False)
# AugustusPB parameters
augustus_pb = luigi.BoolParameter(default=False)
pb_genome_chunksize = luigi.IntParameter(default=5000000, significant=False)
pb_genome_overlap = luigi.IntParameter(default=500000, significant=False)
pb_cfg = luigi.Parameter(default='augustus_cfgs/extrinsic.M.RM.PB.E.W.cfg', significant=False)
# Hgm parameters
hgm_cpu = luigi.IntParameter(default=4, significant=False)
# assemblyHub parameters
assembly_hub = luigi.BoolParameter(default=False)
hub_email = luigi.Parameter(default='NoEmail', significant=False)
# Paralogy detection options
global_near_best = luigi.FloatParameter(default=0.15, significant=False)
filter_overlapping_genes = luigi.BoolParameter(default=False, significant=True)
overlapping_gene_distance = luigi.IntParameter(default=1, significant=True)
# consensus options
intron_rnaseq_support = luigi.IntParameter(default=0, significant=False)
exon_rnaseq_support = luigi.IntParameter(default=0, significant=False)
intron_annot_support = luigi.IntParameter(default=0, significant=False)
exon_annot_support = luigi.IntParameter(default=0, significant=False)
original_intron_support = luigi.IntParameter(default=0, significant=False)
denovo_num_introns = luigi.IntParameter(default=0, significant=False)
denovo_splice_support = luigi.IntParameter(default=0, significant=False)
denovo_exon_support = luigi.IntParameter(default=0, significant=False)
denovo_ignore_novel_genes = luigi.BoolParameter(default=False, significant=False)
denovo_only_novel_genes = luigi.BoolParameter(default=False, significant=False)
denovo_novel_end_distance = luigi.IntParameter(default=0, significant=False)
denovo_allow_unsupported = luigi.BoolParameter(default=False, significant=False)
denovo_allow_bad_annot_or_tm = luigi.BoolParameter(default=False, significant=False)
require_pacbio_support = luigi.BoolParameter(default=False, significant=False)
in_species_rna_support_only = luigi.BoolParameter(default=False, significant=True)
rebuild_consensus = luigi.BoolParameter(default=False, significant=True)
# Toil options
batchSystem = luigi.Parameter(default='singleMachine', significant=False)
maxCores = luigi.IntParameter(default=8, significant=False)
parasolCommand = luigi.Parameter(default=None, significant=False)
defaultMemory = luigi.Parameter(default='8G', significant=False)
disableCaching = luigi.BoolParameter(default=False, significant=False)
workDir = luigi.Parameter(default=None, significant=False)
defaultDisk = luigi.Parameter(default='8G', significant=False)
cleanWorkDir = luigi.Parameter(default='onSuccess', significant=False)
provisioner = luigi.Parameter(default=None, significant=False)
nodeTypes = luigi.Parameter(default=None, significant=False)
maxNodes = luigi.Parameter(default=None, significant=False)
minNode = luigi.Parameter(default=None, significant=False)
metrics = luigi.Parameter(default=None, significant=False)
zone = luigi.Parameter(default=None, significant=False)
logLevel = luigi.ChoiceParameter(default="INFO", choices=["INFO", "DEBUG", "ERROR", "WARNING"], significant=False)
def __repr__(self):
"""override the repr to make logging cleaner"""
if hasattr(self, 'genome'):
return 'Task: {} for {}'.format(self.__class__.__name__, self.genome)
elif hasattr(self, 'mode'):
return 'Task: {} for {}'.format(self.__class__.__name__, self.mode)
else:
return 'Task: {}'.format(self.__class__.__name__)
def get_pipeline_args(self):
"""returns a namespace of all of the arguments to the pipeline. Resolves the target genomes variable"""
args = tools.misc.PipelineNamespace()
args.set('binary_mode', self.binary_mode, False)
args.set('hal', os.path.abspath(self.hal), True)
args.set('ref_genome', self.ref_genome, True)
args.set('out_dir', os.path.abspath(self.out_dir), True)
args.set('work_dir', os.path.abspath(self.work_dir), True)
args.set('augustus', self.augustus, True)
args.set('augustus_cgp', self.augustus_cgp, True)
args.set('augustus_pb', self.augustus_pb, True)
args.set('augustus_species', self.augustus_species, True)
args.set('tm_cfg', os.path.abspath(self.tm_cfg), True)
args.set('tmr_cfg', os.path.abspath(self.tmr_cfg), True)
args.set('augustus_cgp', self.augustus_cgp, True)
args.set('maf_chunksize', self.maf_chunksize, True)
args.set('maf_overlap', self.maf_overlap, True)
args.set('pb_genome_chunksize', self.pb_genome_chunksize, True)
args.set('pb_genome_overlap', self.pb_genome_overlap, True)
args.set('pb_cfg', os.path.abspath(self.pb_cfg), True)
args.set('augustus_cgp_cfg_template', os.path.abspath(self.augustus_cgp_cfg_template), True)
args.set('augustus_utr_off', self.augustus_utr_off, True)
if self.cgp_param is not None:
args.set('cgp_param', os.path.abspath(self.cgp_param), True)
else:
args.set('cgp_param', None, True)
args.set('cgp_train_num_exons', self.cgp_train_num_exons, True)
args.set('hgm_cpu', self.hgm_cpu, False)
# user flags for paralog resolution
args.set('global_near_best', self.global_near_best, True)
args.set('filter_overlapping_genes', self.filter_overlapping_genes, True)
args.set('overlapping_gene_distance', self.overlapping_gene_distance, True)
# user specified flags for consensus finding
args.set('intron_rnaseq_support', self.intron_rnaseq_support, False)
args.set('exon_rnaseq_support', self.exon_rnaseq_support, False)
args.set('intron_annot_support', self.intron_annot_support, False)
args.set('exon_annot_support', self.exon_annot_support, False)
args.set('original_intron_support', self.original_intron_support, False)
args.set('denovo_num_introns', self.denovo_num_introns, False)
args.set('denovo_splice_support', self.denovo_splice_support, False)
args.set('denovo_exon_support', self.denovo_exon_support, False)
args.set('denovo_ignore_novel_genes', self.denovo_ignore_novel_genes, False)
args.set('denovo_only_novel_genes', self.denovo_only_novel_genes, False)
args.set('denovo_novel_end_distance', self.denovo_novel_end_distance, False)
args.set('denovo_allow_unsupported', self.denovo_allow_unsupported, False)
args.set('denovo_allow_bad_annot_or_tm', self.denovo_allow_bad_annot_or_tm, False)
args.set('require_pacbio_support', self.require_pacbio_support, False)
args.set('in_species_rna_support_only', self.in_species_rna_support_only, False)
args.set('rebuild_consensus', self.rebuild_consensus, False)
# stats location
args.set('stats_db', os.path.join(args.out_dir, 'databases', 'timing_stats.db'), False)
# flags for assembly hub building
args.set('assembly_hub', self.assembly_hub, False) # assembly hub doesn't need to cause rebuild of gene sets
args.set('hub_email', self.hub_email, False)
# flags for figuring out which genomes we are going to annotate
args.set('annotate_ancestors', self.annotate_ancestors, True)
# halStats is run below, before any validate() methods are called.
if not tools.misc.is_exec('halStats'):
raise ToolMissingException('halStats from the HAL tools package not in global path')
args.set('hal_genomes', tools.hal.extract_genomes(args.hal, self.annotate_ancestors), True)
target_genomes = tools.hal.extract_genomes(args.hal, self.annotate_ancestors, self.target_genomes)
target_genomes = tuple(x for x in target_genomes if x != self.ref_genome)
args.set('target_genomes', target_genomes, True)
args.set('cfg', self.parse_cfg(), True)
args.set('dbs', PipelineTask.get_databases(args), True)
args.set('annotation', args.cfg['ANNOTATION'][args.ref_genome], True)
args.set('hints_db', os.path.join(args.work_dir, 'hints_database', 'hints.db'), True)
args.set('rnaseq_genomes', frozenset(set(args.cfg['INTRONBAM'].keys()) | set(args.cfg['BAM'].keys())), True)
args.set('intron_only_genomes', frozenset(set(args.cfg['INTRONBAM'].keys()) - set(args.cfg['BAM'].keys())), True)
args.set('isoseq_genomes', frozenset(list(args.cfg['ISO_SEQ_BAM'].keys())), True)
args.set('annotation_genomes', frozenset(list(args.cfg['ANNOTATION'].keys())), True)
args.set('external_ref_genomes', args.annotation_genomes - {args.ref_genome}, True)
args.set('modes', self.get_modes(args), True)
args.set('augustus_tmr', True if 'augTMR' in args.modes else False, True)
if self.__class__.__name__ in ['RunCat', 'Augustus', 'AugustusCgp', 'AugustusPb']:
self.validate_cfg(args)
return args
def parse_cfg(self):
"""
Parses the input config file. Config file format:
[ANNOTATION]
annotation = /path/to/gff3
[INTRONBAM]
genome1 = /path/to/non_polyA_bam1.bam, /path/to/non_polyA_bam2.bam
[BAM]
genome1 = /path/to/fofn
[ISO_SEQ_BAM]
genome1 = /path/to/bam/or/fofn
[PROTEIN_FASTA]
genome1 = /path/to/fasta/or/fofn
The annotation field must be populated for the reference genome.
The protein fasta field should be populated for every genome you wish to perform protein alignment to.
BAM annotations can be put either under INTRONBAM or BAM. Any INTRONBAM will only have intron data loaded,
and is suitable for lower quality RNA-seq.
"""
if not os.path.exists(self.config):
raise MissingFileException('Config file {} not found.'.format(self.config))
# configspec validates the input config file
configspec = ['[ANNOTATION]', '__many__ = string',
'[INTRONBAM]', '__many__ = list',
'[BAM]', '__many__ = list',
'[ISO_SEQ_BAM]', '__many__ = list',
'[PROTEIN_FASTA]', '__many__ = list']
parser = ConfigObj(self.config, configspec=configspec)
for key in parser:
if key not in ['ANNOTATION', 'INTRONBAM', 'BAM', 'ISO_SEQ_BAM', 'PROTEIN_FASTA']:
raise InvalidInputException('Invalid field {} in config file'.format(key))
# convert the config into a new dict, parsing the fofns
cfg = collections.defaultdict(dict)
for dtype in ['ANNOTATION', 'PROTEIN_FASTA']:
if dtype not in parser:
cfg[dtype] = {}
else:
for genome, annot in parser[dtype].items():
annot = os.path.abspath(annot)
if not os.path.exists(annot):
raise MissingFileException('Missing {} file {}.'.format(dtype.lower(), annot))
cfg[dtype][genome] = annot
# if a given genome only has one BAM, it is a string. Fix this. Extract all paths from fofn files.
for dtype in ['BAM', 'INTRONBAM', 'ISO_SEQ_BAM']:
if dtype not in parser: # the user does not have to specify all field types
cfg[dtype] = {}
continue
for genome in parser[dtype]:
path = parser[dtype][genome]
if isinstance(path, str):
if not tools.misc.is_bam(path):
# this is a fofn
cfg[dtype][genome] = [os.path.abspath(x.rstrip()) for x in open(path)]
else:
# this is a single BAM
cfg[dtype][genome] = [os.path.abspath(path)]
else:
cfg[dtype][genome] = []
for p in path:
if tools.misc.is_bam(p): # is a bam
cfg[dtype][genome].append(os.path.abspath(p))
else: # assume to be a fofn
cfg[dtype][genome].extend([os.path.abspath(x.rstrip()) for x in open(p)])
# return a hashable version
return frozendict((key, frozendict((ikey, tuple(ival) if isinstance(ival, list) else ival)
for ikey, ival in val.items())) for key, val in cfg.items())
def validate_cfg(self, args):
"""Validate the input config file."""
if len(args.cfg['BAM']) + len(args.cfg['INTRONBAM']) + \
len(args.cfg['ISO_SEQ_BAM']) + len(args.cfg['ANNOTATION']) == 0:
logger.warning('No extrinsic data or annotations found in config. Will load genomes only.')
elif len(args.cfg['BAM']) + len(args.cfg['INTRONBAM']) + len(args.cfg['ISO_SEQ_BAM']) == 0:
logger.warning('No extrinsic data found in config. Will load genomes and annotation only.')
for dtype in ['BAM', 'INTRONBAM', 'ISO_SEQ_BAM']:
for genome in args.cfg[dtype]:
for bam in args.cfg[dtype][genome]:
if not os.path.exists(bam):
raise MissingFileException('Missing BAM {}.'.format(bam))
if not tools.misc.is_bam(bam):
raise InvalidInputException('BAM {} is not a valid BAM.'.format(bam))
if not os.path.exists(bam + '.bai'):
raise MissingFileException('Missing BAM index {}.'.format(bam + '.bai'))
for dtype in ['ANNOTATION', 'PROTEIN_FASTA']:
for genome, annot in args.cfg[dtype].items():
if not os.path.exists(annot):
raise MissingFileException('Missing {} file {}.'.format(dtype.lower(), annot))
if all(g in args.hal_genomes for g in args.target_genomes) is False:
bad_genomes = set(args.hal_genomes) - set(args.target_genomes)
err_msg = 'Genomes {} present in configuration and not present in HAL.'.format(','.join(bad_genomes))
raise UserException(err_msg)
if args.ref_genome not in args.cfg['ANNOTATION']:
raise UserException('Reference genome {} did not have a provided annotation.'.format(self.ref_genome))
# raise if the user if the user is providing dubious inputs
if args.augustus_cgp and len(args.rnaseq_genomes) == 0:
raise InvalidInputException('AugustusCGP is being ran without any RNA-seq hints!')
if args.augustus_pb and len(args.isoseq_genomes) == 0:
raise InvalidInputException('AugustusPB is being ran without any IsoSeq hints!')
def get_modes(self, args):
"""returns a tuple of the execution modes being used here"""
modes = ['transMap']
if args.augustus_cgp is True:
modes.append('augCGP')
if args.augustus is True:
modes.append('augTM')
if len(set(args.rnaseq_genomes) & set(args.target_genomes)) > 0:
modes.append('augTMR')
if args.augustus_pb is True:
modes.append('augPB')
if len(args.annotation_genomes) > 1:
modes.append('exRef')
return tuple(modes)
def get_module_args(self, module, **args):
"""
convenience wrapper that takes a parent module and propagates any required arguments to generate the full
argument set.
"""
pipeline_args = self.get_pipeline_args()
return module.get_args(pipeline_args, **args)
@memoize
def load_docker(self):
"""
Download Docker or Singularity container, if applicable
"""
# We use this environment variable as a bit of global state,
# to avoid threading this through in each of the hundreds of
# command invocations.
os.environ['CAT_BINARY_MODE'] = self.binary_mode
if self.binary_mode == 'docker':
if not tools.misc.is_exec('docker'):
raise ToolMissingException('docker binary not found. '
'Either install it or use a different option for --binary-mode.')
# Update docker container
subprocess.check_call(['docker', 'pull', 'quay.io/ucsc_cgl/cat:latest'])
elif self.binary_mode == 'singularity':
if not tools.misc.is_exec('singularity'):
raise ToolMissingException('singularity binary not found. '
'Either install it or use a different option for --binary-mode.')
os.environ['SINGULARITY_PULLFOLDER'] = os.path.abspath(self.work_dir)
os.environ['SINGULARITY_CACHEDIR'] = os.path.abspath(self.work_dir)
if os.environ.get('SINGULARITY_IMAGE'):
return
tools.fileOps.ensure_dir(self.work_dir)
if not os.path.isfile(os.path.join(self.work_dir, 'cat.img')):
subprocess.check_call(['singularity', 'pull', '--name', 'cat.img',
'docker://quay.io/ucsc_cgl/cat:latest'])
assert os.path.exists(os.path.join(self.work_dir, 'cat.img'))
@staticmethod
def get_databases(pipeline_args):
"""wrapper for get_database() that provides all of the databases"""
dbs = {genome: PipelineTask.get_database(pipeline_args, genome) for genome in pipeline_args.hal_genomes}
return frozendict(dbs)
@staticmethod
def get_database(pipeline_args, genome):
"""database paths must be resolved here to handle multiple programs accessing them"""
base_out_dir = os.path.join(pipeline_args.out_dir, 'databases')
return os.path.join(base_out_dir, '{}.db'.format(genome))
@staticmethod
def get_plot_dir(pipeline_args, genome):
"""plot base directories must be resolved here to handle multiple programs accessing them"""
base_out_dir = os.path.join(pipeline_args.out_dir, 'plots')
return os.path.join(base_out_dir, genome)
@staticmethod
def get_metrics_dir(pipeline_args, genome):
"""plot data directories must be resolved here to handle multiple programs accessing them"""
base_out_dir = os.path.join(pipeline_args.work_dir, 'plot_data')
return os.path.join(base_out_dir, genome)
@staticmethod
def write_metrics(metrics_dict, out_target):
"""write out a metrics dictionary to a path for later loading and plotting"""
tools.fileOps.ensure_file_dir(out_target.path)
with out_target.open('w') as outf:
json.dump(metrics_dict, outf)
@PipelineTask.event_handler(luigi.Event.PROCESSING_TIME)
def processing_time(task, processing_time):
"""
An event to record processing time of each task. This event records directly to a sqlite database.
"""
pipeline_args = task.get_pipeline_args()
stats_db = pipeline_args.stats_db
finish_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
with tools.sqlite.ExclusiveSqlConnection(stats_db) as engine:
c = engine.cursor()
c.execute('create table if not exists stats '
'(TaskId string unique, FinishTime string, ProcessingTime real)')
c.execute('insert or replace into stats values (?, ?, ?)', [task.task_id, finish_time, processing_time])
engine.commit()
class PipelineWrapperTask(PipelineTask, luigi.WrapperTask):
"""add WrapperTask functionality to PipelineTask"""
pass
class AbstractAtomicFileTask(PipelineTask):
"""
Abstract Task for single files.
"""
def run_cmd(self, cmd):
"""
Run a external command that will produce the output file for this task to stdout. Capture this to the file.
"""
# luigi localTargets guarantee atomicity if used as a context manager
with self.output().open('w') as outf:
tools.procOps.run_proc(cmd, stdout=outf)
class ToilTask(PipelineTask):
"""
Task for launching toil pipelines from within luigi.
"""
resources = {'toil': 1} # all toil pipelines use 1 toil
def __repr__(self):
"""override the PipelineTask repr to report the batch system being used"""
base_repr = super(ToilTask, self).__repr__()
return 'Toil' + base_repr + ' using batchSystem {}'.format(self.batchSystem)
def prepare_toil_options(self, work_dir):
"""
Prepares a Namespace object for Toil which has all defaults, overridden as specified
Will see if the jobStore path exists, and if it does, assume that we need to add --restart
:param work_dir: Parent directory where toil work will be done. jobStore will be placed inside. Will be used
to fill in the workDir class variable.
:return: Namespace
"""
toil_args = self.get_toil_defaults()
toil_args.__dict__.update(vars(self))
toil_args.stats = True
toil_args.defaultPreemptable = True
if self.zone is not None:
job_dir = os.path.join(work_dir, 'jobStore') # Directory where the AWS directory file is
if os.path.exists(job_dir):
for i in os.listdir(job_dir):
if os.path.isfile(os.path.join(job_dir, i)) and self.provisioner in i:
job_store = i
toil_args.restart = True
break
if toil_args.restart is not True:
job_store = self.provisioner + ':' + self.zone + ':' + ''.join(
random.choice(string.ascii_lowercase) for _ in range(7))
try:
os.makedirs(job_dir)
except OSError:
pass
tools.fileOps.touch(os.path.join(job_dir, job_store))
else:
job_store = os.path.join(work_dir, 'jobStore')
tools.fileOps.ensure_file_dir(job_store)
# this logic tries to determine if we should try and restart an existing jobStore
if os.path.exists(job_store):
try:
root_job = next(open(os.path.join(job_store, 'rootJobStoreID'))).rstrip()
if not os.path.exists(os.path.join(job_store, 'tmp', root_job)):
shutil.rmtree(job_store)
else:
toil_args.restart = True
except OSError:
toil_args.restart = True
if tools.misc.running_in_container():
# Caching doesn't work in containers, because the
# container filesystems are transient overlays that don't
# support hardlinking.
toil_args.disableCaching = True
if toil_args.batchSystem == 'parasol' and toil_args.disableCaching is False:
raise RuntimeError('Running parasol without disabled caching is a very bad idea.')
if toil_args.batchSystem == 'parasol' and toil_args.workDir is None:
raise RuntimeError('Running parasol without setting a shared work directory will not work. Please specify '
'--workDir.')
if toil_args.workDir is not None:
tools.fileOps.ensure_dir(toil_args.workDir)
toil_args.jobStore = job_store
self.job_store = job_store
return toil_args
def get_toil_defaults(self):
"""
Extracts the default toil options as a dictionary, setting jobStore to None
:return: dict
"""
parser = Job.Runner.getDefaultArgumentParser()
namespace = parser.parse_args(['']) # empty jobStore attribute
namespace.jobStore = None # jobStore attribute will be updated per-batch
namespace.logLevel = self.logLevel
return namespace
@ToilTask.event_handler(luigi.Event.SUCCESS)
def success(task):
"""
An event to record the total CPU time of a toil job.
"""
pipeline_args = task.get_pipeline_args()
stats_db = pipeline_args.stats_db
if task.zone is not None:
cmd = ['toil', 'stats', '--raw', task.job_store]
try:
os.remove(os.path.abspath(task.job_store))
except OSError:
pass
else:
cmd = ['toil', 'stats', '--raw', os.path.abspath(task.job_store)]
raw = tools.procOps.call_proc(cmd)
parsed = raw[raw.index('{'):raw.rfind('}') + 1]
stats = json.loads(parsed)
with tools.sqlite.ExclusiveSqlConnection(stats_db) as engine:
c = engine.cursor()
c.execute('create table if not exists toil_stats '
'(TaskId string unique, TotalTime real, AverageTime real)')
c.execute('insert or replace into toil_stats values (?, ?, ?)', [task.task_id,
stats['jobs']['total_clock'],
stats['jobs']['average_clock']])
engine.commit()
class RebuildableTask(PipelineTask):
def __init__(self, *args, **kwargs):
"""Allows us to force a task to be re-run. https://github.com/spotify/luigi/issues/595"""
super(PipelineTask, self).__init__(*args, **kwargs)
# To force execution, we just remove all outputs before `complete()` is called
if self.rebuild_consensus is True:
outputs = luigi.task.flatten(self.output())
for out in outputs:
if out.exists():
out.remove()
class TrackTask(RebuildableTask):
"""Provides shared values for all of the track tasks"""
genome = luigi.Parameter()
track_path = luigi.Parameter()
trackdb_path = luigi.Parameter()
def requires(self):
yield self.clone(Consensus)
yield self.clone(EvaluateTransMap)
yield self.clone(EvaluateTranscripts)
yield self.clone(Hgm)
yield self.clone(ReferenceFiles)
yield self.clone(EvaluateTransMap)
yield self.clone(TransMap)
def output(self):
return luigi.LocalTarget(self.track_path), luigi.LocalTarget(self.trackdb_path)
###
# pipeline tasks
###
class RunCat(PipelineWrapperTask):
"""
Task that executes the entire pipeline.
"""
def validate(self, pipeline_args):
"""General input validation"""
if not os.path.exists(pipeline_args.hal):
raise InputMissingException('HAL file not found at {}.'.format(pipeline_args.hal))
for d in [pipeline_args.out_dir, pipeline_args.work_dir]:
if not os.path.exists(d):
if not tools.fileOps.dir_is_writeable(os.path.dirname(d)):
raise UserException('Cannot create directory {}.'.format(d))
else:
if not tools.fileOps.dir_is_writeable(d):
raise UserException('Directory {} is not writeable.'.format(d))
if not os.path.exists(pipeline_args.annotation):
raise InputMissingException('Annotation file {} not found.'.format(pipeline_args.annotation))
# TODO: validate augustus species, tm/tmr/cgp/param files.
if pipeline_args.ref_genome not in pipeline_args.hal_genomes:
raise InvalidInputException('Reference genome {} not present in HAL.'.format(pipeline_args.ref_genome))
missing_genomes = {g for g in pipeline_args.target_genomes if g not in pipeline_args.hal_genomes}
if len(missing_genomes) > 0:
missing_genomes = ','.join(missing_genomes)
raise InvalidInputException('Target genomes {} not present in HAL.'.format(missing_genomes))
if pipeline_args.ref_genome in pipeline_args.target_genomes:
raise InvalidInputException('A target genome cannot be the reference genome.')
def requires(self):
self.load_docker()
logger.setLevel(self.logLevel)
pipeline_args = self.get_pipeline_args()
self.validate(pipeline_args)
yield self.clone(PrepareFiles)
yield self.clone(BuildDb)
yield self.clone(Chaining)
yield self.clone(TransMap)
yield self.clone(EvaluateTransMap)
if self.augustus is True:
yield self.clone(Augustus)
if self.augustus_cgp is True:
yield self.clone(AugustusCgp)
yield self.clone(FindDenovoParents, mode='augCGP')
if self.augustus_pb is True:
yield self.clone(AugustusPb)
yield self.clone(FindDenovoParents, mode='augPB')
yield self.clone(IsoSeqTranscripts)
yield self.clone(Hgm)
yield self.clone(AlignTranscripts)
yield self.clone(EvaluateTranscripts)
yield self.clone(Consensus)
yield self.clone(Plots)
if self.assembly_hub is True:
yield self.clone(AssemblyHub)
yield self.clone(ReportStats)
class PrepareFiles(PipelineWrapperTask):
"""
Wrapper for file preparation tasks GenomeFiles and ReferenceFiles
"""
def requires(self):
yield self.clone(GenomeFiles)
yield self.clone(ReferenceFiles)
yield self.clone(ExternalReferenceFiles)
class GenomeFiles(PipelineWrapperTask):
"""
WrapperTask for producing all genome files.
GenomeFiles -> GenomeFasta -> GenomeTwoBit -> GenomeFlatFasta -> GenomeFastaIndex
-> GenomeSizes
"""
@staticmethod
def get_args(pipeline_args, genome):
base_dir = os.path.join(pipeline_args.work_dir, 'genome_files')
args = tools.misc.HashableNamespace()
args.genome = genome
args.fasta = os.path.join(base_dir, genome + '.fa')
args.two_bit = os.path.join(base_dir, genome + '.2bit')
args.sizes = os.path.join(base_dir, genome + '.chrom.sizes')
args.flat_fasta = os.path.join(base_dir, genome + '.fa.flat')
return args
def validate(self):
for haltool in ['hal2fasta', 'halStats']:
if not tools.misc.is_exec(haltool):
raise ToolMissingException('{} from the HAL tools package not in global path'.format(haltool))
if not tools.misc.is_exec('faToTwoBit'):
raise ToolMissingException('faToTwoBit tool from the Kent tools package not in global path.')
if not tools.misc.is_exec('pyfasta'):
raise ToolMissingException('pyfasta wrapper not found in global path.')
def requires(self):
self.validate()
pipeline_args = self.get_pipeline_args()
for genome in list(pipeline_args.target_genomes) + [pipeline_args.ref_genome]:
args = self.get_args(pipeline_args, genome)
yield self.clone(GenomeFasta, **vars(args))
yield self.clone(GenomeTwoBit, **vars(args))
yield self.clone(GenomeSizes, **vars(args))
yield self.clone(GenomeFlatFasta, **vars(args))
class GenomeFasta(AbstractAtomicFileTask):
"""
Produce a fasta file from a hal file. Requires hal2fasta.
"""
genome = luigi.Parameter()
fasta = luigi.Parameter()
def output(self):
return luigi.LocalTarget(self.fasta)
def run(self):
logger.info('Extracting fasta for {}.'.format(self.genome))
cmd = ['hal2fasta', os.path.abspath(self.hal), self.genome]
self.run_cmd(cmd)
@requires(GenomeFasta)
class GenomeTwoBit(AbstractAtomicFileTask):
"""
Produce a 2bit file from a fasta file. Requires kent tool faToTwoBit.
Needs to be done BEFORE we flatten.
"""
two_bit = luigi.Parameter()
def output(self):
return luigi.LocalTarget(self.two_bit)
def run(self):
logger.info('Converting fasta for {} to 2bit.'.format(self.genome))
cmd = ['faToTwoBit', self.fasta, '/dev/stdout']
self.run_cmd(cmd)
class GenomeSizes(AbstractAtomicFileTask):
"""
Produces a genome chromosome sizes file. Requires halStats.
"""
genome = luigi.Parameter()
sizes = luigi.Parameter()
def output(self):
return luigi.LocalTarget(self.sizes)
def run(self):
logger.info('Extracting chromosome sizes for {}.'.format(self.genome))
cmd = ['halStats', '--chromSizes', self.genome, os.path.abspath(self.hal)]
self.run_cmd(cmd)
@requires(GenomeTwoBit)
class GenomeFlatFasta(AbstractAtomicFileTask):
"""
Flattens a genome fasta in-place using pyfasta. Requires the pyfasta package.
"""
flat_fasta = luigi.Parameter()
def output(self):
return luigi.LocalTarget(self.flat_fasta)
def run(self):
logger.info('Flattening fasta for {}.'.format(self.genome))
cmd = ['pyfasta', 'flatten', self.fasta]
tools.procOps.run_proc(cmd)
class ExternalReferenceFiles(PipelineWrapperTask):
"""
WrapperTask for running gff3ToGenePred and genePredToGtf <only> for non-reference annotation files
"""
@staticmethod
def get_args(pipeline_args, genome):
base_dir = os.path.join(pipeline_args.work_dir, 'reference')
args = tools.misc.HashableNamespace()
args.genome = genome
args.annotation_gff3 = pipeline_args.cfg['ANNOTATION'][genome]
args.annotation_gp = os.path.join(base_dir, genome + '.external_reference.gp')
args.annotation_gtf = os.path.join(base_dir, genome + '.external_reference.gtf')
args.annotation_attrs = os.path.join(base_dir, genome + '.external_reference.gp_attrs')
args.duplicates = os.path.join(base_dir, genome + '.external_reference.duplicates.txt')
return args
def validate(self):
for tool in ['gff3ToGenePred', 'genePredToBed']:
if not tools.misc.is_exec(tool):
raise ToolMissingException('{} from the Kent tools package not in global path'.format(tool))
def requires(self):
self.validate()
pipeline_args = self.get_pipeline_args()
for genome in pipeline_args.external_ref_genomes:
args = self.get_args(pipeline_args, genome)
yield self.clone(Gff3ToGenePred, **vars(args))
yield self.clone(TranscriptGtf, **vars(args))
yield self.clone(Gff3ToAttrs, **vars(args))
class ReferenceFiles(PipelineWrapperTask):
"""
WrapperTask for producing annotation files.
ReferenceFiles -> Gff3ToGenePred -> TranscriptBed -> TranscriptFasta -> FlatTranscriptFasta
V
FakePsl, TranscriptGtf
"""
@staticmethod
def get_args(pipeline_args):
base_dir = os.path.join(pipeline_args.work_dir, 'reference')
annotation = os.path.splitext(os.path.basename(pipeline_args.annotation))[0]
args = tools.misc.HashableNamespace()
args.annotation_gff3 = pipeline_args.annotation
args.annotation_gp = os.path.join(base_dir, annotation + '.gp')
args.annotation_attrs = os.path.join(base_dir, annotation + '.gp_attrs')
args.annotation_gtf = os.path.join(base_dir, annotation + '.gtf')
args.transcript_fasta = os.path.join(base_dir, annotation + '.fa')
args.transcript_flat_fasta = os.path.join(base_dir, annotation + '.fa.flat')
args.transcript_bed = os.path.join(base_dir, annotation + '.bed')
args.duplicates = os.path.join(base_dir, annotation + '.duplicates.txt')
args.ref_psl = os.path.join(base_dir, annotation + '.psl')
args.genome = pipeline_args.ref_genome
args.__dict__.update(**vars(GenomeFiles.get_args(pipeline_args, pipeline_args.ref_genome)))
return args
def validate(self):
for tool in ['gff3ToGenePred', 'genePredToBed', 'genePredToFakePsl']:
if not tools.misc.is_exec(tool):
raise ToolMissingException('{} from the Kent tools package not in global path'.format(tool))
def requires(self):
self.validate()
pipeline_args = self.get_pipeline_args()
args = self.get_args(pipeline_args)
yield self.clone(Gff3ToGenePred, **vars(args))
yield self.clone(Gff3ToAttrs, **vars(args))
yield self.clone(TranscriptBed, **vars(args))
yield self.clone(TranscriptFasta, **vars(args))
yield self.clone(TranscriptGtf, **vars(args))
yield self.clone(FlatTranscriptFasta, **vars(args))
yield self.clone(FakePsl, **vars(args))
class Gff3ToGenePred(PipelineTask):
"""
Generates a genePred from a gff3 file.
"""
genome = luigi.Parameter()
annotation_gff3 = luigi.Parameter()
annotation_gp = luigi.Parameter()
annotation_attrs = luigi.Parameter()
duplicates = luigi.Parameter()
def output(self):
return luigi.LocalTarget(self.annotation_gp), luigi.LocalTarget(self.annotation_attrs)
def validate(self):
c = collections.Counter()
annotation_gp, annotation_attrs = self.output()
for l in open(annotation_gp.path):
l = l.split()
c[l[0]] += 1
duplicates = {x for x, y in c.items() if y > 1}
if len(duplicates) > 0:
with open(self.duplicates, 'w') as outf:
for l in duplicates:
outf.write(l + '\n')
raise InvalidInputException('Found {:,} duplicate transcript IDs after parsing input GFF3. '
'Please check your input. One possible cause is the lack of a transcript-level '
'identifier on a gene record. Duplicate IDs have been written to: '
'{}'.format(len(duplicates), self.duplicates))
def run(self):
logger.info('Converting annotation gff3 to genePred.')
if self.genome == self.ref_genome:
cmd = tools.gff3.convert_gff3_cmd(self.annotation_attrs, self.annotation_gff3)
annotation_gp, annotation_attrs = self.output()
with annotation_gp.open('w') as outf:
tools.procOps.run_proc(cmd, stdout=outf)
else:
annotation_gp, annotation_attrs = self.output()
with tools.fileOps.TemporaryFilePath() as tmp_attrs, tools.fileOps.TemporaryFilePath() as tmp_gp:
cmd = tools.gff3.convert_gff3_cmd(tmp_attrs, self.annotation_gff3)
tools.procOps.run_proc(cmd, stdout=tmp_gp)
recs = tools.transcripts.get_gene_pred_dict(tmp_gp)
for rec in recs.values():
rec.name = f'exRef-{rec.name}'
rec.name2 = f'exRef-{rec.name2}'
with annotation_gp.open('w') as outf:
for rec in recs.values():
tools.fileOps.print_row(outf, rec.get_gene_pred())
with annotation_attrs.open('w') as outf:
tools.procOps.run_proc(['sed', 's/^/exRef-/'], stdin=tmp_attrs, stdout=outf)
self.validate()
@requires(Gff3ToGenePred)
class Gff3ToAttrs(PipelineTask):
"""
Converts the attrs file from -attrsOut in gff3ToGenePred into a SQLite table.
"""
table = tools.sqlInterface.Annotation.__tablename__
def output(self):
pipeline_args = self.get_pipeline_args()
database = pipeline_args.dbs[self.genome]
tools.fileOps.ensure_file_dir(database)
conn_str = 'sqlite:///{}'.format(database)
digest = tools.fileOps.hashfile(pipeline_args.cfg['ANNOTATION'][self.genome])
attrs_table = luigi.contrib.sqla.SQLAlchemyTarget(connection_string=conn_str,
target_table=self.table,
update_id='_'.join([self.table, str(digest)]))
return attrs_table
def run(self):
logger.info('Extracting gff3 attributes to sqlite database.')
pipeline_args = self.get_pipeline_args()
df = tools.gff3.parse_gff3(self.annotation_attrs, self.annotation_gp, self.genome != self.ref_genome)
if 'protein_coding' not in set(df.GeneBiotype) or 'protein_coding' not in set(df.TranscriptBiotype):
logger.critical('No protein_coding annotations found!')
# validate number parsed
tot_genes = len(open(self.annotation_gp).readlines())
if tot_genes != len(df):
raise InvalidInputException('The number of genes parsed from the attrs file is not the same number as '
'in the genePred. This is a parser failure. Contact Ian and make him fix it.')
database = pipeline_args.dbs[self.genome]
with tools.sqlite.ExclusiveSqlConnection(database) as engine:
df.to_sql(self.table, engine, if_exists='replace')
self.output().touch()
@requires(Gff3ToGenePred)
class TranscriptBed(AbstractAtomicFileTask):
"""
Produces a BED record from the input genePred annotation. Makes use of Kent tool genePredToBed
"""
transcript_bed = luigi.Parameter()
annotation_gp = luigi.Parameter()
def output(self):
return luigi.LocalTarget(self.transcript_bed)
def run(self):
logger.info('Converting annotation genePred to BED.')
cmd = ['genePredToBed', self.annotation_gp, '/dev/stdout']
self.run_cmd(cmd)
@multiple_requires(GenomeFlatFasta, TranscriptBed)
class TranscriptFasta(AbstractAtomicFileTask):
"""
Produces a fasta for each transcript.
"""
transcript_fasta = luigi.Parameter()
def output(self):
return luigi.LocalTarget(self.transcript_fasta)
def run(self):
logger.info('Extracting reference annotation fasta.')
seq_dict = tools.bio.get_sequence_dict(self.fasta, upper=False)
seqs = {tx.name: tx.get_mrna(seq_dict) for tx in tools.transcripts.transcript_iterator(self.transcript_bed)}
with self.output().open('w') as outf:
for name, seq in seqs.items():
tools.bio.write_fasta(outf, name, seq)
@requires(Gff3ToGenePred)
class TranscriptGtf(AbstractAtomicFileTask):
"""
Produces a GTF out of the genePred for the reference
"""
annotation_gtf = luigi.Parameter()
annotation_gp = luigi.Parameter()
def output(self):
return luigi.LocalTarget(self.annotation_gtf)