list_stds.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  1. """
  2. Functions to create space time dataset lists
  3. Usage:
  4. .. code-block:: python
  5. import grass.temporal as tgis
  6. tgis.register_maps_in_space_time_dataset(type, name, maps)
  7. (C) 2012-2016 by the GRASS Development Team
  8. This program is free software under the GNU General Public
  9. License (>=v2). Read the file COPYING that comes with GRASS GIS
  10. for details.
  11. :authors: Soeren Gebbert
  12. """
  13. from __future__ import print_function
  14. from .core import get_tgis_message_interface, get_available_temporal_mapsets, init_dbif
  15. from .datetime_math import time_delta_to_relative_time
  16. from .factory import dataset_factory
  17. from .open_stds import open_old_stds
  18. import grass.script as gscript
  19. ###############################################################################
  20. def get_dataset_list(type, temporal_type, columns=None, where=None,
  21. order=None, dbif=None):
  22. """ Return a list of time stamped maps or space time datasets of a specific
  23. temporal type that are registered in the temporal database
  24. This method returns a dictionary, the keys are the available mapsets,
  25. the values are the rows from the SQL database query.
  26. :param type: The type of the datasets (strds, str3ds, stvds, raster,
  27. raster_3d, vector)
  28. :param temporal_type: The temporal type of the datasets (absolute,
  29. relative)
  30. :param columns: A comma separated list of columns that will be selected
  31. :param where: A where statement for selected listing without "WHERE"
  32. :param order: A comma separated list of columns to order the
  33. datasets by category
  34. :param dbif: The database interface to be used
  35. :return: A dictionary with the rows of the SQL query for each
  36. available mapset
  37. .. code-block:: python
  38. >>> import grass.temporal as tgis
  39. >>> tgis.core.init()
  40. >>> name = "list_stds_test"
  41. >>> sp = tgis.open_stds.open_new_stds(name=name, type="strds",
  42. ... temporaltype="absolute", title="title", descr="descr",
  43. ... semantic="mean", dbif=None, overwrite=True)
  44. >>> mapset = tgis.get_current_mapset()
  45. >>> stds_list = tgis.list_stds.get_dataset_list("strds", "absolute", columns="name")
  46. >>> rows = stds_list[mapset]
  47. >>> for row in rows:
  48. ... if row["name"] == name:
  49. ... print(True)
  50. True
  51. >>> stds_list = tgis.list_stds.get_dataset_list("strds", "absolute", columns="name,mapset", where="mapset = '%s'"%(mapset))
  52. >>> rows = stds_list[mapset]
  53. >>> for row in rows:
  54. ... if row["name"] == name and row["mapset"] == mapset:
  55. ... print(True)
  56. True
  57. >>> check = sp.delete()
  58. """
  59. id = None
  60. sp = dataset_factory(type, id)
  61. dbif, connection_state_changed = init_dbif(dbif)
  62. mapsets = get_available_temporal_mapsets()
  63. result = {}
  64. for mapset in mapsets.keys():
  65. if temporal_type == "absolute":
  66. table = sp.get_type() + "_view_abs_time"
  67. else:
  68. table = sp.get_type() + "_view_rel_time"
  69. if columns and columns.find("all") == -1:
  70. sql = "SELECT " + str(columns) + " FROM " + table
  71. else:
  72. sql = "SELECT * FROM " + table
  73. if where:
  74. sql += " WHERE " + where
  75. sql += " AND mapset = '%s'" % (mapset)
  76. else:
  77. sql += " WHERE mapset = '%s'" % (mapset)
  78. if order:
  79. sql += " ORDER BY " + order
  80. dbif.execute(sql, mapset=mapset)
  81. rows = dbif.fetchall(mapset=mapset)
  82. if rows:
  83. result[mapset] = rows
  84. if connection_state_changed:
  85. dbif.close()
  86. return result
  87. ###############################################################################
  88. def list_maps_of_stds(type, input, columns, order, where, separator,
  89. method, no_header=False, gran=None, dbif=None,
  90. outpath=None):
  91. """ List the maps of a space time dataset using different methods
  92. :param type: The type of the maps raster, raster3d or vector
  93. :param input: Name of a space time raster dataset
  94. :param columns: A comma separated list of columns to be printed to stdout
  95. :param order: A comma separated list of columns to order the
  96. maps by category
  97. :param where: A where statement for selected listing without "WHERE"
  98. e.g: start_time < "2001-01-01" and end_time > "2001-01-01"
  99. :param separator: The field separator character between the columns
  100. :param method: String identifier to select a method out of cols,
  101. comma,delta or deltagaps
  102. :param dbif: The database interface to be used
  103. - "cols" Print preselected columns specified by columns
  104. - "comma" Print the map ids ("name@mapset") as comma separated string
  105. - "delta" Print the map ids ("name@mapset") with start time,
  106. end time, relative length of intervals and the relative
  107. distance to the begin
  108. - "deltagaps" Same as "delta" with additional listing of gaps.
  109. Gaps can be easily identified as the id is "None"
  110. - "gran" List map using the granularity of the space time dataset,
  111. columns are identical to deltagaps
  112. :param no_header: Suppress the printing of column names
  113. :param gran: The user defined granule to be used if method=gran is
  114. set, in case gran=None the granule of the space time
  115. dataset is used
  116. :param outpath: The path to file where to save output
  117. """
  118. dbif, connection_state_changed = init_dbif(dbif)
  119. msgr = get_tgis_message_interface()
  120. sp = open_old_stds(input, type, dbif)
  121. if separator is None or separator == "":
  122. separator = "\t"
  123. if outpath:
  124. outfile = open(outpath, 'w')
  125. # This method expects a list of objects for gap detection
  126. if method == "delta" or method == "deltagaps" or method == "gran":
  127. if type == "stvds":
  128. columns = "id,name,layer,mapset,start_time,end_time"
  129. else:
  130. columns = "id,name,mapset,start_time,end_time"
  131. if method == "deltagaps":
  132. maps = sp.get_registered_maps_as_objects_with_gaps(where=where,
  133. dbif=dbif)
  134. elif method == "delta":
  135. maps = sp.get_registered_maps_as_objects(where=where,
  136. order="start_time",
  137. dbif=dbif)
  138. elif method == "gran":
  139. if gran is not None and gran != "":
  140. maps = sp.get_registered_maps_as_objects_by_granularity(gran=gran,
  141. dbif=dbif)
  142. else:
  143. maps = sp.get_registered_maps_as_objects_by_granularity(dbif=dbif)
  144. if no_header is False:
  145. string = ""
  146. string += "%s%s" % ("id", separator)
  147. string += "%s%s" % ("name", separator)
  148. if type == "stvds":
  149. string += "%s%s" % ("layer", separator)
  150. string += "%s%s" % ("mapset", separator)
  151. string += "%s%s" % ("start_time", separator)
  152. string += "%s%s" % ("end_time", separator)
  153. string += "%s%s" % ("interval_length", separator)
  154. string += "%s" % ("distance_from_begin")
  155. if outpath:
  156. outfile.write('{st}\n'.format(st=string))
  157. else:
  158. print(string)
  159. if maps and len(maps) > 0:
  160. if isinstance(maps[0], list):
  161. if len(maps[0]) > 0:
  162. first_time, dummy = maps[0][0].get_temporal_extent_as_tuple()
  163. else:
  164. msgr.warning(_("Empty map list"))
  165. return
  166. else:
  167. first_time, dummy = maps[0].get_temporal_extent_as_tuple()
  168. for mymap in maps:
  169. if isinstance(mymap, list):
  170. if len(mymap) > 0:
  171. map = mymap[0]
  172. else:
  173. msgr.fatal(_("Empty entry in map list, this should not happen"))
  174. else:
  175. map = mymap
  176. start, end = map.get_temporal_extent_as_tuple()
  177. if end:
  178. delta = end - start
  179. else:
  180. delta = None
  181. delta_first = start - first_time
  182. if map.is_time_absolute():
  183. if end:
  184. delta = time_delta_to_relative_time(delta)
  185. delta_first = time_delta_to_relative_time(delta_first)
  186. string = ""
  187. string += "%s%s" % (map.get_id(), separator)
  188. string += "%s%s" % (map.get_name(), separator)
  189. if type == "stvds":
  190. string += "%s%s" % (map.get_layer(), separator)
  191. string += "%s%s" % (map.get_mapset(), separator)
  192. string += "%s%s" % (start, separator)
  193. string += "%s%s" % (end, separator)
  194. string += "%s%s" % (delta, separator)
  195. string += "%s" % (delta_first)
  196. if outpath:
  197. outfile.write('{st}\n'.format(st=string))
  198. else:
  199. print(string)
  200. else:
  201. # In comma separated mode only map ids are needed
  202. if method == "comma":
  203. if columns not in ['id', 'name']:
  204. columns = "id"
  205. rows = sp.get_registered_maps(columns, where, order, dbif)
  206. if not rows:
  207. dbif.close()
  208. err = "Space time %(sp)s dataset <%(i)s> is empty"
  209. if where:
  210. err += " or where condition is wrong"
  211. gscript.fatal(_(err) % {
  212. 'sp': sp.get_new_map_instance(None).get_type(),
  213. 'i': sp.get_id()})
  214. if rows:
  215. if method == "comma":
  216. string = ""
  217. count = 0
  218. for row in rows:
  219. if count == 0:
  220. string += row[columns]
  221. else:
  222. string += ",%s" % row[columns]
  223. count += 1
  224. if outpath:
  225. outfile.write('{st}\n'.format(st=string))
  226. else:
  227. print(string)
  228. elif method == "cols":
  229. # Print the column names if requested
  230. if no_header is False:
  231. output = ""
  232. count = 0
  233. collist = columns.split(",")
  234. for key in collist:
  235. if count > 0:
  236. output += separator + str(key)
  237. else:
  238. output += str(key)
  239. count += 1
  240. if outpath:
  241. outfile.write('{st}\n'.format(st=output))
  242. else:
  243. print(output)
  244. for row in rows:
  245. output = ""
  246. count = 0
  247. for col in row:
  248. if count > 0:
  249. output += separator + str(col)
  250. else:
  251. output += str(col)
  252. count += 1
  253. if outpath:
  254. outfile.write('{st}\n'.format(st=output))
  255. else:
  256. print(output)
  257. if outpath:
  258. outfile.close()
  259. if connection_state_changed:
  260. dbif.close()
  261. ###############################################################################
  262. if __name__ == "__main__":
  263. import doctest
  264. doctest.testmod()