gcpmanager.py 102 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750
  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. # region clipping for georectified map
  664. self.clip_to_region = False
  665. # number of GCPs selected to be used for georectification (checked)
  666. self.GCPcount = 0
  667. # forward RMS error
  668. self.fwd_rmserror = 0.0
  669. # backward RMS error
  670. self.bkw_rmserror = 0.0
  671. # list map coords and ID of map display they came from
  672. self.mapcoordlist = []
  673. self.mapcoordlist.append([ 0, # GCP number
  674. 0.0, # source east
  675. 0.0, # source north
  676. 0.0, # target east
  677. 0.0, # target north
  678. 0.0, # forward error
  679. 0.0 ] ) # backward error
  680. # init vars to highlight high RMS errors
  681. self.highest_only = True
  682. self.show_unused = True
  683. self.highest_key = -1
  684. self.rmsthresh = 0
  685. self.rmsmean = 0
  686. self.rmssd = 0
  687. self.SetTarget(self.xygroup, self.currentlocation, self.currentmapset)
  688. self.itemDataMap = None
  689. # images for column sorting
  690. # CheckListCtrlMixin must set an ImageList first
  691. self.il = self.list.GetImageList(wx.IMAGE_LIST_SMALL)
  692. SmallUpArrow = wx.BitmapFromImage(getSmallUpArrowImage())
  693. SmallDnArrow = wx.BitmapFromImage(getSmallDnArrowImage())
  694. self.sm_dn = self.il.Add(SmallDnArrow)
  695. self.sm_up = self.il.Add(SmallUpArrow)
  696. # set mouse characteristics
  697. self.mapwin = self.SrcMapWindow
  698. self.mapwin.mouse['box'] = 'point'
  699. self.mapwin.mouse["use"] == "pointer"
  700. self.mapwin.zoomtype = 0
  701. self.mapwin.pen = wx.Pen(colour='black', width=2, style=wx.SOLID)
  702. self.mapwin.SetCursor(self.cursors["cross"])
  703. self.mapwin = self.TgtMapWindow
  704. # set mouse characteristics
  705. self.mapwin.mouse['box'] = 'point'
  706. self.mapwin.mouse["use"] == "pointer"
  707. self.mapwin.zoomtype = 0
  708. self.mapwin.pen = wx.Pen(colour='black', width=2, style=wx.SOLID)
  709. self.mapwin.SetCursor(self.cursors["cross"])
  710. #
  711. # show new display & draw map
  712. #
  713. self.MapWindow = self.TgtMapWindow
  714. self.Map = self.TgtMap
  715. self.OnZoomToMap(None)
  716. self.MapWindow = self.SrcMapWindow
  717. self.Map = self.SrcMap
  718. self.OnZoomToMap(None)
  719. #
  720. # bindings
  721. #
  722. self.Bind(wx.EVT_ACTIVATE, self.OnFocus)
  723. self.Bind(wx.EVT_CLOSE, self.OnQuit)
  724. def __del__(self):
  725. """!Disable GCP manager mode"""
  726. self.parent.gcpmanagement = None
  727. def CreateGCPList(self):
  728. """!Create GCP List Control"""
  729. return GCPList(parent=self, gcp=self)
  730. # Used by the ColumnSorterMixin, see wx/lib/mixins/listctrl.py
  731. def GetListCtrl(self):
  732. return self.list
  733. # Used by the ColumnSorterMixin, see wx/lib/mixins/listctrl.py
  734. def GetSortImages(self):
  735. return (self.sm_dn, self.sm_up)
  736. def InitMapDisplay(self):
  737. self.list.LoadData()
  738. # initialize column sorter
  739. self.itemDataMap = self.mapcoordlist
  740. ncols = self.list.GetColumnCount()
  741. ColumnSorterMixin.__init__(self, ncols)
  742. # init to ascending sort on first click
  743. self._colSortFlag = [1] * ncols
  744. def SetTarget(self, tgroup, tlocation, tmapset):
  745. """
  746. Sets rectification target to current location and mapset
  747. """
  748. # check to see if we are georectifying map in current working location/mapset
  749. if self.newlocation == self.currentlocation and self.newmapset == self.currentmapset:
  750. gcmd.RunCommand('i.target',
  751. parent = self,
  752. flags = 'c',
  753. group = tgroup)
  754. else:
  755. self.grwiz.SwitchEnv('source')
  756. gcmd.RunCommand('i.target',
  757. parent = self,
  758. group = tgroup,
  759. location = tlocation,
  760. mapset = tmapset)
  761. self.grwiz.SwitchEnv('target')
  762. def AddGCP(self, event):
  763. """
  764. Appends an item to GCP list
  765. """
  766. keyval = self.list.AddGCPItem() + 1
  767. # source east, source north, target east, target north, forward error, backward error
  768. self.mapcoordlist.append([ keyval, # GCP number
  769. 0.0, # source east
  770. 0.0, # source north
  771. 0.0, # target east
  772. 0.0, # target north
  773. 0.0, # forward error
  774. 0.0 ] ) # backward error
  775. if self.statusbarWin['toggle'].GetSelection() == 7: # go to
  776. self.StatusbarUpdate()
  777. def DeleteGCP(self, event):
  778. """
  779. Deletes selected item in GCP list
  780. """
  781. minNumOfItems = self.OnGROrder(None)
  782. if self.list.GetItemCount() <= minNumOfItems:
  783. wx.MessageBox(parent=self, message=_("At least %d GCPs required. Operation cancelled.") % minNumOfItems,
  784. caption=_("Delete GCP"), style=wx.OK | wx.ICON_INFORMATION)
  785. return
  786. key = self.list.DeleteGCPItem()
  787. del self.mapcoordlist[key]
  788. # update key and GCP number
  789. for newkey in range(key, len(self.mapcoordlist)):
  790. index = self.list.FindItemData(-1, newkey + 1)
  791. self.mapcoordlist[newkey][0] = newkey
  792. self.list.SetStringItem(index, 0, str(newkey))
  793. self.list.SetItemData(index, newkey)
  794. # update selected
  795. if self.list.GetItemCount() > 0:
  796. if self.list.selected < self.list.GetItemCount():
  797. self.list.selectedkey = self.list.GetItemData(self.list.selected)
  798. else:
  799. self.list.selected = self.list.GetItemCount() - 1
  800. self.list.selectedkey = self.list.GetItemData(self.list.selected)
  801. self.list.SetItemState(self.list.selected,
  802. wx.LIST_STATE_SELECTED,
  803. wx.LIST_STATE_SELECTED)
  804. else:
  805. self.list.selected = wx.NOT_FOUND
  806. self.list.selectedkey = -1
  807. self.UpdateColours()
  808. if self.statusbarWin['toggle'].GetSelection() == 7: # go to
  809. self.StatusbarUpdate()
  810. if self.list.selectedkey > 0:
  811. self.statusbarWin['goto'].SetValue(self.list.selectedkey)
  812. #self.statusbarWin['goto'].SetValue(0)
  813. def ClearGCP(self, event):
  814. """
  815. Clears all values in selected item of GCP list and unchecks it
  816. """
  817. index = self.list.GetSelected()
  818. for i in range(4):
  819. self.list.SetStringItem(index, i, '0.0')
  820. self.list.SetStringItem(index, 4, '')
  821. self.list.SetStringItem(index, 5, '')
  822. self.list.CheckItem(index, False)
  823. key = self.list.GetItemData(index)
  824. # GCP number, source E, source N, target E, target N, fwd error, bkwd error
  825. self.mapcoordlist[key] = [key, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
  826. def DrawGCP(self, coordtype):
  827. """
  828. Updates GCP and map coord maps and redraws
  829. active (checked) GCP markers
  830. """
  831. self.highest_only = UserSettings.Get(group='gcpman', key='rms', subkey='highestonly')
  832. self.show_unused = UserSettings.Get(group='gcpman', key='symbol', subkey='unused')
  833. col = UserSettings.Get(group='gcpman', key='symbol', subkey='color')
  834. wxLowCol = wx.Colour(col[0], col[1], col[2], 255)
  835. col = UserSettings.Get(group='gcpman', key='symbol', subkey='hcolor')
  836. wxHiCol = wx.Colour(col[0], col[1], col[2], 255)
  837. col = UserSettings.Get(group='gcpman', key='symbol', subkey='scolor')
  838. wxSelCol = wx.Colour(col[0], col[1], col[2], 255)
  839. col = UserSettings.Get(group='gcpman', key='symbol', subkey='ucolor')
  840. wxUnCol = wx.Colour(col[0], col[1], col[2], 255)
  841. spx = UserSettings.Get(group='gcpman', key='symbol', subkey='size')
  842. wpx = UserSettings.Get(group='gcpman', key='symbol', subkey='width')
  843. font = self.GetFont()
  844. font.SetPointSize(int(spx) + 2)
  845. penOrig = polypenOrig = None
  846. mapWin = None
  847. if coordtype == 'source':
  848. mapWin = self.SrcMapWindow
  849. e_idx = 1
  850. n_idx = 2
  851. elif coordtype == 'target':
  852. mapWin = self.TgtMapWindow
  853. e_idx = 3
  854. n_idx = 4
  855. if not mapWin:
  856. wx.MessageBox(parent=self,
  857. message="%s%s." % (_("mapwin not defined for "),
  858. str(idx)),
  859. caption=_("Error"), style=wx.OK | wx.ICON_ERROR | wx.CENTRE)
  860. return
  861. #for gcp in self.mapcoordlist:
  862. for idx in range(self.list.GetItemCount()):
  863. key = self.list.GetItemData(idx)
  864. gcp = self.mapcoordlist[key]
  865. if not self.list.IsChecked(idx):
  866. if self.show_unused:
  867. wxCol = wxUnCol
  868. else:
  869. continue
  870. else:
  871. if self.highest_only == True:
  872. if key == self.highest_key:
  873. wxCol = wxHiCol
  874. else:
  875. wxCol = wxLowCol
  876. elif self.rmsthresh > 0:
  877. if (gcp[5] > self.rmsthresh):
  878. wxCol = wxHiCol
  879. else:
  880. wxCol = wxLowCol
  881. if idx == self.list.selected:
  882. wxCol = wxSelCol
  883. if not penOrig:
  884. penOrig = mapWin.pen
  885. polypenOrig = mapWin.polypen
  886. mapWin.pen = wx.Pen(colour=wxCol, width=wpx, style=wx.SOLID)
  887. mapWin.polypen = wx.Pen(colour=wxCol, width=wpx, style=wx.SOLID) # ?
  888. mapWin.pen.SetColour(wxCol)
  889. mapWin.polypen.SetColour(wxCol)
  890. coord = mapWin.Cell2Pixel((gcp[e_idx], gcp[n_idx]))
  891. mapWin.DrawCross(pdc=mapWin.pdcTmp, coords=coord,
  892. size=spx, text={ 'text' : '%s' % str(gcp[0]),
  893. 'active' : True,
  894. 'font' : font,
  895. 'color': wxCol,
  896. 'coords': [coord[0] + 5,
  897. coord[1] + 5,
  898. 5,
  899. 5]})
  900. if penOrig:
  901. mapWin.pen = penOrig
  902. mapWin.polypen = polypenOrig
  903. def SetGCPData(self, coordtype, coord, mapdisp=None, confirm=False):
  904. """
  905. Inserts coordinates from file, mouse click on map, or after editing
  906. into selected item of GCP list and checks it for use
  907. """
  908. index = self.list.GetSelected()
  909. if index == wx.NOT_FOUND:
  910. return
  911. coord0 = coord[0]
  912. coord1 = coord[1]
  913. key = self.list.GetItemData(index)
  914. if confirm:
  915. if self.MapWindow == self.SrcMapWindow:
  916. currloc = _("source")
  917. else:
  918. currloc = _("target")
  919. ret = wx.MessageBox(parent=self,
  920. caption=_("Set GCP coordinates"),
  921. message=_('Set %s coordinates for GCP No. %s? \n\n'
  922. 'East: %s \n'
  923. 'North: %s') % (currloc, str(key), str(coord0), str(coord1)),
  924. style=wx.ICON_QUESTION | wx.YES_NO | wx.CENTRE)
  925. # for wingrass
  926. if os.name == 'nt':
  927. self.MapWindow.SetFocus()
  928. if ret == wx.NO:
  929. return
  930. if coordtype == 'source':
  931. self.list.SetStringItem(index, 1, str(coord0))
  932. self.list.SetStringItem(index, 2, str(coord1))
  933. self.mapcoordlist[key][1] = coord[0]
  934. self.mapcoordlist[key][2] = coord[1]
  935. elif coordtype == 'target':
  936. self.list.SetStringItem(index, 3, str(coord0))
  937. self.list.SetStringItem(index, 4, str(coord1))
  938. self.mapcoordlist[key][3] = coord[0]
  939. self.mapcoordlist[key][4] = coord[1]
  940. self.list.SetStringItem(index, 5, '0')
  941. self.list.SetStringItem(index, 6, '0')
  942. self.mapcoordlist[key][5] = 0.0
  943. self.mapcoordlist[key][6] = 0.0
  944. # self.list.ResizeColumns()
  945. def SaveGCPs(self, event):
  946. """
  947. Make a POINTS file or save GCP coordinates to existing POINTS file
  948. """
  949. self.GCPcount = 0
  950. try:
  951. f = open(self.file['points'], mode='w')
  952. # use os.linesep or '\n' here ???
  953. f.write('# Ground Control Points File\n')
  954. f.write("# \n")
  955. f.write("# target location: " + self.currentlocation + '\n')
  956. f.write("# target mapset: " + self.currentmapset + '\n')
  957. f.write("#\tsource\t\ttarget\t\tstatus\n")
  958. f.write("#\teast\tnorth\teast\tnorth\t(1=ok, 0=ignore)\n")
  959. f.write("#----------------------- ----------------------- ---------------\n")
  960. for index in range(self.list.GetItemCount()):
  961. if self.list.IsChecked(index) == True:
  962. check = "1"
  963. self.GCPcount += 1
  964. else:
  965. check = "0"
  966. coord0 = self.list.GetItem(index, 1).GetText()
  967. coord1 = self.list.GetItem(index, 2).GetText()
  968. coord2 = self.list.GetItem(index, 3).GetText()
  969. coord3 = self.list.GetItem(index, 4).GetText()
  970. f.write(coord0 + ' ' + coord1 + ' ' + coord2 + ' ' + coord3 + ' ' + check + '\n')
  971. except IOError, err:
  972. wx.MessageBox(parent=self,
  973. message="%s <%s>. %s%s" % (_("Writing POINTS file failed"),
  974. self.file['points'], os.linesep, err),
  975. caption=_("Error"), style=wx.OK | wx.ICON_ERROR | wx.CENTRE)
  976. return
  977. f.close()
  978. # if event != None save also to backup file
  979. if event:
  980. shutil.copy(self.file['points'], self.file['points_bak'])
  981. self.parent.goutput.WriteLog(_('POINTS file saved for group <%s>') % self.xygroup)
  982. #self.SetStatusText(_('POINTS file saved'))
  983. def ReadGCPs(self):
  984. """
  985. Reads GCPs and georectified coordinates from POINTS file
  986. """
  987. self.GCPcount = 0
  988. sourceMapWin = self.SrcMapWindow
  989. targetMapWin = self.TgtMapWindow
  990. #targetMapWin = self.parent.curr_page.maptree.mapdisplay.MapWindow
  991. if not sourceMapWin:
  992. wx.MessageBox(parent=self,
  993. message="%s. %s%s" % (_("source mapwin not defined"),
  994. os.linesep, err),
  995. caption=_("Error"), style=wx.OK | wx.ICON_ERROR | wx.CENTRE)
  996. if not targetMapWin:
  997. wx.MessageBox(parent=self,
  998. message="%s. %s%s" % (_("target mapwin not defined"),
  999. os.linesep, err),
  1000. caption=_("Error"), style=wx.OK | wx.ICON_ERROR | wx.CENTRE)
  1001. try:
  1002. f = open(self.file['points'], 'r')
  1003. GCPcnt = 0
  1004. for line in f.readlines():
  1005. if line[0] == '#' or line =='':
  1006. continue
  1007. line = line.replace('\n', '').strip()
  1008. coords = map(float, line.split())
  1009. if coords[4] == 1:
  1010. check = True
  1011. self.GCPcount +=1
  1012. else:
  1013. check = False
  1014. self.AddGCP(event=None)
  1015. self.SetGCPData('source', (coords[0], coords[1]), sourceMapWin)
  1016. self.SetGCPData('target', (coords[2], coords[3]), targetMapWin)
  1017. index = self.list.GetSelected()
  1018. if index != wx.NOT_FOUND:
  1019. self.list.CheckItem(index, check)
  1020. GCPcnt += 1
  1021. except IOError, err:
  1022. wx.MessageBox(parent=self,
  1023. message="%s <%s>. %s%s" % (_("Reading POINTS file failed"),
  1024. self.file['points'], os.linesep, err),
  1025. caption=_("Error"), style=wx.OK | wx.ICON_ERROR | wx.CENTRE)
  1026. return
  1027. f.close()
  1028. if GCPcnt == 0:
  1029. # 3 gcp is minimum
  1030. for i in range(3):
  1031. self.AddGCP(None)
  1032. if self.CheckGCPcount():
  1033. # calculate RMS
  1034. self.RMSError(self.xygroup, self.gr_order)
  1035. def ReloadGCPs(self, event):
  1036. """!Reload data from file"""
  1037. # use backup
  1038. shutil.copy(self.file['points_bak'], self.file['points'])
  1039. # delete all items in mapcoordlist
  1040. self.mapcoordlist = []
  1041. self.mapcoordlist.append([ 0, # GCP number
  1042. 0.0, # source east
  1043. 0.0, # source north
  1044. 0.0, # target east
  1045. 0.0, # target north
  1046. 0.0, # forward error
  1047. 0.0 ] ) # backward error
  1048. self.list.LoadData()
  1049. self.itemDataMap = self.mapcoordlist
  1050. # draw GCPs (source and target)
  1051. sourceMapWin = self.SrcMapWindow
  1052. sourceMapWin.UpdateMap(render=False, renderVector=False)
  1053. if self.show_target:
  1054. targetMapWin = self.TgtMapWindow
  1055. targetMapWin.UpdateMap(render=False, renderVector=False)
  1056. def OnFocus(self, event):
  1057. # self.grwiz.SwitchEnv('source')
  1058. pass
  1059. def OnRMS(self, event):
  1060. """
  1061. RMS button handler
  1062. """
  1063. self.RMSError(self.xygroup,self.gr_order)
  1064. sourceMapWin = self.SrcMapWindow
  1065. sourceMapWin.UpdateMap(render=False, renderVector=False)
  1066. if self.show_target:
  1067. targetMapWin = self.TgtMapWindow
  1068. targetMapWin.UpdateMap(render=False, renderVector=False)
  1069. def CheckGCPcount(self, msg=False):
  1070. """
  1071. Checks to make sure that the minimum number of GCPs have been defined and
  1072. are active for the selected transformation order
  1073. """
  1074. if (self.GCPcount < 3 and self.gr_order == 1) or \
  1075. (self.GCPcount < 6 and self.gr_order == 2) or \
  1076. (self.GCPcount < 10 and self.gr_order == 3):
  1077. if msg:
  1078. wx.MessageBox(parent=self,
  1079. caption=_("RMS Error"),
  1080. message=_('Insufficient points defined and active (checked) '
  1081. 'for selected rectification method.\n'
  1082. '3+ points needed for 1st order,\n'
  1083. '6+ points for 2nd order, and\n'
  1084. '10+ points for 3rd order.'),
  1085. style=wx.ICON_INFORMATION | wx.ID_OK | wx.CENTRE)
  1086. return False
  1087. else:
  1088. return True
  1089. def OnGeorect(self, event):
  1090. """
  1091. Georectifies map(s) in group using i.rectify or v.transform
  1092. """
  1093. global maptype
  1094. self.SaveGCPs(None)
  1095. if self.CheckGCPcount(msg=True) == False:
  1096. return
  1097. if maptype == 'cell':
  1098. self.grwiz.SwitchEnv('source')
  1099. cmdlist = ['i.rectify','-a','group=%s' % self.xygroup,
  1100. 'extension=%s' % self.extension,'order=%s' % self.gr_order]
  1101. if self.clip_to_region:
  1102. cmdlist.append('-c')
  1103. self.parent.goutput.RunCmd(cmdlist, compReg=False,
  1104. switchPage=True)
  1105. time.sleep(.1)
  1106. elif maptype == 'vector':
  1107. outmsg = ''
  1108. # loop through all vectors in VREF
  1109. # and move resulting vector to target location
  1110. # make sure current mapset has a vector folder
  1111. if not os.path.isdir(os.path.join(self.grassdatabase,
  1112. self.currentlocation,
  1113. self.currentmapset,
  1114. 'vector')):
  1115. os.mkdir(os.path.join(self.grassdatabase,
  1116. self.currentlocation,
  1117. self.currentmapset,
  1118. 'vector'))
  1119. self.grwiz.SwitchEnv('source')
  1120. # make list of vectors to georectify from VREF
  1121. f = open(self.file['vgrp'])
  1122. vectlist = []
  1123. try:
  1124. for vect in f.readlines():
  1125. vect = vect.strip('\n')
  1126. if len(vect) < 1:
  1127. continue
  1128. vectlist.append(vect)
  1129. finally:
  1130. f.close()
  1131. # georectify each vector in VREF using v.transform
  1132. for vect in vectlist:
  1133. self.outname = vect + '_' + self.extension
  1134. self.parent.goutput.WriteLog(text = _('Transforming <%s>...') % vect,
  1135. switchPage = True)
  1136. msg = err = ''
  1137. ret, out, err = gcmd.RunCommand('v.transform',
  1138. flags = '-o',
  1139. input=vect,
  1140. output=self.outname,
  1141. pointsfile=self.file['points'],
  1142. getErrorMsg=True, read=True)
  1143. if ret == 0:
  1144. self.VectGRList.append(self.outname)
  1145. print err
  1146. # note: WriteLog doesn't handle GRASS_INFO_PERCENT well, so using a print here
  1147. # self.parent.goutput.WriteLog(text = _(err), switchPage = True)
  1148. self.parent.goutput.WriteLog(text = _(out), switchPage = True)
  1149. else:
  1150. self.parent.goutput.WriteError(_('Georectification of vector map <%s> failed') %
  1151. self.outname)
  1152. self.parent.goutput.WriteError(_(err))
  1153. # FIXME
  1154. # Copying database information not working.
  1155. # Does not copy from xy location to current location
  1156. # TODO: replace $GISDBASE etc with real paths
  1157. # xyLayer = []
  1158. # for layer in grass.vector_db(map = vect).itervalues():
  1159. # xyLayer.append((layer['driver'],
  1160. # layer['database'],
  1161. # layer['table']))
  1162. # dbConnect = grass.db_connection()
  1163. # print 'db connection =', dbConnect
  1164. # for layer in xyLayer:
  1165. # self.parent.goutput.RunCmd(['db.copy',
  1166. # '--q',
  1167. # '--o',
  1168. # 'from_driver=%s' % layer[0],
  1169. # 'from_database=%s' % layer[1],
  1170. # 'from_table=%s' % layer[2],
  1171. # 'to_driver=%s' % dbConnect['driver'],
  1172. # 'to_database=%s' % dbConnect['database'],
  1173. # 'to_table=%s' % layer[2] + '_' + self.extension])
  1174. # copy all georectified vectors from source location to current location
  1175. for name in self.VectGRList:
  1176. xyvpath = os.path.join(self.grassdatabase,
  1177. self.xylocation,
  1178. self.xymapset,
  1179. 'vector',
  1180. name)
  1181. vpath = os.path.join(self.grassdatabase,
  1182. self.currentlocation,
  1183. self.currentmapset,
  1184. 'vector',
  1185. name)
  1186. if os.path.isdir(vpath):
  1187. self.parent.goutput.WriteWarning(_('Vector map <%s> already exists. '
  1188. 'Change extension name and '
  1189. 'georectify again.') % self.outname)
  1190. break
  1191. else:
  1192. # use shutil.copytree() because shutil.move() deletes src dir
  1193. shutil.copytree(xyvpath, vpath)
  1194. # TODO: connect vectors to copied tables with v.db.connect
  1195. wx.MessageBox('For all vector maps georectified successfully, ' + '\n' +
  1196. 'you will need to copy any attribute tables' + '\n' +
  1197. 'and reconnect them to the georectified vectors')
  1198. self.grwiz.SwitchEnv('target')
  1199. def OnGeorectDone(self, **kargs):
  1200. """!Print final message"""
  1201. global maptype
  1202. if maptype == 'cell':
  1203. return
  1204. returncode = kargs['returncode']
  1205. if returncode == 0:
  1206. self.VectGRList.append(self.outname)
  1207. print '*****vector list = ' + str(self.VectGRList)
  1208. else:
  1209. self.parent.goutput.WriteError(_('Georectification of vector map <%s> failed') %
  1210. self.outname)
  1211. def OnSettings(self, event):
  1212. """!GCP Manager settings"""
  1213. dlg = GrSettingsDialog(parent=self, id=wx.ID_ANY, title=_('GCP Manager settings'))
  1214. if dlg.ShowModal() == wx.ID_OK:
  1215. pass
  1216. dlg.Destroy()
  1217. def UpdateColours(self, srcrender=False, srcrenderVector=False,
  1218. tgtrender=False, tgtrenderVector=False):
  1219. """!update colours"""
  1220. highest_fwd_err = 0.0
  1221. self.highest_key = 0
  1222. highest_idx = 0
  1223. for index in range(self.list.GetItemCount()):
  1224. if self.list.IsChecked(index):
  1225. key = self.list.GetItemData(index)
  1226. fwd_err = self.mapcoordlist[key][5]
  1227. if self.highest_only == True:
  1228. self.list.SetItemTextColour(index, wx.BLACK)
  1229. if highest_fwd_err < fwd_err:
  1230. highest_fwd_err = fwd_err
  1231. self.highest_key = key
  1232. highest_idx = index
  1233. elif self.rmsthresh > 0:
  1234. if (fwd_err > self.rmsthresh):
  1235. self.list.SetItemTextColour(index, wx.RED)
  1236. else:
  1237. self.list.SetItemTextColour(index, wx.BLACK)
  1238. else:
  1239. self.list.SetItemTextColour(index, wx.BLACK)
  1240. if self.highest_only and highest_fwd_err > 0.0:
  1241. self.list.SetItemTextColour(highest_idx, wx.RED)
  1242. sourceMapWin = self.SrcMapWindow
  1243. sourceMapWin.UpdateMap(render=srcrender, renderVector=srcrenderVector)
  1244. if self.show_target:
  1245. targetMapWin = self.TgtMapWindow
  1246. targetMapWin.UpdateMap(render=tgtrender, renderVector=tgtrenderVector)
  1247. def OnQuit(self, event):
  1248. """!Quit georectifier"""
  1249. ret = wx.MessageBox(parent=self,
  1250. caption=_("Quit GCP Manager"),
  1251. message=_('Save ground control points?'),
  1252. style=wx.ICON_QUESTION | wx.YES_NO | wx.CANCEL | wx.CENTRE)
  1253. if ret != wx.CANCEL:
  1254. if ret == wx.YES:
  1255. self.SaveGCPs(None)
  1256. elif ret == wx.NO:
  1257. # restore POINTS file from backup
  1258. if os.path.exists(self.file['points_bak']):
  1259. shutil.copy(self.file['points_bak'], self.file['points'])
  1260. if os.path.exists(self.file['points_bak']):
  1261. os.unlink(self.file['points_bak'])
  1262. self.SrcMap.Clean()
  1263. self.TgtMap.Clean()
  1264. self.grwiz.Cleanup()
  1265. self.Destroy()
  1266. #event.Skip()
  1267. def OnGROrder(self, event):
  1268. """
  1269. sets transformation order for georectifying
  1270. """
  1271. if event:
  1272. self.gr_order = event.GetInt() + 1
  1273. numOfItems = self.list.GetItemCount()
  1274. minNumOfItems = numOfItems
  1275. if self.gr_order == 1:
  1276. minNumOfItems = 3
  1277. # self.SetStatusText(_('Insufficient points, 3+ points needed for 1st order'))
  1278. elif self.gr_order == 2:
  1279. minNumOfItems = 6
  1280. diff = 6 - numOfItems
  1281. # self.SetStatusText(_('Insufficient points, 6+ points needed for 2nd order'))
  1282. elif self.gr_order == 3:
  1283. minNumOfItems = 10
  1284. # self.SetStatusText(_('Insufficient points, 10+ points needed for 3rd order'))
  1285. for i in range(minNumOfItems - numOfItems):
  1286. self.AddGCP(None)
  1287. return minNumOfItems
  1288. def RMSError(self, xygroup, order):
  1289. """
  1290. Uses g.transform to calculate forward and backward error for each used GCP
  1291. in POINTS file and insert error values into GCP list.
  1292. Calculates total forward and backward RMS error for all used points
  1293. """
  1294. # save GCPs to points file to make sure that all checked GCPs are used
  1295. self.SaveGCPs(None)
  1296. #self.SetStatusText('')
  1297. if self.CheckGCPcount(msg=True) == False:
  1298. return
  1299. # get list of forward and reverse rms error values for each point
  1300. self.grwiz.SwitchEnv('source')
  1301. ret = gcmd.RunCommand('g.transform',
  1302. parent = self,
  1303. read = True,
  1304. group = xygroup,
  1305. order = order)
  1306. self.grwiz.SwitchEnv('target')
  1307. if ret:
  1308. errlist = ret.splitlines()
  1309. else:
  1310. wx.MessageBox(parent=self,
  1311. caption=_("RMS Error"),
  1312. message=_('Could not calculate RMS Error. \n'
  1313. 'Possible error with g.transform.'),
  1314. style=wx.ICON_ERROR | wx.ID_OK | wx.CENTRE)
  1315. return
  1316. # insert error values into GCP list for checked items
  1317. sdfactor = float(UserSettings.Get(group='gcpman', key='rms', subkey='sdfactor'))
  1318. GCPcount = 0
  1319. sumsq_fwd_err = 0.0
  1320. sumsq_bkw_err = 0.0
  1321. sum_fwd_err = 0.0
  1322. highest_fwd_err = 0.0
  1323. self.highest_key = 0
  1324. highest_idx = 0
  1325. for index in range(self.list.GetItemCount()):
  1326. key = self.list.GetItemData(index)
  1327. if self.list.IsChecked(index):
  1328. fwd_err, bkw_err = errlist[GCPcount].split()
  1329. self.list.SetStringItem(index, 5, fwd_err)
  1330. self.list.SetStringItem(index, 6, bkw_err)
  1331. self.mapcoordlist[key][5] = float(fwd_err)
  1332. self.mapcoordlist[key][6] = float(bkw_err)
  1333. self.list.SetItemTextColour(index, wx.BLACK)
  1334. if self.highest_only:
  1335. if highest_fwd_err < float(fwd_err):
  1336. highest_fwd_err = float(fwd_err)
  1337. self.highest_key = key
  1338. highest_idx = index
  1339. sumsq_fwd_err += float(fwd_err)**2
  1340. sumsq_bkw_err += float(bkw_err)**2
  1341. sum_fwd_err += float(fwd_err)
  1342. GCPcount += 1
  1343. else:
  1344. self.list.SetStringItem(index, 5, '')
  1345. self.list.SetStringItem(index, 6, '')
  1346. self.mapcoordlist[key][5] = 0.0
  1347. self.mapcoordlist[key][6] = 0.0
  1348. self.list.SetItemTextColour(index, wx.BLACK)
  1349. # SD
  1350. if GCPcount > 0:
  1351. sum_fwd_err /= GCPcount
  1352. self.rmsmean = sum_fwd_err /GCPcount
  1353. self.rmssd = (((sumsq_fwd_err/GCPcount) - self.rmsmean**2)**0.5)
  1354. self.rmsthresh = self.rmsmean + sdfactor * self.rmssd
  1355. else:
  1356. self.rmsthresh = 0
  1357. self.rmsmean = 0
  1358. self.rmssd = 0
  1359. if self.highest_only and highest_fwd_err > 0.0:
  1360. self.list.SetItemTextColour(highest_idx, wx.RED)
  1361. elif GCPcount > 0 and self.rmsthresh > 0 and not self.highest_only:
  1362. for index in range(self.list.GetItemCount()):
  1363. if self.list.IsChecked(index):
  1364. key = self.list.GetItemData(index)
  1365. if (self.mapcoordlist[key][5] > self.rmsthresh):
  1366. self.list.SetItemTextColour(index, wx.RED)
  1367. # calculate global RMS error (geometric mean)
  1368. self.fwd_rmserror = round((sumsq_fwd_err/GCPcount)**0.5,4)
  1369. self.bkw_rmserror = round((sumsq_bkw_err/GCPcount)**0.5,4)
  1370. self.list.ResizeColumns()
  1371. def GetNewExtend(self, region, map = None):
  1372. coord_file = utils.GetTempfile()
  1373. newreg = { 'n' : 0.0, 's' : 0.0, 'e' : 0.0, 'w' : 0.0,}
  1374. try:
  1375. f = open(coord_file, mode='w')
  1376. # NW corner
  1377. f.write(str(region['e']) + " " + str(region['n']) + "\n")
  1378. # NE corner
  1379. f.write(str(region['e']) + " " + str(region['s']) + "\n")
  1380. # SW corner
  1381. f.write(str(region['w']) + " " + str(region['n']) + "\n")
  1382. # SE corner
  1383. f.write(str(region['w']) + " " + str(region['s']) + "\n")
  1384. finally:
  1385. f.close()
  1386. # save GCPs to points file to make sure that all checked GCPs are used
  1387. self.SaveGCPs(None)
  1388. order = self.gr_order
  1389. self.gr_order = 1
  1390. if self.CheckGCPcount(msg=True) == False:
  1391. self.gr_order = order
  1392. return
  1393. self.gr_order = order
  1394. # get list of forward and reverse rms error values for each point
  1395. self.grwiz.SwitchEnv('source')
  1396. if map == 'source':
  1397. ret = gcmd.RunCommand('g.transform',
  1398. parent = self,
  1399. read = True,
  1400. group = self.xygroup,
  1401. order = 1,
  1402. format = 'dst',
  1403. coords = coord_file)
  1404. elif map == 'target':
  1405. ret = gcmd.RunCommand('g.transform',
  1406. parent = self,
  1407. read = True,
  1408. group = self.xygroup,
  1409. order = 1,
  1410. flags = 'r',
  1411. format = 'src',
  1412. coords = coord_file)
  1413. os.unlink(coord_file)
  1414. self.grwiz.SwitchEnv('target')
  1415. if ret:
  1416. errlist = ret.splitlines()
  1417. else:
  1418. wx.MessageBox(parent=self,
  1419. caption=_("Adjust GCP Displays "),
  1420. message=_('Could not calculate new extends. \n'
  1421. 'Possible error with g.transform.'),
  1422. style=wx.ICON_ERROR | wx.ID_OK | wx.CENTRE)
  1423. return
  1424. # fist corner
  1425. e, n = errlist[0].split()
  1426. fe = float(e)
  1427. fn = float(n)
  1428. newreg['n'] = fn
  1429. newreg['s'] = fn
  1430. newreg['e'] = fe
  1431. newreg['w'] = fe
  1432. # other three corners
  1433. for i in range(1, 4):
  1434. e, n = errlist[i].split()
  1435. fe = float(e)
  1436. fn = float(n)
  1437. if fe < newreg['w']:
  1438. newreg['w'] = fe
  1439. if fe > newreg['e']:
  1440. newreg['e'] = fe
  1441. if fn < newreg['s']:
  1442. newreg['s'] = fn
  1443. if fn > newreg['n']:
  1444. newreg['n'] = fn
  1445. return newreg
  1446. def OnHelp(self, event):
  1447. """!Show GCP Manager manual page"""
  1448. cmdlist = ['g.manual', 'entry=wxGUI.GCP_Manager']
  1449. self.parent.goutput.RunCmd(cmdlist, compReg=False,
  1450. switchPage=False)
  1451. def OnUpdateActive(self, event):
  1452. if self.activemap.GetSelection() == 0:
  1453. self.MapWindow = self.SrcMapWindow
  1454. self.Map = self.SrcMap
  1455. else:
  1456. self.MapWindow = self.TgtMapWindow
  1457. self.Map = self.TgtMap
  1458. self.UpdateActive(self.MapWindow)
  1459. # for wingrass
  1460. if os.name == 'nt':
  1461. self.MapWindow.SetFocus()
  1462. def UpdateActive(self, win):
  1463. # optionally disable tool zoomback tool
  1464. self.toolbars['gcpdisp'].Enable('zoomback', enable = (len(self.MapWindow.zoomhistory) > 1))
  1465. if self.activemap.GetSelection() != (win == self.TgtMapWindow):
  1466. self.activemap.SetSelection(win == self.TgtMapWindow)
  1467. self.StatusbarUpdate()
  1468. def AdjustMap(self, newreg):
  1469. """!Adjust map window to new extents
  1470. """
  1471. # adjust map window
  1472. self.Map.region['n'] = newreg['n']
  1473. self.Map.region['s'] = newreg['s']
  1474. self.Map.region['e'] = newreg['e']
  1475. self.Map.region['w'] = newreg['w']
  1476. self.MapWindow.ZoomHistory(self.Map.region['n'], self.Map.region['s'],
  1477. self.Map.region['e'], self.Map.region['w'])
  1478. # LL locations
  1479. if self.Map.projinfo['proj'] == 'll':
  1480. if newreg['n'] > 90.0:
  1481. newreg['n'] = 90.0
  1482. if newreg['s'] < -90.0:
  1483. newreg['s'] = -90.0
  1484. ce = newreg['w'] + (newreg['e'] - newreg['w']) / 2
  1485. cn = newreg['s'] + (newreg['n'] - newreg['s']) / 2
  1486. # calculate new center point and display resolution
  1487. self.Map.region['center_easting'] = ce
  1488. self.Map.region['center_northing'] = cn
  1489. self.Map.region["ewres"] = (newreg['e'] - newreg['w']) / self.Map.width
  1490. self.Map.region["nsres"] = (newreg['n'] - newreg['s']) / self.Map.height
  1491. self.Map.AlignExtentFromDisplay()
  1492. self.MapWindow.ZoomHistory(self.Map.region['n'], self.Map.region['s'],
  1493. self.Map.region['e'], self.Map.region['w'])
  1494. if self.MapWindow.redrawAll is False:
  1495. self.MapWindow.redrawAll = True
  1496. self.MapWindow.UpdateMap()
  1497. self.StatusbarUpdate()
  1498. def OnZoomToSource(self, event):
  1499. """!Set target map window to match extents of source map window
  1500. """
  1501. if not self.MapWindow == self.TgtMapWindow:
  1502. self.MapWindow = self.TgtMapWindow
  1503. self.Map = self.TgtMap
  1504. self.UpdateActive(self.TgtMapWindow)
  1505. # get new N, S, E, W for target
  1506. newreg = self.GetNewExtend(self.SrcMap.region, 'source')
  1507. self.AdjustMap(newreg)
  1508. def OnZoomToTarget(self, event):
  1509. """!Set source map window to match extents of target map window
  1510. """
  1511. if not self.MapWindow == self.SrcMapWindow:
  1512. self.MapWindow = self.SrcMapWindow
  1513. self.Map = self.SrcMap
  1514. self.UpdateActive(self.SrcMapWindow)
  1515. # get new N, S, E, W for target
  1516. newreg = self.GetNewExtend(self.TgtMap.region, 'target')
  1517. self.AdjustMap(newreg)
  1518. def OnZoomMenuGCP(self, event):
  1519. """!Popup Zoom menu
  1520. """
  1521. point = wx.GetMousePosition()
  1522. zoommenu = wx.Menu()
  1523. # Add items to the menu
  1524. zoomsource = wx.MenuItem(zoommenu, wx.ID_ANY, _('Adjust source display to target display'))
  1525. zoommenu.AppendItem(zoomsource)
  1526. self.Bind(wx.EVT_MENU, self.OnZoomToTarget, zoomsource)
  1527. zoomtarget = wx.MenuItem(zoommenu, wx.ID_ANY, _('Adjust target display to source display'))
  1528. zoommenu.AppendItem(zoomtarget)
  1529. self.Bind(wx.EVT_MENU, self.OnZoomToSource, zoomtarget)
  1530. # Popup the menu. If an item is selected then its handler
  1531. # will be called before PopupMenu returns.
  1532. self.PopupMenu(zoommenu)
  1533. zoommenu.Destroy()
  1534. def OnDispResize(self, event):
  1535. """!GCP Map Display resized, adjust Map Windows
  1536. """
  1537. if self.toolbars['gcpdisp']:
  1538. srcwidth, srcheight = self.SrcMapWindow.GetSize()
  1539. tgtwidth, tgtheight = self.TgtMapWindow.GetSize()
  1540. tgtwidth = (srcwidth + tgtwidth) / 2
  1541. self._mgr.GetPane("target").Hide()
  1542. self._mgr.Update()
  1543. self._mgr.GetPane("source").BestSize((tgtwidth, srcheight))
  1544. self._mgr.GetPane("target").BestSize((tgtwidth, tgtheight))
  1545. if self.show_target:
  1546. self._mgr.GetPane("target").Show()
  1547. self._mgr.Update()
  1548. pass
  1549. class GCPList(wx.ListCtrl,
  1550. CheckListCtrlMixin,
  1551. ListCtrlAutoWidthMixin):
  1552. def __init__(self, parent, gcp, id=wx.ID_ANY,
  1553. pos=wx.DefaultPosition, size=wx.DefaultSize,
  1554. style=wx.LC_REPORT | wx.SUNKEN_BORDER | wx.LC_HRULES |
  1555. wx.LC_SINGLE_SEL):
  1556. wx.ListCtrl.__init__(self, parent, id, pos, size, style)
  1557. self.gcp = gcp # GCP class
  1558. self.render = True
  1559. # Mixin settings
  1560. CheckListCtrlMixin.__init__(self)
  1561. ListCtrlAutoWidthMixin.__init__(self)
  1562. # TextEditMixin.__init__(self)
  1563. # tracks whether list items are checked or not
  1564. self.CheckList = []
  1565. self._Create()
  1566. self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnItemSelected)
  1567. self.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.OnItemActivated)
  1568. self.Bind(wx.EVT_LIST_COL_CLICK, self.OnColClick)
  1569. self.selected = wx.NOT_FOUND
  1570. self.selectedkey = -1
  1571. def _Create(self):
  1572. if 0:
  1573. # normal, simple columns
  1574. idx_col = 0
  1575. for col in (_('use'),
  1576. _('source E'),
  1577. _('source N'),
  1578. _('target E'),
  1579. _('target N'),
  1580. _('Forward error'),
  1581. _('Backward error')):
  1582. self.InsertColumn(idx_col, col)
  1583. idx_col += 1
  1584. else:
  1585. # the hard way: we want images on the column header
  1586. info = wx.ListItem()
  1587. info.SetMask(wx.LIST_MASK_TEXT | wx.LIST_MASK_IMAGE | wx.LIST_MASK_FORMAT)
  1588. info.SetImage(-1)
  1589. info.m_format = wx.LIST_FORMAT_LEFT
  1590. idx_col = 0
  1591. for lbl in (_('use'),
  1592. _('source E'),
  1593. _('source N'),
  1594. _('target E'),
  1595. _('target N'),
  1596. _('Forward error'),
  1597. _('Backward error')):
  1598. info.SetText(lbl)
  1599. self.InsertColumnInfo(idx_col, info)
  1600. idx_col += 1
  1601. def LoadData(self):
  1602. """!Load data into list"""
  1603. self.DeleteAllItems()
  1604. self.render = False
  1605. if os.path.isfile(self.gcp.file['points']):
  1606. self.gcp.ReadGCPs()
  1607. else:
  1608. # 3 gcp is minimum
  1609. for i in range(3):
  1610. self.gcp.AddGCP(None)
  1611. # select first point by default
  1612. self.selected = 0
  1613. self.selectedkey = self.GetItemData(self.selected)
  1614. self.SetItemState(self.selected,
  1615. wx.LIST_STATE_SELECTED,
  1616. wx.LIST_STATE_SELECTED)
  1617. self.ResizeColumns()
  1618. self.render = True
  1619. def OnCheckItem(self, index, flag):
  1620. """!Item is checked/unchecked"""
  1621. if self.render:
  1622. # redraw points
  1623. sourceMapWin = self.gcp.SrcMapWindow
  1624. sourceMapWin.UpdateMap(render=False, renderVector=False)
  1625. if self.gcp.show_target:
  1626. targetMapWin = self.gcp.TgtMapWindow
  1627. targetMapWin.UpdateMap(render=False, renderVector=False)
  1628. pass
  1629. def AddGCPItem(self):
  1630. """
  1631. Appends an item to GCP list
  1632. """
  1633. self.selectedkey = self.GetItemCount() + 1
  1634. self.Append([str(self.selectedkey), # GCP number
  1635. '0.0', # source E
  1636. '0.0', # source N
  1637. '0.0', # target E
  1638. '0.0', # target N
  1639. '', # forward error
  1640. '']) # backward error
  1641. self.selected = self.GetItemCount() - 1
  1642. self.SetItemData(self.selected, self.selectedkey)
  1643. self.SetItemState(self.selected,
  1644. wx.LIST_STATE_SELECTED,
  1645. wx.LIST_STATE_SELECTED)
  1646. self.ResizeColumns()
  1647. return self.selected
  1648. def DeleteGCPItem(self):
  1649. """
  1650. Deletes selected item in GCP list
  1651. """
  1652. if self.selected == wx.NOT_FOUND:
  1653. return
  1654. key = self.GetItemData(self.selected)
  1655. self.DeleteItem(self.selected)
  1656. return key
  1657. def ResizeColumns(self):
  1658. """!Resize columns"""
  1659. minWidth = [90, 120]
  1660. for i in range(self.GetColumnCount()):
  1661. self.SetColumnWidth(i, wx.LIST_AUTOSIZE)
  1662. # first column is checkbox, don't set to minWidth
  1663. if i > 0 and self.GetColumnWidth(i) < minWidth[i > 4]:
  1664. self.SetColumnWidth(i, minWidth[i > 4])
  1665. self.SendSizeEvent()
  1666. def GetSelected(self):
  1667. """!Get index of selected item"""
  1668. return self.selected
  1669. def OnItemSelected(self, event):
  1670. """
  1671. Item selected
  1672. """
  1673. if self.render and self.selected != event.GetIndex():
  1674. self.selected = event.GetIndex()
  1675. self.selectedkey = self.GetItemData(self.selected)
  1676. sourceMapWin = self.gcp.SrcMapWindow
  1677. sourceMapWin.UpdateMap(render=False, renderVector=False)
  1678. if self.gcp.show_target:
  1679. targetMapWin = self.gcp.TgtMapWindow
  1680. targetMapWin.UpdateMap(render=False, renderVector=False)
  1681. event.Skip()
  1682. def OnItemActivated(self, event):
  1683. """
  1684. When item double clicked, open editor to update coordinate values
  1685. """
  1686. coords = []
  1687. index = event.GetIndex()
  1688. key = self.GetItemData(index)
  1689. changed = False
  1690. for i in range(1, 5):
  1691. coords.append(self.GetItem(index, i).GetText())
  1692. dlg = EditGCP(parent=self, id=wx.ID_ANY, data=coords, gcpno=key)
  1693. if dlg.ShowModal() == wx.ID_OK:
  1694. values = dlg.GetValues() # string
  1695. if len(values) == 0:
  1696. wx.MessageBox(parent=self,
  1697. caption=_("Edit GCP"),
  1698. message=_("Invalid coordinate value. Operation cancelled."),
  1699. style=wx.CENTRE | wx.ICON_ERROR | wx.ID_OK)
  1700. else:
  1701. for i in range(len(values)):
  1702. if values[i] != coords[i]:
  1703. self.SetStringItem(index, i + 1, values[i])
  1704. changed = True
  1705. if changed:
  1706. # reset RMS and update mapcoordlist
  1707. self.SetStringItem(index, 5, '')
  1708. self.SetStringItem(index, 6, '')
  1709. key = self.GetItemData(index)
  1710. self.gcp.mapcoordlist[key] = [key,
  1711. float(values[0]),
  1712. float(values[1]),
  1713. float(values[2]),
  1714. float(values[3]),
  1715. 0.0,
  1716. 0.0]
  1717. self.gcp.UpdateColours()
  1718. def OnColClick(self, event):
  1719. """!ListCtrl forgets selected item..."""
  1720. self.selected = self.FindItemData(-1, self.selectedkey)
  1721. self.SetItemState(self.selected,
  1722. wx.LIST_STATE_SELECTED,
  1723. wx.LIST_STATE_SELECTED)
  1724. event.Skip()
  1725. class VectGroup(wx.Dialog):
  1726. """
  1727. Dialog to create a vector group (VREF file) for georectifying
  1728. @todo Replace by g.group
  1729. """
  1730. def __init__(self, parent, id, grassdb, location, mapset, group,
  1731. style=wx.DEFAULT_DIALOG_STYLE):
  1732. wx.Dialog.__init__(self, parent, id, style=style,
  1733. title = _("Create vector map group"))
  1734. self.grassdatabase = grassdb
  1735. self.xylocation = location
  1736. self.xymapset = mapset
  1737. self.xygroup = group
  1738. #
  1739. # get list of valid vector directories
  1740. #
  1741. vectlist = os.listdir(os.path.join(self.grassdatabase,
  1742. self.xylocation,
  1743. self.xymapset,
  1744. 'vector'))
  1745. for dir in vectlist:
  1746. if not os.path.isfile(os.path.join(self.grassdatabase,
  1747. self.xylocation,
  1748. self.xymapset,
  1749. 'vector',
  1750. dir,
  1751. 'coor')):
  1752. vectlist.remove(dir)
  1753. utils.ListSortLower(vectlist)
  1754. # path to vref file
  1755. self.vgrpfile = os.path.join(self.grassdatabase,
  1756. self.xylocation,
  1757. self.xymapset,
  1758. 'group',
  1759. self.xygroup,
  1760. 'VREF')
  1761. #
  1762. # buttons
  1763. #
  1764. self.btnCancel = wx.Button(parent = self,
  1765. id = wx.ID_CANCEL)
  1766. self.btnOK = wx.Button(parent = self,
  1767. id = wx.ID_OK)
  1768. self.btnOK.SetDefault()
  1769. #
  1770. # list of vector maps
  1771. #
  1772. self.listMap = wx.CheckListBox(parent = self, id = wx.ID_ANY,
  1773. choices = vectlist)
  1774. if os.path.isfile(self.vgrpfile):
  1775. f = open(self.vgrpfile)
  1776. try:
  1777. checked = []
  1778. for line in f.readlines():
  1779. line = line.replace('\n', '')
  1780. if len(line) < 1:
  1781. continue
  1782. checked.append(line)
  1783. self.listMap.SetCheckedStrings(checked)
  1784. finally:
  1785. f.close()
  1786. line = wx.StaticLine(parent = self,
  1787. id = wx.ID_ANY, size = (20, -1),
  1788. style = wx.LI_HORIZONTAL)
  1789. #
  1790. # layout
  1791. #
  1792. sizer = wx.BoxSizer(wx.VERTICAL)
  1793. box = wx.BoxSizer(wx.HORIZONTAL)
  1794. box.Add(item = wx.StaticText(parent = self, id = wx.ID_ANY,
  1795. label = _('Select vector map(s) to add to group:')),
  1796. flag = wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.LEFT,
  1797. border = 5)
  1798. box.Add(item = self.listMap,
  1799. flag = wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.LEFT,
  1800. border = 5)
  1801. sizer.Add(box, flag = wx.ALIGN_RIGHT | wx.ALL,
  1802. border = 3)
  1803. sizer.Add(item = line, proportion = 0,
  1804. flag = wx.GROW | wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT,
  1805. border = 5)
  1806. # buttons
  1807. btnSizer = wx.StdDialogButtonSizer()
  1808. btnSizer.AddButton(self.btnCancel)
  1809. btnSizer.AddButton(self.btnOK)
  1810. btnSizer.Realize()
  1811. sizer.Add(item = btnSizer, proportion = 0,
  1812. flag = wx.EXPAND | wx.ALL | wx.ALIGN_CENTER,
  1813. border = 5)
  1814. self.SetSizer(sizer)
  1815. sizer.Fit(self)
  1816. self.Layout()
  1817. def MakeVGroup(self):
  1818. """!Create VREF file"""
  1819. vgrouplist = []
  1820. for item in range(self.listMap.GetCount()):
  1821. if not self.listMap.IsChecked(item):
  1822. continue
  1823. vgrouplist.append(self.listMap.GetString(item))
  1824. f = open(self.vgrpfile, mode='w')
  1825. try:
  1826. for vect in vgrouplist:
  1827. f.write(vect + '\n')
  1828. finally:
  1829. f.close()
  1830. class EditGCP(wx.Dialog):
  1831. def __init__(self, parent, data, gcpno, id=wx.ID_ANY,
  1832. title=_("Edit GCP"),
  1833. style=wx.DEFAULT_DIALOG_STYLE):
  1834. """!Dialog for editing GPC and map coordinates in list control"""
  1835. wx.Dialog.__init__(self, parent, id, title=title, style=style)
  1836. panel = wx.Panel(parent=self)
  1837. sizer = wx.BoxSizer(wx.VERTICAL)
  1838. box = wx.StaticBox (parent=panel, id=wx.ID_ANY,
  1839. label=" %s %s " % (_("Ground Control Point No."), str(gcpno)))
  1840. boxSizer = wx.StaticBoxSizer(box, wx.VERTICAL)
  1841. # source coordinates
  1842. gridSizer = wx.GridBagSizer(vgap=5, hgap=5)
  1843. self.xcoord = wx.TextCtrl(parent=panel, id=wx.ID_ANY, size=(150, -1))
  1844. self.ycoord = wx.TextCtrl(parent=panel, id=wx.ID_ANY, size=(150, -1))
  1845. self.ecoord = wx.TextCtrl(parent=panel, id=wx.ID_ANY, size=(150, -1))
  1846. self.ncoord = wx.TextCtrl(parent=panel, id=wx.ID_ANY, size=(150, -1))
  1847. # swap source N, target E
  1848. tmp_coord = data[1]
  1849. data[1] = data[2]
  1850. data[2] = tmp_coord
  1851. row = 0
  1852. col = 0
  1853. idx = 0
  1854. for label, win in ((_("source E:"), self.xcoord),
  1855. (_("target E:"), self.ecoord),
  1856. (_("source N:"), self.ycoord),
  1857. (_("target N:"), self.ncoord)):
  1858. label = wx.StaticText(parent=panel, id=wx.ID_ANY,
  1859. label=label)
  1860. gridSizer.Add(item=label,
  1861. flag=wx.ALIGN_CENTER_VERTICAL,
  1862. pos=(row, col))
  1863. col += 1
  1864. win.SetValue(str(data[idx]))
  1865. gridSizer.Add(item=win,
  1866. pos=(row, col))
  1867. col += 1
  1868. idx += 1
  1869. if col > 3:
  1870. row += 1
  1871. col = 0
  1872. boxSizer.Add(item=gridSizer, proportion=1,
  1873. flag=wx.EXPAND | wx.ALL, border=5)
  1874. sizer.Add(item=boxSizer, proportion=1,
  1875. flag=wx.EXPAND | wx.ALL, border=5)
  1876. #
  1877. # buttons
  1878. #
  1879. self.btnCancel = wx.Button(panel, wx.ID_CANCEL)
  1880. self.btnOk = wx.Button(panel, wx.ID_OK)
  1881. self.btnOk.SetDefault()
  1882. btnSizer = wx.StdDialogButtonSizer()
  1883. btnSizer.AddButton(self.btnCancel)
  1884. btnSizer.AddButton(self.btnOk)
  1885. btnSizer.Realize()
  1886. sizer.Add(item=btnSizer, proportion=0,
  1887. flag=wx.ALIGN_RIGHT | wx.ALL, border=5)
  1888. panel.SetSizer(sizer)
  1889. sizer.Fit(self)
  1890. def GetValues(self, columns=None):
  1891. """!Return list of values (as strings).
  1892. """
  1893. valuelist = []
  1894. try:
  1895. float(self.xcoord.GetValue())
  1896. float(self.ycoord.GetValue())
  1897. float(self.ecoord.GetValue())
  1898. float(self.ncoord.GetValue())
  1899. except ValueError:
  1900. return valuelist
  1901. valuelist.append(self.xcoord.GetValue())
  1902. valuelist.append(self.ycoord.GetValue())
  1903. valuelist.append(self.ecoord.GetValue())
  1904. valuelist.append(self.ncoord.GetValue())
  1905. return valuelist
  1906. class GrSettingsDialog(wx.Dialog):
  1907. def __init__(self, parent, id, title, pos=wx.DefaultPosition, size=wx.DefaultSize,
  1908. style=wx.DEFAULT_DIALOG_STYLE):
  1909. wx.Dialog.__init__(self, parent, id, title, pos, size, style)
  1910. """
  1911. Dialog to set profile text options: font, title
  1912. and font size, axis labels and font size
  1913. """
  1914. #
  1915. # initialize variables
  1916. #
  1917. self.parent = parent
  1918. self.new_src_map = src_map
  1919. self.new_tgt_map = tgt_map
  1920. self.sdfactor = 0
  1921. self.symbol = {}
  1922. # notebook
  1923. notebook = wx.Notebook(parent=self, id=wx.ID_ANY, style=wx.BK_DEFAULT)
  1924. self.__CreateSymbologyPage(notebook)
  1925. self.__CreateRectificationPage(notebook)
  1926. # buttons
  1927. btnSave = wx.Button(self, wx.ID_SAVE)
  1928. btnApply = wx.Button(self, wx.ID_APPLY)
  1929. btnClose = wx.Button(self, wx.ID_CLOSE)
  1930. btnApply.SetDefault()
  1931. # bindings
  1932. btnApply.Bind(wx.EVT_BUTTON, self.OnApply)
  1933. btnApply.SetToolTipString(_("Apply changes for the current session"))
  1934. btnSave.Bind(wx.EVT_BUTTON, self.OnSave)
  1935. btnSave.SetToolTipString(_("Apply and save changes to user settings file (default for next sessions)"))
  1936. btnClose.Bind(wx.EVT_BUTTON, self.OnClose)
  1937. btnClose.SetToolTipString(_("Close dialog"))
  1938. # sizers
  1939. btnSizer = wx.BoxSizer(wx.HORIZONTAL)
  1940. btnSizer.Add(btnApply, flag=wx.LEFT | wx.RIGHT, border=5)
  1941. btnSizer.Add(btnSave, flag=wx.LEFT | wx.RIGHT, border=5)
  1942. btnSizer.Add(btnClose, flag=wx.LEFT | wx.RIGHT, border=5)
  1943. # sizers
  1944. mainSizer = wx.BoxSizer(wx.VERTICAL)
  1945. mainSizer.Add(item=notebook, proportion=1, flag=wx.EXPAND | wx.ALL, border=5)
  1946. mainSizer.Add(item=btnSizer, proportion=0,
  1947. flag=wx.ALIGN_RIGHT | wx.ALL, border=5)
  1948. # flag=wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border=5)
  1949. self.SetSizer(mainSizer)
  1950. mainSizer.Fit(self)
  1951. def __CreateSymbologyPage(self, notebook):
  1952. """!Create notebook page with symbology settings"""
  1953. panel = wx.Panel(parent=notebook, id=wx.ID_ANY)
  1954. notebook.AddPage(page=panel, text=_("Symbology"))
  1955. sizer = wx.BoxSizer(wx.VERTICAL)
  1956. rmsgridSizer = wx.GridBagSizer(vgap=5, hgap=5)
  1957. rmsgridSizer.AddGrowableCol(1)
  1958. # highlight only highest forward RMS error
  1959. self.highlighthighest = wx.CheckBox(parent=panel, id=wx.ID_ANY,
  1960. label=_("Highlight highest RMS error only"))
  1961. hh = UserSettings.Get(group='gcpman', key='rms', subkey='highestonly')
  1962. self.highlighthighest.SetValue(hh)
  1963. rmsgridSizer.Add(item=self.highlighthighest, flag=wx.ALIGN_CENTER_VERTICAL, pos=(0, 0))
  1964. # RMS forward error threshold
  1965. rmslabel = wx.StaticText(parent=panel, id=wx.ID_ANY, label=_("Highlight RMS error > M + SD * factor:"))
  1966. rmslabel.SetToolTip(wx.ToolTip(_("Highlight GCPs with an RMS error larger than \n"
  1967. "mean + standard deviation * given factor. \n"
  1968. "Recommended values for this factor are between 1 and 2.")))
  1969. rmsgridSizer.Add(item=rmslabel, flag=wx.ALIGN_CENTER_VERTICAL, pos=(1, 0))
  1970. sdfactor = UserSettings.Get(group='gcpman', key='rms', subkey='sdfactor')
  1971. self.rmsWin = wx.TextCtrl(parent=panel, id=wx.ID_ANY,
  1972. size=(70,-1), style=wx.TE_NOHIDESEL)
  1973. self.rmsWin.SetValue("%s" % str(sdfactor))
  1974. if (self.parent.highest_only == True):
  1975. self.rmsWin.Disable()
  1976. self.symbol['sdfactor'] = self.rmsWin.GetId()
  1977. rmsgridSizer.Add(item=self.rmsWin, flag=wx.ALIGN_RIGHT, pos=(1, 1))
  1978. sizer.Add(item=rmsgridSizer, flag=wx.EXPAND | wx.ALL, border=5)
  1979. box = wx.StaticBox(parent=panel, id=wx.ID_ANY,
  1980. label=" %s " % _("Symbol settings"))
  1981. boxSizer = wx.StaticBoxSizer(box, wx.VERTICAL)
  1982. gridSizer = wx.GridBagSizer(vgap=5, hgap=5)
  1983. gridSizer.AddGrowableCol(1)
  1984. #
  1985. # general symbol color
  1986. #
  1987. row = 0
  1988. label = wx.StaticText(parent=panel, id=wx.ID_ANY, label=_("Color:"))
  1989. gridSizer.Add(item=label, flag=wx.ALIGN_CENTER_VERTICAL, pos=(row, 0))
  1990. col = UserSettings.Get(group='gcpman', key='symbol', subkey='color')
  1991. colWin = csel.ColourSelect(parent=panel, id=wx.ID_ANY,
  1992. colour=wx.Colour(col[0],
  1993. col[1],
  1994. col[2],
  1995. 255))
  1996. self.symbol['color'] = colWin.GetId()
  1997. gridSizer.Add(item=colWin,
  1998. flag=wx.ALIGN_RIGHT,
  1999. pos=(row, 1))
  2000. #
  2001. # symbol color for high forward RMS error
  2002. #
  2003. row += 1
  2004. label = wx.StaticText(parent=panel, id=wx.ID_ANY, label=_("Color for high RMS error:"))
  2005. gridSizer.Add(item=label, flag=wx.ALIGN_CENTER_VERTICAL, pos=(row, 0))
  2006. hcol = UserSettings.Get(group='gcpman', key='symbol', subkey='hcolor')
  2007. hcolWin = csel.ColourSelect(parent=panel, id=wx.ID_ANY,
  2008. colour=wx.Colour(hcol[0],
  2009. hcol[1],
  2010. hcol[2],
  2011. 255))
  2012. self.symbol['hcolor'] = hcolWin.GetId()
  2013. gridSizer.Add(item=hcolWin,
  2014. flag=wx.ALIGN_RIGHT,
  2015. pos=(row, 1))
  2016. #
  2017. # symbol color for selected GCP
  2018. #
  2019. row += 1
  2020. label = wx.StaticText(parent=panel, id=wx.ID_ANY, label=_("Color for selected GCP:"))
  2021. gridSizer.Add(item=label, flag=wx.ALIGN_CENTER_VERTICAL, pos=(row, 0))
  2022. scol = UserSettings.Get(group='gcpman', key='symbol', subkey='scolor')
  2023. scolWin = csel.ColourSelect(parent=panel, id=wx.ID_ANY,
  2024. colour=wx.Colour(scol[0],
  2025. scol[1],
  2026. scol[2],
  2027. 255))
  2028. self.symbol['scolor'] = scolWin.GetId()
  2029. gridSizer.Add(item=scolWin,
  2030. flag=wx.ALIGN_RIGHT,
  2031. pos=(row, 1))
  2032. #
  2033. # symbol color for unused GCP
  2034. #
  2035. row += 1
  2036. label = wx.StaticText(parent=panel, id=wx.ID_ANY, label=_("Color for unused GCPs:"))
  2037. gridSizer.Add(item=label, flag=wx.ALIGN_CENTER_VERTICAL, pos=(row, 0))
  2038. ucol = UserSettings.Get(group='gcpman', key='symbol', subkey='ucolor')
  2039. ucolWin = csel.ColourSelect(parent=panel, id=wx.ID_ANY,
  2040. colour=wx.Colour(ucol[0],
  2041. ucol[1],
  2042. ucol[2],
  2043. 255))
  2044. self.symbol['ucolor'] = ucolWin.GetId()
  2045. gridSizer.Add(item=ucolWin,
  2046. flag=wx.ALIGN_RIGHT,
  2047. pos=(row, 1))
  2048. # show unused GCPs
  2049. row += 1
  2050. self.showunused = wx.CheckBox(parent=panel, id=wx.ID_ANY,
  2051. label=_("Show unused GCPs"))
  2052. shuu = UserSettings.Get(group='gcpman', key='symbol', subkey='unused')
  2053. self.showunused.SetValue(shuu)
  2054. gridSizer.Add(item=self.showunused, flag=wx.ALIGN_CENTER_VERTICAL, pos=(row, 0))
  2055. #
  2056. # symbol size
  2057. #
  2058. row += 1
  2059. label = wx.StaticText(parent=panel, id=wx.ID_ANY, label=_("Symbol size:"))
  2060. gridSizer.Add(item=label, flag=wx.ALIGN_CENTER_VERTICAL, pos=(row, 0))
  2061. symsize = int(UserSettings.Get(group='gcpman', key='symbol', subkey='size'))
  2062. sizeWin = wx.SpinCtrl(parent=panel, id=wx.ID_ANY,
  2063. min=1, max=20)
  2064. sizeWin.SetValue(symsize)
  2065. self.symbol['size'] = sizeWin.GetId()
  2066. gridSizer.Add(item=sizeWin,
  2067. flag=wx.ALIGN_RIGHT,
  2068. pos=(row, 1))
  2069. #
  2070. # symbol width
  2071. #
  2072. row += 1
  2073. label = wx.StaticText(parent=panel, id=wx.ID_ANY, label=_("Line width:"))
  2074. gridSizer.Add(item=label, flag=wx.ALIGN_CENTER_VERTICAL, pos=(row, 0))
  2075. width = int(UserSettings.Get(group='gcpman', key='symbol', subkey='width'))
  2076. widWin = wx.SpinCtrl(parent=panel, id=wx.ID_ANY,
  2077. min=1, max=10)
  2078. widWin.SetValue(width)
  2079. self.symbol['width'] = widWin.GetId()
  2080. gridSizer.Add(item=widWin,
  2081. flag=wx.ALIGN_RIGHT,
  2082. pos=(row, 1))
  2083. boxSizer.Add(item=gridSizer, flag=wx.EXPAND)
  2084. sizer.Add(item=boxSizer, flag=wx.EXPAND | wx.ALL, border=5)
  2085. #
  2086. # maps to display
  2087. #
  2088. # source map to display
  2089. self.srcselection = gselect.Select(panel, id=wx.ID_ANY,
  2090. size=globalvar.DIALOG_GSELECT_SIZE, type='cell', updateOnPopup = False)
  2091. self.parent.grwiz.SwitchEnv('source')
  2092. self.srcselection.SetElementList(maptype)
  2093. # filter out all maps not in group
  2094. self.srcselection.tcp.GetElementList(elements = self.parent.src_maps)
  2095. # target map to display
  2096. self.tgtselection = gselect.Select(panel, id=wx.ID_ANY,
  2097. size=globalvar.DIALOG_GSELECT_SIZE, type='cell', updateOnPopup = False)
  2098. self.parent.grwiz.SwitchEnv('target')
  2099. self.tgtselection.SetElementList(maptype)
  2100. self.tgtselection.GetElementList()
  2101. sizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY, label=_('Select source map to display:')),
  2102. proportion=0, flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5)
  2103. sizer.Add(item=self.srcselection, proportion=0,
  2104. flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5)
  2105. self.srcselection.SetValue(src_map)
  2106. sizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY, label=_('Select target map to display:')),
  2107. proportion=0, flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5)
  2108. sizer.Add(item=self.tgtselection, proportion=0,
  2109. flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5)
  2110. self.tgtselection.SetValue(tgt_map)
  2111. # bindings
  2112. self.highlighthighest.Bind(wx.EVT_CHECKBOX, self.OnHighlight)
  2113. self.rmsWin.Bind(wx.EVT_TEXT, self.OnSDFactor)
  2114. self.srcselection.Bind(wx.EVT_TEXT, self.OnSrcSelection)
  2115. self.tgtselection.Bind(wx.EVT_TEXT, self.OnTgtSelection)
  2116. panel.SetSizer(sizer)
  2117. return panel
  2118. def __CreateRectificationPage(self, notebook):
  2119. """!Create notebook page with symbology settings"""
  2120. panel = wx.Panel(parent=notebook, id=wx.ID_ANY)
  2121. notebook.AddPage(page=panel, text=_("Rectification"))
  2122. sizer = wx.BoxSizer(wx.VERTICAL)
  2123. # transformation order
  2124. self.rb_grmethod = wx.RadioBox(parent=panel, id=wx.ID_ANY,
  2125. label=" %s " % _("Select rectification method for rasters"),
  2126. choices=[_('1st order'), _('2nd order'), _('3rd order')],
  2127. majorDimension=wx.RA_SPECIFY_COLS)
  2128. sizer.Add(item=self.rb_grmethod, proportion=0,
  2129. flag=wx.EXPAND | wx.ALL, border=5)
  2130. self.rb_grmethod.SetSelection(self.parent.gr_order - 1)
  2131. # clip to region
  2132. self.check = wx.CheckBox(parent=panel, id=wx.ID_ANY,
  2133. label=_("clip to computational region in target location"))
  2134. sizer.Add(item=self.check, proportion=0,
  2135. flag=wx.EXPAND | wx.ALL, border=5)
  2136. self.check.SetValue(self.parent.clip_to_region)
  2137. # extension
  2138. sizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY, label=_('Extension for output maps:')),
  2139. proportion=0, flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5)
  2140. self.ext_txt = wx.TextCtrl(parent=panel, id=wx.ID_ANY, value="", size=(350,-1))
  2141. self.ext_txt.SetValue(self.parent.extension)
  2142. sizer.Add(item=self.ext_txt,
  2143. proportion=0, flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5)
  2144. # bindings
  2145. self.ext_txt.Bind(wx.EVT_TEXT, self.OnExtension)
  2146. self.Bind(wx.EVT_RADIOBOX, self.parent.OnGROrder, self.rb_grmethod)
  2147. self.Bind(wx.EVT_CHECKBOX, self.OnClipRegion, self.check)
  2148. panel.SetSizer(sizer)
  2149. return panel
  2150. def OnHighlight(self, event):
  2151. """!Checkbox 'highlighthighest' checked/unchecked"""
  2152. if self.highlighthighest.IsChecked():
  2153. self.parent.highest_only = True
  2154. self.rmsWin.Disable()
  2155. else:
  2156. self.parent.highest_only = False
  2157. self.rmsWin.Enable()
  2158. def OnSDFactor(self,event):
  2159. """!New factor for RMS threshold = M + SD * factor"""
  2160. self.sdfactor = float(event.GetString())
  2161. if self.sdfactor <= 0:
  2162. wx.MessageBox(parent=self,
  2163. caption=_("Update settings"),
  2164. message=_('RMS threshold factor must be > 0'),
  2165. style=wx.ICON_ERROR | wx.ID_OK | wx.CENTRE)
  2166. elif self.sdfactor < 1:
  2167. wx.MessageBox(parent=self,
  2168. caption=_("Update settings"),
  2169. message=_('RMS threshold factor is < 1\n'
  2170. 'Too many points might be highlighted'),
  2171. style=wx.ICON_EXCLAMATION | wx.ID_OK | wx.CENTRE)
  2172. def OnSrcSelection(self,event):
  2173. """!Source map to display selected"""
  2174. global src_map
  2175. tmp_map = event.GetString()
  2176. if not tmp_map == '' and not tmp_map == src_map:
  2177. self.new_src_map = tmp_map
  2178. def OnTgtSelection(self,event):
  2179. """!Target map to display selected"""
  2180. global tgt_map
  2181. tmp_map = event.GetString()
  2182. if not tmp_map == tgt_map:
  2183. self.new_tgt_map = tmp_map
  2184. def OnClipRegion(self, event):
  2185. self.parent.clip_to_region = event.IsChecked()
  2186. def OnExtension(self, event):
  2187. self.parent.extension = event.GetString()
  2188. def UpdateSettings(self):
  2189. global src_map
  2190. global tgt_map
  2191. layers = None
  2192. UserSettings.Set(group='gcpman', key='rms', subkey='highestonly',
  2193. value=self.highlighthighest.GetValue())
  2194. if self.sdfactor > 0:
  2195. UserSettings.Set(group='gcpman', key='rms', subkey='sdfactor',
  2196. value=self.sdfactor)
  2197. self.parent.sdfactor = self.sdfactor
  2198. if self.parent.rmsthresh > 0:
  2199. self.parent.rmsthresh = self.parent.mean + self.parent.sdfactor * self.parent.rmssd
  2200. UserSettings.Set(group='gcpman', key='symbol', subkey='color',
  2201. value=tuple(wx.FindWindowById(self.symbol['color']).GetColour()))
  2202. UserSettings.Set(group='gcpman', key='symbol', subkey='hcolor',
  2203. value=tuple(wx.FindWindowById(self.symbol['hcolor']).GetColour()))
  2204. UserSettings.Set(group='gcpman', key='symbol', subkey='scolor',
  2205. value=tuple(wx.FindWindowById(self.symbol['scolor']).GetColour()))
  2206. UserSettings.Set(group='gcpman', key='symbol', subkey='ucolor',
  2207. value=tuple(wx.FindWindowById(self.symbol['ucolor']).GetColour()))
  2208. UserSettings.Set(group='gcpman', key='symbol', subkey='unused',
  2209. value=self.showunused.GetValue())
  2210. UserSettings.Set(group='gcpman', key='symbol', subkey='size',
  2211. value=wx.FindWindowById(self.symbol['size']).GetValue())
  2212. UserSettings.Set(group='gcpman', key='symbol', subkey='width',
  2213. value=wx.FindWindowById(self.symbol['width']).GetValue())
  2214. srcrender = False
  2215. srcrenderVector = False
  2216. tgtrender = False
  2217. tgtrenderVector = False
  2218. if self.new_src_map != src_map:
  2219. # remove old layer
  2220. layers = self.parent.grwiz.SrcMap.GetListOfLayers()
  2221. self.parent.grwiz.SrcMap.DeleteLayer(layers[0])
  2222. src_map = self.new_src_map
  2223. cmdlist = ['d.rast', 'map=%s' % src_map]
  2224. self.parent.grwiz.SwitchEnv('source')
  2225. self.parent.grwiz.SrcMap.AddLayer(type='raster', command=cmdlist, l_active=True,
  2226. name=utils.GetLayerNameFromCmd(cmdlist),
  2227. l_hidden=False, l_opacity=1.0, l_render=False)
  2228. self.parent.grwiz.SwitchEnv('target')
  2229. srcrender = True
  2230. if self.new_tgt_map != tgt_map:
  2231. # remove old layer
  2232. layers = self.parent.grwiz.TgtMap.GetListOfLayers()
  2233. if layers:
  2234. self.parent.grwiz.TgtMap.DeleteLayer(layers[0])
  2235. tgt_map = self.new_tgt_map
  2236. if tgt_map != '':
  2237. cmdlist = ['d.rast', 'map=%s' % tgt_map]
  2238. self.parent.grwiz.TgtMap.AddLayer(type='raster', command=cmdlist, l_active=True,
  2239. name=utils.GetLayerNameFromCmd(cmdlist),
  2240. l_hidden=False, l_opacity=1.0, l_render=False)
  2241. tgtrender = True
  2242. if self.parent.show_target == False:
  2243. self.parent.show_target = True
  2244. self.parent._mgr.GetPane("target").Show()
  2245. self.parent.toolbars['gcpdisp'].Enable('zoommenu', enable = True)
  2246. self.parent.activemap.Enable()
  2247. self.parent.TgtMapWindow.ZoomToMap(layers = self.parent.TgtMap.GetListOfLayers())
  2248. self.parent._mgr.Update()
  2249. else: # tgt_map == ''
  2250. if self.parent.show_target == True:
  2251. self.parent.show_target = False
  2252. self.parent._mgr.GetPane("target").Hide()
  2253. self.parent.activemap.SetSelection(0)
  2254. self.parent.activemap.Enable(False)
  2255. self.parent.toolbars['gcpdisp'].Enable('zoommenu', enable = False)
  2256. self.parent._mgr.Update()
  2257. self.parent.UpdateColours(srcrender, srcrenderVector, tgtrender, tgtrenderVector)
  2258. def OnSave(self, event):
  2259. """!Button 'Save' pressed"""
  2260. self.UpdateSettings()
  2261. fileSettings = {}
  2262. UserSettings.ReadSettingsFile(settings=fileSettings)
  2263. fileSettings['gcpman'] = UserSettings.Get(group='gcpman')
  2264. file = UserSettings.SaveToFile(fileSettings)
  2265. self.parent.parent.goutput.WriteLog(_('GCP Manager settings saved to file \'%s\'.') % file)
  2266. #self.Close()
  2267. def OnApply(self, event):
  2268. """!Button 'Apply' pressed"""
  2269. self.UpdateSettings()
  2270. #self.Close()
  2271. def OnClose(self, event):
  2272. """!Button 'Cancel' pressed"""
  2273. self.Close()