File: filter_similar_seqs_expr_and_strand_aware.pl

package info (click to toggle)
trinityrnaseq 2.11.0%2Bdfsg-6
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 417,528 kB
  • sloc: perl: 48,420; cpp: 17,749; java: 12,695; python: 3,124; sh: 1,030; ansic: 983; makefile: 688; xml: 62
file content (303 lines) | stat: -rwxr-xr-x 7,988 bytes parent folder | download | duplicates (2)
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
#!/usr/bin/env perl

use strict;
use warnings;
use Carp;
use Getopt::Long qw(:config posix_default no_ignore_case bundling pass_through);
use Data::Dumper;
use lib ("/usr/lib/trinityrnaseq/PerlLib");
use Fasta_reader;

my $help_flag;


my $MIN_PCT_MAX_EXPR = 5;

my $CPU = 2;

my $REF_MIN_PCT_LEN = 90;

my $usage = <<__EOUSAGE__;


Algorithm is as follows:

    Run CDHIT to cluster according to sequence identity and length

    A reference sequence is selected as having the highest expression level and within ${REF_MIN_PCT_LEN} % length  of the longest sequence in that cluster.

    Any sequences having less than $MIN_PCT_MAX_EXPR of the selected reference sequence are filtered out.

    Use the --filter_antisense_only flag to only have filtering applied to sequences with opposite transcribed orientation from the selected reference sequence in each cluster.

    Output is a new fasta file containing only those entries that pass the filtering criteria.

    
################################################################
#
#  --transcripts_fasta <string>        target transcript fasta file
#
#  --expr_matrix <string>              transcript expression matrix (TPM matrix)
#
#
# Optional:
#
#  --min_pct_max_expr <int>            default: $MIN_PCT_MAX_EXPR
#
#  --filter_antisense_only             default: off
#
#  --CPU <int>                         number of threads
#
#  --ref_min_pct_len <int>             minimum percent of max length to define candidate reference sequences
#                                      default: $REF_MIN_PCT_LEN
#
###########################################################################


__EOUSAGE__

    ;


# cd-hit-est  -i axo.indropB.iworm.fa -o axo.indropB.iworm.fa.cdhit98.fa -c 0.98 -aS 0.95 -T 20

my $transcripts_fasta_file;
my $expr_matrix_file;
my $filter_antisense_only;

my $DEBUG = 0;


&GetOptions ( 'h' => \$help_flag,
              'transcripts_fasta=s' => \$transcripts_fasta_file,
              'expr_matrix=s' => \$expr_matrix_file,
              'filter_antisense_only' => \$filter_antisense_only,

              'CPU=i' => \$CPU,
              'min_pct_max_expr=i' => \$MIN_PCT_MAX_EXPR,
              'REF_MIN_PCT_LEN=i' => \$REF_MIN_PCT_LEN,
    

              'd' => \$DEBUG,
    );


if ($help_flag) {
    die $usage;
}


unless($transcripts_fasta_file && $expr_matrix_file) {
    die $usage;
}


main: {

    my $cdhit_prefix = "$transcripts_fasta_file.cdhit";
    
    my $cmd = "cd-hit-est -i $transcripts_fasta_file -o $cdhit_prefix -d 0 -c 0.98 -aS 0.95 -T $CPU";
    unless (-e "$cdhit_prefix.ok") {
        &process_cmd($cmd);

        &process_cmd("touch $cdhit_prefix.ok");
    }

    my %top_expr_val = &get_top_expr_val($expr_matrix_file);
    
    my %accs_retain = &filter_noisy_transcripts("$cdhit_prefix.clstr", \%top_expr_val, $REF_MIN_PCT_LEN, 
                                                $MIN_PCT_MAX_EXPR, $filter_antisense_only);

    # output refined fasta file:
    

    my $fasta_reader = new Fasta_reader($transcripts_fasta_file);

    my $count_kept = 0;
    my $count_excluded = 0;
    
    while (my $seq_obj = $fasta_reader->next()) {
        my $acc = $seq_obj->get_accession();

        if ($accs_retain{$acc}) {
            print $seq_obj->get_FASTA_format();
            delete $accs_retain{$acc};
            $count_kept++;
        }
        else {
            $count_excluded++;
        }
    }
    
    if (%accs_retain) {
        die "Error, didnt retrieve sequences for accession: " . Dumper(%accs_retain);
    }
    else {
        print STDERR "Done. Excluded $count_excluded  = " . sprintf("%.2f", $count_excluded / ($count_kept + $count_excluded) * 100) . "% of sequences\n";
    }
    
    exit(0);
}

####
sub get_top_expr_val {
    my ($expr_matrix_file) = @_;

    my %top_expr_val;
    
    open(my $fh, $expr_matrix_file) or die "Error, cannot open file: $expr_matrix_file";
    my $header = <$fh>;
    while (<$fh>) {
        chomp;
        my @x = split(/\t/);
        my $trans_acc = shift @x;
        @x = sort {$a<=>$b} @x;
        my $max_expr = pop @x;
        $top_expr_val{$trans_acc} = $max_expr;

    }

    close $fh;

    return(%top_expr_val);
}


####
sub process_cmd {
    my ($cmd) = @_;

    print STDERR "CMD: $cmd\n";
    my $ret = system($cmd);
    if ($ret) {
        die "Error, cmd: $cmd died with ret";
    }

    return;
}

####
sub filter_noisy_transcripts {
    my ($cdhit_clstr_file, $top_expr_vals_href, $ref_min_pct_len, $min_pct_max_expr, $filter_antisense_only) = @_;


    
    
    my %accs_want;

    my $select_clusters_want_sref = sub {
        
        my @structs = @_;
        

    
        @structs = reverse sort {$a->{len}<=>$b->{len}} @structs;

        my $longest_len = $structs[0]->{len};

        my @ref_structs;
        foreach my $struct (@structs) {
            if ($struct->{len} / $longest_len * 100 >= $ref_min_pct_len) {
                push (@ref_structs, $struct);
            }
        }

        # take the highest expr entry as official ref seq
        @ref_structs = reverse sort {$a->{expr}<=>$b->{expr}} @ref_structs;
        
        
        my $ref_seq_struct = shift @ref_structs;
        $accs_want{ $ref_seq_struct->{acc} } = 1;
        
        my $audit_text = "* ref selected as: $ref_seq_struct->{acc} "
            . " len: $ref_seq_struct->{len}"
            . " expr: $ref_seq_struct->{expr}"
            . " [$ref_seq_struct->{orient}]\n";
        

        print STDERR "* selected ref seq as: " . Dumper($ref_seq_struct) if $DEBUG;
        
    
        my $min_allowed_expr = $ref_seq_struct->{expr} * $min_pct_max_expr / 100;

        my $excluded_flag = 0;
        
        foreach my $struct (@structs) {
            
            if ($struct eq $ref_seq_struct) { next; }
        
            my $retain_flag = 0;
    
            if ($filter_antisense_only && $struct->{orient} eq $ref_seq_struct->{orient}) {
                # all good, not antisense
                $retain_flag = 1;
            }

            elsif ($struct->{expr} >= $min_allowed_expr) {
                # meets expression criteria
                $retain_flag = 1;
            }
            
            if ($retain_flag) {
                $accs_want{ $struct->{acc} } = 1;
                $audit_text .= "-keeping: $struct->{acc} len: $struct->{len} expr: $struct->{expr} [$struct->{orient}]\n";
            }
            else {
                print STDERR "-excluding " . Dumper($struct) if $DEBUG;
                $audit_text .= "-EXCLUDING: $struct->{acc} len: $struct->{len} expr: $struct->{expr} [$struct->{orient}]\n";
                
                $excluded_flag = 1;
            }
        }

        if ($excluded_flag) {
            print STDERR "$audit_text\n";
        }
        
    };

    
    my @cluster;
    open(my $fh, $cdhit_clstr_file) or die $!;
    while (<$fh>) {
        chomp;
        if (/^>/) {
            if (@cluster) {
                &$select_clusters_want_sref(@cluster);
            }
            @cluster = ();
        }
        else {
            my ($idx, $len, $trans_acc, $selected_star, $orient_pct) = split(/\s+/);
            $len =~ s/nt,//;
            $trans_acc =~ s/>//;
            $trans_acc =~ s/\.\.\.$//;

            my $expr = $top_expr_vals_href->{$trans_acc};
            unless (defined $expr) {
                die "Error, no expr value for $trans_acc";
            }
            
            my ($orient, $pct) = ('+', '.');
            if ($selected_star eq 'at') {
                ($orient, $pct) = split(/\//, $orient_pct);
            }
            
            my $struct = { acc => $trans_acc,
                           len => $len,
                           orient => $orient,
                           expr => $expr,
            };
            push (@cluster, $struct);
            
        }

    }
    close $fh;
    
    if (@cluster) {
        &$select_clusters_want_sref(@cluster);
    }

    return(%accs_want);
}