register.py 16 KB

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