register.py 19 KB

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