register.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  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) 2012-2013 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 open_stds import *
  17. import grass.script as gscript
  18. ###############################################################################
  19. def register_maps_in_space_time_dataset(
  20. type, name, maps=None, file=None, start=None,
  21. end=None, unit=None, increment=None, dbif=None,
  22. interval=False, fs="|", update_cmd_list=True):
  23. """!Use this method to register maps in space time datasets.
  24. Additionally a start time string and an increment string can be
  25. specified to assign a time interval automatically to the maps.
  26. It takes care of the correct update of the space time datasets from all
  27. registered maps.
  28. @param type The type of the maps rast, rast3d or vect
  29. @param name The name of the space time dataset. Maps will be registered in the
  30. temporal database if the name was set to None
  31. @param maps A comma separated list of map names
  32. @param file Input file, one map per line map with start and optional
  33. end time
  34. @param start The start date and time of the first raster map
  35. (format absolute: "yyyy-mm-dd HH:MM:SS" or "yyyy-mm-dd",
  36. format relative is integer 5)
  37. @param end The end date and time of the first raster map
  38. (format absolute: "yyyy-mm-dd HH:MM:SS" or "yyyy-mm-dd",
  39. format relative is integer 5)
  40. @param unit The unit of the relative time: years, months, days,
  41. hours, minutes, seconds
  42. @param increment Time increment between maps for time stamp creation
  43. (format absolute: NNN seconds, minutes, hours, days,
  44. weeks, months, years; format relative: 1.0)
  45. @param dbif The database interface to be used
  46. @param interval If True, time intervals are created in case the start
  47. time and an increment is provided
  48. @param fs Field separator used in input file
  49. @param update_cmd_list If is True, the command that was invoking this process
  50. will be written to the process history
  51. """
  52. start_time_in_file = False
  53. end_time_in_file = False
  54. msgr = get_tgis_message_interface()
  55. # Make sure the arguments are of type string
  56. if start != "" and start is not None:
  57. start = str(start)
  58. if end != "" and end is not None:
  59. end = str(end)
  60. if increment != "" and increment is not None:
  61. increment = str(increment)
  62. if maps and file:
  63. msgr.fatal(_("%s= and %s= are mutually exclusive") % ("maps", "file"))
  64. if end and increment:
  65. msgr.fatal(_("%s= and %s= are mutually exclusive") % ("end", "increment"))
  66. if end and not start:
  67. msgr.fatal(_("Please specify %s= and %s=") % ("start_time", "end_time"))
  68. if not maps and not file:
  69. msgr.fatal(_("Please specify %s= or %s=") % ("maps", "file"))
  70. # We may need the mapset
  71. mapset = get_current_mapset()
  72. dbif, connected = init_dbif(None)
  73. # The name of the space time dataset is optional
  74. if name:
  75. sp = open_old_stds(name, type, dbif)
  76. if sp.is_time_relative() and (start or end) and not unit:
  77. dbif.close()
  78. msgr.fatal(_("Space time %(sp)s dataset <%(name)s> with relative"
  79. " time found, but no relative unit set for %(sp)s "
  80. "maps") % {
  81. 'sp': sp.get_new_map_instance(None).get_type(),
  82. 'name': name})
  83. maplist = []
  84. # Map names as comma separated string
  85. if maps:
  86. if maps.find(",") < 0:
  87. maplist = [maps, ]
  88. else:
  89. maplist = maps.split(",")
  90. # Build the map list again with the ids
  91. for count in range(len(maplist)):
  92. row = {}
  93. mapid = AbstractMapDataset.build_id(maplist[count], mapset, None)
  94. row["id"] = mapid
  95. maplist[count] = row
  96. # Read the map list from file
  97. if file:
  98. fd = open(file, "r")
  99. line = True
  100. while True:
  101. line = fd.readline()
  102. if not line:
  103. break
  104. line_list = line.split(fs)
  105. # Detect start and end time
  106. if len(line_list) == 2:
  107. start_time_in_file = True
  108. end_time_in_file = False
  109. elif len(line_list) == 3:
  110. start_time_in_file = True
  111. end_time_in_file = True
  112. else:
  113. start_time_in_file = False
  114. end_time_in_file = False
  115. mapname = line_list[0].strip()
  116. row = {}
  117. if start_time_in_file and end_time_in_file:
  118. row["start"] = line_list[1].strip()
  119. row["end"] = line_list[2].strip()
  120. if start_time_in_file and not end_time_in_file:
  121. row["start"] = line_list[1].strip()
  122. row["id"] = AbstractMapDataset.build_id(mapname, mapset)
  123. maplist.append(row)
  124. num_maps = len(maplist)
  125. map_object_list = []
  126. statement = ""
  127. # Store the ids of datasets that must be updated
  128. datatsets_to_modify = {}
  129. msgr.message(_("Gathering map information..."))
  130. for count in range(len(maplist)):
  131. if count % 50 == 0:
  132. msgr.percent(count, num_maps, 1)
  133. # Get a new instance of the map type
  134. map = dataset_factory(type, maplist[count]["id"])
  135. if map.map_exists() is not True:
  136. msgr.fatal(_("Unable to update %(t)s map <%(id)s>. "
  137. "The map does not exist.") %
  138. {'t': map.get_type(),
  139. 'id': map.get_map_id()})
  140. # Use the time data from file
  141. if "start" in maplist[count]:
  142. start = maplist[count]["start"]
  143. if "end" in maplist[count]:
  144. end = maplist[count]["end"]
  145. is_in_db = False
  146. # Put the map into the database
  147. if not map.is_in_db(dbif):
  148. # Break in case no valid time is provided
  149. if (start == "" or start is None) and not map.has_grass_timestamp():
  150. dbif.close()
  151. if map.get_layer():
  152. msgr.fatal(_("Unable to register %(t)s map <%(id)s> with "
  153. "layer %(l)s. The map has timestamp and "
  154. "the start time is not set.") % {
  155. 't': map.get_type(), 'id': map.get_map_id(),
  156. 'l': map.get_layer()})
  157. else:
  158. msgr.fatal(_("Unable to register %(t)s map <%(id)s>. The"
  159. " map has no timestamp and the start time "
  160. "is not set.") % {'t': map.get_type(),
  161. 'id': map.get_map_id()})
  162. if start != "" and start != None:
  163. # We need to check if the time is absolute and the unit was specified
  164. time_object = check_datetime_string(start)
  165. if isinstance(time_object, datetime) and unit:
  166. msgr.fatal(_("%(u)s= can only be set for relative time") % {'u': "unit"})
  167. if not isinstance(time_object, datetime) and not unit:
  168. msgr.fatal(_("%(u)s= must be set in case of relative time stamps") % {'u': "unit"})
  169. if unit:
  170. map.set_time_to_relative()
  171. else:
  172. map.set_time_to_absolute()
  173. else:
  174. is_in_db = True
  175. # Check the overwrite flag
  176. if not gscript.overwrite():
  177. if map.get_layer():
  178. msgr.warning(_("Map is already registered in temporal "
  179. "database. Unable to update %(t)s map "
  180. "<%(id)s> with layer %(l)s. Overwrite flag"
  181. " is not set.") % {'t': map.get_type(),
  182. 'id': map.get_map_id(),
  183. 'l': str(map.get_layer())})
  184. else:
  185. msgr.warning(_("Map is already registered in temporal "
  186. "database. Unable to update %(t)s map "
  187. "<%(id)s>. Overwrite flag is not set.") % {
  188. 't': map.get_type(), 'id': map.get_map_id()})
  189. # Simple registration is allowed
  190. if name:
  191. map_object_list.append(map)
  192. # Jump to next map
  193. continue
  194. # Select information from temporal database
  195. map.select(dbif)
  196. # Save the datasets that must be updated
  197. datasets = map.get_registered_stds(dbif)
  198. if datasets is not None:
  199. for dataset in datasets:
  200. if dataset != "":
  201. datatsets_to_modify[dataset] = dataset
  202. if name and map.get_temporal_type() != sp.get_temporal_type():
  203. dbif.close()
  204. if map.get_layer():
  205. msgr.fatal(_("Unable to update %(t)s map <%(id)s> "
  206. "with layer %(l)s. The temporal types "
  207. "are different.") % {'t': map.get_type(),
  208. 'id': map.get_map_id(),
  209. 'l': map.get_layer()})
  210. else:
  211. msgr.fatal(_("Unable to update %(t)s map <%(id)s>. "
  212. "The temporal types are different.") %
  213. {'t': map.get_type(),
  214. 'id': map.get_map_id()})
  215. # Load the data from the grass file database
  216. map.load()
  217. # Try to read an existing time stamp from the grass spatial database
  218. # in case this map wasn't already registered in the temporal database
  219. if not is_in_db:
  220. map.read_timestamp_from_grass()
  221. # Set the valid time
  222. if start:
  223. # In case the time is in the input file we ignore the increment
  224. # counter
  225. if start_time_in_file:
  226. count = 1
  227. assign_valid_time_to_map(ttype=map.get_temporal_type(),
  228. map=map, start=start, end=end, unit=unit,
  229. increment=increment, mult=count,
  230. interval=interval)
  231. if is_in_db:
  232. # Gather the SQL update statement
  233. statement += map.update_all(dbif=dbif, execute=False)
  234. else:
  235. # Gather the SQL insert statement
  236. statement += map.insert(dbif=dbif, execute=False)
  237. # Sqlite3 performance is better for huge datasets when committing in
  238. # small chunks
  239. if dbif.get_dbmi().__name__ == "sqlite3":
  240. if count % 100 == 0:
  241. if statement is not None and statement != "":
  242. dbif.execute_transaction(statement)
  243. statement = ""
  244. # Store the maps in a list to register in a space time dataset
  245. if name:
  246. map_object_list.append(map)
  247. msgr.percent(num_maps, num_maps, 1)
  248. if statement is not None and statement != "":
  249. msgr.message(_("Registering maps in the temporal database..."))
  250. dbif.execute_transaction(statement)
  251. # Finally Register the maps in the space time dataset
  252. if name and map_object_list:
  253. count = 0
  254. num_maps = len(map_object_list)
  255. msgr.message(_("Registering maps in the space time raster dataset..."))
  256. for map in map_object_list:
  257. if count % 50 == 0:
  258. msgr.percent(count, num_maps, 1)
  259. sp.register_map(map=map, dbif=dbif)
  260. count += 1
  261. # Update the space time tables
  262. if name and map_object_list:
  263. msgr.message(_("Updating space time raster dataset..."))
  264. sp.update_from_registered_maps(dbif)
  265. if update_cmd_list is True:
  266. sp.update_command_string(dbif=dbif)
  267. # Update affected datasets
  268. if datatsets_to_modify:
  269. for dataset in datatsets_to_modify:
  270. if type == "rast" or type == "raster":
  271. ds = dataset_factory("strds", dataset)
  272. elif type == "rast3d":
  273. ds = dataset_factory("str3ds", dataset)
  274. elif type == "vect" or type == "vector":
  275. ds = dataset_factory("stvds", dataset)
  276. ds.select(dbif)
  277. ds.update_from_registered_maps(dbif)
  278. if connected == True:
  279. dbif.close()
  280. msgr.percent(num_maps, num_maps, 1)
  281. ###############################################################################
  282. def assign_valid_time_to_map(ttype, map, start, end, unit, increment=None,
  283. mult=1, interval=False):
  284. """!Assign the valid time to a map dataset
  285. @param ttype The temporal type which should be assigned
  286. and which the time format is of
  287. @param map A map dataset object derived from abstract_map_dataset
  288. @param start The start date and time of the first raster map
  289. (format absolute: "yyyy-mm-dd HH:MM:SS" or "yyyy-mm-dd",
  290. format relative is integer 5)
  291. @param end The end date and time of the first raster map
  292. (format absolute: "yyyy-mm-dd HH:MM:SS" or "yyyy-mm-dd",
  293. format relative is integer 5)
  294. @param unit The unit of the relative time: years, months,
  295. days, hours, minutes, seconds
  296. @param increment Time increment between maps for time stamp creation
  297. (format absolute: NNN seconds, minutes, hours, days,
  298. weeks, months, years; format relative is integer 1)
  299. @param mult A multiplier for the increment
  300. @param interval If True, time intervals are created in case the start
  301. time and an increment is provided
  302. """
  303. msgr = get_tgis_message_interface()
  304. if ttype == "absolute":
  305. start_time = string_to_datetime(start)
  306. if start_time is None:
  307. msgr.fatal(_("Unable to convert string \"%s\"into a "
  308. "datetime object") % (start))
  309. end_time = None
  310. if end:
  311. end_time = string_to_datetime(end)
  312. if end_time is None:
  313. dbif.close()
  314. msgr.fatal(_("Unable to convert string \"%s\"into a "
  315. "datetime object") % (end))
  316. # Add the increment
  317. if increment:
  318. start_time = increment_datetime_by_string(
  319. start_time, increment, mult)
  320. if start_time is None:
  321. msgr.fatal(_("Error occurred in increment computation"))
  322. if interval:
  323. end_time = increment_datetime_by_string(
  324. start_time, increment, 1)
  325. if end_time is None:
  326. msgr.fatal(_("Error occurred in increment computation"))
  327. if map.get_layer():
  328. msgr.debug(1, _("Set absolute valid time for map <%(id)s> with "
  329. "layer %(layer)s to %(start)s - %(end)s") %
  330. {'id': map.get_map_id(), 'layer': map.get_layer(),
  331. 'start': str(start_time), 'end': str(end_time)})
  332. else:
  333. msgr.debug(1, _("Set absolute valid time for map <%s> to %s - %s") %
  334. (map.get_map_id(), str(start_time), str(end_time)))
  335. map.set_absolute_time(start_time, end_time)
  336. else:
  337. start_time = int(start)
  338. end_time = None
  339. if end:
  340. end_time = int(end)
  341. if increment:
  342. start_time = start_time + mult * int(increment)
  343. if interval:
  344. end_time = start_time + int(increment)
  345. if map.get_layer():
  346. msgr.debug(1, _("Set relative valid time for map <%s> with layer %s "
  347. "to %i - %s with unit %s") %
  348. (map.get_map_id(), map.get_layer(), start_time,
  349. str(end_time), unit))
  350. else:
  351. msgr.debug(1, _("Set relative valid time for map <%s> to %i - %s "
  352. "with unit %s") % (map.get_map_id(), start_time,
  353. str(end_time), unit))
  354. map.set_relative_time(start_time, end_time, unit)
  355. ##############################################################################
  356. def register_map_object_list(type, map_list, output_stds,
  357. delete_empty, unit, dbif=None):
  358. """Register a list of AbstractMapDataset objects in the temporal database
  359. and optional in a space time dataset.
  360. @param type The type of the map layer (rast, rast3d, vect)
  361. @param map_list List of AbstractMapDataset objects
  362. @param output_stds The output stds
  363. @param delete_empty Set True to delete empty map layer found in the map_list
  364. @param unit The temporal unit of the space time dataset
  365. @param dbif The database interface to be used
  366. """
  367. import grass.pygrass.modules as pymod
  368. import copy
  369. dbif, connected = init_dbif(dbif)
  370. filename = gscript.tempfile(True)
  371. file = open(filename, 'w')
  372. empty_maps = []
  373. for map_layer in map_list:
  374. # Read the raster map data
  375. map_layer.load()
  376. # In case of a empty map continue, do not register empty maps
  377. if delete_empty:
  378. if map_layer.metadata.get_min() is None and \
  379. map_layer.metadata.get_max() is None:
  380. empty_maps.append(map_layer)
  381. continue
  382. start, end = map_layer.get_temporal_extent_as_tuple()
  383. id = map_layer.get_id()
  384. if not end:
  385. end = start
  386. string = "%s|%s|%s\n" % (id, str(start), str(end))
  387. file.write(string)
  388. file.close()
  389. if output_stds:
  390. output_stds_id = output_stds.get_id()
  391. else:
  392. output_stds_id = None
  393. register_maps_in_space_time_dataset(type, output_stds_id, unit=unit,
  394. file=filename, dbif=dbif)
  395. g_remove = pymod.Module("g.remove", quiet=True,
  396. run_=False, finish_=True)
  397. # Remove empty maps
  398. if len(empty_maps) > 0:
  399. for map in empty_maps:
  400. if map.is_in_db(dbif):
  401. map.delete(dbif)
  402. mod = copy.deepcopy(g_remove)
  403. mod(rast=map.get_name())
  404. mod.run()
  405. if connected:
  406. dbif.close()
  407. if __name__ == "__main__":
  408. import doctest
  409. doctest.testmod()