gcpmanager.py 104 KB

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