benchmark.py 13 KB

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