v_krige_wxGUI.py 25 KB

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