benchmark_r_patch_memory.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. """Benchmarking of r.patch memory parameter
  2. @author Aaron Saw Min Sern
  3. @author Anna Petrasova
  4. """
  5. from grass.exceptions import CalledModuleError
  6. from grass.pygrass.modules import Module
  7. from subprocess import DEVNULL
  8. import grass.benchmark as bm
  9. def main():
  10. results = []
  11. references = ["r_patch_reference_map_{}".format(i) for i in range(4)]
  12. generate_map(rows=5000, cols=5000, fname=references)
  13. # Users can add more or modify existing reference maps
  14. benchmark(0, "r.patch_0MB", references, results)
  15. benchmark(5, "r.patch_5MB", references, results)
  16. benchmark(10, "r.patch_10MB", references, results)
  17. benchmark(100, "r.patch_100MB", references, results)
  18. benchmark(300, "r.patch_300MB", references, results)
  19. for r in references:
  20. Module("g.remove", quiet=True, flags="f", type="raster", name=r)
  21. bm.nprocs_plot(results, filename="rpatch_benchmark_memory.svg")
  22. def benchmark(memory, label, references, results):
  23. output = "benchmark_r_patch"
  24. module = Module(
  25. "r.patch",
  26. input=references,
  27. output=output,
  28. memory=memory,
  29. run_=False,
  30. stdout_=DEVNULL,
  31. overwrite=True,
  32. )
  33. results.append(bm.benchmark_nprocs(module, label=label, max_nprocs=24, repeat=10))
  34. Module("g.remove", quiet=True, flags="f", type="raster", name=output)
  35. def generate_map(rows, cols, fname):
  36. temp = "r_patch_reference_tmp"
  37. Module("g.region", flags="p", s=0, n=rows, w=0, e=cols, res=1)
  38. # Generate using r.random.surface if r.surf.fractal fails
  39. try:
  40. print("Generating reference map using r.surf.fractal...")
  41. for r in fname:
  42. Module(
  43. "r.surf.fractal",
  44. output=temp,
  45. overwrite=True,
  46. )
  47. # Make approximate half of the reference map to be null
  48. Module(
  49. "r.mapcalc",
  50. expression=f"{r} = if({temp}, {temp}, 0, null())",
  51. overwrite=True,
  52. )
  53. except CalledModuleError:
  54. print("r.surf.fractal fails, using r.random.surface instead...")
  55. for r in fname:
  56. Module(
  57. "r.random.surface",
  58. maximum=255,
  59. output=temp,
  60. overwrite=True,
  61. )
  62. Module(
  63. "r.mapcalc",
  64. expression=f"{r} = if({temp} - 128, {temp}, 0, null())",
  65. overwrite=True,
  66. )
  67. Module("g.remove", quiet=True, flags="f", type="raster", name=temp)
  68. if __name__ == "__main__":
  69. main()