space_time_datasets_tools.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681
  1. """!@package grass.temporal
  2. @brief GRASS Python scripting module (temporal GIS functions)
  3. Temporal GIS related functions to be used in Python scripts.
  4. Usage:
  5. @code
  6. import grass.temporal as tgis
  7. tgis.register_maps_in_space_time_dataset(type, name, maps)
  8. ...
  9. @endcode
  10. (C) 2008-2011 by the GRASS Development Team
  11. This program is free software under the GNU General Public
  12. License (>=v2). Read the file COPYING that comes with GRASS
  13. for details.
  14. @author Soeren Gebbert
  15. """
  16. from space_time_datasets import *
  17. ###############################################################################
  18. def register_maps_in_space_time_dataset(
  19. type, name, maps=None, file=None, start=None,
  20. end=None, unit=None, increment=None, dbif=None,
  21. interval=False, fs="|"):
  22. """!Use this method to register maps in space time datasets.
  23. Additionally a start time string and an increment string can be specified
  24. to assign a time interval automatically to the maps.
  25. It takes care of the correct update of the space time datasets from all
  26. registered maps.
  27. @param type: The type of the maps rast, rast3d or vect
  28. @param name: The name of the space time dataset
  29. @param maps: A comma separated list of map names
  30. @param file: Input file one map with start and optional end time,
  31. one per line
  32. @param start: The start date and time of the first raster 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 raster 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. """
  48. start_time_in_file = False
  49. end_time_in_file = False
  50. if maps and file:
  51. core.fatal(_("%s= and %s= are mutually exclusive") % ("input", "file"))
  52. if end and increment:
  53. core.fatal(_("%s= and %s= are mutually exclusive") % (
  54. "end", "increment"))
  55. if end and not start:
  56. core.fatal(_("Please specify %s= and %s=") % ("start_time",
  57. "end_time"))
  58. if not maps and not file:
  59. core.fatal(_("Please specify %s= or %s=") % ("input", "file"))
  60. # We may need the mapset
  61. mapset = core.gisenv()["MAPSET"]
  62. # The name of the space time dataset is optional
  63. if name:
  64. # Check if the dataset name contains the mapset as well
  65. if name.find("@") < 0:
  66. id = name + "@" + mapset
  67. else:
  68. id = name
  69. if type == "rast" or type == "raster":
  70. sp = dataset_factory("strds", id)
  71. elif type == "rast3d":
  72. sp = dataset_factory("str3ds", id)
  73. elif type == "vect" or type == "vector":
  74. sp = dataset_factory("stvds", id)
  75. else:
  76. core.fatal(_("Unkown map type: %s") % (type))
  77. dbif, connect = init_dbif(None)
  78. if name:
  79. # Read content from temporal database
  80. sp.select(dbif)
  81. if not sp.is_in_db(dbif):
  82. dbif.close()
  83. core.fatal(_("Space time %s dataset <%s> no found") %
  84. (sp.get_new_map_instance(None).get_type(), name))
  85. if sp.is_time_relative() and not unit:
  86. dbif.close()
  87. core.fatal(_("Space time %s dataset <%s> with relative time found, "
  88. "but no relative unit set for %s maps") %
  89. (sp.get_new_map_instance(None).get_type(),
  90. name, sp.get_new_map_instance(None).get_type()))
  91. # We need a dummy map object to build the map ids
  92. dummy = dataset_factory(type, None)
  93. maplist = []
  94. # Map names as comma separated string
  95. if maps:
  96. if maps.find(",") < 0:
  97. maplist = [maps, ]
  98. else:
  99. maplist = maps.split(",")
  100. # Build the map list again with the ids
  101. for count in range(len(maplist)):
  102. row = {}
  103. mapid = dummy.build_id(maplist[count], mapset, None)
  104. row["id"] = mapid
  105. maplist[count] = row
  106. # Read the map list from file
  107. if file:
  108. fd = open(file, "r")
  109. line = True
  110. while True:
  111. line = fd.readline()
  112. if not line:
  113. break
  114. line_list = line.split(fs)
  115. # Detect start and end time
  116. if len(line_list) == 2:
  117. start_time_in_file = True
  118. end_time_in_file = False
  119. elif len(line_list) == 3:
  120. start_time_in_file = True
  121. end_time_in_file = True
  122. else:
  123. start_time_in_file = False
  124. end_time_in_file = False
  125. mapname = line_list[0].strip()
  126. row = {}
  127. if start_time_in_file and end_time_in_file:
  128. row["start"] = line_list[1].strip()
  129. row["end"] = line_list[2].strip()
  130. if start_time_in_file and not end_time_in_file:
  131. row["start"] = line_list[1].strip()
  132. row["id"] = dummy.build_id(mapname, mapset)
  133. maplist.append(row)
  134. num_maps = len(maplist)
  135. map_object_list = []
  136. statement = ""
  137. core.message(_("Gathering map informations"))
  138. for count in range(len(maplist)):
  139. core.percent(count, num_maps, 1)
  140. # Get a new instance of the map type
  141. map = dataset_factory(type, maplist[count]["id"])
  142. # Use the time data from file
  143. if "start" in maplist[count]:
  144. start = maplist[count]["start"]
  145. if "end" in maplist[count]:
  146. end = maplist[count]["end"]
  147. is_in_db = False
  148. # Put the map into the database
  149. if not map.is_in_db(dbif):
  150. is_in_db = False
  151. # Break in case no valid time is provided
  152. if start == "" or start is None:
  153. dbif.close()
  154. if map.get_layer():
  155. core.fatal(_("Unable to register %s map <%s> with layer %s. "
  156. "The map has no valid time and the start time is not set.") %
  157. (map.get_type(), map.get_map_id(), map.get_layer()))
  158. else:
  159. core.fatal(_("Unable to register %s map <%s>. The map has no valid"
  160. " time and the start time is not set.") %
  161. (map.get_type(), map.get_map_id()))
  162. if unit:
  163. map.set_time_to_relative()
  164. else:
  165. map.set_time_to_absolute()
  166. else:
  167. is_in_db = True
  168. if not core.overwrite:
  169. continue
  170. map.select(dbif)
  171. if name and map.get_temporal_type() != sp.get_temporal_type():
  172. dbif.close()
  173. if map.get_layer():
  174. core.fatal(_("Unable to register %s map <%s> with layer. "
  175. "The temporal types are different.") %
  176. (map.get_type(), map.get_map_id(), map.get_layer()))
  177. else:
  178. core.fatal(_("Unable to register %s map <%s>. "
  179. "The temporal types are different.") %
  180. (map.get_type(), map.get_map_id()))
  181. # Load the data from the grass file database
  182. map.load()
  183. # Set the valid time
  184. if start:
  185. # In case the time is in the input file we ignore the increment counter
  186. if start_time_in_file:
  187. count = 1
  188. assign_valid_time_to_map(ttype=map.get_temporal_type(),
  189. map=map, start=start, end=end, unit=unit,
  190. increment=increment, mult=count,
  191. interval=interval)
  192. if is_in_db:
  193. # Gather the SQL update statement
  194. statement += map.update_all(dbif=dbif, execute=False)
  195. else:
  196. # Gather the SQL insert statement
  197. statement += map.insert(dbif=dbif, execute=False)
  198. # Sqlite3 performace better for huge datasets when committing in small chunks
  199. if dbmi.__name__ == "sqlite3":
  200. if count % 100 == 0:
  201. if statement is not None and statement != "":
  202. core.message(_("Registering maps in the temporal database")
  203. )
  204. dbif.execute_transaction(statement)
  205. statement = ""
  206. # Store the maps in a list to register in a space time dataset
  207. if name:
  208. map_object_list.append(map)
  209. core.percent(num_maps, num_maps, 1)
  210. if statement is not None and statement != "":
  211. core.message(_("Register maps in the temporal database"))
  212. dbif.execute_transaction(statement)
  213. # Finally Register the maps in the space time dataset
  214. if name:
  215. statement = ""
  216. count = 0
  217. num_maps = len(map_object_list)
  218. core.message(_("Register maps in the space time raster dataset"))
  219. for map in map_object_list:
  220. core.percent(count, num_maps, 1)
  221. sp.register_map(map=map, dbif=dbif)
  222. count += 1
  223. # Update the space time tables
  224. if name:
  225. core.message(_("Update space time raster dataset"))
  226. sp.update_from_registered_maps(dbif)
  227. if connect == True:
  228. dbif.close()
  229. core.percent(num_maps, num_maps, 1)
  230. ###############################################################################
  231. def assign_valid_time_to_map(ttype, map, start, end, unit, increment=None, mult=1, interval=False):
  232. """!Assign the valid time to a map dataset
  233. @param ttype: The temporal type which should be assigned
  234. and which the time format is of
  235. @param map: A map dataset object derived from abstract_map_dataset
  236. @param start: The start date and time of the first raster map
  237. (format absolute: "yyyy-mm-dd HH:MM:SS" or "yyyy-mm-dd",
  238. format relative is integer 5)
  239. @param end: The end date and time of the first raster map
  240. (format absolute: "yyyy-mm-dd HH:MM:SS" or "yyyy-mm-dd",
  241. format relative is integer 5)
  242. @param unit: The unit of the relative time: years, months,
  243. days, hours, minutes, seconds
  244. @param increment: Time increment between maps for time stamp creation
  245. (format absolute: NNN seconds, minutes, hours, days,
  246. weeks, months, years; format relative is integer 1)
  247. @param multi: A multiplier for the increment
  248. @param interval: If True, time intervals are created in case the start
  249. time and an increment is provided
  250. """
  251. if ttype == "absolute":
  252. start_time = string_to_datetime(start)
  253. if start_time is None:
  254. dbif.close()
  255. core.fatal(_("Unable to convert string \"%s\"into a "
  256. "datetime object") % (start))
  257. end_time = None
  258. if end:
  259. end_time = string_to_datetime(end)
  260. if end_time is None:
  261. dbif.close()
  262. core.fatal(_("Unable to convert string \"%s\"into a "
  263. "datetime object") % (end))
  264. # Add the increment
  265. if increment:
  266. start_time = increment_datetime_by_string(
  267. start_time, increment, mult)
  268. if start_time is None:
  269. core.fatal(_("Error in increment computation"))
  270. if interval:
  271. end_time = increment_datetime_by_string(
  272. start_time, increment, 1)
  273. if end_time is None:
  274. core.fatal(_("Error in increment computation"))
  275. if map.get_layer():
  276. core.verbose(_("Set absolute valid time for map <%(id)s> with "
  277. "layer %(layer)s to %(start)s - %(end)s") %
  278. {'id': map.get_map_id(), 'layer': map.get_layer(),
  279. 'start': str(start_time), 'end': str(end_time)})
  280. else:
  281. core.verbose(_("Set absolute valid time for map <%s> to %s - %s") %
  282. (map.get_map_id(), str(start_time), str(end_time)))
  283. map.set_absolute_time(start_time, end_time, None)
  284. else:
  285. start_time = int(start)
  286. end_time = None
  287. if end:
  288. end_time = int(end)
  289. if increment:
  290. start_time = start_time + mult * int(increment)
  291. if interval:
  292. end_time = start_time + int(increment)
  293. if map.get_layer():
  294. core.verbose(_("Set relative valid time for map <%s> with layer %s "
  295. "to %i - %s with unit %s") %
  296. (map.get_map_id(), map.get_layer(), start_time,
  297. str(end_time), unit))
  298. else:
  299. core.verbose(_("Set relative valid time for map <%s> to %i - %s "
  300. "with unit %s") % (map.get_map_id(), start_time,
  301. str(end_time), unit))
  302. map.set_relative_time(start_time, end_time, unit)
  303. ###############################################################################
  304. def dataset_factory(type, id):
  305. """!A factory functions to create space time or map datasets
  306. @param type: the dataset type: rast or raster, rast3d,
  307. vect or vector, strds, str3ds, stvds
  308. @param id: The id of the dataset ("name@mapset")
  309. """
  310. if type == "strds":
  311. sp = space_time_raster_dataset(id)
  312. elif type == "str3ds":
  313. sp = space_time_raster3d_dataset(id)
  314. elif type == "stvds":
  315. sp = space_time_vector_dataset(id)
  316. elif type == "rast" or type == "raster":
  317. sp = raster_dataset(id)
  318. elif type == "rast3d":
  319. sp = raster3d_dataset(id)
  320. elif type == "vect" or type == "vector":
  321. sp = vector_dataset(id)
  322. else:
  323. core.error(_("Unknown dataset type: %s") % type)
  324. return None
  325. return sp
  326. ###############################################################################
  327. def list_maps_of_stds(type, input, columns, order, where, separator, method, header):
  328. """! List the maps of a space time dataset using diffetent methods
  329. @param type: The type of the maps raster, raster3d or vector
  330. @param input: Name of a space time raster dataset
  331. @param columns: A comma separated list of columns to be printed to stdout
  332. @param order: A comma separated list of columns to order the
  333. space time dataset by category
  334. @param where: A where statement for selected listing without "WHERE"
  335. e.g: start_time < "2001-01-01" and end_time > "2001-01-01"
  336. @param separator: The field separator character between the columns
  337. @param method: String identifier to select a method out of cols,
  338. comma,delta or deltagaps
  339. * "cols": Print preselected columns specified by columns
  340. * "comma": Print the map ids (name@mapset) as comma separated string
  341. * "delta": Print the map ids (name@mapset) with start time,
  342. end time, relative length of intervals and the relative
  343. distance to the begin
  344. * "deltagaps": Same as "delta" with additional listing of gaps.
  345. Gaps can be simply identified as the id is "None"
  346. * "gran": List map using the granularity of the space time dataset,
  347. columns are identical to deltagaps
  348. @param header: Set True to print column names
  349. """
  350. mapset = core.gisenv()["MAPSET"]
  351. if input.find("@") >= 0:
  352. id = input
  353. else:
  354. id = input + "@" + mapset
  355. sp = dataset_factory(type, id)
  356. if not sp.is_in_db():
  357. core.fatal(_("Dataset <%s> not found in temporal database") % (id))
  358. sp.select()
  359. if separator is None or separator == "":
  360. separator = "\t"
  361. # This method expects a list of objects for gap detection
  362. if method == "delta" or method == "deltagaps" or method == "gran":
  363. if type == "stvds":
  364. columns = "id,name,layer,mapset,start_time,end_time"
  365. else:
  366. columns = "id,name,mapset,start_time,end_time"
  367. if method == "deltagaps":
  368. maps = sp.get_registered_maps_as_objects_with_gaps(where, None)
  369. elif method == "delta":
  370. maps = sp.get_registered_maps_as_objects(where, "start_time", None)
  371. elif method == "gran":
  372. maps = sp.get_registered_maps_as_objects_by_granularity(None)
  373. if header:
  374. string = ""
  375. string += "%s%s" % ("id", separator)
  376. string += "%s%s" % ("name", separator)
  377. if type == "stvds":
  378. string += "%s%s" % ("layer", separator)
  379. string += "%s%s" % ("mapset", separator)
  380. string += "%s%s" % ("start_time", separator)
  381. string += "%s%s" % ("end_time", separator)
  382. string += "%s%s" % ("interval_length", separator)
  383. string += "%s" % ("distance_from_begin")
  384. if maps and len(maps) > 0:
  385. if isinstance(maps[0], list):
  386. first_time, dummy = maps[0][0].get_valid_time()
  387. else:
  388. first_time, dummy = maps[0].get_valid_time()
  389. for mymap in maps:
  390. if isinstance(mymap, list):
  391. map = mymap[0]
  392. else:
  393. map = mymap
  394. start, end = map.get_valid_time()
  395. if end:
  396. delta = end - start
  397. else:
  398. delta = None
  399. delta_first = start - first_time
  400. if map.is_time_absolute():
  401. if end:
  402. delta = time_delta_to_relative_time(delta)
  403. delta_first = time_delta_to_relative_time(delta_first)
  404. string = ""
  405. string += "%s%s" % (map.get_id(), separator)
  406. string += "%s%s" % (map.get_name(), separator)
  407. if type == "stvds":
  408. string += "%s%s" % (map.get_layer(), separator)
  409. string += "%s%s" % (map.get_mapset(), separator)
  410. string += "%s%s" % (start, separator)
  411. string += "%s%s" % (end, separator)
  412. string += "%s%s" % (delta, separator)
  413. string += "%s" % (delta_first)
  414. print string
  415. else:
  416. # In comma separated mode only map ids are needed
  417. if method == "comma":
  418. columns = "id"
  419. rows = sp.get_registered_maps(columns, where, order, None)
  420. if rows:
  421. if method == "comma":
  422. string = ""
  423. count = 0
  424. for row in rows:
  425. if count == 0:
  426. string += row["id"]
  427. else:
  428. string += ",%s" % row["id"]
  429. count += 1
  430. print string
  431. elif method == "cols":
  432. # Print the column names if requested
  433. if header:
  434. output = ""
  435. count = 0
  436. collist = columns.split(",")
  437. for key in collist:
  438. if count > 0:
  439. output += separator + str(key)
  440. else:
  441. output += str(key)
  442. count += 1
  443. print output
  444. for row in rows:
  445. output = ""
  446. count = 0
  447. for col in row:
  448. if count > 0:
  449. output += separator + str(col)
  450. else:
  451. output += str(col)
  452. count += 1
  453. print output
  454. ###############################################################################
  455. def sample_stds_by_stds_topology(intype, sampletype, inputs, sampler, header, separator, method, spatial=False):
  456. """!Sample the input space time datasets with a sample
  457. space time dataset and print the result to stdout
  458. In case multiple maps are located in the current granule,
  459. the map names are separated by comma.
  460. In case a layer is present, the names map ids are extended
  461. in this form: name:layer@mapset
  462. Attention: Do not use the comma as separator
  463. @param intype: Type of the input space time dataset (strds, stvds or str3ds)
  464. @param samtype: Type of the sample space time dataset (strds, stvds or str3ds)
  465. @param input: Name of a space time dataset
  466. @param sampler: Name of a space time dataset used for temporal sampling
  467. @param header: Set True to print column names
  468. @param separator: The field separator character between the columns
  469. @param method: The method to be used for temporal sampling
  470. (start,during,contain,overlap,equal)
  471. @param spatial: Perform spatial overlapping check
  472. """
  473. mapset = core.gisenv()["MAPSET"]
  474. input_list = inputs.split(",")
  475. sts = []
  476. for input in input_list:
  477. if input.find("@") >= 0:
  478. id = input
  479. else:
  480. id = input + "@" + mapset
  481. st = dataset_factory(intype, id)
  482. sts.append(st)
  483. if sampler.find("@") >= 0:
  484. sid = sampler
  485. else:
  486. sid = sampler + "@" + mapset
  487. sst = dataset_factory(sampletype, sid)
  488. dbif = ()
  489. dbif.connect()
  490. for st in sts:
  491. if st.is_in_db(dbif) == False:
  492. core.fatal(_("Dataset <%s> not found in temporal database") % (id))
  493. st.select(dbif)
  494. if sst.is_in_db(dbif) == False:
  495. core.fatal(_("Dataset <%s> not found in temporal database") % (sid))
  496. sst.select(dbif)
  497. if separator is None or separator == "" or separator.find(",") >= 0:
  498. separator = " | "
  499. mapmatrizes = []
  500. for st in sts:
  501. mapmatrix = st.sample_by_dataset(sst, method, spatial, dbif)
  502. if mapmatrix and len(mapmatrix) > 0:
  503. mapmatrizes.append(mapmatrix)
  504. if len(mapmatrizes) > 0:
  505. if header:
  506. string = ""
  507. string += "%s%s" % (sst.get_id(), separator)
  508. for st in sts:
  509. string += "%s%s" % (st.get_id(), separator)
  510. string += "%s%s" % ("start_time", separator)
  511. string += "%s%s" % ("end_time", separator)
  512. string += "%s%s" % ("interval_length", separator)
  513. string += "%s" % ("distance_from_begin")
  514. first_time, dummy = mapmatrizes[0][0]["granule"].get_valid_time()
  515. for i in range(len(mapmatrizes[0])):
  516. mapname_list = []
  517. for mapmatrix in mapmatrizes:
  518. mapnames = ""
  519. count = 0
  520. entry = mapmatrix[i]
  521. for sample in entry["samples"]:
  522. if count == 0:
  523. mapnames += str(sample.get_id())
  524. else:
  525. mapnames += ",%s" % str(sample.get_id())
  526. count += 1
  527. mapname_list.append(mapnames)
  528. entry = mapmatrizes[0][i]
  529. map = entry["granule"]
  530. start, end = map.get_valid_time()
  531. if end:
  532. delta = end - start
  533. else:
  534. delta = None
  535. delta_first = start - first_time
  536. if map.is_time_absolute():
  537. if end:
  538. delta = time_delta_to_relative_time(delta)
  539. delta_first = time_delta_to_relative_time(delta_first)
  540. string = ""
  541. string += "%s%s" % (map.get_id(), separator)
  542. for mapnames in mapname_list:
  543. string += "%s%s" % (mapnames, separator)
  544. string += "%s%s" % (start, separator)
  545. string += "%s%s" % (end, separator)
  546. string += "%s%s" % (delta, separator)
  547. string += "%s" % (delta_first)
  548. print string
  549. dbif.close()