utils.py 12 KB

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