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 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 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 851 852 853 854 855 856 857 858 859 860 861 862 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 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 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 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 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 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 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 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 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 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 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026
|
#! /usr/bin/env python
##############################################################################
## DendroPy Phylogenetic Computing Library.
##
## Copyright 2010-2015 Jeet Sukumaran and Mark T. Holder.
## All rights reserved.
##
## See "LICENSE.rst" for terms and conditions of usage.
##
## If you use this work or any portion thereof in published work,
## please cite it as:
##
## Sukumaran, J. and M. T. Holder. 2010. DendroPy: a Python library
## for phylogenetic computing. Bioinformatics 26: 1569-1571.
##
##############################################################################
"""
Character and character-sequence data structures.
"""
import warnings
import copy
import collections
from dendropy.utility.textprocessing import StringIO
from dendropy.utility import textprocessing
from dendropy.utility import error
from dendropy.utility import deprecate
from dendropy.utility import container
from dendropy.datamodel import charstatemodel
from dendropy.datamodel.charstatemodel import DNA_STATE_ALPHABET
from dendropy.datamodel.charstatemodel import RNA_STATE_ALPHABET
from dendropy.datamodel.charstatemodel import NUCLEOTIDE_STATE_ALPHABET
from dendropy.datamodel.charstatemodel import PROTEIN_STATE_ALPHABET
from dendropy.datamodel.charstatemodel import RESTRICTION_SITES_STATE_ALPHABET
from dendropy.datamodel.charstatemodel import INFINITE_SITES_STATE_ALPHABET
from dendropy.datamodel import basemodel
from dendropy.datamodel import taxonmodel
from dendropy import dataio
###############################################################################
## ContinuousCharElement
class ContinuousCharElement(
basemodel.DataObject,
basemodel.Annotable):
def __init__(self, value, column_def=None, label=None):
basemodel.DataObject.__init__(self,
label=label)
self.value = value
self.column_def = column_def
###############################################################################
## CharacterType
class CharacterType(
basemodel.DataObject,
basemodel.Annotable):
"""
A character format or type of a particular column: i.e., maps a particular
set of character state definitions to a column in a character matrix.
"""
def __init__(self,
label=None,
state_alphabet=None):
basemodel.DataObject.__init__(self, label=label)
self._state_alphabet = None
self.state_alphabet = state_alphabet
def _get_state_alphabet(self):
"""
The |StateAlphabet| representing the state alphabet for this
column: i.e., the collection of symbols and the state identities to
which they map.
"""
return self._state_alphabet
def _set_state_alphabet(self, value):
self._state_alphabet = value
state_alphabet = property(_get_state_alphabet, _set_state_alphabet)
def __copy__(self, memo=None):
raise TypeError("Cannot directly copy {}".format(self.__class__.__name__))
def taxon_namespace_scoped_copy(self, memo=None):
raise TypeError("Cannot directly copy {}".format(self.__class__.__name__))
def __deepcopy__(self, memo=None):
return basemodel.Annotable.__deepcopy__(self, memo=memo)
###############################################################################
## CharacterDataSequence
class CharacterDataSequence(
basemodel.Annotable,
):
"""
A sequence of character values or values for a particular taxon or entry in
a data matrix.
Objects of this class can be (almost) treated as simple lists, where the
elements are the values of characters (typically, real values in the case
of continuous data, and special instances of |StateIdentity| objects in the
case of discrete data.
Character type data (represented by |CharacterType| instances) and metadata
annotations (represented by |AnnotationSet| instances), if any, are
maintained in a parallel list that need to be accessed separately using the
index of the value to which the data correspond. So, for example, the
|AnnotationSet| object containing the metadata annotations for the first
value in a sequence, ``s[0]``, is available through
``s.annotations_at(0)``, while the character type information for that
first element is available through ``s.character_type_at(0)`` and can be
set through ``s.set_character_type_at(0, c)``.
In most cases where metadata annotations and character type information are
not needed, treating objects of this class as a simple list provides all
the functionality needed. Where metadata annotations or character type
information are required, all the standard list mutation methods (e.g.,
``CharacterDataSequence.insert``, ``CharacterDataSequence.append``,
``CharacterDataSequence.extend``) also take optional ``character_type``
and ``character_annotations`` argument in addition to the primary
``character_value`` argument, thus allowing for setting of the value,
character type, and annotation set simultaneously. While iteration over
character values are available through the standard list iteration
interface, the method ``CharacterDataSequence.cell_iter()`` provides for
iterating over ``<character-value, character-type,
character-annotation-set>`` triplets.
"""
###############################################################################
## Life-cycle
def __init__(self,
character_values=None,
character_types=None,
character_annotations=None):
"""
Parameters
----------
character_values : iterable of values
A set of values for this sequence.
"""
self._character_values = []
self._character_types = []
self._character_annotations = []
if character_values:
self.extend(
character_values=character_values,
character_types=character_types,
character_annotations=character_annotations)
###############################################################################
## Life-cycle
# def values(self):
# return list(self._character_values)
def values(self):
"""
Returns list of values of this vector.
Returns
-------
v : list
List of values making up this vector.
"""
return self._character_values
def symbols_as_list(self):
"""
Returns list of string representation of values of this vector.
Returns
-------
v : list
List of string representation of values making up this vector.
"""
return list(str(cs) for cs in self._character_values)
def symbols_as_string(self, sep=""):
"""
Returns values of this vector as a single string, with individual value
elements separated by ``sep``.
Returns
-------
s : string
String representation of values making up this vector.
"""
return sep.join(str(cs) for cs in self._character_values)
def __str__(self):
return self.symbols_as_string()
def append(self, character_value, character_type=None, character_annotations=None):
"""
Adds a value to ``self``.
Parameters
----------
character_value : object
Value to be stored.
character_type : |CharacterType|
Description of character value.
character_annotations : |AnnotationSet|
Metadata annotations associated with this character.
"""
self._character_values.append(character_value)
self._character_types.append(character_type)
self._character_annotations.append(character_annotations)
def extend(self, character_values, character_types=None, character_annotations=None):
"""
Extends ``self`` with values.
Parameters
----------
character_values : iterable of objects
Values to be stored.
character_types : iterable of |CharacterType| objects
Descriptions of character values.
character_annotations : iterable |AnnotationSet| objects
Metadata annotations associated with characters.
"""
self._character_values.extend(character_values)
if character_types is None:
self._character_types.extend( [None] * len(character_values) )
else:
assert len(character_types) == len(character_values)
self._character_types.extend(character_types)
if character_annotations is None:
self._character_annotations.extend( [None] * len(character_values) )
else:
assert len(character_annotations) == len(character_values)
self._character_annotations.extend(character_annotations)
def __len__(self):
return len(self._character_values)
def __getitem__(self, idx):
return self._character_values[idx]
def __setitem__(self, idx, value):
self._character_values[idx] = value
def __iter__(self):
return self.__next__()
def __next__(self):
for v in self._character_values:
yield v
next = __next__ # Python 2 legacy support
def cell_iter(self):
"""
Iterate over triplets of character values and associated
|CharacterType| and |AnnotationSet| instances.
"""
for v, t, a in zip(self._character_values, self._character_types, self._character_annotations):
yield v, t, a
def __delitem__(self, idx):
del self._character_values[idx]
del self._character_types[idx]
del self._character_annotations[idx]
def set_at(self, idx, character_value, character_type=None, character_annotations=None):
"""
Set value and associated character type and metadata annotations for
element at ``idx``.
Parameters
----------
idx : integer
Index of element to set.
character_value : object
Value to be stored.
character_type : |CharacterType|
Description of character value.
character_annotations : |AnnotationSet|
Metadata annotations associated with this character.
"""
to_add = (idx+1) - len(self._character_values)
while to_add > 0:
self.append(None)
to_add -= 1
self._character_values[idx] = character_value
self._character_types[idx] = character_type
self._character_annotations[idx] = character_annotations
def insert(self, idx, character_value, character_type=None, character_annotations=None):
"""
Insert value and associated character type and metadata annotations for
element at ``idx``.
Parameters
----------
idx : integer
Index of element to set.
character_value : object
Value to be stored.
character_type : |CharacterType|
Description of character value.
character_annotations : |AnnotationSet|
Metadata annotations associated with this character.
"""
self._character_values.insert(idx, character_value)
self._character_types.insert(idx, character_type)
self._character_annotations.insert(idx, character_annotations)
def value_at(self, idx):
"""
Return value of character at ``idx``.
Parameters
----------
idx : integer
Index of element value to return.
Returns
-------
c : object
Value of character at index ``idx``.
"""
return self._character_values[idx]
def character_type_at(self, idx):
"""
Return type of character at ``idx``.
Parameters
----------
idx : integer
Index of element character type to return.
Returns
-------
c : |CharacterType|
|CharacterType| associated with character index ``idx``.
"""
return self._character_types[idx]
def annotations_at(self, idx):
"""
Return metadata annotations of character at ``idx``.
Parameters
----------
idx : integer
Index of element annotations to return.
Returns
-------
c : |AnnotationSet|
|AnnotationSet| representing metadata annotations of character at index ``idx``.
"""
if self._character_annotations[idx] is None:
self._character_annotations[idx] = basemodel.AnnotationSet()
return self._character_annotations[idx]
def has_annotations_at(self, idx):
"""
Return |True| if character at ``idx`` has metadata annotations.
Parameters
----------
idx : integer
Index of element annotations to check.
Returns
-------
b : bool
|True| if character at ``idx`` has metadata annotations, |False|
otherwise.
"""
return not self._character_annotations[idx] is None
def set_character_type_at(self, idx, character_type):
"""
Set type of character at ``idx``.
Parameters
----------
idx : integer
Index of element character type to set.
"""
self._character_types[idx] = character_type
def set_annotations_at(self, idx, annotations):
"""
Set metadata annotations of character at ``idx``.
Parameters
----------
idx : integer
Index of element annotations to set.
"""
self._character_annotations[idx] = annotations
###############################################################################
## Subset of Character (Columns)
class CharacterSubset(
basemodel.DataObject,
basemodel.Annotable,
):
"""
Tracks definition of a subset of characters.
"""
def __init__(self, label=None, character_indices=None):
"""
Parameters
----------
label: str
Name of this subset.
character_indices: iterable of ``int``
Iterable of 0-based (integer) indices of column positions that
constitute this subset.
"""
basemodel.DataObject.__init__(self, label=label)
if character_indices is None:
self.character_indices = set()
else:
self.character_indices = set(character_indices)
def __len__(self):
return len(self.character_indices)
def __iter__(self):
return iter(self.character_indices)
def __deepcopy__(self, memo):
return basemodel.Annotable.__deepcopy__(self, memo=memo)
###############################################################################
## CharacterMatrix
class CharacterMatrix(
taxonmodel.TaxonNamespaceAssociated,
basemodel.Annotable,
basemodel.Deserializable,
basemodel.NonMultiReadable,
basemodel.Serializable,
basemodel.DataObject):
"""
A data structure that manages assocation of operational taxononomic unit
concepts to sequences of character state identities or values.
This is a base class that provides general functionality; derived classes
specialize for particular data types. You will not be using the class
directly, but rather one of the derived classes below, specialized for data
types such as DNA, RNA, continuous, etc.
This class and derived classes behave like a dictionary where the keys are
|Taxon| objects and the values are `CharacterDataSequence` objects. Access
to sequences based on taxon labels as well as indexes are also provided.
Numerous methods are provided to manipulate and iterate over sequences.
Character partitions can be managed through `CharacterSubset` objects,
while management of detailed metadata on character types are available
through |CharacterType| objects.
Objects can be instantiated by reading data from external sources through
the usual ``get_from_stream()``, ``get_from_path()``, or
``get_from_string()`` functions. In addition, a single matrix object can be
instantiated from multiple matrices (``concatenate()``) or data sources
(``concatenate_from_paths``).
A range of methods also exist for importing data from another matrix object.
These vary depending on how "new" and "existing" are treated. A "new"
sequence is a sequence in the other matrix associated with a |Taxon|
object for which there is no sequence defined in the current matrix. An
"existing" sequence is a sequence in the other matrix associated with a
|Taxon| object for which there *is* a sequence defined in the
current matrix.
+---------------------------------+---------------------------------------------+--------------------------------------------+
| | New Sequences: IGNORED | New Sequences: ADDED |
+=================================+=============================================+============================================+
| Existing Sequences: IGNORED | [NO-OP] | :meth:`CharacterMatrix.add_sequences()` |
+---------------------------------+---------------------------------------------+--------------------------------------------+
| Existing Sequences: OVERWRITTEN | :meth:`CharacterMatrix.replace_sequences()` | :meth:`CharacterMatrix.update_sequences()` |
+---------------------------------+---------------------------------------------+--------------------------------------------+
| Existing Sequences: EXTENDED | :meth:`CharacterMatrix.extend_sequences()` | :meth:`CharacterMatrix.extend_matrix()` |
+---------------------------------+---------------------------------------------+--------------------------------------------+
If character subsets have been defined, these subsets can be exported to independent matrices.
"""
###########################################################################
### Class Variables
data_type = None
character_sequence_type = CharacterDataSequence
###########################################################################
### Factory (Class) Methods
def _parse_and_create_from_stream(cls,
stream,
schema,
matrix_offset=0,
**kwargs):
taxon_namespace = taxonmodel.process_kwargs_dict_for_taxon_namespace(kwargs, None)
if taxon_namespace is None:
taxon_namespace = taxonmodel.TaxonNamespace()
def tns_factory(label):
if label is not None and taxon_namespace.label is None:
taxon_namespace.label = label
return taxon_namespace
label = kwargs.pop("label", None)
kwargs["data_type"] = cls.data_type
reader = dataio.get_reader(schema, **kwargs)
char_matrices = reader.read_char_matrices(
stream=stream,
taxon_namespace_factory=tns_factory,
char_matrix_factory=new_char_matrix,
state_alphabet_factory=charstatemodel.StateAlphabet,
global_annotations_target=None)
if len(char_matrices) == 0:
raise ValueError("No character data in data source")
char_matrix = char_matrices[matrix_offset]
if char_matrix.data_type != cls.data_type:
raise ValueError(
"Data source (at offset {}) is of type '{}', "
"but current CharacterMatrix is of type '{}'.".format(
matrix_offset,
char_matrix.data_type,
cls.data_type))
return char_matrix
_parse_and_create_from_stream = classmethod(_parse_and_create_from_stream)
@classmethod
def get(cls, **kwargs):
"""
Instantiate and return a *new* character matrix object from a data source.
**Mandatory Source-Specification Keyword Argument (Exactly One of the Following Required):**
- **file** (*file*) -- File or file-like object of data opened for reading.
- **path** (*str*) -- Path to file of data.
- **url** (*str*) -- URL of data.
- **data** (*str*) -- Data given directly.
**Mandatory Schema-Specification Keyword Argument:**
- **schema** (*str*) -- Identifier of format of data given by the
"``file``", "``path``", "``data``", or "``url``" argument
specified above: ":doc:`fasta </schemas/fasta>`", ":doc:`nexus
</schemas/nexus>`", or ":doc:`nexml </schemas/nexml>`",
":doc:`phylip </schemas/phylip>`", etc.
See "|Schemas|" for more details.
**Optional General Keyword Arguments:**
- **label** (*str*) -- Name or identifier to be assigned to the new
object; if not given, will be assigned the one specified in the
data source, or |None| otherwise.
- **taxon_namespace** (|TaxonNamespace|) -- The |TaxonNamespace|
instance to use to :doc:`manage the taxon names </primer/taxa>`.
If not specified, a new one will be created.
- **matrix_offset** (*int*) -- 0-based index of character block or
matrix in source to be parsed. If not specified then the
first matrix (offset = 0) is assumed.
- **ignore_unrecognized_keyword_arguments** (*bool*) -- If |True|,
then unsupported or unrecognized keyword arguments will not
result in an error. Default is |False|: unsupported keyword
arguments will result in an error.
**Optional Schema-Specific Keyword Arguments:**
These provide control over how the data is interpreted and
processed, and supported argument names and values depend on
the schema as specified by the value passed as the "``schema``"
argument. See "|Schemas|" for more details.
**Examples:**
::
dna1 = dendropy.DnaCharacterMatrix.get(
file=open("pythonidae.fasta"),
schema="fasta")
dna2 = dendropy.DnaCharacterMatrix.get(
url="http://purl.org/phylo/treebase/phylows/matrix/TB2:M2610?format=nexus",
schema="nexus")
aa1 = dendropy.ProteinCharacterMatrix.get(
file=open("pythonidae.dat"),
schema="phylip")
std1 = dendropy.StandardCharacterMatrix.get(
path="python_morph.nex",
schema="nexus")
std2 = dendropy.StandardCharacterMatrix.get(
data=">t1\\n01011\\n\\n>t2\\n11100",
schema="fasta")
"""
return cls._get_from(**kwargs)
def concatenate(cls, char_matrices):
"""
Creates and returns a single character matrix from multiple
CharacterMatrix objects specified as a list, 'char_matrices'.
All the CharacterMatrix objects in the list must be of the
same type, and share the same TaxonNamespace reference. All taxa
must be present in all alignments, all all alignments must
be of the same length. Component parts will be recorded as
character subsets.
"""
taxon_namespace = char_matrices[0].taxon_namespace
nseqs = len(char_matrices[0])
concatenated_chars = cls(taxon_namespace=taxon_namespace)
pos_start = 0
for cidx, cm in enumerate(char_matrices):
if cm.taxon_namespace is not taxon_namespace:
raise ValueError("Different ``taxon_namespace`` references in matrices to be merged")
if len(cm) != len(taxon_namespace):
raise ValueError("Number of sequences not equal to the number of taxa")
if len(cm) != nseqs:
raise ValueError("Different number of sequences across alignments: %d (expecting %d based on first matrix)" % (len(cm), nseqs))
v1 = len(cm[0])
for t, s in cm.items():
if len(s) != v1:
raise ValueError("Unequal length sequences in character matrix %d".format(cidx+1))
concatenated_chars.extend_matrix(cm)
if cm.label is None:
new_label = "locus%03d" % cidx
else:
new_label = cm.label
cs_label = new_label
i = 2
while cs_label in concatenated_chars.character_subsets:
label = "%s_%03d" % (new_label, i)
i += 1
character_indices = range(pos_start, pos_start + cm.vector_size)
pos_start += cm.vector_size
concatenated_chars.new_character_subset(character_indices=character_indices,
label=cs_label)
return concatenated_chars
concatenate = classmethod(concatenate)
def concatenate_from_streams(cls, streams, schema, **kwargs):
"""
Read a character matrix from each file object given in ``streams``,
assuming data format/schema ``schema``, and passing any keyword arguments
down to the underlying specialized reader. Merge the character matrices
and return the combined character matrix. Component parts will be
recorded as character subsets.
"""
taxon_namespace = taxonmodel.process_kwargs_dict_for_taxon_namespace(kwargs, None)
if taxon_namespace is None:
taxon_namespace = taxonmodel.TaxonNamespace()
kwargs["taxon_namespace"] = taxon_namespace
char_matrices = []
for stream in streams:
char_matrices.append(cls.get_from_stream(stream,
schema=schema, **kwargs))
return cls.concatenate(char_matrices)
concatenate_from_streams = classmethod(concatenate_from_streams)
def concatenate_from_paths(cls, paths, schema, **kwargs):
"""
Read a character matrix from each file path given in ``paths``, assuming
data format/schema ``schema``, and passing any keyword arguments down to
the underlying specialized reader. Merge the and return the combined
character matrix. Component parts will be recorded as character
subsets.
"""
streams = [open(path, "rU") for path in paths]
return cls.concatenate_from_streams(streams, schema, **kwargs)
concatenate_from_paths = classmethod(concatenate_from_paths)
def from_dict(cls,
source_dict,
char_matrix=None,
case_sensitive_taxon_labels=False,
**kwargs):
"""
Populates character matrix from dictionary (or similar mapping type),
creating |Taxon| objects and sequences as needed.
Keys must be strings representing labels |Taxon| objects or
|Taxon| objects directly. If key is specified as string, then it
will be dereferenced to the first existing |Taxon| object in the
current taxon namespace with the same label. If no such |Taxon|
object can be found, then a new |Taxon| object is created and
added to the current namespace. If a key is specified as a
|Taxon| object, then this is used directly. If it is not in the
current taxon namespace, it will be added.
Values are the sequences (more generally, iterable of values). If
values are of type `CharacterDataSequence`, then they are added
as-is. Otherwise `CharacterDataSequence` instances are
created for them. Values may be coerced into types compatible with
particular matrices. The classmethod ``coerce_values()`` will be
called for this.
Examples
--------
The following creates a |DnaCharacterMatrix| instance with three
sequences::
d = {
"s1" : "TCCAA",
"s2" : "TGCAA",
"s3" : "TG-AA",
}
dna = DnaCharacterMatrix.from_dict(d)
Three |Taxon| objects will be created, corresponding to the
labels 's1', 's2', 's3'. Each associated string sequence will be
converted to a `CharacterDataSequence`, with each symbol ("A", "C",
etc.) being replaced by the DNA state represented by the symbol.
Parameters
----------
source_dict : dict or other mapping type
Keys must be strings representing labels |Taxon| objects or
|Taxon| objects directly. Values are sequences. See above
for details.
char_matrix : |CharacterMatrix|
Instance of |CharacterMatrix| to populate with data. If not
specified, a new one will be created using keyword arguments
specified by ``kwargs``.
case_sensitive_taxon_labels : boolean
If |True|, matching of string labels specified as keys in ``d`` will
be matched to |Taxon| objects in current taxon namespace
with case being respected. If |False|, then case will be ignored.
\*\*kwargs : keyword arguments, optional
Keyword arguments to be passed to constructor of
|CharacterMatrix| when creating new instance to populate, if
no target instance is provided via ``char_matrix``.
Returns
-------
char_matrix : |CharacterMatrix|
|CharacterMatrix| populated by data from ``d``.
"""
if char_matrix is None:
char_matrix = cls(**kwargs)
for key in source_dict:
if textprocessing.is_str_type(key):
taxon = char_matrix.taxon_namespace.require_taxon(key,
is_case_sensitive=case_sensitive_taxon_labels)
else:
taxon = key
if taxon not in char_matrix.taxon_namespace:
char_matrix.taxon_namespace.add_taxon(taxon)
s = char_matrix.coerce_values(source_dict[key])
char_matrix[taxon] = s
return char_matrix
from_dict = classmethod(from_dict)
###########################################################################
### Lifecycle and Identity
def __init__(self, *args, **kwargs):
if len(args) > 1:
# only allow 1 positional argument
raise error.TooManyArgumentsError(func_name=self.__class__.__name__, max_args=1, args=args)
elif len(args) == 1 and isinstance(args[0], CharacterMatrix):
self._clone_from(args[0], kwargs)
else:
basemodel.DataObject.__init__(self, label=kwargs.pop("label", None))
taxonmodel.TaxonNamespaceAssociated.__init__(self,
taxon_namespace=taxonmodel.process_kwargs_dict_for_taxon_namespace(kwargs, None))
self._taxon_sequence_map = {}
self.character_types = []
self.comments = []
self.character_subsets = container.OrderedCaselessDict()
if len(args) == 1:
# takes care of all possible initializations, including. e.g.,
# tuples and so on
d = collections.OrderedDict(args[0])
self.__class__.from_dict(d, char_matrix=self)
if kwargs:
raise TypeError("Unrecognized or unsupported arguments: {}".format(kwargs))
def __hash__(self):
return id(self)
def __eq__(self, other):
return self is other
def _clone_from(self, src, kwargs_dict):
# super(Tree, self).__init__()
memo = {}
# memo[id(tree)] = self
taxon_namespace = taxonmodel.process_kwargs_dict_for_taxon_namespace(kwargs_dict, src.taxon_namespace)
memo[id(src.taxon_namespace)] = taxon_namespace
if taxon_namespace is not src.taxon_namespace:
for t1 in src.taxon_namespace:
t2 = taxon_namespace.require_taxon(label=t1.label)
memo[id(t1)] = t2
else:
for t1 in src.taxon_namespace:
memo[id(t1)] = t1
t = copy.deepcopy(src, memo)
self.__dict__ = t.__dict__
self.label = kwargs_dict.pop("label", src.label)
return self
def __copy__(self):
other = self.__class__(label=self.label,
taxon_namespace=self.taxon_namespace)
for taxon in self._taxon_sequence_map:
# other._taxon_sequence_map[taxon] = self.__class__.character_sequence_type(self._taxon_sequence_map[taxon])
other._taxon_sequence_map[taxon] = self._taxon_sequence_map[taxon]
memo = {}
memo[id(self)] = other
other.deep_copy_annotations_from(self, memo)
return other
def taxon_namespace_scoped_copy(self, memo=None):
if memo is None:
memo = {}
# this populates ``memo`` with references to the
# the TaxonNamespace and Taxon objects
self.taxon_namespace.populate_memo_for_taxon_namespace_scoped_copy(memo)
return self.__deepcopy__(memo=memo)
def __deepcopy__(self, memo=None):
return basemodel.Annotable.__deepcopy__(self, memo=memo)
###########################################################################
### Data I/O
# def _parse_and_add_from_stream(self, stream, schema, **kwargs):
# """
# Populates objects of this type from ``schema``-formatted
# data in the file-like object source ``stream``, *replacing*
# all current data. If multiple character matrices are in the data
# source, a 0-based index of the character matrix to use can
# be specified using the ``matrix_offset`` keyword (defaults to 0, i.e., first
# character matrix).
# """
# warnings.warn("Repopulating a CharacterMatrix is now deprecated. Instantiate a new instance from the source instead.",
# DeprecationWarning)
# m = self.__class__._parse_and_create_from_stream(stream=stream,
# schema=schema,
# **kwargs)
# return self.clone_from(m)
def _format_and_write_to_stream(self, stream, schema, **kwargs):
"""
Writes out ``self`` in ``schema`` format to a destination given by
file-like object ``stream``.
Parameters
----------
stream : file or file-like object
Destination for data.
schema : string
Must be a recognized character file schema, such as "nexus",
"phylip", etc, for which a specialized writer is available. If this
is not implemented for the schema specified, then a
UnsupportedSchemaError is raised.
\*\*kwargs : keyword arguments, optional
Keyword arguments will be passed directly to the writer for the
specified schema. See documentation for details on keyword
arguments supported by writers of various schemas.
"""
writer = dataio.get_writer(schema, **kwargs)
writer.write_char_matrices([self],
stream)
###########################################################################
### Taxon Management
def reconstruct_taxon_namespace(self,
unify_taxa_by_label=True,
taxon_mapping_memo=None):
"""
See `TaxonNamespaceAssociated.reconstruct_taxon_namespace`.
"""
if taxon_mapping_memo is None:
taxon_mapping_memo = {}
original_taxa = list(self._taxon_sequence_map.keys())
for original_taxon in original_taxa:
if unify_taxa_by_label or original_taxon not in self.taxon_namespace:
t = taxon_mapping_memo.get(original_taxon, None)
if t is None:
# taxon to use not given and
# we have not yet created a counterpart
if unify_taxa_by_label:
# this will force usage of any taxon with
# a label that matches the current taxon
t = self.taxon_namespace.require_taxon(label=original_taxon.label)
else:
# this will unconditionally create a new taxon
t = self.taxon_namespace.new_taxon(label=original_taxon.label)
taxon_mapping_memo[original_taxon] = t
else:
# taxon to use is given by mapping
self.taxon_namespace.add_taxon(t)
if t in self._taxon_sequence_map:
raise error.TaxonNamespaceReconstructionError("Multiple sequences for taxon with label '{}'".format(t.label))
self._taxon_sequence_map[t] = self._taxon_sequence_map[original_taxon]
del self._taxon_sequence_map[original_taxon]
def poll_taxa(self, taxa=None):
"""
Returns a set populated with all of |Taxon| instances associated
with ``self``.
Parameters
----------
taxa : set()
Set to populate. If not specified, a new one will be created.
Returns
-------
taxa : set[|Taxon|]
Set of taxa associated with ``self``.
"""
if taxa is None:
taxa = set()
for taxon in self._taxon_sequence_map:
taxa.add(taxon)
return taxa
def update_taxon_namespace(self):
"""
All |Taxon| objects in ``self`` that are not in
``self.taxon_namespace`` will be added.
"""
assert self.taxon_namespace is not None
for taxon in self._taxon_sequence_map:
if taxon not in self.taxon_namespace:
self.taxon_namespace.add_taxon(taxon)
def reindex_subcomponent_taxa(self):
"""
Synchronizes |Taxon| objects of map to ``taxon_namespace`` of self.
"""
raise NotImplementedError("'reindex_subcomponent_taxa()' is no longer supported; use '{}.reconstruct_taxon_namespace()' instead".format(self.__class__.__name__))
###########################################################################
### Sequence CRUD
def _resolve_key(self, key):
"""
Resolves map access key into |Taxon| instance.
If ``key`` is integer, assumed to be taxon index.
If ``key`` string, assumed to be taxon label.
Otherwise, assumed to be |Taxon| instance directly.
"""
if isinstance(key, int):
if abs(key) < len(self.taxon_namespace):
taxon = self.taxon_namespace[key]
else:
raise IndexError(key)
elif textprocessing.is_str_type(key):
taxon = self.taxon_namespace.get_taxon(label=key)
if taxon is None:
raise KeyError(key)
else:
taxon = key
return taxon
def new_sequence(self, taxon, values=None):
"""
Creates a new `CharacterDataSequence` associated with |Taxon|
``taxon``, and populates it with values in ``values``.
Parameters
----------
taxon : |Taxon|
|Taxon| instance with which this sequence is associated.
values : iterable or |None|
An initial set of values with which to populate the new character
sequence.
Returns
-------
s : `CharacterDataSequence`
A new `CharacterDataSequence` associated with |Taxon|
``taxon``.
"""
if taxon in self._taxon_sequence_map:
raise ValueError("Character values vector for taxon {} already exists".format(repr(taxon)))
if taxon not in self.taxon_namespace:
raise ValueError("Taxon {} is not in object taxon namespace".format(repr(taxon)))
cv = self.__class__.character_sequence_type(values)
self._taxon_sequence_map[taxon] = cv
return cv
def __getitem__(self, key):
"""
Retrieves sequence for ``key``, which can be a index or a label of a
|Taxon| instance in the current taxon namespace, or a
|Taxon| instance directly.
If no sequence is currently associated with specified |Taxon|, a
new one will be created. Note that the |Taxon| object must have
already been defined in the curent taxon namespace.
Parameters
----------
key : integer, string, or |Taxon|
If an integer, assumed to be an index of a |Taxon| object in
the current |TaxonNamespace| object of ``self.taxon_namespace``.
If a string, assumed to be a label of a |Taxon| object in
the current |TaxonNamespace| object of ``self.taxon_namespace``.
Otherwise, assumed to be |Taxon| instance directly. In all
cases, the |Taxon| object must be (already) defined in the
current taxon namespace.
Returns
-------
s : `CharacterDataSequence`
A sequence associated with the |Taxon| instance referenced
by ``key``.
"""
taxon = self._resolve_key(key)
try:
return self._taxon_sequence_map[taxon]
except KeyError:
return self.new_sequence(taxon)
def __setitem__(self, key, values):
"""
Assigns sequence ``values`` to taxon specified by ``key``, which can be a
index or a label of a |Taxon| instance in the current taxon
namespace, or a |Taxon| instance directly.
If no sequence is currently associated with specified |Taxon|, a
new one will be created. Note that the |Taxon| object must have
already been defined in the curent taxon namespace.
Parameters
----------
key : integer, string, or |Taxon|
If an integer, assumed to be an index of a |Taxon| object in
the current |TaxonNamespace| object of ``self.taxon_namespace``.
If a string, assumed to be a label of a |Taxon| object in
the current |TaxonNamespace| object of ``self.taxon_namespace``.
Otherwise, assumed to be |Taxon| instance directly. In all
cases, the |Taxon| object must be (already) defined in the
current taxon namespace.
"""
taxon = self._resolve_key(key)
if taxon not in self.taxon_namespace:
raise ValueError(repr(key))
if not isinstance(values, self.__class__.character_sequence_type):
values = self.__class__.character_sequence_type(values)
self._taxon_sequence_map[taxon] = values
def __contains__(self, key):
"""
Returns |True| if a sequence associated with ``key`` is in ``self``, or
|False| otherwise.
Parameters
----------
key : integer, string, or |Taxon|
If an integer, assumed to be an index of a |Taxon| object in
the current |TaxonNamespace| object of ``self.taxon_namespace``.
If a string, assumed to be a label of a |Taxon| object in
the current |TaxonNamespace| object of ``self.taxon_namespace``.
Otherwise, assumed to be |Taxon| instance directly. In all
cases, the |Taxon| object must be (already) defined in the
current taxon namespace.
Returns
-------
b : boolean
|True| if ``key`` is in ``self``; |False| otherwise.
"""
return self._taxon_sequence_map.__contains__(key)
def __delitem__(self, key):
"""
Removes sequence for ``key``, which can be a index or a label of a
|Taxon| instance in the current taxon namespace, or a
|Taxon| instance directly.
Parameters
----------
key : integer, string, or |Taxon|
If an integer, assumed to be an index of a |Taxon| object in
the current |TaxonNamespace| object of ``self.taxon_namespace``.
If a string, assumed to be a label of a |Taxon| object in
the current |TaxonNamespace| object of ``self.taxon_namespace``.
Otherwise, assumed to be |Taxon| instance directly. In all
cases, the |Taxon| object must be (already) defined in the
current taxon namespace.
"""
return self._taxon_sequence_map.__delitem__(key)
def clear(self):
"""
Removes all sequences from matrix.
"""
self._taxon_sequence_map.clear()
def sequences(self):
"""
List of all sequences in self.
Returns
-------
s : list of `CharacterDataSequence` objects in self
"""
s = [self[taxon] for taxon in self]
return s
def vectors(self):
deprecate.dendropy_deprecation_warning(
message="Deprecated since DendroPy 4: 'vectors()' will no longer be supported in future releases; use 'sequences()' instead")
return self.sequences()
###########################################################################
### Symbol/alphabet management
def coerce_values(self, values):
"""
Converts elements of ``values`` to type of matrix.
This method is called by :meth:`CharacterMatrix.from_dict` to create
sequences from iterables of values. This method should be overridden
by derived classes to ensure that ``values`` consists of types compatible
with the particular type of matrix. For example, a CharacterMatrix type
with a fixed state alphabet (such as |DnaCharacterMatrix|) would
dereference the string elements of ``values`` to return a list of
|StateIdentity| objects corresponding to the symbols represented
by the strings. If there is no value-type conversion done, then
``values`` should be returned as-is. If no value-type conversion is
possible (e.g., when the type of a value is dependent on positionaly
information), then a TypeError should be raised.
Parameters
----------
values : iterable
Iterable of values to be converted.
Returns
-------
v : list of values.
"""
return values
###########################################################################
### Sequence Access Iteration
def __iter__(self):
"Returns an iterator over character map's ordered keys."
for t in self.taxon_namespace:
if t in self._taxon_sequence_map:
yield t
def values(self):
"""
Iterates values (i.e. sequences) in this matrix.
"""
for t in self:
yield self[t]
# def iterkeys(self):
# "Dictionary interface implementation for direct access to character map."
# for t in self.taxon_namespace:
# if t in self._taxon_sequence_map:
# yield t
# def itervalues(self):
# "Dictionary interface implementation for direct access to character map."
# for t in self.taxon_namespace:
# if t in self._taxon_sequence_map:
# yield self._taxon_sequence_map[t]
def items(self):
"Returns character map key, value pairs in key-order."
for t in self.taxon_namespace:
if t in self._taxon_sequence_map:
yield t, self._taxon_sequence_map[t]
# def values(self):
# "Returns list of values."
# return [self._taxon_sequence_map[t] for t in self.taxon_namespace if t in self._taxon_seq_map]
# def pop(self, key, alt_val=None):
# "a.pop(k[, x]): a[k] if k in a, else x (and remove k)"
# return self._taxon_sequence_map.pop(key, alt_val)
# def popitem(self):
# "a.popitem() remove and last (key, value) pair"
# return self._taxon_sequence_map.popitem()
# def keys(self):
# "Returns a copy of the ordered list of character map keys."
# return list(self._taxon_sequence_map.keys())
###########################################################################
### Metrics
def __len__(self):
"""
Number of sequences in matrix.
Returns
-------
n : Number of sequences in matrix.
"""
return len(self._taxon_sequence_map)
def _get_sequence_size(self):
"""
Number of characters in *first* sequence in matrix.
Returns
-------
n : integer
Number of sequences in matrix.
"""
if len(self):
# yuck, but len(self.values())
# means we have to create and populate a list ...
return len(self[next(iter(self._taxon_sequence_map))])
else:
return 0
sequence_size = property(_get_sequence_size, None, None)
vector_size = property(_get_sequence_size, None, None) # legacy
def _get_max_sequence_size(self):
"""
Maximum number of characters across all sequences in matrix.
Returns
-------
n : integer
Maximum number of characters across all sequences in matrix.
"""
max_len = 0
for k in self:
if len(self[k]) > max_len:
max_len = len(self._taxon_sequence_map[k])
return max_len
max_sequence_size = property(_get_max_sequence_size, None, None)
###########################################################################
### Mass/Bulk Operations
def fill(self, value, size=None, append=True):
"""
Pads out all sequences in ``self`` by adding ``value`` to each sequence
until its length is ``size`` long or equal to the length of the longest
sequence if ``size`` is not specified.
Parameters
----------
value : object
A valid value (e.g., a numeric value for continuous characters, or
a |StateIdentity| for discrete character).
size : integer or None
The size (length) up to which the sequences will be padded. If |None|, then
the maximum (longest) sequence size will be used.
append : boolean
If |True| (default), then new values will be added to the end of
each sequence. If |False|, then new values will be inserted to the
front of each sequence.
"""
if size is None:
size = self.max_sequence_size
for k in self:
v = self[k]
while len(v) < size:
if append:
v.append(value)
else:
v.insert(0, value)
return size
def fill_taxa(self):
"""
Adds a new (empty) sequence for each |Taxon| instance in
current taxon namespace that does not have a sequence.
"""
for taxon in self.taxon_namespace:
if taxon not in self:
self[taxon] = CharacterDataSequence()
def pack(self, value=None, size=None, append=True):
"""
Adds missing sequences for all |Taxon| instances in current
namespace, and then pads out all sequences in ``self`` by adding ``value``
to each sequence until its length is ``size`` long or equal to the length
of the longest sequence if ``size`` is not specified. A combination of
:meth:`CharacterMatrix.fill_taxa()` and
:meth:`CharacterMatrix.fill()`.
Parameters
----------
value : object
A valid value (e.g., a numeric value for continuous characters, or
a |StateIdentity| for discrete character).
size : integer or None
The size (length) up to which the sequences will be padded. If |None|, then
the maximum (longest) sequence size will be used.
append : boolean
If |True| (default), then new values will be added to the end of
each sequence. If |False|, then new values will be inserted to the
front of each sequence.
"""
self.fill_taxa()
self.fill(value=value, size=size, append=append)
def add_sequences(self, other_matrix):
"""
Adds sequences for |Taxon| objects that are in ``other_matrix`` but not in
``self``.
Parameters
----------
other_matrix : |CharacterMatrix|
Matrix from which to add sequences.
Notes
-----
1. ``other_matrix`` must be of same type as ``self``.
2. ``other_matrix`` must have the same |TaxonNamespace| as ``self``.
3. Each sequence associated with a |Taxon| reference in ``other_matrix``
but not in ``self`` will be added to ``self`` as a shallow-copy.
4. All other sequences will be ignored.
"""
if other_matrix.taxon_namespace is not self.taxon_namespace:
raise error.TaxonNamespaceIdentityError(self, other_matrix)
for taxon in other_matrix._taxon_sequence_map:
if taxon not in self._taxon_sequence_map:
self._taxon_sequence_map[taxon] = self.__class__.character_sequence_type(other_matrix._taxon_sequence_map[taxon])
def replace_sequences(self, other_matrix):
"""
Replaces sequences for |Taxon| objects shared between ``self`` and
``other_matrix``.
Parameters
----------
other_matrix : |CharacterMatrix|
Matrix from which to replace sequences.
Notes
-----
1. ``other_matrix`` must be of same type as ``self``.
2. ``other_matrix`` must have the same |TaxonNamespace| as ``self``.
3. Each sequence in ``self`` associated with a |Taxon| that is
also represented in ``other_matrix`` will be replaced with a
shallow-copy of the corresponding sequence from ``other_matrix``.
4. All other sequences will be ignored.
"""
if other_matrix.taxon_namespace is not self.taxon_namespace:
raise error.TaxonNamespaceIdentityError(self, other_matrix)
for taxon in other_matrix._taxon_sequence_map:
if taxon in self._taxon_sequence_map:
self._taxon_sequence_map[taxon] = self.__class__.character_sequence_type(other_matrix._taxon_sequence_map[taxon])
def update_sequences(self, other_matrix):
"""
Replaces sequences for |Taxon| objects shared between ``self`` and
``other_matrix`` and adds sequences for |Taxon| objects that are
in ``other_matrix`` but not in ``self``.
Parameters
----------
other_matrix : |CharacterMatrix|
Matrix from which to update sequences.
Notes
-----
1. ``other_matrix`` must be of same type as ``self``.
2. ``other_matrix`` must have the same |TaxonNamespace| as ``self``.
3. Each sequence associated with a |Taxon| reference in ``other_matrix``
but not in ``self`` will be added to ``self``.
4. Each sequence in ``self`` associated with a |Taxon| that is
also represented in ``other_matrix`` will be replaced with a
shallow-copy of the corresponding sequence from ``other_matrix``.
"""
if other_matrix.taxon_namespace is not self.taxon_namespace:
raise error.TaxonNamespaceIdentityError(self, other_matrix)
for taxon in other_matrix._taxon_sequence_map:
self._taxon_sequence_map[taxon] = self.__class__.character_sequence_type(other_matrix._taxon_sequence_map[taxon])
def extend_sequences(self, other_matrix):
"""
Extends sequences in ``self`` with characters associated with
corresponding |Taxon| objects in ``other_matrix``.
Parameters
----------
other_matrix : |CharacterMatrix|
Matrix from which to extend sequences.
Notes
-----
1. ``other_matrix`` must be of same type as ``self``.
2. ``other_matrix`` must have the same |TaxonNamespace| as ``self``.
3. Each sequence associated with a |Taxon| reference in
``other_matrix`` that is also in ``self`` will be appended to the
sequence currently associated with that |Taxon| reference
in ``self``.
4. All other sequences will be ignored.
"""
if other_matrix.taxon_namespace is not self.taxon_namespace:
raise error.TaxonNamespaceIdentityError(self, other_matrix)
for taxon in other_matrix._taxon_sequence_map:
if taxon in self._taxon_sequence_map:
self._taxon_sequence_map[taxon].extend(other_matrix._taxon_sequence_map[taxon])
def extend_matrix(self, other_matrix):
"""
Extends sequences in ``self`` with characters associated with
corresponding |Taxon| objects in ``other_matrix`` and adds
sequences for |Taxon| objects that are in ``other_matrix`` but not
in ``self``.
Parameters
----------
other_matrix : |CharacterMatrix|
Matrix from which to extend.
Notes
-----
1. ``other_matrix`` must be of same type as ``self``.
2. ``other_matrix`` must have the same |TaxonNamespace| as ``self``.
3. Each sequence associated with a |Taxon| reference in ``other_matrix``
that is also in ``self`` will be appending
to the sequence currently associated with that |Taxon|
reference in ``self``.
4. Each sequence associated with a |Taxon| reference in
``other_matrix`` that is also in ``self`` will replace the sequence
currently associated with that |Taxon| reference in ``self``.
"""
if other_matrix.taxon_namespace is not self.taxon_namespace:
raise error.TaxonNamespaceIdentityError(self, other_matrix)
for taxon in other_matrix._taxon_sequence_map:
if taxon in self._taxon_sequence_map:
self._taxon_sequence_map[taxon].extend(other_matrix._taxon_sequence_map[taxon])
else:
self._taxon_sequence_map[taxon]= self.__class__.character_sequence_type(other_matrix._taxon_sequence_map[taxon])
def remove_sequences(self, taxa):
"""
Removes sequences associated with |Taxon| instances specified in
``taxa``. A KeyError is raised if a |Taxon| instance is
specified for which there is no associated sequences.
Parameters
----------
taxa : iterable[|Taxon|]
List or some other iterable of |Taxon| instances.
"""
for taxon in taxa:
del self._taxon_sequence_map[taxon]
def discard_sequences(self, taxa):
"""
Removes sequences associated with |Taxon| instances specified in
``taxa`` if they exist.
Parameters
----------
taxa : iterable[|Taxon|]
List or some other iterable of |Taxon| instances.
"""
for taxon in taxa:
try:
del self._taxon_sequence_map[taxon]
except KeyError:
pass
def keep_sequences(self, taxa):
"""
Discards all sequences *not* associated with any of the |Taxon| instances.
Parameters
----------
taxa : iterable[|Taxon|]
List or some other iterable of |Taxon| instances.
"""
to_keep = set(taxa)
for taxon in self._taxon_sequence_map:
if taxon not in to_keep:
del self._taxon_sequence_map[taxon]
# def extend_characters(self, other_matrix):
# """
# DEPRECATED
# Extends this matrix by adding characters from sequences of taxa
# in given matrix to sequences of taxa with correspond labels in
# this one. Taxa in the second matrix that do not exist in the
# current one are ignored.
# """
# self._taxon_sequence_map.extend_characters(other_matrix.taxon_seq_map)
# def extend_map(self,
# other_map,
# overwrite_existing=False,
# extend_existing=False):
# """
# DEPRECATED
# Extends this matrix by adding taxa and characters from the given
# map to this one. If ``overwrite_existing`` is True and a taxon
# in the other map is already present in the current one, then
# the sequence associated with the taxon in the second map
# replaces the sequence in the current one. If ``extend_existing``
# is True and a taxon in the other matrix is already present in
# the current one, then the squence map with the taxon in
# the second map will be added to the sequence in the current
# one. If both are True, then an exception is raised. If neither
# are True, and a taxon in the other map is already present in
# the current one, then the sequence is ignored.
# """
# self._taxon_sequence_map.extend(other_map,
# overwrite_existing=overwrite_existing,
# extend_existing=extend_existing)
# self.update_taxon_namespace()
# def extend(self,
# other_matrix,
# overwrite_existing=False,
# extend_existing=False):
# """
# Extends this matrix by adding taxa and characters from the given
# matrix to this one. If ``overwrite_existing`` is True and a taxon
# in the other matrix is already present in the current one, then
# the sequence associated with the taxon in the second matrix
# replaces the sequence in the current one. If ``extend_existing``
# is True and a taxon in the other matrix is already present in
# the current one, then the sequence associated with the taxon in
# the second matrix will be added to the sequence in the current
# one. If both are True, then an exception is raised. If neither
# are True, and a taxon in the other matrix is already present in
# the current one, then the sequence is ignored.
# """
# self._taxon_sequence_map.extend(other_matrix.taxon_seq_map,
# overwrite_existing=overwrite_existing,
# extend_existing=extend_existing)
# self.update_taxon_namespace()
###########################################################################
### Character Subset Management
def add_character_subset(self, char_subset):
"""
Adds a CharacterSubset object. Raises an error if one already exists
with the same label.
"""
label = char_subset.label
if label in self.character_subsets:
raise ValueError("Character subset '%s' already defined" % label)
self.character_subsets[label] = char_subset
return self.character_subsets[label]
def new_character_subset(self, label, character_indices):
"""
Defines a set of character (columns) that make up a character set.
Raises an error if one already exists with the same label. Column
indices are 0-based.
"""
cs = CharacterSubset(character_indices=character_indices, label=label)
return self.add_character_subset(cs)
###########################################################################
### CharacterType Management
def new_character_type(self, *args, **kwargs):
return CharacterType(*args, **kwargs)
###########################################################################
### Export
def export_character_subset(self, character_subset):
"""
Returns a new CharacterMatrix (of the same type) consisting only
of columns given by the CharacterSubset, ``character_subset``.
Note that this new matrix will still reference the same taxon set.
"""
if textprocessing.is_str_type(character_subset):
if character_subset not in self.character_subsets:
raise KeyError(character_subset)
else:
character_subset = self.character_subsets[character_subset]
return self.export_character_indices(character_subset.character_indices)
def export_character_indices(self, indices):
"""
Returns a new CharacterMatrix (of the same type) consisting only
of columns given by the 0-based indices in ``indices``.
Note that this new matrix will still reference the same taxon set.
"""
clone = self.__class__(self)
# clear out character subsets; otherwise all indices will have to be
# recalculated, which will require some careful and perhaps arbitrary
# handling of corner cases
clone.character_subsets = container.OrderedCaselessDict()
# clone.clone_from(self)
for vec in clone.values():
for cell_idx in range(len(vec)-1, -1, -1):
if cell_idx not in indices:
del(vec[cell_idx])
return clone
###########################################################################
### Representation
def description(self, depth=1, indent=0, itemize="", output=None):
"""
Returns description of object, up to level ``depth``.
"""
if depth is None or depth < 0:
return
output_strio = StringIO()
label = " (%s: '%s')" % (id(self), self.label)
output_strio.write('%s%s%s object at %s%s'
% (indent*' ',
itemize,
self.__class__.__name__,
hex(id(self)),
label))
if depth >= 1:
output_strio.write(': %d Sequences' % len(self))
if depth >= 2:
if self.taxon_namespace is not None:
tlead = "\n%s[Taxon Set]\n" % (" " * (indent+4))
output_strio.write(tlead)
self.taxon_namespace.description(depth=depth-1, indent=indent+8, itemize="", output=output_strio)
tlead = "\n%s[Characters]\n" % (" " * (indent+4))
output_strio.write(tlead)
indent += 8
maxlabel = max([len(str(t.label)) for t in self.taxon_namespace])
for i, t in enumerate(self.taxon_namespace):
output_strio.write('%s%s%s : %s characters\n' \
% (" " * indent,
"[%d] " % i,
str(t.label),
len(self._taxon_sequence_map[t])))
s = output_strio.getvalue()
if output is not None:
output.write(s)
return s
###########################################################################
### Legacy
def _get_taxon_seq_map(self):
warnings.warn("All methods and features of 'CharacterMatrix.taxon_seq_map' have been integrated directly into 'CharacterMatrix', or otherwise replaced entirely",
stacklevel=2)
return self
taxon_seq_map = property(_get_taxon_seq_map)
###############################################################################
## Specialized Matrices
### Continuous Characters ##################################################
class ContinuousCharacterDataSequence(CharacterDataSequence):
"""
A sequence of continuous character values for a particular taxon or entry
in a data matrix. Specializes `CharacterDataSequence` by assuming all
values are primitive numerics (i.e., either floats or integers) when
copying or representing self.
"""
def symbols_as_list(self):
"""
Returns list of string representation of values of this vector.
Returns
-------
v : list
List of string representation of values making up this vector.
"""
return [str(v) for v in self]
def symbols_as_string(self, sep=" "):
# different default
return CharacterDataSequence.symbols_as_string(self, sep=sep)
class ContinuousCharacterMatrix(CharacterMatrix):
"""
Specializes |CharacterMatrix| for continuous data.
Sequences stored using |ContinuousCharacterDataSequence|, with values of
elements assumed to be ``float`` .
"""
character_sequence_type = ContinuousCharacterDataSequence
data_type = "continuous"
def __init__(self, *args, **kwargs):
CharacterMatrix.__init__(self, *args, **kwargs)
### Discrete Characters ##################################################
class DiscreteCharacterDataSequence(CharacterDataSequence):
pass
class DiscreteCharacterMatrix(CharacterMatrix):
character_sequence_type = DiscreteCharacterDataSequence
data_type = "discrete"
def __init__(self, *args, **kwargs):
CharacterMatrix.__init__(self, *args, **kwargs)
self.state_alphabets = []
self._default_state_alphabet = None
def _get_default_state_alphabet(self):
if self._default_state_alphabet is not None:
return self._default_state_alphabet
elif len(self.state_alphabets) == 1:
return self.state_alphabets[0]
elif len(self.state_alphabets) > 1:
raise TypeError("Multiple state alphabets defined for this matrix with no default specified")
elif len(self.state_alphabets) == 0:
raise TypeError("No state alphabets defined for this matrix")
return None
def _set_default_state_alphabet(self, s):
if s not in self.state_alphabets:
self.state_alphabets.append(s)
self._default_state_alphabet = s
default_state_alphabet = property(_get_default_state_alphabet, _set_default_state_alphabet)
def append_taxon_sequence(self, taxon, state_symbols):
if taxon not in self:
self[taxon] = CharacterDataSequence()
for value in state_symbols:
if textprocessing.is_str_type(value):
symbol = value
else:
symbol = str(value)
self[taxon].append(self.default_symbol_state_map[symbol])
def remap_to_state_alphabet_by_symbol(self,
state_alphabet,
purge_other_state_alphabets=True):
"""
All entities with any reference to a state alphabet will be have the
reference reassigned to state alphabet ``sa``, and all entities with
any reference to a state alphabet element will be have the reference
reassigned to any state alphabet element in ``sa`` that has the same
symbol. Raises KeyError if no matching symbol can be found.
"""
for vi, vec in enumerate(self._taxon_sequence_map.values()):
for ci, cell in enumerate(vec):
vec[ci] = state_alphabet[cell.symbol]
for ct in self.character_types:
if ct is not None:
ct.state_alphabet = state_alphabet
if purge_other_state_alphabets:
self.default_state_alphabet = state_alphabet
def remap_to_default_state_alphabet_by_symbol(self,
purge_other_state_alphabets=True):
"""
All entities with any reference to a state alphabet will be have the
reference reassigned to the default state alphabet, and all entities
with any reference to a state alphabet element will be have the
reference reassigned to any state alphabet element in the default
state alphabet that has the same symbol. Raises ValueError if no
matching symbol can be found.
"""
self.remap_to_state_alphabet_by_symbol(
state_alphabet=self.default_state_alphabet,
purge_other_state_alphabets=purge_other_state_alphabets)
def taxon_state_sets_map(self,
char_indices=None,
gaps_as_missing=True,
gap_state=None,
no_data_state=None):
"""
Returns a dictionary that maps taxon objects to lists of sets of
fundamental state indices.
Parameters
----------
char_indices : iterable of ints
An iterable of indexes of characters to include (by column). If not
given or |None| [default], then all characters are included.
gaps_as_missing : boolean
If |True| [default] then gap characters will be treated as missing
data values. If |False|, then they will be treated as an additional
(fundamental) state.`
Returns
-------
d : dict
A dictionary with class:|Taxon| objects as keys and a list of sets
of fundamental state indexes as values.
E.g., Given the following matrix of DNA characters:
T1 AGN
T2 C-T
T3 GC?
Return with ``gaps_as_missing==True`` ::
{
<T1> : [ set([0]), set([2]), set([0,1,2,3]) ],
<T2> : [ set([1]), set([0,1,2,3]), set([3]) ],
<T3> : [ set([2]), set([1]), set([0,1,2,3]) ],
}
Return with ``gaps_as_missing==False`` ::
{
<T1> : [ set([0]), set([2]), set([0,1,2,3]) ],
<T2> : [ set([1]), set([4]), set([3]) ],
<T3> : [ set([2]), set([1]), set([0,1,2,3,4]) ],
}
Note that when gaps are treated as a fundamental state, not only
does '-' map to a distinct and unique state (4), but '?' (missing
data) maps to set consisting of all bases *and* the gap
state, whereas 'N' maps to a set of all bases but not including the
gap state.
When gaps are treated as missing, on the other hand, then '?' and
'N' and '-' all map to the same set, i.e. of all the bases.
"""
taxon_to_state_indices = {}
for t in self:
cdv = self[t]
if char_indices is None:
ci = range(len(cdv))
else:
ci = char_indices
v = []
for char_index in ci:
state = cdv[char_index]
if gaps_as_missing:
v.append(set(state.fundamental_indexes_with_gaps_as_missing))
else:
v.append(set(state.fundamental_indexes))
taxon_to_state_indices[t] = v
return taxon_to_state_indices
### Fixed Alphabet Characters ##################################################
class FixedAlphabetCharacterDataSequence(CharacterDataSequence):
pass
class FixedAlphabetCharacterMatrix(DiscreteCharacterMatrix):
character_sequence_type = FixedAlphabetCharacterDataSequence
data_type = "fixed"
datatype_alphabet = None
def __init__(self, *args, **kwargs):
DiscreteCharacterMatrix.__init__(self, *args, **kwargs)
self.state_alphabets.append(self.__class__.datatype_alphabet)
self._default_state_alphabet = self.__class__.datatype_alphabet
def coerce_values(self, values):
if self.datatype_alphabet is None:
raise ValueError("'datatype_alphabet' not set")
return charstatemodel.coerce_to_state_identities(
state_alphabet=self.datatype_alphabet,
values=values)
### DNA Characters ##################################################
class DnaCharacterDataSequence(FixedAlphabetCharacterDataSequence):
pass
class DnaCharacterMatrix(FixedAlphabetCharacterMatrix):
"""
Specializes |CharacterMatrix| for DNA data.
"""
character_sequence_type = DnaCharacterDataSequence
data_type = "dna"
datatype_alphabet = DNA_STATE_ALPHABET
### RNA Characters ##################################################
class RnaCharacterDataSequence(FixedAlphabetCharacterDataSequence):
pass
class RnaCharacterMatrix(FixedAlphabetCharacterMatrix):
"""
Specializes |CharacterMatrix| for DNA data.
"""
character_sequence_type = RnaCharacterDataSequence
data_type = "rna"
datatype_alphabet = RNA_STATE_ALPHABET
### Nucleotide Characters ##################################################
class NucleotideCharacterDataSequence(FixedAlphabetCharacterDataSequence):
pass
class NucleotideCharacterMatrix(FixedAlphabetCharacterMatrix):
"""
Specializes |CharacterMatrix| for RNA data.
"""
character_sequence_type = NucleotideCharacterDataSequence
data_type = "nucleotide"
datatype_alphabet = NUCLEOTIDE_STATE_ALPHABET
### Protein Characters ##################################################
class ProteinCharacterDataSequence(FixedAlphabetCharacterDataSequence):
pass
class ProteinCharacterMatrix(FixedAlphabetCharacterMatrix):
"""
Specializes |CharacterMatrix| for protein or amino acid data.
"""
character_sequence_type = ProteinCharacterDataSequence
data_type = "protein"
datatype_alphabet = PROTEIN_STATE_ALPHABET
### Restricted Site Characters ##################################################
class RestrictionSitesCharacterDataSequence(FixedAlphabetCharacterDataSequence):
pass
class RestrictionSitesCharacterMatrix(FixedAlphabetCharacterMatrix):
"""
Specializes |CharacterMatrix| for restriction site data.
"""
character_sequence_type = RestrictionSitesCharacterDataSequence
data_type = "restriction"
datatype_alphabet = RESTRICTION_SITES_STATE_ALPHABET
### Infinite Sites Characters ##################################################
class InfiniteSitesCharacterDataSequence(FixedAlphabetCharacterDataSequence):
pass
class InfiniteSitesCharacterMatrix(FixedAlphabetCharacterMatrix):
"""
Specializes |CharacterMatrix| for infinite sites data.
"""
character_sequence_type = InfiniteSitesCharacterDataSequence
data_type = "infinite"
datatype_alphabet = INFINITE_SITES_STATE_ALPHABET
### Standard Characters ##################################################
class StandardCharacterDataSequence(DiscreteCharacterDataSequence):
pass
class StandardCharacterMatrix(DiscreteCharacterMatrix):
"""
Specializes |CharacterMatrix| for "standard" data (i.e., generic discrete
character data).
"""
character_sequence_type = StandardCharacterDataSequence
data_type = "standard"
def __init__(self, *args, **kwargs):
"""
A default state alphabet consisting of state symbols of 0-9 will
automatically be created unless the ``default_state_alphabet=None`` is
passed in. To specify a different default state alphabet::
default_state_alphabet=dendropy.new_standard_state_alphabet("abc")
default_state_alphabet=dendropy.new_standard_state_alphabet("ij")
"""
if "default_state_alphabet" in kwargs:
default_state_alphabet = kwargs.pop("default_state_alphabet")
else:
default_state_alphabet = charstatemodel.new_standard_state_alphabet()
DiscreteCharacterMatrix.__init__(self, *args, **kwargs)
if default_state_alphabet is not None:
self.default_state_alphabet = default_state_alphabet
def coerce_values(self, values):
if self.default_state_alphabet is None:
raise ValueError("'default_state_alphabet' not set")
return charstatemodel.coerce_to_state_identities(
state_alphabet=self.default_state_alphabet,
values=values)
###############################################################################
## Main Character Matrix Factory Function
data_type_matrix_map = {
'continuous' : ContinuousCharacterMatrix,
'dna' : DnaCharacterMatrix,
'rna' : RnaCharacterMatrix,
'nucleotide' : NucleotideCharacterMatrix,
'protein' : ProteinCharacterMatrix,
'standard' : StandardCharacterMatrix,
'restriction' : RestrictionSitesCharacterMatrix,
'infinite' : InfiniteSitesCharacterMatrix,
}
def get_char_matrix_type(data_type):
if data_type is None:
raise TypeError("'data_type' must be specified")
matrix_type = data_type_matrix_map.get(data_type, None)
if matrix_type is None:
raise KeyError("Unrecognized data type specification: '{}'".format(data_type,
sorted(data_type_matrix_map.keys())))
return matrix_type
def new_char_matrix(data_type, **kwargs):
matrix_type = get_char_matrix_type(data_type=data_type)
m = matrix_type(**kwargs)
return m
|