manager.py 105 KB

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