space_time_datasets_tools.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869
  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, layer=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 raster, raster3d or vector
  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 optional start and 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. layer_in_file = False
  41. if maps and file:
  42. core.fatal(_("%s= and %s= are mutually exclusive") % ("input","file"))
  43. if end and increment:
  44. core.fatal(_("%s= and %s= are mutually exclusive") % ("end","increment"))
  45. if end and not start:
  46. core.fatal(_("Please specify %s= and %s=") % ("start_time","end_time"))
  47. if not maps and not file:
  48. core.fatal(_("Please specify %s= or %s=") % ("input","file"))
  49. if layer and layer == "file":
  50. layer_in_file = True
  51. if start and start == "file":
  52. start_time_in_file = True
  53. if end and end == "file":
  54. end_time_in_file = True
  55. # We may need the mapset
  56. mapset = core.gisenv()["MAPSET"]
  57. # Check if the dataset name contains the mapset as well
  58. if name.find("@") < 0:
  59. id = name + "@" + mapset
  60. else:
  61. id = name
  62. sp = dataset_factory(type, id)
  63. connect = False
  64. if dbif == None:
  65. dbif = sql_database_interface()
  66. dbif.connect()
  67. connect = True
  68. # Read content from temporal database
  69. sp.select(dbif)
  70. if sp.is_in_db(dbif) == False:
  71. dbif.close()
  72. core.fatal(_("Space time %s dataset <%s> no found") % (sp.get_new_map_instance(None).get_type(), name))
  73. dummy = sp.get_new_map_instance(None)
  74. maplist = []
  75. layerlist = []
  76. # Map names as comma separated string
  77. if maps:
  78. if maps.find(",") < 0:
  79. maplist = [maps,]
  80. else:
  81. maplist = maps.split(",")
  82. # Layer as comma separated string
  83. if layer:
  84. if layer.find(",") < 0:
  85. layerlist = (layer,)
  86. else:
  87. layerlist = layer.split(",")
  88. if len(maplist) != len(layerlist):
  89. core.fatal(_("Number of %s= and %s= must be equal") % ("maps","layer"))
  90. # Build the maplist again with the ids
  91. for count in range(len(maplist)):
  92. row = {}
  93. if layer:
  94. mapid = dummy.build_id(maplist[count], mapset, layerlist[count])
  95. else:
  96. mapid = dummy.build_id(maplist[count], mapset, None)
  97. row["id"] = mapid
  98. maplist[count] = row
  99. # Read the map list from file
  100. if file:
  101. fd = open(file, "r")
  102. line = True
  103. while True:
  104. line = fd.readline()
  105. if not line:
  106. break
  107. line_list = line.split(fs)
  108. mapname = line_list[0].strip()
  109. row = {}
  110. if layer_in_file:
  111. row["layer"] = line_list[1].strip()
  112. if start_time_in_file and end_time_in_file:
  113. row["start"] = line_list[2].strip()
  114. row["end"] = line_list[3].strip()
  115. if start_time_in_file and not end_time_in_file:
  116. row["start"] = line_list[2].strip()
  117. row["id"] = dummy.build_id(mapname, mapset, row["layer"])
  118. else:
  119. if start_time_in_file and end_time_in_file:
  120. row["start"] = line_list[1].strip()
  121. row["end"] = line_list[2].strip()
  122. if start_time_in_file and not end_time_in_file:
  123. row["start"] = line_list[1].strip()
  124. row["id"] = dummy.build_id(mapname, mapset)
  125. maplist.append(row)
  126. num_maps = len(maplist)
  127. for count in range(len(maplist)):
  128. core.percent(count, num_maps, 1)
  129. # Get a new instance of the space time dataset map type
  130. map = sp.get_new_map_instance(maplist[count]["id"])
  131. # Use the time data from file
  132. if start_time_in_file:
  133. start = maplist[count]["start"]
  134. if end_time_in_file:
  135. end = maplist[count]["end"]
  136. # Put the map into the database
  137. if map.is_in_db(dbif) == False:
  138. # Break in case no valid time is provided
  139. if start == "" or start == None:
  140. dbif.close()
  141. if map.get_layer():
  142. core.fatal(_("Unable to register %s map <%s> with layer %s. The map has no valid time and the start time is not set.") % \
  143. (map.get_type(), map.get_map_id(), map.get_layer() ))
  144. else:
  145. core.fatal(_("Unable to register %s map <%s>. The map has no valid time and the start time is not set.") % \
  146. (map.get_type(), map.get_map_id() ))
  147. # Load the data from the grass file database
  148. map.load()
  149. if sp.get_temporal_type() == "absolute":
  150. map.set_time_to_absolute()
  151. else:
  152. map.set_time_to_relative()
  153. # Put it into the temporal database
  154. map.insert(dbif)
  155. else:
  156. map.select(dbif)
  157. if map.get_temporal_type() != sp.get_temporal_type():
  158. dbif.close()
  159. if map.get_layer():
  160. core.fatal(_("Unable to register %s map <%s> with layer. The temporal types are different.") % \
  161. (map.get_type(), map.get_map_id(), map.get_layer()))
  162. core.fatal(_("Unable to register %s map <%s>. The temporal types are different.") % \
  163. (map.get_type(), map.get_map_id()))
  164. # In case the time is in the input file we ignore the increment counter
  165. if start_time_in_file:
  166. count = 1
  167. # Set the valid time
  168. if start:
  169. assign_valid_time_to_map(ttype=sp.get_temporal_type(), map=map, start=start, end=end, unit=unit, increment=increment, mult=count, dbif=dbif, interval=interval)
  170. # Finally Register map in the space time dataset
  171. sp.register_map(map, dbif)
  172. # Update the space time tables
  173. sp.update_from_registered_maps(dbif)
  174. if connect == True:
  175. dbif.close()
  176. core.percent(num_maps, num_maps, 1)
  177. ###############################################################################
  178. def unregister_maps_from_space_time_datasets(type, name, maps, layer=None, file=None, dbif=None):
  179. """Unregister maps from a single space time dataset or, in case no dataset name is provided,
  180. unregister from all datasets within the maps are registered.
  181. @param type: The type of the maps raster, vector or raster3d
  182. @param name: Name of an existing space time raster dataset. If no name is provided the raster map(s) are unregistered from all space time datasets in which they are registered.
  183. @param maps: A comma separated list of map names
  184. @param dbif: The database interface to be used
  185. """
  186. if maps and file:
  187. core.fatal(_("%s= and %s= are mutually exclusive") % ("input","file"))
  188. mapset = core.gisenv()["MAPSET"]
  189. if dbif == None:
  190. dbif = sql_database_interface()
  191. dbif.connect()
  192. connect = True
  193. layer_in_file = False
  194. if layer and layer == "file":
  195. layer_in_file = True
  196. # In case a space time dataset is specified
  197. if name:
  198. # Check if the dataset name contains the mapset as well
  199. if name.find("@") < 0:
  200. id = name + "@" + mapset
  201. else:
  202. id = name
  203. if type == "rast":
  204. sp = dataset_factory("strds", id)
  205. if type == "rast3d":
  206. sp = dataset_factory("str3ds", id)
  207. if type == "vect":
  208. sp = dataset_factory("stvds", id)
  209. if sp.is_in_db(dbif) == False:
  210. dbif.close()
  211. core.fatal("Space time " + sp.get_new_map_instance(None).get_type() + " dataset <" + name + "> not found")
  212. maplist = []
  213. layerlist = []
  214. dummy = raster_dataset(None)
  215. # Map names as comma separated string
  216. if maps != None:
  217. if maps.find(",") == -1:
  218. maplist = [maps,]
  219. else:
  220. maplist = maps.split(",")
  221. if layer:
  222. if layer.find(",") < 0:
  223. layerlist = (layer,)
  224. else:
  225. layerlist = layer.split(",")
  226. if len(maplist) != len(layerlist):
  227. core.fatal(_("Number of %s= and %s= must be equal") % ("maps","layer"))
  228. # Build the maplist
  229. for count in range(len(maplist)):
  230. mapname = maplist[count]
  231. if layer:
  232. mylayer = layerlist[count]
  233. mapid = dummy.build_id(mapname, mapset, mylayer)
  234. else:
  235. mapid = dummy.build_id(mapname, mapset)
  236. maplist[count] = mapid
  237. # Read the map list from file
  238. if file:
  239. fd = open(file, "r")
  240. line = True
  241. while True:
  242. line = fd.readline()
  243. if not line:
  244. break
  245. line_list = line.split(fs)
  246. mapname = line_list[0].strip()
  247. if layer_in_file:
  248. mylayer = line_list[1].strip()
  249. mapid = dummy.build_id(mapname, mapset, mylayer)
  250. else:
  251. mapid = dummy.build_id(mapname, mapset)
  252. maplist.append(mapid)
  253. num_maps = len(maplist)
  254. count = 0
  255. for mapid in maplist:
  256. core.percent(count, num_maps, 1)
  257. print mapid
  258. map = dataset_factory(type, mapid)
  259. # Unregister map if in database
  260. if map.is_in_db(dbif) == True:
  261. if name:
  262. sp.select(dbif)
  263. sp.unregister_map(map, dbif)
  264. else:
  265. map.select(dbif)
  266. map.unregister(dbif)
  267. count += 1
  268. if name:
  269. sp.update_from_registered_maps(dbif)
  270. if connect == True:
  271. dbif.close()
  272. core.percent(num_maps, num_maps, 1)
  273. ###############################################################################
  274. def assign_valid_time_to_maps(type, maps, ttype, start, end=None, unit=None, file=file, increment=None, dbif = None, interval=False, fs="|"):
  275. """Use this method to assign valid time (absolute or relative) to raster,
  276. raster3d and vector datasets.
  277. It takes care of the correct update of the space time datasets from all
  278. registered maps.
  279. Valid end time and increment are mutual exclusive.
  280. @param type: The type of the maps raster, raster3d or vector
  281. @param maps: A comma separated list of map names
  282. @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)
  283. @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)
  284. @param unit: The unit of the relative time: years, months, days, hours, minutes, seconds
  285. @param increment: Time increment between maps for time stamp creation (format absolute: NNN seconds, minutes, hours, days, weeks, months, years; format relative: 1.0)
  286. @param file: Input file one map with optional start and end time, one per line
  287. @param dbif: The database interface to be used
  288. @param interval: If True, time intervals are created in case the start time and an increment is provided
  289. @param fs: Field separator used in input file
  290. """
  291. start_time_in_file = False
  292. end_time_in_file = False
  293. if end and increment:
  294. if dbif:
  295. dbif.close()
  296. core.fatal(_("Valid end time and increment are mutual exclusive"))
  297. # List of space time datasets to be updated
  298. splist = {}
  299. if maps and file:
  300. core.fatal(_("%s= and %s= are mutually exclusive") % ("input","file"))
  301. if end and increment:
  302. core.fatal(_("%s= and %s= are mutually exclusive") % ("end","increment"))
  303. if end and not start:
  304. core.fatal(_("Please specify %s= and %s=") % ("start_time","end_time"))
  305. if not maps and not file:
  306. core.fatal(_("Please specify %s= or %s=") % ("input","file"))
  307. if start and start == "file":
  308. start_time_in_file = True
  309. if end and end == "file":
  310. end_time_in_file = True
  311. # We may need the mapset
  312. mapset = core.gisenv()["MAPSET"]
  313. connect = False
  314. if dbif == None:
  315. dbif = sql_database_interface()
  316. dbif.connect()
  317. connect = True
  318. maplist = []
  319. # Map names as comma separated string
  320. if maps:
  321. if maps.find(",") == -1:
  322. maplist = (maps,)
  323. else:
  324. maplist = tuple(maps.split(","))
  325. # Read the map list from file
  326. if file:
  327. fd = open(file, "r")
  328. line = True
  329. while True:
  330. line = fd.readline()
  331. if not line:
  332. break
  333. line_list = line.split(fs)
  334. mapname = line_list[0].strip()
  335. if mapname.find("@") < 0:
  336. mapid = mapname + "@" + mapset
  337. else:
  338. mapid = mapname
  339. row = {}
  340. row["id"] = mapid
  341. if start_time_in_file and end_time_in_file:
  342. row["start"] = line_list[1].strip()
  343. row["end"] = line_list[2].strip()
  344. if start_time_in_file and not end_time_in_file:
  345. row["start"] = line_list[1].strip()
  346. maplist.append(row)
  347. num_maps = len(maplist)
  348. count = 0
  349. for entry in maplist:
  350. core.percent(count, num_maps, 1)
  351. if file:
  352. mapid = entry["id"]
  353. else:
  354. if entry.find("@") < 0:
  355. mapid = entry + "@" + mapset
  356. else:
  357. mapid = entry
  358. map = dataset_factory(type, mapid)
  359. # Use the time data from file
  360. if start_time_in_file:
  361. start = entry["start"]
  362. if end_time_in_file:
  363. end = entry["end"]
  364. if map.is_in_db(dbif) == False:
  365. # Load the data from the grass file database
  366. map.load()
  367. if ttype == "absolute":
  368. map.set_time_to_absolute()
  369. else:
  370. map.set_time_to_relative()
  371. # Put it into the temporal database
  372. map.insert(dbif)
  373. else:
  374. map.select(dbif)
  375. sprows = map.get_registered_datasets(dbif)
  376. # Make an entry in the dataset list, using a dict make sure that
  377. # each dataset is listed only once
  378. if sprows != None:
  379. for dataset in sprows:
  380. splist[dataset["id"]] = True
  381. # In case the time is in the input file we ignore the increment counter
  382. if start_time_in_file:
  383. count = 1
  384. # Set the valid time
  385. assign_valid_time_to_map(ttype=ttype, map=map, start=start, end=end, unit=unit, increment=increment, mult=count, dbif=dbif, interval=interval)
  386. count += 1
  387. # Update all the space time datasets in which registered maps are changed there valid time
  388. for name in splist.keys():
  389. sp = map.get_new_stds_instance(name)
  390. sp.select(dbif)
  391. sp.update_from_registered_maps(dbif)
  392. if connect == True:
  393. dbif.close()
  394. core.percent(num_maps, num_maps, 1)
  395. ###############################################################################
  396. def assign_valid_time_to_map(ttype, map, start, end, unit, increment=None, mult=1, dbif = None, interval=False):
  397. """Assign the valid time to a map dataset
  398. @param ttype: The temporal type which should be assigned and which the time format is of
  399. @param map: A map dataset object derived from abstract_map_dataset
  400. @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)
  401. @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)
  402. @param unit: The unit of the relative time: years, months, days, hours, minutes, seconds
  403. @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)
  404. @param multi: A multiplier for the increment
  405. @param dbif: The database interface to use for sql queries
  406. @param interval: If True, time intervals are created in case the start time and an increment is provided
  407. """
  408. connect = False
  409. if dbif == None:
  410. dbif = sql_database_interface()
  411. dbif.connect()
  412. connect = True
  413. if ttype == "absolute":
  414. start_time = string_to_datetime(start)
  415. if start_time == None:
  416. dbif.close()
  417. core.fatal(_("Unable to convert string \"%s\"into a datetime object")%(start))
  418. end_time = None
  419. if end:
  420. end_time = string_to_datetime(end)
  421. if end_time == None:
  422. dbif.close()
  423. core.fatal(_("Unable to convert string \"%s\"into a datetime object")%(end))
  424. # Add the increment
  425. if increment:
  426. start_time = increment_datetime_by_string(start_time, increment, mult)
  427. if interval:
  428. end_time = increment_datetime_by_string(start_time, increment, 1)
  429. if map.get_layer():
  430. 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)))
  431. else:
  432. core.verbose(_("Set absolute valid time for map <%s> to %s - %s") % (map.get_map_id(), str(start_time), str(end_time)))
  433. map.update_absolute_time(start_time, end_time, None, dbif)
  434. else:
  435. start_time = int(start)
  436. end_time = None
  437. if end:
  438. end_time = int(end)
  439. if increment:
  440. start_time = start_time + mult * int(increment)
  441. if interval:
  442. end_time = start_time + int(increment)
  443. if map.get_layer():
  444. 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))
  445. else:
  446. 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))
  447. map.update_relative_time(start_time, end_time, unit, dbif)
  448. if connect == True:
  449. dbif.close()
  450. ###############################################################################
  451. def dataset_factory(type, id):
  452. """A factory functions to create space time or map datasets
  453. @param type: the dataset type: rast, rast3d, vect, strds, str3ds, stvds
  454. @param id: The id of the dataset ("name@mapset")
  455. """
  456. if type == "strds":
  457. sp = space_time_raster_dataset(id)
  458. elif type == "str3ds":
  459. sp = space_time_raster3d_dataset(id)
  460. elif type == "stvds":
  461. sp = space_time_vector_dataset(id)
  462. elif type == "rast":
  463. sp = raster_dataset(id)
  464. elif type == "rast3d":
  465. sp = raster3d_dataset(id)
  466. elif type == "vect":
  467. sp = vector_dataset(id)
  468. else:
  469. core.error(_("Unknown dataset type: %s") % type)
  470. return None
  471. return sp
  472. ###############################################################################
  473. def list_maps_of_stds(type, input, columns, order, where, separator, method, header):
  474. """ List the maps of a space time dataset using diffetent methods
  475. @param type: The type of the maps raster, raster3d or vector
  476. @param input: Name of a space time raster dataset
  477. @param columns: A comma separated list of columns to be printed to stdout
  478. @param order: A comma separated list of columns to order the space time dataset by category
  479. @param where: A where statement for selected listing without "WHERE" e.g: start_time < "2001-01-01" and end_time > "2001-01-01"
  480. @param separator: The field separator character between the columns
  481. @param method: String identifier to select a method out of cols,comma,delta or deltagaps
  482. * "cols": Print preselected columns specified by columns
  483. * "comma": Print the map ids (name@mapset) as comma separated string
  484. * "delta": Print the map ids (name@mapset) with start time, end time, relative length of intervals and the relative distance to the begin
  485. * "deltagaps": Same as "delta" with additional listing of gaps. Gaps can be simply identified as the id is "None"
  486. * "gran": List map using the granularity of the space time dataset, columns are identical to deltagaps
  487. @param header: Set True to print column names
  488. """
  489. mapset = core.gisenv()["MAPSET"]
  490. if input.find("@") >= 0:
  491. id = input
  492. else:
  493. id = input + "@" + mapset
  494. sp = dataset_factory(type, id)
  495. if sp.is_in_db() == False:
  496. core.fatal(_("Dataset <%s> not found in temporal database") % (id))
  497. sp.select()
  498. if separator == None or separator == "":
  499. separator = "\t"
  500. # This method expects a list of objects for gap detection
  501. if method == "delta" or method == "deltagaps" or method == "gran":
  502. if type == "stvds":
  503. columns = "id,name,layer,mapset,start_time,end_time"
  504. else:
  505. columns = "id,name,mapset,start_time,end_time"
  506. if method == "deltagaps":
  507. maps = sp.get_registered_maps_as_objects_with_gaps(where, None)
  508. elif method == "delta":
  509. maps = sp.get_registered_maps_as_objects(where, "start_time", None)
  510. elif method == "gran":
  511. maps = sp.get_registered_maps_as_objects_by_granularity(None)
  512. if header:
  513. string = ""
  514. string += "%s%s" % ("id", separator)
  515. string += "%s%s" % ("name", separator)
  516. if type == "stvds":
  517. string += "%s%s" % ("layer", separator)
  518. string += "%s%s" % ("mapset", separator)
  519. string += "%s%s" % ("start_time", separator)
  520. string += "%s%s" % ("end_time", separator)
  521. string += "%s%s" % ("interval_length", separator)
  522. string += "%s" % ("distance_from_begin")
  523. print string
  524. if maps and len(maps) > 0:
  525. if isinstance(maps[0], list):
  526. first_time, dummy = maps[0][0].get_valid_time()
  527. else:
  528. first_time, dummy = maps[0].get_valid_time()
  529. for mymap in maps:
  530. if isinstance(mymap, list):
  531. map = mymap[0]
  532. else:
  533. map = mymap
  534. start, end = map.get_valid_time()
  535. if end:
  536. delta = end -start
  537. else:
  538. delta = None
  539. delta_first = start - first_time
  540. if map.is_time_absolute():
  541. if end:
  542. delta = time_delta_to_relative_time(delta)
  543. delta_first = time_delta_to_relative_time(delta_first)
  544. string = ""
  545. string += "%s%s" % (map.get_id(), separator)
  546. string += "%s%s" % (map.get_name(), separator)
  547. if type == "stvds":
  548. string += "%s%s" % (map.get_layer(), separator)
  549. string += "%s%s" % (map.get_mapset(), separator)
  550. string += "%s%s" % (start, separator)
  551. string += "%s%s" % (end, separator)
  552. string += "%s%s" % (delta, separator)
  553. string += "%s" % (delta_first)
  554. print string
  555. else:
  556. # In comma separated mode only map ids are needed
  557. if method == "comma":
  558. columns = "id"
  559. rows = sp.get_registered_maps(columns, where, order, None)
  560. if rows:
  561. if method == "comma":
  562. string = ""
  563. count = 0
  564. for row in rows:
  565. if count == 0:
  566. string += row["id"]
  567. else:
  568. string += ",%s" % row["id"]
  569. count += 1
  570. print string
  571. elif method == "cols":
  572. # Print the column names if requested
  573. if header:
  574. output = ""
  575. count = 0
  576. collist = columns.split(",")
  577. for key in collist:
  578. if count > 0:
  579. output += separator + str(key)
  580. else:
  581. output += str(key)
  582. count += 1
  583. print output
  584. for row in rows:
  585. output = ""
  586. count = 0
  587. for col in row:
  588. if count > 0:
  589. output += separator + str(col)
  590. else:
  591. output += str(col)
  592. count += 1
  593. print output
  594. ###############################################################################
  595. def sample_stds_by_stds_topology(intype, sampletype, input, sampler, header, separator, method):
  596. """ Sample the input space time dataset with a sample space time dataset and print the result to stdout
  597. In case multiple maps are located in the current granule, the map names are separated by comma.
  598. In case a layer is present, the names map ids are extended in this form: name:layer@mapset
  599. Attention: Do not use the comma as separator
  600. @param intype: Type of the input space time dataset (strds, stvds or str3ds)
  601. @param samtype: Type of the sample space time dataset (strds, stvds or str3ds)
  602. @param input: Name of a space time dataset
  603. @param sampler: Name of a space time dataset used for temporal sampling
  604. @param header: Set True to print column names
  605. @param separator: The field separator character between the columns
  606. @param method: The method to be used for sampling (start,during,contain,overlap,equal)
  607. """
  608. mapset = core.gisenv()["MAPSET"]
  609. if input.find("@") >= 0:
  610. id = input
  611. else:
  612. id = input + "@" + mapset
  613. sp = dataset_factory(intype, id)
  614. if sampler.find("@") >= 0:
  615. sid = sampler
  616. else:
  617. sid = sampler + "@" + mapset
  618. ssp = dataset_factory(sampletype, sid)
  619. dbif = sql_database_interface()
  620. dbif.connect()
  621. if sp.is_in_db(dbif) == False:
  622. core.fatal(_("Dataset <%s> not found in temporal database") % (id))
  623. if ssp.is_in_db(dbif) == False:
  624. core.fatal(_("Dataset <%s> not found in temporal database") % (sid))
  625. sp.select(dbif)
  626. ssp.select(dbif)
  627. if separator == None or separator == "" or separator.find(",") >= 0:
  628. separator = " | "
  629. mapmatrix = sp.sample_by_dataset_topology(ssp, method, dbif)
  630. if mapmatrix and len(mapmatrix) > 0:
  631. if header:
  632. string = ""
  633. string += "%s%s" % ("sample_id", separator)
  634. string += "%s%s" % ("ids", separator)
  635. string += "%s%s" % ("start_time", separator)
  636. string += "%s%s" % ("end_time", separator)
  637. string += "%s%s" % ("interval_length", separator)
  638. string += "%s" % ("distance_from_begin")
  639. print string
  640. first_time, dummy = mapmatrix[0]["granule"].get_valid_time()
  641. for entry in mapmatrix:
  642. mapnames = ""
  643. count = 0
  644. for sample in entry["samples"]:
  645. if count == 0:
  646. mapnames += str(sample.get_id())
  647. else:
  648. mapnames += ",%s" % str(sample.get_id())
  649. count += 1
  650. map = entry["granule"]
  651. start, end = map.get_valid_time()
  652. if end:
  653. delta = end - start
  654. else:
  655. delta = None
  656. delta_first = start - first_time
  657. if map.is_time_absolute():
  658. if end:
  659. delta = time_delta_to_relative_time(delta)
  660. delta_first = time_delta_to_relative_time(delta_first)
  661. string = ""
  662. string += "%s%s" % (map.get_id(), separator)
  663. string += "%s%s" % (mapnames, separator)
  664. string += "%s%s" % (start, separator)
  665. string += "%s%s" % (end, separator)
  666. string += "%s%s" % (delta, separator)
  667. string += "%s" % (delta_first)
  668. print string
  669. dbif.close()