The Bioperl toolkit : Perl modules for the life sciences

51
The Bioperl toolkit The Bioperl toolkit : : Perl modules for the life Perl modules for the life sciences sciences Daniel Guariz Pinheiro, PhD. L L aboratório de aboratório de G G enética enética M M olecular e olecular e B B ioinformática ioinformática + DBI + DBI + CGI + CGI

description

The Bioperl toolkit : Perl modules for the life sciences. + DBI + CGI. L aboratório de G enética M olecular e B ioinformática. Daniel Guariz Pinheiro, PhD. O pen B ioinformatics F oundation. Introdução. O que é BioPerl ? - PowerPoint PPT Presentation

Transcript of The Bioperl toolkit : Perl modules for the life sciences

Page 1: The  Bioperl  toolkit : Perl modules for the life sciences

The Bioperl toolkitThe Bioperl toolkit::Perl modules for the life Perl modules for the life

sciencessciences

Daniel Guariz Pinheiro, PhD.L L aboratório de aboratório de G G enética enética M M olecular e olecular e B B ioinformáticaioinformática

+ DBI+ DBI+ CGI+ CGI

Page 2: The  Bioperl  toolkit : Perl modules for the life sciences

IntroduçãoIntrodução

Open Bioinformatics Foundation

Page 3: The  Bioperl  toolkit : Perl modules for the life sciences

Reinvenção da rodaReinvenção da roda

Pode não ser tão eficiente quanto o esperado!

Page 4: The  Bioperl  toolkit : Perl modules for the life sciences

ReferênciasReferências

1: Stajich JE, Block D, Boulez K, Brenner SE, Chervitz SA, Dagdigian C, Fuellen G, Gilbert JG, Korf I, Lapp H, Lehväslaiho H, Matsalla C, Mungall CJ, Osborne BI, Pocock MR, Schattner P, Senger M, Stein LD, Stupka E, Wilkinson MD, Birney E. The Bioperl toolkit: Perl modules for the life sciences. Genome Res. 2002 Oct;12(10):1611-8.

-Arquitetura Geral do Pacote BioPerl

2: Stein LD, Mungall C, Shu S, Caudy M, Mangone M, Day A, Nickerson E, Stajich JE, Harris TW, Arva A, Lewis S. The generic genome browser: a building block for a model organism system database. Genome Res. 2002 Oct;12(10):1599-610.

Gbrowse – Visualização de Genomas

3: Stajich JE, Hahn MW. Disentangling the effects of demography and selection in human history. Mol Biol Evol. 2005 Jan;22(1):63-73. Epub 2004 Sep 8.

GenPop – Genética de Populações

Sendu BalaChristopher FieldsHilmar LappHeikki LehväslaihoAaron MackeyBrian Osborne

Jason Stajich

Lincoln Stein

Resp

on

sáveis Bio

Perl

Principais artigos científicos VSNS-BCD – Universität Bielefeld

Page 5: The  Bioperl  toolkit : Perl modules for the life sciences

CitaçõesCitações

Dados (www.bioperl.org)Dados (www.bioperl.org)

1998 – meados 2008

~600 (projetos e artigos)

~44 (livros)

3 (patentes)

Page 6: The  Bioperl  toolkit : Perl modules for the life sciences

Paradigma de programaçãoParadigma de programação

FUNCIONAMENTOFUNCIONAMENTO:RELACIONAMENTOS ETROCAS DE MENSAGENSENTRE OS OBJETOS

Page 7: The  Bioperl  toolkit : Perl modules for the life sciences

Conceitos - IConceitos - I

Classe:

É a modelagem de um conceito do mundo real (abstração de um objeto).

As propriedades associadas ao conceito são representadas por atributos e operações.

Objeto ou Instância (de uma classe):

É a concretização da classe em uma entidade lógica, que contém dados (atributos) e código para manipulá-los (métodos).

Cada objeto “pertence” a uma classe.

Mensagem:

Comunicação entre objetos.Se manda uma mensagem a um objeto para pedir a ele executar uma operação particular.

Page 8: The  Bioperl  toolkit : Perl modules for the life sciences

Conceitos - IIConceitos - IIHerança:

(Especialização/generalização) é o mecanismo pelo qual uma classe (sub-classe) pode estender outra classe (super-classe), aproveitando seus métodos e atributos.

No modelo a objetos, uma sub-classe possui todos os atributos e todas as operações da super-classe. A sub-classe pode acrescentar alguns atributos e métodos. Ela pode também redefinir alguns métodos da super-classe. Ela não pode tirar nenhuma propriedade da super-classe.

Encapsulamento:

Detalhes da implementação são transparentes a quem manipula o objeto;

Polimorfismo:

É o princípio pelo qual duas ou mais classes derivadas de uma mesma superclasse podem invocar métodos que têm a mesma identificação (assinatura) mas comportamentos distintos.

Interface:

A Interface é uma classe que possui apenas as especificações sem a implementação.

Page 9: The  Bioperl  toolkit : Perl modules for the life sciences

Diagrama de ClassesDiagrama de Classes

As classes Circle, Square e Triangle redefinem os métodos draw() e erase() daSuperclasse Shape

Page 10: The  Bioperl  toolkit : Perl modules for the life sciences

– Melhor representação do “mundo real”– Ênfase nos dados– Modularidade– Reusabilidade– Produtividade– Manutenibilidade...

Vantagens (POO)Vantagens (POO)

Page 11: The  Bioperl  toolkit : Perl modules for the life sciences

Desvantagens (POO)Desvantagens (POO)

– Desempenho baixo no tempo de execução em relação ao código estruturado;

– Apropriação (Classes – atributos e métodos – e Hierarquia de classes)

– Fragilidade(Necessidade de definições precisas das

classes – requer análise cuidadosa do projeto)

...

Page 12: The  Bioperl  toolkit : Perl modules for the life sciences

package Sequence;

sub new {my ($class, $id, $seq, $strand) = @_;my $self = bless {}, $class;$self->set_sequence($id,$seq,$strand);return $self;

}

sub set_sequence {my ($self, $id, $seq, $strand) = @_;$self->{'sequence'} = {'id' => $id,

'seq' => $seq,'strand' => $strand};

}

sub display_fasta_sequence {my $self = shift;my $seq = $self->{'sequence'}->{'seq'};$seq=~s/(.{1,60})/$1\n/g;print ">$self->{'sequence'}->{'id'}\n$seq";

}

1;

Sequence.pm

POO em PerlPOO em Perl

use Sequence;

my $seq = Sequence->new('Seq1','ACCACGATCACATG','+');$seq->display_fasta_sequence();

seq.pl

Definições simplificadas:

Um objeto é simplesmente uma referência à classe a qual ele pertence;

Uma classe é simplesmente um pacote que provê métodos para lidar com as referências do objeto;

Um método é simplesmente uma sub-rotina que espera uma referência ao objeto como primeiro argumento;

Page 13: The  Bioperl  toolkit : Perl modules for the life sciences

CPANCPAN

http://www.cpan.org/

Comprehensive Perl Archive NetworkColeção de módulos em Perl e documentação

Exemplos: • DBD::mysql ; • DBI; • CGI;• GD;

Page 14: The  Bioperl  toolkit : Perl modules for the life sciences

Application Programming Application Programming Interface Interface (API)(API)

Conjunto de rotinas e padrões (convenções) estabelecidos por uma aplicação para a utilização/extensão de suas funcionalidades.

Provê uma interface de alto nível para uma determinada aplicação.

Bio::Perl - API simplificada

Exemplo:

# Lê um todas as seqüências de um arquivo multifasta

my @seq_object_array = read_all_sequences($filename,'fasta');

Page 15: The  Bioperl  toolkit : Perl modules for the life sciences

Arquitetura geral do BioPerlArquitetura geral do BioPerl

Programação Orientada a Objetos (POO)

API (Application Programming Interface)

Princípios:

Separação entre Interface e Implementação;

Generalização de rotinas comuns em um único módulo;

Utilização de certos padrões de desenvolvimento reconhecidos (Design Patterns);

Page 16: The  Bioperl  toolkit : Perl modules for the life sciences

Separação entre Interface e Separação entre Interface e ImplementaçãoImplementação

Interface (Tipos Abstratos de Dados)

Contrato de como os métodos devem ser invocados;

I – adicionado ao nome da classe (Ex.: Bio::SeqI e Bio::Seq; Bio::SeqFeatureI e Bio::SeqFeature)

Page 17: The  Bioperl  toolkit : Perl modules for the life sciences

Generalização de rotinas Generalização de rotinas comuns (único módulo)comuns (único módulo)

Exemplos:

Operações básicas de IO (input/output) – Bio::Root::IO

Operações de IO (input/output) seqüências – Bio::SeqIO

Operações básicas de acesso web – Bio::Root::HTTPget

Operações de acesso web – Bio::DB::GenBank

Page 18: The  Bioperl  toolkit : Perl modules for the life sciences

Utilização de Padrões de Utilização de Padrões de DesenvolvimentoDesenvolvimento

Factory – adição de módulos responsáveis pela criação automática de objetos

Factory – adicionado ao nome da classe (Ex.: Bio::Seq::SeqFactory - Bio::PrimarySeq ou Bio::Seq::Qual)

Strategy – seleção dinâmica de algoritmos

Ex.: next_seq() da classe Bio::SeqIO (Diferentes implementações, uma para cada um dos parsers) – seleção em tempo de execução

Page 19: The  Bioperl  toolkit : Perl modules for the life sciences

CaracterísticasCaracterísticas

Escrito puramente em Perl

Padrão de desenvolvimento rigoroso

Orientações para a padronização do cógido

Testes exaustivos

Documentação (POD - Plain Old Documentation)

perldoc

Requer compilador Perl

v5.005 ou superior

Plataformas suportadas (Sistemas Operacionais)

UNIX-like

Linux, Solaris, FreeBSD, …

Windows

Page 20: The  Bioperl  toolkit : Perl modules for the life sciences

Principais MódulosPrincipais Módulos

Bio::Seq Seqüências e suas propriedades

Bio::SeqFeatureAnotação de seqüências com seus atributos

Bio::DBAcesso a bancos de dados de seqüências

Bio::SeqIOUsado para ler e gravar seqüências em diferentes formatos

Bio::DB::Query::GenBankConsultas a bancos de dados de seqüências (GenBank)

Bio::SearchIO Obter dados de resultados (Ex.: blast)

Bio::LocationManipulação de coordenadas de seqüências

Bio::GraphicsGerar imagens de seqüências e atributos de seqüências

Page 21: The  Bioperl  toolkit : Perl modules for the life sciences

DocumentaçãoDocumentação

http://docs.bioperl.org$ perldoc Bio::SeqIO

Page 22: The  Bioperl  toolkit : Perl modules for the life sciences

Bio::SeqBio::Seq

use Bio::Seq;

my $sequence_as_string = 'ACGTACAGTACAGTACTAGAAACGTA';

my $seqobj = Bio::Seq->new( -display_id => 'my_id',

-seq => $sequence_as_string);

print $seqobj->display_id(),"\n";

print $seqobj->seq(),"\n";

print $seqobj->translate()->seq(),"\n";

print $seqobj->trunc(5,10)->revcom()->seq(),"\n";

my $subseqstr = $seqobj->subseq(5,10);

print $subseqstr,"\n";

my $revcom = $seqobj->revcom();

print $revcom ,"\n";

print $revcom->seq(),"\n";

print $seqobj->desc(),"\n";

Page 23: The  Bioperl  toolkit : Perl modules for the life sciences

Bio::SeqFeature::GenericBio::SeqFeature::Generic

use Bio::Seq; use Bio::SeqFeature::Generic;

my $seqobj = Bio::Seq->new( -display_id => 'my_id', -seq => 'ACGTACAGTACAGTACTAGAAACGTA');

my $feat = new Bio::SeqFeature::Generic ( -start => 5, -end => 15, -strand => -1, -primary_tag => 'repeat', -display_name => 'alu family', -tag=>{ test=>[1,2,3], author=>'someone' } );

$seqobj->add_SeqFeature($feat);

my @features = $seqobj->get_SeqFeatures();

foreach my $feat ( @features ) {

print "Feature ",$feat->primary_tag," starts ",$feat->start," ends ", $feat->end," strand ",$feat->strand,"\n";

print "Feature sequence is ",$feat->seq->seq(),"\n";

foreach my $tag ( $feat->get_all_tags() ) {

print "\t",$tag,"\n";

foreach my $value ( $feat->each_tag_value($tag) ) {

print "\t\t",$value,"\n";

}

}

}

repeat

test

authorsomeone

12

3

primary_tag

tag tag value

tag tag value

Page 24: The  Bioperl  toolkit : Perl modules for the life sciences

Bio::DB::GenBankBio::DB::GenBank

use Bio::DB::GenBank;my $gb = new Bio::DB::GenBank;my $seqobj = $gb->get_Seq_by_acc('J00522'); #my $seqobj = $gb->get_Seq_by_version('J00522.1'); #my $seqobj = $gb->get_Seq_by_gi('195052');

my @features = $seqobj->get_SeqFeatures();foreach my $feat ( @features ) {

print "Feature ",$feat->primary_tag," starts ",$feat->start," ends ",

$feat->end," strand ",$feat->strand,"\n"; print "Feature sequence is ",$feat->seq->seq(),"\n"; foreach my $tag ( $feat->get_all_tags() ) { print "\t",$tag,"\n"; foreach my $value ( $feat->each_tag_value($tag) ) { print "\t\t",$value,"\n"; } }}

Page 25: The  Bioperl  toolkit : Perl modules for the life sciences

GenBankLOCUS NM_000518 626 bp mRNA linear PRI 27-JAN-2008DEFINITION Homo sapiens hemoglobin, beta (HBB), mRNA.ACCESSION NM_000518VERSION NM_000518.4 GI:28302128KEYWORDS .SOURCE Homo sapiens (human) ORGANISM Homo sapiens Eukaryota; Metazoa; Chordata; Craniata; Vertebrata; Euteleostomi; Mammalia; Eutheria; Euarchontoglires; Primates; Haplorrhini; Catarrhini; Hominidae; Homo.REFERENCE 1 (bases 1 to 626) AUTHORS Ma,Q., Abel,K., Sripichai,O., Whitacre,J., Angkachatchai,V., Makarasara,W., Winichagoon,P., Fucharoen,S., Braun,A. and Farrer,L.A. TITLE Beta-globin gene cluster polymorphisms are strongly associated with severity of HbE/beta(0)-thalassemia JOURNAL Clin. Genet. 72 (6), 497-505 (2007) PUBMED 17894837 REMARK GeneRIF: Forty-five SNPs within the interval including the LCR region and the delta gene showed strong association with disease severity.

COMMENT REVIEWED REFSEQ: This record has been curated by NCBI staff. The reference sequence was derived from L48217.1. On Feb 11, 2003 this sequence version replaced gi:13788565. Summary: The alpha (HBA) and beta (HBB) loci determine the structure of the 2 types of polypeptide chains in adult hemoglobin, Hb A. The normal adult hemoglobin tetramer consists of two alpha chains and two beta chains. Mutant beta globin causes sickle cell anemia. Absence of beta chain causes beta-zero-thalassemia. Reduced amounts of detectable beta globin causes beta-plus-thalassemia. The order of the genes in the beta-globin cluster is 5'-epsilon -- gamma-G -- gamma-A -- delta -- beta--3'. Publication Note: This RefSeq record includes a subset of the publications that are available for this gene. Please see the Entrez Gene record to access additional publications. COMPLETENESS: full length.FEATURES Location/Qualifiers source 1..626 /organism="Homo sapiens" /mol_type="mRNA" /db_xref="taxon:9606" /chromosome="11" /map="11p15.5"

gene 1..626 /gene="HBB" /note="hemoglobin, beta; synonyms: HBD, CD113t-C" /db_xref="GeneID:3043" /db_xref="HGNC:4827" /db_xref="HPRD:HPRD_00786" /db_xref="MIM:141900" exon 1..142 /gene="HBB" /inference="alignment:Splign" /number=1 CDS 51..494 /gene="HBB" /GO_component="hemoglobin complex [PMID 1540659] [PMID 10588683]" /GO_function="heme binding; hemoglobin binding [PMID 1512262]; iron ion binding; metal ion binding; oxygen binding [PMID 11747442]; oxygen transporter activity [PMID 1971109] [PMID 11747442]; selenium binding [PMID 15780970]"

/GO_process="nitric oxide transport [PMID 8292032]; oxygen transport [PMID 1540659] [PMID 11747442]; positive regulation of nitric oxide biosynthesis [PMID 7965120]; transport“ /note="beta globin chain" /codon_start=1 /product="beta globin" /protein_id="NP_000509.1" /db_xref="GI:4504349" /db_xref="CCDS:CCDS7753.1" /db_xref="GeneID:3043" /db_xref="HGNC:4827" /db_xref="HPRD:HPRD_00786" /db_xref="MIM:141900" /translation="MVHLTPEEKSAVTALWGKVNVDEVGGEALGRLLVVYPWTQRFFE SFGDLSTPDAVMGNPKVKAHGKKVLGAFSDGLAHLDNLKGTFATLSELHCDKLHVDPE NFRLLGNVLVCVLAHHFGKEFTPPVQAAYQKVVAGVANALAHKYH" exon 143..365 /gene="HBB" /inference="alignment:Splign" /number=2

exon 366..626 /gene="HBB" /inference="alignment:Splign" /number=3 polyA_signal 602..607 /gene="HBB" polyA_site 626 /gene="HBB"

ORIGIN 1 acatttgctt ctgacacaac tgtgttcact agcaacctca aacagacacc atggtgcatc 61 tgactcctga ggagaagtct gccgttactg ccctgtgggg caaggtgaac gtggatgaag 121 ttggtggtga ggccctgggc aggctgctgg tggtctaccc ttggacccag aggttctttg 181 agtcctttgg ggatctgtcc actcctgatg ctgttatggg caaccctaag gtgaaggctc 241 atggcaagaa agtgctcggt gcctttagtg atggcctggc tcacctggac aacctcaagg 301 gcacctttgc cacactgagt gagctgcact gtgacaagct gcacgtggat cctgagaact 361 tcaggctcct gggcaacgtg ctggtctgtg tgctggccca tcactttggc aaagaattca 421 ccccaccagt gcaggctgcc tatcagaaag tggtggctgg tgtggctaat gccctggccc 481 acaagtatca ctaagctcgc tttcttgctg tccaatttct attaaaggtt cctttgttcc 541 ctaagtccaa ctactaaact gggggatatt atgaagggcc ttgagcatct ggattctgcc 601 taataaaaaa catttatttt cattgc//

FASTA (Pearson)>gi|28302128|ref|NM_000518.4| Homo sapiens hemoglobin, beta (HBB), mRNAACATTTGCTTCTGACACAACTGTGTTCACTAGCAACCTCAAACAGACACCATGGTGCATCTGACTCCTGAGGAGAAGTCTGCCGTTACTGCCCTGTGGGGCAAGGTGAACGTGGATGAAGTTGGTGGTGAGGCCCTGGGCAGGCTGCTGGTGGTCTACCCTTGGACCCAGAGGTTCTTTGAGTCCTTTGGGGATCTGTCCACTCCTGATGCTGTTATGGGCAACCCTAAGGTGAAGGCTCATGGCAAGAAAGTGCTCGGTGCCTTTAGTGATGGCCTGGCTCACCTGGACAACCTCAAGGGCACCTTTGCCACACTGAGTGAGCTGCACTGTGACAAGCTGCACGTGGATCCTGAGAACTTCAGGCTCCTGGGCAACGTGCTGGTCTGTGTGCTGGCCCATCACTTTGGCAAAGAATTCACCCCACCAGTGCAGGCTGCCTATCAGAAAGTGGTGGCTGGTGTGGCTAATGCCCTGGCCCACAAGTATCACTAAGCTCGCTTTCTTGCTGTCCAATTTCTATTAAAGGTTCCTTTGTTCCCTAAGTCCAACTACTAAACTGGGGGATATTATGAAGGGCCTTGAGCATCTGGATTCTGCCTAATAAAAAACATTTATTTTCATTGC

Principais Formatos dos Principais Formatos dos BDs Flat files do NCBI/EBIBDs Flat files do NCBI/EBI

EMBL

ID AY509193 standard; mRNA; HUM; 647 BP.XXAC AY509193;XXSV AY509193.1XXDT 20-JAN-2004 (Rel. 78, Created)DT 16-APR-2005 (Rel. 83, Last updated, Version 2)XXDE Homo sapiens hemoglobin beta mRNA, complete cds.XXKW .XXOS Homo sapiens (human)OC Eukaryota; Metazoa; Chordata; Craniata; Vertebrata; Euteleostomi; Mammalia;OC Eutheria; Euarchontoglires; Primates; Catarrhini; Hominidae; Homo.XXFH Key Location/QualifiersFHFT source 1..647FT /db_xref="taxon:9606"FT /mol_type="mRNA"FT /organism="Homo sapiens"FT /isolation_source="recovered SARS patient"FT /cell_type="lymphocyte"

FT CDS 51..494FT /codon_start=1FT /db_xref="GOA:Q6R7N2"FT /db_xref="HSSP:1BAB"FT /db_xref="InterPro:IPR000971"FT /db_xref="InterPro:IPR002337"FT /db_xref="InterPro:IPR012292"FT /db_xref="UniProtKB/TrEMBL:Q6R7N2"FT /note="differentially expressed in lymphocyte of SARSFT patient"FT /product="hemoglobin beta"FT /protein_id="AAR96398.1"FT /translation="MVHLTPEEKSAVTALWGKVNVDEVGGEALGRLLVVYPWTQRLFESFT FGDLFTPDAVMGNPKVKAHGKKVLGAFSDGPAHLDNLKGTFATLSELHCDKLHVDPENFFT RLLGNVLVCVLAHHFGKEFTPPVQAAYQKVVAGVANALAHKYH"XXSQ Sequence 647 BP; 159 A; 158 C; 165 G; 165 T; 0 other; acatttgctt ctgacacaac tgtgttcact agcaacctca aacagacacc atggtgcacc 60 tgactcctga ggagaagtct gccgttactg ccctgtgggg caaggtgaac gtggatgaag 120 ttggtggtga ggccctgggc aggctgctgg tggtctaccc ttggacccag aggctctttg 180 agtcctttgg ggatctgttc actcctgatg ctgttatggg caaccctaag gtgaaggctc 240 atggcaagaa agtgctcggt gcctttagtg atggcccggc tcacctggac aacctcaagg 300 gcacctttgc cacactgagt gagctgcact gtgacaagct gcacgtggat cctgagaact 360 tcaggctcct gggcaacgtg ctggtctgtg tgctggccca tcactttggc aaagaattca 420 ccccaccagt gcaggctgcc tatcagaaag tggtggctgg tgtggctaat gccctggccc 480 acaagtatca ctaagctcgc tttcttgctg tccaatttct attaaaggtt cctttgttcc 540 ctaagtccaa ctactaaact gggggatatt atgaagggcc ttgagcatct ggattctgcc 600 taataaaaaa catttatttt cattgaaaaa aaaaaaaaaa aaaaaaa 647//

Page 26: The  Bioperl  toolkit : Perl modules for the life sciences

Bio::SeqIOBio::SeqIO

use Bio::SeqIO;

my $in = Bio::SeqIO->new( -file => "./NAT2.gbwithparts" );

my $out = Bio::SeqIO->new( -file => ">./NAT2.embl", -format=> 'EMBL' );

while ( my $seq = $in->next_seq() ) { print $seq->display_id(),"\t",$seq->desc(),"\n"; $out->write_seq($seq);}

Page 27: The  Bioperl  toolkit : Perl modules for the life sciences

Bio::DB::Query::GenBankBio::DB::Query::GenBank

use Bio::DB::Query::GenBank;use Bio::DB::GenBank;

# get a stream via a query stringmy $query = Bio::DB::Query::GenBank->new(

-query =>'NAT2[Gene Name] AND Homo sapiens[Organism] AND mRNA[Filter]',

-db => 'nucleotide');my $count = $query->count();

print "Found $count entries\n";

# get a genbank database handlemy $gb = new Bio::DB::GenBank;my $stream = $gb->get_Stream_by_query($query);while (my $seq = $stream->next_seq) {

print $seq->display_id(),"\t",$seq->desc(),"\n";}

Page 28: The  Bioperl  toolkit : Perl modules for the life sciences

Bio::LocationBio::Location

use Bio::SeqIO; my $in = Bio::SeqIO->new( -file => "./ame_ref_chrLG16.gbk" );

while ( my $seq = $in->next_seq() ) { print $seq->display_id, "\n"; for my $feature ( $seq->get_SeqFeatures ) { next unless ( $feature->primary_tag eq 'mRNA'); if ($feature->has_tag('gene')) { my ($name) = $feature->get_tag_values('gene');

my $exonct = 1; print "\t",$name,"\n"; for my $exon ($feature->location->each_Location ) {# print " ",$exon->start, "..",$exon->end,"\n"; my $exonseq = $seq->trunc($exon); $exonseq->display_id($name.".exon".$exonct++);# print "\t\t",$exonseq->display_id(),"\n"; } print "Exon count: $exonct\n"; my $spliced = $feature-

>spliced_seq; print $spliced,"\n“; # print $spliced->seq(),"\n"; } }}

Page 29: The  Bioperl  toolkit : Perl modules for the life sciences

Bio::SearchIOBio::SearchIO

use Bio::SearchIO;my $searchio = new Bio::SearchIO( -format => 'blast', -file => 'blast/blast_output');while( my $result = $searchio->next_result ) { print $result->query_accession(),"\n"; while( my $hit = $result->next_hit ) { print "\t",$hit->accession(),"\t",$hit->description(),"\n"; while( my $hsp = $hit->next_hsp ) { print "\t\t",'Score: ',$hsp->score(),"\n"; print "\t\t",'Identity: ',$hsp->percent_identity(),"\n";

print "\t\t",'e-value: ',$hsp->evalue(),"\n"; print "\t\t",'Query (start,end): ',

$hsp->start('query'),', ',$hsp->end('query'),"\n"; print "\t\t",'Subject (start,end): ',

$hsp->start('subject'),', ',$hsp->end('subject'),"\n"; } }}

Page 30: The  Bioperl  toolkit : Perl modules for the life sciences

Blast outputBlast output

BLASTN 2.2.16 [Mar-25-2007]

Reference: Altschul, Stephen F., Thomas L. Madden, Alejandro A. Schaffer, Jinghui Zhang, Zheng Zhang, Webb Miller, and David J. Lipman (1997), "Gapped BLAST and PSI-BLAST: a new generation of protein database searchprograms", Nucleic Acids Res. 25:3389-3402.

Query= CTC-MA0003-010602-021-H11 (451 letters)

Database: /data/db/hs.fna 21,144 sequences; 56,617,273 total letters

Searching..................................................done

Score ESequences producing significant alignments: (bits) Value

gi|9945313|ref|NM_001967.2| Homo sapiens eukaryotic translation ... 323 9e-88gi|4503528|ref|NM_001416.1| Homo sapiens eukaryotic translation ... 78 9e-14gi|32698801|ref|NG_002809.1| Homo sapiens eukaryotic translation... 62 5e-09

>gi|9945313|ref|NM_001967.2| Homo sapiens eukaryotic translation initiation factor 4A, isoform 2 (EIF4A2), mRNA Length = 1864

Score = 323 bits (163), Expect = 9e-88 Identities = 169/171 (98%) Strand = Plus / Plus

Query: 59 gcatggtgacatggaccagaaggagagagatgttatcatgagggaattccggtcagggtc 118 ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||Sbjct: 924 gcatggtgacatggaccagaaggagagagatgttatcatgagggaattccggtcagggtc 983

Query: 119 aagtcgtgttctgatcactactgacttgtaggctcgcgggattgatgtgcaacaagtgtc 178 ||||||||||||||||||||||||||||| ||||||||||||||||||||||||||||||Sbjct: 984 aagtcgtgttctgatcactactgacttgttggctcgcgggattgatgtgcaacaagtgtc 1043

Query: 179 ttgggttataaattatgatctacctaccaatcgtgaaaactatattcacag 229 || ||||||||||||||||||||||||||||||||||||||||||||||||Sbjct: 1044 tttggttataaattatgatctacctaccaatcgtgaaaactatattcacag 1094

Score = 208 bits (105), Expect = 4e-53 Identities = 108/109 (99%) Strand = Plus / Plus

Query: 340 gaattggcggagggggtcgatttgggaggaaaggtgtggctataaactttgttactgaag 399 |||||||| |||||||||||||||||||||||||||||||||||||||||||||||||||Sbjct: 1094 gaattggcagagggggtcgatttgggaggaaaggtgtggctataaactttgttactgaag 1153

Query: 400 aagacaagaggattcttcgtgacattgagactttctacaatactacagt 448 |||||||||||||||||||||||||||||||||||||||||||||||||Sbjct: 1154 aagacaagaggattcttcgtgacattgagactttctacaatactacagt 1202

Page 31: The  Bioperl  toolkit : Perl modules for the life sciences

Bio::GraphicsBio::Graphics

use Bio::SearchIO; use Bio::Graphics; use Bio::SeqFeature::Generic;

my $searchio = new Bio::SearchIO( -format => 'blast', -file => 'blast/blast_output');

while( my $result = $searchio->next_result ) {

my $query_accession = $result->query_accession();

my $panel = Bio::Graphics::Panel->new(-length => $result->query_length(),-width => 800,

-pad_left=>10, -pad_right=>10);

my $full_length = Bio::SeqFeature::Generic->new(-display_name=>$query_accession,

-start=>1, -end=>$result->query_length());

$panel->add_track($full_length, -glyph => 'arrow', -tick => 2, -fgcolor => 'black',

-double => 1, -label=>1);

my $track = $panel->add_track(-glyph => 'graded_segments', -label => 1, -min_score=>0,

-max_score=>1000);

while( my $hit = $result->next_hit ) {

my $hit_accession = $hit->accession();

while( my $hsp = $hit->next_hsp ) {

my $feature = Bio::SeqFeature::Generic->new(-display_name=> $hit_accession,

-score=> $hsp->score(), -start=> $hsp->start('query'), -end=> $hsp->end('query'));

$track->add_feature($feature);

}

}

open(OUT, ">".$query_accession.'.png'); binmode OUT; print OUT $panel->png; close(OUT);

}

Page 32: The  Bioperl  toolkit : Perl modules for the life sciences

ReferênciasReferências

http://java.sun.com/docs/books/tutorial/java/concepts/

http://perldoc.perl.org/perlboot.html

http://www.bioperl.org/

http://www.ncbi.nlm.nih.gov/pubmed/12368254

http://docs.bioperl.org/

http://lgmb.fmrp.usp.br/~daniel/downloads/cvbioinfo2010

http://stein.cshl.org/genome_informatics/BioGraphics/

Page 33: The  Bioperl  toolkit : Perl modules for the life sciences

Perguntas…Perguntas…

Daniel Guariz Pinheiro

[email protected]

http://lgmb.fmrp.usp.br/~daniel/

Page 34: The  Bioperl  toolkit : Perl modules for the life sciences

ExercíciosExercícios

“There’ s More Than One Way To Do It”

TIMTOWTDI

http://lgmb.fmrp.usp.br/~daniel/downloads/cvbioinfo2010/exercises.txt

Page 35: The  Bioperl  toolkit : Perl modules for the life sciences

Exercício 1Exercício 1

1. Obter e imprimir em um arquivo as seguintes informações do cromossomo 16 (contig genômico) de Apis mellifera (ame_ref_chrLG16.gbk):

Número de acesso dos contigs genômicos <TAB> tamanho da seqüência<TAB> símbolo do gene (Ex.: LOC413891)<TAB><TAB> coordenada do exon (Ex.: 8865..9971) <TAB> informação da orientação (strand: plus(1)/minus(-1))

Exemplo:

NW_001253164 745157 LOC408563 666589..666822 1 672756..672973 1 673083..673254 1 673344..673483 1 673847..674257 1 674369..674599 1 674724..675077 1 679210..679317 1 680024..681271 1 681362..681649 1 681734..681958 1 682047..682250 1 682360..682591 1 682805..683048 1

Page 36: The  Bioperl  toolkit : Perl modules for the life sciences

Exercício 2Exercício 2

2. Obter e imprimir em um arquivo as seguintes informações do arquivo de mRNAsdo gene NAT2 (NAT2.gbwithparts) somente para o número de acesso iniciado porNM_ :

Número de acesso GenBankLocalização no cromossomo exon número do exon coordenada (start..end)

Exemplo:

NM_0000158p22 exon 1 1..101 exon 2 102..1317

Page 37: The  Bioperl  toolkit : Perl modules for the life sciences

Exercício 3Exercício 3

3. Fazer uma consulta no GenBank das formas alternativas do gene BRCA1 () através da BioPerl, obter as seguintes informações e imprimir na tela:

Número de acesso<TAB>Descrição<TAB>números dos exons que compõe essa forma alternativa entre ";"

Query: BRCA1[Gene Name] AND Homo sapiens[Organism] AND RefSeq[Filter] AND mRNA[Filter]db: nucleotide

Exemplo:

NM_007305 Homo sapiens breast cancer 1, early onset (BRCA1), transcript variant BRCA1-delta9-10-11b, mRNA. 1b;3;4;5;6;7;8;11a;12;13;14a;15;16;17;18;19;20;21;22;23;24

Page 38: The  Bioperl  toolkit : Perl modules for the life sciences

Exercício 4Exercício 4

4.1. Baixar o arquivo (exercises/ex4/NW_001253146.gbk) com o contig genômico do cromossomo 16 deApis mellifera;

4.1. Extrair a seqüência completa para um outro arquivo no formato fasta (contig.fna) e extrair as seqüências dos transcritos (mRNAs) após evento de splicing (spliced_seqs) e compor um arquivo multi-fasta com essas seqüências (transcripts.fna) . Utilizar o transcript_id (Ex.: XM_397330.3) como ID da sequência e o símbolo do Gene (Ex.: LOC413891) como descrição;

Exemplo:

> XM_397330.3 LOC413891GAATCGAGATATCGAATCGAATTAAGTCAAGTAAGAATGAAATTAAATCGATTTAAAGCA...

4.2. Gerar um arquivo fasta (proteins.fna) com as seqüencias de proteínas traduzidas a partir das informações do CDS. Utilizar o protein_id (Ex.: XP_397330.2) como ID da sequência e o produto gênico (product) (Ex.: similar to CG1970-PA isoform 1) como descrição;

Exemplo:>XP_397330.2 similar to CG1970-PA isoform 1MTVRALGPFFRSNNLLFRTLNENVVTNNRIIPLVNIESQRREAHQWMPDLDEYKHLLKHE...

Page 39: The  Bioperl  toolkit : Perl modules for the life sciences

Exercício 5Exercício 5

5. Baixar o arquivo (ex5/blast_out_5.txt), resultado de blast de uma EST x seqüencias de referência (RefSeq).

5.1. Imprimir o nome da seqüência (query) e somente para os HITS com score > 100 . Imprimir o número de acesso GenBank (Ex.: NM_001967) e descrição (Ex.: Homo sapiens eukaryotic translation initiation factor 4A, isoform 2 (EIF4A2), mRNA). Imprimir em seguida os HSPs (como no exemplo abaixo) desse HIT com score >= 150;

Exemplo:

CTC-MA0003-010602-021-H11 NM_001967 Homo sapiens eukaryotic translation initiation factor 4A, isoform 2 (EIF4A2), mRNA Score: 163 Identity: 98.8304093567251 e-value: 9e-88 Query (start,end): 59, 229 Subject (start,end): 924, 1094

Page 40: The  Bioperl  toolkit : Perl modules for the life sciences

• O módulo DBI define um conjunto de métodos, variáveis e convenções que provêm uma interface consistente e independente do base de dados atual que está sendo utilizada;

• Conexões: MySQL, MSSQL, Oracle, Informix, PostgreSQL, SQLite, etc.

• DBD::mysql - MySQL driver para DBI – Interface entre a Perl e o MySQL

RDBMS• DBD::SQLite - SQLite driver para DBI

– Interface entre a Perl e SQLite RDBMS

• Database independent interface for Perl

RDBMS - Relational Database Management System DBD – Data Base DriverAPI - Application Programming Interface

API

Módulo DBIMódulo DBI

Page 41: The  Bioperl  toolkit : Perl modules for the life sciences

• Sistemas de Gerenciamento de Bancos de Dados– Programas de computador responsáveis pelo

gerenciamento de uma base de dados. • Provê ferramentas e mecanismos e convenções que

permitem gerenciar o acesso, a manipulação e a organização dos dados.

– MySQL, Oracle, PostgreSQL, SQLite, etc.– Modelo Relacional

• Inspirado na Álgebra Relacional• Linguagem SQL (Structured Query Language)

– Permite realizar operações relacionais, de consulta e inserção de dados;

• MySQL – SGBD relacional• SQLite – SGBD relacional simplificado

Conceitos em Bancos de Conceitos em Bancos de DadosDados

Page 42: The  Bioperl  toolkit : Perl modules for the life sciences

Representação dos DadosRepresentação dos Dados• Tabelas

– Registros (linhas)– Campos (colunas)

id nome cidade estado curso1 Paulo Henrique Alves Porto Velho RO Biologia Experimental2 Matheus Carvalho Bürger Limeira SP Informática Biomédica3 Ricardo Kazuhiro Kavanishi Ribeirão Preto SP Informática Biomédica4 Poliana Fernanda Giachetto Campinas SP Produção Animal5 Luiz Carlos Bertucci Barbosa Araraquara SP Biotecnologia6 André M. Ribeiro dos Santos Belém PA Ciências Biológicas7 Sylvain Darnet Belém PA Biologia molecular e celular8 Luisa Warchavchik Hugerth São Paulo SP Ciências Moleculares9 Maria Izabela Ruz Caffé Campinas SP Informática Biomédica10 Ana Luiza Assin Squillace Mogi Mirim SP Biotecnologia11 Myna Nakabashi São Paulo SP Biotecnologia12 Guilherme Fernandes Lourenço de Oliveira Franca SP Engenharia Biotecnológica13 André Luiz de Oliveira Jaboticabal SP Ciências Biológicas14 Júlio César Botelho de Souza Ribeirão Preto SP Informática Biomédica15 Fernando Moral Mayoral Sao Jose dos Campos SP Ciências Moleculares16 Orzenil Bonfim da Silva Junior Brasilia DF Química17 Diego Martinez Salvanha Ribeirão Preto SP Sistemas de Informação18 Leticia Regina Lima Ribeirao Preto SP Informática Biomédica19 Eric Hainer Ostroski Santo André SP Bioinformática20 Guilherme da Silva Pereira Piracicaba SP Genética e Melhoramento de Plantas

Page 43: The  Bioperl  toolkit : Perl modules for the life sciences

Relacionamentos 1:nRelacionamentos 1:n

id nome cidade_id curso_id1 Paulo Henrique Alves 1 12 Matheus Carvalho Bürger 2 23 Ricardo Kazuhiro Kavanishi 3 24 Poliana Fernanda Giachetto 4 35 Luiz Carlos Bertucci Barbosa 5 46 André M. Ribeiro dos Santos 6 57 Sylvain Darnet 6 68 Luisa Warchavchik Hugerth 7 79 Maria Izabela Ruz Caffé 4 210 Ana Luiza Assin Squillace 8 411 Myna Nakabashi 7 412 Guilherme Fernandes Lourenço de Oliveira 9 813 André Luiz de Oliveira 10 514 Júlio César Botelho de Souza 3 215 Fernando Moral Mayoral 11 716 Orzenil Bonfim da Silva Junior 12 917 Diego Martinez Salvanha 3 1018 Leticia Regina Lima 3 219 Eric Hainer Ostroski 13 1120 Guilherme da Silva Pereira 14 12

id nome estado1 Porto Velho RO2 Limeira SP3 Ribeirão Preto SP4 Campinas SP5 Araraquara SP6 Belém PA7 São Paulo SP8 Mogi Mirim SP9 Franca SP10 Jaboticabal SP11 Sao Jose dos Campos SP12 Brasilia DF13 Santo André SP14 Piracicaba SP

id nome1 Biologia Experimental2 Informática Biomédica3 Produção Animal4 Biotecnologia5 Ciências Biológicas6 Biologia molecular e celular7 Ciências Moleculares8 Engenharia Biotecnológica9 Química10 Sistemas de Informação11 Bioinformática12 Genética e Melhoramento de Plantas

aluno

cidade

curso

Page 44: The  Bioperl  toolkit : Perl modules for the life sciences

Relacionamentos n:mRelacionamentos n:m

id nome

1 Introdução a Perl

2 Introdução a BioPerl

3 Introdução a Linux

aula

aluno_id aula_id

1 1

2 1

3 2

1 2

matricula

aluno

Page 45: The  Bioperl  toolkit : Perl modules for the life sciences

Diagrama de Entidades e Diagrama de Entidades e Relacionamentos (DER)Relacionamentos (DER)

Page 46: The  Bioperl  toolkit : Perl modules for the life sciences

Métodos DBI - conexãoMétodos DBI - conexão

my $dbh = DBI->connect($data_source, $username, $auth);

Conexão

Data source

my $data_source = “dbi:SQLite:test.db”;SQLite

dbi:DriverName:database_namedbi:DriverName:database_namedbi:DriverName:database_name@hostname:port dbi:DriverName:database=database_name;host=hostname;port=port

$dbh->disconnect();

Desconexão

Page 47: The  Bioperl  toolkit : Perl modules for the life sciences

Métodos DBI – DML/DDLMétodos DBI – DML/DDL

DML - Linguagem de Manipulação de Dados

INSERTUPDATEDELETE

$dbh->do($statementl);

DDL - Linguagem de Definição de Dados

CREATEDROPALTER TABLECREATE INDEXALTER INDEXDROP INDEXCREATE VIEWDROP VIEW

$dbh->do(“DELETE FROM matricula”);Exemplo:

Page 48: The  Bioperl  toolkit : Perl modules for the life sciences

Métodos DBI - DQLMétodos DBI - DQL

DQL - Linguagem de Consulta de Dados

SELECT

Métodos (prepare/execure/fetch)

my $sth = $dbh->prepare($statement);

$sth->execute();

while ( my @row = $sth->fetchrow_array ) { print "@row\n";}

my $ary_ref = $dbh->selectall_arrayref($statement);

my $ary_ref = $dbh->selectall_arrayref(“SELECT id, nome FROM aluno”);

Exemplos

my @row_ary = $dbh->selecrow_array(“SELECT id, nome FROM aluno WHERE id=1”);

Page 49: The  Bioperl  toolkit : Perl modules for the life sciences

Exercício 6Exercício 6

6. Utilizar o módulo DBI para manipular um Banco de Dados

6.1. Criar um banco de dados (test.db) usando o SQLite e criar uma tabela (transcript) com id, acc e length para armazenar um id numérico chave, um número de acesso GenBank e o tamanho do transcrito;

$ sqlite3 test.dbsqlite> CREATE TABLE transcript (id int not null primary key, acc varchar(20) not null, length int not null);sqlite> <CTRL+D>

6.2. Inserir as informações no Banco obtendo a partir das informações contidas no arquivo (exercises/ex4/NW_001253146.gbk) que contém contig genomico do cromossomo 16 de Apis mellifera;

6.3. Recuperar as informações da tabela transcripts e imprimi-las na tela de forma tabulada.

Exemplo:

1 XM_397330.3 23582 XM_397331.3 14353 XM_395650.1 11284 XM_396002.1 3935 XM_393027.3 14436 XM_395047.3 16777 XM_395046.3 3428

Page 50: The  Bioperl  toolkit : Perl modules for the life sciences

Módulo CGIMódulo CGI

CGI - Common Gateway Interface

Manipular requisições e respostas HTTP – Páginas HTML dinâmicas

#!/usr/bin/perl

use strict;use warnings;

use CGI;

my $q = CGI->new();

print $q->header; # cria o cabeçalho HTTP

print $q->start_html('hello world');

my $nome = $q->param(‘nome’) || ‘’;

print $q->h1('hello world'), $q->br(), $nome;

print $q->end_html;

Page 51: The  Bioperl  toolkit : Perl modules for the life sciences

Exercício 7Exercício 7

7. Utilizar o módulo CGI para criar uma página HTML formatada com as informações de um determinado transcrito, recuperadas do banco de dados (test.db) (utilizando o módulo DBI), passando por parâmetro um id de transcrito.