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