Thursday 9 June 2011

GRASS GIS programming with Python on Mac OS X

Geographic Resources Analysis Support System (GRASS) is the one of free GIS software.
Because this software supports multiplatform environments, it works on Windows, Mac and Linux.
In my case, I installed GRASS on my iMac and Ubuntu laptop. GRASS is my primary GIS software, now.

Although many popular GIS softwares provide integrated graphical interfaces, GRASS provides "libraries" for geographical analysis,
and users need to combine these libraries for own purposes.
Therefore, programming skills are essential to fully enjoy the benefit of this software.

Bash scripts are the most popular way to implement any procedures.
However, bash scrips aren't supported on Windows platform,
and it's not efficient to implement complicated process.

Because of these reasons, I tried Python scripts for GRASS programming,
and here I draw up memos of setting up and of sample codes on Mac OS X.

1. Setting up Python environment:
Open terminal and set up system environment.

export GISBASE=/Applications/GRASS-6.4.app/Contents/MacOS
export GISRC=/Users/usernamehere/.grassrc6
export LD_LIBRARY_PATH=/Applications/GRASS-6.4.app/Contents/MacOS/lib
export PATH=/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/Library/Frameworks/GDAL.framework/Versions/1.7/Programs/:/Applications/GRASS-6.4.app/Contents/MacOS:/Library/Frameworks/PROJ.framework/Versions/4/Programs/:/Applications/GRASS-6.4.app/Contents/MacOS/lib:/Applications/GRASS-6.4.app/Contents/MacOS/scripts:/Applications/GRASS-6.4.app/Contents/MacOS/etc:/Applications/GRASS-6.4.app/Contents/MacOS/bin:/Applications/GRASS-6.4.app/Contents/MacOS/etc/python:/usr/X11/bin

2. Scripting Python codes:
Open text editor and write scripts like followings, and then save as "sample.py".
In this example, vector information is acquired by using Python script.

# -*- coding: utf-8 -*-
import os
import grass.script as grass

# Get vector map information of "sites" by using "v.info" with "-t" flag.
# You can use multiple flags at the same time by connecting flags characters with +.
# A single flag, "t", is used in this example.
info = grass.parse_command("v.info", flags="t", map="sites")

# The result is retured as dict type.
print info

# Get specific key as integer.
print int(info['points'])

3. Run Python script on GRASS shell.
Type like following on GRASS shell.

GRASS 6.4.0 (miyagi):~ > python path/to/the/python/sample.py

No comments:

Post a Comment