CoordSystemAdaptor.pm 36.5 KB
Newer Older
1 2
=head1 LICENSE

3
Copyright [1999-2013] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
4

5 6 7 8 9 10 11 12 13 14 15 16 17
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

=cut
18 19 20 21 22


=head1 CONTACT

  Please email comments or questions to the public Ensembl
Magali Ruffier's avatar
Magali Ruffier committed
23
  developers list at <http://lists.ensembl.org/mailman/listinfo/dev>.
24 25

  Questions may also be sent to the Ensembl help desk at
Magali Ruffier's avatar
Magali Ruffier committed
26
  <http://www.ensembl.org/Help/Contact>.
27 28

=cut
29 30 31 32 33 34 35

=head1 NAME

Bio::EnsEMBL::DBSQL::CoordSystemAdaptor

=head1 SYNOPSIS

36 37 38
  use Bio::EnsEMBL::Registry;

  Bio::EnsEMBL::Registry->load_registry_from_db(
39 40
    -host => 'ensembldb.ensembl.org',
    -user => 'anonymous'
41 42
  );

43 44
  $csa = Bio::EnsEMBL::Registry->get_adaptor( "human", "core",
    "coordsystem" );
45 46 47 48

  #
  # Get all coord systems in the database:
  #
49 50
  foreach my $cs ( @{ $csa->fetch_all() } ) {
    print $cs->name, ' ', $cs->version, "\n";
51 52 53 54 55 56
  }

  #
  # Fetching by name:
  #

57
  # use the default version of coord_system 'chromosome' (e.g. NCBI33):
58 59
  $cs = $csa->fetch_by_name('chromosome');

60 61
  # get an explicit version of coord_system 'chromosome':
  $cs = $csa->fetch_by_name( 'chromsome', 'NCBI34' );
62

63 64 65
  # get all coord_systems of name 'chromosome':
  foreach $cs ( @{ $csa->fetch_all_by_name('chromosome') } ) {
    print $cs->name, ' ', $cs->version, "\n";
66 67 68
  }

  #
69 70 71 72 73 74
  # Fetching by rank:
  #
  $cs = $csa->fetch_by_rank(2);

  #
  # Fetching the pseudo coord system 'toplevel'
75 76
  #

77
  # Get the default top_level coord system:
78 79
  $cs = $csa->fetch_top_level();

80
  # can also use an alias in fetch_by_name:
81 82
  $cs = $csa->fetch_by_name('toplevel');

83
  # can also request toplevel using rank=0
84 85
  $cs = $csa->fetch_by_rank(0);

86 87 88 89
  #
  # Fetching by sequence level:
  #

90
  # Get the coord system which is used to store sequence:
91 92
  $cs = $csa->fetch_sequence_level();

93
  # can also use an alias in fetch_by_name:
94 95 96 97 98 99 100 101 102 103
  $cs = $csa->fetch_by_name('seqlevel');

  #
  # Fetching by id
  #
  $cs = $csa->fetch_by_dbID(1);


=head1 DESCRIPTION

104 105
This adaptor allows the querying of information from the coordinate
system adaptor.
106 107

Note that many coordinate systems do not have a concept of a version
108 109 110 111 112 113
for the entire coordinate system (though they may have a per-sequence
version).  The 'chromosome' coordinate system usually has a version
(i.e. the assembly version) but the clonal coordinate system does not
(despite having individual sequence versions).  In the case where a
coordinate system does not have a version an empty string ('') is used
instead.
114

115
=head1 METHODS
116 117 118

=cut

119 120
package Bio::EnsEMBL::DBSQL::CoordSystemAdaptor;

121 122 123 124
use strict;
use warnings;

use Bio::EnsEMBL::DBSQL::BaseAdaptor;
125
use Bio::EnsEMBL::Utils::Exception qw(throw warning deprecate);
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142
use Bio::EnsEMBL::CoordSystem;

use vars qw(@ISA);

@ISA = qw(Bio::EnsEMBL::DBSQL::BaseAdaptor);


=head2 new

  Arg [1]    : See BaseAdaptor for arguments (none specific to this
               subclass)
  Example    : $cs = $db->get_CoordSystemAdaptor(); #better than new()
  Description: Creates a new CoordSystem adaptor and caches the contents
               of the coord_system table in memory.
  Returntype : Bio::EnsEMBL::DBSQL::CoordSystemAdaptor
  Exceptions : none
  Caller     :
143
  Status     : Stable
144 145 146 147

=cut

sub new {
148
  my ( $proto, @args ) = @_;
149

150 151
  my $class = ref($proto) || $proto;
  my $self = $class->SUPER::new(@args);
152 153 154

  #
  # Cache the entire contents of the coord_system table cross-referenced
155
  # by dbID and name.
156 157
  #

158
  # keyed on name, list of coord_system value
159 160
  $self->{'_name_cache'} = {};

161
  # keyed on id, coord_system value
162 163
  $self->{'_dbID_cache'} = {};

164
  # keyed on rank
165 166
  $self->{'_rank_cache'} = {};

167 168
  # keyed on id, 1/undef values
  $self->{'_is_sequence_level'}  = {};
169 170
  $self->{'_is_default_version'} = {};

171 172 173 174 175 176
  #cache to store the seq_region_mapping information
  #from internal->external
  $self->{'_internal_seq_region_mapping'} = {};
  #from external->internal
  $self->{'_external_seq_region_mapping'} = {};

177
  my $sth = $self->prepare(
178 179 180 181 182
                  'SELECT coord_system_id, name, rank, version, attrib '
                    . 'FROM coord_system '
                    . 'WHERE species_id = ?' );

  $sth->bind_param( 1, $self->species_id(), SQL_INTEGER );
183 184
  $sth->execute();

185 186
  my ( $dbID, $name, $rank, $version, $attrib );
  $sth->bind_columns( \( $dbID, $name, $rank, $version, $attrib ) );
187

188
  while ( $sth->fetch() ) {
189 190
    my $seq_lvl = 0;
    my $default = 0;
191 192 193

    if ( defined($attrib) ) {
      foreach my $attrib ( split( ',', $attrib ) ) {
194
        $self->{"_is_$attrib"}->{$dbID} = 1;
195
        if ( $attrib eq 'sequence_level' ) {
196
          $seq_lvl = 1;
197
        } elsif ( $attrib eq 'default_version' ) {
198 199 200 201 202
          $default = 1;
        }
      }
    }

203 204 205 206 207 208 209 210
    my $cs =
      Bio::EnsEMBL::CoordSystem->new( -DBID           => $dbID,
                                      -ADAPTOR        => $self,
                                      -NAME           => $name,
                                      -VERSION        => $version,
                                      -RANK           => $rank,
                                      -SEQUENCE_LEVEL => $seq_lvl,
                                      -DEFAULT        => $default );
211 212 213

    $self->{'_dbID_cache'}->{$dbID} = $cs;

214
    $self->{'_name_cache'}->{ lc($name) } ||= [];
215
    $self->{'_rank_cache'}->{$rank} = $cs;
216 217 218 219

    push @{ $self->{'_name_cache'}->{ lc($name) } }, $cs;

  } ## end while ( $sth->fetch() )
220 221
  $sth->finish();

222
  $self->_cache_mapping_paths();
223

224
  $self->_cache_seq_region_mapping();
225

226
  return $self;
227
} ## end sub new
228

229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249
sub _cache_seq_region_mapping {
  #
  # This cache will load the information from the seq_region_table, if
  # any, to allow mapping between internal and external seq_region_id.
  #

  my ($self) = @_;

  # For a given core database, will return the schema_build information.
  my $schema_build = $self->db->_get_schema_build();

  # Prepare the query to get relation for the current database being
  # used.
  my $sql = qq(
  SELECT    s.internal_seq_region_id,
            s.external_seq_region_id
  FROM      seq_region_mapping s,
            mapping_set ms,
            seq_region sr,
            coord_system cs
  WHERE     ms.mapping_set_id = s.mapping_set_id
250
    AND     ms.internal_schema_build = ?
251 252 253 254 255 256 257 258 259 260
    AND     s.internal_seq_region_id = sr.seq_region_id
    AND     sr.coord_system_id = cs.coord_system_id
    AND     cs.species_id = ?);

  my $sth = $self->prepare($sql);

  $sth->bind_param( 1, $schema_build,       SQL_VARCHAR );
  $sth->bind_param( 2, $self->species_id(), SQL_INTEGER );

  $sth->execute();
261

262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280
  # Load the cache:
  foreach my $row ( @{ $sth->fetchall_arrayref() } ) {
    # internal->external
    $self->{'_internal_seq_region_mapping'}->{ $row->[0] } = $row->[1];
    # external->internal
    $self->{'_external_seq_region_mapping'}->{ $row->[1] } = $row->[0];
  }

  $sth->finish();

} ## end sub _cache_seq_region_mapping


sub _cache_mapping_paths {
  # Retrieve a list of available mappings from the meta table.  This
  # may eventually be moved a table of its own if this proves too
  # cumbersome.

  my ($self) = @_;
281

282
  my %mapping_paths;
283
  my $mc = $self->db()->get_MetaContainer();
284

285 286 287 288 289
MAP_PATH:
  foreach
    my $map_path ( @{ $mc->list_value_by_key('assembly.mapping') } )
  {
    my @cs_strings = split( /[|#]/, $map_path );
290

291
    if ( scalar(@cs_strings) < 2 ) {
292 293
      warning(   "Incorrectly formatted assembly.mapping value in meta "
               . "table: $map_path" );
294 295 296 297 298
      next MAP_PATH;
    }

    my @coord_systems;
    foreach my $cs_string (@cs_strings) {
299 300 301 302
      my ( $name, $version ) = split( /:/, $cs_string );

      my $cs = $self->fetch_by_name( $name, $version );

303
      if ( !defined($cs) ) {
304 305
        warning(   "Unknown coordinate system specified in meta table "
                 . " assembly.mapping:\n  $name:$version" );
306 307
        next MAP_PATH;
      }
308

309
      push( @coord_systems, $cs );
310 311
    }

312 313 314 315
    # If the delimiter is a '#' we want a special case, multiple parts
    # of the same component map to the same assembly part.  As this
    # looks like the "long" mapping, we just make the path a bit longer
    # :-)
316

317 318
    if ( index( $map_path, '#' ) != -1 && scalar(@coord_systems) == 2 )
    {
319
      splice( @coord_systems, 1, 0, (undef) );
320 321
    }

322
    my $cs1 = $coord_systems[0];
323
    my $cs2 = $coord_systems[$#coord_systems];
324

325 326 327 328
    my $key1 = $cs1->name();
    $key1 .= ':' . $cs1->version() if $cs1->version();
    my $key2 = $cs2->name();
    $key2 .= ':' . $cs2->version() if $cs2->version();
329

330 331 332 333
    if ( exists( $mapping_paths{"$key1|$key2"} ) ) {
      warning(   "Meta table specifies multiple mapping paths between "
               . "coord systems $key1 and $key2.\n"
               . "Choosing shorter path arbitrarily." );
334

335 336 337
      if ( scalar( @{ $mapping_paths{"$key1|$key2"} } ) <
           scalar(@coord_systems) )
      {
338 339
        next MAP_PATH;
      }
340 341 342
    }

    $mapping_paths{"$key1|$key2"} = \@coord_systems;
343
  } ## end foreach my $map_path ( @{ $mc...
344

345
  # Create the pseudo coord system 'toplevel' and cache it so that only
346
  # one of these is created for each database.
347 348 349 350 351

  my $toplevel =
    Bio::EnsEMBL::CoordSystem->new( -TOP_LEVEL => 1,
                                    -NAME      => 'toplevel',
                                    -ADAPTOR   => $self );
352

353
  $self->{'_top_level'}     = $toplevel;
354
  $self->{'_mapping_paths'} = \%mapping_paths;
355

356 357
  return 1;
} ## end sub _cache_mapping_paths
358 359 360 361 362 363 364

=head2 fetch_all

  Arg [1]    : none
  Example    : foreach my $cs (@{$csa->fetch_all()}) {
                 print $cs->name(), ' ', $cs->version(), "\n";
               }
365 366 367 368
  Description: Retrieves every coordinate system defined in the DB.
               These will be returned in ascending order of rank. I.e.
               The highest coordinate system with rank=1 would be first in the
               array.
369 370 371
  Returntype : listref of Bio::EnsEMBL::CoordSystems
  Exceptions : none
  Caller     : general
372
  Status     : Stable
373 374 375 376 377 378

=cut

sub fetch_all {
  my $self = shift;

379 380 381 382 383 384
  my @coord_systems;

  #order the array by rank in ascending order
  foreach my $rank (sort {$a <=> $b} keys %{$self->{'_rank_cache'}}) {
    push @coord_systems, $self->{'_rank_cache'}->{$rank};
  }
385 386 387 388 389 390

  return \@coord_systems;
}



391 392 393 394 395 396 397 398 399 400 401
=head2 fetch_by_rank

  Arg [1]    : int $rank
  Example    : my $cs = $coord_sys_adaptor->fetch_by_rank(1);
  Description: Retrieves a CoordinateSystem via its rank. 0 is a special
               rank reserved for the pseudo coordinate system 'toplevel'.
               undef is returned if no coordinate system of the specified rank
               exists.
  Returntype : Bio::EnsEMBL::CoordSystem
  Exceptions : none
  Caller     : general
402
  Status     : Stable
403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420

=cut

sub fetch_by_rank {
  my $self = shift;
  my $rank = shift;

  throw("Rank argument must be defined.") if(!defined($rank));
  throw("Rank argument must be a non-negative integer.") if($rank !~ /^\d+$/);

  if($rank == 0) {
    return $self->fetch_top_level();
  }

  return $self->{'_rank_cache'}->{$rank};
}


421 422 423 424 425 426 427 428 429 430 431
=head2 fetch_by_name

  Arg [1]    : string $name
               The name of the coordinate system to retrieve.  Alternatively
               this may be an alias for a real coordinate system.  Valid
               aliases are 'toplevel' and 'seqlevel'.
  Arg [2]    : string $version (optional)
               The version of the coordinate system to retrieve.  If not
               specified the default version will be used.
  Example    : $coord_sys = $csa->fetch_by_name('clone');
               $coord_sys = $csa->fetch_by_name('chromosome', 'NCBI33');
432 433 434
               # toplevel is an pseudo coord system representing the highest
               # coord system in a given region
               # such as the chromosome coordinate system
435 436 437 438 439 440
               $coord_sys = $csa->fetch_by_name('toplevel');
               #seqlevel is an alias for the sequence level coordinate system
               #such as the clone or contig coordinate system
               $coord_sys = $csa->fetch_by_name('seqlevel');
  Description: Retrieves a coordinate system by its name
  Returntype : Bio::EnsEMBL::CoordSystem
441
  Exceptions : throw if no name argument provided
442 443
               warning if no version provided and default does not exist
  Caller     : general
444
  Status     : Stable
445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465

=cut

sub fetch_by_name {
  my $self = shift;
  my $name = lc(shift); #case insensitve matching
  my $version = shift;

  throw('Name argument is required.') if(!$name);

  $version = lc($version) if($version);


  if($name eq 'seqlevel') {
    return $self->fetch_sequence_level();
  } elsif($name eq 'toplevel') {
    return $self->fetch_top_level($version);
  }

  if(!exists($self->{'_name_cache'}->{$name})) {
    if($name =~ /top/) {
466
      warning("Did you mean 'toplevel' coord system instead of '$name'?");
467
    } elsif($name =~ /seq/) {
468
      warning("Did you mean 'seqlevel' coord system instead of '$name'?");
469
    }
470
    return undef;
471 472 473 474 475 476 477 478 479 480 481 482 483
  }

  my @coord_systems = @{$self->{'_name_cache'}->{$name}};

  foreach my $cs (@coord_systems) {
    if($version) {
      return $cs if(lc($cs->version()) eq $version);
    } elsif($self->{'_is_default_version'}->{$cs->dbID()}) {
      return $cs;
    }
  }

  if($version) {
484 485
    #the specific version we were looking for was not found
    return undef;
486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510
  }

  #didn't find a default, just take first one
  my $cs =  shift @coord_systems;
  my $v = $cs->version();
  warning("No default version for coord_system [$name] exists. " .
      "Using version [$v] arbitrarily");

  return $cs;
}


=head2 fetch_all_by_name

  Arg [1]    : string $name
               The name of the coordinate system to retrieve.  This can be
               the name of an actual coordinate system or an alias for a
               coordinate system.  Valid aliases are 'toplevel' and 'seqlevel'.
  Example    : foreach my $cs (@{$csa->fetch_all_by_name('chromosome')}){
                 print $cs->name(), ' ', $cs->version();
               }
  Description: Retrieves all coordinate systems of a particular name
  Returntype : listref of Bio::EnsEMBL::CoordSystem objects
  Exceptions : throw if no name argument provided
  Caller     : general
511
  Status     : Stable
512 513 514 515 516 517 518 519 520 521 522 523

=cut

sub fetch_all_by_name {
  my $self = shift;
  my $name = lc(shift); #case insensitive matching

  throw('Name argument is required') if(!$name);

  if($name eq 'seqlevel') {
    return [$self->fetch_sequence_level()];
  } elsif($name eq 'toplevel') {
524
    return [$self->fetch_top_level()];
525 526 527 528 529
  }

  return $self->{'_name_cache'}->{$name} || [];
}

530
=head2 fetch_all_by_version
531

532 533 534 535 536 537 538 539 540 541
  Arg [1]    : string $version
               The version of the coordinate systems to retrieve.
  Example    : foreach my $cs (@{$csa->fetch_all_by_version('GRCh37')}){
                 print $cs->name(), ' ', $cs->version();
               }
  Description: Retrieves all coordinate systems of a particular version
  Returntype : ArrayRef of Bio::EnsEMBL::CoordSystem objects
  Exceptions : throw if no name argument provided
  Caller     : general
  Status     : Stable
542

543
=cut
544

545 546 547
sub fetch_all_by_version {
  my ($self, $version) = @_;
  throw "Version argument is required" if ! $version;
548 549 550 551 552 553 554 555 556 557 558 559 560 561
  my @coord_systems;

  foreach my $rank (sort {$a <=> $b} keys %{$self->{'_rank_cache'}}) {
    if ($self->{'_rank_cache'}->{$rank}->version()) {
      if ($self->{'_rank_cache'}->{$rank}->version() eq $version) {
        push @coord_systems, $self->{'_rank_cache'}->{$rank};
      }
    } else {
      if (!$version) {
        push @coord_systems, $self->{'_rank_cache'}->{$rank};
      }
    }
  }
  return \@coord_systems;
562
}
563 564 565 566 567 568

=head2 fetch_by_dbID

  Arg [1]    : int dbID
  Example    : $cs = $csa->fetch_by_dbID(4);
  Description: Retrieves a coord_system via its internal
569 570 571
               identifier, or undef if no coordinate system with the provided
               id exists.
  Returntype : Bio::EnsEMBL::CoordSystem or undef
572 573
  Exceptions : thrown if no coord_system exists for specified dbID
  Caller     : general
574
  Status     : Stable
575 576 577 578 579 580 581 582 583 584 585

=cut

sub fetch_by_dbID {
  my $self = shift;
  my $dbID = shift;

  throw('dbID argument is required') if(!$dbID);

  my $cs = $self->{'_dbID_cache'}->{$dbID};

586
  return undef if(!$cs);
587 588 589 590 591 592 593 594

  return $cs;
}



=head2 fetch_top_level

595
  Arg [1]    : none
596
  Example    : $cs = $csa->fetch_top_level();
597
  Description: Retrieves the toplevel pseudo coordinate system.
Kieron Taylor's avatar
Kieron Taylor committed
598
  Returntype : Bio::EnsEMBL::CoordSystem object
599 600
  Exceptions : none
  Caller     : general
601
  Status     : Stable
602 603 604

=cut

605
sub fetch_top_level {
606 607
  my $self = shift;

608
  return $self->{'_top_level'};
609 610 611 612 613 614 615 616 617 618 619 620 621
}


=head2 fetch_sequence_level

  Arg [1]    : none
  Example    : ($id, $name, $version) = $csa->fetch_sequence_level();
  Description: Retrieves the coordinate system at which sequence
               is stored at.
  Returntype : Bio::EnsEMBL::CoordSystem
  Exceptions : throw if no sequence_level coord system exists at all
               throw if multiple sequence_level coord systems exists
  Caller     : general
622
  Status     : Stable
623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639

=cut

sub fetch_sequence_level {
  my $self = shift;

  my @dbIDs = keys %{$self->{'_is_sequence_level'}};

  throw('No sequence_level coord_system is defined') if(!@dbIDs);

  if(@dbIDs > 1) {
    throw('Multiple sequence_level coord_systems are defined.' .
          'Only one is currently supported');
  }

  return $self->{'_dbID_cache'}->{$dbIDs[0]};
}
640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666
=head2 get_default_version

  Arg [1]    : none
  Example    : $version = $csa->get_default_version();
  Description: Retrieves the default version of the assembly
  Returntype : String
  Exceptions : throw if no default version is defined
  Caller     : general
  Status     : Stable

=cut

sub get_default_version {
  my $self = shift;

  my $version;
  foreach my $dbID (keys %{$self->{'_is_default_version'}}) {
    if ($self->{'_dbID_cache'}->{$dbID}->version) {
      $version = $self->{'_dbID_cache'}->{$dbID}->version;
      last;
    }
  }

  return $version;
}


667

668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700
=head2 get_all_versions

  Arg [1]    : none
  Example    : @versions = $csa->get_all_versions();
  Description: Retrieves all the available versions of assemblies
  Returntype : Listref of versions (strings)
  Exceptions : throw if no version is defined
  Caller     : general
  Status     : Stable

=cut

sub get_all_versions {
  my $self = shift;

  my %hash_versions;
  my @versions;
  my $version;
  foreach my $dbID (sort {$a <=> $b} keys %{$self->{'_rank_cache'}}) {
    if ($self->{'_rank_cache'}->{$dbID}->version) {
      $version = $self->{'_rank_cache'}->{$dbID}->version;
      if (!$hash_versions{$version}) {
        $hash_versions{$version} = 1;
        push @versions, $version;
      }
    }
  }

  throw('No versions found') if(!scalar(@versions));

  return \@versions;
}

701 702 703 704 705 706 707

=head2 get_mapping_path

  Arg [1]    : Bio::EnsEMBL::CoordSystem $cs1
  Arg [2]    : Bio::EnsEMBL::CoordSystem $cs2
  Example    : foreach my $cs @{$csa->get_mapping_path($cs1,$cs2);
  Description: Given two coordinate systems this will return a mapping path
708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751
               between them if one has been defined.  Allowed Mapping paths are
               explicitly defined in the meta table.  The following is an
               example:

          mysql> select * from meta where meta_key = 'assembly.mapping';
          +---------+------------------+--------------------------------------+
          | meta_id | meta_key         | meta_value                           |
          +---------+------------------+--------------------------------------+
          |      20 | assembly.mapping | chromosome:NCBI34|contig             |
          |      21 | assembly.mapping | clone|contig                         |
          |      22 | assembly.mapping | supercontig|contig                   |
          |      23 | assembly.mapping | chromosome:NCBI34|contig|clone       |
          |      24 | assembly.mapping | chromosome:NCBI34|contig|supercontig |
          |      25 | assembly.mapping | supercontig|contig|clone             |
          +---------+------------------+--------------------------------------+

               For a one-step mapping path to be valid there needs to be
               a relationship between the two coordinate systems defined in
               the assembly table.  Two step mapping paths work by building
               on the one-step mapping paths which are already defined.

               The first coordinate system in a one step mapping path must
               be the assembled coordinate system and the second must be
               the component.

               Example of use:
               my $cs1 = $cs_adaptor->fetch_by_name('contig');
               my $cs2 = $cs_adaptor->fetch_by_name('chromosome');

               my @path = @{$cs_adaptor->get_mapping_path($cs1,$cs2)};

               if(!@path) {
                 print "No mapping path.";
               }
               elsif(@path == 2) {
                 print "2 step mapping path.";
                 print "Assembled = " . $path[0]->name() . "\n";
                 print "Component = " . $path[1]->name() . "\n";
               } else {
                 print "Multi step mapping path\n";
               }

  Returntype : reference to a list of Bio::EnsEMBL::CoordSystem objects

752 753
  Exceptions : none
  Caller     : general
754
  Status     : Stable
755 756 757 758 759 760 761 762

=cut

sub get_mapping_path {
  my $self = shift;
  my $cs1 = shift;
  my $cs2 = shift;

763 764 765 766 767 768
  if(!ref($cs1) || !ref($cs2) ||
     !$cs1->isa('Bio::EnsEMBL::CoordSystem') ||
     !$cs2->isa('Bio::EnsEMBL::CoordSystem')) {
    throw('Two Bio::EnsEMBL::CoordSystem arguments expected.');
  }

769 770 771 772
  my $key1 = $cs1->name();
  $key1 .= ':' . $cs1->version() if ($cs1->version());
  my $key2 = $cs2->name();
  $key2 .= ':' . $cs2->version() if ($cs2->version());
773

774
  my $path = $self->{'_mapping_paths'}->{"$key1|$key2"};
775

776
  return $path if($path);
777

778
  $path = $self->{'_mapping_paths'}->{"$key2|$key1"};
779

780 781 782
  if(!$path) {
    # No path was explicitly defined, but we might be able to guess a
    # suitable path.  We only guess for missing 2 step paths.
783

784 785 786 787 788
    my %mid1;
    my %mid2;

    foreach my $path (values(%{$self->{'_mapping_paths'}})) {
      next if(@$path != 2);
789

790 791 792 793 794 795
      my $match = undef;

      if($path->[0]->equals($cs1)) {
        $match = 1;
      } elsif($path->[1]->equals($cs1)) {
        $match = 0;
796 797
      }

798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850
      if(defined($match)) {
        my $mid = $path->[$match];
        my $midkey = $mid->name() . ':' . $mid->version();

        # is the same cs mapped to by other cs?
        if($mid2{$midkey}) {
          my $path = [$cs1,$mid,$cs2];
          $self->{'_mapping_paths'}->{"$key1|$key2"} = $path;
          $key1 =~ s/\:$//;
          $key2 =~ s/\:$//;
          $midkey =~ s/\:$//;
          warning("Using implicit mapping path between '$key1' and '$key2' " .
                  "coord systems.\n" .
                  "An explicit 'assembly.mapping' entry should be added " .
                  "to the meta table.\nExample: " .
                  "'$key1|$midkey|$key2'\n");
          return $path;
        } else {
          $mid1{$midkey} = $mid;
        }
      }

      $match = undef;

      if($path->[0]->equals($cs2)) {
        $match = 1;
      } elsif($path->[1]->equals($cs2)) {
        $match = 0;
      }


      if(defined($match)) {
        my $mid = $path->[$match];
        my $midkey = $mid->name() . ':' . $mid->version();

        # is the same cs mapped to by other cs?
        if($mid1{$midkey}) {
          my $path = [$cs2,$mid,$cs1];
          $self->{'_mapping_paths'}->{"$key2|$key1"} = $path;

          $key1 =~ s/\:$//;
          $key2 =~ s/\:$//;
          $midkey =~ s/\:$//;
          warning("Using implicit mapping path between '$key1' and '$key2' " .
                  "coord systems.\n" .
                  "An explicit 'assembly.mapping' entry should be added " .
                  "to the meta table.\nExample: " .
                  "'$key1|$midkey|$key2'\n");

          return $path;
        } else {
          $mid2{$midkey} = $mid;
        }
851 852 853 854
      }
    }
  }

855
  return $path || [];
856 857
}

858 859 860 861
=head2 store_mapping_path

  Arg [1]    : Bio::EnsEMBL::CoordSystem $cs1
  Arg [2]    : Bio::EnsEMBL::CoordSystem $cs2
Kieron Taylor's avatar
Kieron Taylor committed
862
  Arg [3..n] : Bio::EnsEMBL::CoordSystem $cs3..$csN
863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913
  Example    : my $pathref = $csa->store_mapping_path($cs1,$cs2);
  Description: Given two or more coordinate systems this will store 
               mapping paths between them in the database. 

               For example, if $cs1 represents chrs of version
               V1, $cs2 represents contigs, and $cs3 clones then, unless
               they already exist, the following entries will be created 
               in the meta table;
               +------------------+---------------------+ 
               | meta_key         | meta_value          |
               +------------------+---------------------+ 
               | assembly.mapping | chr:V1|clone        |
               | assembly.mapping | clone|contig        |
               | assembly.mapping | chr:V1|clone|contig |
               +------------------+---------------------+


               For a one-step mapping path to be valid there needs to be
               a relationship between the two coordinate systems defined in
               the assembly table.  Two step mapping paths work by building
               on the one-step mapping paths which are already defined.

               The first coordinate system in a one step mapping path must
               be the assembled coordinate system and the second must be
               the component.

  Returntype : reference to a list of lists of new meta_value mapping strings
               created for assembly.mapping
  Exceptions : CoordSystems with no rank/duplicated rank
  Caller     : general
  Status     : Experimental

=cut

sub store_mapping_path{
  my $self = shift;
  my @csystems = @_;

  # Validate and sort the args
  my %seen_ranks;
  @csystems >= 2 or throw('Need two or more CoordSystems');
  my $validate = sub{ 
    ref($_[0]) && $_[0]->isa('Bio::EnsEMBL::CoordSystem') or
        throw('CoordSystem argument expected.');
    my $rank = $_[0]->rank || 
        throw('CoordSystem has no rank: '.$_[0]->name);
    $seen_ranks{$rank} &&
        throw('CoordSystem '.$_[0]->name." shares rank $rank with ".
              $seen_ranks{$rank}->name);
    $seen_ranks{$rank} = $_[0];
  };
914 915 916 917 918 919 920 921 922
  @csystems = map{&{$validate}($_)} @csystems;
  my ($key, @keys);
  foreach my $cs (@csystems) {
    $key = $cs->name();
    if ($cs->version()) {
      $key .= ":" . $cs->version();
    }
    push @keys, $key;
  }
923 924 925 926

  # For each pair in the sorted list, store in the DB
  my $meta = $self->db->get_MetaContainer;
  my @retlist;
927 928 929 930 931
  for( my $i=1; $i<@keys; $i++ ){
    for( my $j=0; $j<(@keys-$i); $j++ ){
      my $mapping = join( "|", @keys );
      
      my $mapping_key = join( "|", @keys );
932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949
      # Skip existing
      next if $self->{'_mapping_paths'}->{$mapping_key};
      
      # Update the database
      $meta->store_key_value('assembly.mapping',$mapping);
      push @retlist, $mapping;
    }
  }

  if( @retlist ){
    # Update mapping path cache
    $self->_cache_mapping_paths;
  }

  # Return the mappings that we have just created
  return [@retlist];
}

950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027

=head2 store_multiple_mapping_path

  Arg [1]    : Bio::EnsEMBL::CoordSystem $cs1
  Arg [2]    : Bio::EnsEMBL::CoordSystem $cs2
  Arg [3..n] : Bio::EnsEMBL::CoordSystem $cs3..$csN
  Example    : my $pathref = $csa->store_multiple_mapping_path($cs1,$cs2);
  Description: Given two or more coordinate systems this will store 
               multiple mapping paths between them in the database. 

               Works similarly to the store_mapping_path method
               But will presume every coord system can be mapped in multiple
               ways to the other coord systems
               This is represented by the use of '#' instead of '|'
               in the mapping key

  Returntype : reference to a list of lists of new meta_value mapping strings
               created for assembly.mapping
  Exceptions : CoordSystems with no rank/duplicated rank
  Caller     : general
  Status     : Experimental

=cut

sub store_multiple_mapping_path{
  my $self = shift;
  my @csystems = @_;

  # Validate and sort the args
  my %seen_ranks;
  @csystems >= 2 or throw('Need two or more CoordSystems');
  my $validate = sub{
    ref($_[0]) && $_[0]->isa('Bio::EnsEMBL::CoordSystem') or
        throw('CoordSystem argument expected.');
    my $rank = $_[0]->rank ||
        throw('CoordSystem has no rank: '.$_[0]->name);
    $seen_ranks{$rank} &&
        throw('CoordSystem '.$_[0]->name." shares rank $rank with ".
              $seen_ranks{$rank}->name);
    $seen_ranks{$rank} = $_[0];
  };
  @csystems = map{&{$validate}($_)} @csystems;
  my ($key, @keys);
  foreach my $cs (@csystems) {
    $key = $cs->name();
    if ($cs->version()) {
      $key .= ":" . $cs->version();
    }
    push @keys, $key;
  }
  # For each pair in the sorted list, store in the DB
  my $meta = $self->db->get_MetaContainer;
  my @retlist;
  for( my $i=1; $i<@keys; $i++ ){
    for( my $j=0; $j<(@keys-$i); $j++ ){
      my $mapping = join( "#", @keys );

      my $mapping_key = join( "#", @keys );
      # Skip existing
      next if $self->{'_mapping_paths'}->{$mapping_key};

      # Update the database
      $meta->store_key_value('assembly.mapping',$mapping);
      push @retlist, $mapping;
    }
  }

  if( @retlist ){
    # Update mapping path cache
    $self->_cache_mapping_paths;
  }

  # Return the mappings that we have just created
  return [@retlist];
}



1028
=head2 fetch_by_attrib
1029

1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042
  Arg [1]    : string attrib
  Arg [2]    : (optional) string version
  Example    : $csa->fetch_by_attrib('default_version','NCBIM37');
  Description: Retrieves a CoordSystem object from the database that have the specified
               attrib and version, if no version is specified, returns the default version
  Returntype : Bio::EnsEMBL::CoordSystem object
  Exceptions : throw when attrib not present
  Caller     : general
  Status     : Stable

=cut

sub fetch_by_attrib {
1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077
  my $self = shift;
  my $attrib = shift;
  my $version = shift;

  $version = lc($version) if($version);

  my @dbIDs = keys %{$self->{"_is_$attrib"}};

  throw("No $attrib coordinate system defined") if(!@dbIDs);

  foreach my $dbID (@dbIDs) {
    my $cs = $self->{'_dbID_cache'}->{$dbID};
    if($version) {
      return $cs if(lc($version) eq $cs->version());
    } elsif($self->{'_is_default_version'}->{$dbID}) {
      return $cs;
    }
  }

  #specifically requested attrib system was not found
  if($version) {
    throw("$attrib coord_system with version [$version] does not exist");
  }

  #coordsystem with attrib exists but no default is defined:
  my $dbID = shift @dbIDs;
  my $cs = $self->{'_dbID_cache'}->{$dbID};
  my $v = $cs->version();
  warning("No default version for $attrib coord_system exists. " .
          "Using version [$v] arbitrarily");

  return $cs;
}


1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102
sub _fetch_by_attrib{
    my $self = shift;
    my $attrib = shift;
    my $version = shift;

    deprecate("You should be using the public method fetch_by_attrib ".
	      "(without initial underscore) instead");

    return $self->fetch_by_attrib($attrib,$version);
}

=head2 fetch_all_by_attrib

  Arg [1]    : string attrib
  Example    : $csa->fetch_all_by_attrib('default_version');
  Description: Retrieves all CoordSystem object from the database that have the specified
               attrib.
  Returntype : reference to a list of Bio::EnsEMBL::CoordSystem objects
  Exceptions : throw when attrib not present
  Caller     : general
  Status     : Stable

=cut

sub fetch_all_by_attrib {
1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113
  my $self = shift;
  my $attrib = shift;

  my @coord_systems = ();
  foreach my $dbID (keys %{$self->{"_is_$attrib"}}) {
    push @coord_systems, $self->{"_dbID_cache"}->{$dbID};
  }

  return \@coord_systems;
}

1114 1115 1116 1117 1118 1119 1120 1121 1122
sub _fetch_all_by_attrib{
    my $self = shift;
    my $attrib = shift;

    deprecate("You should be using the public method fetch_all_by_attrib ".
	      "(without initial underscore) instead");

    return $self->fetch_all_by_attrib($attrib);
}
1123 1124 1125 1126 1127 1128 1129 1130 1131

=head2 store

  Arg [1]    : Bio::EnsEMBL::CoordSystem
  Example    : $csa->store($coord_system);
  Description: Stores a CoordSystem object in the database.
  Returntype : none
  Exceptions : Warning if CoordSystem is already stored in this database.
  Caller     : none
1132
  Status     : Stable
1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146

=cut

sub store {
  my $self = shift;
  my $cs = shift;

  if(!$cs || !ref($cs) || !$cs->isa('Bio::EnsEMBL::CoordSystem')) {
    throw('CoordSystem argument expected.');
  }

  my $db = $self->db();
  my $name = $cs->name();
  my $version = $cs->version();
1147 1148
  my $rank    = $cs->rank();

1149 1150
  my $seqlevel = $cs->is_sequence_level();
  my $default  = $cs->is_default();
1151 1152 1153 1154 1155 1156 1157

  my $toplevel = $cs->is_top_level();

  if($toplevel) {
    throw("The toplevel CoordSystem cannot be stored");
  }

1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187
  #
  # Do lots of sanity checking to prevent bad data from being entered
  #

  if($cs->is_stored($db)) {
    warning("CoordSystem $name $version is already in db.\n");
    return;
  }

  if($name eq 'toplevel' || $name eq 'seqlevel' || !$name) {
    throw("[$name] is not a valid name for a CoordSystem.");
  }

  if($seqlevel && keys(%{$self->{'_is_sequence_level'}})) {
    throw("There can only be one sequence level CoordSystem.");
  }

  if(exists $self->{'_name_cache'}->{lc($name)}) {
    my @coord_systems = @{$self->{'_name_cache'}->{lc($name)}};
    foreach my $c (@coord_systems) {
      if(lc($c->version()) eq lc($version)) {
        warning("CoordSystem $name $version is already in db.\n");
        return;
      }
      if($default && $self->{'_is_default_version'}->{$c->dbID()}) {
        throw("There can only be one default version of CoordSystem $name");
      }
    }
  }

1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198
  if($rank !~ /^\d+$/) {
    throw("Rank attribute must be a positive integer not [$rank]");
  }
  if($rank == 0) {
    throw("Only toplevel CoordSystem may have rank of 0.");
  }

  if(defined($self->{'_rank_cache'}->{$rank})) {
    throw("CoordSystem with rank [$rank] already exists.");
  }

1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209
  my @attrib;

  push @attrib, 'default_version' if($default);
  push @attrib, 'sequence_level' if($seqlevel);

  my $attrib_str = (@attrib) ? join(',', @attrib) : undef;

  #
  # store the coordinate system in the database
  #

1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222
  my $sth =
    $db->dbc->prepare(   'INSERT INTO coord_system '
                       . 'SET name = ?, '
                       . 'version = ?, '
                       . 'attrib = ?,'
                       . 'rank = ?,'
                       . 'species_id = ?' );

  $sth->bind_param( 1, $name,               SQL_VARCHAR );
  $sth->bind_param( 2, $version,            SQL_VARCHAR );
  $sth->bind_param( 3, $attrib_str,         SQL_VARCHAR );
  $sth->bind_param( 4, $rank,               SQL_INTEGER );
  $sth->bind_param( 5, $self->species_id(), SQL_INTEGER );
1223

1224
  $sth->execute();
1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244
  my $dbID = $sth->{'mysql_insertid'};
  $sth->finish();

  if(!$dbID) {
    throw("Did not get dbID from store of CoordSystem.");
  }

  $cs->dbID($dbID);
  $cs->adaptor($self);

  #
  # update the internal caches that are used for fetching
  #
  $self->{'_is_default_version'}->{$dbID} = 1 if($default);
  $self->{'_is_sequence_level'}->{$dbID} = 1 if($seqlevel);

  $self->{'_name_cache'}->{lc($name)} ||= [];
  push @{$self->{'_name_cache'}->{lc($name)}}, $cs;

  $self->{'_dbID_cache'}->{$dbID} = $cs;
1245
  $self->{'_rank_cache'}->{$rank} = $cs;
1246 1247 1248 1249

  return $cs;
}

1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310
=head2 remove

  Arg [1]    : Bio::EnsEMBL::CoordSystem
  Example    : $csa->remove($coord_system);
  Description: Removes a CoordSystem object from the database.
  Returntype : none
  Exceptions : Warning if CoordSystem is not stored in this database.
  Caller     : none
  Status     : Stable

=cut

sub remove {
  my $self = shift;
  my $cs = shift;

  if(!$cs || !ref($cs) || !$cs->isa('Bio::EnsEMBL::CoordSystem')) {
    throw('CoordSystem argument expected.');
  }

  my $db = $self->db();
  my $name = $cs->name();
  my $version = $cs->version();
  my $dbID = $cs->dbID();
  my $rank = $cs->rank(); 

  #
  # Do lots of sanity checking to prevent bad data from being entered
  #

  if(!$cs->is_stored($db)) {
    warning("CoordSystem $name $version does not exist in db.\n");
    return;
  }

  if($name eq 'toplevel' || $name eq 'seqlevel' || !$name) {
    throw("[$name] is not a valid name for a CoordSystem.");
  }

  #
  # store the coordinate system in the database
  #

  my $sth =
    $db->dbc->prepare(   'DELETE FROM coord_system '
                       . 'WHERE name = ? AND '
                       . 'version = ?' );

  $sth->bind_param( 1, $name,               SQL_VARCHAR );
  $sth->bind_param( 2, $version,            SQL_VARCHAR );

  $sth->execute();
  $sth->finish();

  delete $self->{'_name_cache'}->{lc($name)};

  delete $self->{'_dbID_cache'}->{$dbID};
  delete $self->{'_rank_cache'}->{$rank};

  return $cs;
}
1311 1312

1;