list_stds.py 12 KB

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