utils.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481
  1. """!
  2. @package psmap.utils
  3. @brief utilities for wxpsmap (classes, functions)
  4. Classes:
  5. - utils::Rect2D
  6. - utils::Rect2DPP
  7. - utils::Rect2DPS
  8. - utils::UnitConversion
  9. (C) 2012 by Anna Kratochvilova, and 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 Kratochvilova <kratochanna gmail.com>
  13. """
  14. import os
  15. import wx
  16. import string
  17. from math import ceil, floor, sin, cos, pi
  18. try:
  19. import Image as PILImage
  20. havePILImage = True
  21. except ImportError:
  22. havePILImage = False
  23. import grass.script as grass
  24. from core.gcmd import RunCommand
  25. from core.utils import _
  26. class Rect2D(wx.Rect2D):
  27. """!Class representing rectangle with floating point values.
  28. Overrides wx.Rect2D to unify Rect access methods, which are
  29. different (e.g. wx.Rect.GetTopLeft() x wx.Rect2D.GetLeftTop()).
  30. More methods can be added depending on needs.
  31. """
  32. def __init__(self, x = 0, y = 0, width = 0, height = 0):
  33. wx.Rect2D.__init__(self, x = x, y = y, w = width, h = height)
  34. def GetX(self):
  35. return self.x
  36. def GetY(self):
  37. return self.y
  38. def GetWidth(self):
  39. return self.width
  40. def SetWidth(self, width):
  41. self.width = width
  42. def GetHeight(self):
  43. return self.height
  44. def SetHeight(self, height):
  45. self.height = height
  46. class Rect2DPP(Rect2D):
  47. """!Rectangle specified by 2 points (with floating point values).
  48. @see Rect2D, Rect2DPS
  49. """
  50. def __init__(self, topLeft = wx.Point2D(), bottomRight = wx.Point2D()):
  51. Rect2D.__init__(self, x = 0, y = 0, width = 0, height = 0)
  52. x1, y1 = topLeft[0], topLeft[1]
  53. x2, y2 = bottomRight[0], bottomRight[1]
  54. self.SetLeft(min(x1, x2))
  55. self.SetTop(min(y1, y2))
  56. self.SetRight(max(x1, x2))
  57. self.SetBottom(max(y1, y2))
  58. class Rect2DPS(Rect2D):
  59. """!Rectangle specified by point and size (with floating point values).
  60. @see Rect2D, Rect2DPP
  61. """
  62. def __init__(self, pos = wx.Point2D(), size = (0, 0)):
  63. Rect2D.__init__(self, x = pos[0], y = pos[1], width = size[0], height = size[1])
  64. class UnitConversion:
  65. """! Class for converting units"""
  66. def __init__(self, parent = None):
  67. self.parent = parent
  68. if self.parent:
  69. ppi = wx.ClientDC(self.parent).GetPPI()
  70. else:
  71. ppi = (72, 72)
  72. self._unitsPage = { 'inch' : {'val': 1.0, 'tr' : _("inch")},
  73. 'point' : {'val': 72.0, 'tr' : _("point")},
  74. 'centimeter' : {'val': 2.54, 'tr' : _("centimeter")},
  75. 'millimeter' : {'val': 25.4, 'tr' : _("millimeter")}}
  76. self._unitsMap = { 'meters' : {'val': 0.0254, 'tr' : _("meters")},
  77. 'kilometers' : {'val': 2.54e-5, 'tr' : _("kilometers")},
  78. 'feet' : {'val': 1./12, 'tr' : _("feet")},
  79. 'miles' : {'val': 1./63360, 'tr' : _("miles")},
  80. 'nautical miles': {'val': 1/72913.386, 'tr' : _("nautical miles")}}
  81. self._units = { 'pixel' : {'val': ppi[0], 'tr' : _("pixel")},
  82. 'meter' : {'val': 0.0254, 'tr' : _("meter")},
  83. 'nautmiles' : {'val': 1/72913.386, 'tr' :_("nautical miles")},
  84. 'degrees' : {'val': 0.0254 , 'tr' : _("degree")} #like 1 meter, incorrect
  85. }
  86. self._units.update(self._unitsPage)
  87. self._units.update(self._unitsMap)
  88. def getPageUnitsNames(self):
  89. return sorted(self._unitsPage[unit]['tr'] for unit in self._unitsPage.keys())
  90. def getMapUnitsNames(self):
  91. return sorted(self._unitsMap[unit]['tr'] for unit in self._unitsMap.keys())
  92. def getAllUnits(self):
  93. return sorted(self._units.keys())
  94. def findUnit(self, name):
  95. """!Returns unit by its tr. string"""
  96. for unit in self._units.keys():
  97. if self._units[unit]['tr'] == name:
  98. return unit
  99. return None
  100. def findName(self, unit):
  101. """!Returns tr. string of a unit"""
  102. try:
  103. return self._units[unit]['tr']
  104. except KeyError:
  105. return None
  106. def convert(self, value, fromUnit = None, toUnit = None):
  107. return float(value)/self._units[fromUnit]['val']*self._units[toUnit]['val']
  108. def convertRGB(rgb):
  109. """!Converts wx.Colour(r,g,b,a) to string 'r:g:b' or named color,
  110. or named color/r:g:b string to wx.Colour, depending on input"""
  111. # transform a wx.Colour tuple into an r:g:b string
  112. if type(rgb) == wx.Colour:
  113. for name, color in grass.named_colors.items():
  114. if rgb.Red() == int(color[0] * 255) and\
  115. rgb.Green() == int(color[1] * 255) and\
  116. rgb.Blue() == int(color[2] * 255):
  117. return name
  118. return str(rgb.Red()) + ':' + str(rgb.Green()) + ':' + str(rgb.Blue())
  119. # transform a GRASS named color or an r:g:b string into a wx.Colour tuple
  120. else:
  121. color = (grass.parse_color(rgb)[0]*255,
  122. grass.parse_color(rgb)[1]*255,
  123. grass.parse_color(rgb)[2]*255)
  124. color = wx.Colour(*color)
  125. if color.IsOk():
  126. return color
  127. else:
  128. return None
  129. def PaperMapCoordinates(mapInstr, x, y, paperToMap = True):
  130. """!Converts paper (inch) coordinates <-> map coordinates.
  131. @param mapInstr map frame instruction
  132. @param x,y paper coords in inches or mapcoords in map units
  133. @param paperToMap specify conversion direction
  134. """
  135. region = grass.region()
  136. mapWidthPaper = mapInstr['rect'].GetWidth()
  137. mapHeightPaper = mapInstr['rect'].GetHeight()
  138. mapWidthEN = region['e'] - region['w']
  139. mapHeightEN = region['n'] - region['s']
  140. if paperToMap:
  141. diffX = x - mapInstr['rect'].GetX()
  142. diffY = y - mapInstr['rect'].GetY()
  143. diffEW = diffX * mapWidthEN / mapWidthPaper
  144. diffNS = diffY * mapHeightEN / mapHeightPaper
  145. e = region['w'] + diffEW
  146. n = region['n'] - diffNS
  147. if projInfo()['proj'] == 'll':
  148. return e, n
  149. else:
  150. return int(e), int(n)
  151. else:
  152. diffEW = x - region['w']
  153. diffNS = region['n'] - y
  154. diffX = mapWidthPaper * diffEW / mapWidthEN
  155. diffY = mapHeightPaper * diffNS / mapHeightEN
  156. xPaper = mapInstr['rect'].GetX() + diffX
  157. yPaper = mapInstr['rect'].GetY() + diffY
  158. return xPaper, yPaper
  159. def AutoAdjust(self, scaleType, rect, map = None, mapType = None, region = None):
  160. """!Computes map scale, center and map frame rectangle to fit region (scale is not fixed)"""
  161. currRegionDict = {}
  162. if scaleType == 0 and map:# automatic, region from raster or vector
  163. res = ''
  164. if mapType == 'raster':
  165. try:
  166. res = grass.read_command("g.region", flags = 'gu', rast = map)
  167. except grass.ScriptError:
  168. pass
  169. elif mapType == 'vector':
  170. res = grass.read_command("g.region", flags = 'gu', vect = map)
  171. currRegionDict = grass.parse_key_val(res, val_type = float)
  172. elif scaleType == 1 and region: # saved region
  173. res = grass.read_command("g.region", flags = 'gu', region = region)
  174. currRegionDict = grass.parse_key_val(res, val_type = float)
  175. elif scaleType == 2: # current region
  176. env = grass.gisenv()
  177. windFilePath = os.path.join(env['GISDBASE'], env['LOCATION_NAME'], env['MAPSET'], 'WIND')
  178. try:
  179. windFile = open(windFilePath, 'r').read()
  180. except IOError:
  181. currRegionDict = grass.region()
  182. regionDict = grass.parse_key_val(windFile, sep = ':', val_type = float)
  183. region = grass.read_command("g.region", flags = 'gu', n = regionDict['north'], s = regionDict['south'],
  184. e = regionDict['east'], w = regionDict['west'])
  185. currRegionDict = grass.parse_key_val(region, val_type = float)
  186. else:
  187. return None, None, None
  188. if not currRegionDict:
  189. return None, None, None
  190. rX = rect.x
  191. rY = rect.y
  192. rW = rect.width
  193. rH = rect.height
  194. if not hasattr(self, 'unitConv'):
  195. self.unitConv = UnitConversion(self)
  196. toM = 1
  197. if projInfo()['proj'] != 'xy':
  198. toM = float(projInfo()['meters'])
  199. mW = self.unitConv.convert(value = (currRegionDict['e'] - currRegionDict['w']) * toM, fromUnit = 'meter', toUnit = 'inch')
  200. mH = self.unitConv.convert(value = (currRegionDict['n'] - currRegionDict['s']) * toM, fromUnit = 'meter', toUnit = 'inch')
  201. scale = min(rW/mW, rH/mH)
  202. if rW/rH > mW/mH:
  203. x = rX - (rH*(mW/mH) - rW)/2
  204. y = rY
  205. rWNew = rH*(mW/mH)
  206. rHNew = rH
  207. else:
  208. x = rX
  209. y = rY - (rW*(mH/mW) - rH)/2
  210. rHNew = rW*(mH/mW)
  211. rWNew = rW
  212. # center
  213. cE = (currRegionDict['w'] + currRegionDict['e'])/2
  214. cN = (currRegionDict['n'] + currRegionDict['s'])/2
  215. return scale, (cE, cN), Rect2D(x, y, rWNew, rHNew) #inch
  216. def SetResolution(dpi, width, height):
  217. """!If resolution is too high, lower it
  218. @param dpi max DPI
  219. @param width map frame width
  220. @param height map frame height
  221. """
  222. region = grass.region()
  223. if region['cols'] > width * dpi or region['rows'] > height * dpi:
  224. rows = height * dpi
  225. cols = width * dpi
  226. RunCommand('g.region', rows = rows, cols = cols)
  227. def ComputeSetRegion(self, mapDict):
  228. """!Computes and sets region from current scale, map center coordinates and map rectangle"""
  229. if mapDict['scaleType'] == 3: # fixed scale
  230. scale = mapDict['scale']
  231. if not hasattr(self, 'unitConv'):
  232. self.unitConv = UnitConversion(self)
  233. fromM = 1
  234. if projInfo()['proj'] != 'xy':
  235. fromM = float(projInfo()['meters'])
  236. rectHalfInch = (mapDict['rect'].width/2, mapDict['rect'].height/2)
  237. rectHalfMeter = (self.unitConv.convert(value = rectHalfInch[0], fromUnit = 'inch', toUnit = 'meter')/ fromM /scale,
  238. self.unitConv.convert(value = rectHalfInch[1], fromUnit = 'inch', toUnit = 'meter')/ fromM /scale)
  239. centerE = mapDict['center'][0]
  240. centerN = mapDict['center'][1]
  241. raster = self.instruction.FindInstructionByType('raster')
  242. if raster:
  243. rasterId = raster.id
  244. else:
  245. rasterId = None
  246. if rasterId:
  247. RunCommand('g.region', n = ceil(centerN + rectHalfMeter[1]),
  248. s = floor(centerN - rectHalfMeter[1]),
  249. e = ceil(centerE + rectHalfMeter[0]),
  250. w = floor(centerE - rectHalfMeter[0]),
  251. rast = self.instruction[rasterId]['raster'])
  252. else:
  253. RunCommand('g.region', n = ceil(centerN + rectHalfMeter[1]),
  254. s = floor(centerN - rectHalfMeter[1]),
  255. e = ceil(centerE + rectHalfMeter[0]),
  256. w = floor(centerE - rectHalfMeter[0]))
  257. def projInfo():
  258. """!Return region projection and map units information,
  259. taken from render.py"""
  260. projinfo = dict()
  261. ret = RunCommand('g.proj', read = True, flags = 'p')
  262. if not ret:
  263. return projinfo
  264. for line in ret.splitlines():
  265. if ':' in line:
  266. key, val = line.split(':')
  267. projinfo[key.strip()] = val.strip()
  268. elif "XY location (unprojected)" in line:
  269. projinfo['proj'] = 'xy'
  270. projinfo['units'] = ''
  271. break
  272. return projinfo
  273. def GetMapBounds(filename, portrait = True):
  274. """!Run ps.map -b to get information about map bounding box
  275. @param filename psmap input file
  276. @param portrait page orientation"""
  277. orient = ''
  278. if not portrait:
  279. orient = 'r'
  280. try:
  281. bb = map(float, grass.read_command('ps.map',
  282. flags = 'b' + orient,
  283. quiet = True,
  284. input = filename).strip().split('=')[1].split(','))
  285. except (grass.ScriptError, IndexError):
  286. GError(message = _("Unable to run `ps.map -b`"))
  287. return None
  288. return Rect2D(bb[0], bb[3], bb[2] - bb[0], bb[1] - bb[3])
  289. def getRasterType(map):
  290. """!Returns type of raster map (CELL, FCELL, DCELL)"""
  291. if map is None:
  292. map = ''
  293. file = grass.find_file(name = map, element = 'cell')
  294. if file['file']:
  295. rasterType = grass.raster_info(map)['datatype']
  296. return rasterType
  297. else:
  298. return None
  299. def PilImageToWxImage(pilImage, copyAlpha = True):
  300. """!Convert PIL image to wx.Image
  301. Based on http://wiki.wxpython.org/WorkingWithImages
  302. """
  303. hasAlpha = pilImage.mode[-1] == 'A'
  304. if copyAlpha and hasAlpha : # Make sure there is an alpha layer copy.
  305. wxImage = wx.EmptyImage( *pilImage.size )
  306. pilImageCopyRGBA = pilImage.copy()
  307. pilImageCopyRGB = pilImageCopyRGBA.convert('RGB') # RGBA --> RGB
  308. pilImageRgbData = pilImageCopyRGB.tostring()
  309. wxImage.SetData(pilImageRgbData)
  310. wxImage.SetAlphaData(pilImageCopyRGBA.tostring()[3::4]) # Create layer and insert alpha values.
  311. else : # The resulting image will not have alpha.
  312. wxImage = wx.EmptyImage(*pilImage.size)
  313. pilImageCopy = pilImage.copy()
  314. pilImageCopyRGB = pilImageCopy.convert('RGB') # Discard any alpha from the PIL image.
  315. pilImageRgbData = pilImageCopyRGB.tostring()
  316. wxImage.SetData(pilImageRgbData)
  317. return wxImage
  318. def BBoxAfterRotation(w, h, angle):
  319. """!Compute bounding box or rotated rectangle
  320. @param w rectangle width
  321. @param h rectangle height
  322. @param angle angle (0, 360) in degrees
  323. """
  324. angleRad = angle / 180. * pi
  325. ct = cos(angleRad)
  326. st = sin(angleRad)
  327. hct = h * ct
  328. wct = w * ct
  329. hst = h * st
  330. wst = w * st
  331. y = x = 0
  332. if 0 < angle <= 90:
  333. y_min = y
  334. y_max = y + hct + wst
  335. x_min = x - hst
  336. x_max = x + wct
  337. elif 90 < angle <= 180:
  338. y_min = y + hct
  339. y_max = y + wst
  340. x_min = x - hst + wct
  341. x_max = x
  342. elif 180 < angle <= 270:
  343. y_min = y + wst + hct
  344. y_max = y
  345. x_min = x + wct
  346. x_max = x - hst
  347. elif 270 < angle <= 360:
  348. y_min = y + wst
  349. y_max = y + hct
  350. x_min = x
  351. x_max = x + wct - hst
  352. width = int(ceil(abs(x_max) + abs(x_min)))
  353. height = int(ceil(abs(y_max) + abs(y_min)))
  354. return width, height
  355. # hack for Windows, loading EPS works only on Unix
  356. # these functions are taken from EpsImagePlugin.py
  357. def loadPSForWindows(self):
  358. # Load EPS via Ghostscript
  359. if not self.tile:
  360. return
  361. self.im = GhostscriptForWindows(self.tile, self.size, self.fp)
  362. self.mode = self.im.mode
  363. self.size = self.im.size
  364. self.tile = []
  365. def GhostscriptForWindows(tile, size, fp):
  366. """Render an image using Ghostscript (Windows only)"""
  367. # Unpack decoder tile
  368. decoder, tile, offset, data = tile[0]
  369. length, bbox = data
  370. import tempfile, os
  371. file = tempfile.mkstemp()[1]
  372. # Build ghostscript command - for Windows
  373. command = ["gswin32c",
  374. "-q", # quite mode
  375. "-g%dx%d" % size, # set output geometry (pixels)
  376. "-dNOPAUSE -dSAFER", # don't pause between pages, safe mode
  377. "-sDEVICE=ppmraw", # ppm driver
  378. "-sOutputFile=%s" % file # output file
  379. ]
  380. command = string.join(command)
  381. # push data through ghostscript
  382. try:
  383. gs = os.popen(command, "w")
  384. # adjust for image origin
  385. if bbox[0] != 0 or bbox[1] != 0:
  386. gs.write("%d %d translate\n" % (-bbox[0], -bbox[1]))
  387. fp.seek(offset)
  388. while length > 0:
  389. s = fp.read(8192)
  390. if not s:
  391. break
  392. length = length - len(s)
  393. gs.write(s)
  394. status = gs.close()
  395. if status:
  396. raise IOError("gs failed (status %d)" % status)
  397. im = PILImage.core.open_ppm(file)
  398. finally:
  399. try: os.unlink(file)
  400. except: pass
  401. return im