]> git.donarmstrong.com Git - biopieces.git/blob - code_perl/Maasha/BioRun.pm
migrated count_records
[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 "length_seq" )               { script_length_seq(                $in, $out, $options ) }
134     elsif ( $script eq "uppercase_seq" )            { script_uppercase_seq(             $in, $out, $options ) }
135     elsif ( $script eq "complexity_seq" )           { script_complexity_seq(            $in, $out, $options ) }
136     elsif ( $script eq "oligo_freq" )               { script_oligo_freq(                $in, $out, $options ) }
137     elsif ( $script eq "create_weight_matrix" )     { script_create_weight_matrix(      $in, $out, $options ) }
138     elsif ( $script eq "remove_indels" )            { script_remove_indels(             $in, $out, $options ) }
139     elsif ( $script eq "transliterate_seq" )        { script_transliterate_seq(         $in, $out, $options ) }
140     elsif ( $script eq "transliterate_vals" )       { script_transliterate_vals(        $in, $out, $options ) }
141     elsif ( $script eq "translate_seq" )            { script_translate_seq(             $in, $out, $options ) }
142     elsif ( $script eq "get_genome_align" )         { script_get_genome_align(          $in, $out, $options ) }
143     elsif ( $script eq "get_genome_phastcons" )     { script_get_genome_phastcons(      $in, $out, $options ) }
144     elsif ( $script eq "fold_seq" )                 { script_fold_seq(                  $in, $out, $options ) }
145     elsif ( $script eq "tile_seq" )                 { script_tile_seq(                  $in, $out, $options ) }
146     elsif ( $script eq "invert_align" )             { script_invert_align(              $in, $out, $options ) }
147     elsif ( $script eq "patscan_seq" )              { script_patscan_seq(               $in, $out, $options ) }
148     elsif ( $script eq "soap_seq" )                 { script_soap_seq(                  $in, $out, $options ) }
149     elsif ( $script eq "match_seq" )                { script_match_seq(                 $in, $out, $options ) }
150     elsif ( $script eq "create_vmatch_index" )      { script_create_vmatch_index(       $in, $out, $options ) }
151     elsif ( $script eq "write_bed" )                { script_write_bed(                 $in, $out, $options ) }
152     elsif ( $script eq "write_psl" )                { script_write_psl(                 $in, $out, $options ) }
153     elsif ( $script eq "write_fixedstep" )          { script_write_fixedstep(           $in, $out, $options ) }
154     elsif ( $script eq "write_2bit" )               { script_write_2bit(                $in, $out, $options ) }
155     elsif ( $script eq "write_solid" )              { script_write_solid(               $in, $out, $options ) }
156     elsif ( $script eq "write_ucsc_config" )        { script_write_ucsc_config(         $in, $out, $options ) }
157     elsif ( $script eq "head_records" )             { script_head_records(              $in, $out, $options ) }
158     elsif ( $script eq "remove_keys" )              { script_remove_keys(               $in, $out, $options ) }
159     elsif ( $script eq "remove_adaptor" )           { script_remove_adaptor(            $in, $out, $options ) }
160     elsif ( $script eq "remove_mysql_tables" )      { script_remove_mysql_tables(       $in, $out, $options ) }
161     elsif ( $script eq "remove_ucsc_tracks" )       { script_remove_ucsc_tracks(        $in, $out, $options ) }
162     elsif ( $script eq "rename_keys" )              { script_rename_keys(               $in, $out, $options ) }
163     elsif ( $script eq "uniq_vals" )                { script_uniq_vals(                 $in, $out, $options ) }
164     elsif ( $script eq "merge_vals" )               { script_merge_vals(                $in, $out, $options ) }
165     elsif ( $script eq "merge_records" )            { script_merge_records(             $in, $out, $options ) }
166     elsif ( $script eq "compute" )                  { script_compute(                   $in, $out, $options ) }
167     elsif ( $script eq "flip_tab" )                 { script_flip_tab(                  $in, $out, $options ) }
168     elsif ( $script eq "sort_records" )             { script_sort_records(              $in, $out, $options ) }
169     elsif ( $script eq "count_vals" )               { script_count_vals(                $in, $out, $options ) }
170     elsif ( $script eq "plot_histogram" )           { script_plot_histogram(            $in, $out, $options ) }
171     elsif ( $script eq "plot_lendist" )             { script_plot_lendist(              $in, $out, $options ) }
172     elsif ( $script eq "plot_chrdist" )             { script_plot_chrdist(              $in, $out, $options ) }
173     elsif ( $script eq "plot_karyogram" )           { script_plot_karyogram(            $in, $out, $options ) }
174     elsif ( $script eq "plot_matches" )             { script_plot_matches(              $in, $out, $options ) }
175     elsif ( $script eq "plot_seqlogo" )             { script_plot_seqlogo(              $in, $out, $options ) }
176     elsif ( $script eq "plot_phastcons_profiles" )  { script_plot_phastcons_profiles(   $in, $out, $options ) }
177     elsif ( $script eq "length_vals" )              { script_length_vals(               $in, $out, $options ) }
178     elsif ( $script eq "sum_vals" )                 { script_sum_vals(                  $in, $out, $options ) }
179     elsif ( $script eq "mean_vals" )                { script_mean_vals(                 $in, $out, $options ) }
180     elsif ( $script eq "median_vals" )              { script_median_vals(               $in, $out, $options ) }
181     elsif ( $script eq "max_vals" )                 { script_max_vals(                  $in, $out, $options ) }
182     elsif ( $script eq "min_vals" )                 { script_min_vals(                  $in, $out, $options ) }
183     elsif ( $script eq "upload_to_ucsc" )           { script_upload_to_ucsc(            $in, $out, $options ) }
184
185     close $in if defined $in;
186     close $out;
187
188     $t1 = gettimeofday();
189
190     print STDERR "Program: $script" . ( " " x ( 25 - length( $script ) ) ) . sprintf( "Run time: %.4f\n", ( $t1 - $t0 ) ) if $options->{ 'verbose' };
191 }
192
193
194 sub get_options
195 {
196     # Martin A. Hansen, February 2008.
197
198     # Gets options from commandline and checks these vigerously.
199
200     my ( $script,     # name of script
201        ) = @_;
202
203     # Returns hash
204
205     my ( %options, @options, $opt, @genomes, $real );
206
207     if ( $script eq "print_usage" )
208     {
209         @options = qw(
210             data_in|i=s
211         );
212     }
213     elsif ( $script eq "read_psl" )
214     {
215         @options = qw(
216             data_in|i=s
217             num|n=s
218         );
219     }
220     elsif ( $script eq "read_bed" )
221     {
222         @options = qw(
223             data_in|i=s
224             cols|c=s
225             num|n=s
226             check|C
227         );
228     }
229     elsif ( $script eq "read_fixedstep" )
230     {
231         @options = qw(
232             data_in|i=s
233             num|n=s
234         );
235     }
236     elsif ( $script eq "read_blast_tab" )
237     {
238         @options = qw(
239             data_in|i=s
240             num|n=s
241         );
242     }
243     elsif ( $script eq "read_embl" )
244     {
245         @options = qw(
246             data_in|i=s
247             num|n=s
248             keys|k=s
249             feats|f=s
250             quals|q=s
251         );
252     }
253     elsif ( $script eq "read_stockholm" )
254     {
255         @options = qw(
256             data_in|i=s
257             num|n=s
258         );
259     }
260     elsif ( $script eq "read_phastcons" )
261     {
262         @options = qw(
263             data_in|i=s
264             num|n=s
265             min|m=s
266             dist|d=s
267             threshold|t=f
268             gap|g=s
269         );
270     }
271     elsif ( $script eq "read_soft" )
272     {
273         @options = qw(
274             data_in|i=s
275             samples|s=s
276             num|n=s
277         );
278     }
279     elsif ( $script eq "read_gff" )
280     {
281         @options = qw(
282             data_in|i=s
283             num|n=s
284         );
285     }
286     elsif ( $script eq "read_2bit" )
287     {
288         @options = qw(
289             data_in|i=s
290             num|n=s
291             no_mask|N
292         );
293     }
294     elsif ( $script eq "read_solexa" )
295     {
296         @options = qw(
297             data_in|i=s
298             num|n=s
299             format|f=s
300             quality|q=s
301         );
302     }
303     elsif ( $script eq "read_solid" )
304     {
305         @options = qw(
306             data_in|i=s
307             num|n=s
308             quality|q=s
309         );
310     }
311     elsif ( $script eq "read_mysql" )
312     {
313         @options = qw(
314             database|d=s
315             query|q=s
316             user|u=s
317             password|p=s
318         );
319     }
320     elsif ( $script eq "read_ucsc_config" )
321     {
322         @options = qw(
323             data_in|i=s
324             num|n=s
325         );
326     }
327     elsif ( $script eq "length_seq" )
328     {
329         @options = qw(
330             no_stream|x
331             data_out|o=s
332         );
333     }
334     elsif ( $script eq "oligo_freq" )
335     {
336         @options = qw(
337             word_size|w=s
338             all|a
339         );
340     }
341     elsif ( $script eq "create_weight_matrix" )
342     {
343         @options = qw(
344             percent|p
345         );
346     }
347     elsif ( $script eq "transliterate_seq" )
348     {
349         @options = qw(
350             search|s=s
351             replace|r=s
352             delete|d=s
353         );
354     }
355     elsif ( $script eq "transliterate_vals" )
356     {
357         @options = qw(
358             keys|k=s
359             search|s=s
360             replace|r=s
361             delete|d=s
362         );
363     }
364     elsif ( $script eq "translate_seq" )
365     {
366         @options = qw(
367             frames|f=s
368         );
369     }
370     elsif ( $script eq "get_genome_align" )
371     {
372         @options = qw(
373             genome|g=s
374             chr|c=s
375             beg|b=s
376             end|e=s
377             len|l=s
378             strand|s=s
379         );
380     }
381     elsif ( $script eq "get_genome_phastcons" )
382     {
383         @options = qw(
384             genome|g=s
385             chr|c=s
386             beg|b=s
387             end|e=s
388             len|l=s
389             flank|f=s
390         );
391     }
392     elsif ( $script eq "tile_seq" )
393     {
394         @options = qw(
395             identity|i=s
396             supress_indels|s
397         );
398     }
399     elsif ( $script eq "invert_align" )
400     {
401         @options = qw(
402             soft|s
403         );
404     }
405     elsif ( $script eq "patscan_seq" )
406     {
407         @options = qw(
408             patterns|p=s
409             patterns_in|P=s
410             comp|c
411             max_hits|h=s
412             max_misses|m=s
413             genome|g=s
414         );
415     }
416     elsif ( $script eq "soap_seq" )
417     {
418         @options = qw(
419             in_file|i=s
420             genome|g=s
421             seed_size|s=s
422             mismatches|m=s
423             gap_size|G=s
424             cpus|c=s
425         );
426     }
427     elsif ( $script eq "match_seq" )
428     {
429         @options = qw(
430             word_size|w=s
431             direction|d=s
432         );
433     }
434     elsif ( $script eq "create_vmatch_index" )
435     {
436         @options = qw(
437             index_name|i=s
438             prefix_length|p=s
439             no_stream|x
440         );
441     }
442     elsif ( $script eq "write_bed" )
443     {
444         @options = qw(
445             cols|c=s
446             check|C
447             no_stream|x
448             data_out|o=s
449             compress|Z
450         );
451     }
452     elsif ( $script eq "write_psl" )
453     {
454         @options = qw(
455             no_stream|x
456             data_out|o=s
457             compress|Z
458         );
459     }
460     elsif ( $script eq "write_fixedstep" )
461     {
462         @options = qw(
463             no_stream|x
464             data_out|o=s
465             compress|Z
466         );
467     }
468     elsif ( $script eq "write_2bit" )
469     {
470         @options = qw(
471             no_stream|x
472             data_out|o=s
473             no_mask|N
474         );
475     }
476     elsif ( $script eq "write_solid" )
477     {
478         @options = qw(
479             wrap|w=s
480             no_stream|x
481             data_out|o=s
482             compress|Z
483         );
484     }
485     elsif ( $script eq "write_ucsc_config" )
486     {
487         @options = qw(
488             no_stream|x
489             data_out|o=s
490         );
491     }
492     elsif ( $script eq "plot_seqlogo" )
493     {
494         @options = qw(
495             no_stream|x
496             data_out|o=s
497         );
498     }
499     elsif ( $script eq "plot_phastcons_profiles" )
500     {
501         @options = qw(
502             no_stream|x
503             data_out|o=s
504             genome|g=s
505             mean|m
506             median|M
507             flank|f=s
508             terminal|t=s
509             title|T=s
510             xlabel|X=s
511             ylabel|Y=s
512         );
513     }
514     elsif ( $script eq "head_records" )
515     {
516         @options = qw(
517             num|n=s
518         );
519     }
520     elsif ( $script eq "remove_keys" )
521     {
522         @options = qw(
523             keys|k=s
524             save_keys|K=s
525         );
526     }
527     elsif ( $script eq "remove_adaptor" )
528     {
529         @options = qw(
530             adaptor|a=s
531             mismatches|m=s
532             remove|r=s
533             offset|o=s
534         );
535     }
536     elsif ( $script eq "remove_mysql_tables" )
537     {
538         @options = qw(
539             database|d=s
540             tables|t=s
541             keys|k=s
542             user|u=s
543             password|p=s
544             no_stream|x
545         );
546     }
547     elsif ( $script eq "remove_ucsc_tracks" )
548     {
549         @options = qw(
550             database|d=s
551             tracks|t=s
552             keys|k=s
553             config_file|c=s
554             user|u=s
555             password|p=s
556             no_stream|x
557         );
558     }
559     elsif ( $script eq "rename_keys" )
560     {
561         @options = qw(
562             keys|k=s
563         );
564     }
565     elsif ( $script eq "uniq_vals" )
566     {
567         @options = qw(
568             key|k=s
569             invert|i
570         );
571     }
572     elsif ( $script eq "merge_vals" )
573     {
574         @options = qw(
575             keys|k=s
576             delimit|d=s
577         );
578     }
579     elsif ( $script eq "merge_records" )
580     {
581         @options = qw(
582             keys|k=s
583             merge|m=s
584         );
585     }
586     elsif ( $script eq "compute" )
587     {
588         @options = qw(
589             eval|e=s
590         );
591     }
592     elsif ( $script eq "sort_records" )
593     {
594         @options = qw(
595             reverse|r
596             keys|k=s
597         );
598     }
599     elsif ( $script eq "count_vals" )
600     {
601         @options = qw(
602             keys|k=s
603         );
604     }
605     elsif ( $script eq "plot_histogram" )
606     {
607         @options = qw(
608             no_stream|x
609             data_out|o=s
610             terminal|t=s
611             title|T=s
612             xlabel|X=s
613             ylabel|Y=s
614             key|k=s
615             sort|s=s
616         );
617     }
618     elsif ( $script eq "plot_lendist" )
619     {
620         @options = qw(
621             no_stream|x
622             data_out|o=s
623             terminal|t=s
624             title|T=s
625             xlabel|X=s
626             ylabel|Y=s
627             key|k=s
628         );
629     }
630     elsif ( $script eq "plot_chrdist" )
631     {
632         @options = qw(
633             no_stream|x
634             data_out|o=s
635             terminal|t=s
636             title|T=s
637             xlabel|X=s
638             ylabel|Y=s
639         );
640     }
641     elsif ( $script eq "plot_karyogram" )
642     {
643         @options = qw(
644             no_stream|x
645             data_out|o=s
646             genome|g=s
647             feat_color|f=s
648         );
649     }
650     elsif ( $script eq "plot_matches" )
651     {
652         @options = qw(
653             no_stream|x
654             data_out|o=s
655             terminal|t=s
656             title|T=s
657             xlabel|X=s
658             ylabel|Y=s
659             direction|d=s
660         );
661     }
662     elsif ( $script eq "length_vals" )
663     {
664         @options = qw(
665             keys|k=s
666         );
667     }
668     elsif ( $script eq "sum_vals" )
669     {
670         @options = qw(
671             no_stream|x
672             data_out|o=s
673             keys|k=s
674         );
675     }
676     elsif ( $script eq "mean_vals" )
677     {
678         @options = qw(
679             no_stream|x
680             data_out|o=s
681             keys|k=s
682         );
683     }
684     elsif ( $script eq "median_vals" )
685     {
686         @options = qw(
687             no_stream|x
688             data_out|o=s
689             keys|k=s
690         );
691     }
692     elsif ( $script eq "max_vals" )
693     {
694         @options = qw(
695             no_stream|x
696             data_out|o=s
697             keys|k=s
698         );
699     }
700     elsif ( $script eq "min_vals" )
701     {
702         @options = qw(
703             no_stream|x
704             data_out|o=s
705             keys|k=s
706         );
707     }
708     elsif ( $script eq "upload_to_ucsc" )
709     {
710         @options = qw(
711             no_stream|x
712             database|d=s
713             table|t=s
714             short_label|s=s
715             long_label|l=s
716             group|g=s
717             priority|p=f
718             use_score|u
719             visibility|V=s
720             color|c=s
721             check|C
722         );
723     }
724
725     push @options, qw(
726         stream_in|I=s
727         stream_out|O=s
728         verbose|v
729         help|?
730     );
731
732 #    print STDERR Dumper( \@options );
733     
734     GetOptions(
735         \%options,
736         @options,
737     );
738
739 #    print STDERR Dumper( \%options );
740
741     if ( -t STDIN && scalar( keys %options ) == 0 or $options{ "help" } ) {
742         return wantarray ? %options : \%options;
743     }
744
745     $options{ "cols" }      = [ split ",", $options{ "cols" } ]      if defined $options{ "cols" };
746     $options{ "keys" }      = [ split ",", $options{ "keys" } ]      if defined $options{ "keys" };
747     $options{ "no_keys" }   = [ split ",", $options{ "no_keys" } ]   if defined $options{ "no_keys" };
748     $options{ "save_keys" } = [ split ",", $options{ "save_keys" } ] if defined $options{ "save_keys" };
749     $options{ "quals" }     = [ split ",", $options{ "quals" } ]     if defined $options{ "quals" };
750     $options{ "feats" }     = [ split ",", $options{ "feats" } ]     if defined $options{ "feats" };
751     $options{ "frames" }    = [ split ",", $options{ "frames" } ]    if defined $options{ "frames" };
752     $options{ "samples" }   = [ split ",", $options{ "samples" } ]   if defined $options{ "samples" };
753     $options{ "tables" }    = [ split ",", $options{ "tables" } ]    if defined $options{ "tables" };
754     $options{ "tracks" }    = [ split ",", $options{ "tracks" } ]    if defined $options{ "tracks" };
755     
756     # ---- check arguments ----
757
758     if ( $options{ 'data_in' } )
759     {
760         $options{ "files" } = Maasha::Biopieces::getopt_files( $options{ 'data_in' } );
761
762         Maasha::Common::error( qq(Argument to --data_in must be a valid file or fileglob expression) ) if scalar @{ $options{ "files" } } == 0;
763     }
764
765     map { Maasha::Common::error( qq(Argument to --cols must be a whole numbers - not "$_") ) if $_ !~ /^\d+$/ } @{ $options{ "cols" } } if $options{ "cols" };
766
767     # print STDERR Dumper( \%options );
768
769     $real = "beg|end|word_size|wrap|tile_size|len|prefix_length|mismatches|offset|num|skip|cpus|window_size|step_size";
770
771     foreach $opt ( keys %options )
772     {
773         if ( $opt =~ /stream_in|pattern_in|exact_in/ and not -f $options{ $opt } )
774         {
775             Maasha::Common::error( qq(Argument to --$opt must be a valid file or fileglob expression - not "$options{ $opt }") );
776         }
777         elsif ( $opt =~ /$real/ and $options{ $opt } !~ /^\d+$/ )
778         {
779             Maasha::Common::error( qq(Argument to --$opt must be a whole number - not "$options{ $opt }") );
780         }
781         elsif ( $opt =~ /max_hits|max_hits|max_misses|dist|edit_dist|flank|gap|hamming_dist|priority/ and $options{ $opt } !~ /^-?\d+$/ )
782         {
783             Maasha::Common::error( qq(Argument to --$opt must be an integer - not "$options{ $opt }") );
784         }
785         elsif ( $opt =~ /identity|threshold/ and $options{ $opt } !~ /^-?(?:\d+(?:\.\d*)?|\.\d+)$/ )
786         {
787             Maasha::Common::error( qq(Argument to --$opt must be a decimal number - not "$options{ $opt }") );
788         }
789         elsif ( $opt =~ /e_val/ and $options{ $opt } !~ /^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$/ )
790         {
791             Maasha::Common::error( qq(Argument to --$opt must be a float - not "$options{ $opt }") );
792         }
793         elsif ( $opt =~ /strand/ and $options{ $opt } !~ /^(\+|-)$/ )
794         {
795             Maasha::Common::error( qq(Argument to --$opt must be "+" or "-" - not "$options{ $opt }") );
796         }
797         elsif ( $opt eq "genome" )
798         {
799             @genomes = Maasha::Common::ls_dirs( "$ENV{ 'BP_DATA' }/genomes" );
800             map { $_ =~ s/.*\/(.+)$/$1/ } @genomes;
801
802             if ( not grep { $_ =~ /^$options{ $opt }$/ } @genomes ) {
803                 Maasha::Common::error( qq(Genome $options{ $opt } not found in "$ENV{ 'BP_DATA' }/genomes/") );
804             }
805         }
806         elsif ( $opt eq "terminal" and not $options{ $opt } =~ /^(svg|post|dumb|x11)/ )
807         {
808             Maasha::Common::error( qq(Bad --$opt argument "$options{ $opt }") );
809         }
810         elsif ( $opt eq "table" and $options{ $opt } =~ /(-|\.)/ )
811         {
812             Maasha::Common::error( qq(Character '$1' is not allowed in table name: $options{ $opt }) );
813         }
814         elsif ( $opt eq "merge" and $options{ $opt } !~ /^(AandB|AorB|BorA|AnotB|BnotA)$/ )
815         {
816             Maasha::Common::error( qq(Argument to --$opt must be AandB, AorB, BorA, AnotB, or BnotA - not "$options{ $opt }") );
817         }
818         elsif ( $opt eq "format" and $script eq "read_solexa" and $options{ $opt } !~ /octal|decimal/ )
819         {
820             Maasha::Common::error( qq(Argument to --$opt must be octal or decimal - not "$options{ $opt }") );
821         }
822         elsif ( $opt eq "remove" and $script eq "remove_adaptor" and $options{ $opt } !~ /before|after|skip/ )
823         {
824             Maasha::Common::error( qq(Argument to --$opt must be before, after, or skip - not "$options{ $opt }") );
825         }
826     }
827
828     Maasha::Common::error( qq(no --database specified) )                if $script eq "remove_ucsc_tracks"  and not $options{ "database" };
829     Maasha::Common::error( qq(no --index_name specified) )              if $script =~ /create_vmatch_index/ and not $options{ "index_name" };
830     Maasha::Common::error( qq(no --in_file or --genome specified) )     if $script eq "soap_seq" and not $options{ "genome" } and not $options{ "in_file" };
831     Maasha::Common::error( qq(both --in_file and --genome specified) )  if $script eq "soap_seq" and $options{ "genome" } and $options{ "in_file" };
832     Maasha::Common::error( qq(no --genome specified) )                  if $script =~ /get_genome_align|get_genome_phastcons|plot_phastcons_profiles|plot_karyogram/ and not $options{ "genome" };
833     Maasha::Common::error( qq(no --key specified) )                     if $script =~ /plot_lendist|plot_histogram/ and not $options{ "key" };
834     Maasha::Common::error( qq(no --keys speficied) )                    if $script =~ /sort_records|count_vals|sum_vals|mean_vals|median_vals|length_vals/ and not $options{ "keys" };
835
836     if ( $script eq "upload_to_ucsc" )
837     {
838         Maasha::Common::error( qq(no --database specified) ) if not $options{ "database" };
839         Maasha::Common::error( qq(no --table specified) )    if not $options{ "table" };
840     }
841
842     return wantarray ? %options : \%options;
843 }
844
845
846 # >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> SCRIPTS  <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
847
848
849 sub script_print_usage
850 {
851     # Martin A. Hansen, January 2008.
852
853     # Retrieves usage information from file and
854     # prints this nicely formatted.
855
856     my ( $in,        # handle to in stream
857          $out,       # handle to out stream
858          $options,   # options hash
859        ) = @_;
860
861     # Returns nothing.
862
863     my ( $file, $wiki, $lines );
864
865     if ( $options->{ 'data_in' } ) {
866         $file = $options->{ 'data_in' };
867     } else {
868         $file = join "", $ENV{ 'BP_DIR' }, "/bp_usage/", $options->{ 'SCRIPT' }, ".wiki";
869     }
870
871     $wiki = Maasha::Gwiki::gwiki_read( $file );
872
873     ( $wiki->[ 2 ], $wiki->[ 3 ], $wiki->[ 0 ], $wiki->[ 1 ] ) = ( $wiki->[ 0 ], $wiki->[ 1 ], $wiki->[ 2 ], $wiki->[ 3 ] );
874
875     if ( not $options->{ "help" } ) {
876         @{ $wiki } = grep { $_->[ 0 ]->{ 'SECTION' } =~ /Biopiece|summary|Usage|Options|Help/ } @{ $wiki };
877     }
878
879     $lines = Maasha::Gwiki::gwiki2ascii( $wiki );
880
881     print STDERR "$_\n" foreach @{ $lines };
882
883     exit;
884 }
885
886
887 sub script_read_psl
888 {
889     # Martin A. Hansen, August 2007.
890
891     # Read psl table from stream or file.
892
893     my ( $in,        # handle to in stream
894          $out,       # handle to out stream
895          $options,   # options hash
896        ) = @_;
897
898     # Returns nothing.
899
900     my ( $record, $file, $data_in, $num );
901
902     while ( $record = Maasha::Biopieces::get_record( $in ) ) {
903         Maasha::Biopieces::put_record( $record, $out );
904     }
905
906     $num = 1;
907
908     foreach $file ( @{ $options->{ "files" } } )
909     {
910         $data_in = Maasha::Common::read_open( $file );
911
912         while ( $record = Maasha::UCSC::psl_get_entry( $data_in ) ) 
913         {
914             Maasha::Biopieces::put_record( $record, $out );
915
916             goto NUM if $options->{ "num" } and $num == $options->{ "num" };
917
918             $num++;
919         }
920     }
921
922     NUM:
923 }
924
925
926 sub script_read_bed
927 {
928     # Martin A. Hansen, August 2007.
929
930     # Read bed table from stream or file.
931
932     my ( $in,        # handle to in stream
933          $out,       # handle to out stream
934          $options,   # options hash
935        ) = @_;
936
937     # Returns nothing.
938
939     my ( $cols, $file, $record, $bed_entry, $data_in, $num );
940
941     $cols = $options->{ 'cols' }->[ 0 ];
942
943     while ( $record = Maasha::Biopieces::get_record( $in ) ) {
944         Maasha::Biopieces::put_record( $record, $out );
945     }
946
947     $num = 1;
948
949     foreach $file ( @{ $options->{ "files" } } )
950     {
951         $data_in = Maasha::Common::read_open( $file );
952
953         while ( $bed_entry = Maasha::UCSC::BED::bed_entry_get( $data_in, $cols, $options->{ 'check' } ) )
954         {
955             $record = Maasha::UCSC::BED::bed2biopiece( $bed_entry );
956
957             Maasha::Biopieces::put_record( $record, $out );
958
959             goto NUM if $options->{ "num" } and $num == $options->{ "num" };
960
961             $num++;
962         }
963
964         close $data_in;
965     }
966
967     NUM:
968
969     close $data_in if $data_in;
970 }
971
972
973 sub script_read_fixedstep
974 {
975     # Martin A. Hansen, Juli 2008.
976
977     # Read fixedstep wiggle format from stream or file.
978
979     my ( $in,        # handle to in stream
980          $out,       # handle to out stream
981          $options,   # options hash
982        ) = @_;
983
984     # Returns nothing.
985
986     my ( $file, $record, $entry, $data_in, $num );
987
988     while ( $record = Maasha::Biopieces::get_record( $in ) ) {
989         Maasha::Biopieces::put_record( $record, $out );
990     }
991
992     $num = 1;
993
994     foreach $file ( @{ $options->{ "files" } } )
995     {
996         $data_in = Maasha::Common::read_open( $file );
997
998         while ( $entry = Maasha::UCSC::Wiggle::fixedstep_entry_get( $data_in ) )
999         {
1000             $record = Maasha::UCSC::Wiggle::fixedstep2biopiece( $entry );
1001
1002             Maasha::Biopieces::put_record( $record, $out );
1003
1004             goto NUM if $options->{ "num" } and $num == $options->{ "num" };
1005
1006             $num++;
1007         }
1008
1009         close $data_in;
1010     }
1011
1012     NUM:
1013
1014     close $data_in if $data_in;
1015 }
1016
1017
1018 sub script_read_blast_tab
1019 {
1020     # Martin A. Hansen, September 2007.
1021
1022     # Read tabular BLAST output from NCBI blast run with -m8 or -m9.
1023
1024     my ( $in,        # handle to in stream
1025          $out,       # handle to out stream
1026          $options,   # options hash
1027        ) = @_;
1028
1029     # Returns nothing.
1030
1031     my ( $file, $line, @fields, $strand, $record, $data_in, $num );
1032
1033     while ( $record = Maasha::Biopieces::get_record( $in ) ) {
1034         Maasha::Biopieces::put_record( $record, $out );
1035     }
1036
1037     $num = 1;
1038
1039     foreach $file ( @{ $options->{ "files" } } )
1040     {
1041         $data_in = Maasha::Common::read_open( $file );
1042
1043         while ( $line = <$data_in> )
1044         {
1045             chomp $line;
1046
1047             next if $line =~ /^#/;
1048
1049             @fields = split /\t/, $line;
1050
1051             $record->{ "REC_TYPE" }   = "BLAST";
1052             $record->{ "Q_ID" }       = $fields[ 0 ];
1053             $record->{ "S_ID" }       = $fields[ 1 ];
1054             $record->{ "IDENT" }      = $fields[ 2 ];
1055             $record->{ "ALIGN_LEN" }  = $fields[ 3 ];
1056             $record->{ "MISMATCHES" } = $fields[ 4 ];
1057             $record->{ "GAPS" }       = $fields[ 5 ];
1058             $record->{ "Q_BEG" }      = $fields[ 6 ] - 1; # BLAST is 1-based
1059             $record->{ "Q_END" }      = $fields[ 7 ] - 1; # BLAST is 1-based
1060             $record->{ "S_BEG" }      = $fields[ 8 ] - 1; # BLAST is 1-based
1061             $record->{ "S_END" }      = $fields[ 9 ] - 1; # BLAST is 1-based
1062             $record->{ "E_VAL" }      = $fields[ 10 ];
1063             $record->{ "BIT_SCORE" }  = $fields[ 11 ];
1064
1065             if ( $record->{ "S_BEG" } > $record->{ "S_END" } )
1066             {
1067                 $record->{ "STRAND" } = '-';
1068
1069                 ( $record->{ "S_BEG" }, $record->{ "S_END" } ) = ( $record->{ "S_END" }, $record->{ "S_BEG" } );
1070             }
1071             else
1072             {
1073                 $record->{ "STRAND" } = '+';
1074             }
1075
1076             Maasha::Biopieces::put_record( $record, $out );
1077
1078             goto NUM if $options->{ "num" } and $num == $options->{ "num" };
1079
1080             $num++;
1081         }
1082
1083         close $data_in;
1084     }
1085
1086     NUM:
1087
1088     close $data_in if $data_in;
1089 }
1090
1091
1092 sub script_read_embl
1093 {
1094     # Martin A. Hansen, August 2007.
1095
1096     # Read EMBL format.
1097
1098     my ( $in,        # handle to in stream
1099          $out,       # handle to out stream
1100          $options,   # options hash
1101        ) = @_;
1102
1103     # Returns nothing.
1104
1105     my ( %options2, $file, $data_in, $num, $entry, $record );
1106
1107     map { $options2{ "keys" }{ $_ } = 1 }  @{ $options->{ "keys" } };
1108     map { $options2{ "feats" }{ $_ } = 1 } @{ $options->{ "feats" } };
1109     map { $options2{ "quals" }{ $_ } = 1 } @{ $options->{ "quals" } };
1110
1111     while ( $record = Maasha::Biopieces::get_record( $in ) ) {
1112         Maasha::Biopieces::put_record( $record, $out );
1113     }
1114
1115     $num = 1;
1116
1117     foreach $file ( @{ $options->{ "files" } } )
1118     {
1119         $data_in = Maasha::Common::read_open( $file );
1120
1121         while ( $entry = Maasha::EMBL::get_embl_entry( $data_in ) ) 
1122         {
1123             $record = Maasha::EMBL::parse_embl_entry( $entry, \%options2 );
1124
1125             my ( $feat, $feat2, $qual, $qual_val, $record_copy );
1126
1127             $record_copy = dclone $record;
1128
1129             delete $record_copy->{ "FT" };
1130
1131             Maasha::Biopieces::put_record( $record_copy, $out );
1132
1133             delete $record_copy->{ "SEQ" };
1134
1135             foreach $feat ( keys %{ $record->{ "FT" } } )
1136             {
1137                 $record_copy->{ "FEAT_TYPE" } = $feat;
1138
1139                 foreach $feat2 ( @{ $record->{ "FT" }->{ $feat } } )
1140                 {
1141                     foreach $qual ( keys %{ $feat2 } )
1142                     {
1143                         $qual_val = join "; ", @{ $feat2->{ $qual } };
1144
1145                         $qual =~ s/^_//;
1146                         $qual = uc $qual;
1147
1148                         $record_copy->{ $qual } = $qual_val;
1149                     }
1150
1151                     Maasha::Biopieces::put_record( $record_copy, $out );
1152                 }
1153             }
1154
1155             goto NUM if $options->{ "num" } and $num == $options->{ "num" };
1156
1157             $num++;
1158         }
1159
1160         close $data_in;
1161     }
1162
1163     NUM:
1164
1165     close $data_in if $data_in;
1166 }
1167
1168
1169 sub script_read_stockholm
1170 {
1171     # Martin A. Hansen, August 2007.
1172
1173     # Read Stockholm format.
1174
1175     my ( $in,        # handle to in stream
1176          $out,       # handle to out stream
1177          $options,   # options hash
1178        ) = @_;
1179
1180     # Returns nothing.
1181
1182     my ( $data_in, $file, $num, $entry, $record, $record_anno, $record_align, $key, $seq );
1183
1184     while ( $record = Maasha::Biopieces::get_record( $in ) ) {
1185         Maasha::Biopieces::put_record( $record, $out );
1186     }
1187
1188     $num = 1;
1189
1190     foreach $file ( @{ $options->{ "files" } } )
1191     {
1192         $data_in = Maasha::Common::read_open( $file );
1193
1194         while ( $entry = Maasha::Stockholm::get_stockholm_entry( $data_in ) ) 
1195         {
1196             $record = Maasha::Stockholm::parse_stockholm_entry( $entry );
1197
1198             undef $record_anno;
1199
1200             foreach $key ( keys %{ $record->{ "GF" } } ) {
1201                 $record_anno->{ $key } = $record->{ "GF" }->{ $key };
1202             }
1203
1204             $record_anno->{ "ALIGN" } = $num;
1205
1206             Maasha::Biopieces::put_record( $record_anno, $out );
1207
1208             foreach $seq ( @{ $record->{ "ALIGN" } } )
1209             {
1210                 undef $record_align;
1211             
1212                 $record_align = {
1213                     SEQ_NAME  => $seq->[ 0 ],
1214                     SEQ       => $seq->[ 1 ],
1215                 };
1216             
1217                 Maasha::Biopieces::put_record( $record_align, $out );
1218             }
1219
1220             goto NUM if $options->{ "num" } and $num == $options->{ "num" };
1221
1222             $num++;
1223         }
1224
1225         close $data_in;
1226     }
1227
1228     NUM:
1229
1230     close $data_in if $data_in;
1231 }
1232
1233
1234 sub script_read_phastcons
1235 {
1236     # Martin A. Hansen, December 2007.
1237
1238     # Read PhastCons format.
1239
1240     my ( $in,        # handle to in stream
1241          $out,       # handle to out stream
1242          $options,   # options hash
1243        ) = @_;
1244
1245     # Returns nothing.
1246
1247     my ( $data_in, $file, $num, $entry, @records, $record );
1248
1249     $options->{ "min" }       ||= 10;
1250     $options->{ "dist" }      ||= 25;
1251     $options->{ "threshold" } ||= 0.8;
1252     $options->{ "gap" }       ||= 5;
1253
1254     while ( $record = Maasha::Biopieces::get_record( $in ) ) {
1255         Maasha::Biopieces::put_record( $record, $out );
1256     }
1257
1258     $num = 1;
1259
1260     foreach $file ( @{ $options->{ "files" } } )
1261     {
1262         $data_in = Maasha::Common::read_open( $file );
1263
1264         while ( $entry = Maasha::UCSC::fixedstep_get_entry( $data_in ) ) 
1265         {
1266             @records = Maasha::UCSC::phastcons_parse_entry( $entry, $options );
1267
1268             foreach $record ( @records )
1269             {
1270                 $record->{ "REC_TYPE" } = "BED";
1271                 $record->{ "BED_LEN" }  = $record->{ "CHR_END" } - $record->{ "CHR_BEG" } + 1;
1272
1273                 Maasha::Biopieces::put_record( $record, $out );
1274
1275                 goto NUM if $options->{ "num" } and $num == $options->{ "num" };
1276
1277                 $num++;
1278             }
1279         }
1280
1281         close $data_in;
1282     }
1283
1284     NUM:
1285
1286     close $data_in if $data_in;
1287 }
1288
1289
1290 sub script_read_soft
1291 {
1292     # Martin A. Hansen, December 2007.
1293
1294     # Read soft format.
1295     # http://www.ncbi.nlm.nih.gov/geo/info/soft2.html
1296
1297     my ( $in,        # handle to in stream
1298          $out,       # handle to out stream
1299          $options,   # options hash
1300        ) = @_;
1301
1302     # Returns nothing.
1303
1304     my ( $data_in, $file, $num, $records, $record, $soft_index, $fh, @platforms, $plat_table, @samples, $sample, $old_end, $skip );
1305
1306     while ( $record = Maasha::Biopieces::get_record( $in ) ) {
1307         Maasha::Biopieces::put_record( $record, $out );
1308     }
1309
1310     $num = 1;
1311
1312     foreach $file ( @{ $options->{ "files" } } )
1313     {
1314         print STDERR "Creating index for file: $file\n" if $options->{ "verbose" };
1315
1316         $soft_index = Maasha::NCBI::soft_index_file( $file );
1317
1318         $fh         = Maasha::Common::read_open( $file );
1319
1320         @platforms  = grep { $_->{ "SECTION" } =~ /PLATFORM/ } @{ $soft_index };
1321
1322         print STDERR "Getting platform tables for file: $file\n" if $options->{ "verbose" };
1323
1324         $plat_table = Maasha::NCBI::soft_get_platform( $fh, $platforms[ 0 ]->{ "LINE_BEG" }, $platforms[ -1 ]->{ "LINE_END" } );
1325
1326         @samples    = grep { $_->{ "SECTION" } =~ /SAMPLE/ } @{ $soft_index };
1327
1328         $old_end    = $platforms[ -1 ]->{ "LINE_END" };
1329
1330         foreach $sample ( @samples )
1331         {
1332             $skip = 0;
1333             $skip = 1 if ( $options->{ "samples" } and grep { $sample->{ "SECTION" } !~ /$_/ } @{ $options->{ "samples" } } );
1334
1335             print STDERR "Getting samples for dataset: $sample->{ 'SECTION' }\n" if $options->{ "verbose" } and not $skip;
1336
1337             $records = Maasha::NCBI::soft_get_sample( $fh, $plat_table, $sample->{ "LINE_BEG" } - $old_end - 1, $sample->{ "LINE_END" } - $old_end - 1, $skip );
1338
1339             foreach $record ( @{ $records } )
1340             {
1341                 Maasha::Biopieces::put_record( $record, $out );
1342
1343                 goto NUM if $options->{ "num" } and $num == $options->{ "num" };
1344
1345                 $num++;
1346             }
1347
1348             $old_end = $sample->{ "LINE_END" };
1349         }
1350
1351         close $fh;
1352     }
1353
1354     NUM:
1355
1356     close $data_in if $data_in;
1357     close $fh if $fh;
1358 }
1359
1360
1361 sub script_read_gff
1362 {
1363     # Martin A. Hansen, February 2008.
1364
1365     # Read soft format.
1366     # http://www.ncbi.nlm.nih.gov/geo/info/soft2.html
1367
1368     my ( $in,        # handle to in stream
1369          $out,       # handle to out stream
1370          $options,   # options hash
1371        ) = @_;
1372
1373     # Returns nothing.
1374
1375     my ( $data_in, $file, $fh, $num, $record, $entry );
1376
1377     while ( $record = Maasha::Biopieces::get_record( $in ) ) {
1378         Maasha::Biopieces::put_record( $record, $out );
1379     }
1380
1381     $num = 1;
1382
1383     foreach $file ( @{ $options->{ "files" } } )
1384     {
1385         $fh = Maasha::Common::read_open( $file );
1386
1387         while ( $entry = Maasha::GFF::get_entry( $fh ) )
1388         {
1389             Maasha::Biopieces::put_record( $entry, $out );
1390
1391             goto NUM if $options->{ "num" } and $num == $options->{ "num" };
1392
1393             $num++;
1394         }
1395
1396         close $fh;
1397     }
1398
1399     NUM:
1400
1401     close $data_in if $data_in;
1402 }
1403
1404
1405 sub script_read_2bit
1406 {
1407     # Martin A. Hansen, March 2008.
1408
1409     # Read sequences from 2bit file.
1410
1411     my ( $in,        # handle to in stream
1412          $out,       # handle to out stream
1413          $options,   # options hash
1414        ) = @_;
1415
1416     # Returns nothing.
1417
1418     my ( $record, $file, $data_in, $mask, $toc, $line, $num );
1419
1420     $mask = 1 if not $options->{ "no_mask" };
1421
1422     while ( $record = Maasha::Biopieces::get_record( $in ) ) {
1423         Maasha::Biopieces::put_record( $record, $out );
1424     }
1425
1426     $num = 1;
1427
1428     foreach $file ( @{ $options->{ "files" } } )
1429     {
1430         $data_in = Maasha::Common::read_open( $file );
1431
1432         $toc = Maasha::TwoBit::twobit_get_TOC( $data_in );
1433
1434         foreach $line ( @{ $toc } )
1435         {
1436             $record->{ "SEQ_NAME" } = $line->[ 0 ];
1437             $record->{ "SEQ" }      = Maasha::TwoBit::twobit_get_seq( $data_in, $line->[ 1 ], undef, undef, $mask );
1438             $record->{ "SEQ_LEN" }  = length $record->{ "SEQ" };
1439
1440             Maasha::Biopieces::put_record( $record, $out );
1441
1442             goto NUM if $options->{ "num" } and $num == $options->{ "num" };
1443
1444             $num++;
1445         }
1446
1447         close $data_in;
1448     }
1449
1450     NUM:
1451
1452     close $data_in if $data_in;
1453 }
1454
1455
1456 sub script_read_solexa
1457 {
1458     # Martin A. Hansen, March 2008.
1459
1460     # Read Solexa sequence reads from file.
1461
1462     my ( $in,        # handle to in stream
1463          $out,       # handle to out stream
1464          $options,   # options hash
1465        ) = @_;
1466
1467     # Returns nothing.
1468
1469     my ( $record, $file, $data_in, $entry, $num, @seqs, @scores, $i );
1470
1471     $options->{ "format" }  ||= "octal";
1472     $options->{ "quality" } ||= 20;
1473
1474     while ( $record = Maasha::Biopieces::get_record( $in ) ) {
1475         Maasha::Biopieces::put_record( $record, $out );
1476     }
1477
1478     $num = 1;
1479
1480     foreach $file ( @{ $options->{ "files" } } )
1481     {
1482         $data_in = Maasha::Common::read_open( $file );
1483
1484         if ( $options->{ "format" } eq "octal" )
1485         {
1486             while ( $entry = Maasha::Solexa::solexa_get_entry_octal( $data_in ) )
1487             {
1488                 $record = Maasha::Solexa::solexa2biopiece( $entry, $options->{ "quality" } );
1489
1490                 Maasha::Biopieces::put_record( $record, $out );
1491
1492                 goto NUM if $options->{ "num" } and $num == $options->{ "num" };
1493
1494                 $num++;
1495             }
1496         }
1497         else
1498         {
1499             while ( $entry = Maasha::Solexa::solexa_get_entry_decimal( $data_in ) )
1500             {
1501                 $record = Maasha::Solexa::solexa2biopiece( $entry, $options->{ "quality" } );
1502
1503                 Maasha::Biopieces::put_record( $record, $out );
1504
1505                 goto NUM if $options->{ "num" } and $num == $options->{ "num" };
1506
1507                 $num++;
1508             }
1509         }
1510
1511         close $data_in;
1512     }
1513
1514     NUM:
1515
1516     close $data_in if $data_in;
1517 }
1518
1519
1520 sub script_read_solid
1521 {
1522     # Martin A. Hansen, April 2008.
1523
1524     # Read Solid sequence from file.
1525
1526     my ( $in,        # handle to in stream
1527          $out,       # handle to out stream
1528          $options,   # options hash
1529        ) = @_;
1530
1531     # Returns nothing.
1532
1533     my ( $record, $file, $data_in, $line, $num, $seq_name, $seq_cs, $seq_qual, @scores, @seqs, $i );
1534
1535     $options->{ "quality" } ||= 15;
1536
1537     while ( $record = Maasha::Biopieces::get_record( $in ) ) {
1538         Maasha::Biopieces::put_record( $record, $out );
1539     }
1540
1541     $num = 1;
1542
1543     foreach $file ( @{ $options->{ "files" } } )
1544     {
1545         $data_in = Maasha::Common::read_open( $file );
1546
1547         while ( $line = <$data_in> )
1548         {
1549             chomp $line;
1550
1551             ( $seq_name, $seq_cs, $seq_qual ) = split /\t/, $line;
1552
1553             @scores = split /,/, $seq_qual;
1554             @seqs   = split //, Maasha::Solid::color_space2seq( $seq_cs );
1555
1556             for ( $i = 0; $i < @seqs; $i++ ) {
1557                 $seqs[ $i ] = lc $seqs[ $i ] if $scores[ $i ] < $options->{ "quality" };
1558             }
1559
1560             $record = {
1561                 REC_TYPE   => 'SOLID',
1562                 SEQ_NAME   => $seq_name,
1563                 SEQ_CS     => $seq_cs,
1564                 SEQ_QUAL   => join( ";", @scores ),
1565                 SEQ_LEN    => length $seq_cs,
1566                 SEQ        => join( "", @seqs ),
1567                 SCORE_MEAN => sprintf( "%.2f", Maasha::Calc::mean( \@scores ) ),
1568             };
1569
1570             Maasha::Biopieces::put_record( $record, $out );
1571
1572             goto NUM if $options->{ "num" } and $num == $options->{ "num" };
1573
1574             $num++;
1575         }
1576
1577         close $data_in;
1578     }
1579
1580     NUM:
1581
1582     close $data_in if $data_in;
1583 }
1584
1585
1586 sub script_read_mysql
1587 {
1588     # Martin A. Hansen, May 2008.
1589
1590     # Read a MySQL query into stream.
1591
1592     my ( $in,        # handle to in stream
1593          $out,       # handle to out stream
1594          $options,   # options hash
1595        ) = @_;
1596
1597     # Returns nothing.
1598
1599     my ( $record, $dbh, $results );
1600
1601     $options->{ "user" }     ||= Maasha::UCSC::ucsc_get_user();
1602     $options->{ "password" } ||= Maasha::UCSC::ucsc_get_password();
1603
1604     while ( $record = Maasha::Biopieces::get_record( $in ) ) {
1605         Maasha::Biopieces::put_record( $record, $out );
1606     }
1607
1608     $dbh = Maasha::SQL::connect( $options->{ "database" }, $options->{ "user" }, $options->{ "password" } );
1609
1610     $results = Maasha::SQL::query_hashref_list( $dbh, $options->{ "query" } );
1611
1612     Maasha::SQL::disconnect( $dbh );
1613
1614     map { Maasha::Biopieces::put_record( $_ ) } @{ $results };
1615 }
1616
1617
1618 sub script_read_ucsc_config
1619 {
1620     # Martin A. Hansen, November 2008.
1621
1622     # Read track entries from UCSC Genome Browser '.ra' files.
1623
1624     my ( $in,        # handle to in stream
1625          $out,       # handle to out stream
1626          $options,   # options hash
1627        ) = @_;
1628
1629     # Returns nothing.
1630
1631     my ( $record, $file, $data_in, $entry, $num );
1632
1633     while ( $record = Maasha::Biopieces::get_record( $in ) ) {
1634         Maasha::Biopieces::put_record( $record, $out );
1635     }
1636
1637     $num = 1;
1638
1639     foreach $file ( @{ $options->{ "files" } } )
1640     {
1641         $data_in = Maasha::Common::read_open( $file );
1642
1643         while ( $record = Maasha::UCSC::ucsc_config_entry_get( $data_in ) ) 
1644         {
1645             $record->{ 'REC_TYPE' } = "UCSC Config";
1646
1647             Maasha::Biopieces::put_record( $record, $out );
1648
1649             goto NUM if $options->{ "num" } and $num == $options->{ "num" };
1650
1651             $num++;
1652         }
1653
1654         close $data_in;
1655     }
1656
1657     NUM:
1658
1659     close $data_in if $data_in;
1660 }
1661
1662
1663 sub script_length_seq
1664 {
1665     # Martin A. Hansen, August 2007.
1666
1667     # Determine the length of sequences in stream.
1668
1669     my ( $in,        # handle to in stream
1670          $out,       # handle to out stream
1671          $options,   # options hash
1672        ) = @_;
1673
1674     # Returns nothing.
1675
1676     my ( $record, $total );
1677
1678     while ( $record = Maasha::Biopieces::get_record( $in ) ) 
1679     {
1680         if ( $record->{ "SEQ" } )
1681         {
1682             $record->{ "SEQ_LEN" } = length $record->{ "SEQ" };
1683             $total += $record->{ "SEQ_LEN" };
1684         }
1685
1686         Maasha::Biopieces::put_record( $record, $out ) if not $options->{ "no_stream" };
1687     }
1688
1689     Maasha::Biopieces::put_record( { TOTAL_SEQ_LEN => $total }, $out );
1690 }
1691
1692
1693 sub script_complexity_seq
1694 {
1695     # Martin A. Hansen, May 2008.
1696
1697     # Generates an index calculated as the most common di-residue over
1698     # the sequence length for all sequences in stream.
1699
1700     my ( $in,     # handle to in stream
1701          $out,    # handle to out stream
1702        ) = @_;
1703
1704     # Returns nothing.
1705
1706     my ( $record, $index );
1707
1708     while ( $record = Maasha::Biopieces::get_record( $in ) ) 
1709     {
1710         $record->{ "SEQ_COMPLEXITY" } = sprintf( "%.2f", Maasha::Seq::seq_complexity( $record->{ "SEQ" } ) ) if $record->{ "SEQ" };
1711
1712         Maasha::Biopieces::put_record( $record, $out );
1713     }
1714 }
1715
1716
1717 sub script_oligo_freq
1718 {
1719     # Martin A. Hansen, August 2007.
1720
1721     # Determine the length of sequences in stream.
1722
1723     my ( $in,        # handle to in stream
1724          $out,       # handle to out stream
1725          $options,   # options hash
1726        ) = @_;
1727
1728     # Returns nothing.
1729
1730     my ( $record, %oligos, @freq_table );
1731
1732     $options->{ "word_size" } ||= 7;
1733
1734     while ( $record = Maasha::Biopieces::get_record( $in ) ) 
1735     {
1736         if ( $record->{ "SEQ" } )
1737         {
1738             map { $oligos{ $_ }++ } Maasha::Seq::seq2oligos( \$record->{ "SEQ" }, $options->{ "word_size" } );
1739
1740             if ( not $options->{ "all" } )
1741             {
1742                 @freq_table = Maasha::Seq::oligo_freq( \%oligos );
1743
1744                 map { Maasha::Biopieces::put_record( $_, $out ) } @freq_table;
1745             
1746                 undef %oligos;
1747             }
1748         }
1749
1750         Maasha::Biopieces::put_record( $record, $out );
1751     }
1752
1753     if ( $options->{ "all" } )
1754     {
1755         @freq_table = Maasha::Seq::oligo_freq( \%oligos );
1756
1757         map { Maasha::Biopieces::put_record( $_, $out ) } @freq_table;
1758     }
1759 }
1760
1761
1762 sub script_create_weight_matrix
1763 {
1764     # Martin A. Hansen, August 2007.
1765
1766     # Creates a weight matrix from an alignmnet.
1767
1768     my ( $in,        # handle to in stream
1769          $out,       # handle to out stream
1770          $options,   # options hash
1771        ) = @_;
1772
1773     # Returns nothing.
1774
1775     my ( $record, $count, $i, $res, %freq_hash, %res_hash, $freq );
1776
1777     $count = 0;
1778     
1779     while ( $record = Maasha::Biopieces::get_record( $in ) ) 
1780     {
1781         if ( $record->{ "SEQ" } )
1782         {
1783             for ( $i = 0; $i < length $record->{ "SEQ" }; $i++ )
1784             {
1785                 $res = substr $record->{ "SEQ" }, $i, 1;
1786
1787                 $freq_hash{ $i }{ $res }++;
1788                 $res_hash{ $res } = 1;
1789             }
1790
1791             $count++;
1792         }
1793         else
1794         {
1795             Maasha::Biopieces::put_record( $record, $out );
1796         }
1797     }
1798
1799     foreach $res ( sort keys %res_hash )
1800     {
1801         undef $record;
1802
1803         $record->{ "V0" } = $res;
1804
1805         for ( $i = 0; $i < keys %freq_hash; $i++ )
1806         {
1807             $freq = $freq_hash{ $i }{ $res } || 0;
1808
1809             if ( $options->{ "percent" } ) {
1810                 $freq = sprintf( "%.0f", 100 * $freq / $count ) if $freq > 0;
1811             }
1812
1813             $record->{ "V" . ( $i + 1 ) } = $freq;
1814         }
1815
1816         Maasha::Biopieces::put_record( $record, $out );
1817     }
1818 }
1819
1820
1821 sub script_remove_indels
1822 {
1823     # Martin A. Hansen, August 2007.
1824
1825     # Remove indels from sequences in stream.
1826
1827     my ( $in,     # handle to in stream
1828          $out,    # handle to out stream
1829        ) = @_;
1830
1831     # Returns nothing.
1832
1833     my ( $record );
1834
1835     while ( $record = Maasha::Biopieces::get_record( $in ) ) 
1836     {
1837         $record->{ 'SEQ' } =~ tr/-~.//d if $record->{ "SEQ" };
1838
1839         Maasha::Biopieces::put_record( $record, $out );
1840     }
1841 }
1842
1843
1844 sub script_transliterate_seq
1845 {
1846     # Martin A. Hansen, August 2007.
1847
1848     # Transliterate chars from sequence in record.
1849
1850     my ( $in,        # handle to in stream
1851          $out,       # handle to out stream
1852          $options,   # options hash
1853        ) = @_;
1854
1855     # Returns nothing.
1856
1857     my ( $record, $search, $replace, $delete );
1858
1859     $search  = $options->{ "search" }  || "";
1860     $replace = $options->{ "replace" } || "";
1861     $delete  = $options->{ "delete" }  || "";
1862
1863     while ( $record = Maasha::Biopieces::get_record( $in ) ) 
1864     {
1865         if ( $record->{ "SEQ" } )
1866         {
1867             if ( $search and $replace ) {
1868                 eval "\$record->{ 'SEQ' } =~ tr/$search/$replace/";
1869             } elsif ( $delete ) {
1870                 eval "\$record->{ 'SEQ' } =~ tr/$delete//d";
1871             }
1872         }
1873
1874         Maasha::Biopieces::put_record( $record, $out );
1875     }
1876 }
1877
1878
1879 sub script_transliterate_vals
1880 {
1881     # Martin A. Hansen, April 2008.
1882
1883     # Transliterate chars from values in record.
1884
1885     my ( $in,        # handle to in stream
1886          $out,       # handle to out stream
1887          $options,   # options hash
1888        ) = @_;
1889
1890     # Returns nothing.
1891
1892     my ( $record, $search, $replace, $delete, $key );
1893
1894     $search  = $options->{ "search" }  || "";
1895     $replace = $options->{ "replace" } || "";
1896     $delete  = $options->{ "delete" }  || "";
1897
1898     while ( $record = Maasha::Biopieces::get_record( $in ) ) 
1899     {
1900         foreach $key ( @{ $options->{ "keys" } } )
1901         {
1902             if ( exists $record->{ $key } )
1903             {
1904                 if ( $search and $replace ) {
1905                     eval "\$record->{ $key } =~ tr/$search/$replace/";
1906                 } elsif ( $delete ) {
1907                     eval "\$record->{ $key } =~ tr/$delete//d";
1908                 }
1909             }
1910         }
1911
1912         Maasha::Biopieces::put_record( $record, $out );
1913     }
1914 }
1915
1916
1917 sub script_translate_seq
1918 {
1919     # Martin A. Hansen, February 2008.
1920
1921     # Translate DNA sequence into protein sequence.
1922
1923     my ( $in,        # handle to in stream
1924          $out,       # handle to out stream
1925          $options,   # options hash
1926        ) = @_;
1927
1928     # Returns nothing.
1929
1930     my ( $record, $frame, %new_record );
1931
1932     $options->{ "frames" } ||= [ 1, 2, 3, -1, -2, -3 ];
1933
1934     while ( $record = Maasha::Biopieces::get_record( $in ) ) 
1935     {
1936         if ( $record->{ "SEQ" } )
1937         {
1938             if ( Maasha::Seq::seq_guess_type( $record->{ "SEQ" } ) eq "dna" )
1939             {
1940                 foreach $frame ( @{ $options->{ "frames" } } )
1941                 {
1942                     %new_record = %{ $record };
1943
1944                     $new_record{ "SEQ" }     = Maasha::Seq::translate( $record->{ "SEQ" }, $frame );
1945                     $new_record{ "SEQ_LEN" } = length $new_record{ "SEQ" };
1946                     $new_record{ "FRAME" }   = $frame;
1947
1948                     Maasha::Biopieces::put_record( \%new_record, $out );
1949                 }
1950             }
1951         }
1952         else
1953         {
1954             Maasha::Biopieces::put_record( $record, $out );
1955         }
1956     }
1957 }
1958
1959
1960 sub script_get_genome_align
1961 {
1962     # Martin A. Hansen, April 2008.
1963
1964     # Gets a subalignment from a multiple genome alignment.
1965
1966     my ( $in,        # handle to in stream
1967          $out,       # handle to out stream
1968          $options,   # options hash
1969        ) = @_;
1970
1971     # Returns nothing.
1972
1973     my ( $record, $maf_track, $align, $align_num, $beg, $end, $len, $entry );
1974
1975     $options->{ "strand" } ||= "+";
1976
1977     $align_num = 1;
1978
1979     $maf_track = Maasha::Config::maf_track( $options->{ "genome" } );
1980
1981     if ( $options->{ "chr" } and $options->{ "beg" } and ( $options->{ "end" } or $options->{ "len" } ) )
1982     {
1983         $beg = $options->{ "beg" } - 1;
1984         
1985         if ( $options->{ "end" } ) {
1986             $end = $options->{ "end" };
1987         } elsif ( $options->{ "len" } ) {
1988             $end = $beg + $options->{ "len" };
1989         }
1990
1991         $align = Maasha::UCSC::maf_extract( $BP_TMP, $options->{ "genome" }, $maf_track, $options->{ "chr" }, $beg, $end, $options->{ "strand" } );
1992
1993         foreach $entry ( @{ $align } )
1994         {
1995             $entry->{ "CHR" }     = $record->{ "CHR" };
1996             $entry->{ "CHR_BEG" } = $record->{ "CHR_BEG" };
1997             $entry->{ "CHR_END" } = $record->{ "CHR_END" };
1998             $entry->{ "STRAND" }  = $record->{ "STRAND" } || '+';
1999             $entry->{ "Q_ID" }    = $record->{ "Q_ID" };
2000             $entry->{ "SCORE" }   = $record->{ "SCORE" };
2001
2002             Maasha::Biopieces::put_record( $entry, $out );
2003         }
2004     }
2005
2006     while ( $record = Maasha::Biopieces::get_record( $in ) ) 
2007     {
2008         if ( $record->{ "REC_TYPE" } eq "BED" )
2009         {
2010             $align = Maasha::UCSC::maf_extract( $BP_TMP, $options->{ "genome" }, $maf_track, $record->{ "CHR" }, $record->{ "CHR_BEG" }, $record->{ "CHR_END" }, $record->{ "STRAND" } );
2011         }
2012         elsif ( $record->{ "REC_TYPE" } eq "VMATCH" )
2013         {
2014             $align = Maasha::UCSC::maf_extract( $BP_TMP, $options->{ "genome" }, $maf_track, $record->{ "S_ID" }, $record->{ "S_BEG" }, $record->{ "S_END" } + 1, $record->{ "STRAND" } );
2015         }
2016         elsif ( $record->{ "REC_TYPE" } eq "PSL" )
2017         {
2018             $align = Maasha::UCSC::maf_extract( $BP_TMP, $options->{ "genome" }, $maf_track, $record->{ "S_ID" }, $record->{ "S_BEG" }, $record->{ "S_END" }, $record->{ "STRAND" } );
2019         }
2020         elsif ( $record->{ "REC_TYPE" } eq "BLAST" )
2021         {
2022             $align = Maasha::UCSC::maf_extract( $BP_TMP, $options->{ "genome" }, $maf_track, $record->{ "S_ID" }, $record->{ "S_BEG" }, $record->{ "S_END" }, $record->{ "STRAND" } );
2023         }
2024
2025         foreach $entry ( @{ $align } )
2026         {
2027             $entry->{ "CHR" }     = $record->{ "CHR" };
2028             $entry->{ "CHR_BEG" } = $record->{ "CHR_BEG" };
2029             $entry->{ "CHR_END" } = $record->{ "CHR_END" };
2030             $entry->{ "STRAND" }  = $record->{ "STRAND" };
2031             $entry->{ "Q_ID" }    = $record->{ "Q_ID" };
2032             $entry->{ "SCORE" }   = $record->{ "SCORE" };
2033
2034             Maasha::Biopieces::put_record( $entry, $out );
2035         }
2036
2037         $align_num++;
2038     }
2039 }
2040
2041
2042 sub script_get_genome_phastcons
2043 {
2044     # Martin A. Hansen, February 2008.
2045
2046     # Get phastcons scores from genome intervals.
2047
2048     my ( $in,        # handle to in stream
2049          $out,       # handle to out stream
2050          $options,   # options hash
2051        ) = @_;
2052
2053     # Returns nothing.
2054
2055     my ( $phastcons_file, $phastcons_index, $index, $fh_phastcons, $scores, $record );
2056
2057     $options->{ "flank" } ||= 0;
2058
2059     $phastcons_file  = Maasha::Config::genome_phastcons( $options->{ "genome" } );
2060     $phastcons_index = Maasha::Config::genome_phastcons_index( $options->{ "genome" } );
2061
2062     $index           = Maasha::UCSC::fixedstep_index_retrieve( $phastcons_index );
2063     $fh_phastcons    = Maasha::Common::read_open( $phastcons_file );
2064
2065     if ( defined $options->{ "chr" } and defined $options->{ "beg" } and ( defined $options->{ "end" } or defined $options->{ "len" } ) )
2066     {
2067         $options->{ "beg" } -= 1;   # request is 1-based
2068         $options->{ "end" } -= 1;   # request is 1-based
2069
2070         if ( $options->{ "len" } ) {
2071             $options->{ "end" } = $options->{ "beg" } + $options->{ "len" } - 1;
2072         }
2073
2074         $scores = Maasha::UCSC::fixedstep_index_lookup( $index, $fh_phastcons, $options->{ "chr" }, $options->{ "beg" }, $options->{ "end" }, $options->{ "flank" } );
2075
2076         $record->{ "CHR" }       = $options->{ "chr" };
2077         $record->{ "CHR_BEG" }   = $options->{ "beg" } - $options->{ "flank" };
2078         $record->{ "CHR_END" }   = $options->{ "end" } + $options->{ "flank" };
2079         
2080         $record->{ "PHASTCONS" }   = join ",", @{ $scores };
2081         $record->{ "PHAST_COUNT" } = scalar @{ $scores };  # DEBUG
2082
2083         Maasha::Biopieces::put_record( $record, $out );
2084     }   
2085
2086     while ( $record = Maasha::Biopieces::get_record( $in ) ) 
2087     {
2088         if ( $record->{ "REC_TYPE" } eq "BED" )
2089         {
2090             $scores = Maasha::UCSC::fixedstep_index_lookup( $index, $fh_phastcons, $record->{ "CHR" }, $record->{ "CHR_BEG" }, $record->{ "CHR_END" }, $options->{ "flank" } );
2091         }
2092         elsif ( $record->{ "REC_TYPE" } eq "PSL" )
2093         {
2094             $scores = Maasha::UCSC::fixedstep_index_lookup( $index, $fh_phastcons, $record->{ "S_ID" }, $record->{ "S_BEG" }, $record->{ "S_END" }, $options->{ "flank" } );
2095         }
2096         elsif ( $record->{ "REC_TYPE" } eq "BLAST" )
2097         {
2098             $scores = Maasha::UCSC::fixedstep_index_lookup( $index, $fh_phastcons, $record->{ "S_ID" }, $record->{ "S_BEG" }, $record->{ "S_END" }, $options->{ "flank" } );
2099         }
2100
2101         $record->{ "PHASTCONS" } = join ",", @{ $scores } if @{ $scores };
2102 #        $record->{ "PHAST_COUNT" } = @{ $scores } if @{ $scores };  # DEBUG
2103
2104         Maasha::Biopieces::put_record( $record, $out );
2105     }
2106
2107     close $fh_phastcons if $fh_phastcons;                                                                                                                                          
2108 }
2109
2110
2111 sub script_fold_seq
2112 {
2113     # Martin A. Hansen, December 2007.
2114
2115     # Folds sequences in stream into secondary structures.
2116
2117     my ( $in,     # handle to in stream
2118          $out,    # handle to out stream
2119        ) = @_;
2120
2121     # Returns nothing.
2122
2123     my ( $record, $type, $struct, $index );
2124
2125     while ( $record = Maasha::Biopieces::get_record( $in ) ) 
2126     {
2127         if ( $record->{ "SEQ" } )
2128         {
2129             if ( not $type ) {
2130                 $type = Maasha::Seq::seq_guess_type( $record->{ "SEQ" } );
2131             }
2132             
2133             if ( $type ne "protein" )
2134             {
2135                 ( $struct, $index ) = Maasha::Seq::fold_struct_rnafold( $record->{ "SEQ" } );
2136                 $record->{ "SEC_STRUCT" }  = $struct;
2137                 $record->{ "FREE_ENERGY" } = $index;
2138                 $record->{ "SCORE" }       = abs int $index;
2139                 $record->{ "SIZE" }        = length $struct;
2140                 $record->{ "CONF" }        = "1," x $record->{ "SIZE" };
2141             }
2142         }
2143
2144         Maasha::Biopieces::put_record( $record, $out );
2145     }
2146 }
2147
2148
2149 sub script_tile_seq
2150 {
2151     # Martin A. Hansen, February 2008.
2152
2153     # Using the first sequence in stream as reference, tile
2154     # all subsequent sequences based on pairwise alignments.
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, $first, $ref_entry, @entries );
2164
2165     $first = 1;
2166
2167     while ( $record = Maasha::Biopieces::get_record( $in ) ) 
2168     {
2169         if ( $record->{ "SEQ_NAME" } and $record->{ "SEQ" } )
2170         {
2171             if ( $first )
2172             {
2173                 $ref_entry = [ $record->{ "SEQ_NAME" }, $record->{ "SEQ" } ];
2174
2175                 $first = 0;
2176             }
2177             else
2178             {
2179                 push @entries, [ $record->{ "SEQ_NAME" }, $record->{ "SEQ" } ];
2180             }
2181         }
2182         else
2183         {
2184             Maasha::Biopieces::put_record( $record, $out );
2185         }
2186     }
2187
2188     @entries = Maasha::Align::align_tile( $ref_entry, \@entries, $options );
2189
2190     map { Maasha::Biopieces::put_record( { SEQ_NAME => $_->[ SEQ_NAME ], SEQ => $_->[ SEQ ] }, $out ) } @entries;
2191 }
2192
2193
2194 sub script_invert_align
2195 {
2196     # Martin A. Hansen, February 2008.
2197
2198     # Inverts an alignment showing only non-mathing residues
2199     # using the first sequence as reference.
2200
2201     my ( $in,        # handle to in stream
2202          $out,       # handle to out stream
2203          $options,   # options hash
2204        ) = @_;
2205
2206     # Returns nothing.
2207
2208     my ( $record, @entries );
2209
2210     while ( $record = Maasha::Biopieces::get_record( $in ) ) 
2211     {
2212         if ( $record->{ "SEQ_NAME" } and $record->{ "SEQ" } )
2213         {
2214             push @entries, [ $record->{ "SEQ_NAME" }, $record->{ "SEQ" } ];
2215         }
2216         else
2217         {
2218             Maasha::Biopieces::put_record( $record, $out );
2219         }
2220     }
2221
2222     Maasha::Align::align_invert( \@entries, $options->{ "soft" } );
2223
2224     map { Maasha::Biopieces::put_record( { SEQ_NAME => $_->[ SEQ_NAME ], SEQ => $_->[ SEQ ] }, $out ) } @entries;
2225 }
2226
2227
2228 sub script_patscan_seq
2229 {
2230     # Martin A. Hansen, August 2007.
2231
2232     # Locates patterns in sequences using scan_for_matches.
2233
2234     my ( $in,        # handle to in stream
2235          $out,       # handle to out stream
2236          $options,   # options hash
2237        ) = @_;
2238
2239     # Returns nothing.
2240
2241     my ( $genome_file, @args, $arg, $type, $seq_file, $pat_file, $out_file, $fh_in, $fh_out, $record, $patterns, $pattern, $entry, $result, %head_hash, $i );
2242
2243     if ( $options->{ "patterns" } ) {
2244         $patterns = Maasha::Patscan::parse_patterns( $options->{ "patterns" } );
2245     } elsif ( -f $options->{ "patterns_in" } ) {
2246         $patterns = Maasha::Patscan::read_patterns( $options->{ "patterns_in" } );
2247     }
2248
2249     $genome_file = "$ENV{ 'BP_DATA' }/genomes/$options->{ 'genome' }/fasta/$options->{ 'genome' }.fna" if $options->{ 'genome' };
2250
2251     push @args, "-c"                            if $options->{ "comp" };
2252     push @args, "-m $options->{ 'max_hits' }"   if $options->{ 'max_hits' };
2253     push @args, "-n $options->{ 'max_misses' }" if $options->{ 'max_hits' };
2254
2255     $seq_file = "$BP_TMP/patscan.seq";
2256     $pat_file = "$BP_TMP/patscan.pat";
2257     $out_file = "$BP_TMP/patscan.out";
2258
2259     $fh_out = Maasha::Common::write_open( $seq_file );
2260
2261     $i = 0;
2262
2263     while ( $record = Maasha::Biopieces::get_record( $in ) ) 
2264     {
2265         if ( $record->{ "SEQ" } and $record->{ "SEQ_NAME" } )
2266         {
2267             $type = Maasha::Seq::seq_guess_type( $record->{ "SEQ" } ) if not $type;
2268
2269             Maasha::Fasta::put_entry( [ $i, $record->{ "SEQ" } ], $fh_out );
2270
2271             $head_hash{ $i } = $record->{ "SEQ_NAME" };
2272
2273             $i++;
2274         }
2275     }
2276
2277     close $fh_out;
2278
2279     $arg  = join " ", @args;
2280     $arg .= " -p" if $type eq "protein";
2281
2282     foreach $pattern ( @{ $patterns } )
2283     {
2284         $fh_out = Maasha::Common::write_open( $pat_file );
2285
2286         print $fh_out "$pattern\n";
2287
2288         close $fh_out;
2289
2290         if ( $options->{ 'genome' } ) {
2291             `scan_for_matches $arg $pat_file < $genome_file > $out_file`;
2292             # Maasha::Common::run( "scan_for_matches", "$arg $pat_file < $genome_file > $out_file" );
2293         } else {
2294             `scan_for_matches $arg $pat_file < $seq_file > $out_file`;
2295             # Maasha::Common::run( "scan_for_matches", "$arg $pat_file < $seq_file > $out_file" );
2296         }
2297
2298         $fh_in = Maasha::Common::read_open( $out_file );
2299
2300         while ( $entry = Maasha::Fasta::get_entry( $fh_in ) )
2301         {
2302             $result = Maasha::Patscan::parse_scan_result( $entry, $pattern );
2303
2304             if ( $options->{ 'genome' } )
2305             {
2306                 $result->{ "CHR" }     = $result->{ "S_ID" };
2307                 $result->{ "CHR_BEG" } = $result->{ "S_BEG" }; 
2308                 $result->{ "CHR_END" } = $result->{ "S_END" }; 
2309
2310                 delete $result->{ "S_ID" };
2311                 delete $result->{ "S_BEG" };
2312                 delete $result->{ "S_END" };
2313             }
2314             else
2315             {
2316                 $result->{ "S_ID" } = $head_hash{ $result->{ "S_ID" } };
2317             }
2318
2319             Maasha::Biopieces::put_record( $result, $out );
2320         }
2321
2322         close $fh_in;
2323     }
2324
2325     unlink $pat_file;
2326     unlink $seq_file;
2327     unlink $out_file;
2328 }
2329
2330
2331 sub script_soap_seq
2332 {
2333     # Martin A. Hansen, July 2008.
2334
2335     # soap sequences in stream against a given file or genome.
2336
2337     my ( $in,        # handle to in stream
2338          $out,       # handle to out stream
2339          $options,   # options hash
2340        ) = @_;
2341
2342     # Returns nothing.
2343
2344     my ( $genome, $tmp_in, $tmp_out, $fh_in, $fh_out, $record, $line, @fields, $entry, $count, $args );
2345
2346     $options->{ "seed_size" }  ||= 10;
2347     $options->{ "mismatches" } ||= 2;
2348     $options->{ "gap_size" }   ||= 0;
2349     $options->{ "cpus" }       ||= 1;
2350
2351     if ( $options->{ "genome" } ) {
2352         $options->{ "in_file" } = "$ENV{ 'BP_DATA' }/genomes/$options->{ 'genome' }/fasta/$options->{ 'genome' }.fna";
2353     }
2354
2355     $tmp_in  = "$BP_TMP/soap_query.seq";
2356     $tmp_out = "$BP_TMP/soap.result";
2357
2358     $fh_out = Maasha::Common::write_open( $tmp_in );
2359  
2360     $count = 0;
2361
2362     while ( $record = Maasha::Biopieces::get_record( $in ) ) 
2363     {
2364         if ( $entry = Maasha::Fasta::biopiece2fasta( $record ) )
2365         {
2366             Maasha::Fasta::put_entry( $entry, $fh_out );
2367
2368             $count++;
2369         }
2370
2371         Maasha::Biopieces::put_record( $record, $out );
2372     }
2373
2374     close $fh_out;
2375
2376     if ( $count > 0 )
2377     {
2378         $args = join( " ",
2379             "-s $options->{ 'seed_size' }",
2380             "-r 2",
2381             "-a $tmp_in",
2382             "-v $options->{ 'mismatches' }",
2383             "-g $options->{ 'gap_size' }",
2384             "-p $options->{ 'cpus' }",
2385             "-d $options->{ 'in_file' }",
2386             "-o $tmp_out",
2387         );
2388
2389         $args .= " > /dev/null 2>&1" if not $options->{ 'verbose' };
2390
2391         Maasha::Common::run( "soap", $args, 1 );
2392
2393         unlink $tmp_in;
2394
2395         $fh_out = Maasha::Common::read_open( $tmp_out );
2396
2397         undef $record;
2398
2399         while ( $line = <$fh_out> )
2400         {
2401             chomp $line;
2402
2403             @fields = split /\t/, $line;
2404
2405             $record->{ "REC_TYPE" }   = "SOAP";
2406             $record->{ "Q_ID" }       = $fields[ 0 ];
2407             $record->{ "SCORE" }      = $fields[ 3 ];
2408             $record->{ "STRAND" }     = $fields[ 6 ];
2409             $record->{ "S_ID" }       = $fields[ 7 ];
2410             $record->{ "S_BEG" }      = $fields[ 8 ] - 1; # soap is 1-based
2411             $record->{ "S_END" }      = $fields[ 8 ] + $fields[ 5 ] - 2;
2412
2413             Maasha::Biopieces::put_record( $record, $out );
2414         }
2415
2416         close $fh_out;
2417     }
2418
2419     unlink $tmp_out;
2420 }
2421
2422
2423 sub script_match_seq
2424 {
2425     # Martin A. Hansen, August 2007.
2426
2427     # BLATs sequences in stream against a given genome.
2428
2429     my ( $in,        # handle to in stream
2430          $out,       # handle to out stream
2431          $options,   # options hash
2432        ) = @_;
2433
2434     # Returns nothing.
2435
2436     my ( $record, @entries, $results );
2437
2438     $options->{ "word_size" } ||= 20;
2439     $options->{ "direction" } ||= "both";
2440
2441     while ( $record = Maasha::Biopieces::get_record( $in ) ) 
2442     {
2443         if ( $record->{ "SEQ_NAME" } and $record->{ "SEQ" } ) {
2444             push @entries, [ $record->{ "SEQ_NAME" }, $record->{ "SEQ" } ];
2445         }
2446
2447         Maasha::Biopieces::put_record( $record, $out );
2448     }
2449
2450     if ( @entries == 1 )
2451     {
2452         $results = Maasha::Match::match_mummer( [ $entries[ 0 ] ], [ $entries[ 0 ] ], $options, $BP_TMP );
2453
2454         map { Maasha::Biopieces::put_record( $_, $out ) } @{ $results };
2455     }
2456     elsif ( @entries == 2 )
2457     {
2458         $results = Maasha::Match::match_mummer( [ $entries[ 0 ] ], [ $entries[ 1 ] ], $options, $BP_TMP );
2459
2460         map { Maasha::Biopieces::put_record( $_, $out ) } @{ $results };
2461     }
2462 }
2463
2464
2465 sub script_create_vmatch_index
2466 {
2467     # Martin A. Hansen, January 2008.
2468
2469     # Create a vmatch index from sequences in the stream.
2470
2471     my ( $in,        # handle to in stream
2472          $out,       # handle to out stream
2473          $options,   # options hash
2474        ) = @_;
2475
2476     # Returns nothing.
2477
2478     my ( $record, $file_tmp, $fh_tmp, $type, $entry );
2479
2480     if ( $options->{ "index_name" } )
2481     {
2482         $file_tmp = $options->{ 'index_name' };
2483         $fh_tmp   = Maasha::Common::write_open( $file_tmp );
2484     }
2485
2486     while ( $record = Maasha::Biopieces::get_record( $in ) ) 
2487     {
2488         if ( $options->{ "index_name" } and $entry = Maasha::Fasta::biopiece2fasta( $record ) )
2489         {
2490             Maasha::Fasta::put_entry( $entry, $fh_tmp );
2491
2492             $type = Maasha::Seq::seq_guess_type( $entry->[ SEQ ] ) if not defined $type;
2493         }
2494
2495         Maasha::Biopieces::put_record( $record, $out ) if not $options->{ "no_stream" };
2496     }
2497
2498     if ( $options->{ "index_name" } )
2499     {
2500         close $fh_tmp;
2501     
2502         if ( $type eq "protein" ) {
2503             Maasha::Common::run( "mkvtree", "-db $file_tmp -protein -pl $options->{ 'prefix_length' } -allout -indexname $file_tmp > /dev/null 2>&1" );
2504         } else {
2505             Maasha::Common::run( "mkvtree", "-db $file_tmp -dna -pl $options->{ 'prefix_length' } -allout -indexname $file_tmp > /dev/null 2>&1" );
2506         }
2507
2508         unlink $file_tmp;
2509     }
2510 }
2511
2512
2513 sub script_write_bed
2514 {
2515     # Martin A. Hansen, August 2007.
2516
2517     # Write BED format for the UCSC genome browser using records in stream.
2518
2519     my ( $in,        # handle to in stream
2520          $out,       # handle to out stream
2521          $options,   # options hash
2522        ) = @_;
2523
2524     # Returns nothing.
2525
2526     my ( $cols, $fh, $record, $bed_entry, $new_record );
2527
2528     $cols = $options->{ 'cols' }->[ 0 ];
2529
2530     $fh = Maasha::Biopieces::write_stream( $options->{ 'data_out' }, $options->{ 'compress' } );
2531
2532     while ( $record = Maasha::Biopieces::get_record( $in ) ) 
2533     {
2534         $record = Maasha::UCSC::psl2record( $record ) if $record->{ 'tBaseInsert' }; # Dirty addition to allow Affy data from MySQL to be dumped
2535
2536         if ( $bed_entry = Maasha::UCSC::BED::biopiece2bed( $record, $cols ) ) {
2537             Maasha::UCSC::BED::bed_entry_put( $bed_entry, $fh, $cols, $options->{ 'check' } );
2538         }
2539
2540         Maasha::Biopieces::put_record( $record, $out ) if not $options->{ 'no_stream' };
2541     }
2542
2543     close $fh;
2544 }
2545
2546
2547 sub script_write_psl
2548 {
2549     # Martin A. Hansen, August 2007.
2550
2551     # Write PSL output from stream.
2552
2553     my ( $in,        # handle to in stream
2554          $out,       # handle to out stream
2555          $options,   # options hash
2556        ) = @_;
2557
2558     # Returns nothing.
2559
2560     my ( $fh, $record, @output, $first );
2561
2562     $first = 1;
2563
2564     $fh = write_stream( $options->{ "data_out" }, $options->{ "compress" } );
2565
2566     while ( $record = Maasha::Biopieces::get_record( $in ) ) 
2567     {
2568         Maasha::Biopieces::put_record( $record, $out ) if not $options->{ "no_stream" };
2569
2570         if ( $record->{ "REC_TYPE" } and $record->{ "REC_TYPE" } eq "PSL" )
2571         {
2572             Maasha::UCSC::psl_put_header( $fh ) if $first;
2573             Maasha::UCSC::psl_put_entry( $record, $fh );
2574             $first = 0;
2575         }
2576     }
2577
2578     close $fh;
2579 }
2580
2581
2582 sub script_write_fixedstep
2583 {
2584     # Martin A. Hansen, Juli 2008.
2585
2586     # Write fixedStep entries from recrods in the stream.
2587
2588     my ( $in,        # handle to in stream
2589          $out,       # handle to out stream
2590          $options,   # options hash
2591        ) = @_;
2592
2593     # Returns nothing.
2594
2595     my ( $fh, $record, $entry );
2596
2597     $fh = write_stream( $options->{ "data_out" }, $options->{ "compress" } );
2598
2599     while ( $record = Maasha::Biopieces::get_record( $in ) ) 
2600     {
2601         if ( $entry = Maasha::UCSC::Wiggle::biopiece2fixedstep( $record ) ) {
2602             Maasha::UCSC::Wiggle::fixedstep_entry_put( $entry, $fh );
2603         }
2604
2605         Maasha::Biopieces::put_record( $record, $out ) if not $options->{ "no_stream" };
2606     }
2607
2608     close $fh;
2609 }
2610
2611
2612 sub script_write_2bit
2613 {
2614     # Martin A. Hansen, March 2008.
2615
2616     # Write sequence entries from stream in 2bit format.
2617
2618     my ( $in,        # handle to in stream
2619          $out,       # handle to out stream
2620          $options,   # options hash
2621        ) = @_;
2622
2623     # Returns nothing.
2624
2625     my ( $record, $mask, $tmp_file, $fh_tmp, $fh_in, $fh_out, $entry );
2626
2627     $mask = 1 if not $options->{ "no_mask" };
2628
2629     $tmp_file = "$BP_TMP/write_2bit.fna";
2630     $fh_tmp   = Maasha::Common::write_open( $tmp_file );
2631
2632     $fh_out = write_stream( $options->{ "data_out" } );
2633
2634     while ( $record = Maasha::Biopieces::get_record( $in ) ) 
2635     {
2636         if ( $entry = Maasha::Fasta::biopiece2fasta( $record ) ) {
2637             Maasha::Fasta::put_entry( $entry, $fh_tmp );
2638         }
2639
2640         Maasha::Biopieces::put_record( $record, $out ) if not $options->{ "no_stream" };
2641     }
2642
2643     close $fh_tmp;
2644
2645     $fh_in = Maasha::Common::read_open( $tmp_file );
2646
2647     Maasha::TwoBit::fasta2twobit( $fh_in, $fh_out, $mask );
2648
2649     close $fh_in;
2650     close $fh_out;
2651
2652     unlink $tmp_file;
2653 }
2654
2655
2656 sub script_write_solid
2657 {
2658     # Martin A. Hansen, April 2008.
2659
2660     # Write di-base encoded Solid sequence from entries in stream.
2661
2662     my ( $in,        # handle to in stream
2663          $out,       # handle to out stream
2664          $options,   # options hash
2665        ) = @_;
2666
2667     # Returns nothing.
2668
2669     my ( $record, $fh, $entry );
2670
2671     $fh = write_stream( $options->{ "data_out" }, $options->{ "compress" } );
2672
2673     while ( $record = Maasha::Biopieces::get_record( $in ) ) 
2674     {
2675         if ( $entry = Maasha::Fasta::biopiece2fasta( $record ) )
2676         {
2677             $entry->[ SEQ ] = Maasha::Solid::seq2color_space( uc $entry->[ SEQ ] );
2678
2679             Maasha::Fasta::put_entry( $entry, $fh, $options->{ "wrap" } );
2680         }
2681
2682         Maasha::Biopieces::put_record( $record, $out ) if not $options->{ "no_stream" };
2683     }
2684
2685     close $fh;
2686 }
2687
2688
2689 sub script_write_ucsc_config
2690 {
2691     # Martin A. Hansen, November 2008.
2692
2693     # Write UCSC Genome Broser configuration (.ra file type) from
2694     # records in the stream.
2695
2696     my ( $in,        # handle to in stream
2697          $out,       # handle to out stream
2698          $options,   # options hash
2699        ) = @_;
2700
2701     # Returns nothing.
2702
2703     my ( $record, $fh );
2704
2705     $fh = write_stream( $options->{ "data_out" } );
2706
2707     while ( $record = Maasha::Biopieces::get_record( $in ) ) 
2708     {
2709         Maasha::UCSC::ucsc_config_entry_put( $record, $fh ) if $record->{ "REC_TYPE" } eq "UCSC Config";
2710
2711         Maasha::Biopieces::put_record( $record, $out ) if not $options->{ "no_stream" };
2712     }
2713
2714     close $fh;
2715 }
2716
2717
2718 sub script_plot_seqlogo
2719 {
2720     # Martin A. Hansen, August 2007.
2721
2722     # Calculates and writes a sequence logo for alignments.
2723
2724     my ( $in,        # handle to in stream
2725          $out,       # handle to out stream
2726          $options,   # options hash
2727        ) = @_;
2728
2729     # Returns nothing.
2730
2731     my ( $record, @entries, $logo, $fh );
2732
2733     while ( $record = Maasha::Biopieces::get_record( $in ) ) 
2734     {
2735         if ( $record->{ "SEQ_NAME" } and $record->{ "SEQ" } ) {
2736             push @entries, [ $record->{ "SEQ_NAME" }, $record->{ "SEQ" } ];
2737         }
2738
2739         Maasha::Biopieces::put_record( $record, $out ) if not $options->{ "no_stream" };
2740     }
2741
2742     $logo = Maasha::Plot::seq_logo( \@entries );
2743
2744     $fh = write_stream( $options->{ "data_out" } );
2745
2746     print $fh $logo;
2747
2748     close $fh;
2749 }
2750
2751
2752 sub script_plot_phastcons_profiles
2753 {
2754     # Martin A. Hansen, January 2008.
2755
2756     # Plots PhastCons profiles.
2757
2758     my ( $in,        # handle to in stream
2759          $out,       # handle to out stream
2760          $options,   # options hash
2761        ) = @_;
2762
2763     # Returns nothing.
2764
2765     my ( $phastcons_file, $phastcons_index, $index, $fh_phastcons, $record, $scores, $AoA, $plot, $fh );
2766
2767     $options->{ "title" } ||= "PhastCons Profiles";
2768
2769     $phastcons_file  = Maasha::Config::genome_phastcons( $options->{ "genome" } );
2770     $phastcons_index = Maasha::Config::genome_phastcons_index( $options->{ "genome" } );
2771
2772     $index           = Maasha::UCSC::fixedstep_index_retrieve( $phastcons_index );
2773     $fh_phastcons    = Maasha::Common::read_open( $phastcons_file );
2774
2775     while ( $record = Maasha::Biopieces::get_record( $in ) ) 
2776     {
2777         if ( $record->{ "CHR" } and $record->{ "CHR_BEG" } and $record->{ "CHR_END" } )
2778         {
2779             $scores = Maasha::UCSC::fixedstep_index_lookup( $index, $fh_phastcons, $record->{ "CHR" },
2780                                                                                    $record->{ "CHR_BEG" },
2781                                                                                    $record->{ "CHR_END" },
2782                                                                                    $options->{ "flank" } );
2783
2784             push @{ $AoA }, [ @{ $scores } ];
2785         }
2786
2787         Maasha::Biopieces::put_record( $record, $out ) if not $options->{ "no_stream" };
2788     }
2789
2790     Maasha::UCSC::phastcons_normalize( $AoA );
2791
2792     $AoA = [ [ Maasha::UCSC::phastcons_mean( $AoA ) ] ] if $options->{ "mean" };
2793     $AoA = [ [ Maasha::UCSC::phastcons_median( $AoA ) ] ] if $options->{ "median" };
2794
2795     $AoA = Maasha::Matrix::matrix_flip( $AoA );
2796
2797     $plot = Maasha::Plot::lineplot_simple( $AoA, $options, $BP_TMP );
2798
2799     $fh = write_stream( $options->{ "data_out" } );
2800
2801     print $fh "$_\n" foreach @{ $plot };
2802
2803     close $fh;
2804 }
2805
2806
2807 sub script_head_records
2808 {
2809     # Martin A. Hansen, August 2007.
2810
2811     # Display the first sequences in stream.
2812
2813     my ( $in,        # handle to in stream
2814          $out,       # handle to out stream
2815          $options,   # options hash
2816        ) = @_;
2817
2818     # Returns nothing.
2819
2820     my ( $record, $count );
2821
2822     $options->{ "num" } ||= 10;
2823
2824     $count = 0;
2825
2826     while ( $record = Maasha::Biopieces::get_record( $in ) ) 
2827     {
2828         $count++;
2829
2830         Maasha::Biopieces::put_record( $record, $out );
2831
2832         last if $count == $options->{ "num" };
2833     }
2834 }
2835
2836
2837 sub script_remove_keys
2838 {
2839     # Martin A. Hansen, August 2007.
2840
2841     # Remove keys from stream.
2842
2843     my ( $in,        # handle to in stream
2844          $out,       # handle to out stream
2845          $options,   # options hash
2846        ) = @_;
2847
2848     # Returns nothing.
2849
2850     my ( $record, $new_record );
2851
2852     while ( $record = Maasha::Biopieces::get_record( $in ) ) 
2853     {
2854         if ( $options->{ "keys" } )
2855         {
2856             map { delete $record->{ $_ } } @{ $options->{ "keys" } };
2857         }
2858         elsif ( $options->{ "save_keys" } )
2859         {
2860             map { $new_record->{ $_ } = $record->{ $_ } if exists $record->{ $_ } } @{ $options->{ "save_keys" } };
2861
2862             $record = $new_record;
2863         }
2864
2865         Maasha::Biopieces::put_record( $record, $out ) if keys %{ $record };
2866     }
2867 }
2868
2869
2870 sub script_remove_adaptor
2871 {
2872     # Martin A. Hansen, August 2008.
2873
2874     # Find and remove adaptor from sequences in the stream.
2875
2876     my ( $in,        # handle to in stream
2877          $out,       # handle to out stream
2878          $options,   # options hash
2879        ) = @_;
2880
2881     # Returns nothing.
2882
2883     my ( $record, $adaptor, $seq, $adaptor_len, $seq_len, $offset, $max_match, $max_mismatch, $pos );
2884
2885     $options->{ "remove" } ||= "after";
2886
2887     $max_mismatch = $options->{ "mismatches" } || 0;
2888     $offset       = $options->{ "offset" };
2889
2890     if ( not defined $offset ) {
2891         $offset = 0;
2892     } else {
2893         $offset--;
2894     }
2895
2896     $adaptor      = uc $options->{ "adaptor" };
2897     $adaptor_len  = length $adaptor;
2898
2899     while ( $record = Maasha::Biopieces::get_record( $in ) ) 
2900     {
2901         if ( $record->{ "SEQ" } )
2902         {
2903             $seq     = uc $record->{ "SEQ" };
2904             $seq_len = length $seq;
2905
2906             $pos = Maasha::Common::index_m( $seq, $adaptor, $seq_len, $adaptor_len, $offset, $max_mismatch );
2907
2908             $record->{ "ADAPTOR_POS" } = $pos;
2909
2910             if ( $pos >= 0 and $options->{ "remove" } ne "skip" )
2911             {
2912                 if ( $options->{ "remove" } eq "after" )
2913                 {
2914                     $record->{ "SEQ" }     = substr $record->{ "SEQ" }, 0, $pos;
2915                     $record->{ "SEQ_LEN" } = $pos;
2916                 }
2917                 else
2918                 {
2919                     $record->{ "SEQ" }     = substr $record->{ "SEQ" }, $pos + $adaptor_len;
2920                     $record->{ "SEQ_LEN" } = length $record->{ "SEQ" };
2921                 }
2922             }
2923
2924             Maasha::Biopieces::put_record( $record, $out );
2925         }
2926         else
2927         {
2928             Maasha::Biopieces::put_record( $record, $out );
2929         }
2930     }
2931 }
2932
2933
2934 sub script_remove_mysql_tables
2935 {
2936     # Martin A. Hansen, November 2008.
2937
2938     # Remove MySQL tables from values in stream.
2939
2940     my ( $in,        # handle to in stream
2941          $out,       # handle to out stream
2942          $options,   # options hash
2943        ) = @_;
2944
2945     # Returns nothing.
2946
2947     my ( $record, %table_hash, $dbh, $table );
2948
2949     $options->{ "user" }     ||= Maasha::UCSC::ucsc_get_user();
2950     $options->{ "password" } ||= Maasha::UCSC::ucsc_get_password();
2951
2952     map { $table_hash{ $_ } = 1 } @{ $options->{ 'tables' } };
2953
2954     while ( $record = Maasha::Biopieces::get_record( $in ) )
2955     {
2956         map { $table_hash{ $record->{ $_ } } = 1 } @{ $options->{ 'keys' } };
2957
2958         Maasha::Biopieces::put_record( $record, $out ) if not $options->{ 'no_stream' };
2959     }
2960
2961     $dbh = Maasha::SQL::connect( $options->{ "database" }, $options->{ "user" }, $options->{ "password" } );
2962
2963     foreach $table ( sort keys %table_hash )
2964     {
2965         if ( Maasha::SQL::table_exists( $dbh, $table ) )
2966         {
2967             print STDERR qq(Removing table "$table" from database "$options->{ 'database' }" ... ) if $options->{ 'verbose' };
2968             Maasha::SQL::delete_table( $dbh, $table );
2969             print STDERR "done.\n" if $options->{ 'verbose' };
2970         }
2971         else
2972         {
2973             print STDERR qq(WARNING: table "$table" not found in database "$options->{ 'database' }\n");
2974         }
2975     }
2976
2977     Maasha::SQL::disconnect( $dbh );
2978 }
2979
2980
2981 sub script_remove_ucsc_tracks
2982 {
2983     # Martin A. Hansen, November 2008.
2984
2985     # Remove track from MySQL tables and config file.
2986
2987     my ( $in,        # handle to in stream
2988          $out,       # handle to out stream
2989          $options,   # options hash
2990        ) = @_;
2991
2992     # Returns nothing.
2993
2994     my ( $record, %track_hash, $fh_in, $fh_out, $track, @tracks, @new_tracks, $dbh );
2995
2996     $options->{ 'user' }        ||= Maasha::UCSC::ucsc_get_user();
2997     $options->{ 'password' }    ||= Maasha::UCSC::ucsc_get_password();
2998     $options->{ 'config_file' } ||= "$ENV{ 'HOME' }/ucsc/my_tracks.ra";
2999
3000     map { $track_hash{ $_ } = 1 } @{ $options->{ 'tracks' } };
3001
3002     while ( $record = Maasha::Biopieces::get_record( $in ) )
3003     {
3004         map { $track_hash{ $record->{ $_ } } = 1 } @{ $options->{ 'keys' } };
3005
3006         Maasha::Biopieces::put_record( $record, $out ) if not $options->{ 'no_stream' };
3007     }
3008
3009     $fh_in = Maasha::Filesys::file_read_open( $options->{ 'config_file' } );
3010     
3011     while ( $track = Maasha::UCSC::ucsc_config_entry_get( $fh_in ) ) {
3012         push @tracks, $track;
3013     }
3014
3015     close $fh_in;
3016
3017     foreach $track ( @tracks )
3018     {
3019         if ( $track->{ 'database' } eq $options->{ 'database' } and exists $track_hash{ $track->{ 'track' } } ) {
3020             print STDERR qq(Removing track "$track->{ 'track' }" from config file.\n) if $options->{ 'verbose' };
3021         } else {
3022             push @new_tracks, $track;
3023         }
3024     }
3025
3026     rename "$options->{ 'config_file' }", "$options->{ 'config_file' }~";
3027
3028     $fh_out = Maasha::Filesys::file_write_open( $options->{ 'config_file' } );
3029
3030     map { Maasha::UCSC::ucsc_config_entry_put( $_, $fh_out ) } @new_tracks;
3031
3032     close $fh_out;
3033
3034     # ---- locate track in database ----
3035
3036     $dbh = Maasha::SQL::connect( $options->{ "database" }, $options->{ "user" }, $options->{ "password" } );
3037
3038     foreach $track ( sort keys %track_hash )
3039     {
3040         if ( Maasha::SQL::table_exists( $dbh, $track ) )
3041         {
3042             print STDERR qq(Removing table "$track" from database "$options->{ 'database' }" ... ) if $options->{ 'verbose' };
3043             Maasha::SQL::delete_table( $dbh, $track );
3044             print STDERR "done.\n" if $options->{ 'verbose' };
3045         }
3046         else
3047         {
3048             print STDERR qq(WARNING: table "$track" not found in database "$options->{ 'database' }\n");
3049         }
3050     }
3051
3052     Maasha::SQL::disconnect( $dbh );
3053
3054     Maasha::Common::run( "ucscMakeTracks.pl", "-b > /dev/null 2>&1" );
3055 }
3056
3057
3058 sub script_rename_keys
3059 {
3060     # Martin A. Hansen, August 2007.
3061
3062     # Rename keys in stream.
3063
3064     my ( $in,        # handle to in stream
3065          $out,       # handle to out stream
3066          $options,   # options hash
3067        ) = @_;
3068
3069     # Returns nothing.
3070
3071     my ( $record );
3072
3073     while ( $record = Maasha::Biopieces::get_record( $in ) ) 
3074     {
3075         if ( exists $record->{ $options->{ "keys" }->[ 0 ] } )
3076         {
3077             $record->{ $options->{ "keys" }->[ 1 ] } = $record->{ $options->{ "keys" }->[ 0 ] };
3078
3079             delete $record->{ $options->{ "keys" }->[ 0 ] };
3080         }
3081
3082         Maasha::Biopieces::put_record( $record, $out );
3083     }
3084 }
3085
3086
3087 sub script_uniq_vals
3088 {
3089     # Martin A. Hansen, August 2007.
3090
3091     # Find unique values in stream.
3092
3093     my ( $in,        # handle to in stream
3094          $out,       # handle to out stream
3095          $options,   # options hash
3096        ) = @_;
3097
3098     # Returns nothing.
3099
3100     my ( %hash, $record );
3101
3102     while ( $record = Maasha::Biopieces::get_record( $in ) ) 
3103     {
3104         if ( $record->{ $options->{ "key" } } )
3105         {
3106             if ( not $hash{ $record->{ $options->{ "key" } } } and not $options->{ "invert" } )
3107             {
3108                 Maasha::Biopieces::put_record( $record, $out );
3109
3110                 $hash{ $record->{ $options->{ "key" } } } = 1;
3111             }
3112             elsif ( $hash{ $record->{ $options->{ "key" } } } and $options->{ "invert" } )
3113             {
3114                 Maasha::Biopieces::put_record( $record, $out );
3115             }
3116             else
3117             {
3118                 $hash{ $record->{ $options->{ "key" } } } = 1;
3119             }
3120         }
3121         else
3122         {
3123             Maasha::Biopieces::put_record( $record, $out );
3124         }
3125     }
3126 }
3127
3128
3129 sub script_merge_vals
3130 {
3131     # Martin A. Hansen, August 2007.
3132
3133     # Rename keys in stream.
3134
3135     my ( $in,        # handle to in stream
3136          $out,       # handle to out stream
3137          $options,   # options hash
3138        ) = @_;
3139
3140     # Returns nothing.
3141
3142     my ( $record, @join, $i );
3143
3144     $options->{ "delimit" } ||= '_';
3145
3146     while ( $record = Maasha::Biopieces::get_record( $in ) ) 
3147     {
3148         if ( exists $record->{ $options->{ "keys" }->[ 0 ] } )
3149         {
3150             @join = $record->{ $options->{ "keys" }->[ 0 ] };
3151             
3152             for ( $i = 1; $i < @{ $options->{ "keys" } }; $i++ ) {
3153                 push @join, $record->{ $options->{ "keys" }->[ $i ] } if exists $record->{ $options->{ "keys" }->[ $i ] };
3154             }
3155
3156             $record->{ $options->{ "keys" }->[ 0 ] } = join $options->{ "delimit" }, @join;
3157         }
3158
3159         Maasha::Biopieces::put_record( $record, $out );
3160     }
3161 }
3162
3163
3164 sub script_merge_records
3165 {
3166     # Martin A. Hansen, July 2008.
3167
3168     # Merges records in the stream based on identical values of two given keys.
3169
3170     my ( $in,        # handle to in stream
3171          $out,       # handle to out stream
3172          $options,   # options hash
3173        ) = @_;
3174
3175     # Returns nothing.
3176
3177     my ( $merge, $record, $file1, $file2, $fh1, $fh2, $key1, $key2, @keys1, @keys2, @vals1, @vals2,
3178          $num1, $num2, $num, $cmp, $i );
3179
3180     $merge = $options->{ "merge" } || "AandB";
3181
3182     $file1 = "$BP_TMP/merge_records1.tmp";
3183     $file2 = "$BP_TMP/merge_records2.tmp";
3184
3185     $fh1   = Maasha::Common::write_open( $file1 );
3186     $fh2   = Maasha::Common::write_open( $file2 );
3187
3188     $key1  = $options->{ "keys" }->[ 0 ];
3189     $key2  = $options->{ "keys" }->[ 1 ];
3190
3191     $num   = $key2 =~ s/n$//;
3192     $num1  = 0;
3193     $num2  = 0;
3194
3195     while ( $record = Maasha::Biopieces::get_record( $in ) ) 
3196     {
3197         if ( exists $record->{ $key1 } )
3198         {
3199             @keys1 = $key1;
3200             @vals1 = $record->{ $key1 };
3201
3202             delete $record->{ $key1 };
3203
3204             map { push @keys1, $_; push @vals1, $record->{ $_ } } keys %{ $record };
3205
3206             print $fh1 join( "\t", @vals1 ), "\n";
3207
3208             $num1++;
3209         }
3210         elsif ( exists $record->{ $key2 } )
3211         {
3212             @keys2 = $key2;
3213             @vals2 = $record->{ $key2 };
3214
3215             delete $record->{ $key2 };
3216
3217             map { push @keys2, $_; push @vals2, $record->{ $_ } } keys %{ $record };
3218
3219             print $fh2 join( "\t", @vals2 ), "\n";
3220
3221             $num2++;
3222         }
3223     }
3224
3225     close $fh1;
3226     close $fh2;
3227
3228     if ( $num )
3229     {
3230         Maasha::Common::run( "sort", "-k 1,1n $file1 > $file1.sort" ) and rename "$file1.sort", $file1;
3231         Maasha::Common::run( "sort", "-k 1,1n $file2 > $file2.sort" ) and rename "$file2.sort", $file2;
3232     }
3233     else
3234     {
3235         Maasha::Common::run( "sort", "-k 1,1 $file1 > $file1.sort" ) and rename "$file1.sort", $file1;
3236         Maasha::Common::run( "sort", "-k 1,1 $file2 > $file2.sort" ) and rename "$file2.sort", $file2;
3237     }
3238
3239     $fh1 = Maasha::Common::read_open( $file1 );
3240     $fh2 = Maasha::Common::read_open( $file2 );
3241
3242     @vals1 = Maasha::Common::get_fields( $fh1 );
3243     @vals2 = Maasha::Common::get_fields( $fh2 );
3244
3245     while ( $num1 > 0 and $num2 > 0 )
3246     {
3247         undef $record;
3248
3249         if ( $num ) {
3250             $cmp = $vals1[ 0 ] <=> $vals2[ 0 ];
3251         } else {
3252             $cmp = $vals1[ 0 ] cmp $vals2[ 0 ];
3253         }
3254
3255         if ( $cmp < 0 )
3256         {
3257             if ( $merge =~ /^(AorB|AnotB)$/ )
3258             {
3259                 for ( $i = 0; $i < @keys1; $i++ ) {
3260                     $record->{ $keys1[ $i ] } = $vals1[ $i ];
3261                 }
3262
3263                 Maasha::Biopieces::put_record( $record, $out );
3264             }
3265
3266             @vals1 = Maasha::Common::get_fields( $fh1 );
3267             $num1--;
3268         }
3269         elsif ( $cmp > 0 )
3270         {
3271             if ( $merge =~ /^(BorA|BnotA)$/ )
3272             {
3273                 for ( $i = 0; $i < @keys2; $i++ ) {
3274                     $record->{ $keys2[ $i ] } = $vals2[ $i ];
3275                 }
3276
3277                 Maasha::Biopieces::put_record( $record, $out );
3278             }
3279
3280             @vals2 = Maasha::Common::get_fields( $fh2 );
3281             $num2--;
3282         }
3283         else
3284         {
3285             if ( $merge =~ /^(AandB|AorB|BorA)$/ )
3286             {
3287                 for ( $i = 0; $i < @keys1; $i++ ) {
3288                     $record->{ $keys1[ $i ] } = $vals1[ $i ];
3289                 }
3290
3291                 for ( $i = 1; $i < @keys2; $i++ ) {
3292                     $record->{ $keys2[ $i ] } = $vals2[ $i ];
3293                 }
3294             
3295                 Maasha::Biopieces::put_record( $record, $out );
3296             }
3297
3298             @vals1 = Maasha::Common::get_fields( $fh1 );
3299             @vals2 = Maasha::Common::get_fields( $fh2 );
3300             $num1--;
3301             $num2--;
3302         }
3303     }
3304
3305     close $fh1;
3306     close $fh2;
3307
3308     unlink $file1;
3309     unlink $file2;
3310
3311     if ( $num1 > 0 and $merge =~ /^(AorB|AnotB)$/ )
3312     {
3313         undef $record;
3314
3315         for ( $i = 0; $i < @keys1; $i++ ) {
3316             $record->{ $keys1[ $i ] } = $vals1[ $i ];
3317         }
3318
3319         Maasha::Biopieces::put_record( $record, $out );
3320     }
3321
3322     if ( $num2 > 0 and $merge =~ /^(BorA|BnotA)$/ )
3323     {
3324         undef $record;
3325
3326         for ( $i = 0; $i < @keys2; $i++ ) {
3327             $record->{ $keys2[ $i ] } = $vals2[ $i ];
3328         }
3329
3330         Maasha::Biopieces::put_record( $record, $out );
3331     }
3332 }
3333
3334
3335 sub script_compute
3336 {
3337     # Martin A. Hansen, August 2007.
3338
3339     # Evaluate extression for records in stream.
3340
3341     my ( $in,        # handle to in stream
3342          $out,       # handle to out stream
3343          $options,   # options hash
3344        ) = @_;
3345
3346     # Returns nothing.
3347
3348     my ( $record, $eval_key, @keys, $eval_val );
3349
3350     while ( $record = Maasha::Biopieces::get_record( $in ) ) 
3351     {
3352         if ( $options->{ "eval" } )
3353         {
3354             if ( $options->{ "eval" } =~ /^(\S+)\s*=\s*(.+)$/ )
3355             {
3356                 $eval_key = $1;
3357                 $eval_val = $2;
3358
3359                 if ( not @keys )
3360                 {
3361                     @keys = split /\s+|\+|-|\*|\/|\*\*/, $eval_val;
3362
3363                     @keys = grep { exists $record->{ $_ } } @keys;
3364                 }
3365
3366                 map { $eval_val =~ s/\Q$_\E/$record->{ $_ }/g } @keys;
3367
3368                 $record->{ $eval_key } = eval "$eval_val";
3369                 Maasha::Common::error( qq(eval "$eval_key = $eval_val" failed -> $@) ) if $@;
3370             }
3371             else
3372             {
3373                 Maasha::Common::error( qq(Bad compute expression: "$options->{ 'eval' }"\n) );
3374             }
3375         } 
3376
3377         Maasha::Biopieces::put_record( $record, $out );
3378     }
3379 }
3380
3381
3382 sub script_flip_tab
3383 {
3384     # Martin A. Hansen, June 2008.
3385
3386     # Flip a table.
3387
3388     my ( $in,        # handle to in stream
3389          $out,       # handle to out stream
3390          $options,   # options hash
3391        ) = @_;
3392
3393     # Returns nothing.
3394
3395     my ( $record, $key, $A, $B, @rows, @matrix, $row, $i );
3396
3397     while ( $record = Maasha::Biopieces::get_record( $in ) ) 
3398     {
3399         undef @rows;
3400
3401         foreach $key ( sort { $A = $a; $B = $b; $A =~ s/^V(\d+)$/$1/; $B =~ s/^V(\d+)$/$1/; $A <=> $B } keys %{ $record } )
3402         {
3403             push @rows, $record->{ $key };
3404
3405         }
3406
3407         push @matrix, [ @rows ];
3408     }
3409
3410     undef $record;
3411
3412     @matrix = Maasha::Matrix::matrix_flip( \@matrix );
3413
3414     foreach $row ( @matrix )
3415     {
3416         for ( $i = 0; $i < @{ $row }; $i++ ) {
3417             $record->{ "V$i" } = $row->[ $i ];
3418         }
3419
3420         Maasha::Biopieces::put_record( $record, $out );
3421     }
3422 }
3423
3424
3425 sub script_sort_records
3426 {
3427     # Martin A. Hansen, August 2007.
3428
3429     # Sort to sort records according to keys.
3430
3431     my ( $in,        # handle to in stream
3432          $out,       # handle to out stream
3433          $options,   # options hash
3434        ) = @_;
3435
3436     # Returns nothing.
3437
3438     my ( @keys, $key, @sort_cmd, $sort_str, $sort_sub, @records, $record, $i );
3439
3440     foreach $key ( @{ $options->{ "keys" } } )
3441     {
3442         if ( $key =~ s/n$// ) {
3443             push @sort_cmd, qq(\$a->{ "$key" } <=> \$b->{ "$key" });
3444         } else {
3445             push @sort_cmd, qq(\$a->{ "$key" } cmp \$b->{ "$key" });
3446         }
3447     }
3448
3449     $sort_str = join " or ", @sort_cmd;
3450     $sort_sub = eval "sub { $sort_str }";   # NB security issue!
3451
3452     while ( $record = Maasha::Biopieces::get_record( $in ) ) {
3453         push @records, $record;
3454     }
3455
3456     @records = sort $sort_sub @records;
3457
3458     if ( $options->{ "reverse" } )
3459     {
3460         for ( $i = scalar @records - 1; $i >= 0; $i-- ) {
3461             Maasha::Biopieces::put_record( $records[ $i ], $out );
3462         }
3463     }
3464     else
3465     {
3466         for ( $i = 0; $i < scalar @records; $i++ ) {
3467             Maasha::Biopieces::put_record( $records[ $i ], $out );
3468         }
3469     }
3470 }
3471
3472
3473 sub script_count_vals
3474 {
3475     # Martin A. Hansen, August 2007.
3476
3477     # Count records in stream.
3478
3479     my ( $in,        # handle to in stream
3480          $out,       # handle to out stream
3481          $options,   # options hash
3482        ) = @_;
3483
3484     # Returns nothing.
3485
3486     my ( $num, $record, %count_hash, @records, $tmp_file, $fh_out, $fh_in, $cache );
3487
3488     $tmp_file = "$BP_TMP/count_cache.tmp";
3489
3490     $fh_out   = Maasha::Common::write_open( $tmp_file );
3491
3492     $cache    = 0;
3493     $num      = 0;
3494
3495     while ( $record = Maasha::Biopieces::get_record( $in ) ) 
3496     {
3497         map { $count_hash{ $_ }{ $record->{ $_ } }++ if exists $record->{ $_ } } @{ $options->{ "keys" } };
3498
3499         push @records, $record;
3500
3501         if ( scalar @records > 5_000_000 )   # too many records to hold in memory - use disk cache
3502         {
3503             map { Maasha::Biopieces::put_record( $_, $fh_out ) } @records;
3504
3505             undef @records;
3506
3507             $cache = 1;
3508         }
3509
3510         print STDERR "verbose: records read $num\n" if ( $options->{ 'verbose' } and ( $num % 1_000_000 ) == 0 );
3511
3512         $num++;
3513     }
3514
3515     close $fh_out;
3516
3517     if ( $cache )
3518     {
3519         $num   = 0;
3520
3521         $fh_in = Maasha::Common::read_open( $tmp_file );
3522
3523         while ( $record = Maasha::Biopieces::get_record( $fh_in ) )
3524         {
3525             map { $record->{ $_ . "_COUNT" } = $count_hash{ $_ }{ $record->{ $_ } } if exists $record->{ $_ } } @{ $options->{ "keys" } };
3526
3527             Maasha::Biopieces::put_record( $record, $out );
3528
3529             print STDERR "verbose: cache read $num\n" if ( $options->{ 'verbose' } and ( $num % 1_000_000 ) == 0 );
3530
3531             $num++;
3532         }
3533     
3534         close $fh_in;
3535     }
3536
3537     foreach $record ( @records )
3538     {
3539         map { $record->{ $_ . "_COUNT" } = $count_hash{ $_ }{ $record->{ $_ } } if exists $record->{ $_ } } @{ $options->{ "keys" } };
3540
3541         Maasha::Biopieces::put_record( $record, $out );
3542     }
3543
3544     unlink $tmp_file;
3545 }
3546
3547
3548 sub script_plot_histogram
3549 {
3550     # Martin A. Hansen, September 2007.
3551
3552     # Plot a simple histogram for a given key using GNU plot.
3553
3554     my ( $in,        # handle to in stream
3555          $out,       # handle to out stream
3556          $options,   # options hash
3557        ) = @_;
3558
3559     # Returns nothing.
3560
3561     my ( $record, %data_hash, $max, @data_list, $i, $result, $fh );
3562
3563     $options->{ "title" } ||= "Histogram";
3564     $options->{ "sort" }  ||= "num";
3565
3566     while ( $record = Maasha::Biopieces::get_record( $in ) ) 
3567     {
3568         $data_hash{ $record->{ $options->{ "key" } } }++ if defined $record->{ $options->{ "key" } };
3569
3570         Maasha::Biopieces::put_record( $record, $out ) if not $options->{ "no_stream" };
3571     }
3572
3573     if ( $options->{ "sort" } eq "num" ) {
3574         map { push @data_list, [ $_, $data_hash{ $_ } ] } sort { $a <=> $b } keys %data_hash;
3575     } else {
3576         map { push @data_list, [ $_, $data_hash{ $_ } ] } sort keys %data_hash;
3577     }
3578
3579     $result = Maasha::Plot::histogram_simple( \@data_list, $options );
3580
3581     $fh = write_stream( $options->{ "data_out" } );
3582
3583     print $fh "$_\n" foreach @{ $result };
3584
3585     close $fh;
3586 }
3587
3588
3589 sub script_plot_lendist
3590 {
3591     # Martin A. Hansen, August 2007.
3592
3593     # Plot length distribution using GNU plot.
3594
3595     my ( $in,        # handle to in stream
3596          $out,       # handle to out stream
3597          $options,   # options hash
3598        ) = @_;
3599
3600     # Returns nothing.
3601
3602     my ( $record, %data_hash, $max, @data_list, $i, $result, $fh );
3603
3604     $options->{ "title" } ||= "Length Distribution";
3605
3606     while ( $record = Maasha::Biopieces::get_record( $in ) ) 
3607     {
3608         $data_hash{ $record->{ $options->{ "key" } } }++ if defined $record->{ $options->{ "key" } };
3609
3610         Maasha::Biopieces::put_record( $record, $out ) if not $options->{ "no_stream" };
3611     }
3612
3613     $max = Maasha::Calc::list_max( [ keys %data_hash ] );
3614
3615     for ( $i = 0; $i < $max; $i++ ) {
3616         push @data_list, [ $i, $data_hash{ $i } || 0 ];
3617     }
3618
3619     $result = Maasha::Plot::histogram_lendist( \@data_list, $options );
3620
3621     $fh = write_stream( $options->{ "data_out" } );
3622
3623     print $fh "$_\n" foreach @{ $result };
3624
3625     close $fh;
3626 }
3627
3628
3629 sub script_plot_chrdist
3630 {
3631     # Martin A. Hansen, August 2007.
3632
3633     # Plot chromosome distribution using GNU plot.
3634
3635     my ( $in,        # handle to in stream
3636          $out,       # handle to out stream
3637          $options,   # options hash
3638        ) = @_;
3639
3640     # Returns nothing.
3641
3642     my ( $record, %data_hash, @data_list, $elem, $sort_key, $count, $result, $fh );
3643
3644     $options->{ "title" } ||= "Chromosome Distribution";
3645
3646     while ( $record = Maasha::Biopieces::get_record( $in ) ) 
3647     {
3648         if ( $record->{ "CHR" } ) {                                                             # generic
3649             $data_hash{ $record->{ "CHR" } }++;
3650         } elsif ( $record->{ "REC_TYPE" } eq "PATSCAN" and $record->{ "S_ID" } =~ /^chr/i ) {   # patscan
3651             $data_hash{ $record->{ "S_ID" } }++;
3652         } elsif ( $record->{ "REC_TYPE" } eq "PSL" and $record->{ "S_ID" } =~ /^chr/i ) {       # BLAT / PSL
3653             $data_hash{ $record->{ "S_ID" } }++;
3654         } elsif ( $record->{ "REC_TYPE" } eq "BLAST" and $record->{ "S_ID" } =~ /^chr/i ) {     # BLAST
3655             $data_hash{ $record->{ "S_ID" } }++;
3656         }
3657
3658         Maasha::Biopieces::put_record( $record, $out ) if not $options->{ "no_stream" };
3659     }
3660
3661     foreach $elem ( keys %data_hash )
3662     {
3663         $sort_key = $elem;
3664
3665         $sort_key =~ s/chr//i;
3666     
3667         $sort_key =~ s/^X(.*)/99$1/;
3668         $sort_key =~ s/^Y(.*)/99$1/;
3669         $sort_key =~ s/^Z(.*)/999$1/;
3670         $sort_key =~ s/^M(.*)/9999$1/;
3671         $sort_key =~ s/^U(.*)/99999$1/;
3672
3673         $count = $sort_key =~ tr/_//;
3674
3675         $sort_key =~ s/_.*/"999999" x $count/ex;
3676
3677         push @data_list, [ $elem, $data_hash{ $elem }, $sort_key ];
3678     }
3679
3680     @data_list = sort { $a->[ 2 ] <=> $b->[ 2 ] } @data_list;
3681
3682     $result = Maasha::Plot::histogram_chrdist( \@data_list, $options );
3683
3684     $fh = write_stream( $options->{ "data_out" } );
3685
3686     print $fh "$_\n" foreach @{ $result };
3687
3688     close $fh;
3689 }
3690
3691
3692 sub script_plot_karyogram
3693 {
3694     # Martin A. Hansen, August 2007.
3695
3696     # Plot hits on karyogram.
3697
3698     my ( $in,        # handle to in stream
3699          $out,       # handle to out stream
3700          $options,   # options hash
3701        ) = @_;
3702
3703     # Returns nothing.
3704
3705     my ( %options, $record, @data, $fh, $result, %data_hash );
3706
3707     $options->{ "genome" }     ||= "human";
3708     $options->{ "feat_color" } ||= "black";
3709
3710     while ( $record = Maasha::Biopieces::get_record( $in ) ) 
3711     {
3712         if ( $record->{ "CHR" } and $record->{ "CHR_BEG" } and $record->{ "CHR_END" } )
3713         {
3714             push @{ $data_hash{ $record->{ "CHR" } } }, [ $record->{ "CHR_BEG" }, $record->{ "CHR_END" }, $options->{ "feat_color" } ];
3715         }
3716
3717         Maasha::Biopieces::put_record( $record, $out ) if not $options->{ "no_stream" };
3718     }
3719
3720     $result = Maasha::Plot::karyogram( \%data_hash, \%options );
3721
3722     $fh = write_stream( $options->{ "data_out" } );
3723
3724     print $fh $result;
3725
3726     close $fh;
3727 }
3728
3729
3730 sub script_plot_matches
3731 {
3732     # Martin A. Hansen, August 2007.
3733
3734     # Plot matches in 2D generating a dotplot.
3735
3736     my ( $in,        # handle to in stream
3737          $out,       # handle to out stream
3738          $options,   # options hash
3739        ) = @_;
3740
3741     # Returns nothing.
3742
3743     my ( $record, @data, $fh, $result, %data_hash );
3744
3745     $options->{ "direction" } ||= "both";
3746
3747     while ( $record = Maasha::Biopieces::get_record( $in ) ) 
3748     {
3749         if ( defined $record->{ "Q_BEG" } and defined $record->{ "S_BEG" } and $record->{ "Q_END" } and $record->{ "S_END" } ) {
3750             push @data, $record;
3751         }
3752
3753         Maasha::Biopieces::put_record( $record, $out ) if not $options->{ "no_stream" };
3754     }
3755
3756     $options->{ "title" }  ||= "plot_matches";
3757     $options->{ "xlabel" } ||= $data[ 0 ]->{ "Q_ID" };
3758     $options->{ "ylabel" } ||= $data[ 0 ]->{ "S_ID" };
3759
3760     $result = Maasha::Plot::dotplot_matches( \@data, $options, $BP_TMP );
3761
3762     $fh = write_stream( $options->{ "data_out" } );
3763
3764     print $fh "$_\n" foreach @{ $result };
3765
3766     close $fh;
3767 }
3768
3769
3770 sub script_length_vals
3771 {
3772     # Martin A. Hansen, August 2007.
3773
3774     # Determine the length of the value for given keys.
3775
3776     my ( $in,        # handle to in stream
3777          $out,       # handle to out stream
3778          $options,   # options hash
3779        ) = @_;
3780
3781     # Returns nothing.
3782
3783     my ( $record, $key );
3784
3785     while ( $record = Maasha::Biopieces::get_record( $in ) ) 
3786     {
3787         foreach $key ( @{ $options->{ "keys" } } )
3788         {
3789             if ( $record->{ $key } ) {
3790                 $record->{ $key . "_LEN" } = length $record->{ $key };
3791             }
3792         }
3793
3794         Maasha::Biopieces::put_record( $record, $out );
3795     }
3796 }
3797
3798
3799 sub script_sum_vals
3800 {
3801     # Martin A. Hansen, August 2007.
3802
3803     # Calculates the sums for values of given keys.
3804
3805     my ( $in,        # handle to in stream
3806          $out,       # handle to out stream
3807          $options,   # options hash
3808        ) = @_;
3809
3810     # Returns nothing.
3811
3812     my ( $record, $key, %sum_hash, $fh );
3813
3814     while ( $record = Maasha::Biopieces::get_record( $in ) ) 
3815     {
3816         foreach $key ( @{ $options->{ "keys" } } )
3817         {
3818             if ( $record->{ $key } ) {
3819                 $sum_hash{ $key } += $record->{ $key };
3820             }
3821         }
3822
3823         Maasha::Biopieces::put_record( $record, $out ) if not $options->{ "no_stream" };
3824     }
3825
3826     $fh = write_stream( $options->{ "data_out" } );
3827
3828     foreach $key ( @{ $options->{ "keys" } } ) {
3829         Maasha::Biopieces::put_record( { $key . "_SUM" => $sum_hash{ $key } || 0 } , $fh );
3830     }
3831
3832     close $fh;
3833 }
3834
3835
3836 sub script_mean_vals
3837 {
3838     # Martin A. Hansen, August 2007.
3839
3840     # Calculate the mean of values of given keys.
3841
3842     my ( $in,        # handle to in stream
3843          $out,       # handle to out stream
3844          $options,   # options hash
3845        ) = @_;
3846
3847     # Returns nothing.
3848
3849     my ( $record, $key, %sum_hash, %count_hash, $mean, $fh );
3850
3851     while ( $record = Maasha::Biopieces::get_record( $in ) ) 
3852     {
3853         foreach $key ( @{ $options->{ "keys" } } )
3854         {
3855             if ( $record->{ $key } )
3856             {
3857                 $sum_hash{ $key } += $record->{ $key };
3858                 $count_hash{ $key }++;
3859             }
3860         }
3861
3862         Maasha::Biopieces::put_record( $record, $out ) if not $options->{ "no_stream" };
3863     }
3864
3865     $fh = write_stream( $options->{ "data_out" } );
3866
3867     foreach $key ( @{ $options->{ "keys" } } )
3868     {
3869         if ( $count_hash{ $key } ) {
3870             $mean = sprintf( "%.2f", ( $sum_hash{ $key } / $count_hash{ $key } ) );
3871         } else {
3872             $mean = "N/A";
3873         }
3874
3875         Maasha::Biopieces::put_record( { $key . "_MEAN" => $mean } , $fh );
3876     }
3877
3878     close $fh;
3879 }
3880
3881
3882 sub script_median_vals
3883 {
3884     # Martin A. Hansen, March 2008.
3885
3886     # Calculate the median values of given keys.
3887
3888     my ( $in,        # handle to in stream
3889          $out,       # handle to out stream
3890          $options,   # options hash
3891        ) = @_;
3892
3893     # Returns nothing.
3894
3895     my ( $record, $key, %median_hash, $median, $fh );
3896
3897     while ( $record = Maasha::Biopieces::get_record( $in ) ) 
3898     {
3899         foreach $key ( @{ $options->{ "keys" } } ) {
3900             push @{ $median_hash{ $key } }, $record->{ $key } if defined $record->{ $key };
3901         }
3902
3903         Maasha::Biopieces::put_record( $record, $out ) if not $options->{ "no_stream" };
3904     }
3905
3906     $fh = write_stream( $options->{ "data_out" } );
3907
3908     foreach $key ( @{ $options->{ "keys" } } )
3909     {
3910         if ( $median_hash{ $key } ) {
3911             $median = Maasha::Calc::median( $median_hash{ $key } );
3912         } else {
3913             $median = "N/A";
3914         }
3915
3916         Maasha::Biopieces::put_record( { $key . "_MEDIAN" => $median } , $fh );
3917     }
3918
3919     close $fh;
3920 }
3921
3922
3923 sub script_max_vals
3924 {
3925     # Martin A. Hansen, February 2008.
3926
3927     # Determine the maximum values of given keys.
3928
3929     my ( $in,        # handle to in stream
3930          $out,       # handle to out stream
3931          $options,   # options hash
3932        ) = @_;
3933
3934     # Returns nothing.
3935
3936     my ( $record, $key, $fh, %max_hash, $max_record );
3937
3938     while ( $record = Maasha::Biopieces::get_record( $in ) ) 
3939     {
3940         foreach $key ( @{ $options->{ "keys" } } )
3941         {
3942             if ( $record->{ $key } )
3943             {
3944                 $max_hash{ $key } = $record->{ $key } if $record->{ $key } > $max_hash{ $key };
3945             }
3946         }
3947
3948         Maasha::Biopieces::put_record( $record, $out ) if not $options->{ "no_stream" };
3949     }
3950
3951     $fh = write_stream( $options->{ "data_out" } );
3952
3953     foreach $key ( @{ $options->{ "keys" } } )
3954     {
3955         $max_record->{ $key . "_MAX" } = $max_hash{ $key };
3956     }
3957
3958     Maasha::Biopieces::put_record( $max_record, $fh );
3959
3960     close $fh;
3961 }
3962
3963
3964 sub script_min_vals
3965 {
3966     # Martin A. Hansen, February 2008.
3967
3968     # Determine the minimum values of given keys.
3969
3970     my ( $in,        # handle to in stream
3971          $out,       # handle to out stream
3972          $options,   # options hash
3973        ) = @_;
3974
3975     # Returns nothing.
3976
3977     my ( $record, $key, $fh, %min_hash, $min_record );
3978
3979     while ( $record = Maasha::Biopieces::get_record( $in ) ) 
3980     {
3981         foreach $key ( @{ $options->{ "keys" } } )
3982         {
3983             if ( defined $record->{ $key } )
3984             {
3985                 if ( exists $min_hash{ $key } ) {
3986                     $min_hash{ $key } = $record->{ $key } if $record->{ $key } < $min_hash{ $key };
3987                 } else {
3988                     $min_hash{ $key } = $record->{ $key }; 
3989                 }
3990             }
3991         }
3992
3993         Maasha::Biopieces::put_record( $record, $out ) if not $options->{ "no_stream" };
3994     }
3995
3996     $fh = write_stream( $options->{ "data_out" } );
3997
3998     foreach $key ( @{ $options->{ "keys" } } )
3999     {
4000         $min_record->{ $key . "_MIN" } = $min_hash{ $key };
4001     }
4002
4003     Maasha::Biopieces::put_record( $min_record, $fh );
4004
4005     close $fh;
4006 }
4007
4008
4009 sub script_upload_to_ucsc
4010 {
4011     # Martin A. Hansen, August 2007.
4012
4013     # Calculate the mean of values of given keys.
4014
4015     # This routine has developed into the most ugly hack. Do something!
4016
4017     my ( $in,        # handle to in stream
4018          $out,       # handle to out stream
4019          $options,   # options hash
4020        ) = @_;
4021
4022     # Returns nothing.
4023
4024     my ( $record, $file, $wib_file, $wig_file, $wib_dir, $fh_out, $i, $first, $format, $type, $columns, $append, $entry );
4025
4026     $options->{ "short_label" } ||= $options->{ 'table' };
4027     $options->{ "long_label" }  ||= $options->{ 'table' };
4028     $options->{ "group" }       ||= $ENV{ "LOGNAME" };
4029     $options->{ "priority" }    ||= 1;
4030     $options->{ "visibility" }  ||= "pack";
4031     $options->{ "color" }       ||= join( ",", int( rand( 255 ) ), int( rand( 255 ) ), int( rand( 255 ) ) );
4032     $options->{ "chunk_size" }  ||= 10_000_000_000;    # Due to 32-bit UCSC compilation really large tables cannot be loaded in one go.
4033
4034     $file   = "$BP_TMP/ucsc_upload.tmp";
4035     $append = 0;
4036     $first  = 1;
4037     $i      = 0;
4038
4039     $fh_out = Maasha::Common::write_open( $file );
4040
4041     while ( $record = Maasha::Biopieces::get_record( $in ) ) 
4042     {
4043         Maasha::Biopieces::put_record( $record, $out ) if not $options->{ "no_stream" };
4044
4045         if ( $record->{ "REC_TYPE" } eq "fixed_step" )
4046         {
4047             $format = "WIGGLE";
4048
4049             if ( $entry = Maasha::UCSC::Wiggle::biopiece2fixedstep( $record ) ) {
4050                 Maasha::UCSC::Wiggle::fixedstep_entry_put( $entry, $fh_out );
4051             }
4052         }
4053         elsif ( $record->{ "REC_TYPE" } eq "PSL" )
4054         {
4055             $format = "PSL";
4056
4057             Maasha::UCSC::psl_put_header( $fh_out ) if $first;
4058             Maasha::UCSC::psl_put_entry( $record, $fh_out );
4059             
4060             $first = 0;
4061         }
4062         elsif ( $record->{ "REC_TYPE" } eq "BED" and $record->{ "SEC_STRUCT" } )
4063         {
4064             # chrom chromStart  chromEnd    name    score   strand  size    secStr  conf 
4065
4066             $format  = "BED_SS";
4067
4068             print $fh_out join ( "\t",
4069                 $record->{ "CHR" },
4070                 $record->{ "CHR_BEG" },
4071                 $record->{ "CHR_END" } + 1,
4072                 $record->{ "Q_ID" },
4073                 $record->{ "SCORE" },
4074                 $record->{ "STRAND" },
4075                 $record->{ "SIZE" },
4076                 $record->{ "SEC_STRUCT" },
4077                 $record->{ "CONF" },
4078             ), "\n";
4079         }
4080         elsif ( $record->{ "REC_TYPE" } eq "BED" )
4081         {
4082             $format  = "BED";
4083             $columns = $record->{ "BED_COLS" };
4084
4085             if ( $entry = Maasha::UCSC::BED::biopiece2bed( $record, $columns ) ) {
4086                 Maasha::UCSC::BED::bed_entry_put( $entry, $fh_out, $columns, $options->{ 'check' } );
4087             }
4088         }
4089         elsif ( $record->{ "REC_TYPE" } eq "PATSCAN" and $record->{ "CHR" } )
4090         {
4091             $format  = "BED";
4092             $columns = 6;
4093
4094             if ( $entry = Maasha::UCSC::BED::biopiece2bed( $record, $columns ) ) {
4095                 Maasha::UCSC::BED::bed_entry_put( $entry, $fh_out, $columns, $options->{ 'check' } );
4096             }
4097         }
4098         elsif ( $record->{ "REC_TYPE" } eq "BLAST" and $record->{ "S_ID" } =~ /^chr/ )
4099         {
4100             $format  = "BED";
4101             $columns = 6;
4102
4103             $record->{ "SCORE" } = $record->{ "BIT_SCORE" } * 1000;
4104
4105             if ( $entry = Maasha::UCSC::BED::biopiece2bed( $record, $columns ) ) {
4106                 Maasha::UCSC::BED::bed_entry_put( $entry, $fh_out, $columns, $options->{ 'check' } );
4107             }
4108         }
4109         elsif ( $record->{ "REC_TYPE" } eq "VMATCH" and $record->{ "S_ID" } =~ /^chr/i )
4110         {
4111             $format  = "BED";
4112             $columns = 6;
4113
4114             if ( $entry = Maasha::UCSC::BED::biopiece2bed( $record, $columns ) ) {
4115                 Maasha::UCSC::BED::bed_entry_put( $entry, $fh_out, $columns, $options->{ 'check' } );
4116             }
4117         }
4118
4119         if ( $i == $options->{ "chunk_size" } )
4120         {
4121             close $fh_out;
4122
4123             if ( $format eq "BED" ) {
4124                 Maasha::UCSC::bed_upload_to_ucsc( $BP_TMP, $file, $options, $append );
4125             } elsif ( $format eq "PSL" ) {
4126                 Maasha::UCSC::psl_upload_to_ucsc( $file, $options, $append ); 
4127             }
4128
4129             unlink $file;
4130
4131             $first = 1;
4132
4133             $append = 1;
4134
4135             $fh_out = Maasha::Common::write_open( $file );
4136         }
4137
4138         $i++;
4139     }
4140
4141     close $fh_out;
4142
4143     if ( exists $options->{ "database" } and $options->{ "table" } )
4144     {
4145         if ( $format eq "BED" )
4146         {
4147             $type = "bed $columns";
4148
4149             Maasha::UCSC::bed_upload_to_ucsc( $BP_TMP, $file, $options, $append );
4150         }
4151         elsif ( $format eq "BED_SS" )
4152         {
4153             $type = "type bed 6 +";
4154         
4155             Maasha::UCSC::bed_upload_to_ucsc( $BP_TMP, $file, $options, $append );
4156         }
4157         elsif ( $format eq "PSL" )
4158         {
4159             $type = "psl";
4160
4161             Maasha::UCSC::psl_upload_to_ucsc( $file, $options, $append ); 
4162         }
4163         elsif ( $format eq "WIGGLE" )
4164         {
4165             $options->{ "visibility" } = "full";
4166
4167             $wig_file = "$options->{ 'table' }.wig";
4168             $wib_file = "$options->{ 'table' }.wib";
4169
4170             $wib_dir  = "$ENV{ 'HOME' }/ucsc/wib";
4171
4172             Maasha::Common::dir_create_if_not_exists( $wib_dir );
4173
4174             if ( $options->{ 'verbose' } ) {
4175                 `cd $BP_TMP && wigEncode $file $wig_file $wib_file`;
4176             } else {
4177                 `cd $BP_TMP && wigEncode $file $wig_file $wib_file > /dev/null 2>&1`;
4178             }
4179
4180             Maasha::Common::run( "mv", "$BP_TMP/$wib_file $wib_dir" );
4181
4182             unlink $file;
4183
4184             $file = $wig_file;
4185
4186             $type = "wig 0";
4187
4188             Maasha::UCSC::wiggle_upload_to_ucsc( $BP_TMP, $wib_dir, $file, $options );
4189         }
4190
4191         unlink $file;
4192
4193         Maasha::UCSC::ucsc_update_config( $options, $type );
4194     }
4195 }
4196
4197
4198 # >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>><<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
4199
4200 1;
4201
4202 __END__
4203