space_time_datasets_tools.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544
  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. Usage:
  5. @code
  6. import grass.temporal as tgis
  7. tgis.register_maps_in_space_time_dataset(type, name, maps)
  8. ...
  9. @endcode
  10. (C) 2008-2011 by the GRASS Development Team
  11. This program is free software under the GNU General Public
  12. License (>=v2). Read the file COPYING that comes with GRASS
  13. for details.
  14. @author Soeren Gebbert
  15. """
  16. from space_time_datasets import *
  17. ###############################################################################
  18. def register_maps_in_space_time_dataset(type, name, maps=None, file=None, start=None, end=None, increment=None, dbif = None, interval=False, fs="|"):
  19. """Use this method to register maps in space time datasets. This function is generic and
  20. can handle raster, vector and raster3d maps as well as there space time datasets.
  21. Additionally a start time string and an increment string can be specified
  22. to assign a time interval automatically to the maps.
  23. It takes care of the correct update of the space time datasets from all
  24. registered maps.
  25. @param type: The type of the maps raster, raster3d or vector
  26. @param name: The name of the space time dataset
  27. @param maps: A comma separated list of map names
  28. @param file: Input file one map with optional start and end time, one per line
  29. @param start: The start date and time of the first raster map, in case the map has no date (format absolute: "yyyy-mm-dd HH:MM:SS" or "yyyy-mm-dd", format relative 5.0)
  30. @param increment: Time increment between maps for time stamp creation (format absolute: NNN seconds, minutes, hours, days, weeks, months, years; format relative: 1.0)
  31. @param dbif: The database interface to be used
  32. @param interval: If True, time intervals are created in case the start time and an increment is provided
  33. @param fs: Field separator used in input file
  34. """
  35. start_time_in_file = False
  36. end_time_in_file = False
  37. if maps and file:
  38. core.fata(_("%s= and %s= are mutually exclusive") % ("input","file"))
  39. if end and increment:
  40. core.fata(_("%s= and %s= are mutually exclusive") % ("end","increment"))
  41. if end and not start:
  42. core.fata(_("Please specify %s= and %s=") % ("start_time","end_time"))
  43. if not maps and not file:
  44. core.fata(_("Please specify %s= or %s=") % ("input","file"))
  45. if start and start == "file":
  46. start_time_in_file = True
  47. if end and end == "file":
  48. end_time_in_file = True
  49. # We may need the mapset
  50. mapset = core.gisenv()["MAPSET"]
  51. # Check if the dataset name contains the mapset as well
  52. if name.find("@") < 0:
  53. id = name + "@" + mapset
  54. else:
  55. id = name
  56. sp = dataset_factory(type, id)
  57. connect = False
  58. if dbif == None:
  59. dbif = sql_database_interface()
  60. dbif.connect()
  61. connect = True
  62. # Read content from temporal database
  63. sp.select(dbif)
  64. if sp.is_in_db(dbif) == False:
  65. dbif.close()
  66. core.fatal(_("Space time %s dataset <%s> no found") % (sp.get_new_map_instance(None).get_type(). name))
  67. maplist = []
  68. # Map names as comma separated string
  69. if maps:
  70. if maps.find(",") == -1:
  71. maplist = (maps,)
  72. else:
  73. maplist = tuple(maps.split(","))
  74. # Read the map list from file
  75. if file:
  76. fd = open(file, "r")
  77. line = True
  78. while True:
  79. line = fd.readline()
  80. if not line:
  81. break
  82. line_list = line.split(fs)
  83. mapname = line_list[0].strip()
  84. if mapname.find("@") < 0:
  85. mapid = mapname + "@" + mapset
  86. else:
  87. mapid = mapname
  88. row = {}
  89. row["id"] = mapid
  90. if start_time_in_file and end_time_in_file:
  91. row["start"] = line_list[1].strip()
  92. row["end"] = line_list[2].strip()
  93. if start_time_in_file and not end_time_in_file:
  94. row["start"] = line_list[1].strip()
  95. maplist.append(row)
  96. num_maps = len(maplist)
  97. count = 0
  98. for entry in maplist:
  99. core.percent(count, num_maps, 1)
  100. # Get a new instance of the space time dataset map type
  101. if file:
  102. map = sp.get_new_map_instance(entry["id"])
  103. else:
  104. if entry.find("@") < 0:
  105. mapid = entry + "@" + mapset
  106. else:
  107. mapid = entry
  108. map = sp.get_new_map_instance(mapid)
  109. # Use the time data from file
  110. if start_time_in_file:
  111. start = entry["start"]
  112. if end_time_in_file:
  113. end = entry["end"]
  114. # Put the map into the database
  115. if map.is_in_db(dbif) == False:
  116. # Break in case no valid time is provided
  117. if start == "" or start == None:
  118. dbif.close()
  119. core.fatal(_("Unable to register %s map <%s>. The map has no valid time and the start time is not set.") % \
  120. (map.get_type(), map.get_id() ))
  121. # Load the data from the grass file database
  122. map.load()
  123. if sp.get_temporal_type() == "absolute":
  124. map.set_time_to_absolute()
  125. else:
  126. map.set_time_to_relative()
  127. # Put it into the temporal database
  128. map.insert(dbif)
  129. else:
  130. map.select(dbif)
  131. if map.get_temporal_type() != sp.get_temporal_type():
  132. dbif.close()
  133. core.fatal(_("Unable to register %s map <%s>. The temporal types are different.") % (map.get_type(), map.get_id()))
  134. # In case the time is in the input file we ignore the increment counter
  135. if start_time_in_file:
  136. count = 1
  137. # Set the valid time
  138. if start:
  139. assign_valid_time_to_map(ttype=sp.get_temporal_type(), map=map, start=start, end=end, increment=increment, mult=count, dbif=dbif, interval=interval)
  140. # Finally Register map in the space time dataset
  141. sp.register_map(map, dbif)
  142. count += 1
  143. # Update the space time tables
  144. sp.update_from_registered_maps(dbif)
  145. if connect == True:
  146. dbif.close()
  147. core.percent(num_maps, num_maps, 1)
  148. ###############################################################################
  149. def unregister_maps_from_space_time_datasets(type, name, maps, file=None, dbif = None):
  150. """Unregister maps from a single space time dataset or, in case no dataset name is provided,
  151. unregister from all datasets within the maps are registered.
  152. @param type: The type of the maps raster, vector or raster3d
  153. @param name: Name of an existing space time raster dataset. If no name is provided the raster map(s) are unregistered from all space time datasets in which they are registered.
  154. @param maps: A comma separated list of map names
  155. @param dbif: The database interface to be used
  156. """
  157. if maps and file:
  158. core.fata(_("%s= and %s= are mutually exclusive") % ("input","file"))
  159. mapset = core.gisenv()["MAPSET"]
  160. if dbif == None:
  161. dbif = sql_database_interface()
  162. dbif.connect()
  163. connect = True
  164. # In case a space time dataset is specified
  165. if name:
  166. # Check if the dataset name contains the mapset as well
  167. if name.find("@") < 0:
  168. id = name + "@" + mapset
  169. else:
  170. id = name
  171. if type == "rast":
  172. sp = dataset_factory("strds", id)
  173. if type == "rast3d":
  174. sp = dataset_factory("str3ds", id)
  175. if type == "vect":
  176. sp = dataset_factory("stvds", id)
  177. if sp.is_in_db(dbif) == False:
  178. dbif.close()
  179. core.fatal("Space time " + sp.get_new_map_instance(None).get_type() + " dataset <" + name + "> not found")
  180. maplist = []
  181. # Map names as comma separated string
  182. if maps:
  183. if maps.find(",") == -1:
  184. maplist = (maps,)
  185. else:
  186. maplist = tuple(maps.split(","))
  187. # Read the map list from file
  188. if file:
  189. fd = open(file, "r")
  190. line = True
  191. while True:
  192. line = fd.readline()
  193. if not line:
  194. break
  195. line_list = line.split(fs)
  196. mapname = line_list[0].strip()
  197. maplist.append(mapname)
  198. num_maps = len(maplist)
  199. count = 0
  200. for mapname in maplist:
  201. core.percent(count, num_maps, 1)
  202. mapname = mapname.strip()
  203. # Check if the map name contains the mapset as well
  204. if mapname.find("@") < 0:
  205. mapid = mapname + "@" + mapset
  206. else:
  207. mapid = mapname
  208. map = dataset_factory(type, mapid)
  209. # Unregister map if in database
  210. if map.is_in_db(dbif) == True:
  211. if name:
  212. sp.select(dbif)
  213. sp.unregister_map(map, dbif)
  214. else:
  215. map.select(dbif)
  216. map.unregister(dbif)
  217. count += 1
  218. if name:
  219. sp.update_from_registered_maps(dbif)
  220. if connect == True:
  221. dbif.close()
  222. core.percent(num_maps, num_maps, 1)
  223. ###############################################################################
  224. def assign_valid_time_to_maps(type, maps, ttype, start, end=None, file=file, increment=None, dbif = None, interval=False, fs="|"):
  225. """Use this method to assign valid time (absolute or relative) to raster,
  226. raster3d and vector datasets.
  227. It takes care of the correct update of the space time datasets from all
  228. registered maps.
  229. Valid end time and increment are mutual exclusive.
  230. @param type: The type of the maps raster, raster3d or vector
  231. @param maps: A comma separated list of map names
  232. @param start: The start date and time of the first raster map (format absolute: "yyyy-mm-dd HH:MM:SS" or "yyyy-mm-dd", format relative 5.0)
  233. @param end: The end date and time of the first raster map (format absolute: "yyyy-mm-dd HH:MM:SS" or "yyyy-mm-dd", format relative 5.0)
  234. @param increment: Time increment between maps for time stamp creation (format absolute: NNN seconds, minutes, hours, days, weeks, months, years; format relative: 1.0)
  235. @param file: Input file one map with optional start and end time, one per line
  236. @param dbif: The database interface to be used
  237. @param interval: If True, time intervals are created in case the start time and an increment is provided
  238. @param fs: Field separator used in input file
  239. """
  240. start_time_in_file = False
  241. end_time_in_file = False
  242. if end and increment:
  243. if dbif:
  244. dbif.close()
  245. core.fatal(_("Valid end time and increment are mutual exclusive"))
  246. # List of space time datasets to be updated
  247. splist = {}
  248. if maps and file:
  249. core.fata(_("%s= and %s= are mutually exclusive") % ("input","file"))
  250. if end and increment:
  251. core.fata(_("%s= and %s= are mutually exclusive") % ("end","increment"))
  252. if end and not start:
  253. core.fata(_("Please specify %s= and %s=") % ("start_time","end_time"))
  254. if not maps and not file:
  255. core.fata(_("Please specify %s= or %s=") % ("input","file"))
  256. if start and start == "file":
  257. start_time_in_file = True
  258. if end and end == "file":
  259. end_time_in_file = True
  260. # We may need the mapset
  261. mapset = core.gisenv()["MAPSET"]
  262. connect = False
  263. if dbif == None:
  264. dbif = sql_database_interface()
  265. dbif.connect()
  266. connect = True
  267. maplist = []
  268. # Map names as comma separated string
  269. if maps:
  270. if maps.find(",") == -1:
  271. maplist = (maps,)
  272. else:
  273. maplist = tuple(maps.split(","))
  274. # Read the map list from file
  275. if file:
  276. fd = open(file, "r")
  277. line = True
  278. while True:
  279. line = fd.readline()
  280. if not line:
  281. break
  282. line_list = line.split(fs)
  283. mapname = line_list[0].strip()
  284. if mapname.find("@") < 0:
  285. mapid = mapname + "@" + mapset
  286. else:
  287. mapid = mapname
  288. row = {}
  289. row["id"] = mapid
  290. if start_time_in_file and end_time_in_file:
  291. row["start"] = line_list[1].strip()
  292. row["end"] = line_list[2].strip()
  293. if start_time_in_file and not end_time_in_file:
  294. row["start"] = line_list[1].strip()
  295. maplist.append(row)
  296. num_maps = len(maplist)
  297. count = 0
  298. for entry in maplist:
  299. core.percent(count, num_maps, 1)
  300. if file:
  301. mapid = entry["id"]
  302. else:
  303. if entry.find("@") < 0:
  304. mapid = entry + "@" + mapset
  305. else:
  306. mapid = entry
  307. sp = dataset_factory(type, id)
  308. # Use the time data from file
  309. if start_time_in_file:
  310. start = entry["start"]
  311. if end_time_in_file:
  312. end = entry["end"]
  313. if map.is_in_db(dbif) == False:
  314. # Load the data from the grass file database
  315. map.load()
  316. if ttype == "absolute":
  317. map.set_time_to_absolute()
  318. else:
  319. map.set_time_to_relative()
  320. # Put it into the temporal database
  321. map.insert(dbif)
  322. else:
  323. map.select(dbif)
  324. sprows = map.get_registered_datasets(dbif)
  325. # Make an entry in the dataset list, using a dict make sure that
  326. # each dataset is listed only once
  327. if sprows != None:
  328. for dataset in sprows:
  329. splist[dataset["id"]] = True
  330. # In case the time is in the input file we ignore the increment counter
  331. if start_time_in_file:
  332. count = 1
  333. # Set the valid time
  334. assign_valid_time_to_map(ttype=ttype, map=map, start=start, end=end, increment=increment, mult=count, dbif=dbif, interval=interval)
  335. count += 1
  336. # Update all the space time datasets in which registered maps are changed there valid time
  337. for name in splist.keys():
  338. sp = map.get_new_stds_instance(name)
  339. sp.select(dbif)
  340. sp.update_from_registered_maps(dbif)
  341. if connect == True:
  342. dbif.close()
  343. core.percent(num_maps, num_maps, 1)
  344. ###############################################################################
  345. def assign_valid_time_to_map(ttype, map, start, end, increment=None, mult=1, dbif = None, interval=False):
  346. """Assign the valid time to a map dataset
  347. @param ttype: The temporal type which should be assigned and which the time format is of
  348. @param map: A map dataset object derived from abstract_map_dataset
  349. @param start: The start date and time of the first raster map (format absolute: "yyyy-mm-dd HH:MM:SS" or "yyyy-mm-dd", format relative 5.0)
  350. @param end: The end date and time of the first raster map (format absolute: "yyyy-mm-dd HH:MM:SS" or "yyyy-mm-dd", format relative 5.0)
  351. @param increment: Time increment between maps for time stamp creation (format absolute: NNN seconds, minutes, hours, days, weeks, months, years; format relative: 1.0)
  352. @param multi: A multiplier for the increment
  353. @param dbif: The database interface to use for sql queries
  354. @param interval: If True, time intervals are created in case the start time and an increment is provided
  355. """
  356. connect = False
  357. if dbif == None:
  358. dbif = sql_database_interface()
  359. dbif.connect()
  360. connect = True
  361. if ttype == "absolute":
  362. # Create the start time object
  363. if start.find(":") > 0:
  364. time_format = "%Y-%m-%d %H:%M:%S"
  365. else:
  366. time_format = "%Y-%m-%d"
  367. start_time = datetime.strptime(start, time_format)
  368. end_time = None
  369. if end:
  370. end_time = datetime.strptime(end, time_format)
  371. # Add the increment
  372. if increment:
  373. start_time = increment_datetime_by_string(start_time, increment, mult)
  374. if interval:
  375. end_time = increment_datetime_by_string(start_time, increment, 1)
  376. core.verbose(_("Set absolute valid time for map <%s> to %s - %s") % (map.get_id(), str(start_time), str(end_time)))
  377. map.update_absolute_time(start_time, end_time, None, dbif)
  378. else:
  379. start_time = float(start)
  380. end_time = None
  381. if end:
  382. end_time = float(end)
  383. if increment:
  384. start_time = start_time + mult * float(increment)
  385. if interval:
  386. end_time = start_time + float(increment)
  387. core.verbose(_("Set relative valid time for map <%s> to %f - %s") % (map.get_id(), start_time, str(end_time)))
  388. map.update_relative_time(start_time, end_time, dbif)
  389. if connect == True:
  390. dbif.close()
  391. ###############################################################################
  392. def dataset_factory(type, id):
  393. """A factory functions to create space time or map datasets
  394. @param type: the dataset type: rast, rast3d, vect, strds, str3ds, stvds
  395. @param id: The id of the dataset ("name@mapset")
  396. """
  397. if type == "strds":
  398. sp = space_time_raster_dataset(id)
  399. elif type == "str3ds":
  400. sp = space_time_raster3d_dataset(id)
  401. elif type == "stvds":
  402. sp = space_time_vector_dataset(id)
  403. elif type == "rast":
  404. sp = raster_dataset(id)
  405. elif type == "rast3d":
  406. sp = raster3d_dataset(id)
  407. elif type == "vect":
  408. sp = vector_dataset(id)
  409. else:
  410. core.error(_("Unknown dataset type: %s") % type)
  411. return None
  412. return sp