[GRASS-SVN] r44440 - in grass-addons/vector: . v.mkhexgrid

svn_grass at osgeo.org svn_grass at osgeo.org
Fri Nov 26 17:20:35 EST 2010


Author: tsw
Date: 2010-11-26 14:20:35 -0800 (Fri, 26 Nov 2010)
New Revision: 44440

Added:
   grass-addons/vector/v.mkhexgrid/
   grass-addons/vector/v.mkhexgrid/Makefile
   grass-addons/vector/v.mkhexgrid/description.html
   grass-addons/vector/v.mkhexgrid/v.mkhexgrid
Log:
New script for making hexagonal grids uploaded

Added: grass-addons/vector/v.mkhexgrid/Makefile
===================================================================
--- grass-addons/vector/v.mkhexgrid/Makefile	                        (rev 0)
+++ grass-addons/vector/v.mkhexgrid/Makefile	2010-11-26 22:20:35 UTC (rev 44440)
@@ -0,0 +1,7 @@
+MODULE_TOPDIR = ../..
+
+PGM = v.mkhexgrid
+
+include $(MODULE_TOPDIR)/include/Make/Script.make
+
+default: script

Added: grass-addons/vector/v.mkhexgrid/description.html
===================================================================
--- grass-addons/vector/v.mkhexgrid/description.html	                        (rev 0)
+++ grass-addons/vector/v.mkhexgrid/description.html	2010-11-26 22:20:35 UTC (rev 44440)
@@ -0,0 +1,19 @@
+<H2>DESCRIPTION</H2>
+
+<EM>v.mkhexgrid</EM> is a python script that creates a hexagonal grid for the selected region. 
+
+<H2>NOTES</H2>
+
+This script functions by creating a number of GRASS ASCII files and them importing and cleaning them. 
+<h2>SEE ALSO</h2>
+
+<em>
+    <a HREF="v.mkgrid.html">v.mkgrid</a>
+</em>
+
+<H2>AUTHOR</H2>
+Trevor Wiens
+
+<H2>REFERENCES</H2>
+
+<p><i>Last changed: $Date: 2010-11-24 $</i>

Added: grass-addons/vector/v.mkhexgrid/v.mkhexgrid
===================================================================
--- grass-addons/vector/v.mkhexgrid/v.mkhexgrid	                        (rev 0)
+++ grass-addons/vector/v.mkhexgrid/v.mkhexgrid	2010-11-26 22:20:35 UTC (rev 44440)
@@ -0,0 +1,291 @@
+#!/usr/bin/python
+
+############################################################################
+#
+# MODULE:	v.mkhexgrid for GRASS 6.4 (2010-11-23)
+#
+# AUTHOR(S):	Trevor Wiens
+#
+# PURPOSE:      Makes a hexagonal grid
+#
+# REQUIREMENTS: GRASS 6.4 and above
+#
+# COPYRIGHT:	(C) Trevor Wiens, 2010 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.
+#
+# EXAMPLE:
+#     v.mkhexgrid output=test regionname=default at PERMANENT sidelength=1000
+#
+#############################################################################
+
+#%Module
+#%  description: creates a hexagonal grid
+#%  keywords: vector
+#%  keywords: grid
+#%  keywords: hexagon
+#%  keywords: attribute table
+#%End
+#%option
+#%  key: output
+#%  type: string
+#%  gisprompt: new,vector,vector
+#%  label: Output Vector Name
+#%  description: Name of hexagon grid file to create
+#%  required : yes
+#%end
+#%option
+#%  key: regionname
+#%  type: string
+#%  gisprompt: old,windows,region
+#%  label: Named region to set size of output grid
+#%  description: Named region for geographic extent of region to survey
+#%  required: yes
+#%end
+#%option
+#%  key: sidelength
+#%  type: double
+#%  label: Side length
+#%  description: Size of side length in map units
+#%  required: yes
+#%end
+
+import sys
+import os
+import subprocess
+import time
+import csv
+import math
+from grass.script import core as grass
+from grass.script import vector as gvect
+from grass.script import db as gdb
+
+#
+# WriteHexGridVectors - Using basic trig and the fact that hexagons are constructed from 6 equalateral triangles
+#                       hexagons are created
+#
+#
+
+def WriteHexGridVectors(vf, af, side_len, xstart, ystart, xlimit, ylimit):
+    
+    # basic trig
+    angle_a = math.radians(30)
+    hyp = side_len
+    side_b = hyp * math.cos(angle_a)
+    side_a = hyp * math.sin(angle_a)
+
+    # adjust starting line so that entire grid shape is convex
+    x = xstart + side_len + side_a
+    y = ystart + side_b
+    row = 1
+    col = 1
+    cat = 1
+    while y + (2*side_b) < ylimit:
+        while x + (2*side_len) < xlimit: 
+            name = 'x%f_y%f' % (x,y)
+            outstring = CreateHexagon((x, y), side_len, cat)
+            vf.write(outstring)
+            outstring = '%d,%d,%d,"%d_%d"\n' % (cat, row, col, row, col)
+            af.write(outstring)
+            cat = cat + 1
+            x = x + (2*side_len) + (2*side_a)
+            col = col + 1
+        y = y + side_b
+        row = row + 1
+        if row % 2 <> 0:
+            x = xstart + side_len + side_a
+        else:
+            x = xstart
+        col = 1
+        
+#
+# CreateHexagonGrid - creates hexagons based on six equalateral triangles
+#
+#        
+
+def CreateHexagon(origin, side_len, cat):
+
+    # Get the x and y from the tuple
+    orgx = origin[0]
+    orgy = origin[1]
+
+    # basic trig
+    angle_a = math.radians(30)
+    hyp = side_len
+    side_b = hyp * math.cos(angle_a)
+    side_a = hyp * math.sin(angle_a)
+    cx = orgx + (hyp / 2.0)
+    cy = orgy + side_b
+ 
+    # create coordinate string
+    outstring = """B 2
+%f %f
+%f %f
+B  2
+%f %f
+%f %f
+B  2
+%f %f
+%f %f
+B  2
+%f %f
+%f %f
+B  2
+%f %f
+%f %f
+B  2
+%f %f
+%f %f
+C 1 1
+%f %f
+1 %d\n""" % (
+    orgx, orgy,
+    orgx + hyp, orgy,
+    orgx + hyp, orgy,
+    orgx + hyp + side_a, orgy + side_b,
+    orgx + hyp + side_a, orgy + side_b,
+    orgx + hyp, orgy + (2 * side_b),
+    orgx + hyp, orgy + (2 * side_b),
+    orgx, orgy + (2 * side_b),
+    orgx, orgy + (2 * side_b),
+    orgx - side_a, orgy + side_b,
+    orgx - side_a, orgy + side_b,
+    orgx, orgy, cx, cy, cat)
+    return(outstring)
+
+#
+# WriteGrassHeader - writes GRASS header to temporary text file
+#
+#
+
+def WriteGrassHeader(f,outfile,xstart,ystart,xmax,ymax):
+    
+    today = time.strftime("%Y.%m.%d %H:%M:%S",time.localtime())
+    outtext = """ORGANIZATION: n/a
+DIGIT DATE: %s
+DIGIT NAME: v.mkhexgrid
+MAP NAME: %s
+MAP DATE: %s
+MAP SCALE: 
+OTHER INFO: Hexagon Grid
+ZONE: 0
+WEST EDGE: %s
+EAST EDGE: %s
+SOUTH EDGE: %s
+NORTH EDGE: %s
+MAP THRESH: 0.000000
+VERTI:\n""" % (today,outfile,today,xstart,xmax,ystart,ymax)
+    f.write(outtext)
+    return()
+    
+def main():
+    errpipe = subprocess.PIPE
+    outpipe = subprocess.PIPE
+    grass.message('Creating GRASS ascii file with hexagons')
+    # assign name to temporary text file
+    tempname= 'tempgrid%d' % os.getpid()
+    vectorfile = tempname + '.asc'
+    attrfile = tempname + '.csv'
+    attrdesc = tempname + '.csvt'
+    # set region
+    try:
+        r = grass.run_command('g.region', region='%s' % options['regionname'])
+        if r <> 0:
+            raise
+    except:
+        msgtext="An error occured when selecting the specified region. \n" 
+        grass.message(msgtext, flag='e')
+        return(-1)
+    current_region = grass.region()
+    xstart = current_region['w']
+    ystart = current_region['s']
+    xmax = current_region['e']
+    ymax = current_region['n']
+    side_len = options['sidelength']
+    #print "filename: %s\nx: %s, y: %s\nxmax: %s, ymax: %s\nside_length: %s" % (outfile, xstart, ystart, xmax, ymax, side_len)
+    vf = open(vectorfile, "w")
+    af = open(attrfile, "w")
+    af.write('"cat","row_num","col_num","row_col"\n')
+    adf = open(attrdesc, "w")
+    adf.write('"Integer","Integer","Integer","String"')
+    adf.close()
+    WriteGrassHeader(vf,vectorfile,xstart,ystart,xmax,ymax)
+    WriteHexGridVectors(vf, af, float(side_len), float(xstart), float(ystart), float(xmax), float(ymax))
+    vf.close()
+    af.close()
+    # now import and clean up the vector
+    grass.message('Importing GRASS ascii file')
+    try:
+        r = grass.run_command('v.in.ascii', input=vectorfile, output=tempname, format='standard', fs=',')
+        if r <> 0:
+            raise
+    except:
+        msgtext="An error occured when importing ascii file. \n" 
+        grass.message(msgtext, flag='e')
+        return(-1)
+    grass.message('Cleaning and building topology')
+    try:
+        r = grass.run_command('v.clean', flags='-q', input=tempname, \
+            output=options['output'], type='point,line,boundary,centroid,area', tool='rmdupl')
+        if r <> 0:
+            raise
+    except:
+        msgtext="An error occured when cleaning grid layer. \n" 
+        grass.message(msgtext, flag='e')
+        return(-1)
+    grass.message('Importing and linking attributes')
+    # import attributes
+    table_name = options['output'].split('@')[0]
+    schema = gdb.db_connection()['schema']
+    try:
+        # import under temporary name
+        r = grass.run_command('db.in.ogr', dsn=attrfile, output=tempname)
+    except:
+        pass
+    try:
+        # drop connection
+        r = grass.run_command('v.db.connect', flags='d', map=tempname)
+        if r <> 0:
+            raise
+    except:
+        msgtext="An error occured separating attribute table from empty vector. \n" 
+        grass.message(msgtext, flag='e')
+        return(-1)
+    try:
+        # rename table
+        sqltext = "ALTER TABLE %s.%s RENAME TO %s;" % (schema, tempname, table_name)
+        r = grass.write_command('db.execute', stdin = sqltext, stdout = outpipe, stderr = errpipe)
+        if r <> 0:
+            raise
+    except:
+        msgtext="An error occured renaming attribute table. \n" 
+        grass.message(msgtext + '\n' + sqltext, flag='e')
+        return(-1)
+    try:
+        # link to proper table
+        r = grass.run_command('v.db.connect', flags='o', map=options['output'], table=schema+'.'+table_name)
+        # drop temp vector
+        if r <> 0:
+            raise
+    except:
+        msgtext="An error occured connecting attribute table. \n" 
+        grass.message(msgtext, flag='e')
+        return(-1)
+    grass.message('Removing temporary files')
+    try:
+        r = grass.run_command('g.remove', vect=tempname)
+        if r <> 0:
+            raise
+    except:
+        msgtext="An error occured when removing temporary layer. \n" 
+        grass.message(msgtext, flag='e')
+        return(-1)
+    os.remove(vectorfile)
+    os.remove(attrfile)
+    os.remove(attrdesc)
+        
+if __name__ == "__main__":
+    options, flags = grass.parser()
+    sys.exit(main())


Property changes on: grass-addons/vector/v.mkhexgrid/v.mkhexgrid
___________________________________________________________________
Added: svn:executable
   + *



More information about the grass-commit mailing list