Skip to content

Instantly share code, notes, and snippets.

@bniebuhr
Created March 17, 2019 01:56
Show Gist options
  • Save bniebuhr/ecffc6a81313b72a67b6affce6981e09 to your computer and use it in GitHub Desktop.
Save bniebuhr/ecffc6a81313b72a67b6affce6981e09 to your computer and use it in GitHub Desktop.
script to edit and save statistics from raster maps in GRASS GIS, using r.stats
# import modules
import grass.script as grass
def export_statistics(input_map = ''):
'''
Function to calculate and export statistics (using r.stats) from landscape metrics maps.
Results are given in hectares.
Parameters
----------
input_map: string
Landscape metric map from which statistics will be calculated.
Returns
-------
out: txt file
File with the id of the patch (or class), the area (or correspondent metric), in hectares,
and the percentage of the total each patch correponds.
'''
# Define region
grass.run_command('g.region', rast=input_map)
# Calculate area and percentage statistics for the input map using r.stats
x = grass.read_command('r.stats', flags = 'nap', input = input_map)
# Separating values by line
y = x.split('\n')
# Initialize arrays
idd = []
areas = []
if len(y) != 0:
# For each element in the list of values
for i in y:
if i != '':
##print i
# Split by space
f = i.split(' ')
##print f
# Get id (raster value)
ids = f[0]
ids = int(ids)
idd.append(ids)
##print ids
# Get area in m2 and transform to hectares
ha = f[1]
haint = float(ha)
haint = haint/10000
areas.append(haint)
##print haint
# Calculate the percentage
percentages = [float(i)/sum(areas) for i in areas]
# Open output file
txt_file = open(input_map+'.txt', 'w')
# Write header
txt_file.write('CODE'+','+'AREA_HA'+','+'PROPORTION\n')
# For each element
for i in range(len(idd)):
# Write line in the output file
txt_file.write(`idd[i]`+','+`areas[i]`+','+`percentages[i]`+'\n')
# Close the output file
txt_file.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment