From afeb69dff3555c65b1f9d6add57b153ea78030ee Mon Sep 17 00:00:00 2001 From: Manuel Lera-Ramirez Date: Fri, 21 Jun 2024 13:03:20 +0100 Subject: [PATCH] add locations_overlap to utils --- src/pydna/utils.py | 25 +++++++++++++++++++++++++ tests/test_module_utils.py | 36 ++++++++++++++++++++++++++++++++++++ 2 files changed, 61 insertions(+) diff --git a/src/pydna/utils.py b/src/pydna/utils.py index 08078f87..a007e5a8 100644 --- a/src/pydna/utils.py +++ b/src/pydna/utils.py @@ -704,6 +704,31 @@ def location_boundaries(loc: _Union[_sl, _cl]): return loc.parts[0].start, loc.parts[-1].end +def locations_overlap(loc1: _Union[_sl, _cl], loc2: _Union[_sl, _cl], seq_len): + start1, end1 = location_boundaries(loc1) + start2, end2 = location_boundaries(loc2) + + boundaries1 = [(start1, end1)] + boundaries2 = [(start2, end2)] + + if start1 > end1: + boundaries1 = [ + [start1, end1 + seq_len], + [start1 - seq_len, end1], + ] + if start2 > end2: + boundaries2 = [ + [start2, end2 + seq_len], + [start2 - seq_len, end2], + ] + + for b1, b2 in _itertools.product(boundaries1, boundaries2): + if b1[0] < b2[1] and b1[1] > b2[0]: + return True + + return False + + if __name__ == "__main__": cached = _os.getenv("pydna_cached_funcs", "") _os.environ["pydna_cached_funcs"] = "" diff --git a/tests/test_module_utils.py b/tests/test_module_utils.py index 47f1c8e4..d733720d 100644 --- a/tests/test_module_utils.py +++ b/tests/test_module_utils.py @@ -475,5 +475,41 @@ def test_shift_location(): assert shift_location(shift_location(loc, 1, 6), -1, 6) == loc +def test_locations_overlap(): + from pydna.utils import locations_overlap, shift_location + from Bio.SeqFeature import SimpleLocation + + # exact ===== | + # greater ========= | + # inner == | + # right ===== | + # left ===== | + # main ===== | + # ----------------------------------------- + # 0123456789 + main_overlap = SimpleLocation(5, 10) + inner_overlap = SimpleLocation(6, 8) + right_overlap = SimpleLocation(6, 11) + left_overlap = SimpleLocation(4, 9) + exact_overlap = SimpleLocation(5, 10) + greater_overlap = SimpleLocation(3, 12) + no_overlap_left = SimpleLocation(0, 5) + no_overlap_right = SimpleLocation(11, 15) + + overlapping_locations = [inner_overlap, right_overlap, left_overlap, exact_overlap, greater_overlap] + non_overlapping_locations = [no_overlap_left, no_overlap_right] + + for shift in range(20): + main_shifted = shift_location(main_overlap, shift, 20) + for loc in overlapping_locations: + loc_shifted = shift_location(loc, shift, 20) + assert locations_overlap(main_shifted, loc_shifted, 20) + for loc in non_overlapping_locations: + loc_shifted = shift_location(loc, shift, 20) + assert not locations_overlap(main_shifted, loc_shifted, 20) + + + + if __name__ == "__main__": pytest.main([__file__, "-vv", "-s"])