vkrige.py 25 KB

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