register.py 17 KB

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