data.py 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  1. # -*- coding: utf-8 -*-
  2. """
  3. @package animation.data
  4. @brief animation data structures
  5. Classes:
  6. - data::AnimationData
  7. - data::AnimationLayer
  8. (C) 2013 by the GRASS Development Team
  9. This program is free software under the GNU General Public License
  10. (>=v2). Read the file COPYING that comes with GRASS for details.
  11. @author Anna Petrasova <kratochanna gmail.com>
  12. """
  13. import os
  14. import copy
  15. from grass.script.utils import parse_key_val
  16. from grass.script import core as gcore
  17. from core.gcmd import GException
  18. from animation.nviztask import NvizTask
  19. from animation.utils import validateMapNames, getRegisteredMaps, \
  20. checkSeriesCompatibility, validateTimeseriesName, interpolate
  21. from core.layerlist import LayerList, Layer
  22. class AnimationData(object):
  23. def __init__(self):
  24. self._name = None
  25. self._windowIndex = 0
  26. self._layerList = None
  27. # only this stds is taken into account for time computations
  28. # if there are any stds at all
  29. self._firstStdsNameType = None
  30. self._mapCount = None
  31. self._cmdMatrix = None
  32. self._viewModes = [('2d', _("2D view")),
  33. ('3d', _("3D view"))]
  34. self.viewMode = '2d'
  35. self.nvizTask = NvizTask()
  36. self._nvizParameters = self.nvizTask.ListMapParameters()
  37. self.nvizParameter = self._nvizParameters[0]
  38. self.workspaceFile = None
  39. self.legendCmd = None
  40. self._startRegion = None
  41. self._endRegion = None
  42. self._zoomRegionValue = None
  43. self._regions = None
  44. def GetName(self):
  45. return self._name
  46. def SetName(self, name):
  47. if name == '':
  48. raise ValueError(_("No animation name selected."))
  49. self._name = name
  50. name = property(fget=GetName, fset=SetName)
  51. def GetWindowIndex(self):
  52. return self._windowIndex
  53. def SetWindowIndex(self, windowIndex):
  54. self._windowIndex = windowIndex
  55. windowIndex = property(fget=GetWindowIndex, fset=SetWindowIndex)
  56. def SetLayerList(self, layerList):
  57. """
  58. Throws GException if layer list's combination of stds is not valid.
  59. """
  60. mapSeriesList = []
  61. timeseriesList = []
  62. for layer in layerList:
  63. if layer.active and hasattr(layer, 'maps'):
  64. if layer.mapType in ('strds', 'stvds', 'str3ds'):
  65. timeseriesList.append((layer.name, layer.mapType))
  66. self._firstStdsNameType = layer.name, layer.mapType
  67. else:
  68. mapSeriesList.append((layer.maps))
  69. if not timeseriesList:
  70. self._firstStdsNameType = None, None
  71. # this throws GException
  72. count = checkSeriesCompatibility(mapSeriesList=mapSeriesList,
  73. timeseriesList=timeseriesList)
  74. self._mapCount = count
  75. self._layerList = layerList
  76. def GetLayerList(self):
  77. return self._layerList
  78. layerList = property(fget=GetLayerList, fset=SetLayerList)
  79. def GetFirstStdsNameType(self):
  80. return self._firstStdsNameType
  81. firstStdsNameType = property(fget=GetFirstStdsNameType)
  82. def GetMapCount(self):
  83. return self._mapCount
  84. mapCount = property(fget=GetMapCount)
  85. def GetCmdMatrix(self):
  86. return self._cmdMatrix
  87. def SetCmdMatrix(self, cmdMatrix):
  88. self._cmdMatrix = cmdMatrix
  89. cmdMatrix = property(fget=GetCmdMatrix, fset=SetCmdMatrix)
  90. def GetWorkspaceFile(self):
  91. return self._workspaceFile
  92. def SetWorkspaceFile(self, fileName):
  93. if fileName is None:
  94. self._workspaceFile = None
  95. return
  96. if fileName == '':
  97. raise ValueError(_("No workspace file selected."))
  98. if not os.path.exists(fileName):
  99. raise IOError(_("File %s not found") % fileName)
  100. self._workspaceFile = fileName
  101. self.nvizTask.Load(self.workspaceFile)
  102. workspaceFile = property(fget=GetWorkspaceFile, fset=SetWorkspaceFile)
  103. def SetDefaultValues(self, windowIndex, animationIndex):
  104. self.windowIndex = windowIndex
  105. self.name = _("Animation %d") % (animationIndex + 1)
  106. self.layerList = LayerList()
  107. def GetNvizParameters(self):
  108. return self._nvizParameters
  109. nvizParameters = property(fget=GetNvizParameters)
  110. def GetNvizParameter(self):
  111. return self._nvizParameter
  112. def SetNvizParameter(self, param):
  113. self._nvizParameter = param
  114. nvizParameter = property(fget=GetNvizParameter, fset=SetNvizParameter)
  115. def GetViewMode(self):
  116. return self._viewMode
  117. def SetViewMode(self, mode):
  118. self._viewMode = mode
  119. viewMode = property(fget=GetViewMode, fset=SetViewMode)
  120. def GetViewModes(self):
  121. return self._viewModes
  122. viewModes = property(fget=GetViewModes)
  123. def SetLegendCmd(self, cmd):
  124. self._legendCmd = cmd
  125. def GetLegendCmd(self):
  126. return self._legendCmd
  127. legendCmd = property(fget=GetLegendCmd, fset=SetLegendCmd)
  128. def GetNvizCommands(self):
  129. if not self.workspaceFile or not self._layerList:
  130. return []
  131. cmds = self.nvizTask.GetCommandSeries(layerList=self._layerList,
  132. paramName=self.nvizParameter)
  133. region = self.nvizTask.GetRegion()
  134. return {'commands': cmds, 'region': region}
  135. def SetStartRegion(self, region):
  136. self._startRegion = region
  137. def GetStartRegion(self):
  138. return self._startRegion
  139. startRegion = property(fset=SetStartRegion, fget=GetStartRegion)
  140. def SetEndRegion(self, region):
  141. self._endRegion = region
  142. def GetEndRegion(self):
  143. return self._endRegion
  144. endRegion = property(fset=SetEndRegion, fget=GetEndRegion)
  145. def SetZoomRegionValue(self, value):
  146. self._zoomRegionValue = value
  147. def GetZoomRegionValue(self):
  148. return self._zoomRegionValue
  149. zoomRegionValue = property(
  150. fset=SetZoomRegionValue,
  151. fget=GetZoomRegionValue)
  152. def GetRegions(self):
  153. self._computeRegions(self._mapCount, self._startRegion,
  154. self._endRegion, self._zoomRegionValue)
  155. return self._regions
  156. def _computeRegions(
  157. self, count, startRegion, endRegion=None,
  158. zoomValue=None):
  159. """Computes regions based on start region and end region or zoom value
  160. for each of the animation frames."""
  161. region = dict(gcore.region()) # cast to dict, otherwise deepcopy error
  162. if startRegion:
  163. region = dict(parse_key_val(gcore.read_command('g.region',
  164. flags='gu',
  165. region=startRegion),
  166. val_type=float))
  167. del region['cells']
  168. del region['cols']
  169. del region['rows']
  170. if 'projection' in region:
  171. del region['projection']
  172. if 'zone' in region:
  173. del region['zone']
  174. regions = []
  175. for i in range(self._mapCount):
  176. regions.append(copy.copy(region))
  177. self._regions = regions
  178. if not (endRegion or zoomValue):
  179. return
  180. startRegionDict = parse_key_val(
  181. gcore.read_command(
  182. 'g.region',
  183. flags='gu',
  184. region=startRegion),
  185. val_type=float)
  186. if endRegion:
  187. endRegionDict = parse_key_val(
  188. gcore.read_command(
  189. 'g.region',
  190. flags='gu',
  191. region=endRegion),
  192. val_type=float)
  193. for key in ('n', 's', 'e', 'w', 'nsres', 'ewres'):
  194. values = interpolate(
  195. startRegionDict[key],
  196. endRegionDict[key],
  197. self._mapCount)
  198. for value, region in zip(values, regions):
  199. region[key] = value
  200. elif zoomValue:
  201. for i in range(self._mapCount):
  202. regions[i]['n'] -= zoomValue[0] * i
  203. regions[i]['e'] -= zoomValue[1] * i
  204. regions[i]['s'] += zoomValue[0] * i
  205. regions[i]['w'] += zoomValue[1] * i
  206. # handle cases when north < south and similarly EW
  207. if regions[i]['n'] < regions[i]['s'] or \
  208. regions[i]['e'] < regions[i]['w']:
  209. regions[i] = regions[i - 1]
  210. self._regions = regions
  211. def __repr__(self):
  212. return "%s(%r)" % (self.__class__, self.__dict__)
  213. class AnimLayer(Layer):
  214. """Animation layer allows adding either space-time dataset
  215. or series of maps."""
  216. def __init__(self):
  217. Layer.__init__(self)
  218. self._mapTypes.extend(['strds', 'stvds', 'str3ds'])
  219. self._maps = []
  220. def SetName(self, name):
  221. if not self.hidden:
  222. if self._mapType is None:
  223. raise ValueError(
  224. "To set layer name, the type of layer must be specified.")
  225. if self._mapType in ('strds', 'stvds', 'str3ds'):
  226. try:
  227. name = validateTimeseriesName(name, self._mapType)
  228. self._maps = getRegisteredMaps(name, self._mapType)
  229. except (GException, gcore.ScriptError) as e:
  230. raise ValueError(str(e))
  231. else:
  232. self._maps = validateMapNames(name.split(','), self._mapType)
  233. self._name = name
  234. self.label = name
  235. def GetName(self):
  236. return self._name
  237. name = property(fget=GetName, fset=SetName)
  238. def GetMaps(self):
  239. return self._maps
  240. maps = property(fget=GetMaps)