Skip to content

Commit

Permalink
removed unused methods
Browse files Browse the repository at this point in the history
  • Loading branch information
CommanderStorm committed Aug 9, 2024
1 parent 660dd07 commit b59ae88
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 134 deletions.
76 changes: 12 additions & 64 deletions data/processors/maps/roomfinder.py
Original file line number Diff line number Diff line change
Expand Up @@ -123,57 +123,6 @@ def _sort_key(_map: roomfinder.Map) -> tuple[int, float]:
return sorted(available_maps, key=_sort_key)


def _merge_str(s_1: str, s_2: str) -> str:
"""
Merge two strings. The Result is of the format common_prefix s1/s2 common_suffix.
Example: "Thierschbau 5. OG" and "Thierschbau 6. OG" -> "Thierschbau 5/6. OG"
"""
if s_1.strip() == s_2.strip():
return s_1.strip()
prefix = os.path.commonprefix((s_1, s_2))
suffix = os.path.commonprefix((s_1[::-1], s_2[::-1]))[::-1]
s_1 = s_1.removeprefix(prefix).removesuffix(suffix)
s_2 = s_2.removeprefix(prefix).removesuffix(suffix)
if s_1 and s_2:
return f"{prefix}{s_1}/{s_2}{suffix}"
# special case: one string is a pre/postfix of the other
common = s_1 or s_2
while common.endswith(" "):
common = common.removesuffix(" ")
suffix = f" {suffix}"
while common.startswith(" "):
common = common.removeprefix(" ")
prefix = f"{prefix} "
return f"{prefix}({common.strip()}){suffix}"


MergeMap = TypeVar("MergeMap", bound=dict[str, Any] | type[PydanticConfiguration])


def _merge_maps(map1: MergeMap, map2: MergeMap) -> MergeMap:
"""Merge two Maps into one merged map"""
result_map = {}
if isinstance(map1, PydanticConfiguration):
return map1.__class__.model_validate(_merge_maps(map1.model_dump(), map2.model_dump()))

for key in map1:
if key == "id":
result_map["id"] = map1["id"]
elif isinstance(map1[key], abc.Mapping):
result_map[key] = _merge_maps(map1[key], map2[key])
elif isinstance(map1[key], str):
result_map[key] = _merge_str(map1[key], map2[key])
elif isinstance(map1[key], int):
result_map[key] = int((map1[key] + map2[key]) / 2)
elif isinstance(map1[key], float):
result_map[key] = (map1[key] + map2[key]) / 2
else:
value = map1[key]
raise NotImplementedError(f"{key=} ({value=}, {type(value)=}) without a merge-operation defined")
return result_map


def build_roomfinder_maps(data: dict[str, dict[str, Any]]) -> None:
"""Generate the map information for the Roomfinder maps."""
map_assignment_data = _generate_assignment_data()
Expand All @@ -187,6 +136,7 @@ def build_roomfinder_maps(data: dict[str, dict[str, Any]]) -> None:
entry_map["y"] = y_on_map

# set source and filepath so that they are available for all maps
# custom maps have the source already set
entry_map.setdefault("source", "Roomfinder")
entry_map.setdefault("file", f"{entry_map['id']}.webp")

Expand Down Expand Up @@ -262,16 +212,14 @@ def remove_non_covering_maps(data: dict[str, dict[str, Any]]) -> None:
for _id, entry in data.items():
if entry["type"] == "root":
continue
if "roomfinder" not in entry["maps"]:
continue
rf_maps = entry["maps"]["roomfinder"]
to_be_deleted = [
_map
for _map in rf_maps["available"]
if _entry_is_not_on_map(entry["coords"], _map["id"], _map["width"], _map["height"], map_assignment_data)
]
for _map in to_be_deleted:
rf_maps["available"].remove(_map)
if not rf_maps["available"]:
# no availible roomfinder maps don't carry any meaning and are deleted
del entry["maps"]["roomfinder"]
if rf_maps := entry["maps"].get("roomfinder"):
to_be_deleted = [
_map
for _map in rf_maps["available"]
if _entry_is_not_on_map(entry["coords"], _map["id"], _map["width"], _map["height"], map_assignment_data)
]
for _map in to_be_deleted:
rf_maps["available"].remove(_map)
if not rf_maps["available"]:
# no available roomfinder maps don't carry any meaning and are deleted
del entry["maps"]["roomfinder"]
71 changes: 1 addition & 70 deletions data/processors/maps/test_roomfinder.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
import pytest
from external.models import roomfinder
from processors.maps.models import Coordinate
from processors.maps.roomfinder import _calc_xy_of_coords_on_map, _merge_maps, _merge_str
from processors.maps.roomfinder import _calc_xy_of_coords_on_map


def default_map(rotate: int = 0) -> roomfinder.Map:
Expand All @@ -27,75 +27,6 @@ def default_map(rotate: int = 0) -> roomfinder.Map:
)


@pytest.mark.parametrize("s_1", ["abc", " abc", "abc"])
@pytest.mark.parametrize("s_2", ["abc", " abc", "abc"])
def test_merge_identical(s_1: str, s_2: str) -> None:
"""Test if identical inputs are stripped of whitespace"""
assert _merge_str(s_1, s_2) == "abc"


def test_merge_strings_happy_path() -> None:
"""Test if the merging of strings works as expected in the regular case"""
assert _merge_str("Thierschbau 5. OG", "Thierschbau 6. OG") == "Thierschbau 5/6. OG"
assert _merge_str("Pre Something Suf", "Pre Different Suf") == "Pre Something/Different Suf"
assert _merge_str("Hello World", "Hello Universe") == "Hello World/Universe"


def test_merge_strings_subset() -> None:
"""Test if the merging of strings works as expected when one string is a subset of the other"""
assert _merge_str("POSTFIX", "Another POSTFIX") == "(Another) POSTFIX"
assert _merge_str("Another POSTFIX", "POSTFIX") == "(Another) POSTFIX"
assert _merge_str("PREFIX", "PREFIX Another") == "PREFIX (Another)"
assert _merge_str("PREFIX Another", "PREFIX") == "PREFIX (Another)"


def test_merge_maps() -> None:
"""Test if the merging of maps works as expected"""
map1 = {
"id": 1,
"name": "prefix John posfix",
"age": 30,
"favourite_float": 3.0,
"location": {
"city": "New York",
"zip": 0,
},
}

map2 = {
"id": 2,
"name": "prefix Tod posfix",
"age": 25,
"favourite_float": 5.0,
"location": {
"city": "San Francisco",
"zip": 100,
},
}

expected_map = {
"id": 1, # id should be taken from map1
"name": "prefix John/Tod posfix", # merged string
"age": 27, # average
"favourite_float": 4.0, # average
"location": {
"city": "New York/San Francisco", # merged string
"zip": 50, # average
},
}

assert expected_map == _merge_maps(map1, map2)


def test_merge_maps_unequal_keys() -> None:
"""Test if the merging of maps works as expected when the keyspace is not equal"""
with pytest.raises(KeyError):
assert _merge_maps({"a": 1}, {"b": 2}) # different key in b
with pytest.raises(KeyError):
_merge_maps({"a": 1}, {}) # no key in b
assert _merge_maps({}, {"b": 2}) == {} # no key in a => empty map


@pytest.mark.parametrize("rotation", range(360))
def test_coords_to_xy_center_rotation(rotation: int) -> None:
"""Test if xy coordinates are assigned correctly"""
Expand Down

0 comments on commit b59ae88

Please sign in to comment.