| 1 | #!/usr/bin/env perl | ||
| 2 | # PODNAME: prune-tree.pl | ||
| 3 | # ABSTRACT: Prune tips from TREE files based on id lists | ||
| 4 | |||
| 5 | use Modern::Perl '2011'; | ||
| 6 | use autodie; | ||
| 7 | |||
| 8 | use File::Basename; | ||
| 9 | use Getopt::Euclid qw(:vars); | ||
| 10 | use Smart::Comments; | ||
| 11 | use Try::Tiny; | ||
| 12 | |||
| 13 | use Bio::MUST::Core; | ||
| 14 | use Bio::MUST::Core::Utils qw(change_suffix insert_suffix secure_outfile); | ||
| 15 | use aliased 'Bio::MUST::Core::IdList'; | ||
| 16 | use aliased 'Bio::MUST::Core::Tree'; | ||
| 17 | |||
| 18 | |||
| 19 | my $method = $ARGV_from_must ? 'load_lis' : 'load'; | ||
| 20 | |||
| 21 | IDL: | ||
| 22 | for my $infile (@ARGV_infiles) { | ||
| 23 | |||
| 24 | ### Processing: $infile | ||
| 25 | my $list = IdList->$method($infile); | ||
| 26 | $infile =~ s/$_//xms for @ARGV_in_strip; | ||
| 27 | |||
| 28 | # load Tree (either reference tree or tree associated to idl) | ||
| 29 | my $trefile = $ARGV_ref_tree // change_suffix($infile, '.tre'); | ||
| 30 | |||
| 31 | my $tree; | ||
| 32 | try { $tree = Tree->load($trefile) } | ||
| 33 | catch { warn "Warning: cannot load '$trefile' as a Tree; skipping!\n" }; | ||
| 34 | next IDL unless $tree; | ||
| 35 | ### Pruning tips in: $trefile | ||
| 36 | |||
| 37 | # optionally negate list | ||
| 38 | $list = $list->negative_list($tree) if $ARGV_negate_list; | ||
| 39 | |||
| 40 | # prune tree | ||
| 41 | $tree->tree->keep_tips( [ map { $_->foreign_id } $list->all_seq_ids ] ); | ||
| 42 | |||
| 43 | # create suffix named after filename | ||
| 44 | my $outfile = $trefile; | ||
| 45 | if ($ARGV_ref_tree) { | ||
| 46 | my ($filename) = fileparse($infile, qr{\.[^.]*}xms); | ||
| 47 | $outfile = insert_suffix($outfile, "-$filename"); | ||
| 48 | } | ||
| 49 | $outfile = secure_outfile($outfile, $ARGV_out_suffix); | ||
| 50 | ### Output tree in: $outfile | ||
| 51 | $tree->store($outfile); | ||
| 52 | } | ||
| 53 | |||
| 54 | # TODO: generalize the --ref-tree approach to other programs as this allows | ||
| 55 | # a dual use (multiple infiles with or without explicit derived file) | ||
| 56 | |||
| 57 | __END__ |