list_stds.py 12 KB

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