register.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686
  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 (
  20. check_datetime_string,
  21. increment_datetime_by_string,
  22. string_to_datetime,
  23. )
  24. ###############################################################################
  25. def register_maps_in_space_time_dataset(
  26. type,
  27. name,
  28. maps=None,
  29. file=None,
  30. start=None,
  31. end=None,
  32. unit=None,
  33. increment=None,
  34. dbif=None,
  35. interval=False,
  36. fs="|",
  37. update_cmd_list=True,
  38. ):
  39. """Use this method to register maps in space time datasets.
  40. Additionally a start time string and an increment string can be
  41. specified to assign a time interval automatically to the maps.
  42. It takes care of the correct update of the space time datasets from all
  43. registered maps.
  44. :param type: The type of the maps raster, raster_3d or vector
  45. :param name: The name of the space time dataset. Maps will be
  46. registered in the temporal database if the name was set
  47. to None
  48. :param maps: A comma separated list of map names
  49. :param file: Input file, one map per line map with start and optional
  50. end time, or the same as io object (with readline capability)
  51. :param start: The start date and time of the first map
  52. (format absolute: "yyyy-mm-dd HH:MM:SS" or "yyyy-mm-dd",
  53. format relative is integer 5)
  54. :param end: The end date and time of the first map
  55. (format absolute: "yyyy-mm-dd HH:MM:SS" or "yyyy-mm-dd",
  56. format relative is integer 5)
  57. :param unit: The unit of the relative time: years, months, days,
  58. hours, minutes, seconds
  59. :param increment: Time increment between maps for time stamp creation
  60. (format absolute: NNN seconds, minutes, hours, days,
  61. weeks, months, years; format relative: 1.0)
  62. :param dbif: The database interface to be used
  63. :param interval: If True, time intervals are created in case the start
  64. time and an increment is provided
  65. :param fs: Field separator used in input file
  66. :param update_cmd_list: If is True, the command that was invoking this
  67. process will be written to the process history
  68. """
  69. start_time_in_file = False
  70. end_time_in_file = False
  71. semantic_label_in_file = False
  72. msgr = get_tgis_message_interface()
  73. msgr.debug(1, "register_maps_in_space_time_dataset()")
  74. # Make sure the arguments are of type string
  75. if start != "" and start is not None:
  76. start = str(start)
  77. if end != "" and end is not None:
  78. end = str(end)
  79. if increment != "" and increment is not None:
  80. increment = str(increment)
  81. if maps and file:
  82. msgr.fatal(_("%s= and %s= are mutually exclusive") % ("maps", "file"))
  83. if end and increment:
  84. msgr.fatal(_("%s= and %s= are mutually exclusive") % ("end", "increment"))
  85. if end and interval:
  86. msgr.fatal(
  87. _("%s= and the %s flag are mutually exclusive") % ("end", "interval")
  88. )
  89. if increment and not start:
  90. msgr.fatal(_("The increment option requires the start option"))
  91. if interval and not start:
  92. msgr.fatal(_("The interval flag requires the start option"))
  93. if end and not start:
  94. msgr.fatal(_("Please specify %s= and %s=") % ("start_time", "end_time"))
  95. if not maps and not file:
  96. msgr.fatal(_("Please specify %s= or %s=") % ("maps", "file"))
  97. # We may need the mapset
  98. mapset = get_current_mapset()
  99. dbif, connection_state_changed = init_dbif(None)
  100. # create new stds only in the current mapset
  101. # remove all connections to any other mapsets
  102. # ugly hack !
  103. currcon = {}
  104. currcon[mapset] = dbif.connections[mapset]
  105. dbif.connections = currcon
  106. # The name of the space time dataset is optional
  107. if name:
  108. sp = open_old_stds(name, type, dbif)
  109. if sp.is_time_relative() and (start or end) and not unit:
  110. dbif.close()
  111. msgr.fatal(
  112. _(
  113. "Space time %(sp)s dataset <%(name)s> with relative"
  114. " time found, but no relative unit set for %(sp)s "
  115. "maps"
  116. )
  117. % {"name": name, "sp": sp.get_new_map_instance(None).get_type()}
  118. )
  119. maplist = []
  120. # Map names as comma separated string
  121. if maps:
  122. if maps.find(",") < 0:
  123. maplist = [
  124. maps,
  125. ]
  126. else:
  127. maplist = maps.split(",")
  128. # Build the map list again with the ids
  129. for count in range(len(maplist)):
  130. row = {}
  131. mapname = maplist[count]
  132. map_mapset = mapset
  133. if "@" not in mapname:
  134. found = gscript.find_file(element=type, name=mapname)
  135. if found["mapset"] is not None and len(found["mapset"]) > 0:
  136. map_mapset = found["mapset"]
  137. mapid = AbstractMapDataset.build_id(mapname, map_mapset, None)
  138. row["id"] = mapid
  139. maplist[count] = row
  140. # Read the map list from file
  141. if file:
  142. if hasattr(file, "readline"):
  143. fd = file
  144. else:
  145. fd = open(file, "r")
  146. line = True
  147. while True:
  148. line = fd.readline().strip()
  149. if not line:
  150. break
  151. line_list = line.split(fs)
  152. # Detect start and end time (and semantic label)
  153. if len(line_list) == 2:
  154. start_time_in_file = True
  155. end_time_in_file = False
  156. semantic_label_in_file = False
  157. elif len(line_list) == 3:
  158. start_time_in_file = True
  159. # Check if last column is an end time or a semantic label
  160. time_object = check_datetime_string(line_list[2])
  161. if not sp.is_time_relative() and isinstance(time_object, datetime):
  162. end_time_in_file = True
  163. semantic_label_in_file = False
  164. else:
  165. end_time_in_file = False
  166. semantic_label_in_file = True
  167. elif len(line_list) == 4:
  168. start_time_in_file = True
  169. end_time_in_file = True
  170. semantic_label_in_file = True
  171. else:
  172. start_time_in_file = False
  173. end_time_in_file = False
  174. semantic_label_in_file = False
  175. mapname = line_list[0].strip()
  176. row = {}
  177. if start_time_in_file and end_time_in_file:
  178. row["start"] = line_list[1].strip()
  179. row["end"] = line_list[2].strip()
  180. if start_time_in_file and not end_time_in_file:
  181. row["start"] = line_list[1].strip()
  182. if semantic_label_in_file:
  183. idx = 3 if end_time_in_file else 2
  184. # case-sensitive, the user decides on the band name
  185. row["semantic_label"] = line_list[idx].strip()
  186. map_mapset = mapset
  187. if "@" not in mapname:
  188. found = gscript.find_file(element=type, name=mapname)
  189. if found["mapset"] is not None and len(found["mapset"]) > 0:
  190. map_mapset = found["mapset"]
  191. row["id"] = AbstractMapDataset.build_id(mapname, map_mapset)
  192. maplist.append(row)
  193. if start_time_in_file is True and increment:
  194. increment = None
  195. msgr.warning(
  196. _(
  197. "The increment option will be ignored because of time stamps in input file"
  198. )
  199. )
  200. if start_time_in_file is True and interval:
  201. increment = None
  202. msgr.warning(
  203. _(
  204. "The interval flag will be ignored because of time stamps in input file"
  205. )
  206. )
  207. fd.close()
  208. num_maps = len(maplist)
  209. map_object_list = []
  210. statement = ""
  211. # Store the ids of datasets that must be updated
  212. datatsets_to_modify = {}
  213. msgr.debug(2, "Gathering map information...")
  214. for count in range(len(maplist)):
  215. if count % 50 == 0:
  216. msgr.percent(count, num_maps, 1)
  217. # Get a new instance of the map type
  218. map = dataset_factory(type, maplist[count]["id"])
  219. if map.map_exists() is not True:
  220. msgr.fatal(
  221. _("Unable to update %(t)s map <%(id)s>. " "The map does not exist.")
  222. % {"t": map.get_type(), "id": map.get_map_id()}
  223. )
  224. # Use the time data from file
  225. if "start" in maplist[count]:
  226. start = maplist[count]["start"]
  227. if "end" in maplist[count]:
  228. end = maplist[count]["end"]
  229. # Use the semantic label from file
  230. if "semantic_label" in maplist[count]:
  231. semantic_label = maplist[count]["semantic_label"]
  232. else:
  233. semantic_label = None
  234. is_in_db = False
  235. # Put the map into the database of the current mapset
  236. if not map.is_in_db(dbif, mapset):
  237. # Break in case no valid time is provided
  238. if (start == "" or start is None) and not map.has_grass_timestamp():
  239. dbif.close()
  240. if map.get_layer():
  241. msgr.fatal(
  242. _(
  243. "Unable to register %(t)s map <%(id)s> with "
  244. "layer %(l)s. The map has timestamp and "
  245. "the start time is not set."
  246. )
  247. % {
  248. "t": map.get_type(),
  249. "id": map.get_map_id(),
  250. "l": map.get_layer(),
  251. }
  252. )
  253. else:
  254. msgr.fatal(
  255. _(
  256. "Unable to register %(t)s map <%(id)s>. The"
  257. " map has no timestamp and the start time "
  258. "is not set."
  259. )
  260. % {"t": map.get_type(), "id": map.get_map_id()}
  261. )
  262. if start != "" and start is not None:
  263. # We need to check if the time is absolute and the unit was specified
  264. time_object = check_datetime_string(start)
  265. if isinstance(time_object, datetime) and unit:
  266. msgr.fatal(
  267. _("%(u)s= can only be set for relative time") % {"u": "unit"}
  268. )
  269. if not isinstance(time_object, datetime) and not unit:
  270. msgr.fatal(
  271. _("%(u)s= must be set in case of relative time" " stamps")
  272. % {"u": "unit"}
  273. )
  274. if unit:
  275. map.set_time_to_relative()
  276. else:
  277. map.set_time_to_absolute()
  278. else:
  279. is_in_db = True
  280. # Check the overwrite flag
  281. if not gscript.overwrite():
  282. if map.get_layer():
  283. msgr.warning(
  284. _(
  285. "Map is already registered in temporal "
  286. "database. Unable to update %(t)s map "
  287. "<%(id)s> with layer %(l)s. Overwrite flag"
  288. " is not set."
  289. )
  290. % {
  291. "t": map.get_type(),
  292. "id": map.get_map_id(),
  293. "l": str(map.get_layer()),
  294. }
  295. )
  296. else:
  297. msgr.warning(
  298. _(
  299. "Map is already registered in temporal "
  300. "database. Unable to update %(t)s map "
  301. "<%(id)s>. Overwrite flag is not set."
  302. )
  303. % {"t": map.get_type(), "id": map.get_map_id()}
  304. )
  305. # Simple registration is allowed
  306. if name:
  307. map_object_list.append(map)
  308. # Jump to next map
  309. continue
  310. # Select information from temporal database
  311. map.select(dbif)
  312. # Save the datasets that must be updated
  313. datasets = map.get_registered_stds(dbif)
  314. if datasets is not None:
  315. for dataset in datasets:
  316. if dataset != "":
  317. datatsets_to_modify[dataset] = dataset
  318. if name and map.get_temporal_type() != sp.get_temporal_type():
  319. dbif.close()
  320. if map.get_layer():
  321. msgr.fatal(
  322. _(
  323. "Unable to update %(t)s map <%(id)s> "
  324. "with layer %(l)s. The temporal types "
  325. "are different."
  326. )
  327. % {
  328. "t": map.get_type(),
  329. "id": map.get_map_id(),
  330. "l": map.get_layer(),
  331. }
  332. )
  333. else:
  334. msgr.fatal(
  335. _(
  336. "Unable to update %(t)s map <%(id)s>. "
  337. "The temporal types are different."
  338. )
  339. % {"t": map.get_type(), "id": map.get_map_id()}
  340. )
  341. # Load the data from the grass file database
  342. map.load()
  343. # Try to read an existing time stamp from the grass spatial database
  344. # in case this map wasn't already registered in the temporal database
  345. # Read the spatial database time stamp only, if no time stamp was provided for this map
  346. # as method argument or in the input file
  347. if not is_in_db and not start:
  348. map.read_timestamp_from_grass()
  349. # Set the valid time
  350. if start:
  351. # In case the time is in the input file we ignore the increment
  352. # counter
  353. if start_time_in_file:
  354. count = 1
  355. assign_valid_time_to_map(
  356. ttype=map.get_temporal_type(),
  357. map=map,
  358. start=start,
  359. end=end,
  360. unit=unit,
  361. increment=increment,
  362. mult=count,
  363. interval=interval,
  364. )
  365. # Set the semantic label (only raster type supported)
  366. if semantic_label:
  367. # semantic label defined in input file
  368. # -> update raster metadata
  369. # -> write band identifier to GRASS data base
  370. map.set_semantic_label(semantic_label)
  371. else:
  372. # Try to read semantic label from GRASS data base if defined
  373. map.read_semantic_label_from_grass()
  374. if is_in_db:
  375. # Gather the SQL update statement
  376. statement += map.update_all(dbif=dbif, execute=False)
  377. else:
  378. # Gather the SQL insert statement
  379. statement += map.insert(dbif=dbif, execute=False)
  380. # Sqlite3 performance is better for huge datasets when committing in
  381. # small chunks
  382. if dbif.get_dbmi().__name__ == "sqlite3":
  383. if count % 100 == 0:
  384. if statement is not None and statement != "":
  385. dbif.execute_transaction(statement)
  386. statement = ""
  387. # Store the maps in a list to register in a space time dataset
  388. if name:
  389. map_object_list.append(map)
  390. msgr.percent(num_maps, num_maps, 1)
  391. if statement is not None and statement != "":
  392. dbif.execute_transaction(statement)
  393. # Finally Register the maps in the space time dataset
  394. if name and map_object_list:
  395. count = 0
  396. num_maps = len(map_object_list)
  397. for map in map_object_list:
  398. if count % 50 == 0:
  399. msgr.percent(count, num_maps, 1)
  400. sp.register_map(map=map, dbif=dbif)
  401. count += 1
  402. # Update the space time tables
  403. if name and map_object_list:
  404. sp.update_from_registered_maps(dbif)
  405. if update_cmd_list is True:
  406. sp.update_command_string(dbif=dbif)
  407. # Update affected datasets
  408. if datatsets_to_modify:
  409. for dataset in datatsets_to_modify:
  410. if type == "rast" or type == "raster":
  411. ds = dataset_factory("strds", dataset)
  412. elif type == "raster_3d" or type == "rast3d" or type == "raster3d":
  413. ds = dataset_factory("str3ds", dataset)
  414. elif type == "vect" or type == "vector":
  415. ds = dataset_factory("stvds", dataset)
  416. ds.select(dbif)
  417. ds.update_from_registered_maps(dbif)
  418. if connection_state_changed is True:
  419. dbif.close()
  420. msgr.percent(num_maps, num_maps, 1)
  421. ###############################################################################
  422. def assign_valid_time_to_map(
  423. ttype, map, start, end, unit, increment=None, mult=1, interval=False
  424. ):
  425. """Assign the valid time to a map dataset
  426. :param ttype: The temporal type which should be assigned
  427. and which the time format is of
  428. :param map: A map dataset object derived from abstract_map_dataset
  429. :param start: The start date and time of the first map
  430. (format absolute: "yyyy-mm-dd HH:MM:SS" or "yyyy-mm-dd",
  431. format relative is integer 5)
  432. :param end: The end date and time of the first map
  433. (format absolute: "yyyy-mm-dd HH:MM:SS" or "yyyy-mm-dd",
  434. format relative is integer 5)
  435. :param unit: The unit of the relative time: years, months,
  436. days, hours, minutes, seconds
  437. :param increment: Time increment between maps for time stamp creation
  438. (format absolute: NNN seconds, minutes, hours, days,
  439. weeks, months, years; format relative is integer 1)
  440. :param mult: A multiplier for the increment
  441. :param interval: If True, time intervals are created in case the start
  442. time and an increment is provided
  443. """
  444. msgr = get_tgis_message_interface()
  445. if ttype == "absolute":
  446. start_time = string_to_datetime(start)
  447. if start_time is None:
  448. msgr.fatal(
  449. _('Unable to convert string "%s"into a ' "datetime object") % (start)
  450. )
  451. end_time = None
  452. if end:
  453. end_time = string_to_datetime(end)
  454. if end_time is None:
  455. msgr.fatal(
  456. _('Unable to convert string "%s"into a ' "datetime object") % (end)
  457. )
  458. # Add the increment
  459. if increment:
  460. start_time = increment_datetime_by_string(start_time, increment, mult)
  461. if start_time is None:
  462. msgr.fatal(_("Error occurred in increment computation"))
  463. if interval:
  464. end_time = increment_datetime_by_string(start_time, increment, 1)
  465. if end_time is None:
  466. msgr.fatal(_("Error occurred in increment computation"))
  467. if map.get_layer():
  468. msgr.debug(
  469. 1,
  470. _(
  471. "Set absolute valid time for map <%(id)s> with "
  472. "layer %(layer)s to %(start)s - %(end)s"
  473. )
  474. % {
  475. "id": map.get_map_id(),
  476. "layer": map.get_layer(),
  477. "start": str(start_time),
  478. "end": str(end_time),
  479. },
  480. )
  481. else:
  482. msgr.debug(
  483. 1,
  484. _("Set absolute valid time for map <%s> to %s - %s")
  485. % (map.get_map_id(), str(start_time), str(end_time)),
  486. )
  487. map.set_absolute_time(start_time, end_time)
  488. else:
  489. start_time = int(start)
  490. end_time = None
  491. if end:
  492. end_time = int(end)
  493. if increment:
  494. start_time = start_time + mult * int(increment)
  495. if interval:
  496. end_time = start_time + int(increment)
  497. if map.get_layer():
  498. msgr.debug(
  499. 1,
  500. _(
  501. "Set relative valid time for map <%s> with layer"
  502. " %s to %i - %s with unit %s"
  503. )
  504. % (map.get_map_id(), map.get_layer(), start_time, str(end_time), unit),
  505. )
  506. else:
  507. msgr.debug(
  508. 1,
  509. _("Set relative valid time for map <%s> to %i - %s " "with unit %s")
  510. % (map.get_map_id(), start_time, str(end_time), unit),
  511. )
  512. map.set_relative_time(start_time, end_time, unit)
  513. ##############################################################################
  514. def register_map_object_list(
  515. type, map_list, output_stds, delete_empty=False, unit=None, dbif=None
  516. ):
  517. """Register a list of AbstractMapDataset objects in the temporal database
  518. and optional in a space time dataset.
  519. :param type: The type of the map layer (raster, raster_3d, vector)
  520. :param map_list: List of AbstractMapDataset objects
  521. :param output_stds: The output stds
  522. :param delete_empty: Set True to delete empty map layer found in the map_list
  523. :param unit: The temporal unit of the space time dataset
  524. :param dbif: The database interface to be used
  525. """
  526. import grass.pygrass.modules as pymod
  527. import copy
  528. dbif, connection_state_changed = init_dbif(dbif)
  529. filename = gscript.tempfile(True)
  530. file = open(filename, "w")
  531. empty_maps = []
  532. for map_layer in map_list:
  533. # Read the map data
  534. map_layer.load()
  535. # In case of a empty map continue, do not register empty maps
  536. if delete_empty:
  537. if type in ["raster", "raster_3d", "rast", "rast3d"]:
  538. if (
  539. map_layer.metadata.get_min() is None
  540. and map_layer.metadata.get_max() is None
  541. ):
  542. empty_maps.append(map_layer)
  543. continue
  544. if type == "vector":
  545. if map_layer.metadata.get_number_of_primitives() == 0:
  546. empty_maps.append(map_layer)
  547. continue
  548. start, end = map_layer.get_temporal_extent_as_tuple()
  549. id = map_layer.get_id()
  550. if not end:
  551. end = start
  552. string = "%s|%s|%s\n" % (id, str(start), str(end))
  553. file.write(string)
  554. file.close()
  555. if output_stds:
  556. output_stds_id = output_stds.get_id()
  557. else:
  558. output_stds_id = None
  559. register_maps_in_space_time_dataset(
  560. type, output_stds_id, unit=unit, file=filename, dbif=dbif
  561. )
  562. g_remove = pymod.Module("g.remove", flags="f", quiet=True, run_=False, finish_=True)
  563. # Remove empty maps and unregister them from the temporal database
  564. if len(empty_maps) > 0:
  565. for map in empty_maps:
  566. mod = copy.deepcopy(g_remove)
  567. if map.get_name():
  568. if map.get_type() == "raster":
  569. mod(type="raster", name=map.get_name())
  570. if map.get_type() == "raster3d":
  571. mod(type="raster_3d", name=map.get_name())
  572. if map.get_type() == "vector":
  573. mod(type="vector", name=map.get_name())
  574. mod.run()
  575. if map.is_in_db(dbif):
  576. map.delete(dbif)
  577. if connection_state_changed:
  578. dbif.close()
  579. if __name__ == "__main__":
  580. import doctest
  581. doctest.testmod()