register.py 16 KB

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