register.py 20 KB

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