d.polar.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  1. #!/usr/bin/env python
  2. #
  3. ############################################################################
  4. #
  5. # MODULE: d.polar
  6. # AUTHOR(S): Markus Neteler. neteler itc.it
  7. # algorithm + EPS output by Bruno Caprile
  8. # d.graph plotting code by Hamish Bowman
  9. # Converted to Python by Glynn Clements
  10. # PURPOSE: Draws polar diagram of angle map. The outer circle considers
  11. # all cells in the map. If one or many of them are NULL (no data),
  12. # the figure will not reach the outer circle. The vector inside
  13. # indicates the prevalent direction.
  14. # COPYRIGHT: (C) 2006,2008 by the GRASS Development Team
  15. #
  16. # This program is free software under the GNU General Public
  17. # License (>=v2). Read the file COPYING that comes with GRASS
  18. # for details.
  19. #
  20. #############################################################################
  21. #%Module
  22. #% description: Draws polar diagram of angle map such as aspect or flow directions
  23. #% keyword: display
  24. #% keyword: diagram
  25. #%End
  26. #%option G_OPT_R_MAP
  27. #% description: Name of raster angle map
  28. #%End
  29. #%option
  30. #% key: undef
  31. #% type: double
  32. #% description: Pixel value to be interpreted as undefined (different from NULL)
  33. #% required : no
  34. #%End
  35. #%option G_OPT_F_OUTPUT
  36. #% description: Name for optional EPS output file
  37. #% required : no
  38. #%end
  39. #%flag
  40. #% key: x
  41. #% description: Plot using Xgraph
  42. #%end
  43. import os
  44. import string
  45. import types
  46. import math
  47. import atexit
  48. import glob
  49. import shutil
  50. from grass.script.utils import try_remove, basename
  51. from grass.script import core as gcore
  52. def cleanup():
  53. try_remove(tmp)
  54. for f in glob.glob(tmp + '_*'):
  55. try_remove(f)
  56. def plot_xgraph():
  57. newline = ['\n']
  58. p = gcore.Popen(['xgraph'], stdin=gcore.PIPE)
  59. for point in sine_cosine_replic + newline + outercircle + newline + vector:
  60. if isinstance(point, tuple):
  61. p.stdin.write("%f %f\n" % point)
  62. else:
  63. p.stdin.write(point + '\n')
  64. p.stdin.close()
  65. p.wait()
  66. def plot_dgraph():
  67. # use d.info and d.frame to create a square frame in the center of the
  68. # window.
  69. s = gcore.read_command('d.info', flags='d')
  70. f = s.split()
  71. frame_width = float(f[1])
  72. frame_height = float(f[2])
  73. # take shorter side as length of frame side
  74. min_side = min(frame_width, frame_height)
  75. dx = (frame_width - min_side) / 2
  76. dy = (frame_height - min_side) / 2
  77. fl = dx
  78. fr = frame_width - dx
  79. ft = dy
  80. fb = frame_height - dy
  81. tenv = os.environ.copy()
  82. tenv['GRASS_RENDER_FRAME'] = '%f,%f,%f,%f' % (ft, fb, fl, fr)
  83. # polyline calculations
  84. ring = 0.95
  85. scaleval = ring * totalvalidnumber / totalnumber
  86. sine_cosine_replic_normalized = [
  87. ((scaleval * p[0] / maxradius + 1) * 50,
  88. (scaleval * p[1] / maxradius + 1) * 50)
  89. for p in sine_cosine_replic if isinstance(p, tuple)]
  90. # create circle
  91. circle = [(50 * (1 + ring * math.sin(math.radians(i))),
  92. 50 * (1 + ring * math.cos(math.radians(i))))
  93. for i in range(0, 361)]
  94. # trend vector
  95. vect = [((scaleval * p[0] / maxradius + 1) * 50,
  96. (scaleval * p[1] / maxradius + 1) * 50)
  97. for p in vector[1:]]
  98. # Possible TODOs:
  99. # To fill data area with color, use BOTH d.graph's polyline and polygon commands.
  100. # Using polygon alone gives a jagged boundary due to sampling technique
  101. # (not a bug).
  102. # plot it!
  103. lines = [
  104. # draw circle
  105. # mandatory when drawing proportional to non-square frame
  106. "color 180:255:180",
  107. "polyline"] + circle + [
  108. # draw axes
  109. "color 180:180:180",
  110. "width 0",
  111. "move 0 50",
  112. "draw 100 50",
  113. "move 50 0",
  114. "draw 50 100",
  115. # draw the goods
  116. "color red",
  117. "width 0",
  118. "polyline"] + sine_cosine_replic_normalized + [
  119. # draw vector
  120. "color blue",
  121. "width 3",
  122. "polyline"] + vect + [
  123. # draw compass text
  124. "color black",
  125. "width 2",
  126. "size 10 10",
  127. "move 51 97",
  128. "text N",
  129. "move 51 1",
  130. "text S",
  131. "move 1 51",
  132. "text W",
  133. "move 97 51",
  134. "text E",
  135. # draw legend text
  136. "width 0",
  137. "size 10",
  138. "color 0:180:0",
  139. "move 0.5 96.5",
  140. "text All data (incl. NULLs)",
  141. "color red",
  142. "move 0.5 93.5",
  143. "text Real data angles",
  144. "color blue",
  145. "move 0.5 90.5",
  146. "text Avg. direction"
  147. ]
  148. p = gcore.feed_command('d.graph', env=tenv)
  149. for point in lines:
  150. if isinstance(point, tuple):
  151. p.stdin.write("%f %f\n" % point)
  152. else:
  153. p.stdin.write(point + '\n')
  154. p.stdin.close()
  155. p.wait()
  156. def plot_eps(psout):
  157. # EPS output (by M.Neteler and Bruno Caprile, ITC-irst)
  158. gcore.message(_("Generating %s ...") % psout)
  159. outerradius = maxradius
  160. epsscale = 0.1
  161. frameallowance = 1.1
  162. halfframe = 3000
  163. center = (halfframe, halfframe)
  164. scale = halfframe / (outerradius * frameallowance)
  165. diagramlinewidth = halfframe / 400
  166. axeslinewidth = halfframe / 500
  167. axesfontsize = halfframe / 16
  168. diagramfontsize = halfframe / 20
  169. halfframe_2 = halfframe * 2
  170. averagedirectioncolor = 1 # (blue)
  171. diagramcolor = 4 # (red)
  172. circlecolor = 2 # (green)
  173. axescolor = 0 # (black)
  174. northjustification = 2
  175. eastjustification = 6
  176. southjustification = 8
  177. westjustification = 8
  178. northxshift = 1.02 * halfframe
  179. northyshift = 1.98 * halfframe
  180. eastxshift = 1.98 * halfframe
  181. eastyshift = 1.02 * halfframe
  182. southxshift = 1.02 * halfframe
  183. southyshift = 0.02 * halfframe
  184. westxshift = 0.01 * halfframe
  185. westyshift = 1.02 * halfframe
  186. alldatastring = "all data (null included)"
  187. realdatastring = "real data angles"
  188. averagedirectionstring = "avg. direction"
  189. legendsx = 1.95 * halfframe
  190. alldatalegendy = 1.95 * halfframe
  191. realdatalegendy = 1.90 * halfframe
  192. averagedirectionlegendy = 1.85 * halfframe
  193. ##########
  194. outf = file(psout, 'w')
  195. prolog = os.path.join(
  196. os.environ['GISBASE'],
  197. 'etc',
  198. 'd.polar',
  199. 'ps_defs.eps')
  200. inf = file(prolog)
  201. shutil.copyfileobj(inf, outf)
  202. inf.close()
  203. t = string.Template("""
  204. $EPSSCALE $EPSSCALE scale %% EPS-SCALE EPS-SCALE scale
  205. %%
  206. %% drawing axes
  207. %%
  208. col0 %% colAXES-COLOR
  209. $AXESLINEWIDTH setlinewidth %% AXES-LINEWIDTH setlinewidth
  210. [] 0 setdash
  211. newpath
  212. $HALFFRAME 0.0 moveto %% HALF-FRAME 0.0 moveto
  213. $HALFFRAME $HALFFRAME_2 lineto %% HALF-FRAME (2 * HALF-FRAME) lineto
  214. 0.0 $HALFFRAME moveto %% 0.0 HALF-FRAME moveto
  215. $HALFFRAME_2 $HALFFRAME lineto %% (2 * HALF-FRAME) HALF-FRAME lineto
  216. stroke
  217. %%
  218. %% drawing outer circle
  219. %%
  220. col2 %% colCIRCLE-COLOR
  221. $DIAGRAMFONTSIZE /Times-Roman choose-font %% DIAGRAM-FONTSIZE /Times-Roman choose-font
  222. $DIAGRAMLINEWIDTH setlinewidth %% DIAGRAM-LINEWIDTH setlinewidth
  223. [] 0 setdash
  224. newpath
  225. %% coordinates of rescaled, translated outer circle follow
  226. %% first point moveto, then lineto
  227. """)
  228. s = t.substitute(
  229. AXESLINEWIDTH=axeslinewidth,
  230. DIAGRAMFONTSIZE=diagramfontsize,
  231. DIAGRAMLINEWIDTH=diagramlinewidth,
  232. EPSSCALE=epsscale,
  233. HALFFRAME=halfframe,
  234. HALFFRAME_2=halfframe_2
  235. )
  236. outf.write(s)
  237. sublength = len(outercircle) - 2
  238. (x, y) = outercircle[1]
  239. outf.write(
  240. "%.2f %.2f moveto\n" %
  241. (x * scale + halfframe, y * scale + halfframe))
  242. for x, y in outercircle[2:]:
  243. outf.write(
  244. "%.2f %.2f lineto\n" %
  245. (x * scale + halfframe, y * scale + halfframe))
  246. t = string.Template("""
  247. stroke
  248. %%
  249. %% axis titles
  250. %%
  251. col0 %% colAXES-COLOR
  252. $AXESFONTSIZE /Times-Roman choose-font %% AXES-FONTSIZE /Times-Roman choose-font
  253. (N) $NORTHXSHIFT $NORTHYSHIFT $NORTHJUSTIFICATION just-string %% NORTH-X-SHIFT NORTH-Y-SHIFT NORTH-JUSTIFICATION just-string
  254. (E) $EASTXSHIFT $EASTYSHIFT $EASTJUSTIFICATION just-string %% EAST-X-SHIFT EAST-Y-SHIFT EAST-JUSTIFICATION just-string
  255. (S) $SOUTHXSHIFT $SOUTHYSHIFT $SOUTHJUSTIFICATION just-string %% SOUTH-X-SHIFT SOUTH-Y-SHIFT SOUTH-JUSTIFICATION just-string
  256. (W) $WESTXSHIFT $WESTYSHIFT $WESTJUSTIFICATION just-string %% WEST-X-SHIFT WEST-Y-SHIFT WEST-JUSTIFICATION just-string
  257. $DIAGRAMFONTSIZE /Times-Roman choose-font %% DIAGRAM-FONTSIZE /Times-Roman choose-font
  258. %%
  259. %% drawing real data diagram
  260. %%
  261. col4 %% colDIAGRAM-COLOR
  262. $DIAGRAMLINEWIDTH setlinewidth %% DIAGRAM-LINEWIDTH setlinewidth
  263. [] 0 setdash
  264. newpath
  265. %% coordinates of rescaled, translated diagram follow
  266. %% first point moveto, then lineto
  267. """)
  268. s = t.substitute(
  269. AXESFONTSIZE=axesfontsize,
  270. DIAGRAMFONTSIZE=diagramfontsize,
  271. DIAGRAMLINEWIDTH=diagramlinewidth,
  272. EASTJUSTIFICATION=eastjustification,
  273. EASTXSHIFT=eastxshift,
  274. EASTYSHIFT=eastyshift,
  275. NORTHJUSTIFICATION=northjustification,
  276. NORTHXSHIFT=northxshift,
  277. NORTHYSHIFT=northyshift,
  278. SOUTHJUSTIFICATION=southjustification,
  279. SOUTHXSHIFT=southxshift,
  280. SOUTHYSHIFT=southyshift,
  281. WESTJUSTIFICATION=westjustification,
  282. WESTXSHIFT=westxshift,
  283. WESTYSHIFT=westyshift
  284. )
  285. outf.write(s)
  286. sublength = len(sine_cosine_replic) - 2
  287. (x, y) = sine_cosine_replic[1]
  288. outf.write(
  289. "%.2f %.2f moveto\n" %
  290. (x * scale + halfframe, y * scale + halfframe))
  291. for x, y in sine_cosine_replic[2:]:
  292. outf.write(
  293. "%.2f %.2f lineto\n" %
  294. (x * scale + halfframe, y * scale + halfframe))
  295. t = string.Template("""
  296. stroke
  297. %%
  298. %% drawing average direction
  299. %%
  300. col1 %% colAVERAGE-DIRECTION-COLOR
  301. $DIAGRAMLINEWIDTH setlinewidth %% DIAGRAM-LINEWIDTH setlinewidth
  302. [] 0 setdash
  303. newpath
  304. %% coordinates of rescaled, translated average direction follow
  305. %% first point moveto, second lineto
  306. """)
  307. s = t.substitute(DIAGRAMLINEWIDTH=diagramlinewidth)
  308. outf.write(s)
  309. sublength = len(vector) - 2
  310. (x, y) = vector[1]
  311. outf.write(
  312. "%.2f %.2f moveto\n" %
  313. (x * scale + halfframe, y * scale + halfframe))
  314. for x, y in vector[2:]:
  315. outf.write(
  316. "%.2f %.2f lineto\n" %
  317. (x * scale + halfframe, y * scale + halfframe))
  318. t = string.Template("""
  319. stroke
  320. %%
  321. %% drawing legends
  322. %%
  323. col2 %% colCIRCLE-COLOR
  324. %% Line below: (ALL-DATA-STRING) LEGENDS-X ALL-DATA-LEGEND-Y 4 just-string
  325. ($ALLDATASTRING) $LEGENDSX $ALLDATALEGENDY 4 just-string
  326. col4 %% colDIAGRAM-COLOR
  327. %% Line below: (REAL-DATA-STRING) LEGENDS-X REAL-DATA-LEGEND-Y 4 just-string
  328. ($REALDATASTRING) $LEGENDSX $REALDATALEGENDY 4 just-string
  329. col1 %% colAVERAGE-DIRECTION-COLOR
  330. %% Line below: (AVERAGE-DIRECTION-STRING) LEGENDS-X AVERAGE-DIRECTION-LEGEND-Y 4 just-string
  331. ($AVERAGEDIRECTIONSTRING) $LEGENDSX $AVERAGEDIRECTIONLEGENDY 4 just-string
  332. """)
  333. s = t.substitute(
  334. ALLDATALEGENDY=alldatalegendy,
  335. ALLDATASTRING=alldatastring,
  336. AVERAGEDIRECTIONLEGENDY=averagedirectionlegendy,
  337. AVERAGEDIRECTIONSTRING=averagedirectionstring,
  338. LEGENDSX=legendsx,
  339. REALDATALEGENDY=realdatalegendy,
  340. REALDATASTRING=realdatastring
  341. )
  342. outf.write(s)
  343. outf.close()
  344. gcore.message(_("Done."))
  345. def main():
  346. global tmp
  347. global sine_cosine_replic, outercircle, vector
  348. global totalvalidnumber, totalnumber, maxradius
  349. map = options['map']
  350. undef = options['undef']
  351. eps = options['output']
  352. xgraph = flags['x']
  353. tmp = gcore.tempfile()
  354. if eps and xgraph:
  355. gcore.fatal(_("Please select only one output method"))
  356. # check if we have xgraph (if no EPS output requested)
  357. if xgraph and not gcore.find_program('xgraph'):
  358. gcore.fatal(
  359. _("xgraph required, please install first (www.xgraph.org)"))
  360. #################################
  361. # this file contains everthing:
  362. rawfile = tmp + "_raw"
  363. rawf = file(rawfile, 'w')
  364. gcore.run_command('r.stats', flags='1', input=map, stdout=rawf)
  365. rawf.close()
  366. rawf = file(rawfile)
  367. totalnumber = 0
  368. for line in rawf:
  369. totalnumber += 1
  370. rawf.close()
  371. gcore.message(
  372. _("Calculating statistics for polar diagram... (be patient)"))
  373. # wipe out NULL data and undef data if defined by user
  374. # - generate degree binned to integer, eliminate NO DATA (NULL):
  375. # change 360 to 0 to close polar diagram:
  376. rawf = file(rawfile)
  377. nvals = 0
  378. sumcos = 0
  379. sumsin = 0
  380. freq = {}
  381. for line in rawf:
  382. line = line.rstrip('\r\n')
  383. if line in ['*', undef]:
  384. continue
  385. nvals += 1
  386. x = float(line)
  387. rx = math.radians(x)
  388. sumcos += math.cos(rx)
  389. sumsin += math.sin(rx)
  390. ix = round(x)
  391. if ix == 360:
  392. ix = 0
  393. if ix in freq:
  394. freq[ix] += 1
  395. else:
  396. freq[ix] = 1
  397. rawf.close()
  398. totalvalidnumber = nvals
  399. if totalvalidnumber == 0:
  400. gcore.fatal(_("No data pixel found"))
  401. #################################
  402. # unit vector on raw data converted to radians without no data:
  403. unitvector = (sumcos / nvals, sumsin / nvals)
  404. #################################
  405. # how many are there?:
  406. occurrences = sorted([(math.radians(x), freq[x]) for x in freq])
  407. # find the maximum value
  408. maxradius = max([f for a, f in occurrences])
  409. # now do cos() sin()
  410. sine_cosine = [(math.cos(a) * f, math.sin(a) * f) for a, f in occurrences]
  411. sine_cosine_replic = ['"Real data angles'] + sine_cosine + sine_cosine[0:1]
  412. if eps or xgraph:
  413. outercircle = []
  414. outercircle.append('"All Data incl. NULLs')
  415. scale = 1.0 * totalnumber / totalvalidnumber * maxradius
  416. for i in range(0, 361):
  417. a = math.radians(i)
  418. x = math.cos(a) * scale
  419. y = math.sin(a) * scale
  420. outercircle.append((x, y))
  421. # fix vector length to become visible (x? of $MAXRADIUS):
  422. vector = []
  423. vector.append('"Avg. Direction\n')
  424. vector.append((0, 0))
  425. vector.append((unitvector[0] * maxradius, unitvector[1] * maxradius))
  426. ###########################################################
  427. # Now output:
  428. if eps:
  429. psout = basename(eps, 'eps') + '.eps'
  430. plot_eps(psout)
  431. elif xgraph:
  432. plot_xgraph()
  433. else:
  434. plot_dgraph()
  435. gcore.message(_("Average vector:"))
  436. gcore.message(
  437. _("direction: %.1f degrees CCW from East") %
  438. math.degrees(
  439. math.atan2(
  440. unitvector[1],
  441. unitvector[0])))
  442. gcore.message(
  443. _("magnitude: %.1f percent of fullscale") %
  444. (100 *
  445. math.hypot(
  446. unitvector[0],
  447. unitvector[1])))
  448. if __name__ == "__main__":
  449. options, flags = gcore.parser()
  450. atexit.register(cleanup)
  451. main()