r.tileset.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  1. #!/usr/bin/env python
  2. ############################################################################
  3. #
  4. # MODULE: r.tileset
  5. #
  6. # AUTHOR(S): Cedric Shock
  7. # Updated for GRASS7 by Martin Landa, 2009
  8. #
  9. # PURPOSE: To produce tilings of regions in other projections.
  10. #
  11. # COPYRIGHT: (C) 2006-2009 by Cedric Shoc, Martin Landa, and GRASS development team
  12. #
  13. # This program is free software under the GNU General
  14. # Public License (>=v2). Read the file COPYING that
  15. # comes with GRASS for details.
  16. #
  17. #############################################################################
  18. # Bugs:
  19. # Does not know about meridians in projections. However, unlike the usual
  20. # hack used to find meridians, this code is perfectly happy with arbitrary
  21. # rotations and flips
  22. # The following are planned to be fixed in a future version, if it turns out
  23. # to be necessary for someone:
  24. # Does not generate optimal tilings. This means that between an appropriate
  25. # projection for a region and latitude longitude projection, in the
  26. # degenerate case, it may create tiles demanding up to twice the necessary
  27. # information. Requesting data from cylindrical projections near their poles
  28. # results in divergence. You really don't want to use source data from
  29. # someone who put it in a cylindrical projection near a pole, do you?
  30. # Not generating "optimal" tilings has another side effect; the sanity
  31. # of the destination region will not carry over to generating tiles of
  32. # realistic aspect ratio. This might be a problem for some WMS servers
  33. # presenting data in a highly inappropriate projection. Do you really
  34. # want their data?
  35. #%Module
  36. #% description: Produces tilings of the source projection for use in the destination region and projection.
  37. #% keywords: raster, tiling
  38. #%End
  39. #%flag
  40. #% key: g
  41. #% description: Produces shell script output
  42. #%end
  43. #%flag
  44. #% key: w
  45. #% description: Produces web map server query string output
  46. #%end
  47. #%option
  48. #% key: region
  49. #% type: string
  50. #% description: Name of region to use instead of current region for bounds and resolution
  51. #%end
  52. #%option
  53. #% key: sourceproj
  54. #% type: string
  55. #% description: Source projection
  56. #% required : yes
  57. #%end
  58. #%option
  59. #% key: sourcescale
  60. #% type: string
  61. #% description: Conversion factor from units to meters in source projection
  62. #% answer : 1
  63. #%end
  64. #%option
  65. #% key: destproj
  66. #% type: string
  67. #% description: Destination projection, defaults to this location's projection
  68. #% required : no
  69. #%end
  70. #%option
  71. #% key: destscale
  72. #% type: string
  73. #% description: Conversion factor from units to meters in source projection
  74. #% required : no
  75. #%end
  76. #%option
  77. #% key: maxcols
  78. #% type: integer
  79. #% description: Maximum number of columns for a tile in the source projection
  80. #% answer: 1024
  81. #%end
  82. #%option
  83. #% key: maxrows
  84. #% type: integer
  85. #% description: Maximum number of rows for a tile in the source projection
  86. #% answer: 1024
  87. #%end
  88. #%option
  89. #% key: overlap
  90. #% type: integer
  91. #% description: Number of cells tiles should overlap in each direction
  92. #% answer: 0
  93. #%end
  94. #%option
  95. #% key: fs
  96. #% type: string
  97. #% description: Output field separator
  98. #% answer: |
  99. #%end
  100. #%option
  101. #% key: v
  102. #% type: integer
  103. #% description: Verbosity level
  104. #% answer: 0
  105. #%end
  106. # Data structures used in this program:
  107. # A bounding box:
  108. # 0 -> left, 1-> bottom, 2->right, 3-> top
  109. # A border:
  110. # An array of points indexed by 0 for "x" and 4 for "y" + by number 0, 1, 2, and 3
  111. # A reprojector [0] is name of source projection, [1] is name of destination
  112. # A projection - [0] is proj.4 text, [1] is scale
  113. import sys
  114. import subprocess
  115. import tempfile
  116. import math
  117. from grass.script import core as grass
  118. def bboxToPoints(bbox):
  119. """Make points that are the corners of a bounding box"""
  120. points = []
  121. points.append((bbox['w'], bbox['s']))
  122. points.append((bbox['w'], bbox['n']))
  123. points.append((bbox['e'], bbox['n']))
  124. points.append((bbox['e'], bbox['s']))
  125. return points
  126. def pointsToBbox(points):
  127. bbox = {}
  128. min_x = min_y = max_x = max_y = None
  129. for point in points:
  130. if not min_x:
  131. min_x = max_x = point[0]
  132. if not min_y:
  133. min_y = max_y = point[1]
  134. if min_x > point[0]:
  135. min_x = point[0]
  136. if max_x < point[0]:
  137. max_x = point[0]
  138. if min_y > point[1]:
  139. min_y = point[1]
  140. if max_y < point[1]:
  141. max_y = point[1]
  142. bbox['n'] = max_y
  143. bbox['s'] = min_y
  144. bbox['w'] = min_x
  145. bbox['e'] = max_x
  146. return bbox
  147. def project(file, source, dest):
  148. """Projects point (x, y) using projector"""
  149. points = []
  150. ret = grass.read_command('m.proj',
  151. quiet = True,
  152. flags = 'd',
  153. proj_in = source['proj'],
  154. proj_out = dest['proj'],
  155. fs = ';,;',
  156. input = file)
  157. if not ret:
  158. grass.fatal(cs2cs + ' failed')
  159. for line in ret.splitlines():
  160. p_x2, p_y2, p_z2 = map(float, line.split(';'))
  161. points.append((p_x2 / dest['scale'], p_y2 / dest['scale']))
  162. return points
  163. def projectPoints(points, source, dest):
  164. """Projects a list of points"""
  165. dest_points = []
  166. input = tempfile.NamedTemporaryFile(mode="wt")
  167. for point in points:
  168. input.file.write('%f;%f\n' % \
  169. (point[0] * source['scale'],
  170. point[1] * source['scale']))
  171. input.file.flush()
  172. dest_points = project(input.name, source, dest)
  173. return dest_points
  174. def sideLengths(points, xmetric, ymetric):
  175. """Find the length of sides of a set of points from one to the next"""
  176. ret = []
  177. for i in range(len(points)):
  178. x1, y1 = points[i]
  179. j = i + 1
  180. if j >= len(points):
  181. j = 0
  182. sl_x = (points[j][0] - points[i][0]) * xmetric
  183. sl_y = (points[j][1] - points[i][1]) * ymetric
  184. sl_d = math.sqrt(sl_x * sl_x + sl_y * sl_y)
  185. ret.append(sl_d)
  186. return { 'x' : (ret[1], ret[3]),
  187. 'y' : (ret[0], ret[2]) }
  188. def bboxesIntersect(bbox_1, bbox_2):
  189. """Determine if two bounding boxes intersect"""
  190. bi_a1 = (bbox_1['w'], bbox_1['s'])
  191. bi_a2 = (bbox_1['e'], bbox_1['n'])
  192. bi_b1 = (bbox_2['w'], bbox_2['s'])
  193. bi_b2 = (bbox_2['e'], bbox_2['n'])
  194. cin = [False, False]
  195. for i in (0, 1):
  196. if (bi_a1[i] <= bi_b1[i] and bi_a2[i] >= bi_b2[i]) or \
  197. (bi_a1[i] <= bi_b1[i] and bi_a2[i] >= bi_b2[i]) or \
  198. (bi_a1[i] <= bi_b1[i] and bi_a1[i] >= bi_b2[i]) or \
  199. (bi_a2[i] <= bi_b1[i] and bi_a2[i] >= bi_b2[i]):
  200. cin[i] = True
  201. if cin[0] and cin[1]:
  202. return True
  203. return False
  204. def main():
  205. # Take into account those extra pixels we'll be a addin'
  206. max_cols = int(options['maxcols']) - int(options['overlap'])
  207. max_rows = int(options['maxrows']) - int(options['overlap'])
  208. # destination projection
  209. if not options['destproj']:
  210. dest_proj = grass.read_command('g.proj',
  211. quiet = True,
  212. flags = 'jf').rstrip('\n')
  213. if not dest_proj:
  214. grass.fatal('g.proj failed')
  215. else:
  216. dest_proj = options['destproj']
  217. grass.debug("Getting destination projection -> '%s'" % dest_proj)
  218. # projection scale
  219. if not options['destscale']:
  220. ret = grass.parse_command('g.proj',
  221. quiet = True,
  222. flags = 'j')
  223. if not ret:
  224. grass.fatal('g.proj failed')
  225. dest_scale = ret['+to_meter'].strip()
  226. else:
  227. dest_scale = options['destscale']
  228. grass.debug('Getting destination projection scale -> %s' % dest_scale)
  229. # set up the projections
  230. srs_source = { 'proj' : options['sourceproj'],
  231. 'scale' : float(options['sourcescale']) }
  232. srs_dest = { 'proj' : dest_proj,
  233. 'scale' : float(dest_scale) }
  234. if options['region']:
  235. grass.run_command('g.region',
  236. quiet = True,
  237. region = options['region'])
  238. dest_bbox = grass.region()
  239. grass.debug('Getting destination region')
  240. # project the destination region into the source:
  241. grass.verbose('Projecting destination region into source...')
  242. dest_bbox_points = bboxToPoints(dest_bbox)
  243. dest_bbox_source_points = projectPoints(dest_bbox_points,
  244. source = srs_dest,
  245. dest = srs_source)
  246. source_bbox = pointsToBbox(dest_bbox_source_points)
  247. grass.verbose('Projecting source bounding box into destination...')
  248. source_bbox_points = bboxToPoints(source_bbox)
  249. source_bbox_dest_points = projectPoints(source_bbox_points,
  250. source = srs_source,
  251. dest = srs_dest)
  252. x_metric = 1 / dest_bbox['ewres']
  253. y_metric = 1 / dest_bbox['nsres']
  254. grass.verbose('Computing length of sides of source bounding box...')
  255. source_bbox_dest_lengths = sideLengths(source_bbox_dest_points,
  256. x_metric, y_metric)
  257. # Find the skewedness of the two directions.
  258. # Define it to be greater than one
  259. # In the direction (x or y) in which the world is least skewed (ie north south in lat long)
  260. # Divide the world into strips. These strips are as big as possible contrained by max_
  261. # In the other direction do the same thing.
  262. # Theres some recomputation of the size of the world that's got to come in here somewhere.
  263. # For now, however, we are going to go ahead and request more data than is necessary.
  264. # For small regions far from the critical areas of projections this makes very little difference
  265. # in the amount of data gotten.
  266. # We can make this efficient for big regions or regions near critical points later.
  267. bigger = []
  268. bigger.append(max(source_bbox_dest_lengths['x']))
  269. bigger.append(max(source_bbox_dest_lengths['y']))
  270. maxdim = (max_cols, max_rows)
  271. # Compute the number and size of tiles to use in each direction
  272. # I'm making fairly even sized tiles
  273. # They differer from each other in height and width only by one cell
  274. # I'm going to make the numbers all simpler and add this extra cell to
  275. # every tile.
  276. grass.message('Computing tiling...')
  277. tiles = [-1, -1]
  278. tile_base_size = [-1, -1]
  279. tiles_extra_1 = [-1, -1]
  280. tile_size = [-1, -1]
  281. tileset_size = [-1, -1]
  282. tile_size_overlap = [-1, -1]
  283. for i in range(len(bigger)):
  284. # make these into integers.
  285. # round up
  286. bigger[i] = int(bigger[i] + 1)
  287. tiles[i] = int((bigger[i] / maxdim[i]) + 1)
  288. tile_size[i] = tile_base_size[i] = int(bigger[i] / tiles[i])
  289. tiles_extra_1[i] = int(bigger[i] % tiles[i])
  290. # This is adding the extra pixel (remainder) to all of the tiles:
  291. if tiles_extra_1[i] > 0:
  292. tile_size[i] = tile_base_size[i] + 1
  293. tileset_size[i] = int(tile_size[i] * tiles[i])
  294. # Add overlap to tiles (doesn't effect tileset_size
  295. tile_size_overlap[i] = tile_size[i] + int(options['overlap'])
  296. grass.verbose("There will be %d by %d tiles each %d by %d cells" % \
  297. (tiles[0], tiles[1], tile_size[0], tile_size[1]))
  298. ximax = tiles[0]
  299. yimax = tiles[1]
  300. min_x = source_bbox['w']
  301. min_y = source_bbox['s']
  302. max_x = source_bbox['e']
  303. max_y = source_bbox['n']
  304. span_x = (max_x - min_x)
  305. span_y = (max_y - min_y)
  306. xi = 0
  307. tile_bbox = { 'w' : -1, 's': -1, 'e' : -1, 'n' : -1 }
  308. while xi < ximax:
  309. tile_bbox['w'] = min_x + (xi * tile_size[0] / tileset_size[0]) * span_x
  310. tile_bbox['e'] = min_x + ((xi + 1) * tile_size_overlap[0] / tileset_size[0]) * span_x
  311. yi = 0
  312. while yi < yimax:
  313. tile_bbox['s'] = min_y + (yi * tile_size[1] / tileset_size[1]) * span_y
  314. tile_bbox['n'] = min_y + ((yi + 1) * tile_size_overlap[1] / tileset_size[1]) * span_y
  315. tile_bbox_points = bboxToPoints(tile_bbox)
  316. tile_dest_bbox_points = projectPoints(tile_bbox_points,
  317. source = srs_source,
  318. dest = srs_dest)
  319. tile_dest_bbox = pointsToBbox(tile_dest_bbox_points)
  320. if bboxesIntersect(tile_dest_bbox, dest_bbox):
  321. if flags['w']:
  322. print "bbox=%s,%s,%s,%s&width=%s&height=%s" % \
  323. (tile_bbox['w'], tile_bbox['s'], tile_bbox['e'], tile_bbox['n'],
  324. tile_size_overlap[0], tile_size_overlap[1])
  325. elif flags['g']:
  326. print "w=%s;s=%s;e=%s;n=%s;cols=%s;rows=%s" % \
  327. (tile_bbox['w'], tile_bbox['s'], tile_bbox['e'], tile_bbox['n'],
  328. tile_size_overlap[0], tile_size_overlap[1])
  329. else:
  330. fs = options['fs']
  331. print "%s%s%s%s%s%s%s%s%s%s%s" % \
  332. (tile_bbox['w'], fs, tile_bbox['s'], fs, tile_bbox['e'], fs, tile_bbox['n'], fs,
  333. tile_size_overlap[0], fs, tile_size_overlap[1])
  334. yi += 1
  335. xi += 1
  336. if __name__ == "__main__":
  337. cs2cs = 'cs2cs'
  338. options, flags = grass.parser()
  339. sys.exit(main())