georect.py 63 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792
  1. """!
  2. @package georect.py
  3. @brief Georectification module for GRASS GIS. Includes ground control
  4. point management and interactive point and click GCP creation
  5. Classes:
  6. - GeorectWizard
  7. - LocationPage
  8. - GroupPage
  9. - DispMapPage
  10. - GCP
  11. - GCPList
  12. - VectGroup
  13. - EditGCP
  14. - GrSettingsDialog
  15. (C) 2006-2010 by the GRASS Development Team
  16. This program is free software under the GNU General Public License
  17. (>=v2). Read the file COPYING that comes with GRASS for details.
  18. @author Michael Barton
  19. @author Updated by Martin Landa <landa.martin gmail.com>
  20. """
  21. import os
  22. import sys
  23. import tempfile
  24. import shutil
  25. import time
  26. import wx
  27. from wx.lib.mixins.listctrl import CheckListCtrlMixin, ListCtrlAutoWidthMixin, TextEditMixin
  28. import wx.lib.colourselect as csel
  29. import wx.wizard as wiz
  30. import grass.script as grass
  31. import globalvar
  32. import mapdisp
  33. import render
  34. import toolbars
  35. import menuform
  36. import gselect
  37. import gcmd
  38. import utils
  39. from debug import Debug as Debug
  40. from icon import Icons as Icons
  41. from location_wizard import TitledPage as TitledPage
  42. from preferences import globalSettings as UserSettings
  43. try:
  44. import subprocess # Not needed if GRASS commands could actually be quiet
  45. except:
  46. CompatPath = globalvar.ETCWXDIR
  47. sys.path.append(CompatPath)
  48. from compat import subprocess
  49. gmpath = os.path.join(globalvar.ETCWXDIR, "icons")
  50. sys.path.append(gmpath)
  51. #
  52. # global variables
  53. #
  54. global xy_map
  55. global maptype
  56. xy_map = ''
  57. maptype = 'cell'
  58. class GeorectWizard(object):
  59. """
  60. Start wizard here and finish wizard here
  61. """
  62. def __init__(self, parent):
  63. self.parent = parent # GMFrame
  64. #
  65. # get environmental variables
  66. #
  67. self.grassdatabase = grass.gisenv()['GISDBASE']
  68. #
  69. # read original environment settings
  70. #
  71. self.orig_gisrc = os.environ['GISRC']
  72. self.gisrc_dict = {}
  73. try:
  74. f = open(self.orig_gisrc, 'r')
  75. for line in f.readlines():
  76. line = line.replace('\n', '').strip()
  77. if len(line) < 1:
  78. continue
  79. key, value = line.split(':', 1)
  80. self.gisrc_dict[key.strip()] = value.strip()
  81. finally:
  82. f.close()
  83. self.currentlocation = self.gisrc_dict['LOCATION_NAME']
  84. self.currentmapset = self.gisrc_dict['MAPSET']
  85. # location for xy map to georectify
  86. self.newlocation = ''
  87. # mapset for xy map to georectify
  88. self.newmapset = ''
  89. # GISRC file for source location/mapset of map(s) to georectify
  90. self.new_gisrc = ''
  91. #
  92. # define wizard pages
  93. #
  94. self.wizard = wiz.Wizard(parent=parent, id=wx.ID_ANY, title=_("Setup for georectification"))
  95. self.startpage = LocationPage(self.wizard, self)
  96. self.grouppage = GroupPage(self.wizard, self)
  97. self.mappage = DispMapPage(self.wizard, self)
  98. #
  99. # set the initial order of the pages
  100. #
  101. self.startpage.SetNext(self.grouppage)
  102. self.grouppage.SetPrev(self.startpage)
  103. self.grouppage.SetNext(self.mappage)
  104. self.mappage.SetPrev(self.grouppage)
  105. #
  106. # do pages layout
  107. #
  108. self.startpage.DoLayout()
  109. self.grouppage.DoLayout()
  110. self.mappage.DoLayout()
  111. self.wizard.FitToPage(self.startpage)
  112. # self.Bind(wx.EVT_CLOSE, self.Cleanup)
  113. # self.parent.Bind(wx.EVT_ACTIVATE, self.OnGLMFocus)
  114. success = False
  115. #
  116. # run wizard
  117. #
  118. if self.wizard.RunWizard(self.startpage):
  119. success = self.OnWizFinished()
  120. if success == False:
  121. wx.MessageBox(parent=self.parent,
  122. message=_("Georectifying setup canceled."),
  123. caption=_("Georectify"),
  124. style=wx.OK | wx.ICON_INFORMATION | wx.CENTRE)
  125. self.Cleanup()
  126. else:
  127. wx.MessageBox(parent=self.parent,
  128. message=_("Georectifying setup canceled."),
  129. caption=_("Georectify"),
  130. style=wx.OK | wx.ICON_INFORMATION | wx.CENTRE)
  131. self.Cleanup()
  132. #
  133. # start display showing xymap
  134. #
  135. if success != False:
  136. # instance of render.Map to be associated with display
  137. self.Map = render.Map(gisrc=self.new_gisrc)
  138. global maptype
  139. global xy_map
  140. #
  141. # add layer to map
  142. #
  143. if maptype == 'cell':
  144. rendertype = 'raster'
  145. cmdlist = ['d.rast', 'map=%s' % xy_map]
  146. else: # -> vector layer
  147. rendertype = 'vector'
  148. cmdlist = ['d.vect', 'map=%s' % xy_map]
  149. self.Map.AddLayer(type=rendertype, command=cmdlist, l_active=True,
  150. name=utils.GetLayerNameFromCmd(cmdlist),
  151. l_hidden=False, l_opacity=1.0, l_render=False)
  152. #
  153. # start GCP form
  154. #
  155. self.gcpmgr = GCP(self.parent, grwiz=self)
  156. self.gcpmgr.Show()
  157. #
  158. # start map display
  159. #
  160. self.xy_mapdisp = mapdisp.MapFrame(self.gcpmgr, name = "GRMapWindow",
  161. size=globalvar.MAP_WINDOW_SIZE,
  162. toolbars=["georect"],
  163. Map=self.Map, lmgr=self.parent)
  164. self.xy_mapdisp.SetTitle(_("GRASS GIS Map Display: 1" +
  165. " - Location: " + self.newlocation +
  166. " (source location)"))
  167. self.xy_mapdisp.GetWindow().ResetZoomHistory()
  168. self.gcpmgr.SetMapDisplay(self.xy_mapdisp)
  169. self.mapwin = self.xy_mapdisp.MapWindow
  170. # set mouse characteristics
  171. self.mapwin.mouse['box'] = 'point'
  172. self.mapwin.mouse["use"] == "pointer"
  173. self.mapwin.zoomtype = 0
  174. self.mapwin.pen = wx.Pen(colour='black', width=2, style=wx.SOLID)
  175. self.mapwin.SetCursor(self.xy_mapdisp.cursors["cross"])
  176. #
  177. # show new display & draw map
  178. #
  179. self.xy_mapdisp.toolbars['georect'].OnZoomMap(None)
  180. self.xy_mapdisp.CenterOnScreen()
  181. self.xy_mapdisp.Show()
  182. self.gcpmgr.Centre()
  183. self.gcpmgr.Raise()
  184. else:
  185. self.Cleanup()
  186. def SetSrcEnv(self, location, mapset):
  187. """!Create environment to use for location and mapset
  188. that are the source of the file(s) to georectify
  189. @param location source location
  190. @param mapset source mapset
  191. @return False on error
  192. @return True on success
  193. """
  194. self.newlocation = location
  195. self.newmapset = mapset
  196. # check to see if we are georectifying map in current working location/mapset
  197. if self.newlocation == self.currentlocation and self.newmapset == self.currentmapset:
  198. return False
  199. self.gisrc_dict['LOCATION_NAME'] = location
  200. self.gisrc_dict['MAPSET'] = mapset
  201. self.new_gisrc = utils.GetTempfile()
  202. try:
  203. f = open(self.new_gisrc, mode='w')
  204. for line in self.gisrc_dict.items():
  205. f.write(line[0] + ": " + line[1] + "\n")
  206. finally:
  207. f.close()
  208. return True
  209. def SwitchEnv(self, grc):
  210. """
  211. Switches between original working location/mapset and
  212. location/mapset that is source of file(s) to georectify
  213. """
  214. # check to see if we are georectifying map in current working location/mapset
  215. if self.newlocation == self.currentlocation and self.newmapset == self.currentmapset:
  216. return False
  217. if grc == 'original':
  218. os.environ["GISRC"] = str(self.orig_gisrc)
  219. elif grc == 'new':
  220. os.environ["GISRC"] = str(self.new_gisrc)
  221. return True
  222. def OnWizFinished(self):
  223. # self.Cleanup()
  224. return True
  225. def OnGLMFocus(self, event):
  226. """!Layer Manager focus"""
  227. # self.SwitchEnv('original')
  228. event.Skip()
  229. def Cleanup(self):
  230. """!Return to current location and mapset"""
  231. self.SwitchEnv('original')
  232. self.parent.georectifying = None
  233. if hasattr(self, "xy_mapdisp") and \
  234. self.xy_mapdisp:
  235. self.xy_mapdisp.Close()
  236. self.xy_mapdisp = None
  237. self.wizard.Destroy()
  238. # clear GCPs from target display
  239. self.parent.curr_page.maptree.mapdisplay.MapWindow.UpdateMap(render=False)
  240. class LocationPage(TitledPage):
  241. """
  242. Set map type (raster or vector) to georectify and
  243. select location/mapset of map(s) to georectify.
  244. """
  245. def __init__(self, wizard, parent):
  246. TitledPage.__init__(self, wizard, _("Select map type and location/mapset"))
  247. self.parent = parent
  248. self.grassdatabase = self.parent.grassdatabase
  249. self.xylocation = ''
  250. self.xymapset = ''
  251. #
  252. # layout
  253. #
  254. self.sizer.AddGrowableCol(2)
  255. # map type
  256. self.rb_maptype = wx.RadioBox(parent=self, id=wx.ID_ANY,
  257. label=' %s ' % _("Map type to georectify"),
  258. choices=[_('raster'), _('vector')],
  259. majorDimension=wx.RA_SPECIFY_COLS)
  260. self.sizer.Add(item=self.rb_maptype,
  261. flag=wx.ALIGN_CENTER | wx.ALL | wx.EXPAND, border=5,
  262. pos=(1, 1), span=(1, 2))
  263. # location
  264. self.sizer.Add(item=wx.StaticText(parent=self, id=wx.ID_ANY, label=_('Select source location:')),
  265. flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5,
  266. pos=(2, 1))
  267. self.cb_location = gselect.LocationSelect(parent = self, gisdbase = self.grassdatabase)
  268. self.sizer.Add(item=self.cb_location,
  269. flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5,
  270. pos=(2, 2))
  271. # mapset
  272. self.sizer.Add(item=wx.StaticText(parent=self, id=wx.ID_ANY, label=_('Select source mapset:')),
  273. flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5,
  274. pos=(3, 1))
  275. self.cb_mapset = gselect.MapsetSelect(parent = self, gisdbase = self.grassdatabase,
  276. setItems = False)
  277. self.sizer.Add(item=self.cb_mapset,
  278. flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5,
  279. pos=(3,2))
  280. #
  281. # bindings
  282. #
  283. self.Bind(wx.EVT_RADIOBOX, self.OnMaptype, self.rb_maptype)
  284. self.Bind(wx.EVT_COMBOBOX, self.OnLocation, self.cb_location)
  285. self.Bind(wx.EVT_COMBOBOX, self.OnMapset, self.cb_mapset)
  286. self.Bind(wiz.EVT_WIZARD_PAGE_CHANGING, self.OnPageChanging)
  287. self.Bind(wiz.EVT_WIZARD_PAGE_CHANGED, self.OnEnterPage)
  288. # self.Bind(wx.EVT_CLOSE, self.parent.Cleanup)
  289. def OnMaptype(self,event):
  290. """!Change map type"""
  291. global maptype
  292. if event.GetInt() == 0:
  293. maptype = 'cell'
  294. else:
  295. maptype = 'vector'
  296. def OnLocation(self, event):
  297. """!Sets source location for map(s) to georectify"""
  298. self.xylocation = event.GetString()
  299. #create a list of valid mapsets
  300. tmplist = os.listdir(os.path.join(self.grassdatabase, self.xylocation))
  301. self.mapsetList = []
  302. for item in tmplist:
  303. if os.path.isdir(os.path.join(self.grassdatabase, self.xylocation, item)) and \
  304. os.path.exists(os.path.join(self.grassdatabase, self.xylocation, item, 'WIND')):
  305. if item != 'PERMANENT':
  306. self.mapsetList.append(item)
  307. self.xymapset = 'PERMANENT'
  308. utils.ListSortLower(self.mapsetList)
  309. self.mapsetList.insert(0, 'PERMANENT')
  310. self.cb_mapset.SetItems(self.mapsetList)
  311. self.cb_mapset.SetStringSelection(self.xymapset)
  312. if not wx.FindWindowById(wx.ID_FORWARD).IsEnabled():
  313. wx.FindWindowById(wx.ID_FORWARD).Enable(True)
  314. def OnMapset(self, event):
  315. """!Sets source mapset for map(s) to georectify"""
  316. if self.xylocation == '':
  317. wx.MessageBox(_('You must select a valid location before selecting a mapset'))
  318. return
  319. self.xymapset = event.GetString()
  320. if not wx.FindWindowById(wx.ID_FORWARD).IsEnabled():
  321. wx.FindWindowById(wx.ID_FORWARD).Enable(True)
  322. def OnPageChanging(self, event=None):
  323. if event.GetDirection() and \
  324. (self.xylocation == '' or self.xymapset == ''):
  325. wx.MessageBox(_('You must select a valid location and mapset in order to continue'))
  326. event.Veto()
  327. return
  328. self.parent.SetSrcEnv(self.xylocation, self.xymapset)
  329. def OnEnterPage(self, event=None):
  330. if self.xylocation == '' or self.xymapset == '':
  331. wx.FindWindowById(wx.ID_FORWARD).Enable(False)
  332. else:
  333. wx.FindWindowById(wx.ID_FORWARD).Enable(True)
  334. class GroupPage(TitledPage):
  335. """
  336. Set group to georectify. Create group if desired.
  337. """
  338. def __init__(self, wizard, parent):
  339. TitledPage.__init__(self, wizard, _("Select image/map group to georectify"))
  340. self.parent = parent
  341. self.grassdatabase = self.parent.grassdatabase
  342. self.groupList = []
  343. self.xylocation = ''
  344. self.xymapset = ''
  345. self.xygroup = ''
  346. # default extension
  347. self.extension = 'georect' + str(os.getpid())
  348. #
  349. # layout
  350. #
  351. self.sizer.AddGrowableCol(2)
  352. # group
  353. self.sizer.Add(item=wx.StaticText(parent=self, id=wx.ID_ANY, label=_('Select group:')),
  354. flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5,
  355. pos=(1, 1))
  356. self.cb_group = wx.ComboBox(parent=self, id=wx.ID_ANY,
  357. choices=self.groupList, size=(350, -1),
  358. style=wx.CB_DROPDOWN | wx.CB_READONLY)
  359. self.sizer.Add(item=self.cb_group,
  360. flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5,
  361. pos=(1, 2))
  362. # create group
  363. self.sizer.Add(item=wx.StaticText(parent=self, id=wx.ID_ANY, label=_('Create group if none exists')),
  364. flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5,
  365. pos=(2, 1))
  366. btnSizer = wx.BoxSizer(wx.HORIZONTAL)
  367. self.btn_mkgroup = wx.Button(parent=self, id=wx.ID_ANY, label=_("Create/edit group..."))
  368. self.btn_vgroup = wx.Button(parent=self, id=wx.ID_ANY, label=_("Add vector map to group..."))
  369. btnSizer.Add(item=self.btn_mkgroup,
  370. flag=wx.RIGHT, border=5)
  371. btnSizer.Add(item=self.btn_vgroup,
  372. flag=wx.LEFT, border=5)
  373. self.sizer.Add(item=btnSizer,
  374. flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5,
  375. pos=(2, 2))
  376. # extension
  377. self.sizer.Add(item=wx.StaticText(parent=self, id=wx.ID_ANY, label=_('Extension for output maps:')),
  378. flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5,
  379. pos=(3, 1))
  380. self.ext_txt = wx.TextCtrl(parent=self, id=wx.ID_ANY, value="", size=(350,-1))
  381. self.ext_txt.SetValue(self.extension)
  382. self.sizer.Add(item=self.ext_txt,
  383. flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5,
  384. pos=(3, 2))
  385. #
  386. # bindings
  387. #
  388. self.Bind(wx.EVT_COMBOBOX, self.OnGroup, self.cb_group)
  389. self.Bind(wx.EVT_TEXT, self.OnExtension, self.ext_txt)
  390. self.Bind(wiz.EVT_WIZARD_PAGE_CHANGING, self.OnPageChanging)
  391. self.Bind(wiz.EVT_WIZARD_PAGE_CHANGED, self.OnEnterPage)
  392. self.Bind(wx.EVT_CLOSE, self.parent.Cleanup)
  393. # hide vector group button by default
  394. self.btn_vgroup.Hide()
  395. def OnGroup(self, event):
  396. self.xygroup = event.GetString()
  397. def OnMkGroup(self, event):
  398. """!Create new group in source location/mapset"""
  399. menuform.GUI().ParseCommand(['i.group'],
  400. completed=(self.GetOptData, None, ''),
  401. parentframe=self.parent.parent, modal=True)
  402. def OnVGroup(self, event):
  403. """!Add vector maps to group"""
  404. dlg = VectGroup(parent = self,
  405. id = wx.ID_ANY,
  406. grassdb = self.grassdatabase,
  407. location = self.xylocation,
  408. mapset = self.xymapset,
  409. group = self.xygroup)
  410. if dlg.ShowModal() != wx.ID_OK:
  411. return
  412. dlg.MakeVGroup()
  413. self.OnEnterPage()
  414. def GetOptData(self, dcmd, layer, params, propwin):
  415. """!Process i.group"""
  416. # update the page
  417. if dcmd:
  418. gcmd.Command(dcmd)
  419. self.OnEnterPage()
  420. self.Update()
  421. def OnExtension(self, event):
  422. self.extension = event.GetString()
  423. def OnPageChanging(self, event=None):
  424. if event.GetDirection() and self.xygroup == '':
  425. wx.MessageBox(_('You must select a valid image/map group in order to continue'))
  426. event.Veto()
  427. return
  428. if event.GetDirection() and self.extension == '':
  429. wx.MessageBox(_('You must enter an map name extension in order to continue'))
  430. event.Veto()
  431. return
  432. def OnEnterPage(self, event=None):
  433. global maptype
  434. self.groupList = []
  435. self.xylocation = self.parent.gisrc_dict['LOCATION_NAME']
  436. self.xymapset = self.parent.gisrc_dict['MAPSET']
  437. # create a list of groups in selected mapset
  438. if os.path.isdir(os.path.join(self.grassdatabase,
  439. self.xylocation,
  440. self.xymapset,
  441. 'group')):
  442. tmplist = os.listdir(os.path.join(self.grassdatabase,
  443. self.xylocation,
  444. self.xymapset,
  445. 'group'))
  446. for item in tmplist:
  447. if os.path.isdir(os.path.join(self.grassdatabase,
  448. self.xylocation,
  449. self.xymapset,
  450. 'group',
  451. item)):
  452. self.groupList.append(item)
  453. if maptype == 'cell':
  454. self.btn_vgroup.Hide()
  455. self.Bind(wx.EVT_BUTTON, self.OnMkGroup, self.btn_mkgroup)
  456. elif maptype == 'vector':
  457. self.btn_vgroup.Show()
  458. self.Bind(wx.EVT_BUTTON, self.OnMkGroup, self.btn_mkgroup)
  459. self.Bind(wx.EVT_BUTTON, self.OnVGroup, self.btn_vgroup)
  460. utils.ListSortLower(self.groupList)
  461. self.cb_group.SetItems(self.groupList)
  462. if len(self.groupList) > 0 and \
  463. self.xygroup == '':
  464. self.cb_group.SetSelection(0)
  465. self.xygroup = self.groupList[0]
  466. if self.xygroup == '' or \
  467. self.extension == '':
  468. wx.FindWindowById(wx.ID_FORWARD).Enable(False)
  469. else:
  470. wx.FindWindowById(wx.ID_FORWARD).Enable(True)
  471. # switch to source
  472. self.parent.SwitchEnv('new')
  473. class DispMapPage(TitledPage):
  474. """
  475. Select ungeoreferenced map to display for interactively
  476. setting ground control points (GCPs).
  477. """
  478. def __init__(self, wizard, parent):
  479. TitledPage.__init__(self, wizard,
  480. _("Select image/map to display for ground control point (GCP) creation"))
  481. self.parent = parent
  482. global maptype
  483. #
  484. # layout
  485. #
  486. self.sizer.Add(item=wx.StaticText(parent=self, id=wx.ID_ANY, label=_('Select display image/map:')),
  487. flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5,
  488. pos=(1, 1))
  489. self.selection = gselect.Select(self, id=wx.ID_ANY,
  490. size=globalvar.DIALOG_GSELECT_SIZE, type='cell')
  491. self.sizer.Add(item=self.selection,
  492. flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5,
  493. pos=(1, 2))
  494. #
  495. # bindings
  496. #
  497. self.selection.Bind(wx.EVT_TEXT, self.OnSelection)
  498. self.Bind(wiz.EVT_WIZARD_PAGE_CHANGING, self.OnPageChanging)
  499. self.Bind(wiz.EVT_WIZARD_PAGE_CHANGED, self.OnEnterPage)
  500. self.Bind(wx.EVT_CLOSE, self.parent.Cleanup)
  501. def OnSelection(self,event):
  502. """!Map to display selected"""
  503. global xy_map
  504. global maptype
  505. xy_map = event.GetString()
  506. if xy_map == '':
  507. wx.FindWindowById(wx.ID_FORWARD).Enable(False)
  508. else:
  509. wx.FindWindowById(wx.ID_FORWARD).Enable(True)
  510. try:
  511. # set computational region to match selected map and zoom display to region
  512. if maptype == 'cell':
  513. p = gcmd.Command(['g.region', 'rast=xy_map'])
  514. elif maptype == 'vector':
  515. p = gcmd.Command(['g.region', 'vect=xy_map'])
  516. if p.returncode == 0:
  517. print 'returncode = ', str(p.returncode)
  518. self.parent.Map.region = self.parent.Map.GetRegion()
  519. except:
  520. pass
  521. def OnPageChanging(self, event=None):
  522. global xy_map
  523. if event.GetDirection() and xy_map == '':
  524. wx.MessageBox(_('You must select a valid image/map in order to continue'))
  525. event.Veto()
  526. return
  527. self.parent.SwitchEnv('original')
  528. def OnEnterPage(self, event=None):
  529. global maptype
  530. global xy_map
  531. self.selection.SetElementList(maptype,
  532. mapsets = [self.parent.newmapset, ])
  533. if xy_map == '':
  534. wx.FindWindowById(wx.ID_FORWARD).Enable(False)
  535. else:
  536. wx.FindWindowById(wx.ID_FORWARD).Enable(True)
  537. class GCP(wx.Frame):
  538. """!
  539. Manages ground control points for georectifying. Calculates RMS statics.
  540. Calls i.rectify or v.transform to georectify map.
  541. """
  542. def __init__(self, parent, grwiz, mapdisp = None, id = wx.ID_ANY,
  543. title = _("Define/manage ground control points"),
  544. size = (625, 300)):
  545. wx.Frame.__init__(self, parent, id, title, size = size, name = "GCPFrame")
  546. self.SetIcon(wx.Icon(os.path.join(globalvar.ETCICONDIR, 'grass_map.ico'), wx.BITMAP_TYPE_ICO))
  547. #
  548. # init variables
  549. #
  550. self.parent = parent # GMFrame
  551. self.parent.georectifying = self
  552. self.mapdisp = mapdisp # XY-location Map Display
  553. self.grwiz = grwiz # GR Wizard
  554. self.grassdatabase = self.grwiz.grassdatabase
  555. self.currentlocation = self.grwiz.currentlocation
  556. self.currentmapset = self.grwiz.currentmapset
  557. self.newlocation = self.grwiz.newlocation
  558. self.newmapset = self.grwiz.newmapset
  559. self.xylocation = self.grwiz.gisrc_dict['LOCATION_NAME']
  560. self.xymapset = self.grwiz.gisrc_dict['MAPSET']
  561. self.xygroup = self.grwiz.grouppage.xygroup
  562. self.extension = self.grwiz.grouppage.extension
  563. self.outname = ''
  564. self.VectGRList = []
  565. self.file = {
  566. 'points' : os.path.join(self.grassdatabase,
  567. self.xylocation,
  568. self.xymapset,
  569. 'group',
  570. self.xygroup,
  571. 'POINTS'),
  572. 'rgrp' : os.path.join(self.grassdatabase,
  573. self.xylocation,
  574. self.xymapset,
  575. 'group',
  576. self.xygroup,
  577. 'REF'),
  578. 'vgrp' : os.path.join(self.grassdatabase,
  579. self.xylocation,
  580. self.xymapset,
  581. 'group',
  582. self.xygroup,
  583. 'VREF'),
  584. 'target' : os.path.join(self.grassdatabase,
  585. self.xylocation,
  586. self.xymapset,
  587. 'group',
  588. self.xygroup,
  589. 'TARGET'),
  590. }
  591. # polynomial order transformation for georectification
  592. self.gr_order = 1
  593. # number of GCPs selected to be used for georectification (checked)
  594. self.GCPcount = 0
  595. # forward RMS error
  596. self.fwd_rmserror = 0.0
  597. # backward RMS error
  598. self.bkw_rmserror = 0.0
  599. # list map coords and ID of map display they came from
  600. self.mapcoordlist = []
  601. # region clipping for georectified map
  602. self.clip_to_region = False
  603. self.SetTarget(self.xygroup, self.currentlocation, self.currentmapset)
  604. #
  605. # toolbar and display for xy map
  606. #
  607. self.toolbar = toolbars.GCPToolbar(parent=self)
  608. self.SetToolBar(self.toolbar)
  609. self.SetMapDisplay(self.mapdisp)
  610. #
  611. # statusbar
  612. #
  613. self.CreateStatusBar(number=1)
  614. # can put guage into custom statusbar for progress if can figure out how to get progress text from i.rectify
  615. # self.gr_gauge = wx.Gauge(self, -1, 100, (-1,-1), (100, 25))
  616. # self.gr_guage.Pulse()
  617. panel = wx.Panel(parent=self)
  618. #
  619. # do layout
  620. #
  621. sizer = wx.BoxSizer(wx.VERTICAL)
  622. self.rb_grmethod = wx.RadioBox(parent=panel, id=wx.ID_ANY,
  623. label=" %s " % _("Select rectification method for rasters"),
  624. choices=[_('1st order'), _('2nd order'), _('3rd order')],
  625. majorDimension=wx.RA_SPECIFY_COLS)
  626. sizer.Add(item=self.rb_grmethod, proportion=0,
  627. flag=wx.EXPAND | wx.ALL, border=5)
  628. self.check = wx.CheckBox(parent=panel, id=wx.ID_ANY,
  629. label=_("clip to computational region in target location"))
  630. sizer.Add(item=self.check, proportion=0,
  631. flag=wx.EXPAND | wx.ALL, border=5)
  632. box = wx.StaticBox (parent=panel, id=wx.ID_ANY,
  633. label=" %s " % _("Ground Control Points"))
  634. boxSizer = wx.StaticBoxSizer(box, wx.VERTICAL)
  635. # initialize list control for GCP management
  636. self.list = GCPList(parent=panel, gcp=self)
  637. boxSizer.Add(item=self.list, proportion=1,
  638. flag=wx.EXPAND | wx.ALL, border=3)
  639. sizer.Add(item=boxSizer, proportion=1,
  640. flag=wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM, border=5)
  641. #
  642. # bindigs
  643. #
  644. self.Bind(wx.EVT_RADIOBOX, self.OnGRMethod, self.rb_grmethod)
  645. self.Bind(wx.EVT_ACTIVATE, self.OnFocus)
  646. self.Bind(wx.EVT_CLOSE, self.OnQuit)
  647. self.Bind(wx.EVT_CHECKBOX, self.ClipRegion, self.check)
  648. panel.SetSizer(sizer)
  649. # sizer.Fit(self)
  650. def __del__(self):
  651. """!Disable georectification mode"""
  652. self.parent.georectifying = None
  653. def ClipRegion(self, event):
  654. self.clip_to_region = event.IsChecked()
  655. def SetMapDisplay(self, win):
  656. self.mapdisp = win
  657. if self.mapdisp:
  658. self.list.LoadData()
  659. def SetTarget(self, tgroup, tlocation, tmapset):
  660. """
  661. Sets rectification target to current location and mapset
  662. """
  663. # check to see if we are georectifying map in current working location/mapset
  664. if self.newlocation == self.currentlocation and self.newmapset == self.currentmapset:
  665. gcmd.RunCommand('i.target',
  666. parent = self,
  667. flags = 'c',
  668. group = tgroup)
  669. else:
  670. self.grwiz.SwitchEnv('new')
  671. gcmd.RunCommand('i.target',
  672. parent = self,
  673. group = tgroup,
  674. location = tlocation,
  675. mapset = tmapset)
  676. self.grwiz.SwitchEnv('original')
  677. def AddGCP(self, event):
  678. """
  679. Appends an item to GCP list
  680. """
  681. self.list.AddGCPItem()
  682. # x, y, MapWindow instance
  683. self.mapcoordlist.append({ 'gcpcoord' : (0.0, 0.0, None),
  684. 'mapcoord' : (0.0, 0.0, None) })
  685. def DeleteGCP(self, event):
  686. """
  687. Deletes selected item in GCP list
  688. """
  689. minNumOfItems = self.OnGRMethod(None)
  690. if self.list.GetItemCount() <= minNumOfItems:
  691. wx.MessageBox(parent=self, message=_("At least %d GCPs required. Operation cancelled.") % minNumOfItems,
  692. caption=_("Delete GCP"), style=wx.OK | wx.ICON_INFORMATION)
  693. return
  694. item = self.list.DeleteGCPItem()
  695. del self.mapcoordlist[item]
  696. def ClearGCP(self, event):
  697. """
  698. Clears all values in selected item of GCP list and unchecks it
  699. """
  700. index = self.list.GetSelected()
  701. for i in range(4):
  702. self.list.SetStringItem(index, i, '0.0')
  703. self.list.SetStringItem(index, 4, '')
  704. self.list.SetStringItem(index, 5, '')
  705. self.list.CheckItem(index, False)
  706. self.mapcoordlist[index] = { 'gcpcoord' : (0.0, 0.0, None),
  707. 'mapcoord' : (0.0, 0.0, None) }
  708. def DrawGCP(self, coordtype):
  709. """
  710. Updates GCP and map coord maps and redraws
  711. active (checked) GCP markers
  712. """
  713. col = UserSettings.Get(group='georect', key='symbol', subkey='color')
  714. wxCol = wx.Colour(col[0], col[1], col[2], 255)
  715. wpx = UserSettings.Get(group='georect', key='symbol', subkey='width')
  716. font = self.GetFont()
  717. penOrig = polypenOrig = None
  718. idx = 0
  719. for gcp in self.mapcoordlist:
  720. mapWin = gcp[coordtype][2]
  721. if not self.list.IsChecked(idx) or not mapWin:
  722. idx += 1
  723. continue
  724. if not penOrig:
  725. penOrig = mapWin.pen
  726. polypenOrig = mapWin.polypen
  727. mapWin.pen = wx.Pen(colour=wxCol, width=wpx, style=wx.SOLID)
  728. mapWin.polypen = wx.Pen(colour=wxCol, width=wpx, style=wx.SOLID) # ?
  729. coord = mapWin.Cell2Pixel((gcp[coordtype][0], gcp[coordtype][1]))
  730. mapWin.DrawCross(pdc=mapWin.pdcTmp, coords=coord,
  731. size=5, text={ 'text' : '%s' % str(idx + 1),
  732. 'active' : True,
  733. 'font' : font,
  734. 'color': wxCol,
  735. 'coords': [coord[0] + 5,
  736. coord[1] + 5,
  737. 5,
  738. 5]})
  739. idx += 1
  740. if penOrig:
  741. mapWin.pen = penOrig
  742. mapWin.polypen = polypenOrig
  743. def SetGCPData(self, coordtype, coord, mapdisp=None, check=True):
  744. """
  745. Inserts coordinates from mouse click on map
  746. into selected item of GCP list and checks it for use
  747. """
  748. index = self.list.GetSelected()
  749. if index == wx.NOT_FOUND:
  750. return
  751. coord0 = str(coord[0])
  752. coord1 = str(coord[1])
  753. if coordtype == 'gcpcoord':
  754. self.list.SetStringItem(index, 0, coord0)
  755. self.list.SetStringItem(index, 1, coord1)
  756. self.mapcoordlist[index]['gcpcoord'] = (coord[0], coord[1], mapdisp)
  757. elif coordtype == 'mapcoord':
  758. self.list.SetStringItem(index, 2, coord0)
  759. self.list.SetStringItem(index, 3, coord1)
  760. self.mapcoordlist[index][coordtype] = (coord[0], coord[1], mapdisp)
  761. self.list.CheckItem(index, check)
  762. # self.list.ResizeColumns()
  763. def SaveGCPs(self, event):
  764. """
  765. Make a POINTS file or save GCP coordinates to existing POINTS file
  766. """
  767. self.GCPcount = 0
  768. try:
  769. f = open(self.file['points'], mode='w')
  770. # use os.linesep or '\n' here ???
  771. f.write('# Ground Control Points File\n')
  772. f.write("# \n")
  773. f.write("# target location: " + self.currentlocation + '\n')
  774. f.write("# target mapset: " + self.currentmapset + '\n')
  775. f.write("#unrectified xy georectified east north 1=use gcp point\n")
  776. f.write("#-------------- ----------------------- ---------------\n")
  777. for index in range(self.list.GetItemCount()):
  778. if self.list.IsChecked(index) == True:
  779. check = "1"
  780. self.GCPcount += 1
  781. else:
  782. check = "0"
  783. coord0 = self.list.GetItem(index, 0).GetText()
  784. coord1 = self.list.GetItem(index, 1).GetText()
  785. coord2 = self.list.GetItem(index, 2).GetText()
  786. coord3 = self.list.GetItem(index, 3).GetText()
  787. f.write(coord0 + ' ' + coord1 + ' ' + coord2 + ' ' + coord3 + ' ' + check + '\n')
  788. self.parent.goutput.WriteLog(_('POINTS file <%s> saved') % self.file['points'])
  789. self.SetStatusText(_('POINTS file saved'))
  790. except IOError, err:
  791. wx.MessageBox(parent=self,
  792. message="%s <%s>. %s%s" % (_("Writing POINTS file failed"),
  793. self.file['points'], os.linesep, err),
  794. caption=_("Error"), style=wx.OK | wx.ICON_ERROR | wx.CENTRE)
  795. return
  796. f.close()
  797. def ReadGCPs(self):
  798. """
  799. Reads GCPs and georectified coordinates from POINTS file
  800. """
  801. self.GCPcount = 0
  802. sourceMapWin = self.mapdisp.MapWindow
  803. targetMapWin = self.parent.curr_page.maptree.mapdisplay.MapWindow
  804. try:
  805. f = open(self.file['points'], 'r')
  806. GCPcnt = 0
  807. for line in f.readlines():
  808. if line[0] == '#' or line =='':
  809. continue
  810. line = line.replace('\n', '').strip()
  811. coords = map(float, line.split())
  812. if coords[4] == 1:
  813. check = True
  814. self.GCPcount +=1
  815. else:
  816. check = False
  817. index = self.AddGCP(event=None)
  818. self.SetGCPData('gcpcoord', (coords[0], coords[1]), sourceMapWin, check)
  819. self.SetGCPData('mapcoord', (coords[2], coords[3]), targetMapWin, check)
  820. except IOError, err:
  821. wx.MessageBox(parent=self,
  822. message="%s <%s>. %s%s" % (_("Reading POINTS file failed"),
  823. self.file['points'], os.linesep, err),
  824. caption=_("Error"), style=wx.OK | wx.ICON_ERROR | wx.CENTRE)
  825. return
  826. f.close()
  827. #
  828. # draw GCPs (source and target)
  829. #
  830. sourceMapWin.UpdateMap(render=False, renderVector=False)
  831. if targetMapWin:
  832. targetMapWin.UpdateMap(render=False, renderVector=False)
  833. #
  834. # calculate RMS
  835. #
  836. # FIXME auto calculation on load is not working
  837. #if self.CheckGCPcount():
  838. # self.RMSError(self.xygroup, self.gr_order)
  839. def ReloadGCPs(self, event):
  840. """!Reload data from file"""
  841. self.list.LoadData()
  842. def OnFocus(self, event):
  843. # self.grwiz.SwitchEnv('new')
  844. pass
  845. def OnRMS(self, event):
  846. """
  847. RMS button handler
  848. """
  849. self.RMSError(self.xygroup,self.gr_order)
  850. def CheckGCPcount(self, msg=False):
  851. """
  852. Checks to make sure that the minimum number of GCPs have been defined and
  853. are active for the selected transformation order
  854. """
  855. if (self.GCPcount < 3 and self.gr_order == 1) or \
  856. (self.GCPcount < 6 and self.gr_order == 2) or \
  857. (self.GCPcount < 10 and self.gr_order == 3):
  858. if msg:
  859. wx.MessageBox(parent=self,
  860. caption=_("RMS Error"),
  861. message=_('Insufficient points defined and active (checked) '
  862. 'for selected rectification method.\n'
  863. '3+ points needed for 1st order,\n'
  864. '6+ points for 2nd order, and\n'
  865. '10+ points for 3rd order.'),
  866. style=wx.ICON_INFORMATION | wx.ID_OK | wx.CENTRE)
  867. return False
  868. else:
  869. return True
  870. def OnGeorect(self, event):
  871. """
  872. Georectifies map(s) in group using i.rectify or v.transform
  873. """
  874. global maptype
  875. self.SaveGCPs(None)
  876. if self.CheckGCPcount(msg=True) == False:
  877. return
  878. if maptype == 'cell':
  879. self.grwiz.SwitchEnv('new')
  880. cmdlist = ['i.rectify','-a','group=%s' % self.xygroup,
  881. 'extension=%s' % self.extension,'order=%s' % self.gr_order]
  882. if self.clip_to_region:
  883. cmdlist.append('-c')
  884. self.parent.goutput.RunCmd(cmdlist, compReg=False,
  885. switchPage=True)
  886. time.sleep(.1)
  887. elif maptype == 'vector':
  888. outmsg = ''
  889. # loop through all vectors in VREF
  890. # and move resulting vector to target location
  891. # make sure current mapset has a vector folder
  892. if not os.path.isdir(os.path.join(self.grassdatabase,
  893. self.currentlocation,
  894. self.currentmapset,
  895. 'vector')):
  896. os.mkdir(os.path.join(self.grassdatabase,
  897. self.currentlocation,
  898. self.currentmapset,
  899. 'vector'))
  900. self.grwiz.SwitchEnv('new')
  901. # make list of vectors to georectify from VREF
  902. f = open(self.file['vgrp'])
  903. vectlist = []
  904. try:
  905. for vect in f.readlines():
  906. vect = vect.strip('\n')
  907. if len(vect) < 1:
  908. continue
  909. vectlist.append(vect)
  910. finally:
  911. f.close()
  912. # georectify each vector in VREF using v.transform
  913. for vect in vectlist:
  914. self.outname = vect + '_' + self.extension
  915. self.parent.goutput.WriteLog(text = _('Transforming <%s>...') % vect,
  916. switchPage = True)
  917. msg = err = ''
  918. ret, out, err = gcmd.RunCommand('v.transform',
  919. flags = '-o',
  920. input=vect,
  921. output=self.outname,
  922. pointsfile=self.file['points'],
  923. getErrorMsg=True, read=True)
  924. if ret == 0:
  925. self.VectGRList.append(self.outname)
  926. print err
  927. # note: WriteLog doesn't handle GRASS_INFO_PERCENT well, so using a print here
  928. # self.parent.goutput.WriteLog(text = _(err), switchPage = True)
  929. self.parent.goutput.WriteLog(text = _(out), switchPage = True)
  930. else:
  931. self.parent.goutput.WriteError(_('Georectification of vector map <%s> failed') %
  932. self.outname)
  933. self.parent.goutput.WriteError(_(err))
  934. # FIXME
  935. # Copying database information not working.
  936. # Does not copy from xy location to current location
  937. # xyLayer = []
  938. # for layer in grass.vector_db(map = vect).itervalues():
  939. # xyLayer.append((layer['driver'],
  940. # layer['database'],
  941. # layer['table']))
  942. # dbConnect = grass.db_connection()
  943. # print 'db connection =', dbConnect
  944. # for layer in xyLayer:
  945. # self.parent.goutput.RunCmd(['db.copy',
  946. # '--q',
  947. # '--o',
  948. # 'from_driver=%s' % layer[0],
  949. # 'from_database=%s' % layer[1],
  950. # 'from_table=%s' % layer[2],
  951. # 'to_driver=%s' % dbConnect['driver'],
  952. # 'to_database=%s' % dbConnect['database'],
  953. # 'to_table=%s' % layer[2] + '_' + self.extension])
  954. # copy all georectified vectors from source location to current location
  955. for name in self.VectGRList:
  956. xyvpath = os.path.join(self.grassdatabase,
  957. self.xylocation,
  958. self.xymapset,
  959. 'vector',
  960. name)
  961. vpath = os.path.join(self.grassdatabase,
  962. self.currentlocation,
  963. self.currentmapset,
  964. 'vector',
  965. name)
  966. if os.path.isdir(vpath):
  967. self.parent.goutput.WriteWarning(_('Vector map <%s> already exists. '
  968. 'Change extension name and '
  969. 'georectify again.') % self.outname)
  970. break
  971. else:
  972. shutil.move(xyvpath, vpath)
  973. wx.MessageBox('For all vector maps georectified successfully, ' + '\n' +
  974. 'you will need to copy any attribute tables' + '\n' +
  975. 'and reconnect them to the georectified vectors')
  976. self.grwiz.SwitchEnv('original')
  977. def OnGeorectDone(self, **kargs):
  978. """!Print final message"""
  979. global maptype
  980. if maptype == 'cell':
  981. return
  982. returncode = kargs['returncode']
  983. if returncode == 0:
  984. self.VectGRList.append(self.outname)
  985. print '*****vector list = ' + str(self.VectGRList)
  986. else:
  987. self.parent.goutput.WriteError(_('Georectification of vector map <%s> failed') %
  988. self.outname)
  989. def OnSettings(self, event):
  990. """!Georectifier settings"""
  991. dlg = GrSettingsDialog(parent=self, id=wx.ID_ANY, title=_('Georectifier settings'))
  992. if dlg.ShowModal() == wx.ID_OK:
  993. pass
  994. dlg.Destroy()
  995. def OnQuit(self, event):
  996. """!Quit georectifier"""
  997. self.grwiz.Cleanup()
  998. self.Destroy()
  999. event.Skip()
  1000. def OnGRMethod(self, event):
  1001. """
  1002. sets transformation order for georectifying
  1003. """
  1004. if event:
  1005. self.gr_order = event.GetInt() + 1
  1006. numOfItems = self.list.GetItemCount()
  1007. minNumOfItems = numOfItems
  1008. if self.gr_order == 1:
  1009. minNumOfItems = 3
  1010. # self.SetStatusText(_('Insufficient points, 3+ points needed for 1st order'))
  1011. elif self.gr_order == 2:
  1012. minNumOfItems = 6
  1013. diff = 6 - numOfItems
  1014. # self.SetStatusText(_('Insufficient points, 6+ points needed for 2nd order'))
  1015. elif self.gr_order == 3:
  1016. minNumOfItems = 10
  1017. # self.SetStatusText(_('Insufficient points, 10+ points needed for 3rd order'))
  1018. for i in range(minNumOfItems - numOfItems):
  1019. self.AddGCP(None)
  1020. return minNumOfItems
  1021. def RMSError(self, xygroup, order):
  1022. """
  1023. Uses g.transform to calculate forward and backward error for each used GCP
  1024. in POINTS file and insert error values into GCP list.
  1025. Calculates total forward and backward RMS error for all used points
  1026. """
  1027. # save GCPs to points file to make sure that all checked GCPs are used
  1028. self.SaveGCPs(None)
  1029. if self.CheckGCPcount(msg=True) == False:
  1030. return
  1031. # get list of forward and reverse rms error values for each point
  1032. self.grwiz.SwitchEnv('new')
  1033. ret = gcmd.RunCommand('g.transform',
  1034. parent = self,
  1035. read = True,
  1036. group = xygroup,
  1037. order = order)
  1038. self.grwiz.SwitchEnv('original')
  1039. if ret:
  1040. errlist = ret.splitlines()
  1041. if errlist == []:
  1042. return
  1043. # insert error values into GCP list for checked items
  1044. i = 0
  1045. sumsq_fwd_err = 0.0
  1046. sumsq_bkw_err = 0.0
  1047. for index in range(self.list.GetItemCount()):
  1048. if self.list.IsChecked(index):
  1049. fwd_err, bkw_err = errlist[i].split()
  1050. self.list.SetStringItem(index, 4, fwd_err)
  1051. self.list.SetStringItem(index, 5, bkw_err)
  1052. sumsq_fwd_err += float(fwd_err)**2
  1053. sumsq_bkw_err += float(bkw_err)**2
  1054. i += 1
  1055. else:
  1056. self.list.SetStringItem(index, 4, '')
  1057. self.list.SetStringItem(index, 5, '')
  1058. # calculate RMS error
  1059. self.fwd_rmserror = round((sumsq_fwd_err/i)**0.5,4)
  1060. self.bkw_rmserror = round((sumsq_bkw_err/i)**0.5,4)
  1061. self.list.ResizeColumns()
  1062. self.SetStatusText(_('RMS error for selected points forward: %(fwd)s backward: %(bkw)s') % \
  1063. { 'fwd' : self.fwd_rmserror, 'bkw' : self.bkw_rmserror })
  1064. class GCPList(wx.ListCtrl,
  1065. CheckListCtrlMixin,
  1066. ListCtrlAutoWidthMixin):
  1067. def __init__(self, parent, gcp, id=wx.ID_ANY,
  1068. pos=wx.DefaultPosition, size=wx.DefaultSize,
  1069. style=wx.LC_REPORT | wx.SUNKEN_BORDER | wx.LC_HRULES |
  1070. wx.LC_SINGLE_SEL):
  1071. wx.ListCtrl.__init__(self, parent, id, pos, size, style)
  1072. # Mixin settings
  1073. CheckListCtrlMixin.__init__(self)
  1074. ListCtrlAutoWidthMixin.__init__(self)
  1075. # TextEditMixin.__init__(self)
  1076. self.gcp = gcp # GCP class
  1077. # tracks whether list items are checked or not
  1078. self.CheckList = []
  1079. self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnItemSelected)
  1080. self.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.OnItemActivated)
  1081. self._Create()
  1082. self.selected = wx.NOT_FOUND
  1083. def _Create(self):
  1084. idx_col = 0
  1085. for col in (_('use| X coord'),
  1086. _('Y coord'),
  1087. _('E coord'),
  1088. _('N coord'),
  1089. _('Forward error'),
  1090. _('Backward error')):
  1091. self.InsertColumn(idx_col, col)
  1092. idx_col += 1
  1093. def LoadData(self):
  1094. """!Load data into list"""
  1095. self.DeleteAllItems()
  1096. if os.path.isfile(self.gcp.file['points']):
  1097. self.gcp.ReadGCPs()
  1098. else:
  1099. # 3 gcp is minimum
  1100. for i in range(3):
  1101. self.gcp.AddGCP(None)
  1102. # select first point by default
  1103. self.selected = 0
  1104. self.SetItemState(self.selected,
  1105. wx.LIST_STATE_SELECTED,
  1106. wx.LIST_STATE_SELECTED)
  1107. self.ResizeColumns()
  1108. def OnCheckItem(self, index, flag):
  1109. """!Item is checked/unchecked"""
  1110. pass
  1111. def AddGCPItem(self):
  1112. """
  1113. Appends an item to GCP list
  1114. """
  1115. self.Append(['0.0',
  1116. '0.0',
  1117. '0.0',
  1118. '0.0',
  1119. '',
  1120. ''])
  1121. self.selected = self.GetItemCount() - 1
  1122. self.SetItemState(self.selected,
  1123. wx.LIST_STATE_SELECTED,
  1124. wx.LIST_STATE_SELECTED)
  1125. self.ResizeColumns()
  1126. return self.selected
  1127. def DeleteGCPItem(self):
  1128. """
  1129. Deletes selected item in GCP list
  1130. """
  1131. if self.selected == wx.NOT_FOUND:
  1132. return
  1133. self.DeleteItem(self.selected)
  1134. if self.GetItemCount() > 0:
  1135. self.selected = self.GetItemCount() - 1
  1136. self.SetItemState(self.selected,
  1137. wx.LIST_STATE_SELECTED,
  1138. wx.LIST_STATE_SELECTED)
  1139. else:
  1140. self.selected = wx.NOT_FOUND
  1141. return self.selected
  1142. def ResizeColumns(self):
  1143. """!Resize columns"""
  1144. minWidth = 90
  1145. for i in range(self.GetColumnCount()):
  1146. self.SetColumnWidth(i, wx.LIST_AUTOSIZE)
  1147. if self.GetColumnWidth(i) < minWidth:
  1148. self.SetColumnWidth(i, minWidth)
  1149. self.SendSizeEvent()
  1150. def GetSelected(self):
  1151. """!Get index of selected item"""
  1152. return self.selected
  1153. def OnItemSelected(self, event):
  1154. self.selected = event.GetIndex()
  1155. def OnItemActivated(self, event):
  1156. """
  1157. When item double clicked, open editor to update coordinate values
  1158. """
  1159. coords = []
  1160. index = event.GetIndex()
  1161. for i in range(4):
  1162. coords.append(self.GetItem(index, i).GetText())
  1163. dlg = EditGPC(parent=self, id=wx.ID_ANY, data=coords)
  1164. if dlg.ShowModal() == wx.ID_OK:
  1165. values = dlg.GetValues() # string
  1166. if len(values) == 0:
  1167. wx.MessageBox(parent=self,
  1168. caption=_("Edit GCP"),
  1169. message=_("Invalid coordinate value. Operation cancelled."),
  1170. style=wx.CENTRE | wx.ICON_ERROR | wx.ID_OK)
  1171. else:
  1172. for i in range(len(values)):
  1173. if values[i] != coords[i]:
  1174. self.SetStringItem(index, i, values[i])
  1175. mapdisp = self.gcp.mapcoordlist[index]['gcpcoord'][2]
  1176. self.gcp.mapcoordlist[index]['gcpcoord'] = (float(values[0]), float(values[1]), mapdisp)
  1177. mapdisp = self.gcp.mapcoordlist[index]['mapcoord'][2]
  1178. self.gcp.mapcoordlist[index]['mapcoord'] = (float(values[0]), float(values[1]), mapdisp)
  1179. class VectGroup(wx.Dialog):
  1180. """
  1181. Dialog to create a vector group (VREF file) for georectifying
  1182. @todo Replace by g.group
  1183. """
  1184. def __init__(self, parent, id, grassdb, location, mapset, group,
  1185. style=wx.DEFAULT_DIALOG_STYLE):
  1186. wx.Dialog.__init__(self, parent, id, style=style,
  1187. title = _("Create vector map group"))
  1188. self.grassdatabase = grassdb
  1189. self.xylocation = location
  1190. self.xymapset = mapset
  1191. self.xygroup = group
  1192. #
  1193. # get list of valid vector directories
  1194. #
  1195. vectlist = os.listdir(os.path.join(self.grassdatabase,
  1196. self.xylocation,
  1197. self.xymapset,
  1198. 'vector'))
  1199. for dir in vectlist:
  1200. if not os.path.isfile(os.path.join(self.grassdatabase,
  1201. self.xylocation,
  1202. self.xymapset,
  1203. 'vector',
  1204. dir,
  1205. 'coor')):
  1206. vectlist.remove(dir)
  1207. utils.ListSortLower(vectlist)
  1208. # path to vref file
  1209. self.vgrpfile = os.path.join(self.grassdatabase,
  1210. self.xylocation,
  1211. self.xymapset,
  1212. 'group',
  1213. self.xygroup,
  1214. 'VREF')
  1215. #
  1216. # buttons
  1217. #
  1218. self.btnCancel = wx.Button(parent = self,
  1219. id = wx.ID_CANCEL)
  1220. self.btnOK = wx.Button(parent = self,
  1221. id = wx.ID_OK)
  1222. self.btnOK.SetDefault()
  1223. #
  1224. # list of vector maps
  1225. #
  1226. self.listMap = wx.CheckListBox(parent = self, id = wx.ID_ANY,
  1227. choices = vectlist)
  1228. if os.path.isfile(self.vgrpfile):
  1229. f = open(self.vgrpfile)
  1230. try:
  1231. checked = []
  1232. for line in f.readlines():
  1233. line = line.replace('\n', '')
  1234. if len(line) < 1:
  1235. continue
  1236. checked.append(line)
  1237. self.listMap.SetCheckedStrings(checked)
  1238. finally:
  1239. f.close()
  1240. line = wx.StaticLine(parent = self,
  1241. id = wx.ID_ANY, size = (20, -1),
  1242. style = wx.LI_HORIZONTAL)
  1243. #
  1244. # layout
  1245. #
  1246. sizer = wx.BoxSizer(wx.VERTICAL)
  1247. box = wx.BoxSizer(wx.HORIZONTAL)
  1248. box.Add(item = wx.StaticText(parent = self, id = wx.ID_ANY,
  1249. label = _('Select vector map(s) to add to group:')),
  1250. flag = wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.LEFT,
  1251. border = 5)
  1252. box.Add(item = self.listMap,
  1253. flag = wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.LEFT,
  1254. border = 5)
  1255. sizer.Add(box, flag = wx.ALIGN_RIGHT | wx.ALL,
  1256. border = 3)
  1257. sizer.Add(item = line, proportion = 0,
  1258. flag = wx.GROW | wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT,
  1259. border = 5)
  1260. # buttons
  1261. btnSizer = wx.StdDialogButtonSizer()
  1262. btnSizer.AddButton(self.btnCancel)
  1263. btnSizer.AddButton(self.btnOK)
  1264. btnSizer.Realize()
  1265. sizer.Add(item = btnSizer, proportion = 0,
  1266. flag = wx.EXPAND | wx.ALL | wx.ALIGN_CENTER,
  1267. border = 5)
  1268. self.SetSizer(sizer)
  1269. sizer.Fit(self)
  1270. self.Layout()
  1271. def MakeVGroup(self):
  1272. """!Create VREF file"""
  1273. vgrouplist = []
  1274. for item in range(self.listMap.GetCount()):
  1275. if not self.listMap.IsChecked(item):
  1276. continue
  1277. vgrouplist.append(self.listMap.GetString(item))
  1278. f = open(self.vgrpfile, mode='w')
  1279. try:
  1280. for vect in vgrouplist:
  1281. f.write(vect + '\n')
  1282. finally:
  1283. f.close()
  1284. class EditGPC(wx.Dialog):
  1285. def __init__(self, parent, data, id=wx.ID_ANY,
  1286. title=_("Edit GCP"),
  1287. style=wx.DEFAULT_DIALOG_STYLE):
  1288. """!Dialog for editing GPC and map coordinates in list control"""
  1289. wx.Dialog.__init__(self, parent, id, title=title, style=style)
  1290. panel = wx.Panel(parent=self)
  1291. sizer = wx.BoxSizer(wx.VERTICAL)
  1292. box = wx.StaticBox (parent=panel, id=wx.ID_ANY,
  1293. label=" %s " % _("Ground Control Point"))
  1294. boxSizer = wx.StaticBoxSizer(box, wx.VERTICAL)
  1295. # source coordinates
  1296. gridSizer = wx.GridBagSizer(vgap=5, hgap=5)
  1297. self.xcoord = wx.TextCtrl(parent=panel, id=wx.ID_ANY, size=(150, -1))
  1298. self.ycoord = wx.TextCtrl(parent=panel, id=wx.ID_ANY, size=(150, -1))
  1299. self.ncoord = wx.TextCtrl(parent=panel, id=wx.ID_ANY, size=(150, -1))
  1300. self.ecoord = wx.TextCtrl(parent=panel, id=wx.ID_ANY, size=(150, -1))
  1301. row = 0
  1302. col = 0
  1303. idx = 0
  1304. for label, win in ((_("X:"), self.xcoord),
  1305. (_("Y:"), self.ycoord),
  1306. (_("E:"), self.ecoord),
  1307. (_("N:"), self.ncoord)):
  1308. label = wx.StaticText(parent=panel, id=wx.ID_ANY,
  1309. label=label)
  1310. gridSizer.Add(item=label,
  1311. flag=wx.ALIGN_CENTER_VERTICAL,
  1312. pos=(row, col))
  1313. col += 1
  1314. win.SetValue(str(data[idx]))
  1315. gridSizer.Add(item=win,
  1316. pos=(row, col))
  1317. col += 1
  1318. idx += 1
  1319. if col > 3:
  1320. row += 1
  1321. col = 0
  1322. boxSizer.Add(item=gridSizer, proportion=1,
  1323. flag=wx.EXPAND | wx.ALL, border=5)
  1324. sizer.Add(item=boxSizer, proportion=1,
  1325. flag=wx.EXPAND | wx.ALL, border=5)
  1326. #
  1327. # buttons
  1328. #
  1329. self.btnCancel = wx.Button(panel, wx.ID_CANCEL)
  1330. self.btnOk = wx.Button(panel, wx.ID_OK)
  1331. self.btnOk.SetDefault()
  1332. btnSizer = wx.StdDialogButtonSizer()
  1333. btnSizer.AddButton(self.btnCancel)
  1334. btnSizer.AddButton(self.btnOk)
  1335. btnSizer.Realize()
  1336. sizer.Add(item=btnSizer, proportion=0,
  1337. flag=wx.ALIGN_RIGHT | wx.ALL, border=5)
  1338. panel.SetSizer(sizer)
  1339. sizer.Fit(self)
  1340. def GetValues(self, columns=None):
  1341. """!Return list of values (as strings).
  1342. """
  1343. valuelist = []
  1344. try:
  1345. float(self.xcoord.GetValue())
  1346. float(self.ycoord.GetValue())
  1347. float(self.ecoord.GetValue())
  1348. float(self.ncoord.GetValue())
  1349. except ValueError:
  1350. return valuelist
  1351. valuelist.append(self.xcoord.GetValue())
  1352. valuelist.append(self.ycoord.GetValue())
  1353. valuelist.append(self.ecoord.GetValue())
  1354. valuelist.append(self.ncoord.GetValue())
  1355. return valuelist
  1356. class GrSettingsDialog(wx.Dialog):
  1357. def __init__(self, parent, id, title, pos=wx.DefaultPosition, size=wx.DefaultSize,
  1358. style=wx.DEFAULT_DIALOG_STYLE):
  1359. wx.Dialog.__init__(self, parent, id, title, pos, size, style)
  1360. """
  1361. Dialog to set profile text options: font, title
  1362. and font size, axis labels and font size
  1363. """
  1364. #
  1365. # initialize variables
  1366. #
  1367. self.parent = parent
  1368. self.symbol = {}
  1369. self._do_layout()
  1370. def _do_layout(self):
  1371. """!Do layout"""
  1372. # dialog layout
  1373. sizer = wx.BoxSizer(wx.VERTICAL)
  1374. box = wx.StaticBox(parent=self, id=wx.ID_ANY,
  1375. label=" %s " % _("Symbol settings"))
  1376. boxSizer = wx.StaticBoxSizer(box, wx.VERTICAL)
  1377. gridSizer = wx.GridBagSizer(vgap=5, hgap=5)
  1378. gridSizer.AddGrowableCol(1)
  1379. #
  1380. # symbol color
  1381. #
  1382. row = 0
  1383. label = wx.StaticText(parent=self, id=wx.ID_ANY, label=_("Color:"))
  1384. gridSizer.Add(item=label, flag=wx.ALIGN_CENTER_VERTICAL, pos=(row, 0))
  1385. col = UserSettings.Get(group='georect', key='symbol', subkey='color')
  1386. colWin = csel.ColourSelect(parent=self, id=wx.ID_ANY,
  1387. colour=wx.Colour(col[0],
  1388. col[1],
  1389. col[2],
  1390. 255))
  1391. self.symbol['color'] = colWin.GetId()
  1392. gridSizer.Add(item=colWin,
  1393. flag=wx.ALIGN_RIGHT,
  1394. pos=(row, 1))
  1395. #
  1396. # symbol width
  1397. #
  1398. row += 1
  1399. label = wx.StaticText(parent=self, id=wx.ID_ANY, label=_("Width:"))
  1400. gridSizer.Add(item=label, flag=wx.ALIGN_CENTER_VERTICAL, pos=(row, 0))
  1401. width = int(UserSettings.Get(group='georect', key='symbol', subkey='width'))
  1402. widWin = wx.SpinCtrl(parent=self, id=wx.ID_ANY,
  1403. min=1, max=10)
  1404. widWin.SetValue(width)
  1405. self.symbol['width'] = widWin.GetId()
  1406. gridSizer.Add(item=widWin,
  1407. flag=wx.ALIGN_RIGHT,
  1408. pos=(row, 1))
  1409. boxSizer.Add(item=gridSizer, flag=wx.EXPAND)
  1410. sizer.Add(item=boxSizer, flag=wx.EXPAND | wx.ALL, border=5)
  1411. line = wx.StaticLine(parent=self, id=wx.ID_ANY, size=(20, -1), style=wx.LI_HORIZONTAL)
  1412. sizer.Add(item=line, proportion=0,
  1413. flag=wx.GROW|wx.ALIGN_CENTER_VERTICAL|wx.LEFT|wx.RIGHT, border=3)
  1414. #
  1415. # buttons
  1416. #
  1417. btnSave = wx.Button(self, wx.ID_SAVE)
  1418. btnApply = wx.Button(self, wx.ID_APPLY)
  1419. btnCancel = wx.Button(self, wx.ID_CANCEL)
  1420. btnSave.SetDefault()
  1421. # bindigs
  1422. btnApply.Bind(wx.EVT_BUTTON, self.OnApply)
  1423. btnApply.SetToolTipString(_("Apply changes for the current session"))
  1424. btnSave.Bind(wx.EVT_BUTTON, self.OnSave)
  1425. btnSave.SetToolTipString(_("Apply and save changes to user settings file (default for next sessions)"))
  1426. btnSave.SetDefault()
  1427. btnCancel.Bind(wx.EVT_BUTTON, self.OnCancel)
  1428. btnCancel.SetToolTipString(_("Close dialog and ignore changes"))
  1429. # sizers
  1430. btnStdSizer = wx.StdDialogButtonSizer()
  1431. btnStdSizer.AddButton(btnCancel)
  1432. btnStdSizer.AddButton(btnSave)
  1433. btnStdSizer.AddButton(btnApply)
  1434. btnStdSizer.Realize()
  1435. sizer.Add(item=btnStdSizer, proportion=0, flag=wx.ALIGN_RIGHT | wx.ALL, border=5)
  1436. self.SetSizer(sizer)
  1437. sizer.Fit(self)
  1438. def UpdateSettings(self):
  1439. UserSettings.Set(group='georect', key='symbol', subkey='color',
  1440. value=wx.FindWindowById(self.symbol['color']).GetColour())
  1441. UserSettings.Set(group='georect', key='symbol', subkey='width',
  1442. value=wx.FindWindowById(self.symbol['width']).GetValue())
  1443. def OnSave(self, event):
  1444. """!Button 'Save' pressed"""
  1445. self.UpdateSettings()
  1446. fileSettings = {}
  1447. UserSettings.ReadSettingsFile(settings=fileSettings)
  1448. fileSettings['georect'] = UserSettings.Get(group='georect')
  1449. file = UserSettings.SaveToFile(fileSettings)
  1450. self.parent.parent.goutput.WriteLog(_('Georectifier settings saved to file \'%s\'.') % file)
  1451. self.Close()
  1452. def OnApply(self, event):
  1453. """!Button 'Apply' pressed"""
  1454. self.UpdateSettings()
  1455. self.Close()
  1456. def OnCancel(self, event):
  1457. """!Button 'Cancel' pressed"""
  1458. self.Close()