gcpmanager.py 103 KB

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