georect.py 61 KB

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