test_navigation_optimization.py 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  1. """Route equivalence and synthetic many-NPC chase-stage benchmarks."""
  2. import ast
  3. import argparse
  4. import json
  5. from pathlib import Path
  6. import random
  7. import statistics
  8. import sys
  9. import time
  10. from types import SimpleNamespace as NS
  11. import unittest
  12. ROOT = Path(__file__).resolve().parents[1]
  13. sys.path.insert(0, str(ROOT))
  14. import numpy as np
  15. from client_local.algo.navigation import invalidate_navigation
  16. def load_search(path, scene):
  17. tree = ast.parse(path.read_text(encoding='utf-8-sig'))
  18. tree.body = [n for n in tree.body if not (isinstance(n, ast.ImportFrom)
  19. and n.module == 'client_local.level')]
  20. scope = {'level': NS(current_level=scene)}
  21. exec(compile(tree, str(path), 'exec'), scope)
  22. return NS(**scope)
  23. def scene(width=12, height=10):
  24. value = NS(map_x=width, map_y=height,
  25. block=np.zeros((2, width + 1, height + 1), dtype=np.int64), bombs=set(),
  26. recal_npc_paths=True, me=NS(x=width - 2, y=height // 2),
  27. district_square_grid={'x1': 0, 'y1': 0, 'x2': width - 1, 'y2': height - 1})
  28. value.get_bomb_instance = lambda x, y: [1] if (x, y) in value.bombs else []
  29. return value
  30. def searches(value):
  31. return (load_search(ROOT / 'tests/navigation_reference.py', value),
  32. load_search(ROOT / 'client_local/algo/aStar.py', value))
  33. class NavigationTests(unittest.TestCase):
  34. def test_all_small_wall_and_bomb_combinations(self):
  35. cl = scene(2, 2)
  36. old, new = searches(cl)
  37. edges = [(0, 0, 1), (0, 1, 1), (1, 1, 0), (1, 1, 1)]
  38. points = [(x, y) for x in range(2) for y in range(2)]
  39. for wall_bits in range(16):
  40. for bit, (plane, x, y) in enumerate(edges):
  41. cl.block[plane][x][y] = (wall_bits >> bit) & 1
  42. invalidate_navigation(cl)
  43. for bomb_bits in range(16):
  44. cl.bombs = {point for bit, point in enumerate(points) if bomb_bits & (1 << bit)}
  45. for start in points:
  46. for target in points:
  47. self.assertEqual(old.cal_path(start, target, (0, 0), (1, 1)),
  48. new.cal_path(start, target, (0, 0), (1, 1)))
  49. def test_random_routes_match_exactly(self):
  50. for seed in range(80):
  51. rng = random.Random(seed)
  52. cl = scene(9, 7)
  53. cl.block[:] = np.array([rng.choice((0, 0, 0, 1, 2, -1))
  54. for _ in range(cl.block.size)]).reshape(cl.block.shape)
  55. cl.bombs = {(rng.randrange(9), rng.randrange(7)) for _ in range(10)}
  56. old, new = searches(cl)
  57. for _ in range(15):
  58. start, target = [(rng.randrange(9), rng.randrange(7)) for _ in range(2)]
  59. lower = rng.randrange(9), rng.randrange(7)
  60. upper = rng.randrange(lower[0], 9), rng.randrange(lower[1], 7)
  61. with self.subTest(seed=seed, start=start, target=target):
  62. self.assertEqual(old.cal_path(start, target, lower, upper),
  63. new.cal_path(start, target, lower, upper))
  64. def test_obstacle_hooks_invalidate_connectivity(self):
  65. cl = scene(5, 3)
  66. old, new = searches(cl)
  67. args = (0, 1), (4, 1), (0, 0), (4, 2)
  68. self.assertTrue(new.cal_path(*args))
  69. tree = ast.parse((ROOT / 'client_local/sprite/obstacle_instance.py').read_text(encoding='utf-8-sig'))
  70. cls = next(n for n in tree.body if isinstance(n, ast.ClassDef) and n.name == 'ObstacleInstance')
  71. obstacle = NS(x=2, y=0, obstacle={'BLOCK': [[[0] * 4 for _ in range(2)], [[1] * 3]] ,
  72. 'BLOCK_FLAME': [[[0] * 4 for _ in range(2)], [[0] * 3]]})
  73. cl.block_flame = cl.block.copy()
  74. for method_name, expected in (('setup', False), ('uninstall', True)):
  75. method = next(n for n in cls.body if isinstance(n, ast.FunctionDef) and n.name == method_name)
  76. nodes = []
  77. for node in method.body:
  78. dumped = ast.dump(node)
  79. if ('navigation_changed' in dumped or 'invalidate_navigation' in dumped
  80. or isinstance(node, ast.For) and 'block_flame' in dumped):
  81. nodes.append(node)
  82. exec(compile(ast.Module(body=nodes, type_ignores=[]), '<obstacle-hooks>', 'exec'),
  83. {'self': obstacle, 'level': NS(current_level=cl)})
  84. self.assertEqual(bool(new.cal_path(*args)), expected)
  85. self.assertEqual(new.cal_path(*args), old.cal_path(*args))
  86. self.assertTrue(cl.recal_npc_paths)
  87. self.assertEqual(cl._npc_navigation.builds, 3)
  88. def test_bomb_move_throw_remove_and_map_reload_have_no_stale_answers(self):
  89. cl = scene(7, 1)
  90. old, new = searches(cl)
  91. args = (0, 0), (6, 0), (0, 0), (6, 0)
  92. for bombs in ({(3, 0)}, set(), {(4, 0)}, set(), {(0, 0)}, set()):
  93. cl.bombs = bombs
  94. self.assertEqual(old.cal_path(*args), new.cal_path(*args))
  95. self.assertEqual(cl._npc_navigation.builds, 1)
  96. cl.block = cl.block.copy()
  97. cl.block[1][3][0] = 1
  98. self.assertEqual(old.cal_path(*args), new.cal_path(*args))
  99. self.assertEqual(cl._npc_navigation.builds, 2)
  100. def test_dynamic_wall_and_bomb_mutations(self):
  101. cl = scene(9, 7)
  102. old, new = searches(cl)
  103. rng = random.Random(3007)
  104. for _ in range(1200):
  105. plane, x, y = rng.randrange(2), rng.randrange(9), rng.randrange(7)
  106. cl.block[plane][x][y] = rng.choice((0, 1, 2, -1))
  107. invalidate_navigation(cl)
  108. cl.bombs = {(rng.randrange(9), rng.randrange(7)) for _ in range(4)}
  109. args = (rng.randrange(9), rng.randrange(7)), (rng.randrange(9), rng.randrange(7)), (0, 0), (8, 6)
  110. self.assertEqual(old.cal_path(*args), new.cal_path(*args))
  111. def test_ghosts_same_point_and_boundary_queries_match(self):
  112. cl = scene(7, 6)
  113. cl.block[1][3][:6] = 1
  114. old, new = searches(cl)
  115. for ghost in (True, False):
  116. for start, target, lower, upper in (
  117. ((0, 0), (6, 5), (0, 0), (6, 5)),
  118. ((2, 2), (2, 2), (0, 0), (6, 5)),
  119. ((0, 0), (1, 0), (-1, 0), (6, 5))):
  120. self.assertEqual(old.cal_path(start, target, lower, upper, ghost),
  121. new.cal_path(start, target, lower, upper, ghost))
  122. def chase_function(search, cl):
  123. tree = ast.parse((ROOT / 'client_local/sprite/npc.py').read_text(encoding='utf-8-sig'))
  124. cls = next(n for n in tree.body if isinstance(n, ast.ClassDef) and n.name == 'Npc')
  125. method = next(n for n in cls.body if isinstance(n, ast.FunctionDef) and n.name == 'chase_hero')
  126. scope = {'aStar': search, 'level': NS(current_level=cl)}
  127. exec(compile(ast.Module(body=[method], type_ignores=[]), '<real-chase>', 'exec'), scope)
  128. return scope['chase_hero']
  129. def benchmark(output):
  130. results = []
  131. for kind, count in [('open', 80), ('open', 240), ('wall', 80), ('wall', 240),
  132. ('bomb', 160), ('dynamic-wall', 160), ('mixed', 160)]:
  133. cl = scene(40, 30)
  134. if kind in ('wall', 'mixed', 'dynamic-wall'):
  135. cl.block[1][20][:30] = 1
  136. if kind == 'bomb':
  137. cl.bombs = {(20, y) for y in range(30)}
  138. old, new = searches(cl)
  139. rng = random.Random(441)
  140. units = []
  141. for i in range(count):
  142. x = rng.randrange(1, 19) if kind != 'mixed' or i % 2 else rng.randrange(21, 38)
  143. npc = NS(x=x, y=rng.randrange(1, 29), resentful=True, mocking=False, friendly=False,
  144. imitating=False, speed=1, original_speed=1, free_chasing=False,
  145. chasing_monster=False, is_ghost=False, chase_path={}, motion=None)
  146. npc.set_motion = lambda motion=None, npc=npc: setattr(npc, 'motion', motion)
  147. units.append(npc)
  148. samples = {'before': [], 'after': []}
  149. cold = {}
  150. snapshots = {}
  151. for cycle in range(3):
  152. for name, search in ((('before', old), ('after', new)) if cycle % 2 == 0 else
  153. (('after', new), ('before', old))):
  154. cl._npc_navigation = None
  155. chase = chase_function(search, cl)
  156. states = []
  157. for frame in range(5):
  158. if kind == 'dynamic-wall':
  159. cl.block[1][20][15] = frame % 2
  160. invalidate_navigation(cl)
  161. started = time.perf_counter()
  162. for npc in units:
  163. chase(npc)
  164. elapsed = (time.perf_counter() - started) * 1000
  165. if frame == 0:
  166. cold.setdefault(name, []).append(elapsed)
  167. samples[name].append(elapsed)
  168. states.append([(npc.motion, npc.chase_path.copy()) for npc in units])
  169. if cycle == 0:
  170. snapshots[name] = states
  171. assert snapshots['before'] == snapshots['after'], (kind, count)
  172. before, after = (statistics.median(samples[name]) for name in ('before', 'after'))
  173. row = dict(scene=kind, npcs=count, before_ms=round(before, 3), after_ms=round(after, 3),
  174. speedup=round(before / after, 2), cold_before_ms=round(statistics.median(cold['before']), 3),
  175. cold_after_ms=round(statistics.median(cold['after']), 3), identical=True)
  176. results.append(row)
  177. print(json.dumps(row), flush=True)
  178. Path(output).parent.mkdir(parents=True, exist_ok=True)
  179. Path(output).write_text(json.dumps(results, indent=2), encoding='utf-8')
  180. if __name__ == '__main__':
  181. import sys
  182. if '--benchmark' in sys.argv:
  183. parser = argparse.ArgumentParser()
  184. parser.add_argument('--benchmark', required=True)
  185. benchmark(parser.parse_args().benchmark)
  186. else:
  187. unittest.main()