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