[GRASS-SVN] r63677 - grass/branches/releasebranch_7_0/gui/wxpython/rlisetup

svn_grass at osgeo.org svn_grass at osgeo.org
Mon Dec 22 10:15:34 PST 2014


Author: lucadelu
Date: 2014-12-22 10:15:34 -0800 (Mon, 22 Dec 2014)
New Revision: 63677

Modified:
   grass/branches/releasebranch_7_0/gui/wxpython/rlisetup/functions.py
   grass/branches/releasebranch_7_0/gui/wxpython/rlisetup/wizard.py
Log:
g.gui.rlisetup: backports from trunk

Modified: grass/branches/releasebranch_7_0/gui/wxpython/rlisetup/functions.py
===================================================================
--- grass/branches/releasebranch_7_0/gui/wxpython/rlisetup/functions.py	2014-12-22 18:00:07 UTC (rev 63676)
+++ grass/branches/releasebranch_7_0/gui/wxpython/rlisetup/functions.py	2014-12-22 18:15:34 UTC (rev 63677)
@@ -78,28 +78,47 @@
         return False
 
 
-def convertFeature(vect, outrast, cat, origrast):
+def convertFeature(vect, outrast, cat, origrast, layer='1', overwrite=False):
     """Convert a single feature to a raster"""
     tmp_vect = "tmp_{rast}".format(rast=outrast)
-    grass.run_command('v.extract', input=vect, output=tmp_vect, cats=cat,
-                      overwrite=True, quiet=True)
-    grass.run_command('g.region', vector=tmp_vect, align=origrast)
-    grass.run_command('v.to.rast', input=vect, output=outrast, use='cat',
-                      cats=cat, overwrite=True, quiet=True)
+    grass.run_command('v.extract', input=vect, cats=cat, type='area',
+                      layer=layer, output=tmp_vect, flags='d',
+                      overwrite=overwrite, quiet=True)
+    grass.run_command('g.region', rastor=origrast)
+    grass.run_command('g.region', vector=tmp_vect)
+    grass.run_command('g.region', align=origrast)
+    grass.run_command('v.to.rast', input=tmp_vect, type='area',
+                      layer=layer, use='val', value=cat, output=outrast,
+                      overwrite=overwrite, quiet=True)
     grass.run_command('g.remove', flags='f', type='vector',
                       name=tmp_vect, quiet=True)
 
+
+def obtainCategories(vector, layer='1'):
+    """This function returns a list of categories for all areas in
+    the given layer"""
+    vect_cats = []
+    vc = grass.read_command('v.category', input=vector, layer=layer,
+                            option='print', type='centroid')
+    for lc in vc.splitlines():
+        for cat in lc.split('/'):
+            vect_cats.append(int(cat))
+
+    return sorted(set(vect_cats))
+
+
 def obtainAreaVector(outrast):
     """Create the string for configuration file"""
     reg = grass.region()
     return "MASKEDOVERLAYAREA {name}|{n}|{s}|{e}|{w}\n".format(name=outrast,
-                                                             n=reg['n'],
-                                                             s=reg['s'],
-                                                             e=reg['e'],
-                                                             w=reg['w'])
+                                                               n=reg['n'],
+                                                               s=reg['s'],
+                                                               e=reg['e'],
+                                                               w=reg['w'])
 
 
-def sampleAreaVector(vect, rast, vect_cats, progDialog=None):
+def sampleAreaVector(vect, rast, vect_cats, layer='1', overwrite=False,
+                     progDialog=None):
     """Create the strings to add to the configuration file using vector"""
     areanum = len(vect_cats)
     output = []
@@ -108,9 +127,21 @@
         GError(message=_("The polygon seems to have 0 areas"))
         return None
     for n in range(areanum):
-        cat = vect_cats[n]
-        rast_name = "{name}_{cat}".format(name=vect.split('@')[0], cat=cat)
-        convertFeature(vect, rast_name, cat, rast)
+        cat = str(vect_cats[n])
+        outpref = "{rast}_{vect}_".format(vect=vect.split('@')[0],
+                                          rast=rast.split('@')[0])
+        rast_name = "{pref}{cat}".format(pref=outpref, cat=cat)
+        # check if raster already axist
+
+        if len(grass.list_strings('raster', pattern=rast_name, mapset='.')) == 1 \
+           and not overwrite:
+            GError(message=_("The raster map <%s> already exists."
+                             " Please remove or rename the maps "
+                             "with the prefix '%s' or select the "
+                             "option to overwrite existing maps"
+                             % (rast_name, outpref)))
+            return None
+        convertFeature(vect, rast_name, cat, rast, layer, overwrite)
         output.append(obtainAreaVector(rast_name))
         if progDialog:
             progDialog.Update(n)

Modified: grass/branches/releasebranch_7_0/gui/wxpython/rlisetup/wizard.py
===================================================================
--- grass/branches/releasebranch_7_0/gui/wxpython/rlisetup/wizard.py	2014-12-22 18:00:07 UTC (rev 63676)
+++ grass/branches/releasebranch_7_0/gui/wxpython/rlisetup/wizard.py	2014-12-22 18:15:34 UTC (rev 63677)
@@ -33,7 +33,11 @@
 from rlisetup.sampling_frame import RLiSetupMapPanel
 from grass.script import core as grass
 from grass.script import raster as grast
-from functions import SamplingType, sampleAreaVector, convertFeature, obtainAreaVector
+from grass.script import vector as gvect
+from grass.exceptions import CalledModuleError
+
+from functions import SamplingType, sampleAreaVector, convertFeature
+from functions import obtainAreaVector, obtainCategories
 from core.gcmd import GError, GMessage, RunCommand
 
 
@@ -194,21 +198,21 @@
             self.SF_W = newreg['w']  # set env(SF_W) $w
 
             self.SF_Y = abs(round(self.gregion['n'] - newreg['n']) / newreg['nsres'])
-#		 set env(SF_Y) [expr abs(round(($s_n - $n) / $nres)) ]
+#         set env(SF_Y) [expr abs(round(($s_n - $n) / $nres)) ]
             self.SF_X = abs(round(self.gregion['w'] - newreg['w']) / newreg['ewres'])
-#		 set env(SF_X) [expr abs(round(($s_w - $w) / $sres)) ]
+#         set env(SF_X) [expr abs(round(($s_w - $w) / $sres)) ]
             self.SF_RL = abs(round(newreg['n'] - newreg['s']) / newreg['nsres'])
-#		 set env(SF_RL) [expr abs(round(($n - $s) / $nres)) ]
+#         set env(SF_RL) [expr abs(round(($n - $s) / $nres)) ]
             self.SF_CL = abs(round(newreg['e'] - newreg['w']) / newreg['ewres'])
-#		 set env(SF_CL) [expr abs(round(($e - $w) / $sres)) ]
+#         set env(SF_CL) [expr abs(round(($e - $w) / $sres)) ]
             self.per_x = float(self.SF_X) / float(self.rasterinfo['cols'])
-#		 double($env(SF_X)) / double($cols)
+#         double($env(SF_X)) / double($cols)
             self.per_y = float(self.SF_Y) / float(self.rasterinfo['rows'])
-#	       double($env(SF_Y)) / double($rows)
+#           double($env(SF_Y)) / double($rows)
             self.per_rl = float(self.SF_RL) / float(self.rasterinfo['rows'])
-#		 double($env(SF_RL)) / double($rows)
+#         double($env(SF_RL)) / double($rows)
             self.per_cl = float(self.SF_CL) / float(self.rasterinfo['cols'])
-#		 double($env(SF_CL)) / double($cols)
+#         double($env(SF_CL)) / double($cols)
             fil.write("SAMPLINGFRAME %r|%r|%r|%r\n" % (self.per_x, self.per_y,
                                                        self.per_rl, self.per_cl))
 
@@ -428,6 +432,7 @@
         self.rast = ''
         self.conf_name = ''
         self.vect = ''
+        self.VectorEnabled = True
 
         self.parent = parent
 
@@ -463,6 +468,15 @@
                        flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL)
         self.sizer.Add(item=self.vectselect, border=5, pos=(2, 1),
                        flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL)
+        #vector layer
+        self.vectlaylabel = wx.StaticText(parent=self, id=wx.ID_ANY,
+                                          label=_('Vector map layer to use to select areas'))
+        self.vectlayer = wx.ComboBox(parent = self, id = wx.ID_ANY,
+                                     size=(250, -1))
+        self.sizer.Add(item=self.vectlaylabel, border=5, pos=(3, 0),
+                       flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL)
+        self.sizer.Add(item=self.vectlayer, border=5, pos=(3, 1),
+                       flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL)
         #define sampling region
         self.sampling_reg = wx.RadioBox(parent=self, id=wx.ID_ANY,
                                         label=" %s " % _("Define sampling "
@@ -475,13 +489,20 @@
 
         self.sizer.Add(item=self.sampling_reg,
                        flag=wx.ALIGN_CENTER | wx.ALL | wx.EXPAND, border=5,
-                       pos=(4, 0), span=(1, 2))
+                       pos=(5, 0), span=(1, 2))
+        self.infoError = wx.StaticText(self, label='')
+        self.infoError.SetForegroundColour(wx.RED)
+        self.sizer.Add(item=self.infoError,
+                       flag=wx.ALIGN_CENTER | wx.ALL | wx.EXPAND, border=5,
+                       pos=(6, 0), span=(1, 2))
+
         #bindings
         self.sampling_reg.Bind(wx.EVT_RADIOBOX, self.OnSampling)
         self.newconftxt.Bind(wx.EVT_KILL_FOCUS, self.OnName)
         self.newconftxt.Bind(wx.EVT_TEXT, self.OnNameChanged)
         self.vectselect.Bind(wx.EVT_TEXT, self.OnVector)
         self.mapselect.Bind(wx.EVT_TEXT, self.OnRast)
+        self.vectlayer.Bind(wx.EVT_TEXT, self.OnLayer)
         self.Bind(wiz.EVT_WIZARD_PAGE_CHANGED, self.OnEnterPage)
         self.Bind(wiz.EVT_WIZARD_PAGE_CHANGING, self.OnExitPage)
 
@@ -515,16 +536,41 @@
 
     def OnRast(self, event):
         """Sets raster map"""
-        self.rast = event.GetString()
+        self.rast = self.mapselect.GetValue()
         next = wx.FindWindowById(wx.ID_FORWARD)
         next.Enable(self.CheckInput())
 
     def OnVector(self, event):
         """Sets vector map"""
-        self.vect = event.GetString()
+        self.vect = self.vectselect.GetValue()
+        if self.vect:
+            self.VectorEnabled, layers = self.CheckVector(self.vect)
+            if self.VectorEnabled:
+                self.vectlayer.SetItems(layers)
+                self.vectlayer.SetSelection(0)
+                self.vectorlayer = self.vectlayer.GetValue()
+                self.infoError.SetLabel('')
+            else:
+                self.vectlayer.Clear()
+                self.vectlayer.SetValue('')
+                self.vect = ''
+        else:
+            self.infoError.SetLabel('')
+            self.vectlayer.Clear()
+            self.vectlayer.SetValue('')
+
         next = wx.FindWindowById(wx.ID_FORWARD)
         next.Enable(self.CheckInput())
 
+
+    def OnLayer(self, event):
+        try:
+            self.vectorlayer = self.vectlayer.GetValue()
+        except:
+            self.vectorlayer = None
+        next = wx.FindWindowById(wx.ID_FORWARD)
+        next.Enable(self.CheckInput())
+
     def OnEnterPage(self, event):
         """Sets the default values, for the entire map
         """
@@ -533,14 +579,40 @@
         wx.CallAfter(wx.FindWindowById(wx.ID_FORWARD).Enable,
                      self.CheckInput())
 
+    def CheckVector(self, vector):
+        """Check if the type of vector is area and return the number of
+        vector's layer"""
+        try:
+            areas = gvect.vector_info_topo(vector)['areas']
+        except CalledModuleError:
+            self.infoError.SetLabel(_("Vector %s was not found, please "
+                                    "select another vector") % vector)
+            return False, []
+        if areas == 0:
+            self.infoError.SetLabel(_("Vector %s has no areas, please "
+                                    "select another vector") % vector)
+            return False, []
+        links = gvect.vector_info(vector)['num_dblinks']
+        if links == 0:
+            self.infoError.SetLabel(_("Vector %s has no table connected, "
+                                    "please select another vector") % vector)
+            return False, []
+        elif links > 0:
+            layers = []
+            for i in range(1, links + 1):
+                layers.append(str(i))
+            return True, layers
+        else:
+            return False, []
+
     def CheckInput(self):
         """Check input fields.
 
         :return: True if configuration file is given and raster xor vector map,
-        False otherwise
+                 False otherwise
         """
-        #R#return bool(self.conf_name and (bool(self.rast) != bool(self.vect)))
-        return bool(self.conf_name and bool(self.rast))
+        return bool(self.conf_name and bool(self.rast and
+                    bool(self.VectorEnabled)))
 
     def OnExitPage(self, event=None):
         """Function during exiting"""
@@ -730,6 +802,7 @@
         TitledPage.__init__(self, wizard, _("Insert sampling areas"))
         self.samplingtype = 'whole'
         self.parent = parent
+        self.overwriteTemp = False
         # toggles
         self.radioBox = wx.RadioBox(parent=self, id=wx.ID_ANY,
                                     label="",
@@ -775,8 +848,12 @@
         self.regionNumPanel.SetSizer(self.regionPanelSizer)
         self.sizer.Add(self.regionNumPanel, flag=wx.ALIGN_CENTER, pos=(2, 0))
 
-        self.areaPanelSizer = wx.GridBagSizer(1, 3)
+        self.areaPanelSizer = wx.GridBagSizer(2, 3)
         self.areaPanel = wx.Panel(parent=self, id=wx.ID_ANY)
+        self.overwriteText = wx.StaticText(parent=self.areaPanel, id=wx.ID_ANY,
+                                      label=_('Do you want to overwrite existing'
+                                              ' temporal maps if they exist?'))
+        self.overwriteCheck = wx.CheckBox(parent=self.areaPanel, id=wx.ID_ANY)
         self.areaText = wx.StaticText(parent=self.areaPanel, id=wx.ID_ANY,
                                       label=_('Do you want to check vector areas?'))
         self.areaOK = wx.Button(self.areaPanel, wx.ID_ANY, 'Yes', (50, 80))
@@ -785,10 +862,15 @@
         self.areaNO.SetToolTip(wx.ToolTip(_("All the features will be used")))
         self.areaOK.Bind(wx.EVT_BUTTON, self.OnVectYes)
         self.areaNO.Bind(wx.EVT_BUTTON, self.OnVectNo)
+        self.overwriteCheck.Bind(wx.EVT_CHECKBOX, self.OnOverwrite)
+        self.areaPanelSizer.Add(self.overwriteText, flag=wx.ALIGN_CENTER,
+                                pos=(0, 0))
+        self.areaPanelSizer.Add(self.overwriteCheck, flag=wx.ALIGN_CENTER,
+                                pos=(0, 1))
         self.areaPanelSizer.Add(self.areaText, flag=wx.ALIGN_CENTER,
-                                pos=(0, 0))
-        self.areaPanelSizer.Add(self.areaOK, flag=wx.ALIGN_CENTER, pos=(0, 1))
-        self.areaPanelSizer.Add(self.areaNO, flag=wx.ALIGN_CENTER, pos=(0, 2))
+                                pos=(1, 0))
+        self.areaPanelSizer.Add(self.areaOK, flag=wx.ALIGN_CENTER, pos=(1, 1))
+        self.areaPanelSizer.Add(self.areaNO, flag=wx.ALIGN_CENTER, pos=(1, 2))
         self.areaPanel.SetSizer(self.areaPanelSizer)
         self.sizer.Add(self.areaPanel, flag=wx.ALIGN_CENTER, pos=(3, 0))
 
@@ -801,10 +883,10 @@
 
     def OnNumRegions(self, event):
         """Obtain the number of regions"""
-        if event.GetString():
+        if self.regionNumTxt.GetValue():
             self.SetNext(self.parent.regions)
             wx.FindWindowById(wx.ID_FORWARD).Enable(True)
-            self.numregions = event.GetString()
+            self.numregions = self.regionNumTxt.GetValue()
         else:
             wx.FindWindowById(wx.ID_FORWARD).Enable(False)
 
@@ -867,6 +949,10 @@
         self.RegionDraw(event.GetInt())
         return
 
+    def OnOverwrite(self, event):
+        self.overwriteTemp = self.overwriteCheck.GetValue()
+        return
+
     def OnVectYes(self, event):
         """The user choose to select the vector areas, this function set the
         next page to VectorAreasPage"""
@@ -882,9 +968,10 @@
         self.sizer.Hide(self.regionBox)
         self.sizer.Hide(self.areaPanel)
         self.SetNext(self.parent.summarypage)
-        vect_cats = sorted(set(grass.parse_command('v.category', input=self.parent.startpage.vect,
-                                                   option='print',
-                                                   type='centroid').keys()))
+
+        vect_cats = obtainCategories(self.parent.startpage.vect,
+                                     self.parent.startpage.vectorlayer)
+
         self._progressDlg = wx.ProgressDialog(title=_("Analysing vector"),
                                               message="Analysing vector",
                                               maximum=len(vect_cats),
@@ -896,6 +983,8 @@
         self.parent.msAreaList = sampleAreaVector(self.parent.startpage.vect,
                                                   self.parent.startpage.rast,
                                                   vect_cats,
+                                                  self.parent.startpage.vectorlayer,
+                                                  self.overwriteTemp,
                                                   self._progressDlg)
         grass.del_temp_region()
         if self.parent.msAreaList:
@@ -1150,16 +1239,16 @@
             self.panelSizer.Layout()
 
     def OnWidth(self, event):
-        self.width = event.GetString()
+        self.width = self.widthTxt.GetValue()
 
     def OnHeight(self, event):
-        self.height = event.GetString()
+        self.height = self.heightTxt.GetValue()
 
     def OnDistr1(self, event):
-        self.distr1 = event.GetString()
+        self.distr1 = self.distr1Txt.GetValue()
 
     def OnDistr2(self, event):
-        self.distr2 = event.GetString()
+        self.distr2 = self.distr2Txt.GetValue()
 
 
 class MovingKeyPage(TitledPage):
@@ -1239,12 +1328,12 @@
         return bool(self.width and bool(self.height))
 
     def OnWidth(self, event):
-        self.width = event.GetString()
+        self.width = self.widthTxt.GetValue()
         next = wx.FindWindowById(wx.ID_FORWARD)
         next.Enable(self.CheckInput())
 
     def OnHeight(self, event):
-        self.height = event.GetString()
+        self.height = self.heightTxt.GetValue()
         next = wx.FindWindowById(wx.ID_FORWARD)
         next.Enable(self.CheckInput())
 
@@ -1339,10 +1428,10 @@
 
     def OnNumRegions(self, event):
         """Set the number of region"""
-        if event.GetString():
+        if self.regionNumTxt.GetValue():
             self.SetNext(self.parent.drawsampleunitspage)
             wx.FindWindowById(wx.ID_FORWARD).Enable(True)
-            self.numregions = event.GetString()
+            self.numregions = self.regionNumTxt.GetValue()
         else:
             wx.FindWindowById(wx.ID_FORWARD).Enable(False)
 
@@ -1455,6 +1544,8 @@
         self.areascount = self.areascount + 1
         if self.areascount == self.areanum:
             wx.FindWindowById(wx.ID_FORWARD).Enable(True)
+            self.areaOK.Enable(False)
+            self.areaNO.Enable(False)
             return True
         else:
             self.title.SetLabel(_('Select sample area ' + str(self.areascount + 1) \
@@ -1477,9 +1568,23 @@
     def newCat(self):
         """Convert to raster and draw the new feature"""
         cat = self.vect_cats[self.areascount]
-        self.outname = "{name}_{cat}".format(name=self.vect.split('@')[0],
-                                             cat=cat)
-        convertFeature(self.vect, self.outname, cat, self.rast)
+        self.outpref = "{rast}_{vect}_".format(vect=self.vect.split('@')[0],
+                                               rast=self.rast.split('@')[0])
+        self.outname = "{pref}{cat}".format(pref=self.outpref, cat=cat)
+        # check if raster already axist
+
+        if len(grass.list_strings('raster', pattern=self.outname, mapset='.')) == 1 \
+           and not self.parent.samplingareapage.overwriteTemp:
+            GError(parent=self, message=_("The raster map <%s> already exists."
+                                          " Please remove or rename the maps "
+                                          "with the prefix '%s' or select the "
+                                          "option to overwrite existing maps"
+                                          % (self.outname, self.outpref)))
+            self.parent.wizard.ShowPage(self.parent.samplingareapage)
+            return
+        convertFeature(self.vect, self.outname, cat, self.rast,
+                       self.parent.startpage.vectorlayer,
+                       self.parent.samplingareapage.overwriteTemp)
         cmdlistcat = ['d.rast', 'map=%s' % self.outname]
         self.map_.AddLayer(ltype='raster', command=cmdlistcat, active=True,
                            name=self.outname, hidden=False, opacity=1.0,
@@ -1495,9 +1600,9 @@
     def OnEnterPage(self, event):
         """Function during entering: draw the raster map and the first vector
         feature"""
+        print self.parent.samplingareapage.overwriteTemp
         if self.mapPanel is None:
-            self.mapPanel = RLiSetupMapPanel(self, samplingType=self.parent.samplingareapage.samplingtype,
-                                             graphicsType="line")
+            self.mapPanel = RLiSetupMapPanel(self, samplingType=self.parent.samplingareapage.samplingtype)
             self.sizer.Add(item=self.mapPanel, flag=wx.EXPAND, pos=(1, 0))
             self.sizer.AddGrowableCol(0)
             self.sizer.AddGrowableRow(1)
@@ -1505,10 +1610,9 @@
 
         self.rast = self.parent.startpage.rast
         self.vect = self.parent.startpage.vect
-        self.vect_cats = sorted(set(grass.parse_command('v.category',
-                                                        input=self.vect,
-                                                        type='centroid',
-                                                        option='print').keys()))
+        self.vect_cats = obtainCategories(self.vect,
+                                          layer=self.parent.startpage.vectorlayer)
+
         self.areanum = len(self.vect_cats)
         if self.areanum == 0:
             GError(parent=self, message=_("The polygon seems to have 0 areas"))



More information about the grass-commit mailing list