wms_drv.py 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911
  1. """!
  2. @brief WMS, WMTS and NASA OnEarth drivers implemented in GRASS using GDAL Python bindings.
  3. List of classes:
  4. - wms_drv::WMSDrv
  5. - wms_drv::BaseRequestMgr
  6. - wms_drv::WMSRequestMgr
  7. - wms_drv::WMTSRequestMgr
  8. - wms_drv::OnEarthRequestMgr
  9. (C) 2012 by the GRASS Development Team
  10. This program is free software under the GNU General Public License
  11. (>=v2). Read the file COPYING that comes with GRASS for details.
  12. @author Stepan Turek <stepan.turek seznam.cz> (Mentor: Martin Landa)
  13. """
  14. import socket
  15. import grass.script as grass
  16. from time import sleep
  17. try:
  18. from osgeo import gdal
  19. from osgeo import gdalconst
  20. except:
  21. grass.fatal(_("Unable to load GDAL python bindings"))
  22. import numpy as Numeric
  23. Numeric.arrayrange = Numeric.arange
  24. from math import pi, floor
  25. from urllib2 import HTTPError
  26. from httplib import HTTPException
  27. try:
  28. from xml.etree.ElementTree import ParseError
  29. except ImportError: # < Python 2.7
  30. from xml.parsers.expat import ExpatError as ParseError
  31. from wms_base import WMSBase, GetSRSParamVal
  32. from wms_cap_parsers import WMTSCapabilitiesTree, OnEarthCapabilitiesTree
  33. from srs import Srs
  34. class WMSDrv(WMSBase):
  35. def _download(self):
  36. """!Downloads data from WMS server using own driver
  37. @return temp_map with downloaded data
  38. """
  39. grass.message(_("Downloading data from WMS server..."))
  40. if "?" in self.params["url"]:
  41. self.params["url"] += "&"
  42. else:
  43. self.params["url"] += "?"
  44. if not self.params['capfile']:
  45. self.cap_file = self._fetchCapabilities(self.params)
  46. else:
  47. self.cap_file = self.params['capfile']
  48. # initialize correct manager according to chosen OGC service
  49. if self.params['driver'] == 'WMTS_GRASS':
  50. req_mgr = WMTSRequestMgr(self.params, self.bbox, self.region, self.proj_srs, self.cap_file)
  51. elif self.params['driver'] == 'WMS_GRASS':
  52. req_mgr = WMSRequestMgr(self.params, self.bbox, self.region, self.tile_size, self.proj_srs)
  53. elif self.params['driver'] == 'OnEarth_GRASS':
  54. req_mgr = OnEarthRequestMgr(self.params, self.bbox, self.region, self.proj_srs, self.cap_file)
  55. # get information about size in pixels and bounding box of raster, where all tiles will be joined
  56. map_region = req_mgr.GetMapRegion()
  57. init = True
  58. temp_map = None
  59. fetch_try = 0
  60. # iterate through all tiles and download them
  61. while True:
  62. if fetch_try == 0:
  63. # get url for request the tile and information for placing the tile into raster with other tiles
  64. tile = req_mgr.GetNextTile()
  65. # if last tile has been already downloaded
  66. if not tile:
  67. break
  68. # url for request the tile
  69. query_url = tile[0]
  70. # the tile size and offset in pixels for placing it into raster where tiles are joined
  71. tile_ref = tile[1]
  72. grass.debug(query_url, 2)
  73. try:
  74. wms_data = self._fetchDataFromServer(query_url, self.params['username'], self.params['password'])
  75. except (IOError, HTTPException) as e:
  76. if HTTPError == type(e) and e.code == 401:
  77. grass.fatal(_("Authorization failed to '%s' when fetching data.\n%s") % (self.params['url'], str(e)))
  78. else:
  79. grass.fatal(_("Unable to fetch data from: '%s'\n%s") % (self.params['url'], str(e)))
  80. temp_tile = self._tempfile()
  81. # download data into temporary file
  82. try:
  83. temp_tile_opened = open(temp_tile, 'wb')
  84. temp_tile_opened.write(wms_data.read())
  85. except IOError as e:
  86. # some servers are not happy with many subsequent requests for tiles done immediately,
  87. # if immediate request was unsuccessful, try to repeat the request after 5s and 30s breaks
  88. # TODO probably servers can return more kinds of errors related to this problem (not only 104)
  89. if socket.error == type(e) and e[0] == 104 and fetch_try < 2:
  90. fetch_try += 1
  91. if fetch_try == 1:
  92. sleep_time = 5
  93. elif fetch_try == 2:
  94. sleep_time = 30
  95. grass.warning(_("Server refused to send data for a tile.\nRequest will be repeated after %d s.") % sleep_time)
  96. sleep(sleep_time)
  97. continue
  98. else:
  99. grass.fatal(_("Unable to write data into tempfile.\n%s") % str(e))
  100. finally:
  101. temp_tile_opened.close()
  102. fetch_try = 0
  103. tile_dataset_info = gdal.Open(temp_tile, gdal.GA_ReadOnly)
  104. if tile_dataset_info is None:
  105. # print error xml returned from server
  106. try:
  107. error_xml_opened = open(temp_tile, 'rb')
  108. err_str = error_xml_opened.read()
  109. except IOError as e:
  110. grass.fatal(_("Unable to read data from tempfile.\n%s") % str(e))
  111. finally:
  112. error_xml_opened.close()
  113. if err_str is not None:
  114. grass.fatal(_("WMS server error: %s") % err_str)
  115. else:
  116. grass.fatal(_("WMS server unknown error") )
  117. temp_tile_pct2rgb = None
  118. if tile_dataset_info.RasterCount == 1 and \
  119. tile_dataset_info.GetRasterBand(1).GetRasterColorTable() is not None:
  120. # expansion of color table into bands
  121. temp_tile_pct2rgb = self._tempfile()
  122. tile_dataset = self._pct2rgb(temp_tile, temp_tile_pct2rgb)
  123. else:
  124. tile_dataset = tile_dataset_info
  125. # initialization of temp_map_dataset, where all tiles are merged
  126. if init:
  127. temp_map = self._tempfile()
  128. driver = gdal.GetDriverByName(self.gdal_drv_format)
  129. metadata = driver.GetMetadata()
  130. if not metadata.has_key(gdal.DCAP_CREATE) or \
  131. metadata[gdal.DCAP_CREATE] == 'NO':
  132. grass.fatal(_('Driver %s does not supports Create() method') % drv_format)
  133. self.temp_map_bands_num = tile_dataset.RasterCount
  134. temp_map_dataset = driver.Create(temp_map, map_region['cols'], map_region['rows'],
  135. self.temp_map_bands_num,
  136. tile_dataset.GetRasterBand(1).DataType)
  137. init = False
  138. # tile is written into temp_map
  139. tile_to_temp_map = tile_dataset.ReadRaster(0, 0, tile_ref['sizeX'], tile_ref['sizeY'],
  140. tile_ref['sizeX'], tile_ref['sizeY'])
  141. temp_map_dataset.WriteRaster(tile_ref['t_cols_offset'], tile_ref['t_rows_offset'],
  142. tile_ref['sizeX'], tile_ref['sizeY'], tile_to_temp_map)
  143. tile_dataset = None
  144. tile_dataset_info = None
  145. grass.try_remove(temp_tile)
  146. grass.try_remove(temp_tile_pct2rgb)
  147. if not temp_map:
  148. return temp_map
  149. # georeferencing and setting projection of temp_map
  150. projection = grass.read_command('g.proj',
  151. flags = 'wf',
  152. epsg =self.params['srs']).rstrip('\n')
  153. temp_map_dataset.SetProjection(projection)
  154. pixel_x_length = (map_region['maxx'] - map_region['minx']) / int(map_region['cols'])
  155. pixel_y_length = (map_region['miny'] - map_region['maxy']) / int(map_region['rows'])
  156. geo_transform = [map_region['minx'] , pixel_x_length , 0.0 , map_region['maxy'] , 0.0 , pixel_y_length]
  157. temp_map_dataset.SetGeoTransform(geo_transform )
  158. temp_map_dataset = None
  159. return temp_map
  160. def _pct2rgb(self, src_filename, dst_filename):
  161. """!Create new dataset with data in dst_filename with bands according to src_filename
  162. raster color table - modified code from gdal utility pct2rgb
  163. @return new dataset
  164. """
  165. out_bands = 4
  166. band_number = 1
  167. # open source file
  168. src_ds = gdal.Open(src_filename)
  169. if src_ds is None:
  170. grass.fatal(_('Unable to open %s ' % src_filename))
  171. src_band = src_ds.GetRasterBand(band_number)
  172. # Build color table
  173. lookup = [ Numeric.arrayrange(256),
  174. Numeric.arrayrange(256),
  175. Numeric.arrayrange(256),
  176. Numeric.ones(256)*255 ]
  177. ct = src_band.GetRasterColorTable()
  178. if ct is not None:
  179. for i in range(min(256,ct.GetCount())):
  180. entry = ct.GetColorEntry(i)
  181. for c in range(4):
  182. lookup[c][i] = entry[c]
  183. # create the working file
  184. gtiff_driver = gdal.GetDriverByName(self.gdal_drv_format)
  185. tif_ds = gtiff_driver.Create(dst_filename,
  186. src_ds.RasterXSize, src_ds.RasterYSize, out_bands)
  187. # do the processing one scanline at a time
  188. for iY in range(src_ds.RasterYSize):
  189. src_data = src_band.ReadAsArray(0,iY,src_ds.RasterXSize,1)
  190. for iBand in range(out_bands):
  191. band_lookup = lookup[iBand]
  192. dst_data = Numeric.take(band_lookup,src_data)
  193. tif_ds.GetRasterBand(iBand+1).WriteArray(dst_data,0,iY)
  194. return tif_ds
  195. class BaseRequestMgr:
  196. """!Base class for request managers.
  197. """
  198. def _computeRequestData(self, bbox, tl_corner, tile_span, tile_size, mat_num_bbox):
  199. """!Initialize data needed for iteration through tiles. Used by WMTS_GRASS and OnEarth_GRASS drivers.
  200. """
  201. epsilon = 1e-15
  202. # request data bbox specified in row and col number
  203. self.t_num_bbox = {}
  204. self.t_num_bbox['min_col'] = int(floor((bbox['minx'] - tl_corner['minx']) / tile_span['x'] + epsilon))
  205. self.t_num_bbox['max_col'] = int(floor((bbox['maxx'] - tl_corner['minx']) / tile_span['x'] - epsilon))
  206. self.t_num_bbox['min_row'] = int(floor((tl_corner['maxy'] - bbox['maxy']) / tile_span['y'] + epsilon))
  207. self.t_num_bbox['max_row'] = int(floor((tl_corner['maxy'] - bbox['miny']) / tile_span['y'] - epsilon))
  208. # Does required bbox intersects bbox of data available on server?
  209. self.intersects = False
  210. for col in ['min_col', 'max_col']:
  211. for row in ['min_row', 'max_row']:
  212. if (self.t_num_bbox['min_row'] <= self.t_num_bbox[row] and self.t_num_bbox[row] <= mat_num_bbox['max_row']) and \
  213. (self.t_num_bbox['min_col'] <= self.t_num_bbox[col] and self.t_num_bbox[col] <= mat_num_bbox['max_col']):
  214. self.intersects = True
  215. if not self.intersects:
  216. grass.warning(_('Region is out of server data extend.'))
  217. self.map_region = None
  218. return
  219. # crop request bbox to server data bbox extend
  220. if self.t_num_bbox['min_col'] < (mat_num_bbox['min_col']):
  221. self.t_num_bbox['min_col'] = int(mat_num_bbox['min_col'])
  222. if self.t_num_bbox['max_col'] > (mat_num_bbox['max_col']):
  223. self.t_num_bbox['max_col'] = int(mat_num_bbox['max_col'])
  224. if self.t_num_bbox['min_row'] < (mat_num_bbox['min_row']):
  225. self.t_num_bbox['min_row'] = int(mat_num_bbox['min_row'])
  226. if self.t_num_bbox['max_row'] > (mat_num_bbox['max_row']):
  227. self.t_num_bbox['max_row'] = int(mat_num_bbox['max_row'])
  228. grass.debug('t_num_bbox: min_col:%d max_col:%d min_row:%d max_row:%d' % (self.t_num_bbox['min_col'], self.t_num_bbox['max_col'], self.t_num_bbox['min_row'], self.t_num_bbox['max_row']), 3)
  229. num_tiles = (self.t_num_bbox['max_col'] - self.t_num_bbox['min_col'] + 1) * (self.t_num_bbox['max_row'] - self.t_num_bbox['min_row'] + 1)
  230. grass.message(_('Fetching %d tiles with %d x %d pixel size per tile...') % (num_tiles, tile_size['x'], tile_size['y']))
  231. # georeference of raster, where tiles will be merged
  232. self.map_region = {}
  233. self.map_region['minx'] = self.t_num_bbox['min_col'] * tile_span['x'] + tl_corner['minx']
  234. self.map_region['maxy'] = tl_corner['maxy'] - (self.t_num_bbox['min_row']) * tile_span['y']
  235. self.map_region['maxx'] = (self.t_num_bbox['max_col'] + 1) * tile_span['x'] + tl_corner['minx']
  236. self.map_region['miny'] = tl_corner['maxy'] - (self.t_num_bbox['max_row'] + 1) * tile_span['y']
  237. # size of raster, where tiles will be merged
  238. self.map_region['cols'] = int(tile_size['x'] * (self.t_num_bbox['max_col'] - self.t_num_bbox['min_col'] + 1))
  239. self.map_region['rows'] = int(tile_size['y'] * (self.t_num_bbox['max_row'] - self.t_num_bbox['min_row'] + 1))
  240. # hold information about current column and row during iteration
  241. self.i_col = self.t_num_bbox['min_col']
  242. self.i_row = self.t_num_bbox['min_row']
  243. # bbox for first tile request
  244. self.query_bbox = {
  245. 'minx' : tl_corner['minx'],
  246. 'maxy' : tl_corner['maxy'],
  247. 'maxx' : tl_corner['minx'] + tile_span['x'],
  248. 'miny' : tl_corner['maxy'] - tile_span['y'],
  249. }
  250. self.tile_ref = {
  251. 'sizeX' : tile_size['x'],
  252. 'sizeY' : tile_size['y']
  253. }
  254. def _isGeoProj(self, proj):
  255. """!Is it geographic projection?
  256. """
  257. if (proj.find("+proj=latlong") != -1 or \
  258. proj.find("+proj=longlat") != -1):
  259. return True
  260. return False
  261. class WMSRequestMgr(BaseRequestMgr):
  262. def __init__(self, params, bbox, region, tile_size, proj_srs, cap_file = None):
  263. """!Initialize data needed for iteration through tiles.
  264. """
  265. self.version = params['wms_version']
  266. self.srs_param = params['srs']
  267. proj = params['proj_name'] + "=" + GetSRSParamVal(params['srs'])
  268. self.url = params['url'] + ("SERVICE=WMS&REQUEST=GetMap&VERSION=%s&LAYERS=%s&WIDTH=%s&HEIGHT=%s&STYLES=%s&TRANSPARENT=%s" % \
  269. (params['wms_version'], params['layers'], tile_size['cols'], tile_size['rows'], params['styles'], \
  270. params['transparent']))
  271. if params['bgcolor']:
  272. self.url += "&BGCOLOR=" + params['bgcolor']
  273. self.url += "&" +proj+ "&" + "FORMAT=" + params['format']
  274. self.bbox = bbox
  275. self.proj_srs = proj_srs
  276. self.tile_rows = tile_size['rows']
  277. self.tile_cols = tile_size['cols']
  278. if params['urlparams'] != "":
  279. self.url += "&" + params['urlparams']
  280. cols = int(region['cols'])
  281. rows = int(region['rows'])
  282. # computes parameters of tiles
  283. self.num_tiles_x = cols / self.tile_cols
  284. self.last_tile_x_size = cols % self.tile_cols
  285. self.tile_length_x = float(self.tile_cols) / float(cols) * (self.bbox['maxx'] - self.bbox['minx'])
  286. self.last_tile_x = False
  287. if self.last_tile_x_size != 0:
  288. self.last_tile_x = True
  289. self.num_tiles_x = self.num_tiles_x + 1
  290. self.num_tiles_y = rows / self.tile_rows
  291. self.last_tile_y_size = rows % self.tile_rows
  292. self.tile_length_y = float(self.tile_rows) / float(rows) * (self.bbox['maxy'] - self.bbox['miny'])
  293. self.last_tile_y = False
  294. if self.last_tile_y_size != 0:
  295. self.last_tile_y = True
  296. self.num_tiles_y = self.num_tiles_y + 1
  297. self.tile_bbox = dict(self.bbox)
  298. self.tile_bbox['maxx'] = self.bbox['minx'] + self.tile_length_x
  299. self.i_x = 0
  300. self.i_y = 0
  301. self.map_region = self.bbox
  302. self.map_region['cols'] = cols
  303. self.map_region['rows'] = rows
  304. def GetMapRegion(self):
  305. """!Get size in pixels and bounding box of raster where all tiles will be merged.
  306. """
  307. return self.map_region
  308. def GetNextTile(self):
  309. """!Get url for tile request from server and information for merging the tile with other tiles
  310. """
  311. tile_ref = {}
  312. if self.i_x >= self.num_tiles_x:
  313. return None
  314. tile_ref['sizeX'] = self.tile_cols
  315. if self.i_x == self.num_tiles_x - 1 and self.last_tile_x:
  316. tile_ref['sizeX'] = self.last_tile_x_size
  317. # set bbox for tile (N, S)
  318. if self.i_y != 0:
  319. self.tile_bbox['miny'] -= self.tile_length_y
  320. self.tile_bbox['maxy'] -= self.tile_length_y
  321. else:
  322. self.tile_bbox['maxy'] = self.bbox['maxy']
  323. self.tile_bbox['miny'] = self.bbox['maxy'] - self.tile_length_y
  324. tile_ref['sizeY'] = self.tile_rows
  325. if self.i_y == self.num_tiles_y - 1 and self.last_tile_y:
  326. tile_ref['sizeY'] = self.last_tile_y_size
  327. query_bbox = self._getQueryBbox(self.tile_bbox, self.proj_srs, self.srs_param, self.version)
  328. query_url = self.url + "&" + "BBOX=%s,%s,%s,%s" % ( query_bbox['minx'], query_bbox['miny'], query_bbox['maxx'], query_bbox['maxy'])
  329. tile_ref['t_cols_offset'] = int(self.tile_cols * self.i_x)
  330. tile_ref['t_rows_offset'] = int(self.tile_rows * self.i_y)
  331. if self.i_y >= self.num_tiles_y - 1:
  332. self.i_y = 0
  333. self.i_x += 1
  334. # set bbox for next tile (E, W)
  335. self.tile_bbox['maxx'] += self.tile_length_x
  336. self.tile_bbox['minx'] += self.tile_length_x
  337. else:
  338. self.i_y += 1
  339. return query_url, tile_ref
  340. def _getQueryBbox(self, bbox, proj, srs_param, version):
  341. """!Creates query bbox (used in request URL)
  342. Mostly bbox is not modified but if WMS standard is 1.3.0 and
  343. projection is geographic, the bbox x and y are in most cases flipped.
  344. """
  345. # CRS:84 and CRS:83 are exception (CRS:83 and CRS:27 need to be tested)
  346. if srs_param in [84, 83] or version != '1.3.0':
  347. return bbox
  348. elif Srs(GetSRSParamVal(srs_param)).axisorder == 'yx':
  349. return self._flipBbox(bbox)
  350. return bbox
  351. def _flipBbox(self, bbox):
  352. """
  353. Flips bbox values between this keys:
  354. maxy -> maxx
  355. maxx -> maxy
  356. miny -> minx
  357. minx -> miny
  358. @return copy of bbox with flipped coordinates
  359. """
  360. temp_bbox = dict(bbox)
  361. new_bbox = {}
  362. new_bbox['maxy'] = temp_bbox['maxx']
  363. new_bbox['miny'] = temp_bbox['minx']
  364. new_bbox['maxx'] = temp_bbox['maxy']
  365. new_bbox['minx'] = temp_bbox['miny']
  366. return new_bbox
  367. class WMTSRequestMgr(BaseRequestMgr):
  368. def __init__(self, params, bbox, region, proj_srs, cap_file = None):
  369. """!Initializes data needed for iteration through tiles.
  370. """
  371. self.proj_srs = proj_srs
  372. self.meters_per_unit = None
  373. # constant defined in WMTS standard (in meters)
  374. self.pixel_size = 0.00028
  375. # parse capabilities file
  376. try:
  377. # checks all elements needed by this class,
  378. # invalid elements are removed
  379. cap_tree = WMTSCapabilitiesTree(cap_file)
  380. except ParseError as error:
  381. grass.fatal(_("Unable to parse tile service file.\n%s\n") % str(error))
  382. self.xml_ns = cap_tree.getxmlnshandler()
  383. root = cap_tree.getroot()
  384. # get layer tile matrix sets with required projection
  385. mat_sets = self._getMatSets(root, params['layers'], params['srs']) #[[TileMatrixSet, TileMatrixSetLink], ....]
  386. # TODO: what if more tile matrix sets have required srs (returned more than 1)?
  387. mat_set = mat_sets[0][0]
  388. mat_set_link = mat_sets[0][1]
  389. params['tile_matrix_set'] = mat_set.find(self.xml_ns.NsOws('Identifier')).text
  390. # find tile matrix with resolution closest and smaller to wanted resolution
  391. tile_mat = self._findTileMats(mat_set.findall(self.xml_ns.NsWmts('TileMatrix')), region, bbox)
  392. # get extend of data available on server expressed in max/min rows and cols of tile matrix
  393. mat_num_bbox = self._getMatSize(tile_mat, mat_set_link)
  394. # initialize data needed for iteration through tiles
  395. self._computeRequestData(tile_mat, params, bbox, mat_num_bbox, self._getMatSetSrs(mat_set))
  396. def GetMapRegion(self):
  397. """!Get size in pixels and bounding box of raster where all tiles will be merged.
  398. """
  399. return self.map_region
  400. def _getMatSets(self, root, layer_name, srs):
  401. """!Get matrix sets which are available for chosen layer and have required EPSG.
  402. """
  403. contents = root.find(self.xml_ns.NsWmts('Contents'))
  404. layers = contents.findall(self.xml_ns.NsWmts('Layer'))
  405. ch_layer = None
  406. for layer in layers:
  407. layer_id = layer.find(self.xml_ns.NsOws('Identifier')).text
  408. if layer_id == layer_name:
  409. ch_layer = layer
  410. break
  411. if ch_layer is None:
  412. grass.fatal(_("Layer '%s' was not found in capabilities file") % layer_name)
  413. mat_set_links = ch_layer.findall(self.xml_ns.NsWmts('TileMatrixSetLink'))
  414. suitable_mat_sets = []
  415. tileMatrixSets = contents.findall(self.xml_ns.NsWmts('TileMatrixSet'))
  416. for link in mat_set_links:
  417. mat_set_link_id = link.find(self.xml_ns.NsWmts('TileMatrixSet')).text
  418. for mat_set in tileMatrixSets:
  419. mat_set_id = mat_set.find(self.xml_ns.NsOws('Identifier')).text
  420. if mat_set_id != mat_set_link_id:
  421. continue
  422. mat_set_srs = self._getMatSetSrs(mat_set)
  423. if Srs(mat_set_srs).getcode() == (GetSRSParamVal(srs)).upper():
  424. suitable_mat_sets.append([mat_set, link])
  425. if not suitable_mat_sets:
  426. grass.fatal(_("Layer '%s' is not available with %s code.") % (layer_name, "EPSG:" + str(srs)))
  427. return suitable_mat_sets # [[TileMatrixSet, TileMatrixSetLink], ....]
  428. def _getMatSetSrs(self, mat_set):
  429. return mat_set.find(self.xml_ns.NsOws('SupportedCRS')).text
  430. def _findTileMats(self, tile_mats, region, bbox):
  431. """!Find best tile matrix set for requested resolution.
  432. """
  433. scale_dens = []
  434. scale_dens.append((bbox['maxy'] - bbox['miny']) / region['rows'] * self._getMetersPerUnit() / self.pixel_size)
  435. scale_dens.append((bbox['maxx'] - bbox['minx']) / region['cols'] * self._getMetersPerUnit() / self.pixel_size)
  436. scale_den = min(scale_dens)
  437. first = True
  438. for t_mat in tile_mats:
  439. mat_scale_den = float(t_mat.find(self.xml_ns.NsWmts('ScaleDenominator')).text)
  440. if first:
  441. best_scale_den = mat_scale_den
  442. best_t_mat = t_mat
  443. first = False
  444. continue
  445. best_diff = best_scale_den - scale_den
  446. mat_diff = mat_scale_den - scale_den
  447. if (best_diff < mat_diff and mat_diff < 0) or \
  448. (best_diff > mat_diff and best_diff > 0):
  449. best_t_mat = t_mat
  450. best_scale_den = mat_scale_den
  451. return best_t_mat
  452. def _getMetersPerUnit(self):
  453. """!Get coefficient which allows converting units of request projection into meters.
  454. """
  455. if self.meters_per_unit:
  456. return self.meters_per_unit
  457. # for geographic projection
  458. if self._isGeoProj(self.proj_srs):
  459. proj_params = self.proj_srs.split(' ')
  460. for param in proj_params:
  461. if '+a' in param:
  462. a = float(param.split('=')[1])
  463. break
  464. equator_perim = 2 * pi * a
  465. # meters per degree on equator
  466. self.meters_per_unit = equator_perim / 360
  467. # other units
  468. elif '+to_meter' in self.proj_srs:
  469. proj_params = self.proj_srs.split(' ')
  470. for param in proj_params:
  471. if '+to_meter' in param:
  472. self.meters_per_unit = 1/float(param.split('=')[1])
  473. break
  474. # coordinate system in meters
  475. else:
  476. self.meters_per_unit = 1
  477. return self.meters_per_unit
  478. def _getMatSize(self, tile_mat, mat_set_link):
  479. """!Get rows and cols extend of data available on server for chosen layer and tile matrix.
  480. """
  481. # general tile matrix size
  482. mat_num_bbox = {}
  483. mat_num_bbox['min_col'] = mat_num_bbox['min_row'] = 0
  484. mat_num_bbox['max_col'] = int(tile_mat.find(self.xml_ns.NsWmts('MatrixWidth')).text) - 1
  485. mat_num_bbox['max_row'] = int(tile_mat.find(self.xml_ns.NsWmts('MatrixHeight')).text) - 1
  486. # get extend restriction in TileMatrixSetLink for the tile matrix, if exists
  487. tile_mat_set_limits = mat_set_link.find((self.xml_ns.NsWmts('TileMatrixSetLimits')))
  488. if tile_mat_set_limits is None:
  489. return mat_num_bbox
  490. tile_mat_id = tile_mat.find(self.xml_ns.NsOws('Identifier')).text
  491. tile_mat_limits = tile_mat_set_limits.findall(self.xml_ns.NsWmts('TileMatrixLimits'))
  492. for limit in tile_mat_limits:
  493. limit_tile_mat = limit.find(self.xml_ns.NsWmts('TileMatrix'))
  494. limit_id = limit_tile_mat.text
  495. if limit_id == tile_mat_id:
  496. for i in [['min_row', 'MinTileRow'], ['max_row', 'MaxTileRow'], \
  497. ['min_col', 'MinTileCol'], ['max_col', 'MaxTileCol']]:
  498. i_tag = limit.find(self.xml_ns.NsWmts(i[1]))
  499. mat_num_bbox[i[0]] = int(i_tag.text)
  500. if i[0] in ('max_row', 'max_col'):
  501. mat_num_bbox[i[0]] = mat_num_bbox[i[0]] - 1
  502. break
  503. return mat_num_bbox
  504. def _computeRequestData(self, tile_mat, params, bbox, mat_num_bbox, mat_set_srs):
  505. """!Initialize data needed for iteration through tiles.
  506. """
  507. scale_den = float(tile_mat.find(self.xml_ns.NsWmts('ScaleDenominator')).text)
  508. pixel_span = scale_den * self.pixel_size / self._getMetersPerUnit()
  509. tl_str = tile_mat.find(self.xml_ns.NsWmts('TopLeftCorner')).text.split(' ')
  510. tl_corner = {}
  511. tl_corner['minx'] = float(tl_str[0])
  512. tl_corner['maxy'] = float(tl_str[1])
  513. #TODO do it more generally WMS cap parser may use it in future(not needed now)???
  514. s = Srs(mat_set_srs) #NOTE not used params['srs'], it is just number, encoding needed
  515. # TODO needs to be tested, tried only on http://www.landesvermessung.sachsen.de/geoserver/gwc/service/wmts?:
  516. if s.getcode() == 'EPSG:4326' and s.encoding in ('uri', 'urn'):
  517. grass.warning('switch')
  518. (tl_corner['minx'], tl_corner['maxy']) = (tl_corner['maxy'], tl_corner['minx'])
  519. else:
  520. grass.warning('no switch')
  521. tile_span = {}
  522. self.tile_size = {}
  523. self.tile_size['x'] = int(tile_mat.find(self.xml_ns.NsWmts('TileWidth')).text)
  524. tile_span['x'] = pixel_span * self.tile_size['x']
  525. self.tile_size['y'] = int(tile_mat.find(self.xml_ns.NsWmts('TileHeight')).text)
  526. tile_span['y'] = pixel_span * self.tile_size['y']
  527. self.url = params['url'] + ("SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&" \
  528. "LAYER=%s&STYLE=%s&FORMAT=%s&TILEMATRIXSET=%s&TILEMATRIX=%s" % \
  529. (params['layers'], params['styles'], params['format'],
  530. params['tile_matrix_set'], tile_mat.find(self.xml_ns.NsOws('Identifier')).text ))
  531. BaseRequestMgr._computeRequestData(self, bbox, tl_corner, tile_span, self.tile_size, mat_num_bbox)
  532. def GetNextTile(self):
  533. """!Get url for tile request from server and information for merging the tile with other tiles.
  534. """
  535. if not self.intersects or self.i_col > self.t_num_bbox['max_col']:
  536. return None
  537. query_url = self.url + "&TILECOL=%i&TILEROW=%i" % (int(self.i_col), int(self.i_row))
  538. self.tile_ref['t_cols_offset'] = int(self.tile_size['x'] * (self.i_col - self.t_num_bbox['min_col']))
  539. self.tile_ref['t_rows_offset'] = int(self.tile_size['y'] * (self.i_row - self.t_num_bbox['min_row']))
  540. if self.i_row >= self.t_num_bbox['max_row']:
  541. self.i_row = self.t_num_bbox['min_row']
  542. self.i_col += 1
  543. else:
  544. self.i_row += 1
  545. return query_url, self.tile_ref
  546. class OnEarthRequestMgr(BaseRequestMgr):
  547. def __init__(self, params, bbox, region, proj_srs, tile_service):
  548. """!Initializes data needed for iteration through tiles.
  549. """
  550. try:
  551. # checks all elements needed by this class,
  552. # invalid elements are removed
  553. self.cap_tree = OnEarthCapabilitiesTree(tile_service)
  554. except ParseError as error:
  555. grass.fatal(_("Unable to parse tile service file.\n%s\n") % str(error))
  556. root = self.cap_tree.getroot()
  557. # parse tile service file and get needed data for making tile requests
  558. url, self.tile_span, t_patt_bbox, self.tile_size = self._parseTileService(root, bbox, region, params)
  559. self.url = url
  560. self.url[0] = params['url'] + url[0]
  561. # initialize data needed for iteration through tiles
  562. self._computeRequestData(bbox, t_patt_bbox, self.tile_span, self.tile_size)
  563. def GetMapRegion(self):
  564. """!Get size in pixels and bounding box of raster where all tiles will be merged.
  565. """
  566. return self.map_region
  567. def _parseTileService(self, root, bbox, region, params):
  568. """!Get data from tile service file
  569. """
  570. tiled_patterns = root.find('TiledPatterns')
  571. tile_groups = self._getAllTiledGroup(tiled_patterns)
  572. if not tile_groups:
  573. grass.fatal(_("Unable to parse tile service file. \n No tag '%s' was found.") % 'TiledGroup')
  574. req_group = None
  575. for group in tile_groups:
  576. name = group.find('Name')
  577. if name.text == params['layers']:
  578. req_group = group
  579. break
  580. if req_group is None:
  581. grass.fatal(_("Tiled group '%s' was not found in tile service file") % params['layers'])
  582. group_t_patts = req_group.findall('TilePattern')
  583. best_patt = self._parseTilePattern(group_t_patts, bbox, region)
  584. urls = best_patt.text.split('\n')
  585. if params['urlparams']:
  586. url = self._insTimeToTilePatternUrl(params['urlparams'], urls)
  587. else:
  588. url = urls[0]
  589. for u in urls:
  590. if not 'time=${' in u:
  591. url = u
  592. url, t_bbox, width, height = self.cap_tree.gettilepatternurldata(url)
  593. tile_span = {}
  594. tile_span['x'] = abs(t_bbox[0] - t_bbox[2])
  595. tile_span['y'] = abs(t_bbox[1] - t_bbox[3])
  596. tile_pattern_bbox = req_group.find('LatLonBoundingBox')
  597. t_patt_bbox = {}
  598. for s in ['minx', 'miny', 'maxx', 'maxy']:
  599. t_patt_bbox[s] = float(tile_pattern_bbox.get(s))
  600. tile_size = {}
  601. tile_size['x'] = width
  602. tile_size['y'] = height
  603. return url, tile_span, t_patt_bbox, tile_size
  604. def _getAllTiledGroup(self, parent, tiled_groups = None):
  605. """!Get all 'TileGroup' elements
  606. """
  607. if not tiled_groups:
  608. tiled_groups = []
  609. tiled_groups += parent.findall('TiledGroup')
  610. new_groups = parent.findall('TiledGroups')
  611. for group in new_groups:
  612. self._getAllTiledGroup(group, tiled_groups)
  613. return tiled_groups
  614. def _parseTilePattern(self, group_t_patts, bbox, region):
  615. """!Find best tile pattern for requested resolution.
  616. """
  617. res = {}
  618. res['y'] = (bbox['maxy'] - bbox['miny']) / region['rows']
  619. res['x'] = (bbox['maxx'] - bbox['minx']) / region['cols']
  620. if res['x'] < res['y']:
  621. comp_res = 'x'
  622. else:
  623. comp_res = 'y'
  624. t_res = {}
  625. best_patt = None
  626. for pattern in group_t_patts:
  627. url, t_bbox, width, height = self.cap_tree.gettilepatternurldata(pattern.text.split('\n')[0])
  628. t_res['x'] = abs(t_bbox[0] - t_bbox[2]) / width
  629. t_res['y'] = abs(t_bbox[1] - t_bbox[3]) / height
  630. if best_patt is None:
  631. best_res = t_res[comp_res]
  632. best_patt = pattern
  633. first = False
  634. continue
  635. best_diff = best_res - res[comp_res]
  636. tile_diff = t_res[comp_res] - res[comp_res]
  637. if (best_diff < tile_diff and tile_diff < 0) or \
  638. (best_diff > tile_diff and best_diff > 0):
  639. best_res = t_res[comp_res]
  640. best_patt = pattern
  641. return best_patt
  642. def _insTimeToTilePatternUrl(self, url_params, urls):
  643. """!Time can be variable in some urls in OnEarth TMS.
  644. Insert requested time from 'urlparams' into the variable if any url of urls contains the variable.
  645. """
  646. url = None
  647. not_sup_params = []
  648. url_params_list = url_params.split('&')
  649. for param in url_params_list:
  650. try:
  651. k, v = param.split('=')
  652. except ValueError:
  653. grass.warning(_("Wrong form of parameter '%s' in '%s'. \n \
  654. The parameter was ignored.") % (param, 'urlparams'))
  655. if k != 'time':
  656. not_sup_params.append(k)
  657. continue
  658. has_time_var = False
  659. for url in urls:
  660. url_p_idxs = self.geturlparamidxs(url, k)
  661. if not url_p_idxs:
  662. continue
  663. url_p_value = url[url_p_idxs[0] + len(k + '=') : url_p_idxs[1]]
  664. if url_p_value[:2] == '${' and \
  665. url_p_value[len(url_p_value) - 1] == '}':
  666. url = url[:url_p_idxs[0]] + param + url[url_p_idxs[1]:]
  667. has_time_var = True
  668. break
  669. if not has_time_var:
  670. grass.warning(_("Parameter '%s' in '%s' is not variable in tile pattern url.") % (k, 'urlparams'))
  671. if not_sup_params:
  672. grass.warning(_("%s driver supports only '%s' parameter in '%s'. Other parameters are ignored.") % \
  673. ('OnEarth GRASS', 'time', 'urlparams'))
  674. return url
  675. def _computeRequestData(self, bbox, t_patt_bbox, tile_span, tile_size):
  676. """!Initialize data needed for iteration through tiles.
  677. """
  678. epsilon = 1e-15
  679. mat_num_bbox = {}
  680. mat_num_bbox['min_row'] = mat_num_bbox['min_col'] = 0
  681. mat_num_bbox['max_row'] = floor((t_patt_bbox['maxy'] - t_patt_bbox['miny'])/ tile_span['y'] + epsilon)
  682. mat_num_bbox['max_col'] = floor((t_patt_bbox['maxx'] - t_patt_bbox['minx'])/ tile_span['x'] + epsilon)
  683. BaseRequestMgr._computeRequestData(self, bbox, t_patt_bbox, self.tile_span, self.tile_size, mat_num_bbox)
  684. def GetNextTile(self):
  685. """!Get url for tile request from server and information for merging the tile with other tiles
  686. """
  687. if self.i_col > self.t_num_bbox['max_col']:
  688. return None
  689. x_offset = self.tile_span['x'] * self.i_col
  690. y_offset = self.tile_span['y'] * self.i_row
  691. query_url = self.url[0] + "&" + "bbox=%s,%s,%s,%s" % (float(self.query_bbox['minx'] + x_offset),
  692. float(self.query_bbox['miny'] - y_offset),
  693. float(self.query_bbox['maxx'] + x_offset),
  694. float(self.query_bbox['maxy'] - y_offset)) + self.url[1]
  695. self.tile_ref['t_cols_offset'] = int(self.tile_size['y'] * (self.i_col - self.t_num_bbox['min_col']))
  696. self.tile_ref['t_rows_offset'] = int(self.tile_size['x'] * (self.i_row - self.t_num_bbox['min_row']))
  697. if self.i_row >= self.t_num_bbox['max_row']:
  698. self.i_row = self.t_num_bbox['min_row']
  699. self.i_col += 1
  700. else:
  701. self.i_row += 1
  702. return query_url, self.tile_ref