space_time_datasets_tools.py 23 KB

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