utils.py 16 KB

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