benchmark.py 15 KB

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