wms_drv.py 36 KB

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