GRASS Programmer's Manual  6.4.2(2012)
vkrige.py
Go to the documentation of this file.
00001 """
00002 MODULE:    v_krige_wxGUI
00003 
00004 AUTHOR(S): Anne Ghisla <a.ghisla AT gmail.com>
00005 
00006 PURPOSE:   Dedicated GUI for v.krige script.
00007 
00008 DEPENDS:   R 2.x, packages gstat, maptools and spgrass6, optional: automap
00009 
00010 COPYRIGHT: (C) 2009 by the GRASS Development Team
00011 
00012 This program is free software under the GNU General Public
00013 License (>=v2). Read the file COPYING that comes with GRASS
00014 for details.
00015 """
00016 
00017 #@TODO move here imports related to wxGUI
00018 
00019 ### generic imports
00020 import os, sys
00021 from tempfile import gettempdir
00022 import time
00023 import thread
00024 ## i18N
00025 import gettext
00026 gettext.install('grasswxpy', os.path.join(os.getenv("GISBASE"), 'locale'), unicode = True)
00027 
00028 ### dependencies to be checked once, as they are quite time-consuming. cfr. grass.parser.
00029 # GRASS binding
00030 try:
00031     import grass.script as grass
00032 except ImportError:
00033     sys.exit(_("No GRASS-python library found."))
00034 ### wxGUI imports
00035 
00036 GUIModulesPath = os.path.join(os.getenv("GISBASE"), "etc", "wxpython", "gui_modules")
00037 sys.path.append(GUIModulesPath)
00038 
00039 import globalvar
00040 import gselect
00041 import goutput
00042 import menuform
00043 from preferences import globalSettings as UserSettings
00044 #import help
00045 
00046 import wx
00047 import wx.lib.flatnotebook as FN
00048 #import wx.lib.plot as plot # for plotting the variogram.
00049 
00050 # global variables
00051 maxint = 1e6 # instead of sys.maxint, not working with SpinCtrl on 64bit [reported by Bob Moskovitz]
00052 
00053 
00054 #@TODO move away functions not regarding the GUI
00055 
00056 class KrigingPanel(wx.Panel):
00057     """ Main panel. Contains all widgets except Menus and Statusbar. """
00058     def __init__(self, parent, Rinstance, controller, *args, **kwargs):
00059         wx.Panel.__init__(self, parent, *args, **kwargs)
00060         
00061         self.parent = parent 
00062         self.border = 4
00063         
00064         #    1. Input data 
00065         InputBoxSizer = wx.StaticBoxSizer(wx.StaticBox(self, id = wx.ID_ANY, label = _("Input Data")), 
00066                                           orient = wx.HORIZONTAL)
00067         
00068         flexSizer = wx.FlexGridSizer(cols = 3, hgap = 5, vgap = 5)
00069         flexSizer.AddGrowableCol(1)
00070 
00071         flexSizer.Add(item = wx.StaticText(self, id = wx.ID_ANY, label = _("Point dataset:")),
00072                       flag = wx.ALIGN_CENTER_VERTICAL)
00073         self.InputDataMap = gselect.VectorSelect(parent = self,
00074                                                  ftype = 'points',
00075                                                  updateOnPopup = False)
00076         self.InputDataMap.SetFocus()
00077         flexSizer.Add(item = self.InputDataMap, flag = wx.ALIGN_CENTER_VERTICAL)
00078         
00079         RefreshButton = wx.Button(self, id = wx.ID_REFRESH)
00080         RefreshButton.Bind(wx.EVT_BUTTON, self.OnButtonRefresh)
00081         flexSizer.Add(item = RefreshButton, flag = wx.ALIGN_CENTER_VERTICAL)
00082         
00083         flexSizer.Add(item = wx.StaticText(self, id = wx.ID_ANY, label = _("Numeric column:")),
00084                       flag = wx.ALIGN_CENTER_VERTICAL)
00085         self.InputDataColumn = gselect.ColumnSelect(self, id = wx.ID_ANY)
00086         self.InputDataColumn.SetSelection(0)
00087         flexSizer.Add(item = self.InputDataColumn)
00088         
00089         self.InputDataMap.GetChildren()[0].Bind(wx.EVT_TEXT, self.OnInputDataChanged)
00090         
00091         InputBoxSizer.Add(item = flexSizer)
00092         
00093         #    2. Kriging. In book pages one for each R package. Includes variogram fit.
00094         KrigingSizer = wx.StaticBoxSizer(wx.StaticBox(self, id = wx.ID_ANY, label = _("Kriging")), wx.HORIZONTAL)
00095 
00096         self.RPackagesBook = FN.FlatNotebook(parent = self, id = wx.ID_ANY,
00097                                         style = FN.FNB_BOTTOM |
00098                                         FN.FNB_NO_NAV_BUTTONS |
00099                                         FN.FNB_FANCY_TABS | FN.FNB_NO_X_BUTTON)
00100         
00101         for Rpackage in ["gstat"]: # , "geoR"]: #@TODO: enable it if/when it'll be implemented.
00102             self.CreatePage(package = Rpackage, Rinstance = Rinstance, controller = controller)
00103         
00104         ## Command output. From menuform module, cmdPanel class
00105         self.goutput = goutput.GMConsole(parent = self, margin = False,
00106                                          notebook = self.RPackagesBook)
00107         self.goutputId = self.RPackagesBook.GetPageCount()
00108         self.outpage = self.RPackagesBook.AddPage(self.goutput, text = _("Command output"))
00109         
00110         self.RPackagesBook.SetSelection(0)
00111         KrigingSizer.Add(self.RPackagesBook, proportion = 1, flag = wx.EXPAND)
00112         
00113         #    3. Output Parameters.
00114         OutputSizer = wx.StaticBoxSizer(wx.StaticBox(self, id = wx.ID_ANY, label = _("Output")), wx.HORIZONTAL)
00115         
00116         OutputParameters = wx.GridBagSizer(hgap = 5, vgap = 5)
00117         OutputParameters.AddGrowableCol(1)
00118         OutputParameters.Add(item = wx.StaticText(self, id = wx.ID_ANY, label = _("Name for the output raster map:")),
00119                              flag = wx.ALIGN_CENTER_VERTICAL,
00120                              pos = (0, 0))
00121         self.OutputMapName = gselect.Select(parent = self, id = wx.ID_ANY,
00122                                             type = 'raster',
00123                                             mapsets = [grass.gisenv()['MAPSET']])
00124         OutputParameters.Add(item = self.OutputMapName, flag = wx.EXPAND | wx.ALL,
00125                              pos = (0, 1))
00126         self.VarianceRasterCheckbox = wx.CheckBox(self, id = wx.ID_ANY, label = _("Export variance map as well: "))
00127         self.VarianceRasterCheckbox.SetValue(state = True)
00128         OutputParameters.Add(item = self.VarianceRasterCheckbox,
00129                              flag = wx.ALIGN_CENTER_VERTICAL,
00130                              pos = (1, 0))
00131         self.OutputVarianceMapName = gselect.Select(parent = self, id = wx.ID_ANY,
00132                                             type = 'raster',
00133                                             mapsets = [grass.gisenv()['MAPSET']])
00134         self.VarianceRasterCheckbox.Bind(wx.EVT_CHECKBOX, self.OnVarianceCBChecked)
00135         OutputParameters.Add(item = self.OutputVarianceMapName, flag = wx.EXPAND | wx.ALL,
00136                              pos = (1, 1))
00137         
00138         self.OverwriteCheckBox = wx.CheckBox(self, id = wx.ID_ANY,
00139                                              label = _("Allow output files to overwrite existing files"))
00140         self.OverwriteCheckBox.SetValue(UserSettings.Get(group='cmd', key='overwrite', subkey='enabled'))
00141         OutputParameters.Add(item = self.OverwriteCheckBox,
00142                              pos = (2, 0), span = (1, 2))
00143         
00144         OutputSizer.Add(OutputParameters, proportion = 0, flag = wx.EXPAND | wx.ALL, border = self.border)
00145         
00146         #    4. Run Button and Quit Button
00147         ButtonSizer = wx.BoxSizer(wx.HORIZONTAL)
00148         HelpButton = wx.Button(self, id = wx.ID_HELP)
00149         HelpButton.Bind(wx.EVT_BUTTON, self.OnHelpButton)
00150         QuitButton = wx.Button(self, id = wx.ID_EXIT)
00151         QuitButton.Bind(wx.EVT_BUTTON, self.OnCloseWindow)
00152         self.RunButton = wx.Button(self, id = wx.ID_ANY, label = _("&Run")) # no stock ID for Run button.. 
00153         self.RunButton.Bind(wx.EVT_BUTTON, self.OnRunButton)
00154         self.RunButton.Enable(False) # disable it on loading the interface, as input map is not set
00155         ButtonSizer.Add(HelpButton, proportion = 0, flag = wx.ALIGN_LEFT | wx.ALL, border = self.border)
00156         ButtonSizer.Add(QuitButton, proportion = 0, flag = wx.ALIGN_RIGHT | wx.ALL, border = self.border)
00157         ButtonSizer.Add(self.RunButton, proportion = 0, flag = wx.ALIGN_RIGHT | wx.ALL, border = self.border)
00158         
00159         #    Main Sizer. Add each child sizer as soon as it is ready.
00160         Sizer = wx.BoxSizer(wx.VERTICAL)
00161         Sizer.Add(InputBoxSizer, proportion = 0, flag = wx.EXPAND | wx.ALL, border = self.border)
00162         Sizer.Add(KrigingSizer, proportion = 1, flag = wx.EXPAND | wx.ALL, border = self.border)
00163         Sizer.Add(OutputSizer, proportion = 0, flag = wx.EXPAND | wx.ALL, border = self.border)
00164         Sizer.Add(ButtonSizer, proportion = 0, flag = wx.ALIGN_RIGHT | wx.ALL, border = self.border)
00165         self.SetSizerAndFit(Sizer)
00166         
00167         # last action of __init__: update imput data list.
00168         # it's performed in the few seconds gap while user examines interface before clicking anything.
00169         #@TODO: implement a splashcreen IF the maps cause a noticeable lag [markus' suggestion]
00170         self.InputDataMap.GetElementList()
00171         
00172     def CreatePage(self, package, Rinstance, controller):
00173         """ Creates the three notebook pages, one for each R package """
00174         for package in ["gstat"]: 
00175             classobj = eval("RBook"+package+"Panel")
00176             setattr(self, "RBook"+package+"Panel", (classobj(self,
00177                                                              id = wx.ID_ANY,
00178                                                              Rinstance = Rinstance,
00179                                                              controller = controller)))
00180             self.RPackagesBook.AddPage(page = getattr(self, "RBook"+package+"Panel"), text = package)
00181 
00182     def OnButtonRefresh(self, event):
00183         """ Forces refresh of list of available layers. """
00184         self.InputDataMap.GetElementList()
00185 
00186     def OnCloseWindow(self, event):
00187         """ Cancel button pressed"""
00188         self.parent.Close()
00189         event.Skip()
00190 
00191     def OnHelpButton(self, event):
00192         # file = os.path.join(os.getenv("GISBASE"), "docs", "html", "v.krige.html")
00193         # file = os.path.join(os.path.curdir, "description.html")
00194         # @TODO fix HelpWindow
00195         # helpFrame = help.HelpWindow(parent=self, id=wx.ID_ANY,
00196         #                            title=_("GRASS - Help page for v.krige"),
00197         #                            size=(640, 480),
00198         #                            file=file)
00199         # helpFrame.Show(True)
00200 
00201         grass.run_command('g.manual', entry = 'v.krige')
00202         
00203         event.Skip()
00204 
00205     def OnInputDataChanged(self, event):
00206         """ Refreshes list of columns and fills output map name TextCtrl """
00207         MapName = event.GetString()
00208         self.InputDataColumn.InsertColumns(vector = MapName,
00209                                    layer = 1, excludeKey = True,
00210                                    type = ['integer', 'double precision'])
00211         self.InputDataColumn.SetSelection(0)
00212         self.RunButton.Enable(self.InputDataColumn.GetSelection() is not -1)
00213         self.RBookgstatPanel.PlotButton.Enable(self.InputDataColumn.GetSelection() is not -1)
00214         
00215         if self.InputDataColumn.GetSelection() is not -1:
00216             self.OutputMapName.SetValue(MapName.split("@")[0]+"_kriging")
00217             self.OutputVarianceMapName.SetValue(MapName.split("@")[0]+"_kriging_var")
00218         else:
00219             self.OutputMapName.SetValue('')
00220             self.OutputVarianceMapName.SetValue('')
00221         
00222     def OnRunButton(self,event):
00223         """ Execute R analysis. """
00224         #@FIXME: send data to main method instead of running it here.
00225         
00226         #-1: get the selected notebook page. The user shall know that [s]he can modify settings in all
00227         # pages, but only the selected one will be executed when Run is pressed.
00228         SelectedPanel = self.RPackagesBook.GetCurrentPage()
00229         
00230         if self.RPackagesBook.GetPageText(self.RPackagesBook.GetSelection()) == 'Command output':
00231             self.goutput.WriteError("No parameters for running. Please select \"gstat\" tab, check parameters and re-run.")
00232             return False # no break invoked by above function
00233         
00234         # mount command string as it would have been written on CLI
00235         command = ["v.krige", "input=" + self.InputDataMap.GetValue(),
00236                    "column=" + self.InputDataColumn.GetValue(),
00237                    "output=" + self.OutputMapName.GetValue(), 
00238                    "package=" + '%s' % self.RPackagesBook.GetPageText(self.RPackagesBook.GetSelection())]
00239         
00240         if not hasattr(SelectedPanel, 'VariogramCheckBox') or not SelectedPanel.VariogramCheckBox.IsChecked():
00241             command.append("model=" + '%s' % SelectedPanel.ModelChoicebox.GetStringSelection().split(" ")[0])
00242             
00243         for i in ['Sill', 'Nugget', 'Range']:
00244             if getattr(SelectedPanel, i+"ChextBox").IsChecked():
00245                 command.append(i.lower() + "=" + '%s' % getattr(SelectedPanel, i+'Ctrl').GetValue())
00246         
00247         if SelectedPanel.KrigingRadioBox.GetStringSelection() == "Block kriging":
00248             command.append("block=" + '%s' % SelectedPanel.BlockSpinBox.GetValue())
00249         if self.OverwriteCheckBox.IsChecked():
00250             command.append("--overwrite")
00251         if self.VarianceRasterCheckbox.IsChecked():
00252             command.append("output_var=" + self.OutputVarianceMapName.GetValue())
00253         
00254         # give it to the output console
00255         #@FIXME: it runs the command as a NEW instance. Reimports data, recalculates variogram fit..
00256         #otherwise I can use Controller() and mimic RunCmd behaviour.
00257         self.goutput.RunCmd(command, switchPage = True)
00258     
00259     def OnVarianceCBChecked(self, event):
00260         self.OutputVarianceMapName.Enable(event.IsChecked())
00261 
00262 class KrigingModule(wx.Frame):
00263     """ Kriging module for GRASS GIS. Depends on R and its packages gstat and geoR. """
00264     def __init__(self, parent, Rinstance, controller, *args, **kwargs):
00265         wx.Frame.__init__(self, parent, *args, **kwargs)
00266         # setting properties and all widgettery
00267         self.SetTitle(_("Kriging Module"))
00268         self.SetIcon(wx.Icon(os.path.join(globalvar.ETCICONDIR, 'grass_dialog.ico'), wx.BITMAP_TYPE_ICO))
00269         self.log = Log(self) 
00270         self.CreateStatusBar()
00271         self.log.message(_("Ready."))
00272         
00273         self.Panel = KrigingPanel(self, Rinstance, controller)
00274         self.SetMinSize(self.GetBestSize())
00275         self.SetSize(self.GetBestSize())
00276     
00277 class Log:
00278     """ The log output is redirected to the status bar of the containing frame. """
00279     def __init__(self, parent):
00280         self.parent = parent
00281 
00282     def message(self, text_string):
00283         """ Updates status bar """
00284         self.parent.SetStatusText(text_string.strip())
00285 
00286 class RBookPanel(wx.Panel):
00287     """ Generic notebook page with shared widgets and empty kriging functions. """
00288     def __init__(self, parent, *args, **kwargs):
00289         wx.Panel.__init__(self, parent, *args, **kwargs)
00290         
00291         self.parent = parent
00292         
00293         self.VariogramSizer = wx.StaticBoxSizer(wx.StaticBox(self,
00294                                                              id = wx.ID_ANY, 
00295                                                              label = _("Variogram fitting")),
00296                                                 wx.HORIZONTAL)
00297         self.LeftSizer = wx.BoxSizer(wx.VERTICAL)
00298         self.RightSizer = wx.BoxSizer(wx.VERTICAL)
00299         self.ParametersSizer = wx.GridBagSizer(vgap = 5, hgap = 5)
00300 
00301         self.VariogramSizer.Add(self.LeftSizer, proportion = 0, flag = wx.EXPAND | wx.ALL, border = parent.border)
00302         self.VariogramSizer.Add(self.RightSizer, proportion = 0, flag = wx.EXPAND | wx.ALL, border = parent.border)
00303         
00304         # left side of Variogram fitting. The checkboxes and spinctrls.
00305         self.PlotButton = wx.Button(self, id = wx.ID_ANY, label = _("Plot/refresh variogram")) # no stock ID for Run button.. 
00306         self.PlotButton.Bind(wx.EVT_BUTTON, self.OnPlotButton)
00307         self.PlotButton.Enable(False) # grey it out until a suitable layer is available
00308         self.LeftSizer.Add(self.PlotButton, proportion = 0, flag =  wx.ALL, border = parent.border)
00309         self.LeftSizer.Add(self.ParametersSizer, proportion = 0, flag = wx.EXPAND | wx.ALL, border = parent.border)
00310         
00311         self.ParametersList = ["Sill", "Nugget", "Range"]
00312         MinValues = [0,0,1]
00313         for n in self.ParametersList:
00314             setattr(self, n+"ChextBox", wx.CheckBox(self,
00315                                                     id = self.ParametersList.index(n),
00316                                                     label = _(n + ":")))
00317             setattr(self, n+"Ctrl", (wx.SpinCtrl(self,
00318                                                  id = wx.ID_ANY,
00319                                                  min = MinValues[self.ParametersList.index(n)],
00320                                                  max = maxint)))
00321             getattr(self, n+"ChextBox").Bind(wx.EVT_CHECKBOX,
00322                                              self.UseValue,
00323                                              id = self.ParametersList.index(n))
00324             setattr(self, n+"Sizer", (wx.BoxSizer(wx.HORIZONTAL)))
00325             self.ParametersSizer.Add(getattr(self, n+"ChextBox"),
00326                                      flag = wx.ALIGN_CENTER_VERTICAL,
00327                                      pos = (self.ParametersList.index(n),0))
00328             self.ParametersSizer.Add(getattr(self, n+"Ctrl"),
00329                                      flag = wx.EXPAND | wx.ALIGN_CENTER_VERTICAL,
00330                                      pos = (self.ParametersList.index(n),1))
00331         
00332         # right side of the Variogram fitting. The plot area.
00333         #Plot = wx.StaticText(self, id= wx.ID_ANY, label = "Check Plot Variogram to interactively fit model.")
00334         #PlotPanel = wx.Panel(self)
00335         #self.PlotArea = plot.PlotCanvas(PlotPanel)
00336         #self.PlotArea.SetInitialSize(size = (250,250))
00337         #self.RightSizer.Add(PlotPanel, proportion=0, flag= wx.EXPAND|wx.ALL, border=parent.border)
00338         
00339         self.KrigingSizer = wx.StaticBoxSizer(wx.StaticBox(self,
00340                                                              id = wx.ID_ANY,
00341                                                              label = _("Kriging techniques")),
00342                                                 wx.VERTICAL)
00343         
00344         KrigingList = ["Ordinary kriging", "Block kriging"]#, "Universal kriging"] #@FIXME: i18n on the list?
00345         self.KrigingRadioBox = wx.RadioBox(self,
00346                                            id = wx.ID_ANY,
00347                                            choices = KrigingList,
00348                                            majorDimension = 1,
00349                                            style = wx.RA_SPECIFY_COLS)
00350         self.KrigingRadioBox.Bind(wx.EVT_RADIOBOX, self.HideBlockOptions)
00351         self.KrigingSizer.Add(self.KrigingRadioBox, proportion = 0, flag = wx.EXPAND | wx.ALL, border = parent.border)
00352         
00353         # block kriging parameters. Size.
00354         BlockSizer = wx.BoxSizer(wx.HORIZONTAL)
00355         BlockLabel = wx.StaticText(self, id = wx.ID_ANY, label = _("Block size:"))
00356         self.BlockSpinBox = wx.SpinCtrl(self, id = wx.ID_ANY, min = 1, max = maxint)
00357         self.BlockSpinBox.Enable(False) # default choice is Ordinary kriging so block param is disabled
00358         BlockSizer.Add(BlockLabel, flag = wx.ALIGN_CENTER_VERTICAL | wx.ALL, border = parent.border)
00359         BlockSizer.Add(self.BlockSpinBox, flag = wx.EXPAND | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border = parent.border)
00360         self.KrigingSizer.Add(BlockSizer, flag = wx.EXPAND | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border = parent.border)
00361         
00362         self.Sizer = wx.BoxSizer(wx.VERTICAL)
00363         self.Sizer.Add(self.VariogramSizer, proportion = 0, flag = wx.EXPAND | wx.ALL, border = parent.border)
00364         self.Sizer.Add(self.KrigingSizer,  proportion = 0, flag = wx.EXPAND | wx.ALL, border = parent.border)
00365         
00366     def HideBlockOptions(self, event):
00367         self.BlockSpinBox.Enable(event.GetInt() == 1)
00368     
00369     def OnPlotButton(self,event):
00370         """ Plots variogram with current options. """
00371         pass
00372     
00373     def UseValue(self, event):
00374         """ Enables/Disables the SpinCtrl in respect of the checkbox. """
00375         n = self.ParametersList[event.GetId()]
00376         getattr(self, n+"Ctrl").Enable(event.IsChecked())
00377 
00378 class RBookgstatPanel(RBookPanel):
00379     """ Subclass of RBookPanel, with specific gstat options and kriging functions. """
00380     def __init__(self, parent, Rinstance, controller, *args, **kwargs):
00381         RBookPanel.__init__(self, parent, *args, **kwargs)
00382         
00383         # assigns Rinstance, that comes from the GUI call of v.krige.py.
00384         robjects = Rinstance
00385         self.controller = controller
00386         
00387         if robjects.r.require('automap')[0]:
00388             self.VariogramCheckBox = wx.CheckBox(self, id = wx.ID_ANY, label = _("Auto-fit variogram"))
00389             self.LeftSizer.Insert(0,
00390                                   self.VariogramCheckBox,
00391                                   proportion = 0,
00392                                   flag = wx.EXPAND | wx.ALIGN_CENTER_VERTICAL | wx.ALL,
00393                                   border = 4)
00394             self.SetSizerAndFit(self.Sizer)
00395             self.VariogramCheckBox.Bind(wx.EVT_CHECKBOX, self.HideOptions)
00396             self.VariogramCheckBox.SetValue(state = True) # check it by default
00397 
00398         ModelFactor = robjects.r.vgm().rx('long')
00399         ModelList = robjects.r.levels(ModelFactor[0])
00400         #@FIXME: no other way to let the Python pick it up..
00401         # and this is te wrong place where to load this list. should be at the very beginning.
00402         self.ModelChoicebox = wx.Choice(self, id = wx.ID_ANY, choices = ModelList)
00403         
00404         # disable model parameters' widgets by default
00405         for n in ["Sill", "Nugget", "Range"]:
00406             getattr(self, n+"Ctrl").Enable(False)
00407         self.ModelChoicebox.Enable(False)
00408         
00409         VariogramSubSizer = wx.BoxSizer(wx.HORIZONTAL)
00410         VariogramSubSizer.Add(item = wx.StaticText(self,
00411                                                  id =  wx.ID_ANY,
00412                                                  label = _("Model: ")),
00413                               flag = wx.ALIGN_CENTER_VERTICAL | wx.ALL,
00414                               border = 4)
00415         VariogramSubSizer.Add(item = self.ModelChoicebox,
00416                               flag = wx.ALIGN_CENTER_VERTICAL | wx.ALL,
00417                               border = 4)
00418         
00419         self.LeftSizer.Insert(2, item = VariogramSubSizer)
00420         
00421         self.SetSizerAndFit(self.Sizer)
00422     
00423     def HideOptions(self, event):
00424         self.ModelChoicebox.Enable(not event.IsChecked())
00425         for n in ["Sill", "Nugget", "Range"]:
00426             if not event.IsChecked():
00427                 getattr(self, n+"Ctrl").Enable(True)
00428                 getattr(self, n+ "ChextBox").SetValue(True)
00429                 getattr(self, n+ "ChextBox").Enable(False) # grey it out keeping it checked.. improvable
00430             else:
00431                 getattr(self, n+"Ctrl").Enable(False)
00432                 getattr(self, n+ "ChextBox").SetValue(False)
00433                 getattr(self, n+ "ChextBox").Enable(True)
00434         #@FIXME: was for n in self.ParametersSizer.GetChildren(): n.Enable(False) but doesn't work
00435         
00436     def OnPlotButton(self,event):
00437         """ Plots variogram with current options. """
00438         ## BIG WARNING: smell of code duplication. Fix this asap. emminchia!
00439         #controller = Controller() # sed, if needed,
00440         #controller = self.controller
00441         map = self.parent.InputDataMap.GetValue()
00442         column = self.parent.InputDataColumn.GetValue()
00443         
00444         # import data or pick them up
00445         if globals()["InputData"] is None:
00446             globals()["InputData"] = controller.ImportMap(map = map,
00447                                                           column = column)
00448         # fit the variogram or pick it up
00449         Formula = controller.ComposeFormula(column = column,
00450                                             isblock = self.KrigingRadioBox.GetStringSelection() == "Block kriging",
00451                                             inputdata = globals()['InputData'])
00452         #if globals()["Variogram"] is None:
00453         if hasattr(self, 'VariogramCheckBox') and self.VariogramCheckBox.IsChecked():
00454             self.model = ''
00455             for each in ("Sill","Nugget","Range"):
00456                 if getattr(self, each+'ChextBox').IsChecked():
00457                     setattr(self, each.lower(), getattr(self, each+"Ctrl").GetValue())
00458                 else:
00459                     setattr(self, each.lower(), robjects.r('''NA'''))
00460         else:
00461             self.model = self.ModelChoicebox.GetStringSelection().split(" ")[0]
00462             for each in ("Sill","Nugget","Range"):
00463                 if getattr(self, each+'ChextBox').IsChecked(): #@FIXME will be removed when chextboxes will be frozen
00464                     setattr(self, each.lower(), getattr(self, each+"Ctrl").GetValue())
00465             
00466         globals()["Variogram"] = controller.FitVariogram(Formula,
00467                                                          InputData,
00468                                                          model = self.model,
00469                                                          sill = self.sill,
00470                                                          nugget = self.nugget,
00471                                                          range = self.range)
00472         
00473         # use R plot function, in a separate window.
00474         thread.start_new_thread(self.plot, ())
00475         
00476     def plot(self):
00477         #robjects.r.X11()
00478         #robjects.r.png("variogram.png")
00479         textplot = robjects.r.plot(Variogram['datavariogram'], Variogram['variogrammodel'])
00480         print textplot
00481         self.refresh()
00482         #robjects.r['dev.off']()
00483 
00484     def refresh(self):
00485         while True:
00486             rinterface.process_revents()
00487             time.sleep(0.1)
00488         
00489 class RBookgeoRPanel(RBookPanel):
00490     """ Subclass of RBookPanel, with specific geoR options and kriging functions. """
00491     def __init__(self, parent, *args, **kwargs):
00492         RBookPanel.__init__(self, parent, *args, **kwargs)
00493         #@TODO: change these two lines as soon as geoR f(x)s are integrated.
00494         for n in self.GetChildren():
00495             n.Hide()
00496         self.Sizer.Add(wx.StaticText(self, id = wx.ID_ANY, label = _("Work in progress! No functionality provided.")))
00497         self.SetSizerAndFit(self.Sizer)
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Defines