benchmark.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  1. # -*- coding: utf-8 -*-
  2. """
  3. Created on Sat Jun 16 20:24:56 2012
  4. @author: soeren
  5. """
  6. from __future__ import (nested_scopes, generators, division, absolute_import,
  7. with_statement, print_function, unicode_literals)
  8. import optparse
  9. #import numpy as np
  10. import time
  11. import collections
  12. import copy
  13. import cProfile
  14. import sys, os
  15. from jinja2 import Template
  16. sys.path.append(os.getcwd())
  17. sys.path.append("%s/.."%(os.getcwd()))
  18. import grass.lib.gis as libgis
  19. import grass.lib.raster as libraster
  20. import grass.script as core
  21. import grass.pygrass
  22. import ctypes
  23. def test__RasterSegment_value_access__if():
  24. test_a = pygrass.RasterSegment(name="test_a")
  25. test_a.open(mode="r")
  26. test_c = pygrass.RasterSegment(name="test_c")
  27. test_c.open(mode="w", mtype="CELL", overwrite=True)
  28. buff_a = pygrass.Buffer(test_a.cols, test_a.mtype)
  29. for row in range(test_a.rows):
  30. test_a.get_row(row, buff_a)
  31. for col in range(test_a.cols):
  32. test_c.put(row, col, buff_a[col] > 50)
  33. test_a.close()
  34. test_c.close()
  35. def test__RasterSegment_value_access__add():
  36. test_a = pygrass.RasterSegment(name="test_a")
  37. test_a.open(mode="r")
  38. test_b = pygrass.RasterSegment(name="test_b")
  39. test_b.open(mode="r")
  40. test_c = pygrass.RasterSegment(name="test_c")
  41. test_c.open(mode="w", mtype="DCELL", overwrite=True)
  42. buff_a = pygrass.Buffer(test_a.cols, test_a.mtype)
  43. buff_b = pygrass.Buffer(test_b.cols, test_b.mtype)
  44. for row in range(test_a.rows):
  45. test_a.get_row(row, buff_a)
  46. test_b.get_row(row,buff_b)
  47. for col in range(test_a.cols):
  48. test_c.put(row, col, buff_a[col] + buff_b[col])
  49. test_a.close()
  50. test_b.close()
  51. test_c.close()
  52. def test__RasterSegment_row_access__if():
  53. test_a = pygrass.RasterSegment(name="test_a")
  54. test_a.open(mode="r")
  55. test_c = pygrass.RasterSegment(name="test_c")
  56. test_c.open(mode="w", mtype="CELL", overwrite=True)
  57. buff_a = pygrass.Buffer(test_a.cols, test_a.mtype)
  58. for row in range(test_a.rows):
  59. test_a.get_row(row, buff_a)
  60. test_c.put_row(row, buff_a > 50)
  61. test_a.close()
  62. test_c.close()
  63. def test__RasterSegment_row_access__add():
  64. test_a = pygrass.RasterSegment(name="test_a")
  65. test_a.open(mode="r")
  66. test_b = pygrass.RasterSegment(name="test_b")
  67. test_b.open(mode="r")
  68. test_c = pygrass.RasterSegment(name="test_c")
  69. test_c.open(mode="w", mtype="DCELL", overwrite=True)
  70. buff_a = pygrass.Buffer(test_a.cols, test_a.mtype)
  71. buff_b = pygrass.Buffer(test_b.cols, test_b.mtype)
  72. for row in range(test_a.rows):
  73. test_a.get_row(row, buff_a)
  74. test_b.get_row(row,buff_b)
  75. test_c.put_row(row, buff_a + buff_b)
  76. test_a.close()
  77. test_b.close()
  78. test_c.close()
  79. def test__RasterRow_value_access__add():
  80. test_a = pygrass.RasterRow(name="test_a")
  81. test_a.open(mode="r")
  82. test_b = pygrass.RasterRow(name="test_b")
  83. test_b.open(mode="r")
  84. test_c = pygrass.RasterRow(name="test_c")
  85. test_c.open(mode="w", mtype="FCELL", overwrite=True)
  86. buff_a = pygrass.Buffer(test_a.cols, test_a.mtype)
  87. buff_b = pygrass.Buffer(test_b.cols, test_b.mtype)
  88. buff_c = pygrass.Buffer(test_b.cols, test_b.mtype)
  89. for row in range(test_a.rows):
  90. test_a.get_row(row, buff_a)
  91. test_b.get_row(row,buff_b)
  92. for col in range(test_a.cols):
  93. buff_c[col] = buff_a[col] + buff_b[col]
  94. test_c.put_row(buff_c)
  95. test_a.close()
  96. test_b.close()
  97. test_c.close()
  98. def test__RasterRow_value_access__if():
  99. test_a = pygrass.RasterRow(name="test_a")
  100. test_a.open(mode="r")
  101. test_c = pygrass.RasterRow(name="test_c")
  102. test_c.open(mode="w", mtype="CELL", overwrite=True)
  103. buff_a = pygrass.Buffer(test_a.cols, test_a.mtype)
  104. buff_c = pygrass.Buffer(test_a.cols, test_a.mtype)
  105. for row in range(test_a.rows):
  106. test_a.get_row(row, buff_a)
  107. for col in range(test_a.cols):
  108. buff_c[col] = buff_a[col] > 50
  109. test_c.put_row(buff_c)
  110. test_a.close()
  111. test_c.close()
  112. def test__RasterRowIO_row_access__add():
  113. test_a = pygrass.RasterRowIO(name="test_a")
  114. test_a.open(mode="r")
  115. test_b = pygrass.RasterRowIO(name="test_b")
  116. test_b.open(mode="r")
  117. test_c = pygrass.RasterRowIO(name="test_c")
  118. test_c.open(mode="w", mtype="FCELL", overwrite=True)
  119. buff_a = pygrass.Buffer(test_a.cols, test_a.mtype)
  120. buff_b = pygrass.Buffer(test_b.cols, test_b.mtype)
  121. for row in range(test_a.rows):
  122. test_a.get_row(row, buff_a)
  123. test_b.get_row(row,buff_b)
  124. test_c.put_row(buff_a + buff_b)
  125. test_a.close()
  126. test_b.close()
  127. test_c.close()
  128. def test__RasterRowIO_row_access__if():
  129. test_a = pygrass.RasterRowIO(name="test_a")
  130. test_a.open(mode="r")
  131. test_c = pygrass.RasterRowIO(name="test_c")
  132. test_c.open(mode="w", mtype="CELL", overwrite=True)
  133. buff_a = pygrass.Buffer(test_a.cols, test_a.mtype)
  134. for row in range(test_a.rows):
  135. test_a.get_row(row, buff_a)
  136. test_c.put_row(buff_a > 50)
  137. test_a.close()
  138. test_c.close()
  139. def test__RasterRow_row_access__add():
  140. test_a = pygrass.RasterRow(name="test_a")
  141. test_a.open(mode="r")
  142. test_b = pygrass.RasterRow(name="test_b")
  143. test_b.open(mode="r")
  144. test_c = pygrass.RasterRow(name="test_c")
  145. test_c.open(mode="w", mtype="FCELL", overwrite=True)
  146. buff_a = pygrass.Buffer(test_a.cols, test_a.mtype)
  147. buff_b = pygrass.Buffer(test_b.cols, test_b.mtype)
  148. for row in range(test_a.rows):
  149. test_a.get_row(row, buff_a)
  150. test_b.get_row(row,buff_b)
  151. test_c.put_row(buff_a + buff_b)
  152. test_a.close()
  153. test_b.close()
  154. test_c.close()
  155. def test__RasterRow_row_access__if():
  156. test_a = pygrass.RasterRow(name="test_a")
  157. test_a.open(mode="r")
  158. test_c = pygrass.RasterRow(name="test_c")
  159. test_c.open(mode="w", mtype="CELL", overwrite=True)
  160. buff_a = pygrass.Buffer(test_a.cols, test_a.mtype)
  161. for row in range(test_a.rows):
  162. test_a.get_row(row, buff_a)
  163. test_c.put_row(buff_a > 50)
  164. test_a.close()
  165. test_c.close()
  166. def test__mapcalc__add():
  167. core.mapcalc("test_c = test_a + test_b", quite=True, overwrite=True)
  168. def test__mapcalc__if():
  169. core.mapcalc("test_c = if(test_a > 50, 1, 0)", quite=True, overwrite=True)
  170. def mytimer(func, runs=1):
  171. times = []
  172. t = 0.0
  173. for _ in range(runs):
  174. start = time.time()
  175. func()
  176. end = time.time()
  177. times.append(end - start)
  178. t = t + end - start
  179. return t/runs, times
  180. def run_benchmark(resolution_list, runs, testdict, profile):
  181. regions = []
  182. for resolution in resolution_list:
  183. core.use_temp_region()
  184. core.run_command('g.region', e=50, w=-50, n=50, s=-50, res=resolution, flags='p')
  185. # Adjust the computational region for this process
  186. region = libgis.Cell_head()
  187. libraster.Rast_get_window(ctypes.byref(region))
  188. region.e = 50
  189. region.w = -50
  190. region.n = 50
  191. region.s = -50
  192. region.ew_res = resolution
  193. region.ns_res = resolution
  194. libgis.G_adjust_Cell_head(ctypes.byref(region), 0, 0)
  195. libraster.Rast_set_window(ctypes.byref(region))
  196. libgis.G_set_window(ctypes.byref(region))
  197. # Create two raster maps with random numbers
  198. core.mapcalc("test_a = rand(0, 100)", quite=True, overwrite=True)
  199. core.mapcalc("test_b = rand(0.0, 1.0)", quite=True, overwrite=True)
  200. result = collections.OrderedDict()
  201. result['res'] = resolution
  202. result['cols'] = region.cols
  203. result['rows'] = region.rows
  204. result['cells'] = region.rows * region.cols
  205. result['results'] = copy.deepcopy(testdict)
  206. for execmode, operation in result['results'].items():
  207. print(execmode)
  208. for oper, operdict in operation.items():
  209. operdict['time'], operdict['times'] = mytimer(operdict['func'],runs)
  210. if profile:
  211. filename = '{0}_{1}_{2}'.format(execmode, oper, profile)
  212. cProfile.runctx(operdict['func'].__name__ + '()',
  213. globals(), locals(), filename = filename)
  214. print((' {0}: {1: 40.6f}s'.format(oper, operdict['time'])))
  215. del(operdict['func'])
  216. regions.append(result)
  217. core.del_temp_region()
  218. return regions
  219. def get_testlist(loc):
  220. testlist = [test for test in list(loc.keys()) if 'test' in test[:5]]
  221. testlist.sort()
  222. return testlist
  223. def get_testdict(testlist):
  224. testdict = collections.OrderedDict()
  225. for testfunc in testlist:
  226. #import pdb; pdb.set_trace()
  227. dummy, execmode, operation = testfunc.split('__')
  228. if execmode in list(testdict.keys()):
  229. testdict[execmode][operation] = collections.OrderedDict()
  230. testdict[execmode][operation]['func'] = loc[testfunc]
  231. else:
  232. testdict[execmode] = collections.OrderedDict()
  233. testdict[execmode][operation] = collections.OrderedDict()
  234. testdict[execmode][operation]['func'] = loc[testfunc]
  235. return testdict
  236. def print_test(testdict):
  237. for execmode, operation in testdict.items():
  238. print(execmode)
  239. for oper, operdict in operation.items():
  240. print(' ', oper)
  241. for key, value in operdict.items():
  242. print(' ', key)
  243. TXT = """
  244. {% for region in regions %}
  245. {{ '#'*60 }}
  246. ### Benchmark cols = {{ region.cols }} rows = {{ region.rows}} cells = {{ region.cells }}
  247. {{ '#'*60 }}
  248. # equation: c = a + b
  249. {% for execmode, operation in region.results.iteritems() %}
  250. {{ "%-30s - %5s % 12.6fs"|format(execmode, 'add', operation.add.time) }}
  251. {%- endfor %}
  252. # equation: c = if a > 50 then 1 else 0
  253. {% for execmode, operation in region.results.iteritems() %}
  254. {{ "%-30s - %5s % 12.6fs"|format(execmode, 'if', operation.if.time) }}
  255. {%- endfor %}
  256. {%- endfor %}
  257. """
  258. CSV = """Class; Mode; Operation;
  259. """
  260. RST = """
  261. """
  262. #>>> txt = Template(TxT)
  263. #>>> txt.render(name='John Doe')
  264. def get_txt(results):
  265. txt = Template(TXT)
  266. return txt.render(regions = results)
  267. #classes for required options
  268. strREQUIRED = 'required'
  269. class OptionWithDefault(optparse.Option):
  270. ATTRS = optparse.Option.ATTRS + [strREQUIRED]
  271. def __init__(self, *opts, **attrs):
  272. if attrs.get(strREQUIRED, False):
  273. attrs['help'] = '(Required) ' + attrs.get('help', "")
  274. optparse.Option.__init__(self, *opts, **attrs)
  275. class OptionParser(optparse.OptionParser):
  276. def __init__(self, **kwargs):
  277. kwargs['option_class'] = OptionWithDefault
  278. optparse.OptionParser.__init__(self, **kwargs)
  279. def check_values(self, values, args):
  280. for option in self.option_list:
  281. if hasattr(option, strREQUIRED) and option.required:
  282. if not getattr(values, option.dest):
  283. self.error("option %s is required".format(str(option)))
  284. return optparse.OptionParser.check_values(self, values, args)
  285. def main(testdict):
  286. """Main function"""
  287. #usage
  288. usage = "usage: %prog [options] raster_map"
  289. parser = OptionParser(usage=usage)
  290. # ntime
  291. parser.add_option("-n", "--ntimes", dest="ntime",default=5, type="int",
  292. help="Number of run for each test.")
  293. # res
  294. parser.add_option("-r", "--resolution", action="store", type="string",
  295. dest="res", default = '1,0.25',
  296. help="Resolution list separate by comma.")
  297. # fmt
  298. parser.add_option("-f", "--fmt", action="store", type="string",
  299. dest="fmt", default = 'txt',
  300. help="Choose the output format: 'txt', 'csv', 'rst'.")
  301. # output
  302. parser.add_option("-o", "--output", action="store", type="string",
  303. dest="output", help="The output filename.")
  304. # store
  305. parser.add_option("-s", "--store", action="store", type="string",
  306. dest="store", help="The filename of pickle obj.")
  307. # profile
  308. parser.add_option("-p", "--profile", action="store", type="string",
  309. dest="profile", help="The filename of the profile results.")
  310. #return options and argument
  311. options, args = parser.parse_args()
  312. res = [float(r) for r in options.res.split(',')]
  313. #res = [1, 0.25, 0.1, 0.05]
  314. results = run_benchmark(res, options.ntime, testdict, options.profile)
  315. if options.store:
  316. import pickle
  317. output = open(options.store, 'wb')
  318. pickle.dump(results, output)
  319. output.close()
  320. #import pdb; pdb.set_trace()
  321. print(get_txt(results))
  322. #add options
  323. if __name__ == "__main__":
  324. #import pdb; pdb.set_trace()
  325. loc = locals()
  326. testlist = get_testlist(loc)
  327. testdict = get_testdict(testlist)
  328. #print_test(testdict)
  329. #import pdb; pdb.set_trace()
  330. main(testdict)