georect.py 56 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598
  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. self.grassdatabase = grass.gisenv()['GISDBASE']
  65. #
  66. # read original environment settings
  67. #
  68. self.orig_gisrc = os.environ['GISRC']
  69. self.gisrc_dict = {}
  70. try:
  71. f = open(self.orig_gisrc, 'r')
  72. for line in f.readlines():
  73. if line != '':
  74. line = line.replace('\n', '').strip()
  75. key, value = line.split(':')
  76. self.gisrc_dict[key.strip()] = value.strip()
  77. finally:
  78. f.close()
  79. self.currentlocation = self.gisrc_dict['LOCATION_NAME']
  80. self.currentmapset = self.gisrc_dict['MAPSET']
  81. # location for xy map to georectify
  82. self.newlocation = ''
  83. # mapset for xy map to georectify
  84. self.newmapset = ''
  85. # GISRC file for source location/mapset of map(s) to georectify
  86. self.new_gisrc = ''
  87. #
  88. # define wizard pages
  89. #
  90. self.wizard = wiz.Wizard(parent=parent, id=wx.ID_ANY, title=_("Setup for georectification"))
  91. self.startpage = LocationPage(self.wizard, self)
  92. self.grouppage = GroupPage(self.wizard, self)
  93. self.mappage = DispMapPage(self.wizard, self)
  94. # Set the initial order of the pages
  95. self.startpage.SetNext(self.grouppage)
  96. self.grouppage.SetPrev(self.startpage)
  97. self.grouppage.SetNext(self.mappage)
  98. self.mappage.SetPrev(self.grouppage)
  99. #
  100. # do pages layout
  101. #
  102. self.startpage.DoLayout()
  103. self.grouppage.DoLayout()
  104. self.mappage.DoLayout()
  105. self.wizard.FitToPage(self.startpage)
  106. # self.Bind(wx.EVT_CLOSE, self.Cleanup)
  107. # self.parent.Bind(wx.EVT_ACTIVATE, self.OnGLMFocus)
  108. success = False
  109. #
  110. # run wizard
  111. #
  112. if self.wizard.RunWizard(self.startpage):
  113. success = self.OnWizFinished()
  114. if success == False:
  115. wx.MessageBox(_("Georectifying setup canceled."))
  116. self.Cleanup()
  117. else:
  118. wx.MessageBox(_("Georectifying setup canceled."))
  119. self.Cleanup()
  120. #
  121. # start display showing xymap
  122. #
  123. if success != False:
  124. # instance of render.Map to be associated with display
  125. self.Map = render.Map(gisrc=self.new_gisrc)
  126. global maptype
  127. global xy_map
  128. #
  129. # add layer to map
  130. #
  131. if maptype == 'cell':
  132. rendertype = 'raster'
  133. cmdlist = ['d.rast', 'map=%s' % xy_map]
  134. elif maptype == 'vector':
  135. rendertype = 'vector'
  136. cmdlist = ['d.vect', 'map=%s' % xy_map]
  137. self.Map.AddLayer(type=rendertype, command=cmdlist, l_active=True,
  138. name=utils.GetLayerNameFromCmd(cmdlist),
  139. l_hidden=False, l_opacity=1.0, l_render=False)
  140. #
  141. # start GCP form
  142. #
  143. self.gcpmgr = GCP(self.parent, grwiz=self)
  144. self.gcpmgr.Show()
  145. #
  146. # start map display
  147. #
  148. self.xy_mapdisp = mapdisp.MapFrame(self.gcpmgr, title=_("Set ground control points (GCPs)"),
  149. size=globalvar.MAP_WINDOW_SIZE,
  150. toolbars=["georect"],
  151. Map=self.Map, gismgr=self.parent)
  152. self.gcpmgr.SetMapDisplay(self.xy_mapdisp)
  153. self.mapwin = self.xy_mapdisp.MapWindow
  154. # set mouse characteristics
  155. self.mapwin.mouse['box'] = 'point'
  156. self.mapwin.mouse["use"] == "pointer"
  157. self.mapwin.zoomtype = 0
  158. self.mapwin.pen = wx.Pen(colour='black', width=2, style=wx.SOLID)
  159. self.mapwin.SetCursor(self.xy_mapdisp.cursors["cross"])
  160. #
  161. # show new display & draw map
  162. #
  163. self.xy_mapdisp.Show()
  164. else:
  165. self.Cleanup()
  166. def SetSrcEnv(self, location, mapset):
  167. """Create environment to use for location and mapset
  168. that are the source of the file(s) to georectify
  169. @param location source location
  170. @param mapset source mapset
  171. @return False on error
  172. @return True on success
  173. """
  174. self.newlocation = location
  175. self.newmapset = mapset
  176. # check to see if we are georectifying map in current working location/mapset
  177. if self.newlocation == self.currentlocation and self.newmapset == self.currentmapset:
  178. return False
  179. self.gisrc_dict['LOCATION_NAME'] = location
  180. self.gisrc_dict['MAPSET'] = mapset
  181. self.new_gisrc = utils.GetTempfile()
  182. try:
  183. f = open(self.new_gisrc, mode='w')
  184. for line in self.gisrc_dict.items():
  185. f.write(line[0] + ": " + line[1] + "\n")
  186. finally:
  187. f.close()
  188. return True
  189. def SwitchEnv(self, grc):
  190. """
  191. Switches between original working location/mapset and
  192. location/mapset that is source of file(s) to georectify
  193. """
  194. # check to see if we are georectifying map in current working location/mapset
  195. if self.newlocation == self.currentlocation and self.newmapset == self.currentmapset:
  196. return False
  197. if grc == 'original':
  198. os.environ["GISRC"] = str(self.orig_gisrc)
  199. elif grc == 'new':
  200. os.environ["GISRC"] = str(self.new_gisrc)
  201. return True
  202. def OnWizFinished(self):
  203. # self.Cleanup()
  204. return True
  205. def OnGLMFocus(self, event):
  206. """Layer Manager focus"""
  207. # self.SwitchEnv('original')
  208. event.Skip()
  209. def Cleanup(self):
  210. """Return to current location and mapset"""
  211. self.SwitchEnv('original')
  212. self.parent.georectifying = None
  213. if hasattr(self, "xy_mapdisp"):
  214. self.xy_mapdisp.Close()
  215. self.xy_mapdisp = None
  216. self.wizard.Destroy()
  217. class LocationPage(TitledPage):
  218. """
  219. Set map type (raster or vector) to georectify and
  220. select location/mapset of map(s) to georectify.
  221. """
  222. def __init__(self, wizard, parent):
  223. TitledPage.__init__(self, wizard, _("Select map type and location/mapset"))
  224. self.parent = parent
  225. self.grassdatabase = self.parent.grassdatabase
  226. self.xylocation = ''
  227. self.xymapset = ''
  228. tmplist = os.listdir(self.grassdatabase)
  229. self.locList = []
  230. self.mapsetList = []
  231. #
  232. # create a list of valid locations
  233. #
  234. for item in tmplist:
  235. if os.path.isdir(os.path.join(self.grassdatabase, item)) and \
  236. os.path.exists(os.path.join(self.grassdatabase, item, 'PERMANENT')):
  237. self.locList.append(item)
  238. utils.ListSortLower(self.locList)
  239. #
  240. # layout
  241. #
  242. self.sizer.AddGrowableCol(2)
  243. # map type
  244. self.rb_maptype = wx.RadioBox(parent=self, id=wx.ID_ANY, label=' %s ' % _("Map type to georectify"),
  245. choices=[_('raster'), _('vector')], majorDimension=wx.RA_SPECIFY_COLS)
  246. self.sizer.Add(item=self.rb_maptype,
  247. flag=wx.ALIGN_CENTER | wx.ALL | wx.EXPAND, border=5,
  248. pos=(1, 1), span=(1, 2))
  249. # location
  250. self.sizer.Add(item=wx.StaticText(parent=self, id=wx.ID_ANY, label=_('Select source location:')),
  251. flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5,
  252. pos=(2, 1))
  253. self.cb_location = wx.ComboBox(parent=self, id=wx.ID_ANY,
  254. choices = self.locList, size=(300, -1),
  255. style=wx.CB_DROPDOWN | wx.CB_READONLY)
  256. self.sizer.Add(item=self.cb_location,
  257. flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5,
  258. pos=(2, 2))
  259. # mapset
  260. self.sizer.Add(item=wx.StaticText(parent=self, id=wx.ID_ANY, label=_('Select source mapset:')),
  261. flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5,
  262. pos=(3, 1))
  263. self.cb_mapset = wx.ComboBox(parent=self, id=wx.ID_ANY,
  264. choices = self.mapsetList, size=(300, -1),
  265. style=wx.CB_DROPDOWN | wx.CB_READONLY)
  266. self.sizer.Add(item=self.cb_mapset,
  267. flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5,
  268. pos=(3,2))
  269. #
  270. # bindings
  271. #
  272. self.Bind(wx.EVT_RADIOBOX, self.OnMaptype, self.rb_maptype)
  273. self.Bind(wx.EVT_COMBOBOX, self.OnLocation, self.cb_location)
  274. self.Bind(wx.EVT_COMBOBOX, self.OnMapset, self.cb_mapset)
  275. self.Bind(wiz.EVT_WIZARD_PAGE_CHANGING, self.OnPageChanging)
  276. self.Bind(wiz.EVT_WIZARD_PAGE_CHANGED, self.OnEnterPage)
  277. # self.Bind(wx.EVT_CLOSE, self.parent.Cleanup)
  278. def OnMaptype(self,event):
  279. """Change map type"""
  280. global maptype
  281. if event.GetInt() == 0:
  282. maptype = 'cell'
  283. else:
  284. maptype = 'vector'
  285. def OnLocation(self, event):
  286. """Sets source location for map(s) to georectify"""
  287. self.xylocation = event.GetString()
  288. #create a list of valid mapsets
  289. tmplist = os.listdir(os.path.join(self.grassdatabase, self.xylocation))
  290. self.mapsetList = []
  291. for item in tmplist:
  292. if os.path.isdir(os.path.join(self.grassdatabase, self.xylocation, item)) and \
  293. os.path.exists(os.path.join(self.grassdatabase, self.xylocation, item, 'WIND')):
  294. if item != 'PERMANENT':
  295. self.mapsetList.append(item)
  296. self.xymapset = 'PERMANENT'
  297. utils.ListSortLower(self.mapsetList)
  298. self.mapsetList.insert(0, 'PERMANENT')
  299. self.cb_mapset.SetItems(self.mapsetList)
  300. self.cb_mapset.SetStringSelection(self.xymapset)
  301. if not wx.FindWindowById(wx.ID_FORWARD).IsEnabled():
  302. wx.FindWindowById(wx.ID_FORWARD).Enable(True)
  303. def OnMapset(self, event):
  304. """Sets source mapset for map(s) to georectify"""
  305. if self.xylocation == '':
  306. wx.MessageBox(_('You must select a valid location before selecting a mapset'))
  307. return
  308. self.xymapset = event.GetString()
  309. if not wx.FindWindowById(wx.ID_FORWARD).IsEnabled():
  310. wx.FindWindowById(wx.ID_FORWARD).Enable(True)
  311. def OnPageChanging(self, event=None):
  312. if event.GetDirection() and \
  313. (self.xylocation == '' or self.xymapset == ''):
  314. wx.MessageBox(_('You must select a valid location and mapset in order to continue'))
  315. event.Veto()
  316. return
  317. else:
  318. self.parent.SetSrcEnv(self.xylocation, self.xymapset)
  319. def OnEnterPage(self, event=None):
  320. if self.xylocation == '' or self.xymapset == '':
  321. wx.FindWindowById(wx.ID_FORWARD).Enable(False)
  322. else:
  323. wx.FindWindowById(wx.ID_FORWARD).Enable(True)
  324. class GroupPage(TitledPage):
  325. """
  326. Set group to georectify. Create group if desired.
  327. """
  328. def __init__(self, wizard, parent):
  329. TitledPage.__init__(self, wizard, _("Select image/map group to georectify"))
  330. self.parent = parent
  331. self.grassdatabase = self.parent.grassdatabase
  332. self.groupList = []
  333. self.xylocation = ''
  334. self.xymapset = ''
  335. self.xygroup = ''
  336. # default extension
  337. self.extension = 'georect' + str(os.getpid())
  338. #
  339. # layout
  340. #
  341. self.sizer.AddGrowableCol(2)
  342. # group
  343. self.sizer.Add(item=wx.StaticText(parent=self, id=wx.ID_ANY, label=_('Select group:')),
  344. flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5,
  345. pos=(1, 1))
  346. self.cb_group = wx.ComboBox(parent=self, id=wx.ID_ANY,
  347. choices=self.groupList, size=(350, -1),
  348. style=wx.CB_DROPDOWN | wx.CB_READONLY)
  349. self.sizer.Add(item=self.cb_group,
  350. flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5,
  351. pos=(1, 2))
  352. # create group
  353. self.sizer.Add(item=wx.StaticText(parent=self, id=wx.ID_ANY, label=_('Create group if none exists')),
  354. flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5,
  355. pos=(2, 1))
  356. self.btn_mkgroup = wx.Button(parent=self, id=wx.ID_ANY, label=_("Create/edit group..."))
  357. self.sizer.Add(item=self.btn_mkgroup,
  358. flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5,
  359. pos=(2, 2))
  360. # extension
  361. self.sizer.Add(item=wx.StaticText(parent=self, id=wx.ID_ANY, label=_('Extension for output maps:')),
  362. flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5,
  363. pos=(3, 1))
  364. self.ext_txt = wx.TextCtrl(parent=self, id=wx.ID_ANY, value="", size=(350,-1))
  365. self.ext_txt.SetValue(self.extension)
  366. self.sizer.Add(item=self.ext_txt,
  367. flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5,
  368. pos=(3, 2))
  369. #
  370. # bindings
  371. #
  372. self.Bind(wx.EVT_COMBOBOX, self.OnGroup, self.cb_group)
  373. self.Bind(wx.EVT_BUTTON, self.OnMkGroup, self.btn_mkgroup)
  374. self.Bind(wx.EVT_TEXT, self.OnExtension, self.ext_txt)
  375. self.Bind(wiz.EVT_WIZARD_PAGE_CHANGING, self.OnPageChanging)
  376. self.Bind(wiz.EVT_WIZARD_PAGE_CHANGED, self.OnEnterPage)
  377. self.Bind(wx.EVT_CLOSE, self.parent.Cleanup)
  378. def OnGroup(self, event):
  379. self.xygroup = event.GetString()
  380. def OnMkGroup(self, event):
  381. """Create new group in source location/mapset"""
  382. global maptype
  383. # open dialog
  384. if maptype == 'cell':
  385. menuform.GUI().ParseCommand(['i.group'],
  386. completed=(self.GetOptData, None, ''),
  387. parentframe=self.parent.parent, modal=True)
  388. elif maptype == 'vector':
  389. dlg = VectGroup(self, wx.ID_ANY, self.grassdatabase, self.xylocation, self.xymapset, self.xygroup)
  390. if dlg.ShowModal() == wx.ID_OK:
  391. dlg.MakeVGroup()
  392. self.OnEnterPage()
  393. def GetOptData(self, dcmd, layer, params, propwin):
  394. """Process i.group"""
  395. # update the page
  396. if dcmd:
  397. gcmd.Command(dcmd, stderr=None)
  398. self.OnEnterPage()
  399. self.Update()
  400. def OnExtension(self, event):
  401. self.extension = event.GetString()
  402. def OnPageChanging(self, event=None):
  403. if event.GetDirection() and self.xygroup == '':
  404. wx.MessageBox(_('You must select a valid image/map group in order to continue'))
  405. event.Veto()
  406. return
  407. if event.GetDirection() and self.extension == '':
  408. wx.MessageBox(_('You must enter an map name extension in order to continue'))
  409. event.Veto()
  410. return
  411. def OnEnterPage(self, event=None):
  412. self.groupList = []
  413. tmplist = []
  414. self.xylocation = self.parent.gisrc_dict['LOCATION_NAME']
  415. self.xymapset = self.parent.gisrc_dict['MAPSET']
  416. # create a list of groups in selected mapset
  417. if os.path.isdir(os.path.join(self.grassdatabase,self.xylocation,self.xymapset,'group')):
  418. tmplist = os.listdir(os.path.join(self.grassdatabase, self.xylocation, self.xymapset, 'group'))
  419. else:
  420. tmplist = []
  421. # if (event and event.GetDirection()) and self.xygroup == '':
  422. # if tmplist == []:
  423. # wx.MessageBox(_('No map/imagery groups exist to georectify. '
  424. # 'You will need to create one.'))
  425. # else:
  426. for item in tmplist:
  427. if os.path.isdir(os.path.join(self.grassdatabase, self.xylocation, self.xymapset, 'group', item)):
  428. self.groupList.append(item)
  429. utils.ListSortLower(self.groupList)
  430. self.cb_group.SetItems(self.groupList)
  431. if len(self.groupList) > 0:
  432. self.cb_group.SetSelection(0)
  433. self.xygroup = self.groupList[0]
  434. if self.xygroup == '' or self.extension == '':
  435. wx.FindWindowById(wx.ID_FORWARD).Enable(False)
  436. else:
  437. wx.FindWindowById(wx.ID_FORWARD).Enable(True)
  438. # switch to source
  439. self.parent.SwitchEnv('new')
  440. class DispMapPage(TitledPage):
  441. """
  442. Select ungeoreferenced map to display for interactively
  443. setting ground control points (GCPs).
  444. """
  445. def __init__(self, wizard, parent):
  446. TitledPage.__init__(self, wizard, _("Select image/map to display for ground control point (GCP) creation"))
  447. self.parent = parent
  448. global maptype
  449. #
  450. # layout
  451. #
  452. self.sizer.Add(item=wx.StaticText(parent=self, id=wx.ID_ANY, label=_('Select display image/map:')),
  453. flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5,
  454. pos=(1, 1))
  455. self.selection = gselect.Select(self, id=wx.ID_ANY, size=globalvar.DIALOG_GSELECT_SIZE,
  456. type=maptype)
  457. self.sizer.Add(item=self.selection,
  458. flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5,
  459. pos=(1, 2))
  460. #
  461. # bindings
  462. #
  463. self.selection.Bind(wx.EVT_TEXT, self.OnSelection)
  464. self.Bind(wiz.EVT_WIZARD_PAGE_CHANGING, self.OnPageChanging)
  465. self.Bind(wiz.EVT_WIZARD_PAGE_CHANGED, self.OnEnterPage)
  466. self.Bind(wx.EVT_CLOSE, self.parent.Cleanup)
  467. def OnSelection(self,event):
  468. """Map to display selected"""
  469. global xy_map
  470. xy_map = event.GetString()
  471. if xy_map == '':
  472. wx.FindWindowById(wx.ID_FORWARD).Enable(False)
  473. else:
  474. wx.FindWindowById(wx.ID_FORWARD).Enable(True)
  475. def OnPageChanging(self, event=None):
  476. global xy_map
  477. if event.GetDirection() and xy_map == '':
  478. wx.MessageBox(_('You must select a valid image/map in order to continue'))
  479. event.Veto()
  480. return
  481. self.parent.SwitchEnv('original')
  482. def OnEnterPage(self, event=None):
  483. global maptype
  484. global xy_map
  485. self.selection.SetElementList(maptype)
  486. if xy_map == '':
  487. wx.FindWindowById(wx.ID_FORWARD).Enable(False)
  488. else:
  489. wx.FindWindowById(wx.ID_FORWARD).Enable(True)
  490. class GCP(wx.Frame):
  491. """
  492. Manages ground control points for georectifying. Calculates RMS statics.
  493. Calls i.rectify or v.transform to georectify map.
  494. """
  495. def __init__(self, parent, grwiz, mapdisp=None, id=wx.ID_ANY,
  496. title=_("Create & manage ground control points"),
  497. size=wx.DefaultSize):
  498. wx.Frame.__init__(self, parent, id, title, size=(625, 300))
  499. self.SetIcon(wx.Icon(os.path.join(globalvar.ETCICONDIR, 'grass_map.ico'), wx.BITMAP_TYPE_ICO))
  500. #
  501. # init variables
  502. #
  503. self.parent = parent # GMFrame
  504. self.parent.georectifying = self
  505. self.mapdisp = mapdisp # XY-location Map Display
  506. self.grwiz = grwiz # GR Wizard
  507. self.grassdatabase = self.grwiz.grassdatabase
  508. self.currentlocation = self.grwiz.currentlocation
  509. self.currentmapset = self.grwiz.currentmapset
  510. self.newlocation = self.grwiz.newlocation
  511. self.newmapset = self.grwiz.newmapset
  512. self.xylocation = self.grwiz.gisrc_dict['LOCATION_NAME']
  513. self.xymapset = self.grwiz.gisrc_dict['MAPSET']
  514. self.xygroup = self.grwiz.grouppage.xygroup
  515. self.extension = self.grwiz.grouppage.extension
  516. self.file = {
  517. 'points' : os.path.join(self.grassdatabase,
  518. self.xylocation,
  519. self.xymapset,
  520. 'group',
  521. self.xygroup,
  522. 'POINTS'),
  523. 'rgrp' : os.path.join(self.grassdatabase,
  524. self.xylocation,
  525. self.xymapset,
  526. 'group',
  527. self.xygroup,
  528. 'REF'),
  529. 'vgrp' : os.path.join(self.grassdatabase,
  530. self.xylocation,
  531. self.xymapset,
  532. 'group',
  533. self.xygroup,
  534. 'VREF'),
  535. 'target' : os.path.join(self.grassdatabase,
  536. self.xylocation,
  537. self.xymapset,
  538. 'group',
  539. self.xygroup,
  540. 'TARGET'),
  541. }
  542. # polynomial order transformation for georectification
  543. self.gr_order = 1
  544. # number of GCPs selected to be used for georectification (checked)
  545. self.GCPcount = 0
  546. # forward RMS error
  547. self.fwd_rmserror = 0.0
  548. # backward RMS error
  549. self.bkw_rmserror = 0.0
  550. # list map coords and ID of map display they came from
  551. self.mapcoordlist = []
  552. self.SetTarget(self.xygroup, self.currentlocation, self.currentmapset)
  553. #
  554. # toolbar and display for xy map
  555. #
  556. self.toolbar = toolbars.GCPToolbar(parent=self, tbframe=self).GetToolbar()
  557. self.SetToolBar(self.toolbar)
  558. self.SetMapDisplay(self.mapdisp)
  559. #
  560. # statusbar
  561. #
  562. self.CreateStatusBar(number=1)
  563. # can put guage into custom statusbar for progress if can figure out how to get progress text from i.rectify
  564. # self.gr_gauge = wx.Gauge(self, -1, 100, (-1,-1), (100, 25))
  565. # self.gr_guage.Pulse()
  566. panel = wx.Panel(parent=self)
  567. #
  568. # do layout
  569. #
  570. sizer = wx.BoxSizer(wx.VERTICAL)
  571. self.rb_grmethod = wx.RadioBox(parent=panel, id=wx.ID_ANY,
  572. label=" %s " % _("Select rectification method for rasters"),
  573. choices=[_('1st order'), _('2nd order'), _('3rd order')],
  574. majorDimension=wx.RA_SPECIFY_COLS)
  575. sizer.Add(item=self.rb_grmethod, proportion=0,
  576. flag=wx.EXPAND | wx.ALL, border=5)
  577. self.clip_to_region = wx.CheckBox(parent=panel, id=wx.ID_ANY,
  578. label=_("clip to computational region in target location"))
  579. sizer.Add(item=self.clip_to_region, proportion=0,
  580. flag=wx.EXPAND | wx.ALL, border=5)
  581. box = wx.StaticBox (parent=panel, id=wx.ID_ANY,
  582. label=" %s " % _("Ground Control Points"))
  583. boxSizer = wx.StaticBoxSizer(box, wx.VERTICAL)
  584. # initialize list control for GCP management
  585. self.list = GCPList(parent=panel, gcp=self)
  586. boxSizer.Add(item=self.list, proportion=1,
  587. flag=wx.EXPAND | wx.ALL, border=3)
  588. sizer.Add(item=boxSizer, proportion=1,
  589. flag=wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM, border=5)
  590. #
  591. # bindigs
  592. #
  593. self.Bind(wx.EVT_RADIOBOX, self.OnGRMethod, self.rb_grmethod)
  594. self.Bind(wx.EVT_ACTIVATE, self.OnFocus)
  595. self.Bind(wx.EVT_CLOSE, self.OnQuit)
  596. panel.SetSizer(sizer)
  597. # sizer.Fit(self)
  598. def __del__(self):
  599. """Disable georectification mode"""
  600. self.parent.georectifying = None
  601. def SetMapDisplay(self, win):
  602. self.mapdisp = win
  603. if self.mapdisp:
  604. self.list.LoadData()
  605. def SetTarget(self, tgroup, tlocation, tmapset):
  606. """
  607. Sets rectification target to current location and mapset
  608. """
  609. # check to see if we are georectifying map in current working location/mapset
  610. if self.newlocation == self.currentlocation and self.newmapset == self.currentmapset:
  611. gcmd.RunCommand('i.target',
  612. parent = self,
  613. flags = 'c',
  614. group = tgroup)
  615. else:
  616. self.grwiz.SwitchEnv('new')
  617. gcmd.RunCommand('i.target',
  618. parent = self,
  619. group = tgroup,
  620. location = tlocation,
  621. mapset = tmapset)
  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. p = gcmd.RunCommand('v.transform',
  839. parent = self,
  840. quiet = True,
  841. input = vect,
  842. output = outname,
  843. pointsfile = self.pointsfile)
  844. if p == 0:
  845. wx.MessageBox("All maps were georectified successfully")
  846. for vect in vectlist:
  847. outname = vect+'_'+self.extension
  848. xyvpath = os.path.join(self.grassdatabase,self.xylocation,self.xymapset,'vector',outname)
  849. vpath = os.path.join(self.grassdatabase,self.currentlocation,self.currentmapset,'vector',outname)
  850. if os.path.isfile(vpath):
  851. wx.MessageBox("%s already exists. Change extension name and georectify again" % outname)
  852. else:
  853. shutil.move(xyvpath, vpath)
  854. wx.MessageBox('For vector files with attribute tables, you will need to manually copy the tables to the new location')
  855. else:
  856. wx.MessageBox('Some maps were not georectified successfully')
  857. else:
  858. return
  859. def OnSettings(self, event):
  860. """Georectifier settings"""
  861. dlg = GrSettingsDialog(parent=self, id=wx.ID_ANY, title=_('Georectifier settings'))
  862. if dlg.ShowModal() == wx.ID_OK:
  863. pass
  864. dlg.Destroy()
  865. def OnQuit(self, event):
  866. """Quit georectifier"""
  867. self.grwiz.Cleanup()
  868. self.Destroy()
  869. event.Skip()
  870. def OnGRMethod(self, event):
  871. """
  872. sets transformation order for georectifying
  873. """
  874. if event:
  875. self.gr_order = event.GetInt() + 1
  876. numOfItems = self.list.GetItemCount()
  877. minNumOfItems = numOfItems
  878. if self.gr_order == 1:
  879. minNumOfItems = 3
  880. # self.SetStatusText(_('Insufficient points, 3+ points needed for 1st order'))
  881. elif self.gr_order == 2:
  882. minNumOfItems = 6
  883. diff = 6 - numOfItems
  884. # self.SetStatusText(_('Insufficient points, 6+ points needed for 2nd order'))
  885. elif self.gr_order == 3:
  886. minNumOfItems = 10
  887. # self.SetStatusText(_('Insufficient points, 10+ points needed for 3rd order'))
  888. for i in range(minNumOfItems - numOfItems):
  889. self.AddGCP(None)
  890. return minNumOfItems
  891. def RMSError(self, xygroup, order):
  892. """
  893. Uses g.transform to calculate forward and backward error for each used GCP
  894. in POINTS file and insert error values into GCP list.
  895. Calculates total forward and backward RMS error for all used points
  896. """
  897. # save GCPs to points file to make sure that all checked GCPs are used
  898. self.SaveGCPs(None)
  899. if self.CheckGCPcount(msg=True) == False:
  900. return
  901. # get list of forward and reverse rms error values for each point
  902. self.grwiz.SwitchEnv('new')
  903. ret = gcmd.RunCommand('g.transform',
  904. parent = self,
  905. read = True,
  906. group = xygroup,
  907. order = order)
  908. self.grwiz.SwitchEnv('original')
  909. if ret:
  910. errlist = ret.splitlines()
  911. if errlist == []:
  912. return
  913. # insert error values into GCP list for checked items
  914. i = 0
  915. sumsq_fwd_err = 0.0
  916. sumsq_bkw_err = 0.0
  917. for index in range(self.list.GetItemCount()):
  918. if self.list.IsChecked(index):
  919. fwd_err, bkw_err = errlist[i].split()
  920. self.list.SetStringItem(index, 4, fwd_err)
  921. self.list.SetStringItem(index, 5, bkw_err)
  922. sumsq_fwd_err += float(fwd_err)**2
  923. sumsq_bkw_err += float(bkw_err)**2
  924. i += 1
  925. else:
  926. self.list.SetStringItem(index, 4, '')
  927. self.list.SetStringItem(index, 5, '')
  928. # calculate RMS error
  929. self.fwd_rmserror = round((sumsq_fwd_err/i)**0.5,4)
  930. self.bkw_rmserror = round((sumsq_bkw_err/i)**0.5,4)
  931. self.list.ResizeColumns()
  932. self.SetStatusText(_('RMS error for selected points forward: %(fwd)s backward: %(bkw)s') % \
  933. { 'fwd' : self.fwd_rmserror, 'bkw' : self.bkw_rmserror })
  934. class GCPList(wx.ListCtrl,
  935. CheckListCtrlMixin,
  936. ListCtrlAutoWidthMixin):
  937. def __init__(self, parent, gcp, id=wx.ID_ANY,
  938. pos=wx.DefaultPosition, size=wx.DefaultSize,
  939. style=wx.LC_REPORT | wx.SUNKEN_BORDER | wx.LC_HRULES |
  940. wx.LC_SINGLE_SEL):
  941. wx.ListCtrl.__init__(self, parent, id, pos, size, style)
  942. # Mixin settings
  943. CheckListCtrlMixin.__init__(self)
  944. ListCtrlAutoWidthMixin.__init__(self)
  945. # TextEditMixin.__init__(self)
  946. self.gcp = gcp # GCP class
  947. # tracks whether list items are checked or not
  948. self.CheckList = []
  949. self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnItemSelected)
  950. self.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.OnItemActivated)
  951. self._Create()
  952. self.selected = wx.NOT_FOUND
  953. def _Create(self):
  954. idx_col = 0
  955. for col in (_('use| X coord'),
  956. _('Y coord'),
  957. _('E coord'),
  958. _('N coord'),
  959. _('Forward error'),
  960. _('Backward error')):
  961. self.InsertColumn(idx_col, col)
  962. idx_col += 1
  963. def LoadData(self):
  964. """Load data into list"""
  965. self.DeleteAllItems()
  966. if os.path.isfile(self.gcp.file['points']):
  967. self.gcp.ReadGCPs()
  968. else:
  969. # 3 gcp is minimum
  970. for i in range(3):
  971. self.gcp.AddGCP(None)
  972. # select first point by default
  973. self.selected = 0
  974. self.SetItemState(self.selected,
  975. wx.LIST_STATE_SELECTED,
  976. wx.LIST_STATE_SELECTED)
  977. self.ResizeColumns()
  978. def OnCheckItem(self, index, flag):
  979. """Item is checked/unchecked"""
  980. pass
  981. def AddGCPItem(self):
  982. """
  983. Appends an item to GCP list
  984. """
  985. self.Append(['0.0',
  986. '0.0',
  987. '0.0',
  988. '0.0',
  989. '',
  990. ''])
  991. self.selected = self.GetItemCount() - 1
  992. self.SetItemState(self.selected,
  993. wx.LIST_STATE_SELECTED,
  994. wx.LIST_STATE_SELECTED)
  995. self.ResizeColumns()
  996. return self.selected
  997. def DeleteGCPItem(self):
  998. """
  999. Deletes selected item in GCP list
  1000. """
  1001. if self.selected == wx.NOT_FOUND:
  1002. return
  1003. self.DeleteItem(self.selected)
  1004. if self.GetItemCount() > 0:
  1005. self.selected = self.GetItemCount() - 1
  1006. self.SetItemState(self.selected,
  1007. wx.LIST_STATE_SELECTED,
  1008. wx.LIST_STATE_SELECTED)
  1009. else:
  1010. self.selected = wx.NOT_FOUND
  1011. return self.selected
  1012. def ResizeColumns(self):
  1013. """Resize columns"""
  1014. minWidth = 90
  1015. for i in range(self.GetColumnCount()):
  1016. self.SetColumnWidth(i, wx.LIST_AUTOSIZE)
  1017. if self.GetColumnWidth(i) < minWidth:
  1018. self.SetColumnWidth(i, minWidth)
  1019. self.SendSizeEvent()
  1020. def GetSelected(self):
  1021. """Get index of selected item"""
  1022. return self.selected
  1023. def OnItemSelected(self, event):
  1024. self.selected = event.GetIndex()
  1025. def OnItemActivated(self, event):
  1026. """
  1027. When item double clicked, open editor to update coordinate values
  1028. """
  1029. coords = []
  1030. index = event.GetIndex()
  1031. for i in range(4):
  1032. coords.append(self.GetItem(index, i).GetText())
  1033. dlg = EditGPC(parent=self, id=wx.ID_ANY, data=coords)
  1034. if dlg.ShowModal() == wx.ID_OK:
  1035. values = dlg.GetValues() # string
  1036. if len(values) == 0:
  1037. wx.MessageBox(parent=self,
  1038. caption=_("Edit GCP"),
  1039. message=_("Invalid coordinate value. Operation cancelled."),
  1040. style=wx.CENTRE | wx.ICON_ERROR | wx.ID_OK)
  1041. else:
  1042. for i in range(len(values)):
  1043. if values[i] != coords[i]:
  1044. self.SetStringItem(index, i, values[i])
  1045. mapdisp = self.gcp.mapcoordlist[index]['gcpcoord'][2]
  1046. self.gcp.mapcoordlist[index]['gcpcoord'] = (float(values[0]), float(values[1]), mapdisp)
  1047. mapdisp = self.gcp.mapcoordlist[index]['mapcoord'][2]
  1048. self.gcp.mapcoordlist[index]['mapcoord'] = (float(values[0]), float(values[1]), mapdisp)
  1049. class VectGroup(wx.Dialog):
  1050. """
  1051. Dialog to create a vector group (VREF file) for georectifying
  1052. """
  1053. def __init__(self, parent, id, grassdb, location, mapset, group,
  1054. style=wx.DEFAULT_DIALOG_STYLE):
  1055. wx.Dialog.__init__(self, parent, id, style=style)
  1056. self.grassdatabase = grassdb
  1057. self.xylocation = location
  1058. self.xymapset = mapset
  1059. self.xygroup = group
  1060. # get list of valid vector directories
  1061. vectlist = os.listdir(os.path.join(self.grassdatabase,self.xylocation,self.xymapset,'vector'))
  1062. for dir in vectlist:
  1063. if os.path.isfile(os.path.join(self.grassdatabase,self.xylocation,self.xymapset,'vector',dir,'coor')):
  1064. pass
  1065. else:
  1066. vectlist.remove(dir)
  1067. self.vgrouplist = []
  1068. self.vgrpfile = os.path.join(self.grassdatabase,self.xylocation,self.xymapset,'group',self.xygroup,'VREF')
  1069. if os.path.isfile(self.vgrpfile):
  1070. f = open(self.vgrpfile)
  1071. try:
  1072. for line in f:
  1073. if line != '':
  1074. self.vgrouplist.append(line.strip(' \n'))
  1075. finally:
  1076. f.close()
  1077. self.btnCancel = wx.Button(self, wx.ID_CANCEL)
  1078. self.btnSubmit = wx.Button(self, wx.ID_OK)
  1079. self.btnSubmit.SetDefault()
  1080. sizer = wx.BoxSizer(wx.VERTICAL)
  1081. box = wx.BoxSizer(wx.HORIZONTAL)
  1082. label = wx.StaticText(parent=self, id=wx.ID_ANY,
  1083. label='Select vector map(s) to add to group:')
  1084. box.Add(label, flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.LEFT, border=5)
  1085. self.addmap = wx.CheckListBox(self, -1, wx.DefaultPosition, wx.DefaultSize, vectlist)
  1086. box.Add(self.addmap, flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT| wx.LEFT, border=5)
  1087. sizer.Add(box, flag=wx.ALIGN_RIGHT | wx.ALL, border=3)
  1088. box = wx.BoxSizer(wx.HORIZONTAL)
  1089. label = wx.StaticText(parent=self, id=wx.ID_ANY,
  1090. label='Select vector map(s) to remove from group:')
  1091. box.Add(label, flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.LEFT, border=5)
  1092. self.remmap = wx.CheckListBox(self, -1, wx.DefaultPosition, wx.DefaultSize, self.vgrouplist)
  1093. box.Add(self.remmap, flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT| wx.LEFT, border=5)
  1094. sizer.Add(box, flag=wx.ALIGN_RIGHT | wx.ALL, border=3)
  1095. # buttons
  1096. btnSizer = wx.StdDialogButtonSizer()
  1097. btnSizer.AddButton(self.btnCancel)
  1098. btnSizer.AddButton(self.btnSubmit)
  1099. btnSizer.Realize()
  1100. sizer.Add(item=btnSizer, proportion=0,
  1101. flag=wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border=5)
  1102. self.SetSizer(sizer)
  1103. sizer.Fit(self)
  1104. self.Layout()
  1105. self.Bind(wx.EVT_CHECKLISTBOX, self.AddVect, self.addmap)
  1106. self.Bind(wx.EVT_CHECKLISTBOX, self.RemoveVect, self.remmap)
  1107. def AddVect(self, event):
  1108. index = event.GetSelection()
  1109. label = self.addmap.GetString(index)
  1110. if self.addmap.IsChecked(index):
  1111. self.vgrouplist.append(label)
  1112. self.addmap.SetSelection(index)
  1113. event.Skip()
  1114. def RemoveVect(self, event):
  1115. index = event.GetSelection()
  1116. label = self.remmap.GetString(index)
  1117. if self.remmap.IsChecked(index):
  1118. self.vgrouplist.remove(label)
  1119. self.remmap.SetSelection(index)
  1120. event.Skip()
  1121. def MakeVGroup(self):
  1122. f = open(self.vgrpfile, mode='w')
  1123. for vect in self.vgrouplist:
  1124. f.write(vect+'\n')
  1125. class EditGPC(wx.Dialog):
  1126. def __init__(self, parent, data, id=wx.ID_ANY,
  1127. title=_("Edit GCP"),
  1128. style=wx.DEFAULT_DIALOG_STYLE):
  1129. """Dialog for editing GPC and map coordinates in list control"""
  1130. wx.Dialog.__init__(self, parent, id, title=title, style=style)
  1131. panel = wx.Panel(parent=self)
  1132. sizer = wx.BoxSizer(wx.VERTICAL)
  1133. box = wx.StaticBox (parent=panel, id=wx.ID_ANY,
  1134. label=" %s " % _("Ground Control Point"))
  1135. boxSizer = wx.StaticBoxSizer(box, wx.VERTICAL)
  1136. # source coordinates
  1137. gridSizer = wx.GridBagSizer(vgap=5, hgap=5)
  1138. self.xcoord = wx.TextCtrl(parent=panel, id=wx.ID_ANY, size=(150, -1))
  1139. self.ycoord = wx.TextCtrl(parent=panel, id=wx.ID_ANY, size=(150, -1))
  1140. self.ncoord = wx.TextCtrl(parent=panel, id=wx.ID_ANY, size=(150, -1))
  1141. self.ecoord = wx.TextCtrl(parent=panel, id=wx.ID_ANY, size=(150, -1))
  1142. row = 0
  1143. col = 0
  1144. idx = 0
  1145. for label, win in ((_("X:"), self.xcoord),
  1146. (_("Y:"), self.ycoord),
  1147. (_("E:"), self.ecoord),
  1148. (_("N:"), self.ncoord)):
  1149. label = wx.StaticText(parent=panel, id=wx.ID_ANY,
  1150. label=label)
  1151. gridSizer.Add(item=label,
  1152. flag=wx.ALIGN_CENTER_VERTICAL,
  1153. pos=(row, col))
  1154. col += 1
  1155. win.SetValue(str(data[idx]))
  1156. gridSizer.Add(item=win,
  1157. pos=(row, col))
  1158. col += 1
  1159. idx += 1
  1160. if col > 3:
  1161. row += 1
  1162. col = 0
  1163. boxSizer.Add(item=gridSizer, proportion=1,
  1164. flag=wx.EXPAND | wx.ALL, border=5)
  1165. sizer.Add(item=boxSizer, proportion=1,
  1166. flag=wx.EXPAND | wx.ALL, border=5)
  1167. #
  1168. # buttons
  1169. #
  1170. self.btnCancel = wx.Button(panel, wx.ID_CANCEL)
  1171. self.btnOk = wx.Button(panel, wx.ID_OK)
  1172. self.btnOk.SetDefault()
  1173. btnSizer = wx.StdDialogButtonSizer()
  1174. btnSizer.AddButton(self.btnCancel)
  1175. btnSizer.AddButton(self.btnOk)
  1176. btnSizer.Realize()
  1177. sizer.Add(item=btnSizer, proportion=0,
  1178. flag=wx.ALIGN_RIGHT | wx.ALL, border=5)
  1179. panel.SetSizer(sizer)
  1180. sizer.Fit(self)
  1181. def GetValues(self, columns=None):
  1182. """Return list of values (as strings).
  1183. """
  1184. valuelist = []
  1185. try:
  1186. float(self.xcoord.GetValue())
  1187. float(self.ycoord.GetValue())
  1188. float(self.ecoord.GetValue())
  1189. float(self.ncoord.GetValue())
  1190. except ValueError:
  1191. return valuelist
  1192. valuelist.append(self.xcoord.GetValue())
  1193. valuelist.append(self.ycoord.GetValue())
  1194. valuelist.append(self.ecoord.GetValue())
  1195. valuelist.append(self.ncoord.GetValue())
  1196. return valuelist
  1197. class GrSettingsDialog(wx.Dialog):
  1198. def __init__(self, parent, id, title, pos=wx.DefaultPosition, size=wx.DefaultSize,
  1199. style=wx.DEFAULT_DIALOG_STYLE):
  1200. wx.Dialog.__init__(self, parent, id, title, pos, size, style)
  1201. """
  1202. Dialog to set profile text options: font, title
  1203. and font size, axis labels and font size
  1204. """
  1205. #
  1206. # initialize variables
  1207. #
  1208. self.parent = parent
  1209. self.symbol = {}
  1210. self._do_layout()
  1211. def _do_layout(self):
  1212. """Do layout"""
  1213. # dialog layout
  1214. sizer = wx.BoxSizer(wx.VERTICAL)
  1215. box = wx.StaticBox(parent=self, id=wx.ID_ANY,
  1216. label=" %s " % _("Symbol settings"))
  1217. boxSizer = wx.StaticBoxSizer(box, wx.VERTICAL)
  1218. gridSizer = wx.GridBagSizer(vgap=5, hgap=5)
  1219. gridSizer.AddGrowableCol(1)
  1220. #
  1221. # symbol color
  1222. #
  1223. row = 0
  1224. label = wx.StaticText(parent=self, id=wx.ID_ANY, label=_("Color:"))
  1225. gridSizer.Add(item=label, flag=wx.ALIGN_CENTER_VERTICAL, pos=(row, 0))
  1226. col = UserSettings.Get(group='georect', key='symbol', subkey='color')
  1227. colWin = csel.ColourSelect(parent=self, id=wx.ID_ANY,
  1228. colour=wx.Colour(col[0],
  1229. col[1],
  1230. col[2],
  1231. 255))
  1232. self.symbol['color'] = colWin.GetId()
  1233. gridSizer.Add(item=colWin,
  1234. flag=wx.ALIGN_RIGHT,
  1235. pos=(row, 1))
  1236. #
  1237. # symbol width
  1238. #
  1239. row += 1
  1240. label = wx.StaticText(parent=self, id=wx.ID_ANY, label=_("Width:"))
  1241. gridSizer.Add(item=label, flag=wx.ALIGN_CENTER_VERTICAL, pos=(row, 0))
  1242. width = int(UserSettings.Get(group='georect', key='symbol', subkey='width'))
  1243. widWin = wx.SpinCtrl(parent=self, id=wx.ID_ANY,
  1244. min=1, max=10)
  1245. widWin.SetValue(width)
  1246. self.symbol['width'] = widWin.GetId()
  1247. gridSizer.Add(item=widWin,
  1248. flag=wx.ALIGN_RIGHT,
  1249. pos=(row, 1))
  1250. boxSizer.Add(item=gridSizer, flag=wx.EXPAND)
  1251. sizer.Add(item=boxSizer, flag=wx.EXPAND | wx.ALL, border=5)
  1252. line = wx.StaticLine(parent=self, id=wx.ID_ANY, size=(20, -1), style=wx.LI_HORIZONTAL)
  1253. sizer.Add(item=line, proportion=0,
  1254. flag=wx.GROW|wx.ALIGN_CENTER_VERTICAL|wx.LEFT|wx.RIGHT, border=3)
  1255. #
  1256. # buttons
  1257. #
  1258. btnSave = wx.Button(self, wx.ID_SAVE)
  1259. btnApply = wx.Button(self, wx.ID_APPLY)
  1260. btnCancel = wx.Button(self, wx.ID_CANCEL)
  1261. btnSave.SetDefault()
  1262. # bindigs
  1263. btnApply.Bind(wx.EVT_BUTTON, self.OnApply)
  1264. btnApply.SetToolTipString(_("Apply changes for the current session"))
  1265. btnSave.Bind(wx.EVT_BUTTON, self.OnSave)
  1266. btnSave.SetToolTipString(_("Apply and save changes to user settings file (default for next sessions)"))
  1267. btnSave.SetDefault()
  1268. btnCancel.Bind(wx.EVT_BUTTON, self.OnCancel)
  1269. btnCancel.SetToolTipString(_("Close dialog and ignore changes"))
  1270. # sizers
  1271. btnStdSizer = wx.StdDialogButtonSizer()
  1272. btnStdSizer.AddButton(btnCancel)
  1273. btnStdSizer.AddButton(btnSave)
  1274. btnStdSizer.AddButton(btnApply)
  1275. btnStdSizer.Realize()
  1276. sizer.Add(item=btnStdSizer, proportion=0, flag=wx.ALIGN_RIGHT | wx.ALL, border=5)
  1277. self.SetSizer(sizer)
  1278. sizer.Fit(self)
  1279. def UpdateSettings(self):
  1280. UserSettings.Set(group='georect', key='symbol', subkey='color',
  1281. value=wx.FindWindowById(self.symbol['color']).GetColour())
  1282. UserSettings.Set(group='georect', key='symbol', subkey='width',
  1283. value=wx.FindWindowById(self.symbol['width']).GetValue())
  1284. def OnSave(self, event):
  1285. """Button 'Save' pressed"""
  1286. self.UpdateSettings()
  1287. fileSettings = {}
  1288. UserSettings.ReadSettingsFile(settings=fileSettings)
  1289. fileSettings['georect'] = UserSettings.Get(group='georect')
  1290. file = UserSettings.SaveToFile(fileSettings)
  1291. self.parent.parent.goutput.WriteLog(_('Georectifier settings saved to file \'%s\'.') % file)
  1292. self.Close()
  1293. def OnApply(self, event):
  1294. """Button 'Apply' pressed"""
  1295. self.UpdateSettings()
  1296. self.Close()
  1297. def OnCancel(self, event):
  1298. """Button 'Cancel' pressed"""
  1299. self.Close()