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
|
# Copyright 2000 by Jeffrey Chang, Brad Chapman. All rights reserved.
# Copyright 2006 by PeterC. All rights reserved.
# 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.
"""Code to work with GenBank formatted files.
Classes:
Iterator Iterate through a file of GenBank entries
Dictionary Access a GenBank file using a dictionary interface.
ErrorFeatreParser Catch errors caused during parsing.
FeatureParser Parse GenBank data in Seq and SeqFeature objects.
RecordParser Parse GenBank data into a Record object.
NCBIDictionary Access GenBank using a dictionary interface.
_BaseGenBankConsumer A base class for GenBank consumer that implements
some helpful functions that are in common between
consumers.
_FeatureConsumer Create SeqFeature objects from info generated by
the Scanner
_RecordConsumer Create a GenBank record object from Scanner info.
_PrintingConsumer A debugging consumer.
_Scanner Set up a GenBank parser to parse a record.
ParserFailureError Exception indicating a failure in the parser (ie.
scanner or consumer)
LocationParserError Exception indiciating a problem with the spark based
location parser.
Functions:
index_file Get a GenBank file ready to be used as a Dictionary.
search_for Do a query against GenBank.
download_many Download many GenBank records.
"""
import cStringIO
# other Biopython stuff
from Bio.expressions import genbank
from Bio.ParserSupport import AbstractConsumer
import utils
from Bio import Mindy
from Bio.Mindy import SimpleSeqRecord
from Bio import db
from Bio import EUtils
from Bio.EUtils import DBIds, DBIdsClient
#Constants used to parse GenBank header lines
GENBANK_INDENT = 12
GENBANK_SPACER = " " * GENBANK_INDENT
#Constants for parsing GenBank feature lines
FEATURE_KEY_INDENT = 5
FEATURE_QUALIFIER_INDENT = 21
FEATURE_KEY_SPACER = " " * FEATURE_KEY_INDENT
FEATURE_QUALIFIER_SPACER = " " * FEATURE_QUALIFIER_INDENT
class Dictionary:
"""Access a GenBank file using a dictionary-like interface.
"""
def __init__(self, indexname, parser = None):
"""Initialize and open up a GenBank dictionary.
Each entry is a full GenBank record (i.e. from the LOCUS line
to the // at the end of the sequence).
Most GenBank files have only one such "entry", in which case
using this dictionary class is rather unnecessary.
Arguments:
o indexname - The name of the index for the file. This should have been
created using the index_file function.
o parser - An optional argument specifying a parser object that
the records should be run through before returning the output. If
parser is None then the unprocessed contents of the file will be
returned.
"""
self._index = Mindy.open(indexname)
self._parser = parser
def __len__(self):
return len(self.keys())
def __getitem__(self, key):
# first try to retrieve by the base id
try:
seqs = self._index.lookup(id = key)
# if we can't do that, we have to try and fetch by alias
except KeyError:
seqs = self._index.lookup(aliases = key)
if len(seqs) == 1:
seq = seqs[0]
else:
raise KeyError("Multiple sequences found for %s" % key)
if self._parser:
handle = cStringIO.StringIO(seq.text)
return self._parser.parse(handle)
else:
return seq.text
def keys(self):
primary_key_retriever = self._index['id']
return primary_key_retriever.keys()
class Iterator:
"""Iterator interface to move over a file of GenBank entries one at a time.
"""
def __init__(self, handle, parser = None):
"""Initialize the iterator.
Arguments:
o handle - A handle with GenBank entries to iterate through.
o parser - An optional parser to pass the entries through before
returning them. If None, then the raw entry will be returned.
"""
from Martel import RecordReader
from Bio import File
if isinstance(handle, File.UndoHandle):
_handle = handle
else:
_handle = File.UndoHandle(handle)
# skip ahead until we find first record
while _handle.peekline() and _handle.peekline().find("LOCUS") < 0:
_handle.readline()
self._reader = RecordReader.StartsWith(_handle, "LOCUS")
self._parser = parser
def next(self):
"""Return the next GenBank record from the handle.
Will return None if we ran out of records.
"""
from Bio import File
data = self._reader.next()
if self._parser is not None:
if data:
return self._parser.parse(File.StringHandle(data))
return data
def __iter__(self):
return iter(self.next, None)
class ParserFailureError(Exception):
"""Failure caused by some kind of problem in the parser.
"""
pass
class LocationParserError(Exception):
"""Could not Properly parse out a location from a GenBank file.
"""
pass
class FeatureParser:
"""Parse GenBank files into Seq + Feature objects.
"""
def __init__(self, debug_level = 0, use_fuzziness = 1,
feature_cleaner = utils.FeatureValueCleaner()):
"""Initialize a GenBank parser and Feature consumer.
Arguments:
o debug_level - An optional argument that species the amount of
debugging information the parser should spit out. By default we have
no debugging info (the fastest way to do things), but if you want
you can set this as high as two and see exactly where a parse fails.
o use_fuzziness - Specify whether or not to use fuzzy representations.
The default is 1 (use fuzziness).
o feature_cleaner - A class which will be used to clean out the
values of features. This class must implement the function
clean_value. GenBank.utils has a "standard" cleaner class, which
is used by default.
"""
self._scanner = _Scanner(debug_level)
self.use_fuzziness = use_fuzziness
self._cleaner = feature_cleaner
def parse(self, handle):
"""Parse the specified handle.
"""
self._consumer = _FeatureConsumer(self.use_fuzziness,
self._cleaner)
self._scanner.feed(handle, self._consumer)
return self._consumer.data
class RecordParser:
"""Parse GenBank files into Record objects
"""
def __init__(self, debug_level = 0):
"""Initialize the parser.
Arguments:
o debug_level - An optional argument that species the amount of
debugging information the parser should spit out. By default we have
no debugging info (the fastest way to do things), but if you want
you can set this as high as two and see exactly where a parse fails.
"""
self._scanner = _Scanner(debug_level)
def parse(self, handle):
"""Parse the specified handle into a GenBank record.
"""
self._consumer = _RecordConsumer()
self._scanner.feed(handle, self._consumer)
return self._consumer.data
class _BaseGenBankConsumer(AbstractConsumer):
"""Abstract GenBank consumer providing useful general functions.
This just helps to eliminate some duplication in things that most
GenBank consumers want to do.
"""
# Special keys in GenBank records that we should remove spaces from
# For instance, \translation keys have values which are proteins and
# should have spaces and newlines removed from them. This class
# attribute gives us more control over specific formatting problems.
remove_space_keys = ["translation"]
def __init__(self):
pass
def _split_keywords(self, keyword_string):
"""Split a string of keywords into a nice clean list.
"""
# process the keywords into a python list
if keyword_string[-1] == '.':
keywords = keyword_string[:-1]
else:
keywords = keyword_string
keyword_list = keywords.split(';')
clean_keyword_list = [x.strip() for x in keyword_list]
return clean_keyword_list
def _split_accessions(self, accession_string):
"""Split a string of accession numbers into a list.
"""
# first replace all line feeds with spaces
accession = accession_string.replace("\n", " ")
accession_list = accession.split(' ')
clean_accession_list = [x.strip() for x in accession_list]
return clean_accession_list
def _split_taxonomy(self, taxonomy_string):
"""Split a string with taxonomy info into a list.
"""
if taxonomy_string[-1] == '.':
tax_info = taxonomy_string[:-1]
else:
tax_info = taxonomy_string
tax_list = tax_info.split(';')
new_tax_list = []
for tax_item in tax_list:
new_items = tax_item.split("\n")
new_tax_list.extend(new_items)
while '' in new_tax_list:
new_tax_list.remove('')
clean_tax_list = [x.strip() for x in new_tax_list]
return clean_tax_list
def _clean_location(self, location_string):
"""Clean whitespace out of a location string.
The location parser isn't a fan of whitespace, so we clean it out
before feeding it into the parser.
"""
import string
location_line = location_string
for ws in string.whitespace:
location_line = location_line.replace(ws, '')
return location_line
def _remove_newlines(self, text):
"""Remove any newlines in the passed text, returning the new string.
"""
# get rid of newlines in the qualifier value
newlines = ["\n", "\r"]
for ws in newlines:
text = text.replace(ws, "")
return text
def _normalize_spaces(self, text):
"""Replace multiple spaces in the passed text with single spaces.
"""
# get rid of excessive spaces
text_parts = text.split(" ")
text_parts = filter(None, text_parts)
return ' '.join(text_parts)
def _remove_spaces(self, text):
"""Remove all spaces from the passed text.
"""
return text.replace(" ", "")
def _convert_to_python_numbers(self, start, end):
"""Convert a start and end range to python notation.
In GenBank, starts and ends are defined in "biological" coordinates,
where 1 is the first base and [i, j] means to include both i and j.
In python, 0 is the first base and [i, j] means to include i, but
not j.
So, to convert "biological" to python coordinates, we need to
subtract 1 from the start, and leave the end and things should
be converted happily.
"""
new_start = start - 1
new_end = end
return new_start, new_end
class _FeatureConsumer(_BaseGenBankConsumer):
"""Create a SeqRecord object with Features to return.
Attributes:
o use_fuzziness - specify whether or not to parse with fuzziness in
feature locations.
o feature_cleaner - a class that will be used to provide specialized
cleaning-up of feature values.
"""
def __init__(self, use_fuzziness, feature_cleaner = None):
from Bio.SeqRecord import SeqRecord
_BaseGenBankConsumer.__init__(self)
self.data = SeqRecord(None, id = None)
self._use_fuzziness = use_fuzziness
self._feature_cleaner = feature_cleaner
self._seq_type = ''
self._seq_data = []
self._current_ref = None
self._cur_feature = None
self._cur_qualifier_key = None
self._cur_qualifier_value = None
def locus(self, locus_name):
"""Set the locus name is set as the name of the Sequence.
"""
self.data.name = locus_name
def size(self, content):
pass
def residue_type(self, type):
"""Record the sequence type so we can choose an appropriate alphabet.
"""
self._seq_type = type
def data_file_division(self, division):
self.data.annotations['data_file_division'] = division
def date(self, submit_date):
self.data.annotations['date'] = submit_date
def definition(self, definition):
"""Set the definition as the description of the sequence.
"""
self.data.description = definition
def accession(self, acc_num):
"""Set the accession number as the id of the sequence.
If we have multiple accession numbers, the first one passed is
used.
"""
new_acc_nums = self._split_accessions(acc_num)
# if we haven't set the id information yet, add the first acc num
if self.data.id is None:
if len(new_acc_nums) > 0:
self.data.id = new_acc_nums[0]
def nid(self, content):
self.data.annotations['nid'] = content
def pid(self, content):
self.data.annotations['pid'] = content
def version(self, version_id):
"""Set the version to overwrite the id.
Since the verison provides the same information as the accession
number, plus some extra info, we set this as the id if we have
a version.
"""
self.data.id = version_id
def db_source(self, content):
self.data.annotations['db_source'] = content.rstrip()
def gi(self, content):
self.data.annotations['gi'] = content
def keywords(self, content):
self.data.annotations['keywords'] = self._split_keywords(content)
def segment(self, content):
self.data.annotations['segment'] = content
def source(self, content):
if content[-1] == '.':
source_info = content[:-1]
else:
source_info = content
self.data.annotations['source'] = source_info
def organism(self, content):
self.data.annotations['organism'] = content
def taxonomy(self, content):
self.data.annotations['taxonomy'] = self._split_taxonomy(content)
def reference_num(self, content):
"""Signal the beginning of a new reference object.
"""
from Bio.SeqFeature import Reference
# if we have a current reference that hasn't been added to
# the list of references, add it.
if self._current_ref is not None:
self.data.annotations['references'].append(self._current_ref)
else:
self.data.annotations['references'] = []
self._current_ref = Reference()
def reference_bases(self, content):
"""Attempt to determine the sequence region the reference entails.
Possible types of information we may have to deal with:
(bases 1 to 86436)
(sites)
(bases 1 to 105654; 110423 to 111122)
1 (residues 1 to 182)
"""
# first remove the parentheses or other junk
ref_base_info = content[1:-1]
all_locations = []
# parse if we've got 'bases' and 'to'
if ref_base_info.find('bases') != -1 and \
ref_base_info.find('to') != -1:
# get rid of the beginning 'bases'
ref_base_info = ref_base_info[5:]
locations = self._split_reference_locations(ref_base_info)
all_locations.extend(locations)
elif (ref_base_info.find("residues") >= 0 and
ref_base_info.find("to") >= 0):
residues_start = ref_base_info.find("residues")
# get only the information after "residues"
ref_base_info = ref_base_info[(residues_start + len("residues ")):]
locations = self._split_reference_locations(ref_base_info)
all_locations.extend(locations)
# make sure if we are not finding information then we have
# the string 'sites' or the string 'bases'
elif (ref_base_info == 'sites' or
ref_base_info.strip() == 'bases'):
pass
# otherwise raise an error
else:
raise ValueError("Could not parse base info %s in record %s" %
(ref_base_info, self.data.id))
self._current_ref.location = all_locations
def _split_reference_locations(self, location_string):
"""Get reference locations out of a string of reference information
The passed string should be of the form:
1 to 20; 20 to 100
This splits the information out and returns a list of location objects
based on the reference locations.
"""
from Bio import SeqFeature
# split possibly multiple locations using the ';'
all_base_info = location_string.split(';')
new_locations = []
for base_info in all_base_info:
start, end = base_info.split('to')
new_start, new_end = \
self._convert_to_python_numbers(int(start.strip()),
int(end.strip()))
this_location = SeqFeature.FeatureLocation(new_start, new_end)
new_locations.append(this_location)
return new_locations
def authors(self, content):
self._current_ref.authors = content
def consrtm(self, content):
self._current_ref.consrtm = content
def title(self, content):
self._current_ref.title = content
def journal(self, content):
self._current_ref.journal = content
def medline_id(self, content):
self._current_ref.medline_id = content
def pubmed_id(self, content):
self._current_ref.pubmed_id = content
def remark(self, content):
self._current_ref.comment = content
def comment(self, content):
self.data.annotations['comment'] = "\n".join(content)
def features_line(self, content):
"""Get ready for the feature table when we reach the FEATURE line.
"""
self.start_feature_table()
def start_feature_table(self):
"""Indicate we've got to the start of the feature table.
"""
# make sure we've added on our last reference object
if self._current_ref is not None:
self.data.annotations['references'].append(self._current_ref)
self._current_ref = None
def _add_feature(self):
"""Utility function to add a feature to the SeqRecord.
This does all of the appropriate checking to make sure we haven't
left any info behind, and that we are only adding info if it
exists.
"""
if self._cur_feature:
# if we have a left over qualifier, add it to the qualifiers
# on the current feature
self._add_qualifier()
self._cur_qualifier_key = ''
self._cur_qualifier_value = ''
self.data.features.append(self._cur_feature)
def feature_key(self, content):
from Bio import SeqFeature
# if we already have a feature, add it on
self._add_feature()
# start a new feature
self._cur_feature = SeqFeature.SeqFeature()
self._cur_feature.type = content
# assume positive strand to start with if we have DNA or cDNA
# (labelled as mRNA). The complement in the location will
# change this later if something is on the reverse strand
if self._seq_type.find("DNA") >= 0 or self._seq_type.find("mRNA") >= 0:
self._cur_feature.strand = 1
def location(self, content):
"""Parse out location information from the location string.
This uses Andrew's nice spark based parser to do the parsing
for us, and translates the results of the parse into appropriate
Location objects.
"""
from Bio.GenBank import LocationParser
# --- first preprocess the location for the spark parser
# we need to clean up newlines and other whitespace inside
# the location before feeding it to the parser.
# locations should have no whitespace whatsoever based on the
# grammer
location_line = self._clean_location(content)
# Older records have junk like replace(266,"c") in the
# location line. Newer records just replace this with
# the number 266 and have the information in a more reasonable
# place. So we'll just grab out the number and feed this to the
# parser. We shouldn't really be losing any info this way.
if location_line.find('replace') != -1:
comma_pos = location_line.find(',')
location_line = location_line[8:comma_pos]
# feed everything into the scanner and parser
try:
parse_info = \
LocationParser.parse(LocationParser.scan(location_line))
# spark raises SystemExit errors when parsing fails
except SystemExit:
raise LocationParserError(location_line)
# print "parse_info:", repr(parse_info)
# add the parser information the current feature
self._set_location_info(parse_info, self._cur_feature)
def _set_function(self, function, cur_feature):
"""Set the location information based on a function.
This handles all of the location functions like 'join', 'complement'
and 'order'.
Arguments:
o function - A LocationParser.Function object specifying the
function we are acting on.
o cur_feature - The feature to add information to.
"""
from Bio import SeqFeature
from Bio.GenBank import LocationParser
assert isinstance(function, LocationParser.Function), \
"Expected a Function object, got %s" % function
if function.name == "complement":
# mark the current feature as being on the opposite strand
cur_feature.strand = -1
# recursively deal with whatever is left inside the complement
for inner_info in function.args:
self._set_location_info(inner_info, cur_feature)
# deal with functions that have multipe internal segments that
# are connected somehow.
# join and order are current documented functions.
# one-of is something I ran across in old files. Treating it
# as a sub sequence feature seems appropriate to me.
# bond is some piece of junk I found in RefSeq files. I have
# no idea how to interpret it, so I jam it in here
elif (function.name == "join" or function.name == "order" or
function.name == "one-of" or function.name == "bond"):
self._set_ordering_info(function, cur_feature)
elif (function.name == "gap"):
assert len(function.args) == 1, \
"Unexpected number of arguments in gap %s" % function.args
# make the cur information location a gap object
position = self._get_position(function.args[0].local_location)
cur_feature.location = SeqFeature.PositionGap(position)
else:
raise ValueError("Unexpected function name: %s" % function.name)
def _set_ordering_info(self, function, cur_feature):
"""Parse a join or order and all of the information in it.
This deals with functions that order a bunch of locations,
specifically 'join' and 'order'. The inner locations are
added as subfeatures of the top level feature
"""
from Bio import SeqFeature
# for each inner element, create a sub SeqFeature within the
# current feature, then get the information for this feature
for inner_element in function.args:
new_sub_feature = SeqFeature.SeqFeature()
# inherit the type from the parent
new_sub_feature.type = cur_feature.type
# add the join or order info to the location_operator
cur_feature.location_operator = function.name
new_sub_feature.location_operator = function.name
# inherit references and strand from the parent feature
new_sub_feature.ref = cur_feature.ref
new_sub_feature.ref_db = cur_feature.ref_db
new_sub_feature.strand = cur_feature.strand
# set the information for the inner element
self._set_location_info(inner_element, new_sub_feature)
# now add the feature to the sub_features
cur_feature.sub_features.append(new_sub_feature)
# set the location of the top -- this should be a combination of
# the start position of the first sub_feature and the end position
# of the last sub_feature
# these positions are already converted to python coordinates
# (when the sub_features were added) so they don't need to
# be converted again
feature_start = cur_feature.sub_features[0].location.start
feature_end = cur_feature.sub_features[-1].location.end
cur_feature.location = SeqFeature.FeatureLocation(feature_start,
feature_end)
def _set_location_info(self, parse_info, cur_feature):
"""Set the location information for a feature from the parse info.
Arguments:
o parse_info - The classes generated by the LocationParser.
o cur_feature - The feature to add the information to.
"""
from Bio.GenBank import LocationParser
# base case -- we are out of information
if parse_info is None:
return
# parse a location -- this is another base_case -- we assume
# we have no information after a single location
elif isinstance(parse_info, LocationParser.AbsoluteLocation):
self._set_location(parse_info, cur_feature)
return
# parse any of the functions (join, complement, etc)
elif isinstance(parse_info, LocationParser.Function):
self._set_function(parse_info, cur_feature)
# otherwise we are stuck and should raise an error
else:
raise ValueError("Could not parse location info: %s"
% parse_info)
def _set_location(self, location, cur_feature):
"""Set the location information for a feature.
Arguments:
o location - An AbsoluteLocation object specifying the info
about the location.
o cur_feature - The feature to add the information to.
"""
# check to see if we have a cross reference to another accession
# ie. U05344.1:514..741
if location.path is not None:
cur_feature.ref = location.path.accession
cur_feature.ref_db = location.path.database
# now get the actual location information
cur_feature.location = self._get_location(location.local_location)
def _get_location(self, range_info):
"""Return a (possibly fuzzy) location from a Range object.
Arguments:
o range_info - A location range (ie. something like 67..100). This
may also be a single position (ie 27).
This returns a FeatureLocation object.
If parser.use_fuzziness is set at one, the positions for the
end points will possibly be fuzzy.
"""
from Bio import SeqFeature
from Bio.GenBank import LocationParser
# check if we just have a single base
if not(isinstance(range_info, LocationParser.Range)):
pos = self._get_position(range_info)
# move the single position back one to be consistent with how
# python indexes numbers (starting at 0)
pos.position = pos.position - 1
return SeqFeature.FeatureLocation(pos, pos)
# otherwise we need to get both sides of the range
else:
# get *Position objects for the start and end
start_pos = self._get_position(range_info.low)
end_pos = self._get_position(range_info.high)
start_pos.position, end_pos.position = \
self._convert_to_python_numbers(start_pos.position,
end_pos.position)
return SeqFeature.FeatureLocation(start_pos, end_pos)
def _get_position(self, position):
"""Return a (possibly fuzzy) position for a single coordinate.
Arguments:
o position - This is a LocationParser.* object that specifies
a single coordinate. We will examine the object to determine
the fuzziness of the position.
This is used with _get_location to parse out a location of any
end_point of arbitrary fuzziness.
"""
from Bio import SeqFeature
from Bio.GenBank import LocationParser
# case 1 -- just a normal number
if (isinstance(position, LocationParser.Integer)):
final_pos = SeqFeature.ExactPosition(position.val)
# case 2 -- we've got a > sign
elif isinstance(position, LocationParser.LowBound):
final_pos = SeqFeature.AfterPosition(position.base.val)
# case 3 -- we've got a < sign
elif isinstance(position, LocationParser.HighBound):
final_pos = SeqFeature.BeforePosition(position.base.val)
# case 4 -- we've got 100^101
elif isinstance(position, LocationParser.Between):
final_pos = SeqFeature.BetweenPosition(position.low.val,
position.high.val)
# case 5 -- we've got (100.101)
elif isinstance(position, LocationParser.TwoBound):
final_pos = SeqFeature.WithinPosition(position.low.val,
position.high.val)
# case 6 -- we've got a one-of(100, 110) location
elif isinstance(position, LocationParser.Function) and \
position.name == "one-of":
# first convert all of the arguments to positions
position_choices = []
for arg in position.args:
# we only handle AbsoluteLocations with no path
# right now. Not sure if other cases will pop up
assert isinstance(arg, LocationParser.AbsoluteLocation), \
"Unhandled Location type %r" % arg
assert arg.path is None, "Unhandled path in location"
position = self._get_position(arg.local_location)
position_choices.append(position)
final_pos = SeqFeature.OneOfPosition(position_choices)
# if it is none of these cases we've got a problem!
else:
raise ValueError("Unexpected LocationParser object %r" %
position)
# if we are using fuzziness return what we've got
if self._use_fuzziness:
return final_pos
# otherwise return an ExactPosition equivalent
else:
return SeqFeature.ExactPosition(final_pos.location)
def _add_qualifier(self):
"""Add a qualifier to the current feature without loss of info.
If there are multiple qualifier keys with the same name we
would lose some info in the dictionary, so we append a unique
number to the end of the name in case of conflicts.
"""
# if we've got a key from before, add it to the dictionary of
# qualifiers
if self._cur_qualifier_key:
key = self._cur_qualifier_key
value = "".join(self._cur_qualifier_value)
if self._feature_cleaner is not None:
value = self._feature_cleaner.clean_value(key, value)
# if the qualifier name exists, append the value
if key in self._cur_feature.qualifiers:
self._cur_feature.qualifiers[key].append(value)
# otherwise start a new list of the key with its values
else:
self._cur_feature.qualifiers[key] = [value]
def feature_qualifier_name(self, content_list):
"""When we get a qualifier key, use it as a dictionary key.
We receive a list of keys, since you can have valueless keys such as
/pseudo which would be passed in with the next key (since no other
tags separate them in the file)
"""
for content in content_list:
# add a qualifier if we've got one
self._add_qualifier()
# remove the / and = from the qualifier if they're present
qual_key = content.replace('/', '')
qual_key = qual_key.replace('=', '')
qual_key = qual_key.strip()
self._cur_qualifier_key = qual_key
self._cur_qualifier_value = []
def feature_qualifier_description(self, content):
# get rid of the quotes surrounding the qualifier if we've got 'em
qual_value = content.replace('"', '')
self._cur_qualifier_value.append(qual_value)
def contig_location(self, content):
"""Deal with a location of CONTIG information.
"""
from Bio import SeqFeature
# add a last feature if is hasn't been added,
# so that we don't overwrite it
self._add_feature()
# make a feature to add the information to
self._cur_feature = SeqFeature.SeqFeature()
self._cur_feature.type = "contig"
# now set the location on the feature using the standard
# location handler
self.location(content)
# add the contig information to the annotations and get rid
# of the feature to prevent it from being added to the feature table
self.data.annotations["contig"] = self._cur_feature
self._cur_feature = None
def origin_name(self, content):
pass
def base_count(self, content):
pass
def base_number(self, content):
pass
def sequence(self, content):
"""Add up sequence information as we get it.
To try and make things speedier, this puts all of the strings
into a list of strings, and then uses string.join later to put
them together. Supposedly, this is a big time savings
"""
new_seq = content.replace(' ', '')
new_seq = new_seq.upper()
self._seq_data.append(new_seq)
def record_end(self, content):
"""Clean up when we've finished the record.
"""
from Bio import Alphabet
from Bio.Alphabet import IUPAC
from Bio.Seq import Seq
# add the last feature in the table which hasn't been added yet
self._add_feature()
# add the sequence information
# first, determine the alphabet
# we default to an generic alphabet if we don't have a
# seq type or have strange sequence information.
seq_alphabet = Alphabet.generic_alphabet
if self._seq_type:
# mRNA is really also DNA, since it is actually cDNA
if self._seq_type.find('DNA') != -1 or \
self._seq_type.find('mRNA') != -1:
seq_alphabet = IUPAC.ambiguous_dna
# are there every really RNA sequences in GenBank?
elif self._seq_type.find('RNA') != -1:
seq_alphabet = IUPAC.ambiguous_rna
elif self._seq_type == "PROTEIN":
seq_alphabet = IUPAC.protein # or extended protein?
# work around ugly GenBank records which have circular or
# linear but no indication of sequence type
elif self._seq_type in ["circular", "linear"]:
pass
# we have a bug if we get here
else:
raise ValueError("Could not determine alphabet for seq_type %s"
% self._seq_type)
# now set the sequence
sequence = "".join(self._seq_data)
self.data.seq = Seq(sequence, seq_alphabet)
class _RecordConsumer(_BaseGenBankConsumer):
"""Create a GenBank Record object from scanner generated information.
"""
def __init__(self):
_BaseGenBankConsumer.__init__(self)
import Record
self.data = Record.Record()
self._seq_data = []
self._cur_reference = None
self._cur_feature = None
self._cur_qualifier = None
def locus(self, content):
self.data.locus = content
def size(self, content):
self.data.size = content
def residue_type(self, content):
self.data.residue_type = content
def data_file_division(self, content):
self.data.data_file_division = content
def date(self, content):
self.data.date = content
def definition(self, content):
self.data.definition = content
def accession(self, content):
new_accessions = self._split_accessions(content)
self.data.accession.extend(new_accessions)
def nid(self, content):
self.data.nid = content
def pid(self, content):
self.data.pid = content
def version(self, content):
self.data.version = content
def db_source(self, content):
self.data.db_source = content.rstrip()
def gi(self, content):
self.data.gi = content
def keywords(self, content):
self.data.keywords = self._split_keywords(content)
def segment(self, content):
self.data.segment = content
def source(self, content):
self.data.source = content
def organism(self, content):
self.data.organism = content
def taxonomy(self, content):
self.data.taxonomy = self._split_taxonomy(content)
def reference_num(self, content):
"""Grab the reference number and signal the start of a new reference.
"""
# check if we have a reference to add
if self._cur_reference is not None:
self.data.references.append(self._cur_reference)
self._cur_reference = Record.Reference()
self._cur_reference.number = content
def reference_bases(self, content):
self._cur_reference.bases = content
def authors(self, content):
self._cur_reference.authors = content
def consrtm(self, content):
self._cur_reference.consrtm = content
def title(self, content):
self._cur_reference.title = content
def journal(self, content):
self._cur_reference.journal = content
def medline_id(self, content):
self._cur_reference.medline_id = content
def pubmed_id(self, content):
self._cur_reference.pubmed_id = content
def remark(self, content):
self._cur_reference.remark = content
def comment(self, content):
self.data.comment = "\n".join(content)
def primary_ref_line(self,content):
"""Data for the PRIMARY line"""
self.data.primary.append(content)
def primary(self,content):
pass
def features_line(self, content):
"""Get ready for the feature table when we reach the FEATURE line.
"""
self.start_feature_table()
def start_feature_table(self):
"""Signal the start of the feature table.
"""
# we need to add on the last reference
if self._cur_reference is not None:
self.data.references.append(self._cur_reference)
def feature_key(self, content):
"""Grab the key of the feature and signal the start of a new feature.
"""
# first add on feature information if we've got any
self._add_feature()
self._cur_feature = Record.Feature()
self._cur_feature.key = content
def _add_feature(self):
"""Utility function to add a feature to the Record.
This does all of the appropriate checking to make sure we haven't
left any info behind, and that we are only adding info if it
exists.
"""
if self._cur_feature is not None:
# if we have a left over qualifier, add it to the qualifiers
# on the current feature
if self._cur_qualifier is not None:
self._cur_feature.qualifiers.append(self._cur_qualifier)
self._cur_qualifier = None
self.data.features.append(self._cur_feature)
def location(self, content):
self._cur_feature.location = self._clean_location(content)
def feature_qualifier_name(self, content_list):
"""Deal with qualifier names
We receive a list of keys, since you can have valueless keys such as
/pseudo which would be passed in with the next key (since no other
tags separate them in the file)
"""
for content in content_list:
# the record parser keeps the /s -- add them if we don't have 'em
if content.find("/") != 0:
content = "/%s" % content
# add on a qualifier if we've got one
if self._cur_qualifier is not None:
self._cur_feature.qualifiers.append(self._cur_qualifier)
self._cur_qualifier = Record.Qualifier()
self._cur_qualifier.key = content
def feature_qualifier_description(self, content):
# if we have info then the qualifier key should have a ='s
if self._cur_qualifier.key.find("=") == -1:
self._cur_qualifier.key = "%s=" % self._cur_qualifier.key
cur_content = self._remove_newlines(content)
# remove all spaces from the value if it is a type where spaces
# are not important
for remove_space_key in self.__class__.remove_space_keys:
if self._cur_qualifier.key.find(remove_space_key) >= 0:
cur_content = self._remove_spaces(cur_content)
self._cur_qualifier.value = self._normalize_spaces(cur_content)
def base_count(self, content):
self.data.base_counts = content
def origin_name(self, content):
self.data.origin = content
def contig_location(self, content):
"""Signal that we have contig information to add to the record.
"""
self.data.contig = self._clean_location(content)
def sequence(self, content):
"""Add sequence information to a list of sequence strings.
This removes spaces in the data and uppercases the sequence, and
then adds it to a list of sequences. Later on we'll join this
list together to make the final sequence. This is faster than
adding on the new string every time.
"""
new_seq = content.replace(' ', '')
self._seq_data.append(new_seq.upper())
def record_end(self, content):
"""Signal the end of the record and do any necessary clean-up.
"""
# add together all of the sequence parts to create the
# final sequence string
self.data.sequence = "".join(self._seq_data)
# add on the last feature
self._add_feature()
def _strip_and_combine(line_list):
"""Combine multiple lines of content separated by spaces.
This function is used by the EventGenerator callback function to
combine multiple lines of information. The lines are first
stripped to remove whitepsace, and then combined so they are separated
by a space. This is a simple minded way to combine lines, but should
work for most cases.
"""
# first strip out extra whitespace
stripped_line_list = [x.strip() for x in line_list]
# now combine everything with spaces
return ' '.join(stripped_line_list)
class _Scanner:
"""Does the parsing of a GenBank file. Earlier versions of this
class used Martel to do this, but there where significant speed
and memory limitations to this.
"""
def __init__(self, debug = 0):
"""Initialize the scanner.
Arguments:
o debug - The level of debugging that the parser should
display. Level 0 is no debugging, Level 2 displays the most
debugging info (but is slower).
"""
#Following dictionary maps GenBank lines to the associated
#consumer methods - the special cases like LOCUS where one
#genbank line triggers several consumer calls have to be
#handled individually.
self._consumer_dict = {
'DEFINITION' : 'definition',
'ACCESSION' : 'accession',
'NID' : 'nid',
'PID' : 'pid',
'DBSOURCE' : 'db_source',
'KEYWORDS' : 'keywords',
'SEGMENT' : 'segment',
'SOURCE' : 'source',
'AUTHORS' : 'authors',
'CONSRTM' : 'consrtm',
'TITLE' : 'title',
'JOURNAL' : 'journal',
'MEDLINE' : 'medline_id',
'PUBMED' : 'pubmed_id',
'REMARK' : 'remark'}
#We have to handle the following specially:
#ORIGIN (locus, size, residue_type, data_file_division and date)
#COMMENT (comment)
#VERSION (version and gi)
#REFERENCE (eference_num and reference_bases)
#ORGANISM (organism and taxonomy)
#Save the requested debug level
self._debug = debug
def _feed_locus(self, line, consumer):
"""Sub function for the '_feed_header' (and thus 'feed') method.
Should not be invoked directly. This deals with the possible
variations of the LOCUS line which is passed in as a string
argument. No return value"""
#####################################
# LOCUS line #
#####################################
assert line[0:GENBANK_INDENT] == 'LOCUS ', \
'LOCUS line does not start correctly:\n' + line
#Have to break up the locus line, and handle the different bits of it.
#There are at least two different versions of the locus line...
if line[29:33] in [' bp ', ' aa '] :
#Old...
#
# Positions Contents
# --------- --------
# 00:06 LOCUS
# 06:12 spaces
# 12:?? Locus name
# ??:?? space
# ??:29 Length of sequence, right-justified
# 29:33 space, bp, space
# 33:41 strand type
# 41:42 space
# 42:51 Blank (implies linear), linear or circular
# 51:52 space
# 52:55 The division code (e.g. BCT, VRL, INV)
# 55:62 space
# 62:73 Date, in the form dd-MMM-yyyy (e.g., 15-MAR-1991)
#
assert line[29:33] in [' bp ', ' aa '] , \
'LOCUS line does not contain size units at expected position:\n' + line
assert line[41:42] == ' ', \
'LOCUS line does not contain space at position 42:\n' + line
assert line[42:51].strip() in ['','linear','circular'], \
'LOCUS line does not contain valid entry (linear, circular, ...):\n' + line
assert line[51:52] == ' ', \
'LOCUS line does not contain space at position 52:\n' + line
assert line[55:62] == ' ', \
'LOCUS line does not contain spaces from position 56 to 62:\n' + line
assert line[64:65] == '-', \
'LOCUS line does not contain - at position 65 in date:\n' + line
assert line[68:69] == '-', \
'LOCUS line does not contain - at position 69 in date:\n' + line
name_and_length_str = line[GENBANK_INDENT:29]
while name_and_length_str.find(' ')<>-1 :
name_and_length_str = name_and_length_str.replace(' ',' ')
name_and_length = name_and_length_str.split(' ')
assert len(name_and_length)<=2, \
'Cannot parse the name and length in the LOCUS line:\n' + line
assert len(name_and_length)<>1, \
'Name and length collide in the LOCUS line:\n' + line
#Should be possible to split them based on position, if
#a clear definition of the standard exists THAT AGREES with
#existing files.
consumer.locus(name_and_length[0])
consumer.size(name_and_length[1])
#consumer.residue_type(line[33:41].strip())
consumer.residue_type(line[33:51].strip())
consumer.data_file_division(line[52:55])
consumer.date(line[62:73])
elif line[40:44] in [' bp ', ' aa '] :
#New...
#
# Positions Contents
# --------- --------
# 00:06 LOCUS
# 06:12 spaces
# 12:?? Locus name
# ??:?? space
# ??:40 Length of sequence, right-justified
# 40:44 space, bp, space
# 44:47 Blank, ss-, ds-, ms-
# 47:54 Blank, DNA, RNA, tRNA, mRNA, uRNA, snRNA
# 54:55 space
# 55:63 Blank (implies linear), linear or circular
# 63:64 space
# 64:67 The division code (e.g. BCT, VRL, INV)
# 67:68 space
# 68:79 Date, in the form dd-MMM-yyyy (e.g., 15-MAR-1991)
#
assert line[40:44] in [' bp ', ' aa '] , \
'LOCUS line does not contain size units at expected position:\n' + line
assert line[44:47] in [' ', 'ss-', 'ds-', 'ms-'], \
'LOCUS line does not have valid strand type (Single stranded, ...):\n' + line
assert line[47:54].strip() in ['','DNA','RNA','tRNA','mRNA','uRNA','snRNA'], \
'LOCUS line does not contain valid sequence type (DNA, RNA, ...):\n' + line
assert line[54:55] == ' ', \
'LOCUS line does not contain space at position 55:\n' + line
assert line[55:63].strip() in ['','linear','circular'], \
'LOCUS line does not contain valid entry (linear, circular, ...):\n' + line
assert line[63:64] == ' ', \
'LOCUS line does not contain space at position 64:\n' + line
assert line[67:68] == ' ', \
'LOCUS line does not contain space at position 68:\n' + line
assert line[70:71] == '-', \
'LOCUS line does not contain - at position 71 in date:\n' + line
assert line[74:75] == '-', \
'LOCUS line does not contain - at position 75 in date:\n' + line
name_and_length_str = line[GENBANK_INDENT:40]
while name_and_length_str.find(' ')<>-1 :
name_and_length_str = name_and_length_str.replace(' ',' ')
name_and_length = name_and_length_str.split(' ')
assert len(name_and_length)<=2, \
'Cannot parse the name and length in the LOCUS line:\n' + line
assert len(name_and_length)<>1, \
'Name and length collide in the LOCUS line:\n' + line
#Should be possible to split them based on position, if
#a clear definition of the stand exists THAT AGREES with
#existing files.
consumer.locus(name_and_length[0])
consumer.size(name_and_length[1])
consumer.residue_type(line[44:63].strip())
consumer.data_file_division(line[64:67])
consumer.date(line[68:79])
elif line[GENBANK_INDENT:].strip().count(" ")==0 :
#Truncated LOCUS line, as produced by some EMBOSS tools - see bug 1762
#
#e.g.
#
# "LOCUS U00096"
#
#rather than:
#
# "LOCUS U00096 4639675 bp DNA circular BCT"
#
# Positions Contents
# --------- --------
# 00:06 LOCUS
# 06:12 spaces
# 12:?? Locus name
if line[GENBANK_INDENT:].strip() <> "" :
consumer.locus(line[GENBANK_INDENT:].strip())
else :
#Must just have just "LOCUS "
#We can cope with this, but is it a legitimate GenBank file?
print "Warning: Minimal LOCUS line found - is this correct?\n" + line
pass
else :
assert False, \
'Did not recognise the LOCUS line layout:\n' + line
def _feed_header(self, handle, consumer):
"""Sub function for the 'feed' method.
Should not be invoked directly. Returns a string, the last line
read from the GenBank which marks the end of the header (normally
be the FEATURE line )."""
# skip ahead until we find first record
line = handle.readline()
while line.find('LOCUS ') <> 0:
assert line, \
'Unexpected end of file while looking for LOCUS line'
if self._debug : print "Ignoring line:\n" + line
line = handle.readline()
if self._debug : print "Starting LOCUS"
self._feed_locus(line, consumer)
if self._debug : print "Finished LOCUS"
#############################################################
#now read in and cache JUST the header lines, up to and
#excluding the features and nucleotide sequence..
line = handle.readline()
while True :
assert line, \
'Unexpected end of file during GenBank header section'
assert line[0:GENBANK_INDENT] <> GENBANK_SPACER, \
'Unexpected continuation of an entry:\n' + line
if line.find("FEATURES ") == 0 :
#We are about to start the features...
return line
elif line.find('BASE COUNT')==0 :
#This means we have finished the header, and
#there is no list of features...
return line
elif line.find('ORIGIN')==0 :
#This means we have finished the header, and
#there is no list of features...
return line
elif line.find('CONTIG')==0 :
#This means we have finished the header, and
#there is no list of features...
return line
line_type = line[0:GENBANK_INDENT].strip()
data = line[GENBANK_INDENT:]
if data[-1:]=='\n' : data = data[:-1]
if data[-1:]=='\r' : data = data[:-1]
if line_type == 'VERSION' :
#Need to call consumer.version(), and maybe also consumer.gi() as well.
#e.g.
# VERSION AC007323.5 GI:6587720
while data.find(' ')<>-1:
data = data.replace(' ',' ')
if data.find(' GI:')==-1 :
consumer.version(data)
else :
if self._debug : print "Version [" + data.split(' GI:')[0] + "], gi [" + data.split(' GI:')[1] + "]"
consumer.version(data.split(' GI:')[0])
consumer.gi(data.split(' GI:')[1])
#Read in the next line!
line = handle.readline()
elif line_type == 'REFERENCE' :
if self._debug >1 : print "Found reference [" + data + "]"
#Need to call consumer.reference_num() and consumer.reference_bases()
#e.g.
# REFERENCE 1 (bases 1 to 86436)
#
#Note that this can be multiline, see Bug 1968, e.g.
#
# REFERENCE 42 (bases 1517 to 1696; 3932 to 4112; 17880 to 17975; 21142 to
# 28259)
#
#For such cases we will call the consumer once only.
data = data.strip()
#Read in the next line, and see if its more of the reference:
while True:
line = handle.readline()
if line[0:GENBANK_INDENT] == GENBANK_SPACER :
#Add this continuation to the data string
data = data + " " + line[GENBANK_INDENT:]
if data[-1:]=='\n' : data = data[:-1]
if data[-1:]=='\r' : data = data[:-1]
if self._debug >1 : print "Extended reference text [" + data + "]"
else :
#End of the reference, leave this text in the variable "line"
break
#We now have all the reference line(s) stored in a string, data,
#which we pass to the consumer
while data.find(' ')<>-1:
data = data.replace(' ',' ')
if data.find(' ')==-1 :
if self._debug >2 : print 'Reference number \"' + data + '\"'
consumer.reference_num(data)
else :
if self._debug >2 : print 'Reference number \"' + data[:data.find(' ')] + '\", \"' + data[data.find(' ')+1:] + '\"'
consumer.reference_num(data[:data.find(' ')])
consumer.reference_bases(data[data.find(' ')+1:])
elif line_type == 'ORGANISM' :
#The first line is the organism, but subsequent lines go to the taxonomy consumer
consumer.organism(data)
data = ""
while True :
line = handle.readline()
if line[0:GENBANK_INDENT] == GENBANK_SPACER :
data = data + ' ' + line[GENBANK_INDENT:]
if data[-1:]=='\n' : data = data[:-1]
if data[-1:]=='\r' : data = data[:-1]
else :
#We now have all the data for this taxonomy:
consumer.taxonomy(data.strip())
#End of continuation - return to top of loop!
break
elif line_type == 'COMMENT' :
if self._debug > 1 : print "Found comment"
#This can be multiline, and should call consumer.comment() once
#with a list where each entry is a line.
list=[]
list.append(data)
while True:
line = handle.readline()
if line[0:GENBANK_INDENT] == GENBANK_SPACER :
data = line[GENBANK_INDENT:]
if data[-1:]=='\n' : data = data[:-1]
if data[-1:]=='\r' : data = data[:-1]
list.append(data)
if self._debug > 2 : print "Comment continuation [" + data + "]"
else :
#End of the comment
break
consumer.comment(list)
list=[]
elif line_type in self._consumer_dict :
#Its a semi-automatic entry!
#Now, this may be a multi line entry...
while True :
line = handle.readline()
if line[0:GENBANK_INDENT] == GENBANK_SPACER :
data = data + ' ' + line[GENBANK_INDENT:]
if data[-1:]=='\n' : data = data[:-1]
if data[-1:]=='\r' : data = data[:-1]
else :
#We now have all the data for this entry:
getattr(consumer, self._consumer_dict[line_type])(data)
#End of continuation - return to top of loop!
break
else :
#Its an unknown line type, the NCBI might have added
#something new... see bug 1946
#Print a warning, and ignore the line (and any continuation)
print 'WARNING - Ignoring an unknown line type, ' + line_type + ' found:\n' + line
while True :
line = handle.readline()
if line[0:GENBANK_INDENT] == GENBANK_SPACER :
#More of the unknown line type, could print another
#warning...
pass
else :
#Got to the end of it.
break
#############################################################
if self._debug : print "Found start of features..."
assert line.find("FEATURES ") == 0, \
'Internal error - expected to be on the FEATURES line, not:\n' + line
#############################################################
def feed(self, handle, consumer):
"""Feed a set of data into the scanner.
Arguments:
o handle - A handle with the information to parse.
o consumer - The consumer that should be informed of events.
"""
#This will look for the LOCUS line, and then
#continue until the end of the header is found.
#This is usually the FEATURES line.
line = self._feed_header(handle, consumer)
if line[-1:]=='\n' : line = line[:-1]
if line[-1:]=='\r' : line = line[:-1]
if self._debug > 1 :
print "self._feed_header returned :\n" + line
if line.find("FEATURES ") <> 0 :
#It is abnormal, but allowed, that there is no list
#of features... e.g. output from EMBOSS seqret, See bug 1762
if self._debug : print "WARNING - Header was not followed by FEATURES, but by:\n" + line
else :
#At this point, the FEATURES line has normally just been
#read in. Its doesn't actually have any usefull content
#except as a "section divider"
consumer.features_line(line)
#Now parse the features table...
line = handle.readline()
if line[-1:]=='\n' : line = line[:-1]
if line[-1:]=='\r' : line = line[:-1]
while True :
assert line, \
'Unexpected blank line/end of file during GenBank features section'
assert line[0:FEATURE_QUALIFIER_INDENT]<>FEATURE_QUALIFIER_SPACER, \
'Unexpected continuation of feature:\n' + line
if line[0:FEATURE_KEY_INDENT]<>FEATURE_KEY_SPACER :
#This should be the BASE COUNT, ORIGIN or CONTIG line now
break
#So, start of a new feature then.
#This line should have a feature_key and a location string
#(note the location could span several lines!)
#Extract the key...
feature_key = line[FEATURE_KEY_INDENT:FEATURE_QUALIFIER_INDENT].strip()
consumer.feature_key(feature_key)
#Extract the location...
feature_location = line[FEATURE_QUALIFIER_INDENT:].strip()
while feature_location[-1:]=="," :
#Still more to come!
line = handle.readline()
assert line[0:FEATURE_QUALIFIER_INDENT]==FEATURE_QUALIFIER_SPACER, \
'Expected continuation of location, not:\n' + line
line = line[FEATURE_QUALIFIER_INDENT:]
if line[-1:]=='\n' : line = line[:-1]
if line[-1:]=='\r' : line = line[:-1]
feature_location = feature_location + line
#############################################################
if self._debug > 1 : print "Starting " + feature_key + " feature at location " + feature_location
#############################################################
consumer.location(feature_location)
#We have dealt with that line (key and location, plus any lines continuing of the location).
#The next line could be the first of one or more qualifiers to the feature:
#
#Can have single line entries like this:
# /pseudo (no information)
# /name=Fred (unquoted)
# /name="Fred Jones" (quoted)
#
#Can have quoted multiline entries like this:
# /name="Fred
# Jones"
#
#Or even like this (see bug 1903):
# /name="
# Fred Jones"
#
#We can also have unquoted multiline entries (bug 1758):
# /transl_except=(pos:complement(18111697..18111699),
# aa:OTHER)
#
#Note that you can get text of the form /word= which are INSIDE a
#quoted entry, which does not mean its a new feature key!
#(Any examples to hand?)
#
#Also note that the NCBI have sometimes used unescaped quotes inside
#the text, for example it was reported on the mailing list that one
#version of NC_000913 had the following:
# /note="2'-(5"-phosphoribosyl)-3'-dephospho-CoA...
#The 02-DEC-2005 version of the citX gene had been changed to:
# /note="2'-(5'-phosphoribosyl)-3'-dephospho-CoA...
#
#We have also seen blank lines inside a multiline feature (see bug 1942)
line = handle.readline()
if line[-1:]=='\n' : line = line[:-1]
if line[-1:]=='\r' : line = line[:-1]
while line[0:FEATURE_QUALIFIER_INDENT]==FEATURE_QUALIFIER_SPACER :
#This SHOULD be the start of a new qualifier for the current feature
line = line[FEATURE_QUALIFIER_INDENT:]
if line[0:1]<>'/' :
#This is an unquoted multiline feature key, as reported in bug 1758
print "WARNING - Unquoted multiline '%s' entry for %s feature with location %s" \
% (qualifier_name, feature_key, feature_location)
#This will append the line to the description parsed so far:
consumer.feature_qualifier_description(line)
elif line.find("=") == -1 :
#Can have qualifiers with no data, like /psuedo
qualifier_name = line[1:]
consumer.feature_qualifier_name([qualifier_name])
#There is no description in this case
else :
#Expect format /name=... or /name="...
#or in odd cases, /name="\n... see bug 1903
qualifier_name = line[1:line.find('=')]
consumer.feature_qualifier_name([qualifier_name])
qualifier_description = line[line.find("=")+1:]
#Try and get all of the description now, so we can make a single
#call to the consumer. Making less function calls should be
#slightly faster.
if qualifier_description=='\"' \
or ( qualifier_description[0:1]=='\"' and qualifier_description[-1:]<>'\"' ) :
#There should now be one or more lines continuing the description
while True :
line = handle.readline()
if line[-1:]=='\n' : line = line[:-1]
if line[-1:]=='\r' : line = line[:-1]
while line=="" :
#See bug 1942, blank line in feature with malformed /note entry
print "WARNING - Blank line in '%s' entry for %s feature with location %s" \
% (qualifier_name, feature_key, feature_location)
#Ignore it, carry on
line = handle.readline()
if not line : break
if line[-1:]=='\n' : line = line[:-1]
if line[-1:]=='\r' : line = line[:-1]
assert line[0:FEATURE_QUALIFIER_INDENT]==FEATURE_QUALIFIER_SPACER, \
"Expected qualifier description continuation in " \
+ "'%s' entry for %s feature with location %s, not:\n%s" \
% (qualifier_name, feature_key, feature_location, line)
#Note, for backwards compatibility we do not remove the FEATURE_QUALIFIER_SPACER
#from the description
qualifier_description = qualifier_description + '\n' + line
if qualifier_description[-1:]=='\"' :
#That should be the end of the description continuation
break
consumer.feature_qualifier_description(qualifier_description)
#We have dealt with that line (qualifier and description, plus any line continuing the description).
#There could be another qualifier for this feature...
line = handle.readline()
if line[-1:]=='\n' : line = line[:-1]
if line[-1:]=='\r' : line = line[:-1]
#We have dealt with all the qualifiers (if any) for this feature
#Now move on to the next line...
#############################################################
if self._debug : print "Finished features"
#############################################################
#We should now be on the BASE COUNT, ORIGIN or CONTIG line
if line.find('BASE COUNT')==0 :
#Hmm.
line = line[10:].strip()
if self._debug : print "base_count = " + line
consumer.base_count(line)
line = handle.readline()
if line[-1:]=='\n' : line = line[:-1]
if line[-1:]=='\r' : line = line[:-1]
if line.find("ORIGIN")==0 :
#############################################################
if self._debug : print "Starting sequence..."
#############################################################
#May need to call consumer for origin_name if part of ORIGIN line...
line = line[6:].strip()
if line :
if self._debug : print "origin_name = " + line
consumer.origin_name(line)
#Now just consume the sequence lines until reach the // marker
#or a CONTIG line
while True :
line = handle.readline()
if line[-1:]=='\n' : line = line[:-1]
if line[-1:]=='\r' : line = line[:-1]
assert line, \
'Unexpected blank line/end of file during GenBank ORIGIN section'
if line=='//' :
break
if line.find('CONTIG')==0 :
break
assert line[9:10]==' ', \
'Sequence line mal-formed, \n' + line
consumer.base_number(line[0:10].strip())
consumer.sequence(line[10:])
if line.find("CONTIG")==0 :
#############################################################
if self._debug : print "Starting Contig..."
#############################################################
line = line[6:].strip()
contig_location = line + '\n'
while True :
line = handle.readline()
if line[-1:]=='\n' : line = line[:-1]
if line[-1:]=='\r' : line = line[:-1]
assert line, \
'Unexpected blank line/end of file during GenBank CONTIG section'
if line=='//' :
consumer.contig_location(contig_location)
break
elif line[:GENBANK_INDENT]==GENBANK_SPACER :
contig_location = contig_location + line
else:
consumer.contig_location(contig_location)
assert False, \
'Expected CONTIG continuation line or // marker, got\n' + line
break
if line=='//' :
#############################################################
if self._debug : print "Found record end..."
#############################################################
consumer.record_end(line)
return
assert False, \
'Unexpected line near end of file:\n' + line
return
def index_file(filename, indexname, rec2key = None, use_berkeley = 0):
"""Index a GenBank file to prepare it for use as a dictionary.
Arguments:
filename - The name of the GenBank file to be indexed.
indexname - The name of the index to create
rec2key - A reference to a function object which, when called with a
SeqRecord object, will return a key to be used for the record. If no
function is specified then the records will be indexed by the 'id'
attribute of the SeqRecord (the versioned GenBank id).
use_berkeley - specifies whether to use the BerkeleyDB indexer, which
uses the bsddb3 wrappers around the embedded database Berkeley DB. By
default, the standard flat file (non-Berkeley) indexes are used.
"""
if rec2key:
indexer = SimpleSeqRecord.FunctionIndexer(rec2key)
else:
indexer = SimpleSeqRecord.SimpleIndexer()
if use_berkeley:
SimpleSeqRecord.create_berkeleydb([filename], indexname, indexer)
else:
SimpleSeqRecord.create_flatdb([filename], indexname, indexer)
class NCBIDictionary:
"""Access GenBank using a read-only dictionary interface.
"""
VALID_DATABASES = ['nucleotide', 'protein']
VALID_FORMATS = ['genbank', 'fasta']
def __init__(self, database, format, parser = None):
"""Initialize an NCBI dictionary to retrieve sequences.
Create a new Dictionary to access GenBank. Valid values for
database are 'nucleotide' and 'protein'.
Valid values for format are 'genbank' (for nucleotide genbank and
protein genpept) and 'fasta'.
dely and retmax are old options kept only for compatibility -- do not
bother to set them.
parser is an optional parser object
to change the results into another form. If unspecified, then
the raw contents of the file will be returned.
"""
self.parser = parser
if database not in self.__class__.VALID_DATABASES:
raise ValueError("Invalid database %s, should be one of %s" %
(database, self.__class__.VALID_DATABASES))
if format not in self.__class__.VALID_FORMATS:
raise ValueError("Invalid format %s, should be one of %s" %
(format, self.__class__.VALID_FORMATS))
if format == 'fasta':
self.db = db["fasta-sequence-eutils"]
elif format == 'genbank':
if database == 'nucleotide':
self.db = db["nucleotide-genbank-eutils"]
elif database == 'protein':
self.db = db["protein-genbank-eutils"]
def __len__(self):
raise NotImplementedError, "GenBank contains lots of entries"
def clear(self):
raise NotImplementedError, "This is a read-only dictionary"
def __setitem__(self, key, item):
raise NotImplementedError, "This is a read-only dictionary"
def update(self):
raise NotImplementedError, "This is a read-only dictionary"
def copy(self):
raise NotImplementedError, "You don't need to do this..."
def keys(self):
raise NotImplementedError, "You don't really want to do this..."
def items(self):
raise NotImplementedError, "You don't really want to do this..."
def values(self):
raise NotImplementedError, "You don't really want to do this..."
def has_key(self, id):
"""S.has_key(id) -> bool"""
try:
self[id]
except KeyError:
return 0
return 1
def get(self, id, failobj=None):
try:
return self[id]
except KeyError:
return failobj
raise "How did I get here?"
def __getitem__(self, id):
"""Return the GenBank entry specified by the GenBank ID.
Raises a KeyError if there's an error.
"""
handle = self.db[id]
# Parse the record if a parser was passed in.
if self.parser is not None:
return self.parser.parse(handle)
return handle.read()
def search_for(search, database='nucleotide',
reldate=None, mindate=None, maxdate=None,
start_id = 0, max_ids = 50000000):
"""search_for(search[, reldate][, mindate][, maxdate]
[, batchsize][, delay][, callback_fn][, start_id][, max_ids]) -> ids
Search GenBank and return a list of the GenBank identifiers (gi's)
that match the criteria. search is the search string used to
search the database. Valid values for database are
'nucleotide', 'protein', 'popset' and 'genome'. reldate is
the number of dates prior to the current date to restrict the
search. mindate and maxdate are the dates to restrict the search,
e.g. 2002/01/01. start_id is the number to begin retrieval on.
max_ids specifies the maximum number of id's to retrieve.
batchsize, delay and callback_fn are old parameters for
compatibility -- do not set them.
"""
# deal with dates
date_restrict = None
if reldate:
date_restrict = EUtils.WithinNDays(reldate)
elif mindate:
date_restrict = EUtils.DateRange(mindate, maxdate)
eutils_client = DBIdsClient.DBIdsClient()
db_ids = eutils_client.search(search, database, daterange = date_restrict,
retstart = start_id, retmax = max_ids)
ids = []
for db_id in db_ids:
ids.append(db_id.dbids.ids[0])
return ids
def download_many(ids, database = 'nucleotide'):
"""download_many(ids, database) -> handle of results
Download many records from GenBank. ids is a list of gis or
accessions.
callback_fn, broken_fn, delay, faildelay, batchsize, parser are old
parameter for compatibility. They should not be used.
"""
db_ids = DBIds(database, ids)
if database in ['nucleotide']:
format = 'gb'
elif database in ['protein']:
format = 'gp'
else:
raise ValueError("Unexpected database: %s" % database)
eutils_client = DBIdsClient.from_dbids(db_ids)
result_handle = eutils_client.efetch(retmode = "text", rettype = format)
return cStringIO.StringIO(result_handle.read())
|