utils.py 15 KB

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