georect.py 63 KB

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