functions.py 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  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 findmaps(type, pattern=None, mapset='', location='', gisdbase=''):
  37. """Return a list of tuple contining the names of the:
  38. * map
  39. * mapset,
  40. * location,
  41. * gisdbase
  42. """
  43. from grass.pygrass.gis import Gisdbase, Location, Mapset
  44. def find_in_location(type, pattern, location):
  45. res = []
  46. for msetname in location.mapsets():
  47. mset = Mapset(msetname, location.name, location.gisdbase)
  48. res.extend([(m, mset.name, mset.location, mset.gisdbase)
  49. for m in mset.glist(type, pattern)])
  50. return res
  51. def find_in_gisdbase(type, pattern, gisdbase):
  52. res = []
  53. for loc in gisdbase.locations():
  54. res.extend(find_in_location(type, pattern,
  55. Location(loc, gisdbase.name)))
  56. return res
  57. if gisdbase and location and mapset:
  58. mset = Mapset(mapset, location, gisdbase)
  59. return [(m, mset.name, mset.location, mset.gisdbase)
  60. for m in mset.glist(type, pattern)]
  61. elif gisdbase and location:
  62. loc = Location(location, gisdbase)
  63. return find_in_location(type, pattern, loc)
  64. elif gisdbase:
  65. gis = Gisdbase(gisdbase)
  66. return find_in_gisdbase(type, pattern, gis)
  67. elif location:
  68. loc = Location(location)
  69. return find_in_location(type, pattern, loc)
  70. elif mapset:
  71. mset = Mapset(mapset)
  72. return [(m, mset.name, mset.location, mset.gisdbase)
  73. for m in mset.glist(type, pattern)]
  74. else:
  75. gis = Gisdbase()
  76. return find_in_gisdbase(type, pattern, gis)
  77. def remove(oldname, maptype):
  78. """Remove a map"""
  79. grasscore.run_command('g.remove', quiet=True,
  80. **{maptype: '{old}'.format(old=oldname)})
  81. def rename(oldname, newname, maptype):
  82. """Rename a map"""
  83. grasscore.run_command('g.rename', quiet=True,
  84. **{maptype: '{old},{new}'.format(old=oldname,
  85. new=newname), })
  86. def copy(existingmap, newmap, maptype):
  87. """Copy a map
  88. >>> copy('census', 'mycensus', 'vect')
  89. >>> rename('mycensus', 'mynewcensus', 'vect')
  90. >>> remove('mynewcensus', 'vect')
  91. """
  92. grasscore.run_command('g.copy', quiet=True,
  93. **{maptype: '{old},{new}'.format(old=existingmap,
  94. new=newmap), })
  95. def getenv(env):
  96. """Return the current grass environment variables ::
  97. >>> getenv("MAPSET")
  98. 'user1'
  99. """
  100. return libgis.G__getenv(env)
  101. def get_mapset_raster(mapname, mapset=''):
  102. """Return the mapset of the raster map ::
  103. >>> get_mapset_raster('elevation')
  104. 'PERMANENT'
  105. """
  106. return libgis.G_find_raster2(mapname, mapset)
  107. def get_mapset_vector(mapname, mapset=''):
  108. """Return the mapset of the vector map ::
  109. >>> get_mapset_vector('census')
  110. 'PERMANENT'
  111. """
  112. return libgis.G_find_vector2(mapname, mapset)
  113. def is_clean_name(name):
  114. """Return if the name is valid ::
  115. >>> is_clean_name('census')
  116. True
  117. >>> is_clean_name('0census')
  118. False
  119. >>> is_clean_name('census&')
  120. False
  121. """
  122. if name[0].isdigit():
  123. return False
  124. for char in ' @#^?°,;%&/':
  125. if name.find(char) != -1:
  126. return False
  127. return True
  128. def coor2pixel((east, north), region):
  129. """Convert coordinates into a pixel row and col ::
  130. >>> reg = Region()
  131. >>> coor2pixel((reg.west, reg.north), reg)
  132. (0.0, 0.0)
  133. >>> coor2pixel((reg.east, reg.south), reg) == (reg.rows, reg.cols)
  134. True
  135. """
  136. return (libraster.Rast_northing_to_row(north, region.c_region),
  137. libraster.Rast_easting_to_col(east, region.c_region))
  138. def pixel2coor((col, row), region):
  139. """Convert row and col of a pixel into a coordinates ::
  140. >>> reg = Region()
  141. >>> pixel2coor((0, 0), reg) == (reg.north, reg.west)
  142. True
  143. >>> pixel2coor((reg.cols, reg.rows), reg) == (reg.south, reg.east)
  144. True
  145. """
  146. return (libraster.Rast_row_to_northing(row, region.c_region),
  147. libraster.Rast_col_to_easting(col, region.c_region))
  148. def get_raster_for_points(poi_vector, raster, column=None):
  149. """Query a raster map for each point feature of a vector
  150. Example ::
  151. >>> from grass.pygrass.vector import VectorTopo
  152. >>> from grass.pygrass.raster import RasterRow
  153. >>> ele = RasterRow('elevation')
  154. >>> copy('schools','myschools','vect')
  155. >>> sch = VectorTopo('myschools')
  156. >>> get_raster_for_points(sch, ele) # doctest: +ELLIPSIS
  157. [(1, 633649.2856743174, 221412.94434781274, 145.06602)...
  158. >>> sch.table.columns.add('elevation','double precision')
  159. >>> 'elevation' in sch.table.columns
  160. True
  161. >>> get_raster_for_points(sch, ele, 'elevation')
  162. True
  163. >>> sch.table.filters.select('NAMESHORT','elevation')
  164. Filters('SELECT NAMESHORT, elevation FROM myschools;')
  165. >>> cur = sch.table.execute()
  166. >>> cur.fetchall() # doctest: +ELLIPSIS
  167. [(u'SWIFT CREEK', 145.06602), ... (u'9TH GRADE CTR', None)]
  168. >>> remove('myschools','vect')
  169. Parameters
  170. -------------
  171. point: point vector object
  172. raster: raster object
  173. column: column name to update
  174. """
  175. from math import isnan
  176. if not column:
  177. result = []
  178. reg = Region()
  179. if not poi_vector.is_open():
  180. poi_vector.open()
  181. if not raster.is_open():
  182. raster.open()
  183. if poi_vector.num_primitive_of('point') == 0:
  184. raise GrassError(_("Vector doesn't contain points"))
  185. for poi in poi_vector.viter('points'):
  186. val = raster.get_value(poi, reg)
  187. if column:
  188. if val is not None and not isnan(val):
  189. poi.attrs[column] = val
  190. else:
  191. if val is not None and not isnan(val):
  192. result.append((poi.id, poi.x, poi.y, val))
  193. else:
  194. result.append((poi.id, poi.x, poi.y, None))
  195. if not column:
  196. return result
  197. else:
  198. poi.attrs.commit()
  199. return True
  200. def r_export(rast, output='', fmt='png', **kargs):
  201. from grass.pygrass.modules import Module
  202. if rast.exist():
  203. output = output if output else "%s_%s.%s" % (rast.name, rast.mapset,
  204. fmt)
  205. Module('r.out.%s' % fmt, input=rast.fullname(), output=output,
  206. overwrite=True, **kargs)
  207. return output
  208. else:
  209. raise ValueError('Raster map does not exist.')
  210. def get_lib_path(modname, libname):
  211. """Return the path of the libname contained in the module. ::
  212. >>> get_lib_path(modname='r.modis', libname='libmodis')
  213. """
  214. from os.path import isdir, join
  215. from os import getenv
  216. if isdir(join(getenv('GISBASE'), 'etc', modname)):
  217. path = join(os.getenv('GISBASE'), 'etc', modname)
  218. elif getenv('GRASS_ADDON_BASE') and \
  219. isdir(join(getenv('GRASS_ADDON_BASE'), 'etc', modname)):
  220. path = join(getenv('GRASS_ADDON_BASE'), 'etc', modname)
  221. elif getenv('GRASS_ADDON_BASE') and \
  222. isdir(join(getenv('GRASS_ADDON_BASE'), modname, modname)):
  223. path = join(os.getenv('GRASS_ADDON_BASE'), modname, modname)
  224. elif isdir(join('..', libname)):
  225. path = join('..', libname)
  226. else:
  227. path = None
  228. return path