space_time_datasets_tools.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710
  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. # Store the ids of datasets that must be updated
  138. datatsets_to_modify = {}
  139. core.message(_("Gathering map informations"))
  140. for count in range(len(maplist)):
  141. core.percent(count, num_maps, 1)
  142. # Get a new instance of the map type
  143. map = dataset_factory(type, maplist[count]["id"])
  144. # Use the time data from file
  145. if "start" in maplist[count]:
  146. start = maplist[count]["start"]
  147. if "end" in maplist[count]:
  148. end = maplist[count]["end"]
  149. is_in_db = False
  150. # Put the map into the database
  151. if not map.is_in_db(dbif):
  152. is_in_db = False
  153. # Break in case no valid time is provided
  154. if start == "" or start is None:
  155. dbif.close()
  156. if map.get_layer():
  157. core.fatal(_("Unable to register %s map <%s> with layer %s. "
  158. "The map has no valid time and the start time is not set.") %
  159. (map.get_type(), map.get_map_id(), map.get_layer()))
  160. else:
  161. core.fatal(_("Unable to register %s map <%s>. The map has no valid"
  162. " time and the start time is not set.") %
  163. (map.get_type(), map.get_map_id()))
  164. if unit:
  165. map.set_time_to_relative()
  166. else:
  167. map.set_time_to_absolute()
  168. else:
  169. is_in_db = True
  170. if not core.overwrite:
  171. continue
  172. map.select(dbif)
  173. # Safe the datasets that must be updated
  174. datasets = map.get_registered_datasets(dbif)
  175. for dataset in datasets:
  176. datatsets_to_modify[dataset["id"]] = dataset["id"]
  177. if name and map.get_temporal_type() != sp.get_temporal_type():
  178. dbif.close()
  179. if map.get_layer():
  180. core.fatal(_("Unable to register %s map <%s> with layer. "
  181. "The temporal types are different.") %
  182. (map.get_type(), map.get_map_id(), map.get_layer()))
  183. else:
  184. core.fatal(_("Unable to register %s map <%s>. "
  185. "The temporal types are different.") %
  186. (map.get_type(), map.get_map_id()))
  187. # Load the data from the grass file database
  188. map.load()
  189. # Set the valid time
  190. if start:
  191. # In case the time is in the input file we ignore the increment counter
  192. if start_time_in_file:
  193. count = 1
  194. assign_valid_time_to_map(ttype=map.get_temporal_type(),
  195. map=map, start=start, end=end, unit=unit,
  196. increment=increment, mult=count,
  197. interval=interval)
  198. if is_in_db:
  199. # Gather the SQL update statement
  200. statement += map.update_all(dbif=dbif, execute=False)
  201. else:
  202. # Gather the SQL insert statement
  203. statement += map.insert(dbif=dbif, execute=False)
  204. # Sqlite3 performace better for huge datasets when committing in small chunks
  205. if dbmi.__name__ == "sqlite3":
  206. if count % 100 == 0:
  207. if statement is not None and statement != "":
  208. core.message(_("Registering maps in the temporal database")
  209. )
  210. dbif.execute_transaction(statement)
  211. statement = ""
  212. # Store the maps in a list to register in a space time dataset
  213. if name:
  214. map_object_list.append(map)
  215. core.percent(num_maps, num_maps, 1)
  216. if statement is not None and statement != "":
  217. core.message(_("Register maps in the temporal database"))
  218. dbif.execute_transaction(statement)
  219. # Finally Register the maps in the space time dataset
  220. if name:
  221. statement = ""
  222. count = 0
  223. num_maps = len(map_object_list)
  224. core.message(_("Register maps in the space time raster dataset"))
  225. for map in map_object_list:
  226. core.percent(count, num_maps, 1)
  227. sp.register_map(map=map, dbif=dbif)
  228. count += 1
  229. # Update the space time tables
  230. if name:
  231. core.message(_("Update space time raster dataset"))
  232. sp.update_from_registered_maps(dbif)
  233. # Update affected datasets
  234. if datatsets_to_modify:
  235. for dataset in datatsets_to_modify:
  236. if type == "rast" or type == "raster":
  237. ds = dataset_factory("strds", dataset)
  238. elif type == "rast3d":
  239. ds = dataset_factory("str3ds", dataset)
  240. elif type == "vect" or type == "vector":
  241. ds = dataset_factory("stvds", dataset)
  242. ds.select(dbif)
  243. ds.update_from_registered_maps(dbif)
  244. if connect == True:
  245. dbif.close()
  246. core.percent(num_maps, num_maps, 1)
  247. ###############################################################################
  248. def assign_valid_time_to_map(ttype, map, start, end, unit, increment=None, mult=1, interval=False):
  249. """!Assign the valid time to a map dataset
  250. @param ttype: The temporal type which should be assigned
  251. and which the time format is of
  252. @param map: A map dataset object derived from abstract_map_dataset
  253. @param start: The start date and time of the first raster map
  254. (format absolute: "yyyy-mm-dd HH:MM:SS" or "yyyy-mm-dd",
  255. format relative is integer 5)
  256. @param end: The end date and time of the first raster map
  257. (format absolute: "yyyy-mm-dd HH:MM:SS" or "yyyy-mm-dd",
  258. format relative is integer 5)
  259. @param unit: The unit of the relative time: years, months,
  260. days, hours, minutes, seconds
  261. @param increment: Time increment between maps for time stamp creation
  262. (format absolute: NNN seconds, minutes, hours, days,
  263. weeks, months, years; format relative is integer 1)
  264. @param multi: A multiplier for the increment
  265. @param interval: If True, time intervals are created in case the start
  266. time and an increment is provided
  267. """
  268. if ttype == "absolute":
  269. start_time = string_to_datetime(start)
  270. if start_time is None:
  271. dbif.close()
  272. core.fatal(_("Unable to convert string \"%s\"into a "
  273. "datetime object") % (start))
  274. end_time = None
  275. if end:
  276. end_time = string_to_datetime(end)
  277. if end_time is None:
  278. dbif.close()
  279. core.fatal(_("Unable to convert string \"%s\"into a "
  280. "datetime object") % (end))
  281. # Add the increment
  282. if increment:
  283. start_time = increment_datetime_by_string(
  284. start_time, increment, mult)
  285. if start_time is None:
  286. core.fatal(_("Error in increment computation"))
  287. if interval:
  288. end_time = increment_datetime_by_string(
  289. start_time, increment, 1)
  290. if end_time is None:
  291. core.fatal(_("Error in increment computation"))
  292. if map.get_layer():
  293. core.verbose(_("Set absolute valid time for map <%(id)s> with "
  294. "layer %(layer)s to %(start)s - %(end)s") %
  295. {'id': map.get_map_id(), 'layer': map.get_layer(),
  296. 'start': str(start_time), 'end': str(end_time)})
  297. else:
  298. core.verbose(_("Set absolute valid time for map <%s> to %s - %s") %
  299. (map.get_map_id(), str(start_time), str(end_time)))
  300. map.set_absolute_time(start_time, end_time, None)
  301. else:
  302. start_time = int(start)
  303. end_time = None
  304. if end:
  305. end_time = int(end)
  306. if increment:
  307. start_time = start_time + mult * int(increment)
  308. if interval:
  309. end_time = start_time + int(increment)
  310. if map.get_layer():
  311. core.verbose(_("Set relative valid time for map <%s> with layer %s "
  312. "to %i - %s with unit %s") %
  313. (map.get_map_id(), map.get_layer(), start_time,
  314. str(end_time), unit))
  315. else:
  316. core.verbose(_("Set relative valid time for map <%s> to %i - %s "
  317. "with unit %s") % (map.get_map_id(), start_time,
  318. str(end_time), unit))
  319. map.set_relative_time(start_time, end_time, unit)
  320. ###############################################################################
  321. def dataset_factory(type, id):
  322. """!A factory functions to create space time or map datasets
  323. @param type: the dataset type: rast or raster, rast3d,
  324. vect or vector, strds, str3ds, stvds
  325. @param id: The id of the dataset ("name@mapset")
  326. """
  327. if type == "strds":
  328. sp = SpaceTimeRasterDataset(id)
  329. elif type == "str3ds":
  330. sp = SpaceTimeRaster3DDataset(id)
  331. elif type == "stvds":
  332. sp = SpaceTimeVectorDataset(id)
  333. elif type == "rast" or type == "raster":
  334. sp = RasterDataset(id)
  335. elif type == "rast3d":
  336. sp = Raster3DDataset(id)
  337. elif type == "vect" or type == "vector":
  338. sp = VectorDataset(id)
  339. else:
  340. core.error(_("Unknown dataset type: %s") % type)
  341. return None
  342. return sp
  343. ###############################################################################
  344. def list_maps_of_stds(type, input, columns, order, where, separator, method, header):
  345. """! List the maps of a space time dataset using diffetent methods
  346. @param type: The type of the maps raster, raster3d or vector
  347. @param input: Name of a space time raster dataset
  348. @param columns: A comma separated list of columns to be printed to stdout
  349. @param order: A comma separated list of columns to order the
  350. space time dataset by category
  351. @param where: A where statement for selected listing without "WHERE"
  352. e.g: start_time < "2001-01-01" and end_time > "2001-01-01"
  353. @param separator: The field separator character between the columns
  354. @param method: String identifier to select a method out of cols,
  355. comma,delta or deltagaps
  356. - "cols": Print preselected columns specified by columns
  357. - "comma": Print the map ids (name@mapset) as comma separated string
  358. - "delta": Print the map ids (name@mapset) with start time,
  359. end time, relative length of intervals and the relative
  360. distance to the begin
  361. - "deltagaps": Same as "delta" with additional listing of gaps.
  362. Gaps can be simply identified as the id is "None"
  363. - "gran": List map using the granularity of the space time dataset,
  364. columns are identical to deltagaps
  365. @param header: Set True to print column names
  366. """
  367. mapset = core.gisenv()["MAPSET"]
  368. if input.find("@") >= 0:
  369. id = input
  370. else:
  371. id = input + "@" + mapset
  372. sp = dataset_factory(type, id)
  373. if not sp.is_in_db():
  374. core.fatal(_("Dataset <%s> not found in temporal database") % (id))
  375. sp.select()
  376. if separator is None or separator == "":
  377. separator = "\t"
  378. # This method expects a list of objects for gap detection
  379. if method == "delta" or method == "deltagaps" or method == "gran":
  380. if type == "stvds":
  381. columns = "id,name,layer,mapset,start_time,end_time"
  382. else:
  383. columns = "id,name,mapset,start_time,end_time"
  384. if method == "deltagaps":
  385. maps = sp.get_registered_maps_as_objects_with_gaps(where, None)
  386. elif method == "delta":
  387. maps = sp.get_registered_maps_as_objects(where, "start_time", None)
  388. elif method == "gran":
  389. maps = sp.get_registered_maps_as_objects_by_granularity(None)
  390. print "The maps object:", maps
  391. if header:
  392. string = ""
  393. string += "%s%s" % ("id", separator)
  394. string += "%s%s" % ("name", separator)
  395. if type == "stvds":
  396. string += "%s%s" % ("layer", separator)
  397. string += "%s%s" % ("mapset", separator)
  398. string += "%s%s" % ("start_time", separator)
  399. string += "%s%s" % ("end_time", separator)
  400. string += "%s%s" % ("interval_length", separator)
  401. string += "%s" % ("distance_from_begin")
  402. if maps and len(maps) > 0:
  403. if isinstance(maps[0], list):
  404. if len(maps[0]) > 0:
  405. first_time, dummy = maps[0][0].get_valid_time()
  406. else:
  407. core.warning(_("Empty map list."))
  408. return
  409. else:
  410. first_time, dummy = maps[0].get_valid_time()
  411. for mymap in maps:
  412. if isinstance(mymap, list):
  413. if len(mymap) > 0:
  414. map = mymap[0]
  415. else:
  416. core.error(_("Empty entry in map list, continue to next entry"))
  417. else:
  418. map = mymap
  419. start, end = map.get_valid_time()
  420. if end:
  421. delta = end - start
  422. else:
  423. delta = None
  424. delta_first = start - first_time
  425. if map.is_time_absolute():
  426. if end:
  427. delta = time_delta_to_relative_time(delta)
  428. delta_first = time_delta_to_relative_time(delta_first)
  429. string = ""
  430. string += "%s%s" % (map.get_id(), separator)
  431. string += "%s%s" % (map.get_name(), separator)
  432. if type == "stvds":
  433. string += "%s%s" % (map.get_layer(), separator)
  434. string += "%s%s" % (map.get_mapset(), separator)
  435. string += "%s%s" % (start, separator)
  436. string += "%s%s" % (end, separator)
  437. string += "%s%s" % (delta, separator)
  438. string += "%s" % (delta_first)
  439. print string
  440. else:
  441. # In comma separated mode only map ids are needed
  442. if method == "comma":
  443. columns = "id"
  444. rows = sp.get_registered_maps(columns, where, order, None)
  445. if rows:
  446. if method == "comma":
  447. string = ""
  448. count = 0
  449. for row in rows:
  450. if count == 0:
  451. string += row["id"]
  452. else:
  453. string += ",%s" % row["id"]
  454. count += 1
  455. print string
  456. elif method == "cols":
  457. # Print the column names if requested
  458. if header:
  459. output = ""
  460. count = 0
  461. collist = columns.split(",")
  462. for key in collist:
  463. if count > 0:
  464. output += separator + str(key)
  465. else:
  466. output += str(key)
  467. count += 1
  468. print output
  469. for row in rows:
  470. output = ""
  471. count = 0
  472. for col in row:
  473. if count > 0:
  474. output += separator + str(col)
  475. else:
  476. output += str(col)
  477. count += 1
  478. print output
  479. ###############################################################################
  480. def sample_stds_by_stds_topology(intype, sampletype, inputs, sampler, header, separator, method, spatial=False):
  481. """!Sample the input space time datasets with a sample
  482. space time dataset and print the result to stdout
  483. In case multiple maps are located in the current granule,
  484. the map names are separated by comma.
  485. In case a layer is present, the names map ids are extended
  486. in this form: name:layer@mapset
  487. Attention: Do not use the comma as separator
  488. @param intype: Type of the input space time dataset (strds, stvds or str3ds)
  489. @param samtype: Type of the sample space time dataset (strds, stvds or str3ds)
  490. @param input: Name of a space time dataset
  491. @param sampler: Name of a space time dataset used for temporal sampling
  492. @param header: Set True to print column names
  493. @param separator: The field separator character between the columns
  494. @param method: The method to be used for temporal sampling
  495. (start,during,contain,overlap,equal)
  496. @param spatial: Perform spatial overlapping check
  497. """
  498. mapset = core.gisenv()["MAPSET"]
  499. input_list = inputs.split(",")
  500. sts = []
  501. for input in input_list:
  502. if input.find("@") >= 0:
  503. id = input
  504. else:
  505. id = input + "@" + mapset
  506. st = dataset_factory(intype, id)
  507. sts.append(st)
  508. if sampler.find("@") >= 0:
  509. sid = sampler
  510. else:
  511. sid = sampler + "@" + mapset
  512. sst = dataset_factory(sampletype, sid)
  513. dbif = SQLDatabaseInterfaceConnection()
  514. dbif.connect()
  515. for st in sts:
  516. if st.is_in_db(dbif) == False:
  517. core.fatal(_("Dataset <%s> not found in temporal database") % (id))
  518. st.select(dbif)
  519. if sst.is_in_db(dbif) == False:
  520. core.fatal(_("Dataset <%s> not found in temporal database") % (sid))
  521. sst.select(dbif)
  522. if separator is None or separator == "" or separator.find(",") >= 0:
  523. separator = " | "
  524. mapmatrizes = []
  525. for st in sts:
  526. mapmatrix = st.sample_by_dataset(sst, method, spatial, dbif)
  527. if mapmatrix and len(mapmatrix) > 0:
  528. mapmatrizes.append(mapmatrix)
  529. if len(mapmatrizes) > 0:
  530. if header:
  531. string = ""
  532. string += "%s%s" % (sst.get_id(), separator)
  533. for st in sts:
  534. string += "%s%s" % (st.get_id(), separator)
  535. string += "%s%s" % ("start_time", separator)
  536. string += "%s%s" % ("end_time", separator)
  537. string += "%s%s" % ("interval_length", separator)
  538. string += "%s" % ("distance_from_begin")
  539. first_time, dummy = mapmatrizes[0][0]["granule"].get_valid_time()
  540. for i in range(len(mapmatrizes[0])):
  541. mapname_list = []
  542. for mapmatrix in mapmatrizes:
  543. mapnames = ""
  544. count = 0
  545. entry = mapmatrix[i]
  546. for sample in entry["samples"]:
  547. if count == 0:
  548. mapnames += str(sample.get_id())
  549. else:
  550. mapnames += ",%s" % str(sample.get_id())
  551. count += 1
  552. mapname_list.append(mapnames)
  553. entry = mapmatrizes[0][i]
  554. map = entry["granule"]
  555. start, end = map.get_valid_time()
  556. if end:
  557. delta = end - start
  558. else:
  559. delta = None
  560. delta_first = start - first_time
  561. if map.is_time_absolute():
  562. if end:
  563. delta = time_delta_to_relative_time(delta)
  564. delta_first = time_delta_to_relative_time(delta_first)
  565. string = ""
  566. string += "%s%s" % (map.get_id(), separator)
  567. for mapnames in mapname_list:
  568. string += "%s%s" % (mapnames, separator)
  569. string += "%s%s" % (start, separator)
  570. string += "%s%s" % (end, separator)
  571. string += "%s%s" % (delta, separator)
  572. string += "%s" % (delta_first)
  573. print string
  574. dbif.close()