vkrige.py 26 KB

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