register.py 21 KB

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