georect.py 61 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736
  1. """
  2. @package georect.py
  3. @brief Georectification module for GRASS GIS. Includes ground control
  4. point management and interactive point and click GCP creation
  5. Classes:
  6. - GeorectWizard
  7. - LocationPage
  8. - GroupPage
  9. - DispMapPage
  10. - GCP
  11. - GCPList
  12. - VectGroup
  13. - EditGCP
  14. - GrSettingsDialog
  15. (C) 2006-2008 by the GRASS Development Team
  16. This program is free software under the GNU General Public License
  17. (>=v2). Read the file COPYING that comes with GRASS for details.
  18. @author Michael Barton
  19. @author Updated by Martin Landa <landa.martin gmail.com>
  20. """
  21. import os
  22. import sys
  23. import tempfile
  24. import shutil
  25. import time
  26. import wx
  27. from wx.lib.mixins.listctrl import CheckListCtrlMixin, ListCtrlAutoWidthMixin, TextEditMixin
  28. import wx.lib.colourselect as csel
  29. import wx.wizard as wiz
  30. from grass.script import all as grass
  31. import globalvar
  32. import mapdisp
  33. import render
  34. import toolbars
  35. import menuform
  36. import gselect
  37. import gcmd
  38. import utils
  39. from debug import Debug as Debug
  40. from icon import Icons as Icons
  41. from location_wizard import TitledPage as TitledPage
  42. from preferences import globalSettings as UserSettings
  43. try:
  44. import subprocess # Not needed if GRASS commands could actually be quiet
  45. except:
  46. CompatPath = globalvar.ETCWXDIR
  47. sys.path.append(CompatPath)
  48. from compat import subprocess
  49. gmpath = os.path.join(globalvar.ETCWXDIR, "icons")
  50. sys.path.append(gmpath)
  51. #
  52. # global variables
  53. #
  54. global xy_map
  55. global maptype
  56. xy_map = ''
  57. maptype = 'cell'
  58. class GeorectWizard(object):
  59. """
  60. Start wizard here and finish wizard here
  61. """
  62. def __init__(self, parent):
  63. self.parent = parent # GMFrame
  64. #
  65. # get environmental variables
  66. #
  67. self.grassdatabase = grass.gisenv()['GISDBASE']
  68. #
  69. # read original environment settings
  70. #
  71. self.orig_gisrc = os.environ['GISRC']
  72. self.gisrc_dict = {}
  73. try:
  74. f = open(self.orig_gisrc, 'r')
  75. for line in f.readlines():
  76. line = line.replace('\n', '').strip()
  77. if len(line) < 1:
  78. continue
  79. key, value = line.split(':', 1)
  80. self.gisrc_dict[key.strip()] = value.strip()
  81. finally:
  82. f.close()
  83. self.currentlocation = self.gisrc_dict['LOCATION_NAME']
  84. self.currentmapset = self.gisrc_dict['MAPSET']
  85. # location for xy map to georectify
  86. self.newlocation = ''
  87. # mapset for xy map to georectify
  88. self.newmapset = ''
  89. # GISRC file for source location/mapset of map(s) to georectify
  90. self.new_gisrc = ''
  91. #
  92. # define wizard pages
  93. #
  94. self.wizard = wiz.Wizard(parent=parent, id=wx.ID_ANY, title=_("Setup for georectification"))
  95. self.startpage = LocationPage(self.wizard, self)
  96. self.grouppage = GroupPage(self.wizard, self)
  97. self.mappage = DispMapPage(self.wizard, self)
  98. #
  99. # set the initial order of the pages
  100. #
  101. self.startpage.SetNext(self.grouppage)
  102. self.grouppage.SetPrev(self.startpage)
  103. self.grouppage.SetNext(self.mappage)
  104. self.mappage.SetPrev(self.grouppage)
  105. #
  106. # do pages layout
  107. #
  108. self.startpage.DoLayout()
  109. self.grouppage.DoLayout()
  110. self.mappage.DoLayout()
  111. self.wizard.FitToPage(self.startpage)
  112. # self.Bind(wx.EVT_CLOSE, self.Cleanup)
  113. # self.parent.Bind(wx.EVT_ACTIVATE, self.OnGLMFocus)
  114. success = False
  115. #
  116. # run wizard
  117. #
  118. if self.wizard.RunWizard(self.startpage):
  119. success = self.OnWizFinished()
  120. if success == False:
  121. wx.MessageBox(parent=self.parent,
  122. message=_("Georectifying setup canceled."),
  123. caption=_("Georectify"),
  124. style=wx.OK | wx.ICON_INFORMATION | wx.CENTRE)
  125. self.Cleanup()
  126. else:
  127. wx.MessageBox(parent=self.parent,
  128. message=_("Georectifying setup canceled."),
  129. caption=_("Georectify"),
  130. style=wx.OK | wx.ICON_INFORMATION | wx.CENTRE)
  131. self.Cleanup()
  132. #
  133. # start display showing xymap
  134. #
  135. if success != False:
  136. # instance of render.Map to be associated with display
  137. self.Map = render.Map(gisrc=self.new_gisrc)
  138. global maptype
  139. global xy_map
  140. #
  141. # add layer to map
  142. #
  143. if maptype == 'cell':
  144. rendertype = 'raster'
  145. cmdlist = ['d.rast', 'map=%s' % xy_map]
  146. else: # -> vector layer
  147. rendertype = 'vector'
  148. cmdlist = ['d.vect', 'map=%s' % xy_map]
  149. self.Map.AddLayer(type=rendertype, command=cmdlist, l_active=True,
  150. name=utils.GetLayerNameFromCmd(cmdlist),
  151. l_hidden=False, l_opacity=1.0, l_render=False)
  152. #
  153. # start GCP form
  154. #
  155. self.gcpmgr = GCP(self.parent, grwiz=self)
  156. self.gcpmgr.Show()
  157. #
  158. # start map display
  159. #
  160. self.xy_mapdisp = mapdisp.MapFrame(self.gcpmgr, title=_("Set ground control points (GCPs)"),
  161. size=globalvar.MAP_WINDOW_SIZE,
  162. toolbars=["georect"],
  163. Map=self.Map, lmgr=self.parent)
  164. self.gcpmgr.SetMapDisplay(self.xy_mapdisp)
  165. self.mapwin = self.xy_mapdisp.MapWindow
  166. # set mouse characteristics
  167. self.mapwin.mouse['box'] = 'point'
  168. self.mapwin.mouse["use"] == "pointer"
  169. self.mapwin.zoomtype = 0
  170. self.mapwin.pen = wx.Pen(colour='black', width=2, style=wx.SOLID)
  171. self.mapwin.SetCursor(self.xy_mapdisp.cursors["cross"])
  172. #
  173. # show new display & draw map
  174. #
  175. self.xy_mapdisp.Show()
  176. else:
  177. self.Cleanup()
  178. def SetSrcEnv(self, location, mapset):
  179. """!Create environment to use for location and mapset
  180. that are the source of the file(s) to georectify
  181. @param location source location
  182. @param mapset source mapset
  183. @return False on error
  184. @return True on success
  185. """
  186. self.newlocation = location
  187. self.newmapset = mapset
  188. # check to see if we are georectifying map in current working location/mapset
  189. if self.newlocation == self.currentlocation and self.newmapset == self.currentmapset:
  190. return False
  191. self.gisrc_dict['LOCATION_NAME'] = location
  192. self.gisrc_dict['MAPSET'] = mapset
  193. self.new_gisrc = utils.GetTempfile()
  194. try:
  195. f = open(self.new_gisrc, mode='w')
  196. for line in self.gisrc_dict.items():
  197. f.write(line[0] + ": " + line[1] + "\n")
  198. finally:
  199. f.close()
  200. return True
  201. def SwitchEnv(self, grc):
  202. """
  203. Switches between original working location/mapset and
  204. location/mapset that is source of file(s) to georectify
  205. """
  206. # check to see if we are georectifying map in current working location/mapset
  207. if self.newlocation == self.currentlocation and self.newmapset == self.currentmapset:
  208. return False
  209. if grc == 'original':
  210. os.environ["GISRC"] = str(self.orig_gisrc)
  211. elif grc == 'new':
  212. os.environ["GISRC"] = str(self.new_gisrc)
  213. return True
  214. def OnWizFinished(self):
  215. # self.Cleanup()
  216. return True
  217. def OnGLMFocus(self, event):
  218. """!Layer Manager focus"""
  219. # self.SwitchEnv('original')
  220. event.Skip()
  221. def Cleanup(self):
  222. """!Return to current location and mapset"""
  223. self.SwitchEnv('original')
  224. self.parent.georectifying = None
  225. if hasattr(self, "xy_mapdisp"):
  226. self.xy_mapdisp.Close()
  227. self.xy_mapdisp = None
  228. self.wizard.Destroy()
  229. class LocationPage(TitledPage):
  230. """
  231. Set map type (raster or vector) to georectify and
  232. select location/mapset of map(s) to georectify.
  233. """
  234. def __init__(self, wizard, parent):
  235. TitledPage.__init__(self, wizard, _("Select map type and location/mapset"))
  236. self.parent = parent
  237. self.grassdatabase = self.parent.grassdatabase
  238. self.xylocation = ''
  239. self.xymapset = ''
  240. tmplist = os.listdir(self.grassdatabase)
  241. self.locList = []
  242. self.mapsetList = []
  243. #
  244. # create a list of valid locations
  245. #
  246. for item in tmplist:
  247. if os.path.isdir(os.path.join(self.grassdatabase, item)) and \
  248. os.path.exists(os.path.join(self.grassdatabase, item, 'PERMANENT')):
  249. self.locList.append(item)
  250. utils.ListSortLower(self.locList)
  251. #
  252. # layout
  253. #
  254. self.sizer.AddGrowableCol(2)
  255. # map type
  256. self.rb_maptype = wx.RadioBox(parent=self, id=wx.ID_ANY,
  257. label=' %s ' % _("Map type to georectify"),
  258. choices=[_('raster'), _('vector')],
  259. majorDimension=wx.RA_SPECIFY_COLS)
  260. self.sizer.Add(item=self.rb_maptype,
  261. flag=wx.ALIGN_CENTER | wx.ALL | wx.EXPAND, border=5,
  262. pos=(1, 1), span=(1, 2))
  263. # location
  264. self.sizer.Add(item=wx.StaticText(parent=self, id=wx.ID_ANY, label=_('Select source location:')),
  265. flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5,
  266. pos=(2, 1))
  267. self.cb_location = wx.ComboBox(parent=self, id=wx.ID_ANY,
  268. choices = self.locList, size=(300, -1),
  269. style=wx.CB_DROPDOWN | wx.CB_READONLY)
  270. self.sizer.Add(item=self.cb_location,
  271. flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5,
  272. pos=(2, 2))
  273. # mapset
  274. self.sizer.Add(item=wx.StaticText(parent=self, id=wx.ID_ANY, label=_('Select source mapset:')),
  275. flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5,
  276. pos=(3, 1))
  277. self.cb_mapset = wx.ComboBox(parent=self, id=wx.ID_ANY,
  278. choices = self.mapsetList, size=(300, -1),
  279. style=wx.CB_DROPDOWN | wx.CB_READONLY)
  280. self.sizer.Add(item=self.cb_mapset,
  281. flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5,
  282. pos=(3,2))
  283. #
  284. # bindings
  285. #
  286. self.Bind(wx.EVT_RADIOBOX, self.OnMaptype, self.rb_maptype)
  287. self.Bind(wx.EVT_COMBOBOX, self.OnLocation, self.cb_location)
  288. self.Bind(wx.EVT_COMBOBOX, self.OnMapset, self.cb_mapset)
  289. self.Bind(wiz.EVT_WIZARD_PAGE_CHANGING, self.OnPageChanging)
  290. self.Bind(wiz.EVT_WIZARD_PAGE_CHANGED, self.OnEnterPage)
  291. # self.Bind(wx.EVT_CLOSE, self.parent.Cleanup)
  292. def OnMaptype(self,event):
  293. """!Change map type"""
  294. global maptype
  295. if event.GetInt() == 0:
  296. maptype = 'cell'
  297. else:
  298. maptype = 'vector'
  299. def OnLocation(self, event):
  300. """!Sets source location for map(s) to georectify"""
  301. self.xylocation = event.GetString()
  302. #create a list of valid mapsets
  303. tmplist = os.listdir(os.path.join(self.grassdatabase, self.xylocation))
  304. self.mapsetList = []
  305. for item in tmplist:
  306. if os.path.isdir(os.path.join(self.grassdatabase, self.xylocation, item)) and \
  307. os.path.exists(os.path.join(self.grassdatabase, self.xylocation, item, 'WIND')):
  308. if item != 'PERMANENT':
  309. self.mapsetList.append(item)
  310. self.xymapset = 'PERMANENT'
  311. utils.ListSortLower(self.mapsetList)
  312. self.mapsetList.insert(0, 'PERMANENT')
  313. self.cb_mapset.SetItems(self.mapsetList)
  314. self.cb_mapset.SetStringSelection(self.xymapset)
  315. if not wx.FindWindowById(wx.ID_FORWARD).IsEnabled():
  316. wx.FindWindowById(wx.ID_FORWARD).Enable(True)
  317. def OnMapset(self, event):
  318. """!Sets source mapset for map(s) to georectify"""
  319. if self.xylocation == '':
  320. wx.MessageBox(_('You must select a valid location before selecting a mapset'))
  321. return
  322. self.xymapset = event.GetString()
  323. if not wx.FindWindowById(wx.ID_FORWARD).IsEnabled():
  324. wx.FindWindowById(wx.ID_FORWARD).Enable(True)
  325. def OnPageChanging(self, event=None):
  326. if event.GetDirection() and \
  327. (self.xylocation == '' or self.xymapset == ''):
  328. wx.MessageBox(_('You must select a valid location and mapset in order to continue'))
  329. event.Veto()
  330. return
  331. self.parent.SetSrcEnv(self.xylocation, self.xymapset)
  332. def OnEnterPage(self, event=None):
  333. if self.xylocation == '' or self.xymapset == '':
  334. wx.FindWindowById(wx.ID_FORWARD).Enable(False)
  335. else:
  336. wx.FindWindowById(wx.ID_FORWARD).Enable(True)
  337. class GroupPage(TitledPage):
  338. """
  339. Set group to georectify. Create group if desired.
  340. """
  341. def __init__(self, wizard, parent):
  342. TitledPage.__init__(self, wizard, _("Select image/map group to georectify"))
  343. self.parent = parent
  344. self.grassdatabase = self.parent.grassdatabase
  345. self.groupList = []
  346. self.xylocation = ''
  347. self.xymapset = ''
  348. self.xygroup = ''
  349. # default extension
  350. self.extension = 'georect' + str(os.getpid())
  351. #
  352. # layout
  353. #
  354. self.sizer.AddGrowableCol(2)
  355. # group
  356. self.sizer.Add(item=wx.StaticText(parent=self, id=wx.ID_ANY, label=_('Select group:')),
  357. flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5,
  358. pos=(1, 1))
  359. self.cb_group = wx.ComboBox(parent=self, id=wx.ID_ANY,
  360. choices=self.groupList, size=(350, -1),
  361. style=wx.CB_DROPDOWN | wx.CB_READONLY)
  362. self.sizer.Add(item=self.cb_group,
  363. flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5,
  364. pos=(1, 2))
  365. # create group
  366. self.sizer.Add(item=wx.StaticText(parent=self, id=wx.ID_ANY, label=_('Create group if none exists')),
  367. flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5,
  368. pos=(2, 1))
  369. btnSizer = wx.BoxSizer(wx.HORIZONTAL)
  370. self.btn_mkgroup = wx.Button(parent=self, id=wx.ID_ANY, label=_("Create/edit group..."))
  371. self.btn_vgroup = wx.Button(parent=self, id=wx.ID_ANY, label=_("Add vector map to group..."))
  372. self.btn_vgroup.Hide()
  373. btnSizer.Add(item=self.btn_mkgroup,
  374. flag=wx.RIGHT, border=5)
  375. btnSizer.Add(item=self.btn_vgroup,
  376. flag=wx.LEFT, border=5)
  377. self.sizer.Add(item=btnSizer,
  378. flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5,
  379. pos=(2, 2))
  380. # extension
  381. self.sizer.Add(item=wx.StaticText(parent=self, id=wx.ID_ANY, label=_('Extension for output maps:')),
  382. flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5,
  383. pos=(3, 1))
  384. self.ext_txt = wx.TextCtrl(parent=self, id=wx.ID_ANY, value="", size=(350,-1))
  385. self.ext_txt.SetValue(self.extension)
  386. self.sizer.Add(item=self.ext_txt,
  387. flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5,
  388. pos=(3, 2))
  389. #
  390. # bindings
  391. #
  392. self.Bind(wx.EVT_COMBOBOX, self.OnGroup, self.cb_group)
  393. self.Bind(wx.EVT_TEXT, self.OnExtension, self.ext_txt)
  394. self.Bind(wiz.EVT_WIZARD_PAGE_CHANGING, self.OnPageChanging)
  395. self.Bind(wiz.EVT_WIZARD_PAGE_CHANGED, self.OnEnterPage)
  396. self.Bind(wx.EVT_CLOSE, self.parent.Cleanup)
  397. def OnGroup(self, event):
  398. self.xygroup = event.GetString()
  399. def OnMkGroup(self, event):
  400. """!Create new group in source location/mapset"""
  401. menuform.GUI().ParseCommand(['i.group'],
  402. completed=(self.GetOptData, None, ''),
  403. parentframe=self.parent.parent, modal=True)
  404. def OnVGroup(self, event):
  405. """!Add vector maps to group"""
  406. dlg = VectGroup(parent = self,
  407. id = wx.ID_ANY,
  408. grassdb = self.grassdatabase,
  409. location = self.xylocation,
  410. mapset = self.xymapset,
  411. group = self.xygroup)
  412. if dlg.ShowModal() != wx.ID_OK:
  413. return
  414. dlg.MakeVGroup()
  415. self.OnEnterPage()
  416. def GetOptData(self, dcmd, layer, params, propwin):
  417. """!Process i.group"""
  418. # update the page
  419. if dcmd:
  420. gcmd.RunCommand(utils.CmdToTuple(dcmd))
  421. self.OnEnterPage()
  422. self.Update()
  423. def OnExtension(self, event):
  424. self.extension = event.GetString()
  425. def OnPageChanging(self, event=None):
  426. if event.GetDirection() and self.xygroup == '':
  427. wx.MessageBox(_('You must select a valid image/map group in order to continue'))
  428. event.Veto()
  429. return
  430. if event.GetDirection() and self.extension == '':
  431. wx.MessageBox(_('You must enter an map name extension in order to continue'))
  432. event.Veto()
  433. return
  434. def OnEnterPage(self, event=None):
  435. global maptype
  436. self.groupList = []
  437. self.xylocation = self.parent.gisrc_dict['LOCATION_NAME']
  438. self.xymapset = self.parent.gisrc_dict['MAPSET']
  439. # create a list of groups in selected mapset
  440. if os.path.isdir(os.path.join(self.grassdatabase,
  441. self.xylocation,
  442. self.xymapset,
  443. 'group')):
  444. tmplist = os.listdir(os.path.join(self.grassdatabase,
  445. self.xylocation,
  446. self.xymapset,
  447. 'group'))
  448. for item in tmplist:
  449. if os.path.isdir(os.path.join(self.grassdatabase,
  450. self.xylocation,
  451. self.xymapset,
  452. 'group',
  453. item)):
  454. self.groupList.append(item)
  455. if maptype == 'cell':
  456. self.btn_vgroup.Hide()
  457. self.Bind(wx.EVT_BUTTON, self.OnMkGroup, self.btn_mkgroup)
  458. elif maptype == 'vector':
  459. self.btn_vgroup.Show()
  460. self.Bind(wx.EVT_BUTTON, self.OnMkGroup, self.btn_mkgroup)
  461. self.Bind(wx.EVT_BUTTON, self.OnVGroup, self.btn_vgroup)
  462. utils.ListSortLower(self.groupList)
  463. self.cb_group.SetItems(self.groupList)
  464. if len(self.groupList) > 0 and \
  465. self.xygroup == '':
  466. self.cb_group.SetSelection(0)
  467. self.xygroup = self.groupList[0]
  468. if self.xygroup == '' or \
  469. self.extension == '':
  470. wx.FindWindowById(wx.ID_FORWARD).Enable(False)
  471. else:
  472. wx.FindWindowById(wx.ID_FORWARD).Enable(True)
  473. # switch to source
  474. self.parent.SwitchEnv('new')
  475. class DispMapPage(TitledPage):
  476. """
  477. Select ungeoreferenced map to display for interactively
  478. setting ground control points (GCPs).
  479. """
  480. def __init__(self, wizard, parent):
  481. TitledPage.__init__(self, wizard,
  482. _("Select image/map to display for ground control point (GCP) creation"))
  483. self.parent = parent
  484. global maptype
  485. #
  486. # layout
  487. #
  488. self.sizer.Add(item=wx.StaticText(parent=self, id=wx.ID_ANY, label=_('Select display image/map:')),
  489. flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5,
  490. pos=(1, 1))
  491. self.selection = gselect.Select(self, id=wx.ID_ANY,
  492. size=globalvar.DIALOG_GSELECT_SIZE)
  493. self.sizer.Add(item=self.selection,
  494. flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5,
  495. pos=(1, 2))
  496. #
  497. # bindings
  498. #
  499. self.selection.Bind(wx.EVT_TEXT, self.OnSelection)
  500. self.Bind(wiz.EVT_WIZARD_PAGE_CHANGING, self.OnPageChanging)
  501. self.Bind(wiz.EVT_WIZARD_PAGE_CHANGED, self.OnEnterPage)
  502. self.Bind(wx.EVT_CLOSE, self.parent.Cleanup)
  503. def OnSelection(self,event):
  504. """!Map to display selected"""
  505. global xy_map
  506. xy_map = event.GetString()
  507. if xy_map == '':
  508. wx.FindWindowById(wx.ID_FORWARD).Enable(False)
  509. else:
  510. wx.FindWindowById(wx.ID_FORWARD).Enable(True)
  511. def OnPageChanging(self, event=None):
  512. global xy_map
  513. if event.GetDirection() and xy_map == '':
  514. wx.MessageBox(_('You must select a valid image/map in order to continue'))
  515. event.Veto()
  516. return
  517. self.parent.SwitchEnv('original')
  518. def OnEnterPage(self, event=None):
  519. global maptype
  520. global xy_map
  521. self.selection.SetElementList(maptype,
  522. mapsets = [self.parent.newmapset, ])
  523. if xy_map == '':
  524. wx.FindWindowById(wx.ID_FORWARD).Enable(False)
  525. else:
  526. wx.FindWindowById(wx.ID_FORWARD).Enable(True)
  527. class GCP(wx.Frame):
  528. """
  529. Manages ground control points for georectifying. Calculates RMS statics.
  530. Calls i.rectify or v.transform to georectify map.
  531. """
  532. def __init__(self, parent, grwiz, mapdisp=None, id=wx.ID_ANY,
  533. title=_("Create & manage ground control points"),
  534. size=wx.DefaultSize):
  535. wx.Frame.__init__(self, parent, id, title, size=(625, 300))
  536. self.SetIcon(wx.Icon(os.path.join(globalvar.ETCICONDIR, 'grass_map.ico'), wx.BITMAP_TYPE_ICO))
  537. #
  538. # init variables
  539. #
  540. self.parent = parent # GMFrame
  541. self.parent.georectifying = self
  542. self.mapdisp = mapdisp # XY-location Map Display
  543. self.grwiz = grwiz # GR Wizard
  544. self.grassdatabase = self.grwiz.grassdatabase
  545. self.currentlocation = self.grwiz.currentlocation
  546. self.currentmapset = self.grwiz.currentmapset
  547. self.newlocation = self.grwiz.newlocation
  548. self.newmapset = self.grwiz.newmapset
  549. self.xylocation = self.grwiz.gisrc_dict['LOCATION_NAME']
  550. self.xymapset = self.grwiz.gisrc_dict['MAPSET']
  551. self.xygroup = self.grwiz.grouppage.xygroup
  552. self.extension = self.grwiz.grouppage.extension
  553. self.file = {
  554. 'points' : os.path.join(self.grassdatabase,
  555. self.xylocation,
  556. self.xymapset,
  557. 'group',
  558. self.xygroup,
  559. 'POINTS'),
  560. 'rgrp' : os.path.join(self.grassdatabase,
  561. self.xylocation,
  562. self.xymapset,
  563. 'group',
  564. self.xygroup,
  565. 'REF'),
  566. 'vgrp' : os.path.join(self.grassdatabase,
  567. self.xylocation,
  568. self.xymapset,
  569. 'group',
  570. self.xygroup,
  571. 'VREF'),
  572. 'target' : os.path.join(self.grassdatabase,
  573. self.xylocation,
  574. self.xymapset,
  575. 'group',
  576. self.xygroup,
  577. 'TARGET'),
  578. }
  579. # polynomial order transformation for georectification
  580. self.gr_order = 1
  581. # number of GCPs selected to be used for georectification (checked)
  582. self.GCPcount = 0
  583. # forward RMS error
  584. self.fwd_rmserror = 0.0
  585. # backward RMS error
  586. self.bkw_rmserror = 0.0
  587. # list map coords and ID of map display they came from
  588. self.mapcoordlist = []
  589. self.SetTarget(self.xygroup, self.currentlocation, self.currentmapset)
  590. #
  591. # toolbar and display for xy map
  592. #
  593. self.toolbar = toolbars.GCPToolbar(parent=self, tbframe=self).GetToolbar()
  594. self.SetToolBar(self.toolbar)
  595. self.SetMapDisplay(self.mapdisp)
  596. #
  597. # statusbar
  598. #
  599. self.CreateStatusBar(number=1)
  600. # can put guage into custom statusbar for progress if can figure out how to get progress text from i.rectify
  601. # self.gr_gauge = wx.Gauge(self, -1, 100, (-1,-1), (100, 25))
  602. # self.gr_guage.Pulse()
  603. panel = wx.Panel(parent=self)
  604. #
  605. # do layout
  606. #
  607. sizer = wx.BoxSizer(wx.VERTICAL)
  608. self.rb_grmethod = wx.RadioBox(parent=panel, id=wx.ID_ANY,
  609. label=" %s " % _("Select rectification method for rasters"),
  610. choices=[_('1st order'), _('2nd order'), _('3rd order')],
  611. majorDimension=wx.RA_SPECIFY_COLS)
  612. sizer.Add(item=self.rb_grmethod, proportion=0,
  613. flag=wx.EXPAND | wx.ALL, border=5)
  614. self.clip_to_region = wx.CheckBox(parent=panel, id=wx.ID_ANY,
  615. label=_("clip to computational region in target location"))
  616. sizer.Add(item=self.clip_to_region, proportion=0,
  617. flag=wx.EXPAND | wx.ALL, border=5)
  618. box = wx.StaticBox (parent=panel, id=wx.ID_ANY,
  619. label=" %s " % _("Ground Control Points"))
  620. boxSizer = wx.StaticBoxSizer(box, wx.VERTICAL)
  621. # initialize list control for GCP management
  622. self.list = GCPList(parent=panel, gcp=self)
  623. boxSizer.Add(item=self.list, proportion=1,
  624. flag=wx.EXPAND | wx.ALL, border=3)
  625. sizer.Add(item=boxSizer, proportion=1,
  626. flag=wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM, border=5)
  627. #
  628. # bindigs
  629. #
  630. self.Bind(wx.EVT_RADIOBOX, self.OnGRMethod, self.rb_grmethod)
  631. self.Bind(wx.EVT_ACTIVATE, self.OnFocus)
  632. self.Bind(wx.EVT_CLOSE, self.OnQuit)
  633. panel.SetSizer(sizer)
  634. # sizer.Fit(self)
  635. def __del__(self):
  636. """!Disable georectification mode"""
  637. self.parent.georectifying = None
  638. def SetMapDisplay(self, win):
  639. self.mapdisp = win
  640. if self.mapdisp:
  641. self.list.LoadData()
  642. def SetTarget(self, tgroup, tlocation, tmapset):
  643. """
  644. Sets rectification target to current location and mapset
  645. """
  646. # check to see if we are georectifying map in current working location/mapset
  647. if self.newlocation == self.currentlocation and self.newmapset == self.currentmapset:
  648. gcmd.RunCommand('i.target',
  649. parent = self,
  650. flags = 'c',
  651. group = tgroup)
  652. else:
  653. self.grwiz.SwitchEnv('new')
  654. gcmd.RunCommand('i.target',
  655. parent = self,
  656. group = tgroup,
  657. location = tlocation,
  658. mapset = tmapset)
  659. self.grwiz.SwitchEnv('original')
  660. def AddGCP(self, event):
  661. """
  662. Appends an item to GCP list
  663. """
  664. self.list.AddGCPItem()
  665. # x, y, MapWindow instance
  666. self.mapcoordlist.append({ 'gcpcoord' : (0.0, 0.0, None),
  667. 'mapcoord' : (0.0, 0.0, None) })
  668. def DeleteGCP(self, event):
  669. """
  670. Deletes selected item in GCP list
  671. """
  672. minNumOfItems = self.OnGRMethod(None)
  673. if self.list.GetItemCount() <= minNumOfItems:
  674. wx.MessageBox(parent=self, message=_("At least %d GCPs required. Operation cancelled.") % minNumOfItems,
  675. caption=_("Delete GCP"), style=wx.OK | wx.ICON_INFORMATION)
  676. return
  677. item = self.list.DeleteGCPItem()
  678. del self.mapcoordlist[item]
  679. def ClearGCP(self, event):
  680. """
  681. Clears all values in selected item of GCP list and unchecks it
  682. """
  683. index = self.list.GetSelected()
  684. for i in range(4):
  685. self.list.SetStringItem(index, i, '0.0')
  686. self.list.SetStringItem(index, 4, '')
  687. self.list.SetStringItem(index, 5, '')
  688. self.list.CheckItem(index, False)
  689. self.mapcoordlist[index] = { 'gcpcoord' : (0.0, 0.0, None),
  690. 'mapcoord' : (0.0, 0.0, None) }
  691. def DrawGCP(self, coordtype):
  692. """
  693. Updates GCP and map coord maps and redraws
  694. active (checked) GCP markers
  695. """
  696. col = UserSettings.Get(group='georect', key='symbol', subkey='color')
  697. wxCol = wx.Colour(col[0], col[1], col[2], 255)
  698. wpx = UserSettings.Get(group='georect', key='symbol', subkey='width')
  699. font = self.GetFont()
  700. idx = 0
  701. for gcp in self.mapcoordlist:
  702. mapWin = gcp[coordtype][2]
  703. if not self.list.IsChecked(idx) or not mapWin:
  704. idx += 1
  705. continue
  706. mapWin.pen = wx.Pen(colour=wxCol, width=wpx, style=wx.SOLID)
  707. mapWin.polypen = wx.Pen(colour=wxCol, width=wpx, style=wx.SOLID) # ?
  708. coord = mapWin.Cell2Pixel((gcp[coordtype][0], gcp[coordtype][1]))
  709. mapWin.DrawCross(pdc=mapWin.pdcTmp, coords=coord,
  710. size=5, text={ 'text' : '%s' % str(idx + 1),
  711. 'active' : True,
  712. 'font' : font,
  713. 'color': wxCol,
  714. 'coords': [coord[0] + 5,
  715. coord[1] + 5,
  716. 5,
  717. 5]})
  718. idx += 1
  719. def SetGCPData(self, coordtype, coord, mapdisp=None, check=True):
  720. """
  721. Inserts coordinates from mouse click on map
  722. into selected item of GCP list and checks it for use
  723. """
  724. index = self.list.GetSelected()
  725. if index == wx.NOT_FOUND:
  726. return
  727. coord0 = str(coord[0])
  728. coord1 = str(coord[1])
  729. if coordtype == 'gcpcoord':
  730. self.list.SetStringItem(index, 0, coord0)
  731. self.list.SetStringItem(index, 1, coord1)
  732. self.mapcoordlist[index]['gcpcoord'] = (coord[0], coord[1], mapdisp)
  733. elif coordtype == 'mapcoord':
  734. self.list.SetStringItem(index, 2, coord0)
  735. self.list.SetStringItem(index, 3, coord1)
  736. self.mapcoordlist[index][coordtype] = (coord[0], coord[1], mapdisp)
  737. self.list.CheckItem(index, check)
  738. # self.list.ResizeColumns()
  739. def SaveGCPs(self, event):
  740. """
  741. Make a POINTS file or save GCP coordinates to existing POINTS file
  742. """
  743. self.GCPcount = 0
  744. try:
  745. f = open(self.file['points'], mode='w')
  746. # use os.linesep or '\n' here ???
  747. f.write('# Ground Control Points File\n')
  748. f.write("# \n")
  749. f.write("# target location: " + self.currentlocation + '\n')
  750. f.write("# target mapset: " + self.currentmapset + '\n')
  751. f.write("#unrectified xy georectified east north 1=use gcp point\n")
  752. f.write("#-------------- ----------------------- ---------------\n")
  753. for index in range(self.list.GetItemCount()):
  754. if self.list.IsChecked(index) == True:
  755. check = "1"
  756. self.GCPcount += 1
  757. else:
  758. check = "0"
  759. coord0 = self.list.GetItem(index, 0).GetText()
  760. coord1 = self.list.GetItem(index, 1).GetText()
  761. coord2 = self.list.GetItem(index, 2).GetText()
  762. coord3 = self.list.GetItem(index, 3).GetText()
  763. f.write(coord0 + ' ' + coord1 + ' ' + coord2 + ' ' + coord3 + ' ' + check + '\n')
  764. self.parent.goutput.WriteLog(_('POINTS file <%s> saved') % self.file['points'])
  765. self.SetStatusText(_('POINTS file saved'))
  766. except IOError, err:
  767. wx.MessageBox(parent=self,
  768. message="%s <%s>. %s%s" % (_("Writing POINTS file failed"),
  769. self.file['points'], os.linesep, err),
  770. caption=_("Error"), style=wx.OK | wx.ICON_ERROR | wx.CENTRE)
  771. return
  772. f.close()
  773. def ReadGCPs(self):
  774. """
  775. Reads GCPs and georectified coordinates from POINTS file
  776. """
  777. self.GCPcount = 0
  778. sourceMapWin = self.mapdisp.MapWindow
  779. targetMapWin = self.parent.curr_page.maptree.mapdisplay.MapWindow
  780. try:
  781. f = open(self.file['points'], 'r')
  782. GCPcnt = 0
  783. for line in f.readlines():
  784. if line[0] == '#' or line =='':
  785. continue
  786. line = line.replace('\n', '').strip()
  787. coords = map(float, line.split())
  788. if coords[4] == 1:
  789. check = True
  790. self.GCPcount +=1
  791. else:
  792. check = False
  793. index = self.AddGCP(event=None)
  794. self.SetGCPData('gcpcoord', (coords[0], coords[1]), sourceMapWin, check)
  795. self.SetGCPData('mapcoord', (coords[2], coords[3]), targetMapWin, check)
  796. except IOError, err:
  797. wx.MessageBox(parent=self,
  798. message="%s <%s>. %s%s" % (_("Reading POINTS file failed"),
  799. self.file['points'], os.linesep, err),
  800. caption=_("Error"), style=wx.OK | wx.ICON_ERROR | wx.CENTRE)
  801. return
  802. f.close()
  803. #
  804. # draw GCPs (source and target)
  805. #
  806. sourceMapWin.UpdateMap(render=False, renderVector=False)
  807. if targetMapWin:
  808. targetMapWin.UpdateMap(render=False, renderVector=False)
  809. #
  810. # calculate RMS
  811. #
  812. # FIXME auto calculation on load is not working
  813. #if self.CheckGCPcount():
  814. # self.RMSError(self.xygroup, self.gr_order)
  815. def ReloadGCPs(self, event):
  816. """!Reload data from file"""
  817. self.list.LoadData()
  818. def OnFocus(self, event):
  819. # self.grwiz.SwitchEnv('new')
  820. pass
  821. def OnRMS(self, event):
  822. """
  823. RMS button handler
  824. """
  825. self.RMSError(self.xygroup,self.gr_order)
  826. def CheckGCPcount(self, msg=False):
  827. """
  828. Checks to make sure that the minimum number of GCPs have been defined and
  829. are active for the selected transformation order
  830. """
  831. if (self.GCPcount < 3 and self.gr_order == 1) or \
  832. (self.GCPcount < 6 and self.gr_order == 2) or \
  833. (self.GCPcount < 10 and self.gr_order == 3):
  834. if msg:
  835. wx.MessageBox(parent=self,
  836. caption=_("RMS Error"),
  837. message=_('Insufficient points defined and active (checked) '
  838. 'for selected rectification method.\n'
  839. '3+ points needed for 1st order,\n'
  840. '6+ points for 2nd order, and\n'
  841. '10+ points for 3rd order.'),
  842. style=wx.ICON_INFORMATION | wx.ID_OK | wx.CENTRE)
  843. return False
  844. else:
  845. return True
  846. def OnGeorect(self, event):
  847. """
  848. Georectifies map(s) in group using i.rectify or v.transform
  849. """
  850. global maptype
  851. self.SaveGCPs(None)
  852. if self.CheckGCPcount(msg=True) == False:
  853. return
  854. if maptype == 'cell':
  855. self.grwiz.SwitchEnv('new')
  856. cmdlist = ['i.rectify','-a','group=%s' % self.xygroup,
  857. 'extension=%s' % self.extension,'order=%s' % self.gr_order]
  858. if self.clip_to_region:
  859. cmdlist.append('-c')
  860. self.parent.goutput.RunCmd(cmdlist, compReg=False,
  861. switchPage=True)
  862. time.sleep(.1)
  863. self.grwiz.SwitchEnv('original')
  864. elif maptype == 'vector':
  865. # loop through all vectors in VREF
  866. # and move resulting vector to target location
  867. f = open(self.file['vgrp'])
  868. vectlist = []
  869. try:
  870. for vect in f.readlines():
  871. vect = vect.strip('\n')
  872. if len(vect) < 1:
  873. continue
  874. vectlist.append(vect)
  875. finally:
  876. f.close()
  877. for vect in vectlist:
  878. self.grwiz.SwitchEnv('new')
  879. self.outname = vect + '_' + self.extension
  880. self.parent.goutput.WriteLog(text = _('Transforming <%s>...') % vect,
  881. switchPage = True)
  882. xyLayer = []
  883. for layer in grass.vector_db(map = vect).itervalues():
  884. xyLayer.append((layer['driver'],
  885. layer['database'],
  886. layer['table']))
  887. self.parent.goutput.RunCmd(['v.transform',
  888. '--o',
  889. 'input=%s' % vect,
  890. 'output=%s' % self.outname,
  891. 'pointsfile=%s' % self.file['points']],
  892. switchPage = True,
  893. onDone = self.OnGeorectDone)
  894. dbConnect = grass.db_connection()
  895. for layer in xyLayer:
  896. self.parent.goutput.RunCmd(['db.copy',
  897. '--q',
  898. '--o',
  899. 'from_driver=%s' % layer[0],
  900. 'from_database=%s' % layer[1],
  901. 'from_table=%s' % layer[2],
  902. 'to_driver=%s' % dbConnect['driver'],
  903. 'to_database=%s' % dbConnect['database'],
  904. 'to_table=%s' % layer[2] + '_' + self.extension])
  905. def OnGeorectDone(self, **kargs):
  906. """!Print final message"""
  907. global maptype
  908. if maptype == 'cell':
  909. return
  910. returncode = kargs['returncode']
  911. xyvpath = os.path.join(self.grassdatabase,
  912. self.xylocation,
  913. self.xymapset,
  914. 'vector',
  915. self.outname)
  916. vpath = os.path.join(self.grassdatabase,
  917. self.currentlocation,
  918. self.currentmapset,
  919. 'vector',
  920. self.outname)
  921. if os.path.isdir(vpath):
  922. self.parent.goutput.WriteWarning(_('Vector map <%s> already exists. '
  923. 'Change extension name and '
  924. 'georectify again.') % self.outname)
  925. else:
  926. if returncode == 0:
  927. if not os.path.isdir(os.path.join(self.grassdatabase,
  928. self.currentlocation,
  929. self.currentmapset,
  930. 'vector')):
  931. os.mkdir(os.path.join(self.grassdatabase,
  932. self.currentlocation,
  933. self.currentmapset,
  934. 'vector'))
  935. shutil.move(xyvpath, vpath)
  936. self.parent.goutput.WriteCmdLog(_('Vector map <%s> georectified '
  937. 'successfully') % self.outname)
  938. # copy attributes
  939. self.parent.goutput.WriteLog(_('Copying attributes...'))
  940. else:
  941. self.parent.goutput.WriteError(_('Georectification of vector map <%s> failed') %
  942. self.outname)
  943. del self.outname
  944. self.grwiz.SwitchEnv('original')
  945. def OnSettings(self, event):
  946. """!Georectifier settings"""
  947. dlg = GrSettingsDialog(parent=self, id=wx.ID_ANY, title=_('Georectifier settings'))
  948. if dlg.ShowModal() == wx.ID_OK:
  949. pass
  950. dlg.Destroy()
  951. def OnQuit(self, event):
  952. """!Quit georectifier"""
  953. self.grwiz.Cleanup()
  954. self.Destroy()
  955. event.Skip()
  956. def OnGRMethod(self, event):
  957. """
  958. sets transformation order for georectifying
  959. """
  960. if event:
  961. self.gr_order = event.GetInt() + 1
  962. numOfItems = self.list.GetItemCount()
  963. minNumOfItems = numOfItems
  964. if self.gr_order == 1:
  965. minNumOfItems = 3
  966. # self.SetStatusText(_('Insufficient points, 3+ points needed for 1st order'))
  967. elif self.gr_order == 2:
  968. minNumOfItems = 6
  969. diff = 6 - numOfItems
  970. # self.SetStatusText(_('Insufficient points, 6+ points needed for 2nd order'))
  971. elif self.gr_order == 3:
  972. minNumOfItems = 10
  973. # self.SetStatusText(_('Insufficient points, 10+ points needed for 3rd order'))
  974. for i in range(minNumOfItems - numOfItems):
  975. self.AddGCP(None)
  976. return minNumOfItems
  977. def RMSError(self, xygroup, order):
  978. """
  979. Uses g.transform to calculate forward and backward error for each used GCP
  980. in POINTS file and insert error values into GCP list.
  981. Calculates total forward and backward RMS error for all used points
  982. """
  983. # save GCPs to points file to make sure that all checked GCPs are used
  984. self.SaveGCPs(None)
  985. if self.CheckGCPcount(msg=True) == False:
  986. return
  987. # get list of forward and reverse rms error values for each point
  988. self.grwiz.SwitchEnv('new')
  989. ret = gcmd.RunCommand('g.transform',
  990. parent = self,
  991. read = True,
  992. group = xygroup,
  993. order = order)
  994. self.grwiz.SwitchEnv('original')
  995. if ret:
  996. errlist = ret.splitlines()
  997. if errlist == []:
  998. return
  999. # insert error values into GCP list for checked items
  1000. i = 0
  1001. sumsq_fwd_err = 0.0
  1002. sumsq_bkw_err = 0.0
  1003. for index in range(self.list.GetItemCount()):
  1004. if self.list.IsChecked(index):
  1005. fwd_err, bkw_err = errlist[i].split()
  1006. self.list.SetStringItem(index, 4, fwd_err)
  1007. self.list.SetStringItem(index, 5, bkw_err)
  1008. sumsq_fwd_err += float(fwd_err)**2
  1009. sumsq_bkw_err += float(bkw_err)**2
  1010. i += 1
  1011. else:
  1012. self.list.SetStringItem(index, 4, '')
  1013. self.list.SetStringItem(index, 5, '')
  1014. # calculate RMS error
  1015. self.fwd_rmserror = round((sumsq_fwd_err/i)**0.5,4)
  1016. self.bkw_rmserror = round((sumsq_bkw_err/i)**0.5,4)
  1017. self.list.ResizeColumns()
  1018. self.SetStatusText(_('RMS error for selected points forward: %(fwd)s backward: %(bkw)s') % \
  1019. { 'fwd' : self.fwd_rmserror, 'bkw' : self.bkw_rmserror })
  1020. class GCPList(wx.ListCtrl,
  1021. CheckListCtrlMixin,
  1022. ListCtrlAutoWidthMixin):
  1023. def __init__(self, parent, gcp, id=wx.ID_ANY,
  1024. pos=wx.DefaultPosition, size=wx.DefaultSize,
  1025. style=wx.LC_REPORT | wx.SUNKEN_BORDER | wx.LC_HRULES |
  1026. wx.LC_SINGLE_SEL):
  1027. wx.ListCtrl.__init__(self, parent, id, pos, size, style)
  1028. # Mixin settings
  1029. CheckListCtrlMixin.__init__(self)
  1030. ListCtrlAutoWidthMixin.__init__(self)
  1031. # TextEditMixin.__init__(self)
  1032. self.gcp = gcp # GCP class
  1033. # tracks whether list items are checked or not
  1034. self.CheckList = []
  1035. self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnItemSelected)
  1036. self.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.OnItemActivated)
  1037. self._Create()
  1038. self.selected = wx.NOT_FOUND
  1039. def _Create(self):
  1040. idx_col = 0
  1041. for col in (_('use| X coord'),
  1042. _('Y coord'),
  1043. _('E coord'),
  1044. _('N coord'),
  1045. _('Forward error'),
  1046. _('Backward error')):
  1047. self.InsertColumn(idx_col, col)
  1048. idx_col += 1
  1049. def LoadData(self):
  1050. """!Load data into list"""
  1051. self.DeleteAllItems()
  1052. if os.path.isfile(self.gcp.file['points']):
  1053. self.gcp.ReadGCPs()
  1054. else:
  1055. # 3 gcp is minimum
  1056. for i in range(3):
  1057. self.gcp.AddGCP(None)
  1058. # select first point by default
  1059. self.selected = 0
  1060. self.SetItemState(self.selected,
  1061. wx.LIST_STATE_SELECTED,
  1062. wx.LIST_STATE_SELECTED)
  1063. self.ResizeColumns()
  1064. def OnCheckItem(self, index, flag):
  1065. """!Item is checked/unchecked"""
  1066. pass
  1067. def AddGCPItem(self):
  1068. """
  1069. Appends an item to GCP list
  1070. """
  1071. self.Append(['0.0',
  1072. '0.0',
  1073. '0.0',
  1074. '0.0',
  1075. '',
  1076. ''])
  1077. self.selected = self.GetItemCount() - 1
  1078. self.SetItemState(self.selected,
  1079. wx.LIST_STATE_SELECTED,
  1080. wx.LIST_STATE_SELECTED)
  1081. self.ResizeColumns()
  1082. return self.selected
  1083. def DeleteGCPItem(self):
  1084. """
  1085. Deletes selected item in GCP list
  1086. """
  1087. if self.selected == wx.NOT_FOUND:
  1088. return
  1089. self.DeleteItem(self.selected)
  1090. if self.GetItemCount() > 0:
  1091. self.selected = self.GetItemCount() - 1
  1092. self.SetItemState(self.selected,
  1093. wx.LIST_STATE_SELECTED,
  1094. wx.LIST_STATE_SELECTED)
  1095. else:
  1096. self.selected = wx.NOT_FOUND
  1097. return self.selected
  1098. def ResizeColumns(self):
  1099. """!Resize columns"""
  1100. minWidth = 90
  1101. for i in range(self.GetColumnCount()):
  1102. self.SetColumnWidth(i, wx.LIST_AUTOSIZE)
  1103. if self.GetColumnWidth(i) < minWidth:
  1104. self.SetColumnWidth(i, minWidth)
  1105. self.SendSizeEvent()
  1106. def GetSelected(self):
  1107. """!Get index of selected item"""
  1108. return self.selected
  1109. def OnItemSelected(self, event):
  1110. self.selected = event.GetIndex()
  1111. def OnItemActivated(self, event):
  1112. """
  1113. When item double clicked, open editor to update coordinate values
  1114. """
  1115. coords = []
  1116. index = event.GetIndex()
  1117. for i in range(4):
  1118. coords.append(self.GetItem(index, i).GetText())
  1119. dlg = EditGPC(parent=self, id=wx.ID_ANY, data=coords)
  1120. if dlg.ShowModal() == wx.ID_OK:
  1121. values = dlg.GetValues() # string
  1122. if len(values) == 0:
  1123. wx.MessageBox(parent=self,
  1124. caption=_("Edit GCP"),
  1125. message=_("Invalid coordinate value. Operation cancelled."),
  1126. style=wx.CENTRE | wx.ICON_ERROR | wx.ID_OK)
  1127. else:
  1128. for i in range(len(values)):
  1129. if values[i] != coords[i]:
  1130. self.SetStringItem(index, i, values[i])
  1131. mapdisp = self.gcp.mapcoordlist[index]['gcpcoord'][2]
  1132. self.gcp.mapcoordlist[index]['gcpcoord'] = (float(values[0]), float(values[1]), mapdisp)
  1133. mapdisp = self.gcp.mapcoordlist[index]['mapcoord'][2]
  1134. self.gcp.mapcoordlist[index]['mapcoord'] = (float(values[0]), float(values[1]), mapdisp)
  1135. class VectGroup(wx.Dialog):
  1136. """
  1137. Dialog to create a vector group (VREF file) for georectifying
  1138. @todo Replace by g.group
  1139. """
  1140. def __init__(self, parent, id, grassdb, location, mapset, group,
  1141. style=wx.DEFAULT_DIALOG_STYLE):
  1142. wx.Dialog.__init__(self, parent, id, style=style,
  1143. title = _("Create vector map group"))
  1144. self.grassdatabase = grassdb
  1145. self.xylocation = location
  1146. self.xymapset = mapset
  1147. self.xygroup = group
  1148. #
  1149. # get list of valid vector directories
  1150. #
  1151. vectlist = os.listdir(os.path.join(self.grassdatabase,
  1152. self.xylocation,
  1153. self.xymapset,
  1154. 'vector'))
  1155. for dir in vectlist:
  1156. if not os.path.isfile(os.path.join(self.grassdatabase,
  1157. self.xylocation,
  1158. self.xymapset,
  1159. 'vector',
  1160. dir,
  1161. 'coor')):
  1162. vectlist.remove(dir)
  1163. utils.ListSortLower(vectlist)
  1164. # path to vref file
  1165. self.vgrpfile = os.path.join(self.grassdatabase,
  1166. self.xylocation,
  1167. self.xymapset,
  1168. 'group',
  1169. self.xygroup,
  1170. 'VREF')
  1171. #
  1172. # buttons
  1173. #
  1174. self.btnCancel = wx.Button(parent = self,
  1175. id = wx.ID_CANCEL)
  1176. self.btnOK = wx.Button(parent = self,
  1177. id = wx.ID_OK)
  1178. self.btnOK.SetDefault()
  1179. #
  1180. # list of vector maps
  1181. #
  1182. self.listMap = wx.CheckListBox(parent = self, id = wx.ID_ANY,
  1183. choices = vectlist)
  1184. if os.path.isfile(self.vgrpfile):
  1185. f = open(self.vgrpfile)
  1186. try:
  1187. checked = []
  1188. for line in f.readlines():
  1189. line = line.replace('\n', '')
  1190. if len(line) < 1:
  1191. continue
  1192. checked.append(line)
  1193. self.listMap.SetCheckedStrings(checked)
  1194. finally:
  1195. f.close()
  1196. line = wx.StaticLine(parent = self,
  1197. id = wx.ID_ANY, size = (20, -1),
  1198. style = wx.LI_HORIZONTAL)
  1199. #
  1200. # layout
  1201. #
  1202. sizer = wx.BoxSizer(wx.VERTICAL)
  1203. box = wx.BoxSizer(wx.HORIZONTAL)
  1204. box.Add(item = wx.StaticText(parent = self, id = wx.ID_ANY,
  1205. label = _('Select vector map(s) to add to group:')),
  1206. flag = wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.LEFT,
  1207. border = 5)
  1208. box.Add(item = self.listMap,
  1209. flag = wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.LEFT,
  1210. border = 5)
  1211. sizer.Add(box, flag = wx.ALIGN_RIGHT | wx.ALL,
  1212. border = 3)
  1213. sizer.Add(item = line, proportion = 0,
  1214. flag = wx.GROW | wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT,
  1215. border = 5)
  1216. # buttons
  1217. btnSizer = wx.StdDialogButtonSizer()
  1218. btnSizer.AddButton(self.btnCancel)
  1219. btnSizer.AddButton(self.btnOK)
  1220. btnSizer.Realize()
  1221. sizer.Add(item = btnSizer, proportion = 0,
  1222. flag = wx.EXPAND | wx.ALL | wx.ALIGN_CENTER,
  1223. border = 5)
  1224. self.SetSizer(sizer)
  1225. sizer.Fit(self)
  1226. self.Layout()
  1227. def MakeVGroup(self):
  1228. """!Create VREF file"""
  1229. vgrouplist = []
  1230. for item in range(self.listMap.GetCount()):
  1231. if not self.listMap.IsChecked(item):
  1232. continue
  1233. vgrouplist.append(self.listMap.GetString(item))
  1234. f = open(self.vgrpfile, mode='w')
  1235. try:
  1236. for vect in vgrouplist:
  1237. f.write(vect + '\n')
  1238. finally:
  1239. f.close()
  1240. class EditGPC(wx.Dialog):
  1241. def __init__(self, parent, data, id=wx.ID_ANY,
  1242. title=_("Edit GCP"),
  1243. style=wx.DEFAULT_DIALOG_STYLE):
  1244. """!Dialog for editing GPC and map coordinates in list control"""
  1245. wx.Dialog.__init__(self, parent, id, title=title, style=style)
  1246. panel = wx.Panel(parent=self)
  1247. sizer = wx.BoxSizer(wx.VERTICAL)
  1248. box = wx.StaticBox (parent=panel, id=wx.ID_ANY,
  1249. label=" %s " % _("Ground Control Point"))
  1250. boxSizer = wx.StaticBoxSizer(box, wx.VERTICAL)
  1251. # source coordinates
  1252. gridSizer = wx.GridBagSizer(vgap=5, hgap=5)
  1253. self.xcoord = wx.TextCtrl(parent=panel, id=wx.ID_ANY, size=(150, -1))
  1254. self.ycoord = wx.TextCtrl(parent=panel, id=wx.ID_ANY, size=(150, -1))
  1255. self.ncoord = wx.TextCtrl(parent=panel, id=wx.ID_ANY, size=(150, -1))
  1256. self.ecoord = wx.TextCtrl(parent=panel, id=wx.ID_ANY, size=(150, -1))
  1257. row = 0
  1258. col = 0
  1259. idx = 0
  1260. for label, win in ((_("X:"), self.xcoord),
  1261. (_("Y:"), self.ycoord),
  1262. (_("E:"), self.ecoord),
  1263. (_("N:"), self.ncoord)):
  1264. label = wx.StaticText(parent=panel, id=wx.ID_ANY,
  1265. label=label)
  1266. gridSizer.Add(item=label,
  1267. flag=wx.ALIGN_CENTER_VERTICAL,
  1268. pos=(row, col))
  1269. col += 1
  1270. win.SetValue(str(data[idx]))
  1271. gridSizer.Add(item=win,
  1272. pos=(row, col))
  1273. col += 1
  1274. idx += 1
  1275. if col > 3:
  1276. row += 1
  1277. col = 0
  1278. boxSizer.Add(item=gridSizer, proportion=1,
  1279. flag=wx.EXPAND | wx.ALL, border=5)
  1280. sizer.Add(item=boxSizer, proportion=1,
  1281. flag=wx.EXPAND | wx.ALL, border=5)
  1282. #
  1283. # buttons
  1284. #
  1285. self.btnCancel = wx.Button(panel, wx.ID_CANCEL)
  1286. self.btnOk = wx.Button(panel, wx.ID_OK)
  1287. self.btnOk.SetDefault()
  1288. btnSizer = wx.StdDialogButtonSizer()
  1289. btnSizer.AddButton(self.btnCancel)
  1290. btnSizer.AddButton(self.btnOk)
  1291. btnSizer.Realize()
  1292. sizer.Add(item=btnSizer, proportion=0,
  1293. flag=wx.ALIGN_RIGHT | wx.ALL, border=5)
  1294. panel.SetSizer(sizer)
  1295. sizer.Fit(self)
  1296. def GetValues(self, columns=None):
  1297. """!Return list of values (as strings).
  1298. """
  1299. valuelist = []
  1300. try:
  1301. float(self.xcoord.GetValue())
  1302. float(self.ycoord.GetValue())
  1303. float(self.ecoord.GetValue())
  1304. float(self.ncoord.GetValue())
  1305. except ValueError:
  1306. return valuelist
  1307. valuelist.append(self.xcoord.GetValue())
  1308. valuelist.append(self.ycoord.GetValue())
  1309. valuelist.append(self.ecoord.GetValue())
  1310. valuelist.append(self.ncoord.GetValue())
  1311. return valuelist
  1312. class GrSettingsDialog(wx.Dialog):
  1313. def __init__(self, parent, id, title, pos=wx.DefaultPosition, size=wx.DefaultSize,
  1314. style=wx.DEFAULT_DIALOG_STYLE):
  1315. wx.Dialog.__init__(self, parent, id, title, pos, size, style)
  1316. """
  1317. Dialog to set profile text options: font, title
  1318. and font size, axis labels and font size
  1319. """
  1320. #
  1321. # initialize variables
  1322. #
  1323. self.parent = parent
  1324. self.symbol = {}
  1325. self._do_layout()
  1326. def _do_layout(self):
  1327. """!Do layout"""
  1328. # dialog layout
  1329. sizer = wx.BoxSizer(wx.VERTICAL)
  1330. box = wx.StaticBox(parent=self, id=wx.ID_ANY,
  1331. label=" %s " % _("Symbol settings"))
  1332. boxSizer = wx.StaticBoxSizer(box, wx.VERTICAL)
  1333. gridSizer = wx.GridBagSizer(vgap=5, hgap=5)
  1334. gridSizer.AddGrowableCol(1)
  1335. #
  1336. # symbol color
  1337. #
  1338. row = 0
  1339. label = wx.StaticText(parent=self, id=wx.ID_ANY, label=_("Color:"))
  1340. gridSizer.Add(item=label, flag=wx.ALIGN_CENTER_VERTICAL, pos=(row, 0))
  1341. col = UserSettings.Get(group='georect', key='symbol', subkey='color')
  1342. colWin = csel.ColourSelect(parent=self, id=wx.ID_ANY,
  1343. colour=wx.Colour(col[0],
  1344. col[1],
  1345. col[2],
  1346. 255))
  1347. self.symbol['color'] = colWin.GetId()
  1348. gridSizer.Add(item=colWin,
  1349. flag=wx.ALIGN_RIGHT,
  1350. pos=(row, 1))
  1351. #
  1352. # symbol width
  1353. #
  1354. row += 1
  1355. label = wx.StaticText(parent=self, id=wx.ID_ANY, label=_("Width:"))
  1356. gridSizer.Add(item=label, flag=wx.ALIGN_CENTER_VERTICAL, pos=(row, 0))
  1357. width = int(UserSettings.Get(group='georect', key='symbol', subkey='width'))
  1358. widWin = wx.SpinCtrl(parent=self, id=wx.ID_ANY,
  1359. min=1, max=10)
  1360. widWin.SetValue(width)
  1361. self.symbol['width'] = widWin.GetId()
  1362. gridSizer.Add(item=widWin,
  1363. flag=wx.ALIGN_RIGHT,
  1364. pos=(row, 1))
  1365. boxSizer.Add(item=gridSizer, flag=wx.EXPAND)
  1366. sizer.Add(item=boxSizer, flag=wx.EXPAND | wx.ALL, border=5)
  1367. line = wx.StaticLine(parent=self, id=wx.ID_ANY, size=(20, -1), style=wx.LI_HORIZONTAL)
  1368. sizer.Add(item=line, proportion=0,
  1369. flag=wx.GROW|wx.ALIGN_CENTER_VERTICAL|wx.LEFT|wx.RIGHT, border=3)
  1370. #
  1371. # buttons
  1372. #
  1373. btnSave = wx.Button(self, wx.ID_SAVE)
  1374. btnApply = wx.Button(self, wx.ID_APPLY)
  1375. btnCancel = wx.Button(self, wx.ID_CANCEL)
  1376. btnSave.SetDefault()
  1377. # bindigs
  1378. btnApply.Bind(wx.EVT_BUTTON, self.OnApply)
  1379. btnApply.SetToolTipString(_("Apply changes for the current session"))
  1380. btnSave.Bind(wx.EVT_BUTTON, self.OnSave)
  1381. btnSave.SetToolTipString(_("Apply and save changes to user settings file (default for next sessions)"))
  1382. btnSave.SetDefault()
  1383. btnCancel.Bind(wx.EVT_BUTTON, self.OnCancel)
  1384. btnCancel.SetToolTipString(_("Close dialog and ignore changes"))
  1385. # sizers
  1386. btnStdSizer = wx.StdDialogButtonSizer()
  1387. btnStdSizer.AddButton(btnCancel)
  1388. btnStdSizer.AddButton(btnSave)
  1389. btnStdSizer.AddButton(btnApply)
  1390. btnStdSizer.Realize()
  1391. sizer.Add(item=btnStdSizer, proportion=0, flag=wx.ALIGN_RIGHT | wx.ALL, border=5)
  1392. self.SetSizer(sizer)
  1393. sizer.Fit(self)
  1394. def UpdateSettings(self):
  1395. UserSettings.Set(group='georect', key='symbol', subkey='color',
  1396. value=wx.FindWindowById(self.symbol['color']).GetColour())
  1397. UserSettings.Set(group='georect', key='symbol', subkey='width',
  1398. value=wx.FindWindowById(self.symbol['width']).GetValue())
  1399. def OnSave(self, event):
  1400. """!Button 'Save' pressed"""
  1401. self.UpdateSettings()
  1402. fileSettings = {}
  1403. UserSettings.ReadSettingsFile(settings=fileSettings)
  1404. fileSettings['georect'] = UserSettings.Get(group='georect')
  1405. file = UserSettings.SaveToFile(fileSettings)
  1406. self.parent.parent.goutput.WriteLog(_('Georectifier settings saved to file \'%s\'.') % file)
  1407. self.Close()
  1408. def OnApply(self, event):
  1409. """!Button 'Apply' pressed"""
  1410. self.UpdateSettings()
  1411. self.Close()
  1412. def OnCancel(self, event):
  1413. """!Button 'Cancel' pressed"""
  1414. self.Close()