v.report.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  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 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. import sys
  45. import os
  46. import grass.script as grass
  47. def uniq(l):
  48. result = []
  49. last = None
  50. for i in l:
  51. if i != last:
  52. result.append(i)
  53. last = i
  54. return result
  55. def main():
  56. mapname = options['map']
  57. option = options['option']
  58. layer = options['layer']
  59. units = options['units']
  60. nuldev = file(os.devnull, 'w')
  61. if not grass.find_file(mapname, 'vector')['file']:
  62. grass.fatal(_("Vector map <%s> not found") % mapname)
  63. if int(layer) in grass.vector_db(mapname):
  64. colnames = grass.vector_columns(mapname, layer, getDict=False, stderr=nuldev)
  65. isConnection = True
  66. else:
  67. isConnection = False
  68. colnames = ['cat']
  69. if option == 'coor':
  70. extracolnames = ['x', 'y', 'z']
  71. else:
  72. extracolnames = [option]
  73. if units == 'percent':
  74. unitsp = 'meters'
  75. elif units:
  76. unitsp = units
  77. else:
  78. unitsp = None
  79. # NOTE: we suppress -1 cat and 0 cat
  80. if isConnection:
  81. f = grass.vector_db(map=mapname)[int(layer)]
  82. p = grass.pipe_command('v.db.select', quiet=True, map=mapname, layer=layer)
  83. records1 = []
  84. catcol = -1
  85. for line in p.stdout:
  86. cols = line.rstrip('\r\n').split('|')
  87. if catcol == -1:
  88. for i in range(0, len(cols)):
  89. if cols[i] == f['key']:
  90. catcol = i
  91. break
  92. if catcol == -1:
  93. grass.fatal(_("There is a table connected to input vector map '%s', but "
  94. "there is no key column '%s'.") % (mapname, f['key']))
  95. continue
  96. if cols[catcol] == '-1' or cols[catcol] == '0':
  97. continue
  98. records1.append(cols[:catcol] + [int(cols[catcol])] + cols[(catcol+1):])
  99. p.wait()
  100. if p.returncode != 0:
  101. sys.exit(1)
  102. records1.sort(key=lambda r: r[catcol])
  103. if len(records1) == 0:
  104. try:
  105. grass.fatal(_("There is a table connected to input vector map '%s', but "
  106. "there are no categories present in the key column '%s'. Consider using "
  107. "v.to.db to correct this.") % (mapname, f['key']))
  108. except KeyError:
  109. pass
  110. # fetch the requested attribute sorted by cat:
  111. p = grass.pipe_command('v.to.db', flags='p', quiet=True,
  112. map=mapname, option=option,
  113. layer=layer, units=unitsp)
  114. records2 = []
  115. for line in p.stdout:
  116. fields = line.rstrip('\r\n').split('|')
  117. if fields[0] in ['cat', '-1', '0']:
  118. continue
  119. records2.append([int(fields[0])] + fields[1:])
  120. p.wait()
  121. records2.sort()
  122. # make pre-table
  123. # len(records1) may not be the same as len(records2) because
  124. # v.db.select can return attributes that are not linked to features.
  125. records3 = []
  126. for r2 in records2:
  127. records3.append(filter(lambda r1: r1[catcol] == r2[0], records1)[0] + r2[1:])
  128. else:
  129. catcol = 0
  130. records1 = []
  131. p = grass.pipe_command('v.category', inp=mapname, layer=layer, option='print')
  132. for line in p.stdout:
  133. field = int(line.rstrip())
  134. if field > 0:
  135. records1.append(field)
  136. p.wait()
  137. records1.sort()
  138. records1 = uniq(records1)
  139. # make pre-table
  140. p = grass.pipe_command('v.to.db', flags='p', quiet=True,
  141. map=mapname, option=option,
  142. layer=layer, units=unitsp)
  143. records3 = []
  144. for line in p.stdout:
  145. fields = line.rstrip('\r\n').split('|')
  146. if fields[0] in ['cat', '-1', '0']:
  147. continue
  148. records3.append([int(fields[0])] + fields[1:])
  149. p.wait()
  150. records3.sort()
  151. # print table header
  152. sys.stdout.write('|'.join(colnames + extracolnames) + '\n')
  153. # make and print the table:
  154. numcols = len(colnames) + len(extracolnames)
  155. # calculate percents if requested
  156. if units == 'percent' and option != 'coor':
  157. # calculate total value
  158. total = 0
  159. for r in records3:
  160. total += float(r[-1])
  161. # calculate percentages
  162. records4 = [float(r[-1]) * 100 / total for r in records3]
  163. if type(records1[0]) == int:
  164. records3 = [[r1] + [r4] for r1, r4 in zip(records1, records4)]
  165. else:
  166. records3 = [r1 + [r4] for r1, r4 in zip(records1, records4)]
  167. # sort results
  168. if options['sort']:
  169. if options['sort'] == 'asc':
  170. if options['option'] == 'coor':
  171. records3.sort(key=lambda r: (float(r[-3]), float(r[-2]), float(r[-1])))
  172. else:
  173. records3.sort(key=lambda r: float(r[-1]))
  174. else:
  175. if options['option'] == 'coor':
  176. records3.sort(key=lambda r: (float(r[-3]), float(r[-2]), float(r[-1])), reverse=True)
  177. else:
  178. records3.sort(key=lambda r: float(r[-1]), reverse=True)
  179. for r in records3:
  180. sys.stdout.write('|'.join(map(str, r)) + '\n')
  181. if __name__ == "__main__":
  182. options, flags = grass.parser()
  183. main()