d.polar.py 16 KB

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