# $Id: ncbi_taxonomy_parser.pm,v 1.10 2008/02/05 00:34:15 cmungall Exp $
#
#
# see also - http://www.geneontology.org
#          - http://www.godatabase.org/dev
#
# You may distribute this module under the same terms as perl itself

package GO::Parsers::ncbi_taxonomy_parser;

=head1 NAME

  GO::Parsers::ncbi_taxonomy_parser 

=head1 SYNOPSIS

  do not use this class directly; use GO::Parser

=cut

=head1 DESCRIPTION

See L<ftp://ftp.ebi.ac.uk/pub/databases/taxonomy/taxonomy.dat>


=head1 PARSER ARCHITECTURE

This generates Stag event streams from one of the various GO flat file
formats (ontology, defs, xref, associations). See GO::Parser for details

Examples of these files can be found at http://www.geneontology.org

A description of the event streams generated follows; Stag or an XML
handler can be used to catch these events

=cut

use Exporter;
use base qw(GO::Parsers::base_parser);
use GO::Parsers::ParserEventNames;  # declare XML constants

use Carp;
use FileHandle;
use strict qw(subs vars refs);

my %synonymtypes =
  (
   'genbank synonym'=>['related'],
   'synonym'=>['related'],
   'in-part'=>['related'],
   'blast name'=>['related'],
   'misnomer'=>['related'],
   'misspelling'=>['related'],
   'scientific name'=>['exact'],
   'equivalent name'=>['exact'],
   'common name'=>['exact'],
   'genbank common name'=>['exact'],
   'acronym'=>['broad'],
   'genbank acronym'=>['broad'],
   'teleomorph'=>['related'],
   'anamorph'=>['related'],
   'genbank anamorph'=>['related'],
  );

sub syn {
    my $name = shift;
    $name =~ s/\s/_/g;
    $name =~ s/\-/_/g;
    $name;
}

sub parse_fh {
    my ($self, $fh) = @_;
    my $file = $self->file;
    $self->{name_h} = {};

    $self->start_event(OBO);
    $self->event(header=>
                 [
                  ['default-namespace'=>'ncbi_taxonomy'],
                  ['ontology'=>'ncbitaxon'],
                  [remark=>'autogenerated via GO::Parsers::ncbi_taxonomy_parser'],
                  (map {[synonymtypedef=>[[id=>syn($_)],[name=>$_],[scope=>$synonymtypes{$_}->[0]]]]} keys %synonymtypes),
                 ]);

    $self->event(typedef=>
                 [
                  [id=>'has_rank'],
                  [name=>"has_rank"],
                  [def=>[[defstr=>"A metadata relation between a class and its taxonomic rank (eg species, family)"]]],
                  [is_metadata_tag=>1],
                  [comment=>"This is an abstract class for use with the NCBI taxonomy to name the depth of the node within the tree. The link between the node term and the rank is only visible if you are using an obo 1.3 aware browser/editor; otherwise this can be ignored"]
                 ]);

    $self->event(term=>
                 [
                  [id=>_fix_id("taxonomic_rank")],
                  [name=>"taxonomic_rank"],
                  [def=>[[defstr=>"A level of depth within a species taxonomic tree"]]],
                  [comment=>"This is an abstract class for use with the NCBI taxonomy to name the depth of the node within the tree. The link between the node term and the rank is only visible if you are using an obo 1.3 aware browser/editor; otherwise this can be ignored"]
                 ]);

    my $lnum = 0;
    my %h = ();
    my $text;
    while (my $line = <$fh>) {
        chomp $line;
        if ($line eq '//') {
            $self->emit_term(\%h,$text);
            %h = ();
            $text = '';
        }
        else {
            if ($line =~ /^([\w\s\-]+)\s+:\s*(.*)/) {
                my ($k,$v) = ($1,$2);
                $k = lc($k); # lowercase
                $k =~ s/\s+$//;  # removing trailing ws
                push(@{$h{$k}},$v);
            }
            else {
                $self->parse_err("Line: $line");
            }
            $text .= "$line\n";
        }
    }
    $self->pop_stack_to_depth(0);  # end event obo
}

sub _rank_id {
    my $rank = shift;
    $rank =~ s/\s+/_/g;
    _fix_id($rank);
}

sub _fix_id {
    return "NCBITaxon:$_[0]";
}

sub emit_term {
    my ($self, $h, $text) = @_;
    my $id = pop @{$h->{id}};
    if (!$id) {
        $self->parse_err("No id! in:\n$text");
        return;
    }
    $id = _fix_id($id);
    $self->start_event(TERM);
    $self->event(ID,$id);
    my $name = pop @{$h->{'scientific name'}};
    my ($gname) = @{$h->{'genbank common name'} || []};
    if (!$name) {
        $name = $gname;
        pop @{$h->{'genbank common name'}} if $gname;
    }
    if ($self->{name_h}->{$name}) {
        $name .= " [$id]"; # force unique
    }
    $self->{name_h}->{$name} = $id;
    $self->event(NAME, $name);
    foreach my $st (keys %synonymtypes) {
        my $syns = $h->{$st};
        next unless $syns;
        my $scope = $synonymtypes{$st}->[0];
        foreach my $s (@$syns) {
            my @xrefs = ();
            if ($s =~ /\"(.+)\"\s*(.+)/ ||
                $s =~ /\'(.+)\'\s*(.+)/) {
                my $xref = $2;
                $s = $1;
                $xref =~ s/\s+/_/g;
                $xref =~ tr/\(\)//d;
                $xref =~ tr/\[\]//d;
                $xref =~ s@,@\\,@g;
                push(@xrefs, [dbxref=>[[acc=>$xref],[dbname=>"NCBITaxonRef"]]]);
            }
            $self->event(SYNONYM,[
                                  ['@'=>[['scope',$scope],
                                         [SYNONYM_TYPE,syn($st)]]],
                                  [SYNONYM_TEXT,$s],
                                  @xrefs]);
        }
    }
    my $rank = pop @{$h->{rank}};
    if ($rank eq 'no rank') {
        $rank = undef;
    }
    if ($rank) {
        if (!$self->{__rank}->{$rank}) {
            $self->{__rank}->{$rank} = 1;
            $self->event(TERM,[[ID,_rank_id($rank)],
                               [NAME,$rank],
                               [IS_A,_rank_id('taxonomic_rank')],
                              ]);
        }

        #this is the correct way to handle this - as annotation properties
        $self->event(PROPERTY_VALUE,[[TYPE,'has_rank'],
                                     [TO,_rank_id($rank)]])
          if $rank;
        
# do it this way for now until oboedit is fixed:
#        $self->event(RELATIONSHIP,[[TYPE,'has_rank'],
#                                   [TO,_rank_id($rank)]])
    }

    my $gc = pop @{$h->{'gc id'}};
    $self->event(XREF, "GC_ID:$gc") if $gc;
    my $parent_id = pop @{$h->{'parent id'}};
    if ($parent_id) {
        $parent_id = _fix_id($parent_id);
        $self->event(IS_A,$parent_id);
    }
    $self->end_event(TERM);
}

1;
