]> git.donarmstrong.com Git - biopieces.git/blob - code_perl/Maasha/BioRun.pm
migrated tile_seq
[biopieces.git] / code_perl / Maasha / BioRun.pm
1 package Maasha::BioRun;
2
3
4 # Copyright (C) 2007-2009 Martin A. Hansen.
5
6 # This program is free software; you can redistribute it and/or
7 # modify it under the terms of the GNU General Public License
8 # as published by the Free Software Foundation; either version 2
9 # of the License, or (at your option) any later version.
10
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 # GNU General Public License for more details.
15
16 # You should have received a copy of the GNU General Public License
17 # along with this program; if not, write to the Free Software
18 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19
20 # http://www.gnu.org/copyleft/gpl.html
21
22
23 # >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> DESCRIPTION <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
24
25
26 # Routines that contains Biopieces which are run.
27
28
29 # >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>><<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
30
31
32 use strict;
33 use Data::Dumper;
34 use Getopt::Long qw( :config bundling );
35 use Time::HiRes qw( gettimeofday );
36 use Storable qw( dclone );
37 use Maasha::Biopieces;
38 use Maasha::Config;
39 use Maasha::Common;
40 use Maasha::Filesys;
41 use Maasha::Fasta;
42 use Maasha::Align;
43 use Maasha::Matrix;
44 use Maasha::Match;
45 use Maasha::EMBL;
46 use Maasha::Stockholm;
47 use Maasha::Seq;
48 use Maasha::Patscan;
49 use Maasha::Plot;
50 use Maasha::Calc;
51 use Maasha::UCSC;
52 use Maasha::UCSC::BED;
53 use Maasha::UCSC::Wiggle;
54 use Maasha::NCBI;
55 use Maasha::GFF;
56 use Maasha::TwoBit;
57 use Maasha::Solid;
58 use Maasha::Solexa;
59 use Maasha::SQL;
60 use Maasha::Gwiki;
61
62 use vars qw( @ISA @EXPORT_OK );
63
64 require Exporter;
65
66 @ISA = qw( Exporter );
67
68 use constant {
69     SEQ_NAME => 0,
70     SEQ      => 1,
71 };
72
73
74 # >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> GLOBALS <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
75
76
77 my ( $script, $BP_TMP );
78
79 $script = Maasha::Common::get_scriptname();
80 $BP_TMP = Maasha::Common::get_tmpdir();
81
82
83 # >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> RUN SCRIPT <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
84
85
86 run_script( $script );
87
88
89 # >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> SUBROUTINES <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
90
91
92 sub run_script
93 {
94     # Martin A. Hansen, August 2007.
95
96     # Run a specific script.
97
98     my ( $script,   # script name
99        ) = @_;
100
101     # Returns nothing.
102
103     my ( $t0, $t1, $options, $in, $out );
104
105     Maasha::Biopieces::log_biopiece();
106
107     $t0 = gettimeofday();
108
109     $options = get_options( $script );
110
111     $options->{ "SCRIPT" } = $script;
112
113     $script = "print_usage" if ( -t STDIN and keys %{ $options } <= 1 or $options->{ 'help' } );
114
115     $in  = Maasha::Biopieces::read_stream( $options->{ "stream_in" } );
116     $out = Maasha::Biopieces::write_stream( $options->{ "stream_out" } );
117
118     if    ( $script eq "print_usage" )              { script_print_usage(               $in, $out, $options ) }
119     elsif ( $script eq "read_psl" )                 { script_read_psl(                  $in, $out, $options ) }
120     elsif ( $script eq "read_bed" )                 { script_read_bed(                  $in, $out, $options ) }
121     elsif ( $script eq "read_fixedstep" )           { script_read_fixedstep(            $in, $out, $options ) }
122     elsif ( $script eq "read_blast_tab" )           { script_read_blast_tab(            $in, $out, $options ) }
123     elsif ( $script eq "read_embl" )                { script_read_embl(                 $in, $out, $options ) }
124     elsif ( $script eq "read_stockholm" )           { script_read_stockholm(            $in, $out, $options ) }
125     elsif ( $script eq "read_phastcons" )           { script_read_phastcons(            $in, $out, $options ) }
126     elsif ( $script eq "read_soft" )                { script_read_soft(                 $in, $out, $options ) }
127     elsif ( $script eq "read_gff" )                 { script_read_gff(                  $in, $out, $options ) }
128     elsif ( $script eq "read_2bit" )                { script_read_2bit(                 $in, $out, $options ) }
129     elsif ( $script eq "read_solexa" )              { script_read_solexa(               $in, $out, $options ) }
130     elsif ( $script eq "read_solid" )               { script_read_solid(                $in, $out, $options ) }
131     elsif ( $script eq "read_mysql" )               { script_read_mysql(                $in, $out, $options ) }
132     elsif ( $script eq "read_ucsc_config" )         { script_read_ucsc_config(          $in, $out, $options ) }
133     elsif ( $script eq "uppercase_seq" )            { script_uppercase_seq(             $in, $out, $options ) }
134     elsif ( $script eq "complexity_seq" )           { script_complexity_seq(            $in, $out, $options ) }
135     elsif ( $script eq "remove_indels" )            { script_remove_indels(             $in, $out, $options ) }
136     elsif ( $script eq "get_genome_align" )         { script_get_genome_align(          $in, $out, $options ) }
137     elsif ( $script eq "get_genome_phastcons" )     { script_get_genome_phastcons(      $in, $out, $options ) }
138     elsif ( $script eq "soap_seq" )                 { script_soap_seq(                  $in, $out, $options ) }
139     elsif ( $script eq "write_bed" )                { script_write_bed(                 $in, $out, $options ) }
140     elsif ( $script eq "write_psl" )                { script_write_psl(                 $in, $out, $options ) }
141     elsif ( $script eq "write_fixedstep" )          { script_write_fixedstep(           $in, $out, $options ) }
142     elsif ( $script eq "write_2bit" )               { script_write_2bit(                $in, $out, $options ) }
143     elsif ( $script eq "write_solid" )              { script_write_solid(               $in, $out, $options ) }
144     elsif ( $script eq "write_ucsc_config" )        { script_write_ucsc_config(         $in, $out, $options ) }
145     elsif ( $script eq "remove_keys" )              { script_remove_keys(               $in, $out, $options ) }
146     elsif ( $script eq "remove_adaptor" )           { script_remove_adaptor(            $in, $out, $options ) }
147     elsif ( $script eq "remove_mysql_tables" )      { script_remove_mysql_tables(       $in, $out, $options ) }
148     elsif ( $script eq "remove_ucsc_tracks" )       { script_remove_ucsc_tracks(        $in, $out, $options ) }
149     elsif ( $script eq "rename_keys" )              { script_rename_keys(               $in, $out, $options ) }
150     elsif ( $script eq "uniq_vals" )                { script_uniq_vals(                 $in, $out, $options ) }
151     elsif ( $script eq "plot_histogram" )           { script_plot_histogram(            $in, $out, $options ) }
152     elsif ( $script eq "plot_lendist" )             { script_plot_lendist(              $in, $out, $options ) }
153     elsif ( $script eq "plot_chrdist" )             { script_plot_chrdist(              $in, $out, $options ) }
154     elsif ( $script eq "plot_karyogram" )           { script_plot_karyogram(            $in, $out, $options ) }
155     elsif ( $script eq "plot_matches" )             { script_plot_matches(              $in, $out, $options ) }
156     elsif ( $script eq "plot_seqlogo" )             { script_plot_seqlogo(              $in, $out, $options ) }
157     elsif ( $script eq "plot_phastcons_profiles" )  { script_plot_phastcons_profiles(   $in, $out, $options ) }
158     elsif ( $script eq "upload_to_ucsc" )           { script_upload_to_ucsc(            $in, $out, $options ) }
159
160     close $in if defined $in;
161     close $out;
162
163     $t1 = gettimeofday();
164
165     print STDERR "Program: $script" . ( " " x ( 25 - length( $script ) ) ) . sprintf( "Run time: %.4f\n", ( $t1 - $t0 ) ) if $options->{ 'verbose' };
166 }
167
168
169 sub get_options
170 {
171     # Martin A. Hansen, February 2008.
172
173     # Gets options from commandline and checks these vigerously.
174
175     my ( $script,     # name of script
176        ) = @_;
177
178     # Returns hash
179
180     my ( %options, @options, $opt, @genomes, $real );
181
182     if ( $script eq "print_usage" )
183     {
184         @options = qw(
185             data_in|i=s
186         );
187     }
188     elsif ( $script eq "read_psl" )
189     {
190         @options = qw(
191             data_in|i=s
192             num|n=s
193         );
194     }
195     elsif ( $script eq "read_bed" )
196     {
197         @options = qw(
198             data_in|i=s
199             cols|c=s
200             num|n=s
201             check|C
202         );
203     }
204     elsif ( $script eq "read_fixedstep" )
205     {
206         @options = qw(
207             data_in|i=s
208             num|n=s
209         );
210     }
211     elsif ( $script eq "read_blast_tab" )
212     {
213         @options = qw(
214             data_in|i=s
215             num|n=s
216         );
217     }
218     elsif ( $script eq "read_embl" )
219     {
220         @options = qw(
221             data_in|i=s
222             num|n=s
223             keys|k=s
224             feats|f=s
225             quals|q=s
226         );
227     }
228     elsif ( $script eq "read_stockholm" )
229     {
230         @options = qw(
231             data_in|i=s
232             num|n=s
233         );
234     }
235     elsif ( $script eq "read_phastcons" )
236     {
237         @options = qw(
238             data_in|i=s
239             num|n=s
240             min|m=s
241             dist|d=s
242             threshold|t=f
243             gap|g=s
244         );
245     }
246     elsif ( $script eq "read_soft" )
247     {
248         @options = qw(
249             data_in|i=s
250             samples|s=s
251             num|n=s
252         );
253     }
254     elsif ( $script eq "read_gff" )
255     {
256         @options = qw(
257             data_in|i=s
258             num|n=s
259         );
260     }
261     elsif ( $script eq "read_2bit" )
262     {
263         @options = qw(
264             data_in|i=s
265             num|n=s
266             no_mask|N
267         );
268     }
269     elsif ( $script eq "read_solexa" )
270     {
271         @options = qw(
272             data_in|i=s
273             num|n=s
274             format|f=s
275             quality|q=s
276         );
277     }
278     elsif ( $script eq "read_solid" )
279     {
280         @options = qw(
281             data_in|i=s
282             num|n=s
283             quality|q=s
284         );
285     }
286     elsif ( $script eq "read_mysql" )
287     {
288         @options = qw(
289             database|d=s
290             query|q=s
291             user|u=s
292             password|p=s
293         );
294     }
295     elsif ( $script eq "read_ucsc_config" )
296     {
297         @options = qw(
298             data_in|i=s
299             num|n=s
300         );
301     }
302     elsif ( $script eq "get_genome_align" )
303     {
304         @options = qw(
305             genome|g=s
306             chr|c=s
307             beg|b=s
308             end|e=s
309             len|l=s
310             strand|s=s
311         );
312     }
313     elsif ( $script eq "get_genome_phastcons" )
314     {
315         @options = qw(
316             genome|g=s
317             chr|c=s
318             beg|b=s
319             end|e=s
320             len|l=s
321             flank|f=s
322         );
323     }
324     elsif ( $script eq "soap_seq" )
325     {
326         @options = qw(
327             in_file|i=s
328             genome|g=s
329             seed_size|s=s
330             mismatches|m=s
331             gap_size|G=s
332             cpus|c=s
333         );
334     }
335     elsif ( $script eq "write_bed" )
336     {
337         @options = qw(
338             cols|c=s
339             check|C
340             no_stream|x
341             data_out|o=s
342             compress|Z
343         );
344     }
345     elsif ( $script eq "write_psl" )
346     {
347         @options = qw(
348             no_stream|x
349             data_out|o=s
350             compress|Z
351         );
352     }
353     elsif ( $script eq "write_fixedstep" )
354     {
355         @options = qw(
356             no_stream|x
357             data_out|o=s
358             compress|Z
359         );
360     }
361     elsif ( $script eq "write_2bit" )
362     {
363         @options = qw(
364             no_stream|x
365             data_out|o=s
366             no_mask|N
367         );
368     }
369     elsif ( $script eq "write_solid" )
370     {
371         @options = qw(
372             wrap|w=s
373             no_stream|x
374             data_out|o=s
375             compress|Z
376         );
377     }
378     elsif ( $script eq "write_ucsc_config" )
379     {
380         @options = qw(
381             no_stream|x
382             data_out|o=s
383         );
384     }
385     elsif ( $script eq "plot_seqlogo" )
386     {
387         @options = qw(
388             no_stream|x
389             data_out|o=s
390         );
391     }
392     elsif ( $script eq "plot_phastcons_profiles" )
393     {
394         @options = qw(
395             no_stream|x
396             data_out|o=s
397             genome|g=s
398             mean|m
399             median|M
400             flank|f=s
401             terminal|t=s
402             title|T=s
403             xlabel|X=s
404             ylabel|Y=s
405         );
406     }
407     elsif ( $script eq "remove_keys" )
408     {
409         @options = qw(
410             keys|k=s
411             save_keys|K=s
412         );
413     }
414     elsif ( $script eq "remove_adaptor" )
415     {
416         @options = qw(
417             adaptor|a=s
418             mismatches|m=s
419             remove|r=s
420             offset|o=s
421         );
422     }
423     elsif ( $script eq "remove_mysql_tables" )
424     {
425         @options = qw(
426             database|d=s
427             tables|t=s
428             keys|k=s
429             user|u=s
430             password|p=s
431             no_stream|x
432         );
433     }
434     elsif ( $script eq "remove_ucsc_tracks" )
435     {
436         @options = qw(
437             database|d=s
438             tracks|t=s
439             keys|k=s
440             config_file|c=s
441             user|u=s
442             password|p=s
443             no_stream|x
444         );
445     }
446     elsif ( $script eq "rename_keys" )
447     {
448         @options = qw(
449             keys|k=s
450         );
451     }
452     elsif ( $script eq "uniq_vals" )
453     {
454         @options = qw(
455             key|k=s
456             invert|i
457         );
458     }
459     elsif ( $script eq "plot_histogram" )
460     {
461         @options = qw(
462             no_stream|x
463             data_out|o=s
464             terminal|t=s
465             title|T=s
466             xlabel|X=s
467             ylabel|Y=s
468             key|k=s
469             sort|s=s
470         );
471     }
472     elsif ( $script eq "plot_lendist" )
473     {
474         @options = qw(
475             no_stream|x
476             data_out|o=s
477             terminal|t=s
478             title|T=s
479             xlabel|X=s
480             ylabel|Y=s
481             key|k=s
482         );
483     }
484     elsif ( $script eq "plot_chrdist" )
485     {
486         @options = qw(
487             no_stream|x
488             data_out|o=s
489             terminal|t=s
490             title|T=s
491             xlabel|X=s
492             ylabel|Y=s
493         );
494     }
495     elsif ( $script eq "plot_karyogram" )
496     {
497         @options = qw(
498             no_stream|x
499             data_out|o=s
500             genome|g=s
501             feat_color|f=s
502         );
503     }
504     elsif ( $script eq "plot_matches" )
505     {
506         @options = qw(
507             no_stream|x
508             data_out|o=s
509             terminal|t=s
510             title|T=s
511             xlabel|X=s
512             ylabel|Y=s
513             direction|d=s
514         );
515     }
516     elsif ( $script eq "upload_to_ucsc" )
517     {
518         @options = qw(
519             no_stream|x
520             database|d=s
521             table|t=s
522             short_label|s=s
523             long_label|l=s
524             group|g=s
525             priority|p=f
526             use_score|u
527             visibility|V=s
528             color|c=s
529             check|C
530         );
531     }
532
533     push @options, qw(
534         stream_in|I=s
535         stream_out|O=s
536         verbose|v
537         help|?
538     );
539
540 #    print STDERR Dumper( \@options );
541     
542     GetOptions(
543         \%options,
544         @options,
545     );
546
547 #    print STDERR Dumper( \%options );
548
549     if ( -t STDIN && scalar( keys %options ) == 0 or $options{ "help" } ) {
550         return wantarray ? %options : \%options;
551     }
552
553     $options{ "cols" }      = [ split ",", $options{ "cols" } ]      if defined $options{ "cols" };
554     $options{ "keys" }      = [ split ",", $options{ "keys" } ]      if defined $options{ "keys" };
555     $options{ "no_keys" }   = [ split ",", $options{ "no_keys" } ]   if defined $options{ "no_keys" };
556     $options{ "save_keys" } = [ split ",", $options{ "save_keys" } ] if defined $options{ "save_keys" };
557     $options{ "quals" }     = [ split ",", $options{ "quals" } ]     if defined $options{ "quals" };
558     $options{ "feats" }     = [ split ",", $options{ "feats" } ]     if defined $options{ "feats" };
559     $options{ "frames" }    = [ split ",", $options{ "frames" } ]    if defined $options{ "frames" };
560     $options{ "samples" }   = [ split ",", $options{ "samples" } ]   if defined $options{ "samples" };
561     $options{ "tables" }    = [ split ",", $options{ "tables" } ]    if defined $options{ "tables" };
562     $options{ "tracks" }    = [ split ",", $options{ "tracks" } ]    if defined $options{ "tracks" };
563     
564     # ---- check arguments ----
565
566     if ( $options{ 'data_in' } )
567     {
568         $options{ "files" } = Maasha::Biopieces::getopt_files( $options{ 'data_in' } );
569
570         Maasha::Common::error( qq(Argument to --data_in must be a valid file or fileglob expression) ) if scalar @{ $options{ "files" } } == 0;
571     }
572
573     map { Maasha::Common::error( qq(Argument to --cols must be a whole numbers - not "$_") ) if $_ !~ /^\d+$/ } @{ $options{ "cols" } } if $options{ "cols" };
574
575     # print STDERR Dumper( \%options );
576
577     $real = "beg|end|word_size|wrap|len|prefix_length|mismatches|offset|num|skip|cpus|window_size|step_size";
578
579     foreach $opt ( keys %options )
580     {
581         if ( $opt =~ /stream_in|pattern_in|exact_in/ and not -f $options{ $opt } )
582         {
583             Maasha::Common::error( qq(Argument to --$opt must be a valid file or fileglob expression - not "$options{ $opt }") );
584         }
585         elsif ( $opt =~ /$real/ and $options{ $opt } !~ /^\d+$/ )
586         {
587             Maasha::Common::error( qq(Argument to --$opt must be a whole number - not "$options{ $opt }") );
588         }
589         elsif ( $opt =~ /max_hits|max_hits|max_misses|dist|edit_dist|flank|gap|hamming_dist|priority/ and $options{ $opt } !~ /^-?\d+$/ )
590         {
591             Maasha::Common::error( qq(Argument to --$opt must be an integer - not "$options{ $opt }") );
592         }
593         elsif ( $opt =~ /identity|threshold/ and $options{ $opt } !~ /^-?(?:\d+(?:\.\d*)?|\.\d+)$/ )
594         {
595             Maasha::Common::error( qq(Argument to --$opt must be a decimal number - not "$options{ $opt }") );
596         }
597         elsif ( $opt =~ /e_val/ and $options{ $opt } !~ /^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$/ )
598         {
599             Maasha::Common::error( qq(Argument to --$opt must be a float - not "$options{ $opt }") );
600         }
601         elsif ( $opt =~ /strand/ and $options{ $opt } !~ /^(\+|-)$/ )
602         {
603             Maasha::Common::error( qq(Argument to --$opt must be "+" or "-" - not "$options{ $opt }") );
604         }
605         elsif ( $opt eq "genome" )
606         {
607             @genomes = Maasha::Common::ls_dirs( "$ENV{ 'BP_DATA' }/genomes" );
608             map { $_ =~ s/.*\/(.+)$/$1/ } @genomes;
609
610             if ( not grep { $_ =~ /^$options{ $opt }$/ } @genomes ) {
611                 Maasha::Common::error( qq(Genome $options{ $opt } not found in "$ENV{ 'BP_DATA' }/genomes/") );
612             }
613         }
614         elsif ( $opt eq "terminal" and not $options{ $opt } =~ /^(svg|post|dumb|x11)/ )
615         {
616             Maasha::Common::error( qq(Bad --$opt argument "$options{ $opt }") );
617         }
618         elsif ( $opt eq "table" and $options{ $opt } =~ /(-|\.)/ )
619         {
620             Maasha::Common::error( qq(Character '$1' is not allowed in table name: $options{ $opt }) );
621         }
622         elsif ( $opt eq "merge" and $options{ $opt } !~ /^(AandB|AorB|BorA|AnotB|BnotA)$/ )
623         {
624             Maasha::Common::error( qq(Argument to --$opt must be AandB, AorB, BorA, AnotB, or BnotA - not "$options{ $opt }") );
625         }
626         elsif ( $opt eq "format" and $script eq "read_solexa" and $options{ $opt } !~ /octal|decimal/ )
627         {
628             Maasha::Common::error( qq(Argument to --$opt must be octal or decimal - not "$options{ $opt }") );
629         }
630         elsif ( $opt eq "remove" and $script eq "remove_adaptor" and $options{ $opt } !~ /before|after|skip/ )
631         {
632             Maasha::Common::error( qq(Argument to --$opt must be before, after, or skip - not "$options{ $opt }") );
633         }
634     }
635
636     Maasha::Common::error( qq(no --database specified) )                if $script eq "remove_ucsc_tracks"  and not $options{ "database" };
637     Maasha::Common::error( qq(no --in_file or --genome specified) )     if $script eq "soap_seq" and not $options{ "genome" } and not $options{ "in_file" };
638     Maasha::Common::error( qq(both --in_file and --genome specified) )  if $script eq "soap_seq" and $options{ "genome" } and $options{ "in_file" };
639     Maasha::Common::error( qq(no --genome specified) )                  if $script =~ /get_genome_align|get_genome_phastcons|plot_phastcons_profiles|plot_karyogram/ and not $options{ "genome" };
640     Maasha::Common::error( qq(no --key specified) )                     if $script =~ /plot_lendist|plot_histogram/ and not $options{ "key" };
641
642     if ( $script eq "upload_to_ucsc" )
643     {
644         Maasha::Common::error( qq(no --database specified) ) if not $options{ "database" };
645         Maasha::Common::error( qq(no --table specified) )    if not $options{ "table" };
646     }
647
648     return wantarray ? %options : \%options;
649 }
650
651
652 # >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> SCRIPTS  <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
653
654
655 sub script_print_usage
656 {
657     # Martin A. Hansen, January 2008.
658
659     # Retrieves usage information from file and
660     # prints this nicely formatted.
661
662     my ( $in,        # handle to in stream
663          $out,       # handle to out stream
664          $options,   # options hash
665        ) = @_;
666
667     # Returns nothing.
668
669     my ( $file, $wiki, $lines );
670
671     if ( $options->{ 'data_in' } ) {
672         $file = $options->{ 'data_in' };
673     } else {
674         $file = join "", $ENV{ 'BP_DIR' }, "/bp_usage/", $options->{ 'SCRIPT' }, ".wiki";
675     }
676
677     $wiki = Maasha::Gwiki::gwiki_read( $file );
678
679     ( $wiki->[ 2 ], $wiki->[ 3 ], $wiki->[ 0 ], $wiki->[ 1 ] ) = ( $wiki->[ 0 ], $wiki->[ 1 ], $wiki->[ 2 ], $wiki->[ 3 ] );
680
681     if ( not $options->{ "help" } ) {
682         @{ $wiki } = grep { $_->[ 0 ]->{ 'SECTION' } =~ /Biopiece|summary|Usage|Options|Help/ } @{ $wiki };
683     }
684
685     $lines = Maasha::Gwiki::gwiki2ascii( $wiki );
686
687     print STDERR "$_\n" foreach @{ $lines };
688
689     exit;
690 }
691
692
693 sub script_read_psl
694 {
695     # Martin A. Hansen, August 2007.
696
697     # Read psl table from stream or file.
698
699     my ( $in,        # handle to in stream
700          $out,       # handle to out stream
701          $options,   # options hash
702        ) = @_;
703
704     # Returns nothing.
705
706     my ( $record, $file, $data_in, $num );
707
708     while ( $record = Maasha::Biopieces::get_record( $in ) ) {
709         Maasha::Biopieces::put_record( $record, $out );
710     }
711
712     $num = 1;
713
714     foreach $file ( @{ $options->{ "files" } } )
715     {
716         $data_in = Maasha::Common::read_open( $file );
717
718         while ( $record = Maasha::UCSC::psl_get_entry( $data_in ) ) 
719         {
720             Maasha::Biopieces::put_record( $record, $out );
721
722             goto NUM if $options->{ "num" } and $num == $options->{ "num" };
723
724             $num++;
725         }
726     }
727
728     NUM:
729 }
730
731
732 sub script_read_bed
733 {
734     # Martin A. Hansen, August 2007.
735
736     # Read bed table from stream or file.
737
738     my ( $in,        # handle to in stream
739          $out,       # handle to out stream
740          $options,   # options hash
741        ) = @_;
742
743     # Returns nothing.
744
745     my ( $cols, $file, $record, $bed_entry, $data_in, $num );
746
747     $cols = $options->{ 'cols' }->[ 0 ];
748
749     while ( $record = Maasha::Biopieces::get_record( $in ) ) {
750         Maasha::Biopieces::put_record( $record, $out );
751     }
752
753     $num = 1;
754
755     foreach $file ( @{ $options->{ "files" } } )
756     {
757         $data_in = Maasha::Common::read_open( $file );
758
759         while ( $bed_entry = Maasha::UCSC::BED::bed_entry_get( $data_in, $cols, $options->{ 'check' } ) )
760         {
761             $record = Maasha::UCSC::BED::bed2biopiece( $bed_entry );
762
763             Maasha::Biopieces::put_record( $record, $out );
764
765             goto NUM if $options->{ "num" } and $num == $options->{ "num" };
766
767             $num++;
768         }
769
770         close $data_in;
771     }
772
773     NUM:
774
775     close $data_in if $data_in;
776 }
777
778
779 sub script_read_fixedstep
780 {
781     # Martin A. Hansen, Juli 2008.
782
783     # Read fixedstep wiggle format from stream or file.
784
785     my ( $in,        # handle to in stream
786          $out,       # handle to out stream
787          $options,   # options hash
788        ) = @_;
789
790     # Returns nothing.
791
792     my ( $file, $record, $entry, $data_in, $num );
793
794     while ( $record = Maasha::Biopieces::get_record( $in ) ) {
795         Maasha::Biopieces::put_record( $record, $out );
796     }
797
798     $num = 1;
799
800     foreach $file ( @{ $options->{ "files" } } )
801     {
802         $data_in = Maasha::Common::read_open( $file );
803
804         while ( $entry = Maasha::UCSC::Wiggle::fixedstep_entry_get( $data_in ) )
805         {
806             $record = Maasha::UCSC::Wiggle::fixedstep2biopiece( $entry );
807
808             Maasha::Biopieces::put_record( $record, $out );
809
810             goto NUM if $options->{ "num" } and $num == $options->{ "num" };
811
812             $num++;
813         }
814
815         close $data_in;
816     }
817
818     NUM:
819
820     close $data_in if $data_in;
821 }
822
823
824 sub script_read_blast_tab
825 {
826     # Martin A. Hansen, September 2007.
827
828     # Read tabular BLAST output from NCBI blast run with -m8 or -m9.
829
830     my ( $in,        # handle to in stream
831          $out,       # handle to out stream
832          $options,   # options hash
833        ) = @_;
834
835     # Returns nothing.
836
837     my ( $file, $line, @fields, $strand, $record, $data_in, $num );
838
839     while ( $record = Maasha::Biopieces::get_record( $in ) ) {
840         Maasha::Biopieces::put_record( $record, $out );
841     }
842
843     $num = 1;
844
845     foreach $file ( @{ $options->{ "files" } } )
846     {
847         $data_in = Maasha::Common::read_open( $file );
848
849         while ( $line = <$data_in> )
850         {
851             chomp $line;
852
853             next if $line =~ /^#/;
854
855             @fields = split /\t/, $line;
856
857             $record->{ "REC_TYPE" }   = "BLAST";
858             $record->{ "Q_ID" }       = $fields[ 0 ];
859             $record->{ "S_ID" }       = $fields[ 1 ];
860             $record->{ "IDENT" }      = $fields[ 2 ];
861             $record->{ "ALIGN_LEN" }  = $fields[ 3 ];
862             $record->{ "MISMATCHES" } = $fields[ 4 ];
863             $record->{ "GAPS" }       = $fields[ 5 ];
864             $record->{ "Q_BEG" }      = $fields[ 6 ] - 1; # BLAST is 1-based
865             $record->{ "Q_END" }      = $fields[ 7 ] - 1; # BLAST is 1-based
866             $record->{ "S_BEG" }      = $fields[ 8 ] - 1; # BLAST is 1-based
867             $record->{ "S_END" }      = $fields[ 9 ] - 1; # BLAST is 1-based
868             $record->{ "E_VAL" }      = $fields[ 10 ];
869             $record->{ "BIT_SCORE" }  = $fields[ 11 ];
870
871             if ( $record->{ "S_BEG" } > $record->{ "S_END" } )
872             {
873                 $record->{ "STRAND" } = '-';
874
875                 ( $record->{ "S_BEG" }, $record->{ "S_END" } ) = ( $record->{ "S_END" }, $record->{ "S_BEG" } );
876             }
877             else
878             {
879                 $record->{ "STRAND" } = '+';
880             }
881
882             Maasha::Biopieces::put_record( $record, $out );
883
884             goto NUM if $options->{ "num" } and $num == $options->{ "num" };
885
886             $num++;
887         }
888
889         close $data_in;
890     }
891
892     NUM:
893
894     close $data_in if $data_in;
895 }
896
897
898 sub script_read_embl
899 {
900     # Martin A. Hansen, August 2007.
901
902     # Read EMBL format.
903
904     my ( $in,        # handle to in stream
905          $out,       # handle to out stream
906          $options,   # options hash
907        ) = @_;
908
909     # Returns nothing.
910
911     my ( %options2, $file, $data_in, $num, $entry, $record );
912
913     map { $options2{ "keys" }{ $_ } = 1 }  @{ $options->{ "keys" } };
914     map { $options2{ "feats" }{ $_ } = 1 } @{ $options->{ "feats" } };
915     map { $options2{ "quals" }{ $_ } = 1 } @{ $options->{ "quals" } };
916
917     while ( $record = Maasha::Biopieces::get_record( $in ) ) {
918         Maasha::Biopieces::put_record( $record, $out );
919     }
920
921     $num = 1;
922
923     foreach $file ( @{ $options->{ "files" } } )
924     {
925         $data_in = Maasha::Common::read_open( $file );
926
927         while ( $entry = Maasha::EMBL::get_embl_entry( $data_in ) ) 
928         {
929             $record = Maasha::EMBL::parse_embl_entry( $entry, \%options2 );
930
931             my ( $feat, $feat2, $qual, $qual_val, $record_copy );
932
933             $record_copy = dclone $record;
934
935             delete $record_copy->{ "FT" };
936
937             Maasha::Biopieces::put_record( $record_copy, $out );
938
939             delete $record_copy->{ "SEQ" };
940
941             foreach $feat ( keys %{ $record->{ "FT" } } )
942             {
943                 $record_copy->{ "FEAT_TYPE" } = $feat;
944
945                 foreach $feat2 ( @{ $record->{ "FT" }->{ $feat } } )
946                 {
947                     foreach $qual ( keys %{ $feat2 } )
948                     {
949                         $qual_val = join "; ", @{ $feat2->{ $qual } };
950
951                         $qual =~ s/^_//;
952                         $qual = uc $qual;
953
954                         $record_copy->{ $qual } = $qual_val;
955                     }
956
957                     Maasha::Biopieces::put_record( $record_copy, $out );
958                 }
959             }
960
961             goto NUM if $options->{ "num" } and $num == $options->{ "num" };
962
963             $num++;
964         }
965
966         close $data_in;
967     }
968
969     NUM:
970
971     close $data_in if $data_in;
972 }
973
974
975 sub script_read_stockholm
976 {
977     # Martin A. Hansen, August 2007.
978
979     # Read Stockholm format.
980
981     my ( $in,        # handle to in stream
982          $out,       # handle to out stream
983          $options,   # options hash
984        ) = @_;
985
986     # Returns nothing.
987
988     my ( $data_in, $file, $num, $entry, $record, $record_anno, $record_align, $key, $seq );
989
990     while ( $record = Maasha::Biopieces::get_record( $in ) ) {
991         Maasha::Biopieces::put_record( $record, $out );
992     }
993
994     $num = 1;
995
996     foreach $file ( @{ $options->{ "files" } } )
997     {
998         $data_in = Maasha::Common::read_open( $file );
999
1000         while ( $entry = Maasha::Stockholm::get_stockholm_entry( $data_in ) ) 
1001         {
1002             $record = Maasha::Stockholm::parse_stockholm_entry( $entry );
1003
1004             undef $record_anno;
1005
1006             foreach $key ( keys %{ $record->{ "GF" } } ) {
1007                 $record_anno->{ $key } = $record->{ "GF" }->{ $key };
1008             }
1009
1010             $record_anno->{ "ALIGN" } = $num;
1011
1012             Maasha::Biopieces::put_record( $record_anno, $out );
1013
1014             foreach $seq ( @{ $record->{ "ALIGN" } } )
1015             {
1016                 undef $record_align;
1017             
1018                 $record_align = {
1019                     SEQ_NAME  => $seq->[ 0 ],
1020                     SEQ       => $seq->[ 1 ],
1021                 };
1022             
1023                 Maasha::Biopieces::put_record( $record_align, $out );
1024             }
1025
1026             goto NUM if $options->{ "num" } and $num == $options->{ "num" };
1027
1028             $num++;
1029         }
1030
1031         close $data_in;
1032     }
1033
1034     NUM:
1035
1036     close $data_in if $data_in;
1037 }
1038
1039
1040 sub script_read_phastcons
1041 {
1042     # Martin A. Hansen, December 2007.
1043
1044     # Read PhastCons format.
1045
1046     my ( $in,        # handle to in stream
1047          $out,       # handle to out stream
1048          $options,   # options hash
1049        ) = @_;
1050
1051     # Returns nothing.
1052
1053     my ( $data_in, $file, $num, $entry, @records, $record );
1054
1055     $options->{ "min" }       ||= 10;
1056     $options->{ "dist" }      ||= 25;
1057     $options->{ "threshold" } ||= 0.8;
1058     $options->{ "gap" }       ||= 5;
1059
1060     while ( $record = Maasha::Biopieces::get_record( $in ) ) {
1061         Maasha::Biopieces::put_record( $record, $out );
1062     }
1063
1064     $num = 1;
1065
1066     foreach $file ( @{ $options->{ "files" } } )
1067     {
1068         $data_in = Maasha::Common::read_open( $file );
1069
1070         while ( $entry = Maasha::UCSC::fixedstep_get_entry( $data_in ) ) 
1071         {
1072             @records = Maasha::UCSC::phastcons_parse_entry( $entry, $options );
1073
1074             foreach $record ( @records )
1075             {
1076                 $record->{ "REC_TYPE" } = "BED";
1077                 $record->{ "BED_LEN" }  = $record->{ "CHR_END" } - $record->{ "CHR_BEG" } + 1;
1078
1079                 Maasha::Biopieces::put_record( $record, $out );
1080
1081                 goto NUM if $options->{ "num" } and $num == $options->{ "num" };
1082
1083                 $num++;
1084             }
1085         }
1086
1087         close $data_in;
1088     }
1089
1090     NUM:
1091
1092     close $data_in if $data_in;
1093 }
1094
1095
1096 sub script_read_soft
1097 {
1098     # Martin A. Hansen, December 2007.
1099
1100     # Read soft format.
1101     # http://www.ncbi.nlm.nih.gov/geo/info/soft2.html
1102
1103     my ( $in,        # handle to in stream
1104          $out,       # handle to out stream
1105          $options,   # options hash
1106        ) = @_;
1107
1108     # Returns nothing.
1109
1110     my ( $data_in, $file, $num, $records, $record, $soft_index, $fh, @platforms, $plat_table, @samples, $sample, $old_end, $skip );
1111
1112     while ( $record = Maasha::Biopieces::get_record( $in ) ) {
1113         Maasha::Biopieces::put_record( $record, $out );
1114     }
1115
1116     $num = 1;
1117
1118     foreach $file ( @{ $options->{ "files" } } )
1119     {
1120         print STDERR "Creating index for file: $file\n" if $options->{ "verbose" };
1121
1122         $soft_index = Maasha::NCBI::soft_index_file( $file );
1123
1124         $fh         = Maasha::Common::read_open( $file );
1125
1126         @platforms  = grep { $_->{ "SECTION" } =~ /PLATFORM/ } @{ $soft_index };
1127
1128         print STDERR "Getting platform tables for file: $file\n" if $options->{ "verbose" };
1129
1130         $plat_table = Maasha::NCBI::soft_get_platform( $fh, $platforms[ 0 ]->{ "LINE_BEG" }, $platforms[ -1 ]->{ "LINE_END" } );
1131
1132         @samples    = grep { $_->{ "SECTION" } =~ /SAMPLE/ } @{ $soft_index };
1133
1134         $old_end    = $platforms[ -1 ]->{ "LINE_END" };
1135
1136         foreach $sample ( @samples )
1137         {
1138             $skip = 0;
1139             $skip = 1 if ( $options->{ "samples" } and grep { $sample->{ "SECTION" } !~ /$_/ } @{ $options->{ "samples" } } );
1140
1141             print STDERR "Getting samples for dataset: $sample->{ 'SECTION' }\n" if $options->{ "verbose" } and not $skip;
1142
1143             $records = Maasha::NCBI::soft_get_sample( $fh, $plat_table, $sample->{ "LINE_BEG" } - $old_end - 1, $sample->{ "LINE_END" } - $old_end - 1, $skip );
1144
1145             foreach $record ( @{ $records } )
1146             {
1147                 Maasha::Biopieces::put_record( $record, $out );
1148
1149                 goto NUM if $options->{ "num" } and $num == $options->{ "num" };
1150
1151                 $num++;
1152             }
1153
1154             $old_end = $sample->{ "LINE_END" };
1155         }
1156
1157         close $fh;
1158     }
1159
1160     NUM:
1161
1162     close $data_in if $data_in;
1163     close $fh if $fh;
1164 }
1165
1166
1167 sub script_read_gff
1168 {
1169     # Martin A. Hansen, February 2008.
1170
1171     # Read soft format.
1172     # http://www.ncbi.nlm.nih.gov/geo/info/soft2.html
1173
1174     my ( $in,        # handle to in stream
1175          $out,       # handle to out stream
1176          $options,   # options hash
1177        ) = @_;
1178
1179     # Returns nothing.
1180
1181     my ( $data_in, $file, $fh, $num, $record, $entry );
1182
1183     while ( $record = Maasha::Biopieces::get_record( $in ) ) {
1184         Maasha::Biopieces::put_record( $record, $out );
1185     }
1186
1187     $num = 1;
1188
1189     foreach $file ( @{ $options->{ "files" } } )
1190     {
1191         $fh = Maasha::Common::read_open( $file );
1192
1193         while ( $entry = Maasha::GFF::get_entry( $fh ) )
1194         {
1195             Maasha::Biopieces::put_record( $entry, $out );
1196
1197             goto NUM if $options->{ "num" } and $num == $options->{ "num" };
1198
1199             $num++;
1200         }
1201
1202         close $fh;
1203     }
1204
1205     NUM:
1206
1207     close $data_in if $data_in;
1208 }
1209
1210
1211 sub script_read_2bit
1212 {
1213     # Martin A. Hansen, March 2008.
1214
1215     # Read sequences from 2bit file.
1216
1217     my ( $in,        # handle to in stream
1218          $out,       # handle to out stream
1219          $options,   # options hash
1220        ) = @_;
1221
1222     # Returns nothing.
1223
1224     my ( $record, $file, $data_in, $mask, $toc, $line, $num );
1225
1226     $mask = 1 if not $options->{ "no_mask" };
1227
1228     while ( $record = Maasha::Biopieces::get_record( $in ) ) {
1229         Maasha::Biopieces::put_record( $record, $out );
1230     }
1231
1232     $num = 1;
1233
1234     foreach $file ( @{ $options->{ "files" } } )
1235     {
1236         $data_in = Maasha::Common::read_open( $file );
1237
1238         $toc = Maasha::TwoBit::twobit_get_TOC( $data_in );
1239
1240         foreach $line ( @{ $toc } )
1241         {
1242             $record->{ "SEQ_NAME" } = $line->[ 0 ];
1243             $record->{ "SEQ" }      = Maasha::TwoBit::twobit_get_seq( $data_in, $line->[ 1 ], undef, undef, $mask );
1244             $record->{ "SEQ_LEN" }  = length $record->{ "SEQ" };
1245
1246             Maasha::Biopieces::put_record( $record, $out );
1247
1248             goto NUM if $options->{ "num" } and $num == $options->{ "num" };
1249
1250             $num++;
1251         }
1252
1253         close $data_in;
1254     }
1255
1256     NUM:
1257
1258     close $data_in if $data_in;
1259 }
1260
1261
1262 sub script_read_solexa
1263 {
1264     # Martin A. Hansen, March 2008.
1265
1266     # Read Solexa sequence reads from file.
1267
1268     my ( $in,        # handle to in stream
1269          $out,       # handle to out stream
1270          $options,   # options hash
1271        ) = @_;
1272
1273     # Returns nothing.
1274
1275     my ( $record, $file, $data_in, $entry, $num, @seqs, @scores, $i );
1276
1277     $options->{ "format" }  ||= "octal";
1278     $options->{ "quality" } ||= 20;
1279
1280     while ( $record = Maasha::Biopieces::get_record( $in ) ) {
1281         Maasha::Biopieces::put_record( $record, $out );
1282     }
1283
1284     $num = 1;
1285
1286     foreach $file ( @{ $options->{ "files" } } )
1287     {
1288         $data_in = Maasha::Common::read_open( $file );
1289
1290         if ( $options->{ "format" } eq "octal" )
1291         {
1292             while ( $entry = Maasha::Solexa::solexa_get_entry_octal( $data_in ) )
1293             {
1294                 $record = Maasha::Solexa::solexa2biopiece( $entry, $options->{ "quality" } );
1295
1296                 Maasha::Biopieces::put_record( $record, $out );
1297
1298                 goto NUM if $options->{ "num" } and $num == $options->{ "num" };
1299
1300                 $num++;
1301             }
1302         }
1303         else
1304         {
1305             while ( $entry = Maasha::Solexa::solexa_get_entry_decimal( $data_in ) )
1306             {
1307                 $record = Maasha::Solexa::solexa2biopiece( $entry, $options->{ "quality" } );
1308
1309                 Maasha::Biopieces::put_record( $record, $out );
1310
1311                 goto NUM if $options->{ "num" } and $num == $options->{ "num" };
1312
1313                 $num++;
1314             }
1315         }
1316
1317         close $data_in;
1318     }
1319
1320     NUM:
1321
1322     close $data_in if $data_in;
1323 }
1324
1325
1326 sub script_read_solid
1327 {
1328     # Martin A. Hansen, April 2008.
1329
1330     # Read Solid sequence from file.
1331
1332     my ( $in,        # handle to in stream
1333          $out,       # handle to out stream
1334          $options,   # options hash
1335        ) = @_;
1336
1337     # Returns nothing.
1338
1339     my ( $record, $file, $data_in, $line, $num, $seq_name, $seq_cs, $seq_qual, @scores, @seqs, $i );
1340
1341     $options->{ "quality" } ||= 15;
1342
1343     while ( $record = Maasha::Biopieces::get_record( $in ) ) {
1344         Maasha::Biopieces::put_record( $record, $out );
1345     }
1346
1347     $num = 1;
1348
1349     foreach $file ( @{ $options->{ "files" } } )
1350     {
1351         $data_in = Maasha::Common::read_open( $file );
1352
1353         while ( $line = <$data_in> )
1354         {
1355             chomp $line;
1356
1357             ( $seq_name, $seq_cs, $seq_qual ) = split /\t/, $line;
1358
1359             @scores = split /,/, $seq_qual;
1360             @seqs   = split //, Maasha::Solid::color_space2seq( $seq_cs );
1361
1362             for ( $i = 0; $i < @seqs; $i++ ) {
1363                 $seqs[ $i ] = lc $seqs[ $i ] if $scores[ $i ] < $options->{ "quality" };
1364             }
1365
1366             $record = {
1367                 REC_TYPE   => 'SOLID',
1368                 SEQ_NAME   => $seq_name,
1369                 SEQ_CS     => $seq_cs,
1370                 SEQ_QUAL   => join( ";", @scores ),
1371                 SEQ_LEN    => length $seq_cs,
1372                 SEQ        => join( "", @seqs ),
1373                 SCORE_MEAN => sprintf( "%.2f", Maasha::Calc::mean( \@scores ) ),
1374             };
1375
1376             Maasha::Biopieces::put_record( $record, $out );
1377
1378             goto NUM if $options->{ "num" } and $num == $options->{ "num" };
1379
1380             $num++;
1381         }
1382
1383         close $data_in;
1384     }
1385
1386     NUM:
1387
1388     close $data_in if $data_in;
1389 }
1390
1391
1392 sub script_read_mysql
1393 {
1394     # Martin A. Hansen, May 2008.
1395
1396     # Read a MySQL query into stream.
1397
1398     my ( $in,        # handle to in stream
1399          $out,       # handle to out stream
1400          $options,   # options hash
1401        ) = @_;
1402
1403     # Returns nothing.
1404
1405     my ( $record, $dbh, $results );
1406
1407     $options->{ "user" }     ||= Maasha::UCSC::ucsc_get_user();
1408     $options->{ "password" } ||= Maasha::UCSC::ucsc_get_password();
1409
1410     while ( $record = Maasha::Biopieces::get_record( $in ) ) {
1411         Maasha::Biopieces::put_record( $record, $out );
1412     }
1413
1414     $dbh = Maasha::SQL::connect( $options->{ "database" }, $options->{ "user" }, $options->{ "password" } );
1415
1416     $results = Maasha::SQL::query_hashref_list( $dbh, $options->{ "query" } );
1417
1418     Maasha::SQL::disconnect( $dbh );
1419
1420     map { Maasha::Biopieces::put_record( $_ ) } @{ $results };
1421 }
1422
1423
1424 sub script_read_ucsc_config
1425 {
1426     # Martin A. Hansen, November 2008.
1427
1428     # Read track entries from UCSC Genome Browser '.ra' files.
1429
1430     my ( $in,        # handle to in stream
1431          $out,       # handle to out stream
1432          $options,   # options hash
1433        ) = @_;
1434
1435     # Returns nothing.
1436
1437     my ( $record, $file, $data_in, $entry, $num );
1438
1439     while ( $record = Maasha::Biopieces::get_record( $in ) ) {
1440         Maasha::Biopieces::put_record( $record, $out );
1441     }
1442
1443     $num = 1;
1444
1445     foreach $file ( @{ $options->{ "files" } } )
1446     {
1447         $data_in = Maasha::Common::read_open( $file );
1448
1449         while ( $record = Maasha::UCSC::ucsc_config_entry_get( $data_in ) ) 
1450         {
1451             $record->{ 'REC_TYPE' } = "UCSC Config";
1452
1453             Maasha::Biopieces::put_record( $record, $out );
1454
1455             goto NUM if $options->{ "num" } and $num == $options->{ "num" };
1456
1457             $num++;
1458         }
1459
1460         close $data_in;
1461     }
1462
1463     NUM:
1464
1465     close $data_in if $data_in;
1466 }
1467
1468
1469 sub script_complexity_seq
1470 {
1471     # Martin A. Hansen, May 2008.
1472
1473     # Generates an index calculated as the most common di-residue over
1474     # the sequence length for all sequences in stream.
1475
1476     my ( $in,     # handle to in stream
1477          $out,    # handle to out stream
1478        ) = @_;
1479
1480     # Returns nothing.
1481
1482     my ( $record, $index );
1483
1484     while ( $record = Maasha::Biopieces::get_record( $in ) ) 
1485     {
1486         $record->{ "SEQ_COMPLEXITY" } = sprintf( "%.2f", Maasha::Seq::seq_complexity( $record->{ "SEQ" } ) ) if $record->{ "SEQ" };
1487
1488         Maasha::Biopieces::put_record( $record, $out );
1489     }
1490 }
1491
1492
1493 sub script_remove_indels
1494 {
1495     # Martin A. Hansen, August 2007.
1496
1497     # Remove indels from sequences in stream.
1498
1499     my ( $in,     # handle to in stream
1500          $out,    # handle to out stream
1501        ) = @_;
1502
1503     # Returns nothing.
1504
1505     my ( $record );
1506
1507     while ( $record = Maasha::Biopieces::get_record( $in ) ) 
1508     {
1509         $record->{ 'SEQ' } =~ tr/-~.//d if $record->{ "SEQ" };
1510
1511         Maasha::Biopieces::put_record( $record, $out );
1512     }
1513 }
1514
1515
1516 sub script_get_genome_align
1517 {
1518     # Martin A. Hansen, April 2008.
1519
1520     # Gets a subalignment from a multiple genome alignment.
1521
1522     my ( $in,        # handle to in stream
1523          $out,       # handle to out stream
1524          $options,   # options hash
1525        ) = @_;
1526
1527     # Returns nothing.
1528
1529     my ( $record, $maf_track, $align, $align_num, $beg, $end, $len, $entry );
1530
1531     $options->{ "strand" } ||= "+";
1532
1533     $align_num = 1;
1534
1535     $maf_track = Maasha::Config::maf_track( $options->{ "genome" } );
1536
1537     if ( $options->{ "chr" } and $options->{ "beg" } and ( $options->{ "end" } or $options->{ "len" } ) )
1538     {
1539         $beg = $options->{ "beg" } - 1;
1540         
1541         if ( $options->{ "end" } ) {
1542             $end = $options->{ "end" };
1543         } elsif ( $options->{ "len" } ) {
1544             $end = $beg + $options->{ "len" };
1545         }
1546
1547         $align = Maasha::UCSC::maf_extract( $BP_TMP, $options->{ "genome" }, $maf_track, $options->{ "chr" }, $beg, $end, $options->{ "strand" } );
1548
1549         foreach $entry ( @{ $align } )
1550         {
1551             $entry->{ "CHR" }     = $record->{ "CHR" };
1552             $entry->{ "CHR_BEG" } = $record->{ "CHR_BEG" };
1553             $entry->{ "CHR_END" } = $record->{ "CHR_END" };
1554             $entry->{ "STRAND" }  = $record->{ "STRAND" } || '+';
1555             $entry->{ "Q_ID" }    = $record->{ "Q_ID" };
1556             $entry->{ "SCORE" }   = $record->{ "SCORE" };
1557
1558             Maasha::Biopieces::put_record( $entry, $out );
1559         }
1560     }
1561
1562     while ( $record = Maasha::Biopieces::get_record( $in ) ) 
1563     {
1564         if ( $record->{ "REC_TYPE" } eq "BED" )
1565         {
1566             $align = Maasha::UCSC::maf_extract( $BP_TMP, $options->{ "genome" }, $maf_track, $record->{ "CHR" }, $record->{ "CHR_BEG" }, $record->{ "CHR_END" }, $record->{ "STRAND" } );
1567         }
1568         elsif ( $record->{ "REC_TYPE" } eq "VMATCH" )
1569         {
1570             $align = Maasha::UCSC::maf_extract( $BP_TMP, $options->{ "genome" }, $maf_track, $record->{ "S_ID" }, $record->{ "S_BEG" }, $record->{ "S_END" } + 1, $record->{ "STRAND" } );
1571         }
1572         elsif ( $record->{ "REC_TYPE" } eq "PSL" )
1573         {
1574             $align = Maasha::UCSC::maf_extract( $BP_TMP, $options->{ "genome" }, $maf_track, $record->{ "S_ID" }, $record->{ "S_BEG" }, $record->{ "S_END" }, $record->{ "STRAND" } );
1575         }
1576         elsif ( $record->{ "REC_TYPE" } eq "BLAST" )
1577         {
1578             $align = Maasha::UCSC::maf_extract( $BP_TMP, $options->{ "genome" }, $maf_track, $record->{ "S_ID" }, $record->{ "S_BEG" }, $record->{ "S_END" }, $record->{ "STRAND" } );
1579         }
1580
1581         foreach $entry ( @{ $align } )
1582         {
1583             $entry->{ "CHR" }     = $record->{ "CHR" };
1584             $entry->{ "CHR_BEG" } = $record->{ "CHR_BEG" };
1585             $entry->{ "CHR_END" } = $record->{ "CHR_END" };
1586             $entry->{ "STRAND" }  = $record->{ "STRAND" };
1587             $entry->{ "Q_ID" }    = $record->{ "Q_ID" };
1588             $entry->{ "SCORE" }   = $record->{ "SCORE" };
1589
1590             Maasha::Biopieces::put_record( $entry, $out );
1591         }
1592
1593         $align_num++;
1594     }
1595 }
1596
1597
1598 sub script_get_genome_phastcons
1599 {
1600     # Martin A. Hansen, February 2008.
1601
1602     # Get phastcons scores from genome intervals.
1603
1604     my ( $in,        # handle to in stream
1605          $out,       # handle to out stream
1606          $options,   # options hash
1607        ) = @_;
1608
1609     # Returns nothing.
1610
1611     my ( $phastcons_file, $phastcons_index, $index, $fh_phastcons, $scores, $record );
1612
1613     $options->{ "flank" } ||= 0;
1614
1615     $phastcons_file  = Maasha::Config::genome_phastcons( $options->{ "genome" } );
1616     $phastcons_index = Maasha::Config::genome_phastcons_index( $options->{ "genome" } );
1617
1618     $index           = Maasha::UCSC::fixedstep_index_retrieve( $phastcons_index );
1619     $fh_phastcons    = Maasha::Common::read_open( $phastcons_file );
1620
1621     if ( defined $options->{ "chr" } and defined $options->{ "beg" } and ( defined $options->{ "end" } or defined $options->{ "len" } ) )
1622     {
1623         $options->{ "beg" } -= 1;   # request is 1-based
1624         $options->{ "end" } -= 1;   # request is 1-based
1625
1626         if ( $options->{ "len" } ) {
1627             $options->{ "end" } = $options->{ "beg" } + $options->{ "len" } - 1;
1628         }
1629
1630         $scores = Maasha::UCSC::fixedstep_index_lookup( $index, $fh_phastcons, $options->{ "chr" }, $options->{ "beg" }, $options->{ "end" }, $options->{ "flank" } );
1631
1632         $record->{ "CHR" }       = $options->{ "chr" };
1633         $record->{ "CHR_BEG" }   = $options->{ "beg" } - $options->{ "flank" };
1634         $record->{ "CHR_END" }   = $options->{ "end" } + $options->{ "flank" };
1635         
1636         $record->{ "PHASTCONS" }   = join ",", @{ $scores };
1637         $record->{ "PHAST_COUNT" } = scalar @{ $scores };  # DEBUG
1638
1639         Maasha::Biopieces::put_record( $record, $out );
1640     }   
1641
1642     while ( $record = Maasha::Biopieces::get_record( $in ) ) 
1643     {
1644         if ( $record->{ "REC_TYPE" } eq "BED" )
1645         {
1646             $scores = Maasha::UCSC::fixedstep_index_lookup( $index, $fh_phastcons, $record->{ "CHR" }, $record->{ "CHR_BEG" }, $record->{ "CHR_END" }, $options->{ "flank" } );
1647         }
1648         elsif ( $record->{ "REC_TYPE" } eq "PSL" )
1649         {
1650             $scores = Maasha::UCSC::fixedstep_index_lookup( $index, $fh_phastcons, $record->{ "S_ID" }, $record->{ "S_BEG" }, $record->{ "S_END" }, $options->{ "flank" } );
1651         }
1652         elsif ( $record->{ "REC_TYPE" } eq "BLAST" )
1653         {
1654             $scores = Maasha::UCSC::fixedstep_index_lookup( $index, $fh_phastcons, $record->{ "S_ID" }, $record->{ "S_BEG" }, $record->{ "S_END" }, $options->{ "flank" } );
1655         }
1656
1657         $record->{ "PHASTCONS" } = join ",", @{ $scores } if @{ $scores };
1658 #        $record->{ "PHAST_COUNT" } = @{ $scores } if @{ $scores };  # DEBUG
1659
1660         Maasha::Biopieces::put_record( $record, $out );
1661     }
1662
1663     close $fh_phastcons if $fh_phastcons;                                                                                                                                          
1664 }
1665
1666
1667 sub script_soap_seq
1668 {
1669     # Martin A. Hansen, July 2008.
1670
1671     # soap sequences in stream against a given file or genome.
1672
1673     my ( $in,        # handle to in stream
1674          $out,       # handle to out stream
1675          $options,   # options hash
1676        ) = @_;
1677
1678     # Returns nothing.
1679
1680     my ( $genome, $tmp_in, $tmp_out, $fh_in, $fh_out, $record, $line, @fields, $entry, $count, $args );
1681
1682     $options->{ "seed_size" }  ||= 10;
1683     $options->{ "mismatches" } ||= 2;
1684     $options->{ "gap_size" }   ||= 0;
1685     $options->{ "cpus" }       ||= 1;
1686
1687     if ( $options->{ "genome" } ) {
1688         $options->{ "in_file" } = "$ENV{ 'BP_DATA' }/genomes/$options->{ 'genome' }/fasta/$options->{ 'genome' }.fna";
1689     }
1690
1691     $tmp_in  = "$BP_TMP/soap_query.seq";
1692     $tmp_out = "$BP_TMP/soap.result";
1693
1694     $fh_out = Maasha::Common::write_open( $tmp_in );
1695  
1696     $count = 0;
1697
1698     while ( $record = Maasha::Biopieces::get_record( $in ) ) 
1699     {
1700         if ( $entry = Maasha::Fasta::biopiece2fasta( $record ) )
1701         {
1702             Maasha::Fasta::put_entry( $entry, $fh_out );
1703
1704             $count++;
1705         }
1706
1707         Maasha::Biopieces::put_record( $record, $out );
1708     }
1709
1710     close $fh_out;
1711
1712     if ( $count > 0 )
1713     {
1714         $args = join( " ",
1715             "-s $options->{ 'seed_size' }",
1716             "-r 2",
1717             "-a $tmp_in",
1718             "-v $options->{ 'mismatches' }",
1719             "-g $options->{ 'gap_size' }",
1720             "-p $options->{ 'cpus' }",
1721             "-d $options->{ 'in_file' }",
1722             "-o $tmp_out",
1723         );
1724
1725         $args .= " > /dev/null 2>&1" if not $options->{ 'verbose' };
1726
1727         Maasha::Common::run( "soap", $args, 1 );
1728
1729         unlink $tmp_in;
1730
1731         $fh_out = Maasha::Common::read_open( $tmp_out );
1732
1733         undef $record;
1734
1735         while ( $line = <$fh_out> )
1736         {
1737             chomp $line;
1738
1739             @fields = split /\t/, $line;
1740
1741             $record->{ "REC_TYPE" }   = "SOAP";
1742             $record->{ "Q_ID" }       = $fields[ 0 ];
1743             $record->{ "SCORE" }      = $fields[ 3 ];
1744             $record->{ "STRAND" }     = $fields[ 6 ];
1745             $record->{ "S_ID" }       = $fields[ 7 ];
1746             $record->{ "S_BEG" }      = $fields[ 8 ] - 1; # soap is 1-based
1747             $record->{ "S_END" }      = $fields[ 8 ] + $fields[ 5 ] - 2;
1748
1749             Maasha::Biopieces::put_record( $record, $out );
1750         }
1751
1752         close $fh_out;
1753     }
1754
1755     unlink $tmp_out;
1756 }
1757
1758
1759 sub script_write_bed
1760 {
1761     # Martin A. Hansen, August 2007.
1762
1763     # Write BED format for the UCSC genome browser using records in stream.
1764
1765     my ( $in,        # handle to in stream
1766          $out,       # handle to out stream
1767          $options,   # options hash
1768        ) = @_;
1769
1770     # Returns nothing.
1771
1772     my ( $cols, $fh, $record, $bed_entry, $new_record );
1773
1774     $cols = $options->{ 'cols' }->[ 0 ];
1775
1776     $fh = Maasha::Biopieces::write_stream( $options->{ 'data_out' }, $options->{ 'compress' } );
1777
1778     while ( $record = Maasha::Biopieces::get_record( $in ) ) 
1779     {
1780         $record = Maasha::UCSC::psl2record( $record ) if $record->{ 'tBaseInsert' }; # Dirty addition to allow Affy data from MySQL to be dumped
1781
1782         if ( $bed_entry = Maasha::UCSC::BED::biopiece2bed( $record, $cols ) ) {
1783             Maasha::UCSC::BED::bed_entry_put( $bed_entry, $fh, $cols, $options->{ 'check' } );
1784         }
1785
1786         Maasha::Biopieces::put_record( $record, $out ) if not $options->{ 'no_stream' };
1787     }
1788
1789     close $fh;
1790 }
1791
1792
1793 sub script_write_psl
1794 {
1795     # Martin A. Hansen, August 2007.
1796
1797     # Write PSL output from stream.
1798
1799     my ( $in,        # handle to in stream
1800          $out,       # handle to out stream
1801          $options,   # options hash
1802        ) = @_;
1803
1804     # Returns nothing.
1805
1806     my ( $fh, $record, @output, $first );
1807
1808     $first = 1;
1809
1810     $fh = write_stream( $options->{ "data_out" }, $options->{ "compress" } );
1811
1812     while ( $record = Maasha::Biopieces::get_record( $in ) ) 
1813     {
1814         Maasha::Biopieces::put_record( $record, $out ) if not $options->{ "no_stream" };
1815
1816         if ( $record->{ "REC_TYPE" } and $record->{ "REC_TYPE" } eq "PSL" )
1817         {
1818             Maasha::UCSC::psl_put_header( $fh ) if $first;
1819             Maasha::UCSC::psl_put_entry( $record, $fh );
1820             $first = 0;
1821         }
1822     }
1823
1824     close $fh;
1825 }
1826
1827
1828 sub script_write_fixedstep
1829 {
1830     # Martin A. Hansen, Juli 2008.
1831
1832     # Write fixedStep entries from recrods in the stream.
1833
1834     my ( $in,        # handle to in stream
1835          $out,       # handle to out stream
1836          $options,   # options hash
1837        ) = @_;
1838
1839     # Returns nothing.
1840
1841     my ( $fh, $record, $entry );
1842
1843     $fh = write_stream( $options->{ "data_out" }, $options->{ "compress" } );
1844
1845     while ( $record = Maasha::Biopieces::get_record( $in ) ) 
1846     {
1847         if ( $entry = Maasha::UCSC::Wiggle::biopiece2fixedstep( $record ) ) {
1848             Maasha::UCSC::Wiggle::fixedstep_entry_put( $entry, $fh );
1849         }
1850
1851         Maasha::Biopieces::put_record( $record, $out ) if not $options->{ "no_stream" };
1852     }
1853
1854     close $fh;
1855 }
1856
1857
1858 sub script_write_2bit
1859 {
1860     # Martin A. Hansen, March 2008.
1861
1862     # Write sequence entries from stream in 2bit format.
1863
1864     my ( $in,        # handle to in stream
1865          $out,       # handle to out stream
1866          $options,   # options hash
1867        ) = @_;
1868
1869     # Returns nothing.
1870
1871     my ( $record, $mask, $tmp_file, $fh_tmp, $fh_in, $fh_out, $entry );
1872
1873     $mask = 1 if not $options->{ "no_mask" };
1874
1875     $tmp_file = "$BP_TMP/write_2bit.fna";
1876     $fh_tmp   = Maasha::Common::write_open( $tmp_file );
1877
1878     $fh_out = write_stream( $options->{ "data_out" } );
1879
1880     while ( $record = Maasha::Biopieces::get_record( $in ) ) 
1881     {
1882         if ( $entry = Maasha::Fasta::biopiece2fasta( $record ) ) {
1883             Maasha::Fasta::put_entry( $entry, $fh_tmp );
1884         }
1885
1886         Maasha::Biopieces::put_record( $record, $out ) if not $options->{ "no_stream" };
1887     }
1888
1889     close $fh_tmp;
1890
1891     $fh_in = Maasha::Common::read_open( $tmp_file );
1892
1893     Maasha::TwoBit::fasta2twobit( $fh_in, $fh_out, $mask );
1894
1895     close $fh_in;
1896     close $fh_out;
1897
1898     unlink $tmp_file;
1899 }
1900
1901
1902 sub script_write_solid
1903 {
1904     # Martin A. Hansen, April 2008.
1905
1906     # Write di-base encoded Solid sequence from entries in stream.
1907
1908     my ( $in,        # handle to in stream
1909          $out,       # handle to out stream
1910          $options,   # options hash
1911        ) = @_;
1912
1913     # Returns nothing.
1914
1915     my ( $record, $fh, $entry );
1916
1917     $fh = write_stream( $options->{ "data_out" }, $options->{ "compress" } );
1918
1919     while ( $record = Maasha::Biopieces::get_record( $in ) ) 
1920     {
1921         if ( $entry = Maasha::Fasta::biopiece2fasta( $record ) )
1922         {
1923             $entry->[ SEQ ] = Maasha::Solid::seq2color_space( uc $entry->[ SEQ ] );
1924
1925             Maasha::Fasta::put_entry( $entry, $fh, $options->{ "wrap" } );
1926         }
1927
1928         Maasha::Biopieces::put_record( $record, $out ) if not $options->{ "no_stream" };
1929     }
1930
1931     close $fh;
1932 }
1933
1934
1935 sub script_write_ucsc_config
1936 {
1937     # Martin A. Hansen, November 2008.
1938
1939     # Write UCSC Genome Broser configuration (.ra file type) from
1940     # records in the stream.
1941
1942     my ( $in,        # handle to in stream
1943          $out,       # handle to out stream
1944          $options,   # options hash
1945        ) = @_;
1946
1947     # Returns nothing.
1948
1949     my ( $record, $fh );
1950
1951     $fh = write_stream( $options->{ "data_out" } );
1952
1953     while ( $record = Maasha::Biopieces::get_record( $in ) ) 
1954     {
1955         Maasha::UCSC::ucsc_config_entry_put( $record, $fh ) if $record->{ "REC_TYPE" } eq "UCSC Config";
1956
1957         Maasha::Biopieces::put_record( $record, $out ) if not $options->{ "no_stream" };
1958     }
1959
1960     close $fh;
1961 }
1962
1963
1964 sub script_plot_seqlogo
1965 {
1966     # Martin A. Hansen, August 2007.
1967
1968     # Calculates and writes a sequence logo for alignments.
1969
1970     my ( $in,        # handle to in stream
1971          $out,       # handle to out stream
1972          $options,   # options hash
1973        ) = @_;
1974
1975     # Returns nothing.
1976
1977     my ( $record, @entries, $logo, $fh );
1978
1979     while ( $record = Maasha::Biopieces::get_record( $in ) ) 
1980     {
1981         if ( $record->{ "SEQ_NAME" } and $record->{ "SEQ" } ) {
1982             push @entries, [ $record->{ "SEQ_NAME" }, $record->{ "SEQ" } ];
1983         }
1984
1985         Maasha::Biopieces::put_record( $record, $out ) if not $options->{ "no_stream" };
1986     }
1987
1988     $logo = Maasha::Plot::seq_logo( \@entries );
1989
1990     $fh = write_stream( $options->{ "data_out" } );
1991
1992     print $fh $logo;
1993
1994     close $fh;
1995 }
1996
1997
1998 sub script_plot_phastcons_profiles
1999 {
2000     # Martin A. Hansen, January 2008.
2001
2002     # Plots PhastCons profiles.
2003
2004     my ( $in,        # handle to in stream
2005          $out,       # handle to out stream
2006          $options,   # options hash
2007        ) = @_;
2008
2009     # Returns nothing.
2010
2011     my ( $phastcons_file, $phastcons_index, $index, $fh_phastcons, $record, $scores, $AoA, $plot, $fh );
2012
2013     $options->{ "title" } ||= "PhastCons Profiles";
2014
2015     $phastcons_file  = Maasha::Config::genome_phastcons( $options->{ "genome" } );
2016     $phastcons_index = Maasha::Config::genome_phastcons_index( $options->{ "genome" } );
2017
2018     $index           = Maasha::UCSC::fixedstep_index_retrieve( $phastcons_index );
2019     $fh_phastcons    = Maasha::Common::read_open( $phastcons_file );
2020
2021     while ( $record = Maasha::Biopieces::get_record( $in ) ) 
2022     {
2023         if ( $record->{ "CHR" } and $record->{ "CHR_BEG" } and $record->{ "CHR_END" } )
2024         {
2025             $scores = Maasha::UCSC::fixedstep_index_lookup( $index, $fh_phastcons, $record->{ "CHR" },
2026                                                                                    $record->{ "CHR_BEG" },
2027                                                                                    $record->{ "CHR_END" },
2028                                                                                    $options->{ "flank" } );
2029
2030             push @{ $AoA }, [ @{ $scores } ];
2031         }
2032
2033         Maasha::Biopieces::put_record( $record, $out ) if not $options->{ "no_stream" };
2034     }
2035
2036     Maasha::UCSC::phastcons_normalize( $AoA );
2037
2038     $AoA = [ [ Maasha::UCSC::phastcons_mean( $AoA ) ] ] if $options->{ "mean" };
2039     $AoA = [ [ Maasha::UCSC::phastcons_median( $AoA ) ] ] if $options->{ "median" };
2040
2041     $AoA = Maasha::Matrix::matrix_flip( $AoA );
2042
2043     $plot = Maasha::Plot::lineplot_simple( $AoA, $options, $BP_TMP );
2044
2045     $fh = write_stream( $options->{ "data_out" } );
2046
2047     print $fh "$_\n" foreach @{ $plot };
2048
2049     close $fh;
2050 }
2051
2052
2053 sub script_remove_keys
2054 {
2055     # Martin A. Hansen, August 2007.
2056
2057     # Remove keys from stream.
2058
2059     my ( $in,        # handle to in stream
2060          $out,       # handle to out stream
2061          $options,   # options hash
2062        ) = @_;
2063
2064     # Returns nothing.
2065
2066     my ( $record, $new_record );
2067
2068     while ( $record = Maasha::Biopieces::get_record( $in ) ) 
2069     {
2070         if ( $options->{ "keys" } )
2071         {
2072             map { delete $record->{ $_ } } @{ $options->{ "keys" } };
2073         }
2074         elsif ( $options->{ "save_keys" } )
2075         {
2076             map { $new_record->{ $_ } = $record->{ $_ } if exists $record->{ $_ } } @{ $options->{ "save_keys" } };
2077
2078             $record = $new_record;
2079         }
2080
2081         Maasha::Biopieces::put_record( $record, $out ) if keys %{ $record };
2082     }
2083 }
2084
2085
2086 sub script_remove_adaptor
2087 {
2088     # Martin A. Hansen, August 2008.
2089
2090     # Find and remove adaptor from sequences in the stream.
2091
2092     my ( $in,        # handle to in stream
2093          $out,       # handle to out stream
2094          $options,   # options hash
2095        ) = @_;
2096
2097     # Returns nothing.
2098
2099     my ( $record, $adaptor, $seq, $adaptor_len, $seq_len, $offset, $max_match, $max_mismatch, $pos );
2100
2101     $options->{ "remove" } ||= "after";
2102
2103     $max_mismatch = $options->{ "mismatches" } || 0;
2104     $offset       = $options->{ "offset" };
2105
2106     if ( not defined $offset ) {
2107         $offset = 0;
2108     } else {
2109         $offset--;
2110     }
2111
2112     $adaptor      = uc $options->{ "adaptor" };
2113     $adaptor_len  = length $adaptor;
2114
2115     while ( $record = Maasha::Biopieces::get_record( $in ) ) 
2116     {
2117         if ( $record->{ "SEQ" } )
2118         {
2119             $seq     = uc $record->{ "SEQ" };
2120             $seq_len = length $seq;
2121
2122             $pos = Maasha::Common::index_m( $seq, $adaptor, $seq_len, $adaptor_len, $offset, $max_mismatch );
2123
2124             $record->{ "ADAPTOR_POS" } = $pos;
2125
2126             if ( $pos >= 0 and $options->{ "remove" } ne "skip" )
2127             {
2128                 if ( $options->{ "remove" } eq "after" )
2129                 {
2130                     $record->{ "SEQ" }     = substr $record->{ "SEQ" }, 0, $pos;
2131                     $record->{ "SEQ_LEN" } = $pos;
2132                 }
2133                 else
2134                 {
2135                     $record->{ "SEQ" }     = substr $record->{ "SEQ" }, $pos + $adaptor_len;
2136                     $record->{ "SEQ_LEN" } = length $record->{ "SEQ" };
2137                 }
2138             }
2139
2140             Maasha::Biopieces::put_record( $record, $out );
2141         }
2142         else
2143         {
2144             Maasha::Biopieces::put_record( $record, $out );
2145         }
2146     }
2147 }
2148
2149
2150 sub script_remove_mysql_tables
2151 {
2152     # Martin A. Hansen, November 2008.
2153
2154     # Remove MySQL tables from values in stream.
2155
2156     my ( $in,        # handle to in stream
2157          $out,       # handle to out stream
2158          $options,   # options hash
2159        ) = @_;
2160
2161     # Returns nothing.
2162
2163     my ( $record, %table_hash, $dbh, $table );
2164
2165     $options->{ "user" }     ||= Maasha::UCSC::ucsc_get_user();
2166     $options->{ "password" } ||= Maasha::UCSC::ucsc_get_password();
2167
2168     map { $table_hash{ $_ } = 1 } @{ $options->{ 'tables' } };
2169
2170     while ( $record = Maasha::Biopieces::get_record( $in ) )
2171     {
2172         map { $table_hash{ $record->{ $_ } } = 1 } @{ $options->{ 'keys' } };
2173
2174         Maasha::Biopieces::put_record( $record, $out ) if not $options->{ 'no_stream' };
2175     }
2176
2177     $dbh = Maasha::SQL::connect( $options->{ "database" }, $options->{ "user" }, $options->{ "password" } );
2178
2179     foreach $table ( sort keys %table_hash )
2180     {
2181         if ( Maasha::SQL::table_exists( $dbh, $table ) )
2182         {
2183             print STDERR qq(Removing table "$table" from database "$options->{ 'database' }" ... ) if $options->{ 'verbose' };
2184             Maasha::SQL::delete_table( $dbh, $table );
2185             print STDERR "done.\n" if $options->{ 'verbose' };
2186         }
2187         else
2188         {
2189             print STDERR qq(WARNING: table "$table" not found in database "$options->{ 'database' }\n");
2190         }
2191     }
2192
2193     Maasha::SQL::disconnect( $dbh );
2194 }
2195
2196
2197 sub script_remove_ucsc_tracks
2198 {
2199     # Martin A. Hansen, November 2008.
2200
2201     # Remove track from MySQL tables and config file.
2202
2203     my ( $in,        # handle to in stream
2204          $out,       # handle to out stream
2205          $options,   # options hash
2206        ) = @_;
2207
2208     # Returns nothing.
2209
2210     my ( $record, %track_hash, $fh_in, $fh_out, $track, @tracks, @new_tracks, $dbh );
2211
2212     $options->{ 'user' }        ||= Maasha::UCSC::ucsc_get_user();
2213     $options->{ 'password' }    ||= Maasha::UCSC::ucsc_get_password();
2214     $options->{ 'config_file' } ||= "$ENV{ 'HOME' }/ucsc/my_tracks.ra";
2215
2216     map { $track_hash{ $_ } = 1 } @{ $options->{ 'tracks' } };
2217
2218     while ( $record = Maasha::Biopieces::get_record( $in ) )
2219     {
2220         map { $track_hash{ $record->{ $_ } } = 1 } @{ $options->{ 'keys' } };
2221
2222         Maasha::Biopieces::put_record( $record, $out ) if not $options->{ 'no_stream' };
2223     }
2224
2225     $fh_in = Maasha::Filesys::file_read_open( $options->{ 'config_file' } );
2226     
2227     while ( $track = Maasha::UCSC::ucsc_config_entry_get( $fh_in ) ) {
2228         push @tracks, $track;
2229     }
2230
2231     close $fh_in;
2232
2233     foreach $track ( @tracks )
2234     {
2235         if ( $track->{ 'database' } eq $options->{ 'database' } and exists $track_hash{ $track->{ 'track' } } ) {
2236             print STDERR qq(Removing track "$track->{ 'track' }" from config file.\n) if $options->{ 'verbose' };
2237         } else {
2238             push @new_tracks, $track;
2239         }
2240     }
2241
2242     rename "$options->{ 'config_file' }", "$options->{ 'config_file' }~";
2243
2244     $fh_out = Maasha::Filesys::file_write_open( $options->{ 'config_file' } );
2245
2246     map { Maasha::UCSC::ucsc_config_entry_put( $_, $fh_out ) } @new_tracks;
2247
2248     close $fh_out;
2249
2250     # ---- locate track in database ----
2251
2252     $dbh = Maasha::SQL::connect( $options->{ "database" }, $options->{ "user" }, $options->{ "password" } );
2253
2254     foreach $track ( sort keys %track_hash )
2255     {
2256         if ( Maasha::SQL::table_exists( $dbh, $track ) )
2257         {
2258             print STDERR qq(Removing table "$track" from database "$options->{ 'database' }" ... ) if $options->{ 'verbose' };
2259             Maasha::SQL::delete_table( $dbh, $track );
2260             print STDERR "done.\n" if $options->{ 'verbose' };
2261         }
2262         else
2263         {
2264             print STDERR qq(WARNING: table "$track" not found in database "$options->{ 'database' }\n");
2265         }
2266     }
2267
2268     Maasha::SQL::disconnect( $dbh );
2269
2270     Maasha::Common::run( "ucscMakeTracks.pl", "-b > /dev/null 2>&1" );
2271 }
2272
2273
2274 sub script_rename_keys
2275 {
2276     # Martin A. Hansen, August 2007.
2277
2278     # Rename keys in stream.
2279
2280     my ( $in,        # handle to in stream
2281          $out,       # handle to out stream
2282          $options,   # options hash
2283        ) = @_;
2284
2285     # Returns nothing.
2286
2287     my ( $record );
2288
2289     while ( $record = Maasha::Biopieces::get_record( $in ) ) 
2290     {
2291         if ( exists $record->{ $options->{ "keys" }->[ 0 ] } )
2292         {
2293             $record->{ $options->{ "keys" }->[ 1 ] } = $record->{ $options->{ "keys" }->[ 0 ] };
2294
2295             delete $record->{ $options->{ "keys" }->[ 0 ] };
2296         }
2297
2298         Maasha::Biopieces::put_record( $record, $out );
2299     }
2300 }
2301
2302
2303 sub script_uniq_vals
2304 {
2305     # Martin A. Hansen, August 2007.
2306
2307     # Find unique values in stream.
2308
2309     my ( $in,        # handle to in stream
2310          $out,       # handle to out stream
2311          $options,   # options hash
2312        ) = @_;
2313
2314     # Returns nothing.
2315
2316     my ( %hash, $record );
2317
2318     while ( $record = Maasha::Biopieces::get_record( $in ) ) 
2319     {
2320         if ( $record->{ $options->{ "key" } } )
2321         {
2322             if ( not $hash{ $record->{ $options->{ "key" } } } and not $options->{ "invert" } )
2323             {
2324                 Maasha::Biopieces::put_record( $record, $out );
2325
2326                 $hash{ $record->{ $options->{ "key" } } } = 1;
2327             }
2328             elsif ( $hash{ $record->{ $options->{ "key" } } } and $options->{ "invert" } )
2329             {
2330                 Maasha::Biopieces::put_record( $record, $out );
2331             }
2332             else
2333             {
2334                 $hash{ $record->{ $options->{ "key" } } } = 1;
2335             }
2336         }
2337         else
2338         {
2339             Maasha::Biopieces::put_record( $record, $out );
2340         }
2341     }
2342 }
2343
2344
2345 sub script_plot_histogram
2346 {
2347     # Martin A. Hansen, September 2007.
2348
2349     # Plot a simple histogram for a given key using GNU plot.
2350
2351     my ( $in,        # handle to in stream
2352          $out,       # handle to out stream
2353          $options,   # options hash
2354        ) = @_;
2355
2356     # Returns nothing.
2357
2358     my ( $record, %data_hash, $max, @data_list, $i, $result, $fh );
2359
2360     $options->{ "title" } ||= "Histogram";
2361     $options->{ "sort" }  ||= "num";
2362
2363     while ( $record = Maasha::Biopieces::get_record( $in ) ) 
2364     {
2365         $data_hash{ $record->{ $options->{ "key" } } }++ if defined $record->{ $options->{ "key" } };
2366
2367         Maasha::Biopieces::put_record( $record, $out ) if not $options->{ "no_stream" };
2368     }
2369
2370     if ( $options->{ "sort" } eq "num" ) {
2371         map { push @data_list, [ $_, $data_hash{ $_ } ] } sort { $a <=> $b } keys %data_hash;
2372     } else {
2373         map { push @data_list, [ $_, $data_hash{ $_ } ] } sort keys %data_hash;
2374     }
2375
2376     $result = Maasha::Plot::histogram_simple( \@data_list, $options );
2377
2378     $fh = write_stream( $options->{ "data_out" } );
2379
2380     print $fh "$_\n" foreach @{ $result };
2381
2382     close $fh;
2383 }
2384
2385
2386 sub script_plot_lendist
2387 {
2388     # Martin A. Hansen, August 2007.
2389
2390     # Plot length distribution using GNU plot.
2391
2392     my ( $in,        # handle to in stream
2393          $out,       # handle to out stream
2394          $options,   # options hash
2395        ) = @_;
2396
2397     # Returns nothing.
2398
2399     my ( $record, %data_hash, $max, @data_list, $i, $result, $fh );
2400
2401     $options->{ "title" } ||= "Length Distribution";
2402
2403     while ( $record = Maasha::Biopieces::get_record( $in ) ) 
2404     {
2405         $data_hash{ $record->{ $options->{ "key" } } }++ if defined $record->{ $options->{ "key" } };
2406
2407         Maasha::Biopieces::put_record( $record, $out ) if not $options->{ "no_stream" };
2408     }
2409
2410     $max = Maasha::Calc::list_max( [ keys %data_hash ] );
2411
2412     for ( $i = 0; $i < $max; $i++ ) {
2413         push @data_list, [ $i, $data_hash{ $i } || 0 ];
2414     }
2415
2416     $result = Maasha::Plot::histogram_lendist( \@data_list, $options );
2417
2418     $fh = write_stream( $options->{ "data_out" } );
2419
2420     print $fh "$_\n" foreach @{ $result };
2421
2422     close $fh;
2423 }
2424
2425
2426 sub script_plot_chrdist
2427 {
2428     # Martin A. Hansen, August 2007.
2429
2430     # Plot chromosome distribution using GNU plot.
2431
2432     my ( $in,        # handle to in stream
2433          $out,       # handle to out stream
2434          $options,   # options hash
2435        ) = @_;
2436
2437     # Returns nothing.
2438
2439     my ( $record, %data_hash, @data_list, $elem, $sort_key, $count, $result, $fh );
2440
2441     $options->{ "title" } ||= "Chromosome Distribution";
2442
2443     while ( $record = Maasha::Biopieces::get_record( $in ) ) 
2444     {
2445         if ( $record->{ "CHR" } ) {                                                             # generic
2446             $data_hash{ $record->{ "CHR" } }++;
2447         } elsif ( $record->{ "REC_TYPE" } eq "PATSCAN" and $record->{ "S_ID" } =~ /^chr/i ) {   # patscan
2448             $data_hash{ $record->{ "S_ID" } }++;
2449         } elsif ( $record->{ "REC_TYPE" } eq "PSL" and $record->{ "S_ID" } =~ /^chr/i ) {       # BLAT / PSL
2450             $data_hash{ $record->{ "S_ID" } }++;
2451         } elsif ( $record->{ "REC_TYPE" } eq "BLAST" and $record->{ "S_ID" } =~ /^chr/i ) {     # BLAST
2452             $data_hash{ $record->{ "S_ID" } }++;
2453         }
2454
2455         Maasha::Biopieces::put_record( $record, $out ) if not $options->{ "no_stream" };
2456     }
2457
2458     foreach $elem ( keys %data_hash )
2459     {
2460         $sort_key = $elem;
2461
2462         $sort_key =~ s/chr//i;
2463     
2464         $sort_key =~ s/^X(.*)/99$1/;
2465         $sort_key =~ s/^Y(.*)/99$1/;
2466         $sort_key =~ s/^Z(.*)/999$1/;
2467         $sort_key =~ s/^M(.*)/9999$1/;
2468         $sort_key =~ s/^U(.*)/99999$1/;
2469
2470         $count = $sort_key =~ tr/_//;
2471
2472         $sort_key =~ s/_.*/"999999" x $count/ex;
2473
2474         push @data_list, [ $elem, $data_hash{ $elem }, $sort_key ];
2475     }
2476
2477     @data_list = sort { $a->[ 2 ] <=> $b->[ 2 ] } @data_list;
2478
2479     $result = Maasha::Plot::histogram_chrdist( \@data_list, $options );
2480
2481     $fh = write_stream( $options->{ "data_out" } );
2482
2483     print $fh "$_\n" foreach @{ $result };
2484
2485     close $fh;
2486 }
2487
2488
2489 sub script_plot_karyogram
2490 {
2491     # Martin A. Hansen, August 2007.
2492
2493     # Plot hits on karyogram.
2494
2495     my ( $in,        # handle to in stream
2496          $out,       # handle to out stream
2497          $options,   # options hash
2498        ) = @_;
2499
2500     # Returns nothing.
2501
2502     my ( %options, $record, @data, $fh, $result, %data_hash );
2503
2504     $options->{ "genome" }     ||= "human";
2505     $options->{ "feat_color" } ||= "black";
2506
2507     while ( $record = Maasha::Biopieces::get_record( $in ) ) 
2508     {
2509         if ( $record->{ "CHR" } and $record->{ "CHR_BEG" } and $record->{ "CHR_END" } )
2510         {
2511             push @{ $data_hash{ $record->{ "CHR" } } }, [ $record->{ "CHR_BEG" }, $record->{ "CHR_END" }, $options->{ "feat_color" } ];
2512         }
2513
2514         Maasha::Biopieces::put_record( $record, $out ) if not $options->{ "no_stream" };
2515     }
2516
2517     $result = Maasha::Plot::karyogram( \%data_hash, \%options );
2518
2519     $fh = write_stream( $options->{ "data_out" } );
2520
2521     print $fh $result;
2522
2523     close $fh;
2524 }
2525
2526
2527 sub script_plot_matches
2528 {
2529     # Martin A. Hansen, August 2007.
2530
2531     # Plot matches in 2D generating a dotplot.
2532
2533     my ( $in,        # handle to in stream
2534          $out,       # handle to out stream
2535          $options,   # options hash
2536        ) = @_;
2537
2538     # Returns nothing.
2539
2540     my ( $record, @data, $fh, $result, %data_hash );
2541
2542     $options->{ "direction" } ||= "both";
2543
2544     while ( $record = Maasha::Biopieces::get_record( $in ) ) 
2545     {
2546         if ( defined $record->{ "Q_BEG" } and defined $record->{ "S_BEG" } and $record->{ "Q_END" } and $record->{ "S_END" } ) {
2547             push @data, $record;
2548         }
2549
2550         Maasha::Biopieces::put_record( $record, $out ) if not $options->{ "no_stream" };
2551     }
2552
2553     $options->{ "title" }  ||= "plot_matches";
2554     $options->{ "xlabel" } ||= $data[ 0 ]->{ "Q_ID" };
2555     $options->{ "ylabel" } ||= $data[ 0 ]->{ "S_ID" };
2556
2557     $result = Maasha::Plot::dotplot_matches( \@data, $options, $BP_TMP );
2558
2559     $fh = write_stream( $options->{ "data_out" } );
2560
2561     print $fh "$_\n" foreach @{ $result };
2562
2563     close $fh;
2564 }
2565
2566
2567 sub script_upload_to_ucsc
2568 {
2569     # Martin A. Hansen, August 2007.
2570
2571     # Calculate the mean of values of given keys.
2572
2573     # This routine has developed into the most ugly hack. Do something!
2574
2575     my ( $in,        # handle to in stream
2576          $out,       # handle to out stream
2577          $options,   # options hash
2578        ) = @_;
2579
2580     # Returns nothing.
2581
2582     my ( $record, $file, $wib_file, $wig_file, $wib_dir, $fh_out, $i, $first, $format, $type, $columns, $append, $entry );
2583
2584     $options->{ "short_label" } ||= $options->{ 'table' };
2585     $options->{ "long_label" }  ||= $options->{ 'table' };
2586     $options->{ "group" }       ||= $ENV{ "LOGNAME" };
2587     $options->{ "priority" }    ||= 1;
2588     $options->{ "visibility" }  ||= "pack";
2589     $options->{ "color" }       ||= join( ",", int( rand( 255 ) ), int( rand( 255 ) ), int( rand( 255 ) ) );
2590     $options->{ "chunk_size" }  ||= 10_000_000_000;    # Due to 32-bit UCSC compilation really large tables cannot be loaded in one go.
2591
2592     $file   = "$BP_TMP/ucsc_upload.tmp";
2593     $append = 0;
2594     $first  = 1;
2595     $i      = 0;
2596
2597     $fh_out = Maasha::Common::write_open( $file );
2598
2599     while ( $record = Maasha::Biopieces::get_record( $in ) ) 
2600     {
2601         Maasha::Biopieces::put_record( $record, $out ) if not $options->{ "no_stream" };
2602
2603         if ( $record->{ "REC_TYPE" } eq "fixed_step" )
2604         {
2605             $format = "WIGGLE";
2606
2607             if ( $entry = Maasha::UCSC::Wiggle::biopiece2fixedstep( $record ) ) {
2608                 Maasha::UCSC::Wiggle::fixedstep_entry_put( $entry, $fh_out );
2609             }
2610         }
2611         elsif ( $record->{ "REC_TYPE" } eq "PSL" )
2612         {
2613             $format = "PSL";
2614
2615             Maasha::UCSC::psl_put_header( $fh_out ) if $first;
2616             Maasha::UCSC::psl_put_entry( $record, $fh_out );
2617             
2618             $first = 0;
2619         }
2620         elsif ( $record->{ "REC_TYPE" } eq "BED" and $record->{ "SEC_STRUCT" } )
2621         {
2622             # chrom chromStart  chromEnd    name    score   strand  size    secStr  conf 
2623
2624             $format  = "BED_SS";
2625
2626             print $fh_out join ( "\t",
2627                 $record->{ "CHR" },
2628                 $record->{ "CHR_BEG" },
2629                 $record->{ "CHR_END" } + 1,
2630                 $record->{ "Q_ID" },
2631                 $record->{ "SCORE" },
2632                 $record->{ "STRAND" },
2633                 $record->{ "SIZE" },
2634                 $record->{ "SEC_STRUCT" },
2635                 $record->{ "CONF" },
2636             ), "\n";
2637         }
2638         elsif ( $record->{ "REC_TYPE" } eq "BED" )
2639         {
2640             $format  = "BED";
2641             $columns = $record->{ "BED_COLS" };
2642
2643             if ( $entry = Maasha::UCSC::BED::biopiece2bed( $record, $columns ) ) {
2644                 Maasha::UCSC::BED::bed_entry_put( $entry, $fh_out, $columns, $options->{ 'check' } );
2645             }
2646         }
2647         elsif ( $record->{ "REC_TYPE" } eq "PATSCAN" and $record->{ "CHR" } )
2648         {
2649             $format  = "BED";
2650             $columns = 6;
2651
2652             if ( $entry = Maasha::UCSC::BED::biopiece2bed( $record, $columns ) ) {
2653                 Maasha::UCSC::BED::bed_entry_put( $entry, $fh_out, $columns, $options->{ 'check' } );
2654             }
2655         }
2656         elsif ( $record->{ "REC_TYPE" } eq "BLAST" and $record->{ "S_ID" } =~ /^chr/ )
2657         {
2658             $format  = "BED";
2659             $columns = 6;
2660
2661             $record->{ "SCORE" } = $record->{ "BIT_SCORE" } * 1000;
2662
2663             if ( $entry = Maasha::UCSC::BED::biopiece2bed( $record, $columns ) ) {
2664                 Maasha::UCSC::BED::bed_entry_put( $entry, $fh_out, $columns, $options->{ 'check' } );
2665             }
2666         }
2667         elsif ( $record->{ "REC_TYPE" } eq "VMATCH" and $record->{ "S_ID" } =~ /^chr/i )
2668         {
2669             $format  = "BED";
2670             $columns = 6;
2671
2672             if ( $entry = Maasha::UCSC::BED::biopiece2bed( $record, $columns ) ) {
2673                 Maasha::UCSC::BED::bed_entry_put( $entry, $fh_out, $columns, $options->{ 'check' } );
2674             }
2675         }
2676
2677         if ( $i == $options->{ "chunk_size" } )
2678         {
2679             close $fh_out;
2680
2681             if ( $format eq "BED" ) {
2682                 Maasha::UCSC::bed_upload_to_ucsc( $BP_TMP, $file, $options, $append );
2683             } elsif ( $format eq "PSL" ) {
2684                 Maasha::UCSC::psl_upload_to_ucsc( $file, $options, $append ); 
2685             }
2686
2687             unlink $file;
2688
2689             $first = 1;
2690
2691             $append = 1;
2692
2693             $fh_out = Maasha::Common::write_open( $file );
2694         }
2695
2696         $i++;
2697     }
2698
2699     close $fh_out;
2700
2701     if ( exists $options->{ "database" } and $options->{ "table" } )
2702     {
2703         if ( $format eq "BED" )
2704         {
2705             $type = "bed $columns";
2706
2707             Maasha::UCSC::bed_upload_to_ucsc( $BP_TMP, $file, $options, $append );
2708         }
2709         elsif ( $format eq "BED_SS" )
2710         {
2711             $type = "type bed 6 +";
2712         
2713             Maasha::UCSC::bed_upload_to_ucsc( $BP_TMP, $file, $options, $append );
2714         }
2715         elsif ( $format eq "PSL" )
2716         {
2717             $type = "psl";
2718
2719             Maasha::UCSC::psl_upload_to_ucsc( $file, $options, $append ); 
2720         }
2721         elsif ( $format eq "WIGGLE" )
2722         {
2723             $options->{ "visibility" } = "full";
2724
2725             $wig_file = "$options->{ 'table' }.wig";
2726             $wib_file = "$options->{ 'table' }.wib";
2727
2728             $wib_dir  = "$ENV{ 'HOME' }/ucsc/wib";
2729
2730             Maasha::Common::dir_create_if_not_exists( $wib_dir );
2731
2732             if ( $options->{ 'verbose' } ) {
2733                 `cd $BP_TMP && wigEncode $file $wig_file $wib_file`;
2734             } else {
2735                 `cd $BP_TMP && wigEncode $file $wig_file $wib_file > /dev/null 2>&1`;
2736             }
2737
2738             Maasha::Common::run( "mv", "$BP_TMP/$wib_file $wib_dir" );
2739
2740             unlink $file;
2741
2742             $file = $wig_file;
2743
2744             $type = "wig 0";
2745
2746             Maasha::UCSC::wiggle_upload_to_ucsc( $BP_TMP, $wib_dir, $file, $options );
2747         }
2748
2749         unlink $file;
2750
2751         Maasha::UCSC::ucsc_update_config( $options, $type );
2752     }
2753 }
2754
2755
2756 # >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>><<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
2757
2758 1;
2759
2760 __END__
2761