register.py 16 KB

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