register.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  1. """
  2. Functions to register map layer in space time datasets and the temporal database
  3. Usage:
  4. .. code-block:: python
  5. import grass.temporal as tgis
  6. tgis.register_maps_in_space_time_dataset(type, name, maps)
  7. (C) 2012-2013 by the GRASS Development Team
  8. This program is free software under the GNU General Public
  9. License (>=v2). Read the file COPYING that comes with GRASS
  10. for details.
  11. :authors: Soeren Gebbert
  12. """
  13. from open_stds import *
  14. import grass.script as gscript
  15. ###############################################################################
  16. def register_maps_in_space_time_dataset(
  17. type, name, maps=None, file=None, start=None,
  18. end=None, unit=None, increment=None, dbif=None,
  19. interval=False, fs="|", update_cmd_list=True):
  20. """Use this method to register maps in space time datasets.
  21. Additionally a start time string and an increment string can be
  22. specified to assign a time interval automatically to the maps.
  23. It takes care of the correct update of the space time datasets from all
  24. registered maps.
  25. :param type: The type of the maps rast, rast3d or vect
  26. :param name: The name of the space time dataset. Maps will be
  27. registered in the temporal database if the name was set
  28. to None
  29. :param maps: A comma separated list of map names
  30. :param file: Input file, one map per line map with start and optional
  31. end time
  32. :param start: The start date and time of the first raster map
  33. (format absolute: "yyyy-mm-dd HH:MM:SS" or "yyyy-mm-dd",
  34. format relative is integer 5)
  35. :param end: The end date and time of the first raster map
  36. (format absolute: "yyyy-mm-dd HH:MM:SS" or "yyyy-mm-dd",
  37. format relative is integer 5)
  38. :param unit: The unit of the relative time: years, months, days,
  39. hours, minutes, seconds
  40. :param increment: Time increment between maps for time stamp creation
  41. (format absolute: NNN seconds, minutes, hours, days,
  42. weeks, months, years; format relative: 1.0)
  43. :param dbif: The database interface to be used
  44. :param interval: If True, time intervals are created in case the start
  45. time and an increment is provided
  46. :param fs: Field separator used in input file
  47. :param update_cmd_list: If is True, the command that was invoking this
  48. process will be written to the process history
  49. """
  50. start_time_in_file = False
  51. end_time_in_file = False
  52. msgr = get_tgis_message_interface()
  53. # Make sure the arguments are of type string
  54. if start != "" and start is not None:
  55. start = str(start)
  56. if end != "" and end is not None:
  57. end = str(end)
  58. if increment != "" and increment is not None:
  59. increment = str(increment)
  60. if maps and file:
  61. msgr.fatal(_("%s= and %s= are mutually exclusive") % ("maps", "file"))
  62. if end and increment:
  63. msgr.fatal(_("%s= and %s= are mutually exclusive") % ("end",
  64. "increment"))
  65. if end and not start:
  66. msgr.fatal(_("Please specify %s= and %s=") % ("start_time",
  67. "end_time"))
  68. if not maps and not file:
  69. msgr.fatal(_("Please specify %s= or %s=") % ("maps", "file"))
  70. # We may need the mapset
  71. mapset = get_current_mapset()
  72. dbif, connected = init_dbif(None)
  73. # The name of the space time dataset is optional
  74. if name:
  75. sp = open_old_stds(name, type, dbif)
  76. if sp.is_time_relative() and (start or end) and not unit:
  77. dbif.close()
  78. msgr.fatal(_("Space time %(sp)s dataset <%(name)s> with relative"
  79. " time found, but no relative unit set for %(sp)s "
  80. "maps") % {'name': name,
  81. 'sp': sp.get_new_map_instance(None).get_type()})
  82. maplist = []
  83. # Map names as comma separated string
  84. if maps:
  85. if maps.find(",") < 0:
  86. maplist = [maps, ]
  87. else:
  88. maplist = maps.split(",")
  89. # Build the map list again with the ids
  90. for count in range(len(maplist)):
  91. row = {}
  92. mapid = AbstractMapDataset.build_id(maplist[count], mapset, None)
  93. row["id"] = mapid
  94. maplist[count] = row
  95. # Read the map list from file
  96. if file:
  97. fd = open(file, "r")
  98. line = True
  99. while True:
  100. line = fd.readline()
  101. if not line:
  102. break
  103. line_list = line.split(fs)
  104. # Detect start and end time
  105. if len(line_list) == 2:
  106. start_time_in_file = True
  107. end_time_in_file = False
  108. elif len(line_list) == 3:
  109. start_time_in_file = True
  110. end_time_in_file = True
  111. else:
  112. start_time_in_file = False
  113. end_time_in_file = False
  114. mapname = line_list[0].strip()
  115. row = {}
  116. if start_time_in_file and end_time_in_file:
  117. row["start"] = line_list[1].strip()
  118. row["end"] = line_list[2].strip()
  119. if start_time_in_file and not end_time_in_file:
  120. row["start"] = line_list[1].strip()
  121. row["id"] = AbstractMapDataset.build_id(mapname, mapset)
  122. maplist.append(row)
  123. num_maps = len(maplist)
  124. map_object_list = []
  125. statement = ""
  126. # Store the ids of datasets that must be updated
  127. datatsets_to_modify = {}
  128. msgr.message(_("Gathering map information..."))
  129. for count in range(len(maplist)):
  130. if count % 50 == 0:
  131. msgr.percent(count, num_maps, 1)
  132. # Get a new instance of the map type
  133. map = dataset_factory(type, maplist[count]["id"])
  134. if map.map_exists() is not True:
  135. msgr.fatal(_("Unable to update %(t)s map <%(id)s>. "
  136. "The map does not exist.") % {'t': map.get_type(),
  137. 'id': map.get_map_id()})
  138. # Use the time data from file
  139. if "start" in maplist[count]:
  140. start = maplist[count]["start"]
  141. if "end" in maplist[count]:
  142. end = maplist[count]["end"]
  143. is_in_db = False
  144. # Put the map into the database
  145. if not map.is_in_db(dbif):
  146. # Break in case no valid time is provided
  147. if (start == "" or start is None) and not map.has_grass_timestamp():
  148. dbif.close()
  149. if map.get_layer():
  150. msgr.fatal(_("Unable to register %(t)s map <%(id)s> with "
  151. "layer %(l)s. The map has timestamp and "
  152. "the start time is not set.") % {
  153. 't': map.get_type(), 'id': map.get_map_id(),
  154. 'l': map.get_layer()})
  155. else:
  156. msgr.fatal(_("Unable to register %(t)s map <%(id)s>. The"
  157. " map has no timestamp and the start time "
  158. "is not set.") % {'t': map.get_type(),
  159. 'id': map.get_map_id()})
  160. if start != "" and start is not None:
  161. # We need to check if the time is absolute and the unit was specified
  162. time_object = check_datetime_string(start)
  163. if isinstance(time_object, datetime) and unit:
  164. msgr.fatal(_("%(u)s= can only be set for relative time") %
  165. {'u': "unit"})
  166. if not isinstance(time_object, datetime) and not unit:
  167. msgr.fatal(_("%(u)s= must be set in case of relative time"
  168. " stamps") % {'u': "unit"})
  169. if unit:
  170. map.set_time_to_relative()
  171. else:
  172. map.set_time_to_absolute()
  173. else:
  174. is_in_db = True
  175. # Check the overwrite flag
  176. if not gscript.overwrite():
  177. if map.get_layer():
  178. msgr.warning(_("Map is already registered in temporal "
  179. "database. Unable to update %(t)s map "
  180. "<%(id)s> with layer %(l)s. Overwrite flag"
  181. " is not set.") % {'t': map.get_type(),
  182. 'id': map.get_map_id(),
  183. 'l': str(map.get_layer())})
  184. else:
  185. msgr.warning(_("Map is already registered in temporal "
  186. "database. Unable to update %(t)s map "
  187. "<%(id)s>. Overwrite flag is not set.") %
  188. {'t': map.get_type(), 'id': map.get_map_id()})
  189. # Simple registration is allowed
  190. if name:
  191. map_object_list.append(map)
  192. # Jump to next map
  193. continue
  194. # Select information from temporal database
  195. map.select(dbif)
  196. # Save the datasets that must be updated
  197. datasets = map.get_registered_stds(dbif)
  198. if datasets is not None:
  199. for dataset in datasets:
  200. if dataset != "":
  201. datatsets_to_modify[dataset] = dataset
  202. if name and map.get_temporal_type() != sp.get_temporal_type():
  203. dbif.close()
  204. if map.get_layer():
  205. msgr.fatal(_("Unable to update %(t)s map <%(id)s> "
  206. "with layer %(l)s. The temporal types "
  207. "are different.") % {'t': map.get_type(),
  208. 'id': map.get_map_id(),
  209. 'l': map.get_layer()})
  210. else:
  211. msgr.fatal(_("Unable to update %(t)s map <%(id)s>. "
  212. "The temporal types are different.") %
  213. {'t': map.get_type(),
  214. 'id': map.get_map_id()})
  215. # Load the data from the grass file database
  216. map.load()
  217. # Try to read an existing time stamp from the grass spatial database
  218. # in case this map wasn't already registered in the temporal database
  219. if not is_in_db:
  220. map.read_timestamp_from_grass()
  221. # Set the valid time
  222. if start:
  223. # In case the time is in the input file we ignore the increment
  224. # counter
  225. if start_time_in_file:
  226. count = 1
  227. assign_valid_time_to_map(ttype=map.get_temporal_type(),
  228. map=map, start=start, end=end, unit=unit,
  229. increment=increment, mult=count,
  230. interval=interval)
  231. if is_in_db:
  232. # Gather the SQL update statement
  233. statement += map.update_all(dbif=dbif, execute=False)
  234. else:
  235. # Gather the SQL insert statement
  236. statement += map.insert(dbif=dbif, execute=False)
  237. # Sqlite3 performance is better for huge datasets when committing in
  238. # small chunks
  239. if dbif.get_dbmi().__name__ == "sqlite3":
  240. if count % 100 == 0:
  241. if statement is not None and statement != "":
  242. dbif.execute_transaction(statement)
  243. statement = ""
  244. # Store the maps in a list to register in a space time dataset
  245. if name:
  246. map_object_list.append(map)
  247. msgr.percent(num_maps, num_maps, 1)
  248. if statement is not None and statement != "":
  249. msgr.message(_("Registering maps in the temporal database..."))
  250. dbif.execute_transaction(statement)
  251. # Finally Register the maps in the space time dataset
  252. if name and map_object_list:
  253. count = 0
  254. num_maps = len(map_object_list)
  255. msgr.message(_("Registering maps in the space time raster dataset..."))
  256. for map in map_object_list:
  257. if count % 50 == 0:
  258. msgr.percent(count, num_maps, 1)
  259. sp.register_map(map=map, dbif=dbif)
  260. count += 1
  261. # Update the space time tables
  262. if name and map_object_list:
  263. msgr.message(_("Updating space time raster dataset..."))
  264. sp.update_from_registered_maps(dbif)
  265. if update_cmd_list is True:
  266. sp.update_command_string(dbif=dbif)
  267. # Update affected datasets
  268. if datatsets_to_modify:
  269. for dataset in datatsets_to_modify:
  270. if type == "rast" or type == "raster":
  271. ds = dataset_factory("strds", dataset)
  272. elif type == "rast3d":
  273. ds = dataset_factory("str3ds", dataset)
  274. elif type == "vect" or type == "vector":
  275. ds = dataset_factory("stvds", dataset)
  276. ds.select(dbif)
  277. ds.update_from_registered_maps(dbif)
  278. if connected is True:
  279. dbif.close()
  280. msgr.percent(num_maps, num_maps, 1)
  281. ###############################################################################
  282. def assign_valid_time_to_map(ttype, map, start, end, unit, increment=None,
  283. mult=1, interval=False):
  284. """Assign the valid time to a map dataset
  285. :param ttype: The temporal type which should be assigned
  286. and which the time format is of
  287. :param map: A map dataset object derived from abstract_map_dataset
  288. :param start: The start date and time of the first raster map
  289. (format absolute: "yyyy-mm-dd HH:MM:SS" or "yyyy-mm-dd",
  290. format relative is integer 5)
  291. :param end: The end 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 unit: The unit of the relative time: years, months,
  295. days, hours, minutes, seconds
  296. :param increment: Time increment between maps for time stamp creation
  297. (format absolute: NNN seconds, minutes, hours, days,
  298. weeks, months, years; format relative is integer 1)
  299. :param mult: A multiplier for the increment
  300. :param interval: If True, time intervals are created in case the start
  301. time and an increment is provided
  302. """
  303. msgr = get_tgis_message_interface()
  304. if ttype == "absolute":
  305. start_time = string_to_datetime(start)
  306. if start_time is None:
  307. msgr.fatal(_("Unable to convert string \"%s\"into a "
  308. "datetime object") % (start))
  309. end_time = None
  310. if end:
  311. end_time = string_to_datetime(end)
  312. if end_time is None:
  313. dbif.close()
  314. msgr.fatal(_("Unable to convert string \"%s\"into a "
  315. "datetime object") % (end))
  316. # Add the increment
  317. if increment:
  318. start_time = increment_datetime_by_string(
  319. start_time, increment, mult)
  320. if start_time is None:
  321. msgr.fatal(_("Error occurred in increment computation"))
  322. if interval:
  323. end_time = increment_datetime_by_string(
  324. start_time, increment, 1)
  325. if end_time is None:
  326. msgr.fatal(_("Error occurred in increment computation"))
  327. if map.get_layer():
  328. msgr.debug(1, _("Set absolute valid time for map <%(id)s> with "
  329. "layer %(layer)s to %(start)s - %(end)s") %
  330. {'id': map.get_map_id(), 'layer': map.get_layer(),
  331. 'start': str(start_time), 'end': str(end_time)})
  332. else:
  333. msgr.debug(1, _("Set absolute valid time for map <%s> to %s - %s")
  334. % (map.get_map_id(), str(start_time), str(end_time)))
  335. map.set_absolute_time(start_time, end_time)
  336. else:
  337. start_time = int(start)
  338. end_time = None
  339. if end:
  340. end_time = int(end)
  341. if increment:
  342. start_time = start_time + mult * int(increment)
  343. if interval:
  344. end_time = start_time + int(increment)
  345. if map.get_layer():
  346. msgr.debug(1, _("Set relative valid time for map <%s> with layer"
  347. " %s to %i - %s with unit %s") %
  348. (map.get_map_id(), map.get_layer(), start_time,
  349. str(end_time), unit))
  350. else:
  351. msgr.debug(1, _("Set relative valid time for map <%s> to %i - %s "
  352. "with unit %s") % (map.get_map_id(), start_time,
  353. str(end_time), unit))
  354. map.set_relative_time(start_time, end_time, unit)
  355. ##############################################################################
  356. def register_map_object_list(type, map_list, output_stds,
  357. delete_empty, unit, dbif=None):
  358. """Register a list of AbstractMapDataset objects in the temporal database
  359. and optional in a space time dataset.
  360. :param type: The type of the map layer (rast, rast3d, vect)
  361. :param map_list: List of AbstractMapDataset objects
  362. :param output_stds: The output stds
  363. :param delete_empty: Set True to delete empty map layer found in the map_list
  364. :param unit: The temporal unit of the space time dataset
  365. :param dbif: The database interface to be used
  366. """
  367. import grass.pygrass.modules as pymod
  368. import copy
  369. dbif, connected = init_dbif(dbif)
  370. filename = gscript.tempfile(True)
  371. file = open(filename, 'w')
  372. empty_maps = []
  373. for map_layer in map_list:
  374. # Read the raster map data
  375. map_layer.load()
  376. # In case of a empty map continue, do not register empty maps
  377. if delete_empty:
  378. if map_layer.metadata.get_min() is None and \
  379. map_layer.metadata.get_max() is None:
  380. empty_maps.append(map_layer)
  381. continue
  382. start, end = map_layer.get_temporal_extent_as_tuple()
  383. id = map_layer.get_id()
  384. if not end:
  385. end = start
  386. string = "%s|%s|%s\n" % (id, str(start), str(end))
  387. file.write(string)
  388. file.close()
  389. if output_stds:
  390. output_stds_id = output_stds.get_id()
  391. else:
  392. output_stds_id = None
  393. register_maps_in_space_time_dataset(type, output_stds_id, unit=unit,
  394. file=filename, dbif=dbif)
  395. g_remove = pymod.Module("g.remove", flags='f', quiet=True,
  396. run_=False, finish_=True)
  397. # Remove empty maps
  398. if len(empty_maps) > 0:
  399. for map in empty_maps:
  400. if map.is_in_db(dbif):
  401. map.delete(dbif)
  402. mod = copy.deepcopy(g_remove)
  403. mod(type='rast', pattern=map.get_name())
  404. mod.run()
  405. if connected:
  406. dbif.close()
  407. if __name__ == "__main__":
  408. import doctest
  409. doctest.testmod()