[GRASS-SVN] r64212 - grass-addons/grass7/raster/r.niche.similarity

svn_grass at osgeo.org svn_grass at osgeo.org
Fri Jan 16 02:56:25 PST 2015


Author: pvanbosgeo
Date: 2015-01-16 02:56:25 -0800 (Fri, 16 Jan 2015)
New Revision: 64212

Modified:
   grass-addons/grass7/raster/r.niche.similarity/r.niche.similarity.py
Log:
added correlation, small bugfix

Modified: grass-addons/grass7/raster/r.niche.similarity/r.niche.similarity.py
===================================================================
--- grass-addons/grass7/raster/r.niche.similarity/r.niche.similarity.py	2015-01-16 08:35:04 UTC (rev 64211)
+++ grass-addons/grass7/raster/r.niche.similarity/r.niche.similarity.py	2015-01-16 10:56:25 UTC (rev 64212)
@@ -4,7 +4,7 @@
 ########################################################################
 #
 # MODULE:       r.niche.similarity
-# AUTHOR(S):    Paulo van Breugel <paulo AT ecodiv.org>
+# AUTHOR(S):    Paulo van Breugel <p.vanbreugel AT gmail.com>
 # PURPOSE:      Compute  degree of niche overlap using the statistics D
 #               and I (as proposed by Warren et al., 2008) based on
 #               Schoeners D (Schoener, 1968) and Hellinger Distances
@@ -46,21 +46,31 @@
 
 #%flag
 #% key: i
-#% description: Calculate I niche similarity
+#% description: I niche similarity
 #% guisection: Statistics
 #%end
 
 #%flag
 #% key: d
-#% description: Calculate D niche similarity
+#% description: D niche similarity
 #% guisection: Statistics
 #%end
 
+#%flag
+#% key: c
+#% description: Correlation
+#% guisection: Statistics
+#%end
+
+#%rules
+#%required: i,d,c
+#%end
+
 ##----------------------------------------------------------------------------
 # Test purposes
 ##----------------------------------------------------------------------------
-#options = {"maps":"bio1,bio5,bio6", "output":""}
-#flags = {"i":True, "d":True}
+#options = {"maps":"bio_1,bio_5,bio_6", "output":""}
+#flags = {"i":True, "d":True, "c":True}
 
 ##----------------------------------------------------------------------------
 ## STANDARD ##
@@ -77,7 +87,7 @@
 
 # Check if running in GRASS
 if not os.environ.has_key("GISBASE"):
-    grass.message( "You must be in GRASS GIS to run this program." )
+    grass.message("You must be in GRASS GIS to run this program.")
     sys.exit(1)
 
 # Cleanup
@@ -86,8 +96,25 @@
 def cleanup():
     for rast in clean_rast:
         grass.run_command("g.remove",
-        type="rast", name = rast, quiet = True)
+        type="rast", name=rast, quiet=True)
 
+
+def fileexist(fname, suffix):
+    k = 0
+    fname2 = fname[:]
+    fname2 = fname2.split('.')
+    while os.path.isfile(fname):
+        k = k + 1
+        opft = fname.split('.')
+        if len(opft) == 1:
+            fname = opft[0] + "_" + str(k)
+        else:
+            fname = fname2[0] + suffix + str(k) + "." + fname2[1]
+    if k > 0:
+        grass.info("there is already a file " + fname2[0] + ".")
+        grass.info("Using " + fname + " instead")
+    return fname
+
 ##----------------------------------------------------------------------------
 ## main function
 ##----------------------------------------------------------------------------
@@ -102,8 +129,11 @@
     OPF = options['output']
     if OPF == '':
         OPF = tempfile.mkstemp()[1]
+    else:
+        OPF = fileexist(OPF, "v_")
     flag_i = flags['i']
     flag_d = flags['d']
+    flag_c = flags['c']
 
     ## Checks
     #--------------------------------------------------------------------------
@@ -113,26 +143,6 @@
     if NLAY < 2:
         grass.fatal("You need to provide 2 or more raster maps")
 
-    # Check that at least one statistic is selected
-    if flag_i == '' and flag_d == '':
-        grass.fatal("You need to select at least one statistic")
-
-    # Test if text file exists. If so, append _v1 to file name
-    #--------------------------------------------------------------------------
-    k = 0
-    OPFold = OPF[:]
-    OPFold = OPFold.split('.')
-    while os.path.isfile(OPF):
-        k = k + 1
-        opft = OPF.split('.')
-        if len(opft) == 1:
-            OPF = opft[0] + "_" + str(k)
-        else:
-            OPF = OPFold[0] + "_v" + str(k) + "." + OPFold[1]
-    if k > 0:
-        grass.info("there is already a file " + OPFold[0] + ".")
-        grass.info("Using " + OPF + " instead")
-
     #=======================================================================
     ## Calculate D and I and write to standard output (& optionally to file)
     #=======================================================================
@@ -142,7 +152,7 @@
     text_file.write("raster1,raster2,statistic,value" + "\n")
 
     # Write D and I values to standard output and optionally to text file
-    i=0
+    i = 0
     while i < NLAY:
         nlay1 = INMAPS[i]
         nvar1 = VARI[i]
@@ -162,41 +172,50 @@
                 tmpf0 = string.replace(tmpf0, '-', '_')
                 clean_rast.add(tmpf0)
                 grass.mapcalc("$tmpf0 = abs(double($nlay1)/$vsum1 - double($nlay2)/$vsum2)",
-                             tmpf0 = tmpf0,
-                             nlay1 = nlay1,
-                             vsum1 = vsum1,
-                             nlay2 = nlay2,
-                             vsum2 = vsum2,
+                             tmpf0=tmpf0,
+                             nlay1=nlay1,
+                             vsum1=vsum1,
+                             nlay2=nlay2,
+                             vsum2=vsum2,
                              quiet=True)
                 NO = float(grass.parse_command("r.univar", quiet=True, flags="g", map=tmpf0)['sum'])
-                NOV = 1 - ( 0.5 * NO )
+                NOV = 1 - (0.5 * NO)
                 grass.run_command("g.remove", quiet=True, flags="f", type="raster", name=tmpf0)
                 text_file.write("D, " + nvar1 + "," + nvar2 + "," + str(NOV) + "\n")
-                grass.message("niche overlap (D) of " + nvar1 + " and " + nvar2 + ": " + str(round(NOV,3)))
+                grass.message("Niche overlap (D) of " + nvar1 + " and " + nvar2 + ": " + str(round(NOV, 3)))
 
-                ## Calculate I (Warren et al. 2008), but note that the original formulation
-                ## was corrected in erratum by Warren et al, using I = 1 - H^2 * 0.5
-                ## The sqrt in the H formulation and this new ^2 cancel each other out,
-                ## leading to the formulation used below.
-                #=======================================================================
+            ## Calculate I (Warren et al. 2008). Note that the sqrt in the
+            # H formulation and the ^2 in the I formation  cancel each other out,
+            # hence the formulation below.
+            #=======================================================================
 
             if flag_i:
                 tmpf1 = "rniche_" + str(uuid.uuid4())
                 tmpf1 = string.replace(tmpf1, '-', '_')
                 clean_rast.add(tmpf1)
                 grass.mapcalc("$tmpf1 = (sqrt(double($nlay1)/$vsum1) - sqrt(double($nlay2)/$vsum2))^2",
-                             tmpf1 = tmpf1,
-                             nlay1 = nlay1,
-                             vsum1 = vsum1,
-                             nlay2 = nlay2,
-                             vsum2 = vsum2,
+                             tmpf1=tmpf1,
+                             nlay1=nlay1,
+                             vsum1=vsum1,
+                             nlay2=nlay2,
+                             vsum2=vsum2,
                              quiet=True)
                 NE = float(grass.parse_command("r.univar", quiet=True, flags="g", map=tmpf1)['sum'])
                 NEQ = 1 - (0.5 * NE)
                 grass.run_command("g.remove", quiet=True, flags="f", type="raster", name=tmpf1)
                 text_file.write("I, " + nvar1 + "," + nvar2 + "," + str(NEQ) + "\n")
-                grass.message("niche overlap (I) of " + nvar1 + " and " + nvar2 + ": " + str(round(NEQ, 3)))
+                grass.message("Niche overlap (I) of " + nvar1 + " and " + nvar2 + ": " + str(round(NEQ, 3)))
 
+            ## Calculate correlation
+            #=======================================================================
+
+            if flag_c:
+                corl = str(list(grass.parse_command("r.covar", flags="r", map=(nlay1,nlay2)))[0])
+                corl = float(corl.split(' ')[0])
+                text_file.write("corr, " + nvar1 + "," + nvar2 + "," + str(corl) + "\n")
+                grass.message("Correlation of " + nvar1 + " and " + nvar2 + ": " + str(round(corl, 3)))
+
+
             j = j + 1
         i = i + 1
 



More information about the grass-commit mailing list