vkrige.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  1. """
  2. MODULE: vkrige
  3. AUTHOR(S): Anne Ghisla <a.ghisla AT gmail.com>
  4. PURPOSE: Dedicated GUI for v.krige script.
  5. DEPENDS: R 2.x, packages gstat, maptools and spgrass6, optional: automap
  6. COPYRIGHT: (C) 2009 by the GRASS Development Team
  7. This program is free software under the GNU General Public
  8. License (>=v2). Read the file COPYING that comes with GRASS
  9. for details.
  10. """
  11. #@TODO move here imports related to wxGUI
  12. ### generic imports
  13. import os, sys
  14. from tempfile import gettempdir
  15. import time
  16. import thread
  17. from core.utils import _
  18. ### dependencies to be checked once, as they are quite time-consuming. cfr. grass.parser.
  19. # GRASS binding
  20. try:
  21. import grass.script as grass
  22. except ImportError:
  23. sys.exit(_("No GRASS-python library found."))
  24. ### wxGUI imports
  25. GUIModulesPath = os.path.join(os.getenv("GISBASE"), "etc", "gui", "wxpython")
  26. if GUIModulesPath not in sys.path:
  27. sys.path.append(GUIModulesPath)
  28. from core import globalvar
  29. from gui_core import gselect
  30. from core import gconsole
  31. from gui_core import goutput
  32. from core.settings import UserSettings
  33. from gui_core.widgets import GNotebook
  34. #import help
  35. import wx
  36. #import wx.lib.plot as plot # for plotting the variogram.
  37. import rpy2.robjects as robjects
  38. import rpy2.rinterface as rinterface
  39. # global variables
  40. maxint = 1e6 # instead of sys.maxint, not working with SpinCtrl on 64bit [reported by Bob Moskovitz]
  41. #@TODO move away functions not regarding the GUI
  42. class KrigingPanel(wx.Panel):
  43. """ Main panel. Contains all widgets except Menus and Statusbar. """
  44. def __init__(self, parent, Rinstance, controller, *args, **kwargs):
  45. wx.Panel.__init__(self, parent, *args, **kwargs)
  46. self.parent = parent
  47. self.border = 4
  48. # 1. Input data
  49. InputBoxSizer = wx.StaticBoxSizer(wx.StaticBox(self, id = wx.ID_ANY, label = _("Input Data")),
  50. orient = wx.HORIZONTAL)
  51. flexSizer = wx.FlexGridSizer(cols = 3, hgap = 5, vgap = 5)
  52. flexSizer.AddGrowableCol(1)
  53. flexSizer.Add(item = wx.StaticText(self, id = wx.ID_ANY, label = _("Point dataset:")),
  54. flag = wx.ALIGN_CENTER_VERTICAL)
  55. self.InputDataMap = gselect.VectorSelect(parent = self,
  56. ftype = 'points',
  57. updateOnPopup = False)
  58. self.InputDataMap.SetFocus()
  59. flexSizer.Add(item = self.InputDataMap, flag = wx.ALIGN_CENTER_VERTICAL)
  60. RefreshButton = wx.Button(self, id = wx.ID_REFRESH)
  61. RefreshButton.Bind(wx.EVT_BUTTON, self.OnButtonRefresh)
  62. flexSizer.Add(item = RefreshButton, flag = wx.ALIGN_CENTER_VERTICAL)
  63. flexSizer.Add(item = wx.StaticText(self, id = wx.ID_ANY, label = _("Numeric column:")),
  64. flag = wx.ALIGN_CENTER_VERTICAL)
  65. self.InputDataColumn = gselect.ColumnSelect(self, id = wx.ID_ANY)
  66. flexSizer.Add(item = self.InputDataColumn)
  67. self.InputDataMap.GetChildren()[0].Bind(wx.EVT_TEXT, self.OnInputMapChanged)
  68. self.InputDataColumn.GetChildren()[0].Bind(wx.EVT_TEXT, self.OnInputColumnChanged)
  69. InputBoxSizer.Add(item = flexSizer)
  70. # 2. Kriging. In book pages one for each R package. Includes variogram fit.
  71. KrigingSizer = wx.StaticBoxSizer(wx.StaticBox(self, id = wx.ID_ANY, label = _("Kriging")), wx.HORIZONTAL)
  72. self.RPackagesBook = GNotebook(parent = self, style = globalvar.FNPageDStyle)
  73. for Rpackage in ["gstat"]: # , "geoR"]: #@TODO: enable it if/when it'll be implemented.
  74. self.CreatePage(package = Rpackage, Rinstance = Rinstance, controller = controller)
  75. ## Command output. From menuform module, cmdPanel class
  76. self._gconsole = gconsole.GConsole(guiparent = self)
  77. self.goutput = goutput.GConsoleWindow(parent = self, gconsole = self._gconsole, margin = False)
  78. self.goutputId = self.RPackagesBook.GetPageCount()
  79. self.outpage = self.RPackagesBook.AddPage(page = self.goutput, text = _("Command output"), name = 'output')
  80. self._gconsole.Bind(gconsole.EVT_CMD_RUN,
  81. lambda event:
  82. self._switchPageHandler(event = event, priority = 2))
  83. self._gconsole.Bind(gconsole.EVT_CMD_DONE,
  84. lambda event:
  85. self._switchPageHandler(event = event, priority = 3))
  86. self.RPackagesBook.SetSelection(0)
  87. KrigingSizer.Add(self.RPackagesBook, proportion = 1, flag = wx.EXPAND)
  88. # 3. Output Parameters.
  89. OutputSizer = wx.StaticBoxSizer(wx.StaticBox(self, id = wx.ID_ANY, label = _("Output")), wx.HORIZONTAL)
  90. OutputParameters = wx.GridBagSizer(hgap = 5, vgap = 5)
  91. OutputParameters.Add(item = wx.StaticText(self, id = wx.ID_ANY, label = _("Name for the output raster map:")),
  92. flag = wx.ALIGN_CENTER_VERTICAL,
  93. pos = (0, 0))
  94. self.OutputMapName = gselect.Select(parent = self, id = wx.ID_ANY,
  95. type = 'raster',
  96. mapsets = [grass.gisenv()['MAPSET']])
  97. OutputParameters.Add(item = self.OutputMapName, flag = wx.EXPAND | wx.ALL,
  98. pos = (0, 1))
  99. self.VarianceRasterCheckbox = wx.CheckBox(self, id = wx.ID_ANY, label = _("Export variance map as well: "))
  100. self.VarianceRasterCheckbox.SetValue(state = True)
  101. OutputParameters.Add(item = self.VarianceRasterCheckbox,
  102. flag = wx.ALIGN_CENTER_VERTICAL,
  103. pos = (1, 0))
  104. self.OutputVarianceMapName = gselect.Select(parent = self, id = wx.ID_ANY,
  105. type = 'raster',
  106. mapsets = [grass.gisenv()['MAPSET']])
  107. self.VarianceRasterCheckbox.Bind(wx.EVT_CHECKBOX, self.OnVarianceCBChecked)
  108. OutputParameters.Add(item = self.OutputVarianceMapName, flag = wx.EXPAND | wx.ALL,
  109. pos = (1, 1))
  110. self.OverwriteCheckBox = wx.CheckBox(self, id = wx.ID_ANY,
  111. label = _("Allow output files to overwrite existing files"))
  112. self.OverwriteCheckBox.SetValue(UserSettings.Get(group='cmd', key='overwrite', subkey='enabled'))
  113. OutputParameters.Add(item = self.OverwriteCheckBox,
  114. pos = (2, 0), span = (1, 2))
  115. OutputParameters.AddGrowableCol(1)
  116. OutputSizer.Add(OutputParameters, proportion = 0, flag = wx.EXPAND | wx.ALL, border = self.border)
  117. # 4. Run Button and Quit Button
  118. ButtonSizer = wx.BoxSizer(wx.HORIZONTAL)
  119. HelpButton = wx.Button(self, id = wx.ID_HELP)
  120. HelpButton.Bind(wx.EVT_BUTTON, self.OnHelpButton)
  121. QuitButton = wx.Button(self, id = wx.ID_EXIT)
  122. QuitButton.Bind(wx.EVT_BUTTON, self.OnCloseWindow)
  123. self.RunButton = wx.Button(self, id = wx.ID_ANY, label = _("&Run")) # no stock ID for Run button..
  124. self.RunButton.Bind(wx.EVT_BUTTON, self.OnRunButton)
  125. self.RunButton.Enable(False) # disable it on loading the interface, as input map is not set
  126. ButtonSizer.Add(HelpButton, proportion = 0, flag = wx.ALIGN_LEFT | wx.ALL, border = self.border)
  127. ButtonSizer.Add(QuitButton, proportion = 0, flag = wx.ALIGN_RIGHT | wx.ALL, border = self.border)
  128. ButtonSizer.Add(self.RunButton, proportion = 0, flag = wx.ALIGN_RIGHT | wx.ALL, border = self.border)
  129. # Main Sizer. Add each child sizer as soon as it is ready.
  130. Sizer = wx.BoxSizer(wx.VERTICAL)
  131. Sizer.Add(InputBoxSizer, proportion = 0, flag = wx.EXPAND | wx.ALL, border = self.border)
  132. Sizer.Add(KrigingSizer, proportion = 1, flag = wx.EXPAND | wx.ALL, border = self.border)
  133. Sizer.Add(OutputSizer, proportion = 0, flag = wx.EXPAND | wx.ALL, border = self.border)
  134. Sizer.Add(ButtonSizer, proportion = 0, flag = wx.ALIGN_RIGHT | wx.ALL, border = self.border)
  135. self.SetSizerAndFit(Sizer)
  136. # last action of __init__: update imput data list.
  137. # it's performed in the few seconds gap while user examines interface before clicking anything.
  138. #@TODO: implement a splashcreen IF the maps cause a noticeable lag [markus' suggestion]
  139. self.InputDataMap.GetElementList()
  140. def CreatePage(self, package, Rinstance, controller):
  141. """ Creates the three notebook pages, one for each R package """
  142. for package in ["gstat"]: #@TODO add here other packages when they will be implemented
  143. classobj = eval("RBook"+package+"Panel")
  144. setattr(self, "RBook"+package+"Panel", (classobj(self,
  145. id = wx.ID_ANY,
  146. Rinstance = Rinstance,
  147. controller = controller)))
  148. self.RPackagesBook.AddPage(page = getattr(self, "RBook"+package+"Panel"), text = package)
  149. def OnButtonRefresh(self, event):
  150. """ Forces refresh of list of available layers. """
  151. self.InputDataMap.GetElementList()
  152. def OnCloseWindow(self, event):
  153. """ Cancel button pressed"""
  154. self.parent.Close()
  155. event.Skip()
  156. def OnHelpButton(self, event):
  157. grass.run_command('g.manual', entry = 'v.krige')
  158. event.Skip()
  159. def OnInputMapChanged(self, event):
  160. """ Refreshes list of columns."""
  161. MapName = event.GetString()
  162. self.InputDataColumn.InsertColumns(vector = MapName,
  163. layer = 1, excludeKey = False,
  164. type = ['integer', 'double precision'])
  165. def OnInputColumnChanged(self, event):
  166. """Fills output map name TextCtrl """
  167. MapName = self.InputDataMap.GetValue()
  168. enable = bool(self.InputDataColumn.GetValue())
  169. self.RunButton.Enable(enable)
  170. self.RBookgstatPanel.PlotButton.Enable(enable)
  171. if enable:
  172. self.OutputMapName.SetValue(MapName.split("@")[0]+"_kriging")
  173. self.OutputVarianceMapName.SetValue(MapName.split("@")[0]+"_kriging.var")
  174. else:
  175. self.OutputMapName.SetValue('')
  176. self.OutputVarianceMapName.SetValue('')
  177. def OnRunButton(self,event):
  178. """ Execute R analysis. """
  179. #@FIXME: send data to main method instead of running it here.
  180. #-1: get the selected notebook page. The user shall know that [s]he can modify settings in all
  181. # pages, but only the selected one will be executed when Run is pressed.
  182. SelectedPanel = self.RPackagesBook.GetCurrentPage()
  183. if self.RPackagesBook.GetPageText(self.RPackagesBook.GetSelection()) == 'Command output':
  184. self._gconsole.WriteError("No parameters for running. Please select \"gstat\" tab, check parameters and re-run.")
  185. return False # no break invoked by above function
  186. # mount command string as it would have been written on CLI
  187. command = ["v.krige", "input=" + self.InputDataMap.GetValue(),
  188. "column=" + self.InputDataColumn.GetValue(),
  189. "output=" + self.OutputMapName.GetValue(),
  190. "package=" + '%s' % self.RPackagesBook.GetPageText(self.RPackagesBook.GetSelection())]
  191. if not hasattr(SelectedPanel, 'VariogramCheckBox') or not SelectedPanel.VariogramCheckBox.IsChecked():
  192. command.append("model=" + '%s' % SelectedPanel.ModelChoicebox.GetStringSelection().split(" ")[0])
  193. for i in ['Sill', 'Nugget', 'Range']:
  194. if getattr(SelectedPanel, i+"ChextBox").IsChecked():
  195. command.append(i.lower() + "=" + '%s' % getattr(SelectedPanel, i+'Ctrl').GetValue())
  196. if SelectedPanel.KrigingRadioBox.GetStringSelection() == "Block kriging":
  197. command.append("block=" + '%s' % SelectedPanel.BlockSpinBox.GetValue())
  198. if self.OverwriteCheckBox.IsChecked():
  199. command.append("--overwrite")
  200. if self.VarianceRasterCheckbox.IsChecked():
  201. command.append("output_var=" + self.OutputVarianceMapName.GetValue())
  202. # give it to the output console
  203. #@FIXME: it runs the command as a NEW instance. Reimports data, recalculates variogram fit..
  204. #otherwise I can use Controller() and mimic RunCmd behaviour.
  205. self._gconsole.RunCmd(command, switchPage = True)
  206. def OnVarianceCBChecked(self, event):
  207. self.OutputVarianceMapName.Enable(event.IsChecked())
  208. def _switchPageHandler(self, event, priority):
  209. self._switchPage(priority = priority)
  210. event.Skip()
  211. def _switchPage(self, priority):
  212. """!Manages @c 'output' notebook page according to priority."""
  213. if priority == 1:
  214. self.RPackagesBook.HighlightPageByName('output')
  215. if priority >= 2:
  216. self.RPackagesBook.SetSelectionByName('output')
  217. if priority >= 3:
  218. self.SetFocus()
  219. self.Raise()
  220. class KrigingModule(wx.Frame):
  221. """ Kriging module for GRASS GIS. Depends on R and its packages gstat and geoR. """
  222. def __init__(self, parent, Rinstance, controller, *args, **kwargs):
  223. wx.Frame.__init__(self, parent, *args, **kwargs)
  224. # setting properties and all widgettery
  225. self.SetTitle(_("Kriging Module"))
  226. self.SetIcon(wx.Icon(os.path.join(globalvar.ETCICONDIR, 'grass_dialog.ico'), wx.BITMAP_TYPE_ICO))
  227. self.log = Log(self)
  228. self.CreateStatusBar()
  229. self.log.message(_("Ready."))
  230. self.Panel = KrigingPanel(self, Rinstance, controller)
  231. self.SetMinSize(self.GetBestSize())
  232. self.SetSize(self.GetBestSize())
  233. class Log:
  234. """ The log output is redirected to the status bar of the containing frame. """
  235. def __init__(self, parent):
  236. self.parent = parent
  237. def message(self, text_string):
  238. """ Updates status bar """
  239. self.parent.SetStatusText(text_string.strip())
  240. class RBookPanel(wx.Panel):
  241. """ Generic notebook page with shared widgets and empty kriging functions. """
  242. def __init__(self, parent, *args, **kwargs):
  243. wx.Panel.__init__(self, parent, *args, **kwargs)
  244. self.parent = parent
  245. self.VariogramSizer = wx.StaticBoxSizer(wx.StaticBox(self,
  246. id = wx.ID_ANY,
  247. label = _("Variogram fitting")),
  248. wx.HORIZONTAL)
  249. self.LeftSizer = wx.BoxSizer(wx.VERTICAL)
  250. self.RightSizer = wx.BoxSizer(wx.VERTICAL)
  251. self.ParametersSizer = wx.GridBagSizer(vgap = 5, hgap = 5)
  252. self.VariogramSizer.Add(self.LeftSizer, proportion = 0, flag = wx.EXPAND | wx.ALL, border = parent.border)
  253. self.VariogramSizer.Add(self.RightSizer, proportion = 0, flag = wx.EXPAND | wx.ALL, border = parent.border)
  254. # left side of Variogram fitting. The checkboxes and spinctrls.
  255. self.PlotButton = wx.Button(self, id = wx.ID_ANY, label = _("Plot/refresh variogram")) # no stock ID for Run button..
  256. self.PlotButton.Bind(wx.EVT_BUTTON, self.OnPlotButton)
  257. self.PlotButton.Enable(False) # grey it out until a suitable layer is available
  258. self.LeftSizer.Add(self.PlotButton, proportion = 0, flag = wx.ALL, border = parent.border)
  259. self.LeftSizer.Add(self.ParametersSizer, proportion = 0, flag = wx.EXPAND | wx.ALL, border = parent.border)
  260. self.ParametersList = ["Sill", "Nugget", "Range"]
  261. MinValues = [0,0,1]
  262. for n in self.ParametersList:
  263. setattr(self, n+"ChextBox", wx.CheckBox(self,
  264. id = self.ParametersList.index(n),
  265. label = _(n + ":")))
  266. setattr(self, n+"Ctrl", (wx.SpinCtrl(self,
  267. id = wx.ID_ANY,
  268. min = MinValues[self.ParametersList.index(n)],
  269. max = maxint)))
  270. getattr(self, n+"ChextBox").Bind(wx.EVT_CHECKBOX,
  271. self.UseValue,
  272. id = self.ParametersList.index(n))
  273. setattr(self, n+"Sizer", (wx.BoxSizer(wx.HORIZONTAL)))
  274. self.ParametersSizer.Add(getattr(self, n+"ChextBox"),
  275. flag = wx.ALIGN_CENTER_VERTICAL,
  276. pos = (self.ParametersList.index(n),0))
  277. self.ParametersSizer.Add(getattr(self, n+"Ctrl"),
  278. flag = wx.EXPAND | wx.ALIGN_CENTER_VERTICAL,
  279. pos = (self.ParametersList.index(n),1))
  280. # right side of the Variogram fitting. The plot area.
  281. #Plot = wx.StaticText(self, id= wx.ID_ANY, label = "Check Plot Variogram to interactively fit model.")
  282. #PlotPanel = wx.Panel(self)
  283. #self.PlotArea = plot.PlotCanvas(PlotPanel)
  284. #self.PlotArea.SetInitialSize(size = (250,250))
  285. #self.RightSizer.Add(PlotPanel, proportion=0, flag= wx.EXPAND|wx.ALL, border=parent.border)
  286. self.KrigingSizer = wx.StaticBoxSizer(wx.StaticBox(self,
  287. id = wx.ID_ANY,
  288. label = _("Kriging techniques")),
  289. wx.VERTICAL)
  290. KrigingList = ["Ordinary kriging", "Block kriging"]#, "Universal kriging"] #@FIXME: i18n on the list?
  291. self.KrigingRadioBox = wx.RadioBox(self,
  292. id = wx.ID_ANY,
  293. choices = KrigingList,
  294. majorDimension = 1,
  295. style = wx.RA_SPECIFY_COLS)
  296. self.KrigingRadioBox.Bind(wx.EVT_RADIOBOX, self.HideBlockOptions)
  297. self.KrigingSizer.Add(self.KrigingRadioBox, proportion = 0, flag = wx.EXPAND | wx.ALL, border = parent.border)
  298. # block kriging parameters. Size.
  299. BlockSizer = wx.BoxSizer(wx.HORIZONTAL)
  300. BlockLabel = wx.StaticText(self, id = wx.ID_ANY, label = _("Block size:"))
  301. self.BlockSpinBox = wx.SpinCtrl(self, id = wx.ID_ANY, min = 1, max = maxint)
  302. self.BlockSpinBox.Enable(False) # default choice is Ordinary kriging so block param is disabled
  303. BlockSizer.Add(BlockLabel, flag = wx.ALIGN_CENTER_VERTICAL | wx.ALL, border = parent.border)
  304. BlockSizer.Add(self.BlockSpinBox, flag = wx.EXPAND | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border = parent.border)
  305. self.KrigingSizer.Add(BlockSizer, flag = wx.EXPAND | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border = parent.border)
  306. self.Sizer = wx.BoxSizer(wx.VERTICAL)
  307. self.Sizer.Add(self.VariogramSizer, proportion = 0, flag = wx.EXPAND | wx.ALL, border = parent.border)
  308. self.Sizer.Add(self.KrigingSizer, proportion = 0, flag = wx.EXPAND | wx.ALL, border = parent.border)
  309. def HideBlockOptions(self, event):
  310. self.BlockSpinBox.Enable(event.GetInt() == 1)
  311. def OnPlotButton(self,event):
  312. """ Plots variogram with current options. """
  313. pass
  314. def UseValue(self, event):
  315. """ Enables/Disables the SpinCtrl in respect of the checkbox. """
  316. n = self.ParametersList[event.GetId()]
  317. getattr(self, n+"Ctrl").Enable(event.IsChecked())
  318. class RBookgstatPanel(RBookPanel):
  319. """ Subclass of RBookPanel, with specific gstat options and kriging functions. """
  320. def __init__(self, parent, Rinstance, controller, *args, **kwargs):
  321. RBookPanel.__init__(self, parent, *args, **kwargs)
  322. # assigns Rinstance, that comes from the GUI call of v.krige.py.
  323. robjects = Rinstance
  324. self.controller = controller
  325. if robjects.r.require('automap')[0]:
  326. self.VariogramCheckBox = wx.CheckBox(self, id = wx.ID_ANY, label = _("Auto-fit variogram"))
  327. self.LeftSizer.Insert(0,
  328. self.VariogramCheckBox,
  329. proportion = 0,
  330. flag = wx.EXPAND | wx.ALIGN_CENTER_VERTICAL | wx.ALL,
  331. border = 4)
  332. self.SetSizerAndFit(self.Sizer)
  333. self.VariogramCheckBox.Bind(wx.EVT_CHECKBOX, self.HideOptions)
  334. self.VariogramCheckBox.SetValue(state = True) # check it by default
  335. ModelFactor = robjects.r.vgm().rx('long')
  336. ModelList = robjects.r.levels(ModelFactor[0])
  337. #@FIXME: no other way to let the Python pick it up..
  338. # and this is te wrong place where to load this list. should be at the very beginning.
  339. self.ModelChoicebox = wx.Choice(self, id = wx.ID_ANY, choices = ModelList)
  340. # disable model parameters' widgets by default
  341. for n in ["Sill", "Nugget", "Range"]:
  342. getattr(self, n+"Ctrl").Enable(False)
  343. self.ModelChoicebox.Enable(False)
  344. VariogramSubSizer = wx.BoxSizer(wx.HORIZONTAL)
  345. VariogramSubSizer.Add(item = wx.StaticText(self,
  346. id = wx.ID_ANY,
  347. label = _("Model: ")),
  348. flag = wx.ALIGN_CENTER_VERTICAL | wx.ALL,
  349. border = 4)
  350. VariogramSubSizer.Add(item = self.ModelChoicebox,
  351. flag = wx.ALIGN_CENTER_VERTICAL | wx.ALL,
  352. border = 4)
  353. self.LeftSizer.Insert(2, item = VariogramSubSizer)
  354. self.SetSizerAndFit(self.Sizer)
  355. def HideOptions(self, event):
  356. self.ModelChoicebox.Enable(not event.IsChecked())
  357. for n in ["Sill", "Nugget", "Range"]:
  358. if not event.IsChecked():
  359. getattr(self, n+"Ctrl").Enable(True)
  360. getattr(self, n+ "ChextBox").SetValue(True)
  361. getattr(self, n+ "ChextBox").Enable(False) # grey it out keeping it checked.. improvable
  362. else:
  363. getattr(self, n+"Ctrl").Enable(False)
  364. getattr(self, n+ "ChextBox").SetValue(False)
  365. getattr(self, n+ "ChextBox").Enable(True)
  366. #@FIXME: was for n in self.ParametersSizer.GetChildren(): n.Enable(False) but doesn't work
  367. def OnPlotButton(self,event):
  368. """ Plots variogram with current options. """
  369. ## BIG WARNING: smell of code duplication. Fix this asap. emminchia!
  370. #controller = Controller() # sed, if needed,
  371. #controller = self.controller
  372. map = self.parent.InputDataMap.GetValue()
  373. column = self.parent.InputDataColumn.GetValue()
  374. # import data or pick them up
  375. if self.controller.InputData is None:
  376. self.controller.InputData = self.controller.ImportMap(map = map,
  377. column = column)
  378. # fit the variogram or pick it up
  379. #~ Formula = self.controller.ComposeFormula(column = column,
  380. #~ isblock = self.KrigingRadioBox.GetStringSelection() == "Block kriging")
  381. if hasattr(self, 'VariogramCheckBox') and self.VariogramCheckBox.IsChecked():
  382. self.model = ''
  383. for each in ("Sill","Nugget","Range"):
  384. if getattr(self, each+'ChextBox').IsChecked():
  385. setattr(self, each.lower(), getattr(self, each+"Ctrl").GetValue())
  386. else:
  387. setattr(self, each.lower(), robjects.r('''NA'''))
  388. else:
  389. self.model = self.ModelChoicebox.GetStringSelection().split(" ")[0]
  390. for each in ("Sill","Nugget","Range"):
  391. if getattr(self, each+'ChextBox').IsChecked(): #@FIXME will be removed when chextboxes will be frozen
  392. setattr(self, each.lower(), getattr(self, each+"Ctrl").GetValue())
  393. isblock = self.KrigingRadioBox.GetStringSelection() == "Block kriging"
  394. if isblock is not '':
  395. self.predictor = 'x+y'
  396. else:
  397. self.predictor = '1'
  398. self.controller.Variogram = self.controller.FitVariogram(robjects.Formula(str(column) + "~" + self.predictor),
  399. self.controller.InputData,
  400. model = self.model,
  401. sill = self.sill,
  402. nugget = self.nugget,
  403. range = self.range)
  404. # use R plot function, in a separate window.
  405. thread.start_new_thread(self.plot, ())
  406. def plot(self):
  407. #robjects.r.X11()
  408. #robjects.r.png("variogram.png")
  409. textplot = robjects.r.plot(self.controller.Variogram['datavariogram'],
  410. self.controller.Variogram['variogrammodel'])
  411. print textplot
  412. self.refresh()
  413. #robjects.r['dev.off']()
  414. def refresh(self):
  415. while True:
  416. rinterface.process_revents()
  417. time.sleep(0.2)
  418. class RBookgeoRPanel(RBookPanel):
  419. """ Subclass of RBookPanel, with specific geoR options and kriging functions. """
  420. def __init__(self, parent, *args, **kwargs):
  421. RBookPanel.__init__(self, parent, *args, **kwargs)
  422. #@TODO: change these two lines as soon as geoR f(x)s are integrated.
  423. for n in self.GetChildren():
  424. n.Hide()
  425. self.Sizer.Add(wx.StaticText(self, id = wx.ID_ANY, label = _("Work in progress! No functionality provided.")))
  426. self.SetSizerAndFit(self.Sizer)