utils.py 12 KB

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