• Publicidad

Eliminar archivos vacíos en subrutina

Perl aplicado a la bioinformática

Eliminar archivos vacíos en subrutina

Notapor abraham03 » 2017-01-24 18:50 @826

Hola, ¿qué tal?

Tengo este script que convierte un archivo fastq o una carpeta con varios archivos fastq en formato fasta.

Una de las opciones que agregué es la de definir el número de NNN repeticiones (NNNNNNNNNNNNNNNNNNATAGTGAAGAATGCGACGTACAGGATCATCTA), las cuales pueden excluirse si tienen un número determinado de letras 'N'. Ejemplo: si la opción -n es igual a 15 (-n 15) el script excluye a todas las secuencias que tengan 15 o más veces repetida la letra 'N'.

El problema que tengo es que en este caso algunos de los archivos fasta no presentan secuencias porque todas presentaron un número mayor del especificado y por lo cual son excluidas. Debido a ello quiero que esos archivos vacíos (sin secuencias) se eliminen, pero no he podido agregar un código que me resuelva el problema.

Código:
Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
  1. #!/usr/bin/env perl
  2. use strict;
  3. use warnings;
  4. use Getopt::Long;
  5.  
  6. my ($infile, $file_name, $file_format, $N_repeat, $help, $help_descp,
  7.     $options, $options_descrp, $nofile, $new_file, $count);
  8.  
  9. my $fastq_extension = "\\.fastq";
  10.  
  11. GetOptions (
  12.     'in=s'      => \$infile,
  13.     'N|n=i'     =>\$N_repeat,
  14.     'h|help'    =>\$help,
  15.     'op'        =>\$options
  16. );
  17.  
  18.  # Help
  19.  
  20.  $help_descp =(qq(              
  21.               Ussaje:
  22.               fastQF -in fastq_folder/ -n 15
  23.                       or
  24.               fastQF -in file.fastq -n 15
  25.               ));
  26.  
  27.  $options_descrp =(qq(
  28.                    
  29.             -in      infile.fastq or fastq_folder/                  required
  30.             -n       exclude sequences with more than N repeat      optional
  31.             -h       Help description                               optional
  32.             -op      option section                                 optional
  33.                    ));
  34.  
  35.  $nofile =(qq(
  36.             ERROR:  "No File or Folder Were Chosen !"
  37.            
  38.                 Usage:
  39.                     fastQF -in folder/
  40.                    
  41.                 Or See -help or -op section
  42.            ));
  43.  
  44.  # Check Files
  45.  
  46.     if ($help){
  47.         print "$help_descp\n";
  48.         exit;
  49.     }
  50.     elsif ($options){
  51.         print "$options_descrp\n";
  52.         exit;
  53.     }
  54.  
  55.     elsif (!$infile){
  56.         print "$nofile\n";
  57.         exit;
  58.     }
  59.  
  60.  
  61.  #Subroutine to convert from fastq to fasta
  62.  
  63.     sub fastq_fasta {
  64.        
  65.         my $file = shift;
  66.         ($file_name = $file) =~ s/(.*)$fastq_extension.*/$1/;
  67.  
  68. # eliminate old files
  69.  
  70.         my $oldfiles = $file_name.".fasta";
  71.    
  72.         if ($oldfiles){
  73.             unlink $oldfiles;
  74.         }
  75.    
  76.         open LINE,    '<',   $file             or die "can't read or open $file\n";
  77.         open OUTFILE, '>>', "$file_name.fasta" or die "can't write $file_name\n";
  78.  
  79.         while (
  80.             defined(my $head    = <LINE>)       &&
  81.             defined(my $seq     = <LINE>)       &&
  82.             defined(my $qhead   = <LINE>)       &&
  83.             defined(my $quality = <LINE>)
  84.         ) {
  85.                 substr($head, 0, 1, '>');
  86.                
  87.                
  88.                 if (!$N_repeat){
  89.                     print OUTFILE $head, $seq;
  90.                      
  91.                    
  92.                 }
  93.                
  94.                 elsif ($N_repeat){
  95.  
  96.                         my $number_n=$N_repeat-1;
  97.  
  98.                     if ($seq=~ m/(n)\1{$number_n}/ig){
  99.                         next;
  100.                     }
  101.                     else{
  102.                         print OUTFILE $head, $seq;
  103.                     }
  104.                 }
  105.         }
  106.        
  107.         close OUTFILE;
  108.         close LINE;
  109.     }
  110.  
  111.  # execute the subrutine to extract the sequences
  112.  
  113.     if (-f $infile) {           # -f es para folder !!
  114.         fastq_fasta($infile);
  115.     }
  116.     else {
  117.         foreach my $file (glob("$infile/*.fastq")) {
  118.         fastq_fasta($file);
  119.         }
  120.     }
  121.    
  122. exit;
Coloreado en 0.004 segundos, usando GeSHi 1.0.8.4


He intentado agregar un @rray dentro y fuera de la subrutina, pero no me ha funcionado, siempre me elimina solo el último archivo:
Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
  1. @new_file =$file_name.".fasta";
  2.         foreach (@new_file){
  3.            
  4.             if (-z $_) {
  5.                 $count++;
  6.                 if ($count==1){
  7.                     print "\n\"The choosen File present not sequences\"\n";
  8.                     print " \"or was excluded due to -n $N_repeat\"\n\n";
  9.                
  10.                 }
  11.                 elsif ($count >=1){
  12.                     print "\n\"$count Files present not sequences\"\n";
  13.                     print " \" or were excluded due to -n $N_repeat\"\n\n";
  14.                    
  15.                 }
  16.                
  17.                 unlink $new_file;
  18.             }
  19.         }
Coloreado en 0.001 segundos, usando GeSHi 1.0.8.4

Muchas gracias.
abraham03
Perlero nuevo
Perlero nuevo
 
Mensajes: 19
Registrado: 2016-08-05 15:52 @703

Publicidad

Re: Eliminar archivos vacíos en subrutina

Notapor explorer » 2017-01-25 09:51 @452

Una forma de hacerlo es no sacar nada al archivo resultado hasta que no estemos seguros de que sí tenemos un resultado. Es decir: vamos guardando en memoria las líneas del archivo resultado, y luego lo grabamos de golpe (no probado):
Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
  1. sub fastq_fasta {
  2.  
  3.     my $file = shift;
  4.     (my $file_new = $file) =~ s/^(.*)$fastq_extension.*$/$1/;
  5.     $file_new = "$file_new.fasta";
  6.  
  7.     # eliminate old files
  8.     if (-f $file_new) {
  9.         unlink $file_new;
  10.     }
  11.  
  12.     return if not $N_repeat;                    # si no hay repetición, salimos
  13.  
  14.     my $result;
  15.  
  16.     open LINE, '<', $file               or die "can't read file $file\n";
  17.  
  18.     while ( defined(my $head    = <LINE>)
  19.         and defined(my $seq     = <LINE>)
  20.         and defined(my $qhead   = <LINE>)
  21.         and defined(my $quality = <LINE>)
  22.     ) {
  23.         next if $seq =~ m/n{$N_repeat}/i;       # si hay n-repeticiones (o más), salta a la siguiente línea
  24.  
  25.         $result .= ">$head$seq";                # si no, vamos acumulando el resultado
  26.     }
  27.  
  28.     close LINE;
  29.  
  30.     if ($result) {                              # si hay algo, lo guardamos
  31.         open  OUTFILE, '>', $file_new   or die "can't write file $file_new\n";
  32.         print OUTFILE $result;
  33.         close OUTFILE;
  34.     }
  35. }
  36.  
Coloreado en 0.003 segundos, usando GeSHi 1.0.8.4
JF^D Perl programming & Raku programming. Grupo en Telegram: https://t.me/Perl_ES
Avatar de Usuario
explorer
Administrador
Administrador
 
Mensajes: 14476
Registrado: 2005-07-24 18:12 @800
Ubicación: Valladolid, España


Volver a Bioinformática

¿Quién está conectado?

Usuarios navegando por este Foro: No hay usuarios registrados visitando el Foro y 5 invitados