georect.py 56 KB

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