gcpmanager.py 104 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804
  1. """!
  2. @package gcpmanager.py
  3. @brief Georectification module for GRASS GIS. Includes ground control
  4. point management and interactive point and click GCP creation
  5. Classes:
  6. - GCPWizard
  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. @author Markus Metz redesign georectfier -> GCP Manager
  21. """
  22. import os
  23. import sys
  24. import tempfile
  25. import shutil
  26. import time
  27. import cStringIO
  28. import wx
  29. from wx.lib.mixins.listctrl import CheckListCtrlMixin, ColumnSorterMixin, ListCtrlAutoWidthMixin
  30. import wx.lib.colourselect as csel
  31. import wx.wizard as wiz
  32. import grass.script as grass
  33. import globalvar
  34. import render
  35. import toolbars
  36. import menuform
  37. import gselect
  38. import gcmd
  39. import utils
  40. from debug import Debug as Debug
  41. from icon import Icons as Icons
  42. from location_wizard import TitledPage as TitledPage
  43. from preferences import globalSettings as UserSettings
  44. from gcpmapdisp import MapFrame
  45. from mapdisp_window import BufferedWindow
  46. try:
  47. import subprocess # Not needed if GRASS commands could actually be quiet
  48. except:
  49. CompatPath = globalvar.ETCWXDIR
  50. sys.path.append(CompatPath)
  51. from compat import subprocess
  52. gmpath = os.path.join(globalvar.ETCWXDIR, "icons")
  53. sys.path.append(gmpath)
  54. imgpath = os.path.join(globalvar.ETCWXDIR, "images")
  55. #
  56. # global variables
  57. #
  58. global src_map
  59. global tgt_map
  60. global maptype
  61. src_map = ''
  62. tgt_map = ''
  63. maptype = 'cell'
  64. def getSmallUpArrowImage():
  65. stream = open(os.path.join(imgpath, 'small_up_arrow.png'), 'rb')
  66. try:
  67. img = wx.ImageFromStream(stream)
  68. finally:
  69. stream.close()
  70. return img
  71. def getSmallDnArrowImage():
  72. stream = open(os.path.join(imgpath, 'small_down_arrow.png'), 'rb')
  73. try:
  74. img = wx.ImageFromStream(stream)
  75. finally:
  76. stream.close()
  77. stream.close()
  78. return img
  79. class GCPWizard(object):
  80. """
  81. Start wizard here and finish wizard here
  82. """
  83. def __init__(self, parent):
  84. self.parent = parent # GMFrame
  85. #
  86. # get environmental variables
  87. #
  88. self.grassdatabase = grass.gisenv()['GISDBASE']
  89. #
  90. # read original environment settings
  91. #
  92. self.target_gisrc = os.environ['GISRC']
  93. self.gisrc_dict = {}
  94. try:
  95. f = open(self.target_gisrc, 'r')
  96. for line in f.readlines():
  97. line = line.replace('\n', '').strip()
  98. if len(line) < 1:
  99. continue
  100. key, value = line.split(':', 1)
  101. self.gisrc_dict[key.strip()] = value.strip()
  102. finally:
  103. f.close()
  104. self.currentlocation = self.gisrc_dict['LOCATION_NAME']
  105. self.currentmapset = self.gisrc_dict['MAPSET']
  106. # location for xy map to georectify
  107. self.newlocation = ''
  108. # mapset for xy map to georectify
  109. self.newmapset = ''
  110. global maptype
  111. global src_map
  112. global tgt_map
  113. src_map = ''
  114. tgt_map = ''
  115. maptype = 'cell'
  116. # GISRC file for source location/mapset of map(s) to georectify
  117. self.source_gisrc = ''
  118. self.src_maps = []
  119. #
  120. # define wizard pages
  121. #
  122. self.wizard = wiz.Wizard(parent=parent, id=wx.ID_ANY, title=_("Setup for georectification"))
  123. self.startpage = LocationPage(self.wizard, self)
  124. self.grouppage = GroupPage(self.wizard, self)
  125. self.mappage = DispMapPage(self.wizard, self)
  126. #
  127. # set the initial order of the pages
  128. #
  129. self.startpage.SetNext(self.grouppage)
  130. self.grouppage.SetPrev(self.startpage)
  131. self.grouppage.SetNext(self.mappage)
  132. self.mappage.SetPrev(self.grouppage)
  133. #
  134. # do pages layout
  135. #
  136. self.startpage.DoLayout()
  137. self.grouppage.DoLayout()
  138. self.mappage.DoLayout()
  139. self.wizard.FitToPage(self.startpage)
  140. # self.Bind(wx.EVT_CLOSE, self.Cleanup)
  141. # self.parent.Bind(wx.EVT_ACTIVATE, self.OnGLMFocus)
  142. success = False
  143. #
  144. # run wizard
  145. #
  146. if self.wizard.RunWizard(self.startpage):
  147. success = self.OnWizFinished()
  148. if success == False:
  149. wx.MessageBox(parent=self.parent,
  150. message=_("Georectifying setup canceled."),
  151. caption=_("Georectify"),
  152. style=wx.OK | wx.ICON_INFORMATION | wx.CENTRE)
  153. self.Cleanup()
  154. else:
  155. wx.MessageBox(parent=self.parent,
  156. message=_("Georectifying setup canceled."),
  157. caption=_("Georectify"),
  158. style=wx.OK | wx.ICON_INFORMATION | wx.CENTRE)
  159. self.Cleanup()
  160. #
  161. # start GCP display
  162. #
  163. if success != False:
  164. # instance of render.Map to be associated with display
  165. self.SwitchEnv('source')
  166. self.SrcMap = render.Map(gisrc=self.source_gisrc)
  167. self.SwitchEnv('target')
  168. self.TgtMap = render.Map(gisrc=self.target_gisrc)
  169. self.Map = self.SrcMap
  170. #
  171. # add layer to source map
  172. #
  173. if maptype == 'cell':
  174. rendertype = 'raster'
  175. cmdlist = ['d.rast', 'map=%s' % src_map]
  176. else: # -> vector layer
  177. rendertype = 'vector'
  178. cmdlist = ['d.vect', 'map=%s' % src_map]
  179. self.SwitchEnv('source')
  180. self.SrcMap.AddLayer(type=rendertype, command=cmdlist, l_active=True,
  181. name=utils.GetLayerNameFromCmd(cmdlist),
  182. l_hidden=False, l_opacity=1.0, l_render=False)
  183. if tgt_map:
  184. #
  185. # add layer to target map
  186. #
  187. if maptype == 'cell':
  188. rendertype = 'raster'
  189. cmdlist = ['d.rast', 'map=%s' % tgt_map]
  190. else: # -> vector layer
  191. rendertype = 'vector'
  192. cmdlist = ['d.vect', 'map=%s' % tgt_map]
  193. self.SwitchEnv('target')
  194. self.TgtMap.AddLayer(type=rendertype, command=cmdlist, l_active=True,
  195. name=utils.GetLayerNameFromCmd(cmdlist),
  196. l_hidden=False, l_opacity=1.0, l_render=False)
  197. #
  198. # start GCP Manager
  199. #
  200. self.gcpmgr = GCP(self.parent, grwiz=self, size=globalvar.MAP_WINDOW_SIZE,
  201. toolbars=["gcpdisp"],
  202. Map=self.SrcMap, lmgr=self.parent)
  203. # load GCPs
  204. self.gcpmgr.InitMapDisplay()
  205. self.gcpmgr.CenterOnScreen()
  206. self.gcpmgr.Show()
  207. # need to update AUI here for wingrass
  208. self.gcpmgr._mgr.Update()
  209. else:
  210. self.Cleanup()
  211. def SetSrcEnv(self, location, mapset):
  212. """!Create environment to use for location and mapset
  213. that are the source of the file(s) to georectify
  214. @param location source location
  215. @param mapset source mapset
  216. @return False on error
  217. @return True on success
  218. """
  219. self.newlocation = location
  220. self.newmapset = mapset
  221. # check to see if we are georectifying map in current working location/mapset
  222. if self.newlocation == self.currentlocation and self.newmapset == self.currentmapset:
  223. return False
  224. self.gisrc_dict['LOCATION_NAME'] = location
  225. self.gisrc_dict['MAPSET'] = mapset
  226. self.source_gisrc = utils.GetTempfile()
  227. try:
  228. f = open(self.source_gisrc, mode='w')
  229. for line in self.gisrc_dict.items():
  230. f.write(line[0] + ": " + line[1] + "\n")
  231. finally:
  232. f.close()
  233. return True
  234. def SwitchEnv(self, grc):
  235. """
  236. Switches between original working location/mapset and
  237. location/mapset that is source of file(s) to georectify
  238. """
  239. # check to see if we are georectifying map in current working location/mapset
  240. if self.newlocation == self.currentlocation and self.newmapset == self.currentmapset:
  241. return False
  242. if grc == 'target':
  243. os.environ['GISRC'] = str(self.target_gisrc)
  244. elif grc == 'source':
  245. os.environ['GISRC'] = str(self.source_gisrc)
  246. return True
  247. def OnWizFinished(self):
  248. # self.Cleanup()
  249. return True
  250. def OnGLMFocus(self, event):
  251. """!Layer Manager focus"""
  252. # self.SwitchEnv('target')
  253. event.Skip()
  254. def Cleanup(self):
  255. """!Return to current location and mapset"""
  256. self.SwitchEnv('target')
  257. self.parent.gcpmanagement = None
  258. self.wizard.Destroy()
  259. class LocationPage(TitledPage):
  260. """
  261. Set map type (raster or vector) to georectify and
  262. select location/mapset of map(s) to georectify.
  263. """
  264. def __init__(self, wizard, parent):
  265. TitledPage.__init__(self, wizard, _("Select map type and location/mapset"))
  266. self.parent = parent
  267. self.grassdatabase = self.parent.grassdatabase
  268. self.xylocation = ''
  269. self.xymapset = ''
  270. #
  271. # layout
  272. #
  273. self.sizer.AddGrowableCol(2)
  274. # map type
  275. self.rb_maptype = wx.RadioBox(parent=self, id=wx.ID_ANY,
  276. label=' %s ' % _("Map type to georectify"),
  277. choices=[_('raster'), _('vector')],
  278. majorDimension=wx.RA_SPECIFY_COLS)
  279. self.sizer.Add(item=self.rb_maptype,
  280. flag=wx.ALIGN_CENTER | wx.ALL | wx.EXPAND, border=5,
  281. pos=(1, 1), span=(1, 2))
  282. # location
  283. self.sizer.Add(item=wx.StaticText(parent=self, id=wx.ID_ANY, label=_('Select source location:')),
  284. flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5,
  285. pos=(2, 1))
  286. self.cb_location = gselect.LocationSelect(parent = self, gisdbase = self.grassdatabase)
  287. self.sizer.Add(item=self.cb_location,
  288. flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5,
  289. pos=(2, 2))
  290. # mapset
  291. self.sizer.Add(item=wx.StaticText(parent=self, id=wx.ID_ANY, label=_('Select source mapset:')),
  292. flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5,
  293. pos=(3, 1))
  294. self.cb_mapset = gselect.MapsetSelect(parent = self, gisdbase = self.grassdatabase,
  295. setItems = False)
  296. self.sizer.Add(item=self.cb_mapset,
  297. flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5,
  298. pos=(3,2))
  299. #
  300. # bindings
  301. #
  302. self.Bind(wx.EVT_RADIOBOX, self.OnMaptype, self.rb_maptype)
  303. self.Bind(wx.EVT_COMBOBOX, self.OnLocation, self.cb_location)
  304. self.Bind(wx.EVT_COMBOBOX, self.OnMapset, self.cb_mapset)
  305. self.Bind(wiz.EVT_WIZARD_PAGE_CHANGING, self.OnPageChanging)
  306. self.Bind(wiz.EVT_WIZARD_PAGE_CHANGED, self.OnEnterPage)
  307. # self.Bind(wx.EVT_CLOSE, self.parent.Cleanup)
  308. def OnMaptype(self,event):
  309. """!Change map type"""
  310. global maptype
  311. if event.GetInt() == 0:
  312. maptype = 'cell'
  313. else:
  314. maptype = 'vector'
  315. def OnLocation(self, event):
  316. """!Sets source location for map(s) to georectify"""
  317. self.xylocation = event.GetString()
  318. #create a list of valid mapsets
  319. tmplist = os.listdir(os.path.join(self.grassdatabase, self.xylocation))
  320. self.mapsetList = []
  321. for item in tmplist:
  322. if os.path.isdir(os.path.join(self.grassdatabase, self.xylocation, item)) and \
  323. os.path.exists(os.path.join(self.grassdatabase, self.xylocation, item, 'WIND')):
  324. if item != 'PERMANENT':
  325. self.mapsetList.append(item)
  326. self.xymapset = 'PERMANENT'
  327. utils.ListSortLower(self.mapsetList)
  328. self.mapsetList.insert(0, 'PERMANENT')
  329. self.cb_mapset.SetItems(self.mapsetList)
  330. self.cb_mapset.SetStringSelection(self.xymapset)
  331. if not wx.FindWindowById(wx.ID_FORWARD).IsEnabled():
  332. wx.FindWindowById(wx.ID_FORWARD).Enable(True)
  333. def OnMapset(self, event):
  334. """!Sets source mapset for map(s) to georectify"""
  335. if self.xylocation == '':
  336. wx.MessageBox(_('You must select a valid location before selecting a mapset'))
  337. return
  338. self.xymapset = event.GetString()
  339. if not wx.FindWindowById(wx.ID_FORWARD).IsEnabled():
  340. wx.FindWindowById(wx.ID_FORWARD).Enable(True)
  341. def OnPageChanging(self, event=None):
  342. if event.GetDirection() and \
  343. (self.xylocation == '' or self.xymapset == ''):
  344. wx.MessageBox(_('You must select a valid location and mapset in order to continue'))
  345. event.Veto()
  346. return
  347. self.parent.SetSrcEnv(self.xylocation, self.xymapset)
  348. def OnEnterPage(self, event=None):
  349. if self.xylocation == '' or self.xymapset == '':
  350. wx.FindWindowById(wx.ID_FORWARD).Enable(False)
  351. else:
  352. wx.FindWindowById(wx.ID_FORWARD).Enable(True)
  353. class GroupPage(TitledPage):
  354. """
  355. Set group to georectify. Create group if desired.
  356. """
  357. def __init__(self, wizard, parent):
  358. TitledPage.__init__(self, wizard, _("Select image/map group to georectify"))
  359. self.parent = parent
  360. self.grassdatabase = self.parent.grassdatabase
  361. self.groupList = []
  362. self.xylocation = ''
  363. self.xymapset = ''
  364. self.xygroup = ''
  365. # default extension
  366. self.extension = '.georect' + str(os.getpid())
  367. #
  368. # layout
  369. #
  370. self.sizer.AddGrowableCol(2)
  371. # group
  372. self.sizer.Add(item=wx.StaticText(parent=self, id=wx.ID_ANY, label=_('Select group:')),
  373. flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5,
  374. pos=(1, 1))
  375. self.cb_group = wx.ComboBox(parent=self, id=wx.ID_ANY,
  376. choices=self.groupList, size=(350, -1),
  377. style=wx.CB_DROPDOWN | wx.CB_READONLY)
  378. self.sizer.Add(item=self.cb_group,
  379. flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5,
  380. pos=(1, 2))
  381. # create group
  382. self.sizer.Add(item=wx.StaticText(parent=self, id=wx.ID_ANY, label=_('Create group if none exists')),
  383. flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5,
  384. pos=(2, 1))
  385. btnSizer = wx.BoxSizer(wx.HORIZONTAL)
  386. self.btn_mkgroup = wx.Button(parent=self, id=wx.ID_ANY, label=_("Create/edit group..."))
  387. self.btn_vgroup = wx.Button(parent=self, id=wx.ID_ANY, label=_("Add vector map to group..."))
  388. btnSizer.Add(item=self.btn_mkgroup,
  389. flag=wx.RIGHT, border=5)
  390. btnSizer.Add(item=self.btn_vgroup,
  391. flag=wx.LEFT, border=5)
  392. self.sizer.Add(item=btnSizer,
  393. flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5,
  394. pos=(2, 2))
  395. # extension
  396. self.sizer.Add(item=wx.StaticText(parent=self, id=wx.ID_ANY, label=_('Extension for output maps:')),
  397. flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5,
  398. pos=(3, 1))
  399. self.ext_txt = wx.TextCtrl(parent=self, id=wx.ID_ANY, value="", size=(350,-1))
  400. self.ext_txt.SetValue(self.extension)
  401. self.sizer.Add(item=self.ext_txt,
  402. flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5,
  403. pos=(3, 2))
  404. #
  405. # bindings
  406. #
  407. self.Bind(wx.EVT_COMBOBOX, self.OnGroup, self.cb_group)
  408. self.Bind(wx.EVT_TEXT, self.OnExtension, self.ext_txt)
  409. self.Bind(wiz.EVT_WIZARD_PAGE_CHANGING, self.OnPageChanging)
  410. self.Bind(wiz.EVT_WIZARD_PAGE_CHANGED, self.OnEnterPage)
  411. self.Bind(wx.EVT_CLOSE, self.parent.Cleanup)
  412. # hide vector group button by default
  413. self.btn_vgroup.Hide()
  414. def OnGroup(self, event):
  415. self.xygroup = event.GetString()
  416. def OnMkGroup(self, event):
  417. """!Create new group in source location/mapset"""
  418. menuform.GUI().ParseCommand(['i.group'],
  419. completed=(self.GetOptData, None, ''),
  420. parentframe=self.parent.parent, modal=True)
  421. def OnVGroup(self, event):
  422. """!Add vector maps to group"""
  423. dlg = VectGroup(parent = self,
  424. id = wx.ID_ANY,
  425. grassdb = self.grassdatabase,
  426. location = self.xylocation,
  427. mapset = self.xymapset,
  428. group = self.xygroup)
  429. if dlg.ShowModal() != wx.ID_OK:
  430. return
  431. dlg.MakeVGroup()
  432. self.OnEnterPage()
  433. def GetOptData(self, dcmd, layer, params, propwin):
  434. """!Process i.group"""
  435. # update the page
  436. if dcmd:
  437. gcmd.Command(dcmd)
  438. self.OnEnterPage()
  439. self.Update()
  440. def OnExtension(self, event):
  441. self.extension = event.GetString()
  442. def OnPageChanging(self, event=None):
  443. if event.GetDirection() and self.xygroup == '':
  444. wx.MessageBox(_('You must select a valid image/map group in order to continue'))
  445. event.Veto()
  446. return
  447. if event.GetDirection() and self.extension == '':
  448. wx.MessageBox(_('You must enter an map name extension in order to continue'))
  449. event.Veto()
  450. return
  451. def OnEnterPage(self, event=None):
  452. global maptype
  453. self.groupList = []
  454. self.xylocation = self.parent.gisrc_dict['LOCATION_NAME']
  455. self.xymapset = self.parent.gisrc_dict['MAPSET']
  456. # create a list of groups in selected mapset
  457. if os.path.isdir(os.path.join(self.grassdatabase,
  458. self.xylocation,
  459. self.xymapset,
  460. 'group')):
  461. tmplist = os.listdir(os.path.join(self.grassdatabase,
  462. self.xylocation,
  463. self.xymapset,
  464. 'group'))
  465. for item in tmplist:
  466. if os.path.isdir(os.path.join(self.grassdatabase,
  467. self.xylocation,
  468. self.xymapset,
  469. 'group',
  470. item)):
  471. self.groupList.append(item)
  472. if maptype == 'cell':
  473. self.btn_vgroup.Hide()
  474. self.Bind(wx.EVT_BUTTON, self.OnMkGroup, self.btn_mkgroup)
  475. elif maptype == 'vector':
  476. self.btn_vgroup.Show()
  477. self.Bind(wx.EVT_BUTTON, self.OnMkGroup, self.btn_mkgroup)
  478. self.Bind(wx.EVT_BUTTON, self.OnVGroup, self.btn_vgroup)
  479. utils.ListSortLower(self.groupList)
  480. self.cb_group.SetItems(self.groupList)
  481. if len(self.groupList) > 0 and \
  482. self.xygroup == '':
  483. self.cb_group.SetSelection(0)
  484. self.xygroup = self.groupList[0]
  485. if self.xygroup == '' or \
  486. self.extension == '':
  487. wx.FindWindowById(wx.ID_FORWARD).Enable(False)
  488. else:
  489. wx.FindWindowById(wx.ID_FORWARD).Enable(True)
  490. # switch to source
  491. self.parent.SwitchEnv('source')
  492. class DispMapPage(TitledPage):
  493. """
  494. Select ungeoreferenced map to display for interactively
  495. setting ground control points (GCPs).
  496. """
  497. def __init__(self, wizard, parent):
  498. TitledPage.__init__(self, wizard,
  499. _("Select maps to display for ground control point (GCP) creation"))
  500. self.parent = parent
  501. global maptype
  502. #
  503. # layout
  504. #
  505. self.sizer.Add(item=wx.StaticText(parent=self, id=wx.ID_ANY, label=_('Select source map to display:')),
  506. flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5,
  507. pos=(1, 1))
  508. self.srcselection = gselect.Select(self, id=wx.ID_ANY,
  509. size=globalvar.DIALOG_GSELECT_SIZE, type=maptype, updateOnPopup = False)
  510. self.sizer.Add(item=self.srcselection,
  511. flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5,
  512. pos=(1, 2))
  513. self.sizer.Add(item=wx.StaticText(parent=self, id=wx.ID_ANY, label=_('Select target map to display:')),
  514. flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5,
  515. pos=(2, 1))
  516. self.tgtselection = gselect.Select(self, id=wx.ID_ANY,
  517. size=globalvar.DIALOG_GSELECT_SIZE, type=maptype, updateOnPopup = False)
  518. self.sizer.Add(item=self.tgtselection,
  519. flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5,
  520. pos=(2, 2))
  521. #
  522. # bindings
  523. #
  524. self.srcselection.Bind(wx.EVT_TEXT, self.OnSrcSelection)
  525. self.tgtselection.Bind(wx.EVT_TEXT, self.OnTgtSelection)
  526. self.Bind(wiz.EVT_WIZARD_PAGE_CHANGING, self.OnPageChanging)
  527. self.Bind(wiz.EVT_WIZARD_PAGE_CHANGED, self.OnEnterPage)
  528. self.Bind(wx.EVT_CLOSE, self.parent.Cleanup)
  529. def OnSrcSelection(self,event):
  530. """!Source map to display selected"""
  531. global src_map
  532. global maptype
  533. src_map = event.GetString()
  534. if src_map == '':
  535. wx.FindWindowById(wx.ID_FORWARD).Enable(False)
  536. else:
  537. wx.FindWindowById(wx.ID_FORWARD).Enable(True)
  538. try:
  539. # set computational region to match selected map and zoom display to region
  540. if maptype == 'cell':
  541. p = gcmd.Command(['g.region', 'rast=src_map'])
  542. elif maptype == 'vector':
  543. p = gcmd.Command(['g.region', 'vect=src_map'])
  544. if p.returncode == 0:
  545. print 'returncode = ', str(p.returncode)
  546. self.parent.Map.region = self.parent.Map.GetRegion()
  547. except:
  548. pass
  549. def OnTgtSelection(self,event):
  550. """!Source map to display selected"""
  551. global tgt_map
  552. tgt_map = event.GetString()
  553. def OnPageChanging(self, event=None):
  554. global src_map
  555. global tgt_map
  556. if event.GetDirection() and (src_map == ''):
  557. wx.MessageBox(_('You must select a source map in order to continue'))
  558. event.Veto()
  559. return
  560. self.parent.SwitchEnv('target')
  561. def OnEnterPage(self, event=None):
  562. global maptype
  563. global src_map
  564. global tgt_map
  565. self.srcselection.SetElementList(maptype)
  566. ret = gcmd.RunCommand('i.group',
  567. parent = self,
  568. read = True,
  569. group = self.parent.grouppage.xygroup,
  570. flags = 'g')
  571. if ret:
  572. self.parent.src_maps = ret.splitlines()
  573. else:
  574. wx.MessageBox(parent=self,
  575. caption=_("Select maps to display"),
  576. message=_('No maps in selected group <%s>. \n'
  577. 'Please edit group or select another group.') %
  578. self.parent.grouppage.xygroup,
  579. style=wx.ICON_ERROR | wx.ID_OK | wx.CENTRE)
  580. return
  581. # filter out all maps not in group
  582. self.srcselection.tcp.GetElementList(elements = self.parent.src_maps)
  583. src_map = self.parent.src_maps[0]
  584. self.srcselection.SetValue(src_map)
  585. self.parent.SwitchEnv('target')
  586. self.tgtselection.SetElementList(maptype)
  587. self.tgtselection.GetElementList()
  588. self.parent.SwitchEnv('source')
  589. if src_map == '':
  590. wx.FindWindowById(wx.ID_FORWARD).Enable(False)
  591. else:
  592. wx.FindWindowById(wx.ID_FORWARD).Enable(True)
  593. class GCP(MapFrame, wx.Frame, ColumnSorterMixin):
  594. """!
  595. Manages ground control points for georectifying. Calculates RMS statics.
  596. Calls i.rectify or v.transform to georectify map.
  597. """
  598. def __init__(self, parent, grwiz = None, id = wx.ID_ANY,
  599. title = _("Manage Ground Control Points"),
  600. size = (700, 300), toolbars=["gcpdisp"], Map=None, lmgr=None):
  601. self.grwiz = grwiz # GR Wizard
  602. if tgt_map == '':
  603. self.show_target = False
  604. else:
  605. self.show_target = True
  606. #wx.Frame.__init__(self, parent, id, title, size = size, name = "GCPFrame")
  607. MapFrame.__init__(self, parent, id, title, size = size,
  608. Map=Map, toolbars=["gcpdisp"], lmgr=lmgr, name='GCPMapWindow')
  609. #
  610. # init variables
  611. #
  612. self.parent = parent # GMFrame
  613. self.parent.gcpmanagement = self
  614. self.grassdatabase = self.grwiz.grassdatabase
  615. self.currentlocation = self.grwiz.currentlocation
  616. self.currentmapset = self.grwiz.currentmapset
  617. self.newlocation = self.grwiz.newlocation
  618. self.newmapset = self.grwiz.newmapset
  619. self.xylocation = self.grwiz.gisrc_dict['LOCATION_NAME']
  620. self.xymapset = self.grwiz.gisrc_dict['MAPSET']
  621. self.xygroup = self.grwiz.grouppage.xygroup
  622. self.src_maps = self.grwiz.src_maps
  623. self.extension = self.grwiz.grouppage.extension
  624. self.outname = ''
  625. self.VectGRList = []
  626. self.file = {
  627. 'points' : os.path.join(self.grassdatabase,
  628. self.xylocation,
  629. self.xymapset,
  630. 'group',
  631. self.xygroup,
  632. 'POINTS'),
  633. 'points_bak' : os.path.join(self.grassdatabase,
  634. self.xylocation,
  635. self.xymapset,
  636. 'group',
  637. self.xygroup,
  638. 'POINTS_BAK'),
  639. 'rgrp' : os.path.join(self.grassdatabase,
  640. self.xylocation,
  641. self.xymapset,
  642. 'group',
  643. self.xygroup,
  644. 'REF'),
  645. 'vgrp' : os.path.join(self.grassdatabase,
  646. self.xylocation,
  647. self.xymapset,
  648. 'group',
  649. self.xygroup,
  650. 'VREF'),
  651. 'target' : os.path.join(self.grassdatabase,
  652. self.xylocation,
  653. self.xymapset,
  654. 'group',
  655. self.xygroup,
  656. 'TARGET'),
  657. }
  658. # make a backup of the current points file
  659. if os.path.exists(self.file['points']):
  660. shutil.copy(self.file['points'], self.file['points_bak'])
  661. # polynomial order transformation for georectification
  662. self.gr_order = 1
  663. # interpolation method for georectification
  664. self.gr_method = 'nearest'
  665. # region clipping for georectified map
  666. self.clip_to_region = False
  667. # number of GCPs selected to be used for georectification (checked)
  668. self.GCPcount = 0
  669. # forward RMS error
  670. self.fwd_rmserror = 0.0
  671. # backward RMS error
  672. self.bkw_rmserror = 0.0
  673. # list map coords and ID of map display they came from
  674. self.mapcoordlist = []
  675. self.mapcoordlist.append([ 0, # GCP number
  676. 0.0, # source east
  677. 0.0, # source north
  678. 0.0, # target east
  679. 0.0, # target north
  680. 0.0, # forward error
  681. 0.0 ] ) # backward error
  682. # init vars to highlight high RMS errors
  683. self.highest_only = True
  684. self.show_unused = True
  685. self.highest_key = -1
  686. self.rmsthresh = 0
  687. self.rmsmean = 0
  688. self.rmssd = 0
  689. self.SetTarget(self.xygroup, self.currentlocation, self.currentmapset)
  690. self.itemDataMap = None
  691. # images for column sorting
  692. # CheckListCtrlMixin must set an ImageList first
  693. self.il = self.list.GetImageList(wx.IMAGE_LIST_SMALL)
  694. SmallUpArrow = wx.BitmapFromImage(getSmallUpArrowImage())
  695. SmallDnArrow = wx.BitmapFromImage(getSmallDnArrowImage())
  696. self.sm_dn = self.il.Add(SmallDnArrow)
  697. self.sm_up = self.il.Add(SmallUpArrow)
  698. # set mouse characteristics
  699. self.mapwin = self.SrcMapWindow
  700. self.mapwin.mouse['box'] = 'point'
  701. self.mapwin.mouse["use"] == "pointer"
  702. self.mapwin.zoomtype = 0
  703. self.mapwin.pen = wx.Pen(colour='black', width=2, style=wx.SOLID)
  704. self.mapwin.SetCursor(self.cursors["cross"])
  705. self.mapwin = self.TgtMapWindow
  706. # set mouse characteristics
  707. self.mapwin.mouse['box'] = 'point'
  708. self.mapwin.mouse["use"] == "pointer"
  709. self.mapwin.zoomtype = 0
  710. self.mapwin.pen = wx.Pen(colour='black', width=2, style=wx.SOLID)
  711. self.mapwin.SetCursor(self.cursors["cross"])
  712. #
  713. # show new display & draw map
  714. #
  715. if self.show_target:
  716. self.MapWindow = self.TgtMapWindow
  717. self.Map = self.TgtMap
  718. self.OnZoomToMap(None)
  719. self.MapWindow = self.SrcMapWindow
  720. self.Map = self.SrcMap
  721. self.OnZoomToMap(None)
  722. #
  723. # bindings
  724. #
  725. self.Bind(wx.EVT_ACTIVATE, self.OnFocus)
  726. self.Bind(wx.EVT_CLOSE, self.OnQuit)
  727. def __del__(self):
  728. """!Disable GCP manager mode"""
  729. self.parent.gcpmanagement = None
  730. def CreateGCPList(self):
  731. """!Create GCP List Control"""
  732. return GCPList(parent=self, gcp=self)
  733. # Used by the ColumnSorterMixin, see wx/lib/mixins/listctrl.py
  734. def GetListCtrl(self):
  735. return self.list
  736. # Used by the ColumnSorterMixin, see wx/lib/mixins/listctrl.py
  737. def GetSortImages(self):
  738. return (self.sm_dn, self.sm_up)
  739. def InitMapDisplay(self):
  740. self.list.LoadData()
  741. # initialize column sorter
  742. self.itemDataMap = self.mapcoordlist
  743. ncols = self.list.GetColumnCount()
  744. ColumnSorterMixin.__init__(self, ncols)
  745. # init to ascending sort on first click
  746. self._colSortFlag = [1] * ncols
  747. def SetTarget(self, tgroup, tlocation, tmapset):
  748. """
  749. Sets rectification target to current location and mapset
  750. """
  751. # check to see if we are georectifying map in current working location/mapset
  752. if self.newlocation == self.currentlocation and self.newmapset == self.currentmapset:
  753. gcmd.RunCommand('i.target',
  754. parent = self,
  755. flags = 'c',
  756. group = tgroup)
  757. else:
  758. self.grwiz.SwitchEnv('source')
  759. gcmd.RunCommand('i.target',
  760. parent = self,
  761. group = tgroup,
  762. location = tlocation,
  763. mapset = tmapset)
  764. self.grwiz.SwitchEnv('target')
  765. def AddGCP(self, event):
  766. """
  767. Appends an item to GCP list
  768. """
  769. keyval = self.list.AddGCPItem() + 1
  770. # source east, source north, target east, target north, forward error, backward error
  771. self.mapcoordlist.append([ keyval, # GCP number
  772. 0.0, # source east
  773. 0.0, # source north
  774. 0.0, # target east
  775. 0.0, # target north
  776. 0.0, # forward error
  777. 0.0 ] ) # backward error
  778. if self.statusbarWin['toggle'].GetSelection() == 7: # go to
  779. self.StatusbarUpdate()
  780. def DeleteGCP(self, event):
  781. """
  782. Deletes selected item in GCP list
  783. """
  784. minNumOfItems = self.OnGROrder(None)
  785. if self.list.GetItemCount() <= minNumOfItems:
  786. wx.MessageBox(parent=self, message=_("At least %d GCPs required. Operation cancelled.") % minNumOfItems,
  787. caption=_("Delete GCP"), style=wx.OK | wx.ICON_INFORMATION)
  788. return
  789. key = self.list.DeleteGCPItem()
  790. del self.mapcoordlist[key]
  791. # update key and GCP number
  792. for newkey in range(key, len(self.mapcoordlist)):
  793. index = self.list.FindItemData(-1, newkey + 1)
  794. self.mapcoordlist[newkey][0] = newkey
  795. self.list.SetStringItem(index, 0, str(newkey))
  796. self.list.SetItemData(index, newkey)
  797. # update selected
  798. if self.list.GetItemCount() > 0:
  799. if self.list.selected < self.list.GetItemCount():
  800. self.list.selectedkey = self.list.GetItemData(self.list.selected)
  801. else:
  802. self.list.selected = self.list.GetItemCount() - 1
  803. self.list.selectedkey = self.list.GetItemData(self.list.selected)
  804. self.list.SetItemState(self.list.selected,
  805. wx.LIST_STATE_SELECTED,
  806. wx.LIST_STATE_SELECTED)
  807. else:
  808. self.list.selected = wx.NOT_FOUND
  809. self.list.selectedkey = -1
  810. self.UpdateColours()
  811. if self.statusbarWin['toggle'].GetSelection() == 7: # go to
  812. self.StatusbarUpdate()
  813. if self.list.selectedkey > 0:
  814. self.statusbarWin['goto'].SetValue(self.list.selectedkey)
  815. #self.statusbarWin['goto'].SetValue(0)
  816. def ClearGCP(self, event):
  817. """
  818. Clears all values in selected item of GCP list and unchecks it
  819. """
  820. index = self.list.GetSelected()
  821. for i in range(4):
  822. self.list.SetStringItem(index, i, '0.0')
  823. self.list.SetStringItem(index, 4, '')
  824. self.list.SetStringItem(index, 5, '')
  825. self.list.CheckItem(index, False)
  826. key = self.list.GetItemData(index)
  827. # GCP number, source E, source N, target E, target N, fwd error, bkwd error
  828. self.mapcoordlist[key] = [key, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
  829. def DrawGCP(self, coordtype):
  830. """
  831. Updates GCP and map coord maps and redraws
  832. active (checked) GCP markers
  833. """
  834. self.highest_only = UserSettings.Get(group='gcpman', key='rms', subkey='highestonly')
  835. self.show_unused = UserSettings.Get(group='gcpman', key='symbol', subkey='unused')
  836. col = UserSettings.Get(group='gcpman', key='symbol', subkey='color')
  837. wxLowCol = wx.Colour(col[0], col[1], col[2], 255)
  838. col = UserSettings.Get(group='gcpman', key='symbol', subkey='hcolor')
  839. wxHiCol = wx.Colour(col[0], col[1], col[2], 255)
  840. col = UserSettings.Get(group='gcpman', key='symbol', subkey='scolor')
  841. wxSelCol = wx.Colour(col[0], col[1], col[2], 255)
  842. col = UserSettings.Get(group='gcpman', key='symbol', subkey='ucolor')
  843. wxUnCol = wx.Colour(col[0], col[1], col[2], 255)
  844. spx = UserSettings.Get(group='gcpman', key='symbol', subkey='size')
  845. wpx = UserSettings.Get(group='gcpman', key='symbol', subkey='width')
  846. font = self.GetFont()
  847. font.SetPointSize(int(spx) + 2)
  848. penOrig = polypenOrig = None
  849. mapWin = None
  850. if coordtype == 'source':
  851. mapWin = self.SrcMapWindow
  852. e_idx = 1
  853. n_idx = 2
  854. elif coordtype == 'target':
  855. mapWin = self.TgtMapWindow
  856. e_idx = 3
  857. n_idx = 4
  858. if not mapWin:
  859. wx.MessageBox(parent=self,
  860. message="%s%s." % (_("mapwin not defined for "),
  861. str(idx)),
  862. caption=_("Error"), style=wx.OK | wx.ICON_ERROR | wx.CENTRE)
  863. return
  864. #for gcp in self.mapcoordlist:
  865. for idx in range(self.list.GetItemCount()):
  866. key = self.list.GetItemData(idx)
  867. gcp = self.mapcoordlist[key]
  868. if not self.list.IsChecked(idx):
  869. if self.show_unused:
  870. wxCol = wxUnCol
  871. else:
  872. continue
  873. else:
  874. if self.highest_only == True:
  875. if key == self.highest_key:
  876. wxCol = wxHiCol
  877. else:
  878. wxCol = wxLowCol
  879. elif self.rmsthresh > 0:
  880. if (gcp[5] > self.rmsthresh):
  881. wxCol = wxHiCol
  882. else:
  883. wxCol = wxLowCol
  884. if idx == self.list.selected:
  885. wxCol = wxSelCol
  886. if not penOrig:
  887. penOrig = mapWin.pen
  888. polypenOrig = mapWin.polypen
  889. mapWin.pen = wx.Pen(colour=wxCol, width=wpx, style=wx.SOLID)
  890. mapWin.polypen = wx.Pen(colour=wxCol, width=wpx, style=wx.SOLID) # ?
  891. mapWin.pen.SetColour(wxCol)
  892. mapWin.polypen.SetColour(wxCol)
  893. coord = mapWin.Cell2Pixel((gcp[e_idx], gcp[n_idx]))
  894. mapWin.DrawCross(pdc=mapWin.pdcTmp, coords=coord,
  895. size=spx, text={ 'text' : '%s' % str(gcp[0]),
  896. 'active' : True,
  897. 'font' : font,
  898. 'color': wxCol,
  899. 'coords': [coord[0] + 5,
  900. coord[1] + 5,
  901. 5,
  902. 5]})
  903. if penOrig:
  904. mapWin.pen = penOrig
  905. mapWin.polypen = polypenOrig
  906. def SetGCPData(self, coordtype, coord, mapdisp=None, confirm=False):
  907. """
  908. Inserts coordinates from file, mouse click on map, or after editing
  909. into selected item of GCP list and checks it for use
  910. """
  911. index = self.list.GetSelected()
  912. if index == wx.NOT_FOUND:
  913. return
  914. coord0 = coord[0]
  915. coord1 = coord[1]
  916. key = self.list.GetItemData(index)
  917. if confirm:
  918. if self.MapWindow == self.SrcMapWindow:
  919. currloc = _("source")
  920. else:
  921. currloc = _("target")
  922. ret = wx.MessageBox(parent=self,
  923. caption=_("Set GCP coordinates"),
  924. message=_('Set %(coor)s coordinates for GCP No. %(key)s? \n\n'
  925. 'East: %(coor0)s \n'
  926. 'North: %(coor1)s') % \
  927. { 'coor' : currloc,
  928. 'key' : str(key),
  929. 'coor0' : str(coord0),
  930. 'coor1' : str(coord1) },
  931. style=wx.ICON_QUESTION | wx.YES_NO | wx.CENTRE)
  932. # for wingrass
  933. if os.name == 'nt':
  934. self.MapWindow.SetFocus()
  935. if ret == wx.NO:
  936. return
  937. if coordtype == 'source':
  938. self.list.SetStringItem(index, 1, str(coord0))
  939. self.list.SetStringItem(index, 2, str(coord1))
  940. self.mapcoordlist[key][1] = coord[0]
  941. self.mapcoordlist[key][2] = coord[1]
  942. elif coordtype == 'target':
  943. self.list.SetStringItem(index, 3, str(coord0))
  944. self.list.SetStringItem(index, 4, str(coord1))
  945. self.mapcoordlist[key][3] = coord[0]
  946. self.mapcoordlist[key][4] = coord[1]
  947. self.list.SetStringItem(index, 5, '0')
  948. self.list.SetStringItem(index, 6, '0')
  949. self.mapcoordlist[key][5] = 0.0
  950. self.mapcoordlist[key][6] = 0.0
  951. # self.list.ResizeColumns()
  952. def SaveGCPs(self, event):
  953. """
  954. Make a POINTS file or save GCP coordinates to existing POINTS file
  955. """
  956. self.GCPcount = 0
  957. try:
  958. f = open(self.file['points'], mode='w')
  959. # use os.linesep or '\n' here ???
  960. f.write('# Ground Control Points File\n')
  961. f.write("# \n")
  962. f.write("# target location: " + self.currentlocation + '\n')
  963. f.write("# target mapset: " + self.currentmapset + '\n')
  964. f.write("#\tsource\t\ttarget\t\tstatus\n")
  965. f.write("#\teast\tnorth\teast\tnorth\t(1=ok, 0=ignore)\n")
  966. f.write("#----------------------- ----------------------- ---------------\n")
  967. for index in range(self.list.GetItemCount()):
  968. if self.list.IsChecked(index) == True:
  969. check = "1"
  970. self.GCPcount += 1
  971. else:
  972. check = "0"
  973. coord0 = self.list.GetItem(index, 1).GetText()
  974. coord1 = self.list.GetItem(index, 2).GetText()
  975. coord2 = self.list.GetItem(index, 3).GetText()
  976. coord3 = self.list.GetItem(index, 4).GetText()
  977. f.write(coord0 + ' ' + coord1 + ' ' + coord2 + ' ' + coord3 + ' ' + check + '\n')
  978. except IOError, err:
  979. wx.MessageBox(parent=self,
  980. message="%s <%s>. %s%s" % (_("Writing POINTS file failed"),
  981. self.file['points'], os.linesep, err),
  982. caption=_("Error"), style=wx.OK | wx.ICON_ERROR | wx.CENTRE)
  983. return
  984. f.close()
  985. # if event != None save also to backup file
  986. if event:
  987. shutil.copy(self.file['points'], self.file['points_bak'])
  988. self.parent.goutput.WriteLog(_('POINTS file saved for group <%s>') % self.xygroup)
  989. #self.SetStatusText(_('POINTS file saved'))
  990. def ReadGCPs(self):
  991. """
  992. Reads GCPs and georectified coordinates from POINTS file
  993. """
  994. self.GCPcount = 0
  995. sourceMapWin = self.SrcMapWindow
  996. targetMapWin = self.TgtMapWindow
  997. #targetMapWin = self.parent.curr_page.maptree.mapdisplay.MapWindow
  998. if not sourceMapWin:
  999. wx.MessageBox(parent=self,
  1000. message="%s. %s%s" % (_("source mapwin not defined"),
  1001. os.linesep, err),
  1002. caption=_("Error"), style=wx.OK | wx.ICON_ERROR | wx.CENTRE)
  1003. if not targetMapWin:
  1004. wx.MessageBox(parent=self,
  1005. message="%s. %s%s" % (_("target mapwin not defined"),
  1006. os.linesep, err),
  1007. caption=_("Error"), style=wx.OK | wx.ICON_ERROR | wx.CENTRE)
  1008. try:
  1009. f = open(self.file['points'], 'r')
  1010. GCPcnt = 0
  1011. for line in f.readlines():
  1012. if line[0] == '#' or line =='':
  1013. continue
  1014. line = line.replace('\n', '').strip()
  1015. coords = map(float, line.split())
  1016. if coords[4] == 1:
  1017. check = True
  1018. self.GCPcount +=1
  1019. else:
  1020. check = False
  1021. self.AddGCP(event=None)
  1022. self.SetGCPData('source', (coords[0], coords[1]), sourceMapWin)
  1023. self.SetGCPData('target', (coords[2], coords[3]), targetMapWin)
  1024. index = self.list.GetSelected()
  1025. if index != wx.NOT_FOUND:
  1026. self.list.CheckItem(index, check)
  1027. GCPcnt += 1
  1028. except IOError, err:
  1029. wx.MessageBox(parent=self,
  1030. message="%s <%s>. %s%s" % (_("Reading POINTS file failed"),
  1031. self.file['points'], os.linesep, err),
  1032. caption=_("Error"), style=wx.OK | wx.ICON_ERROR | wx.CENTRE)
  1033. return
  1034. f.close()
  1035. if GCPcnt == 0:
  1036. # 3 gcp is minimum
  1037. for i in range(3):
  1038. self.AddGCP(None)
  1039. if self.CheckGCPcount():
  1040. # calculate RMS
  1041. self.RMSError(self.xygroup, self.gr_order)
  1042. def ReloadGCPs(self, event):
  1043. """!Reload data from file"""
  1044. # use backup
  1045. shutil.copy(self.file['points_bak'], self.file['points'])
  1046. # delete all items in mapcoordlist
  1047. self.mapcoordlist = []
  1048. self.mapcoordlist.append([ 0, # GCP number
  1049. 0.0, # source east
  1050. 0.0, # source north
  1051. 0.0, # target east
  1052. 0.0, # target north
  1053. 0.0, # forward error
  1054. 0.0 ] ) # backward error
  1055. self.list.LoadData()
  1056. self.itemDataMap = self.mapcoordlist
  1057. if self._col != -1:
  1058. self.list.ClearColumnImage(self._col)
  1059. self._colSortFlag = [1] * self.list.GetColumnCount()
  1060. # draw GCPs (source and target)
  1061. sourceMapWin = self.SrcMapWindow
  1062. sourceMapWin.UpdateMap(render=False, renderVector=False)
  1063. if self.show_target:
  1064. targetMapWin = self.TgtMapWindow
  1065. targetMapWin.UpdateMap(render=False, renderVector=False)
  1066. def OnFocus(self, event):
  1067. # self.grwiz.SwitchEnv('source')
  1068. pass
  1069. def OnRMS(self, event):
  1070. """
  1071. RMS button handler
  1072. """
  1073. self.RMSError(self.xygroup,self.gr_order)
  1074. sourceMapWin = self.SrcMapWindow
  1075. sourceMapWin.UpdateMap(render=False, renderVector=False)
  1076. if self.show_target:
  1077. targetMapWin = self.TgtMapWindow
  1078. targetMapWin.UpdateMap(render=False, renderVector=False)
  1079. def CheckGCPcount(self, msg=False):
  1080. """
  1081. Checks to make sure that the minimum number of GCPs have been defined and
  1082. are active for the selected transformation order
  1083. """
  1084. if (self.GCPcount < 3 and self.gr_order == 1) or \
  1085. (self.GCPcount < 6 and self.gr_order == 2) or \
  1086. (self.GCPcount < 10 and self.gr_order == 3):
  1087. if msg:
  1088. wx.MessageBox(parent=self,
  1089. caption=_("RMS Error"),
  1090. message=_('Insufficient points defined and active (checked) '
  1091. 'for selected rectification method.\n'
  1092. '3+ points needed for 1st order,\n'
  1093. '6+ points for 2nd order, and\n'
  1094. '10+ points for 3rd order.'),
  1095. style=wx.ICON_INFORMATION | wx.ID_OK | wx.CENTRE)
  1096. return False
  1097. else:
  1098. return True
  1099. def OnGeorect(self, event):
  1100. """
  1101. Georectifies map(s) in group using i.rectify or v.transform
  1102. """
  1103. global maptype
  1104. self.SaveGCPs(None)
  1105. if self.CheckGCPcount(msg=True) == False:
  1106. return
  1107. if maptype == 'cell':
  1108. self.grwiz.SwitchEnv('source')
  1109. if self.clip_to_region:
  1110. flags = "ac"
  1111. else:
  1112. flags = "a"
  1113. busy = wx.BusyInfo(message=_("Rectifying images, please wait..."),
  1114. parent=self)
  1115. wx.Yield()
  1116. ret, msg = gcmd.RunCommand('i.rectify',
  1117. parent = self,
  1118. getErrorMsg = True,
  1119. quiet = True,
  1120. group = self.xygroup,
  1121. extension = self.extension,
  1122. order = self.gr_order,
  1123. method=self.gr_method,
  1124. flags = flags)
  1125. busy.Destroy()
  1126. # provide feedback on failure
  1127. if ret != 0:
  1128. print >> sys.stderr, msg
  1129. elif maptype == 'vector':
  1130. outmsg = ''
  1131. # loop through all vectors in VREF
  1132. # and move resulting vector to target location
  1133. # make sure current mapset has a vector folder
  1134. if not os.path.isdir(os.path.join(self.grassdatabase,
  1135. self.currentlocation,
  1136. self.currentmapset,
  1137. 'vector')):
  1138. os.mkdir(os.path.join(self.grassdatabase,
  1139. self.currentlocation,
  1140. self.currentmapset,
  1141. 'vector'))
  1142. self.grwiz.SwitchEnv('source')
  1143. # make list of vectors to georectify from VREF
  1144. f = open(self.file['vgrp'])
  1145. vectlist = []
  1146. try:
  1147. for vect in f.readlines():
  1148. vect = vect.strip('\n')
  1149. if len(vect) < 1:
  1150. continue
  1151. vectlist.append(vect)
  1152. finally:
  1153. f.close()
  1154. # georectify each vector in VREF using v.transform
  1155. for vect in vectlist:
  1156. self.outname = vect + '_' + self.extension
  1157. self.parent.goutput.WriteLog(text = _('Transforming <%s>...') % vect,
  1158. switchPage = True)
  1159. msg = err = ''
  1160. ret, out, err = gcmd.RunCommand('v.transform',
  1161. flags = '-o',
  1162. input=vect,
  1163. output=self.outname,
  1164. pointsfile=self.file['points'],
  1165. getErrorMsg=True, read=True)
  1166. if ret == 0:
  1167. self.VectGRList.append(self.outname)
  1168. print err
  1169. # note: WriteLog doesn't handle GRASS_INFO_PERCENT well, so using a print here
  1170. # self.parent.goutput.WriteLog(text = _(err), switchPage = True)
  1171. self.parent.goutput.WriteLog(text = _(out), switchPage = True)
  1172. else:
  1173. self.parent.goutput.WriteError(_('Georectification of vector map <%s> failed') %
  1174. self.outname)
  1175. self.parent.goutput.WriteError(_(err))
  1176. # FIXME
  1177. # Copying database information not working.
  1178. # Does not copy from xy location to current location
  1179. # TODO: replace $GISDBASE etc with real paths
  1180. # xyLayer = []
  1181. # for layer in grass.vector_db(map = vect).itervalues():
  1182. # xyLayer.append((layer['driver'],
  1183. # layer['database'],
  1184. # layer['table']))
  1185. # dbConnect = grass.db_connection()
  1186. # print 'db connection =', dbConnect
  1187. # for layer in xyLayer:
  1188. # self.parent.goutput.RunCmd(['db.copy',
  1189. # '--q',
  1190. # '--o',
  1191. # 'from_driver=%s' % layer[0],
  1192. # 'from_database=%s' % layer[1],
  1193. # 'from_table=%s' % layer[2],
  1194. # 'to_driver=%s' % dbConnect['driver'],
  1195. # 'to_database=%s' % dbConnect['database'],
  1196. # 'to_table=%s' % layer[2] + '_' + self.extension])
  1197. # copy all georectified vectors from source location to current location
  1198. for name in self.VectGRList:
  1199. xyvpath = os.path.join(self.grassdatabase,
  1200. self.xylocation,
  1201. self.xymapset,
  1202. 'vector',
  1203. name)
  1204. vpath = os.path.join(self.grassdatabase,
  1205. self.currentlocation,
  1206. self.currentmapset,
  1207. 'vector',
  1208. name)
  1209. if os.path.isdir(vpath):
  1210. self.parent.goutput.WriteWarning(_('Vector map <%s> already exists. '
  1211. 'Change extension name and '
  1212. 'georectify again.') % self.outname)
  1213. break
  1214. else:
  1215. # use shutil.copytree() because shutil.move() deletes src dir
  1216. shutil.copytree(xyvpath, vpath)
  1217. # TODO: connect vectors to copied tables with v.db.connect
  1218. wx.MessageBox('For all vector maps georectified successfully, ' + '\n' +
  1219. 'you will need to copy any attribute tables' + '\n' +
  1220. 'and reconnect them to the georectified vectors')
  1221. self.grwiz.SwitchEnv('target')
  1222. def OnGeorectDone(self, **kargs):
  1223. """!Print final message"""
  1224. global maptype
  1225. if maptype == 'cell':
  1226. return
  1227. returncode = kargs['returncode']
  1228. if returncode == 0:
  1229. self.VectGRList.append(self.outname)
  1230. print '*****vector list = ' + str(self.VectGRList)
  1231. else:
  1232. self.parent.goutput.WriteError(_('Georectification of vector map <%s> failed') %
  1233. self.outname)
  1234. def OnSettings(self, event):
  1235. """!GCP Manager settings"""
  1236. dlg = GrSettingsDialog(parent=self, id=wx.ID_ANY, title=_('GCP Manager settings'))
  1237. if dlg.ShowModal() == wx.ID_OK:
  1238. pass
  1239. dlg.Destroy()
  1240. def UpdateColours(self, srcrender=False, srcrenderVector=False,
  1241. tgtrender=False, tgtrenderVector=False):
  1242. """!update colours"""
  1243. highest_fwd_err = 0.0
  1244. self.highest_key = 0
  1245. highest_idx = 0
  1246. for index in range(self.list.GetItemCount()):
  1247. if self.list.IsChecked(index):
  1248. key = self.list.GetItemData(index)
  1249. fwd_err = self.mapcoordlist[key][5]
  1250. if self.highest_only == True:
  1251. self.list.SetItemTextColour(index, wx.BLACK)
  1252. if highest_fwd_err < fwd_err:
  1253. highest_fwd_err = fwd_err
  1254. self.highest_key = key
  1255. highest_idx = index
  1256. elif self.rmsthresh > 0:
  1257. if (fwd_err > self.rmsthresh):
  1258. self.list.SetItemTextColour(index, wx.RED)
  1259. else:
  1260. self.list.SetItemTextColour(index, wx.BLACK)
  1261. else:
  1262. self.list.SetItemTextColour(index, wx.BLACK)
  1263. if self.highest_only and highest_fwd_err > 0.0:
  1264. self.list.SetItemTextColour(highest_idx, wx.RED)
  1265. sourceMapWin = self.SrcMapWindow
  1266. sourceMapWin.UpdateMap(render=srcrender, renderVector=srcrenderVector)
  1267. if self.show_target:
  1268. targetMapWin = self.TgtMapWindow
  1269. targetMapWin.UpdateMap(render=tgtrender, renderVector=tgtrenderVector)
  1270. def OnQuit(self, event):
  1271. """!Quit georectifier"""
  1272. ret = wx.MessageBox(parent=self,
  1273. caption=_("Quit GCP Manager"),
  1274. message=_('Save ground control points?'),
  1275. style=wx.ICON_QUESTION | wx.YES_NO | wx.CANCEL | wx.CENTRE)
  1276. if ret != wx.CANCEL:
  1277. if ret == wx.YES:
  1278. self.SaveGCPs(None)
  1279. elif ret == wx.NO:
  1280. # restore POINTS file from backup
  1281. if os.path.exists(self.file['points_bak']):
  1282. shutil.copy(self.file['points_bak'], self.file['points'])
  1283. if os.path.exists(self.file['points_bak']):
  1284. os.unlink(self.file['points_bak'])
  1285. self.SrcMap.Clean()
  1286. self.TgtMap.Clean()
  1287. self.grwiz.Cleanup()
  1288. self.Destroy()
  1289. #event.Skip()
  1290. def OnGROrder(self, event):
  1291. """
  1292. sets transformation order for georectifying
  1293. """
  1294. if event:
  1295. self.gr_order = event.GetInt() + 1
  1296. numOfItems = self.list.GetItemCount()
  1297. minNumOfItems = numOfItems
  1298. if self.gr_order == 1:
  1299. minNumOfItems = 3
  1300. # self.SetStatusText(_('Insufficient points, 3+ points needed for 1st order'))
  1301. elif self.gr_order == 2:
  1302. minNumOfItems = 6
  1303. diff = 6 - numOfItems
  1304. # self.SetStatusText(_('Insufficient points, 6+ points needed for 2nd order'))
  1305. elif self.gr_order == 3:
  1306. minNumOfItems = 10
  1307. # self.SetStatusText(_('Insufficient points, 10+ points needed for 3rd order'))
  1308. for i in range(minNumOfItems - numOfItems):
  1309. self.AddGCP(None)
  1310. return minNumOfItems
  1311. def RMSError(self, xygroup, order):
  1312. """
  1313. Uses g.transform to calculate forward and backward error for each used GCP
  1314. in POINTS file and insert error values into GCP list.
  1315. Calculates total forward and backward RMS error for all used points
  1316. """
  1317. # save GCPs to points file to make sure that all checked GCPs are used
  1318. self.SaveGCPs(None)
  1319. #self.SetStatusText('')
  1320. if self.CheckGCPcount(msg=True) == False:
  1321. return
  1322. # get list of forward and reverse rms error values for each point
  1323. self.grwiz.SwitchEnv('source')
  1324. ret = gcmd.RunCommand('g.transform',
  1325. parent = self,
  1326. read = True,
  1327. group = xygroup,
  1328. order = order)
  1329. self.grwiz.SwitchEnv('target')
  1330. if ret:
  1331. errlist = ret.splitlines()
  1332. else:
  1333. wx.MessageBox(parent=self,
  1334. caption=_("RMS Error"),
  1335. message=_('Could not calculate RMS Error. \n'
  1336. 'Possible error with g.transform.'),
  1337. style=wx.ICON_ERROR | wx.ID_OK | wx.CENTRE)
  1338. return
  1339. # insert error values into GCP list for checked items
  1340. sdfactor = float(UserSettings.Get(group='gcpman', key='rms', subkey='sdfactor'))
  1341. GCPcount = 0
  1342. sumsq_fwd_err = 0.0
  1343. sumsq_bkw_err = 0.0
  1344. sum_fwd_err = 0.0
  1345. highest_fwd_err = 0.0
  1346. self.highest_key = 0
  1347. highest_idx = 0
  1348. for index in range(self.list.GetItemCount()):
  1349. key = self.list.GetItemData(index)
  1350. if self.list.IsChecked(index):
  1351. fwd_err, bkw_err = errlist[GCPcount].split()
  1352. self.list.SetStringItem(index, 5, fwd_err)
  1353. self.list.SetStringItem(index, 6, bkw_err)
  1354. self.mapcoordlist[key][5] = float(fwd_err)
  1355. self.mapcoordlist[key][6] = float(bkw_err)
  1356. self.list.SetItemTextColour(index, wx.BLACK)
  1357. if self.highest_only:
  1358. if highest_fwd_err < float(fwd_err):
  1359. highest_fwd_err = float(fwd_err)
  1360. self.highest_key = key
  1361. highest_idx = index
  1362. sumsq_fwd_err += float(fwd_err)**2
  1363. sumsq_bkw_err += float(bkw_err)**2
  1364. sum_fwd_err += float(fwd_err)
  1365. GCPcount += 1
  1366. else:
  1367. self.list.SetStringItem(index, 5, '')
  1368. self.list.SetStringItem(index, 6, '')
  1369. self.mapcoordlist[key][5] = 0.0
  1370. self.mapcoordlist[key][6] = 0.0
  1371. self.list.SetItemTextColour(index, wx.BLACK)
  1372. # SD
  1373. if GCPcount > 0:
  1374. sum_fwd_err /= GCPcount
  1375. self.rmsmean = sum_fwd_err /GCPcount
  1376. self.rmssd = (((sumsq_fwd_err/GCPcount) - self.rmsmean**2)**0.5)
  1377. self.rmsthresh = self.rmsmean + sdfactor * self.rmssd
  1378. else:
  1379. self.rmsthresh = 0
  1380. self.rmsmean = 0
  1381. self.rmssd = 0
  1382. if self.highest_only and highest_fwd_err > 0.0:
  1383. self.list.SetItemTextColour(highest_idx, wx.RED)
  1384. elif GCPcount > 0 and self.rmsthresh > 0 and not self.highest_only:
  1385. for index in range(self.list.GetItemCount()):
  1386. if self.list.IsChecked(index):
  1387. key = self.list.GetItemData(index)
  1388. if (self.mapcoordlist[key][5] > self.rmsthresh):
  1389. self.list.SetItemTextColour(index, wx.RED)
  1390. # calculate global RMS error (geometric mean)
  1391. self.fwd_rmserror = round((sumsq_fwd_err/GCPcount)**0.5,4)
  1392. self.bkw_rmserror = round((sumsq_bkw_err/GCPcount)**0.5,4)
  1393. self.list.ResizeColumns()
  1394. def GetNewExtent(self, region, map = None):
  1395. coord_file = utils.GetTempfile()
  1396. newreg = { 'n' : 0.0, 's' : 0.0, 'e' : 0.0, 'w' : 0.0,}
  1397. try:
  1398. f = open(coord_file, mode='w')
  1399. # NW corner
  1400. f.write(str(region['e']) + " " + str(region['n']) + "\n")
  1401. # NE corner
  1402. f.write(str(region['e']) + " " + str(region['s']) + "\n")
  1403. # SW corner
  1404. f.write(str(region['w']) + " " + str(region['n']) + "\n")
  1405. # SE corner
  1406. f.write(str(region['w']) + " " + str(region['s']) + "\n")
  1407. finally:
  1408. f.close()
  1409. # save GCPs to points file to make sure that all checked GCPs are used
  1410. self.SaveGCPs(None)
  1411. order = self.gr_order
  1412. self.gr_order = 1
  1413. if self.CheckGCPcount(msg=True) == False:
  1414. self.gr_order = order
  1415. return
  1416. self.gr_order = order
  1417. # get list of forward and reverse rms error values for each point
  1418. self.grwiz.SwitchEnv('source')
  1419. if map == 'source':
  1420. ret = gcmd.RunCommand('g.transform',
  1421. parent = self,
  1422. read = True,
  1423. group = self.xygroup,
  1424. order = 1,
  1425. format = 'dst',
  1426. coords = coord_file)
  1427. elif map == 'target':
  1428. ret = gcmd.RunCommand('g.transform',
  1429. parent = self,
  1430. read = True,
  1431. group = self.xygroup,
  1432. order = 1,
  1433. flags = 'r',
  1434. format = 'src',
  1435. coords = coord_file)
  1436. os.unlink(coord_file)
  1437. self.grwiz.SwitchEnv('target')
  1438. if ret:
  1439. errlist = ret.splitlines()
  1440. else:
  1441. wx.MessageBox(parent=self,
  1442. caption=_("Adjust GCP Displays "),
  1443. message=_('Could not calculate new extends. \n'
  1444. 'Possible error with g.transform.'),
  1445. style=wx.ICON_ERROR | wx.ID_OK | wx.CENTRE)
  1446. return
  1447. # fist corner
  1448. e, n = errlist[0].split()
  1449. fe = float(e)
  1450. fn = float(n)
  1451. newreg['n'] = fn
  1452. newreg['s'] = fn
  1453. newreg['e'] = fe
  1454. newreg['w'] = fe
  1455. # other three corners
  1456. for i in range(1, 4):
  1457. e, n = errlist[i].split()
  1458. fe = float(e)
  1459. fn = float(n)
  1460. if fe < newreg['w']:
  1461. newreg['w'] = fe
  1462. if fe > newreg['e']:
  1463. newreg['e'] = fe
  1464. if fn < newreg['s']:
  1465. newreg['s'] = fn
  1466. if fn > newreg['n']:
  1467. newreg['n'] = fn
  1468. return newreg
  1469. def OnHelp(self, event):
  1470. """!Show GCP Manager manual page"""
  1471. cmdlist = ['g.manual', 'entry=wxGUI.GCP_Manager']
  1472. self.parent.goutput.RunCmd(cmdlist, compReg=False,
  1473. switchPage=False)
  1474. def OnUpdateActive(self, event):
  1475. if self.activemap.GetSelection() == 0:
  1476. self.MapWindow = self.SrcMapWindow
  1477. self.Map = self.SrcMap
  1478. else:
  1479. self.MapWindow = self.TgtMapWindow
  1480. self.Map = self.TgtMap
  1481. self.UpdateActive(self.MapWindow)
  1482. # for wingrass
  1483. if os.name == 'nt':
  1484. self.MapWindow.SetFocus()
  1485. def UpdateActive(self, win):
  1486. # optionally disable tool zoomback tool
  1487. self.toolbars['gcpdisp'].Enable('zoomback', enable = (len(self.MapWindow.zoomhistory) > 1))
  1488. if self.activemap.GetSelection() != (win == self.TgtMapWindow):
  1489. self.activemap.SetSelection(win == self.TgtMapWindow)
  1490. self.StatusbarUpdate()
  1491. def AdjustMap(self, newreg):
  1492. """!Adjust map window to new extents
  1493. """
  1494. # adjust map window
  1495. self.Map.region['n'] = newreg['n']
  1496. self.Map.region['s'] = newreg['s']
  1497. self.Map.region['e'] = newreg['e']
  1498. self.Map.region['w'] = newreg['w']
  1499. self.MapWindow.ZoomHistory(self.Map.region['n'], self.Map.region['s'],
  1500. self.Map.region['e'], self.Map.region['w'])
  1501. # LL locations
  1502. if self.Map.projinfo['proj'] == 'll':
  1503. if newreg['n'] > 90.0:
  1504. newreg['n'] = 90.0
  1505. if newreg['s'] < -90.0:
  1506. newreg['s'] = -90.0
  1507. ce = newreg['w'] + (newreg['e'] - newreg['w']) / 2
  1508. cn = newreg['s'] + (newreg['n'] - newreg['s']) / 2
  1509. # calculate new center point and display resolution
  1510. self.Map.region['center_easting'] = ce
  1511. self.Map.region['center_northing'] = cn
  1512. self.Map.region["ewres"] = (newreg['e'] - newreg['w']) / self.Map.width
  1513. self.Map.region["nsres"] = (newreg['n'] - newreg['s']) / self.Map.height
  1514. self.Map.AlignExtentFromDisplay()
  1515. self.MapWindow.ZoomHistory(self.Map.region['n'], self.Map.region['s'],
  1516. self.Map.region['e'], self.Map.region['w'])
  1517. if self.MapWindow.redrawAll is False:
  1518. self.MapWindow.redrawAll = True
  1519. self.MapWindow.UpdateMap()
  1520. self.StatusbarUpdate()
  1521. def OnZoomToSource(self, event):
  1522. """!Set target map window to match extents of source map window
  1523. """
  1524. if not self.MapWindow == self.TgtMapWindow:
  1525. self.MapWindow = self.TgtMapWindow
  1526. self.Map = self.TgtMap
  1527. self.UpdateActive(self.TgtMapWindow)
  1528. # get new N, S, E, W for target
  1529. newreg = self.GetNewExtent(self.SrcMap.region, 'source')
  1530. if newreg:
  1531. self.AdjustMap(newreg)
  1532. def OnZoomToTarget(self, event):
  1533. """!Set source map window to match extents of target map window
  1534. """
  1535. if not self.MapWindow == self.SrcMapWindow:
  1536. self.MapWindow = self.SrcMapWindow
  1537. self.Map = self.SrcMap
  1538. self.UpdateActive(self.SrcMapWindow)
  1539. # get new N, S, E, W for target
  1540. newreg = self.GetNewExtent(self.TgtMap.region, 'target')
  1541. if newreg:
  1542. self.AdjustMap(newreg)
  1543. def OnZoomMenuGCP(self, event):
  1544. """!Popup Zoom menu
  1545. """
  1546. point = wx.GetMousePosition()
  1547. zoommenu = wx.Menu()
  1548. # Add items to the menu
  1549. zoomsource = wx.MenuItem(zoommenu, wx.ID_ANY, _('Adjust source display to target display'))
  1550. zoommenu.AppendItem(zoomsource)
  1551. self.Bind(wx.EVT_MENU, self.OnZoomToTarget, zoomsource)
  1552. zoomtarget = wx.MenuItem(zoommenu, wx.ID_ANY, _('Adjust target display to source display'))
  1553. zoommenu.AppendItem(zoomtarget)
  1554. self.Bind(wx.EVT_MENU, self.OnZoomToSource, zoomtarget)
  1555. # Popup the menu. If an item is selected then its handler
  1556. # will be called before PopupMenu returns.
  1557. self.PopupMenu(zoommenu)
  1558. zoommenu.Destroy()
  1559. def OnDispResize(self, event):
  1560. """!GCP Map Display resized, adjust Map Windows
  1561. """
  1562. if self.toolbars['gcpdisp']:
  1563. srcwidth, srcheight = self.SrcMapWindow.GetSize()
  1564. tgtwidth, tgtheight = self.TgtMapWindow.GetSize()
  1565. srcwidth = (srcwidth + tgtwidth) / 2
  1566. self._mgr.GetPane("target").Hide()
  1567. self._mgr.Update()
  1568. self._mgr.GetPane("source").BestSize((srcwidth, srcheight))
  1569. self._mgr.GetPane("target").BestSize((srcwidth, tgtheight))
  1570. if self.show_target:
  1571. self._mgr.GetPane("target").Show()
  1572. self._mgr.Update()
  1573. pass
  1574. class GCPList(wx.ListCtrl,
  1575. CheckListCtrlMixin,
  1576. ListCtrlAutoWidthMixin):
  1577. def __init__(self, parent, gcp, id=wx.ID_ANY,
  1578. pos=wx.DefaultPosition, size=wx.DefaultSize,
  1579. style=wx.LC_REPORT | wx.SUNKEN_BORDER | wx.LC_HRULES |
  1580. wx.LC_SINGLE_SEL):
  1581. wx.ListCtrl.__init__(self, parent, id, pos, size, style)
  1582. self.gcp = gcp # GCP class
  1583. self.render = True
  1584. # Mixin settings
  1585. CheckListCtrlMixin.__init__(self)
  1586. ListCtrlAutoWidthMixin.__init__(self)
  1587. # TextEditMixin.__init__(self)
  1588. # tracks whether list items are checked or not
  1589. self.CheckList = []
  1590. self._Create()
  1591. self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnItemSelected)
  1592. self.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.OnItemActivated)
  1593. self.Bind(wx.EVT_LIST_COL_CLICK, self.OnColClick)
  1594. self.selected = wx.NOT_FOUND
  1595. self.selectedkey = -1
  1596. def _Create(self):
  1597. if 0:
  1598. # normal, simple columns
  1599. idx_col = 0
  1600. for col in (_('use'),
  1601. _('source E'),
  1602. _('source N'),
  1603. _('target E'),
  1604. _('target N'),
  1605. _('Forward error'),
  1606. _('Backward error')):
  1607. self.InsertColumn(idx_col, col)
  1608. idx_col += 1
  1609. else:
  1610. # the hard way: we want images on the column header
  1611. info = wx.ListItem()
  1612. info.SetMask(wx.LIST_MASK_TEXT | wx.LIST_MASK_IMAGE | wx.LIST_MASK_FORMAT)
  1613. info.SetImage(-1)
  1614. info.m_format = wx.LIST_FORMAT_LEFT
  1615. idx_col = 0
  1616. for lbl in (_('use'),
  1617. _('source E'),
  1618. _('source N'),
  1619. _('target E'),
  1620. _('target N'),
  1621. _('Forward error'),
  1622. _('Backward error')):
  1623. info.SetText(lbl)
  1624. self.InsertColumnInfo(idx_col, info)
  1625. idx_col += 1
  1626. def LoadData(self):
  1627. """!Load data into list"""
  1628. self.DeleteAllItems()
  1629. self.render = False
  1630. if os.path.isfile(self.gcp.file['points']):
  1631. self.gcp.ReadGCPs()
  1632. else:
  1633. # 3 gcp is minimum
  1634. for i in range(3):
  1635. self.gcp.AddGCP(None)
  1636. # select first point by default
  1637. self.selected = 0
  1638. self.selectedkey = self.GetItemData(self.selected)
  1639. self.SetItemState(self.selected,
  1640. wx.LIST_STATE_SELECTED,
  1641. wx.LIST_STATE_SELECTED)
  1642. self.ResizeColumns()
  1643. self.render = True
  1644. def OnCheckItem(self, index, flag):
  1645. """!Item is checked/unchecked"""
  1646. if self.render:
  1647. # redraw points
  1648. sourceMapWin = self.gcp.SrcMapWindow
  1649. sourceMapWin.UpdateMap(render=False, renderVector=False)
  1650. if self.gcp.show_target:
  1651. targetMapWin = self.gcp.TgtMapWindow
  1652. targetMapWin.UpdateMap(render=False, renderVector=False)
  1653. pass
  1654. def AddGCPItem(self):
  1655. """
  1656. Appends an item to GCP list
  1657. """
  1658. self.selectedkey = self.GetItemCount() + 1
  1659. self.Append([str(self.selectedkey), # GCP number
  1660. '0.0', # source E
  1661. '0.0', # source N
  1662. '0.0', # target E
  1663. '0.0', # target N
  1664. '', # forward error
  1665. '']) # backward error
  1666. self.selected = self.GetItemCount() - 1
  1667. self.SetItemData(self.selected, self.selectedkey)
  1668. self.SetItemState(self.selected,
  1669. wx.LIST_STATE_SELECTED,
  1670. wx.LIST_STATE_SELECTED)
  1671. self.ResizeColumns()
  1672. return self.selected
  1673. def DeleteGCPItem(self):
  1674. """
  1675. Deletes selected item in GCP list
  1676. """
  1677. if self.selected == wx.NOT_FOUND:
  1678. return
  1679. key = self.GetItemData(self.selected)
  1680. self.DeleteItem(self.selected)
  1681. return key
  1682. def ResizeColumns(self):
  1683. """!Resize columns"""
  1684. minWidth = [90, 120]
  1685. for i in range(self.GetColumnCount()):
  1686. self.SetColumnWidth(i, wx.LIST_AUTOSIZE)
  1687. # first column is checkbox, don't set to minWidth
  1688. if i > 0 and self.GetColumnWidth(i) < minWidth[i > 4]:
  1689. self.SetColumnWidth(i, minWidth[i > 4])
  1690. self.SendSizeEvent()
  1691. def GetSelected(self):
  1692. """!Get index of selected item"""
  1693. return self.selected
  1694. def OnItemSelected(self, event):
  1695. """
  1696. Item selected
  1697. """
  1698. if self.render and self.selected != event.GetIndex():
  1699. self.selected = event.GetIndex()
  1700. self.selectedkey = self.GetItemData(self.selected)
  1701. sourceMapWin = self.gcp.SrcMapWindow
  1702. sourceMapWin.UpdateMap(render=False, renderVector=False)
  1703. if self.gcp.show_target:
  1704. targetMapWin = self.gcp.TgtMapWindow
  1705. targetMapWin.UpdateMap(render=False, renderVector=False)
  1706. event.Skip()
  1707. def OnItemActivated(self, event):
  1708. """
  1709. When item double clicked, open editor to update coordinate values
  1710. """
  1711. coords = []
  1712. index = event.GetIndex()
  1713. key = self.GetItemData(index)
  1714. changed = False
  1715. for i in range(1, 5):
  1716. coords.append(self.GetItem(index, i).GetText())
  1717. dlg = EditGCP(parent=self, id=wx.ID_ANY, data=coords, gcpno=key)
  1718. if dlg.ShowModal() == wx.ID_OK:
  1719. values = dlg.GetValues() # string
  1720. if len(values) == 0:
  1721. wx.MessageBox(parent=self,
  1722. caption=_("Edit GCP"),
  1723. message=_("Invalid coordinate value. Operation cancelled."),
  1724. style=wx.CENTRE | wx.ICON_ERROR | wx.ID_OK)
  1725. else:
  1726. for i in range(len(values)):
  1727. if values[i] != coords[i]:
  1728. self.SetStringItem(index, i + 1, values[i])
  1729. changed = True
  1730. if changed:
  1731. # reset RMS and update mapcoordlist
  1732. self.SetStringItem(index, 5, '')
  1733. self.SetStringItem(index, 6, '')
  1734. key = self.GetItemData(index)
  1735. self.gcp.mapcoordlist[key] = [key,
  1736. float(values[0]),
  1737. float(values[1]),
  1738. float(values[2]),
  1739. float(values[3]),
  1740. 0.0,
  1741. 0.0]
  1742. self.gcp.UpdateColours()
  1743. def OnColClick(self, event):
  1744. """!ListCtrl forgets selected item..."""
  1745. self.selected = self.FindItemData(-1, self.selectedkey)
  1746. self.SetItemState(self.selected,
  1747. wx.LIST_STATE_SELECTED,
  1748. wx.LIST_STATE_SELECTED)
  1749. event.Skip()
  1750. class VectGroup(wx.Dialog):
  1751. """
  1752. Dialog to create a vector group (VREF file) for georectifying
  1753. @todo Replace by g.group
  1754. """
  1755. def __init__(self, parent, id, grassdb, location, mapset, group,
  1756. style=wx.DEFAULT_DIALOG_STYLE):
  1757. wx.Dialog.__init__(self, parent, id, style=style,
  1758. title = _("Create vector map group"))
  1759. self.grassdatabase = grassdb
  1760. self.xylocation = location
  1761. self.xymapset = mapset
  1762. self.xygroup = group
  1763. #
  1764. # get list of valid vector directories
  1765. #
  1766. vectlist = os.listdir(os.path.join(self.grassdatabase,
  1767. self.xylocation,
  1768. self.xymapset,
  1769. 'vector'))
  1770. for dir in vectlist:
  1771. if not os.path.isfile(os.path.join(self.grassdatabase,
  1772. self.xylocation,
  1773. self.xymapset,
  1774. 'vector',
  1775. dir,
  1776. 'coor')):
  1777. vectlist.remove(dir)
  1778. utils.ListSortLower(vectlist)
  1779. # path to vref file
  1780. self.vgrpfile = os.path.join(self.grassdatabase,
  1781. self.xylocation,
  1782. self.xymapset,
  1783. 'group',
  1784. self.xygroup,
  1785. 'VREF')
  1786. #
  1787. # buttons
  1788. #
  1789. self.btnCancel = wx.Button(parent = self,
  1790. id = wx.ID_CANCEL)
  1791. self.btnOK = wx.Button(parent = self,
  1792. id = wx.ID_OK)
  1793. self.btnOK.SetDefault()
  1794. #
  1795. # list of vector maps
  1796. #
  1797. self.listMap = wx.CheckListBox(parent = self, id = wx.ID_ANY,
  1798. choices = vectlist)
  1799. if os.path.isfile(self.vgrpfile):
  1800. f = open(self.vgrpfile)
  1801. try:
  1802. checked = []
  1803. for line in f.readlines():
  1804. line = line.replace('\n', '')
  1805. if len(line) < 1:
  1806. continue
  1807. checked.append(line)
  1808. self.listMap.SetCheckedStrings(checked)
  1809. finally:
  1810. f.close()
  1811. line = wx.StaticLine(parent = self,
  1812. id = wx.ID_ANY, size = (20, -1),
  1813. style = wx.LI_HORIZONTAL)
  1814. #
  1815. # layout
  1816. #
  1817. sizer = wx.BoxSizer(wx.VERTICAL)
  1818. box = wx.BoxSizer(wx.HORIZONTAL)
  1819. box.Add(item = wx.StaticText(parent = self, id = wx.ID_ANY,
  1820. label = _('Select vector map(s) to add to group:')),
  1821. flag = wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.LEFT,
  1822. border = 5)
  1823. box.Add(item = self.listMap,
  1824. flag = wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.LEFT,
  1825. border = 5)
  1826. sizer.Add(box, flag = wx.ALIGN_RIGHT | wx.ALL,
  1827. border = 3)
  1828. sizer.Add(item = line, proportion = 0,
  1829. flag = wx.GROW | wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT,
  1830. border = 5)
  1831. # buttons
  1832. btnSizer = wx.StdDialogButtonSizer()
  1833. btnSizer.AddButton(self.btnCancel)
  1834. btnSizer.AddButton(self.btnOK)
  1835. btnSizer.Realize()
  1836. sizer.Add(item = btnSizer, proportion = 0,
  1837. flag = wx.EXPAND | wx.ALL | wx.ALIGN_CENTER,
  1838. border = 5)
  1839. self.SetSizer(sizer)
  1840. sizer.Fit(self)
  1841. self.Layout()
  1842. def MakeVGroup(self):
  1843. """!Create VREF file"""
  1844. vgrouplist = []
  1845. for item in range(self.listMap.GetCount()):
  1846. if not self.listMap.IsChecked(item):
  1847. continue
  1848. vgrouplist.append(self.listMap.GetString(item))
  1849. f = open(self.vgrpfile, mode='w')
  1850. try:
  1851. for vect in vgrouplist:
  1852. f.write(vect + '\n')
  1853. finally:
  1854. f.close()
  1855. class EditGCP(wx.Dialog):
  1856. def __init__(self, parent, data, gcpno, id=wx.ID_ANY,
  1857. title=_("Edit GCP"),
  1858. style=wx.DEFAULT_DIALOG_STYLE):
  1859. """!Dialog for editing GPC and map coordinates in list control"""
  1860. wx.Dialog.__init__(self, parent, id, title=title, style=style)
  1861. panel = wx.Panel(parent=self)
  1862. sizer = wx.BoxSizer(wx.VERTICAL)
  1863. box = wx.StaticBox (parent=panel, id=wx.ID_ANY,
  1864. label=" %s %s " % (_("Ground Control Point No."), str(gcpno)))
  1865. boxSizer = wx.StaticBoxSizer(box, wx.VERTICAL)
  1866. # source coordinates
  1867. gridSizer = wx.GridBagSizer(vgap=5, hgap=5)
  1868. self.xcoord = wx.TextCtrl(parent=panel, id=wx.ID_ANY, size=(150, -1))
  1869. self.ycoord = wx.TextCtrl(parent=panel, id=wx.ID_ANY, size=(150, -1))
  1870. self.ecoord = wx.TextCtrl(parent=panel, id=wx.ID_ANY, size=(150, -1))
  1871. self.ncoord = wx.TextCtrl(parent=panel, id=wx.ID_ANY, size=(150, -1))
  1872. # swap source N, target E
  1873. tmp_coord = data[1]
  1874. data[1] = data[2]
  1875. data[2] = tmp_coord
  1876. row = 0
  1877. col = 0
  1878. idx = 0
  1879. for label, win in ((_("source E:"), self.xcoord),
  1880. (_("target E:"), self.ecoord),
  1881. (_("source N:"), self.ycoord),
  1882. (_("target N:"), self.ncoord)):
  1883. label = wx.StaticText(parent=panel, id=wx.ID_ANY,
  1884. label=label)
  1885. gridSizer.Add(item=label,
  1886. flag=wx.ALIGN_CENTER_VERTICAL,
  1887. pos=(row, col))
  1888. col += 1
  1889. win.SetValue(str(data[idx]))
  1890. gridSizer.Add(item=win,
  1891. pos=(row, col))
  1892. col += 1
  1893. idx += 1
  1894. if col > 3:
  1895. row += 1
  1896. col = 0
  1897. boxSizer.Add(item=gridSizer, proportion=1,
  1898. flag=wx.EXPAND | wx.ALL, border=5)
  1899. sizer.Add(item=boxSizer, proportion=1,
  1900. flag=wx.EXPAND | wx.ALL, border=5)
  1901. #
  1902. # buttons
  1903. #
  1904. self.btnCancel = wx.Button(panel, wx.ID_CANCEL)
  1905. self.btnOk = wx.Button(panel, wx.ID_OK)
  1906. self.btnOk.SetDefault()
  1907. btnSizer = wx.StdDialogButtonSizer()
  1908. btnSizer.AddButton(self.btnCancel)
  1909. btnSizer.AddButton(self.btnOk)
  1910. btnSizer.Realize()
  1911. sizer.Add(item=btnSizer, proportion=0,
  1912. flag=wx.ALIGN_RIGHT | wx.ALL, border=5)
  1913. panel.SetSizer(sizer)
  1914. sizer.Fit(self)
  1915. def GetValues(self, columns=None):
  1916. """!Return list of values (as strings).
  1917. """
  1918. valuelist = []
  1919. try:
  1920. float(self.xcoord.GetValue())
  1921. float(self.ycoord.GetValue())
  1922. float(self.ecoord.GetValue())
  1923. float(self.ncoord.GetValue())
  1924. except ValueError:
  1925. return valuelist
  1926. valuelist.append(self.xcoord.GetValue())
  1927. valuelist.append(self.ycoord.GetValue())
  1928. valuelist.append(self.ecoord.GetValue())
  1929. valuelist.append(self.ncoord.GetValue())
  1930. return valuelist
  1931. class GrSettingsDialog(wx.Dialog):
  1932. def __init__(self, parent, id, title, pos=wx.DefaultPosition, size=wx.DefaultSize,
  1933. style=wx.DEFAULT_DIALOG_STYLE):
  1934. wx.Dialog.__init__(self, parent, id, title, pos, size, style)
  1935. """
  1936. Dialog to set profile text options: font, title
  1937. and font size, axis labels and font size
  1938. """
  1939. #
  1940. # initialize variables
  1941. #
  1942. self.parent = parent
  1943. self.new_src_map = src_map
  1944. self.new_tgt_map = tgt_map
  1945. self.sdfactor = 0
  1946. self.symbol = {}
  1947. self.methods = ["nearest",
  1948. "bilinear",
  1949. "bilinear_f",
  1950. "cubic",
  1951. "cubic_f",
  1952. "lanczos",
  1953. "lanczos_f"]
  1954. # notebook
  1955. notebook = wx.Notebook(parent=self, id=wx.ID_ANY, style=wx.BK_DEFAULT)
  1956. self.__CreateSymbologyPage(notebook)
  1957. self.__CreateRectificationPage(notebook)
  1958. # buttons
  1959. btnSave = wx.Button(self, wx.ID_SAVE)
  1960. btnApply = wx.Button(self, wx.ID_APPLY)
  1961. btnClose = wx.Button(self, wx.ID_CLOSE)
  1962. btnApply.SetDefault()
  1963. # bindings
  1964. btnApply.Bind(wx.EVT_BUTTON, self.OnApply)
  1965. btnApply.SetToolTipString(_("Apply changes for the current session"))
  1966. btnSave.Bind(wx.EVT_BUTTON, self.OnSave)
  1967. btnSave.SetToolTipString(_("Apply and save changes to user settings file (default for next sessions)"))
  1968. btnClose.Bind(wx.EVT_BUTTON, self.OnClose)
  1969. btnClose.SetToolTipString(_("Close dialog"))
  1970. # sizers
  1971. btnSizer = wx.BoxSizer(wx.HORIZONTAL)
  1972. btnSizer.Add(btnApply, flag=wx.LEFT | wx.RIGHT, border=5)
  1973. btnSizer.Add(btnSave, flag=wx.LEFT | wx.RIGHT, border=5)
  1974. btnSizer.Add(btnClose, flag=wx.LEFT | wx.RIGHT, border=5)
  1975. # sizers
  1976. mainSizer = wx.BoxSizer(wx.VERTICAL)
  1977. mainSizer.Add(item=notebook, proportion=1, flag=wx.EXPAND | wx.ALL, border=5)
  1978. mainSizer.Add(item=btnSizer, proportion=0,
  1979. flag=wx.ALIGN_RIGHT | wx.ALL, border=5)
  1980. # flag=wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border=5)
  1981. self.SetSizer(mainSizer)
  1982. mainSizer.Fit(self)
  1983. def __CreateSymbologyPage(self, notebook):
  1984. """!Create notebook page with symbology settings"""
  1985. panel = wx.Panel(parent=notebook, id=wx.ID_ANY)
  1986. notebook.AddPage(page=panel, text=_("Symbology"))
  1987. sizer = wx.BoxSizer(wx.VERTICAL)
  1988. rmsgridSizer = wx.GridBagSizer(vgap=5, hgap=5)
  1989. rmsgridSizer.AddGrowableCol(1)
  1990. # highlight only highest forward RMS error
  1991. self.highlighthighest = wx.CheckBox(parent=panel, id=wx.ID_ANY,
  1992. label=_("Highlight highest RMS error only"))
  1993. hh = UserSettings.Get(group='gcpman', key='rms', subkey='highestonly')
  1994. self.highlighthighest.SetValue(hh)
  1995. rmsgridSizer.Add(item=self.highlighthighest, flag=wx.ALIGN_CENTER_VERTICAL, pos=(0, 0))
  1996. # RMS forward error threshold
  1997. rmslabel = wx.StaticText(parent=panel, id=wx.ID_ANY, label=_("Highlight RMS error > M + SD * factor:"))
  1998. rmslabel.SetToolTip(wx.ToolTip(_("Highlight GCPs with an RMS error larger than \n"
  1999. "mean + standard deviation * given factor. \n"
  2000. "Recommended values for this factor are between 1 and 2.")))
  2001. rmsgridSizer.Add(item=rmslabel, flag=wx.ALIGN_CENTER_VERTICAL, pos=(1, 0))
  2002. sdfactor = UserSettings.Get(group='gcpman', key='rms', subkey='sdfactor')
  2003. self.rmsWin = wx.TextCtrl(parent=panel, id=wx.ID_ANY,
  2004. size=(70,-1), style=wx.TE_NOHIDESEL)
  2005. self.rmsWin.SetValue("%s" % str(sdfactor))
  2006. if (self.parent.highest_only == True):
  2007. self.rmsWin.Disable()
  2008. self.symbol['sdfactor'] = self.rmsWin.GetId()
  2009. rmsgridSizer.Add(item=self.rmsWin, flag=wx.ALIGN_RIGHT, pos=(1, 1))
  2010. sizer.Add(item=rmsgridSizer, flag=wx.EXPAND | wx.ALL, border=5)
  2011. box = wx.StaticBox(parent=panel, id=wx.ID_ANY,
  2012. label=" %s " % _("Symbol settings"))
  2013. boxSizer = wx.StaticBoxSizer(box, wx.VERTICAL)
  2014. gridSizer = wx.GridBagSizer(vgap=5, hgap=5)
  2015. gridSizer.AddGrowableCol(1)
  2016. #
  2017. # general symbol color
  2018. #
  2019. row = 0
  2020. label = wx.StaticText(parent=panel, id=wx.ID_ANY, label=_("Color:"))
  2021. gridSizer.Add(item=label, flag=wx.ALIGN_CENTER_VERTICAL, pos=(row, 0))
  2022. col = UserSettings.Get(group='gcpman', key='symbol', subkey='color')
  2023. colWin = csel.ColourSelect(parent=panel, id=wx.ID_ANY,
  2024. colour=wx.Colour(col[0],
  2025. col[1],
  2026. col[2],
  2027. 255))
  2028. self.symbol['color'] = colWin.GetId()
  2029. gridSizer.Add(item=colWin,
  2030. flag=wx.ALIGN_RIGHT,
  2031. pos=(row, 1))
  2032. #
  2033. # symbol color for high forward RMS error
  2034. #
  2035. row += 1
  2036. label = wx.StaticText(parent=panel, id=wx.ID_ANY, label=_("Color for high RMS error:"))
  2037. gridSizer.Add(item=label, flag=wx.ALIGN_CENTER_VERTICAL, pos=(row, 0))
  2038. hcol = UserSettings.Get(group='gcpman', key='symbol', subkey='hcolor')
  2039. hcolWin = csel.ColourSelect(parent=panel, id=wx.ID_ANY,
  2040. colour=wx.Colour(hcol[0],
  2041. hcol[1],
  2042. hcol[2],
  2043. 255))
  2044. self.symbol['hcolor'] = hcolWin.GetId()
  2045. gridSizer.Add(item=hcolWin,
  2046. flag=wx.ALIGN_RIGHT,
  2047. pos=(row, 1))
  2048. #
  2049. # symbol color for selected GCP
  2050. #
  2051. row += 1
  2052. label = wx.StaticText(parent=panel, id=wx.ID_ANY, label=_("Color for selected GCP:"))
  2053. gridSizer.Add(item=label, flag=wx.ALIGN_CENTER_VERTICAL, pos=(row, 0))
  2054. scol = UserSettings.Get(group='gcpman', key='symbol', subkey='scolor')
  2055. scolWin = csel.ColourSelect(parent=panel, id=wx.ID_ANY,
  2056. colour=wx.Colour(scol[0],
  2057. scol[1],
  2058. scol[2],
  2059. 255))
  2060. self.symbol['scolor'] = scolWin.GetId()
  2061. gridSizer.Add(item=scolWin,
  2062. flag=wx.ALIGN_RIGHT,
  2063. pos=(row, 1))
  2064. #
  2065. # symbol color for unused GCP
  2066. #
  2067. row += 1
  2068. label = wx.StaticText(parent=panel, id=wx.ID_ANY, label=_("Color for unused GCPs:"))
  2069. gridSizer.Add(item=label, flag=wx.ALIGN_CENTER_VERTICAL, pos=(row, 0))
  2070. ucol = UserSettings.Get(group='gcpman', key='symbol', subkey='ucolor')
  2071. ucolWin = csel.ColourSelect(parent=panel, id=wx.ID_ANY,
  2072. colour=wx.Colour(ucol[0],
  2073. ucol[1],
  2074. ucol[2],
  2075. 255))
  2076. self.symbol['ucolor'] = ucolWin.GetId()
  2077. gridSizer.Add(item=ucolWin,
  2078. flag=wx.ALIGN_RIGHT,
  2079. pos=(row, 1))
  2080. # show unused GCPs
  2081. row += 1
  2082. self.showunused = wx.CheckBox(parent=panel, id=wx.ID_ANY,
  2083. label=_("Show unused GCPs"))
  2084. shuu = UserSettings.Get(group='gcpman', key='symbol', subkey='unused')
  2085. self.showunused.SetValue(shuu)
  2086. gridSizer.Add(item=self.showunused, flag=wx.ALIGN_CENTER_VERTICAL, pos=(row, 0))
  2087. #
  2088. # symbol size
  2089. #
  2090. row += 1
  2091. label = wx.StaticText(parent=panel, id=wx.ID_ANY, label=_("Symbol size:"))
  2092. gridSizer.Add(item=label, flag=wx.ALIGN_CENTER_VERTICAL, pos=(row, 0))
  2093. symsize = int(UserSettings.Get(group='gcpman', key='symbol', subkey='size'))
  2094. sizeWin = wx.SpinCtrl(parent=panel, id=wx.ID_ANY,
  2095. min=1, max=20)
  2096. sizeWin.SetValue(symsize)
  2097. self.symbol['size'] = sizeWin.GetId()
  2098. gridSizer.Add(item=sizeWin,
  2099. flag=wx.ALIGN_RIGHT,
  2100. pos=(row, 1))
  2101. #
  2102. # symbol width
  2103. #
  2104. row += 1
  2105. label = wx.StaticText(parent=panel, id=wx.ID_ANY, label=_("Line width:"))
  2106. gridSizer.Add(item=label, flag=wx.ALIGN_CENTER_VERTICAL, pos=(row, 0))
  2107. width = int(UserSettings.Get(group='gcpman', key='symbol', subkey='width'))
  2108. widWin = wx.SpinCtrl(parent=panel, id=wx.ID_ANY,
  2109. min=1, max=10)
  2110. widWin.SetValue(width)
  2111. self.symbol['width'] = widWin.GetId()
  2112. gridSizer.Add(item=widWin,
  2113. flag=wx.ALIGN_RIGHT,
  2114. pos=(row, 1))
  2115. boxSizer.Add(item=gridSizer, flag=wx.EXPAND)
  2116. sizer.Add(item=boxSizer, flag=wx.EXPAND | wx.ALL, border=5)
  2117. #
  2118. # maps to display
  2119. #
  2120. # source map to display
  2121. self.srcselection = gselect.Select(panel, id=wx.ID_ANY,
  2122. size=globalvar.DIALOG_GSELECT_SIZE, type='cell', updateOnPopup = False)
  2123. self.parent.grwiz.SwitchEnv('source')
  2124. self.srcselection.SetElementList(maptype)
  2125. # filter out all maps not in group
  2126. self.srcselection.tcp.GetElementList(elements = self.parent.src_maps)
  2127. # target map to display
  2128. self.tgtselection = gselect.Select(panel, id=wx.ID_ANY,
  2129. size=globalvar.DIALOG_GSELECT_SIZE, type='cell', updateOnPopup = False)
  2130. self.parent.grwiz.SwitchEnv('target')
  2131. self.tgtselection.SetElementList(maptype)
  2132. self.tgtselection.GetElementList()
  2133. sizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY, label=_('Select source map to display:')),
  2134. proportion=0, flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5)
  2135. sizer.Add(item=self.srcselection, proportion=0,
  2136. flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5)
  2137. self.srcselection.SetValue(src_map)
  2138. sizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY, label=_('Select target map to display:')),
  2139. proportion=0, flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5)
  2140. sizer.Add(item=self.tgtselection, proportion=0,
  2141. flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5)
  2142. self.tgtselection.SetValue(tgt_map)
  2143. # bindings
  2144. self.highlighthighest.Bind(wx.EVT_CHECKBOX, self.OnHighlight)
  2145. self.rmsWin.Bind(wx.EVT_TEXT, self.OnSDFactor)
  2146. self.srcselection.Bind(wx.EVT_TEXT, self.OnSrcSelection)
  2147. self.tgtselection.Bind(wx.EVT_TEXT, self.OnTgtSelection)
  2148. panel.SetSizer(sizer)
  2149. return panel
  2150. def __CreateRectificationPage(self, notebook):
  2151. """!Create notebook page with symbology settings"""
  2152. panel = wx.Panel(parent=notebook, id=wx.ID_ANY)
  2153. notebook.AddPage(page=panel, text=_("Rectification"))
  2154. sizer = wx.BoxSizer(wx.VERTICAL)
  2155. # transformation order
  2156. self.rb_grorder = wx.RadioBox(parent=panel, id=wx.ID_ANY,
  2157. label=" %s " % _("Select rectification order"),
  2158. choices=[_('1st order'), _('2nd order'), _('3rd order')],
  2159. majorDimension=wx.RA_SPECIFY_COLS)
  2160. sizer.Add(item=self.rb_grorder, proportion=0,
  2161. flag=wx.EXPAND | wx.ALL, border=5)
  2162. self.rb_grorder.SetSelection(self.parent.gr_order - 1)
  2163. # interpolation method
  2164. gridSizer = wx.GridBagSizer(vgap=5, hgap=5)
  2165. gridSizer.AddGrowableCol(1)
  2166. gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY, label=_('Select interpolation method:')),
  2167. pos=(0,0), flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5)
  2168. self.grmethod = wx.Choice(parent=panel, id=wx.ID_ANY,
  2169. choices = self.methods)
  2170. gridSizer.Add(item=self.grmethod, pos=(0,1),
  2171. flag=wx.ALIGN_RIGHT, border=5)
  2172. self.grmethod.SetStringSelection(self.parent.gr_method)
  2173. sizer.Add(item=gridSizer, flag=wx.EXPAND | wx.ALL, border=5)
  2174. # clip to region
  2175. self.check = wx.CheckBox(parent=panel, id=wx.ID_ANY,
  2176. label=_("clip to computational region in target location"))
  2177. sizer.Add(item=self.check, proportion=0,
  2178. flag=wx.EXPAND | wx.ALL, border=5)
  2179. self.check.SetValue(self.parent.clip_to_region)
  2180. # extension
  2181. sizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY, label=_('Extension for output maps:')),
  2182. proportion=0, flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5)
  2183. self.ext_txt = wx.TextCtrl(parent=panel, id=wx.ID_ANY, value="", size=(350,-1))
  2184. self.ext_txt.SetValue(self.parent.extension)
  2185. sizer.Add(item=self.ext_txt,
  2186. proportion=0, flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5)
  2187. # bindings
  2188. self.ext_txt.Bind(wx.EVT_TEXT, self.OnExtension)
  2189. self.Bind(wx.EVT_RADIOBOX, self.parent.OnGROrder, self.rb_grorder)
  2190. self.Bind(wx.EVT_CHOICE, self.OnMethod, self.grmethod)
  2191. self.Bind(wx.EVT_CHECKBOX, self.OnClipRegion, self.check)
  2192. panel.SetSizer(sizer)
  2193. return panel
  2194. def OnHighlight(self, event):
  2195. """!Checkbox 'highlighthighest' checked/unchecked"""
  2196. if self.highlighthighest.IsChecked():
  2197. self.parent.highest_only = True
  2198. self.rmsWin.Disable()
  2199. else:
  2200. self.parent.highest_only = False
  2201. self.rmsWin.Enable()
  2202. def OnSDFactor(self,event):
  2203. """!New factor for RMS threshold = M + SD * factor"""
  2204. self.sdfactor = float(event.GetString())
  2205. if self.sdfactor <= 0:
  2206. wx.MessageBox(parent=self,
  2207. caption=_("Update settings"),
  2208. message=_('RMS threshold factor must be > 0'),
  2209. style=wx.ICON_ERROR | wx.ID_OK | wx.CENTRE)
  2210. elif self.sdfactor < 1:
  2211. wx.MessageBox(parent=self,
  2212. caption=_("Update settings"),
  2213. message=_('RMS threshold factor is < 1\n'
  2214. 'Too many points might be highlighted'),
  2215. style=wx.ICON_EXCLAMATION | wx.ID_OK | wx.CENTRE)
  2216. def OnSrcSelection(self,event):
  2217. """!Source map to display selected"""
  2218. global src_map
  2219. tmp_map = event.GetString()
  2220. if not tmp_map == '' and not tmp_map == src_map:
  2221. self.new_src_map = tmp_map
  2222. def OnTgtSelection(self,event):
  2223. """!Target map to display selected"""
  2224. global tgt_map
  2225. tmp_map = event.GetString()
  2226. if not tmp_map == tgt_map:
  2227. self.new_tgt_map = tmp_map
  2228. def OnMethod(self, event):
  2229. self.parent.gr_method = self.methods[event.GetSelection()]
  2230. def OnClipRegion(self, event):
  2231. self.parent.clip_to_region = event.IsChecked()
  2232. def OnExtension(self, event):
  2233. self.parent.extension = event.GetString()
  2234. def UpdateSettings(self):
  2235. global src_map
  2236. global tgt_map
  2237. layers = None
  2238. UserSettings.Set(group='gcpman', key='rms', subkey='highestonly',
  2239. value=self.highlighthighest.GetValue())
  2240. if self.sdfactor > 0:
  2241. UserSettings.Set(group='gcpman', key='rms', subkey='sdfactor',
  2242. value=self.sdfactor)
  2243. self.parent.sdfactor = self.sdfactor
  2244. if self.parent.rmsthresh > 0:
  2245. self.parent.rmsthresh = self.parent.mean + self.parent.sdfactor * self.parent.rmssd
  2246. UserSettings.Set(group='gcpman', key='symbol', subkey='color',
  2247. value=tuple(wx.FindWindowById(self.symbol['color']).GetColour()))
  2248. UserSettings.Set(group='gcpman', key='symbol', subkey='hcolor',
  2249. value=tuple(wx.FindWindowById(self.symbol['hcolor']).GetColour()))
  2250. UserSettings.Set(group='gcpman', key='symbol', subkey='scolor',
  2251. value=tuple(wx.FindWindowById(self.symbol['scolor']).GetColour()))
  2252. UserSettings.Set(group='gcpman', key='symbol', subkey='ucolor',
  2253. value=tuple(wx.FindWindowById(self.symbol['ucolor']).GetColour()))
  2254. UserSettings.Set(group='gcpman', key='symbol', subkey='unused',
  2255. value=self.showunused.GetValue())
  2256. UserSettings.Set(group='gcpman', key='symbol', subkey='size',
  2257. value=wx.FindWindowById(self.symbol['size']).GetValue())
  2258. UserSettings.Set(group='gcpman', key='symbol', subkey='width',
  2259. value=wx.FindWindowById(self.symbol['width']).GetValue())
  2260. srcrender = False
  2261. srcrenderVector = False
  2262. tgtrender = False
  2263. tgtrenderVector = False
  2264. if self.new_src_map != src_map:
  2265. # remove old layer
  2266. layers = self.parent.grwiz.SrcMap.GetListOfLayers()
  2267. self.parent.grwiz.SrcMap.DeleteLayer(layers[0])
  2268. src_map = self.new_src_map
  2269. cmdlist = ['d.rast', 'map=%s' % src_map]
  2270. self.parent.grwiz.SwitchEnv('source')
  2271. self.parent.grwiz.SrcMap.AddLayer(type='raster', command=cmdlist, l_active=True,
  2272. name=utils.GetLayerNameFromCmd(cmdlist),
  2273. l_hidden=False, l_opacity=1.0, l_render=False)
  2274. self.parent.grwiz.SwitchEnv('target')
  2275. srcrender = True
  2276. if self.new_tgt_map != tgt_map:
  2277. # remove old layer
  2278. layers = self.parent.grwiz.TgtMap.GetListOfLayers()
  2279. if layers:
  2280. self.parent.grwiz.TgtMap.DeleteLayer(layers[0])
  2281. tgt_map = self.new_tgt_map
  2282. if tgt_map != '':
  2283. cmdlist = ['d.rast', 'map=%s' % tgt_map]
  2284. self.parent.grwiz.TgtMap.AddLayer(type='raster', command=cmdlist, l_active=True,
  2285. name=utils.GetLayerNameFromCmd(cmdlist),
  2286. l_hidden=False, l_opacity=1.0, l_render=False)
  2287. tgtrender = True
  2288. if self.parent.show_target == False:
  2289. self.parent.show_target = True
  2290. self.parent._mgr.GetPane("target").Show()
  2291. self.parent._mgr.Update()
  2292. self.parent.toolbars['gcpdisp'].Enable('zoommenu', enable = True)
  2293. self.parent.activemap.Enable()
  2294. self.parent.TgtMapWindow.ZoomToMap(layers = self.parent.TgtMap.GetListOfLayers())
  2295. else: # tgt_map == ''
  2296. if self.parent.show_target == True:
  2297. self.parent.show_target = False
  2298. self.parent._mgr.GetPane("target").Hide()
  2299. self.parent._mgr.Update()
  2300. self.parent.activemap.SetSelection(0)
  2301. self.parent.activemap.Enable(False)
  2302. self.parent.toolbars['gcpdisp'].Enable('zoommenu', enable = False)
  2303. self.parent.UpdateColours(srcrender, srcrenderVector, tgtrender, tgtrenderVector)
  2304. def OnSave(self, event):
  2305. """!Button 'Save' pressed"""
  2306. self.UpdateSettings()
  2307. fileSettings = {}
  2308. UserSettings.ReadSettingsFile(settings=fileSettings)
  2309. fileSettings['gcpman'] = UserSettings.Get(group='gcpman')
  2310. file = UserSettings.SaveToFile(fileSettings)
  2311. self.parent.parent.goutput.WriteLog(_('GCP Manager settings saved to file \'%s\'.') % file)
  2312. #self.Close()
  2313. def OnApply(self, event):
  2314. """!Button 'Apply' pressed"""
  2315. self.UpdateSettings()
  2316. #self.Close()
  2317. def OnClose(self, event):
  2318. """!Button 'Cancel' pressed"""
  2319. self.Close()