register.py 21 KB

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