register.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  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 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. # Use the time data from file
  137. if "start" in maplist[count]:
  138. start = maplist[count]["start"]
  139. if "end" in maplist[count]:
  140. end = maplist[count]["end"]
  141. is_in_db = False
  142. # Put the map into the database
  143. if not map.is_in_db(dbif):
  144. # Break in case no valid time is provided
  145. if (start == "" or start is None) and not map.has_grass_timestamp():
  146. dbif.close()
  147. if map.get_layer():
  148. msgr.fatal(_("Unable to register %(t)s map <%(id)s> with "
  149. "layer %(l)s. The map has timestamp and "
  150. "the start time is not set.") % {
  151. 't': map.get_type(), 'id': map.get_map_id(),
  152. 'l': map.get_layer()})
  153. else:
  154. msgr.fatal(_("Unable to register %(t)s map <%(id)s>. The"
  155. " map has no timestamp and the start time "
  156. "is not set.") % {'t': map.get_type(),
  157. 'id': map.get_map_id()})
  158. if start != "" and start != None:
  159. # We need to check if the time is absolute and the unit was specified
  160. time_object = check_datetime_string(start)
  161. if isinstance(time_object, datetime) and unit:
  162. msgr.fatal(_("%(u)s= can only be set for relative time") % {'u': "unit"})
  163. if not isinstance(time_object, datetime) and not unit:
  164. msgr.fatal(_("%(u)s= must be set in case of relative time stamps") % {'u': "unit"})
  165. if unit:
  166. map.set_time_to_relative()
  167. else:
  168. map.set_time_to_absolute()
  169. else:
  170. is_in_db = True
  171. # Check the overwrite flag
  172. if not core.overwrite():
  173. if map.get_layer():
  174. msgr.warning(_("Map is already registered in temporal "
  175. "database. Unable to update %(t)s map "
  176. "<%(id)s> with layer %(l)s. Overwrite flag"
  177. " is not set.") % {'t': map.get_type(),
  178. 'id': map.get_map_id(),
  179. 'l': str(map.get_layer())})
  180. else:
  181. msgr.warning(_("Map is already registered in temporal "
  182. "database. Unable to update %(t)s map "
  183. "<%(id)s>. Overwrite flag is not set.") % {
  184. 't': map.get_type(), 'id': map.get_map_id()})
  185. # Simple registration is allowed
  186. if name:
  187. map_object_list.append(map)
  188. # Jump to next map
  189. continue
  190. # Select information from temporal database
  191. map.select(dbif)
  192. # Save the datasets that must be updated
  193. datasets = map.get_registered_datasets(dbif)
  194. if datasets:
  195. for dataset in datasets:
  196. datatsets_to_modify[dataset["id"]] = dataset["id"]
  197. if name and map.get_temporal_type() != sp.get_temporal_type():
  198. dbif.close()
  199. if map.get_layer():
  200. msgr.fatal(_("Unable to update %(t)s map <%(id)s> "
  201. "with layer %(l)s. The temporal types "
  202. "are different.") % {'t': map.get_type(),
  203. 'id': map.get_map_id(),
  204. 'l': map.get_layer()})
  205. else:
  206. msgr.fatal(_("Unable to update %(t)s map <%(id)s>. "
  207. "The temporal types are different.") %
  208. {'t': map.get_type(),
  209. 'id': map.get_map_id()})
  210. # Load the data from the grass file database
  211. map.load()
  212. # Try to read an existing time stamp from the grass spatial database
  213. # in case this map wasn't already registered in the temporal database
  214. if not is_in_db:
  215. map.read_timestamp_from_grass()
  216. # Set the valid time
  217. if start:
  218. # In case the time is in the input file we ignore the increment
  219. # counter
  220. if start_time_in_file:
  221. count = 1
  222. assign_valid_time_to_map(ttype=map.get_temporal_type(),
  223. map=map, start=start, end=end, unit=unit,
  224. increment=increment, mult=count,
  225. interval=interval)
  226. if is_in_db:
  227. # Gather the SQL update statement
  228. statement += map.update_all(dbif=dbif, execute=False)
  229. else:
  230. # Gather the SQL insert statement
  231. statement += map.insert(dbif=dbif, execute=False)
  232. # Sqlite3 performace better for huge datasets when committing in
  233. # small chunks
  234. if dbif.dbmi.__name__ == "sqlite3":
  235. if count % 100 == 0:
  236. if statement is not None and statement != "":
  237. dbif.execute_transaction(statement)
  238. statement = ""
  239. # Store the maps in a list to register in a space time dataset
  240. if name:
  241. map_object_list.append(map)
  242. msgr.percent(num_maps, num_maps, 1)
  243. if statement is not None and statement != "":
  244. msgr.message(_("Register maps in the temporal database"))
  245. dbif.execute_transaction(statement)
  246. # Finally Register the maps in the space time dataset
  247. if name and map_object_list:
  248. count = 0
  249. num_maps = len(map_object_list)
  250. msgr.message(_("Register maps in the space time raster dataset"))
  251. for map in map_object_list:
  252. if count % 50 == 0:
  253. msgr.percent(count, num_maps, 1)
  254. sp.register_map(map=map, dbif=dbif)
  255. count += 1
  256. # Update the space time tables
  257. if name and map_object_list:
  258. msgr.message(_("Update space time raster dataset"))
  259. sp.update_from_registered_maps(dbif)
  260. sp.update_command_string(dbif=dbif)
  261. # Update affected datasets
  262. if datatsets_to_modify:
  263. for dataset in datatsets_to_modify:
  264. if type == "rast" or type == "raster":
  265. ds = dataset_factory("strds", dataset)
  266. elif type == "rast3d":
  267. ds = dataset_factory("str3ds", dataset)
  268. elif type == "vect" or type == "vector":
  269. ds = dataset_factory("stvds", dataset)
  270. ds.select(dbif)
  271. ds.update_from_registered_maps(dbif)
  272. if connected == True:
  273. dbif.close()
  274. msgr.percent(num_maps, num_maps, 1)
  275. ###############################################################################
  276. def assign_valid_time_to_map(ttype, map, start, end, unit, increment=None,
  277. mult=1, interval=False):
  278. """!Assign the valid time to a map dataset
  279. @param ttype The temporal type which should be assigned
  280. and which the time format is of
  281. @param map A map dataset object derived from abstract_map_dataset
  282. @param start The start date and time of the first raster map
  283. (format absolute: "yyyy-mm-dd HH:MM:SS" or "yyyy-mm-dd",
  284. format relative is integer 5)
  285. @param end The end date and time of the first raster map
  286. (format absolute: "yyyy-mm-dd HH:MM:SS" or "yyyy-mm-dd",
  287. format relative is integer 5)
  288. @param unit The unit of the relative time: years, months,
  289. days, hours, minutes, seconds
  290. @param increment Time increment between maps for time stamp creation
  291. (format absolute: NNN seconds, minutes, hours, days,
  292. weeks, months, years; format relative is integer 1)
  293. @param mult A multiplier for the increment
  294. @param interval If True, time intervals are created in case the start
  295. time and an increment is provided
  296. """
  297. msgr = get_tgis_message_interface()
  298. if ttype == "absolute":
  299. start_time = string_to_datetime(start)
  300. if start_time is None:
  301. msgr.fatal(_("Unable to convert string \"%s\"into a "
  302. "datetime object") % (start))
  303. end_time = None
  304. if end:
  305. end_time = string_to_datetime(end)
  306. if end_time is None:
  307. dbif.close()
  308. msgr.fatal(_("Unable to convert string \"%s\"into a "
  309. "datetime object") % (end))
  310. # Add the increment
  311. if increment:
  312. start_time = increment_datetime_by_string(
  313. start_time, increment, mult)
  314. if start_time is None:
  315. msgr.fatal(_("Error in increment computation"))
  316. if interval:
  317. end_time = increment_datetime_by_string(
  318. start_time, increment, 1)
  319. if end_time is None:
  320. msgr.fatal(_("Error in increment computation"))
  321. if map.get_layer():
  322. msgr.debug(1, _("Set absolute valid time for map <%(id)s> with "
  323. "layer %(layer)s to %(start)s - %(end)s") %
  324. {'id': map.get_map_id(), 'layer': map.get_layer(),
  325. 'start': str(start_time), 'end': str(end_time)})
  326. else:
  327. msgr.debug(1, _("Set absolute valid time for map <%s> to %s - %s") %
  328. (map.get_map_id(), str(start_time), str(end_time)))
  329. map.set_absolute_time(start_time, end_time, None)
  330. else:
  331. start_time = int(start)
  332. end_time = None
  333. if end:
  334. end_time = int(end)
  335. if increment:
  336. start_time = start_time + mult * int(increment)
  337. if interval:
  338. end_time = start_time + int(increment)
  339. if map.get_layer():
  340. msgr.debug(1, _("Set relative valid time for map <%s> with layer %s "
  341. "to %i - %s with unit %s") %
  342. (map.get_map_id(), map.get_layer(), start_time,
  343. str(end_time), unit))
  344. else:
  345. msgr.debug(1, _("Set relative valid time for map <%s> to %i - %s "
  346. "with unit %s") % (map.get_map_id(), start_time,
  347. str(end_time), unit))
  348. map.set_relative_time(start_time, end_time, unit)
  349. ###############################################################################
  350. if __name__ == "__main__":
  351. import doctest
  352. doctest.testmod()