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
|
import io
import warnings
import numpy
import pytest
from cogent3 import DNA, SequenceCollection, _Table, load_seq
from cogent3.core.annotation_db import (
BasicAnnotationDb,
GenbankAnnotationDb,
GffAnnotationDb,
SupportsFeatures,
_matching_conditions,
_rename_column_if_exists,
load_annotations,
update_file_format,
)
from cogent3.core.sequence import Sequence
from cogent3.parse.genbank import MinimalGenbankParser
from cogent3.util import deserialise
@pytest.fixture(scope="function")
def gff_db(DATA_DIR):
path = DATA_DIR / "c_elegans_WS199_shortened_gff.gff3"
return load_annotations(path=path)
@pytest.fixture(scope="function")
def gff_small_db(DATA_DIR):
path = DATA_DIR / "simple.gff"
return load_annotations(path=path)
@pytest.fixture()
def seq_db(DATA_DIR):
seq = load_seq(DATA_DIR / "c_elegans_WS199_dna_shortened.fasta", moltype="dna")
db = load_annotations(path=DATA_DIR / "c_elegans_WS199_shortened_gff.gff3")
seq.annotation_db = db
return seq
@pytest.fixture()
def seq() -> Sequence:
return Sequence("ATTGTACGCCTTTTTTATTATT", name="test_seq")
@pytest.fixture(scope="function")
def anno_db() -> BasicAnnotationDb:
# an empty db that we can add to
return BasicAnnotationDb()
@pytest.fixture()
def simple_seq_gff_db(DATA_DIR) -> Sequence:
seq = Sequence("ATTGTACGCCTTTTTTATTATT", name="test_seq")
seq.annotate_from_gff(DATA_DIR / "simple.gff")
return seq
def test_assign_valid_db(seq, anno_db):
# should not fail
seq.annotation_db = anno_db
assert seq.annotation_db is anno_db
def test_replace_annotation_db_check_invalid(seq):
with pytest.raises(TypeError):
seq.replace_annotation_db(2, check=True)
def test_replace_annotation_db_nocheck_invalid(seq):
seq.replace_annotation_db(2, check=False)
assert seq.annotation_db == 2
@pytest.mark.parametrize(
"db_name,cls", (("gff_db", GenbankAnnotationDb), ("gb_db", GffAnnotationDb))
)
def test_constructor_db_fail(db_name, cls, request):
db = request.getfixturevalue(db_name)
with pytest.raises(TypeError):
cls(db=db)
@pytest.mark.parametrize(
"db_name,cls", (("gff_db", GenbankAnnotationDb), ("gb_db", GffAnnotationDb))
)
def test_constructor_wrong_db_schema(db_name, cls, request):
db = request.getfixturevalue(db_name)
with pytest.raises(TypeError):
cls(db=db.db)
@pytest.mark.parametrize(
"db_name,cls",
(
("gff_db", GffAnnotationDb),
("anno_db", GffAnnotationDb),
("gb_db", GenbankAnnotationDb),
("anno_db", GenbankAnnotationDb),
),
)
def test_constructor_db_instance_works(db_name, cls, request):
# only compatible db's used to init
db = request.getfixturevalue(db_name)
cls(db=db)
@pytest.mark.parametrize(
"db_name,cls",
(
("gff_db", GffAnnotationDb),
("anno_db", GffAnnotationDb),
("gb_db", GenbankAnnotationDb),
("anno_db", GenbankAnnotationDb),
),
)
def test_constructor_db_connection_works(db_name, cls, request):
# only compatible db's used to init
db = request.getfixturevalue(db_name)
cls(db=db.db)
def test_gff_describe(gff_db):
result = gff_db.describe
assert isinstance(result, _Table)
def test_count_distinct(gff_db):
# no arguments, returns None
assert gff_db.count_distinct() is None
# there are 8 biotypes in the c.elegans gff sample, 2 columns
# all arguments returns, from our example, all the rows
got = gff_db.count_distinct(biotype=True)
assert got.shape == (
8,
2,
)
# all names unique, 11 records, 4 columns
got = gff_db.count_distinct(biotype=True, seqid=True, name=True)
assert got.shape == (11, 4)
def test_count_distinct_values(gb_db):
# there are 8 biotypes in the c.elegans gff sample, 2 columns
# all arguments returns, from our example, all the rows
got = {tuple(r) for r in gb_db.count_distinct(name=True).to_list()}
expect = {("CNA00110", 4), ("CNA00120", 3), ("cgg", 1), ("cat", 1), ("JEC21", 1)}
assert got == expect
def test_count_distinct_gene_name(gb_db):
expect = {("CNA00110", 1), ("CNA00120", 1)}
assert {
tuple(r) for r in gb_db.count_distinct(biotype="gene", name=True).to_list()
} == expect
assert {
tuple(r)
for r in gb_db.count_distinct(
seqid="AE017341", biotype="gene", name=True
).to_list()
} == expect
def test_count_distinct_no_match(gb_db):
# return a table with 0 rows, 2 columns
got = gb_db.count_distinct(biotype=True, name="blah")
assert got.shape == (0, 2)
got = gb_db.count_distinct(biotype="madeup", name=True)
assert got.shape == (0, 2)
def test_gff_features_matching(gff_db):
result = list(gff_db.get_features_matching(biotype="CDS"))
assert len(result)
def test_gff_get_children(gff_db):
# an ID with 8 children
children = list(gff_db.get_feature_children(name="Transcript:B0019.1"))
assert len(children) == 8
# this is parent of the transcript, and due to the funky structure of
# this gff, also to one of the CDS entries
children = list(gff_db.get_feature_children(name="Gene:WBGene00000138"))
assert len(children) == 2
@pytest.mark.parametrize(
"name,expected",
(
("CDS:B0019.1", ("Transcript:B0019.1", "Gene:WBGene00000138")),
("Transcript:B0019.1", ("Gene:WBGene00000138",)),
),
)
def test_gff_get_parent(gff_db, name, expected):
# the first id has two parents, which is weird
got = list(gff_db.get_feature_parent(name=name))
assert len(got) == len(expected)
assert {g["name"] for g in got} == set(expected)
def test_gff_get_children_empty(DATA_DIR):
"""if feature has no children then should return []"""
db = load_annotations(path=DATA_DIR / "simple2.gff")
got = list(db.get_feature_children(name="childless"))
assert got == []
def test_gff_get_parent_empty(DATA_DIR):
"""if feature has no parent then should return []"""
db = load_annotations(path=DATA_DIR / "simple2.gff")
got = list(db.get_feature_parent(name="parentless"))
assert got == []
def test_gff_get_children_non_existent(DATA_DIR):
"""if feature does not exist then should return []"""
db = load_annotations(path=DATA_DIR / "simple2.gff")
got = list(db.get_feature_children(name="nonexistendID"))
assert got == []
def test_gff_get_parent_non_existent(DATA_DIR):
"""if feature does not exist then should return []"""
db = load_annotations(path=DATA_DIR / "simple2.gff")
got = list(db.get_feature_parent(name="nonexistendID"))
assert got == []
def test_gff_counts(gff_db):
got = gff_db.biotype_counts()
assert len(got) > 0
def test_gff_num_matches(gff_db):
count = gff_db.num_matches()
assert count == 11
assert gff_db.num_matches(seqid="I") == 11
assert gff_db.num_matches(seqid="IV") == 0
def test_gb_num_matches(gb_db):
count = gb_db.num_matches()
assert count == 10 # value from manual count from file
assert gb_db.num_matches(seqid="AE017341") == 10
assert gb_db.num_matches(seqid="IV") == 0
def test_gff_find_user_features(gff_db):
record = dict(
seqid="2", name="gene-01", biotype="gene", spans=[(23, 33)], strand="+"
)
gff_db.add_feature(**record)
# by biotype
found = any(
gene["name"] == "gene-01"
for gene in gff_db.get_features_matching(biotype="gene")
)
assert found
# by name
found = any(
gene["name"] == "gene-01"
for gene in gff_db.get_features_matching(name="gene-01")
)
assert found
def test_empty_data():
_ = GffAnnotationDb()
# testing GenBank files
@pytest.fixture(scope="function")
def gb_db(DATA_DIR):
return load_annotations(path=DATA_DIR / "annotated_seq.gb")
def test_load_annotations_multi(DATA_DIR):
one = load_annotations(path=DATA_DIR / "simple.gff")
two = load_annotations(path=DATA_DIR / "simple2.gff")
expect = len(one) + len(two)
got = load_annotations(path=DATA_DIR / "simple*.gff")
assert len(got) == expect
@pytest.mark.parametrize("parent_biotype, name", (("gene", "CNA00110"),))
def test_gb_get_children(gb_db, parent_biotype, name):
parent = list(gb_db.get_features_matching(biotype=parent_biotype, name=name))[0]
coords = numpy.array(parent["spans"])
child = list(
gb_db.get_feature_children(
name=name,
exclude_biotype=parent_biotype,
start=coords.min(),
stop=coords.max(),
)
)[0]
assert child["biotype"] != parent["biotype"]
assert child["name"] == parent["name"]
def test_gb_get_parent(gb_db):
cds_id = "CNA00110"
cds = list(gb_db.get_features_matching(biotype="CDS", name=cds_id))[0]
coords = numpy.array(cds["spans"])
parent = list(
gb_db.get_feature_parent(
name=cds_id,
exclude_biotype="CDS",
start=coords.min(),
stop=coords.max(),
)
)[0]
assert parent["biotype"] != cds["biotype"]
assert parent["biotype"] == "gene"
assert parent["name"] == cds["name"]
def test_protocol_adherence(gff_db, gb_db):
for db in (gff_db, gb_db):
assert isinstance(db, SupportsFeatures)
def test_get_features_matching_no_annotation_db(seq):
"""
Test that `get_features_matching` returns an empty list when no annotation database is attached to the sequence.
"""
assert not list(seq.get_features())
def test_get_features_matching_no_matching_feature(seq, anno_db):
"""
Test that `get_features_matching` returns an empty list when there is no matching feature in the annotation database.
"""
seq.annotation_db = anno_db
anno_db.add_feature(
seqid=seq.name, biotype="exon", name="exon1", spans=[(1, 4)], strand="+"
)
assert not list(seq.get_features(biotype="exon", name="non_matching"))
assert not list(seq.get_features(biotype="CDS"))
def test_get_features_matching_matching_feature(seq, anno_db):
"""
Test that `get_features_matching` returns a list with one matching feature in the annotation database.
"""
seq.annotation_db = anno_db
anno_db.add_feature(
seqid=seq.name, biotype="exon", name="exon1", spans=[(1, 4)], strand="+"
)
got = list(seq.get_features(biotype="exon"))
assert got[0].biotype == "exon"
assert got[0].name == "exon1"
assert len(got) == 1
def test_feature_strand():
from cogent3 import make_seq
# ++ ++++
# --- --
raw_seq = "AACCTTTGGGGAATTT"
plus_spans = [(2, 4), (7, 11)]
plus_seq = "".join(raw_seq[s:e] for s, e in plus_spans)
minus_spans = [(4, 7), (11, 13)]
minus_seq = "".join(raw_seq[s:e] for s, e in minus_spans)
minus_seq = "".join([{"T": "A", "A": "T"}[b] for b in minus_seq[::-1]])
seq = make_seq(raw_seq, name="s1", moltype="dna")
db = GffAnnotationDb()
db.add_feature(
seqid="s1",
biotype="cds",
name="plus",
spans=plus_spans,
strand="+",
on_alignment=False,
)
db.add_feature(
seqid="s1",
biotype="cds",
name="minus",
spans=minus_spans,
strand="-",
on_alignment=False,
)
seq.annotation_db = db
plus = list(seq.get_features(name="plus"))[0]
assert str(plus.get_slice()) == plus_seq
minus = list(seq.get_features(name="minus"))[0]
assert str(minus.get_slice()) == minus_seq
# now reverse complement the sequence
rced = seq.rc()
plus = list(rced.get_features(name="plus"))[0]
assert str(plus.get_slice()) == plus_seq
minus = list(rced.get_features(name="minus"))[0]
assert str(minus.get_slice()) == minus_seq
def test_feature_nucleic():
from cogent3 import make_seq
from cogent3.core import location as loc
# 111111
# 0123456789012345
seq = make_seq("AACCTTTGGGGAATTT", moltype="dna")
mmap = loc.FeatureMap.from_locations(
locations=[(4, 7), (10, 12)], parent_length=len(seq)
)
expect = seq[mmap]
rcseq = seq.rc()
rmap = mmap.nucleic_reversed()
got = rcseq[rmap].rc()
assert str(got) == str(expect)
def test_add_feature_with_parent():
db = GffAnnotationDb()
db.add_feature(
seqid="s1",
biotype="cds",
name="GG",
spans=[(0, 100)],
strand="+",
)
db.add_feature(
seqid="s1",
biotype="exon",
name="child",
spans=[(10, 30)],
strand="+",
parent_id="GG",
)
got = list(db.get_features_matching(name="GG"))[0]
child = list(db.get_feature_children(got["name"]))[0]
assert child["name"] == "child"
def test_get_features_matching_matching_features(anno_db: GffAnnotationDb, seq):
"""
Test that `get_features_matching` returns a list with all matching features in the annotation database.
"""
seq.annotation_db = anno_db
anno_db.add_feature(
seqid=seq.name, biotype="exon", name="exon1", spans=[(1, 4)], strand="+"
)
anno_db.add_feature(
seqid=seq.name, biotype="exon", name="exon2", spans=[(6, 10)], strand="+"
)
got = list(seq.get_features(biotype="exon"))
assert len(got) == 2
def test_annotate_from_gff(DATA_DIR, seq):
seq.annotate_from_gff(DATA_DIR / "simple.gff")
got = list(seq.get_features(biotype="exon"))
assert len(got) == 2
got = list(seq.get_features(biotype="CDS"))
assert len(got) == 2
got = list(seq.get_features(biotype="CpG"))
assert len(got) == 1
def test_get_features_matching_start_stop(DATA_DIR, seq):
seq.annotate_from_gff(DATA_DIR / "simple.gff")
got = list(seq.get_features(start=2, stop=10, allow_partial=True))
assert len(got) == 4
def test_matching_conditions():
got, _ = _matching_conditions({"start": 1, "stop": 5}, allow_partial=True)
expect = "((start >= 1 AND stop <= 5) OR (start <= 1 AND stop > 1) OR (start < 5 AND stop >= 5) OR (start <= 1 AND stop >= 5))"
assert got == expect
def test_matching_conditions_IN():
got, cond = _matching_conditions(
{"biotype": ("CDS", "mRNA", "exon")}, allow_partial=True
)
expect = "biotype IN (?,?,?)"
assert got == expect
assert cond == ("CDS", "mRNA", "exon")
@pytest.mark.parametrize(
"biotype_value_1", ["CDS", "mRNA", "exon", "three_prime_UTR", "intron"]
)
@pytest.mark.parametrize(
"biotype_value_2", ["CDS", "mRNA", "exon", "five_prime_UTR", "intron"]
)
def test_get_features_matching_multiple_biotype_tuple(
seq_db, biotype_value_1, biotype_value_2
):
"""querying for features with multiple values should return the
same result as the sum of querying for each value seperately"""
where_1 = list(seq_db.get_features(biotype=biotype_value_1))
where_2 = list(seq_db.get_features(biotype=biotype_value_2))
in_both = list(seq_db.get_features(biotype=(biotype_value_1, biotype_value_2)))
if biotype_value_1 == biotype_value_2:
assert len(where_1) == len(in_both) and len(where_2) == len(in_both)
else:
assert len(where_1) + len(where_2) == len(in_both)
@pytest.mark.parametrize("biotype_value_1", ["CDS", "mRNA", "exon", "intron"])
@pytest.mark.parametrize("biotype_value_2", ["CDS", "mRNA", "exon", "intron"])
def test_get_features_matching_multiple_biotype_list(
seq_db, biotype_value_1, biotype_value_2
):
"""querying for features with multiple values should return the
same result as the sum of querying for each value seperately"""
where_1 = list(seq_db.get_features(biotype=biotype_value_1))
where_2 = list(seq_db.get_features(biotype=biotype_value_2))
in_both = list(seq_db.get_features(biotype=[biotype_value_1, biotype_value_2]))
if biotype_value_1 == biotype_value_2:
assert len(where_1) == len(in_both) and len(where_2) == len(in_both)
else:
assert len(where_1) + len(where_2) == len(in_both)
@pytest.mark.parametrize("biotype_value_1", ["CDS", "mRNA", "exon", "intron"])
@pytest.mark.parametrize("biotype_value_2", ["CDS", "mRNA", "exon", "intron"])
def test_get_features_matching_multiple_biotype_set(
seq_db, biotype_value_1, biotype_value_2
):
"""querying for features with multiple values should return the
same result as the sum of querying for each value seperately"""
where_1 = list(seq_db.get_features(biotype=biotype_value_1))
where_2 = list(seq_db.get_features(biotype=biotype_value_2))
in_both = list(seq_db.get_features(biotype={biotype_value_1, biotype_value_2}))
if biotype_value_1 == biotype_value_2:
assert len(where_1) == len(in_both) and len(where_2) == len(in_both)
else:
assert len(where_1) + len(where_2) == len(in_both)
def test_get_features_matching_start_stop_seqview(DATA_DIR, seq):
"""testing that get_features_matching adjusts"""
seq.annotate_from_gff(DATA_DIR / "simple.gff")
seq_features = list(seq.get_features(start=0, stop=3, allow_partial=True))
assert len(seq_features) == 3
# edge case, only 1 features that overlaps with index 12
# is actually returning [exon2 at [11:20]/13, CpG1 at [2:12]/13]
# possibly a bug in the SQL generating code
subseq = seq[9:]
seq_features_features = list(
subseq.get_features(start=3, stop=10, allow_partial=True)
)
assert len(seq_features_features) == 1
def test_get_slice():
"""get_slice should return the same as slicing the sequence directly"""
seq = Sequence("ATTGTACGCCCCTGA", name="test_seq")
feature_data = {
"biotype": "CDS",
"name": "fake",
"spans": [
(5, 10),
],
"strand": "+",
}
feature = seq.make_feature(feature_data)
got = feature.get_slice()
assert str(got) == str(seq[5:10])
def test_feature_get_children(seq_db):
feat = list(seq_db.get_features(name="Transcript:B0019.1"))[0]
new_feat_5pUTR = list(feat.get_children(biotype="five_prime_UTR"))
assert len(new_feat_5pUTR) == 1
new_feat_CDS = list(feat.get_children(biotype="CDS"))[0]
assert new_feat_CDS.name == "CDS:B0019.1"
def test_db_persists_post_rc(seq_db):
"""assert that the db persists after the .rc() method call"""
rc_seq = seq_db.rc()
assert rc_seq.annotation_db is not None
def test_rc_get_slice_negative_feature(seq_db):
"""given a feature on the - strand, the feature.get_slice() should return
the same sequence before and after the sequence is reverse complemented
"""
feat = list(seq_db.get_features(name="Transcript:B0019.1"))[0]
rc_seq = seq_db.rc()
r_feat = list(rc_seq.get_features(name="Transcript:B0019.1"))[0]
assert feat.get_slice() == r_feat.get_slice()
def test_rc_get_slice_positive_feature(anno_db):
"""given a feature on the + strand, the feature.get_slice() should return
the same sequence before and after the sequence is reverse complemented
"""
seq = DNA.make_seq("AAAAGGGG", name="seq1")
seq.annotation_db = anno_db
anno_db.add_feature(
seqid=seq.name, biotype="exon", name="exon1", spans=[(2, 6)], strand="+"
)
feat = list(seq.get_features(name="exon1"))[0]
r_seq = seq.rc()
r_feat = list(r_seq.get_features(name="exon1"))[0]
assert feat.get_slice() == r_feat.get_slice()
def test_add_feature(seq):
"""Sequence supports manual adding of features for a seq with no bound AnnotationDb"""
record = dict(name="gene-01", biotype="gene", spans=[(12, 16)], strand="+")
seq.add_feature(**record)
feats = list(seq.get_features(biotype="gene"))
assert seq.annotation_db is not None
assert len(feats) == 1
assert feats[0].biotype == "gene"
def test_add_feature_existing_db(simple_seq_gff_db):
"""Sequence supports manual adding of features for a seq with an existing AnnotationDb"""
record = dict(name="gene-01", biotype="gene", spans=[(12, 16)], strand="+")
simple_seq_gff_db.add_feature(**record)
# total features should be 5+1=6
all_feats = list(simple_seq_gff_db.get_features())
assert len(all_feats) == 6
def test__getitem__(simple_seq_gff_db):
"""Sequence.__getitem__ should keep the underlying seq in the SeqView
and preserve any annotation_db"""
seq_sliced = simple_seq_gff_db[4:6]
assert seq_sliced == str(simple_seq_gff_db)[4:6]
# check the underlying seq is still the original sequence data
assert seq_sliced._seq.seq == str(simple_seq_gff_db)
# check the annotation_db is still attached and the same instance
assert (
seq_sliced.annotation_db
and seq_sliced.annotation_db is simple_seq_gff_db.annotation_db
)
def test_annotate_from_gff_multiple_calls(DATA_DIR, seq):
"""5 records in each gff file, total features on seq should be 10"""
seq.annotate_from_gff(DATA_DIR / "simple.gff")
seq.annotate_from_gff(DATA_DIR / "simple2.gff")
assert len(list(seq.get_features())) == 10
def test_sequence_collection_annotate_from_gff(DATA_DIR):
"""providing a seqid to SequenceCollection.annotate_from_gff will
annotate the SequenceCollection, and the Sequence. Both of these will point
to the same AnnotationDb instance
"""
seqs = {"test_seq": "ATCGATCGATCG", "test_seq2": "GATCGATCGATC"}
seq_coll = SequenceCollection(seqs)
seq_coll.annotate_from_gff(DATA_DIR / "simple.gff", seq_ids="test_seq")
# the seq for which the seqid was provided is annotated
seq = seq_coll.get_seq("test_seq")
assert seq_coll.get_seq("test_seq").annotation_db is not None
# the annotation_db on the seq and the seq collection are the same object
assert seq_coll.get_seq("test_seq").annotation_db is seq_coll.annotation_db
got = list(seq_coll.get_seq("test_seq").get_features(allow_partial=True))
assert len(got) == 5
got = list(seq.get_features(biotype="CDS"))
assert len(got) == 2
got = list(seq.get_features(biotype="CpG"))
assert len(got) == 1
# the seq for which the seqid was NOT provided also has a reference to the same db
seq2 = seq_coll.get_seq("test_seq2")
assert seq2.annotation_db is not None
# querying on that sequence returns []
got = list(seq2.get_features(biotype="CDS"))
assert not got
def test_seq_coll_query(DATA_DIR):
"""obtain same results when querying from collection as from seq"""
seqs = {"test_seq": "ATCGATCGATCG", "test_seq2": "GATCGATCGATC"}
seq_coll = SequenceCollection(seqs)
seq_coll.annotate_from_gff(DATA_DIR / "simple.gff", seq_ids="test_seq")
seq = seq_coll.get_seq("test_seq")
# the seq for which the seqid was provided is annotated
assert seq.annotation_db is not None
# todo gah this test fails when allow_partial=False because start / stop
# not used by seqcoll method
expect = set(
(f.seqid, f.biotype, f.name, str(f.map))
for f in seq.get_features(allow_partial=True)
)
got = set(
(f.seqid, f.biotype, f.name, str(f.map))
for f in seq_coll.get_features(seqid="test_seq", allow_partial=True)
)
assert got == expect
# the annotation_db on the seq and the seq collection are the same object
assert seq.annotation_db is seq_coll.annotation_db
got = list(seq.get_features(biotype="CDS"))
assert len(got) == 2
got = list(seq.get_features(biotype="CpG"))
assert len(got) == 1
def test_gff_update_existing(gff_db, gff_small_db):
expect = gff_db.num_matches() + gff_small_db.num_matches()
gff_db.update(gff_small_db)
assert gff_db.num_matches() == expect
@pytest.mark.parametrize("seqids", (None, "23", ["23"]))
def test_gff_update_existing_specify_seqid(gff_db, gff_small_db, seqids):
expect = gff_db.num_matches() + gff_small_db.num_matches(
seqid=seqids[0] if isinstance(seqids, list) else seqids
)
gff_db.update(gff_small_db, seqids=seqids)
assert gff_db.num_matches() == expect
def test_gff_update_db_from_other_db_existing(gff_db, gff_small_db):
expect = gff_db.num_matches() + gff_small_db.num_matches()
gff_db._update_db_from_other_db(other_db=gff_small_db)
assert gff_db.num_matches() == expect
@pytest.mark.parametrize(
"seqids", ("test_seq", ["test_seq"], "test_seq2", ["test_seq2"], None)
)
def test_gff_update_db_from_other_db_existing_specify_seqid(
gff_db, gff_small_db, seqids
):
expect = gff_db.num_matches() + gff_small_db.num_matches(seqid=seqids)
gff_db._update_db_from_other_db(other_db=gff_small_db, seqids=seqids)
assert gff_db.num_matches() == expect
def test_gff_update_db_from_other_db_existing_none_seqid(gff_db, gff_small_db):
expect = gff_db.num_matches() + gff_small_db.num_matches()
gff_db._update_db_from_other_db(other_db=gff_small_db, seqids=None)
assert gff_db.num_matches() == expect
def test_relative_position_negative_feature(seq_db):
orig_feat_span = list(seq_db.get_features(name="Transcript:B0019.1"))[0].map
view = seq_db[5:]
view_feat_span = list(view.get_features(name="Transcript:B0019.1"))[0].map
assert orig_feat_span[0].start - 5 == view_feat_span[0].start
assert orig_feat_span[0].end - 5 == view_feat_span[0].end
def test_relative_position_positive_feature(anno_db):
seq = DNA.make_seq("AAAAGGGG", name="seq1")
seq.annotation_db = anno_db
anno_db.add_feature(
seqid=seq.name, biotype="exon", name="exon1", spans=[(2, 6)], strand="+"
)
orig_feat_span = list(seq.get_features(name="exon1"))[0].map
view = seq[2:]
view_feat_span = list(view.get_features(name="exon1"))[0].map
assert orig_feat_span[0].start - 2 == view_feat_span[0].start
assert orig_feat_span[0].end - 2 == view_feat_span[0].end
def test_deepcopy(gff_db):
import copy
new = copy.deepcopy(gff_db)
new.add_feature(
seqid="s1", biotype="exon", name="copied-exon", spans=[(2, 6)], strand="+"
)
assert new.num_matches() == gff_db.num_matches() + 1
assert len(list(new.get_features_matching(name="copied-exon"))) == 1
assert len(list(gff_db.get_features_matching(name="copied-exon"))) == 0
def test_pickling(gff_db):
import pickle
recon = pickle.loads(pickle.dumps(gff_db))
assert isinstance(recon, type(gff_db))
recon.add_feature(
seqid="s1", biotype="exon", name="copied-exon", spans=[(2, 6)], strand="+"
)
assert recon.num_matches() == gff_db.num_matches() + 1
@pytest.mark.parametrize("db_name", ("gff_db", "gb_db"))
def test_to_rich_dict(db_name, request):
db = request.getfixturevalue(db_name)
data = db.to_rich_dict()
assert data["init_args"]["source"] == ":memory:"
if db_name == "gb_db":
assert "seqid" in data["init_args"]
@pytest.mark.parametrize("db_name", ("gff_db", "gb_db"))
def test_deserialise(db_name, request):
db = request.getfixturevalue(db_name)
data = db.to_json()
got = deserialise.deserialise_object(data)
assert got is not db
assert isinstance(got, type(db))
assert got.num_matches() == db.num_matches()
def test_querying_attributes_gb(gb_db):
r = list(gb_db.get_records_matching(attributes="lysine biosynthesis"))
assert "lysine biosynthesis" in r[0]["attributes"]["note"][0]
def test_querying_attributes_gff(gff_db):
r = list(gff_db.get_records_matching(attributes="amx-2"))
assert "amx-2" in r[0]["attributes"]
def test_writing_attributes_gff(gff_db):
gff_db.add_feature(
biotype="gene",
seqid="blah",
name="cancer-gene",
attributes="description=cancer",
spans=[(0, 10)],
)
r = list(gff_db.get_records_matching(attributes="cancer"))[0]
assert r["name"] == "cancer-gene"
def test_equal():
db1 = BasicAnnotationDb()
db2 = BasicAnnotationDb()
db3 = BasicAnnotationDb()
assert db1 != db2
# we define equality by same class AND same db instance
db3._db = db2._db
assert db2 == db3
@pytest.mark.parametrize("other", (GenbankAnnotationDb, GffAnnotationDb))
def test_compatible_symmetric(other):
basic = BasicAnnotationDb()
other = other()
assert basic.compatible(basic)
assert basic.compatible(other)
assert other.compatible(other)
assert other.compatible(basic)
@pytest.mark.parametrize("other", (GenbankAnnotationDb, GffAnnotationDb))
def test_compatible_not_symmetric(other):
basic = BasicAnnotationDb()
other = other()
assert basic.compatible(basic, symmetric=False)
assert not basic.compatible(other, symmetric=False)
assert other.compatible(other, symmetric=False)
assert other.compatible(basic, symmetric=False)
def test_incompatible():
gff = GffAnnotationDb()
gb = GenbankAnnotationDb()
assert not gff.compatible(gb)
assert not gb.compatible(gff)
@pytest.mark.parametrize("wrong_type", ({}, BasicAnnotationDb().db))
def test_incompatible_invalid_type(wrong_type):
db = BasicAnnotationDb()
with pytest.raises(TypeError):
db.compatible(wrong_type)
def _custom_namer(data):
for key in ("gene", "locus_tag", "strain"):
if key in data:
return data[key]
return ["default name"]
def test_gb_namer(DATA_DIR):
path = DATA_DIR / "annotated_seq.gb"
got = list(MinimalGenbankParser(path.read_text().splitlines()))
data = got[0]["features"]
db = GenbankAnnotationDb(data=data, namer=_custom_namer, seqid=got[0]["locus"])
# there are 2 repeat regions, which we don't catch with our namer
assert db.num_matches(name="default name") == 2
def test_write(gb_db, tmp_path):
outpath = tmp_path / "ondisk.gbkdb"
gb_db.write(outpath)
got = GenbankAnnotationDb(source=outpath)
assert got.to_rich_dict()["tables"] == gb_db.to_rich_dict()["tables"]
assert isinstance(got, GenbankAnnotationDb)
def convert_to_old_np_format(data: bytes) -> bytes:
with io.BytesIO(data) as stream:
output = numpy.load(stream).tobytes()
return output
def convert_spans_column(db, table_name):
# Convert the database to the old numpy format.
conn = db.db
conn.create_function("convert_to_old_np_format", 1, convert_to_old_np_format)
cursor = conn.cursor()
cursor.execute(f"UPDATE {table_name} SET spans = convert_to_old_np_format(spans);")
conn.commit()
@pytest.mark.parametrize(
"db_name,cls", (("gb_db", GenbankAnnotationDb), ("gff_db", GffAnnotationDb))
)
def test_read_old_format(db_name, cls, tmp_path, request):
db = request.getfixturevalue(db_name)
path = tmp_path / f"old_format_{db_name}.db"
old_tables = db.to_rich_dict()["tables"]
table_name = db_name.split("_")[0]
convert_spans_column(db, table_name)
db.write(path)
new_db = cls(source=path)
with pytest.warns(UserWarning):
new_tables = new_db.to_rich_dict()["tables"]
assert new_tables == old_tables
@pytest.mark.parametrize(
"db_name,cls,backup",
(
("gb_db", GenbankAnnotationDb, True),
("gff_db", GffAnnotationDb, True),
("gb_db", GenbankAnnotationDb, False),
("gff_db", GffAnnotationDb, False),
),
)
def test_update_file_format(db_name, cls, backup, tmp_path, request):
db = request.getfixturevalue(db_name)
old_tables = db.to_rich_dict()["tables"]
path = tmp_path / f"old_format_{db_name}.db"
# Convert to old numpy format
table_name = db_name.split("_")[0]
convert_spans_column(db, table_name)
db.write(path)
with open(path, "rb") as f:
old_format_bytes = f.read()
# The file should be updated without warning
with warnings.catch_warnings():
warnings.simplefilter("error")
update_file_format(path, cls, backup=backup)
backup_path = tmp_path / f"old_format_{db_name}.db.bak"
if backup:
# Check the backup hasn't been modified
with open(backup_path, "rb") as f:
assert old_format_bytes == f.read()
else:
# A backup file should not exist
assert not backup_path.exists()
# The file should have been modified
with open(path, "rb") as f:
assert old_format_bytes != f.read()
# Reading the new file (when spans is loaded) should not produce warnings
with warnings.catch_warnings():
warnings.simplefilter("error")
new_db = cls(source=path)
new_tables = new_db.to_rich_dict()["tables"]
# The tables should remain the same
assert old_tables == new_tables
@pytest.mark.parametrize(
"db_name,cls",
(("gb_db", GenbankAnnotationDb), ("gff_db", GffAnnotationDb)),
)
def test_update_file_format_twice_fails(db_name, cls, tmp_path, request):
db = request.getfixturevalue(db_name)
path = tmp_path / f"old_format_{db_name}.db"
# Convert to old numpy format
table_name = db_name.split("_")[0]
convert_spans_column(db, table_name)
db.write(path)
update_file_format(path, cls, backup=True)
with pytest.raises(FileExistsError):
update_file_format(path, cls, backup=True)
@pytest.mark.parametrize(
"db_name,cls,backup",
(
("gb_db", GenbankAnnotationDb, True),
("gff_db", GffAnnotationDb, True),
("gb_db", GenbankAnnotationDb, False),
("gff_db", GffAnnotationDb, False),
),
)
def test_update_file_format_does_not_modify_correct_file(
db_name, cls, backup, tmp_path, request
):
db = request.getfixturevalue(db_name)
path = tmp_path / f"correct_format_{db_name}.db"
db.write(path)
with open(path, "rb") as f:
old_bytes = f.read()
# Updating the file format should not produce warnings
with warnings.catch_warnings():
warnings.simplefilter("error")
update_file_format(path, cls, backup=backup)
# The file should have remained the same
with open(path, "rb") as f:
assert old_bytes == f.read()
@pytest.mark.parametrize(
"db_name,cls,backup",
(
("gb_db", GenbankAnnotationDb, True),
("gff_db", GffAnnotationDb, True),
("gb_db", GenbankAnnotationDb, False),
("gff_db", GffAnnotationDb, False),
),
)
def test_update_file_format_fake_path(db_name, cls, backup, tmp_path):
path = tmp_path / f"non_existent_{db_name}.db"
with pytest.raises(OSError):
update_file_format(path, cls, backup=backup)
# The path should not have been created in the process
assert not path.exists()
if backup:
# The backup file path should also not exist
backup_path = tmp_path / f"non_existent_{db_name}.db.bak"
assert not backup_path.exists()
@pytest.fixture(scope="function")
def tmp_dir(tmp_path_factory):
return tmp_path_factory.mktemp("annotations")
def test_load_anns_with_write(DATA_DIR, tmp_dir):
inpath = DATA_DIR / "simple.gff"
outpath = tmp_dir / "simple.gffdb"
orig = load_annotations(path=inpath, write_path=outpath)
orig.db.close()
expect = load_annotations(path=inpath)
got = GffAnnotationDb(source=outpath)
assert len(got) == len(expect)
got_data = got.to_rich_dict()
expect_data = expect.to_rich_dict()
assert got_data["tables"] == expect_data["tables"]
def test_gff_end_renamed_to_stop(gff_db, tmp_path):
bad_col_path = tmp_path / "bad_col.gffdb"
correct_rich_dict = gff_db.to_rich_dict()
del correct_rich_dict["init_args"]
for table_name in gff_db.table_names:
# Convert in memory db stop column to the old end name
_rename_column_if_exists(gff_db.db, table_name, "stop", "end")
gff_db.write(tmp_path / bad_col_path)
# Test that end column is renamed to stop on construction
loaded_gff_db = GffAnnotationDb(source=bad_col_path)
new_rich_dict = loaded_gff_db.to_rich_dict()
del new_rich_dict["init_args"]
assert new_rich_dict == correct_rich_dict
def test_gb_end_renamed_to_stop(gb_db, tmp_path):
bad_col_path = tmp_path / "bad_col.gbdb"
correct_rich_dict = gb_db.to_rich_dict()
del correct_rich_dict["init_args"]
for table_name in gb_db.table_names:
# Convert in memory db stop column to the old end name
_rename_column_if_exists(gb_db.db, table_name, "stop", "end")
gb_db.write(tmp_path / bad_col_path)
# Test that end column is renamed to stop on construction
loaded_gb_db = GenbankAnnotationDb(source=bad_col_path)
new_rich_dict = loaded_gb_db.to_rich_dict()
del new_rich_dict["init_args"]
assert new_rich_dict == correct_rich_dict
def test_gbdb_get_children_fails_no_coords(gb_db):
with pytest.raises(ValueError):
_ = list(gb_db.get_feature_children(name="CNA00110"))
def test_gbdb_get_parent_fails_no_coords(gb_db):
with pytest.raises(ValueError):
_ = list(gb_db.get_feature_parent(name="CNA00110"))
def test_load_annotations_invalid_path():
with pytest.raises(IOError):
load_annotations(path="invalidfile.gff3")
@pytest.mark.parametrize("integer", (int, numpy.int64))
def test_subset_gff3_db(gff_db, integer):
subset = gff_db.subset(
seqid="I", start=integer(40), stop=integer(70), allow_partial=True
)
# manual inspection of the original GFF3 file indicates 7 records
# BUT the CDS records get merged into a single row
assert len(subset) == 6
def test_subset_empty_db(gff_db):
subset = gff_db.subset(seqid="X", start=40, stop=70, allow_partial=True)
# no records
assert not len(subset)
def test_subset_gff3_db_with_user(gff_db):
record = dict(
seqid="I", name="gene-01", biotype="gene", spans=[(23, 43)], strand="+"
)
gff_db.add_feature(**record)
subset = gff_db.subset(seqid="I", start=40, stop=70, allow_partial=True)
# manual inspection of the original GFF3 file indicates 7 records
# BUT the CDS records get merged into a single row
assert len(subset) == 7
def test_subset_gb_db(gb_db):
subset = gb_db.subset(biotype="gene")
# manual inspection of the original annotated gb file indicates 2 genes
assert len(subset) == 2
def test_subset_gff3_db_source(gff_db, tmp_dir):
outpath = tmp_dir / "subset.gff3db"
subset = gff_db.subset(
seqid="I", start=40, stop=70, allow_partial=True, source=outpath
)
subset.db.close()
# reload
subset = type(gff_db)(source=outpath)
# manual inspection of the original GFF3 file indicates 7 records
# BUT the CDS records get merged into a single row
assert len(subset) == 6
|