georect.py 63 KB

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