[GRASS-SVN] r35267 - in grass-addons/vector: . v.db.calc

svn_grass at osgeo.org svn_grass at osgeo.org
Wed Jan 7 10:53:20 EST 2009


Author: maxi
Date: 2009-01-07 10:53:20 -0500 (Wed, 07 Jan 2009)
New Revision: 35267

Added:
   grass-addons/vector/v.db.calc/
   grass-addons/vector/v.db.calc/description.html
   grass-addons/vector/v.db.calc/v.db.calc
Log:
field calculator script

Added: grass-addons/vector/v.db.calc/description.html
===================================================================
--- grass-addons/vector/v.db.calc/description.html	                        (rev 0)
+++ grass-addons/vector/v.db.calc/description.html	2009-01-07 15:53:20 UTC (rev 35267)
@@ -0,0 +1,49 @@
+<H2>DESCRIPTION</H2>
+
+
+<EM>v.db.calc</EM> executes a python expression using column values and 
+update the target column values: it allows complex calculation also with DBF attribute table.
+
+<H2>NOTES</H2>
+The v.db.calc must be run with a valid <a href="http://www.python.org/">Python</a> installed.<br>
+The columns within expression should be referred between square brackets <em> [ ] </em>.<br>
+Python functions should be referred with their full name.
+
+<H2>EXAMPLE</H2>
+Add a new column named EXP and populate it with the values of column "VAL" elevated at 0.25:
+<div class="code"><pre>
+v.db.addcol map=build columns="EXP double"
+v.db.calc input=myvector field=EXP exp="math.pow([VAL], 0.25)"
+</pre></div>
+
+Add a new column named EXP and populate it with the values of column "VAL" elevated at 0.25 
+only where column HEIGHT is bigger then 100:
+<div class="code"><pre>
+v.db.addcol map=build columns="EXP double"
+v.db.calc input=myvector field=EXP exp="math.pow([VAL], 0.25)" where="HEIGHT>100"
+</pre></div>
+
+
+<p>
+Add a new text column named TXT and populte it concatenating <em> Dr. </em> and the text values of the column NAME:
+<div class="code"><pre>
+v.db.addcol map=build columns="TXT varchar(25)"
+v.db.calc input=edifici field=EXP2 exp="'Dr. '+'[NAME]'"
+</pre></div>
+
+
+
+<H2>REFERENCES</H2>
+<a href="http://docs.python.org">Python</a>
+<p> 
+<a href="http://docs.python.org/library/cmath.html">Python math library</a>
+
+<H2>SEE ALSO</H2>
+
+<EM><A HREF="v.db.update.html">v.db.update</A></EM>
+
+<H2>AUTHOR</H2>
+
+Massimiliano Cannata <br>
+
+<p><i>Last changed: $Date: 2009-01-07 17:45:44 +0100 (Wed, 07 Jan 2009) $</i>
\ No newline at end of file

Added: grass-addons/vector/v.db.calc/v.db.calc
===================================================================
--- grass-addons/vector/v.db.calc/v.db.calc	                        (rev 0)
+++ grass-addons/vector/v.db.calc/v.db.calc	2009-01-07 15:53:20 UTC (rev 35267)
@@ -0,0 +1,154 @@
+#!/usr/bin/python
+# -*- coding:utf-8 -*-
+############################################################################
+#
+# MODULE:       v.sample.class.py
+#
+# AUTHOR(S):    M. Cannata, M. Molinari (IST-SUPSI www.istgis.ist.supsi.ch:8001/GEOMATICA)
+#
+# PURPOSE:      Field values calculator
+#
+# COPYRIGHT:    (c) 2007 The GRASS Development Team
+#
+#               This program is free software under the GNU General Public
+#               License (>=v2). Read the file COPYING that comes with GRASS
+#               for details.
+#
+############################################################################
+#%Module
+#% description:  Field values calculator
+#% keywords: vector, field, calculator
+#%end
+#%option
+#% key: input
+#% type: string
+#% gisprompt: old,vector,vector
+#% key_desc : name
+#% description: input
+#% required : yes
+#%end
+#%option
+#% key: field
+#% type: string
+#% key_desc : name
+#% description: field to store results
+#% required : yes
+#%end
+#%option
+#% key: exp
+#% type: string
+#% key_desc : operation
+#% description: expression to execute
+#% required : yes
+#%end
+#%option
+#%  key: where
+#%  type: string
+#%  key_desc : expression
+#%  description: where condition to execute
+#%  required : no
+#%end
+
+import os,sys,subprocess,string,random,math,tempfile,time,re
+
+def main(): 
+
+    table = os.getenv('GIS_OPT_input').split('@')[0]
+    field = os.getenv('GIS_OPT_field')
+    exp = os.getenv('GIS_OPT_exp')
+    wherest = os.getenv('GIS_OPT_where')
+
+    #Get vector fields name
+    cmdargs0=["db.columns","table=%s" %table, "--q"]
+    proc0 = subprocess.Popen(cmdargs0, stdout=subprocess.PIPE,stderr=subprocess.PIPE)
+    colnames = proc0.communicate()[0].split("\n")
+
+    #print "cols:\n"
+    #for item in colnames: # print each item
+    #    print item + "\n"
+
+    #Parse operation expression
+    spe = re.split("([\[\]])", exp)
+
+    #Check exp field names validity and get required field list
+    expfields = []
+    for i in range(len(spe)):
+        if(spe[i]=="["):
+            if spe[i+1] not in colnames:
+                print "FATAL ERROR: field " + spe[i+1] + " not found in table " + table + "\n"
+                print "tried SQL: " + spe[i+1] + " not found in table " + table + "\n"
+                return -1
+            else:
+                expfields.append(spe[i+1])
+
+    #Get unique list of required fields
+    uf = list(set(expfields))
+
+    #Prepare query statement
+    lf = ", ".join(uf)
+    sel = "SELECT cat"
+    if len(uf)>0:
+        sel = sel + "," + lf
+    sel = sel  + " from " + table
+    if wherest:
+        sel = sel + " WHERE " + wherest
+
+    #Execute query
+    cmdargs1=["db.select","sql=%s" %sel, "--q", "-c"]
+    proc1 = subprocess.Popen(cmdargs1, stdout=subprocess.PIPE,stderr=subprocess.PIPE)
+    lines = proc1.communicate()[0].split("\n")
+
+    #print "query: " + sel
+
+    #print "unique list:\n"
+    #for item in uf: # print each item
+    #    print item + "\n" 
+
+    #print "selection:\n"
+    #for item in lines: # print each item
+    #    print item + "\n" 
+
+    #Check query results
+    if len(lines) == 1:
+        print "WARNING: no record selected\n"
+        print "executed query: " + sel + "\n"
+        return -1
+    #Process and UPDATE
+    else:
+        #process lines
+        for l in range(0,len(lines)-1):
+            if l%10==0:
+                print "."
+            cols = lines[l].split("|")
+            evalexp = exp
+            for i in range(len(uf)):
+                evalexp = evalexp.replace("["+uf[i]+"]",cols[i+1])
+            try:
+                #print evalexp + "\n"            
+                value = eval(str(evalexp))
+            #except ArithmeticError, e:
+            except StandardError, e:
+                print "\n%s\nIn command: %s" % (repr(e), str(evalexp))
+                return -1
+
+            #print value           
+            updst = "UPDATE " + table + " SET " + field + "=" + str(value) + " WHERE cat=" + cols[0]
+            #print updst
+            cmdargs2=["map=%s"%table,"col=%s"%field,"val=%s"%str(value),"where=cat=%s"%cols[0],"--q"]     
+            os.spawnvp(os.P_WAIT,"v.db.update", ["v.db.update"] + cmdargs2)
+
+    return
+
+if __name__ == "__main__":
+    if ( len(sys.argv) <= 1 or sys.argv[1] != "@ARGS_PARSED@" ):
+        os.execvp("g.parser", [sys.argv[0]] + sys.argv)
+    else:
+	main();  
+
+
+
+
+
+
+
+


Property changes on: grass-addons/vector/v.db.calc/v.db.calc
___________________________________________________________________
Name: svn:executable
   + *



More information about the grass-commit mailing list