georect.py 63 KB

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