SlideShare una empresa de Scribd logo
1 de 17
Descargar para leer sin conexión
Python scripting in GRASS GIS environment




     Geospatial Analysis and Modeling – MEA792
                 Margherita Di Leo
Python scripting in GRASS GIS environment




Python + GRASS GIS:

➢ Python scripts that call GRASS functionality from
outside

➢  Running external commands from Python (as a
grass module)
Python scripting in GRASS GIS environment

Example

Module: r.ipso

Purpose: Creates the ipsographic curve and the
adimensional ipsometric curve

Requires: Matplotlib

http://svn.osgeo.org/grass/grass-addons/raster/r.ipso/
Python scripting in GRASS GIS environment

GUI
#%module
#% description: Creates the ipsographic and ipsometric curve
#% keywords: raster
#%end
#%option
#% key: map
#% type: string
#% gisprompt: old,raster,raster
#% key_desc: name
#% description: Name of elevation raster map
#% required: yes
#%end
#%option
#% key: image
#% type: string
#% gisprompt: new_file,file,input
#% key_desc: image
#% description: output graph
#% required: yes
#%end
#%flag
#% key: a
#% description: generate ipsometric curve
#%END
#%flag
#% key: b
#% description: generate ipsographic curve
#%END
Python scripting in GRASS GIS environment

GUI
#%module
#% description: Creates the ipsographic and ipsometric curve
#% keywords: raster
#%end
#%option
#% key: map
#% type: string
#% gisprompt: old,raster,raster
#% key_desc: name
#% description: Name of elevation raster map
#% required: yes
#%end
#%option
#% key: image
#% type: string
#% gisprompt: new_file,file,input
#% key_desc: image
#% description: output graph
#% required: yes
#%end
#%flag
#% key: a
#% description: generate ipsometric curve
#%END
#%flag
#% key: b
#% description: generate ipsographic curve
#%END
Python scripting in GRASS GIS environment


prompt
GRASS 6.5.svn (Basilicata):~ > r.ipso.py --help

Description:
 Creates the ipsographic and ipsometric curve

Keywords:
 raster

Usage:
 r.ipso.py [-ab] map=name image=image [--verbose] [--quiet]

Flags:
  -a     generate ipsometric curve
  -b     generate ipsographic curve
 --v     Verbose module output
 --q     Quiet module output

Parameters:
    map   Name of elevation raster map
  image   path to output graph
GRASS 6.5.svn (Basilicata):~ >
Python scripting in GRASS GIS environment


output
GRASS   6.5.svn    (Basilicata):~   >   r.ipso.py   map=dem@Fiumarella_dataset   -ab
image=Fiumarella
 100%
Tot. cells 172200.0
===========================
Ipsometric | quantiles
===========================
994 | 0.025
989 | 0.05
980 | 0.1
960 | 0.25
918 | 0.5
870 | 0.75
882 | 0.7
841 | 0.9
817 | 0.975


Done!
GRASS 6.5.svn (Basilicata):~ >
Python scripting in GRASS GIS environment

output
Python scripting in GRASS GIS environment

output
Python scripting in GRASS GIS environment

import
import   sys
import   os
import   matplotlib.pyplot as plt
import   grass.script as grass
import   numpy as np


Main (1/4)
def main():
    # r.stats gives in the first column the elevation and in the second the number of
cells having that elevation
    stats = grass.read_command('r.stats', input = options['map'], fs = 'space', nv =
'*', nsteps = '255', flags = 'inc').split('n')[:-1]

    # res = cellsize
       res = float(grass.read_command('g.region',   rast   =   options['map'],   flags   =
'm').strip().split('n')[4].split('=')[1])
    zn = np.zeros((len(stats),6),float)
    kl = np.zeros((len(stats),2),float)
    prc = np.zeros((9,2),float)

   for i in range(len(stats)):
       if i == 0:
           zn[i,0], zn[i, 1] = map(float, stats[i].split(' '))
           zn[i,2] = zn[i,1]
       else:
           zn[i,0], zn[i, 1] = map(float, stats[i].split(' '))
           zn[i,2] = zn[i,1] + zn[i-1,2]

   totcell = sum(zn[:,1])
   print "Tot. cells", totcell
Python scripting in GRASS GIS environment


Main (2/4)
   for i in range(len(stats)):
       zn[i,3] = 1 - (zn[i,2] / sum(zn[:,1]))
       zn[i,4] = zn[i,3] * (((res**2)/1000000)*sum(zn[:,1]))
       zn[i,5] = ((zn[i,0] - min(zn[:,0])) / (max(zn[:,0]) - min(zn[:,0])) )
       kl[i,0] = zn[i,0]
       kl[i,1] = 1 - (zn[i,2] / totcell)

   # quantiles
   prc[0,0] , prc[0,1]   =   findint(kl,0.025) , 0.025
   prc[1,0] , prc[1,1]   =   findint(kl,0.05) , 0.05
   prc[2,0] , prc[2,1]   =   findint(kl,0.1) , 0.1
   prc[3,0] , prc[3,1]   =   findint(kl,0.25) , 0.25
   prc[4,0] , prc[4,1]   =   findint(kl,0.5) , 0.5
   prc[5,0] , prc[5,1]   =   findint(kl,0.75) , 0.75
   prc[6,0] , prc[6,1]   =   findint(kl,0.9) , 0.9
   prc[7,0] , prc[7,1]   =   findint(kl,0.95) , 0.95
   prc[8,0] , prc[8,1]   =   findint(kl,0.975) , 0.975

    # Managing flag & plot
    if flags['a']:
            plotImage(zn[:,3], zn[:,5],options['image']+'_Ipsometric.png','-','A(i) /
A','Z(i) / Zmax','Ipsometric Curve')
    if flags['b']:
          plotImage(zn[:,4], zn[:,0],options['image']+'_Ipsographic.png','-','A [km^2
]','Z [m.slm]','Ipsographic Curve')
Python scripting in GRASS GIS environment


Main (3/4)
   print "==========================="
   print "Ipsometric | quantiles"
   print "==========================="
   print '%.0f' %findint(kl,0.025) , "|", 0.025
   print '%.0f' %findint(kl,0.05) , "|", 0.05
   print '%.0f' %findint(kl,0.1) , "|", 0.1
   print '%.0f' %findint(kl,0.25) , "|", 0.25
   print '%.0f' %findint(kl,0.5) , "|", 0.5
   print '%.0f' %findint(kl,0.75) , "|", 0.75
   print '%.0f' %findint(kl,0.7) , "|", 0.7
   print '%.0f' %findint(kl,0.9) , "|", 0.9
   print '%.0f' %findint(kl,0.975) , "|", 0.975
   print 'n'
   print 'Done!'
   #print prc


def findint(kl,f):
    Xf = np.abs(kl-f); Xf = np.where(Xf==Xf.min())
    z1 , z2 , f1 , f2 = kl[float(Xf[0])][0] , kl[float(Xf[0]-1)][0] , kl[float(Xf[0])
][1] , kl[float(Xf[0]-1)][1]
    z = z1 + ((z2 - z1) / (f2 - f1)) * (f - f1)
    return z
Python scripting in GRASS GIS environment



Main (4/4)
def plotImage(x,y,image,type,xlabel,ylabel,title):
    plt.plot(x, y, type)
    plt.ylabel(ylabel)
    plt.xlabel(xlabel)
    plt.xlim( min(x), max(x) )
    plt.ylim( min(y), max(y) )
    plt.title(title)
    plt.grid(True)
    plt.savefig(image)
    plt.close('all')

if __name__ == "__main__":
    options, flags = grass.parser()
    sys.exit(main())
Python scripting in GRASS GIS environment
Zn has n rows and 6 columns [len(stats) = n]

Kl has n rows and 2 columns

Prc has 9 rows and 2 columns

                                          Zn

   0            1             2                 3             4            5


   A=          B=         C = (if i=0,      D = (1-C) /      E = Di *    F = (A –
elevation   numbers of    Ci=Ai; else      numbers of       (res^2) /   min(A)) /
              cells      Ci = Ai + B(i-       cells        1000000 *    (max(A) -
                              1) )                        numbers of     min(A))
                                                              cells
Python scripting in GRASS GIS environment
Zn has n rows and 6 columns [len(stats) = n]

Kl has n rows and 2 columns

Prc has 9 rows and 2 columns

                                     kl
                              0            1




                            A=        G = 1 – (C /
                         elevation    num of cell)
Python scripting in GRASS GIS environment

Prc has 9 rows and 2 columns.
It defines the ipsometric curve by the quantiles of the distribution.
It is built by the function ”findint”
def findint(kl,f):
    Xf = np.abs(kl-f); Xf = np.where(Xf==Xf.min())
    z1 , z2 , f1 , f2 = kl[float(Xf[0])][0] , kl[float(Xf[0]-1)][0] , kl[float(Xf[0])
][1] , kl[float(Xf[0]-1)][1]
    z = z1 + ((z2 - z1) / (f2 - f1)) * (f - f1)
    return z

np.abs and np.where are two NumPy routines:

numpy.absolute(x[, out])
  Calculate the absolute value element-wise.

numpy.where(condition[, x, y])
  Return elements, either from x or y, depending on condition.
  If only condition is given, return condition.nonzero().

See NumPy doc at http://docs.scipy.org/doc/
Python scripting in GRASS GIS environment


Some useful links:

GRASS and Python on Osgeo wiki:
http://grass.osgeo.org/wiki/GRASS_and_Python
GRASS Python Scripting Library:
http://grass.osgeo.org/programming6/pythonlib.html
Style rules:
http://trac.osgeo.org/grass/browser/grass/trunk/SUBMITTING_PYTHON

Más contenido relacionado

La actualidad más candente

Mi primer map reduce
Mi primer map reduceMi primer map reduce
Mi primer map reduceRuben Orta
 
K10692 control theory
K10692 control theoryK10692 control theory
K10692 control theorysaagar264
 
Scientific Computing with Python - NumPy | WeiYuan
Scientific Computing with Python - NumPy | WeiYuanScientific Computing with Python - NumPy | WeiYuan
Scientific Computing with Python - NumPy | WeiYuanWei-Yuan Chang
 
Class 8b: Numpy & Matplotlib
Class 8b: Numpy & MatplotlibClass 8b: Numpy & Matplotlib
Class 8b: Numpy & MatplotlibMarc Gouw
 
Statistical inference for (Python) Data Analysis. An introduction.
Statistical inference for (Python) Data Analysis. An introduction.Statistical inference for (Python) Data Analysis. An introduction.
Statistical inference for (Python) Data Analysis. An introduction.Piotr Milanowski
 
XIX PUG-PE - Pygame game development
XIX PUG-PE - Pygame game developmentXIX PUG-PE - Pygame game development
XIX PUG-PE - Pygame game developmentmatheuscmpm
 
Seminar PSU 09.04.2013 - 10.04.2013 MiFIT, Arbuzov Vyacheslav
Seminar PSU 09.04.2013 - 10.04.2013 MiFIT, Arbuzov VyacheslavSeminar PSU 09.04.2013 - 10.04.2013 MiFIT, Arbuzov Vyacheslav
Seminar PSU 09.04.2013 - 10.04.2013 MiFIT, Arbuzov VyacheslavVyacheslav Arbuzov
 
ggtimeseries-->ggplot2 extensions
ggtimeseries-->ggplot2 extensions ggtimeseries-->ggplot2 extensions
ggtimeseries-->ggplot2 extensions Dr. Volkan OBAN
 
The matplotlib Library
The matplotlib LibraryThe matplotlib Library
The matplotlib LibraryHaim Michael
 
ggplot2できれいなグラフ
ggplot2できれいなグラフggplot2できれいなグラフ
ggplot2できれいなグラフDaisuke Ichikawa
 
Data Visualization with R.ggplot2 and its extensions examples.
Data Visualization with R.ggplot2 and its extensions examples.Data Visualization with R.ggplot2 and its extensions examples.
Data Visualization with R.ggplot2 and its extensions examples.Dr. Volkan OBAN
 
Presentation: Plotting Systems in R
Presentation: Plotting Systems in RPresentation: Plotting Systems in R
Presentation: Plotting Systems in RIlya Zhbannikov
 
Yampa AFRP Introduction
Yampa AFRP IntroductionYampa AFRP Introduction
Yampa AFRP IntroductionChengHui Weng
 
Scientific Computing with Python Webinar March 19: 3D Visualization with Mayavi
Scientific Computing with Python Webinar March 19: 3D Visualization with MayaviScientific Computing with Python Webinar March 19: 3D Visualization with Mayavi
Scientific Computing with Python Webinar March 19: 3D Visualization with MayaviEnthought, Inc.
 
Fast Identification of Heavy Hitters by Cached and Packed Group Testing
Fast Identification of Heavy Hitters by Cached and Packed Group TestingFast Identification of Heavy Hitters by Cached and Packed Group Testing
Fast Identification of Heavy Hitters by Cached and Packed Group TestingRakuten Group, Inc.
 
SciSmalltalk: Doing Science with Agility
SciSmalltalk: Doing Science with AgilitySciSmalltalk: Doing Science with Agility
SciSmalltalk: Doing Science with AgilityESUG
 
Megadata With Python and Hadoop
Megadata With Python and HadoopMegadata With Python and Hadoop
Megadata With Python and Hadoopryancox
 
Sergey Shelpuk & Olha Romaniuk - “Deep learning, Tensorflow, and Fashion: how...
Sergey Shelpuk & Olha Romaniuk - “Deep learning, Tensorflow, and Fashion: how...Sergey Shelpuk & Olha Romaniuk - “Deep learning, Tensorflow, and Fashion: how...
Sergey Shelpuk & Olha Romaniuk - “Deep learning, Tensorflow, and Fashion: how...Lviv Startup Club
 

La actualidad más candente (20)

Mi primer map reduce
Mi primer map reduceMi primer map reduce
Mi primer map reduce
 
K10692 control theory
K10692 control theoryK10692 control theory
K10692 control theory
 
Scientific Computing with Python - NumPy | WeiYuan
Scientific Computing with Python - NumPy | WeiYuanScientific Computing with Python - NumPy | WeiYuan
Scientific Computing with Python - NumPy | WeiYuan
 
Class 8b: Numpy & Matplotlib
Class 8b: Numpy & MatplotlibClass 8b: Numpy & Matplotlib
Class 8b: Numpy & Matplotlib
 
Statistical inference for (Python) Data Analysis. An introduction.
Statistical inference for (Python) Data Analysis. An introduction.Statistical inference for (Python) Data Analysis. An introduction.
Statistical inference for (Python) Data Analysis. An introduction.
 
Jan 2012 HUG: RHadoop
Jan 2012 HUG: RHadoopJan 2012 HUG: RHadoop
Jan 2012 HUG: RHadoop
 
XIX PUG-PE - Pygame game development
XIX PUG-PE - Pygame game developmentXIX PUG-PE - Pygame game development
XIX PUG-PE - Pygame game development
 
Seminar PSU 09.04.2013 - 10.04.2013 MiFIT, Arbuzov Vyacheslav
Seminar PSU 09.04.2013 - 10.04.2013 MiFIT, Arbuzov VyacheslavSeminar PSU 09.04.2013 - 10.04.2013 MiFIT, Arbuzov Vyacheslav
Seminar PSU 09.04.2013 - 10.04.2013 MiFIT, Arbuzov Vyacheslav
 
ggtimeseries-->ggplot2 extensions
ggtimeseries-->ggplot2 extensions ggtimeseries-->ggplot2 extensions
ggtimeseries-->ggplot2 extensions
 
The matplotlib Library
The matplotlib LibraryThe matplotlib Library
The matplotlib Library
 
ggplot2できれいなグラフ
ggplot2できれいなグラフggplot2できれいなグラフ
ggplot2できれいなグラフ
 
Data Visualization with R.ggplot2 and its extensions examples.
Data Visualization with R.ggplot2 and its extensions examples.Data Visualization with R.ggplot2 and its extensions examples.
Data Visualization with R.ggplot2 and its extensions examples.
 
Presentation: Plotting Systems in R
Presentation: Plotting Systems in RPresentation: Plotting Systems in R
Presentation: Plotting Systems in R
 
Yampa AFRP Introduction
Yampa AFRP IntroductionYampa AFRP Introduction
Yampa AFRP Introduction
 
Scientific Computing with Python Webinar March 19: 3D Visualization with Mayavi
Scientific Computing with Python Webinar March 19: 3D Visualization with MayaviScientific Computing with Python Webinar March 19: 3D Visualization with Mayavi
Scientific Computing with Python Webinar March 19: 3D Visualization with Mayavi
 
Fast Identification of Heavy Hitters by Cached and Packed Group Testing
Fast Identification of Heavy Hitters by Cached and Packed Group TestingFast Identification of Heavy Hitters by Cached and Packed Group Testing
Fast Identification of Heavy Hitters by Cached and Packed Group Testing
 
SciSmalltalk: Doing Science with Agility
SciSmalltalk: Doing Science with AgilitySciSmalltalk: Doing Science with Agility
SciSmalltalk: Doing Science with Agility
 
Megadata With Python and Hadoop
Megadata With Python and HadoopMegadata With Python and Hadoop
Megadata With Python and Hadoop
 
Sergey Shelpuk & Olha Romaniuk - “Deep learning, Tensorflow, and Fashion: how...
Sergey Shelpuk & Olha Romaniuk - “Deep learning, Tensorflow, and Fashion: how...Sergey Shelpuk & Olha Romaniuk - “Deep learning, Tensorflow, and Fashion: how...
Sergey Shelpuk & Olha Romaniuk - “Deep learning, Tensorflow, and Fashion: how...
 
Computer graphics
Computer graphicsComputer graphics
Computer graphics
 

Similar a Python grass

Python for Scientific Computing -- Ricardo Cruz
Python for Scientific Computing -- Ricardo CruzPython for Scientific Computing -- Ricardo Cruz
Python for Scientific Computing -- Ricardo Cruzrpmcruz
 
Pythran: Static compiler for high performance by Mehdi Amini PyData SV 2014
Pythran: Static compiler for high performance by Mehdi Amini PyData SV 2014Pythran: Static compiler for high performance by Mehdi Amini PyData SV 2014
Pythran: Static compiler for high performance by Mehdi Amini PyData SV 2014PyData
 
Frsa
FrsaFrsa
Frsa_111
 
Python과 node.js기반 데이터 분석 및 가시화
Python과 node.js기반 데이터 분석 및 가시화Python과 node.js기반 데이터 분석 및 가시화
Python과 node.js기반 데이터 분석 및 가시화Tae wook kang
 
All I know about rsc.io/c2go
All I know about rsc.io/c2goAll I know about rsc.io/c2go
All I know about rsc.io/c2goMoriyoshi Koizumi
 
RedisConf18 - Lower Latency Graph Queries in Cypher with Redis Graph
RedisConf18 - Lower Latency Graph Queries in Cypher with Redis GraphRedisConf18 - Lower Latency Graph Queries in Cypher with Redis Graph
RedisConf18 - Lower Latency Graph Queries in Cypher with Redis GraphRedis Labs
 
Root Locus Method - Control System - Bsc Engineering
Root Locus Method - Control System - Bsc EngineeringRoot Locus Method - Control System - Bsc Engineering
Root Locus Method - Control System - Bsc Engineeringdexik15916
 
Data visualization using the grammar of graphics
Data visualization using the grammar of graphicsData visualization using the grammar of graphics
Data visualization using the grammar of graphicsRupak Roy
 
Aaron Ellison Keynote: Reaching the 99%
Aaron Ellison Keynote: Reaching the 99%Aaron Ellison Keynote: Reaching the 99%
Aaron Ellison Keynote: Reaching the 99%David LeBauer
 
Company_X_Data_Analyst_Challenge
Company_X_Data_Analyst_ChallengeCompany_X_Data_Analyst_Challenge
Company_X_Data_Analyst_ChallengeMark Yashar
 
Linear Logistic regession_Practical.pptx
Linear Logistic regession_Practical.pptxLinear Logistic regession_Practical.pptx
Linear Logistic regession_Practical.pptxDr. Amanpreet Kaur
 
Python 培训讲义
Python 培训讲义Python 培训讲义
Python 培训讲义leejd
 

Similar a Python grass (20)

Python for Scientific Computing -- Ricardo Cruz
Python for Scientific Computing -- Ricardo CruzPython for Scientific Computing -- Ricardo Cruz
Python for Scientific Computing -- Ricardo Cruz
 
Pythran: Static compiler for high performance by Mehdi Amini PyData SV 2014
Pythran: Static compiler for high performance by Mehdi Amini PyData SV 2014Pythran: Static compiler for high performance by Mehdi Amini PyData SV 2014
Pythran: Static compiler for high performance by Mehdi Amini PyData SV 2014
 
CLUSTERGRAM
CLUSTERGRAMCLUSTERGRAM
CLUSTERGRAM
 
Rtutorial
RtutorialRtutorial
Rtutorial
 
Frsa
FrsaFrsa
Frsa
 
SCIPY-SYMPY.pdf
SCIPY-SYMPY.pdfSCIPY-SYMPY.pdf
SCIPY-SYMPY.pdf
 
R Language Introduction
R Language IntroductionR Language Introduction
R Language Introduction
 
Python과 node.js기반 데이터 분석 및 가시화
Python과 node.js기반 데이터 분석 및 가시화Python과 node.js기반 데이터 분석 및 가시화
Python과 node.js기반 데이터 분석 및 가시화
 
All I know about rsc.io/c2go
All I know about rsc.io/c2goAll I know about rsc.io/c2go
All I know about rsc.io/c2go
 
R programming language
R programming languageR programming language
R programming language
 
RedisConf18 - Lower Latency Graph Queries in Cypher with Redis Graph
RedisConf18 - Lower Latency Graph Queries in Cypher with Redis GraphRedisConf18 - Lower Latency Graph Queries in Cypher with Redis Graph
RedisConf18 - Lower Latency Graph Queries in Cypher with Redis Graph
 
Root Locus Method - Control System - Bsc Engineering
Root Locus Method - Control System - Bsc EngineeringRoot Locus Method - Control System - Bsc Engineering
Root Locus Method - Control System - Bsc Engineering
 
Data visualization using the grammar of graphics
Data visualization using the grammar of graphicsData visualization using the grammar of graphics
Data visualization using the grammar of graphics
 
Aaron Ellison Keynote: Reaching the 99%
Aaron Ellison Keynote: Reaching the 99%Aaron Ellison Keynote: Reaching the 99%
Aaron Ellison Keynote: Reaching the 99%
 
Company_X_Data_Analyst_Challenge
Company_X_Data_Analyst_ChallengeCompany_X_Data_Analyst_Challenge
Company_X_Data_Analyst_Challenge
 
Seminar PSU 10.10.2014 mme
Seminar PSU 10.10.2014 mmeSeminar PSU 10.10.2014 mme
Seminar PSU 10.10.2014 mme
 
Linear Logistic regession_Practical.pptx
Linear Logistic regession_Practical.pptxLinear Logistic regession_Practical.pptx
Linear Logistic regession_Practical.pptx
 
Python 培训讲义
Python 培训讲义Python 培训讲义
Python 培训讲义
 
Joclad 2010 d
Joclad 2010 dJoclad 2010 d
Joclad 2010 d
 
Big datacourse
Big datacourseBig datacourse
Big datacourse
 

Más de Margherita Di Leo

Presentazione introduttiva v01
Presentazione introduttiva v01Presentazione introduttiva v01
Presentazione introduttiva v01Margherita Di Leo
 
Matera 25/06/2012. Convegno “Software libero ed open data: come ti cambiano l...
Matera 25/06/2012. Convegno “Software libero ed open data: come ti cambiano l...Matera 25/06/2012. Convegno “Software libero ed open data: come ti cambiano l...
Matera 25/06/2012. Convegno “Software libero ed open data: come ti cambiano l...Margherita Di Leo
 
Convegno “Sicurezza informatica e strumenti GIS Free e Open Source per l’Inge...
Convegno “Sicurezza informatica e strumenti GIS Free e Open Source per l’Inge...Convegno “Sicurezza informatica e strumenti GIS Free e Open Source per l’Inge...
Convegno “Sicurezza informatica e strumenti GIS Free e Open Source per l’Inge...Margherita Di Leo
 
Lez.5 - Corso di modelli e GIS per l'ambiente
Lez.5 - Corso di modelli e GIS per l'ambienteLez.5 - Corso di modelli e GIS per l'ambiente
Lez.5 - Corso di modelli e GIS per l'ambienteMargherita Di Leo
 
Lez. 4 - Corso di modelli e GIS per l'ambiente
Lez. 4 - Corso di modelli e GIS per l'ambienteLez. 4 - Corso di modelli e GIS per l'ambiente
Lez. 4 - Corso di modelli e GIS per l'ambienteMargherita Di Leo
 
Lez. 3 - Corso di modelli e GIS per l'ambiente
Lez. 3 - Corso di modelli e GIS per l'ambienteLez. 3 - Corso di modelli e GIS per l'ambiente
Lez. 3 - Corso di modelli e GIS per l'ambienteMargherita Di Leo
 
Lez. 2 - Corso di modelli e GIS per l'ambiente
Lez. 2 - Corso di modelli e GIS per l'ambiente Lez. 2 - Corso di modelli e GIS per l'ambiente
Lez. 2 - Corso di modelli e GIS per l'ambiente Margherita Di Leo
 
Lez. 1 - Corso di Modelli e GIS per l'ambiente
Lez. 1 - Corso di Modelli e GIS per l'ambiente Lez. 1 - Corso di Modelli e GIS per l'ambiente
Lez. 1 - Corso di Modelli e GIS per l'ambiente Margherita Di Leo
 
GrassMeeting Trento Feb 2011
GrassMeeting Trento Feb 2011GrassMeeting Trento Feb 2011
GrassMeeting Trento Feb 2011Margherita Di Leo
 
Lezione master Proidro - Modellazione idrologica con GRASS GIS 17/12/2010
Lezione master Proidro - Modellazione idrologica con GRASS GIS 17/12/2010Lezione master Proidro - Modellazione idrologica con GRASS GIS 17/12/2010
Lezione master Proidro - Modellazione idrologica con GRASS GIS 17/12/2010Margherita Di Leo
 

Más de Margherita Di Leo (15)

Presentazione introduttiva v01
Presentazione introduttiva v01Presentazione introduttiva v01
Presentazione introduttiva v01
 
Matera 25/06/2012. Convegno “Software libero ed open data: come ti cambiano l...
Matera 25/06/2012. Convegno “Software libero ed open data: come ti cambiano l...Matera 25/06/2012. Convegno “Software libero ed open data: come ti cambiano l...
Matera 25/06/2012. Convegno “Software libero ed open data: come ti cambiano l...
 
Convegno “Sicurezza informatica e strumenti GIS Free e Open Source per l’Inge...
Convegno “Sicurezza informatica e strumenti GIS Free e Open Source per l’Inge...Convegno “Sicurezza informatica e strumenti GIS Free e Open Source per l’Inge...
Convegno “Sicurezza informatica e strumenti GIS Free e Open Source per l’Inge...
 
Lez.5 - Corso di modelli e GIS per l'ambiente
Lez.5 - Corso di modelli e GIS per l'ambienteLez.5 - Corso di modelli e GIS per l'ambiente
Lez.5 - Corso di modelli e GIS per l'ambiente
 
Lez. 4 - Corso di modelli e GIS per l'ambiente
Lez. 4 - Corso di modelli e GIS per l'ambienteLez. 4 - Corso di modelli e GIS per l'ambiente
Lez. 4 - Corso di modelli e GIS per l'ambiente
 
Lez. 3 - Corso di modelli e GIS per l'ambiente
Lez. 3 - Corso di modelli e GIS per l'ambienteLez. 3 - Corso di modelli e GIS per l'ambiente
Lez. 3 - Corso di modelli e GIS per l'ambiente
 
Lez. 2 - Corso di modelli e GIS per l'ambiente
Lez. 2 - Corso di modelli e GIS per l'ambiente Lez. 2 - Corso di modelli e GIS per l'ambiente
Lez. 2 - Corso di modelli e GIS per l'ambiente
 
Lez. 1 - Corso di Modelli e GIS per l'ambiente
Lez. 1 - Corso di Modelli e GIS per l'ambiente Lez. 1 - Corso di Modelli e GIS per l'ambiente
Lez. 1 - Corso di Modelli e GIS per l'ambiente
 
Gfossday2011 esercitazione
Gfossday2011 esercitazioneGfossday2011 esercitazione
Gfossday2011 esercitazione
 
Linuxday 2011
Linuxday 2011Linuxday 2011
Linuxday 2011
 
Geoinformatics FCE CTU 2011
Geoinformatics FCE CTU 2011Geoinformatics FCE CTU 2011
Geoinformatics FCE CTU 2011
 
Foss4g it Lugano
Foss4g it LuganoFoss4g it Lugano
Foss4g it Lugano
 
GrassMeeting Trento Feb 2011
GrassMeeting Trento Feb 2011GrassMeeting Trento Feb 2011
GrassMeeting Trento Feb 2011
 
Lezione master Proidro - Modellazione idrologica con GRASS GIS 17/12/2010
Lezione master Proidro - Modellazione idrologica con GRASS GIS 17/12/2010Lezione master Proidro - Modellazione idrologica con GRASS GIS 17/12/2010
Lezione master Proidro - Modellazione idrologica con GRASS GIS 17/12/2010
 
Lecture OSSIM
Lecture OSSIM Lecture OSSIM
Lecture OSSIM
 

Último

Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural ResourcesEnergy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural ResourcesShubhangi Sonawane
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...Nguyen Thanh Tu Collection
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701bronxfugly43
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docxPoojaSen20
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin ClassesCeline George
 
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-IIFood Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-IIShubhangi Sonawane
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...Poonam Aher Patil
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 

Último (20)

Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural ResourcesEnergy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
 
Asian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptxAsian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptx
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-IIFood Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 

Python grass

  • 1. Python scripting in GRASS GIS environment Geospatial Analysis and Modeling – MEA792 Margherita Di Leo
  • 2. Python scripting in GRASS GIS environment Python + GRASS GIS: ➢ Python scripts that call GRASS functionality from outside ➢ Running external commands from Python (as a grass module)
  • 3. Python scripting in GRASS GIS environment Example Module: r.ipso Purpose: Creates the ipsographic curve and the adimensional ipsometric curve Requires: Matplotlib http://svn.osgeo.org/grass/grass-addons/raster/r.ipso/
  • 4. Python scripting in GRASS GIS environment GUI #%module #% description: Creates the ipsographic and ipsometric curve #% keywords: raster #%end #%option #% key: map #% type: string #% gisprompt: old,raster,raster #% key_desc: name #% description: Name of elevation raster map #% required: yes #%end #%option #% key: image #% type: string #% gisprompt: new_file,file,input #% key_desc: image #% description: output graph #% required: yes #%end #%flag #% key: a #% description: generate ipsometric curve #%END #%flag #% key: b #% description: generate ipsographic curve #%END
  • 5. Python scripting in GRASS GIS environment GUI #%module #% description: Creates the ipsographic and ipsometric curve #% keywords: raster #%end #%option #% key: map #% type: string #% gisprompt: old,raster,raster #% key_desc: name #% description: Name of elevation raster map #% required: yes #%end #%option #% key: image #% type: string #% gisprompt: new_file,file,input #% key_desc: image #% description: output graph #% required: yes #%end #%flag #% key: a #% description: generate ipsometric curve #%END #%flag #% key: b #% description: generate ipsographic curve #%END
  • 6. Python scripting in GRASS GIS environment prompt GRASS 6.5.svn (Basilicata):~ > r.ipso.py --help Description: Creates the ipsographic and ipsometric curve Keywords: raster Usage: r.ipso.py [-ab] map=name image=image [--verbose] [--quiet] Flags: -a generate ipsometric curve -b generate ipsographic curve --v Verbose module output --q Quiet module output Parameters: map Name of elevation raster map image path to output graph GRASS 6.5.svn (Basilicata):~ >
  • 7. Python scripting in GRASS GIS environment output GRASS 6.5.svn (Basilicata):~ > r.ipso.py map=dem@Fiumarella_dataset -ab image=Fiumarella 100% Tot. cells 172200.0 =========================== Ipsometric | quantiles =========================== 994 | 0.025 989 | 0.05 980 | 0.1 960 | 0.25 918 | 0.5 870 | 0.75 882 | 0.7 841 | 0.9 817 | 0.975 Done! GRASS 6.5.svn (Basilicata):~ >
  • 8. Python scripting in GRASS GIS environment output
  • 9. Python scripting in GRASS GIS environment output
  • 10. Python scripting in GRASS GIS environment import import sys import os import matplotlib.pyplot as plt import grass.script as grass import numpy as np Main (1/4) def main(): # r.stats gives in the first column the elevation and in the second the number of cells having that elevation stats = grass.read_command('r.stats', input = options['map'], fs = 'space', nv = '*', nsteps = '255', flags = 'inc').split('n')[:-1] # res = cellsize res = float(grass.read_command('g.region', rast = options['map'], flags = 'm').strip().split('n')[4].split('=')[1]) zn = np.zeros((len(stats),6),float) kl = np.zeros((len(stats),2),float) prc = np.zeros((9,2),float) for i in range(len(stats)): if i == 0: zn[i,0], zn[i, 1] = map(float, stats[i].split(' ')) zn[i,2] = zn[i,1] else: zn[i,0], zn[i, 1] = map(float, stats[i].split(' ')) zn[i,2] = zn[i,1] + zn[i-1,2] totcell = sum(zn[:,1]) print "Tot. cells", totcell
  • 11. Python scripting in GRASS GIS environment Main (2/4) for i in range(len(stats)): zn[i,3] = 1 - (zn[i,2] / sum(zn[:,1])) zn[i,4] = zn[i,3] * (((res**2)/1000000)*sum(zn[:,1])) zn[i,5] = ((zn[i,0] - min(zn[:,0])) / (max(zn[:,0]) - min(zn[:,0])) ) kl[i,0] = zn[i,0] kl[i,1] = 1 - (zn[i,2] / totcell) # quantiles prc[0,0] , prc[0,1] = findint(kl,0.025) , 0.025 prc[1,0] , prc[1,1] = findint(kl,0.05) , 0.05 prc[2,0] , prc[2,1] = findint(kl,0.1) , 0.1 prc[3,0] , prc[3,1] = findint(kl,0.25) , 0.25 prc[4,0] , prc[4,1] = findint(kl,0.5) , 0.5 prc[5,0] , prc[5,1] = findint(kl,0.75) , 0.75 prc[6,0] , prc[6,1] = findint(kl,0.9) , 0.9 prc[7,0] , prc[7,1] = findint(kl,0.95) , 0.95 prc[8,0] , prc[8,1] = findint(kl,0.975) , 0.975 # Managing flag & plot if flags['a']: plotImage(zn[:,3], zn[:,5],options['image']+'_Ipsometric.png','-','A(i) / A','Z(i) / Zmax','Ipsometric Curve') if flags['b']: plotImage(zn[:,4], zn[:,0],options['image']+'_Ipsographic.png','-','A [km^2 ]','Z [m.slm]','Ipsographic Curve')
  • 12. Python scripting in GRASS GIS environment Main (3/4) print "===========================" print "Ipsometric | quantiles" print "===========================" print '%.0f' %findint(kl,0.025) , "|", 0.025 print '%.0f' %findint(kl,0.05) , "|", 0.05 print '%.0f' %findint(kl,0.1) , "|", 0.1 print '%.0f' %findint(kl,0.25) , "|", 0.25 print '%.0f' %findint(kl,0.5) , "|", 0.5 print '%.0f' %findint(kl,0.75) , "|", 0.75 print '%.0f' %findint(kl,0.7) , "|", 0.7 print '%.0f' %findint(kl,0.9) , "|", 0.9 print '%.0f' %findint(kl,0.975) , "|", 0.975 print 'n' print 'Done!' #print prc def findint(kl,f): Xf = np.abs(kl-f); Xf = np.where(Xf==Xf.min()) z1 , z2 , f1 , f2 = kl[float(Xf[0])][0] , kl[float(Xf[0]-1)][0] , kl[float(Xf[0]) ][1] , kl[float(Xf[0]-1)][1] z = z1 + ((z2 - z1) / (f2 - f1)) * (f - f1) return z
  • 13. Python scripting in GRASS GIS environment Main (4/4) def plotImage(x,y,image,type,xlabel,ylabel,title): plt.plot(x, y, type) plt.ylabel(ylabel) plt.xlabel(xlabel) plt.xlim( min(x), max(x) ) plt.ylim( min(y), max(y) ) plt.title(title) plt.grid(True) plt.savefig(image) plt.close('all') if __name__ == "__main__": options, flags = grass.parser() sys.exit(main())
  • 14. Python scripting in GRASS GIS environment Zn has n rows and 6 columns [len(stats) = n] Kl has n rows and 2 columns Prc has 9 rows and 2 columns Zn 0 1 2 3 4 5 A= B= C = (if i=0, D = (1-C) / E = Di * F = (A – elevation numbers of Ci=Ai; else numbers of (res^2) / min(A)) / cells Ci = Ai + B(i- cells 1000000 * (max(A) - 1) ) numbers of min(A)) cells
  • 15. Python scripting in GRASS GIS environment Zn has n rows and 6 columns [len(stats) = n] Kl has n rows and 2 columns Prc has 9 rows and 2 columns kl 0 1 A= G = 1 – (C / elevation num of cell)
  • 16. Python scripting in GRASS GIS environment Prc has 9 rows and 2 columns. It defines the ipsometric curve by the quantiles of the distribution. It is built by the function ”findint” def findint(kl,f): Xf = np.abs(kl-f); Xf = np.where(Xf==Xf.min()) z1 , z2 , f1 , f2 = kl[float(Xf[0])][0] , kl[float(Xf[0]-1)][0] , kl[float(Xf[0]) ][1] , kl[float(Xf[0]-1)][1] z = z1 + ((z2 - z1) / (f2 - f1)) * (f - f1) return z np.abs and np.where are two NumPy routines: numpy.absolute(x[, out]) Calculate the absolute value element-wise. numpy.where(condition[, x, y]) Return elements, either from x or y, depending on condition. If only condition is given, return condition.nonzero(). See NumPy doc at http://docs.scipy.org/doc/
  • 17. Python scripting in GRASS GIS environment Some useful links: GRASS and Python on Osgeo wiki: http://grass.osgeo.org/wiki/GRASS_and_Python GRASS Python Scripting Library: http://grass.osgeo.org/programming6/pythonlib.html Style rules: http://trac.osgeo.org/grass/browser/grass/trunk/SUBMITTING_PYTHON