benchmark_flocking.py 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. import timeit
  2. import random
  3. import argparse
  4. import os
  5. import sys
  6. import math
  7. # 1. Catch the argument BEFORE importing the models to avoid the import trap
  8. if "-M" in sys.argv or "--minimal" in sys.argv:
  9. os.environ["PYPDEVS_MINIMAL"] = "1"
  10. else:
  11. os.environ["PYPDEVS_MINIMAL"] = "0"
  12. from pypdevs.simulator import Simulator
  13. from pypdevs.minimal import Simulator as Minimal
  14. from Flocking import Flocking
  15. def calculate_polarisation(space_state):
  16. """
  17. Calculates the Order Parameter (Polarisation) of the flock.
  18. 1.0 = Perfect alignment (all birds flying in the exact same direction).
  19. 0.0 = Complete chaos (birds flying randomly, vectors cancel out).
  20. """
  21. sum_vx, sum_vy = 0.0, 0.0
  22. N = len(space_state.positions)
  23. if N == 0: return 0.0
  24. for pos, vel in space_state.positions.values():
  25. sum_vx += vel[0]
  26. sum_vy += vel[1]
  27. return math.sqrt((sum_vx / N) ** 2 + (sum_vy / N) ** 2)
  28. def runthemodel(seed, num_birds, extent_x, extent_y, visual_distance, minimal=False):
  29. """
  30. Wrapper function to initialize and run the Flocking simulation for benchmarking.
  31. """
  32. model = Flocking(
  33. seed=seed,
  34. extent=(extent_x, extent_y),
  35. num_birds=num_birds,
  36. visual_distance=float(visual_distance)
  37. )
  38. if minimal:
  39. sim = Minimal(model)
  40. else:
  41. sim = Simulator(model)
  42. sim.setTerminationTime(100 + 1e-3)
  43. # sim.setVerbose(None)
  44. # import cProfile
  45. # import pstats
  46. # import io
  47. # start = timeit.default_timer()
  48. # pr = cProfile.Profile()
  49. # pr.enable()
  50. sim.simulate()
  51. # pr.disable()
  52. # s = io.StringIO()
  53. # sortby = pstats.SortKey.CUMULATIVE
  54. # ps = pstats.Stats(pr, stream=s).sort_stats(sortby)
  55. # ps.print_stats()
  56. # print(s.getvalue())
  57. #
  58. # print("run time:", timeit.default_timer() - start)
  59. # final_polarization = calculate_polarisation(model.space.state)
  60. # print("Final polarisation:", final_polarization)
  61. def verify_flocking():
  62. model = Flocking(seed=42, extent=(100, 100), num_birds=200, visual_distance=5.0)
  63. sim = Minimal(model)
  64. target_steps = [1, 5, 25, 50, 100, 250, 500]
  65. for target in target_steps:
  66. sim.setTerminationTime(target + 1e-3)
  67. sim.simulate()
  68. pol = calculate_polarisation(model.space.state)
  69. print(f"Polarisation after {target} steps: {round(pol, 6)}")
  70. setup = ("from Flocking import Flocking\n"
  71. "from benchmark_flocking import runthemodel")
  72. n_run = 100
  73. if __name__ == '__main__':
  74. parser = argparse.ArgumentParser()
  75. parser.add_argument("-M", "--minimal", action="store_true")
  76. args = parser.parse_args()
  77. framework = "PyPDEVS"
  78. if args.minimal:
  79. os.environ["PYPDEVS_MINIMAL"] = "1"
  80. framework = "PyPDEVS-Minimal"
  81. print(f"Running {framework} Flocking with 200 birds, with a visual distance of 5 and in a 100x100 space")
  82. tt = timeit.Timer(f'runthemodel(42, 200, 100, 100, 5, {args.minimal})', setup=setup)
  83. a = tt.repeat(n_run, 1)
  84. median_time = sorted(a)[n_run // 2 + n_run % 2]
  85. print(f"{framework} Flocking-small Median Time for {n_run} runs (ms):", median_time * 1e3)
  86. print(f"Running PyPDEVS {framework} with 400 birds, with a visual distance of 15 and in a 150x150 space")
  87. tt = timeit.Timer(f'runthemodel(42, 400, 150, 150, 15, {args.minimal})', setup=setup)
  88. a = tt.repeat(n_run, 1)
  89. median_time = sorted(a)[n_run // 2 + n_run % 2]
  90. print(f"{framework} Flocking-large Median Time for {n_run} runs (ms):", median_time * 1e3)