register.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  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. ###############################################################################
  18. def register_maps_in_space_time_dataset(
  19. type, name, maps=None, file=None, start=None,
  20. end=None, unit=None, increment=None, dbif=None,
  21. interval=False, fs="|"):
  22. """!Use this method to register maps in space time datasets.
  23. Additionally a start time string and an increment string can be
  24. specified to assign a time interval automatically to the maps.
  25. It takes care of the correct update of the space time datasets from all
  26. registered maps.
  27. @param type The type of the maps rast, rast3d or vect
  28. @param name The name of the space time dataset. Maps will be registered in the
  29. temporal database if the name was set to None
  30. @param maps A comma separated list of map names
  31. @param file Input file, one map per line map with start and optional
  32. end time
  33. @param start The start date and time of the first raster map
  34. (format absolute: "yyyy-mm-dd HH:MM:SS" or "yyyy-mm-dd",
  35. format relative is integer 5)
  36. @param end The end date and time of the first raster map
  37. (format absolute: "yyyy-mm-dd HH:MM:SS" or "yyyy-mm-dd",
  38. format relative is integer 5)
  39. @param unit The unit of the relative time: years, months, days,
  40. hours, minutes, seconds
  41. @param increment Time increment between maps for time stamp creation
  42. (format absolute: NNN seconds, minutes, hours, days,
  43. weeks, months, years; format relative: 1.0)
  44. @param dbif The database interface to be used
  45. @param interval If True, time intervals are created in case the start
  46. time and an increment is provided
  47. @param fs Field separator used in input file
  48. """
  49. start_time_in_file = False
  50. end_time_in_file = False
  51. msgr = get_tgis_message_interface()
  52. # Make sure the arguments are of type string
  53. if start != "" and start is not None:
  54. start = str(start)
  55. if end != "" and end is not None:
  56. end = str(end)
  57. if increment != "" and increment is not None:
  58. increment = str(increment)
  59. if maps and file:
  60. msgr.fatal(_("%(m)s= and %(f)s= are mutually exclusive") % {'m': "maps",
  61. 'f': "file"})
  62. if end and increment:
  63. msgr.fatal(_("%(e)s= and %(i)s= are mutually exclusive") % {'e': "end",
  64. 'i': "increment"})
  65. if end and not start:
  66. msgr.fatal(_("Please specify %(st)s= and %(e)s=") % {'st': "start_time",
  67. 'e': "end_time"})
  68. if not maps and not file:
  69. msgr.fatal(_("Please specify %(m)s= or %(f)s=") % {'m': "maps",
  70. 'f': "file"})
  71. # We may need the mapset
  72. mapset = get_current_mapset()
  73. dbif, connected = init_dbif(None)
  74. # The name of the space time dataset is optional
  75. if name:
  76. sp = open_old_space_time_dataset(name, type, dbif)
  77. if sp.is_time_relative() and (start or end) and not unit:
  78. dbif.close()
  79. msgr.fatal(_("Space time %(sp)s dataset <%(name)s> with relative"
  80. " time found, but no relative unit set for %(sp)s "
  81. "maps") % {
  82. 'sp': sp.get_new_map_instance(None).get_type(),
  83. 'name': name})
  84. maplist = []
  85. # Map names as comma separated string
  86. if maps:
  87. if maps.find(",") < 0:
  88. maplist = [maps, ]
  89. else:
  90. maplist = maps.split(",")
  91. # Build the map list again with the ids
  92. for count in range(len(maplist)):
  93. row = {}
  94. mapid = AbstractMapDataset.build_id(maplist[count], mapset, None)
  95. row["id"] = mapid
  96. maplist[count] = row
  97. # Read the map list from file
  98. if file:
  99. fd = open(file, "r")
  100. line = True
  101. while True:
  102. line = fd.readline()
  103. if not line:
  104. break
  105. line_list = line.split(fs)
  106. # Detect start and end time
  107. if len(line_list) == 2:
  108. start_time_in_file = True
  109. end_time_in_file = False
  110. elif len(line_list) == 3:
  111. start_time_in_file = True
  112. end_time_in_file = True
  113. else:
  114. start_time_in_file = False
  115. end_time_in_file = False
  116. mapname = line_list[0].strip()
  117. row = {}
  118. if start_time_in_file and end_time_in_file:
  119. row["start"] = line_list[1].strip()
  120. row["end"] = line_list[2].strip()
  121. if start_time_in_file and not end_time_in_file:
  122. row["start"] = line_list[1].strip()
  123. row["id"] = AbstractMapDataset.build_id(mapname, mapset)
  124. maplist.append(row)
  125. num_maps = len(maplist)
  126. map_object_list = []
  127. statement = ""
  128. # Store the ids of datasets that must be updated
  129. datatsets_to_modify = {}
  130. msgr.message(_("Gathering map informations"))
  131. for count in range(len(maplist)):
  132. if count % 50 == 0:
  133. msgr.percent(count, num_maps, 1)
  134. # Get a new instance of the map type
  135. map = dataset_factory(type, maplist[count]["id"])
  136. if map.map_exists() is not True:
  137. msgr.fatal(_("Unable to update %(t)s map <%(id)s>. "
  138. "The map does not exists.") %
  139. {'t': map.get_type(),
  140. 'id': map.get_map_id()})
  141. # Use the time data from file
  142. if "start" in maplist[count]:
  143. start = maplist[count]["start"]
  144. if "end" in maplist[count]:
  145. end = maplist[count]["end"]
  146. is_in_db = False
  147. # Put the map into the database
  148. if not map.is_in_db(dbif):
  149. # Break in case no valid time is provided
  150. if (start == "" or start is None) and not map.has_grass_timestamp():
  151. dbif.close()
  152. if map.get_layer():
  153. msgr.fatal(_("Unable to register %(t)s map <%(id)s> with "
  154. "layer %(l)s. The map has timestamp and "
  155. "the start time is not set.") % {
  156. 't': map.get_type(), 'id': map.get_map_id(),
  157. 'l': map.get_layer()})
  158. else:
  159. msgr.fatal(_("Unable to register %(t)s map <%(id)s>. The"
  160. " map has no timestamp and the start time "
  161. "is not set.") % {'t': map.get_type(),
  162. 'id': map.get_map_id()})
  163. if start != "" and start != None:
  164. # We need to check if the time is absolute and the unit was specified
  165. time_object = check_datetime_string(start)
  166. if isinstance(time_object, datetime) and unit:
  167. msgr.fatal(_("%(u)s= can only be set for relative time") % {'u': "unit"})
  168. if not isinstance(time_object, datetime) and not unit:
  169. msgr.fatal(_("%(u)s= must be set in case of relative time stamps") % {'u': "unit"})
  170. if unit:
  171. map.set_time_to_relative()
  172. else:
  173. map.set_time_to_absolute()
  174. else:
  175. is_in_db = True
  176. # Check the overwrite flag
  177. if not core.overwrite():
  178. if map.get_layer():
  179. msgr.warning(_("Map is already registered in temporal "
  180. "database. Unable to update %(t)s map "
  181. "<%(id)s> with layer %(l)s. Overwrite flag"
  182. " is not set.") % {'t': map.get_type(),
  183. 'id': map.get_map_id(),
  184. 'l': str(map.get_layer())})
  185. else:
  186. msgr.warning(_("Map is already registered in temporal "
  187. "database. Unable to update %(t)s map "
  188. "<%(id)s>. Overwrite flag is not set.") % {
  189. 't': map.get_type(), 'id': map.get_map_id()})
  190. # Simple registration is allowed
  191. if name:
  192. map_object_list.append(map)
  193. # Jump to next map
  194. continue
  195. # Select information from temporal database
  196. map.select(dbif)
  197. # Save the datasets that must be updated
  198. datasets = map.get_registered_stds(dbif)
  199. if datasets is not None:
  200. for dataset in datasets:
  201. if dataset != "":
  202. datatsets_to_modify[dataset] = dataset
  203. if name and map.get_temporal_type() != sp.get_temporal_type():
  204. dbif.close()
  205. if map.get_layer():
  206. msgr.fatal(_("Unable to update %(t)s map <%(id)s> "
  207. "with layer %(l)s. The temporal types "
  208. "are different.") % {'t': map.get_type(),
  209. 'id': map.get_map_id(),
  210. 'l': map.get_layer()})
  211. else:
  212. msgr.fatal(_("Unable to update %(t)s map <%(id)s>. "
  213. "The temporal types are different.") %
  214. {'t': map.get_type(),
  215. 'id': map.get_map_id()})
  216. # Load the data from the grass file database
  217. map.load()
  218. # Try to read an existing time stamp from the grass spatial database
  219. # in case this map wasn't already registered in the temporal database
  220. if not is_in_db:
  221. map.read_timestamp_from_grass()
  222. # Set the valid time
  223. if start:
  224. # In case the time is in the input file we ignore the increment
  225. # counter
  226. if start_time_in_file:
  227. count = 1
  228. assign_valid_time_to_map(ttype=map.get_temporal_type(),
  229. map=map, start=start, end=end, unit=unit,
  230. increment=increment, mult=count,
  231. interval=interval)
  232. if is_in_db:
  233. # Gather the SQL update statement
  234. statement += map.update_all(dbif=dbif, execute=False)
  235. else:
  236. # Gather the SQL insert statement
  237. statement += map.insert(dbif=dbif, execute=False)
  238. # Sqlite3 performace better for huge datasets when committing in
  239. # small chunks
  240. if dbif.dbmi.__name__ == "sqlite3":
  241. if count % 100 == 0:
  242. if statement is not None and statement != "":
  243. dbif.execute_transaction(statement)
  244. statement = ""
  245. # Store the maps in a list to register in a space time dataset
  246. if name:
  247. map_object_list.append(map)
  248. msgr.percent(num_maps, num_maps, 1)
  249. if statement is not None and statement != "":
  250. msgr.message(_("Register maps in the temporal database"))
  251. dbif.execute_transaction(statement)
  252. # Finally Register the maps in the space time dataset
  253. if name and map_object_list:
  254. count = 0
  255. num_maps = len(map_object_list)
  256. msgr.message(_("Register maps in the space time raster dataset"))
  257. for map in map_object_list:
  258. if count % 50 == 0:
  259. msgr.percent(count, num_maps, 1)
  260. sp.register_map(map=map, dbif=dbif)
  261. count += 1
  262. # Update the space time tables
  263. if name and map_object_list:
  264. msgr.message(_("Update space time raster dataset"))
  265. sp.update_from_registered_maps(dbif)
  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 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 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. if __name__ == "__main__":
  357. import doctest
  358. doctest.testmod()