d.polar.py 16 KB

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