register.py 18 KB

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