wms_drv.py 37 KB

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