v.report.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  1. #!/usr/bin/env python
  2. #
  3. ############################################################################
  4. #
  5. # MODULE: v.report
  6. # AUTHOR(S): Markus Neteler, converted to Python by Glynn Clements
  7. # Bug fixes, sort for coor by Huidae Cho <grass4u gmail.com>
  8. # PURPOSE: Reports geometry statistics for vector maps
  9. # COPYRIGHT: (C) 2005, 2007-2017, 2019 by MN and the GRASS Development Team
  10. #
  11. # This program is free software under the GNU General Public
  12. # License (>=v2). Read the file COPYING that comes with GRASS
  13. # for details.
  14. #
  15. #############################################################################
  16. #%module
  17. #% description: Reports geometry statistics for vector maps.
  18. #% keyword: vector
  19. #% keyword: geometry
  20. #% keyword: statistics
  21. #%end
  22. #%option G_OPT_V_MAP
  23. #%end
  24. #%option G_OPT_V_FIELD
  25. #% guisection: Selection
  26. #%end
  27. #%option
  28. #% key: option
  29. #% type: string
  30. #% description: Value to calculate
  31. #% options: area,length,coor
  32. #% required: yes
  33. #%end
  34. #%option G_OPT_M_UNITS
  35. #% options: miles,feet,meters,kilometers,acres,hectares,percent
  36. #%end
  37. #%option
  38. #% key: sort
  39. #% type: string
  40. #% description: Sort the result
  41. #% options: asc,desc
  42. #% descriptions: asc;Sort in ascending order;desc;Sort in descending order
  43. #%end
  44. #%flag
  45. #% key: c
  46. #% description: Do not include column names in output
  47. #%end
  48. import sys
  49. import os
  50. import grass.script as grass
  51. from grass.script.utils import decode
  52. # i18N
  53. import gettext
  54. gettext.install('grassmods', os.path.join(os.getenv("GISBASE"), 'locale'))
  55. def uniq(l):
  56. result = []
  57. last = None
  58. for i in l:
  59. if i != last:
  60. result.append(i)
  61. last = i
  62. return result
  63. def main():
  64. mapname = options['map']
  65. option = options['option']
  66. layer = options['layer']
  67. units = options['units']
  68. nuldev = open(os.devnull, 'w')
  69. if not grass.find_file(mapname, 'vector')['file']:
  70. grass.fatal(_("Vector map <%s> not found") % mapname)
  71. if int(layer) in grass.vector_db(mapname):
  72. colnames = grass.vector_columns(mapname, layer, getDict=False, stderr=nuldev)
  73. isConnection = True
  74. else:
  75. isConnection = False
  76. colnames = ['cat']
  77. if option == 'coor':
  78. extracolnames = ['x', 'y', 'z']
  79. else:
  80. extracolnames = [option]
  81. if units == 'percent':
  82. unitsp = 'meters'
  83. elif units:
  84. unitsp = units
  85. else:
  86. unitsp = None
  87. # NOTE: we suppress -1 cat and 0 cat
  88. if isConnection:
  89. f = grass.vector_db(map=mapname)[int(layer)]
  90. p = grass.pipe_command('v.db.select', quiet=True, map=mapname, layer=layer)
  91. records1 = []
  92. catcol = -1
  93. ncols = 0
  94. for line in p.stdout:
  95. cols = decode(line).rstrip('\r\n').split('|')
  96. if catcol == -1:
  97. ncols = len(cols)
  98. for i in range(0, ncols):
  99. if cols[i] == f['key']:
  100. catcol = i
  101. break
  102. if catcol == -1:
  103. grass.fatal(_("There is a table connected to input vector map '%s', but "
  104. "there is no key column '%s'.") % (mapname, f['key']))
  105. continue
  106. if cols[catcol] == '-1' or cols[catcol] == '0':
  107. continue
  108. records1.append(cols[:catcol] + [int(cols[catcol])] + cols[(catcol+1):])
  109. p.wait()
  110. if p.returncode != 0:
  111. sys.exit(1)
  112. records1.sort(key=lambda r: r[catcol])
  113. if len(records1) == 0:
  114. try:
  115. grass.fatal(_("There is a table connected to input vector map '%s', but "
  116. "there are no categories present in the key column '%s'. Consider using "
  117. "v.to.db to correct this.") % (mapname, f['key']))
  118. except KeyError:
  119. pass
  120. # fetch the requested attribute sorted by cat:
  121. p = grass.pipe_command('v.to.db', flags='p', quiet=True,
  122. map=mapname, option=option,
  123. layer=layer, units=unitsp)
  124. records2 = []
  125. for line in p.stdout:
  126. fields = decode(line).rstrip('\r\n').split('|')
  127. if fields[0] in ['cat', '-1', '0']:
  128. continue
  129. records2.append([int(fields[0])] + fields[1:])
  130. p.wait()
  131. records2.sort()
  132. # make pre-table
  133. # len(records1) may not be the same as len(records2) because
  134. # v.db.select can return attributes that are not linked to features.
  135. records3 = []
  136. for r2 in records2:
  137. rec = list(filter(lambda r1: r1[catcol] == r2[0], records1))
  138. if len(rec) > 0:
  139. res = rec[0] + r2[1:]
  140. else:
  141. res = [r2[0]] + [''] * (ncols - 1) + r2[1:]
  142. records3.append(res)
  143. else:
  144. catcol = 0
  145. records1 = []
  146. p = grass.pipe_command('v.category', inp=mapname, layer=layer, option='print')
  147. for line in p.stdout:
  148. field = int(decode(line).rstrip())
  149. if field > 0:
  150. records1.append(field)
  151. p.wait()
  152. records1.sort()
  153. records1 = uniq(records1)
  154. # make pre-table
  155. p = grass.pipe_command('v.to.db', flags='p', quiet=True,
  156. map=mapname, option=option,
  157. layer=layer, units=unitsp)
  158. records3 = []
  159. for line in p.stdout:
  160. fields = decode(line).rstrip('\r\n').split('|')
  161. if fields[0] in ['cat', '-1', '0']:
  162. continue
  163. records3.append([int(fields[0])] + fields[1:])
  164. p.wait()
  165. records3.sort()
  166. # print table header
  167. if not flags['c']:
  168. sys.stdout.write('|'.join(colnames + extracolnames) + '\n')
  169. # make and print the table:
  170. numcols = len(colnames) + len(extracolnames)
  171. # calculate percents if requested
  172. if units == 'percent' and option != 'coor':
  173. # calculate total value
  174. total = 0
  175. for r in records3:
  176. total += float(r[-1])
  177. # calculate percentages
  178. records4 = [float(r[-1]) * 100 / total for r in records3]
  179. if type(records1[0]) == int:
  180. records3 = [[r1] + [r4] for r1, r4 in zip(records1, records4)]
  181. else:
  182. records3 = [r1 + [r4] for r1, r4 in zip(records1, records4)]
  183. # sort results
  184. if options['sort']:
  185. if options['sort'] == 'asc':
  186. if options['option'] == 'coor':
  187. records3.sort(key=lambda r: (float(r[-3]), float(r[-2]), float(r[-1])))
  188. else:
  189. records3.sort(key=lambda r: float(r[-1]))
  190. else:
  191. if options['option'] == 'coor':
  192. records3.sort(key=lambda r: (float(r[-3]), float(r[-2]), float(r[-1])), reverse=True)
  193. else:
  194. records3.sort(key=lambda r: float(r[-1]), reverse=True)
  195. for r in records3:
  196. sys.stdout.write('|'.join(map(str, r)) + '\n')
  197. if __name__ == "__main__":
  198. options, flags = grass.parser()
  199. main()