space_time_datasets.py 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994
  1. """!@package grass.temporal
  2. @brief GRASS Python scripting module (temporal GIS functions)
  3. Temporal GIS related functions to be used in Python scripts.
  4. (C) 2008-2011 by the GRASS Development Team
  5. This program is free software under the GNU General Public
  6. License (>=v2). Read the file COPYING that comes with GRASS
  7. for details.
  8. >>> import grass.script as grass
  9. >>> grass.run_command("r3.mapcalc", overwrite=True, expression="str3ds_map_test_case = 1")
  10. 0
  11. >>> grass.run_command("v.random", overwrite=True, output="stvds_map_test_case",
  12. ... n=100, zmin=0, zmax=100, flags="z", column="elevation")
  13. 0
  14. @author Soeren Gebbert
  15. """
  16. import getpass
  17. from ctypes import *
  18. import grass.lib.gis as libgis
  19. import grass.lib.raster as libraster
  20. import grass.lib.vector as libvector
  21. import grass.lib.raster3d as libraster3d
  22. import grass.script as grass
  23. from abstract_map_dataset import *
  24. from abstract_space_time_dataset import *
  25. ###############################################################################
  26. class RasterDataset(AbstractMapDataset):
  27. """!Raster dataset class
  28. This class provides functions to select, update, insert or delete raster
  29. map information and valid time stamps into the SQL temporal database.
  30. Usage:
  31. @code
  32. >>> import grass.script as grass
  33. >>> init()
  34. >>> grass.use_temp_region()
  35. >>> grass.run_command("g.region", n=80.0, s=0.0, e=120.0, w=0.0,
  36. ... t=1.0, b=0.0, res=10.0)
  37. 0
  38. >>> grass.run_command("r.mapcalc", overwrite=True,
  39. ... expression="strds_map_test_case = 1")
  40. 0
  41. >>> mapset = grass.gisenv()["MAPSET"]
  42. >>> name = "strds_map_test_case"
  43. >>> identifier = "%s@%s" % (name, mapset)
  44. >>> rmap = RasterDataset(identifier)
  45. >>> rmap.set_absolute_time(start_time=datetime(2001,1,1),
  46. ... end_time=datetime(2012,1,1))
  47. True
  48. >>> rmap.map_exists()
  49. True
  50. >>> rmap.load()
  51. >>> rmap.spatial_extent.print_info()
  52. +-------------------- Spatial extent ----------------------------------------+
  53. | North:...................... 80.0
  54. | South:...................... 0.0
  55. | East:.. .................... 120.0
  56. | West:....................... 0.0
  57. | Top:........................ 0.0
  58. | Bottom:..................... 0.0
  59. >>> rmap.absolute_time.print_info()
  60. +-------------------- Absolute time -----------------------------------------+
  61. | Start time:................. 2001-01-01 00:00:00
  62. | End time:................... 2012-01-01 00:00:00
  63. >>> rmap.metadata.print_info()
  64. +-------------------- Metadata information ----------------------------------+
  65. | Datatype:................... CELL
  66. | Number of columns:.......... 8
  67. | Number of rows:............. 12
  68. | Number of cells:............ 96
  69. | North-South resolution:..... 10.0
  70. | East-west resolution:....... 10.0
  71. | Minimum value:.............. 1.0
  72. | Maximum value:.............. 1.0
  73. | STRDS register table ....... None
  74. >>> newmap = rmap.get_new_instance("new@PERMANENT")
  75. >>> isinstance(newmap, RasterDataset)
  76. True
  77. >>> newstrds = rmap.get_new_stds_instance("new@PERMANENT")
  78. >>> isinstance(newstrds, SpaceTimeRasterDataset)
  79. True
  80. >>> rmap.get_type()
  81. 'raster'
  82. >>> rmap.get_stds_register()
  83. >>> rmap.get_absolute_time()
  84. (datetime.datetime(2001, 1, 1, 0, 0), datetime.datetime(2012, 1, 1, 0, 0), None)
  85. >>> rmap.get_valid_time()
  86. (datetime.datetime(2001, 1, 1, 0, 0), datetime.datetime(2012, 1, 1, 0, 0))
  87. >>> rmap.get_name()
  88. 'strds_map_test_case'
  89. >>> rmap.get_mapset() == mapset
  90. True
  91. >>> rmap.get_temporal_type()
  92. 'absolute'
  93. >>> rmap.get_spatial_extent()
  94. (80.0, 0.0, 120.0, 0.0, 0.0, 0.0)
  95. >>> rmap.is_time_absolute()
  96. True
  97. >>> rmap.is_time_relative()
  98. False
  99. >>> grass.run_command("g.remove", rast=name)
  100. 0
  101. >>> grass.del_temp_region()
  102. @endcode
  103. """
  104. def __init__(self, ident):
  105. AbstractMapDataset.__init__(self)
  106. self.reset(ident)
  107. def get_type(self):
  108. return 'raster'
  109. def get_new_instance(self, ident):
  110. """!Return a new instance with the type of this class"""
  111. return RasterDataset(ident)
  112. def get_new_stds_instance(self, ident):
  113. """!Return a new space time dataset instance in which maps
  114. are stored with the type of this class"""
  115. return SpaceTimeRasterDataset(ident)
  116. def get_stds_register(self):
  117. """!Return the space time dataset register table name in which stds
  118. are listed in which this map is registered"""
  119. return self.metadata.get_strds_register()
  120. def set_stds_register(self, name):
  121. """!Set the space time dataset register table name in which stds
  122. are listed in which this map is registered"""
  123. self.metadata.set_strds_register(name)
  124. def spatial_overlapping(self, dataset):
  125. """!Return True if the spatial extents 2d overlap"""
  126. return self.spatial_extent.overlapping_2d(dataset.spatial_extent)
  127. def spatial_relation(self, dataset):
  128. """!Return the two dimensional spatial relation"""
  129. return self.spatial_extent.spatial_relation_2d(dataset.spatial_extent)
  130. def get_np_array(self):
  131. """!Return this raster map as memmap numpy style array to access the raster
  132. values in numpy style without loading the whole map in the RAM.
  133. In case this raster map does exists in the grass spatial database,
  134. the map will be exported using r.out.bin to a temporary location
  135. and assigned to the memmap object that is returned by this function.
  136. In case the raster map does not exists, an empty temporary
  137. binary file will be created and assigned to the memap object.
  138. You need to call the write function to write the memmap
  139. array back into grass.
  140. """
  141. a = garray.array()
  142. if self.map_exists():
  143. a.read(self.get_map_id())
  144. return a
  145. def reset(self, ident):
  146. """!Reset the internal structure and set the identifier"""
  147. self.base = RasterBase(ident=ident)
  148. self.absolute_time = RasterAbsoluteTime(ident=ident)
  149. self.relative_time = RasterRelativeTime(ident=ident)
  150. self.spatial_extent = RasterSpatialExtent(ident=ident)
  151. self.metadata = RasterMetadata(ident=ident)
  152. def has_grass_timestamp(self):
  153. """!Check if a grass file bsased time stamp exists for this map.
  154. """
  155. if G_has_raster_timestamp(self.get_name(), self.get_mapset()):
  156. return True
  157. else:
  158. return False
  159. def write_timestamp_to_grass(self):
  160. """!Write the timestamp of this map into the map metadata in
  161. the grass file system based spatial database.
  162. Internally the libgis API functions are used for writing
  163. """
  164. ts = libgis.TimeStamp()
  165. libgis.G_scan_timestamp(byref(ts), self._convert_timestamp())
  166. check = libgis.G_write_raster_timestamp(self.get_name(), byref(ts))
  167. if check == -1:
  168. core.error(_("Unable to create timestamp file "
  169. "for raster map <%s>" % (self.get_map_id())))
  170. if check == -2:
  171. core.error(_("Invalid datetime in timestamp for raster map <%s>" %
  172. (self.get_map_id())))
  173. def remove_timestamp_from_grass(self):
  174. """!Remove the timestamp from the grass file system based
  175. spatial database
  176. Internally the libgis API functions are used for removal
  177. """
  178. check = libgis.G_remove_raster_timestamp(self.get_name())
  179. if check == -1:
  180. core.error(_("Unable to remove timestamp for raster map <%s>" %
  181. (self.get_name())))
  182. def map_exists(self):
  183. """!Return True in case the map exists in the grass spatial database
  184. @return True if map exists, False otherwise
  185. """
  186. mapset = libgis.G_find_raster(self.get_name(), self.get_mapset())
  187. if not mapset:
  188. return False
  189. return True
  190. def read_info(self):
  191. """!Read the raster map info from the file system and store the content
  192. into a dictionary
  193. This method uses the ctypes interface to the gis and raster libraries
  194. to read the map metadata information
  195. """
  196. kvp = {}
  197. name = self.get_name()
  198. mapset = self.get_mapset()
  199. if not self.map_exists():
  200. core.fatal(_("Raster map <%s> not found" % name))
  201. # Read the region information
  202. region = libgis.Cell_head()
  203. libraster.Rast_get_cellhd(name, mapset, byref(region))
  204. kvp["north"] = region.north
  205. kvp["south"] = region.south
  206. kvp["east"] = region.east
  207. kvp["west"] = region.west
  208. kvp["nsres"] = region.ns_res
  209. kvp["ewres"] = region.ew_res
  210. kvp["rows"] = region.cols
  211. kvp["cols"] = region.rows
  212. maptype = libraster.Rast_map_type(name, mapset)
  213. if maptype == libraster.DCELL_TYPE:
  214. kvp["datatype"] = "DCELL"
  215. elif maptype == libraster.FCELL_TYPE:
  216. kvp["datatype"] = "FCELL"
  217. elif maptype == libraster.CELL_TYPE:
  218. kvp["datatype"] = "CELL"
  219. # Read range
  220. if libraster.Rast_map_is_fp(name, mapset):
  221. range = libraster.FPRange()
  222. libraster.Rast_init_fp_range(byref(range))
  223. ret = libraster.Rast_read_fp_range(name, mapset, byref(range))
  224. if ret < 0:
  225. core.fatal(_("Unable to read range file"))
  226. if ret == 2:
  227. kvp["min"] = None
  228. kvp["max"] = None
  229. else:
  230. min = libgis.DCELL()
  231. max = libgis.DCELL()
  232. libraster.Rast_get_fp_range_min_max(
  233. byref(range), byref(min), byref(max))
  234. kvp["min"] = min.value
  235. kvp["max"] = max.value
  236. else:
  237. range = libraster.Range()
  238. libraster.Rast_init_range(byref(range))
  239. ret = libraster.Rast_read_range(name, mapset, byref(range))
  240. if ret < 0:
  241. core.fatal(_("Unable to read range file"))
  242. if ret == 2:
  243. kvp["min"] = None
  244. kvp["max"] = None
  245. else:
  246. min = libgis.CELL()
  247. max = libgis.CELL()
  248. libraster.Rast_get_range_min_max(
  249. byref(range), byref(min), byref(max))
  250. kvp["min"] = min.value
  251. kvp["max"] = max.value
  252. return kvp
  253. def load(self):
  254. """!Load all info from an existing raster map into the internal s
  255. tructure"""
  256. # Fill base information
  257. self.base.set_creator(str(getpass.getuser()))
  258. # Get the data from an existing raster map
  259. if get_use_ctypes_map_access() == True:
  260. kvp = self.read_info()
  261. else:
  262. kvp = grass.raster_info(self.get_id())
  263. # Fill spatial extent
  264. self.set_spatial_extent(north=kvp["north"], south=kvp["south"],
  265. east=kvp["east"], west=kvp["west"])
  266. # Fill metadata
  267. self.metadata.set_nsres(kvp["nsres"])
  268. self.metadata.set_ewres(kvp["ewres"])
  269. self.metadata.set_datatype(kvp["datatype"])
  270. self.metadata.set_min(kvp["min"])
  271. self.metadata.set_max(kvp["max"])
  272. rows = int(kvp["rows"])
  273. cols = int(kvp["cols"])
  274. ncells = cols * rows
  275. self.metadata.set_cols(cols)
  276. self.metadata.set_rows(rows)
  277. self.metadata.set_number_of_cells(ncells)
  278. ###############################################################################
  279. class Raster3DDataset(AbstractMapDataset):
  280. """!Raster3d dataset class
  281. This class provides functions to select, update, insert or delete raster3d
  282. map information and valid time stamps into the SQL temporal database.
  283. """
  284. def __init__(self, ident):
  285. AbstractMapDataset.__init__(self)
  286. self.reset(ident)
  287. def get_type(self):
  288. return "raster3d"
  289. def get_new_instance(self, ident):
  290. """!Return a new instance with the type of this class"""
  291. return Raster3DDataset(ident)
  292. def get_new_stds_instance(self, ident):
  293. """!Return a new space time dataset instance in which maps
  294. are stored with the type of this class"""
  295. return SpaceTimeRaster3DDataset(ident)
  296. def get_stds_register(self):
  297. """!Return the space time dataset register table name in
  298. which stds are listed in which this map is registered"""
  299. return self.metadata.get_str3ds_register()
  300. def set_stds_register(self, name):
  301. """!Set the space time dataset register table name in
  302. which stds are listed in which this map is registered"""
  303. self.metadata.set_str3ds_register(name)
  304. def spatial_overlapping(self, dataset):
  305. """!Return True if the spatial extents overlap"""
  306. if self.get_type() == dataset.get_type() or dataset.get_type() == "str3ds":
  307. return self.spatial_extent.overlapping(dataset.spatial_extent)
  308. else:
  309. return self.spatial_extent.overlapping_2d(dataset.spatial_extent)
  310. def spatial_relation(self, dataset):
  311. """!Return the two or three dimensional spatial relation"""
  312. if self.get_type() == dataset.get_type() or dataset.get_type() == "str3ds":
  313. return self.spatial_extent.spatial_relation(dataset.spatial_extent)
  314. else:
  315. return self.spatial_extent.spatial_relation_2d(dataset.spatial_extent)
  316. def get_np_array(self):
  317. """!Return this 3D raster map as memmap numpy style array to access the 3D raster
  318. values in numpy style without loading the whole map in the RAM.
  319. In case this 3D raster map does exists in the grass spatial database,
  320. the map will be exported using r3.out.bin to a temporary location
  321. and assigned to the memmap object that is returned by this function.
  322. In case the 3D raster map does not exists, an empty temporary
  323. binary file will be created and assigned to the memap object.
  324. You need to call the write function to write the memmap
  325. array back into grass.
  326. """
  327. a = garray.array3d()
  328. if self.map_exists():
  329. a.read(self.get_map_id())
  330. return a
  331. def reset(self, ident):
  332. """!Reset the internal structure and set the identifier"""
  333. self.base = Raster3DBase(ident=ident)
  334. self.absolute_time = Raster3DAbsoluteTime(ident=ident)
  335. self.relative_time = Raster3DRelativeTime(ident=ident)
  336. self.spatial_extent = Raster3DSpatialExtent(ident=ident)
  337. self.metadata = Raster3DMetadata(ident=ident)
  338. def has_grass_timestamp(self):
  339. """!Check if a grass file bsased time stamp exists for this map.
  340. """
  341. if G_has_raster3d_timestamp(self.get_name(), self.get_mapset()):
  342. return True
  343. else:
  344. return False
  345. def write_timestamp_to_grass(self):
  346. """!Write the timestamp of this map into the map metadata
  347. in the grass file system based spatial database.
  348. Internally the libgis API functions are used for writing
  349. """
  350. ts = libgis.TimeStamp()
  351. libgis.G_scan_timestamp(byref(ts), self._convert_timestamp())
  352. check = libgis.G_write_raster3d_timestamp(self.get_name(), byref(ts))
  353. if check == -1:
  354. core.error(_("Unable to create timestamp file "
  355. "for raster3d map <%s>" % (self.get_map_id())))
  356. if check == -2:
  357. core.error(_("Invalid datetime in timestamp "
  358. "for raster3d map <%s>" % (self.get_map_id())))
  359. def remove_timestamp_from_grass(self):
  360. """!Remove the timestamp from the grass file system based spatial database
  361. Internally the libgis API functions are used for removal
  362. """
  363. check = libgis.G_remove_raster3d_timestamp(self.get_name())
  364. if check == -1:
  365. core.error(_("Unable to remove timestamp for raster3d map <%s>" %
  366. (self.get_name())))
  367. def map_exists(self):
  368. """!Return True in case the map exists in the grass spatial database
  369. @return True if map exists, False otherwise
  370. """
  371. mapset = libgis.G_find_raster3d(self.get_name(), self.get_mapset())
  372. if not mapset:
  373. return False
  374. return True
  375. def read_info(self):
  376. """!Read the raster3d map info from the file system and store the content
  377. into a dictionary
  378. This method uses the ctypes interface to the gis and raster3d libraries
  379. to read the map metadata information
  380. """
  381. kvp = {}
  382. name = self.get_name()
  383. mapset = self.get_mapset()
  384. if not self.map_exists():
  385. core.fatal(_("Raster3d map <%s> not found" % name))
  386. # Read the region information
  387. region = libraster3d.RASTER3D_Region()
  388. libraster3d.Rast3d_read_region_map(name, mapset, byref(region))
  389. kvp["north"] = region.north
  390. kvp["south"] = region.south
  391. kvp["east"] = region.east
  392. kvp["west"] = region.west
  393. kvp["nsres"] = region.ns_res
  394. kvp["ewres"] = region.ew_res
  395. kvp["tbres"] = region.tb_res
  396. kvp["rows"] = region.cols
  397. kvp["cols"] = region.rows
  398. kvp["depths"] = region.depths
  399. kvp["top"] = region.top
  400. kvp["bottom"] = region.bottom
  401. # We need to open the map, this function returns a void pointer
  402. # but we may need the correct type which is RASTER3D_Map, hence
  403. # the casting
  404. g3map = cast(libraster3d.Rast3d_open_cell_old(name, mapset,
  405. libraster3d.RASTER3D_DEFAULT_WINDOW,
  406. libraster3d.RASTER3D_TILE_SAME_AS_FILE,
  407. libraster3d.RASTER3D_NO_CACHE),
  408. POINTER(libraster3d.RASTER3D_Map))
  409. if not g3map:
  410. core.fatal(_("Unable to open 3D raster map <%s>" % (name)))
  411. maptype = libraster3d.Rast3d_file_type_map(g3map)
  412. if maptype == libraster.DCELL_TYPE:
  413. kvp["datatype"] = "DCELL"
  414. elif maptype == libraster.FCELL_TYPE:
  415. kvp["datatype"] = "FCELL"
  416. # Read range
  417. min = libgis.DCELL()
  418. max = libgis.DCELL()
  419. ret = libraster3d.Rast3d_range_load(g3map)
  420. if not ret:
  421. core.fatal(_("Unable to load range of 3D raster map <%s>" %
  422. (name)))
  423. libraster3d.Rast3d_range_min_max(g3map, byref(min), byref(max))
  424. if min.value != min.value:
  425. kvp["min"] = None
  426. else:
  427. kvp["min"] = float(min.value)
  428. if max.value != max.value:
  429. kvp["max"] = None
  430. else:
  431. kvp["max"] = float(max.value)
  432. if not libraster3d.Rast3d_close(g3map):
  433. G_fatal_error(_("Unable to close 3D raster map <%s>" % (name)))
  434. return kvp
  435. def load(self):
  436. """!Load all info from an existing raster3d map into the internal structure"""
  437. # Fill base information
  438. self.base.set_creator(str(getpass.getuser()))
  439. # Fill spatial extent
  440. # Get the data from an existing 3D raster map
  441. if get_use_ctypes_map_access() == True:
  442. kvp = self.read_info()
  443. else:
  444. kvp = grass.raster3d_info(self.get_id())
  445. self.set_spatial_extent(north=kvp["north"], south=kvp["south"],
  446. east=kvp["east"], west=kvp["west"],
  447. top=kvp["top"], bottom=kvp["bottom"])
  448. # Fill metadata
  449. self.metadata.set_nsres(kvp["nsres"])
  450. self.metadata.set_ewres(kvp["ewres"])
  451. self.metadata.set_tbres(kvp["tbres"])
  452. self.metadata.set_datatype(kvp["datatype"])
  453. self.metadata.set_min(kvp["min"])
  454. self.metadata.set_max(kvp["max"])
  455. rows = int(kvp["rows"])
  456. cols = int(kvp["cols"])
  457. depths = int(kvp["depths"])
  458. ncells = cols * rows * depths
  459. self.metadata.set_cols(cols)
  460. self.metadata.set_rows(rows)
  461. self.metadata.set_depths(depths)
  462. self.metadata.set_number_of_cells(ncells)
  463. ###############################################################################
  464. class VectorDataset(AbstractMapDataset):
  465. """!Vector dataset class
  466. This class provides functions to select, update, insert or delete vector
  467. map information and valid time stamps into the SQL temporal database.
  468. """
  469. def __init__(self, ident):
  470. AbstractMapDataset.__init__(self)
  471. self.reset(ident)
  472. def get_type(self):
  473. return "vector"
  474. def get_new_instance(self, ident):
  475. """!Return a new instance with the type of this class"""
  476. return VectorDataset(ident)
  477. def get_new_stds_instance(self, ident):
  478. """!Return a new space time dataset instance in which maps
  479. are stored with the type of this class"""
  480. return SpaceTimeVectorDataset(ident)
  481. def get_stds_register(self):
  482. """!Return the space time dataset register table name in
  483. which stds are listed in which this map is registered"""
  484. return self.metadata.get_stvds_register()
  485. def set_stds_register(self, name):
  486. """!Set the space time dataset register table name in
  487. which stds are listed in which this map is registered"""
  488. self.metadata.set_stvds_register(name)
  489. def get_layer(self):
  490. """!Return the layer"""
  491. return self.base.get_layer()
  492. def spatial_overlapping(self, dataset):
  493. """!Return True if the spatial extents 2d overlap"""
  494. return self.spatial_extent.overlapping_2d(dataset.spatial_extent)
  495. def spatial_relation(self, dataset):
  496. """!Return the two dimensional spatial relation"""
  497. return self.spatial_extent.spatial_relation_2d(dataset.spatial_extent)
  498. def reset(self, ident):
  499. """!Reset the internal structure and set the identifier"""
  500. self.base = VectorBase(ident=ident)
  501. self.absolute_time = VectorAbsoluteTime(ident=ident)
  502. self.relative_time = VectorRelativeTime(ident=ident)
  503. self.spatial_extent = VectorSpatialExtent(ident=ident)
  504. self.metadata = VectorMetadata(ident=ident)
  505. def has_grass_timestamp(self):
  506. """!Check if a grass file bsased time stamp exists for this map.
  507. """
  508. if G_has_vector_timestamp(self.get_name(), self.get_layer(),
  509. self.get_mapset()):
  510. return True
  511. else:
  512. return False
  513. def write_timestamp_to_grass(self):
  514. """!Write the timestamp of this map into the map metadata in
  515. the grass file system based spatial database.
  516. Internally the libgis API functions are used for writing
  517. """
  518. ts = libgis.TimeStamp()
  519. libgis.G_scan_timestamp(byref(ts), self._convert_timestamp())
  520. check = libgis.G_write_vector_timestamp(
  521. self.get_name(), self.get_layer(), byref(ts))
  522. if check == -1:
  523. core.error(_("Unable to create timestamp file "
  524. "for vector map <%s>" % (self.get_map_id())))
  525. if check == -2:
  526. core.error(_("Invalid datetime in timestamp for vector map <%s>" %
  527. (self.get_map_id())))
  528. def remove_timestamp_from_grass(self):
  529. """!Remove the timestamp from the grass file system based spatial
  530. database
  531. Internally the libgis API functions are used for removal
  532. """
  533. check = libgis.G_remove_vector_timestamp(
  534. self.get_name(), self.get_layer())
  535. if check == -1:
  536. core.error(_("Unable to remove timestamp for vector map <%s>" %
  537. (self.get_name())))
  538. def map_exists(self):
  539. """!Return True in case the map exists in the grass spatial database
  540. @return True if map exists, False otherwise
  541. """
  542. mapset = libgis.G_find_vector(self.get_name(), self.get_mapset())
  543. if not mapset:
  544. return False
  545. return True
  546. def read_info(self):
  547. """!Read the vector map info from the file system and store the content
  548. into a dictionary
  549. This method uses the ctypes interface to the vector libraries
  550. to read the map metadata information
  551. """
  552. kvp = {}
  553. name = self.get_name()
  554. mapset = self.get_mapset()
  555. if not self.map_exists():
  556. core.fatal(_("Vector map <%s> not found" % name))
  557. # The vector map structure
  558. Map = libvector.Map_info()
  559. # We open the maps always in topology mode first
  560. libvector.Vect_set_open_level(2)
  561. with_topo = True
  562. # Code lend from v.info main.c
  563. if libvector.Vect_open_old_head2(byref(Map), name, mapset, "1") < 2:
  564. # force level 1, open fully
  565. # NOTE: number of points, lines, boundaries, centroids,
  566. # faces, kernels is still available
  567. libvector.Vect_set_open_level(1) # no topology
  568. with_topo = False
  569. core.message(_("Open map without topology support"))
  570. if libvector.Vect_open_old2(byref(Map), name, mapset, "1") < 1:
  571. core.fatal(_("Unable to open vector map <%s>" %
  572. (libvector.Vect_get_full_name(byref(Map)))))
  573. # Release the vector spatial index memory when closed
  574. libvector.Vect_set_release_support(byref(Map))
  575. # Read the extent information
  576. bbox = libvector.bound_box()
  577. libvector.Vect_get_map_box(byref(Map), byref(bbox))
  578. kvp["north"] = bbox.N
  579. kvp["south"] = bbox.S
  580. kvp["east"] = bbox.E
  581. kvp["west"] = bbox.W
  582. kvp["top"] = bbox.T
  583. kvp["bottom"] = bbox.B
  584. kvp["map3d"] = bool(libvector.Vect_is_3d(byref(Map)))
  585. # Read number of features
  586. if with_topo:
  587. kvp["points"] = libvector.Vect_get_num_primitives(
  588. byref(Map), libvector.GV_POINT)
  589. kvp["lines"] = libvector.Vect_get_num_primitives(
  590. byref(Map), libvector.GV_LINE)
  591. kvp["boundaries"] = libvector.Vect_get_num_primitives(
  592. byref(Map), libvector.GV_BOUNDARY)
  593. kvp["centroids"] = libvector.Vect_get_num_primitives(
  594. byref(Map), libvector.GV_CENTROID)
  595. kvp["faces"] = libvector.Vect_get_num_primitives(
  596. byref(Map), libvector.GV_FACE)
  597. kvp["kernels"] = libvector.Vect_get_num_primitives(
  598. byref(Map), libvector.GV_KERNEL)
  599. # Summarize the primitives
  600. kvp["primitives"] = kvp["points"] + kvp["lines"] + \
  601. kvp["boundaries"] + kvp["centroids"]
  602. if kvp["map3d"]:
  603. kvp["primitives"] += kvp["faces"] + kvp["kernels"]
  604. # Read topology information
  605. kvp["nodes"] = libvector.Vect_get_num_nodes(byref(Map))
  606. kvp["areas"] = libvector.Vect_get_num_areas(byref(Map))
  607. kvp["islands"] = libvector.Vect_get_num_islands(byref(Map))
  608. kvp["holes"] = libvector.Vect_get_num_holes(byref(Map))
  609. kvp["volumes"] = libvector.Vect_get_num_primitives(
  610. byref(Map), libvector.GV_VOLUME)
  611. else:
  612. kvp["points"] = None
  613. kvp["lines"] = None
  614. kvp["boundaries"] = None
  615. kvp["centroids"] = None
  616. kvp["faces"] = None
  617. kvp["kernels"] = None
  618. kvp["primitives"] = None
  619. kvp["nodes"] = None
  620. kvp["areas"] = None
  621. kvp["islands"] = None
  622. kvp["holes"] = None
  623. kvp["volumes"] = None
  624. libvector.Vect_close(byref(Map))
  625. return kvp
  626. def load(self):
  627. """!Load all info from an existing vector map into the internal
  628. structure"""
  629. # Fill base information
  630. self.base.set_creator(str(getpass.getuser()))
  631. # Get the data from an existing vector map
  632. if get_use_ctypes_map_access() == True:
  633. kvp = self.read_info()
  634. else:
  635. kvp = grass.vector_info(self.get_map_id())
  636. # Fill spatial extent
  637. self.set_spatial_extent(north=kvp["north"], south=kvp["south"],
  638. east=kvp["east"], west=kvp["west"],
  639. top=kvp["top"], bottom=kvp["bottom"])
  640. # Fill metadata
  641. self.metadata.set_3d_info(kvp["map3d"])
  642. self.metadata.set_number_of_points(kvp["points"])
  643. self.metadata.set_number_of_lines(kvp["lines"])
  644. self.metadata.set_number_of_boundaries(kvp["boundaries"])
  645. self.metadata.set_number_of_centroids(kvp["centroids"])
  646. self.metadata.set_number_of_faces(kvp["faces"])
  647. self.metadata.set_number_of_kernels(kvp["kernels"])
  648. self.metadata.set_number_of_primitives(kvp["primitives"])
  649. self.metadata.set_number_of_nodes(kvp["nodes"])
  650. self.metadata.set_number_of_areas(kvp["areas"])
  651. self.metadata.set_number_of_islands(kvp["islands"])
  652. self.metadata.set_number_of_holes(kvp["holes"])
  653. self.metadata.set_number_of_volumes(kvp["volumes"])
  654. ###############################################################################
  655. class SpaceTimeRasterDataset(AbstractSpaceTimeDataset):
  656. """!Space time raster dataset class
  657. """
  658. def __init__(self, ident):
  659. AbstractSpaceTimeDataset.__init__(self, ident)
  660. def get_type(self):
  661. return "strds"
  662. def get_new_instance(self, ident):
  663. """!Return a new instance with the type of this class"""
  664. return SpaceTimeRasterDataset(ident)
  665. def get_new_map_instance(self, ident):
  666. """!Return a new instance of a map dataset which is associated "
  667. "with the type of this class"""
  668. return RasterDataset(ident)
  669. def get_map_register(self):
  670. """!Return the name of the map register table"""
  671. return self.metadata.get_raster_register()
  672. def set_map_register(self, name):
  673. """!Set the name of the map register table"""
  674. self.metadata.set_raster_register(name)
  675. def spatial_overlapping(self, dataset):
  676. """!Return True if the spatial extents 2d overlap"""
  677. return self.spatial_extent.overlapping_2d(dataset.spatial_extent)
  678. def spatial_relation(self, dataset):
  679. """!Return the two dimensional spatial relation"""
  680. return self.spatial_extent.spatial_relation_2d(dataset.spatial_extent)
  681. def reset(self, ident):
  682. """!Reset the internal structure and set the identifier"""
  683. self.base = STRDSBase(ident=ident)
  684. self.base.set_creator(str(getpass.getuser()))
  685. self.absolute_time = STRDSAbsoluteTime(ident=ident)
  686. self.relative_time = STRDSRelativeTime(ident=ident)
  687. self.spatial_extent = STRDSSpatialExtent(ident=ident)
  688. self.metadata = STRDSMetadata(ident=ident)
  689. ###############################################################################
  690. class SpaceTimeRaster3DDataset(AbstractSpaceTimeDataset):
  691. """!Space time raster3d dataset class
  692. """
  693. def __init__(self, ident):
  694. AbstractSpaceTimeDataset.__init__(self, ident)
  695. def get_type(self):
  696. return "str3ds"
  697. def get_new_instance(self, ident):
  698. """!Return a new instance with the type of this class"""
  699. return SpaceTimeRaster3DDataset(ident)
  700. def get_new_map_instance(self, ident):
  701. """!Return a new instance of a map dataset which is associated
  702. with the type of this class"""
  703. return Raster3DDataset(ident)
  704. def get_map_register(self):
  705. """!Return the name of the map register table"""
  706. return self.metadata.get_raster3d_register()
  707. def set_map_register(self, name):
  708. """!Set the name of the map register table"""
  709. self.metadata.set_raster3d_register(name)
  710. def spatial_overlapping(self, dataset):
  711. """!Return True if the spatial extents overlap"""
  712. if self.get_type() == dataset.get_type() or dataset.get_type() == "str3ds":
  713. return self.spatial_extent.overlapping(dataset.spatial_extent)
  714. else:
  715. return self.spatial_extent.overlapping_2d(dataset.spatial_extent)
  716. def spatial_relation(self, dataset):
  717. """!Return the two or three dimensional spatial relation"""
  718. if self.get_type() == dataset.get_type() or \
  719. dataset.get_type() == "str3ds":
  720. return self.spatial_extent.spatial_relation(dataset.spatial_extent)
  721. else:
  722. return self.spatial_extent.spatial_relation_2d(dataset.spatial_extent)
  723. def reset(self, ident):
  724. """!Reset the internal structure and set the identifier"""
  725. self.base = STR3DSBase(ident=ident)
  726. self.base.set_creator(str(getpass.getuser()))
  727. self.absolute_time = STR3DSAbsoluteTime(ident=ident)
  728. self.relative_time = STR3DSRelativeTime(ident=ident)
  729. self.spatial_extent = STR3DSSpatialExtent(ident=ident)
  730. self.metadata = STR3DSMetadata(ident=ident)
  731. ###############################################################################
  732. class SpaceTimeVectorDataset(AbstractSpaceTimeDataset):
  733. """!Space time vector dataset class
  734. """
  735. def __init__(self, ident):
  736. AbstractSpaceTimeDataset.__init__(self, ident)
  737. def get_type(self):
  738. return "stvds"
  739. def get_new_instance(self, ident):
  740. """!Return a new instance with the type of this class"""
  741. return SpaceTimeVectorDataset(ident)
  742. def get_new_map_instance(self, ident):
  743. """!Return a new instance of a map dataset which is associated
  744. with the type of this class"""
  745. return VectorDataset(ident)
  746. def get_map_register(self):
  747. """!Return the name of the map register table"""
  748. return self.metadata.get_vector_register()
  749. def set_map_register(self, name):
  750. """!Set the name of the map register table"""
  751. self.metadata.set_vector_register(name)
  752. def spatial_overlapping(self, dataset):
  753. """!Return True if the spatial extents 2d overlap"""
  754. return self.spatial_extent.overlapping_2d(dataset.spatial_extent)
  755. def spatial_relation(self, dataset):
  756. """!Return the two dimensional spatial relation"""
  757. return self.spatial_extent.spatial_relation_2d(dataset.spatial_extent)
  758. def reset(self, ident):
  759. """!Reset the internal structure and set the identifier"""
  760. self.base = STVDSBase(ident=ident)
  761. self.base.set_creator(str(getpass.getuser()))
  762. self.absolute_time = STVDSAbsoluteTime(ident=ident)
  763. self.relative_time = STVDSRelativeTime(ident=ident)
  764. self.spatial_extent = STVDSSpatialExtent(ident=ident)
  765. self.metadata = STVDSMetadata(ident=ident)
  766. ###############################################################################
  767. if __name__ == "__main__":
  768. import doctest
  769. doctest.testmod()