benchmark.py 15 KB

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