functions.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  1. # -*- coding: utf-8 -*-
  2. """
  3. Created on Tue Jun 26 12:38:48 2012
  4. @author: pietro
  5. """
  6. import fnmatch
  7. import os
  8. import grass.lib.gis as libgis
  9. import grass.lib.raster as libraster
  10. from grass.script import core as grasscore
  11. from grass.pygrass.errors import GrassError
  12. from grass.pygrass.gis.region import Region
  13. def looking(obj, filter_string):
  14. """
  15. >>> import grass.lib.vector as libvect
  16. >>> sorted(looking(libvect, '*by_box*')) # doctest: +NORMALIZE_WHITESPACE
  17. ['Vect_select_areas_by_box', 'Vect_select_isles_by_box',
  18. 'Vect_select_lines_by_box', 'Vect_select_nodes_by_box']
  19. """
  20. word_list = dir(obj)
  21. word_list.sort()
  22. return fnmatch.filter(word_list, filter_string)
  23. def findfiles(dirpath, match=None):
  24. """Return a list of the files"""
  25. res = []
  26. for f in sorted(os.listdir(dirpath)):
  27. abspath = os.path.join(dirpath, f)
  28. if os.path.isdir(abspath):
  29. res.extend(findfiles(abspath, match))
  30. if match:
  31. if fnmatch.fnmatch(abspath, match):
  32. res.append(abspath)
  33. else:
  34. res.append(abspath)
  35. return res
  36. def remove(oldname, maptype):
  37. """Remove a map"""
  38. grasscore.run_command('g.remove', quiet=True,
  39. **{maptype: '{old}'.format(old=oldname)})
  40. def rename(oldname, newname, maptype):
  41. """Rename a map"""
  42. grasscore.run_command('g.rename', quiet=True,
  43. **{maptype: '{old},{new}'.format(old=oldname,
  44. new=newname), })
  45. def copy(existingmap, newmap, maptype):
  46. """Copy a map
  47. >>> copy('census', 'mycensus', 'vect')
  48. >>> rename('mycensus', 'mynewcensus', 'vect')
  49. >>> remove('mynewcensus', 'vect')
  50. """
  51. grasscore.run_command('g.copy', quiet=True,
  52. **{maptype: '{old},{new}'.format(old=existingmap,
  53. new=newmap), })
  54. def getenv(env):
  55. """Return the current grass environment variables ::
  56. >>> getenv("MAPSET")
  57. 'user1'
  58. """
  59. return libgis.G__getenv(env)
  60. def get_mapset_raster(mapname, mapset=''):
  61. """Return the mapset of the raster map ::
  62. >>> get_mapset_raster('elevation')
  63. 'PERMANENT'
  64. """
  65. return libgis.G_find_raster(mapname, mapset)
  66. def get_mapset_vector(mapname, mapset=''):
  67. """Return the mapset of the vector map ::
  68. >>> get_mapset_vector('census')
  69. 'PERMANENT'
  70. """
  71. return libgis.G_find_vector(mapname, mapset)
  72. def is_clean_name(name):
  73. """Return if the name is valid ::
  74. >>> is_clean_name('census')
  75. True
  76. >>> is_clean_name('0census')
  77. False
  78. >>> is_clean_name('census&')
  79. False
  80. """
  81. if name[0].isdigit():
  82. return False
  83. for char in ' @#^?°,;%&/':
  84. if name.find(char) != -1:
  85. return False
  86. return True
  87. def coor2pixel((east, north), region):
  88. """Convert coordinates into a pixel row and col ::
  89. >>> reg = Region()
  90. >>> coor2pixel((reg.west, reg.north), reg)
  91. (0.0, 0.0)
  92. >>> coor2pixel((reg.east, reg.south), reg) == (reg.rows, reg.cols)
  93. True
  94. """
  95. return (libraster.Rast_northing_to_row(north, region.c_region),
  96. libraster.Rast_easting_to_col(east, region.c_region))
  97. def pixel2coor((col, row), region):
  98. """Convert row and col of a pixel into a coordinates ::
  99. >>> reg = Region()
  100. >>> pixel2coor((0, 0), reg) == (reg.north, reg.west)
  101. True
  102. >>> pixel2coor((reg.cols, reg.rows), reg) == (reg.south, reg.east)
  103. True
  104. """
  105. return (libraster.Rast_row_to_northing(row, region.c_region),
  106. libraster.Rast_col_to_easting(col, region.c_region))
  107. def get_raster_for_points(poi_vector, raster, column=None):
  108. """Query a raster map for each point feature of a vector
  109. Example ::
  110. >>> from grass.pygrass.vector import VectorTopo
  111. >>> from grass.pygrass.raster import RasterRow
  112. >>> ele = RasterRow('elevation')
  113. >>> copy('schools','myschools','vect')
  114. >>> sch = VectorTopo('myschools')
  115. >>> get_raster_for_points(sch, ele) # doctest: +ELLIPSIS
  116. [(1, 633649.2856743174, 221412.94434781274, 145.06602)...
  117. >>> sch.table.columns.add('elevation','double precision')
  118. >>> 'elevation' in sch.table.columns
  119. True
  120. >>> get_raster_for_points(sch, ele, 'elevation')
  121. True
  122. >>> sch.table.filters.select('NAMESHORT','elevation')
  123. Filters('SELECT NAMESHORT, elevation FROM myschools;')
  124. >>> cur = sch.table.execute()
  125. >>> cur.fetchall() # doctest: +ELLIPSIS
  126. [(u'SWIFT CREEK', 145.06602), ... (u'9TH GRADE CTR', None)]
  127. >>> remove('myschools','vect')
  128. Parameters
  129. -------------
  130. point: point vector object
  131. raster: raster object
  132. column: column name to update
  133. """
  134. from math import isnan
  135. if not column:
  136. result = []
  137. reg = Region()
  138. if not poi_vector.is_open():
  139. poi_vector.open()
  140. if not raster.is_open():
  141. raster.open()
  142. if poi_vector.num_primitive_of('point') == 0:
  143. raise GrassError(_("Vector doesn't contain points"))
  144. for poi in poi_vector.viter('points'):
  145. val = raster.get_value(poi, reg)
  146. if column:
  147. if val is not None and not isnan(val):
  148. poi.attrs[column] = val
  149. else:
  150. if val is not None and not isnan(val):
  151. result.append((poi.id, poi.x, poi.y, val))
  152. else:
  153. result.append((poi.id, poi.x, poi.y, None))
  154. if not column:
  155. return result
  156. else:
  157. poi.attrs.commit()
  158. return True
  159. def r_export(rast, output='', fmt='png', **kargs):
  160. from grass.pygrass.modules import Module
  161. if rast.exist():
  162. output = output if output else "%s_%s.%s" % (rast.name, rast.mapset,
  163. fmt)
  164. Module('r.out.%s' % fmt, input=rast.fullname(), output=output,
  165. overwrite=True, **kargs)
  166. return output
  167. else:
  168. raise ValueError('Raster map does not exist.')