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 (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. # 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 is not None:
  195. for dataset in datasets:
  196. if dataset != "":
  197. datatsets_to_modify[dataset] = dataset
  198. if name and map.get_temporal_type() != sp.get_temporal_type():
  199. dbif.close()
  200. if map.get_layer():
  201. msgr.fatal(_("Unable to update %(t)s map <%(id)s> "
  202. "with layer %(l)s. The temporal types "
  203. "are different.") % {'t': map.get_type(),
  204. 'id': map.get_map_id(),
  205. 'l': map.get_layer()})
  206. else:
  207. msgr.fatal(_("Unable to update %(t)s map <%(id)s>. "
  208. "The temporal types are different.") %
  209. {'t': map.get_type(),
  210. 'id': map.get_map_id()})
  211. # Load the data from the grass file database
  212. map.load()
  213. # Try to read an existing time stamp from the grass spatial database
  214. # in case this map wasn't already registered in the temporal database
  215. if not is_in_db:
  216. map.read_timestamp_from_grass()
  217. # Set the valid time
  218. if start:
  219. # In case the time is in the input file we ignore the increment
  220. # counter
  221. if start_time_in_file:
  222. count = 1
  223. assign_valid_time_to_map(ttype=map.get_temporal_type(),
  224. map=map, start=start, end=end, unit=unit,
  225. increment=increment, mult=count,
  226. interval=interval)
  227. if is_in_db:
  228. # Gather the SQL update statement
  229. statement += map.update_all(dbif=dbif, execute=False)
  230. else:
  231. # Gather the SQL insert statement
  232. statement += map.insert(dbif=dbif, execute=False)
  233. # Sqlite3 performace better for huge datasets when committing in
  234. # small chunks
  235. if dbif.dbmi.__name__ == "sqlite3":
  236. if count % 100 == 0:
  237. if statement is not None and statement != "":
  238. dbif.execute_transaction(statement)
  239. statement = ""
  240. # Store the maps in a list to register in a space time dataset
  241. if name:
  242. map_object_list.append(map)
  243. msgr.percent(num_maps, num_maps, 1)
  244. if statement is not None and statement != "":
  245. msgr.message(_("Register maps in the temporal database"))
  246. dbif.execute_transaction(statement)
  247. # Finally Register the maps in the space time dataset
  248. if name and map_object_list:
  249. count = 0
  250. num_maps = len(map_object_list)
  251. msgr.message(_("Register maps in the space time raster dataset"))
  252. for map in map_object_list:
  253. if count % 50 == 0:
  254. msgr.percent(count, num_maps, 1)
  255. sp.register_map(map=map, dbif=dbif)
  256. count += 1
  257. # Update the space time tables
  258. if name and map_object_list:
  259. msgr.message(_("Update space time raster dataset"))
  260. sp.update_from_registered_maps(dbif)
  261. sp.update_command_string(dbif=dbif)
  262. # Update affected datasets
  263. if datatsets_to_modify:
  264. for dataset in datatsets_to_modify:
  265. if type == "rast" or type == "raster":
  266. ds = dataset_factory("strds", dataset)
  267. elif type == "rast3d":
  268. ds = dataset_factory("str3ds", dataset)
  269. elif type == "vect" or type == "vector":
  270. ds = dataset_factory("stvds", dataset)
  271. ds.select(dbif)
  272. ds.update_from_registered_maps(dbif)
  273. if connected == True:
  274. dbif.close()
  275. msgr.percent(num_maps, num_maps, 1)
  276. ###############################################################################
  277. def assign_valid_time_to_map(ttype, map, start, end, unit, increment=None,
  278. mult=1, interval=False):
  279. """!Assign the valid time to a map dataset
  280. @param ttype The temporal type which should be assigned
  281. and which the time format is of
  282. @param map A map dataset object derived from abstract_map_dataset
  283. @param start The start date and time of the first raster map
  284. (format absolute: "yyyy-mm-dd HH:MM:SS" or "yyyy-mm-dd",
  285. format relative is integer 5)
  286. @param end The end date and time of the first raster map
  287. (format absolute: "yyyy-mm-dd HH:MM:SS" or "yyyy-mm-dd",
  288. format relative is integer 5)
  289. @param unit The unit of the relative time: years, months,
  290. days, hours, minutes, seconds
  291. @param increment Time increment between maps for time stamp creation
  292. (format absolute: NNN seconds, minutes, hours, days,
  293. weeks, months, years; format relative is integer 1)
  294. @param mult A multiplier for the increment
  295. @param interval If True, time intervals are created in case the start
  296. time and an increment is provided
  297. """
  298. msgr = get_tgis_message_interface()
  299. if ttype == "absolute":
  300. start_time = string_to_datetime(start)
  301. if start_time is None:
  302. msgr.fatal(_("Unable to convert string \"%s\"into a "
  303. "datetime object") % (start))
  304. end_time = None
  305. if end:
  306. end_time = string_to_datetime(end)
  307. if end_time is None:
  308. dbif.close()
  309. msgr.fatal(_("Unable to convert string \"%s\"into a "
  310. "datetime object") % (end))
  311. # Add the increment
  312. if increment:
  313. start_time = increment_datetime_by_string(
  314. start_time, increment, mult)
  315. if start_time is None:
  316. msgr.fatal(_("Error in increment computation"))
  317. if interval:
  318. end_time = increment_datetime_by_string(
  319. start_time, increment, 1)
  320. if end_time is None:
  321. msgr.fatal(_("Error in increment computation"))
  322. if map.get_layer():
  323. msgr.debug(1, _("Set absolute valid time for map <%(id)s> with "
  324. "layer %(layer)s to %(start)s - %(end)s") %
  325. {'id': map.get_map_id(), 'layer': map.get_layer(),
  326. 'start': str(start_time), 'end': str(end_time)})
  327. else:
  328. msgr.debug(1, _("Set absolute valid time for map <%s> to %s - %s") %
  329. (map.get_map_id(), str(start_time), str(end_time)))
  330. map.set_absolute_time(start_time, end_time)
  331. else:
  332. start_time = int(start)
  333. end_time = None
  334. if end:
  335. end_time = int(end)
  336. if increment:
  337. start_time = start_time + mult * int(increment)
  338. if interval:
  339. end_time = start_time + int(increment)
  340. if map.get_layer():
  341. msgr.debug(1, _("Set relative valid time for map <%s> with layer %s "
  342. "to %i - %s with unit %s") %
  343. (map.get_map_id(), map.get_layer(), start_time,
  344. str(end_time), unit))
  345. else:
  346. msgr.debug(1, _("Set relative valid time for map <%s> to %i - %s "
  347. "with unit %s") % (map.get_map_id(), start_time,
  348. str(end_time), unit))
  349. map.set_relative_time(start_time, end_time, unit)
  350. ###############################################################################
  351. if __name__ == "__main__":
  352. import doctest
  353. doctest.testmod()