georect.py 55 KB

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