[GRASS-SVN] r33585 - in grass/trunk/scripts: db.dropcol
r.regression.line v.db.dropcol v.db.droptable
svn_grass at osgeo.org
svn_grass at osgeo.org
Sun Sep 28 17:55:11 EDT 2008
Author: glynn
Date: 2008-09-28 17:55:11 -0400 (Sun, 28 Sep 2008)
New Revision: 33585
Added:
grass/trunk/scripts/db.dropcol/db.dropcol.py
grass/trunk/scripts/r.regression.line/r.regression.line.py
grass/trunk/scripts/v.db.dropcol/v.db.dropcol.py
grass/trunk/scripts/v.db.droptable/v.db.droptable.py
Log:
Convert db.dropcol, v.db.dropcol, v.db.droptable, r.regression.line to Python
Added: grass/trunk/scripts/db.dropcol/db.dropcol.py
===================================================================
--- grass/trunk/scripts/db.dropcol/db.dropcol.py (rev 0)
+++ grass/trunk/scripts/db.dropcol/db.dropcol.py 2008-09-28 21:55:11 UTC (rev 33585)
@@ -0,0 +1,122 @@
+#!/usr/bin/env python
+
+############################################################################
+#
+# MODULE: db.dropcolumn
+# AUTHOR(S): Markus Neteler
+# Converted to Python by Glynn Clements
+# PURPOSE: interface to db.execute to drop a column from an
+# attribute table
+# - with special trick for SQLite
+# COPYRIGHT: (C) 2007 by Markus Neteler and 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: Drops a column from selected attribute table
+#% keywords: database, attribute table
+#%End
+
+#%flag
+#% key: f
+#% description: Force removal (required for actual deletion of files)
+#%end
+
+#%option
+#% key: table
+#% type: string
+#% key_desc : name
+#% description: Table from which to drop attribute column
+#% required : yes
+#% gisprompt: old,dbtable,dbtable
+#%end
+
+#%option
+#% key: column
+#% type: string
+#% description: Name of the column
+#% required : yes
+#% gisprompt: old,dbcolumn,dbcolumn
+#%end
+
+import sys
+import os
+import string
+import grass
+
+def main():
+ table = options['table']
+ column = options['column']
+ force = flags['f']
+
+ # check if DB parameters are set, and if not set them.
+ grass.run_command('db.connect', flags = 'c')
+
+ s = grass.read_command('db.connect', flags = 'p')
+ kv = grass.parse_key_val(s, sep = ':')
+ database = kv['database']
+ driver = kv['driver']
+ # schema needed for PG?
+
+ if force:
+ grass.message("Forcing ...")
+
+ if column == "cat":
+ grass.warning("Deleting <%s> column which may be needed to keep table connected to a vector map" % column)
+
+ s = grass.read_command('db.describe', flags = 'c', table = table)
+ cols = [l.split(':')[1].lstrip() for l in s.splitlines() if l.startswith('Column ')]
+ if column not in cols:
+ grass.fatal("Column <%s> not found in table" % column)
+
+ if not force:
+ grass.message("Column <%s> would be deleted." % column)
+ grass.message("")
+ grass.message("You must use the force flag to actually remove it. Exiting.")
+ sys.exit(0)
+
+ if driver == "sqlite":
+ #echo "Using special trick for SQLite"
+ # http://www.sqlite.org/faq.html#q13
+ colnames = []
+ coldef = []
+ s = grass.read_command('db.describe', flags = 'c', table = table)
+ for l in s.splitlines():
+ if not l.startswith('Column '):
+ continue
+ f = l.split(':')
+ if f[1] == column:
+ continue
+ colnames.append(f[1])
+ coltypes.append("%s %s" % (f[1], f[2]))
+
+ colnames = ", ".join(colnames)
+ coltypes = ", ".join(coltypes)
+
+ cmds = [
+ "BEGIN TRANSACTION",
+ "CREATE TEMPORARY TABLE ${table}_backup(${coldef})",
+ "INSERT INTO ${table}_backup SELECT ${colnames} FROM ${table}",
+ "DROP TABLE ${table}",
+ "CREATE TABLE ${table}(${coldef})",
+ "INSERT INTO ${table} SELECT ${colnames} FROM ${table}_backup",
+ "DROP TABLE ${table}_backup",
+ "COMMIT"
+ ]
+ tmpl = string.Template(';\n'.join(cmds))
+ sql = tmpl.substitute(table = table, coldef = coltypes, colnames = colnames)
+ else:
+ sql = "ALTER TABLE %s DROP COLUMN %s" % (table, column)
+
+ if grass.write_command('db.execute', database = database, driver = driver,
+ stdin = sql) != 0:
+ grass.fatal("Cannot continue (problem deleting column).")
+
+if __name__ == "__main__":
+ options, flags = grass.parser()
+ main()
Property changes on: grass/trunk/scripts/db.dropcol/db.dropcol.py
___________________________________________________________________
Name: svn:executable
+ *
Added: grass/trunk/scripts/r.regression.line/r.regression.line.py
===================================================================
--- grass/trunk/scripts/r.regression.line/r.regression.line.py (rev 0)
+++ grass/trunk/scripts/r.regression.line/r.regression.line.py 2008-09-28 21:55:11 UTC (rev 33585)
@@ -0,0 +1,154 @@
+#!/usr/bin/env python
+#
+############################################################################
+#
+# MODULE: r.regression line
+# AUTHOR(S): Dr. Agustin Lobo - alobo at ija.csic.es
+# Updated to GRASS 5.7 by Michael Barton
+# Converted to Python by Glynn Clements
+# PURPOSE: Calculates linear regression from two raster maps: y = a + b*x
+# COPYRIGHT: (C) 2004 by 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: Calculates linear regression from two raster maps: y = a + b*x
+#% keywords: raster, statistics
+#%End
+#%flag
+#% key: g
+#% description: Print in shell script style
+#%End
+#%flag
+#% key: s
+#% description: Slower but accurate (applies to FP maps only)
+#%End
+#%option
+#% key: map1
+#% type: string
+#% gisprompt: old,cell,raster
+#% description: Map for x coefficient
+#% required : yes
+#%end
+#%option
+#% key: map2
+#% type: string
+#% gisprompt: old,cell,raster
+#% description: Map for y coefficient
+#% required : yes
+#%end
+#%option
+#% key: output
+#% type: string
+#% gisprompt: new_file,file,output
+#% description: ASCII file for storing regression coefficients (output to screen if file not specified).
+#% required : no
+#%end
+
+import sys
+import os
+import math
+import grass
+
+def main():
+ shell = flags['g']
+ slow = flags['s']
+ map1 = options['map1']
+ map2 = options['map2']
+ output = options['output']
+
+ if not grass.find_file(map1)['name']:
+ grass.fatal("Raster map <%s> not found" % map1)
+ if not grass.find_file(map2)['name']:
+ grass.fatal("Raster map <%s> not found" % map2)
+
+ #calculate regression equation
+ if slow:
+ # slower but accurate
+ statsflags = 'n1'
+ # | sed 's+$+ 1+g' > "$TMP"
+ else:
+ # count "identical" pixels
+ statsflags = 'cnA'
+
+ p = grass.pipe_command('r.stats', flags = statsflags, input = (map1, map2))
+ tot = sumX = sumsqX = sumY = sumsqY = sumXY = 0.0
+ for line in p.stdout:
+ line = line.rstrip('\r\n')
+ if slow:
+ line += ' 1'
+ f = line.split(' ')
+ if len(f) != 3:
+ continue
+ x = float(f[0])
+ y = float(f[1])
+ n = float(f[2])
+
+ tot += n
+ sumX += n * x
+ sumsqX += n * x * x
+ sumY += n * y
+ sumsqY += n * y * y
+ sumXY += n * x * y
+
+ p.wait()
+
+ B = (sumXY - sumX*sumY/tot)/(sumsqX - sumX*sumX/tot)
+ R = (sumXY - sumX*sumY/tot)/math.sqrt((sumsqX - sumX*sumX/tot)*(sumsqY - sumY*sumY/tot))
+
+ mediaX = sumX/tot
+ sumsqX = sumsqX/tot
+ varX = sumsqX-(mediaX*mediaX)
+ sdX = math.sqrt(varX)
+
+ mediaY = sumY/tot
+ sumsqY = sumsqY/tot
+ varY = sumsqY-(mediaY*mediaY)
+ sdY = math.sqrt(varY)
+
+ A = mediaY - B*mediaX
+ F = R*R/(1-R*R/tot-2)
+
+ vars = dict(
+ a = A,
+ b = B,
+ R = R,
+ N = tot,
+ F = F,
+ medX = mediaX,
+ sdX = sdX,
+ medY = mediaY,
+ sdY = sdY)
+ keys = ['a', 'b', 'R', 'N', 'F', 'medX', 'sdX', 'medY', 'sdY']
+
+ #send output to screen or text file
+ if output:
+ fh = file(output, 'w')
+ else:
+ fh = sys.stdout
+
+ if shell:
+ for k, v in vars.iteritems():
+ fh.write('%s=%f\n' % (k, v))
+ else:
+ lines = [
+ "y = a + b*x",
+ " a: offset",
+ " b: gain",
+ " R: sumXY - sumX*sumY/tot",
+ " N: number of elements",
+ " medX, medY: Means",
+ " sdX, sdY: Standard deviations",
+ ' '.join(keys),
+ ]
+ fh.write('\n'.join(lines) + '\n')
+ fh.write(' '.join([str(vars[k]) for k in keys]) + '\n')
+
+if __name__ == "__main__":
+ options, flags = grass.parser()
+ main()
Property changes on: grass/trunk/scripts/r.regression.line/r.regression.line.py
___________________________________________________________________
Name: svn:executable
+ *
Added: grass/trunk/scripts/v.db.dropcol/v.db.dropcol.py
===================================================================
--- grass/trunk/scripts/v.db.dropcol/v.db.dropcol.py (rev 0)
+++ grass/trunk/scripts/v.db.dropcol/v.db.dropcol.py 2008-09-28 21:55:11 UTC (rev 33585)
@@ -0,0 +1,127 @@
+#!/usr/bin/env python
+
+############################################################################
+#
+# MODULE: v.db.dropcolumn
+# AUTHOR(S): Markus Neteler
+# Converted to Python by Glynn Clements
+# PURPOSE: interface to db.execute to drop a column from the
+# attribute table connected to a given vector map
+# - Based on v.db.addcol
+# - with special trick for SQLite
+# COPYRIGHT: (C) 2007 by 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: Drops a column from the attribute table connected to a given vector map.
+#% keywords: vector, database, attribute table
+#%End
+
+#%option
+#% key: map
+#% type: string
+#% gisprompt: old,vector,vector
+#% key_desc : name
+#% description: Vector map for which to drop attribute column
+#% required : yes
+#%end
+
+#%option
+#% key: layer
+#% type: integer
+#% description: Layer where to drop column
+#% answer: 1
+#% required : no
+#%end
+
+#%option
+#% key: column
+#% type: string
+#% description: Name of the column
+#% required : yes
+#%end
+
+import sys
+import os
+import string
+import grass
+
+def main():
+ map = options['map']
+ layer = options['layer']
+ column = options['column']
+
+ mapset = grass.gisenv()['MAPSET']
+
+ # does map exist in CURRENT mapset?
+ if not grass.find_file(map, element = 'vector', mapset = mapset):
+ grass.fatal("Vector map <%s> not found in current mapset" % map)
+
+ s = grass.read_command('v.db.connect', flags = 'g', map = map, layer = layer);
+ if not s:
+ grass.fatal("An error occured while running v.db.connect")
+ f = s.split()
+ table = f[1]
+ keycol = f[2]
+ database = f[3]
+ driver = f[4]
+
+ if not table:
+ grass.fatal("There is no table connected to the input vector map Cannot delete any column")
+
+ if column == keycol:
+ grass.fatal("Cannot delete <$col> column as it is needed to keep table <%s> connected to the input vector map <%s>" % (table, map))
+
+ s = grass.read_command('v.info', flags = 'c', map = map, layer = layer, quiet = True)
+ if column not in [l.split('|')[1].lstrip() for l in s.splitlines()]:
+ grass.fatal("Column <%s> not found in table <%s>" % (column, table))
+
+ if driver == "sqlite":
+ #echo "Using special trick for SQLite"
+ # http://www.sqlite.org/faq.html#q13
+ colnames = []
+ coldef = []
+ s = grass.read_command('db.describe', flags = 'c', table = table)
+ for l in s.splitlines():
+ if not l.startswith('Column '):
+ continue
+ f = l.split(':')
+ if f[1] == column:
+ continue
+ colnames.append(f[1])
+ coltypes.append("%s %s" % (f[1], f[2]))
+
+ colnames = ", ".join(colnames)
+ coltypes = ", ".join(coltypes)
+
+ cmds = [
+ "BEGIN TRANSACTION",
+ "CREATE TEMPORARY TABLE ${table}_backup(${coldef})",
+ "INSERT INTO ${table}_backup SELECT ${colnames} FROM ${table}",
+ "DROP TABLE ${table}",
+ "CREATE TABLE ${table}(${coldef})",
+ "INSERT INTO ${table} SELECT ${colnames} FROM ${table}_backup",
+ "DROP TABLE ${table}_backup",
+ "COMMIT"
+ ]
+ tmpl = string.Template(';\n'.join(cmds))
+ sql = tmpl.substitute(table = table, coldef = coltypes, colnames = colnames)
+ else:
+ sql = "ALTER TABLE %s DROP COLUMN %s" % (table, column)
+
+ if grass.write_command('db.execute', database = database, driver = driver,
+ stdin = sql) != 0:
+ grass.fatal("Cannot continue (problem deleting column).")
+
+ # write cmd history:
+ grass.run_command('v.support', map = map, cmdhist = os.environ['CMDLINE'])
+
+if __name__ == "__main__":
+ options, flags = grass.parser()
+ main()
Property changes on: grass/trunk/scripts/v.db.dropcol/v.db.dropcol.py
___________________________________________________________________
Name: svn:executable
+ *
Added: grass/trunk/scripts/v.db.droptable/v.db.droptable.py
===================================================================
--- grass/trunk/scripts/v.db.droptable/v.db.droptable.py (rev 0)
+++ grass/trunk/scripts/v.db.droptable/v.db.droptable.py 2008-09-28 21:55:11 UTC (rev 33585)
@@ -0,0 +1,107 @@
+#!/usr/bin/env python
+#
+############################################################################
+#
+# MODULE: v.db.droptable
+# AUTHOR(S): Markus Neteler
+# Converted to Python by Glynn Clements
+# PURPOSE: interface to db.execute to drop an existing table of given vector map
+# COPYRIGHT: (C) 2005, 2008 by 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: Removes existing attribute table of a vector map.
+#% keywords: vector, database, attribute table
+#%End
+#%flag
+#% key: f
+#% description: Force removal (required for actual deletion of table)
+#%end
+#%option
+#% key: map
+#% type: string
+#% gisprompt: old,vector,vector
+#% description: Vector map from which to remove attribute table
+#% required : yes
+#%end
+#%option
+#% key: table
+#% type: string
+#% description: Name of existing attribute table (default: vector map name)
+#% required : no
+#%end
+#%option
+#% key: layer
+#% type: integer
+#% description: Layer from which to drop linked attribute table
+#% answer: 1
+#% required : no
+#%end
+
+import sys
+import os
+import grass
+
+def main():
+ force = flags['f']
+ map = options['map']
+ table = options['table']
+ layer = options['layer']
+
+ # do some paranoia tests as well:
+ s = grass.read_command('v.db.connect', flags = 'g', map = map, layer = layer);
+ if not s:
+ grass.fatal("An error occured while running v.db.connect")
+ f = s.split()
+ if not table:
+ # Removing table name connected to selected layer
+ table = f[1]
+ if not table:
+ grass.fatal("No table assigned to layer <$GIS_OPT_LAYER>")
+ else:
+ # Removing user specified table
+ existingtable = f[1]
+ if existingtable != table:
+ grass.fatal("User selected table <%s> but the table <%s> is linked to layer <%s>"
+ % (table, existingtable, layer))
+
+ # we use the DB settings selected layer
+ database = f[3]
+ driver = f[4]
+
+ grass.message("Removing table <%s> linked to layer <%s> of vector map <%s>"
+ % (table, layer, map))
+
+ if not force:
+ grass.message("You must use the -f (force) flag to actually remove the table. Exiting.")
+ grass.message("Leaving map/table unchanged.")
+ sys.exit(0)
+
+ grass.message("Dropping table <%s>..." % table)
+
+ if grass.write_command('db.execute', stdin = "DROP TABLE %s" % table) != 0:
+ grass.fatal("An error occured while running db.execute")
+
+ grass.run_command('v.db.connect', flags = 'd', map = map, layer = layer)
+
+ grass.message("Current attribute table link(s):")
+ # silently test first to avoid confusing error messages
+ nuldev = file(os.devnull, 'w')
+ if grass.run_command('v.db.connect', flags ='p', map = map, quiet = True,
+ stdout = nuldev, stderr = nuldev) != 0:
+ grass.message("(No database links remaining)")
+ else:
+ grass.run_command('v.db.connect', flags ='p', map = map)
+
+ # write cmd history:
+ grass.run_command('v.support', map = map, cmdhist = os.environ['CMDLINE'])
+
+if __name__ == "__main__":
+ options, flags = grass.parser()
+ main()
Property changes on: grass/trunk/scripts/v.db.droptable/v.db.droptable.py
___________________________________________________________________
Name: svn:executable
+ *
More information about the grass-commit
mailing list