vkrige.py 25 KB

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