register.py 22 KB

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