utils.py 11 KB

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