wms_drv.py 37 KB

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