utils.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  1. """
  2. @package animation.utils
  3. @brief Miscellaneous functions and enum classes
  4. Classes:
  5. - utils::TemporalMode
  6. - utils::TemporalType
  7. - utils::Orientation
  8. - utils::ReplayMode
  9. (C) 2013 by the GRASS Development Team
  10. This program is free software under the GNU General Public License
  11. (>=v2). Read the file COPYING that comes with GRASS for details.
  12. @author Anna Perasova <kratochanna gmail.com>
  13. """
  14. import os
  15. import wx
  16. import hashlib
  17. import six
  18. from multiprocessing import cpu_count
  19. try:
  20. from PIL import Image
  21. hasPIL = True
  22. except ImportError:
  23. hasPIL = False
  24. import grass.temporal as tgis
  25. import grass.script as grass
  26. from grass.script.utils import encode
  27. from gui_core.wrap import EmptyBitmap
  28. from core.gcmd import GException
  29. class TemporalMode:
  30. TEMPORAL = 1
  31. NONTEMPORAL = 2
  32. class TemporalType:
  33. ABSOLUTE = 1
  34. RELATIVE = 2
  35. class Orientation:
  36. FORWARD = 1
  37. BACKWARD = 2
  38. class ReplayMode:
  39. ONESHOT = 1
  40. REVERSE = 2
  41. REPEAT = 3
  42. def validateTimeseriesName(timeseries, etype='strds'):
  43. """Checks if space time dataset exists and completes missing mapset.
  44. Raises GException if dataset doesn't exist.
  45. """
  46. trastDict = tgis.tlist_grouped(etype)
  47. if timeseries.find("@") >= 0:
  48. nameShort, mapset = timeseries.split('@', 1)
  49. if nameShort in trastDict[mapset]:
  50. return timeseries
  51. else:
  52. raise GException(
  53. _("Space time dataset <%s> not found.") %
  54. timeseries)
  55. mapsets = tgis.get_tgis_c_library_interface().available_mapsets()
  56. for mapset in mapsets:
  57. if mapset in trastDict.keys():
  58. if timeseries in trastDict[mapset]:
  59. return timeseries + "@" + mapset
  60. raise GException(_("Space time dataset <%s> not found.") % timeseries)
  61. def validateMapNames(names, etype):
  62. """Checks if maps exist and completes missing mapset.
  63. Input is list of map names.
  64. Raises GException if map doesn't exist.
  65. """
  66. mapDict = grass.list_grouped(etype)
  67. newNames = []
  68. for name in names:
  69. if name.find("@") >= 0:
  70. nameShort, mapset = name.split('@', 1)
  71. if nameShort in mapDict[mapset]:
  72. newNames.append(name)
  73. else:
  74. raise GException(_("Map <%s> not found.") % name)
  75. else:
  76. found = False
  77. for mapset, mapNames in six.iteritems(mapDict):
  78. if name in mapNames:
  79. found = True
  80. newNames.append(name + "@" + mapset)
  81. if not found:
  82. raise GException(_("Map <%s> not found.") % name)
  83. return newNames
  84. def getRegisteredMaps(timeseries, etype):
  85. """Returns list of maps registered in dataset.
  86. Can throw ScriptError if the dataset doesn't exist.
  87. """
  88. timeseriesMaps = []
  89. sp = tgis.open_old_stds(timeseries, etype)
  90. rows = sp.get_registered_maps(columns="id", where=None, order="start_time")
  91. timeseriesMaps = []
  92. if rows:
  93. for row in rows:
  94. timeseriesMaps.append(row["id"])
  95. return timeseriesMaps
  96. def getNameAndLayer(name):
  97. """Checks whether map name contains layer
  98. and returns map name with mapset (when there was mapset)
  99. and layer (can be None).
  100. >>> getNameAndLayer('name:2@mapset')
  101. ('name@mapset', '2')
  102. >>> getNameAndLayer('name@mapset')
  103. ('name@mapset', None)
  104. >>> getNameAndLayer('name:2')
  105. ('name', '2')
  106. """
  107. mapset = layer = None
  108. if '@' in name:
  109. name, mapset = name.split('@')
  110. if ':' in name:
  111. name, layer = name.split(':')
  112. if mapset:
  113. name = name + '@' + mapset
  114. return name, layer
  115. def checkSeriesCompatibility(mapSeriesList=None, timeseriesList=None):
  116. """Checks whether time series (map series and stds) are compatible,
  117. which means they have equal number of maps ad times (in case of stds).
  118. This is needed within layer list, not within the entire animation tool.
  119. Throws GException if these are incompatible.
  120. :return: number of maps for animation
  121. """
  122. timeseriesInfo = {'count': set(), 'temporalType': set(), 'mapType': set(),
  123. 'mapTimes': set()}
  124. if timeseriesList:
  125. for stds, etype in timeseriesList:
  126. sp = tgis.open_old_stds(stds, etype)
  127. mapType = sp.get_map_time() # interval, ...
  128. tempType = sp.get_initial_values()[0] # absolute
  129. timeseriesInfo['mapType'].add(mapType)
  130. timeseriesInfo['temporalType'].add(tempType)
  131. rows = sp.get_registered_maps_as_objects(where=None,
  132. order="start_time")
  133. if rows:
  134. times = []
  135. timeseriesInfo['count'].add(len(rows))
  136. for row in rows:
  137. if tempType == 'absolute':
  138. time = row.get_absolute_time()
  139. else:
  140. time = row.get_relative_time()
  141. times.append(time)
  142. timeseriesInfo['mapTimes'].add(tuple(times))
  143. else:
  144. timeseriesInfo['mapTimes'].add(None)
  145. timeseriesInfo['count'].add(None)
  146. if len(timeseriesInfo['count']) > 1:
  147. raise GException(_("The number of maps in space-time datasets "
  148. "has to be the same."))
  149. if len(timeseriesInfo['temporalType']) > 1:
  150. raise GException(_("The temporal type (absolute/relative) of space-time datasets "
  151. "has to be the same."))
  152. if len(timeseriesInfo['mapType']) > 1:
  153. raise GException(_("The map type (point/interval) of space-time datasets "
  154. "has to be the same."))
  155. if len(timeseriesInfo['mapTimes']) > 1:
  156. raise GException(_("The temporal extents of maps in space-time datasets "
  157. "have to be the same."))
  158. if mapSeriesList:
  159. count = set()
  160. for mapSeries in mapSeriesList:
  161. count.add(len(mapSeries))
  162. if len(count) > 1:
  163. raise GException(_("The number of maps to animate has to be "
  164. "the same for each map series."))
  165. if timeseriesList and list(count)[0] != list(
  166. timeseriesInfo['count'])[0]:
  167. raise GException(_("The number of maps to animate has to be "
  168. "the same as the number of maps in temporal dataset."))
  169. if mapSeriesList:
  170. return list(count)[0]
  171. if timeseriesList:
  172. return list(timeseriesInfo['count'])[0]
  173. def ComputeScaledRect(sourceSize, destSize):
  174. """Fits source rectangle into destination rectangle
  175. by scaling and centering.
  176. >>> ComputeScaledRect(sourceSize = (10, 40), destSize = (100, 50))
  177. {'height': 50, 'scale': 1.25, 'width': 13, 'x': 44, 'y': 0}
  178. :param sourceSize: size of source rectangle
  179. :param destSize: size of destination rectangle
  180. """
  181. ratio1 = destSize[0] / float(sourceSize[0])
  182. ratio2 = destSize[1] / float(sourceSize[1])
  183. if ratio1 < ratio2:
  184. scale = ratio1
  185. width = int(sourceSize[0] * scale + 0.5)
  186. height = int(sourceSize[1] * scale + 0.5)
  187. x = 0
  188. y = int((destSize[1] - height) / 2. + 0.5)
  189. else:
  190. scale = ratio2
  191. width = int(sourceSize[0] * scale + 0.5)
  192. height = int(sourceSize[1] * scale + 0.5)
  193. y = 0
  194. x = int((destSize[0] - width) / 2. + 0.5)
  195. return {'width': width, 'height': height, 'x': x, 'y': y, 'scale': scale}
  196. def RenderText(text, font, bgcolor, fgcolor):
  197. """Renderes text with given font to bitmap."""
  198. dc = wx.MemoryDC(EmptyBitmap(20, 20))
  199. dc.SetFont(font)
  200. w, h = dc.GetTextExtent(text)
  201. bmp = EmptyBitmap(w + 2, h + 2)
  202. dc.SelectObject(bmp)
  203. dc.SetBackgroundMode(wx.SOLID)
  204. dc.SetTextBackground(wx.Colour(*bgcolor))
  205. dc.SetTextForeground(wx.Colour(*fgcolor))
  206. dc.Clear()
  207. dc.DrawText(text, 1, 1)
  208. dc.SelectObject(wx.NullBitmap)
  209. return bmp
  210. def WxImageToPil(image):
  211. """Converts wx.Image to PIL image"""
  212. pilImage = Image.new('RGB', (image.GetWidth(), image.GetHeight()))
  213. pilImage.frombytes(bytes(image.GetData()))
  214. return pilImage
  215. def HashCmd(cmd, region):
  216. """Returns a hash from command given as a list and a region as a dict."""
  217. name = '_'.join(cmd)
  218. if region:
  219. name += str(sorted(region.items()))
  220. return hashlib.sha1(encode(name)).hexdigest()
  221. def HashCmds(cmds, region):
  222. """Returns a hash from list of commands and regions as dicts."""
  223. name = ';'.join([item for sublist in cmds for item in sublist])
  224. if region:
  225. name += str(sorted(region.items()))
  226. return hashlib.sha1(encode(name)).hexdigest()
  227. def GetFileFromCmd(dirname, cmd, region, extension='ppm'):
  228. """Returns file path created as a hash from command and region."""
  229. return os.path.join(dirname, HashCmd(cmd, region) + '.' + extension)
  230. def GetFileFromCmds(dirname, cmds, region, extension='ppm'):
  231. """Returns file path created as a hash from list of commands and regions."""
  232. return os.path.join(dirname, HashCmds(cmds, region) + '.' + extension)
  233. def layerListToCmdsMatrix(layerList):
  234. """Goes thru layerList and create matrix of commands
  235. for the composition of map series.:
  236. :return: matrix of cmds for composition
  237. """
  238. count = 0
  239. for layer in layerList:
  240. if layer.active and hasattr(layer, 'maps'):
  241. # assuming the consistency of map number is checked already
  242. count = len(layer.maps)
  243. break
  244. cmdsForComposition = []
  245. for layer in layerList:
  246. if not layer.active:
  247. continue
  248. if hasattr(layer, 'maps'):
  249. for i, part in enumerate(layer.cmd):
  250. if part.startswith('map='):
  251. cmd = layer.cmd[:]
  252. cmds = []
  253. for map_ in layer.maps:
  254. # check if dataset uses layers instead of maps
  255. mapName, mapLayer = getNameAndLayer(map_)
  256. cmd[i] = 'map={name}'.format(name=mapName)
  257. if mapLayer:
  258. try:
  259. idx = cmd.index('layer')
  260. cmd[idx] = 'layer={layer}'.format(
  261. layer=mapLayer)
  262. except ValueError:
  263. cmd.append(
  264. 'layer={layer}'.format(
  265. layer=mapLayer))
  266. cmds.append(cmd[:])
  267. cmdsForComposition.append(cmds)
  268. else:
  269. cmdsForComposition.append([layer.cmd] * count)
  270. return list(zip(*cmdsForComposition))
  271. def sampleCmdMatrixAndCreateNames(cmdMatrix, sampledSeries, regions):
  272. """Applies information from temporal sampling
  273. to the command matrix."""
  274. namesList = []
  275. j = -1
  276. lastName = ''
  277. for name in sampledSeries:
  278. if name is not None:
  279. if lastName != name:
  280. lastName = name
  281. j += 1
  282. namesList.append(HashCmds(cmdMatrix[j], regions[j]))
  283. else:
  284. namesList.append(None)
  285. assert(j == len(cmdMatrix) - 1)
  286. return namesList
  287. def getCpuCount():
  288. """Returns number of available cpus.
  289. If fails, default (4) is returned.
  290. """
  291. try:
  292. return cpu_count()
  293. except NotImplementedError:
  294. return 4
  295. def interpolate(start, end, count):
  296. """Interpolates values between start and end.
  297. :param start: start value (float)
  298. :param end: end value (float)
  299. :param count: total number of values including start and end
  300. >>> interpolate(0, 10, 5)
  301. [0, 2.5, 5.0, 7.5, 10]
  302. >>> interpolate(10, 0, 5)
  303. [10, 7.5, 5.0, 2.5, 0]
  304. """
  305. step = (end - start) / float(count - 1)
  306. values = []
  307. if start < end:
  308. while start < end:
  309. values.append(start)
  310. start += step
  311. elif end < start:
  312. while end < start:
  313. values.append(start)
  314. start += step
  315. else:
  316. values = [start] * (count - 1)
  317. values.append(end)
  318. return values