register.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  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. from factory import *
  18. from open import *
  19. ###############################################################################
  20. def register_maps_in_space_time_dataset(
  21. type, name, maps=None, file=None, start=None,
  22. end=None, unit=None, increment=None, dbif=None,
  23. interval=False, fs="|"):
  24. """!Use this method to register maps in space time datasets.
  25. Additionally a start time string and an increment string can be
  26. specified to assign a time interval automatically to the maps.
  27. It takes care of the correct update of the space time datasets from all
  28. registered maps.
  29. @param type The type of the maps rast, rast3d or vect
  30. @param name The name of the space time dataset
  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. """
  50. start_time_in_file = False
  51. end_time_in_file = False
  52. if maps and file:
  53. core.fatal(_("%(m)s= and %(f)s= are mutually exclusive") % {'m': "maps",
  54. 'f': "file"})
  55. if end and increment:
  56. core.fatal(_("%(e)s= and %(i)s= are mutually exclusive") % {'e': "end",
  57. 'i': "increment"})
  58. if end and not start:
  59. core.fatal(_("Please specify %(st)s= and %(e)s=") % {'st': "start_time",
  60. 'e': "end_time"})
  61. if not maps and not file:
  62. core.fatal(_("Please specify %(m)s= or %(f)s=") % {'m': "maps",
  63. 'f': "file"})
  64. # We may need the mapset
  65. mapset = get_current_mapset()
  66. dbif, connected = init_dbif(None)
  67. # The name of the space time dataset is optional
  68. if name:
  69. sp = open_old_space_time_dataset(name, type, dbif)
  70. if sp.is_time_relative() and not unit:
  71. dbif.close()
  72. core.fatal(_("Space time %(sp)s dataset <%(name)s> with relative"
  73. " time found, but no relative unit set for %(sp)s "
  74. "maps") % {
  75. 'sp': sp.get_new_map_instance(None).get_type(),
  76. 'name': name})
  77. maplist = []
  78. # Map names as comma separated string
  79. if maps:
  80. if maps.find(",") < 0:
  81. maplist = [maps, ]
  82. else:
  83. maplist = maps.split(",")
  84. # Build the map list again with the ids
  85. for count in range(len(maplist)):
  86. row = {}
  87. mapid = AbstractMapDataset.build_id(maplist[count], mapset, None)
  88. row["id"] = mapid
  89. maplist[count] = row
  90. # Read the map list from file
  91. if file:
  92. fd = open(file, "r")
  93. line = True
  94. while True:
  95. line = fd.readline()
  96. if not line:
  97. break
  98. line_list = line.split(fs)
  99. # Detect start and end time
  100. if len(line_list) == 2:
  101. start_time_in_file = True
  102. end_time_in_file = False
  103. elif len(line_list) == 3:
  104. start_time_in_file = True
  105. end_time_in_file = True
  106. else:
  107. start_time_in_file = False
  108. end_time_in_file = False
  109. mapname = line_list[0].strip()
  110. row = {}
  111. if start_time_in_file and end_time_in_file:
  112. row["start"] = line_list[1].strip()
  113. row["end"] = line_list[2].strip()
  114. if start_time_in_file and not end_time_in_file:
  115. row["start"] = line_list[1].strip()
  116. row["id"] = AbstractMapDataset.build_id(mapname, mapset)
  117. maplist.append(row)
  118. num_maps = len(maplist)
  119. map_object_list = []
  120. statement = ""
  121. # Store the ids of datasets that must be updated
  122. datatsets_to_modify = {}
  123. core.message(_("Gathering map informations"))
  124. for count in range(len(maplist)):
  125. if count % 50 == 0:
  126. core.percent(count, num_maps, 1)
  127. # Get a new instance of the map type
  128. map = dataset_factory(type, maplist[count]["id"])
  129. # Use the time data from file
  130. if "start" in maplist[count]:
  131. start = maplist[count]["start"]
  132. if "end" in maplist[count]:
  133. end = maplist[count]["end"]
  134. is_in_db = False
  135. # Put the map into the database
  136. if not map.is_in_db(dbif):
  137. # Break in case no valid time is provided
  138. if (start == "" or start is None) and not map.has_grass_timestamp():
  139. dbif.close()
  140. if map.get_layer():
  141. core.fatal(_("Unable to register %(t)s map <%(id)s> with "
  142. "layer %(l)s. The map has timestamp and "
  143. "the start time is not set.") % {
  144. 't': map.get_type(), 'id': map.get_map_id(),
  145. 'l': map.get_layer()})
  146. else:
  147. core.fatal(_("Unable to register %(t)s map <%(id)s>. The"
  148. " map has no timestamp and the start time "
  149. "is not set.") % {'t': map.get_type(),
  150. 'id': map.get_map_id()})
  151. if start != "" and start != None:
  152. # We need to check if the time is absolute and the unit was specified
  153. time_object = check_datetime_string(start)
  154. if isinstance(time_object, datetime) and unit:
  155. core.fatal(_("%(u)s= can only be set for relative time") % {'u': "maps"})
  156. if not isinstance(time_object, datetime) and not unit:
  157. core.fatal(_("%(u)s= must be set in case of relative time stamps") % {'u': "maps"})
  158. if unit:
  159. map.set_time_to_relative()
  160. else:
  161. map.set_time_to_absolute()
  162. else:
  163. is_in_db = True
  164. # Check the overwrite flag
  165. if not core.overwrite():
  166. if map.get_layer():
  167. core.warning(_("Map is already registered in temporal "
  168. "database. Unable to update %(t)s map "
  169. "<%(id)s> with layer %(l)s. Overwrite flag"
  170. " is not set.") % {'t': map.get_type(),
  171. 'id': map.get_map_id(),
  172. 'l': str(map.get_layer())})
  173. else:
  174. core.warning(_("Map is already registered in temporal "
  175. "database. Unable to update %(t)s map "
  176. "<%(id)s>. Overwrite flag is not set.") % {
  177. 't': map.get_type(), 'id': map.get_map_id()})
  178. # Simple registration is allowed
  179. if name:
  180. map_object_list.append(map)
  181. # Jump to next map
  182. continue
  183. # Select information from temporal database
  184. map.select(dbif)
  185. # Save the datasets that must be updated
  186. datasets = map.get_registered_datasets(dbif)
  187. if datasets:
  188. for dataset in datasets:
  189. datatsets_to_modify[dataset["id"]] = dataset["id"]
  190. if name and map.get_temporal_type() != sp.get_temporal_type():
  191. dbif.close()
  192. if map.get_layer():
  193. core.fatal(_("Unable to update %(t)s map <%(id)s> "
  194. "with layer %(l)s. The temporal types "
  195. "are different.") % {'t': map.get_type(),
  196. 'id': map.get_map_id(),
  197. 'l': map.get_layer()})
  198. else:
  199. core.fatal(_("Unable to update %(t)s map <%(id)s>. "
  200. "The temporal types are different.") %
  201. {'t': map.get_type(),
  202. 'id': map.get_map_id()})
  203. # Load the data from the grass file database
  204. map.load()
  205. # Try to read an existing time stamp from the grass spatial database
  206. # in case this map wasn't already registered in the temporal database
  207. if not is_in_db:
  208. map.read_timestamp_from_grass()
  209. # Set the valid time
  210. if start:
  211. # In case the time is in the input file we ignore the increment
  212. # counter
  213. if start_time_in_file:
  214. count = 1
  215. assign_valid_time_to_map(ttype=map.get_temporal_type(),
  216. map=map, start=start, end=end, unit=unit,
  217. increment=increment, mult=count,
  218. interval=interval)
  219. if is_in_db:
  220. # Gather the SQL update statement
  221. statement += map.update_all(dbif=dbif, execute=False)
  222. else:
  223. # Gather the SQL insert statement
  224. statement += map.insert(dbif=dbif, execute=False)
  225. # Sqlite3 performace better for huge datasets when committing in
  226. # small chunks
  227. if dbif.dbmi.__name__ == "sqlite3":
  228. if count % 100 == 0:
  229. if statement is not None and statement != "":
  230. dbif.execute_transaction(statement)
  231. statement = ""
  232. # Store the maps in a list to register in a space time dataset
  233. if name:
  234. map_object_list.append(map)
  235. core.percent(num_maps, num_maps, 1)
  236. if statement is not None and statement != "":
  237. core.message(_("Register maps in the temporal database"))
  238. dbif.execute_transaction(statement)
  239. # Finally Register the maps in the space time dataset
  240. if name and map_object_list:
  241. count = 0
  242. num_maps = len(map_object_list)
  243. core.message(_("Register maps in the space time raster dataset"))
  244. for map in map_object_list:
  245. if count % 50 == 0:
  246. core.percent(count, num_maps, 1)
  247. sp.register_map(map=map, dbif=dbif)
  248. count += 1
  249. # Update the space time tables
  250. if name and map_object_list:
  251. core.message(_("Update space time raster dataset"))
  252. sp.update_from_registered_maps(dbif)
  253. sp.update_command_string(dbif=dbif)
  254. # Update affected datasets
  255. if datatsets_to_modify:
  256. for dataset in datatsets_to_modify:
  257. if type == "rast" or type == "raster":
  258. ds = dataset_factory("strds", dataset)
  259. elif type == "rast3d":
  260. ds = dataset_factory("str3ds", dataset)
  261. elif type == "vect" or type == "vector":
  262. ds = dataset_factory("stvds", dataset)
  263. ds.select(dbif)
  264. ds.update_from_registered_maps(dbif)
  265. if connected == True:
  266. dbif.close()
  267. core.percent(num_maps, num_maps, 1)
  268. ###############################################################################
  269. def assign_valid_time_to_map(ttype, map, start, end, unit, increment=None,
  270. mult=1, interval=False):
  271. """!Assign the valid time to a map dataset
  272. @param ttype The temporal type which should be assigned
  273. and which the time format is of
  274. @param map A map dataset object derived from abstract_map_dataset
  275. @param start The start date and time of the first raster map
  276. (format absolute: "yyyy-mm-dd HH:MM:SS" or "yyyy-mm-dd",
  277. format relative is integer 5)
  278. @param end The end date and time of the first raster map
  279. (format absolute: "yyyy-mm-dd HH:MM:SS" or "yyyy-mm-dd",
  280. format relative is integer 5)
  281. @param unit The unit of the relative time: years, months,
  282. days, hours, minutes, seconds
  283. @param increment Time increment between maps for time stamp creation
  284. (format absolute: NNN seconds, minutes, hours, days,
  285. weeks, months, years; format relative is integer 1)
  286. @param mult A multiplier for the increment
  287. @param interval If True, time intervals are created in case the start
  288. time and an increment is provided
  289. """
  290. if ttype == "absolute":
  291. start_time = string_to_datetime(start)
  292. if start_time is None:
  293. core.fatal(_("Unable to convert string \"%s\"into a "
  294. "datetime object") % (start))
  295. end_time = None
  296. if end:
  297. end_time = string_to_datetime(end)
  298. if end_time is None:
  299. dbif.close()
  300. core.fatal(_("Unable to convert string \"%s\"into a "
  301. "datetime object") % (end))
  302. # Add the increment
  303. if increment:
  304. start_time = increment_datetime_by_string(
  305. start_time, increment, mult)
  306. if start_time is None:
  307. core.fatal(_("Error in increment computation"))
  308. if interval:
  309. end_time = increment_datetime_by_string(
  310. start_time, increment, 1)
  311. if end_time is None:
  312. core.fatal(_("Error in increment computation"))
  313. # Commented because of performance issue calling g.message thousend times
  314. #if map.get_layer():
  315. # core.verbose(_("Set absolute valid time for map <%(id)s> with "
  316. # "layer %(layer)s to %(start)s - %(end)s") %
  317. # {'id': map.get_map_id(), 'layer': map.get_layer(),
  318. # 'start': str(start_time), 'end': str(end_time)})
  319. #else:
  320. # core.verbose(_("Set absolute valid time for map <%s> to %s - %s") %
  321. # (map.get_map_id(), str(start_time), str(end_time)))
  322. map.set_absolute_time(start_time, end_time, None)
  323. else:
  324. start_time = int(start)
  325. end_time = None
  326. if end:
  327. end_time = int(end)
  328. if increment:
  329. start_time = start_time + mult * int(increment)
  330. if interval:
  331. end_time = start_time + int(increment)
  332. # Commented because of performance issue calling g.message thousend times
  333. #if map.get_layer():
  334. # core.verbose(_("Set relative valid time for map <%s> with layer %s "
  335. # "to %i - %s with unit %s") %
  336. # (map.get_map_id(), map.get_layer(), start_time,
  337. # str(end_time), unit))
  338. #else:
  339. # core.verbose(_("Set relative valid time for map <%s> to %i - %s "
  340. # "with unit %s") % (map.get_map_id(), start_time,
  341. # str(end_time), unit))
  342. map.set_relative_time(start_time, end_time, unit)