1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 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 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 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 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 701 702 703 704 705 706 707 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
|
# Copyright (C) 2009 by Eric Talevich (eric.talevich@gmail.com)
# This code is part of the Biopython distribution and governed by its
# license. Please see the LICENSE file that should have been included
# as part of this package.
"""Unit tests for the PhyloXML and PhyloXMLIO modules.
"""
import os
import tempfile
import unittest
from itertools import izip, chain
# Python 2.4 doesn't have ElementTree, which PhyloXMLIO needs
from Bio import MissingExternalDependencyError
try:
from Bio.Phylo import PhyloXML as PX, PhyloXMLIO
except ImportError:
raise MissingExternalDependencyError(
"Install an ElementTree implementation if you want to use "
"Bio.Phylo to parse phyloXML files.")
from Bio import Alphabet
from Bio.Seq import Seq
from Bio.SeqRecord import SeqRecord
from Bio.Align import MultipleSeqAlignment
# Example PhyloXML files
EX_APAF = 'PhyloXML/apaf.xml'
EX_BCL2 = 'PhyloXML/bcl_2.xml'
EX_MADE = 'PhyloXML/made_up.xml'
EX_PHYLO = 'PhyloXML/phyloxml_examples.xml'
EX_DOLLO = 'PhyloXML/o_tol_332_d_dollo.xml'
# Temporary file name for Writer tests below
DUMMY = tempfile.mktemp()
# ---------------------------------------------------------
# Parser tests
def _test_read_factory(source, count):
"""Generate a test method for read()ing the given source.
The generated function reads an example file to produce a phyloXML object,
then tests for existence of the root node, and counts the number of
phylogenies under the root.
"""
fname = os.path.basename(source)
def test_read(self):
phx = PhyloXMLIO.read(source)
self.assert_(phx)
self.assertEquals(len(phx), count[0])
self.assertEquals(len(phx.other), count[1])
test_read.__doc__ = "Read %s to produce a phyloXML object." % fname
return test_read
def _test_parse_factory(source, count):
"""Generate a test method for parse()ing the given source.
The generated function extracts each phylogenetic tree using the parse()
function and counts the total number of trees extracted.
"""
fname = os.path.basename(source)
def test_parse(self):
trees = PhyloXMLIO.parse(source)
self.assertEquals(len(list(trees)), count)
test_parse.__doc__ = "Parse the phylogenies in %s." % fname
return test_parse
def _test_shape_factory(source, shapes):
"""Generate a test method for checking tree shapes.
Counts the branches at each level of branching in a phylogenetic tree, 3
clades deep.
"""
fname = os.path.basename(source)
def test_shape(self):
trees = PhyloXMLIO.parse(source)
for tree, shape_expect in izip(trees, shapes):
self.assertEquals(len(tree.clade), len(shape_expect))
for clade, sub_expect in izip(tree.clade, shape_expect):
self.assertEquals(len(clade), sub_expect[0])
for subclade, len_expect in izip(clade, sub_expect[1]):
self.assertEquals(len(subclade), len_expect)
test_shape.__doc__ = "Check the branching structure of %s." % fname
return test_shape
class ParseTests(unittest.TestCase):
"""Tests for proper parsing of example phyloXML files."""
test_read_apaf = _test_read_factory(EX_APAF, (1, 0))
test_read_bcl2 = _test_read_factory(EX_BCL2, (1, 0))
test_read_made = _test_read_factory(EX_MADE, (6, 0))
test_read_phylo = _test_read_factory(EX_PHYLO, (13, 1))
test_read_dollo = _test_read_factory(EX_DOLLO, (1, 0))
test_parse_apaf = _test_parse_factory(EX_APAF, 1)
test_parse_bcl2 = _test_parse_factory(EX_BCL2, 1)
test_parse_made = _test_parse_factory(EX_MADE, 6)
test_parse_phylo = _test_parse_factory(EX_PHYLO, 13)
test_parse_dollo = _test_parse_factory(EX_DOLLO, 1)
test_shape_apaf = _test_shape_factory(EX_APAF,
# lvl-2 clades, sub-clade counts, lvl-3 clades
( ( (2, (2, 2)),
(2, (2, 2)),
),
),
)
test_shape_bcl2 = _test_shape_factory(EX_BCL2,
( ( (2, (2, 2)),
(2, (2, 2)),
),
),
)
test_shape_phylo = _test_shape_factory(EX_PHYLO,
( ( (2, (0, 0)),
(0, ()),
),
( (2, (0, 0)),
(0, ()),
),
( (2, (0, 0)),
(0, ()),
),
( (2, (0, 0)),
(0, ()),
),
( (2, (0, 0)),
(0, ()),
),
( (2, (0, 0)),
(0, ()),
),
( (2, (0, 0)),
(0, ()),
),
( (2, (0, 0)),
(0, ()),
),
( (2, (0, 0)),
(0, ()),
),
( (0, ()),
(2, (0, 0)),
),
( (3, (0, 0, 0)),
(0, ()),
),
( (2, (0, 0)),
(0, ()),
),
( (2, (0, 0)),
(0, ()),
),
),
)
test_shape_dollo = _test_shape_factory(EX_DOLLO,
( ( (2, (2, 2)),
(2, (2, 2)),
),
),
)
class TreeTests(unittest.TestCase):
"""Tests for instantiation and attributes of each complex type."""
# ENH: also test check_str() regexps wherever they're used
def test_Phyloxml(self):
"""Instantiation of Phyloxml objects."""
phx = PhyloXMLIO.read(EX_PHYLO)
self.assert_(isinstance(phx, PX.Phyloxml))
for tree in phx:
self.assert_(isinstance(tree, PX.Phylogeny))
for otr in phx.other:
self.assert_(isinstance(otr, PX.Other))
def test_Other(self):
"""Instantiation of Other objects."""
phx = PhyloXMLIO.read(EX_PHYLO)
otr = phx.other[0]
self.assert_(isinstance(otr, PX.Other))
self.assertEquals(otr.tag, 'alignment')
self.assertEquals(otr.namespace, 'http://example.org/align')
self.assertEquals(len(otr.children), 3)
for child, name, value in izip(otr, ('A', 'B', 'C'), (
'acgtcgcggcccgtggaagtcctctcct', 'aggtcgcggcctgtggaagtcctctcct',
'taaatcgc--cccgtgg-agtccc-cct')):
self.assertEquals(child.tag, 'seq')
self.assertEquals(child.attributes['name'], name)
self.assertEquals(child.value, value)
def test_Phylogeny(self):
"""Instantiation of Phylogeny objects."""
trees = list(PhyloXMLIO.parse(EX_PHYLO))
# Monitor lizards
self.assertEquals(trees[9].name, 'monitor lizards')
self.assertEquals(trees[9].description,
'a pylogeny of some monitor lizards')
self.assertEquals(trees[9].rooted, True)
# Network (unrooted)
tree6 = trees[6]
self.assertEquals(trees[6].name,
'network, node B is connected to TWO nodes: AB and C')
self.assertEquals(trees[6].rooted, False)
def test_Clade(self):
"""Instantiation of Clade objects."""
tree = list(PhyloXMLIO.parse(EX_PHYLO))[6]
clade_ab, clade_c = tree.clade.clades
clade_a, clade_b = clade_ab.clades
for clade, id_source, name, blen in izip(
(clade_ab, clade_a, clade_b, clade_c),
('ab', 'a', 'b', 'c'),
('AB', 'A', 'B', 'C'),
(0.06, 0.102, 0.23, 0.4)):
self.assert_(isinstance(clade, PX.Clade))
self.assertEqual(clade.id_source, id_source)
self.assertEqual(clade.name, name)
self.assertAlmostEqual(clade.branch_length, blen)
def test_Annotation(self):
"""Instantiation of Annotation objects."""
tree = list(PhyloXMLIO.parse(EX_PHYLO))[3]
ann = tree.clade[1].sequences[0].annotations[0]
self.assert_(isinstance(ann, PX.Annotation))
self.assertEqual(ann.desc, 'alcohol dehydrogenase')
self.assertAlmostEqual(ann.confidence.value, 0.67)
self.assertEqual(ann.confidence.type, 'probability')
def test_BinaryCharacters(self):
"""Instantiation of BinaryCharacters objects."""
tree = PhyloXMLIO.parse(EX_DOLLO).next()
bchars = tree.clade[0,0].binary_characters
self.assert_(isinstance(bchars, PX.BinaryCharacters))
self.assertEqual(bchars.type, 'parsimony inferred')
for name, count, value in (
('gained', 2, ['Cofilin_ADF', 'Gelsolin']),
('lost', 0, []),
('present', 2, ['Cofilin_ADF', 'Gelsolin']),
('absent', None, []),
):
self.assertEqual(getattr(bchars, name+'_count'), count)
self.assertEqual(getattr(bchars, name), value)
# TODO: BranchColor -- see made_up.xml
def test_CladeRelation(self):
"""Instantiation of CladeRelation objects."""
tree = list(PhyloXMLIO.parse(EX_PHYLO))[6]
crel = tree.clade_relations[0]
self.assert_(isinstance(crel, PX.CladeRelation))
self.assertEqual(crel.id_ref_0, 'b')
self.assertEqual(crel.id_ref_1, 'c')
self.assertEqual(crel.type, 'network_connection')
def test_Confidence(self):
"""Instantiation of Confidence objects."""
tree = PhyloXMLIO.parse(EX_MADE).next()
self.assertEqual(tree.name, 'testing confidence')
for conf, type, val in izip(tree.confidences,
('bootstrap', 'probability'),
(89.0, 0.71)):
self.assert_(isinstance(conf, PX.Confidence))
self.assertEqual(conf.type, type)
self.assertAlmostEqual(conf.value, val)
self.assertEqual(tree.clade.name, 'b')
self.assertAlmostEqual(tree.clade.width, 0.2)
for conf, val in izip(tree.clade[0].confidences,
(0.9, 0.71)):
self.assert_(isinstance(conf, PX.Confidence))
self.assertEqual(conf.type, 'probability')
self.assertAlmostEqual(conf.value, val)
def test_Date(self):
"""Instantiation of Date objects."""
tree = list(PhyloXMLIO.parse(EX_PHYLO))[11]
silurian = tree.clade[0,0].date
devonian = tree.clade[0,1].date
ediacaran = tree.clade[1].date
for date, desc, val in izip(
(silurian, devonian, ediacaran),
# (10, 20, 30), # range is deprecated
('Silurian', 'Devonian', 'Ediacaran'),
(425, 320, 600)):
self.assert_(isinstance(date, PX.Date))
self.assertEqual(date.unit, 'mya')
# self.assertAlmostEqual(date.range, rang)
self.assertEqual(date.desc, desc)
self.assertAlmostEqual(date.value, val)
def test_Distribution(self):
"""Instantiation of Distribution objects.
Also checks Point type and safe Unicode handling (?).
"""
tree = list(PhyloXMLIO.parse(EX_PHYLO))[10]
hirschweg = tree.clade[0,0].distributions[0]
nagoya = tree.clade[0,1].distributions[0]
eth_zurich = tree.clade[0,2].distributions[0]
san_diego = tree.clade[1].distributions[0]
for dist, desc, lat, long, alt in izip(
(hirschweg, nagoya, eth_zurich, san_diego),
('Hirschweg, Winterthur, Switzerland',
'Nagoya, Aichi, Japan',
u'ETH Z\xfcrich',
'San Diego'),
(47.481277, 35.155904, 47.376334, 32.880933),
(8.769303, 136.915863, 8.548108, -117.217543),
(472, 10, 452, 104)):
self.assert_(isinstance(dist, PX.Distribution))
self.assertEqual(dist.desc, desc)
point = dist.points[0]
self.assert_(isinstance(point, PX.Point))
self.assertEqual(point.geodetic_datum, 'WGS84')
self.assertEqual(point.lat, lat)
self.assertEqual(point.long, long)
self.assertEqual(point.alt, alt)
def test_DomainArchitecture(self):
"""Instantiation of DomainArchitecture objects.
Also checks ProteinDomain type.
"""
tree = PhyloXMLIO.parse(EX_APAF).next()
clade = tree.clade[0,0,0,0,0,0,0,0,0,0]
darch = clade.sequences[0].domain_architecture
self.assert_(isinstance(darch, PX.DomainArchitecture))
self.assertEqual(darch.length, 1249)
for domain, start, end, conf, value in izip(darch.domains,
(6, 109, 605, 647, 689, 733, 872, 993, 1075, 1117, 1168),
(90, 414, 643, 685, 729, 771, 910, 1031, 1113, 1155, 1204),
(7.0e-26, 7.2e-117, 2.4e-6, 1.1e-12, 2.4e-7, 4.7e-14, 2.5e-8,
4.6e-6, 6.3e-7, 1.4e-7, 0.3),
('CARD', 'NB-ARC', 'WD40', 'WD40', 'WD40', 'WD40', 'WD40',
'WD40', 'WD40', 'WD40', 'WD40')):
self.assert_(isinstance(domain, PX.ProteinDomain))
self.assertEqual(domain.start + 1, start)
self.assertEqual(domain.end, end)
self.assertAlmostEqual(domain.confidence, conf)
self.assertEqual(domain.value, value)
def test_Events(self):
"""Instantiation of Events objects."""
tree = list(PhyloXMLIO.parse(EX_PHYLO))[4]
event_s = tree.clade.events
self.assert_(isinstance(event_s, PX.Events))
self.assertEqual(event_s.speciations, 1)
event_d = tree.clade[0].events
self.assert_(isinstance(event_d, PX.Events))
self.assertEqual(event_d.duplications, 1)
def test_Polygon(self):
"""Instantiation of Polygon objects."""
tree = PhyloXMLIO.read(EX_MADE).phylogenies[1]
self.assertEqual(tree.name, 'testing polygon')
dist = tree.clade[0].distributions[0]
for poly in dist.polygons:
self.assert_(isinstance(poly, PX.Polygon))
self.assertEqual(len(poly.points), 3)
self.assertEqual(dist.polygons[0].points[0].alt_unit, 'm')
for point, lat, long, alt in izip(
chain(dist.polygons[0].points, dist.polygons[1].points),
(47.481277, 35.155904, 47.376334, 40.481277, 25.155904,
47.376334),
(8.769303, 136.915863, 8.548108, 8.769303, 136.915863,
7.548108),
(472, 10, 452, 42, 10, 452),
):
self.assert_(isinstance(point, PX.Point))
self.assertEqual(point.geodetic_datum, 'WGS84')
self.assertEqual(point.lat, lat)
self.assertEqual(point.long, long)
self.assertEqual(point.alt, alt)
def test_Property(self):
"""Instantiation of Property objects."""
tree = list(PhyloXMLIO.parse(EX_PHYLO))[8]
for prop, id_ref, value in izip(
tree.properties,
('id_a', 'id_b', 'id_c'),
('1200', '2300', '200')):
self.assert_(isinstance(prop, PX.Property))
self.assertEqual(prop.id_ref, id_ref)
self.assertEqual(prop.datatype, "xsd:integer")
self.assertEqual(prop.ref, "NOAA:depth")
self.assertEqual(prop.applies_to, "node")
self.assertEqual(prop.unit, "METRIC:m" )
self.assertEqual(prop.value, value)
def test_Reference(self):
"""Instantiation of Reference objects."""
tree = PhyloXMLIO.parse(EX_DOLLO).next()
reference = tree.clade[0,0,0,0,0,0].references[0]
self.assert_(isinstance(reference, PX.Reference))
self.assertEqual(reference.doi, '10.1038/nature06614')
self.assertEqual(reference.desc, None)
def test_Sequence(self):
"""Instantiation of Sequence objects.
Also checks Accession and Annotation types.
"""
trees = list(PhyloXMLIO.parse(EX_PHYLO))
# Simple element with id_source
seq0 = trees[4].clade[1].sequences[0]
self.assert_(isinstance(seq0, PX.Sequence))
self.assertEqual(seq0.id_source, 'z')
self.assertEqual(seq0.symbol, 'ADHX')
self.assertEqual(seq0.accession.source, 'ncbi')
self.assertEqual(seq0.accession.value, 'Q17335')
self.assertEqual(seq0.name, 'alcohol dehydrogenase')
self.assertEqual(seq0.annotations[0].ref, 'InterPro:IPR002085')
# More complete elements
seq1 = trees[5].clade[0,0].sequences[0]
seq2 = trees[5].clade[0,1].sequences[0]
seq3 = trees[5].clade[1].sequences[0]
for seq, sym, acc, name, mol_seq, ann_refs in izip(
(seq1, seq2, seq3),
('ADHX', 'RT4I1', 'ADHB'),
('P81431', 'Q54II4', 'Q04945'),
('Alcohol dehydrogenase class-3',
'Reticulon-4-interacting protein 1 homolog, ' \
'mitochondrial precursor',
'NADH-dependent butanol dehydrogenase B'),
('TDATGKPIKCMAAIAWEAKKPLSIEEVEVAPPKSGEVRIKILHSGVCHTD',
'MKGILLNGYGESLDLLEYKTDLPVPKPIKSQVLIKIHSTSINPLDNVMRK',
'MVDFEYSIPTRIFFGKDKINVLGRELKKYGSKVLIVYGGGSIKRNGIYDK'),
(("EC:1.1.1.1", "GO:0004022"),
("GO:0008270", "GO:0016491"),
("GO:0046872", "KEGG:Tetrachloroethene degradation")),
):
self.assert_(isinstance(seq, PX.Sequence))
self.assertEqual(seq.symbol, sym)
self.assertEqual(seq.accession.source, 'UniProtKB')
self.assertEqual(seq.accession.value, acc)
self.assertEqual(seq.name, name)
self.assertEqual(seq.mol_seq.value, mol_seq)
self.assertEqual(seq.annotations[0].ref, ann_refs[0])
self.assertEqual(seq.annotations[1].ref, ann_refs[1])
def test_SequenceRelation(self):
"""Instantiation of SequenceRelation objects."""
tree = list(PhyloXMLIO.parse(EX_PHYLO))[4]
for seqrel, id_ref_0, id_ref_1, type in izip(
tree.sequence_relations,
('x', 'x', 'y'), ('y', 'z', 'z'),
('paralogy', 'orthology', 'orthology')):
self.assert_(isinstance(seqrel, PX.SequenceRelation))
self.assertEqual(seqrel.id_ref_0, id_ref_0)
self.assertEqual(seqrel.id_ref_1, id_ref_1)
self.assertEqual(seqrel.type, type)
def test_Taxonomy(self):
"""Instantiation of Taxonomy objects.
Also checks Id type.
"""
trees = list(PhyloXMLIO.parse(EX_PHYLO))
# Octopus
tax5 = trees[5].clade[0,0].taxonomies[0]
self.assert_(isinstance(tax5, PX.Taxonomy))
self.assertEqual(tax5.id.value, '6645')
self.assertEqual(tax5.id.provider, 'NCBI')
self.assertEqual(tax5.code, 'OCTVU')
self.assertEqual(tax5.scientific_name, 'Octopus vulgaris')
# Nile monitor
tax9 = trees[9].clade[0].taxonomies[0]
self.assert_(isinstance(tax9, PX.Taxonomy))
self.assertEqual(tax9.id.value, '62046')
self.assertEqual(tax9.id.provider, 'NCBI')
self.assertEqual(tax9.scientific_name, 'Varanus niloticus')
self.assertEqual(tax9.common_names[0], 'Nile monitor')
self.assertEqual(tax9.rank, 'species')
def test_Uri(self):
"""Instantiation of Uri objects."""
tree = list(PhyloXMLIO.parse(EX_PHYLO))[9]
uri = tree.clade.taxonomies[0].uri
self.assert_(isinstance(uri, PX.Uri))
self.assertEqual(uri.desc, 'EMBL REPTILE DATABASE')
self.assertEqual(uri.value,
'http://www.embl-heidelberg.de/~uetz/families/Varanidae.html')
# ---------------------------------------------------------
# Serialization tests
class WriterTests(unittest.TestCase):
"""Tests for serialization of objects to phyloXML format.
Modifies the globally defined filenames in order to run the other parser
tests on files (re)generated by PhyloXMLIO's own writer.
"""
def _rewrite_and_call(self, orig_fname, test_cases):
"""Parse, rewrite and retest a phyloXML example file."""
infile = open(orig_fname, 'rb')
phx = PhyloXMLIO.read(infile)
infile.close()
outfile = open(DUMMY, 'w+b')
PhyloXMLIO.write(phx, outfile)
outfile.close()
for cls, tests in test_cases:
inst = cls('setUp')
for test in tests:
getattr(inst, test)()
def test_apaf(self):
"""Round-trip parsing and serialization of apaf.xml."""
global EX_APAF
orig_fname = EX_APAF
try:
EX_APAF = DUMMY
self._rewrite_and_call(orig_fname, (
(ParseTests, [
'test_read_apaf', 'test_parse_apaf', 'test_shape_apaf']),
(TreeTests, ['test_DomainArchitecture']),
))
finally:
EX_APAF = orig_fname
def test_bcl2(self):
"""Round-trip parsing and serialization of bcl_2.xml."""
global EX_BCL2
orig_fname = EX_BCL2
try:
EX_BCL2 = DUMMY
self._rewrite_and_call(orig_fname, (
(ParseTests, [
'test_read_bcl2', 'test_parse_bcl2', 'test_shape_bcl2']),
(TreeTests, ['test_Confidence']),
))
finally:
EX_BCL2 = orig_fname
def test_made(self):
"""Round-trip parsing and serialization of made_up.xml."""
global EX_MADE
orig_fname = EX_MADE
try:
EX_MADE = DUMMY
self._rewrite_and_call(orig_fname, (
(ParseTests, ['test_read_made', 'test_parse_made']),
(TreeTests, ['test_Confidence', 'test_Polygon']),
))
finally:
EX_MADE = orig_fname
def test_phylo(self):
"""Round-trip parsing and serialization of phyloxml_examples.xml."""
global EX_PHYLO
orig_fname = EX_PHYLO
try:
EX_PHYLO = DUMMY
self._rewrite_and_call(orig_fname, (
(ParseTests, [
'test_read_phylo', 'test_parse_phylo', 'test_shape_phylo']),
(TreeTests, [
'test_Phyloxml', 'test_Other',
'test_Phylogeny', 'test_Clade',
'test_Annotation', 'test_CladeRelation',
'test_Date', 'test_Distribution',
'test_Events', 'test_Property',
'test_Sequence', 'test_SequenceRelation',
'test_Taxonomy', 'test_Uri',
]),
))
finally:
EX_PHYLO = orig_fname
def test_dollo(self):
"""Round-trip parsing and serialization of o_tol_332_d_dollo.xml."""
global EX_DOLLO
orig_fname = EX_DOLLO
try:
EX_DOLLO = DUMMY
self._rewrite_and_call(orig_fname, (
(ParseTests, ['test_read_dollo', 'test_parse_dollo']),
(TreeTests, ['test_BinaryCharacters']),
))
finally:
EX_DOLLO = orig_fname
# ---------------------------------------------------------
# Method tests
class MethodTests(unittest.TestCase):
"""Tests for methods on specific classes/objects."""
def setUp(self):
self.phyloxml = PhyloXMLIO.read(EX_PHYLO)
# Type conversions
def test_clade_to_phylogeny(self):
"""Convert a Clade object to a new Phylogeny."""
clade = self.phyloxml.phylogenies[0].clade[0]
tree = clade.to_phylogeny(rooted=True)
self.assert_(isinstance(tree, PX.Phylogeny))
def test_phylogeny_to_phyloxml(self):
"""Convert a Phylogeny object to a new Phyloxml."""
tree = self.phyloxml.phylogenies[0]
doc = tree.to_phyloxml()
self.assert_(isinstance(doc, PX.Phyloxml))
def test_sequence_conversion(self):
pseq = PX.Sequence(
type='protein',
# id_ref=None,
# id_source=None,
symbol='ADHX',
accession=PX.Accession('P81431', source='UniProtKB'),
name='Alcohol dehydrogenase class-3',
# location=None,
mol_seq=PX.MolSeq(
'TDATGKPIKCMAAIAWEAKKPLSIEEVEVAPPKSGEVRIKILHSGVCHTD'),
uri=None,
annotations=[PX.Annotation(ref='EC:1.1.1.1'),
PX.Annotation(ref='GO:0004022')],
domain_architecture=PX.DomainArchitecture(
length=50,
domains=[PX.ProteinDomain(*args) for args in (
# value, start, end, confidence
('FOO', 0, 5, 7.0e-26),
('BAR', 8, 13, 7.2e-117),
('A-OK', 21, 34, 2.4e-06),
('WD40', 40, 50, 0.3))],
))
srec = pseq.to_seqrecord()
# TODO: check seqrec-specific traits (see args)
# Seq(letters, alphabet), id, name, description, features
pseq2 = PX.Sequence.from_seqrecord(srec)
# TODO: check the round-tripped attributes again
def test_to_alignment(self):
tree = self.phyloxml.phylogenies[0]
aln = tree.to_alignment()
self.assert_(isinstance(aln, MultipleSeqAlignment))
self.assertEqual(len(aln), 0)
# Add sequences to the terminals
alphabet = Alphabet.Gapped(Alphabet.generic_dna)
for tip, seqstr in izip(tree.get_terminals(),
('AA--TTA', 'AA--TTG', 'AACCTTC')):
tip.sequences.append(PX.Sequence.from_seqrecord(
SeqRecord(Seq(seqstr, alphabet), id=str(tip))))
# Check the alignment
aln = tree.to_alignment()
self.assert_(isinstance(aln, MultipleSeqAlignment))
self.assertEqual(len(aln), 3)
self.assertEqual(aln.get_alignment_length(), 7)
# Syntax sugar
def test_clade_getitem(self):
"""Clade.__getitem__: get sub-clades by extended indexing."""
tree = self.phyloxml.phylogenies[3]
self.assertEqual(tree.clade[0,0], tree.clade.clades[0].clades[0])
self.assertEqual(tree.clade[0,1], tree.clade.clades[0].clades[1])
self.assertEqual(tree.clade[1], tree.clade.clades[1])
self.assertEqual(len(tree.clade[:]), len(tree.clade.clades))
self.assertEqual(len(tree.clade[0,:]),
len(tree.clade.clades[0].clades))
def test_phyloxml_getitem(self):
"""Phyloxml.__getitem__: get phylogenies by name or index."""
self.assert_(self.phyloxml.phylogenies[9] is self.phyloxml[9])
self.assert_(self.phyloxml['monitor lizards'] is self.phyloxml[9])
self.assertEqual(len(self.phyloxml[:]), len(self.phyloxml))
def test_events(self):
"""Events: Mapping-type behavior."""
evts = self.phyloxml.phylogenies[4].clade.events
# Container behavior: __len__, __contains__
self.assertEquals(len(evts), 1)
self.assertEqual('speciations' in evts, True)
self.assertEqual('duplications' in evts, False)
# Attribute access: __get/set/delitem__
self.assertEqual(evts['speciations'], 1)
self.assertRaises(KeyError, lambda k: evts[k], 'duplications')
evts['duplications'] = 3
self.assertEqual(evts.duplications, 3)
self.assertEqual(len(evts), 2)
del evts['speciations']
self.assertEqual(evts.speciations, None)
self.assertEquals(len(evts), 1)
# Iteration: __iter__, keys, values, items
self.assertEqual(list(iter(evts)), ['duplications'])
self.assertEqual(evts.keys(), ['duplications'])
self.assertEqual(evts.values(), [3])
self.assertEqual(evts.items(), [('duplications', 3)])
def test_singlular(self):
"""Clade, Phylogeny: Singular properties for plural attributes."""
conf = PX.Confidence(0.9, 'bootstrap')
taxo = PX.Taxonomy(rank='genus')
# Clade.taxonomy, Clade.confidence
clade = PX.Clade(confidences=[conf], taxonomies=[taxo])
self.assertEqual(clade.confidence.type, 'bootstrap')
self.assertEqual(clade.taxonomy.rank, 'genus')
# raise if len > 1
clade.confidences.append(conf)
self.assertRaises(AttributeError, getattr, clade, 'confidence')
clade.taxonomies.append(taxo)
self.assertRaises(AttributeError, getattr, clade, 'taxonomy')
# None if []
clade.confidences = []
self.assertEqual(clade.confidence, None)
clade.taxonomies = []
self.assertEqual(clade.taxonomy, None)
# Phylogeny.confidence
tree = PX.Phylogeny(True, confidences=[conf])
self.assertEqual(tree.confidence.type, 'bootstrap')
tree.confidences.append(conf)
self.assertRaises(AttributeError, getattr, tree, 'confidence')
tree.confidences = []
self.assertEqual(tree.confidence, None)
# Other methods
def test_color_hex(self):
"""BranchColor: to_hex() method."""
black = PX.BranchColor(0, 0, 0)
self.assertEqual(black.to_hex(), '#000000')
white = PX.BranchColor(255, 255, 255)
self.assertEqual(white.to_hex(), '#ffffff')
green = PX.BranchColor(14, 192, 113)
self.assertEqual(green.to_hex(), '#0ec071')
# ---------------------------------------------------------
if __name__ == '__main__':
runner = unittest.TextTestRunner(verbosity=2)
unittest.main(testRunner=runner)
# Clean up the temporary file
if os.path.exists(DUMMY):
os.remove(DUMMY)
|